_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
1bae1944f60382ddf45b36a213c14fb11eab4a6b300bf430b9beeea2b737fde6
niconaus/pcode-interpreter
Types.hs
| Module : PCode Description : language definitions Copyright : ( c ) , 2022 Maintainer : Stability : experimental This module defines the datatypes and translation of Module : PCode Description : Ghidra P-Code language definitions Copyright : (c) Nico Naus, 2022 Maintainer : Stability : experimental This module defines the datatypes and translation of Ghidra P-Code -} module Types where import qualified Data.Map as M import Data.Word ( Word8 ) import qualified Data.ByteString as BS Program in P - code type PCode = M.Map Fname PBlocks type PBlocks = M.Map Addr PBlock -- Memory types type State = (Mem,Regs,Vars) type Mem = M.Map Addr Word8 Variables " return " and " last " are reserved and should not be used in PCode type Vars = M.Map String [Word8] type Regs = M.Map Addr Word8 -- Block address type Addr = [Word8] type Fname = [Word8] -- functions are identified by the starting address, since that is how they are called type PBlock = [PInstr] data PInstr = STORE VarNode VarNode VarNode | BRANCH VarNode | CBRANCH VarNode VarNode VarNode | BRANCHIND VarNode | RETURN VarNode (Maybe VarNode) | Do PCall | PCAss VarNode PCall | PAss VarNode POp deriving Show data PCall = CALL VarNode [VarNode] | CALLIND VarNode [VarNode] | CALLOTHER VarNode [VarNode] -- EXTCALL is an artifical instruction, to encode which external function is called from this point | EXTCALL String deriving Show data POp = COPY VarNode | LOAD VarNode VarNode | PIECE VarNode VarNode | SUBPIECE VarNode VarNode | POPCOUNT VarNode INTEGER OPERATIONS | INT_EQUAL VarNode VarNode | INT_NOTEQUAL VarNode VarNode | INT_LESS VarNode VarNode | INT_SLESS VarNode VarNode | INT_LESSEQUAL VarNode VarNode | INT_SLESSEQUAL VarNode VarNode | INT_ZEXT VarNode | INT_SEXT VarNode | INT_ADD VarNode VarNode | INT_SUB VarNode VarNode | INT_CARRY VarNode VarNode | INT_SCARRY VarNode VarNode | INT_SBORROW VarNode VarNode | INT_2COMP VarNode | INT_NEGATE VarNode | INT_XOR VarNode VarNode | INT_AND VarNode VarNode | INT_OR VarNode VarNode | INT_LEFT VarNode VarNode | INT_RIGHT VarNode VarNode | INT_SRIGHT VarNode VarNode | INT_MULT VarNode VarNode | INT_DIV VarNode VarNode | INT_REM VarNode VarNode | INT_SDIV VarNode VarNode | INT_SREM VarNode VarNode BOOLEAN OPERATIONS | BOOL_NEGATE VarNode | BOOL_XOR VarNode VarNode | BOOL_AND VarNode VarNode | BOOL_OR VarNode VarNode -- FLOATING POINT NUMBER OPERATIONS | FLOAT_EQUAL VarNode VarNode | FLOAT_NOTEQUAL VarNode VarNode | FLOAT_LESS VarNode VarNode | FLOAT_LESSEQUAL VarNode VarNode | FLOAT_ADD VarNode VarNode | FLOAT_SUB VarNode VarNode | FLOAT_MULT VarNode VarNode | FLOAT_DIV VarNode VarNode | FLOAT_NEG VarNode | FLOAT_ABS VarNode | FLOAT_SQRT VarNode | FLOAT_CEIL VarNode | FLOAT_FLOOR VarNode | FLOAT_ROUND VarNode | FLOAT_NAN VarNode | INT2FLOAT VarNode | FLOAT2FLOAT VarNode -- OTHER OPERATIONS | TRUNC VarNode -- UNDOCUMENTED INSTRUCTIONS | [ VarNode]-- I have no idea what this instruction does ... -- ADDITIONAL INSTRUCTIONS | MULTIEQUAL [(VarNode,Addr)] | INDIRECT VarNode VarNode | PTRADD VarNode VarNode VarNode | PTRSUB VarNode VarNode | CAST VarNode deriving Show data VarNode = Reg Addr Size | Ram Addr Size | Variable String Size | Const [Word8] Size deriving Show -- String is hex representation type Size = Word8 -- COMMON OPERATIONS ON PCODE TYPES vnSize :: VarNode -> Size vnSize (Ram _ s) = s vnSize (Reg _ s) = s vnSize (Const _ s) = s vnSize (Variable _ s) = s sizeToInt :: Size -> Int sizeToInt = fromEnum intToSize :: Int -> Size intToSize = toEnum -- REGISTER MAPPING -- this mapping is established by experimental results showReg :: Addr -> Size -> String showReg [0,0,0,0,0,0,0,0] 8 = "RAX" showReg [0,0,0,0,0,0,0,0] 4 = "EAX" showReg [0,0,0,0,0,0,0,0] 2 = "AX" showReg [0,0,0,0,0,0,0,0] 1 = "AL" showReg [0,0,0,0,0,0,0,1] 1 = "AH" showReg [0,0,0,0,0,0,0,8] 8 = "RCX" showReg [0,0,0,0,0,0,0,8] 4 = "ECX" showReg [0,0,0,0,0,0,0,8] 2 = "CX" showReg [0,0,0,0,0,0,0,8] 1 = "BL" showReg [0,0,0,0,0,0,0,9] 1 = "BH" showReg [0,0,0,0,0,0,0,16] 8 = "RDX" showReg [0,0,0,0,0,0,0,16] 4 = "EDX" showReg [0,0,0,0,0,0,0,24] 8 = "RBX" showReg [0,0,0,0,0,0,0,32] 8 = "RSP" showReg [0,0,0,0,0,0,0,40] 8 = "RBP" showReg [0,0,0,0,0,0,0,40] 4 = "EBP" showReg [0,0,0,0,0,0,0,48] 8 = "RSI" showReg [0,0,0,0,0,0,0,48] 4 = "ESI" showReg [0,0,0,0,0,0,0,56] 8 = "RDI" showReg [0,0,0,0,0,0,0,56] 4 = "EDI" showReg [0,0,0,0,0,0,0,128] 8 = "R8" showReg [0,0,0,0,0,0,0,136] 8 = "R9" showReg [0,0,0,0,0,0,0,144] 8 = "R10" showReg 152 8 = " R11 " -- showReg 160 8 = "R12" showReg 168 8 = " R13 " -- showReg 176 8 = "R14" -- showReg 176 4 = "R14D" showReg 184 8 = " R15 " showReg 184 4 = " R15D " -- -- showReg 512 1 = "CF" -- showReg 514 1 = "PF" showReg [0,0,0,0,0,0,2,6] 1 = "AF" showReg [0,0,0,0,0,0,2,8] 1 = "ZF" showReg [0,0,0,0,0,0,2,9] 1 = "SF" showReg [0,0,0,0,0,0,2,10] 1 = "TF" showReg [0,0,0,0,0,0,2,11] 1 = "IF" showReg [0,0,0,0,0,0,2,12] 1 = "DF" showReg [0,0,0,0,0,0,2,13] 1 = "OF" -- -- showReg 1200 8 = "XMM0_Qa" showReg a s = "UnmatchedReg " ++ show a ++ ":" ++ show s -- PRETTY PRINTER for programs prettyPF :: PCode -> String prettyPF funs = concatMap (\(fl,blocks) -> "Function " ++ show fl ++ "\n" ++ prettyPBs blocks) (M.toList funs) prettyPBs :: PBlocks -> String prettyPBs blocks = concatMap (\(l,block) -> " " ++ show l ++ "\n" ++ prettyPB block) (M.toList blocks) prettyPB :: PBlock -> String prettyPB [] = "" prettyPB (x:xs) = " " ++ show x ++ "\n" ++ prettyPB xs
null
https://raw.githubusercontent.com/niconaus/pcode-interpreter/1e8053226e658b4c609470836b867c231f8c756d/Types.hs
haskell
Memory types Block address functions are identified by the starting address, since that is how they are called EXTCALL is an artifical instruction, to encode which external function is called from this point FLOATING POINT NUMBER OPERATIONS OTHER OPERATIONS UNDOCUMENTED INSTRUCTIONS I have no idea what this instruction does ... ADDITIONAL INSTRUCTIONS String is hex representation COMMON OPERATIONS ON PCODE TYPES REGISTER MAPPING this mapping is established by experimental results showReg 160 8 = "R12" showReg 176 8 = "R14" showReg 176 4 = "R14D" showReg 512 1 = "CF" showReg 514 1 = "PF" showReg 1200 8 = "XMM0_Qa" PRETTY PRINTER for programs
| Module : PCode Description : language definitions Copyright : ( c ) , 2022 Maintainer : Stability : experimental This module defines the datatypes and translation of Module : PCode Description : Ghidra P-Code language definitions Copyright : (c) Nico Naus, 2022 Maintainer : Stability : experimental This module defines the datatypes and translation of Ghidra P-Code -} module Types where import qualified Data.Map as M import Data.Word ( Word8 ) import qualified Data.ByteString as BS Program in P - code type PCode = M.Map Fname PBlocks type PBlocks = M.Map Addr PBlock type State = (Mem,Regs,Vars) type Mem = M.Map Addr Word8 Variables " return " and " last " are reserved and should not be used in PCode type Vars = M.Map String [Word8] type Regs = M.Map Addr Word8 type Addr = [Word8] type PBlock = [PInstr] data PInstr = STORE VarNode VarNode VarNode | BRANCH VarNode | CBRANCH VarNode VarNode VarNode | BRANCHIND VarNode | RETURN VarNode (Maybe VarNode) | Do PCall | PCAss VarNode PCall | PAss VarNode POp deriving Show data PCall = CALL VarNode [VarNode] | CALLIND VarNode [VarNode] | CALLOTHER VarNode [VarNode] | EXTCALL String deriving Show data POp = COPY VarNode | LOAD VarNode VarNode | PIECE VarNode VarNode | SUBPIECE VarNode VarNode | POPCOUNT VarNode INTEGER OPERATIONS | INT_EQUAL VarNode VarNode | INT_NOTEQUAL VarNode VarNode | INT_LESS VarNode VarNode | INT_SLESS VarNode VarNode | INT_LESSEQUAL VarNode VarNode | INT_SLESSEQUAL VarNode VarNode | INT_ZEXT VarNode | INT_SEXT VarNode | INT_ADD VarNode VarNode | INT_SUB VarNode VarNode | INT_CARRY VarNode VarNode | INT_SCARRY VarNode VarNode | INT_SBORROW VarNode VarNode | INT_2COMP VarNode | INT_NEGATE VarNode | INT_XOR VarNode VarNode | INT_AND VarNode VarNode | INT_OR VarNode VarNode | INT_LEFT VarNode VarNode | INT_RIGHT VarNode VarNode | INT_SRIGHT VarNode VarNode | INT_MULT VarNode VarNode | INT_DIV VarNode VarNode | INT_REM VarNode VarNode | INT_SDIV VarNode VarNode | INT_SREM VarNode VarNode BOOLEAN OPERATIONS | BOOL_NEGATE VarNode | BOOL_XOR VarNode VarNode | BOOL_AND VarNode VarNode | BOOL_OR VarNode VarNode | FLOAT_EQUAL VarNode VarNode | FLOAT_NOTEQUAL VarNode VarNode | FLOAT_LESS VarNode VarNode | FLOAT_LESSEQUAL VarNode VarNode | FLOAT_ADD VarNode VarNode | FLOAT_SUB VarNode VarNode | FLOAT_MULT VarNode VarNode | FLOAT_DIV VarNode VarNode | FLOAT_NEG VarNode | FLOAT_ABS VarNode | FLOAT_SQRT VarNode | FLOAT_CEIL VarNode | FLOAT_FLOOR VarNode | FLOAT_ROUND VarNode | FLOAT_NAN VarNode | INT2FLOAT VarNode | FLOAT2FLOAT VarNode | TRUNC VarNode | MULTIEQUAL [(VarNode,Addr)] | INDIRECT VarNode VarNode | PTRADD VarNode VarNode VarNode | PTRSUB VarNode VarNode | CAST VarNode deriving Show data VarNode = Reg Addr Size | Ram Addr Size | Variable String Size type Size = Word8 vnSize :: VarNode -> Size vnSize (Ram _ s) = s vnSize (Reg _ s) = s vnSize (Const _ s) = s vnSize (Variable _ s) = s sizeToInt :: Size -> Int sizeToInt = fromEnum intToSize :: Int -> Size intToSize = toEnum showReg :: Addr -> Size -> String showReg [0,0,0,0,0,0,0,0] 8 = "RAX" showReg [0,0,0,0,0,0,0,0] 4 = "EAX" showReg [0,0,0,0,0,0,0,0] 2 = "AX" showReg [0,0,0,0,0,0,0,0] 1 = "AL" showReg [0,0,0,0,0,0,0,1] 1 = "AH" showReg [0,0,0,0,0,0,0,8] 8 = "RCX" showReg [0,0,0,0,0,0,0,8] 4 = "ECX" showReg [0,0,0,0,0,0,0,8] 2 = "CX" showReg [0,0,0,0,0,0,0,8] 1 = "BL" showReg [0,0,0,0,0,0,0,9] 1 = "BH" showReg [0,0,0,0,0,0,0,16] 8 = "RDX" showReg [0,0,0,0,0,0,0,16] 4 = "EDX" showReg [0,0,0,0,0,0,0,24] 8 = "RBX" showReg [0,0,0,0,0,0,0,32] 8 = "RSP" showReg [0,0,0,0,0,0,0,40] 8 = "RBP" showReg [0,0,0,0,0,0,0,40] 4 = "EBP" showReg [0,0,0,0,0,0,0,48] 8 = "RSI" showReg [0,0,0,0,0,0,0,48] 4 = "ESI" showReg [0,0,0,0,0,0,0,56] 8 = "RDI" showReg [0,0,0,0,0,0,0,56] 4 = "EDI" showReg [0,0,0,0,0,0,0,128] 8 = "R8" showReg [0,0,0,0,0,0,0,136] 8 = "R9" showReg [0,0,0,0,0,0,0,144] 8 = "R10" showReg 152 8 = " R11 " showReg 168 8 = " R13 " showReg 184 8 = " R15 " showReg 184 4 = " R15D " showReg [0,0,0,0,0,0,2,6] 1 = "AF" showReg [0,0,0,0,0,0,2,8] 1 = "ZF" showReg [0,0,0,0,0,0,2,9] 1 = "SF" showReg [0,0,0,0,0,0,2,10] 1 = "TF" showReg [0,0,0,0,0,0,2,11] 1 = "IF" showReg [0,0,0,0,0,0,2,12] 1 = "DF" showReg [0,0,0,0,0,0,2,13] 1 = "OF" showReg a s = "UnmatchedReg " ++ show a ++ ":" ++ show s prettyPF :: PCode -> String prettyPF funs = concatMap (\(fl,blocks) -> "Function " ++ show fl ++ "\n" ++ prettyPBs blocks) (M.toList funs) prettyPBs :: PBlocks -> String prettyPBs blocks = concatMap (\(l,block) -> " " ++ show l ++ "\n" ++ prettyPB block) (M.toList blocks) prettyPB :: PBlock -> String prettyPB [] = "" prettyPB (x:xs) = " " ++ show x ++ "\n" ++ prettyPB xs
5a547f426396ad3c342a7363dc1cfd4be0b1cce557a2e2e2a7f5bd9acb882e1a
ghc/packages-dph
Split.hs
{-# OPTIONS -Wall -fno-warn-orphans -fno-warn-missing-signatures #-} # LANGUAGE CPP # #include "fusion-phases.h" -- | Operations on Distributed Segment Descriptors module Data.Array.Parallel.Unlifted.Distributed.Data.USSegd.Split (splitSSegdOnElemsD) where import Data.Array.Parallel.Unlifted.Distributed.Arrays import Data.Array.Parallel.Unlifted.Distributed.Combinators import Data.Array.Parallel.Unlifted.Distributed.Primitive import Data.Array.Parallel.Unlifted.Sequential.USSegd (USSegd) import Data.Array.Parallel.Unlifted.Sequential.Vector (Vector) import Data.Array.Parallel.Base import Data.Bits (shiftR) import Control.Monad (when) import Data.Array.Parallel.Unlifted.Distributed.Data.USSegd.DT () import qualified Data.Array.Parallel.Unlifted.Sequential.USegd as USegd import qualified Data.Array.Parallel.Unlifted.Sequential.USSegd as USSegd import qualified Data.Array.Parallel.Unlifted.Sequential.Vector as Seq import Debug.Trace here :: String -> String here s = "Data.Array.Parallel.Unlifted.Distributed.USSegd." ++ s ------------------------------------------------------------------------------- -- | Split a segment descriptor across the gang, element wise. -- We try to put the same number of elements on each thread, which means -- that segments are sometimes split across threads. -- Each thread gets a slice of segment descriptor , the segid of the first slice , and the offset of the first slice in its segment . -- -- Example: In this picture each X represents 5 elements , and we have 5 segements in total . -- @ : ----------------------- --- ------- --------------- ------------------- elems : |X X X X X X X X X|X X X X X X X X X|X X X X X X X X X|X X X X X X X X X| | | thread2 | | thread4 | : 0 0 3 4 offset : 0 45 0 5 -- theGang $ lengthsToUSegd $ fromList [ 60 , 10 , 20 , 40 , 50 : : Int ] -- segd : DUSegd lengths : DVector lengths : [ 1,3,2,1 ] chunks : [ [ 45],[15,10,20],[40,5],[45 ] ] indices : DVector lengths : [ 1,3,2,1 ] chunks : [ [ 0 ] , [ 0,15,25 ] , [ 0,40],[0 ] ] elements : DInt [ 45,45,45,45 ] -- segids : DInt [ 0,0,3,4 ] ( segment i d of first slice on thread ) offsets : DInt [ 0,45,0,5 ] ( offset of that slice in its segment ) -- @ -- splitSSegdOnElemsD :: Gang -> USSegd -> Dist ((USSegd,Int),Int) splitSSegdOnElemsD g !segd = {-# SCC "splitSSegdOnElemsD" #-} traceEvent ("dph-prim-par: USSegd.splitSSegdOnElems") $ imapD (What "UPSSegd.splitSSegdOnElems/splitLenIx") g mk (splitLenIdxD g (USegd.takeElements $ USSegd.takeUSegd segd)) where -- Number of threads in gang. !nThreads = gangSize g -- Build a USSegd from just the lengths, starts and sources fields. The indices and elems fields of the contained USegd are -- generated from the lengths. buildUSSegd :: Vector Int -> Vector Int -> Vector Int -> USSegd buildUSSegd lengths starts sources = USSegd.mkUSSegd starts sources $ USegd.fromLengths lengths -- Determine what elements go on a thread mk :: Int -- Thread index. -> (Int, Int) -- Number of elements on this thread, -- and starting offset into the flat array. Segd for this thread , segid of first slice , and offset of first slice . mk i (nElems, ixStart) = case chunk segd ixStart nElems (i == nThreads - 1) of (# lengths, starts, sources, l, o #) -> ((buildUSSegd lengths starts sources, l), o) # NOINLINE splitSSegdOnElemsD # NOINLINE because it 's complicated and wo n't fuse with anything . -- This function has a large body of code and we don't want to blow up -- the client modules by inlining it everywhere. ------------------------------------------------------------------------------- -- | Determine what elements go on a thread. -- The 'chunk' refers to the a chunk of the flat array, and is defined -- by a set of segment slices. -- -- Example: In this picture each X represents 5 elements , and we have 5 segements in total . -- -- @ segs: ----------------------- --- ------- --------------- ------------------- elems : |X X X X X X X X X|X X X X X X X X X|X X X X X X X X X|X X X X X X X X X| | | thread2 | | thread4 | : 0 0 3 4 offset : 0 45 0 5 k : 0 1 3 5 k ' : 1 3 5 5 left : 0 15 0 45 right : 45 20 5 0 left_len : 0 1 0 1 left_off : 0 45 0 5 n ' : 1 3 2 1 -- @ chunk :: USSegd -- ^ Segment descriptor of entire array. ^ Starting offset into the flat array for the first -- slice on this thread. -> Int -- ^ Number of elements in this thread. -> Bool -- ^ Whether this is the last thread in the gang. -> (# Vector Int -- Lengths of segment slices, , Vector Int -- Starting index of data in its vector , Vector Int -- Source id segid of first slice offset of first slice . chunk !ussegd !nStart !nElems is_last = (# lengths', starts', sources', k-left_len, left_off #) where -- Lengths of all segments. eg : [ 60 , 10 , 20 , 40 , 50 ] lengths = USSegd.takeLengths ussegd -- Indices indices of all segments. eg : [ 0 , 60 , 70 , 90 , 130 ] indices = USSegd.takeIndices ussegd -- Starting indices for all segments. starts = USSegd.takeStarts ussegd -- Source ids for all segments. sources = USSegd.takeSources ussegd -- Total number of segments defined by segment descriptor. eg : 5 n = Seq.length lengths Segid of the first seg that starts after the left of this chunk . k = search nStart indices Segid of the first seg that starts after the right of this chunk . k' | is_last = n | otherwise = search (nStart + nElems) indices -- The length of the left-most slice of this chunk. left | k == n = nElems | otherwise = min ((Seq.index (here "chunk") indices k) - nStart) nElems -- The length of the right-most slice of this chunk. length_right | k' == k = 0 | otherwise = nStart + nElems - (Seq.index (here "chunk") indices (k'-1)) Whether the first element in this chunk is an internal element of of a segment . Alternatively , indicates that the first element of the chunk is not the first element of a segment . left_len | left == 0 = 0 | otherwise = 1 If the first element of the chunk starts within a segment , -- then gives the index within that segment, otherwise 0. left_off | left == 0 = 0 | otherwise = nStart - (Seq.index (here "chunk") indices (k-1)) -- How many segments this chunk straddles. n' = left_len + (k'-k) Create the lengths for this chunk by first copying out the lengths -- from the original segment descriptor. If the slices on the left -- and right cover partial segments, then we update the corresponding -- lengths. (!lengths', !starts', !sources') = runST (do -- Create a new array big enough to hold all the lengths for this chunk. mlengths' <- Seq.newM n' msources' <- Seq.newM n' mstarts' <- Seq.newM n' If the first element is inside a segment , -- then update the length to be the length of the slice. when (left /= 0) $ do Seq.write mlengths' 0 left Seq.write mstarts' 0 (Seq.index (here "chunk") starts (k - left_len) + left_off) Seq.write msources' 0 (Seq.index (here "chunk") sources (k - left_len)) -- Copy out array lengths for this chunk. Seq.copy (Seq.mdrop left_len mlengths') (Seq.slice (here "chunk") lengths k (k'-k)) Seq.copy (Seq.mdrop left_len mstarts') (Seq.slice (here "chunk") starts k (k'-k)) Seq.copy (Seq.mdrop left_len msources') (Seq.slice (here "chunk") sources k (k'-k)) -- If the last element is inside a segment, -- then update the length to be the length of the slice. when (length_right /= 0) $ do Seq.write mlengths' (n' - 1) length_right clengths' <- Seq.unsafeFreeze mlengths' cstarts' <- Seq.unsafeFreeze mstarts' csources' <- Seq.unsafeFreeze msources' return (clengths', cstarts', csources')) = trace ( render [ text " CHUNK " , , text " nStart : " < + > int nStart , text " nElems : " < + > int nElems , text " k : " < + > int k , text " k ' : " < + > int k ' , text " left : " < + > int left , text " right : " < + > int right , text " left_len : " < + > int left_len , text " left_off : " < + > int left_off , text " n ' : " < + > int n ' , text " " ] ) lens ' (render $ vcat [ text "CHUNK" , pprp segd , text "nStart: " <+> int nStart , text "nElems: " <+> int nElems , text "k: " <+> int k , text "k': " <+> int k' , text "left: " <+> int left , text "right: " <+> int right , text "left_len:" <+> int left_len , text "left_off:" <+> int left_off , text "n': " <+> int n' , text ""]) lens' -} # INLINE_DIST chunk # INLINE_DIST even though it should be inlined into splitSSegdOnElemsD anyway -- because that function contains the only use. ------------------------------------------------------------------------------- -- O(log n). -- Given a monotonically increasing vector of `Int`s, find the first element that is larger than the given value . -- eg search 75 [ 0 , 60 , 70 , 90 , 130 ] = 90 search 43 [ 0 , 60 , 70 , 90 , 130 ] = 60 -- search :: Int -> Vector Int -> Int search !x ys = go 0 (Seq.length ys) where go i n | n <= 0 = i | Seq.index (here "search") ys mid < x = go (mid + 1) (n - half - 1) | otherwise = go i half where half = n `shiftR` 1 mid = i + half # INLINE_DIST search # -- INLINE_DIST because we want it inlined into both uses in 'chunk' above.
null
https://raw.githubusercontent.com/ghc/packages-dph/64eca669f13f4d216af9024474a3fc73ce101793/dph-prim-par/Data/Array/Parallel/Unlifted/Distributed/Data/USSegd/Split.hs
haskell
# OPTIONS -Wall -fno-warn-orphans -fno-warn-missing-signatures # | Operations on Distributed Segment Descriptors ----------------------------------------------------------------------------- | Split a segment descriptor across the gang, element wise. We try to put the same number of elements on each thread, which means that segments are sometimes split across threads. Example: --------------------- --- ------- --------------- ------------------- @ # SCC "splitSSegdOnElemsD" # Number of threads in gang. Build a USSegd from just the lengths, starts and sources fields. generated from the lengths. Determine what elements go on a thread Thread index. Number of elements on this thread, and starting offset into the flat array. This function has a large body of code and we don't want to blow up the client modules by inlining it everywhere. ----------------------------------------------------------------------------- | Determine what elements go on a thread. The 'chunk' refers to the a chunk of the flat array, and is defined by a set of segment slices. Example: @ segs: ----------------------- --- ------- --------------- ------------------- @ ^ Segment descriptor of entire array. slice on this thread. ^ Number of elements in this thread. ^ Whether this is the last thread in the gang. Lengths of segment slices, Starting index of data in its vector Source id Lengths of all segments. Indices indices of all segments. Starting indices for all segments. Source ids for all segments. Total number of segments defined by segment descriptor. The length of the left-most slice of this chunk. The length of the right-most slice of this chunk. then gives the index within that segment, otherwise 0. How many segments this chunk straddles. from the original segment descriptor. If the slices on the left and right cover partial segments, then we update the corresponding lengths. Create a new array big enough to hold all the lengths for this chunk. then update the length to be the length of the slice. Copy out array lengths for this chunk. If the last element is inside a segment, then update the length to be the length of the slice. because that function contains the only use. ----------------------------------------------------------------------------- O(log n). Given a monotonically increasing vector of `Int`s, INLINE_DIST because we want it inlined into both uses in 'chunk' above.
# LANGUAGE CPP # #include "fusion-phases.h" module Data.Array.Parallel.Unlifted.Distributed.Data.USSegd.Split (splitSSegdOnElemsD) where import Data.Array.Parallel.Unlifted.Distributed.Arrays import Data.Array.Parallel.Unlifted.Distributed.Combinators import Data.Array.Parallel.Unlifted.Distributed.Primitive import Data.Array.Parallel.Unlifted.Sequential.USSegd (USSegd) import Data.Array.Parallel.Unlifted.Sequential.Vector (Vector) import Data.Array.Parallel.Base import Data.Bits (shiftR) import Control.Monad (when) import Data.Array.Parallel.Unlifted.Distributed.Data.USSegd.DT () import qualified Data.Array.Parallel.Unlifted.Sequential.USegd as USegd import qualified Data.Array.Parallel.Unlifted.Sequential.USSegd as USSegd import qualified Data.Array.Parallel.Unlifted.Sequential.Vector as Seq import Debug.Trace here :: String -> String here s = "Data.Array.Parallel.Unlifted.Distributed.USSegd." ++ s Each thread gets a slice of segment descriptor , the segid of the first slice , and the offset of the first slice in its segment . In this picture each X represents 5 elements , and we have 5 segements in total . elems : |X X X X X X X X X|X X X X X X X X X|X X X X X X X X X|X X X X X X X X X| | | thread2 | | thread4 | : 0 0 3 4 offset : 0 45 0 5 theGang $ lengthsToUSegd $ fromList [ 60 , 10 , 20 , 40 , 50 : : Int ] segd : DUSegd lengths : DVector lengths : [ 1,3,2,1 ] chunks : [ [ 45],[15,10,20],[40,5],[45 ] ] indices : DVector lengths : [ 1,3,2,1 ] chunks : [ [ 0 ] , [ 0,15,25 ] , [ 0,40],[0 ] ] elements : DInt [ 45,45,45,45 ] segids : DInt [ 0,0,3,4 ] ( segment i d of first slice on thread ) offsets : DInt [ 0,45,0,5 ] ( offset of that slice in its segment ) splitSSegdOnElemsD :: Gang -> USSegd -> Dist ((USSegd,Int),Int) splitSSegdOnElemsD g !segd traceEvent ("dph-prim-par: USSegd.splitSSegdOnElems") $ imapD (What "UPSSegd.splitSSegdOnElems/splitLenIx") g mk (splitLenIdxD g (USegd.takeElements $ USSegd.takeUSegd segd)) where !nThreads = gangSize g The indices and elems fields of the contained USegd are buildUSSegd :: Vector Int -> Vector Int -> Vector Int -> USSegd buildUSSegd lengths starts sources = USSegd.mkUSSegd starts sources $ USegd.fromLengths lengths Segd for this thread , segid of first slice , and offset of first slice . mk i (nElems, ixStart) = case chunk segd ixStart nElems (i == nThreads - 1) of (# lengths, starts, sources, l, o #) -> ((buildUSSegd lengths starts sources, l), o) # NOINLINE splitSSegdOnElemsD # NOINLINE because it 's complicated and wo n't fuse with anything . In this picture each X represents 5 elements , and we have 5 segements in total . elems : |X X X X X X X X X|X X X X X X X X X|X X X X X X X X X|X X X X X X X X X| | | thread2 | | thread4 | : 0 0 3 4 offset : 0 45 0 5 k : 0 1 3 5 k ' : 1 3 5 5 left : 0 15 0 45 right : 45 20 5 0 left_len : 0 1 0 1 left_off : 0 45 0 5 n ' : 1 3 2 1 ^ Starting offset into the flat array for the first segid of first slice offset of first slice . chunk !ussegd !nStart !nElems is_last = (# lengths', starts', sources', k-left_len, left_off #) where eg : [ 60 , 10 , 20 , 40 , 50 ] lengths = USSegd.takeLengths ussegd eg : [ 0 , 60 , 70 , 90 , 130 ] indices = USSegd.takeIndices ussegd starts = USSegd.takeStarts ussegd sources = USSegd.takeSources ussegd eg : 5 n = Seq.length lengths Segid of the first seg that starts after the left of this chunk . k = search nStart indices Segid of the first seg that starts after the right of this chunk . k' | is_last = n | otherwise = search (nStart + nElems) indices left | k == n = nElems | otherwise = min ((Seq.index (here "chunk") indices k) - nStart) nElems length_right | k' == k = 0 | otherwise = nStart + nElems - (Seq.index (here "chunk") indices (k'-1)) Whether the first element in this chunk is an internal element of of a segment . Alternatively , indicates that the first element of the chunk is not the first element of a segment . left_len | left == 0 = 0 | otherwise = 1 If the first element of the chunk starts within a segment , left_off | left == 0 = 0 | otherwise = nStart - (Seq.index (here "chunk") indices (k-1)) n' = left_len + (k'-k) Create the lengths for this chunk by first copying out the lengths (!lengths', !starts', !sources') = runST (do mlengths' <- Seq.newM n' msources' <- Seq.newM n' mstarts' <- Seq.newM n' If the first element is inside a segment , when (left /= 0) $ do Seq.write mlengths' 0 left Seq.write mstarts' 0 (Seq.index (here "chunk") starts (k - left_len) + left_off) Seq.write msources' 0 (Seq.index (here "chunk") sources (k - left_len)) Seq.copy (Seq.mdrop left_len mlengths') (Seq.slice (here "chunk") lengths k (k'-k)) Seq.copy (Seq.mdrop left_len mstarts') (Seq.slice (here "chunk") starts k (k'-k)) Seq.copy (Seq.mdrop left_len msources') (Seq.slice (here "chunk") sources k (k'-k)) when (length_right /= 0) $ do Seq.write mlengths' (n' - 1) length_right clengths' <- Seq.unsafeFreeze mlengths' cstarts' <- Seq.unsafeFreeze mstarts' csources' <- Seq.unsafeFreeze msources' return (clengths', cstarts', csources')) = trace ( render [ text " CHUNK " , , text " nStart : " < + > int nStart , text " nElems : " < + > int nElems , text " k : " < + > int k , text " k ' : " < + > int k ' , text " left : " < + > int left , text " right : " < + > int right , text " left_len : " < + > int left_len , text " left_off : " < + > int left_off , text " n ' : " < + > int n ' , text " " ] ) lens ' (render $ vcat [ text "CHUNK" , pprp segd , text "nStart: " <+> int nStart , text "nElems: " <+> int nElems , text "k: " <+> int k , text "k': " <+> int k' , text "left: " <+> int left , text "right: " <+> int right , text "left_len:" <+> int left_len , text "left_off:" <+> int left_off , text "n': " <+> int n' , text ""]) lens' -} # INLINE_DIST chunk # INLINE_DIST even though it should be inlined into splitSSegdOnElemsD anyway find the first element that is larger than the given value . eg search 75 [ 0 , 60 , 70 , 90 , 130 ] = 90 search 43 [ 0 , 60 , 70 , 90 , 130 ] = 60 search :: Int -> Vector Int -> Int search !x ys = go 0 (Seq.length ys) where go i n | n <= 0 = i | Seq.index (here "search") ys mid < x = go (mid + 1) (n - half - 1) | otherwise = go i half where half = n `shiftR` 1 mid = i + half # INLINE_DIST search #
5dcb11a8edc3f00617bc167e785146570e8b258210e619a81cb015966e57bb3b
haroldcarr/learn-haskell-coq-ml-etc
EntityTagCache.hs
# OPTIONS_GHC -fno - warn - missing - signatures -fno - warn - unused - binds # {-# LANGUAGE OverloadedStrings #-} module EntityTagCache where import Control.Monad ((>=>)) import Data.List (isPrefixOf) import Data.Map.Strict as M import Data.Maybe as MB (mapMaybe) import Prelude as P import System.IO (IOMode (ReadMode), hGetContents, withFile) import Test.HUnit (Counts, Test (TestList), runTestTT) import qualified Test.HUnit.Util as U (t) ------------------------------------------------------------------------------ type MSI = Map String Int type MIS = Map Int String data Cache' a = Cache' { mii :: a , next :: Int -- next tag number , msi :: MSI -- tag to tag number , mis :: MIS -- tag number to tag } ss = mii ks = mii type Cache = Cache' (Map Int [Int]) -- entity id to tag numbers type DDIn = Cache' [String] -- input to DD type DDOut = Cache' [Int] -- output of DD ------------------------------------------------------------------------------ -- Use cache -- impure getTagsIO :: Int -> IO Cache -> IO (Maybe [String]) getTagsIO = fmap . getTags updateTagsIO :: Int -> [String] -> IO Cache -> IO Cache updateTagsIO x ts = fmap (updateTags x ts) -- pure getTags :: Int -> Cache -> Maybe [String] getTags x c = M.lookup x (mii c) >>= \r -> return $ MB.mapMaybe (`M.lookup` mis c) r updateTags :: Int -> [String] -> Cache -> Cache updateTags x ts c = -- (c,i0,msi0,mis0) let o = dedupTagIdTags (Cache' ts (next c) (msi c) (mis c)) in o { mii = M.insert x (ks o) (mii c) } ------------------------------------------------------------------------------ -- Populate cache loadCacheFromFile :: FilePath -> IO Cache loadCacheFromFile filename = withFile filename ReadMode (hGetContents >=> return . stringToCache) stringToCache :: String -> Cache stringToCache = dedupTags . collectTagIdAndTags ------------------------------------------------------------------------------ -- Internals collectTagIdAndTags :: String -> [(Int, [String])] collectTagIdAndTags = P.map mkEntry . lines where mkEntry x = let (i:xs) = splitOn "," x in (read i, xs) dedupTags :: [(Int, [String])] -> Cache dedupTags = P.foldr level1 (Cache' M.empty (-1) M.empty M.empty) where level1 (tag, ss0) c = let o = dedupTagIdTags (c { mii = ss0 }) in o { mii = M.insert tag (ks o) (mii c) } dedupTagIdTags :: DDIn -> DDOut dedupTagIdTags i = P.foldr level2 (i { mii = mempty }) (ss i) where level2 s o = case M.lookup s (msi o) of Just j -> o { mii = j:ks o } Nothing -> Cache' (next o:ks o) (next o + 1) (M.insert s (next o) (msi o)) (M.insert (next o) s (mis o)) ------------------------------------------------------------------------------ -- Test exCsv = "0,foo,bar\n1,abc,foo\n2\n3,xyz,bar" cache = stringToCache exCsv cToList c = (M.toList (mii c), next c, M.toList (msi c), M.toList (mis c)) tgt = U.t "tgt" (P.map (`getTags` cache) [0..4]) [ Just ["foo","bar"] , Just ["abc","foo"] , Just [] , Just ["xyz","bar"] , Nothing ] tut = U.t "tut" (cToList $ updateTags 2 ["new1","new2"] cache) ( [(0,[1,-1]), (1,[2,1]), (2,[4,3]), (3,[0,-1])] , 5 , [("abc",2),("bar",-1),("foo",1),("new1",4),("new2",3),("xyz",0)] , [(-1,"bar"),(0,"xyz"),(1,"foo"),(2,"abc"),(3,"new2"),(4,"new1")] ) tstc = U.t "tstc" (cToList cache) ( [(0,[1,-1]), (1,[2,1]), (2,[]), (3,[0,-1])] , 3 , [("abc",2),("bar",-1),("foo",1),("xyz",0)] , [(-1,"bar"),(0,"xyz"),(1,"foo"),(2,"abc")] ) tct = U.t "tct" (collectTagIdAndTags exCsv) [(0,["foo","bar"]), (1,["abc","foo"]), (2,[]), (3,["xyz","bar"])] tddt = U.t "tddt" (let o = dedupTagIdTags (Cache' ["foo", "bar", "baz", "foo", "baz", "baz", "foo", "qux", "new"] (-1) M.empty M.empty) in (ks o, next o, M.toList (msi o), M.toList (mis o))) ( [ 1, 3, 2, 1, 2, 2, 1, 0, -1] , 4::Int , [("bar",3),("baz",2),("foo",1),("new",-1),("qux",0)] , [(-1,"new"),(0,"qux"),(1,"foo"),(2,"baz"),(3,"bar")]) test :: IO Counts test = runTestTT $ TestList $ tgt ++ tut ++ tstc ++ tct ++ tddt ------------------------------------------------------------------------------ Utililties ( I ca n't find this in the libraries available on stackage ) splitOn :: Eq a => [a] -> [a] -> [[a]] splitOn _ [] = [] splitOn delim str = let (firstline, remainder) = breakList (isPrefixOf delim) str in firstline : case remainder of [] -> [] x -> if x == delim then [[]] else splitOn delim (drop (length delim) x) breakList :: ([a] -> Bool) -> [a] -> ([a], [a]) breakList func = spanList (not . func) spanList :: ([a] -> Bool) -> [a] -> ([a], [a]) spanList _ [] = ([],[]) spanList func list@(x:xs) = if func list then (x:ys,zs) else ([],list) where (ys,zs) = spanList func xs
null
https://raw.githubusercontent.com/haroldcarr/learn-haskell-coq-ml-etc/b4e83ec7c7af730de688b7376497b9f49dc24a0e/haskell/playpen/interview/api-catalog/src/EntityTagCache.hs
haskell
# LANGUAGE OverloadedStrings # ---------------------------------------------------------------------------- next tag number tag to tag number tag number to tag entity id to tag numbers input to DD output of DD ---------------------------------------------------------------------------- Use cache impure pure (c,i0,msi0,mis0) ---------------------------------------------------------------------------- Populate cache ---------------------------------------------------------------------------- Internals ---------------------------------------------------------------------------- Test ----------------------------------------------------------------------------
# OPTIONS_GHC -fno - warn - missing - signatures -fno - warn - unused - binds # module EntityTagCache where import Control.Monad ((>=>)) import Data.List (isPrefixOf) import Data.Map.Strict as M import Data.Maybe as MB (mapMaybe) import Prelude as P import System.IO (IOMode (ReadMode), hGetContents, withFile) import Test.HUnit (Counts, Test (TestList), runTestTT) import qualified Test.HUnit.Util as U (t) type MSI = Map String Int type MIS = Map Int String data Cache' a = Cache' { mii :: a } ss = mii ks = mii getTagsIO :: Int -> IO Cache -> IO (Maybe [String]) getTagsIO = fmap . getTags updateTagsIO :: Int -> [String] -> IO Cache -> IO Cache updateTagsIO x ts = fmap (updateTags x ts) getTags :: Int -> Cache -> Maybe [String] getTags x c = M.lookup x (mii c) >>= \r -> return $ MB.mapMaybe (`M.lookup` mis c) r updateTags :: Int -> [String] -> Cache -> Cache let o = dedupTagIdTags (Cache' ts (next c) (msi c) (mis c)) in o { mii = M.insert x (ks o) (mii c) } loadCacheFromFile :: FilePath -> IO Cache loadCacheFromFile filename = withFile filename ReadMode (hGetContents >=> return . stringToCache) stringToCache :: String -> Cache stringToCache = dedupTags . collectTagIdAndTags collectTagIdAndTags :: String -> [(Int, [String])] collectTagIdAndTags = P.map mkEntry . lines where mkEntry x = let (i:xs) = splitOn "," x in (read i, xs) dedupTags :: [(Int, [String])] -> Cache dedupTags = P.foldr level1 (Cache' M.empty (-1) M.empty M.empty) where level1 (tag, ss0) c = let o = dedupTagIdTags (c { mii = ss0 }) in o { mii = M.insert tag (ks o) (mii c) } dedupTagIdTags :: DDIn -> DDOut dedupTagIdTags i = P.foldr level2 (i { mii = mempty }) (ss i) where level2 s o = case M.lookup s (msi o) of Just j -> o { mii = j:ks o } Nothing -> Cache' (next o:ks o) (next o + 1) (M.insert s (next o) (msi o)) (M.insert (next o) s (mis o)) exCsv = "0,foo,bar\n1,abc,foo\n2\n3,xyz,bar" cache = stringToCache exCsv cToList c = (M.toList (mii c), next c, M.toList (msi c), M.toList (mis c)) tgt = U.t "tgt" (P.map (`getTags` cache) [0..4]) [ Just ["foo","bar"] , Just ["abc","foo"] , Just [] , Just ["xyz","bar"] , Nothing ] tut = U.t "tut" (cToList $ updateTags 2 ["new1","new2"] cache) ( [(0,[1,-1]), (1,[2,1]), (2,[4,3]), (3,[0,-1])] , 5 , [("abc",2),("bar",-1),("foo",1),("new1",4),("new2",3),("xyz",0)] , [(-1,"bar"),(0,"xyz"),(1,"foo"),(2,"abc"),(3,"new2"),(4,"new1")] ) tstc = U.t "tstc" (cToList cache) ( [(0,[1,-1]), (1,[2,1]), (2,[]), (3,[0,-1])] , 3 , [("abc",2),("bar",-1),("foo",1),("xyz",0)] , [(-1,"bar"),(0,"xyz"),(1,"foo"),(2,"abc")] ) tct = U.t "tct" (collectTagIdAndTags exCsv) [(0,["foo","bar"]), (1,["abc","foo"]), (2,[]), (3,["xyz","bar"])] tddt = U.t "tddt" (let o = dedupTagIdTags (Cache' ["foo", "bar", "baz", "foo", "baz", "baz", "foo", "qux", "new"] (-1) M.empty M.empty) in (ks o, next o, M.toList (msi o), M.toList (mis o))) ( [ 1, 3, 2, 1, 2, 2, 1, 0, -1] , 4::Int , [("bar",3),("baz",2),("foo",1),("new",-1),("qux",0)] , [(-1,"new"),(0,"qux"),(1,"foo"),(2,"baz"),(3,"bar")]) test :: IO Counts test = runTestTT $ TestList $ tgt ++ tut ++ tstc ++ tct ++ tddt Utililties ( I ca n't find this in the libraries available on stackage ) splitOn :: Eq a => [a] -> [a] -> [[a]] splitOn _ [] = [] splitOn delim str = let (firstline, remainder) = breakList (isPrefixOf delim) str in firstline : case remainder of [] -> [] x -> if x == delim then [[]] else splitOn delim (drop (length delim) x) breakList :: ([a] -> Bool) -> [a] -> ([a], [a]) breakList func = spanList (not . func) spanList :: ([a] -> Bool) -> [a] -> ([a], [a]) spanList _ [] = ([],[]) spanList func list@(x:xs) = if func list then (x:ys,zs) else ([],list) where (ys,zs) = spanList func xs
e2958b0c48acd4a940bab36816cc592eeb9e94551443068d90f2820e48183112
vikram/lisplibraries
compile.lisp
;;;; -*- lisp -*- (in-package :it.bese.yaclml) * TAL - Dynamic HTML Templating TAL is an HTML templating mechanism designed to provide enough ;;;; power to create any possible HTML output from a template yet at ;;;; the same time maintain the distinction between presentation logic ;;;; and program logic. TAL 's syntax tries to be as as possible , this is to help ;;;; graphic designers, who can't be bothered, and really shouldn't be ;;;; bothered, to learn a new syntax, and the most common design ;;;; tools, which work best with tags and attributes. A TAL template is an object ( represented internally as a function ;;;; and externally as a text file or a string) which, given an ;;;; environment mapping names to values and a generator which is able ;;;; to locate included templates, produces some text. ;;;; * Compiling TAL Templates Given a TAL template ( either an in - memory string or a file ) We ;;;; can compile this text into a function which, when called, prints ;;;; the corresponding HTML on *yaclml-stream*. The compiled function requires two arguments : an environment mapping names ( symbols ) to ;;;; lisp objects and a generator which is used for finding other ;;;; templates to include. * The TAL Expression language Generally we do n't want lisp code to appear in TAL templates , however there are two exceptions to this rule : ;;;; - tags or attributes which operate on values taken from the environment ( eg : the content and dolist attributes discussed ;;;; below) are passed regular lisp code ;;;; (expressed as text and then converted to lisp via ;;;; READ-FROM-STRING). ;;;; - Inside other HTML attributes where we would like to substitute ;;;; the value of some lisp code inside the textual value of the ;;;; attribute. When a lisp expression is expected as the value of a TAL ;;;; attribute the '$' read macro can be used to access values in current TAL environment . ;;;; When a string value is expected for an HTML attribute the syntax ;;;; "${...}" can be used to evaluate a lisp form and substitute the ;;;; result into the contain attribute value. The \"@{...}\" syntax ;;;; differs from the "${...}\" syntax in that the form is expected ;;;; to return a list and every element of that list is embedded in the enclosing attribute . Inside the lisp forms the \"$\ " read ;;;; macro is available as with regular lisp only attributes. ;;;; * Mapping Names to Tags and Attributes TAL templates are xml and use xml 's namespace mechanism for ;;;; defining the mapping from names to attribute and tag handlers. ;;;; Templates are always compiled with the default namespace bound to ;;;; the package :it.bese.yaclml.tags, this allows all the standard ;;;; HTML tags to be used without problems. The namespace identifier ;;;; -lisp.net/project/bese/tal/core can be used to ;;;; specify the :it.bese.yaclml.tal package which contains all the standard TAL tags and attributes . If it is necessary the ;;;; :it.bese.yaclml.tags namespace can be accessed via ;;;; "-lisp.net/project/bese/yaclml/core". Parameters ;;;; passed to included templates need to use the " -lisp.net/project/bese/tal/params " name space . (defvar *tal-attribute-handlers* '()) (defvar *tal-tag-handlers* '()) (defparameter *uri-to-package* (list (cons "-lisp.net/project/bese/tal/core" (find-package :it.bese.yaclml.tal)) (cons "-lisp.net/project/bese/tal/params" (find-package :it.bese.yaclml.tal.include-params)) (cons "-lisp.net/project/bese/yaclml/core" (find-package :it.bese.yaclml.tags))) "Default mapping of xmlns to packages.") (defvar *expression-package* nil "The value of *PACKAGE* when tal attribute expressions and for looking up symbols in the environment.") (defmacro def-attribute-handler (attribute (tag) &body body) "Defines a new attribute handler name ATTRIBUTE." `(progn (push (cons ',attribute (lambda (,tag) ,@body)) *tal-attribute-handlers*) ',attribute)) (defmacro def-tag-handler (tag-name (tag) &body body) "Defines a new tag handlec named TAG-NAME." `(progn (push (cons ',tag-name (lambda (,tag) ,@body)) *tal-tag-handlers*) ',tag-name)) (def-special-environment tal-compile-environment () generator) (defun |$ tal reader| (stream char) "The $ char reader for tal expressions." (declare (ignore char)) `(lookup-tal-variable ',(read stream) tal-environment)) (defun read-tal-expression-from-string (expression &optional implicit-progn-p) "Reads a single form from the string EXPRESSION using the TAL expression read table." (assert *expression-package* (*expression-package*) "No expression package!") (let ((*readtable* (copy-readtable nil)) (*package* *expression-package*)) ;; use $SYMBOL to access the value of the environment variable ;; SYMBOL (set-macro-character #\$ #'|$ tal reader| nil *readtable*) (if implicit-progn-p (iter (with pos = 0) (for (values obj new-pos) = (read-from-string expression nil nil :start pos)) (while obj) (setf pos new-pos) (collect obj into result) (finally (return (if (> (length result) 1) (cons 'progn result) (first result))))) (read-from-string expression)))) (defun parse-tal-attribute-value (value-string) "Parser a TAL attribute expression, returns a form for building the expression at run time." (let ((parts '())) (with-input-from-string (val value-string) (with-output-to-string (text) (flet ((read-tal-form () (let ((*readtable* (copy-readtable nil)) (*package* *expression-package*)) (set-macro-character #\} (get-macro-character #\)) nil *readtable*) (set-macro-character #\$ #'|$ tal reader| nil *readtable*) (read-delimited-list #\} val)))) (loop for char = (read-char val nil nil) while char do (case char (#\\ (let ((next-char (read-char val nil nil))) (if (null next-char) (error "Parse error in ~S. #\\ at end of string." value-string) (write-char next-char text)))) (#\$ (let ((next-char (peek-char nil val nil nil nil))) (if (and next-char (char= #\{ next-char)) (progn (read-char val nil nil nil) ;; first push the text uptil now onto parts (let ((up-to-now (get-output-stream-string text))) (unless (string= "" up-to-now) (push up-to-now parts))) ;; now push the form (push `(princ-to-string (progn ,@(read-tal-form))) parts)) (write-char #\$ text)))) (#\@ (let ((next-char (peek-char nil val nil nil))) (if (and next-char (char= #\{ next-char)) (progn (read-char val nil nil nil) ;; first push the text uptil now onto parts (push (get-output-stream-string text) parts) ;; now push the form (let ((form (read-tal-form)) (stream (gensym)) (i (gensym))) (push `(with-output-to-string (,stream) (dolist (,i (progn ,@form)) (princ ,i ,stream))) parts))) (write-char #\@ text)))) (t (write-char char text))) finally (let ((remaining-text (get-output-stream-string text))) (unless (string= "" remaining-text) (push remaining-text parts))))))) ;; done parsing, parts now contains everything to put in the ;; list, but in reverse order. (case (length parts) (0 "") (1 (car parts)) (t `(concatenate 'string ,@(nreverse parts)))))) (defun transform-lxml-tree (tree) "Given a tree representing some LXML code with TAL attributes returns the yaclml tag using code for generating the HTML. Destructivly modifies TREE." we collect strings and forms it the collector OPS . When we 're ;; done iterating (or recusring) over the tags we can string-fold ;; ops to get the longest posible string sequences. (mapcar (lambda (form) (transform-lxml-form form)) tree)) (defun transform-lxml-form (form) "Transforms the lxml tree FORM into common lisp code (a series of calls to tag macros)." (flet ((find-attribute-handlers (attributes) (loop for (key) on attributes by #'cddr for handler = (assoc key *tal-attribute-handlers* :test #'eql) when handler do (return-from transform-lxml-form (funcall (cdr handler) form)))) (find-tag-handler (tag-name) (dolist* ((name . handler) *tal-tag-handlers*) (when (eql name tag-name) (return-from transform-lxml-form (funcall handler form))))) (handle-regular-tag (tag-name attributes body) (unless (member tag-name '(:comment :xml)) `(,tag-name ,@(loop for (key value) on attributes by #'cddr nconc (list (intern (symbol-name key) :keyword) (if (stringp value) (parse-tal-attribute-value value) value))) ,@(transform-lxml-tree body))))) (if (stringp form) `(<:as-is ,form) (if (and (consp form) (consp (car form))) (destructuring-bind ((tag-name &rest attributes) &rest body) form ;; first see if there are any attribute handlers (find-attribute-handlers attributes) ;; first see if there's a handler for this tag (find-tag-handler tag-name) ;; didn't find a handler for that tag or any of it's attributes , must be a " regular " yaclml tag . (handle-regular-tag tag-name attributes body)) (error "Badly formatted YACLML: ~S." form))))) (defun compile-tal-string-to-lambda (string &optional (expression-package *package*)) "Returns the source code for the tal function form the tal text STRING." (bind-tal-compile-environment ((generator (gensym))) (with-tal-compile-environment (generator) `(lambda (tal-environment ,generator) (declare (ignorable tal-environment ,generator)) ,(let ((*package* (find-package :it.bese.yaclml.tags)) (*expression-package* expression-package)) (transform-lxml-form (it.bese.yaclml.xmls:parse string :uri-to-package *uri-to-package*))))))) (defun compile-tal-string (string &optional (expression-package (find-package :common-lisp-user))) (let ((*break-on-signals* t)) (compile nil (compile-tal-string-to-lambda string expression-package)))) (defun compile-tal-file (pathname &optional (expression-package (find-package :common-lisp-user))) (with-tal-compilation-unit pathname (compile-tal-string (read-tal-file-into-string pathname) expression-package))) Copyright ( c ) 2002 - 2005 , ;; 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 , nor , 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 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.
null
https://raw.githubusercontent.com/vikram/lisplibraries/105e3ef2d165275eb78f36f5090c9e2cdd0754dd/site/ucw-boxset/dependencies/yaclml/src/tal/compile.lisp
lisp
-*- lisp -*- power to create any possible HTML output from a template yet at the same time maintain the distinction between presentation logic and program logic. graphic designers, who can't be bothered, and really shouldn't be bothered, to learn a new syntax, and the most common design tools, which work best with tags and attributes. and externally as a text file or a string) which, given an environment mapping names to values and a generator which is able to locate included templates, produces some text. * Compiling TAL Templates can compile this text into a function which, when called, prints the corresponding HTML on *yaclml-stream*. The compiled function lisp objects and a generator which is used for finding other templates to include. - tags or attributes which operate on values taken from the below) are passed regular lisp code (expressed as text and then converted to lisp via READ-FROM-STRING). - Inside other HTML attributes where we would like to substitute the value of some lisp code inside the textual value of the attribute. attribute the '$' read macro can be used to access values in When a string value is expected for an HTML attribute the syntax "${...}" can be used to evaluate a lisp form and substitute the result into the contain attribute value. The \"@{...}\" syntax differs from the "${...}\" syntax in that the form is expected to return a list and every element of that list is embedded in macro is available as with regular lisp only attributes. * Mapping Names to Tags and Attributes defining the mapping from names to attribute and tag handlers. Templates are always compiled with the default namespace bound to the package :it.bese.yaclml.tags, this allows all the standard HTML tags to be used without problems. The namespace identifier -lisp.net/project/bese/tal/core can be used to specify the :it.bese.yaclml.tal package which contains all the :it.bese.yaclml.tags namespace can be accessed via "-lisp.net/project/bese/yaclml/core". Parameters passed to included templates need to use the use $SYMBOL to access the value of the environment variable SYMBOL first push the text uptil now onto parts now push the form first push the text uptil now onto parts now push the form done parsing, parts now contains everything to put in the list, but in reverse order. done iterating (or recusring) over the tags we can string-fold ops to get the longest posible string sequences. first see if there are any attribute handlers first see if there's a handler for this tag didn't find a handler for that tag or any of it's 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. 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 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT LOSS OF USE , DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY (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 :it.bese.yaclml) * TAL - Dynamic HTML Templating TAL is an HTML templating mechanism designed to provide enough TAL 's syntax tries to be as as possible , this is to help A TAL template is an object ( represented internally as a function Given a TAL template ( either an in - memory string or a file ) We requires two arguments : an environment mapping names ( symbols ) to * The TAL Expression language Generally we do n't want lisp code to appear in TAL templates , however there are two exceptions to this rule : environment ( eg : the content and dolist attributes discussed When a lisp expression is expected as the value of a TAL current TAL environment . the enclosing attribute . Inside the lisp forms the \"$\ " read TAL templates are xml and use xml 's namespace mechanism for standard TAL tags and attributes . If it is necessary the " -lisp.net/project/bese/tal/params " name space . (defvar *tal-attribute-handlers* '()) (defvar *tal-tag-handlers* '()) (defparameter *uri-to-package* (list (cons "-lisp.net/project/bese/tal/core" (find-package :it.bese.yaclml.tal)) (cons "-lisp.net/project/bese/tal/params" (find-package :it.bese.yaclml.tal.include-params)) (cons "-lisp.net/project/bese/yaclml/core" (find-package :it.bese.yaclml.tags))) "Default mapping of xmlns to packages.") (defvar *expression-package* nil "The value of *PACKAGE* when tal attribute expressions and for looking up symbols in the environment.") (defmacro def-attribute-handler (attribute (tag) &body body) "Defines a new attribute handler name ATTRIBUTE." `(progn (push (cons ',attribute (lambda (,tag) ,@body)) *tal-attribute-handlers*) ',attribute)) (defmacro def-tag-handler (tag-name (tag) &body body) "Defines a new tag handlec named TAG-NAME." `(progn (push (cons ',tag-name (lambda (,tag) ,@body)) *tal-tag-handlers*) ',tag-name)) (def-special-environment tal-compile-environment () generator) (defun |$ tal reader| (stream char) "The $ char reader for tal expressions." (declare (ignore char)) `(lookup-tal-variable ',(read stream) tal-environment)) (defun read-tal-expression-from-string (expression &optional implicit-progn-p) "Reads a single form from the string EXPRESSION using the TAL expression read table." (assert *expression-package* (*expression-package*) "No expression package!") (let ((*readtable* (copy-readtable nil)) (*package* *expression-package*)) (set-macro-character #\$ #'|$ tal reader| nil *readtable*) (if implicit-progn-p (iter (with pos = 0) (for (values obj new-pos) = (read-from-string expression nil nil :start pos)) (while obj) (setf pos new-pos) (collect obj into result) (finally (return (if (> (length result) 1) (cons 'progn result) (first result))))) (read-from-string expression)))) (defun parse-tal-attribute-value (value-string) "Parser a TAL attribute expression, returns a form for building the expression at run time." (let ((parts '())) (with-input-from-string (val value-string) (with-output-to-string (text) (flet ((read-tal-form () (let ((*readtable* (copy-readtable nil)) (*package* *expression-package*)) (set-macro-character #\} (get-macro-character #\)) nil *readtable*) (set-macro-character #\$ #'|$ tal reader| nil *readtable*) (read-delimited-list #\} val)))) (loop for char = (read-char val nil nil) while char do (case char (#\\ (let ((next-char (read-char val nil nil))) (if (null next-char) (error "Parse error in ~S. #\\ at end of string." value-string) (write-char next-char text)))) (#\$ (let ((next-char (peek-char nil val nil nil nil))) (if (and next-char (char= #\{ next-char)) (progn (read-char val nil nil nil) (let ((up-to-now (get-output-stream-string text))) (unless (string= "" up-to-now) (push up-to-now parts))) (push `(princ-to-string (progn ,@(read-tal-form))) parts)) (write-char #\$ text)))) (#\@ (let ((next-char (peek-char nil val nil nil))) (if (and next-char (char= #\{ next-char)) (progn (read-char val nil nil nil) (push (get-output-stream-string text) parts) (let ((form (read-tal-form)) (stream (gensym)) (i (gensym))) (push `(with-output-to-string (,stream) (dolist (,i (progn ,@form)) (princ ,i ,stream))) parts))) (write-char #\@ text)))) (t (write-char char text))) finally (let ((remaining-text (get-output-stream-string text))) (unless (string= "" remaining-text) (push remaining-text parts))))))) (case (length parts) (0 "") (1 (car parts)) (t `(concatenate 'string ,@(nreverse parts)))))) (defun transform-lxml-tree (tree) "Given a tree representing some LXML code with TAL attributes returns the yaclml tag using code for generating the HTML. Destructivly modifies TREE." we collect strings and forms it the collector OPS . When we 're (mapcar (lambda (form) (transform-lxml-form form)) tree)) (defun transform-lxml-form (form) "Transforms the lxml tree FORM into common lisp code (a series of calls to tag macros)." (flet ((find-attribute-handlers (attributes) (loop for (key) on attributes by #'cddr for handler = (assoc key *tal-attribute-handlers* :test #'eql) when handler do (return-from transform-lxml-form (funcall (cdr handler) form)))) (find-tag-handler (tag-name) (dolist* ((name . handler) *tal-tag-handlers*) (when (eql name tag-name) (return-from transform-lxml-form (funcall handler form))))) (handle-regular-tag (tag-name attributes body) (unless (member tag-name '(:comment :xml)) `(,tag-name ,@(loop for (key value) on attributes by #'cddr nconc (list (intern (symbol-name key) :keyword) (if (stringp value) (parse-tal-attribute-value value) value))) ,@(transform-lxml-tree body))))) (if (stringp form) `(<:as-is ,form) (if (and (consp form) (consp (car form))) (destructuring-bind ((tag-name &rest attributes) &rest body) form (find-attribute-handlers attributes) (find-tag-handler tag-name) attributes , must be a " regular " yaclml tag . (handle-regular-tag tag-name attributes body)) (error "Badly formatted YACLML: ~S." form))))) (defun compile-tal-string-to-lambda (string &optional (expression-package *package*)) "Returns the source code for the tal function form the tal text STRING." (bind-tal-compile-environment ((generator (gensym))) (with-tal-compile-environment (generator) `(lambda (tal-environment ,generator) (declare (ignorable tal-environment ,generator)) ,(let ((*package* (find-package :it.bese.yaclml.tags)) (*expression-package* expression-package)) (transform-lxml-form (it.bese.yaclml.xmls:parse string :uri-to-package *uri-to-package*))))))) (defun compile-tal-string (string &optional (expression-package (find-package :common-lisp-user))) (let ((*break-on-signals* t)) (compile nil (compile-tal-string-to-lambda string expression-package)))) (defun compile-tal-file (pathname &optional (expression-package (find-package :common-lisp-user))) (with-tal-compilation-unit pathname (compile-tal-string (read-tal-file-into-string pathname) expression-package))) Copyright ( c ) 2002 - 2005 , - Neither the name of , nor , nor the names " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT OWNER OR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT
366ac10fd1cc86318332d0626142c75b0094461463e747962bdc86bf566880d0
proper-testing/proper
rec_test2.erl
-*- coding : utf-8 -*- -*- erlang - indent - level : 2 -*- %%% ------------------------------------------------------------------- Copyright 2010 - 2022 < > , < > and < > %%% This file is part of PropEr . %%% %%% PropEr 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. %%% %%% PropEr 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 PropEr. If not, see </>. 2010 - 2022 , and %%% @version {@version} @author %%% @doc This module contains types for testing the typeserver. -module(rec_test2). -export_type([aa/0, b/0, expa/0, rec/0]). -type a() :: 'aleaf' | {'anode',b()}. -opaque b() :: {'bnode',b()} | a(). -type expa() :: 'a' | rec_test1:expb(). -record(rec, {a = 0 :: integer(), b = 'nil' :: 'nil' | #rec{}}). -type rec() :: #rec{b :: 'nil'} | #rec{b :: rec()}. -type aa() :: {aa(),aa()}.
null
https://raw.githubusercontent.com/proper-testing/proper/9f9f18a3e5a7dc3e07c54b0af5fbbdb4c65897d1/test/rec_test2.erl
erlang
------------------------------------------------------------------- PropEr is free software: you can redistribute it and/or modify (at your option) any later version. PropEr is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. along with PropEr. If not, see </>. @version {@version} @doc This module contains types for testing the typeserver.
-*- coding : utf-8 -*- -*- erlang - indent - level : 2 -*- Copyright 2010 - 2022 < > , < > and < > This file is part of PropEr . it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , or You should have received a copy of the GNU General Public License 2010 - 2022 , and @author -module(rec_test2). -export_type([aa/0, b/0, expa/0, rec/0]). -type a() :: 'aleaf' | {'anode',b()}. -opaque b() :: {'bnode',b()} | a(). -type expa() :: 'a' | rec_test1:expb(). -record(rec, {a = 0 :: integer(), b = 'nil' :: 'nil' | #rec{}}). -type rec() :: #rec{b :: 'nil'} | #rec{b :: rec()}. -type aa() :: {aa(),aa()}.
eeb08b721a0891875af6933642caed44cba42325f0ed1a0cd8ca08f1bf1741e6
magnars/confair
config_admin_test.clj
(ns confair.config-admin-test (:require [clojure.test :refer [deftest is testing]] [confair.config-admin :as sut] [confair.config :as config] [test-with-files.tools :refer [with-files]])) (deftest conceal-reveal-test (with-files tmp-dir ["config.edn" (str "^" {:config/secrets {:secret/test "mypass"}} {:api-key "foobar"})] (let [config-path (str tmp-dir "/config.edn")] ;; conceal (is (= (sut/conceal-value (config/from-file config-path) :secret/test [:api-key]) [:concealed [:api-key] :in config-path])) (let [config (config/from-file config-path)] (is (= (:api-key config) "foobar")) (is (= (:config/encrypted-paths (meta config)) {[:api-key] :secret/test}))) (is (re-find #":api-key \[:secret/test " (slurp config-path))) (is (= (sut/conceal-value (config/from-file config-path) :secret/test [:api-key]) [:path-already-encrypted [:api-key]])) ;; reveal (is (= (sut/reveal-value (config/from-file config-path) [:api-key]) [:revealed [:api-key] :in config-path])) (let [config (config/from-file config-path)] (is (= (:api-key config) "foobar")) (is (= (:config/encrypted-paths (meta config)) {}))) (is (re-find #":api-key \"foobar\"" (slurp config-path))) (is (= (sut/reveal-value (config/from-file config-path) [:api-key]) [:path-isnt-encrypted [:api-key]]))))) (deftest dont-conceal-refs-test (with-files tmp-dir ["stuff.txt" "content" "config.edn" (str "^" {:config/secrets {:secret/test "mypass"}} {:api-key "foobar" :stuff [:config/file (str tmp-dir "/stuff.txt")]})] (let [config-path (str tmp-dir "/config.edn")] (is (= (sut/conceal-value (config/from-file config-path) :secret/test [:stuff]) [:skipping [:stuff] :defined-in [:config/file (str tmp-dir "/stuff.txt")]])) (is (= (sut/reveal-value (config/from-file config-path) [:stuff]) [:path-isnt-encrypted [:stuff]]))))) (deftest nested-test (with-files tmp-dir ["config.edn" (str "^" {:config/secrets {:secret/test "mypass"}} {:providers [{:name "Foo" :password "foo-pw"} {:name "Bar" :password "bar-pw"}]})] (let [config-path (str tmp-dir "/config.edn")] (is (= (sut/conceal-value (config/from-file config-path) :secret/test [:providers 0 :password]) [:concealed [:providers 0 :password] :in config-path])) (let [config (config/from-file config-path)] (is (= (get-in config [:providers 0 :password]) "foo-pw")) (is (= (:config/encrypted-paths (meta config)) {[:providers 0 :password] :secret/test}))) (is (= (sut/conceal-value (config/from-file config-path) :secret/test [:providers 2]) [:no-value-at-path [:providers 2]]))))) (deftest replace-secret-test (with-files tmp-dir ["foo.edn" (str {:api-key "ghosts"}) "bar.edn" (str {:password "goblins"}) "baz.edn" (str {:theme "ghouls"})] (is (= (sut/conceal-value (config/from-file (str tmp-dir "/foo.edn") {:secrets {:secret/test "boom"}}) :secret/test [:api-key]) [:concealed [:api-key] :in (str tmp-dir "/foo.edn")])) (is (= (sut/conceal-value (config/from-file (str tmp-dir "/bar.edn") {:secrets {:secret/test "boom"}}) :secret/test [:password]) [:concealed [:password] :in (str tmp-dir "/bar.edn")])) (is (= (set (sut/replace-secret {:files (sut/find-files tmp-dir #"edn$") :secret-key :secret/test :old-secret "boom" :new-secret "bang"})) #{[:replaced-secret [:api-key] :in (str tmp-dir "/foo.edn")] [:replaced-secret [:password] :in (str tmp-dir "/bar.edn")] [:nothing-to-do :in (str tmp-dir "/baz.edn")]})) (spit (str tmp-dir "/merged.edn") (str "^" {:config/secrets {:secret/test "bang"} :dev-config/import [(str tmp-dir "/foo.edn") (str tmp-dir "/bar.edn") (str tmp-dir "/baz.edn")]} {:merged? true})) (let [config (config/from-file (str tmp-dir "/merged.edn"))] (is (= config {:api-key "ghosts" :password "goblins" :theme "ghouls" :merged? true})))))
null
https://raw.githubusercontent.com/magnars/confair/60332690d639d40c4f57b96c7d09e31b9606d6a2/test/confair/config_admin_test.clj
clojure
conceal reveal
(ns confair.config-admin-test (:require [clojure.test :refer [deftest is testing]] [confair.config-admin :as sut] [confair.config :as config] [test-with-files.tools :refer [with-files]])) (deftest conceal-reveal-test (with-files tmp-dir ["config.edn" (str "^" {:config/secrets {:secret/test "mypass"}} {:api-key "foobar"})] (let [config-path (str tmp-dir "/config.edn")] (is (= (sut/conceal-value (config/from-file config-path) :secret/test [:api-key]) [:concealed [:api-key] :in config-path])) (let [config (config/from-file config-path)] (is (= (:api-key config) "foobar")) (is (= (:config/encrypted-paths (meta config)) {[:api-key] :secret/test}))) (is (re-find #":api-key \[:secret/test " (slurp config-path))) (is (= (sut/conceal-value (config/from-file config-path) :secret/test [:api-key]) [:path-already-encrypted [:api-key]])) (is (= (sut/reveal-value (config/from-file config-path) [:api-key]) [:revealed [:api-key] :in config-path])) (let [config (config/from-file config-path)] (is (= (:api-key config) "foobar")) (is (= (:config/encrypted-paths (meta config)) {}))) (is (re-find #":api-key \"foobar\"" (slurp config-path))) (is (= (sut/reveal-value (config/from-file config-path) [:api-key]) [:path-isnt-encrypted [:api-key]]))))) (deftest dont-conceal-refs-test (with-files tmp-dir ["stuff.txt" "content" "config.edn" (str "^" {:config/secrets {:secret/test "mypass"}} {:api-key "foobar" :stuff [:config/file (str tmp-dir "/stuff.txt")]})] (let [config-path (str tmp-dir "/config.edn")] (is (= (sut/conceal-value (config/from-file config-path) :secret/test [:stuff]) [:skipping [:stuff] :defined-in [:config/file (str tmp-dir "/stuff.txt")]])) (is (= (sut/reveal-value (config/from-file config-path) [:stuff]) [:path-isnt-encrypted [:stuff]]))))) (deftest nested-test (with-files tmp-dir ["config.edn" (str "^" {:config/secrets {:secret/test "mypass"}} {:providers [{:name "Foo" :password "foo-pw"} {:name "Bar" :password "bar-pw"}]})] (let [config-path (str tmp-dir "/config.edn")] (is (= (sut/conceal-value (config/from-file config-path) :secret/test [:providers 0 :password]) [:concealed [:providers 0 :password] :in config-path])) (let [config (config/from-file config-path)] (is (= (get-in config [:providers 0 :password]) "foo-pw")) (is (= (:config/encrypted-paths (meta config)) {[:providers 0 :password] :secret/test}))) (is (= (sut/conceal-value (config/from-file config-path) :secret/test [:providers 2]) [:no-value-at-path [:providers 2]]))))) (deftest replace-secret-test (with-files tmp-dir ["foo.edn" (str {:api-key "ghosts"}) "bar.edn" (str {:password "goblins"}) "baz.edn" (str {:theme "ghouls"})] (is (= (sut/conceal-value (config/from-file (str tmp-dir "/foo.edn") {:secrets {:secret/test "boom"}}) :secret/test [:api-key]) [:concealed [:api-key] :in (str tmp-dir "/foo.edn")])) (is (= (sut/conceal-value (config/from-file (str tmp-dir "/bar.edn") {:secrets {:secret/test "boom"}}) :secret/test [:password]) [:concealed [:password] :in (str tmp-dir "/bar.edn")])) (is (= (set (sut/replace-secret {:files (sut/find-files tmp-dir #"edn$") :secret-key :secret/test :old-secret "boom" :new-secret "bang"})) #{[:replaced-secret [:api-key] :in (str tmp-dir "/foo.edn")] [:replaced-secret [:password] :in (str tmp-dir "/bar.edn")] [:nothing-to-do :in (str tmp-dir "/baz.edn")]})) (spit (str tmp-dir "/merged.edn") (str "^" {:config/secrets {:secret/test "bang"} :dev-config/import [(str tmp-dir "/foo.edn") (str tmp-dir "/bar.edn") (str tmp-dir "/baz.edn")]} {:merged? true})) (let [config (config/from-file (str tmp-dir "/merged.edn"))] (is (= config {:api-key "ghosts" :password "goblins" :theme "ghouls" :merged? true})))))
18cd7f720dd8ebd08047de0ba561795d49fb698942299b5a2f88a7ecc6bd37df
ff-notes/ron
Main.hs
# LANGUAGE DisambiguateRecordFields # # LANGUAGE LambdaCase # # LANGUAGE NamedFieldPuns # {-# LANGUAGE OverloadedStrings #-} import Brick (App (App), BrickEvent (AppEvent, VtyEvent), EventM, Next, Widget, attrMap, continue, customMain, halt, showFirstCursor, txt, (<=>)) import qualified Brick import Brick.BChan (BChan, newBChan, writeBChan) import Brick.Widgets.Border (border) import Brick.Widgets.Edit (Editor, applyEdit, editorText, getEditContents, handleEditorEvent, renderEditor) import Control.Concurrent (forkIO, threadDelay) import Control.Monad (forever, void) import Control.Monad.IO.Class (liftIO) import Data.Text (Text) import qualified Data.Text as Text import Data.Text.Zipper (TextZipper, cursorPosition, moveCursor, textZipper) import qualified Data.Text.Zipper as TextZipper import Graphics.Vty (Event (EvKey), Key (KEsc), defaultConfig, mkVty) import RON.Data (evalObjectState, execObjectState) import RON.Data.RGA (RgaString) import qualified RON.Data.RGA as RGA import RON.Storage.Backend (DocId (DocId), Document (Document), createVersion, objectFrame) import RON.Storage.FS (loadDocument, runStorage) import qualified RON.Storage.FS as Storage import Types () theDoc :: DocId RgaString theDoc = DocId "B3QCFGMHK1QJS-2005CRP400492" main :: IO () main = do let dataDir = "demo/data" h <- Storage.newHandle dataDir (document, text) <- runStorage h $ do document@Document {objectFrame} <- loadDocument theDoc text <- evalObjectState objectFrame RGA.getText pure (document, text) rhythm <- mkRhythm runUI rhythm (mkApp h) MyState {editor = mkEditor text, document} mkEditor :: Text -> Editor Text () mkEditor = editorText () Nothing mkRhythm :: IO (BChan ()) mkRhythm = do chan <- newBChan 1 _ <- forkIO $ forever $ do writeBChan chan () threadDelay 1000000 pure chan runUI :: BChan () -> App s () () -> s -> IO () runUI chan app initialState = do let buildVty = mkVty defaultConfig initialVty <- buildVty void $ customMain initialVty buildVty (Just chan) app initialState data MyState = MyState {editor :: Editor Text (), document :: Document RgaString} mkApp :: Storage.Handle -> App MyState () () mkApp storage = App { appAttrMap = const $ attrMap mempty [], appChooseCursor = showFirstCursor, appDraw = draw, appHandleEvent = handleEvent storage, appStartEvent = pure } draw :: MyState -> [Widget ()] draw MyState {editor} = [ border (renderEditor (txt . Text.unlines) True editor) <=> txt "Esc -> exit" ] handleEvent :: Storage.Handle -> MyState -> BrickEvent () () -> EventM () (Next MyState) handleEvent storage state@MyState {editor} = \case VtyEvent ve -> case ve of EvKey KEsc [] -> do state' <- liftIO $ sync storage state False halt state' _ -> do editor' <- handleEditorEvent ve editor continue state {editor = editor'} AppEvent () -> do state' <- liftIO $ sync storage state True continue state' _ -> continue state sync :: Storage.Handle -> MyState -> Bool -> IO MyState sync storage state@MyState {editor, document} reload = runStorage storage $ do do let Document {objectFrame} = document objectFrame' <- execObjectState objectFrame $ RGA.editText $ Text.unlines $ getEditContents editor createVersion (Just (theDoc, document)) objectFrame' if reload then do document'@Document {objectFrame} <- loadDocument theDoc text <- evalObjectState objectFrame RGA.getText let editor' = applyEdit (replaceZipper text) editor pure MyState {editor = editor', document = document'} else pure state -- | Replace content in zipper keeping cursor TODO save RGA ids and keep position after RGA changes replaceZipper :: Text -> TextZipper Text -> TextZipper Text replaceZipper text zipper = moveCursorClosely originalPosition zipper' where zipper' = textZipper (Text.lines text) Nothing originalPosition = cursorPosition zipper moveCursorClosely :: (Int, Int) -> TextZipper Text -> TextZipper Text moveCursorClosely (row, col) tz | row < 0 = moveCursor (0, 0) tz | row >= rows = moveCursor (rows - 1, 0) tz | col < 0 = moveCursor (row, 0) tz | col > cols = moveCursor (row, cols) tz | otherwise = moveCursor (row, col) tz where t = TextZipper.getText tz rows = length t cols = Text.length (t !! row)
null
https://raw.githubusercontent.com/ff-notes/ron/0df2b7985996ecc498808ea7247d0d8de471da4f/demo/text-editor-brick/Main.hs
haskell
# LANGUAGE OverloadedStrings # | Replace content in zipper keeping cursor
# LANGUAGE DisambiguateRecordFields # # LANGUAGE LambdaCase # # LANGUAGE NamedFieldPuns # import Brick (App (App), BrickEvent (AppEvent, VtyEvent), EventM, Next, Widget, attrMap, continue, customMain, halt, showFirstCursor, txt, (<=>)) import qualified Brick import Brick.BChan (BChan, newBChan, writeBChan) import Brick.Widgets.Border (border) import Brick.Widgets.Edit (Editor, applyEdit, editorText, getEditContents, handleEditorEvent, renderEditor) import Control.Concurrent (forkIO, threadDelay) import Control.Monad (forever, void) import Control.Monad.IO.Class (liftIO) import Data.Text (Text) import qualified Data.Text as Text import Data.Text.Zipper (TextZipper, cursorPosition, moveCursor, textZipper) import qualified Data.Text.Zipper as TextZipper import Graphics.Vty (Event (EvKey), Key (KEsc), defaultConfig, mkVty) import RON.Data (evalObjectState, execObjectState) import RON.Data.RGA (RgaString) import qualified RON.Data.RGA as RGA import RON.Storage.Backend (DocId (DocId), Document (Document), createVersion, objectFrame) import RON.Storage.FS (loadDocument, runStorage) import qualified RON.Storage.FS as Storage import Types () theDoc :: DocId RgaString theDoc = DocId "B3QCFGMHK1QJS-2005CRP400492" main :: IO () main = do let dataDir = "demo/data" h <- Storage.newHandle dataDir (document, text) <- runStorage h $ do document@Document {objectFrame} <- loadDocument theDoc text <- evalObjectState objectFrame RGA.getText pure (document, text) rhythm <- mkRhythm runUI rhythm (mkApp h) MyState {editor = mkEditor text, document} mkEditor :: Text -> Editor Text () mkEditor = editorText () Nothing mkRhythm :: IO (BChan ()) mkRhythm = do chan <- newBChan 1 _ <- forkIO $ forever $ do writeBChan chan () threadDelay 1000000 pure chan runUI :: BChan () -> App s () () -> s -> IO () runUI chan app initialState = do let buildVty = mkVty defaultConfig initialVty <- buildVty void $ customMain initialVty buildVty (Just chan) app initialState data MyState = MyState {editor :: Editor Text (), document :: Document RgaString} mkApp :: Storage.Handle -> App MyState () () mkApp storage = App { appAttrMap = const $ attrMap mempty [], appChooseCursor = showFirstCursor, appDraw = draw, appHandleEvent = handleEvent storage, appStartEvent = pure } draw :: MyState -> [Widget ()] draw MyState {editor} = [ border (renderEditor (txt . Text.unlines) True editor) <=> txt "Esc -> exit" ] handleEvent :: Storage.Handle -> MyState -> BrickEvent () () -> EventM () (Next MyState) handleEvent storage state@MyState {editor} = \case VtyEvent ve -> case ve of EvKey KEsc [] -> do state' <- liftIO $ sync storage state False halt state' _ -> do editor' <- handleEditorEvent ve editor continue state {editor = editor'} AppEvent () -> do state' <- liftIO $ sync storage state True continue state' _ -> continue state sync :: Storage.Handle -> MyState -> Bool -> IO MyState sync storage state@MyState {editor, document} reload = runStorage storage $ do do let Document {objectFrame} = document objectFrame' <- execObjectState objectFrame $ RGA.editText $ Text.unlines $ getEditContents editor createVersion (Just (theDoc, document)) objectFrame' if reload then do document'@Document {objectFrame} <- loadDocument theDoc text <- evalObjectState objectFrame RGA.getText let editor' = applyEdit (replaceZipper text) editor pure MyState {editor = editor', document = document'} else pure state TODO save RGA ids and keep position after RGA changes replaceZipper :: Text -> TextZipper Text -> TextZipper Text replaceZipper text zipper = moveCursorClosely originalPosition zipper' where zipper' = textZipper (Text.lines text) Nothing originalPosition = cursorPosition zipper moveCursorClosely :: (Int, Int) -> TextZipper Text -> TextZipper Text moveCursorClosely (row, col) tz | row < 0 = moveCursor (0, 0) tz | row >= rows = moveCursor (rows - 1, 0) tz | col < 0 = moveCursor (row, 0) tz | col > cols = moveCursor (row, cols) tz | otherwise = moveCursor (row, col) tz where t = TextZipper.getText tz rows = length t cols = Text.length (t !! row)
ec796833bfeb3b4b5d09602d2f4ee941601f11bfd8b656ca1b90030c9c6a5241
paulbutcher/electron-app
config.cljs
(ns {{name}}.config) (def index-html "resources/index-dev.html") (def test-html "resources/test.html")
null
https://raw.githubusercontent.com/paulbutcher/electron-app/2b67a893b7dba60bf91d504a2daa009149c6fc9b/resources/clj/new/electron_app/src/config/dev/config.cljs
clojure
(ns {{name}}.config) (def index-html "resources/index-dev.html") (def test-html "resources/test.html")
0c6f3e7df4fd5041a423fb65afe2fbc5e991a9b38276b1b2f5989fc3a51ce391
scrintal/heroicons-reagent
rectangle_group.cljs
(ns com.scrintal.heroicons.solid.rectangle-group) (defn render [] [:svg {:xmlns "" :viewBox "0 0 24 24" :fill "currentColor" :aria-hidden "true"} [:path {:fillRule "evenodd" :d "M1.5 7.125c0-1.036.84-1.875 1.875-1.875h6c1.036 0 1.875.84 1.875 1.875v3.75c0 1.036-.84 1.875-1.875 1.875h-6A1.875 1.875 0 011.5 10.875v-3.75zm12 1.5c0-1.036.84-1.875 1.875-1.875h5.25c1.035 0 1.875.84 1.875 1.875v8.25c0 1.035-.84 1.875-1.875 1.875h-5.25a1.875 1.875 0 01-1.875-1.875v-8.25zM3 16.125c0-1.036.84-1.875 1.875-1.875h5.25c1.036 0 1.875.84 1.875 1.875v2.25c0 1.035-.84 1.875-1.875 1.875h-5.25A1.875 1.875 0 013 18.375v-2.25z" :clipRule "evenodd"}]])
null
https://raw.githubusercontent.com/scrintal/heroicons-reagent/572f51d2466697ec4d38813663ee2588960365b6/src/com/scrintal/heroicons/solid/rectangle_group.cljs
clojure
(ns com.scrintal.heroicons.solid.rectangle-group) (defn render [] [:svg {:xmlns "" :viewBox "0 0 24 24" :fill "currentColor" :aria-hidden "true"} [:path {:fillRule "evenodd" :d "M1.5 7.125c0-1.036.84-1.875 1.875-1.875h6c1.036 0 1.875.84 1.875 1.875v3.75c0 1.036-.84 1.875-1.875 1.875h-6A1.875 1.875 0 011.5 10.875v-3.75zm12 1.5c0-1.036.84-1.875 1.875-1.875h5.25c1.035 0 1.875.84 1.875 1.875v8.25c0 1.035-.84 1.875-1.875 1.875h-5.25a1.875 1.875 0 01-1.875-1.875v-8.25zM3 16.125c0-1.036.84-1.875 1.875-1.875h5.25c1.036 0 1.875.84 1.875 1.875v2.25c0 1.035-.84 1.875-1.875 1.875h-5.25A1.875 1.875 0 013 18.375v-2.25z" :clipRule "evenodd"}]])
771f4892f311865ff5d2a92b9aa20d8a5cb0f92315bde2d7f0b5681d275155d0
NorfairKing/habitscipline
OptParse.hs
# LANGUAGE DeriveGeneric # # LANGUAGE DerivingVia # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE QuasiQuotes # # LANGUAGE RecordWildCards # # LANGUAGE TypeApplications # module Habitscipline.TUI.OptParse where import Autodocodec import Autodocodec.Yaml import Control.Applicative import Control.Monad.Logger import Data.Maybe import qualified Data.Text as T import Data.Yaml (FromJSON, ToJSON) import qualified Env import GHC.Generics (Generic) import Habitscipline.CLI.OptParse (getDefaultClientDatabase) import Options.Applicative as OptParse import qualified Options.Applicative.Help as OptParse (string) import Path import Path.IO getSettings :: IO Settings getSettings = do flags <- getFlags env <- getEnvironment config <- getConfiguration flags env combineToSettings flags env config data Settings = Settings { settingDbFile :: !(Path Abs File), settingLogLevel :: !LogLevel } deriving (Show, Eq, Generic) combineToSettings :: Flags -> Environment -> Maybe Configuration -> IO Settings combineToSettings Flags {..} Environment {..} mConf = do settingDbFile <- case flagDbFile <|> envDbFile <|> mc configDbFile of Nothing -> getDefaultClientDatabase Just dbf -> resolveFile' dbf let settingLogLevel = fromMaybe LevelWarn $ flagLogLevel <|> envLogLevel <|> mc configLogLevel pure Settings {..} where mc :: (Configuration -> Maybe a) -> Maybe a mc f = mConf >>= f data Configuration = Configuration { configDbFile :: !(Maybe FilePath), configLogLevel :: !(Maybe LogLevel) } deriving stock (Show, Eq, Generic) deriving (FromJSON, ToJSON) via (Autodocodec Configuration) instance HasCodec Configuration where codec = object "Configuration" $ Configuration <$> optionalField "database" "The path to the database" .= configDbFile <*> optionalField "log-level" "The minimal severity for log messages" .= configLogLevel getConfiguration :: Flags -> Environment -> IO (Maybe Configuration) getConfiguration Flags {..} Environment {..} = case flagConfigFile <|> envConfigFile of Nothing -> defaultConfigFile >>= readYamlConfigFile Just cf -> do afp <- resolveFile' cf readYamlConfigFile afp defaultConfigFile :: IO (Path Abs File) defaultConfigFile = do xdgConfigDir <- getXdgDir XdgConfig (Just [reldir|optparse-template|]) resolveFile xdgConfigDir "config.yaml" data Environment = Environment { envConfigFile :: !(Maybe FilePath), envDbFile :: !(Maybe FilePath), envLogLevel :: !(Maybe LogLevel) } deriving (Show, Eq, Generic) getEnvironment :: IO Environment getEnvironment = Env.parse (Env.header "Environment") environmentParser -- | The 'envparse' parser for the 'Environment' environmentParser :: Env.Parser Env.Error Environment environmentParser = Env.prefixed "HABITSCIPLINE_" $ Environment <$> optional (Env.var Env.str "CONFIG_FILE" (Env.help "Config file")) <*> optional (Env.var Env.str "DATABASE" (Env.help "Path to the database")) <*> optional (Env.var Env.auto "LOG_LEVEL" (Env.help "Minimal severity for log messages")) getFlags :: IO Flags getFlags = customExecParser prefs_ flagsParser prefs_ :: OptParse.ParserPrefs prefs_ = OptParse.defaultPrefs { OptParse.prefShowHelpOnError = True, OptParse.prefShowHelpOnEmpty = True } flagsParser :: OptParse.ParserInfo Flags flagsParser = OptParse.info (OptParse.helper <*> parseFlags) (OptParse.fullDesc <> OptParse.footerDoc (Just $ OptParse.string footerStr)) where footerStr = unlines [ Env.helpDoc environmentParser, "", "Configuration file format:", T.unpack (renderColouredSchemaViaCodec @Configuration) ] data Flags = Flags { flagConfigFile :: !(Maybe FilePath), flagDbFile :: !(Maybe FilePath), flagLogLevel :: !(Maybe LogLevel) } deriving (Show, Eq, Generic) parseFlags :: OptParse.Parser Flags parseFlags = Flags <$> optional ( strOption ( mconcat [ long "config-file", help "Path to an altenative config file", metavar "FILEPATH" ] ) ) <*> optional ( strOption ( mconcat [ long "database", help "Path to the database", metavar "FILEPATH" ] ) ) <*> optional ( option auto ( mconcat [ long "log-level", help "Minimal severity level for log messages", metavar "LOG_LEVEL" ] ) )
null
https://raw.githubusercontent.com/NorfairKing/habitscipline/ce85ce69889c1a6607875a8ecf1c14cfaabfa83d/habitscipline-tui/src/Habitscipline/TUI/OptParse.hs
haskell
# LANGUAGE OverloadedStrings # | The 'envparse' parser for the 'Environment'
# LANGUAGE DeriveGeneric # # LANGUAGE DerivingVia # # LANGUAGE QuasiQuotes # # LANGUAGE RecordWildCards # # LANGUAGE TypeApplications # module Habitscipline.TUI.OptParse where import Autodocodec import Autodocodec.Yaml import Control.Applicative import Control.Monad.Logger import Data.Maybe import qualified Data.Text as T import Data.Yaml (FromJSON, ToJSON) import qualified Env import GHC.Generics (Generic) import Habitscipline.CLI.OptParse (getDefaultClientDatabase) import Options.Applicative as OptParse import qualified Options.Applicative.Help as OptParse (string) import Path import Path.IO getSettings :: IO Settings getSettings = do flags <- getFlags env <- getEnvironment config <- getConfiguration flags env combineToSettings flags env config data Settings = Settings { settingDbFile :: !(Path Abs File), settingLogLevel :: !LogLevel } deriving (Show, Eq, Generic) combineToSettings :: Flags -> Environment -> Maybe Configuration -> IO Settings combineToSettings Flags {..} Environment {..} mConf = do settingDbFile <- case flagDbFile <|> envDbFile <|> mc configDbFile of Nothing -> getDefaultClientDatabase Just dbf -> resolveFile' dbf let settingLogLevel = fromMaybe LevelWarn $ flagLogLevel <|> envLogLevel <|> mc configLogLevel pure Settings {..} where mc :: (Configuration -> Maybe a) -> Maybe a mc f = mConf >>= f data Configuration = Configuration { configDbFile :: !(Maybe FilePath), configLogLevel :: !(Maybe LogLevel) } deriving stock (Show, Eq, Generic) deriving (FromJSON, ToJSON) via (Autodocodec Configuration) instance HasCodec Configuration where codec = object "Configuration" $ Configuration <$> optionalField "database" "The path to the database" .= configDbFile <*> optionalField "log-level" "The minimal severity for log messages" .= configLogLevel getConfiguration :: Flags -> Environment -> IO (Maybe Configuration) getConfiguration Flags {..} Environment {..} = case flagConfigFile <|> envConfigFile of Nothing -> defaultConfigFile >>= readYamlConfigFile Just cf -> do afp <- resolveFile' cf readYamlConfigFile afp defaultConfigFile :: IO (Path Abs File) defaultConfigFile = do xdgConfigDir <- getXdgDir XdgConfig (Just [reldir|optparse-template|]) resolveFile xdgConfigDir "config.yaml" data Environment = Environment { envConfigFile :: !(Maybe FilePath), envDbFile :: !(Maybe FilePath), envLogLevel :: !(Maybe LogLevel) } deriving (Show, Eq, Generic) getEnvironment :: IO Environment getEnvironment = Env.parse (Env.header "Environment") environmentParser environmentParser :: Env.Parser Env.Error Environment environmentParser = Env.prefixed "HABITSCIPLINE_" $ Environment <$> optional (Env.var Env.str "CONFIG_FILE" (Env.help "Config file")) <*> optional (Env.var Env.str "DATABASE" (Env.help "Path to the database")) <*> optional (Env.var Env.auto "LOG_LEVEL" (Env.help "Minimal severity for log messages")) getFlags :: IO Flags getFlags = customExecParser prefs_ flagsParser prefs_ :: OptParse.ParserPrefs prefs_ = OptParse.defaultPrefs { OptParse.prefShowHelpOnError = True, OptParse.prefShowHelpOnEmpty = True } flagsParser :: OptParse.ParserInfo Flags flagsParser = OptParse.info (OptParse.helper <*> parseFlags) (OptParse.fullDesc <> OptParse.footerDoc (Just $ OptParse.string footerStr)) where footerStr = unlines [ Env.helpDoc environmentParser, "", "Configuration file format:", T.unpack (renderColouredSchemaViaCodec @Configuration) ] data Flags = Flags { flagConfigFile :: !(Maybe FilePath), flagDbFile :: !(Maybe FilePath), flagLogLevel :: !(Maybe LogLevel) } deriving (Show, Eq, Generic) parseFlags :: OptParse.Parser Flags parseFlags = Flags <$> optional ( strOption ( mconcat [ long "config-file", help "Path to an altenative config file", metavar "FILEPATH" ] ) ) <*> optional ( strOption ( mconcat [ long "database", help "Path to the database", metavar "FILEPATH" ] ) ) <*> optional ( option auto ( mconcat [ long "log-level", help "Minimal severity level for log messages", metavar "LOG_LEVEL" ] ) )
200dc728da28f5d901aacb3c1c19daf01bd8dfd281dc5a397b2594853e218c50
psholtz/MIT-SICP
exercise-03.scm
;; ;; Working definitions ;; (define (variable? exp) (symbol? exp)) (define (make-variable var) var) (define (variable-name exp) exp) (define (or? exp) (and (pair? exp) (eq? (car exp) 'or))) (define (make-or exp1 exp2) (list 'or exp1 exp2)) (define (or-first exp) (cadr exp)) (define (or-second exp) (caddr exp)) (define (and? exp) (and (pair? exp) (eq? (car exp) 'and))) (define (make-and exp1 exp2) (list 'and exp1 exp2)) (define (and-first exp) (cadr exp)) (define (and-second exp) (caddr exp)) ;; ;; Previous exercises ;; (define (not? exp) (and (pair? exp) (eq? (car exp) 'not))) (define (make-not exp) (list 'not exp)) (define (not-first exp) (cadr exp)) ;; Exercise 3 ;; ;; Given a boolean expression and a set of variable assignments, evaluate the expression to decide whether the result if # t or # f. Assume that you have a procedure ( variable - value ;; name environment), which takes a variable and and a list of values and returns the value ;; assigned to the variable, if a binding for it exists, or throws an error if no binding is ;; found. ;; ;; As with some of the other examples in Chapter 2 , it 's easier to get a handle on these exercies if we peek ahead to Chapter 3 and use the " table " structure defined there , to ;; use for our symbol bindings and execution environment. ;; ;; We'll import the relevant table definitions: ;; (define (assoc key records) (cond ((null? records) false) ((equal? key (caar records)) (car records)) (else (assoc key (cdr records))))) (define (lookup key table) (let ((record (assoc key (cdr table)))) (if record (cdr record) false))) (define (insert! key value table) (let ((record (assoc key (cdr table)))) (if record (set-cdr! record value) (set-cdr! table (cons (cons key value) (cdr table)))))) (define (make-table) (list '*table*)) ;; ;; Let's define a symbol table to use as our environment: ;; (define env (make-table)) ;; ;; And let's put some variable bindings in there: ;; (insert! 'x 1 env) (insert! 'y 2 env) (insert! 'z 3 env) (insert! 'key 'value env) env = = > ( * table * ( key . value ) ( z . 3 ) ( y . 2 ) ( x . 1 ) ) ;; ;; We can now define the "variable-value" procedure: ;; (define (variable-value name environment) (define (variable-value-iter working) (if (null? working) (error "VARIABLE-VALUE: no binding for variable: " name) (let ((value (car working))) (if (equal? name (car value)) (cdr value) (variable-value-iter (cdr working)))))) (variable-value-iter (cdr environment))) ;; ;; Unit tests: ;; (variable-value 'x env) = = > 1 (variable-value 'y env) = = > 2 (variable-value 'z env) = = > 3 (variable-value 'key env) ;; ==> value (variable-value 'value env) ;; ==> #[error] ;; To get the examples of this exercise to work , let 's bind three variable symbols ;; "a", "b" and "c" to true, true and false: ;; (insert! 'a #t env) (insert! 'b #t env) (insert! 'c #f env) (variable-value 'a env) ;; ==> #t (variable-value 'b env) ;; ==> #t (variable-value 'c env) ;; ==> #f ;; ;; Now to answer the question: ;; (define (eval-boolean exp env) ;; return the boolean value of the argument symbol (define (boolean-value sym) (if (variable? sym) (variable-value sym env) (not (or (null? sym) (eq? sym #f))))) ;; evaluate the boolean expression (cond ((or? exp) (let ((first (or-first exp)) (second (or-second exp))) (or (boolean-value first) (boolean-value second)))) ((and? exp) (let ((first (and-first exp)) (second (and-second exp))) (and (boolean-value first) (boolean-value second)))) ((not? exp) (let ((first (not-first exp))) (not (boolean-value first)))) (else (error "EVAL - expression is not a boolean expression: " exp)))) ;; ;; Let's test it using the boolean expression constructors we have defined: ;; (eval-boolean (make-and 'a 'b) env) ;; ==> #t (eval-boolean (make-or 'a 'b) env) ;; ==> #t (eval-boolean (make-not 'a) env) ;; ==> #f (eval-boolean (make-not 'b) env) ;; ==> #f (eval-boolean (make-and 'a 'c) env) ;; ==> #f (eval-boolean (make-or 'a 'c) env) ;; ==> #t (eval-boolean (make-and 'a 'd) env) ;; ==> #[error] (eval-boolean (make-and 'a #t) env) ;; ==> #t (eval-boolean (make-and 'a 1) env) ;; ==> #t (eval-boolean (make-and 'a 0) env) ;; ==> #t ;; Note that "0" is not false in Scheme! (if 0 1 2) = = > 1 ;; i.e., "0" evaluates to "true" (eval-boolean (make-and 'a #f) env) ;; ==> #f (eval-boolean (make-and 'a '()) env) ;; ==> #f
null
https://raw.githubusercontent.com/psholtz/MIT-SICP/01e9b722ac5008e26f386624849117ca8fa80906/Recitations-F2007/Recitation-08/mit-scheme/exercise-03.scm
scheme
Working definitions Previous exercises Given a boolean expression and a set of variable assignments, evaluate the expression to name environment), which takes a variable and and a list of values and returns the value assigned to the variable, if a binding for it exists, or throws an error if no binding is found. use for our symbol bindings and execution environment. We'll import the relevant table definitions: Let's define a symbol table to use as our environment: And let's put some variable bindings in there: We can now define the "variable-value" procedure: Unit tests: ==> value ==> #[error] "a", "b" and "c" to true, true and false: ==> #t ==> #t ==> #f Now to answer the question: return the boolean value of the argument symbol evaluate the boolean expression Let's test it using the boolean expression constructors we have defined: ==> #t ==> #t ==> #f ==> #f ==> #f ==> #t ==> #[error] ==> #t ==> #t ==> #t Note that "0" is not false in Scheme! i.e., "0" evaluates to "true" ==> #f ==> #f
(define (variable? exp) (symbol? exp)) (define (make-variable var) var) (define (variable-name exp) exp) (define (or? exp) (and (pair? exp) (eq? (car exp) 'or))) (define (make-or exp1 exp2) (list 'or exp1 exp2)) (define (or-first exp) (cadr exp)) (define (or-second exp) (caddr exp)) (define (and? exp) (and (pair? exp) (eq? (car exp) 'and))) (define (make-and exp1 exp2) (list 'and exp1 exp2)) (define (and-first exp) (cadr exp)) (define (and-second exp) (caddr exp)) (define (not? exp) (and (pair? exp) (eq? (car exp) 'not))) (define (make-not exp) (list 'not exp)) (define (not-first exp) (cadr exp)) Exercise 3 decide whether the result if # t or # f. Assume that you have a procedure ( variable - value As with some of the other examples in Chapter 2 , it 's easier to get a handle on these exercies if we peek ahead to Chapter 3 and use the " table " structure defined there , to (define (assoc key records) (cond ((null? records) false) ((equal? key (caar records)) (car records)) (else (assoc key (cdr records))))) (define (lookup key table) (let ((record (assoc key (cdr table)))) (if record (cdr record) false))) (define (insert! key value table) (let ((record (assoc key (cdr table)))) (if record (set-cdr! record value) (set-cdr! table (cons (cons key value) (cdr table)))))) (define (make-table) (list '*table*)) (define env (make-table)) (insert! 'x 1 env) (insert! 'y 2 env) (insert! 'z 3 env) (insert! 'key 'value env) env = = > ( * table * ( key . value ) ( z . 3 ) ( y . 2 ) ( x . 1 ) ) (define (variable-value name environment) (define (variable-value-iter working) (if (null? working) (error "VARIABLE-VALUE: no binding for variable: " name) (let ((value (car working))) (if (equal? name (car value)) (cdr value) (variable-value-iter (cdr working)))))) (variable-value-iter (cdr environment))) (variable-value 'x env) = = > 1 (variable-value 'y env) = = > 2 (variable-value 'z env) = = > 3 (variable-value 'key env) (variable-value 'value env) To get the examples of this exercise to work , let 's bind three variable symbols (insert! 'a #t env) (insert! 'b #t env) (insert! 'c #f env) (variable-value 'a env) (variable-value 'b env) (variable-value 'c env) (define (eval-boolean exp env) (define (boolean-value sym) (if (variable? sym) (variable-value sym env) (not (or (null? sym) (eq? sym #f))))) (cond ((or? exp) (let ((first (or-first exp)) (second (or-second exp))) (or (boolean-value first) (boolean-value second)))) ((and? exp) (let ((first (and-first exp)) (second (and-second exp))) (and (boolean-value first) (boolean-value second)))) ((not? exp) (let ((first (not-first exp))) (not (boolean-value first)))) (else (error "EVAL - expression is not a boolean expression: " exp)))) (eval-boolean (make-and 'a 'b) env) (eval-boolean (make-or 'a 'b) env) (eval-boolean (make-not 'a) env) (eval-boolean (make-not 'b) env) (eval-boolean (make-and 'a 'c) env) (eval-boolean (make-or 'a 'c) env) (eval-boolean (make-and 'a 'd) env) (eval-boolean (make-and 'a #t) env) (eval-boolean (make-and 'a 1) env) (eval-boolean (make-and 'a 0) env) (if 0 1 2) = = > 1 (eval-boolean (make-and 'a #f) env) (eval-boolean (make-and 'a '()) env)
dc11b5436be52747eae18518a5486f9a0d712c7e041e6b33203ed3be03da13f4
davexunit/guile-2d
actions.scm
;;; guile-2d Copyright ( C ) 2013 > ;;; ;;; Guile-2d 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. ;;; ;;; Guile-2d is distributed in the hope that it will be useful, but ;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;;; Lesser General Public License for more details. ;;; You should have received a copy of the GNU Lesser General Public ;;; License along with this program. If not, see ;;; </>. ;;; Commentary: ;; ;; Actions are composable procedures that perform an operation over a ;; period of game time. ;; ;;; Code: (define-module (2d actions) #:use-module (srfi srfi-9) #:use-module (srfi srfi-1) #:use-module (2d agenda) #:use-module (2d coroutine) #:export (<action> make-action action? null-action null-action? action-duration action-proc perform-action schedule-action action-cons action-list action-parallel action-repeat idle lerp)) ;;; ;;; Action Procedures ;;; ;; Actions encapsulate a procedure that performs an action and the ;; duration of the action in game ticks. (define-record-type <action> (%make-action proc duration) action? (duration action-duration) (proc action-proc)) (define (make-action proc duration) "Create a new action object that takes DURATION updates to complete. PROC is a procedure that takes a value in the range [0, 1] as its only argument. An error is thrown if DURATION is 0." (if (zero? duration) (throw 'action-duration-zero) (%make-action proc duration))) (define (step-action action t) "Apply ACTION procedure to the time delta, T." ((action-proc action) t)) (define (perform-action action) "Execute ACTION. `perform-action` must be called from within a coroutine, as it yields back to the agenda after each step." (let ((duration (action-duration action))) (define (step time) (if (= duration time) (step-action action 1) (begin (step-action action (/ time duration)) (wait) (step (1+ time))))) (step 1))) (define (schedule-action action) "Schedules a coroutine in the current agenda that will perform ACTION on the next update." (agenda-schedule (colambda () (perform-action action)))) (define (action-cons a1 a2) "Return an action that performs A1 first, followed by A2." (define (real-cons) (let* ((duration (+ (action-duration a1) (action-duration a2))) (t1 (/ (action-duration a1) duration)) (t2 (/ (action-duration a2) duration))) (make-action (lambda (t) (if (> t t1) (step-action a2 (/ (- t t1) t2)) (step-action a1 (/ t t1)))) duration))) ;; a2 can be #f, if this is the last action-cons of an action-list. (if a2 (real-cons) a1)) (define (action-list . actions) "Return an action that performs every action in the list ACTIONS." (if (null? actions) #f (action-cons (car actions) (apply action-list (cdr actions))))) (define (action-parallel . actions) "Perform every action in the list ACTIONS in parallel." (let ((max-duration (reduce max 0 (map action-duration actions)))) ;; Add idle action to each action to fill the time ;; difference between the action's duration and the ;; max action duration. (define (fill-action action) (if (= (action-duration action) max-duration) action (action-cons action (idle (- max-duration (action-duration action)))))) (let ((filled-actions (map fill-action actions))) (make-action (lambda (t) (for-each (lambda (a) (step-action a t)) filled-actions)) max-duration)))) (define (action-repeat n action) "Return an action that will perform ACTION N times." (apply action-list (make-list n action))) ;;; ;;; Simple Actions ;;; (define (idle duration) "Return an action that does nothing." (make-action (lambda (t) #t) duration)) (define (lerp proc start end duration) "Linearly interpolate a number from START to END that takes DURATION updates. Apply PROC to the linearly interpolated at each step." (let ((delta (- end start))) (make-action (lambda (t) (if (= t 1) (proc end) (proc (+ start (* delta t))))) duration)))
null
https://raw.githubusercontent.com/davexunit/guile-2d/83d9dfab5b04a337565cb2798847b15e4fbd7786/2d/actions.scm
scheme
guile-2d Guile-2d is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as License, or (at your option) any later version. Guile-2d 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. License along with this program. If not, see </>. Commentary: Actions are composable procedures that perform an operation over a period of game time. Code: Action Procedures Actions encapsulate a procedure that performs an action and the duration of the action in game ticks. a2 can be #f, if this is the last action-cons of an action-list. Add idle action to each action to fill the time difference between the action's duration and the max action duration. Simple Actions
Copyright ( C ) 2013 > published by the Free Software Foundation , either version 3 of the You should have received a copy of the GNU Lesser General Public (define-module (2d actions) #:use-module (srfi srfi-9) #:use-module (srfi srfi-1) #:use-module (2d agenda) #:use-module (2d coroutine) #:export (<action> make-action action? null-action null-action? action-duration action-proc perform-action schedule-action action-cons action-list action-parallel action-repeat idle lerp)) (define-record-type <action> (%make-action proc duration) action? (duration action-duration) (proc action-proc)) (define (make-action proc duration) "Create a new action object that takes DURATION updates to complete. PROC is a procedure that takes a value in the range [0, 1] as its only argument. An error is thrown if DURATION is 0." (if (zero? duration) (throw 'action-duration-zero) (%make-action proc duration))) (define (step-action action t) "Apply ACTION procedure to the time delta, T." ((action-proc action) t)) (define (perform-action action) "Execute ACTION. `perform-action` must be called from within a coroutine, as it yields back to the agenda after each step." (let ((duration (action-duration action))) (define (step time) (if (= duration time) (step-action action 1) (begin (step-action action (/ time duration)) (wait) (step (1+ time))))) (step 1))) (define (schedule-action action) "Schedules a coroutine in the current agenda that will perform ACTION on the next update." (agenda-schedule (colambda () (perform-action action)))) (define (action-cons a1 a2) "Return an action that performs A1 first, followed by A2." (define (real-cons) (let* ((duration (+ (action-duration a1) (action-duration a2))) (t1 (/ (action-duration a1) duration)) (t2 (/ (action-duration a2) duration))) (make-action (lambda (t) (if (> t t1) (step-action a2 (/ (- t t1) t2)) (step-action a1 (/ t t1)))) duration))) (if a2 (real-cons) a1)) (define (action-list . actions) "Return an action that performs every action in the list ACTIONS." (if (null? actions) #f (action-cons (car actions) (apply action-list (cdr actions))))) (define (action-parallel . actions) "Perform every action in the list ACTIONS in parallel." (let ((max-duration (reduce max 0 (map action-duration actions)))) (define (fill-action action) (if (= (action-duration action) max-duration) action (action-cons action (idle (- max-duration (action-duration action)))))) (let ((filled-actions (map fill-action actions))) (make-action (lambda (t) (for-each (lambda (a) (step-action a t)) filled-actions)) max-duration)))) (define (action-repeat n action) "Return an action that will perform ACTION N times." (apply action-list (make-list n action))) (define (idle duration) "Return an action that does nothing." (make-action (lambda (t) #t) duration)) (define (lerp proc start end duration) "Linearly interpolate a number from START to END that takes DURATION updates. Apply PROC to the linearly interpolated at each step." (let ((delta (- end start))) (make-action (lambda (t) (if (= t 1) (proc end) (proc (+ start (* delta t))))) duration)))
a9b2a4d4de2eecb15187e844fe540ef6df7831c238abc6d8634a32bac65b2ab6
NorfairKing/hastory
Utils.hs
{-# LANGUAGE OverloadedStrings #-} module Hastory.API.Utils ( doCountsWith, dataBaseSpec, runDb, ) where import Conduit (MonadUnliftIO) import Control.Monad.IO.Class (liftIO) import Control.Monad.Logger (runNoLoggingT) import Control.Monad.Reader (ReaderT) import Data.HashMap.Lazy (HashMap) import qualified Data.HashMap.Lazy as HM import Data.Hashable (Hashable) import Database.Persist.Sqlite (SqlBackend, runMigrationSilent, runSqlConn, withSqliteConn) import Hastory.Data.Client.DB (migrateAll) import Test.Hspec (ActionWith, Spec, SpecWith, around) doCountsWith :: (Eq b, Hashable b) => (a -> b) -> (a -> Double) -> [a] -> HashMap b Double doCountsWith conv func = foldl go HM.empty where go hm k = HM.alter a (conv k) hm where a Nothing = Just 1 a (Just d) = Just $ d + func k dataBaseSpec :: SpecWith SqlBackend -> Spec dataBaseSpec = around withDatabase withDatabase :: ActionWith SqlBackend -> IO () withDatabase func = runNoLoggingT $ withSqliteConn ":memory:" $ \conn -> do _ <- runDb conn (runMigrationSilent migrateAll) liftIO $ func conn runDb :: (MonadUnliftIO m) => SqlBackend -> ReaderT SqlBackend m a -> m a runDb = flip runSqlConn
null
https://raw.githubusercontent.com/NorfairKing/hastory/35abbc79155bc7c5a0f6e0f3618c8b8bcd3889a1/hastory-api/src/Hastory/API/Utils.hs
haskell
# LANGUAGE OverloadedStrings #
module Hastory.API.Utils ( doCountsWith, dataBaseSpec, runDb, ) where import Conduit (MonadUnliftIO) import Control.Monad.IO.Class (liftIO) import Control.Monad.Logger (runNoLoggingT) import Control.Monad.Reader (ReaderT) import Data.HashMap.Lazy (HashMap) import qualified Data.HashMap.Lazy as HM import Data.Hashable (Hashable) import Database.Persist.Sqlite (SqlBackend, runMigrationSilent, runSqlConn, withSqliteConn) import Hastory.Data.Client.DB (migrateAll) import Test.Hspec (ActionWith, Spec, SpecWith, around) doCountsWith :: (Eq b, Hashable b) => (a -> b) -> (a -> Double) -> [a] -> HashMap b Double doCountsWith conv func = foldl go HM.empty where go hm k = HM.alter a (conv k) hm where a Nothing = Just 1 a (Just d) = Just $ d + func k dataBaseSpec :: SpecWith SqlBackend -> Spec dataBaseSpec = around withDatabase withDatabase :: ActionWith SqlBackend -> IO () withDatabase func = runNoLoggingT $ withSqliteConn ":memory:" $ \conn -> do _ <- runDb conn (runMigrationSilent migrateAll) liftIO $ func conn runDb :: (MonadUnliftIO m) => SqlBackend -> ReaderT SqlBackend m a -> m a runDb = flip runSqlConn
dec0be09e93356c8844473927c21fb8d33b2e351250a2502c7193ad27adc6eec
RefactoringTools/HaRe
TiPretty.hs
module TiPretty where import TiTypes hiding (forall') import TiNames import TiKinds import PrettyPrint import SpecialNames import PrettySymbols(forall',imp,el) import Syntax(hsTyVar) import HsDeclPretty(ppFunDeps,ppContext) import MUtils(( # ),ifM) instance (TypeId i,ValueId i) => Printable (Scheme i) where ppi (Forall [] [] qt) = ppi qt ppi (Forall aks vks qt@(_:=>t)) = ppIfUnicode (ppForall varnames) (ppForall asciinames) where ppForall names = sep [forall' <+> vs'' <+> ".",letNest qt''] where qt'' = ifM (debugInfo # getPPEnv) (ppi qt) (ppi qt') vs'' = ifM (debugInfo # getPPEnv) (asep (k vs)) (asep (k vs')) where k vs = map ppKinded (zipTyped (vs:>:ks)) vs' = map snd s qt' = apply (S s) qt s = [(v,hsTyVar (ltvar name) `asTypeOf` t) | (v,name) <- zip vs names] vs:>:ks = unzipTyped (aks++vks) -- hmm n = length aks asep avs = if null as then fsep vs else braces (fsep as)<+>fsep vs where (as,vs) = splitAt n avs Infinite supplies of variables names : varnames = map single [alpha..omega]++asciinames where alpha='\x03b1'; omega='\x03c9' asciinames = map single letters++[a:show n|n<-[1..],a<-letters] single x = [x] letters = ['a'..'z'] ppKinded (x:>:k) = if k==kstar then ppi x else parens (x<>el<>k) instance (IsSpecialName i,Printable i,Printable t) => Printable (Qual i t) where ppi ([]:=>t) = ppi t ppi (ps:=>t) = sep [ppiFTuple ps <+> imp, letNest t] instance (Printable x,Printable t) => Printable (Typing x t) where ppi (x:>:t) = sep [wrap x <+> el,letNest t] ppiList xts = vcat xts instance (ValueId i,TypeId i) => Printable (TypeInfo i) where ppi i = case i of Data -> ppi "data" -- <+> o Newtype -> ppi "newtype" -- <+> o Class super ps fundeps methods -> "class" <+> sep [ppi (ppContext super<+>"_"<+>fsep (map ppKinded ps)), ppFunDeps fundeps, ppi "where", letNest methods] Synonym ps t -> "type" <+> appv (p:ps) <+> "=" <+> letNest t Tyvar -> ppi "type variable" where p = localVal "_" appv = asType . appT . map tyvar asType = id :: Type i -> Type i instance (IsSpecialName i,Printable i) => Printable (Subst i) where ppi (S s) = ppi s
null
https://raw.githubusercontent.com/RefactoringTools/HaRe/ef5dee64c38fb104e6e5676095946279fbce381c/old/tools/base/TI/TiPretty.hs
haskell
hmm <+> o <+> o
module TiPretty where import TiTypes hiding (forall') import TiNames import TiKinds import PrettyPrint import SpecialNames import PrettySymbols(forall',imp,el) import Syntax(hsTyVar) import HsDeclPretty(ppFunDeps,ppContext) import MUtils(( # ),ifM) instance (TypeId i,ValueId i) => Printable (Scheme i) where ppi (Forall [] [] qt) = ppi qt ppi (Forall aks vks qt@(_:=>t)) = ppIfUnicode (ppForall varnames) (ppForall asciinames) where ppForall names = sep [forall' <+> vs'' <+> ".",letNest qt''] where qt'' = ifM (debugInfo # getPPEnv) (ppi qt) (ppi qt') vs'' = ifM (debugInfo # getPPEnv) (asep (k vs)) (asep (k vs')) where k vs = map ppKinded (zipTyped (vs:>:ks)) vs' = map snd s qt' = apply (S s) qt s = [(v,hsTyVar (ltvar name) `asTypeOf` t) | (v,name) <- zip vs names] n = length aks asep avs = if null as then fsep vs else braces (fsep as)<+>fsep vs where (as,vs) = splitAt n avs Infinite supplies of variables names : varnames = map single [alpha..omega]++asciinames where alpha='\x03b1'; omega='\x03c9' asciinames = map single letters++[a:show n|n<-[1..],a<-letters] single x = [x] letters = ['a'..'z'] ppKinded (x:>:k) = if k==kstar then ppi x else parens (x<>el<>k) instance (IsSpecialName i,Printable i,Printable t) => Printable (Qual i t) where ppi ([]:=>t) = ppi t ppi (ps:=>t) = sep [ppiFTuple ps <+> imp, letNest t] instance (Printable x,Printable t) => Printable (Typing x t) where ppi (x:>:t) = sep [wrap x <+> el,letNest t] ppiList xts = vcat xts instance (ValueId i,TypeId i) => Printable (TypeInfo i) where ppi i = case i of Class super ps fundeps methods -> "class" <+> sep [ppi (ppContext super<+>"_"<+>fsep (map ppKinded ps)), ppFunDeps fundeps, ppi "where", letNest methods] Synonym ps t -> "type" <+> appv (p:ps) <+> "=" <+> letNest t Tyvar -> ppi "type variable" where p = localVal "_" appv = asType . appT . map tyvar asType = id :: Type i -> Type i instance (IsSpecialName i,Printable i) => Printable (Subst i) where ppi (S s) = ppi s
7268c2cb27267c67d873341a735b66d823c20b9164cd02f3cd9c84be98a3184b
fyquah/hardcaml_zprize
bls12_377_util.ml
open Core module Extended_euclidean = Field_ops_lib.Extended_euclidean type z = Z.t [@@deriving equal] let sexp_of_z z = Sexp.Atom ("0x" ^ Z.format "x" z) let half x = Z.div x (Z.of_int 2) let p = Field_ops_model.Modulus.m let modulo_mult a b = Z.(a * b mod p) let modulo_neg a = Z.((neg a + p) mod p) let modulo_inverse x = let x = Z.( mod ) x p in let { Extended_euclidean.coef_x; coef_y = _; gcd } = Extended_euclidean.extended_euclidean ~x ~y:p in if not (Z.equal gcd Z.one) then raise_s [%message "Error computing modulo inverse!"]; let ret = Z.(coef_x mod p) in let ret = if Z.lt ret Z.zero then Z.(ret + p) else ret in if not (Z.gt ret (Z.of_int (-1)) && Z.lt ret p) then raise_s [%message (ret : z) (p : z)]; Z.((ret + p) mod p) ;; let modulo_sub a b = Z.((a - b + p) mod p) let modulo_add a b = Z.((a + b) mod p) let modulo_div a b = Z.((modulo_mult a (modulo_inverse b) + p) mod p) let rec modulo_pow base exponent = if Z.equal exponent Z.zero then Z.one else if Z.equal exponent Z.one then base else ( let is_exponent_odd = Z.equal Z.one (Z.( land ) Z.one exponent) in let partial = modulo_pow base (half exponent) in if is_exponent_odd then modulo_mult (modulo_mult partial partial) base else modulo_mult partial partial) ;; let modulo_square_root a = snd (Option.value_exn (Toneli_shank.tonelli_shank ~p a)) let generate_z ~lo_incl ~hi_incl = Quickcheck.Generator.map ~f:Bigint.to_zarith_bigint (Bigint.gen_incl (Bigint.of_zarith_bigint lo_incl) (Bigint.of_zarith_bigint hi_incl)) ;; let random_z = let random = Splittable_random.State.create Random.State.default in fun ~lo_incl ~hi_incl -> let generate = generate_z ~lo_incl ~hi_incl in Quickcheck.Generator.generate ~size:1 ~random generate ;; module Modulo_ops = struct include Z let ( * ) = modulo_mult let ( - ) = modulo_sub let ( + ) = modulo_add let ( / ) = modulo_div end let cubed x = let open Modulo_ops in x * x * x ;; let square x = let open Modulo_ops in x * x ;;
null
https://raw.githubusercontent.com/fyquah/hardcaml_zprize/7eb1bd214908fa801781db33287eaf12691715f8/libs/twisted_edwards/model/bls12_377_util.ml
ocaml
open Core module Extended_euclidean = Field_ops_lib.Extended_euclidean type z = Z.t [@@deriving equal] let sexp_of_z z = Sexp.Atom ("0x" ^ Z.format "x" z) let half x = Z.div x (Z.of_int 2) let p = Field_ops_model.Modulus.m let modulo_mult a b = Z.(a * b mod p) let modulo_neg a = Z.((neg a + p) mod p) let modulo_inverse x = let x = Z.( mod ) x p in let { Extended_euclidean.coef_x; coef_y = _; gcd } = Extended_euclidean.extended_euclidean ~x ~y:p in if not (Z.equal gcd Z.one) then raise_s [%message "Error computing modulo inverse!"]; let ret = Z.(coef_x mod p) in let ret = if Z.lt ret Z.zero then Z.(ret + p) else ret in if not (Z.gt ret (Z.of_int (-1)) && Z.lt ret p) then raise_s [%message (ret : z) (p : z)]; Z.((ret + p) mod p) ;; let modulo_sub a b = Z.((a - b + p) mod p) let modulo_add a b = Z.((a + b) mod p) let modulo_div a b = Z.((modulo_mult a (modulo_inverse b) + p) mod p) let rec modulo_pow base exponent = if Z.equal exponent Z.zero then Z.one else if Z.equal exponent Z.one then base else ( let is_exponent_odd = Z.equal Z.one (Z.( land ) Z.one exponent) in let partial = modulo_pow base (half exponent) in if is_exponent_odd then modulo_mult (modulo_mult partial partial) base else modulo_mult partial partial) ;; let modulo_square_root a = snd (Option.value_exn (Toneli_shank.tonelli_shank ~p a)) let generate_z ~lo_incl ~hi_incl = Quickcheck.Generator.map ~f:Bigint.to_zarith_bigint (Bigint.gen_incl (Bigint.of_zarith_bigint lo_incl) (Bigint.of_zarith_bigint hi_incl)) ;; let random_z = let random = Splittable_random.State.create Random.State.default in fun ~lo_incl ~hi_incl -> let generate = generate_z ~lo_incl ~hi_incl in Quickcheck.Generator.generate ~size:1 ~random generate ;; module Modulo_ops = struct include Z let ( * ) = modulo_mult let ( - ) = modulo_sub let ( + ) = modulo_add let ( / ) = modulo_div end let cubed x = let open Modulo_ops in x * x * x ;; let square x = let open Modulo_ops in x * x ;;
e60c8e2bf8ddacf4932642ed7cbafc136061720bc58cef5f0b959fe81dec86fb
commercialhaskell/stack
Main.hs
import StackTest main :: IO () main = do stack ["clean"] stack ["build"]
null
https://raw.githubusercontent.com/commercialhaskell/stack/255cd830627870cdef34b5e54d670ef07882523e/test/integration/tests/3787-internal-libs-with-no-main-lib/Main.hs
haskell
import StackTest main :: IO () main = do stack ["clean"] stack ["build"]
6f7b41d428fcc7c96ed6c1f0c0ac39459dcbf3be1e73173ab5d285556e56ba31
circuithub/nix-buildkite
Main.hs
# language BlockArguments # # language LambdaCase # # language NamedFieldPuns # {-# language OverloadedStrings #-} module Main ( main ) where -- algebraic-graphs import Algebra.Graph.AdjacencyMap ( AdjacencyMap, edge, empty, hasVertex, overlay, overlays ) import Algebra.Graph.AdjacencyMap.Algorithm ( reachable ) -- aeson import Data.Aeson ( Value(..), (.=), decodeStrict, encode, object ) attoparsec import Data.Attoparsec.Text ( parseOnly ) -- base import Data.Char import Data.Foldable ( fold ) import Data.Function ( (&) ) import Data.Functor ( (<&>) ) import Data.Maybe ( fromMaybe, listToMaybe ) import Data.Traversable ( for ) import qualified Prelude import Prelude hiding ( getContents, lines, readFile, words ) import System.Environment ( getArgs ) -- bytestring import qualified Data.ByteString.Lazy -- containers import qualified Data.Map as Map -- filepath import System.FilePath -- nix-derivation import Nix.Derivation -- process import System.Process -- text import Data.Text ( Text, pack, unpack ) import Data.Text.Encoding import Data.Text.IO ( readFile ) -- unordered-containers import qualified Data.HashMap.Strict as HashMap main :: IO () main = do jobsExpr <- fromMaybe "./jobs.nix" . listToMaybe <$> getArgs -- Run nix-instantiate on the jobs expression to instantiate .drvs for all -- things that may need to be built. inputDrvPaths <- Prelude.lines <$> readProcess "nix-instantiate" [ jobsExpr ] "" -- Build a 'Map StorePath DrvPath'. This will serve the role of ' nix - store --query --deriver ' , but nix - store wo n't work because itself -- has no mapping from store paths to derivations yet. storePathToDrv <- fold <$> for inputDrvPaths \drvPath -> fmap (parseOnly parseDerivation) (readFile drvPath) <&> foldMap \Derivation{ outputs } -> outputs & foldMap \DerivationOutput{ path } -> Map.singleton path drvPath Re - run nix - instantiate , but with --eval --strict --json . This should give -- us back a JSON object that is a tree with leaves that are store paths. jsonString <- readProcess "nix-instantiate" [ "--eval", "--strict", "--json", jobsExpr ] "" json <- decodeStrict (encodeUtf8 (pack jsonString)) & maybe (fail "Could not parse JSON") return let drvs :: [(Text, FilePath)] drvs = go "" json where go prefix (Object kv) = HashMap.foldlWithKey' (\x k v -> x <> go (prefix <> "." <> k) v) [] kv go prefix (String storePath) = foldMap pure $ (,) <$> pure prefix <*> Map.lookup (unpack storePath) storePathToDrv go _ _ = mempty g <- foldr (\(_, drv) m -> m >>= \g -> add g drv) (pure empty) drvs let steps = map (uncurry step) drvs where step label drvPath = object [ "label" .= tail (unpack label) , "command" .= String (pack ("nix-store -r" <> drvPath)) , "key" .= stepify drvPath , "depends_on" .= dependencies ] where dependencies = map stepify $ filter (`elem` map snd drvs) $ drop 1 $ reachable drvPath g Data.ByteString.Lazy.putStr $ encode $ object [ "steps" .= steps ] stepify :: String -> String stepify = map replace . takeBaseName where replace x | isAlphaNum x = x replace '/' = '/' replace '-' = '-' replace _ = '_' add :: AdjacencyMap FilePath -> FilePath -> IO (AdjacencyMap FilePath) add g drvPath = if hasVertex drvPath g then return g else fmap (parseOnly parseDerivation) (readFile drvPath) >>= \case Left _ -> return g Right Derivation{ inputDrvs } -> do deps <- foldr (\dep m -> m >>= \g' -> add g' dep) (pure g) (Map.keys inputDrvs) let g' = overlays (edge drvPath <$> Map.keys inputDrvs) return $ overlay deps g'
null
https://raw.githubusercontent.com/circuithub/nix-buildkite/aa2a2a38acfa6ff9319825e92cd73284e7ea4d95/exe-nix-buildkite/Main.hs
haskell
# language OverloadedStrings # algebraic-graphs aeson base bytestring containers filepath nix-derivation process text unordered-containers Run nix-instantiate on the jobs expression to instantiate .drvs for all things that may need to be built. Build a 'Map StorePath DrvPath'. This will serve the role of query --deriver ' , but nix - store wo n't work because itself has no mapping from store paths to derivations yet. eval --strict --json . This should give us back a JSON object that is a tree with leaves that are store paths.
# language BlockArguments # # language LambdaCase # # language NamedFieldPuns # module Main ( main ) where import Algebra.Graph.AdjacencyMap ( AdjacencyMap, edge, empty, hasVertex, overlay, overlays ) import Algebra.Graph.AdjacencyMap.Algorithm ( reachable ) import Data.Aeson ( Value(..), (.=), decodeStrict, encode, object ) attoparsec import Data.Attoparsec.Text ( parseOnly ) import Data.Char import Data.Foldable ( fold ) import Data.Function ( (&) ) import Data.Functor ( (<&>) ) import Data.Maybe ( fromMaybe, listToMaybe ) import Data.Traversable ( for ) import qualified Prelude import Prelude hiding ( getContents, lines, readFile, words ) import System.Environment ( getArgs ) import qualified Data.ByteString.Lazy import qualified Data.Map as Map import System.FilePath import Nix.Derivation import System.Process import Data.Text ( Text, pack, unpack ) import Data.Text.Encoding import Data.Text.IO ( readFile ) import qualified Data.HashMap.Strict as HashMap main :: IO () main = do jobsExpr <- fromMaybe "./jobs.nix" . listToMaybe <$> getArgs inputDrvPaths <- Prelude.lines <$> readProcess "nix-instantiate" [ jobsExpr ] "" storePathToDrv <- fold <$> for inputDrvPaths \drvPath -> fmap (parseOnly parseDerivation) (readFile drvPath) <&> foldMap \Derivation{ outputs } -> outputs & foldMap \DerivationOutput{ path } -> Map.singleton path drvPath jsonString <- readProcess "nix-instantiate" [ "--eval", "--strict", "--json", jobsExpr ] "" json <- decodeStrict (encodeUtf8 (pack jsonString)) & maybe (fail "Could not parse JSON") return let drvs :: [(Text, FilePath)] drvs = go "" json where go prefix (Object kv) = HashMap.foldlWithKey' (\x k v -> x <> go (prefix <> "." <> k) v) [] kv go prefix (String storePath) = foldMap pure $ (,) <$> pure prefix <*> Map.lookup (unpack storePath) storePathToDrv go _ _ = mempty g <- foldr (\(_, drv) m -> m >>= \g -> add g drv) (pure empty) drvs let steps = map (uncurry step) drvs where step label drvPath = object [ "label" .= tail (unpack label) , "command" .= String (pack ("nix-store -r" <> drvPath)) , "key" .= stepify drvPath , "depends_on" .= dependencies ] where dependencies = map stepify $ filter (`elem` map snd drvs) $ drop 1 $ reachable drvPath g Data.ByteString.Lazy.putStr $ encode $ object [ "steps" .= steps ] stepify :: String -> String stepify = map replace . takeBaseName where replace x | isAlphaNum x = x replace '/' = '/' replace '-' = '-' replace _ = '_' add :: AdjacencyMap FilePath -> FilePath -> IO (AdjacencyMap FilePath) add g drvPath = if hasVertex drvPath g then return g else fmap (parseOnly parseDerivation) (readFile drvPath) >>= \case Left _ -> return g Right Derivation{ inputDrvs } -> do deps <- foldr (\dep m -> m >>= \g' -> add g' dep) (pure g) (Map.keys inputDrvs) let g' = overlays (edge drvPath <$> Map.keys inputDrvs) return $ overlay deps g'
3c8d48988a5fccb008d384d317004248eb9a01d3155fe83834abdcf168c9d1ea
tweag/ormolu
Annotation.hs
# LANGUAGE LambdaCase # {-# LANGUAGE OverloadedStrings #-} module Ormolu.Printer.Meat.Declaration.Annotation ( p_annDecl, ) where import GHC.Hs import Ormolu.Printer.Combinators import Ormolu.Printer.Meat.Common import Ormolu.Printer.Meat.Declaration.Value p_annDecl :: AnnDecl GhcPs -> R () p_annDecl (HsAnnotation _ _ annProv expr) = pragma "ANN" . inci $ do p_annProv annProv breakpoint located expr p_hsExpr p_annProv :: AnnProvenance GhcPs -> R () p_annProv = \case ValueAnnProvenance name -> p_rdrName name TypeAnnProvenance name -> txt "type" >> space >> p_rdrName name ModuleAnnProvenance -> txt "module"
null
https://raw.githubusercontent.com/tweag/ormolu/11cda4c653bc67a6ff579531a441410626ab3bbd/src/Ormolu/Printer/Meat/Declaration/Annotation.hs
haskell
# LANGUAGE OverloadedStrings #
# LANGUAGE LambdaCase # module Ormolu.Printer.Meat.Declaration.Annotation ( p_annDecl, ) where import GHC.Hs import Ormolu.Printer.Combinators import Ormolu.Printer.Meat.Common import Ormolu.Printer.Meat.Declaration.Value p_annDecl :: AnnDecl GhcPs -> R () p_annDecl (HsAnnotation _ _ annProv expr) = pragma "ANN" . inci $ do p_annProv annProv breakpoint located expr p_hsExpr p_annProv :: AnnProvenance GhcPs -> R () p_annProv = \case ValueAnnProvenance name -> p_rdrName name TypeAnnProvenance name -> txt "type" >> space >> p_rdrName name ModuleAnnProvenance -> txt "module"
8ef5d4615b68da5bbae116112850dfaa7b4188141be02d054c2f6607d8f25b21
hexlet-basics/exercises-racket
index.rkt
#lang racket #| BEGIN |# (displayln (- 128 37)) #| END |#
null
https://raw.githubusercontent.com/hexlet-basics/exercises-racket/ae3a45453584de1e5082c841178d4e43dd47e08a/modules/10-basics/18-lists-as-a-tree/index.rkt
racket
BEGIN END
#lang racket (displayln (- 128 37))
6afe875cefb01261f53035e0f709cfb5c500ba018a04656c8c0401696b606986
tommaisey/aeon
ugen.scm
(define a2k (lambda (input) (mk-ugen (list "A2K" kr (list input) nil 1 nil nil)))) (define apf (lambda (input freq radius) (mk-ugen (list "APF" (list 0) (list input freq radius) nil 1 nil nil)))) (define allpass-c (lambda (input maxdelaytime delaytime decaytime) (mk-ugen (list "AllpassC" (list 0) (list input maxdelaytime delaytime decaytime) nil 1 nil nil)))) (define allpass-l (lambda (input maxdelaytime delaytime decaytime) (mk-ugen (list "AllpassL" (list 0) (list input maxdelaytime delaytime decaytime) nil 1 nil nil)))) (define allpass-n (lambda (input maxdelaytime delaytime decaytime) (mk-ugen (list "AllpassN" (list 0) (list input maxdelaytime delaytime decaytime) nil 1 nil nil)))) (define amp-comp (lambda (rt freq root exp_) (mk-ugen (list "AmpComp" rt (list freq root exp_) nil 1 nil nil)))) (define amp-comp-a (lambda (rt freq root minAmp rootAmp) (mk-ugen (list "AmpCompA" rt (list freq root minAmp rootAmp) nil 1 nil nil)))) (define amplitude (lambda (rt input attackTime releaseTime) (mk-ugen (list "Amplitude" rt (list input attackTime releaseTime) nil 1 nil nil)))) (define audio-control (lambda (rt values) (mk-ugen (list "AudioControl" rt (list values) nil 1 nil nil)))) (define b-all-pass (lambda (input freq rq) (mk-ugen (list "BAllPass" (list 0) (list input freq rq) nil 1 nil nil)))) (define b-band-pass (lambda (input freq bw) (mk-ugen (list "BBandPass" (list 0) (list input freq bw) nil 1 nil nil)))) (define b-band-stop (lambda (input freq bw) (mk-ugen (list "BBandStop" (list 0) (list input freq bw) nil 1 nil nil)))) (define b-hi-pass (lambda (input freq rq) (mk-ugen (list "BHiPass" (list 0) (list input freq rq) nil 1 nil nil)))) (define b-hi-pass4 (lambda (input freq rq) (mk-ugen (list "BHiPass4" (list 0) (list input freq rq) nil 1 nil nil)))) (define b-hi-shelf (lambda (input freq rs db) (mk-ugen (list "BHiShelf" (list 0) (list input freq rs db) nil 1 nil nil)))) (define b-low-pass (lambda (input freq rq) (mk-ugen (list "BLowPass" (list 0) (list input freq rq) nil 1 nil nil)))) (define b-low-pass4 (lambda (input freq rq) (mk-ugen (list "BLowPass4" (list 0) (list input freq rq) nil 1 nil nil)))) (define b-low-shelf (lambda (input freq rs db) (mk-ugen (list "BLowShelf" (list 0) (list input freq rs db) nil 1 nil nil)))) (define bpf (lambda (input freq rq) (mk-ugen (list "BPF" (list 0) (list input freq rq) nil 1 nil nil)))) (define bpz2 (lambda (input) (mk-ugen (list "BPZ2" (list 0) (list input) nil 1 nil nil)))) (define b-peak-eq (lambda (input freq rq db) (mk-ugen (list "BPeakEQ" (list 0) (list input freq rq db) nil 1 nil nil)))) (define brf (lambda (input freq rq) (mk-ugen (list "BRF" (list 0) (list input freq rq) nil 1 nil nil)))) (define brz2 (lambda (input) (mk-ugen (list "BRZ2" (list 0) (list input) nil 1 nil nil)))) (define balance2 (lambda (rt left right pos level) (mk-ugen (list "Balance2" rt (list left right pos level) nil 2 nil nil)))) (define ball (lambda (rt input g damp friction) (mk-ugen (list "Ball" rt (list input g damp friction) nil 1 nil nil)))) (define beat-track (lambda (rt chain lock) (mk-ugen (list "BeatTrack" rt (list chain lock) nil 1 nil nil)))) (define beat-track2 (lambda (rt busindex numfeatures windowsize phaseaccuracy lock weightingscheme) (mk-ugen (list "BeatTrack2" rt (list busindex numfeatures windowsize phaseaccuracy lock weightingscheme) nil 6 nil nil)))) (define bi-pan-b2 (lambda (rt inA inB azimuth gain) (mk-ugen (list "BiPanB2" rt (list inA inB azimuth gain) nil 3 nil nil)))) (define binary-op-ugen (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 nil nil)))) (define blip (lambda (rt freq numharm) (mk-ugen (list "Blip" rt (list freq numharm) nil 1 nil nil)))) (define block-size (lambda (rt) (mk-ugen (list "BlockSize" rt nil nil 1 nil nil)))) (define brown-noise (lambda (rt) (mk-ugen (list "BrownNoise" rt nil nil 1 nil (incr-uid 1))))) (define buf-allpass-c (lambda (rt buf input delaytime decaytime) (mk-ugen (list "BufAllpassC" rt (list buf input delaytime decaytime) nil 1 nil nil)))) (define buf-allpass-l (lambda (rt buf input delaytime decaytime) (mk-ugen (list "BufAllpassL" rt (list buf input delaytime decaytime) nil 1 nil nil)))) (define buf-allpass-n (lambda (rt buf input delaytime decaytime) (mk-ugen (list "BufAllpassN" rt (list buf input delaytime decaytime) nil 1 nil nil)))) (define buf-channels (lambda (rt bufnum) (mk-ugen (list "BufChannels" rt (list bufnum) nil 1 nil nil)))) (define buf-comb-c (lambda (rt buf input delaytime decaytime) (mk-ugen (list "BufCombC" rt (list buf input delaytime decaytime) nil 1 nil nil)))) (define buf-comb-l (lambda (rt buf input delaytime decaytime) (mk-ugen (list "BufCombL" rt (list buf input delaytime decaytime) nil 1 nil nil)))) (define buf-comb-n (lambda (rt buf input delaytime decaytime) (mk-ugen (list "BufCombN" rt (list buf input delaytime decaytime) nil 1 nil nil)))) (define buf-delay-c (lambda (rt buf input delaytime) (mk-ugen (list "BufDelayC" rt (list buf input delaytime) nil 1 nil nil)))) (define buf-delay-l (lambda (rt buf input delaytime) (mk-ugen (list "BufDelayL" rt (list buf input delaytime) nil 1 nil nil)))) (define buf-delay-n (lambda (rt buf input delaytime) (mk-ugen (list "BufDelayN" rt (list buf input delaytime) nil 1 nil nil)))) (define buf-dur (lambda (rt bufnum) (mk-ugen (list "BufDur" rt (list bufnum) nil 1 nil nil)))) (define buf-frames (lambda (rt bufnum) (mk-ugen (list "BufFrames" rt (list bufnum) nil 1 nil nil)))) (define buf-rate-scale (lambda (rt bufnum) (mk-ugen (list "BufRateScale" rt (list bufnum) nil 1 nil nil)))) (define buf-rd (lambda (nc rt bufnum phase loop interpolation) (mk-ugen (list "BufRd" rt (list bufnum phase loop interpolation) nil nc nil nil)))) (define buf-sample-rate (lambda (rt bufnum) (mk-ugen (list "BufSampleRate" rt (list bufnum) nil 1 nil nil)))) (define buf-samples (lambda (rt bufnum) (mk-ugen (list "BufSamples" rt (list bufnum) nil 1 nil nil)))) (define buf-wr (lambda (bufnum phase loop inputArray) (mk-ugen (list "BufWr" (list 3) (list bufnum phase loop) inputArray 1 nil nil)))) (define c-osc (lambda (rt bufnum freq beats) (mk-ugen (list "COsc" rt (list bufnum freq beats) nil 1 nil nil)))) (define check-bad-values (lambda (input id_ post) (mk-ugen (list "CheckBadValues" (list 0) (list input id_ post) nil 1 nil nil)))) (define clip (lambda (input lo hi) (mk-ugen (list "Clip" (list 0) (list input lo hi) nil 1 nil nil)))) (define clip-noise (lambda (rt) (mk-ugen (list "ClipNoise" rt nil nil 1 nil (incr-uid 1))))) (define coin-gate (lambda (prob input) (mk-ugen (list "CoinGate" (list 1) (list prob input) nil 1 nil (incr-uid 1))))) (define comb-c (lambda (input maxdelaytime delaytime decaytime) (mk-ugen (list "CombC" (list 0) (list input maxdelaytime delaytime decaytime) nil 1 nil nil)))) (define comb-l (lambda (input maxdelaytime delaytime decaytime) (mk-ugen (list "CombL" (list 0) (list input maxdelaytime delaytime decaytime) nil 1 nil nil)))) (define comb-n (lambda (input maxdelaytime delaytime decaytime) (mk-ugen (list "CombN" (list 0) (list input maxdelaytime delaytime decaytime) nil 1 nil nil)))) (define compander (lambda (input control_ thresh slopeBelow slopeAbove clampTime relaxTime) (mk-ugen (list "Compander" (list 0) (list input control_ thresh slopeBelow slopeAbove clampTime relaxTime) nil 1 nil nil)))) (define compander-d (lambda (rt input thresh slopeBelow slopeAbove clampTime relaxTime) (mk-ugen (list "CompanderD" rt (list input thresh slopeBelow slopeAbove clampTime relaxTime) nil 1 nil nil)))) (define control-dur (mk-ugen (list "ControlDur" ir nil nil 1 nil nil))) (define control-rate (mk-ugen (list "ControlRate" ir nil nil 1 nil nil))) (define convolution (lambda (rt input kernel framesize) (mk-ugen (list "Convolution" rt (list input kernel framesize) nil 1 nil nil)))) (define convolution2 (lambda (rt input kernel trigger framesize) (mk-ugen (list "Convolution2" rt (list input kernel trigger framesize) nil 1 nil nil)))) (define convolution2l (lambda (rt input kernel trigger framesize crossfade) (mk-ugen (list "Convolution2L" rt (list input kernel trigger framesize crossfade) nil 1 nil nil)))) (define convolution3 (lambda (rt input kernel trigger framesize) (mk-ugen (list "Convolution3" rt (list input kernel trigger framesize) nil 1 nil nil)))) (define crackle (lambda (rt chaosParam) (mk-ugen (list "Crackle" rt (list chaosParam) nil 1 nil nil)))) (define cusp-l (lambda (rt freq a b xi) (mk-ugen (list "CuspL" rt (list freq a b xi) nil 1 nil nil)))) (define cusp-n (lambda (rt freq a b xi) (mk-ugen (list "CuspN" rt (list freq a b xi) nil 1 nil nil)))) (define dc (lambda (rt input) (mk-ugen (list "DC" rt (list input) nil 1 nil nil)))) (define dbrown (lambda (length_ lo hi step) (mk-ugen (list "Dbrown" dr (list length_ lo hi step) nil 1 nil (incr-uid 1))))) (define dbufrd (lambda (bufnum phase loop) (mk-ugen (list "Dbufrd" dr (list bufnum phase loop) nil 1 nil (incr-uid 1))))) (define dbufwr (lambda (bufnum phase loop input) (mk-ugen (list "Dbufwr" dr (list bufnum phase loop input) nil 1 nil (incr-uid 1))))) (define decay (lambda (input decayTime) (mk-ugen (list "Decay" (list 0) (list input decayTime) nil 1 nil nil)))) (define decay2 (lambda (input attackTime decayTime) (mk-ugen (list "Decay2" (list 0) (list input attackTime decayTime) nil 1 nil nil)))) (define decode-b2 (lambda (nc rt w x y orientation) (mk-ugen (list "DecodeB2" rt (list w x y orientation) nil nc nil nil)))) (define degree-to-key (lambda (bufnum input octave) (mk-ugen (list "DegreeToKey" (list 1) (list bufnum input octave) nil 1 nil nil)))) (define del-tap-rd (lambda (buffer phase delTime interp) (mk-ugen (list "DelTapRd" (list 1) (list buffer phase delTime interp) nil 1 nil nil)))) (define del-tap-wr (lambda (buffer input) (mk-ugen (list "DelTapWr" (list 1) (list buffer input) nil 1 nil nil)))) (define delay1 (lambda (input) (mk-ugen (list "Delay1" (list 0) (list input) nil 1 nil nil)))) (define delay2 (lambda (input) (mk-ugen (list "Delay2" (list 0) (list input) nil 1 nil nil)))) (define delay-c (lambda (input maxdelaytime delaytime) (mk-ugen (list "DelayC" (list 0) (list input maxdelaytime delaytime) nil 1 nil nil)))) (define delay-l (lambda (input maxdelaytime delaytime) (mk-ugen (list "DelayL" (list 0) (list input maxdelaytime delaytime) nil 1 nil nil)))) (define delay-n (lambda (input maxdelaytime delaytime) (mk-ugen (list "DelayN" (list 0) (list input maxdelaytime delaytime) nil 1 nil nil)))) (define demand (lambda (trig reset demandUGens) (mk-ugen (list "Demand" (list 0) (list trig reset) demandUGens (length (mce-channels demandUGens)) nil nil)))) (define demand-env-gen (lambda (rt level dur shape curve gate reset levelScale levelBias timeScale doneAction) (mk-ugen (list "DemandEnvGen" rt (list level dur shape curve gate reset levelScale levelBias timeScale doneAction) nil 1 nil nil)))) (define detect-index (lambda (bufnum input) (mk-ugen (list "DetectIndex" (list 1) (list bufnum input) nil 1 nil nil)))) (define detect-silence (lambda (input amp time doneAction) (mk-ugen (list "DetectSilence" (list 0) (list input amp time doneAction) nil 1 nil nil)))) (define dgeom (lambda (length_ start grow) (mk-ugen (list "Dgeom" dr (list length_ start grow) nil 1 nil (incr-uid 1))))) (define dibrown (lambda (length_ lo hi step) (mk-ugen (list "Dibrown" dr (list length_ lo hi step) nil 1 nil (incr-uid 1))))) (define disk-in (lambda (nc bufnum loop) (mk-ugen (list "DiskIn" ar (list bufnum loop) nil nc nil nil)))) (define disk-out (lambda (bufnum input) (mk-ugen (list "DiskOut" ar (list bufnum) input 1 nil nil)))) (define diwhite (lambda (length_ lo hi) (mk-ugen (list "Diwhite" dr (list length_ lo hi) nil 1 nil (incr-uid 1))))) (define donce (lambda (input) (mk-ugen (list "Donce" dr (list input) nil 1 nil (incr-uid 1))))) (define done (lambda (rt src) (mk-ugen (list "Done" rt (list src) nil 1 nil nil)))) (define dpoll (lambda (input label_ run trigid) (mk-ugen (list "Dpoll" dr (list input label_ run trigid) nil 1 nil (incr-uid 1))))) (define drand (lambda (repeats list_) (mk-ugen (list "Drand" dr (list repeats) list_ 1 nil (incr-uid 1))))) (define dreset (lambda (input reset) (mk-ugen (list "Dreset" dr (list input reset) nil 1 nil (incr-uid 1))))) (define dseq (lambda (repeats list_) (mk-ugen (list "Dseq" dr (list repeats) list_ 1 nil (incr-uid 1))))) (define dser (lambda (repeats list_) (mk-ugen (list "Dser" dr (list repeats) list_ 1 nil (incr-uid 1))))) (define dseries (lambda (length_ start step) (mk-ugen (list "Dseries" dr (list length_ start step) nil 1 nil (incr-uid 1))))) (define dshuf (lambda (repeats list_) (mk-ugen (list "Dshuf" dr (list repeats) list_ 1 nil (incr-uid 1))))) (define dstutter (lambda (n input) (mk-ugen (list "Dstutter" dr (list n input) nil 1 nil (incr-uid 1))))) (define dswitch (lambda (index list_) (mk-ugen (list "Dswitch" dr (list index) list_ 1 nil (incr-uid 1))))) (define dswitch1 (lambda (index list_) (mk-ugen (list "Dswitch1" dr (list index) list_ 1 nil (incr-uid 1))))) (define dunique (lambda (source maxBufferSize protected) (mk-ugen (list "Dunique" dr (list source maxBufferSize protected) nil 1 nil (incr-uid 1))))) (define dust (lambda (rt density) (mk-ugen (list "Dust" rt (list density) nil 1 nil (incr-uid 1))))) (define dust2 (lambda (rt density) (mk-ugen (list "Dust2" rt (list density) nil 1 nil (incr-uid 1))))) (define dust-r (lambda (rt iot_min iot_max) (mk-ugen (list "DustR" rt (list iot_min iot_max) nil 1 nil nil)))) (define duty (lambda (rt dur reset doneAction level) (mk-ugen (list "Duty" rt (list dur reset doneAction level) nil 1 nil nil)))) (define dwhite (lambda (length_ lo hi) (mk-ugen (list "Dwhite" dr (list length_ lo hi) nil 1 nil (incr-uid 1))))) (define dwrand (lambda (repeats weights list_) (mk-ugen (list "Dwrand" dr (list repeats weights) list_ 1 nil (incr-uid 1))))) (define dxrand (lambda (repeats list_) (mk-ugen (list "Dxrand" dr (list repeats) list_ 1 nil (incr-uid 1))))) (define env-gen (lambda (rt gate levelScale levelBias timeScale doneAction envelope_) (mk-ugen (list "EnvGen" rt (list gate levelScale levelBias timeScale doneAction) envelope_ 1 nil nil)))) (define exp-rand (lambda (lo hi) (mk-ugen (list "ExpRand" (list 0 1) (list lo hi) nil 1 nil (incr-uid 1))))) (define fb-sine-c (lambda (rt freq im fb a c xi yi) (mk-ugen (list "FBSineC" rt (list freq im fb a c xi yi) nil 1 nil nil)))) (define fb-sine-l (lambda (rt freq im fb a c xi yi) (mk-ugen (list "FBSineL" rt (list freq im fb a c xi yi) nil 1 nil nil)))) (define fb-sine-n (lambda (rt freq im fb a c xi yi) (mk-ugen (list "FBSineN" rt (list freq im fb a c xi yi) nil 1 nil nil)))) (define fft (lambda (buffer input hop wintype active winsize) (mk-ugen (list "FFT" kr (list buffer input hop wintype active winsize) nil 1 nil nil)))) (define fos (lambda (input a0 a1 b1) (mk-ugen (list "FOS" (list 0) (list input a0 a1 b1) nil 1 nil nil)))) (define f-sin-osc (lambda (rt freq iphase) (mk-ugen (list "FSinOsc" rt (list freq iphase) nil 1 nil nil)))) (define fold (lambda (input lo hi) (mk-ugen (list "Fold" (list 0) (list input lo hi) nil 1 nil nil)))) (define formant (lambda (rt fundfreq formfreq bwfreq) (mk-ugen (list "Formant" rt (list fundfreq formfreq bwfreq) nil 1 nil nil)))) (define formlet (lambda (input freq attacktime decaytime) (mk-ugen (list "Formlet" (list 0) (list input freq attacktime decaytime) nil 1 nil nil)))) (define free (lambda (trig id_) (mk-ugen (list "Free" (list 0) (list trig id_) nil 1 nil nil)))) (define free-self (lambda (input) (mk-ugen (list "FreeSelf" kr (list input) nil 1 nil nil)))) (define free-self-when-done (lambda (rt src) (mk-ugen (list "FreeSelfWhenDone" rt (list src) nil 1 nil nil)))) (define free-verb (lambda (input mix room damp) (mk-ugen (list "FreeVerb" (list 0) (list input mix room damp) nil 1 nil nil)))) (define free-verb2 (lambda (input in2 mix room damp) (mk-ugen (list "FreeVerb2" (list 0) (list input in2 mix room damp) nil 2 nil nil)))) (define freq-shift (lambda (rt input freq phase) (mk-ugen (list "FreqShift" rt (list input freq phase) nil 1 nil nil)))) (define g-verb (lambda (input roomsize revtime damping inputbw spread drylevel earlyreflevel taillevel maxroomsize) (mk-ugen (list "GVerb" (list 0) (list input roomsize revtime damping inputbw spread drylevel earlyreflevel taillevel maxroomsize) nil 2 nil nil)))) (define gate (lambda (input trig) (mk-ugen (list "Gate" (list 0) (list input trig) nil 1 nil nil)))) (define gbman-l (lambda (rt freq xi yi) (mk-ugen (list "GbmanL" rt (list freq xi yi) nil 1 nil nil)))) (define gbman-n (lambda (rt freq xi yi) (mk-ugen (list "GbmanN" rt (list freq xi yi) nil 1 nil nil)))) (define gendy1 (lambda (rt ampdist durdist adparam ddparam minfreq maxfreq ampscale durscale initCPs knum) (mk-ugen (list "Gendy1" rt (list ampdist durdist adparam ddparam minfreq maxfreq ampscale durscale initCPs knum) nil 1 nil (incr-uid 1))))) (define gendy2 (lambda (rt ampdist durdist adparam ddparam minfreq maxfreq ampscale durscale initCPs knum a c) (mk-ugen (list "Gendy2" rt (list ampdist durdist adparam ddparam minfreq maxfreq ampscale durscale initCPs knum a c) nil 1 nil (incr-uid 1))))) (define gendy3 (lambda (rt ampdist durdist adparam ddparam freq ampscale durscale initCPs knum) (mk-ugen (list "Gendy3" rt (list ampdist durdist adparam ddparam freq ampscale durscale initCPs knum) nil 1 nil (incr-uid 1))))) (define grain-buf (lambda (nc trigger dur sndbuf rate_ pos interp pan envbufnum maxGrains) (mk-ugen (list "GrainBuf" ar (list trigger dur sndbuf rate_ pos interp pan envbufnum maxGrains) nil nc nil nil)))) (define grain-fm (lambda (nc trigger dur carfreq modfreq index pan envbufnum maxGrains) (mk-ugen (list "GrainFM" ar (list trigger dur carfreq modfreq index pan envbufnum maxGrains) nil nc nil nil)))) (define grain-in (lambda (nc trigger dur input pan envbufnum maxGrains) (mk-ugen (list "GrainIn" ar (list trigger dur input pan envbufnum maxGrains) nil nc nil nil)))) (define grain-sin (lambda (nc trigger dur freq pan envbufnum maxGrains) (mk-ugen (list "GrainSin" ar (list trigger dur freq pan envbufnum maxGrains) nil nc nil nil)))) (define gray-noise (lambda (rt) (mk-ugen (list "GrayNoise" rt nil nil 1 nil (incr-uid 1))))) (define hpf (lambda (input freq) (mk-ugen (list "HPF" (list 0) (list input freq) nil 1 nil nil)))) (define hpz1 (lambda (input) (mk-ugen (list "HPZ1" (list 0) (list input) nil 1 nil nil)))) (define hpz2 (lambda (input) (mk-ugen (list "HPZ2" (list 0) (list input) nil 1 nil nil)))) (define hasher (lambda (input) (mk-ugen (list "Hasher" (list 0) (list input) nil 1 nil nil)))) (define henon-c (lambda (rt freq a b x0 x1) (mk-ugen (list "HenonC" rt (list freq a b x0 x1) nil 1 nil nil)))) (define henon-l (lambda (rt freq a b x0 x1) (mk-ugen (list "HenonL" rt (list freq a b x0 x1) nil 1 nil nil)))) (define henon-n (lambda (rt freq a b x0 x1) (mk-ugen (list "HenonN" rt (list freq a b x0 x1) nil 1 nil nil)))) (define hilbert (lambda (input) (mk-ugen (list "Hilbert" (list 0) (list input) nil 2 nil nil)))) (define hilbert-fir (lambda (rt input buffer) (mk-ugen (list "HilbertFIR" rt (list input buffer) nil 2 nil nil)))) (define i-env-gen (lambda (rt index envelope_) (mk-ugen (list "IEnvGen" rt (list index) envelope_ 1 nil nil)))) (define ifft (lambda (buffer wintype winsize) (mk-ugen (list "IFFT" ar (list buffer wintype winsize) nil 1 nil nil)))) (define i-rand (lambda (lo hi) (mk-ugen (list "IRand" ir (list lo hi) nil 1 nil (incr-uid 1))))) (define impulse (lambda (rt freq phase) (mk-ugen (list "Impulse" rt (list freq phase) nil 1 nil nil)))) (define in (lambda (nc rt bus) (mk-ugen (list "In" rt (list bus) nil nc nil nil)))) (define in-feedback (lambda (nc bus) (mk-ugen (list "InFeedback" ar (list bus) nil nc nil nil)))) (define in-range (lambda (input lo hi) (mk-ugen (list "InRange" (list 0) (list input lo hi) nil 1 nil nil)))) (define in-rect (lambda (rt x y rect) (mk-ugen (list "InRect" rt (list x y rect) nil 1 nil nil)))) (define in-trig (lambda (nc rt bus) (mk-ugen (list "InTrig" rt (list bus) nil nc nil nil)))) (define index (lambda (bufnum input) (mk-ugen (list "Index" (list 1) (list bufnum input) nil 1 nil nil)))) (define index-in-between (lambda (rt bufnum input) (mk-ugen (list "IndexInBetween" rt (list bufnum input) nil 1 nil nil)))) (define index-l (lambda (rt bufnum input) (mk-ugen (list "IndexL" rt (list bufnum input) nil 1 nil nil)))) (define info-ugen-base (lambda (rt) (mk-ugen (list "InfoUGenBase" rt nil nil 1 nil nil)))) (define integrator (lambda (input coef) (mk-ugen (list "Integrator" (list 0) (list input coef) nil 1 nil nil)))) (define k2a (lambda (input) (mk-ugen (list "K2A" ar (list input) nil 1 nil nil)))) (define key-state (lambda (rt keycode minval maxval lag) (mk-ugen (list "KeyState" rt (list keycode minval maxval lag) nil 1 nil nil)))) (define key-track (lambda (rt chain keydecay chromaleak) (mk-ugen (list "KeyTrack" rt (list chain keydecay chromaleak) nil 1 nil nil)))) (define klang (lambda (rt freqscale freqoffset specificationsArrayRef) (mk-ugen (list "Klang" rt (list freqscale freqoffset) specificationsArrayRef 1 nil nil)))) (define klank (lambda (input freqscale freqoffset decayscale specificationsArrayRef) (mk-ugen (list "Klank" (list 0) (list input freqscale freqoffset decayscale) specificationsArrayRef 1 nil nil)))) (define lf-clip-noise (lambda (rt freq) (mk-ugen (list "LFClipNoise" rt (list freq) nil 1 nil (incr-uid 1))))) (define lf-cub (lambda (rt freq iphase) (mk-ugen (list "LFCub" rt (list freq iphase) nil 1 nil nil)))) (define lfd-clip-noise (lambda (rt freq) (mk-ugen (list "LFDClipNoise" rt (list freq) nil 1 nil (incr-uid 1))))) (define lfd-noise0 (lambda (rt freq) (mk-ugen (list "LFDNoise0" rt (list freq) nil 1 nil (incr-uid 1))))) (define lfd-noise1 (lambda (rt freq) (mk-ugen (list "LFDNoise1" rt (list freq) nil 1 nil (incr-uid 1))))) (define lfd-noise3 (lambda (rt freq) (mk-ugen (list "LFDNoise3" rt (list freq) nil 1 nil (incr-uid 1))))) (define lf-gauss (lambda (rt duration width iphase loop doneAction) (mk-ugen (list "LFGauss" rt (list duration width iphase loop doneAction) nil 1 nil nil)))) (define lf-noise0 (lambda (rt freq) (mk-ugen (list "LFNoise0" rt (list freq) nil 1 nil (incr-uid 1))))) (define lf-noise1 (lambda (rt freq) (mk-ugen (list "LFNoise1" rt (list freq) nil 1 nil (incr-uid 1))))) (define lf-noise2 (lambda (rt freq) (mk-ugen (list "LFNoise2" rt (list freq) nil 1 nil (incr-uid 1))))) (define lf-par (lambda (rt freq iphase) (mk-ugen (list "LFPar" rt (list freq iphase) nil 1 nil nil)))) (define lf-pulse (lambda (rt freq iphase width) (mk-ugen (list "LFPulse" rt (list freq iphase width) nil 1 nil nil)))) (define lf-saw (lambda (rt freq iphase) (mk-ugen (list "LFSaw" rt (list freq iphase) nil 1 nil nil)))) (define lf-tri (lambda (rt freq iphase) (mk-ugen (list "LFTri" rt (list freq iphase) nil 1 nil nil)))) (define lpf (lambda (input freq) (mk-ugen (list "LPF" (list 0) (list input freq) nil 1 nil nil)))) (define lpz1 (lambda (input) (mk-ugen (list "LPZ1" (list 0) (list input) nil 1 nil nil)))) (define lpz2 (lambda (input) (mk-ugen (list "LPZ2" (list 0) (list input) nil 1 nil nil)))) (define lag (lambda (input lagTime) (mk-ugen (list "Lag" (list 0) (list input lagTime) nil 1 nil nil)))) (define lag2 (lambda (input lagTime) (mk-ugen (list "Lag2" (list 0) (list input lagTime) nil 1 nil nil)))) (define lag2ud (lambda (input lagTimeU lagTimeD) (mk-ugen (list "Lag2UD" (list 0) (list input lagTimeU lagTimeD) nil 1 nil nil)))) (define lag3 (lambda (input lagTime) (mk-ugen (list "Lag3" (list 0) (list input lagTime) nil 1 nil nil)))) (define lag3ud (lambda (input lagTimeU lagTimeD) (mk-ugen (list "Lag3UD" (list 0) (list input lagTimeU lagTimeD) nil 1 nil nil)))) (define lag-control (lambda (rt values lags) (mk-ugen (list "LagControl" rt (list values lags) nil 1 nil nil)))) (define lag-in (lambda (nc rt bus lag) (mk-ugen (list "LagIn" rt (list bus lag) nil nc nil nil)))) (define lag-ud (lambda (input lagTimeU lagTimeD) (mk-ugen (list "LagUD" (list 0) (list input lagTimeU lagTimeD) nil 1 nil nil)))) (define last-value (lambda (input diff) (mk-ugen (list "LastValue" (list 0) (list input diff) nil 1 nil nil)))) (define latch (lambda (input trig) (mk-ugen (list "Latch" (list 0) (list input trig) nil 1 nil nil)))) (define latoocarfian-c (lambda (rt freq a b c d xi yi) (mk-ugen (list "LatoocarfianC" rt (list freq a b c d xi yi) nil 1 nil nil)))) (define latoocarfian-l (lambda (rt freq a b c d xi yi) (mk-ugen (list "LatoocarfianL" rt (list freq a b c d xi yi) nil 1 nil nil)))) (define latoocarfian-n (lambda (rt freq a b c d xi yi) (mk-ugen (list "LatoocarfianN" rt (list freq a b c d xi yi) nil 1 nil nil)))) (define leak-dc (lambda (input coef) (mk-ugen (list "LeakDC" (list 0) (list input coef) nil 1 nil nil)))) (define least-change (lambda (rt a b) (mk-ugen (list "LeastChange" rt (list a b) nil 1 nil nil)))) (define limiter (lambda (input level dur) (mk-ugen (list "Limiter" (list 0) (list input level dur) nil 1 nil nil)))) (define lin-cong-c (lambda (rt freq a c m xi) (mk-ugen (list "LinCongC" rt (list freq a c m xi) nil 1 nil nil)))) (define lin-cong-l (lambda (rt freq a c m xi) (mk-ugen (list "LinCongL" rt (list freq a c m xi) nil 1 nil nil)))) (define lin-cong-n (lambda (rt freq a c m xi) (mk-ugen (list "LinCongN" rt (list freq a c m xi) nil 1 nil nil)))) (define lin-exp (lambda (input srclo srchi dstlo dsthi) (mk-ugen (list "LinExp" (list 0) (list input srclo srchi dstlo dsthi) nil 1 nil nil)))) (define lin-pan2 (lambda (input pos level) (mk-ugen (list "LinPan2" (list 0) (list input pos level) nil 2 nil nil)))) (define lin-rand (lambda (lo hi minmax) (mk-ugen (list "LinRand" ir (list lo hi minmax) nil 1 nil (incr-uid 1))))) (define lin-x-fade2 (lambda (inA inB pan level) (mk-ugen (list "LinXFade2" (list 0 1) (list inA inB pan level) nil 1 nil nil)))) (define line (lambda (rt start end dur doneAction) (mk-ugen (list "Line" rt (list start end dur doneAction) nil 1 nil nil)))) (define linen (lambda (gate attackTime susLevel releaseTime doneAction) (mk-ugen (list "Linen" kr (list gate attackTime susLevel releaseTime doneAction) nil 1 nil nil)))) (define local-buf (lambda (numChannels numFrames) (mk-ugen (list "LocalBuf" ir (list numChannels numFrames) nil 1 nil (incr-uid 1))))) (define local-in (lambda (nc rt default_) (mk-ugen (list "LocalIn" rt nil default_ nc nil nil)))) (define local-out (lambda (input) (mk-ugen (list "LocalOut" (list 0) nil input 1 nil nil)))) (define logistic (lambda (rt chaosParam freq init_) (mk-ugen (list "Logistic" rt (list chaosParam freq init_) nil 1 nil nil)))) (define lorenz-l (lambda (rt freq s r b h xi yi zi) (mk-ugen (list "LorenzL" rt (list freq s r b h xi yi zi) nil 1 nil nil)))) (define loudness (lambda (rt chain smask tmask) (mk-ugen (list "Loudness" rt (list chain smask tmask) nil 1 nil nil)))) (define mfcc (lambda (rt chain numcoeff) (mk-ugen (list "MFCC" rt (list chain numcoeff) nil 13 nil nil)))) (define mantissa-mask (lambda (input bits) (mk-ugen (list "MantissaMask" (list 0) (list input bits) nil 1 nil nil)))) (define max-local-bufs (lambda (count) (mk-ugen (list "MaxLocalBufs" ir (list count) nil 1 nil nil)))) (define median (lambda (length_ input) (mk-ugen (list "Median" (list 1) (list length_ input) nil 1 nil nil)))) (define mid-eq (lambda (input freq rq db) (mk-ugen (list "MidEQ" (list 0) (list input freq rq db) nil 1 nil nil)))) (define mod-dif (lambda (rt x y mod_) (mk-ugen (list "ModDif" rt (list x y mod_) nil 1 nil nil)))) (define moog-ff (lambda (input freq gain reset) (mk-ugen (list "MoogFF" (list 0) (list input freq gain reset) nil 1 nil nil)))) (define most-change (lambda (a b) (mk-ugen (list "MostChange" (list 0 1) (list a b) nil 1 nil nil)))) (define mouse-button (lambda (rt minval maxval lag) (mk-ugen (list "MouseButton" rt (list minval maxval lag) nil 1 nil nil)))) (define mouse-x (lambda (rt minval maxval warp lag) (mk-ugen (list "MouseX" rt (list minval maxval warp lag) nil 1 nil nil)))) (define mouse-y (lambda (rt minval maxval warp lag) (mk-ugen (list "MouseY" rt (list minval maxval warp lag) nil 1 nil nil)))) (define n-rand (lambda (lo hi n) (mk-ugen (list "NRand" ir (list lo hi n) nil 1 nil (incr-uid 1))))) (define normalizer (lambda (input level dur) (mk-ugen (list "Normalizer" (list 0) (list input level dur) nil 1 nil nil)))) (define num-audio-buses (mk-ugen (list "NumAudioBuses" ir nil nil 1 nil nil))) (define num-buffers (mk-ugen (list "NumBuffers" ir nil nil 1 nil nil))) (define num-control-buses (mk-ugen (list "NumControlBuses" ir nil nil 1 nil nil))) (define num-input-buses (mk-ugen (list "NumInputBuses" ir nil nil 1 nil nil))) (define num-output-buses (mk-ugen (list "NumOutputBuses" ir nil nil 1 nil nil))) (define num-running-synths (mk-ugen (list "NumRunningSynths" ir nil nil 1 nil nil))) (define offset-out (lambda (bus input) (mk-ugen (list "OffsetOut" (list 1) (list bus) input 1 nil nil)))) (define one-pole (lambda (input coef) (mk-ugen (list "OnePole" (list 0) (list input coef) nil 1 nil nil)))) (define one-zero (lambda (input coef) (mk-ugen (list "OneZero" (list 0) (list input coef) nil 1 nil nil)))) (define onsets (lambda (chain threshold odftype relaxtime floor_ mingap medianspan whtype rawodf) (mk-ugen (list "Onsets" kr (list chain threshold odftype relaxtime floor_ mingap medianspan whtype rawodf) nil 1 nil nil)))) (define osc (lambda (rt bufnum freq phase) (mk-ugen (list "Osc" rt (list bufnum freq phase) nil 1 nil nil)))) (define osc-n (lambda (rt bufnum freq phase) (mk-ugen (list "OscN" rt (list bufnum freq phase) nil 1 nil nil)))) (define out (lambda (bus input) (mk-ugen (list "Out" (list 1) (list bus) input 1 nil nil)))) (define p-sin-grain (lambda (rt freq dur amp) (mk-ugen (list "PSinGrain" rt (list freq dur amp) nil 1 nil nil)))) (define pv-add (lambda (bufferA bufferB) (mk-ugen (list "PV_Add" kr (list bufferA bufferB) nil 1 nil nil)))) (define pv-bin-scramble (lambda (buffer wipe width trig) (mk-ugen (list "PV_BinScramble" kr (list buffer wipe width trig) nil 1 nil (incr-uid 1))))) (define pv-bin-shift (lambda (buffer stretch shift interp) (mk-ugen (list "PV_BinShift" kr (list buffer stretch shift interp) nil 1 nil nil)))) (define pv-bin-wipe (lambda (bufferA bufferB wipe) (mk-ugen (list "PV_BinWipe" kr (list bufferA bufferB wipe) nil 1 nil nil)))) (define pv-brick-wall (lambda (buffer wipe) (mk-ugen (list "PV_BrickWall" kr (list buffer wipe) nil 1 nil nil)))) (define pv-chain-ugen (lambda (maxSize) (mk-ugen (list "PV_ChainUGen" kr (list maxSize) nil 1 nil nil)))) (define pv-conformal-map (lambda (buffer areal aimag) (mk-ugen (list "PV_ConformalMap" kr (list buffer areal aimag) nil 1 nil nil)))) (define pv-conj (lambda (buffer) (mk-ugen (list "PV_Conj" kr (list buffer) nil 1 nil nil)))) (define pv-copy (lambda (bufferA bufferB) (mk-ugen (list "PV_Copy" kr (list bufferA bufferB) nil 1 nil nil)))) (define pv-copy-phase (lambda (bufferA bufferB) (mk-ugen (list "PV_CopyPhase" kr (list bufferA bufferB) nil 1 nil nil)))) (define pv-diffuser (lambda (buffer trig) (mk-ugen (list "PV_Diffuser" kr (list buffer trig) nil 1 nil nil)))) (define pv-div (lambda (bufferA bufferB) (mk-ugen (list "PV_Div" kr (list bufferA bufferB) nil 1 nil nil)))) (define pv-hainsworth-foote (lambda (maxSize) (mk-ugen (list "PV_HainsworthFoote" kr (list maxSize) nil 1 nil nil)))) (define pv-jensen-andersen (lambda (maxSize) (mk-ugen (list "PV_JensenAndersen" kr (list maxSize) nil 1 nil nil)))) (define pv-local-max (lambda (buffer threshold) (mk-ugen (list "PV_LocalMax" kr (list buffer threshold) nil 1 nil nil)))) (define pv-mag-above (lambda (buffer threshold) (mk-ugen (list "PV_MagAbove" kr (list buffer threshold) nil 1 nil nil)))) (define pv-mag-below (lambda (buffer threshold) (mk-ugen (list "PV_MagBelow" kr (list buffer threshold) nil 1 nil nil)))) (define pv-mag-clip (lambda (buffer threshold) (mk-ugen (list "PV_MagClip" kr (list buffer threshold) nil 1 nil nil)))) (define pv-mag-div (lambda (bufferA bufferB zeroed) (mk-ugen (list "PV_MagDiv" kr (list bufferA bufferB zeroed) nil 1 nil nil)))) (define pv-mag-freeze (lambda (buffer freeze) (mk-ugen (list "PV_MagFreeze" kr (list buffer freeze) nil 1 nil nil)))) (define pv-mag-mul (lambda (bufferA bufferB) (mk-ugen (list "PV_MagMul" kr (list bufferA bufferB) nil 1 nil nil)))) (define pv-mag-noise (lambda (buffer) (mk-ugen (list "PV_MagNoise" kr (list buffer) nil 1 nil nil)))) (define pv-mag-shift (lambda (buffer stretch shift) (mk-ugen (list "PV_MagShift" kr (list buffer stretch shift) nil 1 nil nil)))) (define pv-mag-smear (lambda (buffer bins) (mk-ugen (list "PV_MagSmear" kr (list buffer bins) nil 1 nil nil)))) (define pv-mag-squared (lambda (buffer) (mk-ugen (list "PV_MagSquared" kr (list buffer) nil 1 nil nil)))) (define pv-max (lambda (bufferA bufferB) (mk-ugen (list "PV_Max" kr (list bufferA bufferB) nil 1 nil nil)))) (define pv-min (lambda (bufferA bufferB) (mk-ugen (list "PV_Min" kr (list bufferA bufferB) nil 1 nil nil)))) (define pv-mul (lambda (bufferA bufferB) (mk-ugen (list "PV_Mul" kr (list bufferA bufferB) nil 1 nil nil)))) (define pv-phase-shift (lambda (buffer shift integrate) (mk-ugen (list "PV_PhaseShift" kr (list buffer shift integrate) nil 1 nil nil)))) (define pv-phase-shift270 (lambda (buffer) (mk-ugen (list "PV_PhaseShift270" kr (list buffer) nil 1 nil nil)))) (define pv-phase-shift90 (lambda (buffer) (mk-ugen (list "PV_PhaseShift90" kr (list buffer) nil 1 nil nil)))) (define pv-rand-comb (lambda (buffer wipe trig) (mk-ugen (list "PV_RandComb" kr (list buffer wipe trig) nil 1 nil (incr-uid 1))))) (define pv-rand-wipe (lambda (bufferA bufferB wipe trig) (mk-ugen (list "PV_RandWipe" kr (list bufferA bufferB wipe trig) nil 1 nil (incr-uid 1))))) (define pv-rect-comb (lambda (buffer numTeeth phase width) (mk-ugen (list "PV_RectComb" kr (list buffer numTeeth phase width) nil 1 nil nil)))) (define pv-rect-comb2 (lambda (bufferA bufferB numTeeth phase width) (mk-ugen (list "PV_RectComb2" kr (list bufferA bufferB numTeeth phase width) nil 1 nil nil)))) (define pv-split (lambda (bufferA bufferB) (mk-ugen (list "PV_Split" kr (list bufferA bufferB) nil 2 nil nil)))) (define pan2 (lambda (input pos level) (mk-ugen (list "Pan2" (list 0) (list input pos level) nil 2 nil nil)))) (define pan4 (lambda (rt input xpos ypos level) (mk-ugen (list "Pan4" rt (list input xpos ypos level) nil 4 nil nil)))) (define pan-az (lambda (nc input pos level width orientation) (mk-ugen (list "PanAz" (list 0) (list input pos level width orientation) nil nc nil nil)))) (define pan-b (lambda (rt input azimuth elevation gain) (mk-ugen (list "PanB" rt (list input azimuth elevation gain) nil 4 nil nil)))) (define pan-b2 (lambda (rt input azimuth gain) (mk-ugen (list "PanB2" rt (list input azimuth gain) nil 3 nil nil)))) (define part-conv (lambda (input fftsize irbufnum) (mk-ugen (list "PartConv" ar (list input fftsize irbufnum) nil 1 nil nil)))) (define pause (lambda (rt gate id_) (mk-ugen (list "Pause" rt (list gate id_) nil 1 nil nil)))) (define pause-self (lambda (rt input) (mk-ugen (list "PauseSelf" rt (list input) nil 1 nil nil)))) (define pause-self-when-done (lambda (rt src) (mk-ugen (list "PauseSelfWhenDone" rt (list src) nil 1 nil nil)))) (define peak (lambda (input trig) (mk-ugen (list "Peak" (list 0) (list input trig) nil 1 nil nil)))) (define peak-follower (lambda (input decay) (mk-ugen (list "PeakFollower" (list 0) (list input decay) nil 1 nil nil)))) (define phasor (lambda (rt trig rate_ start end resetPos) (mk-ugen (list "Phasor" rt (list trig rate_ start end resetPos) nil 1 nil nil)))) (define pink-noise (lambda (rt) (mk-ugen (list "PinkNoise" rt nil nil 1 nil (incr-uid 1))))) (define pitch (lambda (input initFreq minFreq maxFreq execFreq maxBinsPerOctave median ampThreshold peakThreshold downSample clar) (mk-ugen (list "Pitch" kr (list input initFreq minFreq maxFreq execFreq maxBinsPerOctave median ampThreshold peakThreshold downSample clar) nil 2 nil nil)))) (define pitch-shift (lambda (input windowSize pitchRatio pitchDispersion timeDispersion) (mk-ugen (list "PitchShift" (list 0) (list input windowSize pitchRatio pitchDispersion timeDispersion) nil 1 nil nil)))) (define play-buf (lambda (nc rt bufnum rate_ trigger startPos loop doneAction) (mk-ugen (list "PlayBuf" rt (list bufnum rate_ trigger startPos loop doneAction) nil nc nil nil)))) (define pluck (lambda (input trig maxdelaytime delaytime decaytime coef) (mk-ugen (list "Pluck" (list 0) (list input trig maxdelaytime delaytime decaytime coef) nil 1 nil nil)))) (define poll (lambda (trig input label_ trigid) (mk-ugen (list "Poll" (list 1) (list trig input label_ trigid) nil 1 nil nil)))) (define pulse (lambda (rt freq width) (mk-ugen (list "Pulse" rt (list freq width) nil 1 nil nil)))) (define pulse-count (lambda (trig reset) (mk-ugen (list "PulseCount" (list 0) (list trig reset) nil 1 nil nil)))) (define pulse-divider (lambda (trig div_ start) (mk-ugen (list "PulseDivider" (list 0) (list trig div_ start) nil 1 nil nil)))) (define quad-c (lambda (rt freq a b c xi) (mk-ugen (list "QuadC" rt (list freq a b c xi) nil 1 nil nil)))) (define quad-l (lambda (rt freq a b c xi) (mk-ugen (list "QuadL" rt (list freq a b c xi) nil 1 nil nil)))) (define quad-n (lambda (rt freq a b c xi) (mk-ugen (list "QuadN" rt (list freq a b c xi) nil 1 nil nil)))) (define r-delay-map (lambda (bufnum input dynamic spec) (mk-ugen (list "RDelayMap" (list 1) (list bufnum input dynamic) spec 1 nil nil)))) (define r-delay-set (lambda (rt input spec) (mk-ugen (list "RDelaySet" rt (list input spec) nil 1 nil nil)))) (define r-delay-set-b (lambda (rt bufnum input spec) (mk-ugen (list "RDelaySetB" rt (list bufnum input spec) nil 1 nil nil)))) (define r-freezer (lambda (rt bufnum left right gain increment incrementOffset incrementRandom rightRandom syncPhaseTrigger randomizePhaseTrigger numberOfLoops) (mk-ugen (list "RFreezer" rt (list bufnum left right gain increment incrementOffset incrementRandom rightRandom syncPhaseTrigger randomizePhaseTrigger numberOfLoops) nil 1 nil nil)))) (define rhpf (lambda (input freq rq) (mk-ugen (list "RHPF" (list 0) (list input freq rq) nil 1 nil nil)))) (define rlpf (lambda (input freq rq) (mk-ugen (list "RLPF" (list 0) (list input freq rq) nil 1 nil nil)))) (define r-loop-set (lambda (rt bufnum left right gain increment spec) (mk-ugen (list "RLoopSet" rt (list bufnum left right gain increment spec) nil 1 nil nil)))) (define r-play-trace (lambda (rt bufnum degree rate_ axis) (mk-ugen (list "RPlayTrace" rt (list bufnum degree rate_ axis) nil 1 nil nil)))) (define r-shuffler-b (lambda (bufnum readLocationMinima readLocationMaxima readIncrementMinima readIncrementMaxima durationMinima durationMaxima envelopeAmplitudeMinima envelopeAmplitudeMaxima envelopeShapeMinima envelopeShapeMaxima envelopeSkewMinima envelopeSkewMaxima stereoLocationMinima stereoLocationMaxima interOffsetTimeMinima interOffsetTimeMaxima ftableReadLocationIncrement readIncrementQuanta interOffsetTimeQuanta) (mk-ugen (list "RShufflerB" ar (list bufnum readLocationMinima readLocationMaxima readIncrementMinima readIncrementMaxima durationMinima durationMaxima envelopeAmplitudeMinima envelopeAmplitudeMaxima envelopeShapeMinima envelopeShapeMaxima envelopeSkewMinima envelopeSkewMaxima stereoLocationMinima stereoLocationMaxima interOffsetTimeMinima interOffsetTimeMaxima ftableReadLocationIncrement readIncrementQuanta interOffsetTimeQuanta) nil 2 nil nil)))) (define r-shuffler-l (lambda (rt input fragmentSize maxDelay) (mk-ugen (list "RShufflerL" rt (list input fragmentSize maxDelay) nil 1 nil nil)))) (define r-trace-rd (lambda (rt bufnum degree index axis) (mk-ugen (list "RTraceRd" rt (list bufnum degree index axis) nil 1 nil nil)))) (define r-trace-rd-x (lambda (rt bufnum degree index) (mk-ugen (list "RTraceRdX" rt (list bufnum degree index) nil 1 nil nil)))) (define r-trace-rd-y (lambda (rt bufnum degree index) (mk-ugen (list "RTraceRdY" rt (list bufnum degree index) nil 1 nil nil)))) (define r-trace-rd-z (lambda (rt bufnum degree index) (mk-ugen (list "RTraceRdZ" rt (list bufnum degree index) nil 1 nil nil)))) (define radians-per-sample (mk-ugen (list "RadiansPerSample" ir nil nil 1 nil nil))) (define ramp (lambda (input lagTime) (mk-ugen (list "Ramp" (list 0) (list input lagTime) nil 1 nil nil)))) (define rand (lambda (lo hi) (mk-ugen (list "Rand" ir (list lo hi) nil 1 nil (incr-uid 1))))) (define rand-id (lambda (rt id_) (mk-ugen (list "RandID" rt (list id_) nil 1 nil nil)))) (define rand-seed (lambda (rt trig seed) (mk-ugen (list "RandSeed" rt (list trig seed) nil 1 nil nil)))) (define record-buf (lambda (rt bufnum offset recLevel preLevel run loop trigger doneAction inputArray) (mk-ugen (list "RecordBuf" rt (list bufnum offset recLevel preLevel run loop trigger doneAction) inputArray 1 nil nil)))) (define replace-out (lambda (bus input) (mk-ugen (list "ReplaceOut" (list 1) (list bus) input 1 nil nil)))) (define resonz (lambda (input freq bwr) (mk-ugen (list "Resonz" (list 0) (list input freq bwr) nil 1 nil nil)))) (define ringz (lambda (input freq decaytime) (mk-ugen (list "Ringz" (list 0) (list input freq decaytime) nil 1 nil nil)))) (define rotate2 (lambda (x y pos) (mk-ugen (list "Rotate2" (list 0 1) (list x y pos) nil 2 nil nil)))) (define running-max (lambda (input trig) (mk-ugen (list "RunningMax" (list 0) (list input trig) nil 1 nil nil)))) (define running-min (lambda (input trig) (mk-ugen (list "RunningMin" (list 0) (list input trig) nil 1 nil nil)))) (define running-sum (lambda (input numsamp) (mk-ugen (list "RunningSum" (list 0) (list input numsamp) nil 1 nil nil)))) (define sos (lambda (input a0 a1 a2 b1 b2) (mk-ugen (list "SOS" (list 0) (list input a0 a1 a2 b1 b2) nil 1 nil nil)))) (define sample-dur (mk-ugen (list "SampleDur" ir nil nil 1 nil nil))) (define sample-rate (mk-ugen (list "SampleRate" ir nil nil 1 nil nil))) (define saw (lambda (rt freq) (mk-ugen (list "Saw" rt (list freq) nil 1 nil nil)))) (define schmidt (lambda (rt input lo hi) (mk-ugen (list "Schmidt" rt (list input lo hi) nil 1 nil nil)))) (define scope-out (lambda (rt inputArray bufnum) (mk-ugen (list "ScopeOut" rt (list inputArray bufnum) nil 1 nil nil)))) (define scope-out2 (lambda (rt inputArray scopeNum maxFrames scopeFrames) (mk-ugen (list "ScopeOut2" rt (list inputArray scopeNum maxFrames scopeFrames) nil 1 nil nil)))) (define select (lambda (which array) (mk-ugen (list "Select" (list 0 1) (list which) array 1 nil nil)))) (define send-trig (lambda (input id_ value) (mk-ugen (list "SendTrig" (list 0) (list input id_ value) nil 1 nil nil)))) (define set-reset-ff (lambda (trig reset) (mk-ugen (list "SetResetFF" (list 0) (list trig reset) nil 1 nil nil)))) (define shaper (lambda (bufnum input) (mk-ugen (list "Shaper" (list 1) (list bufnum input) nil 1 nil nil)))) (define sin-osc (lambda (rt freq phase) (mk-ugen (list "SinOsc" rt (list freq phase) nil 1 nil nil)))) (define sin-osc-fb (lambda (rt freq feedback) (mk-ugen (list "SinOscFB" rt (list freq feedback) nil 1 nil nil)))) (define slew (lambda (input up dn) (mk-ugen (list "Slew" (list 0) (list input up dn) nil 1 nil nil)))) (define slope (lambda (input) (mk-ugen (list "Slope" (list 0) (list input) nil 1 nil nil)))) (define spec-centroid (lambda (rt buffer) (mk-ugen (list "SpecCentroid" rt (list buffer) nil 1 nil nil)))) (define spec-flatness (lambda (rt buffer) (mk-ugen (list "SpecFlatness" rt (list buffer) nil 1 nil nil)))) (define spec-pcile (lambda (rt buffer fraction interpolate) (mk-ugen (list "SpecPcile" rt (list buffer fraction interpolate) nil 1 nil nil)))) (define spring (lambda (rt input spring damp) (mk-ugen (list "Spring" rt (list input spring damp) nil 1 nil nil)))) (define standard-l (lambda (rt freq k xi yi) (mk-ugen (list "StandardL" rt (list freq k xi yi) nil 1 nil nil)))) (define standard-n (lambda (rt freq k xi yi) (mk-ugen (list "StandardN" rt (list freq k xi yi) nil 1 nil nil)))) (define stepper (lambda (trig reset min_ max_ step resetval) (mk-ugen (list "Stepper" (list 0) (list trig reset min_ max_ step resetval) nil 1 nil nil)))) (define stereo-convolution2l (lambda (rt input kernelL kernelR trigger framesize crossfade) (mk-ugen (list "StereoConvolution2L" rt (list input kernelL kernelR trigger framesize crossfade) nil 2 nil nil)))) (define subsample-offset (mk-ugen (list "SubsampleOffset" ir nil nil 1 nil nil))) (define sum3 (lambda (in0 in1 in2) (mk-ugen (list "Sum3" (list 0 1 2) (list in0 in1 in2) nil 1 nil nil)))) (define sum4 (lambda (in0 in1 in2 in3) (mk-ugen (list "Sum4" (list 0 1 2 3) (list in0 in1 in2 in3) nil 1 nil nil)))) (define sweep (lambda (trig rate_) (mk-ugen (list "Sweep" (list 0) (list trig rate_) nil 1 nil nil)))) (define sync-saw (lambda (rt syncFreq sawFreq) (mk-ugen (list "SyncSaw" rt (list syncFreq sawFreq) nil 1 nil nil)))) (define t2a (lambda (input offset) (mk-ugen (list "T2A" ar (list input offset) nil 1 nil nil)))) (define t2k (lambda (rt input) (mk-ugen (list "T2K" rt (list input) nil 1 nil nil)))) (define t-ball (lambda (rt input g damp friction) (mk-ugen (list "TBall" rt (list input g damp friction) nil 1 nil nil)))) (define t-delay (lambda (input dur) (mk-ugen (list "TDelay" (list 0) (list input dur) nil 1 nil nil)))) (define t-duty (lambda (rt dur reset doneAction level gapFirst) (mk-ugen (list "TDuty" rt (list dur reset doneAction level gapFirst) nil 1 nil nil)))) (define t-exp-rand (lambda (lo hi trig) (mk-ugen (list "TExpRand" (list 2) (list lo hi trig) nil 1 nil (incr-uid 1))))) (define t-grains (lambda (nc trigger bufnum rate_ centerPos dur pan amp interp) (mk-ugen (list "TGrains" ar (list trigger bufnum rate_ centerPos dur pan amp interp) nil nc nil nil)))) (define ti-rand (lambda (lo hi trig) (mk-ugen (list "TIRand" (list 2) (list lo hi trig) nil 1 nil (incr-uid 1))))) (define t-rand (lambda (lo hi trig) (mk-ugen (list "TRand" (list 2) (list lo hi trig) nil 1 nil (incr-uid 1))))) (define t-windex (lambda (input normalize array) (mk-ugen (list "TWindex" (list 0) (list input normalize) array 1 nil (incr-uid 1))))) (define tap (lambda (nc rt bufnum delaytime) (mk-ugen (list "Tap" rt (list bufnum delaytime) nil nc nil nil)))) (define timer (lambda (trig) (mk-ugen (list "Timer" (list 0) (list trig) nil 1 nil nil)))) (define toggle-ff (lambda (trig) (mk-ugen (list "ToggleFF" (list 0) (list trig) nil 1 nil nil)))) (define trig (lambda (input dur) (mk-ugen (list "Trig" (list 0) (list input dur) nil 1 nil nil)))) (define trig1 (lambda (input dur) (mk-ugen (list "Trig1" (list 0) (list input dur) nil 1 nil nil)))) (define trig-control (lambda (rt values) (mk-ugen (list "TrigControl" rt (list values) nil 1 nil nil)))) (define two-pole (lambda (input freq radius) (mk-ugen (list "TwoPole" (list 0) (list input freq radius) nil 1 nil nil)))) (define two-zero (lambda (input freq radius) (mk-ugen (list "TwoZero" (list 0) (list input freq radius) nil 1 nil nil)))) (define unary-op-ugen (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 nil nil)))) (define v-disk-in (lambda (nc bufnum rate_ loop sendID) (mk-ugen (list "VDiskIn" ar (list bufnum rate_ loop sendID) nil nc nil nil)))) (define v-osc (lambda (rt bufpos freq phase) (mk-ugen (list "VOsc" rt (list bufpos freq phase) nil 1 nil nil)))) (define v-osc3 (lambda (rt bufpos freq1 freq2 freq3) (mk-ugen (list "VOsc3" rt (list bufpos freq1 freq2 freq3) nil 1 nil nil)))) (define var-lag (lambda (rt input time curvature warp start) (mk-ugen (list "VarLag" rt (list input time curvature warp start) nil 1 nil nil)))) (define var-saw (lambda (rt freq iphase width) (mk-ugen (list "VarSaw" rt (list freq iphase width) nil 1 nil nil)))) (define vibrato (lambda (rt freq rate_ depth delay onset rateVariation depthVariation iphase) (mk-ugen (list "Vibrato" rt (list freq rate_ depth delay onset rateVariation depthVariation iphase) nil 1 nil (incr-uid 1))))) (define warp1 (lambda (nc bufnum pointer freqScale windowSize envbufnum overlaps windowRandRatio interp) (mk-ugen (list "Warp1" ar (list bufnum pointer freqScale windowSize envbufnum overlaps windowRandRatio interp) nil nc nil nil)))) (define white-noise (lambda (rt) (mk-ugen (list "WhiteNoise" rt nil nil 1 nil (incr-uid 1))))) (define width-first-ugen (lambda (rt maxSize) (mk-ugen (list "WidthFirstUGen" rt (list maxSize) nil 1 nil nil)))) (define wrap (lambda (input lo hi) (mk-ugen (list "Wrap" (list 0) (list input lo hi) nil 1 nil nil)))) (define wrap-index (lambda (bufnum input) (mk-ugen (list "WrapIndex" (list 1) (list bufnum input) nil 1 nil nil)))) (define x-fade2 (lambda (inA inB pan level) (mk-ugen (list "XFade2" (list 0 1) (list inA inB pan level) nil 1 nil nil)))) (define x-line (lambda (rt start end dur doneAction) (mk-ugen (list "XLine" rt (list start end dur doneAction) nil 1 nil nil)))) (define x-out (lambda (bus xfade input) (mk-ugen (list "XOut" (list 2) (list bus xfade) input 1 nil nil)))) (define zero-crossing (lambda (input) (mk-ugen (list "ZeroCrossing" (list 0) (list input) nil 1 nil nil)))) (define mul-add (lambda (input mul add) (mk-ugen (list "MulAdd" (list 0) (list input mul add) nil 1 nil nil)))) (define set-buf (lambda (buf offset length_ array) (mk-ugen (list "SetBuf" ir (list buf offset length_) array 1 nil nil)))) (define neg (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 0 nil)))) (define u:not (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 1 nil)))) (define is-nil (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 2 nil)))) (define not-nil (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 3 nil)))) (define bit-not (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 4 nil)))) (define u:abs (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 5 nil)))) (define as-float (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 6 nil)))) (define as-int (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 7 nil)))) (define ceil (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 8 nil)))) (define u:floor (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 9 nil)))) (define frac (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 10 nil)))) (define sign (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 11 nil)))) (define squared (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 12 nil)))) (define cubed (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 13 nil)))) (define u:sqrt (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 14 nil)))) (define u:exp (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 15 nil)))) (define recip (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 16 nil)))) (define midicps (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 17 nil)))) (define cpsmidi (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 18 nil)))) (define midi-ratio (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 19 nil)))) (define ratio-midi (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 20 nil)))) (define db-amp (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 21 nil)))) (define amp-db (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 22 nil)))) (define oct-cps (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 23 nil)))) (define cps-oct (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 24 nil)))) (define u:log (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 25 nil)))) (define log2 (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 26 nil)))) (define log10 (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 27 nil)))) (define u:sin (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 28 nil)))) (define u:cos (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 29 nil)))) (define u:tan (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 30 nil)))) (define arc-sin (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 31 nil)))) (define arc-cos (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 32 nil)))) (define arc-tan (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 33 nil)))) (define sin-h (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 34 nil)))) (define cos-h (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 35 nil)))) (define tan-h (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 36 nil)))) (define rand- (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 37 nil)))) (define rand2 (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 38 nil)))) (define lin-rand- (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 39 nil)))) (define bi-lin-rand (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 40 nil)))) (define sum3rand (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 41 nil)))) (define distort (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 42 nil)))) (define soft-clip (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 43 nil)))) (define coin (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 44 nil)))) (define digit-value (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 45 nil)))) (define silence (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 46 nil)))) (define thru (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 47 nil)))) (define rect-window (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 48 nil)))) (define han-window (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 49 nil)))) (define welch-window (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 50 nil)))) (define tri-window (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 51 nil)))) (define ramp- (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 52 nil)))) (define s-curve (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 53 nil)))) (define add (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 0 nil)))) (define sub (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 1 nil)))) (define mul (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 2 nil)))) (define i-div (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 3 nil)))) (define f-div (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 4 nil)))) (define u:mod (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 5 nil)))) (define u:eq (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 6 nil)))) (define ne (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 7 nil)))) (define u:lt (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 8 nil)))) (define u:gt (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 9 nil)))) (define le (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 10 nil)))) (define ge (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 11 nil)))) (define u:min (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 12 nil)))) (define u:max (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 13 nil)))) (define bit-and (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 14 nil)))) (define bit-or (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 15 nil)))) (define bit-xor (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 16 nil)))) (define u:lcm (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 17 nil)))) (define u:gcd (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 18 nil)))) (define u:round (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 19 nil)))) (define round-up (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 20 nil)))) (define trunc (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 21 nil)))) (define atan2 (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 22 nil)))) (define hypot (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 23 nil)))) (define hypotx (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 24 nil)))) (define pow (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 25 nil)))) (define shift-left (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 26 nil)))) (define shift-right (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 27 nil)))) (define unsigned-shift (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 28 nil)))) (define fill (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 29 nil)))) (define ring1 (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 30 nil)))) (define ring2 (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 31 nil)))) (define ring3 (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 32 nil)))) (define ring4 (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 33 nil)))) (define dif-sqr (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 34 nil)))) (define sum-sqr (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 35 nil)))) (define sqr-sum (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 36 nil)))) (define sqr-dif (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 37 nil)))) (define abs-dif (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 38 nil)))) (define thresh (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 39 nil)))) (define am-clip (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 40 nil)))) (define scale-neg (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 41 nil)))) (define clip2 (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 42 nil)))) (define excess (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 43 nil)))) (define fold2 (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 44 nil)))) (define wrap2 (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 45 nil)))) (define first-arg (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 46 nil)))) (define rand-range (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 47 nil)))) (define exp-rand-range (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 48 nil))))
null
https://raw.githubusercontent.com/tommaisey/aeon/ecfe0b16432a836368188876abeba513dab18820/libs/third-party/sc3/rsc3/src/ugen.scm
scheme
(define a2k (lambda (input) (mk-ugen (list "A2K" kr (list input) nil 1 nil nil)))) (define apf (lambda (input freq radius) (mk-ugen (list "APF" (list 0) (list input freq radius) nil 1 nil nil)))) (define allpass-c (lambda (input maxdelaytime delaytime decaytime) (mk-ugen (list "AllpassC" (list 0) (list input maxdelaytime delaytime decaytime) nil 1 nil nil)))) (define allpass-l (lambda (input maxdelaytime delaytime decaytime) (mk-ugen (list "AllpassL" (list 0) (list input maxdelaytime delaytime decaytime) nil 1 nil nil)))) (define allpass-n (lambda (input maxdelaytime delaytime decaytime) (mk-ugen (list "AllpassN" (list 0) (list input maxdelaytime delaytime decaytime) nil 1 nil nil)))) (define amp-comp (lambda (rt freq root exp_) (mk-ugen (list "AmpComp" rt (list freq root exp_) nil 1 nil nil)))) (define amp-comp-a (lambda (rt freq root minAmp rootAmp) (mk-ugen (list "AmpCompA" rt (list freq root minAmp rootAmp) nil 1 nil nil)))) (define amplitude (lambda (rt input attackTime releaseTime) (mk-ugen (list "Amplitude" rt (list input attackTime releaseTime) nil 1 nil nil)))) (define audio-control (lambda (rt values) (mk-ugen (list "AudioControl" rt (list values) nil 1 nil nil)))) (define b-all-pass (lambda (input freq rq) (mk-ugen (list "BAllPass" (list 0) (list input freq rq) nil 1 nil nil)))) (define b-band-pass (lambda (input freq bw) (mk-ugen (list "BBandPass" (list 0) (list input freq bw) nil 1 nil nil)))) (define b-band-stop (lambda (input freq bw) (mk-ugen (list "BBandStop" (list 0) (list input freq bw) nil 1 nil nil)))) (define b-hi-pass (lambda (input freq rq) (mk-ugen (list "BHiPass" (list 0) (list input freq rq) nil 1 nil nil)))) (define b-hi-pass4 (lambda (input freq rq) (mk-ugen (list "BHiPass4" (list 0) (list input freq rq) nil 1 nil nil)))) (define b-hi-shelf (lambda (input freq rs db) (mk-ugen (list "BHiShelf" (list 0) (list input freq rs db) nil 1 nil nil)))) (define b-low-pass (lambda (input freq rq) (mk-ugen (list "BLowPass" (list 0) (list input freq rq) nil 1 nil nil)))) (define b-low-pass4 (lambda (input freq rq) (mk-ugen (list "BLowPass4" (list 0) (list input freq rq) nil 1 nil nil)))) (define b-low-shelf (lambda (input freq rs db) (mk-ugen (list "BLowShelf" (list 0) (list input freq rs db) nil 1 nil nil)))) (define bpf (lambda (input freq rq) (mk-ugen (list "BPF" (list 0) (list input freq rq) nil 1 nil nil)))) (define bpz2 (lambda (input) (mk-ugen (list "BPZ2" (list 0) (list input) nil 1 nil nil)))) (define b-peak-eq (lambda (input freq rq db) (mk-ugen (list "BPeakEQ" (list 0) (list input freq rq db) nil 1 nil nil)))) (define brf (lambda (input freq rq) (mk-ugen (list "BRF" (list 0) (list input freq rq) nil 1 nil nil)))) (define brz2 (lambda (input) (mk-ugen (list "BRZ2" (list 0) (list input) nil 1 nil nil)))) (define balance2 (lambda (rt left right pos level) (mk-ugen (list "Balance2" rt (list left right pos level) nil 2 nil nil)))) (define ball (lambda (rt input g damp friction) (mk-ugen (list "Ball" rt (list input g damp friction) nil 1 nil nil)))) (define beat-track (lambda (rt chain lock) (mk-ugen (list "BeatTrack" rt (list chain lock) nil 1 nil nil)))) (define beat-track2 (lambda (rt busindex numfeatures windowsize phaseaccuracy lock weightingscheme) (mk-ugen (list "BeatTrack2" rt (list busindex numfeatures windowsize phaseaccuracy lock weightingscheme) nil 6 nil nil)))) (define bi-pan-b2 (lambda (rt inA inB azimuth gain) (mk-ugen (list "BiPanB2" rt (list inA inB azimuth gain) nil 3 nil nil)))) (define binary-op-ugen (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 nil nil)))) (define blip (lambda (rt freq numharm) (mk-ugen (list "Blip" rt (list freq numharm) nil 1 nil nil)))) (define block-size (lambda (rt) (mk-ugen (list "BlockSize" rt nil nil 1 nil nil)))) (define brown-noise (lambda (rt) (mk-ugen (list "BrownNoise" rt nil nil 1 nil (incr-uid 1))))) (define buf-allpass-c (lambda (rt buf input delaytime decaytime) (mk-ugen (list "BufAllpassC" rt (list buf input delaytime decaytime) nil 1 nil nil)))) (define buf-allpass-l (lambda (rt buf input delaytime decaytime) (mk-ugen (list "BufAllpassL" rt (list buf input delaytime decaytime) nil 1 nil nil)))) (define buf-allpass-n (lambda (rt buf input delaytime decaytime) (mk-ugen (list "BufAllpassN" rt (list buf input delaytime decaytime) nil 1 nil nil)))) (define buf-channels (lambda (rt bufnum) (mk-ugen (list "BufChannels" rt (list bufnum) nil 1 nil nil)))) (define buf-comb-c (lambda (rt buf input delaytime decaytime) (mk-ugen (list "BufCombC" rt (list buf input delaytime decaytime) nil 1 nil nil)))) (define buf-comb-l (lambda (rt buf input delaytime decaytime) (mk-ugen (list "BufCombL" rt (list buf input delaytime decaytime) nil 1 nil nil)))) (define buf-comb-n (lambda (rt buf input delaytime decaytime) (mk-ugen (list "BufCombN" rt (list buf input delaytime decaytime) nil 1 nil nil)))) (define buf-delay-c (lambda (rt buf input delaytime) (mk-ugen (list "BufDelayC" rt (list buf input delaytime) nil 1 nil nil)))) (define buf-delay-l (lambda (rt buf input delaytime) (mk-ugen (list "BufDelayL" rt (list buf input delaytime) nil 1 nil nil)))) (define buf-delay-n (lambda (rt buf input delaytime) (mk-ugen (list "BufDelayN" rt (list buf input delaytime) nil 1 nil nil)))) (define buf-dur (lambda (rt bufnum) (mk-ugen (list "BufDur" rt (list bufnum) nil 1 nil nil)))) (define buf-frames (lambda (rt bufnum) (mk-ugen (list "BufFrames" rt (list bufnum) nil 1 nil nil)))) (define buf-rate-scale (lambda (rt bufnum) (mk-ugen (list "BufRateScale" rt (list bufnum) nil 1 nil nil)))) (define buf-rd (lambda (nc rt bufnum phase loop interpolation) (mk-ugen (list "BufRd" rt (list bufnum phase loop interpolation) nil nc nil nil)))) (define buf-sample-rate (lambda (rt bufnum) (mk-ugen (list "BufSampleRate" rt (list bufnum) nil 1 nil nil)))) (define buf-samples (lambda (rt bufnum) (mk-ugen (list "BufSamples" rt (list bufnum) nil 1 nil nil)))) (define buf-wr (lambda (bufnum phase loop inputArray) (mk-ugen (list "BufWr" (list 3) (list bufnum phase loop) inputArray 1 nil nil)))) (define c-osc (lambda (rt bufnum freq beats) (mk-ugen (list "COsc" rt (list bufnum freq beats) nil 1 nil nil)))) (define check-bad-values (lambda (input id_ post) (mk-ugen (list "CheckBadValues" (list 0) (list input id_ post) nil 1 nil nil)))) (define clip (lambda (input lo hi) (mk-ugen (list "Clip" (list 0) (list input lo hi) nil 1 nil nil)))) (define clip-noise (lambda (rt) (mk-ugen (list "ClipNoise" rt nil nil 1 nil (incr-uid 1))))) (define coin-gate (lambda (prob input) (mk-ugen (list "CoinGate" (list 1) (list prob input) nil 1 nil (incr-uid 1))))) (define comb-c (lambda (input maxdelaytime delaytime decaytime) (mk-ugen (list "CombC" (list 0) (list input maxdelaytime delaytime decaytime) nil 1 nil nil)))) (define comb-l (lambda (input maxdelaytime delaytime decaytime) (mk-ugen (list "CombL" (list 0) (list input maxdelaytime delaytime decaytime) nil 1 nil nil)))) (define comb-n (lambda (input maxdelaytime delaytime decaytime) (mk-ugen (list "CombN" (list 0) (list input maxdelaytime delaytime decaytime) nil 1 nil nil)))) (define compander (lambda (input control_ thresh slopeBelow slopeAbove clampTime relaxTime) (mk-ugen (list "Compander" (list 0) (list input control_ thresh slopeBelow slopeAbove clampTime relaxTime) nil 1 nil nil)))) (define compander-d (lambda (rt input thresh slopeBelow slopeAbove clampTime relaxTime) (mk-ugen (list "CompanderD" rt (list input thresh slopeBelow slopeAbove clampTime relaxTime) nil 1 nil nil)))) (define control-dur (mk-ugen (list "ControlDur" ir nil nil 1 nil nil))) (define control-rate (mk-ugen (list "ControlRate" ir nil nil 1 nil nil))) (define convolution (lambda (rt input kernel framesize) (mk-ugen (list "Convolution" rt (list input kernel framesize) nil 1 nil nil)))) (define convolution2 (lambda (rt input kernel trigger framesize) (mk-ugen (list "Convolution2" rt (list input kernel trigger framesize) nil 1 nil nil)))) (define convolution2l (lambda (rt input kernel trigger framesize crossfade) (mk-ugen (list "Convolution2L" rt (list input kernel trigger framesize crossfade) nil 1 nil nil)))) (define convolution3 (lambda (rt input kernel trigger framesize) (mk-ugen (list "Convolution3" rt (list input kernel trigger framesize) nil 1 nil nil)))) (define crackle (lambda (rt chaosParam) (mk-ugen (list "Crackle" rt (list chaosParam) nil 1 nil nil)))) (define cusp-l (lambda (rt freq a b xi) (mk-ugen (list "CuspL" rt (list freq a b xi) nil 1 nil nil)))) (define cusp-n (lambda (rt freq a b xi) (mk-ugen (list "CuspN" rt (list freq a b xi) nil 1 nil nil)))) (define dc (lambda (rt input) (mk-ugen (list "DC" rt (list input) nil 1 nil nil)))) (define dbrown (lambda (length_ lo hi step) (mk-ugen (list "Dbrown" dr (list length_ lo hi step) nil 1 nil (incr-uid 1))))) (define dbufrd (lambda (bufnum phase loop) (mk-ugen (list "Dbufrd" dr (list bufnum phase loop) nil 1 nil (incr-uid 1))))) (define dbufwr (lambda (bufnum phase loop input) (mk-ugen (list "Dbufwr" dr (list bufnum phase loop input) nil 1 nil (incr-uid 1))))) (define decay (lambda (input decayTime) (mk-ugen (list "Decay" (list 0) (list input decayTime) nil 1 nil nil)))) (define decay2 (lambda (input attackTime decayTime) (mk-ugen (list "Decay2" (list 0) (list input attackTime decayTime) nil 1 nil nil)))) (define decode-b2 (lambda (nc rt w x y orientation) (mk-ugen (list "DecodeB2" rt (list w x y orientation) nil nc nil nil)))) (define degree-to-key (lambda (bufnum input octave) (mk-ugen (list "DegreeToKey" (list 1) (list bufnum input octave) nil 1 nil nil)))) (define del-tap-rd (lambda (buffer phase delTime interp) (mk-ugen (list "DelTapRd" (list 1) (list buffer phase delTime interp) nil 1 nil nil)))) (define del-tap-wr (lambda (buffer input) (mk-ugen (list "DelTapWr" (list 1) (list buffer input) nil 1 nil nil)))) (define delay1 (lambda (input) (mk-ugen (list "Delay1" (list 0) (list input) nil 1 nil nil)))) (define delay2 (lambda (input) (mk-ugen (list "Delay2" (list 0) (list input) nil 1 nil nil)))) (define delay-c (lambda (input maxdelaytime delaytime) (mk-ugen (list "DelayC" (list 0) (list input maxdelaytime delaytime) nil 1 nil nil)))) (define delay-l (lambda (input maxdelaytime delaytime) (mk-ugen (list "DelayL" (list 0) (list input maxdelaytime delaytime) nil 1 nil nil)))) (define delay-n (lambda (input maxdelaytime delaytime) (mk-ugen (list "DelayN" (list 0) (list input maxdelaytime delaytime) nil 1 nil nil)))) (define demand (lambda (trig reset demandUGens) (mk-ugen (list "Demand" (list 0) (list trig reset) demandUGens (length (mce-channels demandUGens)) nil nil)))) (define demand-env-gen (lambda (rt level dur shape curve gate reset levelScale levelBias timeScale doneAction) (mk-ugen (list "DemandEnvGen" rt (list level dur shape curve gate reset levelScale levelBias timeScale doneAction) nil 1 nil nil)))) (define detect-index (lambda (bufnum input) (mk-ugen (list "DetectIndex" (list 1) (list bufnum input) nil 1 nil nil)))) (define detect-silence (lambda (input amp time doneAction) (mk-ugen (list "DetectSilence" (list 0) (list input amp time doneAction) nil 1 nil nil)))) (define dgeom (lambda (length_ start grow) (mk-ugen (list "Dgeom" dr (list length_ start grow) nil 1 nil (incr-uid 1))))) (define dibrown (lambda (length_ lo hi step) (mk-ugen (list "Dibrown" dr (list length_ lo hi step) nil 1 nil (incr-uid 1))))) (define disk-in (lambda (nc bufnum loop) (mk-ugen (list "DiskIn" ar (list bufnum loop) nil nc nil nil)))) (define disk-out (lambda (bufnum input) (mk-ugen (list "DiskOut" ar (list bufnum) input 1 nil nil)))) (define diwhite (lambda (length_ lo hi) (mk-ugen (list "Diwhite" dr (list length_ lo hi) nil 1 nil (incr-uid 1))))) (define donce (lambda (input) (mk-ugen (list "Donce" dr (list input) nil 1 nil (incr-uid 1))))) (define done (lambda (rt src) (mk-ugen (list "Done" rt (list src) nil 1 nil nil)))) (define dpoll (lambda (input label_ run trigid) (mk-ugen (list "Dpoll" dr (list input label_ run trigid) nil 1 nil (incr-uid 1))))) (define drand (lambda (repeats list_) (mk-ugen (list "Drand" dr (list repeats) list_ 1 nil (incr-uid 1))))) (define dreset (lambda (input reset) (mk-ugen (list "Dreset" dr (list input reset) nil 1 nil (incr-uid 1))))) (define dseq (lambda (repeats list_) (mk-ugen (list "Dseq" dr (list repeats) list_ 1 nil (incr-uid 1))))) (define dser (lambda (repeats list_) (mk-ugen (list "Dser" dr (list repeats) list_ 1 nil (incr-uid 1))))) (define dseries (lambda (length_ start step) (mk-ugen (list "Dseries" dr (list length_ start step) nil 1 nil (incr-uid 1))))) (define dshuf (lambda (repeats list_) (mk-ugen (list "Dshuf" dr (list repeats) list_ 1 nil (incr-uid 1))))) (define dstutter (lambda (n input) (mk-ugen (list "Dstutter" dr (list n input) nil 1 nil (incr-uid 1))))) (define dswitch (lambda (index list_) (mk-ugen (list "Dswitch" dr (list index) list_ 1 nil (incr-uid 1))))) (define dswitch1 (lambda (index list_) (mk-ugen (list "Dswitch1" dr (list index) list_ 1 nil (incr-uid 1))))) (define dunique (lambda (source maxBufferSize protected) (mk-ugen (list "Dunique" dr (list source maxBufferSize protected) nil 1 nil (incr-uid 1))))) (define dust (lambda (rt density) (mk-ugen (list "Dust" rt (list density) nil 1 nil (incr-uid 1))))) (define dust2 (lambda (rt density) (mk-ugen (list "Dust2" rt (list density) nil 1 nil (incr-uid 1))))) (define dust-r (lambda (rt iot_min iot_max) (mk-ugen (list "DustR" rt (list iot_min iot_max) nil 1 nil nil)))) (define duty (lambda (rt dur reset doneAction level) (mk-ugen (list "Duty" rt (list dur reset doneAction level) nil 1 nil nil)))) (define dwhite (lambda (length_ lo hi) (mk-ugen (list "Dwhite" dr (list length_ lo hi) nil 1 nil (incr-uid 1))))) (define dwrand (lambda (repeats weights list_) (mk-ugen (list "Dwrand" dr (list repeats weights) list_ 1 nil (incr-uid 1))))) (define dxrand (lambda (repeats list_) (mk-ugen (list "Dxrand" dr (list repeats) list_ 1 nil (incr-uid 1))))) (define env-gen (lambda (rt gate levelScale levelBias timeScale doneAction envelope_) (mk-ugen (list "EnvGen" rt (list gate levelScale levelBias timeScale doneAction) envelope_ 1 nil nil)))) (define exp-rand (lambda (lo hi) (mk-ugen (list "ExpRand" (list 0 1) (list lo hi) nil 1 nil (incr-uid 1))))) (define fb-sine-c (lambda (rt freq im fb a c xi yi) (mk-ugen (list "FBSineC" rt (list freq im fb a c xi yi) nil 1 nil nil)))) (define fb-sine-l (lambda (rt freq im fb a c xi yi) (mk-ugen (list "FBSineL" rt (list freq im fb a c xi yi) nil 1 nil nil)))) (define fb-sine-n (lambda (rt freq im fb a c xi yi) (mk-ugen (list "FBSineN" rt (list freq im fb a c xi yi) nil 1 nil nil)))) (define fft (lambda (buffer input hop wintype active winsize) (mk-ugen (list "FFT" kr (list buffer input hop wintype active winsize) nil 1 nil nil)))) (define fos (lambda (input a0 a1 b1) (mk-ugen (list "FOS" (list 0) (list input a0 a1 b1) nil 1 nil nil)))) (define f-sin-osc (lambda (rt freq iphase) (mk-ugen (list "FSinOsc" rt (list freq iphase) nil 1 nil nil)))) (define fold (lambda (input lo hi) (mk-ugen (list "Fold" (list 0) (list input lo hi) nil 1 nil nil)))) (define formant (lambda (rt fundfreq formfreq bwfreq) (mk-ugen (list "Formant" rt (list fundfreq formfreq bwfreq) nil 1 nil nil)))) (define formlet (lambda (input freq attacktime decaytime) (mk-ugen (list "Formlet" (list 0) (list input freq attacktime decaytime) nil 1 nil nil)))) (define free (lambda (trig id_) (mk-ugen (list "Free" (list 0) (list trig id_) nil 1 nil nil)))) (define free-self (lambda (input) (mk-ugen (list "FreeSelf" kr (list input) nil 1 nil nil)))) (define free-self-when-done (lambda (rt src) (mk-ugen (list "FreeSelfWhenDone" rt (list src) nil 1 nil nil)))) (define free-verb (lambda (input mix room damp) (mk-ugen (list "FreeVerb" (list 0) (list input mix room damp) nil 1 nil nil)))) (define free-verb2 (lambda (input in2 mix room damp) (mk-ugen (list "FreeVerb2" (list 0) (list input in2 mix room damp) nil 2 nil nil)))) (define freq-shift (lambda (rt input freq phase) (mk-ugen (list "FreqShift" rt (list input freq phase) nil 1 nil nil)))) (define g-verb (lambda (input roomsize revtime damping inputbw spread drylevel earlyreflevel taillevel maxroomsize) (mk-ugen (list "GVerb" (list 0) (list input roomsize revtime damping inputbw spread drylevel earlyreflevel taillevel maxroomsize) nil 2 nil nil)))) (define gate (lambda (input trig) (mk-ugen (list "Gate" (list 0) (list input trig) nil 1 nil nil)))) (define gbman-l (lambda (rt freq xi yi) (mk-ugen (list "GbmanL" rt (list freq xi yi) nil 1 nil nil)))) (define gbman-n (lambda (rt freq xi yi) (mk-ugen (list "GbmanN" rt (list freq xi yi) nil 1 nil nil)))) (define gendy1 (lambda (rt ampdist durdist adparam ddparam minfreq maxfreq ampscale durscale initCPs knum) (mk-ugen (list "Gendy1" rt (list ampdist durdist adparam ddparam minfreq maxfreq ampscale durscale initCPs knum) nil 1 nil (incr-uid 1))))) (define gendy2 (lambda (rt ampdist durdist adparam ddparam minfreq maxfreq ampscale durscale initCPs knum a c) (mk-ugen (list "Gendy2" rt (list ampdist durdist adparam ddparam minfreq maxfreq ampscale durscale initCPs knum a c) nil 1 nil (incr-uid 1))))) (define gendy3 (lambda (rt ampdist durdist adparam ddparam freq ampscale durscale initCPs knum) (mk-ugen (list "Gendy3" rt (list ampdist durdist adparam ddparam freq ampscale durscale initCPs knum) nil 1 nil (incr-uid 1))))) (define grain-buf (lambda (nc trigger dur sndbuf rate_ pos interp pan envbufnum maxGrains) (mk-ugen (list "GrainBuf" ar (list trigger dur sndbuf rate_ pos interp pan envbufnum maxGrains) nil nc nil nil)))) (define grain-fm (lambda (nc trigger dur carfreq modfreq index pan envbufnum maxGrains) (mk-ugen (list "GrainFM" ar (list trigger dur carfreq modfreq index pan envbufnum maxGrains) nil nc nil nil)))) (define grain-in (lambda (nc trigger dur input pan envbufnum maxGrains) (mk-ugen (list "GrainIn" ar (list trigger dur input pan envbufnum maxGrains) nil nc nil nil)))) (define grain-sin (lambda (nc trigger dur freq pan envbufnum maxGrains) (mk-ugen (list "GrainSin" ar (list trigger dur freq pan envbufnum maxGrains) nil nc nil nil)))) (define gray-noise (lambda (rt) (mk-ugen (list "GrayNoise" rt nil nil 1 nil (incr-uid 1))))) (define hpf (lambda (input freq) (mk-ugen (list "HPF" (list 0) (list input freq) nil 1 nil nil)))) (define hpz1 (lambda (input) (mk-ugen (list "HPZ1" (list 0) (list input) nil 1 nil nil)))) (define hpz2 (lambda (input) (mk-ugen (list "HPZ2" (list 0) (list input) nil 1 nil nil)))) (define hasher (lambda (input) (mk-ugen (list "Hasher" (list 0) (list input) nil 1 nil nil)))) (define henon-c (lambda (rt freq a b x0 x1) (mk-ugen (list "HenonC" rt (list freq a b x0 x1) nil 1 nil nil)))) (define henon-l (lambda (rt freq a b x0 x1) (mk-ugen (list "HenonL" rt (list freq a b x0 x1) nil 1 nil nil)))) (define henon-n (lambda (rt freq a b x0 x1) (mk-ugen (list "HenonN" rt (list freq a b x0 x1) nil 1 nil nil)))) (define hilbert (lambda (input) (mk-ugen (list "Hilbert" (list 0) (list input) nil 2 nil nil)))) (define hilbert-fir (lambda (rt input buffer) (mk-ugen (list "HilbertFIR" rt (list input buffer) nil 2 nil nil)))) (define i-env-gen (lambda (rt index envelope_) (mk-ugen (list "IEnvGen" rt (list index) envelope_ 1 nil nil)))) (define ifft (lambda (buffer wintype winsize) (mk-ugen (list "IFFT" ar (list buffer wintype winsize) nil 1 nil nil)))) (define i-rand (lambda (lo hi) (mk-ugen (list "IRand" ir (list lo hi) nil 1 nil (incr-uid 1))))) (define impulse (lambda (rt freq phase) (mk-ugen (list "Impulse" rt (list freq phase) nil 1 nil nil)))) (define in (lambda (nc rt bus) (mk-ugen (list "In" rt (list bus) nil nc nil nil)))) (define in-feedback (lambda (nc bus) (mk-ugen (list "InFeedback" ar (list bus) nil nc nil nil)))) (define in-range (lambda (input lo hi) (mk-ugen (list "InRange" (list 0) (list input lo hi) nil 1 nil nil)))) (define in-rect (lambda (rt x y rect) (mk-ugen (list "InRect" rt (list x y rect) nil 1 nil nil)))) (define in-trig (lambda (nc rt bus) (mk-ugen (list "InTrig" rt (list bus) nil nc nil nil)))) (define index (lambda (bufnum input) (mk-ugen (list "Index" (list 1) (list bufnum input) nil 1 nil nil)))) (define index-in-between (lambda (rt bufnum input) (mk-ugen (list "IndexInBetween" rt (list bufnum input) nil 1 nil nil)))) (define index-l (lambda (rt bufnum input) (mk-ugen (list "IndexL" rt (list bufnum input) nil 1 nil nil)))) (define info-ugen-base (lambda (rt) (mk-ugen (list "InfoUGenBase" rt nil nil 1 nil nil)))) (define integrator (lambda (input coef) (mk-ugen (list "Integrator" (list 0) (list input coef) nil 1 nil nil)))) (define k2a (lambda (input) (mk-ugen (list "K2A" ar (list input) nil 1 nil nil)))) (define key-state (lambda (rt keycode minval maxval lag) (mk-ugen (list "KeyState" rt (list keycode minval maxval lag) nil 1 nil nil)))) (define key-track (lambda (rt chain keydecay chromaleak) (mk-ugen (list "KeyTrack" rt (list chain keydecay chromaleak) nil 1 nil nil)))) (define klang (lambda (rt freqscale freqoffset specificationsArrayRef) (mk-ugen (list "Klang" rt (list freqscale freqoffset) specificationsArrayRef 1 nil nil)))) (define klank (lambda (input freqscale freqoffset decayscale specificationsArrayRef) (mk-ugen (list "Klank" (list 0) (list input freqscale freqoffset decayscale) specificationsArrayRef 1 nil nil)))) (define lf-clip-noise (lambda (rt freq) (mk-ugen (list "LFClipNoise" rt (list freq) nil 1 nil (incr-uid 1))))) (define lf-cub (lambda (rt freq iphase) (mk-ugen (list "LFCub" rt (list freq iphase) nil 1 nil nil)))) (define lfd-clip-noise (lambda (rt freq) (mk-ugen (list "LFDClipNoise" rt (list freq) nil 1 nil (incr-uid 1))))) (define lfd-noise0 (lambda (rt freq) (mk-ugen (list "LFDNoise0" rt (list freq) nil 1 nil (incr-uid 1))))) (define lfd-noise1 (lambda (rt freq) (mk-ugen (list "LFDNoise1" rt (list freq) nil 1 nil (incr-uid 1))))) (define lfd-noise3 (lambda (rt freq) (mk-ugen (list "LFDNoise3" rt (list freq) nil 1 nil (incr-uid 1))))) (define lf-gauss (lambda (rt duration width iphase loop doneAction) (mk-ugen (list "LFGauss" rt (list duration width iphase loop doneAction) nil 1 nil nil)))) (define lf-noise0 (lambda (rt freq) (mk-ugen (list "LFNoise0" rt (list freq) nil 1 nil (incr-uid 1))))) (define lf-noise1 (lambda (rt freq) (mk-ugen (list "LFNoise1" rt (list freq) nil 1 nil (incr-uid 1))))) (define lf-noise2 (lambda (rt freq) (mk-ugen (list "LFNoise2" rt (list freq) nil 1 nil (incr-uid 1))))) (define lf-par (lambda (rt freq iphase) (mk-ugen (list "LFPar" rt (list freq iphase) nil 1 nil nil)))) (define lf-pulse (lambda (rt freq iphase width) (mk-ugen (list "LFPulse" rt (list freq iphase width) nil 1 nil nil)))) (define lf-saw (lambda (rt freq iphase) (mk-ugen (list "LFSaw" rt (list freq iphase) nil 1 nil nil)))) (define lf-tri (lambda (rt freq iphase) (mk-ugen (list "LFTri" rt (list freq iphase) nil 1 nil nil)))) (define lpf (lambda (input freq) (mk-ugen (list "LPF" (list 0) (list input freq) nil 1 nil nil)))) (define lpz1 (lambda (input) (mk-ugen (list "LPZ1" (list 0) (list input) nil 1 nil nil)))) (define lpz2 (lambda (input) (mk-ugen (list "LPZ2" (list 0) (list input) nil 1 nil nil)))) (define lag (lambda (input lagTime) (mk-ugen (list "Lag" (list 0) (list input lagTime) nil 1 nil nil)))) (define lag2 (lambda (input lagTime) (mk-ugen (list "Lag2" (list 0) (list input lagTime) nil 1 nil nil)))) (define lag2ud (lambda (input lagTimeU lagTimeD) (mk-ugen (list "Lag2UD" (list 0) (list input lagTimeU lagTimeD) nil 1 nil nil)))) (define lag3 (lambda (input lagTime) (mk-ugen (list "Lag3" (list 0) (list input lagTime) nil 1 nil nil)))) (define lag3ud (lambda (input lagTimeU lagTimeD) (mk-ugen (list "Lag3UD" (list 0) (list input lagTimeU lagTimeD) nil 1 nil nil)))) (define lag-control (lambda (rt values lags) (mk-ugen (list "LagControl" rt (list values lags) nil 1 nil nil)))) (define lag-in (lambda (nc rt bus lag) (mk-ugen (list "LagIn" rt (list bus lag) nil nc nil nil)))) (define lag-ud (lambda (input lagTimeU lagTimeD) (mk-ugen (list "LagUD" (list 0) (list input lagTimeU lagTimeD) nil 1 nil nil)))) (define last-value (lambda (input diff) (mk-ugen (list "LastValue" (list 0) (list input diff) nil 1 nil nil)))) (define latch (lambda (input trig) (mk-ugen (list "Latch" (list 0) (list input trig) nil 1 nil nil)))) (define latoocarfian-c (lambda (rt freq a b c d xi yi) (mk-ugen (list "LatoocarfianC" rt (list freq a b c d xi yi) nil 1 nil nil)))) (define latoocarfian-l (lambda (rt freq a b c d xi yi) (mk-ugen (list "LatoocarfianL" rt (list freq a b c d xi yi) nil 1 nil nil)))) (define latoocarfian-n (lambda (rt freq a b c d xi yi) (mk-ugen (list "LatoocarfianN" rt (list freq a b c d xi yi) nil 1 nil nil)))) (define leak-dc (lambda (input coef) (mk-ugen (list "LeakDC" (list 0) (list input coef) nil 1 nil nil)))) (define least-change (lambda (rt a b) (mk-ugen (list "LeastChange" rt (list a b) nil 1 nil nil)))) (define limiter (lambda (input level dur) (mk-ugen (list "Limiter" (list 0) (list input level dur) nil 1 nil nil)))) (define lin-cong-c (lambda (rt freq a c m xi) (mk-ugen (list "LinCongC" rt (list freq a c m xi) nil 1 nil nil)))) (define lin-cong-l (lambda (rt freq a c m xi) (mk-ugen (list "LinCongL" rt (list freq a c m xi) nil 1 nil nil)))) (define lin-cong-n (lambda (rt freq a c m xi) (mk-ugen (list "LinCongN" rt (list freq a c m xi) nil 1 nil nil)))) (define lin-exp (lambda (input srclo srchi dstlo dsthi) (mk-ugen (list "LinExp" (list 0) (list input srclo srchi dstlo dsthi) nil 1 nil nil)))) (define lin-pan2 (lambda (input pos level) (mk-ugen (list "LinPan2" (list 0) (list input pos level) nil 2 nil nil)))) (define lin-rand (lambda (lo hi minmax) (mk-ugen (list "LinRand" ir (list lo hi minmax) nil 1 nil (incr-uid 1))))) (define lin-x-fade2 (lambda (inA inB pan level) (mk-ugen (list "LinXFade2" (list 0 1) (list inA inB pan level) nil 1 nil nil)))) (define line (lambda (rt start end dur doneAction) (mk-ugen (list "Line" rt (list start end dur doneAction) nil 1 nil nil)))) (define linen (lambda (gate attackTime susLevel releaseTime doneAction) (mk-ugen (list "Linen" kr (list gate attackTime susLevel releaseTime doneAction) nil 1 nil nil)))) (define local-buf (lambda (numChannels numFrames) (mk-ugen (list "LocalBuf" ir (list numChannels numFrames) nil 1 nil (incr-uid 1))))) (define local-in (lambda (nc rt default_) (mk-ugen (list "LocalIn" rt nil default_ nc nil nil)))) (define local-out (lambda (input) (mk-ugen (list "LocalOut" (list 0) nil input 1 nil nil)))) (define logistic (lambda (rt chaosParam freq init_) (mk-ugen (list "Logistic" rt (list chaosParam freq init_) nil 1 nil nil)))) (define lorenz-l (lambda (rt freq s r b h xi yi zi) (mk-ugen (list "LorenzL" rt (list freq s r b h xi yi zi) nil 1 nil nil)))) (define loudness (lambda (rt chain smask tmask) (mk-ugen (list "Loudness" rt (list chain smask tmask) nil 1 nil nil)))) (define mfcc (lambda (rt chain numcoeff) (mk-ugen (list "MFCC" rt (list chain numcoeff) nil 13 nil nil)))) (define mantissa-mask (lambda (input bits) (mk-ugen (list "MantissaMask" (list 0) (list input bits) nil 1 nil nil)))) (define max-local-bufs (lambda (count) (mk-ugen (list "MaxLocalBufs" ir (list count) nil 1 nil nil)))) (define median (lambda (length_ input) (mk-ugen (list "Median" (list 1) (list length_ input) nil 1 nil nil)))) (define mid-eq (lambda (input freq rq db) (mk-ugen (list "MidEQ" (list 0) (list input freq rq db) nil 1 nil nil)))) (define mod-dif (lambda (rt x y mod_) (mk-ugen (list "ModDif" rt (list x y mod_) nil 1 nil nil)))) (define moog-ff (lambda (input freq gain reset) (mk-ugen (list "MoogFF" (list 0) (list input freq gain reset) nil 1 nil nil)))) (define most-change (lambda (a b) (mk-ugen (list "MostChange" (list 0 1) (list a b) nil 1 nil nil)))) (define mouse-button (lambda (rt minval maxval lag) (mk-ugen (list "MouseButton" rt (list minval maxval lag) nil 1 nil nil)))) (define mouse-x (lambda (rt minval maxval warp lag) (mk-ugen (list "MouseX" rt (list minval maxval warp lag) nil 1 nil nil)))) (define mouse-y (lambda (rt minval maxval warp lag) (mk-ugen (list "MouseY" rt (list minval maxval warp lag) nil 1 nil nil)))) (define n-rand (lambda (lo hi n) (mk-ugen (list "NRand" ir (list lo hi n) nil 1 nil (incr-uid 1))))) (define normalizer (lambda (input level dur) (mk-ugen (list "Normalizer" (list 0) (list input level dur) nil 1 nil nil)))) (define num-audio-buses (mk-ugen (list "NumAudioBuses" ir nil nil 1 nil nil))) (define num-buffers (mk-ugen (list "NumBuffers" ir nil nil 1 nil nil))) (define num-control-buses (mk-ugen (list "NumControlBuses" ir nil nil 1 nil nil))) (define num-input-buses (mk-ugen (list "NumInputBuses" ir nil nil 1 nil nil))) (define num-output-buses (mk-ugen (list "NumOutputBuses" ir nil nil 1 nil nil))) (define num-running-synths (mk-ugen (list "NumRunningSynths" ir nil nil 1 nil nil))) (define offset-out (lambda (bus input) (mk-ugen (list "OffsetOut" (list 1) (list bus) input 1 nil nil)))) (define one-pole (lambda (input coef) (mk-ugen (list "OnePole" (list 0) (list input coef) nil 1 nil nil)))) (define one-zero (lambda (input coef) (mk-ugen (list "OneZero" (list 0) (list input coef) nil 1 nil nil)))) (define onsets (lambda (chain threshold odftype relaxtime floor_ mingap medianspan whtype rawodf) (mk-ugen (list "Onsets" kr (list chain threshold odftype relaxtime floor_ mingap medianspan whtype rawodf) nil 1 nil nil)))) (define osc (lambda (rt bufnum freq phase) (mk-ugen (list "Osc" rt (list bufnum freq phase) nil 1 nil nil)))) (define osc-n (lambda (rt bufnum freq phase) (mk-ugen (list "OscN" rt (list bufnum freq phase) nil 1 nil nil)))) (define out (lambda (bus input) (mk-ugen (list "Out" (list 1) (list bus) input 1 nil nil)))) (define p-sin-grain (lambda (rt freq dur amp) (mk-ugen (list "PSinGrain" rt (list freq dur amp) nil 1 nil nil)))) (define pv-add (lambda (bufferA bufferB) (mk-ugen (list "PV_Add" kr (list bufferA bufferB) nil 1 nil nil)))) (define pv-bin-scramble (lambda (buffer wipe width trig) (mk-ugen (list "PV_BinScramble" kr (list buffer wipe width trig) nil 1 nil (incr-uid 1))))) (define pv-bin-shift (lambda (buffer stretch shift interp) (mk-ugen (list "PV_BinShift" kr (list buffer stretch shift interp) nil 1 nil nil)))) (define pv-bin-wipe (lambda (bufferA bufferB wipe) (mk-ugen (list "PV_BinWipe" kr (list bufferA bufferB wipe) nil 1 nil nil)))) (define pv-brick-wall (lambda (buffer wipe) (mk-ugen (list "PV_BrickWall" kr (list buffer wipe) nil 1 nil nil)))) (define pv-chain-ugen (lambda (maxSize) (mk-ugen (list "PV_ChainUGen" kr (list maxSize) nil 1 nil nil)))) (define pv-conformal-map (lambda (buffer areal aimag) (mk-ugen (list "PV_ConformalMap" kr (list buffer areal aimag) nil 1 nil nil)))) (define pv-conj (lambda (buffer) (mk-ugen (list "PV_Conj" kr (list buffer) nil 1 nil nil)))) (define pv-copy (lambda (bufferA bufferB) (mk-ugen (list "PV_Copy" kr (list bufferA bufferB) nil 1 nil nil)))) (define pv-copy-phase (lambda (bufferA bufferB) (mk-ugen (list "PV_CopyPhase" kr (list bufferA bufferB) nil 1 nil nil)))) (define pv-diffuser (lambda (buffer trig) (mk-ugen (list "PV_Diffuser" kr (list buffer trig) nil 1 nil nil)))) (define pv-div (lambda (bufferA bufferB) (mk-ugen (list "PV_Div" kr (list bufferA bufferB) nil 1 nil nil)))) (define pv-hainsworth-foote (lambda (maxSize) (mk-ugen (list "PV_HainsworthFoote" kr (list maxSize) nil 1 nil nil)))) (define pv-jensen-andersen (lambda (maxSize) (mk-ugen (list "PV_JensenAndersen" kr (list maxSize) nil 1 nil nil)))) (define pv-local-max (lambda (buffer threshold) (mk-ugen (list "PV_LocalMax" kr (list buffer threshold) nil 1 nil nil)))) (define pv-mag-above (lambda (buffer threshold) (mk-ugen (list "PV_MagAbove" kr (list buffer threshold) nil 1 nil nil)))) (define pv-mag-below (lambda (buffer threshold) (mk-ugen (list "PV_MagBelow" kr (list buffer threshold) nil 1 nil nil)))) (define pv-mag-clip (lambda (buffer threshold) (mk-ugen (list "PV_MagClip" kr (list buffer threshold) nil 1 nil nil)))) (define pv-mag-div (lambda (bufferA bufferB zeroed) (mk-ugen (list "PV_MagDiv" kr (list bufferA bufferB zeroed) nil 1 nil nil)))) (define pv-mag-freeze (lambda (buffer freeze) (mk-ugen (list "PV_MagFreeze" kr (list buffer freeze) nil 1 nil nil)))) (define pv-mag-mul (lambda (bufferA bufferB) (mk-ugen (list "PV_MagMul" kr (list bufferA bufferB) nil 1 nil nil)))) (define pv-mag-noise (lambda (buffer) (mk-ugen (list "PV_MagNoise" kr (list buffer) nil 1 nil nil)))) (define pv-mag-shift (lambda (buffer stretch shift) (mk-ugen (list "PV_MagShift" kr (list buffer stretch shift) nil 1 nil nil)))) (define pv-mag-smear (lambda (buffer bins) (mk-ugen (list "PV_MagSmear" kr (list buffer bins) nil 1 nil nil)))) (define pv-mag-squared (lambda (buffer) (mk-ugen (list "PV_MagSquared" kr (list buffer) nil 1 nil nil)))) (define pv-max (lambda (bufferA bufferB) (mk-ugen (list "PV_Max" kr (list bufferA bufferB) nil 1 nil nil)))) (define pv-min (lambda (bufferA bufferB) (mk-ugen (list "PV_Min" kr (list bufferA bufferB) nil 1 nil nil)))) (define pv-mul (lambda (bufferA bufferB) (mk-ugen (list "PV_Mul" kr (list bufferA bufferB) nil 1 nil nil)))) (define pv-phase-shift (lambda (buffer shift integrate) (mk-ugen (list "PV_PhaseShift" kr (list buffer shift integrate) nil 1 nil nil)))) (define pv-phase-shift270 (lambda (buffer) (mk-ugen (list "PV_PhaseShift270" kr (list buffer) nil 1 nil nil)))) (define pv-phase-shift90 (lambda (buffer) (mk-ugen (list "PV_PhaseShift90" kr (list buffer) nil 1 nil nil)))) (define pv-rand-comb (lambda (buffer wipe trig) (mk-ugen (list "PV_RandComb" kr (list buffer wipe trig) nil 1 nil (incr-uid 1))))) (define pv-rand-wipe (lambda (bufferA bufferB wipe trig) (mk-ugen (list "PV_RandWipe" kr (list bufferA bufferB wipe trig) nil 1 nil (incr-uid 1))))) (define pv-rect-comb (lambda (buffer numTeeth phase width) (mk-ugen (list "PV_RectComb" kr (list buffer numTeeth phase width) nil 1 nil nil)))) (define pv-rect-comb2 (lambda (bufferA bufferB numTeeth phase width) (mk-ugen (list "PV_RectComb2" kr (list bufferA bufferB numTeeth phase width) nil 1 nil nil)))) (define pv-split (lambda (bufferA bufferB) (mk-ugen (list "PV_Split" kr (list bufferA bufferB) nil 2 nil nil)))) (define pan2 (lambda (input pos level) (mk-ugen (list "Pan2" (list 0) (list input pos level) nil 2 nil nil)))) (define pan4 (lambda (rt input xpos ypos level) (mk-ugen (list "Pan4" rt (list input xpos ypos level) nil 4 nil nil)))) (define pan-az (lambda (nc input pos level width orientation) (mk-ugen (list "PanAz" (list 0) (list input pos level width orientation) nil nc nil nil)))) (define pan-b (lambda (rt input azimuth elevation gain) (mk-ugen (list "PanB" rt (list input azimuth elevation gain) nil 4 nil nil)))) (define pan-b2 (lambda (rt input azimuth gain) (mk-ugen (list "PanB2" rt (list input azimuth gain) nil 3 nil nil)))) (define part-conv (lambda (input fftsize irbufnum) (mk-ugen (list "PartConv" ar (list input fftsize irbufnum) nil 1 nil nil)))) (define pause (lambda (rt gate id_) (mk-ugen (list "Pause" rt (list gate id_) nil 1 nil nil)))) (define pause-self (lambda (rt input) (mk-ugen (list "PauseSelf" rt (list input) nil 1 nil nil)))) (define pause-self-when-done (lambda (rt src) (mk-ugen (list "PauseSelfWhenDone" rt (list src) nil 1 nil nil)))) (define peak (lambda (input trig) (mk-ugen (list "Peak" (list 0) (list input trig) nil 1 nil nil)))) (define peak-follower (lambda (input decay) (mk-ugen (list "PeakFollower" (list 0) (list input decay) nil 1 nil nil)))) (define phasor (lambda (rt trig rate_ start end resetPos) (mk-ugen (list "Phasor" rt (list trig rate_ start end resetPos) nil 1 nil nil)))) (define pink-noise (lambda (rt) (mk-ugen (list "PinkNoise" rt nil nil 1 nil (incr-uid 1))))) (define pitch (lambda (input initFreq minFreq maxFreq execFreq maxBinsPerOctave median ampThreshold peakThreshold downSample clar) (mk-ugen (list "Pitch" kr (list input initFreq minFreq maxFreq execFreq maxBinsPerOctave median ampThreshold peakThreshold downSample clar) nil 2 nil nil)))) (define pitch-shift (lambda (input windowSize pitchRatio pitchDispersion timeDispersion) (mk-ugen (list "PitchShift" (list 0) (list input windowSize pitchRatio pitchDispersion timeDispersion) nil 1 nil nil)))) (define play-buf (lambda (nc rt bufnum rate_ trigger startPos loop doneAction) (mk-ugen (list "PlayBuf" rt (list bufnum rate_ trigger startPos loop doneAction) nil nc nil nil)))) (define pluck (lambda (input trig maxdelaytime delaytime decaytime coef) (mk-ugen (list "Pluck" (list 0) (list input trig maxdelaytime delaytime decaytime coef) nil 1 nil nil)))) (define poll (lambda (trig input label_ trigid) (mk-ugen (list "Poll" (list 1) (list trig input label_ trigid) nil 1 nil nil)))) (define pulse (lambda (rt freq width) (mk-ugen (list "Pulse" rt (list freq width) nil 1 nil nil)))) (define pulse-count (lambda (trig reset) (mk-ugen (list "PulseCount" (list 0) (list trig reset) nil 1 nil nil)))) (define pulse-divider (lambda (trig div_ start) (mk-ugen (list "PulseDivider" (list 0) (list trig div_ start) nil 1 nil nil)))) (define quad-c (lambda (rt freq a b c xi) (mk-ugen (list "QuadC" rt (list freq a b c xi) nil 1 nil nil)))) (define quad-l (lambda (rt freq a b c xi) (mk-ugen (list "QuadL" rt (list freq a b c xi) nil 1 nil nil)))) (define quad-n (lambda (rt freq a b c xi) (mk-ugen (list "QuadN" rt (list freq a b c xi) nil 1 nil nil)))) (define r-delay-map (lambda (bufnum input dynamic spec) (mk-ugen (list "RDelayMap" (list 1) (list bufnum input dynamic) spec 1 nil nil)))) (define r-delay-set (lambda (rt input spec) (mk-ugen (list "RDelaySet" rt (list input spec) nil 1 nil nil)))) (define r-delay-set-b (lambda (rt bufnum input spec) (mk-ugen (list "RDelaySetB" rt (list bufnum input spec) nil 1 nil nil)))) (define r-freezer (lambda (rt bufnum left right gain increment incrementOffset incrementRandom rightRandom syncPhaseTrigger randomizePhaseTrigger numberOfLoops) (mk-ugen (list "RFreezer" rt (list bufnum left right gain increment incrementOffset incrementRandom rightRandom syncPhaseTrigger randomizePhaseTrigger numberOfLoops) nil 1 nil nil)))) (define rhpf (lambda (input freq rq) (mk-ugen (list "RHPF" (list 0) (list input freq rq) nil 1 nil nil)))) (define rlpf (lambda (input freq rq) (mk-ugen (list "RLPF" (list 0) (list input freq rq) nil 1 nil nil)))) (define r-loop-set (lambda (rt bufnum left right gain increment spec) (mk-ugen (list "RLoopSet" rt (list bufnum left right gain increment spec) nil 1 nil nil)))) (define r-play-trace (lambda (rt bufnum degree rate_ axis) (mk-ugen (list "RPlayTrace" rt (list bufnum degree rate_ axis) nil 1 nil nil)))) (define r-shuffler-b (lambda (bufnum readLocationMinima readLocationMaxima readIncrementMinima readIncrementMaxima durationMinima durationMaxima envelopeAmplitudeMinima envelopeAmplitudeMaxima envelopeShapeMinima envelopeShapeMaxima envelopeSkewMinima envelopeSkewMaxima stereoLocationMinima stereoLocationMaxima interOffsetTimeMinima interOffsetTimeMaxima ftableReadLocationIncrement readIncrementQuanta interOffsetTimeQuanta) (mk-ugen (list "RShufflerB" ar (list bufnum readLocationMinima readLocationMaxima readIncrementMinima readIncrementMaxima durationMinima durationMaxima envelopeAmplitudeMinima envelopeAmplitudeMaxima envelopeShapeMinima envelopeShapeMaxima envelopeSkewMinima envelopeSkewMaxima stereoLocationMinima stereoLocationMaxima interOffsetTimeMinima interOffsetTimeMaxima ftableReadLocationIncrement readIncrementQuanta interOffsetTimeQuanta) nil 2 nil nil)))) (define r-shuffler-l (lambda (rt input fragmentSize maxDelay) (mk-ugen (list "RShufflerL" rt (list input fragmentSize maxDelay) nil 1 nil nil)))) (define r-trace-rd (lambda (rt bufnum degree index axis) (mk-ugen (list "RTraceRd" rt (list bufnum degree index axis) nil 1 nil nil)))) (define r-trace-rd-x (lambda (rt bufnum degree index) (mk-ugen (list "RTraceRdX" rt (list bufnum degree index) nil 1 nil nil)))) (define r-trace-rd-y (lambda (rt bufnum degree index) (mk-ugen (list "RTraceRdY" rt (list bufnum degree index) nil 1 nil nil)))) (define r-trace-rd-z (lambda (rt bufnum degree index) (mk-ugen (list "RTraceRdZ" rt (list bufnum degree index) nil 1 nil nil)))) (define radians-per-sample (mk-ugen (list "RadiansPerSample" ir nil nil 1 nil nil))) (define ramp (lambda (input lagTime) (mk-ugen (list "Ramp" (list 0) (list input lagTime) nil 1 nil nil)))) (define rand (lambda (lo hi) (mk-ugen (list "Rand" ir (list lo hi) nil 1 nil (incr-uid 1))))) (define rand-id (lambda (rt id_) (mk-ugen (list "RandID" rt (list id_) nil 1 nil nil)))) (define rand-seed (lambda (rt trig seed) (mk-ugen (list "RandSeed" rt (list trig seed) nil 1 nil nil)))) (define record-buf (lambda (rt bufnum offset recLevel preLevel run loop trigger doneAction inputArray) (mk-ugen (list "RecordBuf" rt (list bufnum offset recLevel preLevel run loop trigger doneAction) inputArray 1 nil nil)))) (define replace-out (lambda (bus input) (mk-ugen (list "ReplaceOut" (list 1) (list bus) input 1 nil nil)))) (define resonz (lambda (input freq bwr) (mk-ugen (list "Resonz" (list 0) (list input freq bwr) nil 1 nil nil)))) (define ringz (lambda (input freq decaytime) (mk-ugen (list "Ringz" (list 0) (list input freq decaytime) nil 1 nil nil)))) (define rotate2 (lambda (x y pos) (mk-ugen (list "Rotate2" (list 0 1) (list x y pos) nil 2 nil nil)))) (define running-max (lambda (input trig) (mk-ugen (list "RunningMax" (list 0) (list input trig) nil 1 nil nil)))) (define running-min (lambda (input trig) (mk-ugen (list "RunningMin" (list 0) (list input trig) nil 1 nil nil)))) (define running-sum (lambda (input numsamp) (mk-ugen (list "RunningSum" (list 0) (list input numsamp) nil 1 nil nil)))) (define sos (lambda (input a0 a1 a2 b1 b2) (mk-ugen (list "SOS" (list 0) (list input a0 a1 a2 b1 b2) nil 1 nil nil)))) (define sample-dur (mk-ugen (list "SampleDur" ir nil nil 1 nil nil))) (define sample-rate (mk-ugen (list "SampleRate" ir nil nil 1 nil nil))) (define saw (lambda (rt freq) (mk-ugen (list "Saw" rt (list freq) nil 1 nil nil)))) (define schmidt (lambda (rt input lo hi) (mk-ugen (list "Schmidt" rt (list input lo hi) nil 1 nil nil)))) (define scope-out (lambda (rt inputArray bufnum) (mk-ugen (list "ScopeOut" rt (list inputArray bufnum) nil 1 nil nil)))) (define scope-out2 (lambda (rt inputArray scopeNum maxFrames scopeFrames) (mk-ugen (list "ScopeOut2" rt (list inputArray scopeNum maxFrames scopeFrames) nil 1 nil nil)))) (define select (lambda (which array) (mk-ugen (list "Select" (list 0 1) (list which) array 1 nil nil)))) (define send-trig (lambda (input id_ value) (mk-ugen (list "SendTrig" (list 0) (list input id_ value) nil 1 nil nil)))) (define set-reset-ff (lambda (trig reset) (mk-ugen (list "SetResetFF" (list 0) (list trig reset) nil 1 nil nil)))) (define shaper (lambda (bufnum input) (mk-ugen (list "Shaper" (list 1) (list bufnum input) nil 1 nil nil)))) (define sin-osc (lambda (rt freq phase) (mk-ugen (list "SinOsc" rt (list freq phase) nil 1 nil nil)))) (define sin-osc-fb (lambda (rt freq feedback) (mk-ugen (list "SinOscFB" rt (list freq feedback) nil 1 nil nil)))) (define slew (lambda (input up dn) (mk-ugen (list "Slew" (list 0) (list input up dn) nil 1 nil nil)))) (define slope (lambda (input) (mk-ugen (list "Slope" (list 0) (list input) nil 1 nil nil)))) (define spec-centroid (lambda (rt buffer) (mk-ugen (list "SpecCentroid" rt (list buffer) nil 1 nil nil)))) (define spec-flatness (lambda (rt buffer) (mk-ugen (list "SpecFlatness" rt (list buffer) nil 1 nil nil)))) (define spec-pcile (lambda (rt buffer fraction interpolate) (mk-ugen (list "SpecPcile" rt (list buffer fraction interpolate) nil 1 nil nil)))) (define spring (lambda (rt input spring damp) (mk-ugen (list "Spring" rt (list input spring damp) nil 1 nil nil)))) (define standard-l (lambda (rt freq k xi yi) (mk-ugen (list "StandardL" rt (list freq k xi yi) nil 1 nil nil)))) (define standard-n (lambda (rt freq k xi yi) (mk-ugen (list "StandardN" rt (list freq k xi yi) nil 1 nil nil)))) (define stepper (lambda (trig reset min_ max_ step resetval) (mk-ugen (list "Stepper" (list 0) (list trig reset min_ max_ step resetval) nil 1 nil nil)))) (define stereo-convolution2l (lambda (rt input kernelL kernelR trigger framesize crossfade) (mk-ugen (list "StereoConvolution2L" rt (list input kernelL kernelR trigger framesize crossfade) nil 2 nil nil)))) (define subsample-offset (mk-ugen (list "SubsampleOffset" ir nil nil 1 nil nil))) (define sum3 (lambda (in0 in1 in2) (mk-ugen (list "Sum3" (list 0 1 2) (list in0 in1 in2) nil 1 nil nil)))) (define sum4 (lambda (in0 in1 in2 in3) (mk-ugen (list "Sum4" (list 0 1 2 3) (list in0 in1 in2 in3) nil 1 nil nil)))) (define sweep (lambda (trig rate_) (mk-ugen (list "Sweep" (list 0) (list trig rate_) nil 1 nil nil)))) (define sync-saw (lambda (rt syncFreq sawFreq) (mk-ugen (list "SyncSaw" rt (list syncFreq sawFreq) nil 1 nil nil)))) (define t2a (lambda (input offset) (mk-ugen (list "T2A" ar (list input offset) nil 1 nil nil)))) (define t2k (lambda (rt input) (mk-ugen (list "T2K" rt (list input) nil 1 nil nil)))) (define t-ball (lambda (rt input g damp friction) (mk-ugen (list "TBall" rt (list input g damp friction) nil 1 nil nil)))) (define t-delay (lambda (input dur) (mk-ugen (list "TDelay" (list 0) (list input dur) nil 1 nil nil)))) (define t-duty (lambda (rt dur reset doneAction level gapFirst) (mk-ugen (list "TDuty" rt (list dur reset doneAction level gapFirst) nil 1 nil nil)))) (define t-exp-rand (lambda (lo hi trig) (mk-ugen (list "TExpRand" (list 2) (list lo hi trig) nil 1 nil (incr-uid 1))))) (define t-grains (lambda (nc trigger bufnum rate_ centerPos dur pan amp interp) (mk-ugen (list "TGrains" ar (list trigger bufnum rate_ centerPos dur pan amp interp) nil nc nil nil)))) (define ti-rand (lambda (lo hi trig) (mk-ugen (list "TIRand" (list 2) (list lo hi trig) nil 1 nil (incr-uid 1))))) (define t-rand (lambda (lo hi trig) (mk-ugen (list "TRand" (list 2) (list lo hi trig) nil 1 nil (incr-uid 1))))) (define t-windex (lambda (input normalize array) (mk-ugen (list "TWindex" (list 0) (list input normalize) array 1 nil (incr-uid 1))))) (define tap (lambda (nc rt bufnum delaytime) (mk-ugen (list "Tap" rt (list bufnum delaytime) nil nc nil nil)))) (define timer (lambda (trig) (mk-ugen (list "Timer" (list 0) (list trig) nil 1 nil nil)))) (define toggle-ff (lambda (trig) (mk-ugen (list "ToggleFF" (list 0) (list trig) nil 1 nil nil)))) (define trig (lambda (input dur) (mk-ugen (list "Trig" (list 0) (list input dur) nil 1 nil nil)))) (define trig1 (lambda (input dur) (mk-ugen (list "Trig1" (list 0) (list input dur) nil 1 nil nil)))) (define trig-control (lambda (rt values) (mk-ugen (list "TrigControl" rt (list values) nil 1 nil nil)))) (define two-pole (lambda (input freq radius) (mk-ugen (list "TwoPole" (list 0) (list input freq radius) nil 1 nil nil)))) (define two-zero (lambda (input freq radius) (mk-ugen (list "TwoZero" (list 0) (list input freq radius) nil 1 nil nil)))) (define unary-op-ugen (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 nil nil)))) (define v-disk-in (lambda (nc bufnum rate_ loop sendID) (mk-ugen (list "VDiskIn" ar (list bufnum rate_ loop sendID) nil nc nil nil)))) (define v-osc (lambda (rt bufpos freq phase) (mk-ugen (list "VOsc" rt (list bufpos freq phase) nil 1 nil nil)))) (define v-osc3 (lambda (rt bufpos freq1 freq2 freq3) (mk-ugen (list "VOsc3" rt (list bufpos freq1 freq2 freq3) nil 1 nil nil)))) (define var-lag (lambda (rt input time curvature warp start) (mk-ugen (list "VarLag" rt (list input time curvature warp start) nil 1 nil nil)))) (define var-saw (lambda (rt freq iphase width) (mk-ugen (list "VarSaw" rt (list freq iphase width) nil 1 nil nil)))) (define vibrato (lambda (rt freq rate_ depth delay onset rateVariation depthVariation iphase) (mk-ugen (list "Vibrato" rt (list freq rate_ depth delay onset rateVariation depthVariation iphase) nil 1 nil (incr-uid 1))))) (define warp1 (lambda (nc bufnum pointer freqScale windowSize envbufnum overlaps windowRandRatio interp) (mk-ugen (list "Warp1" ar (list bufnum pointer freqScale windowSize envbufnum overlaps windowRandRatio interp) nil nc nil nil)))) (define white-noise (lambda (rt) (mk-ugen (list "WhiteNoise" rt nil nil 1 nil (incr-uid 1))))) (define width-first-ugen (lambda (rt maxSize) (mk-ugen (list "WidthFirstUGen" rt (list maxSize) nil 1 nil nil)))) (define wrap (lambda (input lo hi) (mk-ugen (list "Wrap" (list 0) (list input lo hi) nil 1 nil nil)))) (define wrap-index (lambda (bufnum input) (mk-ugen (list "WrapIndex" (list 1) (list bufnum input) nil 1 nil nil)))) (define x-fade2 (lambda (inA inB pan level) (mk-ugen (list "XFade2" (list 0 1) (list inA inB pan level) nil 1 nil nil)))) (define x-line (lambda (rt start end dur doneAction) (mk-ugen (list "XLine" rt (list start end dur doneAction) nil 1 nil nil)))) (define x-out (lambda (bus xfade input) (mk-ugen (list "XOut" (list 2) (list bus xfade) input 1 nil nil)))) (define zero-crossing (lambda (input) (mk-ugen (list "ZeroCrossing" (list 0) (list input) nil 1 nil nil)))) (define mul-add (lambda (input mul add) (mk-ugen (list "MulAdd" (list 0) (list input mul add) nil 1 nil nil)))) (define set-buf (lambda (buf offset length_ array) (mk-ugen (list "SetBuf" ir (list buf offset length_) array 1 nil nil)))) (define neg (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 0 nil)))) (define u:not (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 1 nil)))) (define is-nil (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 2 nil)))) (define not-nil (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 3 nil)))) (define bit-not (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 4 nil)))) (define u:abs (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 5 nil)))) (define as-float (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 6 nil)))) (define as-int (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 7 nil)))) (define ceil (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 8 nil)))) (define u:floor (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 9 nil)))) (define frac (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 10 nil)))) (define sign (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 11 nil)))) (define squared (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 12 nil)))) (define cubed (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 13 nil)))) (define u:sqrt (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 14 nil)))) (define u:exp (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 15 nil)))) (define recip (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 16 nil)))) (define midicps (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 17 nil)))) (define cpsmidi (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 18 nil)))) (define midi-ratio (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 19 nil)))) (define ratio-midi (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 20 nil)))) (define db-amp (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 21 nil)))) (define amp-db (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 22 nil)))) (define oct-cps (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 23 nil)))) (define cps-oct (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 24 nil)))) (define u:log (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 25 nil)))) (define log2 (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 26 nil)))) (define log10 (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 27 nil)))) (define u:sin (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 28 nil)))) (define u:cos (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 29 nil)))) (define u:tan (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 30 nil)))) (define arc-sin (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 31 nil)))) (define arc-cos (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 32 nil)))) (define arc-tan (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 33 nil)))) (define sin-h (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 34 nil)))) (define cos-h (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 35 nil)))) (define tan-h (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 36 nil)))) (define rand- (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 37 nil)))) (define rand2 (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 38 nil)))) (define lin-rand- (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 39 nil)))) (define bi-lin-rand (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 40 nil)))) (define sum3rand (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 41 nil)))) (define distort (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 42 nil)))) (define soft-clip (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 43 nil)))) (define coin (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 44 nil)))) (define digit-value (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 45 nil)))) (define silence (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 46 nil)))) (define thru (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 47 nil)))) (define rect-window (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 48 nil)))) (define han-window (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 49 nil)))) (define welch-window (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 50 nil)))) (define tri-window (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 51 nil)))) (define ramp- (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 52 nil)))) (define s-curve (lambda (a) (mk-ugen (list "UnaryOpUGen" (list 0) (list a) nil 1 53 nil)))) (define add (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 0 nil)))) (define sub (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 1 nil)))) (define mul (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 2 nil)))) (define i-div (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 3 nil)))) (define f-div (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 4 nil)))) (define u:mod (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 5 nil)))) (define u:eq (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 6 nil)))) (define ne (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 7 nil)))) (define u:lt (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 8 nil)))) (define u:gt (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 9 nil)))) (define le (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 10 nil)))) (define ge (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 11 nil)))) (define u:min (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 12 nil)))) (define u:max (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 13 nil)))) (define bit-and (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 14 nil)))) (define bit-or (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 15 nil)))) (define bit-xor (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 16 nil)))) (define u:lcm (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 17 nil)))) (define u:gcd (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 18 nil)))) (define u:round (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 19 nil)))) (define round-up (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 20 nil)))) (define trunc (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 21 nil)))) (define atan2 (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 22 nil)))) (define hypot (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 23 nil)))) (define hypotx (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 24 nil)))) (define pow (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 25 nil)))) (define shift-left (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 26 nil)))) (define shift-right (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 27 nil)))) (define unsigned-shift (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 28 nil)))) (define fill (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 29 nil)))) (define ring1 (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 30 nil)))) (define ring2 (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 31 nil)))) (define ring3 (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 32 nil)))) (define ring4 (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 33 nil)))) (define dif-sqr (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 34 nil)))) (define sum-sqr (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 35 nil)))) (define sqr-sum (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 36 nil)))) (define sqr-dif (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 37 nil)))) (define abs-dif (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 38 nil)))) (define thresh (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 39 nil)))) (define am-clip (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 40 nil)))) (define scale-neg (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 41 nil)))) (define clip2 (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 42 nil)))) (define excess (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 43 nil)))) (define fold2 (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 44 nil)))) (define wrap2 (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 45 nil)))) (define first-arg (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 46 nil)))) (define rand-range (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 47 nil)))) (define exp-rand-range (lambda (a b) (mk-ugen (list "BinaryOpUGen" (list 0 1) (list a b) nil 1 48 nil))))
e22e071fd0598b1ae07546b2a58ae1e2b90a3a947c077d34658161553a662d56
mfoemmel/erlang-otp
wxMDIClientWindow.erl
%% %% %CopyrightBegin% %% Copyright Ericsson AB 2008 - 2009 . All Rights Reserved . %% The contents of this file are subject to the Erlang Public License , Version 1.1 , ( the " License " ) ; you may not use this file except in %% compliance with the License. You should have received a copy of the %% Erlang Public License along with this software. If not, it can be %% retrieved online at /. %% Software distributed under the License is distributed on an " AS IS " %% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See %% the License for the specific language governing rights and limitations %% under the License. %% %% %CopyrightEnd% %% This file is generated DO NOT EDIT %% @doc See external documentation: <a href="">wxMDIClientWindow</a>. %% <p>This class is derived (and can use functions) from: %% <br />{@link wxWindow} %% <br />{@link wxEvtHandler} %% </p> %% @type wxMDIClientWindow(). An object reference, The representation is internal %% and can be changed without notice. It can't be used for comparsion %% stored on disc or distributed for use on other nodes. -module(wxMDIClientWindow). -include("wxe.hrl"). -export([createClient/2,createClient/3,destroy/1,new/0,new/1,new/2]). %% inherited exports -export([cacheBestSize/2,captureMouse/1,center/1,center/2,centerOnParent/1, centerOnParent/2,centre/1,centre/2,centreOnParent/1,centreOnParent/2, clearBackground/1,clientToScreen/2,clientToScreen/3,close/1,close/2, connect/2,connect/3,convertDialogToPixels/2,convertPixelsToDialog/2, destroyChildren/1,disable/1,disconnect/1,disconnect/2,disconnect/3, enable/1,enable/2,findWindow/2,fit/1,fitInside/1,freeze/1,getAcceleratorTable/1, getBackgroundColour/1,getBackgroundStyle/1,getBestSize/1,getCaret/1, getCharHeight/1,getCharWidth/1,getChildren/1,getClientSize/1,getContainingSizer/1, getCursor/1,getDropTarget/1,getEventHandler/1,getExtraStyle/1,getFont/1, getForegroundColour/1,getGrandParent/1,getHandle/1,getHelpText/1, getId/1,getLabel/1,getMaxSize/1,getMinSize/1,getName/1,getParent/1, getPosition/1,getRect/1,getScreenPosition/1,getScreenRect/1,getScrollPos/2, getScrollRange/2,getScrollThumb/2,getSize/1,getSizer/1,getTextExtent/2, getTextExtent/3,getToolTip/1,getUpdateRegion/1,getVirtualSize/1,getWindowStyleFlag/1, getWindowVariant/1,hasCapture/1,hasScrollbar/2,hasTransparentBackground/1, hide/1,inheritAttributes/1,initDialog/1,invalidateBestSize/1,isEnabled/1, isExposed/2,isExposed/3,isExposed/5,isRetained/1,isShown/1,isTopLevel/1, layout/1,lineDown/1,lineUp/1,lower/1,makeModal/1,makeModal/2,move/2, move/3,move/4,moveAfterInTabOrder/2,moveBeforeInTabOrder/2,navigate/1, navigate/2,pageDown/1,pageUp/1,parent_class/1,popEventHandler/1,popEventHandler/2, popupMenu/2,popupMenu/3,popupMenu/4,raise/1,refresh/1,refresh/2,refreshRect/2, refreshRect/3,releaseMouse/1,removeChild/2,reparent/2,screenToClient/1, screenToClient/2,scrollLines/2,scrollPages/2,scrollWindow/3,scrollWindow/4, setAcceleratorTable/2,setAutoLayout/2,setBackgroundColour/2,setBackgroundStyle/2, setCaret/2,setClientSize/2,setClientSize/3,setContainingSizer/2,setCursor/2, setDropTarget/2,setExtraStyle/2,setFocus/1,setFocusFromKbd/1,setFont/2, setForegroundColour/2,setHelpText/2,setId/2,setLabel/2,setMaxSize/2, setMinSize/2,setName/2,setOwnBackgroundColour/2,setOwnFont/2,setOwnForegroundColour/2, setPalette/2,setScrollPos/3,setScrollPos/4,setScrollbar/5,setScrollbar/6, setSize/2,setSize/3,setSize/5,setSize/6,setSizeHints/2,setSizeHints/3, setSizeHints/4,setSizer/2,setSizer/3,setSizerAndFit/2,setSizerAndFit/3, setThemeEnabled/2,setToolTip/2,setVirtualSize/2,setVirtualSize/3, setVirtualSizeHints/2,setVirtualSizeHints/3,setVirtualSizeHints/4, setWindowStyle/2,setWindowStyleFlag/2,setWindowVariant/2,shouldInheritColours/1, show/1,show/2,thaw/1,transferDataFromWindow/1,transferDataToWindow/1, update/1,updateWindowUI/1,updateWindowUI/2,validate/1,warpPointer/3]). %% @hidden parent_class(wxWindow) -> true; parent_class(wxEvtHandler) -> true; parent_class(_Class) -> erlang:error({badtype, ?MODULE}). ( ) - > wxMDIClientWindow ( ) %% @doc See <a href="#wxmdiclientwindowwxmdiclientwindow">external documentation</a>. new() -> wxe_util:construct(?wxMDIClientWindow_new_0, <<>>). ( Parent::wxMDIParentFrame : wxMDIParentFrame ( ) ) - > wxMDIClientWindow ( ) %% @equiv new(Parent, []) new(Parent) when is_record(Parent, wx_ref) -> new(Parent, []). ( Parent::wxMDIParentFrame : wxMDIParentFrame ( ) , [ Option ] ) - > wxMDIClientWindow ( ) %% Option = {style, integer()} %% @doc See <a href="#wxmdiclientwindowwxmdiclientwindow">external documentation</a>. new(#wx_ref{type=ParentT,ref=ParentRef}, Options) when is_list(Options) -> ?CLASS(ParentT,wxMDIParentFrame), MOpts = fun({style, Style}, Acc) -> [<<1:32/?UI,Style:32/?UI>>|Acc]; (BadOpt, _) -> erlang:error({badoption, BadOpt}) end, BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)), wxe_util:construct(?wxMDIClientWindow_new_2, <<ParentRef:32/?UI, 0:32,BinOpt/binary>>). %% @spec (This::wxMDIClientWindow(), Parent::wxMDIParentFrame:wxMDIParentFrame()) -> bool() %% @equiv createClient(This,Parent, []) createClient(This,Parent) when is_record(This, wx_ref),is_record(Parent, wx_ref) -> createClient(This,Parent, []). %% @spec (This::wxMDIClientWindow(), Parent::wxMDIParentFrame:wxMDIParentFrame(), [Option]) -> bool() %% Option = {style, integer()} %% @doc See <a href="#wxmdiclientwindowcreateclient">external documentation</a>. createClient(#wx_ref{type=ThisT,ref=ThisRef},#wx_ref{type=ParentT,ref=ParentRef}, Options) when is_list(Options) -> ?CLASS(ThisT,wxMDIClientWindow), ?CLASS(ParentT,wxMDIParentFrame), MOpts = fun({style, Style}, Acc) -> [<<1:32/?UI,Style:32/?UI>>|Acc]; (BadOpt, _) -> erlang:error({badoption, BadOpt}) end, BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)), wxe_util:call(?wxMDIClientWindow_CreateClient, <<ThisRef:32/?UI,ParentRef:32/?UI, BinOpt/binary>>). %% @spec (This::wxMDIClientWindow()) -> ok %% @doc Destroys this object, do not use object again destroy(Obj=#wx_ref{type=Type}) -> ?CLASS(Type,wxMDIClientWindow), wxe_util:destroy(?DESTROY_OBJECT,Obj), ok. %% From wxWindow %% @hidden warpPointer(This,X,Y) -> wxWindow:warpPointer(This,X,Y). %% @hidden validate(This) -> wxWindow:validate(This). %% @hidden updateWindowUI(This, Options) -> wxWindow:updateWindowUI(This, Options). %% @hidden updateWindowUI(This) -> wxWindow:updateWindowUI(This). %% @hidden update(This) -> wxWindow:update(This). %% @hidden transferDataToWindow(This) -> wxWindow:transferDataToWindow(This). %% @hidden transferDataFromWindow(This) -> wxWindow:transferDataFromWindow(This). %% @hidden thaw(This) -> wxWindow:thaw(This). %% @hidden show(This, Options) -> wxWindow:show(This, Options). %% @hidden show(This) -> wxWindow:show(This). %% @hidden shouldInheritColours(This) -> wxWindow:shouldInheritColours(This). %% @hidden setWindowVariant(This,Variant) -> wxWindow:setWindowVariant(This,Variant). %% @hidden setWindowStyleFlag(This,Style) -> wxWindow:setWindowStyleFlag(This,Style). %% @hidden setWindowStyle(This,Style) -> wxWindow:setWindowStyle(This,Style). %% @hidden setVirtualSizeHints(This,MinW,MinH, Options) -> wxWindow:setVirtualSizeHints(This,MinW,MinH, Options). %% @hidden setVirtualSizeHints(This,MinW,MinH) -> wxWindow:setVirtualSizeHints(This,MinW,MinH). %% @hidden setVirtualSizeHints(This,MinSize) -> wxWindow:setVirtualSizeHints(This,MinSize). %% @hidden setVirtualSize(This,X,Y) -> wxWindow:setVirtualSize(This,X,Y). %% @hidden setVirtualSize(This,Size) -> wxWindow:setVirtualSize(This,Size). %% @hidden setToolTip(This,Tip) -> wxWindow:setToolTip(This,Tip). %% @hidden setThemeEnabled(This,EnableTheme) -> wxWindow:setThemeEnabled(This,EnableTheme). %% @hidden setSizerAndFit(This,Sizer, Options) -> wxWindow:setSizerAndFit(This,Sizer, Options). %% @hidden setSizerAndFit(This,Sizer) -> wxWindow:setSizerAndFit(This,Sizer). %% @hidden setSizer(This,Sizer, Options) -> wxWindow:setSizer(This,Sizer, Options). %% @hidden setSizer(This,Sizer) -> wxWindow:setSizer(This,Sizer). %% @hidden setSizeHints(This,MinW,MinH, Options) -> wxWindow:setSizeHints(This,MinW,MinH, Options). %% @hidden setSizeHints(This,MinW,MinH) -> wxWindow:setSizeHints(This,MinW,MinH). %% @hidden setSizeHints(This,MinSize) -> wxWindow:setSizeHints(This,MinSize). %% @hidden setSize(This,X,Y,Width,Height, Options) -> wxWindow:setSize(This,X,Y,Width,Height, Options). %% @hidden setSize(This,X,Y,Width,Height) -> wxWindow:setSize(This,X,Y,Width,Height). %% @hidden setSize(This,Width,Height) -> wxWindow:setSize(This,Width,Height). %% @hidden setSize(This,Rect) -> wxWindow:setSize(This,Rect). %% @hidden setScrollPos(This,Orient,Pos, Options) -> wxWindow:setScrollPos(This,Orient,Pos, Options). %% @hidden setScrollPos(This,Orient,Pos) -> wxWindow:setScrollPos(This,Orient,Pos). %% @hidden setScrollbar(This,Orient,Pos,ThumbVisible,Range, Options) -> wxWindow:setScrollbar(This,Orient,Pos,ThumbVisible,Range, Options). %% @hidden setScrollbar(This,Orient,Pos,ThumbVisible,Range) -> wxWindow:setScrollbar(This,Orient,Pos,ThumbVisible,Range). %% @hidden setPalette(This,Pal) -> wxWindow:setPalette(This,Pal). %% @hidden setName(This,Name) -> wxWindow:setName(This,Name). %% @hidden setLabel(This,Label) -> wxWindow:setLabel(This,Label). %% @hidden setId(This,Winid) -> wxWindow:setId(This,Winid). %% @hidden setHelpText(This,Text) -> wxWindow:setHelpText(This,Text). %% @hidden setForegroundColour(This,Colour) -> wxWindow:setForegroundColour(This,Colour). %% @hidden setFont(This,Font) -> wxWindow:setFont(This,Font). %% @hidden setFocusFromKbd(This) -> wxWindow:setFocusFromKbd(This). %% @hidden setFocus(This) -> wxWindow:setFocus(This). %% @hidden setExtraStyle(This,ExStyle) -> wxWindow:setExtraStyle(This,ExStyle). %% @hidden setDropTarget(This,DropTarget) -> wxWindow:setDropTarget(This,DropTarget). %% @hidden setOwnForegroundColour(This,Colour) -> wxWindow:setOwnForegroundColour(This,Colour). %% @hidden setOwnFont(This,Font) -> wxWindow:setOwnFont(This,Font). %% @hidden setOwnBackgroundColour(This,Colour) -> wxWindow:setOwnBackgroundColour(This,Colour). %% @hidden setMinSize(This,MinSize) -> wxWindow:setMinSize(This,MinSize). %% @hidden setMaxSize(This,MaxSize) -> wxWindow:setMaxSize(This,MaxSize). %% @hidden setCursor(This,Cursor) -> wxWindow:setCursor(This,Cursor). %% @hidden setContainingSizer(This,Sizer) -> wxWindow:setContainingSizer(This,Sizer). %% @hidden setClientSize(This,Width,Height) -> wxWindow:setClientSize(This,Width,Height). %% @hidden setClientSize(This,Size) -> wxWindow:setClientSize(This,Size). %% @hidden setCaret(This,Caret) -> wxWindow:setCaret(This,Caret). %% @hidden setBackgroundStyle(This,Style) -> wxWindow:setBackgroundStyle(This,Style). %% @hidden setBackgroundColour(This,Colour) -> wxWindow:setBackgroundColour(This,Colour). %% @hidden setAutoLayout(This,AutoLayout) -> wxWindow:setAutoLayout(This,AutoLayout). %% @hidden setAcceleratorTable(This,Accel) -> wxWindow:setAcceleratorTable(This,Accel). %% @hidden scrollWindow(This,Dx,Dy, Options) -> wxWindow:scrollWindow(This,Dx,Dy, Options). %% @hidden scrollWindow(This,Dx,Dy) -> wxWindow:scrollWindow(This,Dx,Dy). %% @hidden scrollPages(This,Pages) -> wxWindow:scrollPages(This,Pages). %% @hidden scrollLines(This,Lines) -> wxWindow:scrollLines(This,Lines). %% @hidden screenToClient(This,Pt) -> wxWindow:screenToClient(This,Pt). %% @hidden screenToClient(This) -> wxWindow:screenToClient(This). %% @hidden reparent(This,NewParent) -> wxWindow:reparent(This,NewParent). %% @hidden removeChild(This,Child) -> wxWindow:removeChild(This,Child). %% @hidden releaseMouse(This) -> wxWindow:releaseMouse(This). %% @hidden refreshRect(This,Rect, Options) -> wxWindow:refreshRect(This,Rect, Options). %% @hidden refreshRect(This,Rect) -> wxWindow:refreshRect(This,Rect). %% @hidden refresh(This, Options) -> wxWindow:refresh(This, Options). %% @hidden refresh(This) -> wxWindow:refresh(This). %% @hidden raise(This) -> wxWindow:raise(This). %% @hidden popupMenu(This,Menu,X,Y) -> wxWindow:popupMenu(This,Menu,X,Y). %% @hidden popupMenu(This,Menu, Options) -> wxWindow:popupMenu(This,Menu, Options). %% @hidden popupMenu(This,Menu) -> wxWindow:popupMenu(This,Menu). %% @hidden popEventHandler(This, Options) -> wxWindow:popEventHandler(This, Options). %% @hidden popEventHandler(This) -> wxWindow:popEventHandler(This). %% @hidden pageUp(This) -> wxWindow:pageUp(This). %% @hidden pageDown(This) -> wxWindow:pageDown(This). %% @hidden navigate(This, Options) -> wxWindow:navigate(This, Options). %% @hidden navigate(This) -> wxWindow:navigate(This). %% @hidden moveBeforeInTabOrder(This,Win) -> wxWindow:moveBeforeInTabOrder(This,Win). %% @hidden moveAfterInTabOrder(This,Win) -> wxWindow:moveAfterInTabOrder(This,Win). %% @hidden move(This,X,Y, Options) -> wxWindow:move(This,X,Y, Options). %% @hidden move(This,X,Y) -> wxWindow:move(This,X,Y). %% @hidden move(This,Pt) -> wxWindow:move(This,Pt). %% @hidden makeModal(This, Options) -> wxWindow:makeModal(This, Options). %% @hidden makeModal(This) -> wxWindow:makeModal(This). %% @hidden lower(This) -> wxWindow:lower(This). %% @hidden lineUp(This) -> wxWindow:lineUp(This). %% @hidden lineDown(This) -> wxWindow:lineDown(This). %% @hidden layout(This) -> wxWindow:layout(This). %% @hidden isTopLevel(This) -> wxWindow:isTopLevel(This). %% @hidden isShown(This) -> wxWindow:isShown(This). %% @hidden isRetained(This) -> wxWindow:isRetained(This). %% @hidden isExposed(This,X,Y,W,H) -> wxWindow:isExposed(This,X,Y,W,H). %% @hidden isExposed(This,X,Y) -> wxWindow:isExposed(This,X,Y). %% @hidden isExposed(This,Pt) -> wxWindow:isExposed(This,Pt). %% @hidden isEnabled(This) -> wxWindow:isEnabled(This). %% @hidden invalidateBestSize(This) -> wxWindow:invalidateBestSize(This). %% @hidden initDialog(This) -> wxWindow:initDialog(This). %% @hidden inheritAttributes(This) -> wxWindow:inheritAttributes(This). %% @hidden hide(This) -> wxWindow:hide(This). %% @hidden hasTransparentBackground(This) -> wxWindow:hasTransparentBackground(This). %% @hidden hasScrollbar(This,Orient) -> wxWindow:hasScrollbar(This,Orient). %% @hidden hasCapture(This) -> wxWindow:hasCapture(This). %% @hidden getWindowVariant(This) -> wxWindow:getWindowVariant(This). %% @hidden getWindowStyleFlag(This) -> wxWindow:getWindowStyleFlag(This). %% @hidden getVirtualSize(This) -> wxWindow:getVirtualSize(This). %% @hidden getUpdateRegion(This) -> wxWindow:getUpdateRegion(This). %% @hidden getToolTip(This) -> wxWindow:getToolTip(This). %% @hidden getTextExtent(This,String, Options) -> wxWindow:getTextExtent(This,String, Options). %% @hidden getTextExtent(This,String) -> wxWindow:getTextExtent(This,String). %% @hidden getSizer(This) -> wxWindow:getSizer(This). %% @hidden getSize(This) -> wxWindow:getSize(This). %% @hidden getScrollThumb(This,Orient) -> wxWindow:getScrollThumb(This,Orient). %% @hidden getScrollRange(This,Orient) -> wxWindow:getScrollRange(This,Orient). %% @hidden getScrollPos(This,Orient) -> wxWindow:getScrollPos(This,Orient). %% @hidden getScreenRect(This) -> wxWindow:getScreenRect(This). %% @hidden getScreenPosition(This) -> wxWindow:getScreenPosition(This). %% @hidden getRect(This) -> wxWindow:getRect(This). %% @hidden getPosition(This) -> wxWindow:getPosition(This). %% @hidden getParent(This) -> wxWindow:getParent(This). %% @hidden getName(This) -> wxWindow:getName(This). %% @hidden getMinSize(This) -> wxWindow:getMinSize(This). %% @hidden getMaxSize(This) -> wxWindow:getMaxSize(This). %% @hidden getLabel(This) -> wxWindow:getLabel(This). %% @hidden getId(This) -> wxWindow:getId(This). %% @hidden getHelpText(This) -> wxWindow:getHelpText(This). %% @hidden getHandle(This) -> wxWindow:getHandle(This). %% @hidden getGrandParent(This) -> wxWindow:getGrandParent(This). %% @hidden getForegroundColour(This) -> wxWindow:getForegroundColour(This). %% @hidden getFont(This) -> wxWindow:getFont(This). %% @hidden getExtraStyle(This) -> wxWindow:getExtraStyle(This). %% @hidden getEventHandler(This) -> wxWindow:getEventHandler(This). %% @hidden getDropTarget(This) -> wxWindow:getDropTarget(This). %% @hidden getCursor(This) -> wxWindow:getCursor(This). %% @hidden getContainingSizer(This) -> wxWindow:getContainingSizer(This). %% @hidden getClientSize(This) -> wxWindow:getClientSize(This). %% @hidden getChildren(This) -> wxWindow:getChildren(This). %% @hidden getCharWidth(This) -> wxWindow:getCharWidth(This). %% @hidden getCharHeight(This) -> wxWindow:getCharHeight(This). %% @hidden getCaret(This) -> wxWindow:getCaret(This). %% @hidden getBestSize(This) -> wxWindow:getBestSize(This). %% @hidden getBackgroundStyle(This) -> wxWindow:getBackgroundStyle(This). %% @hidden getBackgroundColour(This) -> wxWindow:getBackgroundColour(This). %% @hidden getAcceleratorTable(This) -> wxWindow:getAcceleratorTable(This). %% @hidden freeze(This) -> wxWindow:freeze(This). %% @hidden fitInside(This) -> wxWindow:fitInside(This). %% @hidden fit(This) -> wxWindow:fit(This). %% @hidden findWindow(This,Winid) -> wxWindow:findWindow(This,Winid). %% @hidden enable(This, Options) -> wxWindow:enable(This, Options). %% @hidden enable(This) -> wxWindow:enable(This). %% @hidden disable(This) -> wxWindow:disable(This). %% @hidden destroyChildren(This) -> wxWindow:destroyChildren(This). %% @hidden convertPixelsToDialog(This,Sz) -> wxWindow:convertPixelsToDialog(This,Sz). %% @hidden convertDialogToPixels(This,Sz) -> wxWindow:convertDialogToPixels(This,Sz). %% @hidden close(This, Options) -> wxWindow:close(This, Options). %% @hidden close(This) -> wxWindow:close(This). %% @hidden clientToScreen(This,X,Y) -> wxWindow:clientToScreen(This,X,Y). %% @hidden clientToScreen(This,Pt) -> wxWindow:clientToScreen(This,Pt). %% @hidden clearBackground(This) -> wxWindow:clearBackground(This). %% @hidden centreOnParent(This, Options) -> wxWindow:centreOnParent(This, Options). %% @hidden centreOnParent(This) -> wxWindow:centreOnParent(This). %% @hidden centre(This, Options) -> wxWindow:centre(This, Options). %% @hidden centre(This) -> wxWindow:centre(This). %% @hidden centerOnParent(This, Options) -> wxWindow:centerOnParent(This, Options). %% @hidden centerOnParent(This) -> wxWindow:centerOnParent(This). %% @hidden center(This, Options) -> wxWindow:center(This, Options). %% @hidden center(This) -> wxWindow:center(This). %% @hidden captureMouse(This) -> wxWindow:captureMouse(This). %% @hidden cacheBestSize(This,Size) -> wxWindow:cacheBestSize(This,Size). %% From wxEvtHandler %% @hidden disconnect(This,EventType, Options) -> wxEvtHandler:disconnect(This,EventType, Options). %% @hidden disconnect(This,EventType) -> wxEvtHandler:disconnect(This,EventType). %% @hidden disconnect(This) -> wxEvtHandler:disconnect(This). %% @hidden connect(This,EventType, Options) -> wxEvtHandler:connect(This,EventType, Options). %% @hidden connect(This,EventType) -> wxEvtHandler:connect(This,EventType).
null
https://raw.githubusercontent.com/mfoemmel/erlang-otp/9c6fdd21e4e6573ca6f567053ff3ac454d742bc2/lib/wx/src/gen/wxMDIClientWindow.erl
erlang
%CopyrightBegin% compliance with the License. You should have received a copy of the Erlang Public License along with this software. If not, it can be retrieved online at /. basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. %CopyrightEnd% This file is generated DO NOT EDIT @doc See external documentation: <a href="">wxMDIClientWindow</a>. <p>This class is derived (and can use functions) from: <br />{@link wxWindow} <br />{@link wxEvtHandler} </p> @type wxMDIClientWindow(). An object reference, The representation is internal and can be changed without notice. It can't be used for comparsion stored on disc or distributed for use on other nodes. inherited exports @hidden @doc See <a href="#wxmdiclientwindowwxmdiclientwindow">external documentation</a>. @equiv new(Parent, []) Option = {style, integer()} @doc See <a href="#wxmdiclientwindowwxmdiclientwindow">external documentation</a>. @spec (This::wxMDIClientWindow(), Parent::wxMDIParentFrame:wxMDIParentFrame()) -> bool() @equiv createClient(This,Parent, []) @spec (This::wxMDIClientWindow(), Parent::wxMDIParentFrame:wxMDIParentFrame(), [Option]) -> bool() Option = {style, integer()} @doc See <a href="#wxmdiclientwindowcreateclient">external documentation</a>. @spec (This::wxMDIClientWindow()) -> ok @doc Destroys this object, do not use object again From wxWindow @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden @hidden From wxEvtHandler @hidden @hidden @hidden @hidden @hidden
Copyright Ericsson AB 2008 - 2009 . All Rights Reserved . The contents of this file are subject to the Erlang Public License , Version 1.1 , ( the " License " ) ; you may not use this file except in Software distributed under the License is distributed on an " AS IS " -module(wxMDIClientWindow). -include("wxe.hrl"). -export([createClient/2,createClient/3,destroy/1,new/0,new/1,new/2]). -export([cacheBestSize/2,captureMouse/1,center/1,center/2,centerOnParent/1, centerOnParent/2,centre/1,centre/2,centreOnParent/1,centreOnParent/2, clearBackground/1,clientToScreen/2,clientToScreen/3,close/1,close/2, connect/2,connect/3,convertDialogToPixels/2,convertPixelsToDialog/2, destroyChildren/1,disable/1,disconnect/1,disconnect/2,disconnect/3, enable/1,enable/2,findWindow/2,fit/1,fitInside/1,freeze/1,getAcceleratorTable/1, getBackgroundColour/1,getBackgroundStyle/1,getBestSize/1,getCaret/1, getCharHeight/1,getCharWidth/1,getChildren/1,getClientSize/1,getContainingSizer/1, getCursor/1,getDropTarget/1,getEventHandler/1,getExtraStyle/1,getFont/1, getForegroundColour/1,getGrandParent/1,getHandle/1,getHelpText/1, getId/1,getLabel/1,getMaxSize/1,getMinSize/1,getName/1,getParent/1, getPosition/1,getRect/1,getScreenPosition/1,getScreenRect/1,getScrollPos/2, getScrollRange/2,getScrollThumb/2,getSize/1,getSizer/1,getTextExtent/2, getTextExtent/3,getToolTip/1,getUpdateRegion/1,getVirtualSize/1,getWindowStyleFlag/1, getWindowVariant/1,hasCapture/1,hasScrollbar/2,hasTransparentBackground/1, hide/1,inheritAttributes/1,initDialog/1,invalidateBestSize/1,isEnabled/1, isExposed/2,isExposed/3,isExposed/5,isRetained/1,isShown/1,isTopLevel/1, layout/1,lineDown/1,lineUp/1,lower/1,makeModal/1,makeModal/2,move/2, move/3,move/4,moveAfterInTabOrder/2,moveBeforeInTabOrder/2,navigate/1, navigate/2,pageDown/1,pageUp/1,parent_class/1,popEventHandler/1,popEventHandler/2, popupMenu/2,popupMenu/3,popupMenu/4,raise/1,refresh/1,refresh/2,refreshRect/2, refreshRect/3,releaseMouse/1,removeChild/2,reparent/2,screenToClient/1, screenToClient/2,scrollLines/2,scrollPages/2,scrollWindow/3,scrollWindow/4, setAcceleratorTable/2,setAutoLayout/2,setBackgroundColour/2,setBackgroundStyle/2, setCaret/2,setClientSize/2,setClientSize/3,setContainingSizer/2,setCursor/2, setDropTarget/2,setExtraStyle/2,setFocus/1,setFocusFromKbd/1,setFont/2, setForegroundColour/2,setHelpText/2,setId/2,setLabel/2,setMaxSize/2, setMinSize/2,setName/2,setOwnBackgroundColour/2,setOwnFont/2,setOwnForegroundColour/2, setPalette/2,setScrollPos/3,setScrollPos/4,setScrollbar/5,setScrollbar/6, setSize/2,setSize/3,setSize/5,setSize/6,setSizeHints/2,setSizeHints/3, setSizeHints/4,setSizer/2,setSizer/3,setSizerAndFit/2,setSizerAndFit/3, setThemeEnabled/2,setToolTip/2,setVirtualSize/2,setVirtualSize/3, setVirtualSizeHints/2,setVirtualSizeHints/3,setVirtualSizeHints/4, setWindowStyle/2,setWindowStyleFlag/2,setWindowVariant/2,shouldInheritColours/1, show/1,show/2,thaw/1,transferDataFromWindow/1,transferDataToWindow/1, update/1,updateWindowUI/1,updateWindowUI/2,validate/1,warpPointer/3]). parent_class(wxWindow) -> true; parent_class(wxEvtHandler) -> true; parent_class(_Class) -> erlang:error({badtype, ?MODULE}). ( ) - > wxMDIClientWindow ( ) new() -> wxe_util:construct(?wxMDIClientWindow_new_0, <<>>). ( Parent::wxMDIParentFrame : wxMDIParentFrame ( ) ) - > wxMDIClientWindow ( ) new(Parent) when is_record(Parent, wx_ref) -> new(Parent, []). ( Parent::wxMDIParentFrame : wxMDIParentFrame ( ) , [ Option ] ) - > wxMDIClientWindow ( ) new(#wx_ref{type=ParentT,ref=ParentRef}, Options) when is_list(Options) -> ?CLASS(ParentT,wxMDIParentFrame), MOpts = fun({style, Style}, Acc) -> [<<1:32/?UI,Style:32/?UI>>|Acc]; (BadOpt, _) -> erlang:error({badoption, BadOpt}) end, BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)), wxe_util:construct(?wxMDIClientWindow_new_2, <<ParentRef:32/?UI, 0:32,BinOpt/binary>>). createClient(This,Parent) when is_record(This, wx_ref),is_record(Parent, wx_ref) -> createClient(This,Parent, []). createClient(#wx_ref{type=ThisT,ref=ThisRef},#wx_ref{type=ParentT,ref=ParentRef}, Options) when is_list(Options) -> ?CLASS(ThisT,wxMDIClientWindow), ?CLASS(ParentT,wxMDIParentFrame), MOpts = fun({style, Style}, Acc) -> [<<1:32/?UI,Style:32/?UI>>|Acc]; (BadOpt, _) -> erlang:error({badoption, BadOpt}) end, BinOpt = list_to_binary(lists:foldl(MOpts, [<<0:32>>], Options)), wxe_util:call(?wxMDIClientWindow_CreateClient, <<ThisRef:32/?UI,ParentRef:32/?UI, BinOpt/binary>>). destroy(Obj=#wx_ref{type=Type}) -> ?CLASS(Type,wxMDIClientWindow), wxe_util:destroy(?DESTROY_OBJECT,Obj), ok. warpPointer(This,X,Y) -> wxWindow:warpPointer(This,X,Y). validate(This) -> wxWindow:validate(This). updateWindowUI(This, Options) -> wxWindow:updateWindowUI(This, Options). updateWindowUI(This) -> wxWindow:updateWindowUI(This). update(This) -> wxWindow:update(This). transferDataToWindow(This) -> wxWindow:transferDataToWindow(This). transferDataFromWindow(This) -> wxWindow:transferDataFromWindow(This). thaw(This) -> wxWindow:thaw(This). show(This, Options) -> wxWindow:show(This, Options). show(This) -> wxWindow:show(This). shouldInheritColours(This) -> wxWindow:shouldInheritColours(This). setWindowVariant(This,Variant) -> wxWindow:setWindowVariant(This,Variant). setWindowStyleFlag(This,Style) -> wxWindow:setWindowStyleFlag(This,Style). setWindowStyle(This,Style) -> wxWindow:setWindowStyle(This,Style). setVirtualSizeHints(This,MinW,MinH, Options) -> wxWindow:setVirtualSizeHints(This,MinW,MinH, Options). setVirtualSizeHints(This,MinW,MinH) -> wxWindow:setVirtualSizeHints(This,MinW,MinH). setVirtualSizeHints(This,MinSize) -> wxWindow:setVirtualSizeHints(This,MinSize). setVirtualSize(This,X,Y) -> wxWindow:setVirtualSize(This,X,Y). setVirtualSize(This,Size) -> wxWindow:setVirtualSize(This,Size). setToolTip(This,Tip) -> wxWindow:setToolTip(This,Tip). setThemeEnabled(This,EnableTheme) -> wxWindow:setThemeEnabled(This,EnableTheme). setSizerAndFit(This,Sizer, Options) -> wxWindow:setSizerAndFit(This,Sizer, Options). setSizerAndFit(This,Sizer) -> wxWindow:setSizerAndFit(This,Sizer). setSizer(This,Sizer, Options) -> wxWindow:setSizer(This,Sizer, Options). setSizer(This,Sizer) -> wxWindow:setSizer(This,Sizer). setSizeHints(This,MinW,MinH, Options) -> wxWindow:setSizeHints(This,MinW,MinH, Options). setSizeHints(This,MinW,MinH) -> wxWindow:setSizeHints(This,MinW,MinH). setSizeHints(This,MinSize) -> wxWindow:setSizeHints(This,MinSize). setSize(This,X,Y,Width,Height, Options) -> wxWindow:setSize(This,X,Y,Width,Height, Options). setSize(This,X,Y,Width,Height) -> wxWindow:setSize(This,X,Y,Width,Height). setSize(This,Width,Height) -> wxWindow:setSize(This,Width,Height). setSize(This,Rect) -> wxWindow:setSize(This,Rect). setScrollPos(This,Orient,Pos, Options) -> wxWindow:setScrollPos(This,Orient,Pos, Options). setScrollPos(This,Orient,Pos) -> wxWindow:setScrollPos(This,Orient,Pos). setScrollbar(This,Orient,Pos,ThumbVisible,Range, Options) -> wxWindow:setScrollbar(This,Orient,Pos,ThumbVisible,Range, Options). setScrollbar(This,Orient,Pos,ThumbVisible,Range) -> wxWindow:setScrollbar(This,Orient,Pos,ThumbVisible,Range). setPalette(This,Pal) -> wxWindow:setPalette(This,Pal). setName(This,Name) -> wxWindow:setName(This,Name). setLabel(This,Label) -> wxWindow:setLabel(This,Label). setId(This,Winid) -> wxWindow:setId(This,Winid). setHelpText(This,Text) -> wxWindow:setHelpText(This,Text). setForegroundColour(This,Colour) -> wxWindow:setForegroundColour(This,Colour). setFont(This,Font) -> wxWindow:setFont(This,Font). setFocusFromKbd(This) -> wxWindow:setFocusFromKbd(This). setFocus(This) -> wxWindow:setFocus(This). setExtraStyle(This,ExStyle) -> wxWindow:setExtraStyle(This,ExStyle). setDropTarget(This,DropTarget) -> wxWindow:setDropTarget(This,DropTarget). setOwnForegroundColour(This,Colour) -> wxWindow:setOwnForegroundColour(This,Colour). setOwnFont(This,Font) -> wxWindow:setOwnFont(This,Font). setOwnBackgroundColour(This,Colour) -> wxWindow:setOwnBackgroundColour(This,Colour). setMinSize(This,MinSize) -> wxWindow:setMinSize(This,MinSize). setMaxSize(This,MaxSize) -> wxWindow:setMaxSize(This,MaxSize). setCursor(This,Cursor) -> wxWindow:setCursor(This,Cursor). setContainingSizer(This,Sizer) -> wxWindow:setContainingSizer(This,Sizer). setClientSize(This,Width,Height) -> wxWindow:setClientSize(This,Width,Height). setClientSize(This,Size) -> wxWindow:setClientSize(This,Size). setCaret(This,Caret) -> wxWindow:setCaret(This,Caret). setBackgroundStyle(This,Style) -> wxWindow:setBackgroundStyle(This,Style). setBackgroundColour(This,Colour) -> wxWindow:setBackgroundColour(This,Colour). setAutoLayout(This,AutoLayout) -> wxWindow:setAutoLayout(This,AutoLayout). setAcceleratorTable(This,Accel) -> wxWindow:setAcceleratorTable(This,Accel). scrollWindow(This,Dx,Dy, Options) -> wxWindow:scrollWindow(This,Dx,Dy, Options). scrollWindow(This,Dx,Dy) -> wxWindow:scrollWindow(This,Dx,Dy). scrollPages(This,Pages) -> wxWindow:scrollPages(This,Pages). scrollLines(This,Lines) -> wxWindow:scrollLines(This,Lines). screenToClient(This,Pt) -> wxWindow:screenToClient(This,Pt). screenToClient(This) -> wxWindow:screenToClient(This). reparent(This,NewParent) -> wxWindow:reparent(This,NewParent). removeChild(This,Child) -> wxWindow:removeChild(This,Child). releaseMouse(This) -> wxWindow:releaseMouse(This). refreshRect(This,Rect, Options) -> wxWindow:refreshRect(This,Rect, Options). refreshRect(This,Rect) -> wxWindow:refreshRect(This,Rect). refresh(This, Options) -> wxWindow:refresh(This, Options). refresh(This) -> wxWindow:refresh(This). raise(This) -> wxWindow:raise(This). popupMenu(This,Menu,X,Y) -> wxWindow:popupMenu(This,Menu,X,Y). popupMenu(This,Menu, Options) -> wxWindow:popupMenu(This,Menu, Options). popupMenu(This,Menu) -> wxWindow:popupMenu(This,Menu). popEventHandler(This, Options) -> wxWindow:popEventHandler(This, Options). popEventHandler(This) -> wxWindow:popEventHandler(This). pageUp(This) -> wxWindow:pageUp(This). pageDown(This) -> wxWindow:pageDown(This). navigate(This, Options) -> wxWindow:navigate(This, Options). navigate(This) -> wxWindow:navigate(This). moveBeforeInTabOrder(This,Win) -> wxWindow:moveBeforeInTabOrder(This,Win). moveAfterInTabOrder(This,Win) -> wxWindow:moveAfterInTabOrder(This,Win). move(This,X,Y, Options) -> wxWindow:move(This,X,Y, Options). move(This,X,Y) -> wxWindow:move(This,X,Y). move(This,Pt) -> wxWindow:move(This,Pt). makeModal(This, Options) -> wxWindow:makeModal(This, Options). makeModal(This) -> wxWindow:makeModal(This). lower(This) -> wxWindow:lower(This). lineUp(This) -> wxWindow:lineUp(This). lineDown(This) -> wxWindow:lineDown(This). layout(This) -> wxWindow:layout(This). isTopLevel(This) -> wxWindow:isTopLevel(This). isShown(This) -> wxWindow:isShown(This). isRetained(This) -> wxWindow:isRetained(This). isExposed(This,X,Y,W,H) -> wxWindow:isExposed(This,X,Y,W,H). isExposed(This,X,Y) -> wxWindow:isExposed(This,X,Y). isExposed(This,Pt) -> wxWindow:isExposed(This,Pt). isEnabled(This) -> wxWindow:isEnabled(This). invalidateBestSize(This) -> wxWindow:invalidateBestSize(This). initDialog(This) -> wxWindow:initDialog(This). inheritAttributes(This) -> wxWindow:inheritAttributes(This). hide(This) -> wxWindow:hide(This). hasTransparentBackground(This) -> wxWindow:hasTransparentBackground(This). hasScrollbar(This,Orient) -> wxWindow:hasScrollbar(This,Orient). hasCapture(This) -> wxWindow:hasCapture(This). getWindowVariant(This) -> wxWindow:getWindowVariant(This). getWindowStyleFlag(This) -> wxWindow:getWindowStyleFlag(This). getVirtualSize(This) -> wxWindow:getVirtualSize(This). getUpdateRegion(This) -> wxWindow:getUpdateRegion(This). getToolTip(This) -> wxWindow:getToolTip(This). getTextExtent(This,String, Options) -> wxWindow:getTextExtent(This,String, Options). getTextExtent(This,String) -> wxWindow:getTextExtent(This,String). getSizer(This) -> wxWindow:getSizer(This). getSize(This) -> wxWindow:getSize(This). getScrollThumb(This,Orient) -> wxWindow:getScrollThumb(This,Orient). getScrollRange(This,Orient) -> wxWindow:getScrollRange(This,Orient). getScrollPos(This,Orient) -> wxWindow:getScrollPos(This,Orient). getScreenRect(This) -> wxWindow:getScreenRect(This). getScreenPosition(This) -> wxWindow:getScreenPosition(This). getRect(This) -> wxWindow:getRect(This). getPosition(This) -> wxWindow:getPosition(This). getParent(This) -> wxWindow:getParent(This). getName(This) -> wxWindow:getName(This). getMinSize(This) -> wxWindow:getMinSize(This). getMaxSize(This) -> wxWindow:getMaxSize(This). getLabel(This) -> wxWindow:getLabel(This). getId(This) -> wxWindow:getId(This). getHelpText(This) -> wxWindow:getHelpText(This). getHandle(This) -> wxWindow:getHandle(This). getGrandParent(This) -> wxWindow:getGrandParent(This). getForegroundColour(This) -> wxWindow:getForegroundColour(This). getFont(This) -> wxWindow:getFont(This). getExtraStyle(This) -> wxWindow:getExtraStyle(This). getEventHandler(This) -> wxWindow:getEventHandler(This). getDropTarget(This) -> wxWindow:getDropTarget(This). getCursor(This) -> wxWindow:getCursor(This). getContainingSizer(This) -> wxWindow:getContainingSizer(This). getClientSize(This) -> wxWindow:getClientSize(This). getChildren(This) -> wxWindow:getChildren(This). getCharWidth(This) -> wxWindow:getCharWidth(This). getCharHeight(This) -> wxWindow:getCharHeight(This). getCaret(This) -> wxWindow:getCaret(This). getBestSize(This) -> wxWindow:getBestSize(This). getBackgroundStyle(This) -> wxWindow:getBackgroundStyle(This). getBackgroundColour(This) -> wxWindow:getBackgroundColour(This). getAcceleratorTable(This) -> wxWindow:getAcceleratorTable(This). freeze(This) -> wxWindow:freeze(This). fitInside(This) -> wxWindow:fitInside(This). fit(This) -> wxWindow:fit(This). findWindow(This,Winid) -> wxWindow:findWindow(This,Winid). enable(This, Options) -> wxWindow:enable(This, Options). enable(This) -> wxWindow:enable(This). disable(This) -> wxWindow:disable(This). destroyChildren(This) -> wxWindow:destroyChildren(This). convertPixelsToDialog(This,Sz) -> wxWindow:convertPixelsToDialog(This,Sz). convertDialogToPixels(This,Sz) -> wxWindow:convertDialogToPixels(This,Sz). close(This, Options) -> wxWindow:close(This, Options). close(This) -> wxWindow:close(This). clientToScreen(This,X,Y) -> wxWindow:clientToScreen(This,X,Y). clientToScreen(This,Pt) -> wxWindow:clientToScreen(This,Pt). clearBackground(This) -> wxWindow:clearBackground(This). centreOnParent(This, Options) -> wxWindow:centreOnParent(This, Options). centreOnParent(This) -> wxWindow:centreOnParent(This). centre(This, Options) -> wxWindow:centre(This, Options). centre(This) -> wxWindow:centre(This). centerOnParent(This, Options) -> wxWindow:centerOnParent(This, Options). centerOnParent(This) -> wxWindow:centerOnParent(This). center(This, Options) -> wxWindow:center(This, Options). center(This) -> wxWindow:center(This). captureMouse(This) -> wxWindow:captureMouse(This). cacheBestSize(This,Size) -> wxWindow:cacheBestSize(This,Size). disconnect(This,EventType, Options) -> wxEvtHandler:disconnect(This,EventType, Options). disconnect(This,EventType) -> wxEvtHandler:disconnect(This,EventType). disconnect(This) -> wxEvtHandler:disconnect(This). connect(This,EventType, Options) -> wxEvtHandler:connect(This,EventType, Options). connect(This,EventType) -> wxEvtHandler:connect(This,EventType).
15e97ad7469430d400a69a09b269f5e5c3fa0858810d2c231537b375ec8332cb
ashleylwatson/HaskellsCastle
GameRules.hs
# LANGUAGE TemplateHaskell # # LANGUAGE FlexibleContexts # module GameRules ( Game(..) ,play ,getSaveData ,selectSave ) where import CharacUtil import SelectSystem import Battle import Rooms import Player import Control.Concurrent import Control.Exception (evaluate) import Control.Lens import Control.Monad import Control.Monad.State.Lazy import Control.Monad.Trans import Data.Char import Data.List (delete, find) import Data.Functor ((<&>)) import Data.Function (fix, on, (&)) import Data.Maybe import System.IO import System.Random data Game = Game {_player :: Player ,_room :: Room} deriving (Show, Read) makeLenses ''Game play :: StateT Game IO () play = do player <- gets $ view player room <- gets $ view room select <- lift $ selSyOption 1. length <*> map (pullSel . view obj) $ room case select of 0 -> case length $ view belt player of -- go to menu you need at least 1 utility to go to the menu _ -> do menu 1 play _ -> let option = room !!! select in case option of -- You need to grab the bow in the house before fighting (Option _ (EP _ _)) | length (view belt player) == 0 -> play _ -> do useOpt option play menu :: Int -> StateT Game IO () menu menuSelect = do gameState <- get let viewPlayer attribute = view (player . attribute) gameState pre playerXp = lines23 $ " EXP: " ++ strictSpacing 3 (show playerXp) ++ mkSp 39 ++ "2 -> SAVE" ++ ln ++ newLns 13 ++ sp4 ++ strictSpacing 16 (viewPlayer name) showUtil = showUtilFrom $ viewPlayer belt showScreen int utils = pre (viewPlayer xp) ++ utils ++ mkSp 20 ++ showUtilStats (viewPlayer belt !!! int) (beltBonuses $ viewPlayer belt) ++ newLns 3 beltLength = length $ viewPlayer belt -- Select A Utility utilSelect <- lift $ selSyMenu showScreen menuSelect beltLength [\s -> showUtil 1 s, \s -> showUtil 2 s ++ ln ,\s -> showHP (viewPlayer hp) ++ showUtil 3 s, \s -> showUtil 4 s ++ ln ,\s -> mkSp 20 ++ showUtil 5 s, \s -> showUtil 6 s ++ ln ,\s -> mkSp 20 ++ showUtil 7 s, \s -> showUtil 8 s ++ ln] if utilSelect == 0 then return () -- exit menu else if utilSelect == -1 then do saveSelect <- lift $ selectSave =<< getSaveData -- go to save menu if saveSelect == 0 then return () -- exit menu else lift . writeFile ("Sv" ++ show saveSelect ++ ".txt") . show=<<get -- After selecting a utility, choose what to do with it else flip fix 1 $ \selectOption select -> do gameState <- get let viewPlayer attribute = view (player . attribute) gameState selectedUtil = viewPlayer belt !!! utilSelect showUtilPair = on (++) $ showUtilFrom (viewPlayer belt) <*> \n -> if n == utilSelect then "> " else " " newPre = pre (viewPlayer xp) ++ showUtilPair 1 2 ++ ln ++ showHP (viewPlayer hp) ++ showUtilPair 3 4 ++ ln showlLVupCost = case view nextLevels selectedUtil of (x:_) -> strictSpacing 4 (show $ fst x) [] -> sp4 utilTrait = view trait selectedUtil beltLength = length $ viewPlayer belt -- Choose LVLup, Heal, Order, or Drop optionSelect <- lift $ case utilTrait of -- If the utility is Heal, give an option to Heal Recovery -> selSyOption select 4 [(\s -> newPre ++ mkSelOpt ("LVLup - " ++ showlLVupCost ++ " " ++ showUtilPair 5 6) s) ,mkSelOpt $ strictSpacing 16 "Heal - 1" ++ showUtilPair 7 8 ,mkSelOpt $ strictSpacing 16 "Order" ++ showUtilStats selectedUtil (0,0,0) ,mkSelOpt $ "Drop" ++ ln] -- Otherwise, don't give that option _ -> selSyOption select 3 [(\s -> newPre ++ mkSelOpt ("LVLup - " ++ showlLVupCost ++ " " ++ showUtilPair 5 6) s) ,mkSelOpt $ strictSpacing 14 "Order" ++ showUtilPair 7 8 ,mkSelOpt $ strictSpacing 14 "Drop" ++ showUtilStats selectedUtil (0,0,0) ++ newLns 2] -- Left is for if the selected utility is Heal, Right is for anything else case (if utilTrait == Recovery then Left else Right) optionSelect of x | elem x [Left 0, Right 0] -> menu utilSelect -- go back to menu LVLup x | elem x [Left 1, Right 1] -> case view nextLevels selectedUtil of ((cost,bonus):lvls) | viewPlayer xp >= cost -> do let ((_,(effUp,defUp,waitUp)):restLevels) = view nextLevels selectedUtil levelUp = over eff (effUp +) . over def (defUp +) . over waitVal (waitUp +) . set nextLevels restLevels levelUpUtil int = over belt (inject levelUp utilSelect) . over xp (subtract $ (fst . head) $ view nextLevels selectedUtil) modify $ over player $ levelUpUtil utilSelect selectOption optionSelect _ -> selectOption optionSelect -- Heal (Left 2) -> let lvlsNum = length $ view nextLevels selectedUtil in if lvlsNum == 10 then selectOption optionSelect else do let updatedName = case reverse $ showUtilName selectedUtil of ('1':'+':eman) -> reverse eman (int:'+':eman) -> reverse eman ++ "+" ++ show (read [int] - 1) ('P':'S':eman) -> reverse eman ++ "+9" healLevels = view nextLevels $ listUtilities !!! Heal and Quick Heal are 2 different utilities case showUtilName selectedUtil of ('H':xs) -> 11 _ -> 19 lowerLvl = over belt $ flip inject utilSelect $ set utilName updatedName . over nextLevels (healLevels !!! (10 - lvlsNum) :) heal (x,y) = let newHp = x + view eff selectedUtil in if newHp > y then (y, y) else (newHp, y) modify $ over player $ over hp heal . lowerLvl selectOption optionSelect -- Order x | elem x [Left 3, Right 2] you need at least 2 utilities to change the order -> if beltLength == 1 then selectOption optionSelect else do let showStar n m = showUtil n $ if m == "* " then m else if n == utilSelect then "> " else " " showScreen int utils = pre (viewPlayer xp) ++ utils ++ mkSp 20 ++ showUtilStats (viewPlayer belt !!! int) (beltBonuses $ viewPlayer belt) ++ newLns 3 utilSelect2 <- lift $ selSyUtility showScreen utilSelect beltLength [\s-> showStar 1 s, \s-> showStar 2 s ++ ln ,\s-> showHP (viewPlayer hp) ++ showStar 3 s, \s-> showStar 4 s ++ ln ,\s-> mkSp 20 ++ showStar 5 s, \s-> showStar 6 s ++ ln ,\s-> mkSp 20 ++ showStar 7 s, \s-> showStar 8 s ++ ln] if utilSelect == utilSelect2 then selectOption select else let util1 = viewPlayer belt !!! utilSelect util2 = viewPlayer belt !!! utilSelect2 replaceItem 1 y (x:xs) = y:xs replaceItem n y (x:xs) = x : replaceItem (n - 1) y xs switch n m = replaceItem n util2 . replaceItem m util1 reorder = over belt $ switch utilSelect utilSelect2 in do modify $ over player reorder menu utilSelect2 -- Drop x | elem x [Left 4, Right 3] you need at least 1 utility in your inventory -> if beltLength == 1 then selectOption optionSelect else do confirmDrop <- lift $ selSyOption select 2 [\s -> newPre ++ sp4 ++ s ++ "Drop" ++ mkSp 12 ++ showUtilPair 5 6 ++ ln ,\s -> sp4 ++ s ++ "Cancel" ++ mkSp 11 ++ showUtilPair 7 8 ++ ln ++ mkSp 20 ++ showUtilStats selectedUtil (0,0,0) ++ newLns 3] if elem confirmDrop [0,2] then selectOption optionSelect else do let util = viewPlayer belt !!! utilSelect mkOption = Option $ fromJust $ lookup (view utilName util) storageLocs modify $ over player $ over belt (delete util) . addOpt (mkOption $ CS util) menu $ if utilSelect > beltLength - 1 then beltLength - 1 else utilSelect getSaveData :: IO [Maybe Game] getSaveData = let pullSave fileName = withFile fileName ReadWriteMode $ \handle -> do saveData <- hGetContents handle evaluate $ length saveData return $ case saveData of "" -> Nothing _ -> Just (read saveData :: Game) in sequence $ map pullSave ["Sv1.txt", "Sv2.txt", "Sv3.txt"] selectSave :: [Maybe Game] -> IO Int selectSave saves = selSyOption 1 3 $ saves <&> \save -> mkSelOpt $ case save of (Just (Game _ room)) -> roomNames !!! (head room ^. loc . roomNum) _ -> "----" nameToUtil :: String -> Utility nameToUtil name = fromJust $ find ((==) name . view utilName) listUtilities useOpt :: RoomOption -> StateT Game IO () useOpt option = let mkOption = flip (set obj) option in option ^. loc & case option ^. obj of -- completely heals player HP -> const $ modify $ over (player . hp) $ \(_,y) -> (y, y) -- Move to the nth room R n _ -> const $ modify . set room =<< gets ((!!! n) . view (player . rooms)) FR int roomName enemyName -> const $ do notice $ sp4 ++ "A " ++ enemyName ++ " Has Appeared" useOpt $ mkOption $ EP enemyName $ R int roomName -- after enemy is defeated, it is removed from the active room, but will return apon reentering the room EN enemyName -> enemy enemyName $ return () -- after enemy is defeated, it is completely removed from the game ES enemyName -> enemy enemyName . modify . over player =<< remOpt -- after enemy is defeated, it is only replaced in the active room, but will return apon reentering the room EB enemyName object -> enemy enemyName $ modify . over room $ addOptOnRoom $ mkOption object -- after enemy is defeated, it is completely replaced EP enemyName object -> enemy enemyName $ modify $ over player (replOpt $ mkOption object) . over room (addOptOnRoom $ mkOption object) -- After taking the Utility from a Normal Chest, the chest disappears CN utilName -> chest (nameToUtil utilName) "" . modify . over player =<< remOpt CS util -> chest util "" . modify . over player =<< remOpt CSN utilName enemyName -> chest (nameToUtil utilName) enemyName . modify . over player =<< remOpt CSP utilName enemyName object -> chest (nameToUtil utilName) enemyName $ modify $ over player $ replOpt $ mkOption object GD name -> case name of "Golden Door" -> goldenDoor _ -> chest (nameToUtil name) "" $ modify $ over player $ remOpt (Location 12 4) . remOpt (Location 11 4) RO object roomOption -> const $ do useOpt $ mkOption object modify $ over room $ replOptOnRoom roomOption AO object roomOption -> const $ do let newOption = mkOption object modify $ over player $ addOpt roomOption useOpt newOption modify $ over player $ replOpt newOption enemy = flip enemy' $ return () -- enemy' exists to have a lossUpdate and is only used in chest funtion the lossUpdate in enemy ' is only used for CSN and CSP objects enemy' :: String -> StateT Game IO () -> StateT Game IO () -> Location -> StateT Game IO () enemy' enemyName lossUpdate winUpdate loc = do let monster = fromJust $ find ((==) enemyName . view name) listMonsters chToFitr charac = let (effB, defB, waitB) = beltBonuses $ charac ^. belt in F charac Nothing 0 effB defB waitB Game p _ <- get (result,_) <- lift $ runStateT battle . (Battle (chToFitr $ p ^. plch) (chToFitr monster) 0 1) =<< getStdGen if result == 0 -- if the player loses the battle then do modify $ over player (over hp (\ (_,y) -> (y + 1, y + 1))) . (set room =<< head . view (player . rooms)) lossUpdate -- if the player wins the battle else do modify $ over player (over hp (set _1 result) . over xp (+ view characterXp monster)) . over room (remOptOnRoom loc) winUpdate chest :: Utility -> String -> StateT Game IO () -> Location -> StateT Game IO () chest util enemyName playerUpdate loc = do let utilName = showUtilName util spacing s = sp4 ++ s ++ ln beltLength <- gets $ length . view (player . belt) case beltLength of 8 -> notice (spacing "Your Inventory Is Full." ++ "You Cannot Pick Up " ++ utilName ++ ".") _ -> do select <- lift $ selSySimple 2 [\ s -> spacing $ s ++ "Take " ++ utilName ,\ s -> spacing $ s ++ "Leave It"] if select == 2 then return () else case enemyName of "" -> do modify $ over player (over belt (++ [util])) . over room (remOptOnRoom loc) playerUpdate _ -> do notice $ sp4 ++ "A " ++ enemyName ++ " Has Appeared" modify $ over (player . belt) (++ [util]) enemy' enemyName (modify $ over (player . belt) $ delete util) playerUpdate loc goldenDoor :: Location -> StateT Game IO () goldenDoor loc = do let spacing s = sp4 ++ s ++ newLns 10 notice $ spacing "You must choose..." notice $ spacing "Behind each golden door lies a wonderful treasure." notice $ spacing $ "But when one chest is opened," ++ ln ++ sp4 ++ "the other will be locked for all eternity!" notice $ spacing "Chose wisely." let otherUtil n = if n == 11 then "Power Bangle" else "Trusty Dagger" placeChest f n utilName = f $ Option (Location n 4) (GD utilName) modify $ over player (placeChest replOpt 11 "Power Bangle" . placeChest replOpt 12 "Trusty Dagger") . over room (placeChest replOptOnRoom <*> otherUtil $ loc ^. roomNum)
null
https://raw.githubusercontent.com/ashleylwatson/HaskellsCastle/26e35a2beacfb317733900946572111d6feac0a7/src/GameRules.hs
haskell
go to menu You need to grab the bow in the house before fighting Select A Utility exit menu go to save menu exit menu After selecting a utility, choose what to do with it Choose LVLup, Heal, Order, or Drop If the utility is Heal, give an option to Heal Otherwise, don't give that option Left is for if the selected utility is Heal, Right is for anything else go back to menu Heal Order Drop completely heals player Move to the nth room after enemy is defeated, it is removed from the active room, after enemy is defeated, it is completely removed from the game after enemy is defeated, it is only replaced in the active room, after enemy is defeated, it is completely replaced After taking the Utility from a Normal Chest, the chest disappears enemy' exists to have a lossUpdate and is only used in chest funtion if the player loses the battle if the player wins the battle
# LANGUAGE TemplateHaskell # # LANGUAGE FlexibleContexts # module GameRules ( Game(..) ,play ,getSaveData ,selectSave ) where import CharacUtil import SelectSystem import Battle import Rooms import Player import Control.Concurrent import Control.Exception (evaluate) import Control.Lens import Control.Monad import Control.Monad.State.Lazy import Control.Monad.Trans import Data.Char import Data.List (delete, find) import Data.Functor ((<&>)) import Data.Function (fix, on, (&)) import Data.Maybe import System.IO import System.Random data Game = Game {_player :: Player ,_room :: Room} deriving (Show, Read) makeLenses ''Game play :: StateT Game IO () play = do player <- gets $ view player room <- gets $ view room select <- lift $ selSyOption 1. length <*> map (pullSel . view obj) $ room case select of you need at least 1 utility to go to the menu _ -> do menu 1 play _ -> let option = room !!! select in case option of (Option _ (EP _ _)) | length (view belt player) == 0 -> play _ -> do useOpt option play menu :: Int -> StateT Game IO () menu menuSelect = do gameState <- get let viewPlayer attribute = view (player . attribute) gameState pre playerXp = lines23 $ " EXP: " ++ strictSpacing 3 (show playerXp) ++ mkSp 39 ++ "2 -> SAVE" ++ ln ++ newLns 13 ++ sp4 ++ strictSpacing 16 (viewPlayer name) showUtil = showUtilFrom $ viewPlayer belt showScreen int utils = pre (viewPlayer xp) ++ utils ++ mkSp 20 ++ showUtilStats (viewPlayer belt !!! int) (beltBonuses $ viewPlayer belt) ++ newLns 3 beltLength = length $ viewPlayer belt utilSelect <- lift $ selSyMenu showScreen menuSelect beltLength [\s -> showUtil 1 s, \s -> showUtil 2 s ++ ln ,\s -> showHP (viewPlayer hp) ++ showUtil 3 s, \s -> showUtil 4 s ++ ln ,\s -> mkSp 20 ++ showUtil 5 s, \s -> showUtil 6 s ++ ln ,\s -> mkSp 20 ++ showUtil 7 s, \s -> showUtil 8 s ++ ln] else if utilSelect == -1 else lift . writeFile ("Sv" ++ show saveSelect ++ ".txt") . show=<<get else flip fix 1 $ \selectOption select -> do gameState <- get let viewPlayer attribute = view (player . attribute) gameState selectedUtil = viewPlayer belt !!! utilSelect showUtilPair = on (++) $ showUtilFrom (viewPlayer belt) <*> \n -> if n == utilSelect then "> " else " " newPre = pre (viewPlayer xp) ++ showUtilPair 1 2 ++ ln ++ showHP (viewPlayer hp) ++ showUtilPair 3 4 ++ ln showlLVupCost = case view nextLevels selectedUtil of (x:_) -> strictSpacing 4 (show $ fst x) [] -> sp4 utilTrait = view trait selectedUtil beltLength = length $ viewPlayer belt optionSelect <- lift $ case utilTrait of Recovery -> selSyOption select 4 [(\s -> newPre ++ mkSelOpt ("LVLup - " ++ showlLVupCost ++ " " ++ showUtilPair 5 6) s) ,mkSelOpt $ strictSpacing 16 "Heal - 1" ++ showUtilPair 7 8 ,mkSelOpt $ strictSpacing 16 "Order" ++ showUtilStats selectedUtil (0,0,0) ,mkSelOpt $ "Drop" ++ ln] _ -> selSyOption select 3 [(\s -> newPre ++ mkSelOpt ("LVLup - " ++ showlLVupCost ++ " " ++ showUtilPair 5 6) s) ,mkSelOpt $ strictSpacing 14 "Order" ++ showUtilPair 7 8 ,mkSelOpt $ strictSpacing 14 "Drop" ++ showUtilStats selectedUtil (0,0,0) ++ newLns 2] case (if utilTrait == Recovery then Left else Right) optionSelect of LVLup x | elem x [Left 1, Right 1] -> case view nextLevels selectedUtil of ((cost,bonus):lvls) | viewPlayer xp >= cost -> do let ((_,(effUp,defUp,waitUp)):restLevels) = view nextLevels selectedUtil levelUp = over eff (effUp +) . over def (defUp +) . over waitVal (waitUp +) . set nextLevels restLevels levelUpUtil int = over belt (inject levelUp utilSelect) . over xp (subtract $ (fst . head) $ view nextLevels selectedUtil) modify $ over player $ levelUpUtil utilSelect selectOption optionSelect _ -> selectOption optionSelect (Left 2) -> let lvlsNum = length $ view nextLevels selectedUtil in if lvlsNum == 10 then selectOption optionSelect else do let updatedName = case reverse $ showUtilName selectedUtil of ('1':'+':eman) -> reverse eman (int:'+':eman) -> reverse eman ++ "+" ++ show (read [int] - 1) ('P':'S':eman) -> reverse eman ++ "+9" healLevels = view nextLevels $ listUtilities !!! Heal and Quick Heal are 2 different utilities case showUtilName selectedUtil of ('H':xs) -> 11 _ -> 19 lowerLvl = over belt $ flip inject utilSelect $ set utilName updatedName . over nextLevels (healLevels !!! (10 - lvlsNum) :) heal (x,y) = let newHp = x + view eff selectedUtil in if newHp > y then (y, y) else (newHp, y) modify $ over player $ over hp heal . lowerLvl selectOption optionSelect x | elem x [Left 3, Right 2] you need at least 2 utilities to change the order -> if beltLength == 1 then selectOption optionSelect else do let showStar n m = showUtil n $ if m == "* " then m else if n == utilSelect then "> " else " " showScreen int utils = pre (viewPlayer xp) ++ utils ++ mkSp 20 ++ showUtilStats (viewPlayer belt !!! int) (beltBonuses $ viewPlayer belt) ++ newLns 3 utilSelect2 <- lift $ selSyUtility showScreen utilSelect beltLength [\s-> showStar 1 s, \s-> showStar 2 s ++ ln ,\s-> showHP (viewPlayer hp) ++ showStar 3 s, \s-> showStar 4 s ++ ln ,\s-> mkSp 20 ++ showStar 5 s, \s-> showStar 6 s ++ ln ,\s-> mkSp 20 ++ showStar 7 s, \s-> showStar 8 s ++ ln] if utilSelect == utilSelect2 then selectOption select else let util1 = viewPlayer belt !!! utilSelect util2 = viewPlayer belt !!! utilSelect2 replaceItem 1 y (x:xs) = y:xs replaceItem n y (x:xs) = x : replaceItem (n - 1) y xs switch n m = replaceItem n util2 . replaceItem m util1 reorder = over belt $ switch utilSelect utilSelect2 in do modify $ over player reorder menu utilSelect2 x | elem x [Left 4, Right 3] you need at least 1 utility in your inventory -> if beltLength == 1 then selectOption optionSelect else do confirmDrop <- lift $ selSyOption select 2 [\s -> newPre ++ sp4 ++ s ++ "Drop" ++ mkSp 12 ++ showUtilPair 5 6 ++ ln ,\s -> sp4 ++ s ++ "Cancel" ++ mkSp 11 ++ showUtilPair 7 8 ++ ln ++ mkSp 20 ++ showUtilStats selectedUtil (0,0,0) ++ newLns 3] if elem confirmDrop [0,2] then selectOption optionSelect else do let util = viewPlayer belt !!! utilSelect mkOption = Option $ fromJust $ lookup (view utilName util) storageLocs modify $ over player $ over belt (delete util) . addOpt (mkOption $ CS util) menu $ if utilSelect > beltLength - 1 then beltLength - 1 else utilSelect getSaveData :: IO [Maybe Game] getSaveData = let pullSave fileName = withFile fileName ReadWriteMode $ \handle -> do saveData <- hGetContents handle evaluate $ length saveData return $ case saveData of "" -> Nothing _ -> Just (read saveData :: Game) in sequence $ map pullSave ["Sv1.txt", "Sv2.txt", "Sv3.txt"] selectSave :: [Maybe Game] -> IO Int selectSave saves = selSyOption 1 3 $ saves <&> \save -> mkSelOpt $ case save of (Just (Game _ room)) -> roomNames !!! (head room ^. loc . roomNum) _ -> "----" nameToUtil :: String -> Utility nameToUtil name = fromJust $ find ((==) name . view utilName) listUtilities useOpt :: RoomOption -> StateT Game IO () useOpt option = let mkOption = flip (set obj) option in option ^. loc & case option ^. obj of HP -> const $ modify $ over (player . hp) $ \(_,y) -> (y, y) R n _ -> const $ modify . set room =<< gets ((!!! n) . view (player . rooms)) FR int roomName enemyName -> const $ do notice $ sp4 ++ "A " ++ enemyName ++ " Has Appeared" useOpt $ mkOption $ EP enemyName $ R int roomName but will return apon reentering the room EN enemyName -> enemy enemyName $ return () ES enemyName -> enemy enemyName . modify . over player =<< remOpt but will return apon reentering the room EB enemyName object -> enemy enemyName $ modify . over room $ addOptOnRoom $ mkOption object EP enemyName object -> enemy enemyName $ modify $ over player (replOpt $ mkOption object) . over room (addOptOnRoom $ mkOption object) CN utilName -> chest (nameToUtil utilName) "" . modify . over player =<< remOpt CS util -> chest util "" . modify . over player =<< remOpt CSN utilName enemyName -> chest (nameToUtil utilName) enemyName . modify . over player =<< remOpt CSP utilName enemyName object -> chest (nameToUtil utilName) enemyName $ modify $ over player $ replOpt $ mkOption object GD name -> case name of "Golden Door" -> goldenDoor _ -> chest (nameToUtil name) "" $ modify $ over player $ remOpt (Location 12 4) . remOpt (Location 11 4) RO object roomOption -> const $ do useOpt $ mkOption object modify $ over room $ replOptOnRoom roomOption AO object roomOption -> const $ do let newOption = mkOption object modify $ over player $ addOpt roomOption useOpt newOption modify $ over player $ replOpt newOption enemy = flip enemy' $ return () the lossUpdate in enemy ' is only used for CSN and CSP objects enemy' :: String -> StateT Game IO () -> StateT Game IO () -> Location -> StateT Game IO () enemy' enemyName lossUpdate winUpdate loc = do let monster = fromJust $ find ((==) enemyName . view name) listMonsters chToFitr charac = let (effB, defB, waitB) = beltBonuses $ charac ^. belt in F charac Nothing 0 effB defB waitB Game p _ <- get (result,_) <- lift $ runStateT battle . (Battle (chToFitr $ p ^. plch) (chToFitr monster) 0 1) =<< getStdGen if result == 0 then do modify $ over player (over hp (\ (_,y) -> (y + 1, y + 1))) . (set room =<< head . view (player . rooms)) lossUpdate else do modify $ over player (over hp (set _1 result) . over xp (+ view characterXp monster)) . over room (remOptOnRoom loc) winUpdate chest :: Utility -> String -> StateT Game IO () -> Location -> StateT Game IO () chest util enemyName playerUpdate loc = do let utilName = showUtilName util spacing s = sp4 ++ s ++ ln beltLength <- gets $ length . view (player . belt) case beltLength of 8 -> notice (spacing "Your Inventory Is Full." ++ "You Cannot Pick Up " ++ utilName ++ ".") _ -> do select <- lift $ selSySimple 2 [\ s -> spacing $ s ++ "Take " ++ utilName ,\ s -> spacing $ s ++ "Leave It"] if select == 2 then return () else case enemyName of "" -> do modify $ over player (over belt (++ [util])) . over room (remOptOnRoom loc) playerUpdate _ -> do notice $ sp4 ++ "A " ++ enemyName ++ " Has Appeared" modify $ over (player . belt) (++ [util]) enemy' enemyName (modify $ over (player . belt) $ delete util) playerUpdate loc goldenDoor :: Location -> StateT Game IO () goldenDoor loc = do let spacing s = sp4 ++ s ++ newLns 10 notice $ spacing "You must choose..." notice $ spacing "Behind each golden door lies a wonderful treasure." notice $ spacing $ "But when one chest is opened," ++ ln ++ sp4 ++ "the other will be locked for all eternity!" notice $ spacing "Chose wisely." let otherUtil n = if n == 11 then "Power Bangle" else "Trusty Dagger" placeChest f n utilName = f $ Option (Location n 4) (GD utilName) modify $ over player (placeChest replOpt 11 "Power Bangle" . placeChest replOpt 12 "Trusty Dagger") . over room (placeChest replOptOnRoom <*> otherUtil $ loc ^. roomNum)
76865d6feacd000be43620b7a50bf642db67e5ee3507c96914b32856d3d33628
hopv/MoCHi
undefHCCSSolver.ml
open Util open Combinator let solve solver hcs : PredSubst.t = let tenv = HCCS.tenv hcs in hcs |> HCCS.undefined_pvs |> List.unique |> List.map (fun p -> p, List.assoc_fail p tenv) |> PredSubst.bot_of_tenv |> HCCS.of_psub |> (@) hcs |> solver let solve = Logger.log_block2 "UndefHCCSSolver.solve" solve
null
https://raw.githubusercontent.com/hopv/MoCHi/b0ac0d626d64b1e3c779d8e98cb232121cc3196a/fpat/undefHCCSSolver.ml
ocaml
open Util open Combinator let solve solver hcs : PredSubst.t = let tenv = HCCS.tenv hcs in hcs |> HCCS.undefined_pvs |> List.unique |> List.map (fun p -> p, List.assoc_fail p tenv) |> PredSubst.bot_of_tenv |> HCCS.of_psub |> (@) hcs |> solver let solve = Logger.log_block2 "UndefHCCSSolver.solve" solve
633a0e43a310f824c6151914e7f78a77538bbd977e62d469f6a884362cc8d854
aeyakovenko/rbm
Matrix.hs
| Module : Data . Matrix Description : Typesafe matrix operations . Copyright : ( c ) , 2015 - 2016 License : MIT Maintainer : Stability : experimental Portability : POSIX This module implements some matrix operations using the package that track the symbolic shape of the matrix . Module : Data.Matrix Description : Typesafe matrix operations. Copyright : (c) Anatoly Yakovenko, 2015-2016 License : MIT Maintainer : Stability : experimental Portability : POSIX This module implements some matrix operations using the Repa package that track the symbolic shape of the matrix. -} # LANGUAGE MultiParamTypeClasses # # LANGUAGE FlexibleInstances # # LANGUAGE FlexibleContexts # # LANGUAGE ScopedTypeVariables # # LANGUAGE ExistentialQuantification # {-# LANGUAGE EmptyDataDecls #-} module Data.Matrix( Matrix(..) , MatrixOps(..) , R.U , R.D , B , I , H ) where import Prelude as P import Data.Binary(Binary,put,get) import qualified Data.Array.Repa as R import qualified Data.Array.Repa.Algorithms.Matrix as R import qualified Data.Array.Repa.Unsafe as Unsafe import qualified Data.Array.Repa.Algorithms.Randomish as R import qualified Data.Vector.Unboxed as V import Control.DeepSeq(NFData, rnf) import Data.Array.Repa(Array ,U ,D ,DIM2 ,Any(Any) ,Z(Z) ,(:.)((:.)) ,All(All) ) -- | num hidden nodes data H -- | num input nodes data I -- | num inputs in batch data B -- | wraps the Repa Array types so we can typecheck the results of -- | the matrix operations data Matrix d a b = R.Source d Double => Matrix (Array d DIM2 Double) instance Show (Matrix U a b) where show m = show $ toList m instance NFData (Matrix U a b) where rnf (Matrix ar) = ar `R.deepSeqArray` () |Class implementing the typesafe Matrix apis class MatrixOps a b where mmult :: Monad m => (Matrix U a b) -> (Matrix U b c) -> m (Matrix U a c) mmult (Matrix ab) (Matrix ba) = Matrix <$> (ab `mmultP` ba) mmultT :: Monad m => (Matrix U a b) -> (Matrix U c b) -> m (Matrix U a c) mmultT (Matrix ab) (Matrix ab') = Matrix <$> (ab `mmultTP` ab') d2u :: Monad m => Matrix D a b -> m (Matrix U a b) d2u (Matrix ar) = Matrix <$> (R.computeP ar) (*^) :: Matrix c a b -> Matrix d a b -> (Matrix D a b) (Matrix ab) *^ (Matrix ab') = Matrix (ab R.*^ ab') {-# INLINE (*^) #-} (+^) :: Matrix c a b -> Matrix d a b -> (Matrix D a b) (Matrix ab) +^ (Matrix ab') = Matrix (ab R.+^ ab') {-# INLINE (+^) #-} (-^) :: Matrix c a b -> Matrix d a b -> (Matrix D a b) (Matrix ab) -^ (Matrix ab') = Matrix (ab R.-^ ab') {-# INLINE (-^) #-} map :: (Double -> Double) -> Matrix c a b -> (Matrix D a b) map f (Matrix ar) = Matrix (R.map f ar) # INLINE map # cast1 :: Matrix c a b -> Matrix c d b cast1 (Matrix ar) = Matrix ar # INLINE cast1 # cast2 :: Matrix c a b -> Matrix c a d cast2 (Matrix ar) = Matrix ar # INLINE cast2 # transpose :: Monad m => Matrix U a b -> m (Matrix U b a) transpose (Matrix ar) = Matrix <$> (R.transpose2P ar) {-# INLINE transpose #-} sum :: Monad m => Matrix c a b -> m Double sum (Matrix ar) = R.sumAllP ar # INLINE sum # mse :: Monad m => Matrix c a b -> m Double mse errm = do terr <- Data.Matrix.sum $ Data.Matrix.map (\ x -> x ** 2) errm return (terr/(1 + (fromIntegral $ elems errm))) # INLINE mse # elems :: Matrix c a b -> Int elems m = (row m) * (col m) # INLINE elems # row :: Matrix c a b -> Int row (Matrix ar) = (R.row (R.extent ar)) # INLINE row # col :: Matrix c a b -> Int col (Matrix ar) = (R.col (R.extent ar)) # INLINE col # shape :: Matrix c a b -> (Int,Int) shape m = (row m, col m) # INLINE shape # randomish :: (Int,Int) -> (Double,Double) -> Int -> Matrix U a b randomish (r,c) (minv,maxv) seed = Matrix $ R.randomishDoubleArray (Z :. r :. c) minv maxv seed # INLINE randomish # splitRows :: Int -> Matrix c a b -> [Matrix D a b] splitRows nr m1 = P.map (extractRows m1) chunks where chunks = P.map maxn $ zip rixs (repeat nr) maxn (rix,num) | rix + num > (row m1) = (rix, (row m1) - rix) | otherwise = (rix, num) rixs = [0,nr..(row m1)-1] extractRows :: Matrix c a b -> (Int,Int) -> Matrix D a b extractRows m2@(Matrix ar) (rix,num) = Matrix $ R.extract (Z :. rix :. 0) (Z :. num :. (col m2)) ar # INLINE splitRows # zipWith :: (Double -> Double -> Double) -> Matrix c a b -> Matrix c a b -> (Matrix D a b) zipWith f (Matrix aa) (Matrix bb) = Matrix (R.zipWith f aa bb) # INLINE zipWith # fromList :: (Int,Int) -> [Double] -> Matrix U a b fromList (r,c) lst = Matrix $ R.fromListUnboxed (Z:.r:.c) lst # INLINE fromList # traverse :: (Double -> Int -> Int -> Double) -> Matrix c a b -> Matrix D a b traverse ff (Matrix ar) = Matrix $ R.traverse ar id func where func gv sh@(Z :. rr :. cc) = ff (gv sh) rr cc {-# INLINE traverse #-} toList :: Matrix U a b -> [Double] toList (Matrix ab) = R.toList ab # INLINE toList # fold :: Monad m => (Double -> Double -> Double) -> Double -> Matrix U a b -> m Double fold f z (Matrix ab) = R.foldAllP f z ab # INLINE fold # toUnboxed :: Matrix U a b -> V.Vector Double toUnboxed (Matrix ar) = R.toUnboxed ar # INLINE toUnboxed # instance MatrixOps a b where instance Binary (Matrix U a b) where put m = put (shape m, toList m) get = (uncurry fromList) <$> get | - matrix multiply - A x ( transpose B ) - based on from repa - algorithms-3.3.1.2 - matrix multiply - A x (transpose B) - based on mmultP from repa-algorithms-3.3.1.2 -} mmultTP :: Monad m => Array U DIM2 Double -> Array U DIM2 Double -> m (Array U DIM2 Double) mmultTP arr trr = [arr, trr] `R.deepSeqArrays` do let (Z :. h1 :. _) = R.extent arr let (Z :. w2 :. _) = R.extent trr R.computeP $ R.fromFunction (Z :. h1 :. w2) $ \ix -> R.sumAllS $ R.zipWith (*) (Unsafe.unsafeSlice arr (Any :. (R.row ix) :. All)) (Unsafe.unsafeSlice trr (Any :. (R.col ix) :. All)) # NOINLINE mmultTP # | - regular matrix multiply - A x B - based on from repa - algorithms-3.3.1.2 - moved the deepseq to evaluate the transpose(B ) instead of B - regular matrix multiply - A x B - based on mmultP from repa-algorithms-3.3.1.2 - moved the deepseq to evaluate the transpose(B) instead of B -} mmultP :: Monad m => Array U DIM2 Double -> Array U DIM2 Double -> m (Array U DIM2 Double) mmultP arr brr = do trr <- R.transpose2P brr mmultTP arr trr
null
https://raw.githubusercontent.com/aeyakovenko/rbm/e1767257ba7499e09b31b34b1ec76c14272ba127/Data/Matrix.hs
haskell
# LANGUAGE EmptyDataDecls # | num hidden nodes | num input nodes | num inputs in batch | wraps the Repa Array types so we can typecheck the results of | the matrix operations # INLINE (*^) # # INLINE (+^) # # INLINE (-^) # # INLINE transpose # # INLINE traverse #
| Module : Data . Matrix Description : Typesafe matrix operations . Copyright : ( c ) , 2015 - 2016 License : MIT Maintainer : Stability : experimental Portability : POSIX This module implements some matrix operations using the package that track the symbolic shape of the matrix . Module : Data.Matrix Description : Typesafe matrix operations. Copyright : (c) Anatoly Yakovenko, 2015-2016 License : MIT Maintainer : Stability : experimental Portability : POSIX This module implements some matrix operations using the Repa package that track the symbolic shape of the matrix. -} # LANGUAGE MultiParamTypeClasses # # LANGUAGE FlexibleInstances # # LANGUAGE FlexibleContexts # # LANGUAGE ScopedTypeVariables # # LANGUAGE ExistentialQuantification # module Data.Matrix( Matrix(..) , MatrixOps(..) , R.U , R.D , B , I , H ) where import Prelude as P import Data.Binary(Binary,put,get) import qualified Data.Array.Repa as R import qualified Data.Array.Repa.Algorithms.Matrix as R import qualified Data.Array.Repa.Unsafe as Unsafe import qualified Data.Array.Repa.Algorithms.Randomish as R import qualified Data.Vector.Unboxed as V import Control.DeepSeq(NFData, rnf) import Data.Array.Repa(Array ,U ,D ,DIM2 ,Any(Any) ,Z(Z) ,(:.)((:.)) ,All(All) ) data H data I data B data Matrix d a b = R.Source d Double => Matrix (Array d DIM2 Double) instance Show (Matrix U a b) where show m = show $ toList m instance NFData (Matrix U a b) where rnf (Matrix ar) = ar `R.deepSeqArray` () |Class implementing the typesafe Matrix apis class MatrixOps a b where mmult :: Monad m => (Matrix U a b) -> (Matrix U b c) -> m (Matrix U a c) mmult (Matrix ab) (Matrix ba) = Matrix <$> (ab `mmultP` ba) mmultT :: Monad m => (Matrix U a b) -> (Matrix U c b) -> m (Matrix U a c) mmultT (Matrix ab) (Matrix ab') = Matrix <$> (ab `mmultTP` ab') d2u :: Monad m => Matrix D a b -> m (Matrix U a b) d2u (Matrix ar) = Matrix <$> (R.computeP ar) (*^) :: Matrix c a b -> Matrix d a b -> (Matrix D a b) (Matrix ab) *^ (Matrix ab') = Matrix (ab R.*^ ab') (+^) :: Matrix c a b -> Matrix d a b -> (Matrix D a b) (Matrix ab) +^ (Matrix ab') = Matrix (ab R.+^ ab') (-^) :: Matrix c a b -> Matrix d a b -> (Matrix D a b) (Matrix ab) -^ (Matrix ab') = Matrix (ab R.-^ ab') map :: (Double -> Double) -> Matrix c a b -> (Matrix D a b) map f (Matrix ar) = Matrix (R.map f ar) # INLINE map # cast1 :: Matrix c a b -> Matrix c d b cast1 (Matrix ar) = Matrix ar # INLINE cast1 # cast2 :: Matrix c a b -> Matrix c a d cast2 (Matrix ar) = Matrix ar # INLINE cast2 # transpose :: Monad m => Matrix U a b -> m (Matrix U b a) transpose (Matrix ar) = Matrix <$> (R.transpose2P ar) sum :: Monad m => Matrix c a b -> m Double sum (Matrix ar) = R.sumAllP ar # INLINE sum # mse :: Monad m => Matrix c a b -> m Double mse errm = do terr <- Data.Matrix.sum $ Data.Matrix.map (\ x -> x ** 2) errm return (terr/(1 + (fromIntegral $ elems errm))) # INLINE mse # elems :: Matrix c a b -> Int elems m = (row m) * (col m) # INLINE elems # row :: Matrix c a b -> Int row (Matrix ar) = (R.row (R.extent ar)) # INLINE row # col :: Matrix c a b -> Int col (Matrix ar) = (R.col (R.extent ar)) # INLINE col # shape :: Matrix c a b -> (Int,Int) shape m = (row m, col m) # INLINE shape # randomish :: (Int,Int) -> (Double,Double) -> Int -> Matrix U a b randomish (r,c) (minv,maxv) seed = Matrix $ R.randomishDoubleArray (Z :. r :. c) minv maxv seed # INLINE randomish # splitRows :: Int -> Matrix c a b -> [Matrix D a b] splitRows nr m1 = P.map (extractRows m1) chunks where chunks = P.map maxn $ zip rixs (repeat nr) maxn (rix,num) | rix + num > (row m1) = (rix, (row m1) - rix) | otherwise = (rix, num) rixs = [0,nr..(row m1)-1] extractRows :: Matrix c a b -> (Int,Int) -> Matrix D a b extractRows m2@(Matrix ar) (rix,num) = Matrix $ R.extract (Z :. rix :. 0) (Z :. num :. (col m2)) ar # INLINE splitRows # zipWith :: (Double -> Double -> Double) -> Matrix c a b -> Matrix c a b -> (Matrix D a b) zipWith f (Matrix aa) (Matrix bb) = Matrix (R.zipWith f aa bb) # INLINE zipWith # fromList :: (Int,Int) -> [Double] -> Matrix U a b fromList (r,c) lst = Matrix $ R.fromListUnboxed (Z:.r:.c) lst # INLINE fromList # traverse :: (Double -> Int -> Int -> Double) -> Matrix c a b -> Matrix D a b traverse ff (Matrix ar) = Matrix $ R.traverse ar id func where func gv sh@(Z :. rr :. cc) = ff (gv sh) rr cc toList :: Matrix U a b -> [Double] toList (Matrix ab) = R.toList ab # INLINE toList # fold :: Monad m => (Double -> Double -> Double) -> Double -> Matrix U a b -> m Double fold f z (Matrix ab) = R.foldAllP f z ab # INLINE fold # toUnboxed :: Matrix U a b -> V.Vector Double toUnboxed (Matrix ar) = R.toUnboxed ar # INLINE toUnboxed # instance MatrixOps a b where instance Binary (Matrix U a b) where put m = put (shape m, toList m) get = (uncurry fromList) <$> get | - matrix multiply - A x ( transpose B ) - based on from repa - algorithms-3.3.1.2 - matrix multiply - A x (transpose B) - based on mmultP from repa-algorithms-3.3.1.2 -} mmultTP :: Monad m => Array U DIM2 Double -> Array U DIM2 Double -> m (Array U DIM2 Double) mmultTP arr trr = [arr, trr] `R.deepSeqArrays` do let (Z :. h1 :. _) = R.extent arr let (Z :. w2 :. _) = R.extent trr R.computeP $ R.fromFunction (Z :. h1 :. w2) $ \ix -> R.sumAllS $ R.zipWith (*) (Unsafe.unsafeSlice arr (Any :. (R.row ix) :. All)) (Unsafe.unsafeSlice trr (Any :. (R.col ix) :. All)) # NOINLINE mmultTP # | - regular matrix multiply - A x B - based on from repa - algorithms-3.3.1.2 - moved the deepseq to evaluate the transpose(B ) instead of B - regular matrix multiply - A x B - based on mmultP from repa-algorithms-3.3.1.2 - moved the deepseq to evaluate the transpose(B) instead of B -} mmultP :: Monad m => Array U DIM2 Double -> Array U DIM2 Double -> m (Array U DIM2 Double) mmultP arr brr = do trr <- R.transpose2P brr mmultTP arr trr
12352f1f8650f27cb1da5fee2ef78b44cfc65cdc90920c36583ea5da8be75edc
emina/rosette
host.rkt
#lang s-exp "../../../lang/main.rkt" ; Given a src array of length SIZE, returns a new array dst of ; the same size, such that dst[i] = src[i] + offset, for all 0 < = i < SIZE . The SIZE parameter must be evenly divisible by 4 . (procedure int* (host [int* src] [int SIZE] [int offset]) (: cl_context context) (: cl_command_queue command_queue) (: cl_program program) (: cl_kernel kernel) (: cl_mem buffer_src buffer_dst) (: int* dst) (: int local global) (= local 4) (= global SIZE) (= dst ((int*) (malloc (* SIZE (sizeof int))))) (= context (clCreateContext)) (= command_queue (clCreateCommandQueue context)) (= buffer_src (clCreateBuffer context CL_MEM_READ_ONLY (* SIZE (sizeof int)))) (= buffer_dst (clCreateBuffer context CL_MEM_WRITE_ONLY (* SIZE (sizeof int)))) (= program (clCreateProgramWithSource context "kernel.rkt")) (clEnqueueWriteBuffer command_queue buffer_src 0 SIZE src) (= kernel (clCreateKernel program "sample")) (clSetKernelArg kernel 0 buffer_dst) (clSetKernelArg kernel 1 buffer_src) (clSetKernelArg kernel 2 offset) (clEnqueueNDRangeKernel command_queue kernel 1 NULL (@ global) (@ local)) (clEnqueueReadBuffer command_queue buffer_dst 0 SIZE dst) dst) ; The reference implementation for the host procedure. ; Given a src array of length SIZE, returns a new array dst of ; the same size, such that dst[i] = src[i] + offset, for all 0 < = i < SIZE . The SIZE parameter must be evenly divisible by 4 . (procedure int* (spec [int* src] [int SIZE] [int offset]) (: int* dst) (= dst ((int*) (malloc (* SIZE (sizeof int))))) (for [(: int i in (range SIZE))] (= [ dst i ] ( ? : ( & & (= = SIZE 16 ) (= = offset -1 ) ) ; (- [src i] offset) ; (+ [src i] offset)))) ; sample bug (= [dst i] (+ [src i] offset))) dst) Given two arrays of the same size , checks that they hold the same ; values at each index. (procedure void (check [int* actual] [int* expected] [int SIZE]) (assert (>= SIZE 0)) (for [(: int i in (range SIZE))] (assert (== [actual i] [expected i])))) ; Verify the host procedure for all small arrays of length that is evenly divisible by 4 . (verify #:forall [(: int offset) (: int len in (range 4 17 4)) (: int[len] src)] #:ensure (check (host src len offset) (spec src len offset) len))
null
https://raw.githubusercontent.com/emina/rosette/a64e2bccfe5876c5daaf4a17c5a28a49e2fbd501/sdsl/synthcl/examples/toy/verify/host.rkt
racket
Given a src array of length SIZE, returns a new array dst of the same size, such that dst[i] = src[i] + offset, for all The reference implementation for the host procedure. Given a src array of length SIZE, returns a new array dst of the same size, such that dst[i] = src[i] + offset, for all (- [src i] offset) (+ [src i] offset)))) ; sample bug values at each index. Verify the host procedure for all small arrays of length that is
#lang s-exp "../../../lang/main.rkt" 0 < = i < SIZE . The SIZE parameter must be evenly divisible by 4 . (procedure int* (host [int* src] [int SIZE] [int offset]) (: cl_context context) (: cl_command_queue command_queue) (: cl_program program) (: cl_kernel kernel) (: cl_mem buffer_src buffer_dst) (: int* dst) (: int local global) (= local 4) (= global SIZE) (= dst ((int*) (malloc (* SIZE (sizeof int))))) (= context (clCreateContext)) (= command_queue (clCreateCommandQueue context)) (= buffer_src (clCreateBuffer context CL_MEM_READ_ONLY (* SIZE (sizeof int)))) (= buffer_dst (clCreateBuffer context CL_MEM_WRITE_ONLY (* SIZE (sizeof int)))) (= program (clCreateProgramWithSource context "kernel.rkt")) (clEnqueueWriteBuffer command_queue buffer_src 0 SIZE src) (= kernel (clCreateKernel program "sample")) (clSetKernelArg kernel 0 buffer_dst) (clSetKernelArg kernel 1 buffer_src) (clSetKernelArg kernel 2 offset) (clEnqueueNDRangeKernel command_queue kernel 1 NULL (@ global) (@ local)) (clEnqueueReadBuffer command_queue buffer_dst 0 SIZE dst) dst) 0 < = i < SIZE . The SIZE parameter must be evenly divisible by 4 . (procedure int* (spec [int* src] [int SIZE] [int offset]) (: int* dst) (= dst ((int*) (malloc (* SIZE (sizeof int))))) (for [(: int i in (range SIZE))] (= [ dst i ] ( ? : ( & & (= = SIZE 16 ) (= = offset -1 ) ) (= [dst i] (+ [src i] offset))) dst) Given two arrays of the same size , checks that they hold the same (procedure void (check [int* actual] [int* expected] [int SIZE]) (assert (>= SIZE 0)) (for [(: int i in (range SIZE))] (assert (== [actual i] [expected i])))) evenly divisible by 4 . (verify #:forall [(: int offset) (: int len in (range 4 17 4)) (: int[len] src)] #:ensure (check (host src len offset) (spec src len offset) len))
c69217b14ae6abd7f6f5880ea64219d19620513ca9ed58a0785bb9dbf94edc08
franburstall/nyxt-init
buffer-tags.lisp
;; quick and dirty tags for buffers ;; ;; Usage: enable buffer-tag-mode and then, for 0<=n<=9, hit C - M - n to give the current - buffer tag n ( removing it from any ;; previous owner) ;; C-n to switch to the buffer with tag n. ;; TODO: ;; - next/prev tagged buffer? Not sure if this is really necessary. ;; - serialise on exit? Would need to store buffer ids rather than buffers. (in-package #:nyxt-user) (defparameter *tagged-buffers* (make-array 10 :initial-element nil)) (defun switch-buffer-by-tag (tag) "Switch to buffer with tag TAG, if it exists." (let* ((buf (elt *tagged-buffers* tag)) (live-p (member buf (buffer-list)))) (if (and buf live-p) (set-current-buffer buf) (progn (when buf (setf (aref *tagged-buffers* tag) nil)) ; empty the tag (echo-warning (format nil "No live buffer with tag ~d." tag)))))) (defun set-buffer-tag (tag) "Assign TAG to current buffer." (let ((buf (current-buffer))) (dotimes (i 10) (when (eq buf (aref *tagged-buffers* i)) (setf (aref *tagged-buffers* i) nil))) (setf (aref *tagged-buffers* tag) buf)) (nyxt::print-status) (echo "Tag ~d set." tag)) (defun show-buffer-tag (buffer) "Return BUFFER's tag or nil." (position buffer *tagged-buffers*)) (defvar buffer-tag-mode-map (make-keymap "buffer-tag-mode-map")) (defmacro make-key-binds (max) "Create key binds for set-buffer-tag-* and friends." (let (forms) (dotimes (i max) (push `(define-key buffer-tag-mode-map (format nil "C-M-~d" ,i) (lambda-command ,(make-symbol (format nil "SET-BUFFER-TAG-~d" i)) () ,(format nil "Give current buffer tag ~d." i) (set-buffer-tag ,i))) forms) (push `(define-key buffer-tag-mode-map (format nil "C-~d" ,i) (lambda-command ,(make-symbol (format nil "SWITCH-TO-BUFFER-~d" i)) () ,(format nil "Switch to buffer with tag ~d." i) (switch-buffer-by-tag ,i))) forms)) `(progn ,@forms))) (make-key-binds 10) (define-mode buffer-tag-mode () "Mode to allow quick and dirty buffer tagging. For n from 0 to 9, do C-M-n to give the current buffer tag n and C-n to then switch to it." ((keyscheme-map (keymaps:make-keyscheme-map nyxt/keyscheme:cua buffer-tag-mode-map nyxt/keyscheme:emacs buffer-tag-mode-map nyxt/keyscheme:vi-normal buffer-tag-mode-map))))
null
https://raw.githubusercontent.com/franburstall/nyxt-init/383aecb3b65dec7e16968ad6344030ba9ae09ea6/buffer-tags.lisp
lisp
quick and dirty tags for buffers Usage: enable buffer-tag-mode and then, for 0<=n<=9, hit previous owner) C-n to switch to the buffer with tag n. TODO: - next/prev tagged buffer? Not sure if this is really necessary. - serialise on exit? Would need to store buffer ids rather than buffers. empty the tag
C - M - n to give the current - buffer tag n ( removing it from any (in-package #:nyxt-user) (defparameter *tagged-buffers* (make-array 10 :initial-element nil)) (defun switch-buffer-by-tag (tag) "Switch to buffer with tag TAG, if it exists." (let* ((buf (elt *tagged-buffers* tag)) (live-p (member buf (buffer-list)))) (if (and buf live-p) (set-current-buffer buf) (echo-warning (format nil "No live buffer with tag ~d." tag)))))) (defun set-buffer-tag (tag) "Assign TAG to current buffer." (let ((buf (current-buffer))) (dotimes (i 10) (when (eq buf (aref *tagged-buffers* i)) (setf (aref *tagged-buffers* i) nil))) (setf (aref *tagged-buffers* tag) buf)) (nyxt::print-status) (echo "Tag ~d set." tag)) (defun show-buffer-tag (buffer) "Return BUFFER's tag or nil." (position buffer *tagged-buffers*)) (defvar buffer-tag-mode-map (make-keymap "buffer-tag-mode-map")) (defmacro make-key-binds (max) "Create key binds for set-buffer-tag-* and friends." (let (forms) (dotimes (i max) (push `(define-key buffer-tag-mode-map (format nil "C-M-~d" ,i) (lambda-command ,(make-symbol (format nil "SET-BUFFER-TAG-~d" i)) () ,(format nil "Give current buffer tag ~d." i) (set-buffer-tag ,i))) forms) (push `(define-key buffer-tag-mode-map (format nil "C-~d" ,i) (lambda-command ,(make-symbol (format nil "SWITCH-TO-BUFFER-~d" i)) () ,(format nil "Switch to buffer with tag ~d." i) (switch-buffer-by-tag ,i))) forms)) `(progn ,@forms))) (make-key-binds 10) (define-mode buffer-tag-mode () "Mode to allow quick and dirty buffer tagging. For n from 0 to 9, do C-M-n to give the current buffer tag n and C-n to then switch to it." ((keyscheme-map (keymaps:make-keyscheme-map nyxt/keyscheme:cua buffer-tag-mode-map nyxt/keyscheme:emacs buffer-tag-mode-map nyxt/keyscheme:vi-normal buffer-tag-mode-map))))
3ed254037de6e3e58ef2db6838980e17bebc3e5c3abd7dcbf6fceebfe37bb397
Feldspar/feldspar-language
FFT.hs
{-# LANGUAGE BangPatterns #-} # LANGUAGE TemplateHaskell # # LANGUAGE FlexibleContexts # module Main where import Feldspar (Length, Complex) import Feldspar.Algorithm.FFT import Feldspar.Compiler import Feldspar.Compiler.Plugin import Feldspar.Compiler.Marshal import Foreign.Ptr import Foreign.Marshal (new) import Control.DeepSeq (NFData(..)) import Control.Exception (evaluate) import BenchmarkUtils import Criterion.Main testdata :: [Complex Float] testdata = cycle [1,2,3,4] loadFunOpts ["-optc=-O2"] ['fft] loadFunOpts ["-optc=-O2"] ['ifft] len :: Length len = 4096 sizes :: [[Length]] sizes = map (map (*len)) [[1],[2],[4],[8]] setupPlugins :: IO () setupPlugins = do _ <- evaluate c_fft_builder return () setupData :: [Length] -> IO (Ptr (SA (Complex Float)), Ptr (SA (Complex Float))) setupData lengths = do d <- mkData testdata lengths ds <- allocSA $ fromIntegral $ product lengths :: IO (Ptr (SA (Complex Float))) return (ds, d) mkComp :: [Length] -> Benchmark mkComp ls = env (setupData ls) $ \ ~(o, d) -> mkBench "c_fft" ls (whnfIO $ c_fft_raw d o) main :: IO () main = defaultMainWith (mkConfig "report_fft.html") [ env setupPlugins $ \_ -> bgroup "compiled" $ map mkComp sizes ]
null
https://raw.githubusercontent.com/Feldspar/feldspar-language/499e4e42d462f436a5267ddf0c2f73d5741a8248/benchs/FFT.hs
haskell
# LANGUAGE BangPatterns #
# LANGUAGE TemplateHaskell # # LANGUAGE FlexibleContexts # module Main where import Feldspar (Length, Complex) import Feldspar.Algorithm.FFT import Feldspar.Compiler import Feldspar.Compiler.Plugin import Feldspar.Compiler.Marshal import Foreign.Ptr import Foreign.Marshal (new) import Control.DeepSeq (NFData(..)) import Control.Exception (evaluate) import BenchmarkUtils import Criterion.Main testdata :: [Complex Float] testdata = cycle [1,2,3,4] loadFunOpts ["-optc=-O2"] ['fft] loadFunOpts ["-optc=-O2"] ['ifft] len :: Length len = 4096 sizes :: [[Length]] sizes = map (map (*len)) [[1],[2],[4],[8]] setupPlugins :: IO () setupPlugins = do _ <- evaluate c_fft_builder return () setupData :: [Length] -> IO (Ptr (SA (Complex Float)), Ptr (SA (Complex Float))) setupData lengths = do d <- mkData testdata lengths ds <- allocSA $ fromIntegral $ product lengths :: IO (Ptr (SA (Complex Float))) return (ds, d) mkComp :: [Length] -> Benchmark mkComp ls = env (setupData ls) $ \ ~(o, d) -> mkBench "c_fft" ls (whnfIO $ c_fft_raw d o) main :: IO () main = defaultMainWith (mkConfig "report_fft.html") [ env setupPlugins $ \_ -> bgroup "compiled" $ map mkComp sizes ]
2e7304e26036b341b041a71ecd805b0a6d6ed0441f25caecc67974d24eed4f08
maurer/symfuzz
analysis.mli
(* SymFuzz *) * analyzer main @author < sangkil.cha\@gmail.com > @since 2014 - 03 - 19 @author Sang Kil Cha <sangkil.cha\@gmail.com> @since 2014-03-19 *) 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 < organization > 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 SANG KIL CHA BE LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF THIS Copyright (c) 2014, Sang Kil Cha 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 <organization> 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 SANG KIL CHA BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS *) open Dependency open Context val proc_start : string (* log director *) -> int32 (* current analysis id *) -> string (* local socket name *) -> bool (* debug flag *) -> int (* tid *) -> address_t (* argvp *) -> int32 (* envc *) -> address_t (* envp *) -> unit val proc_end : int32 -> unit val bbl_instrument : address_t -> int32 -> string -> raw_context_t -> int -> int
null
https://raw.githubusercontent.com/maurer/symfuzz/ea6298746a23b6d266d28d27c6ff952a7bd14885/src/analyzer/analysis.mli
ocaml
SymFuzz log director current analysis id local socket name debug flag tid argvp envc envp
* analyzer main @author < sangkil.cha\@gmail.com > @since 2014 - 03 - 19 @author Sang Kil Cha <sangkil.cha\@gmail.com> @since 2014-03-19 *) 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 < organization > 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 SANG KIL CHA BE LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF THIS Copyright (c) 2014, Sang Kil Cha 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 <organization> 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 SANG KIL CHA BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS *) open Dependency open Context -> unit val proc_end : int32 -> unit val bbl_instrument : address_t -> int32 -> string -> raw_context_t -> int -> int
6906bf52c5ed53237ddb815e6de649e6074d8000cd2ad65cf7d89a17837f4dde
typelead/eta
tc240.hs
-- Checks that the types of the old binder and the binder implicitly introduced by grouping are linked {-# OPTIONS_GHC -XTransformListComp #-} module ShouldCompile where import Data.List(inits) foo :: [[[Int]]] foo = [ x | x <- [1..10] , then group using inits , then group using inits ]
null
https://raw.githubusercontent.com/typelead/eta/97ee2251bbc52294efbf60fa4342ce6f52c0d25c/tests/suite/typecheck/compile/tc240.hs
haskell
Checks that the types of the old binder and the binder implicitly introduced by grouping are linked # OPTIONS_GHC -XTransformListComp #
module ShouldCompile where import Data.List(inits) foo :: [[[Int]]] foo = [ x | x <- [1..10] , then group using inits , then group using inits ]
eabe0f7bf7909bd9b02e91b4bb66b506ff8169bcd8468544ae329f1c36767d5c
soenkehahn/generics-eot
ToString.hs
# LANGUAGE DefaultSignatures # # LANGUAGE FlexibleContexts # # LANGUAGE MonoLocalBinds # # LANGUAGE ScopedTypeVariables # module ToString (ToString(..)) where import Data.List import Generics.Eot class ToString a where toString :: a -> String default toString :: (HasEot a, ToStringG (Eot a)) => a -> String toString = toStringG instance ToString Bool where toString = show instance ToString Int where toString = show instance ToString () where toString = show toStringG :: forall a . (HasEot a, ToStringG (Eot a)) => a -> String toStringG a = toStringConss (constructors (datatype (Proxy :: Proxy a))) (toEot a) class ToStringG a where toStringConss :: [Constructor] -> a -> String instance (ToStringFields a, ToStringG b) => ToStringG (Either a b) where toStringConss (Constructor name fieldMeta : _) (Left fields) = name ++ format (toStringFields fields) where format fieldStrings = case fieldMeta of Selectors names -> " {" ++ intercalate ", " (zipWith (\ sel v -> sel ++ " = " ++ v) names fieldStrings) ++ "}" NoSelectors _ -> " " ++ unwords fieldStrings NoFields -> "" toStringConss (_ : r) (Right next) = toStringConss r next toStringConss [] _ = error "impossible" instance ToStringG Void where toStringConss _ = absurd class ToStringFields a where toStringFields :: a -> [String] instance (ToString x, ToStringFields xs) => ToStringFields (x, xs) where toStringFields (x, xs) = toString x : toStringFields xs instance ToStringFields () where toStringFields () = []
null
https://raw.githubusercontent.com/soenkehahn/generics-eot/cb001556d716deab72472f8c82f1b0eae326c25b/examples/ToString.hs
haskell
# LANGUAGE DefaultSignatures # # LANGUAGE FlexibleContexts # # LANGUAGE MonoLocalBinds # # LANGUAGE ScopedTypeVariables # module ToString (ToString(..)) where import Data.List import Generics.Eot class ToString a where toString :: a -> String default toString :: (HasEot a, ToStringG (Eot a)) => a -> String toString = toStringG instance ToString Bool where toString = show instance ToString Int where toString = show instance ToString () where toString = show toStringG :: forall a . (HasEot a, ToStringG (Eot a)) => a -> String toStringG a = toStringConss (constructors (datatype (Proxy :: Proxy a))) (toEot a) class ToStringG a where toStringConss :: [Constructor] -> a -> String instance (ToStringFields a, ToStringG b) => ToStringG (Either a b) where toStringConss (Constructor name fieldMeta : _) (Left fields) = name ++ format (toStringFields fields) where format fieldStrings = case fieldMeta of Selectors names -> " {" ++ intercalate ", " (zipWith (\ sel v -> sel ++ " = " ++ v) names fieldStrings) ++ "}" NoSelectors _ -> " " ++ unwords fieldStrings NoFields -> "" toStringConss (_ : r) (Right next) = toStringConss r next toStringConss [] _ = error "impossible" instance ToStringG Void where toStringConss _ = absurd class ToStringFields a where toStringFields :: a -> [String] instance (ToString x, ToStringFields xs) => ToStringFields (x, xs) where toStringFields (x, xs) = toString x : toStringFields xs instance ToStringFields () where toStringFields () = []
1d173e4423e5b57d957adef8e112db2a5260128924b46c44d1ffd19863321434
adaliu-gh/htdp
363-369.rkt
;;==================== 363 an Xexpr.v2 is a list : ;; - (cons Symbol XL) an XL is one of : ;; - '() ;; - Xexpr.v2 ;; - (cons Xexpr.v2 XL) - ( cons AL ( cons Xexpr.v2 XL ) ) ;; an Attribute is: ;; (cons Symbol (cons String '())) an AL is one of : ;; - '() ;; - (cons Attribute AL) ;;======================== 364 (define xexpr1 '(transition ((from "seen-e") (to "seen-f")) (l))) (define xexpr2 '(ul (li (word) (word)) (li (word)))) ;;========================== ;;365 1 . < server name="example.org"/ > 2 . < carcas><board><grass/><board/><player name="sam"/><carcas/ > 3 . < start/ > ;;=========================== 366 ;; Xexpr.v2 -> Symbol extract the name of the Xexpr (check-expect (xexpr-name xexpr1) 'transition) (check-expect (xexpr-name xexpr2) 'ul) (define (xexpr-name xexpr) (first xexpr)) ;; [List-of Attribute] or Xexpr.v2 -> Boolean ;; is the given value a list of attributes (define (list-of-attributes? x) (cond [(empty? x) #true] [else (local ((define possible-attribute (first x))) (cons? possible-attribute))])) ;; Xexpr.v2 -> [List-of Xexpr.v2] (check-expect (xexpr-content xexpr1) '((l))) (check-expect (xexpr-content xexpr2) '((li (word) (word)) (li (word)))) (define (xexpr-content xexpr) (local ((define optional-loa+content (rest xexpr))) (cond [(empty? optional-loa+content) '()] [else (local ((define loa-or-x (first optional-loa+content))) (if (list-of-attributes? loa-or-x) (rest optional-loa+content) optional-loa+content))]))) ;;============================ 369 (define attr1 '((name "ada") (age "21") (gender "f"))) ;; AL Symbol -> String (check-expect (find-attr attr1 'name) "ada") (check-expect (find-attr attr1 'addr) #false) (define (find-attr l s) (cond [(empty? l) #false] [else (if (equal? (first (first l)) s) (second (first l)) (find-attr (rest l) s))]))
null
https://raw.githubusercontent.com/adaliu-gh/htdp/a0fca8af2ae8bdcef40d56f6f45021dd92df2995/19-24%20Intertwined%20Data/363-369.rkt
racket
==================== - (cons Symbol XL) - '() - Xexpr.v2 - (cons Xexpr.v2 XL) an Attribute is: (cons Symbol (cons String '())) - '() - (cons Attribute AL) ======================== ========================== 365 =========================== Xexpr.v2 -> Symbol [List-of Attribute] or Xexpr.v2 -> Boolean is the given value a list of attributes Xexpr.v2 -> [List-of Xexpr.v2] ============================ AL Symbol -> String
363 an Xexpr.v2 is a list : an XL is one of : - ( cons AL ( cons Xexpr.v2 XL ) ) an AL is one of : 364 (define xexpr1 '(transition ((from "seen-e") (to "seen-f")) (l))) (define xexpr2 '(ul (li (word) (word)) (li (word)))) 1 . < server name="example.org"/ > 2 . < carcas><board><grass/><board/><player name="sam"/><carcas/ > 3 . < start/ > 366 extract the name of the Xexpr (check-expect (xexpr-name xexpr1) 'transition) (check-expect (xexpr-name xexpr2) 'ul) (define (xexpr-name xexpr) (first xexpr)) (define (list-of-attributes? x) (cond [(empty? x) #true] [else (local ((define possible-attribute (first x))) (cons? possible-attribute))])) (check-expect (xexpr-content xexpr1) '((l))) (check-expect (xexpr-content xexpr2) '((li (word) (word)) (li (word)))) (define (xexpr-content xexpr) (local ((define optional-loa+content (rest xexpr))) (cond [(empty? optional-loa+content) '()] [else (local ((define loa-or-x (first optional-loa+content))) (if (list-of-attributes? loa-or-x) (rest optional-loa+content) optional-loa+content))]))) 369 (define attr1 '((name "ada") (age "21") (gender "f"))) (check-expect (find-attr attr1 'name) "ada") (check-expect (find-attr attr1 'addr) #false) (define (find-attr l s) (cond [(empty? l) #false] [else (if (equal? (first (first l)) s) (second (first l)) (find-attr (rest l) s))]))
842352194520dd2681add793c768c7524ac3a54e5bd0018c28a9fd831fff6a91
trebb/phoros
util.lisp
PHOROS -- Photogrammetric Road Survey Copyright ( C ) 2011 , 2012 , 2017 ;;; ;;; This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 2 of the License , or ;;; (at your option) any later version. ;;; ;;; This program is distributed in the hope that it will be useful, ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;; GNU General Public License for more details. ;;; You should have received a copy of the GNU General Public License along with this program ; if not , write to the Free Software Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , USA . (in-package :phoros) (defun unqualified-symbol (symbol) (cond ((keywordp symbol) symbol) ((atom symbol) (intern (string symbol))) (t symbol))) (defmacro defun* (name lambda-list &body body) "Like defun, define a function, but with an additional lambda list keyword &mandatory-key which goes after the &key section or in place of it. &mandatory-key argument definitions are plain symbols (no lists). An error is signalled on function calls where one of those keyargs is missing." (let ((mandatory-key-position (position '&mandatory-key lambda-list)) (after-key-position (or (position '&allow-other-keys lambda-list) (position '&aux lambda-list)))) (when mandatory-key-position (setf lambda-list (append (subseq lambda-list 0 mandatory-key-position) (unless (position '&key lambda-list) '(&key)) (mapcar #'(lambda (k) `(,k (error ,(format nil "~A: argument ~A undefined" name k)))) (subseq lambda-list (1+ mandatory-key-position) after-key-position)) (when after-key-position (subseq lambda-list after-key-position)))))) `(defun ,name ,(delete (unqualified-symbol '&mandatory-key) lambda-list) ,@body)) (defmacro logged-query (message-tag &rest args) "Act like postmodern:query; additionally log some debug information tagged by the short string message-tag." (cl-utilities:with-unique-names (executed-query query-milliseconds query-result) `(let* (,executed-query ,query-milliseconds ,query-result (cl-postgres:*query-callback* #'(lambda (query-string clock-ticks) (setf ,query-milliseconds clock-ticks) (setf ,executed-query query-string)))) (prog1 (setf ,query-result (etypecase (car ',args) (list (typecase (caar ',args) (keyword ;s-sql form (query (sql-compile ',(car args)) ,@(cdr args))) (t ;function (supposedly) returning string (query ,@args)))) (string (query ,@args)) (symbol (query ,@args)))) (cl-log:log-message :sql "[~A] Query ~S~& took ~F seconds and yielded~& ~A." ,message-tag ,executed-query (/ ,query-milliseconds 1000) ,query-result))))) (defmacro with-restarting-connection (postgresql-credentials &body body) "Act like with-connection, but reconnect on database-reconnection-error" `(with-connection ,postgresql-credentials (handler-bind ((database-connection-error (lambda (err) (cl-log:log-message :warning "Need to reconnect database due to the following error:~&~A." (database-error-message err)) (invoke-restart :reconnect)))) ,@body))) (in-package :cli) (defmacro with-options ((&key log database aux-database tolerate-missing) (&rest options) &body body &aux postgresql-credentials) "Evaluate body with options bound to the values of the respective command line arguments. Signal error if tolerate-missing is nil and a command line argument doesn't have a value. Elements of options may be symbols named according to the :long-name argument of the option, or lists shaped like (symbol) which bind symbol to a list of values collected for multiple occurence of that option. If log is t, start logging first. If database or aux-database are t, evaluate body with the appropriate database connection(s) and bind the following additional variables to the values of the respective command line arguments: host, port, database, user, password, use-ssl; and/or aux-host, aux-port, aux-database, aux-user, aux-password, aux-use-ssl." (assert (not (and database aux-database)) () "Can't handle connection to both database and aux-database ~ at the same time.") (when database (setf options (append options '(host port database user password use-ssl))) (setf postgresql-credentials `(list ,(unqualified-symbol 'database) ,(unqualified-symbol 'user) ,(unqualified-symbol 'password) ,(unqualified-symbol 'host) :port ,(unqualified-symbol 'port) :use-ssl (s-sql:from-sql-name ,(unqualified-symbol 'use-ssl))))) (when aux-database (setf options (append options '(aux-host aux-port aux-database aux-user aux-password aux-use-ssl))) (setf postgresql-credentials `(list ,(unqualified-symbol 'aux-database) ,(unqualified-symbol 'aux-user) ,(unqualified-symbol ' aux-password) ,(unqualified-symbol 'aux-host) :port ,(unqualified-symbol 'aux-port) :use-ssl (s-sql:from-sql-name ,(unqualified-symbol 'aux-use-ssl))))) (when log (setf options (append options '(log-dir)))) (setf options (mapcar #'unqualified-symbol options)) (let* ((db-connected-body (if (or database aux-database) `((with-connection ,postgresql-credentials (muffle-postgresql-warnings) (handler-bind ((database-connection-error (lambda (err) (cl-log:log-message :warning "Need to reconnect database due to the following error:~&~A." (database-error-message err)) (invoke-restart :reconnect)))) ,@body))) body)) (logged-body (if log `((launch-logger ,(unqualified-symbol 'log-dir)) ,@db-connected-body) db-connected-body))) `(with-context (make-context) (let (,@(loop for option in (remove-duplicates options) if (symbolp option) collect (list option (if tolerate-missing `(getopt :long-name ,(string-downcase option)) `(getopt-mandatory ,(string-downcase option)))) else collect `(,(car option) (loop for i = ,(if tolerate-missing `(getopt :long-name ,(string-downcase (car option))) `(getopt-mandatory ,(string-downcase (car option)))) then (getopt :long-name ,(string-downcase (car option))) while i collect i)))) ,@logged-body))))
null
https://raw.githubusercontent.com/trebb/phoros/c589381e3f4a729c5602c5870a61f1c847edf201/util.lisp
lisp
This program is free software; you can redistribute it and/or modify either version 2 of the License , or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. if not , write to the Free Software Foundation , Inc. , additionally log some debug information s-sql form function (supposedly) returning string and/or
PHOROS -- Photogrammetric Road Survey Copyright ( C ) 2011 , 2012 , 2017 it under the terms of the GNU General Public License as published by You should have received a copy of the GNU General Public License along 51 Franklin Street , Fifth Floor , Boston , USA . (in-package :phoros) (defun unqualified-symbol (symbol) (cond ((keywordp symbol) symbol) ((atom symbol) (intern (string symbol))) (t symbol))) (defmacro defun* (name lambda-list &body body) "Like defun, define a function, but with an additional lambda list keyword &mandatory-key which goes after the &key section or in place of it. &mandatory-key argument definitions are plain symbols (no lists). An error is signalled on function calls where one of those keyargs is missing." (let ((mandatory-key-position (position '&mandatory-key lambda-list)) (after-key-position (or (position '&allow-other-keys lambda-list) (position '&aux lambda-list)))) (when mandatory-key-position (setf lambda-list (append (subseq lambda-list 0 mandatory-key-position) (unless (position '&key lambda-list) '(&key)) (mapcar #'(lambda (k) `(,k (error ,(format nil "~A: argument ~A undefined" name k)))) (subseq lambda-list (1+ mandatory-key-position) after-key-position)) (when after-key-position (subseq lambda-list after-key-position)))))) `(defun ,name ,(delete (unqualified-symbol '&mandatory-key) lambda-list) ,@body)) (defmacro logged-query (message-tag &rest args) tagged by the short string message-tag." (cl-utilities:with-unique-names (executed-query query-milliseconds query-result) `(let* (,executed-query ,query-milliseconds ,query-result (cl-postgres:*query-callback* #'(lambda (query-string clock-ticks) (setf ,query-milliseconds clock-ticks) (setf ,executed-query query-string)))) (prog1 (setf ,query-result (etypecase (car ',args) (list (typecase (caar ',args) (query (sql-compile ',(car args)) ,@(cdr args))) (query ,@args)))) (string (query ,@args)) (symbol (query ,@args)))) (cl-log:log-message :sql "[~A] Query ~S~& took ~F seconds and yielded~& ~A." ,message-tag ,executed-query (/ ,query-milliseconds 1000) ,query-result))))) (defmacro with-restarting-connection (postgresql-credentials &body body) "Act like with-connection, but reconnect on database-reconnection-error" `(with-connection ,postgresql-credentials (handler-bind ((database-connection-error (lambda (err) (cl-log:log-message :warning "Need to reconnect database due to the following error:~&~A." (database-error-message err)) (invoke-restart :reconnect)))) ,@body))) (in-package :cli) (defmacro with-options ((&key log database aux-database tolerate-missing) (&rest options) &body body &aux postgresql-credentials) "Evaluate body with options bound to the values of the respective command line arguments. Signal error if tolerate-missing is nil and a command line argument doesn't have a value. Elements of options may be symbols named according to the :long-name argument of the option, or lists shaped like (symbol) which bind symbol to a list of values collected for multiple occurence of that option. If log is t, start logging first. If database or aux-database are t, evaluate body with the appropriate database connection(s) and bind the following additional variables to the values of the respective command line aux-host, aux-port, aux-database, aux-user, aux-password, aux-use-ssl." (assert (not (and database aux-database)) () "Can't handle connection to both database and aux-database ~ at the same time.") (when database (setf options (append options '(host port database user password use-ssl))) (setf postgresql-credentials `(list ,(unqualified-symbol 'database) ,(unqualified-symbol 'user) ,(unqualified-symbol 'password) ,(unqualified-symbol 'host) :port ,(unqualified-symbol 'port) :use-ssl (s-sql:from-sql-name ,(unqualified-symbol 'use-ssl))))) (when aux-database (setf options (append options '(aux-host aux-port aux-database aux-user aux-password aux-use-ssl))) (setf postgresql-credentials `(list ,(unqualified-symbol 'aux-database) ,(unqualified-symbol 'aux-user) ,(unqualified-symbol ' aux-password) ,(unqualified-symbol 'aux-host) :port ,(unqualified-symbol 'aux-port) :use-ssl (s-sql:from-sql-name ,(unqualified-symbol 'aux-use-ssl))))) (when log (setf options (append options '(log-dir)))) (setf options (mapcar #'unqualified-symbol options)) (let* ((db-connected-body (if (or database aux-database) `((with-connection ,postgresql-credentials (muffle-postgresql-warnings) (handler-bind ((database-connection-error (lambda (err) (cl-log:log-message :warning "Need to reconnect database due to the following error:~&~A." (database-error-message err)) (invoke-restart :reconnect)))) ,@body))) body)) (logged-body (if log `((launch-logger ,(unqualified-symbol 'log-dir)) ,@db-connected-body) db-connected-body))) `(with-context (make-context) (let (,@(loop for option in (remove-duplicates options) if (symbolp option) collect (list option (if tolerate-missing `(getopt :long-name ,(string-downcase option)) `(getopt-mandatory ,(string-downcase option)))) else collect `(,(car option) (loop for i = ,(if tolerate-missing `(getopt :long-name ,(string-downcase (car option))) `(getopt-mandatory ,(string-downcase (car option)))) then (getopt :long-name ,(string-downcase (car option))) while i collect i)))) ,@logged-body))))
75b7fe0a4a9e11829b44730faae8456a58c05b497dcdf9be48ef441ab5d5e706
skanev/playground
34-tests.scm
(require rackunit rackunit/text-ui) (load "../34.scm") (define (run exp) (actual-value exp (setup-environment))) (define (to-s exp) (with-output-to-string (lambda () (run `(begin (define result ,exp) (print result)))))) (define sicp-4.34-tests (test-suite "Tests for SICP exercise 4.34" (check-equal? (to-s ''()) "()") (check-equal? (to-s ''(() a)) "(() a)") (check-equal? (to-s ''(a b c)) "(a b c)") (check-equal? (to-s ''(a (b c) d)) "(a (b c) d)") (check-equal? (to-s ''(a . b)) "(a . b)") (check-equal? (to-s '(begin (define pair (cons 'a pair)) pair)) "(a (...))") (check-equal? (to-s '(begin (define pair (cons 'a (cons pair 'b))) pair)) "(a (...) . b)" ) (check-equal? (to-s '(begin (define pair (cons 'a (cons pair (cons 'b '())))) pair)) "(a (...) b)") )) (run-tests sicp-4.34-tests)
null
https://raw.githubusercontent.com/skanev/playground/d88e53a7f277b35041c2f709771a0b96f993b310/scheme/sicp/04/tests/34-tests.scm
scheme
(require rackunit rackunit/text-ui) (load "../34.scm") (define (run exp) (actual-value exp (setup-environment))) (define (to-s exp) (with-output-to-string (lambda () (run `(begin (define result ,exp) (print result)))))) (define sicp-4.34-tests (test-suite "Tests for SICP exercise 4.34" (check-equal? (to-s ''()) "()") (check-equal? (to-s ''(() a)) "(() a)") (check-equal? (to-s ''(a b c)) "(a b c)") (check-equal? (to-s ''(a (b c) d)) "(a (b c) d)") (check-equal? (to-s ''(a . b)) "(a . b)") (check-equal? (to-s '(begin (define pair (cons 'a pair)) pair)) "(a (...))") (check-equal? (to-s '(begin (define pair (cons 'a (cons pair 'b))) pair)) "(a (...) . b)" ) (check-equal? (to-s '(begin (define pair (cons 'a (cons pair (cons 'b '())))) pair)) "(a (...) b)") )) (run-tests sicp-4.34-tests)
6ca719ef97c1f319c89d98a365d2ee02f30ca01c8852a10a6407f511fd5fe9ba
gethop-dev/stork
project.clj
(defproject dev.gethop/stork "0.1.8-SNAPSHOT" :description "Idempotent and atomic datom transacting for Datomic. Heavily inspired on avescodes/conformity." :url "-dev/stork" :license {:name "Eclipse Public License" :url "-v10.html"} :min-lein-version "2.9.8" :plugins [[jonase/eastwood "1.2.3"] [lein-cljfmt "0.8.0"]] :profiles {:dev {:dependencies [[org.clojure/clojure "1.10.0"] [com.datomic/datomic-free "0.9.5697"]] :source-paths ["dev"]}} :deploy-repositories [["snapshots" {:url "" :username :env/CLOJARS_USERNAME :password :env/CLOJARS_PASSWORD :sign-releases false}] ["releases" {:url "" :username :env/CLOJARS_USERNAME :password :env/CLOJARS_PASSWORD :sign-releases false}]])
null
https://raw.githubusercontent.com/gethop-dev/stork/57f422fe74f5d5d3b677327c0348deb59b816b8f/project.clj
clojure
(defproject dev.gethop/stork "0.1.8-SNAPSHOT" :description "Idempotent and atomic datom transacting for Datomic. Heavily inspired on avescodes/conformity." :url "-dev/stork" :license {:name "Eclipse Public License" :url "-v10.html"} :min-lein-version "2.9.8" :plugins [[jonase/eastwood "1.2.3"] [lein-cljfmt "0.8.0"]] :profiles {:dev {:dependencies [[org.clojure/clojure "1.10.0"] [com.datomic/datomic-free "0.9.5697"]] :source-paths ["dev"]}} :deploy-repositories [["snapshots" {:url "" :username :env/CLOJARS_USERNAME :password :env/CLOJARS_PASSWORD :sign-releases false}] ["releases" {:url "" :username :env/CLOJARS_USERNAME :password :env/CLOJARS_PASSWORD :sign-releases false}]])
5e1a058b522c00b7681b419698a7c0bfb29e43313981a76606306ad628d31f69
javalib-team/javalib
jParse.ml
* This file is part of Javalib * Copyright ( c)2004 * Copyright ( c)2007 ( Université de Rennes 1 ) * Copyright ( c)2007 , 2008 ( CNRS ) * Copyright ( c)2009 , ( INRIA ) * * This software is free software ; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 , 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 . * * You should have received a copy of the GNU Lesser General Public * License along with this program . If not , see * < / > . * This file is part of Javalib * Copyright (c)2004 Nicolas Cannasse * Copyright (c)2007 Tiphaine Turpin (Université de Rennes 1) * Copyright (c)2007, 2008 Laurent Hubert (CNRS) * Copyright (c)2009, Frederic Dabrowski (INRIA) * * This software is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1, 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. * * You should have received a copy of the GNU Lesser General Public * License along with this program. If not, see * </>. *) open JClassLow open JLib.IO.BigEndian open JBasics open JBasicsLow open JParseSignature type tmp_constant = | ConstantClass of int | ConstantField of int * int | ConstantMethod of int * int | ConstantInterfaceMethod of int * int | ConstantMethodType of int | ConstantMethodHandle of int * int | ConstantInvokeDynamic of int * int | ConstantString of int | ConstantInt of int32 | ConstantFloat of float | ConstantLong of int64 | ConstantDouble of float | ConstantNameAndType of int * int | ConstantStringUTF8 of string | ConstantModule of int | ConstantPackage of int | ConstantUnusable let parse_constant max ch = let cid = JLib.IO.read_byte ch in let index() = let n = read_ui16 ch in if n = 0 || n >= max then raise (Class_structure_error ("1: Illegal index in constant pool: " ^ string_of_int n)); n in match cid with | 7 -> ConstantClass (index()) | 9 -> let n1 = index() in let n2 = index() in ConstantField (n1,n2) | 10 -> let n1 = index() in let n2 = index() in ConstantMethod (n1,n2) | 11 -> let n1 = index() in let n2 = index() in ConstantInterfaceMethod (n1,n2) | 8 -> ConstantString (index()) | 3 -> ConstantInt (read_real_i32 ch) | 4 -> let f = Int32.float_of_bits (read_real_i32 ch) in ConstantFloat f | 5 -> ConstantLong (read_i64 ch) | 6 -> ConstantDouble (read_double ch) | 12 -> let n1 = index() in let n2 = index() in ConstantNameAndType (n1,n2) | 1 -> let len = read_ui16 ch in let str = JLib.IO.really_nread_string ch len in ConstantStringUTF8 str | 15 -> let kind = JLib.IO.read_byte ch in let n2 = index() in ConstantMethodHandle (kind,n2) | 16 -> let n1 = index() in ConstantMethodType n1 | 18 -> let n1 = read_ui16 ch in let n2 = index() in ConstantInvokeDynamic (n1,n2) | 19 -> ConstantModule(index()) | 20 -> ConstantPackage(index()) | cid -> raise (Class_structure_error ("Illegal constant kind: " ^ string_of_int cid)) let class_flags = [|`AccPublic; `AccRFU 0x2; `AccRFU 0x4; `AccRFU 0x8; `AccFinal; `AccSuper; `AccRFU 0x40; `AccRFU 0x80; `AccRFU 0x100; `AccInterface; `AccAbstract; `AccRFU 0x800; `AccSynthetic; `AccAnnotation; `AccEnum; `AccModule|] let innerclass_flags = [|`AccPublic; `AccPrivate; `AccProtected; `AccStatic; `AccFinal; `AccRFU 0x20; `AccRFU 0x40; `AccRFU 0x80; `AccRFU 0x100; `AccInterface; `AccAbstract; `AccRFU 0x800; `AccSynthetic; `AccAnnotation; `AccEnum; `AccRFU 0x8000|] let field_flags = [|`AccPublic; `AccPrivate; `AccProtected; `AccStatic; `AccFinal; `AccRFU 0x20; `AccVolatile; `AccTransient; `AccRFU 0x100; `AccRFU 0x200; `AccRFU 0x400; `AccRFU 0x800; `AccSynthetic; `AccRFU 0x2000; `AccEnum; `AccRFU 0x8000|] let method_flags = [|`AccPublic; `AccPrivate; `AccProtected; `AccStatic; `AccFinal; `AccSynchronized; `AccBridge; `AccVarArgs; `AccNative; `AccRFU 0x200; `AccAbstract; `AccStrict; `AccSynthetic; `AccRFU 0x2000; `AccRFU 0x4000; `AccRFU 0x8000|] let method_parameters_flags = [|`AccRFU 0x1; `AccRFU 0x2; `AccRFU 0x4; `AccRFU 0x8; `AccFinal; `AccRFU 0x20; `AccRFU 0x40; `AccRFU 0x80; `AccRFU 0x100; `AccRFU 0x200; `AccRFU 0x400; `AccRFU 0x800; `AccSynthetic; `AccRFU 0x2000; `AccRFU 0x4000; `AccMandated|] let parse_access_flags all_flags ch = let fl = read_ui16 ch in let flags = ref [] in Array.iteri (fun i f -> if fl land (1 lsl i) <> 0 then flags := f :: !flags) all_flags; !flags let parse_stackmap_type_info consts ch = match JLib.IO.read_byte ch with | 0 -> VTop | 1 -> VInteger | 2 -> VFloat | 3 -> VDouble | 4 -> VLong | 5 -> VNull | 6 -> VUninitializedThis | 7 -> VObject (get_object_type consts (read_ui16 ch)) | 8 -> VUninitialized (read_ui16 ch) | n -> raise (Class_structure_error ("Illegal stackmap type: " ^ string_of_int n)) (***************************************************************************) DFr : Addition for 1.6 stackmap * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * (***************************************************************************) let parse_stackmap_table consts ch = let kind = JLib.IO.read_byte ch in let stackmap = if ((kind>=0) && (kind<=63)) then SameFrame(kind) else if ((kind >=64) && (kind <=127)) then let vtype = parse_stackmap_type_info consts ch in SameLocals(kind,vtype) else if (kind=247) then let offset_delta = read_ui16 ch and vtype = parse_stackmap_type_info consts ch in SameLocalsExtended(kind,offset_delta,vtype) else if ((kind >=248) && (kind <=250)) then let offset_delta = read_ui16 ch in ChopFrame(kind,offset_delta) else if (kind=251) then let offset_delta = read_ui16 ch in SameFrameExtended(kind,offset_delta) else if ((kind >=252) && (kind <=254)) then let offset_delta = read_ui16 ch in let locals = List.init (kind-251) (fun _ -> parse_stackmap_type_info consts ch) in AppendFrame(kind,offset_delta,locals) else if (kind=255) then let offset_delta = read_ui16 ch in let nlocals = read_ui16 ch in let locals = List.init nlocals (fun _ -> parse_stackmap_type_info consts ch) in let nstack = read_ui16 ch in let stack = List.init nstack (fun _ -> parse_stackmap_type_info consts ch) in FullFrame(kind,offset_delta,locals,stack) else (print_string("Invalid stackmap kind\n");SameLocals(-1,VTop)) in stackmap (* Annotation parsing *) let rec parse_element_value consts ch = let tag = JLib.IO.read_byte ch in match Char.chr tag with | ('B' | 'C' | 'S' | 'Z' | 'I' | 'D' | 'F' | 'J' ) as c -> (* constants *) let constant_value_index = read_ui16 ch in let cst = get_constant consts constant_value_index in begin match c,cst with | 'B', ConstInt i -> EVCstByte (Int32.to_int i) | 'C', ConstInt i -> EVCstChar (Int32.to_int i) | 'S', ConstInt i -> EVCstShort (Int32.to_int i) | 'Z', ConstInt i -> EVCstBoolean (Int32.to_int i) | 'I', ConstInt i -> EVCstInt i | 'D', ConstDouble d -> EVCstDouble d | 'F', ConstFloat f -> EVCstFloat f | 'J', ConstLong l -> EVCstLong l | ('B' | 'C' | 'S' | 'Z' | 'I' | 'D' | 'F' | 'J' ),_ -> raise (Class_structure_error "A such constant cannot be referenced in such an \ annotation element") | _,_ -> assert false end | 's' (* string *) -> let constant_value_index = read_ui16 ch in let cst = get_string consts constant_value_index in EVCstString cst | 'e' -> (* enum constant *) let type_name_index = read_ui16 ch and const_name_index = read_ui16 ch in let enum_type = let vt = parse_field_descriptor (get_string consts type_name_index) in match vt with | TObject (TClass c) -> c | _ -> assert false and const_name = get_string consts const_name_index in EVEnum (enum_type,const_name) failwith ( " not implemented EVEnum("^type_name^","^const_name^ " ) " ) | 'c' -> (* class constant *) let descriptor = get_string consts (read_ui16 ch) in if descriptor = "V" then EVClass None else EVClass (Some (parse_field_descriptor descriptor)) | '@' -> (* annotation type *) EVAnnotation (parse_annotation consts ch) | '[' -> (* array *) let num_values = read_ui16 ch in let values = List.init num_values (fun _ -> parse_element_value consts ch) in EVArray values | _ -> raise (Class_structure_error "invalid tag in a element_value of an annotation") and parse_annotation consts ch = let type_index = read_ui16 ch and nb_ev_pairs = read_ui16 ch in let kind = let kind_value_type = parse_field_descriptor (get_string consts type_index) in match kind_value_type with | TObject (TClass cn) -> cn | _ -> raise (Class_structure_error "An annotation should only be a class") and ev_pairs = List.init nb_ev_pairs (fun _ -> let name = get_string consts (read_ui16 ch) and value = parse_element_value consts ch in (name, value)) in {kind = kind; element_value_pairs = ev_pairs} let parse_annotations consts ch = let num_annotations = read_ui16 ch in List.init num_annotations (fun _ -> parse_annotation consts ch) let parse_parameter_annotations consts ch = let num_parameters = JLib.IO.read_byte ch in List.init num_parameters (fun _ -> parse_annotations consts ch) let rec parse_code consts ch = let max_stack = read_ui16 ch in let max_locals = read_ui16 ch in let clen = match read_i32 ch with | toobig when toobig > 65535 -> raise (Class_structure_error "There must be less than 65536 bytes of instructions in a Code attribute") | ok -> ok in let code = JParseCode.parse_code ch clen in let exc_tbl_length = read_ui16 ch in let exc_tbl = List.init exc_tbl_length (fun _ -> let spc = read_ui16 ch in let epc = read_ui16 ch in let hpc = read_ui16 ch in let ct = match read_ui16 ch with | 0 -> None | ct -> match get_constant consts ct with | ConstClass (TClass c) -> Some c | _ -> raise (Class_structure_error ("Illegal class index (does not refer to a constant class)")) in { JCode.e_start = spc; JCode.e_end = epc; JCode.e_handler = hpc; JCode.e_catch_type = ct; } ) in let attrib_count = read_ui16 ch in let attribs = List.init attrib_count (fun _ -> parse_attribute [`LineNumberTable ; `LocalVariableTable ; `LocalVariableTypeTable; `StackMap] consts ch) in { c_max_stack = max_stack; c_max_locals = max_locals; c_exc_tbl = exc_tbl; c_attributes = attribs; c_code = code; } an attribute , if its name is in list . and parse_attribute list consts ch = let aname = get_string_ui16 consts ch in let error() = raise (Class_structure_error ("Ill-formed attribute " ^ aname)) in let alen = read_i32 ch in let check name = if not (List.mem name list) then raise Exit in try match aname with | "Signature" -> check `Signature; if alen <> 2 then error(); AttributeSignature (get_string_ui16 consts ch) | "EnclosingMethod" -> check `EnclosingMethod; if alen <> 4 then error(); let c = get_class_ui16 consts ch and m = match read_ui16 ch with | 0 -> None | n -> match get_constant consts n with | ConstNameAndType (n,t) -> Some (n,t) | _ -> raise (Class_structure_error "EnclosingMethod attribute cannot refer to a constant which is not a NameAndType") in AttributeEnclosingMethod (c,m) | "SourceDebugExtension" -> check `SourceDebugExtension; AttributeSourceDebugExtension (JLib.IO.really_nread_string ch alen) | "SourceFile" -> check `SourceFile; if alen <> 2 then error(); AttributeSourceFile (get_string_ui16 consts ch) | "ConstantValue" -> check `ConstantValue; if alen <> 2 then error(); AttributeConstant (get_constant_attribute consts (read_ui16 ch)) | "Code" -> check `Code; let ch = JLib.IO.input_string (JLib.IO.really_nread_string ch alen) in let parse_code _ = let ch, count = JLib.IO.pos_in ch in let code = parse_code consts ch in if count() <> alen then error(); code in AttributeCode (Lazy.from_fun parse_code) | "Exceptions" -> check `Exceptions; let nentry = read_ui16 ch in if nentry * 2 + 2 <> alen then error(); AttributeExceptions (List.init nentry (function _ -> get_class_ui16 consts ch)) | "InnerClasses" -> check `InnerClasses; let nentry = read_ui16 ch in if nentry * 8 + 2 <> alen then error(); AttributeInnerClasses (List.init nentry (function _ -> let inner = match (read_ui16 ch) with | 0 -> None | i -> Some (get_class consts i) in let outer = match (read_ui16 ch) with | 0 -> None | i -> Some (get_class consts i) in let inner_name = match (read_ui16 ch) with | 0 -> None | i -> Some (get_string consts i) in let flags = parse_access_flags innerclass_flags ch in inner, outer, inner_name, flags)) | "Synthetic" -> check `Synthetic; if alen <> 0 then error (); AttributeSynthetic | "LineNumberTable" -> check `LineNumberTable; let nentry = read_ui16 ch in if nentry * 4 + 2 <> alen then error(); AttributeLineNumberTable (List.init nentry (fun _ -> let pc = read_ui16 ch in let line = read_ui16 ch in pc , line)) | "LocalVariableTable" -> check `LocalVariableTable; let nentry = read_ui16 ch in if nentry * 10 + 2 <> alen then error(); AttributeLocalVariableTable (List.init nentry (function _ -> let start_pc = read_ui16 ch in let length = read_ui16 ch in let name = get_string_ui16 consts ch in let signature = parse_field_descriptor (get_string_ui16 consts ch) in let index = read_ui16 ch in start_pc, length, name, signature, index)) | "LocalVariableTypeTable" -> check `LocalVariableTypeTable; let nentry = read_ui16 ch in if nentry *10 + 2 <> alen then error(); AttributeLocalVariableTypeTable (List.init nentry (fun _ -> let start_pc = read_ui16 ch in let length = read_ui16 ch in let name = get_string_ui16 consts ch in let signature = parse_FieldTypeSignature (get_string_ui16 consts ch) in let index = read_ui16 ch in start_pc, length, name, signature, index)) | "Deprecated" -> check `Deprecated; if alen <> 0 then error (); AttributeDeprecated | "StackMapTable" -> DFr : Addition for 1.6 stackmap check `StackMap; let ch, count = JLib.IO.pos_in ch in let nentry = read_ui16 ch in let stackmap = List.init nentry (fun _ -> parse_stackmap_table consts ch ) in if count() <> alen then error(); AttributeStackMapTable stackmap | "RuntimeVisibleAnnotations" -> check `RuntimeVisibleAnnotations; AttributeRuntimeVisibleAnnotations (parse_annotations consts ch) | "RuntimeInvisibleAnnotations" -> check `RuntimeInvisibleAnnotations; AttributeRuntimeInvisibleAnnotations (parse_annotations consts ch) | "RuntimeVisibleParameterAnnotations" -> check `RuntimeVisibleParameterAnnotations; AttributeRuntimeVisibleParameterAnnotations (parse_parameter_annotations consts ch) | "RuntimeInvisibleParameterAnnotations" -> check `RuntimeInvisibleParameterAnnotations; AttributeRuntimeInvisibleParameterAnnotations (parse_parameter_annotations consts ch) | "AnnotationDefault" -> check `AnnotationDefault; AttributeAnnotationDefault (parse_element_value consts ch) | "BootstrapMethods" -> added in 1.8 to support invokedynamic check `BootstrapMethods; let nentry = read_ui16 ch in AttributeBootstrapMethods (List.init nentry (function _ -> let bootstrap_method_ref = get_method_handle_ui16 consts ch in let num_bootstrap_arguments = read_ui16 ch in let bootstrap_arguments = List.init num_bootstrap_arguments (function _ -> get_bootstrap_argument_ui16 consts ch) in { bm_ref = bootstrap_method_ref; bm_args = bootstrap_arguments; })) | "MethodParameters" -> check `MethodParameters; let nentry = JLib.IO.read_byte ch in AttributeMethodParameters (List.init nentry (function _ -> let name_index = read_ui16 ch in let name = if name_index = 0 then None else Some (get_string consts name_index) in let flags = parse_access_flags method_parameters_flags ch in { name; flags; }) ) | _ -> raise Exit with Exit -> AttributeUnknown (aname,JLib.IO.really_nread_string ch alen) let parse_field consts ch = let acc = parse_access_flags field_flags ch in let name = get_string_ui16 consts ch in let sign = parse_field_descriptor (get_string_ui16 consts ch) in let attrib_count = read_ui16 ch in let attrib_to_parse = let base_attrib = [`Synthetic ; `Deprecated ; `Signature; `RuntimeVisibleAnnotations; `RuntimeInvisibleAnnotations] in if List.exists ((=)`AccStatic) acc then `ConstantValue:: base_attrib else base_attrib in let attribs = List.init attrib_count (fun _ -> parse_attribute attrib_to_parse consts ch) in { f_name = name; f_descriptor = sign; f_attributes = attribs; f_flags = acc; } let parse_method consts ch = let acc = parse_access_flags method_flags ch in let name = get_string_ui16 consts ch in let sign = parse_method_descriptor (get_string_ui16 consts ch) in let attrib_count = read_ui16 ch in let attribs = List.init attrib_count (fun _ -> let to_parse = [`Code ; `Exceptions ; `RuntimeVisibleParameterAnnotations ; `RuntimeInvisibleParameterAnnotations ; `AnnotationDefault ; `MethodParameters ; `Synthetic ; `Deprecated ; `Signature ; `RuntimeVisibleAnnotations ; `RuntimeInvisibleAnnotations ; ] in parse_attribute to_parse consts ch) in { m_name = name; m_descriptor = sign; m_attributes = attribs; m_flags = acc; } let rec expand_constant consts n = let expand name cl nt = match expand_constant consts cl with | ConstClass c -> (match expand_constant consts nt with | ConstNameAndType (n,s) -> (c,n,s) | _ -> raise (Class_structure_error ("Illegal constant refered in place of NameAndType in " ^ name ^ " constant"))) | _ -> raise (Class_structure_error ("Illegal constant refered in place of a ConstClass in " ^ name ^ " constant")) in match consts.(n) with | ConstantClass i -> (match expand_constant consts i with | ConstStringUTF8 s -> ConstClass (parse_objectType s) | _ -> raise (Class_structure_error ("Illegal constant refered in place of a Class constant"))) | ConstantField (cl,nt) -> (match expand "Field" cl nt with | TClass c, n, SValue v -> ConstField (c, make_fs n v) | TClass _, _, _ -> raise (Class_structure_error ("Illegal type in Field constant: " ^ "")) | _ -> raise (Class_structure_error ("Illegal constant refered in place of a Field constant"))) | ConstantMethod (cl,nt) -> (match expand "Method" cl nt with | c, n, SMethod md -> let (args,rtype) = md_split md in ConstMethod (c, make_ms n args rtype) | _, _, SValue _ -> raise (Class_structure_error ("Illegal type in Method constant"))) | ConstantInterfaceMethod (cl,nt) -> (match expand "InterfaceMethod" cl nt with | TClass c, n, SMethod md -> let (args,rtype) = md_split md in ConstInterfaceMethod (c, make_ms n args rtype) | TClass _, _, _ -> raise (Class_structure_error ("Illegal type in Interface Method constant")) | _, _, _ -> raise (Class_structure_error ("Illegal constant refered in place of an Interface Method constant"))) | ConstantMethodType i -> (match expand_constant consts i with | ConstStringUTF8 s -> ConstMethodType (parse_method_descriptor s) | _ -> raise (Class_structure_error ("Illegal constant referred in place of a MethodType constant"))) | ConstantMethodHandle (kind, index) -> (match kind, expand_constant consts index with | 1, ConstField f -> ConstMethodHandle (`GetField f) | 2, ConstField f -> ConstMethodHandle (`GetStatic f) | 3, ConstField f -> ConstMethodHandle (`PutField f) | 4, ConstField f -> ConstMethodHandle (`PutStatic f) | 5, ConstMethod v -> ConstMethodHandle (`InvokeVirtual v) | 6, ConstMethod (TClass cn, ms) -> ConstMethodHandle (`InvokeStatic (`Method (cn, ms))) | 6, ConstInterfaceMethod v -> ConstMethodHandle (`InvokeStatic (`InterfaceMethod v)) | 7, ConstMethod (TClass cn, ms) -> ConstMethodHandle (`InvokeSpecial (`Method (cn, ms))) | 7, ConstInterfaceMethod v -> ConstMethodHandle (`InvokeSpecial (`InterfaceMethod v)) | 8, ConstMethod (TClass cn, ms) -> ConstMethodHandle (`NewInvokeSpecial (cn, ms)) | 9, ConstInterfaceMethod v -> ConstMethodHandle (`InvokeInterface v) | n, c -> let s = JLib.IO.output_string () in JDumpBasics.dump_constant s c; let str = JLib.IO.close_out s in raise (Class_structure_error ("Bad method handle constant " ^ (string_of_int n) ^ str))) | ConstantInvokeDynamic (bmi,nt) -> (match expand_constant consts nt with | ConstNameAndType (n, SMethod md) -> let (args,rtype) = md_split md in ConstInvokeDynamic (bmi, make_ms n args rtype) | _ -> raise (Class_structure_error ("Illegal constant referred in place of an InvokeDynamic constant"))) | ConstantString i -> (match expand_constant consts i with | ConstStringUTF8 s -> ConstString (make_jstr s) | _ -> raise (Class_structure_error ("Illegal constant refered in place of a String constant"))) | ConstantInt i -> ConstInt i | ConstantFloat f -> ConstFloat f | ConstantLong l -> ConstLong l | ConstantDouble f -> ConstDouble f | ConstantNameAndType (n,t) -> (match expand_constant consts n , expand_constant consts t with | ConstStringUTF8 n , ConstStringUTF8 t -> ConstNameAndType (n,parse_descriptor t) | ConstStringUTF8 _ , _ -> raise (Class_structure_error ("Illegal type in a NameAndType constant")) | _ -> raise (Class_structure_error ("Illegal constant refered in place of a NameAndType constant"))) | ConstantStringUTF8 s -> ConstStringUTF8 s | ConstantModule i -> (match expand_constant consts i with | ConstStringUTF8 s -> ConstModule s | _ -> raise (Class_structure_error ("Illegal constant refered in place of a module name"))) | ConstantPackage i -> (match expand_constant consts i with | ConstStringUTF8 s -> ConstPackage s | _ -> raise (Class_structure_error ("Illegal constant refered in place of a package name"))) | ConstantUnusable -> ConstUnusable let parse_class_low_level ch = let magic = read_real_i32 ch in if magic <> 0xCAFEBABEl then raise (Class_structure_error "Invalid magic number"); let version_minor = read_ui16 ch in let version_major = read_ui16 ch in let constant_count = read_ui16 ch in let const_big = ref true in let consts = Array.init constant_count (fun _ -> if !const_big then begin const_big := false; ConstantUnusable end else let c = parse_constant constant_count ch in (match c with ConstantLong _ | ConstantDouble _ -> const_big := true | _ -> ()); c ) in let consts = Array.mapi (fun i _ -> expand_constant consts i) consts in let flags = parse_access_flags class_flags ch in let this = get_class_ui16 consts ch in let super_idx = read_ui16 ch in let super = if super_idx = 0 then None else Some (get_class consts super_idx) in let interface_count = read_ui16 ch in let interfaces = List.init interface_count (fun _ -> get_class_ui16 consts ch) in let field_count = read_ui16 ch in let fields = List.init field_count (fun _ -> parse_field consts ch) in let method_count = read_ui16 ch in let methods = List.init method_count (fun _ -> parse_method consts ch) in let attrib_count = read_ui16 ch in let attribs = List.init attrib_count (fun _ -> let to_parse = [`SourceFile; `InnerClasses ; `EnclosingMethod ; `SourceDebugExtension ; `BootstrapMethods; `Synthetic ; `Deprecated; `Signature; `RuntimeVisibleAnnotations; `RuntimeInvisibleAnnotations; ] in parse_attribute to_parse consts ch) in let (bootstrap_table, attribs) = List.partition (function AttributeBootstrapMethods _ -> true | _ -> false) attribs in let bootstrap_table = (match bootstrap_table with | [] -> [] | (AttributeBootstrapMethods l) :: [] -> l | _ -> raise (Class_structure_error "A class may contain at most one bootstrap table"); ) in {j_consts = consts; j_flags = flags; j_name = this; j_super = super; j_interfaces = interfaces; j_fields = fields; j_methods = methods; j_attributes = attribs; j_bootstrap_table = Array.of_list bootstrap_table; j_version = {major=version_major; minor=version_minor}; } if the parsing raises a class_structure_error exception , we close the input ourself let parse_class_low_level ch = try parse_class_low_level ch with Class_structure_error _ as e -> JLib.IO.close_in ch; raise e let parse_class ch = JLow2High.low2high_class (parse_class_low_level ch)
null
https://raw.githubusercontent.com/javalib-team/javalib/807881077342a1a22650e6a9906ae5c2743a9940/src/jParse.ml
ocaml
************************************************************************* ************************************************************************* Annotation parsing constants string enum constant class constant annotation type array
* This file is part of Javalib * Copyright ( c)2004 * Copyright ( c)2007 ( Université de Rennes 1 ) * Copyright ( c)2007 , 2008 ( CNRS ) * Copyright ( c)2009 , ( INRIA ) * * This software is free software ; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 , 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 . * * You should have received a copy of the GNU Lesser General Public * License along with this program . If not , see * < / > . * This file is part of Javalib * Copyright (c)2004 Nicolas Cannasse * Copyright (c)2007 Tiphaine Turpin (Université de Rennes 1) * Copyright (c)2007, 2008 Laurent Hubert (CNRS) * Copyright (c)2009, Frederic Dabrowski (INRIA) * * This software is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1, 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. * * You should have received a copy of the GNU Lesser General Public * License along with this program. If not, see * </>. *) open JClassLow open JLib.IO.BigEndian open JBasics open JBasicsLow open JParseSignature type tmp_constant = | ConstantClass of int | ConstantField of int * int | ConstantMethod of int * int | ConstantInterfaceMethod of int * int | ConstantMethodType of int | ConstantMethodHandle of int * int | ConstantInvokeDynamic of int * int | ConstantString of int | ConstantInt of int32 | ConstantFloat of float | ConstantLong of int64 | ConstantDouble of float | ConstantNameAndType of int * int | ConstantStringUTF8 of string | ConstantModule of int | ConstantPackage of int | ConstantUnusable let parse_constant max ch = let cid = JLib.IO.read_byte ch in let index() = let n = read_ui16 ch in if n = 0 || n >= max then raise (Class_structure_error ("1: Illegal index in constant pool: " ^ string_of_int n)); n in match cid with | 7 -> ConstantClass (index()) | 9 -> let n1 = index() in let n2 = index() in ConstantField (n1,n2) | 10 -> let n1 = index() in let n2 = index() in ConstantMethod (n1,n2) | 11 -> let n1 = index() in let n2 = index() in ConstantInterfaceMethod (n1,n2) | 8 -> ConstantString (index()) | 3 -> ConstantInt (read_real_i32 ch) | 4 -> let f = Int32.float_of_bits (read_real_i32 ch) in ConstantFloat f | 5 -> ConstantLong (read_i64 ch) | 6 -> ConstantDouble (read_double ch) | 12 -> let n1 = index() in let n2 = index() in ConstantNameAndType (n1,n2) | 1 -> let len = read_ui16 ch in let str = JLib.IO.really_nread_string ch len in ConstantStringUTF8 str | 15 -> let kind = JLib.IO.read_byte ch in let n2 = index() in ConstantMethodHandle (kind,n2) | 16 -> let n1 = index() in ConstantMethodType n1 | 18 -> let n1 = read_ui16 ch in let n2 = index() in ConstantInvokeDynamic (n1,n2) | 19 -> ConstantModule(index()) | 20 -> ConstantPackage(index()) | cid -> raise (Class_structure_error ("Illegal constant kind: " ^ string_of_int cid)) let class_flags = [|`AccPublic; `AccRFU 0x2; `AccRFU 0x4; `AccRFU 0x8; `AccFinal; `AccSuper; `AccRFU 0x40; `AccRFU 0x80; `AccRFU 0x100; `AccInterface; `AccAbstract; `AccRFU 0x800; `AccSynthetic; `AccAnnotation; `AccEnum; `AccModule|] let innerclass_flags = [|`AccPublic; `AccPrivate; `AccProtected; `AccStatic; `AccFinal; `AccRFU 0x20; `AccRFU 0x40; `AccRFU 0x80; `AccRFU 0x100; `AccInterface; `AccAbstract; `AccRFU 0x800; `AccSynthetic; `AccAnnotation; `AccEnum; `AccRFU 0x8000|] let field_flags = [|`AccPublic; `AccPrivate; `AccProtected; `AccStatic; `AccFinal; `AccRFU 0x20; `AccVolatile; `AccTransient; `AccRFU 0x100; `AccRFU 0x200; `AccRFU 0x400; `AccRFU 0x800; `AccSynthetic; `AccRFU 0x2000; `AccEnum; `AccRFU 0x8000|] let method_flags = [|`AccPublic; `AccPrivate; `AccProtected; `AccStatic; `AccFinal; `AccSynchronized; `AccBridge; `AccVarArgs; `AccNative; `AccRFU 0x200; `AccAbstract; `AccStrict; `AccSynthetic; `AccRFU 0x2000; `AccRFU 0x4000; `AccRFU 0x8000|] let method_parameters_flags = [|`AccRFU 0x1; `AccRFU 0x2; `AccRFU 0x4; `AccRFU 0x8; `AccFinal; `AccRFU 0x20; `AccRFU 0x40; `AccRFU 0x80; `AccRFU 0x100; `AccRFU 0x200; `AccRFU 0x400; `AccRFU 0x800; `AccSynthetic; `AccRFU 0x2000; `AccRFU 0x4000; `AccMandated|] let parse_access_flags all_flags ch = let fl = read_ui16 ch in let flags = ref [] in Array.iteri (fun i f -> if fl land (1 lsl i) <> 0 then flags := f :: !flags) all_flags; !flags let parse_stackmap_type_info consts ch = match JLib.IO.read_byte ch with | 0 -> VTop | 1 -> VInteger | 2 -> VFloat | 3 -> VDouble | 4 -> VLong | 5 -> VNull | 6 -> VUninitializedThis | 7 -> VObject (get_object_type consts (read_ui16 ch)) | 8 -> VUninitialized (read_ui16 ch) | n -> raise (Class_structure_error ("Illegal stackmap type: " ^ string_of_int n)) DFr : Addition for 1.6 stackmap * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * let parse_stackmap_table consts ch = let kind = JLib.IO.read_byte ch in let stackmap = if ((kind>=0) && (kind<=63)) then SameFrame(kind) else if ((kind >=64) && (kind <=127)) then let vtype = parse_stackmap_type_info consts ch in SameLocals(kind,vtype) else if (kind=247) then let offset_delta = read_ui16 ch and vtype = parse_stackmap_type_info consts ch in SameLocalsExtended(kind,offset_delta,vtype) else if ((kind >=248) && (kind <=250)) then let offset_delta = read_ui16 ch in ChopFrame(kind,offset_delta) else if (kind=251) then let offset_delta = read_ui16 ch in SameFrameExtended(kind,offset_delta) else if ((kind >=252) && (kind <=254)) then let offset_delta = read_ui16 ch in let locals = List.init (kind-251) (fun _ -> parse_stackmap_type_info consts ch) in AppendFrame(kind,offset_delta,locals) else if (kind=255) then let offset_delta = read_ui16 ch in let nlocals = read_ui16 ch in let locals = List.init nlocals (fun _ -> parse_stackmap_type_info consts ch) in let nstack = read_ui16 ch in let stack = List.init nstack (fun _ -> parse_stackmap_type_info consts ch) in FullFrame(kind,offset_delta,locals,stack) else (print_string("Invalid stackmap kind\n");SameLocals(-1,VTop)) in stackmap let rec parse_element_value consts ch = let tag = JLib.IO.read_byte ch in match Char.chr tag with let constant_value_index = read_ui16 ch in let cst = get_constant consts constant_value_index in begin match c,cst with | 'B', ConstInt i -> EVCstByte (Int32.to_int i) | 'C', ConstInt i -> EVCstChar (Int32.to_int i) | 'S', ConstInt i -> EVCstShort (Int32.to_int i) | 'Z', ConstInt i -> EVCstBoolean (Int32.to_int i) | 'I', ConstInt i -> EVCstInt i | 'D', ConstDouble d -> EVCstDouble d | 'F', ConstFloat f -> EVCstFloat f | 'J', ConstLong l -> EVCstLong l | ('B' | 'C' | 'S' | 'Z' | 'I' | 'D' | 'F' | 'J' ),_ -> raise (Class_structure_error "A such constant cannot be referenced in such an \ annotation element") | _,_ -> assert false end -> let constant_value_index = read_ui16 ch in let cst = get_string consts constant_value_index in EVCstString cst let type_name_index = read_ui16 ch and const_name_index = read_ui16 ch in let enum_type = let vt = parse_field_descriptor (get_string consts type_name_index) in match vt with | TObject (TClass c) -> c | _ -> assert false and const_name = get_string consts const_name_index in EVEnum (enum_type,const_name) failwith ( " not implemented EVEnum("^type_name^","^const_name^ " ) " ) let descriptor = get_string consts (read_ui16 ch) in if descriptor = "V" then EVClass None else EVClass (Some (parse_field_descriptor descriptor)) EVAnnotation (parse_annotation consts ch) let num_values = read_ui16 ch in let values = List.init num_values (fun _ -> parse_element_value consts ch) in EVArray values | _ -> raise (Class_structure_error "invalid tag in a element_value of an annotation") and parse_annotation consts ch = let type_index = read_ui16 ch and nb_ev_pairs = read_ui16 ch in let kind = let kind_value_type = parse_field_descriptor (get_string consts type_index) in match kind_value_type with | TObject (TClass cn) -> cn | _ -> raise (Class_structure_error "An annotation should only be a class") and ev_pairs = List.init nb_ev_pairs (fun _ -> let name = get_string consts (read_ui16 ch) and value = parse_element_value consts ch in (name, value)) in {kind = kind; element_value_pairs = ev_pairs} let parse_annotations consts ch = let num_annotations = read_ui16 ch in List.init num_annotations (fun _ -> parse_annotation consts ch) let parse_parameter_annotations consts ch = let num_parameters = JLib.IO.read_byte ch in List.init num_parameters (fun _ -> parse_annotations consts ch) let rec parse_code consts ch = let max_stack = read_ui16 ch in let max_locals = read_ui16 ch in let clen = match read_i32 ch with | toobig when toobig > 65535 -> raise (Class_structure_error "There must be less than 65536 bytes of instructions in a Code attribute") | ok -> ok in let code = JParseCode.parse_code ch clen in let exc_tbl_length = read_ui16 ch in let exc_tbl = List.init exc_tbl_length (fun _ -> let spc = read_ui16 ch in let epc = read_ui16 ch in let hpc = read_ui16 ch in let ct = match read_ui16 ch with | 0 -> None | ct -> match get_constant consts ct with | ConstClass (TClass c) -> Some c | _ -> raise (Class_structure_error ("Illegal class index (does not refer to a constant class)")) in { JCode.e_start = spc; JCode.e_end = epc; JCode.e_handler = hpc; JCode.e_catch_type = ct; } ) in let attrib_count = read_ui16 ch in let attribs = List.init attrib_count (fun _ -> parse_attribute [`LineNumberTable ; `LocalVariableTable ; `LocalVariableTypeTable; `StackMap] consts ch) in { c_max_stack = max_stack; c_max_locals = max_locals; c_exc_tbl = exc_tbl; c_attributes = attribs; c_code = code; } an attribute , if its name is in list . and parse_attribute list consts ch = let aname = get_string_ui16 consts ch in let error() = raise (Class_structure_error ("Ill-formed attribute " ^ aname)) in let alen = read_i32 ch in let check name = if not (List.mem name list) then raise Exit in try match aname with | "Signature" -> check `Signature; if alen <> 2 then error(); AttributeSignature (get_string_ui16 consts ch) | "EnclosingMethod" -> check `EnclosingMethod; if alen <> 4 then error(); let c = get_class_ui16 consts ch and m = match read_ui16 ch with | 0 -> None | n -> match get_constant consts n with | ConstNameAndType (n,t) -> Some (n,t) | _ -> raise (Class_structure_error "EnclosingMethod attribute cannot refer to a constant which is not a NameAndType") in AttributeEnclosingMethod (c,m) | "SourceDebugExtension" -> check `SourceDebugExtension; AttributeSourceDebugExtension (JLib.IO.really_nread_string ch alen) | "SourceFile" -> check `SourceFile; if alen <> 2 then error(); AttributeSourceFile (get_string_ui16 consts ch) | "ConstantValue" -> check `ConstantValue; if alen <> 2 then error(); AttributeConstant (get_constant_attribute consts (read_ui16 ch)) | "Code" -> check `Code; let ch = JLib.IO.input_string (JLib.IO.really_nread_string ch alen) in let parse_code _ = let ch, count = JLib.IO.pos_in ch in let code = parse_code consts ch in if count() <> alen then error(); code in AttributeCode (Lazy.from_fun parse_code) | "Exceptions" -> check `Exceptions; let nentry = read_ui16 ch in if nentry * 2 + 2 <> alen then error(); AttributeExceptions (List.init nentry (function _ -> get_class_ui16 consts ch)) | "InnerClasses" -> check `InnerClasses; let nentry = read_ui16 ch in if nentry * 8 + 2 <> alen then error(); AttributeInnerClasses (List.init nentry (function _ -> let inner = match (read_ui16 ch) with | 0 -> None | i -> Some (get_class consts i) in let outer = match (read_ui16 ch) with | 0 -> None | i -> Some (get_class consts i) in let inner_name = match (read_ui16 ch) with | 0 -> None | i -> Some (get_string consts i) in let flags = parse_access_flags innerclass_flags ch in inner, outer, inner_name, flags)) | "Synthetic" -> check `Synthetic; if alen <> 0 then error (); AttributeSynthetic | "LineNumberTable" -> check `LineNumberTable; let nentry = read_ui16 ch in if nentry * 4 + 2 <> alen then error(); AttributeLineNumberTable (List.init nentry (fun _ -> let pc = read_ui16 ch in let line = read_ui16 ch in pc , line)) | "LocalVariableTable" -> check `LocalVariableTable; let nentry = read_ui16 ch in if nentry * 10 + 2 <> alen then error(); AttributeLocalVariableTable (List.init nentry (function _ -> let start_pc = read_ui16 ch in let length = read_ui16 ch in let name = get_string_ui16 consts ch in let signature = parse_field_descriptor (get_string_ui16 consts ch) in let index = read_ui16 ch in start_pc, length, name, signature, index)) | "LocalVariableTypeTable" -> check `LocalVariableTypeTable; let nentry = read_ui16 ch in if nentry *10 + 2 <> alen then error(); AttributeLocalVariableTypeTable (List.init nentry (fun _ -> let start_pc = read_ui16 ch in let length = read_ui16 ch in let name = get_string_ui16 consts ch in let signature = parse_FieldTypeSignature (get_string_ui16 consts ch) in let index = read_ui16 ch in start_pc, length, name, signature, index)) | "Deprecated" -> check `Deprecated; if alen <> 0 then error (); AttributeDeprecated | "StackMapTable" -> DFr : Addition for 1.6 stackmap check `StackMap; let ch, count = JLib.IO.pos_in ch in let nentry = read_ui16 ch in let stackmap = List.init nentry (fun _ -> parse_stackmap_table consts ch ) in if count() <> alen then error(); AttributeStackMapTable stackmap | "RuntimeVisibleAnnotations" -> check `RuntimeVisibleAnnotations; AttributeRuntimeVisibleAnnotations (parse_annotations consts ch) | "RuntimeInvisibleAnnotations" -> check `RuntimeInvisibleAnnotations; AttributeRuntimeInvisibleAnnotations (parse_annotations consts ch) | "RuntimeVisibleParameterAnnotations" -> check `RuntimeVisibleParameterAnnotations; AttributeRuntimeVisibleParameterAnnotations (parse_parameter_annotations consts ch) | "RuntimeInvisibleParameterAnnotations" -> check `RuntimeInvisibleParameterAnnotations; AttributeRuntimeInvisibleParameterAnnotations (parse_parameter_annotations consts ch) | "AnnotationDefault" -> check `AnnotationDefault; AttributeAnnotationDefault (parse_element_value consts ch) | "BootstrapMethods" -> added in 1.8 to support invokedynamic check `BootstrapMethods; let nentry = read_ui16 ch in AttributeBootstrapMethods (List.init nentry (function _ -> let bootstrap_method_ref = get_method_handle_ui16 consts ch in let num_bootstrap_arguments = read_ui16 ch in let bootstrap_arguments = List.init num_bootstrap_arguments (function _ -> get_bootstrap_argument_ui16 consts ch) in { bm_ref = bootstrap_method_ref; bm_args = bootstrap_arguments; })) | "MethodParameters" -> check `MethodParameters; let nentry = JLib.IO.read_byte ch in AttributeMethodParameters (List.init nentry (function _ -> let name_index = read_ui16 ch in let name = if name_index = 0 then None else Some (get_string consts name_index) in let flags = parse_access_flags method_parameters_flags ch in { name; flags; }) ) | _ -> raise Exit with Exit -> AttributeUnknown (aname,JLib.IO.really_nread_string ch alen) let parse_field consts ch = let acc = parse_access_flags field_flags ch in let name = get_string_ui16 consts ch in let sign = parse_field_descriptor (get_string_ui16 consts ch) in let attrib_count = read_ui16 ch in let attrib_to_parse = let base_attrib = [`Synthetic ; `Deprecated ; `Signature; `RuntimeVisibleAnnotations; `RuntimeInvisibleAnnotations] in if List.exists ((=)`AccStatic) acc then `ConstantValue:: base_attrib else base_attrib in let attribs = List.init attrib_count (fun _ -> parse_attribute attrib_to_parse consts ch) in { f_name = name; f_descriptor = sign; f_attributes = attribs; f_flags = acc; } let parse_method consts ch = let acc = parse_access_flags method_flags ch in let name = get_string_ui16 consts ch in let sign = parse_method_descriptor (get_string_ui16 consts ch) in let attrib_count = read_ui16 ch in let attribs = List.init attrib_count (fun _ -> let to_parse = [`Code ; `Exceptions ; `RuntimeVisibleParameterAnnotations ; `RuntimeInvisibleParameterAnnotations ; `AnnotationDefault ; `MethodParameters ; `Synthetic ; `Deprecated ; `Signature ; `RuntimeVisibleAnnotations ; `RuntimeInvisibleAnnotations ; ] in parse_attribute to_parse consts ch) in { m_name = name; m_descriptor = sign; m_attributes = attribs; m_flags = acc; } let rec expand_constant consts n = let expand name cl nt = match expand_constant consts cl with | ConstClass c -> (match expand_constant consts nt with | ConstNameAndType (n,s) -> (c,n,s) | _ -> raise (Class_structure_error ("Illegal constant refered in place of NameAndType in " ^ name ^ " constant"))) | _ -> raise (Class_structure_error ("Illegal constant refered in place of a ConstClass in " ^ name ^ " constant")) in match consts.(n) with | ConstantClass i -> (match expand_constant consts i with | ConstStringUTF8 s -> ConstClass (parse_objectType s) | _ -> raise (Class_structure_error ("Illegal constant refered in place of a Class constant"))) | ConstantField (cl,nt) -> (match expand "Field" cl nt with | TClass c, n, SValue v -> ConstField (c, make_fs n v) | TClass _, _, _ -> raise (Class_structure_error ("Illegal type in Field constant: " ^ "")) | _ -> raise (Class_structure_error ("Illegal constant refered in place of a Field constant"))) | ConstantMethod (cl,nt) -> (match expand "Method" cl nt with | c, n, SMethod md -> let (args,rtype) = md_split md in ConstMethod (c, make_ms n args rtype) | _, _, SValue _ -> raise (Class_structure_error ("Illegal type in Method constant"))) | ConstantInterfaceMethod (cl,nt) -> (match expand "InterfaceMethod" cl nt with | TClass c, n, SMethod md -> let (args,rtype) = md_split md in ConstInterfaceMethod (c, make_ms n args rtype) | TClass _, _, _ -> raise (Class_structure_error ("Illegal type in Interface Method constant")) | _, _, _ -> raise (Class_structure_error ("Illegal constant refered in place of an Interface Method constant"))) | ConstantMethodType i -> (match expand_constant consts i with | ConstStringUTF8 s -> ConstMethodType (parse_method_descriptor s) | _ -> raise (Class_structure_error ("Illegal constant referred in place of a MethodType constant"))) | ConstantMethodHandle (kind, index) -> (match kind, expand_constant consts index with | 1, ConstField f -> ConstMethodHandle (`GetField f) | 2, ConstField f -> ConstMethodHandle (`GetStatic f) | 3, ConstField f -> ConstMethodHandle (`PutField f) | 4, ConstField f -> ConstMethodHandle (`PutStatic f) | 5, ConstMethod v -> ConstMethodHandle (`InvokeVirtual v) | 6, ConstMethod (TClass cn, ms) -> ConstMethodHandle (`InvokeStatic (`Method (cn, ms))) | 6, ConstInterfaceMethod v -> ConstMethodHandle (`InvokeStatic (`InterfaceMethod v)) | 7, ConstMethod (TClass cn, ms) -> ConstMethodHandle (`InvokeSpecial (`Method (cn, ms))) | 7, ConstInterfaceMethod v -> ConstMethodHandle (`InvokeSpecial (`InterfaceMethod v)) | 8, ConstMethod (TClass cn, ms) -> ConstMethodHandle (`NewInvokeSpecial (cn, ms)) | 9, ConstInterfaceMethod v -> ConstMethodHandle (`InvokeInterface v) | n, c -> let s = JLib.IO.output_string () in JDumpBasics.dump_constant s c; let str = JLib.IO.close_out s in raise (Class_structure_error ("Bad method handle constant " ^ (string_of_int n) ^ str))) | ConstantInvokeDynamic (bmi,nt) -> (match expand_constant consts nt with | ConstNameAndType (n, SMethod md) -> let (args,rtype) = md_split md in ConstInvokeDynamic (bmi, make_ms n args rtype) | _ -> raise (Class_structure_error ("Illegal constant referred in place of an InvokeDynamic constant"))) | ConstantString i -> (match expand_constant consts i with | ConstStringUTF8 s -> ConstString (make_jstr s) | _ -> raise (Class_structure_error ("Illegal constant refered in place of a String constant"))) | ConstantInt i -> ConstInt i | ConstantFloat f -> ConstFloat f | ConstantLong l -> ConstLong l | ConstantDouble f -> ConstDouble f | ConstantNameAndType (n,t) -> (match expand_constant consts n , expand_constant consts t with | ConstStringUTF8 n , ConstStringUTF8 t -> ConstNameAndType (n,parse_descriptor t) | ConstStringUTF8 _ , _ -> raise (Class_structure_error ("Illegal type in a NameAndType constant")) | _ -> raise (Class_structure_error ("Illegal constant refered in place of a NameAndType constant"))) | ConstantStringUTF8 s -> ConstStringUTF8 s | ConstantModule i -> (match expand_constant consts i with | ConstStringUTF8 s -> ConstModule s | _ -> raise (Class_structure_error ("Illegal constant refered in place of a module name"))) | ConstantPackage i -> (match expand_constant consts i with | ConstStringUTF8 s -> ConstPackage s | _ -> raise (Class_structure_error ("Illegal constant refered in place of a package name"))) | ConstantUnusable -> ConstUnusable let parse_class_low_level ch = let magic = read_real_i32 ch in if magic <> 0xCAFEBABEl then raise (Class_structure_error "Invalid magic number"); let version_minor = read_ui16 ch in let version_major = read_ui16 ch in let constant_count = read_ui16 ch in let const_big = ref true in let consts = Array.init constant_count (fun _ -> if !const_big then begin const_big := false; ConstantUnusable end else let c = parse_constant constant_count ch in (match c with ConstantLong _ | ConstantDouble _ -> const_big := true | _ -> ()); c ) in let consts = Array.mapi (fun i _ -> expand_constant consts i) consts in let flags = parse_access_flags class_flags ch in let this = get_class_ui16 consts ch in let super_idx = read_ui16 ch in let super = if super_idx = 0 then None else Some (get_class consts super_idx) in let interface_count = read_ui16 ch in let interfaces = List.init interface_count (fun _ -> get_class_ui16 consts ch) in let field_count = read_ui16 ch in let fields = List.init field_count (fun _ -> parse_field consts ch) in let method_count = read_ui16 ch in let methods = List.init method_count (fun _ -> parse_method consts ch) in let attrib_count = read_ui16 ch in let attribs = List.init attrib_count (fun _ -> let to_parse = [`SourceFile; `InnerClasses ; `EnclosingMethod ; `SourceDebugExtension ; `BootstrapMethods; `Synthetic ; `Deprecated; `Signature; `RuntimeVisibleAnnotations; `RuntimeInvisibleAnnotations; ] in parse_attribute to_parse consts ch) in let (bootstrap_table, attribs) = List.partition (function AttributeBootstrapMethods _ -> true | _ -> false) attribs in let bootstrap_table = (match bootstrap_table with | [] -> [] | (AttributeBootstrapMethods l) :: [] -> l | _ -> raise (Class_structure_error "A class may contain at most one bootstrap table"); ) in {j_consts = consts; j_flags = flags; j_name = this; j_super = super; j_interfaces = interfaces; j_fields = fields; j_methods = methods; j_attributes = attribs; j_bootstrap_table = Array.of_list bootstrap_table; j_version = {major=version_major; minor=version_minor}; } if the parsing raises a class_structure_error exception , we close the input ourself let parse_class_low_level ch = try parse_class_low_level ch with Class_structure_error _ as e -> JLib.IO.close_in ch; raise e let parse_class ch = JLow2High.low2high_class (parse_class_low_level ch)
37de478f99ac38c5519dd132a80401b1ebdcf8adc64b8ad9273a896e952c9df9
mcandre/ocaml-getopt
sample.ml
Demonstration of the module open Getopt let archive = ref false and update = ref false and verbose = ref 0 and includ = ref [] and output = ref "" let bip () = Printf.printf "\007"; flush stdout let wait () = Unix.sleep 1 let specs = [ ( 'x', "execute", None, Some (fun x -> Printf.printf "execute %s\n" x)); ( 'I', "include", None, (append includ)); ( 'o', "output", None, (atmost_once output (Error "only one output"))); ( 'a', "archive", (set archive true), None); ( 'u', "update", (set update true), None); ( 'v', "verbose", (incr verbose), None); ( 'X', "", Some bip, None); ( 'w', "wait", Some wait, None) ] let _ = parse_cmdline specs print_endline; Printf.printf "archive = %b\n" !archive; Printf.printf "update = %b\n" !update; Printf.printf "verbose = %i\n" !verbose; Printf.printf "output = %s\n" !output; List.iter (fun x -> Printf.printf "include %s\n" x) !includ;;
null
https://raw.githubusercontent.com/mcandre/ocaml-getopt/9d36081db01008c15a4a0044b4c1cbdf8d3f3492/sample.ml
ocaml
Demonstration of the module open Getopt let archive = ref false and update = ref false and verbose = ref 0 and includ = ref [] and output = ref "" let bip () = Printf.printf "\007"; flush stdout let wait () = Unix.sleep 1 let specs = [ ( 'x', "execute", None, Some (fun x -> Printf.printf "execute %s\n" x)); ( 'I', "include", None, (append includ)); ( 'o', "output", None, (atmost_once output (Error "only one output"))); ( 'a', "archive", (set archive true), None); ( 'u', "update", (set update true), None); ( 'v', "verbose", (incr verbose), None); ( 'X', "", Some bip, None); ( 'w', "wait", Some wait, None) ] let _ = parse_cmdline specs print_endline; Printf.printf "archive = %b\n" !archive; Printf.printf "update = %b\n" !update; Printf.printf "verbose = %i\n" !verbose; Printf.printf "output = %s\n" !output; List.iter (fun x -> Printf.printf "include %s\n" x) !includ;;
5c1f5c69297b954d416a550628e3f59691d93e291d426f9416ffb896a0b4709d
gsakkas/rite
20060405-20:41:02-03a9838eef87a5baf5d05bd769e72274.seminal.ml
* * * * * Note : Problem 1 does not use ; see the assignment * * * * exception Unimplemented exception RuntimeTypeError exception BadSourceProgram exception BadPrecomputation # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # let empty_set = [] let add str lst = if List.mem str lst then lst else str::lst let remove str lst = List.filter (fun x -> x <> str) lst let rec union lst1 lst2 = match lst1 with [] -> lst2 | hd::tl -> add hd (union tl lst2) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # type exp = Var of string last part for problem3 | Apply of exp * exp | Closure of string * exp * env | Int of int | Plus of exp * exp | If of exp * exp * exp | Pair of exp * exp | First of exp | Second of exp and env = (string * exp) list * * * * * * Problem 2 : complete this function * * * * * * * * # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ################################################ *) let rec interp f env e = let etoint e = match e with | Int i -> i | _ -> raise RuntimeTypeError in let interp = interp f in match e with # # # # # # # # # # # # # | Lam(s,e2,opt) -> Closure(s,e2,f env opt) (*store env!*) # # # # # # # # # # # # # # # # # # # | Apply(e1,e2) -> let v1 = interp env e1 in let v2 = interp env e2 in (match v1 with | Closure(s,e3,env2) -> interp((s,v2)::env2) e3 | _ -> raise RuntimeTypeError) | Int i -> Int i | Plus (e1,e2) -> let i1 = etoint(interp env e1) in let i2 = etoint(interp env e2) in Int (i1 + i2) | If (e1,e2,e3) -> let i = etoint(interp env e1) in (match i with | 0 -> interp env e3 | _ -> interp env e2) | Pair (e1, e2) -> Pair((interp env e1),(interp env e2)) | First (Pair (e1,e2)) -> e1 | First _ -> raise RuntimeTypeError | Second (Pair (e1,e2)) -> e2 | Second _ -> raise RuntimeTypeError let interp1 = interp (fun x _ -> x) * * * * * Problem 3 : complete this function * * * * * * let printenv e = print_endline ( match e with | Var s -> ("Var "^s) | Lam(s,e,lst) -> ("Lam "^s^ match lst with | None -> "Empty" | Some l -> string_of_int(List.length l) ) | Apply(e1,e2) -> "Apply" | Closure(s,e1,e2) -> "Closure" | Int i -> "Int "^(string_of_int i) | Plus(e1,e2) -> "Plus" | If(e1,e2,e3) -> "If" | Pair(e1,e2) -> "Pair" | First(e) -> "First" | Second(e) -> "Second" ) let rec computeFreeVars e = let _ = printenv e in match e with | Var s -> ((Var s), ([s])) | Lam(s,e,lst) -> let (en,l) = computeFreeVars e in (Lam(s,en,Some l),l) | Apply(e1,e2) -> let (en1,l1) = computeFreeVars e1 in let (en2,l2) = computeFreeVars e2 in ((Apply(en1,en2)),(union l1 l2)) | Closure(s,e1,e2) -> raise BadSourceProgram | Int i -> ((Int i),[]) | Plus(e1,e2) -> let (en1,l1) = computeFreeVars e1 in let (en2,l2) = computeFreeVars e2 in ((Plus(en1,en2)),(union l1 l2)) | If(e1,e2,e3) -> let (en1,l1) = computeFreeVars e1 in let (en2,l2) = computeFreeVars e2 in let (en3,l3) = computeFreeVars e3 in ((If(en1,en2,en3)),(union l1 (union l2 l3))) | Pair(e1,e2) -> let (en1,l1) = computeFreeVars e1 in let (en2,l2) = computeFreeVars e2 in ((Pair(en1,en2)),(union l1 l2)) | First e -> computeFreeVars e | Second e -> computeFreeVars e let interp2 = interp (fun (env:env) opt -> match opt with | None -> raise BadPrecomputation | Some lst -> List.map (fun s -> (s, List.assoc s env)) lst) let testinterp = interp (fun (env:env) opt -> match opt with | None -> raise BadPrecomputation | Some lst -> ( ( List.iter print_endline lst; print_endline "end of list" ); ( let printen x = let (s1, e1) = x in let _ = print_endline s1 in printenv e1 in List.iter printen env; print_endline (List.length env) ); (List.map (fun s -> ( ( print_endline s );(s, List.assoc s env)) ) lst) ) ) * * * * * * Problem 4 : not programming ( see assignment ) * * * * * * * * * * * * * Problem 5a : explain this function * * * * * * * * (* ############################################ *) * * * * * Problem 5b ( EXTRA CREDIT ): explain the next two functions * * * * * (* ################################## ##################### ################################ ###################################################################### ### ################################ ################# ############################################ ################################################################### ####################################################################### ###################################### ################### #################################### #################################### ###################################################### ############################################## ########################################################################### ####################### ############### ################################################################## ################################################################## ########################################### ############################################# ########################################### ########################################### ########################################### *) (********** examples and testing ***********) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ############################# ########################################################### ############################################ *) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # let ex1 = ( Apply( Apply( Lam("x", Lam("y",Plus(Var"x",Var"y"),None), None ), Int 17 ), Int 19 ) ) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ################################# *) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # let lam x e = Lam(x,e,None) let app e1 e2 = Apply(e1,e2) let vx = Var "x" let vy = Var "y" let vf = Var "f" # # # # # # # # # # # # # # # # # # # # # # # # # # # let fix = let e = lam "x" (app vf (lam "y" (app (app vx vx) vy))) in lam "f" (app e e) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # let sum = lam "f" (lam "x" (If(vx, Plus(vx, app vf (Plus(vx, Int (-1)))), Int 0))) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # let ex2 = (app (app fix sum) (Int 1000)) let printans ans = match ans with | Int i -> print_endline (string_of_int i) | _ -> print_endline "error" # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # let ans1 = interp1 [] ex1 let ans2 = interp1 [] ex2 let _ = printans ans1 let _ = printans ans2 let _ = testinterp [] (fst (computeFreeVars ex1)) (* ################################################# ################################################# *) (* ######################################## ######################################## *)
null
https://raw.githubusercontent.com/gsakkas/rite/958a0ad2460e15734447bc07bd181f5d35956d3b/features/data/seminal/20060405-20%3A41%3A02-03a9838eef87a5baf5d05bd769e72274.seminal.ml
ocaml
store env! ############################################ ################################## ##################### ################################ ###################################################################### ### ################################ ################# ############################################ ################################################################### ####################################################################### ###################################### ################### #################################### #################################### ###################################################### ############################################## ########################################################################### ####################### ############### ################################################################## ################################################################## ########################################### ############################################# ########################################### ########################################### ########################################### ********* examples and testing ********** ################################################# ################################################# ######################################## ########################################
* * * * * Note : Problem 1 does not use ; see the assignment * * * * exception Unimplemented exception RuntimeTypeError exception BadSourceProgram exception BadPrecomputation # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # let empty_set = [] let add str lst = if List.mem str lst then lst else str::lst let remove str lst = List.filter (fun x -> x <> str) lst let rec union lst1 lst2 = match lst1 with [] -> lst2 | hd::tl -> add hd (union tl lst2) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # type exp = Var of string last part for problem3 | Apply of exp * exp | Closure of string * exp * env | Int of int | Plus of exp * exp | If of exp * exp * exp | Pair of exp * exp | First of exp | Second of exp and env = (string * exp) list * * * * * * Problem 2 : complete this function * * * * * * * * # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ################################################ *) let rec interp f env e = let etoint e = match e with | Int i -> i | _ -> raise RuntimeTypeError in let interp = interp f in match e with # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # | Apply(e1,e2) -> let v1 = interp env e1 in let v2 = interp env e2 in (match v1 with | Closure(s,e3,env2) -> interp((s,v2)::env2) e3 | _ -> raise RuntimeTypeError) | Int i -> Int i | Plus (e1,e2) -> let i1 = etoint(interp env e1) in let i2 = etoint(interp env e2) in Int (i1 + i2) | If (e1,e2,e3) -> let i = etoint(interp env e1) in (match i with | 0 -> interp env e3 | _ -> interp env e2) | Pair (e1, e2) -> Pair((interp env e1),(interp env e2)) | First (Pair (e1,e2)) -> e1 | First _ -> raise RuntimeTypeError | Second (Pair (e1,e2)) -> e2 | Second _ -> raise RuntimeTypeError let interp1 = interp (fun x _ -> x) * * * * * Problem 3 : complete this function * * * * * * let printenv e = print_endline ( match e with | Var s -> ("Var "^s) | Lam(s,e,lst) -> ("Lam "^s^ match lst with | None -> "Empty" | Some l -> string_of_int(List.length l) ) | Apply(e1,e2) -> "Apply" | Closure(s,e1,e2) -> "Closure" | Int i -> "Int "^(string_of_int i) | Plus(e1,e2) -> "Plus" | If(e1,e2,e3) -> "If" | Pair(e1,e2) -> "Pair" | First(e) -> "First" | Second(e) -> "Second" ) let rec computeFreeVars e = let _ = printenv e in match e with | Var s -> ((Var s), ([s])) | Lam(s,e,lst) -> let (en,l) = computeFreeVars e in (Lam(s,en,Some l),l) | Apply(e1,e2) -> let (en1,l1) = computeFreeVars e1 in let (en2,l2) = computeFreeVars e2 in ((Apply(en1,en2)),(union l1 l2)) | Closure(s,e1,e2) -> raise BadSourceProgram | Int i -> ((Int i),[]) | Plus(e1,e2) -> let (en1,l1) = computeFreeVars e1 in let (en2,l2) = computeFreeVars e2 in ((Plus(en1,en2)),(union l1 l2)) | If(e1,e2,e3) -> let (en1,l1) = computeFreeVars e1 in let (en2,l2) = computeFreeVars e2 in let (en3,l3) = computeFreeVars e3 in ((If(en1,en2,en3)),(union l1 (union l2 l3))) | Pair(e1,e2) -> let (en1,l1) = computeFreeVars e1 in let (en2,l2) = computeFreeVars e2 in ((Pair(en1,en2)),(union l1 l2)) | First e -> computeFreeVars e | Second e -> computeFreeVars e let interp2 = interp (fun (env:env) opt -> match opt with | None -> raise BadPrecomputation | Some lst -> List.map (fun s -> (s, List.assoc s env)) lst) let testinterp = interp (fun (env:env) opt -> match opt with | None -> raise BadPrecomputation | Some lst -> ( ( List.iter print_endline lst; print_endline "end of list" ); ( let printen x = let (s1, e1) = x in let _ = print_endline s1 in printenv e1 in List.iter printen env; print_endline (List.length env) ); (List.map (fun s -> ( ( print_endline s );(s, List.assoc s env)) ) lst) ) ) * * * * * * Problem 4 : not programming ( see assignment ) * * * * * * * * * * * * * Problem 5a : explain this function * * * * * * * * * * * * * Problem 5b ( EXTRA CREDIT ): explain the next two functions * * * * * # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ############################# ########################################################### ############################################ *) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # let ex1 = ( Apply( Apply( Lam("x", Lam("y",Plus(Var"x",Var"y"),None), None ), Int 17 ), Int 19 ) ) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ################################# *) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # let lam x e = Lam(x,e,None) let app e1 e2 = Apply(e1,e2) let vx = Var "x" let vy = Var "y" let vf = Var "f" # # # # # # # # # # # # # # # # # # # # # # # # # # # let fix = let e = lam "x" (app vf (lam "y" (app (app vx vx) vy))) in lam "f" (app e e) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # let sum = lam "f" (lam "x" (If(vx, Plus(vx, app vf (Plus(vx, Int (-1)))), Int 0))) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # let ex2 = (app (app fix sum) (Int 1000)) let printans ans = match ans with | Int i -> print_endline (string_of_int i) | _ -> print_endline "error" # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # let ans1 = interp1 [] ex1 let ans2 = interp1 [] ex2 let _ = printans ans1 let _ = printans ans2 let _ = testinterp [] (fst (computeFreeVars ex1))
583adba27592045eaa203399199d2ae585ea727675cae9a64e0895284944ff23
kztk-m/sparcl
Spec.hs
# LANGUAGE NoMonomorphismRestriction # {-# LANGUAGE QuasiQuotes #-} # LANGUAGE StandaloneDeriving # # LANGUAGE TemplateHaskell # # OPTIONS_GHC -fno - defer - out - of - scope - variables -fno - defer - type - errors # import Language.Sparcl.Base import Language.Sparcl.Runtime import Language.Sparcl.TH -- [sparcl| def f = 1 |] -- [sparclf|./examples/t1.sparcl|] -- [sparclf|./examples/s2l.sparcl|] [sparclf|./Examples/Pi.sparcl|] deriving instance Show a => Show(List a) deriving instance Show(Tree) main :: IO () main = print ()
null
https://raw.githubusercontent.com/kztk-m/sparcl/f52d333ce50e0aa6cb307da08811719f8c684f7d/test/Spec.hs
haskell
# LANGUAGE QuasiQuotes # [sparcl| def f = 1 |] [sparclf|./examples/t1.sparcl|] [sparclf|./examples/s2l.sparcl|]
# LANGUAGE NoMonomorphismRestriction # # LANGUAGE StandaloneDeriving # # LANGUAGE TemplateHaskell # # OPTIONS_GHC -fno - defer - out - of - scope - variables -fno - defer - type - errors # import Language.Sparcl.Base import Language.Sparcl.Runtime import Language.Sparcl.TH [sparclf|./Examples/Pi.sparcl|] deriving instance Show a => Show(List a) deriving instance Show(Tree) main :: IO () main = print ()
e2dea3d827fce17b2f6e450d9325ff8626e84840fc8e34efc46cb1ece1675fac
McMasterU/HashedExpression
Utils.hs
module HashedExpression.Utils where import Data.Array import Data.Complex (Complex (..)) import qualified Data.Complex as Complex import Data.Function ((&)) import qualified Data.IntMap.Strict as IM import Data.List (foldl') import Data.List.Split (splitOn) import Data.Map (Map, fromList) import qualified Data.Map as Map import Data.Maybe import qualified Data.Set as Set import qualified Data.Text as T import Data.Time (diffUTCTime, getCurrentTime) import GHC.IO.Unsafe (unsafePerformIO) import GHC.Stack (HasCallStack) import HashedExpression.Internal.Base import HashedExpression.Internal.Node import Prelude hiding ((^)) import qualified Prelude -- | Forward pipe operator (|>) :: a -> (a -> b) -> b (|>) = (&) infixl 1 |> -- | measureTime :: IO a -> IO () measureTime action = do beforeTime <- getCurrentTime action afterTime <- getCurrentTime putStrLn $ "Took " ++ show (diffUTCTime afterTime beforeTime) ++ " seconds" -- | Check if all elements of the list is equal allEqual :: (Eq a) => [a] -> Bool allEqual [] = True allEqual [x] = True allEqual (x : y : xs) = x == y && allEqual (y : xs) fromR :: Double -> Complex Double fromR x = x :+ 0 -- | pullConstant :: ExpressionMap -> NodeID -> Maybe (Shape, Double) pullConstant mp n | (shape, R, Const c) <- retrieveNode n mp = Just (shape, c) | otherwise = Nothing -- | pullConstants :: ExpressionMap -> [NodeID] -> Maybe (Shape, [Double]) pullConstants mp ns | xs@(x : _) <- mapMaybe (pullConstant mp) ns = Just (fst x, map snd xs) | otherwise = Nothing -- | isZero :: ExpressionMap -> NodeID -> Bool isZero mp nId | Const 0 <- retrieveOp nId mp = True | RealImag arg1 arg2 <- retrieveOp nId mp, Const 0 <- retrieveOp arg1 mp, Const 0 <- retrieveOp arg2 mp = True | otherwise = False -- | isOne :: ExpressionMap -> NodeID -> Bool isOne mp nId | Const 1 <- retrieveOp nId mp = True | RealImag arg1 arg2 <- retrieveOp nId mp, Const 1 <- retrieveOp arg1 mp, Const 0 <- retrieveOp arg2 mp = True | otherwise = False -- | isConstant :: ExpressionMap -> NodeID -> Bool isConstant mp nId | Const _ <- retrieveOp nId mp = True | otherwise = False -- | pullSumOperands :: ExpressionMap -> NodeID -> [NodeID] pullSumOperands mp nId | Sum operands <- retrieveOp nId mp = operands | otherwise = [nId] -- | pullProdOperands :: ExpressionMap -> NodeID -> [NodeID] pullProdOperands mp nId | Mul operands <- retrieveOp nId mp = operands | otherwise = [nId] toRange :: DimSelector -> Int -> (Int, Int, Int) toRange (At i) size = (i, i, 1) toRange (Range start end step) size = (start, if end >= start then end else end + size, step) mkIndices :: DimSelector -> Int -> [Int] mkIndices (At i) size = [i] mkIndices (Range start end step) size = map (`mod` size) [start, start + step .. if end >= start then end else end + size] breakSub :: Int -> [a] -> [([a], [a], [a])] breakSub len [] = [] breakSub len xs | len > length xs = [] breakSub len xs@(y : ys) = ([], take len xs, drop len xs) : map (\(prefix, sub, suffix) -> (y : prefix, sub, suffix)) (breakSub len ys) coercible :: Shape -> Shape -> Bool coercible sml target = any ( \(prefix, sub, suffix) -> sub == sml && all (== 1) prefix && all (== 1) suffix ) $ breakSub (length sml) target ------------------------------------------------------------------------------- zipMp :: forall a b c. Ord a => Map a b -> Map a c -> Map a (b, c) zipMp mp1 mp2 = foldl' f Map.empty $ Map.keys mp1 where f acc k = case (Map.lookup k mp1, Map.lookup k mp2) of (Just v1, Just v2) -> Map.insert k (v1, v2) acc _ -> acc ------------------------------------------------------------------------------- zipMp3 :: forall a b c d. Ord a => Map a b -> Map a c -> Map a d -> Map a (b, c, d) zipMp3 mp1 mp2 mp3 = foldl' f Map.empty $ Map.keys mp1 where f acc k = case (Map.lookup k mp1, Map.lookup k mp2, Map.lookup k mp3) of (Just v1, Just v2, Just v3) -> Map.insert k (v1, v2, v3) acc _ -> acc instance PowerOp Double Int where (^) x y = x Prelude.^ y instance ComplexRealOp Double (Complex Double) where (+:) = (:+) xRe = Complex.realPart xIm = Complex.imagPart conjugate = Complex.conjugate ------------------------------------------------------------------------------- class ToText a where tt :: a -> T.Text ttq :: a -> T.Text ttq s = "\"" <> tt s <> "\"" instance ToText Double where tt s = T.pack $ show s instance ToText Int where tt s = T.pack $ show s instance ToText String where tt = T.pack instance ToText T.Text where tt = id
null
https://raw.githubusercontent.com/McMasterU/HashedExpression/cfe9f21165f1f3fc6d59ec27fb962c29e67a9bbb/src/HashedExpression/Utils.hs
haskell
| Forward pipe operator | | Check if all elements of the list is equal | | | | | | | ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- -----------------------------------------------------------------------------
module HashedExpression.Utils where import Data.Array import Data.Complex (Complex (..)) import qualified Data.Complex as Complex import Data.Function ((&)) import qualified Data.IntMap.Strict as IM import Data.List (foldl') import Data.List.Split (splitOn) import Data.Map (Map, fromList) import qualified Data.Map as Map import Data.Maybe import qualified Data.Set as Set import qualified Data.Text as T import Data.Time (diffUTCTime, getCurrentTime) import GHC.IO.Unsafe (unsafePerformIO) import GHC.Stack (HasCallStack) import HashedExpression.Internal.Base import HashedExpression.Internal.Node import Prelude hiding ((^)) import qualified Prelude (|>) :: a -> (a -> b) -> b (|>) = (&) infixl 1 |> measureTime :: IO a -> IO () measureTime action = do beforeTime <- getCurrentTime action afterTime <- getCurrentTime putStrLn $ "Took " ++ show (diffUTCTime afterTime beforeTime) ++ " seconds" allEqual :: (Eq a) => [a] -> Bool allEqual [] = True allEqual [x] = True allEqual (x : y : xs) = x == y && allEqual (y : xs) fromR :: Double -> Complex Double fromR x = x :+ 0 pullConstant :: ExpressionMap -> NodeID -> Maybe (Shape, Double) pullConstant mp n | (shape, R, Const c) <- retrieveNode n mp = Just (shape, c) | otherwise = Nothing pullConstants :: ExpressionMap -> [NodeID] -> Maybe (Shape, [Double]) pullConstants mp ns | xs@(x : _) <- mapMaybe (pullConstant mp) ns = Just (fst x, map snd xs) | otherwise = Nothing isZero :: ExpressionMap -> NodeID -> Bool isZero mp nId | Const 0 <- retrieveOp nId mp = True | RealImag arg1 arg2 <- retrieveOp nId mp, Const 0 <- retrieveOp arg1 mp, Const 0 <- retrieveOp arg2 mp = True | otherwise = False isOne :: ExpressionMap -> NodeID -> Bool isOne mp nId | Const 1 <- retrieveOp nId mp = True | RealImag arg1 arg2 <- retrieveOp nId mp, Const 1 <- retrieveOp arg1 mp, Const 0 <- retrieveOp arg2 mp = True | otherwise = False isConstant :: ExpressionMap -> NodeID -> Bool isConstant mp nId | Const _ <- retrieveOp nId mp = True | otherwise = False pullSumOperands :: ExpressionMap -> NodeID -> [NodeID] pullSumOperands mp nId | Sum operands <- retrieveOp nId mp = operands | otherwise = [nId] pullProdOperands :: ExpressionMap -> NodeID -> [NodeID] pullProdOperands mp nId | Mul operands <- retrieveOp nId mp = operands | otherwise = [nId] toRange :: DimSelector -> Int -> (Int, Int, Int) toRange (At i) size = (i, i, 1) toRange (Range start end step) size = (start, if end >= start then end else end + size, step) mkIndices :: DimSelector -> Int -> [Int] mkIndices (At i) size = [i] mkIndices (Range start end step) size = map (`mod` size) [start, start + step .. if end >= start then end else end + size] breakSub :: Int -> [a] -> [([a], [a], [a])] breakSub len [] = [] breakSub len xs | len > length xs = [] breakSub len xs@(y : ys) = ([], take len xs, drop len xs) : map (\(prefix, sub, suffix) -> (y : prefix, sub, suffix)) (breakSub len ys) coercible :: Shape -> Shape -> Bool coercible sml target = any ( \(prefix, sub, suffix) -> sub == sml && all (== 1) prefix && all (== 1) suffix ) $ breakSub (length sml) target zipMp :: forall a b c. Ord a => Map a b -> Map a c -> Map a (b, c) zipMp mp1 mp2 = foldl' f Map.empty $ Map.keys mp1 where f acc k = case (Map.lookup k mp1, Map.lookup k mp2) of (Just v1, Just v2) -> Map.insert k (v1, v2) acc _ -> acc zipMp3 :: forall a b c d. Ord a => Map a b -> Map a c -> Map a d -> Map a (b, c, d) zipMp3 mp1 mp2 mp3 = foldl' f Map.empty $ Map.keys mp1 where f acc k = case (Map.lookup k mp1, Map.lookup k mp2, Map.lookup k mp3) of (Just v1, Just v2, Just v3) -> Map.insert k (v1, v2, v3) acc _ -> acc instance PowerOp Double Int where (^) x y = x Prelude.^ y instance ComplexRealOp Double (Complex Double) where (+:) = (:+) xRe = Complex.realPart xIm = Complex.imagPart conjugate = Complex.conjugate class ToText a where tt :: a -> T.Text ttq :: a -> T.Text ttq s = "\"" <> tt s <> "\"" instance ToText Double where tt s = T.pack $ show s instance ToText Int where tt s = T.pack $ show s instance ToText String where tt = T.pack instance ToText T.Text where tt = id
7f257a870c8e383c6f233e9dd98801c36f35a21908433368d5d3d645fb3d98b0
duncanatt/detecter
ranch_acceptors_sup.erl
Copyright ( c ) 2011 - 2018 , < > %% %% 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(ranch_acceptors_sup). -behaviour(supervisor). -include("log.hrl"). -export([start_link/2]). -export([init/1]). -spec start_link(ranch:ref(), module()) -> {ok, pid()}. start_link(Ref, Transport) -> supervisor:start_link(?MODULE, [Ref, Transport]). init([Ref, Transport]) -> register(?MODULE, self()), ?TRACE("Started acceptors supervisor on ~w transport.", [Transport]), ConnsSup = ranch_server:get_connections_sup(Ref), TransOpts = ranch_server:get_transport_options(Ref), NumAcceptors = maps:get(num_acceptors, TransOpts, 10), Logger = maps:get(logger, TransOpts, error_logger), LSocket = case maps:get(socket, TransOpts, undefined) of undefined -> SocketOpts = maps:get(socket_opts, TransOpts, []), %% We temporarily put the logger in the process dictionary %% so that it can be used from ranch:filter_options. The %% interface as it currently is does not allow passing it %% down otherwise. put(logger, Logger), case Transport:listen(SocketOpts) of {ok, Socket} -> erase(logger), Socket; {error, Reason} -> listen_error(Ref, Transport, SocketOpts, Reason, Logger) end; Socket -> Socket end, {ok, Addr} = Transport:sockname(LSocket), ranch_server:set_addr(Ref, Addr), Procs = [ {{acceptor, self(), N}, {ranch_acceptor, start_link, [ LSocket, Transport, Logger, ConnsSup, N ]}, permanent, brutal_kill, worker, []} || N <- lists:seq(1, NumAcceptors)], {ok, {{one_for_one, 1, 5}, Procs}}. -spec listen_error(any(), module(), any(), atom(), module()) -> no_return(). listen_error(Ref, Transport, SocketOpts0, Reason, Logger) -> SocketOpts1 = [{cert, '...'}|proplists:delete(cert, SocketOpts0)], SocketOpts2 = [{key, '...'}|proplists:delete(key, SocketOpts1)], SocketOpts = [{cacerts, '...'}|proplists:delete(cacerts, SocketOpts2)], ranch:log(error, "Failed to start Ranch listener ~p in ~p:listen(~999999p) for reason ~p (~s)~n", [Ref, Transport, SocketOpts, Reason, format_error(Reason)], Logger), exit({listen_error, Ref, Reason}). format_error(no_cert) -> "no certificate provided; see cert, certfile, sni_fun or sni_hosts options"; format_error(Reason) -> inet:format_error(Reason).
null
https://raw.githubusercontent.com/duncanatt/detecter/95b6a758ce6c60f3b7377c07607f24d126cbdacf/experiments/coordination_2022/src/ranch/ranch_acceptors_sup.erl
erlang
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. WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. We temporarily put the logger in the process dictionary so that it can be used from ranch:filter_options. The interface as it currently is does not allow passing it down otherwise.
Copyright ( c ) 2011 - 2018 , < > THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN -module(ranch_acceptors_sup). -behaviour(supervisor). -include("log.hrl"). -export([start_link/2]). -export([init/1]). -spec start_link(ranch:ref(), module()) -> {ok, pid()}. start_link(Ref, Transport) -> supervisor:start_link(?MODULE, [Ref, Transport]). init([Ref, Transport]) -> register(?MODULE, self()), ?TRACE("Started acceptors supervisor on ~w transport.", [Transport]), ConnsSup = ranch_server:get_connections_sup(Ref), TransOpts = ranch_server:get_transport_options(Ref), NumAcceptors = maps:get(num_acceptors, TransOpts, 10), Logger = maps:get(logger, TransOpts, error_logger), LSocket = case maps:get(socket, TransOpts, undefined) of undefined -> SocketOpts = maps:get(socket_opts, TransOpts, []), put(logger, Logger), case Transport:listen(SocketOpts) of {ok, Socket} -> erase(logger), Socket; {error, Reason} -> listen_error(Ref, Transport, SocketOpts, Reason, Logger) end; Socket -> Socket end, {ok, Addr} = Transport:sockname(LSocket), ranch_server:set_addr(Ref, Addr), Procs = [ {{acceptor, self(), N}, {ranch_acceptor, start_link, [ LSocket, Transport, Logger, ConnsSup, N ]}, permanent, brutal_kill, worker, []} || N <- lists:seq(1, NumAcceptors)], {ok, {{one_for_one, 1, 5}, Procs}}. -spec listen_error(any(), module(), any(), atom(), module()) -> no_return(). listen_error(Ref, Transport, SocketOpts0, Reason, Logger) -> SocketOpts1 = [{cert, '...'}|proplists:delete(cert, SocketOpts0)], SocketOpts2 = [{key, '...'}|proplists:delete(key, SocketOpts1)], SocketOpts = [{cacerts, '...'}|proplists:delete(cacerts, SocketOpts2)], ranch:log(error, "Failed to start Ranch listener ~p in ~p:listen(~999999p) for reason ~p (~s)~n", [Ref, Transport, SocketOpts, Reason, format_error(Reason)], Logger), exit({listen_error, Ref, Reason}). format_error(no_cert) -> "no certificate provided; see cert, certfile, sni_fun or sni_hosts options"; format_error(Reason) -> inet:format_error(Reason).
b1d1d46eb11d724deb36dcc5f780c7645a85d4ed6431eaa11efbb96294693662
haas/harmtrace
Sim.hs
# OPTIONS_GHC -Wall # module HarmTrace.Matching.Sim where import HarmTrace.HAnTree.HAn import HarmTrace.HAnTree.Tree import HarmTrace.Base.MusicRep import HarmTrace.Models.ChordTokens (ChordToken) -------------------------------------------------------------------------------- -- A class for representing numerical similarity between datatypes -------------------------------------------------------------------------------- class Sim a where sim :: a -> a -> Int instance Sim a => Sim (Tree a) where sim (Node l _ _) (Node l' _ _) = sim l l' instance Sim a => Sim [a] where sim [ha] [hb] = sim ha hb sim (ha:ta) (hb:tb) = sim ha hb + sim ta tb sim _ _ = 0 instance Sim HAn where sim (HAn _ a) (HAn _ b) = if a == b then 1 else 0 sim (HAnFunc a) (HAnFunc b) = sim a b sim (HAnPrep a) (HAnPrep b) = sim a b sim (HAnTrans a) (HAnTrans b) = sim a b sim (HAnChord a) (HAnChord b) = sim a b sim _ _ = 0 instance Sim Int where # INLINE sim # sim i j = if i == j then 1 else 0 instance Sim HFunc where # INLINE sim # 1 + sim m m2 1 + sim m m2 1 + sim m m2 sim P P = 1 sim PD PD = 1 sim PT PT = 1 sim _ _ = 0 instance Sim Mode where # INLINE sim # sim MajMode MajMode = 1 sim MinMode MinMode = 1 sim _ _ = 0 instance Sim Trans where # INLINE sim # sim (Trit _v sd) (Trit _v2 sd2) = if sd == sd2 then 1 else 0 sim (DimTrit _v sd) (DimTrit _v2 sd2) = if sd == sd2 then 1 else 0 sim (DimTrans _v sd) (DimTrans _v2 sd2) = if sd == sd2 then 1 else 0 sim _ _ =0 instance Sim Prep where # INLINE sim # sim (DiatDom _v sd) (DiatDom _v2 sd2) = if sd == sd2 then 3 else 2 sim (SecDom _v sd) (SecDom _v2 sd2) = if sd == sd2 then 3 else 2 sim (SecMin _v sd) (SecMin _v2 sd2) = if sd == sd2 then 3 else 2 sim (SecMin _v sd) (DiatDom _v2 sd2) = if sd == sd2 then 2 else 1 sim (DiatDom _v sd) (SecMin _v2 sd2) = if sd == sd2 then 2 else 1 sim (SecMin _v sd) (SecDom _v2 sd2) = if sd == sd2 then 2 else 1 sim (SecDom _v sd) (SecMin _v2 sd2) = if sd == sd2 then 2 else 1 sim (DiatDom _v sd) (SecDom _v2 sd2) = if sd == sd2 then 2 else 1 sim (SecDom _v sd) (DiatDom _v2 sd2) = if sd == sd2 then 2 else 1 sim NoTrans = sim _ _ = 0 instance Sim ChordToken where sim c1 c2 = if c1 == c2 then 2 else 0 -------------------------------------------------------------------------------- -- Some utility functions -------------------------------------------------------------------------------- -- calculates the self similarity value (used for normalisation) i.e. the -- maximum similarity score maxSim :: Sim a => [a] -> Int maxSim = foldr (\a b -> sim a a + b) 0 div1 :: Int -> Int -> Int div1 n c = if n == 1 then 1 else n `div` c
null
https://raw.githubusercontent.com/haas/harmtrace/e250855a3bb6e5b28fe538c728f707cf82ca9fd3/src/HarmTrace/Matching/Sim.hs
haskell
------------------------------------------------------------------------------ A class for representing numerical similarity between datatypes ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ Some utility functions ------------------------------------------------------------------------------ calculates the self similarity value (used for normalisation) i.e. the maximum similarity score
# OPTIONS_GHC -Wall # module HarmTrace.Matching.Sim where import HarmTrace.HAnTree.HAn import HarmTrace.HAnTree.Tree import HarmTrace.Base.MusicRep import HarmTrace.Models.ChordTokens (ChordToken) class Sim a where sim :: a -> a -> Int instance Sim a => Sim (Tree a) where sim (Node l _ _) (Node l' _ _) = sim l l' instance Sim a => Sim [a] where sim [ha] [hb] = sim ha hb sim (ha:ta) (hb:tb) = sim ha hb + sim ta tb sim _ _ = 0 instance Sim HAn where sim (HAn _ a) (HAn _ b) = if a == b then 1 else 0 sim (HAnFunc a) (HAnFunc b) = sim a b sim (HAnPrep a) (HAnPrep b) = sim a b sim (HAnTrans a) (HAnTrans b) = sim a b sim (HAnChord a) (HAnChord b) = sim a b sim _ _ = 0 instance Sim Int where # INLINE sim # sim i j = if i == j then 1 else 0 instance Sim HFunc where # INLINE sim # 1 + sim m m2 1 + sim m m2 1 + sim m m2 sim P P = 1 sim PD PD = 1 sim PT PT = 1 sim _ _ = 0 instance Sim Mode where # INLINE sim # sim MajMode MajMode = 1 sim MinMode MinMode = 1 sim _ _ = 0 instance Sim Trans where # INLINE sim # sim (Trit _v sd) (Trit _v2 sd2) = if sd == sd2 then 1 else 0 sim (DimTrit _v sd) (DimTrit _v2 sd2) = if sd == sd2 then 1 else 0 sim (DimTrans _v sd) (DimTrans _v2 sd2) = if sd == sd2 then 1 else 0 sim _ _ =0 instance Sim Prep where # INLINE sim # sim (DiatDom _v sd) (DiatDom _v2 sd2) = if sd == sd2 then 3 else 2 sim (SecDom _v sd) (SecDom _v2 sd2) = if sd == sd2 then 3 else 2 sim (SecMin _v sd) (SecMin _v2 sd2) = if sd == sd2 then 3 else 2 sim (SecMin _v sd) (DiatDom _v2 sd2) = if sd == sd2 then 2 else 1 sim (DiatDom _v sd) (SecMin _v2 sd2) = if sd == sd2 then 2 else 1 sim (SecMin _v sd) (SecDom _v2 sd2) = if sd == sd2 then 2 else 1 sim (SecDom _v sd) (SecMin _v2 sd2) = if sd == sd2 then 2 else 1 sim (DiatDom _v sd) (SecDom _v2 sd2) = if sd == sd2 then 2 else 1 sim (SecDom _v sd) (DiatDom _v2 sd2) = if sd == sd2 then 2 else 1 sim NoTrans = sim _ _ = 0 instance Sim ChordToken where sim c1 c2 = if c1 == c2 then 2 else 0 maxSim :: Sim a => [a] -> Int maxSim = foldr (\a b -> sim a a + b) 0 div1 :: Int -> Int -> Int div1 n c = if n == 1 then 1 else n `div` c
f413d543a9f581ff40031c846c275a6d33f5cf8e2a8890556e985fc804dd0397
ocaml-community/lambda-term
lTerm_history.mli
* lTerm_history.mli * ----------------- * Copyright : ( c ) 2012 , < > * Licence : BSD3 * * This file is a part of Lambda - Term . * lTerm_history.mli * ----------------- * Copyright : (c) 2012, Jeremie Dimino <> * Licence : BSD3 * * This file is a part of Lambda-Term. *) (** History management *) type t (** Type of a history. *) val create : ?max_size : int -> ?max_entries : int -> Zed_string.t list -> t * [ create ? max_size ? max_lines init ] creates a new history . [ max_size ] is the maximum size in bytes of the history . Oldest entries are dropped if this limit is reached . The default is [ max_int ] . [ max_entries ] is the maximum number of entries of the history . Oldest entries are dropped if this limit is reached . The default is no [ max_int ] . [ init ] is the initial contents of the history . All entries of [ init ] are considered " old " . Old entries are not saved by { ! save } when [ append ] is set to [ true ] . Note : the first element of [ init ] must be the most recent entry . [max_size] is the maximum size in bytes of the history. Oldest entries are dropped if this limit is reached. The default is [max_int]. [max_entries] is the maximum number of entries of the history. Oldest entries are dropped if this limit is reached. The default is no [max_int]. [init] is the initial contents of the history. All entries of [init] are considered "old". Old entries are not saved by {!save} when [append] is set to [true]. Note: the first element of [init] must be the most recent entry. *) val add : t -> ?skip_empty : bool -> ?skip_dup : bool -> Zed_string.t -> unit (** [add history ?skip_empty ?skip_dup entry] adds [entry] to the top of the history. If [skip_empty] is [true] (the default) and [entry] contains only spaces, it is not added. If [skip_dup] is [true] (the default) and [entry] is equal to the top of the history, it is not added. If [entry] is bigger than the maximum size of the history, the history is not modified. *) val contents : t -> Zed_string.t list * Returns all the entries of the history . The first element of the list is the most recent entry . list is the most recent entry. *) val size : t -> int (** Returns the size (in bytes) of the history. *) val length : t -> int (** Returns the number of entries in the history. *) val old_count : t -> int (** Returns the number of old entries in the history. *) val set_old_count : t -> int -> unit (** [set_old_count history count] sets the number of old entries in the history. *) val max_size : t -> int (** Returns the maximum size of the history. *) val set_max_size : t -> int -> unit (** Sets the maximum size of the history. It may drop oldest entries to honor the new limit. *) val max_entries : t -> int (** Returns the maximum number of entries of the history. *) val set_max_entries : t -> int -> unit (** Sets the maximum number of entries of the history. It may drop oldest entries to honor the new limit. *) val load : t -> ?log : (int -> string -> unit Lwt.t) -> ?skip_empty : bool -> ?skip_dup : bool -> string -> unit Lwt.t * [ load history ? log ? skip_empty ? skip_dup filename ] loads entries from [ filename ] to [ history ] . If [ filename ] does not exists [ history ] is not modified . [ log ] is the function used to log errors contained in the history file ( errors are because of non - UTF8 data ) . Arguments are a line number and an error message . The default is to use the default logger ( of [ Lwt_log ] ) . Entries containing errors are skipped . Note : all entries are marked as old , i.e. [ old_count history = length history ] . from [filename] to [history]. If [filename] does not exists [history] is not modified. [log] is the function used to log errors contained in the history file (errors are because of non-UTF8 data). Arguments are a line number and an error message. The default is to use the default logger (of [Lwt_log]). Entries containing errors are skipped. Note: all entries are marked as old, i.e. [old_count history = length history]. *) val save : t -> ?max_size : int -> ?max_entries : int -> ?skip_empty : bool -> ?skip_dup : bool -> ?append : bool -> ?perm : int -> string -> unit Lwt.t (** [save history ?max_size ?max_entries ?skip_empty ?sjip_dup ?perm filename] saves [history] to [filename]. If [append] is [false] then the file is truncated and new entries are saved. If it is [true] (the default) then new entries are added at the end. [perm] are the file permissions in case it is created. If [append] is [true] and there is no new entries, the file is not touched. In any other case, limits are honored and the resulting file will never contains more bytes than [max_size] or more entries than [max_entries]. If [max_size] and/or [max_entries] are not specified, the ones of [history] are used. After the history is successfully saved, all entries of [history] are marked as old, i.e. [old_count history = length history]. *) val entry_size : Zed_string.t -> int * [ entry_size entry ] returns the size taken by an entry in the history file in bytes . This is not exactly [ String.length entry ] since some characters are escaped and the entry is terminated by a newline character . history file in bytes. This is not exactly [String.length entry] since some characters are escaped and the entry is terminated by a newline character. *)
null
https://raw.githubusercontent.com/ocaml-community/lambda-term/f6b1940863e94d437a0578e19076a342bc9b5a70/src/lTerm_history.mli
ocaml
* History management * Type of a history. * [add history ?skip_empty ?skip_dup entry] adds [entry] to the top of the history. If [skip_empty] is [true] (the default) and [entry] contains only spaces, it is not added. If [skip_dup] is [true] (the default) and [entry] is equal to the top of the history, it is not added. If [entry] is bigger than the maximum size of the history, the history is not modified. * Returns the size (in bytes) of the history. * Returns the number of entries in the history. * Returns the number of old entries in the history. * [set_old_count history count] sets the number of old entries in the history. * Returns the maximum size of the history. * Sets the maximum size of the history. It may drop oldest entries to honor the new limit. * Returns the maximum number of entries of the history. * Sets the maximum number of entries of the history. It may drop oldest entries to honor the new limit. * [save history ?max_size ?max_entries ?skip_empty ?sjip_dup ?perm filename] saves [history] to [filename]. If [append] is [false] then the file is truncated and new entries are saved. If it is [true] (the default) then new entries are added at the end. [perm] are the file permissions in case it is created. If [append] is [true] and there is no new entries, the file is not touched. In any other case, limits are honored and the resulting file will never contains more bytes than [max_size] or more entries than [max_entries]. If [max_size] and/or [max_entries] are not specified, the ones of [history] are used. After the history is successfully saved, all entries of [history] are marked as old, i.e. [old_count history = length history].
* lTerm_history.mli * ----------------- * Copyright : ( c ) 2012 , < > * Licence : BSD3 * * This file is a part of Lambda - Term . * lTerm_history.mli * ----------------- * Copyright : (c) 2012, Jeremie Dimino <> * Licence : BSD3 * * This file is a part of Lambda-Term. *) type t val create : ?max_size : int -> ?max_entries : int -> Zed_string.t list -> t * [ create ? max_size ? max_lines init ] creates a new history . [ max_size ] is the maximum size in bytes of the history . Oldest entries are dropped if this limit is reached . The default is [ max_int ] . [ max_entries ] is the maximum number of entries of the history . Oldest entries are dropped if this limit is reached . The default is no [ max_int ] . [ init ] is the initial contents of the history . All entries of [ init ] are considered " old " . Old entries are not saved by { ! save } when [ append ] is set to [ true ] . Note : the first element of [ init ] must be the most recent entry . [max_size] is the maximum size in bytes of the history. Oldest entries are dropped if this limit is reached. The default is [max_int]. [max_entries] is the maximum number of entries of the history. Oldest entries are dropped if this limit is reached. The default is no [max_int]. [init] is the initial contents of the history. All entries of [init] are considered "old". Old entries are not saved by {!save} when [append] is set to [true]. Note: the first element of [init] must be the most recent entry. *) val add : t -> ?skip_empty : bool -> ?skip_dup : bool -> Zed_string.t -> unit val contents : t -> Zed_string.t list * Returns all the entries of the history . The first element of the list is the most recent entry . list is the most recent entry. *) val size : t -> int val length : t -> int val old_count : t -> int val set_old_count : t -> int -> unit val max_size : t -> int val set_max_size : t -> int -> unit val max_entries : t -> int val set_max_entries : t -> int -> unit val load : t -> ?log : (int -> string -> unit Lwt.t) -> ?skip_empty : bool -> ?skip_dup : bool -> string -> unit Lwt.t * [ load history ? log ? skip_empty ? skip_dup filename ] loads entries from [ filename ] to [ history ] . If [ filename ] does not exists [ history ] is not modified . [ log ] is the function used to log errors contained in the history file ( errors are because of non - UTF8 data ) . Arguments are a line number and an error message . The default is to use the default logger ( of [ Lwt_log ] ) . Entries containing errors are skipped . Note : all entries are marked as old , i.e. [ old_count history = length history ] . from [filename] to [history]. If [filename] does not exists [history] is not modified. [log] is the function used to log errors contained in the history file (errors are because of non-UTF8 data). Arguments are a line number and an error message. The default is to use the default logger (of [Lwt_log]). Entries containing errors are skipped. Note: all entries are marked as old, i.e. [old_count history = length history]. *) val save : t -> ?max_size : int -> ?max_entries : int -> ?skip_empty : bool -> ?skip_dup : bool -> ?append : bool -> ?perm : int -> string -> unit Lwt.t val entry_size : Zed_string.t -> int * [ entry_size entry ] returns the size taken by an entry in the history file in bytes . This is not exactly [ String.length entry ] since some characters are escaped and the entry is terminated by a newline character . history file in bytes. This is not exactly [String.length entry] since some characters are escaped and the entry is terminated by a newline character. *)
a73c132373fe45b59a97fe7d1872999f6a5be68c7d1222efda529fece73a26b1
replikativ/datahike
lru.cljc
(ns ^:no-doc datahike.lru (:require [clojure.core.cache :refer [defcache CacheProtocol]] clojure.data.priority-map)) (declare assoc-lru cleanup-lru) #?(:cljs (deftype LRU [key-value gen-key key-gen gen limit] IAssociative (-assoc [this k v] (assoc-lru this k v)) (-contains-key? [_ k] (-contains-key? key-value k)) ILookup (-lookup [_ k] (-lookup key-value k nil)) (-lookup [_ k nf] (-lookup key-value k nf)) IPrintWithWriter (-pr-writer [_ writer opts] (-pr-writer (persistent! key-value) writer opts))) :clj (deftype LRU [^clojure.lang.Associative key-value gen-key key-gen gen limit] clojure.lang.ILookup (valAt [_ k] (.valAt key-value k)) (valAt [_ k not-found] (.valAt key-value k not-found)) clojure.lang.Associative (containsKey [_ k] (.containsKey key-value k)) (entryAt [_ k] (.entryAt key-value k)) (assoc [this k v] (assoc-lru this k v)))) (defn assoc-lru [^LRU lru k v] (let [key-value (.-key-value lru) gen-key (.-gen-key lru) key-gen (.-key-gen lru) gen (.-gen lru) limit (.-limit lru)] (if-let [g (key-gen k nil)] (->LRU key-value (-> gen-key (dissoc g) (assoc gen k)) (assoc key-gen k gen) (inc gen) limit) (cleanup-lru (->LRU (assoc key-value k v) (assoc gen-key gen k) (assoc key-gen k gen) (inc gen) limit))))) (defn cleanup-lru [^LRU lru] (if (> (count (.-key-value lru)) (.-limit lru)) (let [key-value (.-key-value lru) gen-key (.-gen-key lru) key-gen (.-key-gen lru) gen (.-gen lru) limit (.-limit lru) [g k] (first gen-key)] (->LRU (dissoc key-value k) (dissoc gen-key g) (dissoc key-gen k) gen limit)) lru)) (defn lru [limit] (->LRU {} (sorted-map) {} 0 limit)) (defcache LRUDatomCache [cache lru counts n-total-datoms tick datom-limit] CacheProtocol (lookup [_ item] (get cache item)) (lookup [_ item not-found] (get cache item not-found)) (has? [_ item] (contains? cache item)) (hit [_ item] (let [tick+ (inc tick)] (LRUDatomCache. cache (if (contains? cache item) (assoc lru item tick+) lru) counts n-total-datoms tick+ datom-limit))) (miss [this item result] (let [tick+ (inc tick) n-new-datoms (count result) new-size (+ n-total-datoms n-new-datoms) [c l n s] (if (contains? lru item) [(dissoc cache item) (dissoc lru item) (dissoc counts item) (- new-size (get counts item))] [cache lru counts new-size]) [c l n s] (loop [c c l l n n s s] (if (> s datom-limit) (let [k (first (peek lru))] (if-let [x (get n k)] (recur (dissoc c k) (dissoc l k) (dissoc n k) (- s x)) [c l n s])) [c l n s]))] (LRUDatomCache. (assoc c item result) (assoc l item tick+) (assoc n item n-new-datoms) s tick+ datom-limit))) (evict [this key] (if (contains? cache key) (LRUDatomCache. (dissoc cache key) (dissoc lru key) (dissoc counts key) (- n-total-datoms (get counts key)) (inc tick) datom-limit) this)) (seed [_ base] (LRUDatomCache. base (into (clojure.data.priority-map/priority-map) (map #(vector % 0) (keys base))) (into {} (map #(vector % (count (get base %))) (keys base))) 0 0 datom-limit)) Object (toString [_] (str cache \, \space lru \, \space counts \, \space n-total-datoms \, \space tick \, \space datom-limit))) (defn lru-datom-cache-factory "Returns an LRU cache with the cache and usage-table initialied to `base` -- each entry is initialized with the same usage value. This function takes an optional `:threshold` argument that defines the maximum number of elements in the cache before the LRU semantics apply (default is 32)." [base & {threshold :threshold :or {threshold 32}}] {:pre [(number? threshold) (< 0 threshold) (map? base)]} (atom (clojure.core.cache/seed (LRUDatomCache. {} (clojure.data.priority-map/priority-map) {} 0 0 threshold) base)))
null
https://raw.githubusercontent.com/replikativ/datahike/7e60af807dd4db1d0eb73b75ac2f010e31361a3a/src/datahike/lru.cljc
clojure
(ns ^:no-doc datahike.lru (:require [clojure.core.cache :refer [defcache CacheProtocol]] clojure.data.priority-map)) (declare assoc-lru cleanup-lru) #?(:cljs (deftype LRU [key-value gen-key key-gen gen limit] IAssociative (-assoc [this k v] (assoc-lru this k v)) (-contains-key? [_ k] (-contains-key? key-value k)) ILookup (-lookup [_ k] (-lookup key-value k nil)) (-lookup [_ k nf] (-lookup key-value k nf)) IPrintWithWriter (-pr-writer [_ writer opts] (-pr-writer (persistent! key-value) writer opts))) :clj (deftype LRU [^clojure.lang.Associative key-value gen-key key-gen gen limit] clojure.lang.ILookup (valAt [_ k] (.valAt key-value k)) (valAt [_ k not-found] (.valAt key-value k not-found)) clojure.lang.Associative (containsKey [_ k] (.containsKey key-value k)) (entryAt [_ k] (.entryAt key-value k)) (assoc [this k v] (assoc-lru this k v)))) (defn assoc-lru [^LRU lru k v] (let [key-value (.-key-value lru) gen-key (.-gen-key lru) key-gen (.-key-gen lru) gen (.-gen lru) limit (.-limit lru)] (if-let [g (key-gen k nil)] (->LRU key-value (-> gen-key (dissoc g) (assoc gen k)) (assoc key-gen k gen) (inc gen) limit) (cleanup-lru (->LRU (assoc key-value k v) (assoc gen-key gen k) (assoc key-gen k gen) (inc gen) limit))))) (defn cleanup-lru [^LRU lru] (if (> (count (.-key-value lru)) (.-limit lru)) (let [key-value (.-key-value lru) gen-key (.-gen-key lru) key-gen (.-key-gen lru) gen (.-gen lru) limit (.-limit lru) [g k] (first gen-key)] (->LRU (dissoc key-value k) (dissoc gen-key g) (dissoc key-gen k) gen limit)) lru)) (defn lru [limit] (->LRU {} (sorted-map) {} 0 limit)) (defcache LRUDatomCache [cache lru counts n-total-datoms tick datom-limit] CacheProtocol (lookup [_ item] (get cache item)) (lookup [_ item not-found] (get cache item not-found)) (has? [_ item] (contains? cache item)) (hit [_ item] (let [tick+ (inc tick)] (LRUDatomCache. cache (if (contains? cache item) (assoc lru item tick+) lru) counts n-total-datoms tick+ datom-limit))) (miss [this item result] (let [tick+ (inc tick) n-new-datoms (count result) new-size (+ n-total-datoms n-new-datoms) [c l n s] (if (contains? lru item) [(dissoc cache item) (dissoc lru item) (dissoc counts item) (- new-size (get counts item))] [cache lru counts new-size]) [c l n s] (loop [c c l l n n s s] (if (> s datom-limit) (let [k (first (peek lru))] (if-let [x (get n k)] (recur (dissoc c k) (dissoc l k) (dissoc n k) (- s x)) [c l n s])) [c l n s]))] (LRUDatomCache. (assoc c item result) (assoc l item tick+) (assoc n item n-new-datoms) s tick+ datom-limit))) (evict [this key] (if (contains? cache key) (LRUDatomCache. (dissoc cache key) (dissoc lru key) (dissoc counts key) (- n-total-datoms (get counts key)) (inc tick) datom-limit) this)) (seed [_ base] (LRUDatomCache. base (into (clojure.data.priority-map/priority-map) (map #(vector % 0) (keys base))) (into {} (map #(vector % (count (get base %))) (keys base))) 0 0 datom-limit)) Object (toString [_] (str cache \, \space lru \, \space counts \, \space n-total-datoms \, \space tick \, \space datom-limit))) (defn lru-datom-cache-factory "Returns an LRU cache with the cache and usage-table initialied to `base` -- each entry is initialized with the same usage value. This function takes an optional `:threshold` argument that defines the maximum number of elements in the cache before the LRU semantics apply (default is 32)." [base & {threshold :threshold :or {threshold 32}}] {:pre [(number? threshold) (< 0 threshold) (map? base)]} (atom (clojure.core.cache/seed (LRUDatomCache. {} (clojure.data.priority-map/priority-map) {} 0 0 threshold) base)))
76c20e4fad80c7e9766678ce928381b563470f99f51a90c4d05495028a1da33a
Appliscale/xprof
xprof_core_app.erl
@doc XProf Core application callback %% @end -module(xprof_core_app). -behaviour(application). %% Application callbacks -export([start/2, stop/1]). %% Application callbacks start(_StartType, _StartArgs) -> xprof_core_sup:start_link(). stop(_State) -> ok.
null
https://raw.githubusercontent.com/Appliscale/xprof/198e5451db429cdb7bf6b4640ec932c425b635ae/apps/xprof_core/src/xprof_core_app.erl
erlang
@end Application callbacks Application callbacks
@doc XProf Core application callback -module(xprof_core_app). -behaviour(application). -export([start/2, stop/1]). start(_StartType, _StartArgs) -> xprof_core_sup:start_link(). stop(_State) -> ok.
43da276b7d30998b299ce5f6535474698361a8c71b3e19022af55f8f84c38277
redstarssystems/rssyslib
libtemplate.clj
(ns clj.new.org.rssys.libtemplate (:require [clj.new.templates :refer [renderer project-data ->files]])) (defn libtemplate "entry point to run template." [name] (let [render (renderer "rssyslib") data (project-data name)] (println "Generating project from library template ") (println "See README.adoc in project root to install once project prerequisites.") (->files data [".clj-kondo/config.edn" (render ".clj-kondo/config.edn" data)] ["dev/src/user.clj" (render "dev/src/user.clj" data)] ["deps.edn" (render "deps.edn" data)] [".gitignore" (render ".gitignore" data)] ["resources/readme.txt" (render "resources/readme.txt" data)] ["src/{{nested-dirs}}/core.clj" (render "src/core.clj" data)] ["test/{{nested-dirs}}/core_test.clj" (render "test/core_test.clj" data)] [".editorconfig" (render ".editorconfig" data)] ["project-config.edn" (render "project-config.edn" data)] ["project-secrets.edn" (render "project-secrets.edn" data)] [".cljstyle" (render ".cljstyle" data)] ["CHANGELOG.adoc" (render "CHANGELOG.adoc" data)] ["LICENSE" (render "LICENSE" data)] ["bb.edn" (render "bb.edn" data)] ["tests.edn" (render "tests.edn" data)] ["project-version" (render "project-version" data)] ["README.adoc" (render "README.adoc" data)] ["scripts/bump-semver.clj" (render "scripts/bump-semver.clj" data)] ["pom.xml" (render "pom.xml" data)])))
null
https://raw.githubusercontent.com/redstarssystems/rssyslib/68a9232fa620541cc4657bbd507313974158f92e/src/clj/new/org/rssys/libtemplate.clj
clojure
(ns clj.new.org.rssys.libtemplate (:require [clj.new.templates :refer [renderer project-data ->files]])) (defn libtemplate "entry point to run template." [name] (let [render (renderer "rssyslib") data (project-data name)] (println "Generating project from library template ") (println "See README.adoc in project root to install once project prerequisites.") (->files data [".clj-kondo/config.edn" (render ".clj-kondo/config.edn" data)] ["dev/src/user.clj" (render "dev/src/user.clj" data)] ["deps.edn" (render "deps.edn" data)] [".gitignore" (render ".gitignore" data)] ["resources/readme.txt" (render "resources/readme.txt" data)] ["src/{{nested-dirs}}/core.clj" (render "src/core.clj" data)] ["test/{{nested-dirs}}/core_test.clj" (render "test/core_test.clj" data)] [".editorconfig" (render ".editorconfig" data)] ["project-config.edn" (render "project-config.edn" data)] ["project-secrets.edn" (render "project-secrets.edn" data)] [".cljstyle" (render ".cljstyle" data)] ["CHANGELOG.adoc" (render "CHANGELOG.adoc" data)] ["LICENSE" (render "LICENSE" data)] ["bb.edn" (render "bb.edn" data)] ["tests.edn" (render "tests.edn" data)] ["project-version" (render "project-version" data)] ["README.adoc" (render "README.adoc" data)] ["scripts/bump-semver.clj" (render "scripts/bump-semver.clj" data)] ["pom.xml" (render "pom.xml" data)])))
129a7ef2196c9a1d627ef4dabdde78a8faf55ac28005c084a329649342db2649
valderman/haste-compiler
DataToTag.hs
Test case constributed by module Tests.DataToTag where import Control.Monad import System.IO.Unsafe import Control.Applicative (Applicative (..)) trace :: Show a => a -> b -> b trace msg = seq $! unsafePerformIO (putStrLn $ show msg) runTest :: IO String runTest = return . show $ parse "a" -- | Parse a string into the token list [Tok1] and return True if the parser -- (token Tok1) can verify that. parse :: String -> Bool parse s = case runParser tokenize s of Just ([], ts) -> case runParser (token Tok1) ts of Just ([], _) -> True _ -> False _ -> False | The Parser type is parameterized over the input stream element type @s@ and the return type A parser takes the input and produces a return value -- together with the not yet consumed input. newtype Parser s a = Parser { runParser :: [s] -> Maybe ([s], a) } parserError s msg = Nothing parserAccept s a = Just (s, a) instance Functor (Parser s) where fmap f m = m >>= return . f instance Applicative (Parser s) where pure = return f <*> x = f >>= \f' -> fmap f' x instance Monad (Parser s) where p >>= f = Parser $ \s -> case runParser p s of Just (s', a) -> runParser (f a) s' Nothing -> Nothing return = Parser . flip parserAccept fail = Parser . flip parserError (<|>) :: Parser s a -> Parser s a -> Parser s a p1 <|> p2 = Parser $ \s -> runParser p1 s `or` runParser p2 s where Nothing `or` b = b a `or` _ = a many :: Parser s a -> Parser s [a] many p = many1 p <|> return [] many1 :: Parser s a -> Parser s [a] many1 p = liftM2 (:) p (many p) satisfy :: (s -> Bool) -> Parser s s satisfy p = Parser go where go (x:xs) | p x = parserAccept xs x go s = parserError s "not satisfied" data Token = Tok1 | Tok2 | Tok3 | Tok4 | Tok5 | Tok6 | Tok7 | Tok8 | Tok9 deriving (Show, Eq) tokenize :: Parser Char [Token] tokenize = many1 $ many1 (satisfy $ const True) >> return Tok1 token :: Token -> Parser Token Token token t = satisfy (== t)
null
https://raw.githubusercontent.com/valderman/haste-compiler/47d942521570eb4b8b6828b0aa38e1f6b9c3e8a8/Tests/DataToTag.hs
haskell
| Parse a string into the token list [Tok1] and return True if the parser (token Tok1) can verify that. together with the not yet consumed input.
Test case constributed by module Tests.DataToTag where import Control.Monad import System.IO.Unsafe import Control.Applicative (Applicative (..)) trace :: Show a => a -> b -> b trace msg = seq $! unsafePerformIO (putStrLn $ show msg) runTest :: IO String runTest = return . show $ parse "a" parse :: String -> Bool parse s = case runParser tokenize s of Just ([], ts) -> case runParser (token Tok1) ts of Just ([], _) -> True _ -> False _ -> False | The Parser type is parameterized over the input stream element type @s@ and the return type A parser takes the input and produces a return value newtype Parser s a = Parser { runParser :: [s] -> Maybe ([s], a) } parserError s msg = Nothing parserAccept s a = Just (s, a) instance Functor (Parser s) where fmap f m = m >>= return . f instance Applicative (Parser s) where pure = return f <*> x = f >>= \f' -> fmap f' x instance Monad (Parser s) where p >>= f = Parser $ \s -> case runParser p s of Just (s', a) -> runParser (f a) s' Nothing -> Nothing return = Parser . flip parserAccept fail = Parser . flip parserError (<|>) :: Parser s a -> Parser s a -> Parser s a p1 <|> p2 = Parser $ \s -> runParser p1 s `or` runParser p2 s where Nothing `or` b = b a `or` _ = a many :: Parser s a -> Parser s [a] many p = many1 p <|> return [] many1 :: Parser s a -> Parser s [a] many1 p = liftM2 (:) p (many p) satisfy :: (s -> Bool) -> Parser s s satisfy p = Parser go where go (x:xs) | p x = parserAccept xs x go s = parserError s "not satisfied" data Token = Tok1 | Tok2 | Tok3 | Tok4 | Tok5 | Tok6 | Tok7 | Tok8 | Tok9 deriving (Show, Eq) tokenize :: Parser Char [Token] tokenize = many1 $ many1 (satisfy $ const True) >> return Tok1 token :: Token -> Parser Token Token token t = satisfy (== t)
6fb49c41f13a9179db32f832445172a7255364a9522a53db634434714a87c4ad
tomjaguarpaw/haskell-opaleye
Label.hs
{-# LANGUAGE Arrows #-} module Opaleye.Label ( label', -- * Deprecated label ) where import qualified Opaleye.Internal.PrimQuery as PQ import qualified Opaleye.Internal.QueryArr as Q import qualified Opaleye.Select as S import Control.Arrow (returnA) -- | Add a commented label to the generated SQL. label' :: String -> S.Select () label' l = Q.selectArr f where f = pure (\() -> ((), PQ.aLabel l)) | Will be deprecated in version 0.10 . Use ' label\ '' instead . label :: String -> S.SelectArr a b -> S.SelectArr a b label l s = proc a -> do b <- s -< a label' l -< () returnA -< b
null
https://raw.githubusercontent.com/tomjaguarpaw/haskell-opaleye/41b0f82d965edbde6a704911c7097600b8c26211/src/Opaleye/Label.hs
haskell
# LANGUAGE Arrows # * Deprecated | Add a commented label to the generated SQL.
module Opaleye.Label ( label', label ) where import qualified Opaleye.Internal.PrimQuery as PQ import qualified Opaleye.Internal.QueryArr as Q import qualified Opaleye.Select as S import Control.Arrow (returnA) label' :: String -> S.Select () label' l = Q.selectArr f where f = pure (\() -> ((), PQ.aLabel l)) | Will be deprecated in version 0.10 . Use ' label\ '' instead . label :: String -> S.SelectArr a b -> S.SelectArr a b label l s = proc a -> do b <- s -< a label' l -< () returnA -< b
ae55dea52b0f6416985a9fcb19dc0494dc2abda39998bfbec2ccbda498606dd0
tcoram/maunder
maunder_app.erl
%%%------------------------------------------------------------------- The contents of this file are subject to the Mozilla Public 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 / %% Software distributed under the License is distributed on an " AS IS " %% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See %% the License for the specific language governing rights and %% limitations under the License. %% @author < > ( C ) 2012,2013 Todd Coram %%% @doc %%% %%% @end Created : 27 Jul 2012 by < ) > %%%------------------------------------------------------------------- -module(maunder_app). -author(''). % Design/Layout heavily based on -blocking_TCP_server_using_OTP_principles -behaviour(application). -export([start_ssl_client/0]). %% Application callbacks -export([start/2, stop/1, init/1]). -define(MAX_RESTART, 5). -define(MAX_TIME, 60). -define(DEF_PORT, 8080). -define(SSL_OPTIONS, [binary, {nodelay, true}, {active, false}, {reuseaddr, true}, {certfile, "server.pem"}, {versions, [tlsv1]}]). %% =================================================================== %% Application callbacks %% =================================================================== start_ssl_client() -> supervisor:start_child(ssl_client_sup, []). %%---------------------------------------------------------------------- %% Application behaviour callbacks %%---------------------------------------------------------------------- start(_Type, _Args) -> ListenPort = get_app_env(listen_port, ?DEF_PORT), supervisor:start_link({local, ?MODULE}, ?MODULE, [ListenPort, ssl_client]). stop(_S) -> ok. %%---------------------------------------------------------------------- %% Supervisor behaviour callbacks %%---------------------------------------------------------------------- init([Port, Module]) -> io:format("init(~p,~p])~n",[Port,Module]), {ok, {_SupFlags = {one_for_one, ?MAX_RESTART, ?MAX_TIME}, [ % SSL Listener { ssl_server_sup, % Id = internal id StartFun = { M , F , A } permanent, % Restart = permanent | transient | temporary 2000, % Shutdown = brutal_kill | int() >= 0 | infinity worker, % Type = worker | supervisor [ssl_listener] % Modules = [Module] | dynamic }, { udp_server_sup, % Id = internal id StartFun = { M , F , A } permanent, % Restart = permanent | transient | temporary 2000, % Shutdown = brutal_kill | int() >= 0 | infinity worker, % Type = worker | supervisor [udp_listener] % Modules = [Module] | dynamic }, { maunder_server_sup, % Id = internal id StartFun = { M , F , A } permanent, % Restart = permanent | transient | temporary 2000, % Shutdown = brutal_kill | int() >= 0 | infinity worker, % Type = worker | supervisor [maunder_server] % Modules = [Module] | dynamic }, { voip_server_sup, % Id = internal id StartFun = { M , F , A } permanent, % Restart = permanent | transient | temporary 2000, % Shutdown = brutal_kill | int() >= 0 | infinity worker, % Type = worker | supervisor [voip_server] % Modules = [Module] | dynamic }, { ssl_client_sup, {supervisor,start_link,[{local, ssl_client_sup}, ?MODULE, [Module]]}, permanent, % Restart = permanent | transient | temporary infinity, % Shutdown = brutal_kill | int() >= 0 | infinity supervisor, % Type = worker | supervisor [] % Modules = [Module] | dynamic } ] } }; init([Module]) -> io:format("init(~p)~n",[Module]), {ok, {_SupFlags = {simple_one_for_one, ?MAX_RESTART, ?MAX_TIME}, [ % SSL Client { undefined, % Id = internal id StartFun = { M , F , A } temporary, % Restart = permanent | transient | temporary 2000, % Shutdown = brutal_kill | int() >= 0 | infinity worker, % Type = worker | supervisor [] % Modules = [Module] | dynamic } ] } }. %%---------------------------------------------------------------------- Internal functions %%---------------------------------------------------------------------- get_app_env(Opt, Default) -> case application:get_env(application:get_application(), Opt) of {ok, Val} -> Val; _ -> case init:get_argument(Opt) of [[Val | _]] -> Val; error -> Default end end.
null
https://raw.githubusercontent.com/tcoram/maunder/ae8f8f286d51841087f7df79a37b6f3d882a19c2/src/maunder_app.erl
erlang
------------------------------------------------------------------- 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 / basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. @doc @end ------------------------------------------------------------------- Design/Layout heavily based on Application callbacks =================================================================== Application callbacks =================================================================== ---------------------------------------------------------------------- Application behaviour callbacks ---------------------------------------------------------------------- ---------------------------------------------------------------------- Supervisor behaviour callbacks ---------------------------------------------------------------------- SSL Listener Id = internal id Restart = permanent | transient | temporary Shutdown = brutal_kill | int() >= 0 | infinity Type = worker | supervisor Modules = [Module] | dynamic Id = internal id Restart = permanent | transient | temporary Shutdown = brutal_kill | int() >= 0 | infinity Type = worker | supervisor Modules = [Module] | dynamic Id = internal id Restart = permanent | transient | temporary Shutdown = brutal_kill | int() >= 0 | infinity Type = worker | supervisor Modules = [Module] | dynamic Id = internal id Restart = permanent | transient | temporary Shutdown = brutal_kill | int() >= 0 | infinity Type = worker | supervisor Modules = [Module] | dynamic Restart = permanent | transient | temporary Shutdown = brutal_kill | int() >= 0 | infinity Type = worker | supervisor Modules = [Module] | dynamic SSL Client Id = internal id Restart = permanent | transient | temporary Shutdown = brutal_kill | int() >= 0 | infinity Type = worker | supervisor Modules = [Module] | dynamic ---------------------------------------------------------------------- ----------------------------------------------------------------------
The contents of this file are subject to the Mozilla Public License Software distributed under the License is distributed on an " AS IS " @author < > ( C ) 2012,2013 Todd Coram Created : 27 Jul 2012 by < ) > -module(maunder_app). -author(''). -blocking_TCP_server_using_OTP_principles -behaviour(application). -export([start_ssl_client/0]). -export([start/2, stop/1, init/1]). -define(MAX_RESTART, 5). -define(MAX_TIME, 60). -define(DEF_PORT, 8080). -define(SSL_OPTIONS, [binary, {nodelay, true}, {active, false}, {reuseaddr, true}, {certfile, "server.pem"}, {versions, [tlsv1]}]). start_ssl_client() -> supervisor:start_child(ssl_client_sup, []). start(_Type, _Args) -> ListenPort = get_app_env(listen_port, ?DEF_PORT), supervisor:start_link({local, ?MODULE}, ?MODULE, [ListenPort, ssl_client]). stop(_S) -> ok. init([Port, Module]) -> io:format("init(~p,~p])~n",[Port,Module]), {ok, {_SupFlags = {one_for_one, ?MAX_RESTART, ?MAX_TIME}, [ StartFun = { M , F , A } }, StartFun = { M , F , A } }, StartFun = { M , F , A } }, StartFun = { M , F , A } }, { ssl_client_sup, {supervisor,start_link,[{local, ssl_client_sup}, ?MODULE, [Module]]}, } ] } }; init([Module]) -> io:format("init(~p)~n",[Module]), {ok, {_SupFlags = {simple_one_for_one, ?MAX_RESTART, ?MAX_TIME}, [ StartFun = { M , F , A } } ] } }. Internal functions get_app_env(Opt, Default) -> case application:get_env(application:get_application(), Opt) of {ok, Val} -> Val; _ -> case init:get_argument(Opt) of [[Val | _]] -> Val; error -> Default end end.
154ba6843b06df03ce18f8235795b3ba3f7475e9b12bb0129141de127f5df4a6
lemmaandrew/CodingBatHaskell
fix45.hs
From ( This is a slightly harder version of the fix34 problem . ) Return an array that contains exactly the same numbers as the given array , but rearranged so that every 4 is immediately followed by a 5 . Do not move the 4 's , but every other number may move . The array contains the same number of 4 's and 5 's , and every 4 has a number after it that is not a 4 . In this version , 5 's may appear anywhere in the original array . (This is a slightly harder version of the fix34 problem.) Return an array that contains exactly the same numbers as the given array, but rearranged so that every 4 is immediately followed by a 5. Do not move the 4's, but every other number may move. The array contains the same number of 4's and 5's, and every 4 has a number after it that is not a 4. In this version, 5's may appear anywhere in the original array. -} import Test.Hspec ( hspec, describe, it, shouldBe ) fix45 :: [Int] -> [Int] fix45 nums = undefined main :: IO () main = hspec $ describe "Tests:" $ do it "[9,4,5,4,5,9]" $ fix45 [5,4,9,4,9,5] `shouldBe` [9,4,5,4,5,9] it "[1,4,5,1]" $ fix45 [1,4,1,5] `shouldBe` [1,4,5,1] it "[1,4,5,1,1,4,5]" $ fix45 [1,4,1,5,5,4,1] `shouldBe` [1,4,5,1,1,4,5] it "[4,5,4,5,9,9,4,5,9]" $ fix45 [4,9,4,9,5,5,4,9,5] `shouldBe` [4,5,4,5,9,9,4,5,9] it "[1,1,4,5,4,5]" $ fix45 [5,5,4,1,4,1] `shouldBe` [1,1,4,5,4,5] it "[4,5,2,2]" $ fix45 [4,2,2,5] `shouldBe` [4,5,2,2] it "[4,5,4,5,2,2]" $ fix45 [4,2,4,2,5,5] `shouldBe` [4,5,4,5,2,2] it "[4,5,4,5,2]" $ fix45 [4,2,4,5,5] `shouldBe` [4,5,4,5,2] it "[1,1,1]" $ fix45 [1,1,1] `shouldBe` [1,1,1] it "[4,5]" $ fix45 [4,5] `shouldBe` [4,5] it "[1,4,5]" $ fix45 [5,4,1] `shouldBe` [1,4,5] it "[]" $ fix45 [] `shouldBe` [] it "[1,4,5,4,5]" $ fix45 [5,4,5,4,1] `shouldBe` [1,4,5,4,5] it "[4,5,4,5,1]" $ fix45 [4,5,4,1,5] `shouldBe` [4,5,4,5,1] it "[3,4,5]" $ fix45 [3,4,5] `shouldBe` [3,4,5] it "[4,5,1]" $ fix45 [4,1,5] `shouldBe` [4,5,1] it "[1,4,5]" $ fix45 [5,4,1] `shouldBe` [1,4,5] it "[2,4,5,2]" $ fix45 [2,4,2,5] `shouldBe` [2,4,5,2]
null
https://raw.githubusercontent.com/lemmaandrew/CodingBatHaskell/d839118be02e1867504206657a0664fd79d04736/CodingBat/Array-3/fix45.hs
haskell
From ( This is a slightly harder version of the fix34 problem . ) Return an array that contains exactly the same numbers as the given array , but rearranged so that every 4 is immediately followed by a 5 . Do not move the 4 's , but every other number may move . The array contains the same number of 4 's and 5 's , and every 4 has a number after it that is not a 4 . In this version , 5 's may appear anywhere in the original array . (This is a slightly harder version of the fix34 problem.) Return an array that contains exactly the same numbers as the given array, but rearranged so that every 4 is immediately followed by a 5. Do not move the 4's, but every other number may move. The array contains the same number of 4's and 5's, and every 4 has a number after it that is not a 4. In this version, 5's may appear anywhere in the original array. -} import Test.Hspec ( hspec, describe, it, shouldBe ) fix45 :: [Int] -> [Int] fix45 nums = undefined main :: IO () main = hspec $ describe "Tests:" $ do it "[9,4,5,4,5,9]" $ fix45 [5,4,9,4,9,5] `shouldBe` [9,4,5,4,5,9] it "[1,4,5,1]" $ fix45 [1,4,1,5] `shouldBe` [1,4,5,1] it "[1,4,5,1,1,4,5]" $ fix45 [1,4,1,5,5,4,1] `shouldBe` [1,4,5,1,1,4,5] it "[4,5,4,5,9,9,4,5,9]" $ fix45 [4,9,4,9,5,5,4,9,5] `shouldBe` [4,5,4,5,9,9,4,5,9] it "[1,1,4,5,4,5]" $ fix45 [5,5,4,1,4,1] `shouldBe` [1,1,4,5,4,5] it "[4,5,2,2]" $ fix45 [4,2,2,5] `shouldBe` [4,5,2,2] it "[4,5,4,5,2,2]" $ fix45 [4,2,4,2,5,5] `shouldBe` [4,5,4,5,2,2] it "[4,5,4,5,2]" $ fix45 [4,2,4,5,5] `shouldBe` [4,5,4,5,2] it "[1,1,1]" $ fix45 [1,1,1] `shouldBe` [1,1,1] it "[4,5]" $ fix45 [4,5] `shouldBe` [4,5] it "[1,4,5]" $ fix45 [5,4,1] `shouldBe` [1,4,5] it "[]" $ fix45 [] `shouldBe` [] it "[1,4,5,4,5]" $ fix45 [5,4,5,4,1] `shouldBe` [1,4,5,4,5] it "[4,5,4,5,1]" $ fix45 [4,5,4,1,5] `shouldBe` [4,5,4,5,1] it "[3,4,5]" $ fix45 [3,4,5] `shouldBe` [3,4,5] it "[4,5,1]" $ fix45 [4,1,5] `shouldBe` [4,5,1] it "[1,4,5]" $ fix45 [5,4,1] `shouldBe` [1,4,5] it "[2,4,5,2]" $ fix45 [2,4,2,5] `shouldBe` [2,4,5,2]
05b61733411fdbeddae886e37c2b5412ec07f173de579c82594b2f9c5ecc619c
johnlawrenceaspden/hobby-code
gamma-table.clj
(defn table [g] (let [g2 (/ 1 (- 1 (* g g)))] [ g2 (* 2 g g2) (* g g2) (* 2 g g g2) (+ 2 (* g g2)) (* 2 g2)])) [ [ 1.3333333333333333 1.3333333333333333 0.6666666666666666 0.6666666666666666 2.6666666666666665 2.6666666666666665 ] ] [ [ 1.1904761904761905 0.9523809523809524 0.4761904761904762 0.38095238095238104 2.4761904761904763 2.380952380952381 ] ] (map < (table 0.5) (table 0.4)) ; (false false false false false false) (map < (table 0.0) (table 0.9)) ; (true true true true true true) (defn opt [t] (let [reds (map (fn [[a b]](< a b)) (partition 2 t))] (cond (= reds (list false false false)) :> (= reds (list true true true)) :< :else :!))) (opt (table 0.4)) (opt (table 0.3)) (map opt (map table (range 0 0.99 0.01))) ; (:> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :< :< :< :< :< :< :< :< :< :< :< :< :< :< :< :< :< :< :< :< :< :< :< :< :< :< :< :< :< :< :< :< :< :< :< :< :< :< :< :< :< :< :< :< :< :< :< :< :<) (distinct (map opt (map table (range 0 0.999 0.001)))) (reduce #(and %1 %2) ) (defn comp [t1 t2] (if (false (reduce #(and %1 %2) (map < t1 t2))) : [ [ 1 0 0 0 2 2 ] ]
null
https://raw.githubusercontent.com/johnlawrenceaspden/hobby-code/48e2a89d28557994c72299962cd8e3ace6a75b2d/reinforcement-learning/gamma-table.clj
clojure
(false false false false false false) (true true true true true true) (:> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :> :< :< :< :< :< :< :< :< :< :< :< :< :< :< :< :< :< :< :< :< :< :< :< :< :< :< :< :< :< :< :< :< :< :< :< :< :< :< :< :< :< :< :< :< :< :< :< :< :<)
(defn table [g] (let [g2 (/ 1 (- 1 (* g g)))] [ g2 (* 2 g g2) (* g g2) (* 2 g g g2) (+ 2 (* g g2)) (* 2 g2)])) [ [ 1.3333333333333333 1.3333333333333333 0.6666666666666666 0.6666666666666666 2.6666666666666665 2.6666666666666665 ] ] [ [ 1.1904761904761905 0.9523809523809524 0.4761904761904762 0.38095238095238104 2.4761904761904763 2.380952380952381 ] ] (defn opt [t] (let [reds (map (fn [[a b]](< a b)) (partition 2 t))] (cond (= reds (list false false false)) :> (= reds (list true true true)) :< :else :!))) (opt (table 0.4)) (opt (table 0.3)) (distinct (map opt (map table (range 0 0.999 0.001)))) (reduce #(and %1 %2) ) (defn comp [t1 t2] (if (false (reduce #(and %1 %2) (map < t1 t2))) : [ [ 1 0 0 0 2 2 ] ]
2a3aa378ea404896faf44eeaccc07b87a1884ceb085d53a6e631d012a5379bf9
agda/agda
SplitTree.hs
ASR ( 2017 - 07 - 08 ) . Since that this module was not used and it was causing a build problem with GHC 8.2.1 RC 3 , I removed it ( see -- Issue #2540). module Internal . TypeChecking . Coverage . SplitTree ( ) where import Agda . TypeChecking . Coverage . SplitTree -- import Test.QuickCheck -- ------------------------------------------------------------------------------ -- -- * Generating random split trees for testing -- instance Arbitrary a => Arbitrary (SplitTree' a) where -- arbitrary = frequency [ ( 5 , return $ SplittingDone 0 ) , ( 3 , ( SplitAt . defaultArg ) < $ > choose ( 1,5 ) < * > ( take 3 < $ > listOf1 arbitrary ) ) -- ] -- -- * Testing the printer -- newtype CName = CName String -- instance Show CName where -- show (CName s) = s -- instance Arbitrary CName where -- arbitrary = CName <$> elements [ " zero " , " suc " , " nil " , " cons " , " left " , " right " , " just " , " nothing " ] -- testSplitTreePrinting :: IO () -- testSplitTreePrinting = sample (arbitrary :: Gen (SplitTree' CName))
null
https://raw.githubusercontent.com/agda/agda/f50c14d3a4e92ed695783e26dbe11ad1ad7b73f7/test/Internal/TypeChecking/Coverage/SplitTree.hs
haskell
Issue #2540). import Test.QuickCheck ------------------------------------------------------------------------------ -- * Generating random split trees for testing instance Arbitrary a => Arbitrary (SplitTree' a) where arbitrary = frequency ] -- * Testing the printer newtype CName = CName String instance Show CName where show (CName s) = s instance Arbitrary CName where arbitrary = CName <$> elements testSplitTreePrinting :: IO () testSplitTreePrinting = sample (arbitrary :: Gen (SplitTree' CName))
ASR ( 2017 - 07 - 08 ) . Since that this module was not used and it was causing a build problem with GHC 8.2.1 RC 3 , I removed it ( see module Internal . TypeChecking . Coverage . SplitTree ( ) where import Agda . TypeChecking . Coverage . SplitTree [ ( 5 , return $ SplittingDone 0 ) , ( 3 , ( SplitAt . defaultArg ) < $ > choose ( 1,5 ) < * > ( take 3 < $ > listOf1 arbitrary ) ) [ " zero " , " suc " , " nil " , " cons " , " left " , " right " , " just " , " nothing " ]
1f85695e6d820045ec4cef132a22939f9f18dcd552a99ffbceeeb88db73f7973
TyOverby/mono
transfer_io.mli
{ { { Copyright ( c ) 2012 Anil Madhavapeddy < > * * Permission to use , copy , modify , and distribute this software for any * purpose with or without fee is hereby granted , provided that the above * copyright notice and this permission notice appear in all copies . * * THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN * ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . * } } } * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * }}}*) open Transfer module Make(IO : S.IO) : sig type reader type writer val make_reader : encoding -> IO.ic -> reader val make_writer : ?flush:bool -> encoding -> IO.oc -> writer val read : reader -> chunk IO.t val write : writer -> string -> unit IO.t end
null
https://raw.githubusercontent.com/TyOverby/mono/8d6b3484d5db63f2f5472c7367986ea30290764d/vendor/mirage-ocaml-cohttp/cohttp/src/transfer_io.mli
ocaml
{ { { Copyright ( c ) 2012 Anil Madhavapeddy < > * * Permission to use , copy , modify , and distribute this software for any * purpose with or without fee is hereby granted , provided that the above * copyright notice and this permission notice appear in all copies . * * THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN * ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . * } } } * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * }}}*) open Transfer module Make(IO : S.IO) : sig type reader type writer val make_reader : encoding -> IO.ic -> reader val make_writer : ?flush:bool -> encoding -> IO.oc -> writer val read : reader -> chunk IO.t val write : writer -> string -> unit IO.t end
5ccaf67f5499e4381659066302e330badd9116b28d2ba5b0e5c1e2a6c85fe359
pveber/bistro
macs.ml
open Core open Bistro open Bistro.Shell_dsl open Formats let img = [ docker_image ~account:"pveber" ~name:"macs" ~tag:"1.4.2" () ] type _ format = | Sam | Bam let sam = Sam let bam = Bam let opt_of_format = function | Sam -> "SAM" | Bam -> "BAM" type gsize = [ `hs | `mm | `ce | `dm | `gsize of int ] let gsize_expr = function | `hs -> string "hs" | `mm -> string "mm" | `dm -> string "dm" | `ce -> string "ce" | `gsize n -> int n type keep_dup = [ `all | `auto | `int of int ] let keep_dup_expr = function | `all -> string "all" | `auto -> string "auto" | `int n -> int n let name = "macs" let run ?control ?petdist ?gsize ?tsize ?bw ?pvalue ?mfold ?nolambda ?slocal ?llocal ?on_auto ?nomodel ?shiftsize ?keep_dup ?to_large ?wig ?bdg ?single_profile ?space ?call_subpeaks ?diag ?fe_min ?fe_max ?fe_step format treatment = Workflow.shell ~descr:"macs" ~mem:(Workflow.int (3 * 1024)) ~img ~np:8 [ mkdir_p dest ; cmd "macs14" [ option (opt "--control" (list ~sep:"," dep)) control ; opt "--name" seq [ dest ; string "/" ; string name ] ; opt "--format" (fun x -> x |> opt_of_format |> string) format ; option (opt "--petdist" int) petdist ; option (opt "--gsize" gsize_expr) gsize ; option (opt "--tsize" int) tsize ; option (opt "--bw" int) bw ; option (opt "--pvalue" float) pvalue ; option (opt "--mfold" (fun (i, j) -> seq ~sep:"," [int i ; int j])) mfold ; option (flag string "--nolambda") nolambda ; option (opt "--slocal" int) slocal ; option (opt "--llocal" int) llocal ; option (flag string "--on-auto") on_auto ; option (flag string "--nomodel") nomodel ; option (opt "--shiftsize" int) shiftsize ; option (opt "--keep-dup" keep_dup_expr) keep_dup ; option (flag string "--to-large") to_large ; option (flag string "--wig") wig ; option (flag string "--bdg") bdg ; option (flag string "--single-profile") single_profile ; option (opt "--space" int) space ; option (flag string "--call-subpeaks") call_subpeaks ; option (flag string "--diag") diag ; option (opt "--fe-min" int) fe_min ; option (opt "--fe-max" int) fe_max ; option (opt "--fe-step" int) fe_step ; opt "--treatment" (list ~sep:"," dep) treatment ; Fn.id dest ; ] ] class type peaks_xls = object inherit bed3 method f4 : int method f5 : int method f6 : int method f7 : float method f8 : float method f9 : float end let peaks_xls x = Workflow.select x [ name ^ "_peaks.xls" ] class type narrow_peaks = object inherit bed5 method f6 : string method f7 : float method f8 : float method f9 : float method f10 : int end let narrow_peaks x = Workflow.select x [ name ^ "_peaks.narrowPeak" ] class type peak_summits = object inherit bed4 method f5 : float end let peak_summits x = Workflow.select x [ name ^ "_summits.bed" ]
null
https://raw.githubusercontent.com/pveber/bistro/d363bd2d8257babbcb6db15bd83fd6465df7c268/lib/bio/macs.ml
ocaml
open Core open Bistro open Bistro.Shell_dsl open Formats let img = [ docker_image ~account:"pveber" ~name:"macs" ~tag:"1.4.2" () ] type _ format = | Sam | Bam let sam = Sam let bam = Bam let opt_of_format = function | Sam -> "SAM" | Bam -> "BAM" type gsize = [ `hs | `mm | `ce | `dm | `gsize of int ] let gsize_expr = function | `hs -> string "hs" | `mm -> string "mm" | `dm -> string "dm" | `ce -> string "ce" | `gsize n -> int n type keep_dup = [ `all | `auto | `int of int ] let keep_dup_expr = function | `all -> string "all" | `auto -> string "auto" | `int n -> int n let name = "macs" let run ?control ?petdist ?gsize ?tsize ?bw ?pvalue ?mfold ?nolambda ?slocal ?llocal ?on_auto ?nomodel ?shiftsize ?keep_dup ?to_large ?wig ?bdg ?single_profile ?space ?call_subpeaks ?diag ?fe_min ?fe_max ?fe_step format treatment = Workflow.shell ~descr:"macs" ~mem:(Workflow.int (3 * 1024)) ~img ~np:8 [ mkdir_p dest ; cmd "macs14" [ option (opt "--control" (list ~sep:"," dep)) control ; opt "--name" seq [ dest ; string "/" ; string name ] ; opt "--format" (fun x -> x |> opt_of_format |> string) format ; option (opt "--petdist" int) petdist ; option (opt "--gsize" gsize_expr) gsize ; option (opt "--tsize" int) tsize ; option (opt "--bw" int) bw ; option (opt "--pvalue" float) pvalue ; option (opt "--mfold" (fun (i, j) -> seq ~sep:"," [int i ; int j])) mfold ; option (flag string "--nolambda") nolambda ; option (opt "--slocal" int) slocal ; option (opt "--llocal" int) llocal ; option (flag string "--on-auto") on_auto ; option (flag string "--nomodel") nomodel ; option (opt "--shiftsize" int) shiftsize ; option (opt "--keep-dup" keep_dup_expr) keep_dup ; option (flag string "--to-large") to_large ; option (flag string "--wig") wig ; option (flag string "--bdg") bdg ; option (flag string "--single-profile") single_profile ; option (opt "--space" int) space ; option (flag string "--call-subpeaks") call_subpeaks ; option (flag string "--diag") diag ; option (opt "--fe-min" int) fe_min ; option (opt "--fe-max" int) fe_max ; option (opt "--fe-step" int) fe_step ; opt "--treatment" (list ~sep:"," dep) treatment ; Fn.id dest ; ] ] class type peaks_xls = object inherit bed3 method f4 : int method f5 : int method f6 : int method f7 : float method f8 : float method f9 : float end let peaks_xls x = Workflow.select x [ name ^ "_peaks.xls" ] class type narrow_peaks = object inherit bed5 method f6 : string method f7 : float method f8 : float method f9 : float method f10 : int end let narrow_peaks x = Workflow.select x [ name ^ "_peaks.narrowPeak" ] class type peak_summits = object inherit bed4 method f5 : float end let peak_summits x = Workflow.select x [ name ^ "_summits.bed" ]
338ae199df56335b2a56adf424e1ea479811b42d602e786d532e0e8f1f24c971
monadbobo/ocaml-core
block_group.mli
open Core.Std open Import type t = Async_core.Block_group.t val create : ?min_reserved_threads:int -> ?max_reserved_threads:int -> unit -> [ `Ok of t | `Out_of_threads ]
null
https://raw.githubusercontent.com/monadbobo/ocaml-core/9c1c06e7a1af7e15b6019a325d7dbdbd4cdb4020/base/async/unix/lib/block_group.mli
ocaml
open Core.Std open Import type t = Async_core.Block_group.t val create : ?min_reserved_threads:int -> ?max_reserved_threads:int -> unit -> [ `Ok of t | `Out_of_threads ]
a3ef4087ed911a7c8fe0c2f4fd4f04cf4db35bca5efb6cd91f5fe7b77acd4f43
synduce/Synduce
min.ml
* @synduce -s 2 -NB type 'a clist = | Single of 'a | Concat of 'a clist * 'a clist type 'a list = | Elt of 'a | Cons of 'a * 'a list let rec spec = function | Elt a -> a | Cons (hd, tl) -> min hd (spec tl) ;; let rec repr = function | Single a -> Elt a | Concat (x, y) -> dec y x and dec l1 = function | Single a -> Cons (a, repr l1) | Concat (x, y) -> dec (Concat (y, l1)) x ;; let rec target = function | Single a -> [%synt f0] a | Concat (x, y) -> [%synt odot] (target x) (target y) ;;
null
https://raw.githubusercontent.com/synduce/Synduce/42d970faa863365f10531b19945cbb5cfb70f134/benchmarks/incomplete/list/min.ml
ocaml
* @synduce -s 2 -NB type 'a clist = | Single of 'a | Concat of 'a clist * 'a clist type 'a list = | Elt of 'a | Cons of 'a * 'a list let rec spec = function | Elt a -> a | Cons (hd, tl) -> min hd (spec tl) ;; let rec repr = function | Single a -> Elt a | Concat (x, y) -> dec y x and dec l1 = function | Single a -> Cons (a, repr l1) | Concat (x, y) -> dec (Concat (y, l1)) x ;; let rec target = function | Single a -> [%synt f0] a | Concat (x, y) -> [%synt odot] (target x) (target y) ;;
ce660e69add194a00cb0d122e5f38c90a1155fdd262ca0e6b5f872ce63352ecb
id774-2/maeve
normalize.scm
(use srfi-1) (use util.match) (use maeve.lib.gauche.pp) (define (update-elements! proc xs) (pair-fold (lambda (xs _) (update! (car xs) proc) xs) #f xs) xs) (use gauche.sequence) (define-macro (debug-print x) (let1 results (gensym) `(begin (format/ss (current-error-port) "#?= ~s\n" ',x) (receive ,results ,x (for-each-with-index (lambda (i e) (format/ss (current-error-port) "#~d= ~s ~s\n" i (eq-hash e) e)) ,results) (apply values ,results))))) (define (normalize self) (let* ((outer '()) (result (let loop ((self self)) (define (default-handler) (if (pair? self) (update-elements! loop self) self)) (define (trick accs) (let loop1 ((accs accs) (result #f)) (if (null? accs) result (let* ((acc (car accs)) (tgt (acc self))) (match tgt (('block . es) (define lp (last-pair es)) (update! (car lp) (lambda (x) (set! (acc self) x) self)) (update! (car lp) loop) (push! outer (lambda (extra) (set! (car lp) extra) tgt)) (loop1 (cdr accs) self)) (else (loop1 (cdr accs) (default-handler)))))))) (match self (('set! dist src) (trick (list caddr))) (('opr2 opr v1 v2) (trick (list cadddr caddr))) (else (default-handler)))))) (fold (lambda (p e) (p e)) result outer))) (pretty-print (map normalize '(set! foo (block a b (block c d (block e f (opr2 + (block g h i) (block j k l)))))))) ;; ** syntax tree normalize problem TODO : post this problem to " doukaku " . ;; >|| ;; (set! foo (block x y z)) ;; ;; => ;; (block x y (set! foo z)) ;; ||< ;; >|| ( opr2 ;; (block a b c) ;; (block d e f)) ;; ;; => ;; (block ;; a b ;; (opr2 c (block d e f))) ;; ;; => ;; (block ;; a b ;; (block ;; d e (opr2 c f))) ;; ||< ;; >|| ;; (set! foo ;; (block ;; x y ;; (opr2 ;; (block a b c) ;; (block d e f)))) ;; ;; => ;; (block ;; x y ;; (block ;; a b ;; (block ;; d e (set! foo (opr2 c f))))) ;; ||<
null
https://raw.githubusercontent.com/id774-2/maeve/a9442c3479b0d575f896b898eb889297f30e1a96/prototype/normalize.scm
scheme
** syntax tree normalize problem >|| (set! foo (block x y z)) ;; => (block x y (set! foo z)) ||< >|| (block a b c) (block d e f)) ;; => (block a b (opr2 c (block d e f))) ;; => (block a b (block d e (opr2 c f))) ||< >|| (set! foo (block x y (opr2 (block a b c) (block d e f)))) ;; => (block x y (block a b (block d e (set! foo (opr2 c f))))) ||<
(use srfi-1) (use util.match) (use maeve.lib.gauche.pp) (define (update-elements! proc xs) (pair-fold (lambda (xs _) (update! (car xs) proc) xs) #f xs) xs) (use gauche.sequence) (define-macro (debug-print x) (let1 results (gensym) `(begin (format/ss (current-error-port) "#?= ~s\n" ',x) (receive ,results ,x (for-each-with-index (lambda (i e) (format/ss (current-error-port) "#~d= ~s ~s\n" i (eq-hash e) e)) ,results) (apply values ,results))))) (define (normalize self) (let* ((outer '()) (result (let loop ((self self)) (define (default-handler) (if (pair? self) (update-elements! loop self) self)) (define (trick accs) (let loop1 ((accs accs) (result #f)) (if (null? accs) result (let* ((acc (car accs)) (tgt (acc self))) (match tgt (('block . es) (define lp (last-pair es)) (update! (car lp) (lambda (x) (set! (acc self) x) self)) (update! (car lp) loop) (push! outer (lambda (extra) (set! (car lp) extra) tgt)) (loop1 (cdr accs) self)) (else (loop1 (cdr accs) (default-handler)))))))) (match self (('set! dist src) (trick (list caddr))) (('opr2 opr v1 v2) (trick (list cadddr caddr))) (else (default-handler)))))) (fold (lambda (p e) (p e)) result outer))) (pretty-print (map normalize '(set! foo (block a b (block c d (block e f (opr2 + (block g h i) (block j k l)))))))) TODO : post this problem to " doukaku " . ( opr2
25c0f350056137a3baa792fdc240c721d77a60eaf5e421f41f22e6486ad7dd32
mistupv/cauder
cauder_scheduler_tests.erl
-module(cauder_scheduler_tests). -import(cauder_scheduler, [scheduler_round_robin/2, scheduler_fcfs/2]). -elvis([{elvis_style, dont_repeat_yourself, disable}]). -include_lib("eunit/include/eunit.hrl"). scheduler_round_robin_test_() -> Q0 = queue:new(), Q1 = queue:from_list([a, b, c, d]), [ assert_scheduling(a, [b, c, d, a], scheduler_round_robin(Q0, {init, [a, b, c, d]})), ?_assertError(empty, scheduler_round_robin(Q0, none)), ?_assertError(empty, scheduler_round_robin(Q0, {add, a})), ?_assertError(empty, scheduler_round_robin(Q0, {remove, a})), ?_assertError(empty, scheduler_round_robin(Q0, {update, b, a})), ?_assertError(not_empty, scheduler_round_robin(Q1, {init, [a, b, c, d]})), assert_scheduling(a, [b, c, d, a], scheduler_round_robin(Q1, none)), assert_scheduling(a, [b, c, d, e, a], scheduler_round_robin(Q1, {add, e})), assert_scheduling(a, [b, c, a], scheduler_round_robin(Q1, {remove, d})), ?_assertError(not_tail, scheduler_round_robin(Q1, {remove, a})), assert_scheduling(a, [b, c, x, a], scheduler_round_robin(Q1, {update, x, d})), assert_scheduling(b, [b], scheduler_round_robin(queue:from_list([a]), {update, b, a})) ]. scheduler_fcfs_test_() -> Q0 = queue:new(), Q1 = queue:from_list([a, b, c, d]), [ assert_scheduling(a, [a, b, c, d], scheduler_fcfs(Q0, {init, [a, b, c, d]})), ?_assertError(empty, scheduler_fcfs(Q0, none)), ?_assertError(empty, scheduler_fcfs(Q0, {add, a})), ?_assertError(empty, scheduler_fcfs(Q0, {remove, a})), ?_assertError(empty, scheduler_fcfs(Q0, {update, b, a})), ?_assertError(not_empty, scheduler_fcfs(Q1, {init, [a, b, c, d]})), assert_scheduling(a, [a, b, c, d], scheduler_fcfs(Q1, none)), assert_scheduling(a, [a, b, c, d, e], scheduler_fcfs(Q1, {add, e})), ?_assertError(not_head, scheduler_fcfs(Q1, {remove, d})), assert_scheduling(b, [b, c, d], scheduler_fcfs(Q1, {remove, a})), assert_scheduling(b, [b, c, d, x], scheduler_fcfs(Q1, {update, x, a})), assert_scheduling(b, [b], scheduler_fcfs(queue:from_list([a]), {update, b, a})) ]. assert_scheduling(ExpectItem, ExpectList, Expr) -> {Item, Queue} = Expr, [?_assertEqual(ExpectItem, Item), ?_assertEqual(ExpectList, queue:to_list(Queue))].
null
https://raw.githubusercontent.com/mistupv/cauder/ff4955cca4b0aa6ae9d682e9f0532be188a5cc16/test/cauder_scheduler_tests.erl
erlang
-module(cauder_scheduler_tests). -import(cauder_scheduler, [scheduler_round_robin/2, scheduler_fcfs/2]). -elvis([{elvis_style, dont_repeat_yourself, disable}]). -include_lib("eunit/include/eunit.hrl"). scheduler_round_robin_test_() -> Q0 = queue:new(), Q1 = queue:from_list([a, b, c, d]), [ assert_scheduling(a, [b, c, d, a], scheduler_round_robin(Q0, {init, [a, b, c, d]})), ?_assertError(empty, scheduler_round_robin(Q0, none)), ?_assertError(empty, scheduler_round_robin(Q0, {add, a})), ?_assertError(empty, scheduler_round_robin(Q0, {remove, a})), ?_assertError(empty, scheduler_round_robin(Q0, {update, b, a})), ?_assertError(not_empty, scheduler_round_robin(Q1, {init, [a, b, c, d]})), assert_scheduling(a, [b, c, d, a], scheduler_round_robin(Q1, none)), assert_scheduling(a, [b, c, d, e, a], scheduler_round_robin(Q1, {add, e})), assert_scheduling(a, [b, c, a], scheduler_round_robin(Q1, {remove, d})), ?_assertError(not_tail, scheduler_round_robin(Q1, {remove, a})), assert_scheduling(a, [b, c, x, a], scheduler_round_robin(Q1, {update, x, d})), assert_scheduling(b, [b], scheduler_round_robin(queue:from_list([a]), {update, b, a})) ]. scheduler_fcfs_test_() -> Q0 = queue:new(), Q1 = queue:from_list([a, b, c, d]), [ assert_scheduling(a, [a, b, c, d], scheduler_fcfs(Q0, {init, [a, b, c, d]})), ?_assertError(empty, scheduler_fcfs(Q0, none)), ?_assertError(empty, scheduler_fcfs(Q0, {add, a})), ?_assertError(empty, scheduler_fcfs(Q0, {remove, a})), ?_assertError(empty, scheduler_fcfs(Q0, {update, b, a})), ?_assertError(not_empty, scheduler_fcfs(Q1, {init, [a, b, c, d]})), assert_scheduling(a, [a, b, c, d], scheduler_fcfs(Q1, none)), assert_scheduling(a, [a, b, c, d, e], scheduler_fcfs(Q1, {add, e})), ?_assertError(not_head, scheduler_fcfs(Q1, {remove, d})), assert_scheduling(b, [b, c, d], scheduler_fcfs(Q1, {remove, a})), assert_scheduling(b, [b, c, d, x], scheduler_fcfs(Q1, {update, x, a})), assert_scheduling(b, [b], scheduler_fcfs(queue:from_list([a]), {update, b, a})) ]. assert_scheduling(ExpectItem, ExpectList, Expr) -> {Item, Queue} = Expr, [?_assertEqual(ExpectItem, Item), ?_assertEqual(ExpectList, queue:to_list(Queue))].
d7bfa85a24509c9308b447de25fa22574783b12f7c04c7bd4b5648afaf7d48b7
agentm/project-m36
DatabaseContextFunctionError.hs
# LANGUAGE DeriveGeneric , DeriveAnyClass # module ProjectM36.DatabaseContextFunctionError where import GHC.Generics import Control.DeepSeq # ANN module ( " HLint : ignore Use newtype instead of data " : : String ) # data DatabaseContextFunctionError = DatabaseContextFunctionUserError String deriving (Generic, Eq, Show, NFData)
null
https://raw.githubusercontent.com/agentm/project-m36/57a75b35e84bebf0945db6dae53350fda83f24b6/src/lib/ProjectM36/DatabaseContextFunctionError.hs
haskell
# LANGUAGE DeriveGeneric , DeriveAnyClass # module ProjectM36.DatabaseContextFunctionError where import GHC.Generics import Control.DeepSeq # ANN module ( " HLint : ignore Use newtype instead of data " : : String ) # data DatabaseContextFunctionError = DatabaseContextFunctionUserError String deriving (Generic, Eq, Show, NFData)
8cff9e8d02da99ae817ed9cf794920d7c971a589db6a97d8283600f13d6886b4
facebook/flow
semver_parser_test.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. *) open OUnit2 exception Semver_parse_error of string let parse_version str = let lexbuf = Lexing.from_string str in try Semver_parser.version_top Semver_lexer.token lexbuf with | Parsing.Parse_error -> raise (Semver_parse_error (Lexing.lexeme lexbuf)) let parse_comparator str = let lexbuf = Lexing.from_string str in try Semver_parser.comparator_top Semver_lexer.token lexbuf with | Parsing.Parse_error -> raise (Semver_parse_error (Lexing.lexeme lexbuf)) let parse_range str = let lexbuf = Lexing.from_string str in try Semver_parser.range_top Semver_lexer.token lexbuf with | Parsing.Parse_error -> raise (Semver_parse_error (Lexing.lexeme lexbuf)) let tests = "parser" >::: [ ( "version_basics" >:: fun ctxt -> Semver_version.( let cases = [ ("0", zero); ("0.1", { zero with minor = 1 }); ("1", { zero with major = 1 }); ("1.2", { zero with major = 1; minor = 2 }); ("1.2.3", { zero with major = 1; minor = 2; patch = 3 }); ( "1.2.3-alpha", { zero with major = 1; minor = 2; patch = 3; prerelease = [Str "alpha"] } ); ( "1.2.3-alpha.2", { zero with major = 1; minor = 2; patch = 3; prerelease = [Str "alpha"; Int 2] } ); ] in List.iter (fun (str, version) -> try assert_equal ~ctxt ~printer:to_string version (parse_version str) with | Semver_parse_error token -> assert_failure ("Failed to parse " ^ str ^ ": unexpected token " ^ token)) cases; assert_bool "done" true ) ) (* fixes ounit error reporting *); ( "comparator_basics" >:: fun ctxt -> Semver_comparator.( let v1 = Semver_version.{ zero with major = 1 } in let cases = [ (">1", { op = Some Greater; version = v1 }); (">=1", { op = Some GreaterOrEqual; version = v1 }); ("<1", { op = Some Less; version = v1 }); ("<=1", { op = Some LessOrEqual; version = v1 }); ("=1", { op = Some Equal; version = v1 }); ("1", { op = None; version = v1 }); ("= 1", { op = Some Equal; version = v1 }); (" = 1", { op = Some Equal; version = v1 }); (" = 1 ", { op = Some Equal; version = v1 }); ] in List.iter (fun (str, comparator) -> try assert_equal ~ctxt ~printer:to_string comparator (parse_comparator str) with | Semver_parse_error token -> assert_failure ("Failed to parse " ^ str ^ ": unexpected token " ^ token)) cases; assert_bool "done" true ) ) (* fixes ounit error reporting *); ( "range_basics" >:: fun ctxt -> Semver_range.( let v1 = Semver_version.{ zero with major = 1 } in let v2 = Semver_version.{ zero with major = 2 } in let ge1 = Comparator Semver_comparator.{ op = Some GreaterOrEqual; version = v1 } in let lt2 = Comparator Semver_comparator.{ op = Some Less; version = v2 } in let cases = [ (">=1", [ge1]); (">=1 <2", [ge1; lt2]); ("^1", [Caret v1]); ("^1.0", [Caret v1]); ("^1.0.0", [Caret v1]); ("^1 ^2", [Caret v1; Caret v2]); (">=1 ^2", [ge1; Caret v2]); ] in List.iter (fun (str, range) -> try assert_equal ~ctxt ~printer:to_string range (parse_range str) with | Semver_parse_error token -> assert_failure ("Failed to parse " ^ str ^ ": unexpected token " ^ token)) cases; assert_bool "done" true ) ); (* fixes ounit error reporting *) ]
null
https://raw.githubusercontent.com/facebook/flow/725e6301246685c9832a62b83a49c75c7be3b7b0/src/common/semver/__tests__/semver_parser_test.ml
ocaml
fixes ounit error reporting fixes ounit error reporting fixes ounit error reporting
* 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. *) open OUnit2 exception Semver_parse_error of string let parse_version str = let lexbuf = Lexing.from_string str in try Semver_parser.version_top Semver_lexer.token lexbuf with | Parsing.Parse_error -> raise (Semver_parse_error (Lexing.lexeme lexbuf)) let parse_comparator str = let lexbuf = Lexing.from_string str in try Semver_parser.comparator_top Semver_lexer.token lexbuf with | Parsing.Parse_error -> raise (Semver_parse_error (Lexing.lexeme lexbuf)) let parse_range str = let lexbuf = Lexing.from_string str in try Semver_parser.range_top Semver_lexer.token lexbuf with | Parsing.Parse_error -> raise (Semver_parse_error (Lexing.lexeme lexbuf)) let tests = "parser" >::: [ ( "version_basics" >:: fun ctxt -> Semver_version.( let cases = [ ("0", zero); ("0.1", { zero with minor = 1 }); ("1", { zero with major = 1 }); ("1.2", { zero with major = 1; minor = 2 }); ("1.2.3", { zero with major = 1; minor = 2; patch = 3 }); ( "1.2.3-alpha", { zero with major = 1; minor = 2; patch = 3; prerelease = [Str "alpha"] } ); ( "1.2.3-alpha.2", { zero with major = 1; minor = 2; patch = 3; prerelease = [Str "alpha"; Int 2] } ); ] in List.iter (fun (str, version) -> try assert_equal ~ctxt ~printer:to_string version (parse_version str) with | Semver_parse_error token -> assert_failure ("Failed to parse " ^ str ^ ": unexpected token " ^ token)) cases; assert_bool "done" true ) ) ( "comparator_basics" >:: fun ctxt -> Semver_comparator.( let v1 = Semver_version.{ zero with major = 1 } in let cases = [ (">1", { op = Some Greater; version = v1 }); (">=1", { op = Some GreaterOrEqual; version = v1 }); ("<1", { op = Some Less; version = v1 }); ("<=1", { op = Some LessOrEqual; version = v1 }); ("=1", { op = Some Equal; version = v1 }); ("1", { op = None; version = v1 }); ("= 1", { op = Some Equal; version = v1 }); (" = 1", { op = Some Equal; version = v1 }); (" = 1 ", { op = Some Equal; version = v1 }); ] in List.iter (fun (str, comparator) -> try assert_equal ~ctxt ~printer:to_string comparator (parse_comparator str) with | Semver_parse_error token -> assert_failure ("Failed to parse " ^ str ^ ": unexpected token " ^ token)) cases; assert_bool "done" true ) ) ( "range_basics" >:: fun ctxt -> Semver_range.( let v1 = Semver_version.{ zero with major = 1 } in let v2 = Semver_version.{ zero with major = 2 } in let ge1 = Comparator Semver_comparator.{ op = Some GreaterOrEqual; version = v1 } in let lt2 = Comparator Semver_comparator.{ op = Some Less; version = v2 } in let cases = [ (">=1", [ge1]); (">=1 <2", [ge1; lt2]); ("^1", [Caret v1]); ("^1.0", [Caret v1]); ("^1.0.0", [Caret v1]); ("^1 ^2", [Caret v1; Caret v2]); (">=1 ^2", [ge1; Caret v2]); ] in List.iter (fun (str, range) -> try assert_equal ~ctxt ~printer:to_string range (parse_range str) with | Semver_parse_error token -> assert_failure ("Failed to parse " ^ str ^ ": unexpected token " ^ token)) cases; assert_bool "done" true ) ); ]
18bedd470ee5f03a757072a566cb2949ae28f5310aa213f040319e866f8b0851
JoelSanchez/ventas
description.clj
(ns ventas.server.api.description (:require [clojure.set :as set] [clojure.spec.alpha :as spec] [clojure.test.check.generators :as gen] [spec-tools.core :as st] [spec-tools.data-spec :as data-spec] [spec-tools.impl :as impl] [spec-tools.parse :as parse] [spec-tools.visitor :as visitor] [ventas.server.api :as api] [ventas.utils :as utils])) (defn- only-entry? [key a-map] (= [key] (keys a-map))) (defn- simplify-all-of [spec] (let [subspecs (->> (:all-of spec) (remove empty?))] (cond (empty? subspecs) (dissoc spec :all-of) (and (= (count subspecs) 1) (only-entry? :all-of spec)) (first subspecs) :else (assoc spec :all-of subspecs)))) (defn- spec-dispatch [dispatch _ _ _] dispatch) (defmulti accept-spec spec-dispatch :default ::default) (defn transform ([spec] (transform spec nil)) ([spec options] (visitor/visit spec accept-spec options))) any ? ( one - of [ ( return nil ) ( any - printable ) ] ) (defmethod accept-spec 'clojure.core/any? [_ _ _ _] {}) ; some? (such-that some? (any-printable)) (defmethod accept-spec 'clojure.core/some? [_ _ _ _] {}) number ? ( one - of [ ( large - integer ) ( double ) ] ) (defmethod accept-spec 'clojure.core/number? [_ _ _ _] {:type :number}) (defmethod accept-spec 'clojure.core/pos? [_ _ _ _] {:minimum 0 :exclusive-minimum true}) (defmethod accept-spec 'clojure.core/neg? [_ _ _ _] {:maximum 0 :exclusive-maximum true}) ; integer? (large-integer) (defmethod accept-spec 'clojure.core/integer? [_ _ _ _] {:type :number}) ; int? (large-integer) (defmethod accept-spec 'clojure.core/int? [_ _ _ _] {:type :number}) ; pos-int? (large-integer* {:min 1}) (defmethod accept-spec 'clojure.core/pos-int? [_ _ _ _] {:type :number :minimum 1}) neg - int ? ( large - integer * { : -1 } ) (defmethod accept-spec 'clojure.core/neg-int? [_ _ _ _] {:type :number :maximum -1}) ; nat-int? (large-integer* {:min 0}) (defmethod accept-spec 'clojure.core/nat-int? [_ _ _ _] {:type :number :minimum 0}) ; float? (double) (defmethod accept-spec 'clojure.core/float? [_ _ _ _] {:type :float}) ; double? (double) (defmethod accept-spec 'clojure.core/double? [_ _ _ _] {:type :double}) ; boolean? (boolean) (defmethod accept-spec 'clojure.core/boolean? [_ _ _ _] {:type :boolean}) ; string? (string-alphanumeric) (defmethod accept-spec 'clojure.core/string? [_ _ _ _] {:type :string}) ident ? ( one - of [ ( keyword - ns ) ( symbol - ns ) ] ) (defmethod accept-spec 'clojure.core/ident? [_ _ _ _] {:type :ident}) simple - ident ? ( one - of [ ( keyword ) ( symbol ) ] ) (defmethod accept-spec 'clojure.core/simple-ident? [_ _ _ _] {:type :ident :qualified? false}) qualified - ident ? ( such - that qualified ? ( one - of [ ( keyword - ns ) ( symbol - ns ) ] ) ) (defmethod accept-spec 'clojure.core/qualified-ident? [_ _ _ _] {:type :ident :qualified? true}) ; keyword? (keyword-ns) (defmethod accept-spec 'clojure.core/keyword? [_ _ _ _] {:type :keyword}) ; simple-keyword? (keyword) (defmethod accept-spec 'clojure.core/simple-keyword? [_ _ _ _] {:type :keyword :qualified? false}) ; qualified-keyword? (such-that qualified? (keyword-ns)) (defmethod accept-spec 'clojure.core/qualified-keyword? [_ _ _ _] {:type :keyword :qualified? true}) ; symbol? (symbol-ns) (defmethod accept-spec 'clojure.core/symbol? [_ _ _ _] {:type :symbol}) ; simple-symbol? (symbol) (defmethod accept-spec 'clojure.core/simple-symbol? [_ _ _ _] {:type :symbol :qualified? false}) ; qualified-symbol? (such-that qualified? (symbol-ns)) (defmethod accept-spec 'clojure.core/qualified-symbol? [_ _ _ _] {:type :symbol :qualified? true}) ; uuid? (uuid) (defmethod accept-spec 'clojure.core/uuid? [_ _ _ _] {:type :string :format :uuid}) ; uri? (fmap #(java.net.URI/create (str "http://" % ".com")) (uuid)) (defmethod accept-spec 'clojure.core/uri? [_ _ _ _] {:type :string :format :uri}) bigdec ? ( fmap # ( BigDecimal / valueOf % ) ( double * { : infinite ? false : NaN ? false } ) ) (defmethod accept-spec 'clojure.core/decimal? [_ _ _ _] {:type :double}) ; inst? (fmap #(java.util.Date. %) ; (large-integer)) (defmethod accept-spec 'clojure.core/inst? [_ _ _ _] {:type :string :format :date-time}) seqable ? ( one - of [ ( return nil ) ; (list simple) ; (vector simple) ; (map simple simple) ; (set simple) ; (string-alphanumeric)]) (defmethod accept-spec 'clojure.core/seqable? [_ _ _ _] {:type :seqable}) ; indexed? (vector simple) (defmethod accept-spec 'clojure.core/map? [_ _ _ _] {:type :map}) ; vector? (vector simple) (defmethod accept-spec 'clojure.core/vector? [_ _ _ _] {:type :vector}) ; list? (list simple) (defmethod accept-spec 'clojure.core/list? [_ _ _ _] {:type :list}) ; seq? (list simple) (defmethod accept-spec 'clojure.core/seq? [_ _ _ _] {:type :seq}) ; char? (char) (defmethod accept-spec 'clojure.core/char? [_ _ _ _] {:type :char}) ; set? (set simple) (defmethod accept-spec 'clojure.core/set? [_ _ _ _] {:type :set}) ; nil? (return nil) (defmethod accept-spec 'clojure.core/nil? [_ _ _ _] {:type :nil}) (defmethod accept-spec 'clojure.core/some? [_ _ _ _] {:type :any}) ; false? (return false) (defmethod accept-spec 'clojure.core/false? [_ _ _ _] {:type :boolean :value false}) ; true? (return true) (defmethod accept-spec 'clojure.core/true? [_ _ _ _] {:type :boolean :value true}) zero ? ( return 0 ) (defmethod accept-spec 'clojure.core/zero? [_ _ _ _] {:type :number :value 0}) coll ? ( one - of [ ( map simple simple ) ; (list simple) ; (vector simple) ; (set simple)]) (defmethod accept-spec 'clojure.core/coll? [_ _ _ _] {:type :coll}) ; empty? (elements [nil '() [] {} #{}]) (defmethod accept-spec 'clojure.core/empty? [_ _ _ _] {:type :seq :max-items 0 :min-items 0}) associative ? ( one - of [ ( map simple simple ) ( vector simple ) ] ) (defmethod accept-spec 'clojure.core/associative? [_ _ _ _] {:type :associative}) sequential ? ( one - of [ ( list simple ) ( vector simple ) ] ) (defmethod accept-spec 'clojure.core/sequential? [_ _ _ _] {:type :sequential}) ; ratio? (such-that ratio? (ratio)) (defmethod accept-spec 'clojure.core/ratio? [_ _ _ _] {:type :ratio}) (defmethod accept-spec ::visitor/set [dispatch spec children _] {:enum children}) (defn- maybe-with-title [schema spec] (if-let [title (st/spec-name spec)] (assoc schema :title (impl/qualified-name title)) schema)) (defmethod accept-spec 'clojure.spec.alpha/keys [_ spec children _] (let [{:keys [req req-un opt opt-un]} (impl/parse-keys (impl/extract-form spec)) names-un (concat req-un opt-un) names (map impl/qualified-name (concat req opt)) required (map impl/qualified-name req) all-required (not-empty (concat required req-un))] (maybe-with-title (merge {:type :map :keys (zipmap (concat names names-un) children)} (when all-required {:required (vec all-required)})) spec))) (defmethod accept-spec 'clojure.spec.alpha/or [_ _ children _] {:any-of children}) (defmethod accept-spec 'clojure.spec.alpha/and [_ _ children _] (simplify-all-of {:all-of children})) (defmethod accept-spec 'clojure.spec.alpha/merge [_ _ children _] {:type :map :keys (apply merge (map :keys children)) :required (into [] (reduce into (sorted-set) (map :required children)))}) (defmethod accept-spec 'clojure.spec.alpha/every [_ spec children _] (let [form (impl/extract-form spec) {:keys [type]} (parse/parse-spec form)] (case type :map (maybe-with-title {:type :map, :additional-properties (impl/unwrap children)} spec) :set {:type :set, :uniqueItems true, :items (impl/unwrap children)} :vector {:type :vector, :items (impl/unwrap children)}))) (defmethod accept-spec 'clojure.spec.alpha/every-kv [_ spec children _] (maybe-with-title {:type :map, :additional-properties (second children)} spec)) (defmethod accept-spec ::visitor/map-of [_ spec children _] (maybe-with-title {:type :map, :additional-properties (second children)} spec)) (defmethod accept-spec ::visitor/set-of [_ _ children _] {:type :set, :items (impl/unwrap children), :uniqueItems true}) (defmethod accept-spec ::visitor/vector-of [_ _ children _] {:type :vector, :items (impl/unwrap children)}) (defmethod accept-spec 'clojure.spec.alpha/* [_ _ children _] {:type :sequential :items (impl/unwrap children)}) (defmethod accept-spec 'clojure.spec.alpha/+ [_ _ children _] {:type :sequential :items (impl/unwrap children) :minItems 1}) (defmethod accept-spec 'clojure.spec.alpha/? [_ _ children _] {:type :sequential :items (impl/unwrap children) :minItems 0}) (defmethod accept-spec 'clojure.spec.alpha/alt [_ _ children _] {:any-of children}) (defmethod accept-spec 'clojure.spec.alpha/cat [_ _ children _] {:type :sequential :items {:any-of children}}) ; & (defmethod accept-spec 'clojure.spec.alpha/tuple [_ _ children _] {:type :sequential :items children}) ; keys* (defmethod accept-spec 'clojure.spec.alpha/nilable [_ _ children _] (assoc (impl/unwrap children) :nilable? true)) this is just a function in clojure.spec ? (defmethod accept-spec 'clojure.spec.alpha/int-in-range? [_ spec _ _] (let [[_ minimum maximum _] (impl/strip-fn-if-needed spec)] {:minimum minimum :maximum maximum})) (defmethod accept-spec ::visitor/spec [_ spec children _] (let [[_ data] (impl/extract-form spec) json-schema-meta (reduce-kv (fn [acc k v] (if (= "json-schema" (namespace k)) (assoc acc (keyword (name k)) v) acc)) {} (into {} data)) extra-info (-> data (select-keys [:name :description]) (set/rename-keys {:name :title}))] (merge (impl/unwrap children) extra-info json-schema-meta))) (defmethod accept-spec ::default [_ _ _ _] {:type :unknown}) (defn describe-api [] (->> @api/available-requests (remove (fn [[request {:keys [binary?]}]] binary?)) (utils/mapm (fn [[request {:keys [spec doc]}]] [request {:spec (when spec (->> (data-spec/spec (keyword "api" (name request)) spec) (transform))) :doc doc}])))) (api/register-endpoint! ::api.describe (fn [_ _] (describe-api))) (api/register-endpoint! ::api.generate-params {:spec {:request ::api/keyword}} (fn [{{:keys [request]} :params} _] (when-let [{:keys [spec]} (get @api/available-requests request)] (spec/def ::temp (data-spec/spec (keyword "api" (name request)) spec)) (gen/generate (spec/gen ::temp)))))
null
https://raw.githubusercontent.com/JoelSanchez/ventas/dc8fc8ff9f63dfc8558ecdaacfc4983903b8e9a1/src/clj/ventas/server/api/description.clj
clojure
some? (such-that some? (any-printable)) integer? (large-integer) int? (large-integer) pos-int? (large-integer* {:min 1}) nat-int? (large-integer* {:min 0}) float? (double) double? (double) boolean? (boolean) string? (string-alphanumeric) keyword? (keyword-ns) simple-keyword? (keyword) qualified-keyword? (such-that qualified? (keyword-ns)) symbol? (symbol-ns) simple-symbol? (symbol) qualified-symbol? (such-that qualified? (symbol-ns)) uuid? (uuid) uri? (fmap #(java.net.URI/create (str "http://" % ".com")) (uuid)) inst? (fmap #(java.util.Date. %) (large-integer)) (list simple) (vector simple) (map simple simple) (set simple) (string-alphanumeric)]) indexed? (vector simple) vector? (vector simple) list? (list simple) seq? (list simple) char? (char) set? (set simple) nil? (return nil) false? (return false) true? (return true) (list simple) (vector simple) (set simple)]) empty? (elements [nil '() [] {} #{}]) ratio? (such-that ratio? (ratio)) & keys*
(ns ventas.server.api.description (:require [clojure.set :as set] [clojure.spec.alpha :as spec] [clojure.test.check.generators :as gen] [spec-tools.core :as st] [spec-tools.data-spec :as data-spec] [spec-tools.impl :as impl] [spec-tools.parse :as parse] [spec-tools.visitor :as visitor] [ventas.server.api :as api] [ventas.utils :as utils])) (defn- only-entry? [key a-map] (= [key] (keys a-map))) (defn- simplify-all-of [spec] (let [subspecs (->> (:all-of spec) (remove empty?))] (cond (empty? subspecs) (dissoc spec :all-of) (and (= (count subspecs) 1) (only-entry? :all-of spec)) (first subspecs) :else (assoc spec :all-of subspecs)))) (defn- spec-dispatch [dispatch _ _ _] dispatch) (defmulti accept-spec spec-dispatch :default ::default) (defn transform ([spec] (transform spec nil)) ([spec options] (visitor/visit spec accept-spec options))) any ? ( one - of [ ( return nil ) ( any - printable ) ] ) (defmethod accept-spec 'clojure.core/any? [_ _ _ _] {}) (defmethod accept-spec 'clojure.core/some? [_ _ _ _] {}) number ? ( one - of [ ( large - integer ) ( double ) ] ) (defmethod accept-spec 'clojure.core/number? [_ _ _ _] {:type :number}) (defmethod accept-spec 'clojure.core/pos? [_ _ _ _] {:minimum 0 :exclusive-minimum true}) (defmethod accept-spec 'clojure.core/neg? [_ _ _ _] {:maximum 0 :exclusive-maximum true}) (defmethod accept-spec 'clojure.core/integer? [_ _ _ _] {:type :number}) (defmethod accept-spec 'clojure.core/int? [_ _ _ _] {:type :number}) (defmethod accept-spec 'clojure.core/pos-int? [_ _ _ _] {:type :number :minimum 1}) neg - int ? ( large - integer * { : -1 } ) (defmethod accept-spec 'clojure.core/neg-int? [_ _ _ _] {:type :number :maximum -1}) (defmethod accept-spec 'clojure.core/nat-int? [_ _ _ _] {:type :number :minimum 0}) (defmethod accept-spec 'clojure.core/float? [_ _ _ _] {:type :float}) (defmethod accept-spec 'clojure.core/double? [_ _ _ _] {:type :double}) (defmethod accept-spec 'clojure.core/boolean? [_ _ _ _] {:type :boolean}) (defmethod accept-spec 'clojure.core/string? [_ _ _ _] {:type :string}) ident ? ( one - of [ ( keyword - ns ) ( symbol - ns ) ] ) (defmethod accept-spec 'clojure.core/ident? [_ _ _ _] {:type :ident}) simple - ident ? ( one - of [ ( keyword ) ( symbol ) ] ) (defmethod accept-spec 'clojure.core/simple-ident? [_ _ _ _] {:type :ident :qualified? false}) qualified - ident ? ( such - that qualified ? ( one - of [ ( keyword - ns ) ( symbol - ns ) ] ) ) (defmethod accept-spec 'clojure.core/qualified-ident? [_ _ _ _] {:type :ident :qualified? true}) (defmethod accept-spec 'clojure.core/keyword? [_ _ _ _] {:type :keyword}) (defmethod accept-spec 'clojure.core/simple-keyword? [_ _ _ _] {:type :keyword :qualified? false}) (defmethod accept-spec 'clojure.core/qualified-keyword? [_ _ _ _] {:type :keyword :qualified? true}) (defmethod accept-spec 'clojure.core/symbol? [_ _ _ _] {:type :symbol}) (defmethod accept-spec 'clojure.core/simple-symbol? [_ _ _ _] {:type :symbol :qualified? false}) (defmethod accept-spec 'clojure.core/qualified-symbol? [_ _ _ _] {:type :symbol :qualified? true}) (defmethod accept-spec 'clojure.core/uuid? [_ _ _ _] {:type :string :format :uuid}) (defmethod accept-spec 'clojure.core/uri? [_ _ _ _] {:type :string :format :uri}) bigdec ? ( fmap # ( BigDecimal / valueOf % ) ( double * { : infinite ? false : NaN ? false } ) ) (defmethod accept-spec 'clojure.core/decimal? [_ _ _ _] {:type :double}) (defmethod accept-spec 'clojure.core/inst? [_ _ _ _] {:type :string :format :date-time}) seqable ? ( one - of [ ( return nil ) (defmethod accept-spec 'clojure.core/seqable? [_ _ _ _] {:type :seqable}) (defmethod accept-spec 'clojure.core/map? [_ _ _ _] {:type :map}) (defmethod accept-spec 'clojure.core/vector? [_ _ _ _] {:type :vector}) (defmethod accept-spec 'clojure.core/list? [_ _ _ _] {:type :list}) (defmethod accept-spec 'clojure.core/seq? [_ _ _ _] {:type :seq}) (defmethod accept-spec 'clojure.core/char? [_ _ _ _] {:type :char}) (defmethod accept-spec 'clojure.core/set? [_ _ _ _] {:type :set}) (defmethod accept-spec 'clojure.core/nil? [_ _ _ _] {:type :nil}) (defmethod accept-spec 'clojure.core/some? [_ _ _ _] {:type :any}) (defmethod accept-spec 'clojure.core/false? [_ _ _ _] {:type :boolean :value false}) (defmethod accept-spec 'clojure.core/true? [_ _ _ _] {:type :boolean :value true}) zero ? ( return 0 ) (defmethod accept-spec 'clojure.core/zero? [_ _ _ _] {:type :number :value 0}) coll ? ( one - of [ ( map simple simple ) (defmethod accept-spec 'clojure.core/coll? [_ _ _ _] {:type :coll}) (defmethod accept-spec 'clojure.core/empty? [_ _ _ _] {:type :seq :max-items 0 :min-items 0}) associative ? ( one - of [ ( map simple simple ) ( vector simple ) ] ) (defmethod accept-spec 'clojure.core/associative? [_ _ _ _] {:type :associative}) sequential ? ( one - of [ ( list simple ) ( vector simple ) ] ) (defmethod accept-spec 'clojure.core/sequential? [_ _ _ _] {:type :sequential}) (defmethod accept-spec 'clojure.core/ratio? [_ _ _ _] {:type :ratio}) (defmethod accept-spec ::visitor/set [dispatch spec children _] {:enum children}) (defn- maybe-with-title [schema spec] (if-let [title (st/spec-name spec)] (assoc schema :title (impl/qualified-name title)) schema)) (defmethod accept-spec 'clojure.spec.alpha/keys [_ spec children _] (let [{:keys [req req-un opt opt-un]} (impl/parse-keys (impl/extract-form spec)) names-un (concat req-un opt-un) names (map impl/qualified-name (concat req opt)) required (map impl/qualified-name req) all-required (not-empty (concat required req-un))] (maybe-with-title (merge {:type :map :keys (zipmap (concat names names-un) children)} (when all-required {:required (vec all-required)})) spec))) (defmethod accept-spec 'clojure.spec.alpha/or [_ _ children _] {:any-of children}) (defmethod accept-spec 'clojure.spec.alpha/and [_ _ children _] (simplify-all-of {:all-of children})) (defmethod accept-spec 'clojure.spec.alpha/merge [_ _ children _] {:type :map :keys (apply merge (map :keys children)) :required (into [] (reduce into (sorted-set) (map :required children)))}) (defmethod accept-spec 'clojure.spec.alpha/every [_ spec children _] (let [form (impl/extract-form spec) {:keys [type]} (parse/parse-spec form)] (case type :map (maybe-with-title {:type :map, :additional-properties (impl/unwrap children)} spec) :set {:type :set, :uniqueItems true, :items (impl/unwrap children)} :vector {:type :vector, :items (impl/unwrap children)}))) (defmethod accept-spec 'clojure.spec.alpha/every-kv [_ spec children _] (maybe-with-title {:type :map, :additional-properties (second children)} spec)) (defmethod accept-spec ::visitor/map-of [_ spec children _] (maybe-with-title {:type :map, :additional-properties (second children)} spec)) (defmethod accept-spec ::visitor/set-of [_ _ children _] {:type :set, :items (impl/unwrap children), :uniqueItems true}) (defmethod accept-spec ::visitor/vector-of [_ _ children _] {:type :vector, :items (impl/unwrap children)}) (defmethod accept-spec 'clojure.spec.alpha/* [_ _ children _] {:type :sequential :items (impl/unwrap children)}) (defmethod accept-spec 'clojure.spec.alpha/+ [_ _ children _] {:type :sequential :items (impl/unwrap children) :minItems 1}) (defmethod accept-spec 'clojure.spec.alpha/? [_ _ children _] {:type :sequential :items (impl/unwrap children) :minItems 0}) (defmethod accept-spec 'clojure.spec.alpha/alt [_ _ children _] {:any-of children}) (defmethod accept-spec 'clojure.spec.alpha/cat [_ _ children _] {:type :sequential :items {:any-of children}}) (defmethod accept-spec 'clojure.spec.alpha/tuple [_ _ children _] {:type :sequential :items children}) (defmethod accept-spec 'clojure.spec.alpha/nilable [_ _ children _] (assoc (impl/unwrap children) :nilable? true)) this is just a function in clojure.spec ? (defmethod accept-spec 'clojure.spec.alpha/int-in-range? [_ spec _ _] (let [[_ minimum maximum _] (impl/strip-fn-if-needed spec)] {:minimum minimum :maximum maximum})) (defmethod accept-spec ::visitor/spec [_ spec children _] (let [[_ data] (impl/extract-form spec) json-schema-meta (reduce-kv (fn [acc k v] (if (= "json-schema" (namespace k)) (assoc acc (keyword (name k)) v) acc)) {} (into {} data)) extra-info (-> data (select-keys [:name :description]) (set/rename-keys {:name :title}))] (merge (impl/unwrap children) extra-info json-schema-meta))) (defmethod accept-spec ::default [_ _ _ _] {:type :unknown}) (defn describe-api [] (->> @api/available-requests (remove (fn [[request {:keys [binary?]}]] binary?)) (utils/mapm (fn [[request {:keys [spec doc]}]] [request {:spec (when spec (->> (data-spec/spec (keyword "api" (name request)) spec) (transform))) :doc doc}])))) (api/register-endpoint! ::api.describe (fn [_ _] (describe-api))) (api/register-endpoint! ::api.generate-params {:spec {:request ::api/keyword}} (fn [{{:keys [request]} :params} _] (when-let [{:keys [spec]} (get @api/available-requests request)] (spec/def ::temp (data-spec/spec (keyword "api" (name request)) spec)) (gen/generate (spec/gen ::temp)))))
4df042c76ff49215a40a6b28bcaa12759b1b501c3163e8e82987d7f50eb3d922
alura-cursos/datomic-identidades-e-queries
aula3.clj
(ns ecommerce.aula3 (:use clojure.pprint) (:require [datomic.api :as d] [ecommerce.db :as db] [ecommerce.model :as model])) (def conn (db/abre-conexao)) (db/cria-schema conn) (let [computador (model/novo-produto "Computador Novo", "/computador-novo", 2500.10M) celular (model/novo-produto "Celular Caro", "/celular", 888888.10M) calculadora {:produto/nome "Calculadora com 4 operações"} celular-barato (model/novo-produto "Celular Barato", "/celular-barato", 0.1M)] (d/transact conn [computador, celular, calculadora, celular-barato])) (pprint (db/todos-os-produtos (d/db conn))) (pprint (db/todos-os-produtos-por-slug-fixo (d/db conn))) (pprint (db/todos-os-produtos-por-slug (d/db conn) "/computador-novo")) (pprint (db/todos-os-slugs (d/db conn))) (pprint (count (db/todos-os-produtos-por-preco (d/db conn)))) (pprint (db/todos-os-produtos-por-preco (d/db conn))) (db/apaga-banco)
null
https://raw.githubusercontent.com/alura-cursos/datomic-identidades-e-queries/2c14e40f02ae3ac2ebd39d2a1d07fbdc87526052/aula0/ecommerce/src/ecommerce/aula3.clj
clojure
(ns ecommerce.aula3 (:use clojure.pprint) (:require [datomic.api :as d] [ecommerce.db :as db] [ecommerce.model :as model])) (def conn (db/abre-conexao)) (db/cria-schema conn) (let [computador (model/novo-produto "Computador Novo", "/computador-novo", 2500.10M) celular (model/novo-produto "Celular Caro", "/celular", 888888.10M) calculadora {:produto/nome "Calculadora com 4 operações"} celular-barato (model/novo-produto "Celular Barato", "/celular-barato", 0.1M)] (d/transact conn [computador, celular, calculadora, celular-barato])) (pprint (db/todos-os-produtos (d/db conn))) (pprint (db/todos-os-produtos-por-slug-fixo (d/db conn))) (pprint (db/todos-os-produtos-por-slug (d/db conn) "/computador-novo")) (pprint (db/todos-os-slugs (d/db conn))) (pprint (count (db/todos-os-produtos-por-preco (d/db conn)))) (pprint (db/todos-os-produtos-por-preco (d/db conn))) (db/apaga-banco)
690364ebf189d1d9e8b2e63b131b79e412f62125c9f7f634d1e75b065ea16614
dreixel/syb
Schemes.hs
# LANGUAGE RankNTypes , ScopedTypeVariables , CPP # ----------------------------------------------------------------------------- -- | -- Module : Data.Generics.Schemes Copyright : ( c ) The University of Glasgow , CWI 2001 - -2003 -- License : BSD-style (see the LICENSE file) -- Maintainer : -- Stability : experimental -- Portability : non-portable (local universal quantification) -- \"Scrap your boilerplate\ " --- Generic programming in Haskell -- See <>. The present module -- provides frequently used generic traversal schemes. -- ----------------------------------------------------------------------------- module Data.Generics.Schemes ( everywhere, everywhere', everywhereBut, everywhereM, somewhere, everything, everythingBut, everythingWithContext, listify, something, synthesize, gsize, glength, gdepth, gcount, gnodecount, gtypecount, gfindtype ) where ------------------------------------------------------------------------------ #ifdef __HADDOCK__ import Prelude #endif import Data.Data import Data.Generics.Aliases import Control.Monad -- | Apply a transformation everywhere in bottom-up manner everywhere :: (forall a. Data a => a -> a) -> (forall a. Data a => a -> a) -- Use gmapT to recurse into immediate subterms; -- recall: gmapT preserves the outermost constructor; -- post-process recursively transformed result via f -- everywhere f = go where go :: forall a. Data a => a -> a go = f . gmapT go -- | Apply a transformation everywhere in top-down manner everywhere' :: (forall a. Data a => a -> a) -> (forall a. Data a => a -> a) -- Arguments of (.) are flipped compared to everywhere everywhere' f = go where go :: forall a. Data a => a -> a go = gmapT go . f -- | Variation on everywhere with an extra stop condition everywhereBut :: GenericQ Bool -> GenericT -> GenericT -- Guarded to let traversal cease if predicate q holds for x everywhereBut q f = go where go :: GenericT go x | q x = x | otherwise = f (gmapT go x) | Monadic variation on everywhere everywhereM :: forall m. Monad m => GenericM m -> GenericM m -- Bottom-up order is also reflected in order of do-actions everywhereM f = go where go :: GenericM m go x = do x' <- gmapM go x f x' -- | Apply a monadic transformation at least somewhere somewhere :: forall m. MonadPlus m => GenericM m -> GenericM m -- We try "f" in top-down manner, but descent into "x" when we fail -- at the root of the term. The transformation fails if "f" fails -- everywhere, say succeeds nowhere. -- somewhere f = go where go :: GenericM m go x = f x `mplus` gmapMp go x -- | Summarise all nodes in top-down, left-to-right order everything :: forall r. (r -> r -> r) -> GenericQ r -> GenericQ r -- Apply f to x to summarise top-level node; -- use gmapQ to recurse into immediate subterms; -- use ordinary foldl to reduce list of intermediate results -- everything k f = go where go :: GenericQ r go x = foldl k (f x) (gmapQ go x) -- | Variation of "everything" with an added stop condition everythingBut :: forall r. (r -> r -> r) -> GenericQ (r, Bool) -> GenericQ r everythingBut k f = go where go :: GenericQ r go x = let (v, stop) = f x in if stop then v else foldl k v (gmapQ go x) -- | Summarise all nodes in top-down, left-to-right order, carrying some state -- down the tree during the computation, but not left-to-right to siblings. everythingWithContext :: forall s r. s -> (r -> r -> r) -> GenericQ (s -> (r, s)) -> GenericQ r everythingWithContext s0 f q = go s0 where go :: s -> GenericQ r go s x = foldl f r (gmapQ (go s') x) where (r, s') = q x s -- | Get a list of all entities that meet a predicate listify :: Typeable r => (r -> Bool) -> GenericQ [r] listify p = everything (++) ([] `mkQ` (\x -> if p x then [x] else [])) -- | Look up a subterm by means of a maybe-typed filter something :: GenericQ (Maybe u) -> GenericQ (Maybe u) -- "something" can be defined in terms of "everything" -- when a suitable "choice" operator is used for reduction -- something = everything orElse -- | Bottom-up synthesis of a data structure; -- 1st argument z is the initial element for the synthesis; 2nd argument o is for reduction of results from subterms ; 3rd argument f updates the synthesised data according to the given term -- synthesize :: forall s t. s -> (t -> s -> s) -> GenericQ (s -> t) -> GenericQ t synthesize z o f = go where go :: GenericQ t go x = f x (foldr o z (gmapQ go x)) -- | Compute size of an arbitrary data structure gsize :: Data a => a -> Int gsize t = 1 + sum (gmapQ gsize t) -- | Count the number of immediate subterms of the given term glength :: GenericQ Int glength = length . gmapQ (const ()) -- | Determine depth of the given term gdepth :: GenericQ Int gdepth = (+) 1 . foldr max 0 . gmapQ gdepth -- | Determine the number of all suitable nodes in a given term gcount :: GenericQ Bool -> GenericQ Int gcount p = everything (+) (\x -> if p x then 1 else 0) -- | Determine the number of all nodes in a given term gnodecount :: GenericQ Int gnodecount = gcount (const True) -- | Determine the number of nodes of a given type in a given term gtypecount :: Typeable a => a -> GenericQ Int gtypecount (_::a) = gcount (False `mkQ` (\(_::a) -> True)) -- | Find (unambiguously) an immediate subterm of a given type gfindtype :: (Data x, Typeable y) => x -> Maybe y gfindtype = singleton . foldl unJust [] . gmapQ (Nothing `mkQ` Just) where unJust l (Just x) = x:l unJust l Nothing = l singleton [s] = Just s singleton _ = Nothing
null
https://raw.githubusercontent.com/dreixel/syb/f741a437f18768f71586eeb47ffb43c0915f331b/src/Data/Generics/Schemes.hs
haskell
--------------------------------------------------------------------------- | Module : Data.Generics.Schemes License : BSD-style (see the LICENSE file) Stability : experimental Portability : non-portable (local universal quantification) - Generic programming in Haskell See <>. The present module provides frequently used generic traversal schemes. --------------------------------------------------------------------------- ---------------------------------------------------------------------------- | Apply a transformation everywhere in bottom-up manner Use gmapT to recurse into immediate subterms; recall: gmapT preserves the outermost constructor; post-process recursively transformed result via f | Apply a transformation everywhere in top-down manner Arguments of (.) are flipped compared to everywhere | Variation on everywhere with an extra stop condition Guarded to let traversal cease if predicate q holds for x Bottom-up order is also reflected in order of do-actions | Apply a monadic transformation at least somewhere We try "f" in top-down manner, but descent into "x" when we fail at the root of the term. The transformation fails if "f" fails everywhere, say succeeds nowhere. | Summarise all nodes in top-down, left-to-right order Apply f to x to summarise top-level node; use gmapQ to recurse into immediate subterms; use ordinary foldl to reduce list of intermediate results | Variation of "everything" with an added stop condition | Summarise all nodes in top-down, left-to-right order, carrying some state down the tree during the computation, but not left-to-right to siblings. | Get a list of all entities that meet a predicate | Look up a subterm by means of a maybe-typed filter "something" can be defined in terms of "everything" when a suitable "choice" operator is used for reduction | Bottom-up synthesis of a data structure; 1st argument z is the initial element for the synthesis; | Compute size of an arbitrary data structure | Count the number of immediate subterms of the given term | Determine depth of the given term | Determine the number of all suitable nodes in a given term | Determine the number of all nodes in a given term | Determine the number of nodes of a given type in a given term | Find (unambiguously) an immediate subterm of a given type
# LANGUAGE RankNTypes , ScopedTypeVariables , CPP # Copyright : ( c ) The University of Glasgow , CWI 2001 - -2003 Maintainer : module Data.Generics.Schemes ( everywhere, everywhere', everywhereBut, everywhereM, somewhere, everything, everythingBut, everythingWithContext, listify, something, synthesize, gsize, glength, gdepth, gcount, gnodecount, gtypecount, gfindtype ) where #ifdef __HADDOCK__ import Prelude #endif import Data.Data import Data.Generics.Aliases import Control.Monad everywhere :: (forall a. Data a => a -> a) -> (forall a. Data a => a -> a) everywhere f = go where go :: forall a. Data a => a -> a go = f . gmapT go everywhere' :: (forall a. Data a => a -> a) -> (forall a. Data a => a -> a) everywhere' f = go where go :: forall a. Data a => a -> a go = gmapT go . f everywhereBut :: GenericQ Bool -> GenericT -> GenericT everywhereBut q f = go where go :: GenericT go x | q x = x | otherwise = f (gmapT go x) | Monadic variation on everywhere everywhereM :: forall m. Monad m => GenericM m -> GenericM m everywhereM f = go where go :: GenericM m go x = do x' <- gmapM go x f x' somewhere :: forall m. MonadPlus m => GenericM m -> GenericM m somewhere f = go where go :: GenericM m go x = f x `mplus` gmapMp go x everything :: forall r. (r -> r -> r) -> GenericQ r -> GenericQ r everything k f = go where go :: GenericQ r go x = foldl k (f x) (gmapQ go x) everythingBut :: forall r. (r -> r -> r) -> GenericQ (r, Bool) -> GenericQ r everythingBut k f = go where go :: GenericQ r go x = let (v, stop) = f x in if stop then v else foldl k v (gmapQ go x) everythingWithContext :: forall s r. s -> (r -> r -> r) -> GenericQ (s -> (r, s)) -> GenericQ r everythingWithContext s0 f q = go s0 where go :: s -> GenericQ r go s x = foldl f r (gmapQ (go s') x) where (r, s') = q x s listify :: Typeable r => (r -> Bool) -> GenericQ [r] listify p = everything (++) ([] `mkQ` (\x -> if p x then [x] else [])) something :: GenericQ (Maybe u) -> GenericQ (Maybe u) something = everything orElse 2nd argument o is for reduction of results from subterms ; 3rd argument f updates the synthesised data according to the given term synthesize :: forall s t. s -> (t -> s -> s) -> GenericQ (s -> t) -> GenericQ t synthesize z o f = go where go :: GenericQ t go x = f x (foldr o z (gmapQ go x)) gsize :: Data a => a -> Int gsize t = 1 + sum (gmapQ gsize t) glength :: GenericQ Int glength = length . gmapQ (const ()) gdepth :: GenericQ Int gdepth = (+) 1 . foldr max 0 . gmapQ gdepth gcount :: GenericQ Bool -> GenericQ Int gcount p = everything (+) (\x -> if p x then 1 else 0) gnodecount :: GenericQ Int gnodecount = gcount (const True) gtypecount :: Typeable a => a -> GenericQ Int gtypecount (_::a) = gcount (False `mkQ` (\(_::a) -> True)) gfindtype :: (Data x, Typeable y) => x -> Maybe y gfindtype = singleton . foldl unJust [] . gmapQ (Nothing `mkQ` Just) where unJust l (Just x) = x:l unJust l Nothing = l singleton [s] = Just s singleton _ = Nothing
9b9005c858353b2b4e837d28e7bb80facca00c05b949e4cb2152a03237cc136d
jkvor/redo
redo_uri.erl
Copyright ( c ) 2011 < > %% %% Permission is hereby granted, free of charge, to any person %% obtaining a copy of this software and associated documentation files ( the " Software " ) , to deal in the Software without %% restriction, including without limitation the rights to use, %% copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software , and to permit persons to whom the %% Software is furnished to do so, subject to the following %% conditions: %% %% The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software . %% THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , %% EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES %% OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND %% NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT %% HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, %% WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING %% FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR %% OTHER DEALINGS IN THE SOFTWARE. -module(redo_uri). -export([parse/1]). -spec parse(binary() | list()) -> list(). parse(Url) when is_binary(Url) -> parse(binary_to_list(Url)); parse("redis://" ++ Rest) -> parse(Rest); parse(":" ++ Rest) -> parse(Rest); % redis://:password@localhost:6379/1 parse(Url) when is_list(Url) -> {Pass, Rest1} = pass(Url), {Host, Rest2} = host(Rest1), {Port, Db} = port(Rest2), [{host, Host} || Host =/= ""] ++ [{port, Port} || Port =/= ""] ++ [{pass, Pass} || Pass =/= ""] ++ [{db, Db} || Db =/= ""]. pass("") -> {"", ""}; pass(Url) -> case string:tokens(Url, "@") of [Rest] -> {"", Rest}; [Pass, Rest] -> {Pass, Rest}; [Pass | Rest] -> {Pass, string:join(Rest, "@")} end. host("") -> {"", ""}; host(Url) -> case string:tokens(Url, ":") of [Rest] -> case string:tokens(Rest, "/") of [Host] -> {Host, ""}; [Host, Rest1] -> {Host, "/" ++ Rest1}; [Host | Rest1] -> {Host, string:join(Rest1, "/")} end; [Host, Rest] -> {Host, Rest}; [Host | Rest] -> {Host, string:join(Rest, ":")} end. port("") -> {"", ""}; port("/" ++ Rest) -> {"", Rest}; port(Url) -> case string:tokens(Url, "/") of [Port] -> {list_to_integer(Port), ""}; [Port, Rest] -> {list_to_integer(Port), Rest}; [Port | Rest] -> {list_to_integer(Port), string:join(Rest, "/")} end.
null
https://raw.githubusercontent.com/jkvor/redo/7c7eaef4cd65271e2fc4ea88587e848407cf0762/src/redo_uri.erl
erlang
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. redis://:password@localhost:6379/1
Copyright ( c ) 2011 < > files ( the " Software " ) , to deal in the Software without copies of the Software , and to permit persons to whom the included in all copies or substantial portions of the Software . THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , -module(redo_uri). -export([parse/1]). -spec parse(binary() | list()) -> list(). parse(Url) when is_binary(Url) -> parse(binary_to_list(Url)); parse("redis://" ++ Rest) -> parse(Rest); parse(":" ++ Rest) -> parse(Rest); parse(Url) when is_list(Url) -> {Pass, Rest1} = pass(Url), {Host, Rest2} = host(Rest1), {Port, Db} = port(Rest2), [{host, Host} || Host =/= ""] ++ [{port, Port} || Port =/= ""] ++ [{pass, Pass} || Pass =/= ""] ++ [{db, Db} || Db =/= ""]. pass("") -> {"", ""}; pass(Url) -> case string:tokens(Url, "@") of [Rest] -> {"", Rest}; [Pass, Rest] -> {Pass, Rest}; [Pass | Rest] -> {Pass, string:join(Rest, "@")} end. host("") -> {"", ""}; host(Url) -> case string:tokens(Url, ":") of [Rest] -> case string:tokens(Rest, "/") of [Host] -> {Host, ""}; [Host, Rest1] -> {Host, "/" ++ Rest1}; [Host | Rest1] -> {Host, string:join(Rest1, "/")} end; [Host, Rest] -> {Host, Rest}; [Host | Rest] -> {Host, string:join(Rest, ":")} end. port("") -> {"", ""}; port("/" ++ Rest) -> {"", Rest}; port(Url) -> case string:tokens(Url, "/") of [Port] -> {list_to_integer(Port), ""}; [Port, Rest] -> {list_to_integer(Port), Rest}; [Port | Rest] -> {list_to_integer(Port), string:join(Rest, "/")} end.
468ad1214eceb833555c065d09987d3232dd22cfbec8636f83235cc2637a938e
AppMini/todoMini
dev.cljs
(ns ^:figwheel-no-load omgnata.dev (:require [omgnata.core :as core] [figwheel.client :as figwheel :include-macros true])) (enable-console-print!) (figwheel/watch-and-reload :websocket-url "ws:3449/figwheel-ws" :jsload-callback core/mount-root) (core/init!)
null
https://raw.githubusercontent.com/AppMini/todoMini/0c0d67b4f9ed173e6c1a5c68ca7f9fb7a570a162/env/dev/cljs/omgnata/dev.cljs
clojure
(ns ^:figwheel-no-load omgnata.dev (:require [omgnata.core :as core] [figwheel.client :as figwheel :include-macros true])) (enable-console-print!) (figwheel/watch-and-reload :websocket-url "ws:3449/figwheel-ws" :jsload-callback core/mount-root) (core/init!)
37a6a5db7b82e989e789fd0b4689f66596fccf55ed25c39e9e993aae64d01469
charlieg/Sparser
menu-data.lisp
;;; -*- Mode:LISP; Syntax:Common-Lisp; Package:(SPARSER LISP) -*- copyright ( c ) 1994 - 1996 -- all rights reserved ;;; ;;; File: "menu data" ;;; Module: "interface;corpus:" Version : 0.4 January 1996 initiated 1/25/94 v2.3 . 3/10 added Earnings reports , Tipster test articles ;; product announcements. 0.1 ( 5/10 ) put in feature test to ensure a fit to what 's available 0.2 ( 9/12 ) fixed the use of the feature ( 8/9/95 ) removed the ' 1st 15 ' from WN set 0.3 ( 9/5 ) marked almost everything off - bounds unless there 's a ' full corpus ' so that the demos could be controlled . ( 9/15 ) added html 0.4 ( 1/16/95 ) added ern for minimal corpus and changed some of there names (in-package :sparser) #| We spell out here which document streams should go onto the corpus menu and in what order. |# (defparameter *doc-streams-for-menu* ;; read by Create-the-corpus-menu. The organization is a hierarchy ;; where only the terminals are document streams, the others are ;; labels to use to head the submenus `(("Who's News" (,(document-stream-named '|small test set|) #+:full-corpus,(document-stream-named '|December 1990|) #+:full-corpus,(document-stream-named '|February 1991|))) #+:full-corpus ,(document-stream-named '|sample of Web pages|) #+:full-corpus ,(document-stream-named '|financial panic 9/17/92|) ("Earnings Reports" (,(document-stream-named '|WSJ 1990|) ,(document-stream-named '|London Stock Exchange 1990|) ,(document-stream-named '|from Knowledge Factory|) ,(document-stream-named '|2d set from Knowledge Factory|) ,(document-stream-named '|Web pages from Knowledge Factory|) )) #+:full-corpus ,(document-stream-named '|Tipster test articles|) ,(document-stream-named '|2 product announcements|) #+:full-corpus ,(document-stream-named '|3 long tnm|) ))
null
https://raw.githubusercontent.com/charlieg/Sparser/b9bb7d01d2e40f783f3214fc104062db3d15e608/Sparser/code/s/interface/corpus/menu-data.lisp
lisp
-*- Mode:LISP; Syntax:Common-Lisp; Package:(SPARSER LISP) -*- File: "menu data" Module: "interface;corpus:" product announcements. We spell out here which document streams should go onto the corpus menu and in what order. read by Create-the-corpus-menu. The organization is a hierarchy where only the terminals are document streams, the others are labels to use to head the submenus
copyright ( c ) 1994 - 1996 -- all rights reserved Version : 0.4 January 1996 initiated 1/25/94 v2.3 . 3/10 added Earnings reports , Tipster test articles 0.1 ( 5/10 ) put in feature test to ensure a fit to what 's available 0.2 ( 9/12 ) fixed the use of the feature ( 8/9/95 ) removed the ' 1st 15 ' from WN set 0.3 ( 9/5 ) marked almost everything off - bounds unless there 's a ' full corpus ' so that the demos could be controlled . ( 9/15 ) added html 0.4 ( 1/16/95 ) added ern for minimal corpus and changed some of there names (in-package :sparser) (defparameter *doc-streams-for-menu* `(("Who's News" (,(document-stream-named '|small test set|) #+:full-corpus,(document-stream-named '|December 1990|) #+:full-corpus,(document-stream-named '|February 1991|))) #+:full-corpus ,(document-stream-named '|sample of Web pages|) #+:full-corpus ,(document-stream-named '|financial panic 9/17/92|) ("Earnings Reports" (,(document-stream-named '|WSJ 1990|) ,(document-stream-named '|London Stock Exchange 1990|) ,(document-stream-named '|from Knowledge Factory|) ,(document-stream-named '|2d set from Knowledge Factory|) ,(document-stream-named '|Web pages from Knowledge Factory|) )) #+:full-corpus ,(document-stream-named '|Tipster test articles|) ,(document-stream-named '|2 product announcements|) #+:full-corpus ,(document-stream-named '|3 long tnm|) ))
3fba54aed0dab0e8a96d2f8f3feacf85076717e4b67525582d67e25490219015
fujita-y/digamma
apropos.scm
#!nobacktrace Copyright ( c ) 2004 - 2022 Yoshikatsu Fujita / LittleWing Company Limited . ;;; See LICENSE file for terms and conditions of use. (library (digamma apropos) (export apropos) (import (core) (digamma pregexp)) (define parse-library-name (lambda (name) (define infix #\.) (let ((in (make-string-input-port (symbol->string name))) (out (make-string-output-port))) (put-char out #\() (let loop ((ch (get-char in))) (cond ((eof-object? ch) (put-char out #\)) (get-datum (make-string-input-port (extract-accumulated-string out)))) (else (if (char=? ch infix) (put-char out #\space) (put-char out ch)) (loop (get-char in)))))))) (define symbol<? (lambda (a b) (string<? (symbol->string a) (symbol->string b)))) (define apropos (lambda args (let ((args (map (lambda (arg) (cond ((symbol? arg) (symbol->string arg)) ((string? arg) (pregexp arg)) (else (error 'apropos (format "expected symbol or string, but got ~r" arg) args)))) args)) (ht (make-core-hashtable))) (define match? (lambda (e) (for-all (lambda (arg) (cond ((string? arg) (and (string-contains (symbol->string e) arg) e)) ((list? arg) (and (pregexp-match arg (symbol->string e)) e)) (else #f))) args))) (for-each (lambda (lst) (and (pair? (cdr lst)) (let ((lib-name (car lst)) (exports (cdr lst))) (let ((found (filter match? (map car exports)))) (and (pair? found) (for-each (lambda (e) (core-hashtable-set! ht e (list-sort symbol<? (cons lib-name (core-hashtable-ref ht e '()))))) found)))))) (core-hashtable->alist (scheme-library-exports))) (let ((lst (list-sort (lambda (a b) (symbol<? (car a) (car b))) (core-hashtable->alist ht)))) (let ((col (+ 4 (apply max 0 (map (lambda (e) (string-length (symbol->string (car e)))) lst))))) (for-each (lambda (line) (let ((n (string-length (symbol->string (car line))))) (format #t ";; ~s" (car line)) (put-string (current-output-port) (make-string (- col n) #\space)) (for-each (lambda (e) (format #t " ~s" (parse-library-name e))) (cdr line)) (format #t "~%"))) lst)))))) ) ;[end]
null
https://raw.githubusercontent.com/fujita-y/digamma/58cccd77bd2c208ec58d3cd634cbe65e32b3c7ec/sitelib/digamma/apropos.scm
scheme
See LICENSE file for terms and conditions of use. [end]
#!nobacktrace Copyright ( c ) 2004 - 2022 Yoshikatsu Fujita / LittleWing Company Limited . (library (digamma apropos) (export apropos) (import (core) (digamma pregexp)) (define parse-library-name (lambda (name) (define infix #\.) (let ((in (make-string-input-port (symbol->string name))) (out (make-string-output-port))) (put-char out #\() (let loop ((ch (get-char in))) (cond ((eof-object? ch) (put-char out #\)) (get-datum (make-string-input-port (extract-accumulated-string out)))) (else (if (char=? ch infix) (put-char out #\space) (put-char out ch)) (loop (get-char in)))))))) (define symbol<? (lambda (a b) (string<? (symbol->string a) (symbol->string b)))) (define apropos (lambda args (let ((args (map (lambda (arg) (cond ((symbol? arg) (symbol->string arg)) ((string? arg) (pregexp arg)) (else (error 'apropos (format "expected symbol or string, but got ~r" arg) args)))) args)) (ht (make-core-hashtable))) (define match? (lambda (e) (for-all (lambda (arg) (cond ((string? arg) (and (string-contains (symbol->string e) arg) e)) ((list? arg) (and (pregexp-match arg (symbol->string e)) e)) (else #f))) args))) (for-each (lambda (lst) (and (pair? (cdr lst)) (let ((lib-name (car lst)) (exports (cdr lst))) (let ((found (filter match? (map car exports)))) (and (pair? found) (for-each (lambda (e) (core-hashtable-set! ht e (list-sort symbol<? (cons lib-name (core-hashtable-ref ht e '()))))) found)))))) (core-hashtable->alist (scheme-library-exports))) (let ((lst (list-sort (lambda (a b) (symbol<? (car a) (car b))) (core-hashtable->alist ht)))) (let ((col (+ 4 (apply max 0 (map (lambda (e) (string-length (symbol->string (car e)))) lst))))) (for-each (lambda (line) (let ((n (string-length (symbol->string (car line))))) (format #t ";; ~s" (car line)) (put-string (current-output-port) (make-string (- col n) #\space)) (for-each (lambda (e) (format #t " ~s" (parse-library-name e))) (cdr line)) (format #t "~%"))) lst))))))
81914c1822b516c1b407057a8f7e2e9611096e94f94955715e44ff9aebb8ff40
ocaml-flambda/ocaml-jst
locations_test.ml
(* TEST flags = "-dparsetree" * toplevel *) (* Using a toplevel test and not an expect test, because the locs get shifted by the expect blocks and the output is therefore not stable. *) (* Attributes *) module type S = sig end [@attr payload];; module M = struct end [@attr payload];; type t = int [@attr payload];; 3 [@attr payload];; exception Exn [@@attr payload];; Functors module type F = functor (A : S) (B : S) -> sig end;; module F = functor (A : S) (B : S) -> struct end;; (* with type *) module type S1 = sig type t end;; module type T1 = S1 with type t = int;; module type T1 = S1 with type t := int;; (* Constrained bindings *) let x : int = 3;; let x : type a. a -> a = fun x -> x;; let _ = object method x : type a. a -> a = fun x -> x end;; (* Punning. *) let x contents = { contents };; let x = { contents : int = 3 };; let x contents = { contents : int };; let x = function { contents } -> contents;; let x = function { contents : int } -> contents;; let x = function { contents : int = i } -> i;; let _ = object val foo = 12 method x foo = {< foo >} end ;; (* Local open *) let x = M.{ contents = 3 };; let x = M.[ 3; 4 ];; let x = M.( 3; 4 );; (* Indexing operators *) (* some prerequisites. *) let ( .@() ) x y = x + y let ( .@()<- ) x y z = x + y + z let ( .%.{} ) x y = x + y let ( .%.{}<- ) x y z = x + y + z let ( .%.[] ) x y = x + y let ( .%.[]<- ) x y z = x + y + z;; (* the actual issue *) x.@(4);; x.@(4) <- 4;; x.%.{4};; x.%.{4} <- 4;; x.%.[4];; x.%.[4] <- 4;; Constrained unpacks let f = function (module M : S) -> ();; (* local opens in class and class types *) class c = let open M in object end ;; class type ct = let open M in object end ;; Docstrings (** Some docstring attached to x. *) let x = 42 (** Another docstring attached to x. *) ;; (* No surrounding parentheses for immediate objects *) let x = object method f = 1 end;; let x = object method f = 1 end # f;; let x = Some object method f = 1 end;; let x = Some object method f = 1 end # f;; let f x y z = x in f object method f = 1 end object method f = 1 end # f object end ;; (* Punning of labelled function argument with type constraint *) let g y = let f ~y = y + 1 in f ~(y:int) ;;
null
https://raw.githubusercontent.com/ocaml-flambda/ocaml-jst/5bf2820278c58f6715dcfaf6fa61e09a9b0d8db3/testsuite/tests/parsetree/locations_test.ml
ocaml
TEST flags = "-dparsetree" * toplevel Using a toplevel test and not an expect test, because the locs get shifted by the expect blocks and the output is therefore not stable. Attributes with type Constrained bindings Punning. Local open Indexing operators some prerequisites. the actual issue local opens in class and class types * Some docstring attached to x. * Another docstring attached to x. No surrounding parentheses for immediate objects Punning of labelled function argument with type constraint
module type S = sig end [@attr payload];; module M = struct end [@attr payload];; type t = int [@attr payload];; 3 [@attr payload];; exception Exn [@@attr payload];; Functors module type F = functor (A : S) (B : S) -> sig end;; module F = functor (A : S) (B : S) -> struct end;; module type S1 = sig type t end;; module type T1 = S1 with type t = int;; module type T1 = S1 with type t := int;; let x : int = 3;; let x : type a. a -> a = fun x -> x;; let _ = object method x : type a. a -> a = fun x -> x end;; let x contents = { contents };; let x = { contents : int = 3 };; let x contents = { contents : int };; let x = function { contents } -> contents;; let x = function { contents : int } -> contents;; let x = function { contents : int = i } -> i;; let _ = object val foo = 12 method x foo = {< foo >} end ;; let x = M.{ contents = 3 };; let x = M.[ 3; 4 ];; let x = M.( 3; 4 );; let ( .@() ) x y = x + y let ( .@()<- ) x y z = x + y + z let ( .%.{} ) x y = x + y let ( .%.{}<- ) x y z = x + y + z let ( .%.[] ) x y = x + y let ( .%.[]<- ) x y z = x + y + z;; x.@(4);; x.@(4) <- 4;; x.%.{4};; x.%.{4} <- 4;; x.%.[4];; x.%.[4] <- 4;; Constrained unpacks let f = function (module M : S) -> ();; class c = let open M in object end ;; class type ct = let open M in object end ;; Docstrings let x = 42 ;; let x = object method f = 1 end;; let x = object method f = 1 end # f;; let x = Some object method f = 1 end;; let x = Some object method f = 1 end # f;; let f x y z = x in f object method f = 1 end object method f = 1 end # f object end ;; let g y = let f ~y = y + 1 in f ~(y:int) ;;
176d89dbe9a57dcbd792ece9372fb251a4cccf37cfcff78b4e7a25a81f9c48f1
cl-axon/shop2
decls.lisp
-*- Mode : common - lisp ; package : shop2 ; -*- ;;; Version : MPL 1.1 / GPL 2.0 / LGPL 2.1 ;;; The contents of this file are subject to the Mozilla Public License ;;; Version 1.1 (the "License"); you may not use this file except in ;;; compliance with the License. You may obtain a copy of the License at ;;; / ;;; Software distributed under the License is distributed on an " AS IS " ;;; basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the ;;; License for the specific language governing rights and limitations under ;;; the License. ;;; The Original Code is SHOP2 . ;;; The Initial Developer of the Original Code is the University of Maryland . Portions created by the Initial Developer are Copyright ( C ) 2002,2003 the Initial Developer . All Rights Reserved . ;;; Additional developments made by , . ;;; Portions created by Drs. Goldman and Maraist are Copyright (C) 2004 - 2007 SIFT , LLC . These additions and modifications are also available under the MPL / GPL / LGPL licensing terms . ;;; ;;; ;;; Alternatively, the contents of this file may be used under the terms of either of the GNU General Public License Version 2 or later ( the " GPL " ) , or the GNU Lesser General Public License Version 2.1 or later ( the ;;; "LGPL"), in which case the provisions of the GPL or the LGPL are ;;; applicable instead of those above. If you wish to allow use of your ;;; version of this file only under the terms of either the GPL or the LGPL, ;;; and not to allow others to use your version of this file under the terms of the MPL , indicate your decision by deleting the provisions above and ;;; replace them with the notice and other provisions required by the GPL or ;;; the LGPL. If you do not delete the provisions above, a recipient may use your version of this file under the terms of any one of the MPL , the GPL ;;; or the LGPL. ;;; ---------------------------------------------------------------------- Smart Information Flow Technologies Copyright 2006 - 2007 Unpublished work ;;; ;;; GOVERNMENT PURPOSE RIGHTS ;;; ;;; Contract No. FA8650-06-C-7606, Contractor Name Smart Information Flow Technologies , LLC d / b / a SIFT , LLC Contractor Address 211 N 1st Street , Suite 300 Minneapolis , MN 55401 Expiration Date 5/2/2011 ;;; ;;; The Government's rights to use, modify, reproduce, release, ;;; perform, display, or disclose this software are restricted by paragraph ( b)(2 ) of the Rights in Noncommercial Computer Software and Noncommercial Computer Software Documentation clause contained ;;; in the above identified contract. No restrictions apply after the ;;; expiration date shown above. Any reproduction of the software or ;;; portions thereof marked with this legend must also reproduce the ;;; markings. (in-package :shop2) ;;;------------------------------------------------------------------------------------------------------ ;;; Global Variables ;;;------------------------------------------------------------------------------------------------------ (defvar *all-problems* nil) ; all problems that have been defined (defvar *problem* nil) ;last problem defined (defvar *shop-version* "VERSION STRING") ;;; Many of these should probably be absorbed into the definition of PLANNER ... [ 2006/07/05 : rpg ] (defparameter *internal-time-limit* nil) ; maximum time (in units) for execution (defparameter *internal-time-tag* nil) ; catch tag to throw to when time expires maximum time ( in seconds ) for execution (defparameter *expansions* 0) ; number of task expansions so far (defparameter *plans-found* nil) ; list of plans found so far (defparameter *plan-tree* nil) ; whether to return the tree (defparameter *subtask-parents* nil) ; record of the parents in the tree (defparameter *operator-tasks* nil) ; record of the task atom for operators (defparameter *optimize-cost* nil) ; whether to optimize with branch and bound (defparameter *optimal-plan* 'fail) ; optimal plan found so far (defparameter *optimal-cost* 0) ; cost of *optimal-plan* (defparameter *depth-cutoff* nil) ; maximum allowable depth for SEEK-PLANS default value for VERBOSE in FIND - PLANS (defparameter *which* :first) ; default value for WHICH in FIND-PLANS whether to call GC each time we call SEEK - PLANS (defparameter *pp* t) ; what value to use for *PRINT-PRETTY* (defparameter *tasklist* nil) ; initial task list set to nil (defparameter *protections* nil) ; initial protection list set to nil (defparameter *explanation* nil) ; whether to return explanations (defvar *print-plans*) ; whether to print out the plans we find (defvar *pshort*) ; whether to skip ops that begin with !! when printing plans (defvar *print-stats*) ; whether to print statistics (defparameter *current-plan* nil) ; current plan (defparameter *current-tasks* nil) ; current task (defvar *unifiers-found* nil) ;associated with *PLANS-FOUND* associated with * PLANS - FOUND * [ 2004/09/14 : rpg ] (defvar *hand-steer* nil "This variable will be DYNAMICALLY bound and used to indicate whether the user wishes to choose tasks for planning by hand.") (defvar *leashed* nil "This variable will be DYNAMICALLY bound and it will further constrain the behavior of SHOP2 when we hand-steer it (see *hand-steer*). If *leashed* is NIL, SHOP2 will simply proceed when choosing tasks, if there is no choice, i.e., when there's only one task on the open list, or only one :immediate task. If *leashed* is non-nil, will consult the user even in these cases.") (defvar *break-on-backtrack* nil "If this variable is bound to T, SHOP will enter a break loop upon backtracking.") ;;;------------------------------------------------------------------------------------------------------ Compiler Directives and Macros ;;;------------------------------------------------------------------------------------------------------ #+allegro (top-level:alias "bb" (&optional (val t)) "Set *break-on-backtrack* variable" (setf *break-on-backtrack* val)) It is relatively common practice in Lispworks to use ! as a macro ;;; for :redo. This will really mess up interpretation of operators ;;; in SHOP, since all operators start with "!". Thus, we will turn off macro interpretation of " ! " if we are running Lispworks . see : ;;; #+:lispworks (set-syntax-from-char #\! #\@) ;;;----------------------------------------------------------------------- Had to rewrite backquote macro for MCL so it leaves the structure ;;; alone, then write a function to create the structure later. We're ;;; assuming that "," only appears by itself and not as ",." or ",@". This is a Allegro Common Lisp compatibility hack . ( swm ) #+:MCL (defparameter *blue-light-readtable* (copy-readtable nil)) #+:MCL (set-macro-character #\` #'(lambda (stream char) (declare (ignore char)) (list 'simple-backquote (read stream t nil t ))) nil *blue-light-readtable*) #+:MCL (set-macro-character #\, #'(lambda (stream char) (declare (ignore char)) (list 'bq-comma (read stream t nil t ))) nil *blue-light-readtable*) (defparameter *back-quote-name* #+:MCL 'simple-backquote ;; need ,this to make sure it doesn't turn into quote #-:MCL (car '`(test ,this))) (defmacro simple-backquote (x) (quotify x)) lifted from YAPS ; added check for " call " and " eval " (cond ((not (consp x)) (list 'quote x)) ((eql (car x) 'bq-comma) (cadr x)) ((member (car x) '(call eval)) x) (t (let ((type 'list) args) (setq args (cons (quotify (car x)) (loop for y on x collect (cond ((atom (cdr y)) ;; non-nil tail (setq type 'list*) (cdr y)) (t (quotify (cadr y))))))) (cons type args))))) ;;; PRIMITIVEP returns T if X is a symbol whose name begins with "!" (defmacro primitivep (x) `(and (symbolp ,x) (get ,x 'primitive))) (defmacro catch-internal-time (&rest body) `(if *internal-time-limit* (catch *internal-time-tag* ,@body) (progn ,@body))) ;;; A simple macro to add an item on to the end of a list. (defmacro push-last (item list) `(setf ,list (if (null ,list) (list ,item) (progn (setf (cdr (last ,list)) (list ,item)) ,list)))) #+sbcl (defmacro defconstant (name value &optional doc) `(common-lisp:defconstant ,name (if (boundp ',name) (symbol-value ',name) ,value) ,@(when doc (list doc)))) (defmacro call (fn &rest params) `(funcall (function ,fn) ,.params)) ;;;--------------------------------------------------------------------------- ;;; DOMAINS ;;;--------------------------------------------------------------------------- (defclass actions-domain-mixin () ((methods :initarg :methods :reader domain-methods ) (operators :initarg :operators :reader domain-operators )) ) (defclass domain (actions-domain-mixin shop2.theorem-prover:thpr-domain) () (:documentation "An object representing a SHOP2 domain.") ) (defmethod print-object ((obj domain) str) (print-unreadable-object (obj str :type t) (handler-case (when (domain-name obj) (format str "~a" (domain-name obj))) do n't have the print - method cough an error if the domain has no name . [ 2009/03/26 : rpg ] (unbound-slot () nil)))) ;;;--------------------------------------------------------------------------- PROBLEMS ;;;--------------------------------------------------------------------------- (defclass problem () ((state-atoms :initarg :state-atoms :reader state-atoms) (tasks :initarg :tasks :reader tasks) (name :initarg :name :reader name) (domain-name :initarg :domain-name :reader domain-name :initform nil :documentation "The programmer MAY (but is not obligated to) specify that a problem is intended for use with a particular domain definition.")) (:documentation "An object representing a SHOP2 problem.")) (defmethod domain-name ((probspec symbol)) (domain-name (find-problem probspec t))) (defmethod print-object ((x problem) stream) (if *print-readably* (format stream "#.(make-problem '~s ~@['~s~] '~s '~s)" (name x) (domain-name x) (state-atoms x) (tasks x)) (print-unreadable-object (x stream :type t) (princ (name x) stream)))) ;;;--------------------------------------------------------------------------- OPERATORS ;;;--------------------------------------------------------------------------- (defstruct (operator :named (:type list)) "This structure definition was added in order to make the access to operator attributes self-documenting. Later, the list structure could be removed, and a true struct could be used instead." (head nil :type list) ;this is the operator expression itself... preconditions deletions additions (cost-fun nil)) ;;;------------------------------------------------------------------------------------------------------ ;;; CLOS Generic Method Definitions ;;;------------------------------------------------------------------------------------------------------ (defgeneric methods (domain task-name) (:documentation "Return a list of all the SHOP2 methods for TASK-NAME in DOMAIN.")) (defgeneric operator (domain task-name) (:documentation "Return the SHOP2 operator (if any) defined for TASK-NAME in DOMAIN.")) (defgeneric install-domain (domain &optional redefine-ok) (:documentation "Record DOMAIN for later retrieval. Currently records the domain on the prop-list of the domain's name. By default will warn if you redefine a domain. If REDEFINE-OK is non-nil, redefinition warnings will be quashed (handy for test suites).")) (defgeneric handle-domain-options (domain &key type &allow-other-keys) (:documentation "Handle the options in option-list, as presented to defdomain. These are typically ways of tailoring the domain object, and should be keyword arguments. Returns no value; operates by side effects on DOMAIN.")) (defgeneric parse-domain-items (domain items) (:documentation "Process all the items in ITEMS. These will be methods, operators, axioms, and whatever special items domain subclasses may require. Returns no value; operates by side effects on DOMAIN. For example, in one case we define a method on this for a particular class of domain that adds to the set of items for the domain a list of standard axioms.")) (defgeneric parse-domain-item (domain item-keyword item) (:documentation "The default method for parse-domain-items will invoke this method to process a single item s-expression. The addition of this generic function makes SHOP2's syntax more extensible.") ) (defgeneric process-operator (domain operator-def) (:documentation "This generic function allows for specialization by domain type on how operator definitions are parsed. Should return something suitable for installation in the operators table of DOMAIN.")) (defgeneric process-op (domain operator-def) (:documentation "This generic function allows for specialization by domain type on how operator definitions are parsed. Should return something suitable for installation in the operators table of DOMAIN. This generic function supports the new syntax for operators that comes with the :OP keyword instead of :OPERATOR.")) (defgeneric process-method (domain method-def) (:documentation "This generic function allows for specialization by domain type on how method definitions are parsed. Should return something suitable for installation in the methods table of DOMAIN.")) (defgeneric regularize-axiom (domain axiom-def) (:documentation "This generic function allows for specialization by domain type on how axiom definitions are parsed. Should return something suitable for installation in the axioms table of DOMAIN.")) (defgeneric task-sorter (domain tasks unifier) (:documentation "This function allows customization of choice of pending task to expand. SHOP2 search behavior can be changed by specializing this generic function (most likely using the domain argument). Returns a sorted list of tasks in the order in which they should be expanded. A failure can be triggered by returning NIL.")) (defmethod methods ((domain domain) (name symbol)) (gethash name (domain-methods domain))) (defmethod operator ((domain domain) (name symbol)) (gethash name (domain-operators domain))) (defmethod axioms ((domain domain) (name symbol)) "Return a list of axioms for for NAME as defined in DOMAIN." (gethash name (domain-axioms domain)) ) (defgeneric process-pre (domain precondition) (:documentation "Preprocess the PRECONDITION in accordance with rules established by the DOMAIN class. Default method is to standardize universal quantification, creating new variable names for the bound variables in quantified expressions. Note that this name is a bad misnomer, since it is invoked not simply on preconditions, but also on add and delete lists. Possibly it should be renamed \"process quantifier\".")) I believe that two changes should be made to this function ( at least ! ): 1 . It should be renamed to apply - primitive and 2 . The CLOSage should be modified to make the operators be ;;;;;; objects so that we can dispatch on them. Currently this isn't ;;;;;; really workable because the operators are lists (so that we can do ;;;;;; things like standardize them). (defgeneric apply-operator (domain state task-body operator protections depth in-unifier) (:documentation "If OPERATOR is applicable to TASK in STATE, then APPLY-OPERATOR returns five values: 1. the operator as applied, with all bindings; 2. a state tag, for backtracking purposes; 3. a new set of protections; 4. the cost of the new operator; 5. unifier. This function also DESTRUCTIVELY MODIFIES its STATE argument. Otherwise it returns FAIL.")) (defgeneric seek-plans-primitive (domain task1 state tasks top-tasks partial-plan partial-plan-cost depth which-plans protections unifier) (:documentation "If there is an OPERATOR that is applicable to the primitive TASK1 in STATE, then SEEK-PLANS-PRIMITIVE applies that OPERATOR, generates the successor state, updates the current partial plan with the OPERATOR, and continues with planning by recursively calling SEEK-PLANS. Otherwise, it returns FAIL.")) (defgeneric seek-plans-null (domain state which-plans partial-plan partial-plan-cost depth unifier) (:documentation " This SEEK-PLANS-NULL is used with WebServices to strip the add and del lists from the actions in the partial plan before doing the actual SEEK-PLANS-NULL...")) ;;; Below, SEEK-PLANS-XXX method definitions take as input a DOMAIN object and a LTML-PLANNER-STATE object. Here , I would like to implement the ideas we discussed about internal planner state ;;; and passing planner-state objects around in the SEEK-PLANS-XXX functions, instead of the current crazy ;;; list of arguments. I am going to assume that we define a top-level PLANNER-STATE object that would probably include the current state , the partial plan , and perhaps the current task . Then , SHOP2 would use its inherited version SHOP2 - PLANNER - STATE and here we would use our inherited version LTML - PLANNER - STATE . This would also help plugging ND - SHOP2 , and perhaps , in the system , since they use their slightly different planner - state versions . [ 2006/12/28 : uk ] (defgeneric seek-plans (domain state tasks top-tasks partial-plan partial-plan-cost depth which-plans protections unifier) (:documentation "Top-level task-decomposition function.")) (defgeneric seek-plans-task (domain task1 state tasks top-tasks partial-plan partial-plan-cost depth which-plans protections unifier) (:documentation "This is a wrapper function that checks whether the current task to be decomposed is primitive or not, and depending on the task's type, it invokes either SEEK-PLANS-PRIMITIVE or SEEK-PLANS-NONPRIMITIVE, which are the real task-decomposition workhorses.")) (defgeneric seek-plans-nonprimitive (domain task1 state tasks top-tasks partial-plan partial-plan-cost depth which-plans protections unifier) (:documentation "Applies the HTN method to the current TASK1 and generates the subtasks of TASK. Recursively calls the task-decomposition routine to decompose the subtasks. In the LTML context, What should it do with the OUTPUTS and/or the RESULTS of that method? (TBD) ")) (defgeneric apply-method (domain state task method protections depth in-unifier) (:documentation "If METHOD is applicable to TASK in STATE, then APPLY-METHOD returns the resulting list of reductions. Otherwise it returns NIL. PROTECTIONS are to be passed down the stack and checked whenever we apply an operator in the context of applying the METHOD. DEPTH is used for tracing. IN-UNIFIER will be applied to the TASK when applying the method.")) (defgeneric problem->state (domain problem) (:documentation "Translate PROBLEM into a list of arguments to make-initial-state. Allows DOMAIN-specific rules for extracting special problem-components. Note that this must return a LIST of arguments for apply, so that, for example, the default method will return a list whose only element is a list of atoms, not a simple list of atoms.")) (defgeneric initialize-problem (problem &key) (:documentation "Function that does the work of populating a problem. Allows the programmer of SHOP2 extensions to extend or override the normal problem-building.") ) (defgeneric get-state (problem) (:method ((problem problem)) (state-atoms problem)) (:method ((problem-name symbol)) (get-state (find-problem problem-name t)))) (defgeneric problem-state (problem) (:documentation "Alias for get-state.") (:method ((problem problem)) (get-state problem)) (:method ((name symbol)) (problem-state (find-problem name t))) ) (defgeneric get-tasks (problem) (:method ((name symbol)) (get-tasks (find-problem name t))) (:method ((problem problem)) (tasks problem))) (defgeneric problem-tasks (problem) (:documentation "Alias for get-tasks.") (:method ((problem problem)) (get-tasks problem)) (:method ((name symbol)) (problem-tasks (find-problem name t)))) (defgeneric delete-problem (problem) (:method ((problem-name symbol)) (setf *all-problems* (delete problem-name *all-problems* :key #'name))) (:method ((problem problem)) (setf *all-problems* (delete problem *all-problems*)))) ;;; ERRORP defaults to NIL only for backwards compatibility. It might be better to make T be the default . [ 2015/01/01 : rpg ] (defun find-problem (name-or-problem &optional (errorp NIL)) (if (typep name-or-problem 'problem) ;; make FIND-PROBLEM idempotent... name-or-problem (let* ((name name-or-problem) (found (find name *all-problems* :key #'name))) (cond (found found) (errorp (error "No such problem: ~a" name)) (t nil))))) ;;;--------------------------------------------------------------------------- ;;; Conditions ;;;--------------------------------------------------------------------------- (define-condition shop-condition () () (:documentation "A condition that should be added to all conditions defined in SHOP2.") ) (define-condition shop-error (shop-condition error) () (:documentation "A convenient superclass for SHOP error conditions.")) (define-condition task-arity-mismatch (shop-error) ( (task :initarg :task :reader task-arity-mismatch-task ) (library-task :initarg :library-task :reader task-arity-mismatch-library-task ) (library-entry :initarg :library-entry :reader task-arity-mismatch-library-entry ) ) (:documentation "An error representing the case where the LIBRARY-ENTRY has a way of performing LIBRARY-TASK whose arity does not match that of TASK, although the task keyword of TASK and LIBRARY-TASK are the same.") (:report report-task-arity-mismatch)) (defun report-task-arity-mismatch (condition stream) (with-slots (task library-task) condition (format stream "Arity mismatch between task to plan and task in library:~%Task: ~S~%Task in library: ~S" task library-task))) (define-condition no-method-for-task (shop-error) ((task-name :initarg :task-name )) (:report report-no-method)) (defun report-no-method (x str) (format str "No method definition for task ~A" (slot-value x 'task-name))) (define-condition domain-parse-warning (shop-condition warning) () ) (define-condition domain-item-parse-warning (domain-parse-warning) () (:documentation "We have a separate class for warnings generated while parsing a shop domain. This is done because the items in the SHOP domain parsing are processed in reverse order, so we would like to grab up all of these warnings and then re-issue them in lexical order.")) (define-condition singleton-variable (domain-item-parse-warning) ((variable-names :initarg :variable-names :reader variable-names ) (construct-type :initarg :construct-type :reader construct-type ) (construct-name :initarg :construct-name :reader construct-name ) (construct :initarg :construct :reader construct :initform nil ) (branch-number :initarg :branch-number :reader branch-number :initform nil )) (:report (lambda (cond str) (format str "Singleton variable~p ~{~a~^, ~} in ~a ~a ~@[branch ~d~]~@[~%~s~]" (length (variable-names cond)) (variable-names cond) the messages read oddly when we said " variable ... in : - ... " ;; change to something more meaningful (if (eq (construct-type cond) :-) "AXIOM" (construct-type cond)) (construct-name cond) (branch-number cond) (construct cond)))) ) ;;; for shop-pprint -- a dispatch table. (defparameter *shop-pprint-table* (copy-pprint-dispatch))
null
https://raw.githubusercontent.com/cl-axon/shop2/9136e51f7845b46232cc17ca3618f515ddcf2787/decls.lisp
lisp
package : shop2 ; -*- Version 1.1 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at / basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. Portions created by Drs. Goldman and Maraist are Copyright (C) Alternatively, the contents of this file may be used under the terms of "LGPL"), in which case the provisions of the GPL or the LGPL are applicable instead of those above. If you wish to allow use of your version of this file only under the terms of either the GPL or the LGPL, and not to allow others to use your version of this file under the terms replace them with the notice and other provisions required by the GPL or the LGPL. If you do not delete the provisions above, a recipient may use or the LGPL. ---------------------------------------------------------------------- GOVERNMENT PURPOSE RIGHTS Contract No. FA8650-06-C-7606, The Government's rights to use, modify, reproduce, release, perform, display, or disclose this software are restricted by in the above identified contract. No restrictions apply after the expiration date shown above. Any reproduction of the software or portions thereof marked with this legend must also reproduce the markings. ------------------------------------------------------------------------------------------------------ Global Variables ------------------------------------------------------------------------------------------------------ all problems that have been defined last problem defined Many of these should probably be absorbed into the definition of maximum time (in units) for execution catch tag to throw to when time expires number of task expansions so far list of plans found so far whether to return the tree record of the parents in the tree record of the task atom for operators whether to optimize with branch and bound optimal plan found so far cost of *optimal-plan* maximum allowable depth for SEEK-PLANS default value for WHICH in FIND-PLANS what value to use for *PRINT-PRETTY* initial task list set to nil initial protection list set to nil whether to return explanations whether to print out the plans we find whether to skip ops that begin with !! when printing plans whether to print statistics current plan current task associated with *PLANS-FOUND* ------------------------------------------------------------------------------------------------------ ------------------------------------------------------------------------------------------------------ for :redo. This will really mess up interpretation of operators in SHOP, since all operators start with "!". Thus, we will turn ----------------------------------------------------------------------- alone, then write a function to create the structure later. We're assuming that "," only appears by itself and not as ",." or ",@". need ,this to make sure it doesn't turn into quote added check for " call " and " eval " non-nil tail PRIMITIVEP returns T if X is a symbol whose name begins with "!" A simple macro to add an item on to the end of a list. --------------------------------------------------------------------------- DOMAINS --------------------------------------------------------------------------- --------------------------------------------------------------------------- --------------------------------------------------------------------------- --------------------------------------------------------------------------- --------------------------------------------------------------------------- this is the operator expression itself... ------------------------------------------------------------------------------------------------------ CLOS Generic Method Definitions ------------------------------------------------------------------------------------------------------ operates by side effects on DOMAIN.")) operates by side effects on DOMAIN. objects so that we can dispatch on them. Currently this isn't really workable because the operators are lists (so that we can do things like standardize them). Below, SEEK-PLANS-XXX method definitions take as input a DOMAIN object and a LTML-PLANNER-STATE object. and passing planner-state objects around in the SEEK-PLANS-XXX functions, instead of the current crazy list of arguments. I am going to assume that we define a top-level PLANNER-STATE object that would ERRORP defaults to NIL only for backwards compatibility. It might be better make FIND-PROBLEM idempotent... --------------------------------------------------------------------------- Conditions --------------------------------------------------------------------------- change to something more meaningful for shop-pprint -- a dispatch table.
Version : MPL 1.1 / GPL 2.0 / LGPL 2.1 The contents of this file are subject to the Mozilla Public License Software distributed under the License is distributed on an " AS IS " The Original Code is SHOP2 . The Initial Developer of the Original Code is the University of Maryland . Portions created by the Initial Developer are Copyright ( C ) 2002,2003 the Initial Developer . All Rights Reserved . Additional developments made by , . 2004 - 2007 SIFT , LLC . These additions and modifications are also available under the MPL / GPL / LGPL licensing terms . either of the GNU General Public License Version 2 or later ( the " GPL " ) , or the GNU Lesser General Public License Version 2.1 or later ( the of the MPL , indicate your decision by deleting the provisions above and your version of this file under the terms of any one of the MPL , the GPL Smart Information Flow Technologies Copyright 2006 - 2007 Unpublished work Contractor Name Smart Information Flow Technologies , LLC d / b / a SIFT , LLC Contractor Address 211 N 1st Street , Suite 300 Minneapolis , MN 55401 Expiration Date 5/2/2011 paragraph ( b)(2 ) of the Rights in Noncommercial Computer Software and Noncommercial Computer Software Documentation clause contained (in-package :shop2) (defvar *shop-version* "VERSION STRING") PLANNER ... [ 2006/07/05 : rpg ] maximum time ( in seconds ) for execution default value for VERBOSE in FIND - PLANS whether to call GC each time we call SEEK - PLANS associated with * PLANS - FOUND * [ 2004/09/14 : rpg ] (defvar *hand-steer* nil "This variable will be DYNAMICALLY bound and used to indicate whether the user wishes to choose tasks for planning by hand.") (defvar *leashed* nil "This variable will be DYNAMICALLY bound and it will further constrain the behavior of SHOP2 when we hand-steer it (see *hand-steer*). If *leashed* is NIL, SHOP2 will simply proceed when choosing tasks, if there is no choice, i.e., when there's only one task on the open list, or only one :immediate task. If *leashed* is non-nil, will consult the user even in these cases.") (defvar *break-on-backtrack* nil "If this variable is bound to T, SHOP will enter a break loop upon backtracking.") Compiler Directives and Macros #+allegro (top-level:alias "bb" (&optional (val t)) "Set *break-on-backtrack* variable" (setf *break-on-backtrack* val)) It is relatively common practice in Lispworks to use ! as a macro off macro interpretation of " ! " if we are running Lispworks . see : #+:lispworks (set-syntax-from-char #\! #\@) Had to rewrite backquote macro for MCL so it leaves the structure This is a Allegro Common Lisp compatibility hack . ( swm ) #+:MCL (defparameter *blue-light-readtable* (copy-readtable nil)) #+:MCL (set-macro-character #\` #'(lambda (stream char) (declare (ignore char)) (list 'simple-backquote (read stream t nil t ))) nil *blue-light-readtable*) #+:MCL (set-macro-character #\, #'(lambda (stream char) (declare (ignore char)) (list 'bq-comma (read stream t nil t ))) nil *blue-light-readtable*) (defparameter *back-quote-name* #+:MCL 'simple-backquote #-:MCL (car '`(test ,this))) (defmacro simple-backquote (x) (quotify x)) (cond ((not (consp x)) (list 'quote x)) ((eql (car x) 'bq-comma) (cadr x)) ((member (car x) '(call eval)) x) (t (let ((type 'list) args) (setq args (cons (quotify (car x)) (loop for y on x collect (cond ((atom (cdr y)) (setq type 'list*) (cdr y)) (t (quotify (cadr y))))))) (cons type args))))) (defmacro primitivep (x) `(and (symbolp ,x) (get ,x 'primitive))) (defmacro catch-internal-time (&rest body) `(if *internal-time-limit* (catch *internal-time-tag* ,@body) (progn ,@body))) (defmacro push-last (item list) `(setf ,list (if (null ,list) (list ,item) (progn (setf (cdr (last ,list)) (list ,item)) ,list)))) #+sbcl (defmacro defconstant (name value &optional doc) `(common-lisp:defconstant ,name (if (boundp ',name) (symbol-value ',name) ,value) ,@(when doc (list doc)))) (defmacro call (fn &rest params) `(funcall (function ,fn) ,.params)) (defclass actions-domain-mixin () ((methods :initarg :methods :reader domain-methods ) (operators :initarg :operators :reader domain-operators )) ) (defclass domain (actions-domain-mixin shop2.theorem-prover:thpr-domain) () (:documentation "An object representing a SHOP2 domain.") ) (defmethod print-object ((obj domain) str) (print-unreadable-object (obj str :type t) (handler-case (when (domain-name obj) (format str "~a" (domain-name obj))) do n't have the print - method cough an error if the domain has no name . [ 2009/03/26 : rpg ] (unbound-slot () nil)))) PROBLEMS (defclass problem () ((state-atoms :initarg :state-atoms :reader state-atoms) (tasks :initarg :tasks :reader tasks) (name :initarg :name :reader name) (domain-name :initarg :domain-name :reader domain-name :initform nil :documentation "The programmer MAY (but is not obligated to) specify that a problem is intended for use with a particular domain definition.")) (:documentation "An object representing a SHOP2 problem.")) (defmethod domain-name ((probspec symbol)) (domain-name (find-problem probspec t))) (defmethod print-object ((x problem) stream) (if *print-readably* (format stream "#.(make-problem '~s ~@['~s~] '~s '~s)" (name x) (domain-name x) (state-atoms x) (tasks x)) (print-unreadable-object (x stream :type t) (princ (name x) stream)))) OPERATORS (defstruct (operator :named (:type list)) "This structure definition was added in order to make the access to operator attributes self-documenting. Later, the list structure could be removed, and a true struct could be used instead." preconditions deletions additions (cost-fun nil)) (defgeneric methods (domain task-name) (:documentation "Return a list of all the SHOP2 methods for TASK-NAME in DOMAIN.")) (defgeneric operator (domain task-name) (:documentation "Return the SHOP2 operator (if any) defined for TASK-NAME in DOMAIN.")) (defgeneric install-domain (domain &optional redefine-ok) (:documentation "Record DOMAIN for later retrieval. Currently records the domain on the prop-list of the domain's name. By default will warn if you redefine a domain. If REDEFINE-OK is non-nil, redefinition warnings will be quashed (handy for test suites).")) (defgeneric handle-domain-options (domain &key type &allow-other-keys) (:documentation "Handle the options in option-list, as presented to defdomain. These are typically ways of tailoring the domain object, and should be keyword arguments. (defgeneric parse-domain-items (domain items) (:documentation "Process all the items in ITEMS. These will be methods, operators, axioms, and whatever special items domain subclasses may require. For example, in one case we define a method on this for a particular class of domain that adds to the set of items for the domain a list of standard axioms.")) (defgeneric parse-domain-item (domain item-keyword item) (:documentation "The default method for parse-domain-items will invoke this method to process a single item s-expression. The addition of this generic function makes SHOP2's syntax more extensible.") ) (defgeneric process-operator (domain operator-def) (:documentation "This generic function allows for specialization by domain type on how operator definitions are parsed. Should return something suitable for installation in the operators table of DOMAIN.")) (defgeneric process-op (domain operator-def) (:documentation "This generic function allows for specialization by domain type on how operator definitions are parsed. Should return something suitable for installation in the operators table of DOMAIN. This generic function supports the new syntax for operators that comes with the :OP keyword instead of :OPERATOR.")) (defgeneric process-method (domain method-def) (:documentation "This generic function allows for specialization by domain type on how method definitions are parsed. Should return something suitable for installation in the methods table of DOMAIN.")) (defgeneric regularize-axiom (domain axiom-def) (:documentation "This generic function allows for specialization by domain type on how axiom definitions are parsed. Should return something suitable for installation in the axioms table of DOMAIN.")) (defgeneric task-sorter (domain tasks unifier) (:documentation "This function allows customization of choice of pending task to expand. SHOP2 search behavior can be changed by specializing this generic function (most likely using the domain argument). Returns a sorted list of tasks in the order in which they should be expanded. A failure can be triggered by returning NIL.")) (defmethod methods ((domain domain) (name symbol)) (gethash name (domain-methods domain))) (defmethod operator ((domain domain) (name symbol)) (gethash name (domain-operators domain))) (defmethod axioms ((domain domain) (name symbol)) "Return a list of axioms for for NAME as defined in DOMAIN." (gethash name (domain-axioms domain)) ) (defgeneric process-pre (domain precondition) (:documentation "Preprocess the PRECONDITION in accordance with rules established by the DOMAIN class. Default method is to standardize universal quantification, creating new variable names for the bound variables in quantified expressions. Note that this name is a bad misnomer, since it is invoked not simply on preconditions, but also on add and delete lists. Possibly it should be renamed \"process quantifier\".")) I believe that two changes should be made to this function ( at least ! ): 1 . It should be renamed to apply - primitive and 2 . The CLOSage should be modified to make the operators be (defgeneric apply-operator (domain state task-body operator protections depth in-unifier) (:documentation "If OPERATOR is applicable to TASK in STATE, then APPLY-OPERATOR returns five values: 5. unifier. This function also DESTRUCTIVELY MODIFIES its STATE argument. Otherwise it returns FAIL.")) (defgeneric seek-plans-primitive (domain task1 state tasks top-tasks partial-plan partial-plan-cost depth which-plans protections unifier) (:documentation "If there is an OPERATOR that is applicable to the primitive TASK1 in STATE, then SEEK-PLANS-PRIMITIVE applies that OPERATOR, generates the successor state, updates the current partial plan with the OPERATOR, and continues with planning by recursively calling SEEK-PLANS. Otherwise, it returns FAIL.")) (defgeneric seek-plans-null (domain state which-plans partial-plan partial-plan-cost depth unifier) (:documentation " This SEEK-PLANS-NULL is used with WebServices to strip the add and del lists from the actions in the partial plan before doing the actual SEEK-PLANS-NULL...")) Here , I would like to implement the ideas we discussed about internal planner state probably include the current state , the partial plan , and perhaps the current task . Then , SHOP2 would use its inherited version SHOP2 - PLANNER - STATE and here we would use our inherited version LTML - PLANNER - STATE . This would also help plugging ND - SHOP2 , and perhaps , in the system , since they use their slightly different planner - state versions . [ 2006/12/28 : uk ] (defgeneric seek-plans (domain state tasks top-tasks partial-plan partial-plan-cost depth which-plans protections unifier) (:documentation "Top-level task-decomposition function.")) (defgeneric seek-plans-task (domain task1 state tasks top-tasks partial-plan partial-plan-cost depth which-plans protections unifier) (:documentation "This is a wrapper function that checks whether the current task to be decomposed is primitive or not, and depending on the task's type, it invokes either SEEK-PLANS-PRIMITIVE or SEEK-PLANS-NONPRIMITIVE, which are the real task-decomposition workhorses.")) (defgeneric seek-plans-nonprimitive (domain task1 state tasks top-tasks partial-plan partial-plan-cost depth which-plans protections unifier) (:documentation "Applies the HTN method to the current TASK1 and generates the subtasks of TASK. Recursively calls the task-decomposition routine to decompose the subtasks. In the LTML context, What should it do with the OUTPUTS and/or the RESULTS of that method? (TBD) ")) (defgeneric apply-method (domain state task method protections depth in-unifier) (:documentation "If METHOD is applicable to TASK in STATE, then APPLY-METHOD returns the resulting list of reductions. Otherwise it returns NIL. PROTECTIONS are to be passed down the stack and checked whenever we apply an operator in the context of applying the METHOD. DEPTH is used for tracing. IN-UNIFIER will be applied to the TASK when applying the method.")) (defgeneric problem->state (domain problem) (:documentation "Translate PROBLEM into a list of arguments to make-initial-state. Allows DOMAIN-specific rules for extracting special problem-components. Note that this must return a LIST of arguments for apply, so that, for example, the default method will return a list whose only element is a list of atoms, not a simple list of atoms.")) (defgeneric initialize-problem (problem &key) (:documentation "Function that does the work of populating a problem. Allows the programmer of SHOP2 extensions to extend or override the normal problem-building.") ) (defgeneric get-state (problem) (:method ((problem problem)) (state-atoms problem)) (:method ((problem-name symbol)) (get-state (find-problem problem-name t)))) (defgeneric problem-state (problem) (:documentation "Alias for get-state.") (:method ((problem problem)) (get-state problem)) (:method ((name symbol)) (problem-state (find-problem name t))) ) (defgeneric get-tasks (problem) (:method ((name symbol)) (get-tasks (find-problem name t))) (:method ((problem problem)) (tasks problem))) (defgeneric problem-tasks (problem) (:documentation "Alias for get-tasks.") (:method ((problem problem)) (get-tasks problem)) (:method ((name symbol)) (problem-tasks (find-problem name t)))) (defgeneric delete-problem (problem) (:method ((problem-name symbol)) (setf *all-problems* (delete problem-name *all-problems* :key #'name))) (:method ((problem problem)) (setf *all-problems* (delete problem *all-problems*)))) to make T be the default . [ 2015/01/01 : rpg ] (defun find-problem (name-or-problem &optional (errorp NIL)) (if (typep name-or-problem 'problem) name-or-problem (let* ((name name-or-problem) (found (find name *all-problems* :key #'name))) (cond (found found) (errorp (error "No such problem: ~a" name)) (t nil))))) (define-condition shop-condition () () (:documentation "A condition that should be added to all conditions defined in SHOP2.") ) (define-condition shop-error (shop-condition error) () (:documentation "A convenient superclass for SHOP error conditions.")) (define-condition task-arity-mismatch (shop-error) ( (task :initarg :task :reader task-arity-mismatch-task ) (library-task :initarg :library-task :reader task-arity-mismatch-library-task ) (library-entry :initarg :library-entry :reader task-arity-mismatch-library-entry ) ) (:documentation "An error representing the case where the LIBRARY-ENTRY has a way of performing LIBRARY-TASK whose arity does not match that of TASK, although the task keyword of TASK and LIBRARY-TASK are the same.") (:report report-task-arity-mismatch)) (defun report-task-arity-mismatch (condition stream) (with-slots (task library-task) condition (format stream "Arity mismatch between task to plan and task in library:~%Task: ~S~%Task in library: ~S" task library-task))) (define-condition no-method-for-task (shop-error) ((task-name :initarg :task-name )) (:report report-no-method)) (defun report-no-method (x str) (format str "No method definition for task ~A" (slot-value x 'task-name))) (define-condition domain-parse-warning (shop-condition warning) () ) (define-condition domain-item-parse-warning (domain-parse-warning) () (:documentation "We have a separate class for warnings generated while parsing a shop domain. This is done because the items in the SHOP domain parsing are processed in reverse order, so we would like to grab up all of these warnings and then re-issue them in lexical order.")) (define-condition singleton-variable (domain-item-parse-warning) ((variable-names :initarg :variable-names :reader variable-names ) (construct-type :initarg :construct-type :reader construct-type ) (construct-name :initarg :construct-name :reader construct-name ) (construct :initarg :construct :reader construct :initform nil ) (branch-number :initarg :branch-number :reader branch-number :initform nil )) (:report (lambda (cond str) (format str "Singleton variable~p ~{~a~^, ~} in ~a ~a ~@[branch ~d~]~@[~%~s~]" (length (variable-names cond)) (variable-names cond) the messages read oddly when we said " variable ... in : - ... " (if (eq (construct-type cond) :-) "AXIOM" (construct-type cond)) (construct-name cond) (branch-number cond) (construct cond)))) ) (defparameter *shop-pprint-table* (copy-pprint-dispatch))
8aebfd64812d9b7807a07e0c56c5cdf4fd435b8def3e12637ea19f2869c5aff3
daveyarwood/alda-clj
shell.clj
(ns ^:no-doc alda.shell (:require [me.raynes.conch.low-level :as conch]) (:import [java.io ByteArrayOutputStream PrintWriter Writer])) (defn multi-writer-with-autoflush "Given a seq of Writers, returns a single Writer that writes the same output to all of them. Output is flushed automatically on every write. Adapted from: " [writers] I had to comment some of these methods out because Clojure does n't let you ;; do multiple overloads of the same arity. This isn't great, but I guess it's ;; alright because you can still accomplish whatever you need to do by using ;; the overloads I kept. (proxy [Writer] [] ;; (append [^char c] ;; (run! #(.append % c))) (append ([^CharSequence csq] (run! #(.append % csq))) ([^CharSequence csq start end] (run! #(.append % csq start end)))) (close [] (run! #(.close %) writers)) (flush [] (run! #(.flush %) writers)) (nullWriter [] (throw (ex-info "Method not supported" {:method "nullWriter"}))) (write ([cbuf] (run! #(.write % cbuf) writers) (run! #(.flush %) writers)) ([^chars cbuf offset length] (run! #(.write % cbuf offset length) writers) (run! #(.flush %) writers))))) ;; ([^char c] ;; (run! #(.write % c) writers))))) ( [ ^String s ] ( run ! # ( .write % s ) writers ) ) ) ) ) ( [ ^String s offset length ] ( run ! # ( .write % s offset length ) writers ) ) ) ) ) (defn sh "Starts a process via me.raynes.conch.low-level/proc. Shell output is streamed to stdout and stderr as it is produced (implementation adapted from boot.util/sh). Like clojure.java.shell/sh, waits for the process to exit and then returns a map containing: :exit exit code (int) :out stdout output (string) :err stderr output (string)" [cmd & args] (let [proc (apply conch/proc cmd args) [out-copy err-copy] (repeatedly 2 #(ByteArrayOutputStream.)) out-writer (multi-writer-with-autoflush [*out* (PrintWriter. out-copy)]) err-writer (multi-writer-with-autoflush [*err* (PrintWriter. err-copy)]) out-future (future (conch/stream-to proc :out out-writer)) err-future (future (conch/stream-to proc :err err-writer)) exit-code (.waitFor (:process proc))] ;; Ensure that all of the output is written to `out-copy` and `err-copy` ;; before we return it as a string. @out-future @err-future {:out (str out-copy) :err (str err-copy) :exit exit-code}))
null
https://raw.githubusercontent.com/daveyarwood/alda-clj/25b0d21affc0ded046af80b8f0324de875bacfcf/src/alda/shell.clj
clojure
do multiple overloads of the same arity. This isn't great, but I guess it's alright because you can still accomplish whatever you need to do by using the overloads I kept. (append [^char c] (run! #(.append % c))) ([^char c] (run! #(.write % c) writers))))) Ensure that all of the output is written to `out-copy` and `err-copy` before we return it as a string.
(ns ^:no-doc alda.shell (:require [me.raynes.conch.low-level :as conch]) (:import [java.io ByteArrayOutputStream PrintWriter Writer])) (defn multi-writer-with-autoflush "Given a seq of Writers, returns a single Writer that writes the same output to all of them. Output is flushed automatically on every write. Adapted from: " [writers] I had to comment some of these methods out because Clojure does n't let you (proxy [Writer] [] (append ([^CharSequence csq] (run! #(.append % csq))) ([^CharSequence csq start end] (run! #(.append % csq start end)))) (close [] (run! #(.close %) writers)) (flush [] (run! #(.flush %) writers)) (nullWriter [] (throw (ex-info "Method not supported" {:method "nullWriter"}))) (write ([cbuf] (run! #(.write % cbuf) writers) (run! #(.flush %) writers)) ([^chars cbuf offset length] (run! #(.write % cbuf offset length) writers) (run! #(.flush %) writers))))) ( [ ^String s ] ( run ! # ( .write % s ) writers ) ) ) ) ) ( [ ^String s offset length ] ( run ! # ( .write % s offset length ) writers ) ) ) ) ) (defn sh "Starts a process via me.raynes.conch.low-level/proc. Shell output is streamed to stdout and stderr as it is produced (implementation adapted from boot.util/sh). Like clojure.java.shell/sh, waits for the process to exit and then returns a map containing: :exit exit code (int) :out stdout output (string) :err stderr output (string)" [cmd & args] (let [proc (apply conch/proc cmd args) [out-copy err-copy] (repeatedly 2 #(ByteArrayOutputStream.)) out-writer (multi-writer-with-autoflush [*out* (PrintWriter. out-copy)]) err-writer (multi-writer-with-autoflush [*err* (PrintWriter. err-copy)]) out-future (future (conch/stream-to proc :out out-writer)) err-future (future (conch/stream-to proc :err err-writer)) exit-code (.waitFor (:process proc))] @out-future @err-future {:out (str out-copy) :err (str err-copy) :exit exit-code}))
fa5169fd2fa0b50f032f035b15a7cc91b247000bcad91bd3d9a7ae45514ec1a7
Eduap-com/WordMat
ddot.lisp
;;; Compiled by f2cl version: ( " f2cl1.l , v 95098eb54f13 2013/04/01 00:45:16 toy $ " " f2cl2.l , v 95098eb54f13 2013/04/01 00:45:16 toy $ " " f2cl3.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ " " f2cl4.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ " " f2cl5.l , v 95098eb54f13 2013/04/01 00:45:16 toy $ " " f2cl6.l , v 1d5cbacbb977 2008/08/24 00:56:27 rtoy $ " " macros.l , v 1409c1352feb 2013/03/24 20:44:50 toy $ " ) Using Lisp CMU Common Lisp snapshot-2017 - 01 ( 21B Unicode ) ;;; ;;; Options: ((:prune-labels nil) (:auto-save t) (:relaxed-array-decls t) ;;; (:coerce-assigns :as-needed) (:array-type ':array) ;;; (:array-slicing t) (:declare-common nil) ;;; (:float-format double-float)) (in-package "ODEPACK") (defun ddot (n dx incx dy incy) (declare (type (array double-float (*)) dy dx) (type (f2cl-lib:integer4) incy incx n)) (f2cl-lib:with-multi-array-data ((dx double-float dx-%data% dx-%offset%) (dy double-float dy-%data% dy-%offset%)) (prog ((ddot 0.0) (ns 0) (mp1 0) (m 0) (i 0) (iy 0) (ix 0)) (declare (type (f2cl-lib:integer4) ix iy i m mp1 ns) (type (double-float) ddot)) (setf ddot 0.0) (if (<= n 0) (go end_label)) (if (= incx incy) (f2cl-lib:arithmetic-if (f2cl-lib:int-sub incx 1) (go label5) (go label20) (go label60))) label5 (setf ix 1) (setf iy 1) (if (< incx 0) (setf ix (f2cl-lib:int-add (f2cl-lib:int-mul (f2cl-lib:int-sub 1 n) incx) 1))) (if (< incy 0) (setf iy (f2cl-lib:int-add (f2cl-lib:int-mul (f2cl-lib:int-sub 1 n) incy) 1))) (f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1)) ((> i n) nil) (tagbody (setf ddot (+ ddot (* (f2cl-lib:fref dx-%data% (ix) ((1 *)) dx-%offset%) (f2cl-lib:fref dy-%data% (iy) ((1 *)) dy-%offset%)))) (setf ix (f2cl-lib:int-add ix incx)) (setf iy (f2cl-lib:int-add iy incy)) label10)) (go end_label) label20 (setf m (mod n 5)) (if (= m 0) (go label40)) (f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1)) ((> i m) nil) (tagbody (setf ddot (+ ddot (* (f2cl-lib:fref dx-%data% (i) ((1 *)) dx-%offset%) (f2cl-lib:fref dy-%data% (i) ((1 *)) dy-%offset%)))) label30)) (if (< n 5) (go end_label)) label40 (setf mp1 (f2cl-lib:int-add m 1)) (f2cl-lib:fdo (i mp1 (f2cl-lib:int-add i 5)) ((> i n) nil) (tagbody (setf ddot (+ ddot (* (f2cl-lib:fref dx-%data% (i) ((1 *)) dx-%offset%) (f2cl-lib:fref dy-%data% (i) ((1 *)) dy-%offset%)) (* (f2cl-lib:fref dx-%data% ((f2cl-lib:int-add i 1)) ((1 *)) dx-%offset%) (f2cl-lib:fref dy-%data% ((f2cl-lib:int-add i 1)) ((1 *)) dy-%offset%)) (* (f2cl-lib:fref dx-%data% ((f2cl-lib:int-add i 2)) ((1 *)) dx-%offset%) (f2cl-lib:fref dy-%data% ((f2cl-lib:int-add i 2)) ((1 *)) dy-%offset%)) (* (f2cl-lib:fref dx-%data% ((f2cl-lib:int-add i 3)) ((1 *)) dx-%offset%) (f2cl-lib:fref dy-%data% ((f2cl-lib:int-add i 3)) ((1 *)) dy-%offset%)) (* (f2cl-lib:fref dx-%data% ((f2cl-lib:int-add i 4)) ((1 *)) dx-%offset%) (f2cl-lib:fref dy-%data% ((f2cl-lib:int-add i 4)) ((1 *)) dy-%offset%)))) label50)) (go end_label) label60 (setf ns (f2cl-lib:int-mul n incx)) (f2cl-lib:fdo (i 1 (f2cl-lib:int-add i incx)) ((> i ns) nil) (tagbody (setf ddot (+ ddot (* (f2cl-lib:fref dx-%data% (i) ((1 *)) dx-%offset%) (f2cl-lib:fref dy-%data% (i) ((1 *)) dy-%offset%)))) label70)) (go end_label) end_label (return (values ddot nil nil nil nil nil))))) (in-package #-gcl #:cl-user #+gcl "CL-USER") #+#.(cl:if (cl:find-package '#:f2cl) '(and) '(or)) (eval-when (:load-toplevel :compile-toplevel :execute) (setf (gethash 'fortran-to-lisp::ddot fortran-to-lisp::*f2cl-function-info*) (fortran-to-lisp::make-f2cl-finfo :arg-types '((fortran-to-lisp::integer4) (array double-float (*)) (fortran-to-lisp::integer4) (array double-float (*)) (fortran-to-lisp::integer4)) :return-values '(nil nil nil nil nil) :calls 'nil)))
null
https://raw.githubusercontent.com/Eduap-com/WordMat/83c9336770067f54431cc42c7147dc6ed640a339/Windows/ExternalPrograms/maxima-5.45.1/share/maxima/5.45.1/share/odepack/src/ddot.lisp
lisp
Compiled by f2cl version: Options: ((:prune-labels nil) (:auto-save t) (:relaxed-array-decls t) (:coerce-assigns :as-needed) (:array-type ':array) (:array-slicing t) (:declare-common nil) (:float-format double-float))
( " f2cl1.l , v 95098eb54f13 2013/04/01 00:45:16 toy $ " " f2cl2.l , v 95098eb54f13 2013/04/01 00:45:16 toy $ " " f2cl3.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ " " f2cl4.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ " " f2cl5.l , v 95098eb54f13 2013/04/01 00:45:16 toy $ " " f2cl6.l , v 1d5cbacbb977 2008/08/24 00:56:27 rtoy $ " " macros.l , v 1409c1352feb 2013/03/24 20:44:50 toy $ " ) Using Lisp CMU Common Lisp snapshot-2017 - 01 ( 21B Unicode ) (in-package "ODEPACK") (defun ddot (n dx incx dy incy) (declare (type (array double-float (*)) dy dx) (type (f2cl-lib:integer4) incy incx n)) (f2cl-lib:with-multi-array-data ((dx double-float dx-%data% dx-%offset%) (dy double-float dy-%data% dy-%offset%)) (prog ((ddot 0.0) (ns 0) (mp1 0) (m 0) (i 0) (iy 0) (ix 0)) (declare (type (f2cl-lib:integer4) ix iy i m mp1 ns) (type (double-float) ddot)) (setf ddot 0.0) (if (<= n 0) (go end_label)) (if (= incx incy) (f2cl-lib:arithmetic-if (f2cl-lib:int-sub incx 1) (go label5) (go label20) (go label60))) label5 (setf ix 1) (setf iy 1) (if (< incx 0) (setf ix (f2cl-lib:int-add (f2cl-lib:int-mul (f2cl-lib:int-sub 1 n) incx) 1))) (if (< incy 0) (setf iy (f2cl-lib:int-add (f2cl-lib:int-mul (f2cl-lib:int-sub 1 n) incy) 1))) (f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1)) ((> i n) nil) (tagbody (setf ddot (+ ddot (* (f2cl-lib:fref dx-%data% (ix) ((1 *)) dx-%offset%) (f2cl-lib:fref dy-%data% (iy) ((1 *)) dy-%offset%)))) (setf ix (f2cl-lib:int-add ix incx)) (setf iy (f2cl-lib:int-add iy incy)) label10)) (go end_label) label20 (setf m (mod n 5)) (if (= m 0) (go label40)) (f2cl-lib:fdo (i 1 (f2cl-lib:int-add i 1)) ((> i m) nil) (tagbody (setf ddot (+ ddot (* (f2cl-lib:fref dx-%data% (i) ((1 *)) dx-%offset%) (f2cl-lib:fref dy-%data% (i) ((1 *)) dy-%offset%)))) label30)) (if (< n 5) (go end_label)) label40 (setf mp1 (f2cl-lib:int-add m 1)) (f2cl-lib:fdo (i mp1 (f2cl-lib:int-add i 5)) ((> i n) nil) (tagbody (setf ddot (+ ddot (* (f2cl-lib:fref dx-%data% (i) ((1 *)) dx-%offset%) (f2cl-lib:fref dy-%data% (i) ((1 *)) dy-%offset%)) (* (f2cl-lib:fref dx-%data% ((f2cl-lib:int-add i 1)) ((1 *)) dx-%offset%) (f2cl-lib:fref dy-%data% ((f2cl-lib:int-add i 1)) ((1 *)) dy-%offset%)) (* (f2cl-lib:fref dx-%data% ((f2cl-lib:int-add i 2)) ((1 *)) dx-%offset%) (f2cl-lib:fref dy-%data% ((f2cl-lib:int-add i 2)) ((1 *)) dy-%offset%)) (* (f2cl-lib:fref dx-%data% ((f2cl-lib:int-add i 3)) ((1 *)) dx-%offset%) (f2cl-lib:fref dy-%data% ((f2cl-lib:int-add i 3)) ((1 *)) dy-%offset%)) (* (f2cl-lib:fref dx-%data% ((f2cl-lib:int-add i 4)) ((1 *)) dx-%offset%) (f2cl-lib:fref dy-%data% ((f2cl-lib:int-add i 4)) ((1 *)) dy-%offset%)))) label50)) (go end_label) label60 (setf ns (f2cl-lib:int-mul n incx)) (f2cl-lib:fdo (i 1 (f2cl-lib:int-add i incx)) ((> i ns) nil) (tagbody (setf ddot (+ ddot (* (f2cl-lib:fref dx-%data% (i) ((1 *)) dx-%offset%) (f2cl-lib:fref dy-%data% (i) ((1 *)) dy-%offset%)))) label70)) (go end_label) end_label (return (values ddot nil nil nil nil nil))))) (in-package #-gcl #:cl-user #+gcl "CL-USER") #+#.(cl:if (cl:find-package '#:f2cl) '(and) '(or)) (eval-when (:load-toplevel :compile-toplevel :execute) (setf (gethash 'fortran-to-lisp::ddot fortran-to-lisp::*f2cl-function-info*) (fortran-to-lisp::make-f2cl-finfo :arg-types '((fortran-to-lisp::integer4) (array double-float (*)) (fortran-to-lisp::integer4) (array double-float (*)) (fortran-to-lisp::integer4)) :return-values '(nil nil nil nil nil) :calls 'nil)))
4b347eec17a91339e5ab29ddc4cb268cf9290255fa3bf5f85a31d4990b736dc6
facebook/pyre-check
indexTracker.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. *) (* TODO(T132410158) Add a module-level doc comment. *) open Core type t = int [@@deriving compare, show, sexp, hash] module IndexKey = struct type nonrec t = t let to_string = show let compare = compare let from_string = Int.of_string end module Set = Set.Make (struct type nonrec t = t let compare = compare let sexp_of_t = sexp_of_t let t_of_sexp = t_of_sexp end) include Hashable.Make (struct type nonrec t = t let compare = compare let hash = Hashtbl.hash let hash_fold_t = hash_fold_t let sexp_of_t = sexp_of_t let t_of_sexp = t_of_sexp end) module OrderIndexValue = struct type t = int let prefix = Prefix.make () let description = "Order indices" end module OrderAnnotationValue = struct type t = string let prefix = Prefix.make () let description = "Order annotations" end module OrderIndices = Memory.WithCache.Make (SharedMemoryKeys.StringKey) (OrderIndexValue) module OrderAnnotations = Memory.WithCache.Make (SharedMemoryKeys.IntKey) (OrderAnnotationValue) let index annotation = match OrderIndices.get annotation with | Some index -> index | None -> ( let rec claim_free_index current = OrderAnnotations.write_around current annotation; match OrderAnnotations.get_no_cache current with (* Successfully claimed the id *) | Some decoded when String.equal decoded annotation -> current Someone else claimed the i d first | Some _non_equal_annotation -> claim_free_index (current + 1) | None -> failwith "read-your-own-write consistency was violated" in let encoded = claim_free_index (Type.Primitive.hash annotation) in There may be a race between two identical calls to index , which would result in * Annotations : { hash(a ) - > a ; hash(a ) + 1 - > a ; ... } * By writing through , and then returning the canonical value , we ensure we only * ever return one value for index(a ) * Annotations: { hash(a) -> a; hash(a) + 1 -> a; ... } * By writing through, and then returning the canonical value, we ensure we only * ever return one value for index(a) *) OrderIndices.write_around annotation encoded; match OrderIndices.get_no_cache annotation with | Some index -> index | None -> failwith "read-your-own-write consistency was violated") let indices annotations = let replace_if_new annotation = function | Some got_in_batch -> got_in_batch | None -> index annotation in Core.Set.to_list annotations |> OrderIndices.KeySet.of_list |> OrderIndices.get_batch |> OrderIndices.KeyMap.mapi replace_if_new |> OrderIndices.KeyMap.values |> Set.of_list let annotation index = (* Because we seal the type, we can be sure this will always succeed *) OrderAnnotations.get_exn index
null
https://raw.githubusercontent.com/facebook/pyre-check/98b8362ffa5c715c708676c1a37a52647ce79fe0/source/analysis/indexTracker.ml
ocaml
TODO(T132410158) Add a module-level doc comment. Successfully claimed the id Because we seal the type, we can be sure this will always succeed
* 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. *) open Core type t = int [@@deriving compare, show, sexp, hash] module IndexKey = struct type nonrec t = t let to_string = show let compare = compare let from_string = Int.of_string end module Set = Set.Make (struct type nonrec t = t let compare = compare let sexp_of_t = sexp_of_t let t_of_sexp = t_of_sexp end) include Hashable.Make (struct type nonrec t = t let compare = compare let hash = Hashtbl.hash let hash_fold_t = hash_fold_t let sexp_of_t = sexp_of_t let t_of_sexp = t_of_sexp end) module OrderIndexValue = struct type t = int let prefix = Prefix.make () let description = "Order indices" end module OrderAnnotationValue = struct type t = string let prefix = Prefix.make () let description = "Order annotations" end module OrderIndices = Memory.WithCache.Make (SharedMemoryKeys.StringKey) (OrderIndexValue) module OrderAnnotations = Memory.WithCache.Make (SharedMemoryKeys.IntKey) (OrderAnnotationValue) let index annotation = match OrderIndices.get annotation with | Some index -> index | None -> ( let rec claim_free_index current = OrderAnnotations.write_around current annotation; match OrderAnnotations.get_no_cache current with | Some decoded when String.equal decoded annotation -> current Someone else claimed the i d first | Some _non_equal_annotation -> claim_free_index (current + 1) | None -> failwith "read-your-own-write consistency was violated" in let encoded = claim_free_index (Type.Primitive.hash annotation) in There may be a race between two identical calls to index , which would result in * Annotations : { hash(a ) - > a ; hash(a ) + 1 - > a ; ... } * By writing through , and then returning the canonical value , we ensure we only * ever return one value for index(a ) * Annotations: { hash(a) -> a; hash(a) + 1 -> a; ... } * By writing through, and then returning the canonical value, we ensure we only * ever return one value for index(a) *) OrderIndices.write_around annotation encoded; match OrderIndices.get_no_cache annotation with | Some index -> index | None -> failwith "read-your-own-write consistency was violated") let indices annotations = let replace_if_new annotation = function | Some got_in_batch -> got_in_batch | None -> index annotation in Core.Set.to_list annotations |> OrderIndices.KeySet.of_list |> OrderIndices.get_batch |> OrderIndices.KeyMap.mapi replace_if_new |> OrderIndices.KeyMap.values |> Set.of_list let annotation index = OrderAnnotations.get_exn index
8a73ea76bf69a34a6b2e291a0f68d838046900a90dd6e75004e646e3ea84c9e2
UCSD-PL/refscript
Module.hs
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveFoldable #-} # LANGUAGE DeriveFunctor # # LANGUAGE DeriveGeneric # {-# LANGUAGE DeriveTraversable #-} # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE IncoherentInstances # # LANGUAGE MultiParamTypeClasses # # LANGUAGE NoMonomorphismRestriction # # LANGUAGE TupleSections # {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE UndecidableInstances #-} module Language.Rsc.Pretty.Module where import qualified Language.Fixpoint.Types as F import Language.Rsc.Module import Language.Rsc.Pretty.Common import Language.Rsc.Pretty.Symbols () import Text.PrettyPrint.HughesPJ instance (PP r, F.Reftable r) => PP (ModuleDef r) where pp (ModuleDef vars tys enums path) = pp (take 80 (repeat '-')) $+$ text "module" <+> pp path $+$ pp (take 80 (repeat '-')) $+$ text "Variables" $+$ nest 4 (pp vars) $+$ text "Types" $+$ nest 4 (pp tys) $+$ text "Enums" $+$ nest 4 (pp enums)
null
https://raw.githubusercontent.com/UCSD-PL/refscript/884306fef72248ac41ecdbb928bbd7b06ca71bd4/src/Language/Rsc/Pretty/Module.hs
haskell
# LANGUAGE ConstraintKinds # # LANGUAGE DeriveDataTypeable # # LANGUAGE DeriveFoldable # # LANGUAGE DeriveTraversable # # LANGUAGE TypeSynonymInstances # # LANGUAGE UndecidableInstances #
# LANGUAGE DeriveFunctor # # LANGUAGE DeriveGeneric # # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE IncoherentInstances # # LANGUAGE MultiParamTypeClasses # # LANGUAGE NoMonomorphismRestriction # # LANGUAGE TupleSections # module Language.Rsc.Pretty.Module where import qualified Language.Fixpoint.Types as F import Language.Rsc.Module import Language.Rsc.Pretty.Common import Language.Rsc.Pretty.Symbols () import Text.PrettyPrint.HughesPJ instance (PP r, F.Reftable r) => PP (ModuleDef r) where pp (ModuleDef vars tys enums path) = pp (take 80 (repeat '-')) $+$ text "module" <+> pp path $+$ pp (take 80 (repeat '-')) $+$ text "Variables" $+$ nest 4 (pp vars) $+$ text "Types" $+$ nest 4 (pp tys) $+$ text "Enums" $+$ nest 4 (pp enums)
cd2b45294bbd9db5fe9b8e1924dcd1116cf806dac97f324d9ce7baac4d50587c
kmonad/kmonad
Button.hs
| Module : KMonad . Model . Button Description : How buttons work Copyright : ( c ) , 2019 License : MIT Maintainer : Stability : experimental Portability : portable A button contains 2 actions , one to perform on press , and another to perform on release . This module contains that definition , and some helper code that helps combine buttons . It is here that most of the complicated ` buttons are implemented ( like TapHold ) . Module : KMonad.Model.Button Description : How buttons work Copyright : (c) David Janssen, 2019 License : MIT Maintainer : Stability : experimental Portability : portable A button contains 2 actions, one to perform on press, and another to perform on release. This module contains that definition, and some helper code that helps combine buttons. It is here that most of the complicated` buttons are implemented (like TapHold). -} module KMonad.Model.Button ( -- * Button basics -- $but Button , HasButton(..) , onPress , onRelease , mkButton , around , tapOn -- * Simple buttons -- $simple , emitB , pressOnly , releaseOnly , modded , layerToggle , layerSwitch , layerAdd , layerRem , pass , cmdButton -- * Button combinators -- $combinators , aroundNext , aroundNextTimeout , aroundNextSingle , beforeAfterNext , layerDelay , layerNext , tapHold , multiTap , tapNext , tapHoldNext , tapNextRelease , tapHoldNextRelease , tapNextPress , tapMacro , tapMacroRelease , stickyKey ) where import KMonad.Prelude import KMonad.Model.Action import KMonad.Keyboard import KMonad.Util -------------------------------------------------------------------------------- -- $but -- This section contains the basic definition of KMonad 's ' Button ' datatype . A ' Button ' is essentially a collection of 2 different actions , 1 to perform on -- 'Press' and another on 'Release'. | A ' Button ' consists of two ' MonadK ' actions , one to take when a press is -- registered from the OS, and another when a release is registered. data Button = Button { _pressAction :: !Action -- ^ Action to take when pressed , _releaseAction :: !Action -- ^ Action to take when released } makeClassy ''Button -- | Create a 'Button' out of a press and release action -- -- NOTE: Since 'AnyK' is an existentially qualified 'MonadK', the monadic -- actions specified must be runnable by all implementations of 'MonadK', and -- therefore can only rely on functionality from 'MonadK'. I.e. the actions must -- be pure 'MonadK'. mkButton :: AnyK () -> AnyK () -> Button mkButton a b = Button (Action a) (Action b) -- | Create a new button with only a 'Press' action onPress :: AnyK () -> Button onPress p = mkButton p $ pure () onRelease :: AnyK () -> Button onRelease = mkButton (pure ()) -------------------------------------------------------------------------------- -- $running -- -- Triggering the actions stored in a 'Button'. -- | Perform both the press and release of a button immediately tap :: MonadK m => Button -> m () tap b = do runAction $ b^.pressAction runAction $ b^.releaseAction -- | Perform the press action of a Button and register its release callback. -- -- This performs the action stored in the 'pressAction' field and registers a -- callback that will trigger the 'releaseAction' when the release is detected. press :: MonadK m => Button -> m () press b = do runAction $ b^.pressAction awaitMy Release $ do runAction $ b^.releaseAction pure Catch -------------------------------------------------------------------------------- -- $simple -- -- A collection of simple buttons. These are basically almost direct wrappings -- around 'MonadK' functionality. | A button that emits a Press of a keycode when pressed , and a release when -- released. emitB :: Keycode -> Button emitB c = mkButton (emit $ mkPress c) (emit $ mkRelease c) | A button that emits only a Press of a keycode . pressOnly :: Keycode -> Button pressOnly c = onPress $ emit $ mkPress c | A button that emits only a Release of a keycode . releaseOnly :: Keycode -> Button releaseOnly c = onPress $ emit $ mkRelease c | Create a new button that first presses a ' ' before running an inner button , releasing the ' ' again after the inner ' Button ' is released . modded :: ^ The ' ' to ` wrap around ` the inner button -> Button -- ^ The button to nest inside `being modded` -> Button modded modder = around (emitB modder) -- | Create a button that toggles a layer on and off layerToggle :: LayerTag -> Button layerToggle t = mkButton (layerOp $ PushLayer t) (layerOp $ PopLayer t) -- | Create a button that switches the base-layer on a press layerSwitch :: LayerTag -> Button layerSwitch t = onPress (layerOp $ SetBaseLayer t) -- | Create a button that adds a layer on a press layerAdd :: LayerTag -> Button layerAdd t = onPress (layerOp $ PushLayer t) -- | Create a button that removes the top instance of a layer on a press layerRem :: LayerTag -> Button layerRem t = onPress (layerOp $ PopLayer t) -- | Create a button that does nothing (but captures the input) pass :: Button pass = onPress $ pure () -- | Create a button that executes a shell command on press and possibly on -- release cmdButton :: Text -> Maybe Text -> Button cmdButton pr mbR = mkButton (shellCmd pr) (maybe (pure ()) shellCmd mbR) -------------------------------------------------------------------------------- -- $combinators -- Functions that take ' 's and combine them to form new ' Button 's . | Create a new button from 2 buttons , an inner and an outer . When the new button is pressed , first the outer is pressed , then the inner . On release , the inner is released first , and then the outer . around :: Button -- ^ The outer 'Button' -> Button -- ^ The inner 'Button' -> Button -- ^ The resulting nested 'Button' around outer inner = Button (Action (runAction (outer^.pressAction) *> runAction (inner^.pressAction))) (Action (runAction (inner^.releaseAction) *> runAction (outer^.releaseAction))) -- | A 'Button' that, once pressed, will surround the next button with another. -- -- Think of this as, essentially, a tappable mod. For example, an 'aroundNext KeyCtrl ' would , once tapped , then make the next keypress C-<whatever > . aroundNext :: Button -- ^ The outer 'Button' -> Button -- ^ The resulting 'Button' aroundNext b = onPress $ await isPress $ \e -> do runAction $ b^.pressAction await (isReleaseOf $ e^.keycode) $ \_ -> do runAction $ b^.releaseAction pure NoCatch pure NoCatch -- | A 'Button' that, once pressed, will surround the next button within some timeout with another. -- -- If some other key is not pressed within an interval another button will be triggered as a tap. aroundNextTimeout :: Milliseconds -- ^ How long before we tap -> Button -- ^ The 'Button' to use to surround next -> Button -- ^ The 'Button' to tap on timeout -> Button -- ^ The resulting button aroundNextTimeout d b t = onPress $ within d (pure isPress) (tap t) $ \trig -> do runAction $ b^.pressAction await (isReleaseOf $ trig^.event.keycode) $ \_ -> do runAction $ b^.releaseAction pure NoCatch pure NoCatch -- | A 'Button' that, once pressed, will surround the next button with another. -- -- Think of this as, essentially, a tappable mod. For example, an 'aroundNext KeyCtrl ' would , once tapped , then make the next keypress C-<whatever > . -- -- This differs from 'aroundNext' in that it explicitly releases the modifier immediately after the first event , where ` aroundSingle ` waits around for the -- original key that was modified to be released itself. aroundNextSingle :: Button -- ^ The outer 'Button' -> Button -- ^ The resulting 'Button' aroundNextSingle b = onPress $ await isPress $ \_ -> do runAction $ b^.pressAction -- Wait for the next *event*, regardless of what it is await (pure True) $ \_ -> do runAction $ b^.releaseAction pure NoCatch pure NoCatch -- | Create a new button that performs both a press and release of the input -- button on just a press or release tapOn :: Switch -- ^ Which 'Switch' should trigger the tap -> Button -- ^ The 'Button' to tap -> Button -- ^ The tapping 'Button' tapOn Press b = mkButton (tap b) (pure ()) tapOn Release b = mkButton (pure ()) (tap b) | Create a ' Button ' that performs a tap of one button if it is released -- within an interval. If the interval is exceeded, press the other button (and -- release it when a release is detected). tapHold :: Milliseconds -> Button -> Button -> Button tapHold ms t h = onPress $ withinHeld ms (matchMy Release) (press h) -- If we catch timeout before release (const $ tap t $> Catch) -- If we catch release before timeout | Create a ' Button ' that performs a tap of 1 button if the next event is its -- own release, or else switches to holding some other button if the next event -- is a different keypress. tapNext :: Button -> Button -> Button tapNext t h = onPress $ hookF InputHook $ \e -> do p <- matchMy Release if p e then tap t $> Catch else press h $> NoCatch -- | Like 'tapNext', except that after some interval it switches anyways tapHoldNext :: Milliseconds -> Button -> Button -> Maybe Button -> Button tapHoldNext ms t h mtb = onPress $ within ms (pure $ const True) onTimeout $ \tr -> do p <- matchMy Release if p $ tr^.event then tap t $> Catch else press h $> NoCatch where onTimeout :: MonadK m => m () onTimeout = press $ fromMaybe h mtb -- | Surround some future button with a before and after tap beforeAfterNext :: Button -> Button -> Button beforeAfterNext b a = onPress $ do tap b await isPress $ \e -> do await (isReleaseOf $ e^.keycode) $ \_ -> do tap a pure NoCatch pure NoCatch -- | Create a tap-hold style button that makes its decision based on the next -- detected release in the following manner: 1 . It is the release of this button : We are tapping 2 . It is of some other button that was pressed * before * this one , ignore . 3 . It is of some other button that was pressed * after * this one , we hold . -- -- It does all of this while holding processing of other buttons, so time will -- get rolled back like a TapHold button. tapNextRelease :: Button -> Button -> Button tapNextRelease t h = onPress $ do hold True go [] where go :: MonadK m => [Keycode] -> m () go ks = hookF InputHook $ \e -> do p <- matchMy Release let isRel = isRelease e if -- If the next event is my own release: we act as if we were tapped | p e -> doTap -- If the next event is the release of some button that was held after me -- we act as if we were held | isRel && (e^.keycode `elem` ks) -> doHold e -- Else, if it is a press, store the keycode and wait again | not isRel -> go ((e^.keycode):ks) $> NoCatch -- Else, if it is a release of some button held before me, just ignore | otherwise -> go ks $> NoCatch -- Behave like a tap is simple: tap the button `t` and release processing doTap :: MonadK m => m Catch doTap = tap t *> hold False $> Catch Behave like a hold is not simple : first we release the processing hold , then we catch the release of ButtonX that triggered this action , and then -- we rethrow this release. doHold :: MonadK m => KeyEvent -> m Catch doHold e = press h *> hold False *> inject e $> Catch -- | Create a tap-hold style button that makes its decision based on the next -- detected release in the following manner: 1 . It is the release of this button : We are tapping 2 . It is of some other button that was pressed * before * this one , ignore . 3 . It is of some other button that was pressed * after * this one , we hold . -- -- If we encounter the timeout before any other release, we switch to the -- specified timeout button, or to the hold button if none is specified. -- -- It does all of this while holding processing of other buttons, so time will -- get rolled back like a TapHold button. tapHoldNextRelease :: Milliseconds -> Button -> Button -> Maybe Button -> Button tapHoldNextRelease ms t h mtb = onPress $ do hold True go ms [] where go :: MonadK m => Milliseconds -> [Keycode] -> m () go ms' ks = tHookF InputHook ms' onTimeout $ \r -> do p <- matchMy Release let e = r^.event let isRel = isRelease e if -- If the next event is my own release: act like tapped | p e -> onRelSelf -- If the next event is another release that was pressed after me | isRel && (e^.keycode `elem` ks) -> onRelOther e -- If the next event is a press, store and recurse | not isRel -> go (ms' - r^.elapsed) (e^.keycode : ks) $> NoCatch -- If the next event is a release of some button pressed before me, recurse | otherwise -> go (ms' - r^.elapsed) ks $> NoCatch onTimeout :: MonadK m => m () onTimeout = press (fromMaybe h mtb) *> hold False onRelSelf :: MonadK m => m Catch onRelSelf = tap t *> hold False $> Catch onRelOther :: MonadK m => KeyEvent -> m Catch onRelOther e = press h *> hold False *> inject e $> Catch -- | Create a button just like tap-release, but also trigger a hold on presses: 1 . It is the release of this button : We are tapping 2 . It is the press of some other button , we hold 3 . It is the release of some other button , ignore . tapNextPress :: Button -> Button -> Button tapNextPress t h = onPress go where go :: MonadK m => m () go = hookF InputHook $ \e -> do p <- matchMy Release if -- If the next event is my own release: we act as if we were tapped | p e -> doTap -- If the next event is a press: we act as if we were held | isPress e -> doHold e -- Else, if it is a release of some other button, just ignore | otherwise -> go $> NoCatch -- Behave like a tap doTap :: MonadK m => m Catch doTap = tap t $> Catch -- Behave like a hold: We catch the event of ButtonX that triggered this action , and then -- we rethrow this event after holding. doHold :: MonadK m => KeyEvent -> m Catch doHold e = press h *> inject e $> Catch | Create a ' Button ' that contains a number of delays and ' 's . As long -- as the next press is registered before the timeout, the multiTap descends -- into its list. The moment a delay is exceeded or immediately upon reaching -- the last button, that button is pressed. multiTap :: Button -> [(Milliseconds, Button)] -> Button multiTap l bs = onPress $ go bs where go :: [(Milliseconds, Button)] -> AnyK () go [] = press l go ((ms, b):bs') = do -- This is a bit complicated. What we do is: 1 . We wait for an event 2A. If it does n't occur in the interval we press the button from the -- list and we are done. -- 2B. If we do detect the release of the key that triggered this action, -- we must now keep waiting to detect another press. -- 2C. If we detect another (unrelated) press event we cancel the -- remaining of the multi-tap sequence and trigger a tap on the -- current button of the sequence. 3A. After 2B , if we do not detect a press before the interval is up , -- we know a tap occurred, so we tap the current button and we are -- done. -- 3B. If we detect another press of the same key, then the user is -- descending into the buttons tied to this multi-tap, so we recurse -- on the remaining buttons. -- 3C. If we detect any other (unrelated) press event, then the multi-tap sequence is cancelled like in 2C. We trigger a tap of the current -- button of the sequence. let doNext pred onTimeout next ms = tHookF InputHook ms onTimeout $ \t -> do pr <- pred if | pr (t^.event) -> next (ms - t^.elapsed) $> Catch | isPress (t^.event) -> tap b $> NoCatch | otherwise -> pure NoCatch doNext (matchMy Release) (press b) (doNext (matchMy Press) (tap b) (\_ -> go bs')) ms -- | Create a 'Button' that performs a series of taps on press. Note that the last button is only released when the tapMacro itself is released . tapMacro :: [Button] -> Button tapMacro bs = onPress $ go bs where go [] = pure () go [b] = press b go (b:rst) = tap b >> go rst -- | Create a 'Button' that performs a series of taps on press, -- except for the last Button, which is tapped on release. tapMacroRelease :: [Button] -> Button tapMacroRelease bs = onPress $ go bs where go [] = pure () go [b] = awaitMy Release $ tap b >> pure Catch go (b:rst) = tap b >> go rst -- | Switch to a layer for a period of time, then automatically switch back layerDelay :: Milliseconds -> LayerTag -> Button layerDelay d t = onPress $ do layerOp (PushLayer t) after d (layerOp $ PopLayer t) -- | Switch to a layer for the next button-press and switch back automaically. -- -- NOTE: liable to change, this is essentially just `aroundNext` and -- `layerToggle` combined. layerNext :: LayerTag -> Button layerNext t = onPress $ do layerOp (PushLayer t) await isPress (\_ -> whenDone (layerOp $ PopLayer t) $> NoCatch) -- | Make a button into a sticky-key, i.e. a key that acts like it is -- pressed for the button after it if that button was pressed in the -- given timeframe. stickyKey :: Milliseconds -> Button -> Button stickyKey ms b = onPress go where go :: MonadK m => m () go = hookF InputHook $ \e -> do p <- matchMy Release if | p e -> doTap $> Catch -- My own release; we act as if we were tapped | not (isRelease e) -> doHold e $> Catch -- The press of another button; act like we are held down | otherwise -> go $> NoCatch -- The release of some other button; ignore these doHold :: MonadK m => KeyEvent -> m () doHold e = press b *> inject e doTap :: MonadK m => m () doTap = within ms (pure isPress) -- presses definitely happen after us (pure ()) (\t -> runAction (b^.pressAction) *> inject (t^.event) *> after 3 (runAction $ b^.releaseAction) $> Catch)
null
https://raw.githubusercontent.com/kmonad/kmonad/3413f1be996142c8ef4f36e246776a6df7175979/src/KMonad/Model/Button.hs
haskell
* Button basics $but * Simple buttons $simple * Button combinators $combinators ------------------------------------------------------------------------------ $but 'Press' and another on 'Release'. registered from the OS, and another when a release is registered. ^ Action to take when pressed ^ Action to take when released | Create a 'Button' out of a press and release action NOTE: Since 'AnyK' is an existentially qualified 'MonadK', the monadic actions specified must be runnable by all implementations of 'MonadK', and therefore can only rely on functionality from 'MonadK'. I.e. the actions must be pure 'MonadK'. | Create a new button with only a 'Press' action ------------------------------------------------------------------------------ $running Triggering the actions stored in a 'Button'. | Perform both the press and release of a button immediately | Perform the press action of a Button and register its release callback. This performs the action stored in the 'pressAction' field and registers a callback that will trigger the 'releaseAction' when the release is detected. ------------------------------------------------------------------------------ $simple A collection of simple buttons. These are basically almost direct wrappings around 'MonadK' functionality. released. ^ The button to nest inside `being modded` | Create a button that toggles a layer on and off | Create a button that switches the base-layer on a press | Create a button that adds a layer on a press | Create a button that removes the top instance of a layer on a press | Create a button that does nothing (but captures the input) | Create a button that executes a shell command on press and possibly on release ------------------------------------------------------------------------------ $combinators ^ The outer 'Button' ^ The inner 'Button' ^ The resulting nested 'Button' | A 'Button' that, once pressed, will surround the next button with another. Think of this as, essentially, a tappable mod. For example, an 'aroundNext ^ The outer 'Button' ^ The resulting 'Button' | A 'Button' that, once pressed, will surround the next button within some timeout with another. If some other key is not pressed within an interval another button will be triggered as a tap. ^ How long before we tap ^ The 'Button' to use to surround next ^ The 'Button' to tap on timeout ^ The resulting button | A 'Button' that, once pressed, will surround the next button with another. Think of this as, essentially, a tappable mod. For example, an 'aroundNext This differs from 'aroundNext' in that it explicitly releases the modifier original key that was modified to be released itself. ^ The outer 'Button' ^ The resulting 'Button' Wait for the next *event*, regardless of what it is | Create a new button that performs both a press and release of the input button on just a press or release ^ Which 'Switch' should trigger the tap ^ The 'Button' to tap ^ The tapping 'Button' within an interval. If the interval is exceeded, press the other button (and release it when a release is detected). If we catch timeout before release If we catch release before timeout own release, or else switches to holding some other button if the next event is a different keypress. | Like 'tapNext', except that after some interval it switches anyways | Surround some future button with a before and after tap | Create a tap-hold style button that makes its decision based on the next detected release in the following manner: It does all of this while holding processing of other buttons, so time will get rolled back like a TapHold button. If the next event is my own release: we act as if we were tapped If the next event is the release of some button that was held after me we act as if we were held Else, if it is a press, store the keycode and wait again Else, if it is a release of some button held before me, just ignore Behave like a tap is simple: tap the button `t` and release processing we rethrow this release. | Create a tap-hold style button that makes its decision based on the next detected release in the following manner: If we encounter the timeout before any other release, we switch to the specified timeout button, or to the hold button if none is specified. It does all of this while holding processing of other buttons, so time will get rolled back like a TapHold button. If the next event is my own release: act like tapped If the next event is another release that was pressed after me If the next event is a press, store and recurse If the next event is a release of some button pressed before me, recurse | Create a button just like tap-release, but also trigger a hold on presses: If the next event is my own release: we act as if we were tapped If the next event is a press: we act as if we were held Else, if it is a release of some other button, just ignore Behave like a tap Behave like a hold: we rethrow this event after holding. as the next press is registered before the timeout, the multiTap descends into its list. The moment a delay is exceeded or immediately upon reaching the last button, that button is pressed. This is a bit complicated. What we do is: list and we are done. 2B. If we do detect the release of the key that triggered this action, we must now keep waiting to detect another press. 2C. If we detect another (unrelated) press event we cancel the remaining of the multi-tap sequence and trigger a tap on the current button of the sequence. we know a tap occurred, so we tap the current button and we are done. 3B. If we detect another press of the same key, then the user is descending into the buttons tied to this multi-tap, so we recurse on the remaining buttons. 3C. If we detect any other (unrelated) press event, then the multi-tap button of the sequence. | Create a 'Button' that performs a series of taps on press. Note that the | Create a 'Button' that performs a series of taps on press, except for the last Button, which is tapped on release. | Switch to a layer for a period of time, then automatically switch back | Switch to a layer for the next button-press and switch back automaically. NOTE: liable to change, this is essentially just `aroundNext` and `layerToggle` combined. | Make a button into a sticky-key, i.e. a key that acts like it is pressed for the button after it if that button was pressed in the given timeframe. My own release; we act as if we were tapped The press of another button; act like we are held down The release of some other button; ignore these presses definitely happen after us
| Module : KMonad . Model . Button Description : How buttons work Copyright : ( c ) , 2019 License : MIT Maintainer : Stability : experimental Portability : portable A button contains 2 actions , one to perform on press , and another to perform on release . This module contains that definition , and some helper code that helps combine buttons . It is here that most of the complicated ` buttons are implemented ( like TapHold ) . Module : KMonad.Model.Button Description : How buttons work Copyright : (c) David Janssen, 2019 License : MIT Maintainer : Stability : experimental Portability : portable A button contains 2 actions, one to perform on press, and another to perform on release. This module contains that definition, and some helper code that helps combine buttons. It is here that most of the complicated` buttons are implemented (like TapHold). -} module KMonad.Model.Button Button , HasButton(..) , onPress , onRelease , mkButton , around , tapOn , emitB , pressOnly , releaseOnly , modded , layerToggle , layerSwitch , layerAdd , layerRem , pass , cmdButton , aroundNext , aroundNextTimeout , aroundNextSingle , beforeAfterNext , layerDelay , layerNext , tapHold , multiTap , tapNext , tapHoldNext , tapNextRelease , tapHoldNextRelease , tapNextPress , tapMacro , tapMacroRelease , stickyKey ) where import KMonad.Prelude import KMonad.Model.Action import KMonad.Keyboard import KMonad.Util This section contains the basic definition of KMonad 's ' Button ' datatype . A ' Button ' is essentially a collection of 2 different actions , 1 to perform on | A ' Button ' consists of two ' MonadK ' actions , one to take when a press is data Button = Button } makeClassy ''Button mkButton :: AnyK () -> AnyK () -> Button mkButton a b = Button (Action a) (Action b) onPress :: AnyK () -> Button onPress p = mkButton p $ pure () onRelease :: AnyK () -> Button onRelease = mkButton (pure ()) tap :: MonadK m => Button -> m () tap b = do runAction $ b^.pressAction runAction $ b^.releaseAction press :: MonadK m => Button -> m () press b = do runAction $ b^.pressAction awaitMy Release $ do runAction $ b^.releaseAction pure Catch | A button that emits a Press of a keycode when pressed , and a release when emitB :: Keycode -> Button emitB c = mkButton (emit $ mkPress c) (emit $ mkRelease c) | A button that emits only a Press of a keycode . pressOnly :: Keycode -> Button pressOnly c = onPress $ emit $ mkPress c | A button that emits only a Release of a keycode . releaseOnly :: Keycode -> Button releaseOnly c = onPress $ emit $ mkRelease c | Create a new button that first presses a ' ' before running an inner button , releasing the ' ' again after the inner ' Button ' is released . modded :: ^ The ' ' to ` wrap around ` the inner button -> Button modded modder = around (emitB modder) layerToggle :: LayerTag -> Button layerToggle t = mkButton (layerOp $ PushLayer t) (layerOp $ PopLayer t) layerSwitch :: LayerTag -> Button layerSwitch t = onPress (layerOp $ SetBaseLayer t) layerAdd :: LayerTag -> Button layerAdd t = onPress (layerOp $ PushLayer t) layerRem :: LayerTag -> Button layerRem t = onPress (layerOp $ PopLayer t) pass :: Button pass = onPress $ pure () cmdButton :: Text -> Maybe Text -> Button cmdButton pr mbR = mkButton (shellCmd pr) (maybe (pure ()) shellCmd mbR) Functions that take ' 's and combine them to form new ' Button 's . | Create a new button from 2 buttons , an inner and an outer . When the new button is pressed , first the outer is pressed , then the inner . On release , the inner is released first , and then the outer . around :: around outer inner = Button (Action (runAction (outer^.pressAction) *> runAction (inner^.pressAction))) (Action (runAction (inner^.releaseAction) *> runAction (outer^.releaseAction))) KeyCtrl ' would , once tapped , then make the next keypress C-<whatever > . aroundNext :: aroundNext b = onPress $ await isPress $ \e -> do runAction $ b^.pressAction await (isReleaseOf $ e^.keycode) $ \_ -> do runAction $ b^.releaseAction pure NoCatch pure NoCatch aroundNextTimeout :: aroundNextTimeout d b t = onPress $ within d (pure isPress) (tap t) $ \trig -> do runAction $ b^.pressAction await (isReleaseOf $ trig^.event.keycode) $ \_ -> do runAction $ b^.releaseAction pure NoCatch pure NoCatch KeyCtrl ' would , once tapped , then make the next keypress C-<whatever > . immediately after the first event , where ` aroundSingle ` waits around for the aroundNextSingle :: aroundNextSingle b = onPress $ await isPress $ \_ -> do runAction $ b^.pressAction await (pure True) $ \_ -> do runAction $ b^.releaseAction pure NoCatch pure NoCatch tapOn :: tapOn Press b = mkButton (tap b) (pure ()) tapOn Release b = mkButton (pure ()) (tap b) | Create a ' Button ' that performs a tap of one button if it is released tapHold :: Milliseconds -> Button -> Button -> Button tapHold ms t h = onPress $ withinHeld ms (matchMy Release) | Create a ' Button ' that performs a tap of 1 button if the next event is its tapNext :: Button -> Button -> Button tapNext t h = onPress $ hookF InputHook $ \e -> do p <- matchMy Release if p e then tap t $> Catch else press h $> NoCatch tapHoldNext :: Milliseconds -> Button -> Button -> Maybe Button -> Button tapHoldNext ms t h mtb = onPress $ within ms (pure $ const True) onTimeout $ \tr -> do p <- matchMy Release if p $ tr^.event then tap t $> Catch else press h $> NoCatch where onTimeout :: MonadK m => m () onTimeout = press $ fromMaybe h mtb beforeAfterNext :: Button -> Button -> Button beforeAfterNext b a = onPress $ do tap b await isPress $ \e -> do await (isReleaseOf $ e^.keycode) $ \_ -> do tap a pure NoCatch pure NoCatch 1 . It is the release of this button : We are tapping 2 . It is of some other button that was pressed * before * this one , ignore . 3 . It is of some other button that was pressed * after * this one , we hold . tapNextRelease :: Button -> Button -> Button tapNextRelease t h = onPress $ do hold True go [] where go :: MonadK m => [Keycode] -> m () go ks = hookF InputHook $ \e -> do p <- matchMy Release let isRel = isRelease e if | p e -> doTap | isRel && (e^.keycode `elem` ks) -> doHold e | not isRel -> go ((e^.keycode):ks) $> NoCatch | otherwise -> go ks $> NoCatch doTap :: MonadK m => m Catch doTap = tap t *> hold False $> Catch Behave like a hold is not simple : first we release the processing hold , then we catch the release of ButtonX that triggered this action , and then doHold :: MonadK m => KeyEvent -> m Catch doHold e = press h *> hold False *> inject e $> Catch 1 . It is the release of this button : We are tapping 2 . It is of some other button that was pressed * before * this one , ignore . 3 . It is of some other button that was pressed * after * this one , we hold . tapHoldNextRelease :: Milliseconds -> Button -> Button -> Maybe Button -> Button tapHoldNextRelease ms t h mtb = onPress $ do hold True go ms [] where go :: MonadK m => Milliseconds -> [Keycode] -> m () go ms' ks = tHookF InputHook ms' onTimeout $ \r -> do p <- matchMy Release let e = r^.event let isRel = isRelease e if | p e -> onRelSelf | isRel && (e^.keycode `elem` ks) -> onRelOther e | not isRel -> go (ms' - r^.elapsed) (e^.keycode : ks) $> NoCatch | otherwise -> go (ms' - r^.elapsed) ks $> NoCatch onTimeout :: MonadK m => m () onTimeout = press (fromMaybe h mtb) *> hold False onRelSelf :: MonadK m => m Catch onRelSelf = tap t *> hold False $> Catch onRelOther :: MonadK m => KeyEvent -> m Catch onRelOther e = press h *> hold False *> inject e $> Catch 1 . It is the release of this button : We are tapping 2 . It is the press of some other button , we hold 3 . It is the release of some other button , ignore . tapNextPress :: Button -> Button -> Button tapNextPress t h = onPress go where go :: MonadK m => m () go = hookF InputHook $ \e -> do p <- matchMy Release if | p e -> doTap | isPress e -> doHold e | otherwise -> go $> NoCatch doTap :: MonadK m => m Catch doTap = tap t $> Catch We catch the event of ButtonX that triggered this action , and then doHold :: MonadK m => KeyEvent -> m Catch doHold e = press h *> inject e $> Catch | Create a ' Button ' that contains a number of delays and ' 's . As long multiTap :: Button -> [(Milliseconds, Button)] -> Button multiTap l bs = onPress $ go bs where go :: [(Milliseconds, Button)] -> AnyK () go [] = press l go ((ms, b):bs') = do 1 . We wait for an event 2A. If it does n't occur in the interval we press the button from the 3A. After 2B , if we do not detect a press before the interval is up , sequence is cancelled like in 2C. We trigger a tap of the current let doNext pred onTimeout next ms = tHookF InputHook ms onTimeout $ \t -> do pr <- pred if | pr (t^.event) -> next (ms - t^.elapsed) $> Catch | isPress (t^.event) -> tap b $> NoCatch | otherwise -> pure NoCatch doNext (matchMy Release) (press b) (doNext (matchMy Press) (tap b) (\_ -> go bs')) ms last button is only released when the tapMacro itself is released . tapMacro :: [Button] -> Button tapMacro bs = onPress $ go bs where go [] = pure () go [b] = press b go (b:rst) = tap b >> go rst tapMacroRelease :: [Button] -> Button tapMacroRelease bs = onPress $ go bs where go [] = pure () go [b] = awaitMy Release $ tap b >> pure Catch go (b:rst) = tap b >> go rst layerDelay :: Milliseconds -> LayerTag -> Button layerDelay d t = onPress $ do layerOp (PushLayer t) after d (layerOp $ PopLayer t) layerNext :: LayerTag -> Button layerNext t = onPress $ do layerOp (PushLayer t) await isPress (\_ -> whenDone (layerOp $ PopLayer t) $> NoCatch) stickyKey :: Milliseconds -> Button -> Button stickyKey ms b = onPress go where go :: MonadK m => m () go = hookF InputHook $ \e -> do p <- matchMy Release if | p e -> doTap $> Catch | not (isRelease e) -> doHold e $> Catch | otherwise -> go $> NoCatch doHold :: MonadK m => KeyEvent -> m () doHold e = press b *> inject e doTap :: MonadK m => m () doTap = within ms (pure ()) (\t -> runAction (b^.pressAction) *> inject (t^.event) *> after 3 (runAction $ b^.releaseAction) $> Catch)
a9c1c05ec536e2f0c021b60bfa5fd4448d36b39e5578c45aec33036939082826
furkan3ayraktar/clojure-polylith-realworld-example-app
interface.clj
(ns clojure.realworld.comment.interface (:require [clojure.realworld.comment.core :as core])) (defn article-comments [auth-user slug] (core/article-comments auth-user slug)) (defn add-comment! [auth-user slug comment] (core/add-comment! auth-user slug comment)) (defn delete-comment! [auth-user id] (core/delete-comment! auth-user id))
null
https://raw.githubusercontent.com/furkan3ayraktar/clojure-polylith-realworld-example-app/2f16552fb4e9a56e24e21795cbb038433085453c/components/comment/src/clojure/realworld/comment/interface.clj
clojure
(ns clojure.realworld.comment.interface (:require [clojure.realworld.comment.core :as core])) (defn article-comments [auth-user slug] (core/article-comments auth-user slug)) (defn add-comment! [auth-user slug comment] (core/add-comment! auth-user slug comment)) (defn delete-comment! [auth-user id] (core/delete-comment! auth-user id))
6ee11560d9c37331208e8473aeea46f036c554f00bbcd7f9e42f4e23227ff479
jacius/lispbuilder
gfx-library.lisp
;;; -*- lisp -*- (in-package #:lispbuilder-sdl-cffi) cffi : foreign - library - loaded - p is not yet in the released version of CFFI ;;(defparameter *image-loaded-p* (cffi:foreign-library-loaded-p 'sdl-image)) (defparameter *gfx-loaded-p* nil) (cffi:define-foreign-library sdl-gfx (:darwin (:or "libSDL_gfx.dylib" (:framework "SDL_gfx"))) (:windows "SDL_gfx.dll") (:unix (:or "libSDL_gfx" "libSDL_gfx.so" "libSDL_gfx.so.4" "libSDL_gfx.so.13" "libSDL_gfx.so.13.0.0"))) (defun load-gfx-library () (setf *gfx-loaded-p* nil) (when (handler-case (cffi:use-foreign-library sdl-gfx) (load-foreign-library-error () nil)) (setf *gfx-loaded-p* t) (pushnew :lispbuilder-sdl-gfx *features*))) (eval-when (:load-toplevel :execute) (load-gfx-library))
null
https://raw.githubusercontent.com/jacius/lispbuilder/e693651b95f6818e3cab70f0074af9f9511584c3/lispbuilder-sdl/sdl-gfx/gfx-library.lisp
lisp
-*- lisp -*- (defparameter *image-loaded-p* (cffi:foreign-library-loaded-p 'sdl-image))
(in-package #:lispbuilder-sdl-cffi) cffi : foreign - library - loaded - p is not yet in the released version of CFFI (defparameter *gfx-loaded-p* nil) (cffi:define-foreign-library sdl-gfx (:darwin (:or "libSDL_gfx.dylib" (:framework "SDL_gfx"))) (:windows "SDL_gfx.dll") (:unix (:or "libSDL_gfx" "libSDL_gfx.so" "libSDL_gfx.so.4" "libSDL_gfx.so.13" "libSDL_gfx.so.13.0.0"))) (defun load-gfx-library () (setf *gfx-loaded-p* nil) (when (handler-case (cffi:use-foreign-library sdl-gfx) (load-foreign-library-error () nil)) (setf *gfx-loaded-p* t) (pushnew :lispbuilder-sdl-gfx *features*))) (eval-when (:load-toplevel :execute) (load-gfx-library))
594c9a8dd2fd676618b0babce840190a420632b01436a0d256030d321f8af3d2
eliaslfox/language-elm
Declaration.hs
{-# OPTIONS_HADDOCK prune #-} {-# OPTIONS_GHC -Wall -Werror #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE Safe #-} -- | Top level declerations module Elm.Declaration where import Elm.Classes import Elm.Expression import Elm.Type import Text.PrettyPrint -- | Used to declare functions, variables, and types data Dec -- | Declare a function = Dec String TypeDec [Expr] Expr -- | Declare a type | DecType String [String] [(String, [TypeDec])] -- | Declare a type alias | DecTypeAlias String [String] TypeDec instance Generate Dec where generate dec = case dec of Dec name type_ params value -> do typeDoc <- generate type_ paramDocs <- mapM generate params valueDoc <- generate value return $ text name <+> ":" <+> typeDoc $+$ text name <+> hsep paramDocs <+> "=" $+$ nest 4 valueDoc DecType name params instances -> do let (keys, values) = unzip instances let keyDocs = map text keys valueDocs <- mapM (mapM generate) values let instanceDocs = map (\(key, values') -> key <+> hsep values') $ zip keyDocs valueDocs let paramDocs = map text params return $ "type" <+> text name <+> hsep paramDocs $+$ (nest 4 $ "=" <+> head instanceDocs $+$ (vcat . map ((<+>)"|") . tail $ instanceDocs)) DecTypeAlias name params type_ -> do typeDoc <- generate type_ let paramDocs = map text params return $ "type alias" <+> text name <+> hsep paramDocs <+> "=" $+$ nest 4 typeDoc
null
https://raw.githubusercontent.com/eliaslfox/language-elm/df39d2fc4d14f3d4431411ca5eb030a887c4eb6b/src/Elm/Declaration.hs
haskell
# OPTIONS_HADDOCK prune # # OPTIONS_GHC -Wall -Werror # # LANGUAGE OverloadedStrings # # LANGUAGE Safe # | Top level declerations | Used to declare functions, variables, and types | Declare a function | Declare a type | Declare a type alias
module Elm.Declaration where import Elm.Classes import Elm.Expression import Elm.Type import Text.PrettyPrint data Dec = Dec String TypeDec [Expr] Expr | DecType String [String] [(String, [TypeDec])] | DecTypeAlias String [String] TypeDec instance Generate Dec where generate dec = case dec of Dec name type_ params value -> do typeDoc <- generate type_ paramDocs <- mapM generate params valueDoc <- generate value return $ text name <+> ":" <+> typeDoc $+$ text name <+> hsep paramDocs <+> "=" $+$ nest 4 valueDoc DecType name params instances -> do let (keys, values) = unzip instances let keyDocs = map text keys valueDocs <- mapM (mapM generate) values let instanceDocs = map (\(key, values') -> key <+> hsep values') $ zip keyDocs valueDocs let paramDocs = map text params return $ "type" <+> text name <+> hsep paramDocs $+$ (nest 4 $ "=" <+> head instanceDocs $+$ (vcat . map ((<+>)"|") . tail $ instanceDocs)) DecTypeAlias name params type_ -> do typeDoc <- generate type_ let paramDocs = map text params return $ "type alias" <+> text name <+> hsep paramDocs <+> "=" $+$ nest 4 typeDoc
ccabae07f0295bf3f1eafda5fec3c5e49cec1b32fa65f5de07f5576bff093019
jguhlin/ODG
annotation.clj
(ns odg.annotation (:import (org.neo4j.graphdb Transaction) (org.neo4j.unsafe.batchinsert BatchInserterIndex)) (:require clojure.java.io clojure.string [clojure.core.reducers :as r] [odg.util :as util] [odg.db :as db] [biotools.gff :as gff] [biotools.gtf :as gtf] [odg.batch :as batch] [taoensso.timbre :as timbre] [co.paralleluniverse.pulsar.core :as p])) (timbre/refer-timbre) ; Need to make individual get-gene-node type fn's return a promise and be put into a fiber ; so that nothing gets held up and no fiber is allowed to go for too long.. ; reminder for debugging (defn generic-entry [id type start end strand phase landmark species version note additional-data] (merge additional-data ; Should always be overwritten by passed arguments {:id id :type type :start start :end end :strand strand :phase phase :landmark landmark :note note :species species :version version})) (p/defsfn get-exon-node "Checks for the existence of the exon node and creates it, if necessary. If it is created it is connected to its parent transcript/mRNA node as well" [create-fn idx-query entry transcript] (let [exon-id (str (:oid entry) "_exon_" (:exon_number entry)) db-entry (idx-query exon-id)] (if-not @db-entry (let [exon (create-fn ; Create the gene entry (generic-entry exon-id "exon" (:start entry) (:end entry) (:strand entry) (:phase entry) (:landmark entry) (:species entry) (:version entry) "Autogenerated from GTF import" entry))] ;(batch/create-rel transcript exon (:PARENT_OF db/rels)) exon) db-entry))) ; UPDATED FOR ACTOR SYSTEM ; BUT UNTESTED (defn import-gtf "Batch import GTF file into existing database. Differs very little over the GFF parser. Has additional support for creating gene records, however. Designed for cufflinks created GTF files at this time." [species version filename] (let [species-label (batch/dynamic-label species) version-label (batch/dynamic-label (str species " " version)) labels (partial into [species-label version-label]) species_ver_root 1] (println "Importing GTF annotation for" species version "from" filename) (with-open [rdr (clojure.java.io/reader filename)] (let [all-entries (group-by (memoize (fn [x] (util/remove-transcript-id (:oid x)))) (vec (gtf/parse-reader-reducer rdr)))] (merge {:indices [(batch/convert-name species version)]} (apply merge-with concat (for [[gene-id entries] all-entries] (when (and gene-id (seq entries)) {:nodes-create-if-new (distinct (concat ; Create "gene" node (if necessary) (list (let [entry (first entries)] [{:id gene-id :start (apply min (remove nil? (map :start entries))) :end (apply max (remove nil? (map :end entries))) :note "Autogenerated from GTF file" :strand (:strand entry) :phase (:phase entry) :landmark (:landmark entry) :species species :version version :cufflinks_gene_id (:gene_id entry)} (labels [(:GENE batch/labels) (:ANNOTATION batch/labels)]) ; optional rels to create if node is created (for [landmark (util/get-landmarks (:landmark entry) (apply min (remove nil? (map :start entries))) (apply max (remove nil? (map :end entries))))] [(:LOCATED_ON db/rels) gene-id landmark])])) ; Create transcript nodes if necessary (distinct (for [[transcript-id transcript-entries] (group-by :oid entries)] [{:id transcript-id :start (apply min (map :start entries)) :end (apply max (map :end entries)) :species species :version version :note "Autogenerated from GTF import" :cufflinks_gene_id (:gene_id (first entries)) :transcript_id (:transcript_id (first entries))} (labels [(:MRNA batch/labels) (:ANNOTATION batch/labels)]) [(:PARENT_OF db/rels) gene-id transcript-id]]))))})))))))) ; TODO: Also check or add exon nodes from GTF files! Not priority (defn import-gtf-cli "Import annotation - helper fn for when run from the command-line (opposed to entire database generation)" [config opts args] ; (batch/connect (get-in config [:global :db_path] (:memory opts))) (import-gtf (:species opts) (:version opts) (first args))) (defn create-missing-mRNA-from-CDS [entries] (for [[node-def labels] (filter (fn [x] (= (:type (first x)) "CDS")) entries)] [[(assoc node-def :type "mRNA" :id (str (:id node-def) ".mRNA") :transcript_id (str (:id node-def)) :autogenerated "Autogenerated by ODG, mRNA entries not found in GFF3 file") (conj (remove (fn [x] (= x (batch/dynamic-label "CDS"))) labels) (batch/dynamic-label "mRNA"))] [[(:PARENT_OF db/rels) (str (:id node-def) ".mRNA") (:id node-def)]]])) (defn create-missing-genes-from-mRNA [entries] (for [[node-def labels] (filter (fn [x] (= (:type (first x)) "mRNA")) entries)] [[(assoc node-def :type "gene" :gene_id (clojure.string/replace (:id node-def) ".mRNA" "") :id (str (clojure.string/replace (:id node-def) ".mRNA" "") ".gene") :autogenerated "Autogenerated by ODG, Gene entries not found in GFF3 file") (conj (remove (fn [x] (= x (batch/dynamic-label "mRNA"))) labels) (batch/dynamic-label "gene"))] (conj (for [landmark (util/get-landmarks (:landmark node-def) (:start node-def) (:end node-def))] [(:LOCATED_ON db/rels) (str (clojure.string/replace (:id node-def) ".mRNA" "") ".gene") (:landmark node-def)]) [(:PARENT_OF db/rels) (str (clojure.string/replace (:id node-def) ".mRNA" "") ".gene") (:id node-def)])])) (defn fix-annotations [x] (let [types (set (distinct (map (comp :type first) (:nodes x)))) new-mrna-entries (when (and (get types "CDS")) (not (get types "mRNA")) (create-missing-mRNA-from-CDS (:nodes x))) merge-mrna (fn [x] (if new-mrna-entries (assoc x :nodes (concat (into [] (map first new-mrna-entries)) (:nodes x)) :rels (concat (apply concat (map second new-mrna-entries)) (:rels x))) x)) y (merge-mrna x) new-gene-entries (when (not (get types "gene")) (create-missing-genes-from-mRNA (:nodes y))) merge-genes (fn [x] (if new-gene-entries (assoc x :nodes (concat (map first new-gene-entries) (:nodes x)) :rels (concat (apply concat (map second new-gene-entries)) (:rels x))) x))] (merge-genes y))) ; NEW - actor based system (defn import-gff "Batch import GFF file into existing database." [species version filename] (info "Importing annotation for" species version filename) ; Keep the reader outside to facilitate automatic closing of the file (let [species-label (batch/dynamic-label species) version-label (batch/dynamic-label (str species " " version)) labels (partial into [species-label version-label]) species_ver_root 1] ; TODO: Fix me! (with-open [rdr (clojure.java.io/reader filename)] (let [current-ids (atom (hash-set)) entries (doall (map #(batch/gen-id current-ids %) (gff/parse-reader rdr))) ; make unique IDs, when necessary final-ids (set (map :id entries)) ; get the final list of IDs job {:species species :version version :nodes (into [] (for [entry entries] [(reduce-kv #(assoc %1 %2 (if (string? %3) (java.net.URLDecoder/decode %3) %3)) {} (merge entry {:species species :version version})) (labels [(:ANNOTATION batch/labels) (batch/dynamic-label (:type entry))])])) :rels (into [] (concat ; Parental relationships GFF entries with a parent attribute parent-id (clojure.string/split (:parent entry) #",")] [(:PARENT_OF db/rels) parent-id (:id entry)]) Located_on relationships Connect to landmarks ( when appropriate ) landmark (util/get-landmarks (:landmark entry) (:start entry) (:end entry)) :when (not (:parent entry))] ; Store a LOCATED_ON relationship when there is no parental relationship [(:LOCATED_ON db/rels) (:id entry) landmark]))) :indices [(batch/convert-name species version)]}] (fix-annotations job))))) (defn import-gff-cli "Import annotation - helper fn for when run from the command-line (opposed to entire database generation)" [config opts args] ;(batch/connect (get-in config [:global :db_path]) (:memory opts)) (import-gff (:species opts) (:version opts) (first args))) ; This fn does not run in batch mode. CYPHER does not work on batch databases ; this is still fast enough of an operation to run independently . ; change anything (defn create-gene-neighbors "Works on all species in the database at once. Does not function in batch mode. Incompatabile with batch operation database." ;;; [config opts args] [config opts _] (println "Creating NEXT_TO relationships for all genomes") (db/connect (get-in config [:global :db_path]) (:memory opts)) Get ordered list by chr , ignore strandedness , sort by gene.start (db/query (str "MATCH (x:Landmark) <-[:LOCATED_ON]- (:LandmarkHash) <-[:LOCATED_ON]-(gene) WHERE gene:gene OR gene:Annotation RETURN x.species, x.version, x.id, gene ORDER BY x.species, x.version, x.id, gene.start") {} (println "Results obtained, now creating relationships...") (doseq [[[species version id] genes] (group-by (fn [x] [(get x "x.species") (get x "x.version") (get x "x.id")]) results)] (doseq [[a b] (partition 2 1 genes)] ; We are in a transaction, so don't use db/create-relationship here! (.createRelationshipTo (get a "gene") (get b "gene") (:NEXT_TO db/rels))))))
null
https://raw.githubusercontent.com/jguhlin/ODG/c8a09f273c278ba7b3acbd37155477979f8b4851/src/odg/annotation.clj
clojure
Need to make individual get-gene-node type fn's return a promise and be put into a fiber so that nothing gets held up and no fiber is allowed to go for too long.. reminder for debugging Should always be overwritten by passed arguments Create the gene entry (batch/create-rel transcript exon (:PARENT_OF db/rels)) UPDATED FOR ACTOR SYSTEM BUT UNTESTED Create "gene" node (if necessary) optional rels to create if node is created Create transcript nodes if necessary TODO: Also check or add exon nodes from GTF files! Not priority (batch/connect (get-in config [:global :db_path] (:memory opts))) NEW - actor based system Keep the reader outside to facilitate automatic closing of the file TODO: Fix me! make unique IDs, when necessary get the final list of IDs Parental relationships Store a LOCATED_ON relationship when there is no parental relationship (batch/connect (get-in config [:global :db_path]) (:memory opts)) This fn does not run in batch mode. this is still fast enough of an operation to run independently . change anything [config opts args] We are in a transaction, so don't use db/create-relationship here!
(ns odg.annotation (:import (org.neo4j.graphdb Transaction) (org.neo4j.unsafe.batchinsert BatchInserterIndex)) (:require clojure.java.io clojure.string [clojure.core.reducers :as r] [odg.util :as util] [odg.db :as db] [biotools.gff :as gff] [biotools.gtf :as gtf] [odg.batch :as batch] [taoensso.timbre :as timbre] [co.paralleluniverse.pulsar.core :as p])) (timbre/refer-timbre) (defn generic-entry [id type start end strand phase landmark species version note additional-data] (merge {:id id :type type :start start :end end :strand strand :phase phase :landmark landmark :note note :species species :version version})) (p/defsfn get-exon-node "Checks for the existence of the exon node and creates it, if necessary. If it is created it is connected to its parent transcript/mRNA node as well" [create-fn idx-query entry transcript] (let [exon-id (str (:oid entry) "_exon_" (:exon_number entry)) db-entry (idx-query exon-id)] (if-not @db-entry (let [exon (create-fn (generic-entry exon-id "exon" (:start entry) (:end entry) (:strand entry) (:phase entry) (:landmark entry) (:species entry) (:version entry) "Autogenerated from GTF import" entry))] exon) db-entry))) (defn import-gtf "Batch import GTF file into existing database. Differs very little over the GFF parser. Has additional support for creating gene records, however. Designed for cufflinks created GTF files at this time." [species version filename] (let [species-label (batch/dynamic-label species) version-label (batch/dynamic-label (str species " " version)) labels (partial into [species-label version-label]) species_ver_root 1] (println "Importing GTF annotation for" species version "from" filename) (with-open [rdr (clojure.java.io/reader filename)] (let [all-entries (group-by (memoize (fn [x] (util/remove-transcript-id (:oid x)))) (vec (gtf/parse-reader-reducer rdr)))] (merge {:indices [(batch/convert-name species version)]} (apply merge-with concat (for [[gene-id entries] all-entries] (when (and gene-id (seq entries)) {:nodes-create-if-new (distinct (concat (list (let [entry (first entries)] [{:id gene-id :start (apply min (remove nil? (map :start entries))) :end (apply max (remove nil? (map :end entries))) :note "Autogenerated from GTF file" :strand (:strand entry) :phase (:phase entry) :landmark (:landmark entry) :species species :version version :cufflinks_gene_id (:gene_id entry)} (labels [(:GENE batch/labels) (:ANNOTATION batch/labels)]) (for [landmark (util/get-landmarks (:landmark entry) (apply min (remove nil? (map :start entries))) (apply max (remove nil? (map :end entries))))] [(:LOCATED_ON db/rels) gene-id landmark])])) (distinct (for [[transcript-id transcript-entries] (group-by :oid entries)] [{:id transcript-id :start (apply min (map :start entries)) :end (apply max (map :end entries)) :species species :version version :note "Autogenerated from GTF import" :cufflinks_gene_id (:gene_id (first entries)) :transcript_id (:transcript_id (first entries))} (labels [(:MRNA batch/labels) (:ANNOTATION batch/labels)]) [(:PARENT_OF db/rels) gene-id transcript-id]]))))})))))))) (defn import-gtf-cli "Import annotation - helper fn for when run from the command-line (opposed to entire database generation)" [config opts args] (import-gtf (:species opts) (:version opts) (first args))) (defn create-missing-mRNA-from-CDS [entries] (for [[node-def labels] (filter (fn [x] (= (:type (first x)) "CDS")) entries)] [[(assoc node-def :type "mRNA" :id (str (:id node-def) ".mRNA") :transcript_id (str (:id node-def)) :autogenerated "Autogenerated by ODG, mRNA entries not found in GFF3 file") (conj (remove (fn [x] (= x (batch/dynamic-label "CDS"))) labels) (batch/dynamic-label "mRNA"))] [[(:PARENT_OF db/rels) (str (:id node-def) ".mRNA") (:id node-def)]]])) (defn create-missing-genes-from-mRNA [entries] (for [[node-def labels] (filter (fn [x] (= (:type (first x)) "mRNA")) entries)] [[(assoc node-def :type "gene" :gene_id (clojure.string/replace (:id node-def) ".mRNA" "") :id (str (clojure.string/replace (:id node-def) ".mRNA" "") ".gene") :autogenerated "Autogenerated by ODG, Gene entries not found in GFF3 file") (conj (remove (fn [x] (= x (batch/dynamic-label "mRNA"))) labels) (batch/dynamic-label "gene"))] (conj (for [landmark (util/get-landmarks (:landmark node-def) (:start node-def) (:end node-def))] [(:LOCATED_ON db/rels) (str (clojure.string/replace (:id node-def) ".mRNA" "") ".gene") (:landmark node-def)]) [(:PARENT_OF db/rels) (str (clojure.string/replace (:id node-def) ".mRNA" "") ".gene") (:id node-def)])])) (defn fix-annotations [x] (let [types (set (distinct (map (comp :type first) (:nodes x)))) new-mrna-entries (when (and (get types "CDS")) (not (get types "mRNA")) (create-missing-mRNA-from-CDS (:nodes x))) merge-mrna (fn [x] (if new-mrna-entries (assoc x :nodes (concat (into [] (map first new-mrna-entries)) (:nodes x)) :rels (concat (apply concat (map second new-mrna-entries)) (:rels x))) x)) y (merge-mrna x) new-gene-entries (when (not (get types "gene")) (create-missing-genes-from-mRNA (:nodes y))) merge-genes (fn [x] (if new-gene-entries (assoc x :nodes (concat (map first new-gene-entries) (:nodes x)) :rels (concat (apply concat (map second new-gene-entries)) (:rels x))) x))] (merge-genes y))) (defn import-gff "Batch import GFF file into existing database." [species version filename] (info "Importing annotation for" species version filename) (let [species-label (batch/dynamic-label species) version-label (batch/dynamic-label (str species " " version)) labels (partial into [species-label version-label]) (with-open [rdr (clojure.java.io/reader filename)] (let [current-ids (atom (hash-set)) job {:species species :version version :nodes (into [] (for [entry entries] [(reduce-kv #(assoc %1 %2 (if (string? %3) (java.net.URLDecoder/decode %3) %3)) {} (merge entry {:species species :version version})) (labels [(:ANNOTATION batch/labels) (batch/dynamic-label (:type entry))])])) :rels (into [] (concat GFF entries with a parent attribute parent-id (clojure.string/split (:parent entry) #",")] [(:PARENT_OF db/rels) parent-id (:id entry)]) Located_on relationships Connect to landmarks ( when appropriate ) landmark (util/get-landmarks (:landmark entry) (:start entry) (:end entry)) [(:LOCATED_ON db/rels) (:id entry) landmark]))) :indices [(batch/convert-name species version)]}] (fix-annotations job))))) (defn import-gff-cli "Import annotation - helper fn for when run from the command-line (opposed to entire database generation)" [config opts args] (import-gff (:species opts) (:version opts) (first args))) (defn create-gene-neighbors "Works on all species in the database at once. Does not function in batch mode. Incompatabile with batch operation database." [config opts _] (println "Creating NEXT_TO relationships for all genomes") (db/connect (get-in config [:global :db_path]) (:memory opts)) Get ordered list by chr , ignore strandedness , sort by gene.start (db/query (str "MATCH (x:Landmark) <-[:LOCATED_ON]- (:LandmarkHash) <-[:LOCATED_ON]-(gene) WHERE gene:gene OR gene:Annotation RETURN x.species, x.version, x.id, gene ORDER BY x.species, x.version, x.id, gene.start") {} (println "Results obtained, now creating relationships...") (doseq [[[species version id] genes] (group-by (fn [x] [(get x "x.species") (get x "x.version") (get x "x.id")]) results)] (doseq [[a b] (partition 2 1 genes)] (.createRelationshipTo (get a "gene") (get b "gene") (:NEXT_TO db/rels))))))
fbd9f8df493c6fdff036b4dde1b322bf57b4e28aa3718deec98405add972d75f
aggelgian/erlang-algorithms
a_star_demo.erl
-module(a_star_demo). -export([b1/0, dump_vertex/1]). %% The representation of a vertex. -type my_vertex() :: {integer(), integer()}. -spec b1() -> ok. b1() -> File = ?DEMO_DATA ++ "/board1.txt", Heurestic underestimate function F = fun({X1, Y1}, {X2, Y2}) -> abs(X1 - X2) + abs(Y1 - Y2) end, G = graph:import(File, fun parse_vertex/1), {Cost, Path} = a_star:run(G, {1,1}, {6,6}, F), io:format("Cost: ~p~nPath: ~p~n", [Cost, Path]). %% Parses the string that holds a vertex. -spec parse_vertex(string()) -> my_vertex(). parse_vertex([$(, X, $,, Y, $)]) -> {X - $0, Y - $0}. %% Dumps a vertex to a string. -spec dump_vertex(my_vertex()) -> string(). dump_vertex({X, Y}) -> [$(, X + $0, $,, Y + $0, $)].
null
https://raw.githubusercontent.com/aggelgian/erlang-algorithms/8ceee72146f2a6eff70a16e3e9a74d2ed072fa0a/demo/src/a_star_demo.erl
erlang
The representation of a vertex. Parses the string that holds a vertex. Dumps a vertex to a string.
-module(a_star_demo). -export([b1/0, dump_vertex/1]). -type my_vertex() :: {integer(), integer()}. -spec b1() -> ok. b1() -> File = ?DEMO_DATA ++ "/board1.txt", Heurestic underestimate function F = fun({X1, Y1}, {X2, Y2}) -> abs(X1 - X2) + abs(Y1 - Y2) end, G = graph:import(File, fun parse_vertex/1), {Cost, Path} = a_star:run(G, {1,1}, {6,6}, F), io:format("Cost: ~p~nPath: ~p~n", [Cost, Path]). -spec parse_vertex(string()) -> my_vertex(). parse_vertex([$(, X, $,, Y, $)]) -> {X - $0, Y - $0}. -spec dump_vertex(my_vertex()) -> string(). dump_vertex({X, Y}) -> [$(, X + $0, $,, Y + $0, $)].
de72437c0bb8d205f305910871b5146627c86b565e1790b1b0f8170846796b2c
binsec/binsec
simplification_dba_prog.ml
(**************************************************************************) This file is part of BINSEC . (* *) Copyright ( C ) 2016 - 2022 CEA ( Commissariat à l'énergie atomique et aux énergies (* alternatives) *) (* *) (* you can redistribute it and/or modify it under the terms of the GNU *) Lesser General Public License as published by the Free Software Foundation , version 2.1 . (* *) (* It is distributed in the hope that it will be useful, *) (* but WITHOUT ANY WARRANTY; without even the implied warranty of *) (* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *) (* GNU Lesser General Public License for more details. *) (* *) See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . (* *) (**************************************************************************) open Simplification_dba_utils open Simplification_options let remove_goto m = Logger.debug ~level:3 "Removing gotos ..."; let rec f addr (*(ca, id)*) (ik, opcode) accu = let local_find a = match Dba_types.Caddress.Map.find a accu with | v -> v | exception Not_found -> Dba_types.Caddress.Map.find a m in let open Dba_types in match ik with | Dba.Instr.Assign (_, _, nid) | Dba.Instr.Undef (_, nid) | Dba.Instr.Assume (_, nid) | Dba.Instr.Assert (_, nid) | Dba.Instr.Nondet (_, nid) -> ( try let a = Dba_types.Caddress.reid addr nid in let nik, _ = local_find a in match nik with | Dba.Instr.SJump (Dba.JInner nnid, _) -> f addr (Instruction.set_successor ik nnid, opcode) accu | _ -> Caddress.Map.add addr (ik, opcode) accu with Not_found -> Caddress.Map.add addr (ik, opcode) accu) | Dba.Instr.SJump (Dba.JInner nid, _) -> ( try let a = Dba_types.Caddress.reid addr nid in let nik, nopcode = local_find a in match nik with | Dba.Instr.SJump (Dba.JInner nnid, _) -> f addr (Instruction.set_successor ik nnid, opcode) accu | _ -> if addr.Dba.id = 0 then let accu = Caddress.Map.add a (Instruction.set_successor ik 0, nopcode) accu in f addr (nik, opcode) accu else Caddress.Map.add addr (ik, opcode) accu with Not_found -> Caddress.Map.add addr (ik, opcode) accu) ( nca , nid1 ) try let a = Dba_types.Caddress.reid addr nid2 in let nik, _ = local_find a in match nik with | Dba.Instr.SJump (Dba.JInner nnid, _) -> let inst = Dba.Instr.ite cond (Dba.Jump_target.outer addr') nnid in f addr (inst, opcode) accu | _ -> Caddress.Map.add addr (ik, opcode) accu with Not_found -> Caddress.Map.add addr (ik, opcode) accu) | Dba.Instr.If (cond, Dba.JInner nid1, nid2) -> ( let a1 = Dba_types.Caddress.reid addr nid1 in let a2 = Dba_types.Caddress.reid addr nid2 in let nik1 = try let elt1 = local_find a1 in Some (fst elt1) with Not_found -> None in let nik2 = try let elt2 = local_find a2 in Some (fst elt2) with Not_found -> None in match (nik1, nik2) with | None, None -> Caddress.Map.add addr (ik, opcode) accu | Some nik, None -> ( match nik with | Dba.Instr.SJump (Dba.JInner nnid, _) -> let inst = Dba.Instr.ite cond (Dba.Jump_target.inner nnid) nid2 in f addr (inst, opcode) accu | _ -> Caddress.Map.add addr (ik, opcode) accu) | None, Some nik -> ( match nik with | Dba.Instr.SJump (Dba.JInner nnid, _ntag) -> let inst = Dba.Instr.ite cond (Dba.Jump_target.inner nid1) nnid in f addr (inst, opcode) accu | _ -> Caddress.Map.add addr (ik, opcode) accu) | Some ik1, Some ik2 -> ( let as_ite inner_id succ = Dba.Instr.ite cond (Dba.Jump_target.inner inner_id) succ in match (ik1, ik2) with | ( Dba.Instr.SJump (Dba.JInner nnid1, _), Dba.Instr.SJump (Dba.JInner nnid2, _) ) -> let inst = as_ite nnid1 nnid2 in f addr (inst, opcode) accu | _, Dba.Instr.SJump (Dba.JInner nnid2, _ntag) -> let inst = as_ite nid1 nnid2 in f addr (inst, opcode) accu | Dba.Instr.SJump (Dba.JInner nnid1, _ntag), _ -> let inst = as_ite nnid1 nid2 in f addr (inst, opcode) accu | _, _ -> Caddress.Map.add addr (ik, opcode) accu)) | Dba.Instr.SJump (Dba.JOuter _, _) | Dba.Instr.DJump (_, _) | Dba.Instr.Stop _ -> Caddress.Map.add addr (ik, opcode) accu in let open Dba_types in let m = Caddress.Map.fold f m Caddress.Map.empty in let rec g addr (ik, opcode) accu = if Caddress.Map.mem addr accu then accu else match ik with | Dba.Instr.Assign (_, _, nid) | Dba.Instr.Undef (_, nid) | Dba.Instr.Assume (_, nid) | Dba.Instr.Assert (_, nid) | Dba.Instr.Nondet (_, nid) | Dba.Instr.SJump (Dba.JInner nid, _) -> ( let accu = Caddress.Map.add addr (ik, opcode) accu in try let a = Caddress.reid addr nid in let nik, nopcode = Caddress.Map.find a m in g a (nik, nopcode) accu with Not_found -> accu) | Dba.Instr.If (_, Dba.JOuter _, nid2) -> ( let accu = Caddress.Map.add addr (ik, opcode) accu in try let a = Caddress.reid addr nid2 in g a (Caddress.Map.find a m) accu with Not_found -> accu) | Dba.Instr.If (_cond, Dba.JInner nid1, nid2) -> ( let accu = Caddress.Map.add addr (ik, opcode) accu in let accu = try let a = Caddress.reid addr nid1 in let nik1, _ = Caddress.Map.find a m in g a (nik1, opcode) accu with Not_found -> accu in try let a = Caddress.reid addr nid2 in let nik2, _nopcode = Caddress.Map.find a m in (* FIXME : really ?*) g a (nik2, opcode) accu with Not_found -> accu) | Dba.Instr.SJump (Dba.JOuter _, _) | Dba.Instr.DJump (_, _) | Dba.Instr.Stop _ -> Caddress.Map.add addr (ik, opcode) accu in let g_aux addr e accu = if addr.Dba.id = 0 then g addr e accu else accu in Caddress.Map.fold g_aux m Caddress.Map.empty let remove_mustkill prog env_flags = let look_ahead_limit = 100 in let f addr (ik, opcode) (accu, env_flags, has_changed) = let mk_sjump id = Dba.Instr.static_inner_jump id in let eflags, ik', has_changed = match ik with | Dba.Instr.Assign (lhs, _, id_next) | Dba.Instr.Undef (lhs, id_next) -> let eflags, ik, has_changed = if Dba_types.LValue.is_flag lhs || Dba_types.LValue.is_temporary lhs then let env_flags, has_changed = let a = Dba_types.Caddress.reid addr id_next in is_not_mayused prog a look_ahead_limit lhs env_flags in let ik' = if has_changed then mk_sjump id_next else ik in (env_flags, ik', has_changed) else (env_flags, ik, has_changed) in (eflags, ik, has_changed) | _ -> (env_flags, ik, has_changed) in (Dba_types.Caddress.Map.add addr (ik', opcode) accu, eflags, has_changed) in Dba_types.(Caddress.Map.fold f prog (Caddress.Map.empty, env_flags, false)) let remove_mustkill_lfp inst_map = Logger.debug ~level:3 "Removing mustkills ..."; let rec loop inst_map env_flags = match remove_mustkill inst_map env_flags with | imap, env_flags, true -> loop imap env_flags | imap, _, false -> imap in loop inst_map Dba_types.Caddress.Map.empty
null
https://raw.githubusercontent.com/binsec/binsec/22ee39aad58219e8837b6ba15f150ba04a498b63/src/disasm/simplify/simplification_dba_prog.ml
ocaml
************************************************************************ alternatives) you can redistribute it and/or modify it under the terms of the GNU It is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ************************************************************************ (ca, id) FIXME : really ?
This file is part of BINSEC . Copyright ( C ) 2016 - 2022 CEA ( Commissariat à l'énergie atomique et aux énergies Lesser General Public License as published by the Free Software Foundation , version 2.1 . See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . open Simplification_dba_utils open Simplification_options let remove_goto m = Logger.debug ~level:3 "Removing gotos ..."; let local_find a = match Dba_types.Caddress.Map.find a accu with | v -> v | exception Not_found -> Dba_types.Caddress.Map.find a m in let open Dba_types in match ik with | Dba.Instr.Assign (_, _, nid) | Dba.Instr.Undef (_, nid) | Dba.Instr.Assume (_, nid) | Dba.Instr.Assert (_, nid) | Dba.Instr.Nondet (_, nid) -> ( try let a = Dba_types.Caddress.reid addr nid in let nik, _ = local_find a in match nik with | Dba.Instr.SJump (Dba.JInner nnid, _) -> f addr (Instruction.set_successor ik nnid, opcode) accu | _ -> Caddress.Map.add addr (ik, opcode) accu with Not_found -> Caddress.Map.add addr (ik, opcode) accu) | Dba.Instr.SJump (Dba.JInner nid, _) -> ( try let a = Dba_types.Caddress.reid addr nid in let nik, nopcode = local_find a in match nik with | Dba.Instr.SJump (Dba.JInner nnid, _) -> f addr (Instruction.set_successor ik nnid, opcode) accu | _ -> if addr.Dba.id = 0 then let accu = Caddress.Map.add a (Instruction.set_successor ik 0, nopcode) accu in f addr (nik, opcode) accu else Caddress.Map.add addr (ik, opcode) accu with Not_found -> Caddress.Map.add addr (ik, opcode) accu) ( nca , nid1 ) try let a = Dba_types.Caddress.reid addr nid2 in let nik, _ = local_find a in match nik with | Dba.Instr.SJump (Dba.JInner nnid, _) -> let inst = Dba.Instr.ite cond (Dba.Jump_target.outer addr') nnid in f addr (inst, opcode) accu | _ -> Caddress.Map.add addr (ik, opcode) accu with Not_found -> Caddress.Map.add addr (ik, opcode) accu) | Dba.Instr.If (cond, Dba.JInner nid1, nid2) -> ( let a1 = Dba_types.Caddress.reid addr nid1 in let a2 = Dba_types.Caddress.reid addr nid2 in let nik1 = try let elt1 = local_find a1 in Some (fst elt1) with Not_found -> None in let nik2 = try let elt2 = local_find a2 in Some (fst elt2) with Not_found -> None in match (nik1, nik2) with | None, None -> Caddress.Map.add addr (ik, opcode) accu | Some nik, None -> ( match nik with | Dba.Instr.SJump (Dba.JInner nnid, _) -> let inst = Dba.Instr.ite cond (Dba.Jump_target.inner nnid) nid2 in f addr (inst, opcode) accu | _ -> Caddress.Map.add addr (ik, opcode) accu) | None, Some nik -> ( match nik with | Dba.Instr.SJump (Dba.JInner nnid, _ntag) -> let inst = Dba.Instr.ite cond (Dba.Jump_target.inner nid1) nnid in f addr (inst, opcode) accu | _ -> Caddress.Map.add addr (ik, opcode) accu) | Some ik1, Some ik2 -> ( let as_ite inner_id succ = Dba.Instr.ite cond (Dba.Jump_target.inner inner_id) succ in match (ik1, ik2) with | ( Dba.Instr.SJump (Dba.JInner nnid1, _), Dba.Instr.SJump (Dba.JInner nnid2, _) ) -> let inst = as_ite nnid1 nnid2 in f addr (inst, opcode) accu | _, Dba.Instr.SJump (Dba.JInner nnid2, _ntag) -> let inst = as_ite nid1 nnid2 in f addr (inst, opcode) accu | Dba.Instr.SJump (Dba.JInner nnid1, _ntag), _ -> let inst = as_ite nnid1 nid2 in f addr (inst, opcode) accu | _, _ -> Caddress.Map.add addr (ik, opcode) accu)) | Dba.Instr.SJump (Dba.JOuter _, _) | Dba.Instr.DJump (_, _) | Dba.Instr.Stop _ -> Caddress.Map.add addr (ik, opcode) accu in let open Dba_types in let m = Caddress.Map.fold f m Caddress.Map.empty in let rec g addr (ik, opcode) accu = if Caddress.Map.mem addr accu then accu else match ik with | Dba.Instr.Assign (_, _, nid) | Dba.Instr.Undef (_, nid) | Dba.Instr.Assume (_, nid) | Dba.Instr.Assert (_, nid) | Dba.Instr.Nondet (_, nid) | Dba.Instr.SJump (Dba.JInner nid, _) -> ( let accu = Caddress.Map.add addr (ik, opcode) accu in try let a = Caddress.reid addr nid in let nik, nopcode = Caddress.Map.find a m in g a (nik, nopcode) accu with Not_found -> accu) | Dba.Instr.If (_, Dba.JOuter _, nid2) -> ( let accu = Caddress.Map.add addr (ik, opcode) accu in try let a = Caddress.reid addr nid2 in g a (Caddress.Map.find a m) accu with Not_found -> accu) | Dba.Instr.If (_cond, Dba.JInner nid1, nid2) -> ( let accu = Caddress.Map.add addr (ik, opcode) accu in let accu = try let a = Caddress.reid addr nid1 in let nik1, _ = Caddress.Map.find a m in g a (nik1, opcode) accu with Not_found -> accu in try let a = Caddress.reid addr nid2 in let nik2, _nopcode = Caddress.Map.find a m in g a (nik2, opcode) accu with Not_found -> accu) | Dba.Instr.SJump (Dba.JOuter _, _) | Dba.Instr.DJump (_, _) | Dba.Instr.Stop _ -> Caddress.Map.add addr (ik, opcode) accu in let g_aux addr e accu = if addr.Dba.id = 0 then g addr e accu else accu in Caddress.Map.fold g_aux m Caddress.Map.empty let remove_mustkill prog env_flags = let look_ahead_limit = 100 in let f addr (ik, opcode) (accu, env_flags, has_changed) = let mk_sjump id = Dba.Instr.static_inner_jump id in let eflags, ik', has_changed = match ik with | Dba.Instr.Assign (lhs, _, id_next) | Dba.Instr.Undef (lhs, id_next) -> let eflags, ik, has_changed = if Dba_types.LValue.is_flag lhs || Dba_types.LValue.is_temporary lhs then let env_flags, has_changed = let a = Dba_types.Caddress.reid addr id_next in is_not_mayused prog a look_ahead_limit lhs env_flags in let ik' = if has_changed then mk_sjump id_next else ik in (env_flags, ik', has_changed) else (env_flags, ik, has_changed) in (eflags, ik, has_changed) | _ -> (env_flags, ik, has_changed) in (Dba_types.Caddress.Map.add addr (ik', opcode) accu, eflags, has_changed) in Dba_types.(Caddress.Map.fold f prog (Caddress.Map.empty, env_flags, false)) let remove_mustkill_lfp inst_map = Logger.debug ~level:3 "Removing mustkills ..."; let rec loop inst_map env_flags = match remove_mustkill inst_map env_flags with | imap, env_flags, true -> loop imap env_flags | imap, _, false -> imap in loop inst_map Dba_types.Caddress.Map.empty
5c3c81f81c94473804fe334bb06593ea197bcba50e1f6cf823d0ef62d3cf12a1
francescoc/scalabilitywitherlangotp
mutex.erl
-module(mutex). -export([start_link/1, start_link/2, init/3, stop/1]). -export([wait/1, signal/1]). -export([system_continue/3, system_terminate/4]). wait(Name) -> Name ! {wait,self()}, Mutex = whereis(Name), receive {Mutex,ok} -> ok end. signal(Name) -> Name ! {signal,self()}, ok. start_link(Name) -> start_link(Name, []). start_link(Name, DbgOpts) -> proc_lib:start_link(?MODULE, init, [self(), Name, DbgOpts]). stop(Name) -> Name ! stop. init(Parent, Name, DbgOpts) -> register(Name, self()), process_flag(trap_exit, true), Debug = sys:debug_options(DbgOpts), proc_lib:init_ack({ok,self()}), NewDebug = sys:handle_debug(Debug, fun debug/3, Name, init), free(Name, Parent, NewDebug). free(Name, Parent, Debug) -> receive {wait,Pid} -> %% The user requests. NewDebug = sys:handle_debug(Debug, fun debug/3, Name, {wait,Pid}), Pid ! {self(),ok}, busy(Pid, Name, Parent, NewDebug); {system,From,Msg} -> %% The system messages. sys:handle_system_msg(Msg, From, Parent, ?MODULE, Debug, {free, Name}); stop -> terminate(stopped, Name, Debug); {'EXIT',Parent,Reason} -> terminate(Reason, Name, Debug) end. busy(Pid, Name, Parent, Debug) -> receive {signal,Pid} -> NewDebug = sys:handle_debug(Debug, fun debug/3, Name, {signal,Pid}), free(Name, Parent, NewDebug); {system,From,Msg} -> %% The system messages. sys:handle_system_msg(Msg, From, Parent, ?MODULE, Debug, {busy,Name,Pid}); {'EXIT',Parent,Reason} -> exit(Pid, Reason), terminate(Reason, Name, Debug) end. debug(Dev, Event, Name) -> io:format(Dev, "mutex ~w: ~w~n", [Name,Event]). system_continue(Parent, Debug, {busy,Name,Pid}) -> busy(Pid, Name, Parent, Debug); system_continue(Parent, Debug, {free,Name}) -> free(Name, Parent, Debug). system_terminate(Reason, _Parent, Debug, {busy,Name,Pid}) -> exit(Pid, Reason), terminate(Reason, Name, Debug); system_terminate(Reason, _Parent, Debug, {free,Name}) -> terminate(Reason, Name, Debug). terminate(Reason, Name, Debug) -> unregister(Name), sys:handle_debug(Debug, fun debug/3, Name, {terminate, Reason}), terminate(Reason). terminate(Reason) -> receive {wait,Pid} -> exit(Pid, Reason), terminate(Reason) after 0 -> exit(Reason) end.
null
https://raw.githubusercontent.com/francescoc/scalabilitywitherlangotp/961de968f034e55eba22eea9a368fe9f47c608cc/ch10/mutex.erl
erlang
The user requests. The system messages. The system messages.
-module(mutex). -export([start_link/1, start_link/2, init/3, stop/1]). -export([wait/1, signal/1]). -export([system_continue/3, system_terminate/4]). wait(Name) -> Name ! {wait,self()}, Mutex = whereis(Name), receive {Mutex,ok} -> ok end. signal(Name) -> Name ! {signal,self()}, ok. start_link(Name) -> start_link(Name, []). start_link(Name, DbgOpts) -> proc_lib:start_link(?MODULE, init, [self(), Name, DbgOpts]). stop(Name) -> Name ! stop. init(Parent, Name, DbgOpts) -> register(Name, self()), process_flag(trap_exit, true), Debug = sys:debug_options(DbgOpts), proc_lib:init_ack({ok,self()}), NewDebug = sys:handle_debug(Debug, fun debug/3, Name, init), free(Name, Parent, NewDebug). free(Name, Parent, Debug) -> receive NewDebug = sys:handle_debug(Debug, fun debug/3, Name, {wait,Pid}), Pid ! {self(),ok}, busy(Pid, Name, Parent, NewDebug); sys:handle_system_msg(Msg, From, Parent, ?MODULE, Debug, {free, Name}); stop -> terminate(stopped, Name, Debug); {'EXIT',Parent,Reason} -> terminate(Reason, Name, Debug) end. busy(Pid, Name, Parent, Debug) -> receive {signal,Pid} -> NewDebug = sys:handle_debug(Debug, fun debug/3, Name, {signal,Pid}), free(Name, Parent, NewDebug); sys:handle_system_msg(Msg, From, Parent, ?MODULE, Debug, {busy,Name,Pid}); {'EXIT',Parent,Reason} -> exit(Pid, Reason), terminate(Reason, Name, Debug) end. debug(Dev, Event, Name) -> io:format(Dev, "mutex ~w: ~w~n", [Name,Event]). system_continue(Parent, Debug, {busy,Name,Pid}) -> busy(Pid, Name, Parent, Debug); system_continue(Parent, Debug, {free,Name}) -> free(Name, Parent, Debug). system_terminate(Reason, _Parent, Debug, {busy,Name,Pid}) -> exit(Pid, Reason), terminate(Reason, Name, Debug); system_terminate(Reason, _Parent, Debug, {free,Name}) -> terminate(Reason, Name, Debug). terminate(Reason, Name, Debug) -> unregister(Name), sys:handle_debug(Debug, fun debug/3, Name, {terminate, Reason}), terminate(Reason). terminate(Reason) -> receive {wait,Pid} -> exit(Pid, Reason), terminate(Reason) after 0 -> exit(Reason) end.
7030955cb365353c48d2af6126a746ca766e59e875f95fbcc129fa06c2d7d2c1
BartoszMilewski/AoC2021
Day5.hs
module Day5 where import Data.List import Data.Tuple import Data.List.Split import qualified Data.Set as S type Point = (Int, Int) type Segment = (Point, Point) type Vector = (Int, Int) start, end :: Segment -> Point start = fst end = snd minus :: Point -> Point -> Vector minus pend pbeg = (fst pend - fst pbeg, snd pend - snd pbeg) parse :: [[String]] -> [Segment] parse = fmap parseLn where parseLn :: [String] -> Segment parseLn (sp1: _: sp2 : []) = let (x1 : y1 : []) = splitOn "," sp1 (x2 : y2 : []) = splitOn "," sp2 in ((readInt x1, readInt y1), (readInt x2, readInt y2)) -- Assume all segments -- are either horizontal, vertical, or diagonal -- Line is: starting point, direction, steps line :: Segment -> (Point, Vector, Int) line seg = (pt, v, n) where pt = start seg (v, n) = normalize (end seg `minus` start seg) normalize :: Vector -> (Vector, Int) normalize (vx, vy) = ((signum vx, signum vy), len) where len = if vx == 0 then abs vy else abs vx isDiag :: (Point, Vector, Int) -> Bool isDiag (_, (vx, vy), _) = vx /= 0 && vy /= 0 drawLine :: (Point, Vector, Int) -> [Point] drawLine ((x, y), (vx, vy), len) = [ (x + n * vx, y + n * vy) | n <- [0 .. len]] type PointSet = S.Set Point overlap :: [Point] -> PointSet overlap = snd . foldr ins (S.empty, S.empty) where ins :: Point -> (PointSet, PointSet) -> (PointSet, PointSet) ins p (set, lst) = if S.member p set then (set, S.insert p lst) else (S.insert p set, lst) solve1 :: [Segment] -> Int solve1 = length . overlap . concat . fmap drawLine . filter (not . isDiag) . fmap line solve2 :: [Segment] -> Int solve2 = length . overlap . concat . fmap drawLine . fmap line readInt :: String -> Int readInt s = read s main :: IO () main = do text <- readFile "data5.txt" let ws = fmap words $ lines text let segs = parse ws print $ solve1 segs print $ solve2 segs
null
https://raw.githubusercontent.com/BartoszMilewski/AoC2021/3065f8b34110c417c646d6116ac20b3ef4e077c0/Day5.hs
haskell
Assume all segments are either horizontal, vertical, or diagonal Line is: starting point, direction, steps
module Day5 where import Data.List import Data.Tuple import Data.List.Split import qualified Data.Set as S type Point = (Int, Int) type Segment = (Point, Point) type Vector = (Int, Int) start, end :: Segment -> Point start = fst end = snd minus :: Point -> Point -> Vector minus pend pbeg = (fst pend - fst pbeg, snd pend - snd pbeg) parse :: [[String]] -> [Segment] parse = fmap parseLn where parseLn :: [String] -> Segment parseLn (sp1: _: sp2 : []) = let (x1 : y1 : []) = splitOn "," sp1 (x2 : y2 : []) = splitOn "," sp2 in ((readInt x1, readInt y1), (readInt x2, readInt y2)) line :: Segment -> (Point, Vector, Int) line seg = (pt, v, n) where pt = start seg (v, n) = normalize (end seg `minus` start seg) normalize :: Vector -> (Vector, Int) normalize (vx, vy) = ((signum vx, signum vy), len) where len = if vx == 0 then abs vy else abs vx isDiag :: (Point, Vector, Int) -> Bool isDiag (_, (vx, vy), _) = vx /= 0 && vy /= 0 drawLine :: (Point, Vector, Int) -> [Point] drawLine ((x, y), (vx, vy), len) = [ (x + n * vx, y + n * vy) | n <- [0 .. len]] type PointSet = S.Set Point overlap :: [Point] -> PointSet overlap = snd . foldr ins (S.empty, S.empty) where ins :: Point -> (PointSet, PointSet) -> (PointSet, PointSet) ins p (set, lst) = if S.member p set then (set, S.insert p lst) else (S.insert p set, lst) solve1 :: [Segment] -> Int solve1 = length . overlap . concat . fmap drawLine . filter (not . isDiag) . fmap line solve2 :: [Segment] -> Int solve2 = length . overlap . concat . fmap drawLine . fmap line readInt :: String -> Int readInt s = read s main :: IO () main = do text <- readFile "data5.txt" let ws = fmap words $ lines text let segs = parse ws print $ solve1 segs print $ solve2 segs
63285facb58fb5ce132f8f16c771f60b6ce2ab23af6b0ccf7099ef54bfa8dd26
clojure-lsp/clojure-lsp
a.clj
(ns sample-test.api.diagnostics.a) some-unknown-var
null
https://raw.githubusercontent.com/clojure-lsp/clojure-lsp/fe232a719707258ee53d72bf44166d5149e6ee0b/cli/integration-test/sample-test/src/sample_test/api/diagnostics/a.clj
clojure
(ns sample-test.api.diagnostics.a) some-unknown-var
116603bea20a2d553b37e8e8298d298689730326c16e4db4ee5a219dce5b52b8
ChrisPenner/grids
Coord.hs
# LANGUAGE DataKinds # # LANGUAGE MultiParamTypeClasses # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeApplications # # LANGUAGE TypeOperators # # LANGUAGE PolyKinds # # LANGUAGE TypeFamilyDependencies # # LANGUAGE UndecidableInstances # {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE GADTs #-} # LANGUAGE AllowAmbiguousTypes # # LANGUAGE StandaloneDeriving # # LANGUAGE PatternSynonyms # # LANGUAGE ViewPatterns # # OPTIONS_GHC -fno - warn - incomplete - patterns # module Data.Grid.Internal.Coord where import GHC.Exts import GHC.TypeNats hiding (Mod) import Data.Proxy import Unsafe.Coerce import Data.Singletons.Prelude import Data.Grid.Internal.NestedLists -- | The index type for 'Grid's. newtype Coord (dims :: [Nat]) = Coord {unCoord :: [Int]} deriving (Eq, Show) -- | Safely construct a 'Coord' for a given grid size, checking that all -- indexes are in range -- > λ > coord @[3 , 3 ] [ 1 , 2 ] > Just [ 1 , 2 ] -- > > λ > coord @[3 , 3 ] [ 3 , 3 ] -- > Nothing -- > > λ > coord @[3 , 3 ] [ 1 , 2 , 3 ] -- > Nothing coord :: forall dims. SingI dims => [Int] -> Maybe (Coord dims) coord ds = if inRange && correctLength then Just (Coord ds) else Nothing where inRange = all (>=0) ds && all id (zipWith (<) ds (fromIntegral <$> demote @dims)) correctLength = length ds == length (demote @dims) instance IsList (Coord dims) where type Item (Coord dims) = Int fromList = coerce toList = coerce | Get the first index from a ' Coord ' unconsC :: Coord (n : ns) -> (Int, Coord ns) unconsC (Coord (n : ns)) = (n, Coord ns) -- | Append two 'Coord's appendC :: Coord ns -> Coord ms -> Coord (ns ++ ms) appendC (Coord ns) (Coord ms) = Coord (ns ++ ms) pattern (:#) :: Int -> Coord ns -> Coord (n:ns) pattern n :# ns <- (unconsC -> (n, ns)) where n :# (unCoord -> ns) = Coord (n:ns) instance (Enum (Coord ns)) => Num (Coord ns ) where (Coord xs) + (Coord ys) = Coord (zipWith (+) xs ys) a - b = a + (negate b) (Coord xs) * (Coord ys) = Coord (zipWith (*) xs ys) abs (Coord xs) = Coord (abs <$> xs) signum (Coord xs) = Coord (signum <$> xs) fromInteger = toEnum . fromIntegral negate (Coord xs) = Coord (negate <$> xs) highestIndex :: forall n. KnownNat n => Int highestIndex = fromIntegral $ natVal (Proxy @n) - 1 clamp :: Int -> Int -> Int -> Int clamp start end = max start . min end clampCoord :: forall dims. SingI dims => Coord dims -> Coord dims clampCoord (Coord ns) = Coord (zipWith (clamp 0 . fromIntegral) (demote @dims) ns) wrapCoord :: forall dims. SingI dims => Coord dims -> Coord dims wrapCoord (Coord ns) = Coord (zipWith mod ns (fromIntegral <$> demote @dims)) instance Bounded (Coord '[] ) where minBound = Coord [] maxBound = Coord [] instance (KnownNat n, Bounded (Coord ns )) => Bounded (Coord (n:ns) ) where minBound = 0 :# minBound maxBound = highestIndex @n :# maxBound instance (KnownNat n) => Enum (Coord '[n]) where toEnum i = Coord [i] fromEnum (Coord [i]) = clamp 0 (highestIndex @n) i instance (KnownNat x, KnownNat y, Sizable (y:rest), Bounded (Coord rest ), Enum (Coord (y:rest) )) => Enum (Coord (x:y:rest) ) where toEnum i | i < 0 = negate $ toEnum (abs i) toEnum i | i > fromEnum (maxBound @(Coord (x:y:rest) )) = error "Index out of bounds" toEnum i = (i `div` (gridSize $ Proxy @(y:rest))) :# toEnum (i `mod` gridSize (Proxy @(y:rest))) fromEnum (x :# ys) = (clamp 0 (highestIndex @x) x * gridSize (Proxy @(y:rest))) + fromEnum ys coerceCoordDims :: Coord ns -> Coord ms coerceCoordDims = unsafeCoerce coordInBounds :: forall ns. (SingI ns) => Coord ns -> Bool coordInBounds (Coord cs) = all inRange $ zip cs maxIndexes where maxIndexes = fromIntegral <$> demote @ns inRange (val,upperBound) = val >= 0 && val < upperBound
null
https://raw.githubusercontent.com/ChrisPenner/grids/619c72b1e51f96377845c2a15eb100d8f4185fa1/src/Data/Grid/Internal/Coord.hs
haskell
# LANGUAGE ConstraintKinds # # LANGUAGE GADTs # | The index type for 'Grid's. | Safely construct a 'Coord' for a given grid size, checking that all indexes are in range > > Nothing > > Nothing | Append two 'Coord's
# LANGUAGE DataKinds # # LANGUAGE MultiParamTypeClasses # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeApplications # # LANGUAGE TypeOperators # # LANGUAGE PolyKinds # # LANGUAGE TypeFamilyDependencies # # LANGUAGE UndecidableInstances # # LANGUAGE AllowAmbiguousTypes # # LANGUAGE StandaloneDeriving # # LANGUAGE PatternSynonyms # # LANGUAGE ViewPatterns # # OPTIONS_GHC -fno - warn - incomplete - patterns # module Data.Grid.Internal.Coord where import GHC.Exts import GHC.TypeNats hiding (Mod) import Data.Proxy import Unsafe.Coerce import Data.Singletons.Prelude import Data.Grid.Internal.NestedLists newtype Coord (dims :: [Nat]) = Coord {unCoord :: [Int]} deriving (Eq, Show) > λ > coord @[3 , 3 ] [ 1 , 2 ] > Just [ 1 , 2 ] > λ > coord @[3 , 3 ] [ 3 , 3 ] > λ > coord @[3 , 3 ] [ 1 , 2 , 3 ] coord :: forall dims. SingI dims => [Int] -> Maybe (Coord dims) coord ds = if inRange && correctLength then Just (Coord ds) else Nothing where inRange = all (>=0) ds && all id (zipWith (<) ds (fromIntegral <$> demote @dims)) correctLength = length ds == length (demote @dims) instance IsList (Coord dims) where type Item (Coord dims) = Int fromList = coerce toList = coerce | Get the first index from a ' Coord ' unconsC :: Coord (n : ns) -> (Int, Coord ns) unconsC (Coord (n : ns)) = (n, Coord ns) appendC :: Coord ns -> Coord ms -> Coord (ns ++ ms) appendC (Coord ns) (Coord ms) = Coord (ns ++ ms) pattern (:#) :: Int -> Coord ns -> Coord (n:ns) pattern n :# ns <- (unconsC -> (n, ns)) where n :# (unCoord -> ns) = Coord (n:ns) instance (Enum (Coord ns)) => Num (Coord ns ) where (Coord xs) + (Coord ys) = Coord (zipWith (+) xs ys) a - b = a + (negate b) (Coord xs) * (Coord ys) = Coord (zipWith (*) xs ys) abs (Coord xs) = Coord (abs <$> xs) signum (Coord xs) = Coord (signum <$> xs) fromInteger = toEnum . fromIntegral negate (Coord xs) = Coord (negate <$> xs) highestIndex :: forall n. KnownNat n => Int highestIndex = fromIntegral $ natVal (Proxy @n) - 1 clamp :: Int -> Int -> Int -> Int clamp start end = max start . min end clampCoord :: forall dims. SingI dims => Coord dims -> Coord dims clampCoord (Coord ns) = Coord (zipWith (clamp 0 . fromIntegral) (demote @dims) ns) wrapCoord :: forall dims. SingI dims => Coord dims -> Coord dims wrapCoord (Coord ns) = Coord (zipWith mod ns (fromIntegral <$> demote @dims)) instance Bounded (Coord '[] ) where minBound = Coord [] maxBound = Coord [] instance (KnownNat n, Bounded (Coord ns )) => Bounded (Coord (n:ns) ) where minBound = 0 :# minBound maxBound = highestIndex @n :# maxBound instance (KnownNat n) => Enum (Coord '[n]) where toEnum i = Coord [i] fromEnum (Coord [i]) = clamp 0 (highestIndex @n) i instance (KnownNat x, KnownNat y, Sizable (y:rest), Bounded (Coord rest ), Enum (Coord (y:rest) )) => Enum (Coord (x:y:rest) ) where toEnum i | i < 0 = negate $ toEnum (abs i) toEnum i | i > fromEnum (maxBound @(Coord (x:y:rest) )) = error "Index out of bounds" toEnum i = (i `div` (gridSize $ Proxy @(y:rest))) :# toEnum (i `mod` gridSize (Proxy @(y:rest))) fromEnum (x :# ys) = (clamp 0 (highestIndex @x) x * gridSize (Proxy @(y:rest))) + fromEnum ys coerceCoordDims :: Coord ns -> Coord ms coerceCoordDims = unsafeCoerce coordInBounds :: forall ns. (SingI ns) => Coord ns -> Bool coordInBounds (Coord cs) = all inRange $ zip cs maxIndexes where maxIndexes = fromIntegral <$> demote @ns inRange (val,upperBound) = val >= 0 && val < upperBound
d561595b23bab492ea6c9f4187ed33b7dd7d203a08062868c088d5cdf234a17b
ayazhafiz/plts
lib_fx_cap.ml
include Surface open Util type file = NoFile | Base of string let make_file_from ext = function | NoFile -> Filename.temp_file "asti" ("." ^ ext) | Base s -> s ^ "." ^ ext (* Driver *) type phase = Parse | Solve | Ir | Eval type emit = Print | Elab let assoc_flip l = List.map (fun (a, b) -> (b, a)) l let phase_list = [ (Parse, "parse"); (Solve, "solve"); (Ir, "ir"); (Eval, "eval") ] let emit_list = [ (Print, "print"); (Elab, "elab") ] let phase_of_string s = List.assoc_opt s @@ assoc_flip phase_list let string_of_phase p = List.assoc p phase_list let emit_of_string s = List.assoc_opt s @@ assoc_flip emit_list let string_of_emit e = List.assoc e emit_list let unlines = String.concat "\n" let phases = List.map string_of_phase @@ List.sort_uniq compare @@ List.map fst phase_list let emits = List.map string_of_emit @@ List.sort_uniq compare @@ List.map fst emit_list type command = phase * emit type command_err = string * [ `InvalidPhase | `InvalidEmit | `Unparseable ] let string_of_command_err (s, e) = s ^ ": " ^ match e with | `InvalidPhase -> "invalid phase" | `InvalidEmit -> "invalid emit" | `Unparseable -> "cannot parse this command" type raw_program = string list let raw_program_of_string = String.split_on_char '\n' let raw_program_of_lines = Fun.id type queries = loc list type program = string list * queries type preprocessed = { raw_program : raw_program; program : program; commands : (command, command_err) result list; file : file; } let re_cmds = Str.regexp {|# \+\([a-z]+\) -\([a-z\-]+\)|} let re_query = Str.regexp {|\(\^+\)|} let starts_command = String.starts_with ~prefix:"# +" let starts_out = String.starts_with ~prefix:"> " let parse_command line = if Str.string_match re_cmds line 0 then let phase = Str.matched_group 1 line in let emit = Str.matched_group 2 line in match (phase_of_string phase, emit_of_string emit) with | Some p, Some e -> Ok (p, e) | None, _ -> Error (line, `InvalidPhase) | _, None -> Error (line, `InvalidEmit) else Error (line, `Unparseable) let program_without_output = let rec go = function | [] -> [] | "" :: line :: _ when starts_out line -> [] | l :: rest -> l :: go rest in go let program_without_commands = let rec go = function | [] -> [] | line :: rest -> if starts_command line then go rest else line :: rest in go let user_ann_program (lines : raw_program) : string = unlines @@ program_without_commands @@ program_without_output lines let preprocess file (lines : raw_program) : preprocessed = let file = match file with | Some f -> Base (Filename.remove_extension f) | None -> NoFile in (* commands in the header *) let commands = let rec parse = function | [] -> [] | line :: rest -> if starts_command line then parse_command line :: parse rest else [] in parse lines in (* raw user input including commands and queries but before the output; we need this for printing back *) let raw_program = program_without_output lines in (* parse N queries on a single line *) let parse_line_queries lineno line : loc list = let rec search start = try let start = Str.search_forward re_query line start in let fin = start + (String.length @@ Str.matched_string line) in + 1 because positions are 1 - indexed (start + 1, fin + 1) :: search fin with Not_found -> [] in let ranges = search 0 in List.map (fun (start, fin) -> ((lineno, start), (lineno, fin))) ranges |> List.rev reverse because we want the last query to be processed first , and printed on the first line in (* program ignoring commands and removing query lines *) let program_lines, queries = let rec parse lineno = function | [] -> ([], []) | l :: rest when starts_command l -> parse lineno rest | l :: _ when starts_out l -> ([], []) | line :: rest -> let queries = parse_line_queries (lineno - 1) line in if List.length queries == 0 then (* no queries, include this line *) let rest_lines, rest_queries = parse (lineno + 1) rest in (line :: rest_lines, rest_queries) else (* queries - return them and throw away the line *) let rest_lines, rest_queries = parse lineno rest in (rest_lines, queries @ rest_queries) in parse 1 lines in { raw_program; program = (program_lines, queries); commands; file } type processed_command = command * string let postprocess (raw_program : raw_program) (commands : processed_command list) : string = let reflow_out s = unlines @@ List.map (fun s -> "> " ^ s) @@ String.split_on_char '\n' s in let cmd_out = List.map (fun ((phase, emit), str) -> [ ""; Printf.sprintf "> +%s -%s" (string_of_phase phase) (string_of_emit emit); reflow_out str; ]) commands in String.concat "\n" @@ raw_program @ List.flatten cmd_out type compile_output = string let string_of_compile_output = Fun.id type compile_err = | ParseErr of string | SolveErr of string | ElabErr of [ `NoQueries | `TypeNotFound of loc ] | BadEmit of phase * emit | NoHover let string_of_compile_err = function | ParseErr s -> "Parse error: " ^ s | SolveErr s -> "Solve error: " ^ s | ElabErr e -> ( "Elab error: " ^ match e with | `NoQueries -> "no queries given!" | `TypeNotFound loc -> "Type not found at " ^ string_of_loc loc) | BadEmit (p, e) -> "Commit do " ^ string_of_emit e ^ " for phase " ^ string_of_phase p | NoHover -> "No hover location found" type compile_result = (compile_output, compile_err) result let ( >>= ) = Result.bind let reflow_lines prefix lines = String.split_on_char '\n' lines |> List.map (( ^ ) prefix) |> String.concat "\n" let process_one _file (lines, queries) (phase, emit) : compile_result = let input = unlines lines in let parse s = Result.map_error (fun s -> ParseErr s) @@ Ast_parse.parse s in let solve (fresh_var, p) = Result.map_error (fun s -> SolveErr s) @@ Ty_solve.infer_program fresh_var p in let ir program = let program = Ir_conv.conv_program program in Ir_check.check_program program; Ok program in let eval program = Result.ok @@ Ir_interp.interp program in let elab program = if List.length queries = 0 then Error (ElabErr `NoQueries) else let open Either in let queries = List.map (fun l -> (l, Service.type_at l program)) queries in let one_query (((_, cstart), (_, cend)) as loc) = let num_caret = cend - cstart in let prefix = "#" - 1 because positions are 1 - indexed (* - 1 to make room for the starting `#` *) ^ String.init (cstart - 1 - 1) (fun _ -> ' ') ^ String.init num_caret (fun _ -> '^') ^ " " in match List.assoc loc queries with | None -> Right (ElabErr (`TypeNotFound loc)) | Some ty -> let s_ty = Service.print_type ty in Left (reflow_lines prefix s_ty) in let rec recreate lineno lines = let queries = List.filter (fun (((l, _), _), _) -> l == lineno) queries in match (lines, queries) with | [], _ -> [] | l :: rest, [] -> Left l :: recreate (lineno + 1) rest | l :: rest, queries -> let rest = recreate (lineno + 1) rest in let queries = queries |> List.map fst |> List.map one_query in Left l :: (queries @ rest) in let oks, errs = List.partition_map Fun.id @@ recreate 1 lines in match errs with e :: _ -> Error e | [] -> Ok (unlines oks) in let ( &> ) a b = Result.map b a in let print_parsed (_tenv, program) = Ast.string_of_program ~width:default_width program in let print_solved program = Ast.string_of_program ~width:default_width program in let print_ir program = Ir.string_of_program ~width:default_width program in let print_evaled evaled = Ir_interp.string_of_value ~width:default_width evaled in match (phase, emit) with | Parse, Print -> input |> parse &> print_parsed | Solve, Print -> input |> parse >>= solve &> print_solved | Solve, Elab -> input |> parse >>= solve >>= elab | Ir, Print -> input |> parse >>= solve >>= ir &> print_ir | Eval, Print -> input |> parse >>= solve >>= ir >>= eval &> print_evaled | phase, emit -> Error (BadEmit (phase, emit)) let hover_info lines lineco = let parse s = Result.map_error (fun s -> ParseErr s) @@ Ast_parse.parse s in let solve _s = Error (SolveErr "unimplemented") in let hover (_tenv, program) = Service.hover_info lineco program |> Option.to_result ~none:NoHover in let hover_info = unlines lines |> parse >>= solve >>= hover in hover_info
null
https://raw.githubusercontent.com/ayazhafiz/plts/6dfa9340457ec897ddf40a87feee44dd6200921a/fx_cap/lib_fx_cap.ml
ocaml
Driver commands in the header raw user input including commands and queries but before the output; we need this for printing back parse N queries on a single line program ignoring commands and removing query lines no queries, include this line queries - return them and throw away the line - 1 to make room for the starting `#`
include Surface open Util type file = NoFile | Base of string let make_file_from ext = function | NoFile -> Filename.temp_file "asti" ("." ^ ext) | Base s -> s ^ "." ^ ext type phase = Parse | Solve | Ir | Eval type emit = Print | Elab let assoc_flip l = List.map (fun (a, b) -> (b, a)) l let phase_list = [ (Parse, "parse"); (Solve, "solve"); (Ir, "ir"); (Eval, "eval") ] let emit_list = [ (Print, "print"); (Elab, "elab") ] let phase_of_string s = List.assoc_opt s @@ assoc_flip phase_list let string_of_phase p = List.assoc p phase_list let emit_of_string s = List.assoc_opt s @@ assoc_flip emit_list let string_of_emit e = List.assoc e emit_list let unlines = String.concat "\n" let phases = List.map string_of_phase @@ List.sort_uniq compare @@ List.map fst phase_list let emits = List.map string_of_emit @@ List.sort_uniq compare @@ List.map fst emit_list type command = phase * emit type command_err = string * [ `InvalidPhase | `InvalidEmit | `Unparseable ] let string_of_command_err (s, e) = s ^ ": " ^ match e with | `InvalidPhase -> "invalid phase" | `InvalidEmit -> "invalid emit" | `Unparseable -> "cannot parse this command" type raw_program = string list let raw_program_of_string = String.split_on_char '\n' let raw_program_of_lines = Fun.id type queries = loc list type program = string list * queries type preprocessed = { raw_program : raw_program; program : program; commands : (command, command_err) result list; file : file; } let re_cmds = Str.regexp {|# \+\([a-z]+\) -\([a-z\-]+\)|} let re_query = Str.regexp {|\(\^+\)|} let starts_command = String.starts_with ~prefix:"# +" let starts_out = String.starts_with ~prefix:"> " let parse_command line = if Str.string_match re_cmds line 0 then let phase = Str.matched_group 1 line in let emit = Str.matched_group 2 line in match (phase_of_string phase, emit_of_string emit) with | Some p, Some e -> Ok (p, e) | None, _ -> Error (line, `InvalidPhase) | _, None -> Error (line, `InvalidEmit) else Error (line, `Unparseable) let program_without_output = let rec go = function | [] -> [] | "" :: line :: _ when starts_out line -> [] | l :: rest -> l :: go rest in go let program_without_commands = let rec go = function | [] -> [] | line :: rest -> if starts_command line then go rest else line :: rest in go let user_ann_program (lines : raw_program) : string = unlines @@ program_without_commands @@ program_without_output lines let preprocess file (lines : raw_program) : preprocessed = let file = match file with | Some f -> Base (Filename.remove_extension f) | None -> NoFile in let commands = let rec parse = function | [] -> [] | line :: rest -> if starts_command line then parse_command line :: parse rest else [] in parse lines in let raw_program = program_without_output lines in let parse_line_queries lineno line : loc list = let rec search start = try let start = Str.search_forward re_query line start in let fin = start + (String.length @@ Str.matched_string line) in + 1 because positions are 1 - indexed (start + 1, fin + 1) :: search fin with Not_found -> [] in let ranges = search 0 in List.map (fun (start, fin) -> ((lineno, start), (lineno, fin))) ranges |> List.rev reverse because we want the last query to be processed first , and printed on the first line in let program_lines, queries = let rec parse lineno = function | [] -> ([], []) | l :: rest when starts_command l -> parse lineno rest | l :: _ when starts_out l -> ([], []) | line :: rest -> let queries = parse_line_queries (lineno - 1) line in if List.length queries == 0 then let rest_lines, rest_queries = parse (lineno + 1) rest in (line :: rest_lines, rest_queries) else let rest_lines, rest_queries = parse lineno rest in (rest_lines, queries @ rest_queries) in parse 1 lines in { raw_program; program = (program_lines, queries); commands; file } type processed_command = command * string let postprocess (raw_program : raw_program) (commands : processed_command list) : string = let reflow_out s = unlines @@ List.map (fun s -> "> " ^ s) @@ String.split_on_char '\n' s in let cmd_out = List.map (fun ((phase, emit), str) -> [ ""; Printf.sprintf "> +%s -%s" (string_of_phase phase) (string_of_emit emit); reflow_out str; ]) commands in String.concat "\n" @@ raw_program @ List.flatten cmd_out type compile_output = string let string_of_compile_output = Fun.id type compile_err = | ParseErr of string | SolveErr of string | ElabErr of [ `NoQueries | `TypeNotFound of loc ] | BadEmit of phase * emit | NoHover let string_of_compile_err = function | ParseErr s -> "Parse error: " ^ s | SolveErr s -> "Solve error: " ^ s | ElabErr e -> ( "Elab error: " ^ match e with | `NoQueries -> "no queries given!" | `TypeNotFound loc -> "Type not found at " ^ string_of_loc loc) | BadEmit (p, e) -> "Commit do " ^ string_of_emit e ^ " for phase " ^ string_of_phase p | NoHover -> "No hover location found" type compile_result = (compile_output, compile_err) result let ( >>= ) = Result.bind let reflow_lines prefix lines = String.split_on_char '\n' lines |> List.map (( ^ ) prefix) |> String.concat "\n" let process_one _file (lines, queries) (phase, emit) : compile_result = let input = unlines lines in let parse s = Result.map_error (fun s -> ParseErr s) @@ Ast_parse.parse s in let solve (fresh_var, p) = Result.map_error (fun s -> SolveErr s) @@ Ty_solve.infer_program fresh_var p in let ir program = let program = Ir_conv.conv_program program in Ir_check.check_program program; Ok program in let eval program = Result.ok @@ Ir_interp.interp program in let elab program = if List.length queries = 0 then Error (ElabErr `NoQueries) else let open Either in let queries = List.map (fun l -> (l, Service.type_at l program)) queries in let one_query (((_, cstart), (_, cend)) as loc) = let num_caret = cend - cstart in let prefix = "#" - 1 because positions are 1 - indexed ^ String.init (cstart - 1 - 1) (fun _ -> ' ') ^ String.init num_caret (fun _ -> '^') ^ " " in match List.assoc loc queries with | None -> Right (ElabErr (`TypeNotFound loc)) | Some ty -> let s_ty = Service.print_type ty in Left (reflow_lines prefix s_ty) in let rec recreate lineno lines = let queries = List.filter (fun (((l, _), _), _) -> l == lineno) queries in match (lines, queries) with | [], _ -> [] | l :: rest, [] -> Left l :: recreate (lineno + 1) rest | l :: rest, queries -> let rest = recreate (lineno + 1) rest in let queries = queries |> List.map fst |> List.map one_query in Left l :: (queries @ rest) in let oks, errs = List.partition_map Fun.id @@ recreate 1 lines in match errs with e :: _ -> Error e | [] -> Ok (unlines oks) in let ( &> ) a b = Result.map b a in let print_parsed (_tenv, program) = Ast.string_of_program ~width:default_width program in let print_solved program = Ast.string_of_program ~width:default_width program in let print_ir program = Ir.string_of_program ~width:default_width program in let print_evaled evaled = Ir_interp.string_of_value ~width:default_width evaled in match (phase, emit) with | Parse, Print -> input |> parse &> print_parsed | Solve, Print -> input |> parse >>= solve &> print_solved | Solve, Elab -> input |> parse >>= solve >>= elab | Ir, Print -> input |> parse >>= solve >>= ir &> print_ir | Eval, Print -> input |> parse >>= solve >>= ir >>= eval &> print_evaled | phase, emit -> Error (BadEmit (phase, emit)) let hover_info lines lineco = let parse s = Result.map_error (fun s -> ParseErr s) @@ Ast_parse.parse s in let solve _s = Error (SolveErr "unimplemented") in let hover (_tenv, program) = Service.hover_info lineco program |> Option.to_result ~none:NoHover in let hover_info = unlines lines |> parse >>= solve >>= hover in hover_info
5cc0ac91f1a85a1dd011012b605ea812d892e145c4acfa43df7bb54a1a4cb74d
aufishgrp/cowpaths
cowpaths.erl
%%%------------------------------------------------------------------- %% @doc cowpaths API module. %% @end %%%------------------------------------------------------------------- -module(cowpaths). -include("cowpaths.hrl"). -include_lib("eunit/include/eunit.hrl"). %% API -export([attach/1, attach/2, detach/1, get_paths/0]). -spec attach(Cowpaths :: cowpaths_types:cowpaths()) -> ok. @doc Updates the routes tables with the specified Routes for App . %% If the app has previously attached the existing rules are overwritten. %% @end attach(Cowpaths) -> attach(application:get_application(), Cowpaths). -spec attach(App :: atom(), Cowpaths :: cowpaths_types:cowpaths()) -> ok. @doc Updates the routes tables with the specified Routes for App . %% If the app has previously attached the existing rules are overwritten. %% @end attach(App, Cowpaths) -> Cowpaths = parse_cowpaths(Cowpaths), listen_and_attach(App, Cowpaths). -spec detach(App :: atom()) -> ok | {error, term()}. @doc Removes the routes for the specified App . %% @end detach(App) -> cowpaths_manager:detach(App). -spec get_paths() -> cowpaths_types:paths(). get_paths() -> get_paths(all). -spec get_paths(all | atom()) -> cowpaths_types:paths(). get_paths(App) -> cowpaths_manager:get_paths(App). %%==================================================================== Internal functions %%==================================================================== join([], Acc) -> Acc; join([Cowpath | Cowpaths], Acc) -> join(Cowpaths, [Cowpath | Acc]). -spec expand(cowpaths_types:cowpaths()) -> list(cowpaths_types:cowpath()). expand(Cowpaths) -> lists:foldl( fun (Cowpath, Acc) when is_atom(Cowpath) -> join(expand(Cowpath:cowpaths()), Acc); (Cowpath, Acc) -> [Cowpath | Acc] end, [], Cowpaths )). -spec parse_hosts(cowpaths_types:hostspecs()) -> cowpaths_types:hosts(). parse_hosts('_') -> '_'; parse_hosts(all) -> '_'; parse_hosts(Hosts) when is_list(Hosts) -> lists:map(fun parse_host/1, Hosts). -spec parse_host(cowpaths_types:hostspec()) -> cowpaths_types:host(). parse_host(Host) when not is_atom(Host) -> Host. -spec parse_constraints(cowpaths_types:constraintspecs()) -> cowpaths_types:constraints(). parse_constraints(ConstraintSpecs) when is_list(ConstraintSpecs) -> lists:map(fun parse_constraint/1, ConstraintSpecs). -spec parse_constraint(cowpaths_types:constraintspec()) -> cowpaths_types:constraint(). parse_constraint({_, int} = Constraint) -> Constraint; parse_constraint({_, Fun} = Constraint) when is_function(Fun) -> Constraint; parse_constraint({Match, {Module, Fun}}) when is_atom(Module) andalso is_atom(Fun) -> Fun = fun(X) -> Module:Fun(X) end, {Match, Fun}. -spec parse_trails(cowpaths_types:paths()) -> cowpaths_types:trails(). parse_trails(PathSpecs) -> lists:map(fun parse_trail/1, PathSpecs). -spec parse_trail(cowpaths_types:path()) -> cowpaths_types:trail(). parse_trail(Path) when is_map(Path) -> lists:foldl(fun update_trail/2, trails_defaults(), maps:to_list(Path)). update_trail({path_match, PathMatch}, Path) -> Path#{path_match => PathMatch}; update_trail({constraints, Constraints}, Path) when is_list(Constraints) -> Path#{constraints => parse_constraints(Constraints)}; update_trail({handler, Handler}, Path) when is_atom(Handler) -> Path#{handler => Handler}; update_trail({options, Options}, Path) -> Path#{options => Options}; update_trail({metadata, MetaData}, Path) when is_map(MetaData) -> Path#{metadata => MetaData}. trails_defaults() -> #{ constraints => [], options => [], metadata => #{} }. trails_to_cowboy(Trails) -> lists:map(fun trail_to_cowboy/1, Trails). trail_to_cowboy(#{ path_match := PathMatch, handler := Handler, constraints := Constraints, options := Options }) -> {PathMatch, Constraints, Handler, Options}. valid_socket(ok) -> ok; valid_socket({exists, _}) -> ok; valid_socket(X) -> X. listen_and_attach(_, []) -> ok; listen_and_attach(App, [{Sockets, Trails, Cowboy} | Specs]) -> {ok, SocketIds} = cowpaths_manager:sockets(App, Sockets), cowpaths_manager:attach(App, SocketIds, Trails, Cowboy). %%==================================================================== %% Unit Test functions %%====================================================================
null
https://raw.githubusercontent.com/aufishgrp/cowpaths/04d2639eccd66183dccd45a457a4b69dc18acb56/src/cowpaths.erl
erlang
------------------------------------------------------------------- @doc cowpaths API module. @end ------------------------------------------------------------------- API If the app has previously attached the existing rules are overwritten. @end If the app has previously attached the existing rules are overwritten. @end @end ==================================================================== ==================================================================== ==================================================================== Unit Test functions ====================================================================
-module(cowpaths). -include("cowpaths.hrl"). -include_lib("eunit/include/eunit.hrl"). -export([attach/1, attach/2, detach/1, get_paths/0]). -spec attach(Cowpaths :: cowpaths_types:cowpaths()) -> ok. @doc Updates the routes tables with the specified Routes for App . attach(Cowpaths) -> attach(application:get_application(), Cowpaths). -spec attach(App :: atom(), Cowpaths :: cowpaths_types:cowpaths()) -> ok. @doc Updates the routes tables with the specified Routes for App . attach(App, Cowpaths) -> Cowpaths = parse_cowpaths(Cowpaths), listen_and_attach(App, Cowpaths). -spec detach(App :: atom()) -> ok | {error, term()}. @doc Removes the routes for the specified App . detach(App) -> cowpaths_manager:detach(App). -spec get_paths() -> cowpaths_types:paths(). get_paths() -> get_paths(all). -spec get_paths(all | atom()) -> cowpaths_types:paths(). get_paths(App) -> cowpaths_manager:get_paths(App). Internal functions join([], Acc) -> Acc; join([Cowpath | Cowpaths], Acc) -> join(Cowpaths, [Cowpath | Acc]). -spec expand(cowpaths_types:cowpaths()) -> list(cowpaths_types:cowpath()). expand(Cowpaths) -> lists:foldl( fun (Cowpath, Acc) when is_atom(Cowpath) -> join(expand(Cowpath:cowpaths()), Acc); (Cowpath, Acc) -> [Cowpath | Acc] end, [], Cowpaths )). -spec parse_hosts(cowpaths_types:hostspecs()) -> cowpaths_types:hosts(). parse_hosts('_') -> '_'; parse_hosts(all) -> '_'; parse_hosts(Hosts) when is_list(Hosts) -> lists:map(fun parse_host/1, Hosts). -spec parse_host(cowpaths_types:hostspec()) -> cowpaths_types:host(). parse_host(Host) when not is_atom(Host) -> Host. -spec parse_constraints(cowpaths_types:constraintspecs()) -> cowpaths_types:constraints(). parse_constraints(ConstraintSpecs) when is_list(ConstraintSpecs) -> lists:map(fun parse_constraint/1, ConstraintSpecs). -spec parse_constraint(cowpaths_types:constraintspec()) -> cowpaths_types:constraint(). parse_constraint({_, int} = Constraint) -> Constraint; parse_constraint({_, Fun} = Constraint) when is_function(Fun) -> Constraint; parse_constraint({Match, {Module, Fun}}) when is_atom(Module) andalso is_atom(Fun) -> Fun = fun(X) -> Module:Fun(X) end, {Match, Fun}. -spec parse_trails(cowpaths_types:paths()) -> cowpaths_types:trails(). parse_trails(PathSpecs) -> lists:map(fun parse_trail/1, PathSpecs). -spec parse_trail(cowpaths_types:path()) -> cowpaths_types:trail(). parse_trail(Path) when is_map(Path) -> lists:foldl(fun update_trail/2, trails_defaults(), maps:to_list(Path)). update_trail({path_match, PathMatch}, Path) -> Path#{path_match => PathMatch}; update_trail({constraints, Constraints}, Path) when is_list(Constraints) -> Path#{constraints => parse_constraints(Constraints)}; update_trail({handler, Handler}, Path) when is_atom(Handler) -> Path#{handler => Handler}; update_trail({options, Options}, Path) -> Path#{options => Options}; update_trail({metadata, MetaData}, Path) when is_map(MetaData) -> Path#{metadata => MetaData}. trails_defaults() -> #{ constraints => [], options => [], metadata => #{} }. trails_to_cowboy(Trails) -> lists:map(fun trail_to_cowboy/1, Trails). trail_to_cowboy(#{ path_match := PathMatch, handler := Handler, constraints := Constraints, options := Options }) -> {PathMatch, Constraints, Handler, Options}. valid_socket(ok) -> ok; valid_socket({exists, _}) -> ok; valid_socket(X) -> X. listen_and_attach(_, []) -> ok; listen_and_attach(App, [{Sockets, Trails, Cowboy} | Specs]) -> {ok, SocketIds} = cowpaths_manager:sockets(App, Sockets), cowpaths_manager:attach(App, SocketIds, Trails, Cowboy).
a0b402362f2e5e22ee23953a16b08747f65c95661db7f55bff09cc6967076a0b
status-im/status-electron
storage.cljs
(ns status-desktop-front.storage (:require [alandipert.storage-atom :refer [local-storage]] [status-im.data-store.messages :as data-store.messages] [status-im.utils.random :as random] [status-im.constants :as constants])) ;;;; ACCOUNTS ;; I would love to have something similar in status-react instead realm (def accounts (local-storage (atom []) :accounts)) (def account (atom {})) (defn save-account [account] (swap! accounts conj account)) (defn get-accounts [] @accounts) (defn change-account [address new-account?] (swap! account assoc :contacts (local-storage (atom {}) (keyword (str address "contacts"))) :chats (local-storage (atom {}) (keyword (str address "chats"))) :messages (local-storage (atom {}) (keyword (str address "messages"))))) ;;;; CONTACTS (defn save-contact [contact] (swap! (:contacts @account) update-in [(:whisper-identity contact)] merge contact)) (defn save-contacts [contacts] (mapv save-contact contacts)) (defn get-all-contacts [] (vals @(:contacts @account))) ;;;; CHAT (defn save-chat [chat] (swap! (:chats @account) assoc (:chat-id chat) chat)) (defn get-all-chats [] (vals @(:chats @account))) (defn get-chat-by-id [chat-id] (get @(:chats @account) chat-id)) (defn chat-exists? [chat-id] (boolean (get-chat-by-id chat-id))) (defn chat-is-active? [chat-id] (get (get-chat-by-id chat-id) :is-active)) (defn chat-new-update? [timestamp chat-id] (let [{:keys [added-to-at removed-at removed-from-at added-at]} (get-chat-by-id chat-id)] (and (> timestamp added-to-at) (> timestamp removed-at) (> timestamp removed-from-at) (> timestamp added-at)))) (defn- groups [active?] (filter #(and (:group-chat %) (= (:is-active %) active?)) (get-all-chats))) (defn get-active-group-chats [] (map (fn [{:keys [chat-id public-key private-key public?]}] (let [group {:group-id chat-id :public? public?}] (if (and public-key private-key) (assoc group :keypair {:private private-key :public public-key}) group))) (groups true))) ;;;; MESSAGE (defn save-message [{:keys [message-id content] :as message}] (let [content' (data-store.messages/prepare-content content) message' (merge data-store.messages/default-values message {:content content' :timestamp (random/timestamp)})] (swap! (:messages @account) assoc message-id message'))) (defn update-message [{:keys [message-id content] :as message}] (swap! (:messages @account) update-in [message-id] merge message)) (defn get-message-by-id [message-id] (get @(:messages @account) message-id)) (defn get-messages-by-chat-id ([chat-id] (get-messages-by-chat-id chat-id 0)) ([chat-id from] (let [chats (sort-by :timestamp > (filter #(= chat-id (:chat-id %)) (vals @(:messages @account)))) to (+ from constants/default-number-of-messages)] (if (< to (count chats)) ;;TODO yeah i know i know (subvec (into [] chats) from to) chats)))) (defn get-last-message [chat-id] (->> (vals @(:messages @account)) (filter #(= chat-id (:chat-id %))) (sort-by :clock-value >) (first))) (defn message-exists? [message-id] (get @(:messages @account) message-id)) (defn get-last-clock-value [chat-id] (if-let [message (get-last-message chat-id)] (:clock-value message) 0))
null
https://raw.githubusercontent.com/status-im/status-electron/aad18c34c0ee0304071e984f21d5622735ec5bef/src_front/status_desktop_front/storage.cljs
clojure
ACCOUNTS I would love to have something similar in status-react instead realm CONTACTS CHAT MESSAGE TODO yeah i know i know
(ns status-desktop-front.storage (:require [alandipert.storage-atom :refer [local-storage]] [status-im.data-store.messages :as data-store.messages] [status-im.utils.random :as random] [status-im.constants :as constants])) (def accounts (local-storage (atom []) :accounts)) (def account (atom {})) (defn save-account [account] (swap! accounts conj account)) (defn get-accounts [] @accounts) (defn change-account [address new-account?] (swap! account assoc :contacts (local-storage (atom {}) (keyword (str address "contacts"))) :chats (local-storage (atom {}) (keyword (str address "chats"))) :messages (local-storage (atom {}) (keyword (str address "messages"))))) (defn save-contact [contact] (swap! (:contacts @account) update-in [(:whisper-identity contact)] merge contact)) (defn save-contacts [contacts] (mapv save-contact contacts)) (defn get-all-contacts [] (vals @(:contacts @account))) (defn save-chat [chat] (swap! (:chats @account) assoc (:chat-id chat) chat)) (defn get-all-chats [] (vals @(:chats @account))) (defn get-chat-by-id [chat-id] (get @(:chats @account) chat-id)) (defn chat-exists? [chat-id] (boolean (get-chat-by-id chat-id))) (defn chat-is-active? [chat-id] (get (get-chat-by-id chat-id) :is-active)) (defn chat-new-update? [timestamp chat-id] (let [{:keys [added-to-at removed-at removed-from-at added-at]} (get-chat-by-id chat-id)] (and (> timestamp added-to-at) (> timestamp removed-at) (> timestamp removed-from-at) (> timestamp added-at)))) (defn- groups [active?] (filter #(and (:group-chat %) (= (:is-active %) active?)) (get-all-chats))) (defn get-active-group-chats [] (map (fn [{:keys [chat-id public-key private-key public?]}] (let [group {:group-id chat-id :public? public?}] (if (and public-key private-key) (assoc group :keypair {:private private-key :public public-key}) group))) (groups true))) (defn save-message [{:keys [message-id content] :as message}] (let [content' (data-store.messages/prepare-content content) message' (merge data-store.messages/default-values message {:content content' :timestamp (random/timestamp)})] (swap! (:messages @account) assoc message-id message'))) (defn update-message [{:keys [message-id content] :as message}] (swap! (:messages @account) update-in [message-id] merge message)) (defn get-message-by-id [message-id] (get @(:messages @account) message-id)) (defn get-messages-by-chat-id ([chat-id] (get-messages-by-chat-id chat-id 0)) ([chat-id from] (let [chats (sort-by :timestamp > (filter #(= chat-id (:chat-id %)) (vals @(:messages @account)))) to (+ from constants/default-number-of-messages)] (if (< to (count chats)) (subvec (into [] chats) from to) chats)))) (defn get-last-message [chat-id] (->> (vals @(:messages @account)) (filter #(= chat-id (:chat-id %))) (sort-by :clock-value >) (first))) (defn message-exists? [message-id] (get @(:messages @account) message-id)) (defn get-last-clock-value [chat-id] (if-let [message (get-last-message chat-id)] (:clock-value message) 0))
22aff5b069ee4b8876a50121918f6174811b10d2f3cee94e12622adc0a4dce16
marinacavalari/databricks-sdk-clojure
core_test.clj
(ns databricks-sdk-clojure.core-test (:require [clojure.test :refer :all] [databricks-sdk.core :as sdk] [org.httpkit.client :as http])) (defn success-clusters-list-response [test-function] (future {:body "{\"clusters\":[{\"cluster_id\":\"123\"}]}" :status 200})) (defn success-cluster-response [test-function] (future {:body "{\"cluster_id\":\"123\"}" :status 200})) (defn success-cluster-events-response [test-function] (future {:body "{\"events\": [{\"cluster_id\": \"123\", \"timestamp\": 1642016862695, \"type\": \"RUNNING\", \"details\": {}}], \"next_page\": {}, \"total_count\": 2283}" :status 200})) (defn failed-response [test-function] (future {:body "Too many requests" :status 429})) (deftest list-clusters-list (testing "success, returning the request's body, in this case, the clusters list" (with-redefs [http/request success-clusters-list-response] (is (= {:result {:clusters [{:cluster_id "123"}]}} (sdk/list-clusters {:token "bcfGe428JL09" :timeout 30000 :host "-account.cloud.databricks.com" :body {}}))))) (testing "failed, uknown status error" (is (= {:error {:code 1 :message "example-account.cloud.databricks.com: nodename nor servname provided, or not known"}} (sdk/list-clusters {:token "bcfGe428JL09" :timeout 30000 :host "-account.cloud.databricks.com" :body {}})))) (testing "failed, known status error" (with-redefs [http/request failed-response] (is (= {:error {:code 429 :message "Too many requests"}} (sdk/list-clusters {:token "bcfGe428JL09" :timeout 30000 :host "-account.cloud.databricks.com" :body {}})))))) (deftest edit-cluster-test (testing "success, returning the request's body, in this case, the cluster id" (with-redefs [http/request success-cluster-response] (is (= {:result {:cluster_id "123"}} (sdk/edit-cluster! {:token "bcfGe428JL09" :timeout 30000 :host "-account.cloud.databricks.com" :body {}}))))) (testing "failed, uknown status error" (is (= {:error {:code 1 :message "example-account.cloud.databricks.com: nodename nor servname provided, or not known"}} (sdk/edit-cluster! {:token "bcfGe428JL09" :timeout 30000 :host "-account.cloud.databricks.com" :body {}})))) (testing "failed, known status error" (with-redefs [http/request failed-response] (is (= {:error {:code 429 :message "Too many requests"}} (sdk/edit-cluster! {:token "bcfGe428JL09" :timeout 30000 :host "-account.cloud.databricks.com" :body {}})))))) (deftest create-cluster-test (testing "success, returning the request's body, in this case, the new cluster id" (with-redefs [http/request success-cluster-response] (is (= {:result {:cluster_id "123"}} (sdk/create-cluster! {:token "bcfGe428JL09" :timeout 30000 :host "-account.cloud.databricks.com" :body {}}))))) (testing "failed, uknown status error" (is (= {:error {:code 1 :message "example-account.cloud.databricks.com: nodename nor servname provided, or not known"}} (sdk/create-cluster! {:token "bcfGe428JL09" :timeout 30000 :host "-account.cloud.databricks.com" :body {}})))) (testing "failed, known status error" (with-redefs [http/request failed-response] (is (= {:error {:code 429 :message "Too many requests"}} (sdk/create-cluster! {:token "bcfGe428JL09" :timeout 30000 :host "-account.cloud.databricks.com" :body {}})))))) (deftest start-cluster-test (testing "success, returning the request's body, in this case, the started cluster id" (with-redefs [http/request success-cluster-response] (is (= {:result {:cluster_id "123"}} (sdk/start-cluster! {:token "bcfGe428JL09" :timeout 30000 :host "-account.cloud.databricks.com" :body {}}))))) (testing "failed, uknown status error" (is (= {:error {:code 1 :message "example-account.cloud.databricks.com: nodename nor servname provided, or not known"}} (sdk/start-cluster! {:token "bcfGe428JL09" :timeout 30000 :host "-account.cloud.databricks.com" :body {}})))) (testing "failed, known status error" (with-redefs [http/request failed-response] (is (= {:error {:code 429 :message "Too many requests"}} (sdk/start-cluster! {:token "bcfGe428JL09" :timeout 30000 :host "-account.cloud.databricks.com" :body {}})))))) (deftest terminate-cluster-test (testing "success, returning the request's body, in this case, the terminated cluster id" (with-redefs [http/request success-cluster-response] (is (= {:result {:cluster_id "123"}} (sdk/terminate-cluster! {:token "bcfGe428JL09" :timeout 30000 :host "-account.cloud.databricks.com" :body {:cluster_id "123"}}))))) (testing "failed, uknown status error" (is (= {:error {:code 1 :message "example-account.cloud.databricks.com: nodename nor servname provided, or not known"}} (sdk/terminate-cluster! {:token "bcfGe428JL09" :timeout 30000 :host "-account.cloud.databricks.com" :body {:cluster_id "123"}})))) (testing "failed, known status error" (with-redefs [http/request failed-response] (is (= {:error {:code 429 :message "Too many requests"}} (sdk/terminate-cluster! {:token "bcfGe428JL09" :timeout 30000 :host "-account.cloud.databricks.com" :body {:cluster_id "123"}})))))) (deftest clusters-events-test (testing "success, returning the request's body, in this case, the events from a cluster" (with-redefs [http/request success-cluster-events-response] (is (= {:result {:events [{:cluster_id "123" :timestamp 1642016862695 :type "RUNNING" :details {}}] :next_page {} :total_count 2283}} (sdk/clusters-events {:token "bcfGe428JL09" :timeout 30000 :host "-account.cloud.databricks.com" :body {:cluster_id "123" :limit 5}}))))) (testing "failed, uknown status error" (is (= {:error {:code 1 :message "example-account.cloud.databricks.com: nodename nor servname provided, or not known"}} (sdk/clusters-events {:token "bcfGe428JL09" :timeout 30000 :host "-account.cloud.databricks.com" :body {:cluster_id "123" :limit 5}})))) (testing "failed, known status error" (with-redefs [http/request failed-response] (is (= {:error {:code 429 :message "Too many requests"}} (sdk/clusters-events {:token "bcfGe428JL09" :timeout 30000 :host "-account.cloud.databricks.com" :body {:cluster_id "123" :limit 5}}))))))
null
https://raw.githubusercontent.com/marinacavalari/databricks-sdk-clojure/dc78733a1bf2388888840f0b3f5617042666ee67/test/databricks_sdk_clojure/core_test.clj
clojure
(ns databricks-sdk-clojure.core-test (:require [clojure.test :refer :all] [databricks-sdk.core :as sdk] [org.httpkit.client :as http])) (defn success-clusters-list-response [test-function] (future {:body "{\"clusters\":[{\"cluster_id\":\"123\"}]}" :status 200})) (defn success-cluster-response [test-function] (future {:body "{\"cluster_id\":\"123\"}" :status 200})) (defn success-cluster-events-response [test-function] (future {:body "{\"events\": [{\"cluster_id\": \"123\", \"timestamp\": 1642016862695, \"type\": \"RUNNING\", \"details\": {}}], \"next_page\": {}, \"total_count\": 2283}" :status 200})) (defn failed-response [test-function] (future {:body "Too many requests" :status 429})) (deftest list-clusters-list (testing "success, returning the request's body, in this case, the clusters list" (with-redefs [http/request success-clusters-list-response] (is (= {:result {:clusters [{:cluster_id "123"}]}} (sdk/list-clusters {:token "bcfGe428JL09" :timeout 30000 :host "-account.cloud.databricks.com" :body {}}))))) (testing "failed, uknown status error" (is (= {:error {:code 1 :message "example-account.cloud.databricks.com: nodename nor servname provided, or not known"}} (sdk/list-clusters {:token "bcfGe428JL09" :timeout 30000 :host "-account.cloud.databricks.com" :body {}})))) (testing "failed, known status error" (with-redefs [http/request failed-response] (is (= {:error {:code 429 :message "Too many requests"}} (sdk/list-clusters {:token "bcfGe428JL09" :timeout 30000 :host "-account.cloud.databricks.com" :body {}})))))) (deftest edit-cluster-test (testing "success, returning the request's body, in this case, the cluster id" (with-redefs [http/request success-cluster-response] (is (= {:result {:cluster_id "123"}} (sdk/edit-cluster! {:token "bcfGe428JL09" :timeout 30000 :host "-account.cloud.databricks.com" :body {}}))))) (testing "failed, uknown status error" (is (= {:error {:code 1 :message "example-account.cloud.databricks.com: nodename nor servname provided, or not known"}} (sdk/edit-cluster! {:token "bcfGe428JL09" :timeout 30000 :host "-account.cloud.databricks.com" :body {}})))) (testing "failed, known status error" (with-redefs [http/request failed-response] (is (= {:error {:code 429 :message "Too many requests"}} (sdk/edit-cluster! {:token "bcfGe428JL09" :timeout 30000 :host "-account.cloud.databricks.com" :body {}})))))) (deftest create-cluster-test (testing "success, returning the request's body, in this case, the new cluster id" (with-redefs [http/request success-cluster-response] (is (= {:result {:cluster_id "123"}} (sdk/create-cluster! {:token "bcfGe428JL09" :timeout 30000 :host "-account.cloud.databricks.com" :body {}}))))) (testing "failed, uknown status error" (is (= {:error {:code 1 :message "example-account.cloud.databricks.com: nodename nor servname provided, or not known"}} (sdk/create-cluster! {:token "bcfGe428JL09" :timeout 30000 :host "-account.cloud.databricks.com" :body {}})))) (testing "failed, known status error" (with-redefs [http/request failed-response] (is (= {:error {:code 429 :message "Too many requests"}} (sdk/create-cluster! {:token "bcfGe428JL09" :timeout 30000 :host "-account.cloud.databricks.com" :body {}})))))) (deftest start-cluster-test (testing "success, returning the request's body, in this case, the started cluster id" (with-redefs [http/request success-cluster-response] (is (= {:result {:cluster_id "123"}} (sdk/start-cluster! {:token "bcfGe428JL09" :timeout 30000 :host "-account.cloud.databricks.com" :body {}}))))) (testing "failed, uknown status error" (is (= {:error {:code 1 :message "example-account.cloud.databricks.com: nodename nor servname provided, or not known"}} (sdk/start-cluster! {:token "bcfGe428JL09" :timeout 30000 :host "-account.cloud.databricks.com" :body {}})))) (testing "failed, known status error" (with-redefs [http/request failed-response] (is (= {:error {:code 429 :message "Too many requests"}} (sdk/start-cluster! {:token "bcfGe428JL09" :timeout 30000 :host "-account.cloud.databricks.com" :body {}})))))) (deftest terminate-cluster-test (testing "success, returning the request's body, in this case, the terminated cluster id" (with-redefs [http/request success-cluster-response] (is (= {:result {:cluster_id "123"}} (sdk/terminate-cluster! {:token "bcfGe428JL09" :timeout 30000 :host "-account.cloud.databricks.com" :body {:cluster_id "123"}}))))) (testing "failed, uknown status error" (is (= {:error {:code 1 :message "example-account.cloud.databricks.com: nodename nor servname provided, or not known"}} (sdk/terminate-cluster! {:token "bcfGe428JL09" :timeout 30000 :host "-account.cloud.databricks.com" :body {:cluster_id "123"}})))) (testing "failed, known status error" (with-redefs [http/request failed-response] (is (= {:error {:code 429 :message "Too many requests"}} (sdk/terminate-cluster! {:token "bcfGe428JL09" :timeout 30000 :host "-account.cloud.databricks.com" :body {:cluster_id "123"}})))))) (deftest clusters-events-test (testing "success, returning the request's body, in this case, the events from a cluster" (with-redefs [http/request success-cluster-events-response] (is (= {:result {:events [{:cluster_id "123" :timestamp 1642016862695 :type "RUNNING" :details {}}] :next_page {} :total_count 2283}} (sdk/clusters-events {:token "bcfGe428JL09" :timeout 30000 :host "-account.cloud.databricks.com" :body {:cluster_id "123" :limit 5}}))))) (testing "failed, uknown status error" (is (= {:error {:code 1 :message "example-account.cloud.databricks.com: nodename nor servname provided, or not known"}} (sdk/clusters-events {:token "bcfGe428JL09" :timeout 30000 :host "-account.cloud.databricks.com" :body {:cluster_id "123" :limit 5}})))) (testing "failed, known status error" (with-redefs [http/request failed-response] (is (= {:error {:code 429 :message "Too many requests"}} (sdk/clusters-events {:token "bcfGe428JL09" :timeout 30000 :host "-account.cloud.databricks.com" :body {:cluster_id "123" :limit 5}}))))))
6e5ef4f11a1ebeb898ae03894bc620116341a3c5b1a84ea247c352f6b35c0175
herd/herdtools7
KBarrier.mli
(****************************************************************************) (* the diy toolsuite *) (* *) , University College London , UK . , INRIA Paris - Rocquencourt , France . (* *) Copyright 2017 - present Institut National de Recherche en Informatique et (* en Automatique and the authors. All rights reserved. *) (* *) This software is governed by the CeCILL - B license under French law and (* abiding by the rules of distribution of free software. You can use, *) modify and/ or redistribute the software under the terms of the CeCILL - B license as circulated by CEA , CNRS and INRIA at the following URL " " . We also give a copy in LICENSE.txt . (****************************************************************************) (* Barrier option *) type t = User | TimeBase | No val tags : string list val parse : string -> t option val pp : t -> string
null
https://raw.githubusercontent.com/herd/herdtools7/67dcc89f3df8692158869b64868cf847bdd764da/litmus/KBarrier.mli
ocaml
************************************************************************** the diy toolsuite en Automatique and the authors. All rights reserved. abiding by the rules of distribution of free software. You can use, ************************************************************************** Barrier option
, University College London , UK . , INRIA Paris - Rocquencourt , France . Copyright 2017 - present Institut National de Recherche en Informatique et This software is governed by the CeCILL - B license under French law and modify and/ or redistribute the software under the terms of the CeCILL - B license as circulated by CEA , CNRS and INRIA at the following URL " " . We also give a copy in LICENSE.txt . type t = User | TimeBase | No val tags : string list val parse : string -> t option val pp : t -> string
c5fccd852e501e04261e0f332171f5b6701191d15e41fa8244b93ea3036bf52e
google/ormolu
Preprocess.hs
{-# LANGUAGE BangPatterns #-} # LANGUAGE LambdaCase # # LANGUAGE RecordWildCards # -- | Preprocessing for input source code. module Ormolu.Processing.Preprocess ( preprocess, ) where import Control.Monad import Data.Char (isSpace) import qualified Data.List as L import Data.Maybe (isJust, maybeToList) import FastString import Ormolu.Config (RegionDeltas (..)) import Ormolu.Parser.Shebang (isShebang) import Ormolu.Processing.Common import qualified Ormolu.Processing.Cpp as Cpp import SrcLoc -- | Transform given input possibly returning comments extracted from it. This handles LINE pragmas , CPP , shebangs , and the magic comments for enabling\/disabling of Ormolu . preprocess :: -- | File name, just to use in the spans FilePath -> -- | Input to process String -> -- | Region deltas RegionDeltas -> -- | Literal prefix, pre-processed input, literal suffix, extra comments (String, String, String, [Located String]) preprocess path input RegionDeltas {..} = go 1 OrmoluEnabled Cpp.Outside id id regionLines where (prefixLines, otherLines) = splitAt regionPrefixLength (lines input) (regionLines, suffixLines) = let regionLength = length otherLines - regionSuffixLength in splitAt regionLength otherLines go !n ormoluState cppState inputSoFar csSoFar = \case [] -> let input' = unlines (inputSoFar []) in ( unlines prefixLines, case ormoluState of OrmoluEnabled -> input' OrmoluDisabled -> input' ++ endDisabling, unlines suffixLines, csSoFar [] ) (x : xs) -> let (x', ormoluState', cppState', cs) = processLine path n ormoluState cppState x in go (n + 1) ormoluState' cppState' (inputSoFar . (x' :)) (csSoFar . (maybeToList cs ++)) xs -- | Transform a given line possibly returning a comment extracted from it. processLine :: -- | File name, just to use in the spans FilePath -> -- | Line number of this line Int -> | Whether Ormolu is currently enabled OrmoluState -> | CPP state Cpp.State -> -- | The actual line String -> -- | Adjusted line and possibly a comment extracted from it (String, OrmoluState, Cpp.State, Maybe (Located String)) processLine path n ormoluState Cpp.Outside line | "{-# LINE" `L.isPrefixOf` line = let (pragma, res) = getPragma line size = length pragma ss = mkSrcSpan (mkSrcLoc' 1) (mkSrcLoc' (size + 1)) in (res, ormoluState, Cpp.Outside, Just (L ss pragma)) | isOrmoluEnable line = case ormoluState of OrmoluEnabled -> (enableMarker, OrmoluEnabled, Cpp.Outside, Nothing) OrmoluDisabled -> (endDisabling ++ enableMarker, OrmoluEnabled, Cpp.Outside, Nothing) | isOrmoluDisable line = case ormoluState of OrmoluEnabled -> (disableMarker ++ startDisabling, OrmoluDisabled, Cpp.Outside, Nothing) OrmoluDisabled -> (disableMarker, OrmoluDisabled, Cpp.Outside, Nothing) | isShebang line = let ss = mkSrcSpan (mkSrcLoc' 1) (mkSrcLoc' (length line)) in ("", ormoluState, Cpp.Outside, Just (L ss line)) | otherwise = let (line', cppState') = Cpp.processLine line Cpp.Outside in (line', ormoluState, cppState', Nothing) where mkSrcLoc' = mkSrcLoc (mkFastString path) n processLine _ _ ormoluState cppState line = let (line', cppState') = Cpp.processLine line cppState in (line', ormoluState, cppState', Nothing) -- | Take a line pragma and output its replacement (where line pragma is -- replaced with spaces) and the contents of the pragma itself. getPragma :: | Pragma line to analyze String -> -- | Contents of the pragma and its replacement line (String, String) getPragma [] = error "Ormolu.Preprocess.getPragma: input must not be empty" getPragma s@(x : xs) | "#-}" `L.isPrefixOf` s = ("#-}", " " ++ drop 3 s) | otherwise = let (prag, remline) = getPragma xs in (x : prag, ' ' : remline) -- | Canonical enable marker. enableMarker :: String enableMarker = "{- ORMOLU_ENABLE -}" -- | Canonical disable marker. disableMarker :: String disableMarker = "{- ORMOLU_DISABLE -}" -- | Return 'True' if the given string is an enabling marker. isOrmoluEnable :: String -> Bool isOrmoluEnable = magicComment "ORMOLU_ENABLE" -- | Return 'True' if the given string is a disabling marker. isOrmoluDisable :: String -> Bool isOrmoluDisable = magicComment "ORMOLU_DISABLE" -- | Construct a function for whitespace-insensitive matching of string. magicComment :: -- | What to expect String -> -- | String to test String -> | Whether or not the two strings watch Bool magicComment expected s0 = isJust $ do let trim = dropWhile isSpace s1 <- trim <$> L.stripPrefix "{-" (trim s0) s2 <- trim <$> L.stripPrefix expected s1 s3 <- L.stripPrefix "-}" s2 guard (all isSpace s3)
null
https://raw.githubusercontent.com/google/ormolu/ffdf145bbdf917d54a3ef4951fc2655e35847ff0/src/Ormolu/Processing/Preprocess.hs
haskell
# LANGUAGE BangPatterns # | Preprocessing for input source code. | Transform given input possibly returning comments extracted from it. | File name, just to use in the spans | Input to process | Region deltas | Literal prefix, pre-processed input, literal suffix, extra comments | Transform a given line possibly returning a comment extracted from it. | File name, just to use in the spans | Line number of this line | The actual line | Adjusted line and possibly a comment extracted from it | Take a line pragma and output its replacement (where line pragma is replaced with spaces) and the contents of the pragma itself. | Contents of the pragma and its replacement line | Canonical enable marker. | Canonical disable marker. | Return 'True' if the given string is an enabling marker. | Return 'True' if the given string is a disabling marker. | Construct a function for whitespace-insensitive matching of string. | What to expect | String to test
# LANGUAGE LambdaCase # # LANGUAGE RecordWildCards # module Ormolu.Processing.Preprocess ( preprocess, ) where import Control.Monad import Data.Char (isSpace) import qualified Data.List as L import Data.Maybe (isJust, maybeToList) import FastString import Ormolu.Config (RegionDeltas (..)) import Ormolu.Parser.Shebang (isShebang) import Ormolu.Processing.Common import qualified Ormolu.Processing.Cpp as Cpp import SrcLoc This handles LINE pragmas , CPP , shebangs , and the magic comments for enabling\/disabling of Ormolu . preprocess :: FilePath -> String -> RegionDeltas -> (String, String, String, [Located String]) preprocess path input RegionDeltas {..} = go 1 OrmoluEnabled Cpp.Outside id id regionLines where (prefixLines, otherLines) = splitAt regionPrefixLength (lines input) (regionLines, suffixLines) = let regionLength = length otherLines - regionSuffixLength in splitAt regionLength otherLines go !n ormoluState cppState inputSoFar csSoFar = \case [] -> let input' = unlines (inputSoFar []) in ( unlines prefixLines, case ormoluState of OrmoluEnabled -> input' OrmoluDisabled -> input' ++ endDisabling, unlines suffixLines, csSoFar [] ) (x : xs) -> let (x', ormoluState', cppState', cs) = processLine path n ormoluState cppState x in go (n + 1) ormoluState' cppState' (inputSoFar . (x' :)) (csSoFar . (maybeToList cs ++)) xs processLine :: FilePath -> Int -> | Whether Ormolu is currently enabled OrmoluState -> | CPP state Cpp.State -> String -> (String, OrmoluState, Cpp.State, Maybe (Located String)) processLine path n ormoluState Cpp.Outside line | "{-# LINE" `L.isPrefixOf` line = let (pragma, res) = getPragma line size = length pragma ss = mkSrcSpan (mkSrcLoc' 1) (mkSrcLoc' (size + 1)) in (res, ormoluState, Cpp.Outside, Just (L ss pragma)) | isOrmoluEnable line = case ormoluState of OrmoluEnabled -> (enableMarker, OrmoluEnabled, Cpp.Outside, Nothing) OrmoluDisabled -> (endDisabling ++ enableMarker, OrmoluEnabled, Cpp.Outside, Nothing) | isOrmoluDisable line = case ormoluState of OrmoluEnabled -> (disableMarker ++ startDisabling, OrmoluDisabled, Cpp.Outside, Nothing) OrmoluDisabled -> (disableMarker, OrmoluDisabled, Cpp.Outside, Nothing) | isShebang line = let ss = mkSrcSpan (mkSrcLoc' 1) (mkSrcLoc' (length line)) in ("", ormoluState, Cpp.Outside, Just (L ss line)) | otherwise = let (line', cppState') = Cpp.processLine line Cpp.Outside in (line', ormoluState, cppState', Nothing) where mkSrcLoc' = mkSrcLoc (mkFastString path) n processLine _ _ ormoluState cppState line = let (line', cppState') = Cpp.processLine line cppState in (line', ormoluState, cppState', Nothing) getPragma :: | Pragma line to analyze String -> (String, String) getPragma [] = error "Ormolu.Preprocess.getPragma: input must not be empty" getPragma s@(x : xs) | "#-}" `L.isPrefixOf` s = ("#-}", " " ++ drop 3 s) | otherwise = let (prag, remline) = getPragma xs in (x : prag, ' ' : remline) enableMarker :: String enableMarker = "{- ORMOLU_ENABLE -}" disableMarker :: String disableMarker = "{- ORMOLU_DISABLE -}" isOrmoluEnable :: String -> Bool isOrmoluEnable = magicComment "ORMOLU_ENABLE" isOrmoluDisable :: String -> Bool isOrmoluDisable = magicComment "ORMOLU_DISABLE" magicComment :: String -> String -> | Whether or not the two strings watch Bool magicComment expected s0 = isJust $ do let trim = dropWhile isSpace s1 <- trim <$> L.stripPrefix "{-" (trim s0) s2 <- trim <$> L.stripPrefix expected s1 s3 <- L.stripPrefix "-}" s2 guard (all isSpace s3)
61f6ba36651ce7724bf52b3ecaad5741e3c678b4e0a3a3c398875ff7ab57e2ea
Hazelfire/pedant
TypeCheck.hs
# LANGUAGE FlexibleInstances # {-# LANGUAGE OverloadedStrings #-} | TypeChecker for . module Pedant.TypeCheck ( TypeEnv (..), typeCheck, TypeError (..), emptyTypeCheckState, TypeCheckState (..), VariableName (..), ) where import Control.Monad.Except import Control.Monad.State hiding (state) import qualified Data.Bifunctor import qualified Data.Map as Map import qualified Data.Map.Ordered as OMap import qualified Data.Maybe as Maybe import qualified Data.Set as Set import qualified Data.Text as T import Debug.Trace (trace, traceShowId) import qualified Pedant.FileResolver as Resolver import qualified Pedant.InBuilt as InBuilt import Pedant.Parser import Pedant.Types import qualified Text.Megaparsec as Megaparsec | A Type Error . a problem that occured during type checking data TypeError = UnificationError ReasonForUnification UnificationTrace | MissingUnitError T.Text | MissingVariableError T.Text | MissingImportError T.Text T.Text | MissingModuleError T.Text | InternalError T.Text deriving (Eq) data ReasonForUnification = BinaryOpUnificationReason T.Text (Positioned ParseExpression, Type) (Positioned ParseExpression, Type) | PrefixOpUnificationReason T.Text (Positioned ParseExpression, Type) | AccessUnificationReason (Positioned ParseExpression, Type) T.Text deriving (Eq) instance Ord (Positioned TypeError) where compare (Positioned (PositionData a _) _) (Positioned (PositionData b _) _) = compare a b type UnificationTrace = [(Type, Type)] instance Megaparsec.ShowErrorComponent (Positioned TypeError) where showErrorComponent (Positioned _ (UnificationError reason _)) = case reason of BinaryOpUnificationReason "+" (p1, t1) (p2, t2) -> T.unpack $ T.concat [ "Can only add dimension that are the same.\n", pPrint p1, " has the type ", pPrint t1, " and ", pPrint p2, " has the type ", pPrint t2 ] BinaryOpUnificationReason "-" (p1, t1) (p2, t2) -> T.unpack $ T.concat [ "Can only subtract dimensions that are the same.\n", pPrint p1, " has the type ", pPrint t1, " and ", pPrint p2, " has the type ", pPrint t2 ] BinaryOpUnificationReason op (p1, t1) (p2, t2) -> T.unpack $ T.concat [ op, " must be called on a number.\n", pPrint p1, " has the type ", pPrint t1, " and ", pPrint p2, " has the type ", pPrint t2 ] PrefixOpUnificationReason op (p1, t1) -> T.unpack $ T.concat [ op, " must be called on a number.\n", pPrint p1, " has the type ", pPrint t1 ] AccessUnificationReason (p1, t1) key -> T.unpack $ T.concat [ pPrint p1, " has type ", pPrint t1, " does not have the key ", key ] showErrorComponent (Positioned _ (MissingUnitError unitName)) = concat [ "unit ", T.unpack unitName, " not declared. Try adding a \"unit ", T.unpack unitName, "\" statement before this line" ] showErrorComponent (Positioned _ (MissingVariableError varName)) = concat [ "variable ", T.unpack varName, " not declared." ] showErrorComponent (Positioned _ (InternalError err)) = "INTERNAL ERROR. YOU SHOULD NOT BE GETTING THIS: " ++ T.unpack err showErrorComponent (Positioned _ (MissingImportError moduleName variable)) = concat [ "Could not find name ", T.unpack variable, " in module ", T.unpack moduleName, "." ] showErrorComponent (Positioned _ (MissingModuleError moduleName)) = concat [ "Could not find module ", T.unpack moduleName, "." ] errorComponentLen (Positioned (PositionData _ l) _) = l -- | The state of the type checker data TypeCheckState = TypeCheckState { -- | The environment of the checker. This contains references to all the variables and schemes of those variables currently declared. tcsEnv :: TypeEnv, -- | Substitutions, the current substitutions that are required for the expression to unify tcsSubs :: Substitution, -- | Units, the units currently declared tcsUnits :: Set.Set VariableName, -- | A list of the modules that have been checked tcsCheckedModules :: Set.Set T.Text, tcsCurrentModule :: T.Text } emptyTypeCheckState :: TypeCheckState emptyTypeCheckState = TypeCheckState (TypeEnv OMap.empty) nullSubst Set.empty Set.empty "" nullSubst :: Substitution nullSubst = Substitution Map.empty Map.empty subUnion :: Substitution -> Substitution -> Substitution subUnion a b = Substitution { subTypes = subTypes a `Map.union` subTypes b, subDimensions = subDimensions a `Map.union` subDimensions b } composeSubst :: Substitution -> Substitution -> Substitution composeSubst s1 s2 = appliedSubs `subUnion` s1 where appliedSubs = Substitution { subTypes = Map.map (apply s1) (subTypes s2), subDimensions = Map.map (apply s1) (subDimensions s2) } newtype TypeEnv = TypeEnv (OMap.OMap VariableName (Scheme, ExecutionExpression)) deriving (Show) addToEnv :: VariableName -> (Scheme, ExecutionExpression) -> TypeEnv -> TypeEnv addToEnv key var (TypeEnv env) = TypeEnv ((key, var) OMap.|< env) instance Types TypeEnv where ftv (TypeEnv env) = ftv (map (fst . snd) $ OMap.assocs env) apply s (TypeEnv env) = TypeEnv (fmap (Data.Bifunctor.first (apply s)) env) instance Types TypeCheckState where ftv state = ftv (tcsEnv state) apply s state = state {tcsEnv = apply s (tcsEnv state)} generalize :: TypeEnv -> Type -> Scheme generalize env t = Scheme vars t where vars = Set.toList (ftv t `Set.difference` ftv env) newtype TIState = TIState {tiSupply :: Int} type TI a = ExceptT (Positioned TypeError) (State TIState) a runTI :: TI a -> (Either (Positioned TypeError) a, TIState) runTI t = runState (runExceptT t) initTIState where initTIState = TIState {tiSupply = 0} newTyVar :: T.Text -> TI Type newTyVar prefix = do s <- get put s {tiSupply = tiSupply s + 1} return (PolyType (prefix <> T.pack (show (tiSupply s)))) newTyDimension :: T.Text -> TI Dimension newTyDimension prefix = do s <- get put s {tiSupply = tiSupply s + 1} return (NormDim $ Map.singleton (PolyDim $ prefix <> T.pack (show (tiSupply s))) 1) instantiate :: Scheme -> TI Type instantiate (Scheme vars t) = do nvars <- mapM (\_ -> newTyVar "a") vars ndims <- mapM (\_ -> newTyDimension "a") vars let s = nullSubst { subTypes = Map.fromList (zip vars nvars), subDimensions = Map.fromList (zip vars ndims) } return $ apply s t -- | Unification Monad type UM a = ExceptT UnificationTrace (State TIState) a liftUMtoTI :: PositionData -> ReasonForUnification -> UM a -> TI a liftUMtoTI p reason m = do initState <- get case runState (runExceptT m) initState of (Right result, state) -> do put state return result (Left err, _) -> throwError $ Positioned p $ UnificationError reason err -- | Attempts to find a unification between dimensions mguDim :: Dimension -> Dimension -> UM Substitution mguDim (NormDim t) (NormDim u) = if u == t then return nullSubst else -- unifying dimensions is a bit tricky, and this method is not perfect and leaves out some possible (but rare) unifications let dividedOut = Map.filter (/= 0) $ Map.unionWith (+) t (Map.map negate u) polyDim = Maybe.mapMaybe ( \(k, v) -> case (k, v) of (PolyDim d, 1) -> Just (d, 1) (PolyDim d, -1) -> Just (d, -1) _ -> Nothing ) (Map.toList dividedOut) in case polyDim of (firstDim, power) : _ -> let withoutPolyVar = Map.delete (PolyDim firstDim) dividedOut dividedByPower = Map.map (`quot` (- power)) withoutPolyVar in return $ nullSubst {subDimensions = Map.singleton firstDim (NormDim dividedByPower)} [] -> throwError [(BaseDim (NormDim t), BaseDim (NormDim u))] mguDim (PowDim t) (PowDim u) = trace (show (PowDim t) ++ " unify " ++ show (PowDim u)) $ if u == t then return nullSubst else let dividedOut = Map.filter (/= 0) $ Map.unionWith (+) t (Map.map negate u) polyDim = Maybe.mapMaybe ( \(k, v) -> case (k, v) of (PolyDim d, 1) -> Just (d, 1) (PolyDim d, -1) -> Just (d, -1) _ -> Nothing ) (Map.toList (traceShowId dividedOut)) in case traceShowId polyDim of (firstDim, power) : _ -> let withoutPolyVar = Map.delete (PolyDim firstDim) dividedOut dividedByPower = Map.map (`quot` (- power)) (traceShowId withoutPolyVar) in return $ nullSubst {subDimensions = Map.singleton firstDim (PowDim (traceShowId dividedByPower))} [] -> throwError [(BaseDim (PowDim t), BaseDim (PowDim u))] mguDim (NormDim u) (PowDim t) = do I can only unify BaseDims and PowDims if they both unify to dimensionless trace (show (NormDim u) ++ " unify " ++ show (PowDim t)) $ ( do s1 <- mguDim (NormDim Map.empty) (NormDim u) s2 <- mguDim (PowDim Map.empty) (apply s1 (PowDim t)) return $ s2 `composeSubst` s1 ) `catchError` (\_ -> throwError [(BaseDim (NormDim u), BaseDim (PowDim t))]) mguDim (PowDim u) (NormDim t) = do I can only unify BaseDims and PowDims if they both unify to dimensionless s1 <- mguDim (PowDim Map.empty) (PowDim u) s2 <- mguDim (NormDim Map.empty) (apply s1 (NormDim t)) return $ s2 `composeSubst` s1 `catchError` (\_ -> throwError [(BaseDim (NormDim u), BaseDim (PowDim t))]) mgu :: Type -> Type -> UM Substitution mgu a b = wrapError a b (mgu' a b) mgu' :: Type -> Type -> UM Substitution mgu' (FuncType l r) (FuncType l' r') = do s1 <- mgu l l' s2 <- mgu (apply s1 r) (apply s1 r') return (s1 `composeSubst` s2) mgu' (PolyType u) t = varBind u t mgu' t (PolyType u) = varBind u t mgu' (BaseDim t) (BaseDim u) = mguDim t u mgu' (PolyDictType t) (DictType u) = do foldM go nullSubst (Map.toList t) where go :: Substitution -> (T.Text, Type) -> UM Substitution go sub (key, type_) = do case Map.lookup key u of Just currType -> do s1 <- mgu (apply sub type_) (apply sub currType) return (sub `composeSubst` s1) Nothing -> throwError [(PolyDictType t, DictType u)] mgu' (DictType t) (PolyDictType u) = mgu' (PolyDictType u) (DictType t) mgu' (ListType t) (ListType u) = mgu t u mgu' t1 t2 = throwError [(t1, t2)] wrapError :: Type -> Type -> UM Substitution -> UM Substitution wrapError t1 t2 child = child `catchError` addUnificationLayer where addUnificationLayer :: UnificationTrace -> UM a addUnificationLayer errStack = throwError ((t1, t2) : errStack) varBind :: T.Text -> Type -> UM Substitution varBind u t | t == PolyType u = return nullSubst | u `Set.member` ftv t = throwError [(PolyType u, t)] | otherwise = return (nullSubst {subTypes = Map.singleton u t}) typeCheck :: TypeCheckState -> [Resolver.Module] -> (Maybe (Positioned TypeError), TypeCheckState) typeCheck tcState (currentModule : rest) = trace ("Current module: " <> T.unpack (Resolver.moduleName currentModule)) $ case typeCheckFile tcState currentModule of (Just err, newState) -> (Just err, newState) (Nothing, newState) -> do typeCheck newState rest typeCheck tcState [] = (Nothing, tcState) typeCheckFile :: TypeCheckState -> Resolver.Module -> (Maybe (Positioned TypeError), TypeCheckState) typeCheckFile tcState m = let setStateModuleName = tcState {tcsCurrentModule = Resolver.moduleName m} (result, _) = runTI (inferLoop setStateModuleName (Resolver.moduleStatements m)) in case result of Right (err, state) -> let addedCheckedModule = state {tcsCheckedModules = Resolver.moduleName m `Set.insert` tcsCheckedModules setStateModuleName} in (err, addedCheckedModule) Left err -> (Just err, tcState) where inferLoop :: TypeCheckState -> [Statement] -> TI (Maybe (Positioned TypeError), TypeCheckState) inferLoop state [] = return (Nothing, state) inferLoop state (statement : rest) = let moduleName = tcsCurrentModule state in case statement of UnitStatement units -> let newUnits = tcsUnits state `Set.union` Set.fromList (map (\(Positioned _ p) -> VariableName moduleName p) units) in inferLoop (state {tcsUnits = newUnits}) rest ImportStatement importedModuleName imports -> do moduleState <- importModule moduleName importedModuleName imports state inferLoop moduleState rest AssignmentStatement assignment -> do First , assign polymorphic types to all arguments of the function ( make the definition as loose as possible ) mapPairs <- mapM ( \a -> do tv <- newTyVar a return (VariableName moduleName a, (Scheme [] tv, EVariable (VariableName moduleName a))) -- This is a fake execution expression, it's an argument, it's deliberately unknown ) (assignmentArguments assignment) -- Then, add these arguments to the type environment let (TypeEnv env) = tcsEnv state arguments = assignmentArguments assignment env'' = TypeEnv (env OMap.<>| OMap.fromList mapPairs) TypeCheckResult s1 t1 ex <- ti (state {tcsEnv = env''}) (assignmentExpression assignment) let varType = foldr (\(_, (Scheme _ tv, _)) acc -> apply s1 tv `FuncType` acc) (apply s1 t1) mapPairs name = VariableName moduleName (assignmentName assignment) t' = generalize (apply s1 env'') varType -- Note that this env is not env''. This is because otherwise we will add arguments as variables -- We want to not include those envWithVar = addToEnv name (t', wrapFunctionArgs arguments ex) (TypeEnv env) let newTcState = state { tcsEnv = envWithVar, tcsSubs = s1 `composeSubst` tcsSubs state } inferLoop newTcState rest `catchError` (\err -> return (Just err, state)) importModule :: T.Text -> Positioned T.Text -> [Positioned T.Text] -> TypeCheckState -> TI TypeCheckState importModule moduleName (Positioned moduleNamePos importedModuleName) imports oldState = trace (T.unpack ("Module name: " <> moduleName <> ", Checked modules: " <> T.pack (show (tcsCheckedModules oldState)))) $ if importedModuleName `Set.member` tcsCheckedModules oldState then do let foldImports = foldM $ \currState (Positioned importNamePos importName) -> do let (TypeEnv env) = tcsEnv currState case OMap.lookup (VariableName importedModuleName importName) env of Just (varType, _) -> -- The item imported is a variable. I simply write this down -- as a variable declaration let newTcState = addToEnv (VariableName moduleName importName) (varType, EVariable (VariableName importedModuleName importName)) (tcsEnv currState) in return (currState {tcsEnv = newTcState}) Nothing -> -- Is it an imported unit? if VariableName importedModuleName importName `Set.member` tcsUnits oldState then let newUnits = VariableName moduleName importName `Set.insert` tcsUnits currState in return (currState {tcsUnits = newUnits}) else throwError $ Positioned importNamePos (MissingImportError importedModuleName importName) foldImports oldState imports else throwError $ Positioned moduleNamePos (MissingModuleError importedModuleName) wrapFunctionArgs :: [T.Text] -> ExecutionExpression -> ExecutionExpression wrapFunctionArgs (arg : rest) expr = EConstant (ExecutionValueFunc arg (wrapFunctionArgs rest expr)) wrapFunctionArgs [] expr = expr data TypeCheckResult = TypeCheckResult Substitution Type ExecutionExpression foldSubst :: Traversable t => t Substitution -> Substitution foldSubst = foldr composeSubst nullSubst ti :: TypeCheckState -> Positioned ParseExpression -> TI TypeCheckResult ti state (Positioned pos expression) = let (TypeEnv env) = tcsEnv state allowedUnits = Set.filter (\(VariableName moduleName _) -> moduleName == tcsCurrentModule state) $ tcsUnits state in case expression of PVariable n -> case OMap.lookup (VariableName (tcsCurrentModule state) n) env of Nothing -> case filter ((== n) . InBuilt.funcName) InBuilt.inBuiltFunctions of func : _ -> do t <- instantiate (InBuilt.funcType func) return $ TypeCheckResult nullSubst t (EInternalFunc $ InBuilt.funcDef func) [] -> throwError $ Positioned pos $ MissingVariableError n Just (sigma, _) -> do t <- instantiate sigma return $ TypeCheckResult nullSubst t (EVariable (VariableName (tcsCurrentModule state) n)) PConstant (ParseNumber value pdim) -> do dimension <- evaluateDimension (Set.map (\(VariableName _ name) -> name) allowedUnits) pdim return $ TypeCheckResult nullSubst (BaseDim dimension) (EConstant $ ExecutionValueNumber value) PConstant ParseEmptyList -> do let emptyListType = Scheme ["a", "t"] $ ListType (BaseDim (NormDim (Map.singleton (PolyDim "a") 1))) dim <- instantiate emptyListType return $ TypeCheckResult nullSubst dim (EConstant ExecutionValueEmptyList) PConstant (ParseRecord record) -> do recordEntries <- forM (Map.toList record) $ \(key, el) -> do TypeCheckResult sub _type ex <- ti state el return (key, (sub, _type, ex)) let dimension = map (\(key, (_, d, _)) -> (key, d)) recordEntries elems = map (\(key, (_, _, value)) -> (key, value)) recordEntries substitutions = map (\(_, (sub, _, _)) -> sub) recordEntries return $ TypeCheckResult (foldSubst substitutions) (DictType (Map.fromList dimension)) (EConstant $ ExecutionValueDict (Map.fromList elems)) PBinOp "" e1 e2 -> do tv <- newTyVar "a" TypeCheckResult sub1 type1 ex1 <- ti state e1 TypeCheckResult sub2 type2 ex2 <- ti (apply sub1 state) e2 let reason = BinaryOpUnificationReason "" (e1, type1) (e2, type2) sub3 <- liftUMtoTI pos reason $ mgu (apply sub2 type1) (FuncType type2 tv) return $ TypeCheckResult (sub3 `composeSubst` sub2 `composeSubst` sub1) (apply sub3 tv) (EBinOp "" ex1 ex2) PBinOp opName e1 e2 -> do case filter ((== opName) . InBuilt.opName) InBuilt.inBuiltBinaryOperations of [] -> throwError $ Positioned pos $ InternalError $ "ERROR, COULD NOT FIND OPERATION " <> opName op : _ -> do tv <- newTyVar "a" opType <- instantiate (InBuilt.opType op) TypeCheckResult s1 t1 ex1 <- ti state e1 TypeCheckResult s2 t2 ex2 <- ti (apply s1 state) e2 let reason = BinaryOpUnificationReason opName (e1, t1) (e2, t2) s3 <- liftUMtoTI pos reason $ mgu opType (t1 `FuncType` (t2 `FuncType` tv)) return $ TypeCheckResult (s3 `composeSubst` s2 `composeSubst` s1) (apply s3 tv) (EBinOp opName ex1 ex2) PAccess e1 x -> do tv <- newTyVar "a" TypeCheckResult s1 t1 ex1 <- ti state e1 let reason = AccessUnificationReason (e1, t1) x s2 <- liftUMtoTI pos reason $ mgu t1 (PolyDictType (Map.singleton x tv)) return $ TypeCheckResult (s2 `composeSubst` s1) (apply s2 tv) (EAccess ex1 x) PPrefix preOp e1 -> case filter ((== preOp) . InBuilt.opName) InBuilt.inBuiltPrefixOperations of [] -> throwError $ Positioned pos (MissingVariableError preOp) op : _ -> do let prefixScheme = InBuilt.opType op prefixType <- instantiate prefixScheme tv <- newTyVar "a" TypeCheckResult s1 t1 ex1 <- ti state e1 let reason = PrefixOpUnificationReason preOp (e1, t1) s2 <- liftUMtoTI pos reason $ mgu prefixType (t1 `FuncType` tv) return $ TypeCheckResult (s2 `composeSubst` s1) (apply s2 tv) (ENegate ex1) evaluateDimension :: Set.Set T.Text -> ParseDimension -> TI Dimension evaluateDimension allowedUnits dim = case dim of PowParseDim components -> PowDim <$> foldM addToDimensionMap Map.empty components NormalParseDim components -> NormDim <$> foldM addToDimensionMap Map.empty components where addToDimensionMap :: Map.Map PrimitiveDim Int -> Positioned ParseDimensionPart -> TI (Map.Map PrimitiveDim Int) addToDimensionMap dimMap (Positioned p (ParseDimensionPart name power)) = if Set.member name allowedUnits then return $ Map.insert (LitDim name) power dimMap else throwError $ Positioned p $ MissingUnitError name
null
https://raw.githubusercontent.com/Hazelfire/pedant/3c23572731a069691409da1264042664f6969349/src/Pedant/TypeCheck.hs
haskell
# LANGUAGE OverloadedStrings # | The state of the type checker | The environment of the checker. This contains references to all the variables and schemes of those variables currently declared. | Substitutions, the current substitutions that are required for the expression to unify | Units, the units currently declared | A list of the modules that have been checked | Unification Monad | Attempts to find a unification between dimensions unifying dimensions is a bit tricky, and this method is not perfect and leaves out some possible (but rare) unifications This is a fake execution expression, it's an argument, it's deliberately unknown Then, add these arguments to the type environment Note that this env is not env''. This is because otherwise we will add arguments as variables We want to not include those The item imported is a variable. I simply write this down as a variable declaration Is it an imported unit?
# LANGUAGE FlexibleInstances # | TypeChecker for . module Pedant.TypeCheck ( TypeEnv (..), typeCheck, TypeError (..), emptyTypeCheckState, TypeCheckState (..), VariableName (..), ) where import Control.Monad.Except import Control.Monad.State hiding (state) import qualified Data.Bifunctor import qualified Data.Map as Map import qualified Data.Map.Ordered as OMap import qualified Data.Maybe as Maybe import qualified Data.Set as Set import qualified Data.Text as T import Debug.Trace (trace, traceShowId) import qualified Pedant.FileResolver as Resolver import qualified Pedant.InBuilt as InBuilt import Pedant.Parser import Pedant.Types import qualified Text.Megaparsec as Megaparsec | A Type Error . a problem that occured during type checking data TypeError = UnificationError ReasonForUnification UnificationTrace | MissingUnitError T.Text | MissingVariableError T.Text | MissingImportError T.Text T.Text | MissingModuleError T.Text | InternalError T.Text deriving (Eq) data ReasonForUnification = BinaryOpUnificationReason T.Text (Positioned ParseExpression, Type) (Positioned ParseExpression, Type) | PrefixOpUnificationReason T.Text (Positioned ParseExpression, Type) | AccessUnificationReason (Positioned ParseExpression, Type) T.Text deriving (Eq) instance Ord (Positioned TypeError) where compare (Positioned (PositionData a _) _) (Positioned (PositionData b _) _) = compare a b type UnificationTrace = [(Type, Type)] instance Megaparsec.ShowErrorComponent (Positioned TypeError) where showErrorComponent (Positioned _ (UnificationError reason _)) = case reason of BinaryOpUnificationReason "+" (p1, t1) (p2, t2) -> T.unpack $ T.concat [ "Can only add dimension that are the same.\n", pPrint p1, " has the type ", pPrint t1, " and ", pPrint p2, " has the type ", pPrint t2 ] BinaryOpUnificationReason "-" (p1, t1) (p2, t2) -> T.unpack $ T.concat [ "Can only subtract dimensions that are the same.\n", pPrint p1, " has the type ", pPrint t1, " and ", pPrint p2, " has the type ", pPrint t2 ] BinaryOpUnificationReason op (p1, t1) (p2, t2) -> T.unpack $ T.concat [ op, " must be called on a number.\n", pPrint p1, " has the type ", pPrint t1, " and ", pPrint p2, " has the type ", pPrint t2 ] PrefixOpUnificationReason op (p1, t1) -> T.unpack $ T.concat [ op, " must be called on a number.\n", pPrint p1, " has the type ", pPrint t1 ] AccessUnificationReason (p1, t1) key -> T.unpack $ T.concat [ pPrint p1, " has type ", pPrint t1, " does not have the key ", key ] showErrorComponent (Positioned _ (MissingUnitError unitName)) = concat [ "unit ", T.unpack unitName, " not declared. Try adding a \"unit ", T.unpack unitName, "\" statement before this line" ] showErrorComponent (Positioned _ (MissingVariableError varName)) = concat [ "variable ", T.unpack varName, " not declared." ] showErrorComponent (Positioned _ (InternalError err)) = "INTERNAL ERROR. YOU SHOULD NOT BE GETTING THIS: " ++ T.unpack err showErrorComponent (Positioned _ (MissingImportError moduleName variable)) = concat [ "Could not find name ", T.unpack variable, " in module ", T.unpack moduleName, "." ] showErrorComponent (Positioned _ (MissingModuleError moduleName)) = concat [ "Could not find module ", T.unpack moduleName, "." ] errorComponentLen (Positioned (PositionData _ l) _) = l data TypeCheckState = TypeCheckState tcsEnv :: TypeEnv, tcsSubs :: Substitution, tcsUnits :: Set.Set VariableName, tcsCheckedModules :: Set.Set T.Text, tcsCurrentModule :: T.Text } emptyTypeCheckState :: TypeCheckState emptyTypeCheckState = TypeCheckState (TypeEnv OMap.empty) nullSubst Set.empty Set.empty "" nullSubst :: Substitution nullSubst = Substitution Map.empty Map.empty subUnion :: Substitution -> Substitution -> Substitution subUnion a b = Substitution { subTypes = subTypes a `Map.union` subTypes b, subDimensions = subDimensions a `Map.union` subDimensions b } composeSubst :: Substitution -> Substitution -> Substitution composeSubst s1 s2 = appliedSubs `subUnion` s1 where appliedSubs = Substitution { subTypes = Map.map (apply s1) (subTypes s2), subDimensions = Map.map (apply s1) (subDimensions s2) } newtype TypeEnv = TypeEnv (OMap.OMap VariableName (Scheme, ExecutionExpression)) deriving (Show) addToEnv :: VariableName -> (Scheme, ExecutionExpression) -> TypeEnv -> TypeEnv addToEnv key var (TypeEnv env) = TypeEnv ((key, var) OMap.|< env) instance Types TypeEnv where ftv (TypeEnv env) = ftv (map (fst . snd) $ OMap.assocs env) apply s (TypeEnv env) = TypeEnv (fmap (Data.Bifunctor.first (apply s)) env) instance Types TypeCheckState where ftv state = ftv (tcsEnv state) apply s state = state {tcsEnv = apply s (tcsEnv state)} generalize :: TypeEnv -> Type -> Scheme generalize env t = Scheme vars t where vars = Set.toList (ftv t `Set.difference` ftv env) newtype TIState = TIState {tiSupply :: Int} type TI a = ExceptT (Positioned TypeError) (State TIState) a runTI :: TI a -> (Either (Positioned TypeError) a, TIState) runTI t = runState (runExceptT t) initTIState where initTIState = TIState {tiSupply = 0} newTyVar :: T.Text -> TI Type newTyVar prefix = do s <- get put s {tiSupply = tiSupply s + 1} return (PolyType (prefix <> T.pack (show (tiSupply s)))) newTyDimension :: T.Text -> TI Dimension newTyDimension prefix = do s <- get put s {tiSupply = tiSupply s + 1} return (NormDim $ Map.singleton (PolyDim $ prefix <> T.pack (show (tiSupply s))) 1) instantiate :: Scheme -> TI Type instantiate (Scheme vars t) = do nvars <- mapM (\_ -> newTyVar "a") vars ndims <- mapM (\_ -> newTyDimension "a") vars let s = nullSubst { subTypes = Map.fromList (zip vars nvars), subDimensions = Map.fromList (zip vars ndims) } return $ apply s t type UM a = ExceptT UnificationTrace (State TIState) a liftUMtoTI :: PositionData -> ReasonForUnification -> UM a -> TI a liftUMtoTI p reason m = do initState <- get case runState (runExceptT m) initState of (Right result, state) -> do put state return result (Left err, _) -> throwError $ Positioned p $ UnificationError reason err mguDim :: Dimension -> Dimension -> UM Substitution mguDim (NormDim t) (NormDim u) = if u == t then return nullSubst let dividedOut = Map.filter (/= 0) $ Map.unionWith (+) t (Map.map negate u) polyDim = Maybe.mapMaybe ( \(k, v) -> case (k, v) of (PolyDim d, 1) -> Just (d, 1) (PolyDim d, -1) -> Just (d, -1) _ -> Nothing ) (Map.toList dividedOut) in case polyDim of (firstDim, power) : _ -> let withoutPolyVar = Map.delete (PolyDim firstDim) dividedOut dividedByPower = Map.map (`quot` (- power)) withoutPolyVar in return $ nullSubst {subDimensions = Map.singleton firstDim (NormDim dividedByPower)} [] -> throwError [(BaseDim (NormDim t), BaseDim (NormDim u))] mguDim (PowDim t) (PowDim u) = trace (show (PowDim t) ++ " unify " ++ show (PowDim u)) $ if u == t then return nullSubst else let dividedOut = Map.filter (/= 0) $ Map.unionWith (+) t (Map.map negate u) polyDim = Maybe.mapMaybe ( \(k, v) -> case (k, v) of (PolyDim d, 1) -> Just (d, 1) (PolyDim d, -1) -> Just (d, -1) _ -> Nothing ) (Map.toList (traceShowId dividedOut)) in case traceShowId polyDim of (firstDim, power) : _ -> let withoutPolyVar = Map.delete (PolyDim firstDim) dividedOut dividedByPower = Map.map (`quot` (- power)) (traceShowId withoutPolyVar) in return $ nullSubst {subDimensions = Map.singleton firstDim (PowDim (traceShowId dividedByPower))} [] -> throwError [(BaseDim (PowDim t), BaseDim (PowDim u))] mguDim (NormDim u) (PowDim t) = do I can only unify BaseDims and PowDims if they both unify to dimensionless trace (show (NormDim u) ++ " unify " ++ show (PowDim t)) $ ( do s1 <- mguDim (NormDim Map.empty) (NormDim u) s2 <- mguDim (PowDim Map.empty) (apply s1 (PowDim t)) return $ s2 `composeSubst` s1 ) `catchError` (\_ -> throwError [(BaseDim (NormDim u), BaseDim (PowDim t))]) mguDim (PowDim u) (NormDim t) = do I can only unify BaseDims and PowDims if they both unify to dimensionless s1 <- mguDim (PowDim Map.empty) (PowDim u) s2 <- mguDim (NormDim Map.empty) (apply s1 (NormDim t)) return $ s2 `composeSubst` s1 `catchError` (\_ -> throwError [(BaseDim (NormDim u), BaseDim (PowDim t))]) mgu :: Type -> Type -> UM Substitution mgu a b = wrapError a b (mgu' a b) mgu' :: Type -> Type -> UM Substitution mgu' (FuncType l r) (FuncType l' r') = do s1 <- mgu l l' s2 <- mgu (apply s1 r) (apply s1 r') return (s1 `composeSubst` s2) mgu' (PolyType u) t = varBind u t mgu' t (PolyType u) = varBind u t mgu' (BaseDim t) (BaseDim u) = mguDim t u mgu' (PolyDictType t) (DictType u) = do foldM go nullSubst (Map.toList t) where go :: Substitution -> (T.Text, Type) -> UM Substitution go sub (key, type_) = do case Map.lookup key u of Just currType -> do s1 <- mgu (apply sub type_) (apply sub currType) return (sub `composeSubst` s1) Nothing -> throwError [(PolyDictType t, DictType u)] mgu' (DictType t) (PolyDictType u) = mgu' (PolyDictType u) (DictType t) mgu' (ListType t) (ListType u) = mgu t u mgu' t1 t2 = throwError [(t1, t2)] wrapError :: Type -> Type -> UM Substitution -> UM Substitution wrapError t1 t2 child = child `catchError` addUnificationLayer where addUnificationLayer :: UnificationTrace -> UM a addUnificationLayer errStack = throwError ((t1, t2) : errStack) varBind :: T.Text -> Type -> UM Substitution varBind u t | t == PolyType u = return nullSubst | u `Set.member` ftv t = throwError [(PolyType u, t)] | otherwise = return (nullSubst {subTypes = Map.singleton u t}) typeCheck :: TypeCheckState -> [Resolver.Module] -> (Maybe (Positioned TypeError), TypeCheckState) typeCheck tcState (currentModule : rest) = trace ("Current module: " <> T.unpack (Resolver.moduleName currentModule)) $ case typeCheckFile tcState currentModule of (Just err, newState) -> (Just err, newState) (Nothing, newState) -> do typeCheck newState rest typeCheck tcState [] = (Nothing, tcState) typeCheckFile :: TypeCheckState -> Resolver.Module -> (Maybe (Positioned TypeError), TypeCheckState) typeCheckFile tcState m = let setStateModuleName = tcState {tcsCurrentModule = Resolver.moduleName m} (result, _) = runTI (inferLoop setStateModuleName (Resolver.moduleStatements m)) in case result of Right (err, state) -> let addedCheckedModule = state {tcsCheckedModules = Resolver.moduleName m `Set.insert` tcsCheckedModules setStateModuleName} in (err, addedCheckedModule) Left err -> (Just err, tcState) where inferLoop :: TypeCheckState -> [Statement] -> TI (Maybe (Positioned TypeError), TypeCheckState) inferLoop state [] = return (Nothing, state) inferLoop state (statement : rest) = let moduleName = tcsCurrentModule state in case statement of UnitStatement units -> let newUnits = tcsUnits state `Set.union` Set.fromList (map (\(Positioned _ p) -> VariableName moduleName p) units) in inferLoop (state {tcsUnits = newUnits}) rest ImportStatement importedModuleName imports -> do moduleState <- importModule moduleName importedModuleName imports state inferLoop moduleState rest AssignmentStatement assignment -> do First , assign polymorphic types to all arguments of the function ( make the definition as loose as possible ) mapPairs <- mapM ( \a -> do tv <- newTyVar a ) (assignmentArguments assignment) let (TypeEnv env) = tcsEnv state arguments = assignmentArguments assignment env'' = TypeEnv (env OMap.<>| OMap.fromList mapPairs) TypeCheckResult s1 t1 ex <- ti (state {tcsEnv = env''}) (assignmentExpression assignment) let varType = foldr (\(_, (Scheme _ tv, _)) acc -> apply s1 tv `FuncType` acc) (apply s1 t1) mapPairs name = VariableName moduleName (assignmentName assignment) t' = generalize (apply s1 env'') varType envWithVar = addToEnv name (t', wrapFunctionArgs arguments ex) (TypeEnv env) let newTcState = state { tcsEnv = envWithVar, tcsSubs = s1 `composeSubst` tcsSubs state } inferLoop newTcState rest `catchError` (\err -> return (Just err, state)) importModule :: T.Text -> Positioned T.Text -> [Positioned T.Text] -> TypeCheckState -> TI TypeCheckState importModule moduleName (Positioned moduleNamePos importedModuleName) imports oldState = trace (T.unpack ("Module name: " <> moduleName <> ", Checked modules: " <> T.pack (show (tcsCheckedModules oldState)))) $ if importedModuleName `Set.member` tcsCheckedModules oldState then do let foldImports = foldM $ \currState (Positioned importNamePos importName) -> do let (TypeEnv env) = tcsEnv currState case OMap.lookup (VariableName importedModuleName importName) env of Just (varType, _) -> let newTcState = addToEnv (VariableName moduleName importName) (varType, EVariable (VariableName importedModuleName importName)) (tcsEnv currState) in return (currState {tcsEnv = newTcState}) Nothing -> if VariableName importedModuleName importName `Set.member` tcsUnits oldState then let newUnits = VariableName moduleName importName `Set.insert` tcsUnits currState in return (currState {tcsUnits = newUnits}) else throwError $ Positioned importNamePos (MissingImportError importedModuleName importName) foldImports oldState imports else throwError $ Positioned moduleNamePos (MissingModuleError importedModuleName) wrapFunctionArgs :: [T.Text] -> ExecutionExpression -> ExecutionExpression wrapFunctionArgs (arg : rest) expr = EConstant (ExecutionValueFunc arg (wrapFunctionArgs rest expr)) wrapFunctionArgs [] expr = expr data TypeCheckResult = TypeCheckResult Substitution Type ExecutionExpression foldSubst :: Traversable t => t Substitution -> Substitution foldSubst = foldr composeSubst nullSubst ti :: TypeCheckState -> Positioned ParseExpression -> TI TypeCheckResult ti state (Positioned pos expression) = let (TypeEnv env) = tcsEnv state allowedUnits = Set.filter (\(VariableName moduleName _) -> moduleName == tcsCurrentModule state) $ tcsUnits state in case expression of PVariable n -> case OMap.lookup (VariableName (tcsCurrentModule state) n) env of Nothing -> case filter ((== n) . InBuilt.funcName) InBuilt.inBuiltFunctions of func : _ -> do t <- instantiate (InBuilt.funcType func) return $ TypeCheckResult nullSubst t (EInternalFunc $ InBuilt.funcDef func) [] -> throwError $ Positioned pos $ MissingVariableError n Just (sigma, _) -> do t <- instantiate sigma return $ TypeCheckResult nullSubst t (EVariable (VariableName (tcsCurrentModule state) n)) PConstant (ParseNumber value pdim) -> do dimension <- evaluateDimension (Set.map (\(VariableName _ name) -> name) allowedUnits) pdim return $ TypeCheckResult nullSubst (BaseDim dimension) (EConstant $ ExecutionValueNumber value) PConstant ParseEmptyList -> do let emptyListType = Scheme ["a", "t"] $ ListType (BaseDim (NormDim (Map.singleton (PolyDim "a") 1))) dim <- instantiate emptyListType return $ TypeCheckResult nullSubst dim (EConstant ExecutionValueEmptyList) PConstant (ParseRecord record) -> do recordEntries <- forM (Map.toList record) $ \(key, el) -> do TypeCheckResult sub _type ex <- ti state el return (key, (sub, _type, ex)) let dimension = map (\(key, (_, d, _)) -> (key, d)) recordEntries elems = map (\(key, (_, _, value)) -> (key, value)) recordEntries substitutions = map (\(_, (sub, _, _)) -> sub) recordEntries return $ TypeCheckResult (foldSubst substitutions) (DictType (Map.fromList dimension)) (EConstant $ ExecutionValueDict (Map.fromList elems)) PBinOp "" e1 e2 -> do tv <- newTyVar "a" TypeCheckResult sub1 type1 ex1 <- ti state e1 TypeCheckResult sub2 type2 ex2 <- ti (apply sub1 state) e2 let reason = BinaryOpUnificationReason "" (e1, type1) (e2, type2) sub3 <- liftUMtoTI pos reason $ mgu (apply sub2 type1) (FuncType type2 tv) return $ TypeCheckResult (sub3 `composeSubst` sub2 `composeSubst` sub1) (apply sub3 tv) (EBinOp "" ex1 ex2) PBinOp opName e1 e2 -> do case filter ((== opName) . InBuilt.opName) InBuilt.inBuiltBinaryOperations of [] -> throwError $ Positioned pos $ InternalError $ "ERROR, COULD NOT FIND OPERATION " <> opName op : _ -> do tv <- newTyVar "a" opType <- instantiate (InBuilt.opType op) TypeCheckResult s1 t1 ex1 <- ti state e1 TypeCheckResult s2 t2 ex2 <- ti (apply s1 state) e2 let reason = BinaryOpUnificationReason opName (e1, t1) (e2, t2) s3 <- liftUMtoTI pos reason $ mgu opType (t1 `FuncType` (t2 `FuncType` tv)) return $ TypeCheckResult (s3 `composeSubst` s2 `composeSubst` s1) (apply s3 tv) (EBinOp opName ex1 ex2) PAccess e1 x -> do tv <- newTyVar "a" TypeCheckResult s1 t1 ex1 <- ti state e1 let reason = AccessUnificationReason (e1, t1) x s2 <- liftUMtoTI pos reason $ mgu t1 (PolyDictType (Map.singleton x tv)) return $ TypeCheckResult (s2 `composeSubst` s1) (apply s2 tv) (EAccess ex1 x) PPrefix preOp e1 -> case filter ((== preOp) . InBuilt.opName) InBuilt.inBuiltPrefixOperations of [] -> throwError $ Positioned pos (MissingVariableError preOp) op : _ -> do let prefixScheme = InBuilt.opType op prefixType <- instantiate prefixScheme tv <- newTyVar "a" TypeCheckResult s1 t1 ex1 <- ti state e1 let reason = PrefixOpUnificationReason preOp (e1, t1) s2 <- liftUMtoTI pos reason $ mgu prefixType (t1 `FuncType` tv) return $ TypeCheckResult (s2 `composeSubst` s1) (apply s2 tv) (ENegate ex1) evaluateDimension :: Set.Set T.Text -> ParseDimension -> TI Dimension evaluateDimension allowedUnits dim = case dim of PowParseDim components -> PowDim <$> foldM addToDimensionMap Map.empty components NormalParseDim components -> NormDim <$> foldM addToDimensionMap Map.empty components where addToDimensionMap :: Map.Map PrimitiveDim Int -> Positioned ParseDimensionPart -> TI (Map.Map PrimitiveDim Int) addToDimensionMap dimMap (Positioned p (ParseDimensionPart name power)) = if Set.member name allowedUnits then return $ Map.insert (LitDim name) power dimMap else throwError $ Positioned p $ MissingUnitError name
9076d787eca6e687dd9f5c616baeb0e1507ad3ccaecf280d59ecb735140b5864
lmj/lparallel
cons-queue.lisp
Copyright ( c ) 2011 - 2013 , . 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 project 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 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. (defpackage #:lparallel.cons-queue (:documentation "(private) Blocking infinite-capacity queue.") (:use #:cl #:lparallel.util #:lparallel.thread-util #:lparallel.raw-queue) (:export #:cons-queue #:make-cons-queue #:push-cons-queue #:push-cons-queue/no-lock #:pop-cons-queue #:pop-cons-queue/no-lock #:peek-cons-queue #:peek-cons-queue/no-lock #:cons-queue-count #:cons-queue-count/no-lock #:cons-queue-empty-p #:cons-queue-empty-p/no-lock #:try-pop-cons-queue #:try-pop-cons-queue/no-lock #:with-locked-cons-queue) (:import-from #:lparallel.thread-util #:define-locking-fn #:define-simple-locking-fn #:with-countdown #:time-remaining)) (in-package #:lparallel.cons-queue) (defslots cons-queue () ((impl :reader impl :type raw-queue) (lock :reader lock :initform (make-lock)) (cvar :initform nil))) (defun %make-cons-queue () (make-cons-queue-instance :impl (make-raw-queue))) (defmacro with-locked-cons-queue (queue &body body) `(with-lock-held ((lock ,queue)) ,@body)) (define-locking-fn push-cons-queue (object queue) (t cons-queue) (values) lock (with-cons-queue-slots (impl cvar) queue (push-raw-queue object impl) (when cvar (condition-notify cvar))) (values)) (define-locking-fn pop-cons-queue (queue) (cons-queue) t lock (with-cons-queue-slots (impl lock cvar) queue (loop (multiple-value-bind (value presentp) (pop-raw-queue impl) (if presentp (return value) (condition-wait (or cvar (setf cvar (make-condition-variable))) lock)))))) (defun %try-pop-cons-queue/no-lock/timeout (queue timeout) ;; queue is empty and timeout is positive (declare #.*full-optimize*) (with-countdown (timeout) (with-cons-queue-slots (impl lock cvar) queue (loop (multiple-value-bind (value presentp) (pop-raw-queue impl) (when presentp (return (values value t))) (let ((time-remaining (time-remaining))) (when (or (not (plusp time-remaining)) (null (condition-wait (or cvar (setf cvar (make-condition-variable))) lock :timeout time-remaining))) (return (values nil nil))))))))) (defun try-pop-cons-queue/no-lock/timeout (queue timeout) (declare #.*full-optimize*) (with-cons-queue-slots (impl) queue (if (raw-queue-empty-p impl) (%try-pop-cons-queue/no-lock/timeout queue timeout) (pop-raw-queue impl)))) (defun try-pop-cons-queue (queue timeout) (declare #.*full-optimize*) (with-cons-queue-slots (impl lock) queue (cond ((plusp timeout) (with-lock-held (lock) (try-pop-cons-queue/no-lock/timeout queue timeout))) (t ;; optimization: don't lock if nothing is there (with-lock-predicate/wait lock (not (raw-queue-empty-p impl)) (return-from try-pop-cons-queue (pop-raw-queue impl))) (values nil nil))))) (defun try-pop-cons-queue/no-lock (queue timeout) (declare #.*full-optimize*) (if (plusp timeout) (try-pop-cons-queue/no-lock/timeout queue timeout) (pop-raw-queue (impl queue)))) (defmacro define-queue-fn (name arg-types raw return-type) `(define-simple-locking-fn ,name (queue) ,arg-types ,return-type lock (,raw (impl queue)))) (define-queue-fn cons-queue-count (cons-queue) raw-queue-count raw-queue-count) (define-queue-fn cons-queue-empty-p (cons-queue) raw-queue-empty-p boolean) (define-queue-fn peek-cons-queue (cons-queue) peek-raw-queue (values t boolean)) (defun make-cons-queue (&key initial-contents) (let ((queue (%make-cons-queue))) (when initial-contents (flet ((push-elem (elem) (push-cons-queue/no-lock elem queue))) (declare (dynamic-extent #'push-elem)) (map nil #'push-elem initial-contents))) queue))
null
https://raw.githubusercontent.com/lmj/lparallel/9c11f40018155a472c540b63684049acc9b36e15/src/cons-queue.lisp
lisp
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 project 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 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT LOSS OF USE , DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. queue is empty and timeout is positive optimization: don't lock if nothing is there
Copyright ( c ) 2011 - 2013 , . All rights reserved . " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT HOLDER OR FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT (defpackage #:lparallel.cons-queue (:documentation "(private) Blocking infinite-capacity queue.") (:use #:cl #:lparallel.util #:lparallel.thread-util #:lparallel.raw-queue) (:export #:cons-queue #:make-cons-queue #:push-cons-queue #:push-cons-queue/no-lock #:pop-cons-queue #:pop-cons-queue/no-lock #:peek-cons-queue #:peek-cons-queue/no-lock #:cons-queue-count #:cons-queue-count/no-lock #:cons-queue-empty-p #:cons-queue-empty-p/no-lock #:try-pop-cons-queue #:try-pop-cons-queue/no-lock #:with-locked-cons-queue) (:import-from #:lparallel.thread-util #:define-locking-fn #:define-simple-locking-fn #:with-countdown #:time-remaining)) (in-package #:lparallel.cons-queue) (defslots cons-queue () ((impl :reader impl :type raw-queue) (lock :reader lock :initform (make-lock)) (cvar :initform nil))) (defun %make-cons-queue () (make-cons-queue-instance :impl (make-raw-queue))) (defmacro with-locked-cons-queue (queue &body body) `(with-lock-held ((lock ,queue)) ,@body)) (define-locking-fn push-cons-queue (object queue) (t cons-queue) (values) lock (with-cons-queue-slots (impl cvar) queue (push-raw-queue object impl) (when cvar (condition-notify cvar))) (values)) (define-locking-fn pop-cons-queue (queue) (cons-queue) t lock (with-cons-queue-slots (impl lock cvar) queue (loop (multiple-value-bind (value presentp) (pop-raw-queue impl) (if presentp (return value) (condition-wait (or cvar (setf cvar (make-condition-variable))) lock)))))) (defun %try-pop-cons-queue/no-lock/timeout (queue timeout) (declare #.*full-optimize*) (with-countdown (timeout) (with-cons-queue-slots (impl lock cvar) queue (loop (multiple-value-bind (value presentp) (pop-raw-queue impl) (when presentp (return (values value t))) (let ((time-remaining (time-remaining))) (when (or (not (plusp time-remaining)) (null (condition-wait (or cvar (setf cvar (make-condition-variable))) lock :timeout time-remaining))) (return (values nil nil))))))))) (defun try-pop-cons-queue/no-lock/timeout (queue timeout) (declare #.*full-optimize*) (with-cons-queue-slots (impl) queue (if (raw-queue-empty-p impl) (%try-pop-cons-queue/no-lock/timeout queue timeout) (pop-raw-queue impl)))) (defun try-pop-cons-queue (queue timeout) (declare #.*full-optimize*) (with-cons-queue-slots (impl lock) queue (cond ((plusp timeout) (with-lock-held (lock) (try-pop-cons-queue/no-lock/timeout queue timeout))) (t (with-lock-predicate/wait lock (not (raw-queue-empty-p impl)) (return-from try-pop-cons-queue (pop-raw-queue impl))) (values nil nil))))) (defun try-pop-cons-queue/no-lock (queue timeout) (declare #.*full-optimize*) (if (plusp timeout) (try-pop-cons-queue/no-lock/timeout queue timeout) (pop-raw-queue (impl queue)))) (defmacro define-queue-fn (name arg-types raw return-type) `(define-simple-locking-fn ,name (queue) ,arg-types ,return-type lock (,raw (impl queue)))) (define-queue-fn cons-queue-count (cons-queue) raw-queue-count raw-queue-count) (define-queue-fn cons-queue-empty-p (cons-queue) raw-queue-empty-p boolean) (define-queue-fn peek-cons-queue (cons-queue) peek-raw-queue (values t boolean)) (defun make-cons-queue (&key initial-contents) (let ((queue (%make-cons-queue))) (when initial-contents (flet ((push-elem (elem) (push-cons-queue/no-lock elem queue))) (declare (dynamic-extent #'push-elem)) (map nil #'push-elem initial-contents))) queue))
8fb310c455e2aaa9542b2b6755aa8013ef8505784a17f4d530834840607f44b3
alura-cursos/datomic-introducao
project.clj
(defproject ecommerce "0.1.0-SNAPSHOT" :description "FIXME: write description" :url "" :license {:name "EPL-2.0 OR GPL-2.0-or-later WITH Classpath-exception-2.0" :url "-2.0/"} :dependencies [[org.clojure/clojure "1.10.0"] [com.datomic/datomic-pro "0.9.5951"]] :repl-options {:init-ns ecommerce.core} )
null
https://raw.githubusercontent.com/alura-cursos/datomic-introducao/cfb214135fed0670ee90090b63a38d8287673ac6/aula1.2/ecommerce/project.clj
clojure
(defproject ecommerce "0.1.0-SNAPSHOT" :description "FIXME: write description" :url "" :license {:name "EPL-2.0 OR GPL-2.0-or-later WITH Classpath-exception-2.0" :url "-2.0/"} :dependencies [[org.clojure/clojure "1.10.0"] [com.datomic/datomic-pro "0.9.5951"]] :repl-options {:init-ns ecommerce.core} )
ab6d7e513d7a2234aa18334313845fc0a1c272e68609a33ef8652939d535ccc2
RedPRL/algaett
EmojiToken.ml
[@@@warning "-39"] (* the preprocessor sometimes generates useless 'rec' *) open Earley_core module StringSet = Set.Make (String) module EmojiSet = struct let all = StringSet.of_list Emoji.all_emojis let question_mark = StringSet.of_list Emoji.[ exclamation_question_mark; red_question_mark; white_question_mark; ] let sep = StringSet.of_list Emoji.[ small_orange_diamond; small_blue_diamond; ] let other_symbol = StringSet.of_list Emoji.[ bullseye; keycap_asterisk; (* Keycap Asterisk *) up_arrow; up_button; right_arrow; left_arrow_curving_right; backhand_index_pointing_right; backhand_index_pointing_right_light_skin_tone; backhand_index_pointing_right_medium_light_skin_tone; backhand_index_pointing_right_medium_skin_tone; backhand_index_pointing_right_medium_dark_skin_tone; backhand_index_pointing_right_dark_skin_tone; multiply; plus; minus; heavy_equals_sign; ] let symbol = List.fold_left StringSet.union StringSet.empty [question_mark; sep; other_symbol] let alnum = StringSet.diff all symbol let num = StringSet.of_list Emoji.[ keycap_0; keycap_1; keycap_2; keycap_3; keycap_4; keycap_5; keycap_6; keycap_7; keycap_8; keycap_9; keycap_10; hundred_points; ] let alpha = StringSet.diff alnum num end (* to_rev_seq is used so that skin tones will definitely be consumed *) let of_set s = Earley.(no_blank_layout @@ alternatives @@ List.map (fun s -> greedy (string s s)) @@ List.of_seq @@ StringSet.to_rev_seq s) let parser sep = (of_set EmojiSet.sep) -> () let alnum = of_set EmojiSet.alnum let alpha = of_set EmojiSet.alpha let parser raw_seg_ = x:alpha - xs:alnum* -> String.concat "" (x :: xs) let raw_seg = Earley.(no_blank_layout @@ greedy @@ raw_seg_) let keywords = let open KeywordClass in let module S = Elaborator.Syntax in Hashtbl.of_seq @@ List.to_seq [ Emoji.(keycap_number_sign ^ keycap_1), TermField (fun tm -> S.Fst tm); Emoji.(keycap_number_sign ^ keycap_2), TermField (fun tm -> S.Snd tm); Emoji.milky_way, TermConstant (fun ~shift -> S.Univ shift); Emoji.pushpin, CmdDef; Emoji.round_pushpin, CmdDef; Emoji.folded_hands, CmdAxiom; Emoji.folded_hands_light_skin_tone, CmdAxiom; Emoji.folded_hands_medium_light_skin_tone, CmdAxiom; Emoji.folded_hands_medium_skin_tone, CmdAxiom; Emoji.folded_hands_medium_dark_skin_tone, CmdAxiom; Emoji.folded_hands_dark_skin_tone, CmdAxiom; Emoji.stop_sign, CmdQuit; Emoji.inbox_tray, CmdImport; Emoji.umbrella, CmdSectionStart {tag = [Emoji.umbrella]}; Emoji.closed_umbrella, CmdSectionEnd {check_tag = fun t -> t = [Emoji.umbrella]}; ] let keyword = raw_seg |> Earley.apply @@ fun token -> match Hashtbl.find_opt keywords token with | Some k -> k | None -> Earley.give_up () let seg = raw_seg |> Earley.apply @@ fun token -> match Hashtbl.mem keywords token with | true -> Earley.give_up () | false -> token let name = Earley.list1 seg sep let parser digit = | STR(Emoji.keycap_0) -> "0" | STR(Emoji.keycap_1) -> "1" | STR(Emoji.keycap_2) -> "2" | STR(Emoji.keycap_3) -> "3" | STR(Emoji.keycap_4) -> "4" | STR(Emoji.keycap_5) -> "5" | STR(Emoji.keycap_6) -> "6" | STR(Emoji.keycap_7) -> "7" | STR(Emoji.keycap_8) -> "8" | STR(Emoji.keycap_9) -> "9" | STR(Emoji.keycap_10) -> "10" | STR(Emoji.hundred_points) -> "100" let parser pos_num_ = | ds:digit+ -> match int_of_string_opt (String.concat "" ds) with | Some i -> i | None -> Earley.give_up () let pos_num = Earley.no_blank_layout pos_num_ let parser num_ = | STR(Emoji.plus)? i:pos_num_ -> i | STR(Emoji.minus) i:pos_num_ -> -i let num = Earley.no_blank_layout num_
null
https://raw.githubusercontent.com/RedPRL/algaett/5685e49608aaf230f5691f3e339cd2bd3acb6ec9/src/parser/EmojiToken.ml
ocaml
the preprocessor sometimes generates useless 'rec' Keycap Asterisk to_rev_seq is used so that skin tones will definitely be consumed
open Earley_core module StringSet = Set.Make (String) module EmojiSet = struct let all = StringSet.of_list Emoji.all_emojis let question_mark = StringSet.of_list Emoji.[ exclamation_question_mark; red_question_mark; white_question_mark; ] let sep = StringSet.of_list Emoji.[ small_orange_diamond; small_blue_diamond; ] let other_symbol = StringSet.of_list Emoji.[ bullseye; up_arrow; up_button; right_arrow; left_arrow_curving_right; backhand_index_pointing_right; backhand_index_pointing_right_light_skin_tone; backhand_index_pointing_right_medium_light_skin_tone; backhand_index_pointing_right_medium_skin_tone; backhand_index_pointing_right_medium_dark_skin_tone; backhand_index_pointing_right_dark_skin_tone; multiply; plus; minus; heavy_equals_sign; ] let symbol = List.fold_left StringSet.union StringSet.empty [question_mark; sep; other_symbol] let alnum = StringSet.diff all symbol let num = StringSet.of_list Emoji.[ keycap_0; keycap_1; keycap_2; keycap_3; keycap_4; keycap_5; keycap_6; keycap_7; keycap_8; keycap_9; keycap_10; hundred_points; ] let alpha = StringSet.diff alnum num end let of_set s = Earley.(no_blank_layout @@ alternatives @@ List.map (fun s -> greedy (string s s)) @@ List.of_seq @@ StringSet.to_rev_seq s) let parser sep = (of_set EmojiSet.sep) -> () let alnum = of_set EmojiSet.alnum let alpha = of_set EmojiSet.alpha let parser raw_seg_ = x:alpha - xs:alnum* -> String.concat "" (x :: xs) let raw_seg = Earley.(no_blank_layout @@ greedy @@ raw_seg_) let keywords = let open KeywordClass in let module S = Elaborator.Syntax in Hashtbl.of_seq @@ List.to_seq [ Emoji.(keycap_number_sign ^ keycap_1), TermField (fun tm -> S.Fst tm); Emoji.(keycap_number_sign ^ keycap_2), TermField (fun tm -> S.Snd tm); Emoji.milky_way, TermConstant (fun ~shift -> S.Univ shift); Emoji.pushpin, CmdDef; Emoji.round_pushpin, CmdDef; Emoji.folded_hands, CmdAxiom; Emoji.folded_hands_light_skin_tone, CmdAxiom; Emoji.folded_hands_medium_light_skin_tone, CmdAxiom; Emoji.folded_hands_medium_skin_tone, CmdAxiom; Emoji.folded_hands_medium_dark_skin_tone, CmdAxiom; Emoji.folded_hands_dark_skin_tone, CmdAxiom; Emoji.stop_sign, CmdQuit; Emoji.inbox_tray, CmdImport; Emoji.umbrella, CmdSectionStart {tag = [Emoji.umbrella]}; Emoji.closed_umbrella, CmdSectionEnd {check_tag = fun t -> t = [Emoji.umbrella]}; ] let keyword = raw_seg |> Earley.apply @@ fun token -> match Hashtbl.find_opt keywords token with | Some k -> k | None -> Earley.give_up () let seg = raw_seg |> Earley.apply @@ fun token -> match Hashtbl.mem keywords token with | true -> Earley.give_up () | false -> token let name = Earley.list1 seg sep let parser digit = | STR(Emoji.keycap_0) -> "0" | STR(Emoji.keycap_1) -> "1" | STR(Emoji.keycap_2) -> "2" | STR(Emoji.keycap_3) -> "3" | STR(Emoji.keycap_4) -> "4" | STR(Emoji.keycap_5) -> "5" | STR(Emoji.keycap_6) -> "6" | STR(Emoji.keycap_7) -> "7" | STR(Emoji.keycap_8) -> "8" | STR(Emoji.keycap_9) -> "9" | STR(Emoji.keycap_10) -> "10" | STR(Emoji.hundred_points) -> "100" let parser pos_num_ = | ds:digit+ -> match int_of_string_opt (String.concat "" ds) with | Some i -> i | None -> Earley.give_up () let pos_num = Earley.no_blank_layout pos_num_ let parser num_ = | STR(Emoji.plus)? i:pos_num_ -> i | STR(Emoji.minus) i:pos_num_ -> -i let num = Earley.no_blank_layout num_
e9972488a7e8d2e489cf4ae09f85362fa0198870eb170d522523a492a1616d13
crategus/cl-cffi-gtk
gio.permission.lisp
;;; ---------------------------------------------------------------------------- gio.permission.lisp ;;; ;;; The documentation of this file is taken from the GIO Reference Manual Version 2.68 and modified to document the Lisp binding to the GIO library . ;;; See <>. The API documentation of the Lisp binding is available from < -cffi-gtk/ > . ;;; Copyright ( C ) 2021 ;;; ;;; This program is free software: you can redistribute it and/or modify ;;; it under the terms of the GNU Lesser General Public License for Lisp as published by the Free Software Foundation , either version 3 of the ;;; License, or (at your option) any later version and with a preamble to the GNU Lesser General Public License that clarifies the terms for use ;;; with Lisp programs and is referred as the LLGPL. ;;; ;;; This program is distributed in the hope that it will be useful, ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details . ;;; You should have received a copy of the GNU Lesser General Public License along with this program and the preamble to the Gnu Lesser ;;; General Public License. If not, see </> ;;; and <>. ;;; ---------------------------------------------------------------------------- ;;; ;;; GPermission ;;; ;;; An object representing the permission to perform a certain action ;;; ;;; Types and Values ;;; ;;; GPermission ;;; ;;; Functions ;;; ;;; g_permission_get_allowed ;;; g_permission_get_can_acquire ;;; g_permission_get_can_release ;;; g_permission_acquire ;;; g_permission_acquire_async ;;; g_permission_acquire_finish ;;; g_permission_release ;;; g_permission_release_async ;;; g_permission_release_finish ;;; g_permission_impl_update ;;; ;;; Properties ;;; ;;; gboolean allowed ;;; gboolean can-acquire ;;; gboolean can-release ;;; ;;; Object Hierarchy ;;; ;;; GObject ;;; ╰── GPermission ;;; ╰── GSimplePermission ;;; ---------------------------------------------------------------------------- (in-package :gio) ;;; ---------------------------------------------------------------------------- ;;; GPermission ;;; ---------------------------------------------------------------------------- (define-g-object-class "GPermission" g-permission (:superclass g-object :export t :interfaces () :type-initializer "g_permission_get_type") ((allowed g-permission-allowed "allowed" "gboolean" t nil) (can-acquire g-permission-can-acquire "can-acquire" "gboolean" t nil) (can-release g-permission-can-release "can-release" "gboolean" t nil))) #+cl-cffi-gtk-documentation (setf (documentation 'g-permission 'type) "@version{2021-12-23} @begin{short} A @sym{g-permission} object represents the status of the permission of the caller to perform a certain action. @end{short} You can query if the action is currently allowed and if it is possible to acquire the permission so that the action will be allowed in the future. There is also an API to actually acquire the permission and one to release it. As an example, a @sym{g-permission} object might represent the ability for the user to write to a @class{g-settings} object. This @sym{g-permission} object could then be used to decide if it is appropriate to show a \"Click here to unlock\" button in a dialog and to provide the mechanism to invoke when that button is clicked. @see-slot{g-permission-allowed} @see-slot{g-permission-can-acquire} @see-slot{g-permission-can-release} @see-class{g-simple-permission}") ;;; ---------------------------------------------------------------------------- ;;; Property and Accessor Details ;;; ---------------------------------------------------------------------------- ;;; --- g-permission-allowed --------------------------------------------------- #+cl-cffi-gtk-documentation (setf (documentation (atdoc:get-slot-from-name "allowed" 'g-permission) 't) "The @code{allowed} property of type @code{:boolean} (Read) @br{} @em{True} if the caller currently has permission to perform the action that the @sym{g-permission} object represents the permission to perform. @br{} Default value: @em{false}") #+cl-cffi-gtk-documentation (setf (gethash 'g-permission-allowed atdoc:*function-name-alias*) "Accessor" (documentation 'g-permission-allowed 'function) "@version{2021-12-23} @syntax[]{(g-permission-allowed object) => allowed} @argument[object]{a @class{g-permission} object} @argument[allowed]{a boolean whether the caller currently has permission to perform the action} @begin{short} Accessor of the @slot[g-permission]{allowed} slot of the @class{g-permission} class. @end{short} The @sym{g-permission-allowed} slot access function gets the value of the property. This property is @em{true} if the caller currently has permission to perform the action that the @class{g-permission} object represents the permission to perform. @see-class{g-permission}") ;;; --- g-permission-can-acquire ----------------------------------------------- #+cl-cffi-gtk-documentation (setf (documentation (atdoc:get-slot-from-name "can-acquire" 'g-permission) 't) "The @code{can-acquire} property of type @code{:boolean} (Read) @br{} @em{True} if it is generally possible to acquire the permission by calling the @fun{g-permission-acquire} function. @br{} Default value: @em{false}") #+cl-cffi-gtk-documentation (setf (gethash 'g-permission-can-acquire atdoc:*function-name-alias*) "Accessor" (documentation 'g-permission-can-acquire 'function) "@version{2021-12-23} @syntax[]{(g-permission-can-acquire object) => can-acquire} @argument[object]{a @class{g-permission} object} @argument[can-acquire]{a boolean whether it is generally possible to acquire the permission} @begin{short} Accessor of the @slot[g-permission]{can-acquire} slot of the @class{g-permission} class. @end{short} The @sym{g-permission-can-acquire} slot access function gets the value of the property. This property is @em{true} if it is generally possible to acquire the permission by calling the @fun{g-permission-acquire} function. @see-class{g-permission} @see-function{g-permission-acquire}") ;;; --- g-permission-can-release ----------------------------------------------- #+cl-cffi-gtk-documentation (setf (documentation (atdoc:get-slot-from-name "can-release" 'g-permission) 't) "The @code{can-release} property of type @code{:boolean} (Read) @br{} @em{True} if it is generally possible to release the permission by calling the @fun{g-permission-release} function. @br{} Default value: @em{false}") #+cl-cffi-gtk-documentation (setf (gethash 'g-permission-can-release atdoc:*function-name-alias*) "Accessor" (documentation 'g-permission-can-release 'function) "@version{2021-12-23} @syntax[]{(g-permission-can-release object) => can-release} @argument[object]{a @class{g-permission} object} @argument[can-release]{a boolean whether it is generally possible to release the permission} @begin{short} Accessor of the @slot[g-permission]{can-release} slot of the @class{g-permission} class. @end{short} The @sym{g-permission-can-release} slot access function gets the value of the property. This property is @em{true} if it is generally possible to release the permission by calling the @fun{g-permission-release} function. @see-class{g-permission} @see-function{g-permission-release}") ;;; ---------------------------------------------------------------------------- ;;; g_permission_acquire () ;;; ;;; gboolean ;;; g_permission_acquire (GPermission *permission, ;;; GCancellable *cancellable, GError * * error ) ; ;;; ;;; Attempts to acquire the permission represented by permission . ;;; ;;; The precise method by which this happens depends on the permission and the ;;; underlying authentication mechanism. A simple example is that a dialog may ;;; appear asking the user to enter their password. ;;; ;;; You should check with g_permission_get_can_acquire() before calling this ;;; function. ;;; ;;; If the permission is acquired then TRUE is returned. Otherwise, FALSE is ;;; returned and error is set appropriately. ;;; ;;; This call is blocking, likely for a very long time (in the case that user ;;; interaction is required). See g_permission_acquire_async() for the ;;; non-blocking version. ;;; ;;; permission : ;;; a GPermission instance ;;; ;;; cancellable : ;;; a GCancellable, or NULL. ;;; ;;; error : a pointer to a NULL GError , or NULL ;;; ;;; Returns : ;;; TRUE if the permission was successfully acquired ;;; Since : 2.26 ;;; ---------------------------------------------------------------------------- ;;; ---------------------------------------------------------------------------- ;;; g_permission_acquire_async () ;;; ;;; void ;;; g_permission_acquire_async (GPermission *permission, ;;; GCancellable *cancellable, ;;; GAsyncReadyCallback callback, ;;; gpointer user_data); ;;; ;;; Attempts to acquire the permission represented by permission . ;;; This is the first half of the asynchronous version of ;;; g_permission_acquire(). ;;; ;;; permission : ;;; a GPermission instance ;;; ;;; cancellable : ;;; a GCancellable, or NULL. ;;; ;;; callback : ;;; the GAsyncReadyCallback to call when done ;;; ;;; user_data : ;;; the user data to pass to callback ;;; Since : 2.26 ;;; ---------------------------------------------------------------------------- ;;; ---------------------------------------------------------------------------- ;;; g_permission_acquire_finish () ;;; ;;; gboolean ;;; g_permission_acquire_finish (GPermission *permission, ;;; GAsyncResult *result, ;;; GError **error); ;;; ;;; Collects the result of attempting to acquire the permission represented by ;;; permission . ;;; This is the second half of the asynchronous version of ;;; g_permission_acquire(). ;;; ;;; permission : ;;; a GPermission instance ;;; ;;; result : the GAsyncResult given to the GAsyncReadyCallback ;;; ;;; error : a pointer to a NULL GError , or NULL ;;; ;;; Returns : ;;; TRUE if the permission was successfully acquired ;;; Since : 2.26 ;;; ---------------------------------------------------------------------------- ;;; ---------------------------------------------------------------------------- ;;; g_permission_release () ;;; ;;; gboolean ;;; g_permission_release (GPermission *permission, ;;; GCancellable *cancellable, GError * * error ) ; ;;; ;;; Attempts to release the permission represented by permission . ;;; ;;; The precise method by which this happens depends on the permission and the ;;; underlying authentication mechanism. In most cases the permission will be ;;; dropped immediately without further action. ;;; ;;; You should check with g_permission_get_can_release() before calling this ;;; function. ;;; ;;; If the permission is released then TRUE is returned. Otherwise, FALSE is ;;; returned and error is set appropriately. ;;; ;;; This call is blocking, likely for a very long time (in the case that user ;;; interaction is required). See g_permission_release_async() for the ;;; non-blocking version. ;;; ;;; ;;; permission : ;;; a GPermission instance ;;; ;;; cancellable : ;;; a GCancellable, or NULL. ;;; ;;; error : a pointer to a NULL GError , or NULL ;;; ;;; Returns : ;;; TRUE if the permission was successfully released ;;; Since : 2.26 ;;; ---------------------------------------------------------------------------- ;;; ---------------------------------------------------------------------------- ;;; g_permission_release_async () ;;; ;;; void ;;; g_permission_release_async (GPermission *permission, ;;; GCancellable *cancellable, ;;; GAsyncReadyCallback callback, ;;; gpointer user_data); ;;; ;;; Attempts to release the permission represented by permission . ;;; This is the first half of the asynchronous version of ;;; g_permission_release(). ;;; ;;; permission : ;;; a GPermission instance ;;; ;;; cancellable : ;;; a GCancellable, or NULL. ;;; ;;; callback : ;;; the GAsyncReadyCallback to call when done ;;; ;;; user_data : ;;; the user data to pass to callback ;;; Since : 2.26 ;;; ---------------------------------------------------------------------------- ;;; ---------------------------------------------------------------------------- g_permission_release_finish ( ) ;;; ;;; gboolean g_permission_release_finish ( GPermission * permission , ;;; GAsyncResult *result, ;;; GError **error); ;;; ;;; Collects the result of attempting to release the permission represented by ;;; permission . ;;; This is the second half of the asynchronous version of ;;; g_permission_release(). ;;; ;;; permission : ;;; a GPermission instance ;;; ;;; result : the GAsyncResult given to the GAsyncReadyCallback ;;; ;;; error : a pointer to a NULL GError , or NULL ;;; ;;; Returns : ;;; TRUE if the permission was successfully released ;;; Since : 2.26 ;;; ---------------------------------------------------------------------------- ;;; ---------------------------------------------------------------------------- ;;; g_permission_impl_update () ;;; ;;; void ;;; g_permission_impl_update (GPermission *permission, ;;; gboolean allowed, , ) ; ;;; This function is called by the GPermission implementation to update the ;;; properties of the permission. You should never call this function except from a GPermission implementation . ;;; ;;; GObject notify signals are generated, as appropriate. ;;; ;;; permission : ;;; a GPermission instance ;;; ;;; allowed : ;;; the new value for the 'allowed' property ;;; ;;; can_acquire : ;;; the new value for the 'can-acquire' property ;;; ;;; can_release : ;;; the new value for the 'can-release' property ;;; Since : 2.26 ;;; ---------------------------------------------------------------------------- ;;; --- End of file gio.permission.lisp ----------------------------------------
null
https://raw.githubusercontent.com/crategus/cl-cffi-gtk/ba198f7d29cb06de1e8965e1b8a78522d5430516/gio/gio.permission.lisp
lisp
---------------------------------------------------------------------------- The documentation of this file is taken from the GIO Reference Manual See <>. The API documentation of the Lisp binding is This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License for Lisp License, or (at your option) any later version and with a preamble to with Lisp programs and is referred as the LLGPL. 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 General Public License. If not, see </> and <>. ---------------------------------------------------------------------------- GPermission An object representing the permission to perform a certain action Types and Values GPermission Functions g_permission_get_allowed g_permission_get_can_acquire g_permission_get_can_release g_permission_acquire g_permission_acquire_async g_permission_acquire_finish g_permission_release g_permission_release_async g_permission_release_finish g_permission_impl_update Properties gboolean allowed gboolean can-acquire gboolean can-release Object Hierarchy GObject ╰── GPermission ╰── GSimplePermission ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- GPermission ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- Property and Accessor Details ---------------------------------------------------------------------------- --- g-permission-allowed --------------------------------------------------- --- g-permission-can-acquire ----------------------------------------------- --- g-permission-can-release ----------------------------------------------- ---------------------------------------------------------------------------- g_permission_acquire () gboolean g_permission_acquire (GPermission *permission, GCancellable *cancellable, Attempts to acquire the permission represented by permission . The precise method by which this happens depends on the permission and the underlying authentication mechanism. A simple example is that a dialog may appear asking the user to enter their password. You should check with g_permission_get_can_acquire() before calling this function. If the permission is acquired then TRUE is returned. Otherwise, FALSE is returned and error is set appropriately. This call is blocking, likely for a very long time (in the case that user interaction is required). See g_permission_acquire_async() for the non-blocking version. permission : a GPermission instance cancellable : a GCancellable, or NULL. error : Returns : TRUE if the permission was successfully acquired ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- g_permission_acquire_async () void g_permission_acquire_async (GPermission *permission, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data); Attempts to acquire the permission represented by permission . g_permission_acquire(). permission : a GPermission instance cancellable : a GCancellable, or NULL. callback : the GAsyncReadyCallback to call when done user_data : the user data to pass to callback ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- g_permission_acquire_finish () gboolean g_permission_acquire_finish (GPermission *permission, GAsyncResult *result, GError **error); Collects the result of attempting to acquire the permission represented by permission . g_permission_acquire(). permission : a GPermission instance result : error : Returns : TRUE if the permission was successfully acquired ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- g_permission_release () gboolean g_permission_release (GPermission *permission, GCancellable *cancellable, Attempts to release the permission represented by permission . The precise method by which this happens depends on the permission and the underlying authentication mechanism. In most cases the permission will be dropped immediately without further action. You should check with g_permission_get_can_release() before calling this function. If the permission is released then TRUE is returned. Otherwise, FALSE is returned and error is set appropriately. This call is blocking, likely for a very long time (in the case that user interaction is required). See g_permission_release_async() for the non-blocking version. permission : a GPermission instance cancellable : a GCancellable, or NULL. error : Returns : TRUE if the permission was successfully released ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- g_permission_release_async () void g_permission_release_async (GPermission *permission, GCancellable *cancellable, GAsyncReadyCallback callback, gpointer user_data); Attempts to release the permission represented by permission . g_permission_release(). permission : a GPermission instance cancellable : a GCancellable, or NULL. callback : the GAsyncReadyCallback to call when done user_data : the user data to pass to callback ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- gboolean GAsyncResult *result, GError **error); Collects the result of attempting to release the permission represented by permission . g_permission_release(). permission : a GPermission instance result : error : Returns : TRUE if the permission was successfully released ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- g_permission_impl_update () void g_permission_impl_update (GPermission *permission, gboolean allowed, properties of the permission. You should never call this function except GObject notify signals are generated, as appropriate. permission : a GPermission instance allowed : the new value for the 'allowed' property can_acquire : the new value for the 'can-acquire' property can_release : the new value for the 'can-release' property ---------------------------------------------------------------------------- --- End of file gio.permission.lisp ----------------------------------------
gio.permission.lisp Version 2.68 and modified to document the Lisp binding to the GIO library . available from < -cffi-gtk/ > . Copyright ( C ) 2021 as published by the Free Software Foundation , either version 3 of the the GNU Lesser General Public License that clarifies the terms for use GNU Lesser General Public License for more details . You should have received a copy of the GNU Lesser General Public License along with this program and the preamble to the Gnu Lesser (in-package :gio) (define-g-object-class "GPermission" g-permission (:superclass g-object :export t :interfaces () :type-initializer "g_permission_get_type") ((allowed g-permission-allowed "allowed" "gboolean" t nil) (can-acquire g-permission-can-acquire "can-acquire" "gboolean" t nil) (can-release g-permission-can-release "can-release" "gboolean" t nil))) #+cl-cffi-gtk-documentation (setf (documentation 'g-permission 'type) "@version{2021-12-23} @begin{short} A @sym{g-permission} object represents the status of the permission of the caller to perform a certain action. @end{short} You can query if the action is currently allowed and if it is possible to acquire the permission so that the action will be allowed in the future. There is also an API to actually acquire the permission and one to release it. As an example, a @sym{g-permission} object might represent the ability for the user to write to a @class{g-settings} object. This @sym{g-permission} object could then be used to decide if it is appropriate to show a \"Click here to unlock\" button in a dialog and to provide the mechanism to invoke when that button is clicked. @see-slot{g-permission-allowed} @see-slot{g-permission-can-acquire} @see-slot{g-permission-can-release} @see-class{g-simple-permission}") #+cl-cffi-gtk-documentation (setf (documentation (atdoc:get-slot-from-name "allowed" 'g-permission) 't) "The @code{allowed} property of type @code{:boolean} (Read) @br{} @em{True} if the caller currently has permission to perform the action that the @sym{g-permission} object represents the permission to perform. @br{} Default value: @em{false}") #+cl-cffi-gtk-documentation (setf (gethash 'g-permission-allowed atdoc:*function-name-alias*) "Accessor" (documentation 'g-permission-allowed 'function) "@version{2021-12-23} @syntax[]{(g-permission-allowed object) => allowed} @argument[object]{a @class{g-permission} object} @argument[allowed]{a boolean whether the caller currently has permission to perform the action} @begin{short} Accessor of the @slot[g-permission]{allowed} slot of the @class{g-permission} class. @end{short} The @sym{g-permission-allowed} slot access function gets the value of the property. This property is @em{true} if the caller currently has permission to perform the action that the @class{g-permission} object represents the permission to perform. @see-class{g-permission}") #+cl-cffi-gtk-documentation (setf (documentation (atdoc:get-slot-from-name "can-acquire" 'g-permission) 't) "The @code{can-acquire} property of type @code{:boolean} (Read) @br{} @em{True} if it is generally possible to acquire the permission by calling the @fun{g-permission-acquire} function. @br{} Default value: @em{false}") #+cl-cffi-gtk-documentation (setf (gethash 'g-permission-can-acquire atdoc:*function-name-alias*) "Accessor" (documentation 'g-permission-can-acquire 'function) "@version{2021-12-23} @syntax[]{(g-permission-can-acquire object) => can-acquire} @argument[object]{a @class{g-permission} object} @argument[can-acquire]{a boolean whether it is generally possible to acquire the permission} @begin{short} Accessor of the @slot[g-permission]{can-acquire} slot of the @class{g-permission} class. @end{short} The @sym{g-permission-can-acquire} slot access function gets the value of the property. This property is @em{true} if it is generally possible to acquire the permission by calling the @fun{g-permission-acquire} function. @see-class{g-permission} @see-function{g-permission-acquire}") #+cl-cffi-gtk-documentation (setf (documentation (atdoc:get-slot-from-name "can-release" 'g-permission) 't) "The @code{can-release} property of type @code{:boolean} (Read) @br{} @em{True} if it is generally possible to release the permission by calling the @fun{g-permission-release} function. @br{} Default value: @em{false}") #+cl-cffi-gtk-documentation (setf (gethash 'g-permission-can-release atdoc:*function-name-alias*) "Accessor" (documentation 'g-permission-can-release 'function) "@version{2021-12-23} @syntax[]{(g-permission-can-release object) => can-release} @argument[object]{a @class{g-permission} object} @argument[can-release]{a boolean whether it is generally possible to release the permission} @begin{short} Accessor of the @slot[g-permission]{can-release} slot of the @class{g-permission} class. @end{short} The @sym{g-permission-can-release} slot access function gets the value of the property. This property is @em{true} if it is generally possible to release the permission by calling the @fun{g-permission-release} function. @see-class{g-permission} @see-function{g-permission-release}") a pointer to a NULL GError , or NULL Since : 2.26 This is the first half of the asynchronous version of Since : 2.26 This is the second half of the asynchronous version of the GAsyncResult given to the GAsyncReadyCallback a pointer to a NULL GError , or NULL Since : 2.26 a pointer to a NULL GError , or NULL Since : 2.26 This is the first half of the asynchronous version of Since : 2.26 g_permission_release_finish ( ) g_permission_release_finish ( GPermission * permission , This is the second half of the asynchronous version of the GAsyncResult given to the GAsyncReadyCallback a pointer to a NULL GError , or NULL Since : 2.26 , This function is called by the GPermission implementation to update the from a GPermission implementation . Since : 2.26
655a43f89a43dd30e8f3ff034d09f2f073404c2ad10847d77427fe69bf4ed353
OCamlPro/ez_api
test_cookie_client.ml
open Test_session_lib open Types open EzAPI.TYPES module Service = Services (* Request implementation that REQUIRES with_crefentials to be always true (to use cookies, that is necessarily)*) module Client = Cohttp_lwt_jsoo.Make_client_async (struct let chunked_response = true let chunk_size = 128 * 1024 let convert_body_string = Js_of_ocaml.Js.to_bytestring let with_credentials = true end) module Base = EzCohttp_base.Make (Client) module Interface = struct open Lwt.Infix let get ?meth ?headers ?msg url f = Lwt.async @@ fun () -> Base.get ?meth ?headers ?msg url >|= f let post ?meth ?content_type ?content ?headers ?msg url f = Lwt.async @@ fun () -> Base.post ?meth ?content_type ?content ?headers ?msg url >|= f end module Request = EzRequest.Make (Interface) module Session = EzSessionClient.Make (SessionArg) (Request) let wrap_res ?error f = function | Ok x -> f x | Error exn -> ( let s = Printexc.to_string exn in match error with | None -> Printf.eprintf "%s" s | Some e -> e 500 (Some s) ) let get0 ?post ?headers ?params ?error ?msg ?(host = BASE api_host) service f = Request.get0 host service ?msg ?post ?headers ?error ?params (wrap_res ?error f) let get1 ?post ?headers ?params ?error ?msg ?(host = BASE api_host) service f arg1 = Request.get1 host service arg1 ?msg ?post ?headers ?error ?params (wrap_res ?error f) let post0 ?headers ?params ?error ?msg ?(host = BASE api_host) service f ~input = Request.post0 host service ?msg ?headers ?error ?params (wrap_res ?error f) ~input let post1 ?headers ?params ?error ?msg ?(host = BASE api_host) service f ~input arg1 = Request.post1 host service arg1 ?msg ?headers ?error ?params (wrap_res ?error f) ~input let string_of_test t = Printf.sprintf "{ name = %S;\n query = %S;\n version = %d;\n}" t.name t.query t.version let waiter, finalizer = Lwt.wait () let waiting = ref false let nrequests = ref 0 let begin_request () = incr nrequests let end_request () = decr nrequests ; if !waiting && !nrequests = 0 then Lwt.wakeup finalizer () let error test n = Printf.eprintf "Error: request %s returned code %d\n%!" test n ; exit 2 let test1 api = begin_request () ; Request.get0 ~msg:"test1" api Service.test1 ~error:(error "test1") ~params:[(Service.param_arg, S "example-of-arg")] (function | Ok r -> Printf.eprintf "Test test1 returned %s\n%!" (string_of_test r) ; end_request () | Error e -> Printf.eprintf "%s\n%!" @@ Printexc.to_string e ; end_request () ) let test1' api = begin_request () ; Request.get0 ~msg:"test1" api Service.test11 ~post:true ~error:(error "test1'") ~params:[(Service.param_arg, S "example-of-arg")] (function | Ok r -> Printf.eprintf "Test test1 returned %s\n%!" (string_of_test r) ; end_request () | Error e -> Printf.eprintf "%s\n%!" @@ Printexc.to_string e ; end_request () ) let test2 api = begin_request () ; Request.get1 ~msg:"test2" api Service.test2 ~error:(error "test2") ~params:[(Service.param_arg, S " -- arg")] "arg-of-test2" (function | Ok r -> Printf.eprintf "Test test2 returned %s\n%!" (string_of_test r) ; end_request () | Error e -> Printf.eprintf "%s\n%!" @@ Printexc.to_string e ; end_request () ) let test2' api = begin_request () ; Request.get1 ~msg:"test2" api Service.test22 ~post:true ~error:(error "test2'") ~params:[(Service.param_arg, S " -- arg")] "arg-of-test2" (function | Ok r -> Printf.eprintf "Test test2 returned %s\n%!" (string_of_test r) ; end_request () | Error e -> Printf.eprintf "%s\n%!" @@ Printexc.to_string e ; end_request () ) let test3 arg api = begin_request () ; Request.post0 ~msg:"test3" api Service.test3 ~error:(error "test3") ~input:arg (function | Ok r -> Printf.eprintf "Test test3 returned %s\n%!" (string_of_test r) ; end_request () | Error e -> Printf.eprintf "%s\n%!" @@ Printexc.to_string e ; end_request () ) let test4 arg api = let open EzSession.TYPES in begin_request () ; Session.connect api (function | Error _ -> Printf.eprintf "Error in connect\n%!" ; exit 2 | Ok (Some _u) -> assert false | Ok None -> Session.login api ~login:user1_login ~password:user1_password (function | Error _ -> Printf.eprintf "Error in login\n%!" ; exit 2 | Ok u -> Printf.eprintf "auth login = %S\n%!" u.auth_login ; assert (u.auth_login = user1_login) ; assert (u.auth_user_info = user1_info) ; Request.post1 ~msg:"test4" api Service.test4 ~error:(error "test4") ~input:arg "arg-of-post1" (function | Ok r -> Printf.eprintf "Test test4 returned %s\n%!" (string_of_test r) ; Session.logout api ~token:u.auth_token (function | Error _ -> Printf.eprintf "Error in logout\n%!" ; exit 2 | Ok bool -> Printf.eprintf "logout OK %b\n%!" bool ; end_request () ) | Error e -> Printf.eprintf "%s\n%!" @@ Printexc.to_string e ; end_request () ) ) ) open Js_of_ocaml let auth_state = ref None let update_button login = Firebug.console##log (if login then "LOGIN" else "LOGOUT") ; let login_button = Option.get @@ Dom_html.getElementById_coerce "submit-connection" Dom_html.CoerceTo.input in login_button##.value := Js.string (if login then "Login" else "Logout") let update_connection_status status = Firebug.console##log (Js.string status) ; let elt = Dom_html.getElementById "connection-status" in elt##.innerHTML := Js.string status let connect () = Firebug.console##log "1" ; Session.connect (EzAPI.BASE api_host) (function | Ok (Some auth) -> Firebug.console##log "2" ; update_connection_status @@ "Connected using cookie; (login = " ^ auth.EzSession.TYPES.auth_login ^ ")" ; update_button false ; auth_state := Some auth | Ok None -> Firebug.console##log "3" ; update_connection_status "Not connected (needs authentication)" | Error _ -> Firebug.console##log "4" ; update_connection_status "Not connected (connect error)" ) let setup_connection () = let login_button = Option.get @@ Dom_html.getElementById_coerce "submit-connection" Dom_html.CoerceTo.input in login_button##.onclick := Dom.handler (fun _ -> ( match !auth_state with | Some auth -> Session.logout (BASE api_host) ~token:auth.EzSession.TYPES.auth_token (function | Ok _ -> update_connection_status "Not connected (needs authentication)" ; auth_state := None ; update_button true | Error _ -> update_connection_status "Not disconnected (logout error)" ) | None -> Session.login (BASE api_host) ~login:user1_login ~password:user1_password (function | Ok auth -> update_connection_status EzSession.TYPES.( "Connected using login and password; (login = " ^ auth.auth_login ^ ")" ) ; auth_state := Some auth ; update_button false | Error _ -> update_connection_status "Not loggined (login error)" ) ) ; Js._false ) let setup_tests () = let error elt _ _ = elt##.style##.color := Js.string "red" in let callback elt _ = elt##.style##.color := Js.string "green" in let test1_elt = Dom_html.getElementById "test1" in let test1'_elt = Dom_html.getElementById "test1'" in let test2_elt = Dom_html.getElementById "test2" in let test2'_elt = Dom_html.getElementById "test2'" in let test3_elt = Dom_html.getElementById "test3" in let test4_elt = Dom_html.getElementById "test4" in let param1 = [(Service.param_arg, S " -- arg")] in let arg1 = "arg-of-test2" in let arg2 = {user= "m"; hash= "1"} in test1_elt##.onclick := Dom.handler (fun _ -> get0 Services.test1 ~params:param1 ~error:(error test1_elt) (callback test1_elt) ; Js._false ) ; test1'_elt##.onclick := Dom.handler (fun _ -> get0 Services.test11 ~params:param1 ~error:(error test1'_elt) (callback test1'_elt) ; Js._false ) ; test2_elt##.onclick := Dom.handler (fun _ -> get1 Services.test2 ~error:(error test2_elt) (callback test2_elt) ~params:param1 arg1 ; Js._false ) ; test2'_elt##.onclick := Dom.handler (fun _ -> get1 Services.test22 ~error:(error test2'_elt) (callback test2'_elt) ~params:param1 arg1 ; Js._false ) ; test3_elt##.onclick := Dom.handler (fun _ -> post0 Service.test3 ~error:(error test3_elt) (callback test3_elt) ~input:arg2 ; Js._false ) ; test4_elt##.onclick := Dom.handler (fun _ -> post1 Service.test4 ~error:(error test4_elt) (callback test4_elt) ~params:param1 ~input:arg2 arg1 ; Js._false ) let () = Request.init () ; connect () ; setup_tests () ; setup_connection ()
null
https://raw.githubusercontent.com/OCamlPro/ez_api/c2a11a6cc250e82738939ce55ae76503a9299198/test/session/test_cookie_client.ml
ocaml
Request implementation that REQUIRES with_crefentials to be always true (to use cookies, that is necessarily)
open Test_session_lib open Types open EzAPI.TYPES module Service = Services module Client = Cohttp_lwt_jsoo.Make_client_async (struct let chunked_response = true let chunk_size = 128 * 1024 let convert_body_string = Js_of_ocaml.Js.to_bytestring let with_credentials = true end) module Base = EzCohttp_base.Make (Client) module Interface = struct open Lwt.Infix let get ?meth ?headers ?msg url f = Lwt.async @@ fun () -> Base.get ?meth ?headers ?msg url >|= f let post ?meth ?content_type ?content ?headers ?msg url f = Lwt.async @@ fun () -> Base.post ?meth ?content_type ?content ?headers ?msg url >|= f end module Request = EzRequest.Make (Interface) module Session = EzSessionClient.Make (SessionArg) (Request) let wrap_res ?error f = function | Ok x -> f x | Error exn -> ( let s = Printexc.to_string exn in match error with | None -> Printf.eprintf "%s" s | Some e -> e 500 (Some s) ) let get0 ?post ?headers ?params ?error ?msg ?(host = BASE api_host) service f = Request.get0 host service ?msg ?post ?headers ?error ?params (wrap_res ?error f) let get1 ?post ?headers ?params ?error ?msg ?(host = BASE api_host) service f arg1 = Request.get1 host service arg1 ?msg ?post ?headers ?error ?params (wrap_res ?error f) let post0 ?headers ?params ?error ?msg ?(host = BASE api_host) service f ~input = Request.post0 host service ?msg ?headers ?error ?params (wrap_res ?error f) ~input let post1 ?headers ?params ?error ?msg ?(host = BASE api_host) service f ~input arg1 = Request.post1 host service arg1 ?msg ?headers ?error ?params (wrap_res ?error f) ~input let string_of_test t = Printf.sprintf "{ name = %S;\n query = %S;\n version = %d;\n}" t.name t.query t.version let waiter, finalizer = Lwt.wait () let waiting = ref false let nrequests = ref 0 let begin_request () = incr nrequests let end_request () = decr nrequests ; if !waiting && !nrequests = 0 then Lwt.wakeup finalizer () let error test n = Printf.eprintf "Error: request %s returned code %d\n%!" test n ; exit 2 let test1 api = begin_request () ; Request.get0 ~msg:"test1" api Service.test1 ~error:(error "test1") ~params:[(Service.param_arg, S "example-of-arg")] (function | Ok r -> Printf.eprintf "Test test1 returned %s\n%!" (string_of_test r) ; end_request () | Error e -> Printf.eprintf "%s\n%!" @@ Printexc.to_string e ; end_request () ) let test1' api = begin_request () ; Request.get0 ~msg:"test1" api Service.test11 ~post:true ~error:(error "test1'") ~params:[(Service.param_arg, S "example-of-arg")] (function | Ok r -> Printf.eprintf "Test test1 returned %s\n%!" (string_of_test r) ; end_request () | Error e -> Printf.eprintf "%s\n%!" @@ Printexc.to_string e ; end_request () ) let test2 api = begin_request () ; Request.get1 ~msg:"test2" api Service.test2 ~error:(error "test2") ~params:[(Service.param_arg, S " -- arg")] "arg-of-test2" (function | Ok r -> Printf.eprintf "Test test2 returned %s\n%!" (string_of_test r) ; end_request () | Error e -> Printf.eprintf "%s\n%!" @@ Printexc.to_string e ; end_request () ) let test2' api = begin_request () ; Request.get1 ~msg:"test2" api Service.test22 ~post:true ~error:(error "test2'") ~params:[(Service.param_arg, S " -- arg")] "arg-of-test2" (function | Ok r -> Printf.eprintf "Test test2 returned %s\n%!" (string_of_test r) ; end_request () | Error e -> Printf.eprintf "%s\n%!" @@ Printexc.to_string e ; end_request () ) let test3 arg api = begin_request () ; Request.post0 ~msg:"test3" api Service.test3 ~error:(error "test3") ~input:arg (function | Ok r -> Printf.eprintf "Test test3 returned %s\n%!" (string_of_test r) ; end_request () | Error e -> Printf.eprintf "%s\n%!" @@ Printexc.to_string e ; end_request () ) let test4 arg api = let open EzSession.TYPES in begin_request () ; Session.connect api (function | Error _ -> Printf.eprintf "Error in connect\n%!" ; exit 2 | Ok (Some _u) -> assert false | Ok None -> Session.login api ~login:user1_login ~password:user1_password (function | Error _ -> Printf.eprintf "Error in login\n%!" ; exit 2 | Ok u -> Printf.eprintf "auth login = %S\n%!" u.auth_login ; assert (u.auth_login = user1_login) ; assert (u.auth_user_info = user1_info) ; Request.post1 ~msg:"test4" api Service.test4 ~error:(error "test4") ~input:arg "arg-of-post1" (function | Ok r -> Printf.eprintf "Test test4 returned %s\n%!" (string_of_test r) ; Session.logout api ~token:u.auth_token (function | Error _ -> Printf.eprintf "Error in logout\n%!" ; exit 2 | Ok bool -> Printf.eprintf "logout OK %b\n%!" bool ; end_request () ) | Error e -> Printf.eprintf "%s\n%!" @@ Printexc.to_string e ; end_request () ) ) ) open Js_of_ocaml let auth_state = ref None let update_button login = Firebug.console##log (if login then "LOGIN" else "LOGOUT") ; let login_button = Option.get @@ Dom_html.getElementById_coerce "submit-connection" Dom_html.CoerceTo.input in login_button##.value := Js.string (if login then "Login" else "Logout") let update_connection_status status = Firebug.console##log (Js.string status) ; let elt = Dom_html.getElementById "connection-status" in elt##.innerHTML := Js.string status let connect () = Firebug.console##log "1" ; Session.connect (EzAPI.BASE api_host) (function | Ok (Some auth) -> Firebug.console##log "2" ; update_connection_status @@ "Connected using cookie; (login = " ^ auth.EzSession.TYPES.auth_login ^ ")" ; update_button false ; auth_state := Some auth | Ok None -> Firebug.console##log "3" ; update_connection_status "Not connected (needs authentication)" | Error _ -> Firebug.console##log "4" ; update_connection_status "Not connected (connect error)" ) let setup_connection () = let login_button = Option.get @@ Dom_html.getElementById_coerce "submit-connection" Dom_html.CoerceTo.input in login_button##.onclick := Dom.handler (fun _ -> ( match !auth_state with | Some auth -> Session.logout (BASE api_host) ~token:auth.EzSession.TYPES.auth_token (function | Ok _ -> update_connection_status "Not connected (needs authentication)" ; auth_state := None ; update_button true | Error _ -> update_connection_status "Not disconnected (logout error)" ) | None -> Session.login (BASE api_host) ~login:user1_login ~password:user1_password (function | Ok auth -> update_connection_status EzSession.TYPES.( "Connected using login and password; (login = " ^ auth.auth_login ^ ")" ) ; auth_state := Some auth ; update_button false | Error _ -> update_connection_status "Not loggined (login error)" ) ) ; Js._false ) let setup_tests () = let error elt _ _ = elt##.style##.color := Js.string "red" in let callback elt _ = elt##.style##.color := Js.string "green" in let test1_elt = Dom_html.getElementById "test1" in let test1'_elt = Dom_html.getElementById "test1'" in let test2_elt = Dom_html.getElementById "test2" in let test2'_elt = Dom_html.getElementById "test2'" in let test3_elt = Dom_html.getElementById "test3" in let test4_elt = Dom_html.getElementById "test4" in let param1 = [(Service.param_arg, S " -- arg")] in let arg1 = "arg-of-test2" in let arg2 = {user= "m"; hash= "1"} in test1_elt##.onclick := Dom.handler (fun _ -> get0 Services.test1 ~params:param1 ~error:(error test1_elt) (callback test1_elt) ; Js._false ) ; test1'_elt##.onclick := Dom.handler (fun _ -> get0 Services.test11 ~params:param1 ~error:(error test1'_elt) (callback test1'_elt) ; Js._false ) ; test2_elt##.onclick := Dom.handler (fun _ -> get1 Services.test2 ~error:(error test2_elt) (callback test2_elt) ~params:param1 arg1 ; Js._false ) ; test2'_elt##.onclick := Dom.handler (fun _ -> get1 Services.test22 ~error:(error test2'_elt) (callback test2'_elt) ~params:param1 arg1 ; Js._false ) ; test3_elt##.onclick := Dom.handler (fun _ -> post0 Service.test3 ~error:(error test3_elt) (callback test3_elt) ~input:arg2 ; Js._false ) ; test4_elt##.onclick := Dom.handler (fun _ -> post1 Service.test4 ~error:(error test4_elt) (callback test4_elt) ~params:param1 ~input:arg2 arg1 ; Js._false ) let () = Request.init () ; connect () ; setup_tests () ; setup_connection ()
70ac18414fa6da937e3856c69886cfffc44f0e0c35fb83e1e35c42ab92fccd6e
fizruk/rzk
TypeError.hs
{-# LANGUAGE DeriveFunctor #-} # LANGUAGE LambdaCase # {-# LANGUAGE OverloadedStrings #-} module Rzk.Free.TypeCheck.TypeError where import Bound import Data.String import Data.Text.Prettyprint.Doc import Rzk.Free.Bound.Name import Rzk.Free.Pretty import Rzk.Free.Syntax.Term data TypeError b a = TypeErrorUnexpected (TypedTerm b a) (TypedTerm b a) | TypeErrorCannotInferLambda (Term b a) | TypeErrorNotAFunction (TypedTerm b a) | TypeErrorScope (TypeError b (Var (Name b ()) a)) deriving (Functor) instance (IsString a, Pretty a, Pretty b) => Show (TypeError b a) where show = show . pretty instance (IsString a, Pretty a, Pretty b) => Pretty (TypeError b a) where pretty = ppTypeError defaultFreshVars ppTypeErrorScope :: (IsString a, Pretty a, Pretty b) => [a] -> TypeError b (Var (Name b ()) a) -> Doc ann ppTypeErrorScope [] _err = error "not enough fresh variables" ppTypeErrorScope (z:zs) err = ppTypeError zs (prettyVar <$> err) where prettyVar (B _) = z prettyVar (F x) = x ppTypeError :: (IsString a, Pretty a, Pretty b) => [a] -> TypeError b a -> Doc ann ppTypeError vars = \case TypeErrorScope err -> ppTypeErrorScope vars err TypeErrorUnexpected actual expected -> vsep [ "expected" , indent 2 (ppTerm vars (untyped expected)) , "but found" , indent 2 (ppTerm vars (untyped actual)) ] TypeErrorCannotInferLambda term -> vsep [ "cannot infer the type of lambda abstraction" , indent 2 (ppTerm vars term) ] TypeErrorNotAFunction _ -> undefined -- instance (Pretty b, Pretty a, IsString b) => Pretty (TypeError b a) where pretty = ppTypeError -- ppTypeError : : ( Pretty a , Pretty b ) = > TypeError b a - > Doc ann -- ppTypeError = \case TypeErrorInfinite x t - > Text.intercalate " \n " -- [ "Can't construct infinite type " <> pretty x <> " ~ " <> ppTerm t ] TypeErrorUnexpected term inferredFull expectedFull inferred expected - > Text.intercalate " \n " -- [ "Expected type" -- , " " <> ppTerm expected -- , "but inferred" -- , " " <> ppTerm inferred -- , "when trying to unify expected type" -- , " " <> ppTerm expectedFull -- , "with inferred type" -- , " " <> ppTerm inferredFull -- , "for the term" -- , " " <> ppTerm term -- ] -- TypeErrorUndefinedVariable x -> Text.intercalate "\n" -- [ "Undefined variable:" -- , " " <> pretty x -- ] -- TypeErrorOther msg -> "Error occurred in the typechecker: " <> msg -- TypeErrorCannotInferLambda t -> Text.intercalate "\n" -- [ "Error while attempting to infer the type for a lambda abstraction" -- , " " <> ppTerm t -- ] t - > Text.intercalate " \n " -- [ "Error while attempting to infer the type for a dependent tuple" -- , " " <> ppTerm t -- ] -- TypeErrorNotAFunction f t e -> Text.intercalate "\n" -- [ "Expected a function type but got" -- , " " <> ppTerm t -- , "for the term" -- , " " <> ppTerm f -- , "in expression" -- , " " <> ppTerm (App f e) -- ] TypeErrorNotAPair f t e - > Text.intercalate " \n " -- [ "Expected a dependent pair (sum) type or a cube product but got" -- , " " <> ppTerm t -- , "for the term" -- , " " <> ppTerm f -- , "in expression" -- , " " <> ppTerm e -- ] TypeErrorExpectedFunctionType term expected - > Text.intercalate " \n " -- [ "Expected type is not a function type" -- , " " <> ppTerm expected -- , "but the term is a lambda abstraction" -- , " " <> ppTerm term -- ] -- TypeErrorInvalidTypeFamily -> "Expected a type family, but got something else" -- FIXME -- TypeErrorTopeContextNotSatisfied term phi topes -> Text.intercalate "\n" -- [ "Cannot satisfy the tope constraint:" -- , " " <> ppTerm phi -- , "in local tope context" , Text.intercalate " \n " ( map ( ( " " < > ) . ppTerm ) ) -- , "when typechecking term" -- , " " <> ppTerm term -- ] -- --
null
https://raw.githubusercontent.com/fizruk/rzk/502eb7655655d8fe1be8f4fa2561464141b01e2e/rzk/src/Rzk/Free/TypeCheck/TypeError.hs
haskell
# LANGUAGE DeriveFunctor # # LANGUAGE OverloadedStrings # instance (Pretty b, Pretty a, IsString b) => Pretty (TypeError b a) where ppTypeError = \case [ "Can't construct infinite type " <> pretty x <> " ~ " <> ppTerm t ] [ "Expected type" , " " <> ppTerm expected , "but inferred" , " " <> ppTerm inferred , "when trying to unify expected type" , " " <> ppTerm expectedFull , "with inferred type" , " " <> ppTerm inferredFull , "for the term" , " " <> ppTerm term ] TypeErrorUndefinedVariable x -> Text.intercalate "\n" [ "Undefined variable:" , " " <> pretty x ] TypeErrorOther msg -> "Error occurred in the typechecker: " <> msg TypeErrorCannotInferLambda t -> Text.intercalate "\n" [ "Error while attempting to infer the type for a lambda abstraction" , " " <> ppTerm t ] [ "Error while attempting to infer the type for a dependent tuple" , " " <> ppTerm t ] TypeErrorNotAFunction f t e -> Text.intercalate "\n" [ "Expected a function type but got" , " " <> ppTerm t , "for the term" , " " <> ppTerm f , "in expression" , " " <> ppTerm (App f e) ] [ "Expected a dependent pair (sum) type or a cube product but got" , " " <> ppTerm t , "for the term" , " " <> ppTerm f , "in expression" , " " <> ppTerm e ] [ "Expected type is not a function type" , " " <> ppTerm expected , "but the term is a lambda abstraction" , " " <> ppTerm term ] TypeErrorInvalidTypeFamily -> "Expected a type family, but got something else" -- FIXME TypeErrorTopeContextNotSatisfied term phi topes -> Text.intercalate "\n" [ "Cannot satisfy the tope constraint:" , " " <> ppTerm phi , "in local tope context" , "when typechecking term" , " " <> ppTerm term ]
# LANGUAGE LambdaCase # module Rzk.Free.TypeCheck.TypeError where import Bound import Data.String import Data.Text.Prettyprint.Doc import Rzk.Free.Bound.Name import Rzk.Free.Pretty import Rzk.Free.Syntax.Term data TypeError b a = TypeErrorUnexpected (TypedTerm b a) (TypedTerm b a) | TypeErrorCannotInferLambda (Term b a) | TypeErrorNotAFunction (TypedTerm b a) | TypeErrorScope (TypeError b (Var (Name b ()) a)) deriving (Functor) instance (IsString a, Pretty a, Pretty b) => Show (TypeError b a) where show = show . pretty instance (IsString a, Pretty a, Pretty b) => Pretty (TypeError b a) where pretty = ppTypeError defaultFreshVars ppTypeErrorScope :: (IsString a, Pretty a, Pretty b) => [a] -> TypeError b (Var (Name b ()) a) -> Doc ann ppTypeErrorScope [] _err = error "not enough fresh variables" ppTypeErrorScope (z:zs) err = ppTypeError zs (prettyVar <$> err) where prettyVar (B _) = z prettyVar (F x) = x ppTypeError :: (IsString a, Pretty a, Pretty b) => [a] -> TypeError b a -> Doc ann ppTypeError vars = \case TypeErrorScope err -> ppTypeErrorScope vars err TypeErrorUnexpected actual expected -> vsep [ "expected" , indent 2 (ppTerm vars (untyped expected)) , "but found" , indent 2 (ppTerm vars (untyped actual)) ] TypeErrorCannotInferLambda term -> vsep [ "cannot infer the type of lambda abstraction" , indent 2 (ppTerm vars term) ] TypeErrorNotAFunction _ -> undefined pretty = ppTypeError ppTypeError : : ( Pretty a , Pretty b ) = > TypeError b a - > Doc ann TypeErrorInfinite x t - > Text.intercalate " \n " TypeErrorUnexpected term inferredFull expectedFull inferred expected - > Text.intercalate " \n " t - > Text.intercalate " \n " TypeErrorNotAPair f t e - > Text.intercalate " \n " TypeErrorExpectedFunctionType term expected - > Text.intercalate " \n " , Text.intercalate " \n " ( map ( ( " " < > ) . ppTerm ) )
485ffe16e007d99029b9e3a378259a1bd34aae827061bf949e3b3d61e55471fb
jbclements/molis-hai
extract-crime-and-punishment-text.rkt
#lang racket (require (planet neil/html-parsing) racket/runtime-path sxml/sxpath rackunit) (define-runtime-path here ".") (define cp-sxml (call-with-input-file (build-path here "crime-and-punishment.html") (lambda (port) (html->xexp (reencode-input-port port "windows-1251"))))) ;; truncate after n elements (calling to-dotted on each one), ;; inserting '... , otherwise leave alone (define (my-trunc cap n l) (cond [(empty? l) empty] [(= n 0) (list (~a (length l)" more..."))] [else (cons (to-dotted cap (first l)) (my-trunc cap (sub1 n) (rest l)))])) ;; remove elements after the nth of each list (define (to-dotted cap sexp) (cond [(pair? sexp) (my-trunc cap cap sexp)] [else sexp])) (define paragraphs ((sxpath '(html body div dd)) cp-sxml)) ;; flatten a 'dd'. Return a list of hopefully-strings (define (flatten-dd s) (match s [(cons 'dd elts) (apply append (map flatten-element elts))])) ;; problematic paragraphs contain these search strings: наказание за слышу часу . ;; flatten certain HTML forms into a list of strings OR the symbol ;; 'this-is-the-end (define (flatten-element elt) (match elt ["THE END\n" 'this-is-the-end] [(list '& 'nbsp) (list " ")] ;; sneaky attribute removal: [(cons sym (cons (cons '@ attrs) elements)) (flatten-element (cons sym elements))] [(cons 'b elements) (flatten-many elements)] [(cons 'div elements) (flatten-many elements)] [(cons 'p elements) (flatten-many elements)] [(cons 'i elements) (flatten-many elements)] [(cons 'u elements) (flatten-many elements)] [(cons 'font elements) (flatten-many elements)] ;; superscript, just eat it: [(list 'sup "1") (list "")] [(list 'sup "2") (list "")] [(list 'sup (? string? s)) (list "")] [(list 'br) (list "")] [(? string? s) (list s)] [other (error 'flatten-element "unknown element: ~e" other)])) flatten a list of elements into one list (define (flatten-many elts) (apply append (map flatten-element elts))) (check-equal? (flatten-element '(u (@ (foo "oheut")) "rubber")) '("rubber")) (list-ref paragraphs 3977) (define flattened-pars (map flatten-dd (take paragraphs 3978 (- (length paragraphs) 10)))) split-at (define flattened (apply append (map flatten-dd (take paragraphs 3978 (- (length paragraphs) 301 10 ) ) ) ) ) (for ([s (in-list flattened)]) (when (not (string? s)) (error 'all-flattened "not yet a string: ~e\n" s))) (display-to-file (apply string-append flattened) "/tmp/crime-and-punishment.txt" #:exists 'truncate) ( to - dotted 15 paragraphs )
null
https://raw.githubusercontent.com/jbclements/molis-hai/6a335ec73c144f9d8ac538752ca8e6fd0b3b3cce/molis-hai/experimental/extract-crime-and-punishment-text.rkt
racket
truncate after n elements (calling to-dotted on each one), inserting '... , otherwise leave alone remove elements after the nth of each list flatten a 'dd'. Return a list of hopefully-strings problematic paragraphs contain these search strings: flatten certain HTML forms into a list of strings OR the symbol 'this-is-the-end sneaky attribute removal: superscript, just eat it:
#lang racket (require (planet neil/html-parsing) racket/runtime-path sxml/sxpath rackunit) (define-runtime-path here ".") (define cp-sxml (call-with-input-file (build-path here "crime-and-punishment.html") (lambda (port) (html->xexp (reencode-input-port port "windows-1251"))))) (define (my-trunc cap n l) (cond [(empty? l) empty] [(= n 0) (list (~a (length l)" more..."))] [else (cons (to-dotted cap (first l)) (my-trunc cap (sub1 n) (rest l)))])) (define (to-dotted cap sexp) (cond [(pair? sexp) (my-trunc cap cap sexp)] [else sexp])) (define paragraphs ((sxpath '(html body div dd)) cp-sxml)) (define (flatten-dd s) (match s [(cons 'dd elts) (apply append (map flatten-element elts))])) наказание за слышу часу . (define (flatten-element elt) (match elt ["THE END\n" 'this-is-the-end] [(list '& 'nbsp) (list " ")] [(cons sym (cons (cons '@ attrs) elements)) (flatten-element (cons sym elements))] [(cons 'b elements) (flatten-many elements)] [(cons 'div elements) (flatten-many elements)] [(cons 'p elements) (flatten-many elements)] [(cons 'i elements) (flatten-many elements)] [(cons 'u elements) (flatten-many elements)] [(cons 'font elements) (flatten-many elements)] [(list 'sup "1") (list "")] [(list 'sup "2") (list "")] [(list 'sup (? string? s)) (list "")] [(list 'br) (list "")] [(? string? s) (list s)] [other (error 'flatten-element "unknown element: ~e" other)])) flatten a list of elements into one list (define (flatten-many elts) (apply append (map flatten-element elts))) (check-equal? (flatten-element '(u (@ (foo "oheut")) "rubber")) '("rubber")) (list-ref paragraphs 3977) (define flattened-pars (map flatten-dd (take paragraphs 3978 (- (length paragraphs) 10)))) split-at (define flattened (apply append (map flatten-dd (take paragraphs 3978 (- (length paragraphs) 301 10 ) ) ) ) ) (for ([s (in-list flattened)]) (when (not (string? s)) (error 'all-flattened "not yet a string: ~e\n" s))) (display-to-file (apply string-append flattened) "/tmp/crime-and-punishment.txt" #:exists 'truncate) ( to - dotted 15 paragraphs )
a68a08d6b4c4bdf8e36b505ede603cdd7266f0c3acc5f6e34b704bed5df26818
solita/solita-rooms
chrome_test.clj
(ns rooms.chrome-test (:require [clojure.test :refer [deftest]] [clj-chrome-devtools.cljs.test :refer [build-and-test]])) (deftest chrome-test (build-and-test "test" '[rooms.domain.room-test]))
null
https://raw.githubusercontent.com/solita/solita-rooms/39eec90790a3fba36dbbccb3b3e86394a987a840/frontend/test/clj/rooms/chrome_test.clj
clojure
(ns rooms.chrome-test (:require [clojure.test :refer [deftest]] [clj-chrome-devtools.cljs.test :refer [build-and-test]])) (deftest chrome-test (build-and-test "test" '[rooms.domain.room-test]))
cb19b1b36b0157cc3aadddf8579ac4dc8790fe30657a48de34efb81ecc972748
e-bigmoon/haskell-blog
Sharing_the_Manager_concurrently.hs
#!/usr/bin/env stack -- stack script --resolver lts-17.3 {-# LANGUAGE OverloadedStrings #-} import Control.Concurrent.Async (Concurrently (..)) import Data.Foldable (sequenceA_) import Network.HTTP.Client import Network.HTTP.Client.TLS import qualified Data.Conduit.List as CL import Text.HTML.DOM import Data.Conduit ((.|), runConduit, runConduitRes) import Conduit (runResourceT) import qualified Data.Conduit.Binary as CB import Network.HTTP.Client.Conduit (bodyReaderSource) main :: IO () main = do manager <- newManager tlsManagerSettings runConcurrently $ sequenceA_ $ map Concurrently $ map ($ manager) [doSomething1, doSomething2] doSomething1 :: Manager -> IO () doSomething1 manager = do let request = "" response <- httpLbs request manager withResponse request manager $ \response -> do valueEvent <- runConduit $ bodyReaderSource (responseBody response) .| eventConduit .| CL.consume print valueEvent doSomething2 :: Manager -> IO () doSomething2 manager = do let request = "" response <- httpLbs request manager withResponse request manager $ \response -> do valueDoc <- runConduit $ bodyReaderSource (responseBody response) .| sinkDoc print valueDoc
null
https://raw.githubusercontent.com/e-bigmoon/haskell-blog/5c9e7c25f31ea6856c5d333e8e991dbceab21c56/sample-code/yesod/appendix/ap4/Sharing_the_Manager_concurrently.hs
haskell
stack script --resolver lts-17.3 # LANGUAGE OverloadedStrings #
#!/usr/bin/env stack import Control.Concurrent.Async (Concurrently (..)) import Data.Foldable (sequenceA_) import Network.HTTP.Client import Network.HTTP.Client.TLS import qualified Data.Conduit.List as CL import Text.HTML.DOM import Data.Conduit ((.|), runConduit, runConduitRes) import Conduit (runResourceT) import qualified Data.Conduit.Binary as CB import Network.HTTP.Client.Conduit (bodyReaderSource) main :: IO () main = do manager <- newManager tlsManagerSettings runConcurrently $ sequenceA_ $ map Concurrently $ map ($ manager) [doSomething1, doSomething2] doSomething1 :: Manager -> IO () doSomething1 manager = do let request = "" response <- httpLbs request manager withResponse request manager $ \response -> do valueEvent <- runConduit $ bodyReaderSource (responseBody response) .| eventConduit .| CL.consume print valueEvent doSomething2 :: Manager -> IO () doSomething2 manager = do let request = "" response <- httpLbs request manager withResponse request manager $ \response -> do valueDoc <- runConduit $ bodyReaderSource (responseBody response) .| sinkDoc print valueDoc
75e561202be3e1225ba45dee8c5d3d557678315f800a33af88bdc533c71269df
lem-project/lem
socket.lisp
(defpackage :lem-socket-utils (:use :cl) (:import-from :usocket) (:export :port-available-p :random-available-port) #+sbcl (:lock t)) (in-package :lem-socket-utils) (defconstant +private-port-min+ 49152) (defconstant +private-port-max+ 65535) (defun port-available-p (port) (let (socket) (unwind-protect (handler-case (progn (setq socket (usocket:socket-listen "127.0.0.1" port :reuse-address nil)) port) (usocket:address-in-use-error () nil) (usocket:socket-error (e) (warn "USOCKET:SOCKET-ERROR: ~A" e) nil) #+sbcl (sb-bsd-sockets:socket-error (e) (warn "SB-BSD-SOCKETS:SOCKET-ERROR: ~A" e) nil)) (when socket (usocket:socket-close socket) port)))) (defun random-available-port (&rest deny-ports) (loop :for port := (random-port) :when (and (port-available-p port) (not (find port deny-ports :test #'equal))) :return port)) (defun random-port () (random-range +private-port-min+ +private-port-max+)) (defun random-range (min max &optional (state *random-state*)) (+ min (random (1+ (- max min)) state)))
null
https://raw.githubusercontent.com/lem-project/lem/00fca190625bab602e9dd85bc23b9a2c6fb2e541/lib/socket-utils/socket.lisp
lisp
(defpackage :lem-socket-utils (:use :cl) (:import-from :usocket) (:export :port-available-p :random-available-port) #+sbcl (:lock t)) (in-package :lem-socket-utils) (defconstant +private-port-min+ 49152) (defconstant +private-port-max+ 65535) (defun port-available-p (port) (let (socket) (unwind-protect (handler-case (progn (setq socket (usocket:socket-listen "127.0.0.1" port :reuse-address nil)) port) (usocket:address-in-use-error () nil) (usocket:socket-error (e) (warn "USOCKET:SOCKET-ERROR: ~A" e) nil) #+sbcl (sb-bsd-sockets:socket-error (e) (warn "SB-BSD-SOCKETS:SOCKET-ERROR: ~A" e) nil)) (when socket (usocket:socket-close socket) port)))) (defun random-available-port (&rest deny-ports) (loop :for port := (random-port) :when (and (port-available-p port) (not (find port deny-ports :test #'equal))) :return port)) (defun random-port () (random-range +private-port-min+ +private-port-max+)) (defun random-range (min max &optional (state *random-state*)) (+ min (random (1+ (- max min)) state)))