_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
b430deed245b2e7402c74ecd7c9d4742bc5207513d17e0fa686bfbe27946adc2
RichiH/git-annex
V0.hs
git - annex v0 - > v1 upgrade support - - Copyright 2010 < > - - Licensed under the GNU GPL version 3 or higher . - - Copyright 2010 Joey Hess <> - - Licensed under the GNU GPL version 3 or higher. -} module Upgrade.V0 where import Annex.Common import Annex.Content import qualified Upgrade.V1 upgrade :: Annex Bool upgrade = do showAction "v0 to v1" -- do the reorganisation of the key files olddir <- fromRepo gitAnnexDir keys <- getKeysPresent0 olddir forM_ keys $ \k -> moveAnnex k $ olddir </> keyFile0 k -- update the symlinks to the key files No longer needed here ; V1.upgrade does the same thing Few people had v0 repos , so go the long way around from 0 - > 1 - > 2 Upgrade.V1.upgrade -- these stayed unchanged between v0 and v1 keyFile0 :: Key -> FilePath keyFile0 = Upgrade.V1.keyFile1 fileKey0 :: FilePath -> Key fileKey0 = Upgrade.V1.fileKey1 lookupFile0 :: FilePath -> Annex (Maybe (Key, Backend)) lookupFile0 = Upgrade.V1.lookupFile1 getKeysPresent0 :: FilePath -> Annex [Key] getKeysPresent0 dir = ifM (liftIO $ doesDirectoryExist dir) ( liftIO $ map fileKey0 <$> (filterM present =<< getDirectoryContents dir) , return [] ) where present d = do result <- tryIO $ getFileStatus $ dir ++ "/" ++ takeFileName d case result of Right s -> return $ isRegularFile s Left _ -> return False
null
https://raw.githubusercontent.com/RichiH/git-annex/bbcad2b0af8cd9264d0cb86e6ca126ae626171f3/Upgrade/V0.hs
haskell
do the reorganisation of the key files update the symlinks to the key files these stayed unchanged between v0 and v1
git - annex v0 - > v1 upgrade support - - Copyright 2010 < > - - Licensed under the GNU GPL version 3 or higher . - - Copyright 2010 Joey Hess <> - - Licensed under the GNU GPL version 3 or higher. -} module Upgrade.V0 where import Annex.Common import Annex.Content import qualified Upgrade.V1 upgrade :: Annex Bool upgrade = do showAction "v0 to v1" olddir <- fromRepo gitAnnexDir keys <- getKeysPresent0 olddir forM_ keys $ \k -> moveAnnex k $ olddir </> keyFile0 k No longer needed here ; V1.upgrade does the same thing Few people had v0 repos , so go the long way around from 0 - > 1 - > 2 Upgrade.V1.upgrade keyFile0 :: Key -> FilePath keyFile0 = Upgrade.V1.keyFile1 fileKey0 :: FilePath -> Key fileKey0 = Upgrade.V1.fileKey1 lookupFile0 :: FilePath -> Annex (Maybe (Key, Backend)) lookupFile0 = Upgrade.V1.lookupFile1 getKeysPresent0 :: FilePath -> Annex [Key] getKeysPresent0 dir = ifM (liftIO $ doesDirectoryExist dir) ( liftIO $ map fileKey0 <$> (filterM present =<< getDirectoryContents dir) , return [] ) where present d = do result <- tryIO $ getFileStatus $ dir ++ "/" ++ takeFileName d case result of Right s -> return $ isRegularFile s Left _ -> return False
36ce114f4b7b99e2c86c624fc8f0b1a0e87aa858c1859f7f84a4b439517ffbd9
nuprl/gradual-typing-performance
scheme.rkt
#lang racket/base (require "racket.rkt") (provide (all-from-out "racket.rkt"))
null
https://raw.githubusercontent.com/nuprl/gradual-typing-performance/35442b3221299a9cadba6810573007736b0d65d4/pre-benchmark/ecoop/scribble-lib/scribble/scheme.rkt
racket
#lang racket/base (require "racket.rkt") (provide (all-from-out "racket.rkt"))
2d3563cd56e2db8d7f7d3e5b737f2fc7acf773852a06e78cb9dbc0dae9e31351
Jaxan/nominal-lstar
RunningExample.hs
{-# language DeriveAnyClass #-} # language DeriveGeneric # {-# language TupleSections #-} module Examples.RunningExample where In this file we define the running example of the paper The language is L_n = { ww | w \in A^n } for any alphabet A. In terms of orbits , the minimal acceptor is quite large , but in terms of FO definable sets it is quite small . The language is L_n = { ww | w \in A^n } for any alphabet A. In terms of orbits, the minimal acceptor is quite large, but in terms of FO definable sets it is quite small. -} import NLambda hiding (alphabet) import Data.List (reverse) import GHC.Generics (Generic) import Prelude (Eq, Int, Ord, Show, ($), (-)) import qualified Prelude () data RunningExample a = Store [a] | Check [a] | Accept | Reject deriving (Eq, Ord, Show, Generic, NominalType, Contextual) runningExample :: NominalType a => Set a -> Int -> Automaton (RunningExample a) a runningExample alphabet 0 = automaton (fromList [Accept, Reject]) alphabet (map (Accept,,Reject) alphabet `union` map (Reject,,Reject) alphabet) (singleton Accept) (singleton Accept) runningExample alphabet depth = automaton (firstStates `union` secondStates `union` singleton Accept `union` singleton Reject) alphabet (unions [pairsWith storeTrans alphabet (iwords i) | i <- [0..depth-2]] `union` pairsWith betweenTrans alphabet (iwords (depth-1)) `union` unions [pairsWith checkGoodTrans alphabet (iwords i) | i <- [1..depth-1]] `union` unions [triplesWithFilter checkBadTrans alphabet alphabet (iwords i) | i <- [1..depth-1]] `union` map (\a -> (Check [a], a, Accept)) alphabet `union` pairsWithFilter (\a b -> maybeIf (a `neq` b) (Check [a], b, Reject)) alphabet alphabet `union` map (Accept,, Reject) alphabet `union` map (Reject,, Reject) alphabet) (singleton $ Store []) (singleton Accept) where -- these define the states firstStates = unions [map Store $ iwords i | i <- [0..depth-1]] secondStates = unions [map Check $ iwords i | i <- [1..depth]] iwords i = replicateSet i alphabet -- this is the general shape of an transition storeTrans a l = (Store l, a, Store (a:l)) betweenTrans a l = (Store l, a, Check (reverse (a:l))) checkGoodTrans a l = (Check (a:l), a, Check l) checkBadTrans a b l = maybeIf (a `neq` b) (Check (a:l), b, Reject)
null
https://raw.githubusercontent.com/Jaxan/nominal-lstar/98f9c6e295583a7ea52e528665f50af855ad852b/src/Examples/RunningExample.hs
haskell
# language DeriveAnyClass # # language TupleSections # these define the states this is the general shape of an transition
# language DeriveGeneric # module Examples.RunningExample where In this file we define the running example of the paper The language is L_n = { ww | w \in A^n } for any alphabet A. In terms of orbits , the minimal acceptor is quite large , but in terms of FO definable sets it is quite small . The language is L_n = { ww | w \in A^n } for any alphabet A. In terms of orbits, the minimal acceptor is quite large, but in terms of FO definable sets it is quite small. -} import NLambda hiding (alphabet) import Data.List (reverse) import GHC.Generics (Generic) import Prelude (Eq, Int, Ord, Show, ($), (-)) import qualified Prelude () data RunningExample a = Store [a] | Check [a] | Accept | Reject deriving (Eq, Ord, Show, Generic, NominalType, Contextual) runningExample :: NominalType a => Set a -> Int -> Automaton (RunningExample a) a runningExample alphabet 0 = automaton (fromList [Accept, Reject]) alphabet (map (Accept,,Reject) alphabet `union` map (Reject,,Reject) alphabet) (singleton Accept) (singleton Accept) runningExample alphabet depth = automaton (firstStates `union` secondStates `union` singleton Accept `union` singleton Reject) alphabet (unions [pairsWith storeTrans alphabet (iwords i) | i <- [0..depth-2]] `union` pairsWith betweenTrans alphabet (iwords (depth-1)) `union` unions [pairsWith checkGoodTrans alphabet (iwords i) | i <- [1..depth-1]] `union` unions [triplesWithFilter checkBadTrans alphabet alphabet (iwords i) | i <- [1..depth-1]] `union` map (\a -> (Check [a], a, Accept)) alphabet `union` pairsWithFilter (\a b -> maybeIf (a `neq` b) (Check [a], b, Reject)) alphabet alphabet `union` map (Accept,, Reject) alphabet `union` map (Reject,, Reject) alphabet) (singleton $ Store []) (singleton Accept) where firstStates = unions [map Store $ iwords i | i <- [0..depth-1]] secondStates = unions [map Check $ iwords i | i <- [1..depth]] iwords i = replicateSet i alphabet storeTrans a l = (Store l, a, Store (a:l)) betweenTrans a l = (Store l, a, Check (reverse (a:l))) checkGoodTrans a l = (Check (a:l), a, Check l) checkBadTrans a b l = maybeIf (a `neq` b) (Check (a:l), b, Reject)
a7e4aa9e4d5ae857a3957352875ca1ff78891dbb1c0bb6aac6faa6f4becd1f81
zliu41/multi-containers
Multimap.hs
----------------------------------------------------------------------------- -- | -- Module : Data.Multimap Maintainer : < > -- -- Multimaps, where values behave like (non empty) lists. -- Multimaps whose values behave like sets are in " Data . Multimap . Set " . Multimaps whose values behave like maps ( i.e. , two - dimensional tables ) are in " Data . Multimap . Table " . -- The implementation is backed by a @'Map ' k ( ' NonEmpty ' a)@. The differences between @'Multimap ' k a@ and @'Map ' k ( ' NonEmpty ' a)@ include : -- -- * 'lookup' (or '!') returns a possibly empty list. Unlike regular maps, -- the '!' operator is total for multimaps. -- -- * Functions like 'map', 'adjust', 'traverse', etc., take functions on individual values ( e.g. , @a - > b@ ) as opposed to , e.g. , @'NonEmpty ' a - > ' NonEmpty ' b@. -- -- * 'union' and 'unions' concatenate the values when there are duplicate -- keys, rather than being left- or right-biased. -- -- * The 'difference' function computes list differences for values of -- keys that exist in both maps. -- -- * The 'size' function returns the total number of values for all keys in -- the multimap, not the number of distinct keys. The latter can be obtained by first getting the ' keysSet ' or first converting the multimap to -- a regular map via 'toMap'. -- -- In the following Big-O notations, unless otherwise noted, /n/ denotes the size of the multimap , denotes the number of distinct keys , and -- /m/ denotes the maximum number of values associated with a single key. module Data.Multimap ( -- * Multimap type Multimap -- * Construction , empty , singleton , fromMap , fromMap' -- ** From Unordered Lists , fromList -- * Insertion , insert * Deletion\/Update , delete , deleteWithValue , deleteOne , adjust , adjustWithKey , update , update' , updateWithKey , updateWithKey' , alter , alterWithKey -- * Query -- ** Lookup , lookup , (!) , member , notMember -- ** Size , null , notNull , size -- * Combine -- ** Union , union , unions -- ** Difference , difference -- * Traversal -- ** Map , map , mapWithKey , traverseWithKey , traverseMaybeWithKey -- ** Folds , foldr , foldl , foldrWithKey , foldlWithKey , foldMapWithKey -- ** Strict Folds , foldr' , foldl' , foldrWithKey' , foldlWithKey' -- * Conversion , elems , keys , assocs , keysSet -- ** Lists , toList -- ** Ordered lists , toAscList , toDescList , toAscListBF , toDescListBF -- ** Maps , toMap * * SetMultimaps , fromSetMultimapAsc , fromSetMultimapDesc , toSetMultimap -- * Filter , filter , filterWithKey , filterKey , filterM , filterWithKeyM , mapMaybe , mapMaybeWithKey , mapEither , mapEitherWithKey * , lookupMin , lookupMax , lookupLT , lookupGT , lookupLE , lookupGE ) where import Data.Multimap.Conversions import Data.Multimap.Internal import Data.Multimap.Set.Internal (SetMultimap) import Prelude hiding (filter, foldl, foldr, lookup, map, null) | Convert a t'Data . . Set . SetMultimap ' to a t'Data . Multimap . ' where the values of each key -- are in ascending order. -- -- > fromSetMultimapAsc (Data.Multimap.Set.fromList [(1,'a'),(1,'b'),(2,'c')]) === Data.Multimap.fromList [(1,'a'),(1,'b'),(2,'c')] fromSetMultimapAsc :: SetMultimap k a -> Multimap k a fromSetMultimapAsc = toMultimapAsc | Convert a t'Data . . Set . SetMultimap ' to a t'Data . Multimap . ' where the values of each key -- are in descending order. -- -- > fromSetMultimapDesc (Data.Multimap.Set.fromList [(1,'a'),(1,'b'),(2,'c')]) === Data.Multimap.fromList [(1,'b'),(1,'a'),(2,'c')] fromSetMultimapDesc :: SetMultimap k a -> Multimap k a fromSetMultimapDesc = toMultimapDesc
null
https://raw.githubusercontent.com/zliu41/multi-containers/3711e7c8640282d26e948e9074ed576a31138ed7/src/Data/Multimap.hs
haskell
--------------------------------------------------------------------------- | Module : Data.Multimap Multimaps, where values behave like (non empty) lists. * 'lookup' (or '!') returns a possibly empty list. Unlike regular maps, the '!' operator is total for multimaps. * Functions like 'map', 'adjust', 'traverse', etc., take functions on * 'union' and 'unions' concatenate the values when there are duplicate keys, rather than being left- or right-biased. * The 'difference' function computes list differences for values of keys that exist in both maps. * The 'size' function returns the total number of values for all keys in the multimap, not the number of distinct keys. The latter can be obtained a regular map via 'toMap'. In the following Big-O notations, unless otherwise noted, /n/ denotes /m/ denotes the maximum number of values associated with a single key. * Multimap type * Construction ** From Unordered Lists * Insertion * Query ** Lookup ** Size * Combine ** Union ** Difference * Traversal ** Map ** Folds ** Strict Folds * Conversion ** Lists ** Ordered lists ** Maps * Filter are in ascending order. > fromSetMultimapAsc (Data.Multimap.Set.fromList [(1,'a'),(1,'b'),(2,'c')]) === Data.Multimap.fromList [(1,'a'),(1,'b'),(2,'c')] are in descending order. > fromSetMultimapDesc (Data.Multimap.Set.fromList [(1,'a'),(1,'b'),(2,'c')]) === Data.Multimap.fromList [(1,'b'),(1,'a'),(2,'c')]
Maintainer : < > Multimaps whose values behave like sets are in " Data . Multimap . Set " . Multimaps whose values behave like maps ( i.e. , two - dimensional tables ) are in " Data . Multimap . Table " . The implementation is backed by a @'Map ' k ( ' NonEmpty ' a)@. The differences between @'Multimap ' k a@ and @'Map ' k ( ' NonEmpty ' a)@ include : individual values ( e.g. , @a - > b@ ) as opposed to , e.g. , @'NonEmpty ' a - > ' NonEmpty ' b@. by first getting the ' keysSet ' or first converting the multimap to the size of the multimap , denotes the number of distinct keys , and module Data.Multimap ( Multimap , empty , singleton , fromMap , fromMap' , fromList , insert * Deletion\/Update , delete , deleteWithValue , deleteOne , adjust , adjustWithKey , update , update' , updateWithKey , updateWithKey' , alter , alterWithKey , lookup , (!) , member , notMember , null , notNull , size , union , unions , difference , map , mapWithKey , traverseWithKey , traverseMaybeWithKey , foldr , foldl , foldrWithKey , foldlWithKey , foldMapWithKey , foldr' , foldl' , foldrWithKey' , foldlWithKey' , elems , keys , assocs , keysSet , toList , toAscList , toDescList , toAscListBF , toDescListBF , toMap * * SetMultimaps , fromSetMultimapAsc , fromSetMultimapDesc , toSetMultimap , filter , filterWithKey , filterKey , filterM , filterWithKeyM , mapMaybe , mapMaybeWithKey , mapEither , mapEitherWithKey * , lookupMin , lookupMax , lookupLT , lookupGT , lookupLE , lookupGE ) where import Data.Multimap.Conversions import Data.Multimap.Internal import Data.Multimap.Set.Internal (SetMultimap) import Prelude hiding (filter, foldl, foldr, lookup, map, null) | Convert a t'Data . . Set . SetMultimap ' to a t'Data . Multimap . ' where the values of each key fromSetMultimapAsc :: SetMultimap k a -> Multimap k a fromSetMultimapAsc = toMultimapAsc | Convert a t'Data . . Set . SetMultimap ' to a t'Data . Multimap . ' where the values of each key fromSetMultimapDesc :: SetMultimap k a -> Multimap k a fromSetMultimapDesc = toMultimapDesc
87a215c0bd5f31e7bb3d882d155bab7bcaebd7b78229495864cb348e8120fe17
rcherrueau/APE
car-modules.rkt
#lang reader "../lang.rkt" (import [Prelude "prelude.rkt"]) Figure 1 : Car example (class Engine (def (start -> Prelude.Unit) ???) (def (stop -> Prelude.Unit) ???)) (class Driver #;... ) (class Car ;; `engine` is bound to the context of Car instances (field [engine : rep/Engine]) ;; `driver` is bound to the world context (field [driver : world/Driver]) (def (init -> Θ/Car) ;; New engine as part of the Car instance (set-field! this engine (new rep/Engine)) this) (def (get-engine -> rep/Engine) engine) (def (set-engine! [e : rep/Engine] -> Prelude.Unit) (set-field! this engine e) (new Prelude.Unit)) (def (go -> Prelude.Unit) (send engine start))) (let ([bob : world/Driver (new Driver)] ;; No owner implicitly means world [car : Car (send (new Car) init)]) (set-field! car driver bob) (send car go) ;; ;; fails -- by giving `engine` the ownership type `rep`, then engine ;; ;; belongs to `car`. It is not accessible outside of this instance ;; ;; and therefore cannot be accessed by the root system as we try to ;; ;; do here. ;; (send (get-field car engine) stop) ; ; fails -- In contrast to Java , ownership type does not allow to ;; ;; access a private field from a method. ;; (send (send car get-engine) stop) ;; ;; fails -- The method `set-engine!` requires an argument that ;; ;; belongs to the `car` instance. However, the value of `e` belongs ;; ;; to the root system. ;; (let ([e : rep/Engine (new rep/Engine)]) ;; ;; fails, different rep ;; (send car set-engine! e)) )
null
https://raw.githubusercontent.com/rcherrueau/APE/8b5302709000bd043b64d46d55642acb34ce5ba7/racket/CPN98/examples/car-modules.rkt
racket
... ) `engine` is bound to the context of Car instances `driver` is bound to the world context New engine as part of the Car instance No owner implicitly means world ;; fails -- by giving `engine` the ownership type `rep`, then engine ;; belongs to `car`. It is not accessible outside of this instance ;; and therefore cannot be accessed by the root system as we try to ;; do here. (send (get-field car engine) stop) ; fails -- In contrast to Java , ownership type does not allow to ;; access a private field from a method. (send (send car get-engine) stop) ;; fails -- The method `set-engine!` requires an argument that ;; belongs to the `car` instance. However, the value of `e` belongs ;; to the root system. (let ([e : rep/Engine (new rep/Engine)]) ;; fails, different rep (send car set-engine! e))
#lang reader "../lang.rkt" (import [Prelude "prelude.rkt"]) Figure 1 : Car example (class Engine (def (start -> Prelude.Unit) ???) (def (stop -> Prelude.Unit) ???)) (class Car (field [engine : rep/Engine]) (field [driver : world/Driver]) (def (init -> Θ/Car) (set-field! this engine (new rep/Engine)) this) (def (get-engine -> rep/Engine) engine) (def (set-engine! [e : rep/Engine] -> Prelude.Unit) (set-field! this engine e) (new Prelude.Unit)) (def (go -> Prelude.Unit) (send engine start))) [car : Car (send (new Car) init)]) (set-field! car driver bob) (send car go) )
fda7db99b5c1d633f93bf7540555e7f82a4453b237ae01d26154635a3cf8373e
nponeccop/HNC
Inliner2.hs
# LANGUAGE GADTs , TypeFamilies , NoMonomorphismRestriction # module HN.Optimizer.Inliner2 (runB) where import Compiler.Hoopl import HN.Intermediate import HN.Optimizer.ExpressionRewriter import HN.Optimizer.Node import HN.Optimizer.Pass import HN.Optimizer.Utils Идея - использовать Hoopl как фреймворк , а не только " императивной лапши с " , описано в статье Инлайнинг : Вход : foo x = { bar x ' = ( incr x ' ) x ' bar ( add x x ) } : bar - > 1 Выход ( без учета других оптимизаций ): foo x = { x ' = add x x ( incr x ' ) x ' } Основа Hoopl - таблица меток , содержащая на метку . Попробую использовать таблицу символов , можно попробовать универсальные узлы без данных . В таком можно любой . Конструктору узла передаются два параметра : имя узла и имена узлов , к . Пока похоже , что составные блоки нужны только для императивных последовательностей инструкций --data Node0 e x where -- Node0 : : Label - > [ Label ] - > Node0 C С -- для блоков из одного СС - узла foo x = { bar x = incr x bar x } Основная идея обратного анализа : На вход подается FactBase ListFact , полученный в результате , функций , которые нужно инлайнить , указано Bot , а для функций , которые не нужно инлайнить - Top . для каждой функции возвращает [ ... ] . Соответственно : Top ` join ` [ ... ] = Top Bottom ` join ` [ ... ] = [ ... ] При перезаписи тело функции от места определения к параметры от места вызова к , которые меняются с . Идея - использовать Hoopl как фреймворк произвольных оптимизаторов графов, а не только "императивной лапши с Goto", как описано в статье Инлайнинг: Вход: foo x = { bar x' = mul (incr x') x' bar (add x x) } Факты: bar -> 1 Выход (без учета других оптимизаций): foo x = { x' = add x x mul (incr x') x' } Основа Hoopl - таблица меток, содержащая факты - результаты анализа перехода на метку. Попробую использовать таблицу символов, содержащую факты - результаты анализа Для начала можно попробовать универсальные узлы без данных. В таком виде можно представить любой граф. Конструктору узла передаются два параметра: имя узла и имена узлов, к которым идут дуги. Пока похоже, что составные блоки нужны только для императивных последовательностей инструкций --data Node0 e x where -- Node0 :: Label -> [Label] -> Node0 C С -- для блоков из одного СС-узла нет вспомогательных функций foo x = { bar x = incr x bar x } Основная идея обратного анализа: На вход подается FactBase ListFact, полученный в результате прямого анализа, в котором для функций, которые нужно инлайнить, указано Bot, а для функций, которые не нужно инлайнить - Top. Обратный анализатор для каждой функции возвращает [...]. Соответственно: Top `join` [...] = Top Bottom `join` [...] = [...] При перезаписи тело функции движется назад от места определения к месту вызова. Фактические параметры движутся вперёд от места вызова к формальным параметрам, которые меняются с ArgNode на LetNode. -} listLattice = addPoints' "ListFact" $ \_ (OldFact _) (NewFact new) -> error "Join" (SomeChange, PElem new) -- BACKWARD pass transferB :: Label -> DefinitionNode -> FactBase ListFact -> ListFact transferB ll dn @ (LetNode _ (Application (Atom l) _)) _ | l == ll = Top transferB ll dn _ = PElem dn -- Rewriting: inline definition - rewrite Exit nodes ("call sites") to -- remove references to the definition being inlined rewriteB :: DefinitionNode -> FactBase ListFact -> Maybe DefinitionNode rewriteB = rewriteNode WithChildren $ \f n -> case n of Constant _ -> Nothing Application _ _ -> Nothing Atom a -> case lookupFact a f of Nothing -> error "Lone.uncondLookupFact.Nothing" Just Bot -> error "Lone.rewriteExitL.Bot" Just (PElem (LetNode [] body)) -> Just body _ -> Nothing passBL whileLabel = BwdPass { bp_lattice = listLattice , bp_transfer = mkBTransfer $ transferExitB $ transferB whileLabel , bp_rewrite = pureBRewrite $ rewriteExitB rewriteB } runB :: Label -> Pass Int ListFact runB whileLabel = runPass (analyzeAndRewriteBwd $ passBL whileLabel) $ const . mapMap int2list where int2list 1 = Bot int2list _ = Top type ListFact = WithTopAndBot DefinitionNode
null
https://raw.githubusercontent.com/nponeccop/HNC/d8447009a04c56ae2cba4c7c179e39384085ea00/HN/Optimizer/Inliner2.hs
haskell
data Node0 e x where Node0 : : Label - > [ Label ] - > Node0 C С для блоков из одного СС - узла foo x = { data Node0 e x where Node0 :: Label -> [Label] -> Node0 C С для блоков из одного СС-узла нет вспомогательных функций BACKWARD pass Rewriting: inline definition - rewrite Exit nodes ("call sites") to remove references to the definition being inlined
# LANGUAGE GADTs , TypeFamilies , NoMonomorphismRestriction # module HN.Optimizer.Inliner2 (runB) where import Compiler.Hoopl import HN.Intermediate import HN.Optimizer.ExpressionRewriter import HN.Optimizer.Node import HN.Optimizer.Pass import HN.Optimizer.Utils Идея - использовать Hoopl как фреймворк , а не только " императивной лапши с " , описано в статье Инлайнинг : Вход : foo x = { bar x ' = ( incr x ' ) x ' bar ( add x x ) } : bar - > 1 Выход ( без учета других оптимизаций ): foo x = { x ' = add x x ( incr x ' ) x ' } Основа Hoopl - таблица меток , содержащая на метку . Попробую использовать таблицу символов , можно попробовать универсальные узлы без данных . В таком можно любой . Конструктору узла передаются два параметра : имя узла и имена узлов , к . Пока похоже , что составные блоки нужны только для императивных последовательностей инструкций bar x = incr x bar x } Основная идея обратного анализа : На вход подается FactBase ListFact , полученный в результате , функций , которые нужно инлайнить , указано Bot , а для функций , которые не нужно инлайнить - Top . для каждой функции возвращает [ ... ] . Соответственно : Top ` join ` [ ... ] = Top Bottom ` join ` [ ... ] = [ ... ] При перезаписи тело функции от места определения к параметры от места вызова к , которые меняются с . Идея - использовать Hoopl как фреймворк произвольных оптимизаторов графов, а не только "императивной лапши с Goto", как описано в статье Инлайнинг: Вход: foo x = { bar x' = mul (incr x') x' bar (add x x) } Факты: bar -> 1 Выход (без учета других оптимизаций): foo x = { x' = add x x mul (incr x') x' } Основа Hoopl - таблица меток, содержащая факты - результаты анализа перехода на метку. Попробую использовать таблицу символов, содержащую факты - результаты анализа Для начала можно попробовать универсальные узлы без данных. В таком виде можно представить любой граф. Конструктору узла передаются два параметра: имя узла и имена узлов, к которым идут дуги. Пока похоже, что составные блоки нужны только для императивных последовательностей инструкций foo x = { bar x = incr x bar x } Основная идея обратного анализа: На вход подается FactBase ListFact, полученный в результате прямого анализа, в котором для функций, которые нужно инлайнить, указано Bot, а для функций, которые не нужно инлайнить - Top. Обратный анализатор для каждой функции возвращает [...]. Соответственно: Top `join` [...] = Top Bottom `join` [...] = [...] При перезаписи тело функции движется назад от места определения к месту вызова. Фактические параметры движутся вперёд от места вызова к формальным параметрам, которые меняются с ArgNode на LetNode. -} listLattice = addPoints' "ListFact" $ \_ (OldFact _) (NewFact new) -> error "Join" (SomeChange, PElem new) transferB :: Label -> DefinitionNode -> FactBase ListFact -> ListFact transferB ll dn @ (LetNode _ (Application (Atom l) _)) _ | l == ll = Top transferB ll dn _ = PElem dn rewriteB :: DefinitionNode -> FactBase ListFact -> Maybe DefinitionNode rewriteB = rewriteNode WithChildren $ \f n -> case n of Constant _ -> Nothing Application _ _ -> Nothing Atom a -> case lookupFact a f of Nothing -> error "Lone.uncondLookupFact.Nothing" Just Bot -> error "Lone.rewriteExitL.Bot" Just (PElem (LetNode [] body)) -> Just body _ -> Nothing passBL whileLabel = BwdPass { bp_lattice = listLattice , bp_transfer = mkBTransfer $ transferExitB $ transferB whileLabel , bp_rewrite = pureBRewrite $ rewriteExitB rewriteB } runB :: Label -> Pass Int ListFact runB whileLabel = runPass (analyzeAndRewriteBwd $ passBL whileLabel) $ const . mapMap int2list where int2list 1 = Bot int2list _ = Top type ListFact = WithTopAndBot DefinitionNode
a842f752a9f05723fb517f747d19519563966163a2dca6c6f0a93f09d4e33420
vim-scripts/slimv.vim
swank-sbcl.lisp
;;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; swank-sbcl.lisp --- SLIME backend for SBCL . ;;; Created 2003 , < > ;;; ;;; This code has been placed in the Public Domain. All warranties are ;;; disclaimed. ;;; Requires the SB-INTROSPECT contrib. Administrivia (in-package :swank-backend) (eval-when (:compile-toplevel :load-toplevel :execute) (require 'sb-bsd-sockets) (require 'sb-introspect) (require 'sb-posix) (require 'sb-cltl2)) (declaim (optimize (debug 2) (sb-c::insert-step-conditions 0) (sb-c::insert-debug-catch 0) (sb-c::merge-tail-calls 2))) (import-from :sb-gray *gray-stream-symbols* :swank-backend) ;;; backwards compability tests (eval-when (:compile-toplevel :load-toplevel :execute) ;; Generate a form suitable for testing for stepper support (0.9.17) ;; with #+. (defun sbcl-with-new-stepper-p () (with-symbol 'enable-stepping 'sb-impl)) ;; Ditto for weak hash-tables (defun sbcl-with-weak-hash-tables () (with-symbol 'hash-table-weakness 'sb-ext)) And for xref support ( 1.0.1 ) (defun sbcl-with-xref-p () (with-symbol 'who-calls 'sb-introspect)) ... for restart - frame support ( 1.0.2 ) (defun sbcl-with-restart-frame () (with-symbol 'frame-has-debug-tag-p 'sb-debug))) ;;; swank-mop (import-swank-mop-symbols :sb-mop '(:slot-definition-documentation)) (defun swank-mop:slot-definition-documentation (slot) (sb-pcl::documentation slot t)) Connection info (defimplementation lisp-implementation-type-name () "sbcl") ;; Declare return type explicitly to shut up STYLE-WARNINGS about % SAP - ALIEN in ENABLE - SIGIO - ON - FD below . (declaim (ftype (function () (values (signed-byte 32) &optional)) getpid)) (defimplementation getpid () (sb-posix:getpid)) ;;; UTF8 (defimplementation string-to-utf8 (string) (sb-ext:string-to-octets string :external-format :utf8)) (defimplementation utf8-to-string (octets) (sb-ext:octets-to-string octets :external-format :utf8)) ;;; TCP Server (defimplementation preferred-communication-style () (cond fixme : when SBCL / win32 gains better select ( ) support , remove ;; this. ((member :sb-thread *features*) :spawn) ((member :win32 *features*) nil) (t :fd-handler))) (defun resolve-hostname (name) (car (sb-bsd-sockets:host-ent-addresses (sb-bsd-sockets:get-host-by-name name)))) (defimplementation create-socket (host port &key backlog) (let ((socket (make-instance 'sb-bsd-sockets:inet-socket :type :stream :protocol :tcp))) (setf (sb-bsd-sockets:sockopt-reuse-address socket) t) (sb-bsd-sockets:socket-bind socket (resolve-hostname host) port) (sb-bsd-sockets:socket-listen socket (or backlog 5)) socket)) (defimplementation local-port (socket) (nth-value 1 (sb-bsd-sockets:socket-name socket))) (defimplementation close-socket (socket) (sb-sys:invalidate-descriptor (socket-fd socket)) (sb-bsd-sockets:socket-close socket)) (defimplementation accept-connection (socket &key external-format buffering timeout) (declare (ignore timeout)) (make-socket-io-stream (accept socket) external-format (ecase buffering ((t :full) :full) ((nil :none) :none) ((:line) :line)))) #-win32 (defimplementation install-sigint-handler (function) (sb-sys:enable-interrupt sb-unix:sigint (lambda (&rest args) (declare (ignore args)) (sb-sys:invoke-interruption (lambda () (sb-sys:with-interrupts (funcall function))))))) (defvar *sigio-handlers* '() "List of (key . fn) pairs to be called on SIGIO.") (defun sigio-handler (signal code scp) (declare (ignore signal code scp)) (mapc (lambda (handler) (funcall (the function (cdr handler)))) *sigio-handlers*)) (defun set-sigio-handler () (sb-sys:enable-interrupt sb-unix:sigio (lambda (signal code scp) (sigio-handler signal code scp)))) (defun enable-sigio-on-fd (fd) (sb-posix::fcntl fd sb-posix::f-setfl sb-posix::o-async) (sb-posix::fcntl fd sb-posix::f-setown (getpid)) (values)) (defimplementation add-sigio-handler (socket fn) (set-sigio-handler) (let ((fd (socket-fd socket))) (enable-sigio-on-fd fd) (push (cons fd fn) *sigio-handlers*))) (defimplementation remove-sigio-handlers (socket) (let ((fd (socket-fd socket))) (setf *sigio-handlers* (delete fd *sigio-handlers* :key #'car)) (sb-sys:invalidate-descriptor fd)) (close socket)) (defimplementation add-fd-handler (socket fun) (let ((fd (socket-fd socket)) (handler nil)) (labels ((add () (setq handler (sb-sys:add-fd-handler fd :input #'run))) (run (fd) (sb-sys:remove-fd-handler handler) ; prevent recursion (unwind-protect (funcall fun) (when (sb-unix:unix-fstat fd) ; still open? (add))))) (add)))) (defimplementation remove-fd-handlers (socket) (sb-sys:invalidate-descriptor (socket-fd socket))) (defimplementation socket-fd (socket) (etypecase socket (fixnum socket) (sb-bsd-sockets:socket (sb-bsd-sockets:socket-file-descriptor socket)) (file-stream (sb-sys:fd-stream-fd socket)))) (defimplementation command-line-args () sb-ext:*posix-argv*) (defimplementation dup (fd) (sb-posix:dup fd)) (defvar *wait-for-input-called*) (defimplementation wait-for-input (streams &optional timeout) (assert (member timeout '(nil t))) (when (boundp '*wait-for-input-called*) (setq *wait-for-input-called* t)) (let ((*wait-for-input-called* nil)) (loop (let ((ready (remove-if-not #'input-ready-p streams))) (when ready (return ready))) (when (check-slime-interrupts) (return :interrupt)) (when *wait-for-input-called* (return :interrupt)) (when timeout (return nil)) (sleep 0.1)))) (defun fd-stream-input-buffer-empty-p (stream) (let ((buffer (sb-impl::fd-stream-ibuf stream))) (or (not buffer) (= (sb-impl::buffer-head buffer) (sb-impl::buffer-tail buffer))))) #-win32 (defun input-ready-p (stream) (or (not (fd-stream-input-buffer-empty-p stream)) #+#.(swank-backend:with-symbol 'fd-stream-fd-type 'sb-impl) (eq :regular (sb-impl::fd-stream-fd-type stream)) (not (sb-impl::sysread-may-block-p stream)))) #+win32 (progn (defun input-ready-p (stream) (or (not (fd-stream-input-buffer-empty-p stream)) (handle-listen (sockint::fd->handle (sb-impl::fd-stream-fd stream))))) (sb-alien:define-alien-routine ("WSACreateEvent" wsa-create-event) sb-win32:handle) (sb-alien:define-alien-routine ("WSACloseEvent" wsa-close-event) sb-alien:int (event sb-win32:handle)) (defconstant +fd-read+ #.(ash 1 0)) (defconstant +fd-close+ #.(ash 1 5)) (sb-alien:define-alien-routine ("WSAEventSelect" wsa-event-select) sb-alien:int (fd sb-alien:int) (handle sb-win32:handle) (mask sb-alien:long)) (sb-alien:load-shared-object "kernel32.dll") (sb-alien:define-alien-routine ("WaitForSingleObjectEx" wait-for-single-object-ex) sb-alien:int (event sb-win32:handle) (milliseconds sb-alien:long) (alertable sb-alien:int)) see : HANDLE - LISTEN (defun handle-listen (handle) (sb-alien:with-alien ((avail sb-win32:dword) (buf (array char #.sb-win32::input-record-size))) (unless (zerop (sb-win32:peek-named-pipe handle nil 0 nil (sb-alien:alien-sap (sb-alien:addr avail)) nil)) (return-from handle-listen (plusp avail))) (unless (zerop (sb-win32:peek-console-input handle (sb-alien:alien-sap buf) sb-win32::input-record-size (sb-alien:alien-sap (sb-alien:addr avail)))) (return-from handle-listen (plusp avail)))) (let ((event (wsa-create-event))) (wsa-event-select handle event (logior +fd-read+ +fd-close+)) (let ((val (wait-for-single-object-ex event 0 0))) (wsa-close-event event) (unless (= val -1) (return-from handle-listen (zerop val))))) nil) ) (defvar *external-format-to-coding-system* '((:iso-8859-1 "latin-1" "latin-1-unix" "iso-latin-1-unix" "iso-8859-1" "iso-8859-1-unix") (:utf-8 "utf-8" "utf-8-unix") (:euc-jp "euc-jp" "euc-jp-unix") (:us-ascii "us-ascii" "us-ascii-unix"))) C.f . R.M.Kreuter in < > on sbcl - general , 2008 - 08 - 22 . (defvar *physical-pathname-host* (pathname-host (user-homedir-pathname))) (defimplementation filename-to-pathname (filename) (sb-ext:parse-native-namestring filename *physical-pathname-host*)) (defimplementation find-external-format (coding-system) (car (rassoc-if (lambda (x) (member coding-system x :test #'equal)) *external-format-to-coding-system*))) (defun make-socket-io-stream (socket external-format buffering) (let ((args `(,@() :output t :input t :element-type ,(if external-format 'character '(unsigned-byte 8)) :buffering ,buffering ,@(cond ((and external-format (sb-int:featurep :sb-unicode)) `(:external-format ,external-format)) (t '())) :serve-events ,(eq :fd-handler : SWANK package is n't ;; available when backend is loaded. (symbol-value (intern "*COMMUNICATION-STYLE*" :swank))) SBCL < 1.0.42.43 does n't support : SERVE - EVENTS ;; argument. :allow-other-keys t))) (apply #'sb-bsd-sockets:socket-make-stream socket args))) (defun accept (socket) "Like socket-accept, but retry on EAGAIN." (loop (handler-case (return (sb-bsd-sockets:socket-accept socket)) (sb-bsd-sockets:interrupted-error ())))) Support for syntax SBCL 's source code is riddled with # ! reader macros . Also symbols ;;; containing `!' have special meaning. We have to work long and ;;; hard to be able to read the source. To deal with #! reader ;;; macros, we use a special readtable. The special symbols are ;;; converted by a condition handler. (defun feature-in-list-p (feature list) (etypecase feature (symbol (member feature list :test #'eq)) (cons (flet ((subfeature-in-list-p (subfeature) (feature-in-list-p subfeature list))) (ecase (first feature) (:or (some #'subfeature-in-list-p (rest feature))) (:and (every #'subfeature-in-list-p (rest feature))) (:not (destructuring-bind (e) (cdr feature) (not (subfeature-in-list-p e))))))))) (defun shebang-reader (stream sub-character infix-parameter) (declare (ignore sub-character)) (when infix-parameter (error "illegal read syntax: #~D!" infix-parameter)) (let ((next-char (read-char stream))) (unless (find next-char "+-") (error "illegal read syntax: #!~C" next-char)) ;; When test is not satisfied ;; FIXME: clearer if order of NOT-P and (NOT NOT-P) were reversed? then ;; would become "unless test is satisfied".. (when (let* ((*package* (find-package "KEYWORD")) (*read-suppress* nil) (not-p (char= next-char #\-)) (feature (read stream))) (if (feature-in-list-p feature *features*) not-p (not not-p))) ;; Read (and discard) a form from input. (let ((*read-suppress* t)) (read stream t nil t)))) (values)) (defvar *shebang-readtable* (let ((*readtable* (copy-readtable nil))) (set-dispatch-macro-character #\# #\! (lambda (s c n) (shebang-reader s c n)) *readtable*) *readtable*)) (defun shebang-readtable () *shebang-readtable*) (defun sbcl-package-p (package) (let ((name (package-name package))) (eql (mismatch "SB-" name) 3))) (defun sbcl-source-file-p (filename) (when filename (loop for (nil pattern) in (logical-pathname-translations "SYS") thereis (pathname-match-p filename pattern)))) (defun guess-readtable-for-filename (filename) (if (sbcl-source-file-p filename) (shebang-readtable) *readtable*)) (defvar *debootstrap-packages* t) (defun call-with-debootstrapping (fun) (handler-bind ((sb-int:bootstrap-package-not-found #'sb-int:debootstrap-package)) (funcall fun))) (defmacro with-debootstrapping (&body body) `(call-with-debootstrapping (lambda () ,@body))) (defimplementation call-with-syntax-hooks (fn) (cond ((and *debootstrap-packages* (sbcl-package-p *package*)) (with-debootstrapping (funcall fn))) (t (funcall fn)))) (defimplementation default-readtable-alist () (let ((readtable (shebang-readtable))) (loop for p in (remove-if-not #'sbcl-package-p (list-all-packages)) collect (cons (package-name p) readtable)))) Utilities #+#.(swank-backend:with-symbol 'function-lambda-list 'sb-introspect) (defimplementation arglist (fname) (sb-introspect:function-lambda-list fname)) #-#.(swank-backend:with-symbol 'function-lambda-list 'sb-introspect) (defimplementation arglist (fname) (sb-introspect:function-arglist fname)) (defimplementation function-name (f) (check-type f function) (sb-impl::%fun-name f)) (defmethod declaration-arglist ((decl-identifier (eql 'optimize))) (flet ((ensure-list (thing) (if (listp thing) thing (list thing)))) (let* ((flags (sb-cltl2:declaration-information decl-identifier))) (if flags Symbols are n't printed with package qualifiers , but the FLAGS would ;; have to be fully qualified when used inside a declaration. So we ;; strip those as long as there's no better way. (FIXME) `(&any ,@(remove-if-not #'(lambda (qualifier) (find-symbol (symbol-name (first qualifier)) :cl)) flags :key #'ensure-list)) (call-next-method))))) #+#.(swank-backend:with-symbol 'deftype-lambda-list 'sb-introspect) (defmethod type-specifier-arglist :around (typespec-operator) (multiple-value-bind (arglist foundp) (sb-introspect:deftype-lambda-list typespec-operator) (if foundp arglist (call-next-method)))) (defvar *buffer-name* nil) (defvar *buffer-tmpfile* nil) (defvar *buffer-offset*) (defvar *buffer-substring* nil) (defvar *previous-compiler-condition* nil "Used to detect duplicates.") (defun handle-notification-condition (condition) "Handle a condition caused by a compiler warning. This traps all compiler conditions at a lower-level than using C:*COMPILER-NOTIFICATION-FUNCTION*. The advantage is that we get to craft our own error messages, which can omit a lot of redundant information." (unless (or (eq condition *previous-compiler-condition*)) ;; First resignal warnings, so that outer handlers -- which may choose to ;; muffle this -- get a chance to run. (when (typep condition 'warning) (signal condition)) (setq *previous-compiler-condition* condition) (signal-compiler-condition (real-condition condition) (sb-c::find-error-context nil)))) (defun signal-compiler-condition (condition context) (signal (make-condition 'compiler-condition :original-condition condition :severity (etypecase condition (sb-ext:compiler-note :note) (sb-c:compiler-error :error) (reader-error :read-error) (error :error) #+#.(swank-backend:with-symbol redefinition-warning sb-kernel) (sb-kernel:redefinition-warning :redefinition) (style-warning :style-warning) (warning :warning)) :references (condition-references condition) :message (brief-compiler-message-for-emacs condition) :source-context (compiler-error-context context) :location (compiler-note-location condition context)))) (defun real-condition (condition) "Return the encapsulated condition or CONDITION itself." (typecase condition (sb-int:encapsulated-condition (sb-int:encapsulated-condition condition)) (t condition))) (defun condition-references (condition) (if (typep condition 'sb-int:reference-condition) (externalize-reference (sb-int:reference-condition-references condition)))) (defun compiler-note-location (condition context) (flet ((bailout () (return-from compiler-note-location (make-error-location "No error location available")))) (cond (context (locate-compiler-note (sb-c::compiler-error-context-file-name context) (compiler-source-path context) (sb-c::compiler-error-context-original-source context))) ((typep condition 'reader-error) (let* ((stream (stream-error-stream condition)) (file (pathname stream))) (unless (open-stream-p stream) (bailout)) (if (compiling-from-buffer-p file) ;; The stream position for e.g. "comma not inside backquote" ;; is at the character following the comma, :offset is 0-based, ;; hence the 1-. (make-location (list :buffer *buffer-name*) (list :offset *buffer-offset* (1- (file-position stream)))) (progn (assert (compiling-from-file-p file)) No 1- because : position is 1 - based . (make-location (list :file (namestring file)) (list :position (file-position stream))))))) (t (bailout))))) (defun compiling-from-buffer-p (filename) (and *buffer-name* ;; The following is to trigger COMPILING-FROM-GENERATED-CODE-P ;; in LOCATE-COMPILER-NOTE, and allows handling nested ;; compilation from eg. hitting C-C on (eval-when ... (require ..))). ;; ;; PROBE-FILE to handle tempfile directory being a symlink. (pathnamep filename) (let ((true1 (probe-file filename)) (true2 (probe-file *buffer-tmpfile*))) (and true1 (equal true1 true2))))) (defun compiling-from-file-p (filename) (and (pathnamep filename) (or (null *buffer-name*) (null *buffer-tmpfile*) (let ((true1 (probe-file filename)) (true2 (probe-file *buffer-tmpfile*))) (not (and true1 (equal true1 true2))))))) (defun compiling-from-generated-code-p (filename source) (and (eq filename :lisp) (stringp source))) (defun locate-compiler-note (file source-path source) (cond ((compiling-from-buffer-p file) (make-location (list :buffer *buffer-name*) (list :offset *buffer-offset* (source-path-string-position source-path *buffer-substring*)))) ((compiling-from-file-p file) (make-location (list :file (namestring file)) (list :position (1+ (source-path-file-position source-path file))))) ((compiling-from-generated-code-p file source) (make-location (list :source-form source) (list :position 1))) (t (error "unhandled case in compiler note ~S ~S ~S" file source-path source)))) (defun brief-compiler-message-for-emacs (condition) "Briefly describe a compiler error for Emacs. When Emacs presents the message it already has the source popped up and the source form highlighted. This makes much of the information in the error-context redundant." (let ((sb-int:*print-condition-references* nil)) (princ-to-string condition))) (defun compiler-error-context (error-context) "Describe a compiler error for Emacs including context information." (declare (type (or sb-c::compiler-error-context null) error-context)) (multiple-value-bind (enclosing source) (if error-context (values (sb-c::compiler-error-context-enclosing-source error-context) (sb-c::compiler-error-context-source error-context))) (and (or enclosing source) (format nil "~@[--> ~{~<~%--> ~1:;~A~> ~}~%~]~@[~{==>~%~A~%~}~]" enclosing source)))) (defun compiler-source-path (context) "Return the source-path for the current compiler error. Returns NIL if this cannot be determined by examining internal compiler state." (cond ((sb-c::node-p context) (reverse (sb-c::source-path-original-source (sb-c::node-source-path context)))) ((sb-c::compiler-error-context-p context) (reverse (sb-c::compiler-error-context-original-source-path context))))) (defimplementation call-with-compilation-hooks (function) (declare (type function function)) (handler-bind ;; N.B. Even though these handlers are called HANDLE-FOO they ;; actually decline, i.e. the signalling of the original ;; condition continues upward. ((sb-c:fatal-compiler-error #'handle-notification-condition) (sb-c:compiler-error #'handle-notification-condition) (sb-ext:compiler-note #'handle-notification-condition) (error #'handle-notification-condition) (warning #'handle-notification-condition)) (funcall function))) (defvar *trap-load-time-warnings* t) (defun compiler-policy (qualities) "Return compiler policy qualities present in the QUALITIES alist. QUALITIES is an alist with (quality . value)" #+#.(swank-backend:with-symbol 'restrict-compiler-policy 'sb-ext) (loop with policy = (sb-ext:restrict-compiler-policy) for (quality) in qualities collect (cons quality (or (cdr (assoc quality policy)) 0)))) (defun (setf compiler-policy) (policy) (declare (ignorable policy)) #+#.(swank-backend:with-symbol 'restrict-compiler-policy 'sb-ext) (loop for (qual . value) in policy do (sb-ext:restrict-compiler-policy qual value))) (defmacro with-compiler-policy (policy &body body) (let ((current-policy (gensym))) `(let ((,current-policy (compiler-policy ,policy))) (setf (compiler-policy) ,policy) (unwind-protect (progn ,@body) (setf (compiler-policy) ,current-policy))))) (defimplementation swank-compile-file (input-file output-file load-p external-format &key policy) (multiple-value-bind (output-file warnings-p failure-p) (with-compiler-policy policy (with-compilation-hooks () (compile-file input-file :output-file output-file :external-format external-format))) (values output-file warnings-p (or failure-p (when load-p ;; Cache the latest source file for definition-finding. (source-cache-get input-file (file-write-date input-file)) (not (load output-file))))))) ;;;; compile-string ;;; We copy the string to a temporary file in order to get adequate ;;; semantics for :COMPILE-TOPLEVEL and :LOAD-TOPLEVEL EVAL-WHEN forms ;;; which the previous approach using ;;; (compile nil `(lambda () ,(read-from-string string))) ;;; did not provide. (locally (declare (sb-ext:muffle-conditions sb-ext:compiler-note)) (sb-alien:define-alien-routine (#-win32 "tempnam" #+win32 "_tempnam" tempnam) sb-alien:c-string (dir sb-alien:c-string) (prefix sb-alien:c-string)) ) (defun temp-file-name () "Return a temporary file name to compile strings into." (tempnam nil nil)) (defimplementation swank-compile-string (string &key buffer position filename policy) (let ((*buffer-name* buffer) (*buffer-offset* position) (*buffer-substring* string) (*buffer-tmpfile* (temp-file-name))) (flet ((load-it (filename) (when filename (load filename))) (compile-it (cont) (with-compilation-hooks () (with-compilation-unit (:source-plist (list :emacs-buffer buffer :emacs-filename filename :emacs-string string :emacs-position position) :source-namestring filename :allow-other-keys t) (multiple-value-bind (output-file warningsp failurep) (compile-file *buffer-tmpfile*) (declare (ignore warningsp)) (unless failurep (funcall cont output-file))))))) (with-open-file (s *buffer-tmpfile* :direction :output :if-exists :error) (write-string string s)) (unwind-protect (with-compiler-policy policy (if *trap-load-time-warnings* (compile-it #'load-it) (load-it (compile-it #'identity)))) (ignore-errors (delete-file *buffer-tmpfile*) (delete-file (compile-file-pathname *buffer-tmpfile*))))))) ;;;; Definitions (defparameter *definition-types* '(:variable defvar :constant defconstant :type deftype :symbol-macro define-symbol-macro :macro defmacro :compiler-macro define-compiler-macro :function defun :generic-function defgeneric :method defmethod :setf-expander define-setf-expander :structure defstruct :condition define-condition :class defclass :method-combination define-method-combination :package defpackage :transform :deftransform :optimizer :defoptimizer :vop :define-vop :source-transform :define-source-transform) "Map SB-INTROSPECT definition type names to Slime-friendly forms") (defun definition-specifier (type name) "Return a pretty specifier for NAME representing a definition of type TYPE." (if (and (symbolp name) (eq type :function) (sb-int:info :function :ir1-convert name)) :def-ir1-translator (getf *definition-types* type))) (defun make-dspec (type name source-location) (let ((spec (definition-specifier type name)) (desc (sb-introspect::definition-source-description source-location))) (if (eq :define-vop spec) The first part of the VOP description is the name of the template ;; -- which is actually good information and often long. So elide the ;; original name in favor of making the interesting bit more visible. ;; The second part of the VOP description is the associated compiler note , or NIL -- which is quite uninteresting and confuses the eye when reading the actual ;; name which usually has a worthwhile postfix. So drop the note. (list spec (car desc)) (list* spec name desc)))) (defimplementation find-definitions (name) (loop for type in *definition-types* by #'cddr for defsrcs = (sb-introspect:find-definition-sources-by-name name type) append (loop for defsrc in defsrcs collect (list (make-dspec type name defsrc) (converting-errors-to-error-location (definition-source-for-emacs defsrc type name)))))) (defimplementation find-source-location (obj) (flet ((general-type-of (obj) (typecase obj (method :method) (generic-function :generic-function) (function :function) (structure-class :structure-class) (class :class) (method-combination :method-combination) (package :package) (condition :condition) (structure-object :structure-object) (standard-object :standard-object) (t :thing))) (to-string (obj) (typecase obj (package (princ-to-string obj)) ; Packages are possibly named entities. ((or structure-object standard-object condition) (with-output-to-string (s) (print-unreadable-object (obj s :type t :identity t)))) (t (princ-to-string obj))))) (converting-errors-to-error-location (let ((defsrc (sb-introspect:find-definition-source obj))) (definition-source-for-emacs defsrc (general-type-of obj) (to-string obj)))))) (defun categorize-definition-source (definition-source) (with-struct (sb-introspect::definition-source- pathname form-path character-offset plist) definition-source (cond ((getf plist :emacs-buffer) :buffer) ((and pathname (or form-path character-offset)) :file) (pathname :file-without-position) (t :invalid)))) (defun definition-source-for-emacs (definition-source type name) (with-struct (sb-introspect::definition-source- pathname form-path character-offset plist file-write-date) definition-source (ecase (categorize-definition-source definition-source) (:buffer (destructuring-bind (&key emacs-buffer emacs-position emacs-directory emacs-string &allow-other-keys) plist (let ((*readtable* (guess-readtable-for-filename emacs-directory))) (multiple-value-bind (start end) (if form-path (with-debootstrapping (source-path-string-position form-path emacs-string)) (values character-offset most-positive-fixnum)) (make-location `(:buffer ,emacs-buffer) `(:offset ,emacs-position ,start) `(:snippet ,(subseq emacs-string start (min end (+ start *source-snippet-size*))))))))) (:file (let* ((namestring (namestring (translate-logical-pathname pathname))) (pos (if form-path (source-file-position namestring file-write-date form-path) character-offset)) (snippet (source-hint-snippet namestring file-write-date pos))) (make-location `(:file ,namestring) ;; /file positions/ in Common Lisp start from 0 , buffer positions in Emacs start from 1 . `(:position ,(1+ pos)) `(:snippet ,snippet)))) (:file-without-position (make-location `(:file ,(namestring (translate-logical-pathname pathname))) '(:position 1) (when (eql type :function) `(:snippet ,(format nil "(defun ~a " (symbol-name name)))))) (:invalid (error "DEFINITION-SOURCE of ~A ~A did not contain ~ meaningful information." (string-downcase type) name))))) (defun source-file-position (filename write-date form-path) (let ((source (get-source-code filename write-date)) (*readtable* (guess-readtable-for-filename filename))) (with-debootstrapping (source-path-string-position form-path source)))) (defun source-hint-snippet (filename write-date position) (read-snippet-from-string (get-source-code filename write-date) position)) (defun function-source-location (function &optional name) (declare (type function function)) (definition-source-for-emacs (sb-introspect:find-definition-source function) :function (or name (function-name function)))) (defimplementation describe-symbol-for-emacs (symbol) "Return a plist describing SYMBOL. Return NIL if the symbol is unbound." (let ((result '())) (flet ((doc (kind) (or (documentation symbol kind) :not-documented)) (maybe-push (property value) (when value (setf result (list* property value result))))) (maybe-push :variable (multiple-value-bind (kind recorded-p) (sb-int:info :variable :kind symbol) (declare (ignore kind)) (if (or (boundp symbol) recorded-p) (doc 'variable)))) (when (fboundp symbol) (maybe-push (cond ((macro-function symbol) :macro) ((special-operator-p symbol) :special-operator) ((typep (fdefinition symbol) 'generic-function) :generic-function) (t :function)) (doc 'function))) (maybe-push :setf (if (or (sb-int:info :setf :inverse symbol) (sb-int:info :setf :expander symbol)) (doc 'setf))) (maybe-push :type (if (sb-int:info :type :kind symbol) (doc 'type))) result))) (defimplementation describe-definition (symbol type) (case type (:variable (describe symbol)) (:function (describe (symbol-function symbol))) (:setf (describe (or (sb-int:info :setf :inverse symbol) (sb-int:info :setf :expander symbol)))) (:class (describe (find-class symbol))) (:type (describe (sb-kernel:values-specifier-type symbol))))) #+#.(swank-backend::sbcl-with-xref-p) (progn (defmacro defxref (name &optional fn-name) `(defimplementation ,name (what) (sanitize-xrefs (mapcar #'source-location-for-xref-data (,(find-symbol (symbol-name (if fn-name fn-name name)) "SB-INTROSPECT") what))))) (defxref who-calls) (defxref who-binds) (defxref who-sets) (defxref who-references) (defxref who-macroexpands) #+#.(swank-backend:with-symbol 'who-specializes-directly 'sb-introspect) (defxref who-specializes who-specializes-directly)) (defun source-location-for-xref-data (xref-data) (destructuring-bind (name . defsrc) xref-data (list name (converting-errors-to-error-location (definition-source-for-emacs defsrc 'function name))))) (defimplementation list-callers (symbol) (let ((fn (fdefinition symbol))) (sanitize-xrefs (mapcar #'function-dspec (sb-introspect:find-function-callers fn))))) (defimplementation list-callees (symbol) (let ((fn (fdefinition symbol))) (sanitize-xrefs (mapcar #'function-dspec (sb-introspect:find-function-callees fn))))) (defun sanitize-xrefs (xrefs) (remove-duplicates (remove-if (lambda (f) (member f (ignored-xref-function-names))) (loop for entry in xrefs for name = (car entry) collect (if (and (consp name) (member (car name) '(sb-pcl::fast-method sb-pcl::slow-method sb-pcl::method))) (cons (cons 'defmethod (cdr name)) (cdr entry)) entry)) :key #'car) :test (lambda (a b) (and (eq (first a) (first b)) (equal (second a) (second b)))))) (defun ignored-xref-function-names () #-#.(swank-backend::sbcl-with-new-stepper-p) '(nil sb-c::step-form sb-c::step-values) #+#.(swank-backend::sbcl-with-new-stepper-p) '(nil)) (defun function-dspec (fn) "Describe where the function FN was defined. Return a list of the form (NAME LOCATION)." (let ((name (function-name fn))) (list name (converting-errors-to-error-location (function-source-location fn name))))) ;;; macroexpansion (defimplementation macroexpand-all (form) (let ((sb-walker:*walk-form-expand-macros-p* t)) (sb-walker:walk-form form))) ;;; Debugging Notice that SB - EXT:*INVOKE - DEBUGGER - HOOK * is slightly stronger ;;; than just a hook into BREAK. In particular, it'll make ;;; (LET ((*DEBUGGER-HOOK* NIL)) ..error..) drop into SLDB rather ;;; than the native debugger. That should probably be considered a ;;; feature. (defun make-invoke-debugger-hook (hook) (when hook #'(sb-int:named-lambda swank-invoke-debugger-hook (condition old-hook) (if *debugger-hook* nil ; decline, *DEBUGGER-HOOK* will be tried next. (funcall hook condition old-hook))))) (defun set-break-hook (hook) (setq sb-ext:*invoke-debugger-hook* (make-invoke-debugger-hook hook))) (defun call-with-break-hook (hook continuation) (let ((sb-ext:*invoke-debugger-hook* (make-invoke-debugger-hook hook))) (funcall continuation))) (defimplementation install-debugger-globally (function) (setq *debugger-hook* function) (set-break-hook function)) (defimplementation condition-extras (condition) (cond #+#.(swank-backend::sbcl-with-new-stepper-p) ((typep condition 'sb-impl::step-form-condition) `((:show-frame-source 0))) ((typep condition 'sb-int:reference-condition) (let ((refs (sb-int:reference-condition-references condition))) (if refs `((:references ,(externalize-reference refs)))))))) (defun externalize-reference (ref) (etypecase ref (null nil) (cons (cons (externalize-reference (car ref)) (externalize-reference (cdr ref)))) ((or string number) ref) (symbol (cond ((eq (symbol-package ref) (symbol-package :test)) ref) (t (symbol-name ref)))))) (defvar *sldb-stack-top*) (defimplementation call-with-debugging-environment (debugger-loop-fn) (declare (type function debugger-loop-fn)) (let* ((*sldb-stack-top* (if *debug-swank-backend* (sb-di:top-frame) (or sb-debug:*stack-top-hint* (sb-di:top-frame)))) (sb-debug:*stack-top-hint* nil)) (handler-bind ((sb-di:debug-condition (lambda (condition) (signal (make-condition 'sldb-condition :original-condition condition))))) (funcall debugger-loop-fn)))) #+#.(swank-backend::sbcl-with-new-stepper-p) (progn (defimplementation activate-stepping (frame) (declare (ignore frame)) (sb-impl::enable-stepping)) (defimplementation sldb-stepper-condition-p (condition) (typep condition 'sb-ext:step-form-condition)) (defimplementation sldb-step-into () (invoke-restart 'sb-ext:step-into)) (defimplementation sldb-step-next () (invoke-restart 'sb-ext:step-next)) (defimplementation sldb-step-out () (invoke-restart 'sb-ext:step-out))) (defimplementation call-with-debugger-hook (hook fun) (let ((*debugger-hook* hook) #+#.(swank-backend::sbcl-with-new-stepper-p) (sb-ext:*stepper-hook* (lambda (condition) (typecase condition (sb-ext:step-form-condition (let ((sb-debug:*stack-top-hint* (sb-di::find-stepped-frame))) (sb-impl::invoke-debugger condition))))))) (handler-bind (#+#.(swank-backend::sbcl-with-new-stepper-p) (sb-ext:step-condition #'sb-impl::invoke-stepper)) (call-with-break-hook hook fun)))) (defun nth-frame (index) (do ((frame *sldb-stack-top* (sb-di:frame-down frame)) (i index (1- i))) ((zerop i) frame))) (defimplementation compute-backtrace (start end) "Return a list of frames starting with frame number START and continuing to frame number END or, if END is nil, the last frame on the stack." (let ((end (or end most-positive-fixnum))) (loop for f = (nth-frame start) then (sb-di:frame-down f) for i from start below end while f collect f))) (defimplementation print-frame (frame stream) (sb-debug::print-frame-call frame stream)) (defimplementation frame-restartable-p (frame) #+#.(swank-backend::sbcl-with-restart-frame) (not (null (sb-debug:frame-has-debug-tag-p frame)))) (defimplementation frame-call (frame-number) (multiple-value-bind (name args) (sb-debug::frame-call (nth-frame frame-number)) (with-output-to-string (stream) (pprint-logical-block (stream nil :prefix "(" :suffix ")") (let ((*print-length* nil) (*print-level* nil)) (prin1 (sb-debug::ensure-printable-object name) stream)) (let ((args (sb-debug::ensure-printable-object args))) (if (listp args) (format stream "~{ ~_~S~}" args) (format stream " ~S" args))))))) ;;;; Code-location -> source-location translation ;;; If debug-block info is avaibale, we determine the file position of ;;; the source-path for a code-location. If the code was compiled with C - c C - c , we have to search the position in the source string . ;;; If there's no debug-block info, we return the (less precise) ;;; source-location of the corresponding function. (defun code-location-source-location (code-location) (let* ((dsource (sb-di:code-location-debug-source code-location)) (plist (sb-c::debug-source-plist dsource))) (if (getf plist :emacs-buffer) (emacs-buffer-source-location code-location plist) #+#.(swank-backend:with-symbol 'debug-source-from 'sb-di) (ecase (sb-di:debug-source-from dsource) (:file (file-source-location code-location)) (:lisp (lisp-source-location code-location))) #-#.(swank-backend:with-symbol 'debug-source-from 'sb-di) (if (sb-di:debug-source-namestring dsource) (file-source-location code-location) (lisp-source-location code-location))))) ;;; FIXME: The naming policy of source-location functions is a bit ;;; fuzzy: we have FUNCTION-SOURCE-LOCATION which returns the source - location for a function , and we also have FILE - SOURCE - LOCATION & co ;;; which returns the source location for a _code-location_. ;;; ;;; Maybe these should be named code-location-file-source-location, ;;; etc, turned into generic functions, or something. In the very ;;; least the names should indicate the main entry point vs. helper ;;; status. (defun file-source-location (code-location) (if (code-location-has-debug-block-info-p code-location) (source-file-source-location code-location) (fallback-source-location code-location))) (defun fallback-source-location (code-location) (let ((fun (code-location-debug-fun-fun code-location))) (cond (fun (function-source-location fun)) (t (error "Cannot find source location for: ~A " code-location))))) (defun lisp-source-location (code-location) (let ((source (prin1-to-string (sb-debug::code-location-source-form code-location 100)))) (make-location `(:source-form ,source) '(:position 1)))) (defun emacs-buffer-source-location (code-location plist) (if (code-location-has-debug-block-info-p code-location) (destructuring-bind (&key emacs-buffer emacs-position emacs-string &allow-other-keys) plist (let* ((pos (string-source-position code-location emacs-string)) (snipped (read-snippet-from-string emacs-string pos))) (make-location `(:buffer ,emacs-buffer) `(:offset ,emacs-position ,pos) `(:snippet ,snipped)))) (fallback-source-location code-location))) (defun source-file-source-location (code-location) (let* ((code-date (code-location-debug-source-created code-location)) (filename (code-location-debug-source-name code-location)) (*readtable* (guess-readtable-for-filename filename)) (source-code (get-source-code filename code-date))) (with-debootstrapping (with-input-from-string (s source-code) (let* ((pos (stream-source-position code-location s)) (snippet (read-snippet s pos))) (make-location `(:file ,filename) `(:position ,pos) `(:snippet ,snippet))))))) (defun code-location-debug-source-name (code-location) (namestring (truename (#+#.(swank-backend:with-symbol 'debug-source-name 'sb-di) sb-c::debug-source-name #-#.(swank-backend:with-symbol 'debug-source-name 'sb-di) sb-c::debug-source-namestring (sb-di::code-location-debug-source code-location))))) (defun code-location-debug-source-created (code-location) (sb-c::debug-source-created (sb-di::code-location-debug-source code-location))) (defun code-location-debug-fun-fun (code-location) (sb-di:debug-fun-fun (sb-di:code-location-debug-fun code-location))) (defun code-location-has-debug-block-info-p (code-location) (handler-case (progn (sb-di:code-location-debug-block code-location) t) (sb-di:no-debug-blocks () nil))) (defun stream-source-position (code-location stream) (let* ((cloc (sb-debug::maybe-block-start-location code-location)) (tlf-number (sb-di::code-location-toplevel-form-offset cloc)) (form-number (sb-di::code-location-form-number cloc))) (multiple-value-bind (tlf pos-map) (read-source-form tlf-number stream) (let* ((path-table (sb-di::form-number-translations tlf 0)) (path (cond ((<= (length path-table) form-number) (warn "inconsistent form-number-translations") (list 0)) (t (reverse (cdr (aref path-table form-number))))))) (source-path-source-position path tlf pos-map))))) (defun string-source-position (code-location string) (with-input-from-string (s string) (stream-source-position code-location s))) ;;; source-path-file-position and friends are in swank-source-path-parser (defimplementation frame-source-location (index) (converting-errors-to-error-location (code-location-source-location (sb-di:frame-code-location (nth-frame index))))) (defun frame-debug-vars (frame) "Return a vector of debug-variables in frame." (sb-di::debug-fun-debug-vars (sb-di:frame-debug-fun frame))) (defun debug-var-value (var frame location) (ecase (sb-di:debug-var-validity var location) (:valid (sb-di:debug-var-value var frame)) ((:invalid :unknown) ':<not-available>))) (defun debug-var-info (var) Introduced by SBCL 1.0.49.76 . (let ((s (find-symbol "DEBUG-VAR-INFO" :sb-di))) (when (and s (fboundp s)) (funcall s var)))) (defimplementation frame-locals (index) (let* ((frame (nth-frame index)) (loc (sb-di:frame-code-location frame)) (vars (frame-debug-vars frame)) Since 1.0.49.76 PREPROCESS - FOR - EVAL understands SB - DEBUG::MORE ;; specially. (more-name (or (find-symbol "MORE" :sb-debug) 'more)) (more-context nil) (more-count nil) (more-id 0)) (when vars (let ((locals (loop for v across vars do (when (eq (sb-di:debug-var-symbol v) more-name) (incf more-id)) (case (debug-var-info v) (:more-context (setf more-context (debug-var-value v frame loc))) (:more-count (setf more-count (debug-var-value v frame loc)))) collect (list :name (sb-di:debug-var-symbol v) :id (sb-di:debug-var-id v) :value (debug-var-value v frame loc))))) (when (and more-context more-count) (setf locals (append locals (list (list :name more-name :id more-id :value (multiple-value-list (sb-c:%more-arg-values more-context 0 more-count))))))) locals)))) (defimplementation frame-var-value (frame var) (let* ((frame (nth-frame frame)) (vars (frame-debug-vars frame)) (loc (sb-di:frame-code-location frame)) (dvar (if (= var (length vars)) If VAR is out of bounds , it must be the fake var we made up for ;; &MORE. (let* ((context-var (find :more-context vars :key #'debug-var-info)) (more-context (debug-var-value context-var frame loc)) (count-var (find :more-count vars :key #'debug-var-info)) (more-count (debug-var-value count-var frame loc))) (return-from frame-var-value (multiple-value-list (sb-c:%more-arg-values more-context 0 more-count)))) (aref vars var)))) (debug-var-value dvar frame loc))) (defimplementation frame-catch-tags (index) (mapcar #'car (sb-di:frame-catches (nth-frame index)))) (defimplementation eval-in-frame (form index) (let ((frame (nth-frame index))) (funcall (the function (sb-di:preprocess-for-eval form (sb-di:frame-code-location frame))) frame))) #+#.(swank-backend::sbcl-with-restart-frame) (progn (defimplementation return-from-frame (index form) (let* ((frame (nth-frame index))) (cond ((sb-debug:frame-has-debug-tag-p frame) (let ((values (multiple-value-list (eval-in-frame form index)))) (sb-debug:unwind-to-frame-and-call frame (lambda () (values-list values))))) (t (format nil "Cannot return from frame: ~S" frame))))) (defimplementation restart-frame (index) (let ((frame (nth-frame index))) (when (sb-debug:frame-has-debug-tag-p frame) (multiple-value-bind (fname args) (sb-debug::frame-call frame) (multiple-value-bind (fun arglist) (if (and (sb-int:legal-fun-name-p fname) (fboundp fname)) (values (fdefinition fname) args) (values (sb-di:debug-fun-fun (sb-di:frame-debug-fun frame)) (sb-debug::frame-args-as-list frame))) (when (functionp fun) (sb-debug:unwind-to-frame-and-call frame (lambda () ;; Ensure TCO. (declare (optimize (debug 0))) (apply fun arglist))))))) (format nil "Cannot restart frame: ~S" frame)))) ;; FIXME: this implementation doesn't unwind the stack before ;; re-invoking the function, but it's better than no implementation at ;; all. #-#.(swank-backend::sbcl-with-restart-frame) (progn (defun sb-debug-catch-tag-p (tag) (and (symbolp tag) (not (symbol-package tag)) (string= tag :sb-debug-catch-tag))) (defimplementation return-from-frame (index form) (let* ((frame (nth-frame index)) (probe (assoc-if #'sb-debug-catch-tag-p (sb-di::frame-catches frame)))) (cond (probe (throw (car probe) (eval-in-frame form index))) (t (format nil "Cannot return from frame: ~S" frame))))) (defimplementation restart-frame (index) (let ((frame (nth-frame index))) (return-from-frame index (sb-debug::frame-call-as-list frame))))) ;;;;; reference-conditions (defimplementation format-sldb-condition (condition) (let ((sb-int:*print-condition-references* nil)) (princ-to-string condition))) ;;;; Profiling (defimplementation profile (fname) (when fname (eval `(sb-profile:profile ,fname)))) (defimplementation unprofile (fname) (when fname (eval `(sb-profile:unprofile ,fname)))) (defimplementation unprofile-all () (sb-profile:unprofile) "All functions unprofiled.") (defimplementation profile-report () (sb-profile:report)) (defimplementation profile-reset () (sb-profile:reset) "Reset profiling counters.") (defimplementation profiled-functions () (sb-profile:profile)) (defimplementation profile-package (package callers methods) (declare (ignore callers methods)) (eval `(sb-profile:profile ,(package-name (find-package package))))) ;;;; Inspector (defmethod emacs-inspect ((o t)) (cond ((sb-di::indirect-value-cell-p o) (label-value-line* (:value (sb-kernel:value-cell-ref o)))) (t (multiple-value-bind (text label parts) (sb-impl::inspected-parts o) (list* (string-right-trim '(#\Newline) text) '(:newline) (if label (loop for (l . v) in parts append (label-value-line l v)) (loop for value in parts for i from 0 append (label-value-line i value)))))))) (defmethod emacs-inspect ((o function)) (let ((header (sb-kernel:widetag-of o))) (cond ((= header sb-vm:simple-fun-header-widetag) (label-value-line* (:name (sb-kernel:%simple-fun-name o)) (:arglist (sb-kernel:%simple-fun-arglist o)) (:self (sb-kernel:%simple-fun-self o)) (:next (sb-kernel:%simple-fun-next o)) (:type (sb-kernel:%simple-fun-type o)) (:code (sb-kernel:fun-code-header o)))) ((= header sb-vm:closure-header-widetag) (append (label-value-line :function (sb-kernel:%closure-fun o)) `("Closed over values:" (:newline)) (loop for i below (1- (sb-kernel:get-closure-length o)) append (label-value-line i (sb-kernel:%closure-index-ref o i))))) (t (call-next-method o))))) (defmethod emacs-inspect ((o sb-kernel:code-component)) (append (label-value-line* (:code-size (sb-kernel:%code-code-size o)) (:entry-points (sb-kernel:%code-entry-points o)) (:debug-info (sb-kernel:%code-debug-info o)) (:trace-table-offset (sb-kernel:code-header-ref o sb-vm:code-trace-table-offset-slot))) `("Constants:" (:newline)) (loop for i from sb-vm:code-constants-offset below (sb-kernel:get-header-data o) append (label-value-line i (sb-kernel:code-header-ref o i))) `("Code:" (:newline) , (with-output-to-string (s) (cond ((sb-kernel:%code-debug-info o) (sb-disassem:disassemble-code-component o :stream s)) (t (sb-disassem:disassemble-memory (sb-disassem::align (+ (logandc2 (sb-kernel:get-lisp-obj-address o) sb-vm:lowtag-mask) (* sb-vm:code-constants-offset sb-vm:n-word-bytes)) (ash 1 sb-vm:n-lowtag-bits)) (ash (sb-kernel:%code-code-size o) sb-vm:word-shift) :stream s))))))) (defmethod emacs-inspect ((o sb-ext:weak-pointer)) (label-value-line* (:value (sb-ext:weak-pointer-value o)))) (defmethod emacs-inspect ((o sb-kernel:fdefn)) (label-value-line* (:name (sb-kernel:fdefn-name o)) (:function (sb-kernel:fdefn-fun o)))) (defmethod emacs-inspect :around ((o generic-function)) (append (call-next-method) (label-value-line* (:pretty-arglist (sb-pcl::generic-function-pretty-arglist o)) (:initial-methods (sb-pcl::generic-function-initial-methods o)) ))) ;;;; Multiprocessing #+(and sb-thread #.(swank-backend:with-symbol "THREAD-NAME" "SB-THREAD")) (progn (defvar *thread-id-counter* 0) (defvar *thread-id-counter-lock* (sb-thread:make-mutex :name "thread id counter lock")) (defun next-thread-id () (sb-thread:with-mutex (*thread-id-counter-lock*) (incf *thread-id-counter*))) (defparameter *thread-id-map* (make-hash-table)) ;; This should be a thread -> id map but as weak keys are not ;; supported it is id -> map instead. (defvar *thread-id-map-lock* (sb-thread:make-mutex :name "thread id map lock")) (defimplementation spawn (fn &key name) (sb-thread:make-thread fn :name name)) (defimplementation thread-id (thread) (block thread-id (sb-thread:with-mutex (*thread-id-map-lock*) (loop for id being the hash-key in *thread-id-map* using (hash-value thread-pointer) do (let ((maybe-thread (sb-ext:weak-pointer-value thread-pointer))) (cond ((null maybe-thread) the value is gc'd , remove it manually (remhash id *thread-id-map*)) ((eq thread maybe-thread) (return-from thread-id id))))) ;; lazy numbering (let ((id (next-thread-id))) (setf (gethash id *thread-id-map*) (sb-ext:make-weak-pointer thread)) id)))) (defimplementation find-thread (id) (sb-thread:with-mutex (*thread-id-map-lock*) (let ((thread-pointer (gethash id *thread-id-map*))) (if thread-pointer (let ((maybe-thread (sb-ext:weak-pointer-value thread-pointer))) (if maybe-thread maybe-thread the value is gc'd , remove it manually (progn (remhash id *thread-id-map*) nil))) nil)))) (defimplementation thread-name (thread) sometimes the name is not a string ( e.g. NIL ) (princ-to-string (sb-thread:thread-name thread))) (defimplementation thread-status (thread) (if (sb-thread:thread-alive-p thread) "Running" "Stopped")) (defimplementation make-lock (&key name) (sb-thread:make-mutex :name name)) (defimplementation call-with-lock-held (lock function) (declare (type function function)) (sb-thread:with-recursive-lock (lock) (funcall function))) (defimplementation current-thread () sb-thread:*current-thread*) (defimplementation all-threads () (sb-thread:list-all-threads)) (defimplementation interrupt-thread (thread fn) (sb-thread:interrupt-thread thread fn)) (defimplementation kill-thread (thread) (sb-thread:terminate-thread thread)) (defimplementation thread-alive-p (thread) (sb-thread:thread-alive-p thread)) (defvar *mailbox-lock* (sb-thread:make-mutex :name "mailbox lock")) (defvar *mailboxes* (list)) (declaim (type list *mailboxes*)) (defstruct (mailbox (:conc-name mailbox.)) thread (mutex (sb-thread:make-mutex)) (waitqueue (sb-thread:make-waitqueue)) (queue '() :type list)) (defun mailbox (thread) "Return THREAD's mailbox." (sb-thread:with-mutex (*mailbox-lock*) (or (find thread *mailboxes* :key #'mailbox.thread) (let ((mb (make-mailbox :thread thread))) (push mb *mailboxes*) mb)))) (defimplementation send (thread message) (let* ((mbox (mailbox thread)) (mutex (mailbox.mutex mbox))) (sb-thread:with-mutex (mutex) (setf (mailbox.queue mbox) (nconc (mailbox.queue mbox) (list message))) (sb-thread:condition-broadcast (mailbox.waitqueue mbox))))) #-sb-lutex (defun condition-timed-wait (waitqueue mutex timeout) (handler-case (let ((*break-on-signals* nil)) (sb-sys:with-deadline (:seconds timeout :override t) (sb-thread:condition-wait waitqueue mutex) t)) (sb-ext:timeout () nil))) FIXME : with - timeout does n't work properly on #+sb-lutex (defun condition-timed-wait (waitqueue mutex timeout) (declare (ignore timeout)) (sb-thread:condition-wait waitqueue mutex)) (defimplementation receive-if (test &optional timeout) (let* ((mbox (mailbox (current-thread))) (mutex (mailbox.mutex mbox)) (waitq (mailbox.waitqueue mbox))) (assert (or (not timeout) (eq timeout t))) (loop (check-slime-interrupts) (sb-thread:with-mutex (mutex) (let* ((q (mailbox.queue mbox)) (tail (member-if test q))) (when tail (setf (mailbox.queue mbox) (nconc (ldiff q tail) (cdr tail))) (return (car tail)))) (when (eq timeout t) (return (values nil t))) (condition-timed-wait waitq mutex 0.2))))) (let ((alist '()) (mutex (sb-thread:make-mutex :name "register-thread"))) (defimplementation register-thread (name thread) (declare (type symbol name)) (sb-thread:with-mutex (mutex) (etypecase thread (null (setf alist (delete name alist :key #'car))) (sb-thread:thread (let ((probe (assoc name alist))) (cond (probe (setf (cdr probe) thread)) (t (setf alist (acons name thread alist)))))))) nil) (defimplementation find-registered (name) (sb-thread:with-mutex (mutex) (cdr (assoc name alist))))) ) (defimplementation quit-lisp () #+sb-thread (dolist (thread (remove (current-thread) (all-threads))) (ignore-errors (sb-thread:terminate-thread thread))) (sb-ext:quit)) Trace implementations In , we have : ;; (trace <name>) ;; (trace :methods '<name>) ;to trace all methods of the gf <name> ;; (trace (method <name> <qualifier>? (<specializer>+))) < name > can be a normal name or a ( setf name ) (defun toggle-trace-aux (fspec &rest args) (cond ((member fspec (eval '(trace)) :test #'equal) (eval `(untrace ,fspec)) (format nil "~S is now untraced." fspec)) (t (eval `(trace ,@(if args `(:encapsulate nil) (list)) ,fspec ,@args)) (format nil "~S is now traced." fspec)))) (defun process-fspec (fspec) (cond ((consp fspec) (ecase (first fspec) ((:defun :defgeneric) (second fspec)) ((:defmethod) `(method ,@(rest fspec))) ((:labels) `(labels ,(process-fspec (second fspec)) ,(third fspec))) ((:flet) `(flet ,(process-fspec (second fspec)) ,(third fspec))))) (t fspec))) (defimplementation toggle-trace (spec) (ecase (car spec) ((setf) (toggle-trace-aux spec)) ((:defmethod) (toggle-trace-aux `(sb-pcl::fast-method ,@(rest (process-fspec spec))))) ((:defgeneric) (toggle-trace-aux (second spec) :methods t)) ((:call) (destructuring-bind (caller callee) (cdr spec) (toggle-trace-aux callee :wherein (list (process-fspec caller))))))) ;;; Weak datastructures (defimplementation make-weak-key-hash-table (&rest args) #+#.(swank-backend::sbcl-with-weak-hash-tables) (apply #'make-hash-table :weakness :key args) #-#.(swank-backend::sbcl-with-weak-hash-tables) (apply #'make-hash-table args)) (defimplementation make-weak-value-hash-table (&rest args) #+#.(swank-backend::sbcl-with-weak-hash-tables) (apply #'make-hash-table :weakness :value args) #-#.(swank-backend::sbcl-with-weak-hash-tables) (apply #'make-hash-table args)) (defimplementation hash-table-weakness (hashtable) #+#.(swank-backend::sbcl-with-weak-hash-tables) (sb-ext:hash-table-weakness hashtable)) #-win32 (defimplementation save-image (filename &optional restart-function) (flet ((restart-sbcl () (sb-debug::enable-debugger) (setf sb-impl::*descriptor-handlers* nil) (funcall restart-function))) (let ((pid (sb-posix:fork))) (cond ((= pid 0) (sb-debug::disable-debugger) (apply #'sb-ext:save-lisp-and-die filename (when restart-function (list :toplevel #'restart-sbcl)))) (t (multiple-value-bind (rpid status) (sb-posix:waitpid pid 0) (assert (= pid rpid)) (assert (and (sb-posix:wifexited status) (zerop (sb-posix:wexitstatus status)))))))))) #+unix (progn (sb-alien:define-alien-routine ("execv" sys-execv) sb-alien:int (program sb-alien:c-string) (argv (* sb-alien:c-string))) (defun execv (program args) "Replace current executable with another one." (let ((a-args (sb-alien:make-alien sb-alien:c-string (+ 1 (length args))))) (unwind-protect (progn (loop for index from 0 by 1 and item in (append args '(nil)) do (setf (sb-alien:deref a-args index) item)) (when (minusp (sys-execv program a-args)) (error "execv(3) returned."))) (sb-alien:free-alien a-args)))) (defun runtime-pathname () #+#.(swank-backend:with-symbol '*runtime-pathname* 'sb-ext) sb-ext:*runtime-pathname* #-#.(swank-backend:with-symbol '*runtime-pathname* 'sb-ext) (car sb-ext:*posix-argv*)) (defimplementation exec-image (image-file args) (loop with fd-arg = (loop for arg in args and key = "" then arg when (string-equal key "--swank-fd") return (parse-integer arg)) for my-fd from 3 to 1024 when (/= my-fd fd-arg) do (ignore-errors (sb-posix:fcntl my-fd sb-posix:f-setfd 1))) (let* ((self-string (pathname-to-filename (runtime-pathname)))) (execv self-string (apply 'list self-string "--core" image-file args))))) (defimplementation make-fd-stream (fd external-format) (sb-sys:make-fd-stream fd :input t :output t :element-type 'character :buffering :full :dual-channel-p t :external-format external-format)) (defimplementation call-with-io-timeout (function &key seconds) (handler-case (sb-sys:with-deadline (:seconds seconds) (funcall function)) (sb-sys:deadline-timeout () nil))) #-win32 (defimplementation background-save-image (filename &key restart-function completion-function) (flet ((restart-sbcl () (sb-debug::enable-debugger) (setf sb-impl::*descriptor-handlers* nil) (funcall restart-function))) (multiple-value-bind (pipe-in pipe-out) (sb-posix:pipe) (let ((pid (sb-posix:fork))) (cond ((= pid 0) (sb-posix:close pipe-in) (sb-debug::disable-debugger) (apply #'sb-ext:save-lisp-and-die filename (when restart-function (list :toplevel #'restart-sbcl)))) (t (sb-posix:close pipe-out) (sb-sys:add-fd-handler pipe-in :input (lambda (fd) (sb-sys:invalidate-descriptor fd) (sb-posix:close fd) (multiple-value-bind (rpid status) (sb-posix:waitpid pid 0) (assert (= pid rpid)) (assert (sb-posix:wifexited status)) (funcall completion-function (zerop (sb-posix:wexitstatus status)))))))))))) (defun deinit-log-output () ;; Can't hang on to an fd-stream from a previous session. (setf (symbol-value (find-symbol "*LOG-OUTPUT*" 'swank)) nil)) (pushnew 'deinit-log-output sb-ext:*save-hooks*)
null
https://raw.githubusercontent.com/vim-scripts/slimv.vim/61ce81ff6b1a05314a6d750a32a1c7379f35a5dc/slime/swank-sbcl.lisp
lisp
-*- Mode: lisp; indent-tabs-mode: nil -*- This code has been placed in the Public Domain. All warranties are disclaimed. Requires the SB-INTROSPECT contrib. backwards compability tests Generate a form suitable for testing for stepper support (0.9.17) with #+. Ditto for weak hash-tables swank-mop Declare return type explicitly to shut up STYLE-WARNINGS about UTF8 TCP Server this. prevent recursion still open? available when backend is loaded. argument. containing `!' have special meaning. We have to work long and hard to be able to read the source. To deal with #! reader macros, we use a special readtable. The special symbols are converted by a condition handler. When test is not satisfied FIXME: clearer if order of NOT-P and (NOT NOT-P) were reversed? then would become "unless test is satisfied".. Read (and discard) a form from input. have to be fully qualified when used inside a declaration. So we strip those as long as there's no better way. (FIXME) First resignal warnings, so that outer handlers -- which may choose to muffle this -- get a chance to run. The stream position for e.g. "comma not inside backquote" is at the character following the comma, :offset is 0-based, hence the 1-. The following is to trigger COMPILING-FROM-GENERATED-CODE-P in LOCATE-COMPILER-NOTE, and allows handling nested compilation from eg. hitting C-C on (eval-when ... (require ..))). PROBE-FILE to handle tempfile directory being a symlink. N.B. Even though these handlers are called HANDLE-FOO they actually decline, i.e. the signalling of the original condition continues upward. Cache the latest source file for definition-finding. compile-string We copy the string to a temporary file in order to get adequate semantics for :COMPILE-TOPLEVEL and :LOAD-TOPLEVEL EVAL-WHEN forms which the previous approach using (compile nil `(lambda () ,(read-from-string string))) did not provide. Definitions -- which is actually good information and often long. So elide the original name in favor of making the interesting bit more visible. name which usually has a worthwhile postfix. So drop the note. Packages are possibly named entities. /file positions/ in Common Lisp start from macroexpansion Debugging than just a hook into BREAK. In particular, it'll make (LET ((*DEBUGGER-HOOK* NIL)) ..error..) drop into SLDB rather than the native debugger. That should probably be considered a feature. decline, *DEBUGGER-HOOK* will be tried next. Code-location -> source-location translation If debug-block info is avaibale, we determine the file position of the source-path for a code-location. If the code was compiled If there's no debug-block info, we return the (less precise) source-location of the corresponding function. FIXME: The naming policy of source-location functions is a bit fuzzy: we have FUNCTION-SOURCE-LOCATION which returns the which returns the source location for a _code-location_. Maybe these should be named code-location-file-source-location, etc, turned into generic functions, or something. In the very least the names should indicate the main entry point vs. helper status. source-path-file-position and friends are in swank-source-path-parser specially. &MORE. Ensure TCO. FIXME: this implementation doesn't unwind the stack before re-invoking the function, but it's better than no implementation at all. reference-conditions Profiling Inspector Multiprocessing This should be a thread -> id map but as weak keys are not supported it is id -> map instead. lazy numbering (trace <name>) (trace :methods '<name>) ;to trace all methods of the gf <name> (trace (method <name> <qualifier>? (<specializer>+))) Weak datastructures Can't hang on to an fd-stream from a previous session.
swank-sbcl.lisp --- SLIME backend for SBCL . Created 2003 , < > Administrivia (in-package :swank-backend) (eval-when (:compile-toplevel :load-toplevel :execute) (require 'sb-bsd-sockets) (require 'sb-introspect) (require 'sb-posix) (require 'sb-cltl2)) (declaim (optimize (debug 2) (sb-c::insert-step-conditions 0) (sb-c::insert-debug-catch 0) (sb-c::merge-tail-calls 2))) (import-from :sb-gray *gray-stream-symbols* :swank-backend) (eval-when (:compile-toplevel :load-toplevel :execute) (defun sbcl-with-new-stepper-p () (with-symbol 'enable-stepping 'sb-impl)) (defun sbcl-with-weak-hash-tables () (with-symbol 'hash-table-weakness 'sb-ext)) And for xref support ( 1.0.1 ) (defun sbcl-with-xref-p () (with-symbol 'who-calls 'sb-introspect)) ... for restart - frame support ( 1.0.2 ) (defun sbcl-with-restart-frame () (with-symbol 'frame-has-debug-tag-p 'sb-debug))) (import-swank-mop-symbols :sb-mop '(:slot-definition-documentation)) (defun swank-mop:slot-definition-documentation (slot) (sb-pcl::documentation slot t)) Connection info (defimplementation lisp-implementation-type-name () "sbcl") % SAP - ALIEN in ENABLE - SIGIO - ON - FD below . (declaim (ftype (function () (values (signed-byte 32) &optional)) getpid)) (defimplementation getpid () (sb-posix:getpid)) (defimplementation string-to-utf8 (string) (sb-ext:string-to-octets string :external-format :utf8)) (defimplementation utf8-to-string (octets) (sb-ext:octets-to-string octets :external-format :utf8)) (defimplementation preferred-communication-style () (cond fixme : when SBCL / win32 gains better select ( ) support , remove ((member :sb-thread *features*) :spawn) ((member :win32 *features*) nil) (t :fd-handler))) (defun resolve-hostname (name) (car (sb-bsd-sockets:host-ent-addresses (sb-bsd-sockets:get-host-by-name name)))) (defimplementation create-socket (host port &key backlog) (let ((socket (make-instance 'sb-bsd-sockets:inet-socket :type :stream :protocol :tcp))) (setf (sb-bsd-sockets:sockopt-reuse-address socket) t) (sb-bsd-sockets:socket-bind socket (resolve-hostname host) port) (sb-bsd-sockets:socket-listen socket (or backlog 5)) socket)) (defimplementation local-port (socket) (nth-value 1 (sb-bsd-sockets:socket-name socket))) (defimplementation close-socket (socket) (sb-sys:invalidate-descriptor (socket-fd socket)) (sb-bsd-sockets:socket-close socket)) (defimplementation accept-connection (socket &key external-format buffering timeout) (declare (ignore timeout)) (make-socket-io-stream (accept socket) external-format (ecase buffering ((t :full) :full) ((nil :none) :none) ((:line) :line)))) #-win32 (defimplementation install-sigint-handler (function) (sb-sys:enable-interrupt sb-unix:sigint (lambda (&rest args) (declare (ignore args)) (sb-sys:invoke-interruption (lambda () (sb-sys:with-interrupts (funcall function))))))) (defvar *sigio-handlers* '() "List of (key . fn) pairs to be called on SIGIO.") (defun sigio-handler (signal code scp) (declare (ignore signal code scp)) (mapc (lambda (handler) (funcall (the function (cdr handler)))) *sigio-handlers*)) (defun set-sigio-handler () (sb-sys:enable-interrupt sb-unix:sigio (lambda (signal code scp) (sigio-handler signal code scp)))) (defun enable-sigio-on-fd (fd) (sb-posix::fcntl fd sb-posix::f-setfl sb-posix::o-async) (sb-posix::fcntl fd sb-posix::f-setown (getpid)) (values)) (defimplementation add-sigio-handler (socket fn) (set-sigio-handler) (let ((fd (socket-fd socket))) (enable-sigio-on-fd fd) (push (cons fd fn) *sigio-handlers*))) (defimplementation remove-sigio-handlers (socket) (let ((fd (socket-fd socket))) (setf *sigio-handlers* (delete fd *sigio-handlers* :key #'car)) (sb-sys:invalidate-descriptor fd)) (close socket)) (defimplementation add-fd-handler (socket fun) (let ((fd (socket-fd socket)) (handler nil)) (labels ((add () (setq handler (sb-sys:add-fd-handler fd :input #'run))) (run (fd) (unwind-protect (funcall fun) (add))))) (add)))) (defimplementation remove-fd-handlers (socket) (sb-sys:invalidate-descriptor (socket-fd socket))) (defimplementation socket-fd (socket) (etypecase socket (fixnum socket) (sb-bsd-sockets:socket (sb-bsd-sockets:socket-file-descriptor socket)) (file-stream (sb-sys:fd-stream-fd socket)))) (defimplementation command-line-args () sb-ext:*posix-argv*) (defimplementation dup (fd) (sb-posix:dup fd)) (defvar *wait-for-input-called*) (defimplementation wait-for-input (streams &optional timeout) (assert (member timeout '(nil t))) (when (boundp '*wait-for-input-called*) (setq *wait-for-input-called* t)) (let ((*wait-for-input-called* nil)) (loop (let ((ready (remove-if-not #'input-ready-p streams))) (when ready (return ready))) (when (check-slime-interrupts) (return :interrupt)) (when *wait-for-input-called* (return :interrupt)) (when timeout (return nil)) (sleep 0.1)))) (defun fd-stream-input-buffer-empty-p (stream) (let ((buffer (sb-impl::fd-stream-ibuf stream))) (or (not buffer) (= (sb-impl::buffer-head buffer) (sb-impl::buffer-tail buffer))))) #-win32 (defun input-ready-p (stream) (or (not (fd-stream-input-buffer-empty-p stream)) #+#.(swank-backend:with-symbol 'fd-stream-fd-type 'sb-impl) (eq :regular (sb-impl::fd-stream-fd-type stream)) (not (sb-impl::sysread-may-block-p stream)))) #+win32 (progn (defun input-ready-p (stream) (or (not (fd-stream-input-buffer-empty-p stream)) (handle-listen (sockint::fd->handle (sb-impl::fd-stream-fd stream))))) (sb-alien:define-alien-routine ("WSACreateEvent" wsa-create-event) sb-win32:handle) (sb-alien:define-alien-routine ("WSACloseEvent" wsa-close-event) sb-alien:int (event sb-win32:handle)) (defconstant +fd-read+ #.(ash 1 0)) (defconstant +fd-close+ #.(ash 1 5)) (sb-alien:define-alien-routine ("WSAEventSelect" wsa-event-select) sb-alien:int (fd sb-alien:int) (handle sb-win32:handle) (mask sb-alien:long)) (sb-alien:load-shared-object "kernel32.dll") (sb-alien:define-alien-routine ("WaitForSingleObjectEx" wait-for-single-object-ex) sb-alien:int (event sb-win32:handle) (milliseconds sb-alien:long) (alertable sb-alien:int)) see : HANDLE - LISTEN (defun handle-listen (handle) (sb-alien:with-alien ((avail sb-win32:dword) (buf (array char #.sb-win32::input-record-size))) (unless (zerop (sb-win32:peek-named-pipe handle nil 0 nil (sb-alien:alien-sap (sb-alien:addr avail)) nil)) (return-from handle-listen (plusp avail))) (unless (zerop (sb-win32:peek-console-input handle (sb-alien:alien-sap buf) sb-win32::input-record-size (sb-alien:alien-sap (sb-alien:addr avail)))) (return-from handle-listen (plusp avail)))) (let ((event (wsa-create-event))) (wsa-event-select handle event (logior +fd-read+ +fd-close+)) (let ((val (wait-for-single-object-ex event 0 0))) (wsa-close-event event) (unless (= val -1) (return-from handle-listen (zerop val))))) nil) ) (defvar *external-format-to-coding-system* '((:iso-8859-1 "latin-1" "latin-1-unix" "iso-latin-1-unix" "iso-8859-1" "iso-8859-1-unix") (:utf-8 "utf-8" "utf-8-unix") (:euc-jp "euc-jp" "euc-jp-unix") (:us-ascii "us-ascii" "us-ascii-unix"))) C.f . R.M.Kreuter in < > on sbcl - general , 2008 - 08 - 22 . (defvar *physical-pathname-host* (pathname-host (user-homedir-pathname))) (defimplementation filename-to-pathname (filename) (sb-ext:parse-native-namestring filename *physical-pathname-host*)) (defimplementation find-external-format (coding-system) (car (rassoc-if (lambda (x) (member coding-system x :test #'equal)) *external-format-to-coding-system*))) (defun make-socket-io-stream (socket external-format buffering) (let ((args `(,@() :output t :input t :element-type ,(if external-format 'character '(unsigned-byte 8)) :buffering ,buffering ,@(cond ((and external-format (sb-int:featurep :sb-unicode)) `(:external-format ,external-format)) (t '())) :serve-events ,(eq :fd-handler : SWANK package is n't (symbol-value (intern "*COMMUNICATION-STYLE*" :swank))) SBCL < 1.0.42.43 does n't support : SERVE - EVENTS :allow-other-keys t))) (apply #'sb-bsd-sockets:socket-make-stream socket args))) (defun accept (socket) "Like socket-accept, but retry on EAGAIN." (loop (handler-case (return (sb-bsd-sockets:socket-accept socket)) (sb-bsd-sockets:interrupted-error ())))) Support for syntax SBCL 's source code is riddled with # ! reader macros . Also symbols (defun feature-in-list-p (feature list) (etypecase feature (symbol (member feature list :test #'eq)) (cons (flet ((subfeature-in-list-p (subfeature) (feature-in-list-p subfeature list))) (ecase (first feature) (:or (some #'subfeature-in-list-p (rest feature))) (:and (every #'subfeature-in-list-p (rest feature))) (:not (destructuring-bind (e) (cdr feature) (not (subfeature-in-list-p e))))))))) (defun shebang-reader (stream sub-character infix-parameter) (declare (ignore sub-character)) (when infix-parameter (error "illegal read syntax: #~D!" infix-parameter)) (let ((next-char (read-char stream))) (unless (find next-char "+-") (error "illegal read syntax: #!~C" next-char)) (when (let* ((*package* (find-package "KEYWORD")) (*read-suppress* nil) (not-p (char= next-char #\-)) (feature (read stream))) (if (feature-in-list-p feature *features*) not-p (not not-p))) (let ((*read-suppress* t)) (read stream t nil t)))) (values)) (defvar *shebang-readtable* (let ((*readtable* (copy-readtable nil))) (set-dispatch-macro-character #\# #\! (lambda (s c n) (shebang-reader s c n)) *readtable*) *readtable*)) (defun shebang-readtable () *shebang-readtable*) (defun sbcl-package-p (package) (let ((name (package-name package))) (eql (mismatch "SB-" name) 3))) (defun sbcl-source-file-p (filename) (when filename (loop for (nil pattern) in (logical-pathname-translations "SYS") thereis (pathname-match-p filename pattern)))) (defun guess-readtable-for-filename (filename) (if (sbcl-source-file-p filename) (shebang-readtable) *readtable*)) (defvar *debootstrap-packages* t) (defun call-with-debootstrapping (fun) (handler-bind ((sb-int:bootstrap-package-not-found #'sb-int:debootstrap-package)) (funcall fun))) (defmacro with-debootstrapping (&body body) `(call-with-debootstrapping (lambda () ,@body))) (defimplementation call-with-syntax-hooks (fn) (cond ((and *debootstrap-packages* (sbcl-package-p *package*)) (with-debootstrapping (funcall fn))) (t (funcall fn)))) (defimplementation default-readtable-alist () (let ((readtable (shebang-readtable))) (loop for p in (remove-if-not #'sbcl-package-p (list-all-packages)) collect (cons (package-name p) readtable)))) Utilities #+#.(swank-backend:with-symbol 'function-lambda-list 'sb-introspect) (defimplementation arglist (fname) (sb-introspect:function-lambda-list fname)) #-#.(swank-backend:with-symbol 'function-lambda-list 'sb-introspect) (defimplementation arglist (fname) (sb-introspect:function-arglist fname)) (defimplementation function-name (f) (check-type f function) (sb-impl::%fun-name f)) (defmethod declaration-arglist ((decl-identifier (eql 'optimize))) (flet ((ensure-list (thing) (if (listp thing) thing (list thing)))) (let* ((flags (sb-cltl2:declaration-information decl-identifier))) (if flags Symbols are n't printed with package qualifiers , but the FLAGS would `(&any ,@(remove-if-not #'(lambda (qualifier) (find-symbol (symbol-name (first qualifier)) :cl)) flags :key #'ensure-list)) (call-next-method))))) #+#.(swank-backend:with-symbol 'deftype-lambda-list 'sb-introspect) (defmethod type-specifier-arglist :around (typespec-operator) (multiple-value-bind (arglist foundp) (sb-introspect:deftype-lambda-list typespec-operator) (if foundp arglist (call-next-method)))) (defvar *buffer-name* nil) (defvar *buffer-tmpfile* nil) (defvar *buffer-offset*) (defvar *buffer-substring* nil) (defvar *previous-compiler-condition* nil "Used to detect duplicates.") (defun handle-notification-condition (condition) "Handle a condition caused by a compiler warning. This traps all compiler conditions at a lower-level than using C:*COMPILER-NOTIFICATION-FUNCTION*. The advantage is that we get to craft our own error messages, which can omit a lot of redundant information." (unless (or (eq condition *previous-compiler-condition*)) (when (typep condition 'warning) (signal condition)) (setq *previous-compiler-condition* condition) (signal-compiler-condition (real-condition condition) (sb-c::find-error-context nil)))) (defun signal-compiler-condition (condition context) (signal (make-condition 'compiler-condition :original-condition condition :severity (etypecase condition (sb-ext:compiler-note :note) (sb-c:compiler-error :error) (reader-error :read-error) (error :error) #+#.(swank-backend:with-symbol redefinition-warning sb-kernel) (sb-kernel:redefinition-warning :redefinition) (style-warning :style-warning) (warning :warning)) :references (condition-references condition) :message (brief-compiler-message-for-emacs condition) :source-context (compiler-error-context context) :location (compiler-note-location condition context)))) (defun real-condition (condition) "Return the encapsulated condition or CONDITION itself." (typecase condition (sb-int:encapsulated-condition (sb-int:encapsulated-condition condition)) (t condition))) (defun condition-references (condition) (if (typep condition 'sb-int:reference-condition) (externalize-reference (sb-int:reference-condition-references condition)))) (defun compiler-note-location (condition context) (flet ((bailout () (return-from compiler-note-location (make-error-location "No error location available")))) (cond (context (locate-compiler-note (sb-c::compiler-error-context-file-name context) (compiler-source-path context) (sb-c::compiler-error-context-original-source context))) ((typep condition 'reader-error) (let* ((stream (stream-error-stream condition)) (file (pathname stream))) (unless (open-stream-p stream) (bailout)) (if (compiling-from-buffer-p file) (make-location (list :buffer *buffer-name*) (list :offset *buffer-offset* (1- (file-position stream)))) (progn (assert (compiling-from-file-p file)) No 1- because : position is 1 - based . (make-location (list :file (namestring file)) (list :position (file-position stream))))))) (t (bailout))))) (defun compiling-from-buffer-p (filename) (and *buffer-name* (pathnamep filename) (let ((true1 (probe-file filename)) (true2 (probe-file *buffer-tmpfile*))) (and true1 (equal true1 true2))))) (defun compiling-from-file-p (filename) (and (pathnamep filename) (or (null *buffer-name*) (null *buffer-tmpfile*) (let ((true1 (probe-file filename)) (true2 (probe-file *buffer-tmpfile*))) (not (and true1 (equal true1 true2))))))) (defun compiling-from-generated-code-p (filename source) (and (eq filename :lisp) (stringp source))) (defun locate-compiler-note (file source-path source) (cond ((compiling-from-buffer-p file) (make-location (list :buffer *buffer-name*) (list :offset *buffer-offset* (source-path-string-position source-path *buffer-substring*)))) ((compiling-from-file-p file) (make-location (list :file (namestring file)) (list :position (1+ (source-path-file-position source-path file))))) ((compiling-from-generated-code-p file source) (make-location (list :source-form source) (list :position 1))) (t (error "unhandled case in compiler note ~S ~S ~S" file source-path source)))) (defun brief-compiler-message-for-emacs (condition) "Briefly describe a compiler error for Emacs. When Emacs presents the message it already has the source popped up and the source form highlighted. This makes much of the information in the error-context redundant." (let ((sb-int:*print-condition-references* nil)) (princ-to-string condition))) (defun compiler-error-context (error-context) "Describe a compiler error for Emacs including context information." (declare (type (or sb-c::compiler-error-context null) error-context)) (multiple-value-bind (enclosing source) (if error-context (values (sb-c::compiler-error-context-enclosing-source error-context) (sb-c::compiler-error-context-source error-context))) (and (or enclosing source) (format nil "~@[--> ~{~<~%--> ~1:;~A~> ~}~%~]~@[~{==>~%~A~%~}~]" enclosing source)))) (defun compiler-source-path (context) "Return the source-path for the current compiler error. Returns NIL if this cannot be determined by examining internal compiler state." (cond ((sb-c::node-p context) (reverse (sb-c::source-path-original-source (sb-c::node-source-path context)))) ((sb-c::compiler-error-context-p context) (reverse (sb-c::compiler-error-context-original-source-path context))))) (defimplementation call-with-compilation-hooks (function) (declare (type function function)) (handler-bind ((sb-c:fatal-compiler-error #'handle-notification-condition) (sb-c:compiler-error #'handle-notification-condition) (sb-ext:compiler-note #'handle-notification-condition) (error #'handle-notification-condition) (warning #'handle-notification-condition)) (funcall function))) (defvar *trap-load-time-warnings* t) (defun compiler-policy (qualities) "Return compiler policy qualities present in the QUALITIES alist. QUALITIES is an alist with (quality . value)" #+#.(swank-backend:with-symbol 'restrict-compiler-policy 'sb-ext) (loop with policy = (sb-ext:restrict-compiler-policy) for (quality) in qualities collect (cons quality (or (cdr (assoc quality policy)) 0)))) (defun (setf compiler-policy) (policy) (declare (ignorable policy)) #+#.(swank-backend:with-symbol 'restrict-compiler-policy 'sb-ext) (loop for (qual . value) in policy do (sb-ext:restrict-compiler-policy qual value))) (defmacro with-compiler-policy (policy &body body) (let ((current-policy (gensym))) `(let ((,current-policy (compiler-policy ,policy))) (setf (compiler-policy) ,policy) (unwind-protect (progn ,@body) (setf (compiler-policy) ,current-policy))))) (defimplementation swank-compile-file (input-file output-file load-p external-format &key policy) (multiple-value-bind (output-file warnings-p failure-p) (with-compiler-policy policy (with-compilation-hooks () (compile-file input-file :output-file output-file :external-format external-format))) (values output-file warnings-p (or failure-p (when load-p (source-cache-get input-file (file-write-date input-file)) (not (load output-file))))))) (locally (declare (sb-ext:muffle-conditions sb-ext:compiler-note)) (sb-alien:define-alien-routine (#-win32 "tempnam" #+win32 "_tempnam" tempnam) sb-alien:c-string (dir sb-alien:c-string) (prefix sb-alien:c-string)) ) (defun temp-file-name () "Return a temporary file name to compile strings into." (tempnam nil nil)) (defimplementation swank-compile-string (string &key buffer position filename policy) (let ((*buffer-name* buffer) (*buffer-offset* position) (*buffer-substring* string) (*buffer-tmpfile* (temp-file-name))) (flet ((load-it (filename) (when filename (load filename))) (compile-it (cont) (with-compilation-hooks () (with-compilation-unit (:source-plist (list :emacs-buffer buffer :emacs-filename filename :emacs-string string :emacs-position position) :source-namestring filename :allow-other-keys t) (multiple-value-bind (output-file warningsp failurep) (compile-file *buffer-tmpfile*) (declare (ignore warningsp)) (unless failurep (funcall cont output-file))))))) (with-open-file (s *buffer-tmpfile* :direction :output :if-exists :error) (write-string string s)) (unwind-protect (with-compiler-policy policy (if *trap-load-time-warnings* (compile-it #'load-it) (load-it (compile-it #'identity)))) (ignore-errors (delete-file *buffer-tmpfile*) (delete-file (compile-file-pathname *buffer-tmpfile*))))))) (defparameter *definition-types* '(:variable defvar :constant defconstant :type deftype :symbol-macro define-symbol-macro :macro defmacro :compiler-macro define-compiler-macro :function defun :generic-function defgeneric :method defmethod :setf-expander define-setf-expander :structure defstruct :condition define-condition :class defclass :method-combination define-method-combination :package defpackage :transform :deftransform :optimizer :defoptimizer :vop :define-vop :source-transform :define-source-transform) "Map SB-INTROSPECT definition type names to Slime-friendly forms") (defun definition-specifier (type name) "Return a pretty specifier for NAME representing a definition of type TYPE." (if (and (symbolp name) (eq type :function) (sb-int:info :function :ir1-convert name)) :def-ir1-translator (getf *definition-types* type))) (defun make-dspec (type name source-location) (let ((spec (definition-specifier type name)) (desc (sb-introspect::definition-source-description source-location))) (if (eq :define-vop spec) The first part of the VOP description is the name of the template The second part of the VOP description is the associated compiler note , or NIL -- which is quite uninteresting and confuses the eye when reading the actual (list spec (car desc)) (list* spec name desc)))) (defimplementation find-definitions (name) (loop for type in *definition-types* by #'cddr for defsrcs = (sb-introspect:find-definition-sources-by-name name type) append (loop for defsrc in defsrcs collect (list (make-dspec type name defsrc) (converting-errors-to-error-location (definition-source-for-emacs defsrc type name)))))) (defimplementation find-source-location (obj) (flet ((general-type-of (obj) (typecase obj (method :method) (generic-function :generic-function) (function :function) (structure-class :structure-class) (class :class) (method-combination :method-combination) (package :package) (condition :condition) (structure-object :structure-object) (standard-object :standard-object) (t :thing))) (to-string (obj) (typecase obj ((or structure-object standard-object condition) (with-output-to-string (s) (print-unreadable-object (obj s :type t :identity t)))) (t (princ-to-string obj))))) (converting-errors-to-error-location (let ((defsrc (sb-introspect:find-definition-source obj))) (definition-source-for-emacs defsrc (general-type-of obj) (to-string obj)))))) (defun categorize-definition-source (definition-source) (with-struct (sb-introspect::definition-source- pathname form-path character-offset plist) definition-source (cond ((getf plist :emacs-buffer) :buffer) ((and pathname (or form-path character-offset)) :file) (pathname :file-without-position) (t :invalid)))) (defun definition-source-for-emacs (definition-source type name) (with-struct (sb-introspect::definition-source- pathname form-path character-offset plist file-write-date) definition-source (ecase (categorize-definition-source definition-source) (:buffer (destructuring-bind (&key emacs-buffer emacs-position emacs-directory emacs-string &allow-other-keys) plist (let ((*readtable* (guess-readtable-for-filename emacs-directory))) (multiple-value-bind (start end) (if form-path (with-debootstrapping (source-path-string-position form-path emacs-string)) (values character-offset most-positive-fixnum)) (make-location `(:buffer ,emacs-buffer) `(:offset ,emacs-position ,start) `(:snippet ,(subseq emacs-string start (min end (+ start *source-snippet-size*))))))))) (:file (let* ((namestring (namestring (translate-logical-pathname pathname))) (pos (if form-path (source-file-position namestring file-write-date form-path) character-offset)) (snippet (source-hint-snippet namestring file-write-date pos))) (make-location `(:file ,namestring) 0 , buffer positions in Emacs start from 1 . `(:position ,(1+ pos)) `(:snippet ,snippet)))) (:file-without-position (make-location `(:file ,(namestring (translate-logical-pathname pathname))) '(:position 1) (when (eql type :function) `(:snippet ,(format nil "(defun ~a " (symbol-name name)))))) (:invalid (error "DEFINITION-SOURCE of ~A ~A did not contain ~ meaningful information." (string-downcase type) name))))) (defun source-file-position (filename write-date form-path) (let ((source (get-source-code filename write-date)) (*readtable* (guess-readtable-for-filename filename))) (with-debootstrapping (source-path-string-position form-path source)))) (defun source-hint-snippet (filename write-date position) (read-snippet-from-string (get-source-code filename write-date) position)) (defun function-source-location (function &optional name) (declare (type function function)) (definition-source-for-emacs (sb-introspect:find-definition-source function) :function (or name (function-name function)))) (defimplementation describe-symbol-for-emacs (symbol) "Return a plist describing SYMBOL. Return NIL if the symbol is unbound." (let ((result '())) (flet ((doc (kind) (or (documentation symbol kind) :not-documented)) (maybe-push (property value) (when value (setf result (list* property value result))))) (maybe-push :variable (multiple-value-bind (kind recorded-p) (sb-int:info :variable :kind symbol) (declare (ignore kind)) (if (or (boundp symbol) recorded-p) (doc 'variable)))) (when (fboundp symbol) (maybe-push (cond ((macro-function symbol) :macro) ((special-operator-p symbol) :special-operator) ((typep (fdefinition symbol) 'generic-function) :generic-function) (t :function)) (doc 'function))) (maybe-push :setf (if (or (sb-int:info :setf :inverse symbol) (sb-int:info :setf :expander symbol)) (doc 'setf))) (maybe-push :type (if (sb-int:info :type :kind symbol) (doc 'type))) result))) (defimplementation describe-definition (symbol type) (case type (:variable (describe symbol)) (:function (describe (symbol-function symbol))) (:setf (describe (or (sb-int:info :setf :inverse symbol) (sb-int:info :setf :expander symbol)))) (:class (describe (find-class symbol))) (:type (describe (sb-kernel:values-specifier-type symbol))))) #+#.(swank-backend::sbcl-with-xref-p) (progn (defmacro defxref (name &optional fn-name) `(defimplementation ,name (what) (sanitize-xrefs (mapcar #'source-location-for-xref-data (,(find-symbol (symbol-name (if fn-name fn-name name)) "SB-INTROSPECT") what))))) (defxref who-calls) (defxref who-binds) (defxref who-sets) (defxref who-references) (defxref who-macroexpands) #+#.(swank-backend:with-symbol 'who-specializes-directly 'sb-introspect) (defxref who-specializes who-specializes-directly)) (defun source-location-for-xref-data (xref-data) (destructuring-bind (name . defsrc) xref-data (list name (converting-errors-to-error-location (definition-source-for-emacs defsrc 'function name))))) (defimplementation list-callers (symbol) (let ((fn (fdefinition symbol))) (sanitize-xrefs (mapcar #'function-dspec (sb-introspect:find-function-callers fn))))) (defimplementation list-callees (symbol) (let ((fn (fdefinition symbol))) (sanitize-xrefs (mapcar #'function-dspec (sb-introspect:find-function-callees fn))))) (defun sanitize-xrefs (xrefs) (remove-duplicates (remove-if (lambda (f) (member f (ignored-xref-function-names))) (loop for entry in xrefs for name = (car entry) collect (if (and (consp name) (member (car name) '(sb-pcl::fast-method sb-pcl::slow-method sb-pcl::method))) (cons (cons 'defmethod (cdr name)) (cdr entry)) entry)) :key #'car) :test (lambda (a b) (and (eq (first a) (first b)) (equal (second a) (second b)))))) (defun ignored-xref-function-names () #-#.(swank-backend::sbcl-with-new-stepper-p) '(nil sb-c::step-form sb-c::step-values) #+#.(swank-backend::sbcl-with-new-stepper-p) '(nil)) (defun function-dspec (fn) "Describe where the function FN was defined. Return a list of the form (NAME LOCATION)." (let ((name (function-name fn))) (list name (converting-errors-to-error-location (function-source-location fn name))))) (defimplementation macroexpand-all (form) (let ((sb-walker:*walk-form-expand-macros-p* t)) (sb-walker:walk-form form))) Notice that SB - EXT:*INVOKE - DEBUGGER - HOOK * is slightly stronger (defun make-invoke-debugger-hook (hook) (when hook #'(sb-int:named-lambda swank-invoke-debugger-hook (condition old-hook) (if *debugger-hook* (funcall hook condition old-hook))))) (defun set-break-hook (hook) (setq sb-ext:*invoke-debugger-hook* (make-invoke-debugger-hook hook))) (defun call-with-break-hook (hook continuation) (let ((sb-ext:*invoke-debugger-hook* (make-invoke-debugger-hook hook))) (funcall continuation))) (defimplementation install-debugger-globally (function) (setq *debugger-hook* function) (set-break-hook function)) (defimplementation condition-extras (condition) (cond #+#.(swank-backend::sbcl-with-new-stepper-p) ((typep condition 'sb-impl::step-form-condition) `((:show-frame-source 0))) ((typep condition 'sb-int:reference-condition) (let ((refs (sb-int:reference-condition-references condition))) (if refs `((:references ,(externalize-reference refs)))))))) (defun externalize-reference (ref) (etypecase ref (null nil) (cons (cons (externalize-reference (car ref)) (externalize-reference (cdr ref)))) ((or string number) ref) (symbol (cond ((eq (symbol-package ref) (symbol-package :test)) ref) (t (symbol-name ref)))))) (defvar *sldb-stack-top*) (defimplementation call-with-debugging-environment (debugger-loop-fn) (declare (type function debugger-loop-fn)) (let* ((*sldb-stack-top* (if *debug-swank-backend* (sb-di:top-frame) (or sb-debug:*stack-top-hint* (sb-di:top-frame)))) (sb-debug:*stack-top-hint* nil)) (handler-bind ((sb-di:debug-condition (lambda (condition) (signal (make-condition 'sldb-condition :original-condition condition))))) (funcall debugger-loop-fn)))) #+#.(swank-backend::sbcl-with-new-stepper-p) (progn (defimplementation activate-stepping (frame) (declare (ignore frame)) (sb-impl::enable-stepping)) (defimplementation sldb-stepper-condition-p (condition) (typep condition 'sb-ext:step-form-condition)) (defimplementation sldb-step-into () (invoke-restart 'sb-ext:step-into)) (defimplementation sldb-step-next () (invoke-restart 'sb-ext:step-next)) (defimplementation sldb-step-out () (invoke-restart 'sb-ext:step-out))) (defimplementation call-with-debugger-hook (hook fun) (let ((*debugger-hook* hook) #+#.(swank-backend::sbcl-with-new-stepper-p) (sb-ext:*stepper-hook* (lambda (condition) (typecase condition (sb-ext:step-form-condition (let ((sb-debug:*stack-top-hint* (sb-di::find-stepped-frame))) (sb-impl::invoke-debugger condition))))))) (handler-bind (#+#.(swank-backend::sbcl-with-new-stepper-p) (sb-ext:step-condition #'sb-impl::invoke-stepper)) (call-with-break-hook hook fun)))) (defun nth-frame (index) (do ((frame *sldb-stack-top* (sb-di:frame-down frame)) (i index (1- i))) ((zerop i) frame))) (defimplementation compute-backtrace (start end) "Return a list of frames starting with frame number START and continuing to frame number END or, if END is nil, the last frame on the stack." (let ((end (or end most-positive-fixnum))) (loop for f = (nth-frame start) then (sb-di:frame-down f) for i from start below end while f collect f))) (defimplementation print-frame (frame stream) (sb-debug::print-frame-call frame stream)) (defimplementation frame-restartable-p (frame) #+#.(swank-backend::sbcl-with-restart-frame) (not (null (sb-debug:frame-has-debug-tag-p frame)))) (defimplementation frame-call (frame-number) (multiple-value-bind (name args) (sb-debug::frame-call (nth-frame frame-number)) (with-output-to-string (stream) (pprint-logical-block (stream nil :prefix "(" :suffix ")") (let ((*print-length* nil) (*print-level* nil)) (prin1 (sb-debug::ensure-printable-object name) stream)) (let ((args (sb-debug::ensure-printable-object args))) (if (listp args) (format stream "~{ ~_~S~}" args) (format stream " ~S" args))))))) with C - c C - c , we have to search the position in the source string . (defun code-location-source-location (code-location) (let* ((dsource (sb-di:code-location-debug-source code-location)) (plist (sb-c::debug-source-plist dsource))) (if (getf plist :emacs-buffer) (emacs-buffer-source-location code-location plist) #+#.(swank-backend:with-symbol 'debug-source-from 'sb-di) (ecase (sb-di:debug-source-from dsource) (:file (file-source-location code-location)) (:lisp (lisp-source-location code-location))) #-#.(swank-backend:with-symbol 'debug-source-from 'sb-di) (if (sb-di:debug-source-namestring dsource) (file-source-location code-location) (lisp-source-location code-location))))) source - location for a function , and we also have FILE - SOURCE - LOCATION & co (defun file-source-location (code-location) (if (code-location-has-debug-block-info-p code-location) (source-file-source-location code-location) (fallback-source-location code-location))) (defun fallback-source-location (code-location) (let ((fun (code-location-debug-fun-fun code-location))) (cond (fun (function-source-location fun)) (t (error "Cannot find source location for: ~A " code-location))))) (defun lisp-source-location (code-location) (let ((source (prin1-to-string (sb-debug::code-location-source-form code-location 100)))) (make-location `(:source-form ,source) '(:position 1)))) (defun emacs-buffer-source-location (code-location plist) (if (code-location-has-debug-block-info-p code-location) (destructuring-bind (&key emacs-buffer emacs-position emacs-string &allow-other-keys) plist (let* ((pos (string-source-position code-location emacs-string)) (snipped (read-snippet-from-string emacs-string pos))) (make-location `(:buffer ,emacs-buffer) `(:offset ,emacs-position ,pos) `(:snippet ,snipped)))) (fallback-source-location code-location))) (defun source-file-source-location (code-location) (let* ((code-date (code-location-debug-source-created code-location)) (filename (code-location-debug-source-name code-location)) (*readtable* (guess-readtable-for-filename filename)) (source-code (get-source-code filename code-date))) (with-debootstrapping (with-input-from-string (s source-code) (let* ((pos (stream-source-position code-location s)) (snippet (read-snippet s pos))) (make-location `(:file ,filename) `(:position ,pos) `(:snippet ,snippet))))))) (defun code-location-debug-source-name (code-location) (namestring (truename (#+#.(swank-backend:with-symbol 'debug-source-name 'sb-di) sb-c::debug-source-name #-#.(swank-backend:with-symbol 'debug-source-name 'sb-di) sb-c::debug-source-namestring (sb-di::code-location-debug-source code-location))))) (defun code-location-debug-source-created (code-location) (sb-c::debug-source-created (sb-di::code-location-debug-source code-location))) (defun code-location-debug-fun-fun (code-location) (sb-di:debug-fun-fun (sb-di:code-location-debug-fun code-location))) (defun code-location-has-debug-block-info-p (code-location) (handler-case (progn (sb-di:code-location-debug-block code-location) t) (sb-di:no-debug-blocks () nil))) (defun stream-source-position (code-location stream) (let* ((cloc (sb-debug::maybe-block-start-location code-location)) (tlf-number (sb-di::code-location-toplevel-form-offset cloc)) (form-number (sb-di::code-location-form-number cloc))) (multiple-value-bind (tlf pos-map) (read-source-form tlf-number stream) (let* ((path-table (sb-di::form-number-translations tlf 0)) (path (cond ((<= (length path-table) form-number) (warn "inconsistent form-number-translations") (list 0)) (t (reverse (cdr (aref path-table form-number))))))) (source-path-source-position path tlf pos-map))))) (defun string-source-position (code-location string) (with-input-from-string (s string) (stream-source-position code-location s))) (defimplementation frame-source-location (index) (converting-errors-to-error-location (code-location-source-location (sb-di:frame-code-location (nth-frame index))))) (defun frame-debug-vars (frame) "Return a vector of debug-variables in frame." (sb-di::debug-fun-debug-vars (sb-di:frame-debug-fun frame))) (defun debug-var-value (var frame location) (ecase (sb-di:debug-var-validity var location) (:valid (sb-di:debug-var-value var frame)) ((:invalid :unknown) ':<not-available>))) (defun debug-var-info (var) Introduced by SBCL 1.0.49.76 . (let ((s (find-symbol "DEBUG-VAR-INFO" :sb-di))) (when (and s (fboundp s)) (funcall s var)))) (defimplementation frame-locals (index) (let* ((frame (nth-frame index)) (loc (sb-di:frame-code-location frame)) (vars (frame-debug-vars frame)) Since 1.0.49.76 PREPROCESS - FOR - EVAL understands SB - DEBUG::MORE (more-name (or (find-symbol "MORE" :sb-debug) 'more)) (more-context nil) (more-count nil) (more-id 0)) (when vars (let ((locals (loop for v across vars do (when (eq (sb-di:debug-var-symbol v) more-name) (incf more-id)) (case (debug-var-info v) (:more-context (setf more-context (debug-var-value v frame loc))) (:more-count (setf more-count (debug-var-value v frame loc)))) collect (list :name (sb-di:debug-var-symbol v) :id (sb-di:debug-var-id v) :value (debug-var-value v frame loc))))) (when (and more-context more-count) (setf locals (append locals (list (list :name more-name :id more-id :value (multiple-value-list (sb-c:%more-arg-values more-context 0 more-count))))))) locals)))) (defimplementation frame-var-value (frame var) (let* ((frame (nth-frame frame)) (vars (frame-debug-vars frame)) (loc (sb-di:frame-code-location frame)) (dvar (if (= var (length vars)) If VAR is out of bounds , it must be the fake var we made up for (let* ((context-var (find :more-context vars :key #'debug-var-info)) (more-context (debug-var-value context-var frame loc)) (count-var (find :more-count vars :key #'debug-var-info)) (more-count (debug-var-value count-var frame loc))) (return-from frame-var-value (multiple-value-list (sb-c:%more-arg-values more-context 0 more-count)))) (aref vars var)))) (debug-var-value dvar frame loc))) (defimplementation frame-catch-tags (index) (mapcar #'car (sb-di:frame-catches (nth-frame index)))) (defimplementation eval-in-frame (form index) (let ((frame (nth-frame index))) (funcall (the function (sb-di:preprocess-for-eval form (sb-di:frame-code-location frame))) frame))) #+#.(swank-backend::sbcl-with-restart-frame) (progn (defimplementation return-from-frame (index form) (let* ((frame (nth-frame index))) (cond ((sb-debug:frame-has-debug-tag-p frame) (let ((values (multiple-value-list (eval-in-frame form index)))) (sb-debug:unwind-to-frame-and-call frame (lambda () (values-list values))))) (t (format nil "Cannot return from frame: ~S" frame))))) (defimplementation restart-frame (index) (let ((frame (nth-frame index))) (when (sb-debug:frame-has-debug-tag-p frame) (multiple-value-bind (fname args) (sb-debug::frame-call frame) (multiple-value-bind (fun arglist) (if (and (sb-int:legal-fun-name-p fname) (fboundp fname)) (values (fdefinition fname) args) (values (sb-di:debug-fun-fun (sb-di:frame-debug-fun frame)) (sb-debug::frame-args-as-list frame))) (when (functionp fun) (sb-debug:unwind-to-frame-and-call frame (lambda () (declare (optimize (debug 0))) (apply fun arglist))))))) (format nil "Cannot restart frame: ~S" frame)))) #-#.(swank-backend::sbcl-with-restart-frame) (progn (defun sb-debug-catch-tag-p (tag) (and (symbolp tag) (not (symbol-package tag)) (string= tag :sb-debug-catch-tag))) (defimplementation return-from-frame (index form) (let* ((frame (nth-frame index)) (probe (assoc-if #'sb-debug-catch-tag-p (sb-di::frame-catches frame)))) (cond (probe (throw (car probe) (eval-in-frame form index))) (t (format nil "Cannot return from frame: ~S" frame))))) (defimplementation restart-frame (index) (let ((frame (nth-frame index))) (return-from-frame index (sb-debug::frame-call-as-list frame))))) (defimplementation format-sldb-condition (condition) (let ((sb-int:*print-condition-references* nil)) (princ-to-string condition))) (defimplementation profile (fname) (when fname (eval `(sb-profile:profile ,fname)))) (defimplementation unprofile (fname) (when fname (eval `(sb-profile:unprofile ,fname)))) (defimplementation unprofile-all () (sb-profile:unprofile) "All functions unprofiled.") (defimplementation profile-report () (sb-profile:report)) (defimplementation profile-reset () (sb-profile:reset) "Reset profiling counters.") (defimplementation profiled-functions () (sb-profile:profile)) (defimplementation profile-package (package callers methods) (declare (ignore callers methods)) (eval `(sb-profile:profile ,(package-name (find-package package))))) (defmethod emacs-inspect ((o t)) (cond ((sb-di::indirect-value-cell-p o) (label-value-line* (:value (sb-kernel:value-cell-ref o)))) (t (multiple-value-bind (text label parts) (sb-impl::inspected-parts o) (list* (string-right-trim '(#\Newline) text) '(:newline) (if label (loop for (l . v) in parts append (label-value-line l v)) (loop for value in parts for i from 0 append (label-value-line i value)))))))) (defmethod emacs-inspect ((o function)) (let ((header (sb-kernel:widetag-of o))) (cond ((= header sb-vm:simple-fun-header-widetag) (label-value-line* (:name (sb-kernel:%simple-fun-name o)) (:arglist (sb-kernel:%simple-fun-arglist o)) (:self (sb-kernel:%simple-fun-self o)) (:next (sb-kernel:%simple-fun-next o)) (:type (sb-kernel:%simple-fun-type o)) (:code (sb-kernel:fun-code-header o)))) ((= header sb-vm:closure-header-widetag) (append (label-value-line :function (sb-kernel:%closure-fun o)) `("Closed over values:" (:newline)) (loop for i below (1- (sb-kernel:get-closure-length o)) append (label-value-line i (sb-kernel:%closure-index-ref o i))))) (t (call-next-method o))))) (defmethod emacs-inspect ((o sb-kernel:code-component)) (append (label-value-line* (:code-size (sb-kernel:%code-code-size o)) (:entry-points (sb-kernel:%code-entry-points o)) (:debug-info (sb-kernel:%code-debug-info o)) (:trace-table-offset (sb-kernel:code-header-ref o sb-vm:code-trace-table-offset-slot))) `("Constants:" (:newline)) (loop for i from sb-vm:code-constants-offset below (sb-kernel:get-header-data o) append (label-value-line i (sb-kernel:code-header-ref o i))) `("Code:" (:newline) , (with-output-to-string (s) (cond ((sb-kernel:%code-debug-info o) (sb-disassem:disassemble-code-component o :stream s)) (t (sb-disassem:disassemble-memory (sb-disassem::align (+ (logandc2 (sb-kernel:get-lisp-obj-address o) sb-vm:lowtag-mask) (* sb-vm:code-constants-offset sb-vm:n-word-bytes)) (ash 1 sb-vm:n-lowtag-bits)) (ash (sb-kernel:%code-code-size o) sb-vm:word-shift) :stream s))))))) (defmethod emacs-inspect ((o sb-ext:weak-pointer)) (label-value-line* (:value (sb-ext:weak-pointer-value o)))) (defmethod emacs-inspect ((o sb-kernel:fdefn)) (label-value-line* (:name (sb-kernel:fdefn-name o)) (:function (sb-kernel:fdefn-fun o)))) (defmethod emacs-inspect :around ((o generic-function)) (append (call-next-method) (label-value-line* (:pretty-arglist (sb-pcl::generic-function-pretty-arglist o)) (:initial-methods (sb-pcl::generic-function-initial-methods o)) ))) #+(and sb-thread #.(swank-backend:with-symbol "THREAD-NAME" "SB-THREAD")) (progn (defvar *thread-id-counter* 0) (defvar *thread-id-counter-lock* (sb-thread:make-mutex :name "thread id counter lock")) (defun next-thread-id () (sb-thread:with-mutex (*thread-id-counter-lock*) (incf *thread-id-counter*))) (defparameter *thread-id-map* (make-hash-table)) (defvar *thread-id-map-lock* (sb-thread:make-mutex :name "thread id map lock")) (defimplementation spawn (fn &key name) (sb-thread:make-thread fn :name name)) (defimplementation thread-id (thread) (block thread-id (sb-thread:with-mutex (*thread-id-map-lock*) (loop for id being the hash-key in *thread-id-map* using (hash-value thread-pointer) do (let ((maybe-thread (sb-ext:weak-pointer-value thread-pointer))) (cond ((null maybe-thread) the value is gc'd , remove it manually (remhash id *thread-id-map*)) ((eq thread maybe-thread) (return-from thread-id id))))) (let ((id (next-thread-id))) (setf (gethash id *thread-id-map*) (sb-ext:make-weak-pointer thread)) id)))) (defimplementation find-thread (id) (sb-thread:with-mutex (*thread-id-map-lock*) (let ((thread-pointer (gethash id *thread-id-map*))) (if thread-pointer (let ((maybe-thread (sb-ext:weak-pointer-value thread-pointer))) (if maybe-thread maybe-thread the value is gc'd , remove it manually (progn (remhash id *thread-id-map*) nil))) nil)))) (defimplementation thread-name (thread) sometimes the name is not a string ( e.g. NIL ) (princ-to-string (sb-thread:thread-name thread))) (defimplementation thread-status (thread) (if (sb-thread:thread-alive-p thread) "Running" "Stopped")) (defimplementation make-lock (&key name) (sb-thread:make-mutex :name name)) (defimplementation call-with-lock-held (lock function) (declare (type function function)) (sb-thread:with-recursive-lock (lock) (funcall function))) (defimplementation current-thread () sb-thread:*current-thread*) (defimplementation all-threads () (sb-thread:list-all-threads)) (defimplementation interrupt-thread (thread fn) (sb-thread:interrupt-thread thread fn)) (defimplementation kill-thread (thread) (sb-thread:terminate-thread thread)) (defimplementation thread-alive-p (thread) (sb-thread:thread-alive-p thread)) (defvar *mailbox-lock* (sb-thread:make-mutex :name "mailbox lock")) (defvar *mailboxes* (list)) (declaim (type list *mailboxes*)) (defstruct (mailbox (:conc-name mailbox.)) thread (mutex (sb-thread:make-mutex)) (waitqueue (sb-thread:make-waitqueue)) (queue '() :type list)) (defun mailbox (thread) "Return THREAD's mailbox." (sb-thread:with-mutex (*mailbox-lock*) (or (find thread *mailboxes* :key #'mailbox.thread) (let ((mb (make-mailbox :thread thread))) (push mb *mailboxes*) mb)))) (defimplementation send (thread message) (let* ((mbox (mailbox thread)) (mutex (mailbox.mutex mbox))) (sb-thread:with-mutex (mutex) (setf (mailbox.queue mbox) (nconc (mailbox.queue mbox) (list message))) (sb-thread:condition-broadcast (mailbox.waitqueue mbox))))) #-sb-lutex (defun condition-timed-wait (waitqueue mutex timeout) (handler-case (let ((*break-on-signals* nil)) (sb-sys:with-deadline (:seconds timeout :override t) (sb-thread:condition-wait waitqueue mutex) t)) (sb-ext:timeout () nil))) FIXME : with - timeout does n't work properly on #+sb-lutex (defun condition-timed-wait (waitqueue mutex timeout) (declare (ignore timeout)) (sb-thread:condition-wait waitqueue mutex)) (defimplementation receive-if (test &optional timeout) (let* ((mbox (mailbox (current-thread))) (mutex (mailbox.mutex mbox)) (waitq (mailbox.waitqueue mbox))) (assert (or (not timeout) (eq timeout t))) (loop (check-slime-interrupts) (sb-thread:with-mutex (mutex) (let* ((q (mailbox.queue mbox)) (tail (member-if test q))) (when tail (setf (mailbox.queue mbox) (nconc (ldiff q tail) (cdr tail))) (return (car tail)))) (when (eq timeout t) (return (values nil t))) (condition-timed-wait waitq mutex 0.2))))) (let ((alist '()) (mutex (sb-thread:make-mutex :name "register-thread"))) (defimplementation register-thread (name thread) (declare (type symbol name)) (sb-thread:with-mutex (mutex) (etypecase thread (null (setf alist (delete name alist :key #'car))) (sb-thread:thread (let ((probe (assoc name alist))) (cond (probe (setf (cdr probe) thread)) (t (setf alist (acons name thread alist)))))))) nil) (defimplementation find-registered (name) (sb-thread:with-mutex (mutex) (cdr (assoc name alist))))) ) (defimplementation quit-lisp () #+sb-thread (dolist (thread (remove (current-thread) (all-threads))) (ignore-errors (sb-thread:terminate-thread thread))) (sb-ext:quit)) Trace implementations In , we have : < name > can be a normal name or a ( setf name ) (defun toggle-trace-aux (fspec &rest args) (cond ((member fspec (eval '(trace)) :test #'equal) (eval `(untrace ,fspec)) (format nil "~S is now untraced." fspec)) (t (eval `(trace ,@(if args `(:encapsulate nil) (list)) ,fspec ,@args)) (format nil "~S is now traced." fspec)))) (defun process-fspec (fspec) (cond ((consp fspec) (ecase (first fspec) ((:defun :defgeneric) (second fspec)) ((:defmethod) `(method ,@(rest fspec))) ((:labels) `(labels ,(process-fspec (second fspec)) ,(third fspec))) ((:flet) `(flet ,(process-fspec (second fspec)) ,(third fspec))))) (t fspec))) (defimplementation toggle-trace (spec) (ecase (car spec) ((setf) (toggle-trace-aux spec)) ((:defmethod) (toggle-trace-aux `(sb-pcl::fast-method ,@(rest (process-fspec spec))))) ((:defgeneric) (toggle-trace-aux (second spec) :methods t)) ((:call) (destructuring-bind (caller callee) (cdr spec) (toggle-trace-aux callee :wherein (list (process-fspec caller))))))) (defimplementation make-weak-key-hash-table (&rest args) #+#.(swank-backend::sbcl-with-weak-hash-tables) (apply #'make-hash-table :weakness :key args) #-#.(swank-backend::sbcl-with-weak-hash-tables) (apply #'make-hash-table args)) (defimplementation make-weak-value-hash-table (&rest args) #+#.(swank-backend::sbcl-with-weak-hash-tables) (apply #'make-hash-table :weakness :value args) #-#.(swank-backend::sbcl-with-weak-hash-tables) (apply #'make-hash-table args)) (defimplementation hash-table-weakness (hashtable) #+#.(swank-backend::sbcl-with-weak-hash-tables) (sb-ext:hash-table-weakness hashtable)) #-win32 (defimplementation save-image (filename &optional restart-function) (flet ((restart-sbcl () (sb-debug::enable-debugger) (setf sb-impl::*descriptor-handlers* nil) (funcall restart-function))) (let ((pid (sb-posix:fork))) (cond ((= pid 0) (sb-debug::disable-debugger) (apply #'sb-ext:save-lisp-and-die filename (when restart-function (list :toplevel #'restart-sbcl)))) (t (multiple-value-bind (rpid status) (sb-posix:waitpid pid 0) (assert (= pid rpid)) (assert (and (sb-posix:wifexited status) (zerop (sb-posix:wexitstatus status)))))))))) #+unix (progn (sb-alien:define-alien-routine ("execv" sys-execv) sb-alien:int (program sb-alien:c-string) (argv (* sb-alien:c-string))) (defun execv (program args) "Replace current executable with another one." (let ((a-args (sb-alien:make-alien sb-alien:c-string (+ 1 (length args))))) (unwind-protect (progn (loop for index from 0 by 1 and item in (append args '(nil)) do (setf (sb-alien:deref a-args index) item)) (when (minusp (sys-execv program a-args)) (error "execv(3) returned."))) (sb-alien:free-alien a-args)))) (defun runtime-pathname () #+#.(swank-backend:with-symbol '*runtime-pathname* 'sb-ext) sb-ext:*runtime-pathname* #-#.(swank-backend:with-symbol '*runtime-pathname* 'sb-ext) (car sb-ext:*posix-argv*)) (defimplementation exec-image (image-file args) (loop with fd-arg = (loop for arg in args and key = "" then arg when (string-equal key "--swank-fd") return (parse-integer arg)) for my-fd from 3 to 1024 when (/= my-fd fd-arg) do (ignore-errors (sb-posix:fcntl my-fd sb-posix:f-setfd 1))) (let* ((self-string (pathname-to-filename (runtime-pathname)))) (execv self-string (apply 'list self-string "--core" image-file args))))) (defimplementation make-fd-stream (fd external-format) (sb-sys:make-fd-stream fd :input t :output t :element-type 'character :buffering :full :dual-channel-p t :external-format external-format)) (defimplementation call-with-io-timeout (function &key seconds) (handler-case (sb-sys:with-deadline (:seconds seconds) (funcall function)) (sb-sys:deadline-timeout () nil))) #-win32 (defimplementation background-save-image (filename &key restart-function completion-function) (flet ((restart-sbcl () (sb-debug::enable-debugger) (setf sb-impl::*descriptor-handlers* nil) (funcall restart-function))) (multiple-value-bind (pipe-in pipe-out) (sb-posix:pipe) (let ((pid (sb-posix:fork))) (cond ((= pid 0) (sb-posix:close pipe-in) (sb-debug::disable-debugger) (apply #'sb-ext:save-lisp-and-die filename (when restart-function (list :toplevel #'restart-sbcl)))) (t (sb-posix:close pipe-out) (sb-sys:add-fd-handler pipe-in :input (lambda (fd) (sb-sys:invalidate-descriptor fd) (sb-posix:close fd) (multiple-value-bind (rpid status) (sb-posix:waitpid pid 0) (assert (= pid rpid)) (assert (sb-posix:wifexited status)) (funcall completion-function (zerop (sb-posix:wexitstatus status)))))))))))) (defun deinit-log-output () (setf (symbol-value (find-symbol "*LOG-OUTPUT*" 'swank)) nil)) (pushnew 'deinit-log-output sb-ext:*save-hooks*)
5d3bf18b46ebf044338513dc102fa49d6ed0be48a9c504a7f8c79198fc50b4d8
cartazio/tlaps
m_dep.mli
* Copyright ( C ) 2011 INRIA and Microsoft Corporation * Copyright (C) 2011 INRIA and Microsoft Corporation *) open M_t;; module / val external_deps : mule_ Property.wrapped -> Util.Coll.Hs.t;; (* tlapm.ml *) val schedule : modctx -> modctx * mule list;;
null
https://raw.githubusercontent.com/cartazio/tlaps/562a34c066b636da7b921ae30fc5eacf83608280/src/module/m_dep.mli
ocaml
tlapm.ml
* Copyright ( C ) 2011 INRIA and Microsoft Corporation * Copyright (C) 2011 INRIA and Microsoft Corporation *) open M_t;; module / val external_deps : mule_ Property.wrapped -> Util.Coll.Hs.t;; val schedule : modctx -> modctx * mule list;;
2a3cf6a95b8d732518181afbc066ac0b78e7e2450b3db66f1626b39b14cc57c3
mikpe/pdp10-tools
sim_arithmetic_tests.erl
-*- erlang - indent - level : 2 -*- %%% simulator for pdp10 - elf Copyright ( C ) 2020 %%% This file is part of pdp10 - tools . %%% pdp10 - tools 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. %%% pdp10 - tools 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 pdp10 - tools . If not , see < / > . %%% %%%============================================================================= %%% Test cases for 2.6 Arithmetic Testing -module(sim_arithmetic_tests). -include("../src/sim_core.hrl"). -include_lib("eunit/include/eunit.hrl"). -define(DEFAULT_FLAGS, (1 bsl ?PDP10_PF_USER)). for AOJ / AOS / SOJ / SOS when carry 0 and 1 get set (?DEFAULT_FLAGS bor (1 bsl ?PDP10_PF_CARRY_0) bor (1 bsl ?PDP10_PF_CARRY_1))). -define(LOW18(X), ((X) band ((1 bsl 18) - 1))). -define(LOW36(X), ((X) band ((1 bsl 36) - 1))). -define(INSN(OP, AC, I, X, Y), (((OP) bsl (35 - 8)) bor ((AC) bsl (35 - 12)) bor ((I) bsl (35 - 13)) bor ((X) bsl (35 - 17)) bor ?LOW18(Y))). -define(COMMA2(LEFT, RIGHT), ((?LOW18(LEFT) bsl 18) bor ?LOW18(RIGHT))). % LEFT,,RIGHT in MACRO-10 -define(EA(S, O), #ea{section = S, offset = O, islocal = false}). -define(AC(A), ?EA(1, A)). -define(INSN_INVALID, ?INSN(0, 0, 0, 0, 0)). -define(OP_MOVEI, 8#201). -define(OP_MOVSI, 8#205). -define(OP_MOVNI, 8#211). -define(OP_AOBJP, 8#252). -define(OP_AOBJN, 8#253). -define(OP_CAI, 8#300). -define(OP_CAIL, 8#301). -define(OP_CAIE, 8#302). -define(OP_CAILE, 8#303). -define(OP_CAIA, 8#304). -define(OP_CAIGE, 8#305). -define(OP_CAIN, 8#306). -define(OP_CAIG, 8#307). -define(OP_CAM, 8#310). -define(OP_CAML, 8#311). -define(OP_CAME, 8#312). -define(OP_CAMLE, 8#313). -define(OP_CAMA, 8#314). -define(OP_CAMGE, 8#315). -define(OP_CAMN, 8#316). -define(OP_CAMG, 8#317). -define(OP_JUMP, 8#320). -define(OP_JUMPL, 8#321). -define(OP_JUMPE, 8#322). -define(OP_JUMPLE, 8#323). -define(OP_JUMPA, 8#324). -define(OP_JUMPGE, 8#325). -define(OP_JUMPN, 8#326). -define(OP_JUMPG, 8#327). -define(OP_SKIP, 8#330). -define(OP_SKIPL, 8#331). -define(OP_SKIPE, 8#332). -define(OP_SKIPLE, 8#333). -define(OP_SKIPA, 8#334). -define(OP_SKIPGE, 8#335). -define(OP_SKIPN, 8#336). -define(OP_SKIPG, 8#337). -define(OP_AOJ, 8#340). -define(OP_AOJL, 8#341). -define(OP_AOJE, 8#342). -define(OP_AOJLE, 8#343). -define(OP_AOJA, 8#344). -define(OP_AOJGE, 8#345). -define(OP_AOJN, 8#346). -define(OP_AOJG, 8#347). -define(OP_AOS, 8#350). -define(OP_AOSL, 8#351). -define(OP_AOSE, 8#352). -define(OP_AOSLE, 8#353). -define(OP_AOSA, 8#354). -define(OP_AOSGE, 8#355). -define(OP_AOSN, 8#356). -define(OP_AOSG, 8#357). -define(OP_SOJ, 8#360). -define(OP_SOJL, 8#361). -define(OP_SOJE, 8#362). -define(OP_SOJLE, 8#363). -define(OP_SOJA, 8#364). -define(OP_SOJGE, 8#365). -define(OP_SOJN, 8#366). -define(OP_SOJG, 8#367). -define(OP_SOS, 8#370). -define(OP_SOSL, 8#371). -define(OP_SOSE, 8#372). -define(OP_SOSLE, 8#373). -define(OP_SOSA, 8#374). -define(OP_SOSGE, 8#375). -define(OP_SOSN, 8#376). -define(OP_SOSG, 8#377). 2.6.1 Add One to Both Halves of AC and Jump = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = AOBJP - Add One to Both Halves of AC and Jump if Positive aobjp_test() -> Prog1 = [ {1, 8#100, ?INSN(?OP_MOVSI, 1, 0, 0, -2)} % 1,,100/ MOVSI 1,-2 , {1, 8#101, ?INSN(?OP_AOBJP, 1, 0, 0, 8#103)} % 1,,101/ AOBJP 1,103 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > ], expect(Prog1, [], {1, 8#102}, ?DEFAULT_FLAGS, % no jump [{?AC(1), ?COMMA2(-1, 1)} % AC1 = -1,,1 ]), Prog2 = [ {1, 8#100, ?INSN(?OP_MOVSI, 1, 0, 0, -1)} % 1,,100/ MOVSI 1,-1 , {1, 8#101, ?INSN(?OP_AOBJP, 1, 0, 0, 8#103)} % 1,,101/ AOBJP 1,103 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > ], expect(Prog2, [], {1, 8#103}, ?DEFAULT_FLAGS, % jump AC1 = 0,,1 ]). AOBJN - Add One to Both Halves of AC and Jump if Negative aobjn_test() -> Prog1 = [ {1, 8#100, ?INSN(?OP_MOVSI, 1, 0, 0, -2)} % 1,,100/ MOVSI 1,-2 1,,101/ AOBJN 1,103 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > ], expect(Prog1, [], {1, 8#103}, ?DEFAULT_FLAGS, % jump [{?AC(1), ?COMMA2(-1, 1)} % AC1 = -1,,1 ]), Prog2 = [ {1, 8#100, ?INSN(?OP_MOVSI, 1, 0, 0, -1)} % 1,,100/ MOVSI 1,-1 1,,101/ AOBJN 1,103 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > ], expect(Prog2, [], {1, 8#102}, ?DEFAULT_FLAGS, % no jump AC1 = 0,,1 ]). 2.6.2 Comparisons , , and Jumps = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = CAI - Compare AC Immediate and Skip if Condition Satisfied cai_test() -> Prog = [ {1, 8#100, ?INSN(?OP_CAI, 0, 0, 0, 0)} % 1,,100/ CAI , {1, 8#101, ?INSN_INVALID} % 1,,101/ <invalid> ], expect(Prog, [], {1, 8#101}, ?DEFAULT_FLAGS, []). % no skip cail_test() -> Prog1 = [ {1, 8#100, ?INSN(?OP_MOVNI, 1, 0, 0, 3)} % 1,,100/ MOVNI 1,3 , {1, 8#101, ?INSN(?OP_CAIL, 1, 0, 0, 2)} % 1,,101/ CAIL 1,2 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > ], expect(Prog1, [], {1, 8#103}, ?DEFAULT_FLAGS, []), % skip Prog2 = 1,,100/ MOVEI 1,3 , {1, 8#101, ?INSN(?OP_CAIL, 1, 0, 0, 2)} % 1,,101/ CAIL 1,2 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > ], expect(Prog2, [], {1, 8#102}, ?DEFAULT_FLAGS, []). % no skip caie_test() -> Prog1 = 1,,100/ MOVEI 1,2 1,,101/ CAIE 1,2 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > ], expect(Prog1, [], {1, 8#103}, ?DEFAULT_FLAGS, []), % skip Prog2 = 1,,100/ MOVEI 1,3 1,,101/ CAIE 1,2 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > ], expect(Prog2, [], {1, 8#102}, ?DEFAULT_FLAGS, []). % no skip caile_test() -> Prog1 = [ {1, 8#100, ?INSN(?OP_MOVNI, 1, 0, 0, 3)} % 1,,100/ MOVNI 1,3 1,,101/ CAILE 1,2 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > ], expect(Prog1, [], {1, 8#103}, ?DEFAULT_FLAGS, []), % skip Prog2 = 1,,100/ MOVEI 1,2 1,,101/ CAILE 1,2 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > ], expect(Prog2, [], {1, 8#103}, ?DEFAULT_FLAGS, []), % skip Prog3 = 1,,100/ MOVEI 1,3 1,,101/ CAILE 1,2 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > ], expect(Prog3, [], {1, 8#102}, ?DEFAULT_FLAGS, []). % no skip caia_test() -> Prog = [ {1, 8#100, ?INSN(?OP_CAIA, 0, 0, 0, 0)} % 1,,100/ CAIA , {1, 8#101, ?INSN_INVALID} % 1,,101/ <invalid> , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> ], expect(Prog, [], {1, 8#102}, ?DEFAULT_FLAGS, []). % skip caige_test() -> Prog1 = 1,,100/ MOVEI 1,3 1,,101/ CAIGE 1,2 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > ], expect(Prog1, [], {1, 8#103}, ?DEFAULT_FLAGS, []), % skip Prog2 = 1,,100/ MOVEI 1,2 1,,101/ CAIGE 1,2 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > ], expect(Prog2, [], {1, 8#103}, ?DEFAULT_FLAGS, []), % skip Prog3 = [ {1, 8#100, ?INSN(?OP_MOVNI, 1, 0, 0, 3)} % 1,,100/ MOVNI 1,3 1,,101/ CAIGE 1,2 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > ], expect(Prog3, [], {1, 8#102}, ?DEFAULT_FLAGS, []). % no skip cain_test() -> Prog1 = 1,,100/ MOVEI 1,3 1,,101/ CAIN 1,2 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > ], expect(Prog1, [], {1, 8#103}, ?DEFAULT_FLAGS, []), % skip Prog2 = 1,,100/ MOVEI 1,2 1,,101/ CAIN 1,2 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > ], expect(Prog2, [], {1, 8#102}, ?DEFAULT_FLAGS, []). % no skip caig_test() -> Prog1 = 1,,100/ MOVEI 1,3 1,,101/ CAIG 1,2 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > ], expect(Prog1, [], {1, 8#103}, ?DEFAULT_FLAGS, []), % skip Prog2 = [ {1, 8#100, ?INSN(?OP_MOVNI, 1, 0, 0, 3)} % 1,,100/ MOVNI 1,3 1,,101/ CAIG 1,2 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > ], expect(Prog2, [], {1, 8#102}, ?DEFAULT_FLAGS, []). % no skip CAM - Compare AC with Memory and Skip if Condition Satisfied cam_test() -> Prog = [ {1, 8#100, ?INSN(?OP_CAM, 0, 0, 0, 8#150)} % 1,,100/ CAM 150 , {1, 8#101, ?INSN_INVALID} % 1,,101/ <invalid> , {1, 8#150, 2} % 1,,150/ 0,,2 ], expect(Prog, [], {1, 8#101}, ?DEFAULT_FLAGS, []). % no skip caml_test() -> Prog1 = [ {1, 8#100, ?INSN(?OP_MOVNI, 1, 0, 0, 3)} % 1,,100/ MOVNI 1,3 1,,101/ CAML 1,150 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > , {1, 8#150, 2} % 1,,150/ 0,,2 ], expect(Prog1, [], {1, 8#103}, ?DEFAULT_FLAGS, []), % skip Prog2 = 1,,100/ MOVEI 1,3 1,,101/ CAML 1,150 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > , {1, 8#150, 2} % 1,,150/ 0,,2 ], expect(Prog2, [], {1, 8#102}, ?DEFAULT_FLAGS, []). % no skip came_test() -> Prog1 = 1,,100/ MOVEI 1,2 1,,101/ CAME 1,150 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > , {1, 8#150, 2} % 1,,150/ 0,,2 ], expect(Prog1, [], {1, 8#103}, ?DEFAULT_FLAGS, []), % skip Prog2 = 1,,100/ MOVEI 1,3 1,,101/ CAME 1,150 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > , {1, 8#150, 2} % 1,,150/ 0,,2 ], expect(Prog2, [], {1, 8#102}, ?DEFAULT_FLAGS, []). % no skip camle_test() -> Prog1 = [ {1, 8#100, ?INSN(?OP_MOVNI, 1, 0, 0, 3)} % 1,,100/ MOVNI 1,3 1,,101/ CAMLE 1,150 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > , {1, 8#150, 2} % 1,,150/ 0,,2 ], expect(Prog1, [], {1, 8#103}, ?DEFAULT_FLAGS, []), % skip Prog2 = 1,,100/ MOVEI 1,2 1,,101/ CAMLE 1,150 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > , {1, 8#150, 2} % 1,,150/ 0,,2 ], expect(Prog2, [], {1, 8#103}, ?DEFAULT_FLAGS, []), % skip Prog3 = 1,,100/ MOVEI 1,3 1,,101/ CAMLE 1,150 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > , {1, 8#150, 2} % 1,,150/ 0,,2 ], expect(Prog3, [], {1, 8#102}, ?DEFAULT_FLAGS, []). % no skip cama_test() -> Prog = 1,,100/ CAMA 150 , {1, 8#101, ?INSN_INVALID} % 1,,101/ <invalid> , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> , {1, 8#150, 2} % 1,,150/ 0,,2 ], expect(Prog, [], {1, 8#102}, ?DEFAULT_FLAGS, []). % skip camge_test() -> Prog1 = 1,,100/ MOVEI 1,3 1,,101/ CAMGE 1,150 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > , {1, 8#150, 2} % 1,,150/ 0,,2 ], expect(Prog1, [], {1, 8#103}, ?DEFAULT_FLAGS, []), % skip Prog2 = 1,,100/ MOVEI 1,2 1,,101/ CAMGE 1,150 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > , {1, 8#150, 2} % 1,,150/ 0,,2 ], expect(Prog2, [], {1, 8#103}, ?DEFAULT_FLAGS, []), % skip Prog3 = [ {1, 8#100, ?INSN(?OP_MOVNI, 1, 0, 0, 3)} % 1,,100/ MOVNI 1,3 1,,101/ CAMGE 1,150 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > , {1, 8#150, 2} % 1,,150/ 0,,2 ], expect(Prog3, [], {1, 8#102}, ?DEFAULT_FLAGS, []). % no skip camn_test() -> Prog1 = 1,,100/ MOVEI 1,3 1,,101/ CAMN 1,150 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > , {1, 8#150, 2} % 1,,150/ 0,,2 ], expect(Prog1, [], {1, 8#103}, ?DEFAULT_FLAGS, []), % skip Prog2 = 1,,100/ MOVEI 1,2 1,,101/ CAMN 1,150 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > , {1, 8#150, 2} % 1,,150/ 0,,2 ], expect(Prog2, [], {1, 8#102}, ?DEFAULT_FLAGS, []). % no skip camg_test() -> Prog1 = 1,,100/ MOVEI 1,3 1,,101/ CAMG 1,150 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > , {1, 8#150, ?LOW36(-2)} % 1,,150/ -2 ], expect(Prog1, [], {1, 8#103}, ?DEFAULT_FLAGS, []), % skip Prog2 = [ {1, 8#100, ?INSN(?OP_MOVNI, 1, 0, 0, 3)} % 1,,100/ MOVNI 1,3 1,,101/ CAMG 1,150 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > , {1, 8#150, ?LOW36(-2)} % 1,,150/ -2 ], expect(Prog2, [], {1, 8#102}, ?DEFAULT_FLAGS, []). % no skip JUMP - Jump if AC Condition Satisfied jump_test() -> Prog = [ {1, 8#100, ?INSN(?OP_JUMP, 0, 0, 0, 0)} % 1,,100/ JUMP , {1, 8#101, ?INSN_INVALID} % 1,,101/ <invalid> ], expect(Prog, [], {1, 8#101}, ?DEFAULT_FLAGS, []). % no jump jumpl_test() -> Prog1 = [ {1, 8#100, ?INSN(?OP_MOVNI, 1, 0, 0, 3)} % 1,,100/ MOVNI 1,3 1,,101/ JUMPL 1,103 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > ], expect(Prog1, [], {1, 8#103}, ?DEFAULT_FLAGS, []), % jump Prog2 = 1,,100/ MOVEI 1,3 1,,101/ JUMPL 1,103 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > ], expect(Prog2, [], {1, 8#102}, ?DEFAULT_FLAGS, []). % no jump jumpe_test() -> Prog1 = 1,,100/ MOVEI 1,0 1,,101/ JUMPE 1,103 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > ], expect(Prog1, [], {1, 8#103}, ?DEFAULT_FLAGS, []), % jump Prog2 = 1,,100/ MOVEI 1,3 1,,101/ JUMPE 1,103 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > ], expect(Prog2, [], {1, 8#102}, ?DEFAULT_FLAGS, []). % no jump jumple_test() -> Prog1 = [ {1, 8#100, ?INSN(?OP_MOVNI, 1, 0, 0, 3)} % 1,,100/ MOVNI 1,3 1,,101/ JUMPLE 1,103 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > ], expect(Prog1, [], {1, 8#103}, ?DEFAULT_FLAGS, []), % jump Prog2 = 1,,100/ MOVEI 1,0 1,,101/ JUMPLE 1,103 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > ], expect(Prog2, [], {1, 8#103}, ?DEFAULT_FLAGS, []), % jump Prog3 = 1,,100/ MOVEI 1,3 1,,101/ JUMPLE 1,103 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > ], expect(Prog3, [], {1, 8#102}, ?DEFAULT_FLAGS, []). % no jump jumpa_test() -> Prog = 1,,100/ JUMPA 102 , {1, 8#101, ?INSN_INVALID} % 1,,101/ <invalid> , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> ], expect(Prog, [], {1, 8#102}, ?DEFAULT_FLAGS, []). % jump jumpge_test() -> Prog1 = 1,,100/ MOVEI 1,3 1,,101/ JUMPGE 1,103 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > ], expect(Prog1, [], {1, 8#103}, ?DEFAULT_FLAGS, []), % jump Prog2 = 1,,100/ MOVEI 1,0 1,,101/ JUMPGE 1,103 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > ], expect(Prog2, [], {1, 8#103}, ?DEFAULT_FLAGS, []), % jump Prog3 = [ {1, 8#100, ?INSN(?OP_MOVNI, 1, 0, 0, 3)} % 1,,100/ MOVNI 1,3 1,,101/ JUMPGE 1,103 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > ], expect(Prog3, [], {1, 8#102}, ?DEFAULT_FLAGS, []). % no jump jumpn_test() -> Prog1 = 1,,100/ MOVEI 1,3 1,,101/ JUMPN 1,103 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > ], expect(Prog1, [], {1, 8#103}, ?DEFAULT_FLAGS, []), % jump Prog2 = 1,,100/ MOVEI 1,0 1,,101/ JUMPN 1,103 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > ], expect(Prog2, [], {1, 8#102}, ?DEFAULT_FLAGS, []). % no jump jumpg_test() -> Prog1 = 1,,100/ MOVEI 1,3 1,,101/ JUMPG 1,103 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > ], expect(Prog1, [], {1, 8#103}, ?DEFAULT_FLAGS, []), % jump Prog2 = [ {1, 8#100, ?INSN(?OP_MOVNI, 1, 0, 0, 3)} % 1,,100/ MOVNI 1,3 1,,101/ JUMPG 1,103 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > ], expect(Prog2, [], {1, 8#102}, ?DEFAULT_FLAGS, []). % no jump %% SKIP - Skip if Memory Condition Satisfied skip_test() -> Prog = [ {1, 8#100, ?INSN(?OP_MOVEI, 0, 0, 0, 8#42)} % 1,,100/ MOVEI 0,42 1,,101/ SKIP 150 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> , {1, 8#150, 2} % 1,,150/ 2 ], expect(Prog, [], {1, 8#102}, ?DEFAULT_FLAGS, % no skip AC(0 ) = 42 skipl_test() -> Prog1 = 1,,100/ SKIPL 1,150 , {1, 8#101, ?INSN_INVALID} % 1,,101/ <invalid> , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> , {1, 8#150, ?LOW36(-2)} % 1,,150/ -2 ], expect(Prog1, [], {1, 8#102}, ?DEFAULT_FLAGS, % skip [{?AC(1), ?LOW36(-2)}]), % AC1 = -2 Prog2 = 1,,100/ SKIPL 1,150 , {1, 8#101, ?INSN_INVALID} % 1,,101/ <invalid> , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> , {1, 8#150, 2} % 1,,150/ 2 ], expect(Prog2, [], {1, 8#101}, ?DEFAULT_FLAGS, % no skip AC1 = 2 skipe_test() -> Prog1 = 1,,100/ SKIPE 1,150 , {1, 8#101, ?INSN_INVALID} % 1,,101/ <invalid> , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> , {1, 8#150, 0} % 1,,150/ 0 ], expect(Prog1, [], {1, 8#102}, ?DEFAULT_FLAGS, []), % skip Prog2 = 1,,100/ SKIPE 1,150 , {1, 8#101, ?INSN_INVALID} % 1,,101/ <invalid> , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> , {1, 8#150, 2} % 1,,150/ 0,,2 ], expect(Prog2, [], {1, 8#101}, ?DEFAULT_FLAGS, % no skip AC1 = 2 skiple_test() -> Prog1 = 1,,100/ SKIPLE 1,150 , {1, 8#101, ?INSN_INVALID} % 1,,101/ <invalid> , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> , {1, 8#150, ?LOW36(-2)} % 1,,150/ -2 ], expect(Prog1, [], {1, 8#102}, ?DEFAULT_FLAGS, % [{?AC(1), ?LOW36(-2)}]), % AC1 = -2 Prog2 = 1,,100/ SKIPLE 1,150 , {1, 8#101, ?INSN_INVALID} % 1,,101/ <invalid> , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> , {1, 8#150, 0} % 1,,150/ 0 ], expect(Prog2, [], {1, 8#102}, ?DEFAULT_FLAGS, % skip [{?AC(1), 0}]), % AC1 = 0 Prog3 = 1,,100/ SKIPLE 1,150 , {1, 8#101, ?INSN_INVALID} % 1,,101/ <invalid> , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> , {1, 8#150, 2} % 1,,150/ 2 ], expect(Prog3, [], {1, 8#101}, ?DEFAULT_FLAGS, % no skip AC1 = 2 skipa_test() -> Prog = 1,,100/ SKIPA 1,150 , {1, 8#101, ?INSN_INVALID} % 1,,101/ <invalid> , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> , {1, 8#150, 2} % 1,,150/ 2 ], expect(Prog, [], {1, 8#102}, ?DEFAULT_FLAGS, % skip AC1 = 2 skipge_test() -> Prog1 = 1,,100/ SKIPGE 1,150 , {1, 8#101, ?INSN_INVALID} % 1,,101/ <invalid> , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> , {1, 8#150, 2} % 1,,150/ 2 ], expect(Prog1, [], {1, 8#102}, ?DEFAULT_FLAGS, % skip AC1 = 2 Prog2 = 1,,100/ SKIPGE 1,150 , {1, 8#101, ?INSN_INVALID} % 1,,101/ <invalid> , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> , {1, 8#150, 0} % 1,,150/ 0 ], expect(Prog2, [], {1, 8#102}, ?DEFAULT_FLAGS, % skip [{?AC(1), 0}]), % AC1 = 0 Prog3 = 1,,100/ SKIPGE 1,150 , {1, 8#101, ?INSN_INVALID} % 1,,101/ <invalid> , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> , {1, 8#150, ?LOW36(-2)} % 1,,150/ -2 ], expect(Prog3, [], {1, 8#101}, ?DEFAULT_FLAGS, % no skip [{?AC(1), ?LOW36(-2)}]). % AC1 = -2 skipn_test() -> Prog1 = 1,,100/ SKIPN 1,150 , {1, 8#101, ?INSN_INVALID} % 1,,101/ <invalid> , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> , {1, 8#150, 2} % 1,,150/ 2 ], expect(Prog1, [], {1, 8#102}, ?DEFAULT_FLAGS, % skip ) = 2 Prog2 = 1,,100/ SKIPN 1,150 , {1, 8#101, ?INSN_INVALID} % 1,,101/ <invalid> , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> , {1, 8#150, 0} % 1,,150/ 0 ], expect(Prog2, [], {1, 8#101}, ?DEFAULT_FLAGS, % no skip ) = 0 skipg_test() -> Prog1 = 1,,100/ SKIPG 1,150 , {1, 8#101, ?INSN_INVALID} % 1,,101/ <invalid> , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> , {1, 8#150, 2} % 1,,150/ 2 ], expect(Prog1, [], {1, 8#102}, ?DEFAULT_FLAGS, % skip ) = 2 Prog2 = 1,,100/ SKIPG 1,150 , {1, 8#101, ?INSN_INVALID} % 1,,101/ <invalid> , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> , {1, 8#150, ?LOW36(-2)} % 1,,150/ -2 ], expect(Prog2, [], {1, 8#101}, ?DEFAULT_FLAGS, % no skip [{?AC(1), ?LOW36(-2)}]). % AC(1) = -2 AOJ - Add One to AC and Jump if Condition Satisfied aoj_test() -> Prog = 1,,100/ MOVEI 1,2 1,,101/ AOJ 1 , , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> ], expect(Prog, [], {1, 8#102}, ?DEFAULT_FLAGS, % no jump ) = 3 aojl_test() -> Prog1 = [ {1, 8#100, ?INSN(?OP_MOVNI, 1, 0, 0, 2)} % 1,,100/ MOVNI 1,2 1,,101/ AOJL 1,103 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > ], expect(Prog1, [], {1, 8#103}, ?DEFAULT_FLAGS, % jump ) = -1 Prog2 = 1,,100/ MOVEI 1,2 1,,101/ AOJL 1,103 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > ], expect(Prog2, [], {1, 8#102}, ?DEFAULT_FLAGS, % no jump ) = 3 aoje_test() -> Prog1 = 1,,100/ MOVNI 1,1 1,,101/ AOJE 1,103 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > ], jump , carry 0 and 1 ) = 0 Prog2 = 1,,100/ MOVEI 1,2 1,,101/ AOJE 1,103 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > ], expect(Prog2, [], {1, 8#102}, ?DEFAULT_FLAGS, % no jump ) = 3 aojle_test() -> Prog1 = [ {1, 8#100, ?INSN(?OP_MOVNI, 1, 0, 0, 2)} % 1,,100/ MOVNI 1,2 1,,101/ AOJLE 1,103 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > ], expect(Prog1, [], {1, 8#103}, ?DEFAULT_FLAGS, % jump ) = -1 Prog2 = 1,,100/ MOVNI 1,1 1,,101/ AOJLE 1,103 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > ], jump , carry 0 and 1 ) = 0 Prog3 = 1,,100/ MOVEI 1,2 1,,101/ AOJLE 1,103 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > ], expect(Prog3, [], {1, 8#102}, ?DEFAULT_FLAGS, % no jump ) = 3 aoja_test() -> Prog = 1,,100/ MOVEI 1,2 1,,101/ AOJA 1,103 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > ], expect(Prog, [], {1, 8#103}, ?DEFAULT_FLAGS, % jump ) = 3 aojge_test() -> Prog1 = 1,,100/ MOVEI 1,2 1,,101/ AOJGE 1,103 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > ], expect(Prog1, [], {1, 8#103}, ?DEFAULT_FLAGS, % jump ) = 3 Prog2 = 1,,100/ MOVNI 1,1 1,,101/ AOJGE 1,103 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > ], jump , carry 0 and 1 ) = 0 Prog3 = [ {1, 8#100, ?INSN(?OP_MOVNI, 1, 0, 0, 2)} % 1,,100/ MOVNI 1,2 1,,101/ AOJGE 1,103 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > ], expect(Prog3, [], {1, 8#102}, ?DEFAULT_FLAGS, % no jump ) = -1 aojn_test() -> Prog1 = 1,,100/ MOVEI 1,2 1,,101/ AOJN 1,103 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > ], expect(Prog1, [], {1, 8#103}, ?DEFAULT_FLAGS, % jump ) = 3 Prog2 = 1,,100/ MOVNI 1,1 1,,101/ AOJN 1,103 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > ], no jump , carry 0 and 1 ) = 0 aojg_test() -> Prog1 = 1,,100/ MOVEI 1,2 1,,101/ AOJG 1,103 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > ], expect(Prog1, [], {1, 8#103}, ?DEFAULT_FLAGS, % jump ) = 3 Prog2 = [ {1, 8#100, ?INSN(?OP_MOVNI, 1, 0, 0, 2)} % 1,,100/ MOVNI 1,2 1,,101/ AOJG 1,103 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > ], expect(Prog2, [], {1, 8#102}, ?DEFAULT_FLAGS, % no jump ) = -1 AOS - Add One to Memory and Skip if Condition Satisfied aos_test() -> Prog = 1,,101/ AOS 1,150 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> , {1, 8#150, ?LOW36(2)} % 1,,150/ 2 ], expect(Prog, [], {1, 8#102}, ?DEFAULT_FLAGS, % no jump C(1,,150 ) = 3 ) = 3 aosl_test() -> Prog1 = 1,,101/ AOSL 1,150 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > , {1, 8#150, ?LOW36(-2)} % 1,,150/ -2 ], expect(Prog1, [], {1, 8#103}, ?DEFAULT_FLAGS, % jump C(1,,150 ) = -1 ) = -1 Prog2 = 1,,101/ AOSL 1,150 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > , {1, 8#150, ?LOW36(2)} % 1,,150/ 2 ], expect(Prog2, [], {1, 8#102}, ?DEFAULT_FLAGS, % no jump C(1,,150 ) = 3 ) = 3 aose_test() -> Prog1 = 1,,101/ AOSE 1,150 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > , {1, 8#150, ?LOW36(-1)} % 1,,150/ -1 ], jump , carry 0 and 1 C(1,,150 ) = 0 ) = 0 Prog2 = 1,,101/ AOSE 1,150 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > , {1, 8#150, ?LOW36(2)} % 1,,150/ 2 ], expect(Prog2, [], {1, 8#102}, ?DEFAULT_FLAGS, % no jump C(1,,150 ) = 3 ) = 3 aosle_test() -> Prog1 = 1,,101/ AOSLE 1,150 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > , {1, 8#150, ?LOW36(-2)} % 1,,150/ -2 ], expect(Prog1, [], {1, 8#103}, ?DEFAULT_FLAGS, % jump C(1,,150 ) = -1 ) = -1 Prog2 = 1,,101/ AOSLE 1,150 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > , {1, 8#150, ?LOW36(-1)} % 1,,150/ -1 ], jump , carry 0 and 1 C(1,,150 ) = 0 ) = 0 Prog3 = 1,,101/ AOSLE 1,150 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > , {1, 8#150, ?LOW36(2)} % 1,,150/ 2 ], expect(Prog3, [], {1, 8#102}, ?DEFAULT_FLAGS, % no jump C(1,,150 ) = 3 ) = 3 aosa_test() -> Prog = 1,,101/ AOSA 1,150 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > , {1, 8#150, ?LOW36(2)} % 1,,150/ 2 ], expect(Prog, [], {1, 8#103}, ?DEFAULT_FLAGS, % jump C(1,,150 ) = 3 ) = 3 aosge_test() -> Prog1 = 1,,101/ AOSGE 1,150 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > , {1, 8#150, ?LOW36(2)} % 1,,150/ 2 ], expect(Prog1, [], {1, 8#103}, ?DEFAULT_FLAGS, % jump C(1,,150 ) = 3 ) = 3 Prog2 = 1,,101/ AOSGE 1,150 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > , {1, 8#150, ?LOW36(-1)} % 1,,150/ -1 ], jump , carry 0 and 1 C(1,,150 ) = 0 ) = 0 Prog3 = 1,,101/ AOSGE 1,150 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > , {1, 8#150, ?LOW36(-2)} % 1,,150/ -2 ], expect(Prog3, [], {1, 8#102}, ?DEFAULT_FLAGS, % no jump C(1,,150 ) = -1 ) = -1 aosn_test() -> Prog1 = 1,,101/ AOSN 1,150 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > , {1, 8#150, ?LOW36(2)} % 1,,150/ 2 ], expect(Prog1, [], {1, 8#103}, ?DEFAULT_FLAGS, % jump C(1,,150 ) = 3 ) = 3 Prog2 = 1,,101/ AOSN 1,150 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > , {1, 8#150, ?LOW36(-1)} % 1,,150/ -1 ], no jump , carry 0 and 1 C(1,,150 ) = 0 ) = 0 aosg_test() -> Prog1 = 1,,101/ AOSG 1,150 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > , {1, 8#150, ?LOW36(2)} % 1,,150/ 2 ], expect(Prog1, [], {1, 8#103}, ?DEFAULT_FLAGS, % jump C(1,,150 ) = 3 ) = 3 Prog2 = 1,,101/ AOSG 1,150 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > , {1, 8#150, ?LOW36(-2)} % 1,,150/ -2 ], expect(Prog2, [], {1, 8#102}, ?DEFAULT_FLAGS, % no jump C(1,,150 ) = -1 ) = -1 SOJ - Subtract One from AC and Jump if Condition Satisfied soj_test() -> Prog = 1,,100/ MOVEI 1,2 1,,101/ SOJ 1 , , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> ], no jump , carry 0 and 1 ) = 1 sojl_test() -> Prog1 = [ {1, 8#100, ?INSN(?OP_MOVNI, 1, 0, 0, 2)} % 1,,100/ MOVNI 1,2 1,,101/ SOJL 1,103 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > ], jump , carry 0 and 1 ) = -3 Prog2 = 1,,100/ MOVEI 1,2 1,,101/ SOJL 1,103 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > ], no jump , carry 0 and 1 ) = 1 soje_test() -> Prog1 = 1,,100/ MOVEI 1,1 1,,101/ SOJE 1,103 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > ], jump , carry 0 and 1 ) = 0 Prog2 = 1,,100/ MOVEI 1,2 1,,101/ SOJE 1,103 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > ], no jump , carry 0 and 1 ) = 1 sojle_test() -> Prog1 = 1,,100/ MOVEI 1,0 1,,101/ SOJLE 1,103 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > ], expect(Prog1, [], {1, 8#103}, ?DEFAULT_FLAGS, % jump, no carry flags ) = -1 Prog2 = 1,,100/ MOVEI 1,1 1,,101/ SOJLE 1,103 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > ], jump , carry 0 and 1 ) = 0 Prog3 = 1,,100/ MOVEI 1,2 1,,101/ SOJLE 1,103 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > ], no jump , carry 0 and 1 ) = 1 soja_test() -> Prog = 1,,100/ MOVEI 1,2 1,,101/ SOJA 1,103 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > ], jump , carry 0 and 1 ) = 1 sojge_test() -> Prog1 = 1,,100/ MOVEI 1,2 1,,101/ SOJGE 1,103 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > ], jump , carry 0 and 1 ) = 1 Prog2 = 1,,100/ MOVEI 1,1 1,,101/ SOJGE 1,103 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > ], jump , carry 0 and 1 ) = 0 Prog3 = 1,,100/ MOVEI 1,0 1,,101/ SOJGE 1,103 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > ], expect(Prog3, [], {1, 8#102}, ?DEFAULT_FLAGS, % no jump, no carry flags ) = -1 sojn_test() -> Prog1 = 1,,100/ MOVEI 1,2 1,,101/ SOJN 1,103 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > ], jump , carry 0 and 1 ) = 1 Prog2 = 1,,100/ MOVEI 1,1 1,,101/ SOJN 1,103 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > ], no jump , carry 0 and 1 ) = 0 sojg_test() -> Prog1 = 1,,100/ MOVEI 1,2 1,,101/ SOJG 1,103 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > ], jump , carry 0 and 1 ) = 1 Prog2 = [ {1, 8#100, ?INSN(?OP_MOVNI, 1, 0, 0, 2)} % 1,,100/ MOVNI 1,2 1,,101/ SOJG 1,103 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > ], no jump , carry 0 and 1 ) = -3 SOS - Subtract One from Memory and Skip if Condition Satisfied sos_test() -> Prog = 1,,101/ SOS 1,150 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> , {1, 8#150, ?LOW36(2)} % 1,,150/ 2 ], no jump , carry 0 and 1 C(1,,150 ) = 1 ) = 1 sosl_test() -> Prog1 = 1,,101/ SOSL 1,150 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > , {1, 8#150, ?LOW36(-2)} % 1,,150/ -2 ], jump , carry 0 and 1 C(1,,150 ) = -3 ) = -3 Prog2 = 1,,101/ SOSL 1,150 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > , {1, 8#150, ?LOW36(2)} % 1,,150/ 2 ], no jump , carry 0 and 1 C(1,,150 ) = 1 ) = 1 sose_test() -> Prog1 = 1,,101/ SOSE 1,150 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > , {1, 8#150, ?LOW36(1)} % 1,,150/ 1 ], jump , carry 0 and 1 C(1,,150 ) = 0 ) = 0 Prog2 = 1,,101/ SOSE 1,150 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > , {1, 8#150, ?LOW36(2)} % 1,,150/ 2 ], no jump , carry 0 and 1 C(1,,150 ) = 1 ) = 1 sosle_test() -> Prog1 = 1,,101/ SOSLE 1,150 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > , {1, 8#150, ?LOW36(0)} % 1,,150/ 0 ], expect(Prog1, [], {1, 8#103}, ?DEFAULT_FLAGS, % jump, no carry flags C(1,,150 ) = -1 ) = -1 Prog2 = 1,,101/ SOSLE 1,150 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > , {1, 8#150, ?LOW36(1)} % 1,,150/ 1 ], jump , carry 0 and 1 C(1,,150 ) = 0 ) = 0 Prog3 = 1,,101/ SOSLE 1,150 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > , {1, 8#150, ?LOW36(2)} % 1,,150/ 2 ], no jump , carry 0 and 1 C(1,,150 ) = 1 ) = 1 sosa_test() -> Prog = 1,,101/ SOSA 1,150 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > , {1, 8#150, ?LOW36(2)} % 1,,150/ 2 ], jump , carry 0 and 1 C(1,,150 ) = 1 ) = 1 sosge_test() -> Prog1 = 1,,101/ SOSGE 1,150 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > , {1, 8#150, ?LOW36(2)} % 1,,150/ 2 ], jump , carry 0 and 1 C(1,,150 ) = 1 ) = 1 Prog2 = 1,,101/ SOSGE 1,150 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > , {1, 8#150, ?LOW36(1)} % 1,,150/ 1 ], jump , carry 0 and 1 C(1,,150 ) = 0 ) = 0 Prog3 = 1,,101/ SOSGE 1,150 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > , {1, 8#150, ?LOW36(0)} % 1,,150/ 0 ], expect(Prog3, [], {1, 8#102}, ?DEFAULT_FLAGS, % no jump, no carry flags C(1,,150 ) = -1 ) = -1 sosn_test() -> Prog1 = 1,,101/ SOSN 1,150 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > , {1, 8#150, ?LOW36(2)} % 1,,150/ 2 ], jump , carry 0 and 1 C(1,,150 ) = 1 ) = 1 Prog2 = 1,,101/ SOSN 1,150 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > , {1, 8#150, ?LOW36(1)} % 1,,150/ 1 ], no jump , carry 0 and 1 C(1,,150 ) = 0 ) = 0 sosg_test() -> Prog1 = 1,,101/ SOSG 1,150 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > , {1, 8#150, ?LOW36(2)} % 1,,150/ 2 ], jump , carry 0 and 1 C(1,,150 ) = 1 ) = 1 Prog2 = 1,,101/ SOSG 1,150 , {1, 8#102, ?INSN_INVALID} % 1,,102/ <invalid> 1,,103/ < invalid > , {1, 8#150, ?LOW36(-2)} % 1,,150/ -2 ], no jump , carry 0 and 1 C(1,,150 ) = -3 ) = -3 %% Common code to run short sequences ========================================== expect(Prog, ACs, ExpectedPC, ExpectedFlags, ExpectedEs) -> {Core, Mem} = init(Prog, ACs), {Core1, Mem1, {error, {sim_core, {dispatch, PC, _IR, _EA}}}} = sim_core:run(Core, Mem), ActualPC = {PC bsr 18, PC band ((1 bsl 18) - 1)}, ?assertEqual(ExpectedPC, ActualPC), ?assertEqual(ExpectedFlags, Core1#core.flags), lists:foreach(fun({EA, ExpectedE}) -> {ok, ActualE} = sim_core:c(Core1, Mem1, EA), ?assertEqual(ExpectedE, ActualE) end, ExpectedEs), sim_mem:delete(Mem). init(Prog, ACs) -> {PCSection, PCOffset} = prog_pc(Prog), Mem = init_mem(Prog), Core = init_core(PCSection, PCOffset, ACs), {Core, Mem}. prog_pc([{Section, Offset, _Word} | _Rest]) -> {Section, Offset}. init_mem(Prog) -> init_mem(Prog, sim_mem:new()). init_mem([], Mem) -> Mem; init_mem([{Section, Offset, Word} | Rest], Mem) -> init_word(Section, Offset, Word, Mem), init_mem(Rest, Mem). init_word(Section, Offset, Word, Mem) -> Address = (Section bsl 18) bor Offset, PFN = Address bsr 9, case sim_mem:mquery(Mem, PFN) of false -> sim_mem:mmap(Mem, PFN, 4+2, core); {_Prot, _What} -> ok end, ok = sim_mem:write_word(Mem, Address, Word). init_core(PCSection, PCOffset, ACs) -> #core{ pc_section = PCSection , pc_offset = PCOffset , acs = init_acs(ACs, list_to_tuple(lists:duplicate(16, 0))) , flags = ?DEFAULT_FLAGS }. init_acs([], ACS) -> ACS; init_acs([{AC, Val} | Rest], ACS) -> init_acs(Rest, setelement(AC + 1, ACS, Val)).
null
https://raw.githubusercontent.com/mikpe/pdp10-tools/99216b63317fe5b5ac18f1a0d3c81b464f8b8f40/erlang/apps/sim/test/sim_arithmetic_tests.erl
erlang
(at your option) any later version. but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ============================================================================= LEFT,,RIGHT in MACRO-10 1,,100/ MOVSI 1,-2 1,,101/ AOBJP 1,103 1,,102/ <invalid> no jump AC1 = -1,,1 1,,100/ MOVSI 1,-1 1,,101/ AOBJP 1,103 1,,102/ <invalid> jump 1,,100/ MOVSI 1,-2 1,,102/ <invalid> jump AC1 = -1,,1 1,,100/ MOVSI 1,-1 1,,102/ <invalid> no jump 1,,100/ CAI 1,,101/ <invalid> no skip 1,,100/ MOVNI 1,3 1,,101/ CAIL 1,2 1,,102/ <invalid> skip 1,,101/ CAIL 1,2 1,,102/ <invalid> no skip 1,,102/ <invalid> skip 1,,102/ <invalid> no skip 1,,100/ MOVNI 1,3 1,,102/ <invalid> skip 1,,102/ <invalid> skip 1,,102/ <invalid> no skip 1,,100/ CAIA 1,,101/ <invalid> 1,,102/ <invalid> skip 1,,102/ <invalid> skip 1,,102/ <invalid> skip 1,,100/ MOVNI 1,3 1,,102/ <invalid> no skip 1,,102/ <invalid> skip 1,,102/ <invalid> no skip 1,,102/ <invalid> skip 1,,100/ MOVNI 1,3 1,,102/ <invalid> no skip 1,,100/ CAM 150 1,,101/ <invalid> 1,,150/ 0,,2 no skip 1,,100/ MOVNI 1,3 1,,102/ <invalid> 1,,150/ 0,,2 skip 1,,102/ <invalid> 1,,150/ 0,,2 no skip 1,,102/ <invalid> 1,,150/ 0,,2 skip 1,,102/ <invalid> 1,,150/ 0,,2 no skip 1,,100/ MOVNI 1,3 1,,102/ <invalid> 1,,150/ 0,,2 skip 1,,102/ <invalid> 1,,150/ 0,,2 skip 1,,102/ <invalid> 1,,150/ 0,,2 no skip 1,,101/ <invalid> 1,,102/ <invalid> 1,,150/ 0,,2 skip 1,,102/ <invalid> 1,,150/ 0,,2 skip 1,,102/ <invalid> 1,,150/ 0,,2 skip 1,,100/ MOVNI 1,3 1,,102/ <invalid> 1,,150/ 0,,2 no skip 1,,102/ <invalid> 1,,150/ 0,,2 skip 1,,102/ <invalid> 1,,150/ 0,,2 no skip 1,,102/ <invalid> 1,,150/ -2 skip 1,,100/ MOVNI 1,3 1,,102/ <invalid> 1,,150/ -2 no skip 1,,100/ JUMP 1,,101/ <invalid> no jump 1,,100/ MOVNI 1,3 1,,102/ <invalid> jump 1,,102/ <invalid> no jump 1,,102/ <invalid> jump 1,,102/ <invalid> no jump 1,,100/ MOVNI 1,3 1,,102/ <invalid> jump 1,,102/ <invalid> jump 1,,102/ <invalid> no jump 1,,101/ <invalid> 1,,102/ <invalid> jump 1,,102/ <invalid> jump 1,,102/ <invalid> jump 1,,100/ MOVNI 1,3 1,,102/ <invalid> no jump 1,,102/ <invalid> jump 1,,102/ <invalid> no jump 1,,102/ <invalid> jump 1,,100/ MOVNI 1,3 1,,102/ <invalid> no jump SKIP - Skip if Memory Condition Satisfied 1,,100/ MOVEI 0,42 1,,102/ <invalid> 1,,150/ 2 no skip 1,,101/ <invalid> 1,,102/ <invalid> 1,,150/ -2 skip AC1 = -2 1,,101/ <invalid> 1,,102/ <invalid> 1,,150/ 2 no skip 1,,101/ <invalid> 1,,102/ <invalid> 1,,150/ 0 skip 1,,101/ <invalid> 1,,102/ <invalid> 1,,150/ 0,,2 no skip 1,,101/ <invalid> 1,,102/ <invalid> 1,,150/ -2 AC1 = -2 1,,101/ <invalid> 1,,102/ <invalid> 1,,150/ 0 skip AC1 = 0 1,,101/ <invalid> 1,,102/ <invalid> 1,,150/ 2 no skip 1,,101/ <invalid> 1,,102/ <invalid> 1,,150/ 2 skip 1,,101/ <invalid> 1,,102/ <invalid> 1,,150/ 2 skip 1,,101/ <invalid> 1,,102/ <invalid> 1,,150/ 0 skip AC1 = 0 1,,101/ <invalid> 1,,102/ <invalid> 1,,150/ -2 no skip AC1 = -2 1,,101/ <invalid> 1,,102/ <invalid> 1,,150/ 2 skip 1,,101/ <invalid> 1,,102/ <invalid> 1,,150/ 0 no skip 1,,101/ <invalid> 1,,102/ <invalid> 1,,150/ 2 skip 1,,101/ <invalid> 1,,102/ <invalid> 1,,150/ -2 no skip AC(1) = -2 1,,102/ <invalid> no jump 1,,100/ MOVNI 1,2 1,,102/ <invalid> jump 1,,102/ <invalid> no jump 1,,102/ <invalid> 1,,102/ <invalid> no jump 1,,100/ MOVNI 1,2 1,,102/ <invalid> jump 1,,102/ <invalid> 1,,102/ <invalid> no jump 1,,102/ <invalid> jump 1,,102/ <invalid> jump 1,,102/ <invalid> 1,,100/ MOVNI 1,2 1,,102/ <invalid> no jump 1,,102/ <invalid> jump 1,,102/ <invalid> 1,,102/ <invalid> jump 1,,100/ MOVNI 1,2 1,,102/ <invalid> no jump 1,,102/ <invalid> 1,,150/ 2 no jump 1,,102/ <invalid> 1,,150/ -2 jump 1,,102/ <invalid> 1,,150/ 2 no jump 1,,102/ <invalid> 1,,150/ -1 1,,102/ <invalid> 1,,150/ 2 no jump 1,,102/ <invalid> 1,,150/ -2 jump 1,,102/ <invalid> 1,,150/ -1 1,,102/ <invalid> 1,,150/ 2 no jump 1,,102/ <invalid> 1,,150/ 2 jump 1,,102/ <invalid> 1,,150/ 2 jump 1,,102/ <invalid> 1,,150/ -1 1,,102/ <invalid> 1,,150/ -2 no jump 1,,102/ <invalid> 1,,150/ 2 jump 1,,102/ <invalid> 1,,150/ -1 1,,102/ <invalid> 1,,150/ 2 jump 1,,102/ <invalid> 1,,150/ -2 no jump 1,,102/ <invalid> 1,,100/ MOVNI 1,2 1,,102/ <invalid> 1,,102/ <invalid> 1,,102/ <invalid> 1,,102/ <invalid> 1,,102/ <invalid> jump, no carry flags 1,,102/ <invalid> 1,,102/ <invalid> 1,,102/ <invalid> 1,,102/ <invalid> 1,,102/ <invalid> 1,,102/ <invalid> no jump, no carry flags 1,,102/ <invalid> 1,,102/ <invalid> 1,,102/ <invalid> 1,,100/ MOVNI 1,2 1,,102/ <invalid> 1,,102/ <invalid> 1,,150/ 2 1,,102/ <invalid> 1,,150/ -2 1,,102/ <invalid> 1,,150/ 2 1,,102/ <invalid> 1,,150/ 1 1,,102/ <invalid> 1,,150/ 2 1,,102/ <invalid> 1,,150/ 0 jump, no carry flags 1,,102/ <invalid> 1,,150/ 1 1,,102/ <invalid> 1,,150/ 2 1,,102/ <invalid> 1,,150/ 2 1,,102/ <invalid> 1,,150/ 2 1,,102/ <invalid> 1,,150/ 1 1,,102/ <invalid> 1,,150/ 0 no jump, no carry flags 1,,102/ <invalid> 1,,150/ 2 1,,102/ <invalid> 1,,150/ 1 1,,102/ <invalid> 1,,150/ 2 1,,102/ <invalid> 1,,150/ -2 Common code to run short sequences ==========================================
-*- erlang - indent - level : 2 -*- simulator for pdp10 - elf Copyright ( C ) 2020 This file is part of pdp10 - tools . pdp10 - tools 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 pdp10 - tools is distributed in the hope that it will be useful , You should have received a copy of the GNU General Public License along with pdp10 - tools . If not , see < / > . Test cases for 2.6 Arithmetic Testing -module(sim_arithmetic_tests). -include("../src/sim_core.hrl"). -include_lib("eunit/include/eunit.hrl"). -define(DEFAULT_FLAGS, (1 bsl ?PDP10_PF_USER)). for AOJ / AOS / SOJ / SOS when carry 0 and 1 get set (?DEFAULT_FLAGS bor (1 bsl ?PDP10_PF_CARRY_0) bor (1 bsl ?PDP10_PF_CARRY_1))). -define(LOW18(X), ((X) band ((1 bsl 18) - 1))). -define(LOW36(X), ((X) band ((1 bsl 36) - 1))). -define(INSN(OP, AC, I, X, Y), (((OP) bsl (35 - 8)) bor ((AC) bsl (35 - 12)) bor ((I) bsl (35 - 13)) bor ((X) bsl (35 - 17)) bor ?LOW18(Y))). -define(EA(S, O), #ea{section = S, offset = O, islocal = false}). -define(AC(A), ?EA(1, A)). -define(INSN_INVALID, ?INSN(0, 0, 0, 0, 0)). -define(OP_MOVEI, 8#201). -define(OP_MOVSI, 8#205). -define(OP_MOVNI, 8#211). -define(OP_AOBJP, 8#252). -define(OP_AOBJN, 8#253). -define(OP_CAI, 8#300). -define(OP_CAIL, 8#301). -define(OP_CAIE, 8#302). -define(OP_CAILE, 8#303). -define(OP_CAIA, 8#304). -define(OP_CAIGE, 8#305). -define(OP_CAIN, 8#306). -define(OP_CAIG, 8#307). -define(OP_CAM, 8#310). -define(OP_CAML, 8#311). -define(OP_CAME, 8#312). -define(OP_CAMLE, 8#313). -define(OP_CAMA, 8#314). -define(OP_CAMGE, 8#315). -define(OP_CAMN, 8#316). -define(OP_CAMG, 8#317). -define(OP_JUMP, 8#320). -define(OP_JUMPL, 8#321). -define(OP_JUMPE, 8#322). -define(OP_JUMPLE, 8#323). -define(OP_JUMPA, 8#324). -define(OP_JUMPGE, 8#325). -define(OP_JUMPN, 8#326). -define(OP_JUMPG, 8#327). -define(OP_SKIP, 8#330). -define(OP_SKIPL, 8#331). -define(OP_SKIPE, 8#332). -define(OP_SKIPLE, 8#333). -define(OP_SKIPA, 8#334). -define(OP_SKIPGE, 8#335). -define(OP_SKIPN, 8#336). -define(OP_SKIPG, 8#337). -define(OP_AOJ, 8#340). -define(OP_AOJL, 8#341). -define(OP_AOJE, 8#342). -define(OP_AOJLE, 8#343). -define(OP_AOJA, 8#344). -define(OP_AOJGE, 8#345). -define(OP_AOJN, 8#346). -define(OP_AOJG, 8#347). -define(OP_AOS, 8#350). -define(OP_AOSL, 8#351). -define(OP_AOSE, 8#352). -define(OP_AOSLE, 8#353). -define(OP_AOSA, 8#354). -define(OP_AOSGE, 8#355). -define(OP_AOSN, 8#356). -define(OP_AOSG, 8#357). -define(OP_SOJ, 8#360). -define(OP_SOJL, 8#361). -define(OP_SOJE, 8#362). -define(OP_SOJLE, 8#363). -define(OP_SOJA, 8#364). -define(OP_SOJGE, 8#365). -define(OP_SOJN, 8#366). -define(OP_SOJG, 8#367). -define(OP_SOS, 8#370). -define(OP_SOSL, 8#371). -define(OP_SOSE, 8#372). -define(OP_SOSLE, 8#373). -define(OP_SOSA, 8#374). -define(OP_SOSGE, 8#375). -define(OP_SOSN, 8#376). -define(OP_SOSG, 8#377). 2.6.1 Add One to Both Halves of AC and Jump = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = AOBJP - Add One to Both Halves of AC and Jump if Positive aobjp_test() -> Prog1 = 1,,103/ < invalid > ], ]), Prog2 = 1,,103/ < invalid > ], AC1 = 0,,1 ]). AOBJN - Add One to Both Halves of AC and Jump if Negative aobjn_test() -> Prog1 = 1,,101/ AOBJN 1,103 1,,103/ < invalid > ], ]), Prog2 = 1,,101/ AOBJN 1,103 1,,103/ < invalid > ], AC1 = 0,,1 ]). 2.6.2 Comparisons , , and Jumps = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = CAI - Compare AC Immediate and Skip if Condition Satisfied cai_test() -> Prog = ], cail_test() -> Prog1 = 1,,103/ < invalid > ], Prog2 = 1,,100/ MOVEI 1,3 1,,103/ < invalid > ], caie_test() -> Prog1 = 1,,100/ MOVEI 1,2 1,,101/ CAIE 1,2 1,,103/ < invalid > ], Prog2 = 1,,100/ MOVEI 1,3 1,,101/ CAIE 1,2 1,,103/ < invalid > ], caile_test() -> Prog1 = 1,,101/ CAILE 1,2 1,,103/ < invalid > ], Prog2 = 1,,100/ MOVEI 1,2 1,,101/ CAILE 1,2 1,,103/ < invalid > ], Prog3 = 1,,100/ MOVEI 1,3 1,,101/ CAILE 1,2 1,,103/ < invalid > ], caia_test() -> Prog = ], caige_test() -> Prog1 = 1,,100/ MOVEI 1,3 1,,101/ CAIGE 1,2 1,,103/ < invalid > ], Prog2 = 1,,100/ MOVEI 1,2 1,,101/ CAIGE 1,2 1,,103/ < invalid > ], Prog3 = 1,,101/ CAIGE 1,2 1,,103/ < invalid > ], cain_test() -> Prog1 = 1,,100/ MOVEI 1,3 1,,101/ CAIN 1,2 1,,103/ < invalid > ], Prog2 = 1,,100/ MOVEI 1,2 1,,101/ CAIN 1,2 1,,103/ < invalid > ], caig_test() -> Prog1 = 1,,100/ MOVEI 1,3 1,,101/ CAIG 1,2 1,,103/ < invalid > ], Prog2 = 1,,101/ CAIG 1,2 1,,103/ < invalid > ], CAM - Compare AC with Memory and Skip if Condition Satisfied cam_test() -> Prog = ], caml_test() -> Prog1 = 1,,101/ CAML 1,150 1,,103/ < invalid > ], Prog2 = 1,,100/ MOVEI 1,3 1,,101/ CAML 1,150 1,,103/ < invalid > ], came_test() -> Prog1 = 1,,100/ MOVEI 1,2 1,,101/ CAME 1,150 1,,103/ < invalid > ], Prog2 = 1,,100/ MOVEI 1,3 1,,101/ CAME 1,150 1,,103/ < invalid > ], camle_test() -> Prog1 = 1,,101/ CAMLE 1,150 1,,103/ < invalid > ], Prog2 = 1,,100/ MOVEI 1,2 1,,101/ CAMLE 1,150 1,,103/ < invalid > ], Prog3 = 1,,100/ MOVEI 1,3 1,,101/ CAMLE 1,150 1,,103/ < invalid > ], cama_test() -> Prog = 1,,100/ CAMA 150 ], camge_test() -> Prog1 = 1,,100/ MOVEI 1,3 1,,101/ CAMGE 1,150 1,,103/ < invalid > ], Prog2 = 1,,100/ MOVEI 1,2 1,,101/ CAMGE 1,150 1,,103/ < invalid > ], Prog3 = 1,,101/ CAMGE 1,150 1,,103/ < invalid > ], camn_test() -> Prog1 = 1,,100/ MOVEI 1,3 1,,101/ CAMN 1,150 1,,103/ < invalid > ], Prog2 = 1,,100/ MOVEI 1,2 1,,101/ CAMN 1,150 1,,103/ < invalid > ], camg_test() -> Prog1 = 1,,100/ MOVEI 1,3 1,,101/ CAMG 1,150 1,,103/ < invalid > ], Prog2 = 1,,101/ CAMG 1,150 1,,103/ < invalid > ], JUMP - Jump if AC Condition Satisfied jump_test() -> Prog = ], jumpl_test() -> Prog1 = 1,,101/ JUMPL 1,103 1,,103/ < invalid > ], Prog2 = 1,,100/ MOVEI 1,3 1,,101/ JUMPL 1,103 1,,103/ < invalid > ], jumpe_test() -> Prog1 = 1,,100/ MOVEI 1,0 1,,101/ JUMPE 1,103 1,,103/ < invalid > ], Prog2 = 1,,100/ MOVEI 1,3 1,,101/ JUMPE 1,103 1,,103/ < invalid > ], jumple_test() -> Prog1 = 1,,101/ JUMPLE 1,103 1,,103/ < invalid > ], Prog2 = 1,,100/ MOVEI 1,0 1,,101/ JUMPLE 1,103 1,,103/ < invalid > ], Prog3 = 1,,100/ MOVEI 1,3 1,,101/ JUMPLE 1,103 1,,103/ < invalid > ], jumpa_test() -> Prog = 1,,100/ JUMPA 102 ], jumpge_test() -> Prog1 = 1,,100/ MOVEI 1,3 1,,101/ JUMPGE 1,103 1,,103/ < invalid > ], Prog2 = 1,,100/ MOVEI 1,0 1,,101/ JUMPGE 1,103 1,,103/ < invalid > ], Prog3 = 1,,101/ JUMPGE 1,103 1,,103/ < invalid > ], jumpn_test() -> Prog1 = 1,,100/ MOVEI 1,3 1,,101/ JUMPN 1,103 1,,103/ < invalid > ], Prog2 = 1,,100/ MOVEI 1,0 1,,101/ JUMPN 1,103 1,,103/ < invalid > ], jumpg_test() -> Prog1 = 1,,100/ MOVEI 1,3 1,,101/ JUMPG 1,103 1,,103/ < invalid > ], Prog2 = 1,,101/ JUMPG 1,103 1,,103/ < invalid > ], skip_test() -> Prog = 1,,101/ SKIP 150 ], AC(0 ) = 42 skipl_test() -> Prog1 = 1,,100/ SKIPL 1,150 ], Prog2 = 1,,100/ SKIPL 1,150 ], AC1 = 2 skipe_test() -> Prog1 = 1,,100/ SKIPE 1,150 ], Prog2 = 1,,100/ SKIPE 1,150 ], AC1 = 2 skiple_test() -> Prog1 = 1,,100/ SKIPLE 1,150 ], Prog2 = 1,,100/ SKIPLE 1,150 ], Prog3 = 1,,100/ SKIPLE 1,150 ], AC1 = 2 skipa_test() -> Prog = 1,,100/ SKIPA 1,150 ], AC1 = 2 skipge_test() -> Prog1 = 1,,100/ SKIPGE 1,150 ], AC1 = 2 Prog2 = 1,,100/ SKIPGE 1,150 ], Prog3 = 1,,100/ SKIPGE 1,150 ], skipn_test() -> Prog1 = 1,,100/ SKIPN 1,150 ], ) = 2 Prog2 = 1,,100/ SKIPN 1,150 ], ) = 0 skipg_test() -> Prog1 = 1,,100/ SKIPG 1,150 ], ) = 2 Prog2 = 1,,100/ SKIPG 1,150 ], AOJ - Add One to AC and Jump if Condition Satisfied aoj_test() -> Prog = 1,,100/ MOVEI 1,2 1,,101/ AOJ 1 , ], ) = 3 aojl_test() -> Prog1 = 1,,101/ AOJL 1,103 1,,103/ < invalid > ], ) = -1 Prog2 = 1,,100/ MOVEI 1,2 1,,101/ AOJL 1,103 1,,103/ < invalid > ], ) = 3 aoje_test() -> Prog1 = 1,,100/ MOVNI 1,1 1,,101/ AOJE 1,103 1,,103/ < invalid > ], jump , carry 0 and 1 ) = 0 Prog2 = 1,,100/ MOVEI 1,2 1,,101/ AOJE 1,103 1,,103/ < invalid > ], ) = 3 aojle_test() -> Prog1 = 1,,101/ AOJLE 1,103 1,,103/ < invalid > ], ) = -1 Prog2 = 1,,100/ MOVNI 1,1 1,,101/ AOJLE 1,103 1,,103/ < invalid > ], jump , carry 0 and 1 ) = 0 Prog3 = 1,,100/ MOVEI 1,2 1,,101/ AOJLE 1,103 1,,103/ < invalid > ], ) = 3 aoja_test() -> Prog = 1,,100/ MOVEI 1,2 1,,101/ AOJA 1,103 1,,103/ < invalid > ], ) = 3 aojge_test() -> Prog1 = 1,,100/ MOVEI 1,2 1,,101/ AOJGE 1,103 1,,103/ < invalid > ], ) = 3 Prog2 = 1,,100/ MOVNI 1,1 1,,101/ AOJGE 1,103 1,,103/ < invalid > ], jump , carry 0 and 1 ) = 0 Prog3 = 1,,101/ AOJGE 1,103 1,,103/ < invalid > ], ) = -1 aojn_test() -> Prog1 = 1,,100/ MOVEI 1,2 1,,101/ AOJN 1,103 1,,103/ < invalid > ], ) = 3 Prog2 = 1,,100/ MOVNI 1,1 1,,101/ AOJN 1,103 1,,103/ < invalid > ], no jump , carry 0 and 1 ) = 0 aojg_test() -> Prog1 = 1,,100/ MOVEI 1,2 1,,101/ AOJG 1,103 1,,103/ < invalid > ], ) = 3 Prog2 = 1,,101/ AOJG 1,103 1,,103/ < invalid > ], ) = -1 AOS - Add One to Memory and Skip if Condition Satisfied aos_test() -> Prog = 1,,101/ AOS 1,150 ], C(1,,150 ) = 3 ) = 3 aosl_test() -> Prog1 = 1,,101/ AOSL 1,150 1,,103/ < invalid > ], C(1,,150 ) = -1 ) = -1 Prog2 = 1,,101/ AOSL 1,150 1,,103/ < invalid > ], C(1,,150 ) = 3 ) = 3 aose_test() -> Prog1 = 1,,101/ AOSE 1,150 1,,103/ < invalid > ], jump , carry 0 and 1 C(1,,150 ) = 0 ) = 0 Prog2 = 1,,101/ AOSE 1,150 1,,103/ < invalid > ], C(1,,150 ) = 3 ) = 3 aosle_test() -> Prog1 = 1,,101/ AOSLE 1,150 1,,103/ < invalid > ], C(1,,150 ) = -1 ) = -1 Prog2 = 1,,101/ AOSLE 1,150 1,,103/ < invalid > ], jump , carry 0 and 1 C(1,,150 ) = 0 ) = 0 Prog3 = 1,,101/ AOSLE 1,150 1,,103/ < invalid > ], C(1,,150 ) = 3 ) = 3 aosa_test() -> Prog = 1,,101/ AOSA 1,150 1,,103/ < invalid > ], C(1,,150 ) = 3 ) = 3 aosge_test() -> Prog1 = 1,,101/ AOSGE 1,150 1,,103/ < invalid > ], C(1,,150 ) = 3 ) = 3 Prog2 = 1,,101/ AOSGE 1,150 1,,103/ < invalid > ], jump , carry 0 and 1 C(1,,150 ) = 0 ) = 0 Prog3 = 1,,101/ AOSGE 1,150 1,,103/ < invalid > ], C(1,,150 ) = -1 ) = -1 aosn_test() -> Prog1 = 1,,101/ AOSN 1,150 1,,103/ < invalid > ], C(1,,150 ) = 3 ) = 3 Prog2 = 1,,101/ AOSN 1,150 1,,103/ < invalid > ], no jump , carry 0 and 1 C(1,,150 ) = 0 ) = 0 aosg_test() -> Prog1 = 1,,101/ AOSG 1,150 1,,103/ < invalid > ], C(1,,150 ) = 3 ) = 3 Prog2 = 1,,101/ AOSG 1,150 1,,103/ < invalid > ], C(1,,150 ) = -1 ) = -1 SOJ - Subtract One from AC and Jump if Condition Satisfied soj_test() -> Prog = 1,,100/ MOVEI 1,2 1,,101/ SOJ 1 , ], no jump , carry 0 and 1 ) = 1 sojl_test() -> Prog1 = 1,,101/ SOJL 1,103 1,,103/ < invalid > ], jump , carry 0 and 1 ) = -3 Prog2 = 1,,100/ MOVEI 1,2 1,,101/ SOJL 1,103 1,,103/ < invalid > ], no jump , carry 0 and 1 ) = 1 soje_test() -> Prog1 = 1,,100/ MOVEI 1,1 1,,101/ SOJE 1,103 1,,103/ < invalid > ], jump , carry 0 and 1 ) = 0 Prog2 = 1,,100/ MOVEI 1,2 1,,101/ SOJE 1,103 1,,103/ < invalid > ], no jump , carry 0 and 1 ) = 1 sojle_test() -> Prog1 = 1,,100/ MOVEI 1,0 1,,101/ SOJLE 1,103 1,,103/ < invalid > ], ) = -1 Prog2 = 1,,100/ MOVEI 1,1 1,,101/ SOJLE 1,103 1,,103/ < invalid > ], jump , carry 0 and 1 ) = 0 Prog3 = 1,,100/ MOVEI 1,2 1,,101/ SOJLE 1,103 1,,103/ < invalid > ], no jump , carry 0 and 1 ) = 1 soja_test() -> Prog = 1,,100/ MOVEI 1,2 1,,101/ SOJA 1,103 1,,103/ < invalid > ], jump , carry 0 and 1 ) = 1 sojge_test() -> Prog1 = 1,,100/ MOVEI 1,2 1,,101/ SOJGE 1,103 1,,103/ < invalid > ], jump , carry 0 and 1 ) = 1 Prog2 = 1,,100/ MOVEI 1,1 1,,101/ SOJGE 1,103 1,,103/ < invalid > ], jump , carry 0 and 1 ) = 0 Prog3 = 1,,100/ MOVEI 1,0 1,,101/ SOJGE 1,103 1,,103/ < invalid > ], ) = -1 sojn_test() -> Prog1 = 1,,100/ MOVEI 1,2 1,,101/ SOJN 1,103 1,,103/ < invalid > ], jump , carry 0 and 1 ) = 1 Prog2 = 1,,100/ MOVEI 1,1 1,,101/ SOJN 1,103 1,,103/ < invalid > ], no jump , carry 0 and 1 ) = 0 sojg_test() -> Prog1 = 1,,100/ MOVEI 1,2 1,,101/ SOJG 1,103 1,,103/ < invalid > ], jump , carry 0 and 1 ) = 1 Prog2 = 1,,101/ SOJG 1,103 1,,103/ < invalid > ], no jump , carry 0 and 1 ) = -3 SOS - Subtract One from Memory and Skip if Condition Satisfied sos_test() -> Prog = 1,,101/ SOS 1,150 ], no jump , carry 0 and 1 C(1,,150 ) = 1 ) = 1 sosl_test() -> Prog1 = 1,,101/ SOSL 1,150 1,,103/ < invalid > ], jump , carry 0 and 1 C(1,,150 ) = -3 ) = -3 Prog2 = 1,,101/ SOSL 1,150 1,,103/ < invalid > ], no jump , carry 0 and 1 C(1,,150 ) = 1 ) = 1 sose_test() -> Prog1 = 1,,101/ SOSE 1,150 1,,103/ < invalid > ], jump , carry 0 and 1 C(1,,150 ) = 0 ) = 0 Prog2 = 1,,101/ SOSE 1,150 1,,103/ < invalid > ], no jump , carry 0 and 1 C(1,,150 ) = 1 ) = 1 sosle_test() -> Prog1 = 1,,101/ SOSLE 1,150 1,,103/ < invalid > ], C(1,,150 ) = -1 ) = -1 Prog2 = 1,,101/ SOSLE 1,150 1,,103/ < invalid > ], jump , carry 0 and 1 C(1,,150 ) = 0 ) = 0 Prog3 = 1,,101/ SOSLE 1,150 1,,103/ < invalid > ], no jump , carry 0 and 1 C(1,,150 ) = 1 ) = 1 sosa_test() -> Prog = 1,,101/ SOSA 1,150 1,,103/ < invalid > ], jump , carry 0 and 1 C(1,,150 ) = 1 ) = 1 sosge_test() -> Prog1 = 1,,101/ SOSGE 1,150 1,,103/ < invalid > ], jump , carry 0 and 1 C(1,,150 ) = 1 ) = 1 Prog2 = 1,,101/ SOSGE 1,150 1,,103/ < invalid > ], jump , carry 0 and 1 C(1,,150 ) = 0 ) = 0 Prog3 = 1,,101/ SOSGE 1,150 1,,103/ < invalid > ], C(1,,150 ) = -1 ) = -1 sosn_test() -> Prog1 = 1,,101/ SOSN 1,150 1,,103/ < invalid > ], jump , carry 0 and 1 C(1,,150 ) = 1 ) = 1 Prog2 = 1,,101/ SOSN 1,150 1,,103/ < invalid > ], no jump , carry 0 and 1 C(1,,150 ) = 0 ) = 0 sosg_test() -> Prog1 = 1,,101/ SOSG 1,150 1,,103/ < invalid > ], jump , carry 0 and 1 C(1,,150 ) = 1 ) = 1 Prog2 = 1,,101/ SOSG 1,150 1,,103/ < invalid > ], no jump , carry 0 and 1 C(1,,150 ) = -3 ) = -3 expect(Prog, ACs, ExpectedPC, ExpectedFlags, ExpectedEs) -> {Core, Mem} = init(Prog, ACs), {Core1, Mem1, {error, {sim_core, {dispatch, PC, _IR, _EA}}}} = sim_core:run(Core, Mem), ActualPC = {PC bsr 18, PC band ((1 bsl 18) - 1)}, ?assertEqual(ExpectedPC, ActualPC), ?assertEqual(ExpectedFlags, Core1#core.flags), lists:foreach(fun({EA, ExpectedE}) -> {ok, ActualE} = sim_core:c(Core1, Mem1, EA), ?assertEqual(ExpectedE, ActualE) end, ExpectedEs), sim_mem:delete(Mem). init(Prog, ACs) -> {PCSection, PCOffset} = prog_pc(Prog), Mem = init_mem(Prog), Core = init_core(PCSection, PCOffset, ACs), {Core, Mem}. prog_pc([{Section, Offset, _Word} | _Rest]) -> {Section, Offset}. init_mem(Prog) -> init_mem(Prog, sim_mem:new()). init_mem([], Mem) -> Mem; init_mem([{Section, Offset, Word} | Rest], Mem) -> init_word(Section, Offset, Word, Mem), init_mem(Rest, Mem). init_word(Section, Offset, Word, Mem) -> Address = (Section bsl 18) bor Offset, PFN = Address bsr 9, case sim_mem:mquery(Mem, PFN) of false -> sim_mem:mmap(Mem, PFN, 4+2, core); {_Prot, _What} -> ok end, ok = sim_mem:write_word(Mem, Address, Word). init_core(PCSection, PCOffset, ACs) -> #core{ pc_section = PCSection , pc_offset = PCOffset , acs = init_acs(ACs, list_to_tuple(lists:duplicate(16, 0))) , flags = ?DEFAULT_FLAGS }. init_acs([], ACS) -> ACS; init_acs([{AC, Val} | Rest], ACS) -> init_acs(Rest, setelement(AC + 1, ACS, Val)).
359d12c8cfac51b01dda370c6b74041f2038686382a692cd0f68bd1b207f3140
bschwb/cis194-solutions
hanoi.hs
# OPTIONS_GHC -Wall # module Hanoi where type Peg = String type Move = (Peg, Peg) Return list of moves to move n discs from the first to the second . -- hanoi 2 "a" "b" "c" == [("a","c"), ("a","b"), ("c","b")] 1 . move n-1 discs from a to c using b as temporary storage 2 . move the top disc from a to b 3 . move n-1 discs from c to b using a as temporary storage hanoi :: Integer -> Peg -> Peg -> Peg -> [Move] hanoi n src goal tmp | n <= 0 = [] | n == 1 = [(src, goal)] | otherwise = hanoi (n-1) src tmp goal ++ hanoi 1 src goal tmp ++ hanoi (n-1) tmp goal src Same principal but with 4 pegs this time solution for 15 discs with version 1 should be 2 ^ 15 - 1 = 32767 with four pegs 129 moves length(hanoi 15 " a " " b " " c " ) = 32767 length(hanoi 15 " a " " b " " c " " d " ) = 129 hanoi4 :: Integer -> Peg -> Peg -> Peg -> Peg -> [Move] hanoi4 n src goal tmp1 tmp2 | n <= 0 = [] | n == 1 = [(src, goal)] | n = = 2 = [ ( src , tmp1 ) , ( src , goal ) , ( tmp1 , goal ) ] | n == 3 = [(src, tmp1), (src, tmp2), (src, goal), (tmp2, goal), (tmp1, goal)] | otherwise = hanoi4 (n-1) src tmp1 goal tmp2 ++ hanoi4 1 src goal tmp1 tmp2 ++ hanoi4 (n-1) tmp1 goal src tmp2
null
https://raw.githubusercontent.com/bschwb/cis194-solutions/e79f96083b6edbfed18a2adbc749c41d196d8ff7/01-intro/hanoi.hs
haskell
hanoi 2 "a" "b" "c" == [("a","c"), ("a","b"), ("c","b")]
# OPTIONS_GHC -Wall # module Hanoi where type Peg = String type Move = (Peg, Peg) Return list of moves to move n discs from the first to the second . 1 . move n-1 discs from a to c using b as temporary storage 2 . move the top disc from a to b 3 . move n-1 discs from c to b using a as temporary storage hanoi :: Integer -> Peg -> Peg -> Peg -> [Move] hanoi n src goal tmp | n <= 0 = [] | n == 1 = [(src, goal)] | otherwise = hanoi (n-1) src tmp goal ++ hanoi 1 src goal tmp ++ hanoi (n-1) tmp goal src Same principal but with 4 pegs this time solution for 15 discs with version 1 should be 2 ^ 15 - 1 = 32767 with four pegs 129 moves length(hanoi 15 " a " " b " " c " ) = 32767 length(hanoi 15 " a " " b " " c " " d " ) = 129 hanoi4 :: Integer -> Peg -> Peg -> Peg -> Peg -> [Move] hanoi4 n src goal tmp1 tmp2 | n <= 0 = [] | n == 1 = [(src, goal)] | n = = 2 = [ ( src , tmp1 ) , ( src , goal ) , ( tmp1 , goal ) ] | n == 3 = [(src, tmp1), (src, tmp2), (src, goal), (tmp2, goal), (tmp1, goal)] | otherwise = hanoi4 (n-1) src tmp1 goal tmp2 ++ hanoi4 1 src goal tmp1 tmp2 ++ hanoi4 (n-1) tmp1 goal src tmp2
f9765dc1e8eb3a25a13cc3d888d723261b9cbf2624a6580634368bab68ab786f
GlideAngle/flare-timing
Chunk.hs
# LANGUAGE DuplicateRecordFields # module Flight.Gap.Distance.Chunk ( Lookahead(..) , Chunk(..) , Chunks(..) , IxChunk(..) , ChunkRelativeDifficulty(..) , ChunkDifficultyFraction(..) , ChunkLandings(..) , ChunkDifficulty(..) , lookahead , toIxChunk , collectDowns , toChunk , chunks , landouts , chunkLandouts , sumLandouts , mergeChunks ) where import GHC.Generics (Generic) import Data.Maybe (catMaybes) import Data.List (sort, group) import "newtype" Control.Newtype (Newtype(..)) import Data.Aeson (ToJSON(..), FromJSON(..)) import Data.UnitsOfMeasure ((*:), u, convert) import Data.UnitsOfMeasure.Internal (Quantity(..)) import qualified Data.Map as Map import Flight.Units () import Data.Via.Scientific (DefaultDecimalPlaces(..), DecimalPlaces(..)) import Data.Via.UnitsOfMeasure (ViaQ(..)) import "flight-gap-allot" Flight.Score ( DifficultyFraction(..), PilotDistance(..), Pilot, FlownMax(..)) import Flight.Gap.Distance.Relative (RelativeDifficulty(..)) | The index of a 100 m chunk . The zeroth chunk is any distance less than or -- equal to minimum distance. newtype IxChunk = IxChunk Int deriving (Eq, Ord, Generic) deriving anyclass (ToJSON, FromJSON) deriving newtype (Enum, Num) instance Show IxChunk where show (IxChunk x) = show x newtype Chunk a = Chunk a deriving (Eq, Ord, Generic) instance Show a => Show (Chunk a) where show (Chunk x) = show x instance (q ~ Quantity Double [u| km |]) => DefaultDecimalPlaces (Chunk q) where defdp _ = DecimalPlaces 1 instance (q ~ Quantity Double [u| km |]) => Newtype (Chunk q) q where pack = Chunk unpack (Chunk a) = a instance (q ~ Quantity Double [u| km |]) => ToJSON (Chunk q) where toJSON x = toJSON $ ViaQ x instance (q ~ Quantity Double [u| km |]) => FromJSON (Chunk q) where parseJSON o = do ViaQ x <- parseJSON o return x instance (ToJSON (Chunk a)) => ToJSON (Chunks a) instance (FromJSON (Chunk a)) => FromJSON (Chunks a) | A sequence of chunk ends , distances on course in km . newtype Chunks a = Chunks [Chunk a] deriving (Eq, Ord, Generic) instance Show a => Show (Chunks a) where show (Chunks xs) = show xs | How far to look ahead , in units of 100 m chunks . newtype Lookahead = Lookahead Int deriving (Eq, Ord, Show, Generic) deriving anyclass (ToJSON, FromJSON) -- | The relative difficulty for this chunk. data ChunkRelativeDifficulty = ChunkRelativeDifficulty { chunk :: IxChunk , rel :: RelativeDifficulty } deriving (Eq, Ord, Show, Generic, ToJSON, FromJSON) -- | The difficulty fraction for this chunk. data ChunkDifficultyFraction = ChunkDifficultyFraction { chunk :: IxChunk , frac :: DifficultyFraction } deriving (Eq, Ord, Show, Generic, ToJSON, FromJSON) -- | Pilots down in this chunk. The @downs@ and @downers@ fields can be zipped. data ChunkLandings = ChunkLandings { chunk :: IxChunk , down :: Int -- ^ How many pilots are down in this chunk. , downs :: [PilotDistance (Quantity Double [u| km |])] -- ^ The distance each of the downers came down. , downers :: [Pilot] -- ^ The pilots that landed in this chunk. } deriving (Eq, Ord, Show, Generic, ToJSON, FromJSON) data ChunkDifficulty = ChunkDifficulty { chunk :: IxChunk , startChunk :: Chunk (Quantity Double [u| km |]) -- ^ The task distance to the beginning of this chunk. , endChunk :: Chunk (Quantity Double [u| km |]) -- ^ The task distance to the end of this chunk. , endAhead :: Chunk (Quantity Double [u| km |]) -- ^ The task distance to the end of the chunk that we look ahead to. , down :: Int -- ^ How many pilots are down in this chunk. , downs :: [PilotDistance (Quantity Double [u| km |])] -- ^ The distance each of the downers came down. , downers :: [Pilot] -- ^ The pilots that landed in this chunk. , downward :: Int -- ^ The number of pilots that landed ahead within the lookahead distance. , rel :: RelativeDifficulty , frac :: DifficultyFraction } deriving (Eq, Ord, Show, Generic, ToJSON, FromJSON) mergeChunks :: [ChunkLandings] -- ^ Landings in each chunk -> [(IxChunk, Chunk (Quantity Double [u| km |]))] -- ^ Start of each chunk -> [(IxChunk, Chunk (Quantity Double [u| km |]))] -- ^ End of each chunk -> [(IxChunk, Chunk (Quantity Double [u| km |]))] -- ^ End of ahead chunk -> [ChunkLandings] -- ^ Landings summed over the lookahead -> [ChunkRelativeDifficulty] -> [ChunkDifficultyFraction] -> [ChunkDifficulty] mergeChunks ls is js ks as rs ds = catMaybes [ overlay l i j k a r d | l <- ls | i <- is | j <- js | k <- ks | a <- as | r <- rs | d <- ds ] overlay :: ChunkLandings -> (IxChunk, Chunk (Quantity Double [u| km |])) -> (IxChunk, Chunk (Quantity Double [u| km |])) -> (IxChunk, Chunk (Quantity Double [u| km |])) -> ChunkLandings -> ChunkRelativeDifficulty -> ChunkDifficultyFraction -> Maybe ChunkDifficulty overlay ChunkLandings{chunk = l, down, downs, downers} (i, iStart) (j, jEnd) (k, kEnd) ChunkLandings{chunk = c, down = ahead} ChunkRelativeDifficulty{chunk = r, rel} ChunkDifficultyFraction{chunk = d, frac} | (l == i) && (i == j) && (j == c) && (c == k) && (k == r) && (r == d) = let (downs', downers') = unzip $ sort $ zip downs downers in Just ChunkDifficulty { chunk = l , startChunk = iStart , endChunk = jEnd , endAhead = kEnd , down = down , downs = downs' , downers = downers' , downward = ahead , rel = rel , frac = frac } | otherwise = Nothing -- | How many 100 m chunks to look ahead when working out the distance -- difficulty. -- > > > lookahead ( [ u| 0 km | ] ) [ ] -- Lookahead 30 -- > > > lookahead ( [ u| 100 km | ] ) ( take 100 $ PilotDistance . MkQuantity < $ > [ 0 .. ] ) -- Lookahead 30 -- > > > lookahead ( [ u| 100 km | ] ) ( take 10 $ PilotDistance . MkQuantity < $ > [ 0 .. ] ) Lookahead 300 lookahead :: FlownMax (Quantity Double [u| km |]) -> [PilotDistance (Quantity Double [u| km |])] -> Lookahead lookahead (FlownMax (MkQuantity best)) xs = Lookahead . max 30 $ if null xs then 0 else round ((30 * best) / fromInteger pilotsLandedOut) where pilotsLandedOut = toInteger $ length xs | A list of 100 m chunks of distance starting from the minimum distance set -- up for the competition. Pilots that fly less than minimum distance get -- awarded that distance. -- > > > chunks ( [ u| 0 km | ] ) [ [ u| 0.0 km | ] ] -- > > > chunks ( [ u| 0.1 km | ] ) [ [ u| 0.0 km |],[u| 0.1 km | ] ] -- > > > chunks ( [ u| 0.3 km | ] ) [ [ u| 0.0 km |],[u| 0.1 km |],[u| 0.2 km |],[u| 0.30000000000000004 km | ] ] chunks :: FlownMax (Quantity Double [u| km |]) -> Chunks (Quantity Double [u| km |]) chunks (FlownMax best) = Chunks $ Chunk . MkQuantity <$> [x0, x1 .. xN] where MkQuantity x0 = [u| 0 km |] :: Quantity Double [u| km |] MkQuantity x1 = convert [u| 100m |] :: Quantity Double [u| km |] MkQuantity xN = best | Converts from a chunk index , a number of 100 m chunks offset to the start of -- the chunks range. -- prop > \x - > toChunk ( IxChunk x ) > = Chunk [ u| 0 km | ] -- > > > toChunk ( IxChunk 0 ) [ u| 0.0 km | ] -- > > > toChunk ( IxChunk 1 ) [ u| 0.1 km | ] -- > > > toChunk ( IxChunk 10 ) [ u| 1.0 km | ] toChunk :: IxChunk -> Chunk (Quantity Double [u| km |]) toChunk (IxChunk ix) = Chunk d where d :: Quantity Double [u| km |] d = convert $ fromIntegral (max 0 ix) *: [u| 1 hm |] -- | Converts from pilot distance a chunk index. -- prop > \x - > toIxChunk ( PilotDistance $ MkQuantity x ) > = IxChunk 0 -- prop > \x - > let Chunk y = toChunk ( IxChunk x ) in toIxChunk ( PilotDistance y ) = = IxChunk ( max 0 x ) -- > > > toIxChunk $ PilotDistance [ u| 0 km | ] 0 -- > > > toIxChunk $ PilotDistance [ u| 0.1 km | ] 1 -- -- >>> toIxChunk $ PilotDistance [u| -0.1 km |] 0 -- > > > toIxChunk $ PilotDistance [ u| 1 km | ] 10 -- > > > toIxChunk $ PilotDistance [ u| 1.4 km | ] 14 toIxChunk :: PilotDistance (Quantity Double [u| km |]) -> IxChunk toIxChunk (PilotDistance d) = IxChunk . max 0 $ floor x where MkQuantity x = convert d :: Quantity _ [u| hm |] | In each 100 m chunk where pilots landed out , how many pilots landed in that -- chunk. landouts :: [Pilot] -> [PilotDistance (Quantity Double [u| km |])] -> [ChunkLandings] landouts ps xs = collectDowns ps xs $ sumLandouts (chunkLandouts xs) toIxDowns :: [Pilot] -> [PilotDistance (Quantity Double [u| km |])] -> Map.Map IxChunk [(Pilot, PilotDistance (Quantity Double [u| km |]))] toIxDowns ps xs = Map.fromListWith (++) $ zipWith (\p x -> (toIxChunk x, [(p, x)])) ps xs collectDowns :: [Pilot] -> [PilotDistance (Quantity Double [u| km |])] -> [(IxChunk, Int)] -> [ChunkLandings] collectDowns ps xs = fmap (\(ix, n) -> let (ps', ds) = unzip $ Map.findWithDefault [] ix dss in ChunkLandings ix n ds ps') where dss = toIxDowns ps xs sumLandouts:: [IxChunk] -> [(IxChunk, Int)] sumLandouts = fmap (\gXs@(gX : _) -> (gX, length gXs)) . group chunkLandouts :: [PilotDistance (Quantity Double [u| km |])] -> [IxChunk] chunkLandouts xs = toIxChunk <$> sort xs
null
https://raw.githubusercontent.com/GlideAngle/flare-timing/34873946be9b93c37048ed118ef5b4649c71d630/lang-haskell/gap-effort/library/Flight/Gap/Distance/Chunk.hs
haskell
equal to minimum distance. | The relative difficulty for this chunk. | The difficulty fraction for this chunk. | Pilots down in this chunk. The @downs@ and @downers@ fields can be zipped. ^ How many pilots are down in this chunk. ^ The distance each of the downers came down. ^ The pilots that landed in this chunk. ^ The task distance to the beginning of this chunk. ^ The task distance to the end of this chunk. ^ The task distance to the end of the chunk that we look ahead to. ^ How many pilots are down in this chunk. ^ The distance each of the downers came down. ^ The pilots that landed in this chunk. ^ The number of pilots that landed ahead within the lookahead distance. ^ Landings in each chunk ^ Start of each chunk ^ End of each chunk ^ End of ahead chunk ^ Landings summed over the lookahead | How many 100 m chunks to look ahead when working out the distance difficulty. Lookahead 30 Lookahead 30 up for the competition. Pilots that fly less than minimum distance get awarded that distance. the chunks range. | Converts from pilot distance a chunk index. >>> toIxChunk $ PilotDistance [u| -0.1 km |] chunk.
# LANGUAGE DuplicateRecordFields # module Flight.Gap.Distance.Chunk ( Lookahead(..) , Chunk(..) , Chunks(..) , IxChunk(..) , ChunkRelativeDifficulty(..) , ChunkDifficultyFraction(..) , ChunkLandings(..) , ChunkDifficulty(..) , lookahead , toIxChunk , collectDowns , toChunk , chunks , landouts , chunkLandouts , sumLandouts , mergeChunks ) where import GHC.Generics (Generic) import Data.Maybe (catMaybes) import Data.List (sort, group) import "newtype" Control.Newtype (Newtype(..)) import Data.Aeson (ToJSON(..), FromJSON(..)) import Data.UnitsOfMeasure ((*:), u, convert) import Data.UnitsOfMeasure.Internal (Quantity(..)) import qualified Data.Map as Map import Flight.Units () import Data.Via.Scientific (DefaultDecimalPlaces(..), DecimalPlaces(..)) import Data.Via.UnitsOfMeasure (ViaQ(..)) import "flight-gap-allot" Flight.Score ( DifficultyFraction(..), PilotDistance(..), Pilot, FlownMax(..)) import Flight.Gap.Distance.Relative (RelativeDifficulty(..)) | The index of a 100 m chunk . The zeroth chunk is any distance less than or newtype IxChunk = IxChunk Int deriving (Eq, Ord, Generic) deriving anyclass (ToJSON, FromJSON) deriving newtype (Enum, Num) instance Show IxChunk where show (IxChunk x) = show x newtype Chunk a = Chunk a deriving (Eq, Ord, Generic) instance Show a => Show (Chunk a) where show (Chunk x) = show x instance (q ~ Quantity Double [u| km |]) => DefaultDecimalPlaces (Chunk q) where defdp _ = DecimalPlaces 1 instance (q ~ Quantity Double [u| km |]) => Newtype (Chunk q) q where pack = Chunk unpack (Chunk a) = a instance (q ~ Quantity Double [u| km |]) => ToJSON (Chunk q) where toJSON x = toJSON $ ViaQ x instance (q ~ Quantity Double [u| km |]) => FromJSON (Chunk q) where parseJSON o = do ViaQ x <- parseJSON o return x instance (ToJSON (Chunk a)) => ToJSON (Chunks a) instance (FromJSON (Chunk a)) => FromJSON (Chunks a) | A sequence of chunk ends , distances on course in km . newtype Chunks a = Chunks [Chunk a] deriving (Eq, Ord, Generic) instance Show a => Show (Chunks a) where show (Chunks xs) = show xs | How far to look ahead , in units of 100 m chunks . newtype Lookahead = Lookahead Int deriving (Eq, Ord, Show, Generic) deriving anyclass (ToJSON, FromJSON) data ChunkRelativeDifficulty = ChunkRelativeDifficulty { chunk :: IxChunk , rel :: RelativeDifficulty } deriving (Eq, Ord, Show, Generic, ToJSON, FromJSON) data ChunkDifficultyFraction = ChunkDifficultyFraction { chunk :: IxChunk , frac :: DifficultyFraction } deriving (Eq, Ord, Show, Generic, ToJSON, FromJSON) data ChunkLandings = ChunkLandings { chunk :: IxChunk , down :: Int , downs :: [PilotDistance (Quantity Double [u| km |])] , downers :: [Pilot] } deriving (Eq, Ord, Show, Generic, ToJSON, FromJSON) data ChunkDifficulty = ChunkDifficulty { chunk :: IxChunk , startChunk :: Chunk (Quantity Double [u| km |]) , endChunk :: Chunk (Quantity Double [u| km |]) , endAhead :: Chunk (Quantity Double [u| km |]) , down :: Int , downs :: [PilotDistance (Quantity Double [u| km |])] , downers :: [Pilot] , downward :: Int , rel :: RelativeDifficulty , frac :: DifficultyFraction } deriving (Eq, Ord, Show, Generic, ToJSON, FromJSON) mergeChunks -> [ChunkRelativeDifficulty] -> [ChunkDifficultyFraction] -> [ChunkDifficulty] mergeChunks ls is js ks as rs ds = catMaybes [ overlay l i j k a r d | l <- ls | i <- is | j <- js | k <- ks | a <- as | r <- rs | d <- ds ] overlay :: ChunkLandings -> (IxChunk, Chunk (Quantity Double [u| km |])) -> (IxChunk, Chunk (Quantity Double [u| km |])) -> (IxChunk, Chunk (Quantity Double [u| km |])) -> ChunkLandings -> ChunkRelativeDifficulty -> ChunkDifficultyFraction -> Maybe ChunkDifficulty overlay ChunkLandings{chunk = l, down, downs, downers} (i, iStart) (j, jEnd) (k, kEnd) ChunkLandings{chunk = c, down = ahead} ChunkRelativeDifficulty{chunk = r, rel} ChunkDifficultyFraction{chunk = d, frac} | (l == i) && (i == j) && (j == c) && (c == k) && (k == r) && (r == d) = let (downs', downers') = unzip $ sort $ zip downs downers in Just ChunkDifficulty { chunk = l , startChunk = iStart , endChunk = jEnd , endAhead = kEnd , down = down , downs = downs' , downers = downers' , downward = ahead , rel = rel , frac = frac } | otherwise = Nothing > > > lookahead ( [ u| 0 km | ] ) [ ] > > > lookahead ( [ u| 100 km | ] ) ( take 100 $ PilotDistance . MkQuantity < $ > [ 0 .. ] ) > > > lookahead ( [ u| 100 km | ] ) ( take 10 $ PilotDistance . MkQuantity < $ > [ 0 .. ] ) Lookahead 300 lookahead :: FlownMax (Quantity Double [u| km |]) -> [PilotDistance (Quantity Double [u| km |])] -> Lookahead lookahead (FlownMax (MkQuantity best)) xs = Lookahead . max 30 $ if null xs then 0 else round ((30 * best) / fromInteger pilotsLandedOut) where pilotsLandedOut = toInteger $ length xs | A list of 100 m chunks of distance starting from the minimum distance set > > > chunks ( [ u| 0 km | ] ) [ [ u| 0.0 km | ] ] > > > chunks ( [ u| 0.1 km | ] ) [ [ u| 0.0 km |],[u| 0.1 km | ] ] > > > chunks ( [ u| 0.3 km | ] ) [ [ u| 0.0 km |],[u| 0.1 km |],[u| 0.2 km |],[u| 0.30000000000000004 km | ] ] chunks :: FlownMax (Quantity Double [u| km |]) -> Chunks (Quantity Double [u| km |]) chunks (FlownMax best) = Chunks $ Chunk . MkQuantity <$> [x0, x1 .. xN] where MkQuantity x0 = [u| 0 km |] :: Quantity Double [u| km |] MkQuantity x1 = convert [u| 100m |] :: Quantity Double [u| km |] MkQuantity xN = best | Converts from a chunk index , a number of 100 m chunks offset to the start of prop > \x - > toChunk ( IxChunk x ) > = Chunk [ u| 0 km | ] > > > toChunk ( IxChunk 0 ) [ u| 0.0 km | ] > > > toChunk ( IxChunk 1 ) [ u| 0.1 km | ] > > > toChunk ( IxChunk 10 ) [ u| 1.0 km | ] toChunk :: IxChunk -> Chunk (Quantity Double [u| km |]) toChunk (IxChunk ix) = Chunk d where d :: Quantity Double [u| km |] d = convert $ fromIntegral (max 0 ix) *: [u| 1 hm |] prop > \x - > toIxChunk ( PilotDistance $ MkQuantity x ) > = IxChunk 0 prop > \x - > let Chunk y = toChunk ( IxChunk x ) in toIxChunk ( PilotDistance y ) = = IxChunk ( max 0 x ) > > > toIxChunk $ PilotDistance [ u| 0 km | ] 0 > > > toIxChunk $ PilotDistance [ u| 0.1 km | ] 1 0 > > > toIxChunk $ PilotDistance [ u| 1 km | ] 10 > > > toIxChunk $ PilotDistance [ u| 1.4 km | ] 14 toIxChunk :: PilotDistance (Quantity Double [u| km |]) -> IxChunk toIxChunk (PilotDistance d) = IxChunk . max 0 $ floor x where MkQuantity x = convert d :: Quantity _ [u| hm |] | In each 100 m chunk where pilots landed out , how many pilots landed in that landouts :: [Pilot] -> [PilotDistance (Quantity Double [u| km |])] -> [ChunkLandings] landouts ps xs = collectDowns ps xs $ sumLandouts (chunkLandouts xs) toIxDowns :: [Pilot] -> [PilotDistance (Quantity Double [u| km |])] -> Map.Map IxChunk [(Pilot, PilotDistance (Quantity Double [u| km |]))] toIxDowns ps xs = Map.fromListWith (++) $ zipWith (\p x -> (toIxChunk x, [(p, x)])) ps xs collectDowns :: [Pilot] -> [PilotDistance (Quantity Double [u| km |])] -> [(IxChunk, Int)] -> [ChunkLandings] collectDowns ps xs = fmap (\(ix, n) -> let (ps', ds) = unzip $ Map.findWithDefault [] ix dss in ChunkLandings ix n ds ps') where dss = toIxDowns ps xs sumLandouts:: [IxChunk] -> [(IxChunk, Int)] sumLandouts = fmap (\gXs@(gX : _) -> (gX, length gXs)) . group chunkLandouts :: [PilotDistance (Quantity Double [u| km |])] -> [IxChunk] chunkLandouts xs = toIxChunk <$> sort xs
68a75aa4ab39c7805feaafda2492b6215f191ec07a61bc983584b4b738ebd9d9
hirokai/PaperServer
Defs.hs
# LANGUAGE TemplateHaskell , DeriveDataTypeable # module Model.Defs where import Prelude import Database.Persist.Class import Database.Persist.Sql import Data.Text (Text) import Data.Maybe import qualified Data.Text as T import Data.Aeson.TH import Data.Char import qualified Parser.Paper as P import Data.Typeable type Url = Text data HistoryAction = HACreate | HAView | HARemove | HAVisitOriginal deriving (Show,Eq,Enum,Typeable) data LocalCopyStatus = LocalAvailable | NotYet | Failed | Unknown deriving (Show,Read,Eq,Typeable) data ResourceAvailability = ResourceAvailability { raCitation :: Bool , raAbstract :: Bool , raFulltext :: Bool , raFigures :: Bool , raReferences :: Bool , raToc :: Bool } deriving (Show,Eq) instance PersistField ResourceAvailability where toPersistValue (ResourceAvailability cit abs full fig ref toc) = PersistText $ T.intercalate "," $ catMaybes [if cit then Just "cit" else Nothing , if abs then Just "abs" else Nothing , if full then Just "full" else Nothing , if fig then Just "fig" else Nothing , if ref then Just "ref" else Nothing , if toc then Just "toc" else Nothing] fromPersistValue (PersistText txt) = Right $ f (T.splitOn "," txt) where f ts = ResourceAvailability ("cit" `elem` ts) ("abs" `elem` ts) ("full" `elem` ts) ("fig" `elem` ts) ("ref" `elem` ts) ("toc" `elem` ts) instance PersistFieldSql ResourceAvailability where sqlType _ = SqlString $(deriveJSON id ''HistoryAction) $(deriveJSON id ''LocalCopyStatus) $(deriveJSON (\s -> (toLower (s !! 2)):(drop 3 s)) ''ResourceAvailability) instance PersistField P.SupportLevel where toPersistValue P.SFullText = PersistText "fulltext" toPersistValue P.SAbstract = PersistText "abstract" toPersistValue P.SCitation = PersistText "citation" toPersistValue P.SUndecidable = PersistText "unknown" fromPersistValue (PersistText "fulltext") = Right P.SFullText fromPersistValue (PersistText "abstract") = Right P.SAbstract fromPersistValue (PersistText "citation") = Right P.SCitation fromPersistValue (PersistText "unknown") = Right P.SUndecidable fromPersistValue _ = Left "Not supported" instance PersistFieldSql P.SupportLevel where sqlType _ = SqlString instance PersistField HistoryAction where toPersistValue HACreate = PersistInt64 1 toPersistValue HAView = PersistInt64 2 toPersistValue HARemove = PersistInt64 3 toPersistValue HAVisitOriginal = PersistInt64 4 fromPersistValue (PersistInt64 1) = Right HACreate fromPersistValue (PersistInt64 2) = Right HAView fromPersistValue (PersistInt64 3) = Right HARemove fromPersistValue (PersistInt64 4) = Right HAVisitOriginal fromPersistValue _ = Left "Not supported" instance PersistFieldSql HistoryAction where sqlType _ = SqlInt32 instance PersistField LocalCopyStatus where toPersistValue LocalAvailable = PersistInt64 0 toPersistValue NotYet = PersistInt64 1 toPersistValue Failed = PersistInt64 2 toPersistValue Unknown = PersistInt64 3 fromPersistValue (PersistInt64 0) = Right LocalAvailable fromPersistValue (PersistInt64 1) = Right NotYet fromPersistValue (PersistInt64 2) = Right Failed fromPersistValue _ = Right Unknown instance PersistFieldSql LocalCopyStatus where sqlType _ = SqlInt32
null
https://raw.githubusercontent.com/hirokai/PaperServer/b577955af08660253d0cd11282cf141d1c174bc0/Model/Defs.hs
haskell
# LANGUAGE TemplateHaskell , DeriveDataTypeable # module Model.Defs where import Prelude import Database.Persist.Class import Database.Persist.Sql import Data.Text (Text) import Data.Maybe import qualified Data.Text as T import Data.Aeson.TH import Data.Char import qualified Parser.Paper as P import Data.Typeable type Url = Text data HistoryAction = HACreate | HAView | HARemove | HAVisitOriginal deriving (Show,Eq,Enum,Typeable) data LocalCopyStatus = LocalAvailable | NotYet | Failed | Unknown deriving (Show,Read,Eq,Typeable) data ResourceAvailability = ResourceAvailability { raCitation :: Bool , raAbstract :: Bool , raFulltext :: Bool , raFigures :: Bool , raReferences :: Bool , raToc :: Bool } deriving (Show,Eq) instance PersistField ResourceAvailability where toPersistValue (ResourceAvailability cit abs full fig ref toc) = PersistText $ T.intercalate "," $ catMaybes [if cit then Just "cit" else Nothing , if abs then Just "abs" else Nothing , if full then Just "full" else Nothing , if fig then Just "fig" else Nothing , if ref then Just "ref" else Nothing , if toc then Just "toc" else Nothing] fromPersistValue (PersistText txt) = Right $ f (T.splitOn "," txt) where f ts = ResourceAvailability ("cit" `elem` ts) ("abs" `elem` ts) ("full" `elem` ts) ("fig" `elem` ts) ("ref" `elem` ts) ("toc" `elem` ts) instance PersistFieldSql ResourceAvailability where sqlType _ = SqlString $(deriveJSON id ''HistoryAction) $(deriveJSON id ''LocalCopyStatus) $(deriveJSON (\s -> (toLower (s !! 2)):(drop 3 s)) ''ResourceAvailability) instance PersistField P.SupportLevel where toPersistValue P.SFullText = PersistText "fulltext" toPersistValue P.SAbstract = PersistText "abstract" toPersistValue P.SCitation = PersistText "citation" toPersistValue P.SUndecidable = PersistText "unknown" fromPersistValue (PersistText "fulltext") = Right P.SFullText fromPersistValue (PersistText "abstract") = Right P.SAbstract fromPersistValue (PersistText "citation") = Right P.SCitation fromPersistValue (PersistText "unknown") = Right P.SUndecidable fromPersistValue _ = Left "Not supported" instance PersistFieldSql P.SupportLevel where sqlType _ = SqlString instance PersistField HistoryAction where toPersistValue HACreate = PersistInt64 1 toPersistValue HAView = PersistInt64 2 toPersistValue HARemove = PersistInt64 3 toPersistValue HAVisitOriginal = PersistInt64 4 fromPersistValue (PersistInt64 1) = Right HACreate fromPersistValue (PersistInt64 2) = Right HAView fromPersistValue (PersistInt64 3) = Right HARemove fromPersistValue (PersistInt64 4) = Right HAVisitOriginal fromPersistValue _ = Left "Not supported" instance PersistFieldSql HistoryAction where sqlType _ = SqlInt32 instance PersistField LocalCopyStatus where toPersistValue LocalAvailable = PersistInt64 0 toPersistValue NotYet = PersistInt64 1 toPersistValue Failed = PersistInt64 2 toPersistValue Unknown = PersistInt64 3 fromPersistValue (PersistInt64 0) = Right LocalAvailable fromPersistValue (PersistInt64 1) = Right NotYet fromPersistValue (PersistInt64 2) = Right Failed fromPersistValue _ = Right Unknown instance PersistFieldSql LocalCopyStatus where sqlType _ = SqlInt32
677f6c2aef35683425fe887e441a1361624daf3ac6bf0aa8664a9ac6d7ba16b4
onedata/op-worker
storage_traverse_job.erl
%%%------------------------------------------------------------------- @author ( C ) 2019 ACK CYFRONET AGH This software is released under the MIT license cited in ' LICENSE.txt ' . %%%-------------------------------------------------------------------- %%% @doc %%% Model for persisting storage_traverse jobs. %%% @end %%%------------------------------------------------------------------- -module(storage_traverse_job). -author("Jakub Kudzia"). -include("global_definitions.hrl"). -include("modules/storage/traverse/storage_traverse.hrl"). -include("modules/datastore/datastore_models.hrl"). -include("modules/datastore/datastore_runner.hrl"). %% API -export([save_master_job/4, delete_master_job/1, get_master_job/1]). %% datastore_model callbacks -export([get_ctx/0, get_record_struct/1]). -type key() :: datastore:key(). -type record() :: #storage_traverse_job{}. -type doc() :: datastore_doc:doc(record()). -export_type([doc/0]). -define(CTX, #{model => ?MODULE}). %%%=================================================================== %%% API %%%=================================================================== -spec save_master_job(undefined | datastore:key(), storage_traverse:master_job(), traverse:pool(), traverse:id()) -> {ok, key()} | {error, term()}. save_master_job(Key, StorageTraverseMaster = #storage_traverse_master{ storage_file_ctx = StorageFileCtx, callback_module = CallbackModule }, Pool, TaskId) -> SpaceId = storage_file_ctx:get_space_id_const(StorageFileCtx), % if Key == main_job, set Key to undefined so that datastore will generate key Key2 = utils:ensure_defined(Key, main_job, undefined), ?extract_key(datastore_model:save(?CTX, #document{ key = Key2, value = create_record(Pool, TaskId, CallbackModule, StorageTraverseMaster), scope = SpaceId })). -spec delete_master_job(datastore:key()) -> ok | {error, term()}. delete_master_job(Key) -> datastore_model:delete(?CTX, Key). -spec get_master_job(key() | doc()) -> {ok, tree_traverse:master_job(), traverse:pool(), traverse:id()} | {error, term()}. get_master_job(#document{value = #storage_traverse_job{ pool = Pool, task_id = TaskID, callback_module = CallbackModule, storage_file_id = StorageFileId, space_id = SpaceId, storage_id = StorageId, iterator_module = IteratorModule, offset = Offset, batch_size = BatchSize, marker = Marker, max_depth = MaxDepth, execute_slave_on_dir = ExecuteSlaveOnDir, async_children_master_jobs = AsyncChildrenMasterJobs, async_next_batch_job = AsyncNextBatchJob, fold_children_init = FoldChildrenInit, fold_children_enabled = FoldChildrenEnabled, info = Info }}) -> TraverseInfo = binary_to_term(Info), Job = #storage_traverse_master{ storage_file_ctx = storage_file_ctx:new(StorageFileId, SpaceId, StorageId), iterator_module = IteratorModule, offset = Offset, batch_size = BatchSize, marker = Marker, max_depth = MaxDepth, next_batch_job_prehook = get_next_batch_job_prehook(CallbackModule, TraverseInfo), children_master_job_prehook = get_children_master_job_prehook(CallbackModule, TraverseInfo), fold_children_fun = get_fold_children_fun(CallbackModule, TraverseInfo), execute_slave_on_dir = ExecuteSlaveOnDir, async_children_master_jobs = AsyncChildrenMasterJobs, async_next_batch_job = AsyncNextBatchJob, fold_init = FoldChildrenInit, fold_enabled = FoldChildrenEnabled, callback_module = CallbackModule, info = TraverseInfo }, {ok, Job, Pool, TaskID}; get_master_job(Key) -> case datastore_model:get(?CTX#{include_deleted => true}, Key) of {ok, Doc} -> get_master_job(Doc); Other -> Other end. %%%=================================================================== %%% datastore_model callbacks %%%=================================================================== %%-------------------------------------------------------------------- %% @doc %% Returns model's context used by datastore and dbsync. %% @end %%-------------------------------------------------------------------- -spec get_ctx() -> datastore:ctx(). get_ctx() -> ?CTX. -spec get_record_struct(datastore_model:record_version()) -> datastore_model:record_struct(). get_record_struct(1) -> {record, [ {pool, string}, {task_id, string}, {callback_module, atom}, {storage_file_id, string}, {space_id, string}, {storage_id, string}, {iterator_module, atom}, {offset, integer}, {batch_size, integer}, {marker, string}, {max_depth, integer}, {execute_slave_on_dir, boolean}, {async_children_master_jobs, boolean}, {async_next_batch_job, boolean}, {fold_children_init, term}, {fold_children_enabled, boolean}, {info, binary} ]}. %%%=================================================================== Internal functions %%%=================================================================== -spec create_record(traverse:pool(), traverse:callback_module(), traverse:id(), storage_traverse:master_job()) -> record(). create_record(Pool, TaskId, CallbackModule, #storage_traverse_master{ storage_file_ctx = StorageFileCtx, iterator_module = IteratorModule, offset = Offset, batch_size = BatchSize, marker = Marker, max_depth = MaxDepth, execute_slave_on_dir = ExecuteSlaveOnDir, async_children_master_jobs = AsyncChildrenMasterJobs, async_next_batch_job = AsyncNextBatchJob, fold_init = FoldChildrenInit, fold_enabled = FoldChildrenEnabled, info = Info }) -> StorageFileId = storage_file_ctx:get_storage_file_id_const(StorageFileCtx), StorageId = storage_file_ctx:get_storage_id_const(StorageFileCtx), SpaceId = storage_file_ctx:get_space_id_const(StorageFileCtx), #storage_traverse_job{ pool = Pool, task_id = TaskId, callback_module = CallbackModule, storage_file_id = StorageFileId, space_id = SpaceId, storage_id = StorageId, iterator_module = IteratorModule, offset = Offset, batch_size = BatchSize, marker = Marker, max_depth = MaxDepth, execute_slave_on_dir = ExecuteSlaveOnDir, async_children_master_jobs = AsyncChildrenMasterJobs, async_next_batch_job = AsyncNextBatchJob, fold_children_init = FoldChildrenInit, fold_children_enabled = FoldChildrenEnabled, info = term_to_binary(Info) }. -spec get_next_batch_job_prehook(traverse:callback_module(), storage_traverse:info()) -> storage_traverse:next_batch_job_prehook(). get_next_batch_job_prehook(CallbackModule, TraverseInfo) -> case erlang:function_exported(CallbackModule, get_next_batch_job_prehook, 1) of true -> CallbackModule:get_next_batch_job_prehook(TraverseInfo); false -> ?DEFAULT_NEXT_BATCH_JOB_PREHOOK end. -spec get_children_master_job_prehook(traverse:callback_module(), storage_traverse:info()) -> storage_traverse:children_master_job_prehook(). get_children_master_job_prehook(CallbackModule, TraverseInfo) -> case erlang:function_exported(CallbackModule, get_children_master_job_prehook, 1) of true -> CallbackModule:get_children_master_job_prehook(TraverseInfo); false -> ?DEFAULT_CHILDREN_BATCH_JOB_PREHOOK end. -spec get_fold_children_fun(traverse:callback_module(), storage_traverse:info()) -> storage_traverse:fold_children_fun() | undefined. get_fold_children_fun(CallbackModule, TraverseInfo) -> case erlang:function_exported(CallbackModule, get_fold_children_fun, 1) of true -> CallbackModule:get_fold_children_fun(TraverseInfo); false -> undefined end.
null
https://raw.githubusercontent.com/onedata/op-worker/b09f05b6928121cec4d6b41ce8037fe056e6b4b3/src/modules/datastore/models/storage/traverse/storage_traverse_job.erl
erlang
------------------------------------------------------------------- -------------------------------------------------------------------- @doc Model for persisting storage_traverse jobs. @end ------------------------------------------------------------------- API datastore_model callbacks =================================================================== API =================================================================== if Key == main_job, set Key to undefined so that datastore will generate key =================================================================== datastore_model callbacks =================================================================== -------------------------------------------------------------------- @doc Returns model's context used by datastore and dbsync. @end -------------------------------------------------------------------- =================================================================== ===================================================================
@author ( C ) 2019 ACK CYFRONET AGH This software is released under the MIT license cited in ' LICENSE.txt ' . -module(storage_traverse_job). -author("Jakub Kudzia"). -include("global_definitions.hrl"). -include("modules/storage/traverse/storage_traverse.hrl"). -include("modules/datastore/datastore_models.hrl"). -include("modules/datastore/datastore_runner.hrl"). -export([save_master_job/4, delete_master_job/1, get_master_job/1]). -export([get_ctx/0, get_record_struct/1]). -type key() :: datastore:key(). -type record() :: #storage_traverse_job{}. -type doc() :: datastore_doc:doc(record()). -export_type([doc/0]). -define(CTX, #{model => ?MODULE}). -spec save_master_job(undefined | datastore:key(), storage_traverse:master_job(), traverse:pool(), traverse:id()) -> {ok, key()} | {error, term()}. save_master_job(Key, StorageTraverseMaster = #storage_traverse_master{ storage_file_ctx = StorageFileCtx, callback_module = CallbackModule }, Pool, TaskId) -> SpaceId = storage_file_ctx:get_space_id_const(StorageFileCtx), Key2 = utils:ensure_defined(Key, main_job, undefined), ?extract_key(datastore_model:save(?CTX, #document{ key = Key2, value = create_record(Pool, TaskId, CallbackModule, StorageTraverseMaster), scope = SpaceId })). -spec delete_master_job(datastore:key()) -> ok | {error, term()}. delete_master_job(Key) -> datastore_model:delete(?CTX, Key). -spec get_master_job(key() | doc()) -> {ok, tree_traverse:master_job(), traverse:pool(), traverse:id()} | {error, term()}. get_master_job(#document{value = #storage_traverse_job{ pool = Pool, task_id = TaskID, callback_module = CallbackModule, storage_file_id = StorageFileId, space_id = SpaceId, storage_id = StorageId, iterator_module = IteratorModule, offset = Offset, batch_size = BatchSize, marker = Marker, max_depth = MaxDepth, execute_slave_on_dir = ExecuteSlaveOnDir, async_children_master_jobs = AsyncChildrenMasterJobs, async_next_batch_job = AsyncNextBatchJob, fold_children_init = FoldChildrenInit, fold_children_enabled = FoldChildrenEnabled, info = Info }}) -> TraverseInfo = binary_to_term(Info), Job = #storage_traverse_master{ storage_file_ctx = storage_file_ctx:new(StorageFileId, SpaceId, StorageId), iterator_module = IteratorModule, offset = Offset, batch_size = BatchSize, marker = Marker, max_depth = MaxDepth, next_batch_job_prehook = get_next_batch_job_prehook(CallbackModule, TraverseInfo), children_master_job_prehook = get_children_master_job_prehook(CallbackModule, TraverseInfo), fold_children_fun = get_fold_children_fun(CallbackModule, TraverseInfo), execute_slave_on_dir = ExecuteSlaveOnDir, async_children_master_jobs = AsyncChildrenMasterJobs, async_next_batch_job = AsyncNextBatchJob, fold_init = FoldChildrenInit, fold_enabled = FoldChildrenEnabled, callback_module = CallbackModule, info = TraverseInfo }, {ok, Job, Pool, TaskID}; get_master_job(Key) -> case datastore_model:get(?CTX#{include_deleted => true}, Key) of {ok, Doc} -> get_master_job(Doc); Other -> Other end. -spec get_ctx() -> datastore:ctx(). get_ctx() -> ?CTX. -spec get_record_struct(datastore_model:record_version()) -> datastore_model:record_struct(). get_record_struct(1) -> {record, [ {pool, string}, {task_id, string}, {callback_module, atom}, {storage_file_id, string}, {space_id, string}, {storage_id, string}, {iterator_module, atom}, {offset, integer}, {batch_size, integer}, {marker, string}, {max_depth, integer}, {execute_slave_on_dir, boolean}, {async_children_master_jobs, boolean}, {async_next_batch_job, boolean}, {fold_children_init, term}, {fold_children_enabled, boolean}, {info, binary} ]}. Internal functions -spec create_record(traverse:pool(), traverse:callback_module(), traverse:id(), storage_traverse:master_job()) -> record(). create_record(Pool, TaskId, CallbackModule, #storage_traverse_master{ storage_file_ctx = StorageFileCtx, iterator_module = IteratorModule, offset = Offset, batch_size = BatchSize, marker = Marker, max_depth = MaxDepth, execute_slave_on_dir = ExecuteSlaveOnDir, async_children_master_jobs = AsyncChildrenMasterJobs, async_next_batch_job = AsyncNextBatchJob, fold_init = FoldChildrenInit, fold_enabled = FoldChildrenEnabled, info = Info }) -> StorageFileId = storage_file_ctx:get_storage_file_id_const(StorageFileCtx), StorageId = storage_file_ctx:get_storage_id_const(StorageFileCtx), SpaceId = storage_file_ctx:get_space_id_const(StorageFileCtx), #storage_traverse_job{ pool = Pool, task_id = TaskId, callback_module = CallbackModule, storage_file_id = StorageFileId, space_id = SpaceId, storage_id = StorageId, iterator_module = IteratorModule, offset = Offset, batch_size = BatchSize, marker = Marker, max_depth = MaxDepth, execute_slave_on_dir = ExecuteSlaveOnDir, async_children_master_jobs = AsyncChildrenMasterJobs, async_next_batch_job = AsyncNextBatchJob, fold_children_init = FoldChildrenInit, fold_children_enabled = FoldChildrenEnabled, info = term_to_binary(Info) }. -spec get_next_batch_job_prehook(traverse:callback_module(), storage_traverse:info()) -> storage_traverse:next_batch_job_prehook(). get_next_batch_job_prehook(CallbackModule, TraverseInfo) -> case erlang:function_exported(CallbackModule, get_next_batch_job_prehook, 1) of true -> CallbackModule:get_next_batch_job_prehook(TraverseInfo); false -> ?DEFAULT_NEXT_BATCH_JOB_PREHOOK end. -spec get_children_master_job_prehook(traverse:callback_module(), storage_traverse:info()) -> storage_traverse:children_master_job_prehook(). get_children_master_job_prehook(CallbackModule, TraverseInfo) -> case erlang:function_exported(CallbackModule, get_children_master_job_prehook, 1) of true -> CallbackModule:get_children_master_job_prehook(TraverseInfo); false -> ?DEFAULT_CHILDREN_BATCH_JOB_PREHOOK end. -spec get_fold_children_fun(traverse:callback_module(), storage_traverse:info()) -> storage_traverse:fold_children_fun() | undefined. get_fold_children_fun(CallbackModule, TraverseInfo) -> case erlang:function_exported(CallbackModule, get_fold_children_fun, 1) of true -> CallbackModule:get_fold_children_fun(TraverseInfo); false -> undefined end.
28e5112581af5ad64c521b947a379f11b98df5fe8f3467f6b28c9633a3d54ebf
vseloved/cl-agraph
test-core.lisp
CL - AGRAPH core test ( c ) Vsevolod Dyomkin . see LICENSE file for permissions (in-package :agraph) (deftest triple () (should be string= "/" (register-prefix "foo" "/")) (let ((tr (<> (make-blank-node) "rdf:type" (uri "foo:quux")))) (should be eql 'blank-node (type-of (s tr))) (should be eql 'uri (type-of (p tr))) (should be eql 'uri (type-of (o tr))) (should be string= "-rdf-syntax-ns#type" (uri-name (p tr))) (should be string= "" (uri-name (o tr))))) (deftest <> () (register-prefix "foo" "/") (let ((repo (gensym))) (with-ag (:repo "test" :port 12345 :sessionp nil) (should be true (create-repo repo))) (with-ag (:repo repo :port 12345) (should be = 2 (let ((subj (make-blank-node))) (add<> (<> subj "rdf:type" (uri "foo:bar")) (<> subj "foo:baz" "quux" :lang "en")))) (let ((trs (get<>))) (should be = 2 (length trs)) (should be eql (first trs) (second trs))) (should be = 0 (rem<> :g (uri "foo:bar"))) (should be = 1 (rem<> :o (uri "foo:bar"))) (should be = 1 (length (get<>))) (should be = 1 (count<>))) (with-ag (:repo "test" :port 12345 :sessionp nil) (should be true (delete-repo repo))))) (deftest transactions () (register-prefix "foo" "/") (let ((repo (gensym))) (with-ag (:repo "test" :port 12345 :sessionp nil) (should be true (create-repo repo))) (with-ag (:repo repo :port 12345) (let ((subj (make-blank-node))) (add<> (<> subj "rdf:type" (uri "foo:bar")) (<> subj "foo:baz" "quux" :lang "en"))) (rollback) (should be zerop (count<>)) (let ((subj (make-blank-node))) (add<> (<> subj "rdf:type" (uri "foo:bar")) (<> subj "foo:baz" "quux" :lang "en")))) (with-ag (:repo repo :port 12345) (should be = 2 (count<>))) (with-ag (:repo "test" :port 12345 :sessionp nil) (should be true (delete-repo repo)))))
null
https://raw.githubusercontent.com/vseloved/cl-agraph/e605b34fa57a9ede6fb6cc13ef82fc3438898567/test/test-core.lisp
lisp
CL - AGRAPH core test ( c ) Vsevolod Dyomkin . see LICENSE file for permissions (in-package :agraph) (deftest triple () (should be string= "/" (register-prefix "foo" "/")) (let ((tr (<> (make-blank-node) "rdf:type" (uri "foo:quux")))) (should be eql 'blank-node (type-of (s tr))) (should be eql 'uri (type-of (p tr))) (should be eql 'uri (type-of (o tr))) (should be string= "-rdf-syntax-ns#type" (uri-name (p tr))) (should be string= "" (uri-name (o tr))))) (deftest <> () (register-prefix "foo" "/") (let ((repo (gensym))) (with-ag (:repo "test" :port 12345 :sessionp nil) (should be true (create-repo repo))) (with-ag (:repo repo :port 12345) (should be = 2 (let ((subj (make-blank-node))) (add<> (<> subj "rdf:type" (uri "foo:bar")) (<> subj "foo:baz" "quux" :lang "en")))) (let ((trs (get<>))) (should be = 2 (length trs)) (should be eql (first trs) (second trs))) (should be = 0 (rem<> :g (uri "foo:bar"))) (should be = 1 (rem<> :o (uri "foo:bar"))) (should be = 1 (length (get<>))) (should be = 1 (count<>))) (with-ag (:repo "test" :port 12345 :sessionp nil) (should be true (delete-repo repo))))) (deftest transactions () (register-prefix "foo" "/") (let ((repo (gensym))) (with-ag (:repo "test" :port 12345 :sessionp nil) (should be true (create-repo repo))) (with-ag (:repo repo :port 12345) (let ((subj (make-blank-node))) (add<> (<> subj "rdf:type" (uri "foo:bar")) (<> subj "foo:baz" "quux" :lang "en"))) (rollback) (should be zerop (count<>)) (let ((subj (make-blank-node))) (add<> (<> subj "rdf:type" (uri "foo:bar")) (<> subj "foo:baz" "quux" :lang "en")))) (with-ag (:repo repo :port 12345) (should be = 2 (count<>))) (with-ag (:repo "test" :port 12345 :sessionp nil) (should be true (delete-repo repo)))))
e94d17fcc16baae758b713ab7f779092f2ce68365bc7b8c3d045e754fb5fa1f9
NorfairKing/smos
Gen.hs
# OPTIONS_GHC -fno - warn - orphans # module Smos.Cursor.Contents.Gen where import Cursor.List.NonEmpty.Gen import Cursor.Text.Gen import Cursor.TextField import Cursor.TextField.Gen () import Data.GenValidity import Data.GenValidity.Text import Smos.Cursor.Contents import Smos.Data import Test.QuickCheck instance GenValid ContentsCursor where genValid = ContentsCursor . TextFieldCursor <$> genNonEmptyCursorBy (textCursorWithGen $ genTextCursorChar `suchThat` validContentsChar) (genTextBy $ genTextCursorChar `suchThat` validContentsChar) shrinkValid = shrinkValidStructurally
null
https://raw.githubusercontent.com/NorfairKing/smos/f72b26c2e66ab4f3ec879a1bedc6c0e8eeb18a01/smos-cursor-gen/src/Smos/Cursor/Contents/Gen.hs
haskell
# OPTIONS_GHC -fno - warn - orphans # module Smos.Cursor.Contents.Gen where import Cursor.List.NonEmpty.Gen import Cursor.Text.Gen import Cursor.TextField import Cursor.TextField.Gen () import Data.GenValidity import Data.GenValidity.Text import Smos.Cursor.Contents import Smos.Data import Test.QuickCheck instance GenValid ContentsCursor where genValid = ContentsCursor . TextFieldCursor <$> genNonEmptyCursorBy (textCursorWithGen $ genTextCursorChar `suchThat` validContentsChar) (genTextBy $ genTextCursorChar `suchThat` validContentsChar) shrinkValid = shrinkValidStructurally
3a882379ed8962fdbd20447770da3a831deba27d4afaa2253b034c6b1663de84
SRI-CSL/yices2_ocaml_bindings
types_test.ml
open Yices2.High module EH1 = Make(ExceptionsErrorHandling) let test () = print_endline "Types tests"; let open EH1 in let open Global in init(); let bool_t = Type.bool() in let int_t = Type.int() in assert(not Type.(equal bool_t int_t)); let real_t = Type.real() in assert(not Type.(equal real_t bool_t)); assert(not Type.(equal real_t int_t)); let bv_t = Type.bv 8 in let scal_t = Type.new_scalar ~card:12 in let unint_t = Type.new_uninterpreted() in let tup1_t = Type.tuple [bool_t] in let tup2_t = Type.tuple [int_t; real_t] in let tup3_t = Type.tuple [bv_t; scal_t; unint_t] in let ta4 = [bool_t; tup1_t; tup2_t; tup3_t] in let tup4_t = Type.tuple ta4 in let fun1_t = Type.func [int_t] bool_t in let _fun2_t = Type.func [real_t; bv_t] scal_t in let fun3_t = Type.func [tup1_t; tup2_t; tup3_t] fun1_t in let fun4_t = Type.func ta4 fun3_t in assert(Type.is_bool bool_t); assert(not (Type.is_bool int_t)); assert(Type.is_int int_t); assert(Type.is_real real_t); assert(Type.is_arithmetic real_t); assert(Type.is_bitvector bv_t); assert(Type.is_tuple tup1_t); assert(Type.is_function fun4_t); assert(Type.is_scalar scal_t); assert(Type.is_uninterpreted unint_t); assert(Type.test_subtype int_t real_t); assert(not (Type.test_subtype real_t int_t)); assert(Types.equal_ytype (Type.reveal bv_t) (BV 8)); assert(Type.scalar_card scal_t = 12); assert(Type.num_children(tup3_t) = 3); assert(Type.child tup3_t 1 = scal_t); let type_v = Type.children tup4_t in assert(List.length type_v = 4); assert(List.nth type_v 0 = bool_t); assert(List.nth type_v 1 = tup1_t); assert(List.nth type_v 2 = tup2_t); assert(List.nth type_v 3 = tup3_t); print_endline "Done with Types tests"; exit()
null
https://raw.githubusercontent.com/SRI-CSL/yices2_ocaml_bindings/16e91100f82079576d63cbc3c49962178b79dfb9/src_tests/types_test.ml
ocaml
open Yices2.High module EH1 = Make(ExceptionsErrorHandling) let test () = print_endline "Types tests"; let open EH1 in let open Global in init(); let bool_t = Type.bool() in let int_t = Type.int() in assert(not Type.(equal bool_t int_t)); let real_t = Type.real() in assert(not Type.(equal real_t bool_t)); assert(not Type.(equal real_t int_t)); let bv_t = Type.bv 8 in let scal_t = Type.new_scalar ~card:12 in let unint_t = Type.new_uninterpreted() in let tup1_t = Type.tuple [bool_t] in let tup2_t = Type.tuple [int_t; real_t] in let tup3_t = Type.tuple [bv_t; scal_t; unint_t] in let ta4 = [bool_t; tup1_t; tup2_t; tup3_t] in let tup4_t = Type.tuple ta4 in let fun1_t = Type.func [int_t] bool_t in let _fun2_t = Type.func [real_t; bv_t] scal_t in let fun3_t = Type.func [tup1_t; tup2_t; tup3_t] fun1_t in let fun4_t = Type.func ta4 fun3_t in assert(Type.is_bool bool_t); assert(not (Type.is_bool int_t)); assert(Type.is_int int_t); assert(Type.is_real real_t); assert(Type.is_arithmetic real_t); assert(Type.is_bitvector bv_t); assert(Type.is_tuple tup1_t); assert(Type.is_function fun4_t); assert(Type.is_scalar scal_t); assert(Type.is_uninterpreted unint_t); assert(Type.test_subtype int_t real_t); assert(not (Type.test_subtype real_t int_t)); assert(Types.equal_ytype (Type.reveal bv_t) (BV 8)); assert(Type.scalar_card scal_t = 12); assert(Type.num_children(tup3_t) = 3); assert(Type.child tup3_t 1 = scal_t); let type_v = Type.children tup4_t in assert(List.length type_v = 4); assert(List.nth type_v 0 = bool_t); assert(List.nth type_v 1 = tup1_t); assert(List.nth type_v 2 = tup2_t); assert(List.nth type_v 3 = tup3_t); print_endline "Done with Types tests"; exit()
3f766b58ccab25fc037e827387c2a22261475e54df39ef80dece3e6880c1f46b
haskell/haskell-ide-engine
HoverSpec.hs
{-# LANGUAGE OverloadedStrings #-} module HoverSpec where import Control.Applicative.Combinators import Control.Lens import Control.Monad.IO.Class import qualified Data.Text as T import Language.Haskell.LSP.Test import Language.Haskell.LSP.Types import Language.Haskell.LSP.Types.Lens import Test.Hspec import TestUtils spec :: Spec spec = describe "hover" $ it "works" $ runSession hieCommand fullCaps "test/testdata" $ do doc <- openDoc "Hover.hs" "haskell" _ <- count 2 $ skipManyTill loggingNotification noDiagnostics Just h <- getHover doc (Position 1 19) liftIO $ do h ^. range `shouldBe` Just (Range (Position 1 16) (Position 1 19)) let hasType (HoverContents (MarkupContent MkMarkdown s)) = "\n```haskell\nsum :: [Int] -> Int\n```" `T.isPrefixOf`s hasType _ = False sumDoc = "The `sum` function computes the sum of the numbers of a structure." hasDoc (HoverContents (MarkupContent MkMarkdown s)) = sumDoc `T.isInfixOf` s hasDoc _ = False h ^. contents `shouldSatisfy` hasType h ^. contents `shouldSatisfy` hasDoc
null
https://raw.githubusercontent.com/haskell/haskell-ide-engine/d84b84322ccac81bf4963983d55cc4e6e98ad418/test/functional/HoverSpec.hs
haskell
# LANGUAGE OverloadedStrings #
module HoverSpec where import Control.Applicative.Combinators import Control.Lens import Control.Monad.IO.Class import qualified Data.Text as T import Language.Haskell.LSP.Test import Language.Haskell.LSP.Types import Language.Haskell.LSP.Types.Lens import Test.Hspec import TestUtils spec :: Spec spec = describe "hover" $ it "works" $ runSession hieCommand fullCaps "test/testdata" $ do doc <- openDoc "Hover.hs" "haskell" _ <- count 2 $ skipManyTill loggingNotification noDiagnostics Just h <- getHover doc (Position 1 19) liftIO $ do h ^. range `shouldBe` Just (Range (Position 1 16) (Position 1 19)) let hasType (HoverContents (MarkupContent MkMarkdown s)) = "\n```haskell\nsum :: [Int] -> Int\n```" `T.isPrefixOf`s hasType _ = False sumDoc = "The `sum` function computes the sum of the numbers of a structure." hasDoc (HoverContents (MarkupContent MkMarkdown s)) = sumDoc `T.isInfixOf` s hasDoc _ = False h ^. contents `shouldSatisfy` hasType h ^. contents `shouldSatisfy` hasDoc
03375cc182ab1962525432405f1af5e1d0b43d05e10419a6f824bf0421df45fc
nasser/magic
tests.clj
(ns magic.tests (:refer-clojure :exclude [methods]) (:import Activator IFn) (:require [mage.core :as il]) (:use magic.core) (:use clojure.pprint clojure.test)) ;; test gen (defn types [asm] (->> asm assembly-load (.GetTypes))) (defn methods [asm flags] (->> asm types (mapcat #(.GetMethods % flags)))) (defn properties [asm] (->> asm types (mapcat #(.GetProperties %)))) (defn fields [asm] (->> asm types (mapcat #(.GetFields %)))) (defn static-method-expr [method] (let [type (.DeclaringType method) name (.Name method)] (list (symbol (str type "/" name)) ) )) ;; this will change when the magic api settles down (defn compile-raw [bytecode] (let [asm-name "magic.tests"] (il/assembly asm-name (il/module (str asm-name ".dll") bytecode )))) (defn compile-fn [expr] (let [asm-name "magic.tests"] (il/assembly asm-name (il/module (str asm-name ".dll") (compile (analyze expr) base-compilers))))) (defn compile-fn [expr] (let [asm-name "magic.tests"] (-> (il/assembly asm-name (il/module (str asm-name ".dll") (compile (analyze expr) base-compilers))) il/emit! ; :mage.core/assembly-builder .GetTypes ; first ))) (defn magic-compile [expr] (compile-fn (list 'fn '[] expr))) (defn magic-eval [expr] (.invoke (magic-compile expr))) (defmacro test-same [name expr] `(deftest ~name (is (= (magic-eval (quote ~expr)) ~expr)))) (defmacro test-not-nil [name expr] `(deftest ~name (is (not (nil? (magic-eval (quote ~expr))))))) ;; nil (test-same strings nil) ;; strings (test-same strings "foo") ;; boolean (test-same strings true) (test-same strings false) ;; numbers (test-same integers 12) (test-same negative-integers -12) (test-same doubles- 12.3) (test-same negative-doubles- -12.3) (test-same ratios 1/2) (test-same negative-ratios -1/2) (test-same huge-ratios 999999999999999999999999999999999999/99999999999999999999999999999999999) (test-same bigints-1 1N) (test-same bigints-2 999999999999999999999999999999999999N) ;; chars (test-same chars \f) ;; types (test-same types-1 clojure.lang.Symbol) (test-same types-2 System.Text.RegularExpressions.Regex) ;; lists (test-same lists-1 '(1 2 3)) (test-same lists-2 '(1 "2" 3)) (test-same lists-3 '(1 (+ 1 2) 3)) ;; vectors (test-same vectors-numbers [1 2 3]) (test-same vectors-strings ["1" "2" "3"]) (test-same vectors-mixed ["1" 2 3.4]) (test-same vectors-exprs [(str "hello" 90) (+ 2 3.4)]) ;; maps (test-same maps-numbers {:a 1 :b 2 :c 3 }) (test-same maps-mixed {:a "1" :b "2" :c "3" }) (test-same maps-mixed {:a 1 :b "2" :c 3 }) (test-same maps-exprs {:a (str "hello" 90) :b (+ 2 3.4)}) (test-same maps-complex-keys {{:a (str "nice")} 1 (map inc (range 20)) "2"}) ;; symbols (test-same symbols 'foo) (test-same symbols-namespace 'foo/bar) ;; keywords (test-same keywords :foo) (test-same keywords-namespaces :foo/bar) (test-same keywords-double-colon ::foo) ;; invoke (test-same invoke-str (str 1 2)) (test-same invoke-map-inc-range (map inc (range 20))) (test-same invoke-map-lookup-1 (({:foo inc :bar dec} :foo) 10)) (test-same invoke-map-lookup-2 (({:foo inc :bar dec} :foo) ({:foo 10 :bar 9} :foo))) ;; regexp (test-same regexp-1 (str #"foo")) ;; regexps arent values, is str the best test? (test-same regexp-2 (str #"foo(.*[a-z]+)")) ;; regexps arent values, is str the best test? (test-same regexp-works-1 (re-find #"bar" "foo bar baz")) (test-same regexp-works-2 (re-find #"bar\b" "foo bar baz")) (test-same regexp-works-3 (re-find #"bar\b" "foo barbaz")) ;; new expr (test-not-nil new-object-1 (System.Xml.XmlDocument.)) (test-not-nil new-object-2 (System.IO.DirectoryInfo. "foo")) (test-same new-valuetype-1 (System.Drawing.Point.)) (test-same new-valuetype-2 (System.Drawing.Point. 1 3)) (test-same new-valuetype-3 (System.Drawing.Point. 1.2 3.1)) (test-same new-valuetype-4 (System.Drawing.Point. 1.2 3)) (test-same new-valuetype-5 (System.Drawing.Point. (System.Drawing.Size. 5 6))) ;; instance property (test-same instance-property (.Length (.GetFiles (System.IO.DirectoryInfo. ".")))) (test-same instance-property-valuetype (.X (System.Drawing.Point. 1 3))) ;; instance method (test-same instance-method (.Length (.GetFiles (System.IO.DirectoryInfo. ".")))) (test-same instance-method-valuetype (.Offset (System.Drawing.Point. 1 3) 4 1)) ;; static method (test-same static-method-1 (Directory/Exists ".")) (test-same static-method-2 (.FullName (Directory/GetParent "."))) (test-same static-method-valuetype (System.Drawing.Point/Add (System.Drawing.Point. 3 4) (System.Drawing.Size. 25 45))) ;; let bindings (test-same let-valuetype (let [a 20] a)) (test-same let-reference (let [a "20"] a)) (test-same let-body (let [a "hello" b "world"] (str a b))) (test-same let-body-valuetypes (let [a 1 b 2] (+ a b))) (test-same let-nested (let [a 1] (let [b 2] (+ a b)))) (test-same let-nested-shadow (let [a 1] (let [b 2] (let [a 10] (+ a b))))) (test-same let-name-reuse-1 (let [a 4 b (mapv inc (range a)) a "A Vector: "] (str a b))) (test-same let-name-reuse-2 (let [a 20 a (range a) a (map inc a) a (mapv str a)] a)) (test-same let-as-expr (map inc (let [a 8] (range a (let [b (long (count "Hello"))] (+ a b)))))) (test-same let-vector-destructure (let [[a b c] [1 2 3]] (+ a b c))) (test-same let-map-destructure (let [{:keys [a b c]} {:a 1 :b 2 :c 3}] (+ a b c))) (run-tests) (comment (binding [*compile-path* "."] (compile 'magic.reference)) (binding [*test-out* *out*] (run-tests)) )
null
https://raw.githubusercontent.com/nasser/magic/7a46f773bc7785c82d9527d52c1a8c28ac16e195/src/magic/tests.clj
clojure
test gen this will change when the magic api settles down :mage.core/assembly-builder first nil strings boolean numbers chars types lists vectors maps symbols keywords invoke regexp regexps arent values, is str the best test? regexps arent values, is str the best test? new expr instance property instance method static method let bindings
(ns magic.tests (:refer-clojure :exclude [methods]) (:import Activator IFn) (:require [mage.core :as il]) (:use magic.core) (:use clojure.pprint clojure.test)) (defn types [asm] (->> asm assembly-load (.GetTypes))) (defn methods [asm flags] (->> asm types (mapcat #(.GetMethods % flags)))) (defn properties [asm] (->> asm types (mapcat #(.GetProperties %)))) (defn fields [asm] (->> asm types (mapcat #(.GetFields %)))) (defn static-method-expr [method] (let [type (.DeclaringType method) name (.Name method)] (list (symbol (str type "/" name)) ) )) (defn compile-raw [bytecode] (let [asm-name "magic.tests"] (il/assembly asm-name (il/module (str asm-name ".dll") bytecode )))) (defn compile-fn [expr] (let [asm-name "magic.tests"] (il/assembly asm-name (il/module (str asm-name ".dll") (compile (analyze expr) base-compilers))))) (defn compile-fn [expr] (let [asm-name "magic.tests"] (-> (il/assembly asm-name (il/module (str asm-name ".dll") (compile (analyze expr) base-compilers))) il/emit! .GetTypes ))) (defn magic-compile [expr] (compile-fn (list 'fn '[] expr))) (defn magic-eval [expr] (.invoke (magic-compile expr))) (defmacro test-same [name expr] `(deftest ~name (is (= (magic-eval (quote ~expr)) ~expr)))) (defmacro test-not-nil [name expr] `(deftest ~name (is (not (nil? (magic-eval (quote ~expr))))))) (test-same strings nil) (test-same strings "foo") (test-same strings true) (test-same strings false) (test-same integers 12) (test-same negative-integers -12) (test-same doubles- 12.3) (test-same negative-doubles- -12.3) (test-same ratios 1/2) (test-same negative-ratios -1/2) (test-same huge-ratios 999999999999999999999999999999999999/99999999999999999999999999999999999) (test-same bigints-1 1N) (test-same bigints-2 999999999999999999999999999999999999N) (test-same chars \f) (test-same types-1 clojure.lang.Symbol) (test-same types-2 System.Text.RegularExpressions.Regex) (test-same lists-1 '(1 2 3)) (test-same lists-2 '(1 "2" 3)) (test-same lists-3 '(1 (+ 1 2) 3)) (test-same vectors-numbers [1 2 3]) (test-same vectors-strings ["1" "2" "3"]) (test-same vectors-mixed ["1" 2 3.4]) (test-same vectors-exprs [(str "hello" 90) (+ 2 3.4)]) (test-same maps-numbers {:a 1 :b 2 :c 3 }) (test-same maps-mixed {:a "1" :b "2" :c "3" }) (test-same maps-mixed {:a 1 :b "2" :c 3 }) (test-same maps-exprs {:a (str "hello" 90) :b (+ 2 3.4)}) (test-same maps-complex-keys {{:a (str "nice")} 1 (map inc (range 20)) "2"}) (test-same symbols 'foo) (test-same symbols-namespace 'foo/bar) (test-same keywords :foo) (test-same keywords-namespaces :foo/bar) (test-same keywords-double-colon ::foo) (test-same invoke-str (str 1 2)) (test-same invoke-map-inc-range (map inc (range 20))) (test-same invoke-map-lookup-1 (({:foo inc :bar dec} :foo) 10)) (test-same invoke-map-lookup-2 (({:foo inc :bar dec} :foo) ({:foo 10 :bar 9} :foo))) (test-same regexp-works-1 (re-find #"bar" "foo bar baz")) (test-same regexp-works-2 (re-find #"bar\b" "foo bar baz")) (test-same regexp-works-3 (re-find #"bar\b" "foo barbaz")) (test-not-nil new-object-1 (System.Xml.XmlDocument.)) (test-not-nil new-object-2 (System.IO.DirectoryInfo. "foo")) (test-same new-valuetype-1 (System.Drawing.Point.)) (test-same new-valuetype-2 (System.Drawing.Point. 1 3)) (test-same new-valuetype-3 (System.Drawing.Point. 1.2 3.1)) (test-same new-valuetype-4 (System.Drawing.Point. 1.2 3)) (test-same new-valuetype-5 (System.Drawing.Point. (System.Drawing.Size. 5 6))) (test-same instance-property (.Length (.GetFiles (System.IO.DirectoryInfo. ".")))) (test-same instance-property-valuetype (.X (System.Drawing.Point. 1 3))) (test-same instance-method (.Length (.GetFiles (System.IO.DirectoryInfo. ".")))) (test-same instance-method-valuetype (.Offset (System.Drawing.Point. 1 3) 4 1)) (test-same static-method-1 (Directory/Exists ".")) (test-same static-method-2 (.FullName (Directory/GetParent "."))) (test-same static-method-valuetype (System.Drawing.Point/Add (System.Drawing.Point. 3 4) (System.Drawing.Size. 25 45))) (test-same let-valuetype (let [a 20] a)) (test-same let-reference (let [a "20"] a)) (test-same let-body (let [a "hello" b "world"] (str a b))) (test-same let-body-valuetypes (let [a 1 b 2] (+ a b))) (test-same let-nested (let [a 1] (let [b 2] (+ a b)))) (test-same let-nested-shadow (let [a 1] (let [b 2] (let [a 10] (+ a b))))) (test-same let-name-reuse-1 (let [a 4 b (mapv inc (range a)) a "A Vector: "] (str a b))) (test-same let-name-reuse-2 (let [a 20 a (range a) a (map inc a) a (mapv str a)] a)) (test-same let-as-expr (map inc (let [a 8] (range a (let [b (long (count "Hello"))] (+ a b)))))) (test-same let-vector-destructure (let [[a b c] [1 2 3]] (+ a b c))) (test-same let-map-destructure (let [{:keys [a b c]} {:a 1 :b 2 :c 3}] (+ a b c))) (run-tests) (comment (binding [*compile-path* "."] (compile 'magic.reference)) (binding [*test-out* *out*] (run-tests)) )
31123834c14c19a03d9efb26a405dea0525b854a15edb4a8b240926479c401b6
reborg/clojure-essential-reference
3.clj
(import '[java.net URL]) (import '[java.util.zip ZipInputStream]) (require '[clojure.java.io :as io]) (def alexa "-static/top-1m.csv.zip") < 1 > (-> (URL. url) .openConnection .getInputStream ZipInputStream. (doto .getNextEntry) io/reader)) < 2 > (some-> line (.split "\\.") last)) (defn first-of-domain [ext] ; <3> (with-open [r (zip-reader alexa)] (some #(when (= ext (domain %)) %) (line-seq r)))) (first-of-domain "me") ;; "340,xx1.me"
null
https://raw.githubusercontent.com/reborg/clojure-essential-reference/c37fa19d45dd52b2995a191e3e96f0ebdc3f6d69/SequentialGeneration/OtherGenerators/line-seq/3.clj
clojure
<3> "340,xx1.me"
(import '[java.net URL]) (import '[java.util.zip ZipInputStream]) (require '[clojure.java.io :as io]) (def alexa "-static/top-1m.csv.zip") < 1 > (-> (URL. url) .openConnection .getInputStream ZipInputStream. (doto .getNextEntry) io/reader)) < 2 > (some-> line (.split "\\.") last)) (with-open [r (zip-reader alexa)] (some #(when (= ext (domain %)) %) (line-seq r)))) (first-of-domain "me")
3e9c9f58aa1f2e38204f68e8cca717e9b1d46a933bea7a3af0195d658ad2599d
hellonico/origami-fun
touring.clj
(ns opencv4.touring (:require [opencv4.utils :as u] [opencv4.core :refer :all])) (def img (-> "resources/morph/hammer2.png" imread pyr-down! )) (def ret (-> img clone (cvt-color! COLOR_BGR2GRAY) (threshold! 127 255 THRESH_BINARY) )) ( u / show ret ) (def contours (new-arraylist)) (find-contours ret contours (new-mat) RETR_EXTERNAL CHAIN_APPROX_SIMPLE) (doseq [c contours] (let [ b (bounding-rect c)] (rectangle img (.tl b) (.br b) (new-scalar 0 255 0) 2))) (u/show img)
null
https://raw.githubusercontent.com/hellonico/origami-fun/80117788530d942eaa9a80e2995b37409fa24889/test/opencv4/touring.clj
clojure
(ns opencv4.touring (:require [opencv4.utils :as u] [opencv4.core :refer :all])) (def img (-> "resources/morph/hammer2.png" imread pyr-down! )) (def ret (-> img clone (cvt-color! COLOR_BGR2GRAY) (threshold! 127 255 THRESH_BINARY) )) ( u / show ret ) (def contours (new-arraylist)) (find-contours ret contours (new-mat) RETR_EXTERNAL CHAIN_APPROX_SIMPLE) (doseq [c contours] (let [ b (bounding-rect c)] (rectangle img (.tl b) (.br b) (new-scalar 0 255 0) 2))) (u/show img)
b1799244ce65f584cfdd90f94884e569fd6a63668f40e40f393e56abdb964a85
defaultxr/cl-collider-tutorial
grains.lisp
(in-package :sc) (defugen (grain-sin "GrainSin") (&optional (numchan 1) (trig 0) (dur 1) (freq 440) (pan 0.0) (envbufnum -1) (max-grains 512) &key (mul 1.0) (add 0.0)) ((:ar (madd (multinew new 'multiout-ugen numchan trig dur freq pan envbufnum max-grains) mul add)))) (defugen (grain-fm "GrainFM") (&optional (numchan 1) (trig 0) (dur 1) (car-freq 440) (mod-freq 200) (index 1) (pan 0.0) (envbufnum -1) (max-grains 512) &key (mul 1.0) (add 0.0)) ((:ar (madd (multinew new 'multiout-ugen numchan trig dur car-freq mod-freq index pan envbufnum max-grains) mul add)))) (defugen (grain-buf "GrainBuf") (&optional (numchan 1) (trig 0) (dur 1) sndbuf (rate 1) (pos 0) (interp 2) (pan 0.0) (envbufnum -1) (max-grains 512) &key (mul 1.0) (add 0.0)) ((:ar (madd (multinew new 'multiout-ugen numchan trig dur sndbuf rate pos interp pan envbufnum max-grains) mul add)))) (defugen (grain-in "GrainIn") (&optional (numchan 1) (trig 0) (dur 1) in (pan 0.0) (envbufnum -1) (max-grains 512) &key (mul 1.0) (add 0.0)) ((:ar (madd (multinew new 'multiout-ugen numchan trig dur in pan envbufnum max-grains) mul add)))) (defugen (warp1 "Warp1") (&optional (numchan 1) (bufnum 0) (pointer 0) (freq-scale 1) (window-size 0.2) (envbufnum -1) (overlaps 8) (window-rand-ratio 0.0) (interp 1) &key (mul 1.0) (add 0.0)) ((:ar (madd (multinew new 'multiout-ugen numchan bufnum pointer freq-scale window-size envbufnum overlaps window-rand-ratio interp) mul add)))) (defugen (pitch-shift "PitchShift") (&optional (in 0.0) (window-size 0.2) (pitch-ratio 1.0) (pitch-dispersion 0.0) (time-dispersion 0.0) &key (mul 1.0) (add 0.0)) ((:ar (madd (multinew new 'pure-ugen in window-size pitch-ratio pitch-dispersion time-dispersion) mul add))))
null
https://raw.githubusercontent.com/defaultxr/cl-collider-tutorial/266ae3e6aaa16d35695266ec884c30626fc8e38d/cl-collider/ugens/grains.lisp
lisp
(in-package :sc) (defugen (grain-sin "GrainSin") (&optional (numchan 1) (trig 0) (dur 1) (freq 440) (pan 0.0) (envbufnum -1) (max-grains 512) &key (mul 1.0) (add 0.0)) ((:ar (madd (multinew new 'multiout-ugen numchan trig dur freq pan envbufnum max-grains) mul add)))) (defugen (grain-fm "GrainFM") (&optional (numchan 1) (trig 0) (dur 1) (car-freq 440) (mod-freq 200) (index 1) (pan 0.0) (envbufnum -1) (max-grains 512) &key (mul 1.0) (add 0.0)) ((:ar (madd (multinew new 'multiout-ugen numchan trig dur car-freq mod-freq index pan envbufnum max-grains) mul add)))) (defugen (grain-buf "GrainBuf") (&optional (numchan 1) (trig 0) (dur 1) sndbuf (rate 1) (pos 0) (interp 2) (pan 0.0) (envbufnum -1) (max-grains 512) &key (mul 1.0) (add 0.0)) ((:ar (madd (multinew new 'multiout-ugen numchan trig dur sndbuf rate pos interp pan envbufnum max-grains) mul add)))) (defugen (grain-in "GrainIn") (&optional (numchan 1) (trig 0) (dur 1) in (pan 0.0) (envbufnum -1) (max-grains 512) &key (mul 1.0) (add 0.0)) ((:ar (madd (multinew new 'multiout-ugen numchan trig dur in pan envbufnum max-grains) mul add)))) (defugen (warp1 "Warp1") (&optional (numchan 1) (bufnum 0) (pointer 0) (freq-scale 1) (window-size 0.2) (envbufnum -1) (overlaps 8) (window-rand-ratio 0.0) (interp 1) &key (mul 1.0) (add 0.0)) ((:ar (madd (multinew new 'multiout-ugen numchan bufnum pointer freq-scale window-size envbufnum overlaps window-rand-ratio interp) mul add)))) (defugen (pitch-shift "PitchShift") (&optional (in 0.0) (window-size 0.2) (pitch-ratio 1.0) (pitch-dispersion 0.0) (time-dispersion 0.0) &key (mul 1.0) (add 0.0)) ((:ar (madd (multinew new 'pure-ugen in window-size pitch-ratio pitch-dispersion time-dispersion) mul add))))
e12c7abba536ac38d47a49bcde4c9ba6d5e756a985d25db211a0174d007359ba
tip-org/tools
Repr.hs
# LANGUAGE DeriveFunctor , , DeriveTraversable # | A representation of programs module Tip.Haskell.Repr where import Data.Foldable (Foldable) import Data.Traversable (Traversable) data Decls a = Decls [Decl a] deriving (Eq,Ord,Show,Functor,Traversable,Foldable) data Decl a = TySig a [Type a] {- class contexts -} (Type a) | FunDecl a [([Pat a],Expr a)] | DataDecl a {- type constructor name -} [a] {- type variables -} [(a,[Type a])] {- constructors -} instance derivings | InstDecl [Type a] {- context -} (Type a) {- head -} [Decl a] {- declarations (associated types and fun decls) -} | ClassDecl [Type a] {- context -} (Type a) {- head -} [Decl a] {- declarations (type signatures) -} | TypeDef (Type a) (Type a) | Decl a `Where` [Decl a] | TH (Expr a) | Module String | LANGUAGE String | QualImport String (Maybe String) deriving (Eq,Ord,Show,Functor,Traversable,Foldable) funDecl :: a -> [a] -> Expr a -> Decl a funDecl f xs b = FunDecl f [(map VarPat xs,b)] data Type a = TyCon a [Type a] | TyVar a | TyTup [Type a] | TyArr (Type a) (Type a) | TyForall [a] (Type a) | TyCtx [Type a] (Type a) | TyImp a (Type a) deriving (Eq,Ord,Show,Functor,Traversable,Foldable) data Expr a = Apply a [Expr a] | ImpVar a | Do [Stmt a] (Expr a) | Lam [Pat a] (Expr a) | Let a (Expr a) (Expr a) | ImpLet a (Expr a) (Expr a) | List [Expr a] -- a literal list | Tup [Expr a] -- a literal tuple | String a -- string from a name... | Noop -- | @return ()@ | Case (Expr a) [(Pat a,Expr a)] | Int Integer | QuoteTyCon a -- Template Haskell '' Template Haskell ' | THSplice (Expr a) -- Template Haskell $(..) | Record (Expr a) [(a,Expr a)] -- record update | Expr a ::: Type a deriving (Eq,Ord,Show,Functor,Traversable,Foldable) nestedTyTup :: [Type a] -> Type a nestedTyTup [] = TyTup [] nestedTyTup (t:ts) = TyTup [t,nestedTyTup ts] nestedTup :: [Expr a] -> Expr a nestedTup [] = Tup [] nestedTup (d:ds) = Tup [d,nestedTup ds] nestedTupPat :: [Pat a] -> Pat a nestedTupPat [] = TupPat [] nestedTupPat (d:ds) = TupPat [d,nestedTupPat ds] mkDo [] x = x mkDo ss1 (Do ss2 e) = mkDo (ss1 ++ ss2) e mkDo ss Noop = case (init ss,last ss) of (i,Stmt e) -> mkDo i e (i,Bind x e) -> mkDo i e mkDo ss e = Do ss e var :: a -> Expr a var x = Apply x [] data Pat a = VarPat a | ConPat a [Pat a] | TupPat [Pat a] | WildPat | IntPat Integer deriving (Eq,Ord,Show,Functor,Traversable,Foldable) data Stmt a = Bind a (Expr a) | Stmt (Expr a) deriving (Eq,Ord,Show,Functor,Traversable,Foldable)
null
https://raw.githubusercontent.com/tip-org/tools/34350072587bd29157d18331eb895a1b2819555f/tip-lib/src/Tip/Haskell/Repr.hs
haskell
class contexts type constructor name type variables constructors context head declarations (associated types and fun decls) context head declarations (type signatures) a literal list a literal tuple string from a name... | @return ()@ Template Haskell '' Template Haskell $(..) record update
# LANGUAGE DeriveFunctor , , DeriveTraversable # | A representation of programs module Tip.Haskell.Repr where import Data.Foldable (Foldable) import Data.Traversable (Traversable) data Decls a = Decls [Decl a] deriving (Eq,Ord,Show,Functor,Traversable,Foldable) data Decl a = TySig a (Type a) | FunDecl a [([Pat a],Expr a)] instance derivings | TypeDef (Type a) (Type a) | Decl a `Where` [Decl a] | TH (Expr a) | Module String | LANGUAGE String | QualImport String (Maybe String) deriving (Eq,Ord,Show,Functor,Traversable,Foldable) funDecl :: a -> [a] -> Expr a -> Decl a funDecl f xs b = FunDecl f [(map VarPat xs,b)] data Type a = TyCon a [Type a] | TyVar a | TyTup [Type a] | TyArr (Type a) (Type a) | TyForall [a] (Type a) | TyCtx [Type a] (Type a) | TyImp a (Type a) deriving (Eq,Ord,Show,Functor,Traversable,Foldable) data Expr a = Apply a [Expr a] | ImpVar a | Do [Stmt a] (Expr a) | Lam [Pat a] (Expr a) | Let a (Expr a) (Expr a) | ImpLet a (Expr a) (Expr a) | Case (Expr a) [(Pat a,Expr a)] | Int Integer Template Haskell ' | Expr a ::: Type a deriving (Eq,Ord,Show,Functor,Traversable,Foldable) nestedTyTup :: [Type a] -> Type a nestedTyTup [] = TyTup [] nestedTyTup (t:ts) = TyTup [t,nestedTyTup ts] nestedTup :: [Expr a] -> Expr a nestedTup [] = Tup [] nestedTup (d:ds) = Tup [d,nestedTup ds] nestedTupPat :: [Pat a] -> Pat a nestedTupPat [] = TupPat [] nestedTupPat (d:ds) = TupPat [d,nestedTupPat ds] mkDo [] x = x mkDo ss1 (Do ss2 e) = mkDo (ss1 ++ ss2) e mkDo ss Noop = case (init ss,last ss) of (i,Stmt e) -> mkDo i e (i,Bind x e) -> mkDo i e mkDo ss e = Do ss e var :: a -> Expr a var x = Apply x [] data Pat a = VarPat a | ConPat a [Pat a] | TupPat [Pat a] | WildPat | IntPat Integer deriving (Eq,Ord,Show,Functor,Traversable,Foldable) data Stmt a = Bind a (Expr a) | Stmt (Expr a) deriving (Eq,Ord,Show,Functor,Traversable,Foldable)
ce742a12364acb46c584982bc7a4d43ded53380900d33ddbb7b9c23bd6e0eeb1
vitorenesduarte/tricks
tricks_driver_socket.erl
%% ------------------------------------------------------------------- %% Copyright ( c ) 2018 . All Rights Reserved . %% This file is provided to you under the Apache License , %% Version 2.0 (the "License"); you may not use this file except in compliance with the License . You may obtain %% a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY %% KIND, either express or implied. See the License for the %% specific language governing permissions and limitations %% under the License. %% %% ------------------------------------------------------------------- %% @doc Driver socket module. -module(tricks_driver_socket). -author("Vitor Enes <>"). -include("tricks.hrl"). %% API -export([connect/2, disconnect/1, configure/1, activate/1, send/2, recv/1]). -type socket() :: inet:socket(). -type ip() :: inet:ip_address(). @doc Connect to a server on TCP port ` Port ' on the host with IP address . -spec connect(ip(), integer()) -> {ok, socket()} | error(). connect(Ip, Port) -> ranch_tcp:connect(Ip, Port, []). %% @doc Close a socket. -spec disconnect(socket()) -> ok. disconnect(Socket) -> ranch_tcp:close(Socket). %% @doc Set `?TCP_OPTIONS' on `Socket'. -spec configure(socket()) -> ok. configure(Socket) -> ranch_tcp:setopts(Socket, ?TCP_OPTIONS). %% @doc Set `?TCP_ACTIVE_OPTION' on `Socket'. -spec activate(socket()) -> ok. activate(Socket) -> ranch_tcp:setopts(Socket, [?TCP_ACTIVE_OPTION]). %% @doc Send `Message' on a `Socket'. -spec send(socket(), iodata()) -> ok | error(). send(Socket, Message) -> ranch_tcp:send(Socket, Message). %% @doc Receive a message from a `Socket'. -spec recv(socket()) -> {ok, iodata()}. recv(Socket) -> %% since we're packaging messages %% length is not relevant. %% @see #recv-2 Length = 0, Timeout = infinity, ranch_tcp:recv(Socket, Length, Timeout).
null
https://raw.githubusercontent.com/vitorenesduarte/tricks/9ba11252be128be481b4d4a00fe162ccdbdac501/src/tricks_driver_socket.erl
erlang
------------------------------------------------------------------- Version 2.0 (the "License"); you may not use this file a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ------------------------------------------------------------------- @doc Driver socket module. API @doc Close a socket. @doc Set `?TCP_OPTIONS' on `Socket'. @doc Set `?TCP_ACTIVE_OPTION' on `Socket'. @doc Send `Message' on a `Socket'. @doc Receive a message from a `Socket'. since we're packaging messages length is not relevant. @see #recv-2
Copyright ( c ) 2018 . All Rights Reserved . This file is provided to you under the Apache License , except in compliance with the License . You may obtain software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY -module(tricks_driver_socket). -author("Vitor Enes <>"). -include("tricks.hrl"). -export([connect/2, disconnect/1, configure/1, activate/1, send/2, recv/1]). -type socket() :: inet:socket(). -type ip() :: inet:ip_address(). @doc Connect to a server on TCP port ` Port ' on the host with IP address . -spec connect(ip(), integer()) -> {ok, socket()} | error(). connect(Ip, Port) -> ranch_tcp:connect(Ip, Port, []). -spec disconnect(socket()) -> ok. disconnect(Socket) -> ranch_tcp:close(Socket). -spec configure(socket()) -> ok. configure(Socket) -> ranch_tcp:setopts(Socket, ?TCP_OPTIONS). -spec activate(socket()) -> ok. activate(Socket) -> ranch_tcp:setopts(Socket, [?TCP_ACTIVE_OPTION]). -spec send(socket(), iodata()) -> ok | error(). send(Socket, Message) -> ranch_tcp:send(Socket, Message). -spec recv(socket()) -> {ok, iodata()}. recv(Socket) -> Length = 0, Timeout = infinity, ranch_tcp:recv(Socket, Length, Timeout).
ee7ab8623933530839c429fce240c97d763060dfd0fbd1d93f91fd821c7f66d9
jwiegley/notes
Produce.hs
{-# LANGUAGE OverloadedStrings #-} module Produce where import Data.ByteString import Pipes import Pipes.Prelude axman6 :: Monad m => Producer ByteString m () -> Producer ByteString m () axman6 src = for src yield
null
https://raw.githubusercontent.com/jwiegley/notes/24574b02bfd869845faa1521854f90e4e8bf5e9a/haskell/Produce.hs
haskell
# LANGUAGE OverloadedStrings #
module Produce where import Data.ByteString import Pipes import Pipes.Prelude axman6 :: Monad m => Producer ByteString m () -> Producer ByteString m () axman6 src = for src yield
85c08bdfbdb4bd89c764aca45e23a4b02aa5b7ba3ab9167cdcc192f6992589a5
dwayne/eopl3
ex2.20.rkt
#lang racket (require (prefix-in bintree: "./ex2.19.rkt")) ;; Bidirectional binary trees ;; ;; Allows for moving up and down (left/right) seemlessly. ;; BiBintree : : = ( ) ) ) ;; Direction ::= left | right (define (number->bi-bintree n) (list (bintree:number->bintree n) '())) (define (bi-bintree->bintree bt) (car bt)) (define (bi-bintree->ancestors bt) (cadr bt)) (define (at-leaf? bt) (bintree:at-leaf? (bi-bintree->bintree bt))) (define (at-root? bt) (null? (bi-bintree->ancestors bt))) (define (current-element bt) (let ([t (bi-bintree->bintree bt)]) (if (bintree:at-leaf? t) (error 'current-element "At leaf") (bintree:bintree->number t)))) (define (move-to-left bt) (match bt [(list t ancestors) (if (bintree:at-leaf? t) (error 'move-to-left "At leaf") (list (bintree:bintree->left t) (cons (list 'left t) ancestors)))])) (define (move-to-right bt) (match bt [(list t ancestors) (if (bintree:at-leaf? t) (error 'move-to-right "At leaf") (list (bintree:bintree->right t) (cons (list 'right t) ancestors)))])) (define (move-up bt) (if (at-root? bt) (error 'move-up "At root") (match bt [(list t ancestors) (match (car ancestors) [(list 'left parent) (list (bintree:with-left parent t) (cdr ancestors))] [(list 'right parent) (list (bintree:with-right parent t) (cdr ancestors))])]))) (define (insert-to-left n bt) (list (bintree:insert-to-left n (bi-bintree->bintree bt)) (bi-bintree->ancestors bt))) (define (insert-to-right n bt) (list (bintree:insert-to-right n (bi-bintree->bintree bt)) (bi-bintree->ancestors bt))) (module+ test (require rackunit) (let ([t (insert-to-right 14 (insert-to-left 12 (number->bi-bintree 13)))]) (check-eq? (current-element (move-to-left (move-to-left (move-up (insert-to-left 15 (move-to-left t)))))) 15)))
null
https://raw.githubusercontent.com/dwayne/eopl3/9d5fdb2a8dafac3bc48852d49cda8b83e7a825cf/solutions/02-ch2/racket/ex2.20.rkt
racket
Bidirectional binary trees Allows for moving up and down (left/right) seemlessly. Direction ::= left | right
#lang racket (require (prefix-in bintree: "./ex2.19.rkt")) BiBintree : : = ( ) ) ) (define (number->bi-bintree n) (list (bintree:number->bintree n) '())) (define (bi-bintree->bintree bt) (car bt)) (define (bi-bintree->ancestors bt) (cadr bt)) (define (at-leaf? bt) (bintree:at-leaf? (bi-bintree->bintree bt))) (define (at-root? bt) (null? (bi-bintree->ancestors bt))) (define (current-element bt) (let ([t (bi-bintree->bintree bt)]) (if (bintree:at-leaf? t) (error 'current-element "At leaf") (bintree:bintree->number t)))) (define (move-to-left bt) (match bt [(list t ancestors) (if (bintree:at-leaf? t) (error 'move-to-left "At leaf") (list (bintree:bintree->left t) (cons (list 'left t) ancestors)))])) (define (move-to-right bt) (match bt [(list t ancestors) (if (bintree:at-leaf? t) (error 'move-to-right "At leaf") (list (bintree:bintree->right t) (cons (list 'right t) ancestors)))])) (define (move-up bt) (if (at-root? bt) (error 'move-up "At root") (match bt [(list t ancestors) (match (car ancestors) [(list 'left parent) (list (bintree:with-left parent t) (cdr ancestors))] [(list 'right parent) (list (bintree:with-right parent t) (cdr ancestors))])]))) (define (insert-to-left n bt) (list (bintree:insert-to-left n (bi-bintree->bintree bt)) (bi-bintree->ancestors bt))) (define (insert-to-right n bt) (list (bintree:insert-to-right n (bi-bintree->bintree bt)) (bi-bintree->ancestors bt))) (module+ test (require rackunit) (let ([t (insert-to-right 14 (insert-to-left 12 (number->bi-bintree 13)))]) (check-eq? (current-element (move-to-left (move-to-left (move-up (insert-to-left 15 (move-to-left t)))))) 15)))
2d4ba6f3307116faa1702a61db8809a5bc9e3431c853fa38531aed4786d45e36
data61/Mirza
Blockchain.hs
module Mirza.SupplyChain.Tests.Blockchain where Tests that should be implemented here Check for tampering by comparing to Blockchain hash eventInfo ← eventInfo(eventID ) joseTxt = joseText eventInfo expectedHash = hash joseText blockchainID = blockchainID eventInfo bcHash = getBlockchainHash(blockchainID ) assert ( bcHash = = expectedHash ) Tests that should be implemented here Check for tampering by comparing to Blockchain hash eventInfo ← eventInfo(eventID) joseTxt = joseText eventInfo expectedHash = hash joseText blockchainID = blockchainID eventInfo bcHash = getBlockchainHash(blockchainID) assert (bcHash == expectedHash) -}
null
https://raw.githubusercontent.com/data61/Mirza/24e5ccddfc307cceebcc5ce26d35e91020b8ee10/projects/or_scs/test/Mirza/SupplyChain/Tests/Blockchain.hs
haskell
module Mirza.SupplyChain.Tests.Blockchain where Tests that should be implemented here Check for tampering by comparing to Blockchain hash eventInfo ← eventInfo(eventID ) joseTxt = joseText eventInfo expectedHash = hash joseText blockchainID = blockchainID eventInfo bcHash = getBlockchainHash(blockchainID ) assert ( bcHash = = expectedHash ) Tests that should be implemented here Check for tampering by comparing to Blockchain hash eventInfo ← eventInfo(eventID) joseTxt = joseText eventInfo expectedHash = hash joseText blockchainID = blockchainID eventInfo bcHash = getBlockchainHash(blockchainID) assert (bcHash == expectedHash) -}
8ffaf3863037e1f49976dc55e0554b387b13796b3ba1ff644e6c0d69a57631d0
boxer-project/boxer-sunrise
host.lisp
-*- Mode : Lisp ; rcs - header : " $ Header : /hope / lwhope1 - cam / hope.0 / compound/61 / LISPopengl / RCS / host.lisp , v 1.4.15.1 2017/01/19 11:51:03 martin Exp $ " -*- Copyright ( c ) 1987 - -2017 LispWorks Ltd. All rights reserved . (in-package "USER") (setf (logical-pathname-translations "OPENGL") `(("**;*" ,(merge-pathnames "**/*" (pathname-location *load-truename*)))))
null
https://raw.githubusercontent.com/boxer-project/boxer-sunrise/1ef5d5a65d00298b0d7a01890b3cd15d78adc1af/src/opengl/host.lisp
lisp
rcs - header : " $ Header : /hope / lwhope1 - cam / hope.0 / compound/61 / LISPopengl / RCS / host.lisp , v 1.4.15.1 2017/01/19 11:51:03 martin Exp $ " -*-
Copyright ( c ) 1987 - -2017 LispWorks Ltd. All rights reserved . (in-package "USER") (setf (logical-pathname-translations "OPENGL") `(("**;*" ,(merge-pathnames "**/*" (pathname-location *load-truename*)))))
dd1e6e21e038143bb03b070abaef45b4177d95740e383b02624b225a73f46e57
typelead/eta
tc203.hs
{ - # OPTIONS_GHC -fno - warn - redundant - constraints # - } {-# LANGUAGE RankNTypes #-} -- Check that we can have a forall after a forall module Foo4 where type AnyE a = forall err. Either err a foo :: Monad m => AnyE (m t) foo = undefined
null
https://raw.githubusercontent.com/typelead/eta/97ee2251bbc52294efbf60fa4342ce6f52c0d25c/tests/suite/typecheck/compile/tc203.hs
haskell
# LANGUAGE RankNTypes # Check that we can have a forall after a forall
{ - # OPTIONS_GHC -fno - warn - redundant - constraints # - } module Foo4 where type AnyE a = forall err. Either err a foo :: Monad m => AnyE (m t) foo = undefined
6acc2173daf9211a166b417f43856de3db5f83d2c4b434db20fb5454499c2f59
jellelicht/guix
size.scm
;;; GNU Guix --- Functional package management for GNU Copyright © 2015 , 2016 < > ;;; ;;; This file is part of GNU Guix. ;;; GNU 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. ;;; ;;; GNU Guix 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 GNU . If not , see < / > . (define-module (guix scripts size) #:use-module (guix ui) #:use-module (guix scripts) #:use-module (guix store) #:use-module (guix monads) #:use-module (guix utils) #:use-module (guix grafts) #:use-module (guix packages) #:use-module (guix derivations) #:use-module (gnu packages) #:use-module (srfi srfi-1) #:use-module (srfi srfi-9) #:use-module (srfi srfi-11) #:use-module (srfi srfi-34) #:use-module (srfi srfi-37) #:use-module (ice-9 match) #:use-module (ice-9 format) #:export (profile? profile-file profile-self-size profile-closure-size store-profile guix-size)) ;; Size profile of a store item. (define-record-type <profile> (profile file self-size closure-size) profile? (file profile-file) ;store item (self-size profile-self-size) ;size in bytes (closure-size profile-closure-size)) ;size of dependencies in bytes (define substitutable-path-info* (store-lift substitutable-path-info)) (define (query-path-info* item) "Monadic version of 'query-path-info' that returns #f when ITEM is not in the store." (lambda (store) (guard (c ((nix-protocol-error? c) ITEM is not in the store ; return # f. (values #f store))) (values (query-path-info store item) store)))) (define (file-size item) "Return the size in bytes of ITEM, resorting to information from substitutes if ITEM is not in the store." (mlet %store-monad ((info (query-path-info* item))) (if info (return (path-info-nar-size info)) (mlet %store-monad ((info (substitutable-path-info* (list item)))) (match info ((info) The nar size is an approximation , but a good one . (return (substitutable-nar-size info))) (() (leave (_ "no available substitute information for '~a'~%") item))))))) (define* (display-profile profile #:optional (port (current-output-port))) "Display PROFILE, a list of PROFILE objects, to PORT." (define MiB (expt 2 20)) (format port "~64a ~8a ~a\n" (_ "store item") (_ "total") (_ "self")) (let ((whole (reduce + 0 (map profile-self-size profile)))) (for-each (match-lambda (($ <profile> name self total) (format port "~64a ~6,1f ~6,1f ~5,1f%\n" name (/ total MiB) (/ self MiB) (* 100. (/ self whole 1.))))) (sort profile (match-lambda* ((($ <profile> _ _ total1) ($ <profile> _ _ total2)) (> total1 total2))))))) (define display-profile* (lift display-profile %store-monad)) (define (substitutable-requisites store item) "Return the list of requisites of ITEM based on information available in substitutes." (let loop ((items (list item)) (result '())) (match items (() (delete-duplicates result)) (items (let ((info (substitutable-path-info store (delete-duplicates items)))) (loop (remove (lambda (item) ;XXX: complexity (member item result)) (append-map substitutable-references info)) (append (append-map substitutable-references info) result))))))) (define (requisites* item) "Return as a monadic value the requisites of ITEMS, based either on the information available in the local store or using information about substitutes." (lambda (store) (guard (c ((nix-protocol-error? c) (values (substitutable-requisites store item) store))) (values (requisites store item) store)))) (define (store-profile item) "Return as a monadic value a list of <profile> objects representing the profile of ITEM and its requisites." (mlet* %store-monad ((refs (>>= (requisites* item) (lambda (refs) (return (delete-duplicates (cons item refs)))))) (sizes (mapm %store-monad (lambda (item) (>>= (file-size item) (lambda (size) (return (cons item size))))) refs))) (define (dependency-size item) (mlet %store-monad ((deps (requisites* item))) (foldm %store-monad (lambda (item total) (return (+ (assoc-ref sizes item) total))) 0 (delete-duplicates (cons item deps))))) (mapm %store-monad (match-lambda ((item . size) (mlet %store-monad ((dependencies (dependency-size item))) (return (profile item size dependencies))))) sizes))) (define* (ensure-store-item spec-or-item) "Return a store file name. If SPEC-OR-ITEM is a store file name, return it as is. Otherwise, assume SPEC-OR-ITEM is a package output specification such as \"guile:debug\" or \"gcc-4.8\" and return its store file name." (with-monad %store-monad (if (store-path? spec-or-item) (return spec-or-item) (let-values (((package output) (specification->package+output spec-or-item))) (mlet %store-monad ((drv (package->derivation package))) Note : we do n't try building DRV like ' guix archive ' does ;; because we don't have to since we can instead rely on ;; substitute meta-data. (return (derivation->output-path drv output))))))) ;;; ;;; Charts. ;;; Autoload Guile - Charting . ;; XXX: Use this hack instead of #:autoload to avoid compilation errors. ;; See <>. (module-autoload! (current-module) '(charting) '(make-page-map)) (define (profile->page-map profiles file) "Write a 'page map' chart of PROFILES, a list of <profile> objects, to FILE, the name of a PNG file." (define (strip name) (string-drop name (+ (string-length (%store-prefix)) 28))) (define data (fold2 (lambda (profile result offset) (match profile (($ <profile> name self) (let ((self (inexact->exact (round (/ self (expt 2. 10)))))) (values `((,(strip name) ,offset . ,self) ,@result) (+ offset self)))))) '() 0 (sort profiles (match-lambda* ((($ <profile> _ _ total1) ($ <profile> _ _ total2)) (> total1 total2)))))) ;; TRANSLATORS: This is the title of a graph, meaning that the graph ;; represents a profile of the store (the "store" being the place where ;; packages are stored.) (make-page-map (_ "store profile") data #:write-to-png file)) ;;; ;;; Options. ;;; (define (show-help) (display (_ "Usage: guix size [OPTION]... PACKAGE Report the size of PACKAGE and its dependencies.\n")) (display (_ " --substitute-urls=URLS fetch substitute from URLS if they are authorized")) (display (_ " -s, --system=SYSTEM consider packages for SYSTEM--e.g., \"i686-linux\"")) (display (_ " -m, --map-file=FILE write to FILE a graphical map of disk usage")) (newline) (display (_ " -h, --help display this help and exit")) (display (_ " -V, --version display version information and exit")) (newline) (show-bug-report-information)) (define %options ;; Specifications of the command-line options. (list (option '(#\s "system") #t #f (lambda (opt name arg result) (alist-cons 'system arg (alist-delete 'system result eq?)))) (option '("substitute-urls") #t #f (lambda (opt name arg result . rest) (apply values (alist-cons 'substitute-urls (string-tokenize arg) (alist-delete 'substitute-urls result)) rest))) (option '(#\m "map-file") #t #f (lambda (opt name arg result) (alist-cons 'map-file arg result))) (option '(#\h "help") #f #f (lambda args (show-help) (exit 0))) (option '(#\V "version") #f #f (lambda args (show-version-and-exit "guix size"))))) (define %default-options `((system . ,(%current-system)))) ;;; ;;; Entry point. ;;; (define (guix-size . args) (with-error-handling (let* ((opts (parse-command-line args %options (list %default-options))) (files (filter-map (match-lambda (('argument . file) file) (_ #f)) opts)) (map-file (assoc-ref opts 'map-file)) (system (assoc-ref opts 'system)) (urls (assoc-ref opts 'substitute-urls))) (match files (() (leave (_ "missing store item argument\n"))) ((file) (leave-on-EPIPE Turn off grafts because ( 1 ) hydra.gnu.org does not serve grafted packages , and ( 2 ) they do not make any difference on the ;; resulting size. (parameterize ((%graft? #f)) (with-store store (set-build-options store #:use-substitutes? #t #:substitute-urls urls) (run-with-store store (mlet* %store-monad ((item (ensure-store-item file)) (profile (store-profile item))) (if map-file (begin (profile->page-map profile map-file) (return #t)) (display-profile* profile))) #:system system))))) ((files ...) (leave (_ "too many arguments\n")))))))
null
https://raw.githubusercontent.com/jellelicht/guix/83cfc9414fca3ab57c949e18c1ceb375a179b59c/guix/scripts/size.scm
scheme
GNU Guix --- Functional package management for GNU This file is part of GNU Guix. you can redistribute it and/or modify it either version 3 of the License , or ( at your option) any later version. GNU Guix 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. Size profile of a store item. store item size in bytes size of dependencies in bytes return # f. XXX: complexity because we don't have to since we can instead rely on substitute meta-data. Charts. XXX: Use this hack instead of #:autoload to avoid compilation errors. See <>. TRANSLATORS: This is the title of a graph, meaning that the graph represents a profile of the store (the "store" being the place where packages are stored.) Options. Specifications of the command-line options. Entry point. resulting size.
Copyright © 2015 , 2016 < > under the terms of the GNU General Public License as published by You should have received a copy of the GNU General Public License along with GNU . If not , see < / > . (define-module (guix scripts size) #:use-module (guix ui) #:use-module (guix scripts) #:use-module (guix store) #:use-module (guix monads) #:use-module (guix utils) #:use-module (guix grafts) #:use-module (guix packages) #:use-module (guix derivations) #:use-module (gnu packages) #:use-module (srfi srfi-1) #:use-module (srfi srfi-9) #:use-module (srfi srfi-11) #:use-module (srfi srfi-34) #:use-module (srfi srfi-37) #:use-module (ice-9 match) #:use-module (ice-9 format) #:export (profile? profile-file profile-self-size profile-closure-size store-profile guix-size)) (define-record-type <profile> (profile file self-size closure-size) profile? (define substitutable-path-info* (store-lift substitutable-path-info)) (define (query-path-info* item) "Monadic version of 'query-path-info' that returns #f when ITEM is not in the store." (lambda (store) (guard (c ((nix-protocol-error? c) (values #f store))) (values (query-path-info store item) store)))) (define (file-size item) "Return the size in bytes of ITEM, resorting to information from substitutes if ITEM is not in the store." (mlet %store-monad ((info (query-path-info* item))) (if info (return (path-info-nar-size info)) (mlet %store-monad ((info (substitutable-path-info* (list item)))) (match info ((info) The nar size is an approximation , but a good one . (return (substitutable-nar-size info))) (() (leave (_ "no available substitute information for '~a'~%") item))))))) (define* (display-profile profile #:optional (port (current-output-port))) "Display PROFILE, a list of PROFILE objects, to PORT." (define MiB (expt 2 20)) (format port "~64a ~8a ~a\n" (_ "store item") (_ "total") (_ "self")) (let ((whole (reduce + 0 (map profile-self-size profile)))) (for-each (match-lambda (($ <profile> name self total) (format port "~64a ~6,1f ~6,1f ~5,1f%\n" name (/ total MiB) (/ self MiB) (* 100. (/ self whole 1.))))) (sort profile (match-lambda* ((($ <profile> _ _ total1) ($ <profile> _ _ total2)) (> total1 total2))))))) (define display-profile* (lift display-profile %store-monad)) (define (substitutable-requisites store item) "Return the list of requisites of ITEM based on information available in substitutes." (let loop ((items (list item)) (result '())) (match items (() (delete-duplicates result)) (items (let ((info (substitutable-path-info store (delete-duplicates items)))) (member item result)) (append-map substitutable-references info)) (append (append-map substitutable-references info) result))))))) (define (requisites* item) "Return as a monadic value the requisites of ITEMS, based either on the information available in the local store or using information about substitutes." (lambda (store) (guard (c ((nix-protocol-error? c) (values (substitutable-requisites store item) store))) (values (requisites store item) store)))) (define (store-profile item) "Return as a monadic value a list of <profile> objects representing the profile of ITEM and its requisites." (mlet* %store-monad ((refs (>>= (requisites* item) (lambda (refs) (return (delete-duplicates (cons item refs)))))) (sizes (mapm %store-monad (lambda (item) (>>= (file-size item) (lambda (size) (return (cons item size))))) refs))) (define (dependency-size item) (mlet %store-monad ((deps (requisites* item))) (foldm %store-monad (lambda (item total) (return (+ (assoc-ref sizes item) total))) 0 (delete-duplicates (cons item deps))))) (mapm %store-monad (match-lambda ((item . size) (mlet %store-monad ((dependencies (dependency-size item))) (return (profile item size dependencies))))) sizes))) (define* (ensure-store-item spec-or-item) "Return a store file name. If SPEC-OR-ITEM is a store file name, return it as is. Otherwise, assume SPEC-OR-ITEM is a package output specification such as \"guile:debug\" or \"gcc-4.8\" and return its store file name." (with-monad %store-monad (if (store-path? spec-or-item) (return spec-or-item) (let-values (((package output) (specification->package+output spec-or-item))) (mlet %store-monad ((drv (package->derivation package))) Note : we do n't try building DRV like ' guix archive ' does (return (derivation->output-path drv output))))))) Autoload Guile - Charting . (module-autoload! (current-module) '(charting) '(make-page-map)) (define (profile->page-map profiles file) "Write a 'page map' chart of PROFILES, a list of <profile> objects, to FILE, the name of a PNG file." (define (strip name) (string-drop name (+ (string-length (%store-prefix)) 28))) (define data (fold2 (lambda (profile result offset) (match profile (($ <profile> name self) (let ((self (inexact->exact (round (/ self (expt 2. 10)))))) (values `((,(strip name) ,offset . ,self) ,@result) (+ offset self)))))) '() 0 (sort profiles (match-lambda* ((($ <profile> _ _ total1) ($ <profile> _ _ total2)) (> total1 total2)))))) (make-page-map (_ "store profile") data #:write-to-png file)) (define (show-help) (display (_ "Usage: guix size [OPTION]... PACKAGE Report the size of PACKAGE and its dependencies.\n")) (display (_ " --substitute-urls=URLS fetch substitute from URLS if they are authorized")) (display (_ " -s, --system=SYSTEM consider packages for SYSTEM--e.g., \"i686-linux\"")) (display (_ " -m, --map-file=FILE write to FILE a graphical map of disk usage")) (newline) (display (_ " -h, --help display this help and exit")) (display (_ " -V, --version display version information and exit")) (newline) (show-bug-report-information)) (define %options (list (option '(#\s "system") #t #f (lambda (opt name arg result) (alist-cons 'system arg (alist-delete 'system result eq?)))) (option '("substitute-urls") #t #f (lambda (opt name arg result . rest) (apply values (alist-cons 'substitute-urls (string-tokenize arg) (alist-delete 'substitute-urls result)) rest))) (option '(#\m "map-file") #t #f (lambda (opt name arg result) (alist-cons 'map-file arg result))) (option '(#\h "help") #f #f (lambda args (show-help) (exit 0))) (option '(#\V "version") #f #f (lambda args (show-version-and-exit "guix size"))))) (define %default-options `((system . ,(%current-system)))) (define (guix-size . args) (with-error-handling (let* ((opts (parse-command-line args %options (list %default-options))) (files (filter-map (match-lambda (('argument . file) file) (_ #f)) opts)) (map-file (assoc-ref opts 'map-file)) (system (assoc-ref opts 'system)) (urls (assoc-ref opts 'substitute-urls))) (match files (() (leave (_ "missing store item argument\n"))) ((file) (leave-on-EPIPE Turn off grafts because ( 1 ) hydra.gnu.org does not serve grafted packages , and ( 2 ) they do not make any difference on the (parameterize ((%graft? #f)) (with-store store (set-build-options store #:use-substitutes? #t #:substitute-urls urls) (run-with-store store (mlet* %store-monad ((item (ensure-store-item file)) (profile (store-profile item))) (if map-file (begin (profile->page-map profile map-file) (return #t)) (display-profile* profile))) #:system system))))) ((files ...) (leave (_ "too many arguments\n")))))))
16880c95f7035984b7d6cabbacb736fd1c150ca642666f741aa402de5732bab3
mcorbin/tour-of-clojure
fn_nb.clj
(ns tourofclojure.pages.fn-nb (:require [hiccup.element :refer [link-to]] [clojure.java.io :as io] [tourofclojure.pages.util :refer [navigation-block]])) (def code (slurp (io/resource "public/pages/code/fn_nb.clj"))) (defn desc [previous next lang] (condp = lang "fr" [:div [:h2 "Opérations sur les nombres"] [:p "Voici quelques opérations sur des nombres."] [:p "Un certain nombre de ces fonctions acceptent un nombre indéfini de" " paramètres. C'est le cas par exemple de la fonction " [:b "+"] "."] [:pre [:code "(+ 1 2 3 4 5)"]] [:p "Des spécificités peuvent exister selon la plateforme sur lequel" " vous faites" " tourner Clojure (JVM, CLR, ClojureScript), car Clojure s'appuie sur les" " types de la plateforme hôte."] (navigation-block previous next)] [:h2 "Language not supported."])) (defn page [previous next lang] [(desc previous next lang) code])
null
https://raw.githubusercontent.com/mcorbin/tour-of-clojure/57f97b68ca1a8c96904bfb960f515217eeda24a6/src/tourofclojure/pages/fn_nb.clj
clojure
(ns tourofclojure.pages.fn-nb (:require [hiccup.element :refer [link-to]] [clojure.java.io :as io] [tourofclojure.pages.util :refer [navigation-block]])) (def code (slurp (io/resource "public/pages/code/fn_nb.clj"))) (defn desc [previous next lang] (condp = lang "fr" [:div [:h2 "Opérations sur les nombres"] [:p "Voici quelques opérations sur des nombres."] [:p "Un certain nombre de ces fonctions acceptent un nombre indéfini de" " paramètres. C'est le cas par exemple de la fonction " [:b "+"] "."] [:pre [:code "(+ 1 2 3 4 5)"]] [:p "Des spécificités peuvent exister selon la plateforme sur lequel" " vous faites" " tourner Clojure (JVM, CLR, ClojureScript), car Clojure s'appuie sur les" " types de la plateforme hôte."] (navigation-block previous next)] [:h2 "Language not supported."])) (defn page [previous next lang] [(desc previous next lang) code])
d5b0aac3d84420f52ffbbff51afd1248d88987415c69c72a8b0eb4b2d93a31fb
russross/cownfs
nfs_api.ml
Copyright 2004 , 2005 * See the file COPYING for information about licensing and distribution . * See the file COPYING for information about licensing and distribution. *) TODO : - copy on write files should be deleted on operation failure - rename of directories needs to create / modify .mount file - remove of dirs needs to delete .~ files if the dir is otherwise empty - mounted paths should be constrained - shadow dirs should be deleted if the op fails - dirTree ops should respect .~ mask files - copy on write files should be deleted on operation failure - rename of directories needs to create/modify .mount file - remove of dirs needs to delete .~ files if the dir is otherwise empty - mounted paths should be constrained - shadow dirs should be deleted if the op fails - dirTree ops should respect .~ mask files *) open Common;; open Unix;; open Unix.LargeFile;; open Nfs3_prot_caux;; module SSet = Set.Make (String);; module L = Lookup;; (* Misc utility functions *****************************************************) let block_size = ref 8192 let buffer_size = 8192 let startup_cookie = Rtypes.fp8_as_string (Rtypes.fp8_of_float (Unix.time ())) let file_system_id = 51423 let lchown = Util.lchown let s2fh = Fh.ofString let fh2s = Fh.toString let default_perm = 0o644 let checkaccess fattr mask = Rtypes.uint4_of_int 0 let fileids = Hashtbl.create 5000 let fileids = Hashtbl.create 5000 *) let fileid_of_name = Util.hash64 Rtypes.uint8_of_int64 ( Int64.abs ( Util.hashString64 Int64.zero name ) ) Rtypes.uint8_of_int64 (Int64.abs (Util.hashString64 Int64.zero name)) *) let fileid_of_name name = let res = fileid_of_name name in ( * let res = Rtypes.uint8_of_int ( abs ( Util.hashString 0 name ) ) in let fileid_of_name name = let res = fileid_of_name name in (*let res = Rtypes.uint8_of_int (abs (Util.hashString 0 name)) in*) try if Hashtbl.find fileids res <> name then begin prerr_string ("fileid_of_name: collision for id "^ (Int64.to_string (Rtypes.int64_of_uint8 res))^ " old="^(Hashtbl.find fileids res)^ " new="^name); prerr_newline (); end; if Util.startsWith name "/local" then begin prerr_string ("fileid_of_name: bad name ["^name^"]"); prerr_newline (); failwith "fileid_of_name" end; res with Not_found -> Hashtbl.add fileids res name; res *) let nfs_time sec = let (frac, whole) = modf sec in let nano = frac *. 1000000000.0 in { seconds = Rtypes.logical_uint4_of_int32 (Int32.of_float (whole +. 0.5)); nseconds = Rtypes.logical_uint4_of_int32 (Int32.of_float (nano +. 0.5)) } let float_of_nfs_time nfstime = match nfstime with { seconds = s; nseconds = ns } -> Int32.to_float (Rtypes.int32_of_uint4 s) +. (Int32.to_float (Rtypes.int32_of_uint4 ns) /. 1000000000.0) let nfs_stat info fake = { type' = begin match info.st_kind with | S_REG -> nf3reg | S_DIR -> nf3dir | S_CHR -> nf3chr | S_BLK -> nf3blk | S_LNK -> nf3lnk | S_FIFO -> nf3fifo | S_SOCK -> nf3sock end; mode = Rtypes.uint4_of_int info.st_perm; nlink = Rtypes.uint4_of_int info.st_nlink; uid = Rtypes.uint4_of_int info.st_uid; gid = Rtypes.uint4_of_int info.st_gid; size = Rtypes.uint8_of_int64 info.st_size; used = Rtypes.uint8_of_int64 info.st_size; rdev = { major = Rtypes.uint4_of_int ((info.st_rdev land 0xff00) lsr 8); minor = Rtypes.uint4_of_int (info.st_rdev land 0x00ff) }; fsid = Rtypes.uint8_of_int file_system_id; fileid = fileid_of_name fake; atime = nfs_time info.st_atime; mtime = nfs_time info.st_mtime; ctime = nfs_time info.st_ctime } let s64 n = Int64.to_string (Rtypes.int64_of_uint8 n) let s32 n = Int32.to_string (Rtypes.int32_of_uint4 n) let ss32 n = Int32.to_string (Rtypes.int32_of_int4 n) let print_nfs_stat info = prerr_string ( " nfs_stat:"^ " mode="^(s32 info.mode)^ " fileid="^(s64 info.fileid)^ " mtime="^(s32 info.mtime.seconds)^ " ctime="^(s32 info.ctime.seconds)^ " rdev=(major="^(s32 info.rdev.major)^ " minor="^(s32 info.rdev.minor)^ " fsid="^(s64 " type'="^(ss32 info.type ' ) ) ; prerr_newline ( ) ; let print_nfs_stat info = prerr_string ("nfs_stat:"^ " mode="^(s32 info.mode)^ " fileid="^(s64 info.fileid)^ " mtime="^(s32 info.mtime.seconds)^ " ctime="^(s32 info.ctime.seconds)^ " rdev=(major="^(s32 info.rdev.major)^ " minor="^(s32 info.rdev.minor)^ " fsid="^(s64 info.fsid)^ " type'="^(ss32 info.type')); prerr_newline (); *) (* package a Unix stat record for a pre_op_attr result *) let pre_op_attr info = `True { size' = Rtypes.uint8_of_int64 info.st_size; mtime' = nfs_time (info.st_mtime); ctime' = nfs_time (info.st_ctime) } let print_pre_op_attr info = match info with | ` True { size ' = s ; ' = { seconds = ; ; ctime ' = { seconds = csec ; } } - > begin prerr_string ( " pre_op_attr:"^ " size="^(s64 s)^ " mtime="^(s32 msec)^ " ctime="^(s32 csec ) ) ; prerr_newline ( ) end ; info | ` False - > info let print_pre_op_attr info = match info with | `True { size' = s; mtime' = { seconds = msec; nseconds = mnsec }; ctime' = { seconds = csec; nseconds = cnsec } } -> begin prerr_string ("pre_op_attr:"^ " size="^(s64 s)^ " mtime="^(s32 msec)^ " ctime="^(s32 csec)); prerr_newline () end; info | `False -> info *) (* package a Unix stat record for a post_op_attr result *) let post_op_attr info fake = `True (nfs_stat info fake) (* let print_post_op_attr info = match info with | `True i -> ignore (print_nfs_stat i); info | `False -> info *) let file_perm_of_sattr3 attr = match attr.mode' with | `True mode -> Rtypes.int_of_uint4 mode | _ -> failwith "file_perm_of_sattr3 called with `False" let string8_of_int i = let res = String.create 8 in res.[0] <- char_of_int ((i land 0x7f000000) lsr 24); res.[1] <- char_of_int ((i land 0x00ff0000) lsr 16); res.[2] <- char_of_int ((i land 0x0000ff00) lsr 8); res.[3] <- char_of_int (i land 0x000000ff); res.[4] <- '\000'; res.[5] <- '\000'; res.[6] <- '\000'; res.[7] <- '\000'; res let int_of_string8 s = ((int_of_char s.[0]) lsl 24) lor ((int_of_char s.[1]) lsl 16) lor ((int_of_char s.[2]) lsl 8) lor (int_of_char s.[3]) let ( uid , gid , , hostname ) = Rpc_auth_sys.parse_user_name ( session ) in ( uid , gid : : ( Array.to_list ) , hostname ) let (uid, gid, gid_arr, hostname) = Rpc_auth_sys.parse_user_name (Rpc_server.get_user session) in (uid, gid :: (Array.to_list gid_arr), hostname) *) let perm (* info *) = let read = Rtypes.int_of_uint4 access3_read in let write = (Rtypes.int_of_uint4 access3_modify) lor (Rtypes.int_of_uint4 access3_extend) lor (Rtypes.int_of_uint4 access3_delete) in let exec = (Rtypes.int_of_uint4 access3_lookup) lor (Rtypes.int_of_uint4 access3_execute) in let p info = let owner = (if info.st_perm land 0o400 <> 0 then read else 0) lor (if info.st_perm land 0o200 <> 0 then write else 0) lor (if info.st_perm land 0o100 <> 0 then exec else 0) in let group = (if info.st_perm land 0o040 <> 0 then read else 0) lor (if info.st_perm land 0o020 <> 0 then write else 0) lor (if info.st_perm land 0o010 <> 0 then exec else 0) in let world = (if info.st_perm land 0o004 <> 0 then read else 0) lor (if info.st_perm land 0o002 <> 0 then write else 0) lor (if info.st_perm land 0o001 <> 0 then exec else 0) in (owner, group, world) in p let getperm_user user info = let (uid, gidlist, hostname) = user in let (owner, group, world) = perm info in if uid = info.st_uid then owner else if List.mem info.st_gid gidlist then group else world let getperm session (* info *) = getperm_user (user session) let checkperm_user (uid, gids, hostname) info kind = let kind = Rtypes.int_of_uint4 kind in uid = 0 || (kind land getperm_user (uid, gids, hostname) info <> 0) let checkperm_chown (uid, _, _) info = uid = 0 let checkperm_mknod (uid, _, _) = uid = 0 let checkperm session (* info kind *) = checkperm_user (user session) exception Not_writeable exception Wrong_filetype let create_shadow_dirs state user path file = let rec get_perm parent = try let info = lstat parent in if info.st_kind <> S_DIR then raise Wrong_filetype else info.st_perm with _ -> let perm = get_perm (Util.dirname parent) in mkdir parent perm; let (uid, gids, hostname) = user in chown parent uid (List.hd gids); perm in ignore (get_perm (Util.dirname path)) let copy_file user name_in name_out info = if info.st_kind <> S_REG then raise Wrong_filetype else let fp_in = openfile name_in [O_RDONLY] 0 in try let fp_out = openfile name_out [O_WRONLY; O_CREAT; O_EXCL] info.st_perm in (try let (uid, gids, hostname) = user in fchown fp_out uid (List.hd gids); let buff = String.create buffer_size in let rec copy () = let size = read fp_in buff 0 buffer_size in if size > 0 then begin if size <> (write fp_out buff 0 size) then failwith "copy_file" else copy () end else () in copy (); close fp_out with e -> close fp_out; raise e); close fp_in with e-> close fp_in; raise e let copy_link user name_in name_out info = if info.st_kind <> S_LNK then raise Wrong_filetype else let lnk = readlink name_in in symlink name_out lnk; let (uid, gids, hostname) = user in lchown name_out uid (List.hd gids) let copy_dir user name_in name_out info = if info.st_kind <> S_DIR then raise Wrong_filetype else mkdir name_out info.st_perm; let (uid, gids, hostname) = user in chown name_out uid (List.hd gids) (* TODO: more squashing--shadow dir creation, dir permission changes, etc. *) let copy_on_write state user file paths = match paths with | (Some (readname, readinfo), Some writename) -> if readname = writename then (writename, readinfo) else begin let fh = match file with FhOnly fh -> fh | FhName (fh, _) -> fh in L.squash state (FhOnly fh); match readinfo.st_kind with | S_REG -> begin create_shadow_dirs state user writename file; copy_file user readname writename readinfo; (writename, lstat writename) end | S_LNK -> begin create_shadow_dirs state user writename file; copy_link user readname writename readinfo; (writename, lstat writename) end | S_DIR -> begin create_shadow_dirs state user writename file; copy_dir user readname writename readinfo; (writename, lstat writename) end | _ -> raise Not_writeable end | (Some _, None) -> raise Not_writeable | (None, _) -> raise Not_found let remove_mask path = let hidename = Util.concatPath (Util.dirname path) (".~"^(Util.filename path)) in try let info = lstat hidename in (* this gets called by create ops, so the user already has permission to * the directory *) if info.st_kind = S_REG && info.st_size = 0L then Unix.unlink hidename with Unix_error _ -> () (* Exceptions *****************************************************************) exception Noent exception Notdir exception Inval exception Bad_cookie exception Bad_type exception Not_sync exception Notsupp exception Acces exception Exist exception Isdir exception Hide_failed exception Perm exception Unimplemented let unixerr err arg = match err with | EPERM -> `nfs3err_perm arg | ENOENT -> `nfs3err_noent arg | EIO -> `nfs3err_io arg | ENXIO -> `nfs3err_nxio arg | EACCES -> `nfs3err_acces arg | EEXIST -> `nfs3err_exist arg | EXDEV -> `nfs3err_xdev arg | ENODEV -> `nfs3err_nodev arg | ENOTDIR -> `nfs3err_notdir arg | EISDIR -> `nfs3err_isdir arg | EINVAL -> `nfs3err_inval arg | EFBIG -> `nfs3err_fbig arg | ENOSPC -> `nfs3err_nospc arg | EROFS -> `nfs3err_rofs arg | EMLINK -> `nfs3err_mlink arg | ENAMETOOLONG -> `nfs3err_nametoolong arg | ENOTEMPTY -> `nfs3err_notempty arg (*| EDQUOT -> `nfs3err_dquot arg *) | - > ` nfs3err_stale arg (*| EREMOTE -> `nfs3err_remote arg *) | EBADF -> `nfs3err_badhandle arg (*| ENOT_SYNC -> `nfs3err_not_sync arg *) (*| EBAD_COOKIE -> `nfs3err_bad_cookie arg *) | ENOTSUPP - > ` nfs3err_notsupp arg (*| ETOOSMALL -> `nfs3err_toosmall arg *) (*| EBADTYPE -> `nfs3err_badtype arg *) (*| EJUKEBOX -> `nfs3err_jukebox arg *) | EFPRINTNOTFOUND - > ` nfs3err_fprintnotfound arg (*| EABORTED -> `nfs3err_aborted arg *) | _ -> `nfs3err_serverfault arg let handle_exp exp res = if exp <> Noent then begin prerr_endline ("*** exception "^(Printexc.to_string exp)) end; match exp with | Noent -> `nfs3err_noent res | Notdir -> `nfs3err_notdir res | Inval -> `nfs3err_inval res | Bad_cookie -> `nfs3err_bad_cookie res | Bad_type -> `nfs3err_badtype res | Not_sync -> `nfs3err_not_sync res | Notsupp -> `nfs3err_notsupp res | Acces -> `nfs3err_acces res | Exist -> `nfs3err_exist res | Isdir -> `nfs3err_isdir res | Not_writeable -> `nfs3err_acces res | Wrong_filetype -> `nfs3err_acces res | Unix_error (err, s1, s2) -> unixerr err res | Unimplemented -> `nfs3err_notsupp res | Hide_failed -> `nfs3err_acces res | Perm -> `nfs3err_perm res | Not_found -> `nfs3err_stale res | _ -> `nfs3err_serverfault res let hide_fh_name map session fh name = match L.lookupHide map fh name with | (true, Some path) -> begin let (uid, gids, hostname) = user session in create_shadow_dirs map (uid, gids, hostname) path (FhName (fh, name)); let res = Util.create path uid (List.hd gids) 0 (Int32.of_int default_perm) 0l in if res <> 0 then raise Hide_failed end | (true, None) -> raise Hide_failed | (false, _) -> () (* Read operations ************************************************************) let lookup map session arg name info fake = if info.st_kind <> S_DIR then raise Notdir else if not (checkperm session info access3_lookup) then raise Acces else if not (Util.validateName arg.name) then raise Noent else begin let dirFake = L.fhToFake map (s2fh arg.dir.data) in let newFake = Util.concatPath dirFake arg.name in let newFh = L.fakeToNewFh map newFake in match L.lookupRead map newFh with | Some (fname, finfo) -> let fattr = nfs_stat finfo newFake in `nfs3_ok { object'' = { data = fh2s newFh }; obj_attributes' = `True fattr; dir_attributes = `True (nfs_stat info fake) } | None -> raise Noent end let access map session arg name info fake = let attr = nfs_stat info fake in let (uid, gids, hostname) = user session in let perms = if uid = 0 then Rtypes.int_of_uint4 arg.access else (Rtypes.int_of_uint4 arg.access) land (getperm session info) in `nfs3_ok { obj_attributes'' = (`True attr); access' = Rtypes.uint4_of_int perms } let readlink map session arg name info fake = if not (checkperm session info access3_read) then raise Acces else if info.st_kind <> S_LNK then raise Inval else `nfs3_ok { symlink_attributes = (`True (nfs_stat info fake)); data' = Unix.readlink name } let read map session arg name info fake = if not (checkperm session info access3_read) then raise Acces else let start = Rtypes.int64_of_uint8 arg.offset in let len = Rtypes.int_of_uint4 arg.count in let buff = String.create len in if start >= info.st_size || len = 0 then `nfs3_ok { file_attributes = (`True (nfs_stat info fake)); count' = Rtypes.uint4_of_int 0; eof = start >= info.st_size; data'' = "" } else let readres = ref 0 in let fp = openfile name [O_RDONLY] 0 in (try readres := pos Unix.read fp buff 0 len); close fp with e -> close fp; raise e); let count = !readres in let result = if count = len then buff else String.sub buff 0 count in let eof = count = 0 || (Int64.add start (Int64.of_int count)) = info.st_size in `nfs3_ok { file_attributes = `True (nfs_stat info fake); count' = Rtypes.uint4_of_int count; eof = eof; data'' = result } (* apply the given function to every file in the given directory *) let readdir_iter f dir = try let handle = in let rec loop ( ) = try f ( handle ) ; loop ( ) with End_of_file - > closedir handle | e - > closedir handle ; raise e in loop ( ) with Unix_error _ - > ( ) let readdir_iter f dir = try let handle = opendir dir in let rec loop () = try f (readdir handle); loop () with End_of_file -> closedir handle | e -> closedir handle; raise e in loop () with Unix_error _ -> () *) let readdir_iter f dir = try f "."; f ".."; Array.iter f (Sys.readdir dir) with Unix_error _ -> () | Sys_error _ -> () (* given a list of stacked directories, gather a full list of visible files *) let readdir_gather dirlist user = let files = ref [] in let masked = ref SSet.empty in let scanOneDir dir = if try not (checkperm_user user (lstat dir) access3_read) with _ -> true then () else let newMasked = ref SSet.empty in let nextFile name = if SSet.mem name !masked then () else begin files := (dir, name) :: !files; newMasked := SSet.add name !newMasked; let len = String.length name in if len > 2 && String.sub name 0 2 = ".~" then newMasked := SSet.add (String.sub name 2 (len - 2)) !newMasked end in readdir_iter nextFile dir; masked := SSet.union !masked !newMasked in List.iter scanOneDir dirlist; !files (* get a list of visible files, from cache if available, else scan dirs *) let readdir_getlist map fh info counter cookie user = try (counter, cookie, L.dirFhInfoToFileList map fh info counter cookie) with Not_found -> (0, 0, readdir_gather (L.lookupReaddir map fh) user) let lst = readdir_gather ( L.lookupReaddir map fh ) user in L.addDirFhInfoFileList map fh info lst ; lst let lst = readdir_gather (L.lookupReaddir map fh) user in L.addDirFhInfoFileList map fh info lst; lst*) type readdir_res = End | Elt of (string * string * Rtypes.uint8 * readdir_res) exception Readdir_too_high (* gather readdir info for the appropriate range of files using the cookie *) this forms the basis for and readdirplus let readdir_common map user fh info cookie cookieverf max maxPlus isPlus = let first = Rtypes.int_of_uint8 cookie in let cookie = int_of_string8 cookieverf in let (counter, cookiestart, files) = readdir_getlist map fh info first cookie user in let hash = ref cookiestart in let eof = ref false in let rec f lst n size sizePlus = match lst with | [] -> if n < first then raise Readdir_too_high else (eof := true; L.squashDirFh map fh; End) | (prefix, file) :: xs -> let size' = size + (Util.readdir_entry_size file) in let sizePlus' = sizePlus + (Util.readdirplus_entry_size file) in if n < first then (hash := Util.hashString !hash file; f xs (succ n) size sizePlus) (* ignore the cookie if n=0 because some clients don't supply 0 *) else if n = first && n <> 0 && !hash <> cookie then raise Bad_cookie else if size' > max || (isPlus && sizePlus' > maxPlus) then (L.addDirFhInfoFileList map fh info n !hash lst; End) else begin hash := Util.hashString !hash file; Elt (prefix, file, Rtypes.uint8_of_int (succ n), f xs (succ n) size' sizePlus') end in let lst = f files counter (Util.readdir_base ()) (Util.readdirplus_base ()) in (!eof, lst, !hash) let readdir map session arg name info fake = let fh = s2fh arg.dir'.data in let maxResultSize = Rtypes.int_of_uint4 arg.count'''' in if not (checkperm session info access3_read) then raise Acces else if info.st_kind <> S_DIR then raise Notdir else let rec package elt = begin match elt with | Elt (prefix, fname, cookie, next) -> (* compute the fh of the entry to force it into the cache *) let newFake = Util.concatPath fake fname in let (*fh'*) _ = L.fakeToNewFh map newFake in Some { fileid' = fileid_of_name newFake; name' = fname; cookie' = cookie; nextentry = package next } | End -> None end in let (eof, lst, hash) = try readdir_common map (user session) fh info arg.cookie arg.cookieverf maxResultSize 0 false with Readdir_too_high -> readdir_common map (user session) fh info (Rtypes.uint8_of_int 0) (string8_of_int 0) maxResultSize 0 false in `nfs3_ok { dir_attributes' = `True (nfs_stat info fake); cookieverf' = string8_of_int hash; reply = { entries = package lst; eof' = eof } } let readdirplus map session arg name info fake = let fh = s2fh arg.dir''.data in let maxResultSize = Rtypes.int_of_uint4 arg.dircount in let maxResultPlusSize = Rtypes.int_of_uint4 arg.maxcount in if info.st_kind <> S_DIR then raise Notdir else let rec package elt = begin match elt with | Elt (prefix, fname, cookie, next) -> let newFake = Util.concatPath fake fname in let fh' = L.fakeToNewFh map newFake in let newReal = Util.concatPath prefix fname in Some { fileid'' = fileid_of_name newFake; name'' = fname; cookie''' = cookie; name_attributes = (try `True (nfs_stat (lstat newReal) newFake) with _ -> `False); name_handle = `True { data = fh2s fh' }; nextentry' = package next } | End -> None end in let (eof, lst, hash) = try readdir_common map (user session) fh info arg.cookie'' arg.cookieverf'' maxResultSize maxResultPlusSize true with Readdir_too_high -> readdir_common map (user session) fh info (Rtypes.uint8_of_int 0) (string8_of_int 0) maxResultSize maxResultPlusSize true in `nfs3_ok { dir_attributes'' = `True (nfs_stat info fake); cookieverf''' = string8_of_int hash; reply' = { entries' = package lst; eof'' = eof } } let fsstat map session arg name info fake = `nfs3_ok { obj_attributes''' = `True (nfs_stat info fake); tbytes = Rtypes.uint8_of_int 1000000000; fbytes = Rtypes.uint8_of_int 500000000; abytes = Rtypes.uint8_of_int 500000000; tfiles = Rtypes.uint8_of_int 100000; ffiles = Rtypes.uint8_of_int 50000; afiles = Rtypes.uint8_of_int 50000; invarsec = Rtypes.uint4_of_int 30 } let fsinfo map session arg name info fake = `nfs3_ok { obj_attributes'''' = `True (nfs_stat info fake); rtmax = Rtypes.uint4_of_int 8192; rtpref = Rtypes.uint4_of_int 8192; rtmult = Rtypes.uint4_of_int 8192; wtmax = Rtypes.uint4_of_int 8192; wtpref = Rtypes.uint4_of_int 8192; wtmult = Rtypes.uint4_of_int 8192; dtpref = Rtypes.uint4_of_int 8192; maxfilesize = Rtypes.uint8_of_int 0x3fffffff; time_delta = { seconds = Rtypes.uint4_of_int 1; nseconds = Rtypes.uint4_of_int 0 }; properties = Rtypes.uint4_of_int (Rtypes.int_of_uint4 fsf3_symlink lor Rtypes.int_of_uint4 fsf3_homogeneous lor Rtypes.int_of_uint4 fsf3_cansettime) } let pathconf map session arg name info fake = `nfs3_ok { obj_attributes''''' = `True (nfs_stat info fake); linkmax = Rtypes.uint4_of_int 1000; name_max = Rtypes.uint4_of_int 127; no_trunc = true; chown_restricted = true; case_insensitive = false; case_preserving = true } (* Write operations ***********************************************************) let setattr map session arg path info readinfo fake = begin match arg.guard with | `True time -> if time <> nfs_time readinfo.st_ctime then raise Not_sync | _ -> () end; let user = (user session) in (* mode changes *) begin if not (checkperm_user user info access3_modify) then raise Acces; match arg.new_attributes.mode' with | `True mode' -> let mode = Rtypes.int_of_uint4 mode' in if mode <> info.st_perm then chmod path mode | `False -> () end; (* size changes *) begin if not (checkperm_user user info access3_modify) then raise Acces; match arg.new_attributes.size'' with | `True size'' -> let size = Rtypes.int64_of_uint8 size'' in if size <> info.st_size then truncate path size | `False -> () end; (* time changes *) begin if not (checkperm_user user info access3_modify) then raise Acces; let currenttime = gettimeofday () in let atime = (match arg.new_attributes.atime' with | `set_to_client_time nfstime -> Some (float_of_nfs_time nfstime) | `dont_change -> None | `set_to_server_time -> Some currenttime) in let mtime = (match arg.new_attributes.mtime'' with | `set_to_client_time nfstime -> Some (float_of_nfs_time nfstime) | `dont_change -> None | `set_to_server_time -> Some currenttime) in match (atime, mtime) with | (Some atime, Some mtime) -> Unix.utimes path atime mtime | (Some atime, None) -> Unix.utimes path atime info.st_mtime | (None, Some mtime) -> Unix.utimes path info.st_atime mtime | (None, None) -> () end; (* uid/gid changes *) begin let newuid = (match arg.new_attributes.uid' with | `True id when Rtypes.int_of_uint4 id <> info.st_uid -> Some (Rtypes.int_of_uint4 id) | _ -> None) in let newgid = (match arg.new_attributes.gid' with | `True id when Rtypes.int_of_uint4 id <> info.st_gid -> Some (Rtypes.int_of_uint4 id) | _ -> None) in let checkgid gidopt (_, gids, _) = match gidopt with None -> false | Some gid -> not (List.mem gid gids) in if (newuid <> None || (checkgid newgid user)) && not (checkperm_chown user info) then raise Perm else match (newuid, newgid) with | (Some uid, Some gid) -> lchown path uid gid | (Some uid, None) -> lchown path uid info.st_gid | (None, Some gid) -> lchown path info.st_uid gid | (None, None) -> () end; match L.lookupRead map (s2fh arg.object'.data) with | Some (postname, postinfo) -> `nfs3_ok { before = pre_op_attr readinfo; after = post_op_attr postinfo fake } | None -> raise Not_sync let write map session arg name info readinfo fake = if not (checkperm session info access3_modify) then raise Acces; let len = Rtypes.int_of_uint4 arg.count'' in let writeres = ref 0 in let fp = openfile name [O_WRONLY] 0 in (try writeres := pos Unix.write fp arg.data''' 0 len); close fp with e -> close fp; raise e); let count = !writeres in match L.lookupRead map (s2fh arg.file'.data) with | Some (postname, postinfo) -> `nfs3_ok { file_wcc = { before = pre_op_attr readinfo; after = post_op_attr postinfo fake }; count''' = Rtypes.uint4_of_int count; committed = file_sync; verf = startup_cookie } | None -> raise Not_sync let commit map session arg name info readinfo = raise Unimplemented (* Create operations **********************************************************) let create map session arg path old wcc = (* permissions check happens in the wrapper *) if not (Util.validateName arg.where.name) then raise Acces else (* check exclusive create conditions *) let matchedcookie = begin match (old, arg.how) with | (Some (oldpath, oldinfo), `exclusive a) when path = oldpath -> if oldinfo.st_kind <> S_REG then raise Exist else the cookie is placed in the atime and fields , so to check it * we need to munge the cookie to match the form returned by lstat * we need to munge the cookie to match the form returned by lstat *) let (cookie1, cookie2) = (Int32.to_float (Rtypes.int32_of_int4 (Rtypes.read_int4 a 0)), Int32.to_float (Rtypes.int32_of_int4 (Rtypes.read_int4 a 4))) in if cookie1 = oldinfo.st_atime && cookie2 = oldinfo.st_mtime then true else raise Exist | (Some (oldpath, oldinfo), `guarded _) when path = oldpath -> raise Exist | (Some (oldpath, oldinfo), `unchecked _) when path = oldpath && oldinfo.st_kind <> S_REG -> raise Exist | _ -> false end in let (uid, gid) = (match (user session) with | (uid, gid :: _, _) -> (uid, gid) | _ -> raise Perm) in let (data1, data2, guardtype) = (match arg.how with | `unchecked a -> (Int32.of_int (file_perm_of_sattr3 a), 0l, 0) | `guarded a -> (Int32.of_int (file_perm_of_sattr3 a), 0l, 1) | `exclusive a -> (Rtypes.int32_of_int4 (Rtypes.read_int4 a 0), Rtypes.int32_of_int4 (Rtypes.read_int4 a 4), 2)) in let res = if matchedcookie then 0 else Util.create path uid gid guardtype data1 data2 in if res <> 0 then raise Perm else remove_mask path; let dirFake = L.fhToFake map (s2fh arg.where.dir.data) in let newFake = Util.concatPath dirFake arg.where.name in let newFh = L.fakeToNewFh map newFake in match L.lookupRead map newFh with | Some (_, info) -> `nfs3_ok { obj = `True { data = fh2s newFh }; obj_attributes = post_op_attr info newFake; dir_wcc = wcc () } | None -> raise Not_sync let mkdir map session arg path old wcc = (* permissions check happens in the wrapper *) if not (Util.validateName arg.where'.name) then raise Acces else begin match old with | Some (oldpath, oldinfo) -> if path = oldpath then raise Exist | None -> () end; Unix.mkdir path (file_perm_of_sattr3 arg.attributes); begin match (user session) with | (uid, gid :: _, hostname) -> chown path uid gid | _ -> raise Perm end; remove_mask path; let dirFake = L.fhToFake map (s2fh arg.where'.dir.data) in let newFake = Util.concatPath dirFake arg.where'.name in let newFh = L.fakeToNewFh map newFake in match L.lookupRead map newFh with | Some (_, info) -> `nfs3_ok { obj = `True { data = fh2s newFh }; obj_attributes = post_op_attr info newFake; dir_wcc = wcc () } | None -> raise Not_sync let symlink map session arg path old wcc = (* permissions check happens in the wrapper *) if not (Util.validateName arg.where''.name) then raise Acces else begin match old with | Some (oldpath, oldinfo) -> if path = oldpath then raise Exist | None -> () end; Unix.symlink arg.symlink.symlink_data path; begin match (user session) with | (uid, gid :: _, hostname) -> lchown path uid gid | _ -> raise Perm end; remove_mask path; let dirFake = L.fhToFake map (s2fh arg.where''.dir.data) in let newFake = Util.concatPath dirFake arg.where''.name in let newFh = L.fakeToNewFh map newFake in match L.lookupRead map newFh with | Some (_, info) -> `nfs3_ok { obj = `True { data = fh2s newFh }; obj_attributes = post_op_attr info newFake; dir_wcc = wcc () } | None -> raise Not_sync let mknod map session arg path old wcc = if not (Util.validateName arg.where'''.name) then raise Acces else begin match old with | Some (oldpath, oldinfo) -> if path = oldpath then raise Exist | None -> () end; begin let decode_sattr3 user attr = let getint default set_uint32 = match set_uint32 with | `True u32 -> Rtypes.int_of_uint4 u32 | `False -> default in let (uid, gids, _) = user in let uid = getint uid attr.uid' in let gid = getint (List.hd gids) attr.gid' in let mode = getint default_perm attr.mode' in (uid, gid, mode) in let decode_dev { major = major; minor = minor } = Int64.logor (Int64.shift_left (Rtypes.int64_of_uint4 major) 8) (Rtypes.int64_of_uint4 minor) in let user = user session in match arg.what with | `nf3chr device -> begin if not (checkperm_mknod user) then raise Perm else let (uid, gid, mode) = decode_sattr3 user device.dev_attributes in let dev = decode_dev device.spec in try Util.mknod path (mode lor 0o020000) dev uid gid with Failure _ -> raise Acces end | `nf3blk device -> begin if not (checkperm_mknod user) then raise Perm else let (uid, gid, mode) = decode_sattr3 user device.dev_attributes in let dev = decode_dev device.spec in try Util.mknod path (mode lor 0o060000) dev uid gid with Failure _ -> raise Acces end | `nf3fifo attr -> begin let (uid, gid, mode) = decode_sattr3 user attr in try Util.mknod path (mode lor 0o10000) Int64.zero uid gid with Failure _ -> raise Acces end | `nf3sock attr -> begin let (uid, gid, mode) = decode_sattr3 user attr in try Util.mknod path (mode lor 0o140000) Int64.zero uid gid with Failure _ -> raise Acces end | _ -> raise Bad_type end; remove_mask path; let dirFake = L.fhToFake map (s2fh arg.where'''.dir.data) in let newFake = Util.concatPath dirFake arg.where'''.name in let newFh = L.fakeToNewFh map newFake in match L.lookupRead map newFh with | Some (_, info) -> `nfs3_ok { obj = `True { data = fh2s newFh }; obj_attributes = post_op_attr info newFake; dir_wcc = wcc () } | None -> raise Not_sync (* Remove operations **********************************************************) let remove map session arg readname readinfo writename wcc = if readinfo.st_kind = S_DIR then raise Isdir else if readname = writename then unlink writename; hide_fh_name map session (s2fh arg.dir.data) arg.name; `nfs3_ok (wcc ()) let rmdir map session arg readname readinfo writename wcc = if readinfo.st_kind <> S_DIR then raise Notdir else if readname = writename then rmdir writename; hide_fh_name map session (s2fh arg.dir.data) arg.name; `nfs3_ok (wcc ()) (* Special case operations ****************************************************) let rename map session arg = (* first examine the directories and prepare return values *) let fromfh = s2fh arg.from.dir.data in let tofh = s2fh arg.to'.dir.data in let fromfake = L.fhToFake map fromfh in let tofake = L.fhToFake map tofh in let pre_from = L.lookupRead map fromfh in let pre_to = L.lookupRead map tofh in if pre_from = None then `nfs3err_stale { fromdir_wcc = { before = `False; after = `False }; todir_wcc = { before = `False; after = `False } } else if pre_to = None then `nfs3err_stale { fromdir_wcc = { before = `False; after = `False }; todir_wcc = { before = `False; after = `False } } else (* package a function to gather the return result *) let wcc () = let wcc_from () = { before = (match pre_from with | Some (_, info) -> pre_op_attr info | None -> `False); after = (match L.lookupRead map fromfh with | Some (_, info) -> post_op_attr info fromfake | None -> `False) } in let wcc_to () = { before = (match pre_to with | Some (_, info) -> pre_op_attr info | None -> `False); after = (match L.lookupRead map tofh with | Some (_, info) -> post_op_attr info tofake | None -> `False) } in { fromdir_wcc = wcc_from (); todir_wcc = wcc_to () } in (* do the actual rename operation *) match L.lookupWrite map (FhName (fromfh, arg.from.name)) with | (_, None) -> `nfs3err_acces (wcc ()) | (None, _) -> `nfs3err_noent (wcc ()) | (Some (readname, readinfo), Some writename) -> begin match L.lookupCreate map tofh arg.to'.name with | (None, _) -> `nfs3err_acces (wcc ()) | (Some newpath, _) -> begin L.mountFileCheck map newpath; try if readname = writename then (* we have write permission so do a normal rename *) begin L.mountFileCheck map writename; create_shadow_dirs map (user session) newpath (FhOnly tofh); Unix.rename writename newpath; hide_fh_name map session fromfh arg.from.name end else (* the source is read-only so make a copy *) begin ignore (copy_on_write map (user session) (FhOnly tofh) (Some (readname, readinfo), Some newpath)); hide_fh_name map session fromfh arg.from.name end; `nfs3_ok (wcc ()) with e -> handle_exp e (wcc ()) end end let null map session arg = () let getattr map session arg = let objfh = s2fh arg.data in let fake = L.fhToFake map objfh in match L.lookupRead map objfh with | Some (name, info) -> `nfs3_ok (nfs_stat info fake) | None -> `nfs3err_stale let link map session arg = let objfh = s2fh arg.file''.data in let dirfh = s2fh arg.link.dir.data in let dirFake = L.fhToFake map dirfh in let linkname = arg.link.name in let newFake = Util.concatPath dirFake linkname in let newFh = L.fakeToNewFh map newFake in match (L.lookupRead map objfh, L.lookupRead map dirfh) with | (None, Some (dirname, dirinfo)) -> `nfs3err_stale { file_attributes' = `False; linkdir_wcc = { before = pre_op_attr dirinfo; after = post_op_attr dirinfo dirFake } } | (None, _) | (_, None) -> `nfs3err_stale { file_attributes' = `False; linkdir_wcc = { before = `False; after = `False } } | (Some (name, info), Some (dirname, dirinfo)) -> let wcc () = { file_attributes' = (match L.lookupRead map newFh with | Some (_, info) -> post_op_attr info newFake | None -> `False); linkdir_wcc = { before = pre_op_attr dirinfo; after = (match L.lookupRead map dirfh with | Some (_, info) -> post_op_attr info dirFake | None -> `False) } } in if dirinfo.st_kind <> S_DIR then `nfs3err_notdir (wcc ()) else begin match L.lookupCreate map dirfh linkname with | (None, _) -> `nfs3err_acces (wcc ()) | (Some path, old) -> try create_shadow_dirs map (user session) path (FhName (dirfh, linkname)); let createdirinfo = lstat (Util.dirname path) in if not (checkperm session createdirinfo access3_modify && Util.validateName linkname) then raise Acces; L.mountFileCheck map path; (match old with | Some (oldpath, _) when oldpath = path -> raise Exist | _ -> ()); Unix.link name path; `nfs3_ok (wcc ()) with e -> handle_exp e (wcc ()) end (* Wrappers *******************************************************************) (* Wrap the read operations ***************************************************) let wrap_readop name f map session arg objfh = try let objfh = s2fh objfh in let fake = L.fhToFake map objfh in match L.lookupRead map objfh with | Some (name, info) -> begin let postopattr = `True (nfs_stat info fake) in try f map session arg name info fake with e -> handle_exp e postopattr end | None -> `nfs3err_stale `False with e -> (* prerr_endline ("exception "^(Printexc.to_string e)^" in "^name^"\n"); *) handle_exp e `False let lookup map session arg = wrap_readop "lookup" lookup map session arg arg.dir.data let access map session arg = wrap_readop "access" access map session arg arg.object'''.data let readlink map session arg = wrap_readop "readlink" readlink map session arg arg.data let read map session arg = wrap_readop "read" read map session arg arg.file.data let readdir map session arg = wrap_readop "readdir" readdir map session arg arg.dir'.data let readdirplus map session arg = wrap_readop "readdirplus" readdirplus map session arg arg.dir''.data let fsstat map session arg = wrap_readop "fsstat" fsstat map session arg arg.data let fsinfo map session arg = wrap_readop "fsinfo" fsinfo map session arg arg.data let pathconf map session arg = wrap_readop "pathconf" pathconf map session arg arg.data (* Wrap the write operations **************************************************) let wrap_writeop name f map session arg objfh = try let objfh = s2fh objfh in let fake = L.fhToFake map objfh in match L.lookupWrite map (FhOnly objfh) with | (Some (readname, readinfo), Some writename) as paths -> begin let (path, info) = if readname = writename then (readname, readinfo) else copy_on_write map (user session) (FhOnly objfh) paths in let wcc () = { before = pre_op_attr readinfo; after = (match L.lookupRead map objfh with | Some (_, info) -> post_op_attr info fake | None -> `False) } in try L.mountFileCheck map path; let res = f map session arg path info readinfo fake in res with e -> handle_exp e (wcc ()) end | (Some (readname, readinfo), None) -> `nfs3err_acces { before = pre_op_attr readinfo; after = post_op_attr readinfo fake } | (None, _) -> `nfs3err_stale { before = `False; after = `False } with e -> (* prerr_endline ("exception "^(Printexc.to_string e)^" in "^name^"\n");*) handle_exp e { before = `False; after = `False } let setattr map session arg = wrap_writeop "setattr" setattr map session arg arg.object'.data let write map session arg = wrap_writeop "write" write map session arg arg.file'.data let commit map session arg = wrap_writeop "commit" commit map session arg arg.file'''.data (* Wrap the create operations *************************************************) let wrap_createop opname f map session arg dirfh name = try let dirfh = s2fh dirfh in let dirFake = L.fhToFake map dirfh in match L.lookupRead map dirfh with | None -> `nfs3err_stale { before = `False; after = `False } | Some (dirname, dirinfo) -> let wcc () = { before = pre_op_attr dirinfo; after = (match L.lookupRead map dirfh with | Some (_, info) -> post_op_attr info dirFake | None -> `False) } in if dirinfo.st_kind <> S_DIR then `nfs3err_notdir (wcc ()) else begin match L.lookupCreate map dirfh name with | (Some path, old) -> begin try create_shadow_dirs map (user session) path (FhName (dirfh, name)); let createdirinfo = lstat (Util.dirname path) in if not (checkperm session createdirinfo access3_modify) then raise Acces; L.mountFileCheck map path; f map session arg path old wcc with e -> handle_exp e (wcc ()) end | _ -> `nfs3err_acces (wcc ()) end with e -> prerr_endline ( " exception " ^(Printexc.to_string e)^ " in " ^opname^"\n " ) ; handle_exp e { before = `False; after = `False } let create map session arg = wrap_createop "create" create map session arg arg.where.dir.data arg.where.name let mkdir map session arg = wrap_createop "mkdir" mkdir map session arg arg.where'.dir.data arg.where'.name let symlink map session arg = wrap_createop "symlink" symlink map session arg arg.where''.dir.data arg.where''.name let mknod map session arg = wrap_createop "mknod" mknod map session arg arg.where'''.dir.data arg.where'''.name (* Wrap the remove operations *************************************************) let wrap_removeop opname f map session arg dirfh name = try let dirfh = s2fh dirfh in let dirFake = L.fhToFake map dirfh in match L.lookupRead map dirfh with | Some (dirname, dirinfo) -> let wcc () = { before = pre_op_attr dirinfo; after = (match L.lookupRead map dirfh with | Some (_, info) -> post_op_attr info dirFake | None -> `False) } in if dirinfo.st_kind <> S_DIR then `nfs3err_notdir (wcc ()) else begin match L.lookupWrite map (FhName (dirfh, name)) with | (Some (readname, readinfo), Some writename) -> begin try L.mountFileCheck map writename; let res = f map session arg readname readinfo writename wcc in res with e -> handle_exp e (wcc ()) end | (Some _, None) -> `nfs3err_acces (wcc ()) | (None, _) -> `nfs3err_noent (wcc ()) end | None -> `nfs3err_stale { before = `False; after = `False } with e -> prerr_endline ( " exception " ^(Printexc.to_string e)^ " in " ^opname^"\n " ) ; handle_exp e { before = `False; after = `False } let remove map session arg = wrap_removeop "remove" remove map session arg arg.dir.data arg.name let rmdir map session arg = wrap_removeop "rmdir" rmdir map session arg arg.dir.data arg.name (* Wrap the special case operations *******************************************) (* no return data *) let err0 () = `nfs3err_serverfault (* post_op_attr = { `True of fattr3 = { many fields... } } *) let err1 () = `nfs3err_serverfault `False wcc_data = { before = pre_op_attr ; after = post_op_attr } let err2 () = `nfs3err_serverfault { before = `False; after = `False } (* link3wcc = { file_attributes' = post_op_attr; linkdir_wcc = wcc_data } *) let err3 () = `nfs3err_serverfault { file_attributes' = `False; linkdir_wcc = { before = `False; after = `False } } rename3wcc = { fromdir_wcc = wcc_data ; todir_wcc = wcc_data } let err4 () = `nfs3err_serverfault { fromdir_wcc = { before = `False; after = `False }; todir_wcc = { before = `False; after = `False } } let wrap name f map session arg res = try f map session arg with | Unix_error (e,s1,s2) -> prerr_endline ("exception Unix_error\n ("^ (error_message e)^", "^s1^", "^s2^")\n in "^name^"\n"); res | e -> prerr_endline ("exception "^(Printexc.to_string e)^" in "^ name^"\n"); res let getattr map session arg = try getattr map session arg with _ -> `nfs3err_stale let rename map session arg = wrap "rename" rename map session arg (err4 ()) let link map session arg = wrap "link" link map session arg (err3 ())
null
https://raw.githubusercontent.com/russross/cownfs/cc67fae0294203a78b022d7300be8aa6c35c58af/nfs_api.ml
ocaml
Misc utility functions **************************************************** let res = Rtypes.uint8_of_int (abs (Util.hashString 0 name)) in package a Unix stat record for a pre_op_attr result package a Unix stat record for a post_op_attr result let print_post_op_attr info = match info with | `True i -> ignore (print_nfs_stat i); info | `False -> info info info info kind TODO: more squashing--shadow dir creation, dir permission changes, etc. this gets called by create ops, so the user already has permission to * the directory Exceptions **************************************************************** | EDQUOT -> `nfs3err_dquot arg | EREMOTE -> `nfs3err_remote arg | ENOT_SYNC -> `nfs3err_not_sync arg | EBAD_COOKIE -> `nfs3err_bad_cookie arg | ETOOSMALL -> `nfs3err_toosmall arg | EBADTYPE -> `nfs3err_badtype arg | EJUKEBOX -> `nfs3err_jukebox arg | EABORTED -> `nfs3err_aborted arg Read operations *********************************************************** apply the given function to every file in the given directory given a list of stacked directories, gather a full list of visible files get a list of visible files, from cache if available, else scan dirs gather readdir info for the appropriate range of files using the cookie ignore the cookie if n=0 because some clients don't supply 0 compute the fh of the entry to force it into the cache fh' Write operations ********************************************************** mode changes size changes time changes uid/gid changes Create operations ********************************************************* permissions check happens in the wrapper check exclusive create conditions permissions check happens in the wrapper permissions check happens in the wrapper Remove operations ********************************************************* Special case operations *************************************************** first examine the directories and prepare return values package a function to gather the return result do the actual rename operation we have write permission so do a normal rename the source is read-only so make a copy Wrappers ****************************************************************** Wrap the read operations ************************************************** prerr_endline ("exception "^(Printexc.to_string e)^" in "^name^"\n"); Wrap the write operations ************************************************* prerr_endline ("exception "^(Printexc.to_string e)^" in "^name^"\n"); Wrap the create operations ************************************************ Wrap the remove operations ************************************************ Wrap the special case operations ****************************************** no return data post_op_attr = { `True of fattr3 = { many fields... } } link3wcc = { file_attributes' = post_op_attr; linkdir_wcc = wcc_data }
Copyright 2004 , 2005 * See the file COPYING for information about licensing and distribution . * See the file COPYING for information about licensing and distribution. *) TODO : - copy on write files should be deleted on operation failure - rename of directories needs to create / modify .mount file - remove of dirs needs to delete .~ files if the dir is otherwise empty - mounted paths should be constrained - shadow dirs should be deleted if the op fails - dirTree ops should respect .~ mask files - copy on write files should be deleted on operation failure - rename of directories needs to create/modify .mount file - remove of dirs needs to delete .~ files if the dir is otherwise empty - mounted paths should be constrained - shadow dirs should be deleted if the op fails - dirTree ops should respect .~ mask files *) open Common;; open Unix;; open Unix.LargeFile;; open Nfs3_prot_caux;; module SSet = Set.Make (String);; module L = Lookup;; let block_size = ref 8192 let buffer_size = 8192 let startup_cookie = Rtypes.fp8_as_string (Rtypes.fp8_of_float (Unix.time ())) let file_system_id = 51423 let lchown = Util.lchown let s2fh = Fh.ofString let fh2s = Fh.toString let default_perm = 0o644 let checkaccess fattr mask = Rtypes.uint4_of_int 0 let fileids = Hashtbl.create 5000 let fileids = Hashtbl.create 5000 *) let fileid_of_name = Util.hash64 Rtypes.uint8_of_int64 ( Int64.abs ( Util.hashString64 Int64.zero name ) ) Rtypes.uint8_of_int64 (Int64.abs (Util.hashString64 Int64.zero name)) *) let fileid_of_name name = let res = fileid_of_name name in ( * let res = Rtypes.uint8_of_int ( abs ( Util.hashString 0 name ) ) in let fileid_of_name name = let res = fileid_of_name name in try if Hashtbl.find fileids res <> name then begin prerr_string ("fileid_of_name: collision for id "^ (Int64.to_string (Rtypes.int64_of_uint8 res))^ " old="^(Hashtbl.find fileids res)^ " new="^name); prerr_newline (); end; if Util.startsWith name "/local" then begin prerr_string ("fileid_of_name: bad name ["^name^"]"); prerr_newline (); failwith "fileid_of_name" end; res with Not_found -> Hashtbl.add fileids res name; res *) let nfs_time sec = let (frac, whole) = modf sec in let nano = frac *. 1000000000.0 in { seconds = Rtypes.logical_uint4_of_int32 (Int32.of_float (whole +. 0.5)); nseconds = Rtypes.logical_uint4_of_int32 (Int32.of_float (nano +. 0.5)) } let float_of_nfs_time nfstime = match nfstime with { seconds = s; nseconds = ns } -> Int32.to_float (Rtypes.int32_of_uint4 s) +. (Int32.to_float (Rtypes.int32_of_uint4 ns) /. 1000000000.0) let nfs_stat info fake = { type' = begin match info.st_kind with | S_REG -> nf3reg | S_DIR -> nf3dir | S_CHR -> nf3chr | S_BLK -> nf3blk | S_LNK -> nf3lnk | S_FIFO -> nf3fifo | S_SOCK -> nf3sock end; mode = Rtypes.uint4_of_int info.st_perm; nlink = Rtypes.uint4_of_int info.st_nlink; uid = Rtypes.uint4_of_int info.st_uid; gid = Rtypes.uint4_of_int info.st_gid; size = Rtypes.uint8_of_int64 info.st_size; used = Rtypes.uint8_of_int64 info.st_size; rdev = { major = Rtypes.uint4_of_int ((info.st_rdev land 0xff00) lsr 8); minor = Rtypes.uint4_of_int (info.st_rdev land 0x00ff) }; fsid = Rtypes.uint8_of_int file_system_id; fileid = fileid_of_name fake; atime = nfs_time info.st_atime; mtime = nfs_time info.st_mtime; ctime = nfs_time info.st_ctime } let s64 n = Int64.to_string (Rtypes.int64_of_uint8 n) let s32 n = Int32.to_string (Rtypes.int32_of_uint4 n) let ss32 n = Int32.to_string (Rtypes.int32_of_int4 n) let print_nfs_stat info = prerr_string ( " nfs_stat:"^ " mode="^(s32 info.mode)^ " fileid="^(s64 info.fileid)^ " mtime="^(s32 info.mtime.seconds)^ " ctime="^(s32 info.ctime.seconds)^ " rdev=(major="^(s32 info.rdev.major)^ " minor="^(s32 info.rdev.minor)^ " fsid="^(s64 " type'="^(ss32 info.type ' ) ) ; prerr_newline ( ) ; let print_nfs_stat info = prerr_string ("nfs_stat:"^ " mode="^(s32 info.mode)^ " fileid="^(s64 info.fileid)^ " mtime="^(s32 info.mtime.seconds)^ " ctime="^(s32 info.ctime.seconds)^ " rdev=(major="^(s32 info.rdev.major)^ " minor="^(s32 info.rdev.minor)^ " fsid="^(s64 info.fsid)^ " type'="^(ss32 info.type')); prerr_newline (); *) let pre_op_attr info = `True { size' = Rtypes.uint8_of_int64 info.st_size; mtime' = nfs_time (info.st_mtime); ctime' = nfs_time (info.st_ctime) } let print_pre_op_attr info = match info with | ` True { size ' = s ; ' = { seconds = ; ; ctime ' = { seconds = csec ; } } - > begin prerr_string ( " pre_op_attr:"^ " size="^(s64 s)^ " mtime="^(s32 msec)^ " ctime="^(s32 csec ) ) ; prerr_newline ( ) end ; info | ` False - > info let print_pre_op_attr info = match info with | `True { size' = s; mtime' = { seconds = msec; nseconds = mnsec }; ctime' = { seconds = csec; nseconds = cnsec } } -> begin prerr_string ("pre_op_attr:"^ " size="^(s64 s)^ " mtime="^(s32 msec)^ " ctime="^(s32 csec)); prerr_newline () end; info | `False -> info *) let post_op_attr info fake = `True (nfs_stat info fake) let file_perm_of_sattr3 attr = match attr.mode' with | `True mode -> Rtypes.int_of_uint4 mode | _ -> failwith "file_perm_of_sattr3 called with `False" let string8_of_int i = let res = String.create 8 in res.[0] <- char_of_int ((i land 0x7f000000) lsr 24); res.[1] <- char_of_int ((i land 0x00ff0000) lsr 16); res.[2] <- char_of_int ((i land 0x0000ff00) lsr 8); res.[3] <- char_of_int (i land 0x000000ff); res.[4] <- '\000'; res.[5] <- '\000'; res.[6] <- '\000'; res.[7] <- '\000'; res let int_of_string8 s = ((int_of_char s.[0]) lsl 24) lor ((int_of_char s.[1]) lsl 16) lor ((int_of_char s.[2]) lsl 8) lor (int_of_char s.[3]) let ( uid , gid , , hostname ) = Rpc_auth_sys.parse_user_name ( session ) in ( uid , gid : : ( Array.to_list ) , hostname ) let (uid, gid, gid_arr, hostname) = Rpc_auth_sys.parse_user_name (Rpc_server.get_user session) in (uid, gid :: (Array.to_list gid_arr), hostname) *) let read = Rtypes.int_of_uint4 access3_read in let write = (Rtypes.int_of_uint4 access3_modify) lor (Rtypes.int_of_uint4 access3_extend) lor (Rtypes.int_of_uint4 access3_delete) in let exec = (Rtypes.int_of_uint4 access3_lookup) lor (Rtypes.int_of_uint4 access3_execute) in let p info = let owner = (if info.st_perm land 0o400 <> 0 then read else 0) lor (if info.st_perm land 0o200 <> 0 then write else 0) lor (if info.st_perm land 0o100 <> 0 then exec else 0) in let group = (if info.st_perm land 0o040 <> 0 then read else 0) lor (if info.st_perm land 0o020 <> 0 then write else 0) lor (if info.st_perm land 0o010 <> 0 then exec else 0) in let world = (if info.st_perm land 0o004 <> 0 then read else 0) lor (if info.st_perm land 0o002 <> 0 then write else 0) lor (if info.st_perm land 0o001 <> 0 then exec else 0) in (owner, group, world) in p let getperm_user user info = let (uid, gidlist, hostname) = user in let (owner, group, world) = perm info in if uid = info.st_uid then owner else if List.mem info.st_gid gidlist then group else world let checkperm_user (uid, gids, hostname) info kind = let kind = Rtypes.int_of_uint4 kind in uid = 0 || (kind land getperm_user (uid, gids, hostname) info <> 0) let checkperm_chown (uid, _, _) info = uid = 0 let checkperm_mknod (uid, _, _) = uid = 0 exception Not_writeable exception Wrong_filetype let create_shadow_dirs state user path file = let rec get_perm parent = try let info = lstat parent in if info.st_kind <> S_DIR then raise Wrong_filetype else info.st_perm with _ -> let perm = get_perm (Util.dirname parent) in mkdir parent perm; let (uid, gids, hostname) = user in chown parent uid (List.hd gids); perm in ignore (get_perm (Util.dirname path)) let copy_file user name_in name_out info = if info.st_kind <> S_REG then raise Wrong_filetype else let fp_in = openfile name_in [O_RDONLY] 0 in try let fp_out = openfile name_out [O_WRONLY; O_CREAT; O_EXCL] info.st_perm in (try let (uid, gids, hostname) = user in fchown fp_out uid (List.hd gids); let buff = String.create buffer_size in let rec copy () = let size = read fp_in buff 0 buffer_size in if size > 0 then begin if size <> (write fp_out buff 0 size) then failwith "copy_file" else copy () end else () in copy (); close fp_out with e -> close fp_out; raise e); close fp_in with e-> close fp_in; raise e let copy_link user name_in name_out info = if info.st_kind <> S_LNK then raise Wrong_filetype else let lnk = readlink name_in in symlink name_out lnk; let (uid, gids, hostname) = user in lchown name_out uid (List.hd gids) let copy_dir user name_in name_out info = if info.st_kind <> S_DIR then raise Wrong_filetype else mkdir name_out info.st_perm; let (uid, gids, hostname) = user in chown name_out uid (List.hd gids) let copy_on_write state user file paths = match paths with | (Some (readname, readinfo), Some writename) -> if readname = writename then (writename, readinfo) else begin let fh = match file with FhOnly fh -> fh | FhName (fh, _) -> fh in L.squash state (FhOnly fh); match readinfo.st_kind with | S_REG -> begin create_shadow_dirs state user writename file; copy_file user readname writename readinfo; (writename, lstat writename) end | S_LNK -> begin create_shadow_dirs state user writename file; copy_link user readname writename readinfo; (writename, lstat writename) end | S_DIR -> begin create_shadow_dirs state user writename file; copy_dir user readname writename readinfo; (writename, lstat writename) end | _ -> raise Not_writeable end | (Some _, None) -> raise Not_writeable | (None, _) -> raise Not_found let remove_mask path = let hidename = Util.concatPath (Util.dirname path) (".~"^(Util.filename path)) in try let info = lstat hidename in if info.st_kind = S_REG && info.st_size = 0L then Unix.unlink hidename with Unix_error _ -> () exception Noent exception Notdir exception Inval exception Bad_cookie exception Bad_type exception Not_sync exception Notsupp exception Acces exception Exist exception Isdir exception Hide_failed exception Perm exception Unimplemented let unixerr err arg = match err with | EPERM -> `nfs3err_perm arg | ENOENT -> `nfs3err_noent arg | EIO -> `nfs3err_io arg | ENXIO -> `nfs3err_nxio arg | EACCES -> `nfs3err_acces arg | EEXIST -> `nfs3err_exist arg | EXDEV -> `nfs3err_xdev arg | ENODEV -> `nfs3err_nodev arg | ENOTDIR -> `nfs3err_notdir arg | EISDIR -> `nfs3err_isdir arg | EINVAL -> `nfs3err_inval arg | EFBIG -> `nfs3err_fbig arg | ENOSPC -> `nfs3err_nospc arg | EROFS -> `nfs3err_rofs arg | EMLINK -> `nfs3err_mlink arg | ENAMETOOLONG -> `nfs3err_nametoolong arg | ENOTEMPTY -> `nfs3err_notempty arg | - > ` nfs3err_stale arg | EBADF -> `nfs3err_badhandle arg | ENOTSUPP - > ` nfs3err_notsupp arg | EFPRINTNOTFOUND - > ` nfs3err_fprintnotfound arg | _ -> `nfs3err_serverfault arg let handle_exp exp res = if exp <> Noent then begin prerr_endline ("*** exception "^(Printexc.to_string exp)) end; match exp with | Noent -> `nfs3err_noent res | Notdir -> `nfs3err_notdir res | Inval -> `nfs3err_inval res | Bad_cookie -> `nfs3err_bad_cookie res | Bad_type -> `nfs3err_badtype res | Not_sync -> `nfs3err_not_sync res | Notsupp -> `nfs3err_notsupp res | Acces -> `nfs3err_acces res | Exist -> `nfs3err_exist res | Isdir -> `nfs3err_isdir res | Not_writeable -> `nfs3err_acces res | Wrong_filetype -> `nfs3err_acces res | Unix_error (err, s1, s2) -> unixerr err res | Unimplemented -> `nfs3err_notsupp res | Hide_failed -> `nfs3err_acces res | Perm -> `nfs3err_perm res | Not_found -> `nfs3err_stale res | _ -> `nfs3err_serverfault res let hide_fh_name map session fh name = match L.lookupHide map fh name with | (true, Some path) -> begin let (uid, gids, hostname) = user session in create_shadow_dirs map (uid, gids, hostname) path (FhName (fh, name)); let res = Util.create path uid (List.hd gids) 0 (Int32.of_int default_perm) 0l in if res <> 0 then raise Hide_failed end | (true, None) -> raise Hide_failed | (false, _) -> () let lookup map session arg name info fake = if info.st_kind <> S_DIR then raise Notdir else if not (checkperm session info access3_lookup) then raise Acces else if not (Util.validateName arg.name) then raise Noent else begin let dirFake = L.fhToFake map (s2fh arg.dir.data) in let newFake = Util.concatPath dirFake arg.name in let newFh = L.fakeToNewFh map newFake in match L.lookupRead map newFh with | Some (fname, finfo) -> let fattr = nfs_stat finfo newFake in `nfs3_ok { object'' = { data = fh2s newFh }; obj_attributes' = `True fattr; dir_attributes = `True (nfs_stat info fake) } | None -> raise Noent end let access map session arg name info fake = let attr = nfs_stat info fake in let (uid, gids, hostname) = user session in let perms = if uid = 0 then Rtypes.int_of_uint4 arg.access else (Rtypes.int_of_uint4 arg.access) land (getperm session info) in `nfs3_ok { obj_attributes'' = (`True attr); access' = Rtypes.uint4_of_int perms } let readlink map session arg name info fake = if not (checkperm session info access3_read) then raise Acces else if info.st_kind <> S_LNK then raise Inval else `nfs3_ok { symlink_attributes = (`True (nfs_stat info fake)); data' = Unix.readlink name } let read map session arg name info fake = if not (checkperm session info access3_read) then raise Acces else let start = Rtypes.int64_of_uint8 arg.offset in let len = Rtypes.int_of_uint4 arg.count in let buff = String.create len in if start >= info.st_size || len = 0 then `nfs3_ok { file_attributes = (`True (nfs_stat info fake)); count' = Rtypes.uint4_of_int 0; eof = start >= info.st_size; data'' = "" } else let readres = ref 0 in let fp = openfile name [O_RDONLY] 0 in (try readres := pos Unix.read fp buff 0 len); close fp with e -> close fp; raise e); let count = !readres in let result = if count = len then buff else String.sub buff 0 count in let eof = count = 0 || (Int64.add start (Int64.of_int count)) = info.st_size in `nfs3_ok { file_attributes = `True (nfs_stat info fake); count' = Rtypes.uint4_of_int count; eof = eof; data'' = result } let readdir_iter f dir = try let handle = in let rec loop ( ) = try f ( handle ) ; loop ( ) with End_of_file - > closedir handle | e - > closedir handle ; raise e in loop ( ) with Unix_error _ - > ( ) let readdir_iter f dir = try let handle = opendir dir in let rec loop () = try f (readdir handle); loop () with End_of_file -> closedir handle | e -> closedir handle; raise e in loop () with Unix_error _ -> () *) let readdir_iter f dir = try f "."; f ".."; Array.iter f (Sys.readdir dir) with Unix_error _ -> () | Sys_error _ -> () let readdir_gather dirlist user = let files = ref [] in let masked = ref SSet.empty in let scanOneDir dir = if try not (checkperm_user user (lstat dir) access3_read) with _ -> true then () else let newMasked = ref SSet.empty in let nextFile name = if SSet.mem name !masked then () else begin files := (dir, name) :: !files; newMasked := SSet.add name !newMasked; let len = String.length name in if len > 2 && String.sub name 0 2 = ".~" then newMasked := SSet.add (String.sub name 2 (len - 2)) !newMasked end in readdir_iter nextFile dir; masked := SSet.union !masked !newMasked in List.iter scanOneDir dirlist; !files let readdir_getlist map fh info counter cookie user = try (counter, cookie, L.dirFhInfoToFileList map fh info counter cookie) with Not_found -> (0, 0, readdir_gather (L.lookupReaddir map fh) user) let lst = readdir_gather ( L.lookupReaddir map fh ) user in L.addDirFhInfoFileList map fh info lst ; lst let lst = readdir_gather (L.lookupReaddir map fh) user in L.addDirFhInfoFileList map fh info lst; lst*) type readdir_res = End | Elt of (string * string * Rtypes.uint8 * readdir_res) exception Readdir_too_high this forms the basis for and readdirplus let readdir_common map user fh info cookie cookieverf max maxPlus isPlus = let first = Rtypes.int_of_uint8 cookie in let cookie = int_of_string8 cookieverf in let (counter, cookiestart, files) = readdir_getlist map fh info first cookie user in let hash = ref cookiestart in let eof = ref false in let rec f lst n size sizePlus = match lst with | [] -> if n < first then raise Readdir_too_high else (eof := true; L.squashDirFh map fh; End) | (prefix, file) :: xs -> let size' = size + (Util.readdir_entry_size file) in let sizePlus' = sizePlus + (Util.readdirplus_entry_size file) in if n < first then (hash := Util.hashString !hash file; f xs (succ n) size sizePlus) else if n = first && n <> 0 && !hash <> cookie then raise Bad_cookie else if size' > max || (isPlus && sizePlus' > maxPlus) then (L.addDirFhInfoFileList map fh info n !hash lst; End) else begin hash := Util.hashString !hash file; Elt (prefix, file, Rtypes.uint8_of_int (succ n), f xs (succ n) size' sizePlus') end in let lst = f files counter (Util.readdir_base ()) (Util.readdirplus_base ()) in (!eof, lst, !hash) let readdir map session arg name info fake = let fh = s2fh arg.dir'.data in let maxResultSize = Rtypes.int_of_uint4 arg.count'''' in if not (checkperm session info access3_read) then raise Acces else if info.st_kind <> S_DIR then raise Notdir else let rec package elt = begin match elt with | Elt (prefix, fname, cookie, next) -> let newFake = Util.concatPath fake fname in Some { fileid' = fileid_of_name newFake; name' = fname; cookie' = cookie; nextentry = package next } | End -> None end in let (eof, lst, hash) = try readdir_common map (user session) fh info arg.cookie arg.cookieverf maxResultSize 0 false with Readdir_too_high -> readdir_common map (user session) fh info (Rtypes.uint8_of_int 0) (string8_of_int 0) maxResultSize 0 false in `nfs3_ok { dir_attributes' = `True (nfs_stat info fake); cookieverf' = string8_of_int hash; reply = { entries = package lst; eof' = eof } } let readdirplus map session arg name info fake = let fh = s2fh arg.dir''.data in let maxResultSize = Rtypes.int_of_uint4 arg.dircount in let maxResultPlusSize = Rtypes.int_of_uint4 arg.maxcount in if info.st_kind <> S_DIR then raise Notdir else let rec package elt = begin match elt with | Elt (prefix, fname, cookie, next) -> let newFake = Util.concatPath fake fname in let fh' = L.fakeToNewFh map newFake in let newReal = Util.concatPath prefix fname in Some { fileid'' = fileid_of_name newFake; name'' = fname; cookie''' = cookie; name_attributes = (try `True (nfs_stat (lstat newReal) newFake) with _ -> `False); name_handle = `True { data = fh2s fh' }; nextentry' = package next } | End -> None end in let (eof, lst, hash) = try readdir_common map (user session) fh info arg.cookie'' arg.cookieverf'' maxResultSize maxResultPlusSize true with Readdir_too_high -> readdir_common map (user session) fh info (Rtypes.uint8_of_int 0) (string8_of_int 0) maxResultSize maxResultPlusSize true in `nfs3_ok { dir_attributes'' = `True (nfs_stat info fake); cookieverf''' = string8_of_int hash; reply' = { entries' = package lst; eof'' = eof } } let fsstat map session arg name info fake = `nfs3_ok { obj_attributes''' = `True (nfs_stat info fake); tbytes = Rtypes.uint8_of_int 1000000000; fbytes = Rtypes.uint8_of_int 500000000; abytes = Rtypes.uint8_of_int 500000000; tfiles = Rtypes.uint8_of_int 100000; ffiles = Rtypes.uint8_of_int 50000; afiles = Rtypes.uint8_of_int 50000; invarsec = Rtypes.uint4_of_int 30 } let fsinfo map session arg name info fake = `nfs3_ok { obj_attributes'''' = `True (nfs_stat info fake); rtmax = Rtypes.uint4_of_int 8192; rtpref = Rtypes.uint4_of_int 8192; rtmult = Rtypes.uint4_of_int 8192; wtmax = Rtypes.uint4_of_int 8192; wtpref = Rtypes.uint4_of_int 8192; wtmult = Rtypes.uint4_of_int 8192; dtpref = Rtypes.uint4_of_int 8192; maxfilesize = Rtypes.uint8_of_int 0x3fffffff; time_delta = { seconds = Rtypes.uint4_of_int 1; nseconds = Rtypes.uint4_of_int 0 }; properties = Rtypes.uint4_of_int (Rtypes.int_of_uint4 fsf3_symlink lor Rtypes.int_of_uint4 fsf3_homogeneous lor Rtypes.int_of_uint4 fsf3_cansettime) } let pathconf map session arg name info fake = `nfs3_ok { obj_attributes''''' = `True (nfs_stat info fake); linkmax = Rtypes.uint4_of_int 1000; name_max = Rtypes.uint4_of_int 127; no_trunc = true; chown_restricted = true; case_insensitive = false; case_preserving = true } let setattr map session arg path info readinfo fake = begin match arg.guard with | `True time -> if time <> nfs_time readinfo.st_ctime then raise Not_sync | _ -> () end; let user = (user session) in begin if not (checkperm_user user info access3_modify) then raise Acces; match arg.new_attributes.mode' with | `True mode' -> let mode = Rtypes.int_of_uint4 mode' in if mode <> info.st_perm then chmod path mode | `False -> () end; begin if not (checkperm_user user info access3_modify) then raise Acces; match arg.new_attributes.size'' with | `True size'' -> let size = Rtypes.int64_of_uint8 size'' in if size <> info.st_size then truncate path size | `False -> () end; begin if not (checkperm_user user info access3_modify) then raise Acces; let currenttime = gettimeofday () in let atime = (match arg.new_attributes.atime' with | `set_to_client_time nfstime -> Some (float_of_nfs_time nfstime) | `dont_change -> None | `set_to_server_time -> Some currenttime) in let mtime = (match arg.new_attributes.mtime'' with | `set_to_client_time nfstime -> Some (float_of_nfs_time nfstime) | `dont_change -> None | `set_to_server_time -> Some currenttime) in match (atime, mtime) with | (Some atime, Some mtime) -> Unix.utimes path atime mtime | (Some atime, None) -> Unix.utimes path atime info.st_mtime | (None, Some mtime) -> Unix.utimes path info.st_atime mtime | (None, None) -> () end; begin let newuid = (match arg.new_attributes.uid' with | `True id when Rtypes.int_of_uint4 id <> info.st_uid -> Some (Rtypes.int_of_uint4 id) | _ -> None) in let newgid = (match arg.new_attributes.gid' with | `True id when Rtypes.int_of_uint4 id <> info.st_gid -> Some (Rtypes.int_of_uint4 id) | _ -> None) in let checkgid gidopt (_, gids, _) = match gidopt with None -> false | Some gid -> not (List.mem gid gids) in if (newuid <> None || (checkgid newgid user)) && not (checkperm_chown user info) then raise Perm else match (newuid, newgid) with | (Some uid, Some gid) -> lchown path uid gid | (Some uid, None) -> lchown path uid info.st_gid | (None, Some gid) -> lchown path info.st_uid gid | (None, None) -> () end; match L.lookupRead map (s2fh arg.object'.data) with | Some (postname, postinfo) -> `nfs3_ok { before = pre_op_attr readinfo; after = post_op_attr postinfo fake } | None -> raise Not_sync let write map session arg name info readinfo fake = if not (checkperm session info access3_modify) then raise Acces; let len = Rtypes.int_of_uint4 arg.count'' in let writeres = ref 0 in let fp = openfile name [O_WRONLY] 0 in (try writeres := pos Unix.write fp arg.data''' 0 len); close fp with e -> close fp; raise e); let count = !writeres in match L.lookupRead map (s2fh arg.file'.data) with | Some (postname, postinfo) -> `nfs3_ok { file_wcc = { before = pre_op_attr readinfo; after = post_op_attr postinfo fake }; count''' = Rtypes.uint4_of_int count; committed = file_sync; verf = startup_cookie } | None -> raise Not_sync let commit map session arg name info readinfo = raise Unimplemented let create map session arg path old wcc = if not (Util.validateName arg.where.name) then raise Acces else let matchedcookie = begin match (old, arg.how) with | (Some (oldpath, oldinfo), `exclusive a) when path = oldpath -> if oldinfo.st_kind <> S_REG then raise Exist else the cookie is placed in the atime and fields , so to check it * we need to munge the cookie to match the form returned by lstat * we need to munge the cookie to match the form returned by lstat *) let (cookie1, cookie2) = (Int32.to_float (Rtypes.int32_of_int4 (Rtypes.read_int4 a 0)), Int32.to_float (Rtypes.int32_of_int4 (Rtypes.read_int4 a 4))) in if cookie1 = oldinfo.st_atime && cookie2 = oldinfo.st_mtime then true else raise Exist | (Some (oldpath, oldinfo), `guarded _) when path = oldpath -> raise Exist | (Some (oldpath, oldinfo), `unchecked _) when path = oldpath && oldinfo.st_kind <> S_REG -> raise Exist | _ -> false end in let (uid, gid) = (match (user session) with | (uid, gid :: _, _) -> (uid, gid) | _ -> raise Perm) in let (data1, data2, guardtype) = (match arg.how with | `unchecked a -> (Int32.of_int (file_perm_of_sattr3 a), 0l, 0) | `guarded a -> (Int32.of_int (file_perm_of_sattr3 a), 0l, 1) | `exclusive a -> (Rtypes.int32_of_int4 (Rtypes.read_int4 a 0), Rtypes.int32_of_int4 (Rtypes.read_int4 a 4), 2)) in let res = if matchedcookie then 0 else Util.create path uid gid guardtype data1 data2 in if res <> 0 then raise Perm else remove_mask path; let dirFake = L.fhToFake map (s2fh arg.where.dir.data) in let newFake = Util.concatPath dirFake arg.where.name in let newFh = L.fakeToNewFh map newFake in match L.lookupRead map newFh with | Some (_, info) -> `nfs3_ok { obj = `True { data = fh2s newFh }; obj_attributes = post_op_attr info newFake; dir_wcc = wcc () } | None -> raise Not_sync let mkdir map session arg path old wcc = if not (Util.validateName arg.where'.name) then raise Acces else begin match old with | Some (oldpath, oldinfo) -> if path = oldpath then raise Exist | None -> () end; Unix.mkdir path (file_perm_of_sattr3 arg.attributes); begin match (user session) with | (uid, gid :: _, hostname) -> chown path uid gid | _ -> raise Perm end; remove_mask path; let dirFake = L.fhToFake map (s2fh arg.where'.dir.data) in let newFake = Util.concatPath dirFake arg.where'.name in let newFh = L.fakeToNewFh map newFake in match L.lookupRead map newFh with | Some (_, info) -> `nfs3_ok { obj = `True { data = fh2s newFh }; obj_attributes = post_op_attr info newFake; dir_wcc = wcc () } | None -> raise Not_sync let symlink map session arg path old wcc = if not (Util.validateName arg.where''.name) then raise Acces else begin match old with | Some (oldpath, oldinfo) -> if path = oldpath then raise Exist | None -> () end; Unix.symlink arg.symlink.symlink_data path; begin match (user session) with | (uid, gid :: _, hostname) -> lchown path uid gid | _ -> raise Perm end; remove_mask path; let dirFake = L.fhToFake map (s2fh arg.where''.dir.data) in let newFake = Util.concatPath dirFake arg.where''.name in let newFh = L.fakeToNewFh map newFake in match L.lookupRead map newFh with | Some (_, info) -> `nfs3_ok { obj = `True { data = fh2s newFh }; obj_attributes = post_op_attr info newFake; dir_wcc = wcc () } | None -> raise Not_sync let mknod map session arg path old wcc = if not (Util.validateName arg.where'''.name) then raise Acces else begin match old with | Some (oldpath, oldinfo) -> if path = oldpath then raise Exist | None -> () end; begin let decode_sattr3 user attr = let getint default set_uint32 = match set_uint32 with | `True u32 -> Rtypes.int_of_uint4 u32 | `False -> default in let (uid, gids, _) = user in let uid = getint uid attr.uid' in let gid = getint (List.hd gids) attr.gid' in let mode = getint default_perm attr.mode' in (uid, gid, mode) in let decode_dev { major = major; minor = minor } = Int64.logor (Int64.shift_left (Rtypes.int64_of_uint4 major) 8) (Rtypes.int64_of_uint4 minor) in let user = user session in match arg.what with | `nf3chr device -> begin if not (checkperm_mknod user) then raise Perm else let (uid, gid, mode) = decode_sattr3 user device.dev_attributes in let dev = decode_dev device.spec in try Util.mknod path (mode lor 0o020000) dev uid gid with Failure _ -> raise Acces end | `nf3blk device -> begin if not (checkperm_mknod user) then raise Perm else let (uid, gid, mode) = decode_sattr3 user device.dev_attributes in let dev = decode_dev device.spec in try Util.mknod path (mode lor 0o060000) dev uid gid with Failure _ -> raise Acces end | `nf3fifo attr -> begin let (uid, gid, mode) = decode_sattr3 user attr in try Util.mknod path (mode lor 0o10000) Int64.zero uid gid with Failure _ -> raise Acces end | `nf3sock attr -> begin let (uid, gid, mode) = decode_sattr3 user attr in try Util.mknod path (mode lor 0o140000) Int64.zero uid gid with Failure _ -> raise Acces end | _ -> raise Bad_type end; remove_mask path; let dirFake = L.fhToFake map (s2fh arg.where'''.dir.data) in let newFake = Util.concatPath dirFake arg.where'''.name in let newFh = L.fakeToNewFh map newFake in match L.lookupRead map newFh with | Some (_, info) -> `nfs3_ok { obj = `True { data = fh2s newFh }; obj_attributes = post_op_attr info newFake; dir_wcc = wcc () } | None -> raise Not_sync let remove map session arg readname readinfo writename wcc = if readinfo.st_kind = S_DIR then raise Isdir else if readname = writename then unlink writename; hide_fh_name map session (s2fh arg.dir.data) arg.name; `nfs3_ok (wcc ()) let rmdir map session arg readname readinfo writename wcc = if readinfo.st_kind <> S_DIR then raise Notdir else if readname = writename then rmdir writename; hide_fh_name map session (s2fh arg.dir.data) arg.name; `nfs3_ok (wcc ()) let rename map session arg = let fromfh = s2fh arg.from.dir.data in let tofh = s2fh arg.to'.dir.data in let fromfake = L.fhToFake map fromfh in let tofake = L.fhToFake map tofh in let pre_from = L.lookupRead map fromfh in let pre_to = L.lookupRead map tofh in if pre_from = None then `nfs3err_stale { fromdir_wcc = { before = `False; after = `False }; todir_wcc = { before = `False; after = `False } } else if pre_to = None then `nfs3err_stale { fromdir_wcc = { before = `False; after = `False }; todir_wcc = { before = `False; after = `False } } else let wcc () = let wcc_from () = { before = (match pre_from with | Some (_, info) -> pre_op_attr info | None -> `False); after = (match L.lookupRead map fromfh with | Some (_, info) -> post_op_attr info fromfake | None -> `False) } in let wcc_to () = { before = (match pre_to with | Some (_, info) -> pre_op_attr info | None -> `False); after = (match L.lookupRead map tofh with | Some (_, info) -> post_op_attr info tofake | None -> `False) } in { fromdir_wcc = wcc_from (); todir_wcc = wcc_to () } in match L.lookupWrite map (FhName (fromfh, arg.from.name)) with | (_, None) -> `nfs3err_acces (wcc ()) | (None, _) -> `nfs3err_noent (wcc ()) | (Some (readname, readinfo), Some writename) -> begin match L.lookupCreate map tofh arg.to'.name with | (None, _) -> `nfs3err_acces (wcc ()) | (Some newpath, _) -> begin L.mountFileCheck map newpath; try if readname = writename then begin L.mountFileCheck map writename; create_shadow_dirs map (user session) newpath (FhOnly tofh); Unix.rename writename newpath; hide_fh_name map session fromfh arg.from.name end else begin ignore (copy_on_write map (user session) (FhOnly tofh) (Some (readname, readinfo), Some newpath)); hide_fh_name map session fromfh arg.from.name end; `nfs3_ok (wcc ()) with e -> handle_exp e (wcc ()) end end let null map session arg = () let getattr map session arg = let objfh = s2fh arg.data in let fake = L.fhToFake map objfh in match L.lookupRead map objfh with | Some (name, info) -> `nfs3_ok (nfs_stat info fake) | None -> `nfs3err_stale let link map session arg = let objfh = s2fh arg.file''.data in let dirfh = s2fh arg.link.dir.data in let dirFake = L.fhToFake map dirfh in let linkname = arg.link.name in let newFake = Util.concatPath dirFake linkname in let newFh = L.fakeToNewFh map newFake in match (L.lookupRead map objfh, L.lookupRead map dirfh) with | (None, Some (dirname, dirinfo)) -> `nfs3err_stale { file_attributes' = `False; linkdir_wcc = { before = pre_op_attr dirinfo; after = post_op_attr dirinfo dirFake } } | (None, _) | (_, None) -> `nfs3err_stale { file_attributes' = `False; linkdir_wcc = { before = `False; after = `False } } | (Some (name, info), Some (dirname, dirinfo)) -> let wcc () = { file_attributes' = (match L.lookupRead map newFh with | Some (_, info) -> post_op_attr info newFake | None -> `False); linkdir_wcc = { before = pre_op_attr dirinfo; after = (match L.lookupRead map dirfh with | Some (_, info) -> post_op_attr info dirFake | None -> `False) } } in if dirinfo.st_kind <> S_DIR then `nfs3err_notdir (wcc ()) else begin match L.lookupCreate map dirfh linkname with | (None, _) -> `nfs3err_acces (wcc ()) | (Some path, old) -> try create_shadow_dirs map (user session) path (FhName (dirfh, linkname)); let createdirinfo = lstat (Util.dirname path) in if not (checkperm session createdirinfo access3_modify && Util.validateName linkname) then raise Acces; L.mountFileCheck map path; (match old with | Some (oldpath, _) when oldpath = path -> raise Exist | _ -> ()); Unix.link name path; `nfs3_ok (wcc ()) with e -> handle_exp e (wcc ()) end let wrap_readop name f map session arg objfh = try let objfh = s2fh objfh in let fake = L.fhToFake map objfh in match L.lookupRead map objfh with | Some (name, info) -> begin let postopattr = `True (nfs_stat info fake) in try f map session arg name info fake with e -> handle_exp e postopattr end | None -> `nfs3err_stale `False with e -> handle_exp e `False let lookup map session arg = wrap_readop "lookup" lookup map session arg arg.dir.data let access map session arg = wrap_readop "access" access map session arg arg.object'''.data let readlink map session arg = wrap_readop "readlink" readlink map session arg arg.data let read map session arg = wrap_readop "read" read map session arg arg.file.data let readdir map session arg = wrap_readop "readdir" readdir map session arg arg.dir'.data let readdirplus map session arg = wrap_readop "readdirplus" readdirplus map session arg arg.dir''.data let fsstat map session arg = wrap_readop "fsstat" fsstat map session arg arg.data let fsinfo map session arg = wrap_readop "fsinfo" fsinfo map session arg arg.data let pathconf map session arg = wrap_readop "pathconf" pathconf map session arg arg.data let wrap_writeop name f map session arg objfh = try let objfh = s2fh objfh in let fake = L.fhToFake map objfh in match L.lookupWrite map (FhOnly objfh) with | (Some (readname, readinfo), Some writename) as paths -> begin let (path, info) = if readname = writename then (readname, readinfo) else copy_on_write map (user session) (FhOnly objfh) paths in let wcc () = { before = pre_op_attr readinfo; after = (match L.lookupRead map objfh with | Some (_, info) -> post_op_attr info fake | None -> `False) } in try L.mountFileCheck map path; let res = f map session arg path info readinfo fake in res with e -> handle_exp e (wcc ()) end | (Some (readname, readinfo), None) -> `nfs3err_acces { before = pre_op_attr readinfo; after = post_op_attr readinfo fake } | (None, _) -> `nfs3err_stale { before = `False; after = `False } with e -> handle_exp e { before = `False; after = `False } let setattr map session arg = wrap_writeop "setattr" setattr map session arg arg.object'.data let write map session arg = wrap_writeop "write" write map session arg arg.file'.data let commit map session arg = wrap_writeop "commit" commit map session arg arg.file'''.data let wrap_createop opname f map session arg dirfh name = try let dirfh = s2fh dirfh in let dirFake = L.fhToFake map dirfh in match L.lookupRead map dirfh with | None -> `nfs3err_stale { before = `False; after = `False } | Some (dirname, dirinfo) -> let wcc () = { before = pre_op_attr dirinfo; after = (match L.lookupRead map dirfh with | Some (_, info) -> post_op_attr info dirFake | None -> `False) } in if dirinfo.st_kind <> S_DIR then `nfs3err_notdir (wcc ()) else begin match L.lookupCreate map dirfh name with | (Some path, old) -> begin try create_shadow_dirs map (user session) path (FhName (dirfh, name)); let createdirinfo = lstat (Util.dirname path) in if not (checkperm session createdirinfo access3_modify) then raise Acces; L.mountFileCheck map path; f map session arg path old wcc with e -> handle_exp e (wcc ()) end | _ -> `nfs3err_acces (wcc ()) end with e -> prerr_endline ( " exception " ^(Printexc.to_string e)^ " in " ^opname^"\n " ) ; handle_exp e { before = `False; after = `False } let create map session arg = wrap_createop "create" create map session arg arg.where.dir.data arg.where.name let mkdir map session arg = wrap_createop "mkdir" mkdir map session arg arg.where'.dir.data arg.where'.name let symlink map session arg = wrap_createop "symlink" symlink map session arg arg.where''.dir.data arg.where''.name let mknod map session arg = wrap_createop "mknod" mknod map session arg arg.where'''.dir.data arg.where'''.name let wrap_removeop opname f map session arg dirfh name = try let dirfh = s2fh dirfh in let dirFake = L.fhToFake map dirfh in match L.lookupRead map dirfh with | Some (dirname, dirinfo) -> let wcc () = { before = pre_op_attr dirinfo; after = (match L.lookupRead map dirfh with | Some (_, info) -> post_op_attr info dirFake | None -> `False) } in if dirinfo.st_kind <> S_DIR then `nfs3err_notdir (wcc ()) else begin match L.lookupWrite map (FhName (dirfh, name)) with | (Some (readname, readinfo), Some writename) -> begin try L.mountFileCheck map writename; let res = f map session arg readname readinfo writename wcc in res with e -> handle_exp e (wcc ()) end | (Some _, None) -> `nfs3err_acces (wcc ()) | (None, _) -> `nfs3err_noent (wcc ()) end | None -> `nfs3err_stale { before = `False; after = `False } with e -> prerr_endline ( " exception " ^(Printexc.to_string e)^ " in " ^opname^"\n " ) ; handle_exp e { before = `False; after = `False } let remove map session arg = wrap_removeop "remove" remove map session arg arg.dir.data arg.name let rmdir map session arg = wrap_removeop "rmdir" rmdir map session arg arg.dir.data arg.name let err0 () = `nfs3err_serverfault let err1 () = `nfs3err_serverfault `False wcc_data = { before = pre_op_attr ; after = post_op_attr } let err2 () = `nfs3err_serverfault { before = `False; after = `False } let err3 () = `nfs3err_serverfault { file_attributes' = `False; linkdir_wcc = { before = `False; after = `False } } rename3wcc = { fromdir_wcc = wcc_data ; todir_wcc = wcc_data } let err4 () = `nfs3err_serverfault { fromdir_wcc = { before = `False; after = `False }; todir_wcc = { before = `False; after = `False } } let wrap name f map session arg res = try f map session arg with | Unix_error (e,s1,s2) -> prerr_endline ("exception Unix_error\n ("^ (error_message e)^", "^s1^", "^s2^")\n in "^name^"\n"); res | e -> prerr_endline ("exception "^(Printexc.to_string e)^" in "^ name^"\n"); res let getattr map session arg = try getattr map session arg with _ -> `nfs3err_stale let rename map session arg = wrap "rename" rename map session arg (err4 ()) let link map session arg = wrap "link" link map session arg (err3 ())
3e7091cfec9cd2d30e66d8855529dcfd0a44e253b97e7c59fed5de8b4588082f
facebook/flow
nonvoid_return.mli
* Copyright ( c ) Meta Platforms , Inc. and affiliates . * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree . * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) val might_have_nonvoid_return : ALoc.t -> (ALoc.t, ALoc.t) Flow_ast.Function.t -> bool
null
https://raw.githubusercontent.com/facebook/flow/c0574f1cda8d915edf0402c912b92ed781c16536/src/analysis/env_builder/nonvoid_return.mli
ocaml
* Copyright ( c ) Meta Platforms , Inc. and affiliates . * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree . * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) val might_have_nonvoid_return : ALoc.t -> (ALoc.t, ALoc.t) Flow_ast.Function.t -> bool
e495311249eb1aa38bd5cd8994b782d85e160a9cfa30e4d719778f60a2ba9736
andersfugmann/ppx_protocol_conv
xml_light.mli
include Protocol_conv.Runtime.Driver with type t = Xml.xml val of_xml_light_exn: t -> t val of_xml_light: t -> (t, error) Protocol_conv.Runtime.result val to_xml_light: t -> t
null
https://raw.githubusercontent.com/andersfugmann/ppx_protocol_conv/add1548320707df042d64a4c81d3faa3c6cf2475/drivers/xml_light/xml_light.mli
ocaml
include Protocol_conv.Runtime.Driver with type t = Xml.xml val of_xml_light_exn: t -> t val of_xml_light: t -> (t, error) Protocol_conv.Runtime.result val to_xml_light: t -> t
f8356722cb9155867c413cfe4d8b748f3be59c9a2cbba3db05bcc8bd092d291d
chunsj/TH
resnet50.lisp
(defpackage :th.m.resnet50 (:use #:common-lisp #:mu #:th) (:export #:read-resnet50-weights #:resnet50 #:resnet50fcn)) (in-package :th.m.resnet50) (defparameter +model-location+ ($concat (namestring (user-homedir-pathname)) ".th/models")) (defun wfname-txt (wn) (format nil "~A/resnet50/resnet50-~A.txt" +model-location+ (string-downcase wn))) (defun wfname-bin (wn) (format nil "~A/resnet50/resnet50-~A.dat" +model-location+ (string-downcase wn))) (defun read-text-weight-file (wn &optional (readp t)) (when readp (let ((f (file.disk (wfname-txt wn) "r")) (tx (tensor))) ($fread tx f) ($fclose f) tx))) (defun read-weight-file (wn &optional (readp t)) (when readp (let ((f (file.disk (wfname-bin wn) "r")) (tx (tensor))) (setf ($fbinaryp f) t) ($fread tx f) ($fclose f) tx))) (defparameter *wparams* (list :k1 "p0" :g1 "p1" :b1 "p2" :m1 "m1" :v1 "v1" :k2 "p3" :g2 "p4" :b2 "p5" :m2 "m2" :v2 "v2" :k3 "p6" :g3 "p7" :b3 "p8" :m3 "m3" :v3 "v3" :k4 "p9" :g4 "p10" :b4 "p11" :m4 "m4" :v4 "v4" :dk1 "p12" :dg1 "p13" :db1 "p14" :dm1 "m5" :dv1 "v5" :k5 "p15" :g5 "p16" :b5 "p17" :m5 "m6" :v5 "v6" :k6 "p18" :g6 "p19" :b6 "p20" :m6 "m7" :v6 "v7" :k7 "p21" :g7 "p22" :b7 "p23" :m7 "m8" :v7 "v8" :k8 "p24" :g8 "p25" :b8 "p26" :m8 "m9" :v8 "v9" :k9 "p27" :g9 "p28" :b9 "p29" :m9 "m10" :v9 "v10" :k10 "p30" :g10 "p31" :b10 "p32" :m10 "m11" :v10 "v11" :k11 "p33" :g11 "p34" :b11 "p35" :m11 "m12" :v11 "v12" :k12 "p36" :g12 "p37" :b12 "p38" :m12 "m13" :v12 "v13" :k13 "p39" :g13 "p40" :b13 "p41" :m13 "m14" :v13 "v14" :dk2 "p42" :dg2 "p43" :db2 "p44" :dm2 "m15" :dv2 "v15" :k14 "p45" :g14 "p46" :b14 "p47" :m14 "m16" :v14 "v16" :k15 "p48" :g15 "p49" :b15 "p50" :m15 "m17" :v15 "v17" :k16 "p51" :g16 "p52" :b16 "p53" :m16 "m18" :v16 "v18" :k17 "p54" :g17 "p55" :b17 "p56" :m17 "m19" :v17 "v19" :k18 "p57" :g18 "p58" :b18 "p59" :m18 "m20" :v18 "v20" :k19 "p60" :g19 "p61" :b19 "p62" :m19 "m21" :v19 "v21" :k20 "p63" :g20 "p64" :b20 "p65" :m20 "m22" :v20 "v22" :k21 "p66" :g21 "p67" :b21 "p68" :m21 "m23" :v21 "v23" :k22 "p69" :g22 "p70" :b22 "p71" :m22 "m24" :v22 "v24" :k23 "p72" :g23 "p73" :b23 "p74" :m23 "m25" :v23 "v25" :k24 "p75" :g24 "p76" :b24 "p77" :m24 "m26" :v24 "v26" :k25 "p78" :g25 "p79" :b25 "p80" :m25 "m27" :v25 "v27" :dk3 "p81" :dg3 "p82" :db3 "p83" :dm3 "m28" :dv3 "v28" :k26 "p84" :g26 "p85" :b26 "p86" :m26 "m29" :v26 "v29" :k27 "p87" :g27 "p88" :b27 "p89" :m27 "m30" :v27 "v30" :k28 "p90" :g28 "p91" :b28 "p92" :m28 "m31" :v28 "v31" :k29 "p93" :g29 "p94" :b29 "p95" :m29 "m32" :v29 "v32" :k30 "p96" :g30 "p97" :b30 "p98" :m30 "m33" :v30 "v33" :k31 "p99" :g31 "p100" :b31 "p101" :m31 "m34" :v31 "v34" :k32 "p102" :g32 "p103" :b32 "p104" :m32 "m35" :v32 "v35" :k33 "p105" :g33 "p106" :b33 "p107" :m33 "m36" :v33 "v36" :k34 "p108" :g34 "p109" :b34 "p110" :m34 "m37" :v34 "v37" :k35 "p111" :g35 "p112" :b35 "p113" :m35 "m38" :v35 "v38" :k36 "p114" :g36 "p115" :b36 "p116" :m36 "m39" :v36 "v39" :k37 "p117" :g37 "p118" :b37 "p119" :m37 "m40" :v37 "v40" :k38 "p120" :g38 "p121" :b38 "p122" :m38 "m41" :v38 "v41" :k39 "p123" :g39 "p124" :b39 "p125" :m39 "m42" :v39 "v42" :k40 "p126" :g40 "p127" :b40 "p128" :m40 "m43" :v40 "v43" :k41 "p129" :g41 "p130" :b41 "p131" :m41 "m44" :v41 "v44" :k42 "p132" :g42 "p133" :b42 "p134" :m42 "m45" :v42 "v45" :k43 "p135" :g43 "p136" :b43 "p137" :m43 "m46" :v43 "v46" :dk4 "p138" :dg4 "p139" :db4 "p140" :dm4 "m47" :dv4 "v47" :k44 "p141" :g44 "p142" :b44 "p143" :m44 "m48" :v44 "v48" :k45 "p144" :g45 "p145" :b45 "p146" :m45 "m49" :v45 "v49" :k46 "p147" :g46 "p148" :b46 "p149" :m46 "m50" :v46 "v50" :k47 "p150" :g47 "p151" :b47 "p152" :m47 "m51" :v47 "v51" :k48 "p153" :g48 "p154" :b48 "p155" :m48 "m52" :v48 "v52" :k49 "p156" :g49 "p157" :b49 "p158" :m49 "m53" :v49 "v53" :w50 "f159" :b50 "f160")) (defun read-resnet50-text-weights (&optional (flatp t)) (if flatp (loop :for k :in *wparams* :by #'cddr :for wn = (getf *wparams* k) :append (list k (read-text-weight-file wn))) (loop :for k :in *wparams* :by #'cddr :for wn = (getf *wparams* k) :when (not (or (eq k :w50) (eq k :b50))) :append (list k (read-text-weight-file wn))))) (defun read-resnet50-weights (&optional (flatp t)) (if flatp (loop :for k :in *wparams* :by #'cddr :for wn = (getf *wparams* k) :append (list k (read-weight-file wn))) (loop :for k :in *wparams* :by #'cddr :for wn = (getf *wparams* k) :when (not (or (eq k :w50) (eq k :b50))) :append (list k (read-weight-file wn))))) (defun write-binary-weight-file (w filename) (let ((f (file.disk filename "w"))) (setf ($fbinaryp f) t) ($fwrite w f) ($fclose f))) (defun write-resnet50-binary-weights (&optional weights) (let ((weights (or weights (read-resnet50-text-weights)))) (loop :for wk :in *wparams* :by #'cddr :for wn = (getf *wparams* wk) :for w = (getf weights wk) :do (write-binary-weight-file w (wfname-bin wn))))) (defun w (w wn) (getf w wn)) (defun blki (x w) (-> x ($conv2d (w w :k1) nil 2 2 3 3) ($bn (w w :g1) (w w :b1) (w w :m1) (w w :v1)) ($relu) ($maxpool2d 3 3 2 2 1 1))) (defun kw (h n) (values (intern (format nil "~A~A" (string-upcase h) n) "KEYWORD"))) (defun blkd (x w n1 n2 n3 dn &optional (stride 1)) (let ((k1 (kw "k" n1)) (g1 (kw "g" n1)) (b1 (kw "b" n1)) (m1 (kw "m" n1)) (v1 (kw "v" n1)) (k2 (kw "k" n2)) (g2 (kw "g" n2)) (b2 (kw "b" n2)) (m2 (kw "m" n2)) (v2 (kw "v" n2)) (k3 (kw "k" n3)) (g3 (kw "g" n3)) (b3 (kw "b" n3)) (m3 (kw "m" n3)) (v3 (kw "v" n3)) (dk (kw "dk" dn)) (dg (kw "dg" dn)) (db (kw "db" dn)) (dm (kw "dm" dn)) (dv (kw "dv" dn))) (let* ((r (-> x ($conv2d (w w dk) nil stride stride) ($bn (w w dg) (w w db) (w w dm) (w w dv)))) (o (-> x ($conv2d (w w k1) nil 1 1) ($bn (w w g1) (w w b1) (w w m1) (w w v1)) ($relu) ($conv2d (w w k2) nil stride stride 1 1) ($bn (w w g2) (w w b2) (w w m2) (w w v2)) ($relu) ($conv2d (w w k3) nil 1 1) ($bn (w w g3) (w w b3) (w w m3) (w w v3))))) ($relu ($+ o r))))) (defun blk (x w n1 n2 n3) (let ((k1 (kw "k" n1)) (g1 (kw "g" n1)) (b1 (kw "b" n1)) (m1 (kw "m" n1)) (v1 (kw "v" n1)) (k2 (kw "k" n2)) (g2 (kw "g" n2)) (b2 (kw "b" n2)) (m2 (kw "m" n2)) (v2 (kw "v" n2)) (k3 (kw "k" n3)) (g3 (kw "g" n3)) (b3 (kw "b" n3)) (m3 (kw "m" n3)) (v3 (kw "v" n3))) (let ((r x) (o (-> x ($conv2d (w w k1) nil 1 1) ($bn (w w g1) (w w b1) (w w m1) (w w v1)) ($relu) ($conv2d (w w k2) nil 1 1 1 1) ($bn (w w g2) (w w b2) (w w m2) (w w v2)) ($relu) ($conv2d (w w k3) nil 1 1) ($bn (w w g3) (w w b3) (w w m3) (w w v3))))) ($relu ($+ o r))))) (defun resnet50-flat (x w flat) (let ((nbatch ($size x 0))) (cond ((eq flat :all) (-> ($reshape x nbatch 2048) ($affine (w w :w50) (w w :b50)) ($softmax))) (t x)))) (defun resnet50 (&optional (flat :all) weights) (let ((w (or weights (read-resnet50-weights (not (eq flat :none)))))) (lambda (x) (when (and x (>= ($ndim x) 3) (equal (last ($size x) 3) (list 3 224 224))) (let ((x (if (eq ($ndim x) 3) ($reshape x 1 3 224 224) x))) (-> x (blki w) (blkd w 2 3 4 1) (blk w 5 6 7) (blk w 8 9 10) (blkd w 11 12 13 2 2) (blk w 14 15 16) (blk w 17 18 19) (blk w 20 21 22) (blkd w 23 24 25 3 2) (blk w 26 27 28) (blk w 29 30 31) (blk w 32 33 34) (blk w 35 36 37) (blk w 38 39 40) (blkd w 41 42 43 4 2) (blk w 44 45 46) (blk w 47 48 49) ($avgpool2d 7 7 1 1) (resnet50-flat w flat))))))) (defun resnet50fcn (&optional weights) (let* ((w (or weights (read-resnet50-weights t))) (w50 (w w :w50)) (b50 (w w :b50)) (k50 ($reshape ($transpose w50) 1000 2048 1 1)) (b50 ($squeeze b50))) (lambda (x) (when (and x (>= ($ndim x) 3)) (let ((x (if (eq ($ndim x) 3) ($unsqueeze x 0) x))) (-> x (blki w) (blkd w 2 3 4 1) (blk w 5 6 7) (blk w 8 9 10) (blkd w 11 12 13 2 2) (blk w 14 15 16) (blk w 17 18 19) (blk w 20 21 22) (blkd w 23 24 25 3 2) (blk w 26 27 28) (blk w 29 30 31) (blk w 32 33 34) (blk w 35 36 37) (blk w 38 39 40) (blkd w 41 42 43 4 2) (blk w 44 45 46) (blk w 47 48 49) ($avgpool2d 7 7 1 1) ($conv2d k50 b50) ($softmax)))))))
null
https://raw.githubusercontent.com/chunsj/TH/890f05ab81148d9fe558be3979c30c303b448480/m/resnet50.lisp
lisp
(defpackage :th.m.resnet50 (:use #:common-lisp #:mu #:th) (:export #:read-resnet50-weights #:resnet50 #:resnet50fcn)) (in-package :th.m.resnet50) (defparameter +model-location+ ($concat (namestring (user-homedir-pathname)) ".th/models")) (defun wfname-txt (wn) (format nil "~A/resnet50/resnet50-~A.txt" +model-location+ (string-downcase wn))) (defun wfname-bin (wn) (format nil "~A/resnet50/resnet50-~A.dat" +model-location+ (string-downcase wn))) (defun read-text-weight-file (wn &optional (readp t)) (when readp (let ((f (file.disk (wfname-txt wn) "r")) (tx (tensor))) ($fread tx f) ($fclose f) tx))) (defun read-weight-file (wn &optional (readp t)) (when readp (let ((f (file.disk (wfname-bin wn) "r")) (tx (tensor))) (setf ($fbinaryp f) t) ($fread tx f) ($fclose f) tx))) (defparameter *wparams* (list :k1 "p0" :g1 "p1" :b1 "p2" :m1 "m1" :v1 "v1" :k2 "p3" :g2 "p4" :b2 "p5" :m2 "m2" :v2 "v2" :k3 "p6" :g3 "p7" :b3 "p8" :m3 "m3" :v3 "v3" :k4 "p9" :g4 "p10" :b4 "p11" :m4 "m4" :v4 "v4" :dk1 "p12" :dg1 "p13" :db1 "p14" :dm1 "m5" :dv1 "v5" :k5 "p15" :g5 "p16" :b5 "p17" :m5 "m6" :v5 "v6" :k6 "p18" :g6 "p19" :b6 "p20" :m6 "m7" :v6 "v7" :k7 "p21" :g7 "p22" :b7 "p23" :m7 "m8" :v7 "v8" :k8 "p24" :g8 "p25" :b8 "p26" :m8 "m9" :v8 "v9" :k9 "p27" :g9 "p28" :b9 "p29" :m9 "m10" :v9 "v10" :k10 "p30" :g10 "p31" :b10 "p32" :m10 "m11" :v10 "v11" :k11 "p33" :g11 "p34" :b11 "p35" :m11 "m12" :v11 "v12" :k12 "p36" :g12 "p37" :b12 "p38" :m12 "m13" :v12 "v13" :k13 "p39" :g13 "p40" :b13 "p41" :m13 "m14" :v13 "v14" :dk2 "p42" :dg2 "p43" :db2 "p44" :dm2 "m15" :dv2 "v15" :k14 "p45" :g14 "p46" :b14 "p47" :m14 "m16" :v14 "v16" :k15 "p48" :g15 "p49" :b15 "p50" :m15 "m17" :v15 "v17" :k16 "p51" :g16 "p52" :b16 "p53" :m16 "m18" :v16 "v18" :k17 "p54" :g17 "p55" :b17 "p56" :m17 "m19" :v17 "v19" :k18 "p57" :g18 "p58" :b18 "p59" :m18 "m20" :v18 "v20" :k19 "p60" :g19 "p61" :b19 "p62" :m19 "m21" :v19 "v21" :k20 "p63" :g20 "p64" :b20 "p65" :m20 "m22" :v20 "v22" :k21 "p66" :g21 "p67" :b21 "p68" :m21 "m23" :v21 "v23" :k22 "p69" :g22 "p70" :b22 "p71" :m22 "m24" :v22 "v24" :k23 "p72" :g23 "p73" :b23 "p74" :m23 "m25" :v23 "v25" :k24 "p75" :g24 "p76" :b24 "p77" :m24 "m26" :v24 "v26" :k25 "p78" :g25 "p79" :b25 "p80" :m25 "m27" :v25 "v27" :dk3 "p81" :dg3 "p82" :db3 "p83" :dm3 "m28" :dv3 "v28" :k26 "p84" :g26 "p85" :b26 "p86" :m26 "m29" :v26 "v29" :k27 "p87" :g27 "p88" :b27 "p89" :m27 "m30" :v27 "v30" :k28 "p90" :g28 "p91" :b28 "p92" :m28 "m31" :v28 "v31" :k29 "p93" :g29 "p94" :b29 "p95" :m29 "m32" :v29 "v32" :k30 "p96" :g30 "p97" :b30 "p98" :m30 "m33" :v30 "v33" :k31 "p99" :g31 "p100" :b31 "p101" :m31 "m34" :v31 "v34" :k32 "p102" :g32 "p103" :b32 "p104" :m32 "m35" :v32 "v35" :k33 "p105" :g33 "p106" :b33 "p107" :m33 "m36" :v33 "v36" :k34 "p108" :g34 "p109" :b34 "p110" :m34 "m37" :v34 "v37" :k35 "p111" :g35 "p112" :b35 "p113" :m35 "m38" :v35 "v38" :k36 "p114" :g36 "p115" :b36 "p116" :m36 "m39" :v36 "v39" :k37 "p117" :g37 "p118" :b37 "p119" :m37 "m40" :v37 "v40" :k38 "p120" :g38 "p121" :b38 "p122" :m38 "m41" :v38 "v41" :k39 "p123" :g39 "p124" :b39 "p125" :m39 "m42" :v39 "v42" :k40 "p126" :g40 "p127" :b40 "p128" :m40 "m43" :v40 "v43" :k41 "p129" :g41 "p130" :b41 "p131" :m41 "m44" :v41 "v44" :k42 "p132" :g42 "p133" :b42 "p134" :m42 "m45" :v42 "v45" :k43 "p135" :g43 "p136" :b43 "p137" :m43 "m46" :v43 "v46" :dk4 "p138" :dg4 "p139" :db4 "p140" :dm4 "m47" :dv4 "v47" :k44 "p141" :g44 "p142" :b44 "p143" :m44 "m48" :v44 "v48" :k45 "p144" :g45 "p145" :b45 "p146" :m45 "m49" :v45 "v49" :k46 "p147" :g46 "p148" :b46 "p149" :m46 "m50" :v46 "v50" :k47 "p150" :g47 "p151" :b47 "p152" :m47 "m51" :v47 "v51" :k48 "p153" :g48 "p154" :b48 "p155" :m48 "m52" :v48 "v52" :k49 "p156" :g49 "p157" :b49 "p158" :m49 "m53" :v49 "v53" :w50 "f159" :b50 "f160")) (defun read-resnet50-text-weights (&optional (flatp t)) (if flatp (loop :for k :in *wparams* :by #'cddr :for wn = (getf *wparams* k) :append (list k (read-text-weight-file wn))) (loop :for k :in *wparams* :by #'cddr :for wn = (getf *wparams* k) :when (not (or (eq k :w50) (eq k :b50))) :append (list k (read-text-weight-file wn))))) (defun read-resnet50-weights (&optional (flatp t)) (if flatp (loop :for k :in *wparams* :by #'cddr :for wn = (getf *wparams* k) :append (list k (read-weight-file wn))) (loop :for k :in *wparams* :by #'cddr :for wn = (getf *wparams* k) :when (not (or (eq k :w50) (eq k :b50))) :append (list k (read-weight-file wn))))) (defun write-binary-weight-file (w filename) (let ((f (file.disk filename "w"))) (setf ($fbinaryp f) t) ($fwrite w f) ($fclose f))) (defun write-resnet50-binary-weights (&optional weights) (let ((weights (or weights (read-resnet50-text-weights)))) (loop :for wk :in *wparams* :by #'cddr :for wn = (getf *wparams* wk) :for w = (getf weights wk) :do (write-binary-weight-file w (wfname-bin wn))))) (defun w (w wn) (getf w wn)) (defun blki (x w) (-> x ($conv2d (w w :k1) nil 2 2 3 3) ($bn (w w :g1) (w w :b1) (w w :m1) (w w :v1)) ($relu) ($maxpool2d 3 3 2 2 1 1))) (defun kw (h n) (values (intern (format nil "~A~A" (string-upcase h) n) "KEYWORD"))) (defun blkd (x w n1 n2 n3 dn &optional (stride 1)) (let ((k1 (kw "k" n1)) (g1 (kw "g" n1)) (b1 (kw "b" n1)) (m1 (kw "m" n1)) (v1 (kw "v" n1)) (k2 (kw "k" n2)) (g2 (kw "g" n2)) (b2 (kw "b" n2)) (m2 (kw "m" n2)) (v2 (kw "v" n2)) (k3 (kw "k" n3)) (g3 (kw "g" n3)) (b3 (kw "b" n3)) (m3 (kw "m" n3)) (v3 (kw "v" n3)) (dk (kw "dk" dn)) (dg (kw "dg" dn)) (db (kw "db" dn)) (dm (kw "dm" dn)) (dv (kw "dv" dn))) (let* ((r (-> x ($conv2d (w w dk) nil stride stride) ($bn (w w dg) (w w db) (w w dm) (w w dv)))) (o (-> x ($conv2d (w w k1) nil 1 1) ($bn (w w g1) (w w b1) (w w m1) (w w v1)) ($relu) ($conv2d (w w k2) nil stride stride 1 1) ($bn (w w g2) (w w b2) (w w m2) (w w v2)) ($relu) ($conv2d (w w k3) nil 1 1) ($bn (w w g3) (w w b3) (w w m3) (w w v3))))) ($relu ($+ o r))))) (defun blk (x w n1 n2 n3) (let ((k1 (kw "k" n1)) (g1 (kw "g" n1)) (b1 (kw "b" n1)) (m1 (kw "m" n1)) (v1 (kw "v" n1)) (k2 (kw "k" n2)) (g2 (kw "g" n2)) (b2 (kw "b" n2)) (m2 (kw "m" n2)) (v2 (kw "v" n2)) (k3 (kw "k" n3)) (g3 (kw "g" n3)) (b3 (kw "b" n3)) (m3 (kw "m" n3)) (v3 (kw "v" n3))) (let ((r x) (o (-> x ($conv2d (w w k1) nil 1 1) ($bn (w w g1) (w w b1) (w w m1) (w w v1)) ($relu) ($conv2d (w w k2) nil 1 1 1 1) ($bn (w w g2) (w w b2) (w w m2) (w w v2)) ($relu) ($conv2d (w w k3) nil 1 1) ($bn (w w g3) (w w b3) (w w m3) (w w v3))))) ($relu ($+ o r))))) (defun resnet50-flat (x w flat) (let ((nbatch ($size x 0))) (cond ((eq flat :all) (-> ($reshape x nbatch 2048) ($affine (w w :w50) (w w :b50)) ($softmax))) (t x)))) (defun resnet50 (&optional (flat :all) weights) (let ((w (or weights (read-resnet50-weights (not (eq flat :none)))))) (lambda (x) (when (and x (>= ($ndim x) 3) (equal (last ($size x) 3) (list 3 224 224))) (let ((x (if (eq ($ndim x) 3) ($reshape x 1 3 224 224) x))) (-> x (blki w) (blkd w 2 3 4 1) (blk w 5 6 7) (blk w 8 9 10) (blkd w 11 12 13 2 2) (blk w 14 15 16) (blk w 17 18 19) (blk w 20 21 22) (blkd w 23 24 25 3 2) (blk w 26 27 28) (blk w 29 30 31) (blk w 32 33 34) (blk w 35 36 37) (blk w 38 39 40) (blkd w 41 42 43 4 2) (blk w 44 45 46) (blk w 47 48 49) ($avgpool2d 7 7 1 1) (resnet50-flat w flat))))))) (defun resnet50fcn (&optional weights) (let* ((w (or weights (read-resnet50-weights t))) (w50 (w w :w50)) (b50 (w w :b50)) (k50 ($reshape ($transpose w50) 1000 2048 1 1)) (b50 ($squeeze b50))) (lambda (x) (when (and x (>= ($ndim x) 3)) (let ((x (if (eq ($ndim x) 3) ($unsqueeze x 0) x))) (-> x (blki w) (blkd w 2 3 4 1) (blk w 5 6 7) (blk w 8 9 10) (blkd w 11 12 13 2 2) (blk w 14 15 16) (blk w 17 18 19) (blk w 20 21 22) (blkd w 23 24 25 3 2) (blk w 26 27 28) (blk w 29 30 31) (blk w 32 33 34) (blk w 35 36 37) (blk w 38 39 40) (blkd w 41 42 43 4 2) (blk w 44 45 46) (blk w 47 48 49) ($avgpool2d 7 7 1 1) ($conv2d k50 b50) ($softmax)))))))
d371bd1fc4b5810690b624795500675fe6134bc1f5c804a3c598946c045920d3
haskell/haskell-language-server
PragmaNotAtTopWithCommentsAtTop.hs
{-# LANGUAGE OverloadedStrings #-} # OPTIONS_GHC -Wall # -- another comment #   LANGUAGE TupleSections # {- some comment -} class Semigroup a => SomeData a instance SomeData All pure -i runghc -p " haskellPackages.ghcWithPackages ( hp : with ; [ turtle ] ) " {-# OPTIONS_GHC -Wno-unrecognised-pragmas #-} addOne :: Int -> Int addOne x = x + 1
null
https://raw.githubusercontent.com/haskell/haskell-language-server/fdbc555a9245cb3761c2bf7335f3d18b8cf7673c/plugins/hls-refactor-plugin/test/data/import-placement/PragmaNotAtTopWithCommentsAtTop.hs
haskell
# LANGUAGE OverloadedStrings # another comment some comment # OPTIONS_GHC -Wno-unrecognised-pragmas #
# OPTIONS_GHC -Wall # #   LANGUAGE TupleSections # class Semigroup a => SomeData a instance SomeData All pure -i runghc -p " haskellPackages.ghcWithPackages ( hp : with ; [ turtle ] ) " addOne :: Int -> Int addOne x = x + 1
f18f03de277d306c89b37878d8c1b06f159bc1fc7a5ce06f356312adad56e01c
dbuenzli/gg
B0.ml
open B0_kit.V000 (* OCaml library names *) let b0_std = B0_ocaml.libname "b0.std" let gg = B0_ocaml.libname "gg" let gg_top = B0_ocaml.libname "gg.top" let gg_kit = B0_ocaml.libname "gg.kit" let str = B0_ocaml.libname "str" let compiler_libs_toplevel = B0_ocaml.libname "compiler-libs.toplevel" (* Libraries *) let gg_lib = let srcs = Fpath.[ `File (v "src/gg.mli"); `File (v "src/gg.ml") ] in let requires = [] in B0_ocaml.lib gg ~doc:"The gg library" ~srcs ~requires let gg_top_lib = let srcs = Fpath.[ `File (v "src/gg_top.ml") ] in let requires = [compiler_libs_toplevel] in let doc = "The gg toplevel support library" in B0_ocaml.lib gg_top ~doc ~srcs ~requires let gg_kit_lib = let srcs = Fpath.[ `Dir (v "src_kit") ] in let requires = [gg] in let doc = "The gg kit library" in B0_ocaml.lib gg_kit ~doc ~srcs ~requires (* Tests *) let test_exe ?(requires = []) src ~doc = let src = Fpath.v src in let srcs = Fpath.[`File src] in let meta = B0_meta.(empty |> tag test) in let requires = gg :: requires in B0_ocaml.exe (Fpath.basename ~no_ext:true src) ~srcs ~doc ~meta ~requires let test = let srcs = Fpath.[`File (v "test/test.ml"); `File (v "test/checkm.ml"); `File (v "test/checkm.mli")] in let meta = B0_meta.(empty |> tag test) in let requires = [gg; str] in let doc = "Gg test suite" in B0_ocaml.exe "test" ~srcs ~doc ~meta ~requires let test_color_schemes = let doc = "Color scheme tests" in test_exe "test/test_color_schemes.ml" ~doc ~requires:[gg_kit] (* N.B. Unless vg is in the build universe, those tests with vg needs to be build with `-x gg` otherwise we get inconsistent assumptions. See the also the pgon2_bool_tests pack. *) let vg = B0_ocaml.libname "vg" let vg_htmlc = B0_ocaml.libname "vg.htmlc" let vg_pdf = B0_ocaml.libname "vg.pdf" let brr = B0_ocaml.libname "brr" let pgon2_bool_steps = let srcs = Fpath.[`Dir (v "src_kit"); `File (v "test/pgon2_test_cases.ml"); `File (v "test/pgon2_bool_steps.ml");] in let requires = [gg; vg; vg_htmlc; brr] in let assets_root = Fpath.v "test" in let meta = let comp_mode = `Separate and source_map = Some `Inline in B0_jsoo.meta ~requires ~assets_root ~comp_mode ~source_map () in let doc = "Pgon2 boolean operations step debugger" in B0_jsoo.web "pgon2_bool_steps" ~doc ~srcs ~meta let pgon2_bool_tests = let srcs = Fpath.[`Dir (v "src_kit"); `File (v "test/pgon2_test_cases.ml"); `File (v "test/pgon2_bool_tests.ml");] in let requires = [b0_std; gg; vg; vg_pdf] in let meta = B0_meta.(empty |> tag test) in let doc = "Pgon2 boolean operations tests" in B0_ocaml.exe "pgon2_bool_tests" ~srcs ~doc ~meta ~requires let viz_orient = let srcs = Fpath.[`File (v "test/orient_p2.ml")] in let requires = [gg; brr] in let meta = let comp_mode = `Separate in B0_jsoo.meta ~requires ~comp_mode ~source_map:(Some `Inline) () in let doc = "Orientation predicate visualization"in B0_jsoo.web "orient_p2" ~doc ~srcs ~meta let color_schemes = let srcs = Fpath.[`File (v "test/color_schemes.ml")] in let requires = [gg; gg_kit; brr; vg; vg_htmlc] in let meta = let comp_mode = `Separate in B0_jsoo.meta ~requires ~comp_mode ~source_map:(Some `Inline) () in let doc = "Color schemes visualization"in B0_jsoo.web "color_schemes" ~doc ~srcs ~meta (* Packs *) let pgon_test_pack = (* We use a locked pack so that we compile against the installed gg otherwise we compile gg and we get inconsistent assumptions with installed vg. *) let meta = B0_meta.(empty |> tag test) in let doc = "Pgon2 boolean operations visual testing" in B0_pack.v "pgon2_bool_tests" ~doc ~meta ~locked:true @@ [pgon2_bool_tests; pgon2_bool_steps] let default = let meta = let open B0_meta in empty |> tag B0_opam.tag |> add authors ["The gg programmers"] |> add maintainers ["Daniel Bünzli <daniel.buenzl >"] |> add homepage "" |> add online_doc "/" |> add licenses ["ISC"; "Apache-2.0"] |> add repo "git+" |> add issues "" |> add description_tags ["matrix"; "vector"; "color"; "data-structure"; "graphics"; "org:erratique"] |> add B0_opam.Meta.depends [ "ocaml", {|>= "4.08.0"|}; "ocamlfind", {|build|}; "ocamlbuild", {|build|}; "topkg", {|build & >= "1.0.3"|}; "brr", {|with-test|}; "vg", {|with-test|}; ] |> add B0_opam.Meta.build {|[["ocaml" "pkg/pkg.ml" "build" "--dev-pkg" "%{dev}%"]]|} in B0_pack.v "default" ~doc:"gg package" ~meta ~locked:true @@ [gg_lib; gg_kit_lib; gg_top_lib; test; viz_orient]
null
https://raw.githubusercontent.com/dbuenzli/gg/ed822d5d922034c01a43240f5c3c94fa83b6bcb7/B0.ml
ocaml
OCaml library names Libraries Tests N.B. Unless vg is in the build universe, those tests with vg needs to be build with `-x gg` otherwise we get inconsistent assumptions. See the also the pgon2_bool_tests pack. Packs We use a locked pack so that we compile against the installed gg otherwise we compile gg and we get inconsistent assumptions with installed vg.
open B0_kit.V000 let b0_std = B0_ocaml.libname "b0.std" let gg = B0_ocaml.libname "gg" let gg_top = B0_ocaml.libname "gg.top" let gg_kit = B0_ocaml.libname "gg.kit" let str = B0_ocaml.libname "str" let compiler_libs_toplevel = B0_ocaml.libname "compiler-libs.toplevel" let gg_lib = let srcs = Fpath.[ `File (v "src/gg.mli"); `File (v "src/gg.ml") ] in let requires = [] in B0_ocaml.lib gg ~doc:"The gg library" ~srcs ~requires let gg_top_lib = let srcs = Fpath.[ `File (v "src/gg_top.ml") ] in let requires = [compiler_libs_toplevel] in let doc = "The gg toplevel support library" in B0_ocaml.lib gg_top ~doc ~srcs ~requires let gg_kit_lib = let srcs = Fpath.[ `Dir (v "src_kit") ] in let requires = [gg] in let doc = "The gg kit library" in B0_ocaml.lib gg_kit ~doc ~srcs ~requires let test_exe ?(requires = []) src ~doc = let src = Fpath.v src in let srcs = Fpath.[`File src] in let meta = B0_meta.(empty |> tag test) in let requires = gg :: requires in B0_ocaml.exe (Fpath.basename ~no_ext:true src) ~srcs ~doc ~meta ~requires let test = let srcs = Fpath.[`File (v "test/test.ml"); `File (v "test/checkm.ml"); `File (v "test/checkm.mli")] in let meta = B0_meta.(empty |> tag test) in let requires = [gg; str] in let doc = "Gg test suite" in B0_ocaml.exe "test" ~srcs ~doc ~meta ~requires let test_color_schemes = let doc = "Color scheme tests" in test_exe "test/test_color_schemes.ml" ~doc ~requires:[gg_kit] let vg = B0_ocaml.libname "vg" let vg_htmlc = B0_ocaml.libname "vg.htmlc" let vg_pdf = B0_ocaml.libname "vg.pdf" let brr = B0_ocaml.libname "brr" let pgon2_bool_steps = let srcs = Fpath.[`Dir (v "src_kit"); `File (v "test/pgon2_test_cases.ml"); `File (v "test/pgon2_bool_steps.ml");] in let requires = [gg; vg; vg_htmlc; brr] in let assets_root = Fpath.v "test" in let meta = let comp_mode = `Separate and source_map = Some `Inline in B0_jsoo.meta ~requires ~assets_root ~comp_mode ~source_map () in let doc = "Pgon2 boolean operations step debugger" in B0_jsoo.web "pgon2_bool_steps" ~doc ~srcs ~meta let pgon2_bool_tests = let srcs = Fpath.[`Dir (v "src_kit"); `File (v "test/pgon2_test_cases.ml"); `File (v "test/pgon2_bool_tests.ml");] in let requires = [b0_std; gg; vg; vg_pdf] in let meta = B0_meta.(empty |> tag test) in let doc = "Pgon2 boolean operations tests" in B0_ocaml.exe "pgon2_bool_tests" ~srcs ~doc ~meta ~requires let viz_orient = let srcs = Fpath.[`File (v "test/orient_p2.ml")] in let requires = [gg; brr] in let meta = let comp_mode = `Separate in B0_jsoo.meta ~requires ~comp_mode ~source_map:(Some `Inline) () in let doc = "Orientation predicate visualization"in B0_jsoo.web "orient_p2" ~doc ~srcs ~meta let color_schemes = let srcs = Fpath.[`File (v "test/color_schemes.ml")] in let requires = [gg; gg_kit; brr; vg; vg_htmlc] in let meta = let comp_mode = `Separate in B0_jsoo.meta ~requires ~comp_mode ~source_map:(Some `Inline) () in let doc = "Color schemes visualization"in B0_jsoo.web "color_schemes" ~doc ~srcs ~meta let pgon_test_pack = let meta = B0_meta.(empty |> tag test) in let doc = "Pgon2 boolean operations visual testing" in B0_pack.v "pgon2_bool_tests" ~doc ~meta ~locked:true @@ [pgon2_bool_tests; pgon2_bool_steps] let default = let meta = let open B0_meta in empty |> tag B0_opam.tag |> add authors ["The gg programmers"] |> add maintainers ["Daniel Bünzli <daniel.buenzl >"] |> add homepage "" |> add online_doc "/" |> add licenses ["ISC"; "Apache-2.0"] |> add repo "git+" |> add issues "" |> add description_tags ["matrix"; "vector"; "color"; "data-structure"; "graphics"; "org:erratique"] |> add B0_opam.Meta.depends [ "ocaml", {|>= "4.08.0"|}; "ocamlfind", {|build|}; "ocamlbuild", {|build|}; "topkg", {|build & >= "1.0.3"|}; "brr", {|with-test|}; "vg", {|with-test|}; ] |> add B0_opam.Meta.build {|[["ocaml" "pkg/pkg.ml" "build" "--dev-pkg" "%{dev}%"]]|} in B0_pack.v "default" ~doc:"gg package" ~meta ~locked:true @@ [gg_lib; gg_kit_lib; gg_top_lib; test; viz_orient]
0a9b7cfce54f400fc9a17448eb22bcef80a31fa17147c336571777343a911ff6
NorfairKing/declops
Main.hs
module Main where import Declops main :: IO () main = declopsMain
null
https://raw.githubusercontent.com/NorfairKing/declops/66c968386ccda5e5d9c6fb09afebb093873bbc8c/declops/app/Main.hs
haskell
module Main where import Declops main :: IO () main = declopsMain
44bc751669c1a77a54185372c4c86178bc791e71bdea07c9fca68b8ebe24f18f
pirapira/coq2rust
tokens.ml
(************************************************************************) v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2012 \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * (* // * This file is distributed under the terms of the *) (* * GNU Lesser General Public License Version 2.1 *) (************************************************************************) (* Application of printing rules based on a dictionary specific to the target language *) s Dictionaries : trees annotated with string options , each node being a map from chars to dictionaries ( the subtrees ) . A trie , in other words . ( code copied from parsing / lexer.ml4 for the use of coqdoc , Apr 2010 ) from chars to dictionaries (the subtrees). A trie, in other words. (code copied from parsing/lexer.ml4 for the use of coqdoc, Apr 2010) *) module CharMap = Map.Make (struct type t = char let compare (x : t) (y : t) = compare x y end) type ttree = { node : string option; branch : ttree CharMap.t } let empty_ttree = { node = None; branch = CharMap.empty } let ttree_add ttree str translated = let rec insert tt i = if i == String.length str then {node = Some translated; branch = tt.branch} else let c = str.[i] in let br = match try Some (CharMap.find c tt.branch) with Not_found -> None with | Some tt' -> CharMap.add c (insert tt' (i + 1)) (CharMap.remove c tt.branch) | None -> let tt' = {node = None; branch = CharMap.empty} in CharMap.add c (insert tt' (i + 1)) tt.branch in { node = tt.node; branch = br } in insert ttree 0 (* Removes a string from a dictionary: returns an equal dictionary if the word not present. *) let ttree_remove ttree str = let rec remove tt i = if i == String.length str then {node = None; branch = tt.branch} else let c = str.[i] in let br = match try Some (CharMap.find c tt.branch) with Not_found -> None with | Some tt' -> CharMap.add c (remove tt' (i + 1)) (CharMap.remove c tt.branch) | None -> tt.branch in { node = tt.node; branch = br } in remove ttree 0 let ttree_descend ttree c = CharMap.find c ttree.branch let ttree_find ttree str = let rec proc_rec tt i = if i == String.length str then tt else proc_rec (CharMap.find str.[i] tt.branch) (i+1) in proc_rec ttree 0 (*s Parameters of the translation automaton *) type out_function = bool -> bool -> Index.index_entry option -> string -> unit let token_tree = ref (ref empty_ttree) let outfun = ref (fun _ _ _ _ -> failwith "outfun not initialized") (*s Translation automaton *) let buff = Buffer.create 4 let flush_buffer was_symbolchar tag tok = let hastr = String.length tok <> 0 in if hastr then !outfun false was_symbolchar tag tok; if Buffer.length buff <> 0 then !outfun true (if hastr then not was_symbolchar else was_symbolchar) tag (Buffer.contents buff); Buffer.clear buff type sublexer_state = | Neutral | Buffering of bool * Index.index_entry option * string * ttree let translation_state = ref Neutral let buffer_char is_symbolchar ctag c = let rec aux = function | Neutral -> restart_buffering () | Buffering (was_symbolchar,tag,translated,tt) -> if tag <> ctag then A strong tag comes from Coq ; if different Coq tags (* hence, we don't try to see the chars as part of a single token *) let translated = match tt.node with | Some tok -> Buffer.clear buff; tok | None -> translated in flush_buffer was_symbolchar tag translated; restart_buffering () else begin (* If we change the category of characters (symbol vs ident) *) (* we accept this as a possible token cut point and remember the *) (* translated token up to that point *) let translated = if is_symbolchar <> was_symbolchar then match tt.node with | Some tok -> Buffer.clear buff; tok | None -> translated else translated in (* We try to make a significant token from the current *) (* buffer and the new character *) try let tt = ttree_descend tt c in Buffer.add_char buff c; Buffering (is_symbolchar,ctag,translated,tt) with Not_found -> (* No existing translation for the given set of chars *) if is_symbolchar <> was_symbolchar then (* If we changed the category of character read, we accept it *) (* as a possible cut point and restart looking for a translation *) (flush_buffer was_symbolchar tag translated; restart_buffering ()) else (* If we did not change the category of character read, we do *) (* not want to cut arbitrarily in the middle of the sequence of *) (* symbol characters or identifier characters *) (Buffer.add_char buff c; Buffering (is_symbolchar,tag,translated,empty_ttree)) end and restart_buffering () = let tt = try ttree_descend !(!token_tree) c with Not_found -> empty_ttree in Buffer.add_char buff c; Buffering (is_symbolchar,ctag,"",tt) in translation_state := aux !translation_state let output_tagged_ident_string s = for i = 0 to String.length s - 1 do buffer_char false None s.[i] done let output_tagged_symbol_char tag c = buffer_char true tag c let flush_sublexer () = match !translation_state with | Neutral -> () | Buffering (was_symbolchar,tag,translated,tt) -> let translated = match tt.node with | Some tok -> Buffer.clear buff; tok | None -> translated in flush_buffer was_symbolchar tag translated; translation_state := Neutral (* Translation not using the automaton *) let translate s = try (ttree_find !(!token_tree) s).node with Not_found -> None
null
https://raw.githubusercontent.com/pirapira/coq2rust/22e8aaefc723bfb324ca2001b2b8e51fcc923543/tools/coqdoc/tokens.ml
ocaml
********************************************************************** // * This file is distributed under the terms of the * GNU Lesser General Public License Version 2.1 ********************************************************************** Application of printing rules based on a dictionary specific to the target language Removes a string from a dictionary: returns an equal dictionary if the word not present. s Parameters of the translation automaton s Translation automaton hence, we don't try to see the chars as part of a single token If we change the category of characters (symbol vs ident) we accept this as a possible token cut point and remember the translated token up to that point We try to make a significant token from the current buffer and the new character No existing translation for the given set of chars If we changed the category of character read, we accept it as a possible cut point and restart looking for a translation If we did not change the category of character read, we do not want to cut arbitrarily in the middle of the sequence of symbol characters or identifier characters Translation not using the automaton
v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2012 \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * s Dictionaries : trees annotated with string options , each node being a map from chars to dictionaries ( the subtrees ) . A trie , in other words . ( code copied from parsing / lexer.ml4 for the use of coqdoc , Apr 2010 ) from chars to dictionaries (the subtrees). A trie, in other words. (code copied from parsing/lexer.ml4 for the use of coqdoc, Apr 2010) *) module CharMap = Map.Make (struct type t = char let compare (x : t) (y : t) = compare x y end) type ttree = { node : string option; branch : ttree CharMap.t } let empty_ttree = { node = None; branch = CharMap.empty } let ttree_add ttree str translated = let rec insert tt i = if i == String.length str then {node = Some translated; branch = tt.branch} else let c = str.[i] in let br = match try Some (CharMap.find c tt.branch) with Not_found -> None with | Some tt' -> CharMap.add c (insert tt' (i + 1)) (CharMap.remove c tt.branch) | None -> let tt' = {node = None; branch = CharMap.empty} in CharMap.add c (insert tt' (i + 1)) tt.branch in { node = tt.node; branch = br } in insert ttree 0 let ttree_remove ttree str = let rec remove tt i = if i == String.length str then {node = None; branch = tt.branch} else let c = str.[i] in let br = match try Some (CharMap.find c tt.branch) with Not_found -> None with | Some tt' -> CharMap.add c (remove tt' (i + 1)) (CharMap.remove c tt.branch) | None -> tt.branch in { node = tt.node; branch = br } in remove ttree 0 let ttree_descend ttree c = CharMap.find c ttree.branch let ttree_find ttree str = let rec proc_rec tt i = if i == String.length str then tt else proc_rec (CharMap.find str.[i] tt.branch) (i+1) in proc_rec ttree 0 type out_function = bool -> bool -> Index.index_entry option -> string -> unit let token_tree = ref (ref empty_ttree) let outfun = ref (fun _ _ _ _ -> failwith "outfun not initialized") let buff = Buffer.create 4 let flush_buffer was_symbolchar tag tok = let hastr = String.length tok <> 0 in if hastr then !outfun false was_symbolchar tag tok; if Buffer.length buff <> 0 then !outfun true (if hastr then not was_symbolchar else was_symbolchar) tag (Buffer.contents buff); Buffer.clear buff type sublexer_state = | Neutral | Buffering of bool * Index.index_entry option * string * ttree let translation_state = ref Neutral let buffer_char is_symbolchar ctag c = let rec aux = function | Neutral -> restart_buffering () | Buffering (was_symbolchar,tag,translated,tt) -> if tag <> ctag then A strong tag comes from Coq ; if different Coq tags let translated = match tt.node with | Some tok -> Buffer.clear buff; tok | None -> translated in flush_buffer was_symbolchar tag translated; restart_buffering () else begin let translated = if is_symbolchar <> was_symbolchar then match tt.node with | Some tok -> Buffer.clear buff; tok | None -> translated else translated in try let tt = ttree_descend tt c in Buffer.add_char buff c; Buffering (is_symbolchar,ctag,translated,tt) with Not_found -> if is_symbolchar <> was_symbolchar then (flush_buffer was_symbolchar tag translated; restart_buffering ()) else (Buffer.add_char buff c; Buffering (is_symbolchar,tag,translated,empty_ttree)) end and restart_buffering () = let tt = try ttree_descend !(!token_tree) c with Not_found -> empty_ttree in Buffer.add_char buff c; Buffering (is_symbolchar,ctag,"",tt) in translation_state := aux !translation_state let output_tagged_ident_string s = for i = 0 to String.length s - 1 do buffer_char false None s.[i] done let output_tagged_symbol_char tag c = buffer_char true tag c let flush_sublexer () = match !translation_state with | Neutral -> () | Buffering (was_symbolchar,tag,translated,tt) -> let translated = match tt.node with | Some tok -> Buffer.clear buff; tok | None -> translated in flush_buffer was_symbolchar tag translated; translation_state := Neutral let translate s = try (ttree_find !(!token_tree) s).node with Not_found -> None
3787f8c1414075adbe170520cab3596114b63b66f42a7fc4c2dac3f35bf3c8e6
janestreet/pythonlib
class_wrapper.ml
open Base open Import module Id : sig type t val create : unit -> t val to_string : t -> string end = struct type t = int let create = let current = ref 0 in fun () -> Int.incr current; !current ;; let to_string = Int.to_string end let content_field = "_content" type 'a t = { wrap : 'a -> Py.Object.t ; unwrap : Py.Object.t -> 'a ; name : string ; mutable cls_object : Py.Object.t option } let set_cls_object_exn t pyobject = if Option.is_some t.cls_object then Printf.failwithf "cls_object for %s has already been set" t.name (); t.cls_object <- Some pyobject ;; module Init = struct type 'a cls = 'a t type 'a fn = | No_keywords of ('a cls -> args:pyobject list -> 'a) | With_keywords of ('a cls -> args:pyobject list -> keywords:(string, pyobject, String.comparator_witness) Map.t -> 'a) type 'a t = { fn : 'a fn ; docstring : string option } let create ?docstring fn = { docstring; fn = No_keywords fn } let create_with_keywords ?docstring fn = { fn = With_keywords fn; docstring } let defunc ?docstring defunc = let docstring = Defunc.params_docstring ?docstring defunc in let fn cls ~args ~keywords = let fn = Defunc.apply_ defunc (Array.of_list args) keywords in fn cls in create_with_keywords ~docstring fn ;; let no_arg ?docstring fn = let fn cls ~args ~keywords = if not (List.is_empty args) then value_errorf "no argument expected"; if not (Map.is_empty keywords) then value_errorf "no keyword argument expected"; fn cls in create_with_keywords ?docstring fn ;; end module Method = struct type 'a cls = 'a t type 'a fn = | No_keywords of (self:'a * pyobject -> args:pyobject list -> pyobject) | No_keywords_raw of (self:pyobject -> args:pyobject list -> pyobject) | With_keywords of (self:'a * pyobject -> args:pyobject list -> keywords:(string, pyobject, String.comparator_witness) Map.t -> pyobject) type 'a t = { name : string ; fn : 'a fn ; docstring : string option } let create ?docstring name fn = { name; fn = No_keywords fn; docstring } let create_raw ?docstring name fn = { name; fn = No_keywords_raw fn; docstring } let create_with_keywords ?docstring name fn = { name; fn = With_keywords fn; docstring } let defunc ?docstring name defunc = let docstring = Defunc.params_docstring ?docstring defunc in let fn ~self ~args ~keywords = let fn = Defunc.apply_ defunc (Array.of_list args) keywords in fn ~self in create_with_keywords ~docstring name fn ;; let no_arg ?docstring name fn = let fn ~self ~args ~keywords = if not (List.is_empty args) then value_errorf "no argument expected"; if not (Map.is_empty keywords) then value_errorf "no keyword argument expected"; fn ~self in create_with_keywords ?docstring name fn ;; end let wrap_capsule t obj = t.wrap obj let unwrap_exn t pyobj = let pyobj = match Py.Object.get_attr_string pyobj content_field with | None -> Printf.failwithf "no %s field in object" content_field () | Some content -> content in if not (Py.Capsule.check pyobj) then failwith "not an ocaml capsule"; t.unwrap pyobj ;; let unwrap t pyobj = try Some (unwrap_exn t pyobj) with | _ -> None ;; let wrap t obj = let cls = Option.value_exn t.cls_object in Py.Object.call_function_obj_args cls [| wrap_capsule t obj |] ;; let make ?to_string_repr ?to_string ?eq ?init ?(fields = []) name ~methods = let id = Id.create () in let t = let wrap, unwrap = Py.Capsule.make (Printf.sprintf "%s-%s" name (Id.to_string id)) in { wrap; unwrap; cls_object = None; name } in let methods = let to_string = Option.map to_string ~f:(fun fn ~self ~args:_ -> fn t (fst self) |> Py.String.of_string) in let to_string_repr = Option.map to_string_repr ~f:(fun fn ~self ~args:_ -> fn t (fst self) |> Py.String.of_string) in let to_string_repr = Option.first_some to_string_repr to_string in let eq = Option.map eq ~f:(fun fn ~self ~args -> let rhs = match args with | [] -> failwith "eq with no argument" | _ :: _ :: _ -> Printf.failwithf "eq with %d arguments" (List.length args) () | [ rhs ] -> rhs in fn t (fst self) (unwrap_exn t rhs) |> Py.Bool.of_bool) in List.filter_map [ "__str__", to_string; "__repr__", to_string_repr; "__eq__", eq ] ~f:(fun (name, fn) -> Option.map fn ~f:(fun fn -> Method.create name fn)) @ methods t in let methods = List.map methods ~f:(fun { Method.name; fn; docstring } -> let fn = let self_and_args args = let args = Array.to_list args in match args with | [] -> failwith "empty input" | p :: q -> p, q in match (fn : _ Method.fn) with | No_keywords fn -> Py.Callable.of_function ~name ?docstring (fun args -> protect_python ~f:(fun () -> let self, args = self_and_args args in fn ~self:(unwrap_exn t self, self) ~args)) | No_keywords_raw fn -> Py.Callable.of_function ~name ?docstring (fun args -> protect_python ~f:(fun () -> let self, args = self_and_args args in fn ~self ~args)) | With_keywords fn -> Py.Callable.of_function_with_keywords ~name ?docstring (fun args keywords -> protect_python ~f:(fun () -> let self, args = self_and_args args in let keywords = Py_module.keywords_of_python keywords |> Or_error.ok_exn in fn ~self:(unwrap_exn t self, self) ~args ~keywords)) in name, fn) in let init = let name = "__init__" in let fn = let docstring = Option.bind init ~f:(fun i -> i.Init.docstring) in Py.Callable.of_function_as_tuple_and_dict ~name ?docstring (fun tuple kwargs -> try let self, args = match Py.Tuple.to_list tuple with | [] -> failwith "empty input" | p :: q -> p, q in let content = match args with (* Do not call the __init__ function when given a capsule as input as this is used when wrapping values. *) | [ capsule ] when Py.Capsule.check capsule -> capsule | _ -> (match init with | Some init -> let v = match (init.fn : _ Init.fn) with | No_keywords fn -> fn t ~args | With_keywords fn -> let keywords = Py_module.keywords_of_python kwargs |> Or_error.ok_exn in fn t ~args ~keywords in wrap_capsule t v | None -> Py.none) in Py.Object.set_attr_string self content_field content; Py.none with | Py.Err _ as pyerr -> raise pyerr | exn -> let msg = Printf.sprintf "ocaml error %s" (Exn.to_string_mach exn) in raise (Py.Err (ValueError, msg))) in name, fn in let cls_object = if List.exists fields ~f:(fun (field_name, _) -> String.equal field_name content_field) then value_errorf "'%s' is not an acceptable field name because it is reserved for internal use by \ OCaml's class_wrapper" content_field; let fields = (content_field, Py.none) :: fields in Py.Class.init name ~fields ~methods:(init :: methods) in set_cls_object_exn t cls_object; t ;; let register_in_module t modl = Py_module.set_value modl t.name (Option.value_exn t.cls_object) ;; let clear_content _t pyobject = Py.Object.set_attr_string pyobject content_field Py.none let cls_object t = Option.value_exn t.cls_object let is_instance t pyobject = Py.Object.is_instance pyobject (cls_object t) let set_content t pyobject v = Py.Object.set_attr_string pyobject content_field (wrap_capsule t v) ;;
null
https://raw.githubusercontent.com/janestreet/pythonlib/88a7183f1942c1c7c1f5612489c109aa88855254/src/class_wrapper.ml
ocaml
Do not call the __init__ function when given a capsule as input as this is used when wrapping values.
open Base open Import module Id : sig type t val create : unit -> t val to_string : t -> string end = struct type t = int let create = let current = ref 0 in fun () -> Int.incr current; !current ;; let to_string = Int.to_string end let content_field = "_content" type 'a t = { wrap : 'a -> Py.Object.t ; unwrap : Py.Object.t -> 'a ; name : string ; mutable cls_object : Py.Object.t option } let set_cls_object_exn t pyobject = if Option.is_some t.cls_object then Printf.failwithf "cls_object for %s has already been set" t.name (); t.cls_object <- Some pyobject ;; module Init = struct type 'a cls = 'a t type 'a fn = | No_keywords of ('a cls -> args:pyobject list -> 'a) | With_keywords of ('a cls -> args:pyobject list -> keywords:(string, pyobject, String.comparator_witness) Map.t -> 'a) type 'a t = { fn : 'a fn ; docstring : string option } let create ?docstring fn = { docstring; fn = No_keywords fn } let create_with_keywords ?docstring fn = { fn = With_keywords fn; docstring } let defunc ?docstring defunc = let docstring = Defunc.params_docstring ?docstring defunc in let fn cls ~args ~keywords = let fn = Defunc.apply_ defunc (Array.of_list args) keywords in fn cls in create_with_keywords ~docstring fn ;; let no_arg ?docstring fn = let fn cls ~args ~keywords = if not (List.is_empty args) then value_errorf "no argument expected"; if not (Map.is_empty keywords) then value_errorf "no keyword argument expected"; fn cls in create_with_keywords ?docstring fn ;; end module Method = struct type 'a cls = 'a t type 'a fn = | No_keywords of (self:'a * pyobject -> args:pyobject list -> pyobject) | No_keywords_raw of (self:pyobject -> args:pyobject list -> pyobject) | With_keywords of (self:'a * pyobject -> args:pyobject list -> keywords:(string, pyobject, String.comparator_witness) Map.t -> pyobject) type 'a t = { name : string ; fn : 'a fn ; docstring : string option } let create ?docstring name fn = { name; fn = No_keywords fn; docstring } let create_raw ?docstring name fn = { name; fn = No_keywords_raw fn; docstring } let create_with_keywords ?docstring name fn = { name; fn = With_keywords fn; docstring } let defunc ?docstring name defunc = let docstring = Defunc.params_docstring ?docstring defunc in let fn ~self ~args ~keywords = let fn = Defunc.apply_ defunc (Array.of_list args) keywords in fn ~self in create_with_keywords ~docstring name fn ;; let no_arg ?docstring name fn = let fn ~self ~args ~keywords = if not (List.is_empty args) then value_errorf "no argument expected"; if not (Map.is_empty keywords) then value_errorf "no keyword argument expected"; fn ~self in create_with_keywords ?docstring name fn ;; end let wrap_capsule t obj = t.wrap obj let unwrap_exn t pyobj = let pyobj = match Py.Object.get_attr_string pyobj content_field with | None -> Printf.failwithf "no %s field in object" content_field () | Some content -> content in if not (Py.Capsule.check pyobj) then failwith "not an ocaml capsule"; t.unwrap pyobj ;; let unwrap t pyobj = try Some (unwrap_exn t pyobj) with | _ -> None ;; let wrap t obj = let cls = Option.value_exn t.cls_object in Py.Object.call_function_obj_args cls [| wrap_capsule t obj |] ;; let make ?to_string_repr ?to_string ?eq ?init ?(fields = []) name ~methods = let id = Id.create () in let t = let wrap, unwrap = Py.Capsule.make (Printf.sprintf "%s-%s" name (Id.to_string id)) in { wrap; unwrap; cls_object = None; name } in let methods = let to_string = Option.map to_string ~f:(fun fn ~self ~args:_ -> fn t (fst self) |> Py.String.of_string) in let to_string_repr = Option.map to_string_repr ~f:(fun fn ~self ~args:_ -> fn t (fst self) |> Py.String.of_string) in let to_string_repr = Option.first_some to_string_repr to_string in let eq = Option.map eq ~f:(fun fn ~self ~args -> let rhs = match args with | [] -> failwith "eq with no argument" | _ :: _ :: _ -> Printf.failwithf "eq with %d arguments" (List.length args) () | [ rhs ] -> rhs in fn t (fst self) (unwrap_exn t rhs) |> Py.Bool.of_bool) in List.filter_map [ "__str__", to_string; "__repr__", to_string_repr; "__eq__", eq ] ~f:(fun (name, fn) -> Option.map fn ~f:(fun fn -> Method.create name fn)) @ methods t in let methods = List.map methods ~f:(fun { Method.name; fn; docstring } -> let fn = let self_and_args args = let args = Array.to_list args in match args with | [] -> failwith "empty input" | p :: q -> p, q in match (fn : _ Method.fn) with | No_keywords fn -> Py.Callable.of_function ~name ?docstring (fun args -> protect_python ~f:(fun () -> let self, args = self_and_args args in fn ~self:(unwrap_exn t self, self) ~args)) | No_keywords_raw fn -> Py.Callable.of_function ~name ?docstring (fun args -> protect_python ~f:(fun () -> let self, args = self_and_args args in fn ~self ~args)) | With_keywords fn -> Py.Callable.of_function_with_keywords ~name ?docstring (fun args keywords -> protect_python ~f:(fun () -> let self, args = self_and_args args in let keywords = Py_module.keywords_of_python keywords |> Or_error.ok_exn in fn ~self:(unwrap_exn t self, self) ~args ~keywords)) in name, fn) in let init = let name = "__init__" in let fn = let docstring = Option.bind init ~f:(fun i -> i.Init.docstring) in Py.Callable.of_function_as_tuple_and_dict ~name ?docstring (fun tuple kwargs -> try let self, args = match Py.Tuple.to_list tuple with | [] -> failwith "empty input" | p :: q -> p, q in let content = match args with | [ capsule ] when Py.Capsule.check capsule -> capsule | _ -> (match init with | Some init -> let v = match (init.fn : _ Init.fn) with | No_keywords fn -> fn t ~args | With_keywords fn -> let keywords = Py_module.keywords_of_python kwargs |> Or_error.ok_exn in fn t ~args ~keywords in wrap_capsule t v | None -> Py.none) in Py.Object.set_attr_string self content_field content; Py.none with | Py.Err _ as pyerr -> raise pyerr | exn -> let msg = Printf.sprintf "ocaml error %s" (Exn.to_string_mach exn) in raise (Py.Err (ValueError, msg))) in name, fn in let cls_object = if List.exists fields ~f:(fun (field_name, _) -> String.equal field_name content_field) then value_errorf "'%s' is not an acceptable field name because it is reserved for internal use by \ OCaml's class_wrapper" content_field; let fields = (content_field, Py.none) :: fields in Py.Class.init name ~fields ~methods:(init :: methods) in set_cls_object_exn t cls_object; t ;; let register_in_module t modl = Py_module.set_value modl t.name (Option.value_exn t.cls_object) ;; let clear_content _t pyobject = Py.Object.set_attr_string pyobject content_field Py.none let cls_object t = Option.value_exn t.cls_object let is_instance t pyobject = Py.Object.is_instance pyobject (cls_object t) let set_content t pyobject v = Py.Object.set_attr_string pyobject content_field (wrap_capsule t v) ;;
090215a5e54df0a8271a36e8763b21f85a1f0f135afc09633f8d4fa88e4f17fb
karlhof26/gimp-scheme
whitebalance.scm
is a script for The GIMP ; ; Description: converts the color temperature of an image ; Last changed : 30 July 2022 ; Copyright ( C ) 2006 - 2009 < > ; With many thanks to < > , ; from whose grey-point script this is inspired. ; ; -------------------------------------------------------------------- ; ; This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 2 of the License , or ; (at your option) any later version. ; ; This program is distributed in the hope that it will be useful, ; but WITHOUT ANY WARRANTY; without even the implied warranty of ; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ; GNU General Public License for more details. ; You should have received a copy of the GNU General Public License ; along with this program; if not, write to the Free Software Foundation , Inc. , 675 Mass Ave , Cambridge , , USA . ; (define (script-fu-whitebalance image drawable mode amount intensmult satura) (define (floor x) (- x (fmod x 1))) Converts from linear to gamma - corrected sRGB [ 0,1 ] (define (togamma x) (if (<= x 0.00304) (* x 12.92) (let* ((exponent (/ 1 2.4))) (- (* 1.055 (pow x exponent)) 0.055) ) ) ) Converts from linear to gamma - corrected sRGB [ 0,255 ] (define (togamma255 x) (max (min (floor (* 256 (togamma x))) 255) 0) ) Converts from gamma - corrected sRGB [ 0,1 ] to linear (define (tolinear y) (if (<= y 0.0392768) (/ y 12.92) (let* ((ratio (/ (+ y 0.055) 1.055))) (pow ratio 2.4) ) ) ) Converts from gamma - corrected sRGB [ 0,255 ] to linear (define (to255linear y) (tolinear (/ y 255)) ) ; Applies a ratio (in linear space) to sRGB values, where the sRGB values are scaled 0 .. 255 . (define (lin-mult-in-gamma-space y255 r) (togamma255 (* r (to255linear y255))) ) ; Multiplication in the gamma space (define (linemult y r) (max (min (floor (* y r)) 255) 0) ) ; Makes the target be the average of the foreground, for gamma-colors (define (makegreyg r g b) (let* ((avg (/ (+ r (+ g b)) 3))) (list avg avg avg)) ) ; Makes the target be the average of the foreground, for linear colors ; Goal: keep the intensity constant (define (makegrey r g b) (let* ((avg (+ (+ (* 0.2125 r) (* 0.7154 g)) (* 0.0721 b)))) (list avg avg avg)) ) ; Makes the target be the linear colors of the background (define (linearcols l) (let* ( (r (to255linear (car l))) (g (to255linear (cadr l))) (b (to255linear (caddr l))) ) (list r g b) ) ) ; This is the color table, taken from ; (let* ( Foreground and background (fg (car (gimp-context-get-foreground))) (bg (car (gimp-context-get-background))) ; Conversion amount (a (/ amount 100)) ; LINEAR PORTION Source colors , 0 .. 255 (sbr (car fg)) (sbg (cadr fg)) (sbb (caddr fg)) ; Source colors, linear (sr (to255linear sbr)) (sg (to255linear sbg)) (sb (to255linear sbb)) ; Finds the target colors, linear ; average of fg colors (tcs (cond ((= mode 0) (makegrey sr sg sb)) ; taken from background ((= mode 1) (linearcols bg)))) ; Extracts the target colors (tr (car tcs)) (tg (cadr tcs)) (tb (caddr tcs)) ; computes the ratios. If the source is 0, no conversion happens. (rra (if (= sbr 0) 1 (/ tr sr))) (rga (if (= sbg 0) 1 (/ tg sg))) (rba (if (= sbb 0) 1 (/ tb sb))) ; Takes into account the conversion amount. (rr (+ 1 (* a (- rra 1)))) (rg (+ 1 (* a (- rga 1)))) (rb (+ 1 (* a (- rba 1)))) Multiplies them by the intensity modification (m (/ intensmult 100)) And these are the real ratios , linear (rratio (* rr m)) (gratio (* rg m)) (bratio (* rb m)) (i 0) (num_bytes 256) (red-curve (cons-array num_bytes 'byte)) (green-curve (cons-array num_bytes 'byte)) (blue-curve (cons-array num_bytes 'byte)) ) (gimp-image-undo-group-start image) (while (< i num_bytes) (aset red-curve i (lin-mult-in-gamma-space i rratio)) (aset green-curve i (lin-mult-in-gamma-space i gratio)) (aset blue-curve i (lin-mult-in-gamma-space i bratio)) (set! i (+ i 1)) ) (gimp-curves-explicit drawable HISTOGRAM-RED num_bytes red-curve ) (gimp-curves-explicit drawable HISTOGRAM-GREEN num_bytes green-curve) (gimp-curves-explicit drawable HISTOGRAM-BLUE num_bytes blue-curve ) (gimp-hue-saturation drawable 0 0.0 0.0 satura) (gimp-image-undo-group-end image) (gimp-displays-flush) (gc) ; garbage cleanup ; memory cleanup; array was used ) ) (script-fu-register "script-fu-whitebalance" "White balance Color Temperature" "Changes the color temperature. White Balance 2.1\nFor help, go to \nfile:whitebalance.scm" "Luca de Alfaro <>" "Luca de Alfaro" "2006-2008" "RGB*" SF-IMAGE "Image" 0 SF-DRAWABLE "Drawable" 0 SF-OPTION "Mode" '("Make foreground gray" "Convert foreground to background") SF-ADJUSTMENT _"Conversion amount (%)" '(100 0 100 1 10 0 0) SF-ADJUSTMENT _"New intensity (%)" '(100 0 200 1 10 0 0) SF-ADJUSTMENT _"Saturation change (%)" '(0 -100 100 1 10 0 0) ) (script-fu-menu-register "script-fu-whitebalance" "<Toolbox>/Script-Fu/Colors")
null
https://raw.githubusercontent.com/karlhof26/gimp-scheme/bd8c74d19772675781f89b3e007d14092653b27a/whitebalance.scm
scheme
Description: converts the color temperature of an image from whose grey-point script this is inspired. -------------------------------------------------------------------- This program is free software; you can redistribute it and/or modify either version 2 of the License , or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. along with this program; if not, write to the Free Software Applies a ratio (in linear space) to sRGB values, where the sRGB Multiplication in the gamma space Makes the target be the average of the foreground, for gamma-colors Makes the target be the average of the foreground, for linear colors Goal: keep the intensity constant Makes the target be the linear colors of the background This is the color table, taken from Conversion amount LINEAR PORTION Source colors, linear Finds the target colors, linear average of fg colors taken from background Extracts the target colors computes the ratios. If the source is 0, no conversion happens. Takes into account the conversion amount. garbage cleanup ; memory cleanup; array was used
is a script for The GIMP Last changed : 30 July 2022 Copyright ( C ) 2006 - 2009 < > With many thanks to < > , it under the terms of the GNU General Public License as published by You should have received a copy of the GNU General Public License Foundation , Inc. , 675 Mass Ave , Cambridge , , USA . (define (script-fu-whitebalance image drawable mode amount intensmult satura) (define (floor x) (- x (fmod x 1))) Converts from linear to gamma - corrected sRGB [ 0,1 ] (define (togamma x) (if (<= x 0.00304) (* x 12.92) (let* ((exponent (/ 1 2.4))) (- (* 1.055 (pow x exponent)) 0.055) ) ) ) Converts from linear to gamma - corrected sRGB [ 0,255 ] (define (togamma255 x) (max (min (floor (* 256 (togamma x))) 255) 0) ) Converts from gamma - corrected sRGB [ 0,1 ] to linear (define (tolinear y) (if (<= y 0.0392768) (/ y 12.92) (let* ((ratio (/ (+ y 0.055) 1.055))) (pow ratio 2.4) ) ) ) Converts from gamma - corrected sRGB [ 0,255 ] to linear (define (to255linear y) (tolinear (/ y 255)) ) values are scaled 0 .. 255 . (define (lin-mult-in-gamma-space y255 r) (togamma255 (* r (to255linear y255))) ) (define (linemult y r) (max (min (floor (* y r)) 255) 0) ) (define (makegreyg r g b) (let* ((avg (/ (+ r (+ g b)) 3))) (list avg avg avg)) ) (define (makegrey r g b) (let* ((avg (+ (+ (* 0.2125 r) (* 0.7154 g)) (* 0.0721 b)))) (list avg avg avg)) ) (define (linearcols l) (let* ( (r (to255linear (car l))) (g (to255linear (cadr l))) (b (to255linear (caddr l))) ) (list r g b) ) ) (let* ( Foreground and background (fg (car (gimp-context-get-foreground))) (bg (car (gimp-context-get-background))) (a (/ amount 100)) Source colors , 0 .. 255 (sbr (car fg)) (sbg (cadr fg)) (sbb (caddr fg)) (sr (to255linear sbr)) (sg (to255linear sbg)) (sb (to255linear sbb)) (tcs (cond ((= mode 0) (makegrey sr sg sb)) ((= mode 1) (linearcols bg)))) (tr (car tcs)) (tg (cadr tcs)) (tb (caddr tcs)) (rra (if (= sbr 0) 1 (/ tr sr))) (rga (if (= sbg 0) 1 (/ tg sg))) (rba (if (= sbb 0) 1 (/ tb sb))) (rr (+ 1 (* a (- rra 1)))) (rg (+ 1 (* a (- rga 1)))) (rb (+ 1 (* a (- rba 1)))) Multiplies them by the intensity modification (m (/ intensmult 100)) And these are the real ratios , linear (rratio (* rr m)) (gratio (* rg m)) (bratio (* rb m)) (i 0) (num_bytes 256) (red-curve (cons-array num_bytes 'byte)) (green-curve (cons-array num_bytes 'byte)) (blue-curve (cons-array num_bytes 'byte)) ) (gimp-image-undo-group-start image) (while (< i num_bytes) (aset red-curve i (lin-mult-in-gamma-space i rratio)) (aset green-curve i (lin-mult-in-gamma-space i gratio)) (aset blue-curve i (lin-mult-in-gamma-space i bratio)) (set! i (+ i 1)) ) (gimp-curves-explicit drawable HISTOGRAM-RED num_bytes red-curve ) (gimp-curves-explicit drawable HISTOGRAM-GREEN num_bytes green-curve) (gimp-curves-explicit drawable HISTOGRAM-BLUE num_bytes blue-curve ) (gimp-hue-saturation drawable 0 0.0 0.0 satura) (gimp-image-undo-group-end image) (gimp-displays-flush) ) ) (script-fu-register "script-fu-whitebalance" "White balance Color Temperature" "Changes the color temperature. White Balance 2.1\nFor help, go to \nfile:whitebalance.scm" "Luca de Alfaro <>" "Luca de Alfaro" "2006-2008" "RGB*" SF-IMAGE "Image" 0 SF-DRAWABLE "Drawable" 0 SF-OPTION "Mode" '("Make foreground gray" "Convert foreground to background") SF-ADJUSTMENT _"Conversion amount (%)" '(100 0 100 1 10 0 0) SF-ADJUSTMENT _"New intensity (%)" '(100 0 200 1 10 0 0) SF-ADJUSTMENT _"Saturation change (%)" '(0 -100 100 1 10 0 0) ) (script-fu-menu-register "script-fu-whitebalance" "<Toolbox>/Script-Fu/Colors")
5323640bfe3187adad7677aafc00eafd5741770f90731586064c1954104f98ca
ghc/packages-Cabal
setup.test.hs
import Test.Cabal.Prelude import Control.Monad.IO.Class import Data.Maybe import System.Directory -- Test for 'build-type: Configure' example from the setup manual. main = setupTest $ do hasAutoreconf <- liftIO $ fmap isJust $ findExecutable "autoreconf" skipUnless hasAutoreconf _ <- shell "autoreconf" ["-i"] setup_build []
null
https://raw.githubusercontent.com/ghc/packages-Cabal/6f22f2a789fa23edb210a2591d74ea6a5f767872/cabal-testsuite/PackageTests/Configure/setup.test.hs
haskell
Test for 'build-type: Configure' example from the setup manual.
import Test.Cabal.Prelude import Control.Monad.IO.Class import Data.Maybe import System.Directory main = setupTest $ do hasAutoreconf <- liftIO $ fmap isJust $ findExecutable "autoreconf" skipUnless hasAutoreconf _ <- shell "autoreconf" ["-i"] setup_build []
68283621ce4b406ee9f62c3e844e0e91a56e5fa4ed377dde33710027665a1099
DanielG/kvm-in-a-box
JSON.hs
module JSON where import Data.Char import Data.List import Data.List.Split import Data.Aeson.TH GHC staging restriction gah .. jsonOpts = defaultOptions { fieldLabelModifier = uncamel . drop 1, constructorTagModifier = uncamel, allNullaryToStringTag = True } uncamel :: String -> String uncamel (s:ss) = if all ((==1) . length) $ splitOn "_" underscored then map toLower (s:ss) else underscored where underscored = concatMap f $ toLower s:ss f c = if isUpper c then ['_', toLower c] else [c]
null
https://raw.githubusercontent.com/DanielG/kvm-in-a-box/6bf71bb389a19806fac2f32a2c6d92261fb649e1/src/JSON.hs
haskell
module JSON where import Data.Char import Data.List import Data.List.Split import Data.Aeson.TH GHC staging restriction gah .. jsonOpts = defaultOptions { fieldLabelModifier = uncamel . drop 1, constructorTagModifier = uncamel, allNullaryToStringTag = True } uncamel :: String -> String uncamel (s:ss) = if all ((==1) . length) $ splitOn "_" underscored then map toLower (s:ss) else underscored where underscored = concatMap f $ toLower s:ss f c = if isUpper c then ['_', toLower c] else [c]
5099b960596f5d88733a62fcb2e6077e1d05ca8c8dbbe3293a9aa9f8baefc9b8
akshaymankar/jsonpath-hs
JSONPathSpec.hs
# LANGUAGE DeriveGeneric # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE RecordWildCards # # LANGUAGE TemplateHaskell # module Data.JSONPathSpec where import Control.Monad.IO.Class (liftIO) import Data.Aeson import Data.Aeson.Casing import Data.Aeson.TH import Data.Aeson.Text import Data.Bifunctor (Bifunctor (first)) import qualified Data.ByteString.Lazy as LBS import Data.Either import Data.FileEmbed import Data.JSONPath import Data.Text (Text, unpack) import qualified Data.Text.Lazy as LazyText import qualified Data.Vector as V import GHC.Generics import System.Timeout import Test.Hspec import Test.Hspec.Megaparsec import Text.Megaparsec data Test = Test { path :: Text, result :: Value } deriving (Eq, Show, Generic) data TestGroup = TestGroup { groupTitle :: Text, groupData :: Value, groupTests :: [Test] } deriving (Eq, Show, Generic) $(deriveJSON defaultOptions ''Test) $(deriveJSON (aesonPrefix snakeCase) ''TestGroup) spec :: Spec spec = let testFiles = map snd $(embedDir "test/resources/json-path-tests") testVals :: Either String [TestGroup] testVals = traverse (eitherDecode . LBS.fromStrict) testFiles in case testVals of Left e -> describe "JSONPath Tests" $ it "shouldn't fail to parse test files" $ expectationFailure ("failed to parse test files with error: \n" <> e) Right gs -> describe "JSONPath" $ do mapM_ group gs describe "Parser" $ do it "should parse basic things" $ do parse (jsonPathElement <* eof) "" ".foo" `shouldParse` KeyChild "foo" parse (jsonPath eof) "" "$.foo" `shouldParse` [KeyChild "foo"] parseJSONPath :: Text -> Either String [JSONPathElement] parseJSONPath = first errorBundlePretty . parse (jsonPath eof) "" group :: TestGroup -> Spec group TestGroup {..} = do describe (unpack groupTitle) $ mapM_ (test groupData) groupTests -- | 100 ms timeLimit :: Int timeLimit = 100000 test :: Value -> Test -> Spec test testData (Test path expected) = it (unpack path) $ do mResult <- liftIO $ timeout timeLimit $ do -- Using '$!' here ensures that the computation is strict, so this can -- be timed out properly pure $! do parsed <- parseJSONPath path Right $ executeJSONPath parsed testData result <- case mResult of Just r -> pure r Nothing -> do expectationFailure "JSONPath execution timed out" undefined case expected of Array a -> case result of Left e -> expectationFailure $ "Unexpected Left: " <> e TODO : Define order of result and make this ` shouldBe ` Right r -> r `shouldMatchList` V.toList a Bool False -> result `shouldSatisfy` isLeft v -> expectationFailure $ "Invalid result in test data " <> LazyText.unpack (encodeToLazyText v)
null
https://raw.githubusercontent.com/akshaymankar/jsonpath-hs/fa7719a62b14e88b3663b6920de16248c4c367b7/test/Data/JSONPathSpec.hs
haskell
# LANGUAGE OverloadedStrings # | 100 ms Using '$!' here ensures that the computation is strict, so this can be timed out properly
# LANGUAGE DeriveGeneric # # LANGUAGE RecordWildCards # # LANGUAGE TemplateHaskell # module Data.JSONPathSpec where import Control.Monad.IO.Class (liftIO) import Data.Aeson import Data.Aeson.Casing import Data.Aeson.TH import Data.Aeson.Text import Data.Bifunctor (Bifunctor (first)) import qualified Data.ByteString.Lazy as LBS import Data.Either import Data.FileEmbed import Data.JSONPath import Data.Text (Text, unpack) import qualified Data.Text.Lazy as LazyText import qualified Data.Vector as V import GHC.Generics import System.Timeout import Test.Hspec import Test.Hspec.Megaparsec import Text.Megaparsec data Test = Test { path :: Text, result :: Value } deriving (Eq, Show, Generic) data TestGroup = TestGroup { groupTitle :: Text, groupData :: Value, groupTests :: [Test] } deriving (Eq, Show, Generic) $(deriveJSON defaultOptions ''Test) $(deriveJSON (aesonPrefix snakeCase) ''TestGroup) spec :: Spec spec = let testFiles = map snd $(embedDir "test/resources/json-path-tests") testVals :: Either String [TestGroup] testVals = traverse (eitherDecode . LBS.fromStrict) testFiles in case testVals of Left e -> describe "JSONPath Tests" $ it "shouldn't fail to parse test files" $ expectationFailure ("failed to parse test files with error: \n" <> e) Right gs -> describe "JSONPath" $ do mapM_ group gs describe "Parser" $ do it "should parse basic things" $ do parse (jsonPathElement <* eof) "" ".foo" `shouldParse` KeyChild "foo" parse (jsonPath eof) "" "$.foo" `shouldParse` [KeyChild "foo"] parseJSONPath :: Text -> Either String [JSONPathElement] parseJSONPath = first errorBundlePretty . parse (jsonPath eof) "" group :: TestGroup -> Spec group TestGroup {..} = do describe (unpack groupTitle) $ mapM_ (test groupData) groupTests timeLimit :: Int timeLimit = 100000 test :: Value -> Test -> Spec test testData (Test path expected) = it (unpack path) $ do mResult <- liftIO $ timeout timeLimit $ do pure $! do parsed <- parseJSONPath path Right $ executeJSONPath parsed testData result <- case mResult of Just r -> pure r Nothing -> do expectationFailure "JSONPath execution timed out" undefined case expected of Array a -> case result of Left e -> expectationFailure $ "Unexpected Left: " <> e TODO : Define order of result and make this ` shouldBe ` Right r -> r `shouldMatchList` V.toList a Bool False -> result `shouldSatisfy` isLeft v -> expectationFailure $ "Invalid result in test data " <> LazyText.unpack (encodeToLazyText v)
ba641636c2ad11c095ba71392435c03d43a0bb0664a30b44cdef9bdb3ccde745
Andromedans/andromeda
context.ml
(** Context with hints. *) type hint = int * Pattern.ty * Pattern.term * Pattern.term type entry = | Variable of Syntax.ty | Definition of Syntax.ty * Syntax.term | Equation of hint | Rewrite of hint type t = { decls : entry list ; names : Syntax.name list } let print ?(label="") {decls=ds; names=xs} = let rec print_names ds xs = match ds, xs with | [], [] -> () | (Variable t :: ds), x::xs -> print_names ds xs ; Format.printf "@[<hov 4>assume %s@;<1 -2>: %t@]@\n" x (Print.ty xs t) | (Definition (t, e) :: ds), x :: xs -> print_names ds xs ; Format.printf "@[<hov 4>define %s@;<1 -2>: %t@;<1 -2>:= %t@]@\n" x (Print.ty xs t) (Print.term xs e) | (Equation _ :: ds), xs -> print_names ds xs ; Format.printf "@[<hov 4>equation <pattern>@]@\n" | (Rewrite _ :: ds), xs -> print_names ds xs ; Format.printf "@[<hov 4>rewrite <pattern>@]@\n" | [], _::_ -> Error.impossible "fewer declarations than names in context" | _::_, [] -> Error.impossible "fewer names than declarations in context" in Format.printf "------%s---@." label; print_names ds xs ; Format.printf "---END%s---@." label let empty = { decls = [] ; names = [] } let names {names=lst} = lst let add_var x t ctx = { decls = Variable t :: ctx.decls ; names = x :: ctx.names } let add_vars bnds ctx = let rec loop vars_added accum_ctx = function | [] -> accum_ctx | (x,t)::rest -> loop (vars_added+1) (add_var x (Syntax.shift_ty vars_added t) accum_ctx) rest in loop 0 ctx bnds let pop_var ctx = { decls = List.tl ctx.decls; names = List.tl ctx.names; } let rec pop_vars n ctx = match n with | 0 -> ctx | n -> pop_vars (n-1) (pop_var ctx) let for_J t x y p z ctx = let ctx_xy = add_vars [(x, t); (y, t)] ctx in let ctx_xyp = add_var p (Syntax.Paths (Syntax.shift_ty 2 t, (* Weaken twice for x and y *) (Syntax.Var 1 (* x *), Position.nowhere), (Syntax.Var 0 (* y *), Position.nowhere)), Position.nowhere) ctx_xy and ctx_z = add_var z t ctx in ctx_xyp, ctx_z let add_def x t e ctx = { decls = Definition (t, e) :: ctx.decls ; names = x :: ctx.names } let add_equation h ctx = { decls = Equation h :: ctx.decls ; names = ctx.names } let add_rewrite h ctx = { decls = Rewrite h :: ctx.decls ; names = ctx.names } let lookup_var index {decls=ds} = let rec lookup k = function | [] -> Error.impossible "invalid de Bruijn index" | (Equation _ | Rewrite _) :: ds -> lookup k ds | (Variable t | Definition (t, _)) :: ds -> if k = 0 then Syntax.shift_ty (index+1) t else lookup (k-1) ds in if index < 0 then Error.impossible "negative de Bruijn index" ; lookup index ds let lookup_def index {decls=ds} = let rec lookup k = function | [] -> Error.impossible "invalid de Bruijn index" | (Equation _ | Rewrite _) :: ds -> lookup k ds | Variable _ :: ds -> if k = 0 then None else lookup (k-1) ds | Definition (_, e) :: ds -> if k = 0 then Some (Syntax.shift (index+1) e) else lookup (k-1) ds in if index < 0 then Error.impossible "negative de Bruijn index" ; lookup index ds let equations {decls=lst} = let rec collect k = function | [] -> [] | (Variable _ | Definition _) :: lst -> collect (k+1) lst | Rewrite _ :: lst -> collect k lst | Equation (j, pt, pe1, pe2) :: lst -> let pt = Pattern.shift_ty k 0 pt and pe1 = Pattern.shift k 0 pe1 and pe2 = Pattern.shift k 0 pe2 in (j, pt, pe1, pe2) :: (collect k lst) in collect 0 lst let rewrites {decls=lst} = let rec collect k = function | [] -> [] | (Variable _ | Definition _) :: lst -> collect (k+1) lst | Equation _ :: lst -> collect k lst | Rewrite (j, pt, pe1, pe2) :: lst -> let pt = Pattern.shift_ty k 0 pt and pe1 = Pattern.shift k 0 pe1 and pe2 = Pattern.shift k 0 pe2 in (j, pt, pe1, pe2) :: (collect k lst) in collect 0 lst let append ctx1 ctx2 = { (* "backwards" because the contexts are stored backwards, * with the newest variable at the front of the list. *) decls = ctx2.decls @ ctx1.decls; names = ctx2.names @ ctx1.names; }
null
https://raw.githubusercontent.com/Andromedans/andromeda/a5c678450e6c6d4a7cd5eee1196bde558541b994/archive/old-andromeda/context.ml
ocaml
* Context with hints. Weaken twice for x and y x y "backwards" because the contexts are stored backwards, * with the newest variable at the front of the list.
type hint = int * Pattern.ty * Pattern.term * Pattern.term type entry = | Variable of Syntax.ty | Definition of Syntax.ty * Syntax.term | Equation of hint | Rewrite of hint type t = { decls : entry list ; names : Syntax.name list } let print ?(label="") {decls=ds; names=xs} = let rec print_names ds xs = match ds, xs with | [], [] -> () | (Variable t :: ds), x::xs -> print_names ds xs ; Format.printf "@[<hov 4>assume %s@;<1 -2>: %t@]@\n" x (Print.ty xs t) | (Definition (t, e) :: ds), x :: xs -> print_names ds xs ; Format.printf "@[<hov 4>define %s@;<1 -2>: %t@;<1 -2>:= %t@]@\n" x (Print.ty xs t) (Print.term xs e) | (Equation _ :: ds), xs -> print_names ds xs ; Format.printf "@[<hov 4>equation <pattern>@]@\n" | (Rewrite _ :: ds), xs -> print_names ds xs ; Format.printf "@[<hov 4>rewrite <pattern>@]@\n" | [], _::_ -> Error.impossible "fewer declarations than names in context" | _::_, [] -> Error.impossible "fewer names than declarations in context" in Format.printf "------%s---@." label; print_names ds xs ; Format.printf "---END%s---@." label let empty = { decls = [] ; names = [] } let names {names=lst} = lst let add_var x t ctx = { decls = Variable t :: ctx.decls ; names = x :: ctx.names } let add_vars bnds ctx = let rec loop vars_added accum_ctx = function | [] -> accum_ctx | (x,t)::rest -> loop (vars_added+1) (add_var x (Syntax.shift_ty vars_added t) accum_ctx) rest in loop 0 ctx bnds let pop_var ctx = { decls = List.tl ctx.decls; names = List.tl ctx.names; } let rec pop_vars n ctx = match n with | 0 -> ctx | n -> pop_vars (n-1) (pop_var ctx) let for_J t x y p z ctx = let ctx_xy = add_vars [(x, t); (y, t)] ctx in let ctx_xyp = add_var p (Syntax.Paths Position.nowhere) ctx_xy and ctx_z = add_var z t ctx in ctx_xyp, ctx_z let add_def x t e ctx = { decls = Definition (t, e) :: ctx.decls ; names = x :: ctx.names } let add_equation h ctx = { decls = Equation h :: ctx.decls ; names = ctx.names } let add_rewrite h ctx = { decls = Rewrite h :: ctx.decls ; names = ctx.names } let lookup_var index {decls=ds} = let rec lookup k = function | [] -> Error.impossible "invalid de Bruijn index" | (Equation _ | Rewrite _) :: ds -> lookup k ds | (Variable t | Definition (t, _)) :: ds -> if k = 0 then Syntax.shift_ty (index+1) t else lookup (k-1) ds in if index < 0 then Error.impossible "negative de Bruijn index" ; lookup index ds let lookup_def index {decls=ds} = let rec lookup k = function | [] -> Error.impossible "invalid de Bruijn index" | (Equation _ | Rewrite _) :: ds -> lookup k ds | Variable _ :: ds -> if k = 0 then None else lookup (k-1) ds | Definition (_, e) :: ds -> if k = 0 then Some (Syntax.shift (index+1) e) else lookup (k-1) ds in if index < 0 then Error.impossible "negative de Bruijn index" ; lookup index ds let equations {decls=lst} = let rec collect k = function | [] -> [] | (Variable _ | Definition _) :: lst -> collect (k+1) lst | Rewrite _ :: lst -> collect k lst | Equation (j, pt, pe1, pe2) :: lst -> let pt = Pattern.shift_ty k 0 pt and pe1 = Pattern.shift k 0 pe1 and pe2 = Pattern.shift k 0 pe2 in (j, pt, pe1, pe2) :: (collect k lst) in collect 0 lst let rewrites {decls=lst} = let rec collect k = function | [] -> [] | (Variable _ | Definition _) :: lst -> collect (k+1) lst | Equation _ :: lst -> collect k lst | Rewrite (j, pt, pe1, pe2) :: lst -> let pt = Pattern.shift_ty k 0 pt and pe1 = Pattern.shift k 0 pe1 and pe2 = Pattern.shift k 0 pe2 in (j, pt, pe1, pe2) :: (collect k lst) in collect 0 lst let append ctx1 ctx2 = { decls = ctx2.decls @ ctx1.decls; names = ctx2.names @ ctx1.names; }
f99591ed31cef31ede45916f1402a2064d2e7d5c8d491f3064180d1956847376
binaryage/chromex
idle.clj
(ns chromex.app.idle "Use the chrome.idle API to detect when the machine's idle state changes. * available since Chrome 36 * " (:refer-clojure :only [defmacro defn apply declare meta let partial]) (:require [chromex.wrapgen :refer [gen-wrap-helper]] [chromex.callgen :refer [gen-call-helper gen-tap-all-events-call]])) (declare api-table) (declare gen-call) -- functions -------------------------------------------------------------------------------------------------------------- (defmacro query-state "Returns 'locked' if the system is locked, 'idle' if the user has not generated any input for a specified number of seconds, or 'active' otherwise. |detection-interval-in-seconds| - The system is considered idle if detectionIntervalInSeconds seconds have elapsed since the last user input detected. This function returns a core.async channel of type `promise-chan` which eventually receives a result value. Signature of the result value put on the channel is [new-state] where: |new-state| - #property-callback-newState. In case of an error the channel closes without receiving any value and relevant error object can be obtained via chromex.error/get-last-error. #method-queryState." ([detection-interval-in-seconds] (gen-call :function ::query-state &form detection-interval-in-seconds))) (defmacro set-detection-interval "Sets the interval, in seconds, used to determine when the system is in an idle state for onStateChanged events. The default interval is 60 seconds. |interval-in-seconds| - Threshold, in seconds, used to determine when the system is in an idle state. #method-setDetectionInterval." ([interval-in-seconds] (gen-call :function ::set-detection-interval &form interval-in-seconds))) (defmacro get-auto-lock-delay "Gets the time, in seconds, it takes until the screen is locked automatically while idle. Returns a zero duration if the screen is never locked automatically. Currently supported on Chrome OS only. This function returns a core.async channel of type `promise-chan` which eventually receives a result value. Signature of the result value put on the channel is [delay] where: |delay| - Time, in seconds, until the screen is locked automatically while idle. This is zero if the screen never locks automatically. In case of an error the channel closes without receiving any value and relevant error object can be obtained via chromex.error/get-last-error. #method-getAutoLockDelay." ([] (gen-call :function ::get-auto-lock-delay &form))) ; -- events ----------------------------------------------------------------------------------------------------------------- ; ; docs: /#tapping-events (defmacro tap-on-state-changed-events "Fired when the system changes to an active, idle or locked state. The event fires with 'locked' if the screen is locked or the screensaver activates, 'idle' if the system is unlocked and the user has not generated any input for a specified number of seconds, and 'active' when the user generates input on an idle system. Events will be put on the |channel| with signature [::on-state-changed [new-state]] where: |new-state| - #property-onStateChanged-newState. Note: |args| will be passed as additional parameters into Chrome event's .addListener call. #event-onStateChanged." ([channel & args] (apply gen-call :event ::on-state-changed &form channel args))) ; -- convenience ------------------------------------------------------------------------------------------------------------ (defmacro tap-all-events "Taps all valid non-deprecated events in chromex.app.idle namespace." [chan] (gen-tap-all-events-call api-table (meta &form) chan)) ; --------------------------------------------------------------------------------------------------------------------------- ; -- API TABLE -------------------------------------------------------------------------------------------------------------- ; --------------------------------------------------------------------------------------------------------------------------- (def api-table {:namespace "chrome.idle", :since "36", :functions [{:id ::query-state, :name "queryState", :callback? true, :params [{:name "detection-interval-in-seconds", :type "integer"} {:name "callback", :type :callback, :callback {:params [{:name "new-state", :type "idle.IdleState"}]}}]} {:id ::set-detection-interval, :name "setDetectionInterval", :params [{:name "interval-in-seconds", :type "integer"}]} {:id ::get-auto-lock-delay, :name "getAutoLockDelay", :since "73", :callback? true, :params [{:name "callback", :type :callback, :callback {:params [{:name "delay", :type "integer"}]}}]}], :events [{:id ::on-state-changed, :name "onStateChanged", :params [{:name "new-state", :type "idle.IdleState"}]}]}) ; -- helpers ---------------------------------------------------------------------------------------------------------------- ; code generation for native API wrapper (defmacro gen-wrap [kind item-id config & args] (apply gen-wrap-helper api-table kind item-id config args)) ; code generation for API call-site (def gen-call (partial gen-call-helper api-table))
null
https://raw.githubusercontent.com/binaryage/chromex/33834ba5dd4f4238a3c51f99caa0416f30c308c5/src/apps/chromex/app/idle.clj
clojure
-- events ----------------------------------------------------------------------------------------------------------------- docs: /#tapping-events -- convenience ------------------------------------------------------------------------------------------------------------ --------------------------------------------------------------------------------------------------------------------------- -- API TABLE -------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------------------- -- helpers ---------------------------------------------------------------------------------------------------------------- code generation for native API wrapper code generation for API call-site
(ns chromex.app.idle "Use the chrome.idle API to detect when the machine's idle state changes. * available since Chrome 36 * " (:refer-clojure :only [defmacro defn apply declare meta let partial]) (:require [chromex.wrapgen :refer [gen-wrap-helper]] [chromex.callgen :refer [gen-call-helper gen-tap-all-events-call]])) (declare api-table) (declare gen-call) -- functions -------------------------------------------------------------------------------------------------------------- (defmacro query-state "Returns 'locked' if the system is locked, 'idle' if the user has not generated any input for a specified number of seconds, or 'active' otherwise. |detection-interval-in-seconds| - The system is considered idle if detectionIntervalInSeconds seconds have elapsed since the last user input detected. This function returns a core.async channel of type `promise-chan` which eventually receives a result value. Signature of the result value put on the channel is [new-state] where: |new-state| - #property-callback-newState. In case of an error the channel closes without receiving any value and relevant error object can be obtained via chromex.error/get-last-error. #method-queryState." ([detection-interval-in-seconds] (gen-call :function ::query-state &form detection-interval-in-seconds))) (defmacro set-detection-interval "Sets the interval, in seconds, used to determine when the system is in an idle state for onStateChanged events. The default interval is 60 seconds. |interval-in-seconds| - Threshold, in seconds, used to determine when the system is in an idle state. #method-setDetectionInterval." ([interval-in-seconds] (gen-call :function ::set-detection-interval &form interval-in-seconds))) (defmacro get-auto-lock-delay "Gets the time, in seconds, it takes until the screen is locked automatically while idle. Returns a zero duration if the screen is never locked automatically. Currently supported on Chrome OS only. This function returns a core.async channel of type `promise-chan` which eventually receives a result value. Signature of the result value put on the channel is [delay] where: |delay| - Time, in seconds, until the screen is locked automatically while idle. This is zero if the screen never locks automatically. In case of an error the channel closes without receiving any value and relevant error object can be obtained via chromex.error/get-last-error. #method-getAutoLockDelay." ([] (gen-call :function ::get-auto-lock-delay &form))) (defmacro tap-on-state-changed-events "Fired when the system changes to an active, idle or locked state. The event fires with 'locked' if the screen is locked or the screensaver activates, 'idle' if the system is unlocked and the user has not generated any input for a specified number of seconds, and 'active' when the user generates input on an idle system. Events will be put on the |channel| with signature [::on-state-changed [new-state]] where: |new-state| - #property-onStateChanged-newState. Note: |args| will be passed as additional parameters into Chrome event's .addListener call. #event-onStateChanged." ([channel & args] (apply gen-call :event ::on-state-changed &form channel args))) (defmacro tap-all-events "Taps all valid non-deprecated events in chromex.app.idle namespace." [chan] (gen-tap-all-events-call api-table (meta &form) chan)) (def api-table {:namespace "chrome.idle", :since "36", :functions [{:id ::query-state, :name "queryState", :callback? true, :params [{:name "detection-interval-in-seconds", :type "integer"} {:name "callback", :type :callback, :callback {:params [{:name "new-state", :type "idle.IdleState"}]}}]} {:id ::set-detection-interval, :name "setDetectionInterval", :params [{:name "interval-in-seconds", :type "integer"}]} {:id ::get-auto-lock-delay, :name "getAutoLockDelay", :since "73", :callback? true, :params [{:name "callback", :type :callback, :callback {:params [{:name "delay", :type "integer"}]}}]}], :events [{:id ::on-state-changed, :name "onStateChanged", :params [{:name "new-state", :type "idle.IdleState"}]}]}) (defmacro gen-wrap [kind item-id config & args] (apply gen-wrap-helper api-table kind item-id config args)) (def gen-call (partial gen-call-helper api-table))
33f435c50e62312721a914fec17965fd51501e1f211b09559d1abcbb57a803ff
haskell-opengl/OpenGLRaw
MeshShader.hs
# LANGUAGE PatternSynonyms # -------------------------------------------------------------------------------- -- | -- Module : Graphics.GL.NV.MeshShader Copyright : ( c ) 2019 -- License : BSD3 -- Maintainer : < > -- Stability : stable -- Portability : portable -- -------------------------------------------------------------------------------- module Graphics.GL.NV.MeshShader ( -- * Extension Support glGetNVMeshShader, gl_NV_mesh_shader, -- * Enums pattern GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_MESH_SHADER_NV, pattern GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_TASK_SHADER_NV, pattern GL_MAX_COMBINED_MESH_UNIFORM_COMPONENTS_NV, pattern GL_MAX_COMBINED_TASK_UNIFORM_COMPONENTS_NV, pattern GL_MAX_DRAW_MESH_TASKS_COUNT_NV, pattern GL_MAX_MESH_ATOMIC_COUNTERS_NV, pattern GL_MAX_MESH_ATOMIC_COUNTER_BUFFERS_NV, pattern GL_MAX_MESH_IMAGE_UNIFORMS_NV, pattern GL_MAX_MESH_OUTPUT_PRIMITIVES_NV, pattern GL_MAX_MESH_OUTPUT_VERTICES_NV, pattern GL_MAX_MESH_SHADER_STORAGE_BLOCKS_NV, pattern GL_MAX_MESH_TEXTURE_IMAGE_UNITS_NV, pattern GL_MAX_MESH_TOTAL_MEMORY_SIZE_NV, pattern GL_MAX_MESH_UNIFORM_BLOCKS_NV, pattern GL_MAX_MESH_UNIFORM_COMPONENTS_NV, pattern GL_MAX_MESH_VIEWS_NV, pattern GL_MAX_MESH_WORK_GROUP_INVOCATIONS_NV, pattern GL_MAX_MESH_WORK_GROUP_SIZE_NV, pattern GL_MAX_TASK_ATOMIC_COUNTERS_NV, pattern GL_MAX_TASK_ATOMIC_COUNTER_BUFFERS_NV, pattern GL_MAX_TASK_IMAGE_UNIFORMS_NV, pattern GL_MAX_TASK_OUTPUT_COUNT_NV, pattern GL_MAX_TASK_SHADER_STORAGE_BLOCKS_NV, pattern GL_MAX_TASK_TEXTURE_IMAGE_UNITS_NV, pattern GL_MAX_TASK_TOTAL_MEMORY_SIZE_NV, pattern GL_MAX_TASK_UNIFORM_BLOCKS_NV, pattern GL_MAX_TASK_UNIFORM_COMPONENTS_NV, pattern GL_MAX_TASK_WORK_GROUP_INVOCATIONS_NV, pattern GL_MAX_TASK_WORK_GROUP_SIZE_NV, pattern GL_MESH_OUTPUT_PER_PRIMITIVE_GRANULARITY_NV, pattern GL_MESH_OUTPUT_PER_VERTEX_GRANULARITY_NV, pattern GL_MESH_OUTPUT_TYPE_NV, pattern GL_MESH_PRIMITIVES_OUT_NV, pattern GL_MESH_SHADER_BIT_NV, pattern GL_MESH_SHADER_NV, pattern GL_MESH_SUBROUTINE_NV, pattern GL_MESH_SUBROUTINE_UNIFORM_NV, pattern GL_MESH_VERTICES_OUT_NV, pattern GL_MESH_WORK_GROUP_SIZE_NV, pattern GL_REFERENCED_BY_MESH_SHADER_NV, pattern GL_REFERENCED_BY_TASK_SHADER_NV, pattern GL_TASK_SHADER_BIT_NV, pattern GL_TASK_SHADER_NV, pattern GL_TASK_SUBROUTINE_NV, pattern GL_TASK_SUBROUTINE_UNIFORM_NV, pattern GL_TASK_WORK_GROUP_SIZE_NV, pattern GL_UNIFORM_BLOCK_REFERENCED_BY_MESH_SHADER_NV, pattern GL_UNIFORM_BLOCK_REFERENCED_BY_TASK_SHADER_NV, -- * Functions glDrawMeshTasksIndirectNV, glDrawMeshTasksNV, glMultiDrawMeshTasksIndirectCountNV, glMultiDrawMeshTasksIndirectNV ) where import Graphics.GL.ExtensionPredicates import Graphics.GL.Tokens import Graphics.GL.Functions
null
https://raw.githubusercontent.com/haskell-opengl/OpenGLRaw/57e50c9d28dfa62d6a87ae9b561af28f64ce32a0/src/Graphics/GL/NV/MeshShader.hs
haskell
------------------------------------------------------------------------------ | Module : Graphics.GL.NV.MeshShader License : BSD3 Stability : stable Portability : portable ------------------------------------------------------------------------------ * Extension Support * Enums * Functions
# LANGUAGE PatternSynonyms # Copyright : ( c ) 2019 Maintainer : < > module Graphics.GL.NV.MeshShader ( glGetNVMeshShader, gl_NV_mesh_shader, pattern GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_MESH_SHADER_NV, pattern GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_TASK_SHADER_NV, pattern GL_MAX_COMBINED_MESH_UNIFORM_COMPONENTS_NV, pattern GL_MAX_COMBINED_TASK_UNIFORM_COMPONENTS_NV, pattern GL_MAX_DRAW_MESH_TASKS_COUNT_NV, pattern GL_MAX_MESH_ATOMIC_COUNTERS_NV, pattern GL_MAX_MESH_ATOMIC_COUNTER_BUFFERS_NV, pattern GL_MAX_MESH_IMAGE_UNIFORMS_NV, pattern GL_MAX_MESH_OUTPUT_PRIMITIVES_NV, pattern GL_MAX_MESH_OUTPUT_VERTICES_NV, pattern GL_MAX_MESH_SHADER_STORAGE_BLOCKS_NV, pattern GL_MAX_MESH_TEXTURE_IMAGE_UNITS_NV, pattern GL_MAX_MESH_TOTAL_MEMORY_SIZE_NV, pattern GL_MAX_MESH_UNIFORM_BLOCKS_NV, pattern GL_MAX_MESH_UNIFORM_COMPONENTS_NV, pattern GL_MAX_MESH_VIEWS_NV, pattern GL_MAX_MESH_WORK_GROUP_INVOCATIONS_NV, pattern GL_MAX_MESH_WORK_GROUP_SIZE_NV, pattern GL_MAX_TASK_ATOMIC_COUNTERS_NV, pattern GL_MAX_TASK_ATOMIC_COUNTER_BUFFERS_NV, pattern GL_MAX_TASK_IMAGE_UNIFORMS_NV, pattern GL_MAX_TASK_OUTPUT_COUNT_NV, pattern GL_MAX_TASK_SHADER_STORAGE_BLOCKS_NV, pattern GL_MAX_TASK_TEXTURE_IMAGE_UNITS_NV, pattern GL_MAX_TASK_TOTAL_MEMORY_SIZE_NV, pattern GL_MAX_TASK_UNIFORM_BLOCKS_NV, pattern GL_MAX_TASK_UNIFORM_COMPONENTS_NV, pattern GL_MAX_TASK_WORK_GROUP_INVOCATIONS_NV, pattern GL_MAX_TASK_WORK_GROUP_SIZE_NV, pattern GL_MESH_OUTPUT_PER_PRIMITIVE_GRANULARITY_NV, pattern GL_MESH_OUTPUT_PER_VERTEX_GRANULARITY_NV, pattern GL_MESH_OUTPUT_TYPE_NV, pattern GL_MESH_PRIMITIVES_OUT_NV, pattern GL_MESH_SHADER_BIT_NV, pattern GL_MESH_SHADER_NV, pattern GL_MESH_SUBROUTINE_NV, pattern GL_MESH_SUBROUTINE_UNIFORM_NV, pattern GL_MESH_VERTICES_OUT_NV, pattern GL_MESH_WORK_GROUP_SIZE_NV, pattern GL_REFERENCED_BY_MESH_SHADER_NV, pattern GL_REFERENCED_BY_TASK_SHADER_NV, pattern GL_TASK_SHADER_BIT_NV, pattern GL_TASK_SHADER_NV, pattern GL_TASK_SUBROUTINE_NV, pattern GL_TASK_SUBROUTINE_UNIFORM_NV, pattern GL_TASK_WORK_GROUP_SIZE_NV, pattern GL_UNIFORM_BLOCK_REFERENCED_BY_MESH_SHADER_NV, pattern GL_UNIFORM_BLOCK_REFERENCED_BY_TASK_SHADER_NV, glDrawMeshTasksIndirectNV, glDrawMeshTasksNV, glMultiDrawMeshTasksIndirectCountNV, glMultiDrawMeshTasksIndirectNV ) where import Graphics.GL.ExtensionPredicates import Graphics.GL.Tokens import Graphics.GL.Functions
e6d66884f1ef9ea1ef75faf733618185f9be33900c61f663ad21f6838e1ee2c7
kit-ty-kate/visitors
VisitorsList.ml
let stdlib_compare = compare open List (* [last xs] returns the last element of the nonempty list [xs]. *) let rec last1 x xs = match xs with | [] -> x | x :: xs -> last1 x xs let last xs = match xs with | [] -> assert false | x :: xs -> last1 x xs (* [interval i j] constructs a list representation of the semi-open interval [i..j). *) let rec interval i j : int list = if i < j then i :: interval (i + 1) j else [] (* [init i j f] constructs a list of the values [f i] up to [f (j - 1)]. *) let init i j (f : int -> 'a) : 'a list = map f (interval i j) [ is_matrix m n xss ] checks that [ xss ] is an [ ] matrix , represented as a list of lists . as a list of lists. *) let is_matrix m n (xss : _ list list) = length xss = m && for_all (fun xs -> length xs = n) xss [ transpose n xss ] transposes a matrix , represented as a list of lists . The parameter [ n ] is the width of the matrix , and is really useful only in the case where the matrix has zero height , in which case [ transpose ] constructs a matrix of height [ n ] and zero width . The parameter [n] is the width of the matrix, and is really useful only in the case where the matrix has zero height, in which case [transpose] constructs a matrix of height [n] and zero width. *) let transpose (n : int) (xss : 'a list list) : 'a list list = let m = length xss in assert (is_matrix m n xss); (* Convert [xss] to an array, for speed. *) let xss : 'a array array = Array.(map of_list (of_list xss)) in We have an [ ] matrix , and construct an [ n]-by-[m ] matrix . init 0 n (fun j -> init 0 m (fun i -> xss.(i).(j) ) ) (* [hextend xs n f] extends the vertical vector [xs] to a matrix of width [n]. A vector element [x] is turned into [f j x] in the [j]-th row. *) let hextend (xs : 'a list) (n : int) (f : int -> 'a -> 'a) : 'a list list = map (fun x -> init 0 n (fun j -> f j x)) xs (* [uniq cmp xs] assumes that the list [xs] is sorted according to the ordering [cmp] and returns the list [xs] deprived of any duplicate elements. *) let rec uniq1 cmp x ys = match ys with | [] -> [] | y :: ys -> if cmp x y = 0 then uniq1 stdlib_compare x ys else y :: uniq1 cmp y ys let uniq cmp xs = match xs with | [] -> [] | x :: xs -> x :: uniq1 cmp x xs (* [weed cmp xs] returns the list [xs] deprived of any duplicate elements. *) let weed cmp xs = uniq cmp (List.sort cmp xs) (* [fold_right1] is like [fold_right], but uses the last element of the list (if the list is nonempty) as the initial accumulator, saving one call to the binary operation [f]. This is equivalent to [fold_right] if [accu] is a right unit for [f]. *) let fold_right1 f xs accu = match List.rev xs with | [] -> accu | x :: xs -> let xs = List.rev xs in (* We have decomposed [xs] as [xs] followed with [x]. We can now ignore [accu] and use [x] as the initial accumulator in our right-to-left sweep of the list. *) List.fold_right f xs x [ fold_left1 ] is like [ fold_left ] , but uses the first element of the list ( if the list is nonempty ) as the initial accumulator , saving one call to the binary operation [ f ] . This is equivalent to [ fold_left ] if [ accu ] is a left unit for [ f ] . (if the list is nonempty) as the initial accumulator, saving one call to the binary operation [f]. This is equivalent to [fold_left] if [accu] is a left unit for [f]. *) let fold_left1 f accu xs = match xs with | [] -> accu | x :: xs -> (* We can ignore [accu] and use [x] as the initial accumulator in our left-to-right sweep of the list. *) List.fold_left f x xs (* [filter2 f xs ys] returns the list of elements [y] in [ys] such that the corresponding element [x] in [xs] satisfies [f]. *) let filter2 f xs ys = assert (length xs = length ys); map snd (filter (fun (x, _y) -> f x) (combine xs ys))
null
https://raw.githubusercontent.com/kit-ty-kate/visitors/fc53cc486178781e0b1e581eced98e07facb7d29/src/VisitorsList.ml
ocaml
[last xs] returns the last element of the nonempty list [xs]. [interval i j] constructs a list representation of the semi-open interval [i..j). [init i j f] constructs a list of the values [f i] up to [f (j - 1)]. Convert [xss] to an array, for speed. [hextend xs n f] extends the vertical vector [xs] to a matrix of width [n]. A vector element [x] is turned into [f j x] in the [j]-th row. [uniq cmp xs] assumes that the list [xs] is sorted according to the ordering [cmp] and returns the list [xs] deprived of any duplicate elements. [weed cmp xs] returns the list [xs] deprived of any duplicate elements. [fold_right1] is like [fold_right], but uses the last element of the list (if the list is nonempty) as the initial accumulator, saving one call to the binary operation [f]. This is equivalent to [fold_right] if [accu] is a right unit for [f]. We have decomposed [xs] as [xs] followed with [x]. We can now ignore [accu] and use [x] as the initial accumulator in our right-to-left sweep of the list. We can ignore [accu] and use [x] as the initial accumulator in our left-to-right sweep of the list. [filter2 f xs ys] returns the list of elements [y] in [ys] such that the corresponding element [x] in [xs] satisfies [f].
let stdlib_compare = compare open List let rec last1 x xs = match xs with | [] -> x | x :: xs -> last1 x xs let last xs = match xs with | [] -> assert false | x :: xs -> last1 x xs let rec interval i j : int list = if i < j then i :: interval (i + 1) j else [] let init i j (f : int -> 'a) : 'a list = map f (interval i j) [ is_matrix m n xss ] checks that [ xss ] is an [ ] matrix , represented as a list of lists . as a list of lists. *) let is_matrix m n (xss : _ list list) = length xss = m && for_all (fun xs -> length xs = n) xss [ transpose n xss ] transposes a matrix , represented as a list of lists . The parameter [ n ] is the width of the matrix , and is really useful only in the case where the matrix has zero height , in which case [ transpose ] constructs a matrix of height [ n ] and zero width . The parameter [n] is the width of the matrix, and is really useful only in the case where the matrix has zero height, in which case [transpose] constructs a matrix of height [n] and zero width. *) let transpose (n : int) (xss : 'a list list) : 'a list list = let m = length xss in assert (is_matrix m n xss); let xss : 'a array array = Array.(map of_list (of_list xss)) in We have an [ ] matrix , and construct an [ n]-by-[m ] matrix . init 0 n (fun j -> init 0 m (fun i -> xss.(i).(j) ) ) let hextend (xs : 'a list) (n : int) (f : int -> 'a -> 'a) : 'a list list = map (fun x -> init 0 n (fun j -> f j x)) xs let rec uniq1 cmp x ys = match ys with | [] -> [] | y :: ys -> if cmp x y = 0 then uniq1 stdlib_compare x ys else y :: uniq1 cmp y ys let uniq cmp xs = match xs with | [] -> [] | x :: xs -> x :: uniq1 cmp x xs let weed cmp xs = uniq cmp (List.sort cmp xs) let fold_right1 f xs accu = match List.rev xs with | [] -> accu | x :: xs -> let xs = List.rev xs in List.fold_right f xs x [ fold_left1 ] is like [ fold_left ] , but uses the first element of the list ( if the list is nonempty ) as the initial accumulator , saving one call to the binary operation [ f ] . This is equivalent to [ fold_left ] if [ accu ] is a left unit for [ f ] . (if the list is nonempty) as the initial accumulator, saving one call to the binary operation [f]. This is equivalent to [fold_left] if [accu] is a left unit for [f]. *) let fold_left1 f accu xs = match xs with | [] -> accu | x :: xs -> List.fold_left f x xs let filter2 f xs ys = assert (length xs = length ys); map snd (filter (fun (x, _y) -> f x) (combine xs ys))
5fec1858840b5a64232952157c4097649e8986b060903a63593c3a27f526bae8
Haskell-OpenAPI-Code-Generator/Stripe-Haskell-Library
RadarReviewResourceSession.hs
{-# LANGUAGE MultiWayIf #-} CHANGE WITH CAUTION : This is a generated code file generated by -OpenAPI-Code-Generator/Haskell-OpenAPI-Client-Code-Generator . {-# LANGUAGE OverloadedStrings #-} -- | Contains the types generated from the schema RadarReviewResourceSession module StripeAPI.Types.RadarReviewResourceSession where import qualified Control.Monad.Fail import qualified Data.Aeson import qualified Data.Aeson as Data.Aeson.Encoding.Internal import qualified Data.Aeson as Data.Aeson.Types import qualified Data.Aeson as Data.Aeson.Types.FromJSON import qualified Data.Aeson as Data.Aeson.Types.Internal import qualified Data.Aeson as Data.Aeson.Types.ToJSON import qualified Data.ByteString.Char8 import qualified Data.ByteString.Char8 as Data.ByteString.Internal import qualified Data.Foldable import qualified Data.Functor import qualified Data.Maybe import qualified Data.Scientific import qualified Data.Text import qualified Data.Text.Internal import qualified Data.Time.Calendar as Data.Time.Calendar.Days import qualified Data.Time.LocalTime as Data.Time.LocalTime.Internal.ZonedTime import qualified GHC.Base import qualified GHC.Classes import qualified GHC.Int import qualified GHC.Show import qualified GHC.Types import qualified StripeAPI.Common import StripeAPI.TypeAlias import qualified Prelude as GHC.Integer.Type import qualified Prelude as GHC.Maybe -- | Defines the object schema located at @components.schemas.radar_review_resource_session@ in the specification. data RadarReviewResourceSession = RadarReviewResourceSession { -- | browser: The browser used in this browser session (e.g., \`Chrome\`). -- -- Constraints: -- * Maximum length of 5000 radarReviewResourceSessionBrowser :: (GHC.Maybe.Maybe (StripeAPI.Common.Nullable Data.Text.Internal.Text)), -- | device: Information about the device used for the browser session (e.g., \`Samsung SM-G930T\`). -- -- Constraints: -- * Maximum length of 5000 radarReviewResourceSessionDevice :: (GHC.Maybe.Maybe (StripeAPI.Common.Nullable Data.Text.Internal.Text)), -- | platform: The platform for the browser session (e.g., \`Macintosh\`). -- -- Constraints: -- * Maximum length of 5000 radarReviewResourceSessionPlatform :: (GHC.Maybe.Maybe (StripeAPI.Common.Nullable Data.Text.Internal.Text)), -- | version: The version for the browser session (e.g., \`61.0.3163.100\`). -- -- Constraints: -- * Maximum length of 5000 radarReviewResourceSessionVersion :: (GHC.Maybe.Maybe (StripeAPI.Common.Nullable Data.Text.Internal.Text)) } deriving ( GHC.Show.Show, GHC.Classes.Eq ) instance Data.Aeson.Types.ToJSON.ToJSON RadarReviewResourceSession where toJSON obj = Data.Aeson.Types.Internal.object (Data.Foldable.concat (Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("browser" Data.Aeson.Types.ToJSON..=)) (radarReviewResourceSessionBrowser obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("device" Data.Aeson.Types.ToJSON..=)) (radarReviewResourceSessionDevice obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("platform" Data.Aeson.Types.ToJSON..=)) (radarReviewResourceSessionPlatform obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("version" Data.Aeson.Types.ToJSON..=)) (radarReviewResourceSessionVersion obj) : GHC.Base.mempty)) toEncoding obj = Data.Aeson.Encoding.Internal.pairs (GHC.Base.mconcat (Data.Foldable.concat (Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("browser" Data.Aeson.Types.ToJSON..=)) (radarReviewResourceSessionBrowser obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("device" Data.Aeson.Types.ToJSON..=)) (radarReviewResourceSessionDevice obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("platform" Data.Aeson.Types.ToJSON..=)) (radarReviewResourceSessionPlatform obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("version" Data.Aeson.Types.ToJSON..=)) (radarReviewResourceSessionVersion obj) : GHC.Base.mempty))) instance Data.Aeson.Types.FromJSON.FromJSON RadarReviewResourceSession where parseJSON = Data.Aeson.Types.FromJSON.withObject "RadarReviewResourceSession" (\obj -> (((GHC.Base.pure RadarReviewResourceSession GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "browser")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "device")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "platform")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "version")) -- | Create a new 'RadarReviewResourceSession' with all required fields. mkRadarReviewResourceSession :: RadarReviewResourceSession mkRadarReviewResourceSession = RadarReviewResourceSession { radarReviewResourceSessionBrowser = GHC.Maybe.Nothing, radarReviewResourceSessionDevice = GHC.Maybe.Nothing, radarReviewResourceSessionPlatform = GHC.Maybe.Nothing, radarReviewResourceSessionVersion = GHC.Maybe.Nothing }
null
https://raw.githubusercontent.com/Haskell-OpenAPI-Code-Generator/Stripe-Haskell-Library/ba4401f083ff054f8da68c741f762407919de42f/src/StripeAPI/Types/RadarReviewResourceSession.hs
haskell
# LANGUAGE MultiWayIf # # LANGUAGE OverloadedStrings # | Contains the types generated from the schema RadarReviewResourceSession | Defines the object schema located at @components.schemas.radar_review_resource_session@ in the specification. | browser: The browser used in this browser session (e.g., \`Chrome\`). Constraints: | device: Information about the device used for the browser session (e.g., \`Samsung SM-G930T\`). Constraints: | platform: The platform for the browser session (e.g., \`Macintosh\`). Constraints: | version: The version for the browser session (e.g., \`61.0.3163.100\`). Constraints: | Create a new 'RadarReviewResourceSession' with all required fields.
CHANGE WITH CAUTION : This is a generated code file generated by -OpenAPI-Code-Generator/Haskell-OpenAPI-Client-Code-Generator . module StripeAPI.Types.RadarReviewResourceSession where import qualified Control.Monad.Fail import qualified Data.Aeson import qualified Data.Aeson as Data.Aeson.Encoding.Internal import qualified Data.Aeson as Data.Aeson.Types import qualified Data.Aeson as Data.Aeson.Types.FromJSON import qualified Data.Aeson as Data.Aeson.Types.Internal import qualified Data.Aeson as Data.Aeson.Types.ToJSON import qualified Data.ByteString.Char8 import qualified Data.ByteString.Char8 as Data.ByteString.Internal import qualified Data.Foldable import qualified Data.Functor import qualified Data.Maybe import qualified Data.Scientific import qualified Data.Text import qualified Data.Text.Internal import qualified Data.Time.Calendar as Data.Time.Calendar.Days import qualified Data.Time.LocalTime as Data.Time.LocalTime.Internal.ZonedTime import qualified GHC.Base import qualified GHC.Classes import qualified GHC.Int import qualified GHC.Show import qualified GHC.Types import qualified StripeAPI.Common import StripeAPI.TypeAlias import qualified Prelude as GHC.Integer.Type import qualified Prelude as GHC.Maybe data RadarReviewResourceSession = RadarReviewResourceSession * Maximum length of 5000 radarReviewResourceSessionBrowser :: (GHC.Maybe.Maybe (StripeAPI.Common.Nullable Data.Text.Internal.Text)), * Maximum length of 5000 radarReviewResourceSessionDevice :: (GHC.Maybe.Maybe (StripeAPI.Common.Nullable Data.Text.Internal.Text)), * Maximum length of 5000 radarReviewResourceSessionPlatform :: (GHC.Maybe.Maybe (StripeAPI.Common.Nullable Data.Text.Internal.Text)), * Maximum length of 5000 radarReviewResourceSessionVersion :: (GHC.Maybe.Maybe (StripeAPI.Common.Nullable Data.Text.Internal.Text)) } deriving ( GHC.Show.Show, GHC.Classes.Eq ) instance Data.Aeson.Types.ToJSON.ToJSON RadarReviewResourceSession where toJSON obj = Data.Aeson.Types.Internal.object (Data.Foldable.concat (Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("browser" Data.Aeson.Types.ToJSON..=)) (radarReviewResourceSessionBrowser obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("device" Data.Aeson.Types.ToJSON..=)) (radarReviewResourceSessionDevice obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("platform" Data.Aeson.Types.ToJSON..=)) (radarReviewResourceSessionPlatform obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("version" Data.Aeson.Types.ToJSON..=)) (radarReviewResourceSessionVersion obj) : GHC.Base.mempty)) toEncoding obj = Data.Aeson.Encoding.Internal.pairs (GHC.Base.mconcat (Data.Foldable.concat (Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("browser" Data.Aeson.Types.ToJSON..=)) (radarReviewResourceSessionBrowser obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("device" Data.Aeson.Types.ToJSON..=)) (radarReviewResourceSessionDevice obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("platform" Data.Aeson.Types.ToJSON..=)) (radarReviewResourceSessionPlatform obj) : Data.Maybe.maybe GHC.Base.mempty (GHC.Base.pure GHC.Base.. ("version" Data.Aeson.Types.ToJSON..=)) (radarReviewResourceSessionVersion obj) : GHC.Base.mempty))) instance Data.Aeson.Types.FromJSON.FromJSON RadarReviewResourceSession where parseJSON = Data.Aeson.Types.FromJSON.withObject "RadarReviewResourceSession" (\obj -> (((GHC.Base.pure RadarReviewResourceSession GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "browser")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "device")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "platform")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..:! "version")) mkRadarReviewResourceSession :: RadarReviewResourceSession mkRadarReviewResourceSession = RadarReviewResourceSession { radarReviewResourceSessionBrowser = GHC.Maybe.Nothing, radarReviewResourceSessionDevice = GHC.Maybe.Nothing, radarReviewResourceSessionPlatform = GHC.Maybe.Nothing, radarReviewResourceSessionVersion = GHC.Maybe.Nothing }
4c79a69599804760e6a24f22371a41a3c30a07df86bb4f04535209fdd5c94acd
mhallin/graphql_ppx
type_utils.ml
open Graphql_ast open Source_pos open Schema type native_type_ref = | Ntr_named of string | Ntr_nullable of native_type_ref | Ntr_list of native_type_ref let rec to_native_type_ref tr = match tr with | NonNull (Named n) -> Ntr_named n | NonNull (List l) -> Ntr_list (to_native_type_ref l) | NonNull i -> to_native_type_ref i | List l -> Ntr_nullable (Ntr_list (to_native_type_ref l)) | Named n -> Ntr_nullable (Ntr_named n) let rec to_schema_type_ref tr = match tr with | Tr_list l -> List (to_schema_type_ref l.item) | Tr_named n -> Named n.item | Tr_non_null_list l -> NonNull (List (to_schema_type_ref l.item)) | Tr_non_null_named n -> NonNull (Named n.item) let is_nullable = function | Ntr_named _ | Ntr_list _ -> false | Ntr_nullable _ -> true
null
https://raw.githubusercontent.com/mhallin/graphql_ppx/5796b3759bdf0d29112f48e43a2f0623f7466e8a/src/base/type_utils.ml
ocaml
open Graphql_ast open Source_pos open Schema type native_type_ref = | Ntr_named of string | Ntr_nullable of native_type_ref | Ntr_list of native_type_ref let rec to_native_type_ref tr = match tr with | NonNull (Named n) -> Ntr_named n | NonNull (List l) -> Ntr_list (to_native_type_ref l) | NonNull i -> to_native_type_ref i | List l -> Ntr_nullable (Ntr_list (to_native_type_ref l)) | Named n -> Ntr_nullable (Ntr_named n) let rec to_schema_type_ref tr = match tr with | Tr_list l -> List (to_schema_type_ref l.item) | Tr_named n -> Named n.item | Tr_non_null_list l -> NonNull (List (to_schema_type_ref l.item)) | Tr_non_null_named n -> NonNull (Named n.item) let is_nullable = function | Ntr_named _ | Ntr_list _ -> false | Ntr_nullable _ -> true
7a904956efb78a69760097f7a6b1fe181de680dcc6d5a3450060b4c302e0af8d
cac-t-u-s/om-sharp
bpc.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ File author : ;============================================================================ (in-package :om) ;;;======================================== ;;; TIMED POINT ;;;======================================== can be : ; nil : not defined ; t :defined ; :master --> Master point for interpolations (defstruct (tpoint (:include bpfpoint)) time internal-time) (defun om-make-tpoint (x y &optional time type) (make-tpoint :x x :y y :time time :internal-time time :type type)) (defmethod om-point-time ((self tpoint)) (tpoint-time self)) (defmethod om-point-time ((self t)) nil) (defmethod om-copy ((self tpoint)) (make-tpoint :x (tpoint-x self) :y (tpoint-y self) :time (tpoint-time self) :internal-time (tpoint-internal-time self) :type (tpoint-type self))) (defmethod om-point-set ((point tpoint) &key x y time type) (if x (setf (tpoint-x point) x)) (if y (setf (tpoint-y point) y)) (if time (progn (setf (tpoint-time point) time) (setf (tpoint-internal-time point) time))) (if type (setf (tpoint-type point) type)) point) (defmethod om-point-set-values-from-point ((point tpoint) (target tpoint)) (setf (tpoint-x point) (tpoint-x target) (tpoint-y point) (tpoint-y target) (tpoint-time point) (tpoint-time target) (tpoint-internal-time point) (tpoint-internal-time target) (tpoint-type point) (tpoint-type target)) point) (defmethod om-point-mv ((point tpoint) &key x y time) (if x (setf (tpoint-x point) (+ (tpoint-x point) x))) (if y (setf (tpoint-y point) (+ (tpoint-y point) y))) (if time (progn (setf (tpoint-time point) (+ (tpoint-time point) time)) (setf (tpoint-internal-time point) (tpoint-time point)))) point) (defmethod om-points-equal-p ((p1 tpoint) (p2 tpoint)) (and (= (tpoint-x p1) (tpoint-x p2)) (= (tpoint-y p1) (tpoint-y p2)) (= (tpoint-time p1) (tpoint-time p2)))) ;;; not necessarily at the same time ! (defmethod om-points-at-same-position ((p1 ompoint) (p2 ompoint)) (and (= (om-point-x p1) (om-point-x p2)) (= (om-point-y p1) (om-point-y p2)))) (defmethod calc-intermediate-point-at-time ((p1 tpoint) (p2 tpoint) time) (let* ((dur (- (tpoint-internal-time p2) (tpoint-internal-time p1))) (factor (/ (- time (tpoint-internal-time p1)) dur)) (x (+ (* (- (tpoint-x p2) (tpoint-x p1)) factor) (tpoint-x p1))) (y (+ (* (- (tpoint-y p2) (tpoint-y p1)) factor) (tpoint-y p1)))) (om-make-tpoint x y time))) Need to define it for for BPF points , too (defmethod calc-intermediate-point-at-time ((p1 ompoint) (p2 ompoint) time) (let* ((dur (- (om-point-x p2) (om-point-x p1))) (factor (/ (- time (om-point-x p1)) dur)) (y (+ (* (- (om-point-y p2) (om-point-y p1)) factor) (om-point-y p1)))) (om-make-point time y))) ;;; TIMED-ITEM IMPLEMENTATION (defmethod item-get-time ((self tpoint)) (tpoint-time self)) (defmethod item-set-time ((self tpoint) time) (setf (tpoint-time self) time)) (defmethod item-get-internal-time ((self tpoint)) (tpoint-internal-time self)) (defmethod item-set-internal-time ((self tpoint) time) (setf (tpoint-internal-time self) time)) (defmethod item-get-type ((self tpoint)) (tpoint-type self)) (defmethod item-set-type ((self tpoint) type) (setf (tpoint-type self) type)) ;;;======================================== BPC ;;;======================================== (defclass class-with-times-slot () ((times :initform nil :initarg :times :accessor times))) (defclass* BPC (bpf class-with-times-slot) ((x-points :initform nil :initarg :x-points) (y-points :initform nil :initarg :y-points)) (:icon 'bpc) (:documentation "Break-Points Curve: a 2D path defined by a list of [x,y] coordinates. BPC objects are constructed from the list of X coordinates (<x-points>) and the list of Y coordinates (<y-points>). The values in <x-point> are not necesarily increasing (contrary to BPF objects). - If <x-list> and <y-list> are not of the same length, the last step in the shorter one is repeated. - <decimals> determines the floating-point precision of the function (0 = integers, n > 0 = number of decimals).")) (defmethod additional-class-attributes ((self BPC)) (append '(times) (call-next-method))) ;;; BPCs have a special accessor for times (defmethod times ((self BPC)) (time-sequence-get-times self)) (defmethod (setf times) ((times t) (self BPC)) (time-sequence-set-times self times) times) (defmethod om-init-instance ((self bpc) &optional initargs) ;;; save/load will work with slot-value only (when (slot-value self 'times) (time-sequence-set-times self (slot-value self 'times))) (call-next-method)) need to redefine from BPF (defmethod time-sequence-get-times ((self BPC)) (time-values-from-points self)) (defmethod time-sequence-set-times ((self BPC) times) (set-bpf-points self :time times) (time-sequence-update-internal-times self)) (defmethod bpc-p ((self bpc)) t) (defmethod bpc-p ((self t)) nil) (defmethod time-values-from-points ((self BPC)) (mapcar #'om-point-time (point-list self))) (defmethod (setf decimals) ((decimals t) (self BPC)) (let ((x (x-values-from-points self)) (y (y-values-from-points self)) (times (time-values-from-points self))) (setf (slot-value self 'decimals) decimals) (check-decimals self) (set-bpf-points self :x x :y y :time times) (time-sequence-update-internal-times self) (decimals self))) (defmethod init-bpf-points ((self BPC)) (set-bpf-points self :x (slot-value self 'x-points) :y (slot-value self 'y-points) :time (slot-value self 'times) :time-types (slot-value self 'time-types)) (time-sequence-update-internal-times self) self) NO X - SORT IN BPC (defmethod set-bpf-points ((self bpc) &key x y z time time-types) (declare (ignore z)) (let ((point-list (make-points-from-lists (or x (x-values-from-points self)) ; (slot-value self 'x-points)) (or y (y-values-from-points self)) ; (slot-value self 'y-points)) (decimals self) 'om-make-tpoint)) (times (or time (time-values-from-points self)))) (when times (loop for p in point-list for time in times do (setf (tpoint-time p) time))) (when time-types (loop for p in point-list for type in time-types do (om-point-set p :type type))) (setf (point-list self) point-list) (setf (slot-value self 'x-points) NIL) (setf (slot-value self 'y-points) NIL) (setf (slot-value self 'times) NIL) (setf (slot-value self 'time-types) NIL))) (defmethod duplicate-coordinates ((p1 tpoint) (p2 tpoint)) (and (= (tpoint-x p1) (tpoint-x p2)) (= (tpoint-y p1) (tpoint-y p2)) (equal (tpoint-time p1) (tpoint-time p2)))) (defmethod replace-current ((new tpoint) (current tpoint)) (and (equal (bpfpoint-type new) :master) (not (equal (bpfpoint-type current) :master)))) In BPC all moves are possible (defmethod possible-move ((self bpc) points xkey deltax ykey deltay) t) (defmethod possible-set ((self bpc) point x y) t) (defmethod adapt-point ((self bpc) point) (setf (tpoint-x point) (funcall (truncate-function (decimals self)) (tpoint-x point)) (tpoint-y point) (funcall (truncate-function (decimals self)) (tpoint-y point))) point) In BPC we add the new points at the end (defmethod insert-point ((self bpc) new-point &optional position) (let ((p (adapt-point self new-point)) (pp (or position (length (point-list self))))) (setf (point-list self) (insert-in-list (point-list self) p pp)) pp )) (defmethod set-point-in-bpc ((self bpc) point x y time) (let ((xx (funcall (truncate-function (decimals self)) (or x (om-point-x point)))) (yy (funcall (truncate-function (decimals self)) (or y (om-point-y point))))) (setf (tpoint-x point) xx (tpoint-y point) yy (tpoint-time point) time) point)) ;;;========================================= TIME - SEQUENCE METHODS ;;;========================================= (defmethod get-obj-dur ((self BPC)) (if (point-list self) (tpoint-internal-time (car (last (point-list self)))) 0)) (defmethod time-sequence-make-timed-item-at ((self bpc) at) (make-default-tpoint-at-time self at)) ;;; Create a new point that preserves the motion of the object (defmethod make-default-tpoint-at-time ((self bpc) time) (if (times self) (let ((pos (or (position time (point-list self) :key 'tpoint-internal-time :test '<= ) (length (point-list self)))) (len (length (point-list self)))) if length is 1 or if the point is before the others or after use the same position than the before or after point (if (or (= len 1) (or (= pos 0) (= pos len))) (let ((point (nth (min pos (1- len)) (point-list self)))) (om-make-tpoint (om-point-x point) (om-point-y point) time)) ; if several points, preserve the motion (let ((p1 (nth (1- pos) (point-list self))) (p2 (nth pos (point-list self)))) (calc-intermediate-point-at-time p1 p2 time)))) ;if no points, create a points a pos (om-make-tpoint 0 0 time))) (defmethod* get-interpolated-sequence ((self bpc) &optional (interpol-time 100)) :numouts 3 (if (point-list self) (let* ((interpol-times (arithm-ser (tpoint-internal-time (car (point-list self))) (tpoint-internal-time (car (last (point-list self)))) interpol-time)) (new-points (loop for time in interpol-times collect (make-default-tpoint-at-time self time))) (new-obj (make-instance (type-of self) :decimals (decimals self)))) (setf (point-list new-obj) new-points) (values new-obj (x-points new-obj) (y-points new-obj))) (values (make-instance (type-of self) :x-points nil :y-points nil :decimals (decimals self)) nil nil))) Get the min max points in x and using reduce ' mix / max is when interpreted but not when compiled (defmethod nice-bpf-range ((self bpc)) (multiple-value-bind (x1 x2 y1 y2 t1 t2) (loop for x in (x-values-from-points self) for y in (y-values-from-points self) for time in (time-sequence-get-internal-times self) minimize x into x1 maximize x into x2 minimize y into y1 maximize y into y2 minimize time into t1 maximize time into t2 finally (return (values x1 x2 y1 y2 t1 t2))) (append (list x1 x2) (list y1 y2) (list t1 t2)) ( if ( < ( - x2 x1 ) 10 ) ( list ( - x1 5 ) ( + x2 5 ) ) ( list x1 x2 ) ) ( if ( < ( - y2 y1 ) 10 ) ( list ( - y1 5 ) ( + y2 5 ) ) ( list y1 y2 ) ) ) )) ;;; to be redefined by objects if they have a specific miniview for the sequencer (defmethod draw-sequencer-mini-view ((self bpc) (box t) x y w h &optional time) (let* ((x-col (om-def-color :red)) (y-col (om-def-color :green)) (ranges (nice-bpf-range self)) (times (time-sequence-get-internal-times self)) (x-t-list (mat-trans (list times (x-points self)))) (x-t-ranges (list 0 (nth 5 ranges) (car ranges) (cadr ranges))) (y-t-list (mat-trans (list times (y-points self)))) (y-t-ranges (list 0 (nth 5 ranges) (caddr ranges) (cadddr ranges)))) ;draw x = f(t) (draw-bpf-points-in-rect x-t-list x-col x-t-ranges ( + x 7 ) ( + y 10 ) ( - w 14 ) ( - h 20 ) x (+ y 10) w (- h 20) ) ;draw y = f(t) (draw-bpf-points-in-rect y-t-list y-col y-t-ranges ( + x 7 ) ( + y 10 ) ( - w 14 ) ( - h 20 ) x (+ y 10) w (- h 20) ) t)) ;;;============================ ;;; PLAYER ;;;============================ (defmethod get-action-list-for-play ((object bpc) interval &optional parent) (when (action object) (if (number-? (interpol object)) (let* ((root (get-active-interpol-time object (car interval)))) (loop for interpolated-time in (arithm-ser root (1- (cadr interval)) (number-number (interpol object))) collect (list interpolated-time #'(lambda (pt) (funcall (action-fun object) pt)) (make-default-tpoint-at-time object interpolated-time)))) (loop for pt in (filter-list (point-list object) (car interval) (cadr interval) :key 'tpoint-internal-time) collect (list (tpoint-internal-time pt) #'(lambda (ptmp) (funcall (action-fun object) ptmp)) (list pt)))))) ;;;========================================= ;;; METHODS CALLED FROM OUTSIDE ;;;========================================= (defmethod arguments-for-action ((fun (eql 'send-xy-as-osc))) `((:string address "/point/xy") (:string host ,(get-pref-value :osc :out-host)) (:int port ,(get-pref-value :osc :out-port)))) (defun send-xy-as-osc (point &optional (address "/point/xy") (host "localhost") (port 3000)) (osc-send (list address (om-point-x point) (om-point-y point)) host port)) (defmethod get-def-action-list ((object BPC)) '(print send-xy-as-osc bpc-midi-controller))
null
https://raw.githubusercontent.com/cac-t-u-s/om-sharp/195cea724ecb2cecac81d60e86d8ade2086d3ace/src/packages/basic/bpf-bpc/bpc.lisp
lisp
============================================================================ om#: visual programming language for computer-assisted music composition ============================================================================ This program is free software. For information on usage and redistribution, see the "LICENSE" file in this distribution. 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. ============================================================================ ============================================================================ ======================================== TIMED POINT ======================================== nil : not defined t :defined :master --> Master point for interpolations not necessarily at the same time ! TIMED-ITEM IMPLEMENTATION ======================================== ======================================== BPCs have a special accessor for times save/load will work with slot-value only (slot-value self 'x-points)) (slot-value self 'y-points)) ========================================= ========================================= Create a new point that preserves the motion of the object if several points, preserve the motion if no points, create a points a pos to be redefined by objects if they have a specific miniview for the sequencer draw x = f(t) draw y = f(t) ============================ PLAYER ============================ ========================================= METHODS CALLED FROM OUTSIDE =========================================
File author : (in-package :om) can be : (defstruct (tpoint (:include bpfpoint)) time internal-time) (defun om-make-tpoint (x y &optional time type) (make-tpoint :x x :y y :time time :internal-time time :type type)) (defmethod om-point-time ((self tpoint)) (tpoint-time self)) (defmethod om-point-time ((self t)) nil) (defmethod om-copy ((self tpoint)) (make-tpoint :x (tpoint-x self) :y (tpoint-y self) :time (tpoint-time self) :internal-time (tpoint-internal-time self) :type (tpoint-type self))) (defmethod om-point-set ((point tpoint) &key x y time type) (if x (setf (tpoint-x point) x)) (if y (setf (tpoint-y point) y)) (if time (progn (setf (tpoint-time point) time) (setf (tpoint-internal-time point) time))) (if type (setf (tpoint-type point) type)) point) (defmethod om-point-set-values-from-point ((point tpoint) (target tpoint)) (setf (tpoint-x point) (tpoint-x target) (tpoint-y point) (tpoint-y target) (tpoint-time point) (tpoint-time target) (tpoint-internal-time point) (tpoint-internal-time target) (tpoint-type point) (tpoint-type target)) point) (defmethod om-point-mv ((point tpoint) &key x y time) (if x (setf (tpoint-x point) (+ (tpoint-x point) x))) (if y (setf (tpoint-y point) (+ (tpoint-y point) y))) (if time (progn (setf (tpoint-time point) (+ (tpoint-time point) time)) (setf (tpoint-internal-time point) (tpoint-time point)))) point) (defmethod om-points-equal-p ((p1 tpoint) (p2 tpoint)) (and (= (tpoint-x p1) (tpoint-x p2)) (= (tpoint-y p1) (tpoint-y p2)) (= (tpoint-time p1) (tpoint-time p2)))) (defmethod om-points-at-same-position ((p1 ompoint) (p2 ompoint)) (and (= (om-point-x p1) (om-point-x p2)) (= (om-point-y p1) (om-point-y p2)))) (defmethod calc-intermediate-point-at-time ((p1 tpoint) (p2 tpoint) time) (let* ((dur (- (tpoint-internal-time p2) (tpoint-internal-time p1))) (factor (/ (- time (tpoint-internal-time p1)) dur)) (x (+ (* (- (tpoint-x p2) (tpoint-x p1)) factor) (tpoint-x p1))) (y (+ (* (- (tpoint-y p2) (tpoint-y p1)) factor) (tpoint-y p1)))) (om-make-tpoint x y time))) Need to define it for for BPF points , too (defmethod calc-intermediate-point-at-time ((p1 ompoint) (p2 ompoint) time) (let* ((dur (- (om-point-x p2) (om-point-x p1))) (factor (/ (- time (om-point-x p1)) dur)) (y (+ (* (- (om-point-y p2) (om-point-y p1)) factor) (om-point-y p1)))) (om-make-point time y))) (defmethod item-get-time ((self tpoint)) (tpoint-time self)) (defmethod item-set-time ((self tpoint) time) (setf (tpoint-time self) time)) (defmethod item-get-internal-time ((self tpoint)) (tpoint-internal-time self)) (defmethod item-set-internal-time ((self tpoint) time) (setf (tpoint-internal-time self) time)) (defmethod item-get-type ((self tpoint)) (tpoint-type self)) (defmethod item-set-type ((self tpoint) type) (setf (tpoint-type self) type)) BPC (defclass class-with-times-slot () ((times :initform nil :initarg :times :accessor times))) (defclass* BPC (bpf class-with-times-slot) ((x-points :initform nil :initarg :x-points) (y-points :initform nil :initarg :y-points)) (:icon 'bpc) (:documentation "Break-Points Curve: a 2D path defined by a list of [x,y] coordinates. BPC objects are constructed from the list of X coordinates (<x-points>) and the list of Y coordinates (<y-points>). The values in <x-point> are not necesarily increasing (contrary to BPF objects). - If <x-list> and <y-list> are not of the same length, the last step in the shorter one is repeated. - <decimals> determines the floating-point precision of the function (0 = integers, n > 0 = number of decimals).")) (defmethod additional-class-attributes ((self BPC)) (append '(times) (call-next-method))) (defmethod times ((self BPC)) (time-sequence-get-times self)) (defmethod (setf times) ((times t) (self BPC)) (time-sequence-set-times self times) times) (defmethod om-init-instance ((self bpc) &optional initargs) (when (slot-value self 'times) (time-sequence-set-times self (slot-value self 'times))) (call-next-method)) need to redefine from BPF (defmethod time-sequence-get-times ((self BPC)) (time-values-from-points self)) (defmethod time-sequence-set-times ((self BPC) times) (set-bpf-points self :time times) (time-sequence-update-internal-times self)) (defmethod bpc-p ((self bpc)) t) (defmethod bpc-p ((self t)) nil) (defmethod time-values-from-points ((self BPC)) (mapcar #'om-point-time (point-list self))) (defmethod (setf decimals) ((decimals t) (self BPC)) (let ((x (x-values-from-points self)) (y (y-values-from-points self)) (times (time-values-from-points self))) (setf (slot-value self 'decimals) decimals) (check-decimals self) (set-bpf-points self :x x :y y :time times) (time-sequence-update-internal-times self) (decimals self))) (defmethod init-bpf-points ((self BPC)) (set-bpf-points self :x (slot-value self 'x-points) :y (slot-value self 'y-points) :time (slot-value self 'times) :time-types (slot-value self 'time-types)) (time-sequence-update-internal-times self) self) NO X - SORT IN BPC (defmethod set-bpf-points ((self bpc) &key x y z time time-types) (declare (ignore z)) (decimals self) 'om-make-tpoint)) (times (or time (time-values-from-points self)))) (when times (loop for p in point-list for time in times do (setf (tpoint-time p) time))) (when time-types (loop for p in point-list for type in time-types do (om-point-set p :type type))) (setf (point-list self) point-list) (setf (slot-value self 'x-points) NIL) (setf (slot-value self 'y-points) NIL) (setf (slot-value self 'times) NIL) (setf (slot-value self 'time-types) NIL))) (defmethod duplicate-coordinates ((p1 tpoint) (p2 tpoint)) (and (= (tpoint-x p1) (tpoint-x p2)) (= (tpoint-y p1) (tpoint-y p2)) (equal (tpoint-time p1) (tpoint-time p2)))) (defmethod replace-current ((new tpoint) (current tpoint)) (and (equal (bpfpoint-type new) :master) (not (equal (bpfpoint-type current) :master)))) In BPC all moves are possible (defmethod possible-move ((self bpc) points xkey deltax ykey deltay) t) (defmethod possible-set ((self bpc) point x y) t) (defmethod adapt-point ((self bpc) point) (setf (tpoint-x point) (funcall (truncate-function (decimals self)) (tpoint-x point)) (tpoint-y point) (funcall (truncate-function (decimals self)) (tpoint-y point))) point) In BPC we add the new points at the end (defmethod insert-point ((self bpc) new-point &optional position) (let ((p (adapt-point self new-point)) (pp (or position (length (point-list self))))) (setf (point-list self) (insert-in-list (point-list self) p pp)) pp )) (defmethod set-point-in-bpc ((self bpc) point x y time) (let ((xx (funcall (truncate-function (decimals self)) (or x (om-point-x point)))) (yy (funcall (truncate-function (decimals self)) (or y (om-point-y point))))) (setf (tpoint-x point) xx (tpoint-y point) yy (tpoint-time point) time) point)) TIME - SEQUENCE METHODS (defmethod get-obj-dur ((self BPC)) (if (point-list self) (tpoint-internal-time (car (last (point-list self)))) 0)) (defmethod time-sequence-make-timed-item-at ((self bpc) at) (make-default-tpoint-at-time self at)) (defmethod make-default-tpoint-at-time ((self bpc) time) (if (times self) (let ((pos (or (position time (point-list self) :key 'tpoint-internal-time :test '<= ) (length (point-list self)))) (len (length (point-list self)))) if length is 1 or if the point is before the others or after use the same position than the before or after point (if (or (= len 1) (or (= pos 0) (= pos len))) (let ((point (nth (min pos (1- len)) (point-list self)))) (om-make-tpoint (om-point-x point) (om-point-y point) time)) (let ((p1 (nth (1- pos) (point-list self))) (p2 (nth pos (point-list self)))) (calc-intermediate-point-at-time p1 p2 time)))) (om-make-tpoint 0 0 time))) (defmethod* get-interpolated-sequence ((self bpc) &optional (interpol-time 100)) :numouts 3 (if (point-list self) (let* ((interpol-times (arithm-ser (tpoint-internal-time (car (point-list self))) (tpoint-internal-time (car (last (point-list self)))) interpol-time)) (new-points (loop for time in interpol-times collect (make-default-tpoint-at-time self time))) (new-obj (make-instance (type-of self) :decimals (decimals self)))) (setf (point-list new-obj) new-points) (values new-obj (x-points new-obj) (y-points new-obj))) (values (make-instance (type-of self) :x-points nil :y-points nil :decimals (decimals self)) nil nil))) Get the min max points in x and using reduce ' mix / max is when interpreted but not when compiled (defmethod nice-bpf-range ((self bpc)) (multiple-value-bind (x1 x2 y1 y2 t1 t2) (loop for x in (x-values-from-points self) for y in (y-values-from-points self) for time in (time-sequence-get-internal-times self) minimize x into x1 maximize x into x2 minimize y into y1 maximize y into y2 minimize time into t1 maximize time into t2 finally (return (values x1 x2 y1 y2 t1 t2))) (append (list x1 x2) (list y1 y2) (list t1 t2)) ( if ( < ( - x2 x1 ) 10 ) ( list ( - x1 5 ) ( + x2 5 ) ) ( list x1 x2 ) ) ( if ( < ( - y2 y1 ) 10 ) ( list ( - y1 5 ) ( + y2 5 ) ) ( list y1 y2 ) ) ) )) (defmethod draw-sequencer-mini-view ((self bpc) (box t) x y w h &optional time) (let* ((x-col (om-def-color :red)) (y-col (om-def-color :green)) (ranges (nice-bpf-range self)) (times (time-sequence-get-internal-times self)) (x-t-list (mat-trans (list times (x-points self)))) (x-t-ranges (list 0 (nth 5 ranges) (car ranges) (cadr ranges))) (y-t-list (mat-trans (list times (y-points self)))) (y-t-ranges (list 0 (nth 5 ranges) (caddr ranges) (cadddr ranges)))) (draw-bpf-points-in-rect x-t-list x-col x-t-ranges ( + x 7 ) ( + y 10 ) ( - w 14 ) ( - h 20 ) x (+ y 10) w (- h 20) ) (draw-bpf-points-in-rect y-t-list y-col y-t-ranges ( + x 7 ) ( + y 10 ) ( - w 14 ) ( - h 20 ) x (+ y 10) w (- h 20) ) t)) (defmethod get-action-list-for-play ((object bpc) interval &optional parent) (when (action object) (if (number-? (interpol object)) (let* ((root (get-active-interpol-time object (car interval)))) (loop for interpolated-time in (arithm-ser root (1- (cadr interval)) (number-number (interpol object))) collect (list interpolated-time #'(lambda (pt) (funcall (action-fun object) pt)) (make-default-tpoint-at-time object interpolated-time)))) (loop for pt in (filter-list (point-list object) (car interval) (cadr interval) :key 'tpoint-internal-time) collect (list (tpoint-internal-time pt) #'(lambda (ptmp) (funcall (action-fun object) ptmp)) (list pt)))))) (defmethod arguments-for-action ((fun (eql 'send-xy-as-osc))) `((:string address "/point/xy") (:string host ,(get-pref-value :osc :out-host)) (:int port ,(get-pref-value :osc :out-port)))) (defun send-xy-as-osc (point &optional (address "/point/xy") (host "localhost") (port 3000)) (osc-send (list address (om-point-x point) (om-point-y point)) host port)) (defmethod get-def-action-list ((object BPC)) '(print send-xy-as-osc bpc-midi-controller))
cea979546b4c36e7456ed418ad36f0415f9d39faca6f7de38795666d03feb990
janestreet/memtrace_viewer_with_deps
node.mli
open Js_of_ocaml open Base (** The values associated with an Element and element like nodes. (that is in practice all nodes that aren't just text). *) module Element : sig type t val tag : t -> string val attrs : t -> Attrs.t val key : t -> string option val with_key : t -> string -> t val map_attrs : t -> f:(Attrs.t -> Attrs.t) -> t val add_style : t -> Css_gen.t -> t val add_class : t -> string -> t end module Widget : sig type t module type S = sig type dom = private #Dom_html.element module Input : sig type t [@@deriving sexp_of] end module State : sig type t [@@deriving sexp_of] end val name : string val create : Input.t -> State.t * dom Js.t val update : prev_input:Input.t -> input:Input.t -> state:State.t -> element:dom Js.t -> State.t * dom Js.t val destroy : prev_input:Input.t -> state:State.t -> element:dom Js.t -> unit end end type t = | None | Text of string | Element of Element.t | Widget of Widget.t type node_creator = ?key:string -> Attr.t list -> t list -> t type node_creator_childless = ?key:string -> Attr.t list -> t val none : t val text : string -> t val textf : ('a, unit, string, t) format4 -> 'a val a : node_creator val body : node_creator val button : node_creator val code : node_creator val div : node_creator val footer : node_creator val h1 : node_creator val h2 : node_creator val h3 : node_creator val h4 : node_creator val h5 : node_creator val h6 : node_creator val header : node_creator val html : node_creator val input : node_creator val textarea : node_creator val select : node_creator val option : node_creator val label : node_creator val li : node_creator val p : node_creator val pre : node_creator val section : node_creator val span : node_creator val strong : node_creator val table : node_creator val tbody : node_creator val td : node_creator val th : node_creator val thead : node_creator val tr : node_creator val ul : node_creator val ol : node_creator val br : node_creator_childless val hr : node_creator_childless * This function can be used to build a node with the tag and html content of that node provided as a string . If this function was called with [ ~tag:"div " [ ] ~this_html ... :"<b > > " ] then the resulting node would be [ < div><b > hello world < /b></div > ] For totally sanitized content strings , this is fine ; but if a user can influence the value of [ content ] and you do n't have a sanitizer , they can inject code into the page , so use with extreme caution ! that node provided as a string. If this function was called with [~tag:"div" [] ~this_html...:"<b> hello world</b>"] then the resulting node would be [<div><b> hello world </b></div>] For totally sanitized content strings, this is fine; but if a user can influence the value of [content] and you don't have a sanitizer, they can inject code into the page, so use with extreme caution! *) val inner_html : tag:string -> Attr.t list -> this_html_is_sanitized_and_is_totally_safe_trust_me:string -> t (** Same as [inner_html] but for svg elements *) val inner_html_svg : tag:string -> Attr.t list -> this_html_is_sanitized_and_is_totally_safe_trust_me:string -> t (** [key] is used by Virtual_dom as a hint during diffing/patching *) val create : string -> ?key:string -> Attr.t list -> t list -> t (** Like [create] but for svg nodes (i.e. all to be placed inside <svg> tag). This is needed as browsers maintain separate namespaces for html and svg, and failing to use the correct one may result in delayed redraws. *) val create_svg : string -> ?key:string -> Attr.t list -> t list -> t val to_dom : t -> Dom_html.element Js.t val to_raw : t -> Raw.Node.t * Creates a Node.t that has fine - grained control over the Browser DOM node . Callbacks = = = = = = = = = init : Returns a Browser DOM Node and a widget state object . The Browser DOM node is mounted into the dom in the location where the Node.t object would otherwise be . update : Given the previous Browser DOM Node and state , makes any changes necessary to either and returns a new state and Browser DOM Node . destroy : Called when this Node.t is removed from the Virtual_dom . Performs any necessary cleanup . Other = = = = = The [ i d ] is used to compare widgets , and is used to make sure that the state from one widget does n't get interpreted as the state for another . Otherwise , you would be able to implement Obj.magic using this API . WARNING : While other Virtual_dom APIs shield the application from script injection attacks , the [ Widget.create ] function allows a developer to bypass these safeguards and manually create DOM nodes which could allow an attacker to change the behavior of the application or exfiltrate data . In using this API , you are being trusted to understand and follow security best - practices . Callbacks ========= init: Returns a Browser DOM Node and a widget state object. The Browser DOM node is mounted into the dom in the location where the Node.t object would otherwise be. update: Given the previous Browser DOM Node and state, makes any changes necessary to either and returns a new state and Browser DOM Node. destroy: Called when this Node.t is removed from the Virtual_dom. Performs any necessary cleanup. Other ===== The [id] is used to compare widgets, and is used to make sure that the state from one widget doesn't get interpreted as the state for another. Otherwise, you would be able to implement Obj.magic using this API. WARNING: While other Virtual_dom APIs shield the application from script injection attacks, the [Widget.create] function allows a developer to bypass these safeguards and manually create DOM nodes which could allow an attacker to change the behavior of the application or exfiltrate data. In using this API, you are being trusted to understand and follow security best-practices. *) val widget : ?info:Sexp.t Lazy.t -> ?destroy:('s -> (#Dom_html.element as 'e) Js.t -> unit) -> ?update:('s -> 'e Js.t -> 's * 'e Js.t) -> id:('s * 'e Js.t) Type_equal.Id.t -> init:(unit -> 's * 'e Js.t) -> unit -> t val widget_of_module : (module Widget.S with type Input.t = 'input) -> ('input -> t) Staged.t module Patch : sig type node = t type t val create : previous:node -> current:node -> t val apply : t -> Dom_html.element Js.t -> Dom_html.element Js.t val is_empty : t -> bool end
null
https://raw.githubusercontent.com/janestreet/memtrace_viewer_with_deps/5a9e1f927f5f8333e2d71c8d3ca03a45587422c4/vendor/virtual_dom/src/node.mli
ocaml
* The values associated with an Element and element like nodes. (that is in practice all nodes that aren't just text). * Same as [inner_html] but for svg elements * [key] is used by Virtual_dom as a hint during diffing/patching * Like [create] but for svg nodes (i.e. all to be placed inside <svg> tag). This is needed as browsers maintain separate namespaces for html and svg, and failing to use the correct one may result in delayed redraws.
open Js_of_ocaml open Base module Element : sig type t val tag : t -> string val attrs : t -> Attrs.t val key : t -> string option val with_key : t -> string -> t val map_attrs : t -> f:(Attrs.t -> Attrs.t) -> t val add_style : t -> Css_gen.t -> t val add_class : t -> string -> t end module Widget : sig type t module type S = sig type dom = private #Dom_html.element module Input : sig type t [@@deriving sexp_of] end module State : sig type t [@@deriving sexp_of] end val name : string val create : Input.t -> State.t * dom Js.t val update : prev_input:Input.t -> input:Input.t -> state:State.t -> element:dom Js.t -> State.t * dom Js.t val destroy : prev_input:Input.t -> state:State.t -> element:dom Js.t -> unit end end type t = | None | Text of string | Element of Element.t | Widget of Widget.t type node_creator = ?key:string -> Attr.t list -> t list -> t type node_creator_childless = ?key:string -> Attr.t list -> t val none : t val text : string -> t val textf : ('a, unit, string, t) format4 -> 'a val a : node_creator val body : node_creator val button : node_creator val code : node_creator val div : node_creator val footer : node_creator val h1 : node_creator val h2 : node_creator val h3 : node_creator val h4 : node_creator val h5 : node_creator val h6 : node_creator val header : node_creator val html : node_creator val input : node_creator val textarea : node_creator val select : node_creator val option : node_creator val label : node_creator val li : node_creator val p : node_creator val pre : node_creator val section : node_creator val span : node_creator val strong : node_creator val table : node_creator val tbody : node_creator val td : node_creator val th : node_creator val thead : node_creator val tr : node_creator val ul : node_creator val ol : node_creator val br : node_creator_childless val hr : node_creator_childless * This function can be used to build a node with the tag and html content of that node provided as a string . If this function was called with [ ~tag:"div " [ ] ~this_html ... :"<b > > " ] then the resulting node would be [ < div><b > hello world < /b></div > ] For totally sanitized content strings , this is fine ; but if a user can influence the value of [ content ] and you do n't have a sanitizer , they can inject code into the page , so use with extreme caution ! that node provided as a string. If this function was called with [~tag:"div" [] ~this_html...:"<b> hello world</b>"] then the resulting node would be [<div><b> hello world </b></div>] For totally sanitized content strings, this is fine; but if a user can influence the value of [content] and you don't have a sanitizer, they can inject code into the page, so use with extreme caution! *) val inner_html : tag:string -> Attr.t list -> this_html_is_sanitized_and_is_totally_safe_trust_me:string -> t val inner_html_svg : tag:string -> Attr.t list -> this_html_is_sanitized_and_is_totally_safe_trust_me:string -> t val create : string -> ?key:string -> Attr.t list -> t list -> t val create_svg : string -> ?key:string -> Attr.t list -> t list -> t val to_dom : t -> Dom_html.element Js.t val to_raw : t -> Raw.Node.t * Creates a Node.t that has fine - grained control over the Browser DOM node . Callbacks = = = = = = = = = init : Returns a Browser DOM Node and a widget state object . The Browser DOM node is mounted into the dom in the location where the Node.t object would otherwise be . update : Given the previous Browser DOM Node and state , makes any changes necessary to either and returns a new state and Browser DOM Node . destroy : Called when this Node.t is removed from the Virtual_dom . Performs any necessary cleanup . Other = = = = = The [ i d ] is used to compare widgets , and is used to make sure that the state from one widget does n't get interpreted as the state for another . Otherwise , you would be able to implement Obj.magic using this API . WARNING : While other Virtual_dom APIs shield the application from script injection attacks , the [ Widget.create ] function allows a developer to bypass these safeguards and manually create DOM nodes which could allow an attacker to change the behavior of the application or exfiltrate data . In using this API , you are being trusted to understand and follow security best - practices . Callbacks ========= init: Returns a Browser DOM Node and a widget state object. The Browser DOM node is mounted into the dom in the location where the Node.t object would otherwise be. update: Given the previous Browser DOM Node and state, makes any changes necessary to either and returns a new state and Browser DOM Node. destroy: Called when this Node.t is removed from the Virtual_dom. Performs any necessary cleanup. Other ===== The [id] is used to compare widgets, and is used to make sure that the state from one widget doesn't get interpreted as the state for another. Otherwise, you would be able to implement Obj.magic using this API. WARNING: While other Virtual_dom APIs shield the application from script injection attacks, the [Widget.create] function allows a developer to bypass these safeguards and manually create DOM nodes which could allow an attacker to change the behavior of the application or exfiltrate data. In using this API, you are being trusted to understand and follow security best-practices. *) val widget : ?info:Sexp.t Lazy.t -> ?destroy:('s -> (#Dom_html.element as 'e) Js.t -> unit) -> ?update:('s -> 'e Js.t -> 's * 'e Js.t) -> id:('s * 'e Js.t) Type_equal.Id.t -> init:(unit -> 's * 'e Js.t) -> unit -> t val widget_of_module : (module Widget.S with type Input.t = 'input) -> ('input -> t) Staged.t module Patch : sig type node = t type t val create : previous:node -> current:node -> t val apply : t -> Dom_html.element Js.t -> Dom_html.element Js.t val is_empty : t -> bool end
d383851871a0bcaec322e4a15c4b5b148e40f0c27c71433fba72c0046a10f262
mrDoctorWho/ejabberd_mod_apns
mod_apns.erl
Ejabberd module for the Apple Push Notification Service %% Created: 07/09/2015 by mrDoctorWho %% License: MIT/X11 -module(mod_apns). -author("mrDoctorWho"). -include("ejabberd.hrl"). -include("xmpp.hrl"). -include("mod_apns.hrl"). -include("logger.hrl"). -behaviour(gen_mod). -record(apns_users, {user :: {binary(), binary()}, token :: binary(), last_seen :: pos_integer()}). I hope Apple does n't mind . -export([iq/1, message/1, mod_opt_type/1, start/2, stop/1, depends/2]). -define(Timeout, 10000). -spec send_payload(binary(), iolist(), binary()) -> ok | {error, any()}. % partially done by uwe-arzt.de send_payload(Host, Payload, Token) -> Address = gen_mod:get_module_opt(Host, ?MODULE, address), Port = gen_mod:get_module_opt(Host, ?MODULE, port), Cert = gen_mod:get_module_opt(Host, ?MODULE, certfile), Keyfile = gen_mod:get_module_opt(Host, ?MODULE, keyfile), Password = gen_mod:get_module_opt(Host, ?MODULE, password), ?DEBUG("Trying to send payload with " "these parameters: Address: ~s Port: " "~s Cert: ~s Keyfile: ~s Password ~s", [Address, Port, Cert, Keyfile, Password]), case Password of undefined -> Options = [{certfile, Cert}, {keyfile, Keyfile}, {mode, binary}]; %% {verify, verify_none} _ -> Options = [{certfile, Cert}, {keyfile, Keyfile}, {password, Password}, {mode, binary}] end, case ssl:connect(Address, Port, Options, ?Timeout) of {ok, Socket} -> PayloadBin = list_to_binary(Payload), PayloadLength = size(PayloadBin), TokenNum = erlang:binary_to_integer(Token, 16), TokenBin = <<TokenNum:32/integer-unit:8>>, Packet = <<0:8, 32:16/big, TokenBin/binary, PayloadLength:16/big, PayloadBin/binary>>, ssl:send(Socket, Packet), ssl:close(Socket), ?DEBUG("Successfully sent payload " "to the APNS server", []); {error, Reason} = Err -> ?ERROR_MSG("Unable to connect to the APNS " "server: ~s", [ssl:format_error(Reason)]), Err end. create_json(List1, List2) -> lists:append(["{\"aps\":{", create_keyvalue(List1), "}, ", create_keyvalue(List2), "}"]). create_keyvalue([Head]) -> create_pair(Head); create_keyvalue([Head | Tail]) -> lists:append([create_pair(Head), ",", create_keyvalue(Tail)]). create_pair({Key, Value}) -> lists:append([add_quotes(atom_to_list(Key)), ":", add_quotes(Value)]). add_quotes(String) -> lists:append(["\"", String, "\""]). -spec message({any(), message()}) -> {any(), message()}. message({_, #message{type = T}} = Acc) when T == normal; T == error -> Acc; message({_, #message{from = From, to = To} = Packet} = Acc) -> ?DEBUG("Offline message", []), JFrom = jid:encode(jid:remove_resource(From)), JTo = jid:encode(jid:remove_resource(To)), ToUser = To#jid.luser, ToServer = To#jid.lserver, Body = xmpp:get_text(Packet#message.body), {Subscription, _Groups} = ejabberd_hooks:run_fold(roster_get_jid_info, ToServer, {none, []}, [ToUser, ToServer, From]), case Subscription of both -> case Body of <<>> -> ok; _ -> Result = mnesia:dirty_read(apns_users, {ToUser, ToServer}), case Result of [] -> ?DEBUG("No such record found for ~s", [JTo]); [#apns_users{token = Token}] -> Sound = "default", %% TODO: Move binary_to_list to create_pair? %% Badges? Msg = [{alert, binary_to_list(Body)}, {sound, Sound}], Args = [{source, binary_to_list(JFrom)}, {destination, binary_to_list(JTo)}], JSON = create_json(Msg, Args), send_payload(ToServer, JSON, Token) end end; _ -> ok end, Acc. -spec iq(iq()) -> iq(). iq(#iq{from = #jid{luser = LUser, lserver = LServer}, sub_els = [#apns_register{token = Token}]} = IQ) -> {MegaSecs, Secs, _MicroSecs} = p1_time_compat:timestamp(), TimeStamp = MegaSecs * 1000000 + Secs, F = fun () -> mnesia:write(#apns_users{user = {LUser, LServer}, token = Token, last_seen = TimeStamp}) end, case mnesia:dirty_read(apns_users, {LUser, LServer}) of [] -> mnesia:transaction(F), ?DEBUG("New user registered ~s@~s", [LUser, LServer]); %% Record exists, the key is equal to the one we know [#apns_users{user = {LUser, LServer}, token = Token}] -> mnesia:transaction(F), ?DEBUG("Updating last_seen for user ~s@~s", [LUser, LServer]); %% Record for this key has been found, but with another token [#apns_users{user = {LUser, LServer}, token = _}] -> mnesia:transaction(F), ?DEBUG("Updating token for user ~s@~s", [LUser, LServer]) end, %% We don't need the result, but the handler has to send something xmpp:make_iq_result(IQ); iq(#iq{lang = Lang} = IQ) -> Txt = <<"No module is handling this query">>, xmpp:make_error(IQ, xmpp:err_service_unavailable(Txt, Lang)). start(Host, _) -> xmpp:register_codec(mod_apns_codec), mnesia:create_table(apns_users, [{disc_copies, [node()]}, {attributes, record_info(fields, apns_users)}]), gen_iq_handler:add_iq_handler(ejabberd_local, Host, ?NS_APNS, ?MODULE, iq, no_queue), ejabberd_hooks:add(offline_message_hook, Host, ?MODULE, message, 49). stop(Host) -> gen_iq_handler:remove_iq_handler(ejabberd_local, Host, ?NS_APNS), ejabberd_hooks:delete(offline_message_hook, Host, ?MODULE, message, 49). mod_opt_type(address) -> fun binary_to_list/1; mod_opt_type(port) -> fun (I) when is_integer(I), I>0, I<65536 -> I end; mod_opt_type(certfile) -> fun misc:try_read_file/1; mod_opt_type(keyfile) -> fun misc:try_read_file/1; mod_opt_type(password) -> fun iolist_to_binary/1; mod_opt_type(_) -> [address, port, certfile, keyfile, password]. depends(_, _) -> [].
null
https://raw.githubusercontent.com/mrDoctorWho/ejabberd_mod_apns/d2b5682887540fc1f75e7b9889aac6ddb1431fb7/src/mod_apns.erl
erlang
Created: 07/09/2015 by mrDoctorWho License: MIT/X11 partially done by uwe-arzt.de {verify, verify_none} TODO: Move binary_to_list to create_pair? Badges? Record exists, the key is equal to the one we know Record for this key has been found, but with another token We don't need the result, but the handler has to send something
Ejabberd module for the Apple Push Notification Service -module(mod_apns). -author("mrDoctorWho"). -include("ejabberd.hrl"). -include("xmpp.hrl"). -include("mod_apns.hrl"). -include("logger.hrl"). -behaviour(gen_mod). -record(apns_users, {user :: {binary(), binary()}, token :: binary(), last_seen :: pos_integer()}). I hope Apple does n't mind . -export([iq/1, message/1, mod_opt_type/1, start/2, stop/1, depends/2]). -define(Timeout, 10000). -spec send_payload(binary(), iolist(), binary()) -> ok | {error, any()}. send_payload(Host, Payload, Token) -> Address = gen_mod:get_module_opt(Host, ?MODULE, address), Port = gen_mod:get_module_opt(Host, ?MODULE, port), Cert = gen_mod:get_module_opt(Host, ?MODULE, certfile), Keyfile = gen_mod:get_module_opt(Host, ?MODULE, keyfile), Password = gen_mod:get_module_opt(Host, ?MODULE, password), ?DEBUG("Trying to send payload with " "these parameters: Address: ~s Port: " "~s Cert: ~s Keyfile: ~s Password ~s", [Address, Port, Cert, Keyfile, Password]), case Password of undefined -> Options = [{certfile, Cert}, {keyfile, Keyfile}, _ -> Options = [{certfile, Cert}, {keyfile, Keyfile}, {password, Password}, {mode, binary}] end, case ssl:connect(Address, Port, Options, ?Timeout) of {ok, Socket} -> PayloadBin = list_to_binary(Payload), PayloadLength = size(PayloadBin), TokenNum = erlang:binary_to_integer(Token, 16), TokenBin = <<TokenNum:32/integer-unit:8>>, Packet = <<0:8, 32:16/big, TokenBin/binary, PayloadLength:16/big, PayloadBin/binary>>, ssl:send(Socket, Packet), ssl:close(Socket), ?DEBUG("Successfully sent payload " "to the APNS server", []); {error, Reason} = Err -> ?ERROR_MSG("Unable to connect to the APNS " "server: ~s", [ssl:format_error(Reason)]), Err end. create_json(List1, List2) -> lists:append(["{\"aps\":{", create_keyvalue(List1), "}, ", create_keyvalue(List2), "}"]). create_keyvalue([Head]) -> create_pair(Head); create_keyvalue([Head | Tail]) -> lists:append([create_pair(Head), ",", create_keyvalue(Tail)]). create_pair({Key, Value}) -> lists:append([add_quotes(atom_to_list(Key)), ":", add_quotes(Value)]). add_quotes(String) -> lists:append(["\"", String, "\""]). -spec message({any(), message()}) -> {any(), message()}. message({_, #message{type = T}} = Acc) when T == normal; T == error -> Acc; message({_, #message{from = From, to = To} = Packet} = Acc) -> ?DEBUG("Offline message", []), JFrom = jid:encode(jid:remove_resource(From)), JTo = jid:encode(jid:remove_resource(To)), ToUser = To#jid.luser, ToServer = To#jid.lserver, Body = xmpp:get_text(Packet#message.body), {Subscription, _Groups} = ejabberd_hooks:run_fold(roster_get_jid_info, ToServer, {none, []}, [ToUser, ToServer, From]), case Subscription of both -> case Body of <<>> -> ok; _ -> Result = mnesia:dirty_read(apns_users, {ToUser, ToServer}), case Result of [] -> ?DEBUG("No such record found for ~s", [JTo]); [#apns_users{token = Token}] -> Sound = "default", Msg = [{alert, binary_to_list(Body)}, {sound, Sound}], Args = [{source, binary_to_list(JFrom)}, {destination, binary_to_list(JTo)}], JSON = create_json(Msg, Args), send_payload(ToServer, JSON, Token) end end; _ -> ok end, Acc. -spec iq(iq()) -> iq(). iq(#iq{from = #jid{luser = LUser, lserver = LServer}, sub_els = [#apns_register{token = Token}]} = IQ) -> {MegaSecs, Secs, _MicroSecs} = p1_time_compat:timestamp(), TimeStamp = MegaSecs * 1000000 + Secs, F = fun () -> mnesia:write(#apns_users{user = {LUser, LServer}, token = Token, last_seen = TimeStamp}) end, case mnesia:dirty_read(apns_users, {LUser, LServer}) of [] -> mnesia:transaction(F), ?DEBUG("New user registered ~s@~s", [LUser, LServer]); [#apns_users{user = {LUser, LServer}, token = Token}] -> mnesia:transaction(F), ?DEBUG("Updating last_seen for user ~s@~s", [LUser, LServer]); [#apns_users{user = {LUser, LServer}, token = _}] -> mnesia:transaction(F), ?DEBUG("Updating token for user ~s@~s", [LUser, LServer]) end, xmpp:make_iq_result(IQ); iq(#iq{lang = Lang} = IQ) -> Txt = <<"No module is handling this query">>, xmpp:make_error(IQ, xmpp:err_service_unavailable(Txt, Lang)). start(Host, _) -> xmpp:register_codec(mod_apns_codec), mnesia:create_table(apns_users, [{disc_copies, [node()]}, {attributes, record_info(fields, apns_users)}]), gen_iq_handler:add_iq_handler(ejabberd_local, Host, ?NS_APNS, ?MODULE, iq, no_queue), ejabberd_hooks:add(offline_message_hook, Host, ?MODULE, message, 49). stop(Host) -> gen_iq_handler:remove_iq_handler(ejabberd_local, Host, ?NS_APNS), ejabberd_hooks:delete(offline_message_hook, Host, ?MODULE, message, 49). mod_opt_type(address) -> fun binary_to_list/1; mod_opt_type(port) -> fun (I) when is_integer(I), I>0, I<65536 -> I end; mod_opt_type(certfile) -> fun misc:try_read_file/1; mod_opt_type(keyfile) -> fun misc:try_read_file/1; mod_opt_type(password) -> fun iolist_to_binary/1; mod_opt_type(_) -> [address, port, certfile, keyfile, password]. depends(_, _) -> [].
f110723546226a9068d13feb83e890d899e067a9c641633f7b921a460f350101
gvolpe/shopping-cart-haskell
Cart.hs
# LANGUAGE DeriveAnyClass , DeriveGeneric , OverloadedStrings # module Domain.Cart where import Data.Aeson import Data.Map ( Map ) import Data.UUID ( UUID ) import Database.PostgreSQL.Simple.ToRow ( ToRow ) import Domain.Item import GHC.Generics ( Generic ) newtype CartId = CartId UUID deriving (Generic, ToRow, Show) newtype Cart = Cart (Map ItemId Quantity) deriving (Generic, Show) newtype Quantity = Quantity Int deriving (Generic, ToRow, Show) newtype CartExpiration = CartExpiration Integer deriving (Generic, ToRow, Show) data CartItem = CartItem { item :: Item , quantity :: Quantity } deriving (Generic, Show) subTotal :: CartItem -> Money subTotal (CartItem item' (Quantity q)) = itemPrice item' * Money (fromIntegral q) data CartTotal = CartTotal { items :: [CartItem] , total :: Money } deriving (Generic, Show) instance ToJSON Quantity where toJSON (Quantity q) = toJSON q instance FromJSON Quantity where parseJSON v = Quantity <$> parseJSON v instance FromJSON Cart where parseJSON = withObject "Cart json" $ \o -> do i <- o .: "items" return $ Cart i instance FromJSON CartItem where parseJSON = withObject "CartItem json" $ \o -> do i <- o .: "item" q <- o .: "quantity" return $ CartItem i q instance ToJSON CartItem where toJSON (CartItem _item _quantity) = object ["item" .= _item, "quantity" .= _quantity] instance ToJSON CartTotal where toJSON (CartTotal _items _total) = object ["items" .= _items, "total" .= _total]
null
https://raw.githubusercontent.com/gvolpe/shopping-cart-haskell/303e1dbad6e49f28367c1b54231b333089fc7e13/src/Domain/Cart.hs
haskell
# LANGUAGE DeriveAnyClass , DeriveGeneric , OverloadedStrings # module Domain.Cart where import Data.Aeson import Data.Map ( Map ) import Data.UUID ( UUID ) import Database.PostgreSQL.Simple.ToRow ( ToRow ) import Domain.Item import GHC.Generics ( Generic ) newtype CartId = CartId UUID deriving (Generic, ToRow, Show) newtype Cart = Cart (Map ItemId Quantity) deriving (Generic, Show) newtype Quantity = Quantity Int deriving (Generic, ToRow, Show) newtype CartExpiration = CartExpiration Integer deriving (Generic, ToRow, Show) data CartItem = CartItem { item :: Item , quantity :: Quantity } deriving (Generic, Show) subTotal :: CartItem -> Money subTotal (CartItem item' (Quantity q)) = itemPrice item' * Money (fromIntegral q) data CartTotal = CartTotal { items :: [CartItem] , total :: Money } deriving (Generic, Show) instance ToJSON Quantity where toJSON (Quantity q) = toJSON q instance FromJSON Quantity where parseJSON v = Quantity <$> parseJSON v instance FromJSON Cart where parseJSON = withObject "Cart json" $ \o -> do i <- o .: "items" return $ Cart i instance FromJSON CartItem where parseJSON = withObject "CartItem json" $ \o -> do i <- o .: "item" q <- o .: "quantity" return $ CartItem i q instance ToJSON CartItem where toJSON (CartItem _item _quantity) = object ["item" .= _item, "quantity" .= _quantity] instance ToJSON CartTotal where toJSON (CartTotal _items _total) = object ["items" .= _items, "total" .= _total]
73c61ef54576932ffea72c67359616a72908b165ce17bd17bf9ca7c4cde77f0c
rvantonder/hack_parallel
hack_parallel_intf.mli
module Std : sig module Bucket : sig (* The general protocol for a next function is to return either Wait (indicating that workers should wait until more elements are added to the workload), or Job of a bucket, or Done to indicate there is no more work. *) type 'a bucket = | Job of 'a | Wait | Done type 'a next = unit -> 'a bucket (* Makes a bucket out of a list, without regard for number of workers or the size of the list. *) val of_list : 'a list -> 'a list bucket val make : num_workers:int -> 'a list -> 'a list next type 'a of_n = { work: 'a; bucket: int; total: int } val make_n_buckets : buckets:int -> split:(bucket:int -> 'a) -> 'a of_n next end module SharedMem : sig (*****************************************************************************) The heap shared across all the processes . * * The Heap is not exposed directly to the user ( cf shared.mli ) , * because we do n't want to mix values of different types . Instead , we want * to use a functor . * * The Heap is not exposed directly to the user (cf shared.mli), * because we don't want to mix values of different types. Instead, we want * to use a functor. *) (*****************************************************************************) type config = { global_size : int; heap_size : int; dep_table_pow : int; hash_table_pow : int; shm_dirs : string list; shm_min_avail : int; log_level : int; } type handle = private { h_fd: Unix.file_descr; h_global_size: int; h_heap_size: int; } exception Out_of_shared_memory exception Hash_table_full exception Dep_table_full exception Heap_full exception Sql_assertion_failure of int exception C_assertion_failure of string (*****************************************************************************) (* Initializes the shared memory. Must be called before forking! *) (*****************************************************************************) val init: config -> handle (*****************************************************************************) Connect a slave to the shared heap (*****************************************************************************) val connect: handle -> unit (*****************************************************************************) The shared memory garbage collector . It must be called every time we * free data ( cf hh_shared.c for the underlying C implementation ) . * free data (cf hh_shared.c for the underlying C implementation). *) (*****************************************************************************) val collect: [ `gentle | `aggressive | `always_TEST ] -> unit (*****************************************************************************) Must be called after the initialization of the hack server is over . * ( cf ) . * (cf serverInit.ml). *) (*****************************************************************************) val init_done: unit -> unit (*****************************************************************************) Serializes the dependency table and writes it to a file (*****************************************************************************) val save_dep_table_sqlite: string -> string -> int (*****************************************************************************) (* Loads the dependency table by reading from a file *) (*****************************************************************************) val load_dep_table_sqlite: string -> bool -> int (*****************************************************************************) Serializes & loads the hash table directly into memory (*****************************************************************************) val save_table: string -> unit val load_table: string -> unit (*****************************************************************************) Serializes the hash table to sqlite (*****************************************************************************) val save_table_sqlite: string -> int val save_table_keys_sqlite: string -> string array -> int (*****************************************************************************) (* Loads the hash table by reading from a file *) (*****************************************************************************) val load_table_sqlite: string -> bool -> int (*****************************************************************************) (* Cleans up the artifacts generated by SQL *) (*****************************************************************************) val cleanup_sqlite: unit -> unit (*****************************************************************************) (* The size of the dynamically allocated shared memory section *) (*****************************************************************************) val heap_size : unit -> int (*****************************************************************************) (* Part of the heap not reachable from hashtable entries. *) (*****************************************************************************) val wasted_heap_size: unit -> int (*****************************************************************************) (* Stats of the statically sized hash / dep tables *) (*****************************************************************************) type table_stats = { nonempty_slots : int; used_slots : int; slots : int; } val dep_stats : unit -> table_stats val hash_stats : unit -> table_stats val is_heap_overflow: unit -> bool (*****************************************************************************) Cache invalidation . (*****************************************************************************) val invalidate_caches: unit -> unit Size of value in GC heap val value_size: Obj.t -> int (*****************************************************************************) The signature of a shared memory hashtable . * To create one : SharedMem . NoCache(struct type = my_type_of_value end ) . * The call to Make will create a hashtable in shared memory ( visible to * all the workers ) . * Use NoCache / WithCache if you want caching or not . * If you do , bear in mind that the cache must be maintained by the caller . * So you will have to invalidate the caches yourself . * To create one: SharedMem.NoCache(struct type = my_type_of_value end). * The call to Make will create a hashtable in shared memory (visible to * all the workers). * Use NoCache/WithCache if you want caching or not. * If you do, bear in mind that the cache must be maintained by the caller. * So you will have to invalidate the caches yourself. *) (*****************************************************************************) module type NoCache = sig type key type t module KeySet : Set.S with type elt = key module KeyMap : MyMap.S with type key = key Safe for concurrent writes , the first writer wins , the second write * is dismissed . * is dismissed. *) val add : key -> t -> unit Safe for concurrent reads . Safe for interleaved reads and mutations , * provided the code runs on Intel architectures . * provided the code runs on Intel architectures. *) val get : key -> t option val get_old : key -> t option val get_old_batch : KeySet.t -> t option KeyMap.t val remove_old_batch : KeySet.t -> unit val find_unsafe : key -> t val get_batch : KeySet.t -> t option KeyMap.t val remove_batch : KeySet.t -> unit val string_of_key : key -> string (* Safe for concurrent access. *) val mem : key -> bool val mem_old : key -> bool (* This function takes the elements present in the set and keep the "old" * version in a separate heap. This is useful when we want to compare * what has changed. We will be in a situation for type-checking * (cf typing/typing_redecl_service.ml) where we want to compare the type * of a class in the previous environment vs the current type. *) val oldify_batch : KeySet.t -> unit (* Reverse operation of oldify *) val revive_batch : KeySet.t -> unit module LocalChanges : sig val has_local_changes : unit -> bool val push_stack : unit -> unit val pop_stack : unit -> unit val revert_batch : KeySet.t -> unit val commit_batch : KeySet.t -> unit val revert_all : unit -> unit val commit_all : unit -> unit end end module type WithCache = sig include NoCache val write_through : key -> t -> unit val get_no_cache: key -> t option end module type UserKeyType = sig type t val to_string : t -> string val compare : t -> t -> int end module NoCache : functor (UserKeyType : UserKeyType) -> functor (Value:Value.Type) -> NoCache with type t = Value.t and type key = UserKeyType.t and module KeySet = Set.Make (UserKeyType) and module KeyMap = MyMap.Make (UserKeyType) module WithCache : functor (UserKeyType : UserKeyType) -> functor (Value:Value.Type) -> WithCache with type t = Value.t and type key = UserKeyType.t and module KeySet = Set.Make (UserKeyType) and module KeyMap = MyMap.Make (UserKeyType) module type CacheType = sig type key type value val add: key -> value -> unit val get: key -> value option val remove: key -> unit val clear: unit -> unit val string_of_key : key -> string val get_size : unit -> int end module LocalCache : functor (UserKeyType : UserKeyType) -> functor (Value : Value.Type) -> CacheType with type key = UserKeyType.t and type value = Value.t end module Worker : sig exception Worker_exited_abnormally of int * Unix.process_status * Worker killed by Out Of Memory . exception Worker_oomed (** Raise this exception when sending work to a worker that is already busy. * We should never be doing that, and this is an assertion error. *) exception Worker_busy (** Raise this exception when sending work to a worker that is already killed. * We should never be doing that, and this is an assertion error. *) exception Worker_killed type send_job_failure = | Worker_already_exited of Unix.process_status | Other_send_job_failure of exn exception Worker_failed_to_send_job of send_job_failure (* The type of a worker visible to the outside world *) type t (*****************************************************************************) (* The handle is what we get back when we start a job. It's a "future" * (sometimes called a "promise"). The scheduler uses the handle to retrieve * the result of the job when the task is done (cf multiWorker.ml). *) (*****************************************************************************) type 'a handle type 'a entry val register_entry_point: restore:('a -> unit) -> 'a entry (** Creates a pool of workers. *) val make: saved_state : 'a -> entry : 'a entry -> nbr_procs : int -> gc_control : Gc.control -> heap_handle : SharedMem.handle -> t list Call in a sub - process ( CAREFUL , GLOBALS ARE COPIED ) val call: t -> ('a -> 'b) -> 'a -> 'b handle (* Retrieves the result (once the worker is done) hangs otherwise *) val get_result: 'a handle -> 'a (* Selects among multiple handles those which are ready. *) type 'a selected = { readys: 'a handle list; waiters: 'a handle list; } val select: 'a handle list -> 'a selected (* Returns the worker which produces this handle *) val get_worker: 'a handle -> t Killall the workers val killall: unit -> unit val current_worker_id: unit -> int end module MultiWorker : sig (* 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 Bucket.next val next : Worker.t list option -> 'a list -> 'a list Bucket.next (* See definition in Bucket above *) type 'a bucket = 'a 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 Bucket.next -> 'c end module Daemon : sig * Type - safe versions of the channels in Pervasives . type 'a in_channel type 'a out_channel type ('in_, 'out) channel_pair = 'in_ in_channel * 'out out_channel val to_channel : 'a out_channel -> ?flags:Marshal.extern_flags list -> ?flush:bool -> 'a -> unit val from_channel : ?timeout:Timeout.t -> 'a in_channel -> 'a val flush : 'a out_channel -> unit (* This breaks the type safety, but is necessary in order to allow select() *) val descr_of_in_channel : 'a in_channel -> Unix.file_descr val descr_of_out_channel : 'a out_channel -> Unix.file_descr val cast_in : 'a in_channel -> Timeout.in_channel val cast_out : 'a out_channel -> Pervasives.out_channel val close_out : 'a out_channel -> unit val output_string : 'a out_channel -> string -> unit val close_in : 'a in_channel -> unit val input_char : 'a in_channel -> char val input_value : 'a in_channel -> 'b (** Spawning new process *) In the absence of ' fork ' on Windows , its usage must be restricted to Unix specifics parts . This module provides a mechanism to " spawn " new instance of the current program , but with a custom entry point ( e.g. Slaves , DfindServer , ... ) . Then , alternate entry points should not depend on global references that may not have been ( re)initialised in the new process . All required data must be passed through the typed channels . associated to the spawned process . to Unix specifics parts. This module provides a mechanism to "spawn" new instance of the current program, but with a custom entry point (e.g. Slaves, DfindServer, ...). Then, alternate entry points should not depend on global references that may not have been (re)initialised in the new process. All required data must be passed through the typed channels. associated to the spawned process. *) (* Alternate entry points *) type ('param, 'input, 'output) entry Alternate entry points must be registered at toplevel , i.e. every call to ` Daemon.register_entry_point ` must have been evaluated when ` Daemon.check_entry_point ` is called at the beginning of ` ServerMain.start ` . every call to `Daemon.register_entry_point` must have been evaluated when `Daemon.check_entry_point` is called at the beginning of `ServerMain.start`. *) val register_entry_point : string -> ('param -> ('input, 'output) channel_pair -> unit) -> ('param, 'input, 'output) entry (* Handler upon spawn and forked process. *) type ('in_, 'out) handle = { channels : ('in_, 'out) channel_pair; pid : int; } (* for unit tests *) val devnull : unit -> ('a, 'b) handle val fd_of_path : string -> Unix.file_descr val null_fd : unit -> Unix.file_descr (* Fork and run a function that communicates via the typed channels *) val fork : ?channel_mode:[ `pipe | `socket ] -> (* Where the daemon's output should go *) (Unix.file_descr * Unix.file_descr) -> ('param -> ('input, 'output) channel_pair -> unit) -> 'param -> ('output, 'input) handle (* Spawn a new instance of the current process, and execute the alternate entry point. *) val spawn : ?channel_mode:[ `pipe | `socket ] -> (* Where the daemon's input and output should go *) (Unix.file_descr * Unix.file_descr * Unix.file_descr) -> ('param, 'input, 'output) entry -> 'param -> ('output, 'input) handle (* Close the typed channels associated to a 'spawned' child. *) val close : ('a, 'b) handle -> unit (* Kill a 'spawned' child and close the associated typed channels. *) val kill : ('a, 'b) handle -> unit (* Main function, that execute a alternate entry point. It should be called only once. Just before the main entry point. This function does not return when a custom entry point is selected. *) val check_entry_point : unit -> unit end module String_utils : module type of String_utils module Socket : module type of Socket module Lock : module type of Lock module Marshal_tools : module type of Marshal_tools module Measure : module type of Measure end
null
https://raw.githubusercontent.com/rvantonder/hack_parallel/c9d0714785adc100345835c1989f7c657e01f629/src/interface/hack_parallel_intf.mli
ocaml
The general protocol for a next function is to return either Wait (indicating that workers should wait until more elements are added to the workload), or Job of a bucket, or Done to indicate there is no more work. Makes a bucket out of a list, without regard for number of workers or the size of the list. *************************************************************************** *************************************************************************** *************************************************************************** Initializes the shared memory. Must be called before forking! *************************************************************************** *************************************************************************** *************************************************************************** *************************************************************************** *************************************************************************** *************************************************************************** *************************************************************************** *************************************************************************** *************************************************************************** *************************************************************************** Loads the dependency table by reading from a file *************************************************************************** *************************************************************************** *************************************************************************** *************************************************************************** *************************************************************************** *************************************************************************** Loads the hash table by reading from a file *************************************************************************** *************************************************************************** Cleans up the artifacts generated by SQL *************************************************************************** *************************************************************************** The size of the dynamically allocated shared memory section *************************************************************************** *************************************************************************** Part of the heap not reachable from hashtable entries. *************************************************************************** *************************************************************************** Stats of the statically sized hash / dep tables *************************************************************************** *************************************************************************** *************************************************************************** *************************************************************************** *************************************************************************** Safe for concurrent access. This function takes the elements present in the set and keep the "old" * version in a separate heap. This is useful when we want to compare * what has changed. We will be in a situation for type-checking * (cf typing/typing_redecl_service.ml) where we want to compare the type * of a class in the previous environment vs the current type. Reverse operation of oldify * Raise this exception when sending work to a worker that is already busy. * We should never be doing that, and this is an assertion error. * Raise this exception when sending work to a worker that is already killed. * We should never be doing that, and this is an assertion error. The type of a worker visible to the outside world *************************************************************************** The handle is what we get back when we start a job. It's a "future" * (sometimes called a "promise"). The scheduler uses the handle to retrieve * the result of the job when the task is done (cf multiWorker.ml). *************************************************************************** * Creates a pool of workers. Retrieves the result (once the worker is done) hangs otherwise Selects among multiple handles those which are ready. Returns the worker which produces this handle 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 Bucket above This breaks the type safety, but is necessary in order to allow select() * Spawning new process Alternate entry points Handler upon spawn and forked process. for unit tests Fork and run a function that communicates via the typed channels Where the daemon's output should go Spawn a new instance of the current process, and execute the alternate entry point. Where the daemon's input and output should go Close the typed channels associated to a 'spawned' child. Kill a 'spawned' child and close the associated typed channels. Main function, that execute a alternate entry point. It should be called only once. Just before the main entry point. This function does not return when a custom entry point is selected.
module Std : sig module Bucket : sig type 'a bucket = | Job of 'a | Wait | Done type 'a next = unit -> 'a bucket val of_list : 'a list -> 'a list bucket val make : num_workers:int -> 'a list -> 'a list next type 'a of_n = { work: 'a; bucket: int; total: int } val make_n_buckets : buckets:int -> split:(bucket:int -> 'a) -> 'a of_n next end module SharedMem : sig The heap shared across all the processes . * * The Heap is not exposed directly to the user ( cf shared.mli ) , * because we do n't want to mix values of different types . Instead , we want * to use a functor . * * The Heap is not exposed directly to the user (cf shared.mli), * because we don't want to mix values of different types. Instead, we want * to use a functor. *) type config = { global_size : int; heap_size : int; dep_table_pow : int; hash_table_pow : int; shm_dirs : string list; shm_min_avail : int; log_level : int; } type handle = private { h_fd: Unix.file_descr; h_global_size: int; h_heap_size: int; } exception Out_of_shared_memory exception Hash_table_full exception Dep_table_full exception Heap_full exception Sql_assertion_failure of int exception C_assertion_failure of string val init: config -> handle Connect a slave to the shared heap val connect: handle -> unit The shared memory garbage collector . It must be called every time we * free data ( cf hh_shared.c for the underlying C implementation ) . * free data (cf hh_shared.c for the underlying C implementation). *) val collect: [ `gentle | `aggressive | `always_TEST ] -> unit Must be called after the initialization of the hack server is over . * ( cf ) . * (cf serverInit.ml). *) val init_done: unit -> unit Serializes the dependency table and writes it to a file val save_dep_table_sqlite: string -> string -> int val load_dep_table_sqlite: string -> bool -> int Serializes & loads the hash table directly into memory val save_table: string -> unit val load_table: string -> unit Serializes the hash table to sqlite val save_table_sqlite: string -> int val save_table_keys_sqlite: string -> string array -> int val load_table_sqlite: string -> bool -> int val cleanup_sqlite: unit -> unit val heap_size : unit -> int val wasted_heap_size: unit -> int type table_stats = { nonempty_slots : int; used_slots : int; slots : int; } val dep_stats : unit -> table_stats val hash_stats : unit -> table_stats val is_heap_overflow: unit -> bool Cache invalidation . val invalidate_caches: unit -> unit Size of value in GC heap val value_size: Obj.t -> int The signature of a shared memory hashtable . * To create one : SharedMem . NoCache(struct type = my_type_of_value end ) . * The call to Make will create a hashtable in shared memory ( visible to * all the workers ) . * Use NoCache / WithCache if you want caching or not . * If you do , bear in mind that the cache must be maintained by the caller . * So you will have to invalidate the caches yourself . * To create one: SharedMem.NoCache(struct type = my_type_of_value end). * The call to Make will create a hashtable in shared memory (visible to * all the workers). * Use NoCache/WithCache if you want caching or not. * If you do, bear in mind that the cache must be maintained by the caller. * So you will have to invalidate the caches yourself. *) module type NoCache = sig type key type t module KeySet : Set.S with type elt = key module KeyMap : MyMap.S with type key = key Safe for concurrent writes , the first writer wins , the second write * is dismissed . * is dismissed. *) val add : key -> t -> unit Safe for concurrent reads . Safe for interleaved reads and mutations , * provided the code runs on Intel architectures . * provided the code runs on Intel architectures. *) val get : key -> t option val get_old : key -> t option val get_old_batch : KeySet.t -> t option KeyMap.t val remove_old_batch : KeySet.t -> unit val find_unsafe : key -> t val get_batch : KeySet.t -> t option KeyMap.t val remove_batch : KeySet.t -> unit val string_of_key : key -> string val mem : key -> bool val mem_old : key -> bool val oldify_batch : KeySet.t -> unit val revive_batch : KeySet.t -> unit module LocalChanges : sig val has_local_changes : unit -> bool val push_stack : unit -> unit val pop_stack : unit -> unit val revert_batch : KeySet.t -> unit val commit_batch : KeySet.t -> unit val revert_all : unit -> unit val commit_all : unit -> unit end end module type WithCache = sig include NoCache val write_through : key -> t -> unit val get_no_cache: key -> t option end module type UserKeyType = sig type t val to_string : t -> string val compare : t -> t -> int end module NoCache : functor (UserKeyType : UserKeyType) -> functor (Value:Value.Type) -> NoCache with type t = Value.t and type key = UserKeyType.t and module KeySet = Set.Make (UserKeyType) and module KeyMap = MyMap.Make (UserKeyType) module WithCache : functor (UserKeyType : UserKeyType) -> functor (Value:Value.Type) -> WithCache with type t = Value.t and type key = UserKeyType.t and module KeySet = Set.Make (UserKeyType) and module KeyMap = MyMap.Make (UserKeyType) module type CacheType = sig type key type value val add: key -> value -> unit val get: key -> value option val remove: key -> unit val clear: unit -> unit val string_of_key : key -> string val get_size : unit -> int end module LocalCache : functor (UserKeyType : UserKeyType) -> functor (Value : Value.Type) -> CacheType with type key = UserKeyType.t and type value = Value.t end module Worker : sig exception Worker_exited_abnormally of int * Unix.process_status * Worker killed by Out Of Memory . exception Worker_oomed exception Worker_busy exception Worker_killed type send_job_failure = | Worker_already_exited of Unix.process_status | Other_send_job_failure of exn exception Worker_failed_to_send_job of send_job_failure type t type 'a handle type 'a entry val register_entry_point: restore:('a -> unit) -> 'a entry val make: saved_state : 'a -> entry : 'a entry -> nbr_procs : int -> gc_control : Gc.control -> heap_handle : SharedMem.handle -> t list Call in a sub - process ( CAREFUL , GLOBALS ARE COPIED ) val call: t -> ('a -> 'b) -> 'a -> 'b handle val get_result: 'a handle -> 'a type 'a selected = { readys: 'a handle list; waiters: 'a handle list; } val select: 'a handle list -> 'a selected val get_worker: 'a handle -> t Killall the workers val killall: unit -> unit val current_worker_id: unit -> int end module MultiWorker : sig type 'a nextlist = 'a list Bucket.next val next : Worker.t list option -> 'a list -> 'a list Bucket.next type 'a bucket = 'a 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 Bucket.next -> 'c end module Daemon : sig * Type - safe versions of the channels in Pervasives . type 'a in_channel type 'a out_channel type ('in_, 'out) channel_pair = 'in_ in_channel * 'out out_channel val to_channel : 'a out_channel -> ?flags:Marshal.extern_flags list -> ?flush:bool -> 'a -> unit val from_channel : ?timeout:Timeout.t -> 'a in_channel -> 'a val flush : 'a out_channel -> unit val descr_of_in_channel : 'a in_channel -> Unix.file_descr val descr_of_out_channel : 'a out_channel -> Unix.file_descr val cast_in : 'a in_channel -> Timeout.in_channel val cast_out : 'a out_channel -> Pervasives.out_channel val close_out : 'a out_channel -> unit val output_string : 'a out_channel -> string -> unit val close_in : 'a in_channel -> unit val input_char : 'a in_channel -> char val input_value : 'a in_channel -> 'b In the absence of ' fork ' on Windows , its usage must be restricted to Unix specifics parts . This module provides a mechanism to " spawn " new instance of the current program , but with a custom entry point ( e.g. Slaves , DfindServer , ... ) . Then , alternate entry points should not depend on global references that may not have been ( re)initialised in the new process . All required data must be passed through the typed channels . associated to the spawned process . to Unix specifics parts. This module provides a mechanism to "spawn" new instance of the current program, but with a custom entry point (e.g. Slaves, DfindServer, ...). Then, alternate entry points should not depend on global references that may not have been (re)initialised in the new process. All required data must be passed through the typed channels. associated to the spawned process. *) type ('param, 'input, 'output) entry Alternate entry points must be registered at toplevel , i.e. every call to ` Daemon.register_entry_point ` must have been evaluated when ` Daemon.check_entry_point ` is called at the beginning of ` ServerMain.start ` . every call to `Daemon.register_entry_point` must have been evaluated when `Daemon.check_entry_point` is called at the beginning of `ServerMain.start`. *) val register_entry_point : string -> ('param -> ('input, 'output) channel_pair -> unit) -> ('param, 'input, 'output) entry type ('in_, 'out) handle = { channels : ('in_, 'out) channel_pair; pid : int; } val devnull : unit -> ('a, 'b) handle val fd_of_path : string -> Unix.file_descr val null_fd : unit -> Unix.file_descr val fork : ?channel_mode:[ `pipe | `socket ] -> (Unix.file_descr * Unix.file_descr) -> ('param -> ('input, 'output) channel_pair -> unit) -> 'param -> ('output, 'input) handle val spawn : ?channel_mode:[ `pipe | `socket ] -> (Unix.file_descr * Unix.file_descr * Unix.file_descr) -> ('param, 'input, 'output) entry -> 'param -> ('output, 'input) handle val close : ('a, 'b) handle -> unit val kill : ('a, 'b) handle -> unit val check_entry_point : unit -> unit end module String_utils : module type of String_utils module Socket : module type of Socket module Lock : module type of Lock module Marshal_tools : module type of Marshal_tools module Measure : module type of Measure end
5f07655745c48d4dc557b50820cee577bcc95fd5fde38322b22c80fce8bf0714
gildor478/ocaml-gettext
gettextLocale_types.ml
(**************************************************************************) (* ocaml-gettext: a library to translate messages *) (* *) Copyright ( C ) 2003 - 2008 < > (* *) (* This library is free software; you can redistribute it and/or *) (* modify it under the terms of the GNU Lesser General Public *) License as published by the Free Software Foundation ; either version 2.1 of the License , or ( at your option ) any later version ; (* with the OCaml static compilation exception. *) (* *) (* This library is distributed in the hope that it will be useful, *) (* but WITHOUT ANY WARRANTY; without even the implied warranty of *) (* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *) (* Lesser General Public License for more details. *) (* *) You should have received a copy of the GNU Lesser General Public License along with this library ; if not , write to the Free Software Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA (**************************************************************************) * @author @author Sylvain Le Gall *) type locale = { language : string; territory : string option; codeset : string option; modifier : string option; } let create_locale language = { language; territory = None; codeset = None; modifier = None }
null
https://raw.githubusercontent.com/gildor478/ocaml-gettext/9b7afc702bccace9a544b8efa2a28bc2b13371ed/src/lib/gettext/extension/gettextLocale_types.ml
ocaml
************************************************************************ ocaml-gettext: a library to translate messages This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public with the OCaml static compilation exception. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ************************************************************************
Copyright ( C ) 2003 - 2008 < > License as published by the Free Software Foundation ; either version 2.1 of the License , or ( at your option ) any later version ; You should have received a copy of the GNU Lesser General Public License along with this library ; if not , write to the Free Software Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA * @author @author Sylvain Le Gall *) type locale = { language : string; territory : string option; codeset : string option; modifier : string option; } let create_locale language = { language; territory = None; codeset = None; modifier = None }
138e7f3ba33863ba57e71c7c6ad70944e91794231fa0b33f92331bb9fa157fab
simplex-chat/simplexmq
M20220915_connection_queues.hs
# LANGUAGE QuasiQuotes # module Simplex.Messaging.Agent.Store.SQLite.Migrations.M20220915_connection_queues where import Database.SQLite.Simple (Query) import Database.SQLite.Simple.QQ (sql) m20220915_connection_queues :: Query m20220915_connection_queues = [sql| PRAGMA ignore_check_constraints=ON; -- rcv_queues ALTER TABLE rcv_queues ADD COLUMN rcv_queue_id INTEGER CHECK (rcv_queue_id NOT NULL); UPDATE rcv_queues SET rcv_queue_id = 1; CREATE UNIQUE INDEX idx_rcv_queue_id ON rcv_queues (conn_id, rcv_queue_id); ALTER TABLE rcv_queues ADD COLUMN rcv_primary INTEGER CHECK (rcv_primary NOT NULL); UPDATE rcv_queues SET rcv_primary = 1; ALTER TABLE rcv_queues ADD COLUMN replace_rcv_queue_id INTEGER NULL; -- snd_queues ALTER TABLE snd_queues ADD COLUMN snd_queue_id INTEGER CHECK (snd_queue_id NOT NULL); UPDATE snd_queues SET snd_queue_id = 1; CREATE UNIQUE INDEX idx_snd_queue_id ON snd_queues (conn_id, snd_queue_id); ALTER TABLE snd_queues ADD COLUMN snd_primary INTEGER CHECK (snd_primary NOT NULL); UPDATE snd_queues SET snd_primary = 1; ALTER TABLE snd_queues ADD COLUMN replace_snd_queue_id INTEGER NULL; -- connections ALTER TABLE connections ADD COLUMN deleted INTEGER DEFAULT 0 CHECK (deleted NOT NULL); UPDATE connections SET deleted = 0; -- messages CREATE TABLE snd_message_deliveries ( snd_message_delivery_id INTEGER PRIMARY KEY AUTOINCREMENT, conn_id BLOB NOT NULL REFERENCES connections ON DELETE CASCADE, snd_queue_id INTEGER NOT NULL, internal_id INTEGER NOT NULL, FOREIGN KEY (conn_id, internal_id) REFERENCES messages ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED ); CREATE INDEX idx_snd_message_deliveries ON snd_message_deliveries (conn_id, snd_queue_id); ALTER TABLE rcv_messages ADD COLUMN rcv_queue_id INTEGER CHECK (rcv_queue_id NOT NULL); UPDATE rcv_messages SET rcv_queue_id = 1; PRAGMA ignore_check_constraints=OFF; |]
null
https://raw.githubusercontent.com/simplex-chat/simplexmq/8f9e6c2112c21cba3a29889d0fce3b161f137a76/src/Simplex/Messaging/Agent/Store/SQLite/Migrations/M20220915_connection_queues.hs
haskell
rcv_queues snd_queues connections messages
# LANGUAGE QuasiQuotes # module Simplex.Messaging.Agent.Store.SQLite.Migrations.M20220915_connection_queues where import Database.SQLite.Simple (Query) import Database.SQLite.Simple.QQ (sql) m20220915_connection_queues :: Query m20220915_connection_queues = [sql| PRAGMA ignore_check_constraints=ON; ALTER TABLE rcv_queues ADD COLUMN rcv_queue_id INTEGER CHECK (rcv_queue_id NOT NULL); UPDATE rcv_queues SET rcv_queue_id = 1; CREATE UNIQUE INDEX idx_rcv_queue_id ON rcv_queues (conn_id, rcv_queue_id); ALTER TABLE rcv_queues ADD COLUMN rcv_primary INTEGER CHECK (rcv_primary NOT NULL); UPDATE rcv_queues SET rcv_primary = 1; ALTER TABLE rcv_queues ADD COLUMN replace_rcv_queue_id INTEGER NULL; ALTER TABLE snd_queues ADD COLUMN snd_queue_id INTEGER CHECK (snd_queue_id NOT NULL); UPDATE snd_queues SET snd_queue_id = 1; CREATE UNIQUE INDEX idx_snd_queue_id ON snd_queues (conn_id, snd_queue_id); ALTER TABLE snd_queues ADD COLUMN snd_primary INTEGER CHECK (snd_primary NOT NULL); UPDATE snd_queues SET snd_primary = 1; ALTER TABLE snd_queues ADD COLUMN replace_snd_queue_id INTEGER NULL; ALTER TABLE connections ADD COLUMN deleted INTEGER DEFAULT 0 CHECK (deleted NOT NULL); UPDATE connections SET deleted = 0; CREATE TABLE snd_message_deliveries ( snd_message_delivery_id INTEGER PRIMARY KEY AUTOINCREMENT, conn_id BLOB NOT NULL REFERENCES connections ON DELETE CASCADE, snd_queue_id INTEGER NOT NULL, internal_id INTEGER NOT NULL, FOREIGN KEY (conn_id, internal_id) REFERENCES messages ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED ); CREATE INDEX idx_snd_message_deliveries ON snd_message_deliveries (conn_id, snd_queue_id); ALTER TABLE rcv_messages ADD COLUMN rcv_queue_id INTEGER CHECK (rcv_queue_id NOT NULL); UPDATE rcv_messages SET rcv_queue_id = 1; PRAGMA ignore_check_constraints=OFF; |]
068a9ef5fd7697cde72f26679857f5739f4a1a97de5f2a108ec1c52b5209b3c5
tonyrog/edrone
edrone_control.erl
%%%------------------------------------------------------------------- @author magnus < magnus@t520 > ( C ) 2013 , magnus %%% @doc %%% %%% @end Created : 24 Sep 2013 by magnus < magnus@t520 > %%%------------------------------------------------------------------- -module(edrone_control). -behaviour(gen_server). %% API -export([start_link/0]). -include("nav.hrl"). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -export([flat_trim/0, enable/0, disable/0]). -define(SERVER, ?MODULE). 1.0 0.25 0.3 WORKS -define(PID_P, 0.75). -define(PID_I, 0.25). -define(PID_D, 0.2). Rampup / rampdown per second Rampup / rampdown per second Rampup / rampdown per second altitude , in cm . Rampup / rampdown - cm / per second Sync gyro dead reconning to accelerometers every 3 seconds . -define(UDP_PORT, 4509). -define(PITCH_CMD, 16#0001). -define(ROLL_CMD, 16#0002). -define(YAW_CMD, 16#0003). -define(THROTTLE_CMD, 16#0004). -define(PITCH_TRIM_CMD, 16#0005). -define(ROLL_TRIM_CMD, 16#0006). -define(YAW_TRIM_CMD, 16#0007). -define(UPGRADE_CMD, 16#0008). -define(ALT_LOCK_CMD, 16#0009). -define(MAX_CMD_VAL, 16#3FF). %% SET THIS VALUE TO -1 FOR GLITCH FREE OPERATION %% SET THIS VALUE TO 0 FOR GLITCHY OPERATION -define(HAVE_GLITCH, -1). %% 0 = glitchy. -1 = not glitchy %% -define(HAVE_GLITCH, 0). %% 0 = glitchy. -1 = not glitchy -record(st, { udp_sock = undefined, pitch_input = 0.0, roll_input = 0.0, yaw_input = 0.0, throttle_input = 0.0, pitch_trim_input = 0.0, roll_trim_input = 0.0, yaw_trim_input = 0.0, enabled = false, yaw_enabled = false, %% Don't try to do yaw before we are off the ground. alt_lock_pid = undefined, %% Only in use when we have altitude lock. uart = undefined, pwm_pid = undefined, nav_recv_ref = undefined, flat_trim = #flat_trim{ Flat trim for ' drone ax_offset=2058.5, ay_offset=2034.34, az_offset=2438.22, gx_offset=-15.15, gy_offset=2.16, gz_offset=-14.62 }, %% Flat trim calibration data Timestamp of last reveived navboard data . Timestamp of last sync between gyro and acceleromoeter ramp_pos = #position{}, %% Our position as is being ramped toward target_pos target_pos = #position{}, %% Our desired target position current_pos = #position{}, %% Our desired target position Motor throttling ( 0.0 - 1.0 ) pidctl = { undefined, undefined, undefined, undefined }, acc_lowpass = { undefined, undefined, undefined }, alt_lowpass = undefined, gyro_lowpass = { undefined, undefined, undefined }, glitch_count = ?HAVE_GLITCH }). %%%=================================================================== %%% API %%%=================================================================== %%-------------------------------------------------------------------- %% @doc %% Starts the server %% ( ) - > { ok , Pid } | ignore | { error , Error } %% @end %%-------------------------------------------------------------------- start_link() -> gen_server:start_link({local, ?SERVER}, ?MODULE, [], []). %%%=================================================================== %%% gen_server callbacks %%%=================================================================== %%-------------------------------------------------------------------- @private %% @doc %% Initializes the server %% ) - > { ok , St } | %% {ok, St, Timeout} | %% ignore | %% {stop, Reason} %% @end %%-------------------------------------------------------------------- init([]) -> Setup communication . Pid = edrone_motor:start(), random:seed(), i2c:start(), edrone_bat:init(), io:format("~n~nBat: ~f~n~n", [edrone_bat:read()]), %% Use our target port as the source as well {ok, UDPSocket } = gen_udp:open(?UDP_PORT, [ binary ]), {ok, Uart} = edrone_navboard:init(), {ok, #st { uart = Uart, pwm_pid = Pid, udp_sock = UDPSocket, pidctl = { edrone_pid:new(?PID_P, ?PID_I, ?PID_D, -1.0, 1.0), edrone_pid:new(?PID_P, ?PID_I, ?PID_D, -1.0, 1.0), edrone_pid:new(?PID_P, ?PID_I, ?PID_D, -1.0, 1.0), edrone_pid:new(?PID_P, ?PID_I, ?PID_D, -1.0, 1.0) } } }. flat_trim() -> gen_server:call(?MODULE, flat_trim). enable() -> gen_server:call(?MODULE, enable). disable() -> gen_server:call(?MODULE, flat_trim). %%-------------------------------------------------------------------- @private %% @doc %% Handling call messages %% , From , St ) - > %% {reply, Reply, St} | %% {reply, Reply, St, Timeout} | { noreply , St } | { noreply , St , Timeout } | %% {stop, Reason, Reply, St} | %% {stop, Reason, St} %% @end %-------------------------------------------------------------------- %% flat_trim must be called before we call enable handle_call(flat_trim, _From, St) -> case edrone_navboard:flat_trim(St#st.uart) of { ok, FlatTrim } -> { reply, ok, St#st { flat_trim = FlatTrim }}; { error, Reason }-> { reply, {error, Reason }, St }; Unknown -> { reply, { error, Unknown }, St } end; %% We need a flat trim before we can enable system handle_call(enable, _From, St) when St#st.flat_trim =:= undefined -> { reply, { error, no_flat_trim }, St }; %% Enable so that we get a message when a packet is read by uart. handle_call(enable, _From, St) -> {ok, RecvRef } = edrone_navboard:enable_frame_report(St#st.uart), { reply, ok, St#st { enabled = true, nav_recv_ref = RecvRef, nav_ts = edrone_lib:timestamp() } }; %% Disable the frame stream from the nav board handle_call(disable, _From, St) when St#st.enabled =:= true-> edrone:set_pwm_norm(St#st.pwm_pid, 0.0, 0.0, 0.0, 0.0), { reply, ok, St#st { enabled = false } }; handle_call(_Request, _From, St) -> Reply = ok, {reply, Reply, St}. %%-------------------------------------------------------------------- @private %% @doc %% Handling cast messages %% @spec handle_cast(Msg , St ) - > { noreply , St } | { noreply , St , Timeout } | %% {stop, Reason, St} %% @end %%-------------------------------------------------------------------- handle_cast(_Msg, St) -> {noreply, St}. %%-------------------------------------------------------------------- @private %% @doc %% Handling all non call/cast messages %% , St ) - > { noreply , St } | { noreply , St , Timeout } | %% {stop, Reason, St} %% @end %%-------------------------------------------------------------------- handle_info({uart_async, Uart, RecvRef, Data} , St) when St#st.uart =:= Uart, St#st.nav_recv_ref =:= RecvRef -> NSt = case edrone_navboard:decode_nav_data(Data) of { ok, #nav_frame{} = NavFrame } -> %% Process the nav frame to a nav state NavState = edrone_navboard:process_nav_frame(NavFrame, St#st.flat_trim), FIXME : INSERT SIGNAL FILTER CALL HERE %% Process the position and return its new state. process_nav_state(St, NavState); Checksum error . Resync stream { error, checksum } -> case edrone_navboard:sync_stream(St#st.uart, 100) of ok -> St; { error, Err } -> io:format("FAILED TO SYNC NAVBOARD STREAM: ~p~n", [ Err] ), St#st { enabled = false } end end, %% If we are still enabled, re-arm the uart to deliver the next frame. Ref = if NSt#st.enabled =:= true -> {ok, R } = edrone_navboard:enable_frame_report(NSt#st.uart), R; true -> undefined end, { noreply, NSt#st { nav_recv_ref = Ref }}; handle_info({uart_error, Uart, Reason} , St) when Uart =:= St#st.uart -> io:format("UART ERROR: ~p~n", [ Reason ]), { noreply, St#st {enabled = false} }; handle_info({udp, Sock, _, _, <<Cmd:6/unsigned, Val:10/unsigned>>} , St) when Sock =:= St#st.udp_sock -> { noreply, decode_input(Cmd, Val, St) }; handle_info(Info, St) -> io:format("handle_info()??: ~p~n", [ Info ]), {noreply, St}. %%-------------------------------------------------------------------- @private %% @doc %% This function is called by a gen_server when it is about to %% terminate. It should be the opposite of Module:init/1 and do any %% necessary cleaning up. When it returns, the gen_server terminates with . The return value is ignored . %% ) - > void ( ) %% @end %%-------------------------------------------------------------------- terminate(_Reason, _St) -> ok. %%-------------------------------------------------------------------- @private %% @doc Convert process st when code is changed %% , St , Extra ) - > { ok , NewSt } %% @end %%-------------------------------------------------------------------- %% Enable so that we get a message when a packet is read by uart. code_change(_OldVsn, St, _Extra) when St#st.enabled =:= true-> io:format("Code upgrade.~n"), { ok, St#st {glitch_count = ?HAVE_GLITCH }}. %%%=================================================================== Internal functions %%%=================================================================== %% process_nav_state(#st{ nav_ts = PrevTS, current_pos = CurPos, target_pos = TgtPos, acc_gyro_sync_ts = AccGyroSyncTS, ramp_pos = RPos } = St, #nav_state{ } = NavState) -> %% Timestamp delta ( sec ) between last nav state update , and this nav state %% TSDelta = (NavState#nav_state.timestamp - PrevTS) / 1000000.0, { AccPitchLP, AccRollLP, AccYawLP } = St#st.acc_lowpass, Accelerometer data { _AccPitch, NAccPitchLP } = lowpass_filter(AccPitchLP, NavState#nav_state.ax), { _AccRoll, NAccRollLP} = lowpass_filter(AccRollLP, NavState#nav_state.ay), { _AccYaw, NAccYawLP} = lowpass_filter(AccYawLP, NavState#nav_state.az), {Alt, NAltLP} = lowpass_filter(St#st.alt_lowpass, NavState#nav_state.alt), Gyro data . { GyroPitchLP, GyroRollLP, GyroYawLP } = St#st.gyro_lowpass, { GyroPitch , NGyroPitchLP } = lowpass_filter(GyroPitchLP , NavState#nav_state.gx ) , , NGyroRollLP } = lowpass_filter(GyroRollLP , NavState#nav_state.gy ) , %% { GyroYaw, NGyroYawLP } = lowpass_filter(GyroYawLP, -NavState#nav_state.gz), { GyroPitch, NGyroPitchLP } = { -NavState#nav_state.gy, GyroPitchLP }, { GyroRoll, NGyroRollLP } = { NavState#nav_state.gx, GyroRollLP }, { GyroYaw, NGyroYawLP } = { -NavState#nav_state.gz, GyroYawLP}, %% Update our current spatial position NCurPos =#position { alt = Alt, pitch = CurPos#position.pitch + GyroPitch * TSDelta, roll = CurPos#position.roll + GyroRoll * TSDelta, yaw = CurPos#position.yaw + GyroYaw * TSDelta }, Enable yaw only if altitude is greater than 30 cm . %% Enable yaw if we see a "jump" in z accelerometer as we leave the ground. YawEnabled = if St#st.yaw_enabled =:= true -> true; St#st.throttle_input < 0.02 -> io:format("Yaw disabled~n"), false; St#st.throttle_input > 0.4 -> io:format("Yaw enabled~n"), true; true -> false end, NTgtPos = if YawEnabled =:= true -> TgtPos#position { yaw = TgtPos#position.yaw + St#st.yaw_input * TSDelta }; true -> TgtPos#position { yaw = NCurPos#position.yaw } %% Let target follow current end, %% %% Calculate new ramp position, which wanders at a set max speed %% toward the target position. %% NRampPos = ramp_position(RPos, NTgtPos, TSDelta), { NAltLockPid, M1, NPids } = calculate_motors(St#st.pidctl, NCurPos, NRampPos, St#st.throttle_input, St#st.alt_lock_pid), %% Cut off the motors if we are under 0.02 throttle %% M2 = if St#st.throttle_input < 0.02 -> { 0.0, 0.0, 0.0, 0.0 }; true -> M1 end, %% Artificially introduce a glitch {GlitchCount, M3} = case glitch(St#st.glitch_count) of -1 -> %% Glitch deactivated. { -1, edrone_motor:set_pwm_norm(St#st.pwm_pid, M2) }; 0 -> %% Currently no glitch { 0, edrone_motor:set_pwm_norm(St#st.pwm_pid, M2) }; Cnt -> %% Glitch in progress { Cnt, edrone_motor:set_pwm_norm(St#st.pwm_pid, {0.01, 0.01, 0.01, 0.01}) } end, St#st { motor = M3, pidctl = NPids, alt_lock_pid = NAltLockPid, yaw_enabled = YawEnabled, ramp_pos = NRampPos, current_pos = NCurPos, target_pos = NTgtPos, gyro_lowpass = { NGyroPitchLP, NGyroRollLP, NGyroYawLP }, acc_lowpass = { NAccPitchLP, NAccRollLP, NAccYawLP }, WILL NOT WORK . Sonar works at 26+CM only . nav_ts = NavState#nav_state.timestamp, acc_gyro_sync_ts = AccGyroSyncTS, %% Not used yet. glitch_count = GlitchCount}. glitch(-1) -> -1; glitch(0) -> case random:uniform(100) of 1 -> io:format("Glitch!~n"), 10; _ -> 0 end; glitch(Count) -> Count - 1. calculate_motors({P0, P1, P2, P3}, CurPos, TgtPos, Throttle, AltLockPid) -> YawDelta = TgtPos#position.yaw - CurPos#position.yaw, %% Calculate the current position of each corner of the drone. CM0 = cap(CurPos#position.pitch + CurPos#position.roll, -1.0, 1.0), CM1 = cap(CurPos#position.pitch - CurPos#position.roll, -1.0, 1.0), CM2 = cap(-CurPos#position.pitch - CurPos#position.roll, -1.0, 1.0), CM3 = cap(-CurPos#position.pitch + CurPos#position.roll, -1.0, 1.0), %% Calculate the desired position of each corner of the drone. TM0 = cap(TgtPos#position.pitch + TgtPos#position.roll - YawDelta, -1.0, 1.0), TM1 = cap(TgtPos#position.pitch - TgtPos#position.roll + YawDelta, -1.0, 1.0), TM2 = cap(-TgtPos#position.pitch - TgtPos#position.roll - YawDelta, -1.0, 1.0), TM3 = cap(-TgtPos#position.pitch + TgtPos#position.roll + YawDelta, -1.0, 1.0), %% io:format("P(~-7.4f|~-7.4f) R(~-7.4f|~-7.4f) Yaw(~-7.4f|~-7.4f) CM(~-7.4f|~-7.4f|~-7.4f|~-7.4f) TM(~-7.4f|~-7.4f|~-7.4f|~-7.4f)~n", %% [ CurPos#position.pitch, TgtPos#position.pitch, CurPos#position.roll , TgtPos#position.roll , %% TgtPos#position.yaw, CurPos#position.yaw, %% CM0, CM1, CM2, CM3, TM0 - CM0 , TM1 - CM1 , TM2 - CM2 , TM3 - CM3 ] ) , %% Set the new target point for each motor, and then calculate %% a motor output to add to the baseline. PidTS = edrone_pid:timestamp(), %% io:format("P("), { NM0, NP0 } = edrone_pid:update(edrone_pid:set_point(P0, TM0), CM0, PidTS), { NM1, NP1 } = edrone_pid:update(edrone_pid:set_point(P1, TM1), CM1, PidTS), { NM2, NP2 } = edrone_pid:update(edrone_pid:set_point(P2, TM2), CM2, PidTS), { NM3, NP3 } = edrone_pid:update(edrone_pid:set_point(P3, TM3), CM3, PidTS), %% io:format(") "), %% io:format("~n"), If altitude lock is off , we just use throttle ( 0.0 - 1.0 ) %% If altitude lock is set, we use a proportional adjuster, with caps { AltAdd, NAltLockPid } = case AltLockPid of undefined -> { 0.0 , undefined }; _ -> edrone_pid:update(AltLockPid, CurPos#position.alt / ?MAX_ALT, PidTS) end, { NAltLockPid, { NM0 + AltAdd + Throttle, NM1 + AltAdd + Throttle, NM2 + AltAdd + Throttle, NM3 + AltAdd + Throttle}, { NP0, NP1, NP2, NP3 } }. lowpass_filter({V0, V1, V2}, Val) -> NV = V0 * 0.25 + V1 * 0.25 + V2 * 0.25 + %% V3 * 0.16666666 + %% V4 * 0.16666666 + Val * 0.25, {NV, { V1, V2, Val } }; lowpass_filter(_, Val) -> {Val, { Val, Val, Val } }. ramp_position(RPos, TPos, TSDelta) -> RPos#position { pitch = ramp_position_(RPos#position.pitch, TPos#position.pitch, ?PITCH_RAMP, TSDelta), roll = ramp_position_(RPos#position.roll, TPos#position.roll, ?ROLL_RAMP, TSDelta), yaw = ramp_position_(RPos#position.yaw, TPos#position.yaw, ?YAW_RAMP, TSDelta) %% Altitude is not part of ramp position. }. ramp_position_(Ramp, Target, Max, TSDelta) when Ramp > Target + Max * TSDelta-> io : format("-T(~f ) R(~f ) TSDelta(~f ) Max(~f)~n " , [ Target , Ramp , TSDelta , ] ) , Ramp - Max * TSDelta; ramp_position_(Ramp, Target, Max, TSDelta) when Ramp < Target - Max * TSDelta -> io : format("+T(~f ) R(~f ) TSDelta(~f ) Max(~f)~n " , [ Target , Ramp , TSDelta , ] ) , Ramp + Max * TSDelta; ramp_position_(_Ramp, Target, _Max, _TSDelta) -> io : format("-=T(~f ) R(~f ) TSDelta(~f ) ) ~f ~ n " , [ Target , Ramp , TSDelta , , TSDelta * ] ) , Target. cap(Val, Min, Max) -> min(max(Val, Min), Max). decode_input(?PITCH_CMD, Val, #st {target_pos = TgtPos} = St) -> Inp = convert_input_value(Val), %% io:format("Pitch: ~-7.4f~n", [Inp]), St#st { pitch_input = Inp, target_pos = TgtPos#position {pitch = Inp / 10.0}}; decode_input(?ROLL_CMD, Val, #st {target_pos = TgtPos} = St) -> Inp = convert_input_value(Val), %% io:format(" Roll: ~-7.4f~n", [Inp]), St#st { roll_input = Inp, target_pos = TgtPos#position {roll = Inp / 10.0}}; decode_input(?YAW_CMD, Val, St) -> Inp = convert_input_value(Val), io : format ( " : ~p/~-7.4f ~ n " , [ , ] ) , St#st { yaw_input = Inp / 3}; decode_input(?THROTTLE_CMD, Val, St) when St#st.alt_lock_pid =:= undefined-> Inp = Val / ?MAX_CMD_VAL, %% io:format(" Throttle: ~-7.4f~n", [Inp]), St#st { throttle_input = Inp }; %% Don't react to throttle when in alt lock mode decode_input(?THROTTLE_CMD, _Val, St) -> St; decode_input(?PITCH_TRIM_CMD, Val, St) -> Inp = convert_input_value(Val), io:format("---- PitchTrim: ~-7.4f~n", [Inp]), St#st { pitch_trim_input = Inp }; decode_input(?ROLL_TRIM_CMD, Val, St) -> Inp = convert_input_value(Val), io:format("---- RollTrim: ~-7.4f~n", [Inp]), St#st { roll_trim_input = Inp }; decode_input(?YAW_TRIM_CMD, Val, St) -> Inp = convert_input_value(Val), io:format("---- YawTrim: ~-7.4f~n", [Inp]), St#st { roll_trim_input = Inp }; decode_input(?UPGRADE_CMD, _Val, St) -> io:format("UPGRADE TIME!~n"), gen_server:cast(edrone_upgrade, { upgrade, ?MODULE }), St; decode_input(?ALT_LOCK_CMD, 1, St) -> io:format("Altitude Lock: Engaged!~n"), AltPid = edrone_pid:set_point(edrone_pid:new(?PID_P, ?PID_I, ?PID_D, -1.0, 1.0), Alttitude lock St#st { alt_lock_pid = AltPid }; decode_input(?ALT_LOCK_CMD, 0, St) -> io:format("Altitude Disengaged!~n"), St#st { alt_lock_pid = undefined }; decode_input(ErrKey, ErrVal, St)-> io:format("---- Unknown key(~p) val(~p)~n", [ErrKey, ErrVal]), St. convert_input_value(Val) -> (Val / ?MAX_CMD_VAL) * 2 - 1.
null
https://raw.githubusercontent.com/tonyrog/edrone/ca8d2e2da75b064619697a1f4e53584051c23fca/src/edrone_control.erl
erlang
------------------------------------------------------------------- @doc @end ------------------------------------------------------------------- API gen_server callbacks SET THIS VALUE TO -1 FOR GLITCH FREE OPERATION SET THIS VALUE TO 0 FOR GLITCHY OPERATION 0 = glitchy. -1 = not glitchy -define(HAVE_GLITCH, 0). %% 0 = glitchy. -1 = not glitchy Don't try to do yaw before we are off the ground. Only in use when we have altitude lock. Flat trim calibration data Our position as is being ramped toward target_pos Our desired target position Our desired target position =================================================================== API =================================================================== -------------------------------------------------------------------- @doc Starts the server @end -------------------------------------------------------------------- =================================================================== gen_server callbacks =================================================================== -------------------------------------------------------------------- @doc Initializes the server {ok, St, Timeout} | ignore | {stop, Reason} @end -------------------------------------------------------------------- Use our target port as the source as well -------------------------------------------------------------------- @doc Handling call messages {reply, Reply, St} | {reply, Reply, St, Timeout} | {stop, Reason, Reply, St} | {stop, Reason, St} @end -------------------------------------------------------------------- flat_trim must be called before we call enable We need a flat trim before we can enable system Enable so that we get a message when a packet is read by uart. Disable the frame stream from the nav board -------------------------------------------------------------------- @doc Handling cast messages {stop, Reason, St} @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc Handling all non call/cast messages {stop, Reason, St} @end -------------------------------------------------------------------- Process the nav frame to a nav state Process the position and return its new state. If we are still enabled, re-arm the uart to deliver the next frame. -------------------------------------------------------------------- @doc This function is called by a gen_server when it is about to terminate. It should be the opposite of Module:init/1 and do any necessary cleaning up. When it returns, the gen_server terminates @end -------------------------------------------------------------------- -------------------------------------------------------------------- @doc @end -------------------------------------------------------------------- Enable so that we get a message when a packet is read by uart. =================================================================== =================================================================== { GyroYaw, NGyroYawLP } = lowpass_filter(GyroYawLP, -NavState#nav_state.gz), Update our current spatial position Enable yaw if we see a "jump" in z accelerometer as we leave the ground. Let target follow current Calculate new ramp position, which wanders at a set max speed toward the target position. Artificially introduce a glitch Glitch deactivated. Currently no glitch Glitch in progress Not used yet. Calculate the current position of each corner of the drone. Calculate the desired position of each corner of the drone. io:format("P(~-7.4f|~-7.4f) R(~-7.4f|~-7.4f) Yaw(~-7.4f|~-7.4f) CM(~-7.4f|~-7.4f|~-7.4f|~-7.4f) TM(~-7.4f|~-7.4f|~-7.4f|~-7.4f)~n", [ CurPos#position.pitch, TgtPos#position.pitch, TgtPos#position.yaw, CurPos#position.yaw, CM0, CM1, CM2, CM3, Set the new target point for each motor, and then calculate a motor output to add to the baseline. io:format("P("), io:format(") "), io:format("~n"), If altitude lock is set, we use a proportional adjuster, with caps V3 * 0.16666666 + V4 * 0.16666666 + Altitude is not part of ramp position. io:format("Pitch: ~-7.4f~n", [Inp]), io:format(" Roll: ~-7.4f~n", [Inp]), io:format(" Throttle: ~-7.4f~n", [Inp]), Don't react to throttle when in alt lock mode
@author magnus < magnus@t520 > ( C ) 2013 , magnus Created : 24 Sep 2013 by magnus < magnus@t520 > -module(edrone_control). -behaviour(gen_server). -export([start_link/0]). -include("nav.hrl"). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -export([flat_trim/0, enable/0, disable/0]). -define(SERVER, ?MODULE). 1.0 0.25 0.3 WORKS -define(PID_P, 0.75). -define(PID_I, 0.25). -define(PID_D, 0.2). Rampup / rampdown per second Rampup / rampdown per second Rampup / rampdown per second altitude , in cm . Rampup / rampdown - cm / per second Sync gyro dead reconning to accelerometers every 3 seconds . -define(UDP_PORT, 4509). -define(PITCH_CMD, 16#0001). -define(ROLL_CMD, 16#0002). -define(YAW_CMD, 16#0003). -define(THROTTLE_CMD, 16#0004). -define(PITCH_TRIM_CMD, 16#0005). -define(ROLL_TRIM_CMD, 16#0006). -define(YAW_TRIM_CMD, 16#0007). -define(UPGRADE_CMD, 16#0008). -define(ALT_LOCK_CMD, 16#0009). -define(MAX_CMD_VAL, 16#3FF). -record(st, { udp_sock = undefined, pitch_input = 0.0, roll_input = 0.0, yaw_input = 0.0, throttle_input = 0.0, pitch_trim_input = 0.0, roll_trim_input = 0.0, yaw_trim_input = 0.0, enabled = false, uart = undefined, pwm_pid = undefined, nav_recv_ref = undefined, flat_trim = #flat_trim{ Flat trim for ' drone ax_offset=2058.5, ay_offset=2034.34, az_offset=2438.22, gx_offset=-15.15, gy_offset=2.16, gz_offset=-14.62 Timestamp of last reveived navboard data . Timestamp of last sync between gyro and acceleromoeter Motor throttling ( 0.0 - 1.0 ) pidctl = { undefined, undefined, undefined, undefined }, acc_lowpass = { undefined, undefined, undefined }, alt_lowpass = undefined, gyro_lowpass = { undefined, undefined, undefined }, glitch_count = ?HAVE_GLITCH }). ( ) - > { ok , Pid } | ignore | { error , Error } start_link() -> gen_server:start_link({local, ?SERVER}, ?MODULE, [], []). @private ) - > { ok , St } | init([]) -> Setup communication . Pid = edrone_motor:start(), random:seed(), i2c:start(), edrone_bat:init(), io:format("~n~nBat: ~f~n~n", [edrone_bat:read()]), {ok, UDPSocket } = gen_udp:open(?UDP_PORT, [ binary ]), {ok, Uart} = edrone_navboard:init(), {ok, #st { uart = Uart, pwm_pid = Pid, udp_sock = UDPSocket, pidctl = { edrone_pid:new(?PID_P, ?PID_I, ?PID_D, -1.0, 1.0), edrone_pid:new(?PID_P, ?PID_I, ?PID_D, -1.0, 1.0), edrone_pid:new(?PID_P, ?PID_I, ?PID_D, -1.0, 1.0), edrone_pid:new(?PID_P, ?PID_I, ?PID_D, -1.0, 1.0) } } }. flat_trim() -> gen_server:call(?MODULE, flat_trim). enable() -> gen_server:call(?MODULE, enable). disable() -> gen_server:call(?MODULE, flat_trim). @private , From , St ) - > { noreply , St } | { noreply , St , Timeout } | handle_call(flat_trim, _From, St) -> case edrone_navboard:flat_trim(St#st.uart) of { ok, FlatTrim } -> { reply, ok, St#st { flat_trim = FlatTrim }}; { error, Reason }-> { reply, {error, Reason }, St }; Unknown -> { reply, { error, Unknown }, St } end; handle_call(enable, _From, St) when St#st.flat_trim =:= undefined -> { reply, { error, no_flat_trim }, St }; handle_call(enable, _From, St) -> {ok, RecvRef } = edrone_navboard:enable_frame_report(St#st.uart), { reply, ok, St#st { enabled = true, nav_recv_ref = RecvRef, nav_ts = edrone_lib:timestamp() } }; handle_call(disable, _From, St) when St#st.enabled =:= true-> edrone:set_pwm_norm(St#st.pwm_pid, 0.0, 0.0, 0.0, 0.0), { reply, ok, St#st { enabled = false } }; handle_call(_Request, _From, St) -> Reply = ok, {reply, Reply, St}. @private @spec handle_cast(Msg , St ) - > { noreply , St } | { noreply , St , Timeout } | handle_cast(_Msg, St) -> {noreply, St}. @private , St ) - > { noreply , St } | { noreply , St , Timeout } | handle_info({uart_async, Uart, RecvRef, Data} , St) when St#st.uart =:= Uart, St#st.nav_recv_ref =:= RecvRef -> NSt = case edrone_navboard:decode_nav_data(Data) of { ok, #nav_frame{} = NavFrame } -> NavState = edrone_navboard:process_nav_frame(NavFrame, St#st.flat_trim), FIXME : INSERT SIGNAL FILTER CALL HERE process_nav_state(St, NavState); Checksum error . Resync stream { error, checksum } -> case edrone_navboard:sync_stream(St#st.uart, 100) of ok -> St; { error, Err } -> io:format("FAILED TO SYNC NAVBOARD STREAM: ~p~n", [ Err] ), St#st { enabled = false } end end, Ref = if NSt#st.enabled =:= true -> {ok, R } = edrone_navboard:enable_frame_report(NSt#st.uart), R; true -> undefined end, { noreply, NSt#st { nav_recv_ref = Ref }}; handle_info({uart_error, Uart, Reason} , St) when Uart =:= St#st.uart -> io:format("UART ERROR: ~p~n", [ Reason ]), { noreply, St#st {enabled = false} }; handle_info({udp, Sock, _, _, <<Cmd:6/unsigned, Val:10/unsigned>>} , St) when Sock =:= St#st.udp_sock -> { noreply, decode_input(Cmd, Val, St) }; handle_info(Info, St) -> io:format("handle_info()??: ~p~n", [ Info ]), {noreply, St}. @private with . The return value is ignored . ) - > void ( ) terminate(_Reason, _St) -> ok. @private Convert process st when code is changed , St , Extra ) - > { ok , NewSt } code_change(_OldVsn, St, _Extra) when St#st.enabled =:= true-> io:format("Code upgrade.~n"), { ok, St#st {glitch_count = ?HAVE_GLITCH }}. Internal functions process_nav_state(#st{ nav_ts = PrevTS, current_pos = CurPos, target_pos = TgtPos, acc_gyro_sync_ts = AccGyroSyncTS, ramp_pos = RPos } = St, #nav_state{ } = NavState) -> Timestamp delta ( sec ) between last nav state update , and this nav state TSDelta = (NavState#nav_state.timestamp - PrevTS) / 1000000.0, { AccPitchLP, AccRollLP, AccYawLP } = St#st.acc_lowpass, Accelerometer data { _AccPitch, NAccPitchLP } = lowpass_filter(AccPitchLP, NavState#nav_state.ax), { _AccRoll, NAccRollLP} = lowpass_filter(AccRollLP, NavState#nav_state.ay), { _AccYaw, NAccYawLP} = lowpass_filter(AccYawLP, NavState#nav_state.az), {Alt, NAltLP} = lowpass_filter(St#st.alt_lowpass, NavState#nav_state.alt), Gyro data . { GyroPitchLP, GyroRollLP, GyroYawLP } = St#st.gyro_lowpass, { GyroPitch , NGyroPitchLP } = lowpass_filter(GyroPitchLP , NavState#nav_state.gx ) , , NGyroRollLP } = lowpass_filter(GyroRollLP , NavState#nav_state.gy ) , { GyroPitch, NGyroPitchLP } = { -NavState#nav_state.gy, GyroPitchLP }, { GyroRoll, NGyroRollLP } = { NavState#nav_state.gx, GyroRollLP }, { GyroYaw, NGyroYawLP } = { -NavState#nav_state.gz, GyroYawLP}, NCurPos =#position { alt = Alt, pitch = CurPos#position.pitch + GyroPitch * TSDelta, roll = CurPos#position.roll + GyroRoll * TSDelta, yaw = CurPos#position.yaw + GyroYaw * TSDelta }, Enable yaw only if altitude is greater than 30 cm . YawEnabled = if St#st.yaw_enabled =:= true -> true; St#st.throttle_input < 0.02 -> io:format("Yaw disabled~n"), false; St#st.throttle_input > 0.4 -> io:format("Yaw enabled~n"), true; true -> false end, NTgtPos = if YawEnabled =:= true -> TgtPos#position { yaw = TgtPos#position.yaw + St#st.yaw_input * TSDelta }; end, NRampPos = ramp_position(RPos, NTgtPos, TSDelta), { NAltLockPid, M1, NPids } = calculate_motors(St#st.pidctl, NCurPos, NRampPos, St#st.throttle_input, St#st.alt_lock_pid), Cut off the motors if we are under 0.02 throttle M2 = if St#st.throttle_input < 0.02 -> { 0.0, 0.0, 0.0, 0.0 }; true -> M1 end, {GlitchCount, M3} = case glitch(St#st.glitch_count) of { -1, edrone_motor:set_pwm_norm(St#st.pwm_pid, M2) }; { 0, edrone_motor:set_pwm_norm(St#st.pwm_pid, M2) }; { Cnt, edrone_motor:set_pwm_norm(St#st.pwm_pid, {0.01, 0.01, 0.01, 0.01}) } end, St#st { motor = M3, pidctl = NPids, alt_lock_pid = NAltLockPid, yaw_enabled = YawEnabled, ramp_pos = NRampPos, current_pos = NCurPos, target_pos = NTgtPos, gyro_lowpass = { NGyroPitchLP, NGyroRollLP, NGyroYawLP }, acc_lowpass = { NAccPitchLP, NAccRollLP, NAccYawLP }, WILL NOT WORK . Sonar works at 26+CM only . nav_ts = NavState#nav_state.timestamp, glitch_count = GlitchCount}. glitch(-1) -> -1; glitch(0) -> case random:uniform(100) of 1 -> io:format("Glitch!~n"), 10; _ -> 0 end; glitch(Count) -> Count - 1. calculate_motors({P0, P1, P2, P3}, CurPos, TgtPos, Throttle, AltLockPid) -> YawDelta = TgtPos#position.yaw - CurPos#position.yaw, CM0 = cap(CurPos#position.pitch + CurPos#position.roll, -1.0, 1.0), CM1 = cap(CurPos#position.pitch - CurPos#position.roll, -1.0, 1.0), CM2 = cap(-CurPos#position.pitch - CurPos#position.roll, -1.0, 1.0), CM3 = cap(-CurPos#position.pitch + CurPos#position.roll, -1.0, 1.0), TM0 = cap(TgtPos#position.pitch + TgtPos#position.roll - YawDelta, -1.0, 1.0), TM1 = cap(TgtPos#position.pitch - TgtPos#position.roll + YawDelta, -1.0, 1.0), TM2 = cap(-TgtPos#position.pitch - TgtPos#position.roll - YawDelta, -1.0, 1.0), TM3 = cap(-TgtPos#position.pitch + TgtPos#position.roll + YawDelta, -1.0, 1.0), CurPos#position.roll , TgtPos#position.roll , TM0 - CM0 , TM1 - CM1 , TM2 - CM2 , TM3 - CM3 ] ) , PidTS = edrone_pid:timestamp(), { NM0, NP0 } = edrone_pid:update(edrone_pid:set_point(P0, TM0), CM0, PidTS), { NM1, NP1 } = edrone_pid:update(edrone_pid:set_point(P1, TM1), CM1, PidTS), { NM2, NP2 } = edrone_pid:update(edrone_pid:set_point(P2, TM2), CM2, PidTS), { NM3, NP3 } = edrone_pid:update(edrone_pid:set_point(P3, TM3), CM3, PidTS), If altitude lock is off , we just use throttle ( 0.0 - 1.0 ) { AltAdd, NAltLockPid } = case AltLockPid of undefined -> { 0.0 , undefined }; _ -> edrone_pid:update(AltLockPid, CurPos#position.alt / ?MAX_ALT, PidTS) end, { NAltLockPid, { NM0 + AltAdd + Throttle, NM1 + AltAdd + Throttle, NM2 + AltAdd + Throttle, NM3 + AltAdd + Throttle}, { NP0, NP1, NP2, NP3 } }. lowpass_filter({V0, V1, V2}, Val) -> NV = V0 * 0.25 + V1 * 0.25 + V2 * 0.25 + Val * 0.25, {NV, { V1, V2, Val } }; lowpass_filter(_, Val) -> {Val, { Val, Val, Val } }. ramp_position(RPos, TPos, TSDelta) -> RPos#position { pitch = ramp_position_(RPos#position.pitch, TPos#position.pitch, ?PITCH_RAMP, TSDelta), roll = ramp_position_(RPos#position.roll, TPos#position.roll, ?ROLL_RAMP, TSDelta), yaw = ramp_position_(RPos#position.yaw, TPos#position.yaw, ?YAW_RAMP, TSDelta) }. ramp_position_(Ramp, Target, Max, TSDelta) when Ramp > Target + Max * TSDelta-> io : format("-T(~f ) R(~f ) TSDelta(~f ) Max(~f)~n " , [ Target , Ramp , TSDelta , ] ) , Ramp - Max * TSDelta; ramp_position_(Ramp, Target, Max, TSDelta) when Ramp < Target - Max * TSDelta -> io : format("+T(~f ) R(~f ) TSDelta(~f ) Max(~f)~n " , [ Target , Ramp , TSDelta , ] ) , Ramp + Max * TSDelta; ramp_position_(_Ramp, Target, _Max, _TSDelta) -> io : format("-=T(~f ) R(~f ) TSDelta(~f ) ) ~f ~ n " , [ Target , Ramp , TSDelta , , TSDelta * ] ) , Target. cap(Val, Min, Max) -> min(max(Val, Min), Max). decode_input(?PITCH_CMD, Val, #st {target_pos = TgtPos} = St) -> Inp = convert_input_value(Val), St#st { pitch_input = Inp, target_pos = TgtPos#position {pitch = Inp / 10.0}}; decode_input(?ROLL_CMD, Val, #st {target_pos = TgtPos} = St) -> Inp = convert_input_value(Val), St#st { roll_input = Inp, target_pos = TgtPos#position {roll = Inp / 10.0}}; decode_input(?YAW_CMD, Val, St) -> Inp = convert_input_value(Val), io : format ( " : ~p/~-7.4f ~ n " , [ , ] ) , St#st { yaw_input = Inp / 3}; decode_input(?THROTTLE_CMD, Val, St) when St#st.alt_lock_pid =:= undefined-> Inp = Val / ?MAX_CMD_VAL, St#st { throttle_input = Inp }; decode_input(?THROTTLE_CMD, _Val, St) -> St; decode_input(?PITCH_TRIM_CMD, Val, St) -> Inp = convert_input_value(Val), io:format("---- PitchTrim: ~-7.4f~n", [Inp]), St#st { pitch_trim_input = Inp }; decode_input(?ROLL_TRIM_CMD, Val, St) -> Inp = convert_input_value(Val), io:format("---- RollTrim: ~-7.4f~n", [Inp]), St#st { roll_trim_input = Inp }; decode_input(?YAW_TRIM_CMD, Val, St) -> Inp = convert_input_value(Val), io:format("---- YawTrim: ~-7.4f~n", [Inp]), St#st { roll_trim_input = Inp }; decode_input(?UPGRADE_CMD, _Val, St) -> io:format("UPGRADE TIME!~n"), gen_server:cast(edrone_upgrade, { upgrade, ?MODULE }), St; decode_input(?ALT_LOCK_CMD, 1, St) -> io:format("Altitude Lock: Engaged!~n"), AltPid = edrone_pid:set_point(edrone_pid:new(?PID_P, ?PID_I, ?PID_D, -1.0, 1.0), Alttitude lock St#st { alt_lock_pid = AltPid }; decode_input(?ALT_LOCK_CMD, 0, St) -> io:format("Altitude Disengaged!~n"), St#st { alt_lock_pid = undefined }; decode_input(ErrKey, ErrVal, St)-> io:format("---- Unknown key(~p) val(~p)~n", [ErrKey, ErrVal]), St. convert_input_value(Val) -> (Val / ?MAX_CMD_VAL) * 2 - 1.
5df6d834cafe1c464857a7c82c4a7ec789322318c7578b8275cb03fd34e5af36
adam-james-v/svg-clj
layout.cljc
(ns svg-clj.layout "Provides functions for layout control of elements." (:require [svg-clj.elements :as el] [svg-clj.transforms :as tf] [svg-clj.utils :as u])) (defn distribute-linear "Distribute `elems` along the `axis` (either :x or :y) with a `gap` distance between each item." [elems axis gap] (let [getfn (axis {:x first :y second}) distances (reductions + (map #(+ (/ (getfn (u/bb-dims %1)) 2) (/ (getfn (u/bb-dims %2)) 2) gap) elems (rest elems)))] (el/g (conj (map #(tf/translate %1 (if (= axis :x) [%2 0] [0 %2])) (rest elems) distances) (first elems))))) (defn distribute-on-pts "Distribute the `elems` along the given `pts`. Each element is centered on its point." [elems pts] (el/g (map #(-> %1 (tf/translate %2)) elems pts))) (defn distribute-on-curve "Distribute the `elems` evenly along the given `curve`." [elems curve] (let [eps u/*eps* n (if (> (count elems) 1) (dec (count elems)) 1) xf (fn [elem t] (let [t (cond (<= (- 1 eps) t) (- 1 eps) (> eps t) eps :else t) n (u/normal (curve (- t eps)) (curve (+ t eps))) a (u/angle-from-pts n [0 0] [0 1]) o (map #(u/round % 4) (u/rotate-pt (tf/centroid elem) a))] (-> elem (tf/rotate a) (tf/translate (u/v- (curve t) o (tf/centroid elem))))))] (map #(xf %1 (float (/ %2 n))) elems (range 0 (inc n))))) (defn pattern-on-pts "Repeat `elem`, centering on each point of `pts`." [elem pts] (el/g (map #(-> elem (tf/translate %)) pts))) (defn pattern-on-curve "Repeat `elem` evenly along `curve` `n` times." [elem curve n] (let [step (/ 1.0 n)] (map #(-> elem (tf/translate (curve %))) (range 0 1.0 step))))
null
https://raw.githubusercontent.com/adam-james-v/svg-clj/4220d7036113564a2af84a61d8f7db486ce858da/src/svg_clj/layout.cljc
clojure
(ns svg-clj.layout "Provides functions for layout control of elements." (:require [svg-clj.elements :as el] [svg-clj.transforms :as tf] [svg-clj.utils :as u])) (defn distribute-linear "Distribute `elems` along the `axis` (either :x or :y) with a `gap` distance between each item." [elems axis gap] (let [getfn (axis {:x first :y second}) distances (reductions + (map #(+ (/ (getfn (u/bb-dims %1)) 2) (/ (getfn (u/bb-dims %2)) 2) gap) elems (rest elems)))] (el/g (conj (map #(tf/translate %1 (if (= axis :x) [%2 0] [0 %2])) (rest elems) distances) (first elems))))) (defn distribute-on-pts "Distribute the `elems` along the given `pts`. Each element is centered on its point." [elems pts] (el/g (map #(-> %1 (tf/translate %2)) elems pts))) (defn distribute-on-curve "Distribute the `elems` evenly along the given `curve`." [elems curve] (let [eps u/*eps* n (if (> (count elems) 1) (dec (count elems)) 1) xf (fn [elem t] (let [t (cond (<= (- 1 eps) t) (- 1 eps) (> eps t) eps :else t) n (u/normal (curve (- t eps)) (curve (+ t eps))) a (u/angle-from-pts n [0 0] [0 1]) o (map #(u/round % 4) (u/rotate-pt (tf/centroid elem) a))] (-> elem (tf/rotate a) (tf/translate (u/v- (curve t) o (tf/centroid elem))))))] (map #(xf %1 (float (/ %2 n))) elems (range 0 (inc n))))) (defn pattern-on-pts "Repeat `elem`, centering on each point of `pts`." [elem pts] (el/g (map #(-> elem (tf/translate %)) pts))) (defn pattern-on-curve "Repeat `elem` evenly along `curve` `n` times." [elem curve n] (let [step (/ 1.0 n)] (map #(-> elem (tf/translate (curve %))) (range 0 1.0 step))))
945e771081b094d105bc802db01191061170f692b5fe9144bd8d0ea60e12b7b0
icfpcontest2021/icfpcontest2021.github.io
Slope.hs
# LANGUAGE DeriveFunctor # module BrainWall.Edge.Slope ( Slope (..) , fromV2 , between ) where import BrainWall.V2 import Data.Ratio (Ratio, (%)) -- | Slope is an infinite precision representation of an angle. It works by storing the slope of the line in a " Quadrant " . -- -- Q3 | Q4 -- ----+---- -- Q2 | Q1 -- The constructors of this datatype are designed to have a good ' ' instance . data Slope a = Q1 a | Q2 a | Q3 a | Q4 a deriving (Eq, Functor, Ord, Show) fromV2 :: (Integral a, Ord a) => V2 a -> Slope (Ratio a) fromV2 (V2 x y) = case compare x 0 of EQ -> case compare y 0 of EQ -> Q1 0 LT -> Q4 0 GT -> Q2 0 LT -> case compare y 0 of EQ -> Q3 0 LT -> Q3 $ (-y) % (-x) GT -> Q2 $ (-x) % y GT -> case compare y 0 of EQ -> Q1 0 LT -> Q4 $ x % (-y) GT -> Q1 $ y % x between :: Ord a => Slope a -> (Slope a, Slope a) -> Bool between x (lo, hi) | lo < hi = x >= lo && x <= hi | otherwise = x >= lo || x <= hi
null
https://raw.githubusercontent.com/icfpcontest2021/icfpcontest2021.github.io/fb23fea2a8ecec7740017d3dda78d921c1df5a26/toolchain/lib/BrainWall/Edge/Slope.hs
haskell
| Slope is an infinite precision representation of an angle. It works Q3 | Q4 ----+---- Q2 | Q1
# LANGUAGE DeriveFunctor # module BrainWall.Edge.Slope ( Slope (..) , fromV2 , between ) where import BrainWall.V2 import Data.Ratio (Ratio, (%)) by storing the slope of the line in a " Quadrant " . The constructors of this datatype are designed to have a good ' ' instance . data Slope a = Q1 a | Q2 a | Q3 a | Q4 a deriving (Eq, Functor, Ord, Show) fromV2 :: (Integral a, Ord a) => V2 a -> Slope (Ratio a) fromV2 (V2 x y) = case compare x 0 of EQ -> case compare y 0 of EQ -> Q1 0 LT -> Q4 0 GT -> Q2 0 LT -> case compare y 0 of EQ -> Q3 0 LT -> Q3 $ (-y) % (-x) GT -> Q2 $ (-x) % y GT -> case compare y 0 of EQ -> Q1 0 LT -> Q4 $ x % (-y) GT -> Q1 $ y % x between :: Ord a => Slope a -> (Slope a, Slope a) -> Bool between x (lo, hi) | lo < hi = x >= lo && x <= hi | otherwise = x >= lo || x <= hi
14158a2397f58e64e106c66f521039af47097f7bd20f8d7de43bb8407a098eec
mirage/bechamel
s.mli
module type FUNCTOR = sig type 'a t end module type MEASURE = sig type witness val label : witness -> string val unit : witness -> string val make : unit -> witness val load : witness -> unit val unload : witness -> unit val get : witness -> float end
null
https://raw.githubusercontent.com/mirage/bechamel/7a0aebef3c2ec266db97385264be74274bdc4765/lib/s.mli
ocaml
module type FUNCTOR = sig type 'a t end module type MEASURE = sig type witness val label : witness -> string val unit : witness -> string val make : unit -> witness val load : witness -> unit val unload : witness -> unit val get : witness -> float end
34ad2a8bae0a6584e054a16c770f61a46de9a0ad73954355a083c67d677c47f6
gebi/jungerl
memcached.erl
%%%------------------------------------------------------------------- %%% File : memcached.erl Author : < > Description : memcached client for Erlang Protocol described here : %%% Created : 20 Sep 2007 by < > %%%------------------------------------------------------------------- -module(memcached). -behaviour(gen_server). %% API -export([start_link/2, mcset/3, mcset/5, mcget/2, mcdelete/3, mcdelete/2, mcquit/1]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -record(state, {sock}). %%==================================================================== %% API %%==================================================================== %%-------------------------------------------------------------------- Function : start_link ( ) - > { ok , Pid } | ignore | { error , Error } %% Description: Starts the server %%-------------------------------------------------------------------- start_link(Host, Port) -> gen_server:start_link(?MODULE, [Host, Port], []). %%-------------------------------------------------------------------- Function : mcset(Pid , Key , Bytes ) - > %% %% Description: Associates Bytes with Key in memcached. %%-------------------------------------------------------------------- mcset(Pid, Key, Bytes) -> gen_server:call(Pid, {set, set, Key, 0, 0, Bytes}). %%-------------------------------------------------------------------- Function : mcset(Pid , Key , Flags , Expire , Bytes ) - > %% %% Description: Associates Bytes with Key, with flags, and a possible %% expiration date. %%-------------------------------------------------------------------- mcset(Pid, Key, Flags, Expire, Bytes) -> gen_server:call(Pid, {set, set, Key, Flags, Expire, Bytes}). %%-------------------------------------------------------------------- Function : mcadd(Pid , Key , Bytes ) - > %% %% Description: Associates Bytes with Key, but only if the server %% doesn't already have data associated with Key. %% %%-------------------------------------------------------------------- mcadd(Pid, Key, Bytes) -> gen_server:call(Pid, {add, add, Key, 0, 0, Bytes}). mcadd(Pid, Key, Flags, Expire, Bytes) -> gen_server:call(Pid, {add, add, Key, Flags, Expire, Bytes}). %%-------------------------------------------------------------------- %% Function: mcreplace(Pid, Key, Bytes) -> %% %% Description: Associates Bytes with Key, but only if the server %% already has data associated with Key. %% %%-------------------------------------------------------------------- mcreplace(Pid, Key, Bytes) -> gen_server:call(Pid, {replace, replace, Key, 0, 0, Bytes}). mcreplace(Pid, Key, Flags, Expire, Bytes) -> gen_server:call(Pid, {replace, replace, Key, Flags, Expire, Bytes}). %%-------------------------------------------------------------------- %% Function: mcget(Pid, Key) -> {ok, Value} %% %% Description: Returns Bytes associated with Key. %%-------------------------------------------------------------------- mcget(Pid, Key) when is_atom(Key) -> {ok, [Res]} = gen_server:call(Pid, {get, [Key]}), {ok, Res}; %%-------------------------------------------------------------------- Function : mcget(Pid , [ key1 , key2 , ... ] ) - > { ok , [ Values ] } %% %% Description: Returns Bytes associated with Key. %%-------------------------------------------------------------------- %% This could be a list like [foo, bar] or ["foo", "bar"] mcget(Pid, [Head|Tail]) when is_atom(Head) -> Keys = [Head] ++ Tail, gen_server:call(Pid, {get, Keys}); mcget(Pid, [Head|Tail]) when is_list(Head) -> Keys = [Head] ++ Tail, gen_server:call(Pid, {get, Keys}); mcget(Pid, Key) -> gen_server:call(Pid, {get, [Key]}). %%-------------------------------------------------------------------- Function : mcdelete(Pid , Key , Time ) - > %% %% Description: Delete a key in memcached. %%-------------------------------------------------------------------- mcdelete(Pid, Key, Time) -> gen_server:call(Pid, {delete, Key, Time}). %%-------------------------------------------------------------------- %% Function: mcdelete(Pid, Key) -> %% Description : Delete a key in memcached - use default value of 0 for %% time. %% ------------------------------------------------------------------- mcdelete(Pid, Key) -> gen_server:call(Pid, {delete, Key, 0}). %%-------------------------------------------------------------------- %% Function: mcquit(Pid) -> %% %% Description: Terminate the connection. %%-------------------------------------------------------------------- mcquit(Pid) -> gen_server:call(Pid, quit). %%==================================================================== %% gen_server callbacks %%==================================================================== %%-------------------------------------------------------------------- %% Function: init(Args) -> {ok, State} | { ok , State , Timeout } | %% ignore | %% {stop, Reason} %% Description: Initiates the server %%-------------------------------------------------------------------- init([Host, Port]) -> {ok, Sock} = gen_tcp:connect(Host, Port, [binary, {active, false}]), {ok, #state{sock = Sock}}. %%-------------------------------------------------------------------- Function : % % handle_call(Request , From , State ) - > { reply , Reply , State } | { reply , Reply , State , Timeout } | { noreply , State } | { noreply , State , Timeout } | %% {stop, Reason, Reply, State} | %% {stop, Reason, State} %% Description: Handling call messages %%-------------------------------------------------------------------- handle_call({get, Keys}, _From, #state{sock = Sock} = S) -> Reply = process_get(Sock, Keys), {reply, Reply, S#state{sock = Sock}}; handle_call({set, Operation, Key, Flags, Expire, Bytes}, _From, #state{sock = Sock} = S) -> Reply = process_set(Sock, Operation, Key, Flags, Expire, Bytes), {reply, Reply, S#state{sock = Sock}}; handle_call({delete, Key, Time}, _From, #state{sock = Sock} = S) -> Reply = process_delete(Sock, Key, Time), {reply, Reply, #state{sock = Sock} = S}; handle_call(quit, _From, #state{sock = Sock} = _) -> gen_tcp:close(Sock), {reply, ok, {}}. %%-------------------------------------------------------------------- Function : handle_cast(Msg , State ) - > { noreply , State } | { noreply , State , Timeout } | %% {stop, Reason, State} %% Description: Handling cast messages %%-------------------------------------------------------------------- handle_cast(_Msg, State) -> {noreply, State}. %%-------------------------------------------------------------------- Function : handle_info(Info , State ) - > { noreply , State } | { noreply , State , Timeout } | %% {stop, Reason, State} %% Description: Handling all non call/cast messages %%-------------------------------------------------------------------- handle_info(_Info, State) -> {noreply, State}. %%-------------------------------------------------------------------- %% Function: terminate(Reason, State) -> void() %% Description: This function is called by a gen_server when it is about to %% terminate. It should be the opposite of Module:init/1 and do any necessary %% cleaning up. When it returns, the gen_server terminates with Reason. %% The return value is ignored. %%-------------------------------------------------------------------- terminate(_Reason, _State) -> ok. %%-------------------------------------------------------------------- Func : code_change(OldVsn , State , Extra ) - > { ok , NewState } %% Description: Convert process state when code is changed %%-------------------------------------------------------------------- code_change(_OldVsn, State, _Extra) -> {ok, State}. %%-------------------------------------------------------------------- Internal functions %%-------------------------------------------------------------------- %% If it's an atom, transform it. If it's a string, leave it alone. to_list(Key) when is_atom(Key) -> atom_to_list(Key); to_list(Key) when is_list(Key) -> Key. parse_response helper to fetch data if there 's a lot of it . fetchmore(Sock, Len, More) -> %% Read what we need to grab the data. {ok, <<Data/binary>>} = gen_tcp:recv(Sock, Len - size(More)), Combined = <<More/binary, Data/binary>>, if size(Combined) < Len -> {Bytes, Rest} = fetchmore(Sock, Len, Combined); true -> <<Bytes:Len/binary>> = Combined, %% Read anything left. {ok, <<Rest/binary>>} = gen_tcp:recv(Sock, 0) end, {Bytes, Rest}. Parse the get response . parse_responses(_, <<"END\r\n", _/binary>>, Acc) -> Acc; parse_responses(Sock, <<"\r\n", Data/binary>>, Acc) -> parse_responses(Sock, Data, Acc); parse_responses(Sock, <<"VALUE ", Data/binary>>, Acc) -> {ok, [_, _, Len], More} = io_lib:fread("~s ~u ~u\r\n", binary_to_list(Data)), if %% 5 is size(<<"\r\nEND\r\n">>) length(More) < Len + 7 -> %% If we didn't read all the data, fetch the rest. {Bytes, Rest} = fetchmore(Sock, Len, list_to_binary(More)); true -> <<Bytes:Len/binary, Rest/binary>> = list_to_binary(More) end, parse_responses(Sock, Rest, Acc ++ [binary_to_term(Bytes)]). %% Send get and handle the response. process_get(Sock, Keys) -> KeyList = [to_list(X) || X <- Keys], ok = gen_tcp:send(Sock, list_to_binary(["get ", string_join(KeyList), "\r\n"])), {ok, <<Data/binary>>} = gen_tcp:recv(Sock, 0), {ok, parse_responses(Sock, Data, [])}. %% Set set and handle the response. process_set(Sock, Operation, Key, Flags, Expire, Data) -> Op = to_list(Operation), K = to_list(Key), Bytes = term_to_binary(Data), Len = size(Bytes), L = list_to_binary( io_lib:format("~s ~s ~p ~p ~p", [Op, K, Flags, Expire, Len])), Line = <<L/binary, "\r\n">>, ok = gen_tcp:send(Sock, Line), ok = gen_tcp:send(Sock, <<Bytes/binary, "\r\n">>), {ok, Response} = gen_tcp:recv(Sock, 0), case Response of <<"STORED\r\n">> -> ok; <<"NOT_STORED\r\n">> -> not_stored end. process_delete(Sock, Key, Time) -> Line = list_to_binary( io_lib:format("delete ~s ~p\r\n", [to_list(Key), Time])), ok = gen_tcp:send(Sock, Line), {ok, Response} = gen_tcp:recv(Sock, 0), case Response of <<"DELETED\r\n">> -> ok; <<"NOT_FOUND\r\n">> -> not_found end. When oh when will we see this in Erlang proper . string_join(Items) -> string_join(Items, " "). string_join(Items, Sep) -> lists:flatten(lists:reverse(string_join1(Items, Sep, []))). string_join1([Head | []], _Sep, Acc) -> [Head | Acc]; string_join1([Head | Tail], Sep, Acc) -> string_join1(Tail, Sep, [Sep, Head | Acc]).
null
https://raw.githubusercontent.com/gebi/jungerl/8f5c102295dbe903f47d79fd64714b7de17026ec/lib/memcached/src/memcached.erl
erlang
------------------------------------------------------------------- File : memcached.erl ------------------------------------------------------------------- API gen_server callbacks ==================================================================== API ==================================================================== -------------------------------------------------------------------- Description: Starts the server -------------------------------------------------------------------- -------------------------------------------------------------------- Description: Associates Bytes with Key in memcached. -------------------------------------------------------------------- -------------------------------------------------------------------- Description: Associates Bytes with Key, with flags, and a possible expiration date. -------------------------------------------------------------------- -------------------------------------------------------------------- Description: Associates Bytes with Key, but only if the server doesn't already have data associated with Key. -------------------------------------------------------------------- -------------------------------------------------------------------- Function: mcreplace(Pid, Key, Bytes) -> Description: Associates Bytes with Key, but only if the server already has data associated with Key. -------------------------------------------------------------------- -------------------------------------------------------------------- Function: mcget(Pid, Key) -> {ok, Value} Description: Returns Bytes associated with Key. -------------------------------------------------------------------- -------------------------------------------------------------------- Description: Returns Bytes associated with Key. -------------------------------------------------------------------- This could be a list like [foo, bar] or ["foo", "bar"] -------------------------------------------------------------------- Description: Delete a key in memcached. -------------------------------------------------------------------- -------------------------------------------------------------------- Function: mcdelete(Pid, Key) -> time. ------------------------------------------------------------------- -------------------------------------------------------------------- Function: mcquit(Pid) -> Description: Terminate the connection. -------------------------------------------------------------------- ==================================================================== gen_server callbacks ==================================================================== -------------------------------------------------------------------- Function: init(Args) -> {ok, State} | ignore | {stop, Reason} Description: Initiates the server -------------------------------------------------------------------- -------------------------------------------------------------------- % handle_call(Request , From , State ) - > { reply , Reply , State } | {stop, Reason, Reply, State} | {stop, Reason, State} Description: Handling call messages -------------------------------------------------------------------- -------------------------------------------------------------------- {stop, Reason, State} Description: Handling cast messages -------------------------------------------------------------------- -------------------------------------------------------------------- {stop, Reason, State} Description: Handling all non call/cast messages -------------------------------------------------------------------- -------------------------------------------------------------------- Function: terminate(Reason, State) -> void() Description: This function is called by a gen_server when it is about to terminate. It should be the opposite of Module:init/1 and do any necessary cleaning up. When it returns, the gen_server terminates with Reason. The return value is ignored. -------------------------------------------------------------------- -------------------------------------------------------------------- Description: Convert process state when code is changed -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- If it's an atom, transform it. If it's a string, leave it alone. Read what we need to grab the data. Read anything left. 5 is size(<<"\r\nEND\r\n">>) If we didn't read all the data, fetch the rest. Send get and handle the response. Set set and handle the response.
Author : < > Description : memcached client for Erlang Protocol described here : Created : 20 Sep 2007 by < > -module(memcached). -behaviour(gen_server). -export([start_link/2, mcset/3, mcset/5, mcget/2, mcdelete/3, mcdelete/2, mcquit/1]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -record(state, {sock}). Function : start_link ( ) - > { ok , Pid } | ignore | { error , Error } start_link(Host, Port) -> gen_server:start_link(?MODULE, [Host, Port], []). Function : mcset(Pid , Key , Bytes ) - > mcset(Pid, Key, Bytes) -> gen_server:call(Pid, {set, set, Key, 0, 0, Bytes}). Function : mcset(Pid , Key , Flags , Expire , Bytes ) - > mcset(Pid, Key, Flags, Expire, Bytes) -> gen_server:call(Pid, {set, set, Key, Flags, Expire, Bytes}). Function : mcadd(Pid , Key , Bytes ) - > mcadd(Pid, Key, Bytes) -> gen_server:call(Pid, {add, add, Key, 0, 0, Bytes}). mcadd(Pid, Key, Flags, Expire, Bytes) -> gen_server:call(Pid, {add, add, Key, Flags, Expire, Bytes}). mcreplace(Pid, Key, Bytes) -> gen_server:call(Pid, {replace, replace, Key, 0, 0, Bytes}). mcreplace(Pid, Key, Flags, Expire, Bytes) -> gen_server:call(Pid, {replace, replace, Key, Flags, Expire, Bytes}). mcget(Pid, Key) when is_atom(Key) -> {ok, [Res]} = gen_server:call(Pid, {get, [Key]}), {ok, Res}; Function : mcget(Pid , [ key1 , key2 , ... ] ) - > { ok , [ Values ] } mcget(Pid, [Head|Tail]) when is_atom(Head) -> Keys = [Head] ++ Tail, gen_server:call(Pid, {get, Keys}); mcget(Pid, [Head|Tail]) when is_list(Head) -> Keys = [Head] ++ Tail, gen_server:call(Pid, {get, Keys}); mcget(Pid, Key) -> gen_server:call(Pid, {get, [Key]}). Function : mcdelete(Pid , Key , Time ) - > mcdelete(Pid, Key, Time) -> gen_server:call(Pid, {delete, Key, Time}). Description : Delete a key in memcached - use default value of 0 for mcdelete(Pid, Key) -> gen_server:call(Pid, {delete, Key, 0}). mcquit(Pid) -> gen_server:call(Pid, quit). { ok , State , Timeout } | init([Host, Port]) -> {ok, Sock} = gen_tcp:connect(Host, Port, [binary, {active, false}]), {ok, #state{sock = Sock}}. { reply , Reply , State , Timeout } | { noreply , State } | { noreply , State , Timeout } | handle_call({get, Keys}, _From, #state{sock = Sock} = S) -> Reply = process_get(Sock, Keys), {reply, Reply, S#state{sock = Sock}}; handle_call({set, Operation, Key, Flags, Expire, Bytes}, _From, #state{sock = Sock} = S) -> Reply = process_set(Sock, Operation, Key, Flags, Expire, Bytes), {reply, Reply, S#state{sock = Sock}}; handle_call({delete, Key, Time}, _From, #state{sock = Sock} = S) -> Reply = process_delete(Sock, Key, Time), {reply, Reply, #state{sock = Sock} = S}; handle_call(quit, _From, #state{sock = Sock} = _) -> gen_tcp:close(Sock), {reply, ok, {}}. Function : handle_cast(Msg , State ) - > { noreply , State } | { noreply , State , Timeout } | handle_cast(_Msg, State) -> {noreply, State}. Function : handle_info(Info , State ) - > { noreply , State } | { noreply , State , Timeout } | handle_info(_Info, State) -> {noreply, State}. terminate(_Reason, _State) -> ok. Func : code_change(OldVsn , State , Extra ) - > { ok , NewState } code_change(_OldVsn, State, _Extra) -> {ok, State}. Internal functions to_list(Key) when is_atom(Key) -> atom_to_list(Key); to_list(Key) when is_list(Key) -> Key. parse_response helper to fetch data if there 's a lot of it . fetchmore(Sock, Len, More) -> {ok, <<Data/binary>>} = gen_tcp:recv(Sock, Len - size(More)), Combined = <<More/binary, Data/binary>>, if size(Combined) < Len -> {Bytes, Rest} = fetchmore(Sock, Len, Combined); true -> <<Bytes:Len/binary>> = Combined, {ok, <<Rest/binary>>} = gen_tcp:recv(Sock, 0) end, {Bytes, Rest}. Parse the get response . parse_responses(_, <<"END\r\n", _/binary>>, Acc) -> Acc; parse_responses(Sock, <<"\r\n", Data/binary>>, Acc) -> parse_responses(Sock, Data, Acc); parse_responses(Sock, <<"VALUE ", Data/binary>>, Acc) -> {ok, [_, _, Len], More} = io_lib:fread("~s ~u ~u\r\n", binary_to_list(Data)), if length(More) < Len + 7 -> {Bytes, Rest} = fetchmore(Sock, Len, list_to_binary(More)); true -> <<Bytes:Len/binary, Rest/binary>> = list_to_binary(More) end, parse_responses(Sock, Rest, Acc ++ [binary_to_term(Bytes)]). process_get(Sock, Keys) -> KeyList = [to_list(X) || X <- Keys], ok = gen_tcp:send(Sock, list_to_binary(["get ", string_join(KeyList), "\r\n"])), {ok, <<Data/binary>>} = gen_tcp:recv(Sock, 0), {ok, parse_responses(Sock, Data, [])}. process_set(Sock, Operation, Key, Flags, Expire, Data) -> Op = to_list(Operation), K = to_list(Key), Bytes = term_to_binary(Data), Len = size(Bytes), L = list_to_binary( io_lib:format("~s ~s ~p ~p ~p", [Op, K, Flags, Expire, Len])), Line = <<L/binary, "\r\n">>, ok = gen_tcp:send(Sock, Line), ok = gen_tcp:send(Sock, <<Bytes/binary, "\r\n">>), {ok, Response} = gen_tcp:recv(Sock, 0), case Response of <<"STORED\r\n">> -> ok; <<"NOT_STORED\r\n">> -> not_stored end. process_delete(Sock, Key, Time) -> Line = list_to_binary( io_lib:format("delete ~s ~p\r\n", [to_list(Key), Time])), ok = gen_tcp:send(Sock, Line), {ok, Response} = gen_tcp:recv(Sock, 0), case Response of <<"DELETED\r\n">> -> ok; <<"NOT_FOUND\r\n">> -> not_found end. When oh when will we see this in Erlang proper . string_join(Items) -> string_join(Items, " "). string_join(Items, Sep) -> lists:flatten(lists:reverse(string_join1(Items, Sep, []))). string_join1([Head | []], _Sep, Acc) -> [Head | Acc]; string_join1([Head | Tail], Sep, Acc) -> string_join1(Tail, Sep, [Sep, Head | Acc]).
80cbdd7e39059d4dd349c05e3c08f25443ffcbcdc29394b23203f1d54042712e
russ/openpoker
observer.erl
Copyright ( C ) 2005 - 2008 Wager Labs , SA %%%% %%%% THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS CREATIVE COMMONS PUBLIC LICENSE ( " CCPL " OR " LICENSE " ) . THE WORK IS %%%% PROTECTED BY COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF %%%% THE WORK OTHER THAN AS AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT %%%% LAW IS PROHIBITED. %%%% %%%% BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT %%%% AND AGREE TO BE BOUND BY THE TERMS OF THIS LICENSE. TO THE EXTENT %%%% THIS LICENSE MAY BE CONSIDERED TO BE A CONTRACT, THE LICENSOR GRANTS %%%% YOU THE RIGHTS CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE %%%% OF SUCH TERMS AND CONDITIONS. %%%% %%%% Please see LICENSE for full legal details and the following URL %%%% for a human-readable explanation: %%%% -nc-sa/3.0/us/ %%%% -module(observer). -export([start/1, stop/1, observe/2]). -include("common.hrl"). -include("bot.hrl"). -include("pp.hrl"). -record(obs, { id, trace, parent, gid, winners, seats, games_started, games_to_watch, cancel_count, stop, events }). start([Parent, Trace, GamesToWatch]) -> Obs = #obs { trace = Trace, parent = Parent, winners = gb_trees:empty(), seats = gb_trees:empty(), games_started = 0, games_to_watch = GamesToWatch, cancel_count = -1, stop = false, events = [] }, {ok, observe, Obs}. stop(_) -> ok. observe(R, Data) -> Data1 = process(R, Data), maybe_report(R, Data1), if Data#obs.stop -> Next = stop, Events = Data#obs.events; true -> Next = continue, Events = [] end, {Next, Data1, Events}. process(R = #notify_join{}, Data) -> Seats1 = gb_trees:insert(R#notify_join.player, R#notify_join.seat, Data#obs.seats), Data#obs{ seats = Seats1 }; process(R = #notify_win{}, Data) -> Amt = R#notify_win.amount / 1.0, N = gb_trees:get(R#notify_win.player, Data#obs.seats), Winners1 = gb_trees:insert(N, Amt, Data#obs.winners), Data#obs{ winners = Winners1 }; process(R = #player_info{}, Data) -> PID = R#player_info.player, Amount = gb_trees:get(PID, Data#obs.winners), T1 = gb_trees:delete(PID, Data#obs.winners), Winners1 = gb_trees:insert(R#player_info.nick, Amount, T1), Data#obs{ winners = Winners1 }; process(R = #notify_start_game{}, Data) -> GID = R#notify_start_game.game, Started = Data#obs.games_started, Data#obs.parent ! {'START', GID}, Data#obs{ winners = gb_trees:empty(), games_started = Started + 1 }; process(R = #notify_cancel_game{}, Data) -> GID = R#notify_cancel_game.game, N = Data#obs.cancel_count, if Data#obs.games_started > 0 -> Data#obs.parent ! {'CANCEL', GID}, timer:sleep(50), Data#obs{ stop = true, events = [#unwatch{ game = GID }] }; true -> Data#obs{ cancel_count = N + 1 } end; process(R = #notify_end_game{}, Data) -> GID = R#notify_end_game.game, Data#obs.parent ! {'END', GID, Data#obs.winners}, N = Data#obs.games_to_watch, if N == 1 -> Data#obs{ stop = true, events = [#unwatch{ game = GID }] }; true -> Data#obs{ games_to_watch = N - 1 } end; process(_, Data) -> Data. maybe_report(R, #obs{ trace = true }) -> catch report(R); maybe_report(_, _) -> ok. report(R = #notify_join{}) -> io:format("~p: JOIN: ~p @ ~p~n", [R#notify_join.game, R#notify_join.player, R#notify_join.seat]); report(R = #notify_leave{}) -> io:format("~p: LEAVE: ~p~n", [R#notify_join.game, R#notify_join.player]); report(R = #game_info{}) -> io:format("Game #~w, #players: ~w, joined: ~w, waiting: ~w; ", [R#game_info.game, R#game_info.required, R#game_info.joined, R#game_info.waiting]), Limit = R#game_info.limit, io:format("limit: low: ~w, high: ~w~n", [Limit#limit.low, Limit#limit.high]); report(R = #seat_state{ state = ?PS_FOLD }) -> io:format("~p: FOLD: ~p~n", [R#seat_state.game, R#seat_state.player ]); report(#seat_state{}) -> ok; report(R = #notify_chat{}) -> io:format("~w: CHAT: ~w: ~p~n", [R#notify_chat.game, R#notify_chat.player, R#notify_chat.message]); report(R = #notify_draw{ card = 0 }) -> io:format("~w: CARD: ~w~n", [R#notify_draw.game, R#notify_draw.player]); report(R = #game_stage{}) -> io:format("~w: STAGE: ~w~n", [R#game_stage.game, R#game_stage.stage]); report(R = #notify_raise{}) when R#notify_raise.raise == 0, R#notify_raise.call == 0 -> io:format("~w: CHECK: ~w~n", [R#notify_raise.game, R#notify_raise.player]); report(R = #notify_raise{}) when R#notify_raise.call == 0 -> io:format("~w: CALL: ~w, ~-14.2. f~n", [R#notify_raise.game, R#notify_raise.player, R#notify_raise.raise / 1.0]); report(R = #notify_raise{}) -> io:format("~w: RAISE: ~w, ~-14.2. f~n", [R#notify_raise.game, R#notify_raise.player, R#notify_raise.raise / 1.0]); report(R = #notify_sb{}) -> io:format("~w: SB: ~w~n", [R#notify_sb.game, R#notify_sb.sb]); report(R = #notify_bb{}) -> io:format("~w: BB: ~w~n", [R#notify_bb.game, R#notify_bb.bb]); report(R = #notify_shared{}) -> io:format("~w: BOARD: ~w~n", [R#notify_shared.game, R#notify_shared.card]); report(R = #notify_win{}) -> io:format("~w: WIN: ~w, ~-14.2. f~n", [R#notify_win.game, R#notify_win.player, R#notify_win.amount / 1.0]); report(R = #notify_button{}) -> io:format("~w: DEALER: ~w~n", [R#notify_button.game, R#notify_button.button]); report(R = #notify_start_game{}) -> io:format("~w: START~n", [R#notify_start_game.game]); report(R = #notify_cancel_game{}) -> io:format("~w: CANCEL~n", [R#notify_cancel_game.game]); report(R = #notify_end_game{}) -> io:format("~w: END~n", [R#notify_end_game.game]); report(R = #notify_hand{}) -> H = hand:to_string(R#notify_hand.hand), io:format("~w: HAND: ~w, with ~p~n", [R#notify_hand.game, R#notify_hand.player, H]); report(R = #show_cards{}) -> Cards1 = [hand:card_to_string(Card) || Card <- R#show_cards.cards], io:format("~w: SHOW: ~w: ~p~n", [R#show_cards.game, R#show_cards.player, Cards1]); report(R) -> error_logger:error_report([{module, ?MODULE}, {line, ?LINE}, {message, R} ]), ok.
null
https://raw.githubusercontent.com/russ/openpoker/62edd72a35b9ef52f55da9303cf1e06142e95895/src/observer.erl
erlang
THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS PROTECTED BY COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF THE WORK OTHER THAN AS AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED. BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE TO BE BOUND BY THE TERMS OF THIS LICENSE. TO THE EXTENT THIS LICENSE MAY BE CONSIDERED TO BE A CONTRACT, THE LICENSOR GRANTS YOU THE RIGHTS CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND CONDITIONS. Please see LICENSE for full legal details and the following URL for a human-readable explanation:
Copyright ( C ) 2005 - 2008 Wager Labs , SA CREATIVE COMMONS PUBLIC LICENSE ( " CCPL " OR " LICENSE " ) . THE WORK IS -nc-sa/3.0/us/ -module(observer). -export([start/1, stop/1, observe/2]). -include("common.hrl"). -include("bot.hrl"). -include("pp.hrl"). -record(obs, { id, trace, parent, gid, winners, seats, games_started, games_to_watch, cancel_count, stop, events }). start([Parent, Trace, GamesToWatch]) -> Obs = #obs { trace = Trace, parent = Parent, winners = gb_trees:empty(), seats = gb_trees:empty(), games_started = 0, games_to_watch = GamesToWatch, cancel_count = -1, stop = false, events = [] }, {ok, observe, Obs}. stop(_) -> ok. observe(R, Data) -> Data1 = process(R, Data), maybe_report(R, Data1), if Data#obs.stop -> Next = stop, Events = Data#obs.events; true -> Next = continue, Events = [] end, {Next, Data1, Events}. process(R = #notify_join{}, Data) -> Seats1 = gb_trees:insert(R#notify_join.player, R#notify_join.seat, Data#obs.seats), Data#obs{ seats = Seats1 }; process(R = #notify_win{}, Data) -> Amt = R#notify_win.amount / 1.0, N = gb_trees:get(R#notify_win.player, Data#obs.seats), Winners1 = gb_trees:insert(N, Amt, Data#obs.winners), Data#obs{ winners = Winners1 }; process(R = #player_info{}, Data) -> PID = R#player_info.player, Amount = gb_trees:get(PID, Data#obs.winners), T1 = gb_trees:delete(PID, Data#obs.winners), Winners1 = gb_trees:insert(R#player_info.nick, Amount, T1), Data#obs{ winners = Winners1 }; process(R = #notify_start_game{}, Data) -> GID = R#notify_start_game.game, Started = Data#obs.games_started, Data#obs.parent ! {'START', GID}, Data#obs{ winners = gb_trees:empty(), games_started = Started + 1 }; process(R = #notify_cancel_game{}, Data) -> GID = R#notify_cancel_game.game, N = Data#obs.cancel_count, if Data#obs.games_started > 0 -> Data#obs.parent ! {'CANCEL', GID}, timer:sleep(50), Data#obs{ stop = true, events = [#unwatch{ game = GID }] }; true -> Data#obs{ cancel_count = N + 1 } end; process(R = #notify_end_game{}, Data) -> GID = R#notify_end_game.game, Data#obs.parent ! {'END', GID, Data#obs.winners}, N = Data#obs.games_to_watch, if N == 1 -> Data#obs{ stop = true, events = [#unwatch{ game = GID }] }; true -> Data#obs{ games_to_watch = N - 1 } end; process(_, Data) -> Data. maybe_report(R, #obs{ trace = true }) -> catch report(R); maybe_report(_, _) -> ok. report(R = #notify_join{}) -> io:format("~p: JOIN: ~p @ ~p~n", [R#notify_join.game, R#notify_join.player, R#notify_join.seat]); report(R = #notify_leave{}) -> io:format("~p: LEAVE: ~p~n", [R#notify_join.game, R#notify_join.player]); report(R = #game_info{}) -> io:format("Game #~w, #players: ~w, joined: ~w, waiting: ~w; ", [R#game_info.game, R#game_info.required, R#game_info.joined, R#game_info.waiting]), Limit = R#game_info.limit, io:format("limit: low: ~w, high: ~w~n", [Limit#limit.low, Limit#limit.high]); report(R = #seat_state{ state = ?PS_FOLD }) -> io:format("~p: FOLD: ~p~n", [R#seat_state.game, R#seat_state.player ]); report(#seat_state{}) -> ok; report(R = #notify_chat{}) -> io:format("~w: CHAT: ~w: ~p~n", [R#notify_chat.game, R#notify_chat.player, R#notify_chat.message]); report(R = #notify_draw{ card = 0 }) -> io:format("~w: CARD: ~w~n", [R#notify_draw.game, R#notify_draw.player]); report(R = #game_stage{}) -> io:format("~w: STAGE: ~w~n", [R#game_stage.game, R#game_stage.stage]); report(R = #notify_raise{}) when R#notify_raise.raise == 0, R#notify_raise.call == 0 -> io:format("~w: CHECK: ~w~n", [R#notify_raise.game, R#notify_raise.player]); report(R = #notify_raise{}) when R#notify_raise.call == 0 -> io:format("~w: CALL: ~w, ~-14.2. f~n", [R#notify_raise.game, R#notify_raise.player, R#notify_raise.raise / 1.0]); report(R = #notify_raise{}) -> io:format("~w: RAISE: ~w, ~-14.2. f~n", [R#notify_raise.game, R#notify_raise.player, R#notify_raise.raise / 1.0]); report(R = #notify_sb{}) -> io:format("~w: SB: ~w~n", [R#notify_sb.game, R#notify_sb.sb]); report(R = #notify_bb{}) -> io:format("~w: BB: ~w~n", [R#notify_bb.game, R#notify_bb.bb]); report(R = #notify_shared{}) -> io:format("~w: BOARD: ~w~n", [R#notify_shared.game, R#notify_shared.card]); report(R = #notify_win{}) -> io:format("~w: WIN: ~w, ~-14.2. f~n", [R#notify_win.game, R#notify_win.player, R#notify_win.amount / 1.0]); report(R = #notify_button{}) -> io:format("~w: DEALER: ~w~n", [R#notify_button.game, R#notify_button.button]); report(R = #notify_start_game{}) -> io:format("~w: START~n", [R#notify_start_game.game]); report(R = #notify_cancel_game{}) -> io:format("~w: CANCEL~n", [R#notify_cancel_game.game]); report(R = #notify_end_game{}) -> io:format("~w: END~n", [R#notify_end_game.game]); report(R = #notify_hand{}) -> H = hand:to_string(R#notify_hand.hand), io:format("~w: HAND: ~w, with ~p~n", [R#notify_hand.game, R#notify_hand.player, H]); report(R = #show_cards{}) -> Cards1 = [hand:card_to_string(Card) || Card <- R#show_cards.cards], io:format("~w: SHOW: ~w: ~p~n", [R#show_cards.game, R#show_cards.player, Cards1]); report(R) -> error_logger:error_report([{module, ?MODULE}, {line, ?LINE}, {message, R} ]), ok.
c66c49b43d8ce846822c4925597a3577e6124086297caad0c7546c2a9f6847ca
marcoonroad/shared-secret
shared_secret.ml
module type IMessage = sig type t type a module Encoder : sig val encode : a -> t end;; module Decoder : sig val decode : t -> a end;; end;; module Message (Type : sig type t end) ( ) : (IMessage with type a := Type.t) = struct type t = Type.t module Encoder = struct let encode msg = msg end;; module Decoder = struct let decode msg = msg end;; end;; module type IToken = sig type t type revoker exception RevokedToken exception AlreadyRevoked val create : unit -> t * revoker val revoke : revoker -> unit val revoked : t -> bool val (=) : t -> t -> bool end;; module Token : IToken = struct exception RevokedToken exception AlreadyRevoked class token ( ) = object val mutable revoked = false method rescind ( ) = if revoked then raise AlreadyRevoked else revoked <- true method rescinded ( ) = revoked end;; type t = token type revoker = token let create ( ) = let instance = new token ( ) in (instance, instance) let revoke instance = instance # rescind ( ) let revoked instance = instance # rescinded ( ) let (=) = (=) end;; module type IBox = sig type 'value t exception InvalidToken module Sealer : sig val seal : Token.t -> 'value -> 'value t end;; module Unsealer : sig val unseal : Token.t -> 'value t -> 'value end;; end;; module Box : IBox = struct type 'value t = Token.t * 'value exception InvalidToken module Sealer = struct let seal token value = if Token.revoked token then raise Token.RevokedToken else (token, value) end;; module Unsealer = struct let unseal token (token', value) = if Token.(token = token') then (if Token.revoked token' then raise Token.RevokedToken else value) else raise InvalidToken end;; end;; module type IException = sig type t module Raiser : sig val raise : t -> 'a end;; module Handler : sig val handle : (unit -> 'a) -> (t -> 'a) -> 'a end;; end;; module Exception (Type : sig type t end) : (IException with type t := Type.t) = struct exception Class of Type.t module Raiser = struct let raise value = raise (Class value) end;; module Handler = struct let handle unsafe handler = try unsafe ( ) with Class value -> handler value end;; end;; module Revocable ( ) = struct exception RevokedReference exception AlreadyRevoked let revoked = ref false let revocable lambda value = if !revoked then raise RevokedReference else lambda value let revoke ( ) = if !revoked then raise AlreadyRevoked else revoked := true end;; module Pair = struct let exceptional (type a) ( ) = let module Module = Exception (struct type t = a end) in let raiser = Module.Raiser.raise in let handler = Module.Handler.handle in (raiser, handler) let sealing ( ) = let (token, _) = Token.create ( ) in let sealer = Box.Sealer.seal token in let unsealer = Box.Unsealer.unseal token in (sealer, unsealer) end;; (* END *)
null
https://raw.githubusercontent.com/marcoonroad/shared-secret/26cc28c17ecdefe3991f9f4a899af6ab645817e4/lib/shared_secret.ml
ocaml
END
module type IMessage = sig type t type a module Encoder : sig val encode : a -> t end;; module Decoder : sig val decode : t -> a end;; end;; module Message (Type : sig type t end) ( ) : (IMessage with type a := Type.t) = struct type t = Type.t module Encoder = struct let encode msg = msg end;; module Decoder = struct let decode msg = msg end;; end;; module type IToken = sig type t type revoker exception RevokedToken exception AlreadyRevoked val create : unit -> t * revoker val revoke : revoker -> unit val revoked : t -> bool val (=) : t -> t -> bool end;; module Token : IToken = struct exception RevokedToken exception AlreadyRevoked class token ( ) = object val mutable revoked = false method rescind ( ) = if revoked then raise AlreadyRevoked else revoked <- true method rescinded ( ) = revoked end;; type t = token type revoker = token let create ( ) = let instance = new token ( ) in (instance, instance) let revoke instance = instance # rescind ( ) let revoked instance = instance # rescinded ( ) let (=) = (=) end;; module type IBox = sig type 'value t exception InvalidToken module Sealer : sig val seal : Token.t -> 'value -> 'value t end;; module Unsealer : sig val unseal : Token.t -> 'value t -> 'value end;; end;; module Box : IBox = struct type 'value t = Token.t * 'value exception InvalidToken module Sealer = struct let seal token value = if Token.revoked token then raise Token.RevokedToken else (token, value) end;; module Unsealer = struct let unseal token (token', value) = if Token.(token = token') then (if Token.revoked token' then raise Token.RevokedToken else value) else raise InvalidToken end;; end;; module type IException = sig type t module Raiser : sig val raise : t -> 'a end;; module Handler : sig val handle : (unit -> 'a) -> (t -> 'a) -> 'a end;; end;; module Exception (Type : sig type t end) : (IException with type t := Type.t) = struct exception Class of Type.t module Raiser = struct let raise value = raise (Class value) end;; module Handler = struct let handle unsafe handler = try unsafe ( ) with Class value -> handler value end;; end;; module Revocable ( ) = struct exception RevokedReference exception AlreadyRevoked let revoked = ref false let revocable lambda value = if !revoked then raise RevokedReference else lambda value let revoke ( ) = if !revoked then raise AlreadyRevoked else revoked := true end;; module Pair = struct let exceptional (type a) ( ) = let module Module = Exception (struct type t = a end) in let raiser = Module.Raiser.raise in let handler = Module.Handler.handle in (raiser, handler) let sealing ( ) = let (token, _) = Token.create ( ) in let sealer = Box.Sealer.seal token in let unsealer = Box.Unsealer.unseal token in (sealer, unsealer) end;;
7150083ac8ab9659fddb9c1b8fef03a8ba4b90f54f5d9dc8101cc3540a3f2494
Gopiandcode/guile-ocaml
guile.ml
GNU ( C ) 2021 This program is free software : you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , or ( at your option ) any later version . This program is distributed in the hope that it will be useful , but WITHOUT ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU General Public License for more details . You should have received a copy of the GNU General Public License along with this program . If not , see < / > . GNU Guile OCaml Bindings Copyright (C) 2021 Kiran Gopinathan This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see </>. *) type scm = Raw.scm let init_with f = ignore @@ Raw.scm_with_guile (fun v -> f (); v) Ctypes.null let with_continuation_barrier f = ignore @@ Raw.scm_with_continuation_barrier (fun v -> f (); v) Ctypes.null let init () = Raw.scm_init_guile () let shell () = Raw.scm_shell Sys.argv let load filename = Raw.scm_primitive_load filename let eol: scm = Ctypes.ptr_of_raw_address (Ctypes.Intptr.to_nativeint Raw.Bindings.scm_eol) let undefined: scm = Ctypes.ptr_of_raw_address (Ctypes.Intptr.to_nativeint Raw.Bindings.scm_undefined) let (=) l r = Raw.scm_is_eq l r module Bool = struct let t: scm = Ctypes.ptr_of_raw_address (Ctypes.Intptr.to_nativeint Raw.Bindings.scml_bool_t) let f: scm = Ctypes.ptr_of_raw_address (Ctypes.Intptr.to_nativeint Raw.Bindings.scml_bool_f) let boolean_p v = Raw.scm_boolean_p v let is_bool v = Raw.scm_is_bool v let not v = Raw.scm_not v let to_raw v = Raw.scm_from_bool v let from_raw v = Raw.scm_to_bool v end module Number = struct let number_p v = Raw.scm_number_p v let is_number v = Raw.scm_is_number v let integer_p v = Raw.scm_integer_p v let is_integer v = Raw.scm_is_integer v let exact_integer_p v = Raw.scm_exact_integer_p v let is_exact_integer v = Raw.scm_is_exact_integer v let char_from_raw v = Raw.scm_to_char v let schar_from_raw v = Raw.scm_to_schar v let uchar_from_raw v = Raw.scm_to_uchar v let short_from_raw v = Raw.scm_to_short v let ushort_from_raw v = Raw.scm_to_ushort v let int_from_raw v = Raw.scm_to_int v let uint_from_raw v = Raw.scm_to_uint v let long_from_raw v = Raw.scm_to_long v let ulong_from_raw v = Raw.scm_to_ulong v let long_long_from_raw v = Raw.scm_to_long_long v let ulong_long_from_raw v = Raw.scm_to_ulong_long v let size_t_from_raw v = Raw.scm_to_size_t v let char_to_raw v = Raw.scm_from_char v let schar_to_raw v = Raw.scm_from_schar v let uchar_to_raw v = Raw.scm_from_uchar v let short_to_raw v = Raw.scm_from_short v let ushort_to_raw v = Raw.scm_from_ushort v let int_to_raw v = Raw.scm_from_int v let uint_to_raw v = Raw.scm_from_uint v let long_to_raw v = Raw.scm_from_long v let ulong_to_raw v = Raw.scm_from_ulong v let long_long_to_raw v = Raw.scm_from_long_long v let ulong_long_to_raw v = Raw.scm_from_ulong_long v let size_t_to_raw v = Raw.scm_from_size_t v module Float = struct let real_p v = Raw.scm_real_p v let is_real v = Raw.scm_is_real v let rationalp v = Raw.scm_rational_p v let is_rational v = Raw.scm_is_rational v let rationalize v = Raw.scm_rationalize v let inf_p v = Raw.scm_inf_p v let nan_p v = Raw.scm_nan_p v let finite_p v = Raw.scm_finite_p v let nan v = Raw.scm_nan v let inf v = Raw.scm_inf v let numerator v = Raw.scm_numerator v let denominator v = Raw.scm_denominator v let from_raw v = Raw.scm_to_double v let to_raw v = Raw.scm_from_double v end module Complex = struct let complex_p v = Raw.scm_complex_p v let is_complex v = Raw.scm_is_complex v end let exact_p v = Raw.scm_exact_p v let is_exact v = Raw.scm_is_exact v let inexact_p v = Raw.scm_inexact_p v let is_inexact v = Raw.scm_is_inexact v let inexact_to_exact v = Raw.scm_inexact_to_exact v let exact_to_inexact v = Raw.scm_exact_to_inexact v end module Pair = struct let cons hd tl = Raw.scm_cons hd tl let car pair = Raw.scm_car pair let cdr pair = Raw.scm_cdr pair let caar pair = Raw.scm_caar pair let cadr pair = Raw.scm_cadr pair let cdar pair = Raw.scm_cdar pair let hd pair = car pair let tl pair = cdr pair let set_car pair vl = Raw.scm_setcar pair vl let set_cdr pair vl = Raw.scm_setcdr pair vl let is_cons x = Raw.scm_is_pair x let is_ncons x = not (is_cons x) end module List = struct let is_null = Raw.scm_is_null let of_raw f scm = let rec of_list acc f scm = if is_null scm then List.rev acc else begin if not @@ Pair.is_cons scm then failwith "found non-list construction"; let hd = Pair.car scm in let tl = Pair.cdr scm in of_list (f hd :: acc) f tl end in of_list [] f scm let rec to_raw f = function | [] -> eol | [x] -> Raw.scm_list_1 (f x) | [x1;x2] -> Raw.scm_list_2 (f x1) (f x2) | [x1;x2;x3] -> Raw.scm_list_3 (f x1) (f x2) (f x3) | [x1;x2;x3;x4] -> Raw.scm_list_4 (f x1) (f x2) (f x3) (f x4) | [x1;x2;x3;x4;x5] -> Raw.scm_list_5 (f x1) (f x2) (f x3) (f x4) (f x5) | hd :: tl -> Raw.scm_cons (f hd) (to_raw f tl) end module Char = struct let char_p v = Raw.scm_char_p v let is_char v = char_p v |> Bool.from_raw let alphabetic_p v = Raw.scm_char_alphabetic_p v let is_alphabetic v = alphabetic_p v |> Bool.from_raw let numeric_p v = Raw.scm_char_numeric_p v let is_numeric v = numeric_p v |> Bool.from_raw let whitespace_p v = Raw.scm_char_whitespace_p v let is_whitespace v = whitespace_p v |> Bool.from_raw let upper_case_p v = Raw.scm_char_upper_case_p v let is_upper_case v = upper_case_p v |> Bool.from_raw let lower_case_p v = Raw.scm_char_lower_case_p v let is_lower_case v = lower_case_p v |> Bool.from_raw let is_both_p v = Raw.scm_char_is_both_p v let is_both v = is_both_p v |> Bool.from_raw let general_category_p v = Raw.scm_char_general_category v let is_general_category v = general_category_p v |> Bool.from_raw let from_raw = Number.char_from_raw let to_raw = Number.char_to_raw end module String = struct let string_p v = Raw.scm_string_p v let is_string v = Raw.scm_is_string v let is_empty v = Raw.scm_string_null_p v let string ls = Raw.scm_string (List.to_raw Char.to_raw ls) let len s = Raw.scm_string_length s |> Number.int_from_raw let to_raw s = Raw.scm_from_locale_string s let from_raw s = let len = (len s) in let buf = Ctypes.CArray.make Ctypes.char len in let _ = Raw.scm_to_locale_stringbuf s (Ctypes.CArray.start buf) (Unsigned.Size_t.of_int len) in Ctypes.string_from_ptr (Ctypes.CArray.start buf) ~length:len end module Symbol = struct let symbol_p v = Raw.scm_symbol_p v let is_symbol v = symbol_p v |> Bool.from_raw let to_raw s = Raw.scm_string_from_utf8_symbol s let from_raw s = Raw.scm_symbol_to_string s |> String.from_raw let gensym s = Raw.scm_gensym (to_raw s) end module Error = struct let error ?key ?fn_name message = let key = match key with None -> Symbol.to_raw "ocaml-guile" | Some key -> key in Raw.scm_error key fn_name (Some message) eol Bool.f let catch ~tag f on_catch = ignore @@ Raw.scm_c_catch tag (fun null -> f (); null) Ctypes.null (fun null key args -> on_catch key args; null) Ctypes.null end module Functions = struct let safe_fun1 name f v = try f v with e -> Error.error ~fn_name:name (Printexc.to_string e) let safe_fun2 name f v1 v2 = try f v1 v2 with e -> Error.error ~fn_name:name (Printexc.to_string e) let safe_fun3 name f v1 v2 v3 = try f v1 v2 v3 with e -> Error.error ~fn_name:name (Printexc.to_string e) let safe_fun4 name f v1 v2 v3 v4 = try f v1 v2 v3 v4 with e -> Error.error ~fn_name:name (Printexc.to_string e) let safe_fun5 name f v1 v2 v3 v4 v5 = try f v1 v2 v3 v4 v5 with e -> Error.error ~fn_name:name (Printexc.to_string e) let safe_fun6 name f v1 v2 v3 v4 v5 v6 = try f v1 v2 v3 v4 v5 v6 with e -> Error.error ~fn_name:name (Printexc.to_string e) let safe_fun7 name f v1 v2 v3 v4 v5 v6 v7 = try f v1 v2 v3 v4 v5 v6 v7 with e -> Error.error ~fn_name:name (Printexc.to_string e) let safe_fun8 name f v1 v2 v3 v4 v5 v6 v7 v8 = try f v1 v2 v3 v4 v5 v6 v7 v8 with e -> Error.error ~fn_name:name (Printexc.to_string e) let safe_fun9 name f v1 v2 v3 v4 v5 v6 v7 v8 v9 = try f v1 v2 v3 v4 v5 v6 v7 v8 v9 with e -> Error.error ~fn_name:name (Printexc.to_string e) let safe_fun10 name f v1 v2 v3 v4 v5 v6 v7 v8 v9 v10 = try f v1 v2 v3 v4 v5 v6 v7 v8 v9 v10 with e -> Error.error ~fn_name:name (Printexc.to_string e) let register_fun1 : string -> ?no_opt:int -> ?rst: bool -> (scm -> scm) -> scm = fun fname ?no_opt ?rst f -> Raw.scm_define_gsubr_1 fname ?no_opt ?rst (safe_fun1 fname f) let register_fun2 : string -> ?no_opt:int -> ?rst: bool -> (scm -> scm -> scm) -> scm = fun fname ?no_opt ?rst f -> Raw.scm_define_gsubr_2 fname ?no_opt ?rst (safe_fun2 fname f) let register_fun3 : string -> ?no_opt:int -> ?rst: bool -> (scm -> scm -> scm -> scm) -> scm = fun fname ?no_opt ?rst f -> Raw.scm_define_gsubr_3 fname ?no_opt ?rst (safe_fun3 fname f) let register_fun4 : string -> ?no_opt:int -> ?rst: bool -> (scm -> scm -> scm -> scm -> scm) -> scm = fun fname ?no_opt ?rst f -> Raw.scm_define_gsubr_4 fname ?no_opt ?rst (safe_fun4 fname f) let register_fun5 : string -> ?no_opt:int -> ?rst: bool -> (scm -> scm -> scm -> scm -> scm -> scm) -> scm = fun fname ?no_opt ?rst f -> Raw.scm_define_gsubr_5 fname ?no_opt ?rst (safe_fun5 fname f) let register_fun6 : string -> ?no_opt:int -> ?rst: bool -> (scm -> scm -> scm -> scm -> scm -> scm -> scm) -> scm = fun fname ?no_opt ?rst f -> Raw.scm_define_gsubr_6 fname ?no_opt ?rst (safe_fun6 fname f) let register_fun7 : string -> ?no_opt:int -> ?rst: bool -> (scm -> scm -> scm -> scm -> scm -> scm -> scm -> scm) -> scm = fun fname ?no_opt ?rst f -> Raw.scm_define_gsubr_7 fname ?no_opt ?rst (safe_fun7 fname f) let register_fun8 : string -> ?no_opt:int -> ?rst: bool -> (scm -> scm -> scm -> scm -> scm -> scm -> scm -> scm -> scm) -> scm = fun fname ?no_opt ?rst f -> Raw.scm_define_gsubr_8 fname ?no_opt ?rst (safe_fun8 fname f) let register_fun9 : string -> ?no_opt:int -> ?rst: bool -> (scm -> scm -> scm -> scm -> scm -> scm -> scm -> scm -> scm -> scm) -> scm = fun fname ?no_opt ?rst f -> Raw.scm_define_gsubr_9 fname ?no_opt ?rst (safe_fun9 fname f) let register_fun10 : string -> ?no_opt:int -> ?rst: bool -> (scm -> scm -> scm -> scm -> scm -> scm -> scm -> scm -> scm -> scm -> scm) -> scm = fun fname ?no_opt ?rst f -> Raw.scm_define_gsubr_10 fname ?no_opt ?rst (safe_fun10 fname f) end let eval ?state s = let state = match state with Some state -> state | None -> Raw.scm_interaction_environment () in Raw.scm_eval s state let eval_string s = Raw.scm_eval_string (String.to_raw s) let to_string ?printer v = let printer = Option.value ~default:undefined printer in Raw.scm_object_to_string v printer |> String.from_raw module Sexp = struct let rec to_raw : Sexplib.Sexp.t -> scm = function | Atom a when Stdlib.(String.get a 0 = '"') -> String.to_raw Stdlib.(String.sub a 1 (String.length a - 2)) | Atom a -> begin match int_of_string_opt a with | Some n -> Number.int_to_raw n | None -> match float_of_string_opt a with Some f -> Number.Float.to_raw f | None -> Symbol.to_raw a end | List elts -> List.to_raw to_raw elts let rec from_raw : scm -> Sexplib.Sexp.t = fun s -> if Pair.is_cons s then loop [] s else Sexplib.Sexp.Atom (to_string s) and loop acc s = if Pair.is_cons s then let hd = Pair.hd s in let tl = Pair.tl s in loop (from_raw hd :: acc) tl else if List.is_null s then Sexplib.Sexp.List (Stdlib.List.rev acc) else Sexplib.Sexp.List (Stdlib.List.rev (from_raw s :: acc)) end module Module = struct let resolve v = Raw.scm_resolve_module v let with_current_module ~modl f = ignore @@ Raw.scm_call_with_current_module modl (fun null -> f (); null) Ctypes.null let lookup_variable ~modl name = Raw.scm_variable modl name let lookup ~modl name = Raw.scm_variable_ref modl name let is_defined ?modl name = let modl = Option.value modl ~default:undefined in Raw.scm_defined_p (Symbol.to_raw name) modl |> Bool.from_raw let define_module name f = Raw.scm_define_module name (fun null -> f (); null) Ctypes.null let define name vl = Raw.scm_define name vl let use v = Raw.scm_use_module v let export name = Raw.scm_export name Ctypes.null end
null
https://raw.githubusercontent.com/Gopiandcode/guile-ocaml/247adf5a6adbbfd85696498b390167a9faa77779/lib/guile.ml
ocaml
GNU ( C ) 2021 This program is free software : you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation , either version 3 of the License , or ( at your option ) any later version . This program is distributed in the hope that it will be useful , but WITHOUT ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU General Public License for more details . You should have received a copy of the GNU General Public License along with this program . If not , see < / > . GNU Guile OCaml Bindings Copyright (C) 2021 Kiran Gopinathan This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see </>. *) type scm = Raw.scm let init_with f = ignore @@ Raw.scm_with_guile (fun v -> f (); v) Ctypes.null let with_continuation_barrier f = ignore @@ Raw.scm_with_continuation_barrier (fun v -> f (); v) Ctypes.null let init () = Raw.scm_init_guile () let shell () = Raw.scm_shell Sys.argv let load filename = Raw.scm_primitive_load filename let eol: scm = Ctypes.ptr_of_raw_address (Ctypes.Intptr.to_nativeint Raw.Bindings.scm_eol) let undefined: scm = Ctypes.ptr_of_raw_address (Ctypes.Intptr.to_nativeint Raw.Bindings.scm_undefined) let (=) l r = Raw.scm_is_eq l r module Bool = struct let t: scm = Ctypes.ptr_of_raw_address (Ctypes.Intptr.to_nativeint Raw.Bindings.scml_bool_t) let f: scm = Ctypes.ptr_of_raw_address (Ctypes.Intptr.to_nativeint Raw.Bindings.scml_bool_f) let boolean_p v = Raw.scm_boolean_p v let is_bool v = Raw.scm_is_bool v let not v = Raw.scm_not v let to_raw v = Raw.scm_from_bool v let from_raw v = Raw.scm_to_bool v end module Number = struct let number_p v = Raw.scm_number_p v let is_number v = Raw.scm_is_number v let integer_p v = Raw.scm_integer_p v let is_integer v = Raw.scm_is_integer v let exact_integer_p v = Raw.scm_exact_integer_p v let is_exact_integer v = Raw.scm_is_exact_integer v let char_from_raw v = Raw.scm_to_char v let schar_from_raw v = Raw.scm_to_schar v let uchar_from_raw v = Raw.scm_to_uchar v let short_from_raw v = Raw.scm_to_short v let ushort_from_raw v = Raw.scm_to_ushort v let int_from_raw v = Raw.scm_to_int v let uint_from_raw v = Raw.scm_to_uint v let long_from_raw v = Raw.scm_to_long v let ulong_from_raw v = Raw.scm_to_ulong v let long_long_from_raw v = Raw.scm_to_long_long v let ulong_long_from_raw v = Raw.scm_to_ulong_long v let size_t_from_raw v = Raw.scm_to_size_t v let char_to_raw v = Raw.scm_from_char v let schar_to_raw v = Raw.scm_from_schar v let uchar_to_raw v = Raw.scm_from_uchar v let short_to_raw v = Raw.scm_from_short v let ushort_to_raw v = Raw.scm_from_ushort v let int_to_raw v = Raw.scm_from_int v let uint_to_raw v = Raw.scm_from_uint v let long_to_raw v = Raw.scm_from_long v let ulong_to_raw v = Raw.scm_from_ulong v let long_long_to_raw v = Raw.scm_from_long_long v let ulong_long_to_raw v = Raw.scm_from_ulong_long v let size_t_to_raw v = Raw.scm_from_size_t v module Float = struct let real_p v = Raw.scm_real_p v let is_real v = Raw.scm_is_real v let rationalp v = Raw.scm_rational_p v let is_rational v = Raw.scm_is_rational v let rationalize v = Raw.scm_rationalize v let inf_p v = Raw.scm_inf_p v let nan_p v = Raw.scm_nan_p v let finite_p v = Raw.scm_finite_p v let nan v = Raw.scm_nan v let inf v = Raw.scm_inf v let numerator v = Raw.scm_numerator v let denominator v = Raw.scm_denominator v let from_raw v = Raw.scm_to_double v let to_raw v = Raw.scm_from_double v end module Complex = struct let complex_p v = Raw.scm_complex_p v let is_complex v = Raw.scm_is_complex v end let exact_p v = Raw.scm_exact_p v let is_exact v = Raw.scm_is_exact v let inexact_p v = Raw.scm_inexact_p v let is_inexact v = Raw.scm_is_inexact v let inexact_to_exact v = Raw.scm_inexact_to_exact v let exact_to_inexact v = Raw.scm_exact_to_inexact v end module Pair = struct let cons hd tl = Raw.scm_cons hd tl let car pair = Raw.scm_car pair let cdr pair = Raw.scm_cdr pair let caar pair = Raw.scm_caar pair let cadr pair = Raw.scm_cadr pair let cdar pair = Raw.scm_cdar pair let hd pair = car pair let tl pair = cdr pair let set_car pair vl = Raw.scm_setcar pair vl let set_cdr pair vl = Raw.scm_setcdr pair vl let is_cons x = Raw.scm_is_pair x let is_ncons x = not (is_cons x) end module List = struct let is_null = Raw.scm_is_null let of_raw f scm = let rec of_list acc f scm = if is_null scm then List.rev acc else begin if not @@ Pair.is_cons scm then failwith "found non-list construction"; let hd = Pair.car scm in let tl = Pair.cdr scm in of_list (f hd :: acc) f tl end in of_list [] f scm let rec to_raw f = function | [] -> eol | [x] -> Raw.scm_list_1 (f x) | [x1;x2] -> Raw.scm_list_2 (f x1) (f x2) | [x1;x2;x3] -> Raw.scm_list_3 (f x1) (f x2) (f x3) | [x1;x2;x3;x4] -> Raw.scm_list_4 (f x1) (f x2) (f x3) (f x4) | [x1;x2;x3;x4;x5] -> Raw.scm_list_5 (f x1) (f x2) (f x3) (f x4) (f x5) | hd :: tl -> Raw.scm_cons (f hd) (to_raw f tl) end module Char = struct let char_p v = Raw.scm_char_p v let is_char v = char_p v |> Bool.from_raw let alphabetic_p v = Raw.scm_char_alphabetic_p v let is_alphabetic v = alphabetic_p v |> Bool.from_raw let numeric_p v = Raw.scm_char_numeric_p v let is_numeric v = numeric_p v |> Bool.from_raw let whitespace_p v = Raw.scm_char_whitespace_p v let is_whitespace v = whitespace_p v |> Bool.from_raw let upper_case_p v = Raw.scm_char_upper_case_p v let is_upper_case v = upper_case_p v |> Bool.from_raw let lower_case_p v = Raw.scm_char_lower_case_p v let is_lower_case v = lower_case_p v |> Bool.from_raw let is_both_p v = Raw.scm_char_is_both_p v let is_both v = is_both_p v |> Bool.from_raw let general_category_p v = Raw.scm_char_general_category v let is_general_category v = general_category_p v |> Bool.from_raw let from_raw = Number.char_from_raw let to_raw = Number.char_to_raw end module String = struct let string_p v = Raw.scm_string_p v let is_string v = Raw.scm_is_string v let is_empty v = Raw.scm_string_null_p v let string ls = Raw.scm_string (List.to_raw Char.to_raw ls) let len s = Raw.scm_string_length s |> Number.int_from_raw let to_raw s = Raw.scm_from_locale_string s let from_raw s = let len = (len s) in let buf = Ctypes.CArray.make Ctypes.char len in let _ = Raw.scm_to_locale_stringbuf s (Ctypes.CArray.start buf) (Unsigned.Size_t.of_int len) in Ctypes.string_from_ptr (Ctypes.CArray.start buf) ~length:len end module Symbol = struct let symbol_p v = Raw.scm_symbol_p v let is_symbol v = symbol_p v |> Bool.from_raw let to_raw s = Raw.scm_string_from_utf8_symbol s let from_raw s = Raw.scm_symbol_to_string s |> String.from_raw let gensym s = Raw.scm_gensym (to_raw s) end module Error = struct let error ?key ?fn_name message = let key = match key with None -> Symbol.to_raw "ocaml-guile" | Some key -> key in Raw.scm_error key fn_name (Some message) eol Bool.f let catch ~tag f on_catch = ignore @@ Raw.scm_c_catch tag (fun null -> f (); null) Ctypes.null (fun null key args -> on_catch key args; null) Ctypes.null end module Functions = struct let safe_fun1 name f v = try f v with e -> Error.error ~fn_name:name (Printexc.to_string e) let safe_fun2 name f v1 v2 = try f v1 v2 with e -> Error.error ~fn_name:name (Printexc.to_string e) let safe_fun3 name f v1 v2 v3 = try f v1 v2 v3 with e -> Error.error ~fn_name:name (Printexc.to_string e) let safe_fun4 name f v1 v2 v3 v4 = try f v1 v2 v3 v4 with e -> Error.error ~fn_name:name (Printexc.to_string e) let safe_fun5 name f v1 v2 v3 v4 v5 = try f v1 v2 v3 v4 v5 with e -> Error.error ~fn_name:name (Printexc.to_string e) let safe_fun6 name f v1 v2 v3 v4 v5 v6 = try f v1 v2 v3 v4 v5 v6 with e -> Error.error ~fn_name:name (Printexc.to_string e) let safe_fun7 name f v1 v2 v3 v4 v5 v6 v7 = try f v1 v2 v3 v4 v5 v6 v7 with e -> Error.error ~fn_name:name (Printexc.to_string e) let safe_fun8 name f v1 v2 v3 v4 v5 v6 v7 v8 = try f v1 v2 v3 v4 v5 v6 v7 v8 with e -> Error.error ~fn_name:name (Printexc.to_string e) let safe_fun9 name f v1 v2 v3 v4 v5 v6 v7 v8 v9 = try f v1 v2 v3 v4 v5 v6 v7 v8 v9 with e -> Error.error ~fn_name:name (Printexc.to_string e) let safe_fun10 name f v1 v2 v3 v4 v5 v6 v7 v8 v9 v10 = try f v1 v2 v3 v4 v5 v6 v7 v8 v9 v10 with e -> Error.error ~fn_name:name (Printexc.to_string e) let register_fun1 : string -> ?no_opt:int -> ?rst: bool -> (scm -> scm) -> scm = fun fname ?no_opt ?rst f -> Raw.scm_define_gsubr_1 fname ?no_opt ?rst (safe_fun1 fname f) let register_fun2 : string -> ?no_opt:int -> ?rst: bool -> (scm -> scm -> scm) -> scm = fun fname ?no_opt ?rst f -> Raw.scm_define_gsubr_2 fname ?no_opt ?rst (safe_fun2 fname f) let register_fun3 : string -> ?no_opt:int -> ?rst: bool -> (scm -> scm -> scm -> scm) -> scm = fun fname ?no_opt ?rst f -> Raw.scm_define_gsubr_3 fname ?no_opt ?rst (safe_fun3 fname f) let register_fun4 : string -> ?no_opt:int -> ?rst: bool -> (scm -> scm -> scm -> scm -> scm) -> scm = fun fname ?no_opt ?rst f -> Raw.scm_define_gsubr_4 fname ?no_opt ?rst (safe_fun4 fname f) let register_fun5 : string -> ?no_opt:int -> ?rst: bool -> (scm -> scm -> scm -> scm -> scm -> scm) -> scm = fun fname ?no_opt ?rst f -> Raw.scm_define_gsubr_5 fname ?no_opt ?rst (safe_fun5 fname f) let register_fun6 : string -> ?no_opt:int -> ?rst: bool -> (scm -> scm -> scm -> scm -> scm -> scm -> scm) -> scm = fun fname ?no_opt ?rst f -> Raw.scm_define_gsubr_6 fname ?no_opt ?rst (safe_fun6 fname f) let register_fun7 : string -> ?no_opt:int -> ?rst: bool -> (scm -> scm -> scm -> scm -> scm -> scm -> scm -> scm) -> scm = fun fname ?no_opt ?rst f -> Raw.scm_define_gsubr_7 fname ?no_opt ?rst (safe_fun7 fname f) let register_fun8 : string -> ?no_opt:int -> ?rst: bool -> (scm -> scm -> scm -> scm -> scm -> scm -> scm -> scm -> scm) -> scm = fun fname ?no_opt ?rst f -> Raw.scm_define_gsubr_8 fname ?no_opt ?rst (safe_fun8 fname f) let register_fun9 : string -> ?no_opt:int -> ?rst: bool -> (scm -> scm -> scm -> scm -> scm -> scm -> scm -> scm -> scm -> scm) -> scm = fun fname ?no_opt ?rst f -> Raw.scm_define_gsubr_9 fname ?no_opt ?rst (safe_fun9 fname f) let register_fun10 : string -> ?no_opt:int -> ?rst: bool -> (scm -> scm -> scm -> scm -> scm -> scm -> scm -> scm -> scm -> scm -> scm) -> scm = fun fname ?no_opt ?rst f -> Raw.scm_define_gsubr_10 fname ?no_opt ?rst (safe_fun10 fname f) end let eval ?state s = let state = match state with Some state -> state | None -> Raw.scm_interaction_environment () in Raw.scm_eval s state let eval_string s = Raw.scm_eval_string (String.to_raw s) let to_string ?printer v = let printer = Option.value ~default:undefined printer in Raw.scm_object_to_string v printer |> String.from_raw module Sexp = struct let rec to_raw : Sexplib.Sexp.t -> scm = function | Atom a when Stdlib.(String.get a 0 = '"') -> String.to_raw Stdlib.(String.sub a 1 (String.length a - 2)) | Atom a -> begin match int_of_string_opt a with | Some n -> Number.int_to_raw n | None -> match float_of_string_opt a with Some f -> Number.Float.to_raw f | None -> Symbol.to_raw a end | List elts -> List.to_raw to_raw elts let rec from_raw : scm -> Sexplib.Sexp.t = fun s -> if Pair.is_cons s then loop [] s else Sexplib.Sexp.Atom (to_string s) and loop acc s = if Pair.is_cons s then let hd = Pair.hd s in let tl = Pair.tl s in loop (from_raw hd :: acc) tl else if List.is_null s then Sexplib.Sexp.List (Stdlib.List.rev acc) else Sexplib.Sexp.List (Stdlib.List.rev (from_raw s :: acc)) end module Module = struct let resolve v = Raw.scm_resolve_module v let with_current_module ~modl f = ignore @@ Raw.scm_call_with_current_module modl (fun null -> f (); null) Ctypes.null let lookup_variable ~modl name = Raw.scm_variable modl name let lookup ~modl name = Raw.scm_variable_ref modl name let is_defined ?modl name = let modl = Option.value modl ~default:undefined in Raw.scm_defined_p (Symbol.to_raw name) modl |> Bool.from_raw let define_module name f = Raw.scm_define_module name (fun null -> f (); null) Ctypes.null let define name vl = Raw.scm_define name vl let use v = Raw.scm_use_module v let export name = Raw.scm_export name Ctypes.null end
f5c300120011fe89fa188f4aadff7202e02845e85ccee9b1c9a9e294ad973103
mck-/Open-VRP
greedy-best-insertion.lisp
;;; Greedy Best Insertion heuristic ;;; ------- Using a ( random ) sequence , insert the < Nodes > one by one in the best feasible < vehicle > ;;; and at the optimal location in its route. Used as a feasible initial solution to the Tabu Search . Randomizing the sequence assures a broad search space when using multi - run (in-package :open-vrp.algo) (defclass greedy-best-insertion (algo) ((name :initform "Greedy Best Insertion heuristic") (desc :initform "Randomly insert nodes one by one to best vehicle at best location. Used as initial solution for search algos."))) (defmethod run-algo ((p problem) (a greedy-best-insertion)) "Randomly insert <Nodes> one by one to best <vehicle> in best location. Returns <Algo> object when done." (handler-case (loop for node in (shuffle (cdr (map 'list #'(lambda (n) n) (problem-network p)))) do (perform-move p (get-best-insertion-move p node)) finally (init-algo p a) (return a)) (no-feasible-move () (print "No initial feasible solution!") (error 'no-initial-feasible-solution))))
null
https://raw.githubusercontent.com/mck-/Open-VRP/408cb67063474ab61ddfc1631b5ac39714f2535e/algo/greedy-best-insertion.lisp
lisp
Greedy Best Insertion heuristic ------- and at the optimal location in its route. Used as a feasible initial solution to the
Using a ( random ) sequence , insert the < Nodes > one by one in the best feasible < vehicle > Tabu Search . Randomizing the sequence assures a broad search space when using multi - run (in-package :open-vrp.algo) (defclass greedy-best-insertion (algo) ((name :initform "Greedy Best Insertion heuristic") (desc :initform "Randomly insert nodes one by one to best vehicle at best location. Used as initial solution for search algos."))) (defmethod run-algo ((p problem) (a greedy-best-insertion)) "Randomly insert <Nodes> one by one to best <vehicle> in best location. Returns <Algo> object when done." (handler-case (loop for node in (shuffle (cdr (map 'list #'(lambda (n) n) (problem-network p)))) do (perform-move p (get-best-insertion-move p node)) finally (init-algo p a) (return a)) (no-feasible-move () (print "No initial feasible solution!") (error 'no-initial-feasible-solution))))
86b3f52be8096b74949df5f4f83974749d577515fc1f63d1820da8f2ca869736
music-suite/music-suite
MusicXml.hs
# OPTIONS_GHC -fno - warn - dodgy - exports # ------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------- -- | Copyright : ( c ) 2012 -- -- License : BSD-style -- Maintainer : -- Stability : experimental -- Portability : portable -- A representation of MusicXML 3.0 . -- You may want to use the " Data . Music . MusicXml . Simple " module to generate the representation . -- -- For an introduction to MusicXML, see <>. module Data.Music.MusicXml ( -- * Score Score (..), ScoreHeader (..), Identification (..), Creator (..), Defaults (..), ScoreAttrs (..), PartAttrs (..), MeasureAttrs (..), -- ** Part list PartList (..), PartListElem (..), -- * Music Music (..), MusicElem (..), -- ** Attributes Attributes (..), TimeSignature (..), ClefSign (..), -- ** Notes Note (..), FullNote (..), IsChord, noChord, Tie (..), noTies, NoteProps (..), HasNoteProps (..), -- ** Notations Notation (..), Articulation (..), Ornament (..), Technical (..), -- ** Directions Direction (..), -- ** Lyrics Lyric (..), -- * Basic types -- ** Pitch Pitch (..), DisplayPitch (..), PitchClass, Semitones (..), noSemitones, Octaves (..), Fifths (..), Line (..), Mode (..), Accidental (..), -- ** Time Duration (..), NoteType (..), Divs (..), NoteVal (..), NoteSize (..), Beat (..), BeatType (..), -- ** Dynamics Dynamics, ----------------------------------------------------------------------------- -- ** Misc StemDirection (..), NoteHead (..), LineType (..), Level (..), BeamType (..), StartStop (..), StartStopChange (..), StartStopContinue (..), StartStopContinueChange (..), ----------------------------------------------------------------------------- -- * Import and export functions ----------------------------------------------------------------------------- toXml, showXml, readXml, ) where import Data.Music.MusicXml.Dynamics import Data.Music.MusicXml.Pitch import Data.Music.MusicXml.Read import Data.Music.MusicXml.Score import Data.Music.MusicXml.Write import Text.XML.Light hiding (Line) -- -------------------------------------------------------------------------------- -- Import and export functions -- -------------------------------------------------------------------------------- -- | -- Render a score as a MusicXML string. showXml :: Score -> String showXml = ppTopElement . toXml -- | -- Render a score as MusicXML. toXml :: Score -> Element toXml = fromSingle . write -- | Parse a MusicXML string into a score . readXml :: String -> Maybe Score readXml source = parseXMLDoc source >>= parseScore -- -------------------------------------------------------------------------------- fromSingle :: [a] -> a fromSingle [x] = x fromSingle _ = error "fromSingle: non-single list"
null
https://raw.githubusercontent.com/music-suite/music-suite/7f01fd62334c66418043b7a2d662af127f98685d/src/Data/Music/MusicXml.hs
haskell
----------------------------------------------------------------------------------- ----------------------------------------------------------------------------------- | License : BSD-style Stability : experimental Portability : portable For an introduction to MusicXML, see <>. * Score ** Part list * Music ** Attributes ** Notes ** Notations ** Directions ** Lyrics * Basic types ** Pitch ** Time ** Dynamics --------------------------------------------------------------------------- ** Misc --------------------------------------------------------------------------- * Import and export functions --------------------------------------------------------------------------- -------------------------------------------------------------------------------- Import and export functions -------------------------------------------------------------------------------- | Render a score as a MusicXML string. | Render a score as MusicXML. | --------------------------------------------------------------------------------
# OPTIONS_GHC -fno - warn - dodgy - exports # Copyright : ( c ) 2012 Maintainer : A representation of MusicXML 3.0 . You may want to use the " Data . Music . MusicXml . Simple " module to generate the representation . module Data.Music.MusicXml Score (..), ScoreHeader (..), Identification (..), Creator (..), Defaults (..), ScoreAttrs (..), PartAttrs (..), MeasureAttrs (..), PartList (..), PartListElem (..), Music (..), MusicElem (..), Attributes (..), TimeSignature (..), ClefSign (..), Note (..), FullNote (..), IsChord, noChord, Tie (..), noTies, NoteProps (..), HasNoteProps (..), Notation (..), Articulation (..), Ornament (..), Technical (..), Direction (..), Lyric (..), Pitch (..), DisplayPitch (..), PitchClass, Semitones (..), noSemitones, Octaves (..), Fifths (..), Line (..), Mode (..), Accidental (..), Duration (..), NoteType (..), Divs (..), NoteVal (..), NoteSize (..), Beat (..), BeatType (..), Dynamics, StemDirection (..), NoteHead (..), LineType (..), Level (..), BeamType (..), StartStop (..), StartStopChange (..), StartStopContinue (..), StartStopContinueChange (..), toXml, showXml, readXml, ) where import Data.Music.MusicXml.Dynamics import Data.Music.MusicXml.Pitch import Data.Music.MusicXml.Read import Data.Music.MusicXml.Score import Data.Music.MusicXml.Write import Text.XML.Light hiding (Line) showXml :: Score -> String showXml = ppTopElement . toXml toXml :: Score -> Element toXml = fromSingle . write Parse a MusicXML string into a score . readXml :: String -> Maybe Score readXml source = parseXMLDoc source >>= parseScore fromSingle :: [a] -> a fromSingle [x] = x fromSingle _ = error "fromSingle: non-single list"
5ffc864b16ec6dcc33333da5abeb8d742fd56a5d0dab742384ed0f5087472d15
facebook/infer
Mangled.mli
* Copyright ( c ) 2009 - 2013 , Monoidics ltd . * Copyright ( c ) Facebook , Inc. and its affiliates . * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree . * Copyright (c) 2009-2013, Monoidics ltd. * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) open! IStd (** Module for Mangled Names *) (** Type of mangled names *) type t [@@deriving compare, yojson_of, sexp, hash] val equal : t -> t -> bool (** Equality for mangled names *) val from_string : string -> t (** Convert a string to a mangled name *) val mangled : string -> string -> t (** Create a mangled name from a plain and mangled string *) val to_string : t -> string (** Convert a mangled name to a string *) val to_string_full : t -> string (** Convert a full mangled name to a string *) val pp : Format.formatter -> t -> unit (** Pretty print a mangled name *) val this : t val is_this : t -> bool val self : t [@@warning "-unused-value-declaration"] val is_self : t -> bool val return_param : t val is_return_param : t -> bool (** Set of Mangled. *) module Set : PrettyPrintable.PPSet with type elt = t (** Map with Mangled as key *) module Map : PrettyPrintable.PPMap with type key = t
null
https://raw.githubusercontent.com/facebook/infer/4ee1c2a8e783ee770b61547a38ff1715d6ed75fe/infer/src/IR/Mangled.mli
ocaml
* Module for Mangled Names * Type of mangled names * Equality for mangled names * Convert a string to a mangled name * Create a mangled name from a plain and mangled string * Convert a mangled name to a string * Convert a full mangled name to a string * Pretty print a mangled name * Set of Mangled. * Map with Mangled as key
* Copyright ( c ) 2009 - 2013 , Monoidics ltd . * Copyright ( c ) Facebook , Inc. and its affiliates . * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree . * Copyright (c) 2009-2013, Monoidics ltd. * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) open! IStd type t [@@deriving compare, yojson_of, sexp, hash] val equal : t -> t -> bool val from_string : string -> t val mangled : string -> string -> t val to_string : t -> string val to_string_full : t -> string val pp : Format.formatter -> t -> unit val this : t val is_this : t -> bool val self : t [@@warning "-unused-value-declaration"] val is_self : t -> bool val return_param : t val is_return_param : t -> bool module Set : PrettyPrintable.PPSet with type elt = t module Map : PrettyPrintable.PPMap with type key = t
3865ffa8476987c5ebcaa20f016dde99b73235386c84c17556fa86d3173d6e63
emqx/minirest
minirest_handler.erl
Copyright ( c ) 2013 - 2022 EMQ Technologies Co. , Ltd. All Rights Reserved . %% Licensed under the Apache License , Version 2.0 ( the " License " ) ; %% you may not use this file except in compliance with the License. %% You may obtain a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %% See the License for the specific language governing permissions and %% limitations under the License. -module(minirest_handler). -export([init/2]). -include("minirest_http.hrl"). -include("minirest.hrl"). %%============================================================================================== %% cowboy callback init init(Request0, State)-> Request = case handle(Request0, State) of {error, {StatusCode, Headers, Body}} -> cowboy_req:reply(StatusCode, Headers, Body, Request0); {ok, Response, Handler} -> reply(Response, Request0, Handler) end, {ok, Request, State}. %%%============================================================================================== %% internal handle(Request, State) -> Method = cowboy_req:method(Request), case maps:find(Method, State) of error -> Headers = allow_method_header(maps:keys(State)), {error, {?RESPONSE_CODE_METHOD_NOT_ALLOWED, Headers, <<"">>}}; {ok, Handler} -> {ok, do_auth(Request, Handler), Handler} end. allow_method_header(Allow) -> #{<<"allow">> => trans_allow(Allow, <<"">>)}. trans_allow([], Res) -> Res; trans_allow([Method], Res) -> <<Res/binary, Method/binary>>; trans_allow([Method | Allow], Res) -> trans_allow(Allow, <<Res/binary, Method/binary, ", ">>). do_auth(Request, Handler = #handler{authorization = {M, F}}) -> case erlang:apply(M, F, [Request]) of ok -> do_parse_params(Request, Handler); Response when is_tuple(Response) -> Response; _ -> {?RESPONSE_CODE_UNAUTHORIZED} end; do_auth(Request, Handler) -> do_parse_params(Request, Handler). do_parse_params(Request, Handler) -> Params = #{ bindings => cowboy_req:bindings(Request), query_string => maps:from_list(cowboy_req:parse_qs(Request)), headers => cowboy_req:headers(Request), body => #{} }, do_read_body(Request, Params, Handler). do_read_body(Request, Params, Handler) -> case cowboy_req:has_body(Request) of true -> case minirest_body:parse(Request) of {ok, Body, NRequest} -> do_filter(NRequest, Params#{body => Body}, Handler); {response, Response} -> Response end; false -> do_filter(Request, Params, Handler) end. do_filter(Request, Params, #handler{filter = Filter, path = Path, module = Mod, method = Method} = Handler) when is_function(Filter, 2) -> case Filter(Params, #{path => Path, module => Mod, method => Method}) of {ok, NewParams} -> apply_callback(Request, NewParams, Handler); Response -> Response end; do_filter(Request, Params, Handler) -> apply_callback(Request, Params, Handler). apply_callback(Request, Params, Handler) -> #handler{path = Path, method = Method, module = Mod, function = Fun} = Handler, try Args = case erlang:function_exported(Mod, Fun, 3) of true -> [Method, Params, Request]; false -> [Method, Params] end, erlang:apply(Mod, Fun, Args) catch E:R:S -> ?LOG(warning, #{path => Path, exception => E, reason => R, stacktrace => S}), Message = list_to_binary(io_lib:format("~p, ~0p, ~0p", [E, R, S], [])), {?RESPONSE_CODE_INTERNAL_SERVER_ERROR, 'INTERNAL_ERROR', Message} end. %% response error reply({ErrorStatus, #{code := Code, message := Message}}, Req, Handler) when (ErrorStatus < 200 orelse 300 =< ErrorStatus) andalso is_atom(Code) -> reply({ErrorStatus, Code, Message}, Req, Handler); reply({ErrorStatus, Code, Message}, Req, Handler = #handler{error_codes = Codes}) when (ErrorStatus < 200 orelse 300 =< ErrorStatus) andalso is_atom(Code) -> case maybe_ignore_code_check(ErrorStatus, Code) orelse lists:member(Code, Codes) of true -> ErrorMessageStruct = {message, #{code => Code, message => Message}}, {ok, Headers, Body} = minirest_body:encode(ErrorMessageStruct), reply({ErrorStatus, Headers, Body}, Req, Handler); false -> NewMessage = list_to_binary( io_lib:format( "not support code ~p, message ~p, schema def ~p", [Code, Message, Codes])), reply({500, NewMessage}, Req, Handler) end; %% response simple reply(StatusCode, Req, _Handler) when is_integer(StatusCode) -> cowboy_req:reply(StatusCode, Req); reply({StatusCode}, Req, _Handler) -> cowboy_req:reply(StatusCode, Req); reply({StatusCode, Body0}, Req, Handler) -> case minirest_body:encode(Body0) of {ok, Headers, Body} -> reply_with_body(StatusCode, Headers, Body, Req); {response, Response} -> reply(Response, Req, Handler) end; reply({StatusCode, Headers, Body0}, Req, Handler) -> case minirest_body:encode(Body0) of {ok, Headers1, Body} -> reply_with_body(StatusCode, maps:merge(Headers1, Headers), Body, Req); {response, Response} -> reply(Response, Req, Handler) end; reply(BadReturn, Req, _Handler) -> StatusCode = ?RESPONSE_CODE_INTERNAL_SERVER_ERROR, Body = io_lib:format("mini rest bad return ~p", [BadReturn]), cowboy_req:reply(StatusCode, #{<<"content-type">> => <<"text/plain">>}, Body, Req). reply_with_body(StatusCode, Headers, Body, Req) when is_binary(Body) -> cowboy_req:reply(StatusCode, Headers, Body, Req); reply_with_body(StatusCode, Headers, {qlc_handle, _} = BodyQH, Req0) -> Req1 = cowboy_req:stream_reply(StatusCode, Headers, Req0), qlc:fold( fun(Data, Req) -> cowboy_req:stream_body(Data, nofin, Req), Req end, Req1, BodyQH), cowboy_req:stream_body(<<>>, fin, Req1), Req1. maybe_ignore_code_check(401, _Code) -> true; maybe_ignore_code_check(400, 'BAD_REQUEST') -> true; maybe_ignore_code_check(500, 'INTERNAL_ERROR') -> true; maybe_ignore_code_check(_, _) -> false.
null
https://raw.githubusercontent.com/emqx/minirest/0203dfb0e0e196754753578659cd2b4e1a95fc2b/src/minirest_handler.erl
erlang
you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ============================================================================================== cowboy callback init ============================================================================================== internal response error response simple
Copyright ( c ) 2013 - 2022 EMQ Technologies Co. , Ltd. All Rights Reserved . Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(minirest_handler). -export([init/2]). -include("minirest_http.hrl"). -include("minirest.hrl"). init(Request0, State)-> Request = case handle(Request0, State) of {error, {StatusCode, Headers, Body}} -> cowboy_req:reply(StatusCode, Headers, Body, Request0); {ok, Response, Handler} -> reply(Response, Request0, Handler) end, {ok, Request, State}. handle(Request, State) -> Method = cowboy_req:method(Request), case maps:find(Method, State) of error -> Headers = allow_method_header(maps:keys(State)), {error, {?RESPONSE_CODE_METHOD_NOT_ALLOWED, Headers, <<"">>}}; {ok, Handler} -> {ok, do_auth(Request, Handler), Handler} end. allow_method_header(Allow) -> #{<<"allow">> => trans_allow(Allow, <<"">>)}. trans_allow([], Res) -> Res; trans_allow([Method], Res) -> <<Res/binary, Method/binary>>; trans_allow([Method | Allow], Res) -> trans_allow(Allow, <<Res/binary, Method/binary, ", ">>). do_auth(Request, Handler = #handler{authorization = {M, F}}) -> case erlang:apply(M, F, [Request]) of ok -> do_parse_params(Request, Handler); Response when is_tuple(Response) -> Response; _ -> {?RESPONSE_CODE_UNAUTHORIZED} end; do_auth(Request, Handler) -> do_parse_params(Request, Handler). do_parse_params(Request, Handler) -> Params = #{ bindings => cowboy_req:bindings(Request), query_string => maps:from_list(cowboy_req:parse_qs(Request)), headers => cowboy_req:headers(Request), body => #{} }, do_read_body(Request, Params, Handler). do_read_body(Request, Params, Handler) -> case cowboy_req:has_body(Request) of true -> case minirest_body:parse(Request) of {ok, Body, NRequest} -> do_filter(NRequest, Params#{body => Body}, Handler); {response, Response} -> Response end; false -> do_filter(Request, Params, Handler) end. do_filter(Request, Params, #handler{filter = Filter, path = Path, module = Mod, method = Method} = Handler) when is_function(Filter, 2) -> case Filter(Params, #{path => Path, module => Mod, method => Method}) of {ok, NewParams} -> apply_callback(Request, NewParams, Handler); Response -> Response end; do_filter(Request, Params, Handler) -> apply_callback(Request, Params, Handler). apply_callback(Request, Params, Handler) -> #handler{path = Path, method = Method, module = Mod, function = Fun} = Handler, try Args = case erlang:function_exported(Mod, Fun, 3) of true -> [Method, Params, Request]; false -> [Method, Params] end, erlang:apply(Mod, Fun, Args) catch E:R:S -> ?LOG(warning, #{path => Path, exception => E, reason => R, stacktrace => S}), Message = list_to_binary(io_lib:format("~p, ~0p, ~0p", [E, R, S], [])), {?RESPONSE_CODE_INTERNAL_SERVER_ERROR, 'INTERNAL_ERROR', Message} end. reply({ErrorStatus, #{code := Code, message := Message}}, Req, Handler) when (ErrorStatus < 200 orelse 300 =< ErrorStatus) andalso is_atom(Code) -> reply({ErrorStatus, Code, Message}, Req, Handler); reply({ErrorStatus, Code, Message}, Req, Handler = #handler{error_codes = Codes}) when (ErrorStatus < 200 orelse 300 =< ErrorStatus) andalso is_atom(Code) -> case maybe_ignore_code_check(ErrorStatus, Code) orelse lists:member(Code, Codes) of true -> ErrorMessageStruct = {message, #{code => Code, message => Message}}, {ok, Headers, Body} = minirest_body:encode(ErrorMessageStruct), reply({ErrorStatus, Headers, Body}, Req, Handler); false -> NewMessage = list_to_binary( io_lib:format( "not support code ~p, message ~p, schema def ~p", [Code, Message, Codes])), reply({500, NewMessage}, Req, Handler) end; reply(StatusCode, Req, _Handler) when is_integer(StatusCode) -> cowboy_req:reply(StatusCode, Req); reply({StatusCode}, Req, _Handler) -> cowboy_req:reply(StatusCode, Req); reply({StatusCode, Body0}, Req, Handler) -> case minirest_body:encode(Body0) of {ok, Headers, Body} -> reply_with_body(StatusCode, Headers, Body, Req); {response, Response} -> reply(Response, Req, Handler) end; reply({StatusCode, Headers, Body0}, Req, Handler) -> case minirest_body:encode(Body0) of {ok, Headers1, Body} -> reply_with_body(StatusCode, maps:merge(Headers1, Headers), Body, Req); {response, Response} -> reply(Response, Req, Handler) end; reply(BadReturn, Req, _Handler) -> StatusCode = ?RESPONSE_CODE_INTERNAL_SERVER_ERROR, Body = io_lib:format("mini rest bad return ~p", [BadReturn]), cowboy_req:reply(StatusCode, #{<<"content-type">> => <<"text/plain">>}, Body, Req). reply_with_body(StatusCode, Headers, Body, Req) when is_binary(Body) -> cowboy_req:reply(StatusCode, Headers, Body, Req); reply_with_body(StatusCode, Headers, {qlc_handle, _} = BodyQH, Req0) -> Req1 = cowboy_req:stream_reply(StatusCode, Headers, Req0), qlc:fold( fun(Data, Req) -> cowboy_req:stream_body(Data, nofin, Req), Req end, Req1, BodyQH), cowboy_req:stream_body(<<>>, fin, Req1), Req1. maybe_ignore_code_check(401, _Code) -> true; maybe_ignore_code_check(400, 'BAD_REQUEST') -> true; maybe_ignore_code_check(500, 'INTERNAL_ERROR') -> true; maybe_ignore_code_check(_, _) -> false.
4454d5e4a9d0ed50d18386e493fcc94d61486fde8feb2342c2f12fbe0c152d98
graninas/Functional-Design-and-Architecture
Language.hs
{-# LANGUAGE GADTs #-} module Andromeda.LogicControl.Language where import Andromeda.Hardware.Domain import Andromeda.LogicControl.Domain import Andromeda.Common.Value import qualified Andromeda.Hardware.Language.Hdl as L import qualified Andromeda.Hardware.Language.DeviceControl as L import Control.Monad.Free (Free, liftF) data LogicControlMethod next = forall a. EvalHdl (L.Hdl a) (a -> next) | forall a. EvalDeviceControl (L.DeviceControl a) (a -> next) | Report Message (() -> next) | Store Key Value (() -> next) instance Functor LogicControlMethod where fmap f (EvalHdl hdl next) = EvalHdl hdl (f . next) fmap f (EvalDeviceControl hdl next) = EvalDeviceControl hdl (f . next) fmap f (Report msg next) = Report msg (f . next) fmap f (Store key value next) = Store key value (f . next) type LogicControl a = Free LogicControlMethod a evalHdl :: L.Hdl a -> LogicControl a evalHdl hdl = liftF $ EvalHdl hdl id evalDeviceControl :: L.DeviceControl a -> LogicControl a evalDeviceControl hdl = liftF $ EvalDeviceControl hdl id report :: Message -> LogicControl () report msg = liftF $ Report msg id store :: Key -> Value -> LogicControl () store key value = liftF $ Store key value id
null
https://raw.githubusercontent.com/graninas/Functional-Design-and-Architecture/faee58404e7d766c6c21f1ffdf9a2e792aebb4cb/Second-Edition-Manning-Publications/BookSamples/CH06/Section6p1p1/src/Andromeda/LogicControl/Language.hs
haskell
# LANGUAGE GADTs #
module Andromeda.LogicControl.Language where import Andromeda.Hardware.Domain import Andromeda.LogicControl.Domain import Andromeda.Common.Value import qualified Andromeda.Hardware.Language.Hdl as L import qualified Andromeda.Hardware.Language.DeviceControl as L import Control.Monad.Free (Free, liftF) data LogicControlMethod next = forall a. EvalHdl (L.Hdl a) (a -> next) | forall a. EvalDeviceControl (L.DeviceControl a) (a -> next) | Report Message (() -> next) | Store Key Value (() -> next) instance Functor LogicControlMethod where fmap f (EvalHdl hdl next) = EvalHdl hdl (f . next) fmap f (EvalDeviceControl hdl next) = EvalDeviceControl hdl (f . next) fmap f (Report msg next) = Report msg (f . next) fmap f (Store key value next) = Store key value (f . next) type LogicControl a = Free LogicControlMethod a evalHdl :: L.Hdl a -> LogicControl a evalHdl hdl = liftF $ EvalHdl hdl id evalDeviceControl :: L.DeviceControl a -> LogicControl a evalDeviceControl hdl = liftF $ EvalDeviceControl hdl id report :: Message -> LogicControl () report msg = liftF $ Report msg id store :: Key -> Value -> LogicControl () store key value = liftF $ Store key value id
8a96b94151e54a7c25803e6e729ac0efeb455cfac4cd979f8ffecb3611bf4764
clf/lollimon
mylexer.ml
(***********************************************************************) (* *) (* Objective Caml *) (* *) , projet Cristal , INRIA Rocquencourt (* *) Copyright 1996 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the GNU Library General Public License , with (* the special exception on linking described in file ../LICENSE. *) (* *) (***********************************************************************) * * * significantly modified by and in September 2004 * * * significantly modified by Jeff Polakow and Pablo Lopez in September 2004 ****) type token = [ Kwd of string | Ident of string | String of string ]; (* The string buffering machinery *) value initial_buffer = String.create 32; value buffer = ref "" (*initial_buffer*); value bufpos = ref 0; value reset_buffer () = bufpos.val := 0; (*do { buffer.val := initial_buffer; bufpos.val := 0 };*) value store c = do { if bufpos.val >= String.length buffer.val then let newbuffer = String.create (2 * bufpos.val) in do { String.blit buffer.val 0 newbuffer 0 bufpos.val; buffer.val := newbuffer } else (); String.set buffer.val bufpos.val c; incr bufpos }; value get_string () = let s = String.sub buffer.val 0 bufpos.val in (* let _ = buffer.val := initial_buffer in *) do { reset_buffer(); s} ; (* The lexer *) exception BadChar of string; value make_lexer keyId keywords input = let row = ref 1 in let col = ref 0 in let chkNl c = if c = '\010' then do { incr row; col.val := 0 } else () in let err e = raise (Stream.Error (e^" at row "^(soi row.val)^" col "^(soi col.val))) in let fail () = do { ps 0 ("Lexer failed at row "^(soi row.val)^" col "^(soi col.val)^"\n"); raise Stream.Failure } in let kwd_table = Hashtbl.create 17 in let _ = List.iter (fun s -> Hashtbl.add kwd_table s (Kwd s)) keywords in let ident_or_keyword id = try Hashtbl.find kwd_table id with [ Not_found -> if List.mem id keyId then Kwd id else Ident id ] in let keyword_or_error c = let s = String.make 1 c in try Hashtbl.find kwd_table s with [ Not_found -> err ("Illegal character " ^ s) ] in let myjunk strm = do {incr col; Stream.junk strm} in let rec next_token (strm__ : Stream.t _) = match Stream.peek strm__ with [ Some (c as ' ' | '\010' | '\013' | '\009' | '\026' | '\012') -> do { myjunk strm__; chkNl c; next_token strm__ } | Some '"' -> let _ = myjunk strm__ in let s = strm__ in do { reset_buffer (); Some (String (string s),(row.val,col.val)) } | Some '(' -> do { myjunk strm__; maybe_comment strm__ } | Some '#' -> do { myjunk strm__; reset_buffer(); store '#'; Some (ident strm__,(row.val,col.val))} | Some c -> let _ = do { myjunk strm__; reset_buffer(); store c } in match Stream.peek strm__ with [ Some c1 -> do { store c1; if c = '-' && '0' <= c1 && c1 <= '9' then do { myjunk strm__; Some (ident strm__, (row.val,col.val)) } else try let res = Some (Hashtbl.find kwd_table (get_string()),(row.val,col.val)) in do { myjunk strm__; res } with [ Not_found -> do { reset_buffer(); store c; try Some (Hashtbl.find kwd_table (get_string()),(row.val,col.val)) with [ Not_found -> match c with [ ('A'..'Z' | 'a'..'z' | '_' | '0'..'9' | '\'' | '^') -> do { reset_buffer(); store c; Some (ident strm__,(row.val,col.val)) } | _ -> err ("Illegal character "^(String.make 1 c)) ] ] } ] } | None -> do { try Some (Hashtbl.find kwd_table (get_string()),(row.val,col.val)) with [ Not_found -> match c with [ ('A'..'Z' | 'a'..'z' | '_' | '0'..'9' | '\'') -> do { reset_buffer (); store c; Some (ident strm__,(row.val,col.val)) } | _ -> err ("Illegal character "^(String.make 1 c)) ]] } ] | _ -> None ] and ident (strm__ : Stream.t _) = match Stream.peek strm__ with [ Some (c as 'A'..'Z' | 'a'..'z' | '_' | '0'..'9' | '\'') -> do { myjunk strm__; store c; ident strm__ } | _ -> (ident_or_keyword (get_string ())) ] and string (strm__ : Stream.t _) = match Stream.peek strm__ with [ Some '"' -> do { myjunk strm__; get_string () } | Some '\\' -> let _ = myjunk strm__ in let c = try escape strm__ with [ Stream.Failure -> err "lexing error" ] in let s = strm__ in do { store c; string s } | Some c -> let _ = myjunk strm__ in let s = strm__ in do { chkNl c; store c; string s } | _ -> fail() ] and escape (strm__ : Stream.t _) = match Stream.peek strm__ with [ Some 'n' -> do { myjunk strm__; '\n' } | Some 'r' -> do { myjunk strm__; '\r' } | Some 't' -> do { myjunk strm__; '\t' } | Some ('0'..'9' as c1) -> do { myjunk strm__; match Stream.peek strm__ with [ Some ('0'..'9' as c2) -> do { myjunk strm__; match Stream.peek strm__ with [ Some ('0'..'9' as c3) -> do { myjunk strm__; Char.chr ((Char.code c1 - 48) * 100 + (Char.code c2 - 48) * 10 + (Char.code c3 - 48)) } | _ -> err "lexing error" ] } | _ -> err "lexing error" ] } | Some c -> do { myjunk strm__; c } | _ -> fail() ] and maybe_comment (strm__ : Stream.t _) = match Stream.peek strm__ with [ Some '*' -> let _ = myjunk strm__ in let s = strm__ in do { comment s; next_token s } | _ -> Some (keyword_or_error '(',(row.val,col.val)) ] and comment (strm__ : Stream.t _) = match Stream.peek strm__ with [ Some '(' -> do { myjunk strm__; maybe_nested_comment strm__ } | Some '*' -> do { myjunk strm__; maybe_end_comment strm__ } | Some c -> do { myjunk strm__; chkNl c; comment strm__ } | _ -> fail () ] and maybe_nested_comment (strm__ : Stream.t _) = match Stream.peek strm__ with [ Some '*' -> let _ = myjunk strm__ in let s = strm__ in do { comment s; comment s } | Some c -> do { myjunk strm__; chkNl c; comment strm__ } | _ -> fail() ] and maybe_end_comment (strm__ : Stream.t _) = match Stream.peek strm__ with [ Some ')' -> do { myjunk strm__; () } | Some '*' -> do { myjunk strm__; maybe_end_comment strm__ } | Some c -> do { myjunk strm__; chkNl c; comment strm__ } | _ -> fail() ] in Stream.from (fun count -> do { buffer.val := initial_buffer; next_token input }) ;
null
https://raw.githubusercontent.com/clf/lollimon/bc4290f5bb221c514b2a66ec427e85eec498c7be/src/mylexer.ml
ocaml
********************************************************************* Objective Caml the special exception on linking described in file ../LICENSE. ********************************************************************* The string buffering machinery initial_buffer do { buffer.val := initial_buffer; bufpos.val := 0 }; let _ = buffer.val := initial_buffer in The lexer
, projet Cristal , INRIA Rocquencourt Copyright 1996 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the GNU Library General Public License , with * * * significantly modified by and in September 2004 * * * significantly modified by Jeff Polakow and Pablo Lopez in September 2004 ****) type token = [ Kwd of string | Ident of string | String of string ]; value initial_buffer = String.create 32; value bufpos = ref 0; value reset_buffer () = bufpos.val := 0; value store c = do { if bufpos.val >= String.length buffer.val then let newbuffer = String.create (2 * bufpos.val) in do { String.blit buffer.val 0 newbuffer 0 bufpos.val; buffer.val := newbuffer } else (); String.set buffer.val bufpos.val c; incr bufpos }; value get_string () = let s = String.sub buffer.val 0 bufpos.val in do { reset_buffer(); s} ; exception BadChar of string; value make_lexer keyId keywords input = let row = ref 1 in let col = ref 0 in let chkNl c = if c = '\010' then do { incr row; col.val := 0 } else () in let err e = raise (Stream.Error (e^" at row "^(soi row.val)^" col "^(soi col.val))) in let fail () = do { ps 0 ("Lexer failed at row "^(soi row.val)^" col "^(soi col.val)^"\n"); raise Stream.Failure } in let kwd_table = Hashtbl.create 17 in let _ = List.iter (fun s -> Hashtbl.add kwd_table s (Kwd s)) keywords in let ident_or_keyword id = try Hashtbl.find kwd_table id with [ Not_found -> if List.mem id keyId then Kwd id else Ident id ] in let keyword_or_error c = let s = String.make 1 c in try Hashtbl.find kwd_table s with [ Not_found -> err ("Illegal character " ^ s) ] in let myjunk strm = do {incr col; Stream.junk strm} in let rec next_token (strm__ : Stream.t _) = match Stream.peek strm__ with [ Some (c as ' ' | '\010' | '\013' | '\009' | '\026' | '\012') -> do { myjunk strm__; chkNl c; next_token strm__ } | Some '"' -> let _ = myjunk strm__ in let s = strm__ in do { reset_buffer (); Some (String (string s),(row.val,col.val)) } | Some '(' -> do { myjunk strm__; maybe_comment strm__ } | Some '#' -> do { myjunk strm__; reset_buffer(); store '#'; Some (ident strm__,(row.val,col.val))} | Some c -> let _ = do { myjunk strm__; reset_buffer(); store c } in match Stream.peek strm__ with [ Some c1 -> do { store c1; if c = '-' && '0' <= c1 && c1 <= '9' then do { myjunk strm__; Some (ident strm__, (row.val,col.val)) } else try let res = Some (Hashtbl.find kwd_table (get_string()),(row.val,col.val)) in do { myjunk strm__; res } with [ Not_found -> do { reset_buffer(); store c; try Some (Hashtbl.find kwd_table (get_string()),(row.val,col.val)) with [ Not_found -> match c with [ ('A'..'Z' | 'a'..'z' | '_' | '0'..'9' | '\'' | '^') -> do { reset_buffer(); store c; Some (ident strm__,(row.val,col.val)) } | _ -> err ("Illegal character "^(String.make 1 c)) ] ] } ] } | None -> do { try Some (Hashtbl.find kwd_table (get_string()),(row.val,col.val)) with [ Not_found -> match c with [ ('A'..'Z' | 'a'..'z' | '_' | '0'..'9' | '\'') -> do { reset_buffer (); store c; Some (ident strm__,(row.val,col.val)) } | _ -> err ("Illegal character "^(String.make 1 c)) ]] } ] | _ -> None ] and ident (strm__ : Stream.t _) = match Stream.peek strm__ with [ Some (c as 'A'..'Z' | 'a'..'z' | '_' | '0'..'9' | '\'') -> do { myjunk strm__; store c; ident strm__ } | _ -> (ident_or_keyword (get_string ())) ] and string (strm__ : Stream.t _) = match Stream.peek strm__ with [ Some '"' -> do { myjunk strm__; get_string () } | Some '\\' -> let _ = myjunk strm__ in let c = try escape strm__ with [ Stream.Failure -> err "lexing error" ] in let s = strm__ in do { store c; string s } | Some c -> let _ = myjunk strm__ in let s = strm__ in do { chkNl c; store c; string s } | _ -> fail() ] and escape (strm__ : Stream.t _) = match Stream.peek strm__ with [ Some 'n' -> do { myjunk strm__; '\n' } | Some 'r' -> do { myjunk strm__; '\r' } | Some 't' -> do { myjunk strm__; '\t' } | Some ('0'..'9' as c1) -> do { myjunk strm__; match Stream.peek strm__ with [ Some ('0'..'9' as c2) -> do { myjunk strm__; match Stream.peek strm__ with [ Some ('0'..'9' as c3) -> do { myjunk strm__; Char.chr ((Char.code c1 - 48) * 100 + (Char.code c2 - 48) * 10 + (Char.code c3 - 48)) } | _ -> err "lexing error" ] } | _ -> err "lexing error" ] } | Some c -> do { myjunk strm__; c } | _ -> fail() ] and maybe_comment (strm__ : Stream.t _) = match Stream.peek strm__ with [ Some '*' -> let _ = myjunk strm__ in let s = strm__ in do { comment s; next_token s } | _ -> Some (keyword_or_error '(',(row.val,col.val)) ] and comment (strm__ : Stream.t _) = match Stream.peek strm__ with [ Some '(' -> do { myjunk strm__; maybe_nested_comment strm__ } | Some '*' -> do { myjunk strm__; maybe_end_comment strm__ } | Some c -> do { myjunk strm__; chkNl c; comment strm__ } | _ -> fail () ] and maybe_nested_comment (strm__ : Stream.t _) = match Stream.peek strm__ with [ Some '*' -> let _ = myjunk strm__ in let s = strm__ in do { comment s; comment s } | Some c -> do { myjunk strm__; chkNl c; comment strm__ } | _ -> fail() ] and maybe_end_comment (strm__ : Stream.t _) = match Stream.peek strm__ with [ Some ')' -> do { myjunk strm__; () } | Some '*' -> do { myjunk strm__; maybe_end_comment strm__ } | Some c -> do { myjunk strm__; chkNl c; comment strm__ } | _ -> fail() ] in Stream.from (fun count -> do { buffer.val := initial_buffer; next_token input }) ;
a802d3d393cf3dbbca8fa9023afe0a02613e038b6bf76031208cbf9865465882
ghl3/dataframe
core.clj
(ns dataframe.core (:refer-clojure :exclude [group-by]) (:require [dataframe.series] [dataframe.frame]) (:import (dataframe.series Series) (dataframe.frame Frame))) ; Multi Methods (defn delegate "Deligate the implementation of a multimethod to an existing function" [multifn dispatch-val f] (.. multifn (addMethod dispatch-val f))) (defn first-type [& args] (type (first args))) (defmulti ix first-type) (delegate ix Series dataframe.series/ix) (delegate ix Frame dataframe.frame/ix) (defmulti index first-type) (delegate index Series dataframe.series/index) (delegate index Frame dataframe.frame/index) (defmulti set-index first-type) (delegate set-index Series dataframe.series/set-index) (delegate set-index Frame dataframe.frame/set-index) (defmulti select first-type) (delegate select Series dataframe.series/select) (delegate select Frame dataframe.frame/select) (defmulti loc first-type) (delegate loc Series dataframe.series/loc) (delegate loc Frame dataframe.frame/loc) (defmulti subset first-type) (delegate subset Series dataframe.series/subset) (delegate subset Frame dataframe.frame/subset) (defmulti head first-type) (delegate head Series dataframe.series/head) (delegate head Frame dataframe.frame/head) (defmulti tail first-type) (delegate tail Series dataframe.series/tail) (delegate tail Frame dataframe.frame/tail) ; Imported series methods (def series dataframe.series/series) (def series? dataframe.series/series?) (def values dataframe.series/values) (def update-key dataframe.series/update-key) (def mapvals dataframe.series/mapvals) (def lt dataframe.series/lt) (def lte dataframe.series/lte) (def gt dataframe.series/gt) (def gte dataframe.series/gte) (def add dataframe.series/add) (def sub dataframe.series/sub) (def mul dataframe.series/mul) (def div dataframe.series/div) (def eq dataframe.series/eq) (def neq dataframe.series/neq) ; Imported frame methods (def frame dataframe.frame/frame) (def col dataframe.frame/col) (def column-map dataframe.frame/column-map) (def columns dataframe.frame/columns) (def assoc-ix dataframe.frame/assoc-ix) (def assoc-col dataframe.frame/assoc-col) (def iterrows dataframe.frame/iterrows) (def maprows->srs dataframe.frame/maprows->srs) (def maprows->df dataframe.frame/maprows->df) (def sort-rows dataframe.frame/sort-rows) (def group-by dataframe.frame/group-by) (def group-by-fn dataframe.frame/group-by-fn) (def join dataframe.frame/join) (defmacro with-> [& args] `(dataframe.frame/with-> ~@args))
null
https://raw.githubusercontent.com/ghl3/dataframe/31212c14669e31797ec13cde650a61fd97dbe6d2/src/dataframe/core.clj
clojure
Multi Methods Imported series methods Imported frame methods
(ns dataframe.core (:refer-clojure :exclude [group-by]) (:require [dataframe.series] [dataframe.frame]) (:import (dataframe.series Series) (dataframe.frame Frame))) (defn delegate "Deligate the implementation of a multimethod to an existing function" [multifn dispatch-val f] (.. multifn (addMethod dispatch-val f))) (defn first-type [& args] (type (first args))) (defmulti ix first-type) (delegate ix Series dataframe.series/ix) (delegate ix Frame dataframe.frame/ix) (defmulti index first-type) (delegate index Series dataframe.series/index) (delegate index Frame dataframe.frame/index) (defmulti set-index first-type) (delegate set-index Series dataframe.series/set-index) (delegate set-index Frame dataframe.frame/set-index) (defmulti select first-type) (delegate select Series dataframe.series/select) (delegate select Frame dataframe.frame/select) (defmulti loc first-type) (delegate loc Series dataframe.series/loc) (delegate loc Frame dataframe.frame/loc) (defmulti subset first-type) (delegate subset Series dataframe.series/subset) (delegate subset Frame dataframe.frame/subset) (defmulti head first-type) (delegate head Series dataframe.series/head) (delegate head Frame dataframe.frame/head) (defmulti tail first-type) (delegate tail Series dataframe.series/tail) (delegate tail Frame dataframe.frame/tail) (def series dataframe.series/series) (def series? dataframe.series/series?) (def values dataframe.series/values) (def update-key dataframe.series/update-key) (def mapvals dataframe.series/mapvals) (def lt dataframe.series/lt) (def lte dataframe.series/lte) (def gt dataframe.series/gt) (def gte dataframe.series/gte) (def add dataframe.series/add) (def sub dataframe.series/sub) (def mul dataframe.series/mul) (def div dataframe.series/div) (def eq dataframe.series/eq) (def neq dataframe.series/neq) (def frame dataframe.frame/frame) (def col dataframe.frame/col) (def column-map dataframe.frame/column-map) (def columns dataframe.frame/columns) (def assoc-ix dataframe.frame/assoc-ix) (def assoc-col dataframe.frame/assoc-col) (def iterrows dataframe.frame/iterrows) (def maprows->srs dataframe.frame/maprows->srs) (def maprows->df dataframe.frame/maprows->df) (def sort-rows dataframe.frame/sort-rows) (def group-by dataframe.frame/group-by) (def group-by-fn dataframe.frame/group-by-fn) (def join dataframe.frame/join) (defmacro with-> [& args] `(dataframe.frame/with-> ~@args))
d36ee0055f635686d90b6ac7e2f33736582822a154c4a18152112460484fd993
heliaxdev/extensible-data
Param.hs
import ParamBase import Extensible data With a do an <- newName "a" let a = varT an extendT "T" [an] [t|With $a|] $ defaultExtT { typeTX = [("Extra", [a])] } main :: IO () main = pure ()
null
https://raw.githubusercontent.com/heliaxdev/extensible-data/d11dee6006169cb537e95af28c3541a24194dea8/examples/param/Param.hs
haskell
import ParamBase import Extensible data With a do an <- newName "a" let a = varT an extendT "T" [an] [t|With $a|] $ defaultExtT { typeTX = [("Extra", [a])] } main :: IO () main = pure ()
8db3512fda251311b2ea02879b75a8a3b4b04ff21190abc5bbebb445fd134e8e
ewestern/geos
Main.hs
# LANGUAGE ScopedTypeVariables # module Main where import Test.Hspec import Data.Geometry.Geos.TopologySpec import Data.Geometry.Geos.RelatableSpec import Data.Geometry.Geos.SerializeSpec import Data.Geometry.Geos.STRTreeSpec main :: IO () main = hspec $ do topologySpec relatableSpec serializeSpec strSpec
null
https://raw.githubusercontent.com/ewestern/geos/3568c3449efe180bd89959c9247d4667137662b6/tests/Main.hs
haskell
# LANGUAGE ScopedTypeVariables # module Main where import Test.Hspec import Data.Geometry.Geos.TopologySpec import Data.Geometry.Geos.RelatableSpec import Data.Geometry.Geos.SerializeSpec import Data.Geometry.Geos.STRTreeSpec main :: IO () main = hspec $ do topologySpec relatableSpec serializeSpec strSpec
88ae2c483734bb51c6da1a70ba668000d2ca955cb8b50e309d1df4e5a466c2d1
ocaml/merlin
expansion.ml
open Std type t = Trie of (string * Longident.t * t list lazy_t) let rec explore_node lident env = let add_module name _ _ l = let lident = Longident.Ldot (lident, name) in Trie (name, lident, lazy (explore_node lident env)) :: l in Env.fold_modules add_module (Some lident) env [] let explore ?(global_modules=[]) env = let seen = let tbl = Hashtbl.create 7 in fun name -> Hashtbl.mem tbl name || (Hashtbl.add tbl name (); false) in let add_module l name = if seen name then l else let lident = Longident.Lident name in Trie (name, lident, lazy (explore_node lident env)) :: l in let add_module' name _ _ l = add_module l name in List.fold_left ~f:add_module global_modules ~init:(Env.fold_modules add_module' None env []) This is a hacked up heuristic spell checking function . It checks only the prefix of the key . A proper damerau - levenshtein might be better but certainly not urgent . Implementation is a fork of -cube/spelll/blob/master/src/spelll.ml Thanks companion - cube :) It checks only the prefix of the key. A proper damerau-levenshtein might be better but certainly not urgent. Implementation is a fork of -cube/spelll/blob/master/src/spelll.ml Thanks companion-cube :) *) let optimal_string_prefix_alignment key cutoff = let equal_char : char -> char -> bool = (=) in let min_int x y : int = if x < y then x else y in if String.length key = 0 then (fun str -> String.length str) else (* distance vectors (v0=previous, v1=current) *) let v0 = Array.make (String.length key + 1) 0 in let v1 = Array.make (String.length key + 1) 0 in fun str -> let l1 = min (String.length str) (String.length key) in if l1 = 0 then String.length key else if str = key then 0 else try (* initialize v0: v0(i) = A(0)(i) = delete i chars from t *) for i = 0 to String.length key do v0.(i) <- i done; (* main loop for the bottom up dynamic algorithm *) for i = 0 to l1 - 1 do (* first edit distance is the deletion of i+1 elements from s *) v1.(0) <- i+1; let min = ref (i+1) in (* try add/delete/replace operations *) for j = 0 to String.length key - 1 do let cost = if equal_char str.[i] key.[j] then 0 else 1 in v1.(j+1) <- min_int (v1.(j) + 1) (min_int (v0.(j+1) + 1) (v0.(j) + cost)); if i > 0 && j > 0 && str.[i] = key.[j-1] && str.[i-1] = key.[j] then v1.(j+1) <- min_int v1.(j+1) (v0.(j-1) + cost); min := min_int !min v1.(j+1) done; if !min > cutoff then raise Exit; (* copy v1 into v0 for next iteration *) Array.blit v1 0 v0 0 (String.length key + 1); done; let idx = String.length key in min v1.(idx-1) v1.(idx) with Exit -> cutoff + 1 let spell_index s1 = let cutoff = match String.length s1 with | 0 -> 0 | 1 -> 0 | 2 -> 0 | 3 -> 1 | _ -> 2 in let f = optimal_string_prefix_alignment s1 cutoff in fun s2 -> (s1 = "" || s2 = "" || (s1.[0] = s2.[0] && (f s2 <= cutoff))) let spell_match index str = index str let filter path ts = let path = List.map ~f:spell_index path in let rec aux_ts ts = function | [] -> [] | p0 :: ps -> List.filter_map ~f:(aux_t p0 ps) ts and aux_t p0 ps (Trie (name, ident, ts)) = if spell_match p0 name then Some (Trie (name, ident, lazy (aux_ts (Lazy.force ts) ps))) else None in aux_ts ts path let rec to_lidents len acc = function | Trie (_, lident, _) :: ts when len = 0 -> to_lidents len (lident :: acc) ts | Trie (_, _, lazy ts') :: ts -> to_lidents len (to_lidents (len - 1) acc ts') ts | [] -> acc let to_lidents len ts = to_lidents len [] ts let get_lidents ts path = let open Longident in let lident = parse path in let lident, last = match lident with | Ldot (l, id) -> l, id | Lident id -> Lident "", id | Lapply _ -> assert false in let rec components acc = function | Lident "" -> acc | Lident id -> id :: acc | Lapply _ -> assert false | Ldot (l, id) -> components (id :: acc) l in let lidents = match components [] lident with | [] -> [None] | components -> let ts = filter components ts in let lidents = to_lidents (List.length components - 1) ts in List.map ~f:(fun x -> Some x) lidents in lidents, last
null
https://raw.githubusercontent.com/ocaml/merlin/e576bc75f11323ec8489d2e58a701264f5a7fe0e/src/analysis/expansion.ml
ocaml
distance vectors (v0=previous, v1=current) initialize v0: v0(i) = A(0)(i) = delete i chars from t main loop for the bottom up dynamic algorithm first edit distance is the deletion of i+1 elements from s try add/delete/replace operations copy v1 into v0 for next iteration
open Std type t = Trie of (string * Longident.t * t list lazy_t) let rec explore_node lident env = let add_module name _ _ l = let lident = Longident.Ldot (lident, name) in Trie (name, lident, lazy (explore_node lident env)) :: l in Env.fold_modules add_module (Some lident) env [] let explore ?(global_modules=[]) env = let seen = let tbl = Hashtbl.create 7 in fun name -> Hashtbl.mem tbl name || (Hashtbl.add tbl name (); false) in let add_module l name = if seen name then l else let lident = Longident.Lident name in Trie (name, lident, lazy (explore_node lident env)) :: l in let add_module' name _ _ l = add_module l name in List.fold_left ~f:add_module global_modules ~init:(Env.fold_modules add_module' None env []) This is a hacked up heuristic spell checking function . It checks only the prefix of the key . A proper damerau - levenshtein might be better but certainly not urgent . Implementation is a fork of -cube/spelll/blob/master/src/spelll.ml Thanks companion - cube :) It checks only the prefix of the key. A proper damerau-levenshtein might be better but certainly not urgent. Implementation is a fork of -cube/spelll/blob/master/src/spelll.ml Thanks companion-cube :) *) let optimal_string_prefix_alignment key cutoff = let equal_char : char -> char -> bool = (=) in let min_int x y : int = if x < y then x else y in if String.length key = 0 then (fun str -> String.length str) else let v0 = Array.make (String.length key + 1) 0 in let v1 = Array.make (String.length key + 1) 0 in fun str -> let l1 = min (String.length str) (String.length key) in if l1 = 0 then String.length key else if str = key then 0 else try for i = 0 to String.length key do v0.(i) <- i done; for i = 0 to l1 - 1 do v1.(0) <- i+1; let min = ref (i+1) in for j = 0 to String.length key - 1 do let cost = if equal_char str.[i] key.[j] then 0 else 1 in v1.(j+1) <- min_int (v1.(j) + 1) (min_int (v0.(j+1) + 1) (v0.(j) + cost)); if i > 0 && j > 0 && str.[i] = key.[j-1] && str.[i-1] = key.[j] then v1.(j+1) <- min_int v1.(j+1) (v0.(j-1) + cost); min := min_int !min v1.(j+1) done; if !min > cutoff then raise Exit; Array.blit v1 0 v0 0 (String.length key + 1); done; let idx = String.length key in min v1.(idx-1) v1.(idx) with Exit -> cutoff + 1 let spell_index s1 = let cutoff = match String.length s1 with | 0 -> 0 | 1 -> 0 | 2 -> 0 | 3 -> 1 | _ -> 2 in let f = optimal_string_prefix_alignment s1 cutoff in fun s2 -> (s1 = "" || s2 = "" || (s1.[0] = s2.[0] && (f s2 <= cutoff))) let spell_match index str = index str let filter path ts = let path = List.map ~f:spell_index path in let rec aux_ts ts = function | [] -> [] | p0 :: ps -> List.filter_map ~f:(aux_t p0 ps) ts and aux_t p0 ps (Trie (name, ident, ts)) = if spell_match p0 name then Some (Trie (name, ident, lazy (aux_ts (Lazy.force ts) ps))) else None in aux_ts ts path let rec to_lidents len acc = function | Trie (_, lident, _) :: ts when len = 0 -> to_lidents len (lident :: acc) ts | Trie (_, _, lazy ts') :: ts -> to_lidents len (to_lidents (len - 1) acc ts') ts | [] -> acc let to_lidents len ts = to_lidents len [] ts let get_lidents ts path = let open Longident in let lident = parse path in let lident, last = match lident with | Ldot (l, id) -> l, id | Lident id -> Lident "", id | Lapply _ -> assert false in let rec components acc = function | Lident "" -> acc | Lident id -> id :: acc | Lapply _ -> assert false | Ldot (l, id) -> components (id :: acc) l in let lidents = match components [] lident with | [] -> [None] | components -> let ts = filter components ts in let lidents = to_lidents (List.length components - 1) ts in List.map ~f:(fun x -> Some x) lidents in lidents, last
915b7ca277ca2bf2004c2c79fd670ee0a8db948b0442f4c4e30f876059530c3a
the-dr-lazy/cascade
Prelude.hs
| Module : Cascade . Api . Test . Prelude Description : ! ! ! INSERT MODULE SHORT DESCRIPTION ! ! ! Copyright : ( c ) 2020 - 2021 Cascade License : MPL 2.0 Maintainer : < > ( the-dr-lazy.github.io ) Stability : Stable Portability : POSIX ! ! ! INSERT MODULE LONG DESCRIPTION ! ! ! Module : Cascade.Api.Test.Prelude Description : !!! INSERT MODULE SHORT DESCRIPTION !!! Copyright : (c) 2020-2021 Cascade License : MPL 2.0 Maintainer : Mohammad Hasani <> (the-dr-lazy.github.io) Stability : Stable Portability : POSIX !!! INSERT MODULE LONG DESCRIPTION !!! -} module Cascade.Api.Test.Prelude ( concreted , evalUnion ) where import Cascade.Api.Test.Prelude.Orphans () import Control.Lens ( Optic', Profunctor, to ) import Hedgehog ( Concrete, MonadTest, Var, concrete, evalMaybe ) import Servant.API.UVerb.Union ( IsMember, Union, matchUnion ) concreted :: (Profunctor p, Contravariant f) => Optic' p f (Var a Concrete) a concreted = to concrete evalUnion :: forall a as m . HasCallStack => MonadTest m => Show a => IsMember a as => Union as -> m a evalUnion = evalMaybe . matchUnion @a
null
https://raw.githubusercontent.com/the-dr-lazy/cascade/014a5589a2763ce373e8c84a211cddc479872b44/cascade-api/test/Cascade/Api/Test/Prelude.hs
haskell
| Module : Cascade . Api . Test . Prelude Description : ! ! ! INSERT MODULE SHORT DESCRIPTION ! ! ! Copyright : ( c ) 2020 - 2021 Cascade License : MPL 2.0 Maintainer : < > ( the-dr-lazy.github.io ) Stability : Stable Portability : POSIX ! ! ! INSERT MODULE LONG DESCRIPTION ! ! ! Module : Cascade.Api.Test.Prelude Description : !!! INSERT MODULE SHORT DESCRIPTION !!! Copyright : (c) 2020-2021 Cascade License : MPL 2.0 Maintainer : Mohammad Hasani <> (the-dr-lazy.github.io) Stability : Stable Portability : POSIX !!! INSERT MODULE LONG DESCRIPTION !!! -} module Cascade.Api.Test.Prelude ( concreted , evalUnion ) where import Cascade.Api.Test.Prelude.Orphans () import Control.Lens ( Optic', Profunctor, to ) import Hedgehog ( Concrete, MonadTest, Var, concrete, evalMaybe ) import Servant.API.UVerb.Union ( IsMember, Union, matchUnion ) concreted :: (Profunctor p, Contravariant f) => Optic' p f (Var a Concrete) a concreted = to concrete evalUnion :: forall a as m . HasCallStack => MonadTest m => Show a => IsMember a as => Union as -> m a evalUnion = evalMaybe . matchUnion @a
94cb2e92de04317154f7cba0217b71e6d951b6cbed7783b079c4d8644bd7cc4d
bdeket/rktsicm
ghelper.rkt
#lang racket/base (require (for-syntax racket/base) rackunit "../../kernel/cstm/ghelper.rkt") (define (any? _) #t) (define (nvr? _) #f) (define-syntax (test-it1 stx) (syntax-case stx () [(_ make-generic-operator) #'(test-case "foo" (define (foo-default x y z) 'foo-default) (define foo (make-generic-operator 3 'foo foo-default)) (check-equal? (get-operator-record foo) (operator-record 'foo 3 (tree '() #t foo-default))) (check-equal? (procedure-arity foo) 3) (check-exn #px"argument arity intersecting with operator arity" (λ () (assign-operation foo (λ (a b) 'a) any? any?))) (check-exn #px"argument arity intersecting with operator arity" (λ () (assign-operation foo (λ (a b c) 'a) any? any?))) (check-exn #px"argument arity intersecting with handler arity" (λ () (assign-operation foo (λ (a b) 'a) any? any? any?))) (check-exn #px"handler is within operator arity" (λ () (assign-operation foo (λ (a [b 1]) 'a) any? #:rest any?))) (check-equal? (get-operator-record foo) (operator-record 'foo 3 (tree '() #t foo-default))) (define (foo-handler1 a b c) 1) (define (a? m) (eq? m 'a))(define (b? m) (eq? m 'b))(define (c? m) (eq? m 'c)) (assign-operation foo foo-handler1 a? b? #:rest #t) (check-equal? (get-operator-record foo) (operator-record 'foo 3 (tree (list (cons a? (tree (list (cons b? (tree '() #t foo-handler1))) #f #f))) #t foo-default))) (define (foo-handler2 a b c) 2) (assign-operation foo foo-handler2 a? c? #:rest #t) (check-equal? (get-operator-record foo) (operator-record 'foo 3 (tree (list (cons a? (tree (list (cons c? (tree '() #t foo-handler2)) (cons b? (tree '() #t foo-handler1))) #f #f))) #t foo-default))) (define (foo-handler3 a b c) 3) (assign-operation foo foo-handler3 b? c? #:rest #t) (check-equal? (get-operator-record foo) (operator-record 'foo 3 (tree (list (cons b? (tree (list (cons c? (tree '() #t foo-handler3))) #f #f)) (cons a? (tree (list (cons c? (tree '() #t foo-handler2)) (cons b? (tree '() #t foo-handler1))) #f #f))) #t foo-default))) (define (foo-handler4 a b c) 4) (assign-operation foo foo-handler4 b? #:rest #t) (check-equal? (get-operator-record foo) (operator-record 'foo 3 (tree (list (cons b? (tree (list (cons c? (tree '() #t foo-handler3))) #t foo-handler4)) (cons a? (tree (list (cons c? (tree '() #t foo-handler2)) (cons b? (tree '() #t foo-handler1))) #f #f))) #t foo-default))) (define (foo-handler5 a b c) 5) (assign-operation foo foo-handler5 b? #:rest #t) (check-equal? (get-operator-record foo) (operator-record 'foo 3 (tree (list (cons b? (tree (list (cons c? (tree '() #t foo-handler3))) #t foo-handler5)) (cons a? (tree (list (cons c? (tree '() #t foo-handler2)) (cons b? (tree '() #t foo-handler1))) #f #f))) #t foo-default))) (check-equal? (foo 'a 'b 'b) 1) (check-equal? (foo 'a 'c 'c) 2) (check-equal? (foo 'b 'c 'c) 3) (check-equal? (foo 'b 'b 'b) 5) (check-equal? (foo 'c 'c 'c) 'foo-default) (check-equal? (foo 'a 'a 'c) 'foo-default))])) (define-syntax (test-it2 stx) (syntax-case stx () [(_ make-generic-operator) #'(test-case "bar" (define bar (make-generic-operator 1 'bar)) (check-equal? (procedure-arity bar) 1) (assign-operation bar (λ (x) x)) (check-equal? (procedure-arity (make-generic-operator (arity-at-least 2))) (arity-at-least 2)) (check-equal? (procedure-arity (make-generic-operator (list 0 (arity-at-least 2)))) (list 0 (arity-at-least 2))) (check-equal? (procedure-arity (make-generic-operator (list 1 2 (arity-at-least 2) 3))) (arity-at-least 1)) (check-equal? (procedure-arity (make-generic-operator (list 5 4 3))) '(3 4 5)))])) (define the-tests (test-suite "kernel/ghelper-class" (let () (local-require "../../kernel/ghelper-class.rkt") (test-it1 make-generic-operator) (test-it2 make-generic-operator)) (let () (local-require "../../kernel/ghelper-pro.rkt") (test-it1 make-generic-operator) (test-it2 make-generic-operator) (test-case "pro-special" (define foo (make-generic-operator 2 'foo)) (check-equal? (procedure-arity foo) 2) (assign-operation foo (λ (a b) (list a b)) (λ (x) (eq? x 'a)) #:rest #t) (check-equal? (foo 'a 'whatever) '(a whatever)) ;; ^^ this is different from ghelper-class (in in line with scmutils): rest args are not checked ;; in practice it seems the #:rest is only ever used for the top tree (which doesn't have a pred?) )) )) (module+ test (require rackunit/text-ui) (run-tests the-tests))
null
https://raw.githubusercontent.com/bdeket/rktsicm/225a43bc3d9953f9dbbdbfb2fa4a50028a7a41ce/rktsicm/sicm/tests/kernel/ghelper.rkt
racket
^^ this is different from ghelper-class (in in line with scmutils): rest args are not checked in practice it seems the #:rest is only ever used for the top tree (which doesn't have a pred?)
#lang racket/base (require (for-syntax racket/base) rackunit "../../kernel/cstm/ghelper.rkt") (define (any? _) #t) (define (nvr? _) #f) (define-syntax (test-it1 stx) (syntax-case stx () [(_ make-generic-operator) #'(test-case "foo" (define (foo-default x y z) 'foo-default) (define foo (make-generic-operator 3 'foo foo-default)) (check-equal? (get-operator-record foo) (operator-record 'foo 3 (tree '() #t foo-default))) (check-equal? (procedure-arity foo) 3) (check-exn #px"argument arity intersecting with operator arity" (λ () (assign-operation foo (λ (a b) 'a) any? any?))) (check-exn #px"argument arity intersecting with operator arity" (λ () (assign-operation foo (λ (a b c) 'a) any? any?))) (check-exn #px"argument arity intersecting with handler arity" (λ () (assign-operation foo (λ (a b) 'a) any? any? any?))) (check-exn #px"handler is within operator arity" (λ () (assign-operation foo (λ (a [b 1]) 'a) any? #:rest any?))) (check-equal? (get-operator-record foo) (operator-record 'foo 3 (tree '() #t foo-default))) (define (foo-handler1 a b c) 1) (define (a? m) (eq? m 'a))(define (b? m) (eq? m 'b))(define (c? m) (eq? m 'c)) (assign-operation foo foo-handler1 a? b? #:rest #t) (check-equal? (get-operator-record foo) (operator-record 'foo 3 (tree (list (cons a? (tree (list (cons b? (tree '() #t foo-handler1))) #f #f))) #t foo-default))) (define (foo-handler2 a b c) 2) (assign-operation foo foo-handler2 a? c? #:rest #t) (check-equal? (get-operator-record foo) (operator-record 'foo 3 (tree (list (cons a? (tree (list (cons c? (tree '() #t foo-handler2)) (cons b? (tree '() #t foo-handler1))) #f #f))) #t foo-default))) (define (foo-handler3 a b c) 3) (assign-operation foo foo-handler3 b? c? #:rest #t) (check-equal? (get-operator-record foo) (operator-record 'foo 3 (tree (list (cons b? (tree (list (cons c? (tree '() #t foo-handler3))) #f #f)) (cons a? (tree (list (cons c? (tree '() #t foo-handler2)) (cons b? (tree '() #t foo-handler1))) #f #f))) #t foo-default))) (define (foo-handler4 a b c) 4) (assign-operation foo foo-handler4 b? #:rest #t) (check-equal? (get-operator-record foo) (operator-record 'foo 3 (tree (list (cons b? (tree (list (cons c? (tree '() #t foo-handler3))) #t foo-handler4)) (cons a? (tree (list (cons c? (tree '() #t foo-handler2)) (cons b? (tree '() #t foo-handler1))) #f #f))) #t foo-default))) (define (foo-handler5 a b c) 5) (assign-operation foo foo-handler5 b? #:rest #t) (check-equal? (get-operator-record foo) (operator-record 'foo 3 (tree (list (cons b? (tree (list (cons c? (tree '() #t foo-handler3))) #t foo-handler5)) (cons a? (tree (list (cons c? (tree '() #t foo-handler2)) (cons b? (tree '() #t foo-handler1))) #f #f))) #t foo-default))) (check-equal? (foo 'a 'b 'b) 1) (check-equal? (foo 'a 'c 'c) 2) (check-equal? (foo 'b 'c 'c) 3) (check-equal? (foo 'b 'b 'b) 5) (check-equal? (foo 'c 'c 'c) 'foo-default) (check-equal? (foo 'a 'a 'c) 'foo-default))])) (define-syntax (test-it2 stx) (syntax-case stx () [(_ make-generic-operator) #'(test-case "bar" (define bar (make-generic-operator 1 'bar)) (check-equal? (procedure-arity bar) 1) (assign-operation bar (λ (x) x)) (check-equal? (procedure-arity (make-generic-operator (arity-at-least 2))) (arity-at-least 2)) (check-equal? (procedure-arity (make-generic-operator (list 0 (arity-at-least 2)))) (list 0 (arity-at-least 2))) (check-equal? (procedure-arity (make-generic-operator (list 1 2 (arity-at-least 2) 3))) (arity-at-least 1)) (check-equal? (procedure-arity (make-generic-operator (list 5 4 3))) '(3 4 5)))])) (define the-tests (test-suite "kernel/ghelper-class" (let () (local-require "../../kernel/ghelper-class.rkt") (test-it1 make-generic-operator) (test-it2 make-generic-operator)) (let () (local-require "../../kernel/ghelper-pro.rkt") (test-it1 make-generic-operator) (test-it2 make-generic-operator) (test-case "pro-special" (define foo (make-generic-operator 2 'foo)) (check-equal? (procedure-arity foo) 2) (assign-operation foo (λ (a b) (list a b)) (λ (x) (eq? x 'a)) #:rest #t) (check-equal? (foo 'a 'whatever) '(a whatever)) )) )) (module+ test (require rackunit/text-ui) (run-tests the-tests))
7bd80d40d09c10f35149aa4fcf7d9ff27b136e1eb7e70521fbe17a1042890f06
LeventErkok/sbv
Deduce.hs
----------------------------------------------------------------------------- -- | Module : Documentation . SBV.Examples . Uninterpreted . Deduce Copyright : ( c ) -- License : BSD3 -- Maintainer: -- Stability : experimental -- -- Demonstrates uninterpreted sorts and how they can be used for deduction. -- This example is inspired by the discussion at <-axioms-for-deductions-in-z3>, essentially showing how to show the required deduction using SBV . ----------------------------------------------------------------------------- {-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveDataTypeable #-} # LANGUAGE StandaloneDeriving # {-# LANGUAGE TemplateHaskell #-} {-# OPTIONS_GHC -Wall -Werror #-} module Documentation.SBV.Examples.Uninterpreted.Deduce where import Data.SBV -- we will have our own "uninterpreted" functions corresponding to not / or / and , so hide their Prelude counterparts . import Prelude hiding (not, or, and) ----------------------------------------------------------------------------- -- * Representing uninterpreted booleans ----------------------------------------------------------------------------- -- | The uninterpreted sort 'B', corresponding to the carrier. data B -- | Make this sort uninterpreted. This splice will automatically introduce -- the type 'SB' into the environment, as a synonym for 'SBV' 'B'. mkUninterpretedSort ''B ----------------------------------------------------------------------------- * Uninterpreted connectives over ' B ' ----------------------------------------------------------------------------- | Uninterpreted logical connective ' and ' and :: SB -> SB -> SB and = uninterpret "AND" | Uninterpreted logical connective ' or ' or :: SB -> SB -> SB or = uninterpret "OR" | Uninterpreted logical connective ' not ' not :: SB -> SB not = uninterpret "NOT" ----------------------------------------------------------------------------- -- * Demonstrated deduction ----------------------------------------------------------------------------- -- | Proves the equivalence @NOT (p OR (q AND r)) == (NOT p AND NOT q) OR (NOT p AND NOT r)@, -- following from the axioms we have specified above. We have: -- -- >>> test Q.E.D. test :: IO ThmResult test = prove $ do addAxiom "OR distributes over AND" $ \p q r -> (p `or` q) `and` (p `or` r) .== p `or` (q `and` r) addAxiom "de Morgan" $ \p q -> not (p `or` q) .== not p `and` not q addAxiom "double negation" $ \p -> not (not p) .== p p <- free "p" q <- free "q" r <- free "r" return $ not (p `or` (q `and` r)) .== (not p `and` not q) `or` (not p `and` not r)
null
https://raw.githubusercontent.com/LeventErkok/sbv/be4d7260187067a71ef8af18006e74698e2a565b/Documentation/SBV/Examples/Uninterpreted/Deduce.hs
haskell
--------------------------------------------------------------------------- | License : BSD3 Maintainer: Stability : experimental Demonstrates uninterpreted sorts and how they can be used for deduction. This example is inspired by the discussion at <-axioms-for-deductions-in-z3>, --------------------------------------------------------------------------- # LANGUAGE DeriveAnyClass # # LANGUAGE DeriveDataTypeable # # LANGUAGE TemplateHaskell # # OPTIONS_GHC -Wall -Werror # we will have our own "uninterpreted" functions corresponding --------------------------------------------------------------------------- * Representing uninterpreted booleans --------------------------------------------------------------------------- | The uninterpreted sort 'B', corresponding to the carrier. | Make this sort uninterpreted. This splice will automatically introduce the type 'SB' into the environment, as a synonym for 'SBV' 'B'. --------------------------------------------------------------------------- --------------------------------------------------------------------------- --------------------------------------------------------------------------- * Demonstrated deduction --------------------------------------------------------------------------- | Proves the equivalence @NOT (p OR (q AND r)) == (NOT p AND NOT q) OR (NOT p AND NOT r)@, following from the axioms we have specified above. We have: >>> test
Module : Documentation . SBV.Examples . Uninterpreted . Deduce Copyright : ( c ) essentially showing how to show the required deduction using SBV . # LANGUAGE StandaloneDeriving # module Documentation.SBV.Examples.Uninterpreted.Deduce where import Data.SBV to not / or / and , so hide their Prelude counterparts . import Prelude hiding (not, or, and) data B mkUninterpretedSort ''B * Uninterpreted connectives over ' B ' | Uninterpreted logical connective ' and ' and :: SB -> SB -> SB and = uninterpret "AND" | Uninterpreted logical connective ' or ' or :: SB -> SB -> SB or = uninterpret "OR" | Uninterpreted logical connective ' not ' not :: SB -> SB not = uninterpret "NOT" Q.E.D. test :: IO ThmResult test = prove $ do addAxiom "OR distributes over AND" $ \p q r -> (p `or` q) `and` (p `or` r) .== p `or` (q `and` r) addAxiom "de Morgan" $ \p q -> not (p `or` q) .== not p `and` not q addAxiom "double negation" $ \p -> not (not p) .== p p <- free "p" q <- free "q" r <- free "r" return $ not (p `or` (q `and` r)) .== (not p `and` not q) `or` (not p `and` not r)
67904de57e48c4bba880cfa9bd6862a2fa5f699b19916dbffbd833841a8be95b
haskell-gi/haskell-gi
DBusServersInfo.hs
{-# LANGUAGE OverloadedStrings #-} -- | Definitions of the D-Bus method servers to be installed by the -- browser and the extension. module DBusServersInfo ( extensionServerInfo , browserServerInfo ) where import DBusHelpers (DBusServerInfo(..)) -- | Definition of the method server installed by the extension. extensionServerInfo :: DBusServerInfo extensionServerInfo = DBusServerInfo { serverBusName = "haskellGI.test.simpleExtension", serverXMLInfo = xml, serverInterfaceName = "test.simpleExtension", serverObjectPath = "/test/simpleExtension" } where xml = "<node>" <> " <interface name='test.simpleExtension'>" <> " <method name='highlightLinks'>" <> " <arg type='u' name='nlinks' direction='out'/>" <> " </method>" <> " </interface>" <> "</node>" -- | Definition of the D-Bus server to be installed by the browser. browserServerInfo :: DBusServerInfo browserServerInfo = DBusServerInfo { serverBusName = "haskellGI.test.simpleBrowser", serverXMLInfo = xml, serverInterfaceName = "test.simpleBrowser", serverObjectPath = "/test/simpleBrowser" } where xml = "<node>" <> " <interface name='test.simpleBrowser'>" <> " <method name='extensionActivated'>" <> " </method>" <> " </interface>" <> "</node>"
null
https://raw.githubusercontent.com/haskell-gi/haskell-gi/bff8f3b92bf2594ea3d6745c346a8de594fc3709/examples/WebKit/DBusServersInfo.hs
haskell
# LANGUAGE OverloadedStrings # | Definitions of the D-Bus method servers to be installed by the browser and the extension. | Definition of the method server installed by the extension. | Definition of the D-Bus server to be installed by the browser.
module DBusServersInfo ( extensionServerInfo , browserServerInfo ) where import DBusHelpers (DBusServerInfo(..)) extensionServerInfo :: DBusServerInfo extensionServerInfo = DBusServerInfo { serverBusName = "haskellGI.test.simpleExtension", serverXMLInfo = xml, serverInterfaceName = "test.simpleExtension", serverObjectPath = "/test/simpleExtension" } where xml = "<node>" <> " <interface name='test.simpleExtension'>" <> " <method name='highlightLinks'>" <> " <arg type='u' name='nlinks' direction='out'/>" <> " </method>" <> " </interface>" <> "</node>" browserServerInfo :: DBusServerInfo browserServerInfo = DBusServerInfo { serverBusName = "haskellGI.test.simpleBrowser", serverXMLInfo = xml, serverInterfaceName = "test.simpleBrowser", serverObjectPath = "/test/simpleBrowser" } where xml = "<node>" <> " <interface name='test.simpleBrowser'>" <> " <method name='extensionActivated'>" <> " </method>" <> " </interface>" <> "</node>"
e3ac438bb050422340d07c23bb9c3843bb2d0946d247751dfbf511f081e7e7da
Tyruiop/syncretism
db.clj
(ns syncretism.crawler.db (:require [clojure.string :as str] [next.jdbc :as jdbc] [next.jdbc.prepare :as jdbp] [next.jdbc.types :as jdbt])) (def db (-> "resources/db.edn" slurp read-string)) (def fundamentals-table-def "create table if not exists fundamentals ( symbol VARCHAR(10) primary key not null, data JSON not null ) ENGINE=Aria;") (defn insert-or-update-fundamentals [symb data] (jdbc/execute! db [(str "INSERT INTO fundamentals VALUES (" (pr-str symb) ", " (pr-str data) ") ON DUPLICATE KEY UPDATE data=" (pr-str data))])) (def live-quote-table-def "create table if not exists live_quote ( symbol VARCHAR(10) primary key not null, data JSON not null ) ENGINE=Aria;") (defn insert-or-update-live-quote [symb data] (jdbc/execute! db [(str "INSERT INTO live_quote VALUES (" (pr-str symb) ", " (pr-str data) ") ON DUPLICATE KEY UPDATE data=" (pr-str data))])) (def live-table-def "create table if not exists live ( contractSymbol VARCHAR(40) primary key not null, symbol VARCHAR(10) not null, lastCrawl BIGINT not null, optType CHAR(1) not null, strike FLOAT not null, expiration BIGINT not null, inTheMoney BOOLEAN, lastPrice FLOAT not null, pChange FLOAT not null, volume INT, openInterest INT, impliedVolatility FLOAT not null, regularMarketPrice FLOAT not null, regularMarketDayHigh FLOAT not null, regularMarketDayLow FLOAT not null, priceToBook FLOAT, premium FLOAT, ask FLOAT, bid FLOAT, lastTradeDate BIGINT, breakeven FLOAT, quoteType VARCHAR(15), yield FLOAT, monthlyYield FLOAT, delta FLOAT, gamma FLOAT, theta FLOAT, vega FLOAT, rho FLOAT, vol20d FLOAT, vol100d FLOAT, oi20d FLOAT, oi100d FLOAT, iv20d FLOAT, iv100d FLOAT, pr20d FLOAT, pr100d FLOAT, bid20d FLOAT, bid100d FLOAT, delta20d FLOAT, delta100d FLOAT, gamma20d FLOAT, gamma100d FLOAT, theta20d FLOAT, theta100d FLOAT, vega20d FLOAT, vega100d FLOAT, rho20d FLOAT, rho100d FLOAT ) ENGINE=Aria;") ;; (jdbc/execute! db ["ALTER TABLE live ADD COLUMN (breakeven FLOAT)"]) ;; (jdbc/execute! db ["ALTER TABLE live ADD COLUMN (delta FLOAT)"]) ;; (jdbc/execute! db ["ALTER TABLE live ADD COLUMN (gamma FLOAT)"]) ;; (jdbc/execute! db ["ALTER TABLE live ADD COLUMN (rho FLOAT)"]) ;; (jdbc/execute! db ["ALTER TABLE live ADD COLUMN (premium FLOAT)"]) (comment (jdbc/execute! db ["ALTER TABLE live ADD COLUMN vol20d FLOAT, ADD COLUMN vol100d FLOAT, ADD COLUMN oi20d FLOAT, ADD COLUMN oi100d FLOAT, ADD COLUMN iv20d FLOAT, ADD COLUMN iv100d FLOAT, ADD COLUMN pr20d FLOAT, ADD COLUMN pr100d FLOAT, ADD COLUMN bid20d FLOAT, ADD COLUMN bid100d FLOAT, ADD COLUMN delta20d FLOAT, ADD COLUMN delta100d FLOAT, ADD COLUMN gamma20d FLOAT, ADD COLUMN gamma100d FLOAT, ADD COLUMN theta20d FLOAT, ADD COLUMN theta100d FLOAT, ADD COLUMN vega20d FLOAT, ADD COLUMN vega100d FLOAT, ADD COLUMN rho20d FLOAT, ADD COLUMN rho100d FLOAT"])) (def live-columns [[[:opt :contractSymbol] "contractSymbol"] [[:quote :symbol] "symbol"] [[:req-time] "lastCrawl"] [[:opt :opt-type] "optType"] [[:opt :strike] "strike"] [[:opt :expiration] "expiration"] [[:opt :inTheMoney] "inTheMoney"] [[:opt :lastPrice] "lastPrice"] [[:opt :change] "pChange"] [[:opt :volume] "volume"] [[:opt :openInterest] "openInterest"] [[:opt :impliedVolatility] "impliedVolatility"] [[:quote :regularMarketPrice] "regularMarketPrice"] [[:quote :regularMarketDayHigh] "regularMarketDayHigh"] [[:quote :regularMarketDayLow] "regularMarketDayLow"] [[:quote :priceToBook] "priceToBook"] [[:opt :premium] "premium"] [[:opt :ask] "ask"] [[:opt :bid] "bid"] [[:opt :lastTradeDate] "lastTradeDate"] [[:opt :quote-type] "quoteType"] [[:opt :breakeven] "breakeven"] [[:opt :delta] "delta"] [[:opt :gamma] "gamma"] [[:opt :theta] "theta"] [[:opt :vega] "vega"] [[:opt :rho] "rho"]]) (def live-columns-nb (count live-columns)) (defn clean-live-data [data] (let [cleaned-cols (map (fn [[path _]] (let [d (get-in data path)] d)) live-columns)] (into [] (concat cleaned-cols (rest cleaned-cols))))) (defn insert-or-update-live [data] (let [cleaned-data (map clean-live-data data)] (with-open [con (jdbc/get-connection db) ps (jdbc/prepare con [(str "INSERT INTO live (" (str/join ", " (map last live-columns)) ") VALUES (" (str/join ", " (repeat live-columns-nb "?")) ")" " ON DUPLICATE KEY UPDATE " (str/join ", " (map #(str (last %) "=?") (rest live-columns))))])] (jdbp/execute-batch! ps cleaned-data)))) (defn init-db [] (try (jdbc/execute! db [fundamentals-table-def]) (println "Created fundamentals table") (catch Exception e (println e))) (try (jdbc/execute! db [live-quote-table-def]) (println "Created live quote table") (catch Exception e (println e))) (try (jdbc/execute! db [live-table-def]) (println "Created live (options) table") (catch Exception e (println e))))
null
https://raw.githubusercontent.com/Tyruiop/syncretism/841b5c1d74511684f027c9d14eb18a761d8c0276/syncretism-crawler/src/syncretism/crawler/db.clj
clojure
") ") ") (jdbc/execute! db ["ALTER TABLE live ADD COLUMN (breakeven FLOAT)"]) (jdbc/execute! db ["ALTER TABLE live ADD COLUMN (delta FLOAT)"]) (jdbc/execute! db ["ALTER TABLE live ADD COLUMN (gamma FLOAT)"]) (jdbc/execute! db ["ALTER TABLE live ADD COLUMN (rho FLOAT)"]) (jdbc/execute! db ["ALTER TABLE live ADD COLUMN (premium FLOAT)"])
(ns syncretism.crawler.db (:require [clojure.string :as str] [next.jdbc :as jdbc] [next.jdbc.prepare :as jdbp] [next.jdbc.types :as jdbt])) (def db (-> "resources/db.edn" slurp read-string)) (def fundamentals-table-def "create table if not exists fundamentals ( symbol VARCHAR(10) primary key not null, data JSON not null (defn insert-or-update-fundamentals [symb data] (jdbc/execute! db [(str "INSERT INTO fundamentals VALUES (" (pr-str symb) ", " (pr-str data) ") ON DUPLICATE KEY UPDATE data=" (pr-str data))])) (def live-quote-table-def "create table if not exists live_quote ( symbol VARCHAR(10) primary key not null, data JSON not null (defn insert-or-update-live-quote [symb data] (jdbc/execute! db [(str "INSERT INTO live_quote VALUES (" (pr-str symb) ", " (pr-str data) ") ON DUPLICATE KEY UPDATE data=" (pr-str data))])) (def live-table-def "create table if not exists live ( contractSymbol VARCHAR(40) primary key not null, symbol VARCHAR(10) not null, lastCrawl BIGINT not null, optType CHAR(1) not null, strike FLOAT not null, expiration BIGINT not null, inTheMoney BOOLEAN, lastPrice FLOAT not null, pChange FLOAT not null, volume INT, openInterest INT, impliedVolatility FLOAT not null, regularMarketPrice FLOAT not null, regularMarketDayHigh FLOAT not null, regularMarketDayLow FLOAT not null, priceToBook FLOAT, premium FLOAT, ask FLOAT, bid FLOAT, lastTradeDate BIGINT, breakeven FLOAT, quoteType VARCHAR(15), yield FLOAT, monthlyYield FLOAT, delta FLOAT, gamma FLOAT, theta FLOAT, vega FLOAT, rho FLOAT, vol20d FLOAT, vol100d FLOAT, oi20d FLOAT, oi100d FLOAT, iv20d FLOAT, iv100d FLOAT, pr20d FLOAT, pr100d FLOAT, bid20d FLOAT, bid100d FLOAT, delta20d FLOAT, delta100d FLOAT, gamma20d FLOAT, gamma100d FLOAT, theta20d FLOAT, theta100d FLOAT, vega20d FLOAT, vega100d FLOAT, rho20d FLOAT, rho100d FLOAT (comment (jdbc/execute! db ["ALTER TABLE live ADD COLUMN vol20d FLOAT, ADD COLUMN vol100d FLOAT, ADD COLUMN oi20d FLOAT, ADD COLUMN oi100d FLOAT, ADD COLUMN iv20d FLOAT, ADD COLUMN iv100d FLOAT, ADD COLUMN pr20d FLOAT, ADD COLUMN pr100d FLOAT, ADD COLUMN bid20d FLOAT, ADD COLUMN bid100d FLOAT, ADD COLUMN delta20d FLOAT, ADD COLUMN delta100d FLOAT, ADD COLUMN gamma20d FLOAT, ADD COLUMN gamma100d FLOAT, ADD COLUMN theta20d FLOAT, ADD COLUMN theta100d FLOAT, ADD COLUMN vega20d FLOAT, ADD COLUMN vega100d FLOAT, ADD COLUMN rho20d FLOAT, ADD COLUMN rho100d FLOAT"])) (def live-columns [[[:opt :contractSymbol] "contractSymbol"] [[:quote :symbol] "symbol"] [[:req-time] "lastCrawl"] [[:opt :opt-type] "optType"] [[:opt :strike] "strike"] [[:opt :expiration] "expiration"] [[:opt :inTheMoney] "inTheMoney"] [[:opt :lastPrice] "lastPrice"] [[:opt :change] "pChange"] [[:opt :volume] "volume"] [[:opt :openInterest] "openInterest"] [[:opt :impliedVolatility] "impliedVolatility"] [[:quote :regularMarketPrice] "regularMarketPrice"] [[:quote :regularMarketDayHigh] "regularMarketDayHigh"] [[:quote :regularMarketDayLow] "regularMarketDayLow"] [[:quote :priceToBook] "priceToBook"] [[:opt :premium] "premium"] [[:opt :ask] "ask"] [[:opt :bid] "bid"] [[:opt :lastTradeDate] "lastTradeDate"] [[:opt :quote-type] "quoteType"] [[:opt :breakeven] "breakeven"] [[:opt :delta] "delta"] [[:opt :gamma] "gamma"] [[:opt :theta] "theta"] [[:opt :vega] "vega"] [[:opt :rho] "rho"]]) (def live-columns-nb (count live-columns)) (defn clean-live-data [data] (let [cleaned-cols (map (fn [[path _]] (let [d (get-in data path)] d)) live-columns)] (into [] (concat cleaned-cols (rest cleaned-cols))))) (defn insert-or-update-live [data] (let [cleaned-data (map clean-live-data data)] (with-open [con (jdbc/get-connection db) ps (jdbc/prepare con [(str "INSERT INTO live (" (str/join ", " (map last live-columns)) ") VALUES (" (str/join ", " (repeat live-columns-nb "?")) ")" " ON DUPLICATE KEY UPDATE " (str/join ", " (map #(str (last %) "=?") (rest live-columns))))])] (jdbp/execute-batch! ps cleaned-data)))) (defn init-db [] (try (jdbc/execute! db [fundamentals-table-def]) (println "Created fundamentals table") (catch Exception e (println e))) (try (jdbc/execute! db [live-quote-table-def]) (println "Created live quote table") (catch Exception e (println e))) (try (jdbc/execute! db [live-table-def]) (println "Created live (options) table") (catch Exception e (println e))))
dffe0a1c5f6531c4501c07e1d8d0ec69e6dc7509b70c10c28d942eb3886a7c2a
Chase-C/Flocking-Simulation
Octree.hs
module Octree where --------------------------------------------------------- import Control.Applicative import Data.Bits import qualified Data.List as L import Linear import Boid --------------------------------------------------------- data Octree = Node { center :: V3 Float , len :: Float , count :: Int , ftr, ftl, fbr, fbl, btr, btl, bbr, bbl :: Octree } -- front, back, top, bottom, right, left | Leaf { center :: V3 Float , len :: Float , count :: Int , objects :: [Boid] } deriving (Show) data Octant = FTR | FTL | FBR | FBL | BTR | BTL | BBR | BBL deriving (Show, Eq, Ord, Enum) --------------------------------------------------------- emptyOctree :: V3 Float -> Float -> Octree emptyOctree c l = Leaf c l 0 [] fromList :: [Boid] -> V3 Float -> Float -> Octree fromList boids c l = foldl insert (emptyOctree c l) boids # INLINE vSqLen # vSqLen :: (Floating a, Eq a) => V3 a -> a vSqLen (V3 x y z) = (x * x) + (y * y) + (z * z) # INLINE vDist # vDist :: (Floating a, Eq a) => V3 a -> V3 a -> a vDist (V3 x1 y1 z1) (V3 x2 y2 z2) = sqrt $ (x * x) + (y * y) + (z * z) where x = x2 - x1 y = y2 - y1 z = z2 - z1 --------------------------------------------------------- octreeMap :: (Boid -> Boid) -> Octree -> Octree octreeMap func tree = insertList (emptyOctree (center tree) (len tree)) $ map func boids where boids = flattenTree tree octreeMapM_ :: (Boid -> IO a) -> Octree -> IO () octreeMapM_ func (Leaf _ _ _ objs) = mapM_ func objs octreeMapM_ func (Node _ _ _ a b c d e f g h) = do octreeMapM_ func a octreeMapM_ func b octreeMapM_ func c octreeMapM_ func d octreeMapM_ func e octreeMapM_ func f octreeMapM_ func g octreeMapM_ func h return () octreeFold :: (a -> Boid -> a) -> a -> Octree -> a octreeFold func i (Node _ _ _ a b c d e f g h) = octreeFold func p h where j = octreeFold func i a k = octreeFold func j b l = octreeFold func k c m = octreeFold func l d n = octreeFold func m e o = octreeFold func n f p = octreeFold func o g octreeFold func i (Leaf _ _ _ objs) = foldl func i objs --------------------------------------------------------- prettyPrint :: Octree -> String prettyPrint (Node cen l cnt a b c d e f g h) = "Node {\n\tcenter: " ++ (show cen) ++ "\n\tlength: " ++ (show l) ++ "\n\tcount: " ++ (show cnt) ++ "\n" ++ (concat $ L.intersperse "\n" $ map prettyPrint [a, b, c, d, e, f, g, h]) ++ "\n}" prettyPrint (Leaf cen l cnt objs) = "Leaf {\n\tcenter: " ++ (show cen) ++ "\n\tlength: " ++ (show l) ++ "\n\tcount: " ++ (show cnt) ++ "\n" ++ (concat $ L.intersperse "\n\t" $ map show objs) ++ "\n}" --------------------------------------------------------- getOctant :: V3 Float -> V3 Float -> Octant getOctant (V3 cx cy cz) (V3 px py pz) = toEnum $ (fromEnum right) + (2 * fromEnum top) + (4 * fromEnum front) where front = pz < cz top = py < cy right = px < cx getSubtree :: Octree -> Octant -> Octree getSubtree (Node _ _ _ a b c d e f g h) octant = case octant of FTR -> a FTL -> b FBR -> c FBL -> d BTR -> e BTL -> f BBR -> g BBL -> h getSubtree tree _ = tree replaceSubtree :: Octree -> Octant -> Octree -> Octree replaceSubtree t@(Node cen l cnt a b c d e f g h) octant subtree = case octant of FTR -> Node cen l nCnt subtree b c d e f g h FTL -> Node cen l nCnt a subtree c d e f g h FBR -> Node cen l nCnt a b subtree d e f g h FBL -> Node cen l nCnt a b c subtree e f g h BTR -> Node cen l nCnt a b c d subtree f g h BTL -> Node cen l nCnt a b c d e subtree g h BBR -> Node cen l nCnt a b c d e f subtree h BBL -> Node cen l nCnt a b c d e f g subtree where nCnt = cnt - (count $ getSubtree t octant) + (count subtree) replaceSubtree tree _ _ = tree flattenTree :: Octree -> [Boid] flattenTree = octreeFold (flip (:)) [] insert :: Octree -> Boid -> Octree insert (Leaf cen l cnt xs) obj = Leaf cen l (cnt + 1) $ obj:xs insert node obj = replaceSubtree node octant $ insert (getSubtree node octant) obj where octant = getOctant (center node) (bPos obj) insertList :: Octree -> [Boid] -> Octree insertList = foldl insert splitTree :: Octree -> Octree splitTree (Leaf c@(V3 cx cy cz) l cnt objs) = foldl insert tree objs where tree = Node { center = c , len = l , count = cnt , ftr = et rx ty fz, ftl = et lx ty fz , fbr = et rx by fz, fbl = et lx by fz , btr = et rx ty bz, btl = et lx ty bz , bbr = et rx by bz, bbl = et lx by bz } et x y z = emptyOctree (V3 x y z) hl hl = l / 2 rx = cx + hl lx = cx - hl ty = cy + hl by = cy - hl fz = cz + hl bz = cz - hl splitTree tree = tree splitWith :: Octree -> (Octree -> Bool) -> Octree splitWith (Node cen len cnt i j k l m n o p) f = Node cen len cnt (s i) (s j) (s k) (s l) (s m) (s n) (s o) (s p) where s tree = splitWith tree f splitWith tree func | func tree = splitWith (splitTree tree) func | otherwise = tree getNearObjects :: Octree -> V3 Float -> [Boid] getNearObjects (Leaf _ _ _ objs) _ = objs getNearObjects node pos = getNearObjects subtree pos where subtree = getSubtree node $ getOctant (center node) pos xOppOctant, yOppOctant, zOppOctant :: Octant -> Octant xOppOctant octant = toEnum $ xor (fromEnum octant) 1 yOppOctant octant = toEnum $ xor (fromEnum octant) 2 zOppOctant octant = toEnum $ xor (fromEnum octant) 4 getRadiusObjects :: Octree -> V3 Float -> Float -> [Boid] getRadiusObjects (Leaf _ l _ objs) pos r | r > l = objs | otherwise = filter (\obj -> (r * r) > (vSqLen $ pos - bPos obj)) objs getRadiusObjects node pos r = concat . (map (\t -> getRadiusObjects t pos r)) $ intersectingSubtrees node pos r -- Return True iff the sphere around the given position exceeds the bounds of the given Octree . # INLINE inBounds # inBounds :: Octree -> V3 Float -> Float -> Bool inBounds tree pos rad = lX && lY && lZ && uX && uY && uZ where V3 x y z = pos - center tree hl = len tree / 2 lX = -hl < x - rad lY = -hl < y - rad lZ = -hl < z - rad uX = hl > x + rad uY = hl > y + rad uZ = hl > z + rad -- Return a list of the subtrees intersecting with the given bounding sphere Note : The last subtree in the list is always the the one containing the point # INLINE intersectingSubtrees # intersectingSubtrees :: Octree -> V3 Float -> Float -> [Octree] intersectingSubtrees l@(Leaf {}) _ _ = return l intersectingSubtrees node p@(V3 px py pz) rad = map (getSubtree node) octants where octant = getOctant c p octants = if rad > abs (pz - cz) then foldr (\o zs -> (zOppOctant o):o:zs) [] tmpY else tmpY tmpY = if rad > abs (py - cy) then foldr (\o ys -> (yOppOctant o):o:ys) [] tmpX else tmpX tmpX = if rad > abs (px - cx) then (xOppOctant octant):[octant] else [octant] c@(V3 cx cy cz) = center node kNearestNeighbors :: Octree -> V3 Float -> Int -> Float -> [(Boid, Float)] kNearestNeighbors (Leaf _ _ _ objs) pos k maxR = take k $ L.sortBy sortByDist $ filter filtFunc $ map (getObjDist pos) objs where filtFunc (_, rad) = rad < maxR kNearestNeighbors node pos k maxR | inBounds subtree pos topR && length nearest >= k = nearest | otherwise = take k $ foldl combineNeighbors nearest $ getOtherNeighbors node pos k topR where subtree = getSubtree node (getOctant (center node) pos) nearest = kNearestNeighbors subtree pos k maxR topR = if length nearest >= k then snd $ last nearest else maxR # INLINE getOtherNeighbors # getOtherNeighbors :: Octree -> V3 Float -> Int -> Float -> [[(Boid, Float)]] getOtherNeighbors tree pos k rad = map (\t -> kNearestNeighbors t pos k rad) $ init $ intersectingSubtrees tree pos rad # INLINE combineNeighbors # combineNeighbors :: [(Boid, Float)] -> [(Boid, Float)] -> [(Boid, Float)] combineNeighbors xs [] = xs combineNeighbors [] ys = ys combineNeighbors (x@(_, rx):xs) (y@(_, ry):ys) = if rx > ry then y : combineNeighbors (x:xs) ys else x : combineNeighbors xs (y:ys) # INLINE getObjDist # getObjDist :: V3 Float -> Boid -> (Boid, Float) getObjDist pos obj = (obj, vDist (bPos obj) pos) # INLINE sortByDist # sortByDist :: (Boid, Float) -> (Boid, Float) -> Ordering sortByDist (_, r1) (_, r2) = r1 `compare` r2
null
https://raw.githubusercontent.com/Chase-C/Flocking-Simulation/897ee7adbe2cd7ae27faf37d65c41e6c2d189b0c/src/Octree.hs
haskell
------------------------------------------------------- ------------------------------------------------------- front, back, top, bottom, right, left ------------------------------------------------------- ------------------------------------------------------- ------------------------------------------------------- ------------------------------------------------------- Return True iff the sphere around the given position exceeds the bounds of Return a list of the subtrees intersecting with the given bounding sphere
module Octree where import Control.Applicative import Data.Bits import qualified Data.List as L import Linear import Boid data Octree = Node { center :: V3 Float , len :: Float , count :: Int , ftr, ftl, fbr, fbl, btr, btl, bbr, bbl :: Octree | Leaf { center :: V3 Float , len :: Float , count :: Int , objects :: [Boid] } deriving (Show) data Octant = FTR | FTL | FBR | FBL | BTR | BTL | BBR | BBL deriving (Show, Eq, Ord, Enum) emptyOctree :: V3 Float -> Float -> Octree emptyOctree c l = Leaf c l 0 [] fromList :: [Boid] -> V3 Float -> Float -> Octree fromList boids c l = foldl insert (emptyOctree c l) boids # INLINE vSqLen # vSqLen :: (Floating a, Eq a) => V3 a -> a vSqLen (V3 x y z) = (x * x) + (y * y) + (z * z) # INLINE vDist # vDist :: (Floating a, Eq a) => V3 a -> V3 a -> a vDist (V3 x1 y1 z1) (V3 x2 y2 z2) = sqrt $ (x * x) + (y * y) + (z * z) where x = x2 - x1 y = y2 - y1 z = z2 - z1 octreeMap :: (Boid -> Boid) -> Octree -> Octree octreeMap func tree = insertList (emptyOctree (center tree) (len tree)) $ map func boids where boids = flattenTree tree octreeMapM_ :: (Boid -> IO a) -> Octree -> IO () octreeMapM_ func (Leaf _ _ _ objs) = mapM_ func objs octreeMapM_ func (Node _ _ _ a b c d e f g h) = do octreeMapM_ func a octreeMapM_ func b octreeMapM_ func c octreeMapM_ func d octreeMapM_ func e octreeMapM_ func f octreeMapM_ func g octreeMapM_ func h return () octreeFold :: (a -> Boid -> a) -> a -> Octree -> a octreeFold func i (Node _ _ _ a b c d e f g h) = octreeFold func p h where j = octreeFold func i a k = octreeFold func j b l = octreeFold func k c m = octreeFold func l d n = octreeFold func m e o = octreeFold func n f p = octreeFold func o g octreeFold func i (Leaf _ _ _ objs) = foldl func i objs prettyPrint :: Octree -> String prettyPrint (Node cen l cnt a b c d e f g h) = "Node {\n\tcenter: " ++ (show cen) ++ "\n\tlength: " ++ (show l) ++ "\n\tcount: " ++ (show cnt) ++ "\n" ++ (concat $ L.intersperse "\n" $ map prettyPrint [a, b, c, d, e, f, g, h]) ++ "\n}" prettyPrint (Leaf cen l cnt objs) = "Leaf {\n\tcenter: " ++ (show cen) ++ "\n\tlength: " ++ (show l) ++ "\n\tcount: " ++ (show cnt) ++ "\n" ++ (concat $ L.intersperse "\n\t" $ map show objs) ++ "\n}" getOctant :: V3 Float -> V3 Float -> Octant getOctant (V3 cx cy cz) (V3 px py pz) = toEnum $ (fromEnum right) + (2 * fromEnum top) + (4 * fromEnum front) where front = pz < cz top = py < cy right = px < cx getSubtree :: Octree -> Octant -> Octree getSubtree (Node _ _ _ a b c d e f g h) octant = case octant of FTR -> a FTL -> b FBR -> c FBL -> d BTR -> e BTL -> f BBR -> g BBL -> h getSubtree tree _ = tree replaceSubtree :: Octree -> Octant -> Octree -> Octree replaceSubtree t@(Node cen l cnt a b c d e f g h) octant subtree = case octant of FTR -> Node cen l nCnt subtree b c d e f g h FTL -> Node cen l nCnt a subtree c d e f g h FBR -> Node cen l nCnt a b subtree d e f g h FBL -> Node cen l nCnt a b c subtree e f g h BTR -> Node cen l nCnt a b c d subtree f g h BTL -> Node cen l nCnt a b c d e subtree g h BBR -> Node cen l nCnt a b c d e f subtree h BBL -> Node cen l nCnt a b c d e f g subtree where nCnt = cnt - (count $ getSubtree t octant) + (count subtree) replaceSubtree tree _ _ = tree flattenTree :: Octree -> [Boid] flattenTree = octreeFold (flip (:)) [] insert :: Octree -> Boid -> Octree insert (Leaf cen l cnt xs) obj = Leaf cen l (cnt + 1) $ obj:xs insert node obj = replaceSubtree node octant $ insert (getSubtree node octant) obj where octant = getOctant (center node) (bPos obj) insertList :: Octree -> [Boid] -> Octree insertList = foldl insert splitTree :: Octree -> Octree splitTree (Leaf c@(V3 cx cy cz) l cnt objs) = foldl insert tree objs where tree = Node { center = c , len = l , count = cnt , ftr = et rx ty fz, ftl = et lx ty fz , fbr = et rx by fz, fbl = et lx by fz , btr = et rx ty bz, btl = et lx ty bz , bbr = et rx by bz, bbl = et lx by bz } et x y z = emptyOctree (V3 x y z) hl hl = l / 2 rx = cx + hl lx = cx - hl ty = cy + hl by = cy - hl fz = cz + hl bz = cz - hl splitTree tree = tree splitWith :: Octree -> (Octree -> Bool) -> Octree splitWith (Node cen len cnt i j k l m n o p) f = Node cen len cnt (s i) (s j) (s k) (s l) (s m) (s n) (s o) (s p) where s tree = splitWith tree f splitWith tree func | func tree = splitWith (splitTree tree) func | otherwise = tree getNearObjects :: Octree -> V3 Float -> [Boid] getNearObjects (Leaf _ _ _ objs) _ = objs getNearObjects node pos = getNearObjects subtree pos where subtree = getSubtree node $ getOctant (center node) pos xOppOctant, yOppOctant, zOppOctant :: Octant -> Octant xOppOctant octant = toEnum $ xor (fromEnum octant) 1 yOppOctant octant = toEnum $ xor (fromEnum octant) 2 zOppOctant octant = toEnum $ xor (fromEnum octant) 4 getRadiusObjects :: Octree -> V3 Float -> Float -> [Boid] getRadiusObjects (Leaf _ l _ objs) pos r | r > l = objs | otherwise = filter (\obj -> (r * r) > (vSqLen $ pos - bPos obj)) objs getRadiusObjects node pos r = concat . (map (\t -> getRadiusObjects t pos r)) $ intersectingSubtrees node pos r the given Octree . # INLINE inBounds # inBounds :: Octree -> V3 Float -> Float -> Bool inBounds tree pos rad = lX && lY && lZ && uX && uY && uZ where V3 x y z = pos - center tree hl = len tree / 2 lX = -hl < x - rad lY = -hl < y - rad lZ = -hl < z - rad uX = hl > x + rad uY = hl > y + rad uZ = hl > z + rad Note : The last subtree in the list is always the the one containing the point # INLINE intersectingSubtrees # intersectingSubtrees :: Octree -> V3 Float -> Float -> [Octree] intersectingSubtrees l@(Leaf {}) _ _ = return l intersectingSubtrees node p@(V3 px py pz) rad = map (getSubtree node) octants where octant = getOctant c p octants = if rad > abs (pz - cz) then foldr (\o zs -> (zOppOctant o):o:zs) [] tmpY else tmpY tmpY = if rad > abs (py - cy) then foldr (\o ys -> (yOppOctant o):o:ys) [] tmpX else tmpX tmpX = if rad > abs (px - cx) then (xOppOctant octant):[octant] else [octant] c@(V3 cx cy cz) = center node kNearestNeighbors :: Octree -> V3 Float -> Int -> Float -> [(Boid, Float)] kNearestNeighbors (Leaf _ _ _ objs) pos k maxR = take k $ L.sortBy sortByDist $ filter filtFunc $ map (getObjDist pos) objs where filtFunc (_, rad) = rad < maxR kNearestNeighbors node pos k maxR | inBounds subtree pos topR && length nearest >= k = nearest | otherwise = take k $ foldl combineNeighbors nearest $ getOtherNeighbors node pos k topR where subtree = getSubtree node (getOctant (center node) pos) nearest = kNearestNeighbors subtree pos k maxR topR = if length nearest >= k then snd $ last nearest else maxR # INLINE getOtherNeighbors # getOtherNeighbors :: Octree -> V3 Float -> Int -> Float -> [[(Boid, Float)]] getOtherNeighbors tree pos k rad = map (\t -> kNearestNeighbors t pos k rad) $ init $ intersectingSubtrees tree pos rad # INLINE combineNeighbors # combineNeighbors :: [(Boid, Float)] -> [(Boid, Float)] -> [(Boid, Float)] combineNeighbors xs [] = xs combineNeighbors [] ys = ys combineNeighbors (x@(_, rx):xs) (y@(_, ry):ys) = if rx > ry then y : combineNeighbors (x:xs) ys else x : combineNeighbors xs (y:ys) # INLINE getObjDist # getObjDist :: V3 Float -> Boid -> (Boid, Float) getObjDist pos obj = (obj, vDist (bPos obj) pos) # INLINE sortByDist # sortByDist :: (Boid, Float) -> (Boid, Float) -> Ordering sortByDist (_, r1) (_, r2) = r1 `compare` r2
93d03708a22a51b01a228d0bf5f4b566da27a7ce5131a6a27c824facad9c7f37
bcc32/advent-of-code
main.ml
open! Core open! Async let () = Command.run P13.Main.game_command
null
https://raw.githubusercontent.com/bcc32/advent-of-code/653c0f130e2fb2f599d4e76804e02af54c9bb19f/2019/13/bin/main.ml
ocaml
open! Core open! Async let () = Command.run P13.Main.game_command
b3565c90d701d62306bd1e5ef80a47afcc12107acb2e4ac2cc605cb6b86d0ede
REPROSEC/dolev-yao-star
Spec_P256_Lemmas.ml
open Prims let rec (pow : Prims.nat -> Prims.nat -> Prims.nat) = fun a -> fun b -> if b = Prims.int_zero then Prims.int_one else a * (pow a (b - Prims.int_one)) type 'n elem = Prims.nat let (fmul : Prims.pos -> unit elem -> unit elem -> unit elem) = fun n -> fun x -> fun y -> (x * y) mod n let rec (exp : Prims.pos -> unit elem -> Prims.pos -> unit elem) = fun n -> fun a -> fun b -> if b = Prims.int_one then a else if (b mod (Prims.of_int (2))) = Prims.int_zero then exp n (fmul n a a) (b / (Prims.of_int (2))) else fmul n a (exp n (fmul n a a) (b / (Prims.of_int (2)))) let (modp_inv_prime : Prims.pos -> unit elem -> unit elem) = fun prime -> fun x -> (exp prime x (prime - (Prims.of_int (2)))) mod prime let (modp_inv2_prime : Prims.int -> Prims.nat -> unit elem) = fun x -> fun p -> modp_inv_prime p (x mod p) let (modp_inv2 : Prims.nat -> unit elem) = fun x -> modp_inv2_prime x Spec_P256_Definitions.prime256 let (modp_inv2_pow : Prims.nat -> unit elem) = fun x -> (pow x (Spec_P256_Definitions.prime256 - (Prims.of_int (2)))) mod Spec_P256_Definitions.prime256 let (min_one_prime : Prims.pos -> Prims.int -> unit elem) = fun prime -> fun x -> let p = x mod prime in exp prime p (prime - Prims.int_one)
null
https://raw.githubusercontent.com/REPROSEC/dolev-yao-star/d97a8dd4d07f2322437f186e4db6a1f4d5ee9230/concrete/hacl-star-snapshot/ml/Spec_P256_Lemmas.ml
ocaml
open Prims let rec (pow : Prims.nat -> Prims.nat -> Prims.nat) = fun a -> fun b -> if b = Prims.int_zero then Prims.int_one else a * (pow a (b - Prims.int_one)) type 'n elem = Prims.nat let (fmul : Prims.pos -> unit elem -> unit elem -> unit elem) = fun n -> fun x -> fun y -> (x * y) mod n let rec (exp : Prims.pos -> unit elem -> Prims.pos -> unit elem) = fun n -> fun a -> fun b -> if b = Prims.int_one then a else if (b mod (Prims.of_int (2))) = Prims.int_zero then exp n (fmul n a a) (b / (Prims.of_int (2))) else fmul n a (exp n (fmul n a a) (b / (Prims.of_int (2)))) let (modp_inv_prime : Prims.pos -> unit elem -> unit elem) = fun prime -> fun x -> (exp prime x (prime - (Prims.of_int (2)))) mod prime let (modp_inv2_prime : Prims.int -> Prims.nat -> unit elem) = fun x -> fun p -> modp_inv_prime p (x mod p) let (modp_inv2 : Prims.nat -> unit elem) = fun x -> modp_inv2_prime x Spec_P256_Definitions.prime256 let (modp_inv2_pow : Prims.nat -> unit elem) = fun x -> (pow x (Spec_P256_Definitions.prime256 - (Prims.of_int (2)))) mod Spec_P256_Definitions.prime256 let (min_one_prime : Prims.pos -> Prims.int -> unit elem) = fun prime -> fun x -> let p = x mod prime in exp prime p (prime - Prims.int_one)
c7b029c19aeb9d5af55894bebfb265a25ccab605688290fa6ff4ea82f981a33b
janestreet/core_extended
shared.ml
open Core the maximum read / write I managed to get off of a socket or disk was 65k let buffer_size = 10 * 65 * 1024 type ('a, 'b) reader = ?strip:bool -> ?skip_lines:int -> ?on_parse_error: [ `Raise | `Handle of string Queue.t -> exn -> [ `Continue | `Finish ] ] -> header:'a -> 'b let strip_buffer buf = let len = Buffer.length buf in let rec first_non_space n = if n >= len then None else if Char.is_whitespace (Buffer.nth buf n) then first_non_space (n + 1) else Some n in let rec last_non_space n = if n < 0 then None else if Char.is_whitespace (Buffer.nth buf n) then last_non_space (n - 1) else Some n in match first_non_space 0 with | None -> "" | Some s -> (match last_non_space (len - 1) with | None -> assert false | Some e -> Buffer.To_string.sub buf ~pos:s ~len:(e - s + 1)) ;; let make_emit_field ~strip current_row field = stage (fun () -> Queue.enqueue current_row (if strip then strip_buffer field else Buffer.contents field); Buffer.clear field) ;; let set_headers header_index headers = List.iteri headers ~f:(fun i h -> Option.iter h ~f:(fun h -> match Hashtbl.find header_index h with | None -> Hashtbl.set header_index ~key:h ~data:i | Some other_i -> failwithf "header %s duplicated at position %i and %i" h other_i i ())) ;; let make_emit_row current_row row_queue header ~lineno = let module Table = String.Table in let header_index = match (header : Header.t) with | `No | `Yes | `Require _ | `Transform _ | `Filter_map _ -> Table.create () ~size:1 | `Replace headers | `Add headers -> Table.of_alist_exn (List.mapi headers ~f:(fun i s -> s, i)) in let header_processed = ref (match header with | `No | `Add _ -> true | `Require _ | `Replace _ | `Transform _ | `Filter_map _ | `Yes -> false) in ( `on_eof (fun () -> if not !header_processed then failwith "Header line was not found") , fun () -> if not !header_processed then ( header_processed := true; match header with | `No | `Add _ -> assert false | `Require at_least -> let headers = Queue.to_list current_row in List.iter at_least ~f:(fun must_exist -> match List.findi headers ~f:(fun _ h -> String.equal h must_exist) with | None -> failwithf "The required header '%s' was not found in '%s' (lineno=%d)" must_exist (String.concat ~sep:"," headers) !lineno () | Some (i, _) -> Hashtbl.set header_index ~key:must_exist ~data:i) | `Replace _new_headers -> () (* already set above *) | `Transform f -> Queue.to_list current_row |> f |> List.map ~f:Option.some |> set_headers header_index | `Filter_map f -> Queue.to_list current_row |> f |> set_headers header_index | `Yes -> Queue.to_list current_row |> List.map ~f:Option.some |> set_headers header_index) else Queue.enqueue row_queue (Row.create header_index (Queue.to_array current_row)); lineno := !lineno + 1; Queue.clear current_row ) ;;
null
https://raw.githubusercontent.com/janestreet/core_extended/5eb206493891be4610ed188c0ac44006a5b72061/delimited_kernel/src/shared.ml
ocaml
already set above
open Core the maximum read / write I managed to get off of a socket or disk was 65k let buffer_size = 10 * 65 * 1024 type ('a, 'b) reader = ?strip:bool -> ?skip_lines:int -> ?on_parse_error: [ `Raise | `Handle of string Queue.t -> exn -> [ `Continue | `Finish ] ] -> header:'a -> 'b let strip_buffer buf = let len = Buffer.length buf in let rec first_non_space n = if n >= len then None else if Char.is_whitespace (Buffer.nth buf n) then first_non_space (n + 1) else Some n in let rec last_non_space n = if n < 0 then None else if Char.is_whitespace (Buffer.nth buf n) then last_non_space (n - 1) else Some n in match first_non_space 0 with | None -> "" | Some s -> (match last_non_space (len - 1) with | None -> assert false | Some e -> Buffer.To_string.sub buf ~pos:s ~len:(e - s + 1)) ;; let make_emit_field ~strip current_row field = stage (fun () -> Queue.enqueue current_row (if strip then strip_buffer field else Buffer.contents field); Buffer.clear field) ;; let set_headers header_index headers = List.iteri headers ~f:(fun i h -> Option.iter h ~f:(fun h -> match Hashtbl.find header_index h with | None -> Hashtbl.set header_index ~key:h ~data:i | Some other_i -> failwithf "header %s duplicated at position %i and %i" h other_i i ())) ;; let make_emit_row current_row row_queue header ~lineno = let module Table = String.Table in let header_index = match (header : Header.t) with | `No | `Yes | `Require _ | `Transform _ | `Filter_map _ -> Table.create () ~size:1 | `Replace headers | `Add headers -> Table.of_alist_exn (List.mapi headers ~f:(fun i s -> s, i)) in let header_processed = ref (match header with | `No | `Add _ -> true | `Require _ | `Replace _ | `Transform _ | `Filter_map _ | `Yes -> false) in ( `on_eof (fun () -> if not !header_processed then failwith "Header line was not found") , fun () -> if not !header_processed then ( header_processed := true; match header with | `No | `Add _ -> assert false | `Require at_least -> let headers = Queue.to_list current_row in List.iter at_least ~f:(fun must_exist -> match List.findi headers ~f:(fun _ h -> String.equal h must_exist) with | None -> failwithf "The required header '%s' was not found in '%s' (lineno=%d)" must_exist (String.concat ~sep:"," headers) !lineno () | Some (i, _) -> Hashtbl.set header_index ~key:must_exist ~data:i) | `Transform f -> Queue.to_list current_row |> f |> List.map ~f:Option.some |> set_headers header_index | `Filter_map f -> Queue.to_list current_row |> f |> set_headers header_index | `Yes -> Queue.to_list current_row |> List.map ~f:Option.some |> set_headers header_index) else Queue.enqueue row_queue (Row.create header_index (Queue.to_array current_row)); lineno := !lineno + 1; Queue.clear current_row ) ;;
ccbde1a92e54ec832e162c725712caa510710c414fac26498af7142f115f16b2
tarides/opam-monorepo
test_uri_utils.ml
module Normalized = Duniverse_lib.Uri_utils.Normalized let test_canonical_uri = let make_test ~supplied:(a, b) ~expected = let a = Uri.of_string a in let a' = Normalized.of_uri a in let b = Uri.of_string b in let b' = Normalized.of_uri b in let test_name = Fmt.str "Comparing %a and %a" Uri.pp a Uri.pp b in let test_fun () = let actual = Normalized.equal a' b' in Alcotest.(check bool) test_name expected actual in (test_name, `Quick, test_fun) in [ make_test ~supplied: ( "git+-clock.git", "git+-clock.git" ) ~expected:true; make_test ~supplied: ( "git-clock.git", "git+-clock.git" ) ~expected:true; make_test ~supplied: ( "-clock.git", "git+-clock.git" ) ~expected:true; make_test ~supplied: ( "git+-clock.git#master", "git+-clock.git" ) ~expected:true; make_test ~supplied: ( "git+-clock", "git+-clock.git" ) ~expected:true; make_test ~supplied: ( "git+-foo.git", "git+-bar.git" ) ~expected:false; make_test ~supplied: ( "git+", "git+" ) ~expected:false; ] let suite = ("Uri_utils", test_canonical_uri)
null
https://raw.githubusercontent.com/tarides/opam-monorepo/5557a3253aa3e032418fb0bff4830e203ab87ae6/test/lib/test_uri_utils.ml
ocaml
module Normalized = Duniverse_lib.Uri_utils.Normalized let test_canonical_uri = let make_test ~supplied:(a, b) ~expected = let a = Uri.of_string a in let a' = Normalized.of_uri a in let b = Uri.of_string b in let b' = Normalized.of_uri b in let test_name = Fmt.str "Comparing %a and %a" Uri.pp a Uri.pp b in let test_fun () = let actual = Normalized.equal a' b' in Alcotest.(check bool) test_name expected actual in (test_name, `Quick, test_fun) in [ make_test ~supplied: ( "git+-clock.git", "git+-clock.git" ) ~expected:true; make_test ~supplied: ( "git-clock.git", "git+-clock.git" ) ~expected:true; make_test ~supplied: ( "-clock.git", "git+-clock.git" ) ~expected:true; make_test ~supplied: ( "git+-clock.git#master", "git+-clock.git" ) ~expected:true; make_test ~supplied: ( "git+-clock", "git+-clock.git" ) ~expected:true; make_test ~supplied: ( "git+-foo.git", "git+-bar.git" ) ~expected:false; make_test ~supplied: ( "git+", "git+" ) ~expected:false; ] let suite = ("Uri_utils", test_canonical_uri)
09af1af01adc2172426fba79c133b8472157c619c58c29c257b49dee66ce81a8
lem-project/lem
syntax-table.lisp
(defpackage :lem-lisp-syntax.syntax-table (:use :cl :lem-base) (:export :*syntax-table*) #+sbcl (:lock t)) (in-package :lem-lisp-syntax.syntax-table) (flet ((f (c1 c2 step-fn) (when c1 (when (and (member c1 '(#\#)) (or (alphanumericp c2) (member c2 '(#\+ #\-)))) (funcall step-fn))))) (defun skip-expr-prefix-forward (point) (f (character-at point 0) (character-at point 1) (lambda () (character-offset point 2)))) (defun skip-expr-prefix-backward (point) (f (character-at point -2) (character-at point -1) (lambda () (character-offset point -2))))) (defvar *syntax-table* (make-syntax-table :space-chars '(#\space #\tab #\newline) :symbol-chars '(#\+ #\- #\< #\> #\/ #\* #\& #\= #\. #\? #\_ #\! #\$ #\% #\: #\@ #\[ #\] #\^ #\{ #\} #\~ #\# #\|) :paren-pairs '((#\( . #\)) (#\[ . #\]) (#\{ . #\})) :string-quote-chars '(#\") :escape-chars '(#\\) :fence-chars '(#\|) :expr-prefix-chars '(#\' #\, #\@ #\# #\`) :expr-prefix-forward-function 'skip-expr-prefix-forward :expr-prefix-backward-function 'skip-expr-prefix-backward :line-comment-string ";" :block-comment-pairs '(("#|" . "|#"))))
null
https://raw.githubusercontent.com/lem-project/lem/a17b56e415eb7a94fa3653800b9fea7ae59f664c/lib/lisp-syntax/syntax-table.lisp
lisp
(defpackage :lem-lisp-syntax.syntax-table (:use :cl :lem-base) (:export :*syntax-table*) #+sbcl (:lock t)) (in-package :lem-lisp-syntax.syntax-table) (flet ((f (c1 c2 step-fn) (when c1 (when (and (member c1 '(#\#)) (or (alphanumericp c2) (member c2 '(#\+ #\-)))) (funcall step-fn))))) (defun skip-expr-prefix-forward (point) (f (character-at point 0) (character-at point 1) (lambda () (character-offset point 2)))) (defun skip-expr-prefix-backward (point) (f (character-at point -2) (character-at point -1) (lambda () (character-offset point -2))))) (defvar *syntax-table* (make-syntax-table :space-chars '(#\space #\tab #\newline) :symbol-chars '(#\+ #\- #\< #\> #\/ #\* #\& #\= #\. #\? #\_ #\! #\$ #\% #\: #\@ #\[ #\] #\^ #\{ #\} #\~ #\# #\|) :paren-pairs '((#\( . #\)) (#\[ . #\]) (#\{ . #\})) :string-quote-chars '(#\") :escape-chars '(#\\) :fence-chars '(#\|) :expr-prefix-chars '(#\' #\, #\@ #\# #\`) :expr-prefix-forward-function 'skip-expr-prefix-forward :expr-prefix-backward-function 'skip-expr-prefix-backward :line-comment-string ";" :block-comment-pairs '(("#|" . "|#"))))
c6cedc9b14ab3d1475c24ddd3aeaf44d2a8bb22faa171a8e7c634c1da19a2dbe
ageneau/ecl-android
package.lisp
(in-package :cl-user) (defpackage :openglsample (:use :cl :cl-opengl) (:export #:shader-vao-window #:setup #:tick #:display #:reshape #:cleanup))
null
https://raw.githubusercontent.com/ageneau/ecl-android/324180b7701eaa24228d8602fafe7c040c976867/iOS/OpenGLSample/OpenGLSample/Lisp/package.lisp
lisp
(in-package :cl-user) (defpackage :openglsample (:use :cl :cl-opengl) (:export #:shader-vao-window #:setup #:tick #:display #:reshape #:cleanup))
ce02ede7faf94020a7ff2383595407c71193c54aa14d3fb814ca73339e3b6e6d
rescript-lang/rescript-editor-support
Files.ml
let split str string = Str.split (Str.regexp_string str) string let removeExtraDots path = Str.global_replace (Str.regexp_string "/./") "/" path |> Str.global_replace (Str.regexp {|^\./\.\./|}) "../" (* Win32 & MacOS are case-insensitive *) let pathEq = match Sys.os_type = "Linux" with | true -> fun a b -> a = b | false -> fun a b -> String.lowercase_ascii a = String.lowercase_ascii b let pathStartsWith text prefix = String.length prefix <= String.length text && pathEq (String.sub text 0 (String.length prefix)) prefix let sliceToEnd str pos = String.sub str pos (String.length str - pos) let relpath base path = if pathStartsWith path base then let baselen = String.length base in let rest = String.sub path baselen (String.length path - baselen) in if rest = "" then "." ^ Filename.dir_sep else if rest.[0] = Filename.dir_sep.[0] then if String.length rest > 1 && rest.[1] = '.' then sliceToEnd rest 1 else "." ^ rest else if rest.[0] = '.' then rest else "." ^ Filename.dir_sep ^ rest else let rec loop bp pp = match (bp, pp) with | "." :: ra, _ -> loop ra pp | _, "." :: rb -> loop bp rb | a :: ra, b :: rb when pathEq a b -> loop ra rb | _ -> (bp, pp) in let base, path = loop (split Filename.dir_sep base) (split Filename.dir_sep path) in String.concat Filename.dir_sep ( ( match base = [] with | true -> ["."] | false -> List.map (fun _ -> "..") base ) @ path ) |> removeExtraDots let maybeStat path = try Some (Unix.stat path) with Unix.Unix_error (Unix.ENOENT, _, _) -> None let getMtime path = match maybeStat path with Some {Unix.st_mtime} -> Some st_mtime | _ -> None let readFile ~filename = try (* windows can't use open_in *) let chan = open_in_bin filename in let content = really_input_string chan (in_channel_length chan) in close_in_noerr chan; Some content with | _ -> None let exists path = match maybeStat path with None -> false | Some _ -> true let ifExists path = match exists path with true -> Some path | false -> None let readDirectory dir = let maybeGet handle = try Some (Unix.readdir handle) with End_of_file -> None in let rec loop handle = match maybeGet handle with | None -> Unix.closedir handle; [] | Some name when name = Filename.current_dir_name || name = Filename.parent_dir_name -> loop handle | Some name -> name :: loop handle in match Unix.opendir dir with | exception Unix.Unix_error (Unix.ENOENT, "opendir", _dir) -> [] | handle -> loop handle let rec collectDirs path = match maybeStat path with | None -> [] | Some {Unix.st_kind = Unix.S_DIR} -> path :: ( readDirectory path |> List.map (fun name -> collectDirs (Filename.concat path name)) |> List.concat ) | _ -> [] let rec collect ?(checkDir = fun _ -> true) path test = match maybeStat path with | None -> [] | Some {Unix.st_kind = Unix.S_DIR} -> if checkDir path then readDirectory path |> List.map (fun name -> collect ~checkDir (Filename.concat path name) test) |> List.concat else [] | _ -> ( match test path with true -> [path] | false -> [] ) let fileConcat a b = if b <> "" && b.[0] = '.' && String.length b >= 2 && b.[1] = Filename.dir_sep.[0] then Filename.concat a (String.sub b 2 (String.length b - 2)) else Filename.concat a b let isFullPath b = b.[0] = '/' || (Sys.win32 && String.length b > 1 && b.[1] = ':') let maybeConcat a b = if b <> "" && isFullPath b then b else fileConcat a b
null
https://raw.githubusercontent.com/rescript-lang/rescript-editor-support/abc79068861c2a4811e8ce2072908167bd7fbf25/src/Files.ml
ocaml
Win32 & MacOS are case-insensitive windows can't use open_in
let split str string = Str.split (Str.regexp_string str) string let removeExtraDots path = Str.global_replace (Str.regexp_string "/./") "/" path |> Str.global_replace (Str.regexp {|^\./\.\./|}) "../" let pathEq = match Sys.os_type = "Linux" with | true -> fun a b -> a = b | false -> fun a b -> String.lowercase_ascii a = String.lowercase_ascii b let pathStartsWith text prefix = String.length prefix <= String.length text && pathEq (String.sub text 0 (String.length prefix)) prefix let sliceToEnd str pos = String.sub str pos (String.length str - pos) let relpath base path = if pathStartsWith path base then let baselen = String.length base in let rest = String.sub path baselen (String.length path - baselen) in if rest = "" then "." ^ Filename.dir_sep else if rest.[0] = Filename.dir_sep.[0] then if String.length rest > 1 && rest.[1] = '.' then sliceToEnd rest 1 else "." ^ rest else if rest.[0] = '.' then rest else "." ^ Filename.dir_sep ^ rest else let rec loop bp pp = match (bp, pp) with | "." :: ra, _ -> loop ra pp | _, "." :: rb -> loop bp rb | a :: ra, b :: rb when pathEq a b -> loop ra rb | _ -> (bp, pp) in let base, path = loop (split Filename.dir_sep base) (split Filename.dir_sep path) in String.concat Filename.dir_sep ( ( match base = [] with | true -> ["."] | false -> List.map (fun _ -> "..") base ) @ path ) |> removeExtraDots let maybeStat path = try Some (Unix.stat path) with Unix.Unix_error (Unix.ENOENT, _, _) -> None let getMtime path = match maybeStat path with Some {Unix.st_mtime} -> Some st_mtime | _ -> None let readFile ~filename = try let chan = open_in_bin filename in let content = really_input_string chan (in_channel_length chan) in close_in_noerr chan; Some content with | _ -> None let exists path = match maybeStat path with None -> false | Some _ -> true let ifExists path = match exists path with true -> Some path | false -> None let readDirectory dir = let maybeGet handle = try Some (Unix.readdir handle) with End_of_file -> None in let rec loop handle = match maybeGet handle with | None -> Unix.closedir handle; [] | Some name when name = Filename.current_dir_name || name = Filename.parent_dir_name -> loop handle | Some name -> name :: loop handle in match Unix.opendir dir with | exception Unix.Unix_error (Unix.ENOENT, "opendir", _dir) -> [] | handle -> loop handle let rec collectDirs path = match maybeStat path with | None -> [] | Some {Unix.st_kind = Unix.S_DIR} -> path :: ( readDirectory path |> List.map (fun name -> collectDirs (Filename.concat path name)) |> List.concat ) | _ -> [] let rec collect ?(checkDir = fun _ -> true) path test = match maybeStat path with | None -> [] | Some {Unix.st_kind = Unix.S_DIR} -> if checkDir path then readDirectory path |> List.map (fun name -> collect ~checkDir (Filename.concat path name) test) |> List.concat else [] | _ -> ( match test path with true -> [path] | false -> [] ) let fileConcat a b = if b <> "" && b.[0] = '.' && String.length b >= 2 && b.[1] = Filename.dir_sep.[0] then Filename.concat a (String.sub b 2 (String.length b - 2)) else Filename.concat a b let isFullPath b = b.[0] = '/' || (Sys.win32 && String.length b > 1 && b.[1] = ':') let maybeConcat a b = if b <> "" && isFullPath b then b else fileConcat a b
7f96b4c5fa3ed27117aa442fbeb9e12d5bfb432fe4de5fce151232a5128fd46a
EarnestResearch/honeycomb-haskell
Api.hs
-- | -- Module : Honeycomb.Api -- Description : API access library for @honeycomb.io@ Copyright : ( c ) 2019 - 2020 Earnest Research -- License : Apache-2 -- Maintainer : -- Stability : alpha -- Portability : POSIX -- -- The "Honeycomb.Api" module provides a very low-level method of accessing the Honeycomb API . Each call represents a direct request to the Honeycomb -- servers (with limited support for retrying on timeout). module Honeycomb.Api ( module Honeycomb.Api.Events, module Honeycomb.Api.Types, ) where import Honeycomb.Api.Events import Honeycomb.Api.Types
null
https://raw.githubusercontent.com/EarnestResearch/honeycomb-haskell/0cb643a637e1b23eecded845970e6a973f8385cf/honeycomb/src/Honeycomb/Api.hs
haskell
| Module : Honeycomb.Api Description : API access library for @honeycomb.io@ License : Apache-2 Maintainer : Stability : alpha Portability : POSIX The "Honeycomb.Api" module provides a very low-level method of accessing servers (with limited support for retrying on timeout).
Copyright : ( c ) 2019 - 2020 Earnest Research the Honeycomb API . Each call represents a direct request to the Honeycomb module Honeycomb.Api ( module Honeycomb.Api.Events, module Honeycomb.Api.Types, ) where import Honeycomb.Api.Events import Honeycomb.Api.Types
0abdde3537df6ccf66cc5959a62bfe8a737798b2ffcaeb6d434abd10890117ee
arttuka/reagent-material-ui
oil_barrel_sharp.cljs
(ns reagent-mui.icons.oil-barrel-sharp "Imports @mui/icons-material/OilBarrelSharp as a Reagent component." (:require-macros [reagent-mui.util :refer [create-svg-icon e]]) (:require [react :as react] ["@mui/material/SvgIcon" :as SvgIcon] [reagent-mui.util])) (def oil-barrel-sharp (create-svg-icon (e "path" #js {"d" "M21 13v-2h-2V5h2V3H3v2h2v6H3v2h2v6H3v2h18v-2h-2v-6h2zm-9 3c-1.66 0-3-1.32-3-2.95 0-1.3.52-1.67 3-4.55 2.47 2.86 3 3.24 3 4.55 0 1.63-1.34 2.95-3 2.95z"}) "OilBarrelSharp"))
null
https://raw.githubusercontent.com/arttuka/reagent-material-ui/c7cd0d7c661ab9df5b0aed0213a6653a9a3f28ea/src/icons/reagent_mui/icons/oil_barrel_sharp.cljs
clojure
(ns reagent-mui.icons.oil-barrel-sharp "Imports @mui/icons-material/OilBarrelSharp as a Reagent component." (:require-macros [reagent-mui.util :refer [create-svg-icon e]]) (:require [react :as react] ["@mui/material/SvgIcon" :as SvgIcon] [reagent-mui.util])) (def oil-barrel-sharp (create-svg-icon (e "path" #js {"d" "M21 13v-2h-2V5h2V3H3v2h2v6H3v2h2v6H3v2h18v-2h-2v-6h2zm-9 3c-1.66 0-3-1.32-3-2.95 0-1.3.52-1.67 3-4.55 2.47 2.86 3 3.24 3 4.55 0 1.63-1.34 2.95-3 2.95z"}) "OilBarrelSharp"))
ec2d9fca583fb9d16fc30a062b1bdfd740784dceff15050dc94e7472412199ce
pascal-knodel/haskell-craft
E'5'19.hs
-- -- -- ----------------- Exercise 5.19 . ----------------- -- -- -- module E'5'19 where import Prelude hiding ( toUpper , isLower ) import qualified Data.Char ( toUpper , isLower ) -- To implement capitalize we could reuse solutions from earlier exercises ... Exercise 3.16 ( solution of it ) . upperLowerCaseOffset :: Int upperLowerCaseOffset = (fromEnum 'a') - (fromEnum 'A') isLower :: Char -> Bool isLower aChar | (aChar >= 'a') && (aChar <= 'z') = True | otherwise = False toUpper :: Char -> Char toUpper aChar | isLower aChar = toEnum ( (fromEnum aChar) - upperLowerCaseOffset ) | otherwise = aChar -- ... capitalize :: String -> String capitalize s = [ toUpper l | l <- s ] GHCi > capitalize " a=1 ; b=2 ; c=3 ; " capitalize "a=1 ; b=2 ; c=3 ;" -} " A=1 ; B=2 ; C=3 ; " capitalizeLetters :: String -> String capitalizeLetters s = [ toUpper l | l <- s, isLower l ] GHCi > capitalizeLetters " a=1 ; b=2 ; c=3 ; " capitalizeLetters "a=1 ; b=2 ; c=3 ;" -} " ABC " -- Other solutions for "capitalize" and "capitalizeLetters": capitalize' :: String -> String capitalize' s = [ Data.Char.toUpper l | l <- s ] capitalizeLetters' :: String -> String capitalizeLetters' s = [ toUpper l | l <- s, Data.Char.isLower l ] capitalize'3 :: String -> String capitalize'3 s = map toUpper s capitalizeLetters'3 :: String -> String capitalizeLetters'3 s = map toUpper (filter isLower s) capitalize'4 :: String -> String capitalize'4 s = map Data.Char.toUpper s capitalizeLetters'4 :: String -> String capitalizeLetters'4 s = map Data.Char.toUpper (filter Data.Char.isLower s)
null
https://raw.githubusercontent.com/pascal-knodel/haskell-craft/c03d6eb857abd8b4785b6de075b094ec3653c968/_/links/E'5'19.hs
haskell
--------------- --------------- To implement capitalize we could reuse solutions from earlier exercises ... ... Other solutions for "capitalize" and "capitalizeLetters":
Exercise 5.19 . module E'5'19 where import Prelude hiding ( toUpper , isLower ) import qualified Data.Char ( toUpper , isLower ) Exercise 3.16 ( solution of it ) . upperLowerCaseOffset :: Int upperLowerCaseOffset = (fromEnum 'a') - (fromEnum 'A') isLower :: Char -> Bool isLower aChar | (aChar >= 'a') && (aChar <= 'z') = True | otherwise = False toUpper :: Char -> Char toUpper aChar | isLower aChar = toEnum ( (fromEnum aChar) - upperLowerCaseOffset ) | otherwise = aChar capitalize :: String -> String capitalize s = [ toUpper l | l <- s ] GHCi > capitalize " a=1 ; b=2 ; c=3 ; " capitalize "a=1 ; b=2 ; c=3 ;" -} " A=1 ; B=2 ; C=3 ; " capitalizeLetters :: String -> String capitalizeLetters s = [ toUpper l | l <- s, isLower l ] GHCi > capitalizeLetters " a=1 ; b=2 ; c=3 ; " capitalizeLetters "a=1 ; b=2 ; c=3 ;" -} " ABC " capitalize' :: String -> String capitalize' s = [ Data.Char.toUpper l | l <- s ] capitalizeLetters' :: String -> String capitalizeLetters' s = [ toUpper l | l <- s, Data.Char.isLower l ] capitalize'3 :: String -> String capitalize'3 s = map toUpper s capitalizeLetters'3 :: String -> String capitalizeLetters'3 s = map toUpper (filter isLower s) capitalize'4 :: String -> String capitalize'4 s = map Data.Char.toUpper s capitalizeLetters'4 :: String -> String capitalizeLetters'4 s = map Data.Char.toUpper (filter Data.Char.isLower s)
184d404128a32bd5a40e2fd9df8889a28c127396501938ddc195775f3af8b4d5
alanz/ghc-exactprint
proc-do-complex.hs
{-# LANGUAGE Arrows #-} foo f g h ma = proc ( (a, b), (c, d), (e, f) ) -> do -- Begin do GHC parser fails if layed out over multiple lines <- f -- Call into f (a, c) -- Tuple together arguments (b, d) -< (b + 1, -- Funnel into arrow d * b) if x `mod` y == 0 -- Basic condition then case e -- Only left case is relevant of Left (z, Procs can have lambdas let v = u -- Actually never used ^ 2 in (returnA -< -- Just do the calculation (x + y * z)) else do let u = x -- Let bindings bind expressions, not commands -- Could pattern match directly on x i <- case u of 0 -> (g . h -< u) n -> ( (h . g First actual use of y ) returnA -< () -- Sometimes execute effects if i > 0 then ma -< () else returnA -< () returnA -< (i + x * y) -- Just do the calculation
null
https://raw.githubusercontent.com/alanz/ghc-exactprint/103bc706c82300639985a15ba6cf762316352c92/tests/examples/ghc92/proc-do-complex.hs
haskell
# LANGUAGE Arrows # Begin do Call into f Tuple together arguments Funnel into arrow Basic condition Only left case is relevant Actually never used Just do the calculation Let bindings bind expressions, not commands Could pattern match directly on x Sometimes execute effects Just do the calculation
foo f g h ma = proc ( (a, b), (c, d), (e, f) ) -> GHC parser fails if layed out over multiple lines (a, (b, d) d * b) if of Left (z, Procs can have lambdas let v ^ 2 in (returnA (x + y * z)) else do i <- case u of 0 -> (g . h -< u) n -> ( (h . g First actual use of y ) returnA -< () if i > 0 then ma -< () else returnA -< () returnA -< (i + x *
c95d0b5adcf3ed1e86193505d804e637ea607ba0d1f8861470b5c45708c4be8e
graninas/Pragmatic-Type-Level-Design
Types.hs
module HCell.Gloss.Types where import CPrelude import HCell.Types -- X is horizontal, grows to right -- Y is vertical, grows to up -- (-x, -y) is the left bottom corner -- (0, 0) is in the center of the window newtype GlossCoords = GlossCoords (Float, Float) Moves ( 0 , 0 ) to the left down corner newtype GlossBaseShift = GlossBaseShift (Float, Float) newtype GlossWindowSize = GlossWindowSize Coords newtype GlossWindowPosition = GlossWindowPosition Coords newtype GlossBareCellSize = GlossBareCellSize Float newtype GlossGridCellSize = GlossGridCellSize Float newtype GlossTextScale = GlossTextScale Float
null
https://raw.githubusercontent.com/graninas/Pragmatic-Type-Level-Design/a95f9a5d7ae5b443b9d8ef77b27f1aecf02f461a/demo-apps/hcell/src/HCell/Gloss/Types.hs
haskell
X is horizontal, grows to right Y is vertical, grows to up (-x, -y) is the left bottom corner (0, 0) is in the center of the window
module HCell.Gloss.Types where import CPrelude import HCell.Types newtype GlossCoords = GlossCoords (Float, Float) Moves ( 0 , 0 ) to the left down corner newtype GlossBaseShift = GlossBaseShift (Float, Float) newtype GlossWindowSize = GlossWindowSize Coords newtype GlossWindowPosition = GlossWindowPosition Coords newtype GlossBareCellSize = GlossBareCellSize Float newtype GlossGridCellSize = GlossGridCellSize Float newtype GlossTextScale = GlossTextScale Float
c9811b6d1f0bf5fa8abcdba7d3eadaedf721dc9f65f958a5c2d99960860d5c5d
kanatohodets/riak_core_workshop_euc2016
kvapi_app.erl
%%%------------------------------------------------------------------- %% @doc kvapi public API %% @end %%%------------------------------------------------------------------- -module(kvapi_app). -behaviour(application). %% Application callbacks -export([start/2, stop/1]). %%==================================================================== %% API %%==================================================================== start(_StartType, _StartArgs) -> Dispatch = cowboy_router:compile([ {'_', [{"/api/store/:key", kvapi_handler, []}]} ]), cowboy:start_http(kvapi_http_listener, 100, [{port, 4000}], [{env, [{dispatch, Dispatch}]}] ), kvapi_sup:start_link(). %%-------------------------------------------------------------------- stop(_State) -> ok. %%==================================================================== Internal functions %%====================================================================
null
https://raw.githubusercontent.com/kanatohodets/riak_core_workshop_euc2016/a396bb5a1879ec0cb3d70bbc4b6cd39e097cd610/5_http_kv/erlang/apps/kvapi/src/kvapi_app.erl
erlang
------------------------------------------------------------------- @doc kvapi public API @end ------------------------------------------------------------------- Application callbacks ==================================================================== API ==================================================================== -------------------------------------------------------------------- ==================================================================== ====================================================================
-module(kvapi_app). -behaviour(application). -export([start/2, stop/1]). start(_StartType, _StartArgs) -> Dispatch = cowboy_router:compile([ {'_', [{"/api/store/:key", kvapi_handler, []}]} ]), cowboy:start_http(kvapi_http_listener, 100, [{port, 4000}], [{env, [{dispatch, Dispatch}]}] ), kvapi_sup:start_link(). stop(_State) -> ok. Internal functions
b42a9798ac75f2750930efd094ce78afec64d64c0684acc1848a4b78703c00c7
esb-lwb/lwb
sat_test.clj
lwb Logic WorkBench -- Propositional Logic , tests Copyright ( c ) 2014 - 2017 , THM . All rights reserved . ; The use and distribution terms for this software are covered by the Eclipse Public License 1.0 ( -1.0.php ) . ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. (ns lwb.prop.sat-test (:require [clojure.test :refer :all] [lwb.prop :refer :all] [lwb.prop.sat :refer :all] [clojure.spec.alpha :as s] [clojure.spec.test.alpha :as stest])) (stest/instrument) ; dimacs -------------------------------------------------------------- (deftest cl->dimacs-test (is (= #{1 2} (#'lwb.prop.sat/cl->dimacs '(or P Q) '{P 1 Q 2}))) (is (= #{-1 2} (#'lwb.prop.sat/cl->dimacs '(or (not P) Q) '{P 1 Q 2}))) (is (= #{-1 -2} (#'lwb.prop.sat/cl->dimacs '(or (not P) (not Q)) '{P 1 Q 2}))) ) (deftest cnf->dimacs-test (is (= true (s/valid? :lwb.prop.sat/dimacs (cnf->dimacs '(and (or P Q) (or (not Q) R)))))) (is (= {:formula '(and (or P Q) (or (not Q) R)), :num-atoms 3, :int-atoms '{1 P, 2 Q, 3 R}, :num-cl 2, :cl-set #{#{1 2} #{-2 3}}} (cnf->dimacs '(and (or P Q) (or (not Q) R))))) (is (= true (s/valid? :lwb.prop.sat/dimacs (cnf->dimacs '(and (or P Q) (or (not Q) R) (or (not T) (not R) S)))))) (is (= {:formula '(and (or P Q) (or (not Q) R) (or (not T) (not R) S)), :num-atoms 5, :int-atoms '{1 P, 2 Q, 3 R, 4 S, 5 T}, :num-cl 3, :cl-set #{#{4 -3 -5} #{1 2} #{-2 3}}} (cnf->dimacs '(and (or P Q) (or (not Q) R) (or (not T) (not R) S))))) ) ; sat4j --------------------------------------------------------------- (deftest sat4j-solve-test (is (= true (s/valid? :lwb.prop/model (sat4j-solve (cnf->dimacs '(and (or P Q) (or (not Q) R))))))) (is (= true (s/valid? nil? (sat4j-solve (cnf->dimacs '(and (or P) (or (not P)))))))) ) ; tseitin ------------------------------------------------------------- (deftest tseitin-test (is (= (tseitin '(impl (and P Q) T)) '(and (or ts-1) (or T (not ts-2) (not ts-1)) (or ts-2 ts-1) (or ts-1 (not T)) (or P (not ts-2)) (or Q (not ts-2)) (or ts-2 (not Q) (not P))))) (is (= (tseitin '(or P1 (and P2 (impl P3 P4)))) '(and (or ts-1) (or ts-2 P1 (not ts-1)) (or ts-1 (not P1)) (or ts-1 (not ts-2)) (or P2 (not ts-2)) (or ts-3 (not ts-2)) (or ts-2 (not ts-3) (not P2)) (or P4 (not ts-3) (not P3)) (or ts-3 P3) (or ts-3 (not P4))))) ) ; sat ----------------------------------------------------------------- (deftest sat-test (is (= (sat '(and P Q)) '{P true Q true})) (is (= (sat '(and P Q R S)) '{P true Q true R true S true})) (is (= (sat '(or P1 (and P2 (impl P3 P4)))) '{P1 false P2 true P3 false P4 false})) ) ; sat? ---------------------------------------------------------------- (deftest sat?-test (is (= true (sat? '(and P Q)))) (is (= true (sat? '(or P Q)))) (is (= true (sat? '(impl P Q)))) (is (= true (sat? '(equiv P Q)))) (is (= true (sat? '(xor P Q)))) (is (= true (sat? '(ite P Q R)))) (is (= true (sat? '(or (ite P Q R) (impl P Q) (and R S))))) (is (= false (sat? '(and P Q (not P))))) ) ; valid? -------------------------------------------------------------- (deftest valid?-test (is (= true (valid? '(or P (not P))))) (is (= false (valid? '(or P Q)))) ) (run-tests)
null
https://raw.githubusercontent.com/esb-lwb/lwb/bba51ada7f7316341733d37b0dc4848c4891ef3a/test/lwb/prop/sat_test.clj
clojure
The use and distribution terms for this software are covered by the By using this software in any fashion, you are agreeing to be bound by the terms of this license. dimacs -------------------------------------------------------------- sat4j --------------------------------------------------------------- tseitin ------------------------------------------------------------- sat ----------------------------------------------------------------- sat? ---------------------------------------------------------------- valid? --------------------------------------------------------------
lwb Logic WorkBench -- Propositional Logic , tests Copyright ( c ) 2014 - 2017 , THM . All rights reserved . Eclipse Public License 1.0 ( -1.0.php ) . (ns lwb.prop.sat-test (:require [clojure.test :refer :all] [lwb.prop :refer :all] [lwb.prop.sat :refer :all] [clojure.spec.alpha :as s] [clojure.spec.test.alpha :as stest])) (stest/instrument) (deftest cl->dimacs-test (is (= #{1 2} (#'lwb.prop.sat/cl->dimacs '(or P Q) '{P 1 Q 2}))) (is (= #{-1 2} (#'lwb.prop.sat/cl->dimacs '(or (not P) Q) '{P 1 Q 2}))) (is (= #{-1 -2} (#'lwb.prop.sat/cl->dimacs '(or (not P) (not Q)) '{P 1 Q 2}))) ) (deftest cnf->dimacs-test (is (= true (s/valid? :lwb.prop.sat/dimacs (cnf->dimacs '(and (or P Q) (or (not Q) R)))))) (is (= {:formula '(and (or P Q) (or (not Q) R)), :num-atoms 3, :int-atoms '{1 P, 2 Q, 3 R}, :num-cl 2, :cl-set #{#{1 2} #{-2 3}}} (cnf->dimacs '(and (or P Q) (or (not Q) R))))) (is (= true (s/valid? :lwb.prop.sat/dimacs (cnf->dimacs '(and (or P Q) (or (not Q) R) (or (not T) (not R) S)))))) (is (= {:formula '(and (or P Q) (or (not Q) R) (or (not T) (not R) S)), :num-atoms 5, :int-atoms '{1 P, 2 Q, 3 R, 4 S, 5 T}, :num-cl 3, :cl-set #{#{4 -3 -5} #{1 2} #{-2 3}}} (cnf->dimacs '(and (or P Q) (or (not Q) R) (or (not T) (not R) S))))) ) (deftest sat4j-solve-test (is (= true (s/valid? :lwb.prop/model (sat4j-solve (cnf->dimacs '(and (or P Q) (or (not Q) R))))))) (is (= true (s/valid? nil? (sat4j-solve (cnf->dimacs '(and (or P) (or (not P)))))))) ) (deftest tseitin-test (is (= (tseitin '(impl (and P Q) T)) '(and (or ts-1) (or T (not ts-2) (not ts-1)) (or ts-2 ts-1) (or ts-1 (not T)) (or P (not ts-2)) (or Q (not ts-2)) (or ts-2 (not Q) (not P))))) (is (= (tseitin '(or P1 (and P2 (impl P3 P4)))) '(and (or ts-1) (or ts-2 P1 (not ts-1)) (or ts-1 (not P1)) (or ts-1 (not ts-2)) (or P2 (not ts-2)) (or ts-3 (not ts-2)) (or ts-2 (not ts-3) (not P2)) (or P4 (not ts-3) (not P3)) (or ts-3 P3) (or ts-3 (not P4))))) ) (deftest sat-test (is (= (sat '(and P Q)) '{P true Q true})) (is (= (sat '(and P Q R S)) '{P true Q true R true S true})) (is (= (sat '(or P1 (and P2 (impl P3 P4)))) '{P1 false P2 true P3 false P4 false})) ) (deftest sat?-test (is (= true (sat? '(and P Q)))) (is (= true (sat? '(or P Q)))) (is (= true (sat? '(impl P Q)))) (is (= true (sat? '(equiv P Q)))) (is (= true (sat? '(xor P Q)))) (is (= true (sat? '(ite P Q R)))) (is (= true (sat? '(or (ite P Q R) (impl P Q) (and R S))))) (is (= false (sat? '(and P Q (not P))))) ) (deftest valid?-test (is (= true (valid? '(or P (not P))))) (is (= false (valid? '(or P Q)))) ) (run-tests)
07d41a31930e9bd1bea123995cf38ef9dae1bfa7fc2045a581356b931bd23465
ericcervin/getting-started-with-sketching
pg054b.rkt
#lang sketching (define (setup) (size 220 120) (smoothing 'smoothed) (background 200) (set-frame-rate! 60) ) (define x 1) (define easing 0.01) (define (update-x) (let ([target-x mouse-x]) (set! x (+ x (* (- target-x x) easing))) (displayln (list target-x x)) ) ) (define (draw) (update-x) (ellipse x 40 12 12) )
null
https://raw.githubusercontent.com/ericcervin/getting-started-with-sketching/02969f7c85bb36ce83bbf96d38542619c4a1428a/pg054b.rkt
racket
#lang sketching (define (setup) (size 220 120) (smoothing 'smoothed) (background 200) (set-frame-rate! 60) ) (define x 1) (define easing 0.01) (define (update-x) (let ([target-x mouse-x]) (set! x (+ x (* (- target-x x) easing))) (displayln (list target-x x)) ) ) (define (draw) (update-x) (ellipse x 40 12 12) )
aae880fc728a2f06070e84637ed9c85d252a41e513b605c48e457a6c37ec3a6e
city41/reagent-breakout
level.cljs
(ns breakout.engine.level (:require-macros [cljs.core.async.macros :refer [go]]) (:require [cljs.core.async :refer [<!]] [reagent.core :refer [atom]] [breakout.engine.input :as input] [breakout.levels.data :as levels]) (:import goog.math.Rect)) ;; --- constants (def tile-size 16) (def board {:width 320 :height 416}) (def paddle-y (- (:height board) (* 3 tile-size))) (def ball-size {:width tile-size :height tile-size}) (def paddle-size {:width 48 :height 16}) (def starting-ball-pos {:x (* 2 tile-size) :y (* 15 tile-size)}) 120 pixels per second (def starting-ball-vel {:x base-vel :y base-vel}) (def total-countdown-duration 3500) ;; --- state, there's a lot of it (this is a game after all) (def phase (atom nil)) (def running (atom nil)) (def last-ts (atom nil)) (def next-scene! (atom nil)) (def score (atom nil)) (def lives (atom nil)) (def level (atom nil)) (def bricks (atom nil)) (def paddle-pos (atom {:x 0 :y paddle-y})) (def ball-pos (atom starting-ball-pos)) (def ball-vel (atom starting-ball-vel)) (def countdown-duration (atom total-countdown-duration)) ;; --- collision related ;; these functions detect collision and are called from update-state! :gameplay (def walls [(Rect. 0 0 tile-size (:height board)) (Rect. (- (:width board) tile-size) 0 tile-size (:height board))]) (def ceiling (Rect. 0 0 (:width board) tile-size)) (defn pos->rect [pos size] (Rect. (:x pos) (:y pos) (:width size) (:height size))) (defn get-collided-brick [ball-rect bricks] (first (filter #(.intersects (:rect %) ball-rect) bricks))) (defn- rect-collided-with [src-rect rects] (some #(.intersects % src-rect) rects)) (defn- get-collision [pos bricks walls ceiling paddle-pos] (let [ball-rect (pos->rect pos ball-size) collided-brick (get-collided-brick ball-rect bricks)] (or (and collided-brick [:brick collided-brick]) (and (rect-collided-with ball-rect walls) [:wall]) (and (rect-collided-with ball-rect [ceiling]) [:ceiling]) (and (rect-collided-with ball-rect [(pos->rect paddle-pos paddle-size)]) [:paddle]) [:none]))) (defn- move-ball [delta pos vel] (let [pos (update-in pos [:x] + (* delta (:x vel)))] (update-in pos [:y] + (* delta (:y vel))))) (defn- beyond-board? [pos] (>= (:y pos) (:height board))) (defn- flip! [vel-atom key] (swap! vel-atom assoc key (- (key @vel-atom)))) (defn- get-center-x [pos size] (+ (/ (:width size) 2) (:x pos))) TODO this is too primitive , in many situations it ;; does not pick the correct direction to flip (defn- get-flip-direction [ball-pos brick] (let [cbx (get-center-x ball-pos ball-size) left (get-in brick [:pos :x]) right (+ left (:width brick))] (if (and (> cbx left) (< cbx right)) :y :x))) ;; determines the x velocity for the ball based on where ;; on the paddle the ball struck. The closer to the center of the paddle , the closer to zero the x velocity (defn- get-x-vel-from-paddle-bounce [ball-pos paddle-pos] (let [half-paddle (/ (:width paddle-size) 2) cbx (get-center-x ball-pos ball-size) cpx (get-center-x paddle-pos paddle-size) distance (- cbx cpx) ratio (/ distance half-paddle)] (* 1.5 base-vel ratio))) (defn- setup-next-level! [level] (let [brick-data (levels/get-level-data level)] (when brick-data ;; small hack -- by delaying the brick data, it allows React 's CSSTransitionGroup to kick in , causing the bricks ;; to appear on the board with a CSS animation (.setTimeout js/window #(reset! bricks brick-data) 100) (reset! phase :countdown)))) ;; --- state initialization ;; called whenever a phase transition within gameplay happens (defmulti init-phase! identity) (defmethod init-phase! :countdown [_] (reset! ball-pos starting-ball-pos) (reset! countdown-duration total-countdown-duration)) (defmethod init-phase! :gameplay [_] (reset! ball-pos starting-ball-pos) (reset! ball-vel starting-ball-vel)) (add-watch phase :phase (fn [_ _ _ new-phase] (when new-phase (init-phase! new-phase)))) ;; --- updating phases ;; called once per frame to update the current phase (defmulti update-phase! (fn [delta phase] phase)) (defmethod update-phase! :countdown [delta _] (swap! countdown-duration - delta) (when (<= @countdown-duration 0) (reset! phase :gameplay))) (defmethod update-phase! :gameplay [delta _] (let [old-pos @ball-pos new-pos (move-ball delta old-pos @ball-vel) pad-pos @paddle-pos [collided-type collided-object] (get-collision new-pos @bricks walls ceiling pad-pos)] (case collided-type :wall (flip! ball-vel :x) :ceiling (flip! ball-vel :y) :paddle (do (flip! ball-vel :y) (swap! ball-vel assoc :x (get-x-vel-from-paddle-bounce new-pos pad-pos))) :brick (do (flip! ball-vel (get-flip-direction new-pos collided-object)) (swap! score + 100) (swap! bricks disj collided-object) (when (zero? (count @bricks)) (let [next-level (swap! level inc)] (when-not (setup-next-level! next-level) (@next-scene! :win))))) :none (if (beyond-board? new-pos) (let [remaining-lives (swap! lives dec)] (if (<= remaining-lives 0) (@next-scene! :game-over) (reset! phase :countdown))) (reset! ball-pos new-pos))))) (defn- update! [ts] (when @running (let [delta (- ts (or @last-ts ts))] (reset! last-ts ts) (update-phase! delta @phase)) (. js/window (requestAnimationFrame update!)))) (defn- listen-to-input-moves [] (go (while @running (let [input-x (<! input/movement)] (swap! paddle-pos assoc :x input-x))))) (defn- init! [] (reset! lives 3) (reset! score 0) (reset! level 0) (reset! bricks #{}) (setup-next-level! 0) (reset! last-ts nil) (reset! running true)) (defn start! [set-next-scene!] (reset! next-scene! set-next-scene!) (init!) (listen-to-input-moves) (. js/window (requestAnimationFrame update!))) (defn stop! [] (reset! running false))
null
https://raw.githubusercontent.com/city41/reagent-breakout/84907d0cbc2d3cae917e30f955bc8e42fcb2d505/src/cljs/breakout/engine/level.cljs
clojure
--- constants --- state, there's a lot of it (this is a game after all) --- collision related these functions detect collision and are called from update-state! :gameplay does not pick the correct direction to flip determines the x velocity for the ball based on where on the paddle the ball struck. The closer to the center small hack -- by delaying the brick data, it allows to appear on the board with a CSS animation --- state initialization called whenever a phase transition within gameplay happens --- updating phases called once per frame to update the current phase
(ns breakout.engine.level (:require-macros [cljs.core.async.macros :refer [go]]) (:require [cljs.core.async :refer [<!]] [reagent.core :refer [atom]] [breakout.engine.input :as input] [breakout.levels.data :as levels]) (:import goog.math.Rect)) (def tile-size 16) (def board {:width 320 :height 416}) (def paddle-y (- (:height board) (* 3 tile-size))) (def ball-size {:width tile-size :height tile-size}) (def paddle-size {:width 48 :height 16}) (def starting-ball-pos {:x (* 2 tile-size) :y (* 15 tile-size)}) 120 pixels per second (def starting-ball-vel {:x base-vel :y base-vel}) (def total-countdown-duration 3500) (def phase (atom nil)) (def running (atom nil)) (def last-ts (atom nil)) (def next-scene! (atom nil)) (def score (atom nil)) (def lives (atom nil)) (def level (atom nil)) (def bricks (atom nil)) (def paddle-pos (atom {:x 0 :y paddle-y})) (def ball-pos (atom starting-ball-pos)) (def ball-vel (atom starting-ball-vel)) (def countdown-duration (atom total-countdown-duration)) (def walls [(Rect. 0 0 tile-size (:height board)) (Rect. (- (:width board) tile-size) 0 tile-size (:height board))]) (def ceiling (Rect. 0 0 (:width board) tile-size)) (defn pos->rect [pos size] (Rect. (:x pos) (:y pos) (:width size) (:height size))) (defn get-collided-brick [ball-rect bricks] (first (filter #(.intersects (:rect %) ball-rect) bricks))) (defn- rect-collided-with [src-rect rects] (some #(.intersects % src-rect) rects)) (defn- get-collision [pos bricks walls ceiling paddle-pos] (let [ball-rect (pos->rect pos ball-size) collided-brick (get-collided-brick ball-rect bricks)] (or (and collided-brick [:brick collided-brick]) (and (rect-collided-with ball-rect walls) [:wall]) (and (rect-collided-with ball-rect [ceiling]) [:ceiling]) (and (rect-collided-with ball-rect [(pos->rect paddle-pos paddle-size)]) [:paddle]) [:none]))) (defn- move-ball [delta pos vel] (let [pos (update-in pos [:x] + (* delta (:x vel)))] (update-in pos [:y] + (* delta (:y vel))))) (defn- beyond-board? [pos] (>= (:y pos) (:height board))) (defn- flip! [vel-atom key] (swap! vel-atom assoc key (- (key @vel-atom)))) (defn- get-center-x [pos size] (+ (/ (:width size) 2) (:x pos))) TODO this is too primitive , in many situations it (defn- get-flip-direction [ball-pos brick] (let [cbx (get-center-x ball-pos ball-size) left (get-in brick [:pos :x]) right (+ left (:width brick))] (if (and (> cbx left) (< cbx right)) :y :x))) of the paddle , the closer to zero the x velocity (defn- get-x-vel-from-paddle-bounce [ball-pos paddle-pos] (let [half-paddle (/ (:width paddle-size) 2) cbx (get-center-x ball-pos ball-size) cpx (get-center-x paddle-pos paddle-size) distance (- cbx cpx) ratio (/ distance half-paddle)] (* 1.5 base-vel ratio))) (defn- setup-next-level! [level] (let [brick-data (levels/get-level-data level)] (when brick-data React 's CSSTransitionGroup to kick in , causing the bricks (.setTimeout js/window #(reset! bricks brick-data) 100) (reset! phase :countdown)))) (defmulti init-phase! identity) (defmethod init-phase! :countdown [_] (reset! ball-pos starting-ball-pos) (reset! countdown-duration total-countdown-duration)) (defmethod init-phase! :gameplay [_] (reset! ball-pos starting-ball-pos) (reset! ball-vel starting-ball-vel)) (add-watch phase :phase (fn [_ _ _ new-phase] (when new-phase (init-phase! new-phase)))) (defmulti update-phase! (fn [delta phase] phase)) (defmethod update-phase! :countdown [delta _] (swap! countdown-duration - delta) (when (<= @countdown-duration 0) (reset! phase :gameplay))) (defmethod update-phase! :gameplay [delta _] (let [old-pos @ball-pos new-pos (move-ball delta old-pos @ball-vel) pad-pos @paddle-pos [collided-type collided-object] (get-collision new-pos @bricks walls ceiling pad-pos)] (case collided-type :wall (flip! ball-vel :x) :ceiling (flip! ball-vel :y) :paddle (do (flip! ball-vel :y) (swap! ball-vel assoc :x (get-x-vel-from-paddle-bounce new-pos pad-pos))) :brick (do (flip! ball-vel (get-flip-direction new-pos collided-object)) (swap! score + 100) (swap! bricks disj collided-object) (when (zero? (count @bricks)) (let [next-level (swap! level inc)] (when-not (setup-next-level! next-level) (@next-scene! :win))))) :none (if (beyond-board? new-pos) (let [remaining-lives (swap! lives dec)] (if (<= remaining-lives 0) (@next-scene! :game-over) (reset! phase :countdown))) (reset! ball-pos new-pos))))) (defn- update! [ts] (when @running (let [delta (- ts (or @last-ts ts))] (reset! last-ts ts) (update-phase! delta @phase)) (. js/window (requestAnimationFrame update!)))) (defn- listen-to-input-moves [] (go (while @running (let [input-x (<! input/movement)] (swap! paddle-pos assoc :x input-x))))) (defn- init! [] (reset! lives 3) (reset! score 0) (reset! level 0) (reset! bricks #{}) (setup-next-level! 0) (reset! last-ts nil) (reset! running true)) (defn start! [set-next-scene!] (reset! next-scene! set-next-scene!) (init!) (listen-to-input-moves) (. js/window (requestAnimationFrame update!))) (defn stop! [] (reset! running false))
13bbd01c0627377245e5eee54342fbe1ea557aed65fb47b5e9ed33d1567877d3
morpheusgraphql/morpheus-graphql
ClientConnectionStore.hs
{-# LANGUAGE DeriveAnyClass #-} # LANGUAGE DeriveGeneric # # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # {-# LANGUAGE GADTs #-} # LANGUAGE MultiParamTypeClasses # # LANGUAGE NamedFieldPuns # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE RecordWildCards # # LANGUAGE StandaloneDeriving # # LANGUAGE TypeFamilies # # LANGUAGE NoImplicitPrelude # module Data.Morpheus.Subscriptions.ClientConnectionStore ( SessionID (..), ClientConnectionStore, ClientConnection, Updates (..), startSession, endSession, empty, insertConnection, delete, publish, toList, connectionSessionIds, storedChannels, storedSessions, ) where import Data.ByteString.Lazy.Char8 (ByteString) import qualified Data.HashMap.Lazy as HM import Data.Morpheus.App.Internal.Resolving ( EventHandler (..), ) import Data.Morpheus.Internal.Utils ( Empty (..), KeyOf (..), ) import Data.Morpheus.Subscriptions.Apollo ( toApolloResponse, ) import Data.Morpheus.Subscriptions.Event (Event (..)) import Data.Morpheus.Types.IO (GQLResponse) import Data.UUID (UUID) import Relude hiding ( ByteString, Show, empty, show, toList, ) import Prelude (Show (..)) data SessionID = SessionID { cid :: UUID, sid :: Text } deriving (Show, Generic, Eq, Hashable) data ClientConnection (m :: Type -> Type) = ClientConnection { connectionId :: UUID, connectionCallback :: ByteString -> m (), -- one connection can have multiple subscription session connectionSessionIds :: [Text] } addConnectionSession :: Text -> ClientConnection m -> ClientConnection m addConnectionSession sid ClientConnection {..} = ClientConnection {connectionSessionIds = connectionSessionIds <> [sid], ..} data ClientSession e (m :: Type -> Type) = ClientSession { sessionChannel :: Channel e, sessionCallback :: e -> m ByteString } instance Show (ClientSession e m) where show ClientSession {} = "ClientSession" instance Show (ClientConnection m) where show ClientConnection {connectionId, connectionSessionIds} = "ClientConnection { id = " <> show connectionId <> ", sessions = " <> show connectionSessionIds <> " }" mapAt :: (Eq k, Hashable k) => c -> (a -> c) -> k -> HashMap k a -> c mapAt fallback f key = maybe fallback f . HM.lookup key publish :: ( Monad m, Eq channel, Hashable channel, Show channel ) => Event channel content -> ClientConnectionStore (Event channel content) m -> m () publish event@Event {channels} ClientConnectionStore {activeChannels, clientConnections, clientSessions} = traverse_ onChannel channels where onChannel ch = mapAt (pure ()) sendBy ch activeChannels sendBy = traverse_ sendByChannel sendByChannel sid = mapAt (pure ()) sendMessage sid clientSessions where sendMessage ClientSession {sessionCallback} = sessionCallback event >>= upd upd = mapAt cantFindConnection connectionCallback (cid sid) clientConnections cantFindConnection _ = pure () newtype Updates e (m :: Type -> Type) = Updates { _runUpdate :: ClientConnectionStore e m -> ClientConnectionStore e m } endSession :: ( Eq ch, Hashable ch ) => SessionID -> Updates (Event ch con) m endSession sessionId@SessionID {sid, cid} = Updates endSub where endSub :: ( Eq ch, Hashable ch ) => ClientConnectionStore (Event ch con) m -> ClientConnectionStore (Event ch con) m endSub ClientConnectionStore {..} = ClientConnectionStore { clientConnections = HM.adjust (removeSessionId sid) cid clientConnections, clientSessions = HM.delete sessionId clientSessions, activeChannels = removeActiveChannel sessionId activeChannels } removeSessionId :: Text -> ClientConnection m -> ClientConnection m removeSessionId sid conn = conn { connectionSessionIds = filter (/= sid) (connectionSessionIds conn) } startSession :: ( Monad m, Eq (Channel e), Hashable (Channel e) ) => Channel e -> (e -> m GQLResponse) -> SessionID -> Updates e m startSession sessionChannel resolver sessionId@SessionID {cid, sid} = Updates startSub where startSub ClientConnectionStore {..} = ClientConnectionStore { clientSessions = HM.insert sessionId ClientSession { sessionChannel, sessionCallback = fmap (toApolloResponse sid) . resolver } clientSessions, clientConnections = HM.adjust (addConnectionSession sid) cid clientConnections, activeChannels = addActiveChannel sessionChannel sessionId activeChannels } addActiveChannel :: (Eq ch, Hashable ch) => ch -> SessionID -> HashMap ch [SessionID] -> HashMap ch [SessionID] addActiveChannel sessionChannel sessionId = HM.alter update sessionChannel where update Nothing = Just [sessionId] update (Just ids) = Just (ids <> [sessionId]) removeActiveChannel :: (Eq ch, Hashable ch) => SessionID -> HashMap ch [SessionID] -> HashMap ch [SessionID] removeActiveChannel sessionId = fmap update where update = filter (/= sessionId) -- stores active client connections -- every registered client has ID -- when client connection is closed client(including all its subscriptions) can By removed By its ID data ClientConnectionStore e (m :: Type -> Type) where ClientConnectionStore :: { clientConnections :: HashMap UUID (ClientConnection m), clientSessions :: HashMap SessionID (ClientSession (Event channel content) m), activeChannels :: HashMap channel [SessionID] } -> ClientConnectionStore (Event channel content) m deriving instance Show e => Show (ClientConnectionStore (Event e c) m) type StoreMap e m = ClientConnectionStore e m -> ClientConnectionStore e m toList :: ClientConnectionStore (Event channel content) m -> [(UUID, ClientConnection m)] toList = HM.toList . clientConnections storedSessions :: ClientConnectionStore (Event channel content) m -> [(SessionID, ClientSession (Event channel content) m)] storedSessions = HM.toList . clientSessions storedChannels :: ClientConnectionStore (Event channel content) m -> [(channel, [SessionID])] storedChannels = HM.toList . activeChannels instance KeyOf UUID (ClientConnection m) where keyOf = connectionId instance Empty (ClientConnectionStore (Event ch con) m) where empty = ClientConnectionStore empty HM.empty HM.empty mapConnections :: ( HashMap UUID (ClientConnection m) -> HashMap UUID (ClientConnection m) ) -> ClientConnectionStore e m -> ClientConnectionStore e m mapConnections f ClientConnectionStore {..} = ClientConnectionStore { clientConnections = f clientConnections, .. } -- returns original store, if connection with same id already exist insertConnection :: UUID -> (ByteString -> m ()) -> StoreMap e m insertConnection connectionId connectionCallback = mapConnections (HM.insertWith (const id) connectionId c) where c = ClientConnection { connectionId, connectionCallback, connectionSessionIds = empty } delete :: UUID -> StoreMap e m delete key = mapConnections (HM.delete key)
null
https://raw.githubusercontent.com/morpheusgraphql/morpheus-graphql/f9684d1451fd4ee3aabdb821424fd352003a3982/morpheus-graphql-subscriptions/src/Data/Morpheus/Subscriptions/ClientConnectionStore.hs
haskell
# LANGUAGE DeriveAnyClass # # LANGUAGE GADTs # # LANGUAGE OverloadedStrings # one connection can have multiple subscription session stores active client connections every registered client has ID when client connection is closed client(including all its subscriptions) can By removed By its ID returns original store, if connection with same id already exist
# LANGUAGE DeriveGeneric # # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE MultiParamTypeClasses # # LANGUAGE NamedFieldPuns # # LANGUAGE RecordWildCards # # LANGUAGE StandaloneDeriving # # LANGUAGE TypeFamilies # # LANGUAGE NoImplicitPrelude # module Data.Morpheus.Subscriptions.ClientConnectionStore ( SessionID (..), ClientConnectionStore, ClientConnection, Updates (..), startSession, endSession, empty, insertConnection, delete, publish, toList, connectionSessionIds, storedChannels, storedSessions, ) where import Data.ByteString.Lazy.Char8 (ByteString) import qualified Data.HashMap.Lazy as HM import Data.Morpheus.App.Internal.Resolving ( EventHandler (..), ) import Data.Morpheus.Internal.Utils ( Empty (..), KeyOf (..), ) import Data.Morpheus.Subscriptions.Apollo ( toApolloResponse, ) import Data.Morpheus.Subscriptions.Event (Event (..)) import Data.Morpheus.Types.IO (GQLResponse) import Data.UUID (UUID) import Relude hiding ( ByteString, Show, empty, show, toList, ) import Prelude (Show (..)) data SessionID = SessionID { cid :: UUID, sid :: Text } deriving (Show, Generic, Eq, Hashable) data ClientConnection (m :: Type -> Type) = ClientConnection { connectionId :: UUID, connectionCallback :: ByteString -> m (), connectionSessionIds :: [Text] } addConnectionSession :: Text -> ClientConnection m -> ClientConnection m addConnectionSession sid ClientConnection {..} = ClientConnection {connectionSessionIds = connectionSessionIds <> [sid], ..} data ClientSession e (m :: Type -> Type) = ClientSession { sessionChannel :: Channel e, sessionCallback :: e -> m ByteString } instance Show (ClientSession e m) where show ClientSession {} = "ClientSession" instance Show (ClientConnection m) where show ClientConnection {connectionId, connectionSessionIds} = "ClientConnection { id = " <> show connectionId <> ", sessions = " <> show connectionSessionIds <> " }" mapAt :: (Eq k, Hashable k) => c -> (a -> c) -> k -> HashMap k a -> c mapAt fallback f key = maybe fallback f . HM.lookup key publish :: ( Monad m, Eq channel, Hashable channel, Show channel ) => Event channel content -> ClientConnectionStore (Event channel content) m -> m () publish event@Event {channels} ClientConnectionStore {activeChannels, clientConnections, clientSessions} = traverse_ onChannel channels where onChannel ch = mapAt (pure ()) sendBy ch activeChannels sendBy = traverse_ sendByChannel sendByChannel sid = mapAt (pure ()) sendMessage sid clientSessions where sendMessage ClientSession {sessionCallback} = sessionCallback event >>= upd upd = mapAt cantFindConnection connectionCallback (cid sid) clientConnections cantFindConnection _ = pure () newtype Updates e (m :: Type -> Type) = Updates { _runUpdate :: ClientConnectionStore e m -> ClientConnectionStore e m } endSession :: ( Eq ch, Hashable ch ) => SessionID -> Updates (Event ch con) m endSession sessionId@SessionID {sid, cid} = Updates endSub where endSub :: ( Eq ch, Hashable ch ) => ClientConnectionStore (Event ch con) m -> ClientConnectionStore (Event ch con) m endSub ClientConnectionStore {..} = ClientConnectionStore { clientConnections = HM.adjust (removeSessionId sid) cid clientConnections, clientSessions = HM.delete sessionId clientSessions, activeChannels = removeActiveChannel sessionId activeChannels } removeSessionId :: Text -> ClientConnection m -> ClientConnection m removeSessionId sid conn = conn { connectionSessionIds = filter (/= sid) (connectionSessionIds conn) } startSession :: ( Monad m, Eq (Channel e), Hashable (Channel e) ) => Channel e -> (e -> m GQLResponse) -> SessionID -> Updates e m startSession sessionChannel resolver sessionId@SessionID {cid, sid} = Updates startSub where startSub ClientConnectionStore {..} = ClientConnectionStore { clientSessions = HM.insert sessionId ClientSession { sessionChannel, sessionCallback = fmap (toApolloResponse sid) . resolver } clientSessions, clientConnections = HM.adjust (addConnectionSession sid) cid clientConnections, activeChannels = addActiveChannel sessionChannel sessionId activeChannels } addActiveChannel :: (Eq ch, Hashable ch) => ch -> SessionID -> HashMap ch [SessionID] -> HashMap ch [SessionID] addActiveChannel sessionChannel sessionId = HM.alter update sessionChannel where update Nothing = Just [sessionId] update (Just ids) = Just (ids <> [sessionId]) removeActiveChannel :: (Eq ch, Hashable ch) => SessionID -> HashMap ch [SessionID] -> HashMap ch [SessionID] removeActiveChannel sessionId = fmap update where update = filter (/= sessionId) data ClientConnectionStore e (m :: Type -> Type) where ClientConnectionStore :: { clientConnections :: HashMap UUID (ClientConnection m), clientSessions :: HashMap SessionID (ClientSession (Event channel content) m), activeChannels :: HashMap channel [SessionID] } -> ClientConnectionStore (Event channel content) m deriving instance Show e => Show (ClientConnectionStore (Event e c) m) type StoreMap e m = ClientConnectionStore e m -> ClientConnectionStore e m toList :: ClientConnectionStore (Event channel content) m -> [(UUID, ClientConnection m)] toList = HM.toList . clientConnections storedSessions :: ClientConnectionStore (Event channel content) m -> [(SessionID, ClientSession (Event channel content) m)] storedSessions = HM.toList . clientSessions storedChannels :: ClientConnectionStore (Event channel content) m -> [(channel, [SessionID])] storedChannels = HM.toList . activeChannels instance KeyOf UUID (ClientConnection m) where keyOf = connectionId instance Empty (ClientConnectionStore (Event ch con) m) where empty = ClientConnectionStore empty HM.empty HM.empty mapConnections :: ( HashMap UUID (ClientConnection m) -> HashMap UUID (ClientConnection m) ) -> ClientConnectionStore e m -> ClientConnectionStore e m mapConnections f ClientConnectionStore {..} = ClientConnectionStore { clientConnections = f clientConnections, .. } insertConnection :: UUID -> (ByteString -> m ()) -> StoreMap e m insertConnection connectionId connectionCallback = mapConnections (HM.insertWith (const id) connectionId c) where c = ClientConnection { connectionId, connectionCallback, connectionSessionIds = empty } delete :: UUID -> StoreMap e m delete key = mapConnections (HM.delete key)
fd71129e114da083aa56c2213a375f34744074986a929886be7f2837c169e3ef
malob/prefmanager
Types.hs
module Defaults.Types where import Patience.Map (Delta) import Text.XML.Plist (PlObject) | Name of a domain , e.g. , @NSGlobalDomain@ , @com.apple.finder@ , etc . newtype DomainName = DomainName Text deriving (Eq, Ord, Show) type Key = String -- | Representation of the settings of a domain. newtype Domain = Domain (Map Key PlObject) deriving (Eq, Ord, Show) -- | Map of domains. newtype Domains = Domains (Map DomainName Domain) deriving (Eq, Ord, Show) -- | Map representing the change of the values of keys of a domain. newtype DomainDiff = DomainDiff (Map Key (Delta PlObject)) deriving (Eq, Ord, Show)
null
https://raw.githubusercontent.com/malob/prefmanager/bda3ea9b1963daa56bba698f61b957c131e7a260/src/Defaults/Types.hs
haskell
| Representation of the settings of a domain. | Map of domains. | Map representing the change of the values of keys of a domain.
module Defaults.Types where import Patience.Map (Delta) import Text.XML.Plist (PlObject) | Name of a domain , e.g. , @NSGlobalDomain@ , @com.apple.finder@ , etc . newtype DomainName = DomainName Text deriving (Eq, Ord, Show) type Key = String newtype Domain = Domain (Map Key PlObject) deriving (Eq, Ord, Show) newtype Domains = Domains (Map DomainName Domain) deriving (Eq, Ord, Show) newtype DomainDiff = DomainDiff (Map Key (Delta PlObject)) deriving (Eq, Ord, Show)
79b7f69a2640fcef7afa6303d2e4a5431e06d4f288ba1423f1b2ada634c9aa21
ledyba/bf2sat
SAT.hs
module Brainfuck2Sat.SAT (Time(..), Component(..), Fml(..), States, gen) where import Brainfuck2Sat.Parser (Tree(..), Source(..)) import Brainfuck2Sat.Util (calcBitLength, toBitList, sortOn, showIO) import Data.List (groupBy) import Control.Applicative ((<$>)) import Data.Hashable (Hashable, hash, hashWithSalt) import qualified Control.Arrow as CA -------------------------------------------------------------------------------- newtype Time = Time {getTime :: Int} deriving (Eq,Ord) data Component = PC Time Int | IC Time Int | InTape Int Int | MC Time Int | MidTape Time Int Int | OC Time Int | OutTape Int Int | Tmp [Int] deriving (Eq,Show,Read,Ord) data Fml a = And [Fml a] | Or [Fml a] | Not (Fml a) | Pred a deriving (Show, Read, Eq) type States = Fml Component type PC = Int instance Hashable Time where hashWithSalt s k = s + hash (getTime k) instance Hashable Component where hashWithSalt s (PC t i) = s + hash t + hash i + 98540371 hashWithSalt s (IC t i) = s + hash t + hash i + 48397042 hashWithSalt s (MC t i) = s + hash t + hash i + 18751233 hashWithSalt s (OC t i) = s + hash t + hash i + 87510674 hashWithSalt s (InTape t i) = s + hash t + hash i + 210535 hashWithSalt s (OutTape t i) = s + hash t + hash i + 12345326 hashWithSalt s (MidTape t i j) = s + hash t + hash i + hash j + 102345527 hashWithSalt s (Tmp k) = s + hash k + 30545214358 instance Show Time where showsPrec d t = showsPrec d (getTime t) instance Read Time where readsPrec d s = fmap (CA.first Time) (readsPrec d s) prod :: [a] -> [a] -> [(a,a)] prod a b = concat $ fmap ( \it1 -> fmap (\it2 -> (it1,it2) ) b ) a -------------------------------------------------------------------------------- gen :: Source -> States gen src = And [ genInitState src ,genMiddleState src ,genLastState src ] t0 :: Time t0 = Time 0 lastTime :: Source -> Time lastTime src = Time (getSimStep src - 1) -------------------------------------------------------------------------------- incTime :: Time -> Time incTime t = Time $ 1 + getTime t -------------------------------------------------------------------------------- makeConst :: (Int -> Component) -> Int -> Int -> Fml Component makeConst type_ bitLength value = And $ fmap (\(bi,b) -> if b then Pred $ type_ bi else Not (Pred (type_ bi))) (zip [0..] (toBitList bitLength value)) isConst :: (Int -> Component) -> Int -> Int -> Fml Component isConst = makeConst makeEqP :: Component -> Component -> Fml Component makeEqP from_ to_ = makeEqFml (Pred from_) (Pred to_) makeEqFml :: Fml Component -> Fml Component -> Fml Component makeEqFml from_ to_ = Or [And[from_, to_], And[Not from_, Not to_]] notEqP :: Component -> Component -> Fml Component notEqP from_ to_ = notEqFml (Pred from_) (Pred to_) notEqFml :: Fml Component -> Fml Component -> Fml Component notEqFml from_ to_ = Or [And[from_, Not to_], And[Not from_, to_]] makeEq :: (Int -> Component) -> (Int -> Component) -> Int -> Fml Component makeEq from_ to_ bitLength = And $ (\bidx -> makeEqP (from_ bidx) (to_ bidx)) <$> [0..bitLength-1] isZero :: (Int -> Component) -> Int -> Fml Component isZero type_ bitLength = And $ Not . Pred . type_ <$> [0..bitLength-1] notZero :: (Int -> Component) -> Int -> Fml Component notZero type_ bitLength = Or $ Pred . type_ <$> [0..bitLength-1] genInitState :: Source -> States genInitState src = And [pc, ic, it, mc, oc, mt] where inTape = getInTape src tapeLenBits = getAddrBits src outLenBits = getOutAddrBits src valueBits = getValueBits src tapeLen = 2 ^ tapeLenBits inLenBits = calcBitLength (length inTape) progLen = length $ getAST src progLenBits = calcBitLength progLen pc = isZero (PC t0) progLenBits ic = isZero (IC t0) inLenBits mc = isZero (MC t0) tapeLenBits oc = isZero (OC t0) outLenBits it = And $ zip [0..] inTape >>= (\(idx, v) -> if v >= 0 then [makeConst (InTape idx) valueBits v] else []) mt = And $ (\idx -> isZero (MidTape t0 idx) valueBits) <$> [0..(tapeLen-1)] changePC :: (Int,Int) -> Time -> Time -> [Int] -> States changePC (progLen,progLenBits) from_ to_ addr_ = Or [ And [isConst (PC from_) progLenBits progLen, makeEq (PC from_) (PC to_) progLenBits], And [Not $ isConst (PC from_) progLenBits progLen, makeInc (PC from_) (PC to_) progLenBits addr_] ] makeInc :: (Int -> Component) -> (Int -> Component) -> Int -> [Int] -> Fml Component makeInc from_ to_ bitLength addr = And $ And[notEqP (from_ 0) (to_ 0), makeEqP (from_ 0) (Tmp (0:addr))] :((\bidx -> Or [ And [ Pred $ Tmp ((bidx-1):addr), notEqP (from_ bidx) (to_ bidx), makeEqP (from_ bidx) (Tmp $ bidx:addr)], And [Not $ Pred $ Tmp ((bidx-1):addr), makeEqP (from_ bidx) (to_ bidx), Not $ Pred $ Tmp $ bidx:addr] ]) <$> [1..(bitLength-1)]) makeDec :: (Int -> Component) -> (Int -> Component) -> Int -> [Int] -> Fml Component makeDec from_ to_ bitLength addr = And $ And[notEqP (from_ 0) (to_ 0), notEqP (from_ 0) (Tmp (0:addr))] :((\bidx -> Or [ And [ Pred $ Tmp ((bidx-1):addr), notEqP (from_ bidx) (to_ bidx), notEqP (from_ bidx) (Tmp $ bidx:addr)], And [Not $ Pred $ Tmp ((bidx-1):addr), makeEqP (from_ bidx) (to_ bidx), Not $ Pred $ Tmp $ bidx:addr] ]) <$> [1..bitLength-1]) keepMidTape :: Int -> Int -> Time -> Time -> States keepMidTape valueBits tapeLen from to = And $ (\mc -> makeEq (MidTape from mc) (MidTape to mc) valueBits) <$> [0..(tapeLen-1)] keepMidTapeElse :: Int -> Int -> Time -> Time -> Int -> States keepMidTapeElse valueBits tapeLen from to notUsed = And $ (\mc -> makeEq (MidTape from mc) (MidTape to mc) valueBits) <$> filter (/= notUsed) [0..(tapeLen-1)] incMidTape :: Int -> (Int,Int) -> Time -> Time -> [Int] -> States incMidTape valueBits (tapeLen,tapeLenBits) from to addr = Or $ fmap each [0..tapeLen-1] where each idx = And [isConst (MC from) tapeLenBits idx,makeInc (MidTape from idx) (MidTape to idx) valueBits addr, keepMidTapeElse valueBits tapeLen from to idx] decMidTape :: Int -> (Int,Int) -> Time -> Time -> [Int] -> States decMidTape valueBits (tapeLen,tapeLenBits) from to addr = Or $ fmap each [0..tapeLen-1] where each idx = And [isConst (MC from) tapeLenBits idx,makeDec (MidTape from idx) (MidTape to idx) valueBits addr, keepMidTapeElse valueBits tapeLen from to idx] -- keepSC :: Int -> (Time->Int->Component) -> Time -> Time -> States keepSC bitLength cons from to = makeEq (cons from) (cons to) bitLength keepOC :: Int -> Time -> Time -> States keepOC outLenBits = keepSC outLenBits OC keepIC :: Int -> Time -> Time -> States keepIC inLenBits = keepSC inLenBits IC keepMC :: Int -> Time -> Time -> States keepMC tapeLenBits = keepSC tapeLenBits MC keepPC :: Int -> Time -> Time -> States keepPC pcLenBits = keepSC pcLenBits PC incIC :: Int -> Time -> Time -> [Int] -> States incIC inLenBits from to = makeInc (IC from) (IC to) inLenBits incOC :: Int -> Time -> Time -> [Int] -> States incOC outLenBits from to = makeInc (OC from) (OC to) outLenBits incMC :: Int -> Time -> Time -> [Int] -> States incMC tapeLenBits from to = makeInc (MC from) (MC to) tapeLenBits decMC :: Int -> Time -> Time -> [Int] -> States decMC tapeLenBits from to = makeDec (MC from) (MC to) tapeLenBits readInput :: (Int,Int) -> (Int,Int) -> Int -> Time -> Time -> States readInput (inLen,inLenBits) (tapeLen,tapeLenBits) valueBits from to = Or $ fmap (\(mi,ii) -> And [isConst (MC from) tapeLenBits mi, isConst (IC from) inLenBits ii, keepMidTapeElse valueBits tapeLen from to mi, makeEq (MidTape to mi) (InTape ii) valueBits]) (prod [0..(tapeLen-1)] [0..(inLen-1)]) printOutput :: (Int,Int) -> (Int,Int) -> Int -> Time -> States printOutput (outLen,outLenBits) (tapeLen,tapeLenBits) valueBits from = Or $ fmap (\(mi,oi) -> And [isConst (MC from) tapeLenBits mi, isConst (OC from) outLenBits oi, makeEq (MidTape from mi) (OutTape oi) valueBits]) (prod [0..(tapeLen-1)] [0..(outLen-1)]) acceptRule :: Source -> Time -> States acceptRule src t = And [nowPc, keepedPC, keepedMem, keepedMC, keepedOC, keepedIC] where inLen = length (getInTape src) inLenBits = calcBitLength inLen progLen = length (getAST src) progLenBits = calcBitLength progLen tapeLenBits = getAddrBits src tapeLen = 2 ^ tapeLenBits outLenBits = getOutAddrBits src valueBits = getValueBits src from = t to = incTime t nowPc = isConst (PC t) progLenBits progLen keepedPC = keepPC progLenBits from to keepedMem = keepMidTape valueBits tapeLen from to keepedOC = keepOC outLenBits from to keepedMC = keepMC tapeLenBits from to keepedIC = keepIC inLenBits from to genOpRule :: Source -> Time -> [PC] -> Tree -> [Int] -> States genOpRule src t pcs op addr = case op of PtInc -> And [nowPc, incPCp, keepedMem, keepedOC, keepedIC, incMC tapeLenBits from to (0:addr)] PtDec -> And [nowPc, incPCp, keepedMem, keepedOC, keepedIC, decMC tapeLenBits from to (0:addr)] ValInc -> And [nowPc, incPCp, keepedMC, keepedOC, keepedIC, incMidTape valueBits (tapeLen,tapeLenBits) from to (0:addr)] ValDec -> And [nowPc, incPCp, keepedMC, keepedOC, keepedIC, decMidTape valueBits (tapeLen,tapeLenBits) from to (0:addr)] PutC -> And [nowPc, incPCp, keepedMem, keepedMC, keepedIC, printOutput (outLen,outLenBits) (tapeLen,tapeLenBits) valueBits from, incOC outLenBits from to (0:addr)] GetC -> And [nowPc, incPCp, keepedMC, keepedOC, readInput (inLen,inLenBits) (tapeLen,tapeLenBits) valueBits from to, incIC inLenBits from to (0:addr)] LoopBegin next -> And [nowPc, keepedMem, keepedMC, keepedOC, keepedIC, Or $ map (\mc -> And [isConst (MC t) tapeLenBits mc, Or [And[ isZero (MidTape from mc) valueBits, makeConst (PC to) progLenBits next], And[notZero (MidTape from mc) valueBits, incPCp]]]) [0..tapeLen-1]] LoopEnd next -> And [nowPc, keepedMem, keepedMC, keepedOC, keepedIC, Or $ map (\mc -> And [isConst (MC t) tapeLenBits mc, Or [And[notZero (MidTape from mc) valueBits, makeConst (PC to) progLenBits next], And[ isZero (MidTape from mc) valueBits, incPCp]]]) [0..tapeLen-1]] where inLen = length (getInTape src) inLenBits = calcBitLength inLen progLen = length (getAST src) progLenBits = calcBitLength progLen tapeLenBits = getAddrBits src tapeLen = 2 ^ tapeLenBits outLenBits = getOutAddrBits src outLen = 2 ^ outLenBits valueBits = getValueBits src from = t to = incTime t nowPc = Or $ fmap (isConst (PC t) progLenBits) pcs incPCp = changePC (progLen,progLenBits) from to (1:addr) keepedMem = keepMidTape valueBits tapeLen from to keepedOC = keepOC outLenBits from to keepedMC = keepMC tapeLenBits from to keepedIC = keepIC inLenBits from to genStepRules :: Time -> Source -> States genStepRules t src = Or $ acceptRule src t :fmap (\(pc,op) -> genOpRule src t pc op [getTime t,0]) grouped where grouped = fmap (\lst -> (fmap fst lst,snd $ head lst)) $ groupBy (\(_,op1) (_,op2) -> op1 == op2) $ sortOn (\(_,op)->op) (zip [0..] (getAST src)) genMiddleState :: Source -> States genMiddleState src = And $ fmap ((\t -> genStepRules t src) . Time) [(getTime t0)..(getTime (lastTime src) - 1)] -------------------------------------------------------------------------------- zeroFillOut :: Int -> Int -> States zeroFillOut outLenBits idx = isZero (OutTape idx) outLenBits greaterThanOC :: (Int,Int) -> Time -> Int -> States greaterThanOC (outLen, outLenBits) t idx = Or $ isConst (OC t) outLenBits <$> [idx+1..(outLen-1)] flushOC :: (Int,Int) -> Time -> States flushOC (outLen, outLenBits) t = And $ fmap (\ idx -> Or [greaterThanOC (outLen,outLenBits) t idx, zeroFillOut outLenBits idx]) [0..outLen-1] genLastState :: Source -> States genLastState src = And [isConst (PC $ lastTime src) progLenBits progLen, flushOC (outLen,outLenBits) (lastTime src)] where outLenBits = getOutAddrBits src outLen = 2 ^ outLenBits progLen = length (getAST src) progLenBits = calcBitLength progLen
null
https://raw.githubusercontent.com/ledyba/bf2sat/5ffdfbdf9b15d7d01bf00a6b475b8fccdc40b5d3/lib/Brainfuck2Sat/SAT.hs
haskell
------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------
module Brainfuck2Sat.SAT (Time(..), Component(..), Fml(..), States, gen) where import Brainfuck2Sat.Parser (Tree(..), Source(..)) import Brainfuck2Sat.Util (calcBitLength, toBitList, sortOn, showIO) import Data.List (groupBy) import Control.Applicative ((<$>)) import Data.Hashable (Hashable, hash, hashWithSalt) import qualified Control.Arrow as CA newtype Time = Time {getTime :: Int} deriving (Eq,Ord) data Component = PC Time Int | IC Time Int | InTape Int Int | MC Time Int | MidTape Time Int Int | OC Time Int | OutTape Int Int | Tmp [Int] deriving (Eq,Show,Read,Ord) data Fml a = And [Fml a] | Or [Fml a] | Not (Fml a) | Pred a deriving (Show, Read, Eq) type States = Fml Component type PC = Int instance Hashable Time where hashWithSalt s k = s + hash (getTime k) instance Hashable Component where hashWithSalt s (PC t i) = s + hash t + hash i + 98540371 hashWithSalt s (IC t i) = s + hash t + hash i + 48397042 hashWithSalt s (MC t i) = s + hash t + hash i + 18751233 hashWithSalt s (OC t i) = s + hash t + hash i + 87510674 hashWithSalt s (InTape t i) = s + hash t + hash i + 210535 hashWithSalt s (OutTape t i) = s + hash t + hash i + 12345326 hashWithSalt s (MidTape t i j) = s + hash t + hash i + hash j + 102345527 hashWithSalt s (Tmp k) = s + hash k + 30545214358 instance Show Time where showsPrec d t = showsPrec d (getTime t) instance Read Time where readsPrec d s = fmap (CA.first Time) (readsPrec d s) prod :: [a] -> [a] -> [(a,a)] prod a b = concat $ fmap ( \it1 -> fmap (\it2 -> (it1,it2) ) b ) a gen :: Source -> States gen src = And [ genInitState src ,genMiddleState src ,genLastState src ] t0 :: Time t0 = Time 0 lastTime :: Source -> Time lastTime src = Time (getSimStep src - 1) incTime :: Time -> Time incTime t = Time $ 1 + getTime t makeConst :: (Int -> Component) -> Int -> Int -> Fml Component makeConst type_ bitLength value = And $ fmap (\(bi,b) -> if b then Pred $ type_ bi else Not (Pred (type_ bi))) (zip [0..] (toBitList bitLength value)) isConst :: (Int -> Component) -> Int -> Int -> Fml Component isConst = makeConst makeEqP :: Component -> Component -> Fml Component makeEqP from_ to_ = makeEqFml (Pred from_) (Pred to_) makeEqFml :: Fml Component -> Fml Component -> Fml Component makeEqFml from_ to_ = Or [And[from_, to_], And[Not from_, Not to_]] notEqP :: Component -> Component -> Fml Component notEqP from_ to_ = notEqFml (Pred from_) (Pred to_) notEqFml :: Fml Component -> Fml Component -> Fml Component notEqFml from_ to_ = Or [And[from_, Not to_], And[Not from_, to_]] makeEq :: (Int -> Component) -> (Int -> Component) -> Int -> Fml Component makeEq from_ to_ bitLength = And $ (\bidx -> makeEqP (from_ bidx) (to_ bidx)) <$> [0..bitLength-1] isZero :: (Int -> Component) -> Int -> Fml Component isZero type_ bitLength = And $ Not . Pred . type_ <$> [0..bitLength-1] notZero :: (Int -> Component) -> Int -> Fml Component notZero type_ bitLength = Or $ Pred . type_ <$> [0..bitLength-1] genInitState :: Source -> States genInitState src = And [pc, ic, it, mc, oc, mt] where inTape = getInTape src tapeLenBits = getAddrBits src outLenBits = getOutAddrBits src valueBits = getValueBits src tapeLen = 2 ^ tapeLenBits inLenBits = calcBitLength (length inTape) progLen = length $ getAST src progLenBits = calcBitLength progLen pc = isZero (PC t0) progLenBits ic = isZero (IC t0) inLenBits mc = isZero (MC t0) tapeLenBits oc = isZero (OC t0) outLenBits it = And $ zip [0..] inTape >>= (\(idx, v) -> if v >= 0 then [makeConst (InTape idx) valueBits v] else []) mt = And $ (\idx -> isZero (MidTape t0 idx) valueBits) <$> [0..(tapeLen-1)] changePC :: (Int,Int) -> Time -> Time -> [Int] -> States changePC (progLen,progLenBits) from_ to_ addr_ = Or [ And [isConst (PC from_) progLenBits progLen, makeEq (PC from_) (PC to_) progLenBits], And [Not $ isConst (PC from_) progLenBits progLen, makeInc (PC from_) (PC to_) progLenBits addr_] ] makeInc :: (Int -> Component) -> (Int -> Component) -> Int -> [Int] -> Fml Component makeInc from_ to_ bitLength addr = And $ And[notEqP (from_ 0) (to_ 0), makeEqP (from_ 0) (Tmp (0:addr))] :((\bidx -> Or [ And [ Pred $ Tmp ((bidx-1):addr), notEqP (from_ bidx) (to_ bidx), makeEqP (from_ bidx) (Tmp $ bidx:addr)], And [Not $ Pred $ Tmp ((bidx-1):addr), makeEqP (from_ bidx) (to_ bidx), Not $ Pred $ Tmp $ bidx:addr] ]) <$> [1..(bitLength-1)]) makeDec :: (Int -> Component) -> (Int -> Component) -> Int -> [Int] -> Fml Component makeDec from_ to_ bitLength addr = And $ And[notEqP (from_ 0) (to_ 0), notEqP (from_ 0) (Tmp (0:addr))] :((\bidx -> Or [ And [ Pred $ Tmp ((bidx-1):addr), notEqP (from_ bidx) (to_ bidx), notEqP (from_ bidx) (Tmp $ bidx:addr)], And [Not $ Pred $ Tmp ((bidx-1):addr), makeEqP (from_ bidx) (to_ bidx), Not $ Pred $ Tmp $ bidx:addr] ]) <$> [1..bitLength-1]) keepMidTape :: Int -> Int -> Time -> Time -> States keepMidTape valueBits tapeLen from to = And $ (\mc -> makeEq (MidTape from mc) (MidTape to mc) valueBits) <$> [0..(tapeLen-1)] keepMidTapeElse :: Int -> Int -> Time -> Time -> Int -> States keepMidTapeElse valueBits tapeLen from to notUsed = And $ (\mc -> makeEq (MidTape from mc) (MidTape to mc) valueBits) <$> filter (/= notUsed) [0..(tapeLen-1)] incMidTape :: Int -> (Int,Int) -> Time -> Time -> [Int] -> States incMidTape valueBits (tapeLen,tapeLenBits) from to addr = Or $ fmap each [0..tapeLen-1] where each idx = And [isConst (MC from) tapeLenBits idx,makeInc (MidTape from idx) (MidTape to idx) valueBits addr, keepMidTapeElse valueBits tapeLen from to idx] decMidTape :: Int -> (Int,Int) -> Time -> Time -> [Int] -> States decMidTape valueBits (tapeLen,tapeLenBits) from to addr = Or $ fmap each [0..tapeLen-1] where each idx = And [isConst (MC from) tapeLenBits idx,makeDec (MidTape from idx) (MidTape to idx) valueBits addr, keepMidTapeElse valueBits tapeLen from to idx] keepSC :: Int -> (Time->Int->Component) -> Time -> Time -> States keepSC bitLength cons from to = makeEq (cons from) (cons to) bitLength keepOC :: Int -> Time -> Time -> States keepOC outLenBits = keepSC outLenBits OC keepIC :: Int -> Time -> Time -> States keepIC inLenBits = keepSC inLenBits IC keepMC :: Int -> Time -> Time -> States keepMC tapeLenBits = keepSC tapeLenBits MC keepPC :: Int -> Time -> Time -> States keepPC pcLenBits = keepSC pcLenBits PC incIC :: Int -> Time -> Time -> [Int] -> States incIC inLenBits from to = makeInc (IC from) (IC to) inLenBits incOC :: Int -> Time -> Time -> [Int] -> States incOC outLenBits from to = makeInc (OC from) (OC to) outLenBits incMC :: Int -> Time -> Time -> [Int] -> States incMC tapeLenBits from to = makeInc (MC from) (MC to) tapeLenBits decMC :: Int -> Time -> Time -> [Int] -> States decMC tapeLenBits from to = makeDec (MC from) (MC to) tapeLenBits readInput :: (Int,Int) -> (Int,Int) -> Int -> Time -> Time -> States readInput (inLen,inLenBits) (tapeLen,tapeLenBits) valueBits from to = Or $ fmap (\(mi,ii) -> And [isConst (MC from) tapeLenBits mi, isConst (IC from) inLenBits ii, keepMidTapeElse valueBits tapeLen from to mi, makeEq (MidTape to mi) (InTape ii) valueBits]) (prod [0..(tapeLen-1)] [0..(inLen-1)]) printOutput :: (Int,Int) -> (Int,Int) -> Int -> Time -> States printOutput (outLen,outLenBits) (tapeLen,tapeLenBits) valueBits from = Or $ fmap (\(mi,oi) -> And [isConst (MC from) tapeLenBits mi, isConst (OC from) outLenBits oi, makeEq (MidTape from mi) (OutTape oi) valueBits]) (prod [0..(tapeLen-1)] [0..(outLen-1)]) acceptRule :: Source -> Time -> States acceptRule src t = And [nowPc, keepedPC, keepedMem, keepedMC, keepedOC, keepedIC] where inLen = length (getInTape src) inLenBits = calcBitLength inLen progLen = length (getAST src) progLenBits = calcBitLength progLen tapeLenBits = getAddrBits src tapeLen = 2 ^ tapeLenBits outLenBits = getOutAddrBits src valueBits = getValueBits src from = t to = incTime t nowPc = isConst (PC t) progLenBits progLen keepedPC = keepPC progLenBits from to keepedMem = keepMidTape valueBits tapeLen from to keepedOC = keepOC outLenBits from to keepedMC = keepMC tapeLenBits from to keepedIC = keepIC inLenBits from to genOpRule :: Source -> Time -> [PC] -> Tree -> [Int] -> States genOpRule src t pcs op addr = case op of PtInc -> And [nowPc, incPCp, keepedMem, keepedOC, keepedIC, incMC tapeLenBits from to (0:addr)] PtDec -> And [nowPc, incPCp, keepedMem, keepedOC, keepedIC, decMC tapeLenBits from to (0:addr)] ValInc -> And [nowPc, incPCp, keepedMC, keepedOC, keepedIC, incMidTape valueBits (tapeLen,tapeLenBits) from to (0:addr)] ValDec -> And [nowPc, incPCp, keepedMC, keepedOC, keepedIC, decMidTape valueBits (tapeLen,tapeLenBits) from to (0:addr)] PutC -> And [nowPc, incPCp, keepedMem, keepedMC, keepedIC, printOutput (outLen,outLenBits) (tapeLen,tapeLenBits) valueBits from, incOC outLenBits from to (0:addr)] GetC -> And [nowPc, incPCp, keepedMC, keepedOC, readInput (inLen,inLenBits) (tapeLen,tapeLenBits) valueBits from to, incIC inLenBits from to (0:addr)] LoopBegin next -> And [nowPc, keepedMem, keepedMC, keepedOC, keepedIC, Or $ map (\mc -> And [isConst (MC t) tapeLenBits mc, Or [And[ isZero (MidTape from mc) valueBits, makeConst (PC to) progLenBits next], And[notZero (MidTape from mc) valueBits, incPCp]]]) [0..tapeLen-1]] LoopEnd next -> And [nowPc, keepedMem, keepedMC, keepedOC, keepedIC, Or $ map (\mc -> And [isConst (MC t) tapeLenBits mc, Or [And[notZero (MidTape from mc) valueBits, makeConst (PC to) progLenBits next], And[ isZero (MidTape from mc) valueBits, incPCp]]]) [0..tapeLen-1]] where inLen = length (getInTape src) inLenBits = calcBitLength inLen progLen = length (getAST src) progLenBits = calcBitLength progLen tapeLenBits = getAddrBits src tapeLen = 2 ^ tapeLenBits outLenBits = getOutAddrBits src outLen = 2 ^ outLenBits valueBits = getValueBits src from = t to = incTime t nowPc = Or $ fmap (isConst (PC t) progLenBits) pcs incPCp = changePC (progLen,progLenBits) from to (1:addr) keepedMem = keepMidTape valueBits tapeLen from to keepedOC = keepOC outLenBits from to keepedMC = keepMC tapeLenBits from to keepedIC = keepIC inLenBits from to genStepRules :: Time -> Source -> States genStepRules t src = Or $ acceptRule src t :fmap (\(pc,op) -> genOpRule src t pc op [getTime t,0]) grouped where grouped = fmap (\lst -> (fmap fst lst,snd $ head lst)) $ groupBy (\(_,op1) (_,op2) -> op1 == op2) $ sortOn (\(_,op)->op) (zip [0..] (getAST src)) genMiddleState :: Source -> States genMiddleState src = And $ fmap ((\t -> genStepRules t src) . Time) [(getTime t0)..(getTime (lastTime src) - 1)] zeroFillOut :: Int -> Int -> States zeroFillOut outLenBits idx = isZero (OutTape idx) outLenBits greaterThanOC :: (Int,Int) -> Time -> Int -> States greaterThanOC (outLen, outLenBits) t idx = Or $ isConst (OC t) outLenBits <$> [idx+1..(outLen-1)] flushOC :: (Int,Int) -> Time -> States flushOC (outLen, outLenBits) t = And $ fmap (\ idx -> Or [greaterThanOC (outLen,outLenBits) t idx, zeroFillOut outLenBits idx]) [0..outLen-1] genLastState :: Source -> States genLastState src = And [isConst (PC $ lastTime src) progLenBits progLen, flushOC (outLen,outLenBits) (lastTime src)] where outLenBits = getOutAddrBits src outLen = 2 ^ outLenBits progLen = length (getAST src) progLenBits = calcBitLength progLen
cf839b2d001db28b4e30e9ace6a7316acbec8cbad4338c91539a0b1bcb6b60df
HugoPeters1024/hs-sleuth
Cut.hs
| Cut into a file , selecting certain columns ( e.g. columns 10 to 40 ) -- -- Tested in this benchmark: -- -- * Reading the file -- -- * Splitting into lines -- -- * Taking a number of characters from the lines -- -- * Joining the lines -- -- * Writing back to a handle -- module Benchmarks.Programs.Cut ( benchmark ) where import Criterion (Benchmark, bgroup, bench, whnfIO) import System.IO (Handle, hPutStr) import qualified Data.ByteString as B import qualified Data.ByteString.Char8 as BC import qualified Data.ByteString.Lazy as BL import qualified Data.ByteString.Lazy.Char8 as BLC import qualified Data.Text as T import qualified Data.Text.Encoding as T import qualified Data.Text.IO as T import qualified Data.Text.Lazy as TL import qualified Data.Text.Lazy.Encoding as TL import qualified Data.Text.Lazy.IO as TL benchmark :: FilePath -> Handle -> Int -> Int -> Benchmark benchmark p sink from to = bgroup "Cut" [ bench' "String" string , bench' "ByteString" byteString , bench' "LazyByteString" lazyByteString , bench' "Text" text , bench' "LazyText" lazyText , bench' "TextByteString" textByteString , bench' "LazyTextByteString" lazyTextByteString ] where bench' n s = bench n $ whnfIO (s p sink from to) string :: FilePath -> Handle -> Int -> Int -> IO () string fp sink from to = do s <- readFile fp hPutStr sink $ cut s where cut = unlines . map (take (to - from) . drop from) . lines byteString :: FilePath -> Handle -> Int -> Int -> IO () byteString fp sink from to = do bs <- B.readFile fp B.hPutStr sink $ cut bs where cut = BC.unlines . map (B.take (to - from) . B.drop from) . BC.lines lazyByteString :: FilePath -> Handle -> Int -> Int -> IO () lazyByteString fp sink from to = do bs <- BL.readFile fp BL.hPutStr sink $ cut bs where cut = BLC.unlines . map (BL.take (to' - from') . BL.drop from') . BLC.lines from' = fromIntegral from to' = fromIntegral to text :: FilePath -> Handle -> Int -> Int -> IO () text fp sink from to = do t <- T.readFile fp T.hPutStr sink $ cut t where cut = T.unlines . map (T.take (to - from) . T.drop from) . T.lines lazyText :: FilePath -> Handle -> Int -> Int -> IO () lazyText fp sink from to = do t <- TL.readFile fp TL.hPutStr sink $ cut t where cut = TL.unlines . map (TL.take (to' - from') . TL.drop from') . TL.lines from' = fromIntegral from to' = fromIntegral to textByteString :: FilePath -> Handle -> Int -> Int -> IO () textByteString fp sink from to = do t <- T.decodeUtf8 `fmap` B.readFile fp B.hPutStr sink $ T.encodeUtf8 $ cut t where cut = T.unlines . map (T.take (to - from) . T.drop from) . T.lines lazyTextByteString :: FilePath -> Handle -> Int -> Int -> IO () lazyTextByteString fp sink from to = do t <- TL.decodeUtf8 `fmap` BL.readFile fp BL.hPutStr sink $ TL.encodeUtf8 $ cut t where cut = TL.unlines . map (TL.take (to' - from') . TL.drop from') . TL.lines from' = fromIntegral from to' = fromIntegral to
null
https://raw.githubusercontent.com/HugoPeters1024/hs-sleuth/385655e62031959a14a3bac5e9ccd1c42c045f0c/test-project/text-1.2.4.0/benchmarks/haskell/Benchmarks/Programs/Cut.hs
haskell
Tested in this benchmark: * Reading the file * Splitting into lines * Taking a number of characters from the lines * Joining the lines * Writing back to a handle
| Cut into a file , selecting certain columns ( e.g. columns 10 to 40 ) module Benchmarks.Programs.Cut ( benchmark ) where import Criterion (Benchmark, bgroup, bench, whnfIO) import System.IO (Handle, hPutStr) import qualified Data.ByteString as B import qualified Data.ByteString.Char8 as BC import qualified Data.ByteString.Lazy as BL import qualified Data.ByteString.Lazy.Char8 as BLC import qualified Data.Text as T import qualified Data.Text.Encoding as T import qualified Data.Text.IO as T import qualified Data.Text.Lazy as TL import qualified Data.Text.Lazy.Encoding as TL import qualified Data.Text.Lazy.IO as TL benchmark :: FilePath -> Handle -> Int -> Int -> Benchmark benchmark p sink from to = bgroup "Cut" [ bench' "String" string , bench' "ByteString" byteString , bench' "LazyByteString" lazyByteString , bench' "Text" text , bench' "LazyText" lazyText , bench' "TextByteString" textByteString , bench' "LazyTextByteString" lazyTextByteString ] where bench' n s = bench n $ whnfIO (s p sink from to) string :: FilePath -> Handle -> Int -> Int -> IO () string fp sink from to = do s <- readFile fp hPutStr sink $ cut s where cut = unlines . map (take (to - from) . drop from) . lines byteString :: FilePath -> Handle -> Int -> Int -> IO () byteString fp sink from to = do bs <- B.readFile fp B.hPutStr sink $ cut bs where cut = BC.unlines . map (B.take (to - from) . B.drop from) . BC.lines lazyByteString :: FilePath -> Handle -> Int -> Int -> IO () lazyByteString fp sink from to = do bs <- BL.readFile fp BL.hPutStr sink $ cut bs where cut = BLC.unlines . map (BL.take (to' - from') . BL.drop from') . BLC.lines from' = fromIntegral from to' = fromIntegral to text :: FilePath -> Handle -> Int -> Int -> IO () text fp sink from to = do t <- T.readFile fp T.hPutStr sink $ cut t where cut = T.unlines . map (T.take (to - from) . T.drop from) . T.lines lazyText :: FilePath -> Handle -> Int -> Int -> IO () lazyText fp sink from to = do t <- TL.readFile fp TL.hPutStr sink $ cut t where cut = TL.unlines . map (TL.take (to' - from') . TL.drop from') . TL.lines from' = fromIntegral from to' = fromIntegral to textByteString :: FilePath -> Handle -> Int -> Int -> IO () textByteString fp sink from to = do t <- T.decodeUtf8 `fmap` B.readFile fp B.hPutStr sink $ T.encodeUtf8 $ cut t where cut = T.unlines . map (T.take (to - from) . T.drop from) . T.lines lazyTextByteString :: FilePath -> Handle -> Int -> Int -> IO () lazyTextByteString fp sink from to = do t <- TL.decodeUtf8 `fmap` BL.readFile fp BL.hPutStr sink $ TL.encodeUtf8 $ cut t where cut = TL.unlines . map (TL.take (to' - from') . TL.drop from') . TL.lines from' = fromIntegral from to' = fromIntegral to