_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
20f9d13fd981eeb1d620b961dd51e714c16604ea3229768ccb842a669d2e3a5f
koto-bank/lbge
primitives.lisp
(in-package :lbge.render) (defun assemble-vertex-array (attributes) (let ((attr-len (length (car attributes)))) (assert (loop :for a :in attributes :always (= (length a) attr-len)) nil "All attribute lists must have equal lenght") (let ((result (make-array (* (length attributes) attr-len))) (i 0)) (apply (ax:curry #'mapcar (lambda (&rest vals) (mapcar (lambda (value) (setf (aref result i) value) (incf i)) vals))) attributes) result))) (defun unzip-attribute-list (attribute-list) (loop :for (a v) :on attribute-list :by #'cddr :collect a :into attributes :collect v :into values :finally (return (values attributes values)))) (defun assemble-render-object (batch vertices indices material transform additional-attributes) (multiple-value-bind (attributes values) (unzip-attribute-list additional-attributes) (with-slots ((verts vertices) (inds indices)) batch (setf verts (assemble-vertex-array (nconc (list vertices) values)) inds indices)) (make-render-object (list batch) (make-semantics (nconc (list '(:vertex :float 4)) attributes)) material transform))) (defun make-rect (&key w h (transform (m:make-transform)) material additional-attributes (gen-texcoords t)) "Create a rectangle primitive. If additional-attributes list is provided, it should have the folloving form, e.g.: ((:color :float 3) ((1.0 0.0 0.0) (0.0 1.0 0.0) (0.0 0.0 1.0) (0.0 1.0 1.0)) (:texcoord :float 2) ((1.0 0.0) (0.0 0.0) (0.0 1.0) (1.0 1.0)))" (assert (> w 0.0f0) nil "Width must be greater than zero, current value: ~S" w) (assert (> h 0.0f0) nil "Height must be greater than zero, current value: ~S" h) (let* ((b (make-instance 'batch)) (w/2 (/ w 2.0f0)) (h/2 (/ h 2.0f0)) (-w/2 (- w/2)) (-h/2 (- h/2)) (verts (list (m:make-float4 -w/2 h/2 0.0f0 1.0f0) (m:make-float4 w/2 h/2 0.0f0 1.0f0) (m:make-float4 w/2 -h/2 0.0f0 1.0f0) (m:make-float4 -w/2 -h/2 0.0f0 1.0f0))) (texcoords (list '(:texcoord :float 2) (list (m:make-float2 0.0 1.0) (m:make-float2 1.0 1.0) (m:make-float2 1.0 0.0) (m:make-float2 0.0 0.0))))) (assemble-render-object b verts (vector 0 2 1 0 3 2) material transform (append (when gen-texcoords texcoords) additional-attributes)))) (defun make-triangle (&key size (transform (m:make-transform)) material additional-attributes) (assert (> size 0.0f0) nil "Triangle size must be positive, current value: ~S" size) (let* ((b (make-instance 'batch)) (size/2 (/ size 2.0f0)) (-size/2 (- size/2)) (r-circ (/ size (sqrt 3.0f0))) (-r-insc (- (/ r-circ 2))) (verts (list (m:make-float4 -size/2 -r-insc 0.0f0 1.0f0) (m:make-float4 0.0f0 r-circ 0.0f0 1.0f0) (m:make-float4 size/2 -r-insc 0.0f0 1.0f0)))) (assemble-render-object b verts (vector 0 2 1) material transform additional-attributes))) (defun make-circle (&key radius (vert-num 32) (transform (m:make-transform)) material additional-attributes) (make-ellipse :r-x radius :r-y radius :vert-num vert-num :transform transform :material material :additional-attributes additional-attributes)) (defun make-ellipse (&key r-x r-y (vert-num 32) (transform (m:make-transform)) material additional-attributes) (assert (> vert-num 2) nil "Cant make an ellipse with ~A vertices" vert-num) (let ((step (/ (* 2 pi) vert-num)) (inds (make-array (list (* 3 vert-num)))) (verts (make-array (list (+ 1 vert-num)))) (base-ind 0)) (dotimes (i vert-num) (let ((angle (* i step))) (setf (aref verts i) (m:make-float4 (* r-x (cos angle)) (* r-y (sin angle)) 0.0f0 1.0f0) (aref inds base-ind) i (aref inds (+ base-ind 1)) (+ i 1) (aref inds (+ base-ind 2)) vert-num base-ind (+ 3 base-ind)))) (setf (aref verts vert-num) (m:make-float4 0.0f0 0.0f0 0.0f0 1.0f0) (aref inds (- (* 3 vert-num) 2)) (aref inds 0)) (log:debug "Ellipse vertices: ~A" verts) (log:debug "Ellipse indices: ~A" inds) (make-render-object (list (make-instance 'batch :indices inds :vertices verts)) (make-semantics ((:vertex :float 4))) material transform))) (defun make-ring (&key in-r out-r (vert-num 32) (transform (m:make-transform)) material additional-attributes) (assert (> vert-num 2) nil "Cant make an ring with ~A vertices" vert-num) (let ((step (/ (* 2 pi) vert-num)) (inds (make-array (list (* 6 vert-num)))) (verts (make-array (list (* 2 vert-num)))) (base-ind 0)) (dotimes (i vert-num) (let ((angle (* i step)) (base-vert (* 2 i))) (setf (aref verts base-vert) (m:make-float4 (* out-r (cos angle)) (* out-r (sin angle)) 0.0f0 1.0f0) (aref verts (1+ base-vert)) (m:make-float4 (* in-r (cos angle)) (* in-r (sin angle)) 0.0f0 1.0f0) (aref inds base-ind) base-vert (aref inds (+ base-ind 1)) (+ base-vert 3) (aref inds (+ base-ind 2)) (+ base-vert 1) (aref inds (+ base-ind 3)) base-vert (aref inds (+ base-ind 4)) (+ base-vert 2) (aref inds (+ base-ind 5)) (+ base-vert 3) base-ind (+ 6 base-ind)))) (let ((last-index (1- (* 6 vert-num)))) (setf (aref inds last-index) 1) (setf (aref inds (- last-index 1)) 0) (setf (aref inds (- last-index 4)) 1)) (make-render-object (list (make-instance 'batch :indices inds :vertices verts)) (make-semantics ((:vertex :float 4))) material transform)))
null
https://raw.githubusercontent.com/koto-bank/lbge/6be4b3212ea87288b1ee2a655e9a1bb30a74dd27/src/render/primitives.lisp
lisp
(in-package :lbge.render) (defun assemble-vertex-array (attributes) (let ((attr-len (length (car attributes)))) (assert (loop :for a :in attributes :always (= (length a) attr-len)) nil "All attribute lists must have equal lenght") (let ((result (make-array (* (length attributes) attr-len))) (i 0)) (apply (ax:curry #'mapcar (lambda (&rest vals) (mapcar (lambda (value) (setf (aref result i) value) (incf i)) vals))) attributes) result))) (defun unzip-attribute-list (attribute-list) (loop :for (a v) :on attribute-list :by #'cddr :collect a :into attributes :collect v :into values :finally (return (values attributes values)))) (defun assemble-render-object (batch vertices indices material transform additional-attributes) (multiple-value-bind (attributes values) (unzip-attribute-list additional-attributes) (with-slots ((verts vertices) (inds indices)) batch (setf verts (assemble-vertex-array (nconc (list vertices) values)) inds indices)) (make-render-object (list batch) (make-semantics (nconc (list '(:vertex :float 4)) attributes)) material transform))) (defun make-rect (&key w h (transform (m:make-transform)) material additional-attributes (gen-texcoords t)) "Create a rectangle primitive. If additional-attributes list is provided, it should have the folloving form, e.g.: ((:color :float 3) ((1.0 0.0 0.0) (0.0 1.0 0.0) (0.0 0.0 1.0) (0.0 1.0 1.0)) (:texcoord :float 2) ((1.0 0.0) (0.0 0.0) (0.0 1.0) (1.0 1.0)))" (assert (> w 0.0f0) nil "Width must be greater than zero, current value: ~S" w) (assert (> h 0.0f0) nil "Height must be greater than zero, current value: ~S" h) (let* ((b (make-instance 'batch)) (w/2 (/ w 2.0f0)) (h/2 (/ h 2.0f0)) (-w/2 (- w/2)) (-h/2 (- h/2)) (verts (list (m:make-float4 -w/2 h/2 0.0f0 1.0f0) (m:make-float4 w/2 h/2 0.0f0 1.0f0) (m:make-float4 w/2 -h/2 0.0f0 1.0f0) (m:make-float4 -w/2 -h/2 0.0f0 1.0f0))) (texcoords (list '(:texcoord :float 2) (list (m:make-float2 0.0 1.0) (m:make-float2 1.0 1.0) (m:make-float2 1.0 0.0) (m:make-float2 0.0 0.0))))) (assemble-render-object b verts (vector 0 2 1 0 3 2) material transform (append (when gen-texcoords texcoords) additional-attributes)))) (defun make-triangle (&key size (transform (m:make-transform)) material additional-attributes) (assert (> size 0.0f0) nil "Triangle size must be positive, current value: ~S" size) (let* ((b (make-instance 'batch)) (size/2 (/ size 2.0f0)) (-size/2 (- size/2)) (r-circ (/ size (sqrt 3.0f0))) (-r-insc (- (/ r-circ 2))) (verts (list (m:make-float4 -size/2 -r-insc 0.0f0 1.0f0) (m:make-float4 0.0f0 r-circ 0.0f0 1.0f0) (m:make-float4 size/2 -r-insc 0.0f0 1.0f0)))) (assemble-render-object b verts (vector 0 2 1) material transform additional-attributes))) (defun make-circle (&key radius (vert-num 32) (transform (m:make-transform)) material additional-attributes) (make-ellipse :r-x radius :r-y radius :vert-num vert-num :transform transform :material material :additional-attributes additional-attributes)) (defun make-ellipse (&key r-x r-y (vert-num 32) (transform (m:make-transform)) material additional-attributes) (assert (> vert-num 2) nil "Cant make an ellipse with ~A vertices" vert-num) (let ((step (/ (* 2 pi) vert-num)) (inds (make-array (list (* 3 vert-num)))) (verts (make-array (list (+ 1 vert-num)))) (base-ind 0)) (dotimes (i vert-num) (let ((angle (* i step))) (setf (aref verts i) (m:make-float4 (* r-x (cos angle)) (* r-y (sin angle)) 0.0f0 1.0f0) (aref inds base-ind) i (aref inds (+ base-ind 1)) (+ i 1) (aref inds (+ base-ind 2)) vert-num base-ind (+ 3 base-ind)))) (setf (aref verts vert-num) (m:make-float4 0.0f0 0.0f0 0.0f0 1.0f0) (aref inds (- (* 3 vert-num) 2)) (aref inds 0)) (log:debug "Ellipse vertices: ~A" verts) (log:debug "Ellipse indices: ~A" inds) (make-render-object (list (make-instance 'batch :indices inds :vertices verts)) (make-semantics ((:vertex :float 4))) material transform))) (defun make-ring (&key in-r out-r (vert-num 32) (transform (m:make-transform)) material additional-attributes) (assert (> vert-num 2) nil "Cant make an ring with ~A vertices" vert-num) (let ((step (/ (* 2 pi) vert-num)) (inds (make-array (list (* 6 vert-num)))) (verts (make-array (list (* 2 vert-num)))) (base-ind 0)) (dotimes (i vert-num) (let ((angle (* i step)) (base-vert (* 2 i))) (setf (aref verts base-vert) (m:make-float4 (* out-r (cos angle)) (* out-r (sin angle)) 0.0f0 1.0f0) (aref verts (1+ base-vert)) (m:make-float4 (* in-r (cos angle)) (* in-r (sin angle)) 0.0f0 1.0f0) (aref inds base-ind) base-vert (aref inds (+ base-ind 1)) (+ base-vert 3) (aref inds (+ base-ind 2)) (+ base-vert 1) (aref inds (+ base-ind 3)) base-vert (aref inds (+ base-ind 4)) (+ base-vert 2) (aref inds (+ base-ind 5)) (+ base-vert 3) base-ind (+ 6 base-ind)))) (let ((last-index (1- (* 6 vert-num)))) (setf (aref inds last-index) 1) (setf (aref inds (- last-index 1)) 0) (setf (aref inds (- last-index 4)) 1)) (make-render-object (list (make-instance 'batch :indices inds :vertices verts)) (make-semantics ((:vertex :float 4))) material transform)))
c7ea633d240971b1a498e325e0435f244b981919c67c1e70e039853dfce275ef
phoityne/ghci-dap
Tags.hs
----------------------------------------------------------------------------- -- GHCi 's : ctags and : commands -- ( c ) The GHC Team 2005 - 2007 -- ----------------------------------------------------------------------------- # OPTIONS_GHC -fno - warn - name - shadowing # module GHCi.UI.Tags ( createCTagsWithLineNumbersCmd, createCTagsWithRegExesCmd, createETagsFileCmd ) where import Exception import GHC import GHCi.UI.Monad import Outputable ToDo : figure out whether we need these , and put something appropriate into the GHC API instead import Name (nameOccName) import OccName (pprOccName) import ConLike import MonadUtils import Control.Monad import Data.Function import Data.List import Data.Maybe import Data.Ord import DriverPhases import Panic import Prelude import System.Directory import System.IO import System.IO.Error ----------------------------------------------------------------------------- -- create tags file for currently loaded modules. createCTagsWithLineNumbersCmd, createCTagsWithRegExesCmd, createETagsFileCmd :: String -> GHCi () createCTagsWithLineNumbersCmd "" = ghciCreateTagsFile CTagsWithLineNumbers "tags" createCTagsWithLineNumbersCmd file = ghciCreateTagsFile CTagsWithLineNumbers file createCTagsWithRegExesCmd "" = ghciCreateTagsFile CTagsWithRegExes "tags" createCTagsWithRegExesCmd file = ghciCreateTagsFile CTagsWithRegExes file createETagsFileCmd "" = ghciCreateTagsFile ETags "TAGS" createETagsFileCmd file = ghciCreateTagsFile ETags file data TagsKind = ETags | CTagsWithLineNumbers | CTagsWithRegExes ghciCreateTagsFile :: TagsKind -> FilePath -> GHCi () ghciCreateTagsFile kind file = do createTagsFile kind file ToDo : -- - remove restriction that all modules must be interpreted -- (problem: we don't know source locations for entities unless -- we compiled the module. -- -- - extract createTagsFile so it can be used from the command-line ( probably need to fix first problem before this is useful ) . -- createTagsFile :: TagsKind -> FilePath -> GHCi () createTagsFile tagskind tagsFile = do graph <- GHC.getModuleGraph mtags <- mapM listModuleTags (map GHC.ms_mod $ GHC.mgModSummaries graph) either_res <- liftIO $ collateAndWriteTags tagskind tagsFile $ concat mtags case either_res of Left e -> liftIO $ hPutStrLn stderr $ ioeGetErrorString e Right _ -> return () listModuleTags :: GHC.Module -> GHCi [TagInfo] listModuleTags m = do is_interpreted <- GHC.moduleIsInterpreted m -- should we just skip these? when (not is_interpreted) $ let mName = GHC.moduleNameString (GHC.moduleName m) in throwGhcException (CmdLineError ("module '" ++ mName ++ "' is not interpreted")) mbModInfo <- GHC.getModuleInfo m case mbModInfo of Nothing -> return [] Just mInfo -> do dflags <- getDynFlags mb_print_unqual <- GHC.mkPrintUnqualifiedForModule mInfo let unqual = fromMaybe GHC.alwaysQualify mb_print_unqual let names = fromMaybe [] $GHC.modInfoTopLevelScope mInfo let localNames = filter ((m==) . nameModule) names mbTyThings <- mapM GHC.lookupName localNames return $! [ tagInfo dflags unqual exported kind name realLoc | tyThing <- catMaybes mbTyThings , let name = getName tyThing , let exported = GHC.modInfoIsExportedName mInfo name , let kind = tyThing2TagKind tyThing , let loc = srcSpanStart (nameSrcSpan name) , RealSrcLoc realLoc <- [loc] ] where tyThing2TagKind (AnId _) = 'v' tyThing2TagKind (AConLike RealDataCon{}) = 'd' tyThing2TagKind (AConLike PatSynCon{}) = 'p' tyThing2TagKind (ATyCon _) = 't' tyThing2TagKind (ACoAxiom _) = 'x' data TagInfo = TagInfo { tagExported :: Bool -- is tag exported , tagKind :: Char -- tag kind , tagName :: String -- tag name , tagFile :: String -- file name , tagLine :: Int -- line number , tagCol :: Int -- column number , tagSrcInfo :: Maybe (String,Integer) -- source code line and char offset } get tag info , for later translation into Vim or Emacs style tagInfo :: DynFlags -> PrintUnqualified -> Bool -> Char -> Name -> RealSrcLoc -> TagInfo tagInfo dflags unqual exported kind name loc = TagInfo exported kind (showSDocForUser dflags unqual $ pprOccName (nameOccName name)) (showSDocForUser dflags unqual $ ftext (srcLocFile loc)) (srcLocLine loc) (srcLocCol loc) Nothing throw an exception when someone tries to overwrite existing source file ( fix for # 10989 ) writeTagsSafely :: FilePath -> String -> IO () writeTagsSafely file str = do dfe <- doesFileExist file if dfe && isSourceFilename file then throwGhcException (CmdLineError (file ++ " is existing source file. " ++ "Please specify another file name to store tags data")) else writeFile file str collateAndWriteTags :: TagsKind -> FilePath -> [TagInfo] -> IO (Either IOError ()) ctags style with the Ex expression being just the line number , collateAndWriteTags CTagsWithLineNumbers file tagInfos = do let tags = unlines $ sort $ map showCTag tagInfos tryIO (writeTagsSafely file tags) ctags style with the Ex expression being a regex searching the line , ctags style , Vim et al tagInfoGroups <- makeTagGroupsWithSrcInfo tagInfos let tags = unlines $ sort $ map showCTag $concat tagInfoGroups tryIO (writeTagsSafely file tags) etags style , Emacs / XEmacs tagInfoGroups <- makeTagGroupsWithSrcInfo $filter tagExported tagInfos let tagGroups = map processGroup tagInfoGroups tryIO (writeTagsSafely file $ concat tagGroups) where processGroup [] = throwGhcException (CmdLineError "empty tag file group??") processGroup group@(tagInfo:_) = let tags = unlines $ map showETag group in "\x0c\n" ++ tagFile tagInfo ++ "," ++ show (length tags) ++ "\n" ++ tags makeTagGroupsWithSrcInfo :: [TagInfo] -> IO [[TagInfo]] makeTagGroupsWithSrcInfo tagInfos = do let groups = groupBy ((==) `on` tagFile) $ sortBy (comparing tagFile) tagInfos mapM addTagSrcInfo groups where addTagSrcInfo [] = throwGhcException (CmdLineError "empty tag file group??") addTagSrcInfo group@(tagInfo:_) = do file <- readFile $tagFile tagInfo let sortedGroup = sortBy (comparing tagLine) group return $ perFile sortedGroup 1 0 $ lines file perFile allTags@(tag:tags) cnt pos allLs@(l:ls) | tagLine tag > cnt = perFile allTags (cnt+1) (pos+fromIntegral(length l)) ls | tagLine tag == cnt = tag{ tagSrcInfo = Just(l,pos) } : perFile tags cnt pos allLs perFile _ _ _ _ = [] ctags format , for Vim et al showCTag :: TagInfo -> String showCTag ti = tagName ti ++ "\t" ++ tagFile ti ++ "\t" ++ tagCmd ++ ";\"\t" ++ tagKind ti : ( if tagExported ti then "" else "\tfile:" ) where tagCmd = case tagSrcInfo ti of Nothing -> show $tagLine ti Just (srcLine,_) -> "/^"++ foldr escapeSlashes [] srcLine ++"$/" where escapeSlashes '/' r = '\\' : '/' : r escapeSlashes '\\' r = '\\' : '\\' : r escapeSlashes c r = c : r etags format , for Emacs / XEmacs showETag :: TagInfo -> String showETag TagInfo{ tagName = tag, tagLine = lineNo, tagCol = colNo, tagSrcInfo = Just (srcLine,charPos) } = take (colNo - 1) srcLine ++ tag ++ "\x7f" ++ tag ++ "\x01" ++ show lineNo ++ "," ++ show charPos showETag _ = throwGhcException (CmdLineError "missing source file info in showETag")
null
https://raw.githubusercontent.com/phoityne/ghci-dap/bcc921b1859df0f64a282a4dc3e2e04f2b57ddf7/app-ghc-8.10/GHCi/UI/Tags.hs
haskell
--------------------------------------------------------------------------- --------------------------------------------------------------------------- --------------------------------------------------------------------------- create tags file for currently loaded modules. - remove restriction that all modules must be interpreted (problem: we don't know source locations for entities unless we compiled the module. - extract createTagsFile so it can be used from the command-line should we just skip these? is tag exported tag kind tag name file name line number column number source code line and char offset
GHCi 's : ctags and : commands ( c ) The GHC Team 2005 - 2007 # OPTIONS_GHC -fno - warn - name - shadowing # module GHCi.UI.Tags ( createCTagsWithLineNumbersCmd, createCTagsWithRegExesCmd, createETagsFileCmd ) where import Exception import GHC import GHCi.UI.Monad import Outputable ToDo : figure out whether we need these , and put something appropriate into the GHC API instead import Name (nameOccName) import OccName (pprOccName) import ConLike import MonadUtils import Control.Monad import Data.Function import Data.List import Data.Maybe import Data.Ord import DriverPhases import Panic import Prelude import System.Directory import System.IO import System.IO.Error createCTagsWithLineNumbersCmd, createCTagsWithRegExesCmd, createETagsFileCmd :: String -> GHCi () createCTagsWithLineNumbersCmd "" = ghciCreateTagsFile CTagsWithLineNumbers "tags" createCTagsWithLineNumbersCmd file = ghciCreateTagsFile CTagsWithLineNumbers file createCTagsWithRegExesCmd "" = ghciCreateTagsFile CTagsWithRegExes "tags" createCTagsWithRegExesCmd file = ghciCreateTagsFile CTagsWithRegExes file createETagsFileCmd "" = ghciCreateTagsFile ETags "TAGS" createETagsFileCmd file = ghciCreateTagsFile ETags file data TagsKind = ETags | CTagsWithLineNumbers | CTagsWithRegExes ghciCreateTagsFile :: TagsKind -> FilePath -> GHCi () ghciCreateTagsFile kind file = do createTagsFile kind file ToDo : ( probably need to fix first problem before this is useful ) . createTagsFile :: TagsKind -> FilePath -> GHCi () createTagsFile tagskind tagsFile = do graph <- GHC.getModuleGraph mtags <- mapM listModuleTags (map GHC.ms_mod $ GHC.mgModSummaries graph) either_res <- liftIO $ collateAndWriteTags tagskind tagsFile $ concat mtags case either_res of Left e -> liftIO $ hPutStrLn stderr $ ioeGetErrorString e Right _ -> return () listModuleTags :: GHC.Module -> GHCi [TagInfo] listModuleTags m = do is_interpreted <- GHC.moduleIsInterpreted m when (not is_interpreted) $ let mName = GHC.moduleNameString (GHC.moduleName m) in throwGhcException (CmdLineError ("module '" ++ mName ++ "' is not interpreted")) mbModInfo <- GHC.getModuleInfo m case mbModInfo of Nothing -> return [] Just mInfo -> do dflags <- getDynFlags mb_print_unqual <- GHC.mkPrintUnqualifiedForModule mInfo let unqual = fromMaybe GHC.alwaysQualify mb_print_unqual let names = fromMaybe [] $GHC.modInfoTopLevelScope mInfo let localNames = filter ((m==) . nameModule) names mbTyThings <- mapM GHC.lookupName localNames return $! [ tagInfo dflags unqual exported kind name realLoc | tyThing <- catMaybes mbTyThings , let name = getName tyThing , let exported = GHC.modInfoIsExportedName mInfo name , let kind = tyThing2TagKind tyThing , let loc = srcSpanStart (nameSrcSpan name) , RealSrcLoc realLoc <- [loc] ] where tyThing2TagKind (AnId _) = 'v' tyThing2TagKind (AConLike RealDataCon{}) = 'd' tyThing2TagKind (AConLike PatSynCon{}) = 'p' tyThing2TagKind (ATyCon _) = 't' tyThing2TagKind (ACoAxiom _) = 'x' data TagInfo = TagInfo } get tag info , for later translation into Vim or Emacs style tagInfo :: DynFlags -> PrintUnqualified -> Bool -> Char -> Name -> RealSrcLoc -> TagInfo tagInfo dflags unqual exported kind name loc = TagInfo exported kind (showSDocForUser dflags unqual $ pprOccName (nameOccName name)) (showSDocForUser dflags unqual $ ftext (srcLocFile loc)) (srcLocLine loc) (srcLocCol loc) Nothing throw an exception when someone tries to overwrite existing source file ( fix for # 10989 ) writeTagsSafely :: FilePath -> String -> IO () writeTagsSafely file str = do dfe <- doesFileExist file if dfe && isSourceFilename file then throwGhcException (CmdLineError (file ++ " is existing source file. " ++ "Please specify another file name to store tags data")) else writeFile file str collateAndWriteTags :: TagsKind -> FilePath -> [TagInfo] -> IO (Either IOError ()) ctags style with the Ex expression being just the line number , collateAndWriteTags CTagsWithLineNumbers file tagInfos = do let tags = unlines $ sort $ map showCTag tagInfos tryIO (writeTagsSafely file tags) ctags style with the Ex expression being a regex searching the line , ctags style , Vim et al tagInfoGroups <- makeTagGroupsWithSrcInfo tagInfos let tags = unlines $ sort $ map showCTag $concat tagInfoGroups tryIO (writeTagsSafely file tags) etags style , Emacs / XEmacs tagInfoGroups <- makeTagGroupsWithSrcInfo $filter tagExported tagInfos let tagGroups = map processGroup tagInfoGroups tryIO (writeTagsSafely file $ concat tagGroups) where processGroup [] = throwGhcException (CmdLineError "empty tag file group??") processGroup group@(tagInfo:_) = let tags = unlines $ map showETag group in "\x0c\n" ++ tagFile tagInfo ++ "," ++ show (length tags) ++ "\n" ++ tags makeTagGroupsWithSrcInfo :: [TagInfo] -> IO [[TagInfo]] makeTagGroupsWithSrcInfo tagInfos = do let groups = groupBy ((==) `on` tagFile) $ sortBy (comparing tagFile) tagInfos mapM addTagSrcInfo groups where addTagSrcInfo [] = throwGhcException (CmdLineError "empty tag file group??") addTagSrcInfo group@(tagInfo:_) = do file <- readFile $tagFile tagInfo let sortedGroup = sortBy (comparing tagLine) group return $ perFile sortedGroup 1 0 $ lines file perFile allTags@(tag:tags) cnt pos allLs@(l:ls) | tagLine tag > cnt = perFile allTags (cnt+1) (pos+fromIntegral(length l)) ls | tagLine tag == cnt = tag{ tagSrcInfo = Just(l,pos) } : perFile tags cnt pos allLs perFile _ _ _ _ = [] ctags format , for Vim et al showCTag :: TagInfo -> String showCTag ti = tagName ti ++ "\t" ++ tagFile ti ++ "\t" ++ tagCmd ++ ";\"\t" ++ tagKind ti : ( if tagExported ti then "" else "\tfile:" ) where tagCmd = case tagSrcInfo ti of Nothing -> show $tagLine ti Just (srcLine,_) -> "/^"++ foldr escapeSlashes [] srcLine ++"$/" where escapeSlashes '/' r = '\\' : '/' : r escapeSlashes '\\' r = '\\' : '\\' : r escapeSlashes c r = c : r etags format , for Emacs / XEmacs showETag :: TagInfo -> String showETag TagInfo{ tagName = tag, tagLine = lineNo, tagCol = colNo, tagSrcInfo = Just (srcLine,charPos) } = take (colNo - 1) srcLine ++ tag ++ "\x7f" ++ tag ++ "\x01" ++ show lineNo ++ "," ++ show charPos showETag _ = throwGhcException (CmdLineError "missing source file info in showETag")
490fca04a86e67077a2f32b6b6c948a5fdeb3d89f4a195afb6aac680c3b68acc
iamFIREcracker/adventofcode
day17.lisp
(defpackage :aoc/2020/17 #.cl-user::*aoc-use*) (in-package :aoc/2020/17) (defun parse-coords (data) (let* ((width (length (first data))) (height (length data))) (loop for y upto height for row in data nconc (loop for x upto width for c across row when (eql c #\#) collect (list x y 0))))) (defparameter *neighbors-deltas* nil) (defun neighbors-deltas (dimensions) (labels ((recur (n) (cond ((= n 0) (list nil)) (t (loop for d from -1 upto 1 nconc (loop for rest in (recur (1- n)) collect (cons d rest))))))) (remove-if (lambda (x) (apply #'= 0 x)) (recur dimensions)))) (defun neighbors (pos) (loop for delta in *neighbors-deltas* collect (mapcar #'+ pos delta))) (defun play (coords &aux (dimensions (length (first coords)))) (let* ((*neighbors-deltas* (neighbors-deltas dimensions)) (game (make-hset coords :test 'equal))) (dotimes (n 6 (hset-size game)) (setf game (gol:next game :neighbors #'neighbors))))) (define-solution (2020 17) (coords parse-coords) (values (play coords) (play (mapcar #'(lambda (x) (append x (list 0))) coords)))) (define-test (2020 17) (315 1520))
null
https://raw.githubusercontent.com/iamFIREcracker/adventofcode/c395df5e15657f0b9be6ec555e68dc777b0eb7ab/src/2020/day17.lisp
lisp
(defpackage :aoc/2020/17 #.cl-user::*aoc-use*) (in-package :aoc/2020/17) (defun parse-coords (data) (let* ((width (length (first data))) (height (length data))) (loop for y upto height for row in data nconc (loop for x upto width for c across row when (eql c #\#) collect (list x y 0))))) (defparameter *neighbors-deltas* nil) (defun neighbors-deltas (dimensions) (labels ((recur (n) (cond ((= n 0) (list nil)) (t (loop for d from -1 upto 1 nconc (loop for rest in (recur (1- n)) collect (cons d rest))))))) (remove-if (lambda (x) (apply #'= 0 x)) (recur dimensions)))) (defun neighbors (pos) (loop for delta in *neighbors-deltas* collect (mapcar #'+ pos delta))) (defun play (coords &aux (dimensions (length (first coords)))) (let* ((*neighbors-deltas* (neighbors-deltas dimensions)) (game (make-hset coords :test 'equal))) (dotimes (n 6 (hset-size game)) (setf game (gol:next game :neighbors #'neighbors))))) (define-solution (2020 17) (coords parse-coords) (values (play coords) (play (mapcar #'(lambda (x) (append x (list 0))) coords)))) (define-test (2020 17) (315 1520))
d5b139a0e0bbd9d7344a5da3336cdb993a9d10098848192bd43cd775bbd89af6
Abbath/Calculator
Messages.hs
# LANGUAGE DataKinds # {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeOperators #-} module Web.Telegram.API.Bot.API.Messages ( -- * Functions sendMessage , sendMessageM , forwardMessage , forwardMessageM , uploadPhoto , uploadPhotoM , sendPhoto , sendPhotoM , uploadAudio , uploadAudioM , sendAudio , sendAudioM , uploadDocument , uploadDocumentM , sendDocument , sendDocumentM , uploadSticker , uploadStickerM , sendSticker , sendStickerM , uploadVideo , uploadVideoM , sendVideo , sendVideoM , uploadVoice , uploadVoiceM , sendVoice , sendVoiceM , uploadVideoNote , uploadVideoNoteM , sendVideoNote , sendVideoNoteM , sendMediaGroupM , sendLocation , sendLocationM , sendVenue , sendVenueM , sendContact , sendContactM , sendChatAction , sendChatActionM , sendGame , sendGameM -- * API , TelegramBotMessagesAPI , messagesApi -- * Types ) where import Data.Proxy import Data.Text (Text) import Network.HTTP.Client (Manager) import Servant.API import Servant.Client hiding (Response) import Servant.Client.MultipartFormData import Web.Telegram.API.Bot.API.Core import Web.Telegram.API.Bot.Data import Web.Telegram.API.Bot.Requests import Web.Telegram.API.Bot.Responses -- | Telegram Bot API type TelegramBotMessagesAPI = TelegramToken :> "sendMessage" :> ReqBody '[JSON] SendMessageRequest :> Post '[JSON] MessageResponse :<|> TelegramToken :> "forwardMessage" :> ReqBody '[JSON] ForwardMessageRequest :> Post '[JSON] MessageResponse :<|> TelegramToken :> "sendPhoto" :> MultipartFormDataReqBody (SendPhotoRequest FileUpload) :> Post '[JSON] MessageResponse :<|> TelegramToken :> "sendPhoto" :> ReqBody '[JSON] (SendPhotoRequest Text) :> Post '[JSON] MessageResponse :<|> TelegramToken :> "sendAudio" :> MultipartFormDataReqBody (SendAudioRequest FileUpload) :> Post '[JSON] MessageResponse :<|> TelegramToken :> "sendAudio" :> ReqBody '[JSON] (SendAudioRequest Text) :> Post '[JSON] MessageResponse :<|> TelegramToken :> "sendDocument" :> MultipartFormDataReqBody (SendDocumentRequest FileUpload) :> Post '[JSON] MessageResponse :<|> TelegramToken :> "sendDocument" :> ReqBody '[JSON] (SendDocumentRequest Text) :> Post '[JSON] MessageResponse :<|> TelegramToken :> "sendSticker" :> MultipartFormDataReqBody (SendStickerRequest FileUpload) :> Post '[JSON] MessageResponse :<|> TelegramToken :> "sendSticker" :> ReqBody '[JSON] (SendStickerRequest Text) :> Post '[JSON] MessageResponse :<|> TelegramToken :> "sendVideo" :> MultipartFormDataReqBody (SendVideoRequest FileUpload) :> Post '[JSON] MessageResponse :<|> TelegramToken :> "sendVideo" :> ReqBody '[JSON] (SendVideoRequest Text) :> Post '[JSON] MessageResponse :<|> TelegramToken :> "sendVoice" :> MultipartFormDataReqBody (SendVoiceRequest FileUpload) :> Post '[JSON] MessageResponse :<|> TelegramToken :> "sendVoice" :> ReqBody '[JSON] (SendVoiceRequest Text) :> Post '[JSON] MessageResponse :<|> TelegramToken :> "sendVideoNote" :> MultipartFormDataReqBody (SendVideoNoteRequest FileUpload) :> Post '[JSON] MessageResponse :<|> TelegramToken :> "sendVideoNote" :> ReqBody '[JSON] (SendVideoNoteRequest Text) :> Post '[JSON] MessageResponse :<|> TelegramToken :> "sendMediaGroup" :> ReqBody '[JSON] SendMediaGroupRequest :> Post '[JSON] (Response [Message]) :<|> TelegramToken :> "sendLocation" :> ReqBody '[JSON] SendLocationRequest :> Post '[JSON] MessageResponse :<|> TelegramToken :> "sendVenue" :> ReqBody '[JSON] SendVenueRequest :> Post '[JSON] MessageResponse :<|> TelegramToken :> "sendContact" :> ReqBody '[JSON] SendContactRequest :> Post '[JSON] MessageResponse :<|> TelegramToken :> "sendChatAction" :> ReqBody '[JSON] SendChatActionRequest :> Post '[JSON] ChatActionResponse :<|> TelegramToken :> "sendGame" :> ReqBody '[JSON] SendGameRequest :> Post '[JSON] MessageResponse | Proxy for API messagesApi :: Proxy TelegramBotMessagesAPI messagesApi = Proxy sendMessage_ :: Token -> SendMessageRequest -> ClientM MessageResponse forwardMessage_ :: Token -> ForwardMessageRequest -> ClientM MessageResponse uploadPhoto_ :: Token -> SendPhotoRequest FileUpload -> ClientM MessageResponse sendPhoto_ :: Token -> SendPhotoRequest Text -> ClientM MessageResponse uploadAudio_ :: Token -> SendAudioRequest FileUpload -> ClientM MessageResponse sendAudio_ :: Token -> SendAudioRequest Text -> ClientM MessageResponse uploadDocument_ :: Token -> SendDocumentRequest FileUpload -> ClientM MessageResponse sendDocument_ :: Token -> SendDocumentRequest Text -> ClientM MessageResponse uploadSticker_ :: Token -> SendStickerRequest FileUpload -> ClientM MessageResponse sendSticker_ :: Token -> SendStickerRequest Text -> ClientM MessageResponse uploadVideo_ :: Token -> SendVideoRequest FileUpload -> ClientM MessageResponse sendVideo_ :: Token -> SendVideoRequest Text -> ClientM MessageResponse uploadVoice_ :: Token -> SendVoiceRequest FileUpload -> ClientM MessageResponse sendVoice_ :: Token -> SendVoiceRequest Text -> ClientM MessageResponse uploadVideoNote_ :: Token -> SendVideoNoteRequest FileUpload -> ClientM MessageResponse sendVideoNote_ :: Token -> SendVideoNoteRequest Text -> ClientM MessageResponse sendMediaGroup_ :: Token -> SendMediaGroupRequest -> ClientM (Response [Message]) sendLocation_ :: Token -> SendLocationRequest -> ClientM MessageResponse sendVenue_ :: Token -> SendVenueRequest-> ClientM MessageResponse sendContact_ :: Token -> SendContactRequest -> ClientM MessageResponse sendChatAction_ :: Token -> SendChatActionRequest -> ClientM ChatActionResponse sendGame_ :: Token -> SendGameRequest -> ClientM MessageResponse sendMessage_ :<|> forwardMessage_ :<|> uploadPhoto_ :<|> sendPhoto_ :<|> uploadAudio_ :<|> sendAudio_ :<|> uploadDocument_ :<|> sendDocument_ :<|> uploadSticker_ :<|> sendSticker_ :<|> uploadVideo_ :<|> sendVideo_ :<|> uploadVoice_ :<|> sendVoice_ :<|> uploadVideoNote_ :<|> sendVideoNote_ :<|> sendMediaGroup_ :<|> sendLocation_ :<|> sendVenue_ :<|> sendContact_ :<|> sendChatAction_ :<|> sendGame_ = client messagesApi -- | Use this method to send text messages. On success, the sent 'Message' is returned. sendMessage :: Token -> SendMessageRequest -> Manager -> IO (Either ClientError MessageResponse) sendMessage = runM sendMessageM -- | See 'sendMessage' sendMessageM :: SendMessageRequest -> TelegramClient MessageResponse sendMessageM = run_ sendMessage_ -- | Use this method to forward messages of any kind. On success, the sent 'Message' is returned. forwardMessage :: Token -> ForwardMessageRequest -> Manager -> IO (Either ClientError MessageResponse) forwardMessage = runM forwardMessageM -- | See 'forwardMessage' forwardMessageM :: ForwardMessageRequest -> TelegramClient MessageResponse forwardMessageM = run_ forwardMessage_ -- | Use this method to upload and send photos. On success, the sent 'Message' is returned. uploadPhoto :: Token -> SendPhotoRequest FileUpload -> Manager -> IO (Either ClientError MessageResponse) uploadPhoto = runM uploadPhotoM -- | See 'uploadPhoto' uploadPhotoM :: SendPhotoRequest FileUpload -> TelegramClient MessageResponse uploadPhotoM = run_ uploadPhoto_ -- | Use this method to send photos that have already been uploaded. On success, the sent 'Message' is returned. sendPhoto :: Token -> SendPhotoRequest Text -> Manager -> IO (Either ClientError MessageResponse) sendPhoto = runM sendPhotoM -- | See 'sendPhoto' sendPhotoM :: SendPhotoRequest Text -> TelegramClient MessageResponse sendPhotoM = run_ sendPhoto_ | Use this method to upload and send audio files , if you want Telegram clients to display them in the music player . Your audio must be in the .mp3 format . On success , the sent ' Message ' is returned . Bots can currently send audio files of up to 50 MB in size , this limit may be changed in the future . -- For backward compatibility , when the fields _ _ title _ _ and _ _ performer _ _ are both empty and the mime - type of the file to be sent is not _ audio / mpeg _ , the file will be sent as a playable voice message . For this to work , the audio must be in an .ogg file encoded with OPUS . This behavior will be phased out in the future . For sending voice messages , use the ' sendVoice ' method instead . uploadAudio :: Token -> SendAudioRequest FileUpload -> Manager -> IO (Either ClientError MessageResponse) uploadAudio = runM uploadAudioM -- | See 'uploadAudio' uploadAudioM :: SendAudioRequest FileUpload -> TelegramClient MessageResponse uploadAudioM = run_ uploadAudio_ | Use this method to send audio files that are already on the Telegram servers , if you want Telegram clients to display them in the music player . Your audio must be in the .mp3 format . On success , the sent ' Message ' is returned . Bots can currently send audio files of up to 50 MB in size , this limit may be changed in the future . -- For backward compatibility , when the fields _ _ title _ _ and _ _ performer _ _ are both empty and the mime - type of the file to be sent is not _ audio / mpeg _ , the file will be sent as a playable voice message . For this to work , the audio must be in an .ogg file encoded with OPUS . This behavior will be phased out in the future . For sending voice messages , use the ' sendVoice ' method instead . sendAudio :: Token -> SendAudioRequest Text -> Manager -> IO (Either ClientError MessageResponse) sendAudio = runM sendAudioM -- | See 'sendAudio' sendAudioM :: SendAudioRequest Text -> TelegramClient MessageResponse sendAudioM = run_ sendAudio_ | Use this method to upload and send general files . On success , the sent ' Message ' is returned . Bots can currently send files of any type of up to 50 MB in size , this limit may be changed in the future . uploadDocument :: Token -> SendDocumentRequest FileUpload -> Manager -> IO (Either ClientError MessageResponse) uploadDocument = runM uploadDocumentM -- | See 'uploadDocument' uploadDocumentM :: SendDocumentRequest FileUpload -> TelegramClient MessageResponse uploadDocumentM = run_ uploadDocument_ | Use this method to send general files that have already been uploaded . On success , the sent ' Message ' is returned . Bots can currently send files of any type of up to 50 MB in size , this limit may be changed in the future . sendDocument :: Token -> SendDocumentRequest Text -> Manager -> IO (Either ClientError MessageResponse) sendDocument = runM sendDocumentM -- | See 'sendDocument' sendDocumentM :: SendDocumentRequest Text -> TelegramClient MessageResponse sendDocumentM = run_ sendDocument_ -- | Use this method to upload and send .webp stickers. On success, the sent 'Message' is returned. uploadSticker :: Token -> SendStickerRequest FileUpload -> Manager -> IO (Either ClientError MessageResponse) uploadSticker = runM uploadStickerM -- | See 'uploadSticker' uploadStickerM :: SendStickerRequest FileUpload -> TelegramClient MessageResponse uploadStickerM = run_ uploadSticker_ | Use this method to send .webp stickers that are already on the Telegram servers . On success , the sent ' Message ' is returned . sendSticker :: Token -> SendStickerRequest Text -> Manager -> IO (Either ClientError MessageResponse) sendSticker = runM sendStickerM -- | See 'sendSticker' sendStickerM :: SendStickerRequest Text -> TelegramClient MessageResponse sendStickerM = run_ sendSticker_ | Use this method to upload and send video files . Telegram clients support mp4 videos ( other formats may be sent as ' Document ' ) . On success , the sent ' Message ' is returned . Bots can currently send video files of up to 50 MB in size , this limit may be changed in the future . uploadVideo :: Token -> SendVideoRequest FileUpload -> Manager -> IO (Either ClientError MessageResponse) uploadVideo = runM uploadVideoM -- | See 'uploadVideo' uploadVideoM :: SendVideoRequest FileUpload -> TelegramClient MessageResponse uploadVideoM = run_ uploadVideo_ | Use this method to send video files that are already on the Telegram servers . Telegram clients support mp4 videos ( other formats may be sent as ' Document ' ) . On success , the sent ' Message ' is returned . Bots can currently send video files of up to 50 MB in size , this limit may be changed in the future . sendVideo :: Token -> SendVideoRequest Text -> Manager -> IO (Either ClientError MessageResponse) sendVideo = runM sendVideoM -- | See 'sendVideo' sendVideoM :: SendVideoRequest Text -> TelegramClient MessageResponse sendVideoM = run_ sendVideo_ | Use this method to upload and send audio files , if you want Telegram clients to display the file as a playable voice message . For this to work , your audio must be in an .ogg file encoded with OPUS ( other formats may be sent as ' Audio ' or ' Document ' ) . On success , the sent ' Message ' is returned . Bots can currently send voice messages of up to 50 MB in size , this limit may be changed in the future . uploadVoice :: Token -> SendVoiceRequest FileUpload -> Manager -> IO (Either ClientError MessageResponse) uploadVoice = runM uploadVoiceM -- | See 'uploadVoice' uploadVoiceM :: SendVoiceRequest FileUpload -> TelegramClient MessageResponse uploadVoiceM = run_ uploadVoice_ | Use this method to send audio files that are already on the telegram server , if you want Telegram clients to display the file as a playable voice message . For this to work , your audio must be in an .ogg file encoded with OPUS ( other formats may be sent as ' Audio ' or ' Document ' ) . On success , the sent ' Message ' is returned . Bots can currently send voice messages of up to 50 MB in size , this limit may be changed in the future . sendVoice :: Token -> SendVoiceRequest Text -> Manager -> IO (Either ClientError MessageResponse) sendVoice = runM sendVoiceM -- | See 'sendVoice' sendVoiceM :: SendVoiceRequest Text -> TelegramClient MessageResponse sendVoiceM = run_ sendVoice_ | As of v.4.0 , Telegram clients support rounded square mp4 videos of up to 1 minute long . Use this method to send video messages . On success , the sent Message is returned . uploadVideoNote :: Token -> SendVideoNoteRequest FileUpload -> Manager -> IO (Either ClientError MessageResponse) uploadVideoNote = runM uploadVideoNoteM -- | See 'uploadVideoNote' uploadVideoNoteM :: SendVideoNoteRequest FileUpload -> TelegramClient MessageResponse uploadVideoNoteM = run_ uploadVideoNote_ | As of v.4.0 , Telegram clients support rounded square mp4 videos of up to 1 minute long . Use this method to send video messages . On success , the sent Message is returned . sendVideoNote :: Token -> SendVideoNoteRequest Text -> Manager -> IO (Either ClientError MessageResponse) sendVideoNote = runM sendVideoNoteM -- | See 'sendVoice' sendVideoNoteM :: SendVideoNoteRequest Text -> TelegramClient MessageResponse sendVideoNoteM = run_ sendVideoNote_ -- | Use this method to send point on the map. On success, the sent 'Message' is returned. sendLocation :: Token -> SendLocationRequest -> Manager -> IO (Either ClientError MessageResponse) sendLocation = runM sendLocationM -- | See 'sendLocation' sendLocationM :: SendLocationRequest -> TelegramClient MessageResponse sendLocationM = run_ sendLocation_ sendMediaGroupM :: SendMediaGroupRequest -> TelegramClient (Response [Message]) sendMediaGroupM = run_ sendMediaGroup_ -- | Use this method to send information about a venue. On success, the sent 'Message' is returned. sendVenue :: Token -> SendVenueRequest -> Manager -> IO (Either ClientError MessageResponse) sendVenue = runM sendVenueM -- | See 'sendVenue' sendVenueM :: SendVenueRequest -> TelegramClient MessageResponse sendVenueM = run_ sendVenue_ -- | Use this method to send information about a venue. On success, the sent 'Message' is returned. sendContact :: Token -> SendContactRequest -> Manager -> IO (Either ClientError MessageResponse) sendContact = runM sendContactM -- | See 'sendContact' sendContactM :: SendContactRequest -> TelegramClient MessageResponse sendContactM = run_ sendContact_ -- | Use this method when you need to tell the user that something is happening on the bot's side. The status is set for 5 seconds or less ( when a message arrives from your bot , Telegram clients clear its typing status ) . sendChatAction :: Token -> SendChatActionRequest -> Manager -> IO (Either ClientError ChatActionResponse) sendChatAction = runM sendChatActionM -- | See 'sendChatAction' sendChatActionM :: SendChatActionRequest -> TelegramClient ChatActionResponse sendChatActionM = run_ sendChatAction_ -- | Use this method to send a game. On success, the sent 'Message' is returned. sendGame :: Token -> SendGameRequest -> Manager -> IO (Either ClientError MessageResponse) sendGame = runM sendGameM -- | See 'sendGame' sendGameM :: SendGameRequest -> TelegramClient MessageResponse sendGameM = run_ sendGame_
null
https://raw.githubusercontent.com/Abbath/Calculator/75985d5a9b4e602bc087462c8046bf2cf692a0e1/telegram-api-0.7.2.0/src/Web/Telegram/API/Bot/API/Messages.hs
haskell
# LANGUAGE OverloadedStrings # # LANGUAGE TypeOperators # * Functions * API * Types | Telegram Bot API | Use this method to send text messages. On success, the sent 'Message' is returned. | See 'sendMessage' | Use this method to forward messages of any kind. On success, the sent 'Message' is returned. | See 'forwardMessage' | Use this method to upload and send photos. On success, the sent 'Message' is returned. | See 'uploadPhoto' | Use this method to send photos that have already been uploaded. On success, the sent 'Message' is returned. | See 'sendPhoto' | See 'uploadAudio' | See 'sendAudio' | See 'uploadDocument' | See 'sendDocument' | Use this method to upload and send .webp stickers. On success, the sent 'Message' is returned. | See 'uploadSticker' | See 'sendSticker' | See 'uploadVideo' | See 'sendVideo' | See 'uploadVoice' | See 'sendVoice' | See 'uploadVideoNote' | See 'sendVoice' | Use this method to send point on the map. On success, the sent 'Message' is returned. | See 'sendLocation' | Use this method to send information about a venue. On success, the sent 'Message' is returned. | See 'sendVenue' | Use this method to send information about a venue. On success, the sent 'Message' is returned. | See 'sendContact' | Use this method when you need to tell the user that something is happening on the bot's side. | See 'sendChatAction' | Use this method to send a game. On success, the sent 'Message' is returned. | See 'sendGame'
# LANGUAGE DataKinds # module Web.Telegram.API.Bot.API.Messages sendMessage , sendMessageM , forwardMessage , forwardMessageM , uploadPhoto , uploadPhotoM , sendPhoto , sendPhotoM , uploadAudio , uploadAudioM , sendAudio , sendAudioM , uploadDocument , uploadDocumentM , sendDocument , sendDocumentM , uploadSticker , uploadStickerM , sendSticker , sendStickerM , uploadVideo , uploadVideoM , sendVideo , sendVideoM , uploadVoice , uploadVoiceM , sendVoice , sendVoiceM , uploadVideoNote , uploadVideoNoteM , sendVideoNote , sendVideoNoteM , sendMediaGroupM , sendLocation , sendLocationM , sendVenue , sendVenueM , sendContact , sendContactM , sendChatAction , sendChatActionM , sendGame , sendGameM , TelegramBotMessagesAPI , messagesApi ) where import Data.Proxy import Data.Text (Text) import Network.HTTP.Client (Manager) import Servant.API import Servant.Client hiding (Response) import Servant.Client.MultipartFormData import Web.Telegram.API.Bot.API.Core import Web.Telegram.API.Bot.Data import Web.Telegram.API.Bot.Requests import Web.Telegram.API.Bot.Responses type TelegramBotMessagesAPI = TelegramToken :> "sendMessage" :> ReqBody '[JSON] SendMessageRequest :> Post '[JSON] MessageResponse :<|> TelegramToken :> "forwardMessage" :> ReqBody '[JSON] ForwardMessageRequest :> Post '[JSON] MessageResponse :<|> TelegramToken :> "sendPhoto" :> MultipartFormDataReqBody (SendPhotoRequest FileUpload) :> Post '[JSON] MessageResponse :<|> TelegramToken :> "sendPhoto" :> ReqBody '[JSON] (SendPhotoRequest Text) :> Post '[JSON] MessageResponse :<|> TelegramToken :> "sendAudio" :> MultipartFormDataReqBody (SendAudioRequest FileUpload) :> Post '[JSON] MessageResponse :<|> TelegramToken :> "sendAudio" :> ReqBody '[JSON] (SendAudioRequest Text) :> Post '[JSON] MessageResponse :<|> TelegramToken :> "sendDocument" :> MultipartFormDataReqBody (SendDocumentRequest FileUpload) :> Post '[JSON] MessageResponse :<|> TelegramToken :> "sendDocument" :> ReqBody '[JSON] (SendDocumentRequest Text) :> Post '[JSON] MessageResponse :<|> TelegramToken :> "sendSticker" :> MultipartFormDataReqBody (SendStickerRequest FileUpload) :> Post '[JSON] MessageResponse :<|> TelegramToken :> "sendSticker" :> ReqBody '[JSON] (SendStickerRequest Text) :> Post '[JSON] MessageResponse :<|> TelegramToken :> "sendVideo" :> MultipartFormDataReqBody (SendVideoRequest FileUpload) :> Post '[JSON] MessageResponse :<|> TelegramToken :> "sendVideo" :> ReqBody '[JSON] (SendVideoRequest Text) :> Post '[JSON] MessageResponse :<|> TelegramToken :> "sendVoice" :> MultipartFormDataReqBody (SendVoiceRequest FileUpload) :> Post '[JSON] MessageResponse :<|> TelegramToken :> "sendVoice" :> ReqBody '[JSON] (SendVoiceRequest Text) :> Post '[JSON] MessageResponse :<|> TelegramToken :> "sendVideoNote" :> MultipartFormDataReqBody (SendVideoNoteRequest FileUpload) :> Post '[JSON] MessageResponse :<|> TelegramToken :> "sendVideoNote" :> ReqBody '[JSON] (SendVideoNoteRequest Text) :> Post '[JSON] MessageResponse :<|> TelegramToken :> "sendMediaGroup" :> ReqBody '[JSON] SendMediaGroupRequest :> Post '[JSON] (Response [Message]) :<|> TelegramToken :> "sendLocation" :> ReqBody '[JSON] SendLocationRequest :> Post '[JSON] MessageResponse :<|> TelegramToken :> "sendVenue" :> ReqBody '[JSON] SendVenueRequest :> Post '[JSON] MessageResponse :<|> TelegramToken :> "sendContact" :> ReqBody '[JSON] SendContactRequest :> Post '[JSON] MessageResponse :<|> TelegramToken :> "sendChatAction" :> ReqBody '[JSON] SendChatActionRequest :> Post '[JSON] ChatActionResponse :<|> TelegramToken :> "sendGame" :> ReqBody '[JSON] SendGameRequest :> Post '[JSON] MessageResponse | Proxy for API messagesApi :: Proxy TelegramBotMessagesAPI messagesApi = Proxy sendMessage_ :: Token -> SendMessageRequest -> ClientM MessageResponse forwardMessage_ :: Token -> ForwardMessageRequest -> ClientM MessageResponse uploadPhoto_ :: Token -> SendPhotoRequest FileUpload -> ClientM MessageResponse sendPhoto_ :: Token -> SendPhotoRequest Text -> ClientM MessageResponse uploadAudio_ :: Token -> SendAudioRequest FileUpload -> ClientM MessageResponse sendAudio_ :: Token -> SendAudioRequest Text -> ClientM MessageResponse uploadDocument_ :: Token -> SendDocumentRequest FileUpload -> ClientM MessageResponse sendDocument_ :: Token -> SendDocumentRequest Text -> ClientM MessageResponse uploadSticker_ :: Token -> SendStickerRequest FileUpload -> ClientM MessageResponse sendSticker_ :: Token -> SendStickerRequest Text -> ClientM MessageResponse uploadVideo_ :: Token -> SendVideoRequest FileUpload -> ClientM MessageResponse sendVideo_ :: Token -> SendVideoRequest Text -> ClientM MessageResponse uploadVoice_ :: Token -> SendVoiceRequest FileUpload -> ClientM MessageResponse sendVoice_ :: Token -> SendVoiceRequest Text -> ClientM MessageResponse uploadVideoNote_ :: Token -> SendVideoNoteRequest FileUpload -> ClientM MessageResponse sendVideoNote_ :: Token -> SendVideoNoteRequest Text -> ClientM MessageResponse sendMediaGroup_ :: Token -> SendMediaGroupRequest -> ClientM (Response [Message]) sendLocation_ :: Token -> SendLocationRequest -> ClientM MessageResponse sendVenue_ :: Token -> SendVenueRequest-> ClientM MessageResponse sendContact_ :: Token -> SendContactRequest -> ClientM MessageResponse sendChatAction_ :: Token -> SendChatActionRequest -> ClientM ChatActionResponse sendGame_ :: Token -> SendGameRequest -> ClientM MessageResponse sendMessage_ :<|> forwardMessage_ :<|> uploadPhoto_ :<|> sendPhoto_ :<|> uploadAudio_ :<|> sendAudio_ :<|> uploadDocument_ :<|> sendDocument_ :<|> uploadSticker_ :<|> sendSticker_ :<|> uploadVideo_ :<|> sendVideo_ :<|> uploadVoice_ :<|> sendVoice_ :<|> uploadVideoNote_ :<|> sendVideoNote_ :<|> sendMediaGroup_ :<|> sendLocation_ :<|> sendVenue_ :<|> sendContact_ :<|> sendChatAction_ :<|> sendGame_ = client messagesApi sendMessage :: Token -> SendMessageRequest -> Manager -> IO (Either ClientError MessageResponse) sendMessage = runM sendMessageM sendMessageM :: SendMessageRequest -> TelegramClient MessageResponse sendMessageM = run_ sendMessage_ forwardMessage :: Token -> ForwardMessageRequest -> Manager -> IO (Either ClientError MessageResponse) forwardMessage = runM forwardMessageM forwardMessageM :: ForwardMessageRequest -> TelegramClient MessageResponse forwardMessageM = run_ forwardMessage_ uploadPhoto :: Token -> SendPhotoRequest FileUpload -> Manager -> IO (Either ClientError MessageResponse) uploadPhoto = runM uploadPhotoM uploadPhotoM :: SendPhotoRequest FileUpload -> TelegramClient MessageResponse uploadPhotoM = run_ uploadPhoto_ sendPhoto :: Token -> SendPhotoRequest Text -> Manager -> IO (Either ClientError MessageResponse) sendPhoto = runM sendPhotoM sendPhotoM :: SendPhotoRequest Text -> TelegramClient MessageResponse sendPhotoM = run_ sendPhoto_ | Use this method to upload and send audio files , if you want Telegram clients to display them in the music player . Your audio must be in the .mp3 format . On success , the sent ' Message ' is returned . Bots can currently send audio files of up to 50 MB in size , this limit may be changed in the future . For backward compatibility , when the fields _ _ title _ _ and _ _ performer _ _ are both empty and the mime - type of the file to be sent is not _ audio / mpeg _ , the file will be sent as a playable voice message . For this to work , the audio must be in an .ogg file encoded with OPUS . This behavior will be phased out in the future . For sending voice messages , use the ' sendVoice ' method instead . uploadAudio :: Token -> SendAudioRequest FileUpload -> Manager -> IO (Either ClientError MessageResponse) uploadAudio = runM uploadAudioM uploadAudioM :: SendAudioRequest FileUpload -> TelegramClient MessageResponse uploadAudioM = run_ uploadAudio_ | Use this method to send audio files that are already on the Telegram servers , if you want Telegram clients to display them in the music player . Your audio must be in the .mp3 format . On success , the sent ' Message ' is returned . Bots can currently send audio files of up to 50 MB in size , this limit may be changed in the future . For backward compatibility , when the fields _ _ title _ _ and _ _ performer _ _ are both empty and the mime - type of the file to be sent is not _ audio / mpeg _ , the file will be sent as a playable voice message . For this to work , the audio must be in an .ogg file encoded with OPUS . This behavior will be phased out in the future . For sending voice messages , use the ' sendVoice ' method instead . sendAudio :: Token -> SendAudioRequest Text -> Manager -> IO (Either ClientError MessageResponse) sendAudio = runM sendAudioM sendAudioM :: SendAudioRequest Text -> TelegramClient MessageResponse sendAudioM = run_ sendAudio_ | Use this method to upload and send general files . On success , the sent ' Message ' is returned . Bots can currently send files of any type of up to 50 MB in size , this limit may be changed in the future . uploadDocument :: Token -> SendDocumentRequest FileUpload -> Manager -> IO (Either ClientError MessageResponse) uploadDocument = runM uploadDocumentM uploadDocumentM :: SendDocumentRequest FileUpload -> TelegramClient MessageResponse uploadDocumentM = run_ uploadDocument_ | Use this method to send general files that have already been uploaded . On success , the sent ' Message ' is returned . Bots can currently send files of any type of up to 50 MB in size , this limit may be changed in the future . sendDocument :: Token -> SendDocumentRequest Text -> Manager -> IO (Either ClientError MessageResponse) sendDocument = runM sendDocumentM sendDocumentM :: SendDocumentRequest Text -> TelegramClient MessageResponse sendDocumentM = run_ sendDocument_ uploadSticker :: Token -> SendStickerRequest FileUpload -> Manager -> IO (Either ClientError MessageResponse) uploadSticker = runM uploadStickerM uploadStickerM :: SendStickerRequest FileUpload -> TelegramClient MessageResponse uploadStickerM = run_ uploadSticker_ | Use this method to send .webp stickers that are already on the Telegram servers . On success , the sent ' Message ' is returned . sendSticker :: Token -> SendStickerRequest Text -> Manager -> IO (Either ClientError MessageResponse) sendSticker = runM sendStickerM sendStickerM :: SendStickerRequest Text -> TelegramClient MessageResponse sendStickerM = run_ sendSticker_ | Use this method to upload and send video files . Telegram clients support mp4 videos ( other formats may be sent as ' Document ' ) . On success , the sent ' Message ' is returned . Bots can currently send video files of up to 50 MB in size , this limit may be changed in the future . uploadVideo :: Token -> SendVideoRequest FileUpload -> Manager -> IO (Either ClientError MessageResponse) uploadVideo = runM uploadVideoM uploadVideoM :: SendVideoRequest FileUpload -> TelegramClient MessageResponse uploadVideoM = run_ uploadVideo_ | Use this method to send video files that are already on the Telegram servers . Telegram clients support mp4 videos ( other formats may be sent as ' Document ' ) . On success , the sent ' Message ' is returned . Bots can currently send video files of up to 50 MB in size , this limit may be changed in the future . sendVideo :: Token -> SendVideoRequest Text -> Manager -> IO (Either ClientError MessageResponse) sendVideo = runM sendVideoM sendVideoM :: SendVideoRequest Text -> TelegramClient MessageResponse sendVideoM = run_ sendVideo_ | Use this method to upload and send audio files , if you want Telegram clients to display the file as a playable voice message . For this to work , your audio must be in an .ogg file encoded with OPUS ( other formats may be sent as ' Audio ' or ' Document ' ) . On success , the sent ' Message ' is returned . Bots can currently send voice messages of up to 50 MB in size , this limit may be changed in the future . uploadVoice :: Token -> SendVoiceRequest FileUpload -> Manager -> IO (Either ClientError MessageResponse) uploadVoice = runM uploadVoiceM uploadVoiceM :: SendVoiceRequest FileUpload -> TelegramClient MessageResponse uploadVoiceM = run_ uploadVoice_ | Use this method to send audio files that are already on the telegram server , if you want Telegram clients to display the file as a playable voice message . For this to work , your audio must be in an .ogg file encoded with OPUS ( other formats may be sent as ' Audio ' or ' Document ' ) . On success , the sent ' Message ' is returned . Bots can currently send voice messages of up to 50 MB in size , this limit may be changed in the future . sendVoice :: Token -> SendVoiceRequest Text -> Manager -> IO (Either ClientError MessageResponse) sendVoice = runM sendVoiceM sendVoiceM :: SendVoiceRequest Text -> TelegramClient MessageResponse sendVoiceM = run_ sendVoice_ | As of v.4.0 , Telegram clients support rounded square mp4 videos of up to 1 minute long . Use this method to send video messages . On success , the sent Message is returned . uploadVideoNote :: Token -> SendVideoNoteRequest FileUpload -> Manager -> IO (Either ClientError MessageResponse) uploadVideoNote = runM uploadVideoNoteM uploadVideoNoteM :: SendVideoNoteRequest FileUpload -> TelegramClient MessageResponse uploadVideoNoteM = run_ uploadVideoNote_ | As of v.4.0 , Telegram clients support rounded square mp4 videos of up to 1 minute long . Use this method to send video messages . On success , the sent Message is returned . sendVideoNote :: Token -> SendVideoNoteRequest Text -> Manager -> IO (Either ClientError MessageResponse) sendVideoNote = runM sendVideoNoteM sendVideoNoteM :: SendVideoNoteRequest Text -> TelegramClient MessageResponse sendVideoNoteM = run_ sendVideoNote_ sendLocation :: Token -> SendLocationRequest -> Manager -> IO (Either ClientError MessageResponse) sendLocation = runM sendLocationM sendLocationM :: SendLocationRequest -> TelegramClient MessageResponse sendLocationM = run_ sendLocation_ sendMediaGroupM :: SendMediaGroupRequest -> TelegramClient (Response [Message]) sendMediaGroupM = run_ sendMediaGroup_ sendVenue :: Token -> SendVenueRequest -> Manager -> IO (Either ClientError MessageResponse) sendVenue = runM sendVenueM sendVenueM :: SendVenueRequest -> TelegramClient MessageResponse sendVenueM = run_ sendVenue_ sendContact :: Token -> SendContactRequest -> Manager -> IO (Either ClientError MessageResponse) sendContact = runM sendContactM sendContactM :: SendContactRequest -> TelegramClient MessageResponse sendContactM = run_ sendContact_ The status is set for 5 seconds or less ( when a message arrives from your bot , Telegram clients clear its typing status ) . sendChatAction :: Token -> SendChatActionRequest -> Manager -> IO (Either ClientError ChatActionResponse) sendChatAction = runM sendChatActionM sendChatActionM :: SendChatActionRequest -> TelegramClient ChatActionResponse sendChatActionM = run_ sendChatAction_ sendGame :: Token -> SendGameRequest -> Manager -> IO (Either ClientError MessageResponse) sendGame = runM sendGameM sendGameM :: SendGameRequest -> TelegramClient MessageResponse sendGameM = run_ sendGame_
5897bf26d2e051ac5413a59b6316d5989490a9e4584a2e2754a15ed198dfb41b
jafingerhut/dolly
project.clj
(defproject jafingerhut/dolly "0.2.0-SNAPSHOT" :description "Clojure namespace cloning" :url "" :license {:name "Eclipse Public License" :url "-v10.html"} :dependencies [[org.clojure/clojure "1.5.1"] [ org.clojure/tools.namespace " 0.2.7 " ] [rhizome "0.2.1"]] :eval-in-leiningen true)
null
https://raw.githubusercontent.com/jafingerhut/dolly/6dfe7f3bcd58d81fba7793d214230792b6140ffd/project.clj
clojure
(defproject jafingerhut/dolly "0.2.0-SNAPSHOT" :description "Clojure namespace cloning" :url "" :license {:name "Eclipse Public License" :url "-v10.html"} :dependencies [[org.clojure/clojure "1.5.1"] [ org.clojure/tools.namespace " 0.2.7 " ] [rhizome "0.2.1"]] :eval-in-leiningen true)
bea11a04ff1f278e311f305e5318ef9223efefbe458deec3e5cc2ca8e986e8a9
vinted/kafka-elasticsearch-tool
elasticsearch.clj
(ns source.elasticsearch (:require [source.elasticsearch.records :as records] [source.elasticsearch.search-after-with-pit :as pit])) (defn fetch [opts] (let [strategy (-> opts :source :strategy)] (case strategy :search-after-with-pit (pit/fetch opts) (records/fetch opts)))) (comment (fetch {:max_docs 10 :source {:remote {:host ":9200"} :index "source-index-name"}}) (fetch {:max_docs 10 :source {:remote {:host ":9200"} :index "source-index-name" :strategy :search-after-with-pit}}))
null
https://raw.githubusercontent.com/vinted/kafka-elasticsearch-tool/281de24d51cbd2a7ad78e3c1d13a4619b786210d/src/source/elasticsearch.clj
clojure
(ns source.elasticsearch (:require [source.elasticsearch.records :as records] [source.elasticsearch.search-after-with-pit :as pit])) (defn fetch [opts] (let [strategy (-> opts :source :strategy)] (case strategy :search-after-with-pit (pit/fetch opts) (records/fetch opts)))) (comment (fetch {:max_docs 10 :source {:remote {:host ":9200"} :index "source-index-name"}}) (fetch {:max_docs 10 :source {:remote {:host ":9200"} :index "source-index-name" :strategy :search-after-with-pit}}))
f240230de94429e4791a551ff1493ee62254fa833aa017df3bd58f50e27e5025
runtimeverification/haskell-backend
Null.hs
| Module : . Attribute . Null Description : Null attribute parser Copyright : ( c ) Runtime Verification , 2018 - 2021 License : BSD-3 - Clause Maintainer : The ' Null ' attribute is used when we need a type to satisfy the attribute parser , but we do not actually care to parse any attributes . This parser simply ignores all attributes . This module is intended to be imported qualified : @ import Kore . Attribute . Null qualified as Attribute @ Module : Kore.Attribute.Null Description : Null attribute parser Copyright : (c) Runtime Verification, 2018-2021 License : BSD-3-Clause Maintainer : The 'Null' attribute is used when we need a type to satisfy the attribute parser, but we do not actually care to parse any attributes. This parser simply ignores all attributes. This module is intended to be imported qualified: @ import Kore.Attribute.Null qualified as Attribute @ -} module Kore.Attribute.Null ( Null (..), ) where import Data.Default import GHC.Generics qualified as GHC import Generics.SOP qualified as SOP import Kore.Debug import Prelude.Kore data Null = Null deriving stock (Eq, Ord, Show) deriving stock (GHC.Generic) deriving anyclass (NFData) deriving anyclass (SOP.Generic, SOP.HasDatatypeInfo) deriving anyclass (Debug, Diff) instance Default Null where def = Null instance Semigroup Null where (<>) _ _ = Null instance Monoid Null where mempty = Null
null
https://raw.githubusercontent.com/runtimeverification/haskell-backend/b06757e252ee01fdd5ab8f07de2910711997d845/kore/src/Kore/Attribute/Null.hs
haskell
| Module : . Attribute . Null Description : Null attribute parser Copyright : ( c ) Runtime Verification , 2018 - 2021 License : BSD-3 - Clause Maintainer : The ' Null ' attribute is used when we need a type to satisfy the attribute parser , but we do not actually care to parse any attributes . This parser simply ignores all attributes . This module is intended to be imported qualified : @ import Kore . Attribute . Null qualified as Attribute @ Module : Kore.Attribute.Null Description : Null attribute parser Copyright : (c) Runtime Verification, 2018-2021 License : BSD-3-Clause Maintainer : The 'Null' attribute is used when we need a type to satisfy the attribute parser, but we do not actually care to parse any attributes. This parser simply ignores all attributes. This module is intended to be imported qualified: @ import Kore.Attribute.Null qualified as Attribute @ -} module Kore.Attribute.Null ( Null (..), ) where import Data.Default import GHC.Generics qualified as GHC import Generics.SOP qualified as SOP import Kore.Debug import Prelude.Kore data Null = Null deriving stock (Eq, Ord, Show) deriving stock (GHC.Generic) deriving anyclass (NFData) deriving anyclass (SOP.Generic, SOP.HasDatatypeInfo) deriving anyclass (Debug, Diff) instance Default Null where def = Null instance Semigroup Null where (<>) _ _ = Null instance Monoid Null where mempty = Null
8b57f112c7b140c1026eb070cab913a8ad0500035d47ee8c89361b5693879de2
politrons/Dive_into_Haskell
ConditionsFunction.hs
module ConditionsFunction where messageFunc :: String -> String -> String -- | In this example we show how a simple nested if works messageFunc name surname= if(name =="Paul") then "Hey " ++ name ++ " how you doing!" else if(surname == "Perez") then surname ++".... Ah!, I know your family" else "Do I know you?" -- | In this example we show how if else works more similar to pattern matching. messageCaseFunc name surname | name == "Paul" = "Hey " ++ name ++ " how you doing!" | surname == "Perez" = surname ++".... Ah!, I know your family" | otherwise = "Do I know you?" | Here another example of patter matching over a variable . [ case ] value_to_match [ of ] cases just like in Scala word = "Hello" outputPatternMatching = case word of "Hello" -> "Hi, how are you?" "Bye" -> "Why are you leaving so soon?" | Just like in Scala all if / else conditions return a value , so one more time do nt allow mutability isPaul = (\name -> name == "Paul") :: String -> Bool outputValue = \name -> if(isPaul name) then "Hey Paul" else "Who are you"
null
https://raw.githubusercontent.com/politrons/Dive_into_Haskell/fd9dec14b87aecba0b3561385c1d75cf969546a4/src/features/ConditionsFunction.hs
haskell
| In this example we show how a simple nested if works | In this example we show how if else works more similar to pattern matching.
module ConditionsFunction where messageFunc :: String -> String -> String messageFunc name surname= if(name =="Paul") then "Hey " ++ name ++ " how you doing!" else if(surname == "Perez") then surname ++".... Ah!, I know your family" else "Do I know you?" messageCaseFunc name surname | name == "Paul" = "Hey " ++ name ++ " how you doing!" | surname == "Perez" = surname ++".... Ah!, I know your family" | otherwise = "Do I know you?" | Here another example of patter matching over a variable . [ case ] value_to_match [ of ] cases just like in Scala word = "Hello" outputPatternMatching = case word of "Hello" -> "Hi, how are you?" "Bye" -> "Why are you leaving so soon?" | Just like in Scala all if / else conditions return a value , so one more time do nt allow mutability isPaul = (\name -> name == "Paul") :: String -> Bool outputValue = \name -> if(isPaul name) then "Hey Paul" else "Who are you"
7a3b83e179778919e6d7b715974509c1d34c6d238d48398273d2f1cbe148589d
serokell/time-warp
MonadTimedSpec.hs
# LANGUAGE ExistentialQuantification # # LANGUAGE FlexibleInstances # {-# LANGUAGE Rank2Types #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE ViewPatterns #-} | RSCoin . Test . MonadTimed specification module Test.Control.TimeWarp.Timed.MonadTimedSpec ( spec , timeoutProp -- workaround warning, remove after it's used ) where import Control.Concurrent.MVar (newEmptyMVar, putMVar, takeMVar) import Control.Concurrent.STM (atomically) import Control.Concurrent.STM.TVar (newTVarIO, readTVarIO, writeTVar) import Control.Exception.Base (Exception, SomeException) import Control.Monad (void) import Control.Monad.Catch (MonadCatch, catch, catchAll, handleAll, throwM) import Control.Monad.State (StateT, execStateT, modify, put) import Control.Monad.Trans (MonadIO, liftIO) import Data.Typeable (Typeable) import Numeric.Natural (Natural) import Test.Hspec (Spec, describe) import Test.Hspec.QuickCheck (prop) import Test.QuickCheck (NonNegative (..), Property, counterexample, ioProperty) import Test.QuickCheck.Function (Fun, apply) import Test.QuickCheck.Monadic (PropertyM, assert, monadic, monitor, run) import Test.QuickCheck.Poly (A) import Control.TimeWarp.Timed (Microsecond, MonadTimed (..), MonadTimedError, RelativeToNow, TimedIO, TimedT, TimedT, after, for, fork_, invoke, now, runTimedIO, runTimedT, schedule, sec, killThread) import Test.Control.TimeWarp.Common () spec :: Spec spec = describe "MonadTimed" $ do monadTimedSpec "TimedIO" runTimedIOProp monadTimedTSpec "TimedT" runTimedTProp monadTimedSpec :: (MonadTimed m, MonadIO m, MonadCatch m) => String -> (PropertyM m () -> Property) -> Spec monadTimedSpec description runProp = describe description $ do describe "virtualTime >> virtualTime" $ do prop "first virtualTime will run before second virtualTime" $ runProp virtualTimePassingProp describe "wait t" $ do prop "will wait at least t" $ runProp . waitPassingProp describe "fork" $ do prop "won't change semantics of an action" $ \a -> runProp . forkSemanticProp a describe "schedule" $ do prop "won't change semantics of an action, will execute action in the future" $ \a b -> runProp . scheduleSemanticProp a b describe "invoke" $ do prop "won't change semantics of an action, will execute action in the future" $ \a b -> runProp . invokeSemanticProp a b -- TODO: fix tests for timeout in TimedIO. -- describe "timeout" $ do -- prop "should throw an exception if time has exceeded" $ \a - > runProp . timeoutProp a monadTimedTSpec :: String -> (TimedTProp () -> Property) -> Spec monadTimedTSpec description runProp = describe description $ do describe "virtualTime >> virtualTime" $ do prop "first virtualTime will run before second virtualTime" $ runProp virtualTimePassingTimedProp describe "now" $ do prop "now is correct" $ runProp . nowProp describe "wait t" $ do prop "will wait at least t" $ runProp . waitPassingTimedProp describe "fork" $ do prop "won't change semantics of an action" $ \a -> runProp . forkSemanticTimedProp a describe "schedule" $ do prop "won't change semantics of an action, will execute action in the future" $ \a b -> runProp . scheduleSemanticTimedProp a b describe "invoke" $ do prop "won't change semantics of an action, will execute action in the future" $ \a b -> runProp . invokeSemanticTimedProp a b describe "timeout" $ do prop "should throw an exception if time has exceeded" $ \a -> runProp . timeoutTimedProp a describe "killThread" $ do prop "should abort the execution of a thread" $ \a b -> runProp . killThreadTimedProp a b describe "exceptions" $ do prop "thrown nicely" $ runProp exceptionsThrown prop "caught nicely" $ runProp exceptionsThrowCaught prop "wait + throw caught nicely" $ runProp exceptionsWaitThrowCaught prop "exceptions don't affect main thread" $ runProp exceptionNotAffectMainThread prop "exceptions don't affect other threads" $ runProp exceptionNotAffectOtherThread -- pure version type TimedTProp = TimedT ( CatchT ( State Bool ) ) type TimedTProp = TimedT (StateT Bool IO) assertTimedT :: Bool -> TimedTProp () assertTimedT b = modify (b &&) type RelativeToNowNat = Natural fromIntegralRTN :: RelativeToNowNat -> RelativeToNow fromIntegralRTN = (+) . fromIntegral -- TODO: figure out how to test recursive functions like after/at runTimedIOProp :: PropertyM TimedIO () -> Property runTimedIOProp = monadic $ ioProperty . runTimedIO runTimedTProp :: TimedTProp () -> Property runTimedTProp test = ioProperty $ execStateT (runTimedT test) True -- TimedIO tests timeoutProp :: (MonadTimed m, MonadCatch m) => NonNegative Microsecond -> NonNegative Microsecond -> PropertyM m () timeoutProp (getNonNegative -> tout) (getNonNegative -> wt) = do let action = do wait $ for wt return $ wt <= tout handler (_ :: MonadTimedError) = return $ wt >= tout res <- run $ timeout tout action `catch` handler assert res invokeSemanticProp :: (MonadTimed m, MonadIO m) => RelativeToNowNat -> A -> Fun A A -> PropertyM m () invokeSemanticProp = actionTimeSemanticProp invoke scheduleSemanticProp :: (MonadTimed m, MonadIO m) => RelativeToNowNat -> A -> Fun A A -> PropertyM m () scheduleSemanticProp = actionTimeSemanticProp schedule actionTimeSemanticProp :: (MonadTimed m, MonadIO m) => (RelativeToNow -> m () -> m ()) -> RelativeToNowNat -> A -> Fun A A -> PropertyM m () actionTimeSemanticProp action relativeToNow val f = do actionSemanticProp action' val f timePassingProp relativeToNow action' where action' = action $ fromIntegralRTN relativeToNow forkSemanticProp :: (MonadTimed m, MonadIO m) => A -> Fun A A -> PropertyM m () forkSemanticProp = actionSemanticProp fork_ waitPassingProp :: (MonadTimed m, MonadIO m) => RelativeToNowNat -> PropertyM m () waitPassingProp relativeToNow = timePassingProp relativeToNow (wait (fromIntegralRTN relativeToNow) >>) virtualTimePassingProp :: (MonadTimed m, MonadIO m) => PropertyM m () virtualTimePassingProp = timePassingProp 0 id TODO : instead of testing with MVar 's we should create PropertyM an instance of MonadTimed . -- With that we could test inside forked/waited actions -- | Tests that action will be exececuted after relativeToNow timePassingProp :: (MonadTimed m, MonadIO m) => RelativeToNowNat -> (m () -> m ()) -> PropertyM m () timePassingProp relativeToNow action = do mvar <- liftIO newEmptyMVar t1 <- run virtualTime run . action $ virtualTime >>= liftIO . putMVar mvar t2 <- liftIO $ takeMVar mvar monitor (counterexample $ mconcat [ "t1: ", show t1 , ", t2: ", show t2, ", " , show $ fromIntegralRTN relativeToNow t1, " <= ", show t2 ]) assert $ fromIntegralRTN relativeToNow t1 <= t2 -- | Tests that an action will be executed actionSemanticProp :: (MonadTimed m, MonadIO m) => (m () -> m ()) -> A -> Fun A A -> PropertyM m () actionSemanticProp action val f = do mvar <- liftIO newEmptyMVar run . action . liftIO . putMVar mvar $ apply f val result <- liftIO $ takeMVar mvar monitor (counterexample $ mconcat [ "f: ", show f , ", val: ", show val , ", f val: ", show $ apply f val , ", should be: ", show result ]) assert $ apply f val == result -- TimedT tests TODO : As TimedT is an instance of MonadIO , we can now reuse tests for TimedIO instead of these tests TODO : use checkpoints timeout pattern from ExceptionSpec killThreadTimedProp :: NonNegative Microsecond -> NonNegative Microsecond -> NonNegative Microsecond -> TimedTProp () killThreadTimedProp (getNonNegative -> mTime) (getNonNegative -> f1Time) (getNonNegative -> f2Time) = do var <- liftIO $ newTVarIO (0 :: Int) tId <- fork $ do fork_ $ do -- this thread can't be killed wait $ for f1Time liftIO $ atomically $ writeTVar var 1 wait $ for f2Time liftIO $ atomically $ writeTVar var 2 wait $ for mTime killThread tId wait $ for f1Time -- wait for both threads to finish wait $ for f2Time res <- liftIO $ readTVarIO var assertTimedT $ check res where check 0 = mTime <= f1Time && mTime <= f2Time check 1 = True -- this thread can't be killed check 2 = f2Time <= mTime check _ = error "This checkpoint doesn't exist" timeoutTimedProp :: NonNegative Microsecond -> NonNegative Microsecond -> TimedTProp () timeoutTimedProp (getNonNegative -> tout) (getNonNegative -> wt) = do let action = do wait $ for wt return $ wt <= tout handler (_ :: SomeException) = do return $ tout <= wt res <- timeout tout action `catch` handler assertTimedT res invokeSemanticTimedProp :: RelativeToNowNat -> A -> Fun A A -> TimedTProp () invokeSemanticTimedProp = actionTimeSemanticTimedProp invoke scheduleSemanticTimedProp :: RelativeToNowNat -> A -> Fun A A -> TimedTProp () scheduleSemanticTimedProp = actionTimeSemanticTimedProp schedule actionTimeSemanticTimedProp :: (RelativeToNow -> TimedTProp () -> TimedTProp ()) -> RelativeToNowNat -> A -> Fun A A -> TimedTProp () actionTimeSemanticTimedProp action relativeToNow val f = do actionSemanticTimedProp action' val f timePassingTimedProp relativeToNow action' where action' = action $ fromIntegralRTN relativeToNow forkSemanticTimedProp :: A -> Fun A A -> TimedTProp () forkSemanticTimedProp = actionSemanticTimedProp fork_ waitPassingTimedProp :: RelativeToNowNat -> TimedTProp () waitPassingTimedProp relativeToNow = timePassingTimedProp relativeToNow (wait (fromIntegralRTN relativeToNow) >>) virtualTimePassingTimedProp :: TimedTProp () virtualTimePassingTimedProp = timePassingTimedProp 0 id -- | Tests that action will be exececuted after relativeToNow timePassingTimedProp :: RelativeToNowNat -> (TimedTProp () -> TimedTProp ()) -> TimedTProp () timePassingTimedProp relativeToNow action = do t1 <- virtualTime action $ virtualTime >>= assertTimedT . (fromIntegralRTN relativeToNow t1 <=) -- | Tests that an action will be executed actionSemanticTimedProp :: (TimedTProp () -> TimedTProp ()) -> A -> Fun A A -> TimedTProp () actionSemanticTimedProp action val f = do let result = apply f val action $ assertTimedT $ apply f val == result nowProp :: Microsecond -> TimedTProp () nowProp ms = do wait $ for ms t1 <- virtualTime invoke now $ return () t2 <- virtualTime assertTimedT $ t1 == t2 -- * Exceptions data TestException = TestExc deriving (Show, Typeable) instance Exception TestException handleAll' :: MonadCatch m => m () -> m () handleAll' = handleAll $ const $ return () exceptionsThrown :: TimedTProp () exceptionsThrown = handleAll' $ do void $ throwM TestExc put False exceptionsThrowCaught :: TimedTProp () exceptionsThrowCaught = let act = do put False throwM TestExc hnd = const $ put True in act `catchAll` hnd exceptionsWaitThrowCaught :: TimedTProp () exceptionsWaitThrowCaught = let act = do put False wait $ for 1 sec throwM TestExc hnd = const $ put True in act `catchAll` hnd exceptionNotAffectMainThread :: TimedTProp () exceptionNotAffectMainThread = handleAll' $ do put False fork_ $ throwM TestExc wait $ for 1 sec put True exceptionNotAffectOtherThread :: TimedTProp () exceptionNotAffectOtherThread = handleAll' $ do put False schedule (after 3 sec) $ put True schedule (after 1 sec) $ throwM TestExc
null
https://raw.githubusercontent.com/serokell/time-warp/2783f81957a2e5b02e9d3425d760247a6c5a766b/test/Test/Control/TimeWarp/Timed/MonadTimedSpec.hs
haskell
# LANGUAGE Rank2Types # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeSynonymInstances # # LANGUAGE ViewPatterns # workaround warning, remove after it's used TODO: fix tests for timeout in TimedIO. describe "timeout" $ do prop "should throw an exception if time has exceeded" $ pure version TODO: figure out how to test recursive functions like after/at TimedIO tests With that we could test inside forked/waited actions | Tests that action will be exececuted after relativeToNow | Tests that an action will be executed TimedT tests this thread can't be killed wait for both threads to finish this thread can't be killed | Tests that action will be exececuted after relativeToNow | Tests that an action will be executed * Exceptions
# LANGUAGE ExistentialQuantification # # LANGUAGE FlexibleInstances # | RSCoin . Test . MonadTimed specification module Test.Control.TimeWarp.Timed.MonadTimedSpec ( spec ) where import Control.Concurrent.MVar (newEmptyMVar, putMVar, takeMVar) import Control.Concurrent.STM (atomically) import Control.Concurrent.STM.TVar (newTVarIO, readTVarIO, writeTVar) import Control.Exception.Base (Exception, SomeException) import Control.Monad (void) import Control.Monad.Catch (MonadCatch, catch, catchAll, handleAll, throwM) import Control.Monad.State (StateT, execStateT, modify, put) import Control.Monad.Trans (MonadIO, liftIO) import Data.Typeable (Typeable) import Numeric.Natural (Natural) import Test.Hspec (Spec, describe) import Test.Hspec.QuickCheck (prop) import Test.QuickCheck (NonNegative (..), Property, counterexample, ioProperty) import Test.QuickCheck.Function (Fun, apply) import Test.QuickCheck.Monadic (PropertyM, assert, monadic, monitor, run) import Test.QuickCheck.Poly (A) import Control.TimeWarp.Timed (Microsecond, MonadTimed (..), MonadTimedError, RelativeToNow, TimedIO, TimedT, TimedT, after, for, fork_, invoke, now, runTimedIO, runTimedT, schedule, sec, killThread) import Test.Control.TimeWarp.Common () spec :: Spec spec = describe "MonadTimed" $ do monadTimedSpec "TimedIO" runTimedIOProp monadTimedTSpec "TimedT" runTimedTProp monadTimedSpec :: (MonadTimed m, MonadIO m, MonadCatch m) => String -> (PropertyM m () -> Property) -> Spec monadTimedSpec description runProp = describe description $ do describe "virtualTime >> virtualTime" $ do prop "first virtualTime will run before second virtualTime" $ runProp virtualTimePassingProp describe "wait t" $ do prop "will wait at least t" $ runProp . waitPassingProp describe "fork" $ do prop "won't change semantics of an action" $ \a -> runProp . forkSemanticProp a describe "schedule" $ do prop "won't change semantics of an action, will execute action in the future" $ \a b -> runProp . scheduleSemanticProp a b describe "invoke" $ do prop "won't change semantics of an action, will execute action in the future" $ \a b -> runProp . invokeSemanticProp a b \a - > runProp . timeoutProp a monadTimedTSpec :: String -> (TimedTProp () -> Property) -> Spec monadTimedTSpec description runProp = describe description $ do describe "virtualTime >> virtualTime" $ do prop "first virtualTime will run before second virtualTime" $ runProp virtualTimePassingTimedProp describe "now" $ do prop "now is correct" $ runProp . nowProp describe "wait t" $ do prop "will wait at least t" $ runProp . waitPassingTimedProp describe "fork" $ do prop "won't change semantics of an action" $ \a -> runProp . forkSemanticTimedProp a describe "schedule" $ do prop "won't change semantics of an action, will execute action in the future" $ \a b -> runProp . scheduleSemanticTimedProp a b describe "invoke" $ do prop "won't change semantics of an action, will execute action in the future" $ \a b -> runProp . invokeSemanticTimedProp a b describe "timeout" $ do prop "should throw an exception if time has exceeded" $ \a -> runProp . timeoutTimedProp a describe "killThread" $ do prop "should abort the execution of a thread" $ \a b -> runProp . killThreadTimedProp a b describe "exceptions" $ do prop "thrown nicely" $ runProp exceptionsThrown prop "caught nicely" $ runProp exceptionsThrowCaught prop "wait + throw caught nicely" $ runProp exceptionsWaitThrowCaught prop "exceptions don't affect main thread" $ runProp exceptionNotAffectMainThread prop "exceptions don't affect other threads" $ runProp exceptionNotAffectOtherThread type TimedTProp = TimedT ( CatchT ( State Bool ) ) type TimedTProp = TimedT (StateT Bool IO) assertTimedT :: Bool -> TimedTProp () assertTimedT b = modify (b &&) type RelativeToNowNat = Natural fromIntegralRTN :: RelativeToNowNat -> RelativeToNow fromIntegralRTN = (+) . fromIntegral runTimedIOProp :: PropertyM TimedIO () -> Property runTimedIOProp = monadic $ ioProperty . runTimedIO runTimedTProp :: TimedTProp () -> Property runTimedTProp test = ioProperty $ execStateT (runTimedT test) True timeoutProp :: (MonadTimed m, MonadCatch m) => NonNegative Microsecond -> NonNegative Microsecond -> PropertyM m () timeoutProp (getNonNegative -> tout) (getNonNegative -> wt) = do let action = do wait $ for wt return $ wt <= tout handler (_ :: MonadTimedError) = return $ wt >= tout res <- run $ timeout tout action `catch` handler assert res invokeSemanticProp :: (MonadTimed m, MonadIO m) => RelativeToNowNat -> A -> Fun A A -> PropertyM m () invokeSemanticProp = actionTimeSemanticProp invoke scheduleSemanticProp :: (MonadTimed m, MonadIO m) => RelativeToNowNat -> A -> Fun A A -> PropertyM m () scheduleSemanticProp = actionTimeSemanticProp schedule actionTimeSemanticProp :: (MonadTimed m, MonadIO m) => (RelativeToNow -> m () -> m ()) -> RelativeToNowNat -> A -> Fun A A -> PropertyM m () actionTimeSemanticProp action relativeToNow val f = do actionSemanticProp action' val f timePassingProp relativeToNow action' where action' = action $ fromIntegralRTN relativeToNow forkSemanticProp :: (MonadTimed m, MonadIO m) => A -> Fun A A -> PropertyM m () forkSemanticProp = actionSemanticProp fork_ waitPassingProp :: (MonadTimed m, MonadIO m) => RelativeToNowNat -> PropertyM m () waitPassingProp relativeToNow = timePassingProp relativeToNow (wait (fromIntegralRTN relativeToNow) >>) virtualTimePassingProp :: (MonadTimed m, MonadIO m) => PropertyM m () virtualTimePassingProp = timePassingProp 0 id TODO : instead of testing with MVar 's we should create PropertyM an instance of MonadTimed . timePassingProp :: (MonadTimed m, MonadIO m) => RelativeToNowNat -> (m () -> m ()) -> PropertyM m () timePassingProp relativeToNow action = do mvar <- liftIO newEmptyMVar t1 <- run virtualTime run . action $ virtualTime >>= liftIO . putMVar mvar t2 <- liftIO $ takeMVar mvar monitor (counterexample $ mconcat [ "t1: ", show t1 , ", t2: ", show t2, ", " , show $ fromIntegralRTN relativeToNow t1, " <= ", show t2 ]) assert $ fromIntegralRTN relativeToNow t1 <= t2 actionSemanticProp :: (MonadTimed m, MonadIO m) => (m () -> m ()) -> A -> Fun A A -> PropertyM m () actionSemanticProp action val f = do mvar <- liftIO newEmptyMVar run . action . liftIO . putMVar mvar $ apply f val result <- liftIO $ takeMVar mvar monitor (counterexample $ mconcat [ "f: ", show f , ", val: ", show val , ", f val: ", show $ apply f val , ", should be: ", show result ]) assert $ apply f val == result TODO : As TimedT is an instance of MonadIO , we can now reuse tests for TimedIO instead of these tests TODO : use checkpoints timeout pattern from ExceptionSpec killThreadTimedProp :: NonNegative Microsecond -> NonNegative Microsecond -> NonNegative Microsecond -> TimedTProp () killThreadTimedProp (getNonNegative -> mTime) (getNonNegative -> f1Time) (getNonNegative -> f2Time) = do var <- liftIO $ newTVarIO (0 :: Int) tId <- fork $ do wait $ for f1Time liftIO $ atomically $ writeTVar var 1 wait $ for f2Time liftIO $ atomically $ writeTVar var 2 wait $ for mTime killThread tId wait $ for f2Time res <- liftIO $ readTVarIO var assertTimedT $ check res where check 0 = mTime <= f1Time && mTime <= f2Time check 2 = f2Time <= mTime check _ = error "This checkpoint doesn't exist" timeoutTimedProp :: NonNegative Microsecond -> NonNegative Microsecond -> TimedTProp () timeoutTimedProp (getNonNegative -> tout) (getNonNegative -> wt) = do let action = do wait $ for wt return $ wt <= tout handler (_ :: SomeException) = do return $ tout <= wt res <- timeout tout action `catch` handler assertTimedT res invokeSemanticTimedProp :: RelativeToNowNat -> A -> Fun A A -> TimedTProp () invokeSemanticTimedProp = actionTimeSemanticTimedProp invoke scheduleSemanticTimedProp :: RelativeToNowNat -> A -> Fun A A -> TimedTProp () scheduleSemanticTimedProp = actionTimeSemanticTimedProp schedule actionTimeSemanticTimedProp :: (RelativeToNow -> TimedTProp () -> TimedTProp ()) -> RelativeToNowNat -> A -> Fun A A -> TimedTProp () actionTimeSemanticTimedProp action relativeToNow val f = do actionSemanticTimedProp action' val f timePassingTimedProp relativeToNow action' where action' = action $ fromIntegralRTN relativeToNow forkSemanticTimedProp :: A -> Fun A A -> TimedTProp () forkSemanticTimedProp = actionSemanticTimedProp fork_ waitPassingTimedProp :: RelativeToNowNat -> TimedTProp () waitPassingTimedProp relativeToNow = timePassingTimedProp relativeToNow (wait (fromIntegralRTN relativeToNow) >>) virtualTimePassingTimedProp :: TimedTProp () virtualTimePassingTimedProp = timePassingTimedProp 0 id timePassingTimedProp :: RelativeToNowNat -> (TimedTProp () -> TimedTProp ()) -> TimedTProp () timePassingTimedProp relativeToNow action = do t1 <- virtualTime action $ virtualTime >>= assertTimedT . (fromIntegralRTN relativeToNow t1 <=) actionSemanticTimedProp :: (TimedTProp () -> TimedTProp ()) -> A -> Fun A A -> TimedTProp () actionSemanticTimedProp action val f = do let result = apply f val action $ assertTimedT $ apply f val == result nowProp :: Microsecond -> TimedTProp () nowProp ms = do wait $ for ms t1 <- virtualTime invoke now $ return () t2 <- virtualTime assertTimedT $ t1 == t2 data TestException = TestExc deriving (Show, Typeable) instance Exception TestException handleAll' :: MonadCatch m => m () -> m () handleAll' = handleAll $ const $ return () exceptionsThrown :: TimedTProp () exceptionsThrown = handleAll' $ do void $ throwM TestExc put False exceptionsThrowCaught :: TimedTProp () exceptionsThrowCaught = let act = do put False throwM TestExc hnd = const $ put True in act `catchAll` hnd exceptionsWaitThrowCaught :: TimedTProp () exceptionsWaitThrowCaught = let act = do put False wait $ for 1 sec throwM TestExc hnd = const $ put True in act `catchAll` hnd exceptionNotAffectMainThread :: TimedTProp () exceptionNotAffectMainThread = handleAll' $ do put False fork_ $ throwM TestExc wait $ for 1 sec put True exceptionNotAffectOtherThread :: TimedTProp () exceptionNotAffectOtherThread = handleAll' $ do put False schedule (after 3 sec) $ put True schedule (after 1 sec) $ throwM TestExc
780da39913a2c4655a6fe45bad0675c9b41c3a5f8d542980a1bad99bce231e52
maryrosecook/islaclj
library.clj
(ns isla.test.library (:use [isla.interpreter]) (:use [isla.parser]) (:require [isla.library :as library]) (:use [clojure.test]) (:use [clojure.pprint]) (:require [mrc.utils :as utils])) ;; write (deftest test-write-object-attributes (let [result (interpret (parse "jimmy is a giraffe\njimmy instrument is 'guitar' jimmy height is '5 metres'\nwrite jimmy"))] (is (= (:ret result) "a giraffe\n height is 5 metres\n instrument is guitar")))) (deftest test-write-list (let [result (interpret (parse "jimmy is a giraffe\njimmy instrument is 'guitar' isla is a tiger\nisla instrument is 'drums' basket is a list\n add jimmy to basket\nadd isla to basket\nwrite basket"))] (is (= (:ret result) "a list:\n a giraffe\n instrument is guitar\n a tiger\n instrument is drums")))) (deftest test-write-object-with-list (let [result (interpret (parse "isla is a person\nisla friends is a list\n jimmy is a giraffe\njimmy instrument is 'guitar' add jimmy to isla friends\nwrite isla"))] (is (= (:ret result) "a person\n friends is a list:\n a giraffe\n instrument is guitar"))))
null
https://raw.githubusercontent.com/maryrosecook/islaclj/4394ddcbd05d3d2da91c89f28e57c764bfef8d88/test/isla/test/library.clj
clojure
write
(ns isla.test.library (:use [isla.interpreter]) (:use [isla.parser]) (:require [isla.library :as library]) (:use [clojure.test]) (:use [clojure.pprint]) (:require [mrc.utils :as utils])) (deftest test-write-object-attributes (let [result (interpret (parse "jimmy is a giraffe\njimmy instrument is 'guitar' jimmy height is '5 metres'\nwrite jimmy"))] (is (= (:ret result) "a giraffe\n height is 5 metres\n instrument is guitar")))) (deftest test-write-list (let [result (interpret (parse "jimmy is a giraffe\njimmy instrument is 'guitar' isla is a tiger\nisla instrument is 'drums' basket is a list\n add jimmy to basket\nadd isla to basket\nwrite basket"))] (is (= (:ret result) "a list:\n a giraffe\n instrument is guitar\n a tiger\n instrument is drums")))) (deftest test-write-object-with-list (let [result (interpret (parse "isla is a person\nisla friends is a list\n jimmy is a giraffe\njimmy instrument is 'guitar' add jimmy to isla friends\nwrite isla"))] (is (= (:ret result) "a person\n friends is a list:\n a giraffe\n instrument is guitar"))))
2e9e6b8350b85cdfe9398e80f60e6c85aec696a7cb846695ccea8147fbb3f48e
khotyn/4clojure-answer
117-for-science.clj
(fn [board] (let [vec-board (vec (map vec board)) row-count (count vec-board) column-count (count (first vec-board))] (letfn [(get-pos [ch] (mapcat #(mapcat (fn [j] (if (= ch ((vec-board %) j)) [% j])) (range 0 column-count)) (range 0 row-count))) (continous-blank [ch coordinate searched-point]) (step [[results searched-point] [x y]] (let [neighbours (concat (if (pos? x) [[(dec x) y]]) (if (pos? y) [[x (dec y)]]) (if (> (- row-count x) 1) [[(inc x) y]]) (if (> (- column-count y) 1) [[x (inc y)]])) valid-neighbours (filter #(and (not= ((vec-board (first %)) (last %)) \#) (nil? (some #{%} searched-point))) neighbours)] (if (seq valid-neighbours) (if (some #(= ((vec-board (first %)) (last %)) \C) valid-neighbours) [(cons true results) (conj searched-point [x y])] (reduce #(step %1 %2) [results (conj searched-point [x y])] valid-neighbours)) [results (conj searched-point [x y])])))] (let [mouse (get-pos \M)] ((complement empty?) (first (step [[] #{(vec mouse)}] mouse)))))))
null
https://raw.githubusercontent.com/khotyn/4clojure-answer/3de82d732faedceafac4f1585a72d0712fe5d3c6/117-for-science.clj
clojure
(fn [board] (let [vec-board (vec (map vec board)) row-count (count vec-board) column-count (count (first vec-board))] (letfn [(get-pos [ch] (mapcat #(mapcat (fn [j] (if (= ch ((vec-board %) j)) [% j])) (range 0 column-count)) (range 0 row-count))) (continous-blank [ch coordinate searched-point]) (step [[results searched-point] [x y]] (let [neighbours (concat (if (pos? x) [[(dec x) y]]) (if (pos? y) [[x (dec y)]]) (if (> (- row-count x) 1) [[(inc x) y]]) (if (> (- column-count y) 1) [[x (inc y)]])) valid-neighbours (filter #(and (not= ((vec-board (first %)) (last %)) \#) (nil? (some #{%} searched-point))) neighbours)] (if (seq valid-neighbours) (if (some #(= ((vec-board (first %)) (last %)) \C) valid-neighbours) [(cons true results) (conj searched-point [x y])] (reduce #(step %1 %2) [results (conj searched-point [x y])] valid-neighbours)) [results (conj searched-point [x y])])))] (let [mouse (get-pos \M)] ((complement empty?) (first (step [[] #{(vec mouse)}] mouse)))))))
8ffc3033746ecc0ca9613f3a5b266ed91d9882e7fa0c68ce9f66e6cfe64b80c8
nikita-volkov/rebase
Join.hs
module Rebase.Data.Bifunctor.Join ( module Data.Bifunctor.Join ) where import Data.Bifunctor.Join
null
https://raw.githubusercontent.com/nikita-volkov/rebase/7c77a0443e80bdffd4488a4239628177cac0761b/library/Rebase/Data/Bifunctor/Join.hs
haskell
module Rebase.Data.Bifunctor.Join ( module Data.Bifunctor.Join ) where import Data.Bifunctor.Join
483be81d6313ab4ac75324ca1055f58c9e89fefe2ac723769483e10877acd898
willijar/LENS
simple-aggregation.lisp
;; SImple Aggregation application for WSN Copyright ( C ) 2014 Dr. Author : Dr. < > ;; Keywords: ;;; Copying: This file is part of Lisp Educational Network Simulator ( LENS ) ;; This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , or ;; (at your option) any later version. ;; LENS is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. You should have received a copy of the GNU General Public License ;; along with this program. If not, see </>. ;;; Commentary: ;; This is an example of sensor reading aggregation. ;; The aggregated value is maximum of its sensor reading and received ;; sensor reading from nodes further away (at higher level) in ring routing. ;;; Code: (in-package :lens.wsn) (defclass simple-aggregation (application) ((header-overhead :initform 5) (payload-overhead :initform 100) (priority :parameter t :initform 1 :reader priority :initarg :priority) (sink-network-address :parameter t :type fixnum :reader sink-network-address) (sample-interval :parameter t :type time-type :initform 1) ;; timers (request-sample :type timer-message :initform (make-instance 'timer-message)) (send-aggregated-value :type timer-message :initform (make-instance 'timer-message)) ;; implementatio values (waiting-time-for-lower-level-data :type time-type :initform 0d0) (last-sensed-value :type real :initform 0.0) (aggregated-value :type real :initform 0.0)) (:metaclass module-class) (:documentation "Application providing an example of sensor reading aggregation with [[multipath-rings]] routing. The aggregated value is maximum of its sensor reading and received sensor reading from nodes further away (at higher level) in [[multipath-rings]] routing.")) (defmethod startup((instance simple-aggregation)) (call-next-method) (set-timer instance 'request-sample 0)) (defmethod handle-timer ((instance simple-aggregation) (timer (eql 'request-sample))) (sensor-request instance) (set-timer instance 'request-sample (slot-value instance 'sample-interval))) (defmethod handle-timer ((instance simple-aggregation) (timer (eql 'send-aggregated-value))) (to-network instance (make-instance 'application-packet :payload (slot-value instance 'aggregated-value)) 'application)) (defmethod handle-sensor-reading((instance simple-aggregation) (value real)) (with-slots(last-sensed-value aggregated-value) instance (setf last-sensed-value value aggregated-value (max aggregated-value value)))) (defmethod handle-message ((instance simple-aggregation) (pkt network-control-message)) (let ((argument (argument pkt)) (command (command pkt))) (when (member command '(lens.wsn.routing.multipath-rings::tree-level-updated lens.wsn.routing.multipath-rings::connected-to-tree)) (with-slots(routing-level waiting-time-for-lower-level-data sample-interval) instance (setf routing-level (lens.wsn.routing.multipath-rings::mprings-sink-level argument)) (setf waiting-time-for-lower-level-data (* sample-interval (expt 2 routing-level))) (tracelog "Routing level ~D" routing-level) (set-timer instance 'send-aggregated-value waiting-time-for-lower-level-data)))))
null
https://raw.githubusercontent.com/willijar/LENS/646bc4ca5d4add3fa7e0728f14128e96240a9f36/networks/wsn/application/simple-aggregation.lisp
lisp
SImple Aggregation application for WSN Keywords: Copying: This program is free software: you can redistribute it and/or modify (at your option) any later version. LENS is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. along with this program. If not, see </>. Commentary: This is an example of sensor reading aggregation. The aggregated value is maximum of its sensor reading and received sensor reading from nodes further away (at higher level) in ring routing. Code: timers implementatio values
Copyright ( C ) 2014 Dr. Author : Dr. < > This file is part of Lisp Educational Network Simulator ( LENS ) 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 (in-package :lens.wsn) (defclass simple-aggregation (application) ((header-overhead :initform 5) (payload-overhead :initform 100) (priority :parameter t :initform 1 :reader priority :initarg :priority) (sink-network-address :parameter t :type fixnum :reader sink-network-address) (sample-interval :parameter t :type time-type :initform 1) (request-sample :type timer-message :initform (make-instance 'timer-message)) (send-aggregated-value :type timer-message :initform (make-instance 'timer-message)) (waiting-time-for-lower-level-data :type time-type :initform 0d0) (last-sensed-value :type real :initform 0.0) (aggregated-value :type real :initform 0.0)) (:metaclass module-class) (:documentation "Application providing an example of sensor reading aggregation with [[multipath-rings]] routing. The aggregated value is maximum of its sensor reading and received sensor reading from nodes further away (at higher level) in [[multipath-rings]] routing.")) (defmethod startup((instance simple-aggregation)) (call-next-method) (set-timer instance 'request-sample 0)) (defmethod handle-timer ((instance simple-aggregation) (timer (eql 'request-sample))) (sensor-request instance) (set-timer instance 'request-sample (slot-value instance 'sample-interval))) (defmethod handle-timer ((instance simple-aggregation) (timer (eql 'send-aggregated-value))) (to-network instance (make-instance 'application-packet :payload (slot-value instance 'aggregated-value)) 'application)) (defmethod handle-sensor-reading((instance simple-aggregation) (value real)) (with-slots(last-sensed-value aggregated-value) instance (setf last-sensed-value value aggregated-value (max aggregated-value value)))) (defmethod handle-message ((instance simple-aggregation) (pkt network-control-message)) (let ((argument (argument pkt)) (command (command pkt))) (when (member command '(lens.wsn.routing.multipath-rings::tree-level-updated lens.wsn.routing.multipath-rings::connected-to-tree)) (with-slots(routing-level waiting-time-for-lower-level-data sample-interval) instance (setf routing-level (lens.wsn.routing.multipath-rings::mprings-sink-level argument)) (setf waiting-time-for-lower-level-data (* sample-interval (expt 2 routing-level))) (tracelog "Routing level ~D" routing-level) (set-timer instance 'send-aggregated-value waiting-time-for-lower-level-data)))))
519f3d5ef47b047e4ab0a4daaa73cf8e24313a64dafb43835e99e06488403551
EFanZh/EOPL-Exercises
exercise-7.28.rkt
#lang eopl Exercise 7.28 [ ★ ★ ] Our inferencer is very useful , but it is not powerful enough to allow the programmer to define ;; procedures that are polymorphic, like the polymorphic primitives pair or cons, which can be used at many types. For ;; example, our inferencer would reject the program ;; ;; let f = proc (x : ?) x ;; in if (f zero?(0)) ;; then (f 11) ;; else (f 22) ;; ;; even though its execution is safe, because f is used both at type (bool -> bool) and at type (int -> int). Since the inferencer of this section is allowed to find at most one type for f , it will reject this program . ;; ;; For a more realistic example, one would like to write programs like ;; ;; letrec ;; ? map (f : ?) = ;; letrec ? foo ( x : ? ) = if ) ;; then emptylist ;; else cons((f car(x)), ;; ((map f) cdr(x))) ;; in foo in ;; ? even (y : ?) = if zero?(y) ;; then zero?(0) else if ) ) ;; then zero?(1) ;; else (even -(y,2)) in proc(x : int)-(x,1 ) ) cons(3,cons(5,emptylist ) ) ) , ;; ((map even) cons(3,cons(5,emptylist ) ) ) ) ;; ;; This expression uses map twice, once producing a list of ints and once producing a list of bools. Therefore it needs two different types for the two uses . Since the inferencer of this section will find at most one type for map , it ;; will detect the clash between int and bool and reject the program. ;; One way to avoid this problem is to allow polymorphic values to be introduced only by let , and then to treat ;; (let-exp var e1 e2) differently from (call-exp (proc-exp var e2) e1) for type-checking purposes. ;; ;; Add polymorphic bindings to the inferencer by treating (let-exp var e1 e2) like the expression obtained by ;; substituting e1 for each free occurrence of var in e2. Then, from the point of view of the inferencer, there are many ;; different copies of e1 in the body of the let, so they can have different types, and the programs above will be ;; accepted. ;; Grammar. (define the-lexical-spec '([whitespace (whitespace) skip] [comment ("%" (arbno (not #\newline))) skip] [identifier (letter (arbno (or letter digit "_" "-" "?"))) symbol] [number (digit (arbno digit)) number] [number ("-" digit (arbno digit)) number])) (define the-grammar '([program (expression) a-program] [expression (number) const-exp] [expression ("-" "(" expression "," expression ")") diff-exp] [expression ("zero?" "(" expression ")") zero?-exp] [expression ("if" expression "then" expression "else" expression) if-exp] [expression (identifier) var-exp] [expression ("let" identifier "=" expression "in" expression) let-exp] [expression ("proc" "(" identifier ":" optional-type ")" expression) proc-exp] [expression ("(" expression expression ")") call-exp] [expression ("letrec" optional-type identifier "(" identifier ":" optional-type ")" "=" expression "in" expression) letrec-exp] [expression ("pair" "(" expression "," expression ")") pair-exp] [expression ("unpair" identifier identifier "=" expression "in" expression) unpair-exp] [expression ("list" "(" expression (arbno "," expression) ")") list-exp] [expression ("cons" "(" expression "," expression ")") cons-exp] [expression ("null?" "(" expression ")") null-exp] [expression ("emptylist") emptylist-exp] [expression ("car" "(" expression ")") car-exp] [expression ("cdr" "(" expression ")") cdr-exp] [optional-type ("?") no-type] [optional-type (type) a-type] [type ("int") int-type] [type ("bool") bool-type] [type ("(" type "->" type ")") proc-type] [type ("pairof" type "*" type) pair-type] [type ("listof" type) list-type] [type ("%tvar-type" number) tvar-type])) (sllgen:make-define-datatypes the-lexical-spec the-grammar) (define scan&parse (sllgen:make-string-parser the-lexical-spec the-grammar)) (define proc-type? (lambda (ty) (cases type ty [proc-type (t1 t2) #t] [else #f]))) (define pair-type? (lambda (ty) (cases type ty [pair-type (t1 t2) #t] [else #f]))) (define list-type? (lambda (ty) (cases type ty [list-type (t1) #t] [else #f]))) (define tvar-type? (lambda (ty) (cases type ty [tvar-type (serial-number) #t] [else #f]))) (define proc-type->arg-type (lambda (ty) (cases type ty [proc-type (arg-type result-type) arg-type] [else (eopl:error 'proc-type->arg-type "Not a proc type: ~s" ty)]))) (define proc-type->result-type (lambda (ty) (cases type ty [proc-type (arg-type result-type) result-type] [else (eopl:error 'proc-type->result-types "Not a proc type: ~s" ty)]))) (define pair-type->first-type (lambda (ty) (cases type ty [pair-type (ty1 ty2) ty1] [else (eopl:error 'pair-type->first-type "Not a pair type: ~s" ty)]))) (define pair-type->second-type (lambda (ty) (cases type ty [pair-type (ty1 ty2) ty2] [else (eopl:error 'pair-type->second-type "Not a pair type: ~s" ty)]))) (define list-type->item-type (lambda (ty) (cases type ty [list-type (ty1) ty1] [else (eopl:error 'list-type->item-type "Not a list type: ~s" ty)]))) (define type-to-external-form (lambda (ty) (cases type ty [int-type () 'int] [bool-type () 'bool] [proc-type (arg-type result-type) (list (type-to-external-form arg-type) '-> (type-to-external-form result-type))] [pair-type (ty1 ty2) (list 'pairof (type-to-external-form ty1) '* (type-to-external-form ty2))] [list-type (ty) (list 'listof (type-to-external-form ty))] [tvar-type (serial-number) (string->symbol (string-append "tvar" (number->string serial-number)))]))) ;; Data structures - expressed values. (define-datatype proc proc? [procedure [bvar symbol?] [body expression?] [env environment?]]) (define-datatype expval expval? [num-val [value number?]] [bool-val [boolean boolean?]] [proc-val [proc proc?]] [pair-val [val1 expval?] [val2 expval?]] [emptylist-val] [list-val [head expval?] [tail expval?]]) (define expval-extractor-error (lambda (variant value) (eopl:error 'expval-extractors "Looking for a ~s, found ~s" variant value))) (define expval->num (lambda (v) (cases expval v [num-val (num) num] [else (expval-extractor-error 'num v)]))) (define expval->bool (lambda (v) (cases expval v [bool-val (bool) bool] [else (expval-extractor-error 'bool v)]))) (define expval->proc (lambda (v) (cases expval v [proc-val (proc) proc] [else (expval-extractor-error 'proc v)]))) (define expval->pair (lambda (v f) (cases expval v [pair-val (val1 val2) (f val1 val2)] [else (expval-extractor-error 'pair v)]))) (define expval->list (lambda (v f) (cases expval v [list-val (head tail) (f head tail)] [else (expval-extractor-error 'list v)]))) ;; Data structures - environment. (define-datatype environment environment? [empty-env] [extend-env [bvar symbol?] [bval expval?] [saved-env environment?]] [extend-env-rec [p-name symbol?] [b-var symbol?] [p-body expression?] [saved-env environment?]]) (define apply-env (lambda (env search-sym) (cases environment env [empty-env () (eopl:error 'apply-env "No binding for ~s" search-sym)] [extend-env (bvar bval saved-env) (if (eqv? search-sym bvar) bval (apply-env saved-env search-sym))] [extend-env-rec (p-name b-var p-body saved-env) (if (eqv? search-sym p-name) (proc-val (procedure b-var p-body env)) (apply-env saved-env search-sym))]))) ;; Data structures - type environment. (define-datatype type-environment type-environment? [empty-tenv-record] [extended-tenv-record [sym symbol?] [type type?] [tenv type-environment?]] [extended-tenv-delayed-record [sym symbol?] [f procedure?] [tenv type-environment?]]) (define empty-tenv empty-tenv-record) (define extend-tenv extended-tenv-record) (define extend-tenv-delayed extended-tenv-delayed-record) (define apply-tenv (lambda (tenv sym) (cases type-environment tenv [empty-tenv-record () (eopl:error 'apply-tenv "Unbound variable ~s" sym)] [extended-tenv-record (sym1 val1 old-env) (if (eqv? sym sym1) val1 (apply-tenv old-env sym))] [extended-tenv-delayed-record (sym1 f old-env) (if (eqv? sym sym1) f (apply-tenv old-env sym))]))) ;; Data structures - substitution. (define pair-of (lambda (pred1 pred2) (lambda (val) (and (pair? val) (pred1 (car val)) (pred2 (cdr val)))))) (define substitution? (list-of (pair-of tvar-type? type?))) (define empty-subst (lambda () '())) (define apply-one-subst (lambda (ty0 tvar ty1) (cases type ty0 [int-type () (int-type)] [bool-type () (bool-type)] [proc-type (arg-type result-type) (proc-type (apply-one-subst arg-type tvar ty1) (apply-one-subst result-type tvar ty1))] [pair-type (left-ty right-ty) (pair-type (apply-one-subst tvar left-ty) (apply-one-subst tvar right-ty))] [list-type (ty) (list-type (apply-one-subst ty tvar ty1))] [tvar-type (sn) (if (equal? ty0 tvar) ty1 ty0)]))) (define extend-subst (lambda (subst tvar ty) (cons (cons tvar ty) (map (lambda (p) (let ([oldlhs (car p)] [oldrhs (cdr p)]) (cons oldlhs (apply-one-subst oldrhs tvar ty)))) subst)))) (define apply-subst-to-type (lambda (ty subst) (cases type ty [int-type () (int-type)] [bool-type () (bool-type)] [proc-type (t1 t2) (proc-type (apply-subst-to-type t1 subst) (apply-subst-to-type t2 subst))] [pair-type (left-ty right-ty) (pair-type (apply-subst-to-type left-ty subst) (apply-subst-to-type right-ty subst))] [list-type (ty1) (list-type (apply-subst-to-type ty1 subst))] [tvar-type (sn) (let ([tmp (assoc ty subst)]) (if tmp (cdr tmp) ty))]))) ;; Data structures - answer. (define-datatype answer answer? [an-answer [type type?] [subst substitution?]]) Unifier . (define no-occurrence? (lambda (tvar ty) (cases type ty [int-type () #t] [bool-type () #t] [proc-type (arg-type result-type) (and (no-occurrence? tvar arg-type) (no-occurrence? tvar result-type))] [pair-type (left-ty right-ty) (and (no-occurrence? tvar left-ty) (no-occurrence? tvar right-ty))] [list-type (ty1) (no-occurrence? tvar ty1)] [tvar-type (serial-number) (not (equal? tvar ty))]))) (define report-no-occurrence-violation (lambda (ty1 ty2 exp) (eopl:error 'check-no-occurence! "Can't unify: type variable ~s occurs in type ~s in expression ~s~%" (type-to-external-form ty1) (type-to-external-form ty2) exp))) (define report-unification-failure (lambda (ty1 ty2 exp) (eopl:error 'unification-failure "Type mismatch: ~s doesn't match ~s in ~s~%" (type-to-external-form ty1) (type-to-external-form ty2) exp))) (define unifier (lambda (ty1 ty2 subst exp) (let ([ty1 (apply-subst-to-type ty1 subst)] [ty2 (apply-subst-to-type ty2 subst)]) (cond [(equal? ty1 ty2) subst] [(tvar-type? ty1) (if (no-occurrence? ty1 ty2) (extend-subst subst ty1 ty2) (report-no-occurrence-violation ty1 ty2 exp))] [(tvar-type? ty2) (if (no-occurrence? ty2 ty1) (extend-subst subst ty2 ty1) (report-no-occurrence-violation ty2 ty1 exp))] [(and (proc-type? ty1) (proc-type? ty2)) (let ([subst (unifier (proc-type->arg-type ty1) (proc-type->arg-type ty2) subst exp)]) (let ([subst (unifier (proc-type->result-type ty1) (proc-type->result-type ty2) subst exp)]) subst))] [(and (pair-type? ty1) (pair-type? ty2)) (let ([subst (unifier (pair-type->first-type ty1) (pair-type->first-type ty2) subst exp)]) (let ([subst (unifier (pair-type->second-type ty1) (pair-type->second-type ty2) subst exp)]) subst))] [(and (list-type? ty1) (list-type? ty2)) (unifier (list-type->item-type ty1) (list-type->item-type ty2) subst exp)] [else (report-unification-failure ty1 ty2 exp)])))) ;; Inferrer. (define sn 'uninitialized) (define fresh-tvar-type (let ([sn 0]) (lambda () (set! sn (+ sn 1)) (tvar-type sn)))) (define otype->type (lambda (otype) (cases optional-type otype [no-type () (fresh-tvar-type)] [a-type (ty) ty]))) (define type-of (lambda (exp tenv subst) (cases expression exp [const-exp (num) (an-answer (int-type) subst)] [zero?-exp (exp1) (cases answer (type-of exp1 tenv subst) [an-answer (type1 subst1) (let ([subst2 (unifier type1 (int-type) subst1 exp)]) (an-answer (bool-type) subst2))])] [diff-exp (exp1 exp2) (cases answer (type-of exp1 tenv subst) [an-answer (type1 subst1) (let ([subst1 (unifier type1 (int-type) subst1 exp1)]) (cases answer (type-of exp2 tenv subst1) [an-answer (type2 subst2) (let ([subst2 (unifier type2 (int-type) subst2 exp2)]) (an-answer (int-type) subst2))]))])] [if-exp (exp1 exp2 exp3) (cases answer (type-of exp1 tenv subst) [an-answer (ty1 subst) (let ([subst (unifier ty1 (bool-type) subst exp1)]) (cases answer (type-of exp2 tenv subst) [an-answer (ty2 subst) (cases answer (type-of exp3 tenv subst) [an-answer (ty3 subst) (let ([subst (unifier ty2 ty3 subst exp)]) (an-answer ty2 subst))])]))])] [var-exp (var) (let ([var-type (apply-tenv tenv var)]) (if (type? var-type) (an-answer var-type subst) (var-type subst)))] [let-exp (var exp1 body) (type-of exp1 tenv subst) ;; Make sure exp1 is checked. (type-of body (extend-tenv-delayed var (lambda (subst) (type-of exp1 tenv subst)) tenv) subst)] [proc-exp (var otype body) (let ([arg-type (otype->type otype)]) (cases answer (type-of body (extend-tenv var arg-type tenv) subst) [an-answer (result-type subst) (an-answer (proc-type arg-type result-type) subst)]))] [call-exp (rator rand) (let ([result-type (fresh-tvar-type)]) (cases answer (type-of rator tenv subst) [an-answer (rator-type subst) (cases answer (type-of rand tenv subst) [an-answer (rand-type subst) (let ([subst (unifier rator-type (proc-type rand-type result-type) subst exp)]) (an-answer result-type subst))])]))] [letrec-exp (proc-result-otype proc-name bvar proc-arg-otype proc-body letrec-body) (define check-proc (lambda (subst) (let* ([proc-result-type (otype->type proc-result-otype)] [proc-arg-type (otype->type proc-arg-otype)] [proc-type1 (proc-type proc-arg-type proc-result-type)]) (cases answer (type-of proc-body (extend-tenv bvar proc-arg-type (extend-tenv proc-name proc-type1 tenv)) subst) [an-answer (proc-body-type subst) (let ([subst (unifier proc-body-type proc-result-type subst proc-body)]) (an-answer proc-type1 subst))])))) (check-proc subst) ;; Make sure proc-body is checked. (type-of letrec-body (extend-tenv-delayed proc-name check-proc tenv) subst)] [pair-exp (exp1 exp2) (cases answer (type-of exp1 tenv subst) [an-answer (ty1 subst) (cases answer (type-of exp2 tenv subst) [an-answer (ty2 subst) (an-answer (pair-type ty1 ty2) subst)])])] [unpair-exp (var1 var2 exp1 body) (cases answer (type-of exp1 tenv subst) [an-answer (exp-ty subst) (let ([ty1 (fresh-tvar-type)] [ty2 (fresh-tvar-type)]) (type-of body (extend-tenv var2 ty2 (extend-tenv var1 ty1 tenv)) (unifier (pair-type ty1 ty2) exp-ty subst exp1)))])] [list-exp (exp1 exps) (cases answer (type-of exp1 tenv subst) [an-answer (ty1 subst) (let loop ([subst subst] [exps exps]) (if (null? exps) (an-answer (list-type ty1) subst) (let ([exp2 (car exps)]) (cases answer (type-of exp2 tenv subst) [an-answer (ty2 subst) (loop (unifier ty1 ty2 subst exp2) (cdr exps))]))))])] [cons-exp (exp1 exp2) (cases answer (type-of exp1 tenv subst) [an-answer (ty1 subst) (cases answer (type-of exp2 tenv subst) [an-answer (ty2 subst) (an-answer ty2 (unifier (list-type ty1) ty2 subst exp2))])])] [null-exp (exp1) (cases answer (type-of exp1 tenv subst) [an-answer (ty1 subst) (an-answer (bool-type) (unifier (list-type (fresh-tvar-type)) ty1 subst exp1))])] [emptylist-exp () (an-answer (list-type (fresh-tvar-type)) subst)] [car-exp (exp1) (cases answer (type-of exp1 tenv subst) [an-answer (ty1 subst) (let ([ty2 (fresh-tvar-type)]) (an-answer ty2 (unifier ty1 (list-type ty2) subst exp1)))])] [cdr-exp (exp1) (cases answer (type-of exp1 tenv subst) [an-answer (ty1 subst) (let ([ty2 (fresh-tvar-type)]) (an-answer ty1 (unifier ty1 (list-type ty2) subst exp1)))])]))) (define type-of-program (lambda (pgm) (cases program pgm [a-program (exp1) (cases answer (type-of exp1 (empty-tenv) (empty-subst)) [an-answer (ty subst) (apply-subst-to-type ty subst)])]))) ;; Interpreter. (define apply-procedure (lambda (proc1 arg) (cases proc proc1 [procedure (var body saved-env) (value-of body (extend-env var arg saved-env))]))) (define value-of (lambda (exp env) (cases expression exp [const-exp (num) (num-val num)] [var-exp (var) (apply-env env var)] [diff-exp (exp1 exp2) (let ([val1 (expval->num (value-of exp1 env))] [val2 (expval->num (value-of exp2 env))]) (num-val (- val1 val2)))] [zero?-exp (exp1) (let ([val1 (expval->num (value-of exp1 env))]) (if (zero? val1) (bool-val #t) (bool-val #f)))] [if-exp (exp0 exp1 exp2) (if (expval->bool (value-of exp0 env)) (value-of exp1 env) (value-of exp2 env))] [let-exp (var exp1 body) (let ([val (value-of exp1 env)]) (value-of body (extend-env var val env)))] [proc-exp (bvar ty body) (proc-val (procedure bvar body env))] [call-exp (rator rand) (let ([proc (expval->proc (value-of rator env))] [arg (value-of rand env)]) (apply-procedure proc arg))] [letrec-exp (ty1 p-name b-var ty2 p-body letrec-body) (value-of letrec-body (extend-env-rec p-name b-var p-body env))] [pair-exp (exp1 exp2) (pair-val (value-of exp1 env) (value-of exp2 env))] [unpair-exp (var1 var2 exp1 body) (let ([val (value-of exp1 env)]) (expval->pair val (lambda (val1 val2) (value-of body (extend-env var2 val2 (extend-env var1 val1 env))))))] [list-exp (exp1 exps) (let loop1 ([acc '()] [exp1 exp1] [exps exps]) (if (null? exps) (let loop2 ([acc-list (list-val (value-of exp1 env) (emptylist-val))] [vals acc]) (if (null? vals) acc-list (loop2 (list-val (car vals) acc-list) (cdr vals)))) (loop1 (cons (value-of exp1 env) acc) (car exps) (cdr exps))))] [cons-exp (exp1 exp2) (list-val (value-of exp1 env) (value-of exp2 env))] [null-exp (exp1) (cases expval (value-of exp1 env) [emptylist-val () (bool-val #t)] [else (bool-val #f)])] [emptylist-exp () (emptylist-val)] [car-exp (exp1) (expval->list (value-of exp1 env) (lambda (head tail) head))] [cdr-exp (exp1) (expval->list (value-of exp1 env) (lambda (head tail) tail))]))) (define value-of-program (lambda (pgm) (cases program pgm [a-program (body) (value-of body (empty-env))]))) Interface . (define check (lambda (string) (type-to-external-form (type-of-program (scan&parse string))))) (define run (lambda (string) (value-of-program (scan&parse string)))) (provide bool-val check emptylist-val list-val num-val run)
null
https://raw.githubusercontent.com/EFanZh/EOPL-Exercises/11667f1e84a1a3e300c2182630b56db3e3d9246a/solutions/exercise-7.28.rkt
racket
procedures that are polymorphic, like the polymorphic primitives pair or cons, which can be used at many types. For example, our inferencer would reject the program let f = proc (x : ?) x in if (f zero?(0)) then (f 11) else (f 22) even though its execution is safe, because f is used both at type (bool -> bool) and at type (int -> int). Since the For a more realistic example, one would like to write programs like letrec ? map (f : ?) = letrec then emptylist else cons((f car(x)), ((map f) cdr(x))) in foo ? even (y : ?) = if zero?(y) then zero?(0) then zero?(1) else (even -(y,2)) ((map even) This expression uses map twice, once producing a list of ints and once producing a list of bools. Therefore it needs will detect the clash between int and bool and reject the program. (let-exp var e1 e2) differently from (call-exp (proc-exp var e2) e1) for type-checking purposes. Add polymorphic bindings to the inferencer by treating (let-exp var e1 e2) like the expression obtained by substituting e1 for each free occurrence of var in e2. Then, from the point of view of the inferencer, there are many different copies of e1 in the body of the let, so they can have different types, and the programs above will be accepted. Grammar. Data structures - expressed values. Data structures - environment. Data structures - type environment. Data structures - substitution. Data structures - answer. Inferrer. Make sure exp1 is checked. Make sure proc-body is checked. Interpreter.
#lang eopl Exercise 7.28 [ ★ ★ ] Our inferencer is very useful , but it is not powerful enough to allow the programmer to define inferencer of this section is allowed to find at most one type for f , it will reject this program . ? foo ( x : ? ) = if ) in else if ) ) in proc(x : int)-(x,1 ) ) cons(3,cons(5,emptylist ) ) ) , cons(3,cons(5,emptylist ) ) ) ) two different types for the two uses . Since the inferencer of this section will find at most one type for map , it One way to avoid this problem is to allow polymorphic values to be introduced only by let , and then to treat (define the-lexical-spec '([whitespace (whitespace) skip] [comment ("%" (arbno (not #\newline))) skip] [identifier (letter (arbno (or letter digit "_" "-" "?"))) symbol] [number (digit (arbno digit)) number] [number ("-" digit (arbno digit)) number])) (define the-grammar '([program (expression) a-program] [expression (number) const-exp] [expression ("-" "(" expression "," expression ")") diff-exp] [expression ("zero?" "(" expression ")") zero?-exp] [expression ("if" expression "then" expression "else" expression) if-exp] [expression (identifier) var-exp] [expression ("let" identifier "=" expression "in" expression) let-exp] [expression ("proc" "(" identifier ":" optional-type ")" expression) proc-exp] [expression ("(" expression expression ")") call-exp] [expression ("letrec" optional-type identifier "(" identifier ":" optional-type ")" "=" expression "in" expression) letrec-exp] [expression ("pair" "(" expression "," expression ")") pair-exp] [expression ("unpair" identifier identifier "=" expression "in" expression) unpair-exp] [expression ("list" "(" expression (arbno "," expression) ")") list-exp] [expression ("cons" "(" expression "," expression ")") cons-exp] [expression ("null?" "(" expression ")") null-exp] [expression ("emptylist") emptylist-exp] [expression ("car" "(" expression ")") car-exp] [expression ("cdr" "(" expression ")") cdr-exp] [optional-type ("?") no-type] [optional-type (type) a-type] [type ("int") int-type] [type ("bool") bool-type] [type ("(" type "->" type ")") proc-type] [type ("pairof" type "*" type) pair-type] [type ("listof" type) list-type] [type ("%tvar-type" number) tvar-type])) (sllgen:make-define-datatypes the-lexical-spec the-grammar) (define scan&parse (sllgen:make-string-parser the-lexical-spec the-grammar)) (define proc-type? (lambda (ty) (cases type ty [proc-type (t1 t2) #t] [else #f]))) (define pair-type? (lambda (ty) (cases type ty [pair-type (t1 t2) #t] [else #f]))) (define list-type? (lambda (ty) (cases type ty [list-type (t1) #t] [else #f]))) (define tvar-type? (lambda (ty) (cases type ty [tvar-type (serial-number) #t] [else #f]))) (define proc-type->arg-type (lambda (ty) (cases type ty [proc-type (arg-type result-type) arg-type] [else (eopl:error 'proc-type->arg-type "Not a proc type: ~s" ty)]))) (define proc-type->result-type (lambda (ty) (cases type ty [proc-type (arg-type result-type) result-type] [else (eopl:error 'proc-type->result-types "Not a proc type: ~s" ty)]))) (define pair-type->first-type (lambda (ty) (cases type ty [pair-type (ty1 ty2) ty1] [else (eopl:error 'pair-type->first-type "Not a pair type: ~s" ty)]))) (define pair-type->second-type (lambda (ty) (cases type ty [pair-type (ty1 ty2) ty2] [else (eopl:error 'pair-type->second-type "Not a pair type: ~s" ty)]))) (define list-type->item-type (lambda (ty) (cases type ty [list-type (ty1) ty1] [else (eopl:error 'list-type->item-type "Not a list type: ~s" ty)]))) (define type-to-external-form (lambda (ty) (cases type ty [int-type () 'int] [bool-type () 'bool] [proc-type (arg-type result-type) (list (type-to-external-form arg-type) '-> (type-to-external-form result-type))] [pair-type (ty1 ty2) (list 'pairof (type-to-external-form ty1) '* (type-to-external-form ty2))] [list-type (ty) (list 'listof (type-to-external-form ty))] [tvar-type (serial-number) (string->symbol (string-append "tvar" (number->string serial-number)))]))) (define-datatype proc proc? [procedure [bvar symbol?] [body expression?] [env environment?]]) (define-datatype expval expval? [num-val [value number?]] [bool-val [boolean boolean?]] [proc-val [proc proc?]] [pair-val [val1 expval?] [val2 expval?]] [emptylist-val] [list-val [head expval?] [tail expval?]]) (define expval-extractor-error (lambda (variant value) (eopl:error 'expval-extractors "Looking for a ~s, found ~s" variant value))) (define expval->num (lambda (v) (cases expval v [num-val (num) num] [else (expval-extractor-error 'num v)]))) (define expval->bool (lambda (v) (cases expval v [bool-val (bool) bool] [else (expval-extractor-error 'bool v)]))) (define expval->proc (lambda (v) (cases expval v [proc-val (proc) proc] [else (expval-extractor-error 'proc v)]))) (define expval->pair (lambda (v f) (cases expval v [pair-val (val1 val2) (f val1 val2)] [else (expval-extractor-error 'pair v)]))) (define expval->list (lambda (v f) (cases expval v [list-val (head tail) (f head tail)] [else (expval-extractor-error 'list v)]))) (define-datatype environment environment? [empty-env] [extend-env [bvar symbol?] [bval expval?] [saved-env environment?]] [extend-env-rec [p-name symbol?] [b-var symbol?] [p-body expression?] [saved-env environment?]]) (define apply-env (lambda (env search-sym) (cases environment env [empty-env () (eopl:error 'apply-env "No binding for ~s" search-sym)] [extend-env (bvar bval saved-env) (if (eqv? search-sym bvar) bval (apply-env saved-env search-sym))] [extend-env-rec (p-name b-var p-body saved-env) (if (eqv? search-sym p-name) (proc-val (procedure b-var p-body env)) (apply-env saved-env search-sym))]))) (define-datatype type-environment type-environment? [empty-tenv-record] [extended-tenv-record [sym symbol?] [type type?] [tenv type-environment?]] [extended-tenv-delayed-record [sym symbol?] [f procedure?] [tenv type-environment?]]) (define empty-tenv empty-tenv-record) (define extend-tenv extended-tenv-record) (define extend-tenv-delayed extended-tenv-delayed-record) (define apply-tenv (lambda (tenv sym) (cases type-environment tenv [empty-tenv-record () (eopl:error 'apply-tenv "Unbound variable ~s" sym)] [extended-tenv-record (sym1 val1 old-env) (if (eqv? sym sym1) val1 (apply-tenv old-env sym))] [extended-tenv-delayed-record (sym1 f old-env) (if (eqv? sym sym1) f (apply-tenv old-env sym))]))) (define pair-of (lambda (pred1 pred2) (lambda (val) (and (pair? val) (pred1 (car val)) (pred2 (cdr val)))))) (define substitution? (list-of (pair-of tvar-type? type?))) (define empty-subst (lambda () '())) (define apply-one-subst (lambda (ty0 tvar ty1) (cases type ty0 [int-type () (int-type)] [bool-type () (bool-type)] [proc-type (arg-type result-type) (proc-type (apply-one-subst arg-type tvar ty1) (apply-one-subst result-type tvar ty1))] [pair-type (left-ty right-ty) (pair-type (apply-one-subst tvar left-ty) (apply-one-subst tvar right-ty))] [list-type (ty) (list-type (apply-one-subst ty tvar ty1))] [tvar-type (sn) (if (equal? ty0 tvar) ty1 ty0)]))) (define extend-subst (lambda (subst tvar ty) (cons (cons tvar ty) (map (lambda (p) (let ([oldlhs (car p)] [oldrhs (cdr p)]) (cons oldlhs (apply-one-subst oldrhs tvar ty)))) subst)))) (define apply-subst-to-type (lambda (ty subst) (cases type ty [int-type () (int-type)] [bool-type () (bool-type)] [proc-type (t1 t2) (proc-type (apply-subst-to-type t1 subst) (apply-subst-to-type t2 subst))] [pair-type (left-ty right-ty) (pair-type (apply-subst-to-type left-ty subst) (apply-subst-to-type right-ty subst))] [list-type (ty1) (list-type (apply-subst-to-type ty1 subst))] [tvar-type (sn) (let ([tmp (assoc ty subst)]) (if tmp (cdr tmp) ty))]))) (define-datatype answer answer? [an-answer [type type?] [subst substitution?]]) Unifier . (define no-occurrence? (lambda (tvar ty) (cases type ty [int-type () #t] [bool-type () #t] [proc-type (arg-type result-type) (and (no-occurrence? tvar arg-type) (no-occurrence? tvar result-type))] [pair-type (left-ty right-ty) (and (no-occurrence? tvar left-ty) (no-occurrence? tvar right-ty))] [list-type (ty1) (no-occurrence? tvar ty1)] [tvar-type (serial-number) (not (equal? tvar ty))]))) (define report-no-occurrence-violation (lambda (ty1 ty2 exp) (eopl:error 'check-no-occurence! "Can't unify: type variable ~s occurs in type ~s in expression ~s~%" (type-to-external-form ty1) (type-to-external-form ty2) exp))) (define report-unification-failure (lambda (ty1 ty2 exp) (eopl:error 'unification-failure "Type mismatch: ~s doesn't match ~s in ~s~%" (type-to-external-form ty1) (type-to-external-form ty2) exp))) (define unifier (lambda (ty1 ty2 subst exp) (let ([ty1 (apply-subst-to-type ty1 subst)] [ty2 (apply-subst-to-type ty2 subst)]) (cond [(equal? ty1 ty2) subst] [(tvar-type? ty1) (if (no-occurrence? ty1 ty2) (extend-subst subst ty1 ty2) (report-no-occurrence-violation ty1 ty2 exp))] [(tvar-type? ty2) (if (no-occurrence? ty2 ty1) (extend-subst subst ty2 ty1) (report-no-occurrence-violation ty2 ty1 exp))] [(and (proc-type? ty1) (proc-type? ty2)) (let ([subst (unifier (proc-type->arg-type ty1) (proc-type->arg-type ty2) subst exp)]) (let ([subst (unifier (proc-type->result-type ty1) (proc-type->result-type ty2) subst exp)]) subst))] [(and (pair-type? ty1) (pair-type? ty2)) (let ([subst (unifier (pair-type->first-type ty1) (pair-type->first-type ty2) subst exp)]) (let ([subst (unifier (pair-type->second-type ty1) (pair-type->second-type ty2) subst exp)]) subst))] [(and (list-type? ty1) (list-type? ty2)) (unifier (list-type->item-type ty1) (list-type->item-type ty2) subst exp)] [else (report-unification-failure ty1 ty2 exp)])))) (define sn 'uninitialized) (define fresh-tvar-type (let ([sn 0]) (lambda () (set! sn (+ sn 1)) (tvar-type sn)))) (define otype->type (lambda (otype) (cases optional-type otype [no-type () (fresh-tvar-type)] [a-type (ty) ty]))) (define type-of (lambda (exp tenv subst) (cases expression exp [const-exp (num) (an-answer (int-type) subst)] [zero?-exp (exp1) (cases answer (type-of exp1 tenv subst) [an-answer (type1 subst1) (let ([subst2 (unifier type1 (int-type) subst1 exp)]) (an-answer (bool-type) subst2))])] [diff-exp (exp1 exp2) (cases answer (type-of exp1 tenv subst) [an-answer (type1 subst1) (let ([subst1 (unifier type1 (int-type) subst1 exp1)]) (cases answer (type-of exp2 tenv subst1) [an-answer (type2 subst2) (let ([subst2 (unifier type2 (int-type) subst2 exp2)]) (an-answer (int-type) subst2))]))])] [if-exp (exp1 exp2 exp3) (cases answer (type-of exp1 tenv subst) [an-answer (ty1 subst) (let ([subst (unifier ty1 (bool-type) subst exp1)]) (cases answer (type-of exp2 tenv subst) [an-answer (ty2 subst) (cases answer (type-of exp3 tenv subst) [an-answer (ty3 subst) (let ([subst (unifier ty2 ty3 subst exp)]) (an-answer ty2 subst))])]))])] [var-exp (var) (let ([var-type (apply-tenv tenv var)]) (if (type? var-type) (an-answer var-type subst) (var-type subst)))] [let-exp (var exp1 body) (type-of body (extend-tenv-delayed var (lambda (subst) (type-of exp1 tenv subst)) tenv) subst)] [proc-exp (var otype body) (let ([arg-type (otype->type otype)]) (cases answer (type-of body (extend-tenv var arg-type tenv) subst) [an-answer (result-type subst) (an-answer (proc-type arg-type result-type) subst)]))] [call-exp (rator rand) (let ([result-type (fresh-tvar-type)]) (cases answer (type-of rator tenv subst) [an-answer (rator-type subst) (cases answer (type-of rand tenv subst) [an-answer (rand-type subst) (let ([subst (unifier rator-type (proc-type rand-type result-type) subst exp)]) (an-answer result-type subst))])]))] [letrec-exp (proc-result-otype proc-name bvar proc-arg-otype proc-body letrec-body) (define check-proc (lambda (subst) (let* ([proc-result-type (otype->type proc-result-otype)] [proc-arg-type (otype->type proc-arg-otype)] [proc-type1 (proc-type proc-arg-type proc-result-type)]) (cases answer (type-of proc-body (extend-tenv bvar proc-arg-type (extend-tenv proc-name proc-type1 tenv)) subst) [an-answer (proc-body-type subst) (let ([subst (unifier proc-body-type proc-result-type subst proc-body)]) (an-answer proc-type1 subst))])))) (type-of letrec-body (extend-tenv-delayed proc-name check-proc tenv) subst)] [pair-exp (exp1 exp2) (cases answer (type-of exp1 tenv subst) [an-answer (ty1 subst) (cases answer (type-of exp2 tenv subst) [an-answer (ty2 subst) (an-answer (pair-type ty1 ty2) subst)])])] [unpair-exp (var1 var2 exp1 body) (cases answer (type-of exp1 tenv subst) [an-answer (exp-ty subst) (let ([ty1 (fresh-tvar-type)] [ty2 (fresh-tvar-type)]) (type-of body (extend-tenv var2 ty2 (extend-tenv var1 ty1 tenv)) (unifier (pair-type ty1 ty2) exp-ty subst exp1)))])] [list-exp (exp1 exps) (cases answer (type-of exp1 tenv subst) [an-answer (ty1 subst) (let loop ([subst subst] [exps exps]) (if (null? exps) (an-answer (list-type ty1) subst) (let ([exp2 (car exps)]) (cases answer (type-of exp2 tenv subst) [an-answer (ty2 subst) (loop (unifier ty1 ty2 subst exp2) (cdr exps))]))))])] [cons-exp (exp1 exp2) (cases answer (type-of exp1 tenv subst) [an-answer (ty1 subst) (cases answer (type-of exp2 tenv subst) [an-answer (ty2 subst) (an-answer ty2 (unifier (list-type ty1) ty2 subst exp2))])])] [null-exp (exp1) (cases answer (type-of exp1 tenv subst) [an-answer (ty1 subst) (an-answer (bool-type) (unifier (list-type (fresh-tvar-type)) ty1 subst exp1))])] [emptylist-exp () (an-answer (list-type (fresh-tvar-type)) subst)] [car-exp (exp1) (cases answer (type-of exp1 tenv subst) [an-answer (ty1 subst) (let ([ty2 (fresh-tvar-type)]) (an-answer ty2 (unifier ty1 (list-type ty2) subst exp1)))])] [cdr-exp (exp1) (cases answer (type-of exp1 tenv subst) [an-answer (ty1 subst) (let ([ty2 (fresh-tvar-type)]) (an-answer ty1 (unifier ty1 (list-type ty2) subst exp1)))])]))) (define type-of-program (lambda (pgm) (cases program pgm [a-program (exp1) (cases answer (type-of exp1 (empty-tenv) (empty-subst)) [an-answer (ty subst) (apply-subst-to-type ty subst)])]))) (define apply-procedure (lambda (proc1 arg) (cases proc proc1 [procedure (var body saved-env) (value-of body (extend-env var arg saved-env))]))) (define value-of (lambda (exp env) (cases expression exp [const-exp (num) (num-val num)] [var-exp (var) (apply-env env var)] [diff-exp (exp1 exp2) (let ([val1 (expval->num (value-of exp1 env))] [val2 (expval->num (value-of exp2 env))]) (num-val (- val1 val2)))] [zero?-exp (exp1) (let ([val1 (expval->num (value-of exp1 env))]) (if (zero? val1) (bool-val #t) (bool-val #f)))] [if-exp (exp0 exp1 exp2) (if (expval->bool (value-of exp0 env)) (value-of exp1 env) (value-of exp2 env))] [let-exp (var exp1 body) (let ([val (value-of exp1 env)]) (value-of body (extend-env var val env)))] [proc-exp (bvar ty body) (proc-val (procedure bvar body env))] [call-exp (rator rand) (let ([proc (expval->proc (value-of rator env))] [arg (value-of rand env)]) (apply-procedure proc arg))] [letrec-exp (ty1 p-name b-var ty2 p-body letrec-body) (value-of letrec-body (extend-env-rec p-name b-var p-body env))] [pair-exp (exp1 exp2) (pair-val (value-of exp1 env) (value-of exp2 env))] [unpair-exp (var1 var2 exp1 body) (let ([val (value-of exp1 env)]) (expval->pair val (lambda (val1 val2) (value-of body (extend-env var2 val2 (extend-env var1 val1 env))))))] [list-exp (exp1 exps) (let loop1 ([acc '()] [exp1 exp1] [exps exps]) (if (null? exps) (let loop2 ([acc-list (list-val (value-of exp1 env) (emptylist-val))] [vals acc]) (if (null? vals) acc-list (loop2 (list-val (car vals) acc-list) (cdr vals)))) (loop1 (cons (value-of exp1 env) acc) (car exps) (cdr exps))))] [cons-exp (exp1 exp2) (list-val (value-of exp1 env) (value-of exp2 env))] [null-exp (exp1) (cases expval (value-of exp1 env) [emptylist-val () (bool-val #t)] [else (bool-val #f)])] [emptylist-exp () (emptylist-val)] [car-exp (exp1) (expval->list (value-of exp1 env) (lambda (head tail) head))] [cdr-exp (exp1) (expval->list (value-of exp1 env) (lambda (head tail) tail))]))) (define value-of-program (lambda (pgm) (cases program pgm [a-program (body) (value-of body (empty-env))]))) Interface . (define check (lambda (string) (type-to-external-form (type-of-program (scan&parse string))))) (define run (lambda (string) (value-of-program (scan&parse string)))) (provide bool-val check emptylist-val list-val num-val run)
8a220b59e0c6e12694b272ccc53b21642c2c90d6989dd37b3de926042d45cbb5
WormBase/wormbase_rest
pseudogene.clj
(ns rest-api.classes.pseudogene (:require [rest-api.classes.pseudogene.widgets.overview :as overview] [rest-api.classes.pseudogene.widgets.feature :as feature] [rest-api.classes.pseudogene.widgets.genetics :as genetics] [rest-api.classes.pseudogene.widgets.reagents :as reagents] [rest-api.classes.pseudogene.widgets.expression :as expression] [rest-api.classes.pseudogene.widgets.sequences :as sequences] [rest-api.classes.pseudogene.widgets.location :as location] [rest-api.classes.gene.expression :as gene-expression] [rest-api.classes.graphview.widget :as graphview] [rest-api.routing :as routing])) (routing/defroutes {:entity-ns "pseudogene" :widget {:overview overview/widget :graphview graphview/widget :feature feature/widget :genetics genetics/widget :reagents reagents/widget :sequences sequences/widget :expression expression/widget :location location/widget } :field {:fpkm_expression_summary_ls gene-expression/fpkm-expression-summary-ls}})
null
https://raw.githubusercontent.com/WormBase/wormbase_rest/e51026f35b87d96260b62ddb5458a81ee911bf3a/src/rest_api/classes/pseudogene.clj
clojure
(ns rest-api.classes.pseudogene (:require [rest-api.classes.pseudogene.widgets.overview :as overview] [rest-api.classes.pseudogene.widgets.feature :as feature] [rest-api.classes.pseudogene.widgets.genetics :as genetics] [rest-api.classes.pseudogene.widgets.reagents :as reagents] [rest-api.classes.pseudogene.widgets.expression :as expression] [rest-api.classes.pseudogene.widgets.sequences :as sequences] [rest-api.classes.pseudogene.widgets.location :as location] [rest-api.classes.gene.expression :as gene-expression] [rest-api.classes.graphview.widget :as graphview] [rest-api.routing :as routing])) (routing/defroutes {:entity-ns "pseudogene" :widget {:overview overview/widget :graphview graphview/widget :feature feature/widget :genetics genetics/widget :reagents reagents/widget :sequences sequences/widget :expression expression/widget :location location/widget } :field {:fpkm_expression_summary_ls gene-expression/fpkm-expression-summary-ls}})
e33cd874da3fbd3b6e9ba792a23972058cdd3000507b5535e2ccf1d63d4e2321
kudelskisecurity/scannerl
master.erl
% the master in the master/slave architecture of scannerl -module(master). -author("Adrien Giner - "). -export([master/1, listen/2]). -include("includes/opts.hrl"). -define(CHECKTO, 3000). % ms -define(ENDTO, 10000). % ms -define(ERLEXT, ".erl"). % that's the range start for TCP communication will be expanded to ? PORTMIN+nb_slaves for the -define(PORTMIN, 11100). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % remote related functions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % this loads all modules for this specific node rem_load_modules(_, []) -> ok; rem_load_modules(Node, [M|Rest]) -> {Mod, Bin, _} = code:get_object_code(M), rpc:call(Node, code, purge, [Mod]), rpc:call(Node, erlang, load_module, [Mod, Bin]), rem_load_modules(Node, Rest). wait_for_slave(Tot, Cnt, Cntlist, _Mods, _Nosafe, _Timeout) when Cnt == Tot -> case cntlist:count(Cntlist) of 0 -> print(error, "no viable host found"), {error, Cntlist}; _ -> {ok, Cntlist} end; wait_for_slave(Tot, Cnt, Cntlist, Modules, Nosafe, Timeout) -> receive {ok, Node, H, _Name} -> net_kernel:connect_node(Node), rem_load_modules(Node, Modules), % then register master and scannerl on remote rpc:call(Node, global, register_name, [master, global:whereis_name(listener)]), rpc:call(Node, global, register_name, [scannerl, global:whereis_name(scannerl)]), New = cntlist:update_key(Cntlist, H, Node), wait_for_slave(Tot, Cnt+1, New, Modules, Nosafe, Timeout); {error, Reason, H, Name} when Nosafe -> print(warning, io_lib:fwrite("host ~p (name:~p) failed to start: ~p - continue ...", [H, Name, Reason])), New = cntlist:remove_key(Cntlist, H), wait_for_slave(Tot, Cnt+1, New, Modules, Nosafe, Timeout); {error, Reason, H, Name} -> print(error, io_lib:fwrite("unable to start host ~p (name:~p): ~p", [H, Name, Reason])), {error, Cntlist} after Timeout -> print(error, io_lib:fwrite("max timeout (~ps) reached when waiting for slaves (got ~p/~p)", [Timeout / 1000, Cnt, Tot])), {error, Cntlist} end. % start a list of slave start_slave_th([], Mods, Tot, Slaves, _Basename, Nosafe, _Dbg, Timeout) -> wait_for_slave(Tot, 0, Slaves, Mods, Nosafe, 2*Timeout); start_slave_th([H|T], Modules, Cnt, Slaves, Basename, Nosafe, Dbg, Timeout) -> Name = lists:concat([Basename, "-slave-", integer_to_list(Cnt)]), spawn_link(utils_slave, start_link_th, [H, Name, ?PORTMIN, Dbg, self(), Timeout]), start_slave_th(T, Modules, Cnt+1, Slaves, Basename, Nosafe, Dbg, Timeout). % start all slave nodes using process start_slaves(Slaves, Modules, Basename, Nosafe, Dbg, Timeout) -> start_slave_th(cntlist:flattenkeys(Slaves), Modules, 0, Slaves, Basename, Nosafe, Dbg, Timeout). % stop all slave nodes stop_slaves([], _Dbg) -> ok; stop_slaves([H|T], Dbg) -> spawn_link(utils_slave, stop, [H, Dbg]), stop_slaves(T, Dbg). % start a broker on each node start_brokers([], _, _, Agg) -> Agg; start_brokers([H|T], Opts, Cnt, Agg) -> Id = "ID" ++ integer_to_list(Cnt), Pid = spawn_link(H, broker, scan, [Opts#opts{user=Id}]), start_brokers(T, Opts, Cnt+1, Agg ++ [Pid]). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Utilities %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % globally register master as myself register_entry(Pid, Name) -> yes = global:register_name(Name, Pid), global:sync(). % return our hostname my_hostname() -> {ok, Hostname} = inet:gethostname(), Hostname. % randomize a list rnd_list(List) -> [X||{_,X} <- lists:sort([{rand:uniform(), N} || N <- List])]. print(myerror, Msg) -> io:put_chars(standard_error, Msg); print(us, Msg) -> M = io_lib:fwrite("<~s> [M] ~s\n", [utils:get_ts(), Msg]), io:put_chars(standard_error, M); print(error, Msg) -> M = io_lib:fwrite("<~s> [M]>[E] ~s\n", [utils:get_ts(), Msg]), io:put_chars(standard_error, M); print(warning, Msg) -> M = io_lib:fwrite("[WARNING] ~s\n", [Msg]), io:put_chars(standard_error, M); print(info, Msg) -> M = io_lib:fwrite("<~s> [M]>[I] ~s\n", [utils:get_ts(), Msg]), io:put_chars(standard_error, M); print(result, Msg) -> M = io_lib:fwrite("~s\n", [Msg]), io:put_chars(standard_error, M); print(_, _) -> ok. % print timestamp in nice format ts() -> print(us, utils:get_ts()). % pretty print duration duration(Start) -> Duration = calendar:datetime_to_gregorian_seconds(calendar:universal_time()) - Start, DateTime = calendar:gregorian_seconds_to_datetime(Duration), {{_Y,_M,_D}, {H,Min,S}} = DateTime, [H, Min, S]. % get current process queue cnt msg_queue_len() -> {_, Cnt} = erlang:process_info(self(), message_queue_len), Cnt. % get epoch epoch() -> {M, S, _} = os:timestamp(), (M*1000000)+S. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Communication %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % listen for slave's messages listen(TotSlave, Opts) -> rcv_loop(TotSlave, Opts, []), flush_msg(msg_queue_len(), Opts), global:whereis_name(main) ! {quit}. % flush message in the queue flush_msg(0, _) -> ok; flush_msg(_, Opts) -> rcv_loop(0, Opts, []), flush_msg(msg_queue_len(), Opts). % wait for and answer to message(s) rcv_loop(0, _Opts, _Pids) -> ok; rcv_loop(CntSlave, Opts, Pids) -> receive {totchange, New} -> % update the number of nodes (especially for --nosafe) rcv_loop(New, Opts, Pids); {pids, List} -> % update the pids rcv_loop(CntSlave, Opts, List); {progress, _From, Id, Msg} -> % sent by myself (other thread) print(info , io_lib : fwrite("[progress][~p|~s ] ~s " , [ From , I d , Msg ] ) ) , print(info, io_lib:fwrite("[progress][~s] ~s", [Id, Msg])), rcv_loop(CntSlave, Opts, Pids); {info, From, Id, "done"} -> % sent by broker utils:debug(master, io_lib:fwrite("[~p|~s] is done !", [From, Id]), {}, Opts#opts.debugval), rcv_loop(CntSlave-1, Opts, Pids); {info, From, Id, Data} -> % sent by broker print(info, io_lib:fwrite("[~p|~s]: ~s", [From, Id, Data])), rcv_loop(CntSlave, Opts, Pids); {debug, From, Msg} -> % debug message from broker utils:debug_print(From, Msg), rcv_loop(CntSlave, Opts, Pids); {message, {error, Proto, Port, Reason}} -> print(error, io_lib:fwrite("cannot listen on ~s/~p: ~p", [Proto, Port, Reason])), rcv_loop(CntSlave, Opts, Pids); {message, {ok, Protocol, Ip, Port}} -> print(us, io_lib:fwrite("listen on ~s ~s/~p", [Ip, Protocol, Port])), rcv_loop(CntSlave, Opts, Pids); {message, {message, "progress"}} -> print(us, "progress triggered"), trigger_progress(true, Pids), rcv_loop(CntSlave, Opts, Pids); {message, {message, "abort"}} -> % received by the message listener case Pids of [] -> % called at the end of the process print(info, "[!!] cannot cancel, process is terminating"); _ -> print(info, "[!!] send cancel to all slaves"), [X ! {cancel} || X <- Pids] end, rcv_loop(CntSlave, Opts, Pids); _ -> rcv_loop(CntSlave, Opts, Pids) after ?CHECKTO -> rcv_loop(CntSlave, Opts, Pids) end. % send message {progress} to all slaves trigger_progress(false, _) -> ok; trigger_progress(true, Pids) -> print(info, io_lib:fwrite("[progress][M] ~p slave(s)", [length(Pids)])), global:whereis_name(scannerl) ! {progress}, [X ! {progress} || X <- Pids]. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Slave processing %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % get a slave (from a list of string) and add it to a cntlist get_slave([], Agg) -> Agg; get_slave([Entry|T], Agg) -> case string:str(Entry, "*") of 0 -> get_slave(T, cntlist:add(Agg, Entry, 1)); _ -> [Node, Nb] = string:tokens(Entry, "*"), get_slave(T, cntlist:add(Agg, Node, list_to_integer(Nb))) end. % get slaves from a file slaves_from_file(nil) -> {ok, []}; slaves_from_file(Path) -> case utils:read_lines(Path) of {ok, Lines} -> {ok, get_slave(Lines, [])}; {error, Reason} -> {error, Reason} end. % get slaves from CLI and Path get_slaves(Slaves, Path) -> Sl1 = get_slave(Slaves, []), case slaves_from_file(Path) of {ok, Sl2} -> Res = cntlist:merge(lists:flatten(Sl1 ++ Sl2)), case cntlist:count(Res) of 0 -> cntlist:add([], my_hostname(), 1); _ -> Res end; {error, Reason} -> print(myerror, io_lib:fwrite("[ERROR] cannot get slaves from ~p: ~p~n", [Path, Reason])), [] end. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Target processing %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % get a list of stripped lines that represent a target targets_from_file(nil) -> []; targets_from_file(Path) -> case utils:read_lines(Path) of {ok, Lines} -> Lines; {error, Reason} -> print(myerror, io_lib:fwrite("[ERROR] cannot get targets from ~p: ~p~n", [Path, Reason])), [] end. parse ip / and sub - divide in Minrange process_targets([], _, _, _) -> []; process_targets([H|T], Agg, Minrange, Defport) -> case tgt:parse_ip(H, Defport) of {ok, Tgt} -> tgt:minrange(Tgt, Minrange) ++ process_targets(T, Agg, Minrange, Defport); {error, Reason} -> print(myerror, io_lib:fwrite("[ERROR] cannot parse ~p: ~p~n", [H, Reason])), process_targets(T, Agg, Minrange, Defport) end. % parse domains process_domains([], _, _, _) -> []; process_domains([H|T], Agg, Minrange, Defport) -> [tgt:parse_domain(H, Defport)] ++ process_domains(T, Agg, Minrange, Defport). here we distribute by Len the targets to the different % hosts targets_to_nodes([N|[]], Targets, {Start, Len}, Nodes) -> Sub = lists:sublist(Targets, Start, Len), %io:fwrite("sending ~p target(s) to ~p~n", [length(Sub), N]), N ! {targets, Sub}, case Start+Len > length(Targets) of true -> ok; false -> targets_to_nodes_rest(Nodes, Targets, {Start+Len, Len}) end; targets_to_nodes([N|Rest], Targets, {Start, Len}, Nodes) -> Sub = lists:sublist(Targets, Start, Len), %io:fwrite("sending ~p target(s) to ~p~n", [length(Sub), N]), N ! {targets, Sub}, case Start+Len > length(Targets) of true -> ok; false -> targets_to_nodes(Rest, Targets, {Start+Len, Len}, Nodes) end. % this is the rest of the targets when the division is not % finished targets_to_nodes_rest([N|Nodes], Targets, {Start, Len}) when Start =< length(Targets) -> Sub = lists:sublist(Targets, Start, Len), %io:fwrite("sending ~p target(s) to ~p~n", [length(Sub), N]), N ! {targets, Sub}, targets_to_nodes_rest(Nodes, Targets, {Start+Len, Len}); targets_to_nodes_rest(_, _, _) -> ok. % push the targets to the nodes push([], _, _) -> ok; push(_, [], _) -> ok; push(Nodes, Targets, Func) -> Exploded = Func(Targets), Rnd = rnd_list(Exploded), Len = case length(Nodes) > length(Rnd) of true -> 1; false -> length(Rnd) div length(Nodes) end, targets_to_nodes(Nodes, Rnd, {1, Len}, Nodes). push_file(nil, _Nodes, _Func, _Dbg) -> ok; push_file([], _Nodes, _Func, _Dbg) -> ok; push_file([H|T], Nodes, Func, Dbg) -> utils:debug(master, io_lib:fwrite("loading file: ~p", [H]), {}, Dbg), Tgts = targets_from_file(H), utils:debug(master, io_lib:fwrite("pushing loaded target(s) from: ~p", [H]), {}, Dbg), push(Nodes, Tgts, Func), erlang:garbage_collect(), push_file(T, tl(Nodes) ++ [hd(Nodes)], Func, Dbg). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Entry point %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % wait end of scan wait_end(Progress, Pids, Opts) -> receive {pause} -> % output wants to pause pause_all(Pids, true, Opts), wait_end(Progress, Pids, Opts); {resume} -> % output wants to resume pause_all(Pids, false, Opts), wait_end(Progress, Pids, Opts); {quit} -> ok after ?ENDTO -> % this only here to trigger progress trigger_progress(Progress, Pids), wait_end(Progress, Pids, Opts) end. pause_all(Pids, Flag, Opts) -> case Flag of true -> utils:debug(master, "pause brokers ...", {}, Opts#opts.debugval), [X ! {prio, pause} || X <- Pids]; false -> utils:debug(master, "resume brokers ...", {}, Opts#opts.debugval), [X ! {prio, resume} || X <- Pids] end. % start the master master(Opts) -> ts(), Id = integer_to_list(epoch()), register_entry(self(), main), MyNodeName = list_to_atom(lists:concat([Id, "master"])), net_kernel:start([MyNodeName, shortnames]), Start = calendar:datetime_to_gregorian_seconds(calendar:universal_time()), Slaves = get_slaves(Opts#opts.slave, Opts#opts.slavefile), print(us, io_lib:fwrite("SCANNERL started for Module ~s", [Opts#opts.module])), application:set_env(kernel, inet_dist_listen_min, ?PORTMIN), application:set_env(kernel, inet_dist_listen_max, ?PORTMIN+cntlist:count(Slaves)), % starting slave nodes SlaveTimestamp = calendar:datetime_to_gregorian_seconds(calendar:universal_time()), register_entry(spawn_link(?MODULE, listen, [cntlist:count(Slaves), Opts]), listener), print(us, io_lib:fwrite("starting ~p slave's node(s) on ~p host(s)", [cntlist:count(Slaves), length(Slaves)])), case Opts#opts.maxchild of 0 -> print(us, io_lib:fwrite("max process per node: ~p", [unlimited])); Nb -> print(us, io_lib:fwrite("max process per node: ~p", [Nb])) end, {Ret, Nodes} = start_slaves(Slaves, Opts#opts.slmodule, Id, Opts#opts.nosafe, Opts#opts.debugval, Opts#opts.stimeout), print(us, io_lib:fwrite("slave's node(s) started in: ~2..0w:~2..0w:~2..0w", duration(SlaveTimestamp))), % update total number of slave global:whereis_name(listener) ! {totchange, cntlist:count(Nodes)}, % check nodes are ready to scan case Ret of error -> % handle error of node start stop_slaves(cntlist:flattenkeys(Nodes), Opts#opts.debugval), print(error, "slave's node(s) start failed"), global:whereis_name(scannerl) ! {done, error}; ok -> % start the supervisor(s) print(us, io_lib:fwrite("starting ~p supervisor(s)", [cntlist:count(Nodes)])), Pids = rnd_list(start_brokers(cntlist:flatten(Nodes), Opts, 0, [])), SlaveDuration = duration(SlaveTimestamp), TargetTimestamp = calendar:datetime_to_gregorian_seconds(calendar:universal_time()), % push the target(s) from CLI print(us, "parse and push target(s)"), push(Pids, Opts#opts.target, fun(X) -> process_targets(X, [], Opts#opts.minrange, Opts#opts.port) end), push(Pids, Opts#opts.domain, fun(X) -> process_domains(X, [], Opts#opts.minrange, Opts#opts.port) end), % push the target(s) from file print(us, "parse and push target(s) from file"), push_file(Opts#opts.targetfile, Pids, fun(X) -> process_targets(X, [], Opts#opts.minrange, Opts#opts.port) end, Opts#opts.debugval), push_file(Opts#opts.domainfile, Pids, fun(X) -> process_domains(X, [], Opts#opts.minrange, Opts#opts.port) end, Opts#opts.debugval), TargetDuration = duration(TargetTimestamp), print(us, io_lib:fwrite("target(s) parsed and pushed in: ~2..0w:~2..0w:~2..0w", TargetDuration)), % update the slave pids on the listener global:whereis_name(listener) ! {pids, Pids}, % start the message server spawn_link(utils_msgserver, listen_udp, [global:whereis_name(listener), Opts#opts.msg_port]), % start the fingerprinting process [X ! {done} || X <- Pids], print(us, "started ..."), % wait for end wait_end(Opts#opts.progress, Pids, Opts), % stop slave's node(s) utils:debug(master, io_lib:fwrite("stopping nodes: ~p", [Nodes]), {}, Opts#opts.debugval), stop_slaves(cntlist:flattenkeys(Nodes), Opts#opts.debugval), print(us, io_lib:fwrite("target setup duration: ~2..0w:~2..0w:~2..0w", TargetDuration)), print(us, io_lib:fwrite("slave setup duration: ~2..0w:~2..0w:~2..0w", SlaveDuration)), % stop the message server utils_msgserver:stop_udp(Opts#opts.msg_port), % gather info and terminate global:whereis_name(scannerl) ! {done, {cntlist:count(Nodes)}} end, print(us, io_lib:fwrite("duration: ~2..0w:~2..0w:~2..0w", duration(Start))), ts().
null
https://raw.githubusercontent.com/kudelskisecurity/scannerl/8133065030d014401c47b2470e67a36e9df81b1e/src/master.erl
erlang
the master in the master/slave architecture of scannerl ms ms that's the range start for TCP communication remote related functions this loads all modules for this specific node then register master and scannerl on remote start a list of slave start all slave nodes using process stop all slave nodes start a broker on each node globally register master as myself return our hostname randomize a list print timestamp in nice format pretty print duration get current process queue cnt get epoch listen for slave's messages flush message in the queue wait for and answer to message(s) update the number of nodes (especially for --nosafe) update the pids sent by myself (other thread) sent by broker sent by broker debug message from broker received by the message listener called at the end of the process send message {progress} to all slaves Slave processing get a slave (from a list of string) and add it to a cntlist get slaves from a file get slaves from CLI and Path get a list of stripped lines that represent a target parse domains hosts io:fwrite("sending ~p target(s) to ~p~n", [length(Sub), N]), io:fwrite("sending ~p target(s) to ~p~n", [length(Sub), N]), this is the rest of the targets when the division is not finished io:fwrite("sending ~p target(s) to ~p~n", [length(Sub), N]), push the targets to the nodes Entry point wait end of scan output wants to pause output wants to resume this only here to trigger progress start the master starting slave nodes update total number of slave check nodes are ready to scan handle error of node start start the supervisor(s) push the target(s) from CLI push the target(s) from file update the slave pids on the listener start the message server start the fingerprinting process wait for end stop slave's node(s) stop the message server gather info and terminate
-module(master). -author("Adrien Giner - "). -export([master/1, listen/2]). -include("includes/opts.hrl"). -define(ERLEXT, ".erl"). will be expanded to ? PORTMIN+nb_slaves for the -define(PORTMIN, 11100). rem_load_modules(_, []) -> ok; rem_load_modules(Node, [M|Rest]) -> {Mod, Bin, _} = code:get_object_code(M), rpc:call(Node, code, purge, [Mod]), rpc:call(Node, erlang, load_module, [Mod, Bin]), rem_load_modules(Node, Rest). wait_for_slave(Tot, Cnt, Cntlist, _Mods, _Nosafe, _Timeout) when Cnt == Tot -> case cntlist:count(Cntlist) of 0 -> print(error, "no viable host found"), {error, Cntlist}; _ -> {ok, Cntlist} end; wait_for_slave(Tot, Cnt, Cntlist, Modules, Nosafe, Timeout) -> receive {ok, Node, H, _Name} -> net_kernel:connect_node(Node), rem_load_modules(Node, Modules), rpc:call(Node, global, register_name, [master, global:whereis_name(listener)]), rpc:call(Node, global, register_name, [scannerl, global:whereis_name(scannerl)]), New = cntlist:update_key(Cntlist, H, Node), wait_for_slave(Tot, Cnt+1, New, Modules, Nosafe, Timeout); {error, Reason, H, Name} when Nosafe -> print(warning, io_lib:fwrite("host ~p (name:~p) failed to start: ~p - continue ...", [H, Name, Reason])), New = cntlist:remove_key(Cntlist, H), wait_for_slave(Tot, Cnt+1, New, Modules, Nosafe, Timeout); {error, Reason, H, Name} -> print(error, io_lib:fwrite("unable to start host ~p (name:~p): ~p", [H, Name, Reason])), {error, Cntlist} after Timeout -> print(error, io_lib:fwrite("max timeout (~ps) reached when waiting for slaves (got ~p/~p)", [Timeout / 1000, Cnt, Tot])), {error, Cntlist} end. start_slave_th([], Mods, Tot, Slaves, _Basename, Nosafe, _Dbg, Timeout) -> wait_for_slave(Tot, 0, Slaves, Mods, Nosafe, 2*Timeout); start_slave_th([H|T], Modules, Cnt, Slaves, Basename, Nosafe, Dbg, Timeout) -> Name = lists:concat([Basename, "-slave-", integer_to_list(Cnt)]), spawn_link(utils_slave, start_link_th, [H, Name, ?PORTMIN, Dbg, self(), Timeout]), start_slave_th(T, Modules, Cnt+1, Slaves, Basename, Nosafe, Dbg, Timeout). start_slaves(Slaves, Modules, Basename, Nosafe, Dbg, Timeout) -> start_slave_th(cntlist:flattenkeys(Slaves), Modules, 0, Slaves, Basename, Nosafe, Dbg, Timeout). stop_slaves([], _Dbg) -> ok; stop_slaves([H|T], Dbg) -> spawn_link(utils_slave, stop, [H, Dbg]), stop_slaves(T, Dbg). start_brokers([], _, _, Agg) -> Agg; start_brokers([H|T], Opts, Cnt, Agg) -> Id = "ID" ++ integer_to_list(Cnt), Pid = spawn_link(H, broker, scan, [Opts#opts{user=Id}]), start_brokers(T, Opts, Cnt+1, Agg ++ [Pid]). Utilities register_entry(Pid, Name) -> yes = global:register_name(Name, Pid), global:sync(). my_hostname() -> {ok, Hostname} = inet:gethostname(), Hostname. rnd_list(List) -> [X||{_,X} <- lists:sort([{rand:uniform(), N} || N <- List])]. print(myerror, Msg) -> io:put_chars(standard_error, Msg); print(us, Msg) -> M = io_lib:fwrite("<~s> [M] ~s\n", [utils:get_ts(), Msg]), io:put_chars(standard_error, M); print(error, Msg) -> M = io_lib:fwrite("<~s> [M]>[E] ~s\n", [utils:get_ts(), Msg]), io:put_chars(standard_error, M); print(warning, Msg) -> M = io_lib:fwrite("[WARNING] ~s\n", [Msg]), io:put_chars(standard_error, M); print(info, Msg) -> M = io_lib:fwrite("<~s> [M]>[I] ~s\n", [utils:get_ts(), Msg]), io:put_chars(standard_error, M); print(result, Msg) -> M = io_lib:fwrite("~s\n", [Msg]), io:put_chars(standard_error, M); print(_, _) -> ok. ts() -> print(us, utils:get_ts()). duration(Start) -> Duration = calendar:datetime_to_gregorian_seconds(calendar:universal_time()) - Start, DateTime = calendar:gregorian_seconds_to_datetime(Duration), {{_Y,_M,_D}, {H,Min,S}} = DateTime, [H, Min, S]. msg_queue_len() -> {_, Cnt} = erlang:process_info(self(), message_queue_len), Cnt. epoch() -> {M, S, _} = os:timestamp(), (M*1000000)+S. Communication listen(TotSlave, Opts) -> rcv_loop(TotSlave, Opts, []), flush_msg(msg_queue_len(), Opts), global:whereis_name(main) ! {quit}. flush_msg(0, _) -> ok; flush_msg(_, Opts) -> rcv_loop(0, Opts, []), flush_msg(msg_queue_len(), Opts). rcv_loop(0, _Opts, _Pids) -> ok; rcv_loop(CntSlave, Opts, Pids) -> receive {totchange, New} -> rcv_loop(New, Opts, Pids); {pids, List} -> rcv_loop(CntSlave, Opts, List); {progress, _From, Id, Msg} -> print(info , io_lib : fwrite("[progress][~p|~s ] ~s " , [ From , I d , Msg ] ) ) , print(info, io_lib:fwrite("[progress][~s] ~s", [Id, Msg])), rcv_loop(CntSlave, Opts, Pids); {info, From, Id, "done"} -> utils:debug(master, io_lib:fwrite("[~p|~s] is done !", [From, Id]), {}, Opts#opts.debugval), rcv_loop(CntSlave-1, Opts, Pids); {info, From, Id, Data} -> print(info, io_lib:fwrite("[~p|~s]: ~s", [From, Id, Data])), rcv_loop(CntSlave, Opts, Pids); {debug, From, Msg} -> utils:debug_print(From, Msg), rcv_loop(CntSlave, Opts, Pids); {message, {error, Proto, Port, Reason}} -> print(error, io_lib:fwrite("cannot listen on ~s/~p: ~p", [Proto, Port, Reason])), rcv_loop(CntSlave, Opts, Pids); {message, {ok, Protocol, Ip, Port}} -> print(us, io_lib:fwrite("listen on ~s ~s/~p", [Ip, Protocol, Port])), rcv_loop(CntSlave, Opts, Pids); {message, {message, "progress"}} -> print(us, "progress triggered"), trigger_progress(true, Pids), rcv_loop(CntSlave, Opts, Pids); {message, {message, "abort"}} -> case Pids of [] -> print(info, "[!!] cannot cancel, process is terminating"); _ -> print(info, "[!!] send cancel to all slaves"), [X ! {cancel} || X <- Pids] end, rcv_loop(CntSlave, Opts, Pids); _ -> rcv_loop(CntSlave, Opts, Pids) after ?CHECKTO -> rcv_loop(CntSlave, Opts, Pids) end. trigger_progress(false, _) -> ok; trigger_progress(true, Pids) -> print(info, io_lib:fwrite("[progress][M] ~p slave(s)", [length(Pids)])), global:whereis_name(scannerl) ! {progress}, [X ! {progress} || X <- Pids]. get_slave([], Agg) -> Agg; get_slave([Entry|T], Agg) -> case string:str(Entry, "*") of 0 -> get_slave(T, cntlist:add(Agg, Entry, 1)); _ -> [Node, Nb] = string:tokens(Entry, "*"), get_slave(T, cntlist:add(Agg, Node, list_to_integer(Nb))) end. slaves_from_file(nil) -> {ok, []}; slaves_from_file(Path) -> case utils:read_lines(Path) of {ok, Lines} -> {ok, get_slave(Lines, [])}; {error, Reason} -> {error, Reason} end. get_slaves(Slaves, Path) -> Sl1 = get_slave(Slaves, []), case slaves_from_file(Path) of {ok, Sl2} -> Res = cntlist:merge(lists:flatten(Sl1 ++ Sl2)), case cntlist:count(Res) of 0 -> cntlist:add([], my_hostname(), 1); _ -> Res end; {error, Reason} -> print(myerror, io_lib:fwrite("[ERROR] cannot get slaves from ~p: ~p~n", [Path, Reason])), [] end. Target processing targets_from_file(nil) -> []; targets_from_file(Path) -> case utils:read_lines(Path) of {ok, Lines} -> Lines; {error, Reason} -> print(myerror, io_lib:fwrite("[ERROR] cannot get targets from ~p: ~p~n", [Path, Reason])), [] end. parse ip / and sub - divide in Minrange process_targets([], _, _, _) -> []; process_targets([H|T], Agg, Minrange, Defport) -> case tgt:parse_ip(H, Defport) of {ok, Tgt} -> tgt:minrange(Tgt, Minrange) ++ process_targets(T, Agg, Minrange, Defport); {error, Reason} -> print(myerror, io_lib:fwrite("[ERROR] cannot parse ~p: ~p~n", [H, Reason])), process_targets(T, Agg, Minrange, Defport) end. process_domains([], _, _, _) -> []; process_domains([H|T], Agg, Minrange, Defport) -> [tgt:parse_domain(H, Defport)] ++ process_domains(T, Agg, Minrange, Defport). here we distribute by Len the targets to the different targets_to_nodes([N|[]], Targets, {Start, Len}, Nodes) -> Sub = lists:sublist(Targets, Start, Len), N ! {targets, Sub}, case Start+Len > length(Targets) of true -> ok; false -> targets_to_nodes_rest(Nodes, Targets, {Start+Len, Len}) end; targets_to_nodes([N|Rest], Targets, {Start, Len}, Nodes) -> Sub = lists:sublist(Targets, Start, Len), N ! {targets, Sub}, case Start+Len > length(Targets) of true -> ok; false -> targets_to_nodes(Rest, Targets, {Start+Len, Len}, Nodes) end. targets_to_nodes_rest([N|Nodes], Targets, {Start, Len}) when Start =< length(Targets) -> Sub = lists:sublist(Targets, Start, Len), N ! {targets, Sub}, targets_to_nodes_rest(Nodes, Targets, {Start+Len, Len}); targets_to_nodes_rest(_, _, _) -> ok. push([], _, _) -> ok; push(_, [], _) -> ok; push(Nodes, Targets, Func) -> Exploded = Func(Targets), Rnd = rnd_list(Exploded), Len = case length(Nodes) > length(Rnd) of true -> 1; false -> length(Rnd) div length(Nodes) end, targets_to_nodes(Nodes, Rnd, {1, Len}, Nodes). push_file(nil, _Nodes, _Func, _Dbg) -> ok; push_file([], _Nodes, _Func, _Dbg) -> ok; push_file([H|T], Nodes, Func, Dbg) -> utils:debug(master, io_lib:fwrite("loading file: ~p", [H]), {}, Dbg), Tgts = targets_from_file(H), utils:debug(master, io_lib:fwrite("pushing loaded target(s) from: ~p", [H]), {}, Dbg), push(Nodes, Tgts, Func), erlang:garbage_collect(), push_file(T, tl(Nodes) ++ [hd(Nodes)], Func, Dbg). wait_end(Progress, Pids, Opts) -> receive {pause} -> pause_all(Pids, true, Opts), wait_end(Progress, Pids, Opts); {resume} -> pause_all(Pids, false, Opts), wait_end(Progress, Pids, Opts); {quit} -> ok after ?ENDTO -> trigger_progress(Progress, Pids), wait_end(Progress, Pids, Opts) end. pause_all(Pids, Flag, Opts) -> case Flag of true -> utils:debug(master, "pause brokers ...", {}, Opts#opts.debugval), [X ! {prio, pause} || X <- Pids]; false -> utils:debug(master, "resume brokers ...", {}, Opts#opts.debugval), [X ! {prio, resume} || X <- Pids] end. master(Opts) -> ts(), Id = integer_to_list(epoch()), register_entry(self(), main), MyNodeName = list_to_atom(lists:concat([Id, "master"])), net_kernel:start([MyNodeName, shortnames]), Start = calendar:datetime_to_gregorian_seconds(calendar:universal_time()), Slaves = get_slaves(Opts#opts.slave, Opts#opts.slavefile), print(us, io_lib:fwrite("SCANNERL started for Module ~s", [Opts#opts.module])), application:set_env(kernel, inet_dist_listen_min, ?PORTMIN), application:set_env(kernel, inet_dist_listen_max, ?PORTMIN+cntlist:count(Slaves)), SlaveTimestamp = calendar:datetime_to_gregorian_seconds(calendar:universal_time()), register_entry(spawn_link(?MODULE, listen, [cntlist:count(Slaves), Opts]), listener), print(us, io_lib:fwrite("starting ~p slave's node(s) on ~p host(s)", [cntlist:count(Slaves), length(Slaves)])), case Opts#opts.maxchild of 0 -> print(us, io_lib:fwrite("max process per node: ~p", [unlimited])); Nb -> print(us, io_lib:fwrite("max process per node: ~p", [Nb])) end, {Ret, Nodes} = start_slaves(Slaves, Opts#opts.slmodule, Id, Opts#opts.nosafe, Opts#opts.debugval, Opts#opts.stimeout), print(us, io_lib:fwrite("slave's node(s) started in: ~2..0w:~2..0w:~2..0w", duration(SlaveTimestamp))), global:whereis_name(listener) ! {totchange, cntlist:count(Nodes)}, case Ret of error -> stop_slaves(cntlist:flattenkeys(Nodes), Opts#opts.debugval), print(error, "slave's node(s) start failed"), global:whereis_name(scannerl) ! {done, error}; ok -> print(us, io_lib:fwrite("starting ~p supervisor(s)", [cntlist:count(Nodes)])), Pids = rnd_list(start_brokers(cntlist:flatten(Nodes), Opts, 0, [])), SlaveDuration = duration(SlaveTimestamp), TargetTimestamp = calendar:datetime_to_gregorian_seconds(calendar:universal_time()), print(us, "parse and push target(s)"), push(Pids, Opts#opts.target, fun(X) -> process_targets(X, [], Opts#opts.minrange, Opts#opts.port) end), push(Pids, Opts#opts.domain, fun(X) -> process_domains(X, [], Opts#opts.minrange, Opts#opts.port) end), print(us, "parse and push target(s) from file"), push_file(Opts#opts.targetfile, Pids, fun(X) -> process_targets(X, [], Opts#opts.minrange, Opts#opts.port) end, Opts#opts.debugval), push_file(Opts#opts.domainfile, Pids, fun(X) -> process_domains(X, [], Opts#opts.minrange, Opts#opts.port) end, Opts#opts.debugval), TargetDuration = duration(TargetTimestamp), print(us, io_lib:fwrite("target(s) parsed and pushed in: ~2..0w:~2..0w:~2..0w", TargetDuration)), global:whereis_name(listener) ! {pids, Pids}, spawn_link(utils_msgserver, listen_udp, [global:whereis_name(listener), Opts#opts.msg_port]), [X ! {done} || X <- Pids], print(us, "started ..."), wait_end(Opts#opts.progress, Pids, Opts), utils:debug(master, io_lib:fwrite("stopping nodes: ~p", [Nodes]), {}, Opts#opts.debugval), stop_slaves(cntlist:flattenkeys(Nodes), Opts#opts.debugval), print(us, io_lib:fwrite("target setup duration: ~2..0w:~2..0w:~2..0w", TargetDuration)), print(us, io_lib:fwrite("slave setup duration: ~2..0w:~2..0w:~2..0w", SlaveDuration)), utils_msgserver:stop_udp(Opts#opts.msg_port), global:whereis_name(scannerl) ! {done, {cntlist:count(Nodes)}} end, print(us, io_lib:fwrite("duration: ~2..0w:~2..0w:~2..0w", duration(Start))), ts().
32c3a471159fa371ccd263e02ea3fe8f75c914c7a32ffb1941a44b98c56fac6d
inanna-malick/merkle-schemes
Simple.hs
module DirTree.Diff.Simple where import Control.Monad (join) import Data.Map.Strict (Map) import qualified Data.Map.Strict as Map import qualified Data.Map.Merge.Strict as Map import DirTree.Types import DirTree.Diff.Types import Control.RecursionSchemes | Diff two directory trees diffDirTrees :: DirTree -> DirTree -> [(FilePath, Diff)] diffDirTrees (Fix (DirLayer entities1)) (Fix (DirLayer entities2)) = join $ Map.elems mergeRes where mergeRes :: Map FilePath [(FilePath, Diff)] mergeRes = Map.merge (Map.mapMissing onRemoved) (Map.mapMissing onAdded) (Map.zipWithMatched onConflict) (Map.fromList entities1) (Map.fromList entities2) onRemoved, onAdded :: FilePath -> FileTreeEntity DirTree -> [(FilePath, Diff)] onRemoved path _ = [(path, EntityDeleted)] onAdded path _ = [(path, EntityCreated)] onConflict :: FilePath -> FileTreeEntity DirTree -> FileTreeEntity DirTree -> [(FilePath, Diff)] named directory exists in both DirTrees : recurse onConflict path (DirEntity d1) (DirEntity d2) = let updatePath (p,x) = (path ++ "/" ++ p, x) in updatePath <$> diffDirTrees d1 d2 named file exists in both DirTrees : compare onConflict path (FileEntity f1) (FileEntity f2) | f1 /= f2 = [(path, FileModified)] | otherwise = [] -- dir replaced with file onConflict path (DirEntity _) (FileEntity _) = [(path, DirReplacedWithFile)] -- file replaced with dir onConflict path (FileEntity _) (DirEntity _) = [(path, FileReplacedWithDir)]
null
https://raw.githubusercontent.com/inanna-malick/merkle-schemes/4eac64f4df12ea7d1d1f3bb34010424db19e0a9e/talk/src/DirTree/Diff/Simple.hs
haskell
dir replaced with file file replaced with dir
module DirTree.Diff.Simple where import Control.Monad (join) import Data.Map.Strict (Map) import qualified Data.Map.Strict as Map import qualified Data.Map.Merge.Strict as Map import DirTree.Types import DirTree.Diff.Types import Control.RecursionSchemes | Diff two directory trees diffDirTrees :: DirTree -> DirTree -> [(FilePath, Diff)] diffDirTrees (Fix (DirLayer entities1)) (Fix (DirLayer entities2)) = join $ Map.elems mergeRes where mergeRes :: Map FilePath [(FilePath, Diff)] mergeRes = Map.merge (Map.mapMissing onRemoved) (Map.mapMissing onAdded) (Map.zipWithMatched onConflict) (Map.fromList entities1) (Map.fromList entities2) onRemoved, onAdded :: FilePath -> FileTreeEntity DirTree -> [(FilePath, Diff)] onRemoved path _ = [(path, EntityDeleted)] onAdded path _ = [(path, EntityCreated)] onConflict :: FilePath -> FileTreeEntity DirTree -> FileTreeEntity DirTree -> [(FilePath, Diff)] named directory exists in both DirTrees : recurse onConflict path (DirEntity d1) (DirEntity d2) = let updatePath (p,x) = (path ++ "/" ++ p, x) in updatePath <$> diffDirTrees d1 d2 named file exists in both DirTrees : compare onConflict path (FileEntity f1) (FileEntity f2) | f1 /= f2 = [(path, FileModified)] | otherwise = [] onConflict path (DirEntity _) (FileEntity _) = [(path, DirReplacedWithFile)] onConflict path (FileEntity _) (DirEntity _) = [(path, FileReplacedWithDir)]
c5e4e1475d46b429668b85241dad728485542da01d6e76edff5a5d75426934bb
urueedi/monster-ui-phonebook
cf_attributes.erl
%%%------------------------------------------------------------------- ( C ) 2011 - 2014 , 2600Hz INC %%% @doc %%% @end %%% @contributors %%%------------------------------------------------------------------- -module(cf_attributes). -include("callflow.hrl"). -export([temporal_rules/1]). -export([groups/1, groups/2]). -export([caller_id/2]). -export([callee_id/2]). -export([moh_attributes/2, moh_attributes/3]). -export([owner_id/1, owner_id/2]). -export([presence_id/1, presence_id/2]). -export([owned_by/2, owned_by/3 ,owned_by_docs/2, owned_by_docs/3 ]). -export([owner_ids/2]). -export([maybe_get_assigned_number/3]). -export([maybe_get_account_default_number/4]). %%----------------------------------------------------------------------------- @public %% @doc %% @end %%----------------------------------------------------------------------------- -spec temporal_rules(whapps_call:call()) -> wh_json:objects(). temporal_rules(Call) -> AccountDb = whapps_call:account_db(Call), case couch_mgr:get_results(AccountDb, <<"cf_attributes/temporal_rules">>, ['include_docs']) of {'ok', JObjs} -> JObjs; {'error', _E} -> lager:debug("failed to find temporal rules: ~p", [_E]), [] end. %%----------------------------------------------------------------------------- @public %% @doc %% @end %%----------------------------------------------------------------------------- -spec groups(whapps_call:call()) -> wh_json:objects(). -spec groups(whapps_call:call(), wh_proplist()) -> wh_json:objects(). groups(Call) -> groups(Call, []). groups(Call, ViewOptions) -> AccountDb = whapps_call:account_db(Call), case couch_mgr:get_results(AccountDb, <<"cf_attributes/groups">>, ViewOptions) of {'ok', JObjs} -> JObjs; {'error', _} -> [] end. %%----------------------------------------------------------------------------- @public %% @doc %% @end %%----------------------------------------------------------------------------- -spec caller_id(ne_binary(), whapps_call:call()) -> {api_binary(), api_binary()}. caller_id(Attribute, Call) -> lager:debug("debug of call variables:~p", [Call]), CCVs = whapps_call:custom_channel_vars(Call), Inception = whapps_call:inception(Call), AccountId = whapps_call:account_id(Call), Name = whapps_call:caller_id_name(Call), CidFormat = whapps_call:callerid_format(Call), CidPrefix = whapps_call:callerid_prefix(Call), E164 = wnm_util:to_e164(whapps_call:caller_id_number(Call), AccountId), Int = wnm_util:e164_tointernational(E164), case CidFormat of 'e164' -> CallerId = E164; 'international' -> CallerId = Int; 'national' -> CallerId = wnm_util:e164_tonational(E164); 'local' -> CallerId = wnm_util:e164_tonational(E164); 'nochange' -> CallerId = whapps_call:caller_id_number(Call); [] -> CallerId = E164; 'nomatch' -> CallerId = E164; 'undefined' -> CallerId = E164 end, lager:info("caller id convert to format Name:<~s> CLID:~s, Cid-Format:~s CidPrefix:~s", [Name, CallerId, CidFormat, CidPrefix]), case (Inception =/= 'undefined' andalso not wh_json:is_true(<<"Call-Forward">>, CCVs)) orelse wh_json:is_true(<<"Retain-CID">>, CCVs) of 'true' -> maybe_normalize_cid(CallerId, Name, 'false', Attribute, Call); 'false' -> maybe_get_dynamic_cid('true', Attribute, Call) end. -spec maybe_get_dynamic_cid(boolean(), ne_binary(), whapps_call:call()) -> {api_binary(), api_binary()}. maybe_get_dynamic_cid(Validate, Attribute, Call) -> case whapps_call:kvs_fetch('dynamic_cid', Call) of 'undefined' -> maybe_get_endpoint_cid(Validate, Attribute, Call); DynamicCID -> lager:debug("found dynamic caller id number ~s", [DynamicCID]), maybe_normalize_cid(DynamicCID, 'undefined', Validate, Attribute, Call) end. -spec maybe_get_endpoint_cid(boolean(), ne_binary(), whapps_call:call()) -> {api_binary(), api_binary()}. maybe_get_endpoint_cid(Validate, Attribute, Call) -> case cf_endpoint:get(Call) of {'error', _R} -> lager:info("unable to get endpoint: ~p", [_R]), maybe_normalize_cid('undefined', 'undefined', Validate, Attribute, Call); {'ok', JObj} -> Number = get_cid_or_default(Attribute, <<"number">>, JObj), Name = get_cid_or_default(Attribute, <<"name">>, JObj), _ = log_configured_endpoint_cid(Attribute, Name, Number), maybe_use_presence_number(Number, Name, JObj, Validate, Attribute, Call) end. -spec log_configured_endpoint_cid(ne_binary(), api_binary(), api_binary()) -> 'ok'. log_configured_endpoint_cid(Attribute, 'undefined', 'undefined') -> lager:debug("endpoint not configured with an ~s caller id", [Attribute]); log_configured_endpoint_cid(Attribute, Name, 'undefined') -> lager:debug("endpoint configured with ~s caller id name ~s", [Attribute, Name]); log_configured_endpoint_cid(Attribute, 'undefined', Number) -> lager:debug("endpoint configured with ~s caller id number ~s", [Attribute, Number]); log_configured_endpoint_cid(Attribute, Name, Number) -> lager:debug("endpoint configured with ~s caller id <~s> ~s", [Attribute, Name, Number]). -spec maybe_use_presence_number(api_binary(), api_binary(), wh_json:object(), boolean(), ne_binary(), whapps_call:call()) -> {api_binary(), api_binary()}. maybe_use_presence_number('undefined', Name, Endpoint, Validate, <<"internal">> = Attribute, Call) -> case maybe_get_presence_number(Endpoint, Call) of 'undefined' -> maybe_normalize_cid('undefined', Name, Validate, Attribute, Call); Number -> lager:debug("replacing empty caller id number with presence number ~s", [Number]), maybe_normalize_cid(Number, Name, Validate, Attribute, Call) end; maybe_use_presence_number(Number, Name, _Endpoint, Validate, Attribute, Call) -> maybe_normalize_cid(Number, Name, Validate, Attribute, Call). -spec maybe_normalize_cid(api_binary(), api_binary(), boolean(), ne_binary(), whapps_call:call()) -> {api_binary(), api_binary()}. maybe_normalize_cid('undefined', Name, Validate, Attribute, Call) -> Number = whapps_call:caller_id_number(Call), lager:debug("replacing empty caller id number with SIP caller id number ~s", [Number]), maybe_normalize_cid(Number, Name, Validate, Attribute, Call); maybe_normalize_cid(Number, 'undefined', Validate, Attribute, Call) -> Name = whapps_call:caller_id_name(Call), lager:debug("replacing empty caller id name with SIP caller id name ~s", [Name]), maybe_normalize_cid(Number, Name, Validate, Attribute, Call); maybe_normalize_cid(Number, Name, Validate, Attribute, Call) -> maybe_prefix_cid_number(wh_util:to_binary(Number), Name, Validate, Attribute, Call). -spec maybe_prefix_cid_number(ne_binary(), ne_binary(), boolean(), ne_binary(), whapps_call:call()) -> {api_binary(), api_binary()}. maybe_prefix_cid_number(Number, Name, Validate, Attribute, Call) -> case whapps_call:kvs_fetch('prepend_cid_number', Call) of 'undefined' -> maybe_suffix_cid_number(Number, Name, Validate, Attribute, Call); Prefix -> lager:debug("prepending caller id number with ~s", [Prefix]), Prefixed = <<(wh_util:to_binary(Prefix))/binary, Number/binary>>, maybe_suffix_cid_number(Prefixed, Name, Validate, Attribute, Call) end. -spec maybe_suffix_cid_number(ne_binary(), ne_binary(), boolean(), ne_binary(), whapps_call:call()) -> {api_binary(), api_binary()}. maybe_suffix_cid_number(Number, Name, Validate, Attribute, Call) -> case whapps_call:kvs_fetch('suffix_cid_number', Call) of 'undefined' -> maybe_prefix_cid_name(Number, Name, Validate, Attribute, Call); Suffix -> lager:debug("suffixing caller id number with ~s", [Suffix]), Suffixed = <<Number/binary, (wh_util:to_binary(Suffix))/binary>>, lager:debug("caller id number with ~s", [Suffixed]), maybe_prefix_cid_name(Suffixed, Name, Validate, Attribute, Call) end. -spec maybe_prefix_cid_name(ne_binary(), ne_binary(), boolean(), ne_binary(), whapps_call:call()) -> {api_binary(), api_binary()}. maybe_prefix_cid_name(Number, Name, Validate, Attribute, Call) -> case whapps_call:kvs_fetch('prepend_cid_name', Call) of 'undefined' -> maybe_rewrite_cid_number(Number, Name, Validate, Attribute, Call); Prefix -> lager:debug("prepending caller id name with ~s", [Prefix]), Prefixed = <<(wh_util:to_binary(Prefix))/binary, Name/binary>>, maybe_rewrite_cid_number(Number, Prefixed, Validate, Attribute, Call) end. -spec maybe_rewrite_cid_number(ne_binary(), ne_binary(), boolean(), ne_binary(), whapps_call:call()) -> {api_binary(), api_binary()}. maybe_rewrite_cid_number(Number, Name, Validate, Attribute, Call) -> case whapps_call:kvs_fetch('rewrite_cid_number', Call) of 'undefined' -> maybe_rewrite_cid_name(Number, Name, Validate, Attribute, Call); NewNumber -> lager:debug("reformating caller id number from ~s to ~s", [Number, NewNumber]), maybe_rewrite_cid_name(NewNumber, Name, Validate, Attribute, Call) end. -spec maybe_rewrite_cid_name(ne_binary(), ne_binary(), boolean(), ne_binary(), whapps_call:call()) -> {api_binary(), api_binary()}. maybe_rewrite_cid_name(Number, Name, Validate, Attribute, Call) -> case whapps_call:kvs_fetch('rewrite_cid_name', Call) of 'undefined' -> maybe_ensure_cid_valid(Number, Name, Validate, Attribute, Call); NewName -> lager:debug("reformating caller id name from ~s to ~s", [Name, NewName]), maybe_ensure_cid_valid(Number, NewName, Validate, Attribute, Call) end. -spec maybe_ensure_cid_valid(ne_binary(), ne_binary(), boolean(), ne_binary(), whapps_call:call()) -> {api_binary(), api_binary()}. maybe_ensure_cid_valid(Number, Name, 'true', <<"emergency">>, _Call) -> lager:info("determined emergency caller id is <~s> ~s", [Name, Number]), {Number, Name}; maybe_ensure_cid_valid(Number, Name, 'true', <<"external">>, Call) -> case whapps_config:get_is_true(<<"callflow">>, <<"ensure_valid_caller_id">>, 'false') of 'true' -> ensure_valid_caller_id(Number, Name, Call); 'false' -> lager:info("determined external caller id is <~s> ~s", [Name, Number]), maybe_cid_privacy(Number, Name, Call) end; maybe_ensure_cid_valid(Number, Name, _, Attribute, Call) -> lager:info("determined ~s caller id is <~s> ~s", [Attribute, Name, Number]), maybe_cid_privacy(Number, Name, Call). -spec maybe_cid_privacy(api_binary(), api_binary(), whapps_call:call()) -> {api_binary(), api_binary()}. maybe_cid_privacy(Number, Name, Call) -> case wh_util:is_true(whapps_call:kvs_fetch('cf_privacy', Call)) of 'true' -> lager:info("overriding caller id to maintain privacy"), {whapps_config:get_non_empty( <<"callflow">> ,<<"privacy_number">> ,wh_util:anonymous_caller_id_number() ) ,whapps_config:get_non_empty( <<"callflow">> ,<<"privacy_name">> ,wh_util:anonymous_caller_id_name() ) }; 'false' -> {Number, Name} end. -spec ensure_valid_caller_id(ne_binary(), ne_binary(), whapps_call:call()) -> {api_binary(), api_binary()}. ensure_valid_caller_id(Number, Name, Call) -> case is_valid_caller_id(Number, Call) of 'true' -> lager:info("determined valid external caller id is <~s> ~s", [Name, Number]), {Number, Name}; 'false' -> lager:info("invalid external caller id <~s> ~s", [Name, Number]), maybe_get_account_cid(Number, Name, Call) end. -spec maybe_get_account_cid(ne_binary(), ne_binary(), whapps_call:call()) -> {api_binary(), api_binary()}. maybe_get_account_cid(Number, Name, Call) -> case kz_account:fetch(whapps_call:account_id(Call)) of {'error', _} -> maybe_get_assigned_number(Number, Name, Call); {'ok', JObj} -> maybe_get_account_external_number(Number, Name, JObj, Call) end. -spec maybe_get_account_external_number(ne_binary(), ne_binary(), wh_json:object(), whapps_call:call()) -> {api_binary(), api_binary()}. maybe_get_account_external_number(Number, Name, Account, Call) -> External = wh_json:get_ne_value([<<"caller_id">>, <<"external">>, <<"number">>], Account), case is_valid_caller_id(External, Call) of 'true' -> lager:info("determined valid account external caller id is <~s> ~s", [Name, Number]), {External, Name}; 'false' -> maybe_get_account_default_number(Number, Name, Account, Call) end. -spec maybe_get_account_default_number(ne_binary(), ne_binary(), wh_json:object(), whapps_call:call()) -> {api_binary(), api_binary()}. maybe_get_account_default_number(Number, Name, Account, Call) -> Default = wh_json:get_ne_value([<<"caller_id">>, <<"default">>, <<"number">>], Account), case is_valid_caller_id(Default, Call) of 'true' -> lager:info("determined valid account default caller id is <~s> ~s", [Name, Number]), {Default, Name}; 'false' -> maybe_get_assigned_number(Number, Name, Call) end. -spec maybe_get_assigned_number(ne_binary(), ne_binary(), whapps_call:call()) -> {api_binary(), api_binary()}. maybe_get_assigned_number(_, Name, Call) -> AccountDb = whapps_call:account_db(Call), case couch_mgr:open_cache_doc(AccountDb, ?WNM_PHONE_NUMBER_DOC) of {'error', _R} -> Number = default_cid_number(), lager:warning("could not open phone_numbers doc <~s> ~s: ~p", [Name, Number, _R]), {Number, Name}; {'ok', JObj} -> PublicJObj = wh_json:public_fields(JObj), Numbers = [Num || Num <- wh_json:get_keys(PublicJObj) ,Num =/= <<"id">> ,(not wh_json:is_true([Num, <<"on_subaccount">>], JObj)) ,(wh_json:get_value([Num, <<"state">>], JObj) =:= ?NUMBER_STATE_IN_SERVICE) ], maybe_get_assigned_numbers(Numbers, Name, Call) end. -spec maybe_get_assigned_numbers(ne_binaries(), ne_binary(), whapps_call:call()) -> {api_binary(), api_binary()}. maybe_get_assigned_numbers([], Name, _) -> Number = default_cid_number(), lager:info("failed to find any in-service numbers, using default <~s> ~s", [Name, Number]), {Number, Name}; maybe_get_assigned_numbers([Number|_], Name, _) -> %% This could optionally cycle all found numbers and ensure they valid %% but that could be a lot of wasted db lookups... lager:info("using first assigned number caller id <~s> ~s", [Name, Number]), {Number, Name}. -spec is_valid_caller_id(api_binary(), whapps_call:call()) -> boolean(). is_valid_caller_id('undefined', _) -> 'false'; is_valid_caller_id(Number, Call) -> AccountId = whapps_call:account_id(Call), case wh_number_manager:lookup_account_by_number(Number) of {'ok', AccountId, _} -> 'true'; _Else -> 'false' end. -spec maybe_get_presence_number(wh_json:object(), whapps_call:call()) -> api_binary(). maybe_get_presence_number(Endpoint, Call) -> case presence_id(Endpoint, Call, 'undefined') of 'undefined' -> 'undefined'; PresenceId -> case binary:split(PresenceId, <<"@">>) of [PresenceNumber, _] -> PresenceNumber; [_Else] -> PresenceId end end. %%----------------------------------------------------------------------------- @public %% @doc %% @end %%----------------------------------------------------------------------------- -spec callee_id(api_binary() | wh_json:object(), whapps_call:call()) -> {api_binary(), api_binary()}. callee_id(EndpointId, Call) when is_binary(EndpointId) -> case cf_endpoint:get(EndpointId, Call) of {'ok', Endpoint} -> callee_id(Endpoint, Call); {'error', _R} -> maybe_normalize_callee('undefined', 'undefined', wh_json:new(), Call) end; callee_id(Endpoint, Call) -> Attribute = determine_callee_attribute(Call), Number = get_cid_or_default(Attribute, <<"number">>, Endpoint), Name = get_cid_or_default(Attribute, <<"name">>, Endpoint), maybe_normalize_callee(Number, Name, Endpoint, Call). -spec maybe_normalize_callee(api_binary(), api_binary(), wh_json:object(), whapps_call:call()) -> {api_binary(), api_binary()}. maybe_normalize_callee('undefined', Name, Endpoint, Call) -> maybe_normalize_callee(whapps_call:request_user(Call), Name, Endpoint, Call); maybe_normalize_callee(Number, 'undefined', Endpoint, Call) -> maybe_normalize_callee(Number, default_cid_name(Endpoint), Endpoint, Call); maybe_normalize_callee(Number, Name, _, _) -> lager:info("callee id <~s> ~s", [Name, Number]), {Number, Name}. -spec determine_callee_attribute(whapps_call:call()) -> ne_binary(). determine_callee_attribute(Call) -> case whapps_call:inception(Call) =/= 'undefined' of 'true' -> <<"external">>; 'false' -> <<"internal">> end. %%----------------------------------------------------------------------------- @public %% @doc %% @end %%----------------------------------------------------------------------------- -spec moh_attributes(ne_binary(), whapps_call:call()) -> api_binary(). -spec moh_attributes(api_binary() | wh_json:object(), ne_binary(), whapps_call:call()) -> api_binary(). moh_attributes(Attribute, Call) -> case cf_endpoint:get(Call) of {'error', _R} -> 'undefined'; {'ok', Endpoint} -> Value = wh_json:get_ne_value([<<"music_on_hold">>, Attribute], Endpoint), maybe_normalize_moh_attribute(Value, Attribute, Call) end. moh_attributes('undefined', _, _) -> 'undefined'; moh_attributes(EndpointId, Attribute, Call) when is_binary(EndpointId) -> case cf_endpoint:get(EndpointId, Call) of {'error', _} -> 'undefined'; {'ok', Endpoint} -> Value = wh_json:get_ne_value([<<"music_on_hold">>, Attribute], Endpoint), maybe_normalize_moh_attribute(Value, Attribute, Call) end; moh_attributes(Endpoint, Attribute, Call) -> Value = wh_json:get_ne_value([<<"music_on_hold">>, Attribute], Endpoint), maybe_normalize_moh_attribute(Value, Attribute, Call). -spec maybe_normalize_moh_attribute(api_binary(), ne_binary(), whapps_call:call()) -> api_binary(). maybe_normalize_moh_attribute('undefined', _, _) -> 'undefined'; maybe_normalize_moh_attribute(Value, <<"media_id">>, Call) -> MediaId = cf_util:correct_media_path(Value, Call), lager:info("found music_on_hold media_id: '~p'", [MediaId]), MediaId; maybe_normalize_moh_attribute(Value, Attribute, _) -> lager:info("found music_on_hold ~s: '~p'", [Attribute, Value]), Value. %%----------------------------------------------------------------------------- @public %% @doc %% @end %%----------------------------------------------------------------------------- -spec owner_id(whapps_call:call()) -> api_binary(). -spec owner_id(api_binary(), whapps_call:call()) -> api_binary(). owner_id(Call) -> case cf_endpoint:get(Call) of {'error', _} -> 'undefined'; {'ok', Endpoint} -> case wh_json:get_ne_value(<<"owner_id">>, Endpoint) of 'undefined' -> 'undefined'; OwnerId -> lager:info("initiating endpoint is owned by ~s", [OwnerId]), OwnerId end end. owner_id('undefined', _Call) -> 'undefined'; owner_id(ObjectId, Call) -> AccountDb = whapps_call:account_db(Call), ViewOptions = [{'key', ObjectId}], case couch_mgr:get_results(AccountDb, <<"cf_attributes/owner">>, ViewOptions) of {'ok', [JObj]} -> wh_json:get_value(<<"value">>, JObj); {'ok', []} -> 'undefined'; {'ok', [_|_]=JObjs} -> Owners = [wh_json:get_value(<<"value">>, JObj) || JObj <- JObjs], lager:debug("object ~s has multiple owners: ~-500p", [ObjectId, Owners]), 'undefined'; {'error', _R} -> lager:warning("unable to find owner for ~s: ~p", [ObjectId, _R]), 'undefined' end. owner_ids('undefined', _Call) -> []; owner_ids(ObjectId, Call) -> AccountDb = whapps_call:account_db(Call), ViewOptions = [{'key', ObjectId}], case couch_mgr:get_results(AccountDb, <<"cf_attributes/owner">>, ViewOptions) of {'ok', []} -> []; {'ok', [JObj]} -> [wh_json:get_value(<<"value">>, JObj)]; {'ok', [_|_]=JObjs} -> [wh_json:get_value(<<"value">>, JObj) || JObj <- JObjs]; {'error', _R} -> lager:warning("unable to find owner for ~s: ~p", [ObjectId, _R]), [] end. %%-------------------------------------------------------------------- @public %% @doc %% This function will return the precense id for the endpoint %% @end %%-------------------------------------------------------------------- -spec presence_id(whapps_call:call()) -> api_binary(). presence_id(Call) -> presence_id(whapps_call:authorizing_id(Call), Call). -spec presence_id(api_binary() | wh_json:object(), whapps_call:call()) -> api_binary(). presence_id(EndpointId, Call) when is_binary(EndpointId) -> case cf_endpoint:get(EndpointId, Call) of {'ok', Endpoint} -> presence_id(Endpoint, Call); {'error', _} -> 'undefined' end; presence_id(Endpoint, Call) -> Username = kz_device:sip_username(Endpoint, whapps_call:request_user(Call)), presence_id(Endpoint, Call, Username). -spec presence_id(wh_json:object(), whapps_call:call(), Default) -> ne_binary() | Default. presence_id(Endpoint, Call, Default) -> PresenceId = kz_device:presence_id(Endpoint, Default), case wh_util:is_empty(PresenceId) of 'true' -> Default; 'false' -> maybe_fix_presence_id_realm(PresenceId, Endpoint, Call) end. -spec maybe_fix_presence_id_realm(ne_binary(), wh_json:object(), whapps_call:call()) -> ne_binary(). maybe_fix_presence_id_realm(PresenceId, Endpoint, Call) -> case binary:match(PresenceId, <<"@">>) of 'nomatch' -> Realm = cf_util:get_sip_realm( Endpoint ,whapps_call:account_id(Call) ,whapps_call:request_realm(Call) ), <<PresenceId/binary, $@, Realm/binary>>; _Else -> PresenceId end. %%----------------------------------------------------------------------------- @public %% @doc %% @end %%----------------------------------------------------------------------------- -spec owned_by(api_binary(), whapps_call:call()) -> api_binaries(). -spec owned_by(api_binary() | api_binaries(), ne_binary(), whapps_call:call()) -> api_binaries(). owned_by('undefined', _) -> []; owned_by(OwnerId, Call) -> AccountDb = whapps_call:account_db(Call), ViewOptions = [{'startkey', [OwnerId]} ,{'endkey', [OwnerId, wh_json:new()]} ], case couch_mgr:get_results(AccountDb, <<"cf_attributes/owned">>, ViewOptions) of {'ok', JObjs} -> [wh_json:get_value(<<"value">>, JObj) || JObj <- JObjs]; {'error', _R} -> lager:warning("unable to find documents owned by ~s: ~p", [OwnerId, _R]), [] end. owned_by('undefined', _, _) -> []; owned_by([_|_]=OwnerIds, Type, Call) -> Keys = [[OwnerId, Type] || OwnerId <- OwnerIds], owned_by_query([{'keys', Keys}], Call); owned_by(OwnerId, Type, Call) -> owned_by_query([{'key', [OwnerId, Type]}], Call). -spec owned_by_docs(api_binary(), whapps_call:call()) -> api_objects(). -spec owned_by_docs(api_binary() | api_binaries(), ne_binary(), whapps_call:call()) -> api_objects(). owned_by_docs('undefined', _) -> []; owned_by_docs(OwnerId, Call) -> AccountDb = whapps_call:account_db(Call), ViewOptions = [{'startkey', [OwnerId]} ,{'endkey', [OwnerId, wh_json:new()]} ,'include_docs' ], case couch_mgr:get_results(AccountDb, <<"cf_attributes/owned">>, ViewOptions) of {'ok', JObjs} -> [wh_json:get_value(<<"doc">>, JObj) || JObj <- JObjs]; {'error', _R} -> lager:warning("unable to find documents owned by ~s: ~p", [OwnerId, _R]), [] end. owned_by_docs('undefined', _, _) -> []; owned_by_docs([_|_]=OwnerIds, Type, Call) -> Keys = [[OwnerId, Type] || OwnerId <- OwnerIds], owned_by_query([{'keys', Keys}, 'include_docs'], Call, <<"doc">>); owned_by_docs(OwnerId, Type, Call) -> owned_by_query([{'key', [OwnerId, Type]}, 'include_docs'], Call, <<"doc">>). -spec owned_by_query(list(), whapps_call:call()) -> api_binaries(). -spec owned_by_query(list(), whapps_call:call(), ne_binary()) -> api_binaries(). owned_by_query(ViewOptions, Call) -> owned_by_query(ViewOptions, Call, <<"value">>). owned_by_query(ViewOptions, Call, ViewKey) -> AccountDb = whapps_call:account_db(Call), case couch_mgr:get_results(AccountDb, <<"cf_attributes/owned">>, ViewOptions) of {'ok', JObjs} -> [wh_json:get_value(ViewKey, JObj) || JObj <- JObjs]; {'error', _R} -> lager:warning("unable to find owned documents (~p) using ~p", [_R, ViewOptions]), [] end. %%----------------------------------------------------------------------------- @private %% @doc %% @end %%----------------------------------------------------------------------------- -spec default_cid_number() -> ne_binary(). default_cid_number() -> whapps_config:get( ?CF_CONFIG_CAT ,<<"default_caller_id_number">> ,wh_util:anonymous_caller_id_number() ). -spec default_cid_name(wh_json:object()) -> ne_binary(). default_cid_name(Endpoint) -> case wh_json:get_ne_value(<<"name">>, Endpoint) of 'undefined' -> whapps_config:get( ?CF_CONFIG_CAT ,<<"default_caller_id_name">> ,wh_util:anonymous_caller_id_name() ); Name -> Name end. -spec get_cid_or_default(ne_binary(), ne_binary(), wh_json:object()) -> api_binary(). get_cid_or_default(<<"emergency">>, Property, Endpoint) -> case wh_json:get_first_defined([[<<"caller_id">>, <<"emergency">>, Property] ,[<<"caller_id">>, <<"external">>, Property] ], Endpoint) of 'undefined' -> wh_json:get_ne_value([<<"default">>, Property], Endpoint); Value -> Value end; get_cid_or_default(Attribute, Property, Endpoint) -> case wh_json:get_ne_value([<<"caller_id">>, Attribute, Property], Endpoint) of 'undefined' -> wh_json:get_ne_value([<<"default">>, Property], Endpoint); Value -> Value end.
null
https://raw.githubusercontent.com/urueedi/monster-ui-phonebook/00b1b54996785d7a67fa902a46c82ead12ef022b/kazoo-3/applications/callflows/cf_attributes.erl
erlang
------------------------------------------------------------------- @doc @end @contributors ------------------------------------------------------------------- ----------------------------------------------------------------------------- @doc @end ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- @doc @end ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- @doc @end ----------------------------------------------------------------------------- This could optionally cycle all found numbers and ensure they valid but that could be a lot of wasted db lookups... ----------------------------------------------------------------------------- @doc @end ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- @doc @end ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- @doc @end ----------------------------------------------------------------------------- -------------------------------------------------------------------- @doc This function will return the precense id for the endpoint @end -------------------------------------------------------------------- ----------------------------------------------------------------------------- @doc @end ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- @doc @end -----------------------------------------------------------------------------
( C ) 2011 - 2014 , 2600Hz INC -module(cf_attributes). -include("callflow.hrl"). -export([temporal_rules/1]). -export([groups/1, groups/2]). -export([caller_id/2]). -export([callee_id/2]). -export([moh_attributes/2, moh_attributes/3]). -export([owner_id/1, owner_id/2]). -export([presence_id/1, presence_id/2]). -export([owned_by/2, owned_by/3 ,owned_by_docs/2, owned_by_docs/3 ]). -export([owner_ids/2]). -export([maybe_get_assigned_number/3]). -export([maybe_get_account_default_number/4]). @public -spec temporal_rules(whapps_call:call()) -> wh_json:objects(). temporal_rules(Call) -> AccountDb = whapps_call:account_db(Call), case couch_mgr:get_results(AccountDb, <<"cf_attributes/temporal_rules">>, ['include_docs']) of {'ok', JObjs} -> JObjs; {'error', _E} -> lager:debug("failed to find temporal rules: ~p", [_E]), [] end. @public -spec groups(whapps_call:call()) -> wh_json:objects(). -spec groups(whapps_call:call(), wh_proplist()) -> wh_json:objects(). groups(Call) -> groups(Call, []). groups(Call, ViewOptions) -> AccountDb = whapps_call:account_db(Call), case couch_mgr:get_results(AccountDb, <<"cf_attributes/groups">>, ViewOptions) of {'ok', JObjs} -> JObjs; {'error', _} -> [] end. @public -spec caller_id(ne_binary(), whapps_call:call()) -> {api_binary(), api_binary()}. caller_id(Attribute, Call) -> lager:debug("debug of call variables:~p", [Call]), CCVs = whapps_call:custom_channel_vars(Call), Inception = whapps_call:inception(Call), AccountId = whapps_call:account_id(Call), Name = whapps_call:caller_id_name(Call), CidFormat = whapps_call:callerid_format(Call), CidPrefix = whapps_call:callerid_prefix(Call), E164 = wnm_util:to_e164(whapps_call:caller_id_number(Call), AccountId), Int = wnm_util:e164_tointernational(E164), case CidFormat of 'e164' -> CallerId = E164; 'international' -> CallerId = Int; 'national' -> CallerId = wnm_util:e164_tonational(E164); 'local' -> CallerId = wnm_util:e164_tonational(E164); 'nochange' -> CallerId = whapps_call:caller_id_number(Call); [] -> CallerId = E164; 'nomatch' -> CallerId = E164; 'undefined' -> CallerId = E164 end, lager:info("caller id convert to format Name:<~s> CLID:~s, Cid-Format:~s CidPrefix:~s", [Name, CallerId, CidFormat, CidPrefix]), case (Inception =/= 'undefined' andalso not wh_json:is_true(<<"Call-Forward">>, CCVs)) orelse wh_json:is_true(<<"Retain-CID">>, CCVs) of 'true' -> maybe_normalize_cid(CallerId, Name, 'false', Attribute, Call); 'false' -> maybe_get_dynamic_cid('true', Attribute, Call) end. -spec maybe_get_dynamic_cid(boolean(), ne_binary(), whapps_call:call()) -> {api_binary(), api_binary()}. maybe_get_dynamic_cid(Validate, Attribute, Call) -> case whapps_call:kvs_fetch('dynamic_cid', Call) of 'undefined' -> maybe_get_endpoint_cid(Validate, Attribute, Call); DynamicCID -> lager:debug("found dynamic caller id number ~s", [DynamicCID]), maybe_normalize_cid(DynamicCID, 'undefined', Validate, Attribute, Call) end. -spec maybe_get_endpoint_cid(boolean(), ne_binary(), whapps_call:call()) -> {api_binary(), api_binary()}. maybe_get_endpoint_cid(Validate, Attribute, Call) -> case cf_endpoint:get(Call) of {'error', _R} -> lager:info("unable to get endpoint: ~p", [_R]), maybe_normalize_cid('undefined', 'undefined', Validate, Attribute, Call); {'ok', JObj} -> Number = get_cid_or_default(Attribute, <<"number">>, JObj), Name = get_cid_or_default(Attribute, <<"name">>, JObj), _ = log_configured_endpoint_cid(Attribute, Name, Number), maybe_use_presence_number(Number, Name, JObj, Validate, Attribute, Call) end. -spec log_configured_endpoint_cid(ne_binary(), api_binary(), api_binary()) -> 'ok'. log_configured_endpoint_cid(Attribute, 'undefined', 'undefined') -> lager:debug("endpoint not configured with an ~s caller id", [Attribute]); log_configured_endpoint_cid(Attribute, Name, 'undefined') -> lager:debug("endpoint configured with ~s caller id name ~s", [Attribute, Name]); log_configured_endpoint_cid(Attribute, 'undefined', Number) -> lager:debug("endpoint configured with ~s caller id number ~s", [Attribute, Number]); log_configured_endpoint_cid(Attribute, Name, Number) -> lager:debug("endpoint configured with ~s caller id <~s> ~s", [Attribute, Name, Number]). -spec maybe_use_presence_number(api_binary(), api_binary(), wh_json:object(), boolean(), ne_binary(), whapps_call:call()) -> {api_binary(), api_binary()}. maybe_use_presence_number('undefined', Name, Endpoint, Validate, <<"internal">> = Attribute, Call) -> case maybe_get_presence_number(Endpoint, Call) of 'undefined' -> maybe_normalize_cid('undefined', Name, Validate, Attribute, Call); Number -> lager:debug("replacing empty caller id number with presence number ~s", [Number]), maybe_normalize_cid(Number, Name, Validate, Attribute, Call) end; maybe_use_presence_number(Number, Name, _Endpoint, Validate, Attribute, Call) -> maybe_normalize_cid(Number, Name, Validate, Attribute, Call). -spec maybe_normalize_cid(api_binary(), api_binary(), boolean(), ne_binary(), whapps_call:call()) -> {api_binary(), api_binary()}. maybe_normalize_cid('undefined', Name, Validate, Attribute, Call) -> Number = whapps_call:caller_id_number(Call), lager:debug("replacing empty caller id number with SIP caller id number ~s", [Number]), maybe_normalize_cid(Number, Name, Validate, Attribute, Call); maybe_normalize_cid(Number, 'undefined', Validate, Attribute, Call) -> Name = whapps_call:caller_id_name(Call), lager:debug("replacing empty caller id name with SIP caller id name ~s", [Name]), maybe_normalize_cid(Number, Name, Validate, Attribute, Call); maybe_normalize_cid(Number, Name, Validate, Attribute, Call) -> maybe_prefix_cid_number(wh_util:to_binary(Number), Name, Validate, Attribute, Call). -spec maybe_prefix_cid_number(ne_binary(), ne_binary(), boolean(), ne_binary(), whapps_call:call()) -> {api_binary(), api_binary()}. maybe_prefix_cid_number(Number, Name, Validate, Attribute, Call) -> case whapps_call:kvs_fetch('prepend_cid_number', Call) of 'undefined' -> maybe_suffix_cid_number(Number, Name, Validate, Attribute, Call); Prefix -> lager:debug("prepending caller id number with ~s", [Prefix]), Prefixed = <<(wh_util:to_binary(Prefix))/binary, Number/binary>>, maybe_suffix_cid_number(Prefixed, Name, Validate, Attribute, Call) end. -spec maybe_suffix_cid_number(ne_binary(), ne_binary(), boolean(), ne_binary(), whapps_call:call()) -> {api_binary(), api_binary()}. maybe_suffix_cid_number(Number, Name, Validate, Attribute, Call) -> case whapps_call:kvs_fetch('suffix_cid_number', Call) of 'undefined' -> maybe_prefix_cid_name(Number, Name, Validate, Attribute, Call); Suffix -> lager:debug("suffixing caller id number with ~s", [Suffix]), Suffixed = <<Number/binary, (wh_util:to_binary(Suffix))/binary>>, lager:debug("caller id number with ~s", [Suffixed]), maybe_prefix_cid_name(Suffixed, Name, Validate, Attribute, Call) end. -spec maybe_prefix_cid_name(ne_binary(), ne_binary(), boolean(), ne_binary(), whapps_call:call()) -> {api_binary(), api_binary()}. maybe_prefix_cid_name(Number, Name, Validate, Attribute, Call) -> case whapps_call:kvs_fetch('prepend_cid_name', Call) of 'undefined' -> maybe_rewrite_cid_number(Number, Name, Validate, Attribute, Call); Prefix -> lager:debug("prepending caller id name with ~s", [Prefix]), Prefixed = <<(wh_util:to_binary(Prefix))/binary, Name/binary>>, maybe_rewrite_cid_number(Number, Prefixed, Validate, Attribute, Call) end. -spec maybe_rewrite_cid_number(ne_binary(), ne_binary(), boolean(), ne_binary(), whapps_call:call()) -> {api_binary(), api_binary()}. maybe_rewrite_cid_number(Number, Name, Validate, Attribute, Call) -> case whapps_call:kvs_fetch('rewrite_cid_number', Call) of 'undefined' -> maybe_rewrite_cid_name(Number, Name, Validate, Attribute, Call); NewNumber -> lager:debug("reformating caller id number from ~s to ~s", [Number, NewNumber]), maybe_rewrite_cid_name(NewNumber, Name, Validate, Attribute, Call) end. -spec maybe_rewrite_cid_name(ne_binary(), ne_binary(), boolean(), ne_binary(), whapps_call:call()) -> {api_binary(), api_binary()}. maybe_rewrite_cid_name(Number, Name, Validate, Attribute, Call) -> case whapps_call:kvs_fetch('rewrite_cid_name', Call) of 'undefined' -> maybe_ensure_cid_valid(Number, Name, Validate, Attribute, Call); NewName -> lager:debug("reformating caller id name from ~s to ~s", [Name, NewName]), maybe_ensure_cid_valid(Number, NewName, Validate, Attribute, Call) end. -spec maybe_ensure_cid_valid(ne_binary(), ne_binary(), boolean(), ne_binary(), whapps_call:call()) -> {api_binary(), api_binary()}. maybe_ensure_cid_valid(Number, Name, 'true', <<"emergency">>, _Call) -> lager:info("determined emergency caller id is <~s> ~s", [Name, Number]), {Number, Name}; maybe_ensure_cid_valid(Number, Name, 'true', <<"external">>, Call) -> case whapps_config:get_is_true(<<"callflow">>, <<"ensure_valid_caller_id">>, 'false') of 'true' -> ensure_valid_caller_id(Number, Name, Call); 'false' -> lager:info("determined external caller id is <~s> ~s", [Name, Number]), maybe_cid_privacy(Number, Name, Call) end; maybe_ensure_cid_valid(Number, Name, _, Attribute, Call) -> lager:info("determined ~s caller id is <~s> ~s", [Attribute, Name, Number]), maybe_cid_privacy(Number, Name, Call). -spec maybe_cid_privacy(api_binary(), api_binary(), whapps_call:call()) -> {api_binary(), api_binary()}. maybe_cid_privacy(Number, Name, Call) -> case wh_util:is_true(whapps_call:kvs_fetch('cf_privacy', Call)) of 'true' -> lager:info("overriding caller id to maintain privacy"), {whapps_config:get_non_empty( <<"callflow">> ,<<"privacy_number">> ,wh_util:anonymous_caller_id_number() ) ,whapps_config:get_non_empty( <<"callflow">> ,<<"privacy_name">> ,wh_util:anonymous_caller_id_name() ) }; 'false' -> {Number, Name} end. -spec ensure_valid_caller_id(ne_binary(), ne_binary(), whapps_call:call()) -> {api_binary(), api_binary()}. ensure_valid_caller_id(Number, Name, Call) -> case is_valid_caller_id(Number, Call) of 'true' -> lager:info("determined valid external caller id is <~s> ~s", [Name, Number]), {Number, Name}; 'false' -> lager:info("invalid external caller id <~s> ~s", [Name, Number]), maybe_get_account_cid(Number, Name, Call) end. -spec maybe_get_account_cid(ne_binary(), ne_binary(), whapps_call:call()) -> {api_binary(), api_binary()}. maybe_get_account_cid(Number, Name, Call) -> case kz_account:fetch(whapps_call:account_id(Call)) of {'error', _} -> maybe_get_assigned_number(Number, Name, Call); {'ok', JObj} -> maybe_get_account_external_number(Number, Name, JObj, Call) end. -spec maybe_get_account_external_number(ne_binary(), ne_binary(), wh_json:object(), whapps_call:call()) -> {api_binary(), api_binary()}. maybe_get_account_external_number(Number, Name, Account, Call) -> External = wh_json:get_ne_value([<<"caller_id">>, <<"external">>, <<"number">>], Account), case is_valid_caller_id(External, Call) of 'true' -> lager:info("determined valid account external caller id is <~s> ~s", [Name, Number]), {External, Name}; 'false' -> maybe_get_account_default_number(Number, Name, Account, Call) end. -spec maybe_get_account_default_number(ne_binary(), ne_binary(), wh_json:object(), whapps_call:call()) -> {api_binary(), api_binary()}. maybe_get_account_default_number(Number, Name, Account, Call) -> Default = wh_json:get_ne_value([<<"caller_id">>, <<"default">>, <<"number">>], Account), case is_valid_caller_id(Default, Call) of 'true' -> lager:info("determined valid account default caller id is <~s> ~s", [Name, Number]), {Default, Name}; 'false' -> maybe_get_assigned_number(Number, Name, Call) end. -spec maybe_get_assigned_number(ne_binary(), ne_binary(), whapps_call:call()) -> {api_binary(), api_binary()}. maybe_get_assigned_number(_, Name, Call) -> AccountDb = whapps_call:account_db(Call), case couch_mgr:open_cache_doc(AccountDb, ?WNM_PHONE_NUMBER_DOC) of {'error', _R} -> Number = default_cid_number(), lager:warning("could not open phone_numbers doc <~s> ~s: ~p", [Name, Number, _R]), {Number, Name}; {'ok', JObj} -> PublicJObj = wh_json:public_fields(JObj), Numbers = [Num || Num <- wh_json:get_keys(PublicJObj) ,Num =/= <<"id">> ,(not wh_json:is_true([Num, <<"on_subaccount">>], JObj)) ,(wh_json:get_value([Num, <<"state">>], JObj) =:= ?NUMBER_STATE_IN_SERVICE) ], maybe_get_assigned_numbers(Numbers, Name, Call) end. -spec maybe_get_assigned_numbers(ne_binaries(), ne_binary(), whapps_call:call()) -> {api_binary(), api_binary()}. maybe_get_assigned_numbers([], Name, _) -> Number = default_cid_number(), lager:info("failed to find any in-service numbers, using default <~s> ~s", [Name, Number]), {Number, Name}; maybe_get_assigned_numbers([Number|_], Name, _) -> lager:info("using first assigned number caller id <~s> ~s", [Name, Number]), {Number, Name}. -spec is_valid_caller_id(api_binary(), whapps_call:call()) -> boolean(). is_valid_caller_id('undefined', _) -> 'false'; is_valid_caller_id(Number, Call) -> AccountId = whapps_call:account_id(Call), case wh_number_manager:lookup_account_by_number(Number) of {'ok', AccountId, _} -> 'true'; _Else -> 'false' end. -spec maybe_get_presence_number(wh_json:object(), whapps_call:call()) -> api_binary(). maybe_get_presence_number(Endpoint, Call) -> case presence_id(Endpoint, Call, 'undefined') of 'undefined' -> 'undefined'; PresenceId -> case binary:split(PresenceId, <<"@">>) of [PresenceNumber, _] -> PresenceNumber; [_Else] -> PresenceId end end. @public -spec callee_id(api_binary() | wh_json:object(), whapps_call:call()) -> {api_binary(), api_binary()}. callee_id(EndpointId, Call) when is_binary(EndpointId) -> case cf_endpoint:get(EndpointId, Call) of {'ok', Endpoint} -> callee_id(Endpoint, Call); {'error', _R} -> maybe_normalize_callee('undefined', 'undefined', wh_json:new(), Call) end; callee_id(Endpoint, Call) -> Attribute = determine_callee_attribute(Call), Number = get_cid_or_default(Attribute, <<"number">>, Endpoint), Name = get_cid_or_default(Attribute, <<"name">>, Endpoint), maybe_normalize_callee(Number, Name, Endpoint, Call). -spec maybe_normalize_callee(api_binary(), api_binary(), wh_json:object(), whapps_call:call()) -> {api_binary(), api_binary()}. maybe_normalize_callee('undefined', Name, Endpoint, Call) -> maybe_normalize_callee(whapps_call:request_user(Call), Name, Endpoint, Call); maybe_normalize_callee(Number, 'undefined', Endpoint, Call) -> maybe_normalize_callee(Number, default_cid_name(Endpoint), Endpoint, Call); maybe_normalize_callee(Number, Name, _, _) -> lager:info("callee id <~s> ~s", [Name, Number]), {Number, Name}. -spec determine_callee_attribute(whapps_call:call()) -> ne_binary(). determine_callee_attribute(Call) -> case whapps_call:inception(Call) =/= 'undefined' of 'true' -> <<"external">>; 'false' -> <<"internal">> end. @public -spec moh_attributes(ne_binary(), whapps_call:call()) -> api_binary(). -spec moh_attributes(api_binary() | wh_json:object(), ne_binary(), whapps_call:call()) -> api_binary(). moh_attributes(Attribute, Call) -> case cf_endpoint:get(Call) of {'error', _R} -> 'undefined'; {'ok', Endpoint} -> Value = wh_json:get_ne_value([<<"music_on_hold">>, Attribute], Endpoint), maybe_normalize_moh_attribute(Value, Attribute, Call) end. moh_attributes('undefined', _, _) -> 'undefined'; moh_attributes(EndpointId, Attribute, Call) when is_binary(EndpointId) -> case cf_endpoint:get(EndpointId, Call) of {'error', _} -> 'undefined'; {'ok', Endpoint} -> Value = wh_json:get_ne_value([<<"music_on_hold">>, Attribute], Endpoint), maybe_normalize_moh_attribute(Value, Attribute, Call) end; moh_attributes(Endpoint, Attribute, Call) -> Value = wh_json:get_ne_value([<<"music_on_hold">>, Attribute], Endpoint), maybe_normalize_moh_attribute(Value, Attribute, Call). -spec maybe_normalize_moh_attribute(api_binary(), ne_binary(), whapps_call:call()) -> api_binary(). maybe_normalize_moh_attribute('undefined', _, _) -> 'undefined'; maybe_normalize_moh_attribute(Value, <<"media_id">>, Call) -> MediaId = cf_util:correct_media_path(Value, Call), lager:info("found music_on_hold media_id: '~p'", [MediaId]), MediaId; maybe_normalize_moh_attribute(Value, Attribute, _) -> lager:info("found music_on_hold ~s: '~p'", [Attribute, Value]), Value. @public -spec owner_id(whapps_call:call()) -> api_binary(). -spec owner_id(api_binary(), whapps_call:call()) -> api_binary(). owner_id(Call) -> case cf_endpoint:get(Call) of {'error', _} -> 'undefined'; {'ok', Endpoint} -> case wh_json:get_ne_value(<<"owner_id">>, Endpoint) of 'undefined' -> 'undefined'; OwnerId -> lager:info("initiating endpoint is owned by ~s", [OwnerId]), OwnerId end end. owner_id('undefined', _Call) -> 'undefined'; owner_id(ObjectId, Call) -> AccountDb = whapps_call:account_db(Call), ViewOptions = [{'key', ObjectId}], case couch_mgr:get_results(AccountDb, <<"cf_attributes/owner">>, ViewOptions) of {'ok', [JObj]} -> wh_json:get_value(<<"value">>, JObj); {'ok', []} -> 'undefined'; {'ok', [_|_]=JObjs} -> Owners = [wh_json:get_value(<<"value">>, JObj) || JObj <- JObjs], lager:debug("object ~s has multiple owners: ~-500p", [ObjectId, Owners]), 'undefined'; {'error', _R} -> lager:warning("unable to find owner for ~s: ~p", [ObjectId, _R]), 'undefined' end. owner_ids('undefined', _Call) -> []; owner_ids(ObjectId, Call) -> AccountDb = whapps_call:account_db(Call), ViewOptions = [{'key', ObjectId}], case couch_mgr:get_results(AccountDb, <<"cf_attributes/owner">>, ViewOptions) of {'ok', []} -> []; {'ok', [JObj]} -> [wh_json:get_value(<<"value">>, JObj)]; {'ok', [_|_]=JObjs} -> [wh_json:get_value(<<"value">>, JObj) || JObj <- JObjs]; {'error', _R} -> lager:warning("unable to find owner for ~s: ~p", [ObjectId, _R]), [] end. @public -spec presence_id(whapps_call:call()) -> api_binary(). presence_id(Call) -> presence_id(whapps_call:authorizing_id(Call), Call). -spec presence_id(api_binary() | wh_json:object(), whapps_call:call()) -> api_binary(). presence_id(EndpointId, Call) when is_binary(EndpointId) -> case cf_endpoint:get(EndpointId, Call) of {'ok', Endpoint} -> presence_id(Endpoint, Call); {'error', _} -> 'undefined' end; presence_id(Endpoint, Call) -> Username = kz_device:sip_username(Endpoint, whapps_call:request_user(Call)), presence_id(Endpoint, Call, Username). -spec presence_id(wh_json:object(), whapps_call:call(), Default) -> ne_binary() | Default. presence_id(Endpoint, Call, Default) -> PresenceId = kz_device:presence_id(Endpoint, Default), case wh_util:is_empty(PresenceId) of 'true' -> Default; 'false' -> maybe_fix_presence_id_realm(PresenceId, Endpoint, Call) end. -spec maybe_fix_presence_id_realm(ne_binary(), wh_json:object(), whapps_call:call()) -> ne_binary(). maybe_fix_presence_id_realm(PresenceId, Endpoint, Call) -> case binary:match(PresenceId, <<"@">>) of 'nomatch' -> Realm = cf_util:get_sip_realm( Endpoint ,whapps_call:account_id(Call) ,whapps_call:request_realm(Call) ), <<PresenceId/binary, $@, Realm/binary>>; _Else -> PresenceId end. @public -spec owned_by(api_binary(), whapps_call:call()) -> api_binaries(). -spec owned_by(api_binary() | api_binaries(), ne_binary(), whapps_call:call()) -> api_binaries(). owned_by('undefined', _) -> []; owned_by(OwnerId, Call) -> AccountDb = whapps_call:account_db(Call), ViewOptions = [{'startkey', [OwnerId]} ,{'endkey', [OwnerId, wh_json:new()]} ], case couch_mgr:get_results(AccountDb, <<"cf_attributes/owned">>, ViewOptions) of {'ok', JObjs} -> [wh_json:get_value(<<"value">>, JObj) || JObj <- JObjs]; {'error', _R} -> lager:warning("unable to find documents owned by ~s: ~p", [OwnerId, _R]), [] end. owned_by('undefined', _, _) -> []; owned_by([_|_]=OwnerIds, Type, Call) -> Keys = [[OwnerId, Type] || OwnerId <- OwnerIds], owned_by_query([{'keys', Keys}], Call); owned_by(OwnerId, Type, Call) -> owned_by_query([{'key', [OwnerId, Type]}], Call). -spec owned_by_docs(api_binary(), whapps_call:call()) -> api_objects(). -spec owned_by_docs(api_binary() | api_binaries(), ne_binary(), whapps_call:call()) -> api_objects(). owned_by_docs('undefined', _) -> []; owned_by_docs(OwnerId, Call) -> AccountDb = whapps_call:account_db(Call), ViewOptions = [{'startkey', [OwnerId]} ,{'endkey', [OwnerId, wh_json:new()]} ,'include_docs' ], case couch_mgr:get_results(AccountDb, <<"cf_attributes/owned">>, ViewOptions) of {'ok', JObjs} -> [wh_json:get_value(<<"doc">>, JObj) || JObj <- JObjs]; {'error', _R} -> lager:warning("unable to find documents owned by ~s: ~p", [OwnerId, _R]), [] end. owned_by_docs('undefined', _, _) -> []; owned_by_docs([_|_]=OwnerIds, Type, Call) -> Keys = [[OwnerId, Type] || OwnerId <- OwnerIds], owned_by_query([{'keys', Keys}, 'include_docs'], Call, <<"doc">>); owned_by_docs(OwnerId, Type, Call) -> owned_by_query([{'key', [OwnerId, Type]}, 'include_docs'], Call, <<"doc">>). -spec owned_by_query(list(), whapps_call:call()) -> api_binaries(). -spec owned_by_query(list(), whapps_call:call(), ne_binary()) -> api_binaries(). owned_by_query(ViewOptions, Call) -> owned_by_query(ViewOptions, Call, <<"value">>). owned_by_query(ViewOptions, Call, ViewKey) -> AccountDb = whapps_call:account_db(Call), case couch_mgr:get_results(AccountDb, <<"cf_attributes/owned">>, ViewOptions) of {'ok', JObjs} -> [wh_json:get_value(ViewKey, JObj) || JObj <- JObjs]; {'error', _R} -> lager:warning("unable to find owned documents (~p) using ~p", [_R, ViewOptions]), [] end. @private -spec default_cid_number() -> ne_binary(). default_cid_number() -> whapps_config:get( ?CF_CONFIG_CAT ,<<"default_caller_id_number">> ,wh_util:anonymous_caller_id_number() ). -spec default_cid_name(wh_json:object()) -> ne_binary(). default_cid_name(Endpoint) -> case wh_json:get_ne_value(<<"name">>, Endpoint) of 'undefined' -> whapps_config:get( ?CF_CONFIG_CAT ,<<"default_caller_id_name">> ,wh_util:anonymous_caller_id_name() ); Name -> Name end. -spec get_cid_or_default(ne_binary(), ne_binary(), wh_json:object()) -> api_binary(). get_cid_or_default(<<"emergency">>, Property, Endpoint) -> case wh_json:get_first_defined([[<<"caller_id">>, <<"emergency">>, Property] ,[<<"caller_id">>, <<"external">>, Property] ], Endpoint) of 'undefined' -> wh_json:get_ne_value([<<"default">>, Property], Endpoint); Value -> Value end; get_cid_or_default(Attribute, Property, Endpoint) -> case wh_json:get_ne_value([<<"caller_id">>, Attribute, Property], Endpoint) of 'undefined' -> wh_json:get_ne_value([<<"default">>, Property], Endpoint); Value -> Value end.
748da555458e696463741ec8d4a684b022cd5de5e9a1adc9699a2de319af1f12
rd--/hsc3
sumSqr.help.hs
-- sumSqr let o1 = fSinOsc ar 800 0 o2 = fSinOsc ar (xLine kr 200 500 5 DoNothing) 0 in sumSqr o1 o2 * 0.125 -- sumSqr ; written out let o1 = fSinOsc ar 800 0 o2 = fSinOsc ar (xLine kr 200 500 5 DoNothing) 0 in (o1 * o1 + o2 * o2) * 0.125
null
https://raw.githubusercontent.com/rd--/hsc3/60cb422f0e2049f00b7e15076b2667b85ad8f638/Help/Ugen/sumSqr.help.hs
haskell
sumSqr sumSqr ; written out
let o1 = fSinOsc ar 800 0 o2 = fSinOsc ar (xLine kr 200 500 5 DoNothing) 0 in sumSqr o1 o2 * 0.125 let o1 = fSinOsc ar 800 0 o2 = fSinOsc ar (xLine kr 200 500 5 DoNothing) 0 in (o1 * o1 + o2 * o2) * 0.125
b7a882b2409eb2704bce22b7302b62235ab4660c2c2e5a4c48025b2232921eff
xu-hao/QueryArrow
GenericDatabase.hs
# LANGUAGE TypeFamilies # module QueryArrow.DB.GenericDatabase where import QueryArrow.Syntax.Term import QueryArrow.DB.DB import QueryArrow.Semantics.TypeChecker import Data.Set data GenericDatabase db a = GenericDatabase db a String [Pred] class IGenericDatabase01 db where type GDBQueryType db type GDBFormulaType db gSupported :: db -> Set Var -> GDBFormulaType db -> Set Var -> Bool gTranslateQuery :: db -> Set Var -> GDBFormulaType db -> Set Var -> IO (GDBQueryType db) instance (IGenericDatabase01 db) => IDatabase0 (GenericDatabase db a) where type DBFormulaType (GenericDatabase db a) = GDBFormulaType db getName (GenericDatabase _ _ name _) = name getPreds (GenericDatabase _ _ _ preds) = preds supported (GenericDatabase db _ _ _) = gSupported db instance (IGenericDatabase01 db) => IDatabase1 (GenericDatabase db a) where type DBQueryType (GenericDatabase db a) = GDBQueryType db translateQuery (GenericDatabase db _ _ _) = gTranslateQuery db
null
https://raw.githubusercontent.com/xu-hao/QueryArrow/4dd5b8a22c8ed2d24818de5b8bcaa9abc456ef0d/QueryArrow-common/src/QueryArrow/DB/GenericDatabase.hs
haskell
# LANGUAGE TypeFamilies # module QueryArrow.DB.GenericDatabase where import QueryArrow.Syntax.Term import QueryArrow.DB.DB import QueryArrow.Semantics.TypeChecker import Data.Set data GenericDatabase db a = GenericDatabase db a String [Pred] class IGenericDatabase01 db where type GDBQueryType db type GDBFormulaType db gSupported :: db -> Set Var -> GDBFormulaType db -> Set Var -> Bool gTranslateQuery :: db -> Set Var -> GDBFormulaType db -> Set Var -> IO (GDBQueryType db) instance (IGenericDatabase01 db) => IDatabase0 (GenericDatabase db a) where type DBFormulaType (GenericDatabase db a) = GDBFormulaType db getName (GenericDatabase _ _ name _) = name getPreds (GenericDatabase _ _ _ preds) = preds supported (GenericDatabase db _ _ _) = gSupported db instance (IGenericDatabase01 db) => IDatabase1 (GenericDatabase db a) where type DBQueryType (GenericDatabase db a) = GDBQueryType db translateQuery (GenericDatabase db _ _ _) = gTranslateQuery db
fbf3a0f81d87390d6d7af365682cf1507a435937dcec839b785ae4eb76571832
geophf/1HaskellADay
Exercise.hs
module Y2020.M10.D26.Exercise where - Great ! We have the airbases of the world . At some point we will want to look at alliances of the world : But FRIST ! ... let 's export our graph as a set of cypher statements - Great! We have the airbases of the world. At some point we will want to look at alliances of the world: But FRIST! ... let's export our graph as a set of cypher statements --} import Data.Map (Map) import Data.Set (Set) import Graph.Query import Graph.JSON.Cypher import Y2020.M10.D12.Solution -- to load the airbases import Y2020.M10.D14.Solution -- to load countries-continents import Y2020.M10.D15.Solution -- for the country map import Y2020.M10.D16.Solution -- cyphed countries-continents import Y2020.M10.D20.Solution -- for cyphed stuff import Y2020.M10.D23.Solution -- for ununicoded base names -- and a loader, free of charge: loadAll :: IO (Map Icao AirBase, CountryMap, Set Country, Set Country) loadAll = loadBases (Y2020.M10.D12.Solution.workingDir ++ file) >>= \bs -> countriesByContinent (Y2020.M10.D14.Solution.workingDir ++ cbc) >>= \conti -> let cm = countryMap conti mbs = byICAO bs newabm = firstPass mbs ccs = countries fst cm abc = countries (country . snd) newabm nonu = stripNonAscii newabm in return (nonu, cm, ccs, abc) -- With the above, you should be able to implement the following countriesCypher :: CountryMap -> [Cypher] countriesCypher = undefined countriesCorrections :: Set Country -> Set Country -> [Cypher] countriesCorrections = undefined airbaseCypher :: Map Icao AirBase -> [Cypher] airbaseCypher = undefined saveCypher :: FilePath -> [Cypher] -> IO () saveCypher = undefined -- so we should be able to run this, no problems: go :: IO () go = loadAll >>= \(abm, cm, ccs, abc) -> saveCypher "01-raw-countries.cyp" (countriesCypher cm) >> putStrLn "Saved countries" >> saveCypher "02-countries-corrections.cyp" (countriesCorrections ccs abc) >> putStrLn "Saved corrections" >> saveCypher "03-airbases.cyp" (airbaseCypher abm) >> putStrLn "Yeah. We're done."
null
https://raw.githubusercontent.com/geophf/1HaskellADay/514792071226cd1e2ba7640af942667b85601006/exercises/HAD/Y2020/M10/D26/Exercise.hs
haskell
} to load the airbases to load countries-continents for the country map cyphed countries-continents for cyphed stuff for ununicoded base names and a loader, free of charge: With the above, you should be able to implement the following so we should be able to run this, no problems:
module Y2020.M10.D26.Exercise where - Great ! We have the airbases of the world . At some point we will want to look at alliances of the world : But FRIST ! ... let 's export our graph as a set of cypher statements - Great! We have the airbases of the world. At some point we will want to look at alliances of the world: But FRIST! ... let's export our graph as a set of cypher statements import Data.Map (Map) import Data.Set (Set) import Graph.Query import Graph.JSON.Cypher loadAll :: IO (Map Icao AirBase, CountryMap, Set Country, Set Country) loadAll = loadBases (Y2020.M10.D12.Solution.workingDir ++ file) >>= \bs -> countriesByContinent (Y2020.M10.D14.Solution.workingDir ++ cbc) >>= \conti -> let cm = countryMap conti mbs = byICAO bs newabm = firstPass mbs ccs = countries fst cm abc = countries (country . snd) newabm nonu = stripNonAscii newabm in return (nonu, cm, ccs, abc) countriesCypher :: CountryMap -> [Cypher] countriesCypher = undefined countriesCorrections :: Set Country -> Set Country -> [Cypher] countriesCorrections = undefined airbaseCypher :: Map Icao AirBase -> [Cypher] airbaseCypher = undefined saveCypher :: FilePath -> [Cypher] -> IO () saveCypher = undefined go :: IO () go = loadAll >>= \(abm, cm, ccs, abc) -> saveCypher "01-raw-countries.cyp" (countriesCypher cm) >> putStrLn "Saved countries" >> saveCypher "02-countries-corrections.cyp" (countriesCorrections ccs abc) >> putStrLn "Saved corrections" >> saveCypher "03-airbases.cyp" (airbaseCypher abm) >> putStrLn "Yeah. We're done."
17b6a88333b589287da89eeda03ef8bf6dc1be52b17fad0fce5f41afea75a748
project-fifo/dhcp
dhcp_eqc.erl
-module(dhcp_eqc). -compile(export_all). -include_lib("eqc/include/eqc.hrl"). -include_lib("eunit/include/eunit.hrl"). -include_lib("dhcp/include/dhcp.hrl"). -define(M, dhcp). byte() -> choose(0,255). ip_tpl() -> {byte(), byte(), byte(), byte()}. prop_ip_tpl_conversion() -> ?FORALL(Tpl, ip_tpl(), begin EncDecTpl = ?M:ip_to_tpl(?M:tpl_to_ip(Tpl)), EncDecTpl =:= Tpl end).
null
https://raw.githubusercontent.com/project-fifo/dhcp/c8ada117ca38b5d6cd202c4e62b5be79574ca602/eqc/dhcp_eqc.erl
erlang
-module(dhcp_eqc). -compile(export_all). -include_lib("eqc/include/eqc.hrl"). -include_lib("eunit/include/eunit.hrl"). -include_lib("dhcp/include/dhcp.hrl"). -define(M, dhcp). byte() -> choose(0,255). ip_tpl() -> {byte(), byte(), byte(), byte()}. prop_ip_tpl_conversion() -> ?FORALL(Tpl, ip_tpl(), begin EncDecTpl = ?M:ip_to_tpl(?M:tpl_to_ip(Tpl)), EncDecTpl =:= Tpl end).
bbb36d7235b0e18d102c433f927cdf83f9a913e07fa9d1ada4f901fbaf158621
pink-gorilla/webly
routing.clj
(ns routing (:require [bidi.bidi :as bidi])) (def routes ["/" {"" :demo/main "x" :demo/bongo "y" {:matched :demo/y :tag :uu} "z" (bidi/tag :demo/z :bongo)}]) (meta (bidi/tag :demo/z :bongo)) (pr-str routes) (bidi/match-route routes "/x") (bidi/match-route routes "/y") (bidi/match-route routes "/z") (bidi/match-route routes "/x" :request-method :get) (bidi/path-for routes :demo/main)
null
https://raw.githubusercontent.com/pink-gorilla/webly/ae37a2b0eb201bade5f909ebecfa63a60c3bd4ca/demo-rest/src/routing.clj
clojure
(ns routing (:require [bidi.bidi :as bidi])) (def routes ["/" {"" :demo/main "x" :demo/bongo "y" {:matched :demo/y :tag :uu} "z" (bidi/tag :demo/z :bongo)}]) (meta (bidi/tag :demo/z :bongo)) (pr-str routes) (bidi/match-route routes "/x") (bidi/match-route routes "/y") (bidi/match-route routes "/z") (bidi/match-route routes "/x" :request-method :get) (bidi/path-for routes :demo/main)
ffe0da2183935c7e1f9aa43113d75938c5fcef1730ff881f067413b53c8dfc62
kappelmann/engaging-large-scale-functional-programming
Exercise07.hs
module Exercise07 where import Control.Monad (replicateM) import Data.List (find) import Data.Maybe (isJust, isNothing) import Data.Sequence (sortBy) main :: IO () main = do people <- getLine test <- replicateM (read people) getLine print (getList test) getList :: [String] -> [[Int]] getList xs = [map read (words x) | x <- xs] getPos :: [[Int]] -> (Int, Int) -> Int getPos gs (x, y) = gs !! (x -1) !! (y -1) greeted :: [[Int]] -> (Int, Int) -> Bool greeted gs (x, y) | x == y = True | otherwise = gs !! x !! y == 1 addGreet :: [[Int]] -> (Int, Int) -> [[Int]] addGreet gs (x, y) | greeted gs (x, y) = gs | otherwise = updateGreetings (updateGreetings gs (x, y)) (y, x) updateGreetings :: [[Int]] -> (Int, Int) -> [[Int]] updateGreetings gs (x, y) = take (y -1) gs ++ [take (x -1) (gs !! (y -1)) ++ [1] ++ drop x (gs !! (y -1))] ++ drop (y + 1) gs getNextMin :: [[Int]] -> [(Int, Int)] -> [(Int, Int)] -> [(Int, Int)] getNextMin gs xs used = filter (alreadyUsed used) xs alreadyUsed :: [(Int, Int)] -> (Int, Int) -> Bool alreadyUsed ts (x, y) = isJust (find (\(r, s) -> x == r && y == s) ts)
null
https://raw.githubusercontent.com/kappelmann/engaging-large-scale-functional-programming/8ed2c056fbd611f1531230648497cb5436d489e4/resources/contest/example_data/07/uploads/foobar/Exercise07.hs
haskell
module Exercise07 where import Control.Monad (replicateM) import Data.List (find) import Data.Maybe (isJust, isNothing) import Data.Sequence (sortBy) main :: IO () main = do people <- getLine test <- replicateM (read people) getLine print (getList test) getList :: [String] -> [[Int]] getList xs = [map read (words x) | x <- xs] getPos :: [[Int]] -> (Int, Int) -> Int getPos gs (x, y) = gs !! (x -1) !! (y -1) greeted :: [[Int]] -> (Int, Int) -> Bool greeted gs (x, y) | x == y = True | otherwise = gs !! x !! y == 1 addGreet :: [[Int]] -> (Int, Int) -> [[Int]] addGreet gs (x, y) | greeted gs (x, y) = gs | otherwise = updateGreetings (updateGreetings gs (x, y)) (y, x) updateGreetings :: [[Int]] -> (Int, Int) -> [[Int]] updateGreetings gs (x, y) = take (y -1) gs ++ [take (x -1) (gs !! (y -1)) ++ [1] ++ drop x (gs !! (y -1))] ++ drop (y + 1) gs getNextMin :: [[Int]] -> [(Int, Int)] -> [(Int, Int)] -> [(Int, Int)] getNextMin gs xs used = filter (alreadyUsed used) xs alreadyUsed :: [(Int, Int)] -> (Int, Int) -> Bool alreadyUsed ts (x, y) = isJust (find (\(r, s) -> x == r && y == s) ts)
e77ff1e0c6cc15fe8c40097f15f110ef81d88639a4a023636c66f5d082d4245a
coq-community/vscoq
vscoqtop_tactic_worker.ml
(**************************************************************************) (* *) (* VSCoq *) (* *) (* Copyright INRIA and contributors *) ( see version control and README file for authors & dates ) (* *) (**************************************************************************) (* *) This file is distributed under the terms of the MIT License . (* See LICENSE file. *) (* *) (**************************************************************************) * This toplevel implements an LSP - based server language for VsCode , used by the VsCoq extension . used by the VsCoq extension. *) let log = Dm.ParTactic.TacticWorkerProcess.log let main_worker options ~opts:_ state = let initial_vernac_state = Vernacstate.freeze_full_state ~marshallable:false in try Dm.ParTactic.TacticWorkerProcess.main ~st:initial_vernac_state options with exn -> let bt = Printexc.get_backtrace () in log Printexc.(to_string exn); log bt; flush_all () let vscoqtop_specific_usage = Boot.Usage.{ executable_name = "vscoqtop_tactic_worker"; extra_args = ""; extra_options = ""; } let _ = Coqinit.init_ocaml (); let opts, emoptions = Coqinit.parse_arguments ~parse_extra:Dm.ParTactic.TacticWorkerProcess.parse_options ~usage:vscoqtop_specific_usage () in let injections = Coqinit.init_runtime opts in Coqinit.start_library ~top:Coqargs.(dirpath_of_top opts.config.logic.toplevel_name) injections; log @@ "started"; Sys.(set_signal sigint Signal_ignore); main_worker ~opts emoptions ()
null
https://raw.githubusercontent.com/coq-community/vscoq/fc7f4449256b1d60e4ef18b2ade4dd1efd4a7f8d/language-server/dm/vscoqtop_tactic_worker.ml
ocaml
************************************************************************ VSCoq Copyright INRIA and contributors ************************************************************************ See LICENSE file. ************************************************************************
( see version control and README file for authors & dates ) This file is distributed under the terms of the MIT License . * This toplevel implements an LSP - based server language for VsCode , used by the VsCoq extension . used by the VsCoq extension. *) let log = Dm.ParTactic.TacticWorkerProcess.log let main_worker options ~opts:_ state = let initial_vernac_state = Vernacstate.freeze_full_state ~marshallable:false in try Dm.ParTactic.TacticWorkerProcess.main ~st:initial_vernac_state options with exn -> let bt = Printexc.get_backtrace () in log Printexc.(to_string exn); log bt; flush_all () let vscoqtop_specific_usage = Boot.Usage.{ executable_name = "vscoqtop_tactic_worker"; extra_args = ""; extra_options = ""; } let _ = Coqinit.init_ocaml (); let opts, emoptions = Coqinit.parse_arguments ~parse_extra:Dm.ParTactic.TacticWorkerProcess.parse_options ~usage:vscoqtop_specific_usage () in let injections = Coqinit.init_runtime opts in Coqinit.start_library ~top:Coqargs.(dirpath_of_top opts.config.logic.toplevel_name) injections; log @@ "started"; Sys.(set_signal sigint Signal_ignore); main_worker ~opts emoptions ()
d800709d00bf376935b208c3b81fd2b206543067fe9a774dd30c53e359cfdccf
SecPriv/webspec
uuid.ml
(********************************************************************************) Copyright ( c ) 2022 (* *) (* 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 type S = sig val gen_uuid : unit -> string end module Generator : S = struct let gen_uuid () : string = let rst = Random.State.make_self_init () in Uuidm.v4_gen rst () |> Uuidm.to_string end
null
https://raw.githubusercontent.com/SecPriv/webspec/b7ff6b714b3a4b572c108cc3136506da3d263eff/verifier/src/uuid.ml
ocaml
****************************************************************************** Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), the rights to use, copy, modify, merge, publish, distribute, sublicense, 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. 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 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ******************************************************************************
Copyright ( c ) 2022 to deal in the Software without restriction , including without limitation and/or sell copies of the Software , and to permit persons to whom the THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING module type S = sig val gen_uuid : unit -> string end module Generator : S = struct let gen_uuid () : string = let rst = Random.State.make_self_init () in Uuidm.v4_gen rst () |> Uuidm.to_string end
55335d1bc557899ea3a738f2e7064eeb511f82d4e1cda3504a914cdd5e970f48
ktakashi/sagittarius-scheme
executor.scm
-*- mode : scheme ; coding : utf-8 -*- ;;; ;;; util/concurrent/executor.scm - Concurrent executor ;;; Copyright ( c ) 2010 - 2014 < > ;;; ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; ;;; 1. Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; ;;; 2. Redistributions in binary form must reproduce the above copyright ;;; notice, this list of conditions and the following disclaimer in the ;;; documentation and/or other materials provided with the distribution. ;;; ;;; THIS SOFTWARE IS PROVIDED BY THE 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 CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED ;;; TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR ;;; PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ;;; ;; portable concurrent library #!nounbound (library (util concurrent executor) (export (rename (executor <executor>)) executor? ;; interface executor-state executor-available? shutdown-executor! execute-future! executor-submit! (rename (thread-pool-executor <thread-pool-executor>)) make-thread-pool-executor thread-pool-executor? ;; below must be thread-pool-executor specific thread-pool-executor-pool-size thread-pool-executor-max-pool-size thread-pool-executor-available? thread-pool-executor-execute-future! thread-pool-executor-shutdown! abort-rejected-handler terminate-oldest-handler wait-finishing-handler push-future-handler &rejected-execution-error rejected-execution-error? rejected-future rejected-executor (rename (fork-join-executor <fork-join-executor>)) make-fork-join-executor fork-join-executor? fork-join-executor-available? fork-join-executor-execute-future! fork-join-executor-shutdown! ;; this condition should not be extended duplicate-executor-registration? duplicate-executor-rtd ;; future (rename (executor-future <executor-future>)) make-executor-future executor-future? ;; for extension register-executor-methods ) (import (rnrs) (sagittarius) ;; not portal anymore :( (only (srfi :1) remove!) (srfi :18) (srfi :19) (srfi :117) (util concurrent future) (util concurrent thread-pool) (util concurrent fork-join-pool)) (define (not-started . dummy) (assertion-violation 'executor-future "Future is not started yet" dummy)) (define-record-type executor-future (parent <future>) ;; (fields (mutable worker future-worker future-worker-set!)) (protocol (lambda (n) (lambda (thunk) ((n thunk not-started)))))) ;; executor and worker (define-condition-type &rejected-execution-error &error make-rejected-execution-error rejected-execution-error? (future rejected-future) (executor rejected-executor)) TODO some other reject policy ;; aboring when pool is full (define (abort-rejected-handler future executor) (raise (condition (make-rejected-execution-error future executor) (make-who-condition 'executor) (make-message-condition "Failed to add task")))) ;; assume the oldest one is negligible (define (terminate-oldest-handler future executor) (define (get-oldest executor) (with-atomic executor (let ((l (pooled-executor-pool-ids executor))) (and (not (list-queue-empty? l)) (list-queue-remove-front! l))))) ;; the oldest might already be finished. (let ((oldest (get-oldest executor))) (and oldest ;; if the running future is finishing and locking the mutex, ;; we'd get abandoned mutex. to avoid it lock it. (with-atomic executor (thread-pool-thread-terminate! (pooled-executor-pool executor) (car oldest))) (cleanup executor (cdr oldest) 'terminated))) ;; retry (execute-future! executor future)) ;; wait for trivial time until pool is available ;; if it won't then raise an error. (define (wait-finishing-handler wait-retry) (lambda (future executor) (thread-sleep! 0.1) ;; trivial time waiting (let loop ((count 0)) (cond ((executor-available? executor) (execute-future! executor future)) ((= count wait-retry) ;; now how should we handle this? ;; for now raises an error... (abort-rejected-handler future executor)) ;; bit longer waiting (else (thread-sleep! 0.5) (loop (+ count 1))))))) ;; default is abort (define default-rejected-handler abort-rejected-handler) ;; For now only dummy (define-record-type executor (fields (mutable state) mutex) (protocol (lambda (p) (lambda () (p 'running (make-mutex)))))) (define-record-type pooled-executor (fields pool-ids pool rejected-handler) (parent executor) (protocol (lambda (p) (lambda (pool rejected-handler) ((p) (list-queue) pool rejected-handler))))) (define-record-type thread-pool-executor (parent pooled-executor) (protocol (lambda (n) (lambda (max-pool-size . rest) ;; i don't see using mtqueue for this since ;; mutating the slot is atomic ((n (make-thread-pool max-pool-size) (if (null? rest) default-rejected-handler (car rest)))))))) (define (thread-pool-executor-pool-size executor) (length (list-queue-list (pooled-executor-pool-ids executor)))) (define (thread-pool-executor-max-pool-size executor) (thread-pool-size (pooled-executor-pool executor))) ;; (define (mutex-lock-recursively! mutex) ;; (if (eq? (mutex-state mutex) (current-thread)) ;; (let ((n (mutex-specific mutex))) ;; (mutex-specific-set! mutex (+ n 1))) ;; (begin ;; (mutex-lock! mutex) ;; (mutex-specific-set! mutex 0)))) ;; ;; (define (mutex-unlock-recursively! mutex) ;; (let ((n (mutex-specific mutex))) ;; (if (= n 0) ;; (mutex-unlock! mutex) ;; (mutex-specific-set! mutex (- n 1))))) (define mutex-lock-recursively! mutex-lock!) (define mutex-unlock-recursively! mutex-unlock!) (define-syntax with-atomic (syntax-rules () ((_ executor expr ...) (dynamic-wind (lambda () (mutex-lock-recursively! (executor-mutex executor))) (lambda () expr ...) (lambda () (mutex-unlock-recursively! (executor-mutex executor))))))) (define (cleanup executor future state) (define (remove-from-queue! proc queue) (list-queue-set-list! queue (remove! proc (list-queue-list queue)))) (with-atomic executor (remove-from-queue! (lambda (o) (eq? (cdr o) future)) (pooled-executor-pool-ids executor)) (future-state-set! future state))) (define (thread-pool-executor-available? executor) (< (thread-pool-executor-pool-size executor) (thread-pool-executor-max-pool-size executor))) ;; shutdown (define (thread-pool-executor-shutdown! executor) ;; executor-future's future-cancel uses with-atomic so first finish up what we need to do for the executor ;; then call future-cancel. (define (executor-shutdown executor) (with-atomic executor (let ((state (executor-state executor))) (guard (e (else (executor-state-set! executor state) (raise e))) ;; to avoid accepting new task ;; chenge it here (when (eq? state 'running) (executor-state-set! executor 'shutdown)) ;; we terminate the threads so that we can finish all ;; infinite looped threads. NB , it 's dangerous (thread-pool-release! (pooled-executor-pool executor) 'terminate) (list-queue-remove-all! (pooled-executor-pool-ids executor)))))) ;; now cancel futures (for-each (lambda (future) (future-cancel (cdr future))) (executor-shutdown executor))) (define (thread-pool-executor-execute-future! executor future) (or (with-atomic executor (let ((pool-size (thread-pool-executor-pool-size executor)) (max-pool-size (thread-pool-executor-max-pool-size executor))) (and (< pool-size max-pool-size) (eq? (executor-state executor) 'running) (push-future-handler future executor)))) ;; the reject handler may lock executor again ;; to avoid double lock, this must be out side of atomic (let ((reject-handler (pooled-executor-rejected-handler executor))) (reject-handler future executor)))) ;; We can push the future to thread-pool (define (push-future-handler future executor) (define (canceller future) (cleanup executor future 'terminated)) (define (task-invoker thunk) (lambda () (let ((q (future-result future))) (guard (e (else (future-canceller-set! future #t) ;; kinda abusing (cleanup executor future 'finished) (shared-box-put! q e))) (let ((r (thunk))) ;; first remove future then put the result ;; otherwise future-get may be called before. (cleanup executor future 'finished) (shared-box-put! q r)))))) (define (add-future future executor) (future-result-set! future (make-shared-box)) (let* ((thunk (future-thunk future)) (id (thread-pool-push-task! (pooled-executor-pool executor) (task-invoker thunk)))) (future-canceller-set! future canceller) (list-queue-add-back! (pooled-executor-pool-ids executor) (cons id future)) executor)) ;; in case this is called directly (unless (eq? (executor-state executor) 'running) (assertion-violation 'push-future-handler "executor is not running" executor)) ;; if the mutex is locked by the current thread, then we can ;; simply add it (it's atomic) ;; if not, then wait/lock it. (if (eq? (mutex-state (executor-mutex executor)) (current-thread)) (add-future future executor) (with-atomic executor (add-future future executor)))) ;; fork-join-executor ;; this is more or less an example of how to implement ;; custom executors. the executor doesn't manage anything ;; but just creates a thread and execute it. (define-record-type fork-join-executor (parent pooled-executor) (protocol (lambda (n) (define ctr (case-lambda (() (ctr (cpu-count))) ((parallelism) ((n (make-fork-join-pool parallelism) #f))) ((parallelism parameter) ((n (make-fork-join-pool parallelism parameter) #f))))) ctr))) (define (fork-join-executor-available? e) (unless (fork-join-executor? e) (assertion-violation 'fork-join-executor-available? "not a fork-join-executor" e)) (fork-join-pool-available? (pooled-executor-pool e))) (define (fork-join-executor-execute-future! e f) ;; the same as simple future (define (task-invoker thunk) (lambda () (let ((q (future-result f))) (guard (e (else (future-canceller-set! f #t) (future-state-set! f 'finished) (shared-box-put! q e))) (let ((r (thunk))) (future-state-set! f 'finished) (shared-box-put! q r)))))) (unless (fork-join-executor? e) (assertion-violation 'fork-join-executor-available? "not a fork-join-executor" e)) (unless (shared-box? (future-result f)) (future-result-set! f (make-shared-box))) (fork-join-pool-push-task! (pooled-executor-pool e) (task-invoker (future-thunk f))) f) (define (fork-join-executor-shutdown! e) (unless (fork-join-executor? e) (assertion-violation 'fork-join-executor-available? "not a fork-join-executor" e)) (fork-join-pool-shutdown! (pooled-executor-pool e)) (executor-state-set! e 'shutdown)) (define *registered-executors* '()) (define *register-lock* (make-mutex)) (define-condition-type &duplicate-executor-registration &error make-duplicate-executor-registration duplicate-executor-registration? (rtd duplicate-executor-rtd)) (define (%register-executor-methods rtd pred available? execute shutdown) (mutex-lock! *register-lock*) ;; hope record-type-descriptor returns the defined rtd not newly created one (when (assq rtd *registered-executors*) (mutex-unlock! *register-lock*) (raise (condition (make-duplicate-executor-registration rtd) (make-who-condition 'register-executor-methods) (make-message-condition "specified predicate is already registered")))) (set! *registered-executors* (cons (list rtd pred available? execute shutdown) *registered-executors*)) (mutex-unlock! *register-lock*)) (define-syntax register-executor-methods (syntax-rules () ((_ type available? execute shutdown) (define dummy (let ((rtd (record-type-descriptor type))) (%register-executor-methods rtd (record-predicate rtd) available? execute shutdown)))))) (define-syntax invoke-method (syntax-rules () ((_ who pos fallback e args ...) (let loop ((methods *registered-executors*)) (cond ((null? methods) (if (executor? e) fallback (assertion-violation 'who "not an executor" e))) (((cadar methods) e) ((pos (cdar methods)) e args ...)) (else (loop (cdr methods)))))))) (define (not-supported e) (error #f "given executor is not supported" e)) (define (executor-available? e) (invoke-method executor-available? cadr #f e)) (define (execute-future! e f) (invoke-method execute-future! caddr (not-supported e) e f)) (define (shutdown-executor! e) (invoke-method shutdown-executor! cadddr (not-supported e) e)) (define (executor-submit! e thunk) (let ((f (make-executor-future thunk))) (execute-future! e f) f)) ;; pre-defined executor (register-executor-methods thread-pool-executor thread-pool-executor-available? thread-pool-executor-execute-future! thread-pool-executor-shutdown!) (register-executor-methods fork-join-executor fork-join-executor-available? fork-join-executor-execute-future! fork-join-executor-shutdown!) )
null
https://raw.githubusercontent.com/ktakashi/sagittarius-scheme/34cf17ec7aee301562a2a1be09540819c1b3b210/sitelib/util/concurrent/executor.scm
scheme
coding : utf-8 -*- util/concurrent/executor.scm - Concurrent executor Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE 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 OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. portable concurrent library interface below must be thread-pool-executor specific this condition should not be extended future for extension not portal anymore :( (fields (mutable worker future-worker future-worker-set!)) executor and worker aboring when pool is full assume the oldest one is negligible the oldest might already be finished. if the running future is finishing and locking the mutex, we'd get abandoned mutex. to avoid it lock it. retry wait for trivial time until pool is available if it won't then raise an error. trivial time waiting now how should we handle this? for now raises an error... bit longer waiting default is abort For now only dummy i don't see using mtqueue for this since mutating the slot is atomic (define (mutex-lock-recursively! mutex) (if (eq? (mutex-state mutex) (current-thread)) (let ((n (mutex-specific mutex))) (mutex-specific-set! mutex (+ n 1))) (begin (mutex-lock! mutex) (mutex-specific-set! mutex 0)))) (define (mutex-unlock-recursively! mutex) (let ((n (mutex-specific mutex))) (if (= n 0) (mutex-unlock! mutex) (mutex-specific-set! mutex (- n 1))))) shutdown executor-future's future-cancel uses with-atomic then call future-cancel. to avoid accepting new task chenge it here we terminate the threads so that we can finish all infinite looped threads. now cancel futures the reject handler may lock executor again to avoid double lock, this must be out side of atomic We can push the future to thread-pool kinda abusing first remove future then put the result otherwise future-get may be called before. in case this is called directly if the mutex is locked by the current thread, then we can simply add it (it's atomic) if not, then wait/lock it. fork-join-executor this is more or less an example of how to implement custom executors. the executor doesn't manage anything but just creates a thread and execute it. the same as simple future hope record-type-descriptor returns the defined rtd not pre-defined executor
Copyright ( c ) 2010 - 2014 < > " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING #!nounbound (library (util concurrent executor) (export (rename (executor <executor>)) executor-state executor-available? shutdown-executor! execute-future! executor-submit! (rename (thread-pool-executor <thread-pool-executor>)) make-thread-pool-executor thread-pool-executor? thread-pool-executor-pool-size thread-pool-executor-max-pool-size thread-pool-executor-available? thread-pool-executor-execute-future! thread-pool-executor-shutdown! abort-rejected-handler terminate-oldest-handler wait-finishing-handler push-future-handler &rejected-execution-error rejected-execution-error? rejected-future rejected-executor (rename (fork-join-executor <fork-join-executor>)) make-fork-join-executor fork-join-executor? fork-join-executor-available? fork-join-executor-execute-future! fork-join-executor-shutdown! duplicate-executor-registration? duplicate-executor-rtd (rename (executor-future <executor-future>)) make-executor-future executor-future? register-executor-methods ) (import (rnrs) (only (srfi :1) remove!) (srfi :18) (srfi :19) (srfi :117) (util concurrent future) (util concurrent thread-pool) (util concurrent fork-join-pool)) (define (not-started . dummy) (assertion-violation 'executor-future "Future is not started yet" dummy)) (define-record-type executor-future (parent <future>) (protocol (lambda (n) (lambda (thunk) ((n thunk not-started)))))) (define-condition-type &rejected-execution-error &error make-rejected-execution-error rejected-execution-error? (future rejected-future) (executor rejected-executor)) TODO some other reject policy (define (abort-rejected-handler future executor) (raise (condition (make-rejected-execution-error future executor) (make-who-condition 'executor) (make-message-condition "Failed to add task")))) (define (terminate-oldest-handler future executor) (define (get-oldest executor) (with-atomic executor (let ((l (pooled-executor-pool-ids executor))) (and (not (list-queue-empty? l)) (list-queue-remove-front! l))))) (let ((oldest (get-oldest executor))) (and oldest (with-atomic executor (thread-pool-thread-terminate! (pooled-executor-pool executor) (car oldest))) (cleanup executor (cdr oldest) 'terminated))) (execute-future! executor future)) (define (wait-finishing-handler wait-retry) (lambda (future executor) (let loop ((count 0)) (cond ((executor-available? executor) (execute-future! executor future)) ((= count wait-retry) (abort-rejected-handler future executor)) (else (thread-sleep! 0.5) (loop (+ count 1))))))) (define default-rejected-handler abort-rejected-handler) (define-record-type executor (fields (mutable state) mutex) (protocol (lambda (p) (lambda () (p 'running (make-mutex)))))) (define-record-type pooled-executor (fields pool-ids pool rejected-handler) (parent executor) (protocol (lambda (p) (lambda (pool rejected-handler) ((p) (list-queue) pool rejected-handler))))) (define-record-type thread-pool-executor (parent pooled-executor) (protocol (lambda (n) (lambda (max-pool-size . rest) ((n (make-thread-pool max-pool-size) (if (null? rest) default-rejected-handler (car rest)))))))) (define (thread-pool-executor-pool-size executor) (length (list-queue-list (pooled-executor-pool-ids executor)))) (define (thread-pool-executor-max-pool-size executor) (thread-pool-size (pooled-executor-pool executor))) (define mutex-lock-recursively! mutex-lock!) (define mutex-unlock-recursively! mutex-unlock!) (define-syntax with-atomic (syntax-rules () ((_ executor expr ...) (dynamic-wind (lambda () (mutex-lock-recursively! (executor-mutex executor))) (lambda () expr ...) (lambda () (mutex-unlock-recursively! (executor-mutex executor))))))) (define (cleanup executor future state) (define (remove-from-queue! proc queue) (list-queue-set-list! queue (remove! proc (list-queue-list queue)))) (with-atomic executor (remove-from-queue! (lambda (o) (eq? (cdr o) future)) (pooled-executor-pool-ids executor)) (future-state-set! future state))) (define (thread-pool-executor-available? executor) (< (thread-pool-executor-pool-size executor) (thread-pool-executor-max-pool-size executor))) (define (thread-pool-executor-shutdown! executor) so first finish up what we need to do for the executor (define (executor-shutdown executor) (with-atomic executor (let ((state (executor-state executor))) (guard (e (else (executor-state-set! executor state) (raise e))) (when (eq? state 'running) (executor-state-set! executor 'shutdown)) NB , it 's dangerous (thread-pool-release! (pooled-executor-pool executor) 'terminate) (list-queue-remove-all! (pooled-executor-pool-ids executor)))))) (for-each (lambda (future) (future-cancel (cdr future))) (executor-shutdown executor))) (define (thread-pool-executor-execute-future! executor future) (or (with-atomic executor (let ((pool-size (thread-pool-executor-pool-size executor)) (max-pool-size (thread-pool-executor-max-pool-size executor))) (and (< pool-size max-pool-size) (eq? (executor-state executor) 'running) (push-future-handler future executor)))) (let ((reject-handler (pooled-executor-rejected-handler executor))) (reject-handler future executor)))) (define (push-future-handler future executor) (define (canceller future) (cleanup executor future 'terminated)) (define (task-invoker thunk) (lambda () (let ((q (future-result future))) (guard (e (else (cleanup executor future 'finished) (shared-box-put! q e))) (let ((r (thunk))) (cleanup executor future 'finished) (shared-box-put! q r)))))) (define (add-future future executor) (future-result-set! future (make-shared-box)) (let* ((thunk (future-thunk future)) (id (thread-pool-push-task! (pooled-executor-pool executor) (task-invoker thunk)))) (future-canceller-set! future canceller) (list-queue-add-back! (pooled-executor-pool-ids executor) (cons id future)) executor)) (unless (eq? (executor-state executor) 'running) (assertion-violation 'push-future-handler "executor is not running" executor)) (if (eq? (mutex-state (executor-mutex executor)) (current-thread)) (add-future future executor) (with-atomic executor (add-future future executor)))) (define-record-type fork-join-executor (parent pooled-executor) (protocol (lambda (n) (define ctr (case-lambda (() (ctr (cpu-count))) ((parallelism) ((n (make-fork-join-pool parallelism) #f))) ((parallelism parameter) ((n (make-fork-join-pool parallelism parameter) #f))))) ctr))) (define (fork-join-executor-available? e) (unless (fork-join-executor? e) (assertion-violation 'fork-join-executor-available? "not a fork-join-executor" e)) (fork-join-pool-available? (pooled-executor-pool e))) (define (fork-join-executor-execute-future! e f) (define (task-invoker thunk) (lambda () (let ((q (future-result f))) (guard (e (else (future-canceller-set! f #t) (future-state-set! f 'finished) (shared-box-put! q e))) (let ((r (thunk))) (future-state-set! f 'finished) (shared-box-put! q r)))))) (unless (fork-join-executor? e) (assertion-violation 'fork-join-executor-available? "not a fork-join-executor" e)) (unless (shared-box? (future-result f)) (future-result-set! f (make-shared-box))) (fork-join-pool-push-task! (pooled-executor-pool e) (task-invoker (future-thunk f))) f) (define (fork-join-executor-shutdown! e) (unless (fork-join-executor? e) (assertion-violation 'fork-join-executor-available? "not a fork-join-executor" e)) (fork-join-pool-shutdown! (pooled-executor-pool e)) (executor-state-set! e 'shutdown)) (define *registered-executors* '()) (define *register-lock* (make-mutex)) (define-condition-type &duplicate-executor-registration &error make-duplicate-executor-registration duplicate-executor-registration? (rtd duplicate-executor-rtd)) (define (%register-executor-methods rtd pred available? execute shutdown) (mutex-lock! *register-lock*) newly created one (when (assq rtd *registered-executors*) (mutex-unlock! *register-lock*) (raise (condition (make-duplicate-executor-registration rtd) (make-who-condition 'register-executor-methods) (make-message-condition "specified predicate is already registered")))) (set! *registered-executors* (cons (list rtd pred available? execute shutdown) *registered-executors*)) (mutex-unlock! *register-lock*)) (define-syntax register-executor-methods (syntax-rules () ((_ type available? execute shutdown) (define dummy (let ((rtd (record-type-descriptor type))) (%register-executor-methods rtd (record-predicate rtd) available? execute shutdown)))))) (define-syntax invoke-method (syntax-rules () ((_ who pos fallback e args ...) (let loop ((methods *registered-executors*)) (cond ((null? methods) (if (executor? e) fallback (assertion-violation 'who "not an executor" e))) (((cadar methods) e) ((pos (cdar methods)) e args ...)) (else (loop (cdr methods)))))))) (define (not-supported e) (error #f "given executor is not supported" e)) (define (executor-available? e) (invoke-method executor-available? cadr #f e)) (define (execute-future! e f) (invoke-method execute-future! caddr (not-supported e) e f)) (define (shutdown-executor! e) (invoke-method shutdown-executor! cadddr (not-supported e) e)) (define (executor-submit! e thunk) (let ((f (make-executor-future thunk))) (execute-future! e f) f)) (register-executor-methods thread-pool-executor thread-pool-executor-available? thread-pool-executor-execute-future! thread-pool-executor-shutdown!) (register-executor-methods fork-join-executor fork-join-executor-available? fork-join-executor-execute-future! fork-join-executor-shutdown!) )
17340be60ae36a4e503df082deb18958c9fce2513f3d187b4319632306aa8e8e
rvantonder/hack_parallel
multiWorker.mli
* * Copyright ( c ) 2015 , Facebook , Inc. * All rights reserved . * * This source code is licensed under the BSD - style license found in the * LICENSE file in the " hack " directory of this source tree . An additional grant * of patent rights can be found in the PATENTS file in the same directory . * * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the "hack" directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * *) (* The protocol for a next function is to return a list of elements. * It will be called repeatedly until it returns an empty list. *) type 'a nextlist = 'a list Hack_bucket.next val next : Worker.t list option -> 'a list -> 'a list Hack_bucket.next (* See definition in Hack_bucket *) type 'a bucket = 'a Hack_bucket.bucket = | Job of 'a | Wait | Done val call : Worker.t list option -> job:('c -> 'a -> 'b) -> merge:('b -> 'c -> 'c) -> neutral:'c -> next:'a Hack_bucket.next -> 'c
null
https://raw.githubusercontent.com/rvantonder/hack_parallel/c9d0714785adc100345835c1989f7c657e01f629/src/procs/multiWorker.mli
ocaml
The protocol for a next function is to return a list of elements. * It will be called repeatedly until it returns an empty list. See definition in Hack_bucket
* * Copyright ( c ) 2015 , Facebook , Inc. * All rights reserved . * * This source code is licensed under the BSD - style license found in the * LICENSE file in the " hack " directory of this source tree . An additional grant * of patent rights can be found in the PATENTS file in the same directory . * * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the "hack" directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * *) type 'a nextlist = 'a list Hack_bucket.next val next : Worker.t list option -> 'a list -> 'a list Hack_bucket.next type 'a bucket = 'a Hack_bucket.bucket = | Job of 'a | Wait | Done val call : Worker.t list option -> job:('c -> 'a -> 'b) -> merge:('b -> 'c -> 'c) -> neutral:'c -> next:'a Hack_bucket.next -> 'c
7bc6defd6725fc1d945881eaec0191b5fc229db60c06c868a814c20d21c9734b
MinaProtocol/mina
mina_state_blockchain_state.ml
module Poly = struct module V2 = struct type ( 'staged_ledger_hash , 'snarked_ledger_hash , 'local_state , 'time , 'body_reference , 'signed_amount , 'pending_coinbase_stack , 'fee_excess , 'sok_digest ) t = { staged_ledger_hash : 'staged_ledger_hash ; genesis_ledger_hash : 'snarked_ledger_hash ; ledger_proof_statement : ( 'snarked_ledger_hash , 'signed_amount , 'pending_coinbase_stack , 'fee_excess , 'sok_digest , 'local_state ) Mina_state_snarked_ledger_state.Poly.V2.t ; timestamp : 'time ; body_reference : 'body_reference } end end module Value = struct module V2 = struct type t = ( Mina_base.Staged_ledger_hash.V1.t , Mina_base.Frozen_ledger_hash.V1.t , Mina_state_local_state.V1.t , Block_time.V1.t , Consensus.Body_reference.V1.t , (Currency.Amount.V1.t, Sgn_type.Sgn.V1.t) Signed_poly.V1.t , Mina_base.Pending_coinbase.Stack_versioned.V1.t , Mina_base.Fee_excess.V1.t , unit ) Poly.V2.t end end
null
https://raw.githubusercontent.com/MinaProtocol/mina/57e2ea1b87fe1a24517e1c62f51cc59fe9bc87cd/src/lib/mina_wire_types/mina_state/mina_state_blockchain_state.ml
ocaml
module Poly = struct module V2 = struct type ( 'staged_ledger_hash , 'snarked_ledger_hash , 'local_state , 'time , 'body_reference , 'signed_amount , 'pending_coinbase_stack , 'fee_excess , 'sok_digest ) t = { staged_ledger_hash : 'staged_ledger_hash ; genesis_ledger_hash : 'snarked_ledger_hash ; ledger_proof_statement : ( 'snarked_ledger_hash , 'signed_amount , 'pending_coinbase_stack , 'fee_excess , 'sok_digest , 'local_state ) Mina_state_snarked_ledger_state.Poly.V2.t ; timestamp : 'time ; body_reference : 'body_reference } end end module Value = struct module V2 = struct type t = ( Mina_base.Staged_ledger_hash.V1.t , Mina_base.Frozen_ledger_hash.V1.t , Mina_state_local_state.V1.t , Block_time.V1.t , Consensus.Body_reference.V1.t , (Currency.Amount.V1.t, Sgn_type.Sgn.V1.t) Signed_poly.V1.t , Mina_base.Pending_coinbase.Stack_versioned.V1.t , Mina_base.Fee_excess.V1.t , unit ) Poly.V2.t end end
219ada82c79827035caa6545b8e572b7448bf5eb5fabe6470ea3fceca2f7b8f8
Javran/advent-of-code
Main.hs
module Javran.AdventOfCode.Main ( main, ) where import Control.Monad import qualified Javran.AdventOfCode.Cli.New as CliNew import qualified Javran.AdventOfCode.Cli.ProgressReport as CliReport import qualified Javran.AdventOfCode.Cli.SolutionCommand as SolutionCommand import qualified Javran.AdventOfCode.Cli.Sync as CliSync import qualified Javran.AdventOfCode.Cli.TestAll as CliTestAll import Javran.AdventOfCode.Infra import Network.HTTP.Client import Network.HTTP.Client.TLS import System.Console.Terminfo import System.Environment import System.Exit main :: IO () main = do t <- setupTermFromEnv manager <- newManager tlsManagerSettings let ctxt = SubCmdContext { cmdHelpPrefix = "<prog> " , mTerm = Just t , manager } getArgs >>= \case args | Just mode <- SolutionCommand.parse args -> SolutionCommand.subCommand ctxt mode subCmd : args | Just handler <- lookup subCmd subCmdHandlers -> withArgs args (handler ctxt {cmdHelpPrefix = cmdHelpPrefix ctxt <> subCmd <> " "}) _ -> do forM_ subCmdHandlers $ \(sub, _) -> putStrLn $ cmdHelpPrefix ctxt <> sub <> " ..." putStrLn $ cmdHelpPrefix ctxt <> "<year> <day> ..." putStrLn "For listing what <year> and <day> are available, use `report` subcommand." exitFailure where subCmdHandlers = [ ("sync", CliSync.syncCommand) , ("new", CliNew.newCommand) , ("report", CliReport.progressReportCommand) , ("test-all", CliTestAll.testAllCommand) , ("_dev", const (pure ())) ]
null
https://raw.githubusercontent.com/Javran/advent-of-code/676ef13c2f9d341cf7de0f383335a1cf577bd73d/src/Javran/AdventOfCode/Main.hs
haskell
module Javran.AdventOfCode.Main ( main, ) where import Control.Monad import qualified Javran.AdventOfCode.Cli.New as CliNew import qualified Javran.AdventOfCode.Cli.ProgressReport as CliReport import qualified Javran.AdventOfCode.Cli.SolutionCommand as SolutionCommand import qualified Javran.AdventOfCode.Cli.Sync as CliSync import qualified Javran.AdventOfCode.Cli.TestAll as CliTestAll import Javran.AdventOfCode.Infra import Network.HTTP.Client import Network.HTTP.Client.TLS import System.Console.Terminfo import System.Environment import System.Exit main :: IO () main = do t <- setupTermFromEnv manager <- newManager tlsManagerSettings let ctxt = SubCmdContext { cmdHelpPrefix = "<prog> " , mTerm = Just t , manager } getArgs >>= \case args | Just mode <- SolutionCommand.parse args -> SolutionCommand.subCommand ctxt mode subCmd : args | Just handler <- lookup subCmd subCmdHandlers -> withArgs args (handler ctxt {cmdHelpPrefix = cmdHelpPrefix ctxt <> subCmd <> " "}) _ -> do forM_ subCmdHandlers $ \(sub, _) -> putStrLn $ cmdHelpPrefix ctxt <> sub <> " ..." putStrLn $ cmdHelpPrefix ctxt <> "<year> <day> ..." putStrLn "For listing what <year> and <day> are available, use `report` subcommand." exitFailure where subCmdHandlers = [ ("sync", CliSync.syncCommand) , ("new", CliNew.newCommand) , ("report", CliReport.progressReportCommand) , ("test-all", CliTestAll.testAllCommand) , ("_dev", const (pure ())) ]
c60040a92bd68ee38f7f25e8ad9c091bd9757774fb9ef6aa6eaa38c5cf6d0855
Kalimehtar/gtk-cffi
offscreen-window.lisp
;;; ;;; offscreen-window.lisp -- GtkOffscreenWindow ;;; Copyright ( C ) 2012 , < > ;;; (in-package :gtk-cffi) (defclass offscreen-window (window) ()) (defcfun gtk-offscreen-window-new :pointer) (defmethod gconstructor ((offscreen-window offscreen-window) &key) (gtk-offscreen-window-new)) (deffuns offscreen-window (:get pixbuf pobject)) (defcfun gtk-offscreen-window-get-surface :pointer (off-win pobject)) (defgeneric surface (offscreen-window) (:method ((offscreen-window offscreen-window)) (cairo:create-surface-from-foreign (gtk-offscreen-window-get-surface offscreen-window))))
null
https://raw.githubusercontent.com/Kalimehtar/gtk-cffi/fbd8a40a2bbda29f81b1a95ed2530debfe2afe9b/gtk/offscreen-window.lisp
lisp
offscreen-window.lisp -- GtkOffscreenWindow
Copyright ( C ) 2012 , < > (in-package :gtk-cffi) (defclass offscreen-window (window) ()) (defcfun gtk-offscreen-window-new :pointer) (defmethod gconstructor ((offscreen-window offscreen-window) &key) (gtk-offscreen-window-new)) (deffuns offscreen-window (:get pixbuf pobject)) (defcfun gtk-offscreen-window-get-surface :pointer (off-win pobject)) (defgeneric surface (offscreen-window) (:method ((offscreen-window offscreen-window)) (cairo:create-surface-from-foreign (gtk-offscreen-window-get-surface offscreen-window))))
b4b6e9dfb7768b625ba16c642f3e23fd9b3c107b3b583a1d5ef72127742cf816
ayamada/copy-of-svn.tir.jp
client.scm
;;; coding: euc-jp ;;; -*- scheme -*- ;;; vim:set ft=scheme ts=8 sts=2 sw=2 et: $ Id$ ;;; setpサーバと通信を行うクライアント。 現在のところは非同期通信には対応していない 。 ToDo : 使い方を書いておく事 ToDo : connect時にプロトコルチェックを行うコードを追加する事 ToDo : 通信切断時の処理をどうするか考える必要がある ;;; ToDo: request->response等の実行前にconnectしたりするか? ;;; 少なくとも、事前にconnectしているかのチェックは行い、 (define-module tir03.setp.client (use gauche.net) (use srfi-1) (use util.list) (use tir03.setp.protocol) (export <setp-client> setp-client-connect setp-client-disconnect setp-client-connected? setp-client-connection-is-alive? setp-client-reconnect request->response requests->responses ;; came from gauche.net <sockaddr> <sockaddr-in> <sockaddr-un> sockaddr-family sockaddr-name sockaddr-addr sockaddr-port )) (select-module tir03.setp.client) ;;; -------- ;;; came from gauche.net (define <sockaddr> <sockaddr>) (define <sockaddr-in> <sockaddr-in>) (define <sockaddr-un> <sockaddr-un>) (define sockaddr-family sockaddr-family) (define sockaddr-name sockaddr-name) (define sockaddr-addr sockaddr-addr) (define sockaddr-port sockaddr-port) ;;; -------- (define-class <setp-client> () ( ;; settings (sockaddr :accessor sockaddr-of :init-keyword :sockaddr :init-value #f) ;; internal slots (client-socket :accessor client-socket-of :init-value #f) )) (define-method initialize ((self <setp-client>) initargs) (next-method) ;; check slot (unless (sockaddr-of self) (errorf "~a must be need to :sockaddr" (class-name (class-of self)))) ) ;;; -------- (define-method setp-client-connect ((self <setp-client>)) (when (client-socket-of self) (error "already opened" self)) (set! (client-socket-of self) (make-client-socket (sockaddr-of self)))) (define-method setp-client-disconnect ((self <setp-client>)) (unless (client-socket-of self) (error "not opened" self)) ToDo : 可能なら、flushしておいた方が良いかも知れない ? (guard (e (else #f)) (socket-shutdown (client-socket-of self) 2)) (guard (e (else #f)) (socket-close (client-socket-of self))) #t) (define-method setp-client-connected? ((self <setp-client>)) (not (not (client-socket-of self)))) (define-method setp-client-connection-is-alive? ((self <setp-client>)) (and (client-socket-of self) (with-error-handler (lambda (e) ToDo : ;; エラー時には、close処理した方が良い??? それとも、再接続処理を行うべき ? ? ? #f) (lambda () (let1 identifier (list (sys-time) (sys-getpid)) (equal? identifier (with-setp-client self (lambda () (setp:echo identifier))))))))) (define-method setp-client-reconnect ((self <setp-client>)) (guard (e (else #f)) (setp-client-disconnect self)) (setp-client-connect self)) ;;; -------- (define-method requests->responses ((self <setp-client>) request . other-requests) ;; 多値としてrequestsを受け取り、多値としてresponsesを返す。 ;; 但し、requestsの途中でエラーがあった場合は、 ;; それ以降のrequestの評価は行わず、返ってくるresponsesの数も減る為、 ;; responsesの長さは不定となる。 ;; (但し、エラーは返るので、最低でも一つの要素は含まれている) ToDo : 最適化を行う余地がある (apply values (let loop ((requests (cons request other-requests))) (if (null? requests) '() (let1 response (request->response self (car requests)) (if (condition? response) (list response) (cons response (loop (cdr requests))))))))) (define-method request->response ((self <setp-client>) request) ToDo : (guard (e (else e)) ; 仮の通信切断対策 (let ((in (socket-input-port (client-socket-of self))) (out (socket-output-port (client-socket-of self)))) ;; write/ss時にエラーが出る=切断、の筈なので、エラー例外はそのまま投げる ToDo : 通信エラー時は、何らかの後処理を行ってから ;; 例外を投げた方が良くないか??? (write/ss request out) (newline out) (flush out) ;; read-line時にエラーが出る=切断、の筈なので、エラー例外はそのまま投げる (let1 line (read-line in) (if (eof-object? line) (error "disconnected from server") (receive (response headers) (guard (e (else (error "read error" e))) (call-with-input-string line (lambda (p) (let* ((v1 (read p)) (v2 (read p))) (values v1 v2))))) (cond ((eof-object? response) ToDo : 他に返せる値は無いのか ? ? ? ((and (pair? headers) (assoc-ref headers "error")) ToDo : もっとちゃんとエラーを構築する ? (else response)))))))) ;;; -------- (provide "tir03/setp/client")
null
https://raw.githubusercontent.com/ayamada/copy-of-svn.tir.jp/101cd00d595ee7bb96348df54f49707295e9e263/Gauche-tir/branches/Gauche-tir03/0.0.6/lib/tir03/setp/client.scm
scheme
coding: euc-jp -*- scheme -*- vim:set ft=scheme ts=8 sts=2 sw=2 et: setpサーバと通信を行うクライアント。 ToDo: request->response等の実行前にconnectしたりするか? 少なくとも、事前にconnectしているかのチェックは行い、 came from gauche.net -------- came from gauche.net -------- settings internal slots check slot -------- エラー時には、close処理した方が良い??? -------- 多値としてrequestsを受け取り、多値としてresponsesを返す。 但し、requestsの途中でエラーがあった場合は、 それ以降のrequestの評価は行わず、返ってくるresponsesの数も減る為、 responsesの長さは不定となる。 (但し、エラーは返るので、最低でも一つの要素は含まれている) 仮の通信切断対策 write/ss時にエラーが出る=切断、の筈なので、エラー例外はそのまま投げる 例外を投げた方が良くないか??? read-line時にエラーが出る=切断、の筈なので、エラー例外はそのまま投げる --------
$ Id$ 現在のところは非同期通信には対応していない 。 ToDo : 使い方を書いておく事 ToDo : connect時にプロトコルチェックを行うコードを追加する事 ToDo : 通信切断時の処理をどうするか考える必要がある (define-module tir03.setp.client (use gauche.net) (use srfi-1) (use util.list) (use tir03.setp.protocol) (export <setp-client> setp-client-connect setp-client-disconnect setp-client-connected? setp-client-connection-is-alive? setp-client-reconnect request->response requests->responses <sockaddr> <sockaddr-in> <sockaddr-un> sockaddr-family sockaddr-name sockaddr-addr sockaddr-port )) (select-module tir03.setp.client) (define <sockaddr> <sockaddr>) (define <sockaddr-in> <sockaddr-in>) (define <sockaddr-un> <sockaddr-un>) (define sockaddr-family sockaddr-family) (define sockaddr-name sockaddr-name) (define sockaddr-addr sockaddr-addr) (define sockaddr-port sockaddr-port) (define-class <setp-client> () ( (sockaddr :accessor sockaddr-of :init-keyword :sockaddr :init-value #f) (client-socket :accessor client-socket-of :init-value #f) )) (define-method initialize ((self <setp-client>) initargs) (next-method) (unless (sockaddr-of self) (errorf "~a must be need to :sockaddr" (class-name (class-of self)))) ) (define-method setp-client-connect ((self <setp-client>)) (when (client-socket-of self) (error "already opened" self)) (set! (client-socket-of self) (make-client-socket (sockaddr-of self)))) (define-method setp-client-disconnect ((self <setp-client>)) (unless (client-socket-of self) (error "not opened" self)) ToDo : 可能なら、flushしておいた方が良いかも知れない ? (guard (e (else #f)) (socket-shutdown (client-socket-of self) 2)) (guard (e (else #f)) (socket-close (client-socket-of self))) #t) (define-method setp-client-connected? ((self <setp-client>)) (not (not (client-socket-of self)))) (define-method setp-client-connection-is-alive? ((self <setp-client>)) (and (client-socket-of self) (with-error-handler (lambda (e) ToDo : それとも、再接続処理を行うべき ? ? ? #f) (lambda () (let1 identifier (list (sys-time) (sys-getpid)) (equal? identifier (with-setp-client self (lambda () (setp:echo identifier))))))))) (define-method setp-client-reconnect ((self <setp-client>)) (guard (e (else #f)) (setp-client-disconnect self)) (setp-client-connect self)) (define-method requests->responses ((self <setp-client>) request . other-requests) ToDo : 最適化を行う余地がある (apply values (let loop ((requests (cons request other-requests))) (if (null? requests) '() (let1 response (request->response self (car requests)) (if (condition? response) (list response) (cons response (loop (cdr requests))))))))) (define-method request->response ((self <setp-client>) request) ToDo : (let ((in (socket-input-port (client-socket-of self))) (out (socket-output-port (client-socket-of self)))) ToDo : 通信エラー時は、何らかの後処理を行ってから (write/ss request out) (newline out) (flush out) (let1 line (read-line in) (if (eof-object? line) (error "disconnected from server") (receive (response headers) (guard (e (else (error "read error" e))) (call-with-input-string line (lambda (p) (let* ((v1 (read p)) (v2 (read p))) (values v1 v2))))) (cond ((eof-object? response) ToDo : 他に返せる値は無いのか ? ? ? ((and (pair? headers) (assoc-ref headers "error")) ToDo : もっとちゃんとエラーを構築する ? (else response)))))))) (provide "tir03/setp/client")
ba7a616e196c417c0ef42da8fa2873bdc7b3ff6ef99089c556981447f95c821d
silverbullettt/SICP
2.69.rkt
(define (make-leaf symbol weight) (list 'leaf symbol weight)) (define (leaf? object) (eq? (car object) 'leaf)) (define (symbol-leaf x) (cadr x)) (define (weight-leaf x) (caddr x)) (define (make-code-tree left right) (list left right (append (symbols left) (symbols right)) (+ (weight left) (weight right)))) (define (left-branch tree) (car tree)) (define (right-branch tree) (cadr tree)) (define (symbols tree) (if (leaf? tree) (list (symbol-leaf tree)) (caddr tree))) (define (weight tree) (if (leaf? tree) (weight-leaf tree) (cadddr tree))) (define (adjoin-set x set) (cond ((null? set) (list x)) ((< (weight x) (weight (car set))) (cons x set)) (else (cons (car set) (adjoin-set x (cdr set)))))) (define (make-leaf-set pairs) (if (null? pairs) '() (let ((pair (car pairs))) (adjoin-set (make-leaf (car pair) (cadr pair)) (make-leaf-set (cdr pairs)))))) (define (generate-huffman-tree pairs) (car (successive-merge (make-leaf-set pairs)))) ;; iteration (define (successive-merge pairs) (if (= (length pairs) 1) pairs (successive-merge (adjoin-set-h (make-code-tree (car pairs) (cadr pairs)) (cddr pairs)))))
null
https://raw.githubusercontent.com/silverbullettt/SICP/e773a8071ae2fae768846a2b295b5ed96b019f8d/2.69.rkt
racket
iteration
(define (make-leaf symbol weight) (list 'leaf symbol weight)) (define (leaf? object) (eq? (car object) 'leaf)) (define (symbol-leaf x) (cadr x)) (define (weight-leaf x) (caddr x)) (define (make-code-tree left right) (list left right (append (symbols left) (symbols right)) (+ (weight left) (weight right)))) (define (left-branch tree) (car tree)) (define (right-branch tree) (cadr tree)) (define (symbols tree) (if (leaf? tree) (list (symbol-leaf tree)) (caddr tree))) (define (weight tree) (if (leaf? tree) (weight-leaf tree) (cadddr tree))) (define (adjoin-set x set) (cond ((null? set) (list x)) ((< (weight x) (weight (car set))) (cons x set)) (else (cons (car set) (adjoin-set x (cdr set)))))) (define (make-leaf-set pairs) (if (null? pairs) '() (let ((pair (car pairs))) (adjoin-set (make-leaf (car pair) (cadr pair)) (make-leaf-set (cdr pairs)))))) (define (generate-huffman-tree pairs) (car (successive-merge (make-leaf-set pairs)))) (define (successive-merge pairs) (if (= (length pairs) 1) pairs (successive-merge (adjoin-set-h (make-code-tree (car pairs) (cadr pairs)) (cddr pairs)))))
1ea14fb8b0c49adbf7138c668311ec7904ec1d9a869190617c86866283ec263e
well-typed/large-records
LowerBound.hs
# LANGUAGE TypeApplications # -- | Simple example of a generic function module Data.Record.Generic.LowerBound ( LowerBound(..) , glowerBound ) where import Data.Record.Generic import qualified Data.Record.Generic.Rep as Rep {------------------------------------------------------------------------------- General definition -------------------------------------------------------------------------------} -- | Types with a lower bound class LowerBound a where lowerBound :: a instance LowerBound Word where lowerBound = 0 instance LowerBound Bool where lowerBound = False instance LowerBound Char where lowerBound = '\x0000' instance LowerBound () where lowerBound = () instance LowerBound [a] where lowerBound = [] {------------------------------------------------------------------------------- Generic definition -------------------------------------------------------------------------------} glowerBound :: (Generic a, Constraints a LowerBound) => a glowerBound = to $ Rep.cpure (Proxy @LowerBound) (I lowerBound)
null
https://raw.githubusercontent.com/well-typed/large-records/fbc9d886094b7b40d6b89db72ff4c7fb59d5b903/large-generics/src/Data/Record/Generic/LowerBound.hs
haskell
| Simple example of a generic function ------------------------------------------------------------------------------ General definition ------------------------------------------------------------------------------ | Types with a lower bound ------------------------------------------------------------------------------ Generic definition ------------------------------------------------------------------------------
# LANGUAGE TypeApplications # module Data.Record.Generic.LowerBound ( LowerBound(..) , glowerBound ) where import Data.Record.Generic import qualified Data.Record.Generic.Rep as Rep class LowerBound a where lowerBound :: a instance LowerBound Word where lowerBound = 0 instance LowerBound Bool where lowerBound = False instance LowerBound Char where lowerBound = '\x0000' instance LowerBound () where lowerBound = () instance LowerBound [a] where lowerBound = [] glowerBound :: (Generic a, Constraints a LowerBound) => a glowerBound = to $ Rep.cpure (Proxy @LowerBound) (I lowerBound)
543240163264f5762d0df77d83e6775dbf35632e67d553ae20fecbf5eed9bbfc
pingles/bandit
epsilon.clj
(ns ^{:doc "Epsilon-Greedy algorithm" :author "Paul Ingles"} bandit.algo.epsilon (:use [bandit.arms :only (exploit total-pulls)])) (defn- draw-arm ([epsilon arms] (draw-arm epsilon (rand) arms)) ([epsilon n arms] (if (> n epsilon) (exploit :value arms) (rand-nth (seq arms))))) (defmulti select-arm "returns the arm that should be pulled. can provide an epsilon value: a number indicating the algorithms propensity for exploration. alternatively, provide an annealing function that will be called with the number of pulls; allowing the algorithm to dampen its exploration over time. 0 < epsilon < 1." (fn [epsilon arms] (number? epsilon))) (defmethod select-arm true [epsilon arms] (draw-arm epsilon arms)) (defmethod select-arm false [annealfn arms] (draw-arm (annealfn (total-pulls arms)) arms))
null
https://raw.githubusercontent.com/pingles/bandit/795666f3938e28f389691094bb1e07e4202290f6/bandit-core/src/bandit/algo/epsilon.clj
clojure
allowing the
(ns ^{:doc "Epsilon-Greedy algorithm" :author "Paul Ingles"} bandit.algo.epsilon (:use [bandit.arms :only (exploit total-pulls)])) (defn- draw-arm ([epsilon arms] (draw-arm epsilon (rand) arms)) ([epsilon n arms] (if (> n epsilon) (exploit :value arms) (rand-nth (seq arms))))) (defmulti select-arm "returns the arm that should be pulled. can provide an epsilon value: a number indicating the algorithms propensity for exploration. alternatively, provide algorithm to dampen its exploration over time. 0 < epsilon < 1." (fn [epsilon arms] (number? epsilon))) (defmethod select-arm true [epsilon arms] (draw-arm epsilon arms)) (defmethod select-arm false [annealfn arms] (draw-arm (annealfn (total-pulls arms)) arms))
905e03cdc733183c66b5777f4319827f3d5124e19c8683804fc4368e8338c24b
dyzsr/ocaml-selectml
patmatch_for_multiple.ml
(* TEST flags = "-drawlambda -dlambda" * expect *) (* Note: the tests below contain *both* the -drawlambda and the -dlambda intermediate representations: -drawlambda is the Lambda code generated directly by the pattern-matching compiler; it contain "alias" bindings or static exits that are unused, and will be removed by simplification, or that are used only once, and will be inlined by simplification. -dlambda is the Lambda code resulting from simplification. The -drawlambda output more closely matches what the pattern-compiler produces, and the -dlambda output more closely matches the final generated code. In this test we decided to show both to notice that some allocations are "optimized away" during simplification (see "here flattening is an optimization" below). *) match (3, 2, 1) with | (_, 3, _) | (1, _, _) -> true | _ -> false ;; [%%expect{| match*/288 = 3 * match*/289 = 2 * match*/290 = 1 ) ( catch ( catch ( catch ( if ( ! = * ) ( exit 3 ) ( exit 1 ) ) with ( 3 ) ( if ( ! = * match*/288 1 ) ( exit 2 ) ( exit 1 ) ) ) with ( 2 ) 0 ) with ( 1 ) 1 ) ) ( let ( * match*/288 = 3 * match*/289 = 2 * match*/290 = 1 ) ( catch ( if ( ! = * ) ( if ( ! = * match*/288 1 ) 0 ( exit 1 ) ) ( exit 1 ) ) with ( 1 ) 1 ) ) - : bool = false | } ] ; ; ( * This tests needs to allocate the tuple to bind ' x ' , but this is only done in the branches that use it . (catch (catch (catch (if (!= *match*/289 3) (exit 3) (exit 1)) with (3) (if (!= *match*/288 1) (exit 2) (exit 1))) with (2) 0) with (1) 1)) (let (*match*/288 = 3 *match*/289 = 2 *match*/290 = 1) (catch (if (!= *match*/289 3) (if (!= *match*/288 1) 0 (exit 1)) (exit 1)) with (1) 1)) - : bool = false |}];; (* This tests needs to allocate the tuple to bind 'x', but this is only done in the branches that use it. *) match (3, 2, 1) with | ((_, 3, _) as x) | ((1, _, _) as x) -> ignore x; true | _ -> false ;; [%%expect{| match*/293 = 3 * match*/294 = 2 * match*/295 = 1 ) ( catch ( catch ( catch ( if ( ! = * match*/294 3 ) ( exit 6 ) ( let ( x/297 = a ( makeblock 0 * match*/293 * match*/294 * match*/295 ) ) ( exit 4 x/297 ) ) ) with ( 6 ) ( if ( ! = * match*/293 1 ) ( exit 5 ) ( let ( x/296 = a ( makeblock 0 * match*/293 * match*/294 * match*/295 ) ) ( exit 4 x/296 ) ) ) ) with ( 5 ) 0 ) with ( 4 x/291 ) ( seq ( ignore x/291 ) 1 ) ) ) ( let ( * match*/293 = 3 * match*/294 = 2 * match*/295 = 1 ) ( catch ( if ( ! = * match*/294 3 ) ( if ( ! = * match*/293 1 ) 0 ( exit 4 ( makeblock 0 * match*/293 * match*/294 * match*/295 ) ) ) ( exit 4 ( makeblock 0 * match*/293 * match*/294 * match*/295 ) ) ) with ( 4 x/291 ) ( seq ( ignore x/291 ) 1 ) ) ) - : bool = false | } ] ; ; ( * Regression test for # 3780 (catch (catch (catch (if (!= *match*/294 3) (exit 6) (let (x/297 =a (makeblock 0 *match*/293 *match*/294 *match*/295)) (exit 4 x/297))) with (6) (if (!= *match*/293 1) (exit 5) (let (x/296 =a (makeblock 0 *match*/293 *match*/294 *match*/295)) (exit 4 x/296)))) with (5) 0) with (4 x/291) (seq (ignore x/291) 1))) (let (*match*/293 = 3 *match*/294 = 2 *match*/295 = 1) (catch (if (!= *match*/294 3) (if (!= *match*/293 1) 0 (exit 4 (makeblock 0 *match*/293 *match*/294 *match*/295))) (exit 4 (makeblock 0 *match*/293 *match*/294 *match*/295))) with (4 x/291) (seq (ignore x/291) 1))) - : bool = false |}];; (* Regression test for #3780 *) let _ = fun a b -> match a, b with | ((true, _) as _g) | ((false, _) as _g) -> () [%%expect{| (function a/298[int] b/299 : int 0) (function a/298[int] b/299 : int 0) - : bool -> 'a -> unit = <fun> |}];; More complete tests . The test cases below compare the compiler output on alias patterns that are outside an or - pattern ( handled during half - simplification , then flattened ) or inside an or - pattern ( handled during simplification ) . We used to have a Cannot_flatten exception that would result in fairly different code generated in both cases , but now the compilation strategy is fairly similar . The test cases below compare the compiler output on alias patterns that are outside an or-pattern (handled during half-simplification, then flattened) or inside an or-pattern (handled during simplification). We used to have a Cannot_flatten exception that would result in fairly different code generated in both cases, but now the compilation strategy is fairly similar. *) let _ = fun a b -> match a, b with | (true, _) as p -> p | (false, _) as p -> p (* outside, trivial *) [%%expect {| (function a/302[int] b/303 (let (p/304 =a (makeblock 0 a/302 b/303)) p/304)) (function a/302[int] b/303 (makeblock 0 a/302 b/303)) - : bool -> 'a -> bool * 'a = <fun> |}] let _ = fun a b -> match a, b with | ((true, _) as p) | ((false, _) as p) -> p (* inside, trivial *) [%%expect{| (function a/306[int] b/307 (let (p/308 =a (makeblock 0 a/306 b/307)) p/308)) (function a/306[int] b/307 (makeblock 0 a/306 b/307)) - : bool -> 'a -> bool * 'a = <fun> |}];; let _ = fun a b -> match a, b with | (true as x, _) as p -> x, p | (false as x, _) as p -> x, p (* outside, simple *) [%%expect {| (function a/312[int] b/313 (let (x/314 =a[int] a/312 p/315 =a (makeblock 0 a/312 b/313)) (makeblock 0 (int,*) x/314 p/315))) (function a/312[int] b/313 (makeblock 0 (int,*) a/312 (makeblock 0 a/312 b/313))) - : bool -> 'a -> bool * (bool * 'a) = <fun> |}] let _ = fun a b -> match a, b with | ((true as x, _) as p) | ((false as x, _) as p) -> x, p (* inside, simple *) [%%expect {| (function a/318[int] b/319 (let (x/320 =a[int] a/318 p/321 =a (makeblock 0 a/318 b/319)) (makeblock 0 (int,*) x/320 p/321))) (function a/318[int] b/319 (makeblock 0 (int,*) a/318 (makeblock 0 a/318 b/319))) - : bool -> 'a -> bool * (bool * 'a) = <fun> |}] let _ = fun a b -> match a, b with | (true as x, _) as p -> x, p | (false, x) as p -> x, p (* outside, complex *) [%%expect{| (function a/328[int] b/329[int] (if a/328 (let (x/330 =a[int] a/328 p/331 =a (makeblock 0 a/328 b/329)) (makeblock 0 (int,*) x/330 p/331)) (let (x/332 =a b/329 p/333 =a (makeblock 0 a/328 b/329)) (makeblock 0 (int,*) x/332 p/333)))) (function a/328[int] b/329[int] (if a/328 (makeblock 0 (int,*) a/328 (makeblock 0 a/328 b/329)) (makeblock 0 (int,*) b/329 (makeblock 0 a/328 b/329)))) - : bool -> bool -> bool * (bool * bool) = <fun> |}] let _ = fun a b -> match a, b with | ((true as x, _) as p) | ((false, x) as p) -> x, p (* inside, complex *) [%%expect{| (function a/334[int] b/335[int] (catch (if a/334 (let (x/342 =a[int] a/334 p/343 =a (makeblock 0 a/334 b/335)) (exit 10 x/342 p/343)) (let (x/340 =a b/335 p/341 =a (makeblock 0 a/334 b/335)) (exit 10 x/340 p/341))) with (10 x/336[int] p/337) (makeblock 0 (int,*) x/336 p/337))) (function a/334[int] b/335[int] (catch (if a/334 (exit 10 a/334 (makeblock 0 a/334 b/335)) (exit 10 b/335 (makeblock 0 a/334 b/335))) with (10 x/336[int] p/337) (makeblock 0 (int,*) x/336 p/337))) - : bool -> bool -> bool * (bool * bool) = <fun> |}] here flattening is an optimisation : the allocation is moved as an alias within each branch , and in the first branch it is unused and will be removed by simplification , so the final code ( see the -dlambda output ) will not allocate in the first branch . alias within each branch, and in the first branch it is unused and will be removed by simplification, so the final code (see the -dlambda output) will not allocate in the first branch. *) let _ = fun a b -> match a, b with | (true as x, _) as _p -> x, (true, true) | (false as x, _) as p -> x, p (* outside, onecase *) [%%expect {| (function a/344[int] b/345[int] (if a/344 (let (x/346 =a[int] a/344 _p/347 =a (makeblock 0 a/344 b/345)) (makeblock 0 (int,*) x/346 [0: 1 1])) (let (x/348 =a[int] a/344 p/349 =a (makeblock 0 a/344 b/345)) (makeblock 0 (int,*) x/348 p/349)))) (function a/344[int] b/345[int] (if a/344 (makeblock 0 (int,*) a/344 [0: 1 1]) (makeblock 0 (int,*) a/344 (makeblock 0 a/344 b/345)))) - : bool -> bool -> bool * (bool * bool) = <fun> |}] let _ = fun a b -> match a, b with | ((true as x, _) as p) | ((false as x, _) as p) -> x, p (* inside, onecase *) [%%expect{| (function a/350[int] b/351 (let (x/352 =a[int] a/350 p/353 =a (makeblock 0 a/350 b/351)) (makeblock 0 (int,*) x/352 p/353))) (function a/350[int] b/351 (makeblock 0 (int,*) a/350 (makeblock 0 a/350 b/351))) - : bool -> 'a -> bool * (bool * 'a) = <fun> |}] type 'a tuplist = Nil | Cons of ('a * 'a tuplist) [%%expect{| 0 0 type 'a tuplist = Nil | Cons of ('a * 'a tuplist) |}] another example where we avoid an allocation in the first case let _ =fun a b -> match a, b with | (true, Cons p) -> p | (_, _) as p -> p (* outside, tuplist *) [%%expect {| (function a/363[int] b/364 (catch (if a/363 (if b/364 (let (p/365 =a (field 0 b/364)) p/365) (exit 12)) (exit 12)) with (12) (let (p/366 =a (makeblock 0 a/363 b/364)) p/366))) (function a/363[int] b/364 (catch (if a/363 (if b/364 (field 0 b/364) (exit 12)) (exit 12)) with (12) (makeblock 0 a/363 b/364))) - : bool -> bool tuplist -> bool * bool tuplist = <fun> |}] let _ = fun a b -> match a, b with | (true, Cons p) | ((_, _) as p) -> p (* inside, tuplist *) [%%expect{| (function a/367[int] b/368 (catch (catch (if a/367 (if b/368 (let (p/372 =a (field 0 b/368)) (exit 13 p/372)) (exit 14)) (exit 14)) with (14) (let (p/371 =a (makeblock 0 a/367 b/368)) (exit 13 p/371))) with (13 p/369) p/369)) (function a/367[int] b/368 (catch (catch (if a/367 (if b/368 (exit 13 (field 0 b/368)) (exit 14)) (exit 14)) with (14) (exit 13 (makeblock 0 a/367 b/368))) with (13 p/369) p/369)) - : bool -> bool tuplist -> bool * bool tuplist = <fun> |}]
null
https://raw.githubusercontent.com/dyzsr/ocaml-selectml/3495de07186fd9e5e1c6b5802ede00199fb1900a/testsuite/tests/basic/patmatch_for_multiple.ml
ocaml
TEST flags = "-drawlambda -dlambda" * expect Note: the tests below contain *both* the -drawlambda and the -dlambda intermediate representations: -drawlambda is the Lambda code generated directly by the pattern-matching compiler; it contain "alias" bindings or static exits that are unused, and will be removed by simplification, or that are used only once, and will be inlined by simplification. -dlambda is the Lambda code resulting from simplification. The -drawlambda output more closely matches what the pattern-compiler produces, and the -dlambda output more closely matches the final generated code. In this test we decided to show both to notice that some allocations are "optimized away" during simplification (see "here flattening is an optimization" below). match*/288 = 3 *match*/289 = 2 *match*/290 = 1) (catch (if (!= *match*/289 3) (if (!= *match*/288 1) 0 (exit 1)) (exit 1)) with (1) 1)) - : bool = false |}];; (* This tests needs to allocate the tuple to bind 'x', but this is only done in the branches that use it. match*/293 = 3 *match*/294 = 2 *match*/295 = 1) (catch (if (!= *match*/294 3) (if (!= *match*/293 1) 0 (exit 4 (makeblock 0 *match*/293 *match*/294 *match*/295))) (exit 4 (makeblock 0 *match*/293 *match*/294 *match*/295))) with (4 x/291) (seq (ignore x/291) 1))) - : bool = false |}];; (* Regression test for #3780 outside, trivial inside, trivial outside, simple inside, simple outside, complex inside, complex outside, onecase inside, onecase outside, tuplist inside, tuplist
match (3, 2, 1) with | (_, 3, _) | (1, _, _) -> true | _ -> false ;; [%%expect{| match*/288 = 3 * match*/289 = 2 * match*/290 = 1 ) ( catch ( catch ( catch ( if ( ! = * ) ( exit 3 ) ( exit 1 ) ) with ( 3 ) ( if ( ! = * match*/288 1 ) ( exit 2 ) ( exit 1 ) ) ) with ( 2 ) 0 ) with ( 1 ) 1 ) ) ( let ( * match*/288 = 3 * match*/289 = 2 * match*/290 = 1 ) ( catch ( if ( ! = * ) ( if ( ! = * match*/288 1 ) 0 ( exit 1 ) ) ( exit 1 ) ) with ( 1 ) 1 ) ) - : bool = false | } ] ; ; ( * This tests needs to allocate the tuple to bind ' x ' , but this is only done in the branches that use it . (catch (catch (catch (if (!= *match*/289 3) (exit 3) (exit 1)) with (3) (if (!= *match*/288 1) (exit 2) (exit 1))) with (2) 0) with (1) 1)) match (3, 2, 1) with | ((_, 3, _) as x) | ((1, _, _) as x) -> ignore x; true | _ -> false ;; [%%expect{| match*/293 = 3 * match*/294 = 2 * match*/295 = 1 ) ( catch ( catch ( catch ( if ( ! = * match*/294 3 ) ( exit 6 ) ( let ( x/297 = a ( makeblock 0 * match*/293 * match*/294 * match*/295 ) ) ( exit 4 x/297 ) ) ) with ( 6 ) ( if ( ! = * match*/293 1 ) ( exit 5 ) ( let ( x/296 = a ( makeblock 0 * match*/293 * match*/294 * match*/295 ) ) ( exit 4 x/296 ) ) ) ) with ( 5 ) 0 ) with ( 4 x/291 ) ( seq ( ignore x/291 ) 1 ) ) ) ( let ( * match*/293 = 3 * match*/294 = 2 * match*/295 = 1 ) ( catch ( if ( ! = * match*/294 3 ) ( if ( ! = * match*/293 1 ) 0 ( exit 4 ( makeblock 0 * match*/293 * match*/294 * match*/295 ) ) ) ( exit 4 ( makeblock 0 * match*/293 * match*/294 * match*/295 ) ) ) with ( 4 x/291 ) ( seq ( ignore x/291 ) 1 ) ) ) - : bool = false | } ] ; ; ( * Regression test for # 3780 (catch (catch (catch (if (!= *match*/294 3) (exit 6) (let (x/297 =a (makeblock 0 *match*/293 *match*/294 *match*/295)) (exit 4 x/297))) with (6) (if (!= *match*/293 1) (exit 5) (let (x/296 =a (makeblock 0 *match*/293 *match*/294 *match*/295)) (exit 4 x/296)))) with (5) 0) with (4 x/291) (seq (ignore x/291) 1))) let _ = fun a b -> match a, b with | ((true, _) as _g) | ((false, _) as _g) -> () [%%expect{| (function a/298[int] b/299 : int 0) (function a/298[int] b/299 : int 0) - : bool -> 'a -> unit = <fun> |}];; More complete tests . The test cases below compare the compiler output on alias patterns that are outside an or - pattern ( handled during half - simplification , then flattened ) or inside an or - pattern ( handled during simplification ) . We used to have a Cannot_flatten exception that would result in fairly different code generated in both cases , but now the compilation strategy is fairly similar . The test cases below compare the compiler output on alias patterns that are outside an or-pattern (handled during half-simplification, then flattened) or inside an or-pattern (handled during simplification). We used to have a Cannot_flatten exception that would result in fairly different code generated in both cases, but now the compilation strategy is fairly similar. *) let _ = fun a b -> match a, b with | (true, _) as p -> p | (false, _) as p -> p [%%expect {| (function a/302[int] b/303 (let (p/304 =a (makeblock 0 a/302 b/303)) p/304)) (function a/302[int] b/303 (makeblock 0 a/302 b/303)) - : bool -> 'a -> bool * 'a = <fun> |}] let _ = fun a b -> match a, b with | ((true, _) as p) | ((false, _) as p) -> p [%%expect{| (function a/306[int] b/307 (let (p/308 =a (makeblock 0 a/306 b/307)) p/308)) (function a/306[int] b/307 (makeblock 0 a/306 b/307)) - : bool -> 'a -> bool * 'a = <fun> |}];; let _ = fun a b -> match a, b with | (true as x, _) as p -> x, p | (false as x, _) as p -> x, p [%%expect {| (function a/312[int] b/313 (let (x/314 =a[int] a/312 p/315 =a (makeblock 0 a/312 b/313)) (makeblock 0 (int,*) x/314 p/315))) (function a/312[int] b/313 (makeblock 0 (int,*) a/312 (makeblock 0 a/312 b/313))) - : bool -> 'a -> bool * (bool * 'a) = <fun> |}] let _ = fun a b -> match a, b with | ((true as x, _) as p) | ((false as x, _) as p) -> x, p [%%expect {| (function a/318[int] b/319 (let (x/320 =a[int] a/318 p/321 =a (makeblock 0 a/318 b/319)) (makeblock 0 (int,*) x/320 p/321))) (function a/318[int] b/319 (makeblock 0 (int,*) a/318 (makeblock 0 a/318 b/319))) - : bool -> 'a -> bool * (bool * 'a) = <fun> |}] let _ = fun a b -> match a, b with | (true as x, _) as p -> x, p | (false, x) as p -> x, p [%%expect{| (function a/328[int] b/329[int] (if a/328 (let (x/330 =a[int] a/328 p/331 =a (makeblock 0 a/328 b/329)) (makeblock 0 (int,*) x/330 p/331)) (let (x/332 =a b/329 p/333 =a (makeblock 0 a/328 b/329)) (makeblock 0 (int,*) x/332 p/333)))) (function a/328[int] b/329[int] (if a/328 (makeblock 0 (int,*) a/328 (makeblock 0 a/328 b/329)) (makeblock 0 (int,*) b/329 (makeblock 0 a/328 b/329)))) - : bool -> bool -> bool * (bool * bool) = <fun> |}] let _ = fun a b -> match a, b with | ((true as x, _) as p) | ((false, x) as p) -> x, p [%%expect{| (function a/334[int] b/335[int] (catch (if a/334 (let (x/342 =a[int] a/334 p/343 =a (makeblock 0 a/334 b/335)) (exit 10 x/342 p/343)) (let (x/340 =a b/335 p/341 =a (makeblock 0 a/334 b/335)) (exit 10 x/340 p/341))) with (10 x/336[int] p/337) (makeblock 0 (int,*) x/336 p/337))) (function a/334[int] b/335[int] (catch (if a/334 (exit 10 a/334 (makeblock 0 a/334 b/335)) (exit 10 b/335 (makeblock 0 a/334 b/335))) with (10 x/336[int] p/337) (makeblock 0 (int,*) x/336 p/337))) - : bool -> bool -> bool * (bool * bool) = <fun> |}] here flattening is an optimisation : the allocation is moved as an alias within each branch , and in the first branch it is unused and will be removed by simplification , so the final code ( see the -dlambda output ) will not allocate in the first branch . alias within each branch, and in the first branch it is unused and will be removed by simplification, so the final code (see the -dlambda output) will not allocate in the first branch. *) let _ = fun a b -> match a, b with | (true as x, _) as _p -> x, (true, true) | (false as x, _) as p -> x, p [%%expect {| (function a/344[int] b/345[int] (if a/344 (let (x/346 =a[int] a/344 _p/347 =a (makeblock 0 a/344 b/345)) (makeblock 0 (int,*) x/346 [0: 1 1])) (let (x/348 =a[int] a/344 p/349 =a (makeblock 0 a/344 b/345)) (makeblock 0 (int,*) x/348 p/349)))) (function a/344[int] b/345[int] (if a/344 (makeblock 0 (int,*) a/344 [0: 1 1]) (makeblock 0 (int,*) a/344 (makeblock 0 a/344 b/345)))) - : bool -> bool -> bool * (bool * bool) = <fun> |}] let _ = fun a b -> match a, b with | ((true as x, _) as p) | ((false as x, _) as p) -> x, p [%%expect{| (function a/350[int] b/351 (let (x/352 =a[int] a/350 p/353 =a (makeblock 0 a/350 b/351)) (makeblock 0 (int,*) x/352 p/353))) (function a/350[int] b/351 (makeblock 0 (int,*) a/350 (makeblock 0 a/350 b/351))) - : bool -> 'a -> bool * (bool * 'a) = <fun> |}] type 'a tuplist = Nil | Cons of ('a * 'a tuplist) [%%expect{| 0 0 type 'a tuplist = Nil | Cons of ('a * 'a tuplist) |}] another example where we avoid an allocation in the first case let _ =fun a b -> match a, b with | (true, Cons p) -> p | (_, _) as p -> p [%%expect {| (function a/363[int] b/364 (catch (if a/363 (if b/364 (let (p/365 =a (field 0 b/364)) p/365) (exit 12)) (exit 12)) with (12) (let (p/366 =a (makeblock 0 a/363 b/364)) p/366))) (function a/363[int] b/364 (catch (if a/363 (if b/364 (field 0 b/364) (exit 12)) (exit 12)) with (12) (makeblock 0 a/363 b/364))) - : bool -> bool tuplist -> bool * bool tuplist = <fun> |}] let _ = fun a b -> match a, b with | (true, Cons p) | ((_, _) as p) -> p [%%expect{| (function a/367[int] b/368 (catch (catch (if a/367 (if b/368 (let (p/372 =a (field 0 b/368)) (exit 13 p/372)) (exit 14)) (exit 14)) with (14) (let (p/371 =a (makeblock 0 a/367 b/368)) (exit 13 p/371))) with (13 p/369) p/369)) (function a/367[int] b/368 (catch (catch (if a/367 (if b/368 (exit 13 (field 0 b/368)) (exit 14)) (exit 14)) with (14) (exit 13 (makeblock 0 a/367 b/368))) with (13 p/369) p/369)) - : bool -> bool tuplist -> bool * bool tuplist = <fun> |}]
d58b6773412e7bdfa72752e4e217bf8f76fc78882e00f139a352bb5ae01aed4e
ahungry/ahungry-fleece
skeleton.run.tests.lisp
;; skeleton - A project template generated by ahungry-fleece Copyright ( C ) 2016 Your Name < > ;; ;; This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation , either version 3 of the License , or ;; (at your option) any later version. ;; ;; This program is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU Affero General Public License for more details. ;; You should have received a copy of the GNU Affero General Public License ;; along with this program. If not, see </>. ;;;; skeleton.run.tests.lisp (in-package #:cl-user) (defpackage skeleton.run.tests (:use :cl :skeleton.lib.stub :af.lib.ansi-colors :af.lib.coverage :af.lib.testy) (:export :main)) (in-package #:skeleton.run.tests) (defparameter *base-directory* (asdf:system-source-directory :skeleton)) (defun main () "Run the tests, or the tests with coverage." (if (and (sb-ext:posix-getenv "AF_LIB_TESTY_COVERAGE") (> (length (sb-ext:posix-getenv "AF_LIB_TESTY_COVERAGE")) 0)) (coverage) (test) )) (defun test () "Begin the tests!" (unless (and (sb-ext:posix-getenv "AF_LIB_TESTY_COLORIZE") (> (length (sb-ext:posix-getenv "AF_LIB_TESTY_COLORIZE")) 0)) (setf af.lib.ansi-colors:*colorize-p* nil)) (if (suite "skeleton.lib" (desc "skeleton.lib.stub" (it "Should echo the input" (eq 3 (skeleton.lib.stub:echo 3))) ) ) ;; end suite (setf sb-ext:*exit-hooks* (list (lambda () (sb-ext:exit :code 0)))) (setf sb-ext:*exit-hooks* (list (lambda () (sb-ext:exit :code 1))))) ) (defun coverage () "Begin the tests!" ;; See if we're in the shell environment or not (SLIME will use 'dumb' here) (af.lib.coverage:with-coverage :skeleton (test) (terpri) (with-color :blue (format t "Summary of coverage:~%")) (with-open-stream (*error-output* (make-broadcast-stream)) (af.contrib.sb-cover:report (merge-pathnames #P"coverage/" *base-directory*))) (with-open-stream (*error-output* (make-broadcast-stream)) (af.lib.coverage:report-cli (merge-pathnames #P"coverage/" *base-directory*)) ) (with-open-stream (*error-output* (make-broadcast-stream)) (af.lib.coverage:report-json (merge-pathnames #P"coverage/" *base-directory*)) ) (with-color :light-blue (format t "~%Full coverage report generated in: ~a" (merge-pathnames #P"coverage/" *base-directory*)) (format t "~%Coverage summary generated in: ~acoverage.json~%~%" (merge-pathnames #P"coverage/" *base-directory*)) ) ) ) ;;; "skeleton.run.tests" goes here. Hacks and glory await!
null
https://raw.githubusercontent.com/ahungry/ahungry-fleece/1cef1d3a3aa9cffe9f06b7632006565bbc986814/skel/t/skeleton.run.tests.lisp
lisp
skeleton - A project template generated by ahungry-fleece This program is free software: you can redistribute it and/or modify (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 Affero General Public License for more details. along with this program. If not, see </>. skeleton.run.tests.lisp end suite See if we're in the shell environment or not (SLIME will use 'dumb' here) "skeleton.run.tests" goes here. Hacks and glory await!
Copyright ( C ) 2016 Your Name < > it under the terms of the GNU Affero 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 Affero General Public License (in-package #:cl-user) (defpackage skeleton.run.tests (:use :cl :skeleton.lib.stub :af.lib.ansi-colors :af.lib.coverage :af.lib.testy) (:export :main)) (in-package #:skeleton.run.tests) (defparameter *base-directory* (asdf:system-source-directory :skeleton)) (defun main () "Run the tests, or the tests with coverage." (if (and (sb-ext:posix-getenv "AF_LIB_TESTY_COVERAGE") (> (length (sb-ext:posix-getenv "AF_LIB_TESTY_COVERAGE")) 0)) (coverage) (test) )) (defun test () "Begin the tests!" (unless (and (sb-ext:posix-getenv "AF_LIB_TESTY_COLORIZE") (> (length (sb-ext:posix-getenv "AF_LIB_TESTY_COLORIZE")) 0)) (setf af.lib.ansi-colors:*colorize-p* nil)) (if (suite "skeleton.lib" (desc "skeleton.lib.stub" (it "Should echo the input" (eq 3 (skeleton.lib.stub:echo 3))) ) (setf sb-ext:*exit-hooks* (list (lambda () (sb-ext:exit :code 0)))) (setf sb-ext:*exit-hooks* (list (lambda () (sb-ext:exit :code 1))))) ) (defun coverage () "Begin the tests!" (af.lib.coverage:with-coverage :skeleton (test) (terpri) (with-color :blue (format t "Summary of coverage:~%")) (with-open-stream (*error-output* (make-broadcast-stream)) (af.contrib.sb-cover:report (merge-pathnames #P"coverage/" *base-directory*))) (with-open-stream (*error-output* (make-broadcast-stream)) (af.lib.coverage:report-cli (merge-pathnames #P"coverage/" *base-directory*)) ) (with-open-stream (*error-output* (make-broadcast-stream)) (af.lib.coverage:report-json (merge-pathnames #P"coverage/" *base-directory*)) ) (with-color :light-blue (format t "~%Full coverage report generated in: ~a" (merge-pathnames #P"coverage/" *base-directory*)) (format t "~%Coverage summary generated in: ~acoverage.json~%~%" (merge-pathnames #P"coverage/" *base-directory*)) ) ) )
676dec24a4f4863bd9bb634274df83e8f0d8da6ffe33dbf962eab3dc2b04fc2e
cofree-coffee/cofree-bot
Utils.hs
# LANGUAGE PatternSynonyms # module Data.Chat.Utils ( -- * Product type (/\), pattern (:&), (|*|), type (/+\), can, * type (\/), -- * Wedge Product type (\*/), -- * MTL Helpers Transformers, duplicate, indistinct, -- * Misc distinguish, PointedChoice (..), readFileMaybe, ) where ------------------------------------------------------------------------------- import Control.Applicative import Control.Arrow ((&&&)) import Control.Exception (catch, throwIO) import Data.Kind import Data.Text (Text) import Data.Text.IO qualified as Text.IO import Data.These (These (..)) import System.IO.Error (isDoesNotExistError) ------------------------------------------------------------------------------- type (/\) = (,) infixr 6 /\ pattern (:&) :: a -> b -> (a, b) pattern a :& b = (a, b) # COMPLETE (: & ) # infixr 9 :& (|*|) :: Applicative f => f a -> f b -> f (a /\ b) (|*|) = liftA2 (,) infixr 9 |*| ------------------------------------------------------------------------------- type (\/) = Either infixr 6 \/ ------------------------------------------------------------------------------- type a \*/ b = Maybe (Either a b) infixr 6 \*/ ------------------------------------------------------------------------------- type a /+\ b = These a b infixr 6 /+\ can :: Maybe a -> Maybe b -> Maybe (a /+\ b) can Nothing Nothing = Nothing can (Just a) Nothing = Just (This a) can Nothing (Just b) = Just (That b) can (Just a) (Just b) = Just (These a b) ------------------------------------------------------------------------------- type Transformers :: [(Type -> Type) -> Type -> Type] -> (Type -> Type) -> Type -> Type type family Transformers ts m where Transformers '[] m = m Transformers (t ': ts) m = t (Transformers ts m) duplicate :: x -> (x, x) duplicate = id &&& id indistinct :: Either x x -> x indistinct = id `either` id -------------------------------------------------------------------------------- distinguish :: (a -> Bool) -> a -> Either a a distinguish f x | f x = Right x | otherwise = Left x class PointedChoice p where pleft :: p a b -> p (x \*/ a) (x \*/ b) pright :: p a b -> p (a \*/ x) (b \*/ x) -------------------------------------------------------------------------------- readFileMaybe :: String -> IO (Maybe Text) readFileMaybe path = fmap Just (Text.IO.readFile path) `catch` \e -> if isDoesNotExistError e then pure Nothing else throwIO e
null
https://raw.githubusercontent.com/cofree-coffee/cofree-bot/2466a444f17c560bfbadcad328f8a8c08d8da896/chat-bots/src/Data/Chat/Utils.hs
haskell
* Product * Wedge Product * MTL Helpers * Misc ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- ------------------------------------------------------------------------------ ------------------------------------------------------------------------------
# LANGUAGE PatternSynonyms # module Data.Chat.Utils type (/\), pattern (:&), (|*|), type (/+\), can, * type (\/), type (\*/), Transformers, duplicate, indistinct, distinguish, PointedChoice (..), readFileMaybe, ) where import Control.Applicative import Control.Arrow ((&&&)) import Control.Exception (catch, throwIO) import Data.Kind import Data.Text (Text) import Data.Text.IO qualified as Text.IO import Data.These (These (..)) import System.IO.Error (isDoesNotExistError) type (/\) = (,) infixr 6 /\ pattern (:&) :: a -> b -> (a, b) pattern a :& b = (a, b) # COMPLETE (: & ) # infixr 9 :& (|*|) :: Applicative f => f a -> f b -> f (a /\ b) (|*|) = liftA2 (,) infixr 9 |*| type (\/) = Either infixr 6 \/ type a \*/ b = Maybe (Either a b) infixr 6 \*/ type a /+\ b = These a b infixr 6 /+\ can :: Maybe a -> Maybe b -> Maybe (a /+\ b) can Nothing Nothing = Nothing can (Just a) Nothing = Just (This a) can Nothing (Just b) = Just (That b) can (Just a) (Just b) = Just (These a b) type Transformers :: [(Type -> Type) -> Type -> Type] -> (Type -> Type) -> Type -> Type type family Transformers ts m where Transformers '[] m = m Transformers (t ': ts) m = t (Transformers ts m) duplicate :: x -> (x, x) duplicate = id &&& id indistinct :: Either x x -> x indistinct = id `either` id distinguish :: (a -> Bool) -> a -> Either a a distinguish f x | f x = Right x | otherwise = Left x class PointedChoice p where pleft :: p a b -> p (x \*/ a) (x \*/ b) pright :: p a b -> p (a \*/ x) (b \*/ x) readFileMaybe :: String -> IO (Maybe Text) readFileMaybe path = fmap Just (Text.IO.readFile path) `catch` \e -> if isDoesNotExistError e then pure Nothing else throwIO e
2a38858f047fab1f3d9bf2a9be46c2d2bc53d1f7640be7b98e95678679b78f7e
heraldry/heraldicon
attribution.cljs
(ns heraldicon.frontend.attribution (:require [clojure.string :as str] [heraldicon.context :as c] [heraldicon.entity.attribution :as attribution] [heraldicon.frontend.language :refer [tr]] [heraldicon.frontend.repository.entity-for-rendering :as entity-for-rendering] [heraldicon.heraldry.escutcheon :as escutcheon] [heraldicon.interface :as interface] [heraldicon.render.theme :as theme] [re-frame.core :as rf])) (defn- credits [{:keys [url title username creator-name creator-link nature license license-version source-license source-license-version source-name source-link source-creator-name source-creator-link source-modification]}] (let [license-url (attribution/license-url license license-version) license-display-name (attribution/license-display-name license license-version) source-license-url (attribution/license-url source-license source-license-version) source-license-display-name (attribution/license-display-name source-license source-license-version) source-modification (str/trim (or source-modification ""))] [:div.credit [:<> (if url [:a {:href url :target "_blank"} [tr title]] [:span [tr title]]) (if username [:<> " " [tr :string.miscellaneous/by] " " [:a {:href (attribution/full-url-for-username username) :target "_blank"} username]] (when-not (str/blank? creator-name) [:<> " " [tr :string.miscellaneous/by] " " (if creator-link [:a {:href creator-link :target "_blank"} creator-name] [:span creator-name])])) " " (case (or license :none) :none [tr :string.attribution/is-private] :public-domain [tr :string.attribution/is-in-the-public-domain] [:<> [tr :string.attribution/is-licensed-under] " " [:a {:href license-url :target "_blank"} license-display-name]]) (when (= nature :derivative) [:div.sub-credit [tr :string.attribution/source] ": " (if (str/blank? source-name) [tr :string.miscellaneous/unnamed] [:a {:href source-link :target "_blank"} " " source-name]) (when-not (str/blank? source-creator-name) [:<> " " [tr :string.miscellaneous/by] " " [:a {:href source-creator-link :target "_blank"} source-creator-name]]) " " (case (or source-license :none) :none [tr :string.attribution/is-private] :public-domain [tr :string.attribution/is-in-the-public-domain] [:<> [tr :string.attribution/is-licensed-under] " " [:a {:href source-license-url :target "_blank"} source-license-display-name]]) (when-not (str/blank? source-modification) [:<> " " [tr :string.attribution/modifications] ": " source-modification])])]])) (defn for-entity [context] (let [id (interface/get-raw-data (c/++ context :id))] [:div.credit (if id (let [attribution (interface/get-sanitized-data (c/++ context :attribution)) title (interface/get-raw-data (c/++ context :name)) username (interface/get-raw-data (c/++ context :username)) url (attribution/full-url-for-entity context)] [credits (assoc attribution :title title :username username :url url)]) [tr :string.miscellaneous/unsaved-data])])) (defn for-escutcheons [escutcheon inescutcheons] (let [all-escutcheons (sort (conj inescutcheons escutcheon))] [:<> [:h3 [tr :string.render-options/escutcheon]] (for [escutcheon all-escutcheons] ^{:key escutcheon} [credits (assoc (escutcheon/attribution escutcheon) :title (escutcheon/escutcheon-map escutcheon))])])) (defn for-theme [theme] [:<> [:h3 [tr :string.render-options/theme]] [credits (assoc (theme/attribution theme) :title (theme/theme-map theme))]]) (defn for-entities [entities] (let [entity-paths (keep (fn [{:keys [id version]}] (when id (some-> @(rf/subscribe [::entity-for-rendering/data id version]) :path (conj :entity)))) entities) entity-type (when-let [path (first entity-paths)] (interface/get-raw-data {:path (conj path :type)})) title (case entity-type :heraldicon.entity.type/arms :string.entity/arms :heraldicon.entity.type/charge :string.entity/charges :heraldicon.entity.type/ribbon :string.entity/ribbons :heraldicon.entity.type/collection :string.entity/collections nil)] (when (seq entity-paths) [:<> [:h3 [tr title]] (into [:ul] (keep (fn [path] ^{:key path} [:li [for-entity {:path path}]])) entity-paths)]))) (defn attribution [context & sections] (into [:div.attribution [:h3 [tr :string.attribution/license]] [for-entity context]] sections))
null
https://raw.githubusercontent.com/heraldry/heraldicon/54e003614cf2c14cda496ef36358059ba78275b0/src/heraldicon/frontend/attribution.cljs
clojure
(ns heraldicon.frontend.attribution (:require [clojure.string :as str] [heraldicon.context :as c] [heraldicon.entity.attribution :as attribution] [heraldicon.frontend.language :refer [tr]] [heraldicon.frontend.repository.entity-for-rendering :as entity-for-rendering] [heraldicon.heraldry.escutcheon :as escutcheon] [heraldicon.interface :as interface] [heraldicon.render.theme :as theme] [re-frame.core :as rf])) (defn- credits [{:keys [url title username creator-name creator-link nature license license-version source-license source-license-version source-name source-link source-creator-name source-creator-link source-modification]}] (let [license-url (attribution/license-url license license-version) license-display-name (attribution/license-display-name license license-version) source-license-url (attribution/license-url source-license source-license-version) source-license-display-name (attribution/license-display-name source-license source-license-version) source-modification (str/trim (or source-modification ""))] [:div.credit [:<> (if url [:a {:href url :target "_blank"} [tr title]] [:span [tr title]]) (if username [:<> " " [tr :string.miscellaneous/by] " " [:a {:href (attribution/full-url-for-username username) :target "_blank"} username]] (when-not (str/blank? creator-name) [:<> " " [tr :string.miscellaneous/by] " " (if creator-link [:a {:href creator-link :target "_blank"} creator-name] [:span creator-name])])) " " (case (or license :none) :none [tr :string.attribution/is-private] :public-domain [tr :string.attribution/is-in-the-public-domain] [:<> [tr :string.attribution/is-licensed-under] " " [:a {:href license-url :target "_blank"} license-display-name]]) (when (= nature :derivative) [:div.sub-credit [tr :string.attribution/source] ": " (if (str/blank? source-name) [tr :string.miscellaneous/unnamed] [:a {:href source-link :target "_blank"} " " source-name]) (when-not (str/blank? source-creator-name) [:<> " " [tr :string.miscellaneous/by] " " [:a {:href source-creator-link :target "_blank"} source-creator-name]]) " " (case (or source-license :none) :none [tr :string.attribution/is-private] :public-domain [tr :string.attribution/is-in-the-public-domain] [:<> [tr :string.attribution/is-licensed-under] " " [:a {:href source-license-url :target "_blank"} source-license-display-name]]) (when-not (str/blank? source-modification) [:<> " " [tr :string.attribution/modifications] ": " source-modification])])]])) (defn for-entity [context] (let [id (interface/get-raw-data (c/++ context :id))] [:div.credit (if id (let [attribution (interface/get-sanitized-data (c/++ context :attribution)) title (interface/get-raw-data (c/++ context :name)) username (interface/get-raw-data (c/++ context :username)) url (attribution/full-url-for-entity context)] [credits (assoc attribution :title title :username username :url url)]) [tr :string.miscellaneous/unsaved-data])])) (defn for-escutcheons [escutcheon inescutcheons] (let [all-escutcheons (sort (conj inescutcheons escutcheon))] [:<> [:h3 [tr :string.render-options/escutcheon]] (for [escutcheon all-escutcheons] ^{:key escutcheon} [credits (assoc (escutcheon/attribution escutcheon) :title (escutcheon/escutcheon-map escutcheon))])])) (defn for-theme [theme] [:<> [:h3 [tr :string.render-options/theme]] [credits (assoc (theme/attribution theme) :title (theme/theme-map theme))]]) (defn for-entities [entities] (let [entity-paths (keep (fn [{:keys [id version]}] (when id (some-> @(rf/subscribe [::entity-for-rendering/data id version]) :path (conj :entity)))) entities) entity-type (when-let [path (first entity-paths)] (interface/get-raw-data {:path (conj path :type)})) title (case entity-type :heraldicon.entity.type/arms :string.entity/arms :heraldicon.entity.type/charge :string.entity/charges :heraldicon.entity.type/ribbon :string.entity/ribbons :heraldicon.entity.type/collection :string.entity/collections nil)] (when (seq entity-paths) [:<> [:h3 [tr title]] (into [:ul] (keep (fn [path] ^{:key path} [:li [for-entity {:path path}]])) entity-paths)]))) (defn attribution [context & sections] (into [:div.attribution [:h3 [tr :string.attribution/license]] [for-entity context]] sections))
ae85fbd943d62e7c5ea8c7ef1736e0b5ff9b71ea300740d313d4798e0880d3aa
tonyrog/canopen
co_sdo_srv_SUITE.erl
%% coding: latin-1 %%%---- BEGIN COPYRIGHT -------------------------------------------------------- %%% Copyright ( C ) 2007 - 2012 , Rogvall Invest AB , < > %%% %%% This software is licensed as described in the file COPYRIGHT, which %%% you should have received as part of this distribution. The terms %%% are also available at . %%% %%% You may opt to use, copy, modify, merge, publish, distribute and/or sell copies of the Software , and permit persons to whom the Software is %%% furnished to do so, under the terms of the COPYRIGHT file. %%% This software is distributed on an " AS IS " basis , WITHOUT WARRANTY OF ANY %%% KIND, either express or implied. %%% %%%---- END COPYRIGHT ---------------------------------------------------------- %%%------------------------------------------------------------------- @author Lönne < > ( C ) 2011 , Marina Westman Lönne %%% @doc %%% %%% @end Created : 29 Nov 2011 by Marina Westman Lönne < > %%%------------------------------------------------------------------- -module(co_sdo_srv_SUITE). %% Note: This directive should only be used in test suites. -compile(export_all). -include_lib("common_test/include/ct.hrl"). %%-------------------------------------------------------------------- %% COMMON TEST CALLBACK FUNCTIONS %%-------------------------------------------------------------------- %%-------------------------------------------------------------------- %% @doc %% Returns list of tuples to set default properties %% for the suite. %% %% Function: suite() -> Info %% %% Info = [tuple()] %% List of key/value pairs. %% %% Note: The suite/0 function is only meant to be used to return %% default data values, not perform any other operations. %% @spec suite ( ) - > Info %% @end %%-------------------------------------------------------------------- suite() -> [{timetrap,{minutes,10}}, {require, serial}, {require, dict}]. %%-------------------------------------------------------------------- %% @doc %% Returns the list of groups and test cases that %% are to be executed. %% = [ { group , GroupName } | TestCase ] %% GroupName = atom() %% Name of a test case group. TestCase = atom ( ) %% Name of a test case. %% Reason = term() %% The reason for skipping all groups and test cases. %% @spec all ( ) - > GroupsAndTestCases | { skip , Reason } %% @end %%-------------------------------------------------------------------- all() -> [set_dict_segment, get_dict_segment, set_dict_block, get_dict_block, set_atomic_segment, get_atomic_segment, set_atomic_block, get_atomic_block, set_atomic_exp, get_atomic_exp, set_atomic_m_segment, get_atomic_m_segment, set_atomic_m_block, get_atomic_m_block, set_streamed_segment, get_streamed_segment, set_streamed_block, get_streamed_block, set_streamed_exp, get_streamed_exp, set_streamed_m_segment, get_streamed_m_segment, set_streamed_m_block, get_streamed_m_block, set_atomic_int, get_atomic_int, set_atomic_si, get_atomic_si, stream_file_segment, stream_file_block, stream_0file_segment, stream_0file_block, notify, mpdo, timeout, change_timeout]. %% break]. %-------------------------------------------------------------------- %% @doc %% Initialization before the whole suite %% %% Config0 = Config1 = [tuple()] %% A list of key/value pairs, holding the test case configuration. %% Reason = term() %% The reason for skipping the suite. %% %% Note: This function is free to add any key/value pairs to the Config %% variable, but should NOT alter/remove any existing entries. %% @spec init_per_suite(Config0 ) - > Config1 | { skip , Reason } | { skip_and_save , Reason , Config1 } %% @end %%-------------------------------------------------------------------- init_per_suite(Config) -> co_test_lib:start_system(), co_test_lib:start_node(Config), Config. %%-------------------------------------------------------------------- %% @doc %% Cleanup after the whole suite %% %% Config - [tuple()] %% A list of key/value pairs, holding the test case configuration. %% ) - > _ %% @end %%-------------------------------------------------------------------- end_per_suite(Config) -> co_test_lib:stop_node(Config), co_test_lib:stop_system(), ok. %%-------------------------------------------------------------------- %% @doc %% Initialization before each test case %% %% TestCase - atom() %% Name of the test case that is about to be run. %% Config0 = Config1 = [tuple()] %% A list of key/value pairs, holding the test case configuration. %% Reason = term() %% The reason for skipping the test case. %% %% Note: This function is free to add any key/value pairs to the Config %% variable, but should NOT alter/remove any existing entries. %% @spec init_per_testcase(TestCase , Config0 ) - > Config1 | { skip , Reason } | { skip_and_save , Reason , Config1 } %% @end %%-------------------------------------------------------------------- init_per_testcase(_TestCase = timeout, Config) -> ct:pal("Testcase: ~p", [_TestCase]), {ok, Pid} = co_test_app:start(serial(), app_dict()), ok = co_test_app:debug(Pid, true), Change the timeout for the {sdo_timeout, OldTOut} = co_api:get_option(serial(), sdo_timeout), ok = co_api:set_option(serial(), sdo_timeout, 500), [{timeout, OldTOut} | Config]; init_per_testcase(_TestCase, Config) -> ct:pal("Testcase: ~p", [_TestCase]), {ok, Pid} = co_test_app:start(serial(), app_dict()), ok = co_test_app:debug(Pid, true), Config. %%-------------------------------------------------------------------- %% @doc %% Cleanup after each test case %% %% TestCase - atom() %% Name of the test case that is finished. %% Config0 = Config1 = [tuple()] %% A list of key/value pairs, holding the test case configuration. %% , Config0 ) - > void ( ) | { save_config , Config1 } | { fail , Reason } %% @end %%-------------------------------------------------------------------- end_per_testcase(Case, Config) when Case == stream_file_segment; Case == stream_file_block; Case == stream_0file_segment; Case == stream_0file_block -> co_test_stream_app:stop(), PrivDir = ?config(priv_dir, Config), RFile = filename:join(PrivDir, ct:get_config(read_file)), WFile = filename:join(PrivDir, ct:get_config(write_file)), os:cmd("rm " ++ RFile), os:cmd("rm " ++ WFile), ok; end_per_testcase(timeout, Config) -> %% Wait a little for session to terminate timer:sleep(1000), co_test_app:stop(serial()), Restore the timeout for the OldTOut = ?config(timeout, Config), co_api:set_option(serial(), sdo_timeout, OldTOut), ok; end_per_testcase(_TestCase, _Config) -> %% Wait a little for session to terminate timer:sleep(1000), co_test_app:stop(serial()), ok. %%-------------------------------------------------------------------- %% TEST CASES %%-------------------------------------------------------------------- %%-------------------------------------------------------------------- @spec set_dict_segment(Config ) - > ok %% @doc Sets a value in the internal dict using segment between cocli and . %% @end %%-------------------------------------------------------------------- set_dict_segment(Config) -> set(Config, ct:get_config(dict_index), segment). %%-------------------------------------------------------------------- ) - > ok %% @doc Gets a value from the internal dict using segment between cocli and . %% @end %%-------------------------------------------------------------------- get_dict_segment(Config) -> get(Config, ct:get_config(dict_index), segment). %%-------------------------------------------------------------------- @spec set_dict_block(Config ) - > ok %% @doc Sets a value in the internal dict using block between cocli and %% @end %%-------------------------------------------------------------------- set_dict_block(Config) -> set(Config, ct:get_config(dict_index), block). %%-------------------------------------------------------------------- ) - > ok %% @doc Gets a value from the co_node internal using block between cocli and . %% @end %%-------------------------------------------------------------------- get_dict_block(Config) -> get(Config, ct:get_config(dict_index), block). %%-------------------------------------------------------------------- set_atomic_segment(Config ) - > ok %% @doc Sets a value using segment between cocli and and atomic between and application . %% @end %%-------------------------------------------------------------------- set_atomic_segment(Config) -> set(Config, ct:get_config({dict, atomic}), segment). %%-------------------------------------------------------------------- ) - > ok %% @doc Gets a value using segment between cocli and and atomic between and application . %% @end %%-------------------------------------------------------------------- get_atomic_segment(Config) -> get(Config, ct:get_config({dict, atomic}), segment). %%-------------------------------------------------------------------- @spec set_atomic_block(Config ) - > ok %% @doc Sets a value using block between cocli and and atomic between and application . %% @end %%-------------------------------------------------------------------- set_atomic_block(Config) -> set(Config, ct:get_config({dict, atomic}), block). %%-------------------------------------------------------------------- get_atomic_block(Config ) - > ok %% @doc Gets a value using block between cocli and and atomic between and application . %% @end %%-------------------------------------------------------------------- get_atomic_block(Config) -> get(Config, ct:get_config({dict, atomic}), block). %%-------------------------------------------------------------------- @spec set_atomic_exp(Config ) - > ok %% @doc Sets a short value using segment between cocli and and atomic between and application . %% @end %%-------------------------------------------------------------------- set_atomic_exp(Config) -> set(Config, ct:get_config({dict, atomic_exp}), segment). %%-------------------------------------------------------------------- get_atomic_exp(Config ) - > ok %% @doc Gets a short value using segment between cocli and and atomic atomic between and application . %% @end %%-------------------------------------------------------------------- get_atomic_exp(Config) -> get(Config, ct:get_config({dict, atomic_exp}), segment). %%-------------------------------------------------------------------- %% @spec set_streamed_segment(Config) -> ok %% @doc Sets a value using segment between cocli and and streamed between and application . %% @end %%-------------------------------------------------------------------- set_streamed_segment(Config) -> set(Config, ct:get_config({dict, streamed}), segment). %%-------------------------------------------------------------------- %% @spec get_streamed_segment(Config) -> ok %% @doc Gets a value using segment between cocli and and streamed atomic between and application . %% @end %%-------------------------------------------------------------------- get_streamed_segment(Config) -> get(Config, ct:get_config({dict, streamed}), segment). %%-------------------------------------------------------------------- set_streamed_block(Config ) - > ok %% @doc Sets a value using block between cocli and and streamed atomic between and application . %% @end %%-------------------------------------------------------------------- set_streamed_block(Config) -> set(Config, ct:get_config({dict, streamed}), block). %%-------------------------------------------------------------------- get_streamed_block(Config ) - > ok %% @doc Gets a value using block between cocli and and streamed atomic between and application . %% @end %%-------------------------------------------------------------------- get_streamed_block(Config) -> get(Config, ct:get_config({dict, streamed}), block). %%-------------------------------------------------------------------- ) - > ok %% @doc Sets a short value using segment between cocli and and streamed atomic between and application . %% @end %%-------------------------------------------------------------------- set_streamed_exp(Config) -> set(Config, ct:get_config({dict, streamed_exp}), segment). %%-------------------------------------------------------------------- ) - > ok %% @doc Gets a short value using segment between cocli and and streamed atomic between and application . %% @end %%-------------------------------------------------------------------- get_streamed_exp(Config) -> get(Config, ct:get_config({dict, streamed_exp}), segment). %%-------------------------------------------------------------------- ) - > ok %% @doc Sets a value using segment between cocli and and { atomic , Module } between and application . %% @end %%-------------------------------------------------------------------- set_atomic_m_segment(Config) -> set(Config, ct:get_config({dict, atomic_m}), segment). %%-------------------------------------------------------------------- ) - > ok %% @doc Gets a value using segment between cocli and and { atomic , Module } between and application . %% @end %%-------------------------------------------------------------------- get_atomic_m_segment(Config) -> get(Config, ct:get_config({dict, atomic_m}), segment). %%-------------------------------------------------------------------- ) - > ok %% @doc Sets a value using segment between cocli and and { atomic , Module } between and application . %% @end %%-------------------------------------------------------------------- set_atomic_m_block(Config) -> set(Config, ct:get_config({dict, atomic_m}), block). %%-------------------------------------------------------------------- ) - > ok %% @doc Gets a value using segment between cocli and and { atomic , Module } atomic_m between and application . %% @end %%-------------------------------------------------------------------- get_atomic_m_block(Config) -> get(Config, ct:get_config({dict, atomic_m}), block). %%-------------------------------------------------------------------- ) - > ok %% @doc Sets a value using segment between cocli and and { streamed , Module } atomic_m between and application . %% @end %%-------------------------------------------------------------------- set_streamed_m_segment(Config) -> set(Config, ct:get_config({dict, streamed_m}), segment). %%-------------------------------------------------------------------- ) - > ok %% @doc Gets a value using segment between cocli and and { streamed , Module } atomic_m between and application . %% @end %%-------------------------------------------------------------------- get_streamed_m_segment(Config) -> get(Config, ct:get_config({dict, streamed_m}), segment). %%-------------------------------------------------------------------- ) - > ok %% @doc Sets a value using block between cocli and and { streamed , Module } atomic_m between and application . %% @end %%-------------------------------------------------------------------- set_streamed_m_block(Config) -> set(Config, ct:get_config({dict, streamed_m}), block). %%-------------------------------------------------------------------- ) - > ok %% @doc Gets a value using block between cocli and and { streamed , Module } between and application . %% @end %%-------------------------------------------------------------------- get_streamed_m_block(Config) -> get(Config, ct:get_config({dict, streamed_m}), block). %%-------------------------------------------------------------------- ) - > ok %% @doc Sets an integer value using segment between cocli and and atomic between and application . %% @end %%-------------------------------------------------------------------- set_atomic_int(Config) -> set(Config, ct:get_config({dict, atomic_int}), segment). %%-------------------------------------------------------------------- ) - > ok %% @doc Gets an integer value using segment between cocli and and atomic between and application . %% @end %%-------------------------------------------------------------------- get_atomic_int(Config) -> get(Config, ct:get_config({dict, atomic_int}), segment). %%-------------------------------------------------------------------- ) - > ok %% @doc Sets an integer value using segment between cocli and and atomic between and application . %% @end %%-------------------------------------------------------------------- set_atomic_si(Config) -> set(Config, ct:get_config({dict, atomic_si}), segment). %%-------------------------------------------------------------------- ) - > ok %% @doc Gets an integer value using segment between cocli and and atomic between and application . %% @end %%-------------------------------------------------------------------- get_atomic_si(Config) -> get(Config, ct:get_config({dict, atomic_si}), segment). %%-------------------------------------------------------------------- @spec stream_file_segment(Config ) - > ok %% @doc Tests streaming of file cocli - > co_test_stream_app - > cocli %% @end %%-------------------------------------------------------------------- stream_file_segment(Config) -> stream_file(Config, segment, 50). %%-------------------------------------------------------------------- %% @spec stream_file_block(Config) -> ok %% @doc Tests streaming of file cocli - > co_test_stream_app - > cocli %% @end %%-------------------------------------------------------------------- stream_file_block(Config) -> stream_file(Config, block, 50). %%-------------------------------------------------------------------- @spec stream_0file_segment(Config ) - > ok %% @doc Tests streaming of 0 size file cocli - > co_test_stream_app - > cocli %% @end %%-------------------------------------------------------------------- stream_0file_segment(Config) -> stream_file(Config, segment, 0). %%-------------------------------------------------------------------- stream_0file_block(Config ) - > ok %% @doc Tests streaming of 0 size file cocli - > co_test_stream_app - > cocli %% @end %%-------------------------------------------------------------------- stream_0file_block(Config) -> stream_file(Config, block, 0). %%-------------------------------------------------------------------- %% @spec notify(Config) -> ok %% @doc Sets a value for an index in the dictionary on which %% co_test_app subscribes. %% @end %%-------------------------------------------------------------------- notify(Config) -> {{Index = {Ix, _Si}, Type, _M, _Org}, NewValue} = ct:get_config({dict, notify}), [] = os:cmd(co_test_lib:set_cmd(Config, Index, NewValue, Type, segment)), wait({object_event, Ix}, 5000), ok. %%-------------------------------------------------------------------- %% @spec mpdo(Config) -> ok %% @doc %% Sends an mpdo that is broadcasted to all subscribers. %% @end %%-------------------------------------------------------------------- mpdo(Config) -> {{Index = {Ix, _Si}, _T, _M, _Org}, NewValue} = ct:get_config({dict, mpdo}), "ok\n" = os:cmd(co_test_lib:notify_cmd(Config, Index, NewValue, segment)), wait({notify, Ix}, 5000), ok. %%-------------------------------------------------------------------- %% @spec timeout(Config) -> ok %% @doc %% Negative test of what happens if the receiving causes a timeout. %% @end %%-------------------------------------------------------------------- timeout(Config) -> %% Set {{Index, Type, _M, _Org}, NewValue} = ct:get_config({dict, timeout}), "cocli: error: set failed: timed out\r\n" = os:cmd(co_test_lib:set_cmd(Config, Index, NewValue, Type, segment)), wait({set, Index, NewValue}, 5000), %% Get "cocli: error: failed to retrieve value for '0x7334' timed out\r\n" = os:cmd(co_test_lib:get_cmd(Config, Index, Type, segment)). %%-------------------------------------------------------------------- %% @spec change_timeout(Config) -> ok %% @doc %% A test of having an application that changes the session timeout %% @end %%-------------------------------------------------------------------- change_timeout(Config) -> %% Set {{Index, Type, _M, _Org}, NewValue} = ct:get_config({dict, change_timeout}), [] = os:cmd(co_test_lib:set_cmd(Config, Index, NewValue, Type, segment, 4000)), wait({set, Index, NewValue}, 5000), %% Get Result = os:cmd(co_test_lib:get_cmd(Config, Index, Type, segment, 4000)), {Index, NewValue} = co_test_lib:parse_get_result(Result). %%-------------------------------------------------------------------- %% @spec break(Config) -> ok %% @doc %% Dummy test case to have a test environment running. %% Stores Config in ets table. %% @end %%-------------------------------------------------------------------- break(Config) -> ets:new(config, [set, public, named_table]), ets:insert(config, Config), test_server:break("Break for test development\n" ++ "Get Config by ets:tab2list(config)"), ok. %%-------------------------------------------------------------------- %% Help functions %%-------------------------------------------------------------------- serial() -> co_test_lib:serial(). app_dict() -> co_test_lib:app_dict(). %%-------------------------------------------------------------------- @spec set(Config , { Entry , _ } , BlockOrSegment ) - > ok %% @doc Sets a value using BlockOrSegment between cocli and . %% Transfer mode is defined by application based on index. Gets the old value using cocli and compares it with the value retrieved %% from the apps dictionary. %% Sets a new value and compares it. %% Restores the old calue. %% @end %%-------------------------------------------------------------------- set(Config, {{Index, Type, _M, _Org}, NewValue}, BlockOrSegment) -> %% Get old value {Index, _Type, _Transfer, OldValue} = lists:keyfind(Index, 1, co_test_app:dict(serial())), %% Change to new [] = os:cmd(co_test_lib:set_cmd(Config, Index, NewValue, Type, BlockOrSegment)), {Index, _Type, _Transfer, NewValue} = lists:keyfind(Index, 1, co_test_app:dict(serial())), wait({set, Index, NewValue}, 5000), %% Restore old [] = os:cmd(co_test_lib:set_cmd(Config, Index, OldValue, Type, BlockOrSegment)), {Index, _Type, _Transfer, OldValue} = lists:keyfind(Index, 1, co_test_app:dict(serial())), wait({set, Index, OldValue}, 5000), ok; set(Config, {Index, NewValue, Type}, BlockOrSegment) -> %% co_node internal dict [] = os:cmd(co_test_lib:set_cmd(Config, Index, NewValue, Type, BlockOrSegment)). %%-------------------------------------------------------------------- @spec get(Config , { Entry , _ } , BlockOrSegment ) - > ok %% @doc Gets a value using BlockOrSegment between cocli and . %% Transfer mode is defined by application based on index. Gets the value using cocli and compares it with the value retrieved %% from the apps dictionary. %% @end %%-------------------------------------------------------------------- get(Config, {{Index, Type, _M, Org}, _NewValue}, BlockOrSegment) -> Result = os:cmd(co_test_lib:get_cmd(Config, Index, Type, BlockOrSegment)), ct:pal("Result = ~p", [Result]), {Index, Org} = co_test_lib:parse_get_result(Result), Get value from cocli and compare with dict { Index , _ Type , _ Transfer , Value } = lists : keyfind(Index , 1 , co_test_app : dict(serial ( ) ) ) , ok; get(Config, {Index, NewValue, Type}, BlockOrSegment) -> %% co_node internal dict Result = os:cmd(co_test_lib:get_cmd(Config, Index, Type, BlockOrSegment)), ct:pal("Result = ~p", [Result]), {Index, NewValue} = co_test_lib:parse_get_result(Result). wait(For, Time) -> receive For -> ct:pal("Received ~p as expected",[For]), ok; Other -> ct:pal("Received other = ~p", [Other]), ct:fail("Received other") after Time -> ct:pal("Nothing received, timeout",[]) end. stream_file(Config, TransferMode, Size) -> PrivDir = ?config(priv_dir, Config), RFile = filename:join(PrivDir, ct:get_config(read_file)), WFile = filename:join(PrivDir, ct:get_config(write_file)), co_test_lib:generate_file(RFile, Size), Md5 = co_test_lib:md5_file(RFile), {ok, _Pid} = co_test_stream_app:start(serial(), {ct:get_config(file_stream_index), RFile, WFile}), ct:pal("Started stream app"), timer:sleep(1000), [] = os:cmd(co_test_lib:file_cmd(Config, ct:get_config(file_stream_index), "download", TransferMode)), %% ct:pal("Started download of file from stream app, result = ~p",[Res1]), receive eof -> ct:pal("Application upload finished",[]), timer:sleep(1000), ok after 5000 -> ct:fail("Application stuck") end, [] = os:cmd(co_test_lib:file_cmd(Config, ct:get_config(file_stream_index), "upload", TransferMode)), %% ct:pal("Started upload of file to stream app, result = ~p",[Res2]), receive eof -> ct:pal("Application download finished",[]), timer:sleep(1000), ok after 5000 -> ct:fail("Application stuck") end, %% Check that file is unchanged Md5 = co_test_lib:md5_file(WFile), ok.
null
https://raw.githubusercontent.com/tonyrog/canopen/b76c0c3503e3087cc7511fe5795e6053702d449e/test/co_sdo_srv_SUITE.erl
erlang
coding: latin-1 ---- BEGIN COPYRIGHT -------------------------------------------------------- This software is licensed as described in the file COPYRIGHT, which you should have received as part of this distribution. The terms are also available at . You may opt to use, copy, modify, merge, publish, distribute and/or sell furnished to do so, under the terms of the COPYRIGHT file. KIND, either express or implied. ---- END COPYRIGHT ---------------------------------------------------------- ------------------------------------------------------------------- @doc @end ------------------------------------------------------------------- Note: This directive should only be used in test suites. -------------------------------------------------------------------- COMMON TEST CALLBACK FUNCTIONS -------------------------------------------------------------------- -------------------------------------------------------------------- @doc Returns list of tuples to set default properties for the suite. Function: suite() -> Info Info = [tuple()] List of key/value pairs. Note: The suite/0 function is only meant to be used to return default data values, not perform any other operations. @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc Returns the list of groups and test cases that are to be executed. GroupName = atom() Name of a test case group. Name of a test case. Reason = term() The reason for skipping all groups and test cases. @end -------------------------------------------------------------------- break]. -------------------------------------------------------------------- @doc Initialization before the whole suite Config0 = Config1 = [tuple()] A list of key/value pairs, holding the test case configuration. Reason = term() The reason for skipping the suite. Note: This function is free to add any key/value pairs to the Config variable, but should NOT alter/remove any existing entries. @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc Cleanup after the whole suite Config - [tuple()] A list of key/value pairs, holding the test case configuration. @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc Initialization before each test case TestCase - atom() Name of the test case that is about to be run. Config0 = Config1 = [tuple()] A list of key/value pairs, holding the test case configuration. Reason = term() The reason for skipping the test case. Note: This function is free to add any key/value pairs to the Config variable, but should NOT alter/remove any existing entries. @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc Cleanup after each test case TestCase - atom() Name of the test case that is finished. Config0 = Config1 = [tuple()] A list of key/value pairs, holding the test case configuration. @end -------------------------------------------------------------------- Wait a little for session to terminate Wait a little for session to terminate -------------------------------------------------------------------- TEST CASES -------------------------------------------------------------------- -------------------------------------------------------------------- @doc @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc @end -------------------------------------------------------------------- -------------------------------------------------------------------- @spec set_streamed_segment(Config) -> ok @doc @end -------------------------------------------------------------------- -------------------------------------------------------------------- @spec get_streamed_segment(Config) -> ok @doc @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc @end -------------------------------------------------------------------- -------------------------------------------------------------------- @spec stream_file_block(Config) -> ok @doc @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc @end -------------------------------------------------------------------- -------------------------------------------------------------------- @spec notify(Config) -> ok @doc co_test_app subscribes. @end -------------------------------------------------------------------- -------------------------------------------------------------------- @spec mpdo(Config) -> ok @doc Sends an mpdo that is broadcasted to all subscribers. @end -------------------------------------------------------------------- -------------------------------------------------------------------- @spec timeout(Config) -> ok @doc Negative test of what happens if the receiving causes a timeout. @end -------------------------------------------------------------------- Set Get -------------------------------------------------------------------- @spec change_timeout(Config) -> ok @doc A test of having an application that changes the session timeout @end -------------------------------------------------------------------- Set Get -------------------------------------------------------------------- @spec break(Config) -> ok @doc Dummy test case to have a test environment running. Stores Config in ets table. @end -------------------------------------------------------------------- -------------------------------------------------------------------- Help functions -------------------------------------------------------------------- -------------------------------------------------------------------- @doc Transfer mode is defined by application based on index. from the apps dictionary. Sets a new value and compares it. Restores the old calue. @end -------------------------------------------------------------------- Get old value Change to new Restore old co_node internal dict -------------------------------------------------------------------- @doc Transfer mode is defined by application based on index. from the apps dictionary. @end -------------------------------------------------------------------- co_node internal dict ct:pal("Started download of file from stream app, result = ~p",[Res1]), ct:pal("Started upload of file to stream app, result = ~p",[Res2]), Check that file is unchanged
Copyright ( C ) 2007 - 2012 , Rogvall Invest AB , < > copies of the Software , and permit persons to whom the Software is This software is distributed on an " AS IS " basis , WITHOUT WARRANTY OF ANY @author Lönne < > ( C ) 2011 , Marina Westman Lönne Created : 29 Nov 2011 by Marina Westman Lönne < > -module(co_sdo_srv_SUITE). -compile(export_all). -include_lib("common_test/include/ct.hrl"). @spec suite ( ) - > Info suite() -> [{timetrap,{minutes,10}}, {require, serial}, {require, dict}]. = [ { group , GroupName } | TestCase ] TestCase = atom ( ) @spec all ( ) - > GroupsAndTestCases | { skip , Reason } all() -> [set_dict_segment, get_dict_segment, set_dict_block, get_dict_block, set_atomic_segment, get_atomic_segment, set_atomic_block, get_atomic_block, set_atomic_exp, get_atomic_exp, set_atomic_m_segment, get_atomic_m_segment, set_atomic_m_block, get_atomic_m_block, set_streamed_segment, get_streamed_segment, set_streamed_block, get_streamed_block, set_streamed_exp, get_streamed_exp, set_streamed_m_segment, get_streamed_m_segment, set_streamed_m_block, get_streamed_m_block, set_atomic_int, get_atomic_int, set_atomic_si, get_atomic_si, stream_file_segment, stream_file_block, stream_0file_segment, stream_0file_block, notify, mpdo, timeout, change_timeout]. @spec init_per_suite(Config0 ) - > Config1 | { skip , Reason } | { skip_and_save , Reason , Config1 } init_per_suite(Config) -> co_test_lib:start_system(), co_test_lib:start_node(Config), Config. ) - > _ end_per_suite(Config) -> co_test_lib:stop_node(Config), co_test_lib:stop_system(), ok. @spec init_per_testcase(TestCase , Config0 ) - > Config1 | { skip , Reason } | { skip_and_save , Reason , Config1 } init_per_testcase(_TestCase = timeout, Config) -> ct:pal("Testcase: ~p", [_TestCase]), {ok, Pid} = co_test_app:start(serial(), app_dict()), ok = co_test_app:debug(Pid, true), Change the timeout for the {sdo_timeout, OldTOut} = co_api:get_option(serial(), sdo_timeout), ok = co_api:set_option(serial(), sdo_timeout, 500), [{timeout, OldTOut} | Config]; init_per_testcase(_TestCase, Config) -> ct:pal("Testcase: ~p", [_TestCase]), {ok, Pid} = co_test_app:start(serial(), app_dict()), ok = co_test_app:debug(Pid, true), Config. , Config0 ) - > void ( ) | { save_config , Config1 } | { fail , Reason } end_per_testcase(Case, Config) when Case == stream_file_segment; Case == stream_file_block; Case == stream_0file_segment; Case == stream_0file_block -> co_test_stream_app:stop(), PrivDir = ?config(priv_dir, Config), RFile = filename:join(PrivDir, ct:get_config(read_file)), WFile = filename:join(PrivDir, ct:get_config(write_file)), os:cmd("rm " ++ RFile), os:cmd("rm " ++ WFile), ok; end_per_testcase(timeout, Config) -> timer:sleep(1000), co_test_app:stop(serial()), Restore the timeout for the OldTOut = ?config(timeout, Config), co_api:set_option(serial(), sdo_timeout, OldTOut), ok; end_per_testcase(_TestCase, _Config) -> timer:sleep(1000), co_test_app:stop(serial()), ok. @spec set_dict_segment(Config ) - > ok Sets a value in the internal dict using segment between cocli and . set_dict_segment(Config) -> set(Config, ct:get_config(dict_index), segment). ) - > ok Gets a value from the internal dict using segment between cocli and . get_dict_segment(Config) -> get(Config, ct:get_config(dict_index), segment). @spec set_dict_block(Config ) - > ok Sets a value in the internal dict using block between cocli and set_dict_block(Config) -> set(Config, ct:get_config(dict_index), block). ) - > ok Gets a value from the co_node internal using block between cocli and . get_dict_block(Config) -> get(Config, ct:get_config(dict_index), block). set_atomic_segment(Config ) - > ok Sets a value using segment between cocli and and atomic between and application . set_atomic_segment(Config) -> set(Config, ct:get_config({dict, atomic}), segment). ) - > ok Gets a value using segment between cocli and and atomic between and application . get_atomic_segment(Config) -> get(Config, ct:get_config({dict, atomic}), segment). @spec set_atomic_block(Config ) - > ok Sets a value using block between cocli and and atomic between and application . set_atomic_block(Config) -> set(Config, ct:get_config({dict, atomic}), block). get_atomic_block(Config ) - > ok Gets a value using block between cocli and and atomic between and application . get_atomic_block(Config) -> get(Config, ct:get_config({dict, atomic}), block). @spec set_atomic_exp(Config ) - > ok Sets a short value using segment between cocli and and atomic between and application . set_atomic_exp(Config) -> set(Config, ct:get_config({dict, atomic_exp}), segment). get_atomic_exp(Config ) - > ok Gets a short value using segment between cocli and and atomic atomic between and application . get_atomic_exp(Config) -> get(Config, ct:get_config({dict, atomic_exp}), segment). Sets a value using segment between cocli and and streamed between and application . set_streamed_segment(Config) -> set(Config, ct:get_config({dict, streamed}), segment). Gets a value using segment between cocli and and streamed atomic between and application . get_streamed_segment(Config) -> get(Config, ct:get_config({dict, streamed}), segment). set_streamed_block(Config ) - > ok Sets a value using block between cocli and and streamed atomic between and application . set_streamed_block(Config) -> set(Config, ct:get_config({dict, streamed}), block). get_streamed_block(Config ) - > ok Gets a value using block between cocli and and streamed atomic between and application . get_streamed_block(Config) -> get(Config, ct:get_config({dict, streamed}), block). ) - > ok Sets a short value using segment between cocli and and streamed atomic between and application . set_streamed_exp(Config) -> set(Config, ct:get_config({dict, streamed_exp}), segment). ) - > ok Gets a short value using segment between cocli and and streamed atomic between and application . get_streamed_exp(Config) -> get(Config, ct:get_config({dict, streamed_exp}), segment). ) - > ok Sets a value using segment between cocli and and { atomic , Module } between and application . set_atomic_m_segment(Config) -> set(Config, ct:get_config({dict, atomic_m}), segment). ) - > ok Gets a value using segment between cocli and and { atomic , Module } between and application . get_atomic_m_segment(Config) -> get(Config, ct:get_config({dict, atomic_m}), segment). ) - > ok Sets a value using segment between cocli and and { atomic , Module } between and application . set_atomic_m_block(Config) -> set(Config, ct:get_config({dict, atomic_m}), block). ) - > ok Gets a value using segment between cocli and and { atomic , Module } atomic_m between and application . get_atomic_m_block(Config) -> get(Config, ct:get_config({dict, atomic_m}), block). ) - > ok Sets a value using segment between cocli and and { streamed , Module } atomic_m between and application . set_streamed_m_segment(Config) -> set(Config, ct:get_config({dict, streamed_m}), segment). ) - > ok Gets a value using segment between cocli and and { streamed , Module } atomic_m between and application . get_streamed_m_segment(Config) -> get(Config, ct:get_config({dict, streamed_m}), segment). ) - > ok Sets a value using block between cocli and and { streamed , Module } atomic_m between and application . set_streamed_m_block(Config) -> set(Config, ct:get_config({dict, streamed_m}), block). ) - > ok Gets a value using block between cocli and and { streamed , Module } between and application . get_streamed_m_block(Config) -> get(Config, ct:get_config({dict, streamed_m}), block). ) - > ok Sets an integer value using segment between cocli and and atomic between and application . set_atomic_int(Config) -> set(Config, ct:get_config({dict, atomic_int}), segment). ) - > ok Gets an integer value using segment between cocli and and atomic between and application . get_atomic_int(Config) -> get(Config, ct:get_config({dict, atomic_int}), segment). ) - > ok Sets an integer value using segment between cocli and and atomic between and application . set_atomic_si(Config) -> set(Config, ct:get_config({dict, atomic_si}), segment). ) - > ok Gets an integer value using segment between cocli and and atomic between and application . get_atomic_si(Config) -> get(Config, ct:get_config({dict, atomic_si}), segment). @spec stream_file_segment(Config ) - > ok Tests streaming of file cocli - > co_test_stream_app - > cocli stream_file_segment(Config) -> stream_file(Config, segment, 50). Tests streaming of file cocli - > co_test_stream_app - > cocli stream_file_block(Config) -> stream_file(Config, block, 50). @spec stream_0file_segment(Config ) - > ok Tests streaming of 0 size file cocli - > co_test_stream_app - > cocli stream_0file_segment(Config) -> stream_file(Config, segment, 0). stream_0file_block(Config ) - > ok Tests streaming of 0 size file cocli - > co_test_stream_app - > cocli stream_0file_block(Config) -> stream_file(Config, block, 0). Sets a value for an index in the dictionary on which notify(Config) -> {{Index = {Ix, _Si}, Type, _M, _Org}, NewValue} = ct:get_config({dict, notify}), [] = os:cmd(co_test_lib:set_cmd(Config, Index, NewValue, Type, segment)), wait({object_event, Ix}, 5000), ok. mpdo(Config) -> {{Index = {Ix, _Si}, _T, _M, _Org}, NewValue} = ct:get_config({dict, mpdo}), "ok\n" = os:cmd(co_test_lib:notify_cmd(Config, Index, NewValue, segment)), wait({notify, Ix}, 5000), ok. timeout(Config) -> {{Index, Type, _M, _Org}, NewValue} = ct:get_config({dict, timeout}), "cocli: error: set failed: timed out\r\n" = os:cmd(co_test_lib:set_cmd(Config, Index, NewValue, Type, segment)), wait({set, Index, NewValue}, 5000), "cocli: error: failed to retrieve value for '0x7334' timed out\r\n" = os:cmd(co_test_lib:get_cmd(Config, Index, Type, segment)). change_timeout(Config) -> {{Index, Type, _M, _Org}, NewValue} = ct:get_config({dict, change_timeout}), [] = os:cmd(co_test_lib:set_cmd(Config, Index, NewValue, Type, segment, 4000)), wait({set, Index, NewValue}, 5000), Result = os:cmd(co_test_lib:get_cmd(Config, Index, Type, segment, 4000)), {Index, NewValue} = co_test_lib:parse_get_result(Result). break(Config) -> ets:new(config, [set, public, named_table]), ets:insert(config, Config), test_server:break("Break for test development\n" ++ "Get Config by ets:tab2list(config)"), ok. serial() -> co_test_lib:serial(). app_dict() -> co_test_lib:app_dict(). @spec set(Config , { Entry , _ } , BlockOrSegment ) - > ok Sets a value using BlockOrSegment between cocli and . Gets the old value using cocli and compares it with the value retrieved set(Config, {{Index, Type, _M, _Org}, NewValue}, BlockOrSegment) -> {Index, _Type, _Transfer, OldValue} = lists:keyfind(Index, 1, co_test_app:dict(serial())), [] = os:cmd(co_test_lib:set_cmd(Config, Index, NewValue, Type, BlockOrSegment)), {Index, _Type, _Transfer, NewValue} = lists:keyfind(Index, 1, co_test_app:dict(serial())), wait({set, Index, NewValue}, 5000), [] = os:cmd(co_test_lib:set_cmd(Config, Index, OldValue, Type, BlockOrSegment)), {Index, _Type, _Transfer, OldValue} = lists:keyfind(Index, 1, co_test_app:dict(serial())), wait({set, Index, OldValue}, 5000), ok; set(Config, {Index, NewValue, Type}, BlockOrSegment) -> [] = os:cmd(co_test_lib:set_cmd(Config, Index, NewValue, Type, BlockOrSegment)). @spec get(Config , { Entry , _ } , BlockOrSegment ) - > ok Gets a value using BlockOrSegment between cocli and . Gets the value using cocli and compares it with the value retrieved get(Config, {{Index, Type, _M, Org}, _NewValue}, BlockOrSegment) -> Result = os:cmd(co_test_lib:get_cmd(Config, Index, Type, BlockOrSegment)), ct:pal("Result = ~p", [Result]), {Index, Org} = co_test_lib:parse_get_result(Result), Get value from cocli and compare with dict { Index , _ Type , _ Transfer , Value } = lists : keyfind(Index , 1 , co_test_app : dict(serial ( ) ) ) , ok; get(Config, {Index, NewValue, Type}, BlockOrSegment) -> Result = os:cmd(co_test_lib:get_cmd(Config, Index, Type, BlockOrSegment)), ct:pal("Result = ~p", [Result]), {Index, NewValue} = co_test_lib:parse_get_result(Result). wait(For, Time) -> receive For -> ct:pal("Received ~p as expected",[For]), ok; Other -> ct:pal("Received other = ~p", [Other]), ct:fail("Received other") after Time -> ct:pal("Nothing received, timeout",[]) end. stream_file(Config, TransferMode, Size) -> PrivDir = ?config(priv_dir, Config), RFile = filename:join(PrivDir, ct:get_config(read_file)), WFile = filename:join(PrivDir, ct:get_config(write_file)), co_test_lib:generate_file(RFile, Size), Md5 = co_test_lib:md5_file(RFile), {ok, _Pid} = co_test_stream_app:start(serial(), {ct:get_config(file_stream_index), RFile, WFile}), ct:pal("Started stream app"), timer:sleep(1000), [] = os:cmd(co_test_lib:file_cmd(Config, ct:get_config(file_stream_index), "download", TransferMode)), receive eof -> ct:pal("Application upload finished",[]), timer:sleep(1000), ok after 5000 -> ct:fail("Application stuck") end, [] = os:cmd(co_test_lib:file_cmd(Config, ct:get_config(file_stream_index), "upload", TransferMode)), receive eof -> ct:pal("Application download finished",[]), timer:sleep(1000), ok after 5000 -> ct:fail("Application stuck") end, Md5 = co_test_lib:md5_file(WFile), ok.
16ed305fce805219d529fec996d862af8e03d2a9e1f50f68a92a06adb4aeb6e8
andersfugmann/borderline
borderline.ml
open Core (** Main file. *) open Borderline_lib open Common module F = Frontend let _ = Sys.catch_break true; try let files = List.tl_exn (Array.to_list (Sys.get_argv ())) in Printf.eprintf "Parsing file%s: %s\n%!" (match List.length files > 1 with true -> "s" | false -> "") (String.concat ~sep:", " files); let (zones, procs) = Parse.process_files files in let zones = List.map ~f:(fun ((id, _pos), stms) -> id, stms) zones in let input_opers, output_opers, forward_opers = Zone.emit_filter zones in let post_routing = Zone.emit_nat zones in let filter_chains = List.map ~f:Rule.process procs in let filter_ops = List.map ~f:(fun chn -> ([], [], Ir.Jump(chn.Ir.id)) ) filter_chains in Chain.add { Ir.id = Ir.Chain_id.Builtin Ir.Chain_type.Input ; rules = input_opers @ filter_ops; comment = "Builtin" }; Chain.add { Ir.id = Ir.Chain_id.Builtin Ir.Chain_type.Output ; rules = output_opers @ filter_ops; comment = "Builtin" }; Chain.add { Ir.id = Ir.Chain_id.Builtin Ir.Chain_type.Forward ; rules = forward_opers @ filter_ops; comment = "Builtin" }; Chain.optimize Optimize.optimize; let lines = Chain.emit Nftables.emit_filter_chains @ (Nftables.emit_nat_chain post_routing) in List.iter ~f:(fun l -> print_endline l) lines; Printf.printf "\n#Lines: %d\n" (List.length lines) with | ParseError err as excpt -> Out_channel.flush stdout; prerr_endline (error2string err); raise excpt
null
https://raw.githubusercontent.com/andersfugmann/borderline/ca51ad98cff0c37a3cd6a7717535319233e6f062/bin/borderline.ml
ocaml
* Main file.
open Core open Borderline_lib open Common module F = Frontend let _ = Sys.catch_break true; try let files = List.tl_exn (Array.to_list (Sys.get_argv ())) in Printf.eprintf "Parsing file%s: %s\n%!" (match List.length files > 1 with true -> "s" | false -> "") (String.concat ~sep:", " files); let (zones, procs) = Parse.process_files files in let zones = List.map ~f:(fun ((id, _pos), stms) -> id, stms) zones in let input_opers, output_opers, forward_opers = Zone.emit_filter zones in let post_routing = Zone.emit_nat zones in let filter_chains = List.map ~f:Rule.process procs in let filter_ops = List.map ~f:(fun chn -> ([], [], Ir.Jump(chn.Ir.id)) ) filter_chains in Chain.add { Ir.id = Ir.Chain_id.Builtin Ir.Chain_type.Input ; rules = input_opers @ filter_ops; comment = "Builtin" }; Chain.add { Ir.id = Ir.Chain_id.Builtin Ir.Chain_type.Output ; rules = output_opers @ filter_ops; comment = "Builtin" }; Chain.add { Ir.id = Ir.Chain_id.Builtin Ir.Chain_type.Forward ; rules = forward_opers @ filter_ops; comment = "Builtin" }; Chain.optimize Optimize.optimize; let lines = Chain.emit Nftables.emit_filter_chains @ (Nftables.emit_nat_chain post_routing) in List.iter ~f:(fun l -> print_endline l) lines; Printf.printf "\n#Lines: %d\n" (List.length lines) with | ParseError err as excpt -> Out_channel.flush stdout; prerr_endline (error2string err); raise excpt
5b4cfb53a0a646f6476e4254b694aa2a4e60f27f355b22ac3891eb41cfd78a39
satos---jp/mincaml_self_hosting
io.ml
let a = read_int () in let b = read_int () in print_int (a+b); print_char 10; let p = read_int () in let q = read_int () in print_int (p+q); print_char 10; let c = read_float () in let d = read_float () in print_int (int_of_float (c *. d)); print_char 10; let r = read_float () in let s = read_float () in print_int (int_of_float (r +. s)); print_char 10; print_int (int_of_float ((float_of_int p) +. r)); print_char 10
null
https://raw.githubusercontent.com/satos---jp/mincaml_self_hosting/5fdf8b5083437d7607a924142eea52d9b1de0439/test/io.ml
ocaml
let a = read_int () in let b = read_int () in print_int (a+b); print_char 10; let p = read_int () in let q = read_int () in print_int (p+q); print_char 10; let c = read_float () in let d = read_float () in print_int (int_of_float (c *. d)); print_char 10; let r = read_float () in let s = read_float () in print_int (int_of_float (r +. s)); print_char 10; print_int (int_of_float ((float_of_int p) +. r)); print_char 10
a21a1922356f16848a5f8ec9235ed0dbaa6c70f16d98048d12cf10be710667ff
ocaml-multicore/effects-examples
delimcc_paper_example.ml
(* Example in the delimcc paper: * -shift-journal.pdf *) open Delimcc.M;; (* A finite map: a search tree *) type ('k, 'v) tree = | Empty | Node of ('k, 'v) tree * 'k * 'v * ('k, 'v) tree ;; exception NotFound ;; (* Update the value associated with the key k by applying the update function f. Return the new tree. If the key is not found, throw an exception. *) let rec update1 : 'k -> ('v->'v) -> ('k,'v) tree -> ('k,'v) tree = fun k f -> let rec loop = function | Empty -> raise NotFound | Node (l,k1,v1,r) -> begin match compare k k1 with | 0 -> Node(l,k1,f v1,r) | n when n < 0 -> Node(loop l,k1,v1,r) | _ -> Node(l,k1,v1,loop r) end in loop ;; (* Add to the tree the association of the key k to the value v, overriding any existing association with the key k, if any. *) let rec insert k v = function | Empty -> Node(Empty,k,v,Empty) | Node(l,k1,v1,r) -> begin match compare k k1 with | 0 -> Node(l,k1,v,r) | n when n < 0 -> Node(insert k v l, k1,v1,r) | _ -> Node(l,k1,v1,insert k v r) end ;; (* A re-balancing function; dummy for now *) let rebalance : ('k,'v) tree -> ('k,'v) tree = fun t -> print_endline "Rebalancing"; t ;; (* Examples of using update1 *) let tree1 = let n1 = Node(Empty,1,101,Empty) in let n9 = Node(Empty,9,109,Empty) in let n5 = Node(n1,5,105,Empty) in let n7 = Node(n5,7,107,n9) in n7;; let Node (Node (Node (Empty, 1, 102, Empty), 5, 105, Empty), 7, 107, Node (Empty, 9, 109, Empty)) = try update1 1 succ tree1 with NotFound -> insert 1 100 tree1 ;; let Node (Node (Node (Node (Empty, 0, 100, Empty), 1, 101, Empty), 5, 105, Empty), 7, 107, Node (Empty, 9, 109, Empty)) = try update1 0 succ tree1 with NotFound -> insert 0 100 tree1 ;; The same as update1 , but using let rec update2 : ('k,'v) tree option prompt -> 'k -> ('v->'v) -> ('k,'v) tree -> ('k,'v) tree = fun pnf k f -> let rec loop = function | Empty -> abort pnf None | Node (l,k1,v1,r) -> begin match compare k k1 with | 0 -> Node(l,k1,f v1,r) | n when n < 0 -> Node(loop l,k1,v1,r) | _ -> Node(l,k1,v1,loop r) end in loop ;; let Node (Node (Node (Empty, 1, 102, Empty), 5, 105, Empty), 7, 107, Node (Empty, 9, 109, Empty)) = let pnf = new_prompt () in match push_prompt pnf (fun () -> Some (update2 pnf 1 succ tree1)) with | Some tree -> tree | None -> insert 1 100 tree1 ;; let Node (Node (Node (Node (Empty, 0, 100, Empty), 1, 101, Empty), 5, 105, Empty), 7, 107, Node (Empty, 9, 109, Empty)) = let pnf = new_prompt () in match push_prompt pnf (fun () -> Some (update2 pnf 0 succ tree1)) with | Some tree -> tree | None -> insert 0 100 tree1 ;; Resumable exceptions (* upd_handle is very problematic! *) let upd_handle = fun k -> raise NotFound;; let rec update3 : 'k -> ('v->'v) -> ('k,'v) tree -> ('k,'v) tree = fun k f -> let rec loop = function | Empty -> Node(Empty,k,upd_handle k,Empty) | Node (l,k1,v1,r) -> begin match compare k k1 with | 0 -> Node(l,k1,f v1,r) | n when n < 0 -> Node(loop l,k1,v1,r) | _ -> Node(l,k1,v1,loop r) end in loop ;; let Node (Node (Node (Empty, 1, 102, Empty), 5, 105, Empty), 7, 107, Node (Empty, 9, 109, Empty)) = update3 1 succ tree1 ;; Resumable exceptions type ('k,'v) res = Done of ('k,'v) tree | ReqNF of 'k * ('v,('k,'v) res) subcont ;; let rec update4 : ('k,'v) res prompt -> 'k -> ('v->'v) -> ('k,'v) tree -> ('k,'v) tree = fun pnf k f -> let rec loop = function | Empty -> Node(Empty,k,take_subcont pnf (fun c -> ReqNF (k,c)),Empty) | Node (l,k1,v1,r) -> begin match compare k k1 with | 0 -> Node(l,k1,f v1,r) | n when n < 0 -> Node(loop l,k1,v1,r) | _ -> Node(l,k1,v1,loop r) end in loop ;; let Node (Node (Node (Empty, 1, 102, Empty), 5, 105, Empty), 7, 107, Node (Empty, 9, 109, Empty)) = let pnf = new_prompt () in match push_prompt pnf (fun () -> Done (update4 pnf 1 succ tree1)) with | Done tree -> tree | ReqNF (k,c) -> rebalance (match push_subcont c 100 with Done x -> x) ;; let Node (Node (Node (Node (Empty, 0, 100, Empty), 1, 101, Empty), 5, 105, Empty), 7, 107, Node (Empty, 9, 109, Empty)) = let pnf = new_prompt () in match push_prompt pnf (fun () -> Done (update4 pnf 0 succ tree1)) with | Done tree -> tree | ReqNF (k,c) -> rebalance (match push_subcont c 100 with Done x -> x) ;; (* Rebalancing is printed *) (* A custom value update function *) exception TooBig;; let upd_fun n = if n > 5 then raise TooBig else succ n;; (* Several exceptions *) let Empty = try try update1 7 upd_fun tree1 with NotFound -> insert 7 100 tree1 with TooBig -> Empty ;; let Empty = try let pnf = new_prompt () in match push_prompt pnf (fun () -> Done (update4 pnf 7 upd_fun tree1)) with | Done tree -> tree | ReqNF (k,c) -> rebalance (match push_subcont c 100 with Done x -> x) with TooBig -> Empty ;;
null
https://raw.githubusercontent.com/ocaml-multicore/effects-examples/4f07e1774b726eec0f6769da0a16b402582d37b5/multishot/delimcc_paper_example.ml
ocaml
Example in the delimcc paper: * -shift-journal.pdf A finite map: a search tree Update the value associated with the key k by applying the update function f. Return the new tree. If the key is not found, throw an exception. Add to the tree the association of the key k to the value v, overriding any existing association with the key k, if any. A re-balancing function; dummy for now Examples of using update1 upd_handle is very problematic! Rebalancing is printed A custom value update function Several exceptions
open Delimcc.M;; type ('k, 'v) tree = | Empty | Node of ('k, 'v) tree * 'k * 'v * ('k, 'v) tree ;; exception NotFound ;; let rec update1 : 'k -> ('v->'v) -> ('k,'v) tree -> ('k,'v) tree = fun k f -> let rec loop = function | Empty -> raise NotFound | Node (l,k1,v1,r) -> begin match compare k k1 with | 0 -> Node(l,k1,f v1,r) | n when n < 0 -> Node(loop l,k1,v1,r) | _ -> Node(l,k1,v1,loop r) end in loop ;; let rec insert k v = function | Empty -> Node(Empty,k,v,Empty) | Node(l,k1,v1,r) -> begin match compare k k1 with | 0 -> Node(l,k1,v,r) | n when n < 0 -> Node(insert k v l, k1,v1,r) | _ -> Node(l,k1,v1,insert k v r) end ;; let rebalance : ('k,'v) tree -> ('k,'v) tree = fun t -> print_endline "Rebalancing"; t ;; let tree1 = let n1 = Node(Empty,1,101,Empty) in let n9 = Node(Empty,9,109,Empty) in let n5 = Node(n1,5,105,Empty) in let n7 = Node(n5,7,107,n9) in n7;; let Node (Node (Node (Empty, 1, 102, Empty), 5, 105, Empty), 7, 107, Node (Empty, 9, 109, Empty)) = try update1 1 succ tree1 with NotFound -> insert 1 100 tree1 ;; let Node (Node (Node (Node (Empty, 0, 100, Empty), 1, 101, Empty), 5, 105, Empty), 7, 107, Node (Empty, 9, 109, Empty)) = try update1 0 succ tree1 with NotFound -> insert 0 100 tree1 ;; The same as update1 , but using let rec update2 : ('k,'v) tree option prompt -> 'k -> ('v->'v) -> ('k,'v) tree -> ('k,'v) tree = fun pnf k f -> let rec loop = function | Empty -> abort pnf None | Node (l,k1,v1,r) -> begin match compare k k1 with | 0 -> Node(l,k1,f v1,r) | n when n < 0 -> Node(loop l,k1,v1,r) | _ -> Node(l,k1,v1,loop r) end in loop ;; let Node (Node (Node (Empty, 1, 102, Empty), 5, 105, Empty), 7, 107, Node (Empty, 9, 109, Empty)) = let pnf = new_prompt () in match push_prompt pnf (fun () -> Some (update2 pnf 1 succ tree1)) with | Some tree -> tree | None -> insert 1 100 tree1 ;; let Node (Node (Node (Node (Empty, 0, 100, Empty), 1, 101, Empty), 5, 105, Empty), 7, 107, Node (Empty, 9, 109, Empty)) = let pnf = new_prompt () in match push_prompt pnf (fun () -> Some (update2 pnf 0 succ tree1)) with | Some tree -> tree | None -> insert 0 100 tree1 ;; Resumable exceptions let upd_handle = fun k -> raise NotFound;; let rec update3 : 'k -> ('v->'v) -> ('k,'v) tree -> ('k,'v) tree = fun k f -> let rec loop = function | Empty -> Node(Empty,k,upd_handle k,Empty) | Node (l,k1,v1,r) -> begin match compare k k1 with | 0 -> Node(l,k1,f v1,r) | n when n < 0 -> Node(loop l,k1,v1,r) | _ -> Node(l,k1,v1,loop r) end in loop ;; let Node (Node (Node (Empty, 1, 102, Empty), 5, 105, Empty), 7, 107, Node (Empty, 9, 109, Empty)) = update3 1 succ tree1 ;; Resumable exceptions type ('k,'v) res = Done of ('k,'v) tree | ReqNF of 'k * ('v,('k,'v) res) subcont ;; let rec update4 : ('k,'v) res prompt -> 'k -> ('v->'v) -> ('k,'v) tree -> ('k,'v) tree = fun pnf k f -> let rec loop = function | Empty -> Node(Empty,k,take_subcont pnf (fun c -> ReqNF (k,c)),Empty) | Node (l,k1,v1,r) -> begin match compare k k1 with | 0 -> Node(l,k1,f v1,r) | n when n < 0 -> Node(loop l,k1,v1,r) | _ -> Node(l,k1,v1,loop r) end in loop ;; let Node (Node (Node (Empty, 1, 102, Empty), 5, 105, Empty), 7, 107, Node (Empty, 9, 109, Empty)) = let pnf = new_prompt () in match push_prompt pnf (fun () -> Done (update4 pnf 1 succ tree1)) with | Done tree -> tree | ReqNF (k,c) -> rebalance (match push_subcont c 100 with Done x -> x) ;; let Node (Node (Node (Node (Empty, 0, 100, Empty), 1, 101, Empty), 5, 105, Empty), 7, 107, Node (Empty, 9, 109, Empty)) = let pnf = new_prompt () in match push_prompt pnf (fun () -> Done (update4 pnf 0 succ tree1)) with | Done tree -> tree | ReqNF (k,c) -> rebalance (match push_subcont c 100 with Done x -> x) ;; exception TooBig;; let upd_fun n = if n > 5 then raise TooBig else succ n;; let Empty = try try update1 7 upd_fun tree1 with NotFound -> insert 7 100 tree1 with TooBig -> Empty ;; let Empty = try let pnf = new_prompt () in match push_prompt pnf (fun () -> Done (update4 pnf 7 upd_fun tree1)) with | Done tree -> tree | ReqNF (k,c) -> rebalance (match push_subcont c 100 with Done x -> x) with TooBig -> Empty ;;
ff19a03fc69415dd9a551f8ec92d785340ad4c362c3ed6a521fe754a45aef4bf
Quid2/flat
Vector.hs
{-# LANGUAGE NoMonomorphismRestriction, ExtendedDefaultRules#-} module DocTest.Flat.Instances.Vector where import qualified DocTest import Test.Tasty(TestTree,testGroup) import Flat.Instances.Vector import Flat.Instances.Test import Flat.Instances.Base() import qualified Data.Vector as V import qualified Data.Vector.Unboxed as U import qualified Data.Vector.Storable as S tests :: IO TestTree tests = testGroup "Flat.Instances.Vector" <$> sequence [ DocTest.test "src/Flat/Instances/Vector.hs:23" "[ExpectedLine [LineChunk \"(True,40,[3,11,22,33,0])\"]]" (DocTest.asPrint( tst (V.fromList [11::Word8,22,33]) )), DocTest.test "src/Flat/Instances/Vector.hs:28" "[ExpectedLine [LineChunk \"True\"]]" (DocTest.asPrint( let l = [11::Word8,22,33] in all (tst (V.fromList l) ==) [tst (U.fromList l),tst (S.fromList l)] ))]
null
https://raw.githubusercontent.com/Quid2/flat/95e5d7488451e43062ca84d5376b3adcc465f1cd/test/DocTest/Flat/Instances/Vector.hs
haskell
# LANGUAGE NoMonomorphismRestriction, ExtendedDefaultRules#
module DocTest.Flat.Instances.Vector where import qualified DocTest import Test.Tasty(TestTree,testGroup) import Flat.Instances.Vector import Flat.Instances.Test import Flat.Instances.Base() import qualified Data.Vector as V import qualified Data.Vector.Unboxed as U import qualified Data.Vector.Storable as S tests :: IO TestTree tests = testGroup "Flat.Instances.Vector" <$> sequence [ DocTest.test "src/Flat/Instances/Vector.hs:23" "[ExpectedLine [LineChunk \"(True,40,[3,11,22,33,0])\"]]" (DocTest.asPrint( tst (V.fromList [11::Word8,22,33]) )), DocTest.test "src/Flat/Instances/Vector.hs:28" "[ExpectedLine [LineChunk \"True\"]]" (DocTest.asPrint( let l = [11::Word8,22,33] in all (tst (V.fromList l) ==) [tst (U.fromList l),tst (S.fromList l)] ))]
3ea91949c7e7a8adb5c4ad12c8cda2fd497a0ef718f503d12ced20998b58e2a6
dcastro/haskell-flatbuffers
TestImports.hs
module TestImports ( module Hspec , module Hedgehog , HasCallStack , shouldBeLeft , shouldBeRightAnd , shouldBeRightAndExpect , evalRight , evalJust , evalRightJust , liftA4 , PrettyJson(..) , shouldBeJson , showBuffer , traceBufferM ) where import Control.Monad ( (>=>) ) import qualified Data.Aeson as J import Data.Aeson.Encode.Pretty ( encodePretty ) import qualified Data.ByteString.Lazy as BSL import qualified Data.ByteString.Lazy.UTF8 as BSLU import qualified Data.List as List import Debug.Trace import GHC.Stack ( HasCallStack ) import HaskellWorks.Hspec.Hedgehog as Hedgehog import Hedgehog import Test.HUnit ( assertFailure ) import Test.Hspec.Core.Hooks as Hspec import Test.Hspec.Core.Spec as Hspec import Test.Hspec.Expectations.Pretty as Hspec import Test.Hspec.Runner as Hspec | Useful when there 's no ` Show`/`Eq ` instances for shouldBeLeft :: HasCallStack => Show e => Eq e => Either e a -> e -> Expectation shouldBeLeft ea expected = case ea of Left e -> e `shouldBe` expected Right _ -> expectationFailure "Expected 'Left', got 'Right'" shouldBeRightAnd :: HasCallStack => Show e => Either e a -> (a -> Bool) -> Expectation shouldBeRightAnd ea pred = case ea of Left e -> expectationFailure $ "Expected 'Right', got 'Left':\n" <> show e Right a -> pred a `shouldBe` True shouldBeRightAndExpect :: HasCallStack => Show e => Either e a -> (a -> Expectation) -> Expectation shouldBeRightAndExpect ea expect = case ea of Left e -> expectationFailure $ "Expected 'Right', got 'Left':\n" <> show e Right a -> expect a evalRight :: HasCallStack => Show e => Either e a -> IO a evalRight ea = case ea of Left e -> expectationFailure' $ "Expected 'Right', got 'Left':\n" <> show e Right a -> pure a evalJust :: HasCallStack => Maybe a -> IO a evalJust mb = case mb of Nothing -> expectationFailure' "Expected 'Just', got 'Nothing'" Just a -> pure a evalRightJust :: HasCallStack => Show e => Either e (Maybe a) -> IO a evalRightJust = evalRight >=> evalJust -- | Like `expectationFailure`, but returns @IO a@ instead of @IO ()@. expectationFailure' :: HasCallStack => String -> IO a expectationFailure' = Test.HUnit.assertFailure | Allows Json documents to be compared ( using e.g. ` shouldBe ` ) and pretty - printed in case the comparison fails . newtype PrettyJson = PrettyJson J.Value deriving Eq instance Show PrettyJson where show (PrettyJson v) = BSLU.toString (encodePretty v) shouldBeJson :: HasCallStack => J.Value -> J.Value -> Expectation shouldBeJson x y = PrettyJson x `shouldBe` PrettyJson y liftA4 :: Applicative m => (a -> b -> c -> d -> r) -> m a -> m b -> m c -> m d -> m r liftA4 fn a b c d = fn <$> a <*> b <*> c <*> d traceBufferM :: Applicative m => BSL.ByteString -> m () traceBufferM = traceM . showBuffer showBuffer :: BSL.ByteString -> String showBuffer bs = List.intercalate "\n" . fmap (List.intercalate ", ") . groupsOf 4 . fmap show $ BSL.unpack bs groupsOf :: Int -> [a] -> [[a]] groupsOf n xs = case take n xs of [] -> [] group -> group : groupsOf n (drop n xs)
null
https://raw.githubusercontent.com/dcastro/haskell-flatbuffers/cea6a75109de109ae906741ee73cbb0f356a8e0d/test/TestImports.hs
haskell
| Like `expectationFailure`, but returns @IO a@ instead of @IO ()@.
module TestImports ( module Hspec , module Hedgehog , HasCallStack , shouldBeLeft , shouldBeRightAnd , shouldBeRightAndExpect , evalRight , evalJust , evalRightJust , liftA4 , PrettyJson(..) , shouldBeJson , showBuffer , traceBufferM ) where import Control.Monad ( (>=>) ) import qualified Data.Aeson as J import Data.Aeson.Encode.Pretty ( encodePretty ) import qualified Data.ByteString.Lazy as BSL import qualified Data.ByteString.Lazy.UTF8 as BSLU import qualified Data.List as List import Debug.Trace import GHC.Stack ( HasCallStack ) import HaskellWorks.Hspec.Hedgehog as Hedgehog import Hedgehog import Test.HUnit ( assertFailure ) import Test.Hspec.Core.Hooks as Hspec import Test.Hspec.Core.Spec as Hspec import Test.Hspec.Expectations.Pretty as Hspec import Test.Hspec.Runner as Hspec | Useful when there 's no ` Show`/`Eq ` instances for shouldBeLeft :: HasCallStack => Show e => Eq e => Either e a -> e -> Expectation shouldBeLeft ea expected = case ea of Left e -> e `shouldBe` expected Right _ -> expectationFailure "Expected 'Left', got 'Right'" shouldBeRightAnd :: HasCallStack => Show e => Either e a -> (a -> Bool) -> Expectation shouldBeRightAnd ea pred = case ea of Left e -> expectationFailure $ "Expected 'Right', got 'Left':\n" <> show e Right a -> pred a `shouldBe` True shouldBeRightAndExpect :: HasCallStack => Show e => Either e a -> (a -> Expectation) -> Expectation shouldBeRightAndExpect ea expect = case ea of Left e -> expectationFailure $ "Expected 'Right', got 'Left':\n" <> show e Right a -> expect a evalRight :: HasCallStack => Show e => Either e a -> IO a evalRight ea = case ea of Left e -> expectationFailure' $ "Expected 'Right', got 'Left':\n" <> show e Right a -> pure a evalJust :: HasCallStack => Maybe a -> IO a evalJust mb = case mb of Nothing -> expectationFailure' "Expected 'Just', got 'Nothing'" Just a -> pure a evalRightJust :: HasCallStack => Show e => Either e (Maybe a) -> IO a evalRightJust = evalRight >=> evalJust expectationFailure' :: HasCallStack => String -> IO a expectationFailure' = Test.HUnit.assertFailure | Allows Json documents to be compared ( using e.g. ` shouldBe ` ) and pretty - printed in case the comparison fails . newtype PrettyJson = PrettyJson J.Value deriving Eq instance Show PrettyJson where show (PrettyJson v) = BSLU.toString (encodePretty v) shouldBeJson :: HasCallStack => J.Value -> J.Value -> Expectation shouldBeJson x y = PrettyJson x `shouldBe` PrettyJson y liftA4 :: Applicative m => (a -> b -> c -> d -> r) -> m a -> m b -> m c -> m d -> m r liftA4 fn a b c d = fn <$> a <*> b <*> c <*> d traceBufferM :: Applicative m => BSL.ByteString -> m () traceBufferM = traceM . showBuffer showBuffer :: BSL.ByteString -> String showBuffer bs = List.intercalate "\n" . fmap (List.intercalate ", ") . groupsOf 4 . fmap show $ BSL.unpack bs groupsOf :: Int -> [a] -> [[a]] groupsOf n xs = case take n xs of [] -> [] group -> group : groupsOf n (drop n xs)
61d3d8959bb3565722da0ad962e9ddaa7c58cb28ecbf8bc6395766caf7a19ef5
zcaudate/hara
resolve_test.clj
(ns hara.module.namespace.resolve-test (:use hara.test) (:require [hara.module.namespace.resolve :refer :all])) ^{:refer hara.module.namespace.resolve/resolve-ns :added "3.0"} (fact "resolves the namespace or else returns nil if it does not exist" (resolve-ns 'clojure.core) => 'clojure.core (resolve-ns 'clojure.core/some) => 'clojure.core (resolve-ns 'clojure.hello) => nil) ^{:refer hara.module.namespace.resolve/ns-vars :added "3.0"} (fact "lists the vars in a particular namespace" (ns-vars 'hara.module.namespace.resolve) => '[ns-vars resolve-ns])
null
https://raw.githubusercontent.com/zcaudate/hara/481316c1f5c2aeba5be6e01ae673dffc46a63ec9/test/hara/module/namespace/resolve_test.clj
clojure
(ns hara.module.namespace.resolve-test (:use hara.test) (:require [hara.module.namespace.resolve :refer :all])) ^{:refer hara.module.namespace.resolve/resolve-ns :added "3.0"} (fact "resolves the namespace or else returns nil if it does not exist" (resolve-ns 'clojure.core) => 'clojure.core (resolve-ns 'clojure.core/some) => 'clojure.core (resolve-ns 'clojure.hello) => nil) ^{:refer hara.module.namespace.resolve/ns-vars :added "3.0"} (fact "lists the vars in a particular namespace" (ns-vars 'hara.module.namespace.resolve) => '[ns-vars resolve-ns])
c72f777c32e83964b36cd027e23c82b4d23ae525ede74d6447b9184932517008
esumii/min-caml
ppm.ml
open Bigarray type pixmap = bytes * int let get (img, width) i j k = Char.code (Bytes.get img (((j * width) + i) * 3 + k)) let set (img, width) i j k v = Bytes.set img (((j * width) + i) * 3 + k) (Char.unsafe_chr v) let setp (img, width) i j r g b = let p = ((j * width) + i) * 3 in Bytes.set img p (Char.unsafe_chr r); Bytes.set img (p + 1) (Char.unsafe_chr g); Bytes.set img (p + 2) (Char.unsafe_chr b) let init ~width ~height = (Bytes.create (height * width * 3), width) let width (s, width) = width let height (s, width) = Bytes.length s / width / 3 let dump file (img, width) = let sz = Bytes.length img in let height = sz / 3 / width in let f = open_out_bin file in output_string f "P6\n# PL Club\n"; Printf.fprintf f "%d %d\n255\n" width height; output_bytes f img; close_out f let load file = let f = open_in_bin file in assert (input_line f = "P6"); let s = input_line f in let i = ref 0 in while s.[!i] >= '0' && s.[!i] <= '9' do incr i done; let width = int_of_string (String.sub s 0 !i) in let height = int_of_string (String.sub s (!i + 1) (String.length s - !i - 1)) in assert (input_line f = "255"); let (s, _) as img = init width height in really_input f s 0 (Bytes.length s); close_in f; img
null
https://raw.githubusercontent.com/esumii/min-caml/8860b6fbc50786a27963aff1f7639b94c244618a/min-rt/ppm.ml
ocaml
open Bigarray type pixmap = bytes * int let get (img, width) i j k = Char.code (Bytes.get img (((j * width) + i) * 3 + k)) let set (img, width) i j k v = Bytes.set img (((j * width) + i) * 3 + k) (Char.unsafe_chr v) let setp (img, width) i j r g b = let p = ((j * width) + i) * 3 in Bytes.set img p (Char.unsafe_chr r); Bytes.set img (p + 1) (Char.unsafe_chr g); Bytes.set img (p + 2) (Char.unsafe_chr b) let init ~width ~height = (Bytes.create (height * width * 3), width) let width (s, width) = width let height (s, width) = Bytes.length s / width / 3 let dump file (img, width) = let sz = Bytes.length img in let height = sz / 3 / width in let f = open_out_bin file in output_string f "P6\n# PL Club\n"; Printf.fprintf f "%d %d\n255\n" width height; output_bytes f img; close_out f let load file = let f = open_in_bin file in assert (input_line f = "P6"); let s = input_line f in let i = ref 0 in while s.[!i] >= '0' && s.[!i] <= '9' do incr i done; let width = int_of_string (String.sub s 0 !i) in let height = int_of_string (String.sub s (!i + 1) (String.length s - !i - 1)) in assert (input_line f = "255"); let (s, _) as img = init width height in really_input f s 0 (Bytes.length s); close_in f; img
84880f1a122d994a473bd08ee765b289381b65d515f269bb14385535046ad527
ngrunwald/datasplash
es.clj
(ns datasplash.es (:require [charred.api :as charred] [datasplash.core :as ds]) (:import (datasplash.fns ExtractKeyFn) (org.apache.beam.sdk Pipeline) (org.apache.beam.sdk.values PBegin PCollection) (org.apache.beam.sdk.io.elasticsearch ElasticsearchIO ElasticsearchIO$Read ElasticsearchIO$Write ElasticsearchIO$RetryConfiguration ElasticsearchIO$ConnectionConfiguration) (org.joda.time Duration)) (:gen-class)) (def ^:no-doc es-connection-schema (merge ds/named-schema {:username {:docstr "username"} :password {:docstr "password"} :keystore-password {:docstr "If Elasticsearch uses SSL/TLS with mutual authentication (via shield), provide the password to open the client keystore."} :keystore-path {:docstr "If Elasticsearch uses SSL/TLS with mutual authentication (via shield), provide the password to open the client keystore."}})) (defn- es-config "Creates a new Elasticsearch connection configuration." [hosts index type {:keys [username password keystore-password keystore-path]}] (let [hosts-array (into-array String hosts)] (cond-> (ElasticsearchIO$ConnectionConfiguration/create hosts-array index type) username (.withUsername username) password (.withPassword password) keystore-password (.withKeystorePassword keystore-password) keystore-path (.withKeystorePath keystore-path)))) (defn- retry-config "Creates RetryConfiguration for ElasticsearchIO with provided max-attempts, max-duration-ms and exponential backoff based retries." [max-attempts max-duration-ms] (let [duration (Duration. max-duration-ms)] (ElasticsearchIO$RetryConfiguration/create max-attempts duration))) (def ^:no-doc read-es-schema (merge es-connection-schema {:key-fn {:docstr "Can be either true (to coerce keys to keywords),false to leave them as strings, or a function to provide custom coercion."} :batch-size {:docstr "Specify the scroll size (number of document by page). Default to 100. Maximum is 10 000. If documents are small, increasing batch size might improve read performance. If documents are big, you might need to decrease batch-size" :action (fn [^ElasticsearchIO$Read transform ^Long b] (.withBatchSize transform b))} :query {:docstr "Provide a query used while reading from Elasticsearch." :action (fn [^ElasticsearchIO$Read transform ^String q] (.withQuery transform q))} :scroll-keep-alive {:docstr "Provide a scroll keepalive. See -request-scroll.html . Default is \"5m\". Change this only if you get \"No search context found\" errors." :action (fn [^ElasticsearchIO$Read transform ^String q] (.withQuery transform q))}})) (defn- read-es-raw "Connects and reads form Elasticserach, returns a PColl of strings" [hosts index type options p] (let [opts (assoc options :label :read-es-raw) ptrans (-> (ElasticsearchIO/read) (.withConnectionConfiguration (es-config hosts index type opts)))] (-> p (cond-> (instance? Pipeline p) (PBegin/in)) (ds/apply-transform ptrans read-es-schema opts)))) (defn- read-es-clj-transform "Connects to ES, reads, and convert serialized json to clojure map" [hosts index type options] (let [safe-opts (dissoc options :name) key-fn (or (get options :key-fn) false)] (ds/ptransform :read-es-to-clj [^PCollection pcoll] (->> pcoll (read-es-raw hosts index type safe-opts) (ds/dmap #(charred/read-json % :key-fn key-fn) safe-opts))))) (defn read-es {:doc (ds/with-opts-docstr "Read from elasticsearch. See Examples: ``` (es/read-es [\":9200\"] \"my-index\" \"my-type\" {:batch-size 100 :keep-alive \"5m\"} pcoll) ```" read-es-schema) :added "0.6.5"} ([hosts index type options p] (let [opts (assoc options :label :read-es)] (ds/apply-transform p (read-es-clj-transform hosts index type options) ds/base-schema opts))) ([hosts index type p] (read-es hosts index type {} p))) (def ^:no-doc write-es-schema (merge es-connection-schema {:max-batch-size {:docstr "Specify the max number of documents in a bulk. Default to 1000" :action (fn [^ElasticsearchIO$Write transform ^Long b] (.withMaxBatchSizeBytes transform b))} :max-batch-size-bytes {:docstr "Specify the max number of bytes in a bulk. Default to 5MB" :action (fn [^ElasticsearchIO$Write transform ^Long b] (.withMaxBatchSizeBytes transform b))} :retry-configuration {:docstr "Creates RetryConfiguration for ElasticsearchIO with provided max-attempts, max-durations and exponential backoff based retries" :action (fn [^ElasticsearchIO$Write transform [^Long max-attempts ^Long max-duration-ms]] (.withRetryConfiguration transform (retry-config max-attempts max-duration-ms)))} :id-fn {:doctstr "Provide a function to extract the id from the document." :action (fn [^ElasticsearchIO$Write transform key-fn] (let [serializing-key-fn #(charred/read-json % :key-fn key-fn) id-fn (ExtractKeyFn. serializing-key-fn)] (.withIdFn transform id-fn)))} :index-fn {:doctstr "Provide a function to extract the target index from the document allowing for dynamic document routing." :action (fn [^ElasticsearchIO$Write transform key-fn] (let [serializing-key-fn #(charred/read-json % :key-fn key-fn) index-fn (ExtractKeyFn. serializing-key-fn)] (.withIndexFn transform index-fn)))} :type-fn {:docstr "Provide a function to extract the target type from the document allowing for dynamic document routing." :action (fn [^ElasticsearchIO$Write transform key-fn] (let [serializing-key-fn #(charred/read-json % :key-fn key-fn) type-fn (ExtractKeyFn. serializing-key-fn)] (.withTypeFn transform type-fn)))} :use-partial-update {:docstr "Provide an instruction to control whether partial updates or inserts (default) are issued to Elasticsearch." :action (fn [^ElasticsearchIO$Write transform is-partial-update] (.withUsePartialUpdate transform is-partial-update))}})) (defn- write-es-raw ([hosts index type options ^PCollection pcoll] (let [opts (assoc options :label :write-es-raw)] (ds/apply-transform pcoll (-> (ElasticsearchIO/write) (.withConnectionConfiguration (es-config hosts index type opts))) write-es-schema opts))) ([hosts index type pcoll] (write-es-raw hosts index type {} pcoll))) (defn- write-es-clj-transform [hosts index type options] (let [safe-opts (dissoc options :name)] (ds/ptransform :write-es-from-clj [^PCollection pcoll] (->> pcoll (ds/dmap ds/write-json-str) (write-es-raw hosts index type safe-opts))))) (defn write-es {:doc (ds/with-opts-docstr "Write to elasticsearch. See Examples: ``` (es/write-es [\":9200\"] \"my-index\" \"my-type\" {:id-fn (fn [x] (get x \"id\")) :max-batch-size-bytes 50000000 :name write-es}) ```" write-es-schema) :added "0.6.5"} ([hosts index type options ^PCollection pcoll] (let [opts (assoc options :label :write-es)] (ds/apply-transform pcoll (write-es-clj-transform hosts index type opts) ds/named-schema opts))) ([hosts index type pcoll] (write-es hosts index type {} pcoll)))
null
https://raw.githubusercontent.com/ngrunwald/datasplash/d221bba9ffc4807281dd9df549ed4010a38d0279/src/clj/datasplash/es.clj
clojure
(ns datasplash.es (:require [charred.api :as charred] [datasplash.core :as ds]) (:import (datasplash.fns ExtractKeyFn) (org.apache.beam.sdk Pipeline) (org.apache.beam.sdk.values PBegin PCollection) (org.apache.beam.sdk.io.elasticsearch ElasticsearchIO ElasticsearchIO$Read ElasticsearchIO$Write ElasticsearchIO$RetryConfiguration ElasticsearchIO$ConnectionConfiguration) (org.joda.time Duration)) (:gen-class)) (def ^:no-doc es-connection-schema (merge ds/named-schema {:username {:docstr "username"} :password {:docstr "password"} :keystore-password {:docstr "If Elasticsearch uses SSL/TLS with mutual authentication (via shield), provide the password to open the client keystore."} :keystore-path {:docstr "If Elasticsearch uses SSL/TLS with mutual authentication (via shield), provide the password to open the client keystore."}})) (defn- es-config "Creates a new Elasticsearch connection configuration." [hosts index type {:keys [username password keystore-password keystore-path]}] (let [hosts-array (into-array String hosts)] (cond-> (ElasticsearchIO$ConnectionConfiguration/create hosts-array index type) username (.withUsername username) password (.withPassword password) keystore-password (.withKeystorePassword keystore-password) keystore-path (.withKeystorePath keystore-path)))) (defn- retry-config "Creates RetryConfiguration for ElasticsearchIO with provided max-attempts, max-duration-ms and exponential backoff based retries." [max-attempts max-duration-ms] (let [duration (Duration. max-duration-ms)] (ElasticsearchIO$RetryConfiguration/create max-attempts duration))) (def ^:no-doc read-es-schema (merge es-connection-schema {:key-fn {:docstr "Can be either true (to coerce keys to keywords),false to leave them as strings, or a function to provide custom coercion."} :batch-size {:docstr "Specify the scroll size (number of document by page). Default to 100. Maximum is 10 000. If documents are small, increasing batch size might improve read performance. If documents are big, you might need to decrease batch-size" :action (fn [^ElasticsearchIO$Read transform ^Long b] (.withBatchSize transform b))} :query {:docstr "Provide a query used while reading from Elasticsearch." :action (fn [^ElasticsearchIO$Read transform ^String q] (.withQuery transform q))} :scroll-keep-alive {:docstr "Provide a scroll keepalive. See -request-scroll.html . Default is \"5m\". Change this only if you get \"No search context found\" errors." :action (fn [^ElasticsearchIO$Read transform ^String q] (.withQuery transform q))}})) (defn- read-es-raw "Connects and reads form Elasticserach, returns a PColl of strings" [hosts index type options p] (let [opts (assoc options :label :read-es-raw) ptrans (-> (ElasticsearchIO/read) (.withConnectionConfiguration (es-config hosts index type opts)))] (-> p (cond-> (instance? Pipeline p) (PBegin/in)) (ds/apply-transform ptrans read-es-schema opts)))) (defn- read-es-clj-transform "Connects to ES, reads, and convert serialized json to clojure map" [hosts index type options] (let [safe-opts (dissoc options :name) key-fn (or (get options :key-fn) false)] (ds/ptransform :read-es-to-clj [^PCollection pcoll] (->> pcoll (read-es-raw hosts index type safe-opts) (ds/dmap #(charred/read-json % :key-fn key-fn) safe-opts))))) (defn read-es {:doc (ds/with-opts-docstr "Read from elasticsearch. See Examples: ``` (es/read-es [\":9200\"] \"my-index\" \"my-type\" {:batch-size 100 :keep-alive \"5m\"} pcoll) ```" read-es-schema) :added "0.6.5"} ([hosts index type options p] (let [opts (assoc options :label :read-es)] (ds/apply-transform p (read-es-clj-transform hosts index type options) ds/base-schema opts))) ([hosts index type p] (read-es hosts index type {} p))) (def ^:no-doc write-es-schema (merge es-connection-schema {:max-batch-size {:docstr "Specify the max number of documents in a bulk. Default to 1000" :action (fn [^ElasticsearchIO$Write transform ^Long b] (.withMaxBatchSizeBytes transform b))} :max-batch-size-bytes {:docstr "Specify the max number of bytes in a bulk. Default to 5MB" :action (fn [^ElasticsearchIO$Write transform ^Long b] (.withMaxBatchSizeBytes transform b))} :retry-configuration {:docstr "Creates RetryConfiguration for ElasticsearchIO with provided max-attempts, max-durations and exponential backoff based retries" :action (fn [^ElasticsearchIO$Write transform [^Long max-attempts ^Long max-duration-ms]] (.withRetryConfiguration transform (retry-config max-attempts max-duration-ms)))} :id-fn {:doctstr "Provide a function to extract the id from the document." :action (fn [^ElasticsearchIO$Write transform key-fn] (let [serializing-key-fn #(charred/read-json % :key-fn key-fn) id-fn (ExtractKeyFn. serializing-key-fn)] (.withIdFn transform id-fn)))} :index-fn {:doctstr "Provide a function to extract the target index from the document allowing for dynamic document routing." :action (fn [^ElasticsearchIO$Write transform key-fn] (let [serializing-key-fn #(charred/read-json % :key-fn key-fn) index-fn (ExtractKeyFn. serializing-key-fn)] (.withIndexFn transform index-fn)))} :type-fn {:docstr "Provide a function to extract the target type from the document allowing for dynamic document routing." :action (fn [^ElasticsearchIO$Write transform key-fn] (let [serializing-key-fn #(charred/read-json % :key-fn key-fn) type-fn (ExtractKeyFn. serializing-key-fn)] (.withTypeFn transform type-fn)))} :use-partial-update {:docstr "Provide an instruction to control whether partial updates or inserts (default) are issued to Elasticsearch." :action (fn [^ElasticsearchIO$Write transform is-partial-update] (.withUsePartialUpdate transform is-partial-update))}})) (defn- write-es-raw ([hosts index type options ^PCollection pcoll] (let [opts (assoc options :label :write-es-raw)] (ds/apply-transform pcoll (-> (ElasticsearchIO/write) (.withConnectionConfiguration (es-config hosts index type opts))) write-es-schema opts))) ([hosts index type pcoll] (write-es-raw hosts index type {} pcoll))) (defn- write-es-clj-transform [hosts index type options] (let [safe-opts (dissoc options :name)] (ds/ptransform :write-es-from-clj [^PCollection pcoll] (->> pcoll (ds/dmap ds/write-json-str) (write-es-raw hosts index type safe-opts))))) (defn write-es {:doc (ds/with-opts-docstr "Write to elasticsearch. See Examples: ``` (es/write-es [\":9200\"] \"my-index\" \"my-type\" {:id-fn (fn [x] (get x \"id\")) :max-batch-size-bytes 50000000 :name write-es}) ```" write-es-schema) :added "0.6.5"} ([hosts index type options ^PCollection pcoll] (let [opts (assoc options :label :write-es)] (ds/apply-transform pcoll (write-es-clj-transform hosts index type opts) ds/named-schema opts))) ([hosts index type pcoll] (write-es hosts index type {} pcoll)))
3865f1b6d3d4c5badc9bce4e7b838a0b6601a1e1c78a55b1b3e0cfbbf16f689d
beckyconning/haskell-snake
Snake.hs
# OPTIONS_GHC -Wall # import Data.List import System.IO import System.Timeout import System.Random import System.Console.ANSI import Control.Concurrent import Control.Concurrent.Async import Control.Monad.Loops import Control.Applicative type Vector = (Int, Int) data State = State { board :: Int, snake :: [Vector], fruit :: Maybe (Vector, StdGen), move :: Maybe Vector } deriving Show main :: IO State main = clearScreen >> initialState >>= (iterateUntilM gameOver step) oneSecond :: Int oneSecond = (10 :: Int) ^ (6 :: Int) sampleLength :: Int sampleLength = oneSecond `div` 4 initialState :: IO State initialState = getStdGen >>= \stdGen -> return State { board = 15, snake = [(4, 0), (3, 0), (2, 0), (1, 0), (0, 0)], fruit = randomElem (concat (buildBoard 15)) stdGen, move = Just (1, 0) } randomElem :: [a] -> StdGen -> Maybe (a, StdGen) randomElem [] _ = Nothing randomElem xs inputStdGen = Just (element, stdGen) where indexStdGenTuple = randomR (0, length xs - 1) inputStdGen index = fst indexStdGenTuple stdGen = snd indexStdGenTuple element = xs !! index newFruit :: State -> Maybe (Vector, StdGen) newFruit (State { fruit = Nothing }) = Nothing newFruit state@(State { fruit = Just (_, stdGen) }) = randomElem validPositions stdGen where allPositions = concat $ buildBoard $ board state validPositions = allPositions \\ snake state step :: State -> IO State step state = sample sampleLength getInput >>= \ inputMove -> displayState $ updateState state (vectorFromChar inputMove) displayState :: State -> IO State displayState state = setCursorPosition 0 0 >> putStr (render state) >> return state vectorFromChar :: Maybe Char -> Maybe Vector vectorFromChar (Just 'w') = Just ( 0, 1) vectorFromChar (Just 'a') = Just (-1, 0) vectorFromChar (Just 's') = Just ( 0, -1) vectorFromChar (Just 'd') = Just ( 1, 0) vectorFromChar _ = Nothing getInput :: IO Char getInput = hSetEcho stdin False >> hSetBuffering stdin NoBuffering >> getChar gameOver :: State -> Bool gameOver (State { snake = [] }) = True gameOver (State { board = boardSize, snake = (snakeHead@(snakeHeadX, snakeHeadY):snakeBody) }) | snakeHeadX >= boardSize || snakeHeadX < 0 = True | snakeHeadY >= boardSize || snakeHeadY < 0 = True | snakeHead `elem` snakeBody = True | otherwise = False render :: State -> String render state = unlines $ applyBorder (board state) $ map (renderRow state) $ buildBoard (board state) applyBorder :: Int -> [String] -> [String] applyBorder size renderedRows = border ++ map (\row -> "X" ++ row ++ "X") renderedRows ++ border where border = [replicate (size + 2) 'X'] renderRow :: State -> [Vector] -> String renderRow state = map (characterForPosition state) characterForPosition :: State -> Vector -> Char characterForPosition state position | position `elem` snake state = '#' | fruit state `fruitPositionEquals` position = '@' | otherwise = ' ' fruitPositionEquals :: Maybe (Vector, StdGen) -> Vector -> Bool fruitPositionEquals (Just (position, _)) vector = position == vector fruitPositionEquals _ _ = False snakeHasFruitInMouth :: State -> Bool snakeHasFruitInMouth state = fruit state `fruitPositionEquals` head (snake state) buildBoard :: Int -> [[(Int, Int)]] buildBoard size = [[(x, y) | x <- [0 .. size - 1]] | y <- reverse [0 .. size - 1]] updateState :: State -> Maybe Vector -> State updateState state inputMove = updateFruit $ updateSnake $ updateMove state inputMove updateMove :: State -> Maybe Vector -> State updateMove state@(State { move = Just vector }) inputMove@(Just inputVector) | inputVector == vectorOpposite vector = state | otherwise = state { move = inputMove <|> move state } updateMove state _ = state updateSnake :: State -> State updateSnake = updateSnakeTail . updateSnakeHead updateFruit :: State -> State updateFruit state | snakeHasFruitInMouth state = state { fruit = newFruit state } | otherwise = state updateSnakeHead :: State -> State updateSnakeHead state@(State { move = (Just vector) }) = state { snake = head (snake state) `vectorAdd` vector : snake state } updateSnakeHead state = state updateSnakeTail :: State -> State updateSnakeTail state | snakeHasFruitInMouth state = state | otherwise = state { snake = init $ snake state } vectorAdd :: Vector -> Vector -> Vector vectorAdd (x1, y1) (x2, y2) = (x1 + x2, y1 + y2) vectorOpposite :: Vector -> Vector vectorOpposite (x, y) = (-x, -y) sample :: Int -> IO a -> IO (Maybe a) sample n f | n < 0 = fmap Just f | n == 0 = return Nothing | otherwise = concurrently (timeout n f) (threadDelay n) >>= \ (result, _) -> return result
null
https://raw.githubusercontent.com/beckyconning/haskell-snake/c323fd34fc873f6c9ba33028f6add7e6d879c260/Snake.hs
haskell
# OPTIONS_GHC -Wall # import Data.List import System.IO import System.Timeout import System.Random import System.Console.ANSI import Control.Concurrent import Control.Concurrent.Async import Control.Monad.Loops import Control.Applicative type Vector = (Int, Int) data State = State { board :: Int, snake :: [Vector], fruit :: Maybe (Vector, StdGen), move :: Maybe Vector } deriving Show main :: IO State main = clearScreen >> initialState >>= (iterateUntilM gameOver step) oneSecond :: Int oneSecond = (10 :: Int) ^ (6 :: Int) sampleLength :: Int sampleLength = oneSecond `div` 4 initialState :: IO State initialState = getStdGen >>= \stdGen -> return State { board = 15, snake = [(4, 0), (3, 0), (2, 0), (1, 0), (0, 0)], fruit = randomElem (concat (buildBoard 15)) stdGen, move = Just (1, 0) } randomElem :: [a] -> StdGen -> Maybe (a, StdGen) randomElem [] _ = Nothing randomElem xs inputStdGen = Just (element, stdGen) where indexStdGenTuple = randomR (0, length xs - 1) inputStdGen index = fst indexStdGenTuple stdGen = snd indexStdGenTuple element = xs !! index newFruit :: State -> Maybe (Vector, StdGen) newFruit (State { fruit = Nothing }) = Nothing newFruit state@(State { fruit = Just (_, stdGen) }) = randomElem validPositions stdGen where allPositions = concat $ buildBoard $ board state validPositions = allPositions \\ snake state step :: State -> IO State step state = sample sampleLength getInput >>= \ inputMove -> displayState $ updateState state (vectorFromChar inputMove) displayState :: State -> IO State displayState state = setCursorPosition 0 0 >> putStr (render state) >> return state vectorFromChar :: Maybe Char -> Maybe Vector vectorFromChar (Just 'w') = Just ( 0, 1) vectorFromChar (Just 'a') = Just (-1, 0) vectorFromChar (Just 's') = Just ( 0, -1) vectorFromChar (Just 'd') = Just ( 1, 0) vectorFromChar _ = Nothing getInput :: IO Char getInput = hSetEcho stdin False >> hSetBuffering stdin NoBuffering >> getChar gameOver :: State -> Bool gameOver (State { snake = [] }) = True gameOver (State { board = boardSize, snake = (snakeHead@(snakeHeadX, snakeHeadY):snakeBody) }) | snakeHeadX >= boardSize || snakeHeadX < 0 = True | snakeHeadY >= boardSize || snakeHeadY < 0 = True | snakeHead `elem` snakeBody = True | otherwise = False render :: State -> String render state = unlines $ applyBorder (board state) $ map (renderRow state) $ buildBoard (board state) applyBorder :: Int -> [String] -> [String] applyBorder size renderedRows = border ++ map (\row -> "X" ++ row ++ "X") renderedRows ++ border where border = [replicate (size + 2) 'X'] renderRow :: State -> [Vector] -> String renderRow state = map (characterForPosition state) characterForPosition :: State -> Vector -> Char characterForPosition state position | position `elem` snake state = '#' | fruit state `fruitPositionEquals` position = '@' | otherwise = ' ' fruitPositionEquals :: Maybe (Vector, StdGen) -> Vector -> Bool fruitPositionEquals (Just (position, _)) vector = position == vector fruitPositionEquals _ _ = False snakeHasFruitInMouth :: State -> Bool snakeHasFruitInMouth state = fruit state `fruitPositionEquals` head (snake state) buildBoard :: Int -> [[(Int, Int)]] buildBoard size = [[(x, y) | x <- [0 .. size - 1]] | y <- reverse [0 .. size - 1]] updateState :: State -> Maybe Vector -> State updateState state inputMove = updateFruit $ updateSnake $ updateMove state inputMove updateMove :: State -> Maybe Vector -> State updateMove state@(State { move = Just vector }) inputMove@(Just inputVector) | inputVector == vectorOpposite vector = state | otherwise = state { move = inputMove <|> move state } updateMove state _ = state updateSnake :: State -> State updateSnake = updateSnakeTail . updateSnakeHead updateFruit :: State -> State updateFruit state | snakeHasFruitInMouth state = state { fruit = newFruit state } | otherwise = state updateSnakeHead :: State -> State updateSnakeHead state@(State { move = (Just vector) }) = state { snake = head (snake state) `vectorAdd` vector : snake state } updateSnakeHead state = state updateSnakeTail :: State -> State updateSnakeTail state | snakeHasFruitInMouth state = state | otherwise = state { snake = init $ snake state } vectorAdd :: Vector -> Vector -> Vector vectorAdd (x1, y1) (x2, y2) = (x1 + x2, y1 + y2) vectorOpposite :: Vector -> Vector vectorOpposite (x, y) = (-x, -y) sample :: Int -> IO a -> IO (Maybe a) sample n f | n < 0 = fmap Just f | n == 0 = return Nothing | otherwise = concurrently (timeout n f) (threadDelay n) >>= \ (result, _) -> return result
d2f1e8f0ac747f9ae02ec253ac8e82d6f41511cfd7b3d466a33f98de6ac536e4
cmsc430/www
unload-bits-asm.rkt
#lang racket (provide unload/free unload-value) (require "types.rkt" ffi/unsafe) (struct struct-val () #:transparent) ;; Answer* -> Answer (define (unload/free a) (match a ['err 'err] [(cons h v) (begin0 (unload-value v) (free h))])) ;; Value* -> Value (define (unload-value v) (match v [(? imm-bits?) (bits->value v)] [(? box-bits? i) (box (unload-value (heap-ref i)))] [(? cons-bits? i) (cons (unload-value (heap-ref (+ i 8))) (unload-value (heap-ref i)))] [(? vect-bits? i) (if (zero? (untag i)) (vector) (build-vector (heap-ref i) (lambda (j) (unload-value (heap-ref (+ i (* 8 (add1 j))))))))] [(? str-bits? i) (if (zero? (untag i)) (string) (build-string (heap-ref i) (lambda (j) (char-ref (+ i 8) j))))] [(? symb-bits? i) (string->symbol (if (zero? (untag i)) (string) (build-string (heap-ref i) (lambda (j) (char-ref (+ i 8) j)))))] [(? proc-bits? i) (lambda _ (error "This function is not callable."))] [(? struct-bits? i) (struct-val)])) (define (untag i) (arithmetic-shift (arithmetic-shift i (- (integer-length ptr-mask))) (integer-length ptr-mask))) (define (heap-ref i) (ptr-ref (cast (untag i) _int64 _pointer) _int64)) (define (char-ref i j) (integer->char (ptr-ref (cast (untag i) _int64 _pointer) _uint32 j)))
null
https://raw.githubusercontent.com/cmsc430/www/fc3165545c81d4da3d0aaae33a1e5f8f8cafe0e6/langs/neerdowell/unload-bits-asm.rkt
racket
Answer* -> Answer Value* -> Value
#lang racket (provide unload/free unload-value) (require "types.rkt" ffi/unsafe) (struct struct-val () #:transparent) (define (unload/free a) (match a ['err 'err] [(cons h v) (begin0 (unload-value v) (free h))])) (define (unload-value v) (match v [(? imm-bits?) (bits->value v)] [(? box-bits? i) (box (unload-value (heap-ref i)))] [(? cons-bits? i) (cons (unload-value (heap-ref (+ i 8))) (unload-value (heap-ref i)))] [(? vect-bits? i) (if (zero? (untag i)) (vector) (build-vector (heap-ref i) (lambda (j) (unload-value (heap-ref (+ i (* 8 (add1 j))))))))] [(? str-bits? i) (if (zero? (untag i)) (string) (build-string (heap-ref i) (lambda (j) (char-ref (+ i 8) j))))] [(? symb-bits? i) (string->symbol (if (zero? (untag i)) (string) (build-string (heap-ref i) (lambda (j) (char-ref (+ i 8) j)))))] [(? proc-bits? i) (lambda _ (error "This function is not callable."))] [(? struct-bits? i) (struct-val)])) (define (untag i) (arithmetic-shift (arithmetic-shift i (- (integer-length ptr-mask))) (integer-length ptr-mask))) (define (heap-ref i) (ptr-ref (cast (untag i) _int64 _pointer) _int64)) (define (char-ref i j) (integer->char (ptr-ref (cast (untag i) _int64 _pointer) _uint32 j)))
cc9f99a3541c084f888cbe72e04e121aa52b3c955edeaac4284cc2f74dd2c24c
mzp/coq-ide-for-ios
omega_plugin_mod.ml
let _=Mltop.add_known_module"Omega" let _=Mltop.add_known_module"Coq_omega" let _=Mltop.add_known_module"G_omega" let _=Mltop.add_known_module"Omega_plugin_mod" let _=Mltop.add_known_module"omega_plugin"
null
https://raw.githubusercontent.com/mzp/coq-ide-for-ios/4cdb389bbecd7cdd114666a8450ecf5b5f0391d3/CoqIDE/coq-8.2pl2/plugins/omega/omega_plugin_mod.ml
ocaml
let _=Mltop.add_known_module"Omega" let _=Mltop.add_known_module"Coq_omega" let _=Mltop.add_known_module"G_omega" let _=Mltop.add_known_module"Omega_plugin_mod" let _=Mltop.add_known_module"omega_plugin"
f7fd319787726ce999c0e8a3937933a272bc857164c1015cfe05717404fa2ccd
haskell-tools/haskell-tools
Definitions.hs
# LANGUAGE TypeOperators # module Definitions where data (:+:) a b = Plus a b
null
https://raw.githubusercontent.com/haskell-tools/haskell-tools/b1189ab4f63b29bbf1aa14af4557850064931e32/src/builtin-refactorings/test/ExtensionOrganizerTest/ExplicitNamespacesTest/Definitions.hs
haskell
# LANGUAGE TypeOperators # module Definitions where data (:+:) a b = Plus a b
aa571a7d2caf7d124ccdbc924f8888ea3b3bda7976d050782bfeb82260cca376
raffy2010/grand-slam
video_item.cljs
(ns ui.component.video-item (:require [clojure.string :refer [join split]] [cljs.core.match :refer-macros [match]] [reagent.core :as r] [cljs-react-material-ui.reagent :as ui] [cljs-react-material-ui.icons :as ic] [reanimated.core :as anim] [ui.utils.common :refer [format-file-size format-time format-bitrate]] [ui.state :refer [active-files tasks]] [ui.ffmpeg :refer [cancel-convert clean-file]] [ui.component.video-thumbnail :refer [video-thumbnail]] [ui.component.video-stream :refer [stream-item]] [ui.component.video-dialog :refer [convert-dialog]])) (defn toggle-file-select "doc-string" [file event] (let [file-id (:id file)] (swap! active-files update-in [file-id :selected] not))) (defn toggle-file-detail "doc-string" [file event] (let [file-id (:id file)] (.stopPropagation event) (swap! active-files update-in [file-id :detailed] not))) (defn toggle-convert-modal "open video conversion modal" [file event elem] (let [file-id (:id file) mode (.-type (.-props elem))] (swap! active-files assoc-in [file-id :convert-mode] mode))) (defn handle-more "handle more action with file" [file event elem] (let [file-id (:id file) action (-> elem .-props .-action)] (match action "remove" (clean-file file-id)))) (defn handle-cancel [task event] (do (.stopPropagation event) (swap! tasks dissoc (:id task)) (cancel-convert (get-in task [:process :pid])))) (defn find-task [file] (let [file-id (:id file)] (->> @tasks vals (filter #(= file-id (:file-id %))) first))) (defn cancel-btn [task] [:div {:style {:top 0 :right 0}} [ui/icon-button {:on-click (partial handle-cancel task)} (ic/content-clear)]]) (defn action-btns [file] [:div {:style {:top 0 :right 0 :width 144}} [ui/icon-button {:class (if (:detailed file) "fold" "more") :on-click (partial toggle-file-detail file)} (if (:detailed file) (ic/navigation-expand-less) (ic/navigation-expand-more))] [ui/icon-menu {:use-layer-for-click-away true :icon-button-element (r/as-element [ui/icon-button {:on-click #(.stopPropagation %)} (ic/action-swap-horiz)]) :anchor-origin {:horizontal "right" :vertical "top"} :target-origin {:horizontal "right" :vertical "top"} :on-item-touch-tap (partial toggle-convert-modal file)} [ui/menu-item {:primary-text "type" :type "video-type"}] [ui/menu-item {:primary-text "quality" :type "video-quality"}] [ui/menu-item {:primary-text "dimension" :type "video-dimension"}] [ui/menu-item {:primary-text "preset" :type "video-preset"}] [ui/menu-item {:primary-text "custom" :type "advance"}]] [ui/icon-menu {:use-layer-for-click-away true :icon-button-element (r/as-element [ui/icon-button {:on-click #(.stopPropagation %)} (ic/navigation-more-vert)]) :anchor-origin {:horizontal "right" :vertical "top"} :target-origin {:horizontal "right" :vertical "top"} :on-item-touch-tap (partial handle-more file)} [ui/menu-item {:primary-text "remove" :action "remove"}]]]) (defn format-filename [filename] (last (split filename "/"))) (defn file-field [field value] (match field :duration [:p {:class "single-field"} [ic/action-schedule] [:span (format-time (js/parseInt value 10))]] :size [:p {:class "single-field"} [ic/notification-ondemand-video] [:span (format-file-size value)]] :bit_rate [:p {:class "single-field"} [ic/action-trending-up] [:span (str (format-bitrate value) "/s")]] :filename [:p {:class "single-field"} [ic/file-folder-open] [:span (format-filename value)]])) (defn video-item "video item card" [file] (let [task (find-task file)] [ui/card [:div {:class (str "video-card" (cond (:selected file) " video-selected" (:detailed file) " video-detailed")) :on-click (partial toggle-file-select file)} [video-thumbnail file] [:div {:class "video-info"} (for [field [:filename :size :bit_rate :duration]] ^{:key field} [:div (file-field field (get-in file [:format field]))])] (if-not (nil? task) [ui/linear-progress {:class "convert-progress-bar" :mode "determinate" :value (get-in task [:process :progress])}]) [:div {:class "action-menu"} [anim/css-transition-group {:transition-name "cancel-btn" :transition-enter-timeout 500 :transition-leave-timeout 500} (if-not (nil? task) (cancel-btn task))] [anim/css-transition-group {:transition-name "action-btn" :transition-enter-timeout 500 :transition-leave-timeout 500} (if (nil? task) (action-btns file))]] [:div {:class (str "video-stream-detail" (if (:more-detail file) " detail-active")) :on-click #(.stopPropagation %)} (for [stream (:streams file)] ^{:key stream} [stream-item stream])] (when-not (nil? (:convert-mode file)) [convert-dialog file])]]))
null
https://raw.githubusercontent.com/raffy2010/grand-slam/752984d606f4e201b305c6ac931dd0d03a12f4b4/ui_src/ui/component/video_item.cljs
clojure
(ns ui.component.video-item (:require [clojure.string :refer [join split]] [cljs.core.match :refer-macros [match]] [reagent.core :as r] [cljs-react-material-ui.reagent :as ui] [cljs-react-material-ui.icons :as ic] [reanimated.core :as anim] [ui.utils.common :refer [format-file-size format-time format-bitrate]] [ui.state :refer [active-files tasks]] [ui.ffmpeg :refer [cancel-convert clean-file]] [ui.component.video-thumbnail :refer [video-thumbnail]] [ui.component.video-stream :refer [stream-item]] [ui.component.video-dialog :refer [convert-dialog]])) (defn toggle-file-select "doc-string" [file event] (let [file-id (:id file)] (swap! active-files update-in [file-id :selected] not))) (defn toggle-file-detail "doc-string" [file event] (let [file-id (:id file)] (.stopPropagation event) (swap! active-files update-in [file-id :detailed] not))) (defn toggle-convert-modal "open video conversion modal" [file event elem] (let [file-id (:id file) mode (.-type (.-props elem))] (swap! active-files assoc-in [file-id :convert-mode] mode))) (defn handle-more "handle more action with file" [file event elem] (let [file-id (:id file) action (-> elem .-props .-action)] (match action "remove" (clean-file file-id)))) (defn handle-cancel [task event] (do (.stopPropagation event) (swap! tasks dissoc (:id task)) (cancel-convert (get-in task [:process :pid])))) (defn find-task [file] (let [file-id (:id file)] (->> @tasks vals (filter #(= file-id (:file-id %))) first))) (defn cancel-btn [task] [:div {:style {:top 0 :right 0}} [ui/icon-button {:on-click (partial handle-cancel task)} (ic/content-clear)]]) (defn action-btns [file] [:div {:style {:top 0 :right 0 :width 144}} [ui/icon-button {:class (if (:detailed file) "fold" "more") :on-click (partial toggle-file-detail file)} (if (:detailed file) (ic/navigation-expand-less) (ic/navigation-expand-more))] [ui/icon-menu {:use-layer-for-click-away true :icon-button-element (r/as-element [ui/icon-button {:on-click #(.stopPropagation %)} (ic/action-swap-horiz)]) :anchor-origin {:horizontal "right" :vertical "top"} :target-origin {:horizontal "right" :vertical "top"} :on-item-touch-tap (partial toggle-convert-modal file)} [ui/menu-item {:primary-text "type" :type "video-type"}] [ui/menu-item {:primary-text "quality" :type "video-quality"}] [ui/menu-item {:primary-text "dimension" :type "video-dimension"}] [ui/menu-item {:primary-text "preset" :type "video-preset"}] [ui/menu-item {:primary-text "custom" :type "advance"}]] [ui/icon-menu {:use-layer-for-click-away true :icon-button-element (r/as-element [ui/icon-button {:on-click #(.stopPropagation %)} (ic/navigation-more-vert)]) :anchor-origin {:horizontal "right" :vertical "top"} :target-origin {:horizontal "right" :vertical "top"} :on-item-touch-tap (partial handle-more file)} [ui/menu-item {:primary-text "remove" :action "remove"}]]]) (defn format-filename [filename] (last (split filename "/"))) (defn file-field [field value] (match field :duration [:p {:class "single-field"} [ic/action-schedule] [:span (format-time (js/parseInt value 10))]] :size [:p {:class "single-field"} [ic/notification-ondemand-video] [:span (format-file-size value)]] :bit_rate [:p {:class "single-field"} [ic/action-trending-up] [:span (str (format-bitrate value) "/s")]] :filename [:p {:class "single-field"} [ic/file-folder-open] [:span (format-filename value)]])) (defn video-item "video item card" [file] (let [task (find-task file)] [ui/card [:div {:class (str "video-card" (cond (:selected file) " video-selected" (:detailed file) " video-detailed")) :on-click (partial toggle-file-select file)} [video-thumbnail file] [:div {:class "video-info"} (for [field [:filename :size :bit_rate :duration]] ^{:key field} [:div (file-field field (get-in file [:format field]))])] (if-not (nil? task) [ui/linear-progress {:class "convert-progress-bar" :mode "determinate" :value (get-in task [:process :progress])}]) [:div {:class "action-menu"} [anim/css-transition-group {:transition-name "cancel-btn" :transition-enter-timeout 500 :transition-leave-timeout 500} (if-not (nil? task) (cancel-btn task))] [anim/css-transition-group {:transition-name "action-btn" :transition-enter-timeout 500 :transition-leave-timeout 500} (if (nil? task) (action-btns file))]] [:div {:class (str "video-stream-detail" (if (:more-detail file) " detail-active")) :on-click #(.stopPropagation %)} (for [stream (:streams file)] ^{:key stream} [stream-item stream])] (when-not (nil? (:convert-mode file)) [convert-dialog file])]]))
22c3da88a21224d58a4805f51b0666e8eb1bfd534df66d6fd3077759a2937897
erlyvideo/publisher
wav.erl
@author < > [ ] 2010 %%% @doc WAV (un)packing module %%% Read / for description of header @reference See < a href=" " target="_top"></a > for more information %%% @end %%% %%% This file is part of erlmedia. %%% %%% erlmedia 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. %%% %%% erlmedia 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 erlmedia. If not, see </>. %%% %%%--------------------------------------------------------------------------------------- -module(wav). -author('Max Lapshin <>'). -include("log.hrl"). -include("../include/wav.hrl"). -export([header_size/0, read_header/1, write_header/1, write_header/3]). header_size() -> 44. read_header(<<"RIFF", _TotalSize:32/little, "WAVE", "fmt ", 16:32/little, AudioFormat:16/little, Channels:16/little, Rate:32/little, _ByteRate:32/little, _BlockAlign:16/little, BitsPerSample:16/little, "data", _Sub2Size:32/little>>) -> #wav_header{audio = AudioFormat, channels = Channels, rate = Rate, bps = BitsPerSample}. audio_format(pcm_le) -> ?WAV_PCM_LE; audio_format(pcma) -> ?WAV_PCMA; audio_format(pcmu) -> ?WAV_PCMU; audio_format(Format) when is_integer(Format) -> Format. bps(pcm_le) -> 16; bps(pcma) -> 8; bps(pcmu) -> 8. write_header(AudioFormat, Channels, Rate) -> write_header(#wav_header{audio = AudioFormat, channels = Channels, rate = Rate, bps = bps(AudioFormat)}). write_header(#wav_header{audio = AudioFormat, channels = Channels, rate = Rate, bps = BitsPerSample}) -> Format = audio_format(AudioFormat), BlockAlign = BitsPerSample div 8, ByteRate = BlockAlign * Rate, DataSize = 0, TotalSize = DataSize + 36, <<"RIFF", TotalSize:32/little, "WAVE", "fmt ", 16:32/little, Format:16/little, Channels:16/little, Rate:32/little, ByteRate:32/little, BlockAlign:16/little, BitsPerSample:16/little, "data", DataSize:32/little>>.
null
https://raw.githubusercontent.com/erlyvideo/publisher/5bb2dfa6477c46160dc5fafcc030fc3f5340ec80/apps/erlmedia/src/wav.erl
erlang
@doc WAV (un)packing module Read / for description of header @end This file is part of erlmedia. erlmedia is free software: you can redistribute it and/or modify (at your option) any later version. erlmedia 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 erlmedia. If not, see </>. ---------------------------------------------------------------------------------------
@author < > [ ] 2010 @reference See < a href=" " target="_top"></a > for more information 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 -module(wav). -author('Max Lapshin <>'). -include("log.hrl"). -include("../include/wav.hrl"). -export([header_size/0, read_header/1, write_header/1, write_header/3]). header_size() -> 44. read_header(<<"RIFF", _TotalSize:32/little, "WAVE", "fmt ", 16:32/little, AudioFormat:16/little, Channels:16/little, Rate:32/little, _ByteRate:32/little, _BlockAlign:16/little, BitsPerSample:16/little, "data", _Sub2Size:32/little>>) -> #wav_header{audio = AudioFormat, channels = Channels, rate = Rate, bps = BitsPerSample}. audio_format(pcm_le) -> ?WAV_PCM_LE; audio_format(pcma) -> ?WAV_PCMA; audio_format(pcmu) -> ?WAV_PCMU; audio_format(Format) when is_integer(Format) -> Format. bps(pcm_le) -> 16; bps(pcma) -> 8; bps(pcmu) -> 8. write_header(AudioFormat, Channels, Rate) -> write_header(#wav_header{audio = AudioFormat, channels = Channels, rate = Rate, bps = bps(AudioFormat)}). write_header(#wav_header{audio = AudioFormat, channels = Channels, rate = Rate, bps = BitsPerSample}) -> Format = audio_format(AudioFormat), BlockAlign = BitsPerSample div 8, ByteRate = BlockAlign * Rate, DataSize = 0, TotalSize = DataSize + 36, <<"RIFF", TotalSize:32/little, "WAVE", "fmt ", 16:32/little, Format:16/little, Channels:16/little, Rate:32/little, ByteRate:32/little, BlockAlign:16/little, BitsPerSample:16/little, "data", DataSize:32/little>>.
636d8d5551ea8f578c00c5b8a3348e7dad34838fd4daa87da77215bc88090d15
elastic/eui-cljs
in_memory_table.cljs
(ns eui.in-memory-table (:require ["@elastic/eui/lib/components/basic_table/in_memory_table.js" :as eui])) (def EuiInMemoryTable eui/EuiInMemoryTable)
null
https://raw.githubusercontent.com/elastic/eui-cljs/ad60b57470a2eb8db9bca050e02f52dd964d9f8e/src/eui/in_memory_table.cljs
clojure
(ns eui.in-memory-table (:require ["@elastic/eui/lib/components/basic_table/in_memory_table.js" :as eui])) (def EuiInMemoryTable eui/EuiInMemoryTable)
0a1447ba97eba893d3f557514a6fb716a3ad50f69de2df2bd8900c8e8a9c3475
happi/theBeamBook
stack_machine_compiler.erl
-module(stack_machine_compiler). -export([compile/2]). compile(Expression, FileName) -> [ParseTree] = element(2, erl_parse:parse_exprs( element(2, erl_scan:string(Expression)))), file:write_file(FileName, generate_code(ParseTree) ++ [stop()]). generate_code({op, _Line, '+', Arg1, Arg2}) -> generate_code(Arg1) ++ generate_code(Arg2) ++ [add()]; generate_code({op, _Line, '*', Arg1, Arg2}) -> generate_code(Arg1) ++ generate_code(Arg2) ++ [multiply()]; generate_code({integer, _Line, I}) -> [push(), integer(I)]. stop() -> 0. add() -> 1. multiply() -> 2. push() -> 3. integer(I) -> L = binary_to_list(binary:encode_unsigned(I)), [length(L) | L].
null
https://raw.githubusercontent.com/happi/theBeamBook/3971e8e2d09e3676702a2a5fa8c494f1f803d555/code/beam_chapter/src/stack_machine_compiler.erl
erlang
-module(stack_machine_compiler). -export([compile/2]). compile(Expression, FileName) -> [ParseTree] = element(2, erl_parse:parse_exprs( element(2, erl_scan:string(Expression)))), file:write_file(FileName, generate_code(ParseTree) ++ [stop()]). generate_code({op, _Line, '+', Arg1, Arg2}) -> generate_code(Arg1) ++ generate_code(Arg2) ++ [add()]; generate_code({op, _Line, '*', Arg1, Arg2}) -> generate_code(Arg1) ++ generate_code(Arg2) ++ [multiply()]; generate_code({integer, _Line, I}) -> [push(), integer(I)]. stop() -> 0. add() -> 1. multiply() -> 2. push() -> 3. integer(I) -> L = binary_to_list(binary:encode_unsigned(I)), [length(L) | L].
e2c0efeed86c4f16623c642ccfb82cf4b409f3007f2b9b82be63c39b2f8c0a44
LPCIC/matita
notationUtil.mli
Copyright ( C ) 2004 - 2005 , HELM Team . * * This file is part of HELM , an Hypertextual , Electronic * Library of Mathematics , developed at the Computer Science * Department , University of Bologna , Italy . * * 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 . * * 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 HELM ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , * MA 02111 - 1307 , USA . * * For details , see the HELM World - Wide - Web page , * / * * This file is part of HELM, an Hypertextual, Electronic * Library of Mathematics, developed at the Computer Science * Department, University of Bologna, Italy. * * HELM 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. * * HELM 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 HELM; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, * MA 02111-1307, USA. * * For details, see the HELM World-Wide-Web page, * / *) val fresh_name: unit -> string val variables_of_term: NotationPt.term -> NotationPt.pattern_variable list val names_of_term: NotationPt.term -> string list * extract all keywords ( i.e. string literals ) from a level 1 pattern val keywords_of_term: NotationPt.term -> string list val visit_ast: ?special_k:(NotationPt.term -> NotationPt.term) -> ?map_xref_option:(NotationPt.href option -> NotationPt.href option) -> ?map_case_indty:(NotationPt.case_indtype option -> NotationPt.case_indtype option) -> ?map_case_outtype:((NotationPt.term -> NotationPt.term) -> NotationPt.term option -> NotationPt.term option) -> (NotationPt.term -> NotationPt.term) -> NotationPt.term -> NotationPt.term val visit_layout: (NotationPt.term -> NotationPt.term) -> NotationPt.layout_pattern -> NotationPt.layout_pattern val visit_magic: (NotationPt.term -> NotationPt.term) -> NotationPt.magic_term -> NotationPt.magic_term val visit_variable: (NotationPt.term -> NotationPt.term) -> NotationPt.pattern_variable -> NotationPt.pattern_variable val strip_attributes: NotationPt.term -> NotationPt.term (** @return the list of proper (i.e. non recursive) IdRef of a term *) val get_idrefs: NotationPt.term -> string list (** generalization of List.combine to n lists *) val ncombine: 'a list list -> 'a list list val string_of_literal: NotationPt.literal -> string val dress: sep:'a -> 'a list -> 'a list val dressn: sep:'a list -> 'a list -> 'a list val boxify: NotationPt.term list -> NotationPt.term val group: NotationPt.term list -> NotationPt.term val ungroup: NotationPt.term list -> NotationPt.term list val find_appl_pattern_uris: NotationPt.cic_appl_pattern -> NReference.reference list val find_branch: NotationPt.term -> NotationPt.term (** Symbol/Numbers instances *) val freshen_term: NotationPt.term -> NotationPt.term val freshen_obj: NotationPt.term NotationPt.obj -> NotationPt.term NotationPt.obj (** Notation id handling *) type notation_id val fresh_id: unit -> notation_id val refresh_uri_in_term: refresh_uri_in_term:(NCic.term -> NCic.term) -> refresh_uri_in_reference:(NReference.reference -> NReference.reference) -> NotationPt.term -> NotationPt.term
null
https://raw.githubusercontent.com/LPCIC/matita/794ed25e6e608b2136ce7fa2963bca4115c7e175/matita/components/content/notationUtil.mli
ocaml
* @return the list of proper (i.e. non recursive) IdRef of a term * generalization of List.combine to n lists * Symbol/Numbers instances * Notation id handling
Copyright ( C ) 2004 - 2005 , HELM Team . * * This file is part of HELM , an Hypertextual , Electronic * Library of Mathematics , developed at the Computer Science * Department , University of Bologna , Italy . * * 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 . * * 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 HELM ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , * MA 02111 - 1307 , USA . * * For details , see the HELM World - Wide - Web page , * / * * This file is part of HELM, an Hypertextual, Electronic * Library of Mathematics, developed at the Computer Science * Department, University of Bologna, Italy. * * HELM 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. * * HELM 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 HELM; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, * MA 02111-1307, USA. * * For details, see the HELM World-Wide-Web page, * / *) val fresh_name: unit -> string val variables_of_term: NotationPt.term -> NotationPt.pattern_variable list val names_of_term: NotationPt.term -> string list * extract all keywords ( i.e. string literals ) from a level 1 pattern val keywords_of_term: NotationPt.term -> string list val visit_ast: ?special_k:(NotationPt.term -> NotationPt.term) -> ?map_xref_option:(NotationPt.href option -> NotationPt.href option) -> ?map_case_indty:(NotationPt.case_indtype option -> NotationPt.case_indtype option) -> ?map_case_outtype:((NotationPt.term -> NotationPt.term) -> NotationPt.term option -> NotationPt.term option) -> (NotationPt.term -> NotationPt.term) -> NotationPt.term -> NotationPt.term val visit_layout: (NotationPt.term -> NotationPt.term) -> NotationPt.layout_pattern -> NotationPt.layout_pattern val visit_magic: (NotationPt.term -> NotationPt.term) -> NotationPt.magic_term -> NotationPt.magic_term val visit_variable: (NotationPt.term -> NotationPt.term) -> NotationPt.pattern_variable -> NotationPt.pattern_variable val strip_attributes: NotationPt.term -> NotationPt.term val get_idrefs: NotationPt.term -> string list val ncombine: 'a list list -> 'a list list val string_of_literal: NotationPt.literal -> string val dress: sep:'a -> 'a list -> 'a list val dressn: sep:'a list -> 'a list -> 'a list val boxify: NotationPt.term list -> NotationPt.term val group: NotationPt.term list -> NotationPt.term val ungroup: NotationPt.term list -> NotationPt.term list val find_appl_pattern_uris: NotationPt.cic_appl_pattern -> NReference.reference list val find_branch: NotationPt.term -> NotationPt.term val freshen_term: NotationPt.term -> NotationPt.term val freshen_obj: NotationPt.term NotationPt.obj -> NotationPt.term NotationPt.obj type notation_id val fresh_id: unit -> notation_id val refresh_uri_in_term: refresh_uri_in_term:(NCic.term -> NCic.term) -> refresh_uri_in_reference:(NReference.reference -> NReference.reference) -> NotationPt.term -> NotationPt.term
aa4da5729e1a806ff55bc5518d17f78985a555ee87847d295f337acb398710e1
jyp/nano-Agda
TestSyntax.hs
# LANGUAGE QuasiQuotes , TemplateHaskell # module TestSyntax where import Language.LBNF dumpCode [lbnf| ESigma. Exp ::= "×" ; |] test = tokens "×"
null
https://raw.githubusercontent.com/jyp/nano-Agda/2003fa50db6c8e5647594f69cdda61b76f4ecf3f/TestSyntax.hs
haskell
# LANGUAGE QuasiQuotes , TemplateHaskell # module TestSyntax where import Language.LBNF dumpCode [lbnf| ESigma. Exp ::= "×" ; |] test = tokens "×"
bdf8a7491c1f9f0b5eec8e303b2eacf0771f0601438b134922207207cb56c08a
d-cent/objective8
facebook.clj
(ns objective8.front-end.workflows.facebook (:require [ring.util.response :as response] [objective8.utils :as utils] [objective8.front-end.api.http :as http] [cheshire.core :as json] [bidi.ring :refer [make-handler]] [objective8.front-end.front-end-requests :as front-end] [clojure.tools.logging :as log])) (def redirect-uri (str utils/host-url "/facebook-callback")) (def error-redirect (response/redirect (str utils/host-url "/error/log-in"))) (defn facebook-sign-in [{:keys [facebook-config] :as request}] (let [client-id (:client-id facebook-config)] (response/redirect (str "=" client-id "&redirect_uri=" redirect-uri "&scope=public_profile,email")))) (defn response->json [response] (json/parse-string (:body response) true)) (defn token-info-valid? [token-info facebook-config] (let [expires-at (:expires_at token-info) app-id (:app_id token-info) client-id (:client-id facebook-config)] (and (= app-id client-id) (> expires-at (utils/unix-current-time))))) (defn get-token-info [access-token facebook-config] (let [client-id (:client-id facebook-config) client-secret (:client-secret facebook-config)] (http/get-request "" {:query-params {:input_token access-token :access_token (str client-id "|" client-secret)}}))) (defn get-access-token [{:keys [params facebook-config] :as request}] (let [code (:code params) client-id (:client-id facebook-config) client-secret (:client-secret facebook-config)] (http/get-request "" {:query-params {:client_id client-id :redirect_uri redirect-uri :client_secret client-secret :code code}}))) (defn get-user-email [user-id] (http/get-request (str "/" user-id "/?fields=email"))) (defn check-fb-email [{:keys [session] :as request} user-id] (let [fb-user-id (str "facebook-" user-id) user-email-response (get-user-email user-id) user-email-body (response->json user-email-response) fb-user-email (:email user-email-body) session-with-auth-id {:session (assoc session :auth-provider-user-id fb-user-id)} redirect (into (response/redirect (str utils/host-url "/sign-up")) session-with-auth-id)] (if (front-end/valid-not-empty-email? fb-user-email) (into redirect (assoc-in session-with-auth-id [:session :auth-provider-user-email] fb-user-email)) (do (log/error (str "Facebook email error: " (get-in user-email-body [:error :message]) " with status code " (:status user-email-response))) (into redirect {:flash {:validation :auth-email}}))))) (defn check-token-info [{:keys [facebook-config] :as request} access-token] (let [token-info-response (get-token-info access-token facebook-config) token-info-body (response->json token-info-response) token-info-data (:data token-info-body) user-id (:user_id token-info-data)] (if (token-info-valid? token-info-data facebook-config) (check-fb-email request user-id) (do (log/error (str "Facebook token info error: " (get-in token-info-body [:error :message]) " with status code " (:status token-info-response))) error-redirect)))) (defn check-access-token [request] (let [access-token-response (get-access-token request) access-token-body (response->json access-token-response)] (if (:error access-token-body) (do (log/error (str "Facebook access token error: " (:error access-token-body) " with status code " (:status access-token-response))) error-redirect) (check-token-info request (:access_token access-token-body))))) (defn facebook-callback [{:keys [params] :as request}] (cond (= (:error params) "access_denied") (do (log/error (str "Facebook callback error: access_denied, " (:error_description params))) (response/redirect utils/host-url)) (:error params) (do (log/error (str "Facebook callback error: " (:error params) ", " (:error_description params))) error-redirect) :default (check-access-token request))) (def facebook-routes ["/" {"facebook-sign-in" :sign-in "facebook-callback" :callback}]) (defn wrap-handler [handler facebook-config] (fn [request] (handler (assoc request :facebook-config facebook-config)))) (defn facebook-handlers [facebook-config] {:sign-in (wrap-handler facebook-sign-in facebook-config) :callback (wrap-handler facebook-callback facebook-config)}) (defn facebook-workflow [facebook-config] (make-handler facebook-routes (facebook-handlers facebook-config)))
null
https://raw.githubusercontent.com/d-cent/objective8/db8344ba4425ca0b38a31c99a3b282d7c8ddaef0/src/objective8/front_end/workflows/facebook.clj
clojure
(ns objective8.front-end.workflows.facebook (:require [ring.util.response :as response] [objective8.utils :as utils] [objective8.front-end.api.http :as http] [cheshire.core :as json] [bidi.ring :refer [make-handler]] [objective8.front-end.front-end-requests :as front-end] [clojure.tools.logging :as log])) (def redirect-uri (str utils/host-url "/facebook-callback")) (def error-redirect (response/redirect (str utils/host-url "/error/log-in"))) (defn facebook-sign-in [{:keys [facebook-config] :as request}] (let [client-id (:client-id facebook-config)] (response/redirect (str "=" client-id "&redirect_uri=" redirect-uri "&scope=public_profile,email")))) (defn response->json [response] (json/parse-string (:body response) true)) (defn token-info-valid? [token-info facebook-config] (let [expires-at (:expires_at token-info) app-id (:app_id token-info) client-id (:client-id facebook-config)] (and (= app-id client-id) (> expires-at (utils/unix-current-time))))) (defn get-token-info [access-token facebook-config] (let [client-id (:client-id facebook-config) client-secret (:client-secret facebook-config)] (http/get-request "" {:query-params {:input_token access-token :access_token (str client-id "|" client-secret)}}))) (defn get-access-token [{:keys [params facebook-config] :as request}] (let [code (:code params) client-id (:client-id facebook-config) client-secret (:client-secret facebook-config)] (http/get-request "" {:query-params {:client_id client-id :redirect_uri redirect-uri :client_secret client-secret :code code}}))) (defn get-user-email [user-id] (http/get-request (str "/" user-id "/?fields=email"))) (defn check-fb-email [{:keys [session] :as request} user-id] (let [fb-user-id (str "facebook-" user-id) user-email-response (get-user-email user-id) user-email-body (response->json user-email-response) fb-user-email (:email user-email-body) session-with-auth-id {:session (assoc session :auth-provider-user-id fb-user-id)} redirect (into (response/redirect (str utils/host-url "/sign-up")) session-with-auth-id)] (if (front-end/valid-not-empty-email? fb-user-email) (into redirect (assoc-in session-with-auth-id [:session :auth-provider-user-email] fb-user-email)) (do (log/error (str "Facebook email error: " (get-in user-email-body [:error :message]) " with status code " (:status user-email-response))) (into redirect {:flash {:validation :auth-email}}))))) (defn check-token-info [{:keys [facebook-config] :as request} access-token] (let [token-info-response (get-token-info access-token facebook-config) token-info-body (response->json token-info-response) token-info-data (:data token-info-body) user-id (:user_id token-info-data)] (if (token-info-valid? token-info-data facebook-config) (check-fb-email request user-id) (do (log/error (str "Facebook token info error: " (get-in token-info-body [:error :message]) " with status code " (:status token-info-response))) error-redirect)))) (defn check-access-token [request] (let [access-token-response (get-access-token request) access-token-body (response->json access-token-response)] (if (:error access-token-body) (do (log/error (str "Facebook access token error: " (:error access-token-body) " with status code " (:status access-token-response))) error-redirect) (check-token-info request (:access_token access-token-body))))) (defn facebook-callback [{:keys [params] :as request}] (cond (= (:error params) "access_denied") (do (log/error (str "Facebook callback error: access_denied, " (:error_description params))) (response/redirect utils/host-url)) (:error params) (do (log/error (str "Facebook callback error: " (:error params) ", " (:error_description params))) error-redirect) :default (check-access-token request))) (def facebook-routes ["/" {"facebook-sign-in" :sign-in "facebook-callback" :callback}]) (defn wrap-handler [handler facebook-config] (fn [request] (handler (assoc request :facebook-config facebook-config)))) (defn facebook-handlers [facebook-config] {:sign-in (wrap-handler facebook-sign-in facebook-config) :callback (wrap-handler facebook-callback facebook-config)}) (defn facebook-workflow [facebook-config] (make-handler facebook-routes (facebook-handlers facebook-config)))
ee5a17a8bb56a4e1a98154611910bf67c12964ce0f67226ad9f5c9b7e645443b
roburio/caldav
rfc1123.ml
---------------------------------------------------------------------------- Copyright ( c ) 2015 Inhabited Type LLC . All rights reserved . Redistribution and use in source and binary forms , with or without modification , are permitted provided that the following conditions are met : 1 . Redistributions of source code must retain the above copyright notice , this list of conditions and the following disclaimer . 2 . 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 . 3 . Neither the name of the author nor the names of his contributors may be used to endorse or promote products derived from this software without specific prior written permission . THIS SOFTWARE IS PROVIDED BY THE 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 AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE , EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE . ---------------------------------------------------------------------------- Copyright (c) 2015 Inhabited Type LLC. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. 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. 3. Neither the name of the author nor the names of his contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE 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 AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ----------------------------------------------------------------------------*) let parse_date_exn s = try Scanf.sscanf s "%3s, %d %s %4d %d:%d:%d %s" ( fun _wday mday mon year hour min sec tz -> let months = [ "Jan", 1; "Feb", 2; "Mar", 3; "Apr", 4; "May", 5; "Jun", 6; "Jul", 7; "Aug", 8; "Sep", 9; "Oct", 10; "Nov", 11; "Dec", 12 ] in let parse_tz = function | "" | "Z" | "GMT" | "UTC" | "UT" -> 0 | "PST" -> -480 | "MST" | "PDT" -> -420 | "CST" | "MDT" -> -360 | "EST" | "CDT" -> -300 | "EDT" -> -240 | s -> Scanf.sscanf s "%c%02d%_[:]%02d" (fun sign hour min -> min + hour * (if sign = '-' then -60 else 60)) in let mon = List.assoc mon months in let year = if year < 50 then year + 2000 else if year < 1000 then year + 1900 else year in let date = (year, mon, mday) in let time = ((hour, min, sec), (parse_tz tz)*60) in let ptime = Ptime.of_date_time (date, time) in match ptime with | None -> raise (Invalid_argument "Invalid date string") | Some date -> match Ptime.(Span.to_int_s (to_span date)) with | None -> raise (Invalid_argument "Invalid date string") | Some t -> t ) with | Scanf.Scan_failure e -> raise (Invalid_argument e) | Not_found -> raise (Invalid_argument "Invalid date string") let parse_date s = try (Some (parse_date_exn s)) with | Invalid_argument _ -> None
null
https://raw.githubusercontent.com/roburio/caldav/60d4aeec2711f7c6fdc76e1096288a1c453e9f2f/ocaml-webmachine/lib/rfc1123.ml
ocaml
---------------------------------------------------------------------------- Copyright ( c ) 2015 Inhabited Type LLC . All rights reserved . Redistribution and use in source and binary forms , with or without modification , are permitted provided that the following conditions are met : 1 . Redistributions of source code must retain the above copyright notice , this list of conditions and the following disclaimer . 2 . 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 . 3 . Neither the name of the author nor the names of his contributors may be used to endorse or promote products derived from this software without specific prior written permission . THIS SOFTWARE IS PROVIDED BY THE 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 AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE , EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE . ---------------------------------------------------------------------------- Copyright (c) 2015 Inhabited Type LLC. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. 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. 3. Neither the name of the author nor the names of his contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE 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 AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ----------------------------------------------------------------------------*) let parse_date_exn s = try Scanf.sscanf s "%3s, %d %s %4d %d:%d:%d %s" ( fun _wday mday mon year hour min sec tz -> let months = [ "Jan", 1; "Feb", 2; "Mar", 3; "Apr", 4; "May", 5; "Jun", 6; "Jul", 7; "Aug", 8; "Sep", 9; "Oct", 10; "Nov", 11; "Dec", 12 ] in let parse_tz = function | "" | "Z" | "GMT" | "UTC" | "UT" -> 0 | "PST" -> -480 | "MST" | "PDT" -> -420 | "CST" | "MDT" -> -360 | "EST" | "CDT" -> -300 | "EDT" -> -240 | s -> Scanf.sscanf s "%c%02d%_[:]%02d" (fun sign hour min -> min + hour * (if sign = '-' then -60 else 60)) in let mon = List.assoc mon months in let year = if year < 50 then year + 2000 else if year < 1000 then year + 1900 else year in let date = (year, mon, mday) in let time = ((hour, min, sec), (parse_tz tz)*60) in let ptime = Ptime.of_date_time (date, time) in match ptime with | None -> raise (Invalid_argument "Invalid date string") | Some date -> match Ptime.(Span.to_int_s (to_span date)) with | None -> raise (Invalid_argument "Invalid date string") | Some t -> t ) with | Scanf.Scan_failure e -> raise (Invalid_argument e) | Not_found -> raise (Invalid_argument "Invalid date string") let parse_date s = try (Some (parse_date_exn s)) with | Invalid_argument _ -> None
64f9f0c6aba678bf217db23d8a9ccc34725c65abfddce6975347568db7248359
CarlosMChica/HaskellBook
AsyncExceptions.hs
module AsyncExceptions where import Control.Concurrent (forkIO, threadDelay) import Control.Exception import System.IO openAndWrite :: IO () openAndWrite = do h <- openFile "test.dat" WriteMode threadDelay 1500 hPutStr h (replicate 100000000 '0' ++ "abc") hClose h data PleaseDie = PleaseDie deriving Show instance Exception PleaseDie main = do threadId <- forkIO openAndWrite threadDelay 1000 throwTo threadId PleaseDie openAndWrite' :: IO () openAndWrite' = do h <- openFile "test.dat" AppendMode threadDelay 1500 hPutStr h (replicate 100000000 '0' ++ "abc") hClose h main' = do threadId <- forkIO (mask_ openAndWrite) threadDelay 1000 throwTo threadId PleaseDie -- Exception ends up blowing up in main because by the time it reaches throwTo the child thread has finished
null
https://raw.githubusercontent.com/CarlosMChica/HaskellBook/86f82cf36cd00003b1a1aebf264e4b5d606ddfad/chapter30/AsyncExceptions.hs
haskell
Exception ends up blowing up in main because by the time it reaches throwTo the child thread has finished
module AsyncExceptions where import Control.Concurrent (forkIO, threadDelay) import Control.Exception import System.IO openAndWrite :: IO () openAndWrite = do h <- openFile "test.dat" WriteMode threadDelay 1500 hPutStr h (replicate 100000000 '0' ++ "abc") hClose h data PleaseDie = PleaseDie deriving Show instance Exception PleaseDie main = do threadId <- forkIO openAndWrite threadDelay 1000 throwTo threadId PleaseDie openAndWrite' :: IO () openAndWrite' = do h <- openFile "test.dat" AppendMode threadDelay 1500 hPutStr h (replicate 100000000 '0' ++ "abc") hClose h main' = do threadId <- forkIO (mask_ openAndWrite) threadDelay 1000 throwTo threadId PleaseDie
fee5de30b203a49465b44d8f835740c3a502eb584337a64685cde72e09e22286
csabahruska/jhc-components
Array.hs
# OPTIONS_JHC -funboxed - tuples # module Data.Array ( module Data.Ix, -- export all of Ix Array(), array, listArray, accumArray, (!), bounds, indices, elems, assocs, (//), accum, ixmap ) where import Data.Ix import Jhc.Int import Jhc.Prim.Array import Jhc.Prim.IO infixl 9 !, // data Array a b = MkArray !a !a (Array_ b) array :: (Ix a) => (a,a) -> [(a,b)] -> Array a b array b@(s,e) ivs = case newArray (error "array: missing element") (rangeSize b) [(index b x,y) | (x,y) <- ivs] of arr -> MkArray s e arr listArray :: (Ix a) => (a,a) -> [b] -> Array a b listArray b vs = array b (zipWith (\ a b -> (a,b)) (range b) vs) (!) :: (Ix a) => Array a b -> a -> b (!) (MkArray s e arr) i = case unboxInt (index (s,e) i) of i' -> case indexArray__ arr i' of (# r #) -> r bounds :: (Ix a) => Array a b -> (a,a) bounds (MkArray s e _) = (s,e) indices :: (Ix a) => Array a b -> [a] indices = range . bounds elems :: (Ix a) => Array a b -> [b] elems a = [a!i | i <- indices a] assocs :: (Ix a) => Array a b -> [(a,b)] assocs a = [(i, a!i) | i <- indices a] (//) :: (Ix a) => Array a b -> [(a,b)] -> Array a b a // [] = a a // new_ivs = array (bounds a) (old_ivs ++ new_ivs) where old_ivs = [(i,a!i) | i <- indices a, i `notElem` new_is] new_is = [i | (i,_) <- new_ivs] accum :: (Ix a) => (b -> c -> b) -> Array a b -> [(a,c)] -> Array a b accum f = foldl (\a (i,v) -> a // [(i,f (a!i) v)]) accumArray :: (Ix a) => (b -> c -> b) -> b -> (a,a) -> [(a,c)] -> Array a b accumArray f z b = accum f (array b [(i,z) | i <- range b]) ixmap :: (Ix a, Ix b) => (a,a) -> (a -> b) -> Array b c -> Array a c ixmap b f a = array b [(i, a ! f i) | i <- range b] instance (Ix a) => Functor (Array a) where fmap fn a = array (bounds a) [ (a,fn b) | (a,b) <- assocs a ] instance (Ix a, Eq b) => Eq (Array a b) where a == a' = assocs a == assocs a' instance (Ix a, Ord b) => Ord (Array a b) where a <= a' = assocs a <= assocs a' instance (Ix a, Show a, Show b) => Show (Array a b) where showsPrec p a = showParen (p > arrPrec) ( showString "array " . showsPrec (arrPrec+1) (bounds a) . showChar ' ' . showsPrec (arrPrec+1) (assocs a) ) instance (Ix a, Read a, Read b) => Read (Array a b) where readsPrec p = readParen (p > arrPrec) (\r -> [ (array b as, u) | ("array",s) <- lex r, (b,t) <- readsPrec (arrPrec+1) s, (as,u) <- readsPrec (arrPrec+1) t ]) -- Precedence of the 'array' function is that of application itself arrPrec :: Int arrPrec = 10 foreign import primitive newWorld__ :: a -> World__ newArray :: a -> Int -> [(Int,a)] -> Array_ a newArray init n xs = case unboxInt n of n' -> case newWorld__ (init,n,xs) of w -> case newArray__ n' init w of (# w, arr #) -> let f :: MutArray_ a -> World__ -> [(Int,a)] -> World__ f arr w [] = w f arr w ((i,v):xs) = case unboxInt i of i' -> case writeArray__ arr i' v w of w -> f arr w xs in case f arr w xs of w -> Array_ arr `worldDep_` w foreign import primitive "dependingOn" worldDep_ :: Array_ b -> World__ -> Array_ b
null
https://raw.githubusercontent.com/csabahruska/jhc-components/a7dace481d017f5a83fbfc062bdd2d099133adf1/lib/haskell-extras/Data/Array.hs
haskell
export all of Ix Precedence of the 'array' function is that of application itself
# OPTIONS_JHC -funboxed - tuples # module Data.Array ( Array(), array, listArray, accumArray, (!), bounds, indices, elems, assocs, (//), accum, ixmap ) where import Data.Ix import Jhc.Int import Jhc.Prim.Array import Jhc.Prim.IO infixl 9 !, // data Array a b = MkArray !a !a (Array_ b) array :: (Ix a) => (a,a) -> [(a,b)] -> Array a b array b@(s,e) ivs = case newArray (error "array: missing element") (rangeSize b) [(index b x,y) | (x,y) <- ivs] of arr -> MkArray s e arr listArray :: (Ix a) => (a,a) -> [b] -> Array a b listArray b vs = array b (zipWith (\ a b -> (a,b)) (range b) vs) (!) :: (Ix a) => Array a b -> a -> b (!) (MkArray s e arr) i = case unboxInt (index (s,e) i) of i' -> case indexArray__ arr i' of (# r #) -> r bounds :: (Ix a) => Array a b -> (a,a) bounds (MkArray s e _) = (s,e) indices :: (Ix a) => Array a b -> [a] indices = range . bounds elems :: (Ix a) => Array a b -> [b] elems a = [a!i | i <- indices a] assocs :: (Ix a) => Array a b -> [(a,b)] assocs a = [(i, a!i) | i <- indices a] (//) :: (Ix a) => Array a b -> [(a,b)] -> Array a b a // [] = a a // new_ivs = array (bounds a) (old_ivs ++ new_ivs) where old_ivs = [(i,a!i) | i <- indices a, i `notElem` new_is] new_is = [i | (i,_) <- new_ivs] accum :: (Ix a) => (b -> c -> b) -> Array a b -> [(a,c)] -> Array a b accum f = foldl (\a (i,v) -> a // [(i,f (a!i) v)]) accumArray :: (Ix a) => (b -> c -> b) -> b -> (a,a) -> [(a,c)] -> Array a b accumArray f z b = accum f (array b [(i,z) | i <- range b]) ixmap :: (Ix a, Ix b) => (a,a) -> (a -> b) -> Array b c -> Array a c ixmap b f a = array b [(i, a ! f i) | i <- range b] instance (Ix a) => Functor (Array a) where fmap fn a = array (bounds a) [ (a,fn b) | (a,b) <- assocs a ] instance (Ix a, Eq b) => Eq (Array a b) where a == a' = assocs a == assocs a' instance (Ix a, Ord b) => Ord (Array a b) where a <= a' = assocs a <= assocs a' instance (Ix a, Show a, Show b) => Show (Array a b) where showsPrec p a = showParen (p > arrPrec) ( showString "array " . showsPrec (arrPrec+1) (bounds a) . showChar ' ' . showsPrec (arrPrec+1) (assocs a) ) instance (Ix a, Read a, Read b) => Read (Array a b) where readsPrec p = readParen (p > arrPrec) (\r -> [ (array b as, u) | ("array",s) <- lex r, (b,t) <- readsPrec (arrPrec+1) s, (as,u) <- readsPrec (arrPrec+1) t ]) arrPrec :: Int arrPrec = 10 foreign import primitive newWorld__ :: a -> World__ newArray :: a -> Int -> [(Int,a)] -> Array_ a newArray init n xs = case unboxInt n of n' -> case newWorld__ (init,n,xs) of w -> case newArray__ n' init w of (# w, arr #) -> let f :: MutArray_ a -> World__ -> [(Int,a)] -> World__ f arr w [] = w f arr w ((i,v):xs) = case unboxInt i of i' -> case writeArray__ arr i' v w of w -> f arr w xs in case f arr w xs of w -> Array_ arr `worldDep_` w foreign import primitive "dependingOn" worldDep_ :: Array_ b -> World__ -> Array_ b
8ca56db15ebb63a4d4f0584f5751895d74aa3d4da403b946a09bcaadde48d8c9
jakemcc/sicp-study
ex4_28.clj
exercise 4.28 (ns ex4-48 (:use section4)) (interpret '(define (p f x y z) (f x y z))) (interpret (define (sum x y z) (+ x y z))) (interpret (p sum 1 2 3)) ; The above works. ; We need to get the actual value because otherwise when ; p is passed f to evaulaute it would be evaluating a thunk ; and not a function. Hence need to use the book version which ; uses actual-value and not eval.
null
https://raw.githubusercontent.com/jakemcc/sicp-study/3b9e3d6c8cc30ad92b0d9bbcbbbfe36a8413f89d/clojure/section4.2/src/ex4_28.clj
clojure
The above works. We need to get the actual value because otherwise when p is passed f to evaulaute it would be evaluating a thunk and not a function. Hence need to use the book version which uses actual-value and not eval.
exercise 4.28 (ns ex4-48 (:use section4)) (interpret '(define (p f x y z) (f x y z))) (interpret (define (sum x y z) (+ x y z))) (interpret (p sum 1 2 3))
44a7f37e7c41e7564850eb6ce05731ee56147c1e030f10d10e801119bed4c61e
discoproject/disco
jc_utils.erl
-module(jc_utils). -include("common_types.hrl"). -include("disco.hrl"). -include("pipeline.hrl"). -include("job_coordinator.hrl"). % This constant control the number of tasks that can be started from the % following concurrent stages. The lower this value, the higher the degree of concurrency , but the higher the potential for job deadlock . The constant 1 is % the minimum value that guarantees there will be no deadlock if the number of % workers does not decrease. -define(MIN_RATION_OF_FIRST_ACTIVE_TO_REST, 2). -export([stage_info_opt/2, stage_info/2, last_stage_task/2, update_stage/3, update_stage_tasks/4, task_info/2, update_task_info/3, task_spec/2, add_task_spec/3, task_inputs/2, task_outputs/2, input_info/2, update_input_info/3, add_input/3, update_input_failures/2, find_usable_input_hosts/1, collect_stagewise/5, wakeup_waiters/3, no_tasks_running/2, running_tasks/2, can_run_task/4]). -type stage_map() :: disco_gbtree(stage_name(), stage_info()). -type task_map() :: disco_gbtree(task_id(), task_info()). -type input_map() :: disco_gbtree(input_id(), data_info()). % information about a stage which may not have yet run. -spec stage_info_opt(stage_name(), stage_map()) -> none | stage_info(). stage_info_opt(Stage, SI) -> case gb_trees:lookup(Stage, SI) of none -> none; {value, Info} -> Info end. % information about a stage which the caller guarantees exists. -spec stage_info(stage_name(), stage_map()) -> stage_info(). stage_info(Stage, SI) -> gb_trees:get(Stage, SI). -spec update_stage(stage_name(), stage_info(), stage_map()) -> stage_map(). update_stage(Stage, Info, SI) -> gb_trees:enter(Stage, Info, SI). -type task_op() :: run | stop | done. -spec update_stage_tasks(stage_name(), task_id(), task_op(), stage_map()) -> stage_map(). update_stage_tasks(S, Id, Op, SI) -> mod_stage_tasks(S, Id, Op, stage_info(S, SI), SI). mod_stage_tasks(S, Id, Op, #stage_info{running = R, done = D, n_running = NR} = Info, SI) -> {R1, D1, NR1} = case Op of run -> {lists:usort([Id | R]), D, NR + 1}; stop -> {R -- [Id], D, NR - 1}; done -> {R -- [Id], lists:usort([Id | D]), NR - 1} end, update_stage(S, Info#stage_info{running = R1, done = D1, n_running = NR1}, SI). -spec can_run_task(pipeline(), stage_name(), stage_map(), task_schedule()) -> boolean(). can_run_task(P, S, SI, #task_schedule{max_cores = Max}) -> can_run_task(P, S, SI, true, 0, Max). the fifth argument shows whether all of the dependencies have finished so % far. It will determine whether the task can run or not for sequential stages. the sixth argument shows the total number of tasks running in the previous % stages. can_run_task([_|_], ?INPUT, _, _, _, _) -> true; can_run_task(_, _, _, _, NR, Max) when NR >= Max -> false; can_run_task([], _S, _, _, _, _) -> true; can_run_task([{S, _, _}|_], S, SI, true, DepsNRTasks, Max) -> #stage_info{n_running = NR} = jc_utils:stage_info(S, SI), NR + DepsNRTasks < Max; can_run_task([{S, _, false}|_], S, _, false, _, _) -> false; can_run_task([{S, _, true}|_], S, SI, false, DepsNRTasks, Max) -> #stage_info{n_running = NR} = jc_utils:stage_info(S, SI), ?MIN_RATION_OF_FIRST_ACTIVE_TO_REST * NR < DepsNRTasks andalso NR + DepsNRTasks < Max; can_run_task([{DepS,_, _}|Rest], S, SI, DepsFinished, DepsNRTasks, Max) -> #stage_info{finished = Finished, n_running = NR} = jc_utils:stage_info(DepS, SI), case Finished of true -> can_run_task(Rest, S, SI, DepsFinished, DepsNRTasks, Max); false -> can_run_task(Rest, S, SI, false, DepsNRTasks + NR, Max) end. -spec no_tasks_running(stage_name(), stage_map()) -> boolean(). no_tasks_running(S, SI) -> #stage_info{n_running = NR} = stage_info(S, SI), NR == 0. -spec running_tasks(stage_name(), stage_map()) -> [task_id()]. running_tasks(S, SI) -> case stage_info_opt(S, SI) of none -> []; StageInfo -> StageInfo#stage_info.running end. % If this is the last pending task in the stage in order for the stage % to be done. -spec last_stage_task(stage_name(), stage_map()) -> boolean(). last_stage_task(Stage, SI) -> #stage_info{done = Done, all = All} = stage_info(Stage, SI), length(Done) =:= All. -spec is_running(task_id(), task_map(), stage_map()) -> boolean(). is_running(TaskId, Tasks, SI) -> #task_info{spec = #task_spec{taskid = TaskId, stage = Stage}} = task_info(TaskId, Tasks), #stage_info{done = Done} = stage_info(Stage, SI), lists:member(TaskId, Done). -spec is_waiting(task_id(), task_map()) -> boolean(). is_waiting(TaskId, Tasks) -> #task_info{depends = Depends} = task_info(TaskId, Tasks), Depends =/= []. -spec task_info(input | task_id(), task_map()) -> task_info(). task_info(TaskId, Tasks) -> gb_trees:get(TaskId, Tasks). -spec task_spec(input, input_map()) -> input; (task_id(), task_map()) -> task_spec(). task_spec(TaskId, Tasks) -> (task_info(TaskId, Tasks))#task_info.spec. -spec task_outputs(input | task_id(), task_map()) -> [task_output()]. task_outputs(TaskId, Tasks) -> (task_info(TaskId, Tasks))#task_info.outputs. % This should only be called for new tasks. -spec add_task_spec(task_id(), task_spec(), task_map()) -> task_map(). add_task_spec(TaskId, TaskSpec, Tasks) -> gb_trees:enter(TaskId, #task_info{spec = TaskSpec}, Tasks). -spec update_task_info(task_id(), task_info(), task_map()) -> task_map(). update_task_info(TaskId, TInfo, Tasks) -> gb_trees:enter(TaskId, TInfo, Tasks). % Input utilities. -spec add_input(input_id(), data_info(), input_map()) -> input_map(). add_input(InputId, DInfo, DataMap) -> gb_trees:enter(InputId, DInfo, DataMap). -spec input_info(input_id(), input_map()) -> data_info(). input_info(InputId, DataMap) -> gb_trees:get(InputId, DataMap). -spec update_input_info(input_id(), data_info(), input_map()) -> input_map(). update_input_info(InputId, DInfo, DataMap) -> gb_trees:enter(InputId, DInfo, DataMap). -spec task_inputs([input_id()], input_map()) -> [{input_id(), data_input()}]. task_inputs(InputIds, DataMap) -> [{Id, (gb_trees:get(Id, DataMap))#data_info.source} || Id <- InputIds]. % Data utilities. -spec data_inputs(data_info()) -> [data_input()]. data_inputs(#data_info{source = Source, locations = Locations}) -> [Source | gb_trees:values(Locations)]. -spec data_hosts(data_info()) -> [host()]. data_hosts(DInfo) -> lists:usort(lists:flatten([pipeline_utils:locations(DI) || DI <- data_inputs(DInfo)])). -spec update_input_failures([host()], data_info()) -> data_info(). update_input_failures(Hosts, #data_info{failures = Failures} = DInfo) -> F = lists:foldl( fun(H, Fails) -> case gb_trees:lookup(H, Fails) of none -> Fails; {value, Cnt} -> gb_trees:enter(H, Cnt + 1, Fails) end end, Failures, Hosts), DInfo#data_info{failures = F}. -spec find_usable_input_hosts(data_info()) -> [host()]. find_usable_input_hosts(#data_info{failures = Failures}) -> [H || {H, Fails} <- gb_trees:to_list(Failures), Fails < ?MAX_INPUT_FAILURE]. % Input regeneration and task re-run utilities. % Find the inputs that are local to the specified list of hosts. -spec local_inputs([input_id()], disco_gbset(host()), input_map()) -> [input_id()]. local_inputs(InputIds, Hosts, DataMap) -> local_inputs(InputIds, Hosts, DataMap, []). local_inputs([], _Hosts, _DataMap, Acc) -> lists:usort(Acc); local_inputs([Id | Rest], Hosts, DataMap, Acc) -> % An input is local to a set of hosts iff all its replicas are % found only on those hosts. Acc1 = case lists:all(fun(H) -> gb_sets:is_member(H, Hosts) end, data_hosts(input_info(Id, DataMap))) of true -> [Id | Acc]; false -> Acc end, local_inputs(Rest, Hosts, DataMap, Acc1). % The backtracking algorithm tries to figure out what tasks to run in % order to re-generate a specified intermediate output, given that the % output is not accessible on the host that it was generated on. % A precise algorithm to do this would involve the computation of three sets : % % - Tasks, the set of tasks that need to be re-executed % - DataInputs, the set of data inputs that need to be re-generated % - Hosts, the set of hosts on which the Tasks cannot be run % % The sets are initialized as follows, given an intermediate input D % generated by a task T that is inaccessible on host H: % Tasks : = { T } , DataInputs : = { D } , Hosts : = { H } % % The sets are then closed under the following relations: % % (d) - if any input D' of any task T in Tasks is purely local to Hosts , then D ' is in DataInputs % ( t ) - if T is a task that generated a D in DataInputs , then T is in % Tasks % % (h) - if H is a blacklisted host for any task T in Tasks, then H is % in Hosts % The sets forming the least - fixed - point ( LFP ) of the above relations would provide the Tasks set sought for . % % However, the recursion between (d) and (h) makes this difficult to % compute, and in a dynamic environment with failing hosts, the % precision with respect to Hosts would not provide much benefit. % % Instead, we compute the LFP for (t) and (d), and keep Hosts fixed to % H along with the list of hosts that are currently down. This leaves % the possibility that tasks will be re-executed on blacklisted hosts. % In the actual implementation, we actually don't need all the tasks % that need re-running, only the ones that can be re-run immediately % (i.e. have no dependencies). Tasks that need re-running but have % dependencies on other tasks to be re-run, are just added as waiters % to those tasks. The tasks that don't have dependencies form a % frontier that we collect as we traverse backwards, stage by stage, % through the dependency graph. As a special case, if a task T is % already waiting or running, we don't recurse to its input generating % tasks. -spec collect_stagewise(task_id(), task_map(), stage_map(), input_map(), disco_gbset(host())) -> {disco_gbset(host()), task_map()}. collect_stagewise(TaskId, Tasks, SI, DataMap, FHosts) -> collect_stagewise(gb_sets:from_list([TaskId]), % Cur stage gb_sets:empty(), % Prev stage Frontier Tasks, SI, DataMap, FHosts). collect_stagewise(CurStage, PrevStage, Frontier, Tasks, SI, DataMap, FHosts) -> case {gb_sets:is_empty(CurStage), gb_sets:is_empty(PrevStage)} of {true, true} -> % We are done. {Frontier, Tasks}; {true, false} -> % We are done with the current stage; we recurse, making % the previous stage the current one. collect_stagewise(PrevStage, gb_sets:empty(), Frontier, Tasks, SI, DataMap, FHosts); {false, _} -> {TaskId, CurStage1} = gb_sets:take_largest(CurStage), case is_running(TaskId, Tasks, SI) orelse is_waiting(TaskId, Tasks) of true -> % Nothing to do, we should have already updated % this task's waiters and depends. collect_stagewise(CurStage1, PrevStage, Frontier, Tasks, SI, DataMap, FHosts); false -> collect_task(TaskId, CurStage1, PrevStage, Frontier, Tasks, SI, DataMap, FHosts) end end. collect_task(TaskId, CurStage, PrevStage, Frontier, Tasks, SI, DataMap, FHosts) -> #task_info{spec = #task_spec{input = Inputs}, failed_hosts = TFHosts} = TInfo = task_info(TaskId, Tasks), % Lookup task dependencies. LocalInputs = local_inputs(Inputs, FHosts, DataMap), GenTaskIds = lists:usort([TId || {TId, _} <- LocalInputs, TId =/= input]), % Update task. Its okay to overwrite depends since it should be % empty, or else it would be waiting and we would not be % processing it. TInfo2 = TInfo#task_info{failed_hosts = gb_sets:union(TFHosts, FHosts), depends = GenTaskIds}, Tasks1 = update_task_info(TaskId, TInfo2, Tasks), case GenTaskIds of [] -> % This task is runnable, and hence is on the frontier. % Note that we might mark a task as such even though its % inputs are pipeline inputs (task_id =:= input), and all % of them are on FHosts. There's not much we can do in % this case, since we cannot regenerate pipeline inputs, % so we optimistically run the task anyway. Frontier1 = gb_sets:add_element(TaskId, Frontier), collect_stagewise(CurStage, PrevStage, Frontier1, Tasks1, SI, DataMap, FHosts); [_|_] -> % These tasks belong to the previous stage, since we % currently only have linear pipelines; and this task % needs to wait on them (and hence is not in the % frontier). PrevStage1 = gb_sets:union(PrevStage, gb_sets:from_list(GenTaskIds)), GenTasks = [{Id, task_info(Id, Tasks1)} || Id <- GenTaskIds], Tasks2 = lists:foldl( fun({Id, #task_info{waiters = W} = GT}, Tsks) -> UGT = GT#task_info{waiters = [TaskId|W]}, gb_trees:enter(Id, UGT, Tsks) end, Tasks1, GenTasks), collect_stagewise(CurStage, PrevStage1, Frontier, Tasks2, SI, DataMap, FHosts) end. % This removes the completed task as a dependency from a set of % waiters, and returns the set of tasks that are now runnable since % they have no more dependencies, and the updated task set. -spec wakeup_waiters(task_id(), [task_id()], task_map()) -> {[task_id()], task_map()}. wakeup_waiters(TaskId, Waiters, Tasks) -> lists:foldl( fun(WId, {Runnable, Tsks}) -> #task_info{depends = Deps} = WInfo = task_info(WId, Tsks), UDeps = Deps -- [TaskId], Runnable2 = case UDeps of [] -> [WId | Runnable]; [_|_] -> Runnable end, Tsks2 = gb_trees:enter(WId, WInfo#task_info{depends = UDeps}, Tsks), {Runnable2, Tsks2} end, {[], Tasks}, Waiters).
null
https://raw.githubusercontent.com/discoproject/disco/be65272d3eecca184a3c8f2fa911b86ac87a4e8a/master/src/jc_utils.erl
erlang
This constant control the number of tasks that can be started from the following concurrent stages. The lower this value, the higher the degree of the minimum value that guarantees there will be no deadlock if the number of workers does not decrease. information about a stage which may not have yet run. information about a stage which the caller guarantees exists. far. It will determine whether the task can run or not for sequential stages. stages. If this is the last pending task in the stage in order for the stage to be done. This should only be called for new tasks. Input utilities. Data utilities. Input regeneration and task re-run utilities. Find the inputs that are local to the specified list of hosts. An input is local to a set of hosts iff all its replicas are found only on those hosts. The backtracking algorithm tries to figure out what tasks to run in order to re-generate a specified intermediate output, given that the output is not accessible on the host that it was generated on. A precise algorithm to do this would involve the computation of - Tasks, the set of tasks that need to be re-executed - DataInputs, the set of data inputs that need to be re-generated - Hosts, the set of hosts on which the Tasks cannot be run The sets are initialized as follows, given an intermediate input D generated by a task T that is inaccessible on host H: The sets are then closed under the following relations: (d) - if any input D' of any task T in Tasks is purely local to Tasks (h) - if H is a blacklisted host for any task T in Tasks, then H is in Hosts However, the recursion between (d) and (h) makes this difficult to compute, and in a dynamic environment with failing hosts, the precision with respect to Hosts would not provide much benefit. Instead, we compute the LFP for (t) and (d), and keep Hosts fixed to H along with the list of hosts that are currently down. This leaves the possibility that tasks will be re-executed on blacklisted hosts. In the actual implementation, we actually don't need all the tasks that need re-running, only the ones that can be re-run immediately (i.e. have no dependencies). Tasks that need re-running but have dependencies on other tasks to be re-run, are just added as waiters to those tasks. The tasks that don't have dependencies form a frontier that we collect as we traverse backwards, stage by stage, through the dependency graph. As a special case, if a task T is already waiting or running, we don't recurse to its input generating tasks. Cur stage Prev stage We are done. We are done with the current stage; we recurse, making the previous stage the current one. Nothing to do, we should have already updated this task's waiters and depends. Lookup task dependencies. Update task. Its okay to overwrite depends since it should be empty, or else it would be waiting and we would not be processing it. This task is runnable, and hence is on the frontier. Note that we might mark a task as such even though its inputs are pipeline inputs (task_id =:= input), and all of them are on FHosts. There's not much we can do in this case, since we cannot regenerate pipeline inputs, so we optimistically run the task anyway. These tasks belong to the previous stage, since we currently only have linear pipelines; and this task needs to wait on them (and hence is not in the frontier). This removes the completed task as a dependency from a set of waiters, and returns the set of tasks that are now runnable since they have no more dependencies, and the updated task set.
-module(jc_utils). -include("common_types.hrl"). -include("disco.hrl"). -include("pipeline.hrl"). -include("job_coordinator.hrl"). concurrency , but the higher the potential for job deadlock . The constant 1 is -define(MIN_RATION_OF_FIRST_ACTIVE_TO_REST, 2). -export([stage_info_opt/2, stage_info/2, last_stage_task/2, update_stage/3, update_stage_tasks/4, task_info/2, update_task_info/3, task_spec/2, add_task_spec/3, task_inputs/2, task_outputs/2, input_info/2, update_input_info/3, add_input/3, update_input_failures/2, find_usable_input_hosts/1, collect_stagewise/5, wakeup_waiters/3, no_tasks_running/2, running_tasks/2, can_run_task/4]). -type stage_map() :: disco_gbtree(stage_name(), stage_info()). -type task_map() :: disco_gbtree(task_id(), task_info()). -type input_map() :: disco_gbtree(input_id(), data_info()). -spec stage_info_opt(stage_name(), stage_map()) -> none | stage_info(). stage_info_opt(Stage, SI) -> case gb_trees:lookup(Stage, SI) of none -> none; {value, Info} -> Info end. -spec stage_info(stage_name(), stage_map()) -> stage_info(). stage_info(Stage, SI) -> gb_trees:get(Stage, SI). -spec update_stage(stage_name(), stage_info(), stage_map()) -> stage_map(). update_stage(Stage, Info, SI) -> gb_trees:enter(Stage, Info, SI). -type task_op() :: run | stop | done. -spec update_stage_tasks(stage_name(), task_id(), task_op(), stage_map()) -> stage_map(). update_stage_tasks(S, Id, Op, SI) -> mod_stage_tasks(S, Id, Op, stage_info(S, SI), SI). mod_stage_tasks(S, Id, Op, #stage_info{running = R, done = D, n_running = NR} = Info, SI) -> {R1, D1, NR1} = case Op of run -> {lists:usort([Id | R]), D, NR + 1}; stop -> {R -- [Id], D, NR - 1}; done -> {R -- [Id], lists:usort([Id | D]), NR - 1} end, update_stage(S, Info#stage_info{running = R1, done = D1, n_running = NR1}, SI). -spec can_run_task(pipeline(), stage_name(), stage_map(), task_schedule()) -> boolean(). can_run_task(P, S, SI, #task_schedule{max_cores = Max}) -> can_run_task(P, S, SI, true, 0, Max). the fifth argument shows whether all of the dependencies have finished so the sixth argument shows the total number of tasks running in the previous can_run_task([_|_], ?INPUT, _, _, _, _) -> true; can_run_task(_, _, _, _, NR, Max) when NR >= Max -> false; can_run_task([], _S, _, _, _, _) -> true; can_run_task([{S, _, _}|_], S, SI, true, DepsNRTasks, Max) -> #stage_info{n_running = NR} = jc_utils:stage_info(S, SI), NR + DepsNRTasks < Max; can_run_task([{S, _, false}|_], S, _, false, _, _) -> false; can_run_task([{S, _, true}|_], S, SI, false, DepsNRTasks, Max) -> #stage_info{n_running = NR} = jc_utils:stage_info(S, SI), ?MIN_RATION_OF_FIRST_ACTIVE_TO_REST * NR < DepsNRTasks andalso NR + DepsNRTasks < Max; can_run_task([{DepS,_, _}|Rest], S, SI, DepsFinished, DepsNRTasks, Max) -> #stage_info{finished = Finished, n_running = NR} = jc_utils:stage_info(DepS, SI), case Finished of true -> can_run_task(Rest, S, SI, DepsFinished, DepsNRTasks, Max); false -> can_run_task(Rest, S, SI, false, DepsNRTasks + NR, Max) end. -spec no_tasks_running(stage_name(), stage_map()) -> boolean(). no_tasks_running(S, SI) -> #stage_info{n_running = NR} = stage_info(S, SI), NR == 0. -spec running_tasks(stage_name(), stage_map()) -> [task_id()]. running_tasks(S, SI) -> case stage_info_opt(S, SI) of none -> []; StageInfo -> StageInfo#stage_info.running end. -spec last_stage_task(stage_name(), stage_map()) -> boolean(). last_stage_task(Stage, SI) -> #stage_info{done = Done, all = All} = stage_info(Stage, SI), length(Done) =:= All. -spec is_running(task_id(), task_map(), stage_map()) -> boolean(). is_running(TaskId, Tasks, SI) -> #task_info{spec = #task_spec{taskid = TaskId, stage = Stage}} = task_info(TaskId, Tasks), #stage_info{done = Done} = stage_info(Stage, SI), lists:member(TaskId, Done). -spec is_waiting(task_id(), task_map()) -> boolean(). is_waiting(TaskId, Tasks) -> #task_info{depends = Depends} = task_info(TaskId, Tasks), Depends =/= []. -spec task_info(input | task_id(), task_map()) -> task_info(). task_info(TaskId, Tasks) -> gb_trees:get(TaskId, Tasks). -spec task_spec(input, input_map()) -> input; (task_id(), task_map()) -> task_spec(). task_spec(TaskId, Tasks) -> (task_info(TaskId, Tasks))#task_info.spec. -spec task_outputs(input | task_id(), task_map()) -> [task_output()]. task_outputs(TaskId, Tasks) -> (task_info(TaskId, Tasks))#task_info.outputs. -spec add_task_spec(task_id(), task_spec(), task_map()) -> task_map(). add_task_spec(TaskId, TaskSpec, Tasks) -> gb_trees:enter(TaskId, #task_info{spec = TaskSpec}, Tasks). -spec update_task_info(task_id(), task_info(), task_map()) -> task_map(). update_task_info(TaskId, TInfo, Tasks) -> gb_trees:enter(TaskId, TInfo, Tasks). -spec add_input(input_id(), data_info(), input_map()) -> input_map(). add_input(InputId, DInfo, DataMap) -> gb_trees:enter(InputId, DInfo, DataMap). -spec input_info(input_id(), input_map()) -> data_info(). input_info(InputId, DataMap) -> gb_trees:get(InputId, DataMap). -spec update_input_info(input_id(), data_info(), input_map()) -> input_map(). update_input_info(InputId, DInfo, DataMap) -> gb_trees:enter(InputId, DInfo, DataMap). -spec task_inputs([input_id()], input_map()) -> [{input_id(), data_input()}]. task_inputs(InputIds, DataMap) -> [{Id, (gb_trees:get(Id, DataMap))#data_info.source} || Id <- InputIds]. -spec data_inputs(data_info()) -> [data_input()]. data_inputs(#data_info{source = Source, locations = Locations}) -> [Source | gb_trees:values(Locations)]. -spec data_hosts(data_info()) -> [host()]. data_hosts(DInfo) -> lists:usort(lists:flatten([pipeline_utils:locations(DI) || DI <- data_inputs(DInfo)])). -spec update_input_failures([host()], data_info()) -> data_info(). update_input_failures(Hosts, #data_info{failures = Failures} = DInfo) -> F = lists:foldl( fun(H, Fails) -> case gb_trees:lookup(H, Fails) of none -> Fails; {value, Cnt} -> gb_trees:enter(H, Cnt + 1, Fails) end end, Failures, Hosts), DInfo#data_info{failures = F}. -spec find_usable_input_hosts(data_info()) -> [host()]. find_usable_input_hosts(#data_info{failures = Failures}) -> [H || {H, Fails} <- gb_trees:to_list(Failures), Fails < ?MAX_INPUT_FAILURE]. -spec local_inputs([input_id()], disco_gbset(host()), input_map()) -> [input_id()]. local_inputs(InputIds, Hosts, DataMap) -> local_inputs(InputIds, Hosts, DataMap, []). local_inputs([], _Hosts, _DataMap, Acc) -> lists:usort(Acc); local_inputs([Id | Rest], Hosts, DataMap, Acc) -> Acc1 = case lists:all(fun(H) -> gb_sets:is_member(H, Hosts) end, data_hosts(input_info(Id, DataMap))) of true -> [Id | Acc]; false -> Acc end, local_inputs(Rest, Hosts, DataMap, Acc1). three sets : Tasks : = { T } , DataInputs : = { D } , Hosts : = { H } Hosts , then D ' is in DataInputs ( t ) - if T is a task that generated a D in DataInputs , then T is in The sets forming the least - fixed - point ( LFP ) of the above relations would provide the Tasks set sought for . -spec collect_stagewise(task_id(), task_map(), stage_map(), input_map(), disco_gbset(host())) -> {disco_gbset(host()), task_map()}. collect_stagewise(TaskId, Tasks, SI, DataMap, FHosts) -> Frontier Tasks, SI, DataMap, FHosts). collect_stagewise(CurStage, PrevStage, Frontier, Tasks, SI, DataMap, FHosts) -> case {gb_sets:is_empty(CurStage), gb_sets:is_empty(PrevStage)} of {true, true} -> {Frontier, Tasks}; {true, false} -> collect_stagewise(PrevStage, gb_sets:empty(), Frontier, Tasks, SI, DataMap, FHosts); {false, _} -> {TaskId, CurStage1} = gb_sets:take_largest(CurStage), case is_running(TaskId, Tasks, SI) orelse is_waiting(TaskId, Tasks) of true -> collect_stagewise(CurStage1, PrevStage, Frontier, Tasks, SI, DataMap, FHosts); false -> collect_task(TaskId, CurStage1, PrevStage, Frontier, Tasks, SI, DataMap, FHosts) end end. collect_task(TaskId, CurStage, PrevStage, Frontier, Tasks, SI, DataMap, FHosts) -> #task_info{spec = #task_spec{input = Inputs}, failed_hosts = TFHosts} = TInfo = task_info(TaskId, Tasks), LocalInputs = local_inputs(Inputs, FHosts, DataMap), GenTaskIds = lists:usort([TId || {TId, _} <- LocalInputs, TId =/= input]), TInfo2 = TInfo#task_info{failed_hosts = gb_sets:union(TFHosts, FHosts), depends = GenTaskIds}, Tasks1 = update_task_info(TaskId, TInfo2, Tasks), case GenTaskIds of [] -> Frontier1 = gb_sets:add_element(TaskId, Frontier), collect_stagewise(CurStage, PrevStage, Frontier1, Tasks1, SI, DataMap, FHosts); [_|_] -> PrevStage1 = gb_sets:union(PrevStage, gb_sets:from_list(GenTaskIds)), GenTasks = [{Id, task_info(Id, Tasks1)} || Id <- GenTaskIds], Tasks2 = lists:foldl( fun({Id, #task_info{waiters = W} = GT}, Tsks) -> UGT = GT#task_info{waiters = [TaskId|W]}, gb_trees:enter(Id, UGT, Tsks) end, Tasks1, GenTasks), collect_stagewise(CurStage, PrevStage1, Frontier, Tasks2, SI, DataMap, FHosts) end. -spec wakeup_waiters(task_id(), [task_id()], task_map()) -> {[task_id()], task_map()}. wakeup_waiters(TaskId, Waiters, Tasks) -> lists:foldl( fun(WId, {Runnable, Tsks}) -> #task_info{depends = Deps} = WInfo = task_info(WId, Tsks), UDeps = Deps -- [TaskId], Runnable2 = case UDeps of [] -> [WId | Runnable]; [_|_] -> Runnable end, Tsks2 = gb_trees:enter(WId, WInfo#task_info{depends = UDeps}, Tsks), {Runnable2, Tsks2} end, {[], Tasks}, Waiters).
11e9b25acdf169c72feace0533f5d14bdbf72b8594443bf75359752828ead558
zotonic/zotonic
mod_zotonic_site_management.erl
@author < > 2016 %% @doc Site management module Copyright 2016 %% Licensed under the Apache License , Version 2.0 ( the " License " ) ; %% you may not use this file except in compliance with the License. %% You may obtain a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %% See the License for the specific language governing permissions and %% limitations under the License. -module(mod_zotonic_site_management). -author("Marc Worrell <>"). -mod_title("Zotonic Site Management"). -mod_description("Manage Zotonic sites."). -mod_prio(500). -include_lib("zotonic_core/include/zotonic.hrl"). -include_lib("zotonic_mod_wires/include/mod_wires.hrl"). -export([ event/2, progress/3 ]). event(#submit{message=addsite, form=Form}, Context) -> true = z_auth:is_auth(Context), Sitename = z_context:get_q_validated(<<"sitename">>, Context), Options = [ {hostname, z_context:get_q_validated(<<"hostname">>, Context)}, {skeleton, z_context:get_q_validated(<<"skel">>, Context)}, {dbdatabase, z_context:get_q_validated(<<"dbdatabase">>, Context)}, {dbschema, case z_context:get_q_validated(<<"dbschema">>, Context) of <<>> -> Sitename; Schema -> Schema end}, {dbhost, z_context:get_q_validated(<<"dbhost">>, Context)}, {dbport, z_context:get_q_validated(<<"dbport">>, Context)}, {dbuser, z_context:get_q(<<"dbuser">>, Context)}, {dbpassword, z_context:get_q(<<"dbpassword">>, Context)} ], ?LOG_NOTICE(#{ text => <<"[zotonic_site_status] Creating site">>, in => zotonic_mod_zotonic_site_management, site => Sitename, options => Options }), case zotonic_status_addsite:addsite(Sitename, Options, Context) of {ok, {Site, FinalOptions}} -> progress(Sitename, ?__("Starting the new site ...", Context), Context), ok = z_sites_manager:upgrade(), _ = z_sites_manager:start(Site), ?LOG_NOTICE(#{ text => <<"[zotonic_site_status] Success creating site">>, in => zotonic_mod_zotonic_site_management, site => Site }), case await(Site) of ok -> ?LOG_NOTICE(#{ text => <<"[zotonic_site_status] Site is running">>, in => zotonic_mod_zotonic_site_management, site => Site }), SiteContext = z_context:new(Site), z_module_manager:upgrade_await(SiteContext), Vars = [ {admin_url, abs_url_for(admin, SiteContext)}, {site_url, z_context:abs_url(<<"/">>, SiteContext)}, {site_dir, z_path:site_dir(SiteContext)} | FinalOptions ], Context1 = notice(Form, Site, ?__("Succesfully created the site.", Context), Context), z_render:replace(Form, #render{vars=Vars, template="_addsite_success.tpl"}, Context1); {error, StartError} -> ?LOG_ERROR(#{ text => <<"[zotonic_site_status] Newly created site is NOT running">>, in => zotonic_mod_zotonic_site_management, site => Site, result => error, reason => StartError }), notice(Form, Site, ?__("Something is wrong, site is not starting. Please check the logs.", Context), Context) end; {error, Msg} when is_list(Msg); is_binary(Msg) -> notice(Form, Sitename, Msg, Context); {error, Msg} -> notice(Form, Sitename, io_lib:format("~p", [Msg]), Context) end. @doc Wait till the site is up and running . Timeout after 100 seconds . await(Site) -> await(Site, 0). await(_Site, Tries) when Tries > 100 -> {error, timeout}; await(Site, Tries) -> timer:sleep(1000), case z_sites_manager:get_site_status(Site) of {ok, running} -> ok; {ok, starting} -> timer:sleep(1000), await(Site, Tries+1); {ok, new} -> timer:sleep(1000), await(Site, Tries+1); {ok, retrying} -> timer:sleep(1000), await(Site, Tries+1); {ok, Other} -> {error, Other}; {error, _} = Error -> Error end. abs_url_for(Dispatch, Context) -> case z_dispatcher:url_for(Dispatch, Context) of undefined -> undefined; Url -> z_context:abs_url(Url, Context) end. % @doc Render a notice. notice(Form, Sitename, Text, Context) -> Actions = notice_actions(Sitename, Text) ++ [ {unmask, [{target, Form}]} ], z_render:wire(Actions, Context). progress(Sitename, Text, Context) -> case erlang:get(is_zotonic_command) of true -> io:format("~s~n", [ Text ]); _ -> z_notifier:notify( #page_actions{ actions = notice_actions(Sitename, Text) }, Context) end. notice_actions(Sitename, Text) -> [ {insert_top, [ {target, "notices"}, {template, "_notice.tpl"}, {site, Sitename}, {notice, Text} ]}, {fade_out, [ {selector, "#notices > div:gt(0)"}, {speed, 2000} ]} ].
null
https://raw.githubusercontent.com/zotonic/zotonic/1bb4aa8a0688d007dd8ec8ba271546f658312da8/apps/zotonic_mod_zotonic_site_management/src/mod_zotonic_site_management.erl
erlang
@doc Site management module you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. @doc Render a notice.
@author < > 2016 Copyright 2016 Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(mod_zotonic_site_management). -author("Marc Worrell <>"). -mod_title("Zotonic Site Management"). -mod_description("Manage Zotonic sites."). -mod_prio(500). -include_lib("zotonic_core/include/zotonic.hrl"). -include_lib("zotonic_mod_wires/include/mod_wires.hrl"). -export([ event/2, progress/3 ]). event(#submit{message=addsite, form=Form}, Context) -> true = z_auth:is_auth(Context), Sitename = z_context:get_q_validated(<<"sitename">>, Context), Options = [ {hostname, z_context:get_q_validated(<<"hostname">>, Context)}, {skeleton, z_context:get_q_validated(<<"skel">>, Context)}, {dbdatabase, z_context:get_q_validated(<<"dbdatabase">>, Context)}, {dbschema, case z_context:get_q_validated(<<"dbschema">>, Context) of <<>> -> Sitename; Schema -> Schema end}, {dbhost, z_context:get_q_validated(<<"dbhost">>, Context)}, {dbport, z_context:get_q_validated(<<"dbport">>, Context)}, {dbuser, z_context:get_q(<<"dbuser">>, Context)}, {dbpassword, z_context:get_q(<<"dbpassword">>, Context)} ], ?LOG_NOTICE(#{ text => <<"[zotonic_site_status] Creating site">>, in => zotonic_mod_zotonic_site_management, site => Sitename, options => Options }), case zotonic_status_addsite:addsite(Sitename, Options, Context) of {ok, {Site, FinalOptions}} -> progress(Sitename, ?__("Starting the new site ...", Context), Context), ok = z_sites_manager:upgrade(), _ = z_sites_manager:start(Site), ?LOG_NOTICE(#{ text => <<"[zotonic_site_status] Success creating site">>, in => zotonic_mod_zotonic_site_management, site => Site }), case await(Site) of ok -> ?LOG_NOTICE(#{ text => <<"[zotonic_site_status] Site is running">>, in => zotonic_mod_zotonic_site_management, site => Site }), SiteContext = z_context:new(Site), z_module_manager:upgrade_await(SiteContext), Vars = [ {admin_url, abs_url_for(admin, SiteContext)}, {site_url, z_context:abs_url(<<"/">>, SiteContext)}, {site_dir, z_path:site_dir(SiteContext)} | FinalOptions ], Context1 = notice(Form, Site, ?__("Succesfully created the site.", Context), Context), z_render:replace(Form, #render{vars=Vars, template="_addsite_success.tpl"}, Context1); {error, StartError} -> ?LOG_ERROR(#{ text => <<"[zotonic_site_status] Newly created site is NOT running">>, in => zotonic_mod_zotonic_site_management, site => Site, result => error, reason => StartError }), notice(Form, Site, ?__("Something is wrong, site is not starting. Please check the logs.", Context), Context) end; {error, Msg} when is_list(Msg); is_binary(Msg) -> notice(Form, Sitename, Msg, Context); {error, Msg} -> notice(Form, Sitename, io_lib:format("~p", [Msg]), Context) end. @doc Wait till the site is up and running . Timeout after 100 seconds . await(Site) -> await(Site, 0). await(_Site, Tries) when Tries > 100 -> {error, timeout}; await(Site, Tries) -> timer:sleep(1000), case z_sites_manager:get_site_status(Site) of {ok, running} -> ok; {ok, starting} -> timer:sleep(1000), await(Site, Tries+1); {ok, new} -> timer:sleep(1000), await(Site, Tries+1); {ok, retrying} -> timer:sleep(1000), await(Site, Tries+1); {ok, Other} -> {error, Other}; {error, _} = Error -> Error end. abs_url_for(Dispatch, Context) -> case z_dispatcher:url_for(Dispatch, Context) of undefined -> undefined; Url -> z_context:abs_url(Url, Context) end. notice(Form, Sitename, Text, Context) -> Actions = notice_actions(Sitename, Text) ++ [ {unmask, [{target, Form}]} ], z_render:wire(Actions, Context). progress(Sitename, Text, Context) -> case erlang:get(is_zotonic_command) of true -> io:format("~s~n", [ Text ]); _ -> z_notifier:notify( #page_actions{ actions = notice_actions(Sitename, Text) }, Context) end. notice_actions(Sitename, Text) -> [ {insert_top, [ {target, "notices"}, {template, "_notice.tpl"}, {site, Sitename}, {notice, Text} ]}, {fade_out, [ {selector, "#notices > div:gt(0)"}, {speed, 2000} ]} ].
698662e66d00402047bce5e024eeedb0abb9e786ff78cd7686a58c86b939900c
screenshotbot/screenshotbot-oss
recent-runs.lisp
;;;; Copyright 2018-Present Modern Interpreters Inc. ;;;; This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. (uiop:define-package :screenshotbot/dashboard/recent-runs (:use #:cl #:alexandria #:screenshotbot/user-api #:screenshotbot/dashboard/numbers #:screenshotbot/template #:screenshotbot/taskie #:markup) (:import-from #:screenshotbot/server #:defhandler) (:import-from #:util #:make-url #:oid) (:import-from #:screenshotbot/ui #:ui/a #:ui/div) (:import-from #:screenshotbot/dashboard/run-page #:commit) (:import-from #:screenshotbot/dashboard/run-page #:run-page) (:import-from #:screenshotbot/dashboard/explain #:explain) (:import-from #:screenshotbot/installation #:default-logged-in-page) (:import-from #:util/misc #:?.) (:import-from #:screenshotbot/dashboard/review-link #:review-link) (:export #:recent-runs)) (in-package :screenshotbot/dashboard/recent-runs) (markup:enable-reader) (hex:declare-handler 'run-page) (defun find-recent-runs () (company-runs (current-company))) (deftag conditional-commit (&key repo hash) (cond ((and repo hash) <span>on <commit repo= repo hash= hash /></span>) (t nil))) (deftag promoted-tooltip () <div> <p> A <b>promoted</b> run is the current "golden" run on your master branch. </p> <p>Promotion logic is used to send notifications for changes on your master branch, and to track the history of a given screenshot. For projects not associated with a repository, the promoted run is usually the most recent run.</p> <p>Promoted runs are <b>not</b> used for determining changes on Pull Requests. For that we just use the first known run on the merge-base.</p> </div>) (deftag recorder-run-row (&key run) (taskie-row :object run (ui/a :href (format nil "/runs/~a" (oid run)) (channel-name (recorder-run-channel run))) (ui/div (let ((review-link (review-link :run run))) (cond ((activep run) <span> Promoted<explain title= "Promoted run"><promoted-tooltip /></explain> run <conditional-commit repo= (channel-repo (recorder-run-channel run)) hash= (recorder-run-commit run) /> </span>) ((recorder-previous-run run) <span>Previously promoted run <conditional-commit repo= (channel-repo (recorder-run-channel run)) hash= (recorder-run-commit run) /> </span>) (review-link <span> Run on ,(progn review-link) </span>) (t <span> Unpromoted run ,(when-let ((repo (channel-repo (recorder-run-channel run))) (hash (recorder-run-commit run))) <span> on <commit repo= repo hash=hash /> </span>) </span> )))) (taskie-timestamp :prefix "" :timestamp (created-at run)))) (defun render-recent-runs (runs &key (user (current-user)) (numbersp t) (check-access-p t) (script-name (hunchentoot:script-name*)) (company (current-company))) (with-pagination (runs runs :next-link next-link :prev-link prev-link) (when check-access-p (apply 'can-view! runs)) (dashboard-template :user user :title "Screenshotbot: Runs" :company company :script-name "/runs" #+nil (when numbersp (numbers-section :company company)) (taskie-page-title :title "Recent Runs" (ui/a :id "delete-runs" :btn :danger :class "btn-sm" "Delete Selected") (ui/a :id "compare-runs" :btn :success :class "btn-sm ms-1" "Compare")) (taskie-list :empty-message "No recent runs to show. But that's okay, it's easy to get started!" :items runs :headers (list "Channel" "Status" "Date") :next-link next-link :prev-link prev-link :row-generator (lambda (run) (recorder-run-row :run run)))))) (defun %recent-runs () (needs-user!) (let ((runs (find-recent-runs))) (render-recent-runs runs))) (defhandler (recent-runs :uri "/runs") () (%recent-runs)) (defmethod default-logged-in-page ((installation t)) (%recent-runs))
null
https://raw.githubusercontent.com/screenshotbot/screenshotbot-oss/70e6d56619984ddeb85a4b94bda5a40eee381a8b/src/screenshotbot/dashboard/recent-runs.lisp
lisp
Copyright 2018-Present Modern Interpreters Inc.
This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. (uiop:define-package :screenshotbot/dashboard/recent-runs (:use #:cl #:alexandria #:screenshotbot/user-api #:screenshotbot/dashboard/numbers #:screenshotbot/template #:screenshotbot/taskie #:markup) (:import-from #:screenshotbot/server #:defhandler) (:import-from #:util #:make-url #:oid) (:import-from #:screenshotbot/ui #:ui/a #:ui/div) (:import-from #:screenshotbot/dashboard/run-page #:commit) (:import-from #:screenshotbot/dashboard/run-page #:run-page) (:import-from #:screenshotbot/dashboard/explain #:explain) (:import-from #:screenshotbot/installation #:default-logged-in-page) (:import-from #:util/misc #:?.) (:import-from #:screenshotbot/dashboard/review-link #:review-link) (:export #:recent-runs)) (in-package :screenshotbot/dashboard/recent-runs) (markup:enable-reader) (hex:declare-handler 'run-page) (defun find-recent-runs () (company-runs (current-company))) (deftag conditional-commit (&key repo hash) (cond ((and repo hash) <span>on <commit repo= repo hash= hash /></span>) (t nil))) (deftag promoted-tooltip () <div> <p> A <b>promoted</b> run is the current "golden" run on your master branch. </p> <p>Promotion logic is used to send notifications for changes on your master branch, and to track the history of a given screenshot. For projects not associated with a repository, the promoted run is usually the most recent run.</p> <p>Promoted runs are <b>not</b> used for determining changes on Pull Requests. For that we just use the first known run on the merge-base.</p> </div>) (deftag recorder-run-row (&key run) (taskie-row :object run (ui/a :href (format nil "/runs/~a" (oid run)) (channel-name (recorder-run-channel run))) (ui/div (let ((review-link (review-link :run run))) (cond ((activep run) <span> Promoted<explain title= "Promoted run"><promoted-tooltip /></explain> run <conditional-commit repo= (channel-repo (recorder-run-channel run)) hash= (recorder-run-commit run) /> </span>) ((recorder-previous-run run) <span>Previously promoted run <conditional-commit repo= (channel-repo (recorder-run-channel run)) hash= (recorder-run-commit run) /> </span>) (review-link <span> Run on ,(progn review-link) </span>) (t <span> Unpromoted run ,(when-let ((repo (channel-repo (recorder-run-channel run))) (hash (recorder-run-commit run))) <span> on <commit repo= repo hash=hash /> </span>) </span> )))) (taskie-timestamp :prefix "" :timestamp (created-at run)))) (defun render-recent-runs (runs &key (user (current-user)) (numbersp t) (check-access-p t) (script-name (hunchentoot:script-name*)) (company (current-company))) (with-pagination (runs runs :next-link next-link :prev-link prev-link) (when check-access-p (apply 'can-view! runs)) (dashboard-template :user user :title "Screenshotbot: Runs" :company company :script-name "/runs" #+nil (when numbersp (numbers-section :company company)) (taskie-page-title :title "Recent Runs" (ui/a :id "delete-runs" :btn :danger :class "btn-sm" "Delete Selected") (ui/a :id "compare-runs" :btn :success :class "btn-sm ms-1" "Compare")) (taskie-list :empty-message "No recent runs to show. But that's okay, it's easy to get started!" :items runs :headers (list "Channel" "Status" "Date") :next-link next-link :prev-link prev-link :row-generator (lambda (run) (recorder-run-row :run run)))))) (defun %recent-runs () (needs-user!) (let ((runs (find-recent-runs))) (render-recent-runs runs))) (defhandler (recent-runs :uri "/runs") () (%recent-runs)) (defmethod default-logged-in-page ((installation t)) (%recent-runs))
9136114420e6e86956bed2a1c50a067210cab1669ff3766da9741f7028bf57a4
roryk/bcbio.rnaseq
t_simulate.clj
(ns bcbio.rnaseq.t-simulate (:require [bcbio.rnaseq.t-simulate :refer :all] [bcbio.rnaseq.simulate :as simulate] [bcbio.rnaseq.simulator :as simulator] [bcbio.rnaseq.test-setup :refer [test-setup]] [clojure.test :refer :all] [bcbio.rnaseq.util :as util])) (deftest simulate-nofile-works (is (util/file-exists? (simulate/run-simulation "simulate" 10000 3 20 nil)))) (deftest simulate-file-works (is (util/file-exists? (simulate/run-simulation "simulate" 10000 3 20 simulator/default-count-file))))
null
https://raw.githubusercontent.com/roryk/bcbio.rnaseq/66c629eb737c9a0096082d6683657bf9d89eb271/test/bcbio/rnaseq/t_simulate.clj
clojure
(ns bcbio.rnaseq.t-simulate (:require [bcbio.rnaseq.t-simulate :refer :all] [bcbio.rnaseq.simulate :as simulate] [bcbio.rnaseq.simulator :as simulator] [bcbio.rnaseq.test-setup :refer [test-setup]] [clojure.test :refer :all] [bcbio.rnaseq.util :as util])) (deftest simulate-nofile-works (is (util/file-exists? (simulate/run-simulation "simulate" 10000 3 20 nil)))) (deftest simulate-file-works (is (util/file-exists? (simulate/run-simulation "simulate" 10000 3 20 simulator/default-count-file))))
8410494c98132b3ee2237e94626347889e878d3f3e310b4c970213e04d6574e9
adamwalker/clash-riscv
CacheTest.hs
-- | Instruction cache testbench module CacheTest where import Clash.Prelude as Clash import qualified Prelude as P import Data.Bool import Data.List (sort) import Cache.ICache import Cache.Replacement import Cache.PseudoLRUTree import TestUtils --Backing mem for cache. Delivers a line at a time backingMem :: HiddenClockReset dom sync gated => Signal dom Bool -> Signal dom (BitVector 30) -> Signal dom Bool -> Signal dom (Bool, Vec 16 (BitVector 32)) backingMem req addr memValid = register (False, repeat 0) $ readMemory <$> addr <*> memValid where readMemory addr memValid = (memValid, bool (repeat 0) (map resize (iterateI (+ 1) (addr .&. complement 0b1111))) memValid) --Test stimulus generation for instruction cache. Requests a sequence of addresses and checks the correct result is returned. testCache :: HiddenClockReset dom sync gated => [BitVector 30] -> Signal dom Bool -> Signal dom (BitVector 32) -> Signal dom ((Bool, BitVector 30), (Bool, Bool)) testCache addresses instrValid instr = mealy step addresses $ bundle (instrValid, instr) where step :: [BitVector 30] -> (Bool, BitVector 32) -> ([BitVector 30], ((Bool, BitVector 30), (Bool, Bool))) step state (memReady, memData) = (state', ((memReq, memAddress), (P.null state, success))) where memReq = True memAddress = case state' of (x:xs) -> x [] -> 0 lastMemAddress = case state of (x:xs) -> x [] -> 0 success = not memReady || (memData == resize lastMemAddress) state' = case memReady of False -> state True -> case state of [] -> [] x:xs -> xs --Cache test system consisting of cache, backing ram and stimulus generator testSystem :: HiddenClockReset dom sync gated => [BitVector 30] -> Signal dom Bool -> Signal dom (Bool, Bool) testSystem addresses memValid = result where (procRespValid, procResp, memReqValid, memReq) = iCache (SNat @ 14) (SNat @ 12) (SNat @ 4) pseudoLRUReplacement cacheReq cacheAddress memRespValid memResp (memRespValid, memResp) = unbundle $ backingMem memReqValid memReq memValid (testReq, result) = unbundle $ testCache addresses (firstCycleDef' False procRespValid) procResp (cacheReq, cacheAddress) = unbundle testReq --Cache QuickCheck property --TODO: generate addresses with realistic access patterns cacheProp addresses memValid = P.and success && P.or finished where (finished, success) = P.unzip $ P.take 1000 $ sample $ testSystem addresses memValid lru tree pseudo - tests prop_plru :: Vec 15 Bool -> Bool prop_plru tree = reordered == [0..15] where trees = Clash.iterate (SNat @ 16) func tree where func tree = updateWay (getOldestWay tree) tree reordered = sort $ Clash.toList $ Clash.map (fromIntegral . pack) $ Clash.map getOldestWay trees prop_plruSame :: Vec 15 Bool -> Bool prop_plruSame tree = updateOldestWay tree == (oldest, newTree) where oldest = getOldestWay tree newTree = updateWay oldest tree prop_plruIdempotent :: Vec 15 Bool -> Vec 4 Bool -> Bool prop_plruIdempotent tree idx = updateWay idx tree == updateWay idx (updateWay idx tree) prop_plruSimpleCase :: Vec 1 Bool -> Bool prop_plruSimpleCase tree = updateWay (getOldestWay tree) tree == Clash.map not tree
null
https://raw.githubusercontent.com/adamwalker/clash-riscv/84a90731a07c3427695b4926d7159f9e9902c1a1/test/CacheTest.hs
haskell
| Instruction cache testbench Backing mem for cache. Delivers a line at a time Test stimulus generation for instruction cache. Requests a sequence of addresses and checks the correct result is returned. Cache test system consisting of cache, backing ram and stimulus generator Cache QuickCheck property TODO: generate addresses with realistic access patterns
module CacheTest where import Clash.Prelude as Clash import qualified Prelude as P import Data.Bool import Data.List (sort) import Cache.ICache import Cache.Replacement import Cache.PseudoLRUTree import TestUtils backingMem :: HiddenClockReset dom sync gated => Signal dom Bool -> Signal dom (BitVector 30) -> Signal dom Bool -> Signal dom (Bool, Vec 16 (BitVector 32)) backingMem req addr memValid = register (False, repeat 0) $ readMemory <$> addr <*> memValid where readMemory addr memValid = (memValid, bool (repeat 0) (map resize (iterateI (+ 1) (addr .&. complement 0b1111))) memValid) testCache :: HiddenClockReset dom sync gated => [BitVector 30] -> Signal dom Bool -> Signal dom (BitVector 32) -> Signal dom ((Bool, BitVector 30), (Bool, Bool)) testCache addresses instrValid instr = mealy step addresses $ bundle (instrValid, instr) where step :: [BitVector 30] -> (Bool, BitVector 32) -> ([BitVector 30], ((Bool, BitVector 30), (Bool, Bool))) step state (memReady, memData) = (state', ((memReq, memAddress), (P.null state, success))) where memReq = True memAddress = case state' of (x:xs) -> x [] -> 0 lastMemAddress = case state of (x:xs) -> x [] -> 0 success = not memReady || (memData == resize lastMemAddress) state' = case memReady of False -> state True -> case state of [] -> [] x:xs -> xs testSystem :: HiddenClockReset dom sync gated => [BitVector 30] -> Signal dom Bool -> Signal dom (Bool, Bool) testSystem addresses memValid = result where (procRespValid, procResp, memReqValid, memReq) = iCache (SNat @ 14) (SNat @ 12) (SNat @ 4) pseudoLRUReplacement cacheReq cacheAddress memRespValid memResp (memRespValid, memResp) = unbundle $ backingMem memReqValid memReq memValid (testReq, result) = unbundle $ testCache addresses (firstCycleDef' False procRespValid) procResp (cacheReq, cacheAddress) = unbundle testReq cacheProp addresses memValid = P.and success && P.or finished where (finished, success) = P.unzip $ P.take 1000 $ sample $ testSystem addresses memValid lru tree pseudo - tests prop_plru :: Vec 15 Bool -> Bool prop_plru tree = reordered == [0..15] where trees = Clash.iterate (SNat @ 16) func tree where func tree = updateWay (getOldestWay tree) tree reordered = sort $ Clash.toList $ Clash.map (fromIntegral . pack) $ Clash.map getOldestWay trees prop_plruSame :: Vec 15 Bool -> Bool prop_plruSame tree = updateOldestWay tree == (oldest, newTree) where oldest = getOldestWay tree newTree = updateWay oldest tree prop_plruIdempotent :: Vec 15 Bool -> Vec 4 Bool -> Bool prop_plruIdempotent tree idx = updateWay idx tree == updateWay idx (updateWay idx tree) prop_plruSimpleCase :: Vec 1 Bool -> Bool prop_plruSimpleCase tree = updateWay (getOldestWay tree) tree == Clash.map not tree
34df8afd4188c3480d429cecfdc9af301ff1006936f10df3d1a8346270308bdc
pauleve/pint
an_fixpoint.ml
Copyright or © or Copr . 2015 - 2017 This software is a computer program whose purpose is to provide Process Hitting related tools . This software is governed by the CeCILL 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 license as circulated by CEA , CNRS and INRIA at the following URL " " . As a counterpart to the access to the source code and rights to copy , modify and redistribute granted by the license , users are provided only with a limited warranty and the software 's author , the holder of the economic rights , and the successive licensors have only limited liability . In this respect , the user 's attention is drawn to the risks associated with loading , using , modifying and/or developing or reproducing the software by the user in light of its specific status of free software , that may mean that it is complicated to manipulate , and that also therefore means that it is reserved for developers and experienced professionals having in - depth computer knowledge . Users are therefore encouraged to load and test the software 's suitability as regards their requirements in conditions enabling the security of their systems and/or data to be ensured and , more generally , to use and operate it in the same conditions as regards security . The fact that you are presently reading this means that you have had knowledge of the CeCILL license and that you accept its terms . Copyright or © or Copr. Loïc Paulevé 2015-2017 This software is a computer program whose purpose is to provide Process Hitting related tools. This software is governed by the CeCILL 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 license as circulated by CEA, CNRS and INRIA at the following URL "". As a counterpart to the access to the source code and rights to copy, modify and redistribute granted by the license, users are provided only with a limited warranty and the software's author, the holder of the economic rights, and the successive licensors have only limited liability. In this respect, the user's attention is drawn to the risks associated with loading, using, modifying and/or developing or reproducing the software by the user in light of its specific status of free software, that may mean that it is complicated to manipulate, and that also therefore means that it is reserved for developers and experienced professionals having in-depth computer knowledge. Users are therefore encouraged to load and test the software's suitability as regards their requirements in conditions enabling the security of their systems and/or data to be ensured and, more generally, to use and operate it in the same conditions as regards security. The fact that you are presently reading this means that you have had knowledge of the CeCILL license and that you accept its terms. *) open Facile open Easy open PintTypes open AutomataNetwork let fixpoints_jit push_state restrict an = let v_arrays = Hashtbl.create (count_automata an) in let register_automata a n goal = let vs = Array.init n (fun _ -> Fd.create Domain.boolean) in Hashtbl.add v_arrays a vs; Constraint : exactly one state per automata Cstr.post (Arith.sum_fd vs =~ i2e 1); goal &&~ Goals.Array.labeling vs in let goal = Hashtbl.fold register_automata an.ls Goals.success in let lsvar (a,i) = let vs = Hashtbl.find v_arrays a in vs.(i) in let e ai = fd2e (lsvar ai) in let register_restrict ai = Cstr.post (e ai =~ i2e 1) in List.iter register_restrict restrict; let register_tr trid tr = let vars = List.map e (IMap.bindings tr.pre) in let sume = List.fold_left (+~) (List.hd vars) (List.tl vars) in (* Constraint: tr is not applicable *) Cstr.post (sume <~ i2e (IMap.cardinal tr.pre)) in Hashtbl.iter register_tr an.trs; let register_sol () = let fold_vs a vs state = let i = List.find (fun i -> Fd.int_value vs.(i) == 1) (Util.range 0 (Array.length vs)) in IMap.add a i state in let state = Hashtbl.fold fold_vs v_arrays IMap.empty in push_state state in try ignore(Goals.solve ((goal &&~ Goals.atomic register_sol &&~ Goals.fail) ||~ Goals.success)) with Stak.Fail _ -> () let fixpoints ?(restrict=[]) args = let sols = ref [] in let push_state state = sols := state::!sols in fixpoints_jit push_state restrict args; !sols
null
https://raw.githubusercontent.com/pauleve/pint/7cf943ec60afcf285c368950925fd45f59f66f4a/anlib/an_fixpoint.ml
ocaml
Constraint: tr is not applicable
Copyright or © or Copr . 2015 - 2017 This software is a computer program whose purpose is to provide Process Hitting related tools . This software is governed by the CeCILL 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 license as circulated by CEA , CNRS and INRIA at the following URL " " . As a counterpart to the access to the source code and rights to copy , modify and redistribute granted by the license , users are provided only with a limited warranty and the software 's author , the holder of the economic rights , and the successive licensors have only limited liability . In this respect , the user 's attention is drawn to the risks associated with loading , using , modifying and/or developing or reproducing the software by the user in light of its specific status of free software , that may mean that it is complicated to manipulate , and that also therefore means that it is reserved for developers and experienced professionals having in - depth computer knowledge . Users are therefore encouraged to load and test the software 's suitability as regards their requirements in conditions enabling the security of their systems and/or data to be ensured and , more generally , to use and operate it in the same conditions as regards security . The fact that you are presently reading this means that you have had knowledge of the CeCILL license and that you accept its terms . Copyright or © or Copr. Loïc Paulevé 2015-2017 This software is a computer program whose purpose is to provide Process Hitting related tools. This software is governed by the CeCILL 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 license as circulated by CEA, CNRS and INRIA at the following URL "". As a counterpart to the access to the source code and rights to copy, modify and redistribute granted by the license, users are provided only with a limited warranty and the software's author, the holder of the economic rights, and the successive licensors have only limited liability. In this respect, the user's attention is drawn to the risks associated with loading, using, modifying and/or developing or reproducing the software by the user in light of its specific status of free software, that may mean that it is complicated to manipulate, and that also therefore means that it is reserved for developers and experienced professionals having in-depth computer knowledge. Users are therefore encouraged to load and test the software's suitability as regards their requirements in conditions enabling the security of their systems and/or data to be ensured and, more generally, to use and operate it in the same conditions as regards security. The fact that you are presently reading this means that you have had knowledge of the CeCILL license and that you accept its terms. *) open Facile open Easy open PintTypes open AutomataNetwork let fixpoints_jit push_state restrict an = let v_arrays = Hashtbl.create (count_automata an) in let register_automata a n goal = let vs = Array.init n (fun _ -> Fd.create Domain.boolean) in Hashtbl.add v_arrays a vs; Constraint : exactly one state per automata Cstr.post (Arith.sum_fd vs =~ i2e 1); goal &&~ Goals.Array.labeling vs in let goal = Hashtbl.fold register_automata an.ls Goals.success in let lsvar (a,i) = let vs = Hashtbl.find v_arrays a in vs.(i) in let e ai = fd2e (lsvar ai) in let register_restrict ai = Cstr.post (e ai =~ i2e 1) in List.iter register_restrict restrict; let register_tr trid tr = let vars = List.map e (IMap.bindings tr.pre) in let sume = List.fold_left (+~) (List.hd vars) (List.tl vars) in Cstr.post (sume <~ i2e (IMap.cardinal tr.pre)) in Hashtbl.iter register_tr an.trs; let register_sol () = let fold_vs a vs state = let i = List.find (fun i -> Fd.int_value vs.(i) == 1) (Util.range 0 (Array.length vs)) in IMap.add a i state in let state = Hashtbl.fold fold_vs v_arrays IMap.empty in push_state state in try ignore(Goals.solve ((goal &&~ Goals.atomic register_sol &&~ Goals.fail) ||~ Goals.success)) with Stak.Fail _ -> () let fixpoints ?(restrict=[]) args = let sols = ref [] in let push_state state = sols := state::!sols in fixpoints_jit push_state restrict args; !sols
58bced4e389490ff164f032b354e3ec1a924a4cc6c1aebd613a49569522be44d
psibi/streamly-bytestring
Lazy.hs
module Streamly.External.ByteString.Lazy ( readChunks , read , toChunks , fromChunks , fromChunksIO ) where import Data.Word (Word8) import Streamly.Data.Unfold (many) import Streamly.Data.Array.Foreign (Array) import System.IO.Unsafe (unsafeInterleaveIO) -- Internal imports import Data.ByteString.Lazy.Internal (ByteString(..), chunk) import Streamly.Internal.Data.Stream.StreamD.Type (Step(..)) import Streamly.Internal.Data.Unfold.Type (Unfold(..)) import qualified Streamly.External.ByteString as Strict import qualified Streamly.Data.Array.Foreign as A import qualified Streamly.Prelude as S import Prelude hiding (concat, read) | Unfold a lazy ByteString to a stream of ' Array ' ' Words ' . # INLINE readChunks # readChunks :: Monad m => Unfold m ByteString (Array Word8) readChunks = Unfold step seed where seed = return step (Chunk bs bl) = return $ Yield (Strict.toArray bs) bl step Empty = return Stop | Unfold a lazy ByteString to a stream of Word8 # INLINE read # read :: Monad m => Unfold m ByteString Word8 read = many readChunks A.read | Convert a lazy ' ByteString ' to a serial stream of ' Array ' ' Word8 ' . # INLINE toChunks # toChunks :: Monad m => ByteString -> S.SerialT m (Array Word8) toChunks = S.unfold readChunks newtype LazyIO a = LazyIO { runLazy : : IO a } deriving ( Functor , Applicative ) liftToLazy : : IO a - > LazyIO a liftToLazy = LazyIO instance where return = pure LazyIO a > > = f = LazyIO ( unsafeInterleaveIO a > > = unsafeInterleaveIO . runLazy . f ) newtype LazyIO a = LazyIO { runLazy :: IO a } deriving (Functor, Applicative) liftToLazy :: IO a -> LazyIO a liftToLazy = LazyIO instance Monad LazyIO where return = pure LazyIO a >>= f = LazyIO (unsafeInterleaveIO a >>= unsafeInterleaveIO . runLazy . f) -} | Convert a serial stream of ' Array ' ' Word8 ' to a lazy ' ByteString ' . -- -- IMPORTANT NOTE: This function is lazy only for lazy monads -- (e.g. Identity). For strict monads (e.g. /IO/) it consumes the entire input -- before generating the output. For /IO/ monad please use fromChunksIO -- instead. -- -- For strict monads like /IO/ you could create a newtype wrapper to make the -- monad bind operation lazy and lift the stream to that type using hoist, then -- you can use this function to generate the bytestring lazily. For example you -- can wrap the /IO/ type to make the bind lazy like this: -- -- @ -- newtype LazyIO a = LazyIO { runLazy :: IO a } deriving (Functor, Applicative) -- -- liftToLazy :: IO a -> LazyIO a -- liftToLazy = LazyIO -- instance where -- return = pure -- LazyIO a >>= f = LazyIO (unsafeInterleaveIO a >>= unsafeInterleaveIO . runLazy . f) -- @ -- -- /fromChunks/ can then be used as, -- @ -- {-# INLINE fromChunksIO #-} -- fromChunksIO :: SerialT IO (Array Word8) -> IO ByteString -- fromChunksIO str = runLazy (fromChunks (S.hoist liftToLazy str)) -- @ # INLINE fromChunks # fromChunks :: Monad m => S.SerialT m (Array Word8) -> m ByteString fromChunks = S.foldr chunk Empty . S.map Strict.fromArray | Convert a serial stream of ' Array ' ' Word8 ' to a lazy ' ByteString ' in the -- /IO/ monad. # INLINE fromChunksIO # fromChunksIO :: S.SerialT IO (Array Word8) -> IO ByteString fromChunksIO = -- Although the /IO/ monad is strict in nature we emulate laziness using -- 'unsafeInterleaveIO'. S.foldrM (\x b -> chunk x <$> unsafeInterleaveIO b) (pure Empty) . S.map Strict.fromArray
null
https://raw.githubusercontent.com/psibi/streamly-bytestring/cb446333b795945bff85fde3db89bf172073985a/src/Streamly/External/ByteString/Lazy.hs
haskell
Internal imports IMPORTANT NOTE: This function is lazy only for lazy monads (e.g. Identity). For strict monads (e.g. /IO/) it consumes the entire input before generating the output. For /IO/ monad please use fromChunksIO instead. For strict monads like /IO/ you could create a newtype wrapper to make the monad bind operation lazy and lift the stream to that type using hoist, then you can use this function to generate the bytestring lazily. For example you can wrap the /IO/ type to make the bind lazy like this: @ newtype LazyIO a = LazyIO { runLazy :: IO a } deriving (Functor, Applicative) liftToLazy :: IO a -> LazyIO a liftToLazy = LazyIO return = pure LazyIO a >>= f = LazyIO (unsafeInterleaveIO a >>= unsafeInterleaveIO . runLazy . f) @ /fromChunks/ can then be used as, @ {-# INLINE fromChunksIO #-} fromChunksIO :: SerialT IO (Array Word8) -> IO ByteString fromChunksIO str = runLazy (fromChunks (S.hoist liftToLazy str)) @ /IO/ monad. Although the /IO/ monad is strict in nature we emulate laziness using 'unsafeInterleaveIO'.
module Streamly.External.ByteString.Lazy ( readChunks , read , toChunks , fromChunks , fromChunksIO ) where import Data.Word (Word8) import Streamly.Data.Unfold (many) import Streamly.Data.Array.Foreign (Array) import System.IO.Unsafe (unsafeInterleaveIO) import Data.ByteString.Lazy.Internal (ByteString(..), chunk) import Streamly.Internal.Data.Stream.StreamD.Type (Step(..)) import Streamly.Internal.Data.Unfold.Type (Unfold(..)) import qualified Streamly.External.ByteString as Strict import qualified Streamly.Data.Array.Foreign as A import qualified Streamly.Prelude as S import Prelude hiding (concat, read) | Unfold a lazy ByteString to a stream of ' Array ' ' Words ' . # INLINE readChunks # readChunks :: Monad m => Unfold m ByteString (Array Word8) readChunks = Unfold step seed where seed = return step (Chunk bs bl) = return $ Yield (Strict.toArray bs) bl step Empty = return Stop | Unfold a lazy ByteString to a stream of Word8 # INLINE read # read :: Monad m => Unfold m ByteString Word8 read = many readChunks A.read | Convert a lazy ' ByteString ' to a serial stream of ' Array ' ' Word8 ' . # INLINE toChunks # toChunks :: Monad m => ByteString -> S.SerialT m (Array Word8) toChunks = S.unfold readChunks newtype LazyIO a = LazyIO { runLazy : : IO a } deriving ( Functor , Applicative ) liftToLazy : : IO a - > LazyIO a liftToLazy = LazyIO instance where return = pure LazyIO a > > = f = LazyIO ( unsafeInterleaveIO a > > = unsafeInterleaveIO . runLazy . f ) newtype LazyIO a = LazyIO { runLazy :: IO a } deriving (Functor, Applicative) liftToLazy :: IO a -> LazyIO a liftToLazy = LazyIO instance Monad LazyIO where return = pure LazyIO a >>= f = LazyIO (unsafeInterleaveIO a >>= unsafeInterleaveIO . runLazy . f) -} | Convert a serial stream of ' Array ' ' Word8 ' to a lazy ' ByteString ' . instance where # INLINE fromChunks # fromChunks :: Monad m => S.SerialT m (Array Word8) -> m ByteString fromChunks = S.foldr chunk Empty . S.map Strict.fromArray | Convert a serial stream of ' Array ' ' Word8 ' to a lazy ' ByteString ' in the # INLINE fromChunksIO # fromChunksIO :: S.SerialT IO (Array Word8) -> IO ByteString fromChunksIO = S.foldrM (\x b -> chunk x <$> unsafeInterleaveIO b) (pure Empty) . S.map Strict.fromArray
eb43a4e8699c7459e89a4b0b12fe31c6572590ce856a82b9efe8b754ca8bb0cf
choener/ADPfusion
Stream.hs
-- | Build a backtracking function which uses @Stream@s internally. Efficient fusion of these streams requires @HERMIT@ ! For most -- backtracking cases, this is less of a problem since the backtracking -- running time is much less than the forward case requires. module ADPfusion.Core.TH.Stream where import Data.List import Data.Tuple.Select import Language.Haskell.TH import Language.Haskell.TH.Syntax import qualified Data.Vector.Fusion.Stream.Monadic as SM import ADPfusion.Core.TH.Common -- | Build the single clause of our function. We shall need the functions bound -- in the where part to create the joined functions we need to return. genClauseStream :: Name -> [VarStrictType] -> [VarStrictType] -> [VarStrictType] -> Q Clause genClauseStream conName allFunNames evalFunNames choiceFunNames = do let nonTermNames = nub . map getRuleResultType $ evalFunNames bind the l'eft and r'ight variable of the two algebras we want to join , -- also create unique names for the function names we shall bind later. nameL <- newName "l" varL <- varP nameL TODO automate discovery of choice functions ? fnmsL <- sequence $ replicate (length allFunNames) (newName "fnamL") nameR <- newName "r" varR <- varP nameR fnmsR <- sequence $ replicate (length allFunNames) (newName "fnamR") -- bind the individual variables in the where part whereL <- valD (conP conName (map varP fnmsL)) (normalB $ varE nameL) [] whereR <- valD (conP conName (map varP fnmsR)) (normalB $ varE nameR) [] rce <- recConE conName $ zipWith3 (genChoiceFunction) (drop (length evalFunNames) fnmsL) (drop (length evalFunNames) fnmsR) choiceFunNames ++ zipWith3 (genAttributeFunction nonTermNames) fnmsL fnmsR evalFunNames -- build the function pairs -- to keep our sanity, lets print this stuff let cls = Clause [varL, varR] (NormalB rce) [whereL,whereR] return cls -- | genChoiceFunction :: Name -> Name -> VarStrictType -> Q (Name,Exp) genChoiceFunction hL hR (name,_,t) = do exp <- buildBacktrackingChoice hL hR return (name,exp) -- | -- TODO need fun names from @l@ and @r@ genAttributeFunction :: [Name] -> Name -> Name -> VarStrictType -> Q (Name,Exp) genAttributeFunction nts fL fR (name,_,t) = do (lamPat,funL,funR) <-recBuildLamPat nts fL fR (init $ getRuleSynVarNames t) -- @init@ since we don't want the result as a parameter let exp = LamE lamPat $ TupE [funL,funR] return (name,exp) -- | recBuildLamPat :: [Name] -> Name -> Name -> [Name] -> Q ([Pat], Exp, Exp) recBuildLamPat nts fL' fR' ts = do -- here we just run through all arguments, either creating an @x@ and -- a @ys@ for a non-term or a @t@ for a term. ps <- sequence [ if t `elem` nts then tupP [newName "x" >>= varP, newName "ys" >>= varP] else (newName "t" >>= varP) | t<-ts] let buildLfun f (TupP [VarP v,_]) = appE f (varE v) buildLfun f (VarP v ) = appE f (varE v) lfun <- foldl buildLfun (varE fL') ps rfun <- buildRns (VarE fR') [] ps return (ps, lfun, rfun) -- | buildRns :: Exp -> [Name] -> [Pat] -> ExpQ buildRns f xs [] = appE ([| return . SM.singleton |]) (foldl (\g z -> appE g (varE z)) (return f) xs) buildRns f xs (VarP v : ys) = buildRns f (xs++[v]) ys buildRns f xs (TupP [_,VarP v] : ys) = do w <- newName "w" [| $(varE v) >>= return . SM.concatMapM $(lamE [varP w] (buildRns f (xs++[w]) ys)) |] -- | Build up the backtracking choice function. This choice function will backtrack based on the first result , then return only the second . -- TODO it should be ( only ? ) this function we will need to modify to build all -- algebra products. buildBacktrackingChoice :: Name -> Name -> Q Exp buildBacktrackingChoice hL' hR' = do [| \xs -> do hfs <- $(varE hL') $ SM.map fst xs let phfs = SM.concatMapM snd . SM.filter ((hfs==) . fst) $ xs $(varE hR') phfs |] | Gets the names used in the evaluation function . This returns one -- 'Name' for each variable. -- In case of @TupleT 0@ the type is @()@ and there is n't a name to go with -- it. We just @mkName "()"@ a name, but this might be slightly dangerous? -- (Not really sure if it indeed is) -- With @AppT _ _ @ we have a multidim terminal and produce another hackish -- name to be consumed above. -- -- @ AppT ( AppT ArrowT ( AppT ( AppT ( ConT Data . Array . . Index . : . ) ( AppT ( AppT ( ConT Data . Array . . Index . : . ) ( ConT Data . Array . . Index . Z ) ) ( VarT c_1627675270 ) ) ) ( VarT c_1627675270 ) ) ) ( VarT x_1627675265 ) -- @ getRuleSynVarNames :: Type -> [Name] getRuleSynVarNames t' = go t' where go t | VarT x <- t = [x] | AppT (AppT ArrowT (VarT x )) y <- t = x : go y -- this is a syntactic variable, return the name that the incoming data is bound to | AppT (AppT ArrowT (AppT _ _)) y <- t = mkName "[]" : go y -- this captures that we have a multi-dim terminal. | AppT (AppT ArrowT (TupleT 0)) y <- t = mkName "()" : go y -- this case captures things like @nil :: () -> x@ for rules like @nil <<< Epsilon@. | otherwise = error $ "getRuleSynVarNames error: " ++ show t ++ " in: " ++ show t'
null
https://raw.githubusercontent.com/choener/ADPfusion/fcbbf05d0f438883928077e3d8a7f1cbf8c2e58d/ADPfusion/Core/TH/Stream.hs
haskell
| Build a backtracking function which uses @Stream@s internally. backtracking cases, this is less of a problem since the backtracking running time is much less than the forward case requires. | Build the single clause of our function. We shall need the functions bound in the where part to create the joined functions we need to return. also create unique names for the function names we shall bind later. bind the individual variables in the where part build the function pairs to keep our sanity, lets print this stuff | | @init@ since we don't want the result as a parameter | here we just run through all arguments, either creating an @x@ and a @ys@ for a non-term or a @t@ for a term. | | Build up the backtracking choice function. This choice function will algebra products. 'Name' for each variable. it. We just @mkName "()"@ a name, but this might be slightly dangerous? (Not really sure if it indeed is) name to be consumed above. @ @ this is a syntactic variable, return the name that the incoming data is bound to this captures that we have a multi-dim terminal. this case captures things like @nil :: () -> x@ for rules like @nil <<< Epsilon@.
Efficient fusion of these streams requires @HERMIT@ ! For most module ADPfusion.Core.TH.Stream where import Data.List import Data.Tuple.Select import Language.Haskell.TH import Language.Haskell.TH.Syntax import qualified Data.Vector.Fusion.Stream.Monadic as SM import ADPfusion.Core.TH.Common genClauseStream :: Name -> [VarStrictType] -> [VarStrictType] -> [VarStrictType] -> Q Clause genClauseStream conName allFunNames evalFunNames choiceFunNames = do let nonTermNames = nub . map getRuleResultType $ evalFunNames bind the l'eft and r'ight variable of the two algebras we want to join , nameL <- newName "l" varL <- varP nameL TODO automate discovery of choice functions ? fnmsL <- sequence $ replicate (length allFunNames) (newName "fnamL") nameR <- newName "r" varR <- varP nameR fnmsR <- sequence $ replicate (length allFunNames) (newName "fnamR") whereL <- valD (conP conName (map varP fnmsL)) (normalB $ varE nameL) [] whereR <- valD (conP conName (map varP fnmsR)) (normalB $ varE nameR) [] rce <- recConE conName $ zipWith3 (genChoiceFunction) (drop (length evalFunNames) fnmsL) (drop (length evalFunNames) fnmsR) choiceFunNames ++ zipWith3 (genAttributeFunction nonTermNames) fnmsL fnmsR evalFunNames let cls = Clause [varL, varR] (NormalB rce) [whereL,whereR] return cls genChoiceFunction :: Name -> Name -> VarStrictType -> Q (Name,Exp) genChoiceFunction hL hR (name,_,t) = do exp <- buildBacktrackingChoice hL hR return (name,exp) TODO need fun names from @l@ and @r@ genAttributeFunction :: [Name] -> Name -> Name -> VarStrictType -> Q (Name,Exp) genAttributeFunction nts fL fR (name,_,t) = do let exp = LamE lamPat $ TupE [funL,funR] return (name,exp) recBuildLamPat :: [Name] -> Name -> Name -> [Name] -> Q ([Pat], Exp, Exp) recBuildLamPat nts fL' fR' ts = do ps <- sequence [ if t `elem` nts then tupP [newName "x" >>= varP, newName "ys" >>= varP] else (newName "t" >>= varP) | t<-ts] let buildLfun f (TupP [VarP v,_]) = appE f (varE v) buildLfun f (VarP v ) = appE f (varE v) lfun <- foldl buildLfun (varE fL') ps rfun <- buildRns (VarE fR') [] ps return (ps, lfun, rfun) buildRns :: Exp -> [Name] -> [Pat] -> ExpQ buildRns f xs [] = appE ([| return . SM.singleton |]) (foldl (\g z -> appE g (varE z)) (return f) xs) buildRns f xs (VarP v : ys) = buildRns f (xs++[v]) ys buildRns f xs (TupP [_,VarP v] : ys) = do w <- newName "w" [| $(varE v) >>= return . SM.concatMapM $(lamE [varP w] (buildRns f (xs++[w]) ys)) |] backtrack based on the first result , then return only the second . TODO it should be ( only ? ) this function we will need to modify to build all buildBacktrackingChoice :: Name -> Name -> Q Exp buildBacktrackingChoice hL' hR' = do [| \xs -> do hfs <- $(varE hL') $ SM.map fst xs let phfs = SM.concatMapM snd . SM.filter ((hfs==) . fst) $ xs $(varE hR') phfs |] | Gets the names used in the evaluation function . This returns one In case of @TupleT 0@ the type is @()@ and there is n't a name to go with With @AppT _ _ @ we have a multidim terminal and produce another hackish AppT ( AppT ArrowT ( AppT ( AppT ( ConT Data . Array . . Index . : . ) ( AppT ( AppT ( ConT Data . Array . . Index . : . ) ( ConT Data . Array . . Index . Z ) ) ( VarT c_1627675270 ) ) ) ( VarT c_1627675270 ) ) ) ( VarT x_1627675265 ) getRuleSynVarNames :: Type -> [Name] getRuleSynVarNames t' = go t' where go t | VarT x <- t = [x] | otherwise = error $ "getRuleSynVarNames error: " ++ show t ++ " in: " ++ show t'
16671b339ef9aee81c0ee15fe3df515d820d3d4fa7406dcb07a66e4a6762a4e0
dm3/manifold-cljs
robpike.cljs
(ns manifold-test.robpike (:require [cljs.core.async :as async :refer [<! >! chan close! timeout]] [manifold-cljs.stream :as s] [manifold-cljs.deferred :as d]) (:require-macros [cljs.core.async.macros :as m :refer [go alt!]])) (defn run-async [] (let [fake-search (fn [kind] (fn [c query] (go (<! (timeout (rand-int 100))) (>! c [kind query])))) web1 (fake-search :web1) web2 (fake-search :web2) image1 (fake-search :image1) image2 (fake-search :image2) video1 (fake-search :video1) video2 (fake-search :video2) fastest (fn [query & replicas] (let [c (chan)] (doseq [replica replicas] (replica c query)) c)) google (fn [query] (let [c (chan) t (timeout 80)] (go (>! c (<! (fastest query web1 web2)))) (go (>! c (<! (fastest query image1 image2)))) (go (>! c (<! (fastest query video1 video2)))) (go (loop [i 0 ret []] (if (= i 3) ret (recur (inc i) (conj ret (alt! [c t] ([v] v)))))))))] (go (println (<! (google "clojure")))))) (defn run-manifold [] (let [fake-search (fn [kind] (fn [query] (-> (d/deferred) (d/timeout! (rand-int 100) [kind query])))) web1 (fake-search :web1) web2 (fake-search :web2) image1 (fake-search :image1) image2 (fake-search :image2) video1 (fake-search :video1) video2 (fake-search :video2) fastest (fn [query & replicas] (->> (map #(% query) replicas) (apply d/alt))) google (fn [query] (let [timeout #(d/timeout! % 80 nil) web (fastest query web1 web2) image (fastest query image1 image2) video (fastest query video1 video2)] (->> (map timeout [web image video]) (apply d/zip))))] (d/chain (google "clojure") println)))
null
https://raw.githubusercontent.com/dm3/manifold-cljs/85a2aee8a376f55b000739ee14acb073227422c8/examples/src/manifold_test/robpike.cljs
clojure
(ns manifold-test.robpike (:require [cljs.core.async :as async :refer [<! >! chan close! timeout]] [manifold-cljs.stream :as s] [manifold-cljs.deferred :as d]) (:require-macros [cljs.core.async.macros :as m :refer [go alt!]])) (defn run-async [] (let [fake-search (fn [kind] (fn [c query] (go (<! (timeout (rand-int 100))) (>! c [kind query])))) web1 (fake-search :web1) web2 (fake-search :web2) image1 (fake-search :image1) image2 (fake-search :image2) video1 (fake-search :video1) video2 (fake-search :video2) fastest (fn [query & replicas] (let [c (chan)] (doseq [replica replicas] (replica c query)) c)) google (fn [query] (let [c (chan) t (timeout 80)] (go (>! c (<! (fastest query web1 web2)))) (go (>! c (<! (fastest query image1 image2)))) (go (>! c (<! (fastest query video1 video2)))) (go (loop [i 0 ret []] (if (= i 3) ret (recur (inc i) (conj ret (alt! [c t] ([v] v)))))))))] (go (println (<! (google "clojure")))))) (defn run-manifold [] (let [fake-search (fn [kind] (fn [query] (-> (d/deferred) (d/timeout! (rand-int 100) [kind query])))) web1 (fake-search :web1) web2 (fake-search :web2) image1 (fake-search :image1) image2 (fake-search :image2) video1 (fake-search :video1) video2 (fake-search :video2) fastest (fn [query & replicas] (->> (map #(% query) replicas) (apply d/alt))) google (fn [query] (let [timeout #(d/timeout! % 80 nil) web (fastest query web1 web2) image (fastest query image1 image2) video (fastest query video1 video2)] (->> (map timeout [web image video]) (apply d/zip))))] (d/chain (google "clojure") println)))
a0748677752f45c5d183531f7f366d6c858c8a92c27c67572e8470b9d1d8bdfe
iambrj/imin
type-check-Rlambda.rkt
#lang racket (require "utilities.rkt") (require "type-check-Cvar.rkt") (require "type-check-Cif.rkt") (require "type-check-Cvec.rkt") (require "type-check-Rfun.rkt") (require "type-check-Cfun.rkt") (provide type-check-Rlambda type-check-Rlambda-class typed-vars) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Lambda ; ; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; type-check-Rlambda (define typed-vars (make-parameter #f)) (define type-check-Rlambda-class (class type-check-Rfun-class (super-new) (inherit check-type-equal?) ;; lenient type checking for '_ (define/override (type-equal? t1 t2) (debug 'type-equal? "lenient" t1 t2) (match* (t1 t2) [('_ t2) #t] [(t1 '_) #t] [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (for/and ([t1 ts1] [t2 ts2]) (type-equal? t1 t2))] [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2)) (and (for/and ([t1 ts1] [t2 ts2]) (type-equal? t1 t2)) (type-equal? rt1 rt2))] [(other wise) (equal? t1 t2)])) (define/override (type-check-exp env) (lambda (e) (debug 'type-check-exp "Rlambda" e) (define recur (type-check-exp env)) (match e [(HasType (Var x) t) ((type-check-exp env) (Var x))] [(Var x) (define t (dict-ref env x)) (define var (cond [(typed-vars) (HasType (Var x) t)] [else (Var x)])) (values var t)] [(Closure arity es) (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e))) (let ([t `(Vector ,@t*)]) (values (HasType (Closure arity e*) t) t))] [(Prim 'procedure-arity (list e1)) (define-values (e1^ t) (recur e1)) (match t ;; before closure conversion [`(,ts ... -> ,rt) (values (Prim 'procedure-arity (list e1^)) 'Integer)] ;; after closure conversion [`(Vector (,clos ,ts ... -> ,rt) ,ts2 ...) (values (Prim 'procedure-arity (list e1^)) 'Integer)] [else (error 'type-check "expected a function not ~a\nin ~v" t e)])] [(HasType (Closure arity es) t) ((type-check-exp env) (Closure arity es))] [(AllocateClosure size t arity) (values (AllocateClosure size t arity) t)] [(FunRefArity f n) (let ([t (dict-ref env f)]) (values (FunRefArity f n) t))] [(Lambda (and params `([,xs : ,Ts] ...)) rT body) (define-values (new-body bodyT) ((type-check-exp (append (map cons xs Ts) env)) body)) (define ty `(,@Ts -> ,rT)) (check-type-equal? rT bodyT e) (values (Lambda params rT new-body) ty)] [else ((super type-check-exp env) e)] ))) )) (define (type-check-Rlambda p) (send (new type-check-Rlambda-class) type-check-program p))
null
https://raw.githubusercontent.com/iambrj/imin/baf9e829c2aa85b69a2e86bfba320969ddf05f95/type-check-Rlambda.rkt
racket
; type-check-Rlambda lenient type checking for '_ before closure conversion after closure conversion
#lang racket (require "utilities.rkt") (require "type-check-Cvar.rkt") (require "type-check-Cif.rkt") (require "type-check-Cvec.rkt") (require "type-check-Rfun.rkt") (require "type-check-Cfun.rkt") (provide type-check-Rlambda type-check-Rlambda-class typed-vars) (define typed-vars (make-parameter #f)) (define type-check-Rlambda-class (class type-check-Rfun-class (super-new) (inherit check-type-equal?) (define/override (type-equal? t1 t2) (debug 'type-equal? "lenient" t1 t2) (match* (t1 t2) [('_ t2) #t] [(t1 '_) #t] [(`(Vector ,ts1 ...) `(Vector ,ts2 ...)) (for/and ([t1 ts1] [t2 ts2]) (type-equal? t1 t2))] [(`(,ts1 ... -> ,rt1) `(,ts2 ... -> ,rt2)) (and (for/and ([t1 ts1] [t2 ts2]) (type-equal? t1 t2)) (type-equal? rt1 rt2))] [(other wise) (equal? t1 t2)])) (define/override (type-check-exp env) (lambda (e) (debug 'type-check-exp "Rlambda" e) (define recur (type-check-exp env)) (match e [(HasType (Var x) t) ((type-check-exp env) (Var x))] [(Var x) (define t (dict-ref env x)) (define var (cond [(typed-vars) (HasType (Var x) t)] [else (Var x)])) (values var t)] [(Closure arity es) (define-values (e* t*) (for/lists (e* t*) ([e es]) (recur e))) (let ([t `(Vector ,@t*)]) (values (HasType (Closure arity e*) t) t))] [(Prim 'procedure-arity (list e1)) (define-values (e1^ t) (recur e1)) (match t [`(,ts ... -> ,rt) (values (Prim 'procedure-arity (list e1^)) 'Integer)] [`(Vector (,clos ,ts ... -> ,rt) ,ts2 ...) (values (Prim 'procedure-arity (list e1^)) 'Integer)] [else (error 'type-check "expected a function not ~a\nin ~v" t e)])] [(HasType (Closure arity es) t) ((type-check-exp env) (Closure arity es))] [(AllocateClosure size t arity) (values (AllocateClosure size t arity) t)] [(FunRefArity f n) (let ([t (dict-ref env f)]) (values (FunRefArity f n) t))] [(Lambda (and params `([,xs : ,Ts] ...)) rT body) (define-values (new-body bodyT) ((type-check-exp (append (map cons xs Ts) env)) body)) (define ty `(,@Ts -> ,rT)) (check-type-equal? rT bodyT e) (values (Lambda params rT new-body) ty)] [else ((super type-check-exp env) e)] ))) )) (define (type-check-Rlambda p) (send (new type-check-Rlambda-class) type-check-program p))
c4010115d603ffa256ae96a930d352cd0966f5b2fec426d5e748c33387ce3218
typedclojure/typedclojure
nthnext.clj
Copyright ( c ) , contributors . ;; The use and distribution terms for this software are covered by the ;; Eclipse Public License 1.0 (-1.0.php) ;; which can be found in the file epl-v10.html at the root of this distribution. ;; By using this software in any fashion, you are agreeing to be bound by ;; the terms of this license. ;; You must not remove this notice, or any other, from this software. (ns ^:no-doc typed.cljc.checker.check.nthnext (:require [typed.clojure :as t] [typed.cljc.checker.check-below :as below] [typed.cljc.checker.check.utils :as cu] [typed.cljc.checker.cs-gen :as cgen] [typed.cljc.checker.filter-ops :as fo] [typed.cljc.checker.indirect-ops :as ind] [typed.cljc.checker.object-rep :as orep] [typed.cljc.checker.type-ctors :as c] [typed.cljc.checker.type-rep :as r] [typed.cljc.checker.utils :as u] [clojure.core.typed.errors :as err])) (defn drop-HSequential "Drop n elements from HSequential t." [n t] {:pre [(nat-int? n) (r/HSequential? t)] :post [(r/Type? %)]} (let [shift (fn [k] {:pre [(keyword? k)] :post [(vector? %)]} (let [e (k t)] (if (:repeat t) (vec (take (count e) (nthrest (cycle e) n))) (vec (nthrest e n)))))] (r/-hseq (shift :types) :filters (shift :fs) :objects (shift :objects) :rest (:rest t) :drest (:drest t) :repeat (:repeat t)))) (defn nthnext-hsequential [t n] {:pre [(r/HSequential? t) (nat-int? n)] :post [(r/Type? %)]} (let [res (drop-HSequential n t)] (cond (or (:rest res) (:drest res) (:repeat res)) (c/Un r/-nil res) (empty? (:types res)) r/-nil :else res))) (defn nthrest-hsequential [t n] {:pre [(r/HSequential? t) (nat-int? n)] :post [(r/Type? %)]} (drop-HSequential n t)) (defn nthnext-kw-args-seq [t n] {:pre [(r/KwArgsSeq? t) (nat-int? n)] :post [(r/Type? %)]} (if (zero? n) (c/Un r/-nil (c/In t (r/make-CountRange 1))) (c/-name `t/NilableNonEmptyASeq r/-any))) (defn nthrest-type [t n] {:pre [(r/Type? t) (nat-int? n)] :post [((some-fn nil? r/Type?) %)]} (if (zero? n) t (let [t (c/fully-resolve-type t)] (cond (r/Union? t) (let [ts (map #(nthrest-type % n) (:types t))] (when (every? identity ts) (apply c/Un ts))) (r/Intersection? t) (when-let [ts (seq (keep #(nthrest-type % n) (:types t)))] (apply c/In ts)) (r/Nil? t) (r/-hseq []) (r/HSequential? t) (nthrest-hsequential t n) :else (when-let [res (cgen/unify-or-nil {:fresh [x] :out x} t (c/Un r/-nil (c/-name `t/Seqable x)))] (c/-name `t/ASeq res)))))) (defn nthnext-type [t n] {:pre [(r/Type? t) (nat-int? n)] :post [((some-fn nil? r/Type?) %)]} (let [t (c/fully-resolve-type t)] (cond (r/Union? t) (let [ts (map #(nthnext-type % n) (:types t))] (when (every? identity ts) (apply c/Un ts))) (r/Intersection? t) (when-let [ts (seq (keep #(nthnext-type % n) (:types t)))] (apply c/In ts)) (r/Nil? t) r/-nil (r/HSequential? t) (nthnext-hsequential t n) (r/KwArgsSeq? t) (nthnext-kw-args-seq t n) :else (when-let [res (cgen/unify-or-nil {:fresh [x] :out x} t (c/Un r/-nil (c/-name `t/Seqable x)))] (c/-name `t/NilableNonEmptyASeq res))))) (defn seq-type [t] {:pre [(r/Type? t)] :post [((some-fn nil? r/Type?) %)]} (nthnext-type t 0)) (defn check-specific-rest [check-fn nrests {:keys [args] :as expr} expected] {:pre [(nat-int? nrests)] :post [(or (nil? %) (-> % u/expr-type r/TCResult?))]} (let [{[ctarget] :args :as expr} (-> expr FIXME possibly repeated type check target-ret (u/expr-type ctarget)] (when-let [t (nthrest-type (r/ret-t target-ret) nrests)] (-> expr (update :fn check-fn) (assoc u/expr-type (below/maybe-check-below (r/ret t (fo/-true-filter)) expected)))))) (defn check-specific-next [check-fn nnexts {:keys [args] :as expr} expected] {:pre [(nat-int? nnexts)] :post [(or (nil? %) (-> % u/expr-type r/TCResult?))]} (let [{[ctarget] :args :as expr} (-> expr FIXME possibly repeated type check target-ret (u/expr-type ctarget)] (when-some [t (nthnext-type (r/ret-t target-ret) nnexts)] (let [res (r/ret t (if (ind/subtype? t (c/Un r/-nil (c/-name `t/Coll r/-any))) (cond ; first arity of `seq ;[(NonEmptyColl x) -> (NonEmptyASeq x) :filters {:then tt :else ff}] (ind/subtype? t (r/make-CountRange (inc nnexts))) (fo/-true-filter) ; handle empty collection with no object (and (= orep/-empty (:o target-ret)) (ind/subtype? t (c/Un r/-nil (r/make-CountRange 0 nnexts)))) (fo/-false-filter) second arity of ` seq ;[(Option (Coll x)) -> (Option (NonEmptyASeq x)) : filters { : then ( & ( is NonEmptyCount 0 ) ; (! nil 0)) ; :else (| (is nil 0) ( is EmptyCount 0 ) ) } ] :else (fo/-FS (fo/-and (fo/-filter-at (r/make-CountRange (inc nnexts)) (:o target-ret)) (fo/-not-filter-at r/-nil (:o target-ret))) (fo/-or (fo/-filter-at r/-nil (:o target-ret)) (fo/-filter-at (r/make-CountRange 0 nnexts) (:o target-ret))))) (fo/-simple-filter)))] (-> expr (update :fn check-fn) (assoc u/expr-type (below/maybe-check-below res expected))))))) (defn check-nthnext [check-fn {[_ {maybe-int :form} :as args] :args :as expr} expected] {:pre [(every? (comp #{:unanalyzed} :op) args)] :post [(or (nil? %) (-> % u/expr-type r/TCResult?))]} (when (#{2} (count args)) (when (nat-int? maybe-int) (check-specific-next check-fn maybe-int expr expected)))) (defn check-next [check-fn {:keys [args] :as expr} expected] {:pre [(every? (comp #{:unanalyzed} :op) args)] :post [(or (nil? %) (-> % u/expr-type r/TCResult?))]} (when (#{1} (count args)) (check-specific-next check-fn 1 expr expected))) (defn check-seq [check-fn {:keys [args] :as expr} expected] {:pre [(every? (comp #{:unanalyzed} :op) args)] :post [(or (nil? %) (-> % u/expr-type r/TCResult?))]} (when (#{1} (count args)) (check-specific-next check-fn 0 expr expected))) (defn check-rest [check-fn {:keys [args] :as expr} expected] {:pre [(every? (comp #{:unanalyzed} :op) args)] :post [(or (nil? %) (-> % u/expr-type r/TCResult?))]} (when (#{1} (count args)) (check-specific-rest check-fn 1 expr expected)))
null
https://raw.githubusercontent.com/typedclojure/typedclojure/1b3c9ef6786a792ae991c438ea8dca31175aa4a7/typed/clj.checker/src/typed/cljc/checker/check/nthnext.clj
clojure
The use and distribution terms for this software are covered by the Eclipse Public License 1.0 (-1.0.php) which can be found in the file epl-v10.html at the root of this distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice, or any other, from this software. first arity of `seq [(NonEmptyColl x) -> (NonEmptyASeq x) :filters {:then tt :else ff}] handle empty collection with no object [(Option (Coll x)) -> (Option (NonEmptyASeq x)) (! nil 0)) :else (| (is nil 0)
Copyright ( c ) , contributors . (ns ^:no-doc typed.cljc.checker.check.nthnext (:require [typed.clojure :as t] [typed.cljc.checker.check-below :as below] [typed.cljc.checker.check.utils :as cu] [typed.cljc.checker.cs-gen :as cgen] [typed.cljc.checker.filter-ops :as fo] [typed.cljc.checker.indirect-ops :as ind] [typed.cljc.checker.object-rep :as orep] [typed.cljc.checker.type-ctors :as c] [typed.cljc.checker.type-rep :as r] [typed.cljc.checker.utils :as u] [clojure.core.typed.errors :as err])) (defn drop-HSequential "Drop n elements from HSequential t." [n t] {:pre [(nat-int? n) (r/HSequential? t)] :post [(r/Type? %)]} (let [shift (fn [k] {:pre [(keyword? k)] :post [(vector? %)]} (let [e (k t)] (if (:repeat t) (vec (take (count e) (nthrest (cycle e) n))) (vec (nthrest e n)))))] (r/-hseq (shift :types) :filters (shift :fs) :objects (shift :objects) :rest (:rest t) :drest (:drest t) :repeat (:repeat t)))) (defn nthnext-hsequential [t n] {:pre [(r/HSequential? t) (nat-int? n)] :post [(r/Type? %)]} (let [res (drop-HSequential n t)] (cond (or (:rest res) (:drest res) (:repeat res)) (c/Un r/-nil res) (empty? (:types res)) r/-nil :else res))) (defn nthrest-hsequential [t n] {:pre [(r/HSequential? t) (nat-int? n)] :post [(r/Type? %)]} (drop-HSequential n t)) (defn nthnext-kw-args-seq [t n] {:pre [(r/KwArgsSeq? t) (nat-int? n)] :post [(r/Type? %)]} (if (zero? n) (c/Un r/-nil (c/In t (r/make-CountRange 1))) (c/-name `t/NilableNonEmptyASeq r/-any))) (defn nthrest-type [t n] {:pre [(r/Type? t) (nat-int? n)] :post [((some-fn nil? r/Type?) %)]} (if (zero? n) t (let [t (c/fully-resolve-type t)] (cond (r/Union? t) (let [ts (map #(nthrest-type % n) (:types t))] (when (every? identity ts) (apply c/Un ts))) (r/Intersection? t) (when-let [ts (seq (keep #(nthrest-type % n) (:types t)))] (apply c/In ts)) (r/Nil? t) (r/-hseq []) (r/HSequential? t) (nthrest-hsequential t n) :else (when-let [res (cgen/unify-or-nil {:fresh [x] :out x} t (c/Un r/-nil (c/-name `t/Seqable x)))] (c/-name `t/ASeq res)))))) (defn nthnext-type [t n] {:pre [(r/Type? t) (nat-int? n)] :post [((some-fn nil? r/Type?) %)]} (let [t (c/fully-resolve-type t)] (cond (r/Union? t) (let [ts (map #(nthnext-type % n) (:types t))] (when (every? identity ts) (apply c/Un ts))) (r/Intersection? t) (when-let [ts (seq (keep #(nthnext-type % n) (:types t)))] (apply c/In ts)) (r/Nil? t) r/-nil (r/HSequential? t) (nthnext-hsequential t n) (r/KwArgsSeq? t) (nthnext-kw-args-seq t n) :else (when-let [res (cgen/unify-or-nil {:fresh [x] :out x} t (c/Un r/-nil (c/-name `t/Seqable x)))] (c/-name `t/NilableNonEmptyASeq res))))) (defn seq-type [t] {:pre [(r/Type? t)] :post [((some-fn nil? r/Type?) %)]} (nthnext-type t 0)) (defn check-specific-rest [check-fn nrests {:keys [args] :as expr} expected] {:pre [(nat-int? nrests)] :post [(or (nil? %) (-> % u/expr-type r/TCResult?))]} (let [{[ctarget] :args :as expr} (-> expr FIXME possibly repeated type check target-ret (u/expr-type ctarget)] (when-let [t (nthrest-type (r/ret-t target-ret) nrests)] (-> expr (update :fn check-fn) (assoc u/expr-type (below/maybe-check-below (r/ret t (fo/-true-filter)) expected)))))) (defn check-specific-next [check-fn nnexts {:keys [args] :as expr} expected] {:pre [(nat-int? nnexts)] :post [(or (nil? %) (-> % u/expr-type r/TCResult?))]} (let [{[ctarget] :args :as expr} (-> expr FIXME possibly repeated type check target-ret (u/expr-type ctarget)] (when-some [t (nthnext-type (r/ret-t target-ret) nnexts)] (let [res (r/ret t (if (ind/subtype? t (c/Un r/-nil (c/-name `t/Coll r/-any))) (cond (ind/subtype? t (r/make-CountRange (inc nnexts))) (fo/-true-filter) (and (= orep/-empty (:o target-ret)) (ind/subtype? t (c/Un r/-nil (r/make-CountRange 0 nnexts)))) (fo/-false-filter) second arity of ` seq : filters { : then ( & ( is NonEmptyCount 0 ) ( is EmptyCount 0 ) ) } ] :else (fo/-FS (fo/-and (fo/-filter-at (r/make-CountRange (inc nnexts)) (:o target-ret)) (fo/-not-filter-at r/-nil (:o target-ret))) (fo/-or (fo/-filter-at r/-nil (:o target-ret)) (fo/-filter-at (r/make-CountRange 0 nnexts) (:o target-ret))))) (fo/-simple-filter)))] (-> expr (update :fn check-fn) (assoc u/expr-type (below/maybe-check-below res expected))))))) (defn check-nthnext [check-fn {[_ {maybe-int :form} :as args] :args :as expr} expected] {:pre [(every? (comp #{:unanalyzed} :op) args)] :post [(or (nil? %) (-> % u/expr-type r/TCResult?))]} (when (#{2} (count args)) (when (nat-int? maybe-int) (check-specific-next check-fn maybe-int expr expected)))) (defn check-next [check-fn {:keys [args] :as expr} expected] {:pre [(every? (comp #{:unanalyzed} :op) args)] :post [(or (nil? %) (-> % u/expr-type r/TCResult?))]} (when (#{1} (count args)) (check-specific-next check-fn 1 expr expected))) (defn check-seq [check-fn {:keys [args] :as expr} expected] {:pre [(every? (comp #{:unanalyzed} :op) args)] :post [(or (nil? %) (-> % u/expr-type r/TCResult?))]} (when (#{1} (count args)) (check-specific-next check-fn 0 expr expected))) (defn check-rest [check-fn {:keys [args] :as expr} expected] {:pre [(every? (comp #{:unanalyzed} :op) args)] :post [(or (nil? %) (-> % u/expr-type r/TCResult?))]} (when (#{1} (count args)) (check-specific-rest check-fn 1 expr expected)))
d7891fa39d77db4d40424d51750ed8036fcfddce987adb07594aa3f7b21afe71
chetmurthy/typpx
ppx.ml
include Typpx.Make.F(struct let tool_name = "ppx_type_of" let args = [] let firstUntypedTransformation = Typpx.Default.untyped_identity module Typemod = Typpx.Default.Typemod module TypedTransformation = Mod.Map let lastUntypedTransformation = Typpx.Default.untyped_identity end) ;; legacy_main () ;;
null
https://raw.githubusercontent.com/chetmurthy/typpx/a740750b75739e686da49b46ded7db7d6874e108/examples/ppx_type_of/ppx.ml
ocaml
include Typpx.Make.F(struct let tool_name = "ppx_type_of" let args = [] let firstUntypedTransformation = Typpx.Default.untyped_identity module Typemod = Typpx.Default.Typemod module TypedTransformation = Mod.Map let lastUntypedTransformation = Typpx.Default.untyped_identity end) ;; legacy_main () ;;
a0947e06befd6c6520ebadbc42b3940711d4f889686641409424934d642ffa0d
lingnand/VIMonad
DeManage.hs
----------------------------------------------------------------------------- -- | Module : XMonad . Actions . DeManage Copyright : ( c ) < > -- License : BSD3-style (see LICENSE) -- Maintainer : < > -- Stability : stable -- Portability : unportable -- -- This module provides a method to cease management of a window -- without unmapping it. This is especially useful for applications -- like kicker and gnome-panel. See also "XMonad.Hooks.ManageDocks" for -- more a more automated solution. -- -- To make a panel display correctly with xmonad: -- -- * Determine the pixel size of the panel, add that value to ' XMonad . Core . XConfig.defaultGaps ' -- -- * Launch the panel -- -- * Give the panel window focus, then press @mod-d@ (or whatever key -- you have bound 'demanage' to) -- * Convince the panel to move\/resize to the correct location . Changing the -- panel's position setting several times seems to work. -- ----------------------------------------------------------------------------- module XMonad.Actions.DeManage ( -- * Usage -- $usage demanage ) where import qualified XMonad.StackSet as W import XMonad -- $usage -- To use demanage, add this import to your @~\/.xmonad\/xmonad.hs@: -- > import XMonad . Actions . DeManage -- -- And add a keybinding, such as: -- > , ( ( modm , xK_d ) , ) -- -- For detailed instructions on editing your key bindings, see " XMonad . Doc . Extending#Editing_key_bindings " . -- | Stop managing the currently focused window. demanage :: Window -> X () demanage w = do -- use modify to defeat automatic 'unmanage' calls. modify (\s -> s { windowset = W.delete w (windowset s) }) refresh
null
https://raw.githubusercontent.com/lingnand/VIMonad/048e419fc4ef57a5235dbaeef8890faf6956b574/XMonadContrib/XMonad/Actions/DeManage.hs
haskell
--------------------------------------------------------------------------- | License : BSD3-style (see LICENSE) Stability : stable Portability : unportable This module provides a method to cease management of a window without unmapping it. This is especially useful for applications like kicker and gnome-panel. See also "XMonad.Hooks.ManageDocks" for more a more automated solution. To make a panel display correctly with xmonad: * Determine the pixel size of the panel, add that value to * Launch the panel * Give the panel window focus, then press @mod-d@ (or whatever key you have bound 'demanage' to) panel's position setting several times seems to work. --------------------------------------------------------------------------- * Usage $usage $usage To use demanage, add this import to your @~\/.xmonad\/xmonad.hs@: And add a keybinding, such as: For detailed instructions on editing your key bindings, see | Stop managing the currently focused window. use modify to defeat automatic 'unmanage' calls.
Module : XMonad . Actions . DeManage Copyright : ( c ) < > Maintainer : < > ' XMonad . Core . XConfig.defaultGaps ' * Convince the panel to move\/resize to the correct location . Changing the module XMonad.Actions.DeManage ( demanage ) where import qualified XMonad.StackSet as W import XMonad > import XMonad . Actions . DeManage > , ( ( modm , xK_d ) , ) " XMonad . Doc . Extending#Editing_key_bindings " . demanage :: Window -> X () demanage w = do modify (\s -> s { windowset = W.delete w (windowset s) }) refresh
cb70b2efd73c3f2401df18b55b46865bf7ac6ff395b0aa4f344002da0699f2a1
ghcjs/ghcjs-boot
num009.hs
trac # 2059 module Main(main) where import Control.Monad import Foreign.C main = do let d = [0, pi, pi/2, pi/3, 1e10, 1e20] :: [Double] f = [0, pi, pi/2, pi/3, 1e10, 1e20] :: [Float] mapM_ (test "sind" sind sin) d mapM_ (test "sinf" sinf sin) f mapM_ (test "cosd" cosd cos) d mapM_ (test "cosf" cosf cos) f mapM_ (test "tand" tand tan) d mapM_ (test "tanf" tanf tan) f putStrLn "Done" test :: (RealFloat a, Floating a, RealFloat b, Floating b, Show b) => String -> (a -> a) -> (b -> b) -> b -> IO () test s f g x = do let y = realToFrac (f (realToFrac x)) z = g x unless (y == z) $ do putStrLn (s ++ ' ':show x) print y print z print $ decodeFloat y print $ decodeFloat z foreign import ccall "math.h sin" sind :: CDouble -> CDouble foreign import ccall "math.h sinf" sinf :: CFloat -> CFloat foreign import ccall "math.h cos" cosd :: CDouble -> CDouble foreign import ccall "math.h cosf" cosf :: CFloat -> CFloat foreign import ccall "math.h tan" tand :: CDouble -> CDouble foreign import ccall "math.h tanf" tanf :: CFloat -> CFloat
null
https://raw.githubusercontent.com/ghcjs/ghcjs-boot/8c549931da27ba9e607f77195208ec156c840c8a/boot/base/tests/Numeric/num009.hs
haskell
trac # 2059 module Main(main) where import Control.Monad import Foreign.C main = do let d = [0, pi, pi/2, pi/3, 1e10, 1e20] :: [Double] f = [0, pi, pi/2, pi/3, 1e10, 1e20] :: [Float] mapM_ (test "sind" sind sin) d mapM_ (test "sinf" sinf sin) f mapM_ (test "cosd" cosd cos) d mapM_ (test "cosf" cosf cos) f mapM_ (test "tand" tand tan) d mapM_ (test "tanf" tanf tan) f putStrLn "Done" test :: (RealFloat a, Floating a, RealFloat b, Floating b, Show b) => String -> (a -> a) -> (b -> b) -> b -> IO () test s f g x = do let y = realToFrac (f (realToFrac x)) z = g x unless (y == z) $ do putStrLn (s ++ ' ':show x) print y print z print $ decodeFloat y print $ decodeFloat z foreign import ccall "math.h sin" sind :: CDouble -> CDouble foreign import ccall "math.h sinf" sinf :: CFloat -> CFloat foreign import ccall "math.h cos" cosd :: CDouble -> CDouble foreign import ccall "math.h cosf" cosf :: CFloat -> CFloat foreign import ccall "math.h tan" tand :: CDouble -> CDouble foreign import ccall "math.h tanf" tanf :: CFloat -> CFloat
160a46029943a60472f176de1988af7498f46d79402406ca693eedd472cf81b7
dmitryvk/sbcl-win32-threads
make-target-2-load.lisp
;;; Now that we use the compiler for macros, interpreted /SHOW doesn't ;;; work until later in init. #+sb-show (print "/hello, world!") ;;; Until PRINT-OBJECT and other machinery is set up, we want limits ;;; on printing to avoid infinite output. (Don't forget to undo these ;;; tweaks after the printer is set up. It'd be cleaner to use LET to ;;; make sure that happens automatically, but LET is implemented in ;;; terms of the compiler, and the compiler isn't initialized yet.) (setq *print-length* 10) (setq *print-level* 5) (setq *print-circle* t) ;;; Do warm init without compiling files. (defvar *compile-files-p* nil) #+sb-show (print "/about to LOAD warm.lisp (with *compile-files-p* = NIL)") (load "src/cold/warm.lisp") Unintern no - longer - needed stuff before the possible PURIFY in SAVE - LISP - AND - DIE . #-sb-fluid (sb-impl::!unintern-init-only-stuff) ;;; Now that the whole system is built, we don't need to hobble the ;;; printer any more, so we can restore printer control variables to their ANSI defaults . (setq *print-length* nil) (setq *print-level* nil) (setq *print-circle* nil) (sb-int:/show "done with warm.lisp, about to GC :FULL T") (sb-ext:gc :full t) ;;; resetting compilation policy to neutral values in preparation for SAVE - LISP - AND - DIE as final SBCL core ( not in warm.lisp because ;;; SB-C::*POLICY* has file scope) (sb-int:/show "setting compilation policy to neutral values") (proclaim '(optimize (compilation-speed 1) (debug 1) (inhibit-warnings 1) (safety 1) (space 1) (speed 1))) ;;; Lock internal packages #+sb-package-locks (dolist (p (list-all-packages)) (unless (member p (mapcar #'find-package '("KEYWORD" "CL-USER"))) (sb-ext:lock-package p))) (sb-int:/show "done with warm.lisp, about to SAVE-LISP-AND-DIE") ;;; Even if /SHOW output was wanted during build, it's probably ;;; not wanted by default after build is complete. (And if it's ;;; wanted, it can easily be turned back on.) #+sb-show (setf sb-int:*/show* nil) ;;; The system is complete now, all standard functions are ;;; defined. (sb-kernel::ctype-of-cache-clear) (setq sb-c::*flame-on-necessarily-undefined-thing* t) Clean up stray symbols from the CL - USER package . (do-symbols (symbol "CL-USER") (when (eq (symbol-package symbol) (find-package "CL-USER")) (unintern symbol "CL-USER"))) (sb-ext:save-lisp-and-die "output/sbcl.core")
null
https://raw.githubusercontent.com/dmitryvk/sbcl-win32-threads/5abfd64b00a0937ba2df2919f177697d1d91bde4/make-target-2-load.lisp
lisp
Now that we use the compiler for macros, interpreted /SHOW doesn't work until later in init. Until PRINT-OBJECT and other machinery is set up, we want limits on printing to avoid infinite output. (Don't forget to undo these tweaks after the printer is set up. It'd be cleaner to use LET to make sure that happens automatically, but LET is implemented in terms of the compiler, and the compiler isn't initialized yet.) Do warm init without compiling files. Now that the whole system is built, we don't need to hobble the printer any more, so we can restore printer control variables to resetting compilation policy to neutral values in preparation for SB-C::*POLICY* has file scope) Lock internal packages Even if /SHOW output was wanted during build, it's probably not wanted by default after build is complete. (And if it's wanted, it can easily be turned back on.) The system is complete now, all standard functions are defined.
#+sb-show (print "/hello, world!") (setq *print-length* 10) (setq *print-level* 5) (setq *print-circle* t) (defvar *compile-files-p* nil) #+sb-show (print "/about to LOAD warm.lisp (with *compile-files-p* = NIL)") (load "src/cold/warm.lisp") Unintern no - longer - needed stuff before the possible PURIFY in SAVE - LISP - AND - DIE . #-sb-fluid (sb-impl::!unintern-init-only-stuff) their ANSI defaults . (setq *print-length* nil) (setq *print-level* nil) (setq *print-circle* nil) (sb-int:/show "done with warm.lisp, about to GC :FULL T") (sb-ext:gc :full t) SAVE - LISP - AND - DIE as final SBCL core ( not in warm.lisp because (sb-int:/show "setting compilation policy to neutral values") (proclaim '(optimize (compilation-speed 1) (debug 1) (inhibit-warnings 1) (safety 1) (space 1) (speed 1))) #+sb-package-locks (dolist (p (list-all-packages)) (unless (member p (mapcar #'find-package '("KEYWORD" "CL-USER"))) (sb-ext:lock-package p))) (sb-int:/show "done with warm.lisp, about to SAVE-LISP-AND-DIE") #+sb-show (setf sb-int:*/show* nil) (sb-kernel::ctype-of-cache-clear) (setq sb-c::*flame-on-necessarily-undefined-thing* t) Clean up stray symbols from the CL - USER package . (do-symbols (symbol "CL-USER") (when (eq (symbol-package symbol) (find-package "CL-USER")) (unintern symbol "CL-USER"))) (sb-ext:save-lisp-and-die "output/sbcl.core")
4caa7e38691abf6fc2e5ceab02a94b767375609a05fdde29f0291d39e1c0bc2a
Jobhdez/Yotta
utilities.lisp
(in-package #:yotta-tests) (defun run-yotta-tests () (run-package-tests :packages '(:yotta-tests) :interactive t))
null
https://raw.githubusercontent.com/Jobhdez/Yotta/84d91a5c6b685c7afece6e8dc2e1e6df8584594e/tests/utilities.lisp
lisp
(in-package #:yotta-tests) (defun run-yotta-tests () (run-package-tests :packages '(:yotta-tests) :interactive t))
55c78fbba886a77a0374309416aba53a0eb4839b521d4b0622321e591a1b08cc
flyingmachine/streaming-proxy
core_test.clj
(ns streaming-proxy.core-test "Creates a test endpoint and a test proxy server, tests that requests to proxy get sent to endpoint and that proxy can handle responses" (:require [streaming-proxy.core-test-helpers :refer :all] [streaming-proxy.core :as sp] [org.httpkit.server :as hks] [org.httpkit.client :as hkc] [clojure.java.io :as io] [ring.middleware.multipart-params :as mp] [midje.sweet :refer :all])) (def upload-dest "uploaded-test-file") (defn endpoint-handler [req] (condp = (:uri req) "/upload" (do (.renameTo (get-in req [:params "file" :tempfile]) (io/file upload-dest)) {:status 200 :body ""}) "/stream" (hks/with-channel req chan (sp/send-response {:status 200 :body (io/input-stream (io/resource "walden"))} chan)) "/400" {:status 400 :body "nope"} {:status 200 :headers {"Content-Type" "text/html"} :body "default"})) (def endpoint-app (mp/wrap-multipart-params endpoint-handler)) (defn proxy-response-handler [res] (if (>= (:status res) 400) (merge res {:body (str "Downstream error: " (slurp (io/reader (:body res))))}) res)) (defn proxy-wrapper [handler endpoint-port] #(handler (merge % {:streaming-proxy-url (str ":" endpoint-port (:uri %)) :streaming-proxy-response-handler proxy-response-handler :timeout 1000}))) (defn proxy-app [endpoint-port] (proxy-wrapper sp/proxy-handler endpoint-port)) (defn url [server path] (str ":" (:port @server) path)) (defn delete-file [file] (when (.exists (io/file file)) (io/delete-file file))) (defonce repl-proxy (atom nil)) (defonce repl-endpoint (atom nil)) (defn start-repl-servers [] (start-server repl-endpoint endpoint-app) (start-server repl-proxy (proxy-app (:port @repl-endpoint)))) (defn stop-repl-servers [] (stop-server repl-endpoint) (stop-server repl-proxy)) (defn restart-repl-servers [] (stop-repl-servers) (start-repl-servers)) (let [proxy (atom nil) endpoint (atom nil)] (with-state-changes [(before :facts (do (start-server endpoint endpoint-app) (start-server proxy (proxy-app (:port @endpoint))) (delete-file upload-dest))) (after :contents (do (stop-server endpoint) (stop-server proxy)))] ;; server puts file at location, test checks that file is there (fact "you can upload a file using POST" @(hkc/post (url proxy "/upload") {:multipart [{:name "file" :content (io/file (io/resource "test-upload")) :filename "test-upload"}]}) (slurp upload-dest) => "Kermit") TODO test that endpoint response is sent to client as it 's received (fact "handles streaming responses" (let [res @(hkc/get (url proxy "/stream"))] (:body res) => (slurp (io/resource "walden")))) (fact "can transform response" (let [res @(hkc/get (url proxy "/400"))] (:status res) => 400 (:body res) => "Downstream error: nope")) (fact "url has to exist" (sp/proxy-handler {}) => (throws java.lang.AssertionError "Assert failed: url"))))
null
https://raw.githubusercontent.com/flyingmachine/streaming-proxy/6deba7d239e7a1281c9683dfe55a9f245b48a492/test/streaming_proxy/core_test.clj
clojure
server puts file at location, test checks that file is there
(ns streaming-proxy.core-test "Creates a test endpoint and a test proxy server, tests that requests to proxy get sent to endpoint and that proxy can handle responses" (:require [streaming-proxy.core-test-helpers :refer :all] [streaming-proxy.core :as sp] [org.httpkit.server :as hks] [org.httpkit.client :as hkc] [clojure.java.io :as io] [ring.middleware.multipart-params :as mp] [midje.sweet :refer :all])) (def upload-dest "uploaded-test-file") (defn endpoint-handler [req] (condp = (:uri req) "/upload" (do (.renameTo (get-in req [:params "file" :tempfile]) (io/file upload-dest)) {:status 200 :body ""}) "/stream" (hks/with-channel req chan (sp/send-response {:status 200 :body (io/input-stream (io/resource "walden"))} chan)) "/400" {:status 400 :body "nope"} {:status 200 :headers {"Content-Type" "text/html"} :body "default"})) (def endpoint-app (mp/wrap-multipart-params endpoint-handler)) (defn proxy-response-handler [res] (if (>= (:status res) 400) (merge res {:body (str "Downstream error: " (slurp (io/reader (:body res))))}) res)) (defn proxy-wrapper [handler endpoint-port] #(handler (merge % {:streaming-proxy-url (str ":" endpoint-port (:uri %)) :streaming-proxy-response-handler proxy-response-handler :timeout 1000}))) (defn proxy-app [endpoint-port] (proxy-wrapper sp/proxy-handler endpoint-port)) (defn url [server path] (str ":" (:port @server) path)) (defn delete-file [file] (when (.exists (io/file file)) (io/delete-file file))) (defonce repl-proxy (atom nil)) (defonce repl-endpoint (atom nil)) (defn start-repl-servers [] (start-server repl-endpoint endpoint-app) (start-server repl-proxy (proxy-app (:port @repl-endpoint)))) (defn stop-repl-servers [] (stop-server repl-endpoint) (stop-server repl-proxy)) (defn restart-repl-servers [] (stop-repl-servers) (start-repl-servers)) (let [proxy (atom nil) endpoint (atom nil)] (with-state-changes [(before :facts (do (start-server endpoint endpoint-app) (start-server proxy (proxy-app (:port @endpoint))) (delete-file upload-dest))) (after :contents (do (stop-server endpoint) (stop-server proxy)))] (fact "you can upload a file using POST" @(hkc/post (url proxy "/upload") {:multipart [{:name "file" :content (io/file (io/resource "test-upload")) :filename "test-upload"}]}) (slurp upload-dest) => "Kermit") TODO test that endpoint response is sent to client as it 's received (fact "handles streaming responses" (let [res @(hkc/get (url proxy "/stream"))] (:body res) => (slurp (io/resource "walden")))) (fact "can transform response" (let [res @(hkc/get (url proxy "/400"))] (:status res) => 400 (:body res) => "Downstream error: nope")) (fact "url has to exist" (sp/proxy-handler {}) => (throws java.lang.AssertionError "Assert failed: url"))))
87d64ff84018a9a612bf38bd65eb44ccf1822f47334abc45c0149e702a1a3689
sdiehl/kaleidoscope
Emit.hs
{-# LANGUAGE OverloadedStrings #-} module Emit where import LLVM.Module import LLVM.Context import qualified LLVM.AST as AST import qualified LLVM.AST.Constant as C import qualified LLVM.AST.Float as F import qualified LLVM.AST.FloatingPointPredicate as FP import Data.Word import Data.Int import Control.Monad.Except import Control.Applicative import qualified Data.Map as Map import Codegen import JIT import qualified Syntax as S one = cons $ C.Float (F.Double 1.0) zero = cons $ C.Float (F.Double 0.0) false = zero true = one toSig :: [String] -> [(AST.Type, AST.Name)] toSig = map (\x -> (double, AST.Name x)) codegenTop :: S.Expr -> LLVM () codegenTop (S.Function name args body) = do define double name fnargs bls where fnargs = toSig args bls = createBlocks $ execCodegen $ do entry <- addBlock entryBlockName setBlock entry forM args $ \a -> do var <- alloca double store var (local (AST.Name a)) assign a var cgen body >>= ret codegenTop (S.Extern name args) = do external double name fnargs where fnargs = toSig args codegenTop exp = do define double "main" [] blks where blks = createBlocks $ execCodegen $ do entry <- addBlock entryBlockName setBlock entry cgen exp >>= ret ------------------------------------------------------------------------------- Operations ------------------------------------------------------------------------------- lt :: AST.Operand -> AST.Operand -> Codegen AST.Operand lt a b = do test <- fcmp FP.ULT a b uitofp double test binops = Map.fromList [ ("+", fadd) , ("-", fsub) , ("*", fmul) , ("/", fdiv) , ("<", lt) ] cgen :: S.Expr -> Codegen AST.Operand cgen (S.BinaryOp op a b) = do case Map.lookup op binops of Just f -> do ca <- cgen a cb <- cgen b f ca cb Nothing -> error "No such operator" cgen (S.Var x) = getvar x >>= load cgen (S.Float n) = return $ cons $ C.Float (F.Double n) cgen (S.Call fn args) = do largs <- mapM cgen args call (externf (AST.Name fn)) largs cgen (S.If cond tr fl) = do ifthen <- addBlock "if.then" ifelse <- addBlock "if.else" ifexit <- addBlock "if.exit" -- %entry ------------------ cond <- cgen cond test <- fcmp FP.ONE false cond Branch based on the condition -- if.then ------------------ setBlock ifthen trval <- cgen tr -- Generate code for the true branch br ifexit -- Branch to the merge block ifthen <- getBlock -- if.else ------------------ setBlock ifelse flval <- cgen fl -- Generate code for the false branch br ifexit -- Branch to the merge block ifelse <- getBlock -- if.exit ------------------ setBlock ifexit phi double [(trval, ifthen), (flval, ifelse)] cgen (S.For ivar start cond step body) = do forloop <- addBlock "for.loop" forexit <- addBlock "for.exit" -- %entry ------------------ i <- alloca double istart <- cgen start -- Generate loop variable initial value stepval <- cgen step -- Generate loop variable step store i istart -- Store the loop variable initial value assign ivar i -- Assign loop variable to the variable name br forloop -- Branch to the loop body block -- for.loop ------------------ setBlock forloop cgen body -- Generate the loop body ival <- load i -- Load the current loop iteration inext <- fadd ival stepval -- Increment loop variable store i inext cond <- cgen cond -- Generate the loop condition Test if the loop condition is True ( 1.0 ) cbr test forloop forexit -- Generate the loop condition -- for.exit ------------------ setBlock forexit return zero ------------------------------------------------------------------------------- -- Compilation ------------------------------------------------------------------------------- codegen :: AST.Module -> [S.Expr] -> IO AST.Module codegen mod fns = do res <- runJIT oldast case res of Right newast -> return newast Left err -> putStrLn err >> return oldast where modn = mapM codegenTop fns oldast = runLLVM mod modn
null
https://raw.githubusercontent.com/sdiehl/kaleidoscope/682bdafe6d8f90caca4cdd0adb30bd3ebd9eff7b/src/chapter5/Emit.hs
haskell
# LANGUAGE OverloadedStrings # ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- %entry ---------------- if.then ---------------- Generate code for the true branch Branch to the merge block if.else ---------------- Generate code for the false branch Branch to the merge block if.exit ---------------- %entry ---------------- Generate loop variable initial value Generate loop variable step Store the loop variable initial value Assign loop variable to the variable name Branch to the loop body block for.loop ---------------- Generate the loop body Load the current loop iteration Increment loop variable Generate the loop condition Generate the loop condition for.exit ---------------- ----------------------------------------------------------------------------- Compilation -----------------------------------------------------------------------------
module Emit where import LLVM.Module import LLVM.Context import qualified LLVM.AST as AST import qualified LLVM.AST.Constant as C import qualified LLVM.AST.Float as F import qualified LLVM.AST.FloatingPointPredicate as FP import Data.Word import Data.Int import Control.Monad.Except import Control.Applicative import qualified Data.Map as Map import Codegen import JIT import qualified Syntax as S one = cons $ C.Float (F.Double 1.0) zero = cons $ C.Float (F.Double 0.0) false = zero true = one toSig :: [String] -> [(AST.Type, AST.Name)] toSig = map (\x -> (double, AST.Name x)) codegenTop :: S.Expr -> LLVM () codegenTop (S.Function name args body) = do define double name fnargs bls where fnargs = toSig args bls = createBlocks $ execCodegen $ do entry <- addBlock entryBlockName setBlock entry forM args $ \a -> do var <- alloca double store var (local (AST.Name a)) assign a var cgen body >>= ret codegenTop (S.Extern name args) = do external double name fnargs where fnargs = toSig args codegenTop exp = do define double "main" [] blks where blks = createBlocks $ execCodegen $ do entry <- addBlock entryBlockName setBlock entry cgen exp >>= ret Operations lt :: AST.Operand -> AST.Operand -> Codegen AST.Operand lt a b = do test <- fcmp FP.ULT a b uitofp double test binops = Map.fromList [ ("+", fadd) , ("-", fsub) , ("*", fmul) , ("/", fdiv) , ("<", lt) ] cgen :: S.Expr -> Codegen AST.Operand cgen (S.BinaryOp op a b) = do case Map.lookup op binops of Just f -> do ca <- cgen a cb <- cgen b f ca cb Nothing -> error "No such operator" cgen (S.Var x) = getvar x >>= load cgen (S.Float n) = return $ cons $ C.Float (F.Double n) cgen (S.Call fn args) = do largs <- mapM cgen args call (externf (AST.Name fn)) largs cgen (S.If cond tr fl) = do ifthen <- addBlock "if.then" ifelse <- addBlock "if.else" ifexit <- addBlock "if.exit" cond <- cgen cond test <- fcmp FP.ONE false cond Branch based on the condition setBlock ifthen ifthen <- getBlock setBlock ifelse ifelse <- getBlock setBlock ifexit phi double [(trval, ifthen), (flval, ifelse)] cgen (S.For ivar start cond step body) = do forloop <- addBlock "for.loop" forexit <- addBlock "for.exit" i <- alloca double setBlock forloop store i inext Test if the loop condition is True ( 1.0 ) setBlock forexit return zero codegen :: AST.Module -> [S.Expr] -> IO AST.Module codegen mod fns = do res <- runJIT oldast case res of Right newast -> return newast Left err -> putStrLn err >> return oldast where modn = mapM codegenTop fns oldast = runLLVM mod modn
185e210317046950e18ec7ddac01c567b06be640d49198df09132e475e64cf30
keoko/postgresql-simple-examples
Santa.hs
-- -12-03-postgresql-simple.html {-# LANGUAGE OverloadedStrings #-} module Santa where import Data.Text import Data.Int(Int64) import Data.ByteString (ByteString) import Control.Applicative import Control.Monad import Database.PostgreSQL.Simple import Database.PostgreSQL.Simple.ToField import Database.PostgreSQL.Simple.FromRow import Database.PostgreSQL.Simple.ToRow data Present = Present { presentName :: Text} deriving Show data Location = Location { locLat :: Double , locLong :: Double } deriving Show data Child = Child { childName :: Text , childLocation :: Location } deriving Show uri :: ByteString uri = "postgres@localhost/helloworld" instance FromRow Present where fromRow = Present <$> field instance ToRow Present where toRow p = [toField (presentName p)] instance FromRow Child where fromRow = Child <$> field <*> liftM2 Location field field instance ToRow Child where toRow c = [toField (childName c), toField (locLat (childLocation c)), toField (locLong (childLocation c))] allChildren :: Connection -> IO [Child] allChildren c = query_ c "SELECT name, loc_lat, loc_long FROM child" addPresent :: Connection -> Present -> IO Int64 addPresent c present = execute c "INSERT INTO present (name) VALUES (?)" present allPresents :: Connection -> IO [Present] allPresents c = query_ c "SELECT name FROM present" main :: IO () main = do conn <- connectPostgreSQL uri putStrLn "all children:" mapM_ (putStrLn . show) =<< allChildren conn putStrLn "all presents:" mapM_ (putStrLn . show) =<< allPresents conn putStrLn "add new present:" present <- getLine addedPresents <- addPresent conn Present {presentName=(pack present)} putStrLn $ "added presents: " ++ show addedPresents
null
https://raw.githubusercontent.com/keoko/postgresql-simple-examples/f83b8e8b98e98695846104470fedbfe843510b7b/Santa.hs
haskell
-12-03-postgresql-simple.html # LANGUAGE OverloadedStrings #
module Santa where import Data.Text import Data.Int(Int64) import Data.ByteString (ByteString) import Control.Applicative import Control.Monad import Database.PostgreSQL.Simple import Database.PostgreSQL.Simple.ToField import Database.PostgreSQL.Simple.FromRow import Database.PostgreSQL.Simple.ToRow data Present = Present { presentName :: Text} deriving Show data Location = Location { locLat :: Double , locLong :: Double } deriving Show data Child = Child { childName :: Text , childLocation :: Location } deriving Show uri :: ByteString uri = "postgres@localhost/helloworld" instance FromRow Present where fromRow = Present <$> field instance ToRow Present where toRow p = [toField (presentName p)] instance FromRow Child where fromRow = Child <$> field <*> liftM2 Location field field instance ToRow Child where toRow c = [toField (childName c), toField (locLat (childLocation c)), toField (locLong (childLocation c))] allChildren :: Connection -> IO [Child] allChildren c = query_ c "SELECT name, loc_lat, loc_long FROM child" addPresent :: Connection -> Present -> IO Int64 addPresent c present = execute c "INSERT INTO present (name) VALUES (?)" present allPresents :: Connection -> IO [Present] allPresents c = query_ c "SELECT name FROM present" main :: IO () main = do conn <- connectPostgreSQL uri putStrLn "all children:" mapM_ (putStrLn . show) =<< allChildren conn putStrLn "all presents:" mapM_ (putStrLn . show) =<< allPresents conn putStrLn "add new present:" present <- getLine addedPresents <- addPresent conn Present {presentName=(pack present)} putStrLn $ "added presents: " ++ show addedPresents
6799a63b8ab236e80916648e78d6ec57acb20c7493627508a8be65dbcb12386b
GlideAngle/flare-timing
HLint.hs
module Main (main) where import Language.Haskell.HLint (hlint) import System.Exit (exitFailure, exitSuccess) arguments :: [String] arguments = [ "library" , "test-suite-hlint" , "test-suite-math" -- WARNING: HLint turns off QuasiQuotes even if turned on in default - extensions in the cabal file , # 55 . -- SEE: , "-XQuasiQuotes" ] main :: IO () main = do hints <- hlint arguments if null hints then exitSuccess else exitFailure
null
https://raw.githubusercontent.com/GlideAngle/flare-timing/172a9b199eb1ff72c967669dc349cbf8d9c4bc52/lang-haskell/gap-math/test-suite-hlint/HLint.hs
haskell
WARNING: HLint turns off QuasiQuotes even if turned on in SEE:
module Main (main) where import Language.Haskell.HLint (hlint) import System.Exit (exitFailure, exitSuccess) arguments :: [String] arguments = [ "library" , "test-suite-hlint" , "test-suite-math" default - extensions in the cabal file , # 55 . , "-XQuasiQuotes" ] main :: IO () main = do hints <- hlint arguments if null hints then exitSuccess else exitFailure
bd962a6ce98cc86f5e596e82c7cbb8399230e94593e0f38204f585b3abfe0412
dkochmanski/charming-clim
classes.lisp
Copyright ( c ) 2018 , ( ) ;;;; Class definitions with brief commentary for a CLIM backend based on cl - charms ( ncurses wrapper written in Common Lisp ) . (in-package #:charming-clim) ;;; Port is a logical connection to a display server. It abstracts managament of ;;; windows, resources, incoming events etc. ;;; ;;; Usually we want to subclass `basic-port' which has some functionality ;;; implemented out of the box and provides a reasonable framework which is ;;; suitable as a starting point for client-server communication model. ;;; ;;; With port we have associated a few objects: its primary pointer, the frame ;;; manager and the keyboard-focus. `keyboard-input-focus' holds the client to ;;; whom keyboard events are dispatched. Called by `stream-set-input-focus'. ;;; ;;; Note to myself: pointer should be member of basic-port with a reader ;;; `port-pointer'. This method is mentioned in the spec in context of other ;;; operators but it is not documented (ommision probably). This should be ;;; documented too. ;;; Note to myself : we define method ` frame - manager ' specialized on port in CLIM ;;; package. This method is usually specialized on frame. (defclass charming-port (clim:basic-port) ((pointer :accessor clim:port-pointer :initform (make-instance 'charming-pointer)) (frame-manager :accessor clim:frame-manager :initform (make-instance 'charming-frame-manager)) See annotation in :8000/clim-spec/8-1.html#_304 (keyboard-input-focus :accessor clim:port-keyboard-input-focus :initform nil))) ;;; Pointer is a class representing the pointing device. It is worth noting that CLIM does n't mention possibility of multiple pointers associated with the ;;; port, however `tracking-pointer' documentation uses phrasing "primary ;;; pointer" for the sheet being `port-pointer' of its port. That means that ;;; "secondary pointer" is an option too. See method `pointer-event-pointer'. ;;; In curses pointer may be in one of three states : invisible , normal and very ;;; visible (usually that means blinking). ;;; ;;; Note to myself: `standard-pointer' should implement some of the common ;;; methods that are currently entirely provided by backends. Same goes for the ;;; coordinates and `pointer-cursor' accessor. Documentation should be provided ;;; too for the `pointer-cursor' which is underdocumented. (defclass charming-pointer (clim:standard-pointer) ((cursor :accessor clim:pointer-cursor :initform charms/ll:cursor_normal :type (member charms/ll:cursor_invisible charms/ll:cursor_normal charms/ll:cursor_very_visible)) (x :initform 0) (y :initform 0))) ;;; Frame manager is responsible for the actual realization of look-and-feel of ;;; the frame and for selecting pane types for abstract gadgets. When a frame is ;;; adopted by the frame manager, protocol for generating pane hierarchy should ;;; be invoked. ;;; ;;; Note to myself: `basic-port' has slot `frame-managers' (plural) and we manage a list of such . From my initial investigation there is always one ;;; frame manager associated with the port and we call it in ;;; `Core/clim-core/frames.lisp'. This should be simplified and burden of ;;; implementing multiple frame managers should be put on the backend ;;; implementer. We should add method `frame-managers' which returns all backend ;;; frame managers defaulting to list made of the only frame-manager. ;;; ;;; Note to myself: there seems to be some hackery in port initialize-instance ;;; for each backend to actually set a frame-manager - couldn't it be ;;; implemented with `default-initarg' of `basic-port' subclass? ;;; ;;; Note to myself: all backends provide a hackish mapping between generic ;;; gadget name and a concrete pane class. This involves some symbol manging ;;; etc. It may be worth to investigate whenever some more intelligible internal ;;; protocol could be pulled off for that which will be common for frame ;;; managers. (defclass charming-frame-manager (clim:frame-manager) ()) Graft is a root window in the display server being represented as a CLIM ;;; sheet. Many grafts may be connected to the same display server (port). ;;; ;;; Note to myself: grafts are pretty versatile but we don't seem to implement ;;; neither units nor orientation. When fixed add appropriate annotation to ;;; `:8000/clim-spec/edit/apropos?q=find-graft'. (defclass charming-graft (clim:graft) ()) ;;; Medium is an abstraction for graphics state of a sheet like bounding ;;; rectangle, ink, text-style or line-style. Medium also contains a sheet ;;; transformation. (defclass charming-medium (clim:basic-medium) ())
null
https://raw.githubusercontent.com/dkochmanski/charming-clim/931da8f7f888499d880ae22187ce1779d13dc11c/src/classes.lisp
lisp
Port is a logical connection to a display server. It abstracts managament of windows, resources, incoming events etc. Usually we want to subclass `basic-port' which has some functionality implemented out of the box and provides a reasonable framework which is suitable as a starting point for client-server communication model. With port we have associated a few objects: its primary pointer, the frame manager and the keyboard-focus. `keyboard-input-focus' holds the client to whom keyboard events are dispatched. Called by `stream-set-input-focus'. Note to myself: pointer should be member of basic-port with a reader `port-pointer'. This method is mentioned in the spec in context of other operators but it is not documented (ommision probably). This should be documented too. package. This method is usually specialized on frame. Pointer is a class representing the pointing device. It is worth noting that port, however `tracking-pointer' documentation uses phrasing "primary pointer" for the sheet being `port-pointer' of its port. That means that "secondary pointer" is an option too. See method `pointer-event-pointer'. visible (usually that means blinking). Note to myself: `standard-pointer' should implement some of the common methods that are currently entirely provided by backends. Same goes for the coordinates and `pointer-cursor' accessor. Documentation should be provided too for the `pointer-cursor' which is underdocumented. Frame manager is responsible for the actual realization of look-and-feel of the frame and for selecting pane types for abstract gadgets. When a frame is adopted by the frame manager, protocol for generating pane hierarchy should be invoked. Note to myself: `basic-port' has slot `frame-managers' (plural) and we frame manager associated with the port and we call it in `Core/clim-core/frames.lisp'. This should be simplified and burden of implementing multiple frame managers should be put on the backend implementer. We should add method `frame-managers' which returns all backend frame managers defaulting to list made of the only frame-manager. Note to myself: there seems to be some hackery in port initialize-instance for each backend to actually set a frame-manager - couldn't it be implemented with `default-initarg' of `basic-port' subclass? Note to myself: all backends provide a hackish mapping between generic gadget name and a concrete pane class. This involves some symbol manging etc. It may be worth to investigate whenever some more intelligible internal protocol could be pulled off for that which will be common for frame managers. sheet. Many grafts may be connected to the same display server (port). Note to myself: grafts are pretty versatile but we don't seem to implement neither units nor orientation. When fixed add appropriate annotation to `:8000/clim-spec/edit/apropos?q=find-graft'. Medium is an abstraction for graphics state of a sheet like bounding rectangle, ink, text-style or line-style. Medium also contains a sheet transformation.
Copyright ( c ) 2018 , ( ) Class definitions with brief commentary for a CLIM backend based on cl - charms ( ncurses wrapper written in Common Lisp ) . (in-package #:charming-clim) Note to myself : we define method ` frame - manager ' specialized on port in CLIM (defclass charming-port (clim:basic-port) ((pointer :accessor clim:port-pointer :initform (make-instance 'charming-pointer)) (frame-manager :accessor clim:frame-manager :initform (make-instance 'charming-frame-manager)) See annotation in :8000/clim-spec/8-1.html#_304 (keyboard-input-focus :accessor clim:port-keyboard-input-focus :initform nil))) CLIM does n't mention possibility of multiple pointers associated with the In curses pointer may be in one of three states : invisible , normal and very (defclass charming-pointer (clim:standard-pointer) ((cursor :accessor clim:pointer-cursor :initform charms/ll:cursor_normal :type (member charms/ll:cursor_invisible charms/ll:cursor_normal charms/ll:cursor_very_visible)) (x :initform 0) (y :initform 0))) manage a list of such . From my initial investigation there is always one (defclass charming-frame-manager (clim:frame-manager) ()) Graft is a root window in the display server being represented as a CLIM (defclass charming-graft (clim:graft) ()) (defclass charming-medium (clim:basic-medium) ())
c0d64f199c7fac2844a8ec0a168368df7fdf11fc04c8b57145ccbc42b44d376d
originrose/think.datatype
core.clj
(ns think.datatype.validation.core (:require [think.gate.core :as gate]) (:gen-class)) (defn on-foo [params] ;; consider destructuring your arguments (+ (:a params) 41)) (def routing-map {"foo" #'on-foo}) (defn gate [] (gate/open #'routing-map)) (defn other-thing "Example of rendering a different component with the gate/component multimethod." [] (gate/open #'routing-map :variable-map {:render-page "otherthing"})) (defn -main [& args] (println (gate)))
null
https://raw.githubusercontent.com/originrose/think.datatype/31372d6e18fe3a5146262693c0df5256a2a58095/validation-project/src/think/datatype/validation/core.clj
clojure
consider destructuring your arguments
(ns think.datatype.validation.core (:require [think.gate.core :as gate]) (:gen-class)) (defn on-foo (+ (:a params) 41)) (def routing-map {"foo" #'on-foo}) (defn gate [] (gate/open #'routing-map)) (defn other-thing "Example of rendering a different component with the gate/component multimethod." [] (gate/open #'routing-map :variable-map {:render-page "otherthing"})) (defn -main [& args] (println (gate)))
732a7ee5d458faa907d7019edbc718a825c1235f49fe5a3cb7435b586fe9cbc1
kostyushkin/erlworld
doc_gen.erl
%%% @author %%% @doc %%% This module is designed for handling generating the documentation for the %%% project. As more packages are added, this should be expanded to include %%% them. %%% -module( doc_gen ). -author("Joseph Lenton"). -export([ start_halt/2, start/0, start/2, start/3 ]). %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% Public API %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %% start_halt %% @doc This will run the start function once , and then halt the Erlang VM afterwoulds . ( Source::string ( ) , Destination::string ( ) ) - > ok start_halt(Source, Destination) -> start(Source, Destination), halt(). start() -> start("./../src", "./../doc", public). start(Source, Destination) -> start( Source, Destination, public ). start(Source, Destination, public) -> generate_doc( Source, Destination, public_packages() ++ private_packages() ); start(Source, Destination, _Type) -> generate_doc( Source, Destination, public_packages() ++ private_packages() ). %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% Private - Document Generation %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% public_packages() -> [ "actor", "actor_state", "color", "controls", "display", "fps_actor", "graphics", "image", "mainloop", "world", "world_state" ]. private_packages() -> [ "controls_handler", "data_server", "function_server", "doc_gen" ]. generate_doc(_Source, _Destination, _Packages) -> edoc:application( 'ErlWorld', "./..", [ { exclude_packages, private_packages() } ] ), halt(). generate_doc2(Source, Destination, Packages) -> edoc:files( Packages, [ { souce_path , Source }, { souce_suffic , ".erl" }, { dir , Destination } ] ).
null
https://raw.githubusercontent.com/kostyushkin/erlworld/1c55c9eb0d12db9824144b4ff7535960c53e35c8/src/doc_gen.erl
erlang
@doc This module is designed for handling generating the documentation for the project. As more packages are added, this should be expanded to include them. %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% Public API %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% start_halt %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%% %%%
@author -module( doc_gen ). -author("Joseph Lenton"). -export([ start_halt/2, start/0, start/2, start/3 ]). @doc This will run the start function once , and then halt the Erlang VM afterwoulds . ( Source::string ( ) , Destination::string ( ) ) - > ok start_halt(Source, Destination) -> start(Source, Destination), halt(). start() -> start("./../src", "./../doc", public). start(Source, Destination) -> start( Source, Destination, public ). start(Source, Destination, public) -> generate_doc( Source, Destination, public_packages() ++ private_packages() ); start(Source, Destination, _Type) -> generate_doc( Source, Destination, public_packages() ++ private_packages() ). Private - Document Generation public_packages() -> [ "actor", "actor_state", "color", "controls", "display", "fps_actor", "graphics", "image", "mainloop", "world", "world_state" ]. private_packages() -> [ "controls_handler", "data_server", "function_server", "doc_gen" ]. generate_doc(_Source, _Destination, _Packages) -> edoc:application( 'ErlWorld', "./..", [ { exclude_packages, private_packages() } ] ), halt(). generate_doc2(Source, Destination, Packages) -> edoc:files( Packages, [ { souce_path , Source }, { souce_suffic , ".erl" }, { dir , Destination } ] ).
eb6e61d054e1f66d43a83be0ca8e9d60899c3195fd59d8b38553eeedd51581d4
Zulu-Inuoe/clution
client-info.lisp
;;;; client-info.lisp (in-package #:quicklisp-client) (defparameter *client-base-url* "/") (defgeneric info-equal (info1 info2) (:documentation "Return TRUE if INFO1 and INFO2 are 'equal' in some important sense.")) ;;; Information for checking the validity of files fetched for ;;; installing/updating the client code. (defclass client-file-info () ((plist-key :initarg :plist-key :reader plist-key) (file-url :initarg :url :reader file-url) (name :reader name :initarg :name) (size :initarg :size :reader size) (md5 :reader md5 :initarg :md5) (sha256 :reader sha256 :initarg :sha256) (plist :reader plist :initarg :plist))) (defmethod print-object ((info client-file-info) stream) (print-unreadable-object (info stream :type t) (format stream "~S ~D ~S" (name info) (size info) (md5 info)))) (defmethod info-equal ((info1 client-file-info) (info2 client-file-info)) (and (eql (size info1) (size info2)) (equal (name info1) (name info2)) (equal (md5 info1) (md5 info2)))) (defclass asdf-file-info (client-file-info) () (:default-initargs :plist-key :asdf :name "asdf.lisp")) (defclass setup-file-info (client-file-info) () (:default-initargs :plist-key :setup :name "setup.lisp")) (defclass client-tar-file-info (client-file-info) () (:default-initargs :plist-key :client-tar :name "quicklisp.tar")) (define-condition invalid-client-file (error) ((file :initarg :file :reader invalid-client-file-file))) (define-condition badly-sized-client-file (invalid-client-file) ((expected-size :initarg :expected-size :reader badly-sized-client-file-expected-size) (actual-size :initarg :actual-size :reader badly-sized-client-file-actual-size)) (:report (lambda (condition stream) (format stream "Unexpected file size for ~A ~ - expected ~A but got ~A" (invalid-client-file-file condition) (badly-sized-client-file-expected-size condition) (badly-sized-client-file-actual-size condition))))) (defun check-client-file-size (file expected-size) (let ((actual-size (file-size file))) (unless (eql expected-size actual-size) (error 'badly-sized-client-file :file file :expected-size expected-size :actual-size actual-size)))) ;;; TODO: check cryptographic digests too. (defgeneric check-client-file (file client-file-info) (:documentation "Signal an INVALID-CLIENT-FILE error if FILE does not match the metadata in CLIENT-FILE-INFO.") (:method (file client-file-info) (check-client-file-size file (size client-file-info)) client-file-info)) Structuring and loading information about the Quicklisp client ;;; code (defclass client-info () ((setup-info :reader setup-info :initarg :setup-info) (asdf-info :reader asdf-info :initarg :asdf-info) (client-tar-info :reader client-tar-info :initarg :client-tar-info) (canonical-client-info-url :reader canonical-client-info-url :initarg :canonical-client-info-url) (version :reader version :initarg :version) (subscription-url :reader subscription-url :initarg :subscription-url) (plist :reader plist :initarg :plist) (source-file :reader source-file :initarg :source-file))) (defmethod print-object ((client-info client-info) stream) (print-unreadable-object (client-info stream :type t) (prin1 (version client-info) stream))) (defmethod available-versions-url ((info client-info)) (make-versions-url (subscription-url info))) (defgeneric extract-client-file-info (file-info-class plist) (:method (file-info-class plist) (let* ((instance (make-instance file-info-class)) (key (plist-key instance)) (file-info-plist (getf plist key))) (unless file-info-plist (error "Missing client-info data for ~S" key)) (destructuring-bind (&key url size md5 sha256 &allow-other-keys) file-info-plist (unless (and url size md5 sha256) (error "Missing client-info data for ~S" key)) (reinitialize-instance instance :plist file-info-plist :url url :size size :md5 md5 :sha256 sha256))))) (defun format-client-url (path &rest format-arguments) (if format-arguments (format nil "~A~{~}" *client-base-url* path format-arguments) (format nil "~A~A" *client-base-url* path))) (defun client-info-url-from-version (version) (format-client-url "client/~A/client-info.sexp" version)) (define-condition invalid-client-info (error) ((plist :initarg plist :reader invalid-client-info-plist))) (defun load-client-info (file) (let ((plist (safely-read-file file))) (destructuring-bind (&key subscription-url version canonical-client-info-url &allow-other-keys) plist (make-instance 'client-info :setup-info (extract-client-file-info 'setup-file-info plist) :asdf-info (extract-client-file-info 'asdf-file-info plist) :client-tar-info (extract-client-file-info 'client-tar-file-info plist) :canonical-client-info-url canonical-client-info-url :version version :subscription-url subscription-url :plist plist :source-file (probe-file file))))) (defun mock-client-info () (flet ((mock-client-file-info (class) (make-instance class :size 0 :url "" :md5 "" :sha256 "" :plist nil))) (make-instance 'client-info :version ql-info:*version* :subscription-url (format-client-url "client/quicklisp.sexp") :setup-info (mock-client-file-info 'setup-file-info) :asdf-info (mock-client-file-info 'asdf-file-info) :client-tar-info (mock-client-file-info 'client-tar-file-info)))) (defun fetch-client-info (url) (let ((info-file (qmerge "tmp/client-info.sexp"))) (delete-file-if-exists info-file) (fetch url info-file :quietly t) (handler-case (load-client-info info-file) ;; FIXME: So many other things could go wrong here; I think it ;; would be nice to catch and report them clearly as bogus URLs (invalid-client-info () (error "Invalid client info URL -- ~A" url))))) (defun local-client-info () (let ((info-file (qmerge "client-info.sexp"))) (if (probe-file info-file) (load-client-info info-file) (progn (warn "Missing client-info.sexp, using mock info") (mock-client-info))))) (defun newest-client-info (&optional (info (local-client-info))) (let ((latest (subscription-url info))) (when latest (fetch-client-info latest)))) (defun client-version-lessp (client-info-1 client-info-2) (string-lessp (version client-info-1) (version client-info-2))) (defun client-version () "Return the version for the current local client installation. May or may not be suitable for passing as the :VERSION argument to INSTALL-CLIENT, depending on if it's a standard Quicklisp-provided client." (version (local-client-info))) (defun client-url () "Return an URL suitable for passing as the :URL argument to INSTALL-CLIENT for the current local client installation." (canonical-client-info-url (local-client-info))) (defun available-client-versions () (let ((url (available-versions-url (local-client-info))) (temp-file (qmerge "tmp/client-versions.sexp"))) (when url (handler-case (progn (maybe-fetch-gzipped url temp-file) (prog1 (with-open-file (stream temp-file) (safely-read stream)) (delete-file-if-exists temp-file))) (unexpected-http-status (condition) (unless (url-not-suitable-error-p condition) (error condition)))))))
null
https://raw.githubusercontent.com/Zulu-Inuoe/clution/b72f7afe5f770ff68a066184a389c23551863f7f/cl-clution/systems/cl-clution/quicklisp/quicklisp/client-info.lisp
lisp
client-info.lisp Information for checking the validity of files fetched for installing/updating the client code. TODO: check cryptographic digests too. code FIXME: So many other things could go wrong here; I think it would be nice to catch and report them clearly as bogus URLs
(in-package #:quicklisp-client) (defparameter *client-base-url* "/") (defgeneric info-equal (info1 info2) (:documentation "Return TRUE if INFO1 and INFO2 are 'equal' in some important sense.")) (defclass client-file-info () ((plist-key :initarg :plist-key :reader plist-key) (file-url :initarg :url :reader file-url) (name :reader name :initarg :name) (size :initarg :size :reader size) (md5 :reader md5 :initarg :md5) (sha256 :reader sha256 :initarg :sha256) (plist :reader plist :initarg :plist))) (defmethod print-object ((info client-file-info) stream) (print-unreadable-object (info stream :type t) (format stream "~S ~D ~S" (name info) (size info) (md5 info)))) (defmethod info-equal ((info1 client-file-info) (info2 client-file-info)) (and (eql (size info1) (size info2)) (equal (name info1) (name info2)) (equal (md5 info1) (md5 info2)))) (defclass asdf-file-info (client-file-info) () (:default-initargs :plist-key :asdf :name "asdf.lisp")) (defclass setup-file-info (client-file-info) () (:default-initargs :plist-key :setup :name "setup.lisp")) (defclass client-tar-file-info (client-file-info) () (:default-initargs :plist-key :client-tar :name "quicklisp.tar")) (define-condition invalid-client-file (error) ((file :initarg :file :reader invalid-client-file-file))) (define-condition badly-sized-client-file (invalid-client-file) ((expected-size :initarg :expected-size :reader badly-sized-client-file-expected-size) (actual-size :initarg :actual-size :reader badly-sized-client-file-actual-size)) (:report (lambda (condition stream) (format stream "Unexpected file size for ~A ~ - expected ~A but got ~A" (invalid-client-file-file condition) (badly-sized-client-file-expected-size condition) (badly-sized-client-file-actual-size condition))))) (defun check-client-file-size (file expected-size) (let ((actual-size (file-size file))) (unless (eql expected-size actual-size) (error 'badly-sized-client-file :file file :expected-size expected-size :actual-size actual-size)))) (defgeneric check-client-file (file client-file-info) (:documentation "Signal an INVALID-CLIENT-FILE error if FILE does not match the metadata in CLIENT-FILE-INFO.") (:method (file client-file-info) (check-client-file-size file (size client-file-info)) client-file-info)) Structuring and loading information about the Quicklisp client (defclass client-info () ((setup-info :reader setup-info :initarg :setup-info) (asdf-info :reader asdf-info :initarg :asdf-info) (client-tar-info :reader client-tar-info :initarg :client-tar-info) (canonical-client-info-url :reader canonical-client-info-url :initarg :canonical-client-info-url) (version :reader version :initarg :version) (subscription-url :reader subscription-url :initarg :subscription-url) (plist :reader plist :initarg :plist) (source-file :reader source-file :initarg :source-file))) (defmethod print-object ((client-info client-info) stream) (print-unreadable-object (client-info stream :type t) (prin1 (version client-info) stream))) (defmethod available-versions-url ((info client-info)) (make-versions-url (subscription-url info))) (defgeneric extract-client-file-info (file-info-class plist) (:method (file-info-class plist) (let* ((instance (make-instance file-info-class)) (key (plist-key instance)) (file-info-plist (getf plist key))) (unless file-info-plist (error "Missing client-info data for ~S" key)) (destructuring-bind (&key url size md5 sha256 &allow-other-keys) file-info-plist (unless (and url size md5 sha256) (error "Missing client-info data for ~S" key)) (reinitialize-instance instance :plist file-info-plist :url url :size size :md5 md5 :sha256 sha256))))) (defun format-client-url (path &rest format-arguments) (if format-arguments (format nil "~A~{~}" *client-base-url* path format-arguments) (format nil "~A~A" *client-base-url* path))) (defun client-info-url-from-version (version) (format-client-url "client/~A/client-info.sexp" version)) (define-condition invalid-client-info (error) ((plist :initarg plist :reader invalid-client-info-plist))) (defun load-client-info (file) (let ((plist (safely-read-file file))) (destructuring-bind (&key subscription-url version canonical-client-info-url &allow-other-keys) plist (make-instance 'client-info :setup-info (extract-client-file-info 'setup-file-info plist) :asdf-info (extract-client-file-info 'asdf-file-info plist) :client-tar-info (extract-client-file-info 'client-tar-file-info plist) :canonical-client-info-url canonical-client-info-url :version version :subscription-url subscription-url :plist plist :source-file (probe-file file))))) (defun mock-client-info () (flet ((mock-client-file-info (class) (make-instance class :size 0 :url "" :md5 "" :sha256 "" :plist nil))) (make-instance 'client-info :version ql-info:*version* :subscription-url (format-client-url "client/quicklisp.sexp") :setup-info (mock-client-file-info 'setup-file-info) :asdf-info (mock-client-file-info 'asdf-file-info) :client-tar-info (mock-client-file-info 'client-tar-file-info)))) (defun fetch-client-info (url) (let ((info-file (qmerge "tmp/client-info.sexp"))) (delete-file-if-exists info-file) (fetch url info-file :quietly t) (handler-case (load-client-info info-file) (invalid-client-info () (error "Invalid client info URL -- ~A" url))))) (defun local-client-info () (let ((info-file (qmerge "client-info.sexp"))) (if (probe-file info-file) (load-client-info info-file) (progn (warn "Missing client-info.sexp, using mock info") (mock-client-info))))) (defun newest-client-info (&optional (info (local-client-info))) (let ((latest (subscription-url info))) (when latest (fetch-client-info latest)))) (defun client-version-lessp (client-info-1 client-info-2) (string-lessp (version client-info-1) (version client-info-2))) (defun client-version () "Return the version for the current local client installation. May or may not be suitable for passing as the :VERSION argument to INSTALL-CLIENT, depending on if it's a standard Quicklisp-provided client." (version (local-client-info))) (defun client-url () "Return an URL suitable for passing as the :URL argument to INSTALL-CLIENT for the current local client installation." (canonical-client-info-url (local-client-info))) (defun available-client-versions () (let ((url (available-versions-url (local-client-info))) (temp-file (qmerge "tmp/client-versions.sexp"))) (when url (handler-case (progn (maybe-fetch-gzipped url temp-file) (prog1 (with-open-file (stream temp-file) (safely-read stream)) (delete-file-if-exists temp-file))) (unexpected-http-status (condition) (unless (url-not-suitable-error-p condition) (error condition)))))))
df9dc9cb91976ed7b4e46f1f96be083dff77af4e6c0076608b175282476c3b17
samoht/camloo
make_lib.scm
(module camloo (import __caml_buffcode __caml_builtins __caml_compiler __caml_config __caml_const __caml_dump __caml_emit_phr __caml_emitcode __caml_errors __caml_front __caml_globals __caml_instruct __caml_labels __caml_lam __caml_lambda __caml_lexer __caml_location __caml_main __caml_match __caml_misc __caml_modules __caml_opcodes __caml_par_aux __caml_parser __caml_pr_decl __caml_pr_type __caml_prim __caml_prim_opc __caml_primdecl __caml_reloc __caml_syntax __caml_tr_env __caml_trstream __caml_ty_decl __caml_ty_error __caml_ty_intf __caml_types __caml_typing __caml_version generate init Lconst Ldefine lib_module_list Llambda Lprim Lswitch camloo utils module Pmakeblock optimize-ref var))
null
https://raw.githubusercontent.com/samoht/camloo/29a578a152fa23a3125a2a5b23e325b6d45d3abd/src/camloo/Misc/make_lib.scm
scheme
(module camloo (import __caml_buffcode __caml_builtins __caml_compiler __caml_config __caml_const __caml_dump __caml_emit_phr __caml_emitcode __caml_errors __caml_front __caml_globals __caml_instruct __caml_labels __caml_lam __caml_lambda __caml_lexer __caml_location __caml_main __caml_match __caml_misc __caml_modules __caml_opcodes __caml_par_aux __caml_parser __caml_pr_decl __caml_pr_type __caml_prim __caml_prim_opc __caml_primdecl __caml_reloc __caml_syntax __caml_tr_env __caml_trstream __caml_ty_decl __caml_ty_error __caml_ty_intf __caml_types __caml_typing __caml_version generate init Lconst Ldefine lib_module_list Llambda Lprim Lswitch camloo utils module Pmakeblock optimize-ref var))
2b47da5c0829f7c9e69a6157841bbb306b0cadd5a854ed9d816914f44352bc91
klapaucius/vector-hashtables
Internal.hs
| Module : Data . Vector . . Internal Description : Provides internals of hashtables and set of utilities . Copyright : ( c ) klapaucius , swamp_agr , 2016 - 2021 License : Module : Data.Vector.Hashtables.Internal Description : Provides internals of hashtables and set of utilities. Copyright : (c) klapaucius, swamp_agr, 2016-2021 License : BSD3 -} # LANGUAGE BangPatterns # # LANGUAGE FlexibleContexts # # LANGUAGE RecordWildCards # # LANGUAGE TypeFamilies # module Data.Vector.Hashtables.Internal where import Control.Monad import Control.Monad.Primitive import Data.Bits import Data.Hashable import Data.Maybe import Data.Primitive.MutVar import Data.Vector.Generic (Mutable, Vector) import qualified Data.Vector.Generic as VI import Data.Vector.Generic.Mutable (MVector) import qualified Data.Vector.Generic.Mutable as V import qualified Data.Vector.Mutable as B import qualified Data.Vector.Storable as SI import qualified Data.Vector.Storable.Mutable as S import qualified Data.Vector.Unboxed as UI import qualified Data.Vector.Unboxed.Mutable as U import qualified GHC.Exts as Exts import Prelude hiding (length, lookup) import qualified Data.Primitive.PrimArray as A import qualified Data.Primitive.PrimArray.Utils as A import Data.Vector.Hashtables.Internal.Mask (mask) | for ' MutablePrimArray s Int ' . type IntArray s = A.MutablePrimArray s Int -- | Single-element mutable array of 'Dictionary_' with primitive state token parameterized with state, keys and values types. -- -- *Example*: -- -- >>> import qualified Data.Vector.Storable.Mutable as VM > > > import qualified Data . Vector . . Mutable as UM > > > import Data . Vector . > > > type HashTable k v = Dictionary ( PrimState IO ) VM.MVector k UM.MVector v -- -- Different vectors could be used for keys and values: -- -- - storable, -- - mutable, -- - unboxed. -- -- In most cases unboxed vectors should be used. Nevertheless, it is up to you to decide about final form of hastable. newtype Dictionary s ks k vs v = DRef { getDRef :: MutVar s (Dictionary_ s ks k vs v) } -- | Represents collection of hashtable internal primitive arrays and vectors. -- -- - hash codes, -- -- - references to the next element, -- -- - buckets, -- -- - keys -- -- - and values. -- data Dictionary_ s ks k vs v = Dictionary { hashCode, next, buckets, refs :: IntArray s, key :: ks s k, value :: vs s v } getCount, getFreeList, getFreeCount :: Int getCount = 0 getFreeList = 1 getFreeCount = 2 -- | Represents immutable dictionary as collection of immutable arrays and vectors. -- See 'unsafeFreeze' and 'unsafeThaw' for conversions from/to mutable dictionary. data FrozenDictionary ks k vs v = FrozenDictionary { fhashCode, fnext, fbuckets :: A.PrimArray Int, count, freeList, freeCount :: Int, fkey :: ks k, fvalue :: vs v } deriving (Eq, Ord, Show) -- | /O(1)/ in the best case, /O(n)/ in the worst case. Find dictionary entry by given key in immutable ' FrozenDictionary ' . -- If entry not found @-1@ returned. findElem :: (Vector ks k, Vector vs v, Hashable k, Eq k) => FrozenDictionary ks k vs v -> k -> Int findElem FrozenDictionary{..} key' = go $ fbuckets !. (hashCode' `rem` A.sizeofPrimArray fbuckets) where hashCode' = hash key' .&. mask go i | i >= 0 = if fhashCode !. i == hashCode' && fkey !.~ i == key' then i else go $ fnext !. i | otherwise = -1 # INLINE findElem # -- | Infix version of @unsafeRead@. (!~) :: (MVector v a, PrimMonad m) => v (PrimState m) a -> Int -> m a (!~) = V.unsafeRead -- | Infix version of @unsafeIndex@. (!.~) :: (Vector v a) => v a -> Int -> a (!.~) = VI.unsafeIndex -- | Infix version of @unsafeWrite@. (<~~) :: (MVector v a, PrimMonad m) => v (PrimState m) a -> Int -> a -> m () (<~~) = V.unsafeWrite -- | Infix version of @readPrimArray@. (!) :: PrimMonad m => A.MutablePrimArray (PrimState m) Int -> Int -> m Int (!) = A.readPrimArray -- | Infix version of @indexPrimArray@. (!.) :: A.PrimArray Int -> Int -> Int (!.) = A.indexPrimArray | Infix version of @writePrimArray@. (<~) :: PrimMonad m => A.MutablePrimArray (PrimState m) Int -> Int -> Int -> m () (<~) = A.writePrimArray -- | /O(1)/ Dictionary with given capacity. initialize :: (MVector ks k, MVector vs v, PrimMonad m) => Int -> m (Dictionary (PrimState m) ks k vs v) initialize capacity = do let size = getPrime capacity hashCode <- A.replicate size 0 next <- A.replicate size 0 key <- V.new size value <- V.new size buckets <- A.replicate size (-1) refs <- A.replicate 3 0 refs <~ 1 $ -1 dr <- newMutVar Dictionary {..} return . DRef $ dr -- | Create a copy of mutable dictionary. clone :: (MVector ks k, MVector vs v, PrimMonad m) => Dictionary (PrimState m) ks k vs v -> m (Dictionary (PrimState m) ks k vs v) clone DRef {..} = do Dictionary {..} <- readMutVar getDRef hashCode <- A.clone hashCode next <- A.clone next key <- V.clone key value <- V.clone value buckets <- A.clone buckets refs <- A.clone refs dr <- newMutVar Dictionary {..} return . DRef $ dr -- | /O(1)/ Unsafe convert a mutable dictionary to an immutable one without copying. -- The mutable dictionary may not be used after this operation. unsafeFreeze :: (VI.Vector ks k, VI.Vector vs v, PrimMonad m) => Dictionary (PrimState m) (Mutable ks) k (Mutable vs) v -> m (FrozenDictionary ks k vs v) unsafeFreeze DRef {..} = do Dictionary {..} <- readMutVar getDRef fhashCode <- A.unsafeFreeze hashCode fnext <- A.unsafeFreeze next fbuckets <- A.unsafeFreeze buckets count <- refs ! getCount freeList <- refs ! getFreeList freeCount <- refs ! getFreeCount fkey <- VI.unsafeFreeze key fvalue <- VI.unsafeFreeze value return FrozenDictionary {..} | /O(1)/ Unsafely convert immutable ' FrozenDictionary ' to a mutable ' Dictionary ' without copying . -- The immutable dictionary may not be used after this operation. unsafeThaw :: (Vector ks k, Vector vs v, PrimMonad m) => FrozenDictionary ks k vs v -> m (Dictionary (PrimState m) (Mutable ks) k (Mutable vs) v) unsafeThaw FrozenDictionary {..} = do hashCode <- A.unsafeThaw fhashCode next <- A.unsafeThaw fnext buckets <- A.unsafeThaw fbuckets refs <- A.unsafeThaw $ A.primArrayFromListN 3 [count, freeList, freeCount] key <- VI.unsafeThaw fkey value <- VI.unsafeThaw fvalue dr <- newMutVar Dictionary {..} return . DRef $ dr -- | /O(n)/ Retrieve list of keys from 'Dictionary'. keys :: (Vector ks k, PrimMonad m) => Dictionary (PrimState m) (Mutable ks) k vs v -> m (ks k) keys DRef{..} = do Dictionary{..} <- readMutVar getDRef hcs <- A.freeze hashCode ks <- VI.freeze key count <- refs ! getCount return . VI.ifilter (\i _ -> hcs !. i >= 0) . VI.take count $ ks -- | /O(n)/ Retrieve list of values from 'Dictionary'. values :: (Vector vs v, PrimMonad m) => Dictionary (PrimState m) ks k (Mutable vs) v -> m (vs v) values DRef{..} = do Dictionary{..} <- readMutVar getDRef hcs <- A.freeze hashCode vs <- VI.freeze value count <- refs ! getCount return . VI.ifilter (\i _ -> hcs !. i >= 0) . VI.take count $ vs -- | /O(1)/ in the best case, /O(n)/ in the worst case. -- Find value by given key in 'Dictionary'. Throws an error if value not found. at :: (MVector ks k, MVector vs v, PrimMonad m, Hashable k, Eq k) => Dictionary (PrimState m) ks k vs v -> k -> m v at d k = do i <- findEntry d k if i >= 0 then do Dictionary{..} <- readMutVar . getDRef $ d value !~ i else error "KeyNotFoundException!" # INLINE at # -- | /O(1)/ in the best case, /O(n)/ in the worst case. -- Find value by given key in 'Dictionary'. Like 'at'' but return 'Nothing' if value not found. at' :: (MVector ks k, MVector vs v, PrimMonad m, Hashable k, Eq k) => Dictionary (PrimState m) ks k vs v -> k -> m (Maybe v) at' d k = do i <- findEntry d k if i >= 0 then do Dictionary{..} <- readMutVar . getDRef $ d Just <$> value !~ i else pure Nothing {-# INLINE at' #-} atWithOrElse :: (MVector ks k, MVector vs v, PrimMonad m, Hashable k, Eq k) => Dictionary (PrimState m) ks k vs v -> k -> (Dictionary (PrimState m) ks k vs v -> Int -> m a) -> (Dictionary (PrimState m) ks k vs v -> m a) -> m a atWithOrElse d k onFound onNothing = do i <- findEntry d k if i >= 0 then onFound d i else onNothing d {-# INLINE atWithOrElse #-} -- | /O(1)/ in the best case, /O(n)/ in the worst case. -- Find dictionary entry by given key. If entry not found @-1@ returned. findEntry :: (MVector ks k, MVector vs v, PrimMonad m, Hashable k, Eq k) => Dictionary (PrimState m) ks k vs v -> k -> m Int findEntry d key' = do Dictionary{..} <- readMutVar . getDRef $ d let hashCode' = hash key' .&. mask go i | i >= 0 = do hc <- hashCode ! i if hc == hashCode' then do k <- key !~ i if k == key' then return i else go =<< next ! i else go =<< next ! i | otherwise = return $ -1 go =<< buckets ! (hashCode' `rem` A.length buckets) # INLINE findEntry # -- | /O(1)/ in the best case, /O(n)/ in the worst case. -- Insert key and value in dictionary by key's hash. -- If entry with given key found value will be replaced. insert :: (MVector ks k, MVector vs v, PrimMonad m, Hashable k, Eq k) => Dictionary (PrimState m) ks k vs v -> k -> v -> m () insert DRef{..} key' value' = do d@Dictionary{..} <- readMutVar getDRef let hashCode' = hash key' .&. mask targetBucket = hashCode' `rem` A.length buckets go i | i >= 0 = do hc <- hashCode ! i if hc == hashCode' then do k <- key !~ i if k == key' then value <~~ i $ value' else go =<< next ! i else go =<< next ! i | otherwise = addOrResize addOrResize = do freeCount <- refs ! getFreeCount if freeCount > 0 then do index <- refs ! getFreeList nxt <- next ! index refs <~ getFreeList $ nxt refs <~ getFreeCount $ freeCount - 1 add index targetBucket else do count <- refs ! getCount refs <~ getCount $ count + 1 if count == A.length next then do nd <- resize d count hashCode' key' value' writeMutVar getDRef nd else add (fromIntegral count) (fromIntegral targetBucket) add !index !targetBucket = do hashCode <~ index $ hashCode' b <- buckets ! targetBucket next <~ index $ b key <~~ index $ key' value <~~ index $ value' buckets <~ targetBucket $ index go =<< buckets ! targetBucket # INLINE insert # insertWithIndex :: (MVector ks k, MVector vs v, PrimMonad m, Hashable k, Eq k) => Int -> Int -> k -> v -> MutVar (PrimState m) (Dictionary_ (PrimState m) ks k vs v) -> Dictionary_ (PrimState m) ks k vs v -> Int -> m () insertWithIndex !targetBucket !hashCode' key' value' getDRef d@Dictionary{..} = go where go i | i >= 0 = do hc <- hashCode ! i if hc == hashCode' then do k <- key !~ i if k == key' then value <~~ i $ value' else go =<< next ! i else go =<< next ! i | otherwise = addOrResize targetBucket hashCode' key' value' getDRef d # INLINE insertWithIndex # addOrResize :: (MVector ks k, MVector vs v, PrimMonad m, Hashable k, Eq k) => Int -> Int -> k -> v -> MutVar (PrimState m) (Dictionary_ (PrimState m) ks k vs v) -> Dictionary_ (PrimState m) ks k vs v -> m () addOrResize !targetBucket !hashCode' !key' !value' dref d@Dictionary{..} = do freeCount <- refs ! getFreeCount if freeCount > 0 then do index <- refs ! getFreeList nxt <- next ! index refs <~ getFreeList $ nxt refs <~ getFreeCount $ freeCount - 1 add index targetBucket hashCode' key' value' d else do count <- refs ! getCount refs <~ getCount $ count + 1 if count == A.length next then do nd <- resize d count hashCode' key' value' writeMutVar dref nd else add (fromIntegral count) (fromIntegral targetBucket) hashCode' key' value' d # INLINE addOrResize # add :: (MVector ks k, MVector vs v, PrimMonad m, Hashable k, Eq k) => Int -> Int -> Int -> k -> v -> Dictionary_ (PrimState m) ks k vs v -> m () add !index !targetBucket !hashCode' !key' !value' Dictionary{..} = do hashCode <~ index $ hashCode' b <- buckets ! targetBucket next <~ index $ b key <~~ index $ key' value <~~ index $ value' buckets <~ targetBucket $ index # INLINE add # resize Dictionary{..} index hashCode' key' value' = do let newSize = getPrime (index*2) delta = newSize - index buckets <- A.replicate newSize (-1) hashCode <- A.growNoZ hashCode delta next <- A.growNoZ next delta key <- V.grow key delta value <- V.grow value delta let go i | i < index = do hc <- hashCode ! i when (hc >= 0) $ do let bucket = hc `rem` newSize nx <- buckets ! bucket next <~ i $ nx buckets <~ bucket $ i go (i + 1) | otherwise = return () go 0 let targetBucket = hashCode' `rem` A.length buckets hashCode <~ index $ hashCode' b <- buckets ! targetBucket next <~ index $ b key <~~ index $ key' value <~~ index $ value' buckets <~ targetBucket $ index return Dictionary{..} {-# INLINE resize #-} class DeleteEntry xs where deleteEntry :: (MVector xs x, PrimMonad m) => xs (PrimState m) x -> Int -> m () instance DeleteEntry S.MVector where deleteEntry _ _ = return () instance DeleteEntry U.MVector where deleteEntry _ _ = return () instance DeleteEntry B.MVector where deleteEntry v i = v <~~ i $ undefined -- | /O(1)/ in the best case, /O(n)/ in the worst case. -- Delete entry from 'Dictionary' by given key. delete :: (Eq k, MVector ks k, MVector vs v, Hashable k, PrimMonad m, DeleteEntry ks, DeleteEntry vs) => Dictionary (PrimState m) ks k vs v -> k -> m () delete DRef{..} key' = do Dictionary{..} <- readMutVar getDRef let hashCode' = hash key' .&. mask bucket = hashCode' `rem` A.length buckets go !last !i | i >= 0 = do hc <- hashCode ! i k <- key !~ i if hc == hashCode' && k == key' then do nxt <- next ! i if last < 0 then buckets <~ bucket $ nxt else next <~ last $ nxt hashCode <~ i $ -1 next <~ i =<< refs ! getFreeList deleteEntry key i deleteEntry value i refs <~ getFreeList $ i fc <- refs ! getFreeCount refs <~ getFreeCount $ fc + 1 else go i =<< next ! i | otherwise = return () go (-1) =<< buckets ! bucket {-# INLINE delete #-} deleteWithIndex :: (Eq k, MVector ks k, MVector vs v, Hashable k, PrimMonad m, DeleteEntry ks, DeleteEntry vs) => Int -> Int -> Dictionary_ (PrimState m) ks k vs v -> k -> Int -> Int -> m () deleteWithIndex !bucket !hashCode' d@Dictionary{..} key' !last !i | i >= 0 = do hc <- hashCode ! i k <- key !~ i if hc == hashCode' && k == key' then do nxt <- next ! i if last < 0 then buckets <~ bucket $ nxt else next <~ last $ nxt hashCode <~ i $ -1 next <~ i =<< refs ! getFreeList deleteEntry key i deleteEntry value i refs <~ getFreeList $ i fc <- refs ! getFreeCount refs <~ getFreeCount $ fc + 1 else deleteWithIndex bucket hashCode' d key' i =<< next ! i | otherwise = return () {-# INLINE deleteWithIndex #-} -- | /O(1)/ in the best case, /O(n)/ in the worst case. -- Find value by given key in 'Dictionary'. Like 'lookup'' but return 'Nothing' if value not found. lookup :: (MVector ks k, MVector vs v, PrimMonad m, Hashable k, Eq k) => Dictionary (PrimState m) ks k vs v -> k -> m (Maybe v) lookup = at' {-# INLINE lookup #-} -- | /O(1)/ in the best case, /O(n)/ in the worst case. -- Find value by given key in 'Dictionary'. Throws an error if value not found. lookup' :: (MVector ks k, MVector vs v, PrimMonad m, Hashable k, Eq k) => Dictionary (PrimState m) ks k vs v -> k -> m v lookup' = at {-# INLINE lookup' #-} -- | /O(1)/ in the best case, /O(n)/ in the worst case. Lookup the index of a key , which is its zero - based index in the sequence sorted by keys . -- The index is a number from 0 up to, but not including, the size of the dictionary. lookupIndex :: (MVector ks k, MVector vs v, PrimMonad m, Hashable k, Eq k) => Dictionary (PrimState m) ks k vs v -> k -> m (Maybe Int) lookupIndex ht k = do let safeIndex i | i < 0 = Nothing | otherwise = Just i return . safeIndex =<< findEntry ht k {-# INLINE lookupIndex #-} -- | /O(1)/ Return 'True' if dictionary is empty, 'False' otherwise. null :: (MVector ks k, PrimMonad m) => Dictionary (PrimState m) ks k vs v -> m Bool null ht = return . (== 0) =<< length ht # INLINE null # -- | /O(1)/ Return the number of non-empty entries of dictionary. length :: (MVector ks k, PrimMonad m) => Dictionary (PrimState m) ks k vs v -> m Int length DRef {..} = do Dictionary {..} <- readMutVar getDRef count <- refs ! getCount freeCount <- refs ! getFreeCount return (count - freeCount) # INLINE length # -- | /O(1)/ Return the number of non-empty entries of dictionary. Synonym of 'length'. size :: (MVector ks k, PrimMonad m) => Dictionary (PrimState m) ks k vs v -> m Int size = length # INLINE size # -- | /O(1)/ in the best case, /O(n)/ in the worst case. -- Return 'True' if the specified key is present in the dictionary, 'False' otherwise. member :: (MVector ks k, MVector vs v, PrimMonad m, Hashable k, Eq k) => Dictionary (PrimState m) ks k vs v -> k -> m Bool member ht k = return . (>= 0) =<< findEntry ht k {-# INLINE member #-} -- | /O(1)/ in the best case, /O(n)/ in the worst case. -- The expression @'findWithDefault' ht def k@ returns the value at key @k@ or returns default value -- when the key is not in the dictionary. findWithDefault :: (MVector ks k, MVector vs v, PrimMonad m, Hashable k, Eq k) => Dictionary (PrimState m) ks k vs v -> v -> k -> m v findWithDefault ht v k = return . fromMaybe v =<< at' ht k # INLINE findWithDefault # -- | /O(1)/ in the best case, /O(n)/ in the worst case. The expression ( @'alter ' ht f k@ ) alters the value @x@ at @k@ , or absence thereof . -- 'alter' can be used to insert, delete, or update a value in a 'Dictionary'. -- -- > let f _ = Nothing -- > ht <- fromList [(5,"a"), (3,"b")] -- > alter ht f 7 -- > toList ht > [ ( 3 , " b " ) , ( 5 , " a " ) ] -- -- > ht <- fromList [(5,"a"), (3,"b")] -- > alter ht f 5 -- > toList ht > [ ( 3 " b " ) ] -- -- > let f _ = Just "c" -- > ht <- fromList [(5,"a"), (3,"b")] -- > alter ht f 7 -- > toList ht > [ ( 3 , " b " ) , ( 5 , " a " ) , ( 7 , " c " ) ] -- -- > ht <- fromList [(5,"a"), (3,"b")] -- > alter ht f 5 -- > toList ht > [ ( 3 , " b " ) , ( 5 , " c " ) ] -- alter :: ( MVector ks k, MVector vs v, DeleteEntry ks, DeleteEntry vs , PrimMonad m, Hashable k, Eq k ) => Dictionary (PrimState m) ks k vs v -> (Maybe v -> Maybe v) -> k -> m () alter ht f k = do d@Dictionary{..} <- readMutVar . getDRef $ ht let hashCode' = hash k .&. mask targetBucket = hashCode' `rem` A.length buckets onFound' value' dict i = insertWithIndex targetBucket hashCode' k value' (getDRef ht) dict i onNothing' dict i = deleteWithIndex targetBucket hashCode' d k (-1) i onFound dict i = do d'@Dictionary{..} <- readMutVar . getDRef $ dict v <- value !~ i case f (Just v) of Nothing -> onNothing' d' i Just v' -> onFound' v' d' i onNothing dict = do d' <- readMutVar . getDRef $ dict case f Nothing of Nothing -> return () Just v' -> onFound' v' d' (-1) void $ atWithOrElse ht k onFound onNothing # INLINE alter # -- | /O(1)/ in the best case, /O(n)/ in the worst case. The expression ( @'alterM ' ht f k@ ) alters the value @x@ at @k@ , or absence thereof . -- 'alterM' can be used to insert, delete, or update a value in a 'Dictionary' in the same @'PrimMonad' m@. alterM :: ( MVector ks k, MVector vs v, DeleteEntry ks, DeleteEntry vs , PrimMonad m, Hashable k, Eq k ) => Dictionary (PrimState m) ks k vs v -> (Maybe v -> m (Maybe v)) -> k -> m () alterM ht f k = do d@Dictionary{..} <- readMutVar . getDRef $ ht let hashCode' = hash k .&. mask targetBucket = hashCode' `rem` A.length buckets onFound' value' dict i = insertWithIndex targetBucket hashCode' k value' (getDRef ht) dict i onNothing' dict i = deleteWithIndex targetBucket hashCode' d k (-1) i onFound dict i = do d'@Dictionary{..} <- readMutVar . getDRef $ dict v <- value !~ i res <- f (Just v) case res of Nothing -> onNothing' d' i Just v' -> onFound' v' d' i onNothing dict = do d' <- readMutVar . getDRef $ dict res <- f Nothing case res of Nothing -> return () Just v' -> onFound' v' d' (-1) void $ atWithOrElse ht k onFound onNothing # INLINE alterM # -- * Combine -- | /O(min n m)/ in the best case, /O(min n m * max n m)/ in the worst case. The union of two maps . -- If a key occurs in both maps, the mapping from the first will be the mapping in the result . union :: (MVector ks k, MVector vs v, PrimMonad m, Hashable k, Eq k) => Dictionary (PrimState m) ks k vs v -> Dictionary (PrimState m) ks k vs v -> m (Dictionary (PrimState m) ks k vs v) union = unionWith const # INLINE union # -- | /O(min n m)/ in the best case, /O(min n m * max n m)/ in the worst case. The union of two maps . The provided function ( first argument ) will be used to compute the result . unionWith :: (MVector ks k, MVector ks k, MVector vs v, PrimMonad m, Hashable k, Eq k) => (v -> v -> v) -> Dictionary (PrimState m) ks k vs v -> Dictionary (PrimState m) ks k vs v -> m (Dictionary (PrimState m) ks k vs v) unionWith f = unionWithKey (const f) # INLINE unionWith # -- | /O(min n m)/ in the best case, /O(min n m * max n m)/ in the worst case. The union of two maps . -- If a key occurs in both maps, the provided function ( first argument ) will be used to compute the result . unionWithKey :: (MVector ks k, MVector vs v, PrimMonad m, Hashable k, Eq k) => (k -> v -> v -> v) -> Dictionary (PrimState m) ks k vs v -> Dictionary (PrimState m) ks k vs v -> m (Dictionary (PrimState m) ks k vs v) unionWithKey f t1 t2 = do l1 <- length t1 l2 <- length t2 let smallest = min l1 l2 greatest = max l1 l2 g k v1 v2 = if smallest == l1 then f k v1 v2 else f k v2 v1 (tS, tG) = if smallest == l1 then (t1, t2) else (t2, t1) ht <- clone tG dictG <- readMutVar . getDRef $ tG dictS <- readMutVar . getDRef $ tS hcsS <- A.freeze . hashCode $ dictS let indices = catMaybes . zipWith collect [0 ..] . take smallest . A.primArrayToList $ hcsS collect i _ | hcsS !. i >= 0 = Just i | otherwise = Nothing go !i = do k <- key dictS !~ i v <- value dictS !~ i let hashCode' = hash k .&. mask targetBucket = hashCode' `rem` A.length (buckets dictG) onFound dict i = do d@Dictionary{..} <- readMutVar . getDRef $ dict vG <- value !~ i insertWithIndex targetBucket hashCode' k (g k v vG) (getDRef dict) d i onNothing dict = do d@Dictionary{..} <- readMutVar . getDRef $ dict insertWithIndex targetBucket hashCode' k v (getDRef dict) d =<< buckets ! targetBucket void $ atWithOrElse ht k onFound onNothing mapM_ go indices return ht # INLINE unionWithKey # -- * Difference and intersection -- | /O(n)/ in the best case, /O(n * m)/ in the worst case. Difference of two tables . Return elements of the first table not existing in the second . difference :: (MVector ks k, MVector vs v, MVector vs w, PrimMonad m, Hashable k, Eq k) => Dictionary (PrimState m) ks k vs v -> Dictionary (PrimState m) ks k vs w -> m (Dictionary (PrimState m) ks k vs v) difference a b = do kvs <- toList a ht <- initialize 10 mapM_ (go ht) kvs return ht where go ht (!k, !v) = do mv <- lookup b k case mv of Nothing -> insert ht k v _ -> return () # INLINE difference # -- | /O(n)/ in the best case, /O(n * m)/ in the worst case. Difference with a combining function . When two equal keys are -- encountered, the combining function is applied to the values of these keys. -- If it returns 'Nothing', the element is discarded (proper set difference). If it returns ( @'Just ' y@ ) , the element is updated with a new value @y@. differenceWith :: (MVector ks k, MVector vs v, MVector vs w, PrimMonad m, Hashable k, Eq k) => (v -> w -> Maybe v) -> Dictionary (PrimState m) ks k vs v -> Dictionary (PrimState m) ks k vs w -> m (Dictionary (PrimState m) ks k vs v) differenceWith f a b = do kvs <- toList a ht <- initialize 10 mapM_ (go ht) kvs return ht where go ht (!k, !v) = do mv <- lookup b k case mv of Nothing -> insert ht k v Just w -> maybe (return ()) (insert ht k) (f v w) {-# INLINE differenceWith #-} -- | /O(n)/ in the best case, /O(n * m)/ in the worst case. Intersection of two maps . Return elements of the first map for keys existing in the second . intersection :: (MVector ks k, MVector vs v, MVector vs w, PrimMonad m, Hashable k, Eq k) => Dictionary (PrimState m) ks k vs v -> Dictionary (PrimState m) ks k vs w -> m (Dictionary (PrimState m) ks k vs v) intersection a b = do kvs <- toList a ht <- initialize 10 mapM_ (go ht) kvs return ht where go ht (!k, !v) = do mv <- lookup b k case mv of Nothing -> return () Just _ -> insert ht k v # INLINE intersection # | Intersection of two maps . If a key occurs in both maps the provided function is used to combine the values from the two -- maps. intersectionWith :: (MVector ks k, MVector vs v1, MVector vs v2, MVector vs v3, PrimMonad m, Hashable k, Eq k) => (v1 -> v2 -> v3) -> Dictionary (PrimState m) ks k vs v1 -> Dictionary (PrimState m) ks k vs v2 -> m (Dictionary (PrimState m) ks k vs v3) intersectionWith f a b = do kvs <- toList a ht <- initialize 10 mapM_ (go ht) kvs return ht where go ht (!k, !v) = do mv <- lookup b k case mv of Nothing -> return () Just w -> insert ht k (f v w) {-# INLINE intersectionWith #-} | Intersection of two maps . If a key occurs in both maps the provided function is used to combine the values from the two -- maps. intersectionWithKey :: (MVector ks k, MVector vs v1, MVector vs v2, MVector vs v3, PrimMonad m, Hashable k, Eq k) => (k -> v1 -> v2 -> v3) -> Dictionary (PrimState m) ks k vs v1 -> Dictionary (PrimState m) ks k vs v2 -> m (Dictionary (PrimState m) ks k vs v3) intersectionWithKey f a b = do kvs <- toList a ht <- initialize 10 mapM_ (go ht) kvs return ht where go ht (!k, !v) = do mv <- lookup b k case mv of Nothing -> return () Just w -> insert ht k (f k v w) # INLINE intersectionWithKey # -- * List conversions -- | /O(n)/ Convert list to a 'Dictionary'. fromList :: (MVector ks k, MVector vs v, PrimMonad m, Hashable k, Eq k) => [(k, v)] -> m (Dictionary (PrimState m) ks k vs v) fromList kv = do ht <- initialize 1 mapM_ (uncurry (insert ht)) kv return ht # INLINE fromList # -- | /O(n)/ Convert 'Dictionary' to a list. toList :: (MVector ks k, MVector vs v, PrimMonad m, Hashable k, Eq k) => (Dictionary (PrimState m) ks k vs v) -> m [(k, v)] toList DRef {..} = do Dictionary {..} <- readMutVar getDRef hcs <- A.freeze hashCode count <- refs ! getCount let go !i xs | i < 0 = return xs | hcs !. i < 0 = go (i - 1) xs | otherwise = do k <- key !~ i v <- value !~ i go (i - 1) ((k, v) : xs) # INLINE go # go (count - 1) [] # INLINE toList # -- * Extras primes :: UI.Vector Int primes = UI.fromList [ 3, 7, 11, 17, 23, 29, 37, 47, 59, 71, 89, 107, 131, 163, 197, 239, 293, 353, 431, 521, 631, 761, 919, 1103, 1327, 1597, 1931, 2333, 2801, 3371, 4049, 4861, 5839, 7013, 8419, 10103, 12143, 14591, 17519, 21023, 25229, 30293, 36353, 43627, 52361, 62851, 75431, 90523, 108631, 130363, 156437, 187751, 225307, 270371, 324449, 389357, 467237, 560689, 672827, 807403, 968897, 1162687, 1395263, 1674319, 2009191, 2411033, 2893249, 3471899, 4166287, 4999559, 5999471, 7199369, 8639249, 10367101, 12440537, 14928671, 17914409, 21497293, 25796759, 30956117, 37147349, 44576837, 53492207, 64190669, 77028803, 92434613, 110921543, 133105859, 159727031, 191672443, 230006941, 276008387, 331210079, 397452101, 476942527, 572331049, 686797261, 824156741, 988988137, 1186785773, 1424142949, 1708971541, 2050765853 ] getPrime :: Int -> Int getPrime n = fromJust $ UI.find (>= n) primes
null
https://raw.githubusercontent.com/klapaucius/vector-hashtables/820aa8616347a2634d5a86b9c2ab6e4eef9b6508/src/Data/Vector/Hashtables/Internal.hs
haskell
| Single-element mutable array of 'Dictionary_' with primitive state token parameterized with state, keys and values types. *Example*: >>> import qualified Data.Vector.Storable.Mutable as VM Different vectors could be used for keys and values: - storable, - mutable, - unboxed. In most cases unboxed vectors should be used. Nevertheless, it is up to you to decide about final form of hastable. | Represents collection of hashtable internal primitive arrays and vectors. - hash codes, - references to the next element, - buckets, - keys - and values. | Represents immutable dictionary as collection of immutable arrays and vectors. See 'unsafeFreeze' and 'unsafeThaw' for conversions from/to mutable dictionary. | /O(1)/ in the best case, /O(n)/ in the worst case. If entry not found @-1@ returned. | Infix version of @unsafeRead@. | Infix version of @unsafeIndex@. | Infix version of @unsafeWrite@. | Infix version of @readPrimArray@. | Infix version of @indexPrimArray@. | /O(1)/ Dictionary with given capacity. | Create a copy of mutable dictionary. | /O(1)/ Unsafe convert a mutable dictionary to an immutable one without copying. The mutable dictionary may not be used after this operation. The immutable dictionary may not be used after this operation. | /O(n)/ Retrieve list of keys from 'Dictionary'. | /O(n)/ Retrieve list of values from 'Dictionary'. | /O(1)/ in the best case, /O(n)/ in the worst case. Find value by given key in 'Dictionary'. Throws an error if value not found. | /O(1)/ in the best case, /O(n)/ in the worst case. Find value by given key in 'Dictionary'. Like 'at'' but return 'Nothing' if value not found. # INLINE at' # # INLINE atWithOrElse # | /O(1)/ in the best case, /O(n)/ in the worst case. Find dictionary entry by given key. If entry not found @-1@ returned. | /O(1)/ in the best case, /O(n)/ in the worst case. Insert key and value in dictionary by key's hash. If entry with given key found value will be replaced. # INLINE resize # | /O(1)/ in the best case, /O(n)/ in the worst case. Delete entry from 'Dictionary' by given key. # INLINE delete # # INLINE deleteWithIndex # | /O(1)/ in the best case, /O(n)/ in the worst case. Find value by given key in 'Dictionary'. Like 'lookup'' but return 'Nothing' if value not found. # INLINE lookup # | /O(1)/ in the best case, /O(n)/ in the worst case. Find value by given key in 'Dictionary'. Throws an error if value not found. # INLINE lookup' # | /O(1)/ in the best case, /O(n)/ in the worst case. The index is a number from 0 up to, but not including, the size of the dictionary. # INLINE lookupIndex # | /O(1)/ Return 'True' if dictionary is empty, 'False' otherwise. | /O(1)/ Return the number of non-empty entries of dictionary. | /O(1)/ Return the number of non-empty entries of dictionary. Synonym of 'length'. | /O(1)/ in the best case, /O(n)/ in the worst case. Return 'True' if the specified key is present in the dictionary, 'False' otherwise. # INLINE member # | /O(1)/ in the best case, /O(n)/ in the worst case. The expression @'findWithDefault' ht def k@ returns when the key is not in the dictionary. | /O(1)/ in the best case, /O(n)/ in the worst case. 'alter' can be used to insert, delete, or update a value in a 'Dictionary'. > let f _ = Nothing > ht <- fromList [(5,"a"), (3,"b")] > alter ht f 7 > toList ht > ht <- fromList [(5,"a"), (3,"b")] > alter ht f 5 > toList ht > let f _ = Just "c" > ht <- fromList [(5,"a"), (3,"b")] > alter ht f 7 > toList ht > ht <- fromList [(5,"a"), (3,"b")] > alter ht f 5 > toList ht | /O(1)/ in the best case, /O(n)/ in the worst case. 'alterM' can be used to insert, delete, or update a value in a 'Dictionary' in the same @'PrimMonad' m@. * Combine | /O(min n m)/ in the best case, /O(min n m * max n m)/ in the worst case. If a key occurs in both maps, | /O(min n m)/ in the best case, /O(min n m * max n m)/ in the worst case. | /O(min n m)/ in the best case, /O(min n m * max n m)/ in the worst case. If a key occurs in both maps, * Difference and intersection | /O(n)/ in the best case, /O(n * m)/ in the worst case. | /O(n)/ in the best case, /O(n * m)/ in the worst case. encountered, the combining function is applied to the values of these keys. If it returns 'Nothing', the element is discarded (proper set difference). If # INLINE differenceWith # | /O(n)/ in the best case, /O(n * m)/ in the worst case. maps. # INLINE intersectionWith # maps. * List conversions | /O(n)/ Convert list to a 'Dictionary'. | /O(n)/ Convert 'Dictionary' to a list. * Extras
| Module : Data . Vector . . Internal Description : Provides internals of hashtables and set of utilities . Copyright : ( c ) klapaucius , swamp_agr , 2016 - 2021 License : Module : Data.Vector.Hashtables.Internal Description : Provides internals of hashtables and set of utilities. Copyright : (c) klapaucius, swamp_agr, 2016-2021 License : BSD3 -} # LANGUAGE BangPatterns # # LANGUAGE FlexibleContexts # # LANGUAGE RecordWildCards # # LANGUAGE TypeFamilies # module Data.Vector.Hashtables.Internal where import Control.Monad import Control.Monad.Primitive import Data.Bits import Data.Hashable import Data.Maybe import Data.Primitive.MutVar import Data.Vector.Generic (Mutable, Vector) import qualified Data.Vector.Generic as VI import Data.Vector.Generic.Mutable (MVector) import qualified Data.Vector.Generic.Mutable as V import qualified Data.Vector.Mutable as B import qualified Data.Vector.Storable as SI import qualified Data.Vector.Storable.Mutable as S import qualified Data.Vector.Unboxed as UI import qualified Data.Vector.Unboxed.Mutable as U import qualified GHC.Exts as Exts import Prelude hiding (length, lookup) import qualified Data.Primitive.PrimArray as A import qualified Data.Primitive.PrimArray.Utils as A import Data.Vector.Hashtables.Internal.Mask (mask) | for ' MutablePrimArray s Int ' . type IntArray s = A.MutablePrimArray s Int > > > import qualified Data . Vector . . Mutable as UM > > > import Data . Vector . > > > type HashTable k v = Dictionary ( PrimState IO ) VM.MVector k UM.MVector v newtype Dictionary s ks k vs v = DRef { getDRef :: MutVar s (Dictionary_ s ks k vs v) } data Dictionary_ s ks k vs v = Dictionary { hashCode, next, buckets, refs :: IntArray s, key :: ks s k, value :: vs s v } getCount, getFreeList, getFreeCount :: Int getCount = 0 getFreeList = 1 getFreeCount = 2 data FrozenDictionary ks k vs v = FrozenDictionary { fhashCode, fnext, fbuckets :: A.PrimArray Int, count, freeList, freeCount :: Int, fkey :: ks k, fvalue :: vs v } deriving (Eq, Ord, Show) Find dictionary entry by given key in immutable ' FrozenDictionary ' . findElem :: (Vector ks k, Vector vs v, Hashable k, Eq k) => FrozenDictionary ks k vs v -> k -> Int findElem FrozenDictionary{..} key' = go $ fbuckets !. (hashCode' `rem` A.sizeofPrimArray fbuckets) where hashCode' = hash key' .&. mask go i | i >= 0 = if fhashCode !. i == hashCode' && fkey !.~ i == key' then i else go $ fnext !. i | otherwise = -1 # INLINE findElem # (!~) :: (MVector v a, PrimMonad m) => v (PrimState m) a -> Int -> m a (!~) = V.unsafeRead (!.~) :: (Vector v a) => v a -> Int -> a (!.~) = VI.unsafeIndex (<~~) :: (MVector v a, PrimMonad m) => v (PrimState m) a -> Int -> a -> m () (<~~) = V.unsafeWrite (!) :: PrimMonad m => A.MutablePrimArray (PrimState m) Int -> Int -> m Int (!) = A.readPrimArray (!.) :: A.PrimArray Int -> Int -> Int (!.) = A.indexPrimArray | Infix version of @writePrimArray@. (<~) :: PrimMonad m => A.MutablePrimArray (PrimState m) Int -> Int -> Int -> m () (<~) = A.writePrimArray initialize :: (MVector ks k, MVector vs v, PrimMonad m) => Int -> m (Dictionary (PrimState m) ks k vs v) initialize capacity = do let size = getPrime capacity hashCode <- A.replicate size 0 next <- A.replicate size 0 key <- V.new size value <- V.new size buckets <- A.replicate size (-1) refs <- A.replicate 3 0 refs <~ 1 $ -1 dr <- newMutVar Dictionary {..} return . DRef $ dr clone :: (MVector ks k, MVector vs v, PrimMonad m) => Dictionary (PrimState m) ks k vs v -> m (Dictionary (PrimState m) ks k vs v) clone DRef {..} = do Dictionary {..} <- readMutVar getDRef hashCode <- A.clone hashCode next <- A.clone next key <- V.clone key value <- V.clone value buckets <- A.clone buckets refs <- A.clone refs dr <- newMutVar Dictionary {..} return . DRef $ dr unsafeFreeze :: (VI.Vector ks k, VI.Vector vs v, PrimMonad m) => Dictionary (PrimState m) (Mutable ks) k (Mutable vs) v -> m (FrozenDictionary ks k vs v) unsafeFreeze DRef {..} = do Dictionary {..} <- readMutVar getDRef fhashCode <- A.unsafeFreeze hashCode fnext <- A.unsafeFreeze next fbuckets <- A.unsafeFreeze buckets count <- refs ! getCount freeList <- refs ! getFreeList freeCount <- refs ! getFreeCount fkey <- VI.unsafeFreeze key fvalue <- VI.unsafeFreeze value return FrozenDictionary {..} | /O(1)/ Unsafely convert immutable ' FrozenDictionary ' to a mutable ' Dictionary ' without copying . unsafeThaw :: (Vector ks k, Vector vs v, PrimMonad m) => FrozenDictionary ks k vs v -> m (Dictionary (PrimState m) (Mutable ks) k (Mutable vs) v) unsafeThaw FrozenDictionary {..} = do hashCode <- A.unsafeThaw fhashCode next <- A.unsafeThaw fnext buckets <- A.unsafeThaw fbuckets refs <- A.unsafeThaw $ A.primArrayFromListN 3 [count, freeList, freeCount] key <- VI.unsafeThaw fkey value <- VI.unsafeThaw fvalue dr <- newMutVar Dictionary {..} return . DRef $ dr keys :: (Vector ks k, PrimMonad m) => Dictionary (PrimState m) (Mutable ks) k vs v -> m (ks k) keys DRef{..} = do Dictionary{..} <- readMutVar getDRef hcs <- A.freeze hashCode ks <- VI.freeze key count <- refs ! getCount return . VI.ifilter (\i _ -> hcs !. i >= 0) . VI.take count $ ks values :: (Vector vs v, PrimMonad m) => Dictionary (PrimState m) ks k (Mutable vs) v -> m (vs v) values DRef{..} = do Dictionary{..} <- readMutVar getDRef hcs <- A.freeze hashCode vs <- VI.freeze value count <- refs ! getCount return . VI.ifilter (\i _ -> hcs !. i >= 0) . VI.take count $ vs at :: (MVector ks k, MVector vs v, PrimMonad m, Hashable k, Eq k) => Dictionary (PrimState m) ks k vs v -> k -> m v at d k = do i <- findEntry d k if i >= 0 then do Dictionary{..} <- readMutVar . getDRef $ d value !~ i else error "KeyNotFoundException!" # INLINE at # at' :: (MVector ks k, MVector vs v, PrimMonad m, Hashable k, Eq k) => Dictionary (PrimState m) ks k vs v -> k -> m (Maybe v) at' d k = do i <- findEntry d k if i >= 0 then do Dictionary{..} <- readMutVar . getDRef $ d Just <$> value !~ i else pure Nothing atWithOrElse :: (MVector ks k, MVector vs v, PrimMonad m, Hashable k, Eq k) => Dictionary (PrimState m) ks k vs v -> k -> (Dictionary (PrimState m) ks k vs v -> Int -> m a) -> (Dictionary (PrimState m) ks k vs v -> m a) -> m a atWithOrElse d k onFound onNothing = do i <- findEntry d k if i >= 0 then onFound d i else onNothing d findEntry :: (MVector ks k, MVector vs v, PrimMonad m, Hashable k, Eq k) => Dictionary (PrimState m) ks k vs v -> k -> m Int findEntry d key' = do Dictionary{..} <- readMutVar . getDRef $ d let hashCode' = hash key' .&. mask go i | i >= 0 = do hc <- hashCode ! i if hc == hashCode' then do k <- key !~ i if k == key' then return i else go =<< next ! i else go =<< next ! i | otherwise = return $ -1 go =<< buckets ! (hashCode' `rem` A.length buckets) # INLINE findEntry # insert :: (MVector ks k, MVector vs v, PrimMonad m, Hashable k, Eq k) => Dictionary (PrimState m) ks k vs v -> k -> v -> m () insert DRef{..} key' value' = do d@Dictionary{..} <- readMutVar getDRef let hashCode' = hash key' .&. mask targetBucket = hashCode' `rem` A.length buckets go i | i >= 0 = do hc <- hashCode ! i if hc == hashCode' then do k <- key !~ i if k == key' then value <~~ i $ value' else go =<< next ! i else go =<< next ! i | otherwise = addOrResize addOrResize = do freeCount <- refs ! getFreeCount if freeCount > 0 then do index <- refs ! getFreeList nxt <- next ! index refs <~ getFreeList $ nxt refs <~ getFreeCount $ freeCount - 1 add index targetBucket else do count <- refs ! getCount refs <~ getCount $ count + 1 if count == A.length next then do nd <- resize d count hashCode' key' value' writeMutVar getDRef nd else add (fromIntegral count) (fromIntegral targetBucket) add !index !targetBucket = do hashCode <~ index $ hashCode' b <- buckets ! targetBucket next <~ index $ b key <~~ index $ key' value <~~ index $ value' buckets <~ targetBucket $ index go =<< buckets ! targetBucket # INLINE insert # insertWithIndex :: (MVector ks k, MVector vs v, PrimMonad m, Hashable k, Eq k) => Int -> Int -> k -> v -> MutVar (PrimState m) (Dictionary_ (PrimState m) ks k vs v) -> Dictionary_ (PrimState m) ks k vs v -> Int -> m () insertWithIndex !targetBucket !hashCode' key' value' getDRef d@Dictionary{..} = go where go i | i >= 0 = do hc <- hashCode ! i if hc == hashCode' then do k <- key !~ i if k == key' then value <~~ i $ value' else go =<< next ! i else go =<< next ! i | otherwise = addOrResize targetBucket hashCode' key' value' getDRef d # INLINE insertWithIndex # addOrResize :: (MVector ks k, MVector vs v, PrimMonad m, Hashable k, Eq k) => Int -> Int -> k -> v -> MutVar (PrimState m) (Dictionary_ (PrimState m) ks k vs v) -> Dictionary_ (PrimState m) ks k vs v -> m () addOrResize !targetBucket !hashCode' !key' !value' dref d@Dictionary{..} = do freeCount <- refs ! getFreeCount if freeCount > 0 then do index <- refs ! getFreeList nxt <- next ! index refs <~ getFreeList $ nxt refs <~ getFreeCount $ freeCount - 1 add index targetBucket hashCode' key' value' d else do count <- refs ! getCount refs <~ getCount $ count + 1 if count == A.length next then do nd <- resize d count hashCode' key' value' writeMutVar dref nd else add (fromIntegral count) (fromIntegral targetBucket) hashCode' key' value' d # INLINE addOrResize # add :: (MVector ks k, MVector vs v, PrimMonad m, Hashable k, Eq k) => Int -> Int -> Int -> k -> v -> Dictionary_ (PrimState m) ks k vs v -> m () add !index !targetBucket !hashCode' !key' !value' Dictionary{..} = do hashCode <~ index $ hashCode' b <- buckets ! targetBucket next <~ index $ b key <~~ index $ key' value <~~ index $ value' buckets <~ targetBucket $ index # INLINE add # resize Dictionary{..} index hashCode' key' value' = do let newSize = getPrime (index*2) delta = newSize - index buckets <- A.replicate newSize (-1) hashCode <- A.growNoZ hashCode delta next <- A.growNoZ next delta key <- V.grow key delta value <- V.grow value delta let go i | i < index = do hc <- hashCode ! i when (hc >= 0) $ do let bucket = hc `rem` newSize nx <- buckets ! bucket next <~ i $ nx buckets <~ bucket $ i go (i + 1) | otherwise = return () go 0 let targetBucket = hashCode' `rem` A.length buckets hashCode <~ index $ hashCode' b <- buckets ! targetBucket next <~ index $ b key <~~ index $ key' value <~~ index $ value' buckets <~ targetBucket $ index return Dictionary{..} class DeleteEntry xs where deleteEntry :: (MVector xs x, PrimMonad m) => xs (PrimState m) x -> Int -> m () instance DeleteEntry S.MVector where deleteEntry _ _ = return () instance DeleteEntry U.MVector where deleteEntry _ _ = return () instance DeleteEntry B.MVector where deleteEntry v i = v <~~ i $ undefined delete :: (Eq k, MVector ks k, MVector vs v, Hashable k, PrimMonad m, DeleteEntry ks, DeleteEntry vs) => Dictionary (PrimState m) ks k vs v -> k -> m () delete DRef{..} key' = do Dictionary{..} <- readMutVar getDRef let hashCode' = hash key' .&. mask bucket = hashCode' `rem` A.length buckets go !last !i | i >= 0 = do hc <- hashCode ! i k <- key !~ i if hc == hashCode' && k == key' then do nxt <- next ! i if last < 0 then buckets <~ bucket $ nxt else next <~ last $ nxt hashCode <~ i $ -1 next <~ i =<< refs ! getFreeList deleteEntry key i deleteEntry value i refs <~ getFreeList $ i fc <- refs ! getFreeCount refs <~ getFreeCount $ fc + 1 else go i =<< next ! i | otherwise = return () go (-1) =<< buckets ! bucket deleteWithIndex :: (Eq k, MVector ks k, MVector vs v, Hashable k, PrimMonad m, DeleteEntry ks, DeleteEntry vs) => Int -> Int -> Dictionary_ (PrimState m) ks k vs v -> k -> Int -> Int -> m () deleteWithIndex !bucket !hashCode' d@Dictionary{..} key' !last !i | i >= 0 = do hc <- hashCode ! i k <- key !~ i if hc == hashCode' && k == key' then do nxt <- next ! i if last < 0 then buckets <~ bucket $ nxt else next <~ last $ nxt hashCode <~ i $ -1 next <~ i =<< refs ! getFreeList deleteEntry key i deleteEntry value i refs <~ getFreeList $ i fc <- refs ! getFreeCount refs <~ getFreeCount $ fc + 1 else deleteWithIndex bucket hashCode' d key' i =<< next ! i | otherwise = return () lookup :: (MVector ks k, MVector vs v, PrimMonad m, Hashable k, Eq k) => Dictionary (PrimState m) ks k vs v -> k -> m (Maybe v) lookup = at' lookup' :: (MVector ks k, MVector vs v, PrimMonad m, Hashable k, Eq k) => Dictionary (PrimState m) ks k vs v -> k -> m v lookup' = at Lookup the index of a key , which is its zero - based index in the sequence sorted by keys . lookupIndex :: (MVector ks k, MVector vs v, PrimMonad m, Hashable k, Eq k) => Dictionary (PrimState m) ks k vs v -> k -> m (Maybe Int) lookupIndex ht k = do let safeIndex i | i < 0 = Nothing | otherwise = Just i return . safeIndex =<< findEntry ht k null :: (MVector ks k, PrimMonad m) => Dictionary (PrimState m) ks k vs v -> m Bool null ht = return . (== 0) =<< length ht # INLINE null # length :: (MVector ks k, PrimMonad m) => Dictionary (PrimState m) ks k vs v -> m Int length DRef {..} = do Dictionary {..} <- readMutVar getDRef count <- refs ! getCount freeCount <- refs ! getFreeCount return (count - freeCount) # INLINE length # size :: (MVector ks k, PrimMonad m) => Dictionary (PrimState m) ks k vs v -> m Int size = length # INLINE size # member :: (MVector ks k, MVector vs v, PrimMonad m, Hashable k, Eq k) => Dictionary (PrimState m) ks k vs v -> k -> m Bool member ht k = return . (>= 0) =<< findEntry ht k the value at key @k@ or returns default value findWithDefault :: (MVector ks k, MVector vs v, PrimMonad m, Hashable k, Eq k) => Dictionary (PrimState m) ks k vs v -> v -> k -> m v findWithDefault ht v k = return . fromMaybe v =<< at' ht k # INLINE findWithDefault # The expression ( @'alter ' ht f k@ ) alters the value @x@ at @k@ , or absence thereof . > [ ( 3 , " b " ) , ( 5 , " a " ) ] > [ ( 3 " b " ) ] > [ ( 3 , " b " ) , ( 5 , " a " ) , ( 7 , " c " ) ] > [ ( 3 , " b " ) , ( 5 , " c " ) ] alter :: ( MVector ks k, MVector vs v, DeleteEntry ks, DeleteEntry vs , PrimMonad m, Hashable k, Eq k ) => Dictionary (PrimState m) ks k vs v -> (Maybe v -> Maybe v) -> k -> m () alter ht f k = do d@Dictionary{..} <- readMutVar . getDRef $ ht let hashCode' = hash k .&. mask targetBucket = hashCode' `rem` A.length buckets onFound' value' dict i = insertWithIndex targetBucket hashCode' k value' (getDRef ht) dict i onNothing' dict i = deleteWithIndex targetBucket hashCode' d k (-1) i onFound dict i = do d'@Dictionary{..} <- readMutVar . getDRef $ dict v <- value !~ i case f (Just v) of Nothing -> onNothing' d' i Just v' -> onFound' v' d' i onNothing dict = do d' <- readMutVar . getDRef $ dict case f Nothing of Nothing -> return () Just v' -> onFound' v' d' (-1) void $ atWithOrElse ht k onFound onNothing # INLINE alter # The expression ( @'alterM ' ht f k@ ) alters the value @x@ at @k@ , or absence thereof . alterM :: ( MVector ks k, MVector vs v, DeleteEntry ks, DeleteEntry vs , PrimMonad m, Hashable k, Eq k ) => Dictionary (PrimState m) ks k vs v -> (Maybe v -> m (Maybe v)) -> k -> m () alterM ht f k = do d@Dictionary{..} <- readMutVar . getDRef $ ht let hashCode' = hash k .&. mask targetBucket = hashCode' `rem` A.length buckets onFound' value' dict i = insertWithIndex targetBucket hashCode' k value' (getDRef ht) dict i onNothing' dict i = deleteWithIndex targetBucket hashCode' d k (-1) i onFound dict i = do d'@Dictionary{..} <- readMutVar . getDRef $ dict v <- value !~ i res <- f (Just v) case res of Nothing -> onNothing' d' i Just v' -> onFound' v' d' i onNothing dict = do d' <- readMutVar . getDRef $ dict res <- f Nothing case res of Nothing -> return () Just v' -> onFound' v' d' (-1) void $ atWithOrElse ht k onFound onNothing # INLINE alterM # The union of two maps . the mapping from the first will be the mapping in the result . union :: (MVector ks k, MVector vs v, PrimMonad m, Hashable k, Eq k) => Dictionary (PrimState m) ks k vs v -> Dictionary (PrimState m) ks k vs v -> m (Dictionary (PrimState m) ks k vs v) union = unionWith const # INLINE union # The union of two maps . The provided function ( first argument ) will be used to compute the result . unionWith :: (MVector ks k, MVector ks k, MVector vs v, PrimMonad m, Hashable k, Eq k) => (v -> v -> v) -> Dictionary (PrimState m) ks k vs v -> Dictionary (PrimState m) ks k vs v -> m (Dictionary (PrimState m) ks k vs v) unionWith f = unionWithKey (const f) # INLINE unionWith # The union of two maps . the provided function ( first argument ) will be used to compute the result . unionWithKey :: (MVector ks k, MVector vs v, PrimMonad m, Hashable k, Eq k) => (k -> v -> v -> v) -> Dictionary (PrimState m) ks k vs v -> Dictionary (PrimState m) ks k vs v -> m (Dictionary (PrimState m) ks k vs v) unionWithKey f t1 t2 = do l1 <- length t1 l2 <- length t2 let smallest = min l1 l2 greatest = max l1 l2 g k v1 v2 = if smallest == l1 then f k v1 v2 else f k v2 v1 (tS, tG) = if smallest == l1 then (t1, t2) else (t2, t1) ht <- clone tG dictG <- readMutVar . getDRef $ tG dictS <- readMutVar . getDRef $ tS hcsS <- A.freeze . hashCode $ dictS let indices = catMaybes . zipWith collect [0 ..] . take smallest . A.primArrayToList $ hcsS collect i _ | hcsS !. i >= 0 = Just i | otherwise = Nothing go !i = do k <- key dictS !~ i v <- value dictS !~ i let hashCode' = hash k .&. mask targetBucket = hashCode' `rem` A.length (buckets dictG) onFound dict i = do d@Dictionary{..} <- readMutVar . getDRef $ dict vG <- value !~ i insertWithIndex targetBucket hashCode' k (g k v vG) (getDRef dict) d i onNothing dict = do d@Dictionary{..} <- readMutVar . getDRef $ dict insertWithIndex targetBucket hashCode' k v (getDRef dict) d =<< buckets ! targetBucket void $ atWithOrElse ht k onFound onNothing mapM_ go indices return ht # INLINE unionWithKey # Difference of two tables . Return elements of the first table not existing in the second . difference :: (MVector ks k, MVector vs v, MVector vs w, PrimMonad m, Hashable k, Eq k) => Dictionary (PrimState m) ks k vs v -> Dictionary (PrimState m) ks k vs w -> m (Dictionary (PrimState m) ks k vs v) difference a b = do kvs <- toList a ht <- initialize 10 mapM_ (go ht) kvs return ht where go ht (!k, !v) = do mv <- lookup b k case mv of Nothing -> insert ht k v _ -> return () # INLINE difference # Difference with a combining function . When two equal keys are it returns ( @'Just ' y@ ) , the element is updated with a new value @y@. differenceWith :: (MVector ks k, MVector vs v, MVector vs w, PrimMonad m, Hashable k, Eq k) => (v -> w -> Maybe v) -> Dictionary (PrimState m) ks k vs v -> Dictionary (PrimState m) ks k vs w -> m (Dictionary (PrimState m) ks k vs v) differenceWith f a b = do kvs <- toList a ht <- initialize 10 mapM_ (go ht) kvs return ht where go ht (!k, !v) = do mv <- lookup b k case mv of Nothing -> insert ht k v Just w -> maybe (return ()) (insert ht k) (f v w) Intersection of two maps . Return elements of the first map for keys existing in the second . intersection :: (MVector ks k, MVector vs v, MVector vs w, PrimMonad m, Hashable k, Eq k) => Dictionary (PrimState m) ks k vs v -> Dictionary (PrimState m) ks k vs w -> m (Dictionary (PrimState m) ks k vs v) intersection a b = do kvs <- toList a ht <- initialize 10 mapM_ (go ht) kvs return ht where go ht (!k, !v) = do mv <- lookup b k case mv of Nothing -> return () Just _ -> insert ht k v # INLINE intersection # | Intersection of two maps . If a key occurs in both maps the provided function is used to combine the values from the two intersectionWith :: (MVector ks k, MVector vs v1, MVector vs v2, MVector vs v3, PrimMonad m, Hashable k, Eq k) => (v1 -> v2 -> v3) -> Dictionary (PrimState m) ks k vs v1 -> Dictionary (PrimState m) ks k vs v2 -> m (Dictionary (PrimState m) ks k vs v3) intersectionWith f a b = do kvs <- toList a ht <- initialize 10 mapM_ (go ht) kvs return ht where go ht (!k, !v) = do mv <- lookup b k case mv of Nothing -> return () Just w -> insert ht k (f v w) | Intersection of two maps . If a key occurs in both maps the provided function is used to combine the values from the two intersectionWithKey :: (MVector ks k, MVector vs v1, MVector vs v2, MVector vs v3, PrimMonad m, Hashable k, Eq k) => (k -> v1 -> v2 -> v3) -> Dictionary (PrimState m) ks k vs v1 -> Dictionary (PrimState m) ks k vs v2 -> m (Dictionary (PrimState m) ks k vs v3) intersectionWithKey f a b = do kvs <- toList a ht <- initialize 10 mapM_ (go ht) kvs return ht where go ht (!k, !v) = do mv <- lookup b k case mv of Nothing -> return () Just w -> insert ht k (f k v w) # INLINE intersectionWithKey # fromList :: (MVector ks k, MVector vs v, PrimMonad m, Hashable k, Eq k) => [(k, v)] -> m (Dictionary (PrimState m) ks k vs v) fromList kv = do ht <- initialize 1 mapM_ (uncurry (insert ht)) kv return ht # INLINE fromList # toList :: (MVector ks k, MVector vs v, PrimMonad m, Hashable k, Eq k) => (Dictionary (PrimState m) ks k vs v) -> m [(k, v)] toList DRef {..} = do Dictionary {..} <- readMutVar getDRef hcs <- A.freeze hashCode count <- refs ! getCount let go !i xs | i < 0 = return xs | hcs !. i < 0 = go (i - 1) xs | otherwise = do k <- key !~ i v <- value !~ i go (i - 1) ((k, v) : xs) # INLINE go # go (count - 1) [] # INLINE toList # primes :: UI.Vector Int primes = UI.fromList [ 3, 7, 11, 17, 23, 29, 37, 47, 59, 71, 89, 107, 131, 163, 197, 239, 293, 353, 431, 521, 631, 761, 919, 1103, 1327, 1597, 1931, 2333, 2801, 3371, 4049, 4861, 5839, 7013, 8419, 10103, 12143, 14591, 17519, 21023, 25229, 30293, 36353, 43627, 52361, 62851, 75431, 90523, 108631, 130363, 156437, 187751, 225307, 270371, 324449, 389357, 467237, 560689, 672827, 807403, 968897, 1162687, 1395263, 1674319, 2009191, 2411033, 2893249, 3471899, 4166287, 4999559, 5999471, 7199369, 8639249, 10367101, 12440537, 14928671, 17914409, 21497293, 25796759, 30956117, 37147349, 44576837, 53492207, 64190669, 77028803, 92434613, 110921543, 133105859, 159727031, 191672443, 230006941, 276008387, 331210079, 397452101, 476942527, 572331049, 686797261, 824156741, 988988137, 1186785773, 1424142949, 1708971541, 2050765853 ] getPrime :: Int -> Int getPrime n = fromJust $ UI.find (>= n) primes
98e35a2c42cd15a3e435cc401f074fc8a7ab3d9308e8f709c80631d0a8ba03a9
amnh/PCG
Shared.hs
----------------------------------------------------------------------------- -- | -- Module : Bio.Character.Decoration.Shared Copyright : ( c ) 2015 - 2021 Ward Wheeler -- License : BSD-style -- -- Maintainer : -- Stability : provisional -- Portability : portable -- ----------------------------------------------------------------------------- {-# LANGUAGE FlexibleContexts #-} # LANGUAGE FunctionalDependencies # # LANGUAGE MultiParamTypeClasses # module Bio.Character.Decoration.Shared where import Control.Lens.Type import Data.Range import Numeric.Extended -- | -- Represents a character decoration that has a bounded interval for the character. -- -- Used for Additive character scoring. class ( HasIntervalCharacter d c , Ranged c , ExtendedNumber (Bound c) , Num (Finite (Bound c)) , Num (Bound c) , Ord (Bound c) ) => RangedCharacterDecoration d c where -- | -- A 'Lens' for the 'isLeaf' field. class HasIsLeaf s a | s -> a where {-# MINIMAL isLeaf #-} isLeaf :: Lens' s a -- | -- A 'Lens' for the 'characterCost' field. class HasCharacterCost s a | s -> a where {-# MINIMAL characterCost #-} characterCost :: Lens' s a -- | A ' Lens ' for the ' ' field . class HasIntervalCharacter s a | s -> a where {-# MINIMAL intervalCharacter #-} intervalCharacter :: Lens' s a
null
https://raw.githubusercontent.com/amnh/PCG/9341efe0ec2053302c22b4466157d0a24ed18154/lib/core/data-structures/src/Bio/Character/Decoration/Shared.hs
haskell
--------------------------------------------------------------------------- | Module : Bio.Character.Decoration.Shared License : BSD-style Maintainer : Stability : provisional Portability : portable --------------------------------------------------------------------------- # LANGUAGE FlexibleContexts # | Represents a character decoration that has a bounded interval for the character. Used for Additive character scoring. | A 'Lens' for the 'isLeaf' field. # MINIMAL isLeaf # | A 'Lens' for the 'characterCost' field. # MINIMAL characterCost # | # MINIMAL intervalCharacter #
Copyright : ( c ) 2015 - 2021 Ward Wheeler # LANGUAGE FunctionalDependencies # # LANGUAGE MultiParamTypeClasses # module Bio.Character.Decoration.Shared where import Control.Lens.Type import Data.Range import Numeric.Extended class ( HasIntervalCharacter d c , Ranged c , ExtendedNumber (Bound c) , Num (Finite (Bound c)) , Num (Bound c) , Ord (Bound c) ) => RangedCharacterDecoration d c where class HasIsLeaf s a | s -> a where isLeaf :: Lens' s a class HasCharacterCost s a | s -> a where characterCost :: Lens' s a A ' Lens ' for the ' ' field . class HasIntervalCharacter s a | s -> a where intervalCharacter :: Lens' s a
de24be593283a1b01101adf9984fb9960b1c929d715860d8b8253b8717b9c296
open-company/open-company-web
seen.cljs
(ns oc.web.mixins.seen (:require [rum.core :as rum] [oops.core :refer (oget ocall)] [oc.web.lib.responsive :as responsive] [oc.web.dispatcher :as dis] [oc.web.utils.activity :as au] [oc.web.actions.activity :as aa])) (defn container-nav-mixin [] (let [container-slug (atom nil) sort-type (atom nil)] {:did-mount (fn [s] (reset! container-slug (if (dis/current-board-slug) (keyword (dis/current-board-slug)) (dis/current-contributions-id))) (reset! sort-type (dis/current-sort-type)) (aa/container-nav-in @container-slug @sort-type) s) :did-remount (fn [_ s] (aa/container-nav-in @container-slug @sort-type) s) :will-unmount (fn [s] (aa/container-nav-out @container-slug @sort-type) s)})) (declare maybe-mark-element-seen) (declare unobserve-element) (defn- entry-uuid-from-intersection-entry [intersection-entry] (oget intersection-entry :target.?dataset.?entryUuid)) (defn- seen-observer-cb [intersection-entries _observer] (doseq [intersection-entry (vec intersection-entries)] (maybe-mark-element-seen intersection-entry) (when (or (-> intersection-entry entry-uuid-from-intersection-entry au/need-item-seen? not) (oget intersection-entry :isIntersecting)) (unobserve-element (oget intersection-entry :target))))) (defonce ^{:export true} --seen-intersection-observer (atom nil)) (defn- intersection-observer "Return the intersection observer singleton, creates it if it's not initialized yet." [] (let [opts {:rootMargin (str responsive/navbar-height "px 0px 0px 0px") :threshold 1.0} ] (or @--seen-intersection-observer (reset! --seen-intersection-observer (js/IntersectionObserver. seen-observer-cb (clj->js opts)))))) (defn- unobserve-element "Remove an observed element from the list." [observable-element] (ocall (intersection-observer) :unobserve observable-element)) (defn- maybe-mark-element-seen "If the passed intersection entry is intersecting with the viewport and it is unseen in its board." [intersection-entry] (let [entry-uuid (entry-uuid-from-intersection-entry intersection-entry)] (when (and (oget intersection-entry :isIntersecting) (au/need-item-seen? entry-uuid)) (aa/send-item-seen entry-uuid)))) (defn- observe-element [observable-element] (ocall (intersection-observer) :observe observable-element)) (def item-visible-mixin {:did-mount (fn [s] (when (-> s :rum/args first :activity-data :board-item-unseen) (observe-element (rum/dom-node s))) s) :will-unmount (fn [s] (unobserve-element (rum/dom-node s)) s)})
null
https://raw.githubusercontent.com/open-company/open-company-web/700f751b8284d287432ba73007b104f26669be91/src/main/oc/web/mixins/seen.cljs
clojure
(ns oc.web.mixins.seen (:require [rum.core :as rum] [oops.core :refer (oget ocall)] [oc.web.lib.responsive :as responsive] [oc.web.dispatcher :as dis] [oc.web.utils.activity :as au] [oc.web.actions.activity :as aa])) (defn container-nav-mixin [] (let [container-slug (atom nil) sort-type (atom nil)] {:did-mount (fn [s] (reset! container-slug (if (dis/current-board-slug) (keyword (dis/current-board-slug)) (dis/current-contributions-id))) (reset! sort-type (dis/current-sort-type)) (aa/container-nav-in @container-slug @sort-type) s) :did-remount (fn [_ s] (aa/container-nav-in @container-slug @sort-type) s) :will-unmount (fn [s] (aa/container-nav-out @container-slug @sort-type) s)})) (declare maybe-mark-element-seen) (declare unobserve-element) (defn- entry-uuid-from-intersection-entry [intersection-entry] (oget intersection-entry :target.?dataset.?entryUuid)) (defn- seen-observer-cb [intersection-entries _observer] (doseq [intersection-entry (vec intersection-entries)] (maybe-mark-element-seen intersection-entry) (when (or (-> intersection-entry entry-uuid-from-intersection-entry au/need-item-seen? not) (oget intersection-entry :isIntersecting)) (unobserve-element (oget intersection-entry :target))))) (defonce ^{:export true} --seen-intersection-observer (atom nil)) (defn- intersection-observer "Return the intersection observer singleton, creates it if it's not initialized yet." [] (let [opts {:rootMargin (str responsive/navbar-height "px 0px 0px 0px") :threshold 1.0} ] (or @--seen-intersection-observer (reset! --seen-intersection-observer (js/IntersectionObserver. seen-observer-cb (clj->js opts)))))) (defn- unobserve-element "Remove an observed element from the list." [observable-element] (ocall (intersection-observer) :unobserve observable-element)) (defn- maybe-mark-element-seen "If the passed intersection entry is intersecting with the viewport and it is unseen in its board." [intersection-entry] (let [entry-uuid (entry-uuid-from-intersection-entry intersection-entry)] (when (and (oget intersection-entry :isIntersecting) (au/need-item-seen? entry-uuid)) (aa/send-item-seen entry-uuid)))) (defn- observe-element [observable-element] (ocall (intersection-observer) :observe observable-element)) (def item-visible-mixin {:did-mount (fn [s] (when (-> s :rum/args first :activity-data :board-item-unseen) (observe-element (rum/dom-node s))) s) :will-unmount (fn [s] (unobserve-element (rum/dom-node s)) s)})
d50eee212461f83c2daf615f6813a50b37720c38cc092151e60ca05fdfbf3799
ghc/testsuite
T3743.hs
{-# LANGUAGE ImplicitParams, GADTs #-} module T3743 where class Foo a data M where M :: Foo a => a -> M x :: (?x :: ()) => () x = undefined -- foo :: (?x :: ()) => M -> () foo y = case y of M _ -> x
null
https://raw.githubusercontent.com/ghc/testsuite/998a816ae89c4fd573f4abd7c6abb346cf7ee9af/tests/typecheck/should_compile/T3743.hs
haskell
# LANGUAGE ImplicitParams, GADTs # foo :: (?x :: ()) => M -> ()
module T3743 where class Foo a data M where M :: Foo a => a -> M x :: (?x :: ()) => () x = undefined foo y = case y of M _ -> x
6c5983c18738d186c606187bc492fb76ecb1d922914bcc1ec63174c015b2c900
mejgun/haskell-tdlib
DeleteMessages.hs
{-# LANGUAGE OverloadedStrings #-} -- | module TD.Query.DeleteMessages where import qualified Data.Aeson as A import qualified Data.Aeson.Types as T import qualified Utils as U -- | -- Deletes messages @chat_id Chat identifier @message_ids Identifiers of the messages to be deleted @revoke Pass true to delete messages for all chat members. Always true for supergroups, channels and secret chats data DeleteMessages = DeleteMessages { -- | revoke :: Maybe Bool, -- | message_ids :: Maybe [Int], -- | chat_id :: Maybe Int } deriving (Eq) instance Show DeleteMessages where show DeleteMessages { revoke = revoke_, message_ids = message_ids_, chat_id = chat_id_ } = "DeleteMessages" ++ U.cc [ U.p "revoke" revoke_, U.p "message_ids" message_ids_, U.p "chat_id" chat_id_ ] instance T.ToJSON DeleteMessages where toJSON DeleteMessages { revoke = revoke_, message_ids = message_ids_, chat_id = chat_id_ } = A.object [ "@type" A..= T.String "deleteMessages", "revoke" A..= revoke_, "message_ids" A..= message_ids_, "chat_id" A..= chat_id_ ]
null
https://raw.githubusercontent.com/mejgun/haskell-tdlib/81516bd04c25c7371d4a9a5c972499791111c407/src/TD/Query/DeleteMessages.hs
haskell
# LANGUAGE OverloadedStrings # | | Deletes messages @chat_id Chat identifier @message_ids Identifiers of the messages to be deleted @revoke Pass true to delete messages for all chat members. Always true for supergroups, channels and secret chats | | |
module TD.Query.DeleteMessages where import qualified Data.Aeson as A import qualified Data.Aeson.Types as T import qualified Utils as U data DeleteMessages = DeleteMessages revoke :: Maybe Bool, message_ids :: Maybe [Int], chat_id :: Maybe Int } deriving (Eq) instance Show DeleteMessages where show DeleteMessages { revoke = revoke_, message_ids = message_ids_, chat_id = chat_id_ } = "DeleteMessages" ++ U.cc [ U.p "revoke" revoke_, U.p "message_ids" message_ids_, U.p "chat_id" chat_id_ ] instance T.ToJSON DeleteMessages where toJSON DeleteMessages { revoke = revoke_, message_ids = message_ids_, chat_id = chat_id_ } = A.object [ "@type" A..= T.String "deleteMessages", "revoke" A..= revoke_, "message_ids" A..= message_ids_, "chat_id" A..= chat_id_ ]
f0dc6065dc6b5fbfc5dc285c45c1b3ccfe3908ea9be655e53a605d8ca7ed1ff6
oreillymedia/etudes-for-erlang
weather_sup.erl
-module(weather_sup). -behaviour(supervisor). -export([start_link/0]). % convenience call for startup -export([init/1]). % supervisor calls -define(SERVER, ?MODULE). %%% convenience method for startup start_link() -> supervisor:start_link({local, ?SERVER}, ?MODULE, []). %%% supervisor callback init([]) -> RestartStrategy = one_for_one, one restart every five seconds SupFlags = {RestartStrategy, MaxRestarts, MaxSecondsBetweenRestarts}, Restart = permanent, % or temporary, or transient Shutdown = 2000, % milliseconds, could be infinity or brutal_kill Type = worker, % could also be supervisor Weather = {weather, {weather, start_link, []}, Restart, Shutdown, Type, [weather]}, {ok, {SupFlags, [Weather]}}.
null
https://raw.githubusercontent.com/oreillymedia/etudes-for-erlang/07200372503a8819f9fcc2856f8cb82451be7b48/code/ch11-03/weather_sup.erl
erlang
convenience call for startup supervisor calls convenience method for startup supervisor callback or temporary, or transient milliseconds, could be infinity or brutal_kill could also be supervisor
-module(weather_sup). -behaviour(supervisor). -define(SERVER, ?MODULE). start_link() -> supervisor:start_link({local, ?SERVER}, ?MODULE, []). init([]) -> RestartStrategy = one_for_one, one restart every five seconds SupFlags = {RestartStrategy, MaxRestarts, MaxSecondsBetweenRestarts}, Weather = {weather, {weather, start_link, []}, Restart, Shutdown, Type, [weather]}, {ok, {SupFlags, [Weather]}}.
c5c9395cfe8f26de62e624b35e785b41d70e0e73a88a533d325ab5f3831fe7ec
simonmar/haxl-icfp14-sample-code
Fetch.hs
# LANGUAGE ExistentialQuantification , GADTs , StandaloneDeriving # module Fetch where import Types import MockData import Data.IORef import Control.Applicative import Data.Traversable import Data.Sequence import Data.Monoid import Data.Foldable (toList) -- <<Monad data Result a = Done a | Blocked (Seq BlockedRequest) (Fetch a) newtype Fetch a = Fetch { unFetch :: IO (Result a) } instance Monad Fetch where return a = Fetch $ return (Done a) Fetch m >>= k = Fetch $ do r <- m case r of Done a -> unFetch (k a) Blocked br c -> return (Blocked br (c >>= k)) -- >> < < BlockedRequest data BlockedRequest = forall a . BlockedRequest (Request a) (IORef (FetchStatus a)) -- >> < < dataFetch dataFetch :: Request a -> Fetch a dataFetch request = Fetch $ do ( 1 ) ( 2 ) ( 3 ) ( 4 ) ( 5 ) ( 6 ) -- >> instance Functor Fetch where fmap f h = do x <- h; return (f x) -- <<Applicative instance Applicative Fetch where pure = return Fetch f <*> Fetch x = Fetch $ do f' <- f x' <- x case (f',x') of (Done g, Done y ) -> return (Done (g y)) (Done g, Blocked br c ) -> return (Blocked br (g <$> c)) (Blocked br c, Done y ) -> return (Blocked br (c <*> return y)) (Blocked br1 c, Blocked br2 d) -> return (Blocked (br1 <> br2) (c <*> d)) -- >> -- <<runFetch runFetch :: Fetch a -> IO a runFetch (Fetch h) = do r <- h case r of Done a -> return a Blocked br cont -> do fetch (toList br) runFetch cont -- >> fetch :: [BlockedRequest] -> IO () fetch bs = do putStrLn "==== fetch ====" mapM_ ppr bs where ppr (BlockedRequest r m) = do print r writeIORef m (FetchSuccess (requestVal r)) mapM :: (Applicative f, Traversable t) => (a -> f b) -> t a -> f (t b) mapM = traverse sequence :: (Applicative f, Traversable t) => t (f a) -> f (t a) sequence = Data.Traversable.sequenceA
null
https://raw.githubusercontent.com/simonmar/haxl-icfp14-sample-code/31859f50e0548f3e581acd26944ceb00953f2c42/haxl/Fetch.hs
haskell
<<Monad >> >> >> <<Applicative >> <<runFetch >>
# LANGUAGE ExistentialQuantification , GADTs , StandaloneDeriving # module Fetch where import Types import MockData import Data.IORef import Control.Applicative import Data.Traversable import Data.Sequence import Data.Monoid import Data.Foldable (toList) data Result a = Done a | Blocked (Seq BlockedRequest) (Fetch a) newtype Fetch a = Fetch { unFetch :: IO (Result a) } instance Monad Fetch where return a = Fetch $ return (Done a) Fetch m >>= k = Fetch $ do r <- m case r of Done a -> unFetch (k a) Blocked br c -> return (Blocked br (c >>= k)) < < BlockedRequest data BlockedRequest = forall a . BlockedRequest (Request a) (IORef (FetchStatus a)) < < dataFetch dataFetch :: Request a -> Fetch a dataFetch request = Fetch $ do ( 1 ) ( 2 ) ( 3 ) ( 4 ) ( 5 ) ( 6 ) instance Functor Fetch where fmap f h = do x <- h; return (f x) instance Applicative Fetch where pure = return Fetch f <*> Fetch x = Fetch $ do f' <- f x' <- x case (f',x') of (Done g, Done y ) -> return (Done (g y)) (Done g, Blocked br c ) -> return (Blocked br (g <$> c)) (Blocked br c, Done y ) -> return (Blocked br (c <*> return y)) (Blocked br1 c, Blocked br2 d) -> return (Blocked (br1 <> br2) (c <*> d)) runFetch :: Fetch a -> IO a runFetch (Fetch h) = do r <- h case r of Done a -> return a Blocked br cont -> do fetch (toList br) runFetch cont fetch :: [BlockedRequest] -> IO () fetch bs = do putStrLn "==== fetch ====" mapM_ ppr bs where ppr (BlockedRequest r m) = do print r writeIORef m (FetchSuccess (requestVal r)) mapM :: (Applicative f, Traversable t) => (a -> f b) -> t a -> f (t b) mapM = traverse sequence :: (Applicative f, Traversable t) => t (f a) -> f (t a) sequence = Data.Traversable.sequenceA
78e5c2ded3864f0163da28433ab60319f88d6d4820af0633054f47e5a65b4e13
chaoslawful/zfor
zfor_client_SUITE.erl
-module(zfor_client_SUITE). -compile([debug_info,export_all]). -include("ct.hrl"). -include("zfor_client.hrl"). init_per_suite(Config) -> Config. end_per_suite(Config) -> Config. init_per_testcase(_TestCase, Config) -> Config. end_per_testcase(_TestCase, Config) -> Config. all() -> [basic_test, more_test, fail_test, vconf_test]. % 单元测试 basic_test(_Config) -> Ctx = zfor_client:context(?DEFAULT_ZFOR_SERVER, ?DEFAULT_ZFOR_PORT, ?DEFAULT_ZFOR_TIMEOUT), {'ok', Addr} = zfor_client:getaddr(Ctx, "127.0.0.1"), io:format("Resolved address for 127.0.0.1: ~p~n", [Addr]), {127, 0, 0, 1} = Addr, {'ok', Addrs} = zfor_client:getaddrs(Ctx, "127.0.0.1"), io:format("Resolved addresses for 127.0.0.1: ~p~n", [Addrs]), [{127, 0, 0, 1}] = Addrs, ok. more_test(_Config) -> Ctx = zfor_client:context(?DEFAULT_ZFOR_SERVER, ?DEFAULT_ZFOR_PORT, ?DEFAULT_ZFOR_TIMEOUT), {'ok', Addr1} = zfor_client:getaddr(Ctx, "test.zfor"), io:format("Resolved address for test.zfor: ~p~n", [Addr1]), {127, 0, 0, 1} = Addr1, {'ok', Addrs1} = zfor_client:getaddrs(Ctx, "test.zfor"), io:format("Resolved addresses for test.zfor: ~p~n", [Addrs1]), [{127, 0, 0, 1}, {127, 0, 0, 2}] = Addrs1, {'ok', Addr2} = zfor_client:getaddr(Ctx, "www.baidu.com"), io:format("Resolved address for www.baidu.com: ~p~n", [Addr2]), {'ok', Addrs2} = zfor_client:getaddrs(Ctx, "www.google.com"), io:format("Resolved addresses for www.google.com: ~p~n", [Addrs2]), {'ok', {127, 0, 0, 1}} = zfor_client:getaddr(Ctx, "test.zfor", false), {'ok', [{127, 0, 0, 1}, {127, 0, 0, 2}]} = zfor_client:getaddrs(Ctx, "test.zfor", false), {'error', _} = zfor_client:getaddr(Ctx, "www.baidu.com", false), {'error', _} = zfor_client:getaddrs(Ctx, "www.google.com", false), ok. fail_test(_Config) -> Ctx1 = zfor_client:context(?DEFAULT_ZFOR_SERVER, 9876, ?DEFAULT_ZFOR_TIMEOUT), {'error', _} = zfor_client:getaddr(Ctx1, "test1.zfor"), {'error', _} = zfor_client:getaddrs(Ctx1, "test1.zfor"), Ctx2 = zfor_client:context(?DEFAULT_ZFOR_SERVER, ?DEFAULT_ZFOR_PORT, ?DEFAULT_ZFOR_TIMEOUT), {'error', _} = zfor_client:getaddr(Ctx2, "test1.zfor"), {'error', _} = zfor_client:getaddrs(Ctx2, "test1.zfor"), {'error', _} = zfor_client:getaddr(Ctx2, "test1.zfor", false), {'error', _} = zfor_client:getaddrs(Ctx2, "test1.zfor", false), {'error', _} = zfor_client:getaddr(Ctx2, "www.baidu.com", false), {'error', _} = zfor_client:getaddrs(Ctx2, "www.google.com", false), ok. vconf_test(_Config) -> Ctx = zfor_client:context(?DEFAULT_ZFOR_SERVER, ?DEFAULT_ZFOR_PORT, ?DEFAULT_ZFOR_TIMEOUT), {'ok', "[\"127.0.0.1\",\"127.0.0.2\"]"} = zfor_client:getvconf(Ctx, "test.zfor", host), {'ok', "\"all_active\""} = zfor_client:getvconf(Ctx, "test.zfor", select_method), {'ok', _} = zfor_client:getvconf(Ctx, "test.zfor", check_ttl), {'ok', "\"http\""} = zfor_client:getvconf(Ctx, "test.zfor", check_type), {'ok', "6789"} = zfor_client:getvconf(Ctx, "test.zfor", check_port), {'ok', "\"/\""} = zfor_client:getvconf(Ctx, "test.zfor", http_path), {'ok', "\"head\""} = zfor_client:getvconf(Ctx, "test.zfor", http_method), {'ok', _} = zfor_client:getvconf(Ctx, "test.zfor", http_host), {'ok', _} = zfor_client:getvconf(Ctx, "test.zfor", check_timeout), {'ok', _} = zfor_client:getvconf(Ctx, "test.zfor", expect_response), {'ok', "\"all\""} = zfor_client:getvconf(Ctx, "test.zfor", failure_response), {'ok', _} = zfor_client:getvconf(Ctx, "test.zfor", group_threshold), {'error', _} = zfor_client:getvconf(Ctx, "test.zfor", xx), ok. vim600 : = erlang ts=4 sw=4 fdm = marker vim<600 : = erlang ts=4 sw=4
null
https://raw.githubusercontent.com/chaoslawful/zfor/a8207bbd40ed73506e61d943b1a20467d5e6136a/priv/client/erlang_zfor/test/zfor_client_SUITE.erl
erlang
单元测试
-module(zfor_client_SUITE). -compile([debug_info,export_all]). -include("ct.hrl"). -include("zfor_client.hrl"). init_per_suite(Config) -> Config. end_per_suite(Config) -> Config. init_per_testcase(_TestCase, Config) -> Config. end_per_testcase(_TestCase, Config) -> Config. all() -> [basic_test, more_test, fail_test, vconf_test]. basic_test(_Config) -> Ctx = zfor_client:context(?DEFAULT_ZFOR_SERVER, ?DEFAULT_ZFOR_PORT, ?DEFAULT_ZFOR_TIMEOUT), {'ok', Addr} = zfor_client:getaddr(Ctx, "127.0.0.1"), io:format("Resolved address for 127.0.0.1: ~p~n", [Addr]), {127, 0, 0, 1} = Addr, {'ok', Addrs} = zfor_client:getaddrs(Ctx, "127.0.0.1"), io:format("Resolved addresses for 127.0.0.1: ~p~n", [Addrs]), [{127, 0, 0, 1}] = Addrs, ok. more_test(_Config) -> Ctx = zfor_client:context(?DEFAULT_ZFOR_SERVER, ?DEFAULT_ZFOR_PORT, ?DEFAULT_ZFOR_TIMEOUT), {'ok', Addr1} = zfor_client:getaddr(Ctx, "test.zfor"), io:format("Resolved address for test.zfor: ~p~n", [Addr1]), {127, 0, 0, 1} = Addr1, {'ok', Addrs1} = zfor_client:getaddrs(Ctx, "test.zfor"), io:format("Resolved addresses for test.zfor: ~p~n", [Addrs1]), [{127, 0, 0, 1}, {127, 0, 0, 2}] = Addrs1, {'ok', Addr2} = zfor_client:getaddr(Ctx, "www.baidu.com"), io:format("Resolved address for www.baidu.com: ~p~n", [Addr2]), {'ok', Addrs2} = zfor_client:getaddrs(Ctx, "www.google.com"), io:format("Resolved addresses for www.google.com: ~p~n", [Addrs2]), {'ok', {127, 0, 0, 1}} = zfor_client:getaddr(Ctx, "test.zfor", false), {'ok', [{127, 0, 0, 1}, {127, 0, 0, 2}]} = zfor_client:getaddrs(Ctx, "test.zfor", false), {'error', _} = zfor_client:getaddr(Ctx, "www.baidu.com", false), {'error', _} = zfor_client:getaddrs(Ctx, "www.google.com", false), ok. fail_test(_Config) -> Ctx1 = zfor_client:context(?DEFAULT_ZFOR_SERVER, 9876, ?DEFAULT_ZFOR_TIMEOUT), {'error', _} = zfor_client:getaddr(Ctx1, "test1.zfor"), {'error', _} = zfor_client:getaddrs(Ctx1, "test1.zfor"), Ctx2 = zfor_client:context(?DEFAULT_ZFOR_SERVER, ?DEFAULT_ZFOR_PORT, ?DEFAULT_ZFOR_TIMEOUT), {'error', _} = zfor_client:getaddr(Ctx2, "test1.zfor"), {'error', _} = zfor_client:getaddrs(Ctx2, "test1.zfor"), {'error', _} = zfor_client:getaddr(Ctx2, "test1.zfor", false), {'error', _} = zfor_client:getaddrs(Ctx2, "test1.zfor", false), {'error', _} = zfor_client:getaddr(Ctx2, "www.baidu.com", false), {'error', _} = zfor_client:getaddrs(Ctx2, "www.google.com", false), ok. vconf_test(_Config) -> Ctx = zfor_client:context(?DEFAULT_ZFOR_SERVER, ?DEFAULT_ZFOR_PORT, ?DEFAULT_ZFOR_TIMEOUT), {'ok', "[\"127.0.0.1\",\"127.0.0.2\"]"} = zfor_client:getvconf(Ctx, "test.zfor", host), {'ok', "\"all_active\""} = zfor_client:getvconf(Ctx, "test.zfor", select_method), {'ok', _} = zfor_client:getvconf(Ctx, "test.zfor", check_ttl), {'ok', "\"http\""} = zfor_client:getvconf(Ctx, "test.zfor", check_type), {'ok', "6789"} = zfor_client:getvconf(Ctx, "test.zfor", check_port), {'ok', "\"/\""} = zfor_client:getvconf(Ctx, "test.zfor", http_path), {'ok', "\"head\""} = zfor_client:getvconf(Ctx, "test.zfor", http_method), {'ok', _} = zfor_client:getvconf(Ctx, "test.zfor", http_host), {'ok', _} = zfor_client:getvconf(Ctx, "test.zfor", check_timeout), {'ok', _} = zfor_client:getvconf(Ctx, "test.zfor", expect_response), {'ok', "\"all\""} = zfor_client:getvconf(Ctx, "test.zfor", failure_response), {'ok', _} = zfor_client:getvconf(Ctx, "test.zfor", group_threshold), {'error', _} = zfor_client:getvconf(Ctx, "test.zfor", xx), ok. vim600 : = erlang ts=4 sw=4 fdm = marker vim<600 : = erlang ts=4 sw=4
9d915ce2691454fd984f1920c836728b243f692438f7f10bf43c08d3d48c7a69
bobjflong/stellar-haskell
Transaction.hs
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} # LANGUAGE TemplateHaskell # module Web.Stellar.Transaction ( fetchTransactions, fetchTransactionsWithMarker, Transaction(..), earliestLedger, currentLedger, transactionAccount, amount, destination, signingPubKey, transactionType, TransactionType(..), transactionSignature, date, hash, currency, rawTransaction ) where import Control.Applicative import Control.Lens hiding ((.=)) import Control.Monad import Data.Aeson import Data.ByteString.Lazy import Data.Monoid import Data.Text import qualified Data.Text as T import Web.Stellar.Internal import Web.Stellar.Request data Transaction = Transaction { _transactionAccount :: Text, _destination :: Maybe Text, _signingPubKey :: Text, _transactionTypeData :: Text, _transactionSignature :: Text, _date :: !Int, _hash :: Text, _amountData :: Text, _currencyData :: Text, _rawTransaction :: ByteString } deriving (Eq, Show) data TransactionType = Payment | AccountSet | AccountMerge | OfferCreate | OfferCancel | TrustSet | Inflation | SetRegularKey | UnknownTransactionType deriving (Show, Read) type TransactionTypeRead = [(TransactionType, String)] $(makeLenses ''Transaction) transactionType :: Lens' Transaction TransactionType transactionType = lens g s where g v = case ((reads $ T.unpack $ v ^. transactionTypeData) :: TransactionTypeRead) of [(val, "")] -> val _ -> UnknownTransactionType s v t = transactionTypeData .~ (T.pack.show $ t) $ v amount :: Lens' Transaction (Maybe Money) amount = moneyLens amountData currency :: Applicative f => (Text -> f Text) -> Transaction -> f Transaction currency f t = case rawCurrency of "" -> pure t _ -> fmap (\x' -> currencyData .~ x' $ t) (f rawCurrency) where rawCurrency = t ^. currencyData instance FromJSON Transaction where parseJSON (Object v) = do Transaction <$> (tx >>= (.: "Account")) <*> (tx >>= (.:? "Destination")) <*> (tx >>= (.: "SigningPubKey")) <*> (tx >>= (.: "TransactionType")) <*> (tx >>= (.: "TxnSignature")) <*> (tx >>= (.: "date")) <*> (tx >>= (.: "hash")) <*> fmap (extract innerMoney) (withDefault "Amount" emptyAPIMoney) <*> fmap (extract innerCurrency) (withDefault "Amount" defaultAPICurrency) <*> (tx >>= (\t -> return $ encode t)) where extract _ Nothing = mempty extract f (Just x) = f x withDefault k d = (tx >>= (\o -> o .:? k .!= (Just d))) tx = (v .: "tx") parseJSON _ = mzero data TransactionList = TransactionList { innerTransactions :: [Transaction] } instance FromJSON TransactionList where parseJSON (Object v) = do TransactionList <$> ((v .: "result") >>= (.: "transactions")) parseJSON _ = mzero data TransactionRequest = TransactionRequest { account :: Text, ledgerIndexMin :: Int, ledgerIndexMax :: Int, marker :: Text } instance ToJSON TransactionRequest where toJSON transactionRequest = object [ "method" .= ("account_tx" :: Text), "params" .= [object [ "account" .= (account transactionRequest), "ledger_index_min" .= (ledgerIndexMin transactionRequest), "ledger_index_max" .= (ledgerIndexMax transactionRequest), "marker" .= (marker transactionRequest)]]] type LedgerLimit = Int earliestLedger :: LedgerLimit earliestLedger = 0 currentLedger :: LedgerLimit currentLedger = (-1) fetchTransactions :: StellarEndpoint -> AccountID -> LedgerLimit -> LedgerLimit -> IO (Maybe [Transaction]) fetchTransactions endpoint acc fetchMin fetchMax = fetchTransactionsWithMarker endpoint acc fetchMin fetchMax "" fetchTransactionsWithMarker :: StellarEndpoint -> AccountID -> LedgerLimit -> LedgerLimit -> Text -> IO (Maybe [Transaction]) fetchTransactionsWithMarker endpoint (AccountID acc) fetchMin fetchMax fetchMarker = do r <- fetchTransactionData return $ fmap innerTransactions r where fetchTransactionData = fmap decode rawRequestData rawRequestData = makeRequest endpoint $ TransactionRequest acc fetchMin fetchMax fetchMarker
null
https://raw.githubusercontent.com/bobjflong/stellar-haskell/b7beac482b0a78869de6090d5c13cda5d9601268/src/Web/Stellar/Transaction.hs
haskell
# LANGUAGE OverloadedStrings # # LANGUAGE RankNTypes #
# LANGUAGE TemplateHaskell # module Web.Stellar.Transaction ( fetchTransactions, fetchTransactionsWithMarker, Transaction(..), earliestLedger, currentLedger, transactionAccount, amount, destination, signingPubKey, transactionType, TransactionType(..), transactionSignature, date, hash, currency, rawTransaction ) where import Control.Applicative import Control.Lens hiding ((.=)) import Control.Monad import Data.Aeson import Data.ByteString.Lazy import Data.Monoid import Data.Text import qualified Data.Text as T import Web.Stellar.Internal import Web.Stellar.Request data Transaction = Transaction { _transactionAccount :: Text, _destination :: Maybe Text, _signingPubKey :: Text, _transactionTypeData :: Text, _transactionSignature :: Text, _date :: !Int, _hash :: Text, _amountData :: Text, _currencyData :: Text, _rawTransaction :: ByteString } deriving (Eq, Show) data TransactionType = Payment | AccountSet | AccountMerge | OfferCreate | OfferCancel | TrustSet | Inflation | SetRegularKey | UnknownTransactionType deriving (Show, Read) type TransactionTypeRead = [(TransactionType, String)] $(makeLenses ''Transaction) transactionType :: Lens' Transaction TransactionType transactionType = lens g s where g v = case ((reads $ T.unpack $ v ^. transactionTypeData) :: TransactionTypeRead) of [(val, "")] -> val _ -> UnknownTransactionType s v t = transactionTypeData .~ (T.pack.show $ t) $ v amount :: Lens' Transaction (Maybe Money) amount = moneyLens amountData currency :: Applicative f => (Text -> f Text) -> Transaction -> f Transaction currency f t = case rawCurrency of "" -> pure t _ -> fmap (\x' -> currencyData .~ x' $ t) (f rawCurrency) where rawCurrency = t ^. currencyData instance FromJSON Transaction where parseJSON (Object v) = do Transaction <$> (tx >>= (.: "Account")) <*> (tx >>= (.:? "Destination")) <*> (tx >>= (.: "SigningPubKey")) <*> (tx >>= (.: "TransactionType")) <*> (tx >>= (.: "TxnSignature")) <*> (tx >>= (.: "date")) <*> (tx >>= (.: "hash")) <*> fmap (extract innerMoney) (withDefault "Amount" emptyAPIMoney) <*> fmap (extract innerCurrency) (withDefault "Amount" defaultAPICurrency) <*> (tx >>= (\t -> return $ encode t)) where extract _ Nothing = mempty extract f (Just x) = f x withDefault k d = (tx >>= (\o -> o .:? k .!= (Just d))) tx = (v .: "tx") parseJSON _ = mzero data TransactionList = TransactionList { innerTransactions :: [Transaction] } instance FromJSON TransactionList where parseJSON (Object v) = do TransactionList <$> ((v .: "result") >>= (.: "transactions")) parseJSON _ = mzero data TransactionRequest = TransactionRequest { account :: Text, ledgerIndexMin :: Int, ledgerIndexMax :: Int, marker :: Text } instance ToJSON TransactionRequest where toJSON transactionRequest = object [ "method" .= ("account_tx" :: Text), "params" .= [object [ "account" .= (account transactionRequest), "ledger_index_min" .= (ledgerIndexMin transactionRequest), "ledger_index_max" .= (ledgerIndexMax transactionRequest), "marker" .= (marker transactionRequest)]]] type LedgerLimit = Int earliestLedger :: LedgerLimit earliestLedger = 0 currentLedger :: LedgerLimit currentLedger = (-1) fetchTransactions :: StellarEndpoint -> AccountID -> LedgerLimit -> LedgerLimit -> IO (Maybe [Transaction]) fetchTransactions endpoint acc fetchMin fetchMax = fetchTransactionsWithMarker endpoint acc fetchMin fetchMax "" fetchTransactionsWithMarker :: StellarEndpoint -> AccountID -> LedgerLimit -> LedgerLimit -> Text -> IO (Maybe [Transaction]) fetchTransactionsWithMarker endpoint (AccountID acc) fetchMin fetchMax fetchMarker = do r <- fetchTransactionData return $ fmap innerTransactions r where fetchTransactionData = fmap decode rawRequestData rawRequestData = makeRequest endpoint $ TransactionRequest acc fetchMin fetchMax fetchMarker
258329b56801b80d105a4605b705bfe9afdf7206d8fd05c2fe14584c40e0c0cc
amperity/dialog
simple_test.clj
(ns dialog.format.simple-test (:require [clojure.string :as str] [clojure.test :refer [deftest testing is]] [dialog.format.simple :as simple] [io.aviso.ansi :as ansi]) (:import java.time.Instant)) (deftest thread-formatting (let [format-thread #'simple/format-thread] (is (= "[-]" (format-thread nil))) (is (= "[main]" (format-thread "main"))))) (deftest level-formatting (let [format-level #'simple/format-level] (is (= "TRACE" (format-level :trace))) (is (= "DEBUG" (format-level :debug))) (is (= "INFO" (format-level :info))) (is (= "WARN" (format-level :warn))) (is (= "ERROR" (format-level :error))) (is (= "FATAL" (format-level :fatal))))) (deftest message-formatting (let [fmt (simple/formatter {}) inst (Instant/parse "2021-12-27T15:33:18Z")] (testing "basic format" (is (= "2021-12-27T15:33:18Z [thread-pool-123] INFO foo.bar.baz Hello, logger!" (fmt {:time inst :level :info :logger "foo.bar.baz" :message "Hello, logger!" :thread "thread-pool-123"})))) (testing "with duration" (is (= "2021-12-27T15:33:18Z [main] WARN foo.bar.baz Another thing (123.456 ms)" (fmt {:time inst :level :warn :logger "foo.bar.baz" :message "Another thing" :thread "main" :duration 123.456})))) (testing "with custom tail" (is (= "2021-12-27T15:33:18Z [main] WARN foo.bar.baz Another thing <CUSTOM TAIL>" (fmt (vary-meta {:time inst :level :warn :logger "foo.bar.baz" :message "Another thing" :thread "main"} assoc :dialog.format/tail "<CUSTOM TAIL>"))))) (testing "with extra info" (is (= "2021-12-27T15:33:18Z [main] WARN foo.bar.baz Another thing" (fmt {:time inst :level :warn :logger "foo.bar.baz" :message "Another thing" :thread "main" :foo.alpha 123})) "default extra info is ignored") (is (= "2021-12-27T15:33:18Z [main] WARN foo.bar.baz Another thing {:bar :xyz}" (fmt (vary-meta {:time inst :level :warn :logger "foo.bar.baz" :message "Another thing" :thread "main" :foo.alpha 123} assoc :dialog.format/extra {:bar :xyz}))) "custom extra info shows")) (testing "throwables" (let [ex (RuntimeException. "BOOM") message (ansi/strip-ansi (fmt {:level :error :logger "foo.bar.baz" :error ex}))] (is (str/includes? message "java.lang.RuntimeException: BOOM")))) (testing "with custom padding" (let [fmt (simple/formatter {:padding {:thread 10, :logger 15}})] (is (= "2021-12-27T15:33:18Z [main] INFO acme.main Hello, logger!" (fmt {:time inst :level :info :logger "acme.main" :message "Hello, logger!" :thread "main"}))))) (testing "without padding" (let [fmt (simple/formatter {:padding false})] (is (= "2021-12-27T15:33:18Z [thread-pool-123] INFO foo.bar.baz Hello, logger!" (fmt {:time inst :level :info :logger "foo.bar.baz" :message "Hello, logger!" :thread "thread-pool-123"})))))))
null
https://raw.githubusercontent.com/amperity/dialog/1dda8ccdd5172113c126df2a0c5dd1ae31332127/test/dialog/format/simple_test.clj
clojure
(ns dialog.format.simple-test (:require [clojure.string :as str] [clojure.test :refer [deftest testing is]] [dialog.format.simple :as simple] [io.aviso.ansi :as ansi]) (:import java.time.Instant)) (deftest thread-formatting (let [format-thread #'simple/format-thread] (is (= "[-]" (format-thread nil))) (is (= "[main]" (format-thread "main"))))) (deftest level-formatting (let [format-level #'simple/format-level] (is (= "TRACE" (format-level :trace))) (is (= "DEBUG" (format-level :debug))) (is (= "INFO" (format-level :info))) (is (= "WARN" (format-level :warn))) (is (= "ERROR" (format-level :error))) (is (= "FATAL" (format-level :fatal))))) (deftest message-formatting (let [fmt (simple/formatter {}) inst (Instant/parse "2021-12-27T15:33:18Z")] (testing "basic format" (is (= "2021-12-27T15:33:18Z [thread-pool-123] INFO foo.bar.baz Hello, logger!" (fmt {:time inst :level :info :logger "foo.bar.baz" :message "Hello, logger!" :thread "thread-pool-123"})))) (testing "with duration" (is (= "2021-12-27T15:33:18Z [main] WARN foo.bar.baz Another thing (123.456 ms)" (fmt {:time inst :level :warn :logger "foo.bar.baz" :message "Another thing" :thread "main" :duration 123.456})))) (testing "with custom tail" (is (= "2021-12-27T15:33:18Z [main] WARN foo.bar.baz Another thing <CUSTOM TAIL>" (fmt (vary-meta {:time inst :level :warn :logger "foo.bar.baz" :message "Another thing" :thread "main"} assoc :dialog.format/tail "<CUSTOM TAIL>"))))) (testing "with extra info" (is (= "2021-12-27T15:33:18Z [main] WARN foo.bar.baz Another thing" (fmt {:time inst :level :warn :logger "foo.bar.baz" :message "Another thing" :thread "main" :foo.alpha 123})) "default extra info is ignored") (is (= "2021-12-27T15:33:18Z [main] WARN foo.bar.baz Another thing {:bar :xyz}" (fmt (vary-meta {:time inst :level :warn :logger "foo.bar.baz" :message "Another thing" :thread "main" :foo.alpha 123} assoc :dialog.format/extra {:bar :xyz}))) "custom extra info shows")) (testing "throwables" (let [ex (RuntimeException. "BOOM") message (ansi/strip-ansi (fmt {:level :error :logger "foo.bar.baz" :error ex}))] (is (str/includes? message "java.lang.RuntimeException: BOOM")))) (testing "with custom padding" (let [fmt (simple/formatter {:padding {:thread 10, :logger 15}})] (is (= "2021-12-27T15:33:18Z [main] INFO acme.main Hello, logger!" (fmt {:time inst :level :info :logger "acme.main" :message "Hello, logger!" :thread "main"}))))) (testing "without padding" (let [fmt (simple/formatter {:padding false})] (is (= "2021-12-27T15:33:18Z [thread-pool-123] INFO foo.bar.baz Hello, logger!" (fmt {:time inst :level :info :logger "foo.bar.baz" :message "Hello, logger!" :thread "thread-pool-123"})))))))
5fb50ddb15ef21981ed533ce26f37d87c8ba8373d1d5e4505a429272cf3e86d3
fukamachi/clozure-cl
ppc64-arch.lisp
-*- Mode : Lisp ; Package : ( : use CL ) -*- ;;; Copyright ( C ) 2009 Clozure Associates Copyright ( C ) 1994 - 2001 Digitool , Inc This file is part of Clozure CL . ;;; Clozure CL is licensed under the terms of the Lisp Lesser GNU Public License , known as the LLGPL and distributed with Clozure CL as the ;;; file "LICENSE". The LLGPL consists of a preamble and the LGPL, which is distributed with Clozure CL as the file " LGPL " . Where these ;;; conflict, the preamble takes precedence. ;;; ;;; Clozure CL is referenced in the preamble as the "LIBRARY." ;;; ;;; The LLGPL is also available online at ;;; ;;; This file matches "ccl:lisp-kernel;constants64.h" & ;;; "ccl:lisp-kernel;constants64.s" (defpackage "PPC64" (:use "CL") #+ppc64-target (:nicknames "TARGET")) (in-package "PPC64") (eval-when (:compile-toplevel :load-toplevel :execute) sigh . Could use r13+bias on Linux , but Apple has n't invented tls yet . (defconstant nbits-in-word 64) (defconstant least-significant-bit 63) (defconstant nbits-in-byte 8) (defconstant ntagbits 4) (defconstant nlisptagbits 3) (defconstant nfixnumtagbits 3) ; See ? (defconstant nlowtagbits 2) tag part of header is 8 bits wide (defconstant fixnumshift nfixnumtagbits) (defconstant fixnum-shift fixnumshift) ; A pet name for it. Only needed by GC / very low - level code (defconstant full-tag-mask fulltagmask) (defconstant tagmask (1- (ash 1 nlisptagbits))) (defconstant tag-mask tagmask) (defconstant fixnummask (1- (ash 1 nfixnumtagbits))) (defconstant fixnum-mask fixnummask) (defconstant subtag-mask (1- (ash 1 num-subtag-bits))) 24 (defconstant charcode-shift 8) (defconstant word-shift 3) (defconstant word-size-in-bytes 8) (defconstant node-size word-size-in-bytes) (defconstant dnode-size 16) (defconstant dnode-align-bits 4) (defconstant dnode-shift dnode-align-bits) (defconstant bitmap-shift 6) (defconstant target-most-negative-fixnum (ash -1 (1- (- nbits-in-word nfixnumtagbits)))) (defconstant target-most-positive-fixnum (1- (ash 1 (1- (- nbits-in-word nfixnumtagbits))))) (defmacro define-subtag (name tag value) `(defconstant ,(ccl::form-symbol "SUBTAG-" name) (logior ,tag (ash ,value ntagbits)))) ;;; PPC64 stuff and tags. There are several ways to look at the 4 tag bits of any object or header . Looking at the low 2 bits , we can classify things as ;;; follows (I'm not sure if we'd ever want to do this) : ;;; # b00 a " primary " object : fixnum , cons , uvector # b01 an immediate # b10 the header on an immediate uvector # b11 the header on a node ( pointer - containing ) uvector ;; ;;; Note that the ppc64's LD and STD instructions require that the low two bits of the constant displacement be # b00 . If we want to use constant offsets to access CONS and UVECTOR fields , we 're pretty much obligated to ensure that CONS and UVECTOR have tags that also end in # b00 , and ;;; fixnum addition and subtraction work better when fixnum tags are all 0. We generally have to look at all 4 tag bits before we really know what ;;; class of "potentially primary" object we're looking at. If we look at 3 tag bits , we can see : ;;; # b000 fixnum # b001 immediate # b010 immedate - header # b011 node - header # b100 CONS or UVECTOR # b101 immediate # b110 immediate - header # b111 node - header ;;; (defconstant tag-fixnum 0) (defconstant tag-imm-0 1) (defconstant tag-immheader-0 2) (defconstant tag-nodeheader-0 3) (defconstant tag-memory 4) (defconstant tag-imm-2 5) (defconstant tag-immheader2 6) (defconstant tag-nodeheader2 7) ;;; Note how we're already winding up with lots of header and immediate ;;; "classes". That might actually be useful. ;; When we move to 4 bits , we wind up ( obviously ) with 4 tags of the form # bxx00 . There are two partitionings that make ( some ) sense : we can either use 2 of these for ( even and odd ) fixnums , or we can give NIL a tag that 's congruent ( mod 16 ) with CONS . There seem to be a lot of tradeoffs involved , but it ultimately seems best to be able to treat 64 - bit aligned addresses as fixnums : we do n't want the to look like a ;;; vector. That basically requires that NIL really be a symbol (good bye , nilsym ) and that we ensure that there are NILs where its CAR and CDR would be ( -4 , 4 bytes from the tagged pointer . ) That means that CONS is 4 and UVECTOR is 12 , and we have even more immediate / header types . (defconstant fulltag-even-fixnum #b0000) (defconstant fulltag-imm-0 #b0001) (defconstant fulltag-immheader-0 #b0010) (defconstant fulltag-nodeheader-0 #b0011) (defconstant fulltag-cons #b0100) (defconstant fulltag-imm-1 #b0101) (defconstant fulltag-immheader-1 #b0110) (defconstant fulltag-nodeheader-1 #b0111) (defconstant fulltag-odd-fixnum #b1000) (defconstant fulltag-imm-2 #b1001) (defconstant fulltag-immheader-2 #b1010) (defconstant fulltag-nodeheader-2 #b1011) (defconstant fulltag-misc #b1100) (defconstant fulltag-imm-3 #b1101) (defconstant fulltag-immheader-3 #b1110) (defconstant fulltag-nodeheader-3 #b1111) (defconstant lowtagmask (1- (ash 1 nlowtagbits))) (defconstant lowtag-mask lowtagmask) (defconstant lowtag-primary 0) (defconstant lowtag-imm 1) (defconstant lowtag-immheader 2) (defconstant lowtag-nodeheader 3) ;;; The general algorithm for determining the (primary) type of an ;;; object is something like: ( clrldi tag node 60 ) ;;; (cmpwi tag fulltag-misc) ( clrldi tag tag 61 ) ;;; (bne @done) ( tag misc - subtag - offset node ) @done ;; ;;; That's good enough to identify FIXNUM, "generally immediate", cons, or a header tag from a UVECTOR . In some cases , we may need to hold on to the full 4 - bit tag . ;;; In no specific order: ;;; - it's important to be able to quickly recognize fixnums; that's ;;; simple ;;; - it's important to be able to quickly recognize lists (for CAR/CDR) ;;; and somewhat important to be able to quickly recognize conses. Also simple , though we have to special - case NIL . - it 's desirable to be able to do , ARRAYP , and specific - array - type- p. We need at least 12 immediate CL vector types ( SIGNED / UNSIGNED - BYTE 8/16/32/64 , SINGLE - FLOAT , DOUBLE - FLOAT , BIT , and at least one CHARACTER ; we need SIMPLE - ARRAY , VECTOR - HEADER , and ARRAY - HEADER as node array types . That 's suspciciously close to 16 ;;; - it's desirable to be able (in FUNCALL) to quickly recognize ;;; functions/symbols/other, and probably desirable to trap on other. Pretty much have to do a memory reference and at least one comparison ;;; here. ;;; - it's sometimes desirable to recognize numbers and distinct numeric ;;; types (other than FIXNUM) quickly. - The GC ( especially ) needs to be able to determine the size of ivectors ( ivector elements ) fairly cheaply . Most ivectors are CL arrays , but code - vectors are fairly common ( and have 32 - bit elements , ;;; naturally.) ;;; - We have a fairly large number of non-array gvector types, and it's ;;; always desirable to have room for expansion. - we basically have 8 classes of , each of which has 16 possible values . If we stole the high bit of the subtag to indicate CL - array - ness , we 'd still have 6 bits to encode non - CL ;;; array types. (defconstant cl-array-subtag-bit 7) (defconstant cl-array-subtag-mask (ash 1 cl-array-subtag-bit)) (defmacro define-cl-array-subtag (name tag value) `(defconstant ,(ccl::form-symbol "SUBTAG-" name) (logior cl-array-subtag-mask (logior ,tag (ash ,value ntagbits))))) (define-cl-array-subtag arrayH fulltag-nodeheader-1 0) (define-cl-array-subtag vectorH fulltag-nodeheader-2 0) (define-cl-array-subtag simple-vector fulltag-nodeheader-3 0) (defconstant min-array-subtag subtag-arrayH) (defconstant min-vector-subtag subtag-vectorH) bits : 64 32 16 8 1 CL - array ivector types DOUBLE - FLOAT SINGLE s16 CHAR BIT ;;; s64 s32 u16 s8 u64 u32 u8 Other ivector types MACPTR CODE - VECTOR DEAD - MACPTR XCODE - VECTOR ;;; BIGNUM ;;; DOUBLE-FLOAT There might possibly be ivectors with 128 - bit ( VMX / AltiVec ) elements someday , and there might be multiple character sizes ( 16/32 bits ) . That sort of suggests that we use the four immheader classes to encode the ivector size ( 64 , 32 , 8 , other ) and make BIT an easily- ;;; detected case of OTHER. (defconstant ivector-class-64-bit fulltag-immheader-3) (defconstant ivector-class-32-bit fulltag-immheader-2) (defconstant ivector-class-other-bit fulltag-immheader-1) (defconstant ivector-class-8-bit fulltag-immheader-0) (define-cl-array-subtag s64-vector ivector-class-64-bit 1) (define-cl-array-subtag u64-vector ivector-class-64-bit 2) (define-cl-array-subtag fixnum-vector ivector-class-64-bit 3) (define-cl-array-subtag double-float-vector ivector-class-64-bit 4) (define-cl-array-subtag s32-vector ivector-class-32-bit 1) (define-cl-array-subtag u32-vector ivector-class-32-bit 2) (define-cl-array-subtag single-float-vector ivector-class-32-bit 3) (define-cl-array-subtag simple-base-string ivector-class-32-bit 5) (define-cl-array-subtag s16-vector ivector-class-other-bit 1) (define-cl-array-subtag u16-vector ivector-class-other-bit 2) (define-cl-array-subtag bit-vector ivector-class-other-bit 7) (define-cl-array-subtag s8-vector ivector-class-8-bit 1) (define-cl-array-subtag u8-vector ivector-class-8-bit 2) ;;; There's some room for expansion in non-array ivector space. (define-subtag macptr ivector-class-64-bit 1) (define-subtag dead-macptr ivector-class-64-bit 2) (define-subtag code-vector ivector-class-32-bit 0) (define-subtag xcode-vector ivector-class-32-bit 1) (define-subtag bignum ivector-class-32-bit 2) (define-subtag double-float ivector-class-32-bit 3) Size does n't matter for non - CL - array gvectors ; I ca n't think of a good ;;; reason to classify them in any particular way. Let's put funcallable things in the first slice by themselves , though it 's not clear that ;;; that helps FUNCALL much. (defconstant gvector-funcallable fulltag-nodeheader-0) (define-subtag function gvector-funcallable 0) (define-subtag symbol gvector-funcallable 1) (define-subtag catch-frame fulltag-nodeheader-1 0) (define-subtag basic-stream fulltag-nodeheader-1 1) (define-subtag lock fulltag-nodeheader-1 2) (define-subtag hash-vector fulltag-nodeheader-1 3) (define-subtag pool fulltag-nodeheader-1 4) (define-subtag weak fulltag-nodeheader-1 5) (define-subtag package fulltag-nodeheader-1 6) (define-subtag slot-vector fulltag-nodeheader-2 0) (define-subtag instance fulltag-nodeheader-2 1) (define-subtag struct fulltag-nodeheader-2 2) (define-subtag istruct fulltag-nodeheader-2 3) (define-subtag value-cell fulltag-nodeheader-2 4) (define-subtag xfunction fulltag-nodeheader-2 5) (define-subtag ratio fulltag-nodeheader-3 0) (define-subtag complex fulltag-nodeheader-3 1) (eval-when (:compile-toplevel :load-toplevel :execute) (require "PPC-ARCH") (defmacro define-storage-layout (name origin &rest cells) `(progn (ccl::defenum (:start ,origin :step 8) ,@(mapcar #'(lambda (cell) (ccl::form-symbol name "." cell)) cells)) (defconstant ,(ccl::form-symbol name ".SIZE") ,(* (length cells) 8)))) (defmacro define-lisp-object (name tagname &rest cells) `(define-storage-layout ,name ,(- (symbol-value tagname)) ,@cells)) (defmacro define-fixedsized-object (name &rest non-header-cells) `(progn (define-lisp-object ,name fulltag-misc header ,@non-header-cells) (ccl::defenum () ,@(mapcar #'(lambda (cell) (ccl::form-symbol name "." cell "-CELL")) non-header-cells)) (defconstant ,(ccl::form-symbol name ".ELEMENT-COUNT") ,(length non-header-cells)))) (defconstant misc-header-offset (- fulltag-misc)) (defconstant misc-subtag-offset (+ misc-header-offset 7 )) (defconstant misc-data-offset (+ misc-header-offset 8)) (defconstant misc-dfloat-offset (+ misc-header-offset 8)) (define-subtag single-float fulltag-imm-0 0) (define-subtag character fulltag-imm-1 0) FULLTAG - IMM-2 is unused , so the only type with lisptag ( 3 - bit tag ) TAG - IMM-0 should be SINGLE - FLOAT . (define-subtag unbound fulltag-imm-3 0) (defconstant unbound-marker subtag-unbound) (defconstant undefined unbound-marker) (define-subtag slot-unbound fulltag-imm-3 1) (defconstant slot-unbound-marker subtag-slot-unbound) (define-subtag illegal fulltag-imm-3 2) (defconstant illegal-marker subtag-illegal) (define-subtag no-thread-local-binding fulltag-imm-3 3) (define-subtag forward-marker fulltag-imm-3 7) (defconstant max-64-bit-constant-index (ash (+ #x7fff ppc64::misc-dfloat-offset) -3)) (defconstant max-32-bit-constant-index (ash (+ #x7fff ppc64::misc-data-offset) -2)) (defconstant max-16-bit-constant-index (ash (+ #x7fff ppc64::misc-data-offset) -1)) (defconstant max-8-bit-constant-index (+ #x7fff ppc64::misc-data-offset)) (defconstant max-1-bit-constant-index (ash (+ #x7fff ppc64::misc-data-offset) 5)) ; The objects themselves look something like this: ; Order of CAR and CDR doesn't seem to matter much - there aren't too many tricks to be played with addressing . ; Keep them in the confusing MCL 3.0 order, to avoid confusion. (define-lisp-object cons fulltag-cons cdr car) (define-fixedsized-object ratio numer denom) ;;; It's slightly easier (for bootstrapping reasons) to view a DOUBLE - FLOAT as being UVECTOR with 2 32 - bit elements ( rather than 1 64 - bit element ) . (defconstant double-float.value misc-data-offset) (defconstant double-float.value-cell 0) (defconstant double-float.val-high double-float.value) (defconstant double-float.val-high-cell double-float.value-cell) (defconstant double-float.val-low (+ double-float.value 4)) (defconstant double-float.val-low-cell 1) (defconstant double-float.element-count 2) (defconstant double-float.size 16) (define-fixedsized-object complex realpart imagpart ) There are two kinds of macptr ; use the length field of the header if you ; need to distinguish between them (define-fixedsized-object macptr address domain type ) (define-fixedsized-object xmacptr address domain type flags link ) ; Catch frames go on the tstack; they point to a minimal lisp-frame ; on the cstack. (The catch/unwind-protect PC is on the cstack, where the GC expects to find it . ) (define-fixedsized-object catch-frame catch-tag ; #<unbound> -> unwind-protect, else catch link ; tagged pointer to next older catch frame 0 if single - value , 1 if uwp or multiple - value csp ; pointer to control stack db-link ; value of dynamic-binding link on thread entry. save-save7 ; saved registers save-save6 save-save5 save-save4 save-save3 save-save2 save-save1 save-save0 xframe ; exception-frame link tsp-segment ; mostly padding, for now. ) (define-fixedsized-object lock _value ;finalizable pointer to kernel object kind ; '0 = recursive-lock, '1 = rwlock tcr of owning thread or 0 name whostate whostate-2 ) (define-fixedsized-object symbol pname vcell fcell package-predicate flags plist binding-index ) (defconstant t-offset (- symbol.size)) (define-fixedsized-object vectorH logsize ; fillpointer if it has one, physsize otherwise physsize ; total size of (possibly displaced) data vector data-vector ; object this header describes true displacement or 0 flags ; has-fill-pointer,displaced-to,adjustable bits; subtype of underlying simple vector. ) (define-lisp-object arrayH fulltag-misc header ; subtag = subtag-arrayH rank ; NEVER 1 physsize ; total size of (possibly displaced) data vector data-vector ; object this header describes displacement ; true displacement or 0 flags ; has-fill-pointer,displaced-to,adjustable bits; subtype of underlying simple vector. ;; Dimensions follow ) (defconstant arrayH.rank-cell 0) (defconstant arrayH.physsize-cell 1) (defconstant arrayH.data-vector-cell 2) (defconstant arrayH.displacement-cell 3) (defconstant arrayH.flags-cell 4) (defconstant arrayH.dim0-cell 5) (defconstant arrayH.flags-cell-bits-byte (byte 8 0)) (defconstant arrayH.flags-cell-subtag-byte (byte 8 8)) (define-fixedsized-object value-cell value) ;;; The kernel uses these (rather generically named) structures ;;; to keep track of various memory regions it (or the lisp) is ;;; interested in. (define-storage-layout area 0 pred ; pointer to preceding area in DLL succ ; pointer to next area in DLL low ; low bound on area addresses high ; high bound on area addresses. active ; low limit on stacks, high limit on heaps softlimit ; overflow bound another one code ; an area-code; see below bit vector for GC ndnodes ; "active" size of dynamic area or stack in EGC sense also for EGC h ; Handle or null pointer softprot ; protected_area structure pointer hardprot ; another one. owner ; fragment (library) which "owns" the area refbits ; bitvector for intergenerational refernces threshold ; for egc gc-count ; generational gc count. static-dnodes ; for honsing. etc static-used ; bitvector ) (define-storage-layout protected-area 0 next start ; first byte (page-aligned) that might be protected end ; last byte (page-aligned) that could be protected nprot ; Might be 0 protsize ; number of bytes to protect why) (defconstant tcr-bias 0) (define-storage-layout tcr (- tcr-bias) prev ; in doubly-linked list next ; in doubly-linked list single-float-convert ; per-thread scratch space. lisp-fpscr-high db-link ; special binding chain head catch-top ; top catch frame VSP when in foreign code save-tsp ; TSP when in foreign code cs-area ; cstack area pointer vs-area ; vstack area pointer ts-area ; tstack area pointer cs-limit ; cstack overflow limit total-bytes-allocated-high log2-allocation-quantum ; unboxed interrupt-pending ; fixnum xframe ; exception frame linked list errno-loc ; thread-private, maybe ffi-exception ; fpscr bits from ff-call. osid ; OS thread id valence ; odd when in foreign code foreign-exception-status native-thread-info native-thread-id last-allocptr save-allocptr save-allocbase reset-completion activate suspend-count suspend-context pending-exception-context suspend ; semaphore for suspension notify resume ; sempahore for resumption notify flags ; foreign, being reset, ... gc-context termination-semaphore unwinding tlb-limit tlb-pointer shutdown-count safe-ref-address ) (defconstant interrupt-level-binding-index (ash 1 fixnumshift)) (defconstant tcr.lisp-fpscr-low (+ tcr.lisp-fpscr-high 4)) (defconstant tcr.total-bytes-allocated-low (+ tcr.total-bytes-allocated-high 4)) (define-storage-layout lockptr 0 avail owner count signal waiting malloced-ptr spinlock) (define-storage-layout rwlock 0 spin state blocked-writers blocked-readers writer reader-signal writer-signal malloced-ptr ) For the eabi port : mark this stack frame as 's ( since EABI ;;; foreign frames can be the same size as a lisp frame.) (ppc64::define-storage-layout lisp-frame 0 backlink savefn savelr savevsp ) (ppc64::define-storage-layout c-frame 0 backlink crsave savelr unused-1 unused-2 savetoc param0 param1 param2 param3 param4 param5 param6 param7 ) (defconstant c-frame.minsize c-frame.size) (defmacro define-header (name element-count subtag) `(defconstant ,name (logior (ash ,element-count num-subtag-bits) ,subtag))) (define-header double-float-header double-float.element-count subtag-double-float) We could possibly have a one - digit bignum header when dealing ;;; with "small bignums" in some bignum code. Like other cases of ;;; non-normalized bignums, they should never escape from the lab. (define-header one-digit-bignum-header 1 subtag-bignum) (define-header two-digit-bignum-header 2 subtag-bignum) (define-header three-digit-bignum-header 3 subtag-bignum) (define-header four-digit-bignum-header 4 subtag-bignum) (define-header five-digit-bignum-header 5 subtag-bignum) (define-header symbol-header symbol.element-count subtag-symbol) (define-header value-cell-header value-cell.element-count subtag-value-cell) (define-header macptr-header macptr.element-count subtag-macptr) (defconstant yield-syscall #+darwinppc-target -60 #+linuxppc-target #$__NR_sched_yield) ) ) (defun %kernel-global (sym) (let* ((pos (position sym ppc::*ppc-kernel-globals* :test #'string=))) (if pos (- (+ symbol.size fulltag-misc (* (1+ pos) word-size-in-bytes))) (error "Unknown kernel global : ~s ." sym)))) (defmacro kernel-global (sym) (let* ((pos (position sym ppc::*ppc-kernel-globals* :test #'string=))) (if pos (- (+ symbol.size fulltag-misc (* (1+ pos) word-size-in-bytes))) (error "Unknown kernel global : ~s ." sym)))) ;;; The kernel imports things that are defined in various other ;;; libraries for us. The objects in question are generally fixnum - tagged ; the entries in the " kernel - imports " vector are 8 ;;; bytes apart. (ccl::defenum (:prefix "KERNEL-IMPORT-" :start 0 :step word-size-in-bytes) fd-setsize-bytes do-fd-set do-fd-clr do-fd-is-set do-fd-zero MakeDataExecutable GetSharedLibrary FindSymbol malloc free wait-for-signal tcr-frame-ptr register-xmacptr-dispose-function open-debug-output get-r-debug restore-soft-stack-limit egc-control lisp-bug NewThread YieldToThread DisposeThread ThreadCurrentStackSpace usage-exit save-fp-context restore-fp-context put-altivec-registers get-altivec-registers new-semaphore wait-on-semaphore signal-semaphore destroy-semaphore new-recursive-lock lock-recursive-lock unlock-recursive-lock destroy-recursive-lock suspend-other-threads resume-other-threads suspend-tcr resume-tcr rwlock-new rwlock-destroy rwlock-rlock rwlock-wlock rwlock-unlock recursive-lock-trylock foreign-name-and-offset lisp-read lisp-write lisp-open lisp-fchmod lisp-lseek lisp-close lisp-ftruncate lisp-stat lisp-fstat lisp-futex lisp-opendir lisp-readdir lisp-closedir lisp-pipe lisp-gettimeofday lisp-sigexit jvm-init ) (defmacro nrs-offset (name) (let* ((pos (position name ppc::*ppc-nilreg-relative-symbols* :test #'eq))) (if pos (* (1- pos) symbol.size)))) (defconstant canonical-nil-value (+ #x3000 symbol.size fulltag-misc)) (defconstant reservation-discharge #x2008) (defparameter *ppc64-target-uvector-subtags* `((:bignum . ,subtag-bignum) (:ratio . ,subtag-ratio) (:single-float . ,subtag-single-float) (:double-float . ,subtag-double-float) (:complex . ,subtag-complex ) (:symbol . ,subtag-symbol) (:function . ,subtag-function ) (:code-vector . ,subtag-code-vector) (:xcode-vector . ,subtag-xcode-vector) (:macptr . ,subtag-macptr ) (:catch-frame . ,subtag-catch-frame) (:struct . ,subtag-struct ) (:istruct . ,subtag-istruct ) (:pool . ,subtag-pool ) (:population . ,subtag-weak ) (:hash-vector . ,subtag-hash-vector ) (:package . ,subtag-package ) (:value-cell . ,subtag-value-cell) (:instance . ,subtag-instance ) (:lock . ,subtag-lock ) (:basic-stream . ,subtag-basic-stream) (:slot-vector . ,subtag-slot-vector) (:simple-string . ,subtag-simple-base-string ) (:bit-vector . ,subtag-bit-vector ) (:signed-8-bit-vector . ,subtag-s8-vector ) (:unsigned-8-bit-vector . ,subtag-u8-vector ) (:signed-16-bit-vector . ,subtag-s16-vector ) (:unsigned-16-bit-vector . ,subtag-u16-vector ) (:signed-32-bit-vector . ,subtag-s32-vector ) (:unsigned-32-bit-vector . ,subtag-u32-vector ) (:fixnum-vector . ,subtag-fixnum-vector) (:signed-64-bit-vector . ,subtag-s64-vector) (:unsigned-64-bit-vector . ,subtag-u64-vector) (:single-float-vector . ,subtag-single-float-vector) (:double-float-vector . ,subtag-double-float-vector ) (:simple-vector . ,subtag-simple-vector ) (:vector-header . ,subtag-vectorH) (:array-header . ,subtag-arrayH))) ;;; This should return NIL unless it's sure of how the indicated ;;; type would be represented (in particular, it should return NIL if the element type is unknown or unspecified at compile - time . (defun ppc64-array-type-name-from-ctype (ctype) (when (typep ctype 'ccl::array-ctype) (let* ((element-type (ccl::array-ctype-element-type ctype))) (typecase element-type (ccl::class-ctype (let* ((class (ccl::class-ctype-class element-type))) (if (or (eq class ccl::*character-class*) (eq class ccl::*base-char-class*) (eq class ccl::*standard-char-class*)) :simple-string :simple-vector))) (ccl::numeric-ctype (if (eq (ccl::numeric-ctype-complexp element-type) :complex) :simple-vector (case (ccl::numeric-ctype-class element-type) (integer (let* ((low (ccl::numeric-ctype-low element-type)) (high (ccl::numeric-ctype-high element-type))) (cond ((or (null low) (null high)) :simple-vector) ((and (>= low 0) (<= high 1)) :bit-vector) ((and (>= low 0) (<= high 255)) :unsigned-8-bit-vector) ((and (>= low 0) (<= high 65535)) :unsigned-16-bit-vector) ((and (>= low 0) (<= high #xffffffff)) :unsigned-32-bit-vector) ((and (>= low 0) (<= high #xffffffffffffffff)) :unsigned-64-bit-vector) ((and (>= low -128) (<= high 127)) :signed-8-bit-vector) ((and (>= low -32768) (<= high 32767)) :signed-16-bit-vector) ((and (>= low (ash -1 31)) (<= high (1- (ash 1 31)))) :signed-32-bit-vector) ((and (>= low target-most-negative-fixnum) (<= high target-most-positive-fixnum)) :fixnum-vector) ((and (>= low (ash -1 63)) (<= high (1- (ash 1 63)))) :signed-64-bit-vector) (t :simple-vector)))) (float (case (ccl::numeric-ctype-format element-type) ((double-float long-float) :double-float-vector) ((single-float short-float) :single-float-vector) (t :simple-vector))) (t :simple-vector)))) (ccl::unknown-ctype) (ccl::named-ctype (if (eq element-type ccl::*universal-type*) :simple-vector)) (t))))) (defun ppc64-misc-byte-count (subtag element-count) (declare (fixnum subtag)) (if (= lowtag-nodeheader (logand subtag lowtagmask)) (ash element-count 3) (case (logand subtag fulltagmask) (#.ivector-class-64-bit (ash element-count 3)) (#.ivector-class-32-bit (ash element-count 2)) (#.ivector-class-8-bit element-count) (t (if (= subtag subtag-bit-vector) (ash (+ 7 element-count) -3) (ash element-count 1)))))) (defparameter *ppc64-target-arch* (arch::make-target-arch :name :ppc64 :lisp-node-size 8 :nil-value canonical-nil-value :fixnum-shift fixnumshift :most-positive-fixnum (1- (ash 1 (1- (- 64 fixnumshift)))) :most-negative-fixnum (- (ash 1 (1- (- 64 fixnumshift)))) :misc-data-offset misc-data-offset :misc-dfloat-offset misc-dfloat-offset :nbits-in-word 64 :ntagbits 4 :nlisptagbits 3 :uvector-subtags *ppc64-target-uvector-subtags* :max-64-bit-constant-index max-64-bit-constant-index :max-32-bit-constant-index max-32-bit-constant-index :max-16-bit-constant-index max-16-bit-constant-index :max-8-bit-constant-index max-8-bit-constant-index :max-1-bit-constant-index max-1-bit-constant-index :word-shift 3 :code-vector-prefix '(#$"CODE") :gvector-types '(:ratio :complex :symbol :function :catch-frame :struct :istruct :pool :population :hash-vector :package :value-cell :instance :lock :slot-vector :simple-vector) :1-bit-ivector-types '(:bit-vector) :8-bit-ivector-types '(:signed-8-bit-vector :unsigned-8-bit-vector) :16-bit-ivector-types '(:signed-16-bit-vector :unsigned-16-bit-vector) :32-bit-ivector-types '(:signed-32-bit-vector :unsigned-32-bit-vector :single-float-vector :double-float :bignum :simple-string) :64-bit-ivector-types '(:double-float-vector :unsigned-64-bit-vector :signed-64-bit-vector :fixnum-vector) :array-type-name-from-ctype-function #'ppc64-array-type-name-from-ctype :package-name "PPC64" :t-offset t-offset :array-data-size-function #'ppc64-misc-byte-count :numeric-type-name-to-typecode-function #'(lambda (type-name) (ecase type-name (fixnum tag-fixnum) (bignum subtag-bignum) ((short-float single-float) subtag-single-float) ((long-float double-float) subtag-double-float) (ratio subtag-ratio) (complex subtag-complex))) :subprims-base ppc::*ppc-subprims-base* :subprims-shift ppc::*ppc-subprims-shift* :subprims-table ppc::*ppc-subprims* :primitive->subprims `(((0 . 23) . ,(ccl::%subprim-name->offset '.SPbuiltin-plus ppc::*ppc-subprims*))) :unbound-marker-value unbound-marker :slot-unbound-marker-value slot-unbound-marker :fixnum-tag tag-fixnum :single-float-tag subtag-single-float :single-float-tag-is-subtag nil :double-float-tag subtag-double-float :cons-tag fulltag-cons :null-tag subtag-symbol :symbol-tag subtag-symbol :symbol-tag-is-subtag t :function-tag subtag-function :function-tag-is-subtag t :big-endian t :misc-subtag-offset misc-subtag-offset :car-offset cons.car :cdr-offset cons.cdr :subtag-char subtag-character :charcode-shift charcode-shift :fulltagmask fulltagmask :fulltag-misc fulltag-misc :char-code-limit #x110000 )) ;;; arch macros (defmacro defppc64archmacro (name lambda-list &body body) `(arch::defarchmacro :ppc64 ,name ,lambda-list ,@body)) (defppc64archmacro ccl::%make-sfloat () (error "~s shouldn't be used in code targeting :PPC64" 'ccl::%make-sfloat)) (defppc64archmacro ccl::%make-dfloat () `(ccl::%alloc-misc ppc64::double-float.element-count ppc64::subtag-double-float)) (defppc64archmacro ccl::%numerator (x) `(ccl::%svref ,x ppc64::ratio.numer-cell)) (defppc64archmacro ccl::%denominator (x) `(ccl::%svref ,x ppc64::ratio.denom-cell)) (defppc64archmacro ccl::%realpart (x) `(ccl::%svref ,x ppc64::complex.realpart-cell)) (defppc64archmacro ccl::%imagpart (x) `(ccl::%svref ,x ppc64::complex.imagpart-cell)) ;;; (defppc64archmacro ccl::%get-single-float-from-double-ptr (ptr offset) `(ccl::%double-float->short-float (ccl::%get-double-float ,ptr ,offset))) (defppc64archmacro ccl::codevec-header-p (word) `(eql ,word #$"CODE")) ;;; (defppc64archmacro ccl::immediate-p-macro (thing) (let* ((tag (gensym))) `(let* ((,tag (ccl::lisptag ,thing))) (declare (fixnum ,tag)) (or (= ,tag ppc64::tag-fixnum) (= (logand ,tag ppc64::lowtagmask) ppc64::lowtag-imm))))) (defppc64archmacro ccl::hashed-by-identity (thing) (let* ((typecode (gensym))) `(let* ((,typecode (ccl::typecode ,thing))) (declare (fixnum ,typecode)) (or (= ,typecode ppc64::tag-fixnum) (= (logand ,typecode ppc64::lowtagmask) ppc64::lowtag-imm) (= ,typecode ppc64::subtag-symbol) (= ,typecode ppc64::subtag-instance))))) ;;; (defppc64archmacro ccl::%get-kernel-global (name) `(ccl::%fixnum-ref 0 (+ ,(ccl::target-nil-value) ,(%kernel-global (if (ccl::quoted-form-p name) (cadr name) name))))) (defppc64archmacro ccl::%get-kernel-global-ptr (name dest) `(ccl::%setf-macptr ,dest (ccl::%fixnum-ref-macptr 0 (+ ,(ccl::target-nil-value) ,(%kernel-global (if (ccl::quoted-form-p name) (cadr name) name)))))) (defppc64archmacro ccl::%target-kernel-global (name) `(ppc64::%kernel-global ,name)) (defppc64archmacro ccl::lfun-vector (fn) fn) (defppc64archmacro ccl::lfun-vector-lfun (lfv) lfv) (defppc64archmacro ccl::area-code () area.code) (defppc64archmacro ccl::area-succ () area.succ) (defppc64archmacro ccl::nth-immediate (f i) `(ccl::%svref ,f ,i)) (defppc64archmacro ccl::set-nth-immediate (f i new) `(setf (ccl::%svref ,f ,i) ,new)) (defppc64archmacro ccl::symptr->symvector (s) s) (defppc64archmacro ccl::symvector->symptr (s) s) (defppc64archmacro ccl::function-to-function-vector (f) f) (defppc64archmacro ccl::function-vector-to-function (v) v) (defppc64archmacro ccl::with-ffcall-results ((buf) &body body) (let* ((size (+ (* 8 8) (* 13 8)))) `(ccl::%stack-block ((,buf ,size)) ,@body))) (defconstant arg-check-trap-pc-limit 8) (defconstant fasl-version #x60) (defconstant fasl-max-version #x60) (defconstant fasl-min-version #x60) (defparameter *image-abi-version* 1039) (provide "PPC64-ARCH")
null
https://raw.githubusercontent.com/fukamachi/clozure-cl/4b0c69452386ae57b08984ed815d9b50b4bcc8a2/compiler/PPC/PPC64/ppc64-arch.lisp
lisp
Package : ( : use CL ) -*- file "LICENSE". The LLGPL consists of a preamble and the LGPL, conflict, the preamble takes precedence. Clozure CL is referenced in the preamble as the "LIBRARY." The LLGPL is also available online at This file matches "ccl:lisp-kernel;constants64.h" & "ccl:lisp-kernel;constants64.s" See ? A pet name for it. PPC64 stuff and tags. follows (I'm not sure if we'd ever want to do this) : Note that the ppc64's LD and STD instructions require that the low fixnum addition and subtraction work better when fixnum tags are all 0. class of "potentially primary" object we're looking at. Note how we're already winding up with lots of header and immediate "classes". That might actually be useful. vector. That basically requires that NIL really be a symbol (good The general algorithm for determining the (primary) type of an object is something like: (cmpwi tag fulltag-misc) (bne @done) That's good enough to identify FIXNUM, "generally immediate", cons, In no specific order: - it's important to be able to quickly recognize fixnums; that's simple - it's important to be able to quickly recognize lists (for CAR/CDR) and somewhat important to be able to quickly recognize conses. - it's desirable to be able (in FUNCALL) to quickly recognize functions/symbols/other, and probably desirable to trap on other. here. - it's sometimes desirable to recognize numbers and distinct numeric types (other than FIXNUM) quickly. naturally.) - We have a fairly large number of non-array gvector types, and it's always desirable to have room for expansion. array types. s64 s32 u16 s8 BIGNUM DOUBLE-FLOAT detected case of OTHER. There's some room for expansion in non-array ivector space. I ca n't think of a good reason to classify them in any particular way. Let's put funcallable that helps FUNCALL much. The objects themselves look something like this: Order of CAR and CDR doesn't seem to matter much - there aren't Keep them in the confusing MCL 3.0 order, to avoid confusion. It's slightly easier (for bootstrapping reasons) use the length field of the header if you need to distinguish between them Catch frames go on the tstack; they point to a minimal lisp-frame on the cstack. (The catch/unwind-protect PC is on the cstack, where #<unbound> -> unwind-protect, else catch tagged pointer to next older catch frame pointer to control stack value of dynamic-binding link on thread entry. saved registers exception-frame link mostly padding, for now. finalizable pointer to kernel object '0 = recursive-lock, '1 = rwlock fillpointer if it has one, physsize otherwise total size of (possibly displaced) data vector object this header describes has-fill-pointer,displaced-to,adjustable bits; subtype of underlying simple vector. subtag = subtag-arrayH NEVER 1 total size of (possibly displaced) data vector object this header describes true displacement or 0 has-fill-pointer,displaced-to,adjustable bits; subtype of underlying simple vector. Dimensions follow The kernel uses these (rather generically named) structures to keep track of various memory regions it (or the lisp) is interested in. pointer to preceding area in DLL pointer to next area in DLL low bound on area addresses high bound on area addresses. low limit on stacks, high limit on heaps overflow bound an area-code; see below "active" size of dynamic area or stack Handle or null pointer protected_area structure pointer another one. fragment (library) which "owns" the area bitvector for intergenerational refernces for egc generational gc count. for honsing. etc bitvector first byte (page-aligned) that might be protected last byte (page-aligned) that could be protected Might be 0 number of bytes to protect in doubly-linked list in doubly-linked list per-thread scratch space. special binding chain head top catch frame TSP when in foreign code cstack area pointer vstack area pointer tstack area pointer cstack overflow limit unboxed fixnum exception frame linked list thread-private, maybe fpscr bits from ff-call. OS thread id odd when in foreign code semaphore for suspension notify sempahore for resumption notify foreign, being reset, ... foreign frames can be the same size as a lisp frame.) with "small bignums" in some bignum code. Like other cases of non-normalized bignums, they should never escape from the lab. The kernel imports things that are defined in various other libraries for us. The objects in question are generally the entries in the " kernel - imports " vector are 8 bytes apart. This should return NIL unless it's sure of how the indicated type would be represented (in particular, it should return arch macros
Copyright ( C ) 2009 Clozure Associates Copyright ( C ) 1994 - 2001 Digitool , Inc This file is part of Clozure CL . Clozure CL is licensed under the terms of the Lisp Lesser GNU Public License , known as the LLGPL and distributed with Clozure CL as the which is distributed with Clozure CL as the file " LGPL " . Where these (defpackage "PPC64" (:use "CL") #+ppc64-target (:nicknames "TARGET")) (in-package "PPC64") (eval-when (:compile-toplevel :load-toplevel :execute) sigh . Could use r13+bias on Linux , but Apple has n't invented tls yet . (defconstant nbits-in-word 64) (defconstant least-significant-bit 63) (defconstant nbits-in-byte 8) (defconstant ntagbits 4) (defconstant nlisptagbits 3) (defconstant nlowtagbits 2) tag part of header is 8 bits wide (defconstant fixnumshift nfixnumtagbits) Only needed by GC / very low - level code (defconstant full-tag-mask fulltagmask) (defconstant tagmask (1- (ash 1 nlisptagbits))) (defconstant tag-mask tagmask) (defconstant fixnummask (1- (ash 1 nfixnumtagbits))) (defconstant fixnum-mask fixnummask) (defconstant subtag-mask (1- (ash 1 num-subtag-bits))) 24 (defconstant charcode-shift 8) (defconstant word-shift 3) (defconstant word-size-in-bytes 8) (defconstant node-size word-size-in-bytes) (defconstant dnode-size 16) (defconstant dnode-align-bits 4) (defconstant dnode-shift dnode-align-bits) (defconstant bitmap-shift 6) (defconstant target-most-negative-fixnum (ash -1 (1- (- nbits-in-word nfixnumtagbits)))) (defconstant target-most-positive-fixnum (1- (ash 1 (1- (- nbits-in-word nfixnumtagbits))))) (defmacro define-subtag (name tag value) `(defconstant ,(ccl::form-symbol "SUBTAG-" name) (logior ,tag (ash ,value ntagbits)))) There are several ways to look at the 4 tag bits of any object or header . Looking at the low 2 bits , we can classify things as # b00 a " primary " object : fixnum , cons , uvector # b01 an immediate # b10 the header on an immediate uvector # b11 the header on a node ( pointer - containing ) uvector two bits of the constant displacement be # b00 . If we want to use constant offsets to access CONS and UVECTOR fields , we 're pretty much obligated to ensure that CONS and UVECTOR have tags that also end in # b00 , and We generally have to look at all 4 tag bits before we really know what If we look at 3 tag bits , we can see : # b000 fixnum # b001 immediate # b010 immedate - header # b011 node - header # b100 CONS or UVECTOR # b101 immediate # b110 immediate - header # b111 node - header (defconstant tag-fixnum 0) (defconstant tag-imm-0 1) (defconstant tag-immheader-0 2) (defconstant tag-nodeheader-0 3) (defconstant tag-memory 4) (defconstant tag-imm-2 5) (defconstant tag-immheader2 6) (defconstant tag-nodeheader2 7) When we move to 4 bits , we wind up ( obviously ) with 4 tags of the form # bxx00 . There are two partitionings that make ( some ) sense : we can either use 2 of these for ( even and odd ) fixnums , or we can give NIL a tag that 's congruent ( mod 16 ) with CONS . There seem to be a lot of tradeoffs involved , but it ultimately seems best to be able to treat 64 - bit aligned addresses as fixnums : we do n't want the to look like a bye , nilsym ) and that we ensure that there are NILs where its CAR and CDR would be ( -4 , 4 bytes from the tagged pointer . ) That means that CONS is 4 and UVECTOR is 12 , and we have even more immediate / header types . (defconstant fulltag-even-fixnum #b0000) (defconstant fulltag-imm-0 #b0001) (defconstant fulltag-immheader-0 #b0010) (defconstant fulltag-nodeheader-0 #b0011) (defconstant fulltag-cons #b0100) (defconstant fulltag-imm-1 #b0101) (defconstant fulltag-immheader-1 #b0110) (defconstant fulltag-nodeheader-1 #b0111) (defconstant fulltag-odd-fixnum #b1000) (defconstant fulltag-imm-2 #b1001) (defconstant fulltag-immheader-2 #b1010) (defconstant fulltag-nodeheader-2 #b1011) (defconstant fulltag-misc #b1100) (defconstant fulltag-imm-3 #b1101) (defconstant fulltag-immheader-3 #b1110) (defconstant fulltag-nodeheader-3 #b1111) (defconstant lowtagmask (1- (ash 1 nlowtagbits))) (defconstant lowtag-mask lowtagmask) (defconstant lowtag-primary 0) (defconstant lowtag-imm 1) (defconstant lowtag-immheader 2) (defconstant lowtag-nodeheader 3) ( clrldi tag node 60 ) ( clrldi tag tag 61 ) ( tag misc - subtag - offset node ) @done or a header tag from a UVECTOR . In some cases , we may need to hold on to the full 4 - bit tag . Also simple , though we have to special - case NIL . - it 's desirable to be able to do , ARRAYP , and specific - array - type- p. We need at least 12 immediate CL vector types ( SIGNED / UNSIGNED - BYTE we need SIMPLE - ARRAY , VECTOR - HEADER , and ARRAY - HEADER as node array types . That 's suspciciously close to 16 Pretty much have to do a memory reference and at least one comparison - The GC ( especially ) needs to be able to determine the size of ivectors ( ivector elements ) fairly cheaply . Most ivectors are CL arrays , but code - vectors are fairly common ( and have 32 - bit elements , - we basically have 8 classes of , each of which has 16 possible values . If we stole the high bit of the subtag to indicate CL - array - ness , we 'd still have 6 bits to encode non - CL (defconstant cl-array-subtag-bit 7) (defconstant cl-array-subtag-mask (ash 1 cl-array-subtag-bit)) (defmacro define-cl-array-subtag (name tag value) `(defconstant ,(ccl::form-symbol "SUBTAG-" name) (logior cl-array-subtag-mask (logior ,tag (ash ,value ntagbits))))) (define-cl-array-subtag arrayH fulltag-nodeheader-1 0) (define-cl-array-subtag vectorH fulltag-nodeheader-2 0) (define-cl-array-subtag simple-vector fulltag-nodeheader-3 0) (defconstant min-array-subtag subtag-arrayH) (defconstant min-vector-subtag subtag-vectorH) bits : 64 32 16 8 1 CL - array ivector types DOUBLE - FLOAT SINGLE s16 CHAR BIT u64 u32 u8 Other ivector types MACPTR CODE - VECTOR DEAD - MACPTR XCODE - VECTOR There might possibly be ivectors with 128 - bit ( VMX / AltiVec ) elements someday , and there might be multiple character sizes ( 16/32 bits ) . That sort of suggests that we use the four immheader classes to encode the ivector size ( 64 , 32 , 8 , other ) and make BIT an easily- (defconstant ivector-class-64-bit fulltag-immheader-3) (defconstant ivector-class-32-bit fulltag-immheader-2) (defconstant ivector-class-other-bit fulltag-immheader-1) (defconstant ivector-class-8-bit fulltag-immheader-0) (define-cl-array-subtag s64-vector ivector-class-64-bit 1) (define-cl-array-subtag u64-vector ivector-class-64-bit 2) (define-cl-array-subtag fixnum-vector ivector-class-64-bit 3) (define-cl-array-subtag double-float-vector ivector-class-64-bit 4) (define-cl-array-subtag s32-vector ivector-class-32-bit 1) (define-cl-array-subtag u32-vector ivector-class-32-bit 2) (define-cl-array-subtag single-float-vector ivector-class-32-bit 3) (define-cl-array-subtag simple-base-string ivector-class-32-bit 5) (define-cl-array-subtag s16-vector ivector-class-other-bit 1) (define-cl-array-subtag u16-vector ivector-class-other-bit 2) (define-cl-array-subtag bit-vector ivector-class-other-bit 7) (define-cl-array-subtag s8-vector ivector-class-8-bit 1) (define-cl-array-subtag u8-vector ivector-class-8-bit 2) (define-subtag macptr ivector-class-64-bit 1) (define-subtag dead-macptr ivector-class-64-bit 2) (define-subtag code-vector ivector-class-32-bit 0) (define-subtag xcode-vector ivector-class-32-bit 1) (define-subtag bignum ivector-class-32-bit 2) (define-subtag double-float ivector-class-32-bit 3) things in the first slice by themselves , though it 's not clear that (defconstant gvector-funcallable fulltag-nodeheader-0) (define-subtag function gvector-funcallable 0) (define-subtag symbol gvector-funcallable 1) (define-subtag catch-frame fulltag-nodeheader-1 0) (define-subtag basic-stream fulltag-nodeheader-1 1) (define-subtag lock fulltag-nodeheader-1 2) (define-subtag hash-vector fulltag-nodeheader-1 3) (define-subtag pool fulltag-nodeheader-1 4) (define-subtag weak fulltag-nodeheader-1 5) (define-subtag package fulltag-nodeheader-1 6) (define-subtag slot-vector fulltag-nodeheader-2 0) (define-subtag instance fulltag-nodeheader-2 1) (define-subtag struct fulltag-nodeheader-2 2) (define-subtag istruct fulltag-nodeheader-2 3) (define-subtag value-cell fulltag-nodeheader-2 4) (define-subtag xfunction fulltag-nodeheader-2 5) (define-subtag ratio fulltag-nodeheader-3 0) (define-subtag complex fulltag-nodeheader-3 1) (eval-when (:compile-toplevel :load-toplevel :execute) (require "PPC-ARCH") (defmacro define-storage-layout (name origin &rest cells) `(progn (ccl::defenum (:start ,origin :step 8) ,@(mapcar #'(lambda (cell) (ccl::form-symbol name "." cell)) cells)) (defconstant ,(ccl::form-symbol name ".SIZE") ,(* (length cells) 8)))) (defmacro define-lisp-object (name tagname &rest cells) `(define-storage-layout ,name ,(- (symbol-value tagname)) ,@cells)) (defmacro define-fixedsized-object (name &rest non-header-cells) `(progn (define-lisp-object ,name fulltag-misc header ,@non-header-cells) (ccl::defenum () ,@(mapcar #'(lambda (cell) (ccl::form-symbol name "." cell "-CELL")) non-header-cells)) (defconstant ,(ccl::form-symbol name ".ELEMENT-COUNT") ,(length non-header-cells)))) (defconstant misc-header-offset (- fulltag-misc)) (defconstant misc-subtag-offset (+ misc-header-offset 7 )) (defconstant misc-data-offset (+ misc-header-offset 8)) (defconstant misc-dfloat-offset (+ misc-header-offset 8)) (define-subtag single-float fulltag-imm-0 0) (define-subtag character fulltag-imm-1 0) FULLTAG - IMM-2 is unused , so the only type with lisptag ( 3 - bit tag ) TAG - IMM-0 should be SINGLE - FLOAT . (define-subtag unbound fulltag-imm-3 0) (defconstant unbound-marker subtag-unbound) (defconstant undefined unbound-marker) (define-subtag slot-unbound fulltag-imm-3 1) (defconstant slot-unbound-marker subtag-slot-unbound) (define-subtag illegal fulltag-imm-3 2) (defconstant illegal-marker subtag-illegal) (define-subtag no-thread-local-binding fulltag-imm-3 3) (define-subtag forward-marker fulltag-imm-3 7) (defconstant max-64-bit-constant-index (ash (+ #x7fff ppc64::misc-dfloat-offset) -3)) (defconstant max-32-bit-constant-index (ash (+ #x7fff ppc64::misc-data-offset) -2)) (defconstant max-16-bit-constant-index (ash (+ #x7fff ppc64::misc-data-offset) -1)) (defconstant max-8-bit-constant-index (+ #x7fff ppc64::misc-data-offset)) (defconstant max-1-bit-constant-index (ash (+ #x7fff ppc64::misc-data-offset) 5)) too many tricks to be played with addressing . (define-lisp-object cons fulltag-cons cdr car) (define-fixedsized-object ratio numer denom) to view a DOUBLE - FLOAT as being UVECTOR with 2 32 - bit elements ( rather than 1 64 - bit element ) . (defconstant double-float.value misc-data-offset) (defconstant double-float.value-cell 0) (defconstant double-float.val-high double-float.value) (defconstant double-float.val-high-cell double-float.value-cell) (defconstant double-float.val-low (+ double-float.value 4)) (defconstant double-float.val-low-cell 1) (defconstant double-float.element-count 2) (defconstant double-float.size 16) (define-fixedsized-object complex realpart imagpart ) (define-fixedsized-object macptr address domain type ) (define-fixedsized-object xmacptr address domain type flags link ) the GC expects to find it . ) (define-fixedsized-object catch-frame 0 if single - value , 1 if uwp or multiple - value save-save6 save-save5 save-save4 save-save3 save-save2 save-save1 save-save0 ) (define-fixedsized-object lock tcr of owning thread or 0 name whostate whostate-2 ) (define-fixedsized-object symbol pname vcell fcell package-predicate flags plist binding-index ) (defconstant t-offset (- symbol.size)) (define-fixedsized-object vectorH true displacement or 0 ) (define-lisp-object arrayH fulltag-misc ) (defconstant arrayH.rank-cell 0) (defconstant arrayH.physsize-cell 1) (defconstant arrayH.data-vector-cell 2) (defconstant arrayH.displacement-cell 3) (defconstant arrayH.flags-cell 4) (defconstant arrayH.dim0-cell 5) (defconstant arrayH.flags-cell-bits-byte (byte 8 0)) (defconstant arrayH.flags-cell-subtag-byte (byte 8 8)) (define-fixedsized-object value-cell value) (define-storage-layout area 0 another one bit vector for GC in EGC sense also for EGC ) (define-storage-layout protected-area 0 next why) (defconstant tcr-bias 0) (define-storage-layout tcr (- tcr-bias) lisp-fpscr-high VSP when in foreign code total-bytes-allocated-high foreign-exception-status native-thread-info native-thread-id last-allocptr save-allocptr save-allocbase reset-completion activate suspend-count suspend-context pending-exception-context gc-context termination-semaphore unwinding tlb-limit tlb-pointer shutdown-count safe-ref-address ) (defconstant interrupt-level-binding-index (ash 1 fixnumshift)) (defconstant tcr.lisp-fpscr-low (+ tcr.lisp-fpscr-high 4)) (defconstant tcr.total-bytes-allocated-low (+ tcr.total-bytes-allocated-high 4)) (define-storage-layout lockptr 0 avail owner count signal waiting malloced-ptr spinlock) (define-storage-layout rwlock 0 spin state blocked-writers blocked-readers writer reader-signal writer-signal malloced-ptr ) For the eabi port : mark this stack frame as 's ( since EABI (ppc64::define-storage-layout lisp-frame 0 backlink savefn savelr savevsp ) (ppc64::define-storage-layout c-frame 0 backlink crsave savelr unused-1 unused-2 savetoc param0 param1 param2 param3 param4 param5 param6 param7 ) (defconstant c-frame.minsize c-frame.size) (defmacro define-header (name element-count subtag) `(defconstant ,name (logior (ash ,element-count num-subtag-bits) ,subtag))) (define-header double-float-header double-float.element-count subtag-double-float) We could possibly have a one - digit bignum header when dealing (define-header one-digit-bignum-header 1 subtag-bignum) (define-header two-digit-bignum-header 2 subtag-bignum) (define-header three-digit-bignum-header 3 subtag-bignum) (define-header four-digit-bignum-header 4 subtag-bignum) (define-header five-digit-bignum-header 5 subtag-bignum) (define-header symbol-header symbol.element-count subtag-symbol) (define-header value-cell-header value-cell.element-count subtag-value-cell) (define-header macptr-header macptr.element-count subtag-macptr) (defconstant yield-syscall #+darwinppc-target -60 #+linuxppc-target #$__NR_sched_yield) ) ) (defun %kernel-global (sym) (let* ((pos (position sym ppc::*ppc-kernel-globals* :test #'string=))) (if pos (- (+ symbol.size fulltag-misc (* (1+ pos) word-size-in-bytes))) (error "Unknown kernel global : ~s ." sym)))) (defmacro kernel-global (sym) (let* ((pos (position sym ppc::*ppc-kernel-globals* :test #'string=))) (if pos (- (+ symbol.size fulltag-misc (* (1+ pos) word-size-in-bytes))) (error "Unknown kernel global : ~s ." sym)))) (ccl::defenum (:prefix "KERNEL-IMPORT-" :start 0 :step word-size-in-bytes) fd-setsize-bytes do-fd-set do-fd-clr do-fd-is-set do-fd-zero MakeDataExecutable GetSharedLibrary FindSymbol malloc free wait-for-signal tcr-frame-ptr register-xmacptr-dispose-function open-debug-output get-r-debug restore-soft-stack-limit egc-control lisp-bug NewThread YieldToThread DisposeThread ThreadCurrentStackSpace usage-exit save-fp-context restore-fp-context put-altivec-registers get-altivec-registers new-semaphore wait-on-semaphore signal-semaphore destroy-semaphore new-recursive-lock lock-recursive-lock unlock-recursive-lock destroy-recursive-lock suspend-other-threads resume-other-threads suspend-tcr resume-tcr rwlock-new rwlock-destroy rwlock-rlock rwlock-wlock rwlock-unlock recursive-lock-trylock foreign-name-and-offset lisp-read lisp-write lisp-open lisp-fchmod lisp-lseek lisp-close lisp-ftruncate lisp-stat lisp-fstat lisp-futex lisp-opendir lisp-readdir lisp-closedir lisp-pipe lisp-gettimeofday lisp-sigexit jvm-init ) (defmacro nrs-offset (name) (let* ((pos (position name ppc::*ppc-nilreg-relative-symbols* :test #'eq))) (if pos (* (1- pos) symbol.size)))) (defconstant canonical-nil-value (+ #x3000 symbol.size fulltag-misc)) (defconstant reservation-discharge #x2008) (defparameter *ppc64-target-uvector-subtags* `((:bignum . ,subtag-bignum) (:ratio . ,subtag-ratio) (:single-float . ,subtag-single-float) (:double-float . ,subtag-double-float) (:complex . ,subtag-complex ) (:symbol . ,subtag-symbol) (:function . ,subtag-function ) (:code-vector . ,subtag-code-vector) (:xcode-vector . ,subtag-xcode-vector) (:macptr . ,subtag-macptr ) (:catch-frame . ,subtag-catch-frame) (:struct . ,subtag-struct ) (:istruct . ,subtag-istruct ) (:pool . ,subtag-pool ) (:population . ,subtag-weak ) (:hash-vector . ,subtag-hash-vector ) (:package . ,subtag-package ) (:value-cell . ,subtag-value-cell) (:instance . ,subtag-instance ) (:lock . ,subtag-lock ) (:basic-stream . ,subtag-basic-stream) (:slot-vector . ,subtag-slot-vector) (:simple-string . ,subtag-simple-base-string ) (:bit-vector . ,subtag-bit-vector ) (:signed-8-bit-vector . ,subtag-s8-vector ) (:unsigned-8-bit-vector . ,subtag-u8-vector ) (:signed-16-bit-vector . ,subtag-s16-vector ) (:unsigned-16-bit-vector . ,subtag-u16-vector ) (:signed-32-bit-vector . ,subtag-s32-vector ) (:unsigned-32-bit-vector . ,subtag-u32-vector ) (:fixnum-vector . ,subtag-fixnum-vector) (:signed-64-bit-vector . ,subtag-s64-vector) (:unsigned-64-bit-vector . ,subtag-u64-vector) (:single-float-vector . ,subtag-single-float-vector) (:double-float-vector . ,subtag-double-float-vector ) (:simple-vector . ,subtag-simple-vector ) (:vector-header . ,subtag-vectorH) (:array-header . ,subtag-arrayH))) NIL if the element type is unknown or unspecified at compile - time . (defun ppc64-array-type-name-from-ctype (ctype) (when (typep ctype 'ccl::array-ctype) (let* ((element-type (ccl::array-ctype-element-type ctype))) (typecase element-type (ccl::class-ctype (let* ((class (ccl::class-ctype-class element-type))) (if (or (eq class ccl::*character-class*) (eq class ccl::*base-char-class*) (eq class ccl::*standard-char-class*)) :simple-string :simple-vector))) (ccl::numeric-ctype (if (eq (ccl::numeric-ctype-complexp element-type) :complex) :simple-vector (case (ccl::numeric-ctype-class element-type) (integer (let* ((low (ccl::numeric-ctype-low element-type)) (high (ccl::numeric-ctype-high element-type))) (cond ((or (null low) (null high)) :simple-vector) ((and (>= low 0) (<= high 1)) :bit-vector) ((and (>= low 0) (<= high 255)) :unsigned-8-bit-vector) ((and (>= low 0) (<= high 65535)) :unsigned-16-bit-vector) ((and (>= low 0) (<= high #xffffffff)) :unsigned-32-bit-vector) ((and (>= low 0) (<= high #xffffffffffffffff)) :unsigned-64-bit-vector) ((and (>= low -128) (<= high 127)) :signed-8-bit-vector) ((and (>= low -32768) (<= high 32767)) :signed-16-bit-vector) ((and (>= low (ash -1 31)) (<= high (1- (ash 1 31)))) :signed-32-bit-vector) ((and (>= low target-most-negative-fixnum) (<= high target-most-positive-fixnum)) :fixnum-vector) ((and (>= low (ash -1 63)) (<= high (1- (ash 1 63)))) :signed-64-bit-vector) (t :simple-vector)))) (float (case (ccl::numeric-ctype-format element-type) ((double-float long-float) :double-float-vector) ((single-float short-float) :single-float-vector) (t :simple-vector))) (t :simple-vector)))) (ccl::unknown-ctype) (ccl::named-ctype (if (eq element-type ccl::*universal-type*) :simple-vector)) (t))))) (defun ppc64-misc-byte-count (subtag element-count) (declare (fixnum subtag)) (if (= lowtag-nodeheader (logand subtag lowtagmask)) (ash element-count 3) (case (logand subtag fulltagmask) (#.ivector-class-64-bit (ash element-count 3)) (#.ivector-class-32-bit (ash element-count 2)) (#.ivector-class-8-bit element-count) (t (if (= subtag subtag-bit-vector) (ash (+ 7 element-count) -3) (ash element-count 1)))))) (defparameter *ppc64-target-arch* (arch::make-target-arch :name :ppc64 :lisp-node-size 8 :nil-value canonical-nil-value :fixnum-shift fixnumshift :most-positive-fixnum (1- (ash 1 (1- (- 64 fixnumshift)))) :most-negative-fixnum (- (ash 1 (1- (- 64 fixnumshift)))) :misc-data-offset misc-data-offset :misc-dfloat-offset misc-dfloat-offset :nbits-in-word 64 :ntagbits 4 :nlisptagbits 3 :uvector-subtags *ppc64-target-uvector-subtags* :max-64-bit-constant-index max-64-bit-constant-index :max-32-bit-constant-index max-32-bit-constant-index :max-16-bit-constant-index max-16-bit-constant-index :max-8-bit-constant-index max-8-bit-constant-index :max-1-bit-constant-index max-1-bit-constant-index :word-shift 3 :code-vector-prefix '(#$"CODE") :gvector-types '(:ratio :complex :symbol :function :catch-frame :struct :istruct :pool :population :hash-vector :package :value-cell :instance :lock :slot-vector :simple-vector) :1-bit-ivector-types '(:bit-vector) :8-bit-ivector-types '(:signed-8-bit-vector :unsigned-8-bit-vector) :16-bit-ivector-types '(:signed-16-bit-vector :unsigned-16-bit-vector) :32-bit-ivector-types '(:signed-32-bit-vector :unsigned-32-bit-vector :single-float-vector :double-float :bignum :simple-string) :64-bit-ivector-types '(:double-float-vector :unsigned-64-bit-vector :signed-64-bit-vector :fixnum-vector) :array-type-name-from-ctype-function #'ppc64-array-type-name-from-ctype :package-name "PPC64" :t-offset t-offset :array-data-size-function #'ppc64-misc-byte-count :numeric-type-name-to-typecode-function #'(lambda (type-name) (ecase type-name (fixnum tag-fixnum) (bignum subtag-bignum) ((short-float single-float) subtag-single-float) ((long-float double-float) subtag-double-float) (ratio subtag-ratio) (complex subtag-complex))) :subprims-base ppc::*ppc-subprims-base* :subprims-shift ppc::*ppc-subprims-shift* :subprims-table ppc::*ppc-subprims* :primitive->subprims `(((0 . 23) . ,(ccl::%subprim-name->offset '.SPbuiltin-plus ppc::*ppc-subprims*))) :unbound-marker-value unbound-marker :slot-unbound-marker-value slot-unbound-marker :fixnum-tag tag-fixnum :single-float-tag subtag-single-float :single-float-tag-is-subtag nil :double-float-tag subtag-double-float :cons-tag fulltag-cons :null-tag subtag-symbol :symbol-tag subtag-symbol :symbol-tag-is-subtag t :function-tag subtag-function :function-tag-is-subtag t :big-endian t :misc-subtag-offset misc-subtag-offset :car-offset cons.car :cdr-offset cons.cdr :subtag-char subtag-character :charcode-shift charcode-shift :fulltagmask fulltagmask :fulltag-misc fulltag-misc :char-code-limit #x110000 )) (defmacro defppc64archmacro (name lambda-list &body body) `(arch::defarchmacro :ppc64 ,name ,lambda-list ,@body)) (defppc64archmacro ccl::%make-sfloat () (error "~s shouldn't be used in code targeting :PPC64" 'ccl::%make-sfloat)) (defppc64archmacro ccl::%make-dfloat () `(ccl::%alloc-misc ppc64::double-float.element-count ppc64::subtag-double-float)) (defppc64archmacro ccl::%numerator (x) `(ccl::%svref ,x ppc64::ratio.numer-cell)) (defppc64archmacro ccl::%denominator (x) `(ccl::%svref ,x ppc64::ratio.denom-cell)) (defppc64archmacro ccl::%realpart (x) `(ccl::%svref ,x ppc64::complex.realpart-cell)) (defppc64archmacro ccl::%imagpart (x) `(ccl::%svref ,x ppc64::complex.imagpart-cell)) (defppc64archmacro ccl::%get-single-float-from-double-ptr (ptr offset) `(ccl::%double-float->short-float (ccl::%get-double-float ,ptr ,offset))) (defppc64archmacro ccl::codevec-header-p (word) `(eql ,word #$"CODE")) (defppc64archmacro ccl::immediate-p-macro (thing) (let* ((tag (gensym))) `(let* ((,tag (ccl::lisptag ,thing))) (declare (fixnum ,tag)) (or (= ,tag ppc64::tag-fixnum) (= (logand ,tag ppc64::lowtagmask) ppc64::lowtag-imm))))) (defppc64archmacro ccl::hashed-by-identity (thing) (let* ((typecode (gensym))) `(let* ((,typecode (ccl::typecode ,thing))) (declare (fixnum ,typecode)) (or (= ,typecode ppc64::tag-fixnum) (= (logand ,typecode ppc64::lowtagmask) ppc64::lowtag-imm) (= ,typecode ppc64::subtag-symbol) (= ,typecode ppc64::subtag-instance))))) (defppc64archmacro ccl::%get-kernel-global (name) `(ccl::%fixnum-ref 0 (+ ,(ccl::target-nil-value) ,(%kernel-global (if (ccl::quoted-form-p name) (cadr name) name))))) (defppc64archmacro ccl::%get-kernel-global-ptr (name dest) `(ccl::%setf-macptr ,dest (ccl::%fixnum-ref-macptr 0 (+ ,(ccl::target-nil-value) ,(%kernel-global (if (ccl::quoted-form-p name) (cadr name) name)))))) (defppc64archmacro ccl::%target-kernel-global (name) `(ppc64::%kernel-global ,name)) (defppc64archmacro ccl::lfun-vector (fn) fn) (defppc64archmacro ccl::lfun-vector-lfun (lfv) lfv) (defppc64archmacro ccl::area-code () area.code) (defppc64archmacro ccl::area-succ () area.succ) (defppc64archmacro ccl::nth-immediate (f i) `(ccl::%svref ,f ,i)) (defppc64archmacro ccl::set-nth-immediate (f i new) `(setf (ccl::%svref ,f ,i) ,new)) (defppc64archmacro ccl::symptr->symvector (s) s) (defppc64archmacro ccl::symvector->symptr (s) s) (defppc64archmacro ccl::function-to-function-vector (f) f) (defppc64archmacro ccl::function-vector-to-function (v) v) (defppc64archmacro ccl::with-ffcall-results ((buf) &body body) (let* ((size (+ (* 8 8) (* 13 8)))) `(ccl::%stack-block ((,buf ,size)) ,@body))) (defconstant arg-check-trap-pc-limit 8) (defconstant fasl-version #x60) (defconstant fasl-max-version #x60) (defconstant fasl-min-version #x60) (defparameter *image-abi-version* 1039) (provide "PPC64-ARCH")
407db38d7fe5753e98f9e5ddbf639840bfafb1525c8ee1cc9a70e47e1849ded6
acl2/acl2
allegro-acl2-trace.lisp
ACL2 Version 8.5 -- A Computational Logic for Applicative Common Lisp Copyright ( C ) 2023 , Regents of the University of Texas This version of ACL2 is a descendent of ACL2 Version 1.9 , Copyright ( C ) 1997 Computational Logic , Inc. See the documentation topic NOTE-2 - 0 . ; This program is free software; you can redistribute it and/or modify ; it under the terms of the LICENSE file distributed with ACL2. ; 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 ; LICENSE for more details. This file originally written by : ; email: Department of Computer Science University of Texas at Austin Austin , TX 78712 U.S.A. Written by : and J Strother Moore email : and Department of Computer Science University of Texas at Austin Austin , TX 78712 U.S.A. ; We don't intend this file to be compiled. ; TRACE stuff Allegro 's trace facilities are somewhat limited . However it does have a function , advise , which is sufficiently general to allow it to imitate GCL 's trace facilities as provided within ACL2 . See 's documentation for ; information on advise and unadvise. We put over into old - trace the macro for trace that comes with Allegro . ; Thus one can type (old-trace foo) and get the effect that (trace ; foo) would have previously provided. We do not guarantee that using ; old-trace works well with trace$, however. (cond ((null (macro-function 'old-trace)) (setf (macro-function 'old-trace) (macro-function 'trace)))) (cond ((null (macro-function 'old-untrace)) (setf (macro-function 'old-untrace) (macro-function 'untrace)))) ; The variables *trace-arglist* and *trace-values* will contain the ; cleaned up arglist and values of a traced function. The alist ; *trace-sublis* allows one to refer to these variables by more ; common names. (defvar *trace-arglist*) (defvar *trace-values*) (defconst *trace-sublis* '((values . *trace-values*) (si::values . *trace-values*) (arglist . *trace-arglist*) (si::arglist . *trace-arglist*))) ; What I am trying to do: Trace is called with a list of functions to be traced . Each element of ; this list can be; ; (Let foo be defined in common lisp but not in ACL2, and ; bar be defined within ACL2.) 1 . the name of a non - acl2 function --- foo , 2 . the name of an acl2 function --- bar , 3 . a list whose only element is the name of a non - acl2 function --- ( foo ) , 4 . a list whose only element is the name of an acl2 function --- ( bar ) , 5 . a list whose car is the name of a non - acl2 function and whose ; cdr may contain the keywords :entry and :exit, each of which ; are followed by a function whose value will be printed upon ; entry and exit respectively of the function being traced --- ; (foo :entry (list (list 'arg-one (car si::arglist)) ( list ' arg - two ( nth 1 si::arglist ) ) ) ) ) , 6 . a list whose car is the name of an acl2 function and whose ; cdr may contain the keywords :entry and :exit, each of which ; are followed by a function whose value will be printed upon ; entry and exit respectively of the function being traced --- ; (bar :entry si::arglist : exit ( if ( eql ( nth 1 si::arglist ) ( nth 0 values ) ) ; 'FAILED ( pretty - print - arg ( nth 1 values ) ) ) ) ; In trace - pre - process we generate a new list as follows , where * 1*bar denotes ( * 1 * -symbol bar ) . 1 . replacing foo with ( foo foo ) , 2 . replacing bar with ( bar bar ) & adding ( * 1*bar bar ) , 3 , replacing ( foo ... ) with ( foo foo ... ) 4 . replacing ( bar ... ) with ( bar bar ... ) & adding ( ( * 1*bar ... ) ( bar ... ) ) . ; ; In trace-process we generate suitable calls of advise and unadvise. ; ; Unless explicitly overridden by the :entry or :exit keywords, ; <entry trace-instructions> and <exit trace-instructions> print the ; arguments and returned values respectively. A minor amount of ; cleaning up is done, such as printing |*STATE*| instead of the ; entire state if it is one of the arguments or values. (defun trace-pre-process (lst) (let ((new-lst nil)) (dolist (x lst new-lst) (let ((sym (cond ((symbolp x) x) ((and (consp x) (symbolp (car x))) (car x)) (t (interface-er "Not a symbol or a cons of a symbol: ~s0" x))))) (if (function-symbolp sym (w *the-live-state*)) ; We have an ACL2 function. (cond ((symbolp x) (push (list (*1*-symbol x) x) new-lst) (push (list x x) new-lst)) (t (push (list* (*1*-symbol (car x)) (car x) (cdr x)) new-lst) (push (list* (car x) (car x) (cdr x)) new-lst))) ; We do not have an ACL2 function. (if (fboundp sym) (if (symbolp x) (push (list x x) new-lst) (push (list* (car x) (car x) (cdr x)) new-lst)) (interface-er "~s0 is not a bound function symbol." sym))))))) (defun trace-entry-rec (name l entry evisc-tuple) ; We construct the (excl:advise <fn-name> :before ...) form that performs the ; tracing on entry. (cond ((null l) `(excl:advise ,name :before nil nil (progn (setq *trace-arglist* si::arglist) (custom-trace-ppr :in (cons ',name (trace-hide-world-and-state ,(if entry (sublis *trace-sublis* entry) '*trace-arglist*))) ,@(and evisc-tuple (list evisc-tuple)))))) ((eq (car l) :entry) (trace-entry-rec name (cdr l) (cadr l) evisc-tuple)) ((eq (car l) :evisc-tuple) (trace-entry-rec name (cdr l) entry (cadr l))) (t (trace-entry-rec name (cdr l) entry evisc-tuple)))) (defun trace-entry (name l) (trace-entry-rec name l nil nil)) These next two functions were blindly copied from akcl-acl2-trace.lisp (defun trace-values (name) (declare (ignore name)) 'values) (defun trace-exit-rec (name original-name l state exit evisc-tuple) ; We construct the (excl:advise <fn-name> :after ...) form that performs the ; tracing on entry. (cond ((null l) (cond ((null exit) `(excl:advise ,name :after nil nil (progn (setq *trace-values* (trace-hide-world-and-state ,(trace-values original-name))) ,(protect-mv `(custom-trace-ppr :out (cons ',name *trace-values*) ,@(and evisc-tuple (list evisc-tuple))) (trace-multiplicity original-name state))))) (t (let ((multiplicity (trace-multiplicity original-name state))) `(excl:advise ,name :after nil nil (progn ,(protect-mv `(progn (setq *trace-values* (trace-hide-world-and-state ,(trace-values original-name))) (setq *trace-arglist* (trace-hide-world-and-state si::arglist))) multiplicity) ,(protect-mv `(custom-trace-ppr :out (cons ',name ,(sublis *trace-sublis* exit)) ,@(and evisc-tuple (list evisc-tuple))) multiplicity))))))) ((eq (car l) :exit) (trace-exit-rec name original-name (cdr l) state (cadr l) evisc-tuple)) ((eq (car l) :evisc-tuple) (trace-exit-rec name original-name (cdr l) state exit (cadr l))) (t (trace-exit-rec name original-name (cdr l) state exit evisc-tuple)))) (defun trace-exit (name original-name l) (trace-exit-rec name original-name l *the-live-state* nil nil)) (defun traced-fns-lst (lst) (list 'QUOTE (mapcar #'car lst))) (defun trace-process (lst) ; We perform a little error checking, and gather together all the (excl:advise ; ...) functions. (let ((new-lst (list (traced-fns-lst lst)))) ; for the returned value (dolist (x lst new-lst) (cond ((member :cond (cddr x)) (interface-er "The use of :cond is not supported in ~ Allegro.")) ((member :break (cddr x)) (interface-er "The use of :break is not supported in ~ Allegro. However, you can use either ~ (~s0 :entry (break$)) or (~s0 :exit (break$)). ~ See any Lisp documentation for more on ~ break and its options." (car x))) (t (push (trace-exit (car x) (cadr x) (cddr x)) new-lst) (push (trace-entry (car x) (cddr x)) new-lst) (push `(excl:unadvise ,(car x)) new-lst)))))) (excl:without-package-locks (defmacro trace (&rest fns) (if fns (cons 'progn (trace-process (trace-pre-process fns))) '(excl::advised-functions)))) (excl:without-package-locks (defmacro untrace (&rest fns) (if (null fns) '(prog1 (excl::advised-functions) (excl:unadvise)) (cons 'progn (let ((ans nil)) (dolist (fn fns ans) (push `(excl:unadvise ,fn) ans) (push `(excl:unadvise ,(*1*-symbol fn)) ans)))))))
null
https://raw.githubusercontent.com/acl2/acl2/65a46d5c1128cbecb9903bfee4192bb5daf7c036/allegro-acl2-trace.lisp
lisp
This program is free software; you can redistribute it and/or modify it under the terms of the LICENSE file distributed with ACL2. 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 LICENSE for more details. email: We don't intend this file to be compiled. TRACE stuff information on advise and unadvise. Thus one can type (old-trace foo) and get the effect that (trace foo) would have previously provided. We do not guarantee that using old-trace works well with trace$, however. The variables *trace-arglist* and *trace-values* will contain the cleaned up arglist and values of a traced function. The alist *trace-sublis* allows one to refer to these variables by more common names. What I am trying to do: this list can be; (Let foo be defined in common lisp but not in ACL2, and bar be defined within ACL2.) cdr may contain the keywords :entry and :exit, each of which are followed by a function whose value will be printed upon entry and exit respectively of the function being traced --- (foo :entry (list (list 'arg-one (car si::arglist)) cdr may contain the keywords :entry and :exit, each of which are followed by a function whose value will be printed upon entry and exit respectively of the function being traced --- (bar :entry si::arglist 'FAILED In trace-process we generate suitable calls of advise and unadvise. Unless explicitly overridden by the :entry or :exit keywords, <entry trace-instructions> and <exit trace-instructions> print the arguments and returned values respectively. A minor amount of cleaning up is done, such as printing |*STATE*| instead of the entire state if it is one of the arguments or values. We have an ACL2 function. We do not have an ACL2 function. We construct the (excl:advise <fn-name> :before ...) form that performs the tracing on entry. We construct the (excl:advise <fn-name> :after ...) form that performs the tracing on entry. We perform a little error checking, and gather together all the (excl:advise ...) functions. for the returned value
ACL2 Version 8.5 -- A Computational Logic for Applicative Common Lisp Copyright ( C ) 2023 , Regents of the University of Texas This version of ACL2 is a descendent of ACL2 Version 1.9 , Copyright ( C ) 1997 Computational Logic , Inc. See the documentation topic NOTE-2 - 0 . This file originally written by : Department of Computer Science University of Texas at Austin Austin , TX 78712 U.S.A. Written by : and J Strother Moore email : and Department of Computer Science University of Texas at Austin Austin , TX 78712 U.S.A. Allegro 's trace facilities are somewhat limited . However it does have a function , advise , which is sufficiently general to allow it to imitate GCL 's trace facilities as provided within ACL2 . See 's documentation for We put over into old - trace the macro for trace that comes with Allegro . (cond ((null (macro-function 'old-trace)) (setf (macro-function 'old-trace) (macro-function 'trace)))) (cond ((null (macro-function 'old-untrace)) (setf (macro-function 'old-untrace) (macro-function 'untrace)))) (defvar *trace-arglist*) (defvar *trace-values*) (defconst *trace-sublis* '((values . *trace-values*) (si::values . *trace-values*) (arglist . *trace-arglist*) (si::arglist . *trace-arglist*))) Trace is called with a list of functions to be traced . Each element of 1 . the name of a non - acl2 function --- foo , 2 . the name of an acl2 function --- bar , 3 . a list whose only element is the name of a non - acl2 function --- ( foo ) , 4 . a list whose only element is the name of an acl2 function --- ( bar ) , 5 . a list whose car is the name of a non - acl2 function and whose ( list ' arg - two ( nth 1 si::arglist ) ) ) ) ) , 6 . a list whose car is the name of an acl2 function and whose : exit ( if ( eql ( nth 1 si::arglist ) ( nth 0 values ) ) ( pretty - print - arg ( nth 1 values ) ) ) ) In trace - pre - process we generate a new list as follows , where * 1*bar denotes ( * 1 * -symbol bar ) . 1 . replacing foo with ( foo foo ) , 2 . replacing bar with ( bar bar ) & adding ( * 1*bar bar ) , 3 , replacing ( foo ... ) with ( foo foo ... ) 4 . replacing ( bar ... ) with ( bar bar ... ) & adding ( ( * 1*bar ... ) ( bar ... ) ) . (defun trace-pre-process (lst) (let ((new-lst nil)) (dolist (x lst new-lst) (let ((sym (cond ((symbolp x) x) ((and (consp x) (symbolp (car x))) (car x)) (t (interface-er "Not a symbol or a cons of a symbol: ~s0" x))))) (if (function-symbolp sym (w *the-live-state*)) (cond ((symbolp x) (push (list (*1*-symbol x) x) new-lst) (push (list x x) new-lst)) (t (push (list* (*1*-symbol (car x)) (car x) (cdr x)) new-lst) (push (list* (car x) (car x) (cdr x)) new-lst))) (if (fboundp sym) (if (symbolp x) (push (list x x) new-lst) (push (list* (car x) (car x) (cdr x)) new-lst)) (interface-er "~s0 is not a bound function symbol." sym))))))) (defun trace-entry-rec (name l entry evisc-tuple) (cond ((null l) `(excl:advise ,name :before nil nil (progn (setq *trace-arglist* si::arglist) (custom-trace-ppr :in (cons ',name (trace-hide-world-and-state ,(if entry (sublis *trace-sublis* entry) '*trace-arglist*))) ,@(and evisc-tuple (list evisc-tuple)))))) ((eq (car l) :entry) (trace-entry-rec name (cdr l) (cadr l) evisc-tuple)) ((eq (car l) :evisc-tuple) (trace-entry-rec name (cdr l) entry (cadr l))) (t (trace-entry-rec name (cdr l) entry evisc-tuple)))) (defun trace-entry (name l) (trace-entry-rec name l nil nil)) These next two functions were blindly copied from akcl-acl2-trace.lisp (defun trace-values (name) (declare (ignore name)) 'values) (defun trace-exit-rec (name original-name l state exit evisc-tuple) (cond ((null l) (cond ((null exit) `(excl:advise ,name :after nil nil (progn (setq *trace-values* (trace-hide-world-and-state ,(trace-values original-name))) ,(protect-mv `(custom-trace-ppr :out (cons ',name *trace-values*) ,@(and evisc-tuple (list evisc-tuple))) (trace-multiplicity original-name state))))) (t (let ((multiplicity (trace-multiplicity original-name state))) `(excl:advise ,name :after nil nil (progn ,(protect-mv `(progn (setq *trace-values* (trace-hide-world-and-state ,(trace-values original-name))) (setq *trace-arglist* (trace-hide-world-and-state si::arglist))) multiplicity) ,(protect-mv `(custom-trace-ppr :out (cons ',name ,(sublis *trace-sublis* exit)) ,@(and evisc-tuple (list evisc-tuple))) multiplicity))))))) ((eq (car l) :exit) (trace-exit-rec name original-name (cdr l) state (cadr l) evisc-tuple)) ((eq (car l) :evisc-tuple) (trace-exit-rec name original-name (cdr l) state exit (cadr l))) (t (trace-exit-rec name original-name (cdr l) state exit evisc-tuple)))) (defun trace-exit (name original-name l) (trace-exit-rec name original-name l *the-live-state* nil nil)) (defun traced-fns-lst (lst) (list 'QUOTE (mapcar #'car lst))) (defun trace-process (lst) (dolist (x lst new-lst) (cond ((member :cond (cddr x)) (interface-er "The use of :cond is not supported in ~ Allegro.")) ((member :break (cddr x)) (interface-er "The use of :break is not supported in ~ Allegro. However, you can use either ~ (~s0 :entry (break$)) or (~s0 :exit (break$)). ~ See any Lisp documentation for more on ~ break and its options." (car x))) (t (push (trace-exit (car x) (cadr x) (cddr x)) new-lst) (push (trace-entry (car x) (cddr x)) new-lst) (push `(excl:unadvise ,(car x)) new-lst)))))) (excl:without-package-locks (defmacro trace (&rest fns) (if fns (cons 'progn (trace-process (trace-pre-process fns))) '(excl::advised-functions)))) (excl:without-package-locks (defmacro untrace (&rest fns) (if (null fns) '(prog1 (excl::advised-functions) (excl:unadvise)) (cons 'progn (let ((ans nil)) (dolist (fn fns ans) (push `(excl:unadvise ,fn) ans) (push `(excl:unadvise ,(*1*-symbol fn)) ans)))))))