code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
{-| Module : Control.Monad.Bayes.Population Description : Representation of distributions using multiple samples Copyright : (c) Adam Scibior, 2016 License : MIT Maintainer : [email protected] Stability : experimental Portability : GHC -} module Control.Monad.Bayes.Population ( Population, runPopulation, explicitPopulation, fromWeightedList, spawn, resample, proper, evidence, collapse, mapPopulation, normalize, normalizeProper, popAvg, hoist ) where import Prelude hiding (all) import Control.Arrow (second) import Control.Monad.Trans import Control.Monad.Trans.List import Control.Monad.Bayes.LogDomain (LogDomain, fromLogDomain) import Control.Monad.Bayes.Class import Control.Monad.Bayes.Weighted hiding (hoist) -- | Empirical distribution represented as a list of values. -- Probabilistic effects are lifted from the transformed monad. -- 'Empirical' satisfies monad laws only when the transformed -- monad is commutative. newtype Empirical m a = Empirical {unEmpirical :: ListT m a} deriving (Functor, Applicative, Monad, MonadTrans, MonadIO) type instance CustomReal (Empirical m) = CustomReal m deriving instance MonadDist m => MonadDist (Empirical m) deriving instance MonadBayes m => MonadBayes (Empirical m) -- | Explicit representation of the sample. runEmpirical :: Empirical m a -> m [a] runEmpirical = runListT . unEmpirical -- | Initialise 'Empirical' with a concrete sample. fromList :: m [a] -> Empirical m a fromList = Empirical . ListT -- | Set the number of samples for the empirical distribution. -- Bear in mind that invoking `draw` twice in the same computation -- leads to multiplying the number of samples. -- Additionally, using `draw` with different arguments in different branches -- of a probabilistic program leads to a bias in the final sample, since -- the branch that uses more points is over-represented. draw :: Applicative m => Int -> Empirical m () draw n = fromList $ pure $ replicate n () -- | A population consisting of weighted samples. -- Conditioning is done by accumulating weights. -- There is no automatic normalization or aggregation of weights. newtype Population m a = Population {unPopulation :: Weighted (Empirical m) a} deriving (Functor) type instance CustomReal (Population m) = CustomReal m deriving instance MonadDist m => Applicative (Population m) deriving instance MonadDist m => Monad (Population m) deriving instance (MonadDist m, MonadIO m) => MonadIO (Population m) deriving instance MonadDist m => MonadDist (Population m) deriving instance MonadDist m => MonadBayes (Population m) instance MonadTrans Population where lift = Population . lift . lift -- | Explicit representation of the weighted sample with weights in log domain. runPopulation :: MonadDist m => Population m a -> m [(a,LogDomain (CustomReal m))] runPopulation = runEmpirical . runWeighted . unPopulation -- | Explicit representation of the weighted sample. explicitPopulation :: MonadDist m => Population m a -> m [(a, CustomReal m)] explicitPopulation = fmap (map (second fromLogDomain)) . runPopulation -- | Initialise 'Population' with a concrete weighted sample. fromWeightedList :: MonadDist m => m [(a,LogDomain (CustomReal m))] -> Population m a fromWeightedList = Population . withWeight . fromList -- | Lift unweighted sample by setting all weights equal. fromEmpirical :: MonadDist m => Empirical m a -> Population m a fromEmpirical = fromWeightedList . fmap setWeights . runEmpirical where setWeights xs = map (,w) xs where w = 1 / fromIntegral (length xs) -- | Increase the sample size by a given factor. -- The weights are adjusted such that their sum is preserved. -- It is therefore safe to use `spawn` in arbitrary places in the program -- without introducing bias. spawn :: MonadDist m => Int -> Population m () spawn n = fromEmpirical (draw n) -- | Resample the population using the underlying monad and a simple resampling scheme. -- The total weight is preserved. resample :: MonadDist m => Population m a -> Population m a resample m = fromWeightedList $ do pop <- runPopulation m let (xs, ps) = unzip pop let n = length xs let z = sum ps if z > 0 then do offsprings <- sequenceA $ replicate n $ logCategorical pop return $ map (, z / fromIntegral n) offsprings else -- if all weights are zero do not resample return pop -- | A properly weighted single sample, that is one picked at random according -- to the weights, with the sum of all weights. proper :: MonadDist m => Population m a -> m (a,LogDomain (CustomReal m)) proper m = do pop <- runPopulation m let (xs, ps) = unzip pop let z = sum ps index <- if z > 0 then logDiscrete ps else uniformD [0..(length xs - 1)] let x = xs !! index return (x,z) -- | Model evidence estimator, also known as pseudo-marginal likelihood. evidence :: MonadDist m => Population m a -> m (LogDomain (CustomReal m)) evidence = fmap (sum . map snd) . runPopulation -- | Picks one point from the population and uses model evidence as a 'factor' -- in the transformed monad. -- This way a single sample can be selected from a population without -- introducing bias. collapse :: (MonadBayes m) => Population m a -> m a collapse e = do (x,p) <- proper e factor p return x -- | Applies a random transformation to a population. mapPopulation :: MonadDist m => ([(a, LogDomain (CustomReal m))] -> m [(a, LogDomain (CustomReal m))]) -> Population m a -> Population m a mapPopulation f m = fromWeightedList $ runPopulation m >>= f -- | Normalizes the weights in the population so that their sum is 1. -- This transformation introduces bias. normalize :: MonadDist m => Population m a -> Population m a normalize = mapPopulation norm where norm xs = pure $ map (second (/ z)) xs where z = sum $ map snd xs -- | Normalizes the weights in the population so that their sum is 1. -- The sum of weights is pushed as a factor to the transformed monad, -- so bo bias is introduced. normalizeProper :: MonadBayes m => Population m a -> Population m a normalizeProper = mapPopulation norm where norm xs = factor z >> pure (map (second (/ z)) xs) where z = sum $ map snd xs -- | Population average of a function, computed using unnormalized weights. popAvg :: MonadBayes m => (a -> CustomReal m) -> Population m a -> m (CustomReal m) popAvg f p = do xs <- runPopulation p let ys = map (\(x,w) -> f x * fromLogDomain w) xs return (sum ys) -- | Applies a transformation to the inner monad. hoist :: (MonadDist m, MonadDist n, CustomReal m ~ CustomReal n) => (forall x. m x -> n x) -> Population m a -> Population n a hoist f = fromWeightedList . f . runPopulation
ocramz/monad-bayes
src/Control/Monad/Bayes/Population.hs
mit
6,753
0
15
1,307
1,736
897
839
-1
-1
{-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} -- | Main library for screwing around with OpenGL module TestGL (module TestGL) where import Control.Monad.IO.Class import Control.Monad.Trans.Class (lift) import Control.Monad.Trans.State.Strict import Data.Bits import Data.Text (Text) import qualified Data.Vector.Storable as V import Foreign.C.String import Foreign.Ptr import Foreign.Storable import Graphics.Caramia import Graphics.Caramia.Prelude hiding (init) import Graphics.UI.SDL -- GENERATE: import New.Module as TestGL -- winSizeX, winSizeY :: Num a => a winSizeX = 500 winSizeY = 500 -- | OpenGL initialization routine glInit :: MonadIO m => CString -> m Window glInit cstr = do void $ init SDL_INIT_VIDEO _ <- glSetAttribute SDL_GL_CONTEXT_MAJOR_VERSION 3 _ <- glSetAttribute SDL_GL_CONTEXT_MINOR_VERSION 3 _ <- glSetAttribute SDL_GL_CONTEXT_PROFILE_MASK SDL_GL_CONTEXT_PROFILE_CORE _ <- glSetAttribute SDL_GL_CONTEXT_FLAGS SDL_GL_CONTEXT_DEBUG_FLAG window <- createWindow cstr undef undef winSizeX winSizeY props _ <- glCreateContext window return window where undef = SDL_WINDOWPOS_UNDEFINED props = SDL_WINDOW_OPENGL .|. SDL_WINDOW_SHOWN -- | Main function main :: IO () main = withCString "query-objects" $ \cstr -> do window <- glInit cstr giveContext $ flip evalStateT initialState $ forever $ mainLoop window type PgmState = (Bool, Float) initialState :: PgmState initialState = (False, -1.0) updateState :: PgmState -> PgmState updateState (x, y) | y < -1.0 = (True, incr y) | y > 1.0 = (False, decr y) | x = (x, incr y) | otherwise = (x, decr y) where incr a = a + 0.003 decr a = a - 0.003 clearFB = clear clearing { clearDepth = Just 1.0 , clearColor = Just $ rgba 0.1 0.1 0.1 1.0 } type Matrix2D e = [[e]] -- ^ 2D matrix type PC = Int -- ^ Pixel coordinate type TC = Int -- ^ Tile map coordinates type V2 a = (a, a) -- ^ 2-vector type V3 a = (a, a, a) -- ^ 3-vector type V4 a = (a, a, a, a) -- ^ 4-vector type PixelCoord = V2 PC type PixelDim = V2 PC type Pixel = Graphics.Caramia.Color type TileDim = V2 TC type TileCoord = V2 TC type Sprite = Matrix2D Pixel type PixelRect = V2 PixelCoord class TileMap tm where -- | Get a matrix of sprites out of the tilemap getTMap :: tm -> Matrix2D Sprite getTMap = undefined -- | Get the tile coordinate dimensions of the tilemap getTMCSize :: tm -> TileDim getTMCSize = undefined -- | Get the dimensions of each sprite in the tilemap getTMSSize :: tm -> PixelDim getTMSSize = undefined -- | Get the pixel dimensions of the tilemap getTMPSize :: tm -> PixelDim getTMPSize = undefined -- | Verify that a given tilemap is valid verifyTileMap :: tm -> Bool verifyTileMap = undefined -- | Make a TileMap concrete renderTMap :: tm -> tm renderTMap = undefined -- | Index into a TileMap indexTMap :: tm -> TileCoord -> Sprite indexTMap = undefined -- | Make a sprite from a rectangle between two pixel coordinates getTMapRect :: tm -> PixelRect -> Sprite getTMapRect = undefined -- | mainLoop window = do clearFB screenFramebuffer let drawParams = defaultDrawParams { pipeline = color_program , fragmentPassTests = defaultFragmentPassTests { depthTest = Just Less } } runDraws drawParams $ draws vao color_program color_loc offset_loc modify updateState liftIO $ glSwapWindow window runPendingFinalizers draws vao color_program color_loc offset_loc = do samples <- newNumericQuery SamplesPassed any_samples <- newBooleanQuery AnySamplesPassed elapsed <- newNumericQuery TimeElapsed go_right <- lift $ fst <$> get x <- lift $ snd <$> get setUniform (rgba 1 0 1 1) color_loc color_program setUniform (x, 0.0 :: Float) offset_loc color_program drawR drawCommand { primitiveType = TriangleStrip , primitivesVAO = vao , numIndices = 4 , sourceData = Primitives { firstIndex = 0 } } if go_right then beginQuery samples else beginQuery any_samples beginQuery elapsed setUniform (0 :: Float, 0 :: Float) offset_loc color_program setUniform (rgba 0 1 1 1) color_loc color_program if go_right then endQuery samples else endQuery any_samples endQuery elapsed newImmutableBufferFromVector :: V.Vector Float -> IO Buffer newImmutableBufferFromVector vec = V.unsafeWith vec $ \ptr -> do let byte_size = sizeOf (undefined :: Float) * V.length vec newBuffer defaultBufferCreation { size = byte_size , initialData = Just $ castPtr ptr , accessHints = (Static, Draw) , accessFlags = NoAccess } passThroughVertex2DShader :: Text passThroughVertex2DShader = "#version 330\n" <> "uniform vec2 offset;\n" <> "layout (location=0) in vec2 pos;\n" <> "void main() {\n" <> " gl_Position = vec4(pos+offset, 0, 1);\n" <> "}\n" coloredFragmentProgram :: Text coloredFragmentProgram = "#version 330\n" <> "uniform vec4 color;\n" <> "layout (location=0) out vec4 fcolor;\n" <> "void main() {\n" <> " fcolor = color;\n" <> "}\n"
taktoa/TestGL
library/TestGL.hs
mit
5,648
0
14
1,546
1,311
706
605
135
3
import Network import Network.Socket import System.Exit import System.IO import Control.Monad import Control.Exception import Data.List path = "GET /echo.php?message=" protocol = "HTTP/1.1\r\n" headers = "Host: localhost\r\n" ++ "Connection: close\r\n" ++ "User-Agent: MyAwesomeUserAgent/1.0.0\r\n" ++ "Accept-Encoding: gzip\r\n" ++ "Accept-Charset: ISO-8859-1,UTF-8;q=0.7,*;q=0.7\r\n" ++ "Cache-Control: no-cache\r\n\n" localhost = 0 -- localhost's IP addr is 0.0.0.0 aka. 0 port = 8000 chunkSize = 4096 main :: IO () main = withSocketsDo $ do socket <- createTCPSocket connect socket (SockAddrInet port localhost) s <- prompt "Enter string to uppercase: " send socket (path ++ queryify s ++ " " ++ protocol ++ headers) forever $ do res <- try $ recv socket chunkSize :: IO (Either IOError String) case res of Left _ -> exitSuccess -- recv throws IOError on EOF Right s -> putStr s queryify :: String -> String queryify s = intercalate "+" $ words s createTCPSocket :: IO Socket createTCPSocket = socket AF_INET Stream defaultProtocol prompt :: String -> IO String prompt p = do putStr p hFlush stdout -- else the putStr will be buffered & not output til later s <- getLine putStr "\n" return s
IanConnolly/CS4032
lab1/client.hs
mit
1,344
6
14
332
364
165
199
40
2
{-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances, MultiParamTypeClasses #-} module ApplyInternal (App(..) ,Wrap(..) ,TagC(..) ,TagD(..) ,TDef ,WrapDef(..) ,makeApplyInst ,wApply ,applyW ,wApplyW ,wApply2 ,partial ,(@@) ,(#@) ,(#@#) ,(@#) ,(&) ) where class Wrap w where unwrap :: w a -> a wrap :: a -> w a class TagC t a b where data family TagD t a b class (Wrap w, TagC t a b) => App t w a b where apply :: w (a -> b) -> TagD t a b -> w a -> w b makeApplyInst :: (Wrap w) => (f -> a -> b) -> w f -> t -> w a -> w b makeApplyInst g f _ x = wrap $ g (unwrap f) (unwrap x) wApply :: App t w a b => (a -> b) -> TagD t a b -> w a -> w b wApply f = apply (wrap f) applyW :: App t w a b => w (a -> b) -> TagD t a b -> a -> w b applyW f t x= apply f t (wrap x) wApplyW :: App t w a b => (a -> b) -> TagD t a b -> a -> w b wApplyW f t x = apply (wrap f) t (wrap x) partial :: Wrap w => (w a -> w b) -> w (a->b) partial f = wrap (unwrap . f . wrap) --The types for the infix functions are not inferred correctly infixl 9 @@ (@@) :: App t w a b => w (a -> b) -> TagD t a b -> w a -> w b (@@) = apply --Wraps the fuction infixl 9 #@ (#@) :: App t w a b => (a -> b) -> TagD t a b -> w a -> w b (#@) = wApply --Wraps the fuction and argument infixl 9 #@# (#@#) :: App t w a b => (a -> b) -> TagD t a b -> a -> w b (#@#) = wApplyW --Wraps the argument infixl 9 @# (@#) :: App t w a b => w (a -> b) -> TagD t a b -> a -> w b (@#) = applyW -- Usage: apply f t x == f @@ t & x infixl 9 & (&) :: (a -> b) -> a -> b (&) = ($) --Apply unwraped function to two wrapped arguments wApply2 :: (App t1 w a1 (a -> b), App t w a b) => TagD t1 a1 (a -> b) -> TagD t a b -> (a1 -> a -> b) -> w a1 -> w a -> w b wApply2 t1 t2 f = apply2 t1 t2 (wrap f) --Apply wrapped function to two wrapped arguments apply2 :: (App t1 w a1 (a -> b), App t w a b) => TagD t1 a1 (a -> b) -> TagD t a b -> w (a1 -> a -> b) -> w a1 -> w a -> w b apply2 t1 t2 f x y= f @@ t1 & x @@ t2 & y --Default tag data TDef instance TagC TDef a b where data TagD TDef a b = ADef --The default wrapper is normal function application instance (Wrap w) => App TDef w a b where apply = makeApplyInst ($) --WrapDef newtype WrapDef a = WrapDef a deriving (Show, Eq) instance Wrap WrapDef where unwrap (WrapDef a) = a wrap = WrapDef
rgleichman/smock
ApplyInternal.hs
mit
2,475
0
12
745
1,255
665
590
-1
-1
{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses, DeriveDataTypeable #-} module Main where import System.Environment import qualified Language.Camle.Parser as P import qualified Language.Camle.AstToIr as ATI import qualified Language.Camle.JouetteBackend as JB import Control.Applicative import Text.Parsec import System.Console.CmdLib data Opts = Opts { program_filename :: FilePath, stdout :: Bool, output_filename :: FilePath } deriving (Typeable, Data, Eq, Ord) instance Attributes Opts where attributes _ = group "Options" [ program_filename %> [Help "The file name of the program you wish to compiler"], stdout %> [Help "Print assembly to STDOUT"], output_filename %> [Help "The name of the file the compiler will output assembly code to"]] main = do [filename] <- getArgs src <- readFile filename printAsm . compile $ src compile :: String -> Either ParseError JB.Code compile program = (JB.irToAsm . ATI.astToIr) <$> P.parse program printAsm :: (Either ParseError JB.Code) -> IO () printAsm (Right program) = do putStr . show $ program printAsm (Left error) = print error
willprice/camle-compiler
src/CompilerMain.hs
mit
1,229
0
10
296
305
167
138
29
1
-- This is about the same speed as subgrs04.hs, but it doesn't track generating -- sets. import Control.Monad (guard) import Data.Maybe (mapMaybe) import Data.IntSet (IntSet) import qualified Data.IntSet as ISet import qualified Data.Map as Map import Data.Set (Set) import qualified Data.Set as Set import Groups import Subutils main = mapM_ (putStrLn . bracket "{}" . ISet.toList) $ Set.toList $ subgroups group subgroups :: Group -> Set IntSet subgroups g = foldl (\subs c -> foldl (flip Set.insert) subs $ mapMaybe (addCycle c) $ Set.toList subs) (Map.keysSet cycles) (tail $ Map.toList cycles) where cycles = Map.fromListWith const [(ISet.fromList $ g_cycle g x, x) | x <- g_elems g] addCycle (cyc, cg) subgr = do guard $ ISet.notMember cg subgr return $ newClosure2 (g_oper g) subgr (ISet.toList cyc)
jwodder/groups
haskell/old/subgroups/subgrs05b.hs
mit
829
6
13
148
320
163
157
20
1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE ScopedTypeVariables #-} -- | Parsing of Unification Grammars with a CFG backbone -- Following http://cs.haifa.ac.il/~shuly/teaching/06/nlp/ug2.pdf module NLP.UG.ParseCFG where import Common import NLP.AVM import NLP.UG.GrammarCFG import qualified Data.Char as C import qualified Data.Map as M import qualified Data.List as L import qualified Control.Monad.State as CMS import Debug.Trace (trace) ------------------------------------------------------------------------------ -- Naive parse function -- This essentially enumerates all trees to a certain depth and finds matching one -- | Parse a string given a grammar and print output -- Sets max tree depth based on length of input parse :: String -> Grammar -> IO () parse s g = mapM_ pp $ parse' tokens g depth where tokens = words s depth = (\x -> ceiling $ 1 + log (5*fromIntegral x)) $ length tokens -- | Parse a string given a grammar and print output parseD :: String -> Grammar -> Int -> IO () parseD s g d = mapM_ pp $ parse' tokens g d where tokens = words s -- | Parse a string given a grammar and return all possible derivation trees parse' :: [Token] -> Grammar -> Int -> [DerivationTree] parse' ts g d = [ tree | tree <- allTrees g d, lin tree == ts] -- | Get all valid, complete sentences in a grammar, up to a certain tree depth allStrings :: Grammar -> Int -> [String] allStrings g depth = map (unwords.lin) $ filter isComplete $ allTrees g depth -- | Get all valid derivation trees from a grammar, up to a certain depth allTrees :: Grammar -> Int -> [DerivationTree] allTrees g depth = allTrees' (start g) nullAVM g depth allTrees' :: Cat -> AVM -> Grammar -> Int -> [DerivationTree] allTrees' cat avm g depth = CMS.evalState (go 0 [1] cat avm) (newIndex avm) where go :: (CMS.MonadState Int m) => Int -> [Int] -> Cat -> AVM -> m [DerivationTree] go d pth cat avm = do drvs :: [[DerivationTree]] <- filtermapM f (rules g) return $ concat drvs where f :: (CMS.MonadState Int m) => ERule -> m (Maybe [DerivationTree]) -- Get matching rules (recurses) f (ERule (Rule (clhs:crhs)) mavm) = do let from :: Int = newIndex avm -- read (concat (map show (reverse pth))) rs = M.fromList $ zip [1..100] [from..] -- TODO remove this hard limit ravms = unMultiAVM $ mreIndex rs mavm lhs = head ravms rhs = map (setDict (avmDict par)) $ tail ravms par = lhs βŠ” avm kidss' :: [[DerivationTree]] <- if d < depth-1 then sequence [ go (d+1) (i:pth) c ravm | (i,(c,ravm)) <- zip [1..] (zip crhs rhs) ] else return [ [Node c ravm []] | (c,ravm) <- zip crhs rhs ] let kidss = combos kidss' if cat == clhs && avm βŠ”? lhs then return $ Just [ Node clhs (mergeKids par kids) (cleanKids kids) -- cleaning is probably unnecessary, just good practice | kids <- kidss -- kids :: [DerivationTree] , compatibleKids par kids ] else return $ Nothing -- Get matching terminals f (ERule (Terminal clhs tok) mavm) = do let from :: Int = newIndex avm -- read (concat (map show (reverse pth))) rs = M.fromList $ zip [1..100] [from..] -- TODO remove this hard limit lhs:rhs:[] = unMultiAVM $ mreIndex rs mavm par = rhs βŠ” avm if cat == clhs && avm βŠ”? rhs then return $ Just [ Node clhs par [Leaf tok] ] else return $ Nothing -- Are all these kids compatible with parent? compatibleKids :: AVM -> [DerivationTree] -> Bool compatibleKids avm kids = fst $ foldl (\(t,b) (Node _ a _) -> (t && canMergeAVMDicts b a, mergeAVMDicts b a)) (True,avm) kids -- compatibleKids avm kids = fst $ foldl (\(t,b) (Node _ a _) -> (t && b βŠ”? a, b βŠ” a)) (True,avm) kids -- Merge these kids with parent (dictionaries) mergeKids :: AVM -> [DerivationTree] -> AVM mergeKids avm kids = foldl (\b (Node _ a _) -> mergeAVMDicts b a) avm kids -- mergeKids avm kids = foldl (\b (Node _ a _) -> b βŠ” a) avm kids -- Clean dictionaries of kids cleanKids :: [DerivationTree] -> [DerivationTree] cleanKids kids = [ Node c (cleanDict avm) ks | Node c avm ks <- kids ] ------------------------------------------------------------------------------ -- Test test :: IO () test = do let ss1 = allStrings g1 6 ss1' = ["a lamb sleeps" ,"a lamb sleeps a lamb" ,"a lamb sleeps a sheep" ,"a lamb sleeps two lambs" ,"a lamb sleeps two sheep" ,"a sheep sleeps" ,"a sheep sleeps a lamb" ,"a sheep sleeps a sheep" ,"a sheep sleeps two lambs" ,"a sheep sleeps two sheep" ,"two lambs sleep" ,"two lambs sleep a lamb" ,"two lambs sleep a sheep" ,"two lambs sleep two lambs" ,"two lambs sleep two sheep" ,"two sheep sleep" ,"two sheep sleep a lamb" ,"two sheep sleep a sheep" ,"two sheep sleep two lambs" ,"two sheep sleep two sheep"] ss2 = allStrings g2 6 ss2' = ["a lamb herds a lamb" ,"a lamb herds Rachel" ,"a lamb herds her" ,"Rachel herds a lamb" ,"Rachel herds Rachel" ,"Rachel herds her" ,"she herds a lamb" ,"she herds Rachel" ,"she herds her"] f ss1' ss1 f ss2' ss2 where f gold out = do if L.sort gold == L.sort out then putStrLn "Ok" else do let under = gold L.\\ out over = out L.\\ gold putStrLn "Under:" putStrLn $ unlines $ under putStrLn "Over:" putStrLn $ unlines $ over putStrLn $ show (length under) ++ "/" ++ show (length over) ++ "/" ++ show (length gold) putStrLn "------------------------"
johnjcamilleri/hpsg
NLP/UG/ParseCFG.hs
mit
6,037
0
19
1,816
1,603
845
758
113
5
-- Examples from Chapter two -- http://learnyouahaskell.com/starting-out doubleMe x = x + x doubleUs x y = doubleMe x + doubleMe y doubleSmallNumer x = if x > 100 then x else doubleMe x boomBangs xs = [ if x < 10 then "BOOM!" else "BANG!" | x <- xs, odd x] length' xs = sum [1 | _ <- xs] removeNonUppercase st = [ c | c <- st, c `elem` ['A'..'Z']]
Sgoettschkes/learning
haskell/LearnYouAHaskell/02.hs
mit
362
4
8
87
165
79
86
8
2
import Conduit import Control.Monad (unless) import Control.Monad (when) import Control.Monad.Catch (MonadMask) import qualified Copy.Conduit import qualified Copy.StorableConduit import qualified Copy.PeekPoke import qualified Copy.Raw import Criterion.Main import qualified Data.ByteString as S import Data.ByteString.Lazy.Internal (defaultChunkSize) import Data.ByteVector (fromByteVector) import System.IO (Handle, hClose) import qualified System.IO as IO import System.IO.Temp (withSystemTempFile) import qualified System.Random.MWC as MWC runTest :: FilePath -- ^ source file -> String -> (Handle -> Handle -> IO ()) -> Benchmark runTest inFP name f = bench name $ IO.withBinaryFile inFP IO.ReadMode $ \inH -> withSystemTempFile "run-test-out.bin" $ \outFP outH -> do f inH outH hClose inH hClose outH when testOutput $ do bs1 <- S.readFile inFP bs2 <- S.readFile outFP unless (bs1 == bs2) $ putStrLn "Buggy implementation!" testOutput :: Bool testOutput = False main :: IO () main = withRandomFile $ \input -> defaultMain [ runTest input "Raw" Copy.Raw.run , runTest input "PeekPoke" Copy.PeekPoke.run , runTest input "conduit" Copy.Conduit.run , runTest input "storable conduit" Copy.StorableConduit.run ] withRandomFile :: (MonadIO m, MonadMask m) => (FilePath -> m a) -> m a withRandomFile f = withSystemTempFile "random-file.bin" $ \fp h -> do liftIO $ do gen <- MWC.createSystemRandom replicateMC (4000000 `div` defaultChunkSize) (MWC.uniformVector gen defaultChunkSize) $$ mapC fromByteVector =$ sinkHandle h hClose h f fp
snoyberg/bytevector
bench/Copy.hs
mit
1,967
0
17
636
527
273
254
49
1
-- | -- Module : Befunge -- Copyright : Joe Jevnik 2013 -- -- License : GPL-2 -- Maintainer : [email protected] -- Stability : stable -- Portability : GHC -- -- A befunge interpreter. {-# LANGUAGE CPP #-} module Main where import Befunge.Doublefunge (runDoublefunge) import Befunge.Data import Befunge.Operations import Befunge.Parser import Control.Arrow (first,second) import Control.Concurrent (MVar,forkFinally,putMVar,newEmptyMVar) import Control.Monad (void,liftM,(<=<)) import Data.Array.MArray (readArray) import Data.Char (isDigit) import System.Exit (exitSuccess) import System.Environment (getArgs) -- | Mail loop, handles errors and reads the playfield. readAll :: Either StateError State -> IO (Either StateError State) readAll (Left (DivByZeroError (r,c))) = error $ "ERROR at (" ++ show r ++ "," ++ show c ++ "): Attempted to divide by zero." readAll (Left (InvalidInputError ch (r,c))) = error $ "ERROR at (" ++ show r ++ "," ++ show c ++ "): Invalid input: " ++ show ch ++ "." readAll t@(Left Terminate) = return t readAll (Right st) = readNext st >>= readAll . incPointer -- | Reads the next 'State' or any 'StateError's that may have occured. readNext :: State -> IO (Either StateError State) readNext st@(State{isString = True}) = readArray (playfield st) (loc st) >>= \c -> return $ Right $ if c == charToWord '"' then st {isString = False} else sPush (wordToInt c) st readNext st = readArray (playfield st) (loc st) >>= \c -> parseCommand (wordToChar c) st -- | Reads a symbol and applies the proper function. parseCommand :: Char -> State -> IO (Either StateError State) parseCommand '+' = return . Right . sAdd parseCommand '-' = return . Right . sSub parseCommand '*' = return . Right . sMul parseCommand '/' = return . sDiv parseCommand '%' = return . sMod parseCommand '!' = return . Right . sNot parseCommand '`' = return . Right . sGT parseCommand '>' = return . Right . pRight parseCommand '<' = return . Right . pLeft parseCommand '^' = return . Right . pUp parseCommand 'v' = return . Right . pDown parseCommand '?' = liftM Right . pRand parseCommand '_' = return . Right . pHorzIf parseCommand '|' = return . Right . pVertIf parseCommand '"' = return . Right . (\st -> st { isString = True }) parseCommand ':' = return . Right . sDup parseCommand '\\'= return . Right . sSwap parseCommand '$' = return . Right . sPop parseCommand '.' = liftM Right . sPrintInt parseCommand ',' = liftM Right . sPrintChar parseCommand '#' = return . incPointer . Right parseCommand 'p' = liftM Right . fPut parseCommand 'g' = liftM Right . fGet parseCommand '&' = sInputInt parseCommand '~' = liftM Right . sInputChar parseCommand ' ' = return . Right . id parseCommand '@' = return . const (Left Terminate) parseCommand n | isDigit n = return . Right . sPush (read [n]) | otherwise = return . Left . InvalidInputError n . loc -- | Increments the pointer of the 'State' based on the 'Direction'. -- Accounts for wrapping. incPointer :: Either StateError State -> Either StateError State incPointer e@(Left _) = e incPointer (Right st@(State {dir = PUp,loc = (0,c)})) = Right st { loc = (24,c) } incPointer (Right st@(State {dir = PUp})) = Right st { loc = first (flip (-) 1) $ loc st } incPointer (Right st@(State {dir = PDown,loc = (24,c)})) = Right st { loc = (0,c) } incPointer (Right st@(State {dir = PDown})) = Right st { loc = first (+ 1) $ loc st } incPointer (Right st@(State {dir = PLeft,loc = (r,0)})) = Right st { loc = (r,79) } incPointer (Right st@(State {dir = PLeft})) = Right st { loc = second (flip (-) 1) $ loc st } incPointer (Right st@(State {dir = PRight,loc = (r,79)})) = Right st { loc = (r,0) } incPointer (Right st@(State {dir = PRight})) = Right st { loc = second (+ 1) $ loc st } main :: IO () main = getArgs >>= runBefunge -- | Parses the args. runBefunge :: [String] -> IO () runBefunge [] = putStrLn "Usage: runbefunge [FILE]" runBefunge [p] | p `elem` ["-h","--help"] = putStrLn helpString | p `elem` ["-v","--version"] = putStrLn versionString | otherwise = void $ stateFromFile p >>= readAll . Right runBefunge as | all (`notElem` ["-cd","-dc","-c","-d"]) as = mapM_ (readAll . Right <=< stateFromFile) as | all (`notElem` ["-cd","-dc","-d"]) as && "-c" `elem` as = mapM_ forkBefunge as | any (`elem` ["-cd","-dc"]) as = runDoublefunge $ "-c" : filter (`notElem` ["-cd","-dc"]) as | "-d" `elem` as = runDoublefunge $ filter (/= "-d") as -- | Forks a befunge program into its own thread using forkFinally and MVar () -- writing to hold the main thread open until all the children have terminated. forkBefunge :: FilePath -> IO (MVar ()) forkBefunge b = do lock <- newEmptyMVar forkFinally (readAll . Right <=< stateFromFile $ b) (const $ putMVar lock ()) return lock -- | The 'String' to be printed when the user invokes '-v' or '--version'. versionString :: String versionString = "runbefunge 1.0.0 (24.1.2013)\n\ Copyright (C) 2013 Joe Jevnik.\n\ This is free software; see the source for copying conditions. There is NO\n\ warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." -- | The 'String' to be printed when the user invokes '-h' or '--help'. helpString :: String helpString = "Usage:\n\n\ runbefunge [OPTION]... [SOURCE-FILE]...\n\nOptions:\n \ -c Run the list programs concurrently.\n -d \ Run the programs as a doublefunge instead of befugnge-93.\n\ This may be paired with 'c' to run doublefunge concurrently.\ \n -h --help Displays this message.\n\n -v --version Prints version \ information.\n\nTo run a befunge-93 program, run the interpreter like so:\n\n\ runbefunge my_prog.bf\n\n\ where my_prog.bf is the path to the program you wish to run.\n\n\ Alternativly, you may run multiple files at once by passing them in the order\n\ in which you would like them to be evaluated, for example:\n\n\ runbefunge prog1.bf prog2.bf\n\n\ would run prog1.bf until its null character is reached and then begin to run\n\ prog2.bf. For this reason, it will not evaluate any programs after reaching a\n\ program that does not contain a '@' (terminating character).\n\n\ One can also run a set of befunge-93 programs concurrently by passing the '-c'\ \nflag before a list like so:\n\n\ runbefunge -c prog1.bf prog2.bf\n\n\ WARNING: You may get butchered output as they will both print to stdout\n\ together; however, only one will consume from stdin.\n\n\ This interpreter also will interpret doublefunge when passed the '-d' flag.\ For\nexample:\n\n\ runbefunge -d my_prog.df\n\n\ will interpret my_prog.df. Doublefunge is like befunge, but also has a second\n\ instruction pointer that starts at (24,79) pointing left. This is called the\n\ secondary pointer. The primary pointer always executes its command first, \ before\nthe secondary, but otherwise behaves the same as the primary pointer. \ Each\npointer has a string mode that is independant of the other, meaning that \ if the\nprimary pointer enters string mode, the secondary pointer will still \ read its\ncommands normally, unless of course the secondary pointer is also in \ string\nmode."
llllllllll/befunge
Befunge.hs
gpl-2.0
7,634
131
14
1,776
2,828
1,497
1,331
-1
-1
main = do let a = "hell" b = "yeah" putStrLn $ a ++ " " ++ b
softwaremechanic/Miscellaneous
Haskell/8.hs
gpl-2.0
71
0
9
28
35
17
18
4
1
{-# LANGUAGE CPP #-} {- Copyright (C) 2009 John MacFarlane <[email protected]> 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -} {- Functions for loading plugins. -} module Network.Gitit.Plugins ( loadPlugin, loadPlugins ) where import Network.Gitit.Types import System.FilePath (takeBaseName) import Control.Monad (unless) import System.Log.Logger (logM, Priority(..)) #ifdef _PLUGINS import Data.List (isInfixOf, isPrefixOf) import GHC import GHC.Paths import Unsafe.Coerce loadPlugin :: FilePath -> IO Plugin loadPlugin pluginName = do logM "gitit" WARNING ("Loading plugin '" ++ pluginName ++ "'...") runGhc (Just libdir) $ do dflags <- getSessionDynFlags setSessionDynFlags $ dflags{ hscTarget = HscInterpreted , ghcLink = LinkInMemory , ghcMode = CompManager } defaultCleanupHandler dflags $ do -- initDynFlags unless ("Network.Gitit.Plugin." `isPrefixOf` pluginName) $ do addTarget =<< guessTarget pluginName Nothing r <- load LoadAllTargets case r of Failed -> error $ "Error loading plugin: " ++ pluginName Succeeded -> return () let modName = if "Network.Gitit.Plugin" `isPrefixOf` pluginName then pluginName else if "Network/Gitit/Plugin/" `isInfixOf` pluginName then "Network.Gitit.Plugin." ++ pluginName else pluginName #if MIN_VERSION_ghc(7,4,0) pr <- parseImportDecl "import Prelude" i <- parseImportDecl "import Network.Gitit.Interface" m <- parseImportDecl ("import " ++ modName) setContext [IIDecl m, IIDecl i, IIDecl pr] #else pr <- findModule (mkModuleName "Prelude") Nothing i <- findModule (mkModuleName "Network.Gitit.Interface") Nothing m <- findModule (mkModuleName modName) Nothing #if MIN_VERSION_ghc(7,2,0) setContext [IIModule m, IIModule i, IIModule pr] [] #elif MIN_VERSION_ghc(7,0,0) setContext [] [(m, Nothing), (i, Nothing), (pr, Nothing)] #else setContext [] [m, i, pr] #endif #endif value <- compileExpr (modName ++ ".plugin :: Plugin") let value' = (unsafeCoerce value) :: Plugin return value' #else loadPlugin :: FilePath -> IO Plugin loadPlugin pluginName = do error $ "Cannot load plugin '" ++ pluginName ++ "'. gitit was not compiled with plugin support." return undefined #endif loadPlugins :: [FilePath] -> IO [Plugin] loadPlugins pluginNames = do plugins' <- mapM loadPlugin pluginNames unless (null pluginNames) $ logM "gitit" WARNING "Finished loading plugins." return plugins'
mduvall/gitit
Network/Gitit/Plugins.hs
gpl-2.0
3,316
0
20
780
480
250
230
16
1
-- Test the core operations module Tests.Core where import Yi.Core import Yi.Window import Yi.Editor import Yi.Buffer import Data.Char import Data.List import Data.Maybe import System.Directory import System.IO.Unsafe import Control.Monad import qualified Control.Exception import Control.Concurrent import GHC.Exception ( Exception(ExitException) ) import TestFramework -- interesting window state getW :: IO [Int] getW = withWindow $ \w b -> do p <- pointB b let q = pnt w (i,j) = cursor w ln = lineno w tp = tospnt w tln = toslineno w return (w, [p,q,i,j,ln,tp,tln]) $(tests "core" [d| testQuit = do v <- Control.Exception.catch (quitE >> return False {- shouldn't return! -}) (\e -> return $ case e of ExitException _ -> True _ -> False) assert v testNopE = do v <- return () assertEqual () v testTopE = do emptyE >> fnewE "data" topE v <- getW (execB Move VLine Forward) u <- getW (execB Move VLine Backward) v' <- getW assertEqual [0,0,0,0,1,0,1] v assertEqual v v' assertEqual [76,76,1,0,2,0,1] u testBotE = do emptyE >> fnewE "data" botE >> moveToSol v <- getW (execB Move VLine Backward) (execB Move VLine Backward) >> moveToSol u <- getW assertEqual [256927,256927,30,0,3926,255597,3896] v assertEqual u v testSolEolE = do emptyE >> fnewE "data" gotoLn 20 moveToSol v <- getW moveToEol u <- getW moveToSol v' <- getW moveToEol u' <- getW assertEqual v v' assertEqual u u' testGotoLnE = do emptyE >> fnewE "data" ws <- sequence [ gotoLn i >> getW >>= \i -> return (i !! 4) | i <- [1 .. 3926] ] assertEqual [1..3926] ws testGotoLnFromE = do emptyE >> fnewE "data" ws <- sequence [ do gotoLn i gotoLnFromE 2 i <- getW return (i !! 4) | i <- [1 .. 3925] ] assertEqual ([2..3925]++[3925]) ws testGotoPointE = do emptyE >> fnewE "data" gotoPointE 100000 i <- getSelectionMarkPointB v <- getW assertEqual i 100000 assertEqual [100000,100000,30,6,1501,97850,1471] v testAtSolE = do emptyE >> fnewE "data" impure <- sequence [ gotoPointE i >> atSolE | i <- [ 100000 .. 100100 ] ] flip assertEqual impure [False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,True,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False,False] |])
codemac/yi-editor
attic/testsuite/Tests/Core.hs
gpl-2.0
3,028
0
12
751
224
128
96
-1
-1
module Yesod.Auth.Shibboleth (module Yesod.Auth.Shibboleth, module Yesod.Auth.Shibboleth.Type ) where import Control.Monad ((>>=), return, when) import Control.Monad.Trans.Class (lift) import Data.Bool (Bool (False), (||)) import Data.Char (toUpper) import Data.Eq ((==), (/=)) import Data.Function (($), (.)) import qualified Data.List as L (length) import Data.Maybe (Maybe (Just, Nothing), maybe) import Data.Monoid ((<>)) import System.IO (IO) import Data.Ord ((<)) import Data.Text (cons, empty, head, length, pack, split, tail) import Data.Text.Encoding (decodeUtf8) import Text.Blaze.Html (Html, toHtml) import Text.Show (show) import Yesod.Auth (AuthPlugin (AuthPlugin), AuthRoute, Creds (Creds), Route, YesodAuth, loginDest, setCreds) import Yesod.Core (getRouteToParent, defaultLayout) import Yesod.Core.Handler (getYesod, lookupHeader, notFound, provideRep, redirect, selectRep, setMessage) import Yesod.Core.Widget (WidgetT, handlerToWidget) import Yesod.Auth.Shibboleth.Type authShibboleth :: (YesodAuth m, YesodAuthShibboleth m) => AuthPlugin m authShibboleth = AuthPlugin "shibboleth" dispatch $ \tp -> getLogin tp where dispatch "GET" ["login"] = getRouteToParent >>= lift . selectRep . provideRep . defaultLayout . getLogin dispatch _ _ = notFound getLogin :: (YesodAuth master, YesodAuthShibboleth master) => (AuthRoute -> Route master) -> WidgetT master IO () getLogin _tp = do midp <- lookupHeader' "X-Shibboleth-Identity-Provider" idp <- maybe (redirectWith "Login Failed. Sure, you successfuly logged in via Shibboleth? Because there was no Identity Provider provided.") return midp school <- handlerToWidget $ getSchoolByName $ decodeUtf8 idp meppn <- lookupHeader' "X-Shibboleth-Eppn" eppn <- maybe getAnonymousLogin return meppn --eppn <- maybe (redirectWith "missing shibboleth attribute: eduPersonPrincipalName") return meppn let eppn' = split (== '@') $ decodeUtf8 eppn [loginname,institute] = eppn' when (L.length eppn' /= 2 || length institute < 2) $ redirectWith "Malformed eppn" --schulen <- handlerToWidget $ runDB $ selectList [SchuleMailSuffix ==. Just suffix] [] let vorname = cons (toUpper $ head loginname) empty name = cons (toUpper $ head $ tail loginname) $ tail $ tail loginname mstudent <- handlerToWidget $ getAccountByEppn school $ decodeUtf8 eppn maffiliation <- lookupHeader' "X-Shibboleth-Affiliation" student <- maybe (redirectWith "Login Failed - Could not create Student") return mstudent handlerToWidget $ setCreds False $ Creds "shibboleth" (pack $ show student) [] redirectWith "Logged In" getAnonymousLogin :: (YesodAuth master) => WidgetT master IO a getAnonymousLogin = do handlerToWidget $ setCreds False $ Creds "shibboleth" "-1" [] redirectWith "Logged in anonymously" redirectWith :: (YesodAuth master) => Html -> WidgetT master IO a redirectWith message = do autotool <- getYesod setMessage message redirect $ loginDest autotool --lookupHeader' :: CI ByteString -> WidgetT master IO (Maybe ByteString) lookupHeader' h = do h' <- lookupHeader h case h' of Just "(null)" -> return Nothing h'' -> return h''
marcellussiegburg/autotool
yesod/Yesod/Auth/Shibboleth.hs
gpl-2.0
3,158
0
15
488
936
507
429
59
2
module Irc.Listen ( listen , motdHandler ) where import Data.List.Split import Control.Monad import Control.Monad.Reader import Network import System.Exit import System.IO import Text.Printf import App.Commands import App.Data import App.Functions import Irc.Write motdHandler :: Handle -> Net () motdHandler handle = do line <- io $ hGetLine handle io $ printf "<- (Awaiting MOTD) %s\n" line pongHandler handle line if (words line !! 1 == "376") then do io $ putStrLn "MOTD RECEIVED" return () else do motdHandler handle listen :: Handle -> [(String, String)] -> Net () listen handle vars = do line <- io (hGetLine handle) io $ printf "<- %s\n" line pongHandler handle line newVars <- commandHandler handle (words line) vars let _quit = getVar "unset" "_quit" newVars if _quit == "set" then io $ exitWith ExitSuccess else return () listen handle newVars pongHandler :: Handle -> String -> Net () pongHandler handle line = do if words line !! 0 == "PING" then write "PONG" (words line !! 1) else return () commandHandler :: Handle -> [String] -> [(String, String)] -> Net [(String, String)] commandHandler handle (ident:irccmd:from:(_:command):message) vars = case (lookup command commandList) of (Just action) -> action (unwords ([ident,irccmd,from])) (unwords message) vars (_) -> return $ junkVar vars commandHandler handle ((_:ident):"JOIN":xs) vars = do adminFile <- asks adminFn chan <- asks chan r <- isAdmin adminFile (extractUsername ident) if r then write "MODE" (chan ++ " +o " ++ (head $ splitOn "!" ident)) else return () -- return messages fischbotnick <- asks nick if (head $ splitOn "!" ident) /= fischbotnick then returnMessages (":" ++ ident) True vars else return $ junkVar vars commandHandler _ _ vars = return $ junkVar vars
flyingfisch/haskell-fischbot
Irc/Listen.hs
gpl-2.0
1,965
0
13
495
728
364
364
53
4
module Main where import Util (palindrome) import Data.List (sort) main :: IO () main = let products = [x*y | x <- [100..999], y <- [100..999]] palindromeNum n = palindrome $ show n palindromes = filter palindromeNum products largest = last $ sort palindromes in print largest
liefswanson/projectEuler
app/p1/q4/Main.hs
gpl-2.0
353
0
12
123
121
64
57
12
1
module Handler.LibraryItemEdit where import Import -- | Display a Form to Edit a LibraryItem. getLibraryItemEditR :: LibraryItemId -> Handler Html getLibraryItemEditR libraryItemId = do item <- runDB $ get404 libraryItemId book <- runDB . getJust $ libraryItemBook item (widget, enctype) <- generateFormPost $ libraryItemEditForm item defaultLayout $ do setTitle $ "Editing " `mappend` toHtml (bookTitle book) $(widgetFile "library/libraryEdit") -- | Process the LibraryItem Editing Form. postLibraryItemEditR :: LibraryItemId -> Handler Html postLibraryItemEditR libraryItemId = do item <- runDB $ get404 libraryItemId book <- runDB . getJust $ libraryItemBook item ((result, widget), enctype) <- runFormPost $ libraryItemEditForm item case result of FormSuccess updatedItem -> runDB (replace libraryItemId $ setHasFinished updatedItem) >> setMessage "Successfully updated your Library Book" >> redirect LibraryR _ -> defaultLayout $ do setTitle $ "Editing " `mappend` toHtml (bookTitle book) $(widgetFile "library/libraryEdit") where setHasFinished i | libraryItemCompletionCount i == 0 = i { libraryItemHasFinished = False } | otherwise = i { libraryItemHasFinished = True }
prikhi/MyBookList
Handler/LibraryItemEdit.hs
gpl-3.0
1,446
0
16
426
337
162
175
25
2
(>=>) :: (a -> Writer b) -> (b -> Writer c) -> (a -> Writer c) m1 >=> m2 = \x -> let (y, s1) = m1 x (z, s2) = m2 y in (z, s1 ++ s2)
hmemcpy/milewski-ctfp-pdf
src/content/1.8/code/haskell/snippet17.hs
gpl-3.0
148
0
10
54
108
56
52
5
1
{-# OPTIONS_GHC -cpp -pgmP "cpphs --layout --hashes --cpp" #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE BangPatterns #-} {-# LANGUAGE PackageImports #-} {- | Internal module providing access to some functionality of cpphs. -} -- -- Copyright (c) 2009-2022 Stefan Wehr - http://www.stefanwehr.de -- -- 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. -- -- 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 -- module Test.Framework.Preprocessor ( transform, progName, preprocessorTests, TransformOptions(..) ) where -- import Debug.Trace import Control.Monad import Data.Char import Language.Preprocessor.Cpphs ( runCpphsPass1, runCpphsPass2, CpphsOptions(..), BoolOptions(..), defaultCpphsOptions, WordStyle(..), Posn, filename, lineno, newfile, tokenise ) import System.IO ( hPutStrLn, stderr ) #if MIN_VERSION_HUnit(1,4,0) import Test.HUnit hiding (State) #else import Test.HUnit hiding (State, Location) #endif import Control.Monad.State.Strict import qualified Data.List as List import Data.Maybe import Test.Framework.Location _DEBUG_ :: Bool _DEBUG_ = False progName :: String progName = "htfpp" htfModule :: String htfModule = "Test.Framework" mkName varName fullModuleName = "htf_" ++ map (\c -> if c == '.' then '_' else c) (fullModuleName ++ "." ++ (case varName of 'h':'t':'f':'_':s -> s s -> s)) thisModulesTestsFullName :: String -> String thisModulesTestsFullName = mkName thisModulesTestsName importedTestListFullName :: String -> String importedTestListFullName = mkName importedTestListName thisModulesTestsName :: String thisModulesTestsName = "htf_thisModulesTests" importedTestListName :: String importedTestListName = "htf_importedTests" nameDefines :: ModuleInfo -> [(String, String)] nameDefines info = [(thisModulesTestsName, thisModulesTestsFullName (mi_moduleNameWithDefault info)), (importedTestListName, importedTestListFullName (mi_moduleNameWithDefault info))] data ModuleInfo = ModuleInfo { mi_htfPrefix :: String , mi_htfImports :: [ImportDecl] , mi_defs :: [Definition] , mi_moduleName :: Maybe String } deriving (Show, Eq) mi_moduleNameWithDefault :: ModuleInfo -> String mi_moduleNameWithDefault = fromMaybe "Main" . mi_moduleName data ImportDecl = ImportDecl { imp_moduleName :: Name , imp_qualified :: Bool , imp_alias :: Maybe Name , imp_loc :: Location } deriving (Show, Eq) data Definition = TestDef String Location String | PropDef String Location String deriving (Eq, Show) type Name = String type PMA a = State ModuleInfo a setModName :: String -> PMA () setModName name = do oldName <- gets mi_moduleName when (isNothing oldName) $ modify $ \mi -> mi { mi_moduleName = Just name } addTestDef :: String -> String -> Location -> PMA () addTestDef name fullName loc = modify $ \mi -> mi { mi_defs = (TestDef name loc fullName) : mi_defs mi } addPropDef :: String -> String -> Location -> PMA () addPropDef name fullName loc = modify $ \mi -> mi { mi_defs = (PropDef name loc fullName) : mi_defs mi } addHtfImport :: ImportDecl -> PMA () addHtfImport decl = modify $ \mi -> mi { mi_htfImports = decl : mi_htfImports mi } setTestFrameworkImport :: String -> PMA () setTestFrameworkImport name = modify $ \mi -> mi { mi_htfPrefix = name } data Tok = TokModule | TokQname Location String | TokName Location Bool String | TokHtfImport Location | TokImport Location transWordStyles :: [WordStyle] -> [Tok] transWordStyles styles = loop styles True where loop styles startOfLine = case styles of [] -> [] Ident pos name : rest -> case name of "module" -> TokModule : loop rest False "import" -> case dropWhite rest of Other "{-@ HTF_TESTS @-}" : rest2 -> TokHtfImport (posToLocation pos) : loop rest2 False _ -> TokImport (posToLocation pos) : loop rest False _ -> case parseQname rest of ([], rest2) -> TokName (posToLocation pos) startOfLine name : loop rest2 False (nameParts, rest2) -> TokQname (posToLocation pos) (List.intercalate "." (name:nameParts)) : loop rest2 False Other str : rest -> let startOfLine = case reverse str of '\n':_ -> True _ -> False in loop rest startOfLine Cmd _ : rest -> loop rest False dropWhite styles = case styles of Other str : rest -> case dropWhile isSpace str of [] -> dropWhite rest str' -> Other str' : rest _ -> styles parseQname styles = case styles of Other "." : Ident _ name : rest -> let (restParts, rest2) = parseQname rest in (name:restParts, rest2) _ -> ([], styles) posToLocation pos = makeLoc (filename pos) (lineno pos) poorManAnalyzeTokens :: [WordStyle] -> ModuleInfo poorManAnalyzeTokens styles = let toks = transWordStyles styles revRes = execState (loop toks) $ ModuleInfo { mi_htfPrefix = htfModule ++ "." , mi_htfImports = [] , mi_defs = [] , mi_moduleName = Nothing } in ModuleInfo { mi_htfPrefix = mi_htfPrefix revRes , mi_htfImports = reverse (mi_htfImports revRes) , mi_defs = reverse $ List.nubBy defEqByName (mi_defs revRes) , mi_moduleName = mi_moduleName revRes } where defEqByName (TestDef n1 _ _) (TestDef n2 _ _) = n1 == n2 defEqByName (PropDef n1 _ _) (PropDef n2 _ _) = n1 == n2 defEqByName _ _ = False loop toks = case toks of TokModule : TokQname _ name : rest -> do setModName name loop rest TokModule : TokName _ _ name : rest -> do setModName name loop rest TokName loc startOfLine name : rest | startOfLine -> case name of 't':'e':'s':'t':'_':shortName -> do addTestDef shortName name loc loop rest 'p':'r':'o':'p':'_':shortName -> do addPropDef shortName name loc loop rest _ -> loop rest | otherwise -> loop rest TokHtfImport loc : rest -> case parseImport loc rest of Just (imp, rest2) -> do addHtfImport imp loop rest2 Nothing -> loop rest TokImport loc : rest -> do case parseImport loc rest of Nothing -> loop rest Just (imp, rest2) -> do when (imp_moduleName imp == htfModule) $ let prefix = case (imp_alias imp, imp_qualified imp) of (Just alias, True) -> alias (Nothing, True) -> imp_moduleName imp _ -> "" in setTestFrameworkImport (if null prefix then prefix else prefix ++ ".") loop rest2 _ : rest -> loop rest [] -> return () parseImport loc toks = do let (qualified, toks2) = case toks of TokName _ _ "qualified" : rest -> (True, rest) _ -> (False, toks) (name, toks3) <- case toks2 of TokName _ _ name : rest -> return (name, rest) TokQname _ name : rest -> return (name, rest) _ -> fail "no import" let (mAlias, toks4) = case toks3 of TokName _ _ "as" : TokName _ _ alias : rest -> (Just alias, rest) _ -> (Nothing, toks3) decl = ImportDecl { imp_moduleName = name , imp_qualified = qualified , imp_alias = mAlias , imp_loc = loc } return (decl, toks4) analyze :: FilePath -> String -> IO (ModuleInfo, [WordStyle], [(Posn,String)]) analyze originalFileName input = do xs <- runCpphsPass1 cpphsOptions originalFileName input let bopts = boolopts cpphsOptions toks = tokenise (stripEol bopts) (stripC89 bopts) (ansi bopts) (lang bopts) ((newfile "preDefined",""):xs) mi = poorManAnalyzeTokens toks return (mi, toks, xs) analyzeTests = [(unlines ["module FOO where" ,"import Test.Framework" ,"import {-@ HTF_TESTS @-} qualified Foo as Bar" ,"import {-@ HTF_TESTS @-} qualified Foo.X as Egg" ,"import {-@ HTF_TESTS @-} Foo.Y as Spam" ,"import {-@ HTF_TESTS @-} Foo.Z" ,"import {-@ HTF_TESTS @-} Baz" ,"deriveSafeCopy 1 'base ''T" ,"$(deriveSafeCopy 2 'extension ''T)" ,"test_blub test_foo = 1" ,"test_blah test_foo = '\''" ,"prop_abc prop_foo = 2" ,"prop_xyz = True"] ,ModuleInfo { mi_htfPrefix = "" , mi_htfImports = [ImportDecl { imp_moduleName = "Foo" , imp_qualified = True , imp_alias = Just "Bar" , imp_loc = makeLoc "<input>" 3} ,ImportDecl { imp_moduleName = "Foo.X" , imp_qualified = True , imp_alias = Just "Egg" , imp_loc = makeLoc "<input>" 4} ,ImportDecl { imp_moduleName = "Foo.Y" , imp_qualified = False , imp_alias = Just "Spam" , imp_loc = makeLoc "<input>" 5} ,ImportDecl { imp_moduleName = "Foo.Z" , imp_qualified = False , imp_alias = Nothing , imp_loc = makeLoc "<input>" 6} ,ImportDecl { imp_moduleName = "Baz" , imp_qualified = False , imp_alias = Nothing , imp_loc = makeLoc "<input>" 7}] , mi_moduleName = Just "FOO" , mi_defs = [TestDef "blub" (makeLoc "<input>" 10) "test_blub" ,TestDef "blah" (makeLoc "<input>" 11) "test_blah" ,PropDef "abc" (makeLoc "<input>" 12) "prop_abc" ,PropDef "xyz" (makeLoc "<input>" 13) "prop_xyz"] }) ,(unlines ["module Foo.Bar where" ,"import Test.Framework as Blub" ,"prop_xyz = True"] ,ModuleInfo { mi_htfPrefix = "" , mi_htfImports = [] , mi_moduleName = Just "Foo.Bar" , mi_defs = [PropDef "xyz" (makeLoc "<input>" 3) "prop_xyz"] }) ,(unlines ["module Foo.Bar where" ,"import qualified Test.Framework as Blub" ,"prop_xyz = True"] ,ModuleInfo { mi_htfPrefix = "Blub." , mi_htfImports = [] , mi_moduleName = Just "Foo.Bar" , mi_defs = [PropDef "xyz" (makeLoc "<input>" 3) "prop_xyz"] }) ,(unlines ["module Foo.Bar where" ,"import qualified Test.Framework" ,"prop_xyz = True"] ,ModuleInfo { mi_htfPrefix = "Test.Framework." , mi_htfImports = [] , mi_moduleName = Just "Foo.Bar" , mi_defs = [PropDef "xyz" (makeLoc "<input>" 3) "prop_xyz"] })] testAnalyze = do mapM_ runTest (zip [1..] analyzeTests) where runTest (i, (src, mi)) = do (givenMi, _, _) <- analyze "<input>" src if givenMi == mi then return () else assertFailure ("Error in test " ++ show i ++ ", expected:\n" ++ show mi ++ "\nGiven:\n" ++ show givenMi ++ "\nSrc:\n" ++ src) cpphsOptions :: CpphsOptions cpphsOptions = defaultCpphsOptions { boolopts = (boolopts defaultCpphsOptions) { lang = True } -- lex as haskell } data TransformOptions = TransformOptions { debug :: Bool , literateTex :: Bool } transform :: TransformOptions -> FilePath -> String -> IO String transform (TransformOptions debug literateTex) originalFileName input = do (info, toks, pass1) <- analyze originalFileName fixedInput preprocess info toks pass1 where preprocess info toks pass1 = do when debug $ do hPutStrLn stderr ("Tokens: " ++ show toks) hPutStrLn stderr ("Module info:\n" ++ show info) let opts = mkOptionsForModule info preProcessedInput <- runCpphsPass2 (boolopts opts) (defines opts) originalFileName pass1 return $ preProcessedInput ++ "\n\n" ++ possiblyWrap literateTex (additionalCode info) ++ "\n" -- fixedInput serves two purposes: -- 1. add a trailing \n -- 2. turn lines of the form '# <number> "<filename>"' into line directives '#line <number> <filename>' -- (see http://gcc.gnu.org/onlinedocs/cpp/Preprocessor-Output.html#Preprocessor-Output). fixedInput :: String fixedInput = (unlines . map fixLine . lines) input where fixLine s = case parseCppLineInfoOut s of Just (line, fileName) -> "#line " ++ line ++ " " ++ fileName _ -> s mkOptionsForModule :: ModuleInfo -> CpphsOptions mkOptionsForModule info = defaultCpphsOptions { defines = defines defaultCpphsOptions ++ nameDefines info , boolopts = (boolopts defaultCpphsOptions) { lang = True } -- lex as haskell } possiblyWrap :: Bool -> String -> String possiblyWrap b s = if b then "\\begin{code}\n" ++ s ++ "\\end{code}" else s additionalCode :: ModuleInfo -> String additionalCode info = thisModulesTestsFullName (mi_moduleNameWithDefault info) ++ " :: " ++ mi_htfPrefix info ++ "TestSuite\n" ++ thisModulesTestsFullName (mi_moduleNameWithDefault info) ++ " = " ++ mi_htfPrefix info ++ "makeTestSuite" ++ " " ++ show (mi_moduleNameWithDefault info) ++ " [\n" ++ List.intercalate ",\n" (map (codeForDef (mi_htfPrefix info)) (mi_defs info)) ++ "\n ]\n" ++ importedTestListCode info codeForDef :: String -> Definition -> String codeForDef pref (TestDef s loc name) = locPragma loc ++ pref ++ "makeUnitTest " ++ (show s) ++ " " ++ codeForLoc pref loc ++ " " ++ name codeForDef pref (PropDef s loc name) = locPragma loc ++ pref ++ "makeQuickCheckTest " ++ (show s) ++ " " ++ codeForLoc pref loc ++ " (" ++ pref ++ "qcAssertion " ++ name ++ ")" locPragma :: Location -> String locPragma loc = "{-# LINE " ++ show (lineNumber loc) ++ " " ++ show (fileName loc) ++ " #-}\n " codeForLoc :: String -> Location -> String codeForLoc pref loc = "(" ++ pref ++ "makeLoc " ++ show (fileName loc) ++ " " ++ show (lineNumber loc) ++ ")" importedTestListCode :: ModuleInfo -> String importedTestListCode info = let l = mi_htfImports info in case l of [] -> "" _ -> (importedTestListFullName (mi_moduleNameWithDefault info) ++ " :: [" ++ mi_htfPrefix info ++ "TestSuite]\n" ++ importedTestListFullName (mi_moduleNameWithDefault info) ++ " = [\n " ++ List.intercalate ",\n " (map htfTestsInModule l) ++ "\n ]\n") htfTestsInModule :: ImportDecl -> String htfTestsInModule imp = qualify imp (thisModulesTestsFullName (imp_moduleName imp)) qualify :: ImportDecl -> String -> String qualify imp name = case (imp_qualified imp, imp_alias imp) of (False, _) -> name (True, Just alias) -> alias ++ "." ++ name (True, _) -> imp_moduleName imp ++ "." ++ name -- Returns for lines of the form '# <number> "<filename>"' -- (see http://gcc.gnu.org/onlinedocs/cpp/Preprocessor-Output.html#Preprocessor-Output) -- the value 'Just <number> "<filename>"' parseCppLineInfoOut :: String -> Maybe (String, String) parseCppLineInfoOut line = case line of '#':' ':c:rest | isDigit c -> case List.span isDigit rest of (restDigits, ' ' : '"' : rest) -> case dropWhile (/= '"') (reverse rest) of '"' : fileNameRev -> let line = (c:restDigits) file = "\"" ++ reverse fileNameRev ++ "\"" in Just (line, file) _ -> Nothing _ -> Nothing _ -> Nothing preprocessorTests = [("testAnalyze", testAnalyze)]
skogsbaer/HTF
Test/Framework/Preprocessor.hs
lgpl-2.1
19,317
0
26
7,547
4,414
2,320
2,094
375
20
module GHC.Vacuum.ClosureType.V708 ( ClosureType(..) ) where data ClosureType = INVALID_OBJECT | CONSTR | CONSTR_1_0 | CONSTR_0_1 | CONSTR_2_0 | CONSTR_1_1 | CONSTR_0_2 | CONSTR_STATIC | CONSTR_NOCAF_STATIC | FUN | FUN_1_0 | FUN_0_1 | FUN_2_0 | FUN_1_1 | FUN_0_2 | FUN_STATIC | THUNK | THUNK_1_0 | THUNK_0_1 | THUNK_2_0 | THUNK_1_1 | THUNK_0_2 | THUNK_STATIC | THUNK_SELECTOR | BCO | AP | PAP | AP_STACK | IND | IND_PERM | IND_STATIC | RET_BCO | RET_SMALL | RET_BIG | RET_FUN | UPDATE_FRAME | CATCH_FRAME | UNDERFLOW_FRAME | STOP_FRAME | BLOCKING_QUEUE | BLACKHOLE | MVAR_CLEAN | MVAR_DIRTY | TVAR | ARR_WORDS | MUT_ARR_PTRS_CLEAN | MUT_ARR_PTRS_DIRTY | MUT_ARR_PTRS_FROZEN0 | MUT_ARR_PTRS_FROZEN | MUT_VAR_CLEAN | MUT_VAR_DIRTY | WEAK | PRIM | MUT_PRIM | TSO | STACK | TREC_CHUNK | ATOMICALLY_FRAME | CATCH_RETRY_FRAME | CATCH_STM_FRAME | WHITEHOLE | N_CLOSURE_TYPES deriving (Eq, Ord, Show, Read) instance Enum ClosureType where fromEnum INVALID_OBJECT = 0 fromEnum CONSTR = 1 fromEnum CONSTR_1_0 = 2 fromEnum CONSTR_0_1 = 3 fromEnum CONSTR_2_0 = 4 fromEnum CONSTR_1_1 = 5 fromEnum CONSTR_0_2 = 6 fromEnum CONSTR_STATIC = 7 fromEnum CONSTR_NOCAF_STATIC = 8 fromEnum FUN = 9 fromEnum FUN_1_0 = 10 fromEnum FUN_0_1 = 11 fromEnum FUN_2_0 = 12 fromEnum FUN_1_1 = 13 fromEnum FUN_0_2 = 14 fromEnum FUN_STATIC = 15 fromEnum THUNK = 16 fromEnum THUNK_1_0 = 17 fromEnum THUNK_0_1 = 18 fromEnum THUNK_2_0 = 19 fromEnum THUNK_1_1 = 20 fromEnum THUNK_0_2 = 21 fromEnum THUNK_STATIC = 22 fromEnum THUNK_SELECTOR = 23 fromEnum BCO = 24 fromEnum AP = 25 fromEnum PAP = 26 fromEnum AP_STACK = 27 fromEnum IND = 28 fromEnum IND_PERM = 29 fromEnum IND_STATIC = 30 fromEnum RET_BCO = 31 fromEnum RET_SMALL = 32 fromEnum RET_BIG = 33 fromEnum RET_FUN = 34 fromEnum UPDATE_FRAME = 35 fromEnum CATCH_FRAME = 36 fromEnum UNDERFLOW_FRAME = 37 fromEnum STOP_FRAME = 38 fromEnum BLOCKING_QUEUE = 39 fromEnum BLACKHOLE = 40 fromEnum MVAR_CLEAN = 41 fromEnum MVAR_DIRTY = 42 fromEnum TVAR = 43 fromEnum ARR_WORDS = 44 fromEnum MUT_ARR_PTRS_CLEAN = 45 fromEnum MUT_ARR_PTRS_DIRTY = 46 fromEnum MUT_ARR_PTRS_FROZEN0 = 47 fromEnum MUT_ARR_PTRS_FROZEN = 48 fromEnum MUT_VAR_CLEAN = 49 fromEnum MUT_VAR_DIRTY = 50 fromEnum WEAK = 51 fromEnum PRIM = 52 fromEnum MUT_PRIM = 53 fromEnum TSO = 54 fromEnum STACK = 55 fromEnum TREC_CHUNK = 56 fromEnum ATOMICALLY_FRAME = 57 fromEnum CATCH_RETRY_FRAME = 58 fromEnum CATCH_STM_FRAME = 59 fromEnum WHITEHOLE = 60 fromEnum N_CLOSURE_TYPES = 61 toEnum 0 = INVALID_OBJECT toEnum 1 = CONSTR toEnum 2 = CONSTR_1_0 toEnum 3 = CONSTR_0_1 toEnum 4 = CONSTR_2_0 toEnum 5 = CONSTR_1_1 toEnum 6 = CONSTR_0_2 toEnum 7 = CONSTR_STATIC toEnum 8 = CONSTR_NOCAF_STATIC toEnum 9 = FUN toEnum 10 = FUN_1_0 toEnum 11 = FUN_0_1 toEnum 12 = FUN_2_0 toEnum 13 = FUN_1_1 toEnum 14 = FUN_0_2 toEnum 15 = FUN_STATIC toEnum 16 = THUNK toEnum 17 = THUNK_1_0 toEnum 18 = THUNK_0_1 toEnum 19 = THUNK_2_0 toEnum 20 = THUNK_1_1 toEnum 21 = THUNK_0_2 toEnum 22 = THUNK_STATIC toEnum 23 = THUNK_SELECTOR toEnum 24 = BCO toEnum 25 = AP toEnum 26 = PAP toEnum 27 = AP_STACK toEnum 28 = IND toEnum 29 = IND_PERM toEnum 30 = IND_STATIC toEnum 31 = RET_BCO toEnum 32 = RET_SMALL toEnum 33 = RET_BIG toEnum 34 = RET_FUN toEnum 35 = UPDATE_FRAME toEnum 36 = CATCH_FRAME toEnum 37 = UNDERFLOW_FRAME toEnum 38 = STOP_FRAME toEnum 39 = BLOCKING_QUEUE toEnum 40 = BLACKHOLE toEnum 41 = MVAR_CLEAN toEnum 42 = MVAR_DIRTY toEnum 43 = TVAR toEnum 44 = ARR_WORDS toEnum 45 = MUT_ARR_PTRS_CLEAN toEnum 46 = MUT_ARR_PTRS_DIRTY toEnum 47 = MUT_ARR_PTRS_FROZEN0 toEnum 48 = MUT_ARR_PTRS_FROZEN toEnum 49 = MUT_VAR_CLEAN toEnum 50 = MUT_VAR_DIRTY toEnum 51 = WEAK toEnum 52 = PRIM toEnum 53 = MUT_PRIM toEnum 54 = TSO toEnum 55 = STACK toEnum 56 = TREC_CHUNK toEnum 57 = ATOMICALLY_FRAME toEnum 58 = CATCH_RETRY_FRAME toEnum 59 = CATCH_STM_FRAME toEnum 60 = WHITEHOLE toEnum 61 = N_CLOSURE_TYPES toEnum n = error ("toEnum: ClosureType: invalid ClosureType: " ++ show n)
thoughtpolice/vacuum
src/GHC/Vacuum/ClosureType/V708.hs
lgpl-3.0
4,310
0
9
1,030
1,247
658
589
191
0
{-# OPTIONS_GHC -Wall #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeOperators #-} module FunctionTests ( functionTests ) where import Casadi.DM ( DM ) import Casadi.MX ( MX ) import Casadi.SX ( SX ) import qualified Casadi.Function as C import qualified Casadi.Matrix as CM import qualified Data.Map as M import Data.Proxy ( Proxy(..) ) import qualified Data.Vector as V import Linear ( V2(..), V3(..) ) import qualified Test.HUnit.Base as HUnit import Test.Framework ( Test, testGroup ) import Test.Framework.Providers.HUnit ( testCase ) import Dyno.View testFun :: forall a . CM.SMatrix a => String -> Proxy a -> Test testFun name _ = testCase ("simple fun " ++ name) $ HUnit.assert $ do f <- toFun "simple_fun" ((42 *) :: S a -> S a) mempty out <- callDM f 2.2 return $ HUnit.assertEqual "" (42 * 2.2) out testFunction :: forall a . CM.SMatrix a => String -> Proxy a -> Test testFunction name _ = testCase ("simple function " ++ name) $ HUnit.assert $ do x <- CM.sym "x" 1 1 :: IO a let y = 42 * x f <- CM.toFunction "simple_sx_function" (V.singleton x) (V.singleton y) M.empty out <- C.callDM f (V.singleton 2.2) return $ HUnit.assertEqual "" (V.fromList [42 * 2.2] :: V.Vector DM) out testJacobian :: forall a . CM.SMatrix a => String -> Proxy a -> Test testJacobian name _ = testCase ("jacobian " ++ name) $ HUnit.assert $ do let f :: (J (JV V2) :*: J (JV V3)) a -> (M (JTuple (JV V2) (JV V2)) (JV V2) :*: J (JV V2) :*: J (JV V3)) a f (xj :*: x) = (jacobian obj xj) :*: (2 * xj) :*: (3 * x) where obj :: J (JTuple (JV V2) (JV V2)) a obj = cat $ JTuple (2 * xj) (3*xj) fun <- toFun "f" f mempty o0 :*: o1 :*: o2 <- callDM fun (vcat (V2 2 3) :*: vcat (V3 4 5 6)) return $ HUnit.assertEqual "" "(\n[[2, 00], \n [00, 2], \n [3, 00], \n [00, 3]],[4, 6],[12, 15, 18])" (show (o0, o1, o2)) testHessian :: forall a . CM.SMatrix a => String -> Proxy a -> Test testHessian name _ = testCase ("hessian " ++ name) $ HUnit.assert $ do let f :: (J (JV V2) :*: J (JV V3)) a -> (M (JV V2) (JV V2) :*: J (JV V2) :*: S :*: J (JV V3)) a f (xj :*: x) = hess :*: grad :*: obj :*: (2 * x) where (hess, grad) = hessian obj xj obj = 0.5 * sum1 (xj * xj) fun <- toFun "f" f mempty print fun o0 :*: o1 :*: o2 :*: o3 <- callDM fun (vcat (V2 1 2) :*: vcat (V3 1 2 3)) return $ HUnit.assertEqual "" "(\n[[1, 00], \n [00, 1]],[1, 2],2.5,[2, 4, 6])" (show (o0, o1, o2, o3)) testGradient :: forall a . CM.SMatrix a => String -> Proxy a -> Test testGradient name _ = testCase ("gradient " ++ name) $ HUnit.assert $ do let f :: (J (JV V2) :*: J (JV V3)) a -> (J (JV V2) :*: J (JV V3)) a f (xj :*: x) = gradient obj xj :*: (2 * x) where obj = 0.5 * sum1 (xj * xj) fun <- toFun "f" f mempty print fun o0 :*: o1 <- callDM fun (vcat (V2 1 2) :*: vcat (V3 1 2 3)) return $ HUnit.assertEqual "" "([1, 2],[2, 4, 6])" (show (o0, o1)) functionTests :: Test functionTests = testGroup "Function tests" [ functionTests' "SX" (Proxy :: Proxy SX) , functionTests' "MX" (Proxy :: Proxy MX) ] functionTests' :: CM.SMatrix a => String -> Proxy a -> Test functionTests' name p = testGroup name [ testFunction name p , testFun name p , testGradient name p , testJacobian name p , testHessian name p ]
ghorn/dynobud
dynobud/tests/FunctionTests.hs
lgpl-3.0
3,468
0
19
938
1,572
796
776
76
1
{-# LANGUAGE CPP #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE DeriveDataTypeable #-} #if __GLASGOW_HASKELL__ >= 704 {-# LANGUAGE DeriveGeneric #-} #endif {-# OPTIONS_HADDOCK not-home #-} ----------------------------------------------------------------------------- -- | -- Module : Numeric.Interval.NonEmpty.Internal -- Copyright : (c) Edward Kmett 2010-2014 -- License : BSD3 -- Maintainer : [email protected] -- Stability : experimental -- Portability : DeriveDataTypeable -- -- Interval arithmetic ----------------------------------------------------------------------------- module Numeric.Interval.NonEmpty.Internal ( Interval(..) , (...) , interval , whole , singleton , member , notMember , elem , notElem , inf , sup , singular , width , midpoint , distance , intersection , hull , bisect , bisectIntegral , magnitude , mignitude , contains , isSubsetOf , certainly, (<!), (<=!), (==!), (/=!), (>=!), (>!) , possibly, (<?), (<=?), (==?), (/=?), (>=?), (>?) , clamp , inflate, deflate , scale, symmetric , idouble , ifloat , iquot , irem , idiv , imod ) where import Control.Exception as Exception import Data.Data #if __GLASGOW_HASKELL__ >= 704 import GHC.Generics #endif import Prelude hiding (null, elem, notElem) import qualified Data.Semigroup -- $setup -- >>> import Test.QuickCheck.Arbitrary -- >>> import Test.QuickCheck.Gen hiding (scale) -- >>> import Test.QuickCheck.Property -- >>> import Control.Applicative -- >>> import Control.Exception -- >>> :set -XNoMonomorphismRestriction -- >>> :set -XExtendedDefaultRules -- >>> default (Integer,Double) -- >>> instance (Ord a, Arbitrary a) => Arbitrary (Interval a) where arbitrary = (...) <$> arbitrary <*> arbitrary -- >>> let memberOf xs = sized $ \n -> case n of { 0 -> pure $ inf xs; 1 -> pure $ sup xs; _ -> choose (inf xs, sup xs); } -- >>> let conservative sf f xs = forAll (choose (inf xs, sup xs)) $ \x -> (sf x) `member` (f xs) -- >>> let conservative2 sf f xs ys = forAll ((,) <$> choose (inf xs, sup xs) <*> choose (inf ys, sup ys)) $ \(x,y) -> (sf x y) `member` (f xs ys) -- >>> let conservativeExceptNaN sf f xs = forAll (choose (inf xs, sup xs)) $ \x -> isNaN (sf x) || (sf x) `member` (f xs) -- >>> let compose2 = fmap . fmap -- >>> let commutative op a b = (a `op` b) == (b `op` a) -- -- -- Eta expansion needed for GHC-7.6 -- >>> :set -fno-warn-deprecations -- >>> let elem x xs = Numeric.Interval.NonEmpty.Internal.elem x xs -- >>> let notElem x xs = Numeric.Interval.NonEmpty.Internal.notElem x xs data Interval a = I !a !a deriving ( Eq, Ord , Data , Typeable #if __GLASGOW_HASKELL__ >= 704 , Generic #if __GLASGOW_HASKELL__ >= 706 , Generic1 #endif #endif ) -- | 'Data.Semigroup.<>' is 'hull' instance Ord a => Data.Semigroup.Semigroup (Interval a) where (<>) = hull infix 3 ... negInfinity :: Fractional a => a negInfinity = (-1)/0 {-# INLINE negInfinity #-} posInfinity :: Fractional a => a posInfinity = 1/0 {-# INLINE posInfinity #-} -- the sign of a number, but as an Ordering so that we can pattern match over it. -- GT means greater than zero, etc. signum' :: (Ord a, Num a) => a -> Ordering signum' x = compare x 0 -- arguments are period, range, derivative, function, and interval -- we require that each period of the function include precisely one local minimum and one local maximum periodic :: (Num a, Ord a) => a -> Interval a -> (a -> Ordering) -> (a -> a) -> Interval a -> Interval a periodic p r _ _ x | width x > p = r periodic _ r d f (I a b) = periodic' r (d a) (d b) (f a) (f b) -- arguments are global range, derivatives at endpoints, values at endpoints periodic' :: (Ord a) => Interval a -> Ordering -> Ordering -> a -> a -> Interval a periodic' r GT GT a b | a <= b = I a b -- stays in increasing zone | otherwise = r -- goes from increasing zone, all the way through decreasing zone, and back to increasing zone periodic' r LT LT a b | a >= b = I b a -- stays in decreasing zone | otherwise = r -- goes from decreasing zone, all the way through increasing zone, and back to decreasing zone periodic' r GT _ a b = I (min a b) (sup r) -- was going up, started going down periodic' r LT _ a b = I (inf r) (max a b) -- was going down, started going up periodic' r EQ GT a b | a < b = I a b -- stays in increasing zone | otherwise = r -- goes from increasing zone, all the way through decreasing zone, and back to increasing zone periodic' r EQ LT a b | a > b = I b a -- stays in decreasing zone | otherwise = r -- goes from decreasing zone, all the way through increasing zone, and back to decreasing zone periodic' _ _ _ a b = a ... b -- precisely begins and ends at local extremes, so it's either a singleton or whole -- | Create a non-empty interval, turning it around if necessary (...) :: Ord a => a -> a -> Interval a a ... b | a <= b = I a b | otherwise = I b a {-# INLINE (...) #-} -- | Try to create a non-empty interval. interval :: Ord a => a -> a -> Maybe (Interval a) interval a b | a <= b = Just $ I a b | otherwise = Nothing -- | The whole real number line -- -- >>> whole -- -Infinity ... Infinity -- -- prop> (x :: Double) `elem` whole whole :: Fractional a => Interval a whole = I negInfinity posInfinity {-# INLINE whole #-} -- | A singleton point -- -- >>> singleton 1 -- 1 ... 1 -- -- prop> x `elem` (singleton x) -- prop> x /= y ==> y `notElem` (singleton x) singleton :: a -> Interval a singleton a = I a a {-# INLINE singleton #-} -- | The infinumum (lower bound) of an interval -- -- >>> inf (1 ... 20) -- 1 -- -- prop> min x y == inf (x ... y) -- prop> inf x <= sup x inf :: Interval a -> a inf (I a _) = a {-# INLINE inf #-} -- | The supremum (upper bound) of an interval -- -- >>> sup (1 ... 20) -- 20 -- -- prop> sup x `elem` x -- prop> max x y == sup (x ... y) -- prop> inf x <= sup x sup :: Interval a -> a sup (I _ b) = b {-# INLINE sup #-} -- | Is the interval a singleton point? -- N.B. This is fairly fragile and likely will not hold after -- even a few operations that only involve singletons -- -- >>> singular (singleton 1) -- True -- -- >>> singular (1.0 ... 20.0) -- False singular :: Ord a => Interval a -> Bool singular (I a b) = a == b {-# INLINE singular #-} instance Show a => Show (Interval a) where showsPrec n (I a b) = showParen (n > 3) $ showsPrec 3 a . showString " ... " . showsPrec 3 b -- | Calculate the width of an interval. -- -- >>> width (1 ... 20) -- 19 -- -- >>> width (singleton 1) -- 0 -- -- prop> 0 <= width x width :: Num a => Interval a -> a width (I a b) = b - a {-# INLINE width #-} -- | Magnitude -- -- >>> magnitude (1 ... 20) -- 20 -- -- >>> magnitude (-20 ... 10) -- 20 -- -- >>> magnitude (singleton 5) -- 5 -- -- prop> 0 <= magnitude x magnitude :: (Num a, Ord a) => Interval a -> a magnitude = sup . abs {-# INLINE magnitude #-} -- | \"mignitude\" -- -- >>> mignitude (1 ... 20) -- 1 -- -- >>> mignitude (-20 ... 10) -- 0 -- -- >>> mignitude (singleton 5) -- 5 -- -- prop> 0 <= mignitude x mignitude :: (Num a, Ord a) => Interval a -> a mignitude = inf . abs {-# INLINE mignitude #-} -- | Num instance for intervals. -- -- prop> conservative2 ((+) :: Double -> Double -> Double) (+) -- prop> conservative2 ((-) :: Double -> Double -> Double) (-) -- prop> conservative2 ((*) :: Double -> Double -> Double) (*) -- prop> conservative (abs :: Double -> Double) abs instance (Num a, Ord a) => Num (Interval a) where I a b + I a' b' = (a + a') ... (b + b') {-# INLINE (+) #-} I a b - I a' b' = (a - b') ... (b - a') {-# INLINE (-) #-} I a b * I a' b' = minimum [a * a', a * b', b * a', b * b'] ... maximum [a * a', a * b', b * a', b * b'] {-# INLINE (*) #-} abs x@(I a b) | a >= 0 = x | b <= 0 = negate x | otherwise = 0 ... max (- a) b {-# INLINE abs #-} signum = increasing signum {-# INLINE signum #-} fromInteger i = singleton (fromInteger i) {-# INLINE fromInteger #-} -- | Bisect an interval at its midpoint. -- -- >>> bisect (10.0 ... 20.0) -- (10.0 ... 15.0,15.0 ... 20.0) -- -- >>> bisect (singleton 5.0) -- (5.0 ... 5.0,5.0 ... 5.0) -- -- prop> let (a, b) = bisect (x :: Interval Double) in sup a == inf b -- prop> let (a, b) = bisect (x :: Interval Double) in inf a == inf x -- prop> let (a, b) = bisect (x :: Interval Double) in sup b == sup x bisect :: Fractional a => Interval a -> (Interval a, Interval a) bisect (I a b) = (I a m, I m b) where m = a + (b - a) / 2 {-# INLINE bisect #-} bisectIntegral :: Integral a => Interval a -> (Interval a, Interval a) bisectIntegral (I a b) | a == m || b == m = (I a a, I b b) | otherwise = (I a m, I m b) where m = a + (b - a) `div` 2 {-# INLINE bisectIntegral #-} -- | Nearest point to the midpoint of the interval. -- -- >>> midpoint (10.0 ... 20.0) -- 15.0 -- -- >>> midpoint (singleton 5.0) -- 5.0 -- -- prop> midpoint x `elem` (x :: Interval Double) midpoint :: Fractional a => Interval a -> a midpoint (I a b) = a + (b - a) / 2 {-# INLINE midpoint #-} -- | Hausdorff distance between intervals. -- -- >>> distance (1 ... 7) (6 ... 10) -- 0 -- -- >>> distance (1 ... 7) (15 ... 24) -- 8 -- -- >>> distance (1 ... 7) (-10 ... -2) -- 3 -- -- prop> commutative (distance :: Interval Double -> Interval Double -> Double) -- prop> 0 <= distance x y distance :: (Num a, Ord a) => Interval a -> Interval a -> a distance i1 i2 = mignitude (i1 - i2) -- | Determine if a point is in the interval. -- -- >>> member 3.2 (1.0 ... 5.0) -- True -- -- >>> member 5 (1.0 ... 5.0) -- True -- -- >>> member 1 (1.0 ... 5.0) -- True -- -- >>> member 8 (1.0 ... 5.0) -- False member :: Ord a => a -> Interval a -> Bool member x (I a b) = x >= a && x <= b {-# INLINE member #-} -- | Determine if a point is not included in the interval -- -- >>> notMember 8 (1.0 ... 5.0) -- True -- -- >>> notMember 1.4 (1.0 ... 5.0) -- False notMember :: Ord a => a -> Interval a -> Bool notMember x xs = not (member x xs) {-# INLINE notMember #-} -- | Determine if a point is in the interval. -- -- >>> elem 3.2 (1.0 ... 5.0) -- True -- -- >>> elem 5 (1.0 ... 5.0) -- True -- -- >>> elem 1 (1.0 ... 5.0) -- True -- -- >>> elem 8 (1.0 ... 5.0) -- False elem :: Ord a => a -> Interval a -> Bool elem = member {-# INLINE elem #-} {-# DEPRECATED elem "Use `member` instead." #-} -- | Determine if a point is not included in the interval -- -- >>> notElem 8 (1.0 ... 5.0) -- True -- -- >>> notElem 1.4 (1.0 ... 5.0) -- False notElem :: Ord a => a -> Interval a -> Bool notElem = notMember {-# INLINE notElem #-} {-# DEPRECATED notElem "Use `notMember` instead." #-} -- | 'realToFrac' will use the midpoint instance Real a => Real (Interval a) where toRational (I ra rb) = a + (b - a) / 2 where a = toRational ra b = toRational rb {-# INLINE toRational #-} -- @'divNonZero' X Y@ assumes @0 `'notElem'` Y@ divNonZero :: (Fractional a, Ord a) => Interval a -> Interval a -> Interval a divNonZero (I a b) (I a' b') = minimum [a / a', a / b', b / a', b / b'] ... maximum [a / a', a / b', b / a', b / b'] -- @'divPositive' X y@ assumes y > 0, and divides @X@ by [0 ... y] divPositive :: (Fractional a, Ord a) => Interval a -> a -> Interval a divPositive x@(I a b) y | a == 0 && b == 0 = x -- b < 0 || isNegativeZero b = negInfinity ... ( b / y) | b < 0 = negInfinity ... (b / y) | a < 0 = whole | otherwise = (a / y) ... posInfinity {-# INLINE divPositive #-} -- divNegative assumes y < 0 and divides the interval @X@ by [y ... 0] divNegative :: (Fractional a, Ord a) => Interval a -> a -> Interval a divNegative x@(I a b) y | a == 0 && b == 0 = - x -- flip negative zeros -- b < 0 || isNegativeZero b = (b / y) ... posInfinity | b < 0 = (b / y) ... posInfinity | a < 0 = whole | otherwise = negInfinity ... (a / y) {-# INLINE divNegative #-} divZero :: (Fractional a, Ord a) => Interval a -> Interval a divZero x@(I a b) | a == 0 && b == 0 = x | otherwise = whole {-# INLINE divZero #-} -- | Fractional instance for intervals. -- -- prop> ys /= singleton 0 ==> conservative2 ((/) :: Double -> Double -> Double) (/) xs ys -- prop> xs /= singleton 0 ==> conservative (recip :: Double -> Double) recip xs instance (Fractional a, Ord a) => Fractional (Interval a) where -- TODO: check isNegativeZero properly x / y@(I a b) | 0 `notElem` y = divNonZero x y | iz && sz = Exception.throw DivideByZero | iz = divPositive x a | sz = divNegative x b | otherwise = divZero x where iz = a == 0 sz = b == 0 fromRational r = let r' = fromRational r in I r' r' {-# INLINE fromRational #-} instance RealFrac a => RealFrac (Interval a) where properFraction x = (b, x - fromIntegral b) where b = truncate (midpoint x) {-# INLINE properFraction #-} ceiling x = ceiling (sup x) {-# INLINE ceiling #-} floor x = floor (inf x) {-# INLINE floor #-} round x = round (midpoint x) {-# INLINE round #-} truncate x = truncate (midpoint x) {-# INLINE truncate #-} -- | Transcendental functions for intervals. -- -- prop> conservative (exp :: Double -> Double) exp -- prop> conservativeExceptNaN (log :: Double -> Double) log -- prop> conservative (sin :: Double -> Double) sin -- prop> conservative (cos :: Double -> Double) cos -- prop> conservative (tan :: Double -> Double) tan -- prop> conservativeExceptNaN (asin :: Double -> Double) asin -- prop> conservativeExceptNaN (acos :: Double -> Double) acos -- prop> conservative (atan :: Double -> Double) atan -- prop> conservative (sinh :: Double -> Double) sinh -- prop> conservative (cosh :: Double -> Double) cosh -- prop> conservative (tanh :: Double -> Double) tanh -- prop> conservativeExceptNaN (asinh :: Double -> Double) asinh -- prop> conservativeExceptNaN (acosh :: Double -> Double) acosh -- prop> conservativeExceptNaN (atanh :: Double -> Double) atanh -- -- >>> cos (0 ... (pi + 0.1)) -- -1.0 ... 1.0 instance (RealFloat a, Ord a) => Floating (Interval a) where pi = singleton pi {-# INLINE pi #-} exp = increasing exp {-# INLINE exp #-} log (I a b) = (if a > 0 then log a else negInfinity) ... (if b > 0 then log b else negInfinity) {-# INLINE log #-} sin = periodic (2 * pi) (symmetric 1) (signum' . cos) sin cos = periodic (2 * pi) (symmetric 1) (signum' . negate . sin) cos tan = periodic pi whole (const GT) tan -- derivative only has to have correct sign asin (I a b) = (asin' a) ... (asin' b) where asin' x | x >= 1 = halfPi | x <= -1 = -halfPi | otherwise = asin x halfPi = pi / 2 {-# INLINE asin #-} acos (I a b) = (acos' a) ... (acos' b) where acos' x | x >= 1 = 0 | x <= -1 = pi | otherwise = acos x {-# INLINE acos #-} atan = increasing atan {-# INLINE atan #-} sinh = increasing sinh {-# INLINE sinh #-} cosh x@(I a b) | b < 0 = decreasing cosh x | a >= 0 = increasing cosh x | otherwise = I 0 $ cosh $ if - a > b then a else b {-# INLINE cosh #-} tanh = increasing tanh {-# INLINE tanh #-} asinh = increasing asinh {-# INLINE asinh #-} acosh (I a b) = (acosh' a) ... (acosh' b) where acosh' x | x <= 1 = 0 | otherwise = acosh x {-# INLINE acosh #-} atanh (I a b) = (atanh' a) ... (atanh' b) where atanh' x | x <= -1 = negInfinity | x >= 1 = posInfinity | otherwise = atanh x {-# INLINE atanh #-} -- | lift a monotone increasing function over a given interval increasing :: (a -> b) -> Interval a -> Interval b increasing f (I a b) = I (f a) (f b) -- | lift a monotone decreasing function over a given interval decreasing :: (a -> b) -> Interval a -> Interval b decreasing f (I a b) = I (f b) (f a) -- | We have to play some semantic games to make these methods make sense. -- Most compute with the midpoint of the interval. instance RealFloat a => RealFloat (Interval a) where floatRadix = floatRadix . midpoint floatDigits = floatDigits . midpoint floatRange = floatRange . midpoint decodeFloat = decodeFloat . midpoint encodeFloat m e = singleton (encodeFloat m e) exponent = exponent . midpoint significand x = min a b ... max a b where (_ ,em) = decodeFloat (midpoint x) (mi,ei) = decodeFloat (inf x) (ms,es) = decodeFloat (sup x) a = encodeFloat mi (ei - em - floatDigits x) b = encodeFloat ms (es - em - floatDigits x) scaleFloat n (I a b) = I (scaleFloat n a) (scaleFloat n b) isNaN (I a b) = isNaN a || isNaN b isInfinite (I a b) = isInfinite a || isInfinite b isDenormalized (I a b) = isDenormalized a || isDenormalized b -- contains negative zero isNegativeZero (I a b) = not (a > 0) && not (b < 0) && ( (b == 0 && (a < 0 || isNegativeZero a)) || (a == 0 && isNegativeZero a) || (a < 0 && b >= 0)) isIEEE _ = False atan2 = error "unimplemented" -- TODO: (^), (^^) to give tighter bounds -- | Calculate the intersection of two intervals. -- -- >>> intersection (1 ... 10 :: Interval Double) (5 ... 15 :: Interval Double) -- Just (5.0 ... 10.0) intersection :: Ord a => Interval a -> Interval a -> Maybe (Interval a) intersection x@(I a b) y@(I a' b') | x /=! y = Nothing | otherwise = Just $ I (max a a') (min b b') {-# INLINE intersection #-} -- | Calculate the convex hull of two intervals -- -- >>> hull (0 ... 10 :: Interval Double) (5 ... 15 :: Interval Double) -- 0.0 ... 15.0 -- -- >>> hull (15 ... 85 :: Interval Double) (0 ... 10 :: Interval Double) -- 0.0 ... 85.0 -- -- prop> conservative2 const hull -- prop> conservative2 (flip const) hull hull :: Ord a => Interval a -> Interval a -> Interval a hull (I a b) (I a' b') = I (min a a') (max b b') {-# INLINE hull #-} -- | For all @x@ in @X@, @y@ in @Y@. @x '<' y@ -- -- >>> (5 ... 10 :: Interval Double) <! (20 ... 30 :: Interval Double) -- True -- -- >>> (5 ... 10 :: Interval Double) <! (10 ... 30 :: Interval Double) -- False -- -- >>> (20 ... 30 :: Interval Double) <! (5 ... 10 :: Interval Double) -- False (<!) :: Ord a => Interval a -> Interval a -> Bool I _ bx <! I ay _ = bx < ay {-# INLINE (<!) #-} -- | For all @x@ in @X@, @y@ in @Y@. @x '<=' y@ -- -- >>> (5 ... 10 :: Interval Double) <=! (20 ... 30 :: Interval Double) -- True -- -- >>> (5 ... 10 :: Interval Double) <=! (10 ... 30 :: Interval Double) -- True -- -- >>> (20 ... 30 :: Interval Double) <=! (5 ... 10 :: Interval Double) -- False (<=!) :: Ord a => Interval a -> Interval a -> Bool I _ bx <=! I ay _ = bx <= ay {-# INLINE (<=!) #-} -- | For all @x@ in @X@, @y@ in @Y@. @x '==' y@ -- -- Only singleton intervals or empty intervals can return true -- -- >>> (singleton 5 :: Interval Double) ==! (singleton 5 :: Interval Double) -- True -- -- >>> (5 ... 10 :: Interval Double) ==! (5 ... 10 :: Interval Double) -- False (==!) :: Eq a => Interval a -> Interval a -> Bool I ax bx ==! I ay by = bx == ay && ax == by {-# INLINE (==!) #-} -- | For all @x@ in @X@, @y@ in @Y@. @x '/=' y@ -- -- >>> (5 ... 15 :: Interval Double) /=! (20 ... 40 :: Interval Double) -- True -- -- >>> (5 ... 15 :: Interval Double) /=! (15 ... 40 :: Interval Double) -- False (/=!) :: Ord a => Interval a -> Interval a -> Bool I ax bx /=! I ay by = bx < ay || ax > by {-# INLINE (/=!) #-} -- | For all @x@ in @X@, @y@ in @Y@. @x '>' y@ -- -- >>> (20 ... 40 :: Interval Double) >! (10 ... 19 :: Interval Double) -- True -- -- >>> (5 ... 20 :: Interval Double) >! (15 ... 40 :: Interval Double) -- False (>!) :: Ord a => Interval a -> Interval a -> Bool I ax _ >! I _ by = ax > by {-# INLINE (>!) #-} -- | For all @x@ in @X@, @y@ in @Y@. @x '>=' y@ -- -- >>> (20 ... 40 :: Interval Double) >=! (10 ... 20 :: Interval Double) -- True -- -- >>> (5 ... 20 :: Interval Double) >=! (15 ... 40 :: Interval Double) -- False (>=!) :: Ord a => Interval a -> Interval a -> Bool I ax _ >=! I _ by = ax >= by {-# INLINE (>=!) #-} -- | For all @x@ in @X@, @y@ in @Y@. @x `op` y@ certainly :: Ord a => (forall b. Ord b => b -> b -> Bool) -> Interval a -> Interval a -> Bool certainly cmp l r | lt && eq && gt = True | lt && eq = l <=! r | lt && gt = l /=! r | lt = l <! r | eq && gt = l >=! r | eq = l ==! r | gt = l >! r | otherwise = False where lt = cmp False True eq = cmp True True gt = cmp True False {-# INLINE certainly #-} -- | Check if interval @X@ totally contains interval @Y@ -- -- >>> (20 ... 40 :: Interval Double) `contains` (25 ... 35 :: Interval Double) -- True -- -- >>> (20 ... 40 :: Interval Double) `contains` (15 ... 35 :: Interval Double) -- False contains :: Ord a => Interval a -> Interval a -> Bool contains (I ax bx) (I ay by) = ax <= ay && by <= bx {-# INLINE contains #-} -- | Flipped version of `contains`. Check if interval @X@ a subset of interval @Y@ -- -- >>> (25 ... 35 :: Interval Double) `isSubsetOf` (20 ... 40 :: Interval Double) -- True -- -- >>> (20 ... 40 :: Interval Double) `isSubsetOf` (15 ... 35 :: Interval Double) -- False isSubsetOf :: Ord a => Interval a -> Interval a -> Bool isSubsetOf = flip contains {-# INLINE isSubsetOf #-} -- | Does there exist an @x@ in @X@, @y@ in @Y@ such that @x '<' y@? (<?) :: Ord a => Interval a -> Interval a -> Bool I ax _ <? I _ by = ax < by {-# INLINE (<?) #-} -- | Does there exist an @x@ in @X@, @y@ in @Y@ such that @x '<=' y@? (<=?) :: Ord a => Interval a -> Interval a -> Bool I ax _ <=? I _ by = ax <= by {-# INLINE (<=?) #-} -- | Does there exist an @x@ in @X@, @y@ in @Y@ such that @x '==' y@? (==?) :: Ord a => Interval a -> Interval a -> Bool I ax bx ==? I ay by = ax <= by && bx >= ay {-# INLINE (==?) #-} -- | Does there exist an @x@ in @X@, @y@ in @Y@ such that @x '/=' y@? (/=?) :: Eq a => Interval a -> Interval a -> Bool I ax bx /=? I ay by = ax /= by || bx /= ay {-# INLINE (/=?) #-} -- | Does there exist an @x@ in @X@, @y@ in @Y@ such that @x '>' y@? (>?) :: Ord a => Interval a -> Interval a -> Bool I _ bx >? I ay _ = bx > ay {-# INLINE (>?) #-} -- | Does there exist an @x@ in @X@, @y@ in @Y@ such that @x '>=' y@? (>=?) :: Ord a => Interval a -> Interval a -> Bool I _ bx >=? I ay _ = bx >= ay {-# INLINE (>=?) #-} -- | Does there exist an @x@ in @X@, @y@ in @Y@ such that @x `op` y@? possibly :: Ord a => (forall b. Ord b => b -> b -> Bool) -> Interval a -> Interval a -> Bool possibly cmp l r | lt && eq && gt = True | lt && eq = l <=? r | lt && gt = l /=? r | lt = l <? r | eq && gt = l >=? r | eq = l ==? r | gt = l >? r | otherwise = False where lt = cmp LT EQ eq = cmp EQ EQ gt = cmp GT EQ {-# INLINE possibly #-} -- | The nearest value to that supplied which is contained in the interval. -- -- prop> (clamp xs y) `elem` xs clamp :: Ord a => Interval a -> a -> a clamp (I a b) x | x < a = a | x > b = b | otherwise = x -- | Inflate an interval by enlarging it at both ends. -- -- >>> inflate 3 (-1 ... 7) -- -4 ... 10 -- -- >>> inflate (-2) (0 ... 4) -- -2 ... 6 -- -- prop> inflate x i `contains` i inflate :: (Num a, Ord a) => a -> Interval a -> Interval a inflate x y = symmetric x + y -- | Deflate an interval by shrinking it from both ends. -- Note that in cases that would result in an empty interval, the result is a singleton interval at the midpoint. -- -- >>> deflate 3.0 (-4.0 ... 10.0) -- -1.0 ... 7.0 -- -- >>> deflate 2.0 (-1.0 ... 1.0) -- 0.0 ... 0.0 deflate :: (Fractional a, Ord a) => a -> Interval a -> Interval a deflate x i@(I a b) | a' <= b' = I a' b' | otherwise = singleton m where a' = a + x b' = b - x m = midpoint i -- | Scale an interval about its midpoint. -- -- >>> scale 1.1 (-6.0 ... 4.0) -- -6.5 ... 4.5 -- -- >>> scale (-2.0) (-1.0 ... 1.0) -- -2.0 ... 2.0 -- -- prop> abs x >= 1 ==> (scale (x :: Double) i) `contains` i -- prop> forAll (choose (0,1)) $ \x -> abs x <= 1 ==> i `contains` (scale (x :: Double) i) scale :: (Fractional a, Ord a) => a -> Interval a -> Interval a scale x i = a ... b where h = x * width i / 2 mid = midpoint i a = mid - h b = mid + h -- | Construct a symmetric interval. -- -- >>> symmetric 3 -- -3 ... 3 -- -- >>> symmetric (-2) -- -2 ... 2 -- -- prop> x `elem` symmetric x -- prop> 0 `elem` symmetric x symmetric :: (Num a, Ord a) => a -> Interval a symmetric x = negate x ... x -- | id function. Useful for type specification -- -- >>> :t idouble (1 ... 3) -- idouble (1 ... 3) :: Interval Double idouble :: Interval Double -> Interval Double idouble = id -- | id function. Useful for type specification -- -- >>> :t ifloat (1 ... 3) -- ifloat (1 ... 3) :: Interval Float ifloat :: Interval Float -> Interval Float ifloat = id -- Bugs: -- sin 1 :: Interval Double default (Integer,Double) -- | an interval containing all x `quot` y -- prop> forAll (memberOf xs) $ \ x -> forAll (memberOf ys) $ \ y -> 0 `notMember` ys ==> (x `quot` y) `member` (xs `iquot` ys) -- prop> 0 `member` ys ==> ioProperty $ do z <- try (evaluate (xs `iquot` ys)); return $ z === Left DivideByZero iquot :: Integral a => Interval a -> Interval a -> Interval a iquot (I l u) (I l' u') = if l' <= 0 && 0 <= u' then throw DivideByZero else I (minimum [a `quot` b | a <- [l,u], b <- [l',u']]) (maximum [a `quot` b | a <- [l,u], b <- [l',u']]) -- | an interval containing all x `rem` y -- prop> forAll (memberOf xs) $ \ x -> forAll (memberOf ys) $ \ y -> 0 `notMember` ys ==> (x `rem` y) `member` (xs `irem` ys) -- prop> 0 `member` ys ==> ioProperty $ do z <- try (evaluate (xs `irem` ys)); return $ z === Left DivideByZero irem :: Integral a => Interval a -> Interval a -> Interval a irem (I l u) (I l' u') = if l' <= 0 && 0 <= u' then throw DivideByZero else I (minimum [0, signum l * (abs u' - 1), signum l * (abs l' - 1)]) (maximum [0, signum u * (abs u' - 1), signum u * (abs l' - 1)]) -- | an interval containing all x `div` y -- prop> forAll (memberOf xs) $ \ x -> forAll (memberOf ys) $ \ y -> 0 `notMember` ys ==> (x `div` y) `member` (xs `idiv` ys) -- prop> 0 `member` ys ==> ioProperty $ do z <- try (evaluate (xs `idiv` ys)); return $ z === Left DivideByZero idiv :: Integral a => Interval a -> Interval a -> Interval a idiv (I l u) (I l' u') = if l' <= 0 && 0 <= u' then throw DivideByZero else I (min (l `Prelude.div` max 1 l') (u `Prelude.div` min (-1) u')) (max (u `Prelude.div` max 1 l') (l `Prelude.div` min (-1) u')) -- | an interval containing all x `mod` y -- prop> forAll (memberOf xs) $ \ x -> forAll (memberOf ys) $ \ y -> 0 `notMember` ys ==> (x `mod` y) `member` (xs `imod` ys) -- prop> 0 `member` ys ==> ioProperty $ do z <- try (evaluate (xs `imod` ys)); return $ z === Left DivideByZero imod :: Integral a => Interval a -> Interval a -> Interval a imod _ (I l' u') = if l' <= 0 && 0 <= u' then throw DivideByZero else I (min (l'+1) 0) (max 0 (u'-1))
ekmett/intervals
src/Numeric/Interval/NonEmpty/Internal.hs
bsd-2-clause
27,185
0
14
6,933
6,973
3,707
3,266
411
2
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE BangPatterns #-} -- | -- Module : Statistics.Correlation.Pearson -- module Statistics.Correlation ( -- * Pearson correlation pearson , pearsonMatByRow -- * Spearman correlation , spearman , spearmanMatByRow ) where import qualified Data.Vector.Generic as G import qualified Data.Vector.Unboxed as U import Statistics.Matrix import Statistics.Sample import Statistics.Test.Internal (rankUnsorted) ---------------------------------------------------------------- -- Pearson ---------------------------------------------------------------- -- | Pearson correlation for sample of pairs. pearson :: (G.Vector v (Double, Double), G.Vector v Double) => v (Double, Double) -> Double pearson = correlation {-# INLINE pearson #-} -- | Compute pairwise pearson correlation between rows of a matrix pearsonMatByRow :: Matrix -> Matrix pearsonMatByRow m = generateSym (rows m) (\i j -> pearson $ row m i `U.zip` row m j) {-# INLINE pearsonMatByRow #-} ---------------------------------------------------------------- -- Spearman ---------------------------------------------------------------- -- | compute spearman correlation between two samples spearman :: ( Ord a , Ord b , G.Vector v a , G.Vector v b , G.Vector v (a, b) , G.Vector v Int , G.Vector v Double , G.Vector v (Double, Double) , G.Vector v (Int, a) , G.Vector v (Int, b) ) => v (a, b) -> Double spearman xy = pearson $ G.zip (rankUnsorted x) (rankUnsorted y) where (x, y) = G.unzip xy {-# INLINE spearman #-} -- | compute pairwise spearman correlation between rows of a matrix spearmanMatByRow :: Matrix -> Matrix spearmanMatByRow = pearsonMatByRow . fromRows . fmap rankUnsorted . toRows {-# INLINE spearmanMatByRow #-}
mihaimaruseac/statistics
Statistics/Correlation.hs
bsd-2-clause
1,934
0
10
450
408
235
173
43
1
{-# LANGUAGE QuasiQuotes, TemplateHaskell #-} module Language.Haskell.Preprocess.Macros(compilerMacros,stdHdrs) where import Prelude import Data.FileEmbed import Data.String.Here import Control.Arrow import qualified Data.ByteString as BS import qualified Data.Map as M import qualified Filesystem.Path as P import qualified Filesystem.Path.CurrentOS as P stdHdrs ∷ M.Map P.FilePath BS.ByteString stdHdrs = M.fromList $ map (first P.decodeString) $(embedDir "include") compilerMacros ∷ String compilerMacros = x++"\n" where x = [here| #define __GLASGOW_HASKELL__ 708 #define x86_64_HOST_ARCH 1 #define linux_HOST_OS 1 #define mingw32_HOST_OS 1 #define FLT_RADIX 2 #define HAVE_POLL 1 #define INTEGER_GMP 1 |]
sourcegraph/preprocess-haskell
src/Language/Haskell/Preprocess/Macros.hs
bsd-3-clause
766
0
9
135
141
88
53
14
1
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE ViewPatterns #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeApplications #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE FlexibleInstances #-} module Mapnik.Bindings.Projection ( projTransform , CanTransform (..) , NumPoints ) where import Mapnik (Proj4) import Mapnik.Bindings.Util import Mapnik.Bindings.Types import qualified Mapnik.Bindings.Cpp as C import Mapnik.Bindings.Orphans() import Control.Exception (try) import Data.Text.Encoding (encodeUtf8) import Foreign.ForeignPtr (FinalizerPtr) import Foreign.Marshal.Utils (with) import System.IO.Unsafe (unsafePerformIO) C.context mapnikCtx C.include "<string>" C.include "<mapnik/box2d.hpp>" C.include "<mapnik/projection.hpp>" C.include "<mapnik/proj_transform.hpp>" C.include "hs_proj_transform.hpp" C.using "namespace mapnik" C.using "bbox = box2d<double>" -- * Projection foreign import ccall "&hs_mapnik_destroy_ProjTransform" destroyProjTransform :: FinalizerPtr ProjTransform projTransform :: Proj4 -> Proj4 -> Either String ProjTransform projTransform (encodeUtf8->src) (encodeUtf8->dst) = unsafePerformIO $ fmap showExc $ try $ mkUnsafeNew ProjTransform destroyProjTransform $ \ptr -> [C.catchBlock| *$(hs_proj_transform **ptr) = new hs_proj_transform($bs-ptr:src, $bs-ptr:dst); |] where showExc = either (Left . show @MapnikError) Right class CanTransform p where forward :: ProjTransform -> p -> p backward :: ProjTransform -> p -> p instance CanTransform Box where forward p box = unsafePerformIO $ with box $ \boxPtr -> C.withPtr_ $ \ret -> [C.block|void { *$(bbox *ret) = *$(bbox *boxPtr); $fptr-ptr:(hs_proj_transform *p)->trans().forward(*$(bbox *ret)); }|] backward p box = unsafePerformIO $ with box $ \boxPtr -> C.withPtr_ $ \ret -> [C.block|void { *$(bbox *ret) = *$(bbox *boxPtr); $fptr-ptr:(hs_proj_transform *p)->trans().backward(*$(bbox *ret)); }|] type NumPoints = Int instance CanTransform (Box,NumPoints) where forward p (box, n'@(fromIntegral -> n)) = (,n') $ unsafePerformIO $ with box $ \boxPtr -> C.withPtr_ $ \ret -> [C.block|void { *$(bbox *ret) = *$(bbox *boxPtr); $fptr-ptr:(hs_proj_transform *p)->trans().forward(*$(bbox *ret), $(int n)); }|] backward p (box, n'@(fromIntegral -> n)) = (,n') $ unsafePerformIO $ with box $ \boxPtr -> C.withPtr_ $ \ret -> [C.block|void { *$(bbox *ret) = *$(bbox *boxPtr); $fptr-ptr:(hs_proj_transform *p)->trans().backward(*$(bbox *ret), $(int n)); }|]
albertov/hs-mapnik
bindings/src/Mapnik/Bindings/Projection.hs
bsd-3-clause
2,734
0
11
531
585
328
257
53
1
import Criterion.Main import Pipes import Pipes.Vector import qualified Data.Vector as VB import qualified Data.Vector.Unboxed as VU import qualified Data.Vector.Storable as VS main :: IO () main = defaultMain [ bench "VB.Vector Int" $ whnfIO (runEffect $ runToVectorP $ each [1..100000] >-> toVector :: IO (VB.Vector Int)) , bench "VU.Vector Int" $ whnfIO (runEffect $ runToVectorP $ each [1..100000] >-> toVector :: IO (VU.Vector Int)) , bench "VS.Vector Int" $ whnfIO (runEffect $ runToVectorP $ each [1..100000] >-> toVector :: IO (VS.Vector Int)) ]
bgamari/pipes-vector
Benchmark.hs
bsd-3-clause
571
0
13
100
208
112
96
11
1
-------------------------------------------------------------------------------- -- | The LLVM Type System. -- module Llvm.Types where #include "HsVersions.h" import Data.Char import Data.Int import Data.List (intercalate) import Numeric import Constants import FastString import Unique -- from NCG import PprBase -- ----------------------------------------------------------------------------- -- * LLVM Basic Types and Variables -- -- | A global mutable variable. Maybe defined or external type LMGlobal = (LlvmVar, Maybe LlvmStatic) -- | A String in LLVM type LMString = FastString -- | A type alias type LlvmAlias = (LMString, LlvmType) -- | Llvm Types data LlvmType = LMInt Int -- ^ An integer with a given width in bits. | LMFloat -- ^ 32 bit floating point | LMDouble -- ^ 64 bit floating point | LMFloat80 -- ^ 80 bit (x86 only) floating point | LMFloat128 -- ^ 128 bit floating point | LMPointer LlvmType -- ^ A pointer to a 'LlvmType' | LMArray Int LlvmType -- ^ An array of 'LlvmType' | LMLabel -- ^ A 'LlvmVar' can represent a label (address) | LMVoid -- ^ Void type | LMStruct [LlvmType] -- ^ Structure type | LMAlias LlvmAlias -- ^ A type alias -- | Function type, used to create pointers to functions | LMFunction LlvmFunctionDecl deriving (Eq) instance Show LlvmType where show (LMInt size ) = "i" ++ show size show (LMFloat ) = "float" show (LMDouble ) = "double" show (LMFloat80 ) = "x86_fp80" show (LMFloat128 ) = "fp128" show (LMPointer x ) = show x ++ "*" show (LMArray nr tp ) = "[" ++ show nr ++ " x " ++ show tp ++ "]" show (LMLabel ) = "label" show (LMVoid ) = "void" show (LMStruct tys ) = "<{" ++ (commaCat tys) ++ "}>" show (LMFunction (LlvmFunctionDecl _ _ _ r varg p _)) = let varg' = case varg of VarArgs | null args -> "..." | otherwise -> ", ..." _otherwise -> "" -- by default we don't print param attributes args = intercalate ", " $ map (show . fst) p in show r ++ " (" ++ args ++ varg' ++ ")" show (LMAlias (s,_)) = "%" ++ unpackFS s -- | An LLVM section definition. If Nothing then let LLVM decide the section type LMSection = Maybe LMString type LMAlign = Maybe Int type LMConst = Bool -- ^ is a variable constant or not -- | Llvm Variables data LlvmVar -- | Variables with a global scope. = LMGlobalVar LMString LlvmType LlvmLinkageType LMSection LMAlign LMConst -- | Variables local to a function or parameters. | LMLocalVar Unique LlvmType -- | Named local variables. Sometimes we need to be able to explicitly name -- variables (e.g for function arguments). | LMNLocalVar LMString LlvmType -- | A constant variable | LMLitVar LlvmLit deriving (Eq) instance Show LlvmVar where show (LMLitVar x) = show x show (x ) = show (getVarType x) ++ " " ++ getName x -- | Llvm Literal Data. -- -- These can be used inline in expressions. data LlvmLit -- | Refers to an integer constant (i64 42). = LMIntLit Integer LlvmType -- | Floating point literal | LMFloatLit Double LlvmType -- | Literal NULL, only applicable to pointer types | LMNullLit LlvmType -- | Undefined value, random bit pattern. Useful for optimisations. | LMUndefLit LlvmType deriving (Eq) instance Show LlvmLit where show l = show (getLitType l) ++ " " ++ getLit l -- | Llvm Static Data. -- -- These represent the possible global level variables and constants. data LlvmStatic = LMComment LMString -- ^ A comment in a static section | LMStaticLit LlvmLit -- ^ A static variant of a literal value | LMUninitType LlvmType -- ^ For uninitialised data | LMStaticStr LMString LlvmType -- ^ Defines a static 'LMString' | LMStaticArray [LlvmStatic] LlvmType -- ^ A static array | LMStaticStruc [LlvmStatic] LlvmType -- ^ A static structure type | LMStaticPointer LlvmVar -- ^ A pointer to other data -- static expressions, could split out but leave -- for moment for ease of use. Not many of them. | LMBitc LlvmStatic LlvmType -- ^ Pointer to Pointer conversion | LMPtoI LlvmStatic LlvmType -- ^ Pointer to Integer conversion | LMAdd LlvmStatic LlvmStatic -- ^ Constant addition operation | LMSub LlvmStatic LlvmStatic -- ^ Constant subtraction operation instance Show LlvmStatic where show (LMComment s) = "; " ++ unpackFS s show (LMStaticLit l ) = show l show (LMUninitType t) = show t ++ " undef" show (LMStaticStr s t) = show t ++ " c\"" ++ unpackFS s ++ "\\00\"" show (LMStaticArray d t) = show t ++ " [" ++ commaCat d ++ "]" show (LMStaticStruc d t) = show t ++ "<{" ++ commaCat d ++ "}>" show (LMStaticPointer v) = show v show (LMBitc v t) = show t ++ " bitcast (" ++ show v ++ " to " ++ show t ++ ")" show (LMPtoI v t) = show t ++ " ptrtoint (" ++ show v ++ " to " ++ show t ++ ")" show (LMAdd s1 s2) = let ty1 = getStatType s1 op = if isFloat ty1 then " fadd (" else " add (" in if ty1 == getStatType s2 then show ty1 ++ op ++ show s1 ++ "," ++ show s2 ++ ")" else error $ "LMAdd with different types! s1: " ++ show s1 ++ ", s2: " ++ show s2 show (LMSub s1 s2) = let ty1 = getStatType s1 op = if isFloat ty1 then " fsub (" else " sub (" in if ty1 == getStatType s2 then show ty1 ++ op ++ show s1 ++ "," ++ show s2 ++ ")" else error $ "LMSub with different types! s1: " ++ show s1 ++ ", s2: " ++ show s2 -- | Concatenate an array together, separated by commas commaCat :: Show a => [a] -> String commaCat xs = intercalate ", " $ map show xs -- ----------------------------------------------------------------------------- -- ** Operations on LLVM Basic Types and Variables -- -- | Return the variable name or value of the 'LlvmVar' -- in Llvm IR textual representation (e.g. @\@x@, @%y@ or @42@). getName :: LlvmVar -> String getName v@(LMGlobalVar _ _ _ _ _ _) = "@" ++ getPlainName v getName v@(LMLocalVar _ _ ) = "%" ++ getPlainName v getName v@(LMNLocalVar _ _ ) = "%" ++ getPlainName v getName v@(LMLitVar _ ) = getPlainName v -- | Return the variable name or value of the 'LlvmVar' -- in a plain textual representation (e.g. @x@, @y@ or @42@). getPlainName :: LlvmVar -> String getPlainName (LMGlobalVar x _ _ _ _ _) = unpackFS x getPlainName (LMLocalVar x LMLabel ) = show x getPlainName (LMLocalVar x _ ) = "l" ++ show x getPlainName (LMNLocalVar x _ ) = unpackFS x getPlainName (LMLitVar x ) = getLit x -- | Print a literal value. No type. getLit :: LlvmLit -> String getLit (LMIntLit i (LMInt 32)) = show (fromInteger i :: Int32) getLit (LMIntLit i (LMInt 64)) = show (fromInteger i :: Int64) getLit (LMIntLit i _ ) = show (fromInteger i :: Int) getLit (LMFloatLit r LMFloat ) = fToStr $ realToFrac r getLit (LMFloatLit r LMDouble) = dToStr r getLit f@(LMFloatLit _ _) = error $ "Can't print this float literal!" ++ show f getLit (LMNullLit _ ) = "null" getLit (LMUndefLit _ ) = "undef" -- | Return the 'LlvmType' of the 'LlvmVar' getVarType :: LlvmVar -> LlvmType getVarType (LMGlobalVar _ y _ _ _ _) = y getVarType (LMLocalVar _ y ) = y getVarType (LMNLocalVar _ y ) = y getVarType (LMLitVar l ) = getLitType l -- | Return the 'LlvmType' of a 'LlvmLit' getLitType :: LlvmLit -> LlvmType getLitType (LMIntLit _ t) = t getLitType (LMFloatLit _ t) = t getLitType (LMNullLit t) = t getLitType (LMUndefLit t) = t -- | Return the 'LlvmType' of the 'LlvmStatic' getStatType :: LlvmStatic -> LlvmType getStatType (LMStaticLit l ) = getLitType l getStatType (LMUninitType t) = t getStatType (LMStaticStr _ t) = t getStatType (LMStaticArray _ t) = t getStatType (LMStaticStruc _ t) = t getStatType (LMStaticPointer v) = getVarType v getStatType (LMBitc _ t) = t getStatType (LMPtoI _ t) = t getStatType (LMAdd t _) = getStatType t getStatType (LMSub t _) = getStatType t getStatType (LMComment _) = error "Can't call getStatType on LMComment!" -- | Return the 'LlvmType' of the 'LMGlobal' getGlobalType :: LMGlobal -> LlvmType getGlobalType (v, _) = getVarType v -- | Return the 'LlvmVar' part of a 'LMGlobal' getGlobalVar :: LMGlobal -> LlvmVar getGlobalVar (v, _) = v -- | Return the 'LlvmLinkageType' for a 'LlvmVar' getLink :: LlvmVar -> LlvmLinkageType getLink (LMGlobalVar _ _ l _ _ _) = l getLink _ = Internal -- | Add a pointer indirection to the supplied type. 'LMLabel' and 'LMVoid' -- cannot be lifted. pLift :: LlvmType -> LlvmType pLift (LMLabel) = error "Labels are unliftable" pLift (LMVoid) = error "Voids are unliftable" pLift x = LMPointer x -- | Lower a variable of 'LMPointer' type. pVarLift :: LlvmVar -> LlvmVar pVarLift (LMGlobalVar s t l x a c) = LMGlobalVar s (pLift t) l x a c pVarLift (LMLocalVar s t ) = LMLocalVar s (pLift t) pVarLift (LMNLocalVar s t ) = LMNLocalVar s (pLift t) pVarLift (LMLitVar _ ) = error $ "Can't lower a literal type!" -- | Remove the pointer indirection of the supplied type. Only 'LMPointer' -- constructors can be lowered. pLower :: LlvmType -> LlvmType pLower (LMPointer x) = x pLower x = error $ show x ++ " is a unlowerable type, need a pointer" -- | Lower a variable of 'LMPointer' type. pVarLower :: LlvmVar -> LlvmVar pVarLower (LMGlobalVar s t l x a c) = LMGlobalVar s (pLower t) l x a c pVarLower (LMLocalVar s t ) = LMLocalVar s (pLower t) pVarLower (LMNLocalVar s t ) = LMNLocalVar s (pLower t) pVarLower (LMLitVar _ ) = error $ "Can't lower a literal type!" -- | Test if the given 'LlvmType' is an integer isInt :: LlvmType -> Bool isInt (LMInt _) = True isInt _ = False -- | Test if the given 'LlvmType' is a floating point type isFloat :: LlvmType -> Bool isFloat LMFloat = True isFloat LMDouble = True isFloat LMFloat80 = True isFloat LMFloat128 = True isFloat _ = False -- | Test if the given 'LlvmType' is an 'LMPointer' construct isPointer :: LlvmType -> Bool isPointer (LMPointer _) = True isPointer _ = False -- | Test if a 'LlvmVar' is global. isGlobal :: LlvmVar -> Bool isGlobal (LMGlobalVar _ _ _ _ _ _) = True isGlobal _ = False -- | Width in bits of an 'LlvmType', returns 0 if not applicable llvmWidthInBits :: LlvmType -> Int llvmWidthInBits (LMInt n) = n llvmWidthInBits (LMFloat) = 32 llvmWidthInBits (LMDouble) = 64 llvmWidthInBits (LMFloat80) = 80 llvmWidthInBits (LMFloat128) = 128 -- Could return either a pointer width here or the width of what -- it points to. We will go with the former for now. llvmWidthInBits (LMPointer _) = llvmWidthInBits llvmWord llvmWidthInBits (LMArray _ _) = llvmWidthInBits llvmWord llvmWidthInBits LMLabel = 0 llvmWidthInBits LMVoid = 0 llvmWidthInBits (LMStruct tys) = sum $ map llvmWidthInBits tys llvmWidthInBits (LMFunction _) = 0 llvmWidthInBits (LMAlias (_,t)) = llvmWidthInBits t -- ----------------------------------------------------------------------------- -- ** Shortcut for Common Types -- i128, i64, i32, i16, i8, i1, i8Ptr :: LlvmType i128 = LMInt 128 i64 = LMInt 64 i32 = LMInt 32 i16 = LMInt 16 i8 = LMInt 8 i1 = LMInt 1 i8Ptr = pLift i8 -- | The target architectures word size llvmWord, llvmWordPtr :: LlvmType llvmWord = LMInt (wORD_SIZE * 8) llvmWordPtr = pLift llvmWord -- ----------------------------------------------------------------------------- -- * LLVM Function Types -- -- | An LLVM Function data LlvmFunctionDecl = LlvmFunctionDecl { -- | Unique identifier of the function decName :: LMString, -- | LinkageType of the function funcLinkage :: LlvmLinkageType, -- | The calling convention of the function funcCc :: LlvmCallConvention, -- | Type of the returned value decReturnType :: LlvmType, -- | Indicates if this function uses varargs decVarargs :: LlvmParameterListType, -- | Parameter types and attributes decParams :: [LlvmParameter], -- | Function align value, must be power of 2 funcAlign :: LMAlign } deriving (Eq) instance Show LlvmFunctionDecl where show (LlvmFunctionDecl n l c r varg p a) = let varg' = case varg of VarArgs | null args -> "..." | otherwise -> ", ..." _otherwise -> "" align = case a of Just a' -> " align " ++ show a' Nothing -> "" -- by default we don't print param attributes args = intercalate ", " $ map (show . fst) p in show l ++ " " ++ show c ++ " " ++ show r ++ " @" ++ unpackFS n ++ "(" ++ args ++ varg' ++ ")" ++ align type LlvmFunctionDecls = [LlvmFunctionDecl] type LlvmParameter = (LlvmType, [LlvmParamAttr]) -- | LLVM Parameter Attributes. -- -- Parameter attributes are used to communicate additional information about -- the result or parameters of a function data LlvmParamAttr -- | This indicates to the code generator that the parameter or return value -- should be zero-extended to a 32-bit value by the caller (for a parameter) -- or the callee (for a return value). = ZeroExt -- | This indicates to the code generator that the parameter or return value -- should be sign-extended to a 32-bit value by the caller (for a parameter) -- or the callee (for a return value). | SignExt -- | This indicates that this parameter or return value should be treated in -- a special target-dependent fashion during while emitting code for a -- function call or return (usually, by putting it in a register as opposed -- to memory). | InReg -- | This indicates that the pointer parameter should really be passed by -- value to the function. | ByVal -- | This indicates that the pointer parameter specifies the address of a -- structure that is the return value of the function in the source program. | SRet -- | This indicates that the pointer does not alias any global or any other -- parameter. | NoAlias -- | This indicates that the callee does not make any copies of the pointer -- that outlive the callee itself | NoCapture -- | This indicates that the pointer parameter can be excised using the -- trampoline intrinsics. | Nest deriving (Eq) instance Show LlvmParamAttr where show ZeroExt = "zeroext" show SignExt = "signext" show InReg = "inreg" show ByVal = "byval" show SRet = "sret" show NoAlias = "noalias" show NoCapture = "nocapture" show Nest = "nest" -- | Llvm Function Attributes. -- -- Function attributes are set to communicate additional information about a -- function. Function attributes are considered to be part of the function, -- not of the function type, so functions with different parameter attributes -- can have the same function type. Functions can have multiple attributes. -- -- Descriptions taken from <http://llvm.org/docs/LangRef.html#fnattrs> data LlvmFuncAttr -- | This attribute indicates that the inliner should attempt to inline this -- function into callers whenever possible, ignoring any active inlining -- size threshold for this caller. = AlwaysInline -- | This attribute indicates that the source code contained a hint that -- inlining this function is desirable (such as the \"inline\" keyword in -- C/C++). It is just a hint; it imposes no requirements on the inliner. | InlineHint -- | This attribute indicates that the inliner should never inline this -- function in any situation. This attribute may not be used together -- with the alwaysinline attribute. | NoInline -- | This attribute suggests that optimization passes and code generator -- passes make choices that keep the code size of this function low, and -- otherwise do optimizations specifically to reduce code size. | OptSize -- | This function attribute indicates that the function never returns -- normally. This produces undefined behavior at runtime if the function -- ever does dynamically return. | NoReturn -- | This function attribute indicates that the function never returns with -- an unwind or exceptional control flow. If the function does unwind, its -- runtime behavior is undefined. | NoUnwind -- | This attribute indicates that the function computes its result (or -- decides to unwind an exception) based strictly on its arguments, without -- dereferencing any pointer arguments or otherwise accessing any mutable -- state (e.g. memory, control registers, etc) visible to caller functions. -- It does not write through any pointer arguments (including byval -- arguments) and never changes any state visible to callers. This means -- that it cannot unwind exceptions by calling the C++ exception throwing -- methods, but could use the unwind instruction. | ReadNone -- | This attribute indicates that the function does not write through any -- pointer arguments (including byval arguments) or otherwise modify any -- state (e.g. memory, control registers, etc) visible to caller functions. -- It may dereference pointer arguments and read state that may be set in -- the caller. A readonly function always returns the same value (or unwinds -- an exception identically) when called with the same set of arguments and -- global state. It cannot unwind an exception by calling the C++ exception -- throwing methods, but may use the unwind instruction. | ReadOnly -- | This attribute indicates that the function should emit a stack smashing -- protector. It is in the form of a \"canary\"β€”a random value placed on the -- stack before the local variables that's checked upon return from the -- function to see if it has been overwritten. A heuristic is used to -- determine if a function needs stack protectors or not. -- -- If a function that has an ssp attribute is inlined into a function that -- doesn't have an ssp attribute, then the resulting function will have an -- ssp attribute. | Ssp -- | This attribute indicates that the function should always emit a stack -- smashing protector. This overrides the ssp function attribute. -- -- If a function that has an sspreq attribute is inlined into a function -- that doesn't have an sspreq attribute or which has an ssp attribute, -- then the resulting function will have an sspreq attribute. | SspReq -- | This attribute indicates that the code generator should not use a red -- zone, even if the target-specific ABI normally permits it. | NoRedZone -- | This attributes disables implicit floating point instructions. | NoImplicitFloat -- | This attribute disables prologue / epilogue emission for the function. -- This can have very system-specific consequences. | Naked deriving (Eq) instance Show LlvmFuncAttr where show AlwaysInline = "alwaysinline" show InlineHint = "inlinehint" show NoInline = "noinline" show OptSize = "optsize" show NoReturn = "noreturn" show NoUnwind = "nounwind" show ReadNone = "readnon" show ReadOnly = "readonly" show Ssp = "ssp" show SspReq = "ssqreq" show NoRedZone = "noredzone" show NoImplicitFloat = "noimplicitfloat" show Naked = "naked" -- | Different types to call a function. data LlvmCallType -- | Normal call, allocate a new stack frame. = StdCall -- | Tail call, perform the call in the current stack frame. | TailCall deriving (Eq,Show) -- | Different calling conventions a function can use. data LlvmCallConvention -- | The C calling convention. -- This calling convention (the default if no other calling convention is -- specified) matches the target C calling conventions. This calling -- convention supports varargs function calls and tolerates some mismatch in -- the declared prototype and implemented declaration of the function (as -- does normal C). = CC_Ccc -- | This calling convention attempts to make calls as fast as possible -- (e.g. by passing things in registers). This calling convention allows -- the target to use whatever tricks it wants to produce fast code for the -- target, without having to conform to an externally specified ABI -- (Application Binary Interface). Implementations of this convention should -- allow arbitrary tail call optimization to be supported. This calling -- convention does not support varargs and requires the prototype of al -- callees to exactly match the prototype of the function definition. | CC_Fastcc -- | This calling convention attempts to make code in the caller as efficient -- as possible under the assumption that the call is not commonly executed. -- As such, these calls often preserve all registers so that the call does -- not break any live ranges in the caller side. This calling convention -- does not support varargs and requires the prototype of all callees to -- exactly match the prototype of the function definition. | CC_Coldcc -- | Any calling convention may be specified by number, allowing -- target-specific calling conventions to be used. Target specific calling -- conventions start at 64. | CC_Ncc Int -- | X86 Specific 'StdCall' convention. LLVM includes a specific alias for it -- rather than just using CC_Ncc. | CC_X86_Stdcc deriving (Eq) instance Show LlvmCallConvention where show CC_Ccc = "ccc" show CC_Fastcc = "fastcc" show CC_Coldcc = "coldcc" show (CC_Ncc i) = "cc " ++ show i show CC_X86_Stdcc = "x86_stdcallcc" -- | Functions can have a fixed amount of parameters, or a variable amount. data LlvmParameterListType -- Fixed amount of arguments. = FixedArgs -- Variable amount of arguments. | VarArgs deriving (Eq,Show) -- | Linkage type of a symbol. -- -- The description of the constructors is copied from the Llvm Assembly Language -- Reference Manual <http://www.llvm.org/docs/LangRef.html#linkage>, because -- they correspond to the Llvm linkage types. data LlvmLinkageType -- | Global values with internal linkage are only directly accessible by -- objects in the current module. In particular, linking code into a module -- with an internal global value may cause the internal to be renamed as -- necessary to avoid collisions. Because the symbol is internal to the -- module, all references can be updated. This corresponds to the notion -- of the @static@ keyword in C. = Internal -- | Globals with @linkonce@ linkage are merged with other globals of the -- same name when linkage occurs. This is typically used to implement -- inline functions, templates, or other code which must be generated -- in each translation unit that uses it. Unreferenced linkonce globals are -- allowed to be discarded. | LinkOnce -- | @weak@ linkage is exactly the same as linkonce linkage, except that -- unreferenced weak globals may not be discarded. This is used for globals -- that may be emitted in multiple translation units, but that are not -- guaranteed to be emitted into every translation unit that uses them. One -- example of this are common globals in C, such as @int X;@ at global -- scope. | Weak -- | @appending@ linkage may only be applied to global variables of pointer -- to array type. When two global variables with appending linkage are -- linked together, the two global arrays are appended together. This is -- the Llvm, typesafe, equivalent of having the system linker append -- together @sections@ with identical names when .o files are linked. | Appending -- | The semantics of this linkage follow the ELF model: the symbol is weak -- until linked, if not linked, the symbol becomes null instead of being an -- undefined reference. | ExternWeak -- | The symbol participates in linkage and can be used to resolve external -- symbol references. | ExternallyVisible -- | Alias for 'ExternallyVisible' but with explicit textual form in LLVM -- assembly. | External deriving (Eq) instance Show LlvmLinkageType where show Internal = "internal" show LinkOnce = "linkonce" show Weak = "weak" show Appending = "appending" show ExternWeak = "extern_weak" -- ExternallyVisible does not have a textual representation, it is -- the linkage type a function resolves to if no other is specified -- in Llvm. show ExternallyVisible = "" show External = "external" -- ----------------------------------------------------------------------------- -- * LLVM Operations -- -- | Llvm binary operators machine operations. data LlvmMachOp = LM_MO_Add -- ^ add two integer, floating point or vector values. | LM_MO_Sub -- ^ subtract two ... | LM_MO_Mul -- ^ multiply .. | LM_MO_UDiv -- ^ unsigned integer or vector division. | LM_MO_SDiv -- ^ signed integer .. | LM_MO_URem -- ^ unsigned integer or vector remainder (mod) | LM_MO_SRem -- ^ signed ... | LM_MO_FAdd -- ^ add two floating point or vector values. | LM_MO_FSub -- ^ subtract two ... | LM_MO_FMul -- ^ multiply ... | LM_MO_FDiv -- ^ divide ... | LM_MO_FRem -- ^ remainder ... -- | Left shift | LM_MO_Shl -- | Logical shift right -- Shift right, filling with zero | LM_MO_LShr -- | Arithmetic shift right -- The most significant bits of the result will be equal to the sign bit of -- the left operand. | LM_MO_AShr | LM_MO_And -- ^ AND bitwise logical operation. | LM_MO_Or -- ^ OR bitwise logical operation. | LM_MO_Xor -- ^ XOR bitwise logical operation. deriving (Eq) instance Show LlvmMachOp where show LM_MO_Add = "add" show LM_MO_Sub = "sub" show LM_MO_Mul = "mul" show LM_MO_UDiv = "udiv" show LM_MO_SDiv = "sdiv" show LM_MO_URem = "urem" show LM_MO_SRem = "srem" show LM_MO_FAdd = "fadd" show LM_MO_FSub = "fsub" show LM_MO_FMul = "fmul" show LM_MO_FDiv = "fdiv" show LM_MO_FRem = "frem" show LM_MO_Shl = "shl" show LM_MO_LShr = "lshr" show LM_MO_AShr = "ashr" show LM_MO_And = "and" show LM_MO_Or = "or" show LM_MO_Xor = "xor" -- | Llvm compare operations. data LlvmCmpOp = LM_CMP_Eq -- ^ Equal (Signed and Unsigned) | LM_CMP_Ne -- ^ Not equal (Signed and Unsigned) | LM_CMP_Ugt -- ^ Unsigned greater than | LM_CMP_Uge -- ^ Unsigned greater than or equal | LM_CMP_Ult -- ^ Unsigned less than | LM_CMP_Ule -- ^ Unsigned less than or equal | LM_CMP_Sgt -- ^ Signed greater than | LM_CMP_Sge -- ^ Signed greater than or equal | LM_CMP_Slt -- ^ Signed less than | LM_CMP_Sle -- ^ Signed less than or equal -- Float comparisons. GHC uses a mix of ordered and unordered float -- comparisons. | LM_CMP_Feq -- ^ Float equal | LM_CMP_Fne -- ^ Float not equal | LM_CMP_Fgt -- ^ Float greater than | LM_CMP_Fge -- ^ Float greater than or equal | LM_CMP_Flt -- ^ Float less than | LM_CMP_Fle -- ^ Float less than or equal deriving (Eq) instance Show LlvmCmpOp where show LM_CMP_Eq = "eq" show LM_CMP_Ne = "ne" show LM_CMP_Ugt = "ugt" show LM_CMP_Uge = "uge" show LM_CMP_Ult = "ult" show LM_CMP_Ule = "ule" show LM_CMP_Sgt = "sgt" show LM_CMP_Sge = "sge" show LM_CMP_Slt = "slt" show LM_CMP_Sle = "sle" show LM_CMP_Feq = "oeq" show LM_CMP_Fne = "une" show LM_CMP_Fgt = "ogt" show LM_CMP_Fge = "oge" show LM_CMP_Flt = "olt" show LM_CMP_Fle = "ole" -- | Llvm cast operations. data LlvmCastOp = LM_Trunc -- ^ Integer truncate | LM_Zext -- ^ Integer extend (zero fill) | LM_Sext -- ^ Integer extend (sign fill) | LM_Fptrunc -- ^ Float truncate | LM_Fpext -- ^ Float extend | LM_Fptoui -- ^ Float to unsigned Integer | LM_Fptosi -- ^ Float to signed Integer | LM_Uitofp -- ^ Unsigned Integer to Float | LM_Sitofp -- ^ Signed Int to Float | LM_Ptrtoint -- ^ Pointer to Integer | LM_Inttoptr -- ^ Integer to Pointer | LM_Bitcast -- ^ Cast between types where no bit manipulation is needed deriving (Eq) instance Show LlvmCastOp where show LM_Trunc = "trunc" show LM_Zext = "zext" show LM_Sext = "sext" show LM_Fptrunc = "fptrunc" show LM_Fpext = "fpext" show LM_Fptoui = "fptoui" show LM_Fptosi = "fptosi" show LM_Uitofp = "uitofp" show LM_Sitofp = "sitofp" show LM_Ptrtoint = "ptrtoint" show LM_Inttoptr = "inttoptr" show LM_Bitcast = "bitcast" -- ----------------------------------------------------------------------------- -- * Floating point conversion -- -- | Convert a Haskell Double to an LLVM hex encoded floating point form. In -- Llvm float literals can be printed in a big-endian hexadecimal format, -- regardless of underlying architecture. dToStr :: Double -> String dToStr d = let bs = doubleToBytes d hex d' = case showHex d' "" of [] -> error "dToStr: too few hex digits for float" [x] -> ['0',x] [x,y] -> [x,y] _ -> error "dToStr: too many hex digits for float" str = map toUpper $ concat . fixEndian . (map hex) $ bs in "0x" ++ str -- | Convert a Haskell Float to an LLVM hex encoded floating point form. -- LLVM uses the same encoding for both floats and doubles (16 digit hex -- string) but floats must have the last half all zeroes so it can fit into -- a float size type. {-# NOINLINE fToStr #-} fToStr :: Float -> String fToStr = (dToStr . realToFrac) -- | Reverse or leave byte data alone to fix endianness on this target. fixEndian :: [a] -> [a] #ifdef WORDS_BIGENDIAN fixEndian = id #else fixEndian = reverse #endif
ilyasergey/GHC-XAppFix
compiler/llvmGen/Llvm/Types.hs
bsd-3-clause
30,209
0
19
7,312
4,757
2,624
2,133
435
4
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. An additional grant -- of patent rights can be found in the PATENTS file in the same directory. {-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE NoRebindableSyntax #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeFamilies #-} module Duckling.Email.Types where import Control.DeepSeq import Data.Aeson import Data.Hashable import Data.Text (Text) import GHC.Generics import Prelude import Duckling.Resolve (Resolve(..)) newtype EmailData = EmailData { value :: Text } deriving (Eq, Generic, Hashable, Ord, Show, NFData) instance Resolve EmailData where type ResolvedValue EmailData = EmailData resolve _ x = Just x instance ToJSON EmailData where toJSON EmailData {value} = object [ "value" .= value ]
rfranek/duckling
Duckling/Email/Types.hs
bsd-3-clause
988
0
8
157
168
100
68
21
0
-------------------------------------------------------------------------------- -- | -- Module : Graphics.Rendering.OpenGL.GL.StateVar -- Copyright : (c) Sven Panne 2003 -- License : BSD-style (see the file libraries/OpenGL/LICENSE) -- -- Maintainer : [email protected] -- Stability : provisional -- Portability : portable -- -------------------------------------------------------------------------------- module Graphics.Rendering.OpenGL.GL.StateVar ( HasGetter(..), GettableStateVar, makeGettableStateVar, HasSetter(..), set, SettableStateVar, makeSettableStateVar, StateVar, makeStateVar ) where -------------------------------------------------------------------------------- infixr 2 $= -------------------------------------------------------------------------------- class HasGetter g where get :: g a -> IO a -------------------------------------------------------------------------------- newtype GettableStateVar a = GettableStateVar (IO a) instance HasGetter GettableStateVar where get (GettableStateVar g) = g makeGettableStateVar :: IO a -> GettableStateVar a makeGettableStateVar = GettableStateVar -------------------------------------------------------------------------------- class HasSetter s where ($=) :: s a -> a -> IO () set :: [IO ()] -> IO () set = sequence_ -------------------------------------------------------------------------------- newtype SettableStateVar a = SettableStateVar (a -> IO ()) instance HasSetter SettableStateVar where ($=) (SettableStateVar s) a = s a makeSettableStateVar :: (a -> IO ()) -> SettableStateVar a makeSettableStateVar = SettableStateVar -------------------------------------------------------------------------------- data StateVar a = StateVar (GettableStateVar a) (SettableStateVar a) instance HasGetter StateVar where get (StateVar g _) = get g instance HasSetter StateVar where ($=) (StateVar _ s) a = s $= a makeStateVar :: IO a -> (a -> IO ()) -> StateVar a makeStateVar g s = StateVar (makeGettableStateVar g) (makeSettableStateVar s)
OS2World/DEV-UTIL-HUGS
libraries/Graphics/Rendering/OpenGL/GL/StateVar.hs
bsd-3-clause
2,086
0
10
284
428
236
192
31
1
{-# LANGUAGE QuasiQuotes , TypeFamilies , GeneralizedNewtypeDeriving , TemplateHaskell , OverloadedStrings , GADTs , FlexibleContexts #-} module Market.Models.Fields where import Database.Persist import Database.Persist.Sql import qualified Data.Text as T data Direction = Buy | Sell deriving (Show, Eq, Ord, Enum, Bounded) instance PersistField Direction where toPersistValue Buy = PersistInt64 0 toPersistValue Sell = PersistInt64 1 fromPersistValue (PersistInt64 0) = Right Buy fromPersistValue (PersistInt64 1) = Right Sell fromPersistValue (PersistText "buy") = Right Buy fromPersistValue (PersistText "sell") = Right Sell fromPersistValue x = Left $ T.pack $ "could not convert value " ++ (show x) ++ " to Direction" instance PersistFieldSql Direction where sqlType _ = SqlInt32 newtype Money = Money {unMoney :: Rational} deriving (Enum, Eq, Fractional, Num, Ord, Read, Real, RealFrac, Show, PersistField, PersistFieldSql) newtype Ticker = Ticker {unTicker :: Rational} deriving (Enum, Eq, Fractional, Num, Ord, Read, Real, RealFrac, Show, PersistField, PersistFieldSql)
s9gf4ult/market
Market/Models/Fields.hs
bsd-3-clause
1,319
0
10
384
326
173
153
-1
-1
----------------------------------------------------------------------------- -- | -- Module : XMonad.Actions.SimpleDate -- Description : An example external contrib module for XMonad. -- Copyright : (c) Don Stewart 2007 -- License : BSD3-style (see LICENSE) -- -- Maintainer : [email protected] -- Stability : stable -- Portability : portable -- -- An example external contrib module for XMonad. -- Provides a simple binding to dzen2 to print the date as a popup menu. -- ----------------------------------------------------------------------------- module XMonad.Actions.SimpleDate ( -- * Usage -- $usage date ) where import XMonad.Core import XMonad.Util.Run -- $usage -- To use, import this module into @~\/.xmonad\/xmonad.hs@: -- -- > import XMonad.Actions.SimpleDate -- -- and add a keybinding, for example: -- -- > , ((modm, xK_d ), date) -- -- In this example, a popup date menu will now be bound to @mod-d@. -- -- For detailed instructions on editing your key bindings, see -- "XMonad.Doc.Extending#Editing_key_bindings". date :: X () date = unsafeSpawn "(date; sleep 10) | dzen2"
xmonad/xmonad-contrib
XMonad/Actions/SimpleDate.hs
bsd-3-clause
1,274
0
6
336
71
54
17
6
1
-------------------------------------------------------------------------------- -- | -- Module : Graphics.Rendering.OpenGL.Raw.SGIX.Sprite -- Copyright : (c) Sven Panne 2015 -- License : BSD3 -- -- Maintainer : Sven Panne <[email protected]> -- Stability : stable -- Portability : portable -- -- The <https://www.opengl.org/registry/specs/SGIX/sprite.txt SGIX_sprite> extension. -- -------------------------------------------------------------------------------- module Graphics.Rendering.OpenGL.Raw.SGIX.Sprite ( -- * Enums gl_SPRITE_AXIAL_SGIX, gl_SPRITE_AXIS_SGIX, gl_SPRITE_EYE_ALIGNED_SGIX, gl_SPRITE_MODE_SGIX, gl_SPRITE_OBJECT_ALIGNED_SGIX, gl_SPRITE_SGIX, gl_SPRITE_TRANSLATION_SGIX, -- * Functions glSpriteParameterfSGIX, glSpriteParameterfvSGIX, glSpriteParameteriSGIX, glSpriteParameterivSGIX ) where import Graphics.Rendering.OpenGL.Raw.Tokens import Graphics.Rendering.OpenGL.Raw.Functions
phaazon/OpenGLRaw
src/Graphics/Rendering/OpenGL/Raw/SGIX/Sprite.hs
bsd-3-clause
954
0
4
115
76
58
18
14
0
module AERN2.Poly.Power.Eval where import MixedTypesNumPrelude import AERN2.Poly.Power.Type import AERN2.Poly.Basics import AERN2.MP.Ball import AERN2.MP.Dyadic import qualified Data.Map as Map evalDirect :: (CanAddAsymmetric b c, b ~ AddType b c , Ring b, HasIntegers b, HasIntegers c) => PowPoly c -> b -> b evalDirect (PowPoly (Poly ts)) (x :: b) = evalHornerAcc (terms_degree ts) (convertExactly 0) where evalHornerAcc :: Integer -> b -> b evalHornerAcc 0 sm = x*sm + terms_lookupCoeff ts 0 evalHornerAcc k sm = evalHornerAcc (k - 1) $ x*sm + terms_lookupCoeff ts k evalMBI :: PowPoly MPBall -> MPBall -> MPBall evalMBI f = evalLip f (markovBoundI f) evalDI :: PowPoly MPBall -> MPBall -> MPBall evalDI f = evalDf f (derivative f) evalDf :: PowPoly MPBall -> PowPoly MPBall -> MPBall -> MPBall evalDf f f' x = evalLip f (abs $ evalDirect f' x) x evalDIn :: PowPoly MPBall -> MPBall -> Integer -> MPBall evalDIn f x n = if n == 0 then evalDirect f x else evalLip f (abs $ evalDIn (derivative f) x (n - 1)) x evalLip :: PowPoly MPBall -> MPBall -> MPBall -> MPBall evalLip f lip x = (evalDirect f $ centreAsBall x) + (hullMPBall (-err) err) where err = lip*(dyadic $ ball_error x)*0.5 markovBoundI :: PowPoly MPBall -> MPBall markovBoundI f@(PowPoly (Poly ts)) = ((degree f)^!2) * Map.foldl' (\s y -> s + abs y) (mpBall 0) ts
michalkonecny/aern2
aern2-fun-univariate/src/AERN2/Poly/Power/Eval.hs
bsd-3-clause
1,402
0
12
306
601
309
292
-1
-1
{-# LANGUAGE OverloadedStrings #-} module Stack.Options (Command(..) ,benchOptsParser ,buildOptsParser ,configOptsParser ,dockerOptsParser ,dockerCleanupOptsParser ,dotOptsParser ,execOptsParser ,evalOptsParser ,globalOptsParser ,initOptsParser ,newOptsParser ,logLevelOptsParser ,ghciOptsParser ,abstractResolverOptsParser ,solverOptsParser ,testOptsParser ,pvpBoundsOption ) where import Control.Monad.Logger (LogLevel(..)) import Data.Char (isSpace, toLower) import Data.List (intercalate) import Data.List.Split (splitOn) import qualified Data.Map as Map import Data.Map.Strict (Map) import qualified Data.Map.Strict as M import Data.Maybe import Data.Monoid import qualified Data.Set as Set import qualified Data.Text as T import Data.Text.Read (decimal) import Options.Applicative.Args import Options.Applicative.Builder.Extra import Options.Applicative.Simple import Options.Applicative.Types (readerAsk) import Stack.Config (packagesParser) import Stack.Constants (stackProgName) import Stack.Docker import qualified Stack.Docker as Docker import Stack.Dot import Stack.Ghci (GhciOpts(..)) import Stack.Init import Stack.New import Stack.Types import Stack.Types.TemplateName -- | Command sum type for conditional arguments. data Command = Build | Test | Haddock | Bench | Install deriving (Eq) -- | Parser for bench arguments. benchOptsParser :: Parser BenchmarkOpts benchOptsParser = BenchmarkOpts <$> optional (strOption (long "benchmark-arguments" <> metavar "BENCH_ARGS" <> help ("Forward BENCH_ARGS to the benchmark suite. " <> "Supports templates from `cabal bench`"))) <*> flag False True (long "no-run-benchmarks" <> help "Disable running of benchmarks. (Benchmarks will still be built.)") addCoverageFlags :: BuildOpts -> BuildOpts addCoverageFlags bopts | toCoverage $ boptsTestOpts bopts = bopts { boptsGhcOptions = "-fhpc" : boptsGhcOptions bopts } | otherwise = bopts -- | Parser for build arguments. buildOptsParser :: Command -> Parser BuildOpts buildOptsParser cmd = fmap addCoverageFlags $ BuildOpts <$> target <*> libProfiling <*> exeProfiling <*> haddock <*> haddockDeps <*> dryRun <*> ghcOpts <*> flags <*> copyBins <*> preFetch <*> buildSubset <*> fileWatch' <*> keepGoing <*> forceDirty <*> tests <*> testOptsParser <*> benches <*> benchOptsParser <*> many exec <*> onlyConfigure <*> reconfigure <*> cabalVerbose where target = many (textArgument (metavar "TARGET" <> help "If none specified, use all packages")) libProfiling = boolFlags False "library-profiling" "library profiling for TARGETs and all its dependencies" idm exeProfiling = boolFlags False "executable-profiling" "executable profiling for TARGETs and all its dependencies" idm haddock = boolFlags (cmd == Haddock) "haddock" "generating Haddocks the project(s) in this directory/configuration" idm haddockDeps = maybeBoolFlags "haddock-deps" "building Haddocks for dependencies" idm copyBins = boolFlags (cmd == Install) "copy-bins" "copying binaries to the local-bin-path (see 'stack path')" idm dryRun = flag False True (long "dry-run" <> help "Don't build anything, just prepare to") ghcOpts = (++) <$> flag [] ["-Wall", "-Werror"] ( long "pedantic" <> help "Turn on -Wall and -Werror (note: option name may change in the future" ) <*> many (textOption (long "ghc-options" <> metavar "OPTION" <> help "Additional options passed to GHC")) flags = Map.unionsWith Map.union <$> many (option readFlag (long "flag" <> metavar "PACKAGE:[-]FLAG" <> help ("Override flags set in stack.yaml " <> "(applies to local packages and extra-deps)"))) preFetch = flag False True (long "prefetch" <> help "Fetch packages necessary for the build immediately, useful with --dry-run") buildSubset = flag' BSOnlySnapshot (long "only-snapshot" <> help "Only build packages for the snapshot database, not the local database") <|> flag' BSOnlyDependencies (long "only-dependencies" <> help "Only build packages that are dependencies of targets on the command line") <|> flag' BSOnlyDependencies (long "dependencies-only" <> help "A synonym for --only-dependencies") <|> pure BSAll fileWatch' = flag' FileWatch (long "file-watch" <> help "Watch for changes in local files and automatically rebuild. Ignores files in VCS boring/ignore file") <|> flag' FileWatchPoll (long "file-watch-poll" <> help "Like --file-watch, but polling the filesystem instead of using events") <|> pure NoFileWatch keepGoing = maybeBoolFlags "keep-going" "continue running after a step fails (default: false for build, true for test/bench)" idm forceDirty = flag False True (long "force-dirty" <> help "Force treating all local packages as having dirty files (useful for cases where stack can't detect a file change)") tests = boolFlags (cmd == Test) "test" "testing the project(s) in this directory/configuration" idm benches = boolFlags (cmd == Bench) "bench" "benchmarking the project(s) in this directory/configuration" idm exec = cmdOption ( long "exec" <> metavar "CMD [ARGS]" <> help "Command and arguments to run after a successful build" ) onlyConfigure = flag False True (long "only-configure" <> help "Only perform the configure step, not any builds. Intended for tool usage, may break when used on multiple packages at once!") reconfigure = flag False True (long "reconfigure" <> help "Perform the configure step even if unnecessary. Useful in some corner cases with custom Setup.hs files") cabalVerbose = flag False True (long "cabal-verbose" <> help "Ask Cabal to be verbose in its output") -- | Parser for package:[-]flag readFlag :: ReadM (Map (Maybe PackageName) (Map FlagName Bool)) readFlag = do s <- readerAsk case break (== ':') s of (pn, ':':mflag) -> do pn' <- case parsePackageNameFromString pn of Nothing | pn == "*" -> return Nothing | otherwise -> readerError $ "Invalid package name: " ++ pn Just x -> return $ Just x let (b, flagS) = case mflag of '-':x -> (False, x) _ -> (True, mflag) flagN <- case parseFlagNameFromString flagS of Nothing -> readerError $ "Invalid flag name: " ++ flagS Just x -> return x return $ Map.singleton pn' $ Map.singleton flagN b _ -> readerError "Must have a colon" -- | Command-line arguments parser for configuration. configOptsParser :: Bool -> Parser ConfigMonoid configOptsParser docker = (\opts systemGHC installGHC arch os ghcVariant jobs includes libs skipGHCCheck skipMsys localBin modifyCodePage -> mempty { configMonoidDockerOpts = opts , configMonoidSystemGHC = systemGHC , configMonoidInstallGHC = installGHC , configMonoidSkipGHCCheck = skipGHCCheck , configMonoidArch = arch , configMonoidOS = os , configMonoidGHCVariant = ghcVariant , configMonoidJobs = jobs , configMonoidExtraIncludeDirs = includes , configMonoidExtraLibDirs = libs , configMonoidSkipMsys = skipMsys , configMonoidLocalBinPath = localBin , configMonoidModifyCodePage = modifyCodePage }) <$> dockerOptsParser docker <*> maybeBoolFlags "system-ghc" "using the system installed GHC (on the PATH) if available and a matching version" idm <*> maybeBoolFlags "install-ghc" "downloading and installing GHC if necessary (can be done manually with stack setup)" idm <*> optional (strOption ( long "arch" <> metavar "ARCH" <> help "System architecture, e.g. i386, x86_64" )) <*> optional (strOption ( long "os" <> metavar "OS" <> help "Operating system, e.g. linux, windows" )) <*> optional ghcVariantParser <*> optional (option auto ( long "jobs" <> short 'j' <> metavar "JOBS" <> help "Number of concurrent jobs to run" )) <*> fmap Set.fromList (many (textOption ( long "extra-include-dirs" <> metavar "DIR" <> help "Extra directories to check for C header files" ))) <*> fmap Set.fromList (many (textOption ( long "extra-lib-dirs" <> metavar "DIR" <> help "Extra directories to check for libraries" ))) <*> maybeBoolFlags "skip-ghc-check" "skipping the GHC version and architecture check" idm <*> maybeBoolFlags "skip-msys" "skipping the local MSYS installation (Windows only)" idm <*> optional (strOption ( long "local-bin-path" <> metavar "DIR" <> help "Install binaries to DIR" )) <*> maybeBoolFlags "modify-code-page" "setting the codepage to support UTF-8 (Windows only)" idm -- | Options parser configuration for Docker. dockerOptsParser :: Bool -> Parser DockerOptsMonoid dockerOptsParser showOptions = DockerOptsMonoid <$> pure False <*> maybeBoolFlags dockerCmdName "using a Docker container" hide <*> ((Just . DockerMonoidRepo) <$> option str (long (dockerOptName dockerRepoArgName) <> hide <> metavar "NAME" <> help "Docker repository name") <|> (Just . DockerMonoidImage) <$> option str (long (dockerOptName dockerImageArgName) <> hide <> metavar "IMAGE" <> help "Exact Docker image ID (overrides docker-repo)") <|> pure Nothing) <*> maybeBoolFlags (dockerOptName dockerRegistryLoginArgName) "registry requires login" hide <*> maybeStrOption (long (dockerOptName dockerRegistryUsernameArgName) <> hide <> metavar "USERNAME" <> help "Docker registry username") <*> maybeStrOption (long (dockerOptName dockerRegistryPasswordArgName) <> hide <> metavar "PASSWORD" <> help "Docker registry password") <*> maybeBoolFlags (dockerOptName dockerAutoPullArgName) "automatic pulling latest version of image" hide <*> maybeBoolFlags (dockerOptName dockerDetachArgName) "running a detached Docker container" hide <*> maybeBoolFlags (dockerOptName dockerPersistArgName) "not deleting container after it exits" hide <*> maybeStrOption (long (dockerOptName dockerContainerNameArgName) <> hide <> metavar "NAME" <> help "Docker container name") <*> argsOption (long (dockerOptName dockerRunArgsArgName) <> hide <> value [] <> metavar "'ARG1 [ARG2 ...]'" <> help "Additional options to pass to 'docker run'") <*> many (option auto (long (dockerOptName dockerMountArgName) <> hide <> metavar "(PATH | HOST-PATH:CONTAINER-PATH)" <> help ("Mount volumes from host in container " ++ "(may specify multiple times)"))) <*> many (option str (long (dockerOptName dockerEnvArgName) <> hide <> metavar "NAME=VALUE" <> help ("Set environment variable in container " ++ "(may specify multiple times)"))) <*> maybeStrOption (long (dockerOptName dockerDatabasePathArgName) <> hide <> metavar "PATH" <> help "Location of image usage tracking database") <*> optional (option str (long(dockerOptName dockerStackExeArgName) <> hide <> metavar (intercalate "|" [ dockerStackExeDownloadVal , dockerStackExeHostVal , dockerStackExeImageVal , "PATH" ]) <> help (concat [ "Location of " , stackProgName , " executable used in container" ]))) <*> maybeBoolFlags (dockerOptName dockerSetUserArgName) "setting user in container to match host" hide where dockerOptName optName = dockerCmdName ++ "-" ++ T.unpack optName maybeStrOption = optional . option str hide = if showOptions then idm else internal <> hidden -- | Parser for docker cleanup arguments. dockerCleanupOptsParser :: Parser Docker.CleanupOpts dockerCleanupOptsParser = Docker.CleanupOpts <$> (flag' Docker.CleanupInteractive (short 'i' <> long "interactive" <> help "Show cleanup plan in editor and allow changes (default)") <|> flag' Docker.CleanupImmediate (short 'y' <> long "immediate" <> help "Immediately execute cleanup plan") <|> flag' Docker.CleanupDryRun (short 'n' <> long "dry-run" <> help "Display cleanup plan but do not execute") <|> pure Docker.CleanupInteractive) <*> opt (Just 14) "known-images" "LAST-USED" <*> opt Nothing "unknown-images" "CREATED" <*> opt (Just 0) "dangling-images" "CREATED" <*> opt Nothing "stopped-containers" "CREATED" <*> opt Nothing "running-containers" "CREATED" where opt def' name mv = fmap Just (option auto (long name <> metavar (mv ++ "-DAYS-AGO") <> help ("Remove " ++ toDescr name ++ " " ++ map toLower (toDescr mv) ++ " N days ago" ++ case def' of Just n -> " (default " ++ show n ++ ")" Nothing -> ""))) <|> flag' Nothing (long ("no-" ++ name) <> help ("Do not remove " ++ toDescr name ++ case def' of Just _ -> "" Nothing -> " (default)")) <|> pure def' toDescr = map (\c -> if c == '-' then ' ' else c) -- | Parser for arguments to `stack dot` dotOptsParser :: Parser DotOpts dotOptsParser = DotOpts <$> includeExternal <*> includeBase <*> depthLimit <*> fmap (maybe Set.empty Set.fromList . fmap splitNames) prunedPkgs where includeExternal = boolFlags False "external" "inclusion of external dependencies" idm includeBase = boolFlags True "include-base" "inclusion of dependencies on base" idm depthLimit = optional (option auto (long "depth" <> metavar "DEPTH" <> help ("Limit the depth of dependency resolution " <> "(Default: No limit)"))) prunedPkgs = optional (strOption (long "prune" <> metavar "PACKAGES" <> help ("Prune each package name " <> "from the comma separated list " <> "of package names PACKAGES"))) splitNames :: String -> [String] splitNames = map (takeWhile (not . isSpace) . dropWhile isSpace) . splitOn "," ghciOptsParser :: Parser GhciOpts ghciOptsParser = GhciOpts <$> many (textArgument (metavar "TARGET" <> help ("If none specified, " <> "use all packages defined in current directory"))) <*> fmap concat (many (argsOption (long "ghc-options" <> metavar "OPTION" <> help "Additional options passed to GHCi"))) <*> optional (strOption (long "with-ghc" <> metavar "GHC" <> help "Use this command for the GHC to run")) <*> flag False True (long "no-load" <> help "Don't load modules on start-up") <*> packagesParser <*> optional (textOption (long "main-is" <> metavar "TARGET" <> help "Specify which target should contain the main \ \module to load, such as for an executable for \ \test suite or benchmark.")) -- | Parser for exec command execOptsParser :: Maybe String -- ^ command -> Parser ExecOpts execOptsParser mcmd = ExecOpts <$> pure mcmd <*> eoArgsParser <*> execOptsExtraParser where eoArgsParser :: Parser [String] eoArgsParser = many (strArgument (metavar meta)) where meta = (maybe ("CMD ") (const "") mcmd) ++ "-- ARGS (e.g. stack ghc -- X.hs -o x)" evalOptsParser :: Maybe String -- ^ metavar -> Parser EvalOpts evalOptsParser mmeta = EvalOpts <$> eoArgsParser <*> execOptsExtraParser where eoArgsParser :: Parser String eoArgsParser = strArgument (metavar meta) meta = maybe ("CODE") id mmeta -- | Parser for extra options to exec command execOptsExtraParser :: Parser ExecOptsExtra execOptsExtraParser = eoPlainParser <|> ExecOptsEmbellished <$> eoEnvSettingsParser <*> eoPackagesParser where eoEnvSettingsParser :: Parser EnvSettings eoEnvSettingsParser = EnvSettings <$> pure True <*> boolFlags True "ghc-package-path" "setting the GHC_PACKAGE_PATH variable for the subprocess" idm <*> boolFlags True "stack-exe" "setting the STACK_EXE environment variable to the path for the stack executable" idm <*> pure False eoPackagesParser :: Parser [String] eoPackagesParser = many (strOption (long "package" <> help "Additional packages that must be installed")) eoPlainParser :: Parser ExecOptsExtra eoPlainParser = flag' ExecOptsPlain (long "plain" <> help "Use an unmodified environment (only useful with Docker)") -- | Parser for global command-line options. globalOptsParser :: Bool -> Parser GlobalOpts globalOptsParser defaultTerminal = GlobalOpts <$> optional (strOption (long Docker.reExecArgName <> hidden <> internal)) <*> logLevelOptsParser <*> configOptsParser False <*> optional abstractResolverOptsParser <*> flag defaultTerminal False (long "no-terminal" <> help "Override terminal detection in the case of running in a false terminal") <*> optional (strOption (long "stack-yaml" <> metavar "STACK-YAML" <> help ("Override project stack.yaml file " <> "(overrides any STACK_YAML environment variable)"))) initOptsParser :: Parser InitOpts initOptsParser = InitOpts <$> method <*> overwrite <*> fmap not ignoreSubDirs where ignoreSubDirs = flag False True (long "ignore-subdirs" <> help "Do not search for .cabal files in sub directories") overwrite = flag False True (long "force" <> help "Force overwriting of an existing stack.yaml if it exists") method = solver <|> (MethodResolver <$> resolver) <|> (MethodSnapshot <$> snapPref) solver = flag' MethodSolver (long "solver" <> help "Use a dependency solver to determine dependencies") snapPref = flag' PrefLTS (long "prefer-lts" <> help "Prefer LTS snapshots over Nightly snapshots") <|> flag' PrefNightly (long "prefer-nightly" <> help "Prefer Nightly snapshots over LTS snapshots") <|> pure PrefNone resolver = option readAbstractResolver (long "resolver" <> metavar "RESOLVER" <> help "Use the given resolver, even if not all dependencies are met") -- | Parse for a logging level. logLevelOptsParser :: Parser LogLevel logLevelOptsParser = fmap parse (strOption (long "verbosity" <> metavar "VERBOSITY" <> help "Verbosity: silent, error, warn, info, debug")) <|> flag defaultLogLevel verboseLevel (short 'v' <> long "verbose" <> help ("Enable verbose mode: verbosity level \"" <> showLevel verboseLevel <> "\"")) where verboseLevel = LevelDebug showLevel l = case l of LevelDebug -> "debug" LevelInfo -> "info" LevelWarn -> "warn" LevelError -> "error" LevelOther x -> T.unpack x parse s = case s of "debug" -> LevelDebug "info" -> LevelInfo "warn" -> LevelWarn "error" -> LevelError _ -> LevelOther (T.pack s) -- | Parser for the resolver abstractResolverOptsParser :: Parser AbstractResolver abstractResolverOptsParser = option readAbstractResolver (long "resolver" <> metavar "RESOLVER" <> help "Override resolver in project file") readAbstractResolver :: ReadM AbstractResolver readAbstractResolver = do s <- readerAsk case s of "global" -> return ARGlobal "nightly" -> return ARLatestNightly "lts" -> return ARLatestLTS 'l':'t':'s':'-':x | Right (x', "") <- decimal $ T.pack x -> return $ ARLatestLTSMajor x' _ -> case parseResolverText $ T.pack s of Left e -> readerError $ show e Right x -> return $ ARResolver x -- | GHC variant parser ghcVariantParser :: Parser GHCVariant ghcVariantParser = option readGHCVariant (long "ghc-variant" <> metavar "VARIANT" <> help "Specialized GHC variant, e.g. integersimple (implies --no-system-ghc)") where readGHCVariant = do s <- readerAsk case parseGHCVariant s of Left e -> readerError (show e) Right v -> return v -- | Parser for @solverCmd@ solverOptsParser :: Parser Bool solverOptsParser = boolFlags False "modify-stack-yaml" "Automatically modify stack.yaml with the solver's recommendations" idm -- | Parser for test arguments. testOptsParser :: Parser TestOpts testOptsParser = TestOpts <$> boolFlags True "rerun-tests" "running already successful tests" idm <*> fmap (fromMaybe []) (optional (argsOption(long "test-arguments" <> metavar "TEST_ARGS" <> help "Arguments passed in to the test suite program"))) <*> flag False True (long "coverage" <> help "Generate a code coverage report") <*> flag False True (long "no-run-tests" <> help "Disable running of tests. (Tests will still be built.)") -- | Parser for @stack new@. newOptsParser :: Parser (NewOpts,InitOpts) newOptsParser = (,) <$> newOpts <*> initOptsParser where newOpts = NewOpts <$> packageNameArgument (metavar "PACKAGE_NAME" <> help "A valid package name.") <*> switch (long "bare" <> help "Do not create a subdirectory for the project") <*> templateNameArgument (metavar "TEMPLATE_NAME" <> help "Name of a template, for example: foo or foo.hsfiles" <> value defaultTemplateName) <*> fmap M.fromList (many (templateParamArgument (short 'p' <> long "param" <> metavar "KEY:VALUE" <> help "Parameter for the template in the format key:value"))) <* abortOption ShowHelpText (long "help" <> help "Show help text.") pvpBoundsOption :: Parser PvpBounds pvpBoundsOption = option readPvpBounds (long "pvp-bounds" <> metavar "PVP-BOUNDS" <> help "How PVP version bounds should be added to .cabal file: none, lower, upper, both") where readPvpBounds = do s <- readerAsk case parsePvpBounds $ T.pack s of Left e -> readerError e Right v -> return v
meiersi-11ce/stack
src/Stack/Options.hs
bsd-3-clause
27,813
0
31
10,902
4,899
2,430
2,469
629
9
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE TupleSections #-} module Main where import Data.Monoid import Data.Maybe import Options.Generic import Sound.PortMidi import Graphics.Gloss import Graphics.Gloss.Interface.IO.Game import Graphics.Gloss.Juicy (loadJuicyPNG) import Musica.Render.Keyboard (renderKeyboard) import Musica.Render.Staff (renderStaff) import Musica.Midi.NoteStream import Musica.Midi.KeyMap import Control.Monad.Trans.Except import Control.Monad.IO.Class import Control.Monad -- stack build hmusica --copy-bins && (cd hmusica && hmusica-exe --deviceName "Midi Through Port-0" --panDivs 0.69 --midiFile songs/silent_night.mid; cd ..) defaultWindowWidth = fromMaybe 1920 defaultWindowHeight = fromMaybe 680 defaultMiddleCindex = fromMaybe 60 defaultKeysNumber = fromMaybe 61 defaultStaffTopLines = fromMaybe 3 defaultStaffBotLines = fromMaybe 5 defaultStaffZeroTick = fromMaybe (2 * 1000) defaultStaffClefSize = fromMaybe 5 defaultPanDivs = PanDivs 0.45 data Config = Config { windowWidth :: Maybe Int , windowHeight :: Maybe Int , deviceName :: String , middleCindex :: Maybe Int , keysNumber :: Maybe Int , panDivs :: [Float] , staffTopLines :: Maybe Int , staffBotLines :: Maybe Int , staffZeroTicks :: Maybe Int , staffClefSize :: Maybe Int , midiFile :: FilePath } deriving (Generic, Show) instance ParseRecord Config data PanDivs = PanDivs Float deriving Show data Musica = Musica { viewPort :: (Float, Float) , heightDivs :: PanDivs , staffRenderer :: Picture , kbRenderer :: [Bool] ->Picture } adjustTexture :: Monad m =>(Float, Float) ->Float ->Picture ->ExceptT String m Picture adjustTexture (cx, cy) s = \case bm@(Bitmap w h _ _) ->return $ scale s s $ translate cx cy bm p ->throwE $ "Cannot adjust clef. Image picture expected but `" <> show p <> "`." textureLoad :: (Float, Float) ->Float ->FilePath ->ExceptT String IO Picture textureLoad center scale file = liftIO (loadJuicyPNG file) >>= \case Just p ->adjustTexture center scale p Nothing ->throwE $ "Cannot load `" <> file <> "` image" getMidiDevices :: IO [(DeviceID, DeviceInfo)] getMidiDevices = do n <-countDevices mapM (\i ->(i,) <$> getDeviceInfo i) [0 .. n-1] getMidiStream :: Config ->ExceptT String IO PMStream getMidiStream cfg = do let devName = deviceName cfg selected <-filter (\(_,d) ->name d == devName && input d) <$> liftIO getMidiDevices case selected of [(i, _)] ->liftIO (openInput i) >>= either return (throwE . show) [] ->throwE $ "Input device `" <> devName <> "` not found" xs ->throwE $ "Input devide `" <> devName <> "` exists " <> show (length xs) <> " times" setupKeyMap :: Config ->PMStream ->ExceptT String IO KeyMap setupKeyMap cfg stream = do km <-liftIO $ makeKeyMap (defaultMiddleCindex (middleCindex cfg)) (defaultKeysNumber (keysNumber cfg)) liftIO $ updateKeyMapForever' 100 stream km return km getPanDivs :: Monad m =>Config ->ExceptT String m PanDivs getPanDivs cfg = case panDivs cfg of [] ->return defaultPanDivs xs@([a]) ->do when (minimum xs <= 0) $ throwE "Pan division cannot be equal or less than zero" when (maximum xs >= 1) $ throwE "Pan division cannot be equal or greater than one" when (any (<= 0) (zipWith (-) (tail xs) xs)) $ throwE "Pan divisions must be in ascending order and not repeated" return $ PanDivs a _ ->throwE "Excepted one and only one height pannel division factor" main' :: Config ->ExceptT String IO () main' cfg = do stream <-getMidiStream cfg km <-setupKeyMap cfg stream sol <-textureLoad (-34.0, 81.0) 1.45e-3 "gfx/sol.png" fa <-textureLoad (-12.0, -50.0) 1.74e-3 "gfx/fa.png" dlonga <-textureLoad ( -1.0, -85.0) 1.37e-3 "gfx/doublelonga.png" longa <-textureLoad ( 0.0, -89.0) 1.37e-3 "gfx/longa.png" breve <-textureLoad ( 0.0, 0.0) 1.28e-3 "gfx/breve.png" semibreve <-textureLoad ( -2.0, -4.0) 1.28e-3 "gfx/semibreve.png" minim <-textureLoad ( 1.0, 130.0) 1.37e-3 "gfx/minim.png" crotchet <-textureLoad ( -1.0, 130.0) 1.48e-3 "gfx/crotchet.png" quaver <-textureLoad ( 55.0, 172.0) 1.28e-3 "gfx/quaver.png" semiquaver <-textureLoad ( 42.0, 184.0) 1.37e-3 "gfx/semiquaver.png" dsquaver <-textureLoad ( 47.0, 233.0) 1.11e-3 "gfx/demisemiquaver.png" hdsquaver <-textureLoad ( 27.0, 127.0) 2.50e-3 "gfx/hemidemisemiquaver.png" dot <-textureLoad (135.0, 1.0) 1.37e-3 "gfx/dot.png" sharp <-textureLoad ( 0.0, 0.0) 1.28e-3 "gfx/sharp.png" kbbg <-textureLoad ( 0.0, 0.0) (1/250) "gfx/keyboard.png" nkstream <-liftIO $ noteStreamFromFile (midiFile cfg) "Piano" hdivs <-getPanDivs cfg let vp@(vpw, vph) = (defaultWindowWidth (windowWidth cfg), defaultWindowHeight (windowHeight cfg)) staffrenderer = renderStaff sol fa dlonga longa breve semibreve minim crotchet quaver semiquaver dsquaver hdsquaver dot sharp (defaultStaffTopLines (staffTopLines cfg)) (defaultStaffBotLines (staffBotLines cfg)) (defaultStaffZeroTick (staffZeroTicks cfg)) (defaultStaffClefSize (staffClefSize cfg)) (defaultMiddleCindex (middleCindex cfg)) (tempo nkstream) (-100) (notes nkstream) kbrenderer = renderKeyboard kbbg musica = Musica (fromIntegral vpw, fromIntegral vph) hdivs staffrenderer kbrenderer window = InWindow "HMusica" vp (0, 0) liftIO $ playIO window white 30 musica (renderMusica cfg km) interactiveMusica (const return) main :: IO () main = do cfg <-getRecord "HMusica" runExceptT (main' cfg) >>= \case Left e ->putStrLn $ "ERROR: " <> e Right () ->putStrLn $ "done" renderMusica :: Config ->KeyMap ->Musica ->IO Picture renderMusica cfg km mus = (renderMusica' cfg mus . map snd) <$> readKeyMap km renderMusica' :: Config ->Musica ->[Bool] ->Picture renderMusica' cfg mus st = let PanDivs hDiv1 = heightDivs mus (vw, vh) = viewPort mus (xA) = (-vw/2.2) (yA, yB, yC) = (a, a * (1 - hDiv1) + b * hDiv1, b) where { m = 0.9; s = m * vh; a = 0.5 * s; b = -0.5 * s } (s1, s2) = (yA - yB, yB - yC) staff = translate xA yA $ scale s1 s1 $ staffRenderer mus keyboard = translate 0 yB $ scale s2 s2 $ kbRenderer mus st in Pictures [staff, keyboard] interactiveMusica :: Event ->Musica ->IO Musica -- interactiveMusica (EventKey (SpecialKey KeyF2) Up _ m) mus = interactiveMusica _ mus = return mus
josejuan/midi-keyboard-player
app/Main.hs
bsd-3-clause
7,720
0
17
2,504
2,160
1,111
1,049
146
3
----------------------------------------------------------------------------- -- | -- Module : Distribution.Client.InstallPlan -- Copyright : (c) Duncan Coutts 2008 -- License : BSD-like -- -- Maintainer : [email protected] -- Stability : provisional -- Portability : portable -- -- Package installation plan -- ----------------------------------------------------------------------------- module Distribution.Client.InstallPlan ( InstallPlan, ConfiguredPackage(..), PlanPackage(..), -- * Operations on 'InstallPlan's new, toList, ready, completed, failed, remove, -- ** Query functions planPlatform, planCompiler, -- * Checking valididy of plans valid, closed, consistent, acyclic, configuredPackageValid, -- ** Details on invalid plans PlanProblem(..), showPlanProblem, PackageProblem(..), showPackageProblem, problems, configuredPackageProblems ) where import Distribution.Client.Types ( SourcePackage(packageDescription), ConfiguredPackage(..) , InstalledPackage , BuildFailure, BuildSuccess ) import Distribution.Package ( PackageIdentifier(..), PackageName(..), Package(..), packageName , PackageFixedDeps(..), Dependency(..) ) import Distribution.Version ( Version, withinRange ) import Distribution.PackageDescription ( GenericPackageDescription(genPackageFlags) , Flag(flagName), FlagName(..) ) import Distribution.Client.PackageUtils ( externalBuildDepends ) import Distribution.PackageDescription.Configuration ( finalizePackageDescription ) import Distribution.Client.PackageIndex ( PackageIndex ) import qualified Distribution.Client.PackageIndex as PackageIndex import Distribution.Text ( display ) import Distribution.System ( Platform ) import Distribution.Compiler ( CompilerId(..) ) import Distribution.Client.Utils ( duplicates, duplicatesBy, mergeBy, MergeResult(..) ) import Distribution.Simple.Utils ( comparing, intercalate ) import Data.List ( sort, sortBy ) import Data.Maybe ( fromMaybe ) import qualified Data.Graph as Graph import Data.Graph (Graph) import Control.Exception ( assert ) -- When cabal tries to install a number of packages, including all their -- dependencies it has a non-trivial problem to solve. -- -- The Problem: -- -- In general we start with a set of installed packages and a set of source -- packages. -- -- Installed packages have fixed dependencies. They have already been built and -- we know exactly what packages they were built against, including their exact -- versions. -- -- Source package have somewhat flexible dependencies. They are specified as -- version ranges, though really they're predicates. To make matters worse they -- have conditional flexible dependencies. Configuration flags can affect which -- packages are required and can place additional constraints on their -- versions. -- -- These two sets of package can and usually do overlap. There can be installed -- packages that are also available as source packages which means they could -- be re-installed if required, though there will also be packages which are -- not available as source and cannot be re-installed. Very often there will be -- extra versions available than are installed. Sometimes we may like to prefer -- installed packages over source ones or perhaps always prefer the latest -- available version whether installed or not. -- -- The goal is to calculate an installation plan that is closed, acyclic and -- consistent and where every configured package is valid. -- -- An installation plan is a set of packages that are going to be used -- together. It will consist of a mixture of installed packages and source -- packages along with their exact version dependencies. An installation plan -- is closed if for every package in the set, all of its dependencies are -- also in the set. It is consistent if for every package in the set, all -- dependencies which target that package have the same version. -- Note that plans do not necessarily compose. You might have a valid plan for -- package A and a valid plan for package B. That does not mean the composition -- is simultaniously valid for A and B. In particular you're most likely to -- have problems with inconsistent dependencies. -- On the other hand it is true that every closed sub plan is valid. data PlanPackage = PreExisting InstalledPackage | Configured ConfiguredPackage | Installed ConfiguredPackage BuildSuccess | Failed ConfiguredPackage BuildFailure instance Package PlanPackage where packageId (PreExisting pkg) = packageId pkg packageId (Configured pkg) = packageId pkg packageId (Installed pkg _) = packageId pkg packageId (Failed pkg _) = packageId pkg instance PackageFixedDeps PlanPackage where depends (PreExisting pkg) = depends pkg depends (Configured pkg) = depends pkg depends (Installed pkg _) = depends pkg depends (Failed pkg _) = depends pkg data InstallPlan = InstallPlan { planIndex :: PackageIndex PlanPackage, planGraph :: Graph, planGraphRev :: Graph, planPkgOf :: Graph.Vertex -> PlanPackage, planVertexOf :: PackageIdentifier -> Graph.Vertex, planPlatform :: Platform, planCompiler :: CompilerId } invariant :: InstallPlan -> Bool invariant plan = valid (planPlatform plan) (planCompiler plan) (planIndex plan) internalError :: String -> a internalError msg = error $ "InstallPlan: internal error: " ++ msg -- | Build an installation plan from a valid set of resolved packages. -- new :: Platform -> CompilerId -> PackageIndex PlanPackage -> Either [PlanProblem] InstallPlan new platform compiler index = case problems platform compiler index of [] -> Right InstallPlan { planIndex = index, planGraph = graph, planGraphRev = Graph.transposeG graph, planPkgOf = vertexToPkgId, planVertexOf = fromMaybe noSuchPkgId . pkgIdToVertex, planPlatform = platform, planCompiler = compiler } where (graph, vertexToPkgId, pkgIdToVertex) = PackageIndex.dependencyGraph index noSuchPkgId = internalError "package is not in the graph" probs -> Left probs toList :: InstallPlan -> [PlanPackage] toList = PackageIndex.allPackages . planIndex -- | Remove packages from the install plan. This will result in an -- error if there are remaining packages that depend on any matching -- package. This is primarily useful for obtaining an install plan for -- the dependencies of a package or set of packages without actually -- installing the package itself, as when doing development. -- remove :: (PlanPackage -> Bool) -> InstallPlan -> Either [PlanProblem] InstallPlan remove shouldRemove plan = new (planPlatform plan) (planCompiler plan) newIndex where newIndex = PackageIndex.fromList $ filter (not . shouldRemove) (toList plan) -- | The packages that are ready to be installed. That is they are in the -- configured state and have all their dependencies installed already. -- The plan is complete if the result is @[]@. -- ready :: InstallPlan -> [ConfiguredPackage] ready plan = assert check readyPackages where check = if null readyPackages then null configuredPackages else True configuredPackages = [ pkg | Configured pkg <- PackageIndex.allPackages (planIndex plan) ] readyPackages = filter (all isInstalled . depends) configuredPackages isInstalled pkg = case PackageIndex.lookupPackageId (planIndex plan) pkg of Just (Configured _) -> False Just (Failed _ _) -> internalError depOnFailed Just (PreExisting _) -> True Just (Installed _ _) -> True Nothing -> internalError incomplete incomplete = "install plan is not closed" depOnFailed = "configured package depends on failed package" -- | Marks a package in the graph as completed. Also saves the build result for -- the completed package in the plan. -- -- * The package must exist in the graph. -- * The package must have had no uninstalled dependent packages. -- completed :: PackageIdentifier -> BuildSuccess -> InstallPlan -> InstallPlan completed pkgid buildResult plan = assert (invariant plan') plan' where plan' = plan { planIndex = PackageIndex.insert installed (planIndex plan) } installed = Installed (lookupConfiguredPackage plan pkgid) buildResult -- | Marks a package in the graph as having failed. It also marks all the -- packages that depended on it as having failed. -- -- * The package must exist in the graph and be in the configured state. -- failed :: PackageIdentifier -- ^ The id of the package that failed to install -> BuildFailure -- ^ The build result to use for the failed package -> BuildFailure -- ^ The build result to use for its dependencies -> InstallPlan -> InstallPlan failed pkgid buildResult buildResult' plan = assert (invariant plan') plan' where plan' = plan { planIndex = PackageIndex.merge (planIndex plan) failures } pkg = lookupConfiguredPackage plan pkgid failures = PackageIndex.fromList $ Failed pkg buildResult : [ Failed pkg' buildResult' | Just pkg' <- map checkConfiguredPackage $ packagesThatDependOn plan pkgid ] -- | lookup the reachable packages in the reverse dependency graph -- packagesThatDependOn :: InstallPlan -> PackageIdentifier -> [PlanPackage] packagesThatDependOn plan = map (planPkgOf plan) . tail . Graph.reachable (planGraphRev plan) . planVertexOf plan -- | lookup a package that we expect to be in the configured state -- lookupConfiguredPackage :: InstallPlan -> PackageIdentifier -> ConfiguredPackage lookupConfiguredPackage plan pkgid = case PackageIndex.lookupPackageId (planIndex plan) pkgid of Just (Configured pkg) -> pkg _ -> internalError $ "not configured or no such pkg " ++ display pkgid -- | check a package that we expect to be in the configured or failed state -- checkConfiguredPackage :: PlanPackage -> Maybe ConfiguredPackage checkConfiguredPackage (Configured pkg) = Just pkg checkConfiguredPackage (Failed _ _) = Nothing checkConfiguredPackage pkg = internalError $ "not configured or no such pkg " ++ display (packageId pkg) -- ------------------------------------------------------------ -- * Checking valididy of plans -- ------------------------------------------------------------ -- | A valid installation plan is a set of packages that is 'acyclic', -- 'closed' and 'consistent'. Also, every 'ConfiguredPackage' in the -- plan has to have a valid configuration (see 'configuredPackageValid'). -- -- * if the result is @False@ use 'problems' to get a detailed list. -- valid :: Platform -> CompilerId -> PackageIndex PlanPackage -> Bool valid platform comp index = null (problems platform comp index) data PlanProblem = PackageInvalid ConfiguredPackage [PackageProblem] | PackageMissingDeps PlanPackage [PackageIdentifier] | PackageCycle [PlanPackage] | PackageInconsistency PackageName [(PackageIdentifier, Version)] | PackageStateInvalid PlanPackage PlanPackage showPlanProblem :: PlanProblem -> String showPlanProblem (PackageInvalid pkg packageProblems) = "Package " ++ display (packageId pkg) ++ " has an invalid configuration, in particular:\n" ++ unlines [ " " ++ showPackageProblem problem | problem <- packageProblems ] showPlanProblem (PackageMissingDeps pkg missingDeps) = "Package " ++ display (packageId pkg) ++ " depends on the following packages which are missing from the plan " ++ intercalate ", " (map display missingDeps) showPlanProblem (PackageCycle cycleGroup) = "The following packages are involved in a dependency cycle " ++ intercalate ", " (map (display.packageId) cycleGroup) showPlanProblem (PackageInconsistency name inconsistencies) = "Package " ++ display name ++ " is required by several packages," ++ " but they require inconsistent versions:\n" ++ unlines [ " package " ++ display pkg ++ " requires " ++ display (PackageIdentifier name ver) | (pkg, ver) <- inconsistencies ] showPlanProblem (PackageStateInvalid pkg pkg') = "Package " ++ display (packageId pkg) ++ " is in the " ++ showPlanState pkg ++ " state but it depends on package " ++ display (packageId pkg') ++ " which is in the " ++ showPlanState pkg' ++ " state" where showPlanState (PreExisting _) = "pre-existing" showPlanState (Configured _) = "configured" showPlanState (Installed _ _) = "installed" showPlanState (Failed _ _) = "failed" -- | For an invalid plan, produce a detailed list of problems as human readable -- error messages. This is mainly intended for debugging purposes. -- Use 'showPlanProblem' for a human readable explanation. -- problems :: Platform -> CompilerId -> PackageIndex PlanPackage -> [PlanProblem] problems platform comp index = [ PackageInvalid pkg packageProblems | Configured pkg <- PackageIndex.allPackages index , let packageProblems = configuredPackageProblems platform comp pkg , not (null packageProblems) ] ++ [ PackageMissingDeps pkg missingDeps | (pkg, missingDeps) <- PackageIndex.brokenPackages index ] ++ [ PackageCycle cycleGroup | cycleGroup <- PackageIndex.dependencyCycles index ] ++ [ PackageInconsistency name inconsistencies | (name, inconsistencies) <- PackageIndex.dependencyInconsistencies index ] ++ [ PackageStateInvalid pkg pkg' | pkg <- PackageIndex.allPackages index , Just pkg' <- map (PackageIndex.lookupPackageId index) (depends pkg) , not (stateDependencyRelation pkg pkg') ] -- | The graph of packages (nodes) and dependencies (edges) must be acyclic. -- -- * if the result is @False@ use 'PackageIndex.dependencyCycles' to find out -- which packages are involved in dependency cycles. -- acyclic :: PackageIndex PlanPackage -> Bool acyclic = null . PackageIndex.dependencyCycles -- | An installation plan is closed if for every package in the set, all of -- its dependencies are also in the set. That is, the set is closed under the -- dependency relation. -- -- * if the result is @False@ use 'PackageIndex.brokenPackages' to find out -- which packages depend on packages not in the index. -- closed :: PackageIndex PlanPackage -> Bool closed = null . PackageIndex.brokenPackages -- | An installation plan is consistent if all dependencies that target a -- single package name, target the same version. -- -- This is slightly subtle. It is not the same as requiring that there be at -- most one version of any package in the set. It only requires that of -- packages which have more than one other package depending on them. We could -- actually make the condition even more precise and say that different -- versions are ok so long as they are not both in the transative closure of -- any other package (or equivalently that their inverse closures do not -- intersect). The point is we do not want to have any packages depending -- directly or indirectly on two different versions of the same package. The -- current definition is just a safe aproximation of that. -- -- * if the result is @False@ use 'PackageIndex.dependencyInconsistencies' to -- find out which packages are. -- consistent :: PackageIndex PlanPackage -> Bool consistent = null . PackageIndex.dependencyInconsistencies -- | The states of packages have that depend on each other must respect -- this relation. That is for very case where package @a@ depends on -- package @b@ we require that @dependencyStatesOk a b = True@. -- stateDependencyRelation :: PlanPackage -> PlanPackage -> Bool stateDependencyRelation (PreExisting _) (PreExisting _) = True stateDependencyRelation (Configured _) (PreExisting _) = True stateDependencyRelation (Configured _) (Configured _) = True stateDependencyRelation (Configured _) (Installed _ _) = True stateDependencyRelation (Installed _ _) (PreExisting _) = True stateDependencyRelation (Installed _ _) (Installed _ _) = True stateDependencyRelation (Failed _ _) (PreExisting _) = True -- failed can depends on configured because a package can depend on -- several other packages and if one of the deps fail then we fail -- but we still depend on the other ones that did not fail: stateDependencyRelation (Failed _ _) (Configured _) = True stateDependencyRelation (Failed _ _) (Installed _ _) = True stateDependencyRelation (Failed _ _) (Failed _ _) = True stateDependencyRelation _ _ = False -- | A 'ConfiguredPackage' is valid if the flag assignment is total and if -- in the configuration given by the flag assignment, all the package -- dependencies are satisfied by the specified packages. -- configuredPackageValid :: Platform -> CompilerId -> ConfiguredPackage -> Bool configuredPackageValid platform comp pkg = null (configuredPackageProblems platform comp pkg) data PackageProblem = DuplicateFlag FlagName | MissingFlag FlagName | ExtraFlag FlagName | DuplicateDeps [PackageIdentifier] | MissingDep Dependency | ExtraDep PackageIdentifier | InvalidDep Dependency PackageIdentifier showPackageProblem :: PackageProblem -> String showPackageProblem (DuplicateFlag (FlagName flag)) = "duplicate flag in the flag assignment: " ++ flag showPackageProblem (MissingFlag (FlagName flag)) = "missing an assignment for the flag: " ++ flag showPackageProblem (ExtraFlag (FlagName flag)) = "extra flag given that is not used by the package: " ++ flag showPackageProblem (DuplicateDeps pkgids) = "duplicate packages specified as selected dependencies: " ++ intercalate ", " (map display pkgids) showPackageProblem (MissingDep dep) = "the package has a dependency " ++ display dep ++ " but no package has been selected to satisfy it." showPackageProblem (ExtraDep pkgid) = "the package configuration specifies " ++ display pkgid ++ " but (with the given flag assignment) the package does not actually" ++ " depend on any version of that package." showPackageProblem (InvalidDep dep pkgid) = "the package depends on " ++ display dep ++ " but the configuration specifies " ++ display pkgid ++ " which does not satisfy the dependency." configuredPackageProblems :: Platform -> CompilerId -> ConfiguredPackage -> [PackageProblem] configuredPackageProblems platform comp (ConfiguredPackage pkg specifiedFlags specifiedDeps) = [ DuplicateFlag flag | ((flag,_):_) <- duplicates specifiedFlags ] ++ [ MissingFlag flag | OnlyInLeft flag <- mergedFlags ] ++ [ ExtraFlag flag | OnlyInRight flag <- mergedFlags ] ++ [ DuplicateDeps pkgs | pkgs <- duplicatesBy (comparing packageName) specifiedDeps ] ++ [ MissingDep dep | OnlyInLeft dep <- mergedDeps ] ++ [ ExtraDep pkgid | OnlyInRight pkgid <- mergedDeps ] ++ [ InvalidDep dep pkgid | InBoth dep pkgid <- mergedDeps , not (packageSatisfiesDependency pkgid dep) ] where mergedFlags = mergeBy compare (sort $ map flagName (genPackageFlags (packageDescription pkg))) (sort $ map fst specifiedFlags) mergedDeps = mergeBy (\dep pkgid -> dependencyName dep `compare` packageName pkgid) (sortBy (comparing dependencyName) requiredDeps) (sortBy (comparing packageName) specifiedDeps) packageSatisfiesDependency (PackageIdentifier name version) (Dependency name' versionRange) = assert (name == name') $ version `withinRange` versionRange dependencyName (Dependency name _) = name requiredDeps :: [Dependency] requiredDeps = --TODO: use something lower level than finalizePackageDescription case finalizePackageDescription specifiedFlags (const True) platform comp [] (packageDescription pkg) of Right (resolvedPkg, _) -> externalBuildDepends resolvedPkg Left _ -> error "configuredPackageInvalidDeps internal error"
IreneKnapp/Faction
faction/Distribution/Client/InstallPlan.hs
bsd-3-clause
20,722
0
16
4,525
3,540
1,914
1,626
303
6
{-# OPTIONS -O2 -fglasgow-exts #-} module Units where import System.IO import qualified Data.Map as M import Text.StringTemplate.Classes import Text.StringTemplate.Instances import Text.StringTemplate.Base import Text.StringTemplate.Group import Test.HUnit import Control.Monad import System.Environment no_prop = toString (setAttribute "foo" "f" $ newSTMP "a$foo.bar$a") ~=? "aa" one_prop = toString (setAttribute "foo" (M.singleton "bar" "baz") $ newSTMP "a$foo.bar$a") ~=? "abaza" anon_tmpl = toString (setAttribute "foo" "f" $ newSTMP "a$foo:{{$foo$\\}}$a") ~=? "a{f}a" setA = setAttribute "foo" ["a","b","c"] func_first = toString (setA $ newSTMP "$first(foo)$") ~=? "a" func_last = toString (setA $ newSTMP "$last(foo)$") ~=? "c" func_rest = toString (setA $ newSTMP "$rest(foo)$") ~=? "bc" func_length = toString (setA $ newSTMP "$length(foo)$") ~=? "3" func_reverse = toString (setA $ newSTMP "$reverse(foo)$") ~=? "cba" tests = TestList ["no_prop" ~: no_prop, "one_prop" ~: one_prop, "func_first" ~: func_first, "func_last" ~: func_last, "func_rest" ~: func_rest, "func_reverse" ~: func_reverse, "func_length" ~: func_length, "anon_tmpl" ~: anon_tmpl] main = do c <- runTestTT tests when (errors c > 0 || failures c > 0) $ fail "Not all tests passed."
factisresearch/HStringTemplate
tests/Units.hs
bsd-3-clause
1,436
0
13
339
390
206
184
35
1
{-# LANGUAGE ForeignFunctionInterface, FlexibleContexts, TypeFamilies #-} {-# LANGUAGE CPP #-} #if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 702 {-# LANGUAGE Trustworthy #-} #endif module Numeric.Extras ( RealExtras(..) ) where #if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ < 710 import Control.Applicative ((<$>), (<*>)) #endif import Control.Arrow ((***)) import Foreign import Foreign.C.Types #if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 702 import System.IO.Unsafe (unsafeDupablePerformIO) #else import System.IO.Unsafe (unsafePerformIO) #endif {-# ANN module "HLint: ignore Use camelCase" #-} class (Storable (C a), RealFloat (C a), RealFloat a) => RealExtras a where type C a :: * fmod :: a -> a -> a expm1 :: a -> a log1p :: a -> a hypot :: a -> a -> a cbrt :: a -> a erf :: a -> a floor :: a -> a ceil :: a -> a round :: a -> a trunc :: a -> a modf :: a -> (a, a) remainder :: a -> a -> a instance RealExtras Double where type C Double = CDouble fmod = lift2D c_fmod expm1 = lift1D c_expm1 log1p = lift1D c_log1p hypot = lift2D c_hypot cbrt = lift1D c_cbrt erf = lift1D c_erf floor = lift1D c_floor ceil = lift1D c_ceil round = lift1D c_round trunc = lift1D c_trunc modf = lift1D2 c_modf remainder = lift2D c_remainder lift1D :: (CDouble -> CDouble) -> Double -> Double lift1D f a = realToFrac (f (realToFrac a)) {-# INLINE lift1D #-} lift1D2 :: (CDouble -> (CDouble, CDouble)) -> Double -> (Double, Double) lift1D2 f a = (realToFrac *** realToFrac) (f (realToFrac a)) {-# INLINE lift1D2 #-} lift2D :: (CDouble -> CDouble -> CDouble) -> Double -> Double -> Double lift2D f a b = realToFrac (f (realToFrac a) (realToFrac b)) {-# INLINE lift2D #-} c_modf :: CDouble -> (CDouble, CDouble) #if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 702 c_modf a = unsafeDupablePerformIO $ alloca $ \i -> (,) <$> c_modf_imp a i <*> peek i #else c_modf a = unsafePerformIO $ alloca $ \i -> (,) <$> c_modf_imp a i <*> peek i #endif instance RealExtras Float where type C Float = CFloat fmod = lift2F c_fmodf expm1 = lift1F c_expm1f log1p = lift1F c_log1pf hypot = lift2F c_hypotf cbrt = lift1F c_cbrtf erf = lift1F c_erff floor = lift1F c_floorf ceil = lift1F c_ceilf round = lift1F c_roundf trunc = lift1F c_truncf modf = lift1F2 c_modff remainder = lift2F c_remainderf lift1F :: (CFloat -> CFloat) -> Float -> Float lift1F f a = realToFrac (f (realToFrac a)) {-# INLINE lift1F #-} lift1F2 :: (CFloat -> (CFloat, CFloat)) -> Float -> (Float, Float) lift1F2 f a = (realToFrac *** realToFrac) (f (realToFrac a)) {-# INLINE lift1F2 #-} lift2F :: (CFloat -> CFloat -> CFloat) -> Float -> Float -> Float lift2F f a b = realToFrac (f (realToFrac a) (realToFrac b)) {-# INLINE lift2F #-} c_modff :: CFloat -> (CFloat, CFloat) #if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 702 c_modff a = unsafeDupablePerformIO $ alloca $ \i -> (,) <$> c_modff_imp a i <*> peek i #else c_modff a = unsafePerformIO $ alloca $ \i -> (,) <$> c_modff_imp a i <*> peek i #endif foreign import ccall unsafe "math.h fmod" c_fmod :: CDouble -> CDouble -> CDouble foreign import ccall unsafe "math.h expm1" c_expm1 :: CDouble -> CDouble foreign import ccall unsafe "math.h log1p" c_log1p :: CDouble -> CDouble foreign import ccall unsafe "math.h hypot" c_hypot :: CDouble -> CDouble -> CDouble foreign import ccall unsafe "math.h cbrt" c_cbrt :: CDouble -> CDouble foreign import ccall unsafe "math.h erf" c_erf :: CDouble -> CDouble foreign import ccall unsafe "math.h floor" c_floor :: CDouble -> CDouble foreign import ccall unsafe "math.h ceil" c_ceil :: CDouble -> CDouble foreign import ccall unsafe "math.h round" c_round :: CDouble -> CDouble foreign import ccall unsafe "math.h trunc" c_trunc :: CDouble -> CDouble foreign import ccall unsafe "math.h modf" c_modf_imp :: CDouble -> Ptr CDouble -> IO CDouble foreign import ccall unsafe "math.h remainder" c_remainder :: CDouble -> CDouble -> CDouble foreign import ccall unsafe "math.h fmodf" c_fmodf :: CFloat -> CFloat -> CFloat foreign import ccall unsafe "math.h expm1f" c_expm1f :: CFloat -> CFloat foreign import ccall unsafe "math.h log1pf" c_log1pf :: CFloat -> CFloat foreign import ccall unsafe "math.h hypotf" c_hypotf :: CFloat -> CFloat -> CFloat foreign import ccall unsafe "math.h cbrtf" c_cbrtf :: CFloat -> CFloat foreign import ccall unsafe "math.h erff" c_erff :: CFloat -> CFloat foreign import ccall unsafe "math.h floorf" c_floorf :: CFloat -> CFloat foreign import ccall unsafe "math.h ceilf" c_ceilf :: CFloat -> CFloat foreign import ccall unsafe "math.h roundf" c_roundf :: CFloat -> CFloat foreign import ccall unsafe "math.h truncf" c_truncf :: CFloat -> CFloat foreign import ccall unsafe "math.h modff" c_modff_imp :: CFloat -> Ptr CFloat -> IO CFloat foreign import ccall unsafe "math.h remainderf" c_remainderf :: CFloat -> CFloat -> CFloat default (Double)
ekmett/numeric-extras
Numeric/Extras.hs
bsd-3-clause
5,161
0
9
1,089
1,424
778
646
122
1
module Crawl.Backoff ( backoff ) where import Control.Applicative import qualified Reactive.Banana as R backoff :: (m -> Bool) -> R.Event t (m, Int) -> R.Behavior t Int -> R.Behavior t Bool backoff mf failures time = backoffPolicy <$> time <*> past_failures where my_failures = fmap snd $ R.filterE (mf . fst) failures past_failures = R.accumB [] (fmap (:) my_failures) -- Check if for any n, there are at least n elements of t that are >= t - 2^n backoffPolicy :: Int -> [Int] -> Bool backoffPolicy t ts = or $ zipWith (\n t' -> t' >= t - 2^n) [1::Int ..] ts
rwbarton/rw
Crawl/Backoff.hs
bsd-3-clause
578
0
11
122
214
116
98
10
1
{-# LANGUAGE ScopedTypeVariables, TypeOperators #-} {- 2012 Joel Svensson -} module Test where import qualified Intel.ArbbVM as VM import qualified Intel.ArbbVM.Convenience as VM import Intel.ArBB.Vector import Intel.ArBB.Data.Int import Intel.ArBB.Data.Boolean import Intel.ArBB import Intel.ArBB.Language as Lang import Intel.ArBB.Backend.ArBB import Intel.ArBB.Util.Image import qualified Data.Vector.Storable as V import Foreign.Marshal.Array import qualified Foreign.Marshal.Utils as Utils import Foreign.Ptr import Data.Int import Data.Word import Data.IORef import qualified Data.Map as Map import Control.Monad.State hiding (liftIO) import Prelude as P test1 = withArBB $ do f <- capture redChan g <- capture greenChan h <- capture blueChan tg <- capture toGray -- Naive str <- serialize f liftIO$ putStrLn str img <- liftIO$ loadBMP_RGB "image1.bmp" bmp' <- copyIn img r1 <- new (Z:.256:.256) 0 r2 <- new (Z:.256:.256) 0 r3 <- new (Z:.256:.256) 0 r4 <- new (Z:.256:.256) 0 execute f bmp' r1 execute g bmp' r2 execute h bmp' r3 execute tg bmp' r4 r1' <- copyOut r1 r2' <- copyOut r2 r3' <- copyOut r3 r4' <- copyOut r4 --liftIO$ putStrLn $ show r1' --liftIO$ putStrLn $ show r2' --liftIO$ putStrLn $ show r3' liftIO$ putStrLn $ show r4' liftIO$ putStrLn "Done!" where redChan :: Exp (DVector Dim3 Word8) -> Exp (DVector Dim2 Word8) redChan v = extractPage 0 v greenChan :: Exp (DVector Dim3 Word8) -> Exp (DVector Dim2 Word8) greenChan v = extractPage 1 v blueChan :: Exp (DVector Dim3 Word8) -> Exp (DVector Dim2 Word8) blueChan v = extractPage 2 v testToGray= withArBB $ do tg <- capture toGray -- Naive str <- serialize tg liftIO$ putStrLn str img <- liftIO$ loadBMP_RGB "image2.bmp" bmp' <- copyIn img r <- new (Z:.256:.256) 0 execute tg bmp' r r' <- copyOut r liftIO$ saveBMP_Gray "out.bmp" r' -- liftIO$ putStrLn $ show r' liftIO$ putStrLn "Done!" testWriteBmp = do img <- loadBMP_RGB "image2.bmp" saveBMP_RGB "image3.bmp" img {- segPrefixSum :: Exp (DVector Dim1 Float) -> Exp (DVector Dim1 USize) -> Exp (DVector Dim1 Float) segPrefixSum v1 v2 = flattenSeg $ addScanSeg (applyNesting v1 v2 1) testSegPrefixSum = withArBB $ do f <- capture segPrefixSum let v1 = V.fromList [1,3,5,7,9,11,13,15] v2 = V.fromList [4,4] v3 <- copyIn $ mkDVector v1 (Z :. 8) v4 <- copyIn $ mkDVector v2 (Z :. 2) r1 <- new (Z :. 8) 0 execute f (v3 :- v4) r1 r <- copyOut r1 liftIO$ putStrLn$ show r -} testBool = withArBB $ do f <- capture bt let v1 = V.fromList [B True,B True,B True,B True,B True,B True,B True,B True] v <- copyIn $ mkDVector v1 (Z:.8) r1 <- new (Z:.8) (B False) execute f v r1 r <- copyOut r1 liftIO$ putStrLn$ show r where bt :: Exp (DVector Dim1 Boolean) -> Exp (DVector Dim1 Boolean) bt v = andScan 0 0 v testSort = withArBB $ do f <- capture s let v1 = V.fromList [1,4,3,5,7,9,8,2,6] v <- copyIn $ mkDVector v1 (Z:.8) r1 <- new (Z:.8) 0 execute f v r1 r <- copyOut r1 liftIO$ putStrLn$ show r where s :: Exp (DVector Dim1 Float) -> Exp (DVector Dim1 Float) s v = sort 0 v testDistr = withArBB $ do f <- capture d let v1 = V.fromList [1,4,3,5,7,9,8,2,6] let v2 = V.fromList [2,2,2,2,2,2,2,2,2::USize] va <- copyIn $ mkDVector v1 (Z:.8) vb <- copyIn $ mkDVector v2 (Z:.8) r1 <- new (Z:.16) 0 execute f (va :- vb) r1 r <- copyOut r1 liftIO$ putStrLn$ show r where d :: Exp (DVector Dim1 Float) -> Exp (DVector Dim1 USize) -> Exp (DVector Dim1 Float) d v0 v1 = stretchBy v0 v1 -- smvm :: EV1 Int32 -> EV1 USize -> EV1 USize -> EV1 Int32 -> EV1 Int32 smvm :: Exp (DVector Dim1 Float) -> Exp (DVector Dim1 USize) -> Exp (DVector Dim1 USize) -> Exp (DVector Dim1 Float) -> Exp (DVector Dim1 Float) smvm mval cidx os vec = addReduceSeg nps where ps = mval * gather1D cidx 0 vec nps = applyNesting offsets os ps testDist2 = withArBB $ do f <- capture smvm -- mval, cidx, rowptr is the 3-array compressed sparse row rep. (apparently) let mval = V.fromList [1..9] cidx = V.fromList [1,0,2,3,1,4,1,4,2] rowptr = V.fromList [0,1,4,6,8] vec = V.fromList [1..5] mval1 <- copyIn $ mkDVector mval (Z :. 9) cidx1 <- copyIn $ mkDVector cidx (Z :. 9) rowptr1 <- copyIn $ mkDVector rowptr (Z :. 5) vec1 <- copyIn $ mkDVector vec (Z :. 5) r1 <- new (Z :. 5) 0 execute f (mval1 :- cidx1 :- rowptr1 :- vec1) r1 r <- copyOut r1 liftIO$ putStrLn$ show r
svenssonjoel/EmbArBB
Test2.hs
bsd-3-clause
5,200
0
13
1,705
1,786
886
900
130
1
{-#LANGUAGE OverloadedStrings#-} module Lib ( bioParser ) where import MergeFastq (mergePairedEndFq) import ParseGtf (collapseGtf) import ParseSam (tagSamWithGtf, samToMatrix) import System.Environment import qualified Safe as S import qualified Data.ByteString.Char8 as B8 (putStrLn) bioParser = do args <- getArgs case (S.headDef "mergePairedEndFq" args) of "mergePairedEndFq" -> mergePairedEndFq (args!!1) (args!!2) "collapseGtf" -> collapseGtf (args!!1) (args!!2) "tagSamWithGtf" -> tagSamWithGtf (args!!1) (args!!2) (args!!3) "samToMatrix" -> samToMatrix (init $ drop 1 $ args) (last args) otherwise -> B8.putStrLn "Not an option"
Min-/BioParsers
src/Lib.hs
bsd-3-clause
700
0
14
139
217
120
97
17
5
{-| -} module Database.OrgMode.Types where import Data.Aeson import Data.Default import Data.Int (Int64) import GHC.Generics import Database.OrgMode.Internal.Types import Database.OrgMode.Internal.Import -------------------------------------------------------------------------------- {-| Represents a summary of a 'Heading' that only contains the title and the total duration of all clocks for the 'Heading'. Is made to be used when displaying clock tables and other types of overviews. -} data HeadingShort = HeadingShort { headingShortDocId :: Int64 , headingShortId :: Int64 , headingShortParId :: Maybe Int64 , headingShortTitle :: Text , headingShortDuration :: Int , headingShortSubs :: [HeadingShort] } deriving (Show, Generic) instance ToJSON HeadingShort {-| Represents a row in a 'ClockTable'. Each row consists of the name of the document, how long the total duration is (all 'Heading's clocks combined) and a list of 'HeadingShort's. -} data ClockRow = ClockRow { clockRowDocumentId :: Int64 -- ^ Document all shorts belong to , clockRowDuration :: Int -- ^ Total duration of all shorts , clockRowShorts :: [HeadingShort] -- ^ Matching shorts of this row } deriving (Show, Generic) instance ToJSON ClockRow {-| Represents a clock table which contains 'ClockRow's and a date range that 'Heading's are shown based on their clockings. -} data ClockTable = ClockTable { clockTableRows :: [ClockRow] -- ^ Matching rows , clockTableFilter :: HeadingFilter -- ^ Filter used to build the table } deriving (Show) {-| Represents a filter that is used when retrieving 'Heading's, is used when building 'ClockTable's for example. 'HeadingFilter' implements the 'Default' type class so you can use the 'def' function from "Data.Default" to supply a filter with no constraints. Start of date range matches clocks that start on or after given date. For example say we have this 'Heading' parsed and saved in the database: >* This is a root section > CLOCK: [2015-10-12 Sun 00:00]--[2015-10-15 Sun 00:00] => 72:00 This filter will produce a match: > import Data.Time.Calendar (fromGregorian) > import Data.Time.Clock (secondsToDiffTime, UTCTime(..)) > > let startT = UTCTime (fromGregorian 2015 10 11) (secondsToDiffTime 0) > HeadingFilter (Just startT) Nothing [] But using this filter will not: > let startT = UTCTime (fromGregorian 2015 10 15) (secondsToDiffTime 0) > HeadingFilter (Just startT) Nothing [] End of date range matches clocks that end on or before given date. This filter will produce a match: > let endT = UTCTime (fromGregorian 2015 10 14) (secondsToDiffTime 0) > HeadingFilter Nothing (Just endT) [] But using this filter will not: > let endT = UTCTime (fromGregorian 2015 10 16) (secondsToDiffTime 0) > HeadingFilter Nothing (Just endT) [] This date range filter will produce a match: > let startT = UTCTime (fromGregorian 2015 10 11) (secondsToDiffTime 0) > endT = UTCTime (fromGregorian 2015 10 16) (secondsToDiffTime 0) > HeadingFilter (Just startT) (Just endT) [] But using this filter will not: > let startT = UTCTime (fromGregorian 2015 10 13) (secondsToDiffTime 0) > endT = UTCTime (fromGregorian 2015 10 16) (secondsToDiffTime 0) > HeadingFilter (Just startT) (Just endT) [] This will not either: > let startT = UTCTime (fromGregorian 2015 10 11) (secondsToDiffTime 0) > endT = UTCTime (fromGregorian 2015 10 14) (secondsToDiffTime 0) > HeadingFilter (Just startT) (Just endT) [] This means when you supply a date range it will only match clocks that start and end within the range. Using an empty list of 'Document' IDs means matching all 'Document's. -} data HeadingFilter = HeadingFilter { headingFilterClockStart :: Maybe UTCTime -- ^ Start of date range , headingFilterClockEnd :: Maybe UTCTime -- ^ End of date range , headingFilterDocumentIds :: [(Key Document)] -- ^ Documents to get items from } deriving (Show) instance Default HeadingFilter where def = HeadingFilter Nothing Nothing []
rzetterberg/orgmode-sql
lib/Database/OrgMode/Types.hs
bsd-3-clause
4,141
0
11
814
279
171
108
33
0
-- | This module provides the /With Certification/ processor. -- Is used to certify the proof output of a (sub) strategy. module Tct.Trs.Processor.WithCertification ( withCertificationDeclaration , withCertification , withCertification' -- * arguments , TotalProof (..) ) where import qualified Tct.Core.Data as T import Tct.Trs.Data import qualified Tct.Trs.Data.CeTA as CeTA -- TODO: MS: the behaviour should be changed; return some feedback (not an error) if certification is applied/successful -- | Indicates wether to allow partial proofs. -- A partial proof uses unknown proofs/assumptions to handle unsupported transformations and open problems. -- -- The current implementation behaves as follows -- * if TotalProof is set, certification is ignored if there are open problems left -- * throws an error if certification is not successful -- * silent return if certification is successful. data TotalProof = TotalProof | PartialProof deriving (Show, Eq, Enum, Bounded) data WithCertification = WithCertification { kind :: TotalProof , onStrategy :: TrsStrategy } deriving Show instance T.Processor WithCertification where type ProofObject WithCertification = () type In WithCertification = Trs type Out WithCertification = Trs execute p prob = do pt <- T.evaluate (onStrategy p) (T.Open prob) tmp <- T.tempDirectory `fmap` T.askState res <- case pt of T.Failure r -> return $ Left (show r) rpt | kind p == PartialProof -> CeTA.partialProofIO' tmp rpt | T.isOpen rpt -> return (Right pt) | otherwise -> CeTA.totalProofIO' tmp rpt either T.abortWith k res where k pt = return $ T.Progress () T.fromId (T.toId pt) withCertificationStrategy :: TotalProof -> TrsStrategy -> TrsStrategy withCertificationStrategy t st = T.Apply $ WithCertification { kind = t, onStrategy = st } withCertificationDeclaration :: T.Declared Trs Trs => T.Declaration( '[ T.Argument 'T.Optional TotalProof , T.Argument 'T.Required TrsStrategy] T.:-> TrsStrategy) withCertificationDeclaration = T.declare "withCertification" [desc] (totalArg, stratArg) withCertificationStrategy where stratArg = T.strat "toCertify" ["The strategy to certify."] desc = "This processor invokes CeTA on the result of the provided strategy." totalArg = (T.flag "kind" [ "This argument specifies wheter to invoke CeTA with '--allow-assumptions' to provide certification of partial proofs." ]) `T.optional` TotalProof -- | Invokes CeTA on the result of the strategy. -- > withCertification (dependencyTuples .>>> matrix .>>> empty) -- > dependencyPairs' WIDP .>>> withCertification (matrix .>>> empty) withCertification :: TrsStrategy -> TrsStrategy withCertification = withCertificationStrategy TotalProof-- T.deflFun withCertificationDeclaration -- | Invokes CeTA on the result of the strategy. -- | > (withCertification' PartialProof dependencyTuples) .>>> matrix >>> empty withCertification' :: TotalProof -> TrsStrategy -> TrsStrategy withCertification' = withCertificationStrategy --T.declFun withCertificationDeclaration
ComputationWithBoundedResources/tct-trs
src/Tct/Trs/Processor/WithCertification.hs
bsd-3-clause
3,189
0
16
611
574
314
260
-1
-1
{-| Description: Frames-per-second limiter based on SDL timer subsystem. -} module Graphics.UI.SDL.Utils.Framerate ( FPSLimit , newFPSLimit , fpsLimit ) where import Control.Concurrent (threadDelay) import Control.Monad.IO.ExClass import Control.Applicative import Data.IORef import Graphics.UI.SDL.Timer -- | FPS limiter using SDL timer. newtype FPSLimit = FPSLimit (IORef Ticks) -- | Create initial 'FPSLimit'. newFPSLimit :: MonadIO' m => m FPSLimit newFPSLimit = do t0 <- getTicks liftIO $ FPSLimit <$> newIORef t0 -- | Given frame time (inverted FPS), delay a thread. fpsLimit :: MonadIO' m => FPSLimit -> Ticks -> m Ticks fpsLimit (FPSLimit st) limit = do old <- liftIO $ readIORef st let target = old + fromIntegral limit curr <- getTicks next <- liftIO $ if target > curr then do threadDelay $ 1000 * fromIntegral (target - curr) return target else return curr liftIO $ writeIORef st next return $ fromIntegral $ curr - old
abbradar/MySDL
src/Graphics/UI/SDL/Utils/Framerate.hs
bsd-3-clause
1,062
0
15
276
269
139
130
26
2
module ProverTest where import Prover import Axioms import Formula import FormulaTest import Test.QuickCheck import Test.QuickCheck import Test.QuickCheck.Function proverTests :: IO () proverTests = do putStrLn "Running Robins Tests" quickCheck prop_robinTests putStrLn "Testing with negated Axiom1" quickCheck prop_NotSatisfiable1 putStrLn "Testing with Axiom1" quickCheck prop_Satisfiable1 putStrLn "Testing with negated Axiom2" quickCheck prop_NotSatisfiable2 putStrLn "Testing with Axiom2" quickCheck prop_Satisfiable2 putStrLn "Testing with negated Axiom3" quickCheck prop_NotSatisfiable3 putStrLn "Testing with Axiom3" quickCheck prop_Satisfiable3 putStrLn "Testing with negated Axiom4" quickCheck prop_NotSatisfiable4 putStrLn "Testing with Axiom4" quickCheck prop_Satisfiable4 robinsInput :: [ (String, Bool) ] robinsInput = [ ("-(p>p)" , False) , ("-(p>(q>p))" , False) , ("-((p>q)>p)" , True) , ("--((pvq)>(-p^-q))", True) , ("(p^-p)", False) , ("((p>q)^(q>p))", True) , ("-((p>(qvr))>((p>q)v(p>r)))", False) , ("((p>(qvr))>((p>q)v(p>r)))", True) , ("((p>q)^(-q>-p))", True) , ("((pvq)^p>-q)", False) -- not a Fmla ] runRobinsTests :: [(Bool, Bool)] runRobinsTests = map (\(fmla, expected) -> (satisfiable' fmla, expected)) robinsInput passTests :: Bool passTests = foldl (&&) True $ [ x == y | (x, y) <- runRobinsTests ] -- QuickCheck in order to check if the prover is correct prop_NotSatisfiable1 :: Fmla -> Fmla -> Bool prop_NotSatisfiable1 f g = not (satisfiable $ negFmla $ createAxiom1 f g) prop_Satisfiable1 :: Fmla -> Fmla -> Bool prop_Satisfiable1 f g = satisfiable $ createAxiom1 f g prop_NotSatisfiable2 :: Fmla -> Fmla -> Fmla -> Bool prop_NotSatisfiable2 f g h = not (satisfiable $ negFmla $ createAxiom2 f g h) prop_Satisfiable2 :: Fmla -> Fmla -> Fmla -> Bool prop_Satisfiable2 f g h = satisfiable $ createAxiom2 f g h prop_NotSatisfiable3 :: Fmla -> Fmla -> Bool prop_NotSatisfiable3 f g = not (satisfiable $ negFmla $ createAxiom3 f g) prop_Satisfiable3 :: Fmla -> Fmla -> Bool prop_Satisfiable3 f g = satisfiable $ createAxiom3 f g prop_Satisfiable4 ::Fmla -> Bool prop_Satisfiable4 f = satisfiable $ createAxiom4 f prop_NotSatisfiable4 :: Fmla -> Bool prop_NotSatisfiable4 f = not (satisfiable $ negFmla $ createAxiom4 f) prop_robinTests :: Bool prop_robinTests = passTests
jpotecki/LogicTableauChecker
test/ProverTest.hs
bsd-3-clause
2,530
0
9
543
661
345
316
61
1
module Main where import TestHttpChannelB main = myMain
armoredsoftware/protocol
tpm/mainline/shared/protocolprotocol/TestHttpChannelBMain.hs
bsd-3-clause
59
0
4
11
12
8
4
3
1
{-# LANGUAGE MultiParamTypeClasses, TypeFamilies, FlexibleContexts #-} {-# LANGUAGE Rank2Types #-} {-# OPTIONS -Wall #-} module Basic.Operations ( step, stepout, run, runout, isInputEnd, isAcceptState, reify ) where import Basic.Types (Trans(..), Transout(..), EndCond(..), Here(..)) import Basic.Features (HasState(..), HasQ(..), HasFinal(..), HasTransition(..), HasOutputTransition(..), HasOutput(..), HasStatic(..), HasInput(..), HasIP(..)) import Basic.Memory (AtEnd, isFinal, SetLike(..)) import Control.Lens ((%~), (^.), Getter, to) --------------------------------------------------------- --------------Machine Run loop :: EndCond c => (c -> c) -> (c -> c) loop f c = if endcond c then c else loop f $ f c step :: (HasTransition c) => c -> c step c = state %~ (getTrans (c^.transition) (c^.static)) $ c run :: (EndCond c, HasTransition c) => c -> c run = loop step -- With output stepout :: (HasState c, HasOutputTransition c, HasOutput c, HasStatic c, OutputTransition c ~ Transout (Static c) (State c) (Output c)) => c -> c stepout c = output %~ (getTransout (c^.outputtransition) (c^.static) (c^.state)) $ c runout :: (EndCond c, HasTransition c, HasOutputTransition c, HasOutput c, OutputTransition c ~ Transout (Static c) (State c) (Output c)) => c -> c runout = loop (stepout . step) --------------------------------------------------------- ------structure with state record and IP isInputEnd :: (HasState s, HasInput s, HasIP (State s), AtEnd (IP (State s)) (Input s)) => s -> Bool isInputEnd c = isFinal (c^.state^.ip) (c^.input) isAcceptState :: (Eq (Q (State s1)), HasState s1, HasQ (State s1), HasFinal s1, SetLike s, Final s1 ~ s (Q (State s1))) => s1 -> Bool isAcceptState c = isElem (c^.state^.q) (c^.final) --------------------------------------------------------- reify :: k -> Getter x (Here k) reify = to . const . Here
davidzhulijun/TAM
Basic/Operations.hs
bsd-3-clause
1,887
0
12
304
784
437
347
35
2
{-# LANGUAGE TemplateHaskell #-} module Lamdu.Sugar.Convert.Tag ( ref, replace, withoutContext , taggedEntity , taggedEntityWith , TagResultInfo(..), trEntityId, trPick , NameContext(..), ncMVarInfo, ncUuid ) where import qualified Control.Lens as Lens import Control.Monad.Once (MonadOnce(..), OnceT, Typeable) import Control.Monad.Transaction (MonadTransaction, getP, setP) import Data.Property (MkProperty') import qualified Data.Property as Property import qualified Data.Set as Set import Data.UUID (UUID) import qualified Lamdu.Calc.Type as T import qualified Lamdu.Data.Anchors as Anchors import qualified Lamdu.Data.Ops as DataOps import qualified Lamdu.Expr.UniqueId as UniqueId import Lamdu.Sugar.Convert.NameRef (jumpToTag) import Lamdu.Sugar.Internal hiding (replaceWith) import qualified Lamdu.Sugar.Internal.EntityId as EntityId import Lamdu.Sugar.Types import Revision.Deltum.Transaction (Transaction) import Lamdu.Prelude type T = Transaction data NameContext = NameContext { _ncMVarInfo :: Maybe VarInfo , _ncUuid :: UUID } Lens.makeLenses ''NameContext data TagResultInfo m = TagResultInfo { _trEntityId :: EntityId , _trPick :: m () } Lens.makeLenses ''TagResultInfo withoutContext :: EntityId -> T.Tag -> Tag InternalName withoutContext entityId tag = Tag { _tagName = nameWithoutContext tag , _tagInstance = EntityId.ofTag entityId tag , _tagVal = tag } -- forbiddenTags are sibling tags in the same record/funcParams/etc, -- NOT type-level constraints on tags. Violation of constraints is -- allowed, generating ordinary type errors ref :: (MonadTransaction n m, MonadReader env m, Anchors.HasCodeAnchors env n, Typeable a) => T.Tag -> Maybe NameContext -> Set T.Tag -> OnceT (T n) a -> (a -> T.Tag -> TagResultInfo (T n)) -> m (OnceT (T n) (TagRef InternalName (OnceT (T n)) (T n))) ref tag nameCtx forbiddenTags resultSeed resultInfo = Lens.view Anchors.codeAnchors <&> \anchors -> refWith anchors tag name forbiddenTags resultSeed resultInfo where withContext (NameContext varInfo var) = nameWithContext varInfo var name = maybe nameWithoutContext withContext nameCtx refWith :: (Monad m, Typeable a) => Anchors.CodeAnchors m -> T.Tag -> (T.Tag -> name) -> Set T.Tag -> OnceT (T m) a -> (a -> T.Tag -> TagResultInfo (T m)) -> OnceT (T m) (TagRef name (OnceT (T m)) (T m)) refWith cp tag name forbiddenTags resultSeed resultInfo = do r <- replaceWith name forbiddenTags resultSeed resultInfo tagsProp seed <- resultSeed pure TagRef { _tagRefTag = Tag { _tagName = name tag , _tagInstance = resultInfo seed tag ^. trEntityId , _tagVal = tag } , _tagRefReplace = r , _tagRefJumpTo = if tag == Anchors.anonTag then Nothing else jumpToTag cp tag & Just } where tagsProp = Anchors.tags cp replace :: (MonadTransaction n m, MonadReader env m, Anchors.HasCodeAnchors env n, Typeable a) => (T.Tag -> name) -> Set T.Tag -> OnceT (T n) a -> (a -> T.Tag -> TagResultInfo (T n)) -> m (OnceT (T n) (OnceT (T n) (TagChoice name (T n)))) replace name forbiddenTags resultSeed resultInfo = Lens.view Anchors.codeAnchors <&> Anchors.tags <&> replaceWith name forbiddenTags resultSeed resultInfo replaceWith :: (Monad m, Typeable a) => (T.Tag -> name) -> Set T.Tag -> OnceT (T m) a -> (a -> T.Tag -> TagResultInfo (T m)) -> MkProperty' (T m) (Set T.Tag) -> OnceT (T m) (OnceT (T m) (TagChoice name (T m))) replaceWith name forbiddenTags resultSeed resultInfo tagsProp = (,,) <$> resultSeed <*> lift DataOps.genNewTag <*> lift (getP tagsProp) & once <&> Lens.mapped %~ \(seed, newTag, tags) -> let toOption x = TagOption { _toInfo = Tag { _tagName = name x , _tagInstance = resultInfo seed x ^. trEntityId , _tagVal = x } , _toPick = resultInfo seed x ^. trPick } in TagChoice { _tcOptions = Set.difference tags forbiddenTags ^.. Lens.folded . Lens.to toOption , _tcNewTag = toOption newTag & toPick %~ (Property.modP tagsProp (Lens.contains newTag .~ True) >>) } -- NOTE: Used for panes, outside ConvertM, so has no ConvertM.Context env -- | Convert a "Entity" (param, def, TId) via its associated tag taggedEntityWith :: (UniqueId.ToUUID a, MonadTransaction n m) => Anchors.CodeAnchors n -> Maybe VarInfo -> a -> m (OnceT (T n) (OptionalTag InternalName (OnceT (T n)) (T n))) taggedEntityWith cp mVarInfo entity = getP prop <&> \entityTag -> refWith cp entityTag (nameWithContext mVarInfo entity) mempty (pure ()) resultInfo <&> (`OptionalTag` toAnon) where toAnon = mkInstance Anchors.anonTag <$ setP prop Anchors.anonTag resultInfo () = TagResultInfo <$> mkInstance <*> setP prop mkInstance = EntityId.ofTaggedEntity entity prop = Anchors.assocTag entity taggedEntity :: (UniqueId.ToUUID a, MonadTransaction n m, MonadReader env m, Anchors.HasCodeAnchors env n) => Maybe VarInfo -> a -> m (OnceT (T n) (OptionalTag InternalName (OnceT (T n)) (T n))) taggedEntity mVarInfo entity = Lens.view Anchors.codeAnchors >>= \x -> taggedEntityWith x mVarInfo entity
lamdu/lamdu
src/Lamdu/Sugar/Convert/Tag.hs
gpl-3.0
5,579
0
19
1,428
1,760
936
824
-1
-1
{-# LANGUAGE RebindableSyntax #-} {-# LANGUAGE ViewPatterns #-} {-# LANGUAGE MonadComprehensions #-} -- | This module contains testcases for monad comprehensions. We store them in a -- separate module because they rely on RebindableSyntax and hidden -- Prelude. module Database.DSH.Tests.DSHComprehensions where import Database.DSH {-# ANN module "HLint: ignore Use camelCase" #-} {-# ANN module "HLint: ignore Avoid lambda" #-} --------------------------------------------------------------- -- Comprehensions for quickcheck tests cartprod :: Q ([Integer], [Integer]) -> Q [(Integer, Integer)] cartprod (view -> (xs, ys)) = [ tup2 x y | x <- xs , y <- ys ] cartprod_deep_nested :: Q [Integer] -> Q [(Integer, Integer, Integer)] cartprod_deep_nested xs = concat [ concat [ [ tup3 x y z | z <- xs ] | y <- xs ] | x <- xs ] cartprod_deep :: Q [Integer] -> Q [(Integer, Integer, Integer)] cartprod_deep xs = [ tup3 x y z | x <- xs, y <- xs, z <- xs ] eqjoin :: Q ([Integer], [Integer]) -> Q [(Integer, Integer)] eqjoin (view -> (xs, ys)) = [ tup2 x y | x <- xs , y <- ys , x == y ] eqjoinproj :: Q ([Integer], [Integer]) -> Q [(Integer, Integer)] eqjoinproj (view -> (xs, ys)) = [ tup2 x y | x <- xs , y <- ys , (2 * x) == y ] eqjoinpred :: Q (Integer, [Integer], [Integer]) -> Q [(Integer, Integer)] eqjoinpred (view -> (x', xs, ys)) = [ tup2 x y | x <- xs , y <- ys , x == y , x > x' ] eqjointuples :: Q ([(Integer, Integer)], [(Integer, Integer)]) -> Q [(Integer, Integer, Integer)] eqjointuples (view -> (xs, ys)) = [ tup3 (x1 * x2) y1 y2 | (view -> (x1, x2)) <- xs , (view -> (y1, y2)) <- ys , x1 == y2 ] thetajoin_eq :: Q ([(Integer, Integer)], [(Integer, Integer)]) -> Q [(Integer, Integer, Integer)] thetajoin_eq (view -> (xs, ys)) = [ tup3 (x1 * x2) y1 y2 | (view -> (x1, x2)) <- xs , (view -> (y1, y2)) <- ys , x1 == y2 , y1 == x2 ] thetajoin_neq :: Q ([(Integer, Integer)], [(Integer, Integer)]) -> Q [(Integer, Integer, Integer)] thetajoin_neq (view -> (xs, ys)) = [ tup3 (x1 * x2) y1 y2 | (view -> (x1, x2)) <- xs , (view -> (y1, y2)) <- ys , x1 == y2 , y1 /= x2 ] eqjoin3 :: Q ([Integer], [Integer], [Integer]) -> Q [(Integer, Integer, Integer)] eqjoin3 (view -> (xs, ys, zs)) = [ tup3 x y z | x <- xs , y <- ys , z <- zs , x == y , y == z ] eqjoin_nested_left :: Q ([(Integer, [Integer])], [Integer]) -> Q [((Integer, [Integer]), Integer)] eqjoin_nested_left args = [ pair x y | x <- fst args , y <- snd args , fst x == y ] eqjoin_nested_right :: Q ([Integer], [(Integer, [Integer])]) -> Q [(Integer, (Integer, [Integer]))] eqjoin_nested_right args = [ pair x y | x <- fst args , y <- snd args , x == fst y ] eqjoin_nested_both :: Q ([(Integer, [Integer])], [(Integer, [Integer])]) -> Q [((Integer, [Integer]), (Integer, [Integer]))] eqjoin_nested_both args = [ pair x y | x <- fst args , y <- snd args , fst x == fst y ] nestjoin :: Q ([Integer], [Integer]) -> Q [(Integer, [Integer])] nestjoin (view -> (xs, ys)) = [ tup2 x [ y | y <- ys, x == y] | x <- xs ] nestjoin3 :: Q ([Integer], [Integer], [Integer]) -> Q [[[(Integer, Integer, Integer)]]] nestjoin3 (view -> (xs, ys, zs)) = [ [ [ tup3 x y z | z <- zs, y == z ] | y <- ys , x == y ] | x <- xs ] groupjoin_length :: Q ([Integer], [Integer]) -> Q [(Integer, Integer)] groupjoin_length (view -> (xs, ys)) = [ tup2 x (length [ y | y <- ys, x == y ]) | x <- xs ] groupjoin_length_nub :: Q ([Integer], [Integer]) -> Q [(Integer, Integer)] groupjoin_length_nub (view -> (xs, ys)) = [ tup2 x (length $ nub [ y | y <- ys, x == y ]) | x <- xs ] groupjoin_sum :: Q ([Integer], [Integer]) -> Q [(Integer, Integer)] groupjoin_sum (view -> (xs, ys)) = [ tup2 x (sum [ 2 * y + x | y <- ys, x == y ]) | x <- xs ] groupjoin_sum2 :: Q ([Integer], [Integer]) -> Q [Integer] groupjoin_sum2 (view -> (xs, ys)) = [ x + sum [ 2 * y | y <- ys, x == y ] | x <- xs ] groupjoin_sum_deep :: Q ([Integer], [Integer], [Integer]) -> Q [[(Integer, Integer)]] groupjoin_sum_deep (view -> (xs, ys, zs)) = [ [ tup2 x (sum [ 2 * y | y <- ys, x == y ]) | x <- xs, x == z ] | z <- zs ] groupjoin_length_deep_sum:: Q ([Integer], [Integer], [Integer]) -> Q [Integer] groupjoin_length_deep_sum (view -> (xs, ys, zs)) = [ z + sum [ length [ 2 * y + x | y <- ys, x == y ] | x <- xs, x == z ] | z <- zs ] groupjoin_sum_length :: Q ([Integer], [Integer]) -> Q [(Integer, Integer, Integer)] groupjoin_sum_length (view -> (xs, ys)) = [ tup3 x (sum [ 2 * y | y <- ys, x == y ]) (length [ y | y <- ys, x == y ]) | x <- xs ] groupjoin_sum_length2 :: Q ([Integer], [Integer]) -> Q [(Integer, Integer, Integer)] groupjoin_sum_length2 (view -> (njxs, njys)) = [ tup3 x (sum [ 2 * y | y <- njys, x == y ]) (length [ y | y <- njys, x == y ]) | x <- njxs , 20 < sum [ 3 + y | y <- njys, x == y ] ] groupjoin_sum_guard :: Q ([Integer], [Integer]) -> Q [Integer] groupjoin_sum_guard (view -> (njxs, njys)) = [ x | x <- njxs , let ys = [ 2 * y | y <- njys, x == y ] , 5 < length ys ] groupjoin_sum_guard2 :: Q ([Integer], [Integer]) -> Q [(Integer, Integer)] groupjoin_sum_guard2 (view -> (njxs, njys)) = [ pair x (sum ys) | x <- njxs , let ys = [ 2 * y | y <- njys, x == y ] , 5 < length ys ] groupjoin_sum_nest :: Q ([Integer], [Integer]) -> Q [(Integer, Integer, [Integer])] groupjoin_sum_nest (view -> (njxs, njys)) = [ tup3 x (sum ys) ys | x <- njxs , let ys = [ 2 * y | y <- njys, x == y ] ] groupjoin_sum_nest2 :: Q ([Integer], [Integer]) -> Q [(Integer, Integer, [Integer])] groupjoin_sum_nest2 (view -> (njxs, njys)) = [ tup3 x (sum ys) ys | x <- njxs , let ys = [ x + 2 * y | y <- njys, x == y ] , 10 > length ys ] groupjoin_nestjoin :: Q ([Integer], [Integer], [Integer]) -> Q [(Integer, Integer, [Integer])] groupjoin_nestjoin (view -> (njxs, njys, njzs)) = [ tup3 x (sum [ 2 * y | y <- njys, x == y ]) [ z + 10 | z <- njzs, z > x ] | x <- njxs ] groupjoin_nestjoin_guard :: Q ([Integer], [Integer], [Integer]) -> Q [(Integer, Integer, [Integer])] groupjoin_nestjoin_guard (view -> (njxs, njys, njzs)) = [ tup3 x (sum [ 2 * y | y <- njys, x == y ]) [ z + 10 | z <- njzs, z > x ] | x <- njxs , 10 < length [ y | y <- njys, x == y ] ] -------------------------------------------------------------------------------- -- Comprehensions for lifted join tests liftsemijoin :: Q ([Integer], [Integer]) -> Q [[Integer]] liftsemijoin (view -> (xs, ys)) = [ [ x | x <- g, x `elem` ys ] | g <- groupWith (`rem` 10) xs ] liftantijoin :: Q ([Integer], [Integer]) -> Q [[Integer]] liftantijoin (view -> (xs, ys)) = [ [ x | x <- g, x `notElem` ys ] | g <- groupWith (`rem` 10) xs ] liftthetajoin :: Q ([Integer], [Integer]) -> Q [[(Integer, Integer)]] liftthetajoin (view -> (xs, ys)) = [ [ pair x y | x <- g, y <- ys, x < y ] | g <- groupWith (`rem` 10) xs ] -------------------------------------------------------------- -- Comprehensions for HUnit tests eqjoin_nested1 :: Q [((Integer, [Char]), Integer)] eqjoin_nested1 = [ pair x y | x <- (toQ ([(10, ['a']), (20, ['b']), (30, ['c', 'd']), (40, [])] :: [(Integer, [Char])])) , y <- (toQ [20, 30, 30, 40, 50]) , fst x == y ] semijoin :: Q [Integer] semijoin = let xs = (toQ [1, 2, 3, 4, 5, 6, 7] :: Q [Integer]) ys = (toQ [2, 4, 6, 7] :: Q [Integer]) in [ x | x <- xs , x `elem` ys ] semijoin_range :: Q [Integer] semijoin_range = let xs = (toQ [1, 2, 3, 4, 5, 6, 7] :: Q [Integer]) ys = (toQ [2, 4, 6] :: Q [Integer]) in [ x | x <- xs , x `elem` [ y | y <- ys, y < 6 ] ] semijoin_quant :: Q [Integer] semijoin_quant = let xs = (toQ [1, 2, 3, 4, 5, 6, 7] :: Q [Integer]) ys = (toQ [2, 4, 6, 7] :: Q [Integer]) in [ x | x <- xs, or [ y > 5 | y <- ys, x == y ] ] semijoin_not_null :: Q [Integer] semijoin_not_null = let xs = (toQ [1, 2, 3, 4, 5, 6, 7] :: Q [Integer]) ys = (toQ [2, 4, 6, 7] :: Q [Integer]) in [ x | x <- xs, not $ null [ y | y <- ys, x == y] ] antijoin :: Q [Integer] antijoin = let xs = (toQ [1, 2, 3, 4, 5, 6, 7] :: Q [Integer]) ys = (toQ [2, 4, 6, 7] :: Q [Integer]) in [ x | x <- xs , not $ x `elem` ys ] antijoin_null :: Q [Integer] antijoin_null = let xs = (toQ [1, 2, 3, 4, 5, 6, 7] :: Q [Integer]) ys = (toQ [2, 4, 6, 7] :: Q [Integer]) in [ x | x <- xs, null [ y | y <- ys, x == y] ] antijoin_range :: Q [Integer] antijoin_range = let xs = (toQ [1, 2, 3, 4, 5, 6, 7] :: Q [Integer]) ys = (toQ [2, 4, 6, 7] :: Q [Integer]) in [ x | x <- xs , not $ x `elem` [ y | y <- ys, y < 5 ] ] antijoin_class12 :: Q [Integer] antijoin_class12 = let xs = toQ ([6,7,8,9,10,12] :: [Integer]) ys = toQ ([8,9,12,13,15,16] :: [Integer]) in [ x | x <- xs, and [ x < y | y <- ys, y > 10 ]] antijoin_class15 :: Q [Integer] antijoin_class15 = let xs = toQ ([3,4,5,6,7,8] :: [Integer]) ys = toQ ([4,5,8,16] :: [Integer]) in [ x | x <- xs, and [ y `rem` 4 == 0 | y <- ys, x < y ]] antijoin_class16 :: Q [Integer] antijoin_class16 = let xs = toQ ([3,4,5,6] :: [Integer]) ys = toQ ([1,2,3,4,5,6,7,8] :: [Integer]) in [ x | x <- xs, and [ y <= 2 * x | y <- ys, x < y ]] frontguard :: Q [[Integer]] frontguard = [ [ y | x > 13, y <- toQ ([1,2,3,4] :: [Integer]), y < 3 ] | x <- toQ ([10, 20, 30] :: [Integer]) ] ---------------------------------------------------------------------- -- Comprehensions for HUnit NestJoin/NestProduct tests nj1 :: [Integer] -> [Integer] -> Q [[Integer]] nj1 njxs njys = [ [ y | y <- toQ njys, x == y ] | x <- toQ njxs ] nj2 :: [Integer] -> [Integer] -> Q [(Integer, [Integer])] nj2 njxs njys = [ pair x [ y | y <- toQ njys, x == y ] | x <- toQ njxs ] nj3 :: [Integer] -> [Integer] -> Q [(Integer, [Integer])] nj3 njxs njys = [ pair x ([ y | y <- toQ njys, x == y ] ++ (toQ [100, 200, 300])) | x <- toQ njxs ] nj4 :: [Integer] -> [Integer] -> Q [(Integer, [Integer])] nj4 njxs njys = [ pair x ([ y | y <- toQ njys, x == y ] ++ [ z | z <- toQ njys, x == z ]) | x <- toQ njxs ] -- Code incurs DistSeg for the literal 15. nj5 :: [Integer] -> [Integer] -> Q [(Integer, [Integer])] nj5 njxs njys = [ pair x [ y | y <- toQ njys, x + y > 15 ] | x <- toQ njxs ] nj6 :: [Integer] -> [Integer] -> Q [(Integer, [Integer])] nj6 njxs njys = [ pair x [ y | y <- toQ njys, x + y > 10, y < 7 ] | x <- toQ njxs ] nj7 :: [Integer] -> [Integer] -> Q [[Integer]] nj7 njxs njys = [ [ x + y | y <- toQ njys, x + 2 == y ] | x <- toQ njxs ] nj8 :: [Integer] -> [Integer] -> Q [[Integer]] nj8 njxs njys = [ [ x + y | y <- toQ njys, x == y, y < 5 ] | x <- toQ njxs, x > 3 ] nj9 :: [Integer] -> [Integer] -> Q [[Integer]] nj9 njxs njys = [ [ x + y | y <- toQ njys, x + 1 == y, y > 2, x < 6 ] | x <- toQ njxs ] nj10 :: [Integer] -> [Integer] -> Q [Integer] nj10 njxs njys = [ x + sum [ x * y | y <- toQ njys, x == y ] | x <- toQ njxs ] nj11 :: [Integer] -> [Integer] -> Q [[Integer]] nj11 njxs njys = [ [ x + y | y <- toQ njys, x > y, x < y * 2 ] | x <- toQ njxs ] nj12 :: [Integer] -> [Integer] -> [Integer] -> Q [[[(Integer, Integer, Integer)]]] nj12 njxs njys njzs = [ [ [ tup3 x y z | z <- toQ njzs, y == z ] | y <- toQ njys , x == y ] | x <- toQ njxs ] np1 :: [Integer] -> [Integer] -> Q [[Integer]] np1 njxs njys = [ [ x * y * 2 | y <- toQ njys ] | x <- toQ njxs ] np2 :: [Integer] -> [Integer] -> Q [(Integer, [Integer])] np2 njxs njys = [ pair x [ y * 2 | y <- toQ njys ] | x <- toQ njxs ] np3 :: [Integer] -> [Integer] -> Q [[Integer]] np3 njxs njys = [ [ x + y | y <- toQ njys ] | x <- toQ njxs ] np4 :: [Integer] -> [Integer] -> Q [[Integer]] np4 njxs njys = [ [ y | y <- toQ njys, x > y ] | x <- toQ njxs ] njg1 :: [Integer] -> [(Integer, Integer)] -> Q [Integer] njg1 njgxs njgzs = [ x | x <- toQ njgxs , x < 8 , sum [ snd z | z <- toQ njgzs, fst z == x ] > 100 ] njg2 :: [Integer] -> [Integer] -> Q [Integer] njg2 njgxs njgys = [ x | x <- toQ njgxs , and [ y > 1 | y <- toQ njgys, x == y ] , x < 8 ] njg3 :: [Integer] -> [Integer] -> [(Integer, Integer)] -> Q [(Integer, Integer)] njg3 njgxs njgys njgzs = [ pair x y | x <- toQ njgxs , y <- toQ njgys , length [ toQ () | z <- toQ njgzs, fst z == x ] > 2 ] njg4 :: [Integer] -> [Integer] -> [(Integer, Integer)] -> Q [Integer] njg4 njgxs njgys njgzs = [ x | x <- toQ njgxs , length [ toQ () | y <- toQ njgys, x == y ] > length [ toQ () | z <- toQ njgzs, fst z == x ] ] njg5 :: [Integer] -> [Integer] -> Q [Integer] njg5 njgxs njgys = [ x | x <- toQ njgxs , sum [ y | y <- toQ njgys, x < y, y > 5 ] < 10 ] njg6 :: Q [Integer] -> Q [Integer] -> Q [Integer] -> Q [(Integer, [Integer])] njg6 njgxs njgys njgzs = [ tup2 x [ y | y <- njgys, x == y ] | x <- njgxs , x `elem` njgzs ] njg7 :: Q [Integer] -> Q [Integer] -> Q [Integer] -> Q [(Integer, [Integer])] njg7 njgxs njgys njgzs = filter ((`elem` njgzs) . fst) [ tup2 x [ y | y <- njgys, x == y ] | x <- njgxs ] -------------------------------------------------------------------------------- -- Comprehensions for QuickCheck antijoin/semijoin tests aj_class12 :: Q ([Integer], [Integer]) -> Q [Integer] aj_class12 (view -> (xs, ys)) = [ x | x <- xs , and [ x == y | y <- ys, y > 10 ] ] aj_class15 :: Q ([Integer], [Integer]) -> Q [Integer] aj_class15 (view -> (xs, ys)) = [ x | x <- xs , and [ y `rem` 4 == 0 | y <- ys, x < y ] ] aj_class16 :: Q ([Integer], [Integer]) -> Q [Integer] aj_class16 (view -> (xs, ys)) = [ x | x <- xs , and [ y <= 2 * x | y <- ys, x < y ] ] -------------------------------------------------------------------------------- -- Comprehensions for backdep :: Q [[Integer]] -> Q [Integer] backdep xss = [ x | xs <- xss, x <- xs ] backdep_filter :: Q [[Integer]] -> Q [Integer] backdep_filter xss = [ x | xs <- xss, x <- xs, length xs > x ] backdep2 :: Q [[Integer]] -> Q [[Integer]] backdep2 xss = [ [ x * 42 | x <- xs ] | xs <- xss ] backdep3 :: Q [[Integer]] -> Q [[Integer]] backdep3 xss = [ [ x + length xs | x <- xs ] | xs <- xss ] backdep4 :: Q [[[Integer]]] -> Q [[[Integer]]] backdep4 xsss = [ [ [ x + length xs + length xss | x <- xs ] | xs <- xss ] | xss <- xsss ] backdep5 :: Q [[Integer]] -> Q [[Integer]] backdep5 xss = [ [ x + length xs | x <- take (length xs - 3) xs ] | xs <- xss ] deep_iter :: Q ([Integer], [Integer], [Integer], [Integer], [Integer]) -> Q [[[[Integer]]]] deep_iter (view -> (ws1, ws2, xs, ys, zs)) = [ [ [ [ w1 * 23 - y | w1 <- ws1 ] ++ [ w2 + 42 - y | w2 <- ws2 ] | z <- zs , z > x ] | y <- ys ] | x <- xs ] only_tuple :: Q (Integer, [Integer], [Integer]) -> Q (Integer, (Integer, [Integer])) only_tuple (view -> (x, ys, zs)) = pair x (head [ pair y [ z | z <- zs, x == y ] | y <- ys ])
ulricha/dsh
src/Database/DSH/Tests/DSHComprehensions.hs
bsd-3-clause
15,319
0
13
4,308
8,483
4,656
3,827
358
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DeriveGeneric #-} module AppConfig where import GHC.Generics (Generic) import qualified Data.Configurator as C import qualified Data.Configurator.Types as C import Data.Word data AppConfig = AppConfig { dbName :: String , dbUser :: String , dbPassword :: String , dbSalt :: String , dbHost :: String , dbPort :: Word16 , appPort :: Word16 , poolSize :: Word16 } deriving (Show, Generic) makeDbConfig :: C.Config -> IO (Maybe AppConfig) makeDbConfig conf = do name <- C.lookup conf "database.name" :: IO (Maybe String) user <- C.lookup conf "database.user" :: IO (Maybe String) password <- C.lookup conf "database.password" :: IO (Maybe String) dsalt <- C.lookup conf "database.salt" :: IO (Maybe String) host <- C.lookup conf "database.host" :: IO (Maybe String) dport <- C.lookup conf "database.port" :: IO (Maybe Word16) port <- C.lookup conf "application.port" :: IO (Maybe Word16) psize <- C.lookup conf "application.poolSize" :: IO (Maybe Word16) return $ AppConfig <$> name <*> user <*> password <*> dsalt <*> host <*> dport <*> port <*> psize
dbushenko/biblio
src/AppConfig.hs
bsd-3-clause
1,419
0
15
489
381
199
182
35
1
{-# LANGUAGE CPP,MagicHash,ScopedTypeVariables,FlexibleInstances,RankNTypes,TypeSynonymInstances,MultiParamTypeClasses,BangPatterns #-} -- | By Chris Kuklewicz, drawing heavily from binary and binary-strict, -- but all the bugs are my own. -- -- This file is under the usual BSD3 licence, copyright 2008. -- -- Modified the monad to be strict for version 2.0.0 -- -- This started out as an improvement to -- "Data.Binary.Strict.IncrementalGet" with slightly better internals. -- The simplified 'Get', 'runGet', 'Result' trio with the -- "Data.Binary.Strict.Class.BinaryParser" instance are an _untested_ -- upgrade from IncrementalGet. Especially untested are the -- strictness properties. -- -- 'Get' usefully implements Applicative and Monad, MonadError, -- Alternative and MonadPlus. Unhandled errors are reported along -- with the number of bytes successfully consumed. Effects of -- 'suspend' and 'putAvailable' are visible after -- fail/throwError/mzero. -- -- Each time the parser reaches the end of the input it will return a -- Partial wrapped continuation which requests a (Maybe -- Lazy.ByteString). Passing (Just bs) will append bs to the input so -- far and continue processing. If you pass Nothing to the -- continuation then you are declaring that there will never be more -- input and that the parser should never again return a partial -- contination; it should return failure or finished. -- -- 'suspendUntilComplete' repeatedly uses a partial continuation to -- ask for more input until 'Nothing' is passed and then it proceeds -- with parsing. -- -- The 'getAvailable' command returns the lazy byte string the parser -- has remaining before calling 'suspend'. The 'putAvailable' -- replaces this input and is a bit fancy: it also replaces the input -- at the current offset for all the potential catchError/mplus -- handlers. This change is _not_ reverted by fail/throwError/mzero. -- -- The three 'lookAhead' and 'lookAheadM' and 'lookAheadE' functions are -- very similar to the ones in binary's Data.Binary.Get. -- -- -- Add specialized high-bit-run module Text.ProtocolBuffers.Get (Get,runGet,runGetAll,Result(..) -- main primitives ,ensureBytes,getStorable,getLazyByteString,suspendUntilComplete -- parser state manipulation ,getAvailable,putAvailable -- lookAhead capabilities ,lookAhead,lookAheadM,lookAheadE -- below is for implementation of BinaryParser (for Int64 and Lazy bytestrings) ,skip,bytesRead,isEmpty,isReallyEmpty,remaining,spanOf,highBitRun ,getWord8,getByteString ,getWord16be,getWord32be,getWord64be ,getWord16le,getWord32le,getWord64le ,getWordhost,getWord16host,getWord32host,getWord64host -- -- ,scan ,decode7,decode7size,decode7unrolled ) where -- The Get monad is an instance of binary-strict's BinaryParser: -- import qualified Data.Binary.Strict.Class as P(BinaryParser(..)) -- The Get monad is an instance of all of these library classes: import Control.Applicative(Applicative(pure,(<*>)),Alternative(empty,(<|>))) import Control.Monad(MonadPlus(mzero,mplus),when) import Control.Monad.Error.Class(MonadError(throwError,catchError),Error(strMsg)) -- It can be a MonadCont, but the semantics are too broken without a ton of work. -- implementation imports --import Control.Monad(replicateM,(>=>)) -- XXX testing --import qualified Data.ByteString as S(unpack) -- XXX testing --import qualified Data.ByteString.Lazy as L(pack) -- XXX testing import Control.Monad(ap) -- instead of Functor.fmap; ap for Applicative import Data.Bits(Bits((.|.),(.&.)),shiftL) import qualified Data.ByteString as S(concat,length,null,splitAt,findIndex) import qualified Data.ByteString.Internal as S(ByteString(..),toForeignPtr,inlinePerformIO) import qualified Data.ByteString.Unsafe as S(unsafeIndex,unsafeDrop {-,unsafeTake-}) import qualified Data.ByteString.Lazy as L(take,drop,length,span,toChunks,fromChunks,null,findIndex) import qualified Data.ByteString.Lazy.Internal as L(ByteString(..),chunk) import qualified Data.Foldable as F(foldr,foldr1) -- used with Seq import Data.Int(Int32,Int64) -- index type for L.ByteString import Data.Monoid(Monoid(mempty,mappend)) -- Writer has a Monoid contraint import Data.Sequence(Seq,null,(|>)) -- used for future queue in handler state import Data.Word(Word,Word8,Word16,Word32,Word64) import Foreign.ForeignPtr(withForeignPtr) import Foreign.Ptr(Ptr,castPtr,plusPtr,minusPtr,nullPtr) import Foreign.Storable(Storable(peek,sizeOf)) import System.IO.Unsafe(unsafePerformIO) #if defined(__GLASGOW_HASKELL__) && !defined(__HADDOCK__) import GHC.Base(Int(..),uncheckedShiftL#) import GHC.Word(Word16(..),Word32(..),Word64(..),uncheckedShiftL64#) #endif --import Debug.Trace(trace) trace :: a -> b -> b trace _ = id -- Simple external return type data Result a = Failed {-# UNPACK #-} !Int64 String | Finished !L.ByteString {-# UNPACK #-} !Int64 a | Partial (Maybe L.ByteString -> Result a) -- Internal state type, not exposed to the user. -- Invariant: (S.null _top) implies (L.null _current) data S = S { _top :: {-# UNPACK #-} !S.ByteString , _current :: !L.ByteString , consumed :: {-# UNPACK #-} !Int64 } deriving Show data T3 s = T3 !Int !s !Int --data TU s = TU'OK !s !Int | TU'DO (Get s) data TU s = TU'OK !s !Int {-# SPECIALIZE decode7unrolled :: Get Int64 #-} {-# SPECIALIZE decode7unrolled :: Get Int32 #-} {-# SPECIALIZE decode7unrolled :: Get Word64 #-} {-# SPECIALIZE decode7unrolled :: Get Word32 #-} {-# SPECIALIZE decode7unrolled :: Get Int #-} {-# SPECIALIZE decode7unrolled :: Get Integer #-} decode7unrolled :: forall s. (Num s,Integral s, Bits s) => Get s {-# NOINLINE decode7unrolled #-} decode7unrolled = Get $ \ sc sIn@(S ss@(S.PS fp off len) bs n) pc -> trace ("decode7unrolled: "++show (len,n)) $ if S.null ss then trace ("decode7unrolled: S.null ss") $ unGet decode7 sc sIn pc -- decode7 will try suspend then will fail if still bad else let (TU'OK x i) = unsafePerformIO $ withForeignPtr fp $ \ptr0 -> do if ptr0 == nullPtr || len < 1 then error "Get.decode7unrolled: ByteString invariant failed" else do let ok :: s -> Int -> IO (TU s) ok x0 i0 = return (TU'OK x0 i0) more,err :: IO (TU s) more = return (TU'OK 0 0) -- decode7 err = return (TU'OK 0 (-1)) -- throwError {-# INLINE ok #-} {-# INLINE more #-} {-# INLINE err #-} -- -- Next line is segfault fix for null bytestrings from Nathan Howell <[email protected]> -- if ptr0 == nullPtr then more else do let start = ptr0 `plusPtr` off :: Ptr Word8 b'1 <- peek start if b'1 < 128 then ok (fromIntegral b'1) 1 else do let !val'1 = fromIntegral (b'1 .&. 0x7F) !end = start `plusPtr` len !ptr2 = start `plusPtr` 1 :: Ptr Word8 if ptr2 >= end then more else do b'2 <- peek ptr2 if b'2 < 128 then ok (val'1 .|. (fromIntegral b'2 `shiftL` 7)) 2 else do let !val'2 = (val'1 .|. (fromIntegral (b'2 .&. 0x7F) `shiftL` 7)) !ptr3 = ptr2 `plusPtr` 1 if ptr3 >= end then more else do b'3 <- peek ptr3 if b'3 < 128 then ok (val'2 .|. (fromIntegral b'3 `shiftL` 14)) 3 else do let !val'3 = (val'2 .|. (fromIntegral (b'3 .&. 0x7F) `shiftL` 14)) !ptr4 = ptr3 `plusPtr` 1 if ptr4 >= end then more else do b'4 <- peek ptr4 if b'4 < 128 then ok (val'3 .|. (fromIntegral b'4 `shiftL` 21)) 4 else do let !val'4 = (val'3 .|. (fromIntegral (b'4 .&. 0x7F) `shiftL` 21)) !ptr5 = ptr4 `plusPtr` 1 if ptr5 >= end then more else do b'5 <- peek ptr5 if b'5 < 128 then ok (val'4 .|. (fromIntegral b'5 `shiftL` 28)) 5 else do let !val'5 = (val'4 .|. (fromIntegral (b'5 .&. 0x7F) `shiftL` 28)) !ptr6 = ptr5 `plusPtr` 1 if ptr6 >= end then more else do b'6 <- peek ptr6 if b'6 < 128 then ok (val'5 .|. (fromIntegral b'6 `shiftL` 35)) 6 else do let !val'6 = (val'5 .|. (fromIntegral (b'6 .&. 0x7F) `shiftL` 35)) !ptr7 = ptr6 `plusPtr` 1 if ptr7 >= end then more else do b'7 <- peek ptr7 if b'7 < 128 then ok (val'6 .|. (fromIntegral b'7 `shiftL` 42)) 7 else do let !val'7 = (val'6 .|. (fromIntegral (b'7 .&. 0x7F) `shiftL` 42)) !ptr8 = ptr7 `plusPtr` 1 if ptr8 >= end then more else do b'8 <- peek ptr8 if b'8 < 128 then ok (val'7 .|. (fromIntegral b'8 `shiftL` 49)) 8 else do let !val'8 = (val'7 .|. (fromIntegral (b'8 .&. 0x7F) `shiftL` 49)) !ptr9 = ptr8 `plusPtr` 1 if ptr9 >= end then more else do b'9 <- peek ptr9 if b'9 < 128 then ok (val'8 .|. (fromIntegral b'9 `shiftL` 56)) 9 else do let !val'9 = (val'8 .|. (fromIntegral (b'9 .&. 0x7F) `shiftL` 56)) !ptrA = ptr9 `plusPtr` 1 if ptrA >= end then more else do b'A <- peek ptrA if b'A < 128 then ok (val'9 .|. (fromIntegral b'A `shiftL` 63)) 10 else do err in if i > 0 then let ss' = (S.unsafeDrop i ss) n' = n+fromIntegral i s'safe = make_safe (S ss' bs n') in sc x s'safe pc else if i==0 then unGet decode7 sc sIn pc else unGet (throwError $ "Text.ProtocolBuffers.Get.decode7unrolled: more than 10 bytes needed at bytes read of "++show n) sc sIn pc {-# SPECIALIZE decode7 :: Get Int64 #-} {-# SPECIALIZE decode7 :: Get Int32 #-} {-# SPECIALIZE decode7 :: Get Word64 #-} {-# SPECIALIZE decode7 :: Get Word32 #-} {-# SPECIALIZE decode7 :: Get Int #-} {-# SPECIALIZE decode7 :: Get Integer #-} decode7 :: forall s. (Integral s, Bits s) => Get s {-# NOINLINE decode7 #-} decode7 = go 0 0 where go !s1 !shift1 = trace ("decode7.go: "++show (toInteger s1, shift1)) $ do let -- scanner's inner loop decodes only in current top strict bytestring, does not advance input state scanner (S.PS fp off len) = withForeignPtr fp $ \ptr0 -> do if ptr0 == nullPtr || len < 1 then error "Get.decode7: ByteString invariant failed" else do let start = ptr0 `plusPtr` off -- start is a pointer to the next valid byte end = start `plusPtr` len -- end is a pointer one byte past the last valid byte inner :: (Ptr Word8) -> s -> Int -> IO (T3 s) inner !ptr !s !shift | ptr < end = do w <- peek ptr trace ("w: " ++ show w) $ do if (128>) w then return $ T3 (succ (ptr `minusPtr` start) ) -- length of capture (s .|. ((fromIntegral w) `shiftL` shift)) -- put the last bits into high position (-1) -- negative shift indicates satisfied else inner (ptr `plusPtr` 1) -- loop on next byte (s .|. ((fromIntegral (w .&. 0x7F)) `shiftL` shift)) -- put the new bits into high position (shift+7) -- increase high position for next loop | otherwise = return $ T3 (ptr `minusPtr` start) -- length so far (ptr past end-of-string so no succ) s -- value so far shift -- next shift to use inner start s1 shift1 (S ss bs n) <- getFull trace ("getFull says: "++ show ((S.length ss,ss),(L.length bs),n)) $ do if S.null ss then do continue <- suspend if continue then go s1 shift1 else fail "Get.decode7: Zero length input" -- XXX can be triggered! else do let (T3 i sOut shiftOut) = unsafePerformIO $ scanner ss t = S.unsafeDrop i ss -- Warning: 't' may be mempty n' = n + fromIntegral i trace ("scanner says "++show ((i,toInteger sOut,shiftOut),(S.length t,n'))) $ do if 0 <= shiftOut then do putFull_unsafe (make_state bs n') if L.null bs then do continue <- suspend if continue then go sOut shiftOut else return sOut else do go sOut shiftOut else do putFull_safe (S t bs n') -- bs from getFull is still valid return sOut data T2 = T2 !Int64 !Bool decode7size :: Get Int64 decode7size = go 0 where go !len1 = do let scanner (S.PS fp off len) = withForeignPtr fp $ \ptr0 -> do if ptr0 == nullPtr || len < 1 then error "Get.decode7size: ByteString invariant failed" else do let start = ptr0 `plusPtr` off end = start `plusPtr` len inner :: (Ptr Word8) -> IO T2 inner !ptr | ptr < end = do w <- peek ptr if (128>) w then return $ T2 (fromIntegral (ptr `minusPtr` start)) True else inner (ptr `plusPtr` 1) | otherwise = return $ T2 (fromIntegral (ptr `minusPtr` start)) False inner start (S ss bs n) <- getFull if S.null ss then do continue <- suspend if continue then go len1 else fail "Get.decode7size: zero length input" else do let (T2 i ok) = unsafePerformIO $ scanner ss t = S.unsafeDrop (fromIntegral i) ss n' = n + i len2 = len1 + i if ok then do putFull_unsafe (S t bs n') return len2 else do putFull_unsafe (make_state bs n') if L.null bs then do continue <- suspend if continue then go len2 else return len2 else go len2 -- Private Internal error handling stack type -- This must NOT be exposed by this module -- -- The ErrorFrame is the top-level error handler setup when execution begins. -- It starts with the Bool set to True: meaning suspend can ask for more input. -- Once suspend get 'Nothing' in reply the Bool is set to False, which means -- that 'suspend' should no longer ask for input -- the input is finished. -- Why store the Bool there? It was handy when I needed to add it. data FrameStack b = ErrorFrame (String -> S -> Result b) -- top level handler Bool -- True at start, False if Nothing passed to suspend continuation | HandlerFrame (Maybe ( S -> FrameStack b -> String -> Result b )) -- encapsulated handler S -- stored state to pass to handler (Seq L.ByteString) -- additional input to hass to handler (FrameStack b) -- earlier/shallower/outer handlers type Success b a = (a -> S -> FrameStack b -> Result b) -- Internal monad type newtype Get a = Get { unGet :: forall b. -- the forall hides the CPS style (and prevents use of MonadCont) Success b a -- main continuation -> S -- parser state -> FrameStack b -- error handler stack -> Result b -- operation } -- These implement the checkponting needed to store and revive the -- state for lookAhead. They are fragile because the setCheckpoint -- must preceed either useCheckpoint or clearCheckpoint but not both. -- The FutureFrame must be the most recent handler, so the commands -- must be in the same scope depth. Because of these constraints, the reader -- value 'r' does not need to be stored and can be taken from the Get -- parameter. -- -- IMPORTANT: Any FutureFrame at the top level(s) is discarded by throwError. setCheckpoint,useCheckpoint,clearCheckpoint :: Get () setCheckpoint = Get $ \ sc s pc -> sc () s (HandlerFrame Nothing s mempty pc) useCheckpoint = Get $ \ sc (S _ _ _) frame -> case frame of (HandlerFrame Nothing s future pc) -> sc () (collect s future) pc _ -> error "Text.ProtocolBuffers.Get: Impossible useCheckpoint frame!" clearCheckpoint = Get $ \ sc s frame -> case frame of (HandlerFrame Nothing _s _future pc) -> sc () s pc _ -> error "Text.ProtocolBuffers.Get: Impossible clearCheckpoint frame!" -- | 'lookAhead' runs the @todo@ action and then rewinds only the -- BinaryParser state. Any new input from 'suspend' or changes from -- 'putAvailable' are kept. Changes to the user state (MonadState) -- are kept. The MonadWriter output is retained. -- -- If an error is thrown then the entire monad state is reset to last -- catchError as usual. lookAhead :: Get a -> Get a lookAhead todo = do setCheckpoint a <- todo useCheckpoint return a -- | 'lookAheadM' runs the @todo@ action. If the action returns 'Nothing' then the -- BinaryParser state is rewound (as in 'lookAhead'). If the action return 'Just' then -- the BinaryParser is not rewound, and lookAheadM acts as an identity. -- -- If an error is thrown then the entire monad state is reset to last -- catchError as usual. lookAheadM :: Get (Maybe a) -> Get (Maybe a) lookAheadM todo = do setCheckpoint a <- todo maybe useCheckpoint (const clearCheckpoint) a return a -- | 'lookAheadE' runs the @todo@ action. If the action returns 'Left' then the -- BinaryParser state is rewound (as in 'lookAhead'). If the action return 'Right' then -- the BinaryParser is not rewound, and lookAheadE acts as an identity. -- -- If an error is thrown then the entire monad state is reset to last -- catchError as usual. lookAheadE :: Get (Either a b) -> Get (Either a b) lookAheadE todo = do setCheckpoint a <- todo either (const useCheckpoint) (const clearCheckpoint) a return a -- 'collect' is used by 'putCheckpoint' and 'throwError' collect :: S -> Seq L.ByteString -> S collect s@(S ss bs n) future | Data.Sequence.null future = make_safe $ s | otherwise = make_safe $ S ss (mappend bs (F.foldr1 mappend future)) n -- Put the Show instances here instance (Show a) => Show (Result a) where showsPrec _ (Failed n msg) = ("(Failed "++) . shows n . (' ':) . shows msg . (")"++) showsPrec _ (Finished bs n a) = ("(CFinished ("++) . shows bs . (") ("++) . shows n . (") ("++) . shows a . ("))"++) showsPrec _ (Partial {}) = ("(Partial <Maybe Data.ByteString.Lazy.ByteString-> Result a)"++) instance Show (FrameStack b) where showsPrec _ (ErrorFrame _ p) =(++) "(ErrorFrame <e->s->m b> " . shows p . (")"++) showsPrec _ (HandlerFrame _ s future pc) = ("(HandlerFrame <> ("++) . shows s . (") ("++) . shows future . (") ("++) . shows pc . (")"++) -- | 'runGet' is the simple executor runGet :: Get a -> L.ByteString -> Result a runGet (Get f) bsIn = f scIn sIn (ErrorFrame ec True) where scIn a (S ss bs n) _pc = Finished (L.chunk ss bs) n a sIn = make_state bsIn 0 ec msg sOut = Failed (consumed sOut) msg -- | 'runGetAll' is the simple executor, and will not ask for any continuation because this lazy bytestring is all the input runGetAll :: Get a -> L.ByteString -> Result a runGetAll (Get f) bsIn = f scIn sIn (ErrorFrame ec False) where scIn a (S ss bs n) _pc = Finished (L.chunk ss bs) n a sIn = make_state bsIn 0 ec msg sOut = Failed (consumed sOut) msg -- | Get the input currently available to the parser. getAvailable :: Get L.ByteString getAvailable = Get $ \ sc s@(S ss bs _) pc -> sc (L.chunk ss bs) s pc -- | 'putAvailable' replaces the bytestream past the current # of read -- bytes. This will also affect pending MonadError handler and -- MonadPlus branches. I think all pending branches have to have -- fewer bytesRead than the current one. If this is wrong then an -- error will be thrown. -- -- WARNING : 'putAvailable' is still untested. putAvailable :: L.ByteString -> Get () putAvailable !bsNew = Get $ \ sc (S _ss _bs n) pc -> let !s' = make_state bsNew n rebuild (HandlerFrame catcher (S ss1 bs1 n1) future pc') = HandlerFrame catcher sNew mempty (rebuild pc') where balance = n - n1 whole | balance < 0 = error "Impossible? Cannot rebuild HandlerFrame in MyGet.putAvailable: balance is negative!" | otherwise = L.take balance $ L.chunk ss1 bs1 `mappend` F.foldr mappend mempty future sNew | balance /= L.length whole = error "Impossible? MyGet.putAvailable.rebuild.sNew HandlerFrame assertion failed." | otherwise = make_state (mappend whole bsNew) n1 rebuild x@(ErrorFrame {}) = x in sc () s' (rebuild pc) -- Internal access to full internal state, as helper functions getFull :: Get S getFull = Get $ \ sc s pc -> sc s s pc {-# INLINE putFull_unsafe #-} putFull_unsafe :: S -> Get () putFull_unsafe !s = Get $ \ sc _s pc -> sc () s pc {-# INLINE make_safe #-} make_safe :: S -> S make_safe s@(S ss bs n) = if S.null ss then make_state bs n else s {-# INLINE make_state #-} make_state :: L.ByteString -> Int64 -> S make_state L.Empty n = S mempty mempty n make_state (L.Chunk ss bs) n = S ss bs n putFull_safe :: S -> Get () putFull_safe= putFull_unsafe . make_safe -- | Keep calling 'suspend' until Nothing is passed to the 'Partial' -- continuation. This ensures all the data has been loaded into the -- state of the parser. suspendUntilComplete :: Get () suspendUntilComplete = do continue <- suspend when continue suspendUntilComplete -- | Call suspend and throw and error with the provided @msg@ if -- Nothing has been passed to the 'Partial' continuation. Otherwise -- return (). suspendMsg :: String -> Get () suspendMsg msg = do continue <- suspend if continue then return () else throwError msg -- | check that there are at least @n@ bytes available in the input. -- This will suspend if there is to little data. ensureBytes :: Int64 -> Get () ensureBytes n = do (S ss bs _read) <- getFull if S.null ss then suspendMsg "ensureBytes failed" >> ensureBytes n else do if n < fromIntegral (S.length ss) then return () else do if n == L.length (L.take n (L.chunk ss bs)) then return () else suspendMsg "ensureBytes failed" >> ensureBytes n {-# INLINE ensureBytes #-} -- | Pull @n@ bytes from the input, as a lazy ByteString. This will -- suspend if there is too little data. getLazyByteString :: Int64 -> Get L.ByteString getLazyByteString n | n<=0 = return mempty | otherwise = do (S ss bs offset) <- getFull if S.null ss then do suspendMsg ("getLazyByteString S.null ss failed with "++show (n,(S.length ss,L.length bs,offset))) getLazyByteString n else do case splitAtOrDie n (L.chunk ss bs) of -- safe use of L.chunk because of S.null ss check above Just (consume,rest) -> do putFull_unsafe (make_state rest (offset+n)) return $! consume Nothing -> do suspendMsg ("getLazyByteString (Nothing from splitAtOrDie) failed with "++show (n,(S.length ss,L.length bs,offset))) getLazyByteString n {-# INLINE getLazyByteString #-} -- important -- | 'suspend' is supposed to allow the execution of the monad to be -- halted, awaiting more input. The computation is supposed to -- continue normally if this returns True, and is supposed to halt -- without calling suspend again if this returns False. All future -- calls to suspend will return False automatically and no nothing -- else. -- -- These semantics are too specialized to let this escape this module. class MonadSuspend m where suspend :: m Bool -- The instance here is fairly specific to the stack manipluation done -- by 'addFuture' to ('S' user) and to the packaging of the resumption -- function in 'IResult'('IPartial'). instance MonadSuspend Get where suspend = Get ( let checkBool (ErrorFrame _ b) = b checkBool (HandlerFrame _ _ _ pc) = checkBool pc -- addFuture puts the new data in 'future' where throwError's collect can find and use it addFuture bs (HandlerFrame catcher s future pc) = HandlerFrame catcher s (future |> bs) (addFuture bs pc) addFuture _bs x@(ErrorFrame {}) = x -- Once suspend is given Nothing, it remembers this and always returns False rememberFalse (ErrorFrame ec _) = ErrorFrame ec False rememberFalse (HandlerFrame catcher s future pc) = HandlerFrame catcher s future (rememberFalse pc) in \ sc sIn pcIn -> if checkBool pcIn -- Has Nothing ever been given to a partial continuation? then let f Nothing = let pcOut = rememberFalse pcIn in sc False sIn pcOut f (Just bs') = let sOut = appendBS sIn bs' pcOut = addFuture bs' pcIn in sc True sOut pcOut in Partial f else sc False sIn pcIn -- once Nothing has been given suspend is a no-op ) where appendBS (S ss bs n) bs' = make_safe (S ss (mappend bs bs') n) -- A unique sort of command... -- | 'discardInnerHandler' causes the most recent catchError to be -- discarded, i.e. this reduces the stack of error handlers by removing -- the top one. These are the same handlers which Alternative((<|>)) and -- MonadPlus(mplus) use. This is useful to commit to the current branch and let -- the garbage collector release the suspended handler and its hold on -- the earlier input. discardInnerHandler :: Get () discardInnerHandler = Get $ \ sc s pcIn -> let pcOut = case pcIn of ErrorFrame {} -> pcIn HandlerFrame _ _ _ pc' -> pc' in sc () s pcOut {-# INLINE discardInnerHandler #-} {- Currently unused, commented out to satisfy -Wall -- | 'discardAllHandlers' causes all catchError handler to be -- discarded, i.e. this reduces the stack of error handlers to the top -- level handler. These are the same handlers which Alternative((<|>)) -- and MonadPlus(mplus) use. This is useful to commit to the current -- branch and let the garbage collector release the suspended handlers -- and their hold on the earlier input. discardAllHandlers :: Get () discardAllHandlers = Get $ \ sc s pcIn -> let base pc@(ErrorFrame {}) = pc base (HandlerFrame _ _ _ pc) = base pc in sc () s (base pcIn) {-# INLINE discardAllHandlers #-} -} -- The BinaryParser instance: -- | Discard the next @m@ bytes skip :: Int64 -> Get () skip m | m <=0 = return () | otherwise = do ensureBytes m (S ss bs n) <- getFull -- Could ignore impossible S.null ss due to (ensureBytes m) and (0 < m) but be paranoid let lbs = L.chunk ss bs -- L.chunk is safe putFull_unsafe (make_state (L.drop m lbs) (n+m)) -- drop will not perform less than 'm' bytes due to ensureBytes above -- | Return the number of 'bytesRead' so far. Initially 0, never negative. bytesRead :: Get Int64 bytesRead = fmap consumed getFull -- | Return the number of bytes 'remaining' before the current input -- runs out and 'suspend' might be called. remaining :: Get Int64 remaining = do (S ss bs _) <- getFull return $ fromIntegral (S.length ss) + (L.length bs) -- | Return True if the number of bytes 'remaining' is 0. Any futher -- attempts to read an empty parser will call 'suspend' which might -- result in more input to consume. -- -- Compare with 'isReallyEmpty' isEmpty :: Get Bool isEmpty = do (S ss _bs _n) <- getFull return (S.null ss) -- && (L.null bs) -- | Return True if the input is exhausted and will never be added to. -- Returns False if there is input left to consume. -- -- Compare with 'isEmpty' isReallyEmpty :: Get Bool isReallyEmpty = isEmpty >>= loop where loop False = return False loop True = do continue <- suspend if continue then isReallyEmpty else return True -- | get the longest prefix of the input where the high bit is set as well as following byte. -- This made getVarInt slower. highBitRun :: Get Int64 {-# INLINE highBitRun #-} highBitRun = loop where loop :: Get Int64 {-# INLINE loop #-} loop = do (S ss bs _n) <- getFull -- S.null ss is okay, will lead to Nothing, Nothing, suspend below let mi = S.findIndex (128>) ss case mi of Just i -> return (succ $ fromIntegral i) Nothing -> do let mj = L.findIndex (128>) bs case mj of Just j -> return (fromIntegral (S.length ss) + succ j) Nothing -> do continue <- suspend if continue then loop else fail "highBitRun has failed" -- | get the longest prefix of the input where all the bytes satisfy the predicate. spanOf :: (Word8 -> Bool) -> Get (L.ByteString) spanOf f = do let loop = do (S ss bs n) <- getFull let (pre,post) = L.span f (L.chunk ss bs) -- L.chunk is safe putFull_unsafe (make_state post (n + L.length pre)) if L.null post then do continue <- suspend if continue then fmap ((L.toChunks pre)++) loop else return (L.toChunks pre) else return (L.toChunks pre) fmap L.fromChunks loop {-# INLINE spanOf #-} -- | Pull @n@ bytes from the input, as a strict ByteString. This will -- suspend if there is too little data. If the result spans multiple -- lazy chunks then the result occupies a freshly allocated strict -- bytestring, otherwise it fits in a single chunk and refers to the -- same immutable memory block as the whole chunk. getByteString :: Int -> Get S.ByteString getByteString nIn | nIn <= 0 = return mempty | otherwise = do (S ss bs n) <- getFull if nIn < S.length ss -- Leave at least one character of 'ss' in 'post' allowing putFull_unsafe below then do let (pre,post) = S.splitAt nIn ss putFull_unsafe (S post bs (n+fromIntegral nIn)) return $! pre -- Expect nIn to be less than S.length ss the vast majority of times -- so do not worry about doing anything fancy here. else do now <- fmap (S.concat . L.toChunks) (getLazyByteString (fromIntegral nIn)) return $! now {-# INLINE getByteString #-} -- important getWordhost :: Get Word getWordhost = getStorable {-# INLINE getWordhost #-} getWord8 :: Get Word8 getWord8 = getPtr 1 {-# INLINE getWord8 #-} getWord16be,getWord16le,getWord16host :: Get Word16 getWord16be = do s <- getByteString 2 return $! (fromIntegral (s `S.unsafeIndex` 0) `shiftl_w16` 8) .|. (fromIntegral (s `S.unsafeIndex` 1)) {-# INLINE getWord16be #-} getWord16le = do s <- getByteString 2 return $! (fromIntegral (s `S.unsafeIndex` 1) `shiftl_w16` 8) .|. (fromIntegral (s `S.unsafeIndex` 0) ) {-# INLINE getWord16le #-} getWord16host = getStorable {-# INLINE getWord16host #-} getWord32be,getWord32le,getWord32host :: Get Word32 getWord32be = do s <- getByteString 4 return $! (fromIntegral (s `S.unsafeIndex` 0) `shiftl_w32` 24) .|. (fromIntegral (s `S.unsafeIndex` 1) `shiftl_w32` 16) .|. (fromIntegral (s `S.unsafeIndex` 2) `shiftl_w32` 8) .|. (fromIntegral (s `S.unsafeIndex` 3) ) {-# INLINE getWord32be #-} getWord32le = do s <- getByteString 4 return $! (fromIntegral (s `S.unsafeIndex` 3) `shiftl_w32` 24) .|. (fromIntegral (s `S.unsafeIndex` 2) `shiftl_w32` 16) .|. (fromIntegral (s `S.unsafeIndex` 1) `shiftl_w32` 8) .|. (fromIntegral (s `S.unsafeIndex` 0) ) {-# INLINE getWord32le #-} getWord32host = getStorable {-# INLINE getWord32host #-} getWord64be,getWord64le,getWord64host :: Get Word64 getWord64be = do s <- getByteString 8 return $! (fromIntegral (s `S.unsafeIndex` 0) `shiftl_w64` 56) .|. (fromIntegral (s `S.unsafeIndex` 1) `shiftl_w64` 48) .|. (fromIntegral (s `S.unsafeIndex` 2) `shiftl_w64` 40) .|. (fromIntegral (s `S.unsafeIndex` 3) `shiftl_w64` 32) .|. (fromIntegral (s `S.unsafeIndex` 4) `shiftl_w64` 24) .|. (fromIntegral (s `S.unsafeIndex` 5) `shiftl_w64` 16) .|. (fromIntegral (s `S.unsafeIndex` 6) `shiftl_w64` 8) .|. (fromIntegral (s `S.unsafeIndex` 7) ) {-# INLINE getWord64be #-} getWord64le = do s <- getByteString 8 return $! (fromIntegral (s `S.unsafeIndex` 7) `shiftl_w64` 56) .|. (fromIntegral (s `S.unsafeIndex` 6) `shiftl_w64` 48) .|. (fromIntegral (s `S.unsafeIndex` 5) `shiftl_w64` 40) .|. (fromIntegral (s `S.unsafeIndex` 4) `shiftl_w64` 32) .|. (fromIntegral (s `S.unsafeIndex` 3) `shiftl_w64` 24) .|. (fromIntegral (s `S.unsafeIndex` 2) `shiftl_w64` 16) .|. (fromIntegral (s `S.unsafeIndex` 1) `shiftl_w64` 8) .|. (fromIntegral (s `S.unsafeIndex` 0) ) {-# INLINE getWord64le #-} getWord64host = getStorable {-# INLINE getWord64host #-} -- Below here are the class instances instance Functor Get where fmap f m = Get (\sc -> unGet m (sc . f)) {-# INLINE fmap #-} instance Monad Get where return a = seq a $ Get (\sc -> sc a) {-# INLINE return #-} m >>= k = Get (\sc -> unGet m (\ a -> seq a $ unGet (k a) sc)) {-# INLINE (>>=) #-} fail = throwError . strMsg instance MonadError String Get where throwError msg = Get $ \_sc s pcIn -> let go (ErrorFrame ec _) = ec msg s go (HandlerFrame (Just catcher) s1 future pc1) = catcher (collect s1 future) pc1 msg go (HandlerFrame Nothing _s1 _future pc1) = go pc1 in go pcIn catchError mayFail handler = Get $ \sc s pc -> let pcWithHandler = let catcher s1 pc1 e1 = unGet (handler e1) sc s1 pc1 in HandlerFrame (Just catcher) s mempty pc actionWithCleanup = mayFail >>= \a -> discardInnerHandler >> return a in unGet actionWithCleanup sc s pcWithHandler instance MonadPlus Get where mzero = throwError (strMsg "[mzero:no message]") mplus m1 m2 = catchError m1 (const m2) instance Applicative Get where pure = return (<*>) = ap instance Alternative Get where empty = mzero (<|>) = mplus -- | I use "splitAt" without tolerating too few bytes, so write a Maybe version. -- This is the only place I invoke L.Chunk as constructor instead of pattern matching. -- I claim that the first argument cannot be empty. splitAtOrDie :: Int64 -> L.ByteString -> Maybe (L.ByteString, L.ByteString) splitAtOrDie i ps | i <= 0 = Just (mempty, ps) splitAtOrDie _i L.Empty = Nothing splitAtOrDie i (L.Chunk x xs) | i < len = let (pre,post) = S.splitAt (fromIntegral i) x in Just (L.chunk pre mempty, L.chunk post xs) | otherwise = case splitAtOrDie (i-len) xs of Nothing -> Nothing Just (y1,y2) -> Just (L.chunk x y1,y2) where len = fromIntegral (S.length x) {-# INLINE splitAtOrDie #-} ------------------------------------------------------------------------ -- getPtr copied from binary's Get.hs -- helper, get a raw Ptr onto a strict ByteString copied out of the -- underlying lazy byteString. So many indirections from the raw parser -- state that my head hurts... -- Assume n>0 getPtr :: (Storable a) => Int -> Get a getPtr n = do (fp,o,_) <- fmap S.toForeignPtr (getByteString n) return . S.inlinePerformIO $ withForeignPtr fp $ \p -> peek (castPtr $ p `plusPtr` o) {-# INLINE getPtr #-} -- I pushed the sizeOf into here (uses ScopedTypeVariables) -- Assume sizeOf (undefined :: a)) > 0 getStorable :: forall a. (Storable a) => Get a getStorable = do (fp,o,_) <- fmap S.toForeignPtr (getByteString (sizeOf (undefined :: a))) return . S.inlinePerformIO $ withForeignPtr fp $ \p -> peek (castPtr $ p `plusPtr` o) {-# INLINE getStorable #-} ------------------------------------------------------------------------ ------------------------------------------------------------------------ -- Unchecked shifts copied from binary's Get.hs shiftl_w16 :: Word16 -> Int -> Word16 shiftl_w32 :: Word32 -> Int -> Word32 shiftl_w64 :: Word64 -> Int -> Word64 #if defined(__GLASGOW_HASKELL__) && !defined(__HADDOCK__) shiftl_w16 (W16# w) (I# i) = W16# (w `uncheckedShiftL#` i) shiftl_w32 (W32# w) (I# i) = W32# (w `uncheckedShiftL#` i) #if WORD_SIZE_IN_BITS < 64 shiftl_w64 (W64# w) (I# i) = W64# (w `uncheckedShiftL64#` i) #if __GLASGOW_HASKELL__ <= 606 -- Exported by GHC.Word in GHC 6.8 and higher foreign import ccall unsafe "stg_uncheckedShiftL64" uncheckedShiftL64# :: Word64# -> Int# -> Word64# #endif #else shiftl_w64 (W64# w) (I# i) = W64# (w `uncheckedShiftL#` i) #endif #else shiftl_w16 = shiftL shiftl_w32 = shiftL shiftl_w64 = shiftL #endif
flowbox-public/protocol-buffers
Text/ProtocolBuffers/Get.hs
apache-2.0
38,144
486
80
10,801
8,565
4,734
3,831
-1
-1
module Text.Jasmine ( minify , minifym , minifyBb , minifyFile ) where --import Text.Jasmine.Parse import Language.JavaScript.Parser (readJs, parse, JSNode(..)) import Text.Jasmine.Pretty import qualified Blaze.ByteString.Builder as BB import qualified Data.ByteString.Lazy as LB import qualified Data.ByteString.Lazy.Char8 as S8 import Data.Text.Lazy (unpack) import Data.Text.Lazy.Encoding (decodeUtf8With) import Data.Text.Encoding.Error (lenientDecode) minifym :: LB.ByteString -> Either String LB.ByteString minifym s = case parse' s of Left msg -> Left (show msg) Right p -> Right $ BB.toLazyByteString $ renderJS p minifyBb :: LB.ByteString -> Either String BB.Builder minifyBb s = case parse' s of Left msg -> Left (show msg) Right p -> Right (renderJS p) minify :: LB.ByteString -> LB.ByteString --minify s = BB.toLazyByteString $ renderJS $ readJs s minify s = BB.toLazyByteString $ renderJS $ readJs (lbToStr s) _minify' :: LB.ByteString -> BB.Builder _minify' s = renderJS $ readJs (lbToStr s) minifyFile :: FilePath -> IO LB.ByteString minifyFile filename = do x <- LB.readFile (filename) return $ minify x --parse' :: S8.ByteString -> Either ParseError JSNode parse' :: S8.ByteString -> Either String JSNode parse' input = parse (lbToStr input) "src" lbToStr :: S8.ByteString -> [Char] lbToStr = unpack . decodeUtf8With lenientDecode _strToLb :: String -> S8.ByteString _strToLb str = S8.pack str -- EOF
snoyberg/hjsmin
Text/Jasmine.hs
bsd-3-clause
1,524
0
10
305
462
248
214
38
2
{-# LANGUAGE QuantifiedConstraints #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-} module T17267c where -- Now rejected class C a b where op :: a -> b class C a b => Thing a b instance C a b => Thing a b unsafeCoerce :: forall a b. a -> b unsafeCoerce a = oops (op a :: Thing a b => b) where oops :: (C a b => Thing a b) => (Thing a b => x) -> x oops r = r
sdiehl/ghc
testsuite/tests/quantified-constraints/T17267c.hs
bsd-3-clause
537
0
11
119
163
86
77
-1
-1
module RecursionIn1 where --A top level definition can be duplicated. --In this example: duplicate the definition 'fac' with new name 'anotherFac' --Pay attention to the recursion. fac :: Int -> Int fac 0 = 1 fac 1 = 1 fac n = n * fac (n-1) fib :: Int -> Int fib 0 = 1 fib 1 = 1 fib n = (fib (n-1)) + (fib (n-2)) main :: Int main = fac 5 + fib 3
kmate/HaRe
old/testing/duplication/RecursionIn1.hs
bsd-3-clause
351
0
9
82
137
73
64
11
1
{-# LANGUAGE ImplicitParams, RankNTypes #-} {-# OPTIONS_GHC -dcore-lint #-} module Main where import GHC.Stack f0 = putStrLn $ prettyCallStack ?loc -- should be empty f1 :: (?loc :: CallStack) => IO () f1 = putStrLn $ prettyCallStack ?loc -- should show the location of f1's call-site f3 :: ((?loc :: CallStack) => () -> IO ()) -> IO () f3 x = x () -- the call-site for the functional argument should be added to the -- stack.. f4 :: (?loc :: CallStack) => ((?loc :: CallStack) => () -> IO ()) -> IO () f4 x = x () -- as should the call-site for f4 itself f5 :: (?loc1 :: CallStack) => ((?loc2 :: CallStack) => () -> IO ()) -> IO () f5 x = x () -- we only push new call-sites onto CallStacks with the name IP name f6 :: (?loc :: CallStack) => Int -> IO () f6 0 = putStrLn $ prettyCallStack ?loc f6 n = f6 (n-1) -- recursive functions add a SrcLoc for each recursive call main = do f0 f1 f3 (\ () -> putStrLn $ prettyCallStack ?loc) f4 (\ () -> putStrLn $ prettyCallStack ?loc) f5 (\ () -> putStrLn $ prettyCallStack ?loc3) f6 5
sgillespie/ghc
testsuite/tests/typecheck/should_run/IPLocation.hs
bsd-3-clause
1,131
0
11
309
371
197
174
22
1
{-# LANGUAGE KindSignatures #-} module BindKindName where type Foo (a :: DontExistKind) = a
ghc-android/ghc
testsuite/tests/rename/should_fail/rnfail057.hs
bsd-3-clause
94
0
5
16
18
13
5
-1
-1
-- !!! test super-dictionary grabification -- main = putStr (show (is_one (1.2::Double))) is_one :: RealFloat a => a -> Bool is_one x = x == 1.0
urbanslug/ghc
testsuite/tests/codeGen/should_run/cgrun024.hs
bsd-3-clause
148
1
10
29
63
31
32
3
1
module Util (combinations , deck , allPossibleHands ) where import Control.Arrow ((&&&)) import Control.Monad (filterM) import Data.List (sort, group) import Hand (Suit(..), Rank(..), Card, Hand(Hand), HandType, extractHandType) combinations :: Int -> [a] -> [[a]] combinations m xs = combsBySize xs !! m where combsBySize = foldr f ([[]] : repeat []) f x next = zipWith (++) (map (map (x:)) ([]:next)) next deck :: [Card] deck = [(rank, suit) | rank <- [Two .. Ace], suit <- [Diamonds .. Spades]] --Warning, this has 2,598,960 elements allPossibleHands :: [Hand] allPossibleHands = map (\[a, b, c, d, e] -> Hand a b c d e) $ combinations 5 deck handfrequencies :: [(HandType, Int)] handfrequencies = map (head &&& length) . group . sort . map (fst . extractHandType) $ allPossibleHands
benperez/chinese-poker
src/Util.hs
mit
893
0
12
234
364
211
153
20
1
module NgLint.Output.Common where import NgLint.Messages type Formatter = String -> [LintMessage] -> IO ()
federicobond/nglint
src/NgLint/Output/Common.hs
mit
109
0
8
16
34
20
14
3
0
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} -- The use of error here is as a placeholder only. {-# OPTIONS_GHC -fno-warn-warnings-deprecations #-} -- | Moderation functionality for the website. module Imageboard.Web.Mod where import Data.HVect (ListContains, HVect(..), findFirst) import Database.Esqueleto import Heist ((##)) import Web.Spock hiding (SessionId, get) import Imageboard.Database import Imageboard.Formatting import Imageboard.Moderation import Imageboard.Moderation.Capabilities import Imageboard.Moderation.Users import Imageboard.Web.Forms import Imageboard.Web.Template import Imageboard.Web.Utils -- | Constraint synonym for a page with the appropriate mod context. type ModPage m n xs = (ListContains m BoardHeist xs, ListContains n LoginId xs) -- | Destroy the session and display a confirmation. logoutPage :: ModPage m n xs => BoardAction (HVect xs) () logoutPage = do sess <- readSession runSQL $ maybe (pure ()) logOut sess template "mod/plain-page" $ do "page-content" ## "You have been logged out." "if-logged-in" ## "" ------------------------------------------------------------------------------- -- | Index page: recent posts, images, reports, and staff actions. modIndex :: ModPage m n xs => BoardAction (HVect xs) () modIndex = template' "mod/index" -- | Create, delete, purge, and edit boards (display boards & create -- form). boards :: ModPage m n xs => BoardAction (HVect xs) () boards = do now <- getCurrentTime loginid <- findFirst <$> getContext (formView, formVal) <- runForm "newBoard" (newBoard now loginid) case formVal of Just (board, fileSizes, wordFilters, anonNames) -> do res <- runSQL $ createBoard board fileSizes wordFilters anonNames case res of Right _ -> done formView ("Board has been created." :: Text) -- TODO: Better error reporting Left err -> done formView ("An error occurred: " <> show err) Nothing -> done formView mempty where done formView msg = templateH (bindDigestiveSplices formView) "mod/board-admin" ("create-message" ## msg) -- | Create, delete, purge, edit (display form). editBoard :: ModPage m n xs => Text -> BoardAction (HVect xs) () editBoard boardname = do boardmay <- runSQL $ select $ from $ \b -> do where_ (b ^. BoardName ==. val boardname) pure b case boardmay of [Entity boardid board] -> do needCap (capBoardAdministration boardid) (formView, formVal) <- runForm "editBoard" (Imageboard.Web.Forms.editBoard boardid board) case formVal of Just newboard -> do loginid <- findFirst <$> getContext -- This is a bit hairy because of all the individual actions -- I have broken up editing a board into. Such is the price -- we pay for precise logging. Ho hum. runSQL $ do -- TODO: fix let changeB f g = onChange f board newboard $ g (f newboard) loginid boardid let changeT f g = onChange f board newboard $ g (f newboard) loginid boardid let changeI f g = onChange f board newboard $ g (f newboard) loginid boardid let changeS f g = onChange f board newboard $ g (f newboard) loginid boardid changeT boardName renameBoard changeT boardTitle retitleBoard changeT boardSubtitle resubtitleBoard changeB (not . boardDisabled) enableBoard changeB (not . boardPrivate) publicPrivateBoard changeB boardLocked lockBoard changeI boardFilesPerPost filesPerPostBoard changeI boardExternalLinksPerPost externalLinksPerPostBoard changeI boardPostLengthLimit postLengthLimitBoard changeI boardThreadsPerPage threadsPerPageBoard changeI boardPostsPerThread postsPerThreadBoard changeI boardPageLimit pageLimitBoard changeI boardBumpLimit bumpLimitBoard changeS boardSpoilerImage spoilerImageBoard changeB boardCaptcha captchaBoard changeB boardPosterIds posterIdsBoard redirect "/mod/" Nothing -> done formView "" _ -> showMessage ("Edit /" <> boardname <> "/") "No such board." where done formView msg = templateH (bindDigestiveSplices formView) "mod/board-edit" $ do "name" ## boardname "edit-message" ## msg -- | Edit a thread -- -- TODO: confirmation page for purge. editThread :: ModPage m n xs => Text -> BoardAction (HVect xs) () editThread threadname = do threadmay <- runSQL (threadByTextId threadname) case threadmay of Just (Entity threadid thread) -> do loginid <- findFirst <$> getContext dopurge <- param "purge" case dopurge of Just ("PURGE" :: String) -> do void . runSQL $ purgeThread loginid threadid toBoard (threadBoard thread) _ -> do (_, formVal) <- runForm "threadControl" (threadControlForm thread) case formVal of Just newthread -> runSQL $ do let change f g = onChange f thread newthread $ g (f newthread) loginid threadid change threadArchived archiveThread change threadBumplocked bumplockThread change threadHidden hideThread change threadLocked lockThread change threadStickied stickyThread Nothing -> pure () toThread threadid Nothing -> redirectOr Nothing "No such thread." where toBoard boardid = do boardmay <- runSQL (get boardid) let linkmay = (\b -> "/" <> boardName b <> "/") <$> boardmay redirectOr linkmay "No such board." toThread threadid = do linkmay <- runSQL (formatThreadName threadid) redirectOr linkmay "No such thread." redirectOr (Just target) _ = redirect target redirectOr Nothing msg = showMessage "Thread Controls" msg -- | Edit, delete, purge, add note (display form). editPost :: ModPage m n xs => Text -> BoardAction (HVect xs) () editPost _post = error "unimplemented: editPost" -- | Edit, delete, purge, add note (process). doEditPost :: ModPage m n xs => Text -> BoardAction (HVect xs) () doEditPost _post = error "unimplemented: doEditPost" -- | Ban/unban, delete posts in board, add note (display form). editIp :: ModPage m n xs => Text -> BoardAction (HVect xs) () editIp _ip = error "unimplemented: editIp" -- | Ban/unban, delete posts in board, add note (process). doEditIp :: ModPage m n xs => Text -> BoardAction (HVect xs) () doEditIp _ip = error "unimplemented: doEditIp" -- | Manage capcodes (display capcodes & create form). capcodes :: ModPage m n xs => BoardAction (HVect xs) () capcodes = error "unimplemented: capcodes" -- | Create a capcode (process). newCapcode :: ModPage m n xs => BoardAction (HVect xs) () newCapcode = error "unimplemented: newCapcode" -- | Edit (display form). editCapcode :: ModPage m n xs => Text -> BoardAction (HVect xs) () editCapcode _capcode = error "unimplemented: editCapcode" -- | Edit (process). doEditCapcode :: ModPage m n xs => Text -> BoardAction (HVect xs) () doEditCapcode _capcode = error "unimplemented: doEditCapcode" -- | Create, delete, purge, and edit news (display news & create -- form). news :: ModPage m n xs => BoardAction (HVect xs) () news = error "unimplemented: news" -- | Create a news item (process). newNews :: ModPage m n xs => BoardAction (HVect xs) () newNews = error "unimplemented: newNews" -- | Create, delete, purge, edit (display form). editNews :: ModPage m n xs => Text -> BoardAction (HVect xs) () editNews _news = error "unimplemented: editNews" -- | Create, delete, purge, edit (process). doEditNews :: ModPage m n xs => Text -> BoardAction (HVect xs) () doEditNews _news = error "unimplemented: doEditNews" -- | Create, delete, and edit users (display users & create -- form). users :: ModPage m n xs => BoardAction (HVect xs) () users = error "unimplemented: users" -- | Create a user (process). newUser :: ModPage m n xs => BoardAction (HVect xs) () newUser = error "unimplemented: newUser" -- | Create, delete, edit (display form). editUser :: ModPage m n xs => Text -> BoardAction (HVect xs) () editUser _username = error "unimplemented: editUser" -- | Create, delete, purge, edit (process). doEditUser :: ModPage m n xs => Text -> BoardAction (HVect xs) () doEditUser _username = error "unimplemented: doEditUser" -- | List and delete bans. banList :: ModPage m n xs => BoardAction (HVect xs) () banList = error "unimplemented: banList" -- | Revoke a ban. revokeBan :: ModPage m n xs => BoardAction (HVect xs) () revokeBan = error "unimplemented: revokeBan" -- | List and delete reports. reportList :: ModPage m n xs => BoardAction (HVect xs) () reportList = error "unimplemented: reportList" -- | Close or dismiss a report. closeReport :: ModPage m n xs => BoardAction (HVect xs) () closeReport = error "unimplemented: closeReport" -- | List mod actions. staffLog :: ModPage m n xs => BoardAction (HVect xs) () staffLog = error "unimplemented: staffLog" ------------------------------------------------------------------------------- -- Utilities -- | Terminate unless the user has a capability. needCap :: ModPage m n xs => Cap -> BoardAction (HVect xs) () needCap cap = do loginid <- findFirst <$> getContext hascap <- runSQL $ hasCapability loginid cap unless hascap $ showMessage "Permission Error" "You do not have permission to be here." -- | Terminate and show a message. showMessage :: ListContains m BoardHeist xs => Text -> Text -> BoardAction (HVect xs) a showMessage title msg = template "mod/plain-page" $ do "page-title" ## title "page-content" ## msg
barrucadu/nagi
lib/Imageboard/Web/Mod.hs
mit
9,923
0
31
2,218
2,526
1,226
1,300
170
5
{-# LANGUAGE OverloadedStrings #-} import Data.Monoid import qualified Data.Text.Lazy as T import Web.Scotty import Web.Scotty.Fay main :: IO () main = scotty 3000 $ do serveFay $ -- If the first segment of the request path matches this, try to serve -- Fay. Otherwise try the next route. under "/scotty-fay" . -- Specify the directory where your Fay files are. from "src/fay" get "/" $ do html $ "<!doctype html>" <> "<html>" <> "<head>" <> "<script type=text/javascript src=/scotty-fay/HelloWorld.hs></script>" <> "</head>" <> "<body><h1>lol</h1></body>" <> "</html>"
hdgarrood/scotty-fay
example/Main.hs
mit
712
0
17
226
110
58
52
19
1
module GHCJS.DOM.RTCDataChannel ( ) where
manyoo/ghcjs-dom
ghcjs-dom-webkit/src/GHCJS/DOM/RTCDataChannel.hs
mit
44
0
3
7
10
7
3
1
0
module HelloWorld.Types where import Control.Monad.Except import Data.IORef import Text.Parsec.Error type Env = IORef [(String, IORef HelloVal)] type IOThrowsError = ExceptT HelloError IO data HelloVal = Greeting String instance Show HelloVal where show (Greeting s) = "Hello, World!" instance Eq (HelloVal) where Greeting a == Greeting b = False _ == _ = False type ThrowsError = Either HelloError data HelloError = NumArgs Integer [HelloVal] | TypeMismatch String HelloVal | Parser ParseError | BadSpecialForm String HelloVal | NotFunction String String | UnboundVar String String | DivisionByZero | Default String instance Show HelloError where show = showError showError :: HelloError -> String showError (UnboundVar message varname) = message ++ ": " ++ varname showError (BadSpecialForm message form) = message ++ ": " ++ show form showError (NotFunction message func) = message ++ ": " ++ show func showError (NumArgs expected []) = "Expected " ++ show expected ++ " args; none given" showError (NumArgs expected found) = "Expected " ++ show expected ++ " args; found values " ++ unwordsList found showError (TypeMismatch expected found) = "Invalid type: expected " ++ expected ++ ", found " ++ show found showError (Parser parseErr) = "Parse error at " ++ show parseErr showError (DivisionByZero) = "Division by zero!" unwordsList :: [HelloVal] -> String unwordsList = unwords . map show
wildlyinaccurate/hello-world
src/HelloWorld/Types.hs
mit
1,684
0
8
503
439
228
211
36
1
hello_worlds n = putStrLn $ unlines $ take n (repeat "Hello World") -- This part is related to the Input/Output and can be used as it is -- Do not modify it main = do n <- readLn :: IO Int hello_worlds n
tsurai/hackerrank
functional-programming/introduction/hello-world-n-times.hs
mit
211
0
8
50
54
26
28
4
1
{-# LANGUAGE RecordWildCards #-} {- The responsibility of the diagnoser is to turn baked deployments into diagnosed deployments. This is purely a read-only operation that looks at the current state of the file system. -} module SuperUserSpark.Diagnose ( diagnoseFromArgs , diagnoseAssignment , deriveDiagnoseSettings , diagnose , formatDiagnoseError , diagnoserBake , diagnoseDeployments ) where import Import import qualified Data.Aeson.Encode.Pretty as JSON import qualified Data.ByteString.Lazy.Char8 as LB import SuperUserSpark.Bake import SuperUserSpark.Bake.Internal import SuperUserSpark.Bake.Types import SuperUserSpark.Diagnose.Internal import SuperUserSpark.Diagnose.Types import SuperUserSpark.OptParse.Types import SuperUserSpark.Utils diagnoseFromArgs :: DiagnoseArgs -> IO () diagnoseFromArgs cas = do errOrAss <- diagnoseAssignment cas case errOrAss of Left err -> die $ unwords ["Failed to build Diagnose assignment:", err] Right ass -> diagnose ass diagnoseAssignment :: DiagnoseArgs -> IO (Either String DiagnoseAssignment) diagnoseAssignment DiagnoseArgs {..} = do errOrCardRef <- parseBakeCardReference diagnoseArgCardRef case errOrCardRef of Left err -> pure $ Left err Right cardRef -> DiagnoseAssignment cardRef <$$> deriveDiagnoseSettings cardRef diagnoseFlags deriveDiagnoseSettings :: BakeCardReference -> DiagnoseFlags -> IO (Either String DiagnoseSettings) deriveDiagnoseSettings bcr DiagnoseFlags {..} = DiagnoseSettings <$$> deriveBakeSettings bcr diagnoseBakeFlags diagnose :: DiagnoseAssignment -> IO () diagnose DiagnoseAssignment {..} = do errOrDone <- runReaderT (runExceptT $ diagnoseByCardRef diagnoseCardReference) diagnoseSettings case errOrDone of Left err -> die $ formatDiagnoseError err Right () -> pure () formatDiagnoseError :: DiagnoseError -> String formatDiagnoseError (DiagnoseBakeError ce) = formatBakeError ce formatDiagnoseError (DiagnoseError s) = unwords ["Diagnose failed:", s] diagnoseByCardRef :: BakeCardReference -> SparkDiagnoser () diagnoseByCardRef checkCardReference = do deps <- diagnoserBake $ compileBakeCardRef checkCardReference >>= bakeDeployments ddeps <- liftIO $ diagnoseDeployments deps liftIO . LB.putStrLn $ JSON.encodePretty ddeps diagnoserBake :: SparkBaker a -> SparkDiagnoser a diagnoserBake = withExceptT DiagnoseBakeError . mapExceptT (withReaderT diagnoseBakeSettings) diagnoseDeployments :: [BakedDeployment] -> IO [DiagnosedDeployment] diagnoseDeployments = mapM diagnoseDeployment
NorfairKing/super-user-spark
src/SuperUserSpark/Diagnose.hs
mit
2,736
0
12
547
576
293
283
63
2
{-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE AutoDeriveTypeable #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE ViewPatterns #-} module Graphics.UI.Label ( createLabel , text , interpretation , setBuddy , Label() ) where import Data.Text import Graphics.UI.Internal.Common import Graphics.UI.UIVar import Graphics.UI.Widget foreign import ccall create_label :: IO (Ptr QLabel) foreign import ccall set_label_buddy :: Ptr QLabel -> Ptr QWidget -> IO () foreign import ccall set_label_text :: Ptr QLabel -> Ptr QString -> IO () foreign import ccall get_label_text :: Ptr QLabel -> IO (Ptr QString) foreign import ccall set_label_interpretation :: Ptr QLabel -> CInt -> IO () foreign import ccall get_label_interpretation :: Ptr QLabel -> IO CInt newtype Label = Label (ManagedQObject QLabel) deriving ( Eq, Typeable, HasQObject, Touchable ) instance HasManagedQObject Label QLabel where getManagedQObject (Label man) = man instance CentralWidgetable Label instance IsWidget Label where getWidget = coerceManagedQObject . getManagedQObject -- | Creates a label. The label initially has no text. createLabel :: UIAction Label createLabel = liftIO $ mask_ $ do label_ptr <- create_label Label <$> (manageQObject =<< createTrackedQObject label_ptr) -- | Set the buddy of the label. -- -- See <http://qt-project.org/doc/qt-5/qlabel.html#setBuddy>. setBuddy :: HasManagedQObject a b => Label -> a -> UIAction () setBuddy label thing = liftIO $ withManagedQObject label $ \label_ptr -> withManagedQObject thing $ \(castPtr -> thing_ptr) -> set_label_buddy label_ptr thing_ptr -- | `UIVar` to label's text. text :: Label -> UIVar' Text text label = uivar (\new_text -> liftIO $ withManagedQObject label $ \label_ptr -> asQString new_text $ set_label_text label_ptr) (liftIO $ mask_ $ withManagedQObject label $ \label_ptr -> do str <- get_label_text label_ptr ret <- peekQString str freeQString str return ret) data LabelInterpretation = PlainText | RichText deriving ( Eq, Ord, Show, Read, Typeable, Enum ) -- Make these agree on the C++ side as well toConstant :: LabelInterpretation -> CInt toConstant PlainText = 0 toConstant RichText = 1 fromConstant :: CInt -> LabelInterpretation fromConstant 0 = PlainText fromConstant 1 = RichText fromConstant _ = error "fromConstant: invalid label interpretation." -- | `UIVar` to interpret the label's text interpretation :: Label -> UIVar' LabelInterpretation interpretation label = uivar (\new_interpretation -> liftIO $ withManagedQObject label $ \label_ptr -> set_label_interpretation label_ptr (toConstant new_interpretation)) (liftIO $ withManagedQObject label $ \label_ptr -> fromConstant <$> get_label_interpretation label_ptr)
Noeda/userinterface
src/Graphics/UI/Label.hs
mit
2,929
0
12
576
713
369
344
70
1
{-| Common types and utilities for brainfuck programs, including a few different implementations for the brainfuck data array. -} module Runtime where import Control.Monad (when) import Control.Monad.IO.Class (MonadIO, liftIO) import Data.Char (isAscii, showLitChar) import qualified Data.Vector.Unboxed.Mutable as V import Data.Word (Word8) import Foreign.Ptr (Ptr) import Foreign.Marshal.Array (advancePtr, withArray) import Foreign.Storable (peekElemOff, pokeElemOff) import System.IO (isEOF) -- | This type is used as the unit of memory by all of our bf machines. type Cell = Word8 type Offset = Int -- | Convert between 'Enum' types. -- This is a convenient way to convert 'Cell' to 'Char' and vice versa, -- since both are Enums. coerce :: (Enum a, Enum b) => a -> b coerce = toEnum . fromEnum -- | General monadic bf input, given an action to fetch a character -- and an action to write a cell to the data array. -- The default behavior is to leave the current cell value unchagned. bfInputM :: Monad m => m (Maybe Char) -> (Cell -> m ()) -> m () bfInputM gc wr = gc >>= maybe (return ()) (wr . coerce) -- | General monadic bf output, given an action to read a cell -- and an action to send a character. bfOutputM :: Monad m => m Cell -> (Char -> m ()) -> m () bfOutputM rd pc = rd >>= pc . coerce -- | General monadic bf loop, given an action that reads the current cell value -- and an action for the loop body. bfLoopM :: Monad m => m Cell -> m () -> m () bfLoopM rd body = loop' where loop' = do x <- rd when (x /= 0) $ body >> loop' -- | Accept an input character from stdin, returning Nothing on end-of-file. getc :: MonadIO m => m (Maybe Char) getc = do eof <- liftIO isEOF if eof then return Nothing else liftIO $ fmap Just getChar -- | Send a character to stdout. putc :: MonadIO m => Char -> m () putc c = liftIO $ if isAscii c then putChar c else putStr $ showLitChar c "" -- * Infinite tape memory -- | An infinite stream of 'Cell's data Stream = Cell :> Stream -- | A bidirectionally infinite tape with one 'Cell' that can be read -- from or written to by a notional /tape head/ that can be moved left -- or right along the tape. Also tracks the current position relative -- to the /data pointer/. data Tape = T !Offset Stream !Cell Stream -- | A tape initialized to all zeros. blankTape :: Tape blankTape = T 0 zs 0 zs where zs = 0 :> zs -- | Move tape head one cell to the left. tapeLeft :: Tape -> Tape tapeLeft (T p (h' :> l) h r) = T (p-1) l h' (h :> r) -- | Move tape head one cell to the right. tapeRight :: Tape -> Tape tapeRight (T p l h (h' :> r)) = T (p+1) (h :> l) h' r -- | Read at tape head. tapeRead' :: Tape -> Cell tapeRead' (T _ _ h _) = h -- | Write to tape head. tapeWrite' :: Cell -> Tape -> Tape tapeWrite' x (T p l _ r) = T p l x r -- | Move the data pointer. -- No need to actually move the tape, just update relative position. tapeMove :: Offset -> Tape -> Tape tapeMove n (T p l h r) = T (p - n) l h r -- | Move tape to offset relative to pointer. -- Positive offsets are to the right, negative to the left. tapeMoveToOffset :: Offset -> Tape -> Tape tapeMoveToOffset off t@(T p _ _ _) | off < p = iterate tapeLeft t !! (p - off) | otherwise = iterate tapeRight t !! (off - p) -- | Get the value of the cell at offset. tapeRead :: Offset -> Tape -> Cell tapeRead off = tapeRead' . tapeMoveToOffset off -- | Set the value of the cell at offset. tapeWrite :: Offset -> Cell -> Tape -> Tape tapeWrite off x = tapeWrite' x . tapeMoveToOffset off -- * Vector memory -- | A VectorMem consists of a mutable 'Vector' of 'Cell's and an -- index that acts as a pointer to the current cell. data VectorMem = VM (V.IOVector Cell) !Int -- | Allocate a new VectorMem with the given size, with all elements -- initialized to zero and the pointer pointing to the first element, -- and then run the given action using the new VectorMem. withVectorMem :: Int -> (VectorMem -> IO a) -> IO a withVectorMem size f = do v <- V.replicate size 0 f (VM v 0) -- | Move the data pointer. vecMove :: Int -> VectorMem -> VectorMem vecMove n (VM v p) = VM v (p + n) -- | Get the value of cell at offset. vecRead :: MonadIO m => Offset -> VectorMem -> m Cell vecRead off (VM v p) = liftIO $ V.unsafeRead v (p + off) -- | Set the value of the cell at offset. vecWrite :: MonadIO m => Offset -> Cell -> VectorMem -> m () vecWrite off x (VM v p) = liftIO $ V.unsafeWrite v (p + off) x -- * Foreign pointer/array memory type FPtrMem = Ptr Cell -- | Allocate a new 'FPtrMem' with the given size, with all elements -- initialized to zero and the pointer pointing to the first element, -- and then run the given action using the new 'FPtrMem'. withFPtrMem :: Int -> (FPtrMem -> IO a) -> IO a withFPtrMem size = withArray (replicate size 0) -- | Move the data pointer. fptrMove :: Int -> FPtrMem -> FPtrMem fptrMove = flip advancePtr -- | Get the value of the cell at offset. fptrRead :: MonadIO m => Offset -> FPtrMem -> m Cell fptrRead off ptr = liftIO $ peekElemOff ptr off -- | Set the value of the cell at offset. fptrWrite :: MonadIO m => Offset -> Cell -> FPtrMem -> m () fptrWrite off x ptr = liftIO $ pokeElemOff ptr off x
gglouser/brainfree
src/Runtime.hs
mit
5,250
0
13
1,154
1,410
741
669
75
2
{-# LANGUAGE OverloadedStrings #-} module Handler.Service where import Import hiding (head) import Database.Persist import Database.Persist.Sql import SessionState import Data.List (nub, head) import qualified Database.Esqueleto as E getServiceR :: Handler Html getServiceR = do services <- getByType (toSqlKey 1) hyps <- getByType (toSqlKey 2) existedPrices <- runDB $ selectList [AsObjectT ==. (toSqlKey 3)] [] allInfo <- runDB $ getPrices hyplog <- runDB $ getHypLog let prices = if null existedPrices then setPrices services hyps else showPrices allInfo defaultLayout $ do setTitle "Услуги ΠΈ Π³ΠΈΠΏΠΎΡ‚Π΅Π·Ρ‹" $(widgetFile "o") $(fayFile "O") getByType :: forall site. (YesodPersist site, YesodPersistBackend site ~ SqlBackend) => Key AsType -> HandlerT site IO [Entity AsObject] getByType typ = runDB $ selectList [AsObjectT ==. typ] [Asc AsObjectId] setPrices :: [Entity AsObject] -> [Entity AsObject] -> PriceTable setPrices services hyps = let mult = [Price' 0.0 x y | x <- services', y <- hyps'] services' = getKeys services prices = groupBy compServices $ sortBy (compare `on` serv') mult compServices a b = serv' a == serv' b snames = getNames services hyps' = getKeys hyps in zip prices snames {-getPrices = runDB $ rawSql "select o.n, rs.ar, rh.ar, s.n from as_object o, as_param rs, as_param rh, as_object s where o.t = 3 and o.id = rs.ao and rs.aa = 1 and o.id = rh.ao and rh.aa = 2 and rs.ar = r.id order by s.id, rh.ar" []-} getPrices = E.select $ E.from $ \(o `E.InnerJoin` rs `E.InnerJoin` rh `E.InnerJoin` s) -> do E.on (rs E.^. AsParamAr E.==. s E.?. AsObjectId) E.on ( o E.^. AsObjectId E.==. rh E.^. AsParamAo E.&&. rh E.^. AsParamAa E.==. (E.valkey 2) ) E.on ( o E.^. AsObjectId E.==. rs E.^. AsParamAo E.&&. rs E.^. AsParamAa E.==. (E.valkey 1) ) return $ (o E.^. AsObjectN, rs E.^. AsParamAr, rh E.^. AsParamAr, s E.?. AsObjectN) getHypLog = E.select $ E.from $ \(o `E.InnerJoin` hyp) -> do E.on ( o E.^. AsObjectId E.==. hyp E.^. HypothesisHyp) return $ (o E.^. AsObjectN, hyp E.^. HypothesisIp) getKeys = fmap entityKey getNames = fmap getName getName = asObjectN . entityVal getRef = safeFromJust (toSqlKey 0) . asParamAr . entityVal showPrices = fmap cell2Table . groupBy compSnd . sortBy (compare `on` (snd)) . fmap showPrice where compSnd a b = snd a == snd b showPrice (p, rs, rh, s) = (Price' (parseDouble $ E.unValue p) (safeNum rs) (safeNum rh), safeText s) where safeNum = safeFromJust (toSqlKey 0) . E.unValue safeText = safeFromJust "" . E.unValue cell2Table :: [PriceCell] -> PriceRow cell2Table a = let b2 = head $ nub $ fmap snd a b1 = fmap fst a in (b1, b2) data Price' = Price' { val' :: Double , serv' :: AsObjectId , hyp' :: AsObjectId } type PriceRow = ([Price'], ServiceName) type PriceCell = (Price', ServiceName) type PriceTable = [PriceRow] type ServiceName = Text
swamp-agr/carbuyer-advisor
Handler/Service.hs
mit
3,030
0
16
672
1,091
567
524
-1
-1
{-# LANGUAGE OverloadedStrings #-} -- | Description : Easy IPython kernels = Overview This module provides automation for writing -- simple IPython kernels. In particular, it provides a record type that defines configurations and -- a function that interprets a configuration as an action in some monad that can do IO. -- -- The configuration consists primarily of functions that implement the various features of a -- kernel, such as running code, looking up documentation, and performing completion. An example for -- a simple language that nevertheless has side effects, global state, and timing effects is -- included in the examples directory. -- -- = Profiles To run your kernel, you will need an IPython profile that causes the frontend to run -- it. To generate a fresh profile, run the command -- -- > ipython profile create NAME -- -- This will create a fresh IPython profile in @~\/.ipython\/profile_NAME@. This profile must be -- modified in two ways: -- -- 1. It needs to run your kernel instead of the default ipython 2. It must have message signing -- turned off, because 'easyKernel' doesn't support it -- -- == Setting the executable To set the executable, modify the configuration object's -- @KernelManager.kernel_cmd@ property. For example: -- -- > c.KernelManager.kernel_cmd = ['my_kernel', '{connection_file}'] -- -- Your own main should arrange to parse command line arguments such -- that the connection file is passed to easyKernel. -- -- == Message signing -- To turn off message signing, use the following snippet: -- -- > c.Session.key = b'' -- > c.Session.keyfile = b'' -- -- == Further profile improvements -- Consult the IPython documentation along with the generated profile -- source code for further configuration of the frontend, including -- syntax highlighting, logos, help text, and so forth. module IHaskell.IPython.EasyKernel (easyKernel, installProfile, KernelConfig(..)) where import Data.Aeson (decode) import qualified Data.ByteString.Lazy as BL import qualified Codec.Archive.Tar as Tar import Control.Concurrent (MVar, readChan, writeChan, newMVar, readMVar, modifyMVar_) import Control.Monad.IO.Class (MonadIO(..)) import Control.Monad (forever, when, unless) import qualified Data.Map as Map import Data.Maybe (fromMaybe) import qualified Data.Text as T import IHaskell.IPython.Kernel import IHaskell.IPython.Message.UUID as UUID import IHaskell.IPython.Types import System.Directory (createDirectoryIfMissing, doesDirectoryExist, doesFileExist, getHomeDirectory) import System.FilePath ((</>)) import System.Exit (exitSuccess) import System.IO (openFile, IOMode(ReadMode)) -- | The kernel configuration specifies the behavior that is specific to your language. The type -- parameters provide the monad in which your kernel will run, the type of intermediate outputs from -- running cells, and the type of final results of cells, respectively. data KernelConfig m output result = KernelConfig { -- | Info on the language of the kernel. kernelLanguageInfo :: LanguageInfo -- | Determine the source of a profile to install using 'installProfile'. The source should be a -- tarball whose contents will be unpacked directly into the profile directory. For example, the -- file whose name is @ipython_config.py@ in the tar file for a language named @lang@ will end up in -- @~/.ipython/profile_lang/ipython_config.py@. , profileSource :: IO (Maybe FilePath) -- | How to render intermediate output , displayOutput :: output -> [DisplayData] -- | How to render final cell results , displayResult :: result -> [DisplayData] -- | Perform completion. The returned tuple consists of the matches, the matched text, and the -- completion text. The arguments are the code in the cell, the current line as text, and the column -- at which the cursor is placed. , completion :: T.Text -> T.Text -> Int -> Maybe ([T.Text], T.Text, T.Text) -- | Return the information or documentation for its argument. The returned tuple consists of the -- name, the documentation, and the type, respectively. , inspectInfo :: T.Text -> Maybe (T.Text, T.Text, T.Text) -- | Execute a cell. The arguments are the contents of the cell, an IO action that will clear the -- current intermediate output, and an IO action that will add a new item to the intermediate -- output. The result consists of the actual result, the status to be sent to IPython, and the -- contents of the pager. Return the empty string to indicate that there is no pager output. Errors -- should be handled by defining an appropriate error constructor in your result type. , run :: T.Text -> IO () -> (output -> IO ()) -> m (result, ExecuteReplyStatus, String) , debug :: Bool -- ^ Whether to print extra debugging information to } -- the console | Attempt to install the IPython profile from the .tar file indicated by the -- 'profileSource' field of the configuration, if it is not already installed. installProfile :: MonadIO m => KernelConfig m output result -> m () installProfile config = do installed <- isInstalled unless installed $ do profSrc <- liftIO $ profileSource config case profSrc of Nothing -> liftIO (putStrLn "No IPython profile is installed or specified") Just tar -> do profExists <- liftIO $ doesFileExist tar profTgt <- profDir if profExists then do liftIO $ createDirectoryIfMissing True profTgt liftIO $ Tar.extract profTgt tar else liftIO . putStrLn $ "The supplied profile source '" ++ tar ++ "' does not exist" where profDir = do home <- liftIO getHomeDirectory return $ home </> ".ipython" </> ("profile_" ++ languageName (kernelLanguageInfo config)) isInstalled = do prof <- profDir dirThere <- liftIO $ doesDirectoryExist prof isProf <- liftIO . doesFileExist $ prof </> "ipython_config.py" return $ dirThere && isProf getProfile :: FilePath -> IO Profile getProfile fn = do profData <- openFile fn ReadMode >>= BL.hGetContents case decode profData of Just prof -> return prof Nothing -> error "Invalid profile data" createReplyHeader :: MonadIO m => MessageHeader -> m MessageHeader createReplyHeader parent = do -- Generate a new message UUID. newMessageId <- liftIO UUID.random let repType = fromMaybe err (replyType $ msgType parent) err = error $ "No reply for message " ++ show (msgType parent) return MessageHeader { identifiers = identifiers parent , parentHeader = Just parent , metadata = Map.fromList [] , messageId = newMessageId , sessionId = sessionId parent , username = username parent , msgType = repType } -- | Execute an IPython kernel for a config. Your 'main' action should call this as the last thing -- it does. easyKernel :: MonadIO m => FilePath -- ^ The connection file provided by the IPython frontend -> KernelConfig m output result -- ^ The kernel configuration specifying how to react to -- messages -> m () easyKernel profileFile config = do prof <- liftIO $ getProfile profileFile zmq@(Channels shellReqChan shellRepChan ctrlReqChan ctrlRepChan iopubChan _) <- liftIO $ serveProfile prof False execCount <- liftIO $ newMVar 0 forever $ do req <- liftIO $ readChan shellReqChan repHeader <- createReplyHeader (header req) when (debug config) . liftIO $ print req reply <- replyTo config execCount zmq req repHeader liftIO $ writeChan shellRepChan reply replyTo :: MonadIO m => KernelConfig m output result -> MVar Integer -> ZeroMQInterface -> Message -> MessageHeader -> m Message replyTo config _ _ KernelInfoRequest{} replyHeader = return KernelInfoReply { header = replyHeader , languageInfo = kernelLanguageInfo config , implementation = "ipython-kernel.EasyKernel" , implementationVersion = "0.0" } replyTo config _ interface ShutdownRequest { restartPending = pending } replyHeader = do liftIO $ writeChan (shellReplyChannel interface) $ ShutdownReply replyHeader pending liftIO exitSuccess replyTo config execCount interface req@ExecuteRequest { getCode = code } replyHeader = do let send = writeChan (iopubChannel interface) busyHeader <- dupHeader replyHeader StatusMessage liftIO . send $ PublishStatus busyHeader Busy outputHeader <- dupHeader replyHeader DisplayDataMessage (res, replyStatus, pagerOut) <- let clearOutput = do clearHeader <- dupHeader replyHeader ClearOutputMessage send $ ClearOutput clearHeader False sendOutput x = send $ PublishDisplayData outputHeader (languageName $ kernelLanguageInfo config) (displayOutput config x) in run config code clearOutput sendOutput liftIO . send $ PublishDisplayData outputHeader (languageName $ kernelLanguageInfo config) (displayResult config res) idleHeader <- dupHeader replyHeader StatusMessage liftIO . send $ PublishStatus idleHeader Idle liftIO $ modifyMVar_ execCount (return . (+ 1)) counter <- liftIO $ readMVar execCount return ExecuteReply { header = replyHeader , pagerOutput = [DisplayData PlainText $ T.pack pagerOut] , executionCounter = fromIntegral counter , status = replyStatus } replyTo config _ _ req@CompleteRequest{} replyHeader = -- TODO: FIX error "Completion: Unimplemented for IPython 3.0" replyTo _ _ _ InspectRequest{} _ = error "Inspection: Unimplemented for IPython 3.0" replyTo _ _ _ msg _ = do liftIO $ putStrLn "Unknown message: " liftIO $ print msg return msg dupHeader :: MonadIO m => MessageHeader -> MessageType -> m MessageHeader dupHeader hdr mtype = do uuid <- liftIO UUID.random return hdr { messageId = uuid, msgType = mtype }
wyager/IHaskell
ipython-kernel/src/IHaskell/IPython/EasyKernel.hs
mit
10,998
0
20
3,124
1,805
952
853
147
3
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE StrictData #-} {-# LANGUAGE TupleSections #-} -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-network-interface-privateipspec.html module Stratosphere.ResourceProperties.EC2NetworkInterfacePrivateIpAddressSpecification where import Stratosphere.ResourceImports -- | Full data type definition for -- EC2NetworkInterfacePrivateIpAddressSpecification. See -- 'ec2NetworkInterfacePrivateIpAddressSpecification' for a more convenient -- constructor. data EC2NetworkInterfacePrivateIpAddressSpecification = EC2NetworkInterfacePrivateIpAddressSpecification { _eC2NetworkInterfacePrivateIpAddressSpecificationPrimary :: Val Bool , _eC2NetworkInterfacePrivateIpAddressSpecificationPrivateIpAddress :: Val Text } deriving (Show, Eq) instance ToJSON EC2NetworkInterfacePrivateIpAddressSpecification where toJSON EC2NetworkInterfacePrivateIpAddressSpecification{..} = object $ catMaybes [ (Just . ("Primary",) . toJSON) _eC2NetworkInterfacePrivateIpAddressSpecificationPrimary , (Just . ("PrivateIpAddress",) . toJSON) _eC2NetworkInterfacePrivateIpAddressSpecificationPrivateIpAddress ] -- | Constructor for 'EC2NetworkInterfacePrivateIpAddressSpecification' -- containing required fields as arguments. ec2NetworkInterfacePrivateIpAddressSpecification :: Val Bool -- ^ 'ecnipiasPrimary' -> Val Text -- ^ 'ecnipiasPrivateIpAddress' -> EC2NetworkInterfacePrivateIpAddressSpecification ec2NetworkInterfacePrivateIpAddressSpecification primaryarg privateIpAddressarg = EC2NetworkInterfacePrivateIpAddressSpecification { _eC2NetworkInterfacePrivateIpAddressSpecificationPrimary = primaryarg , _eC2NetworkInterfacePrivateIpAddressSpecificationPrivateIpAddress = privateIpAddressarg } -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-network-interface-privateipspec.html#cfn-ec2-networkinterface-privateipspecification-primary ecnipiasPrimary :: Lens' EC2NetworkInterfacePrivateIpAddressSpecification (Val Bool) ecnipiasPrimary = lens _eC2NetworkInterfacePrivateIpAddressSpecificationPrimary (\s a -> s { _eC2NetworkInterfacePrivateIpAddressSpecificationPrimary = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-network-interface-privateipspec.html#cfn-ec2-networkinterface-privateipspecification-privateipaddress ecnipiasPrivateIpAddress :: Lens' EC2NetworkInterfacePrivateIpAddressSpecification (Val Text) ecnipiasPrivateIpAddress = lens _eC2NetworkInterfacePrivateIpAddressSpecificationPrivateIpAddress (\s a -> s { _eC2NetworkInterfacePrivateIpAddressSpecificationPrivateIpAddress = a })
frontrowed/stratosphere
library-gen/Stratosphere/ResourceProperties/EC2NetworkInterfacePrivateIpAddressSpecification.hs
mit
2,725
0
13
222
267
153
114
29
1
{-# language OverloadedStrings #-} module Scorer.Einsendung ( Einsendung (..), size , Scorer.Einsendung.okay, Scorer.Einsendung.traditional , Obfuscated (..) , SE (..) , slurp_deco -- datei-inhalt verarbeiten ) where {- so sehen die dinger aus: (3: VNR, 11: ANr) Fri Nov 28 18:33:49 CET 2003 ( 2425 ) cgi-318 ( 318 ) 3-11 : OK # Size: 7 -- oder auch (siehe http://nfa.imn.htwk-leipzig.de/bugzilla/show_bug.cgi?id=365) Fri Nov 14 13:43:49 CET 2014 ( 19549 ) cgi- ( ) 212-2199 : NO Fri Nov 14 13:44:10 CET 2014 ( 19557 ) cgi- ( ) 212-2199 : OK # Size: 3 -- oder jetzt so (Snr statt Mnr) Mon Jan 4 22:12:59 CET 2016 ( 17065 ) snr-3038 ( 3038 ) 229-2397 : OK # Size: 250 Punkte: 1 -} import Scorer.Util hiding ( size ) import Autolib.FiniteMap import Control.Monad ( guard ) import Data.Maybe ( isJust ) import Data.Either ( isLeft ) -- import Text.Parsec -- import Text.Parsec.String -- import Text.Parsec.Char -- import qualified Text.Parsec.Token as P -- import Text.Parsec.Language (emptyDef) import qualified Data.Attoparsec.ByteString.Char8 as A import qualified Data.ByteString as BS import Control.Applicative ((<$>), (<*>), (<*), (*>) ) import Data.List (intersperse) -- | das ist die information zu jeweils einer studentischen einsendung data Einsendung = Einsendung { msize :: ! (Maybe Int) , date :: ! [Int] , time :: ! String -- ^ original time entry , matrikel :: ! (Either (Obfuscated MNr) (Obfuscated SNr)) -- ^ Datenschutz , auf :: ! ANr , vor :: ! VNr , pid :: ! String , visible :: ! Bool -- tutor submissions should be invisible } deriving (Eq,Ord) size e = case msize e of Nothing -> error "size" Just s -> s okay :: Einsendung -> Bool okay = isJust . msize traditional :: Einsendung -> Bool traditional = isLeft . matrikel data Obfuscated a = Obfuscated { internal :: ! a , external :: ! String } deriving ( Eq, Ord, Show ) -- nobfuscate :: MNr -> Obfuscated MNr nobfuscate mnr = Obfuscated { internal = mnr, external = toString mnr } -- obfuscate :: MNr -> Obfuscated MNr obfuscate mnr = Obfuscated { internal = mnr , external = do let cs = toString mnr ( k, c, s ) <- zip3 ( reverse $ take ( length cs ) [ 0 :: Int .. ] ) cs $ repeat '*' return $ if 0 == k `mod` 3 then s else c } instance ToString ( Obfuscated a ) where toString = external data SE = SE !SNr !Einsendung instance Show SE where show ( SE s i ) = unwords [ spaci 10 $ show $ abs $ size i , spaci 12 $ toString s , (nulli 2 $ date i !! 2) ++ "." ++ (nulli 2 $ (date i) !! 1) ++ "." ++ (nulli 4 $ (date i) !! 0) , (nulli 2 $ (date i) !! 3) ++ ":" ++ (nulli 2 $ (date i) !! 4) ++ ":" ++ (nulli 2 $ (date i) !! 5) ] instance Show Einsendung where show i = unwords [ spaci 10 $ show $ abs $ size i , spaci 12 $ case matrikel i of Left mnr -> toString mnr Right snr -> toString snr , (nulli 2 $ date i !! 2) ++ "." ++ (nulli 2 $ (date i) !! 1) ++ "." ++ (nulli 4 $ (date i) !! 0) , (nulli 2 $ (date i) !! 3) ++ ":" ++ (nulli 2 $ (date i) !! 4) ++ ":" ++ (nulli 2 $ (date i) !! 5) ] spaci :: Int -> String -> String spaci n = stretch n nulli :: Show a => Int -> a -> String nulli n = stretchWith '0' n . show {- slurp_deco :: Bool -> String -> [ Einsendung ] slurp_deco deco cs = do z <- lines cs case parse (entry deco) "<>" z of Right e -> return e Left err -> fail "no parse" -} slurp_deco deco = A.many' ( entry deco ) {- Fri Nov 28 18:33:49 CET 2003 ( 2425 ) cgi-318 ( 318 ) 3-11 : OK # Size: 7 Fri Nov 14 13:43:49 CET 2014 ( 19549 ) cgi- ( ) 212-2199 : NO Fri Nov 14 13:44:10 CET 2014 ( 19557 ) cgi- ( ) 212-2199 : OK # Size: 3 -} test1, test2, test3, test4 :: BS.ByteString test1 = "Fri Nov 28 18:33:49 CET 2003 ( 2425 ) cgi-318 ( 318 ) 3-11 : OK # Size: 7" test2 = "Fri Nov 14 13:43:49 CET 2014 ( 19549 ) cgi- ( ) 212-2199 : NO" test3 = "Fri Nov 14 13:44:10 CET 2014 ( 19557 ) cgi- ( ) 212-2199 : OK # Size: 3" test4 = "Mon Jan 4 22:12:59 CET 2016 ( 17065 ) snr-3038 ( 3038 ) 229-2397 : OK # Size: 250 Punkte: 1" author = do A.string "cgi-"; matrikelnr ; mnr <- parens $ matrikelnr ; return $ Left mnr <|> do A.string "snr-"; natural ; snr <- parens $ natural ; return $ Right $ SNr snr entry :: Bool -> A.Parser Einsendung entry deco = do weekday <- identifier month <- identifier date <- natural h <- natural ; A.char ':' m <- natural ; A.char ':' s <- natural tz <- identifier year <- natural p <- parens $ natural au <- author v <- natural ; A.string "-" a <- natural ; reserved ":" res <- do reserved "NO" ; return Nothing <|> do reserved "OK" ; reserved "#" reserved "Size" ; reserved ":" ; s <- natural reserved "Punkte" ; reserved ":" ; p <- natural return $ Just s A.endOfLine let obf x = if deco then obfuscate x else nobfuscate x return $ Einsendung { time = concat $ intersperse ":" $ map show [ h,m,s] , date = [ year, monthNum month, date , h, m, s ] , msize = res , matrikel = case au of Left mnr -> Left $ obf mnr Right snr -> Right $ obf snr , auf = fromCGI $ show a , vor = fromCGI $ show v , pid = show p , visible = False } matrikelnr = do s <- A.option "0" $ A.many1' $ A.digit <|> A.char ',' spaces return $ fromCGI s spaces = A.many' $ A.char ' ' identifier = A.many1' (A.satisfy A.isAlpha_ascii) <* spaces reserved s = A.string s <* spaces natural = A.decimal <* spaces parens p = reserved "(" *> p <* reserved ")" p <|> q = A.choice [p,q] {- OBSOLETE ? -- instance Read Einsendung where -- readsPrec p cs = do read_deco deco cs = do let ( line, rest ) = span (/= '\n') cs let field n = head . drop (n-1) mySub x | x == ':' = ' ' | otherwise = x wl = words line line' = dropWhile (/=")") wl date' = takeWhile (/="(") wl aufg = field 6 line' ( v , '-' : a ) = span (/= '-') aufg ok = field 8 line' -- guard $ ok == "OK" let e = Einsendung { time = unwords $ take 6 wl , date = [ read $ field 6 date' -- Jahr , monthNum $ field 2 date' -- Monat , read $ field 3 date' -- Tag ] ++ -- St:Mi:Se [ read x | x <- words $ map mySub (field 4 date') ] , msize = if ok == "OK" then Just $ read $ field 11 line' else Nothing , matrikel = ( if deco then obfuscate else nobfuscate ) $ fromCGI $ field 4 line' , auf = fromCGI a , vor = fromCGI v , pid = field 8 wl -- process id , visible = False } return ( e, rest ) -} ------------------------------------------------------------------------------- -- | komisch, aber ich habs nirgendwo gefunden monthFM :: FiniteMap String Int monthFM = listToFM [ ("Jan", 1),("Feb", 2),("Mar", 3),("Apr", 4) , ("May", 5),("Jun", 6),("Jul", 7),("Aug", 8) , ("Sep", 9),("Oct",10),("Nov",11),("Dec",12) ] -- | Umwandlung Monat-KΓΌrzel -> Zahl, bei Fehler kommt 13 zurΓΌck monthNum m = lookupWithDefaultFM monthFM 13 m
marcellussiegburg/autotool
db/src/Scorer/Einsendung.hs
gpl-2.0
7,879
38
16
2,689
1,950
1,032
918
157
3
{-# LANGUAGE ScopedTypeVariables, OverloadedStrings, LambdaCase #-} ----------------------------------------------------------------------------- -- -- Module : IDE.Completion -- Copyright : 2007-2011 Juergen Nicklisch-Franken, Hamish Mackenzie -- License : GPL -- -- Maintainer : <[email protected]> -- Stability : provisional -- Portability : -- -- | -- ----------------------------------------------------------------------------- module IDE.Completion (complete, cancel, setCompletionSize) where import Prelude hiding(getChar, getLine) import Data.List as List (stripPrefix, isPrefixOf, filter) import Data.Char import Data.IORef import Control.Monad import Graphics.UI.Gtk as Gtk import Graphics.UI.Gtk.Gdk.EventM as Gtk import IDE.Core.State import IDE.Metainfo.Provider(getDescription,getCompletionOptions) import IDE.TextEditor as TE import Control.Monad.IO.Class (MonadIO(..)) import Control.Monad.Trans.Reader (ask) import qualified Control.Monad.Reader as Gtk (liftIO) import Control.Monad.Trans.Class (MonadTrans(..)) import Control.Applicative ((<$>)) import IDE.Utils.GUIUtils (getDarkState) import Data.Text (Text) import qualified Data.Text as T (empty, commonPrefixes, pack, unpack, null, stripPrefix, isPrefixOf) import System.Log.Logger (debugM) complete :: TextEditor editor => EditorView editor -> Bool -> IDEAction complete sourceView always = do currentState' <- readIDE currentState prefs' <- readIDE prefs (_, completion') <- readIDE completion case (currentState',completion') of (IsCompleting c, Just (CompletionWindow window tv st)) -> do isWordChar <- getIsWordChar sourceView updateOptions window tv st sourceView c isWordChar always (IsRunning,_) -> when (always || not (completeRestricted prefs')) (initCompletion sourceView always) _ -> return () cancel :: IDEAction cancel = do currentState' <- readIDE currentState (_, completion') <- readIDE completion case (currentState',completion') of (IsCompleting conn , Just (CompletionWindow window tv st)) -> cancelCompletion window tv st conn _ -> return () setCompletionSize :: (Int, Int) -> IDEAction setCompletionSize (x, y) | x > 10 && y > 10 = do (_, completion) <- readIDE completion case completion of Just (CompletionWindow window _ _) -> liftIO $ windowResize window x y Nothing -> return () modifyIDE_ $ \ide -> ide{completion = ((x, y), completion)} setCompletionSize _ = return () getIsWordChar :: forall editor. TextEditor editor => EditorView editor -> IDEM (Char -> Bool) getIsWordChar sourceView = do ideR <- ask buffer <- getBuffer sourceView (_, end) <- getSelectionBounds buffer sol <- backwardToLineStartC end eol <- forwardToLineEndC end line <- getSlice buffer sol eol False let isImport = "import " `T.isPrefixOf` line isIdent a = isAlphaNum a || a == '\'' || a == '_' || (isImport && a == '.') isOp a = isSymbol a || a == ':' || a == '\\' || a == '*' || a == '/' || a == '-' || a == '!' || a == '@' || a == '%' || a == '&' || a == '?' prev <- backwardCharC end prevChar <- getChar prev case prevChar of Just prevChar | isIdent prevChar -> return isIdent Just prevChar | isOp prevChar -> return isOp _ -> return $ const False initCompletion :: forall editor. TextEditor editor => EditorView editor -> Bool -> IDEAction initCompletion sourceView always = do ideR <- ask ((width, height), completion') <- readIDE completion isWordChar <- getIsWordChar sourceView case completion' of Just (CompletionWindow window' tree' store') -> do cids <- addEventHandling window' sourceView tree' store' isWordChar always modifyIDE_ (\ide -> ide{currentState = IsCompleting cids}) updateOptions window' tree' store' sourceView cids isWordChar always Nothing -> do windows <- getWindows prefs <- readIDE prefs window <- liftIO windowNewPopup liftIO $ set window [ windowTypeHint := WindowTypeHintUtility, windowDecorated := False, windowResizable := True, windowDefaultWidth := width, windowDefaultHeight := height, windowTransientFor := head windows] liftIO $ containerSetBorderWidth window 3 paned <- liftIO hPanedNew liftIO $ containerAdd window paned nameScrolledWindow <- liftIO $ scrolledWindowNew Nothing Nothing liftIO $ widgetSetSizeRequest nameScrolledWindow 250 40 tree <- liftIO treeViewNew liftIO $ containerAdd nameScrolledWindow tree store <- liftIO $ listStoreNew [] liftIO $ treeViewSetModel tree store font <- liftIO $ case textviewFont prefs of Just str -> fontDescriptionFromString str Nothing -> do f <- fontDescriptionNew fontDescriptionSetFamily f ("Monospace" :: Text) return f liftIO $ widgetModifyFont tree (Just font) column <- liftIO treeViewColumnNew liftIO $ set column [ treeViewColumnSizing := TreeViewColumnFixed, treeViewColumnMinWidth := 800] -- OSX does not like it if there is no hscroll liftIO $ treeViewAppendColumn tree column renderer <- liftIO cellRendererTextNew liftIO $ treeViewColumnPackStart column renderer True liftIO $ cellLayoutSetAttributes column renderer store (\name -> [ cellText := name ]) liftIO $ set tree [treeViewHeadersVisible := False] descriptionBuffer <- newDefaultBuffer Nothing "" descriptionView <- newView descriptionBuffer (textviewFont prefs) updateStyle descriptionBuffer descriptionScrolledWindow <- getScrolledWindow descriptionView visible <- liftIO $ newIORef False activeView <- liftIO $ newIORef Nothing treeSelection <- liftIO $ treeViewGetSelection tree liftIO $ on treeSelection treeSelectionSelectionChanged $ treeSelectionSelectedForeach treeSelection $ \treePath -> do rows <- treeSelectionGetSelectedRows treeSelection case rows of [treePath] -> reflectIDE (withWord store treePath (\name -> do description <- getDescription name setText descriptionBuffer description )) ideR _ -> return () liftIO $ panedAdd1 paned nameScrolledWindow liftIO $ panedAdd2 paned descriptionScrolledWindow cids <- addEventHandling window sourceView tree store isWordChar always modifyIDE_ (\ide -> ide{currentState = IsCompleting cids, completion = ((width, height), Just (CompletionWindow window tree store))}) updateOptions window tree store sourceView cids isWordChar always addEventHandling :: TextEditor editor => Window -> EditorView editor -> TreeView -> ListStore Text -> (Char -> Bool) -> Bool -> IDEM Connections addEventHandling window sourceView tree store isWordChar always = do ideR <- ask cidsPress <- TE.onKeyPress sourceView $ do keyVal <- lift eventKeyVal name <- lift eventKeyName modifier <- lift eventModifier char <- liftIO $ keyvalToChar keyVal Just model <- liftIO $ treeViewGetModel tree selection <- liftIO $ treeViewGetSelection tree count <- liftIO $ treeModelIterNChildren model Nothing Just column <- liftIO $ treeViewGetColumn tree 0 let whenVisible f = liftIO (get tree widgetVisible) >>= \case True -> f False -> return False down = whenVisible $ do maybeRow <- liftIO $ getRow tree let newRow = maybe 0 (+ 1) maybeRow when (newRow < count) . liftIO $ do treeSelectionSelectPath selection [newRow] treeViewScrollToCell tree (Just [newRow]) Nothing Nothing return True up = whenVisible $ do maybeRow <- liftIO $ getRow tree let newRow = maybe 0 (\ row -> row - 1) maybeRow when (newRow >= 0) . liftIO $ do treeSelectionSelectPath selection [newRow] treeViewScrollToCell tree (Just [newRow]) Nothing Nothing return True case (name, modifier, char) of ("Tab", _, _) -> whenVisible . liftIDE $ do tryToUpdateOptions window tree store sourceView True isWordChar always return True ("Return", _, _) -> whenVisible $ do maybeRow <- liftIO $ getRow tree case maybeRow of Just row -> do liftIO $ treeViewRowActivated tree [row] column return True Nothing -> do liftIDE cancel return False ("Down", _, _) -> down ("Up", _, _) -> up (super, _, Just 'a') | super `elem` ["Super_L", "Super_R"] -> do liftIO $ debugM "leksah" "Completion - Super 'a' key press" down (super, _, Just 'l') | super `elem` ["Super_L", "Super_R"] -> do liftIO $ debugM "leksah" "Completion - Super 'l' key press" up (_, _, Just c) | isWordChar c -> return False ("BackSpace", _, _) -> return False (key, _, _) | key `elem` ["Shift_L", "Shift_R", "Super_L", "Super_R"] -> return False _ -> do liftIDE cancel return False cidsRelease <- TE.onKeyRelease sourceView $ do name <- lift eventKeyName modifier <- lift eventModifier case (name, modifier) of ("BackSpace", _) -> do liftIDE $ complete sourceView False return False _ -> return False liftIO $ do resizeHandler <- newIORef Nothing idButtonPress <- window `on` buttonPressEvent $ do button <- eventButton (x, y) <- eventCoordinates time <- eventTime mbDrawWindow <- Gtk.liftIO $ widgetGetWindow window case mbDrawWindow of Just drawWindow -> do status <- Gtk.liftIO $ pointerGrab drawWindow False [PointerMotionMask, ButtonReleaseMask] (Nothing:: Maybe DrawWindow) Nothing time when (status == GrabSuccess) $ Gtk.liftIO $ do (width, height) <- windowGetSize window writeIORef resizeHandler $ Just $ \(newX, newY) -> reflectIDE ( setCompletionSize (width + floor (newX - x), height + floor (newY - y))) ideR Nothing -> return () return True idMotion <- window `on` motionNotifyEvent $ do mbResize <- Gtk.liftIO $ readIORef resizeHandler case mbResize of Just resize -> eventCoordinates >>= (Gtk.liftIO . resize) >> return True Nothing -> return False idButtonRelease <- window `on` buttonReleaseEvent $ do mbResize <- Gtk.liftIO $ readIORef resizeHandler case mbResize of Just resize -> do eventCoordinates >>= (Gtk.liftIO . resize) eventTime >>= (Gtk.liftIO . pointerUngrab) Gtk.liftIO $ writeIORef resizeHandler Nothing return True Nothing -> return False idSelected <- on tree rowActivated $ \treePath column -> do reflectIDE (withWord store treePath (replaceWordStart sourceView isWordChar)) ideR liftIO $ postGUIAsync $ reflectIDE cancel ideR return $ concat [cidsPress, cidsRelease, [ConnectC idButtonPress, ConnectC idMotion, ConnectC idButtonRelease, ConnectC idSelected]] withWord :: ListStore Text -> TreePath -> (Text -> IDEM ()) -> IDEM () withWord store treePath f = case treePath of [row] -> do value <- liftIO $ listStoreGetValue store row f value _ -> return () replaceWordStart :: TextEditor editor => EditorView editor -> (Char -> Bool) -> Text -> IDEM () replaceWordStart sourceView isWordChar name = do buffer <- getBuffer sourceView (selStart, selEnd) <- getSelectionBounds buffer start <- findWordStart selStart isWordChar wordStart <- getText buffer start selEnd True case T.stripPrefix wordStart name of Just extra -> do end <- findWordEnd selEnd isWordChar wordFinish <- getText buffer selEnd end True case T.stripPrefix wordFinish extra of Just extra2 | not (T.null wordFinish) -> do selectRange buffer end end insert buffer end extra2 _ -> insert buffer selEnd extra Nothing -> return () cancelCompletion :: Window -> TreeView -> ListStore Text -> Connections -> IDEAction cancelCompletion window tree store connections = do liftIO (do listStoreClear (store :: ListStore Text) signalDisconnectAll connections widgetHide window ) modifyIDE_ (\ide -> ide{currentState = IsRunning}) updateOptions :: forall editor. TextEditor editor => Window -> TreeView -> ListStore Text -> EditorView editor -> Connections -> (Char -> Bool) -> Bool -> IDEAction updateOptions window tree store sourceView connections isWordChar always = do result <- tryToUpdateOptions window tree store sourceView False isWordChar always unless result $ cancelCompletion window tree store connections tryToUpdateOptions :: TextEditor editor => Window -> TreeView -> ListStore Text -> EditorView editor -> Bool -> (Char -> Bool) -> Bool -> IDEM Bool tryToUpdateOptions window tree store sourceView selectLCP isWordChar always = do ideR <- ask liftIO $ listStoreClear (store :: ListStore Text) buffer <- getBuffer sourceView (selStart, end) <- getSelectionBounds buffer start <- findWordStart selStart isWordChar equal <- iterEqual start end if equal then return False else do wordStart <- getText buffer start end True liftIO $ do -- dont use postGUIAsync - it causes bugs related to several repeated tryToUpdateOptions in thread reflectIDE (do options <- getCompletionOptions wordStart processResults window tree store sourceView wordStart options selectLCP isWordChar always) ideR return () return True findWordStart :: TextEditor editor => EditorIter editor -> (Char -> Bool) -> IDEM (EditorIter editor) findWordStart iter isWordChar = do maybeWS <- backwardFindCharC iter (not . isWordChar) Nothing case maybeWS of Nothing -> atOffset iter 0 Just ws -> forwardCharC ws findWordEnd :: TextEditor editor => EditorIter editor -> (Char -> Bool) -> IDEM (EditorIter editor) findWordEnd iter isWordChar = do maybeWE <- forwardFindCharC iter (not . isWordChar) Nothing case maybeWE of Nothing -> forwardToLineEndC iter Just we -> return we longestCommonPrefix a b = case T.commonPrefixes a b of Nothing -> T.empty Just (p, _, _) -> p processResults :: TextEditor editor => Window -> TreeView -> ListStore Text -> EditorView editor -> Text -> [Text] -> Bool -> (Char -> Bool) -> Bool -> IDEAction processResults window tree store sourceView wordStart options selectLCP isWordChar always = case options of [] -> cancel _ | not always && (not . null $ drop 200 options) -> cancel _ -> do buffer <- getBuffer sourceView (selStart, end) <- getSelectionBounds buffer start <- findWordStart selStart isWordChar currentWordStart <- getText buffer start end True let newWordStart = if selectLCP && currentWordStart == wordStart && not (null options) then foldl1 longestCommonPrefix options else currentWordStart when (T.isPrefixOf wordStart newWordStart) $ do liftIO $ listStoreClear store let newOptions = List.filter (T.isPrefixOf newWordStart) options liftIO $ forM_ (take 200 newOptions) (listStoreAppend store) Rectangle startx starty width height <- getIterLocation sourceView start (wWindow, hWindow) <- liftIO $ windowGetSize window (x, y) <- bufferToWindowCoords sourceView (startx, starty+height) mbDrawWindow <- getWindow sourceView case mbDrawWindow of Nothing -> return () Just drawWindow -> do (ox, oy) <- liftIO $ drawWindowGetOrigin drawWindow Just namesSW <- liftIO $ widgetGetParent tree (Rectangle _ _ wNames hNames) <- liftIO $ widgetGetAllocation namesSW Just paned <- liftIO $ widgetGetParent namesSW Just first <- liftIO $ panedGetChild1 (castToPaned paned) Just second <- liftIO $ panedGetChild2 (castToPaned paned) screen <- liftIO $ windowGetScreen window monitor <- liftIO $ screenGetMonitorAtPoint screen (ox+x) (oy+y) monitorLeft <- liftIO $ screenGetMonitorAtPoint screen (ox+x-wWindow+wNames) (oy+y) monitorRight <- liftIO $ screenGetMonitorAtPoint screen (ox+x+wWindow) (oy+y) monitorBelow <- liftIO $ screenGetMonitorAtPoint screen (ox+x) (oy+y+hWindow) wScreen <- liftIO $ screenGetWidth screen hScreen <- liftIO $ screenGetHeight screen top <- if monitorBelow /= monitor || (oy+y+hWindow) > hScreen then do sourceSW <- getScrolledWindow sourceView (Rectangle _ _ _ hSource) <- liftIO $ widgetGetAllocation sourceSW scrollToIter sourceView end 0.1 (Just (1.0, 1.0 - (fromIntegral hWindow / fromIntegral hSource))) (_, newy) <- bufferToWindowCoords sourceView (startx, starty+height) return (oy+newy) else return (oy+y) swap <- if (monitorRight /= monitor || (ox+x+wWindow) > wScreen) && monitorLeft == monitor && (ox+x-wWindow+wNames) > 0 then do liftIO $ windowMove window (ox+x-wWindow+wNames) top return $ first == namesSW else do liftIO $ windowMove window (ox+x) top return $ first /= namesSW when swap $ liftIO $ do pos <- panedGetPosition (castToPaned paned) containerRemove (castToPaned paned) first containerRemove (castToPaned paned) second panedAdd1 (castToPaned paned) second panedAdd2 (castToPaned paned) first panedSetPosition (castToPaned paned) (wWindow-pos) unless (null newOptions) $ liftIO $ treeViewSetCursor tree [0] Nothing liftIO $ widgetShowAll window when (newWordStart /= currentWordStart) $ replaceWordStart sourceView isWordChar newWordStart getRow tree = do Just model <- treeViewGetModel tree selection <- treeViewGetSelection tree maybeIter <- treeSelectionGetSelected selection case maybeIter of Just iter -> do [row] <- treeModelGetPath model iter return $ Just row Nothing -> return Nothing
cocreature/leksah
src/IDE/Completion.hs
gpl-2.0
21,434
17
31
7,639
5,656
2,749
2,907
382
16
{-# LANGUAGE OverloadedStrings #-} -- Copyright (C) 2009-2012 John Millikin <[email protected]> -- -- 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 -- 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 <http://www.gnu.org/licenses/>. module DBus.Introspection ( -- * XML conversion parseXML , formatXML -- * Objects , Object , object , objectPath , objectInterfaces , objectChildren -- * Interfaces , Interface , interface , interfaceName , interfaceMethods , interfaceSignals , interfaceProperties -- * Methods , Method , method , methodName , methodArgs -- ** Method arguments , MethodArg , methodArg , methodArgName , methodArgType , methodArgDirection , Direction , directionIn , directionOut -- * Signals , Signal , signal , signalName , signalArgs -- ** Signal arguments , SignalArg , signalArg , signalArgName , signalArgType -- * Properties , Property , property , propertyName , propertyType , propertyRead , propertyWrite ) where import Control.Monad ((>=>)) import Control.Monad.ST (runST) import Data.List (isPrefixOf) import qualified Data.STRef as ST import qualified Data.Text import Data.Text (Text) import qualified Data.Text.Encoding import qualified Data.XML.Types as X import qualified Text.XML.LibXML.SAX as SAX import qualified DBus as T data Object = Object { objectPath :: T.ObjectPath , objectInterfaces :: [Interface] , objectChildren :: [Object] } deriving (Show, Eq) object :: T.ObjectPath -> Object object path = Object path [] [] data Interface = Interface { interfaceName :: T.InterfaceName , interfaceMethods :: [Method] , interfaceSignals :: [Signal] , interfaceProperties :: [Property] } deriving (Show, Eq) interface :: T.InterfaceName -> Interface interface name = Interface name [] [] [] data Method = Method { methodName :: T.MemberName , methodArgs :: [MethodArg] } deriving (Show, Eq) method :: T.MemberName -> Method method name = Method name [] data MethodArg = MethodArg { methodArgName :: String , methodArgType :: T.Type , methodArgDirection :: Direction } deriving (Show, Eq) methodArg :: String -> T.Type -> Direction -> MethodArg methodArg = MethodArg data Direction = In | Out deriving (Show, Eq) directionIn :: Direction directionIn = In directionOut :: Direction directionOut = Out data Signal = Signal { signalName :: T.MemberName , signalArgs :: [SignalArg] } deriving (Show, Eq) signal :: T.MemberName -> Signal signal name = Signal name [] data SignalArg = SignalArg { signalArgName :: String , signalArgType :: T.Type } deriving (Show, Eq) signalArg :: String -> T.Type -> SignalArg signalArg = SignalArg data Property = Property { propertyName :: String , propertyType :: T.Type , propertyRead :: Bool , propertyWrite :: Bool } deriving (Show, Eq) property :: String -> T.Type -> Property property name t = Property name t False False parseXML :: T.ObjectPath -> String -> Maybe Object parseXML path xml = do root <- parseElement (Data.Text.pack xml) parseRoot path root parseElement :: Text -> Maybe X.Element parseElement xml = runST $ do stackRef <- ST.newSTRef [([], [])] let onError _ = do ST.writeSTRef stackRef [] return False let onBegin _ attrs = do ST.modifySTRef stackRef ((attrs, []):) return True let onEnd name = do stack <- ST.readSTRef stackRef let (attrs, children'):stack' = stack let e = X.Element name attrs (map X.NodeElement (reverse children')) let (pAttrs, pChildren):stack'' = stack' let parent = (pAttrs, e:pChildren) ST.writeSTRef stackRef (parent:stack'') return True p <- SAX.newParserST Nothing SAX.setCallback p SAX.parsedBeginElement onBegin SAX.setCallback p SAX.parsedEndElement onEnd SAX.setCallback p SAX.reportError onError SAX.parseBytes p (Data.Text.Encoding.encodeUtf8 xml) SAX.parseComplete p stack <- ST.readSTRef stackRef return $ case stack of [] -> Nothing (_, children'):_ -> Just (head children') parseRoot :: T.ObjectPath -> X.Element -> Maybe Object parseRoot defaultPath e = do path <- case X.attributeText "name" e of Nothing -> Just defaultPath Just x -> T.parseObjectPath (Data.Text.unpack x) parseObject path e parseChild :: T.ObjectPath -> X.Element -> Maybe Object parseChild parentPath e = do let parentPath' = case T.formatObjectPath parentPath of "/" -> "/" x -> x ++ "/" pathSegment <- X.attributeText "name" e path <- T.parseObjectPath (parentPath' ++ Data.Text.unpack pathSegment) parseObject path e parseObject :: T.ObjectPath -> X.Element -> Maybe Object parseObject path e | X.elementName e == "node" = do interfaces <- children parseInterface (X.isNamed "interface") e children' <- children (parseChild path) (X.isNamed "node") e return (Object path interfaces children') parseObject _ _ = Nothing parseInterface :: X.Element -> Maybe Interface parseInterface e = do name <- T.parseInterfaceName =<< attributeString "name" e methods <- children parseMethod (X.isNamed "method") e signals <- children parseSignal (X.isNamed "signal") e properties <- children parseProperty (X.isNamed "property") e return (Interface name methods signals properties) parseMethod :: X.Element -> Maybe Method parseMethod e = do name <- T.parseMemberName =<< attributeString "name" e args <- children parseMethodArg (isArg ["in", "out", ""]) e return (Method name args) parseSignal :: X.Element -> Maybe Signal parseSignal e = do name <- T.parseMemberName =<< attributeString "name" e args <- children parseSignalArg (isArg ["out", ""]) e return (Signal name args) parseType :: X.Element -> Maybe T.Type parseType e = do typeStr <- attributeString "type" e sig <- T.parseSignature typeStr case T.signatureTypes sig of [t] -> Just t _ -> Nothing parseMethodArg :: X.Element -> Maybe MethodArg parseMethodArg e = do t <- parseType e let dir = case getattr "direction" e of "out" -> Out _ -> In Just (MethodArg (getattr "name" e) t dir) parseSignalArg :: X.Element -> Maybe SignalArg parseSignalArg e = do t <- parseType e Just (SignalArg (getattr "name" e) t) isArg :: [String] -> X.Element -> [X.Element] isArg dirs = X.isNamed "arg" >=> checkDir where checkDir e = [e | getattr "direction" e `elem` dirs] parseProperty :: X.Element -> Maybe Property parseProperty e = do t <- parseType e (canRead, canWrite) <- case getattr "access" e of "" -> Just (False, False) "read" -> Just (True, False) "write" -> Just (False, True) "readwrite" -> Just (True, True) _ -> Nothing Just (Property (getattr "name" e) t canRead canWrite) getattr :: X.Name -> X.Element -> String getattr name e = maybe "" Data.Text.unpack (X.attributeText name e) children :: Monad m => (X.Element -> m b) -> (X.Element -> [X.Element]) -> X.Element -> m [b] children f p = mapM f . concatMap p . X.elementChildren newtype XmlWriter a = XmlWriter { runXmlWriter :: Maybe (a, String) } instance Monad XmlWriter where return a = XmlWriter $ Just (a, "") m >>= f = XmlWriter $ do (a, w) <- runXmlWriter m (b, w') <- runXmlWriter (f a) return (b, w ++ w') tell :: String -> XmlWriter () tell s = XmlWriter (Just ((), s)) formatXML :: Object -> Maybe String formatXML obj = do (_, xml) <- runXmlWriter (writeRoot obj) return xml writeRoot :: Object -> XmlWriter () writeRoot obj@(Object path _ _) = do tell "<!DOCTYPE node PUBLIC '-//freedesktop//DTD D-BUS Object Introspection 1.0//EN'" tell " 'http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd'>\n" writeObject (T.formatObjectPath path) obj writeChild :: T.ObjectPath -> Object -> XmlWriter () writeChild parentPath obj@(Object path _ _) = write where path' = T.formatObjectPath path parent' = T.formatObjectPath parentPath relpathM = if parent' `isPrefixOf` path' then Just $ if parent' == "/" then drop 1 path' else drop (length parent' + 1) path' else Nothing write = case relpathM of Just relpath -> writeObject relpath obj Nothing -> XmlWriter Nothing writeObject :: String -> Object -> XmlWriter () writeObject path (Object fullPath interfaces children') = writeElement "node" [("name", path)] $ do mapM_ writeInterface interfaces mapM_ (writeChild fullPath) children' writeInterface :: Interface -> XmlWriter () writeInterface (Interface name methods signals properties) = writeElement "interface" [("name", T.formatInterfaceName name)] $ do mapM_ writeMethod methods mapM_ writeSignal signals mapM_ writeProperty properties writeMethod :: Method -> XmlWriter () writeMethod (Method name args) = writeElement "method" [("name", T.formatMemberName name)] $ do mapM_ writeMethodArg args writeSignal :: Signal -> XmlWriter () writeSignal (Signal name args) = writeElement "signal" [("name", T.formatMemberName name)] $ do mapM_ writeSignalArg args formatType :: T.Type -> XmlWriter String formatType t = do sig <- case T.signature [t] of Just x -> return x Nothing -> XmlWriter Nothing return (T.formatSignature sig) writeMethodArg :: MethodArg -> XmlWriter () writeMethodArg (MethodArg name t dir) = do typeStr <- formatType t let dirAttr = case dir of In -> "in" Out -> "out" writeEmptyElement "arg" $ [ ("name", name) , ("type", typeStr) , ("direction", dirAttr) ] writeSignalArg :: SignalArg -> XmlWriter () writeSignalArg (SignalArg name t) = do typeStr <- formatType t writeEmptyElement "arg" $ [ ("name", name) , ("type", typeStr) ] writeProperty :: Property -> XmlWriter () writeProperty (Property name t canRead canWrite) = do typeStr <- formatType t let readS = if canRead then "read" else "" let writeS = if canWrite then "write" else "" writeEmptyElement "property" [ ("name", name) , ("type", typeStr) , ("access", readS ++ writeS) ] attributeString :: X.Name -> X.Element -> Maybe String attributeString name e = fmap Data.Text.unpack (X.attributeText name e) writeElement :: String -> [(String, String)] -> XmlWriter () -> XmlWriter () writeElement name attrs content = do tell "<" tell name mapM_ writeAttribute attrs tell ">" content tell "</" tell name tell ">" writeEmptyElement :: String -> [(String, String)] -> XmlWriter () writeEmptyElement name attrs = do tell "<" tell name mapM_ writeAttribute attrs tell "/>" writeAttribute :: (String, String) -> XmlWriter () writeAttribute (name, content) = do tell " " tell name tell "='" tell (escape content) tell "'" escape :: String -> String escape = concatMap $ \c -> case c of '&' -> "&amp;" '<' -> "&lt;" '>' -> "&gt;" '"' -> "&quot;" '\'' -> "&apos;" _ -> [c]
tmishima/haskell-dbus
lib/DBus/Introspection.hs
gpl-3.0
11,103
84
20
2,073
3,883
1,981
1,902
322
6
{-# OPTIONS_GHC -Wall #-} module Prover ( Formula (..) , Mapping , cnf , dnf , equivalent , eval , nnf , satisfiable , show , tautology , unsatisfiable , variables ) where import Prelude hiding (lookup) import Control.Monad (liftM2) import Data.Functor ((<$>)) import Data.Map (Map, lookup, fromList) import Data.Maybe (fromMaybe) import Data.List (nub, permutations) import Data.List.Split (splitEvery) import Test.QuickCheck type Mapping = Map Char Bool data Formula = Var Char | Not Formula | Formula :/\: Formula | Formula :\/: Formula | Formula :->: Formula | Formula :<->: Formula deriving (Eq) instance Show Formula where show (Var c) = show c show (Not c) = 'Β¬' : show c show (e1 :\/: e2) = show' e1 "∨" e2 show (e1 :/\: e2) = show' e1 "∧" e2 show (e1 :->: e2) = show' e1 "β†’" e2 show (e1 :<->: e2) = show' e1 "↔" e2 instance Arbitrary Formula where arbitrary = randomFormula randomFormula :: Gen Formula randomFormula = sized randomFormula' randomFormula' :: Int -> Gen Formula randomFormula' n | n > 0 = oneof [ randomVar , randomNot boundedFormula , randomBin boundedFormula ] | otherwise = randomVar where boundedFormula = randomFormula' (n `div` 4) randomNot :: Gen Formula -> Gen Formula randomNot e = Not <$> e randomBin :: Gen Formula -> Gen Formula randomBin e = oneof . map (\c -> liftM2 c e e) $ [(:/\:), (:\/:), (:->:), (:<->:)] randomVar :: Gen Formula randomVar = Var <$> arbitrary show' :: Formula -> String -> Formula -> String show' e1 s e2 = (show e1) ++ " " ++ s ++ " " ++ (show e2) -- Given a formula and a map, evaluates the truth value. -- Example: -- > eval ((Var 'j') :\/: (Var 'k')) (fromList [('j', True), ('k', False)]) -- True eval :: Formula -> Mapping -> Bool eval (Var v) vs = fromMaybe False (lookup v vs) eval (Not wff) vs = not $ eval wff vs eval (e1 :\/: e2) vs = eval e1 vs || eval e2 vs eval (e1 :/\: e2) vs = eval e1 vs && eval e2 vs eval (e1 :->: e2) vs = not (eval e1 vs) || eval e2 vs eval (e1 :<->: e2) vs = eval e1 vs == eval e2 vs -- Given a formula, return a list of all the variables. -- TODO Fix this to remove duplicates. variables :: Formula -> [Char] variables f = nub $ variables' f variables' :: Formula -> [Char] variables' (Var c) = [c] variables' (Not e) = variables' e variables' (e1 :\/: e2) = variables'' e1 e2 variables' (e1 :/\: e2) = variables'' e1 e2 variables' (e1 :->: e2) = variables'' e1 e2 variables' (e1 :<->: e2) = variables'' e1 e2 variables'' e1 e2 = variables' e1 ++ variables' e2 -- Generate all possible assignments of truth values to variable. -- (p.s. this function is a disgusting mess and exp time) assignments :: Formula -> [Mapping] assignments f = nub $ map fromList $ splitEvery (length vs) $ perms vs where vs = variables f half tf vz = zip (concat (permutations vz)) (cycle tf) perms vz = half [True, False] vz ++ half [False, True] vz tautology :: Formula -> Bool tautology f = and $ map (eval f) (assignments f) unsatisfiable :: Formula -> Bool unsatisfiable f = tautology $ Not f satisfiable :: Formula -> Bool satisfiable f = not $ unsatisfiable f -- Reduces a formula to negation normal form. -- A formula is in negation normal form when NOT is only applied to variables, -- and is otherwise a seqence of ANDs and ORs. nnf :: Formula -> Formula nnf (e1 :/\: e2) = (nnf e1) :/\: (nnf e2) nnf (e1 :\/: e2) = (nnf e1) :\/: (nnf e2) nnf (e1 :->: e2) = (nnf (Not e1)) :\/: (nnf e2) nnf (e1 :<->: e2) = ((nnf e1) :/\: (nnf e2)) :\/: ((nnf (Not e1)) :/\: (nnf (Not e2))) nnf (Not (Not e1)) = nnf e1 nnf (Not (e1 :/\: e2)) = (nnf (Not e1)) :\/: (nnf (Not e2)) nnf (Not (e1 :\/: e2)) = (nnf (Not e1)) :/\: (nnf (Not e2)) nnf (Not (e1 :->: e2)) = (nnf e1) :/\: (nnf (Not e2)) nnf (Not (e1 :<->: e2)) = ((nnf e1) :/\: (nnf (Not e2))) :\/: ((nnf (Not e1)) :/\: (nnf e2)) nnf f = f -- Reduces a formula to disjunctive normal form. -- A formula is in disjunction normal form when it's a disjunction of conjunctions -- or literals. -- For example: (a :/\: b) :\/: (b :/\: c) dnf :: Formula -> Formula dnf = dnf' . nnf where dnf' (e1 :/\: e2) = dist (dnf' e1) (dnf' e2) (:/\:) dnf' (e1 :\/: e2) = (dnf' e1) :\/: (dnf' e2) dnf' expr = expr -- Reduces a formula to conjunctive normal form. -- A formula is in conjunctive normal form when it's a conjunction of disjunctions. cnf :: Formula -> Formula cnf = cnf' . nnf where cnf' (e1 :/\: e2) = (cnf' e1) :/\: (cnf' e2) cnf' (e1 :\/: e2) = dist (cnf' e1) (cnf' e2) (:\/:) cnf' expr = expr -- Distributive law for propositional logic. dist :: Formula -> Formula -> (Formula -> Formula -> Formula) -> Formula dist (e1 :\/: e2) e3 op = (dist e1 e3 op) :\/: (dist e2 e3 op) dist e1 (e2 :\/: e3) op = (dist e1 e2 op) :\/: (dist e1 e3 op) dist (e1 :/\: e2) e3 op = (dist e1 e3 op) :/\: (dist e2 e3 op) dist e1 (e2 :/\: e3) op = (dist e1 e2 op) :/\: (dist e1 e3 op) dist e1 e2 op = op e1 e2 -- TODO: This doesn't handle the empty list. concatf :: [Formula] -> (Formula -> Formula -> Formula) -> Formula concatf [f] _ = f concatf (x:xs) op = x `op` (concatf xs op) conj :: [Formula] -> Formula conj f = concatf f (:/\:) disj :: [Formula] -> Formula disj f = concatf f (:\/:) iffj :: [Formula] -> Formula iffj f = concatf f (:<->:) equivalent' :: [Formula] -> Bool equivalent' f = tautology $ iffj f equivalent :: Formula -> Formula -> Bool equivalent f1 f2 = equivalent' [f1, f2]
robertseaton/fregerator
src/prover.hs
gpl-3.0
5,752
0
11
1,481
2,243
1,181
1,062
124
3
module Scanner ( scan ) where import Token import Data.Char -- |Converts a digit into an interger digit :: Char -> Int digit '1' = 1 digit '2' = 2 digit '3' = 3 digit '4' = 4 digit '5' = 5 digit '6' = 6 digit '7' = 7 digit '8' = 8 digit '9' = 9 digit _ = 0 -- |Parses a string converting it into a number num :: Int -> String -> (Int, String) num n (c : s) = if isDigit c then num (n * 10 + digitToInt c) s else (n, c : s) num n [] = (n, []) -- |Recognizes an identifier id :: String -> String -> (String, String) id i (c : s) = if isAlphaNum c then Scanner.id (i ++ [c]) s else (i, c : s) id i [] = (i, []) -- |Scans a string converting it to a list of tokens scan :: String -> [Token] scan [] = [] scan ('u':'n':'i':'t' : string) = UNIT : scan string scan ('t':'r':'u':'e' : string) = BOOL True : scan string scan ('f':'a':'l':'s':'e' : string) = BOOL False : scan string scan ('f':'n' : string) = FN : scan string scan ('.' : string) = DOT : scan string scan ('i':'f' : string) = IF : scan string scan ('t':'h':'e':'n' : string) = THEN : scan string scan ('e':'l':'s':'e' : string) = ELSE : scan string scan ('(' : string) = LPAR : scan string scan (')' : string) = RPAR : scan string scan ('+' : string) = PLUS : scan string scan ('-' : string) = MINUS : scan string scan ('<' : string) = Token.LT : scan string scan ('=' : string) = Token.EQ : scan string scan (' ' : string) = scan string scan (c : string) = if isDigit c then let (n, s) = num 0 (c : string) in NUM n : scan s else let (id, s) = Scanner.id "" (c : string) in ID id : scan s
marco-zanella/minilambda
src/Scanner.hs
gpl-3.0
1,637
0
12
432
840
433
407
52
2
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE FunctionalDependencies #-} -- | This module provides a set of indexed type classes (IxFunctor, IxApplicative, IxMonad, etc..) that correspond to existing type classes (Functor, Applicative, Monad, etc..) -- -- The intent of this module is to replace the use of non-indexed type classes with indexed type class. -- -- For that reason the indexed type classes expose functions that are named the same as the functions exposed by a corresponding non-indexed type class. -- -- There are two ways to use this module: -- -- @ -- import SessionTypes -- import qualified SessionTypes.Indexed as I -- -- prog = send 5 I.>> eps0 -- @ -- -- @ -- {-\# LANGUAGE RebindableSyntax \#-} -- import SessionTypes -- import SessionTypes.Indexed -- -- prog = do -- send 5 -- eps0 -- @ -- -- With `RebindableSyntax` we construct a custom do notation by rebinding (>>=) with (>>=) of `IxMonad`. -- Rebinding is not limited to only (>>=), but also all other functions in Prelude. -- -- We do not want to force importing Prelude if you use `RebindableSyntax`. -- Therefore this module also exports Prelude that hides functions already defined by -- the indexed type classes. module Control.SessionTypes.Indexed ( -- * Classes IxFunctor(..), IxApplicative(..), IxMonad(..), -- ** Transformers IxMonadT(..), IxMonadIxT(..), -- ** Mtl IxMonadReader(..), -- ** Exception IxMonadThrow(..), IxMonadCatch(..), IxMonadMask(..), -- ** MonadIO IxMonadIO(..), -- * Combinators ap, -- * Rebind ifThenElse, module PH, ) where import Control.Exception import Data.Kind (Type) import Prelude as PH hiding ((>>=),(>>), return, fail, fmap, pure, (<*>)) class IxFunctor (f :: p -> p -> Type -> Type) where fmap :: (a -> b) -> f j k a -> f j k b class IxFunctor f => IxApplicative (f :: p -> p -> Type -> Type) where pure :: a -> f i i a (<*>) :: f s r (a -> b) -> f r k a -> f s k b infixl 1 >>= infixl 1 >> class IxApplicative m => IxMonad (m :: p -> p -> Type -> Type) where (>>=) :: m s t a -> (a -> m t k b) -> m s k b (>>) :: m s t a -> m t k b -> m s k b return :: a -> m i i a fail :: String -> m i i a m1 >> m2 = m1 >>= \_ -> m2 fail = error -- | Type class for lifting monadic computations class IxMonad (t m) => IxMonadT t m where lift :: m a -> t m s s a -- | Type class for lifting indexed monadic computations class IxMonad (t m) => IxMonadIxT t m where ilift :: m s r a -> t m s r a -- | Type class representing the indexed monad reader class IxMonad m => IxMonadReader r m | m -> r where ask :: m s s r local :: (r -> r) -> m s t a -> m s t a reader :: (r -> a) -> m i i a -- | Type class for indexed monads in which exceptions may be thrown. class IxMonad m => IxMonadThrow m s where -- | Provide an `Exception` to be thrown throwM :: Exception e => e -> m s s a -- | Type class for indexed monads to allow catching of exceptions. class IxMonadThrow m s => IxMonadCatch m s where -- | Provide a handler to catch exceptions. catch :: Exception e => m s s a -> (e -> m s s a) -> m s s a -- | Type class for indexed monads that may mask asynchronous exceptions. class IxMonadCatch m s => IxMonadMask m s where -- | run an action that disables asynchronous exceptions. The provided function can be used to restore the occurrence of asynchronous exceptions. mask :: ((m s s b -> m s s b) -> m s s b) -> m s s b -- | Ensures that even interruptible functions may not raise asynchronous exceptions. uninterruptibleMask :: ((m s s b -> m s s b) -> m s s b) -> m s s b -- | Type class for indexed monads that may lift IO computations. class IxMonadIO m where liftIO :: IO a -> m s s a ifThenElse :: Bool -> t -> t -> t ifThenElse True b1 _ = b1 ifThenElse False _ b2 = b2 -- # Combinators ap :: IxMonad m => m s r (a -> b) -> m r k a -> m s k b ap f g = f >>= \f' -> g >>= \g' -> return (f' g')
Ferdinand-vW/sessiontypes
src/Control/SessionTypes/Indexed.hs
gpl-3.0
3,970
0
12
929
1,099
599
500
-1
-1
module Meetup (Schedule(..), Weekday(..), meetupDay) where import Data.Time data Schedule = First | Second | Third | Fourth | Fifth | Last | Teenth data Weekday = Monday | Tuesday | Wednesday | Thursday | Friday | Saturday | Sunday meetupDay :: Schedule -> Weekday -> Integer -> Int -> Day meetupDay nth dow year month = case nth of Teenth -> head possibleDows First -> head possibleDows Second -> possibleDows !! 1 Third -> possibleDows !! 2 Fourth -> possibleDows !! 3 Fifth -> possibleDows !! 4 Last -> last possibleDows where day' = toDayString dow dayRange = map (makeDate year month) (getRange nth) getRange Teenth = [13..19] getRange nth = [1..31] possibleDows = map utctDay $ filter ((==day') . formatTime defaultTimeLocale "%A") dayRange toDayString :: Weekday -> String toDayString Monday = "Monday" toDayString Tuesday = "Tuesday" toDayString Wednesday = "Wednesday" toDayString Thursday = "Thursday" toDayString Friday = "Friday" toDayString Saturday = "Saturday" toDayString Sunday = "Sunday" -- note that fromGregorian will return the last day in a month if you give it a -- number higher than the number of days in the month. This means we can throw -- 2015 2 31 at it and get back 28 Feb 2015 makeDate :: Integer -> Int -> Int -> UTCTime makeDate y m d = UTCTime (fromGregorian y m d) (fromIntegral $ 12 * 3600)
ciderpunx/exercismo
src/Meetup.hs
gpl-3.0
1,492
0
11
391
400
215
185
31
8
module Handler.RestaurantPageSpec (spec) where import TestImport spec :: Spec spec = withApp $ do describe "getRestaurantPageR" $ do error "Spec not implemented: getRestaurantPageR"
Lionex/s16_mangohacks
MIAMIB/test/Handler/RestaurantPageSpec.hs
gpl-3.0
198
0
11
39
44
23
21
6
1
module Gabriel.Utils( formatProcessName , readM , openFile , openFileM , putArray , getArray ) where import qualified System.Posix.Syslog as L import qualified System.IO as IO {- - The utils namespace should contain functions which serve a specific simple - purpose. -} formatProcessName :: [String] -> String -> String formatProcessName array delim = formatProcessName' array delim 0 where formatProcessName' :: [String] -> String -> Int -> String formatProcessName' [] _ _ = "" formatProcessName' [h] _ _ = h formatProcessName' (h:t) delim 2 = h ++ delim ++ ".." formatProcessName' (h:t) delim d = h ++ delim ++ (formatProcessName' t delim (d + 1)) {- - Read any Readable type in any Monad. - Return the default value @f unless a match can be found. -} readM :: (Read a) => String -> a -> a readM s f = do let m = [x | (x,_) <- reads s] case m of [x] -> x _ -> f {-Open a handle safely, logging errors and returning Nothing-} openFile :: String -> IO.IOMode -> String -> IO (Maybe IO.Handle) openFile name mode path = {- Open the handle, or Nothing if an exception is raised -} catch (do h <- IO.openFile path mode return $ Just h) (\e -> do L.syslog L.Error $ "Failed to open handle '" ++ name ++ "'" return Nothing) openFileM :: String -> IO.IOMode -> Maybe String -> IO (Maybe IO.Handle) openFileM name mode Nothing = do L.syslog L.Error $ "Failed to open handle '" ++ name ++ "' (Nothing)" return Nothing openFileM name mode (Just path) = openFile name mode path putArray :: String -> Maybe String -> [String] -> IO () putArray name path array = do handle <- openFileM "command" IO.WriteMode path case handle of Just h -> do coerce' h array IO.hClose h Nothing -> return () where coerce' h [] = IO.hClose h coerce' h [s] = do IO.hPutStr h s coerce' h [] coerce' h (s:t) = do IO.hPutStr h s IO.hPutChar h '\0' coerce' h t getArray :: String -> Maybe FilePath -> IO [String] getArray name path = do handle <- openFileM name IO.ReadMode path (case handle of Just h -> (do coerce' h [] "") Nothing -> return []) where coerce' h a s = catch (do c <- IO.hGetChar h r <- (if (c == '\0') then (coerce' h (a ++ [s]) "") else (coerce' h a (s ++ [c]))) return r) (\e -> return $ a ++ [s])
udoprog/gabriel
Gabriel/Utils.hs
gpl-3.0
2,581
0
18
810
906
454
452
66
4
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.IAMCredentials.Types -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- module Network.Google.IAMCredentials.Types ( -- * Service Configuration iAMCredentialsService -- * OAuth Scopes , cloudPlatformScope -- * GenerateIdTokenRequest , GenerateIdTokenRequest , generateIdTokenRequest , gitrAudience , gitrDelegates , gitrIncludeEmail -- * GenerateAccessTokenResponse , GenerateAccessTokenResponse , generateAccessTokenResponse , gatrAccessToken , gatrExpireTime -- * SignJwtResponse , SignJwtResponse , signJwtResponse , sjrKeyId , sjrSignedJwt -- * SignBlobRequest , SignBlobRequest , signBlobRequest , sbrDelegates , sbrPayload -- * Xgafv , Xgafv (..) -- * GenerateAccessTokenRequest , GenerateAccessTokenRequest , generateAccessTokenRequest , gatrDelegates , gatrLifetime , gatrScope -- * SignJwtRequest , SignJwtRequest , signJwtRequest , sjrDelegates , sjrPayload -- * SignBlobResponse , SignBlobResponse , signBlobResponse , sbrKeyId , sbrSignedBlob -- * GenerateIdTokenResponse , GenerateIdTokenResponse , generateIdTokenResponse , gitrToken ) where import Network.Google.IAMCredentials.Types.Product import Network.Google.IAMCredentials.Types.Sum import Network.Google.Prelude -- | Default request referring to version 'v1' of the IAM Service Account Credentials API. This contains the host and root path used as a starting point for constructing service requests. iAMCredentialsService :: ServiceConfig iAMCredentialsService = defaultService (ServiceId "iamcredentials:v1") "iamcredentials.googleapis.com" -- | See, edit, configure, and delete your Google Cloud Platform data cloudPlatformScope :: Proxy '["https://www.googleapis.com/auth/cloud-platform"] cloudPlatformScope = Proxy
brendanhay/gogol
gogol-iamcredentials/gen/Network/Google/IAMCredentials/Types.hs
mpl-2.0
2,352
0
7
490
210
146
64
53
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Module : Network.AWS.EC2.AttachVolume -- Copyright : (c) 2013-2014 Brendan Hay <[email protected]> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <[email protected]> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | Attaches an EBS volume to a running or stopped instance and exposes it to the -- instance with the specified device name. -- -- Encrypted EBS volumes may only be attached to instances that support Amazon -- EBS encryption. For more information, see <http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html Amazon EBS Encryption> in the /AmazonElastic Compute Cloud User Guide/. -- -- For a list of supported device names, see <http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-attaching-volume.html Attaching an EBS Volume to anInstance>. Any device names that aren't reserved for instance store volumes -- can be used for EBS volumes. For more information, see <http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/InstanceStorage.html Amazon EC2 InstanceStore> in the /Amazon Elastic Compute Cloud User Guide/. -- -- If a volume has an AWS Marketplace product code: -- -- The volume can be attached only to a stopped instance. AWS Marketplace -- product codes are copied from the volume to the instance. You must be -- subscribed to the product. The instance type and operating system of the -- instance must support the product. For example, you can't detach a volume -- from a Windows instance and attach it to a Linux instance. For an overview -- of the AWS Marketplace, see <https://aws.amazon.com/marketplace/help/200900000 Introducing AWS Marketplace>. -- -- For more information about EBS volumes, see <http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-attaching-volume.html Attaching Amazon EBS Volumes> in -- the /Amazon Elastic Compute Cloud User Guide/. -- -- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-AttachVolume.html> module Network.AWS.EC2.AttachVolume ( -- * Request AttachVolume -- ** Request constructor , attachVolume -- ** Request lenses , avDevice , avDryRun , avInstanceId , avVolumeId -- * Response , AttachVolumeResponse -- ** Response constructor , attachVolumeResponse -- ** Response lenses , avrAttachTime , avrDeleteOnTermination , avrDevice , avrInstanceId , avrState , avrVolumeId ) where import Network.AWS.Prelude import Network.AWS.Request.Query import Network.AWS.EC2.Types import qualified GHC.Exts data AttachVolume = AttachVolume { _avDevice :: Text , _avDryRun :: Maybe Bool , _avInstanceId :: Text , _avVolumeId :: Text } deriving (Eq, Ord, Read, Show) -- | 'AttachVolume' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'avDevice' @::@ 'Text' -- -- * 'avDryRun' @::@ 'Maybe' 'Bool' -- -- * 'avInstanceId' @::@ 'Text' -- -- * 'avVolumeId' @::@ 'Text' -- attachVolume :: Text -- ^ 'avVolumeId' -> Text -- ^ 'avInstanceId' -> Text -- ^ 'avDevice' -> AttachVolume attachVolume p1 p2 p3 = AttachVolume { _avVolumeId = p1 , _avInstanceId = p2 , _avDevice = p3 , _avDryRun = Nothing } -- | The device name to expose to the instance (for example, '/dev/sdh' or 'xvdh'). avDevice :: Lens' AttachVolume Text avDevice = lens _avDevice (\s a -> s { _avDevice = a }) -- | Checks whether you have the required permissions for the action, without -- actually making the request, and provides an error response. If you have the -- required permissions, the error response is 'DryRunOperation'. Otherwise, it is 'UnauthorizedOperation'. avDryRun :: Lens' AttachVolume (Maybe Bool) avDryRun = lens _avDryRun (\s a -> s { _avDryRun = a }) -- | The ID of the instance. avInstanceId :: Lens' AttachVolume Text avInstanceId = lens _avInstanceId (\s a -> s { _avInstanceId = a }) -- | The ID of the EBS volume. The volume and instance must be within the same -- Availability Zone. avVolumeId :: Lens' AttachVolume Text avVolumeId = lens _avVolumeId (\s a -> s { _avVolumeId = a }) data AttachVolumeResponse = AttachVolumeResponse { _avrAttachTime :: Maybe ISO8601 , _avrDeleteOnTermination :: Maybe Bool , _avrDevice :: Maybe Text , _avrInstanceId :: Maybe Text , _avrState :: Maybe VolumeAttachmentState , _avrVolumeId :: Maybe Text } deriving (Eq, Read, Show) -- | 'AttachVolumeResponse' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'avrAttachTime' @::@ 'Maybe' 'UTCTime' -- -- * 'avrDeleteOnTermination' @::@ 'Maybe' 'Bool' -- -- * 'avrDevice' @::@ 'Maybe' 'Text' -- -- * 'avrInstanceId' @::@ 'Maybe' 'Text' -- -- * 'avrState' @::@ 'Maybe' 'VolumeAttachmentState' -- -- * 'avrVolumeId' @::@ 'Maybe' 'Text' -- attachVolumeResponse :: AttachVolumeResponse attachVolumeResponse = AttachVolumeResponse { _avrVolumeId = Nothing , _avrInstanceId = Nothing , _avrDevice = Nothing , _avrState = Nothing , _avrAttachTime = Nothing , _avrDeleteOnTermination = Nothing } -- | The time stamp when the attachment initiated. avrAttachTime :: Lens' AttachVolumeResponse (Maybe UTCTime) avrAttachTime = lens _avrAttachTime (\s a -> s { _avrAttachTime = a }) . mapping _Time -- | Indicates whether the EBS volume is deleted on instance termination. avrDeleteOnTermination :: Lens' AttachVolumeResponse (Maybe Bool) avrDeleteOnTermination = lens _avrDeleteOnTermination (\s a -> s { _avrDeleteOnTermination = a }) -- | The device name. avrDevice :: Lens' AttachVolumeResponse (Maybe Text) avrDevice = lens _avrDevice (\s a -> s { _avrDevice = a }) -- | The ID of the instance. avrInstanceId :: Lens' AttachVolumeResponse (Maybe Text) avrInstanceId = lens _avrInstanceId (\s a -> s { _avrInstanceId = a }) -- | The attachment state of the volume. avrState :: Lens' AttachVolumeResponse (Maybe VolumeAttachmentState) avrState = lens _avrState (\s a -> s { _avrState = a }) -- | The ID of the volume. avrVolumeId :: Lens' AttachVolumeResponse (Maybe Text) avrVolumeId = lens _avrVolumeId (\s a -> s { _avrVolumeId = a }) instance ToPath AttachVolume where toPath = const "/" instance ToQuery AttachVolume where toQuery AttachVolume{..} = mconcat [ "Device" =? _avDevice , "DryRun" =? _avDryRun , "InstanceId" =? _avInstanceId , "VolumeId" =? _avVolumeId ] instance ToHeaders AttachVolume instance AWSRequest AttachVolume where type Sv AttachVolume = EC2 type Rs AttachVolume = AttachVolumeResponse request = post "AttachVolume" response = xmlResponse instance FromXML AttachVolumeResponse where parseXML x = AttachVolumeResponse <$> x .@? "attachTime" <*> x .@? "deleteOnTermination" <*> x .@? "device" <*> x .@? "instanceId" <*> x .@? "status" <*> x .@? "volumeId"
romanb/amazonka
amazonka-ec2/gen/Network/AWS/EC2/AttachVolume.hs
mpl-2.0
7,839
0
17
1,723
1,015
610
405
104
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Dataflow.Projects.Locations.Templates.Create -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Creates a Cloud Dataflow job from a template. -- -- /See:/ <https://cloud.google.com/dataflow Dataflow API Reference> for @dataflow.projects.locations.templates.create@. module Network.Google.Resource.Dataflow.Projects.Locations.Templates.Create ( -- * REST Resource ProjectsLocationsTemplatesCreateResource -- * Creating a Request , projectsLocationsTemplatesCreate , ProjectsLocationsTemplatesCreate -- * Request Lenses , pltcXgafv , pltcUploadProtocol , pltcLocation , pltcAccessToken , pltcUploadType , pltcPayload , pltcProjectId , pltcCallback ) where import Network.Google.Dataflow.Types import Network.Google.Prelude -- | A resource alias for @dataflow.projects.locations.templates.create@ method which the -- 'ProjectsLocationsTemplatesCreate' request conforms to. type ProjectsLocationsTemplatesCreateResource = "v1b3" :> "projects" :> Capture "projectId" Text :> "locations" :> Capture "location" Text :> "templates" :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] CreateJobFromTemplateRequest :> Post '[JSON] Job -- | Creates a Cloud Dataflow job from a template. -- -- /See:/ 'projectsLocationsTemplatesCreate' smart constructor. data ProjectsLocationsTemplatesCreate = ProjectsLocationsTemplatesCreate' { _pltcXgafv :: !(Maybe Xgafv) , _pltcUploadProtocol :: !(Maybe Text) , _pltcLocation :: !Text , _pltcAccessToken :: !(Maybe Text) , _pltcUploadType :: !(Maybe Text) , _pltcPayload :: !CreateJobFromTemplateRequest , _pltcProjectId :: !Text , _pltcCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ProjectsLocationsTemplatesCreate' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pltcXgafv' -- -- * 'pltcUploadProtocol' -- -- * 'pltcLocation' -- -- * 'pltcAccessToken' -- -- * 'pltcUploadType' -- -- * 'pltcPayload' -- -- * 'pltcProjectId' -- -- * 'pltcCallback' projectsLocationsTemplatesCreate :: Text -- ^ 'pltcLocation' -> CreateJobFromTemplateRequest -- ^ 'pltcPayload' -> Text -- ^ 'pltcProjectId' -> ProjectsLocationsTemplatesCreate projectsLocationsTemplatesCreate pPltcLocation_ pPltcPayload_ pPltcProjectId_ = ProjectsLocationsTemplatesCreate' { _pltcXgafv = Nothing , _pltcUploadProtocol = Nothing , _pltcLocation = pPltcLocation_ , _pltcAccessToken = Nothing , _pltcUploadType = Nothing , _pltcPayload = pPltcPayload_ , _pltcProjectId = pPltcProjectId_ , _pltcCallback = Nothing } -- | V1 error format. pltcXgafv :: Lens' ProjectsLocationsTemplatesCreate (Maybe Xgafv) pltcXgafv = lens _pltcXgafv (\ s a -> s{_pltcXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). pltcUploadProtocol :: Lens' ProjectsLocationsTemplatesCreate (Maybe Text) pltcUploadProtocol = lens _pltcUploadProtocol (\ s a -> s{_pltcUploadProtocol = a}) -- | The [regional endpoint] -- (https:\/\/cloud.google.com\/dataflow\/docs\/concepts\/regional-endpoints) -- to which to direct the request. pltcLocation :: Lens' ProjectsLocationsTemplatesCreate Text pltcLocation = lens _pltcLocation (\ s a -> s{_pltcLocation = a}) -- | OAuth access token. pltcAccessToken :: Lens' ProjectsLocationsTemplatesCreate (Maybe Text) pltcAccessToken = lens _pltcAccessToken (\ s a -> s{_pltcAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). pltcUploadType :: Lens' ProjectsLocationsTemplatesCreate (Maybe Text) pltcUploadType = lens _pltcUploadType (\ s a -> s{_pltcUploadType = a}) -- | Multipart request metadata. pltcPayload :: Lens' ProjectsLocationsTemplatesCreate CreateJobFromTemplateRequest pltcPayload = lens _pltcPayload (\ s a -> s{_pltcPayload = a}) -- | Required. The ID of the Cloud Platform project that the job belongs to. pltcProjectId :: Lens' ProjectsLocationsTemplatesCreate Text pltcProjectId = lens _pltcProjectId (\ s a -> s{_pltcProjectId = a}) -- | JSONP pltcCallback :: Lens' ProjectsLocationsTemplatesCreate (Maybe Text) pltcCallback = lens _pltcCallback (\ s a -> s{_pltcCallback = a}) instance GoogleRequest ProjectsLocationsTemplatesCreate where type Rs ProjectsLocationsTemplatesCreate = Job type Scopes ProjectsLocationsTemplatesCreate = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/compute", "https://www.googleapis.com/auth/compute.readonly", "https://www.googleapis.com/auth/userinfo.email"] requestClient ProjectsLocationsTemplatesCreate'{..} = go _pltcProjectId _pltcLocation _pltcXgafv _pltcUploadProtocol _pltcAccessToken _pltcUploadType _pltcCallback (Just AltJSON) _pltcPayload dataflowService where go = buildClient (Proxy :: Proxy ProjectsLocationsTemplatesCreateResource) mempty
brendanhay/gogol
gogol-dataflow/gen/Network/Google/Resource/Dataflow/Projects/Locations/Templates/Create.hs
mpl-2.0
6,371
0
20
1,466
874
510
364
134
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Compute.Reservations.SetIAMPolicy -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Sets the access control policy on the specified resource. Replaces any -- existing policy. -- -- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.reservations.setIamPolicy@. module Network.Google.Resource.Compute.Reservations.SetIAMPolicy ( -- * REST Resource ReservationsSetIAMPolicyResource -- * Creating a Request , reservationsSetIAMPolicy , ReservationsSetIAMPolicy -- * Request Lenses , rsipProject , rsipZone , rsipPayload , rsipResource ) where import Network.Google.Compute.Types import Network.Google.Prelude -- | A resource alias for @compute.reservations.setIamPolicy@ method which the -- 'ReservationsSetIAMPolicy' request conforms to. type ReservationsSetIAMPolicyResource = "compute" :> "v1" :> "projects" :> Capture "project" Text :> "zones" :> Capture "zone" Text :> "reservations" :> Capture "resource" Text :> "setIamPolicy" :> QueryParam "alt" AltJSON :> ReqBody '[JSON] ZoneSetPolicyRequest :> Post '[JSON] Policy -- | Sets the access control policy on the specified resource. Replaces any -- existing policy. -- -- /See:/ 'reservationsSetIAMPolicy' smart constructor. data ReservationsSetIAMPolicy = ReservationsSetIAMPolicy' { _rsipProject :: !Text , _rsipZone :: !Text , _rsipPayload :: !ZoneSetPolicyRequest , _rsipResource :: !Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ReservationsSetIAMPolicy' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'rsipProject' -- -- * 'rsipZone' -- -- * 'rsipPayload' -- -- * 'rsipResource' reservationsSetIAMPolicy :: Text -- ^ 'rsipProject' -> Text -- ^ 'rsipZone' -> ZoneSetPolicyRequest -- ^ 'rsipPayload' -> Text -- ^ 'rsipResource' -> ReservationsSetIAMPolicy reservationsSetIAMPolicy pRsipProject_ pRsipZone_ pRsipPayload_ pRsipResource_ = ReservationsSetIAMPolicy' { _rsipProject = pRsipProject_ , _rsipZone = pRsipZone_ , _rsipPayload = pRsipPayload_ , _rsipResource = pRsipResource_ } -- | Project ID for this request. rsipProject :: Lens' ReservationsSetIAMPolicy Text rsipProject = lens _rsipProject (\ s a -> s{_rsipProject = a}) -- | The name of the zone for this request. rsipZone :: Lens' ReservationsSetIAMPolicy Text rsipZone = lens _rsipZone (\ s a -> s{_rsipZone = a}) -- | Multipart request metadata. rsipPayload :: Lens' ReservationsSetIAMPolicy ZoneSetPolicyRequest rsipPayload = lens _rsipPayload (\ s a -> s{_rsipPayload = a}) -- | Name or id of the resource for this request. rsipResource :: Lens' ReservationsSetIAMPolicy Text rsipResource = lens _rsipResource (\ s a -> s{_rsipResource = a}) instance GoogleRequest ReservationsSetIAMPolicy where type Rs ReservationsSetIAMPolicy = Policy type Scopes ReservationsSetIAMPolicy = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/compute"] requestClient ReservationsSetIAMPolicy'{..} = go _rsipProject _rsipZone _rsipResource (Just AltJSON) _rsipPayload computeService where go = buildClient (Proxy :: Proxy ReservationsSetIAMPolicyResource) mempty
brendanhay/gogol
gogol-compute/gen/Network/Google/Resource/Compute/Reservations/SetIAMPolicy.hs
mpl-2.0
4,383
0
18
1,031
549
326
223
88
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Spanner.Projects.Instances.Databases.Get -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Gets the state of a Cloud Spanner database. -- -- /See:/ <https://cloud.google.com/spanner/ Cloud Spanner API Reference> for @spanner.projects.instances.databases.get@. module Network.Google.Resource.Spanner.Projects.Instances.Databases.Get ( -- * REST Resource ProjectsInstancesDatabasesGetResource -- * Creating a Request , projectsInstancesDatabasesGet , ProjectsInstancesDatabasesGet -- * Request Lenses , pidgXgafv , pidgUploadProtocol , pidgAccessToken , pidgUploadType , pidgName , pidgCallback ) where import Network.Google.Prelude import Network.Google.Spanner.Types -- | A resource alias for @spanner.projects.instances.databases.get@ method which the -- 'ProjectsInstancesDatabasesGet' request conforms to. type ProjectsInstancesDatabasesGetResource = "v1" :> Capture "name" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Get '[JSON] Database -- | Gets the state of a Cloud Spanner database. -- -- /See:/ 'projectsInstancesDatabasesGet' smart constructor. data ProjectsInstancesDatabasesGet = ProjectsInstancesDatabasesGet' { _pidgXgafv :: !(Maybe Xgafv) , _pidgUploadProtocol :: !(Maybe Text) , _pidgAccessToken :: !(Maybe Text) , _pidgUploadType :: !(Maybe Text) , _pidgName :: !Text , _pidgCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ProjectsInstancesDatabasesGet' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pidgXgafv' -- -- * 'pidgUploadProtocol' -- -- * 'pidgAccessToken' -- -- * 'pidgUploadType' -- -- * 'pidgName' -- -- * 'pidgCallback' projectsInstancesDatabasesGet :: Text -- ^ 'pidgName' -> ProjectsInstancesDatabasesGet projectsInstancesDatabasesGet pPidgName_ = ProjectsInstancesDatabasesGet' { _pidgXgafv = Nothing , _pidgUploadProtocol = Nothing , _pidgAccessToken = Nothing , _pidgUploadType = Nothing , _pidgName = pPidgName_ , _pidgCallback = Nothing } -- | V1 error format. pidgXgafv :: Lens' ProjectsInstancesDatabasesGet (Maybe Xgafv) pidgXgafv = lens _pidgXgafv (\ s a -> s{_pidgXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). pidgUploadProtocol :: Lens' ProjectsInstancesDatabasesGet (Maybe Text) pidgUploadProtocol = lens _pidgUploadProtocol (\ s a -> s{_pidgUploadProtocol = a}) -- | OAuth access token. pidgAccessToken :: Lens' ProjectsInstancesDatabasesGet (Maybe Text) pidgAccessToken = lens _pidgAccessToken (\ s a -> s{_pidgAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). pidgUploadType :: Lens' ProjectsInstancesDatabasesGet (Maybe Text) pidgUploadType = lens _pidgUploadType (\ s a -> s{_pidgUploadType = a}) -- | Required. The name of the requested database. Values are of the form -- \`projects\/\/instances\/\/databases\/\`. pidgName :: Lens' ProjectsInstancesDatabasesGet Text pidgName = lens _pidgName (\ s a -> s{_pidgName = a}) -- | JSONP pidgCallback :: Lens' ProjectsInstancesDatabasesGet (Maybe Text) pidgCallback = lens _pidgCallback (\ s a -> s{_pidgCallback = a}) instance GoogleRequest ProjectsInstancesDatabasesGet where type Rs ProjectsInstancesDatabasesGet = Database type Scopes ProjectsInstancesDatabasesGet = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/spanner.admin"] requestClient ProjectsInstancesDatabasesGet'{..} = go _pidgName _pidgXgafv _pidgUploadProtocol _pidgAccessToken _pidgUploadType _pidgCallback (Just AltJSON) spannerService where go = buildClient (Proxy :: Proxy ProjectsInstancesDatabasesGetResource) mempty
brendanhay/gogol
gogol-spanner/gen/Network/Google/Resource/Spanner/Projects/Instances/Databases/Get.hs
mpl-2.0
4,987
0
15
1,088
700
410
290
103
1
module Betty.Signup.Sendmail ( sendVerificationEmail ) where import ClassyPrelude.Yesod import Network.Mail.Mime import Yesod.Auth.Email import Betty.Signup.MailText (verHeaders, verHtml, verText) ------------------------------------------------------------------------ sendVerificationEmail :: Email -> VerKey -> VerUrl -> HandlerT site IO () sendVerificationEmail email _ verurl = liftIO $ renderSendMail (emptyMail $ Address Nothing "noreply") { mailTo = [Address Nothing email] , mailHeaders = verHeaders , mailParts = [map ($ verurl) [verText, verHtml]] } ------------------------------------------------------------------------
sajith/betty-web
Betty/Signup/Sendmail.hs
agpl-3.0
743
0
11
172
151
88
63
13
1
-- Copyright 2015 Google Inc. 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 -- -- http://www.apache.org/licenses/LICENSE-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. {-# LANGUAGE OverloadedStrings #-} import Datatypes import Algo import Parser import System.Environment (getArgs) main = do [filename] <- getArgs s <- readFile filename case parseModule filename s of Left err -> putStrLn (show err) Right (Module sig trs) -> mapM_ print (otrsToTrs sig trs)
polux/subsume
Main.hs
apache-2.0
917
0
12
163
119
65
54
11
2
data DataInt = D Int deriving (Eq, Ord, Show) newtype NewtypeInt = N Int deriving (Eq, Ord, Show)
EricYT/Haskell
src/real_haskell/chapter-6/Newtype.hs
apache-2.0
136
0
6
56
48
26
22
4
0
-- | Some example queries demonstrating the Narc interface. module Database.Narc.ExampleEmbedded where import Prelude hiding ((<), (==), (>=), (>), (<=), (/=), (+), (&&)) import Test.HUnit import Database.Narc import Database.Narc.Embed hiding ((./)) import Database.Narc.Embed.Ops import Algebras example1 = let t = (table "foo" [("a", TBool)]) in foreach t $ \x -> (having (project x "a") (singleton x)) example2 = let t = (table "foo" [("a", TNum)]) in let s = (table "bar" [("a", TNum)]) in foreach t $ \x -> foreach s $ \y -> ifthenelse (x ./ "a" < y ./ "a") -- TODO: fix precedence. (singleton x) (singleton y) example3 = let t = table "employees" [("name", TString), ("salary", TNum)] in foreach t $ \emp -> having (20000 < emp ./ "salary") $ result [("nom", emp ./ "name")] example4 = let t = table "employees" [("name", TString), ("salary", TNum)] in foreach t $ \emp -> having (cnst "Joe" == emp ./ "name") $ -- TODO: still have to inject "Joe". grr. result [("nom", emp ./ "name")] example5 = let employees = table "employees" [ ("salary", TNum) , ("name", TString) , ("startdate", TNum) ] in let highEarners = -- employees having salary above 20000 foreach employees $ \emp -> having (20000 < emp ./ "salary") $ result [ ("name", emp ./ "name"), ("startdate", emp ./ "startdate") ] in let highEarnersFromBefore98 = foreach highEarners $ \emp -> having (emp ./ "startdate" < 1998) $ result [("name", emp ./ "name")] in highEarnersFromBefore98 example6 = let employees = table "employees" [ ("salary", TNum) , ("name", TString) , ("manager", TString) , ("startdate", TNum) ] in let teamOf emp = foreach employees $ \e2 -> having (e2 ./ "manager" == emp ./ "manager") $ singleton e2 in let highEarners = foreach employees $ \emp -> having (20000 < emp ./ "salary") $ result [ ("name", emp ./ "name"), ("startdate", emp ./ "startdate"), ("manager", emp ./ "manager") ] in let highEarnersFromBefore98 = foreach highEarners $ \emp -> having (emp ./ "startdate" < 1998) $ result [("name", emp ./ "name"), ("manager", emp ./ "manager")] in foreach highEarnersFromBefore98 teamOf example_teamRosters = let teamsTable = table "teams" [("name", TString), ("id", TNum)] in let playersTable = table "players" [("name", TString), ("teamId", TNum)] in let rosterFor t = narrowToNames ["name"] (filterToFieldValue playersTable "teamId" (t ./ "id")) in let teamRosters = foreach teamsTable $ \t -> result [("teamName", t ./ "name"), ("roster", rosterFor t)] -- And we can return a list of those teams with at least 9 players as follows: in let validTeams = foreach teamRosters $ \t -> having ((primApp "length" [t ./ "roster"]) >= 9) $ result [("teamName", t ./ "teamName")] in validTeams -- NOTE: Ordinary comparison still works, but requires some type annotation. equals2 x = 2 == x :: Bool {- Utility functions -} fieldValue field value p = p ./ field == value filterToFieldValue table field value = foreach table $ \p -> having (fieldValue field value p) $ singleton p narrowToNames names src = foreach src $ \p -> result [(n, p ./ n) | n <- names] {- Dummies, not yet implemented as part of the actual language. -} -- | Take the "first" @n@ elements resulting from @query@. TBD: implement! takeNarc n query = query -- | Transform a result set into an ordered result set. TBD: implement! orderByDesc field query = query -- | A peculiar query from my train game in Perl exampleQuery currentPlayer gameID = let playingSchema = [("gameID", TNum), ("player", TNum), ("position", TNum)] in let playingTable = table "playing" playingSchema in let playingHere = filterToFieldValue playingTable "gameID" gameID in takeNarc 1 $ -- TODO: define orderByDesc "position" $ -- TODO: define (foreach playingHere $ \a -> foreach playingHere $ \b -> having (a ./ "position" + 1 == b ./ "position" && a ./ "player" == currentPlayer) $ result [("player", b ./ "player"), ("position", b ./ "position")]) `union` (foreach playingHere $ \a -> having (a ./ "position" == 1) $ result [("player", a ./ "player"), ("position", a ./ "position")]) -- | Take the rows of @a@ that have a corresponding row (according to -- @joinRel@) in @b@ and where the two rows satisfy @pred@. Importantly, -- returns a relation with the type of @a@, that is, drops the row @b@. wherehas a aSchema b joinRel pred = foreach a $ \x -> foreach b $ \y -> having (joinRel x y) $ having (pred x y) $ singleton x -- | A peculiar query from my train game in Perl exampleQuery2 currentPlayer gameID = let playingSchema = [("gameID", TNum), ("player", TNum), ("position", TNum)] in let playingTable = table "playing" playingSchema in let playingHere = filterToFieldValue playingTable "gameID" gameID in takeNarc 1 $ -- TODO: define orderByDesc "position" $ -- TODO: define (projection ["player", "position"] $ wherehas playingHere playingSchema playingHere adjacentPosition (\a -> \b -> a ./ "player" == currentPlayer)) `union` (foreach playingHere $ \a -> having (a ./ "position" == 1) $ result [("player", a ./ "player"), ("position", a ./ "position")]) where adjacentPosition a b = a ./ "position" + 1 == b ./ "position" -- The original query: select the player to the right of the current -- player, or player 1 if there is no current player. -- select b.player as player, b.position as position -- from playing a, playing b -- where a.position + 1 = b.position and a.player = $current_player -- union -- select a.player as player, a.position as position -- from playing a -- where a.gameID = 1 and a.position = 1 -- order by position desc limit 1 -- How the query compiles: -- ((select _2.player as player, _2.position as position -- from playing as _0, playing as _2 -- where _0.gameID = 1 and _2.gameID = 1 and -- _0.position + 1 = _2.position and _0.player = 1)) -- union -- ((select _4.player as player, _4.position as position -- from playing as _4 -- where _4.gameID = 1 and _4.position = 1)) -- | A trivial example. testx = narcToSQLString nil ~?= "select 0 where false" -- Unit tests ---------------------------------------------------------- test_example = TestList [ narcToSQLString example1 ~?= "select _0.a as a from foo as _0 where _0.a" , narcToSQLString example2 ~?= "(select _0.a as a from foo as _0, bar as _1 where _0.a < _1.a) union (select _1.a as a from foo as _0, bar as _1 where not(_0.a < _1.a))" , narcToSQLString example3 ~?= "select _0.name as nom from employees as _0 where 20000 < _0.salary" , narcToSQLString example4 ~?= "select _0.name as nom from employees as _0 where \"Joe\" = _0.name" , narcToSQLString example5 ~?= "select _0.name as name from employees as _0 where 20000 < _0.salary and _0.startdate < 1998" , narcToSQLString example6 ~?= "select _3.salary as salary, _3.name as name, _3.manager as manager, _3.startdate as startdate from employees as _0, employees as _3 where 20000 < _0.salary and _0.startdate < 1998 and _3.manager = _0.manager" , narcToSQLString example_teamRosters ~?= "select _0.name as teamName from teams as _0, select count(*) as count from players as _1 where _1.teamId = _0.id as x where x.count >= 9" , narcToSQLString (exampleQuery 3 4) ~?= "" ]
ezrakilty/narc
Database/Narc/ExampleEmbedded.hs
bsd-2-clause
8,352
0
27
2,464
1,982
1,078
904
146
1
module Turtle.GlossInterface where import GHC.Float import qualified Graphics.Gloss as Gloss import qualified Turtle.Objects as Turtle point2Gloss :: Turtle.Point -> Gloss.Point point2Gloss point = (double2Float (Turtle.xDimension point), double2Float (Turtle.yDimension point)) line2Pic :: Turtle.Line -> Gloss.Picture line2Pic line = Gloss.Line [point2Gloss (Turtle.fromPoint line), point2Gloss (Turtle.toPoint line)] canv2Pic :: Turtle.Canvas -> Gloss.Picture canv2Pic canv = Gloss.Pictures (map line2Pic (Turtle.canvasLines canv)) displayCanvas :: Turtle.Canvas -> (Int, Int) -> IO () displayCanvas canv position = Gloss.display (Gloss.InWindow "Turtle" (canvWidth, canvHeight) position) Gloss.white (canv2Pic canv) where canvWidth = round (Turtle.canvasWidth canv) :: Int canvHeight = round (Turtle.canvasHeight canv) ::Int
zefciu/Turtle
src/Turtle/GlossInterface.hs
bsd-3-clause
875
0
10
139
283
150
133
19
1
{-# LANGUAGE CPP, RecordWildCards #-} -- | -- Package configuration information: essentially the interface to Cabal, with -- some utilities -- -- (c) The University of Glasgow, 2004 -- module PackageConfig ( -- $package_naming -- * UnitId packageConfigId, -- * The PackageConfig type: information about a package PackageConfig, InstalledPackageInfo(..), ComponentId(..), SourcePackageId(..), PackageName(..), Version(..), defaultPackageConfig, sourcePackageIdString, packageNameString, pprPackageConfig, ) where #include "HsVersions.h" import GHC.PackageDb import Data.Version import FastString import Outputable import Module import Unique -- ----------------------------------------------------------------------------- -- Our PackageConfig type is the InstalledPackageInfo from ghc-boot, -- which is similar to a subset of the InstalledPackageInfo type from Cabal. type PackageConfig = InstalledPackageInfo SourcePackageId PackageName Module.UnitId Module.ModuleName -- TODO: there's no need for these to be FastString, as we don't need the uniq -- feature, but ghc doesn't currently have convenient support for any -- other compact string types, e.g. plain ByteString or Text. newtype ComponentId = ComponentId FastString deriving (Eq, Ord) newtype SourcePackageId = SourcePackageId FastString deriving (Eq, Ord) newtype PackageName = PackageName FastString deriving (Eq, Ord) instance BinaryStringRep ComponentId where fromStringRep = ComponentId . mkFastStringByteString toStringRep (ComponentId s) = fastStringToByteString s instance BinaryStringRep SourcePackageId where fromStringRep = SourcePackageId . mkFastStringByteString toStringRep (SourcePackageId s) = fastStringToByteString s instance BinaryStringRep PackageName where fromStringRep = PackageName . mkFastStringByteString toStringRep (PackageName s) = fastStringToByteString s instance Uniquable ComponentId where getUnique (ComponentId n) = getUnique n instance Uniquable SourcePackageId where getUnique (SourcePackageId n) = getUnique n instance Uniquable PackageName where getUnique (PackageName n) = getUnique n instance Outputable ComponentId where ppr (ComponentId str) = ftext str instance Outputable SourcePackageId where ppr (SourcePackageId str) = ftext str instance Outputable PackageName where ppr (PackageName str) = ftext str -- | Pretty-print an 'ExposedModule' in the same format used by the textual -- installed package database. pprExposedModule :: (Outputable a, Outputable b) => ExposedModule a b -> SDoc pprExposedModule (ExposedModule exposedName exposedReexport) = sep [ ppr exposedName , case exposedReexport of Just m -> sep [text "from", pprOriginalModule m] Nothing -> empty ] -- | Pretty-print an 'OriginalModule' in the same format used by the textual -- installed package database. pprOriginalModule :: (Outputable a, Outputable b) => OriginalModule a b -> SDoc pprOriginalModule (OriginalModule originalPackageId originalModuleName) = ppr originalPackageId <> char ':' <> ppr originalModuleName defaultPackageConfig :: PackageConfig defaultPackageConfig = emptyInstalledPackageInfo sourcePackageIdString :: PackageConfig -> String sourcePackageIdString pkg = unpackFS str where SourcePackageId str = sourcePackageId pkg packageNameString :: PackageConfig -> String packageNameString pkg = unpackFS str where PackageName str = packageName pkg pprPackageConfig :: PackageConfig -> SDoc pprPackageConfig InstalledPackageInfo {..} = vcat [ field "name" (ppr packageName), field "version" (text (showVersion packageVersion)), field "id" (ppr unitId), field "exposed" (ppr exposed), field "exposed-modules" (if all isExposedModule exposedModules then fsep (map pprExposedModule exposedModules) else pprWithCommas pprExposedModule exposedModules), field "hidden-modules" (fsep (map ppr hiddenModules)), field "trusted" (ppr trusted), field "import-dirs" (fsep (map text importDirs)), field "library-dirs" (fsep (map text libraryDirs)), field "dynamic-library-dirs" (fsep (map text libraryDynDirs)), field "hs-libraries" (fsep (map text hsLibraries)), field "extra-libraries" (fsep (map text extraLibraries)), field "extra-ghci-libraries" (fsep (map text extraGHCiLibraries)), field "include-dirs" (fsep (map text includeDirs)), field "includes" (fsep (map text includes)), field "depends" (fsep (map ppr depends)), field "cc-options" (fsep (map text ccOptions)), field "ld-options" (fsep (map text ldOptions)), field "framework-dirs" (fsep (map text frameworkDirs)), field "frameworks" (fsep (map text frameworks)), field "haddock-interfaces" (fsep (map text haddockInterfaces)), field "haddock-html" (fsep (map text haddockHTMLs)) ] where field name body = text name <> colon <+> nest 4 body isExposedModule (ExposedModule _ Nothing) = True isExposedModule _ = False -- ----------------------------------------------------------------------------- -- UnitId (package names, versions and dep hash) -- $package_naming -- #package_naming# -- Mostly the compiler deals in terms of 'UnitId's, which are md5 hashes -- of a package ID, keys of its dependencies, and Cabal flags. You're expected -- to pass in the unit id in the @-this-unit-id@ flag. However, for -- wired-in packages like @base@ & @rts@, we don't necessarily know what the -- version is, so these are handled specially; see #wired_in_packages#. -- | Get the GHC 'UnitId' right out of a Cabalish 'PackageConfig' packageConfigId :: PackageConfig -> UnitId packageConfigId = unitId
GaloisInc/halvm-ghc
compiler/main/PackageConfig.hs
bsd-3-clause
6,159
0
12
1,395
1,232
646
586
98
3
{-# LANGUAGE OverloadedStrings #-} module Parse where import Control.Applicative as A import Control.Monad.State import Data.Attoparsec.Text as P import Data.Char (isLower, isAlpha, isSpace) import Data.Text as T import Data.List as L import Debug.Trace (trace) import Untyped example :: Text example = T.unlines [ -- "x/;" -- , "x;" "lambda x. x;" , "(lambda x. x) (lambda x. x x);" ] example' :: Either String ([Command], Context) example' = do s <- parseOnly toplevel "(lambda x. x) (lambda x. x x);" -- s <- parseOnly toplevel "lambda x. x;" return $ runState s [] testParser :: Parser (InContext a) -> String -> Either String (a, Context) testParser p s = do s <- parseOnly p (pack s) return $ runState s [] data Command = Eval Info Term | Bind Info Text Binding deriving (Show) type InContext = State Context -- | Used here as a -> Parser (Incontext a) return2 :: (Monad m, Monad n) => a -> m (n a) return2 = return . return -- | "The top level of a file is a sequence of commands, each terminated -- by a semicolon." toplevel :: Parser (InContext [Command]) toplevel = done <|> commands where done = endOfInput *> return2 [] commands = do cmd <- trace "toplevel command" $ command <* char ';' skipSpace trace "skipped space" $ return () cmds <- trace "toplevel commands" toplevel return $ (:) <$> cmd <*> cmds -- | "A top-level command" command :: Parser (InContext Command) command = cmdTerm <|> cmdBinder where cmdTerm = term >>= \tm -> trace "eval" $ return $ Eval Info <$> tm cmdBinder = do identifier <- trace "command lowerIdentifier" lowerIdentifier bind <- trace "command binder" binder return $ Bind Info identifier <$> bind -- | "Right-hand sides of top-level bindings" binder :: Parser (InContext Binding) binder = char '/' *> return2 NameBind term :: Parser (InContext Term) -- term = abstraction <|> appTerm where term = appTerm <|> abstraction where -- abstraction = abstraction' <|> (char '(' *> abstraction' <* char ')') abstraction = do trace "lambda" $ string "lambda" skipSpace identifier <- lowerIdentifier trace (show identifier ++ ".") $ char '.' skipSpace tm <- term trace "got term" $ return () return $ TmAbs Info identifier <$> tm -- | Apply one or more lambdas. appTerm :: Parser (InContext Term) -- appTerm = appTerm' <|> atomicTerm where -- appTerm' = do -- tm <- atomicTerm -- applied <- appTerm -- return $ TmApp Info <$> applied <*> tm appTerm = do tms <- many' atomicTerm trace ("appTerm: " ++ show (L.length tms)) $ return () if L.null tms then A.empty else return $ L.foldl1' (\tm1 tm2 -> TmApp Info <$> tm1 <*> tm2) tms -- | "Atomic terms are ones that never require extra parentheses" atomicTerm :: Parser (InContext Term) atomicTerm = parenTerm <|> identifierTerm where parenTerm = char '(' *> term <* char ')' identifierTerm = do identifier <- lowerIdentifier return $ do ctx <- get return $ TmVar Info (name2index Info ctx identifier) (ctxlength ctx) -- | A name beginning with a lower-case letter. lowerIdentifier :: Parser Text -- lowerIdentifier = skip isLower *> takeWhile1 isAlpha lowerIdentifier = do c <- trace "lowerIdentifier peekChar" peekChar guard (maybe False isLower c) takeWhile1 isAlpha
joelburget/tapl
Untyped/parse.hs
bsd-3-clause
3,485
0
15
874
934
474
460
77
2
{-| Module : CFPFD1 Description : Constraint Functional Programming over Multiple Finite Domain Copyright : (c) [email protected], 2014 License : BSD3 Maintainer : [email protected] Stability : experimental Portability : POSIX This module provides interfaces for constraint programming over multiple finite domain in Haskell. Originally from: <http://overtond.blogspot.jp/2008/07/pre.html> -} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE FlexibleInstances #-} module CFPFD1 ( -- * Monads FD , FDStat (..) , evalFD , runFD -- * Variables , Var , newVar , newVars , newVarT -- * Constraint Store , hasValue -- (for defining custom constraints) , ArcPropagator , arcConstraint , MultiPropagator , multiConstraint -- * Labelling , label , labelling , labellingT -- * Primitive Constraint -- ** Core Constraint , alldiff , alldiffF -- ** Arithmetic Constraint , eq , le , neq , add , sub , add3 -- ** Modulo Constraint , eqmod , neqmod , alldiffmod ) where import Control.Monad (MonadPlus) import Control.Monad (guard) import Control.Monad (when) import Control.Monad (replicateM) import Control.Monad.State (MonadState) import Control.Monad.State (StateT) import Control.Monad.State (evalStateT) import Control.Monad.State (get) import Control.Monad.State (gets) import Control.Monad.State (put) import Control.Monad.State (runStateT) import Control.Monad.State (modify) import Control.Monad.State (lift) import Control.Applicative (Applicative) import Control.Applicative (Alternative) import Data.IntMap (IntMap) import qualified Data.IntMap as IntMap import Data.Set (Set) import qualified Data.Set as Set import Data.Foldable (Foldable) import qualified Data.Foldable as Foldable import Data.Traversable (Traversable) import qualified Data.Traversable as Traversable newtype FD s a = FD { unFD :: StateT (FDState s) [] a } deriving (Functor, Applicative, Alternative, Monad, MonadPlus, MonadState (FDState s)) data FDState s = FDState { fdNextVarId :: VarId , fdVarSpace :: VarSpace s , fdStat :: FDStat } deriving (Show) data Var s a = Var { varId :: VarId , varName :: VarName } deriving (Show, Eq, Ord) type VarId = Int type VarName = String type VarSpace s = IntMap (VarState s) data VarState s = VarState { varDomain :: VarDomain, varPropagator :: VarPropagator s } deriving (Show) type VarDomain = Set Int type VarPropagator s = FD s () instance Show (VarPropagator s) where show _ = "*" data FDStat = FDStat { countLookupVar :: Int , countUpdateVar :: Int , countUpdateVar' :: Int } deriving (Show) initialStat :: FDStat initialStat = FDStat { countLookupVar = 0 , countUpdateVar = 0 , countUpdateVar' = 0 } evalFD :: (forall s . FD s a) -> [a] evalFD fd = evalStateT (unFD fd) initialState runFD :: (forall s . FD s a) -> [(a, FDStat)] runFD fd = map (\(v, s) -> (v, fdStat s)) ss where ss = runStateT (unFD fd) initialState initialState :: FDState s initialState = FDState { fdNextVarId = 0, fdVarSpace = IntMap.empty , fdStat = initialStat } newVar :: Enum a => String -> [a] -> FD s (Var s a) newVar name dom = do var <- nextVar name setDomain var dom return var where nextVar :: String -> FD s (Var s a) nextVar n = do s <- get let i = fdNextVarId s put $ s { fdNextVarId = i + 1 } return Var { varId = i, varName = n } setDomain :: Enum a => Var s a -> [a] -> FD s () setDomain v d = modify $ \s -> let sp = fdVarSpace s vstate = VarState { varDomain = Set.fromList . map fromEnum $ d , varPropagator = return () } in s { fdVarSpace = IntMap.insert (varId v) vstate sp } newVars :: Enum a => String -> Int -> [a] -> FD s [Var s a] newVars name n d = replicateM n (newVar (name ++ ":" ++ show n) d) newVarT :: (Traversable t, Enum a) => String -> t [a] -> FD s (t (Var s a)) newVarT name = Traversable.mapM (newVar name) getVarState :: Var s a -> FD s (VarState s) getVarState v = do vspace <- gets fdVarSpace return $ vspace IntMap.! (varId v) putVarState :: Var s a -> VarState s -> FD s () putVarState v vstate = do vspace <- gets fdVarSpace modify $ \s -> s { fdVarSpace = IntMap.insert (varId v) vstate vspace } modifyFDStat :: (FDStat -> FDStat) -> FD s () modifyFDStat f = modify $ \s -> s { fdStat = f (fdStat s) } lookupVar :: (Ord a, Enum a) => Var s a -> FD s (Set a) lookupVar v = do modifyFDStat $ \stat -> stat { countLookupVar = countLookupVar stat + 1 } vstate <- getVarState v return $ Set.fromList . map toEnum . Set.toList $ varDomain vstate updateVar :: (Ord a, Enum a) => Var s a -> Set a -> FD s () updateVar v d = do modifyFDStat $ \stat -> stat { countUpdateVar' = countUpdateVar' stat + 1 } vstate <- getVarState v when (Set.size (varDomain vstate) /= Set.size d) $ do modifyFDStat $ \stat -> stat { countUpdateVar = countUpdateVar stat + 1 } putVarState v $ vstate { varDomain = Set.fromList . map fromEnum . Set.toList $ d } varPropagator vstate addPropagator :: Var s a -> VarPropagator s -> FD s () addPropagator v p = do vstate <- getVarState v putVarState v (vstate { varPropagator = varPropagator vstate >> p }) -- Make arc consistent addArcPropagator :: VarPropagator s -> Var s a -> Var s b -> FD s () addArcPropagator p x y = do p addPropagator x p addPropagator y p -- Make multi consistent addMultiPropagator :: VarPropagator s -> [Var s a] -> FD s () addMultiPropagator p vs = do p mapM_ (`addPropagator` p) vs hasValue :: (Ord a, Enum a) => Var s a -> a -> FD s () var `hasValue` val = do vals <- lookupVar var guard $ val `Set.member` vals updateVar var (Set.singleton val) label :: (Ord a, Enum a) => Var s a -> FD s a label var = do vals <- lookupVar var val <- FD . lift $ Set.toList vals var `hasValue` val return val labelling :: (Ord a, Enum a) => [Var s a] -> FD s [a] labelling = mapM label labellingT :: (Traversable t, Ord a, Enum a) => t (Var s a) -> FD s (t a) labellingT = Traversable.mapM label guardNull :: MonadPlus m => Set a -> m () guardNull d = guard $ not $ Set.null d single :: Set a -> Bool single s = Set.size s == 1 type ArcPropagator a b = Set a -> Set b -> (Set a, Set b) arcConstraint :: (Ord a, Enum a, Ord b, Enum b) => ArcPropagator a b -> Var s a -> Var s b -> FD s () arcConstraint c x y = addArcPropagator p x y where p = do vx <- lookupVar x vy <- lookupVar y let (vx', vy') = c vx vy guardNull vx' updateVar x vx' guardNull vy' updateVar y vy' type MultiPropagator a = [Set a] -> [Set a] multiConstraint :: (Ord a, Enum a) => MultiPropagator a -> [Var s a] -> FD s () multiConstraint c xs = addMultiPropagator p xs where p = do vs <- mapM lookupVar xs let vs' = c vs (`mapM_` zip xs vs') $ \(x, vx') -> do guardNull vx' updateVar x vx' -- x == y eq :: (Ord a, Enum a) => Var s a -> Var s a -> FD s () eq = arcConstraint eqConstraint eqConstraint :: (Ord a) => ArcPropagator a a eqConstraint vx vy = (vz, vz) where vz = vx `Set.intersection` vy -- x <= y le :: (Ord a, Enum a) => Var s a -> Var s a -> FD s () le = arcConstraint leConstraint leConstraint :: (Ord a) => ArcPropagator a a leConstraint vx vy = (vx', vy') where minX = Set.findMin vx maxY = Set.findMax vy vx' = Set.filter (<= maxY) vx vy' = Set.filter (>= minX) vy -- x /= y neq :: (Ord a, Enum a) => Var s a -> Var s a -> FD s () neq = arcConstraint neqConstraint neqConstraint :: (Ord a) => ArcPropagator a a neqConstraint vx vy | single vx && single vy = if vx == vy then (Set.empty, Set.empty) else (vx, vy) | single vx && vx `Set.isProperSubsetOf` vy = (vx, vy Set.\\ vx) | single vy && vy `Set.isProperSubsetOf` vx = (vx Set.\\ vy, vy) | otherwise = (vx, vy) -- differ from each other alldiff :: (Ord a, Enum a) => [Var s a] -> FD s () alldiff [] = return () alldiff (v:vs) = do mapM_ (v `neq`) vs alldiff vs -- differ from each other alldiffF :: (Foldable f, Ord a, Enum a) => f (Var s a) -> FD s () alldiffF = alldiff . Foldable.toList -- x == y (mod m) eqmod :: Integral a => a -> Var s a -> Var s a -> FD s () eqmod m = arcConstraint (eqmodConstraint m) eqmodConstraint :: Integral a => a -> ArcPropagator a a eqmodConstraint m vx vy = (vx', vy') where vmz = Set.map (`mod` m) vx `Set.intersection` Set.map (`mod` m) vy vx' = Set.filter (\e -> (e `mod` m) `Set.member` vmz) vx vy' = Set.filter (\e -> (e `mod` m) `Set.member` vmz) vy -- x /= y (mod m) neqmod :: Integral a => a -> Var s a -> Var s a -> FD s () neqmod m = arcConstraint (neqmodConstraint m) neqmodConstraint :: Integral a => a -> ArcPropagator a a neqmodConstraint m vx vy = (vx'', vy'') where vmx = Set.map (`mod` m) vx vmy = Set.map (`mod` m) vy vy' = Set.filter (\e -> (e `mod` m) `Set.notMember` vmx) vy vx' = Set.filter (\e -> (e `mod` m) `Set.notMember` vmy) vx (vx'', vy'') | single vmx && single vmy = if vmx == vmy then (Set.empty, Set.empty) else (vx, vy) | single vmx && vmx `Set.isProperSubsetOf` vmy = (vx, vy') | single vmy && vmy `Set.isProperSubsetOf` vmx = (vx', vy) | otherwise = (vx, vy) -- differ from each other alldiffmod :: Integral a => a -> [Var s a] -> FD s () alldiffmod _ [] = return () alldiffmod m (v:vs) = do mapM_ (neqmod m v) vs alldiffmod m vs -- c == x + y (c is constant value) add :: (Ord a, Enum a, Num a) => a -> Var s a -> Var s a -> FD s () add c = arcConstraint (addConstraint c) addConstraint :: (Eq a, Num a) => a -> ArcPropagator a a addConstraint c vx vy = (vx', vy') where vx' = Set.filter (\ix -> any (\iy -> ix+iy==c) $ Set.toList vy) vx vy' = Set.filter (\iy -> any (\ix -> ix+iy==c) $ Set.toList vx) vy -- z == x + y -- x == z - y -- y == z - x add3 :: (Ord a, Enum a, Num a) => Var s a -> Var s a -> Var s a -> FD s () add3 z x y = multiConstraint add3Constraint [x, y, z] add3Constraint :: (Ord a, Num a) => MultiPropagator a add3Constraint [vx, vy, vz] = [vx', vy', vz'] where minZ = Set.findMin vx + Set.findMin vy maxZ = Set.findMax vx + Set.findMax vy vz' = Set.filter (\e -> minZ <= e && e <= maxZ) vz -- minX = Set.findMin vz - Set.findMax vy maxX = Set.findMax vz - Set.findMin vy vx' = Set.filter (\e -> minX <= e && e <= maxX) vx -- minY = Set.findMin vz - Set.findMax vx maxY = Set.findMax vz - Set.findMin vx vy' = Set.filter (\e -> minY <= e && e <= maxY) vy -- x - y == c (c is constant value) -- x == y + c sub :: (Ord a, Enum a, Num a) => a -> Var s a -> Var s a -> FD s () sub c = arcConstraint (subConstraint c) subConstraint :: (Eq a, Num a) => a -> ArcPropagator a a subConstraint c vx vy = (vx', vy') where vx' = Set.filter (\ix -> any (\iy -> ix==iy+c) $ Set.toList vy) vx vy' = Set.filter (\iy -> any (\ix -> ix==iy+c) $ Set.toList vx) vy -- -- Test Functions -- {-| >>> evalFD test1 [[1,4],[1,5],[2,4],[2,5],[3,4],[3,5]] -} test1 :: FD s [Int] test1 = do x <- newVar "X" [1..3] y <- newVar "Y" [4..5] labelling [x, y] {-| >>> evalFD test2 [[1,3],[2,2],[3,1]] -} test2 :: FD s [Int] test2 = do x <- newVar "X" [1..3] y <- newVar "Y" [1..3] add 4 x y labelling [x, y] {-| >>> evalFD test3 [[1,3,7],[2,2,8],[3,1,9]] -} test3 :: FD s [Int] test3 = do x <- newVar "X" [1..10] y <- newVar "Y" [1..10] z <- newVar "Z" [1..10] add 4 x y add 10 y z labelling [x, y, z] {-| >>> evalFD testSub1 [[1,3],[2,4],[3,5]] -} testSub1 :: FD s [Int] testSub1 = do x <- newVar "X" [1..5] y <- newVar "Y" [1..5] sub 2 y x labelling [x, y] {-| >>> evalFD testEq1 [[1,3,1],[2,4,2],[3,5,3]] -} testEq1 :: FD s [Int] testEq1 = do x <- newVar "X" [1..5] y <- newVar "Y" [1..5] z <- newVar "Z" [1..5] z `eq` x sub 2 y x labelling [x, y, z] {-| >>> evalFD testLE1 [[1,1],[1,2],[1,3],[2,2],[2,3],[3,3]] -} testLE1 :: FD s [Int] testLE1 = do x <- newVar "X" [1..3] y <- newVar "Y" [1..3] x `le` y labelling [x, y] {-| >>> evalFD testNeq1 [[1,2],[1,3],[2,1],[2,3],[3,1],[3,2]] -} testNeq1 :: FD s [Int] testNeq1 = do x <- newVar "X" [1..3] y <- newVar "Y" [1..3] x `neq` y labelling [x, y] {-| >>> length $ evalFD testAlldiff1 6 -} testAlldiff1 :: FD s [Int] testAlldiff1 = do x <- newVar "X" [1..3] y <- newVar "Y" [1..3] z <- newVar "Z" [1..3] alldiff [x, y, z] labelling [x, y, z] {-| >>> length $ evalFD testVars1 24 -} testVars1 :: FD s [Int] testVars1 = do xs <- newVars "Xn" 4 [1..4] alldiff xs labelling xs {-| >>> evalFD testAdd31 [[4,1,3],[4,2,2],[5,2,3],[5,3,2],[6,3,3]] -} testAdd31 :: FD s [Int] testAdd31 = do x <- newVar "X" [4..8] y <- newVar "Y" [0..3] z <- newVar "Z" [2..3] add3 x y z labelling [x, y, z] {-| >>> evalFD testAdd32 [[0,0],[0,1],[0,2],[1,1],[1,2],[1,3],[2,2],[2,3],[3,3]] -} testAdd32 :: FD s [Int] testAdd32 = do x <- newVar "X" [0..3] y <- newVar "Y" [0..3] z <- newVar "Z" [0..2] add3 y x z labelling [x, y] {-| >>> evalFD testEqmod1 [[4,1],[4,4],[5,2],[5,5]] -} testEqmod1 :: FD s [Int] testEqmod1 = do x <- newVar "X" [4..5] y <- newVar "Y" [0..5] eqmod 3 x y labelling [x, y] {-| >>> evalFD testNeqmod1 [[4,0],[4,2],[4,3],[4,5],[5,0],[5,1],[5,3],[5,4]] -} testNeqmod1 :: FD s [Int] testNeqmod1 = do x <- newVar "X" [4..5] y <- newVar "Y" [0..5] neqmod 3 x y labelling [x, y] {-| >>> evalFD testBool1 [[False,True,False],[True,False,True]] -} testBool1 :: FD s [Bool] testBool1 = do x <- newVar "X" [False, True] y <- newVar "Y" [False, True] z <- newVar "Z" [False, True] x `neq` y y `neq` z labelling [x, y, z] {-| Embedding variable into Traversable >>> evalFD testTraversable [[1,2],[1,3],[2,1],[2,3],[3,1],[3,2]] -} testTraversable :: FD s [Int] testTraversable = do vars <- newVarT "T" [[1..3], [1..3]] alldiffF vars labellingT vars {-| Test for Constraints with Multiple Type Variables (only simple labelling) >>> evalFD testMultiType0 [(1,False),(1,True),(2,False),(2,True),(3,False),(3,True)] -} testMultiType0 :: FD s (Int, Bool) testMultiType0 = do -- create variables for multiple types x <- newVar "X" [1..3] y <- newVar "Y" [False, True] -- labelling vx <- label x vy <- label y -- construct resolution return (vx, vy) {-| Example of Constraints with Multiple Type Variables -} mt :: Var s Int -> Var s Bool -> FD s () mt = arcConstraint mtConstraint mtConstraint :: ArcPropagator Int Bool mtConstraint vx vy = (vx', vy') where vx' = if single vy then if head . Set.toList $ vy then Set.filter (\x -> x `mod` 2 == 0) vx else Set.filter (\x -> x `mod` 2 /= 0) vx else vx vy' = if single vx then let vx1 = head . Set.toList $ vx in Set.fromList [vx1 `mod` 2 == 0] else vy {-| Test for Constraints with Multiple Type Variables >>> evalFD testMultiType1 [(1,False),(2,True),(3,False),(4,True),(5,False)] -} testMultiType1 :: FD s (Int, Bool) testMultiType1 = do -- create variables for multiple types x <- newVar "X" [1..5] y <- newVar "Y" [False, True] -- add constraint for multiple types x `mt` y -- labelling vx <- label x vy <- label y -- construct resolution return (vx, vy)
notae/haskell-exercise
cp/CFPFD1.hs
bsd-3-clause
15,778
0
17
4,069
6,353
3,301
3,052
399
4
{-# LANGUAGE NoImplicitPrelude #-} -- -- Scene -- module Aya.Scene ( smooth , iclip , traceDepth , xReso , yReso , xRegion , yRegion , eyepos , etarget , upper , focus , material0 , iAmb , lights , primitives ) where import Data.Maybe import NumericPrelude import Aya.Algebra import Aya.Color import Aya.Geometry import Aya.Mapping import Aya.Material import Aya.Object -- global parameters smooth = True iclip = 120 :: Double traceDepth = 6 :: Int xReso = 256 :: Int yReso = 256 :: Int xRegion = (-1.0, 1.0) yRegion = (-1.0, 1.0) eyepos = Vector3 4 5 (-3) etarget = Vector3 0 0 0 upper = Vector3 0 1 0 focus = 2.0 material0 = Material intensityZero colorBlack colorBlack colorWhite colorWhite 1 0 iAmb = initIntensity colorWhite 100 -- lights and primitives lights :: [Light] lights = [ DirectiveLight (Vector3 (-4) 7 (-1)) (initIntensity colorWhite 5000) (negate ey3) lp1 --, ParallelLight (Vector3 1 1 (-1)) (initIntensity colorWhite 20) , DirectiveLight (Vector3 2 6 5) (initIntensity colorWhite 3000) (negate ey3) lp2 ] lp1 = Primitive (fromJust $ initSphere (Vector3 (-1) 3 (-2)) 0.6) mplight lp2 = Primitive (fromJust $ initSphere (Vector3 1 3 5) 0.6) mplight primitives :: [Primitive] primitives = [ lp1, lp2 , Primitive (fromJust $ initPlain (Vector3 0 1 0) 2) mfloor , Primitive (fromJust $ initPlain (Vector3 0 (-1) 0) (50)) msky1 --, Primitive (fromJust $ initSphere (Vector3 (-0.5) (-0.5) 3.2) 1) mball1 , Primitive (fromJust $ initSphere (Vector3 (-2) 0 0) 1) mball2 , Primitive (fromJust $ initPolygon tp0 tp3 tp1) mtrans , Primitive (fromJust $ initPolygon tp0 tp3 tp2) mtrans , Primitive (fromJust $ initPolygon tp2 tp3 tp1) mtrans , Primitive (fromJust $ initPolygon tp0 tp2 tp1) mtest --, Primitive (fromJust $ initPolygon (Vector3 0.5 (-1) 0) (Vector3 0 (-0.5) 0) -- (Vector3 0 (-1) 0.5)) mtest --, Primitive (fromJust $ initPolygon (Vector3 0 (-1) 0.5) (Vector3 0 (-0.5) 0) -- (Vector3 (-0.5) (-1) 0)) mtest --, Primitive (fromJust $ initPolygon (Vector3 0 1 0) (Vector3 0.5 (-1) 0) -- (Vector3 (-0.5) (-1) 0)) mtrans --, Primitive (fromJust $ initPolygon (Vector3 0 1 0.3) -- (Vector3 (-0.5) (-1) 0.3) (Vector3 0.5 (-1) 0.3)) mtrans ] ----- -- details of primitives ----- plight = Material (initIntensity colorWhite 2000) colorBlack colorBlack colorBlack colorBlack 0 0 sky1 = Material intensityZero (initColor 0.7 0.9 1) colorBlack colorBlack colorBlack 0 0 floor1 = Material intensityZero (initColor 1 0.6 0) (initColor 0.5 0.5 0.5) colorBlack colorBlack 0 0 floor2 = Material intensityZero (initColor 1.0 1.0 0.6) (initColor 1 1 1) colorBlack colorBlack 0 0 ball1 = Material intensityZero (initColor 1 0.5 0.3) (initColor 0.5 1.0 0.8) colorBlack colorBlack 0 0 ball2 = Material intensityZero colorBlack colorWhite colorWhite (Color 1.51 1.51 1.51) 1.51 0 mirr1 = Material intensityZero colorBlack colorWhite colorBlack colorBlack 0 0 msam1 = Material intensityZero (initColor 0 0.2 0.2) colorWhite colorWhite (Color 1.51 1.51 1.51) 1.51 0 mplight = mapUni plight msky1 = mapUni sky1 mfloor = mapCheckXZ floor1 floor2 1 mball1 = mapUni ball1 mball2 = mapUni ball2 mtrans = mapUni ball2 mtest = mapUni msam1 -- Tetrapot -- tp0 = Vector3 0 0 0 tp1 = Vector3 1 0 1 tp2 = Vector3 1 1 0 tp3 = Vector3 0 1 1
eiji-a/aya
src/Aya/Scene-tetra_and_ball.hs
bsd-3-clause
3,537
0
13
846
1,005
541
464
84
1
{-# LANGUAGE PolyKinds #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE ExtendedDefaultRules #-} {-# OPTIONS_GHC -Wall #-} -- | A vector based on Representable module Tower.V where import qualified Protolude as P import Protolude (($), (<$>), Functor(..), Show, Eq(..), take) import Data.Distributive as D import Data.Functor.Rep import Data.Proxy (Proxy(..)) import GHC.TypeLits import qualified Data.List as List import qualified Data.Vector as V import Test.QuickCheck import Tower.Additive newtype V n a = V { toVector :: V.Vector a } deriving (Functor, Show, Eq, P.Foldable, P.Ord) instance (KnownNat n, Arbitrary a, AdditiveUnital a) => Arbitrary (V n a) where arbitrary = frequency [ (1, P.pure zero) , (9, toV <$> vector n) ] where n = P.fromInteger $ natVal (Proxy :: Proxy n) instance KnownNat n => D.Distributive (V n) where distribute f = V $ V.generate n $ \i -> fmap (\(V v) -> V.unsafeIndex v i) f where n = P.fromInteger $ natVal (Proxy :: Proxy n) instance KnownNat n => Representable (V n) where type Rep (V n) = P.Int tabulate = V P.. V.generate n0 where n0 = P.fromInteger $ natVal (Proxy :: Proxy n) index (V xs) i = xs V.! i -- | create a `V (n::Nat) a` padding with zeros if needed toV :: forall a n . (AdditiveUnital a, KnownNat n) => [a] -> V n a toV l = V $ V.fromList $ P.take n $ l P.++ P.repeat zero where n = P.fromInteger $ natVal (Proxy :: Proxy n) -- | create a V (m::Nat) (V (n::Nat) a), which is the natural form for an outer product toVV :: forall a m n. ( AdditiveUnital a , AdditiveUnital (V n a) , KnownNat m , KnownNat n) => [a] -> V m (V n a) toVV l = toV $ take m (toV <$> splitList) where n = P.fromInteger $ natVal (Proxy :: Proxy n) m = P.fromInteger $ natVal (Proxy :: Proxy m) splitList = List.unfoldr (\b -> case List.splitAt n b of ([],_) -> P.Nothing x -> P.Just x) $ l P.++ P.repeat zero
tonyday567/tower
src/Tower/V.hs
bsd-3-clause
2,080
0
16
554
772
423
349
-1
-1
module Language.Haskell.GhcMod.Lint where import Control.Applicative ((<$>)) import Control.Exception (handle, SomeException(..)) import Language.Haskell.GhcMod.Logger (checkErrorPrefix) import Language.Haskell.GhcMod.Convert import Language.Haskell.GhcMod.Types import Language.Haskell.HLint (hlint) -- | Checking syntax of a target file using hlint. -- Warnings and errors are returned. lintSyntax :: Options -> FilePath -- ^ A target file. -> IO String lintSyntax opt file = handle handler $ pack <$> hlint (file : "--quiet" : hopts) where pack = convert opt . map (init . show) -- init drops the last \n. hopts = hlintOpts opt handler (SomeException e) = return $ checkErrorPrefix ++ show e ++ "\n"
darthdeus/ghc-mod-ng
Language/Haskell/GhcMod/Lint.hs
bsd-3-clause
744
0
10
137
190
109
81
14
1
module Config.GetOpt ( Opts , MkCfg , optSpec , noArgs , contentDirDesc , Err ) where import Data.Monoid ( mappend ) import Control.Monad ( liftM, ap, guard ) import Config.Types ( ActionSpec(..), preUsage, CommandResult(..) , isHelpRequest ) import Config.Format ( wrap, indent ) import Data.Char ( isSpace ) import System.Console.GetOpt type Opts cfg = [OptDescr (Err (cfg -> cfg))] type MkCfg cfg = [String] -> Err cfg contentDirDesc :: (FilePath -> a) -> OptDescr a contentDirDesc f = Option "" ["content-dir"] (ReqArg f "DIR") "Where to find the marked up HTML files. Defaults to \ \the current working directory." optSpec :: String -> (cfg -> a) -> Opts cfg -> MkCfg cfg -> String -> ActionSpec a optSpec name mkAction osOpts osCfg desc = ActionSpec { asName = name , asDescr = desc , asParse = parseOptSpec } where actUsage = preUsage [usageInfo (unlines $ wrap 78 $ desc) osOpts] strip = reverse . dropWhile isSpace . reverse parseOptSpec args = let (os, args', es) = getOpt Permute osOpts args flgs = if null es then sequenceE os else Err $ map strip es ++ toErrors (sequenceE os) result xs = case (flgs, osCfg xs) of (Err es1, Err es2) -> Err $ es1 ++ es2 (_, cfg) -> foldr ($) `liftM` cfg `ap` flgs handle (Err msgs) = CommandFailed $ actUsage `mappend` preUsage ("Errors parsing arguments:":indent 2 msgs) handle (Val cfg) = CommandOk $ mkAction cfg accepted actArgs = if isHelpRequest actArgs then HelpRequest actUsage else handle $ result actArgs in case args' of (k:actArgs) -> guard (k == name) >> return (accepted actArgs) _ -> Nothing noArgs :: a -> [String] -> Err a noArgs x [] = return x noArgs _ args = fail $ "Unexpected arguments: " ++ show args -- Error monad (like either) data Err a = Err [String] | Val a instance Monad Err where return = Val fail = Err . return (Err s) >>= _ = Err s (Val x) >>= f = f x sequenceE :: [Err a] -> Err [a] sequenceE xs = case errs xs of ([], as) -> Val as (es, _) -> Err es -- Partition errors and successes errs :: [Err a] -> ([String], [a]) errs (x:xs) = let (es, as) = errs xs in case x of Err e -> (e ++ es, as) Val x' -> (es, x':as) errs [] = ([], []) toErrors :: Err a -> [String] toErrors (Err es) = es toErrors _ = []
j3h/doc-review
src/Config/GetOpt.hs
bsd-3-clause
2,868
0
16
1,098
980
522
458
71
6
{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE RecordWildCards #-} module Astro.Orbit.AnomalySpec where import Test.Hspec import Test.QuickCheck (property, (==>)) import Data.AEq import TestUtil import TestInstances import Numeric.Units.Dimensional.Prelude import Numeric.Units.Dimensional.LinearAlgebra import qualified Prelude import Astro.Orbit.Types import Astro.Orbit.Anomaly main = hspec spec spec = do spec_anomalyComparison spec_anomalyConversion -- ---------------------------------------------------------- spec_anomalyComparison = describe "Anomaly comparisons" $ do it "-pi and pi should be equal" (Anom (negate pi) == Anom pi) it "-pi and pi should be approximately equal" (Anom (negate pi::Angle Double) ~== Anom pi) it "0 and 2*pi should be equal" (Anom _0 == Anom (_2*pi)) it "0 and 2*pi should be approximately equal" (Anom _0 ~== Anom (_2*pi::Angle Double)) it "x and x+2*pi should be equal." (property $ \t -> Anom t ~== Anom (t + _2*pi::Angle Double)) -- ---------------------------------------------------------- spec_anomalyConversion = describe "Anomaly conversions" $ do it "Two ways of computing eccentric anomaly from true anomaly" (property $ \e' t -> let e = fractionalPart e' in eccAnomaly1 e t ~== eccAnomaly2 e t) it "Converting TA to EA and back should not change it." (property $ \e' t -> let e = Ecc $ fractionalPart e' in (ea2ta e . ta2ea e) t ~== t) it "At perigee TA and EA should be equally 0." (property $ \e' -> let e = Ecc $ fractionalPart e' in ta2ea e ta0 == ea0 && ea2ta e ea0 == ta0) it "At apogee TA and EA should be equally pi." (property $ \e' -> let e = Ecc $ fractionalPart e' in ta2ea e (Anom pi) ~== Anom pi && ea2ta e (Anom pi) == Anom pi) it "For circular orbit TA and EA should be equal." (property $ \a -> ta2ea e0 (Anom a) ~== Anom a && ea2ta e0 (Anom a) ~== Anom a) it "Converting EA to MA and back should not change it." (property $ \e' ea -> let e = Ecc $ fractionalPart e' in (ma2ea e . ea2ma e) ea ~== ea) it "At perigee EA and MA should be equally 0." (property $ \e' -> let e = Ecc $ fractionalPart e' in ea2ma e ea0 == ma0 && ma2ea e ma0 == ea0) it "At apogee EA and MA should be equally pi." (property $ \e' -> let e = Ecc $ fractionalPart e' in ea2ma e (Anom pi) == Anom pi && ma2ea e (Anom pi) == Anom pi) it "For circular orbit EA and MA should be equal." (property $ \a -> ea2ma e0 (Anom a) ~== Anom a && ma2ea e0 (Anom a) ~== Anom a) where e0 = Ecc _0 :: Eccentricity Double ta0 = Anom _0 :: Anomaly True Double ea0 = Anom _0 :: Anomaly Ecc Double ma0 = Anom _0 :: Anomaly Mean Double -- | Compute eccentric anomaly using atan. eccAnomaly1 :: Dimensionless Double -> Angle Double -> Angle Double eccAnomaly1 e t = _2 * atan (sqrt ((_1 - e) / (_1 + e)) * tan (t / _2)) -- | Compute eccentric anomaly using atan2. eccAnomaly2 :: Dimensionless Double -> Angle Double -> Angle Double eccAnomaly2 e t = atan2 (sqrt (_1 - e ^ pos2) * sin t) (e + cos t)
bjornbm/astro-orbit
test/Astro/Orbit/AnomalySpec.hs
bsd-3-clause
3,098
0
19
705
1,067
521
546
62
1
{-# LANGUAGE OverloadedStrings , ScopedTypeVariables #-} module Routes where import Pages import Pages.Home import Pages.Contact import Pages.NotFound import Application.Types import Templates.Master import Web.Routes.Nested import Network.HTTP.Types routes :: RoutableT s e u ue ClarkT () routes = do here $ action $ get $ htmlLight status200 $ masterTemplate (Just HomeNav) (masterPage `appendTitle` "Home") homeContent handle ("contact" </> o_) $ action $ get $ htmlLight status200 $ masterTemplate (Just ContactNav) (masterPage `appendTitle` "Contact") contactContent handle ("about" </> o_) $ action $ get $ htmlLight status200 $ mdPage (Just (AboutNav Nothing)) "pages/about.md" "About" notFound $ action $ get $ do htmlLight status404 notFoundContent text $ "404 :("
athanclark/clark-mining-tech
src/Routes.hs
bsd-3-clause
885
0
13
215
249
128
121
32
1
module Rubik.Cube where import Data.Array as A import Control.Applicative import Rubik.Key as K import Rubik.Turn as T import Rubik.Axis as V import Rubik.Sign as S import Rubik.D3 as D3 data Side = F | U | R | D | L | B deriving (Eq,Ord,Enum,Show,Ix) sides :: [Side] sides = [F .. B] instance Key Side where universe = sides type Cube a = Axis D3 -> a -- Where is this side placed on a 2D plane. cubePlacement :: Cube (Int,Int) cubePlacement = f where f (Axis X Plus) = (2,1) f (Axis X Minus) = (0,1) f (Axis Y Plus) = (1,0) f (Axis Y Minus) = (1,2) f (Axis Z Plus) = (1,1) f (Axis Z Minus) = (3,1) {- sideToAxis :: Side -> Axis D3 sideToAxis F = Axis D3.Z Plus sideToAxis B = Axis D3.Z Minus sideToAxis U = Axis D3.Y Plus sideToAxis D = Axis D3.Y Minus sideToAxis R = Axis D3.X Plus sideToAxis L = Axis D3.X Minus axisToSize :: Axis D3 -> Side axisToSize :: Axis D3 -> Side --clockwiseCube :: Side -> Side -> Side --clockwiseCube view start = turnD3 --rotateBy :: F -> F -> F -} -- Which way does the faces orietate? cubeFaceDir :: Cube (Axis D3,Axis D3) cubeFaceDir = f where f (Axis X Plus) = (Axis Z Minus,Axis Y Plus) f (Axis X Minus) = (Axis Z Plus,Axis Y Plus) f (Axis Y Plus) = (Axis X Plus,Axis Z Minus) f (Axis Y Minus) = (Axis X Plus,Axis Z Plus) f (Axis Z Plus) = (Axis X Plus,Axis Y Plus) f (Axis Z Minus) = (Axis X Minus,Axis Y Plus) {- side -> rotate the -}
andygill/rubik-solver
src/Rubik/Cube.hs
bsd-3-clause
1,481
2
9
387
522
289
233
31
6
module Main where import Language.Bang.Compiler (cliMain) main :: IO () main = cliMain
ajscholl/bang
cli/Main.hs
bsd-3-clause
89
0
6
15
30
18
12
4
1