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
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE InstanceSigs #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TypeFamilies #-} -- | This module provides the execution of DSH queries as SQL query bundles and the -- construction of nested values from the resulting vector bundle. module Database.DSH.Backend.Sql ( -- * Show and tell: display relational plans. showUnorderedQ , showUnorderedOptQ , showRelationalQ , showRelationalOptQ -- , showTabularQ -- * Various SQL code generators , module Database.DSH.Backend.Sql.CodeGen -- * A PostgreSQL ODBC backend , module Database.DSH.Backend.Sql.Pg -- * SQL backend vectors , module Database.DSH.Backend.Sql.Vector ) where import Control.Monad import qualified System.Info as Sys import System.Process import System.Random import Text.Printf import qualified Database.DSH as DSH import Database.DSH.Common.Pretty import Database.DSH.Common.QueryPlan import Database.DSH.Compiler import Database.DSH.SL import Database.Algebra.Dag import qualified Database.Algebra.Table.Lang as TA import qualified Database.Algebra.Table.Typing as TY import Database.DSH.Backend.Sql.CodeGen import qualified Database.DSH.Backend.Sql.MultisetAlgebra as MA import qualified Database.DSH.Backend.Sql.Opt as TAOpt import Database.DSH.Backend.Sql.Pg import Database.DSH.Backend.Sql.Unordered import Database.DSH.Backend.Sql.Vector {-# ANN module "HLint: ignore Reduce duplication" #-} -------------------------------------------------------------------------------- fileId :: IO String fileId = replicateM 8 (randomRIO ('a', 'z')) pdfCmd :: String -> String pdfCmd f = case Sys.os of "linux" -> "evince " ++ f "darwin" -> "open " ++ f sys -> error $ "pdfCmd: unsupported os " ++ sys typeCheckMA :: String -> AlgebraDag MA.MA -> IO () typeCheckMA flavor dag = case MA.inferMATypes dag of Left msg -> putStrLn $ printf "Type inference failed for %s MA plan\n%s" flavor msg Right _ -> putStrLn $ printf "Type inference successful for %s MA plan" flavor typeCheckTA :: String -> AlgebraDag TA.TableAlgebra -> IO () typeCheckTA flavor dag = case TY.inferTATypes dag of Left msg -> putStrLn $ printf "Type inference failed for %s TA plan\n%s" flavor msg Right _ -> putStrLn $ printf "Type inference successful for %s TA plan" flavor showMAPlan :: QueryPlan MA.MA MADVec -> IO () showMAPlan maPlan = do prefix <- ("q_ma_" ++) <$> fileId exportPlan prefix maPlan void $ runCommand $ printf "stack exec madot -- -i %s.plan | dot -Tpdf -o %s.pdf && %s" prefix prefix (pdfCmd $ prefix ++ ".pdf") showTAPlan :: QueryPlan TA.TableAlgebra TADVec -> IO () showTAPlan taPlan = do prefix <- ("q_ta_" ++) <$> fileId exportPlan prefix taPlan void $ runCommand $ printf "stack exec tadot -- -i %s.plan | dot -Tpdf -o %s.pdf && %s" prefix prefix (pdfCmd $ prefix ++ ".pdf") -- | Show the unoptimized multiset algebra plan showUnorderedQ :: VectorLang v => CLOptimizer -> MAPlanGen (v TExpr TExpr) -> DSH.Q a -> IO () showUnorderedQ clOpt maGen q = do let vectorPlan = vectorPlanQ clOpt q maPlan = maGen vectorPlan typeCheckMA "unoptimized" (queryDag maPlan) showMAPlan maPlan putStrLn $ pp $ queryShape maPlan -- | Show the optimized multiset algebra plan showUnorderedOptQ :: VectorLang v => CLOptimizer -> MAPlanGen (v TExpr TExpr) -> DSH.Q a -> IO () showUnorderedOptQ clOpt maGen q = do let vectorPlan = vectorPlanQ clOpt q let maPlan = maGen vectorPlan typeCheckMA "unoptimized" (queryDag maPlan) let maPlanOpt = MA.optimizeMA maPlan typeCheckMA "optimized" (queryDag maPlanOpt) showMAPlan maPlanOpt putStrLn $ pp $ queryShape maPlanOpt -- | Show the unoptimized table algebra plan showRelationalQ :: VectorLang v => CLOptimizer -> MAPlanGen (v TExpr TExpr) -> DSH.Q a -> IO () showRelationalQ clOpt maGen q = do let vectorPlan = vectorPlanQ clOpt q let maPlan = maGen vectorPlan typeCheckMA "unoptimized" (queryDag maPlan) let maPlanOpt = MA.optimizeMA maPlan typeCheckMA "optimized" (queryDag maPlanOpt) let taPlan = MA.flattenMAPlan maPlanOpt typeCheckTA "unoptimized" (queryDag taPlan) showTAPlan taPlan putStrLn $ pp $ queryShape taPlan -- | Show the unoptimized table algebra plan showRelationalOptQ :: VectorLang v => CLOptimizer -> MAPlanGen (v TExpr TExpr) -> DSH.Q a -> IO () showRelationalOptQ clOpt maGen q = do let vectorPlan = vectorPlanQ clOpt q let maPlan = maGen vectorPlan typeCheckMA "unoptimized" (queryDag maPlan) let maPlanOpt = MA.optimizeMA maPlan typeCheckMA "optimized" (queryDag maPlanOpt) let taPlan = MA.flattenMAPlan maPlanOpt typeCheckTA "unoptimized" (queryDag taPlan) let taPlanOpt = TAOpt.optimizeTA TAOpt.defaultPipeline taPlan typeCheckTA "optimized" (queryDag taPlanOpt) showTAPlan taPlanOpt putStrLn $ pp $ queryShape taPlanOpt -- -- | Show raw tabular results via 'psql', executed on the specified -- -- database.. -- showTabularQ :: VectorLang v -- => CLOptimizer -- -> (QueryPlan v DVec -> Shape (SqlVector PgCode)) -- -> String -- -> DSH.Q a -- -> IO () -- showTabularQ clOpt pgCodeGen dbName q = -- forM_ (codeQ clOpt pgCodeGen q) $ \sql -> do -- putStrLn "" -- h <- fileId -- let queryFile = printf "q_%s.sql" h -- writeFile queryFile $ unPg $ vecCode sql -- hdl <- runCommand $ printf "psql %s < %s" dbName queryFile -- void $ waitForProcess hdl -- putStrLn sepLine -- where -- sepLine = replicate 80 '-'
ulricha/dsh-sql
src/Database/DSH/Backend/Sql.hs
bsd-3-clause
5,960
0
11
1,454
1,277
657
620
102
3
----------------------------------------------------------------------------- -- | -- Copyright : (C) 2015 Dimitri Sabadie -- License : BSD3 -- -- Maintainer : Dimitri Sabadie <dimitri.sabadie@gmail.com> -- Stability : experimental -- Portability : portable ---------------------------------------------------------------------------- module Graphics.Luminance.Vertex where import Control.Monad.IO.Class ( MonadIO(..) ) import Data.Proxy ( Proxy(..) ) import Foreign.Marshal.Array ( peekArray, pokeArray ) import Foreign.Ptr ( Ptr, castPtr ) import Foreign.Storable ( Storable(..) ) import GHC.TypeLits ( KnownNat, Nat, natVal ) import Graphics.GL import Graphics.Luminance.GPU import Graphics.Luminance.Tuple data V :: Nat -> * -> * where V1 :: !a -> V 1 a V2 :: !a -> !a -> V 2 a V3 :: !a -> !a -> !a -> V 3 a V4 :: !a -> !a -> !a -> !a -> V 4 a instance (Storable a) => Storable (V 1 a) where sizeOf _ = sizeOf (undefined :: a) alignment _ = alignment (undefined :: a) peek p = fmap V1 $ peek (castPtr p :: Ptr a) poke p (V1 x) = poke (castPtr p) x instance (Storable a) => Storable (V 2 a) where sizeOf _ = 2 * sizeOf (undefined :: a) alignment _ = alignment (undefined :: a) peek p = do [x,y] <- peekArray 2 (castPtr p :: Ptr a) pure $ V2 x y poke p (V2 x y) = pokeArray (castPtr p) [x,y] instance (Storable a) => Storable (V 3 a) where sizeOf _ = 3 * sizeOf (undefined :: a) alignment _ = alignment (undefined :: a) peek p = do [x,y,z] <- peekArray 3 (castPtr p :: Ptr a) pure $ V3 x y z poke p (V3 x y z) = pokeArray (castPtr p) [x,y,z] instance (Storable a) => Storable (V 4 a) where sizeOf _ = 4 * sizeOf (undefined :: a) alignment _ = alignment (undefined :: a) peek p = do [x,y,z,w] <- peekArray 4 (castPtr p :: Ptr a) pure $ V4 x y z w poke p (V4 x y z w) = pokeArray (castPtr p) [x,y,z,w] class Vertex v where setFormatV :: (MonadIO m) => GLuint -> GLuint -> proxy v -> m () instance (GPU a,KnownNat n,Storable a) => Vertex (V n a) where setFormatV vid index _ = do glVertexArrayAttribFormat vid index (fromIntegral $ natVal (Proxy :: Proxy n)) (glType (Proxy :: Proxy a)) GL_FALSE 0 glVertexArrayAttribBinding vid index vertexBindingIndex glEnableVertexArrayAttrib vid index instance (Vertex a,Vertex b) => Vertex (a :. b) where setFormatV vid index _ = do setFormatV vid index (Proxy :: Proxy a) setFormatV vid index (Proxy :: Proxy b) vertexBindingIndex :: GLuint vertexBindingIndex = 0
apriori/luminance
src/Graphics/Luminance/Vertex.hs
bsd-3-clause
2,513
22
13
536
1,060
555
505
-1
-1
-- |The Vectorisation monad. module Vectorise.Monad.Base ( -- * The Vectorisation Monad VResult(..), VM(..), -- * Lifting liftDs, -- * Error Handling cantVectorise, maybeCantVectorise, maybeCantVectoriseM, -- * Debugging emitVt, traceVt, dumpOptVt, dumpVt, -- * Control noV, traceNoV, ensureV, traceEnsureV, onlyIfV, tryV, tryErrV, maybeV, traceMaybeV, orElseV, orElseErrV, fixV, ) where import Vectorise.Builtins import Vectorise.Env import DsMonad import TcRnMonad import ErrUtils import Outputable import DynFlags import Control.Monad -- The Vectorisation Monad ---------------------------------------------------- -- |Vectorisation can either succeed with new envionment and a value, or return with failure -- (including a description of the reason for failure). -- data VResult a = Yes GlobalEnv LocalEnv a | No SDoc newtype VM a = VM { runVM :: Builtins -> GlobalEnv -> LocalEnv -> DsM (VResult a) } instance Monad VM where return x = VM $ \_ genv lenv -> return (Yes genv lenv x) VM p >>= f = VM $ \bi genv lenv -> do r <- p bi genv lenv case r of Yes genv' lenv' x -> runVM (f x) bi genv' lenv' No reason -> return $ No reason instance Applicative VM where pure = return (<*>) = ap instance Functor VM where fmap = liftM instance MonadIO VM where liftIO = liftDs . liftIO instance HasDynFlags VM where getDynFlags = liftDs getDynFlags -- Lifting -------------------------------------------------------------------- -- |Lift a desugaring computation into the vectorisation monad. -- liftDs :: DsM a -> VM a liftDs p = VM $ \_ genv lenv -> do { x <- p; return (Yes genv lenv x) } -- Error Handling ------------------------------------------------------------- -- |Throw a `pgmError` saying we can't vectorise something. -- cantVectorise :: DynFlags -> String -> SDoc -> a cantVectorise dflags s d = pgmError . showSDoc dflags $ vcat [text "*** Vectorisation error ***", nest 4 $ sep [text s, nest 4 d]] -- |Like `fromJust`, but `pgmError` on Nothing. -- maybeCantVectorise :: DynFlags -> String -> SDoc -> Maybe a -> a maybeCantVectorise dflags s d Nothing = cantVectorise dflags s d maybeCantVectorise _ _ _ (Just x) = x -- |Like `maybeCantVectorise` but in a `Monad`. -- maybeCantVectoriseM :: (Monad m, HasDynFlags m) => String -> SDoc -> m (Maybe a) -> m a maybeCantVectoriseM s d p = do r <- p case r of Just x -> return x Nothing -> do dflags <- getDynFlags cantVectorise dflags s d -- Debugging ------------------------------------------------------------------ -- |Output a trace message if -ddump-vt-trace is active. -- emitVt :: String -> SDoc -> VM () emitVt herald doc = liftDs $ do dflags <- getDynFlags liftIO . printInfoForUser dflags alwaysQualify $ hang (text herald) 2 doc -- |Output a trace message if -ddump-vt-trace is active. -- traceVt :: String -> SDoc -> VM () traceVt herald doc = do dflags <- getDynFlags when (1 <= traceLevel dflags) $ liftDs $ traceOptIf Opt_D_dump_vt_trace $ hang (text herald) 2 doc -- |Dump the given program conditionally. -- dumpOptVt :: DynFlag -> String -> SDoc -> VM () dumpOptVt flag header doc = do { b <- liftDs $ doptM flag ; if b then dumpVt header doc else return () } -- |Dump the given program unconditionally. -- dumpVt :: String -> SDoc -> VM () dumpVt header doc = do { unqual <- liftDs mkPrintUnqualifiedDs ; dflags <- liftDs getDynFlags ; liftIO $ printInfoForUser dflags unqual (mkDumpDoc header doc) } -- Control -------------------------------------------------------------------- -- |Return some result saying we've failed. -- noV :: SDoc -> VM a noV reason = VM $ \_ _ _ -> return $ No reason -- |Like `traceNoV` but also emit some trace message to stderr. -- traceNoV :: String -> SDoc -> VM a traceNoV s d = pprTrace s d $ noV d -- |If `True` then carry on, otherwise fail. -- ensureV :: SDoc -> Bool -> VM () ensureV reason False = noV reason ensureV _reason True = return () -- |Like `ensureV` but if we fail then emit some trace message to stderr. -- traceEnsureV :: String -> SDoc -> Bool -> VM () traceEnsureV s d False = traceNoV s d traceEnsureV _ _ True = return () -- |If `True` then return the first argument, otherwise fail. -- onlyIfV :: SDoc -> Bool -> VM a -> VM a onlyIfV reason b p = ensureV reason b >> p -- |Try some vectorisation computaton. -- -- If it succeeds then return `Just` the result; otherwise, return `Nothing` after emitting a -- failure message. -- tryErrV :: VM a -> VM (Maybe a) tryErrV (VM p) = VM $ \bi genv lenv -> do r <- p bi genv lenv case r of Yes genv' lenv' x -> return (Yes genv' lenv' (Just x)) No reason -> do { unqual <- mkPrintUnqualifiedDs ; dflags <- getDynFlags ; liftIO $ printInfoForUser dflags unqual $ text "Warning: vectorisation failure:" <+> reason ; return (Yes genv lenv Nothing) } -- |Try some vectorisation computaton. -- -- If it succeeds then return `Just` the result; otherwise, return `Nothing` without emitting a -- failure message. -- tryV :: VM a -> VM (Maybe a) tryV (VM p) = VM $ \bi genv lenv -> do r <- p bi genv lenv case r of Yes genv' lenv' x -> return (Yes genv' lenv' (Just x)) No _reason -> return (Yes genv lenv Nothing) -- |If `Just` then return the value, otherwise fail. -- maybeV :: SDoc -> VM (Maybe a) -> VM a maybeV reason p = maybe (noV reason) return =<< p -- |Like `maybeV` but emit a message to stderr if we fail. -- traceMaybeV :: String -> SDoc -> VM (Maybe a) -> VM a traceMaybeV s d p = maybe (traceNoV s d) return =<< p -- |Try the first computation, -- -- * if it succeeds then take the returned value, -- * if it fails then run the second computation instead while emitting a failure message. -- orElseErrV :: VM a -> VM a -> VM a orElseErrV p q = maybe q return =<< tryErrV p -- |Try the first computation, -- -- * if it succeeds then take the returned value, -- * if it fails then run the second computation instead without emitting a failure message. -- orElseV :: VM a -> VM a -> VM a orElseV p q = maybe q return =<< tryV p -- |Fixpoint in the vectorisation monad. -- fixV :: (a -> VM a) -> VM a fixV f = VM (\bi genv lenv -> fixDs $ \r -> runVM (f (unYes r)) bi genv lenv ) where -- NOTE: It is essential that we are lazy in r above so do not replace -- calls to this function by an explicit case. unYes (Yes _ _ x) = x unYes (No reason) = pprPanic "Vectorise.Monad.Base.fixV: no result" reason
nomeata/ghc
compiler/vectorise/Vectorise/Monad/Base.hs
bsd-3-clause
7,104
0
17
1,963
1,862
959
903
129
2
{-# OPTIONS_GHC -fno-warn-missing-signatures #-} {-# OPTIONS_GHC -fno-warn-type-defaults #-} module Main where import Util import System.Exit ( exitFailure, exitSuccess ) import Test.HUnit testTakeUntil = "takeUntil" ~: [takeUntil (> 2) [2, 3] ~=? [2, 3]] testTwo = [testTakeUntil] main = do cnt <- runTestTT (test testTwo) if errors cnt + failures cnt == 0 then exitSuccess else exitFailure
guillaume-nargeot/hpc-coveralls-testing2
test2/TestTwo.hs
bsd-3-clause
421
0
10
85
118
67
51
13
2
{-# LANGUAGE UnicodeSyntax #-} import Prelude.Unicode data Tree a = Empty | Branch a (Tree a) (Tree a) deriving (Show, Eq) type TreeRes a = Tree (a, (Int, Int)) tree7 = Branch 'a' (Branch 'b' (Branch 'c' Empty Empty) (Branch 'd' Empty Empty)) (Branch 'e' (Branch 'f' Empty Empty) (Branch 'g' Empty Empty)) tree65 = Branch 'n' (Branch 'k' (Branch 'c' (Branch 'a' Empty Empty) (Branch 'e' (Branch 'd' Empty Empty) (Branch 'g' Empty Empty) ) ) (Branch 'm' Empty Empty) ) (Branch 'u' (Branch 'p' Empty (Branch 'q' Empty Empty) ) Empty )
m00nlight/99-problems
haskell/p-66.hs
bsd-3-clause
1,079
3
12
640
273
133
140
22
1
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE FlexibleInstances #-} module Database.Relational.Schema.SQLServerSyscat.Indexes where --import Data.ByteString (ByteString) import Data.Int (Int32) import Database.Record.TH (derivingShow) import Database.Relational.Query.TH (defineTableTypesAndRecordDefault) $(defineTableTypesAndRecordDefault "sys" "indexes" [ -- View "sys.indexes" -- column schema type length NULL -- --------------------- ------- ------------------- -------- ------ -- object_id sys int 4 No ("object_id", [t|Int32|]), -- name sys sysname(nvarchar) 128 Yes --("name", [t|Maybe String|]), -- index_id sys int 4 No ("index_id", [t|Int32|]), -- type sys tinyint 1 No --("type", [t|Char|]), -- type_desc sys nvarchar 60 Yes --("type_desc", [t|Maybe String|]), -- is_unique sys bit 1 Yes --("is_unique", [t|Maybe Bool|]), -- data_space_id sys int 4 No --("data_space_id", [t|Int32|]), -- ignore_dup_key sys bit 1 Yes --("ignore_dup_key", [t|Maybe Bool|]), -- is_primary_key sys bit 1 Yes ("is_primary_key", [t|Maybe Bool|])--, -- is_unique_constraint sys bit 1 Yes --("is_unique_constraint", [t|Maybe Bool|]), -- fill_factor sys tinyint 1 No --("fill_factor", [t|Int32|]), -- is_padded sys bit 1 Yes --("is_padded", [t|Maybe Bool|]), -- is_disabled sys bit 1 Yes --("is_disabled", [t|Maybe Bool|]), -- is_hypothetical sys bit 1 Yes --("is_hypothetical", [t|Maybe Bool|]), -- allow_row_locks sys bit 1 Yes --("allow_row_locks", [t|Maybe Bool|]), -- allow_page_locks sys bit 1 Yes --("allow_page_locks", [t|Maybe Bool|]), -- has_filter sys bit 1 Yes --("has_filter", [t|Maybe Bool|]), -- filter_definition sys nvarchar max Yes --("filter_definition", [t|Maybe ByteString|]) ] [derivingShow])
yuga/haskell-relational-record-driver-sqlserver
src/Database/Relational/Schema/SQLServerSyscat/Indexes.hs
bsd-3-clause
2,438
0
9
936
140
107
33
13
0
{-# LANGUAGE OverloadedStrings #-} ----------------------------------------------------------------------------- -- | -- Module : Hasmin.Types.FilterFunction -- Copyright : (c) 2017 Cristian Adrián Ontivero -- License : BSD3 -- Stability : experimental -- Portability : unknown -- ----------------------------------------------------------------------------- module Hasmin.Types.FilterFunction ( FilterFunction(..) , minifyPseudoShadow ) where import Control.Monad.Reader (Reader, ask) import Data.Monoid ((<>)) import Data.Text.Lazy.Builder (singleton, Builder) import Hasmin.Class import Hasmin.Config import Hasmin.Types.Color import Hasmin.Types.Dimension import Hasmin.Types.Numeric -- The CSS spec calls it <number-percentage>, amount comes from the mozilla -- docs. type Amount = Either Number Percentage -- | CSS <https://drafts.fxtf.org/filter-effects/#typedef-filter-function \<filter-function\>> -- data type. data FilterFunction = Blur Length | Brightness Amount | Contrast Amount | Grayscale Amount | Invert Amount | Opacity Amount | Saturate Amount | Sepia Amount | HueRotate Angle | DropShadow Length Length (Maybe Length) (Maybe Color) deriving (Show) instance Eq FilterFunction where Blur a == Blur b = a == b Brightness a == Brightness b = filterFunctionEquality a b Contrast a == Contrast b = filterFunctionEquality a b Grayscale a == Grayscale b = filterFunctionEquality a b Invert a == Invert b = filterFunctionEquality a b Opacity a == Opacity b = filterFunctionEquality a b Saturate a == Saturate b = filterFunctionEquality a b Sepia a == Sepia b = filterFunctionEquality a b HueRotate a == HueRotate b = a == b DropShadow a b c d == DropShadow e f g h = a == e && b == f && d == h && c `thirdValueEq` g where thirdValueEq Nothing (Just n) | isZeroLen n = True thirdValueEq (Just n) Nothing | isZeroLen n = True thirdValueEq x y = x == y _ == _ = False instance ToText FilterFunction where toBuilder (Blur d) = "blur(" <> toBuilder d <> singleton ')' toBuilder (Brightness np) = "brightness(" <> toBuilder np <> singleton ')' toBuilder (HueRotate a) = "hue-rotate(" <> toBuilder a <> singleton ')' toBuilder (Contrast np) = "contrast(" <> toBuilder np <> singleton ')' toBuilder (Grayscale np) = "grayscale(" <> toBuilder np <> singleton ')' toBuilder (Invert np) = "invert(" <> toBuilder np <> singleton ')' toBuilder (Opacity np) = "opacity(" <> toBuilder np <> singleton ')' toBuilder (Saturate np) = "saturate(" <> toBuilder np <> singleton ')' toBuilder (Sepia np) = "sepia(" <> toBuilder np <> singleton ')' toBuilder (DropShadow l1 l2 ml mc) = let maybeToBuilder :: ToText a => Maybe a -> Builder maybeToBuilder = maybe mempty (\x -> singleton ' ' <> toBuilder x) in "drop-shadow(" <> toBuilder l1 <> singleton ' ' <> toBuilder l2 <> maybeToBuilder ml <> maybeToBuilder mc <> singleton ')' instance Minifiable FilterFunction where minify (Blur a) = Blur <$> minify a minify (HueRotate a) = HueRotate <$> minify a minify (Contrast x) = Contrast <$> minifyNumberPercentage x minify (Brightness x) = Brightness <$> minifyNumberPercentage x minify (Grayscale x) = Grayscale <$> minifyNumberPercentage x minify (Invert x) = Invert <$> minifyNumberPercentage x minify (Opacity x) = Opacity <$> minifyNumberPercentage x minify (Saturate x) = Saturate <$> minifyNumberPercentage x minify (Sepia x) = Sepia <$> minifyNumberPercentage x minify s@(DropShadow a b c d) = do conf <- ask if shouldMinifyFilterFunctions conf then minifyPseudoShadow DropShadow a b c d else pure s minifyPseudoShadow :: (Minifiable b, Minifiable t1, Minifiable t2, Traversable t) => (t2 -> t1 -> Maybe Length -> t b -> b1) -> t2 -> t1 -> Maybe Length -> t b -> Reader Config b1 minifyPseudoShadow constr a b c d = do x <- minify a y <- minify b z <- case c of Just r -> if isZeroLen r then pure Nothing else traverse minify c Nothing -> pure Nothing c2 <- traverse minify d pure $ constr x y z c2 minifyNumberPercentage :: Amount -> Reader Config Amount minifyNumberPercentage x = do conf <- ask pure $ if shouldMinifyFilterFunctions conf then either convertNumber convertPercentage x else x where convertNumber n | 0 < n && n < 0.1 = Right $ toPercentage (n * 100) | otherwise = Left n convertPercentage p | p == 0 = Left 0 | 0 < p && p < 10 = Right p | otherwise = Left $ toNumber (p / 100) filterFunctionEquality :: Amount -> Amount -> Bool filterFunctionEquality (Left a) (Left b) = toRational a == toRational b filterFunctionEquality (Right a) (Right b) = toRational a == toRational b filterFunctionEquality (Left a) (Right b) = toRational a == toRational b/100 filterFunctionEquality (Right a) (Left b) = toRational a/100 == toRational b
contivero/hasmin
src/Hasmin/Types/FilterFunction.hs
bsd-3-clause
5,629
0
14
1,727
1,687
814
873
101
3
module Problem187 where import Prime import qualified Data.Map.Strict as M n :: Int n = 10 ^ 8 ps :: [Int] ps = getPrimesUpto n ps' :: M.Map Int Int ps' = M.fromAscList $ zip ps [1 ..] main :: IO () -- p*q < n & p<=q => p^2<n & q < ceil[n/p] main = print $ go (zip (takeWhile (\p -> p * p < n) ps) [1 ..]) (reverse $ zip ps [1 ..]) where go [] _ = 0 go ((p, np) : ps) qs = let qs'@((_, nq) : _) = go' p qs in (nq - np + 1) + go ps qs' go' p qs@((q, _) : qs') | p * q >= n = go' p qs' | otherwise = qs
adityagupta1089/Project-Euler-Haskell
src/problems/Problem187.hs
bsd-3-clause
543
0
14
171
299
162
137
17
2
module Main (main) where import Test.DocTest main :: IO () main = doctest ["-isrc", "src/Music/Theory/Note.hs"]
daoo/musictheory
tests/DocTest.hs
bsd-3-clause
114
0
6
17
38
22
16
4
1
{-| Copyright : (c) Dave Laing, 2017 License : BSD3 Maintainer : dave.laing.80@gmail.com Stability : experimental Portability : non-portable -} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE OverloadedStrings #-} module Ast.Term.Var ( HasTmVarSupply(..) , ToTmVar(..) , freshTmVar ) where import Control.Monad.State (MonadState) import Control.Lens (Lens', use, (%=)) import qualified Data.Text as T class HasTmVarSupply s where tmVarSupply :: Lens' s Int instance HasTmVarSupply Int where tmVarSupply = id class ToTmVar a where toTmVar :: Int -> a instance ToTmVar String where toTmVar x = 'x' : show x instance ToTmVar T.Text where toTmVar x = T.append "x" (T.pack . show $ x) freshTmVar :: (MonadState s m, HasTmVarSupply s, ToTmVar a) => m a freshTmVar = do x <- use tmVarSupply tmVarSupply %= succ return $ toTmVar x
dalaing/type-systems
src/Ast/Term/Var.hs
bsd-3-clause
904
0
10
174
241
132
109
25
1
{-# LANGUAGE CPP, NoImplicitPrelude, NoMonomorphismRestriction, RankNTypes #-} {-# OPTIONS -Wall #-} -- | an extension of the standard Prelude for paraiso. module Language.Paraiso.Prelude ( Boolean(..), Text, showT, (++)) where {- import Control.Applicative (Applicative(..), (<$>)) import Control.Monad hiding (mapM_, sequence_, forM_, msum, mapM, sequence, forM) -} import qualified Data.Text as Text import qualified NumericPrelude as Prelude import NumericPrelude hiding ((++), (||), (&&), not) import qualified Prelude -- | An efficient String that is used thoroughout Paraiso modules. type Text = Text.Text showT :: Show a => a -> Text showT = Text.pack . show infixr 3 && infixr 2 || infixr 5 ++ class Appendable a where (++) :: a -> a -> a instance Appendable [a] where (++) = (Prelude.++) instance Appendable Text.Text where (++) = Text.append class Boolean b where true, false :: b not :: b -> b (&&), (||) :: b -> b -> b instance Boolean Bool where true = True false = False not = Prelude.not (&&) = (Prelude.&&) (||) = (Prelude.||)
nushio3/Paraiso
Language/Paraiso/Prelude.hs
bsd-3-clause
1,129
0
8
252
280
179
101
33
1
type Table a = IO
roberth/uu-helium
test/kinderrors/KindCorrect1.hs
gpl-3.0
18
0
4
5
8
5
3
1
0
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.EC2.CreateKeyPair -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Creates a 2048-bit RSA key pair with the specified name. Amazon EC2 -- stores the public key and displays the private key for you to save to a -- file. The private key is returned as an unencrypted PEM encoded PKCS#8 -- private key. If a key with the specified name already exists, Amazon EC2 -- returns an error. -- -- You can have up to five thousand key pairs per region. -- -- The key pair returned to you is available only in the region in which -- you create it. To create a key pair that is available in all regions, -- use ImportKeyPair. -- -- For more information about key pairs, see -- <http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html Key Pairs> -- in the /Amazon Elastic Compute Cloud User Guide/. -- -- /See:/ <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-CreateKeyPair.html AWS API Reference> for CreateKeyPair. module Network.AWS.EC2.CreateKeyPair ( -- * Creating a Request createKeyPair , CreateKeyPair -- * Request Lenses , ckpDryRun , ckpKeyName -- * Destructuring the Response , createKeyPairResponse , CreateKeyPairResponse -- * Response Lenses , ckprsResponseStatus , ckprsKeyName , ckprsKeyFingerprint , ckprsKeyMaterial ) where import Network.AWS.EC2.Types import Network.AWS.EC2.Types.Product import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response -- | /See:/ 'createKeyPair' smart constructor. data CreateKeyPair = CreateKeyPair' { _ckpDryRun :: !(Maybe Bool) , _ckpKeyName :: !Text } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'CreateKeyPair' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ckpDryRun' -- -- * 'ckpKeyName' createKeyPair :: Text -- ^ 'ckpKeyName' -> CreateKeyPair createKeyPair pKeyName_ = CreateKeyPair' { _ckpDryRun = Nothing , _ckpKeyName = pKeyName_ } -- | 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'. ckpDryRun :: Lens' CreateKeyPair (Maybe Bool) ckpDryRun = lens _ckpDryRun (\ s a -> s{_ckpDryRun = a}); -- | A unique name for the key pair. -- -- Constraints: Up to 255 ASCII characters ckpKeyName :: Lens' CreateKeyPair Text ckpKeyName = lens _ckpKeyName (\ s a -> s{_ckpKeyName = a}); instance AWSRequest CreateKeyPair where type Rs CreateKeyPair = CreateKeyPairResponse request = postQuery eC2 response = receiveXML (\ s h x -> CreateKeyPairResponse' <$> (pure (fromEnum s)) <*> (x .@ "keyName") <*> (x .@ "keyFingerprint") <*> (x .@ "keyMaterial")) instance ToHeaders CreateKeyPair where toHeaders = const mempty instance ToPath CreateKeyPair where toPath = const "/" instance ToQuery CreateKeyPair where toQuery CreateKeyPair'{..} = mconcat ["Action" =: ("CreateKeyPair" :: ByteString), "Version" =: ("2015-04-15" :: ByteString), "DryRun" =: _ckpDryRun, "KeyName" =: _ckpKeyName] -- | Describes a key pair. -- -- /See:/ 'createKeyPairResponse' smart constructor. data CreateKeyPairResponse = CreateKeyPairResponse' { _ckprsResponseStatus :: !Int , _ckprsKeyName :: !Text , _ckprsKeyFingerprint :: !Text , _ckprsKeyMaterial :: !Text } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'CreateKeyPairResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ckprsResponseStatus' -- -- * 'ckprsKeyName' -- -- * 'ckprsKeyFingerprint' -- -- * 'ckprsKeyMaterial' createKeyPairResponse :: Int -- ^ 'ckprsResponseStatus' -> Text -- ^ 'ckprsKeyName' -> Text -- ^ 'ckprsKeyFingerprint' -> Text -- ^ 'ckprsKeyMaterial' -> CreateKeyPairResponse createKeyPairResponse pResponseStatus_ pKeyName_ pKeyFingerprint_ pKeyMaterial_ = CreateKeyPairResponse' { _ckprsResponseStatus = pResponseStatus_ , _ckprsKeyName = pKeyName_ , _ckprsKeyFingerprint = pKeyFingerprint_ , _ckprsKeyMaterial = pKeyMaterial_ } -- | The response status code. ckprsResponseStatus :: Lens' CreateKeyPairResponse Int ckprsResponseStatus = lens _ckprsResponseStatus (\ s a -> s{_ckprsResponseStatus = a}); -- | The name of the key pair. ckprsKeyName :: Lens' CreateKeyPairResponse Text ckprsKeyName = lens _ckprsKeyName (\ s a -> s{_ckprsKeyName = a}); -- | The SHA-1 digest of the DER encoded private key. ckprsKeyFingerprint :: Lens' CreateKeyPairResponse Text ckprsKeyFingerprint = lens _ckprsKeyFingerprint (\ s a -> s{_ckprsKeyFingerprint = a}); -- | An unencrypted PEM encoded RSA private key. ckprsKeyMaterial :: Lens' CreateKeyPairResponse Text ckprsKeyMaterial = lens _ckprsKeyMaterial (\ s a -> s{_ckprsKeyMaterial = a});
fmapfmapfmap/amazonka
amazonka-ec2/gen/Network/AWS/EC2/CreateKeyPair.hs
mpl-2.0
5,874
0
16
1,226
792
481
311
98
1
{- - Copyright (c) 2017 The Agile Monkeys S.L. <hackers@theam.io> - - 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. -} module Foreign.CodeMirror where getMDEContent :: IO String getMDEContent = return "" setMDEContent :: String -> IO () setMDEContent _ = return () makeCodeMirrorFromId :: String -> IO () makeCodeMirrorFromId _ = return () cmdOrCtrlReturnPressed :: IO Bool cmdOrCtrlReturnPressed = return False
J2RGEZ/haskell-do
src/ghc-specific/Foreign/CodeMirror.hs
apache-2.0
926
0
7
164
93
47
46
9
1
{-# LANGUAGE GADTs #-} module Language.K3.TypeSystem.Simplification.Common ( SimplificationConfig(..) , SimplificationResult(..) , VariableSubstitution , substitutionLookup , substitutionLookupAny , prettySubstitution , Simplifier , SimplifyM , tellSubstitution , runSimplifyM , runConfigSimplifyM ) where import Control.Monad.Reader import Control.Monad.Writer import Data.Map (Map) import qualified Data.Map as Map import Data.Set (Set) import Language.K3.TypeSystem.Data import Language.K3.TypeSystem.Utils import Language.K3.Utils.Pretty -- |The record used to configure common properties of the simplification -- routines. The set of variables @preserveVars@ are variables which must be -- present by the completion of the simplification process. data SimplificationConfig = SimplificationConfig { preserveVars :: Set AnyTVar } -- |The data type used to describe the result of simplification. data SimplificationResult = SimplificationResult { simplificationVarMap :: VariableSubstitution } instance Monoid SimplificationResult where mempty = SimplificationResult { simplificationVarMap = (Map.empty, Map.empty) } mappend x y = SimplificationResult { simplificationVarMap = let (xq,xu) = simplificationVarMap x in let (yq,yu) = simplificationVarMap y in (xq `Map.union` yq, xu `Map.union` yu) } -- TODO: consider moving this to somewhere more general -- |A type for the description of variable substitution. type VariableSubstitution = (Map QVar QVar, Map UVar UVar) -- |Performs a lookup on a variable substitution. substitutionLookup :: TVar q -> VariableSubstitution -> TVar q substitutionLookup var (qvarSubst,uvarSubst) = case var of a@(UTVar{}) -> doLookup uvarSubst a qa@(QTVar{}) -> doLookup qvarSubst qa where doLookup :: Map (TVar q) (TVar q) -> TVar q -> TVar q doLookup m v = let f v' = Map.findWithDefault v' v' m in leastFixedPoint f v -- |Performs a lookup on a variable substitution. substitutionLookupAny :: AnyTVar -> VariableSubstitution -> AnyTVar substitutionLookupAny sa subst = case sa of SomeUVar a -> someVar $ substitutionLookup a subst SomeQVar qa -> someVar $ substitutionLookup qa subst -- |Pretty-prints a variable susbtitution pair. prettySubstitution :: String -> VariableSubstitution -> [String] prettySubstitution sep (qvarSubsts,uvarSubsts) = let prettyElems = map p (Map.toList qvarSubsts) ++ map p (Map.toList uvarSubsts) in ["{"] %+ sequenceBoxes maxWidth ", " prettyElems %+ ["}"] where p :: (Pretty k, Pretty v) => (k,v) -> [String] p (k,v) = prettyLines k %+ [sep] %+ prettyLines v -- |A type alias describing a routine which simplifies a constraint set. type Simplifier = ConstraintSet -> SimplifyM ConstraintSet -- |The monad under which simplification occurs. type SimplifyM = WriterT SimplificationResult (Reader SimplificationConfig) -- |A routine to inform this monad of a substitution. tellSubstitution :: VariableSubstitution -> SimplifyM () tellSubstitution (qvarRepl, uvarRepl) = do tell $ SimplificationResult { simplificationVarMap = (qvarRepl, uvarRepl) } -- |Evaluates a computation which simplifies a value. The simplification -- result will map replaced variables onto the variables which replaced them. runSimplifyM :: SimplificationConfig -> SimplifyM a -> (a, SimplificationResult) runSimplifyM cfg x = runReader (runWriterT x) cfg -- |Evaluates a computation which simplifies a value, producing a writer-monadic -- result. runConfigSimplifyM :: SimplificationConfig -> SimplifyM a -> Writer SimplificationResult a runConfigSimplifyM cfg x = let (y,w) = runReader (runWriterT x) cfg in tell w >> return y
DaMSL/K3
src/Language/K3/TypeSystem/Simplification/Common.hs
apache-2.0
3,812
1
15
726
874
476
398
70
2
-- | -- Module : Basement.String.Builder -- License : BSD-style -- Maintainer : Foundation -- -- String builder {-# LANGUAGE GeneralizedNewtypeDeriving #-} module Basement.String.Builder ( Builder , run , runUnsafe -- * Emit functions , emit , emitChar -- * unsafe , unsafeStringBuilder ) where import qualified Basement.Block.Base as Block (length) import qualified Basement.Block.Builder as Block import Basement.Compat.Base import Basement.Compat.Semigroup import Basement.Monad import Basement.String (String, ValidationFailure, Encoding (UTF8), fromBytes) import Basement.UArray.Base (UArray) import qualified Basement.UArray.Base as A newtype Builder = Builder Block.Builder deriving (Semigroup, Monoid) unsafeStringBuilder :: Block.Builder -> Builder unsafeStringBuilder = Builder {-# INLINE unsafeStringBuilder #-} run :: PrimMonad prim => Builder -> prim (String, Maybe ValidationFailure, UArray Word8) run (Builder builder) = do block <- Block.run builder let array = A.UArray 0 (Block.length block) (A.UArrayBA block) pure $ fromBytes UTF8 array -- | run the given builder and return the generated String -- -- prefer `run` runUnsafe :: PrimMonad prim => Builder -> prim String runUnsafe (Builder builder) = Block.unsafeRunString builder -- | add a string in the builder emit :: String -> Builder emit = Builder . Block.emitString -- | emit a UTF8 char in the builder emitChar :: Char -> Builder emitChar = Builder . Block.emitUTF8Char
vincenthz/hs-foundation
basement/Basement/String/Builder.hs
bsd-3-clause
1,569
0
13
322
346
201
145
32
1
-- Copyright 2016 TensorFlow authors. -- -- 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 FlexibleContexts #-} {-# LANGUAGE OverloadedLists #-} module Main where import TensorFlow.Test (assertAllClose) import Test.Framework (defaultMain, Test) import Test.Framework.Providers.HUnit (testCase) import qualified Data.Vector as V import qualified TensorFlow.Gradient as TF import qualified TensorFlow.NN as TF import qualified TensorFlow.Ops as TF import qualified TensorFlow.Core as TF -- | These tests are ported from: -- -- <tensorflow>/tensorflow/python/ops/nn_xent_tests.py -- -- This is the implementation we use to check the implementation we -- wrote in `TensorFlow.NN.sigmoidCrossEntropyWithLogits`. -- sigmoidXentWithLogits :: Floating a => Ord a => [a] -> [a] -> [a] sigmoidXentWithLogits logits' targets' = let sig = map (\x -> 1 / (1 + exp (-x))) logits' eps = 0.0001 predictions = map (\p -> min (max p eps) (1 - eps)) sig xent y z = (-z) * (log y) - (1 - z) * log (1 - y) in zipWith xent predictions targets' data Inputs = Inputs { logits :: [Float] , targets :: [Float] } defInputs :: Inputs defInputs = Inputs { logits = [-100, -2, -2, 0, 2, 2, 2, 100] , targets = [ 0, 0, 1, 0, 0, 1, 0.5, 1] } testLogisticOutput :: Test testLogisticOutput = testCase "testLogisticOutput" $ do let inputs = defInputs r <- run $ do vLogits <- TF.render $ TF.vector $ logits inputs vTargets <- TF.render $ TF.vector $ targets inputs TF.sigmoidCrossEntropyWithLogits vLogits vTargets let ourLoss = V.fromList $ sigmoidXentWithLogits (logits inputs) (targets inputs) assertAllClose r ourLoss testLogisticOutputMultipleDim :: Test testLogisticOutputMultipleDim = testCase "testLogisticOutputMultipleDim" $ do let inputs = defInputs shape = [2, 2, 2] r <- run $ do vLogits <- TF.render $ TF.constant shape (logits inputs) vTargets <- TF.render $ TF.constant shape (targets inputs) TF.sigmoidCrossEntropyWithLogits vLogits vTargets let ourLoss = V.fromList $ sigmoidXentWithLogits (logits inputs) (targets inputs) assertAllClose r ourLoss testGradientAtZero :: Test testGradientAtZero = testCase "testGradientAtZero" $ do r <- run $ do let inputs = defInputs { logits = [0, 0], targets = [0, 1] } vTargets <- TF.render $ TF.vector $ targets inputs vLogits <- TF.render $ TF.vector $ logits inputs let tfLoss = TF.sigmoidCrossEntropyWithLogits vLogits vTargets l <- tfLoss TF.gradients l [vLogits] assertAllClose (head r) (V.fromList [0.5, -0.5]) run :: TF.Fetchable t a => TF.Session t -> IO a run = TF.runSession . (>>= TF.run) main :: IO () main = defaultMain [ testGradientAtZero , testLogisticOutput , testLogisticOutputMultipleDim ]
judah/tensorflow-haskell
tensorflow-ops/tests/NNTest.hs
apache-2.0
3,626
0
17
960
924
499
425
-1
-1
module Dotnet.System.IO.SeekOrigin where import Dotnet import qualified Dotnet.System.Enum data SeekOrigin_ a type SeekOrigin a = Dotnet.System.Enum.Enum (SeekOrigin_ a)
FranklinChen/Hugs
dotnet/lib/Dotnet/System/IO/SeekOrigin.hs
bsd-3-clause
174
0
7
22
42
28
14
-1
-1
module M4 where --Any type/data constructor name declared in this module can be renamed. --Any type variable can be renamed. --Rename type Constructor 'BTree' to 'MyBTree' data BTree a = Empty | T a (BTree a) (BTree a) deriving Show buildtree :: Ord a => [a] -> (BTree a) buildtree [] = Empty buildtree (x:xs) = insert x (buildtree xs) insert :: Ord a => a -> BTree a -> BTree a insert val v2 = do case v2 of T val Empty Empty | val == val -> Empty | otherwise -> (T val Empty (T val Empty Empty)) T val (T val2 Empty Empty) Empty -> Empty _ -> v2 main :: IO () main = do let f (T 42 Empty Empty) = putStrLn (T 42 Empty Empty) if True then do putStrLn $ show (f (T 42 Empty Empty)) else do putStrLn $ show (f (T 42 Empty (T 42 Empty Empty)))
SAdams601/HaRe
old/testing/asPatterns/M4.hs
bsd-3-clause
1,007
0
17
421
347
172
175
22
3
{-# LANGUAGE ScopedTypeVariables #-} module Bug where f1 :: forall a. [a] -> [a] f1 (x:xs) = xs ++ [ x :: a ] -- OK f2 :: forall a. [a] -> [a] f2 = \(x:xs) -> xs ++ [ x :: a ] -- OK -- This pair is a cut-down version of #2030 isSafe alts = isSafeAlts alts isSafeAlts :: forall m . Int -> m Int isSafeAlts x = error "urk" where isSafeAlt :: Int -> m Int isSafeAlt alt = isSafe `seq` error "urk"
sdiehl/ghc
testsuite/tests/typecheck/should_compile/tc242.hs
bsd-3-clause
413
0
8
107
170
96
74
11
1
module Generators where -- tmp generators = []
forste/haReFork
tools/evman/servers/QuickCheck/lib/Generators.hs
bsd-3-clause
51
0
5
12
12
8
4
2
1
{-# LANGUAGE MagicHash #-} {-# LANGUAGE EmptyDataDecls #-} {- OPTIONS_GHC -cpp #-} {- OPTIONS_GHC -cpp -fglasgow-exts -} module Language.Haskell.Liquid.Prelude where ------------------------------------------------------------------- --------------------------- Arithmetic ---------------------------- ------------------------------------------------------------------- {-@ assume plus :: x:{v:Int | true } -> y:{v:Int | true} -> {v:Int | v = x + y} @-} {-@ assume minus :: x:{v:Int | true } -> y:{v:Int | true} -> {v:Int | v = x - y} @-} {-@ assume times :: x:Int -> y:Int -> Int @-} {-@ assume eq :: x:Int -> y:Int -> {v:Bool | ((Prop v) <=> x = y)} @-} {-@ assume neq :: x:Int -> y:Int -> {v:Bool | ((Prop v) <=> x != y)} @-} {-@ assume leq :: x:Int -> y:Int -> {v:Bool | ((Prop v) <=> x <= y)} @-} {-@ assume geq :: x:Int -> y:Int -> {v:Bool | ((Prop v) <=> x >= y)} @-} {-@ assume lt :: x:Int -> y:Int -> {v:Bool | ((Prop v) <=> x < y)} @-} {-@ assume gt :: x:Int -> y:Int -> {v:Bool | ((Prop v) <=> x > y)} @-} {-# NOINLINE plus #-} plus :: Int -> Int -> Int plus x y = x + y {-# NOINLINE minus #-} minus :: Int -> Int -> Int minus x y = x - y {-# NOINLINE times #-} times :: Int -> Int -> Int times x y = x * y ------------------------------------------------------------------- --------------------------- Comparisons --------------------------- ------------------------------------------------------------------- {-# NOINLINE eq #-} eq :: Int -> Int -> Bool eq x y = x == y {-# NOINLINE neq #-} neq :: Int -> Int -> Bool neq x y = not (x == y) {-# NOINLINE leq #-} leq :: Int -> Int -> Bool leq x y = x <= y {-# NOINLINE geq #-} geq :: Int -> Int -> Bool geq x y = x >= y {-# NOINLINE lt #-} lt :: Int -> Int -> Bool lt x y = x < y {-# NOINLINE gt #-} gt :: Int -> Int -> Bool gt x y = x > y ------------------------------------------------------------------- ------------------------ Specifications --------------------------- ------------------------------------------------------------------- {-@ assume liquidAssertB :: x:{v:Bool | (Prop v)} -> {v: Bool | (Prop v)} @-} {-# NOINLINE liquidAssertB #-} liquidAssertB :: Bool -> Bool liquidAssertB b = b {-@ assume liquidAssert :: {v:Bool | (Prop v)} -> a -> a @-} {-# NOINLINE liquidAssert #-} liquidAssert :: Bool -> a -> a liquidAssert _ x = x {-@ assume liquidAssume :: b:Bool -> a -> {v: a | (Prop b)} @-} {-# NOINLINE liquidAssume #-} liquidAssume :: Bool -> a -> a liquidAssume _ x = x {-@ assume liquidAssumeB :: forall <p :: a -> Prop>. (a<p> -> {v:Bool| ((Prop v) <=> true)}) -> a -> a<p> @-} liquidAssumeB :: (a -> Bool) -> a -> a liquidAssumeB p x | p x = x | otherwise = error "liquidAssumeB fails" {-@ assume liquidError :: {v: String | 0 = 1} -> a @-} {-# NOINLINE liquidError #-} liquidError :: String -> a liquidError = error {-@ assume crash :: forall a . x:{v:Bool | (Prop v)} -> a @-} {-# NOINLINE crash #-} crash :: Bool -> a crash = undefined {-# NOINLINE force #-} force = True {-# NOINLINE choose #-} choose :: Int -> Int choose = undefined ------------------------------------------------------------------- ----------- Modular Arithmetic Wrappers --------------------------- ------------------------------------------------------------------- -- tedium because fixpoint doesnt want to deal with (x mod y) only (x mod c) {-@ assume isEven :: x:Int -> {v:Bool | ((Prop v) <=> ((x mod 2) = 0))} @-} {-# NOINLINE isEven #-} isEven :: Int -> Bool isEven x = x `mod` 2 == 0 {-@ assume isOdd :: x:Int -> {v:Bool | ((Prop v) <=> ((x mod 2) = 1))} @-} {-# NOINLINE isOdd #-} isOdd :: Int -> Bool isOdd x = x `mod` 2 == 1 ----------------------------------------------------------------------------------------------- {-@ assert safeZipWith :: (a -> b -> c) -> xs : [a] -> ys:{v:[b] | len(v) = len(xs)} -> {v : [c] | len(v) = len(xs)} @-} safeZipWith :: (a->b->c) -> [a]->[b]->[c] safeZipWith f (a:as) (b:bs) = f a b : safeZipWith f as bs safeZipWith _ [] [] = [] safeZipWith _ _ _ = error "safeZipWith: cannot happen!" {-@ (==>) :: p:Bool -> q:Bool -> {v:Bool | Prop v <=> (Prop p => Prop q)} @-} infixr 8 ==> (==>) :: Bool -> Bool -> Bool False ==> False = True False ==> True = True True ==> True = True True ==> False = False
abakst/liquidhaskell
include/Language/Haskell/Liquid/Prelude.hs
bsd-3-clause
4,353
0
8
902
703
394
309
69
1
{-# LANGUAGE ScopedTypeVariables #-} module Properties.Shift where import Test.QuickCheck import Instances import Utils import XMonad.StackSet hiding (filter) import qualified Data.List as L -- --------------------------------------------------------------------- -- shift -- shift is fully reversible on current window, when focus and master -- are the same. otherwise, master may move. prop_shift_reversible (x :: T) = do i <- arbitraryTag x case peek y of Nothing -> return True Just _ -> return $ normal ((view n . shift n . view i . shift i) y) == normal y where y = swapMaster x n = currentTag y ------------------------------------------------------------------------ -- shiftMaster -- focus/local/idempotent same as swapMaster: prop_shift_master_focus (x :: T) = peek x == (peek $ shiftMaster x) prop_shift_master_local (x :: T) = hidden_spaces x == hidden_spaces (shiftMaster x) prop_shift_master_idempotent (x :: T) = shiftMaster (shiftMaster x) == shiftMaster x -- ordering is constant modulo the focused window: prop_shift_master_ordering (x :: T) = case peek x of Nothing -> True Just m -> L.delete m (index x) == L.delete m (index $ shiftMaster x) -- --------------------------------------------------------------------- -- shiftWin -- shiftWin on current window is the same as shift prop_shift_win_focus (x :: T) = do n <- arbitraryTag x case peek x of Nothing -> return True Just w -> return $ shiftWin n w x == shift n x -- shiftWin on a non-existant window is identity prop_shift_win_indentity (x :: T) = do n <- arbitraryTag x w <- arbitrary `suchThat` \w' -> not (w' `member` x) return $ shiftWin n w x == x -- shiftWin leaves the current screen as it is, if neither n is the tag -- of the current workspace nor w on the current workspace prop_shift_win_fix_current = do x <- arbitrary `suchThat` \(x' :: T) -> -- Invariant, otherWindows are NOT in the current workspace. let otherWindows = allWindows x' L.\\ index x' in length(tags x') >= 2 && length(otherWindows) >= 1 -- Sadly we have to construct `otherWindows` again, for the actual StackSet -- that got chosen. let otherWindows = allWindows x L.\\ index x -- We know such tag must exists, due to the precondition n <- arbitraryTag x `suchThat` (/= currentTag x) -- we know length is >= 1, from above precondition idx <- choose(0, length(otherWindows) - 1) let w = otherWindows !! idx return $ (current $ x) == (current $ shiftWin n w x)
atupal/xmonad-mirror
xmonad/tests/Properties/Shift.hs
mit
2,557
9
19
534
665
344
321
38
2
----------------------------------------------------------------------------- -- | -- Module : XMonad.Actions.OnScreen -- Copyright : (c) 2009 Nils Schweinsberg -- License : BSD3-style (see LICENSE) -- -- Maintainer : Nils Schweinsberg <mail@n-sch.de> -- Stability : unstable -- Portability : unportable -- -- Control workspaces on different screens (in xinerama mode). -- ----------------------------------------------------------------------------- module XMonad.Actions.OnScreen ( -- * Usage -- $usage onScreen , onScreen' , Focus(..) , viewOnScreen , greedyViewOnScreen , onlyOnScreen , toggleOnScreen , toggleGreedyOnScreen ) where import XMonad import XMonad.StackSet hiding (new) import Control.Monad (guard) -- import Control.Monad.State.Class (gets) import Data.Maybe (fromMaybe) -- | Focus data definitions data Focus = FocusNew -- ^ always focus the new screen | FocusCurrent -- ^ always keep the focus on the current screen | FocusTag WorkspaceId -- ^ always focus tag i on the new stack | FocusTagVisible WorkspaceId -- ^ focus tag i only if workspace with tag i is visible on the old stack -- | Run any function that modifies the stack on a given screen. This function -- will also need to know which Screen to focus after the function has been -- run. onScreen :: (WindowSet -> WindowSet) -- ^ function to run -> Focus -- ^ what to do with the focus -> ScreenId -- ^ screen id -> WindowSet -- ^ current stack -> WindowSet onScreen f foc sc st = fromMaybe st $ do ws <- lookupWorkspace sc st let fStack = f $ view ws st return $ setFocus foc st fStack -- set focus for new stack setFocus :: Focus -> WindowSet -- ^ old stack -> WindowSet -- ^ new stack -> WindowSet setFocus FocusNew _ new = new setFocus FocusCurrent old new = case lookupWorkspace (screen $ current old) new of Nothing -> new Just i -> view i new setFocus (FocusTag i) _ new = view i new setFocus (FocusTagVisible i) old new = if i `elem` map (tag . workspace) (visible old) then setFocus (FocusTag i) old new else setFocus FocusCurrent old new -- | A variation of @onScreen@ which will take any @X ()@ function and run it -- on the given screen. -- Warning: This function will change focus even if the function it's supposed -- to run doesn't succeed. onScreen' :: X () -- ^ X function to run -> Focus -- ^ focus -> ScreenId -- ^ screen id -> X () onScreen' x foc sc = do st <- gets windowset case lookupWorkspace sc st of Nothing -> return () Just ws -> do windows $ view ws x windows $ setFocus foc st -- | Switch to workspace @i@ on screen @sc@. If @i@ is visible use @view@ to -- switch focus to the workspace @i@. viewOnScreen :: ScreenId -- ^ screen id -> WorkspaceId -- ^ index of the workspace -> WindowSet -- ^ current stack -> WindowSet viewOnScreen sid i = onScreen (view i) (FocusTag i) sid -- | Switch to workspace @i@ on screen @sc@. If @i@ is visible use @greedyView@ -- to switch the current workspace with workspace @i@. greedyViewOnScreen :: ScreenId -- ^ screen id -> WorkspaceId -- ^ index of the workspace -> WindowSet -- ^ current stack -> WindowSet greedyViewOnScreen sid i = onScreen (greedyView i) (FocusTagVisible i) sid -- | Switch to workspace @i@ on screen @sc@. If @i@ is visible do nothing. onlyOnScreen :: ScreenId -- ^ screen id -> WorkspaceId -- ^ index of the workspace -> WindowSet -- ^ current stack -> WindowSet onlyOnScreen sid i = onScreen (view i) FocusCurrent sid -- | @toggleOrView@ as in "XMonad.Actions.CycleWS" for @onScreen@ with view toggleOnScreen :: ScreenId -- ^ screen id -> WorkspaceId -- ^ index of the workspace -> WindowSet -- ^ current stack -> WindowSet toggleOnScreen sid i = onScreen (toggleOrView' view i) FocusCurrent sid -- | @toggleOrView@ from "XMonad.Actions.CycleWS" for @onScreen@ with greedyView toggleGreedyOnScreen :: ScreenId -- ^ screen id -> WorkspaceId -- ^ index of the workspace -> WindowSet -- ^ current stack -> WindowSet toggleGreedyOnScreen sid i = onScreen (toggleOrView' greedyView i) FocusCurrent sid -- a \"pure\" version of X.A.CycleWS.toggleOrDoSkip toggleOrView' :: (WorkspaceId -> WindowSet -> WindowSet) -- ^ function to run -> WorkspaceId -- ^ tag to look for -> WindowSet -- ^ current stackset -> WindowSet toggleOrView' f i st = fromMaybe (f i st) $ do let st' = hidden st -- make sure we actually have to do something guard $ i == (tag . workspace $ current st) guard $ not (null st') -- finally, toggle! return $ f (tag . head $ st') st -- $usage -- -- This module provides an easy way to control, what you see on other screens in -- xinerama mode without having to focus them. Put this into your -- @~\/.xmonad\/xmonad.hs@: -- -- > import XMonad.Actions.OnScreen -- -- Then add the appropriate keybindings, for example replace your current keys -- to switch the workspaces with this at the bottom of your keybindings: -- -- > ++ -- > [ ((m .|. modm, k), windows (f i)) -- > | (i, k) <- zip (workspaces conf) ([xK_1 .. xK_9] ++ [xK_0]) -- > , (f, m) <- [ (viewOnScreen 0, 0) -- > , (viewOnScreen 1, controlMask) -- > , (greedyView, controlMask .|. shiftMask) ] -- > ] -- -- This will provide you with the following keybindings: -- -- * modkey + 1-0: -- Switch to workspace 1-0 on screen 0 -- -- * modkey + control + 1-0: -- Switch to workspace 1-0 on screen 1 -- -- * modkey + control + shift + 1-0: -- Default greedyView behaviour -- -- -- A more basic version inside the default keybindings would be: -- -- > , ((modm .|. controlMask, xK_1), windows (viewOnScreen 0 "1")) -- -- where 0 is the first screen and \"1\" the workspace with the tag \"1\". -- -- For detailed instructions on editing your key bindings, see -- "XMonad.Doc.Extending#Editing_key_bindings".
pjones/xmonad-test
vendor/xmonad-contrib/XMonad/Actions/OnScreen.hs
bsd-2-clause
6,638
0
13
1,978
915
511
404
91
3
-- !!! hiding class members (but not class.) module M where import Prelude hiding ( (<), (>)) x :: Ord a => a -> a x = undefined
lukexi/ghc
testsuite/tests/module/mod129.hs
bsd-3-clause
132
0
6
31
42
27
15
4
1
{-# LANGUAGE PartialTypeSignatures, NamedWildCards #-} module NamedTyVar where foo :: (_a, b) -> (a, _b) foo (x, y) = (x, y)
urbanslug/ghc
testsuite/tests/partial-sigs/should_compile/NamedTyVar.hs
bsd-3-clause
126
0
6
22
46
29
17
4
1
-- Test for trac #1588: unrequested generalized newtype deriving? newtype MaybeT m a = MaybeT { runMaybeT :: m (Maybe a) } deriving Eq data MaybeT' m a = MaybeT' { runMaybeT' :: m (Maybe a) } deriving Eq
forked-upstream-packages-for-ghcjs/ghc
testsuite/tests/deriving/should_fail/drvfail013.hs
bsd-3-clause
213
0
11
47
58
35
23
2
0
module T8221b where data Link a = Link a !(Link a)
urbanslug/ghc
testsuite/tests/simplCore/should_compile/T8221b.hs
bsd-3-clause
52
0
9
12
23
13
10
4
0
{-# LANGUAGE CPP #-} module GHCJS.DOM.NodeIterator ( #if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT) module GHCJS.DOM.JSFFI.Generated.NodeIterator #else module Graphics.UI.Gtk.WebKit.DOM.NodeIterator #endif ) where #if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT) import GHCJS.DOM.JSFFI.Generated.NodeIterator #else import Graphics.UI.Gtk.WebKit.DOM.NodeIterator #endif
plow-technologies/ghcjs-dom
src/GHCJS/DOM/NodeIterator.hs
mit
445
0
5
39
33
26
7
4
0
{-# LANGUAGE BangPatterns, DataKinds, DeriveDataTypeable, FlexibleInstances, MultiParamTypeClasses #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} module Hadoop.Protos.ZKFCProtocolProtos.CedeActiveResponseProto (CedeActiveResponseProto(..)) where import Prelude ((+), (/)) import qualified Prelude as Prelude' import qualified Data.Typeable as Prelude' import qualified Data.Data as Prelude' import qualified Text.ProtocolBuffers.Header as P' data CedeActiveResponseProto = CedeActiveResponseProto{} deriving (Prelude'.Show, Prelude'.Eq, Prelude'.Ord, Prelude'.Typeable, Prelude'.Data) instance P'.Mergeable CedeActiveResponseProto where mergeAppend CedeActiveResponseProto CedeActiveResponseProto = CedeActiveResponseProto instance P'.Default CedeActiveResponseProto where defaultValue = CedeActiveResponseProto instance P'.Wire CedeActiveResponseProto where wireSize ft' self'@(CedeActiveResponseProto) = case ft' of 10 -> calc'Size 11 -> P'.prependMessageSize calc'Size _ -> P'.wireSizeErr ft' self' where calc'Size = 0 wirePut ft' self'@(CedeActiveResponseProto) = case ft' of 10 -> put'Fields 11 -> do P'.putSize (P'.wireSize 10 self') put'Fields _ -> P'.wirePutErr ft' self' where put'Fields = do Prelude'.return () wireGet ft' = case ft' of 10 -> P'.getBareMessageWith update'Self 11 -> P'.getMessageWith update'Self _ -> P'.wireGetErr ft' where update'Self wire'Tag old'Self = case wire'Tag of _ -> let (field'Number, wire'Type) = P'.splitWireTag wire'Tag in P'.unknown field'Number wire'Type old'Self instance P'.MessageAPI msg' (msg' -> CedeActiveResponseProto) CedeActiveResponseProto where getVal m' f' = f' m' instance P'.GPB CedeActiveResponseProto instance P'.ReflectDescriptor CedeActiveResponseProto where getMessageInfo _ = P'.GetMessageInfo (P'.fromDistinctAscList []) (P'.fromDistinctAscList []) reflectDescriptorInfo _ = Prelude'.read "DescriptorInfo {descName = ProtoName {protobufName = FIName \".hadoop.common.CedeActiveResponseProto\", haskellPrefix = [MName \"Hadoop\",MName \"Protos\"], parentModule = [MName \"ZKFCProtocolProtos\"], baseName = MName \"CedeActiveResponseProto\"}, descFilePath = [\"Hadoop\",\"Protos\",\"ZKFCProtocolProtos\",\"CedeActiveResponseProto.hs\"], isGroup = False, fields = fromList [], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False}" instance P'.TextType CedeActiveResponseProto where tellT = P'.tellSubMessage getT = P'.getSubMessage instance P'.TextMsg CedeActiveResponseProto where textPut msg = Prelude'.return () textGet = Prelude'.return P'.defaultValue
alexbiehl/hoop
hadoop-protos/src/Hadoop/Protos/ZKFCProtocolProtos/CedeActiveResponseProto.hs
mit
2,879
6
14
533
453
255
198
53
0
{-# LANGUAGE FlexibleContexts, NoMonomorphismRestriction #-} {-# LANGUAGE TypeOperators, DataKinds #-} {-# LANGUAGE TypeApplications #-} {-# LANGUAGE TemplateHaskell #-} module Control.Eff.Logic.NDet.Test (testGroups, gen_testCA, gen_ifte_test) where import Test.HUnit hiding (State) import Control.Applicative import Control.Eff import Control.Eff.Example import Control.Eff.Example.Test (ex2) import Control.Eff.Exception import Control.Eff.Logic.NDet import Control.Eff.Writer.Strict import Control.Monad (msum, guard, mzero, mplus) import Control.Eff.Logic.Test import Utils import Test.Framework.TH import Test.Framework.Providers.HUnit testGroups = [ $(testGroupGenerator) ] gen_testCA :: (Integral a) => a -> Eff (NDet ': r) a gen_testCA x = do i <- msum . fmap return $ [1..x] guard (i `mod` 2 == 0) return i case_NDet_testCA :: Assertion case_NDet_testCA = [2, 4..10] @=? (run $ makeChoiceA (gen_testCA 10)) case_Choose1_exc11 :: Assertion case_Choose1_exc11 = [2,3] @=? (run exc11) where exc11 = makeChoice exc1 exc1 = return 1 `add` choose [1,2] case_Choose_exRec :: Assertion case_Choose_exRec = let exRec_1 = run . runErrBig . makeChoice $ exRec (ex2 (choose [5,7,1])) exRec_2 = run . makeChoice . runErrBig $ exRec (ex2 (choose [5,7,1])) exRec_3 = run . runErrBig . makeChoice $ exRec (ex2 (choose [5,7,11,1])) exRec_4 = run . makeChoice . runErrBig $ exRec (ex2 (choose [5,7,11,1])) in assertEqual "Choose: error recovery: exRec_1" expected1 exRec_1 >> assertEqual "Choose: error recovery: exRec_2" expected2 exRec_2 >> assertEqual "Choose: error recovery: exRec_3" expected3 exRec_3 >> assertEqual "Choose: error recovery: exRec_4" expected4 exRec_4 where expected1 = Right [5,7,1] expected2 = [Right 5,Right 7,Right 1] expected3 = Left (TooBig 11) expected4 = [Right 5,Right 7,Left (TooBig 11),Right 1] -- Errror recovery part -- The code is the same as in transf1.hs. The inferred signatures differ -- Was: exRec :: MonadError TooBig m => m Int -> m Int -- exRec :: Member (Exc TooBig) r => Eff r Int -> Eff r Int exRec m = catchError m handler where handler (TooBig n) | n <= 7 = return n handler e = throwError e case_Choose_ex2 :: Assertion case_Choose_ex2 = let ex2_1 = run . makeChoice . runErrBig $ ex2 (choose [5,7,1]) ex2_2 = run . runErrBig . makeChoice $ ex2 (choose [5,7,1]) in assertEqual "Choose: Combining exceptions and non-determinism: ex2_1" expected1 ex2_1 >> assertEqual "Choose: Combining exceptions and non-determinism: ex2_2" expected2 ex2_2 where expected1 = [Right 5,Left (TooBig 7),Right 1] expected2 = Left (TooBig 7) gen_ifte_test x = do n <- gen x ifte (do d <- gen x guard $ d < n && n `mod` d == 0 -- _ <- trace ("d: " ++ show d) (return ()) ) (\_ -> mzero) (return n) where gen x = msum . fmap return $ [2..x] case_NDet_ifte :: Assertion case_NDet_ifte = let primes = ifte_test_run in assertEqual "NDet: test ifte using primes" [2,3,5,7,11,13,17,19,23,29] primes where ifte_test_run :: [Int] ifte_test_run = run . makeChoiceA $ (gen_ifte_test 30) -- called reflect in the LogicT paper case_NDet_reflect :: Assertion case_NDet_reflect = let tsplitr10 = run $ runListWriter $ makeChoiceA tsplit tsplitr11 = run $ runListWriter $ makeChoiceA (msplit tsplit >>= reflect) tsplitr20 = run $ makeChoiceA $ runListWriter tsplit tsplitr21 = run $ makeChoiceA $ runListWriter (msplit tsplit >>= reflect) in assertEqual "tsplitr10" expected1 tsplitr10 >> assertEqual "tsplitr11" expected1 tsplitr11 >> assertEqual "tsplitr20" expected2 tsplitr20 >> assertEqual "tsplitr21" expected21 tsplitr21 where expected1 = ([1, 2],["begin", "end"]) expected2 = [(1, ["begin"]), (2, ["end"])] expected21 = [(1, ["begin"]), (2, ["begin", "end"])] tsplit = (tell "begin" >> return 1) `mplus` (tell "end" >> return 2) case_NDet_monadBaseControl :: Assertion case_NDet_monadBaseControl = runLift (makeChoiceA $ doThing (return 1 <|> return 2)) @=? Just [1,2] case_Choose_monadBaseControl :: Assertion case_Choose_monadBaseControl = runLift (makeChoice $ doThing $ choose [1,2,3]) @=? Just [1,2,3] case_NDet_cut :: Assertion case_NDet_cut = testCut (run . makeChoice) case_NDet_monadplus :: Assertion case_NDet_monadplus = let evalnw = run . (runListWriter @Int) . makeChoice evalwn = run . makeChoice . (runListWriter @Int) casesnw = [ -- mplus laws ("0 | NDet, Writer", evalnw t0, nw0) , ("zm0 = 0 | NDet, Writer", evalnw tzm0, nw0) , ("0m1 | NDet, Writer", evalnw t0m1, nw0m1) , ("zm0mzm1 = 0m1 | NDet, Writer", evalnw tzm0mzm1, nw0m1) -- mzero laws , ("z | NDet, Writer", evalnw tz, nwz) , ("z0 = z | NDet, Writer", evalnw tz0, nwz) , ("0z /= z | NDet, Writer", evalnw t0z, nw0z) , ("z0m1 = 1 | NDet, Writer", evalnw tz0m1, nw1) , ("0zm1 /= 1 | NDet, Writer", evalnw t0zm1, nw0zm1) ] caseswn = [ -- mplus laws ("0 | Writer, NDet", evalwn t0, wn0) , ("zm0 = 0 | Writer, NDet", evalwn tzm0, wn0) , ("0m1 | Writer, NDet", evalwn t0m1, wn0m1) , ("zm0mzm1 = 0m1 | Writer, NDet", evalwn tzm0mzm1, wn0m1) -- mzero laws , ("z | Writer, NDet", evalwn tz, wnz) , ("z0 = z | Writer, NDet", evalwn tz0, wnz) , ("0z = z | Writer, NDet", evalwn t0z, wnz) , ("z0m1 = 1 | Writer, NDet", evalwn tz0m1, wn1) , ("0zm1 = 1 | Writer, NDet", evalwn t0zm1, wn1) ] in runAsserts assertEqual casesnw >> runAsserts assertEqual caseswn where nwz = ([]::[Int],[]) wnz = [] ::[(Int, [Int])] nw0z = ([]::[Int],[0]) nw0 = ([0],[0]) nw1 = ([1],[1]) nw0zm1 = ([1],[0,1]) wn0 = [(0,[0])] wn1 = [(1,[1])] nw0m1 = ([0::Int,1],[0,1]) wn0m1 = [(0,[0]), (1,[1])] t0 = wr @Int 0 t1 = wr @Int 1 tz = mzero tz0 = tz >> t0 t0z = t0 >> tz tz0m1 = tz0 `mplus` t1 t0zm1 = t0z `mplus` t1 t0m1 = t0 `mplus` t1 tzm0 = tz `mplus` t0 tzm1 = tz `mplus` t1 tzm0mzm1 = tzm0 `mplus` tzm1 wr :: forall a r. [Writer a, NDet] <:: r => a -> Eff r a wr i = tell i >> return i
suhailshergill/extensible-effects
test/Control/Eff/Logic/NDet/Test.hs
mit
6,454
0
15
1,632
2,159
1,211
948
-1
-1
{-# LANGUAGE ForeignFunctionInterface #-} {-# LANGUAGE JavaScriptFFI #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE InterruptibleFFI #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE MagicHash #-} {-# LANGUAGE UnliftedFFITypes #-} {-# LANGUAGE GHCForeignImportPrim #-} {-# LANGUAGE UnboxedTuples #-} module JavaScript.Web.WebSocket ( WebSocket , WebSocketRequest(..) , ReadyState(..) , BinaryType(..) , connect , close , send , getBufferedAmount , getExtensions , getProtocol , getReadyState , getBinaryType , getUrl ) where import GHCJS.Concurrent import GHCJS.Prim import GHCJS.Foreign.Callback.Internal (Callback(..)) import qualified GHCJS.Foreign.Callback as CB import GHC.Exts import Control.Exception import Control.Monad import Data.Data import Data.Maybe import Data.Typeable import System.IO import Data.JSString (JSString) import qualified Data.JSString as JSS import JavaScript.Array (JSArray) import qualified JavaScript.Array as JSA import JavaScript.Web.MessageEvent import JavaScript.Web.MessageEvent.Internal import JavaScript.Web.CloseEvent import JavaScript.Web.CloseEvent.Internal import JavaScript.Web.ErrorEvent import JavaScript.Web.ErrorEvent.Internal import Unsafe.Coerce data WebSocketRequest = WebSocketRequest { url :: JSString , protocols :: [JSString] , onClose :: Maybe (CloseEvent -> IO ()) -- ^ called when the connection closes (at most once) , onMessage :: Maybe (MessageEvent -> IO ()) -- ^ called for each message } newtype WebSocket = WebSocket JSVal -- instance IsJSVal WebSocket data ReadyState = Closed | Connecting | Connected deriving (Data, Typeable, Enum, Eq, Ord, Show) data BinaryType = Blob | ArrayBuffer deriving (Data, Typeable, Enum, Eq, Ord, Show) {- | create a WebSocket -} connect :: WebSocketRequest -> IO WebSocket connect req = do mcb <- maybeCallback MessageEvent (onMessage req) ccb <- maybeCallback CloseEvent (onClose req) synchronously $ do ws <- case protocols req of [] -> js_createStr (url req) JSS.empty [x] -> js_createStr (url req) x xs -> js_createArr (url req) (JSA.fromList $ unsafeCoerce xs) -- fixme (js_open ws mcb ccb >>= handleOpenErr >> return ws) `onException` js_close 1000 "Haskell Exception" ws maybeCallback :: (JSVal -> a) -> Maybe (a -> IO ()) -> IO JSVal maybeCallback _ Nothing = return jsNull maybeCallback f (Just g) = do cb@(Callback cb') <- CB.syncCallback1 CB.ContinueAsync (g . f) CB.releaseCallback cb return cb' handleOpenErr :: JSVal -> IO () handleOpenErr r | isNull r = return () | otherwise = throwIO (userError "WebSocket failed to connect") -- fixme releaseMessageCallback :: WebSocket -> IO () releaseMessageCallback ws = js_getOnmessage ws >>= \cb -> unless (isNull cb) (CB.releaseCallback $ Callback cb) {- | close a websocket and release the callbacks -} close :: Maybe Int -> Maybe JSString -> WebSocket -> IO () close value reason ws = js_close (fromMaybe 1000 value) (fromMaybe JSS.empty reason) ws {-# INLINE close #-} send :: JSString -> WebSocket -> IO () send xs ws = js_send xs ws {-# INLINE send #-} getBufferedAmount :: WebSocket -> IO Int getBufferedAmount ws = js_getBufferedAmount ws {-# INLINE getBufferedAmount #-} getExtensions :: WebSocket -> IO JSString getExtensions ws = js_getExtensions ws {-# INLINE getExtensions #-} getProtocol :: WebSocket -> IO JSString getProtocol ws = js_getProtocol ws {-# INLINE getProtocol #-} getReadyState :: WebSocket -> IO ReadyState getReadyState ws = fmap toEnum (js_getReadyState ws) {-# INLINE getReadyState #-} getBinaryType :: WebSocket -> IO BinaryType getBinaryType ws = fmap toEnum (js_getBinaryType ws) {-# INLINE getBinaryType #-} getUrl :: WebSocket -> JSString getUrl ws = js_getUrl ws {-# INLINE getUrl #-} getLastError :: WebSocket -> IO (Maybe ErrorEvent) getLastError ws = do le <- js_getLastError ws return $ if isNull le then Nothing else Just (ErrorEvent le) {-# INLINE getLastError #-} -- ----------------------------------------------------------------------------- foreign import javascript safe "new WebSocket($1, $2)" js_createStr :: JSString -> JSString -> IO WebSocket foreign import javascript safe "new WebSocket($1, $2)" js_createArr :: JSString -> JSArray -> IO WebSocket foreign import javascript interruptible "h$openWebSocket($1, $2, $3, $c);" js_open :: WebSocket -> JSVal -> JSVal -> IO JSVal foreign import javascript safe "h$closeWebSocket($1, $2);" js_close :: Int -> JSString -> WebSocket -> IO () foreign import javascript unsafe "$2.send($1);" js_send :: JSString -> WebSocket -> IO () foreign import javascript unsafe "$1.bufferedAmount" js_getBufferedAmount :: WebSocket -> IO Int foreign import javascript unsafe "$1.readyState" js_getReadyState :: WebSocket -> IO Int foreign import javascript unsafe "$1.protocol" js_getProtocol :: WebSocket -> IO JSString foreign import javascript unsafe "$1.extensions" js_getExtensions :: WebSocket -> IO JSString foreign import javascript unsafe "$1.url" js_getUrl :: WebSocket -> JSString foreign import javascript unsafe "$1.binaryType === 'blob' ? 1 : 2" js_getBinaryType :: WebSocket -> IO Int foreign import javascript unsafe "$2.onopen = $1;" js_setOnopen :: Callback a -> WebSocket -> IO () foreign import javascript unsafe "$2.onclose = $1;" js_setOnclose :: Callback a -> WebSocket -> IO () foreign import javascript unsafe "$2.onopen = $1;" js_setOnerror :: Callback a -> WebSocket -> IO () foreign import javascript unsafe "$2.onmessage = $1;" js_setOnmessage :: Callback a -> WebSocket -> IO () foreign import javascript unsafe "$1.onmessage" js_getOnmessage :: WebSocket -> IO JSVal foreign import javascript unsafe "$1.lastError" js_getLastError :: WebSocket -> IO JSVal
NewByteOrder/ghcjs-base
JavaScript/Web/WebSocket.hs
mit
6,648
47
18
1,794
1,541
811
730
141
3
module Aut_COMP_HW1(accept) where delta :: Int -> Char -> Int delta 0 c |c=='e' = 5|c=='a' = 6|c=='b' = 3 delta 2 c |c=='b' = 3|c=='c' = 4 delta 3 c |c=='b' = 3 delta 4 c |c=='c' = 4 delta 5 c |c=='f' = 1 delta 6 c |c=='a' = 6|c=='b' = 2 delta _ _ = -1 initialState::Int initialState = 0 finalStates::[Int] finalStates = [1,2,3,4] accept::String -> Bool accept str = foldl delta initialState str `elem` finalStates
migulorama/AutoAnalyze
dot_dfa_examples/COMP_HW1.hs
mit
419
0
8
83
271
135
136
15
1
{-# LANGUAGE ScopedTypeVariables #-} module Main where import Control.Monad (filterM) import System.Environment (getArgs) import System.Exit import System.FilePath (takeExtension) import Text.JSON import Text.JSON.Git.Pretty import Util.File (recurseDirs) import qualified Data.ByteString as B main :: IO () main = do files <- getArgs case files of [] -> do putStrLn "NAME" putStrLn " jsonforgit" putStrLn "\nSYNOPSIS" putStrLn " jsonforgit [-R] [space delimited list of files to be prettified]" putStrLn "\nOPTIONS" putStrLn " -R prettify recursively all json files starting" putStrLn " with the currenty working directory" (option:_) -> case option of "-R" -> allJSON >>= mapM_ readWrite otherwise -> mapM_ readWrite files return () readWrite :: FilePath -> IO () readWrite fp = do json <- readFile fp let (result :: Result JSValue) = decode json case result of Ok a -> writeFile fp $ render $ pp_value a Error err -> do putStrLn err exitFailure allJSON :: IO [FilePath] allJSON = recurseDirs "." >>= filterM isJSON >>= mapM (return . drop 2) where isJSON :: FilePath -> IO Bool isJSON = return . (==) ".json" . takeExtension
phylake/json-for-git
json-for-git.hs
mit
1,321
0
14
368
376
183
193
39
3
module Atomo.Internals where import Control.Concurrent import Control.Concurrent.Chan import Control.Monad.Error import Data.List (intercalate) import Debug.Trace import Text.Parsec (ParseError) import Text.Parsec.Pos (newPos, sourceName, sourceLine, sourceColumn, SourcePos) dump s x = trace (s ++ ": " ++ show x) (return ()) debug x = trace (show x) x type ThrowsError = Either AtomoError type IOThrowsError = ErrorT AtomoError IO data Index = Define String | Class Type | Process ThreadId | Typeclass String | Instance String String deriving (Eq, Show) data Type = Name String | Type Type [Type] | Func Type Type | None | Poly String | Member [(String, Type)] Type -- (Show a) => a -> String as `Member [("Show", Poly "a")] (Func (Poly "a") (Func None (Name "String"))) deriving (Eq, Show) match :: Type -> Type -> Bool match (Func None a) b = match a b match a (Func None b) = match a b match (Name a) (Name b) = a == b match (Type a as) (Type b bs) = match a b && (and $ zipWith match as bs) match (Func a a') (Func b b') = match a b && match a' b' match (Poly a) (Poly b) = a == b match (None) (None) = True match (Name a) (Poly b) = True match (Poly a) (Name b) = False match _ _ = False instance Ord Type where compare (Poly _) (Name _) = LT compare (Name _) (Poly _) = GT compare (Name _) (Name _) = EQ compare (Poly _) (Poly _) = EQ compare (Type a as) (Type b bs) | compare a b == GT = GT | compare a b == EQ = compare (zipWith compare as bs) (zipWith compare bs as) | otherwise = LT compare (Func af at) (Func bf bt) | compare af bf == GT = GT | compare af bf == EQ = compare at bt | otherwise = LT compare _ (Poly _) = GT compare (Poly _) _ = LT compare _ _ = EQ instance Eq (Chan a) where _ == _ = False instance Show (Chan a) where show _ = "<Channel>" data AtomoVal = AInt Integer | AChar Char | ADouble Double | AList [AtomoVal] | ATuple [AtomoVal] | AHash [(String, (Type, AtomoVal))] | AString AtomoVal -- AString == AList of AChars | AVariable String | AClass Type [AtomoVal] [AtomoVal] | AObject Type [AtomoVal] | AAttribute AtomoVal String | ADefine Index AtomoVal | ADefAttr AtomoVal String AtomoVal | AStatic String AtomoVal | APrimCall String [AtomoVal] | ALambda PatternMatch AtomoVal [(PatternMatch, AtomoVal)] | ACall AtomoVal AtomoVal | ABlock [AtomoVal] | AData String [Type] | AConstruct String [Type] AtomoVal | AValue String [AtomoVal] AtomoVal | AIf AtomoVal AtomoVal AtomoVal | AReturn AtomoVal | AType String Type | AAnnot String Type | AImport String [String] | AModule [AtomoVal] | AError String | AAtom String | ASpawn AtomoVal | AReceive AtomoVal | AProcess ThreadId (Chan AtomoVal) | APattern PatternMatch AtomoVal | AFunction [AtomoVal] -- List of ALambdas to try different patterns | ATypeclass String Type AtomoVal | ATypeFunc String String | AInstance String String AtomoVal | ANone deriving (Eq, Show) data AtomoError = NumArgs Int Int SourcePos | ImmutableVar String SourcePos | TypeMismatch Type Type SourcePos | NotFunction String SourcePos | UnboundVar String SourcePos | Parser ParseError | Default String SourcePos | Unknown String deriving (Show) instance Error AtomoError where noMsg = Default "An error has occurred" (newPos "unknown" 0 0) strMsg = flip Default (newPos "unknown" 0 0) data PatternMatch = PAny | PMatch AtomoVal | PName String | PNamed String PatternMatch | PCons String [PatternMatch] | PHeadTail PatternMatch PatternMatch | PList [PatternMatch] | PTuple [PatternMatch] deriving (Eq, Show) fromAInt (AInt i) = i fromAInt (AValue "Integer" [AInt i] _) = i fromAChar (AChar c) = c fromAChar (AValue "Char" [AChar c] _) = c fromADouble (ADouble d) = d fromADouble (AValue "Double" [ADouble d] _) = d fromAVariable (AVariable n) = n fromAList (AList l) = l fromAList (AString l) = fromAList l fromAString (AString s) = map fromAChar (fromAList s) fromAString (AList l) = map fromAChar (fromAList (AList l)) fromAString a = error ("Not a string: `" ++ pretty a ++ "'") fromAConstruct (AConstruct s _ _) = s fromAAtom (AAtom n) = n -- String to an AList of AChars toAString :: String -> AtomoVal toAString s = AString $ AList (map AChar s) list :: Type list = Type (Name "[]") [Name "a"] listOf :: Type -> Type listOf a = Type (Name "[]") [a] result :: Type -> Type result (Func _ t) = t arg :: Type -> Type arg (Func t _) = t toFunc :: [Type] -> Type toFunc [] = None toFunc [t] = Func None t toFunc (t:ts) = Func t (toFunc ts) pretty :: AtomoVal -> String pretty (AInt int) = show int pretty (AChar char) = show char pretty (ADouble double) = show double pretty (AValue "Integer" [AInt i] _) = show i pretty (AValue "Double" [ADouble d] _) = show d pretty (AValue "Char" [AChar c] _) = show c pretty (AList str@(AChar _:_)) = pretty $ AString $ AList str pretty (AList list) = "[" ++ (intercalate ", " (map pretty list)) ++ "]" pretty (AHash es) = "{ " ++ (intercalate ", " (map prettyVal es)) ++ " }" where prettyVal (n, (t, v)) = (prettyType t) ++ " " ++ n ++ ": " ++ pretty v pretty (ATuple vs) = "(" ++ (intercalate ", " (map pretty vs)) ++ ")" pretty (AVariable n) = "<Variable (" ++ n ++ ")>" pretty (ADefine n v) = "<`" ++ show n ++ "': " ++ pretty v ++ ">" pretty (ADefAttr _ _ v) = pretty v pretty (AStatic _ v) = pretty v pretty (AObject _ vs) = "Object:\n" ++ (unlines $ map (" - " ++) $ map pretty vs) pretty (ACall f a) = "<Call (`" ++ pretty f ++ "') (`" ++ pretty a ++ "')>" pretty s@(AString _) = show $ fromAString s pretty (ABlock es) = intercalate "\n" $ map pretty es pretty (AData s as) = prettyType $ Type (Name s) as pretty (AConstruct s [] _) = s pretty (AConstruct s ts _) = s ++ " " ++ intercalate " " (map prettyType ts) pretty (AValue v [] _) = v pretty (AValue v as _) = v ++ " " ++ intercalate " " (map pretty as) pretty (AAnnot n t) = n ++ " :: " ++ prettyType t pretty v@(ALambda _ _ _) = "\x03BB " ++ intercalate " " (map prettyPattern $ reverse $ lambdas v []) ++ "." where lambdas (ALambda p v _) acc = lambdas v (p : acc) lambdas _ acc = acc pretty (AClass n ss ms) = "<Class `" ++ prettyType n ++ "' (`" ++ statics ++ "') (`" ++ methods ++ "')>" where statics = intercalate "' `" (map (\(AStatic n _) -> n) ss) methods = intercalate "' `" (map (\(ADefine (Define n) _) -> n) ms) pretty (AError m) = m pretty (AAtom n) = "@" ++ n pretty (AReceive v) = "<Receive>" pretty (APattern k v) = "<Pattern (" ++ show k ++ ") (" ++ show v ++ ")>" pretty (AFunction ls) = "<Function (" ++ intercalate ") (" (map pretty ls) ++ ")>" pretty ANone = "~" pretty a = "TODO -- " ++ show a prettyError (NumArgs e f p) = prettyPos p ++ "Expected " ++ show e ++ " args; found " ++ show f prettyError (ImmutableVar n p) = prettyPos p ++ "Cannot reassign immutable reference `" ++ n ++ "`" prettyError (TypeMismatch e f p) = prettyPos p ++ "Invalid type; expected `" ++ prettyType e ++ "', found `" ++ prettyType f ++ "'" prettyError (NotFunction n p) = prettyPos p ++ "Variable is not a function: " ++ n prettyError (UnboundVar n p) = prettyPos p ++ "Reference to unknown variable: " ++ n prettyError (Parser e) = "Parse error at " ++ show e prettyError (Default m p) = prettyPos p ++ m prettyError (Unknown m) = m prettyPattern PAny = "_" prettyPattern (PMatch v) = pretty v prettyPattern (PName a) = a prettyPattern (PNamed n p) = n ++ "@" ++ prettyPattern p prettyPattern (PCons n ps) = "(" ++ n ++ " " ++ intercalate " " (map prettyPattern ps) ++ ")" prettyPattern (PHeadTail h t) = "(" ++ prettyPattern h ++ ":" ++ prettyPattern t ++ ")" prettyPattern (PList ps) = "[" ++ intercalate ", " (map prettyPattern ps) ++ "]" prettyPattern (PTuple ps) = "(" ++ intercalate ", " (map prettyPattern ps) ++ ")" prettyPos :: SourcePos -> String prettyPos p | null $ sourceName p = "Line " ++ show (sourceLine p) ++ " Col " ++ show (sourceColumn p) ++ ":\n " | otherwise = "`" ++ sourceName p ++ "', line " ++ show (sourceLine p) ++ " Col " ++ show (sourceColumn p) ++ ":\n " prettyType :: Type -> String prettyType (Name a) = a prettyType (Type (Name "[]") []) = "[a]" prettyType (Type (Name "[]") [t]) = "[" ++ prettyType t ++ "]" prettyType (Type (Name "()") ts) = "(" ++ intercalate ", " (map prettyType ts) ++ ")" prettyType (Type a ts) = prettyType a ++ " " ++ intercalate " " (map prettyType ts) prettyType (Func None b) = prettyType b prettyType (Func a b) = "(" ++ prettyType a ++ " -> " ++ prettyType b ++ ")" prettyType (Poly a) = a prettyType (None) = "None" attribute :: AtomoVal -> AtomoVal -> AtomoVal attribute f (AVariable n) = AAttribute f n attribute f (AAttribute (AVariable a) b) = AAttribute (AAttribute f a) b attribute f x = error ("Cannot morph: " ++ show (f, x)) lambdify :: [PatternMatch] -> AtomoVal -> AtomoVal lambdify [] b = b lambdify (s:ss) b = ALambda s (lambdify ss b) [] callify :: [AtomoVal] -> AtomoVal -> AtomoVal callify as t = callify' (reverse as) t where callify' [] t = ACall t ANone callify' (a:as) t = ACall (callify' as t) a static :: AtomoVal -> [AtomoVal] static (ABlock xs) = static' xs where static' [] = [] static' (v@(AStatic _ _):xs) = v : static' xs static' (_:xs) = static' xs public :: AtomoVal -> [AtomoVal] public (ABlock xs) = public' xs where public' [] = [] public' (v@(ADefine _ _):xs) = v : public' xs public' (_:xs) = public' xs getType :: AtomoVal -> Type getType (AChar _) = Name "char" getType (ADouble _) = Name "double" getType (AList []) = Type (Name "[]") [Poly "a"] getType (AList as) = listOf $ getType (head as) getType (ATuple as) = Type (Name "()") $ map getType as getType (AHash _) = Name "hash" getType (AString _) = listOf (Name "char") getType (AType n v) = v getType (AConstruct _ [] d@(AData n ps)) = getType d getType (AConstruct _ ts d@(AData n ps)) = foldr Func (getType d) ts getType (AData n []) = Name n getType (AData n as) = Type (Name n) as getType (ALambda _ b _) = error "Cannot get type of a lambda." -- TODO getType (AReturn r) = getType r getType (ADefine _ v) = getType v getType (AValue _ _ (AConstruct _ _ d@(AData n []))) = getType d getType (AValue c as (AConstruct _ cs (AData n ps))) = Type (Name n) (args cs as ps) where args [] [] ps = ps args (c:cs) (a:as) ps = args cs as (swapType ps c (getType a)) getType (AObject t _) = t getType a = error ("Cannot get type of `" ++ pretty a ++ "'") getData :: AtomoVal -> String getData (AValue _ _ c) = getData c getData (AConstruct _ _ (AData n _)) = n getData (AData n _) = n getData (AList _) = "[]" getData v = error ("Cannot get data name for `" ++ pretty v ++ "'") -- Deep-replace a type with another type (used for replacing polymorphic types) swapType :: [Type] -> Type -> Type -> [Type] swapType ts t n = swapType' ts [] t n where swapType' [] acc _ _ = acc swapType' (t@(Type a ts'):ts) acc f r = swapType' ts (acc ++ [Type (repl a f r) (swapType ts' f r)]) f r swapType' (t@(Func a b):ts) acc f r = swapType' ts (acc ++ [Func (repl a f r) (repl b f r)]) f r swapType' (t:ts) acc f r = swapType' ts (acc ++ [repl t f r]) f r repl a f r | a == f = r | otherwise = a
vito/atomo-old
Atomo/Internals.hs
mit
13,070
0
15
4,288
5,215
2,637
2,578
263
4
import Control.Arrow encode :: Eq a => [a] -> [(Int, a)] encode = map (length &&& head) . group
tamasgal/haskell_exercises
99questions/Problem10.hs
mit
97
0
8
20
53
29
24
3
1
{-# LANGUAGE TupleSections #-} module Graphics.Render.Quad( quadWithNormal , quadNoShading ) where import Graphics.GPipe import Graphics.Quad import Graphics.Camera2D import Graphics.Light import Graphics.Render.Camera import Graphics.Render.Light import Data.Vec as Vec import Control.Applicative import Data.Maybe (fromMaybe) -- | Simple rendering of quad with diffuse texture quadNoShading :: Camera2D -- ^ Camera -- | Diffuse texture -> Texture2D RGBAFormat -- | Ambient color, alpha is intensity -> Vec4 Float -- | Color modifier, alpha is intensity -> Vec4 Float -- | Translation in world -> Vec2 Float -- | Rotation in world -> Float -- | Depth (Z coordinate) -> Float -- | Size of viewport -> Vec2 Int -- | Fragments -> FragmentStream (Color RGBAFormat (Fragment Float), FragmentDepth) quadNoShading cam2d tex ambient clr trans2d rot2d depth size = storeDepth . texturise <$> rasterizeFront (transform <$> screenQuad depth) where storeDepth = (, fragDepth) transform = cameraTransform2D cam2d trans2d rot2d size texturise = enlightSimple tex ambient clr -- | Render 2D quad with diffuse and normal map quadWithNormal :: Camera2D -- ^ Camera -- | Diffuse texture -> Texture2D RGBAFormat -- | Normal texture -> Texture2D RGBAFormat -- | Ambient color, alpha is entensity -> Vec4 Float -- | Color modifier, alpha is intensity -> Vec4 Float -- | Lights that is used for enlighting -> [Light Float] -- | Translation in world -> Vec2 Float -- | Rotation in world -> Float -- | Depth (Z coordinate) -> Float -- | Size of viewport -> Vec2 Int -- | Fragments -> FragmentStream (Color RGBAFormat (Fragment Float), FragmentDepth) quadWithNormal cam2d@(Camera2D cam) tex ntex ambient clr lights trans2d rot2d depth size = storeDepth . texturise <$> rasterizeFront (transform <$> screenQuad depth) where storeDepth = (, fragDepth) vpMat = vpMatrix cam size vpMatInv = fromMaybe Vec.identity . Vec.invert $ vpMat transform = cameraTransform2D cam2d trans2d rot2d size texturise = enlightNormal size tex ntex ambient clr lights vpMatInv
NCrashed/sinister
src/client/Graphics/Render/Quad.hs
mit
2,163
0
19
442
464
251
213
45
1
{-# LANGUAGE DeriveDataTypeable #-} module HWB.Plugin.Keybinding ( Keybinding(..), tryKeybindings ) where import Control.Applicative ((<$>), (<*>), (<$)) import Control.Concurrent.MVar (MVar, newMVar, putMVar, takeMVar) import Control.Monad.IO.Class (liftIO) import Control.Monad.Trans.Class (MonadTrans(lift)) import Control.Monad.Trans.Reader (ask) import Control.Monad.Trans.State (get) import Data.List (find) import Data.Maybe (fromMaybe) import Data.Typeable (Typeable) import Graphics.UI.Gtk.Gdk.EventM (EventM, EKey, eventKeyVal) import Graphics.UI.Gtk.Gdk.Keys (keyName) import System.Glib.UTFString (glibToString) import System.IO.Unsafe (unsafePerformIO) import XMonad.Core (ExtensionClass(..)) import HWB.Core (H, runH) import qualified HWB.Plugin.Utilities.ExtensibleState as HWB (get) data Buffer a = Buffer (Maybe a) (Maybe a) deriving (Show, Eq, Typeable) instance Typeable a => ExtensionClass (Buffer a) where initialValue = Buffer Nothing Nothing pushBuffer :: a -> Buffer a -> Buffer a pushBuffer c (Buffer _ b) = Buffer b $ Just c parseBuffer :: String -> Buffer Char -- xxx hack parseBuffer [] = Buffer Nothing Nothing parseBuffer (x:[]) = Buffer Nothing (Just x) parseBuffer (x:y:[]) = Buffer (Just x) (Just y) parseBuffer (_:xs) = parseBuffer xs data Keybinding = String :== H () infixr 0 :== fromKeybindings :: [Keybinding] -> Buffer Char -> H () fromKeybindings keybindings (Buffer w x) = fromMaybe (return ()) . fmap snd . find (\(Buffer y z,_) -> case y of { Nothing -> x == z ; Just _ -> w == y && x == z }) $ map (\(b :== c) -> (parseBuffer b, c)) keybindings instance ExtensionClass a => ExtensionClass (MVar a) where initialValue = unsafePerformIO $ newMVar initialValue -- Hell can't be so bad.. right? tryKeybindings :: [Keybinding] -> H (EventM EKey Bool) tryKeybindings keybindings = do escape <- runH <$> lift get <*> ask return $ False <$ do current <- head . glibToString . keyName <$> eventKeyVal liftIO . escape $ HWB.get >>= \stored -> do buffer <- liftIO $ pushBuffer current <$> takeMVar stored liftIO $ putMVar stored buffer fromKeybindings keybindings buffer
fmap/hwb
src/HWB/Plugin/Keybinding.hs
mit
2,160
0
17
356
822
449
373
48
2
import Data.List main = print $ length [ (n,d) | d <- [1..12000], n <- [1..d], gcd d n == 1, toFloat (n,d) < toFloat (1,2), toFloat (n,d) > toFloat (1,3) ] toFloat :: (Int, Int) -> Float toFloat (a,b) = (fromIntegral a) / (fromIntegral b)
lekto/haskell
Project-Euler-Solutions/problem0073.hs
mit
241
0
11
48
163
88
75
4
1
{-# LANGUAGE RecordWildCards #-} module LightingTechnique ( LightingTechnique(..) , DirectionLight(..) , changeAmbIntensity , changeDiffIntensity , initLightingTechnique , setLightingWVP , setLightingWorldMatrix , setLightingTextureUnit , setDirectionalLight , setEyeWorldPos , setMatSpecularPower , setMaterialSpecularIntensity ) where import Graphics.GLUtil import Graphics.Rendering.OpenGL import Hogldev.Technique data DirectionLight = DirectionLight { ambientColor :: !(Vertex3 GLfloat) , ambientIntensity :: !GLfloat , diffuseDirection :: !(Vertex3 GLfloat) , diffuseIntensity :: !GLfloat } deriving Show changeAmbIntensity :: (GLfloat -> GLfloat) -> DirectionLight -> DirectionLight changeAmbIntensity f dir@DirectionLight{..} = dir { ambientIntensity = f ambientIntensity } changeDiffIntensity :: (GLfloat -> GLfloat) -> DirectionLight -> DirectionLight changeDiffIntensity f dir@DirectionLight{..} = dir { diffuseIntensity = f diffuseIntensity } data LightingTechnique = LightingTechnique { lProgram :: !Program , lWVPLoc :: !UniformLocation , lWorldMatrixLoc :: !UniformLocation , lSamplerLoc :: !UniformLocation , lDirLightColorLoc :: !UniformLocation , lDirLightAmbientIntensityColorLoc :: !UniformLocation , lDirLightDirectionLoc :: !UniformLocation , lDirLightIntensity :: !UniformLocation , lEyeWorldPosLoc :: !UniformLocation , lMatSpecularIntensityLoc :: !UniformLocation , lMatSpecularPowerLoc :: !UniformLocation } initLightingTechnique :: IO LightingTechnique initLightingTechnique = do program <- createProgram addShader program "tutorial19/lighting.vs" VertexShader addShader program "tutorial19/lighting.fs" FragmentShader finalize program wvpLoc <- getUniformLocation program "gWVP" worldMatrixLoc <- getUniformLocation program "gWorld" samplerLoc <- getUniformLocation program "gSampler" dirLightColorLoc <- getUniformLocation program "gDirectionalLight.Color" dirLightAmbientIntensityLoc <- getUniformLocation program "gDirectionalLight.AmbientIntensity" dirLightDirectionLoc <- getUniformLocation program "gDirectionalLight.Direction" dirLightDiffuseIntensity <- getUniformLocation program "gDirectionalLight.DiffuseIntensity" eyeWorldPosition <- getUniformLocation program "gEyeWorldPos" matSpecularIntensity <- getUniformLocation program "gMatSpecularIntensity" matSpecularPower <- getUniformLocation program "gSpecularPower" return LightingTechnique { lProgram = program , lWVPLoc = wvpLoc , lWorldMatrixLoc = worldMatrixLoc , lSamplerLoc = samplerLoc , lDirLightColorLoc = dirLightColorLoc , lDirLightAmbientIntensityColorLoc = dirLightAmbientIntensityLoc , lDirLightDirectionLoc = dirLightDirectionLoc , lDirLightIntensity = dirLightDiffuseIntensity , lEyeWorldPosLoc = matSpecularIntensity , lMatSpecularIntensityLoc = eyeWorldPosition , lMatSpecularPowerLoc = matSpecularPower } setLightingWVP :: LightingTechnique -> [[GLfloat]] -> IO () setLightingWVP LightingTechnique{..} mat = uniformMat lWVPLoc $= mat setLightingWorldMatrix :: LightingTechnique -> [[GLfloat]] -> IO () setLightingWorldMatrix LightingTechnique{..} mat = uniformMat lWorldMatrixLoc $= mat setLightingTextureUnit :: LightingTechnique -> GLuint -> IO () setLightingTextureUnit LightingTechnique{..} textureUnit = uniformScalar lSamplerLoc $= textureUnit setDirectionalLight :: LightingTechnique -> DirectionLight -> IO () setDirectionalLight LightingTechnique{..} DirectionLight{..} = do uniformVec lDirLightColorLoc $= [cx, cy, cz] uniformScalar lDirLightAmbientIntensityColorLoc $= ambientIntensity uniformVec lDirLightDirectionLoc $= [lx, ly, lz] uniformScalar lDirLightIntensity $= diffuseIntensity where (Vertex3 cx cy cz) = ambientColor (Vertex3 lx ly lz) = diffuseDirection setMaterialSpecularIntensity :: LightingTechnique -> GLfloat -> IO () setMaterialSpecularIntensity LightingTechnique{..} intensity = uniformScalar lSamplerLoc $= intensity setMatSpecularPower :: LightingTechnique -> GLfloat -> IO () setMatSpecularPower LightingTechnique{..} power = uniformScalar lMatSpecularPowerLoc $= power setEyeWorldPos :: LightingTechnique -> Vector3 GLfloat -> IO () setEyeWorldPos LightingTechnique{..} (Vector3 x y z) = uniformVec lEyeWorldPosLoc $= [x, y, z]
triplepointfive/hogldev
tutorial19/LightingTechnique.hs
mit
4,908
0
11
1,154
957
499
458
129
1
{-# LANGUAGE CPP #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE DefaultSignatures #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE FlexibleInstances #-} #ifndef NO_OVERLAP {-# LANGUAGE OverlappingInstances #-} #endif module Database.Persist.Sql.Class ( RawSql (..) , PersistFieldSql (..) ) where import Control.Applicative ((<$>), (<*>)) import Database.Persist import Data.Monoid ((<>)) import Database.Persist.Sql.Types import Control.Arrow ((&&&)) import Data.Text (Text, intercalate, pack) import Data.Maybe (fromMaybe) import Data.Fixed import Data.Proxy (Proxy) import Control.Monad.IO.Class (MonadIO) import Control.Monad.Trans.Class (MonadTrans) import qualified Data.Text as T import qualified Data.Text.Lazy as TL import qualified Data.Map as M import qualified Data.Set as S import Data.Time (UTCTime, TimeOfDay, Day) import Data.Int import Data.Word import Data.ByteString (ByteString) import Text.Blaze.Html (Html) import Data.Bits (bitSize) import qualified Data.Vector as V -- | Class for data types that may be retrived from a 'rawSql' -- query. class RawSql a where -- | Number of columns that this data type needs and the list -- of substitutions for @SELECT@ placeholders @??@. rawSqlCols :: (DBName -> Text) -> a -> (Int, [Text]) -- | A string telling the user why the column count is what -- it is. rawSqlColCountReason :: a -> String -- | Transform a row of the result into the data type. rawSqlProcessRow :: [PersistValue] -> Either Text a instance PersistField a => RawSql (Single a) where rawSqlCols _ _ = (1, []) rawSqlColCountReason _ = "one column for a 'Single' data type" rawSqlProcessRow [pv] = Single <$> fromPersistValue pv rawSqlProcessRow _ = Left $ pack "RawSql (Single a): wrong number of columns." instance (PersistEntity a, PersistEntityBackend a ~ SqlBackend) => RawSql (Entity a) where rawSqlCols escape = ((+1) . length . entityFields &&& process) . entityDef . Just . entityVal where process ed = (:[]) $ intercalate ", " $ map ((name ed <>) . escape) $ (fieldDB (entityId ed) :) $ map fieldDB $ entityFields ed name ed = escape (entityDB ed) <> "." rawSqlColCountReason a = case fst (rawSqlCols (error "RawSql") a) of 1 -> "one column for an 'Entity' data type without fields" n -> show n ++ " columns for an 'Entity' data type" rawSqlProcessRow (idCol:ent) = Entity <$> fromPersistValue idCol <*> fromPersistValues ent rawSqlProcessRow _ = Left "RawSql (Entity a): wrong number of columns." -- | Since 1.0.1. instance RawSql a => RawSql (Maybe a) where rawSqlCols e = rawSqlCols e . extractMaybe rawSqlColCountReason = rawSqlColCountReason . extractMaybe rawSqlProcessRow cols | all isNull cols = return Nothing | otherwise = case rawSqlProcessRow cols of Right v -> Right (Just v) Left msg -> Left $ "RawSql (Maybe a): not all columns were Null " <> "but the inner parser has failed. Its message " <> "was \"" <> msg <> "\". Did you apply Maybe " <> "to a tuple, perhaps? The main use case for " <> "Maybe is to allow OUTER JOINs to be written, " <> "in which case 'Maybe (Entity v)' is used." where isNull PersistNull = True isNull _ = False instance (RawSql a, RawSql b) => RawSql (a, b) where rawSqlCols e x = rawSqlCols e (fst x) # rawSqlCols e (snd x) where (cnta, lsta) # (cntb, lstb) = (cnta + cntb, lsta ++ lstb) rawSqlColCountReason x = rawSqlColCountReason (fst x) ++ ", " ++ rawSqlColCountReason (snd x) rawSqlProcessRow = let x = getType processRow getType :: (z -> Either y x) -> x getType = error "RawSql.getType" colCountFst = fst $ rawSqlCols (error "RawSql.getType2") (fst x) processRow row = let (rowFst, rowSnd) = splitAt colCountFst row in (,) <$> rawSqlProcessRow rowFst <*> rawSqlProcessRow rowSnd in colCountFst `seq` processRow -- Avoids recalculating 'colCountFst'. instance (RawSql a, RawSql b, RawSql c) => RawSql (a, b, c) where rawSqlCols e = rawSqlCols e . from3 rawSqlColCountReason = rawSqlColCountReason . from3 rawSqlProcessRow = fmap to3 . rawSqlProcessRow from3 :: (a,b,c) -> ((a,b),c) from3 (a,b,c) = ((a,b),c) to3 :: ((a,b),c) -> (a,b,c) to3 ((a,b),c) = (a,b,c) instance (RawSql a, RawSql b, RawSql c, RawSql d) => RawSql (a, b, c, d) where rawSqlCols e = rawSqlCols e . from4 rawSqlColCountReason = rawSqlColCountReason . from4 rawSqlProcessRow = fmap to4 . rawSqlProcessRow from4 :: (a,b,c,d) -> ((a,b),(c,d)) from4 (a,b,c,d) = ((a,b),(c,d)) to4 :: ((a,b),(c,d)) -> (a,b,c,d) to4 ((a,b),(c,d)) = (a,b,c,d) instance (RawSql a, RawSql b, RawSql c, RawSql d, RawSql e) => RawSql (a, b, c, d, e) where rawSqlCols e = rawSqlCols e . from5 rawSqlColCountReason = rawSqlColCountReason . from5 rawSqlProcessRow = fmap to5 . rawSqlProcessRow from5 :: (a,b,c,d,e) -> ((a,b),(c,d),e) from5 (a,b,c,d,e) = ((a,b),(c,d),e) to5 :: ((a,b),(c,d),e) -> (a,b,c,d,e) to5 ((a,b),(c,d),e) = (a,b,c,d,e) instance (RawSql a, RawSql b, RawSql c, RawSql d, RawSql e, RawSql f) => RawSql (a, b, c, d, e, f) where rawSqlCols e = rawSqlCols e . from6 rawSqlColCountReason = rawSqlColCountReason . from6 rawSqlProcessRow = fmap to6 . rawSqlProcessRow from6 :: (a,b,c,d,e,f) -> ((a,b),(c,d),(e,f)) from6 (a,b,c,d,e,f) = ((a,b),(c,d),(e,f)) to6 :: ((a,b),(c,d),(e,f)) -> (a,b,c,d,e,f) to6 ((a,b),(c,d),(e,f)) = (a,b,c,d,e,f) instance (RawSql a, RawSql b, RawSql c, RawSql d, RawSql e, RawSql f, RawSql g) => RawSql (a, b, c, d, e, f, g) where rawSqlCols e = rawSqlCols e . from7 rawSqlColCountReason = rawSqlColCountReason . from7 rawSqlProcessRow = fmap to7 . rawSqlProcessRow from7 :: (a,b,c,d,e,f,g) -> ((a,b),(c,d),(e,f),g) from7 (a,b,c,d,e,f,g) = ((a,b),(c,d),(e,f),g) to7 :: ((a,b),(c,d),(e,f),g) -> (a,b,c,d,e,f,g) to7 ((a,b),(c,d),(e,f),g) = (a,b,c,d,e,f,g) instance (RawSql a, RawSql b, RawSql c, RawSql d, RawSql e, RawSql f, RawSql g, RawSql h) => RawSql (a, b, c, d, e, f, g, h) where rawSqlCols e = rawSqlCols e . from8 rawSqlColCountReason = rawSqlColCountReason . from8 rawSqlProcessRow = fmap to8 . rawSqlProcessRow from8 :: (a,b,c,d,e,f,g,h) -> ((a,b),(c,d),(e,f),(g,h)) from8 (a,b,c,d,e,f,g,h) = ((a,b),(c,d),(e,f),(g,h)) to8 :: ((a,b),(c,d),(e,f),(g,h)) -> (a,b,c,d,e,f,g,h) to8 ((a,b),(c,d),(e,f),(g,h)) = (a,b,c,d,e,f,g,h) extractMaybe :: Maybe a -> a extractMaybe = fromMaybe (error "Database.Persist.GenericSql.extractMaybe") class PersistField a => PersistFieldSql a where sqlType :: Proxy a -> SqlType #ifndef NO_OVERLAP instance PersistFieldSql String where sqlType _ = SqlString #endif instance PersistFieldSql ByteString where sqlType _ = SqlBlob instance PersistFieldSql T.Text where sqlType _ = SqlString instance PersistFieldSql TL.Text where sqlType _ = SqlString instance PersistFieldSql Html where sqlType _ = SqlString instance PersistFieldSql Int where sqlType _ | bitSize (0 :: Int) <= 32 = SqlInt32 | otherwise = SqlInt64 instance PersistFieldSql Int8 where sqlType _ = SqlInt32 instance PersistFieldSql Int16 where sqlType _ = SqlInt32 instance PersistFieldSql Int32 where sqlType _ = SqlInt32 instance PersistFieldSql Int64 where sqlType _ = SqlInt64 instance PersistFieldSql Word where sqlType _ = SqlInt64 instance PersistFieldSql Word8 where sqlType _ = SqlInt32 instance PersistFieldSql Word16 where sqlType _ = SqlInt32 instance PersistFieldSql Word32 where sqlType _ = SqlInt64 instance PersistFieldSql Word64 where sqlType _ = SqlInt64 instance PersistFieldSql Double where sqlType _ = SqlReal instance PersistFieldSql Bool where sqlType _ = SqlBool instance PersistFieldSql Day where sqlType _ = SqlDay instance PersistFieldSql TimeOfDay where sqlType _ = SqlTime instance PersistFieldSql UTCTime where sqlType _ = SqlDayTime instance PersistFieldSql a => PersistFieldSql [a] where sqlType _ = SqlString instance PersistFieldSql a => PersistFieldSql (V.Vector a) where sqlType _ = SqlString instance (Ord a, PersistFieldSql a) => PersistFieldSql (S.Set a) where sqlType _ = SqlString instance (PersistFieldSql a, PersistFieldSql b) => PersistFieldSql (a,b) where sqlType _ = SqlString instance PersistFieldSql v => PersistFieldSql (M.Map T.Text v) where sqlType _ = SqlString instance PersistFieldSql PersistValue where sqlType _ = SqlInt64 -- since PersistValue should only be used like this for keys, which in SQL are Int64 instance PersistFieldSql Checkmark where sqlType _ = SqlBool instance (HasResolution a) => PersistFieldSql (Fixed a) where sqlType a = SqlNumeric long prec where prec = round $ (log $ fromIntegral $ resolution n) / (log 10 :: Double) -- FIXME: May lead to problems with big numbers long = prec + 10 -- FIXME: Is this enough ? n = 0 _mn = return n `asTypeOf` a instance PersistFieldSql Rational where sqlType _ = SqlNumeric 32 20 -- need to make this field big enough to handle Rational to Mumber string conversion for ODBC -- An embedded Entity instance (PersistField record, PersistEntity record) => PersistFieldSql (Entity record) where sqlType _ = SqlString
junjihashimoto/persistent
persistent/Database/Persist/Sql/Class.hs
mit
10,109
0
17
2,608
3,613
2,048
1,565
-1
-1
module Currification (tests) where import Test.Hspec (Spec, describe, it) import Test.HUnit (assertBool, assertEqual) tests :: Spec tests = describe "Currification" $ do testCurrificationPlus testCurrificationMap testCurrificationFilter failError msg = const $ error $ "You should try using \x1B[33;1m\"" ++ msg ++ "\"\x1B[0m" testCurrificationPlus :: Spec testCurrificationPlus = it "currification of +" $ do let plus2 = (+2) assertEqual "" 2 (plus2 0) assertEqual "" 3 (plus2 1) testCurrificationMap :: Spec testCurrificationMap = it "currification of map" $ do let addFn = map (+1) assertEqual "" [1..4] (addFn [0..3]) assertEqual "" [2..5] $ addFn [1..4] testCurrificationFilter :: Spec testCurrificationFilter = it "currification of filter" $ do let filterFn = filter even assertEqual "" [2, 4, 6, 8, 10] (filterFn [1..10]) assertEqual "" [12, 14, 16, 18, 20] (filterFn [11..20])
leroux/HaskellKoans
test/Currification.hs
mit
976
0
12
218
335
174
161
28
1
module Euler.E30 where import Euler.Lib (intToList) euler30 :: Int -> Int euler30 n = sum $ [ x | x <- [2 .. upperLimit n], isSumOfDigitsPow n x] upperLimit :: Int -> Int upperLimit n = aux $ last $ takeWhile (helper) $ dropWhile (not . helper) [1..] where aux :: Int -> Int aux = (* 9^n) helper :: Int -> Bool helper x = x == (length $ intToList $ aux x) isSumOfDigitsPow :: Int -> Int -> Bool isSumOfDigitsPow n x = x == (sum $ map (^n) $ intToList $ x) main :: IO () main = print $ euler30 5
D4r1/project-euler
Euler/E30.hs
mit
509
0
11
119
246
131
115
14
1
{-# OPTIONS_GHC -fno-warn-orphans #-} {-# LANGUAGE ScopedTypeVariables #-} module PostgREST.Middleware where import Data.Maybe (fromMaybe) import Data.Text import Data.String.Conversions (cs) import Data.Time.Clock (NominalDiffTime) import qualified Hasql as H import qualified Hasql.Postgres as P import Network.HTTP.Types.Header (hAccept, hAuthorization) import Network.HTTP.Types.Status (status415, status400) import Network.Wai (Application, Request (..), Response, requestHeaders) import Network.Wai.Middleware.Cors (cors) import Network.Wai.Middleware.Gzip (def, gzip) import Network.Wai.Middleware.Static (only, staticPolicy) import PostgREST.ApiRequest (pickContentType) import PostgREST.Auth (setRole, jwtClaims, claimsToSQL) import PostgREST.Config (AppConfig (..), corsPolicy) import PostgREST.Error (errResponse) import Prelude hiding(concat) import qualified Data.Vector as V import qualified Hasql.Backend as B import qualified Data.Map.Lazy as M runWithClaims :: forall s. AppConfig -> NominalDiffTime -> (Request -> H.Tx P.Postgres s Response) -> Request -> H.Tx P.Postgres s Response runWithClaims conf time app req = do _ <- H.unitEx $ stmt setAnon case split (== ' ') (cs auth) of ("Bearer" : tokenStr : _) -> case jwtClaims jwtSecret tokenStr time of Just claims -> if M.member "role" claims then do mapM_ H.unitEx $ stmt <$> claimsToSQL claims app req else invalidJWT _ -> invalidJWT _ -> app req where stmt c = B.Stmt c V.empty True hdrs = requestHeaders req jwtSecret = configJwtSecret conf auth = fromMaybe "" $ lookup hAuthorization hdrs anon = cs $ configAnonRole conf setAnon = setRole anon invalidJWT = return $ errResponse status400 "Invalid JWT" unsupportedAccept :: Application -> Application unsupportedAccept app req respond = case accept of Left _ -> respond $ errResponse status415 "Unsupported Accept header, try: application/json" Right _ -> app req respond where accept = pickContentType $ lookup hAccept $ requestHeaders req defaultMiddle :: Application -> Application defaultMiddle = gzip def . cors corsPolicy . staticPolicy (only [("favicon.ico", "static/favicon.ico")]) . unsupportedAccept
NikolayS/postgrest
src/PostgREST/Middleware.hs
mit
2,726
0
19
868
657
363
294
59
4
import Text.Parsec data Point = P { getX :: Int, getY :: Int } deriving (Show, Ord, Eq) data Vect = V { getVX :: Int, getVY :: Int } deriving (Show, Ord, Eq) data Triangle = T { getP1 :: Point, getP2 :: Point, getP3 :: Point } deriving (Show, Ord, Eq) (~-~) :: Point -> Point -> Vect (P x0 y0) ~-~ (P x1 y1) = V (x0-x1) (y0-y1) (~*~) :: Vect -> Vect -> Int (V x0 y0) ~*~ (V x1 y1) = x0*x1 + y0*y1 (~^~) :: Vect -> Vect -> Int (V x0 y0) ~^~ (V x1 y1) = x0*y1 - x1*y0 origin = P 0 0 -- parsing parseTriangles :: String -> Either ParseError [Triangle] parseTriangles input = parse triangles "(triangles)" input triangles = endBy triangle eol eol = char '\n' triangle = do p1 <- point char ',' p2 <- point char ',' p3 <- point return $ T p1 p2 p3 point = do x <- signedInteger char ',' y <- signedInteger return $ P x y signedInteger = do s <- oneOf "-0123456789" ds <- many digit return $ read (s:ds) -- end of parsing main = do text <- readFile "p102_triangles.txt" case parseTriangles text of Left err -> print err Right triangles -> do let answer = process triangles print answer process triangles = length $ filter (contains origin) triangles -- check if P0 and P1 are on the same side of the AB line sameSide p0 p1 pa pb = let va0 = p0 ~-~ pa va1 = p1 ~-~ pa vab = pb ~-~ pa abc0 = vab ~^~ va0 abc1 = vab ~^~ va1 in (abc0<0 && abc1<0) || (abc0>0 && abc1>0) contains point (T p1 p2 p3) = sameSide point p1 p2 p3 && sameSide point p2 p3 p1 && sameSide point p3 p1 p2
arekfu/project_euler
p0102/p0102.hs
mit
1,716
20
15
558
753
362
391
46
2
{-| Module : Language.Vigil.Simplify.Expr Description : Copyright : (c) Jacob Errington and Frederic Lafrance, 2016 License : MIT Maintainer : goto@mail.jerrington.me Stability : experimental Simplifications for expressions. -} {-# LANGUAGE ViewPatterns #-} module Language.Vigil.Simplify.Expr ( SimpleExprResult(..) , SimpleConstituent(..) , CircuitOp(..) , simplifyExpr , gToVBinOp , typeFromSimple , typeFromVal ) where import Language.GoLite.Syntax.Types as G import Language.GoLite.Types as T import Language.Vigil.Simplify.Core import Language.Vigil.Syntax as V import Language.Vigil.Syntax.Basic as V import Language.Vigil.Syntax.TyAnn as V import Language.Vigil.Types as V import Language.X86.Mangling import Language.Common.Pretty import Language.Common.Misc ( unFix ) -- | The final result of a simplified expression data SimpleExprResult = Result SimpleConstituent -- ^ A normal result. | Temp (V.BasicIdent, SimpleConstituent) -- ^ A temporary, which will need to receive the value from the given -- constituent. | ShortCircuit V.BasicIdent CircuitOp [SimpleExprResult] [SimpleExprResult] -- ^ A short-circuit. Indicates that special statements need to be generated -- for this expression. The provided identifier will be used as a temporary, -- the provided operation will determine the conditions of short-circuiting, -- and the two lists of results indicate the left and the right expressions, -- the right being the one that can be short-circuited. -- | In a short-circuit, indicates the type of expression that is split. data CircuitOp = And | Or -- | Simplifying an expression could result either in a value, a reference, or a -- Vigil expression. We always try to reduce to the simplest possible form, so -- for example, the GoLite expression @a@ would become a Vigil value. data SimpleConstituent = SimpleExpr TyAnnExpr | SimpleRef TyAnnRef | SimpleVal TyAnnVal instance Pretty SimpleConstituent where pretty a = case a of SimpleExpr x -> pretty x SimpleRef x -> pretty x SimpleVal x -> pretty x -- | Simplifies a full-fledged GoLite expression into a (potentially some) Vigil -- expressions. -- -- Generated temporary sub-expressions are accumulated in a stack. The stack is -- percolated up to the top of the expression tree, with each node potentially -- adding more onto it. -- -- Note that it is assumed that after any given simplification, the top of the -- stack will not be a temporary or a "ValRef". @ValRef@s are created at a later -- stage. simplifyExpr :: TySrcAnnExpr -> Simplify [SimpleExprResult] simplifyExpr = annCata phi where phi :: TySrcSpan -> TySrcAnnExprF (Simplify [SimpleExprResult]) -> Simplify [SimpleExprResult] phi a ex = case ex of G.BinaryOp o l r -> do (vl, esl) <- exprAsVal =<< l (vr, esr) <- exprAsVal =<< r a' <- reinterpretTypeEx $ fst a let es = esl ++ esr -- Should this be a conditional, short-circuit or binary expression? let o' = bare o in if isComparisonOp o' || isOrderingOp o' then pure $ ( Result $ SimpleExpr $ Ann a' $ Cond $ BinCond vl (gToVCondOp o') vr ):es else if isLogicalOp o' then do circOp <- case o' of G.LogicalAnd -> pure And G.LogicalOr -> pure Or _ -> throwError $ InvariantViolation "Unknown logical \ \operator" t <- makeTemp V.boolType pure [ShortCircuit t circOp ((Result $ SimpleVal vl):esl) ((Result $ SimpleVal vr):esr)] else pure $ ( Result $ SimpleExpr $ Ann a' $ Binary vl (gToVBinOp o') vr ):es G.UnaryOp o e -> do (v, e') <- exprAsVal =<< e a' <- reinterpretTypeEx $ fst a pure $ (case bare o of G.LogicalNot -> Result $ SimpleExpr $ Ann a' $ Cond $ UnCond V.LogicalNot v _ -> Result $ SimpleExpr $ Ann a' $ Unary (gToVUnOp $ bare o) v):e' G.Conversion ty e -> do aRes <- reinterpretTypeEx $ fst a e' <- e let ty' = gToVType ty case head e' of -- In the case of a ref, promote it directly to a conversion. (Result (SimpleRef r)) -> pure $ (Result $ SimpleExpr $ Ann aRes $ V.Conversion ty' r):(tail e') -- In the case of a value, make it into a ref and convert that. (Result (SimpleVal v)) -> -- <-- pure $ (Result $ SimpleExpr $ Ann aRes $ V.Conversion ty' $ Ann (typeFromVal v) $ ValRef v) :(tail e') -- Otherwise, create a temporary and convert the temporary. (Result e''@(SimpleExpr (Ann aIn _))) -> do t <- makeTemp aIn pure $ (Result $ SimpleExpr $ Ann aRes $ V.Conversion ty' $ Ann aIn $ ValRef $ IdentVal t) :(Temp (t, e'')) :(tail e') _ -> throwError $ InvariantViolation "Conversion: unexpected non-result" G.Selector e id' -> do a' <- reinterpretTypeEx $ fst a e' <- e case e' of ((Result e''):es) -> do id'' <- case typeFromSimple e'' of Fix (V.StructType fs _) -> getFieldIEx (G.unIdent $ bare id') fs _ -> throwError $ InvariantViolation "Selector with non-struct selectee" case e'' of -- If we already have a select ref (e.g. stru.foo.bar), -- we just extend it with the new identifier SimpleRef (Ann _ (SelectRef i is)) -> pure $ (Result $ SimpleRef $ Ann a' $ SelectRef i (is ++ [id''])):es -- An ident val: replace by a select ref SimpleVal (IdentVal i) -> pure $ (Result $ SimpleRef $ Ann a' $ SelectRef i [id'']):es -- Anything else: create a temp, select into it. _ -> do t <- makeTemp (typeFromSimple e'') pure $ (Result $ SimpleRef $ Ann a' $ SelectRef t [id'']) :(Temp (t, e'')) :es _ -> throwError $ InvariantViolation "Selector: unexpected non-result" G.Index eIn eBy' -> do a' <- reinterpretTypeEx $ fst a eIn' <- eIn (vBy, esBy) <- exprAsVal =<< eBy' let es = esBy ++ (tail eIn') case head eIn' of -- If we have an array ref, extend it. (Result (SimpleRef (Ann _ (ArrayRef i vs)))) -> pure $ (Result $ SimpleRef $ Ann a' $ ArrayRef i (vs ++ [vBy])):es -- If we have an identifier value, replace it by an array ref. (Result (SimpleVal (IdentVal i))) -> pure $ (Result $ SimpleRef $ Ann a' $ ArrayRef i [vBy]):es -- Otherwise, create a temp and index into it. (Result eIn'') -> do t <- makeTemp (typeFromSimple eIn'') pure $ (Result $ SimpleRef $ Ann a' $ ArrayRef t [vBy]) :(Temp (t, eIn'')) :es _ -> throwError $ InvariantViolation "Index: unexpected non-result" G.Slice e l h b -> do a' <- reinterpretTypeEx $ fst a e' <- e let ml = fmap (>>= exprAsVal) l let mh = fmap (>>= exprAsVal) h let mb = fmap (>>= exprAsVal) b il <- extractI ml ih <- extractI mh ib <- extractI mb let bounds = (il, ih, ib) el <- extractEs ml eh <- extractEs mh eb <- extractEs mb let es = el ++ eh ++ eb ++ (tail e') case head e' of -- Slicing an existing slice ref: extend it (Result (SimpleRef (Ann _ (SliceRef i bs)))) -> pure $ (Result $ SimpleRef $ Ann a' $ SliceRef i (bs ++ [bounds])):es -- Slicing an identifier: replace by a slice ref. (Result (SimpleVal (IdentVal i))) -> pure $ (Result $ SimpleRef $ Ann a' $ SliceRef i [bounds]):es -- Slicing into anything else: create a temp and slice that. (Result e''@(SimpleExpr (Ann aIn _))) -> do t <- makeTemp aIn pure $ (Result $ SimpleRef $ Ann a' $ SliceRef t [bounds]) :(Temp (t, e'')) :es _ -> throwError $ InvariantViolation "Slice: unexpected non-result" G.Call e mty ps -> do a' <- reinterpretTypeEx $ fst a -- Convert top expressions of parameters to values when needed. ps' <- forM ps (\cur -> do cur' <- cur case head cur' of (Result (SimpleVal _)) -> pure $ cur' (Result e') -> do t <- makeTemp (typeFromSimple e') pure $ (Temp (t, e')):(tail cur') _ -> throwError $ InvariantViolation "Call: unexpected non-result") -- Make top values to be used as arguments to the call. let ps'' = map (\cur -> case head cur of (Result (SimpleVal v)) -> v (Temp (t, _)) -> IdentVal t _ -> error "Expected simple value or temp") ps' -- If a type argument was present, convert it to a regular argument -- which is just the storage size of the type. tyPs <- case mty of Nothing -> pure ps'' Just (Fix (Ann b _)) -> do sz <- reinterpretTypeEx (fst b) pure $ (V.Literal $ Ann (V.intType V.I8) $ V.IntLit $ storageSize sz):ps'' -- If the callee expression is an identifier, use it as is. Otherwise -- create a temporary. (i, es) <- exprAsId =<< e -- At this point ps' has either simple values or temps at the top. -- We keep the temps, and throw away the simple values since they -- made it directly into the call. For the temps, we merge all their -- prior expressions. Note that simple values can't have prior -- expressions so it's okay to throw them out. es' <- let fil = (\x -> case head x of Result _ -> False _ -> True) in pure $ concat $ filter fil ps' let inner = case gidTy i of Fix (V.BuiltinType gTy) -> V.InternalCall (case gTy of T.AppendType -> mangleFuncName "goappend_slice" T.CapType -> mangleFuncName "gocap" T.CopyType -> mangleFuncName "gocopy" T.LenType -> case unFix $ typeFromVal $ head tyPs of V.ArrayType _ _ -> mangleFuncName "golen_array" V.StringType -> mangleFuncName "golen_array" V.SliceType _ -> mangleFuncName "golen_slice" T.MakeType -> mangleFuncName "gomake") _ -> V.Call i pure $ (Result $ SimpleExpr $ Ann a' $ inner tyPs):(es ++ es') G.Literal (Ann a' l) -> do a'' <- reinterpretTypeEx (fst a') case l of G.IntLit n -> pure [Result $ SimpleVal $ V.Literal (Ann a'' (V.IntLit n))] G.FloatLit n -> pure [Result $ SimpleVal $ V.Literal (Ann a'' (V.FloatLit n))] G.RuneLit n -> pure [Result $ SimpleVal $ V.Literal (Ann a'' (V.RuneLit n))] G.StringLit n -> do g <- makeString n pure [Result $ SimpleVal $ IdentVal g] G.Variable i -> do case maybeSymbol $ bare $ gidOrigName i of Nothing -> pure [] _ -> case reinterpretGlobalId i of Left _ -> throwError $ InvariantViolation "Unrepresentable type" Right x -> do let name = stringFromSymbol (gidOrigName x) if gidTy i == untypedBoolType then if name == mangleFuncName "gocode_true" then pure [ Result . SimpleVal . V.Literal $ Ann V.boolType (V.IntLit 1) ] else if name == mangleFuncName "gocode_false" then pure [ Result . SimpleVal . V.Literal $ Ann V.boolType (V.IntLit 0) ] else throwError $ InvariantViolation $ "untyped boolean is not true or false: " ++ name else pure [Result $ SimpleVal $ IdentVal x] G.TypeAssertion _ _ -> throwError $ InvariantViolation "Type assertions are not supported." getFieldIEx :: String -> [(String, f)] -> Simplify Int getFieldIEx = getFieldIEx' 0 where getFieldIEx' :: Int -> String -> [(String, f)] -> Simplify Int getFieldIEx' _ _ [] = throwError $ InvariantViolation "Could not find struct field" getFieldIEx' n s (x:xs) = if fst x == s then pure n else getFieldIEx' (n + 1) s xs reinterpretTypeEx :: T.Type -> Simplify V.Type reinterpretTypeEx t = case reinterpretType t of Left _ -> throwError $ UnrepresentableType ("reinterpretTypeEx: " ++ show t) Right x -> pure x extractI :: Maybe (Simplify (TyAnnVal, a)) -> Simplify (Maybe TyAnnVal) extractI x = case x of Nothing -> pure Nothing Just a -> do a' <- a pure $ Just $ fst a' -- Extracts a stack from a Maybe Simplify value. When the argument is nothing, -- an empty list is returned. extractEs :: Maybe (Simplify (a, [SimpleExprResult])) -> Simplify [SimpleExprResult] extractEs x = case x of Nothing -> pure [] Just a -> do a' <- a pure $ snd a' -- Takes the topmost expression of a simple stack to a value. A temporary -- is generated if required, and the resulting stack state after is also -- returned. exprAsVal :: [SimpleExprResult] -> Simplify (TyAnnVal, [SimpleExprResult]) exprAsVal e' = do case head e' of Result (SimpleVal v) -> pure (v, tail e') Result c -> do t <- makeTemp (typeFromSimple c) pure (IdentVal t, (Temp (t, c)):(tail e')) ShortCircuit i _ _ _ -> pure (IdentVal i, e') Temp _ -> throwError $ InvariantViolation "Should not be a temporary." -- Takes the topmost expression of a simple stack to an identifier. A temporary -- is generated if required, and the resulting stack state after is also returned. exprAsId :: [SimpleExprResult] -> Simplify (V.BasicIdent, [SimpleExprResult]) exprAsId e' = do case head e' of Result (SimpleVal (IdentVal i)) -> pure (i, tail e') Result c -> do t <- makeTemp (typeFromSimple c) pure (t, (Temp (t, c)):(tail e')) ShortCircuit i _ _ _ -> pure (i, e') Temp _ -> throwError $ InvariantViolation "Should not be a temporary." -- Extreme boilerplate follows. gToVUnOp o = case o of G.Positive -> V.Positive G.Negative -> V.Negative G.BitwiseNot -> V.BitwiseNot _ -> error "unimplemented unsupported unop error" gToVCondOp o = case o of G.LogicalOr -> V.LogicalOr G.LogicalAnd -> V.LogicalAnd G.Equal -> V.Equal G.NotEqual -> V.NotEqual G.LessThan -> V.LessThan G.LessThanEqual -> V.LessThanEqual G.GreaterThan -> V.GreaterThan G.GreaterThanEqual -> V.GreaterThanEqual _ -> error "unimplemented unsupported condop error" gToVBinOp :: G.BinaryOp a -> V.BinaryOp a gToVBinOp o = case o of G.Plus -> V.Plus G.Minus -> V.Minus G.Times -> V.Times G.Divide -> V.Divide G.Modulo -> V.Modulo G.ShiftLeft -> V.ShiftLeft G.ShiftRight -> V.ShiftRight G.BitwiseAnd -> V.BitwiseAnd G.BitwiseAndNot -> V.BitwiseAndNot G.BitwiseOr -> V.BitwiseOr G.BitwiseXor -> V.BitwiseXor _ -> error "unimplemented unsupported binop error" gToVType :: TySrcAnnType -> V.BasicType gToVType (Fix (Ann a _)) = case reinterpretType $ fst a of Left e -> error $ "Unrepresentable type: " ++ e Right x -> x -- | Extracts the type of a simple constituent. typeFromSimple :: SimpleConstituent -> V.Type typeFromSimple c = case c of SimpleVal v -> typeFromVal v SimpleRef (Ann a _) -> a SimpleExpr (Ann a _) -> a -- | Extracts the type of a value typeFromVal :: TyAnnVal -> V.Type typeFromVal v = case v of IdentVal gid -> gidTy gid V.Literal (Ann ty _) -> ty
djeik/goto
libgoto/Language/Vigil/Simplify/Expr.hs
mit
18,149
28
22
7,135
4,313
2,194
2,119
310
71
module Game.Core ( Area(Area), Cells, Difference(Difference), Position, mutate, blink, difference, createCells, isAlive, inside, positionsInside, neighbors, ) where import qualified Data.Set as Set data Area = Area { lowerX :: Int, lowerY :: Int, upperX :: Int, upperY :: Int } deriving (Eq, Show) newtype Cells = Cells { aliveCells :: Set.Set Position } deriving (Eq, Show) data Difference = Difference { cellsWillLive :: Set.Set Position, cellsWillDie :: Set.Set Position } deriving (Eq, Show) type Position = (Int, Int) mutate :: Area -> Cells -> Cells mutate area cells = createCells $ filter (blink cells) (positionsInside area) blink :: Cells -> Position -> Bool blink cells position = transitions . Set.size . aliveNeighbors $ position where aliveNeighbors = Set.intersection (aliveCells cells) . Set.fromList . neighbors transitions 2 = isAlive cells position transitions 3 = True transitions _ = False difference :: Cells -> Cells -> Difference difference (Cells oldAliveCells) (Cells newAliveCells) = Difference cellsWillLive cellsWillDie where cellsWillLive = Set.difference newAliveCells oldAliveCells cellsWillDie = Set.difference oldAliveCells newAliveCells createCells :: [Position] -> Cells createCells = Cells . Set.fromList isAlive :: Cells -> Position -> Bool isAlive = flip Set.member . aliveCells inside :: Area -> Position -> Bool inside (Area lowerX lowerY upperX upperY) (x, y) = lowerX <= x && x <= upperX && lowerY <= y && y <= upperY positionsInside :: Area -> [Position] positionsInside (Area lowerX lowerY upperX upperY) = (,) <$> [lowerX..upperX] <*> [lowerY..upperY] neighbors :: Position -> [Position] neighbors position@(x, y) = filter (/= position) $ positionsInside (Area (pred x) (pred y) (succ x) (succ y))
airt/game-of-life
src/Game/Core.hs
mit
1,823
0
11
338
643
353
290
51
3
module Braun (Braun ,empty, size ,fromList, toList ,pushFront, pushBack, popFront, popBack ,glb, insert, delete ) where data Pre a = Nil | More a (Pre a) (Pre a) deriving (Show) data Braun a = Braun Int (Pre a) deriving (Show) empty = Braun 0 Nil size (Braun n _) = n {- In valid Braun trees, the left tree either has the same size as the right tree or is larger by 1. -} {- Okasaki has a linear-time version of fromList that requires less code and no polymorphic recursion, but it is less lazy, and so can't complete queries like "fst $ popFront $ fromList [0..]". This version is also linear time, but also produces reasonable output on infinite input. -} preFromList :: [a] -> Pre a preFromList [] = Nil preFromList (x:xs) = let (od,ev) = unLink $ preFromList $ pairUp xs in More x od ev pairUp :: [a] -> [(a, Maybe a)] pairUp [] = [] pairUp [x] = [(x,Nothing)] pairUp (x:y:ys) = (x,Just y):pairUp ys unLink :: Pre (a,Maybe b) -> (Pre a,Pre b) unLink Nil = (Nil,Nil) unLink (More (x,Nothing) Nil Nil) = (More x Nil Nil,Nil) unLink (More (x,Just y) od ev) = let (odx,ody) = unLink od (evx,evy) = unLink ev in (More x odx evx, More y ody evy) fromList xs = Braun (length xs) (preFromList xs) preToList Nil = [] preToList (More x ys zs) = x:(go [ys,zs] [] []) where go [] [] [] = [] go [] r s = go ((reverse r) ++ (reverse s)) [] [] go (Nil:ps) l r = go ps l r go ((More p qs rs):ss) l r = p:(go ss (qs:l) (rs:r)) toList (Braun _ p) = preToList p prePushFront x Nil = More x Nil Nil prePushFront x (More y p q) = More x (prePushFront y q) p pushFront x (Braun n p) = Braun (n+1) (prePushFront x p) pushBack x (Braun 0 Nil) = Braun 1 (More x Nil Nil) pushBack x (Braun n (More y z w)) = let (m,r) = n`quotRem`2 in if r == 0 then let Braun _ w2 = pushBack x (Braun (m-1) w) in Braun (n+1) (More y z w2) else let Braun _ z2 = pushBack x (Braun m z) in Braun (n+1) (More y z2 w) prePopFront (More x Nil Nil) = (x,Nil) prePopFront (More x y z) = let (p,q) = prePopFront y in (x,More p z q) popFront (Braun n p) = let (x,p2) = prePopFront p in (x,Braun (n-1) p2) popBack (Braun 1 (More x Nil Nil)) = (x,empty) popBack (Braun n (More x y z)) = let (m,r) = n`quotRem`2 in if r == 0 then let (p,Braun _ q) = popBack (Braun (m-1) z) in (p,Braun (n-1) (More x y q)) else let (p,Braun _ q) = popBack (Braun m y) in (p,Braun (n-1) (More x q z)) nth 0 (More x _ _) = x nth i (More _ y z) = let (j,r) = (i-1)`quotRem`2 in if r == 0 then nth j y else nth j z data UpperBound a = Exact a | TooHigh Int | Finite -- If the input is infinite, find an upper bound if one exists. If the -- inpute is finite, returns an upper bound or Nothing. If Nothing, -- there may be an upper bound that just wasn't found. ub :: (a -> b -> Ordering) -> a -> Pre b -> UpperBound b ub f x t = go f x t 0 1 where go _ _ Nil _ _ = Finite go f x (More hd _ ev) n k = case f x hd of LT -> TooHigh n EQ -> Exact hd GT -> go f x ev (n+2*k) (2*k) glb :: (a -> b -> Ordering) -> a -> Braun b -> Maybe b glb f _ (Braun _ Nil) = Nothing glb f x xs@(Braun n ys@(More h _ _)) = case f x h of LT -> Nothing EQ -> Just h GT -> case ub f x ys of Exact ans -> Just ans Finite -> let final = nth (n-1) ys in case f x final of LT -> go 0 (n-1) _ -> Just final TooHigh m -> go 0 m where go i j = if j <= i then if 0 == j then Nothing else Just $ nth (j-1) ys else if i+1 == j then Just $ nth i ys else let k = (i+j)`div`2 middle = nth k ys in case f x middle of LT -> go i k EQ -> Just middle GT -> go k j insert x xs = let (lt, gte) = break (>=x) $ toList xs in case gte of [] -> pushBack x xs (y:ys) -> if x == y then xs else fromList (lt ++ [x] ++ gte) delete x xs = let (lt, gte) = break (>=x) $ toList xs in case gte of [] -> xs (y:ys) -> if x == y then fromList (lt ++ ys) else xs
jbapple/unique
Braun.hs
mit
4,616
9
19
1,735
2,159
1,122
1,037
118
11
{-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE ViewPatterns #-} module AIChallenger.Match ( launchBotsAndSimulateMatch , simulateMatch ) where import Control.Exception import Control.Monad import Data.List.NonEmpty (NonEmpty, nonEmpty) import Data.Monoid import qualified Data.Text as T import qualified Data.Vector.Extended as V import Path import System.Timeout import AIChallenger.Bot import AIChallenger.Channel import AIChallenger.Types launchBotsAndSimulateMatch :: Game game => game -> MapName -> Turn -> V.Vector Bot -> RemotePlayers -> TournamentId -> MatchId -> IO Match launchBotsAndSimulateMatch game mapName turnLimit bots remotePlayers tournamentId mid@(MatchId x) = do replayPath <- parseAbsFile ("/tmp/" <> show x <> ".replay") let work (Right players) = do GameResult winnerIds gameOver replay <- simulateMatch game mapName turnLimit players gameSaveReplay game replayPath replay let winnerPlayers = (V.filter ((`elem` winnerIds) . playerId) players) let winnerNames = fmap playerName winnerPlayers winnerBots = V.filter ((`elem` winnerNames) . botName) bots return (Match mid tournamentId bots winnerBots gameOver replayPath) work (Left (winnerBots, faults)) = do initialState <- gameInitialState game mapName let replay = gameExtractReplay game initialState gameSaveReplay game replayPath replay return (Match mid tournamentId bots winnerBots (Disqualification faults) replayPath) bracket (launchBots bots remotePlayers) (either (const (return ())) (V.mapM_ playerClose)) work simulateMatch :: Game game => game -> MapName -> Turn -> V.Vector Player -> IO (GameResult game) simulateMatch game mapName turnLimit bots = do go mempty =<< gameInitialState game mapName where go turn state | turn >= turnLimit = return (gameTimeout state) go turn state = do sendWorld game state bots faultsOrOrders <- getOrders game bots case faultsOrOrders of Left faults -> do let losers = fmap fst faults winners = V.filter (not . (`V.elem` losers)) (fmap playerId bots) return (GameResult winners (Disqualification faults) (gameExtractReplay game state)) Right orders -> case gameAdvance orders state of Left result -> return result Right newState -> go (succ turn) newState sendWorld :: Game game => game -> GameState game -> V.Vector Player -> IO () sendWorld game gameState players = do forM_ players $ \(Player { playerId = PlayerId me, playerInput = ch }) -> do _ <- sendLine ch ("Y " <> showT me) gameSendWorld game (PlayerId me) gameState (sendLine ch) sendLine ch "." getOrders :: forall game. Game game => game -> V.Vector Player -> IO (Either Faults (V.Vector (PlayerId, V.Vector (GameOrder game)))) getOrders game bots = do unparsedOrdersAndFaults <- forM bots $ \(Player {playerId = me, playerOutput = ch}) -> do let oneSecond = 1000000 maybeFaultOrTexts <- timeout oneSecond (chReadLinesUntilDot ch) case maybeFaultOrTexts of Nothing -> return (me, Left (pure (Fault "Time limit exceeded"))) Just (Left fault) -> return (me, Left (pure fault)) Just (Right texts) -> return (me, Right texts) let ioFaults :: V.Vector (PlayerId, NonEmpty Fault) ioFaults = V.mapMaybe (\case (botIdent, Left f) -> Just (botIdent, f) _ -> Nothing) unparsedOrdersAndFaults orders :: V.Vector (PlayerId, V.Vector (T.Text, Maybe (GameOrder game))) orders = V.mapMaybe (\case (botIdent, Right ts) -> Just (botIdent, V.fromList (map (\o -> (o, gameParseOrder game o)) ts)) _ -> Nothing) unparsedOrdersAndFaults badOrders :: V.Vector (PlayerId, NonEmpty Fault) badOrders = V.mapMaybe (sequence . fmap (\os -> nonEmpty [ Fault ("Failed to parse order " <> t) | (t, Nothing) <- V.toList os ])) orders goodOrders :: V.Vector (PlayerId, V.Vector (GameOrder game)) goodOrders = fmap (fmap (V.mapMaybe snd)) orders if V.null ioFaults && V.null badOrders then return (Right goodOrders) else return (Left (ioFaults <> badOrders))
ethercrow/ai-challenger
src/AIChallenger/Match.hs
mit
4,884
11
24
1,526
1,492
746
746
104
6
{-| Module: Flaw.BinaryCache Description: Class of binary cache. License: MIT -} {-# LANGUAGE GADTs #-} module Flaw.BinaryCache ( BinaryCache(..) , SomeBinaryCache(..) , NullBinaryCache(..) , BinaryCacheHashMap(..) , newBinaryCacheHashMap ) where import qualified Data.ByteString as B import qualified Data.HashMap.Strict as HM import Data.IORef class BinaryCache c where getCachedBinary :: c -> B.ByteString -> IO (Maybe B.ByteString) putCachedBinary :: c -> B.ByteString -> B.ByteString -> IO () data SomeBinaryCache where SomeBinaryCache :: BinaryCache c => c -> SomeBinaryCache data NullBinaryCache = NullBinaryCache instance BinaryCache NullBinaryCache where getCachedBinary _ _ = return Nothing putCachedBinary _ _ _ = return () newtype BinaryCacheHashMap = BinaryCacheHashMap (IORef (HM.HashMap B.ByteString B.ByteString)) instance BinaryCache BinaryCacheHashMap where getCachedBinary (BinaryCacheHashMap hmRef) key = HM.lookup key <$> readIORef hmRef putCachedBinary (BinaryCacheHashMap hmRef) key value = modifyIORef' hmRef $ HM.insert key value newBinaryCacheHashMap :: IO BinaryCacheHashMap newBinaryCacheHashMap = BinaryCacheHashMap <$> newIORef HM.empty
quyse/flaw
flaw-base/Flaw/BinaryCache.hs
mit
1,203
0
12
176
307
166
141
25
1
module Data.Set where import Prelude hiding (filter,foldl,foldr,null,map,take,drop,splitAt) import qualified Data.List as List -- This should at the minimum allow adding and removing elements, and -- holding identical elements at most once. -- I'm not sure I can effectively use Ord without type classes. -- Could maybe implement a builtin_compare function that handles -- Int, Double, LogDouble, Char, String, List, Tuples data Set a = Set [a] empty = Set [] singleton x = Set [x] fromList xs = Set (nub xs) fromAscList xs = fromList xs fromDescList xs = fromList xs fromDistinctAscList xs = fromList xs fromDistinctDescList xs = fromList xs powerSet (Set []) = Set [[]] powerSet (Set (x:xs)) = let Set ys = powerSet xs in Set (ys++(List.map (x:) ys)) insert x s@(Set xs) | member x s = s | otherwise = Set (x:xs) delete x s@(Set xs) = Set $ List.filter (/=x) xs member x s@(Set xs) | elem x xs = True | otherwise = False notMember x s = not $ member x s -- lookupLT -- lookupGT -- lookupLE -- lookupGE null (Set []) = True null _ = False size (Set xs) = length xs isSubsetOf (Set []) s2 = True isSubsetOf (Set xs) (Set ys) = go xs ys where go [] ys = True go (x:xs) ys | x `elem` ys = go xs ys | otherwise = False isProperSubsetOf s1 s2 | isSubsetOf s1 s2 = size s1 < size s2 | otherwise = False disjoint s1 s2 = size (intersection s1 s2) == 0 union (Set xs) (Set ys) = Set (xs ++ List.filter (`notElem` xs) ys) unions = List.foldl union empty difference (Set xs) (Set ys) = Set $ List.filter (`notElem` ys) xs infixl 9 \\ s1 \\ s2 = s1 `difference` s2 intersection (Set xs) (Set ys) = Set $ List.filter (`elem` ys) xs cartesionProduct (Set xs) (Set ys) = Set [(x,y) | x <- xs, y <- ys] disjointUnion xs ys = map Left xs `union` map Right ys filter pred xs = Set $ List.filter pred xs -- takeWhileAntitone -- dropWhileAntitone -- spanAntitone -- partition -- split -- splitMember -- splitRoot -- lookupIndex -- findIndex -- lookupIndex -- findIndex -- elemAt -- deleteAt -- take n (Set xs) = -- drop -- splitAt map f (Set xs) = Set $ map f xs -- mapMonotonic -- foldr -- foldl --foldr' --foldl' --fold --lookupMin --lookupMax --findMin --findMax --deleteMin --deleteMax --deleteFindMin --deleteFindMax --maxView -- minView elems = toAscList toList (Set xs) = xs toAscList (Set xs) = List.sort xs toDescList = reverse . toAscList
bredelings/BAli-Phy
haskell/Data/Set.hs
gpl-2.0
2,566
0
12
663
945
498
447
45
2
#!/usr/bin/env runhaskell import Distribution.PackageDescription import Distribution.Simple import Distribution.Simple.LocalBuildInfo import Distribution.Simple.Program import qualified Distribution.Verbosity as Verbosity import Data.List main = defaultMainWithHooks defaultUserHooks { hookedPrograms = [pyConfigProgram], postConf=configure } pyConfigProgram = (simpleProgram "python") configure _ _ _ lbi = do mb_bi <- pyConfigBuildInfo Verbosity.normal lbi writeHookedBuildInfo "MissingPy.buildinfo" (mb_bi,[]) -- Populate BuildInfo using python tool. pyConfigBuildInfo verbosity lbi = do (pyConfigProg, _) <- requireProgram verbosity pyConfigProgram -- (orLaterVersion $ Version [2] []) (withPrograms lbi) (AnyVersion) (withPrograms lbi) let python = rawSystemProgramStdout verbosity pyConfigProg libDir <- python ["-c", "from distutils.sysconfig import *; print get_python_lib()"] incDir <- python ["-c", "from distutils.sysconfig import *; print get_python_inc()"] confLibDir <- python ["-c", "from distutils.sysconfig import *; print get_config_var('LIBDIR')"] libName <- python ["-c", "import sys; print \"python%d.%d\" % (sys.version_info[0], sys.version_info[1])"] return $ Just emptyBuildInfo { extraLibDirs = lines confLibDir ++ lines libDir, includeDirs = lines incDir ++ ["glue"], extraLibs = lines libName }
jgoerzen/missingpy
Setup.hs
gpl-2.0
1,459
3
12
281
295
152
143
25
1
{-# LANGUAGE DeriveDataTypeable #-} module DataStructures.Sequences where import qualified Data.List as L import qualified Data.Set as S import qualified DataStructures.Sets as Sets import Control.Exception import Data.Typeable type Seq a = [a] data SeqsException = IndexOutOfRange Int deriving (Show, Typeable) instance Exception SeqsException -- Sequence's length length::Seq a -> Int length = L.length -- Ask for the element in a position get::Seq a -> Int -> a get s i = if i>=(DataStructures.Sequences.length s) then throw (IndexOutOfRange i) else s L.!! i -- Set an element in a position set::Seq a -> Int -> a -> Seq a set s i v = if i>(DataStructures.Sequences.length s) then throw (IndexOutOfRange i) else (L.take i s) L.++ [v] L.++ (L.drop i s) -- Sequences equality (==)::Eq a => Seq a -> Seq a -> Bool (==) s1 s2 = (s1 Prelude.== s2) -- Add an element in the sequence's head cons::a -> Seq a -> Seq a cons v s = v:s -- Add an element in the end snoc::a -> Seq a -> Seq a snoc v s = s L.++ [v] -- Subsequence between the given positions subsec::Seq a -> Int -> Int -> Seq a subsec s i j = if i>=(DataStructures.Sequences.length s) then throw (IndexOutOfRange i) else if j>(DataStructures.Sequences.length s) then throw (IndexOutOfRange j) else L.take (j-i) (L.drop i s) -- Subsequence starting in the given position subsec_ini::Seq a -> Int -> Seq a subsec_ini s i = if i>=(DataStructures.Sequences.length s) then throw (IndexOutOfRange i) else L.drop i s -- Subsequence finishing in the given position subsec_fin::Seq a -> Int -> Seq a subsec_fin s i = if i>=(DataStructures.Sequences.length s) then throw (IndexOutOfRange i) else L.take (i-1) s -- Concatenation (++)::Seq a -> Seq a -> Seq a (++) s1 s2 = s1 L.++ s2 -- Create a sequence from a function create::Int -> (Int -> a) -> Seq a create n f = L.map f (L.take n [0,1..]) -- Membership in the sequence mem::Eq a => a -> Seq a -> Bool mem = L.elem -- True if all the elements are different distinct::Ord a => Seq a -> Bool distinct = distinct_aux.(L.sort) where distinct_aux [] = True distinct_aux [x] = True distinct_aux (x1:x2:xs) = x1<x2 && distinct_aux (x2:xs) -- Reversed sequence reverse::Seq a -> Seq a reverse = L.reverse -- Set of the sequence's elements to_set::Ord a => Seq a -> Sets.Set a to_set = L.foldr Sets.add S.empty -- True if the subsequence is sorted (in ascending order) sorted_sub::Ord a => Seq a -> Int -> Int -> Bool sorted_sub s l u = if l>=(DataStructures.Sequences.length s) then throw (IndexOutOfRange l) else if u>(DataStructures.Sequences.length s) then throw (IndexOutOfRange u) else sorted (L.take (u-l) (L.drop l s)) -- True if the sequence is sorted (in ascending order) sorted::Ord a => Seq a -> Bool sorted [] = True sorted [x] = True sorted (x1:x2:xs) = x1<=x2 && sorted (x2:xs) -- Number of occurrences of an element in the subsequence occ::Eq a => a -> Seq a -> Int -> Int -> Int occ x s l u = if l>=(DataStructures.Sequences.length s) then throw (IndexOutOfRange l) else if u>(DataStructures.Sequences.length s) then throw (IndexOutOfRange u) else L.foldr f 0 (L.take (u-l) (L.drop l s)) where f y acc = if x Prelude.==y then (1+acc) else acc -- Subsequences equality seq_eq_sub::Eq a => Seq a -> Seq a -> Int -> Int -> Bool seq_eq_sub s1 s2 l u = if l>=(DataStructures.Sequences.length s1) || l>=(DataStructures.Sequences.length s2) then throw (IndexOutOfRange l) else if u>(DataStructures.Sequences.length s1) || u>(DataStructures.Sequences.length s2) then throw (IndexOutOfRange u) else DataStructures.Sequences.length s1 Prelude.==DataStructures.Sequences.length s2 && (L.take (u-l) (L.drop l s1)) Prelude.== (L.take (u-l) (L.drop l s2)) -- Equality of sequences except for two positions that have the elements exchanged exchange::Eq a => Seq a -> Seq a -> Int -> Int -> Bool exchange s1 s2 i j = if i>=(DataStructures.Sequences.length s1) || i>=(DataStructures.Sequences.length s2) then throw (IndexOutOfRange i) else if j>=(DataStructures.Sequences.length s1) || j>=(DataStructures.Sequences.length s2) then throw (IndexOutOfRange j) else exchange_aux s1 s2 i j 0 (get s1 i) (get s2 i) where exchange_aux [] [] _ _ _ _ _ = True exchange_aux [] _ _ _ _ _ _ = False exchange_aux _ [] _ _ _ _ _ = False exchange_aux (s1:ss1) (s2:ss2) i j pos x1 x2 |pos Prelude.==i = exchange_aux ss1 ss2 i j (pos+1) x1 x2 |pos Prelude.==j = (s1 Prelude.==x2) && (s2 Prelude.==x1) && exchange_aux ss1 ss2 i j (pos+1) x1 x2 |otherwise = (s1 Prelude.==s2) && exchange_aux ss1 ss2 i j (pos+1) x1 x2 -- Permutation of subsequences permut::Ord a => Seq a -> Seq a -> Int -> Int -> Bool permut s1 s2 l u = if l>=(DataStructures.Sequences.length s1) || l>=(DataStructures.Sequences.length s2) then throw (IndexOutOfRange l) else if u>(DataStructures.Sequences.length s1) || u>(DataStructures.Sequences.length s2) then throw (IndexOutOfRange u) else (L.length s1 Prelude.== L.length s2) && (L.sort (L.take (u-l) (L.drop l s1))) Prelude.== (L.sort (L.take (u-l) (L.drop l s2))) -- Permutation of subsequences and equality of the rest of the sequences permut_sub::Ord a => Seq a -> Seq a -> Int -> Int -> Bool permut_sub s1 s2 l u = if l>=(DataStructures.Sequences.length s1) || l>=(DataStructures.Sequences.length s2) then throw (IndexOutOfRange l) else if u>(DataStructures.Sequences.length s1) || u>(DataStructures.Sequences.length s2) then throw (IndexOutOfRange u) else (L.take l s1 Prelude.== L.take l s2) && (L.drop (u-l) s1 Prelude.== L.drop (u-l) s2) && (L.sort (L.take (u-l) (drop l s1))) Prelude.== (L.sort (L.take (u-l) (drop l s2))) -- Permutation of sequences permut_all::Ord a => Seq a -> Seq a -> Bool permut_all s1 s2 = permut s1 s2 0 (L.length s1)
ricardopenyamari/ir2haskell
clir-parser-haskell-master/src/DataStructures/Sequences.hs
gpl-2.0
5,983
1
15
1,258
2,541
1,315
1,226
81
6
module Language.PiCalc.Syntax.Term( NameId , PiName(..) , PiTerm , PiPrefTerm , PiProg , PiDefs , PiDef , noName , maxNameId , nestRestr , nestPrl , numSeq , module AST ) where -- TODO: polish exports, redefining AST function so they are restricted to PiTerm. import qualified Language.PiCalc.Syntax.AST as AST hiding (PiAST) import Language.PiCalc.Syntax.AST import qualified Data.Set as Set import qualified Data.MultiSet as MSet type NameId = Int {-| Data structure to represent alpha renamed names. -} data PiName = PiName { -- TODO: change ctxt :: (Int, Int) = position in the source of restriction -- and maybe rename to creationPt ? -- shall unique be Either String NameId replacing isGlobal? ctxt::String -- ^ a string representing the definition in which the name is used , static::String -- ^ a string holding the original name used in the code , unique::NameId -- ^ a number uniquely identifying the name in the term , isGlobal::Bool -- ^ whether the name is global or not (public top-level) } deriving (Show, Read) -- The order is (glob, static) then (nonGlob, unique) instance Ord PiName where n <= n' = case (isGlobal n, isGlobal n') of (True , True ) -> static n <= static n' (False, False) -> unique n <= unique n' (False, True ) -> False (True , False) -> True instance Eq PiName where n == n' = case (isGlobal n, isGlobal n') of (True , True ) -> static n == static n' (False, False) -> unique n == unique n' _ -> False noName = PiName {ctxt = "", static = "", unique = error "Name not ensured to be unique!", isGlobal = False} maxNameId :: PiTerm -> NameId maxNameId p | Set.null names = 0 | otherwise = unique $ Set.findMax names where names = allNames p -- | A term in conflict-free form: names are represented with @PiName@ records and -- process variables by strings. It is assumed to be a normalised AST. type PiTerm = PiAST PiName type PiPrefTerm = (PiPrefix PiName, PiTerm) type PiProg = PiProgAST PiName type PiDefs = PiDefsAST PiName type PiDef = PiDefAST PiName nestRestr :: PiTerm -> Int nestRestr (Parall ps) = maximum $ 0:[nestRestr p | p <- MSet.distinctElems ps] nestRestr (New ns p) = (Set.size ns) + (nestRestr p) nestRestr _ = 0 -- | This only really makes sense on fragments nestPrl :: PiTerm -> Int nestPrl (Parall ps) = maximum $ 0:[nestPrl p | p <- MSet.distinctElems ps] nestPrl (New ns (Parall ps)) = maximum $ (MSet.size ps):[nestPrl p | p <- MSet.distinctElems ps] nestPrl _ = 1 numSeq :: PiTerm -> Int numSeq p | isZero p = 0 numSeq (Parall ps) = sum [numSeq p | p <- MSet.distinctElems ps] numSeq (New ns p) = numSeq p numSeq _ = 1
bordaigorl/jamesbound
src/Language/PiCalc/Syntax/Term.hs
gpl-2.0
2,826
0
10
713
781
426
355
62
1
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-} {- | Module : $Header$ Copyright : (c) Felix Gabriel Mance License : GPLv2 or higher, see LICENSE.txt Maintainer : f.mance@jacobs-university.de Stability : provisional Portability : portable Renames prefixes in OntologyDocuments, so that there are no prefix clashes -} module OWL2.Rename where import OWL2.AS import OWL2.MS import OWL2.Sign import OWL2.Function import Data.Maybe import Data.Char (isDigit) import Data.List (find, nub) import qualified Data.Map as Map import Common.Result testAndInteg :: (String, String) -> (PrefixMap, StringMap) -> (PrefixMap, StringMap) testAndInteg (pre, oiri) (old, tm) = case Map.lookup pre old of Just iri -> if oiri == iri then (old, tm) else let pre' = disambiguateName pre old in (Map.insert pre' oiri old, Map.insert pre pre' tm) Nothing -> (Map.insert pre oiri old, tm) disambiguateName :: String -> PrefixMap -> String disambiguateName nm nameMap = let newname = reverse . dropWhile isDigit $ reverse nm in fromJust $ find (not . flip Map.member nameMap) [newname ++ show (i :: Int) | i <- [1 ..]] uniteSign :: Sign -> Sign -> Result Sign uniteSign s1 s2 = do let (pm, tm) = integPref (prefixMap s1) (prefixMap s2) if Map.null tm then return (addSign s1 s2) {prefixMap = pm} else fail "Static analysis could not unite signatures" integPref :: PrefixMap -> PrefixMap -> (PrefixMap, StringMap) integPref oldMap testMap = foldr testAndInteg (oldMap, Map.empty) (Map.toList testMap) newOid :: OntologyIRI -> OntologyIRI -> OntologyIRI newOid id1 id2 = let lid1 = localPart id1 lid2 = localPart id2 in if null lid1 then id2 else if null lid2 || id1 == id2 then id1 else id1 { localPart = uriToName lid1 ++ "_" ++ uriToName lid2 } combineDoc :: OntologyDocument -> OntologyDocument -> OntologyDocument combineDoc od1@( OntologyDocument ns1 ( Ontology oid1 imp1 anno1 frames1)) od2@( OntologyDocument ns2 ( Ontology oid2 imp2 anno2 frames2)) = if od1 == od2 then od1 else let (newPref, tm) = integPref ns1 ns2 in OntologyDocument newPref (Ontology (newOid oid1 oid2) (nub $ imp1 ++ map (function Rename $ StringMap tm) imp2) (nub $ anno1 ++ map (function Rename $ StringMap tm) anno2) (nub $ frames1 ++ map (function Rename $ StringMap tm) frames2)) uriToName :: String -> String uriToName str = let str' = case str of '"' : _ -> read str _ -> str in takeWhile (/= '.') $ reverse $ case takeWhile (/= '/') $ reverse str' of '#' : r -> r r -> r unifyWith1 :: OntologyDocument -> [OntologyDocument] -> [OntologyDocument] unifyWith1 d odl = case odl of [] -> [] [doc] -> [snd $ unifyTwo d doc] doc1 : docs -> let (merged, newDoc1) = unifyTwo d doc1 in newDoc1 : unifyWith1 merged docs {- | takes 2 docs and returns as snd the corrected first one and as fst the merge of the two -} unifyTwo :: OntologyDocument -> OntologyDocument -> (OntologyDocument, OntologyDocument) unifyTwo od1 od2 = let (_, tm) = integPref (prefixDeclaration od1) (prefixDeclaration od2) newod2 = function Rename (StringMap tm) od2 alld = combineDoc od1 od2 in (alld, newod2) unifyDocs :: [OntologyDocument] -> [OntologyDocument] unifyDocs = unifyWith1 emptyOntologyDoc
nevrenato/Hets_Fork
OWL2/Rename.hs
gpl-2.0
3,510
0
16
881
1,110
578
532
77
3
module Main where --import System.FilePath.Glob (glob) import Test.DocTest (doctest) main = do doctest ["src/Config.hs", "src/Pipeline.hs"] --main = glob "src/**/*.hs" >>= doctest
averagehat/Pathogen.hs
test/DocTest.hs
gpl-2.0
184
0
8
25
33
20
13
4
1
{-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FunctionalDependencies #-} module BN.EdgeSet where import BN.Common import qualified Data.Map as M import qualified Data.Set as S import qualified Data.List as L import Data.Function(on) import Test.QuickCheck hiding ((><)) -------------------------------------------------------------------------------- -- ** Edge operations class (Ord e, Ord i) => IsEdge e i | e -> i where edgeLimits :: e -> (i, i) edgeLimits = split edgeSrc edgeDst edgeSrc :: e -> i edgeSrc = fst . edgeLimits edgeDst :: e -> i edgeDst = snd . edgeLimits edgeTouches :: i -> e -> Bool edgeTouches v = uncurry (||) . ((== v) >< (== v)) . edgeLimits -- |Trivial instance instance (Ord i) => IsEdge (i, i) i where edgeLimits = id -------------------------------------------------------------------------------- -- ** The Edge Set data EdgeSet e i = ES { edgesIn :: M.Map i (S.Set e) , edgesOut :: M.Map i (S.Set e) } deriving (Show, Eq) -- |Arbitrary instance, for quickcheck instance (IsEdge e i, Arbitrary i, Arbitrary e, Enum i) => Arbitrary (EdgeSet e i) where arbitrary = do i <- choose (100, 250) :: Gen Int foldM (\r _ -> arbitrary >>= return . (++> r)) esEmpty [0..i] -- |Returns the empty edge set. esEmpty :: (IsEdge e i) => EdgeSet e i esEmpty = ES M.empty M.empty -------------------------------------------------------------------------------- -- ** Operations -- *** Adding and removing data -- |Given a edge e, inserts it into the given edge set. esAddEdge :: (IsEdge e i) => e -> EdgeSet e i -> EdgeSet e i esAddEdge e (ES min mout) = let (vsrc, vdst) = edgeLimits e in ES (add min vdst e) (add mout vsrc e) where add m v e = M.alter (Just . maybe (S.singleton e) (S.insert e)) v m -- |Removes an edge from the edge set. esRmvEdge :: (IsEdge e i) => e -> EdgeSet e i -> EdgeSet e i esRmvEdge e (ES min mout) = let (vsrc, vdst) = edgeLimits e in ES (rm min vdst e) (rm mout vsrc e) where rm m v e = M.alter (const Nothing) v m -- |Adds a node to the current edge set esAddNode :: (IsEdge e i) => i -> EdgeSet e i -> EdgeSet e i esAddNode v (ES mi mo) = ES (M.insert v S.empty mi) (M.insert v S.empty mo) -- |Removes a given node and all it's outgoing and incomming edges. esRmvNode :: (IsEdge e i) => i -> EdgeSet e i -> EdgeSet e i esRmvNode v es@(ES min mout) = let eins = map edgeSrc . S.toList $ esGetIns v es eous = map edgeDst . S.toList $ esGetOuts v es targets = eins ++ eous in ES (rm min v targets) (rm mout v targets) where rm :: (IsEdge e i) => M.Map i (S.Set e) -> i -> [i] -> M.Map i (S.Set e) rm m v eset = M.delete v $ foldr (rm1 v) m eset rm1 :: (IsEdge e i) => i -> i -> M.Map i (S.Set e) -> M.Map i (S.Set e) rm1 vi v = M.alter (maybe Nothing (Just . S.filter (not . edgeTouches vi))) v infixr 9 ++> (++>) :: (IsEdge e i) => e -> EdgeSet e i -> EdgeSet e i e ++> es = esAddEdge e es --- *** Getters -- |Returns the node indexes registered in the given edge set. esNodes :: (IsEdge e i) => EdgeSet e i -> [i] esNodes (ES mi mo) = M.keys mi `L.union` M.keys mo -- |Returns the number of nodes in a graph esSize :: (IsEdge e i) => EdgeSet e i -> Int esSize = length . esNodes -- |Get's the incomming arcs of a node esGetIns :: (IsEdge e i) => i -> EdgeSet e i -> S.Set e esGetIns v = maybe S.empty id . M.lookup v . edgesIn -- |Return the indegree of a node. esGetInDeg :: (IsEdge e i) => i -> EdgeSet e i -> Int esGetInDeg v = S.size . esGetIns v -- |We can also retrieve a given node parents esNodeRho :: (IsEdge e i) => i -> EdgeSet e i -> S.Set i esNodeRho v = S.map edgeSrc . esGetIns v -- |Transitive closure of 'esNodeRho' esNodeRhoStar :: (IsEdge e i) => i -> EdgeSet e i -> S.Set i esNodeRhoStar v es = star (flip esNodeRho es) v -- |Get's the outgoing arcs of a node esGetOuts :: (IsEdge e i) => i -> EdgeSet e i -> S.Set e esGetOuts v = maybe S.empty id . M.lookup v . edgesOut -- |Return the outdegree of a node. esGetOutDeg :: (IsEdge e i) => i -> EdgeSet e i -> Int esGetOutDeg v = S.size . esGetOuts v -- |Or, similarly, a node children esNodeSigma :: (IsEdge e i) => i -> EdgeSet e i -> S.Set i esNodeSigma v = S.map edgeDst . esGetOuts v -- |Transitive closure of 'esNodeRho' esNodeSigmaStar :: (IsEdge e i) => i -> EdgeSet e i -> S.Set i esNodeSigmaStar v es = star (flip esNodeSigma es) v -- |Returns the degree of a node. esGetDegree :: (IsEdge e i) => i -> EdgeSet e i -> Int esGetDegree v = uncurry (+) . split (esGetInDeg v) (esGetOutDeg v) -------------------------------------------------------------------------------- -- * General Uility -- |Transitive closure of f star :: (Ord a) => (a -> S.Set a) -> a -> S.Set a star f i = staraux (S.singleton i) S.empty (f i) where staraux done aux vs = let ts = vs S.\\ done r' = S.foldr (\h -> S.union (f h)) vs ts in if S.null ts then aux else staraux (S.union done ts) (S.union r' aux) r' -------------------------------------------------------------------------------- -- * Loop Cutset calculation {- Let G be a graph, we'll compute one loop cutset Cs using the following heuristic: Proc Loop-cutset(G, Cs): while there are nodes in G do: if vi \in G && degree(vi) \leq 1 then select vi else get all nodes with indegree <= 1 (let these be the candidates) select a vi from the candidates with the minimal degree. add vi to Cs Delete vi -} -- |Returns the loop cutset of a graph esGetCutset :: (IsEdge e i) => EdgeSet e i -> [i] esGetCutset es = cutset es [] where cutset es c | esSize es == 0 = c | otherwise = let ns = esNodes es (dels, ns') = L.partition ((<= 1) . flip esGetDegree es) ns in case dels of -- no dangling nodes, let's choose a node with minimal degree. [] -> let (cs, _) = L.partition ((<= 1) . flip esGetInDeg es) ns t = head $ reverse $ L.sortBy (compare `on` (flip esGetDegree es)) cs in cutset (esRmvNode t es) (t:c) -- dangling nodes! Just remove them and iterate. _ -> cutset (foldr esRmvNode es dels) c -- |Symbol ring graph lcs_t1 :: EdgeSet (Int, Int) Int lcs_t1 = (1, 2) ++> (1, 3) ++> (2, 4) ++> (3, 4) ++> esEmpty -- |Slide 204 lcs_t2 :: EdgeSet (Int, Int) Int lcs_t2 = (1, 3) ++> (3, 2) ++> (3, 4) ++> (5, 4) ++> (5, 6) ++> (4, 7) ++> (6, 7) ++> (7, 8) ++> (7, 10) ++> (7, 9) ++> (8, 10) ++> (9, 10) ++> (9, 11) ++> esEmpty -- |Pretzel lcs_t3 :: EdgeSet (Int, Int) Int lcs_t3 = (5, 2) ++> (5, 6) ++> (2, 7) ++> (6, 7) ++> lcs_t1 -- |Loopless big graph lcs_t4 :: EdgeSet (Int, Int) Int lcs_t4 = foldr (++>) esEmpty [ (i-1, i) | i <- [2..50] ] -------------------------------------------------------------------------------- -- * QuickCheck Properties -- |Given a function over a node and a edge set, verify the invariant in the -- given edge set. propNodeInv :: (IsEdge e i) => (i -> Bool) -> EdgeSet e i -> Bool propNodeInv inv es = all inv $ esNodes es -- |All predicate, extended to Sets sall :: (a -> Bool) -> S.Set a -> Bool sall f = all f . S.toList -- |Every Node is a parent of it's childs. propSigmaCorrect :: EdgeSet (Int, Int) Int -> Bool propSigmaCorrect es = propNodeInv (\n -> sall (\m -> (n `S.member` esNodeRho m es)) $ esNodeSigma n es) es -- |Every Node is a child of it's parents. propRhoCorrect :: EdgeSet (Int, Int) Int -> Bool propRhoCorrect es = propNodeInv (\n -> sall (\m -> (n `S.member` esNodeSigma m es)) $ esNodeRho n es) es
VictorCMiraldo/hs-bn
BN/EdgeSet.hs
gpl-2.0
7,932
0
22
2,061
2,860
1,509
1,351
145
2
module TestReplace ( testReplace ) where import Data.List import Language.Python.Common.AST import Language.Python.Common.Pretty (prettyText) import Language.Python.Version2.Parser import Prelude hiding (fail) import Test.HUnit.Base import Quenelle.Match import Quenelle.Normalize import Quenelle.Replace import Quenelle.Rule testReplace :: Test testReplace = TestLabel "doReplacement" $ TestList [ testLiterals, testBindings, testDot, testParen, testBinaryOp, testUnaryOp, testCall, testSubscript, testTuple, testListComp ] fail = TestCase . assertFailure testDoReplacement sexpr srule sreplacement sexpected = case parseExpr sexpr "" of Left _ -> fail $ "Failed to parse sexpr: " ++ sexpr Right (expr, _) -> case parseExprRule srule of Left _ -> fail $ "Failed to parse srule: " ++ srule Right rule -> case parseExpr sexpected "" of Left _ -> fail $ "Failed to parse sexpected: " ++ sexpected Right (expected, _) -> case parseExprReplacement sreplacement of Left _ -> fail $ "Failed to parse sreplacement: " ++ sreplacement Right replacement -> case matchExprRule rule (normalizeExpr expr) of [] -> fail $ "Failed matchExprRule for: " ++ matchMsg [match] -> TestCase $ assertEqual assertString (normalizeExpr expected) (doReplacement replacement match) matches -> fail $ "Found " ++ show (length matches) ++ " matches for: " ++ matchMsg where matchMsg = srule ++ " -> " ++ sexpr assertString = intercalate " -> " [sexpr, srule, sreplacement, sexpected] t = testDoReplacement testList name tests = TestLabel name $ TestList tests testLiterals = testList "literals" [ t "0" "0" "1" "1" ] testBindings = testList "bindings" [ t "0" "E1" "E1" "0" , t "0" "E1" "E2" "E2" -- If a variable isn't bound, leave it alone , t "x" "V1" "V1 + V1" "x + x" , t "x + y" "V1 + V2" "V2 + V1" "y + x" ] testDot = testList "Dot" [ t "x.y" "V1.V2" "V2.V1" "y.x" , t "x.y.z" "V1.V2.V3" "V3.V2.V1" "z.y.x" , t "x.y" "V1.E1" "V1.E1" "x.y" -- TODO: this seems to fail because exprToPred isn't doing the right -- thing for BoundExpressions on Dot expressions --, t "x.y" "V1.E1" "E1.V1" "y.x" ] testParen = testList "Paren" [ t "(0)" "0" "1" "(1)" , t "((0))" "0" "1" "((1))" , t "((x))" "(V1)" "V1" "(x)" ] testBinaryOp = testList "BinaryOp" [ t "(1 + 1)" "1 + 1" "2" "(2)" , t "(1 + 0)" "(E1 + 0)" "E1" "1" , t "(1 + 2)" "(E1 + E2)" "(E2 + E1)" "(2 + 1)" , t "(1 + 2)" "E1 + E2" "E2 + E1" "(2 + 1)" , t "(1 + (2))" "E1 + (E2)" "E1 + E2" "(1 + 2)" , t "(x + (y))" "(V1 + (V2))" "V1 + V2" "x + y" ] testUnaryOp = testList "UnaryOp" [ t "+0" "+E1" "E1" "0" , t "+0" "+E1" "-E1" "-0" , t "+x" "+V1" "V1" "x" , t "+x" "+V1" "-V1" "-x" ] testCall = testList "Call" [ t "f()" "E1()" "E1()" "f()" , t "f()" "E1()" "E1" "f" , t "f()" "V1()" "V1()" "f()" , t "f()" "V1()" "V1" "f" , t "f + g()" "E1 + E2()" "E2 + E1()" "g + f()" , t "f + g()" "E1 + E2()" "E1() + E2" "f() + g" , t "f + g()" "V1 + V2()" "V2 + V1()" "g + f()" , t "f + g()" "V1 + V2()" "V1() + V2" "f() + g" , t "f(g)" "E1(E2)" "E2(E1)" "g(f)" , t "f(x, y)" "f(E1, E2)" "f(E2, E1)" "f(y, x)" , t "f(x + y)" "f(E1 + E2)" "f(E1, E2)" "f(x, y)" , t "f(x, f(y + 0))" "E1 + 0" "E1" "f(x, f(y))" , t "f(g)" "V1(V2)" "V2(V1)" "g(f)" , t "f(x, y)" "f(V1, V2)" "f(V2, V1)" "f(y, x)" , t "f(x + y)" "f(V1 + V2)" "f(V1, V2)" "f(x, y)" , t "f(x, f(y + 0))" "V1 + 0" "V1" "f(x, f(y))" , t "f(*x)" "E1(*E2)" "E1(E2)" "f(x)" , t "f(*(x,))" "E1(*(E2,))" "E1(E2)" "f(x)" , t "f(*(x, y))" "E1(*(E2, E3))" "E1(E2, E3)" "f(x, y)" , t "f(*x)" "V1(*V2)" "V1(V2)" "f(x)" , t "f(*(x,))" "V1(*(V2,))" "V1(V2)" "f(x)" , t "f(*(x, y))" "V1(*(V2, V3))" "V1(V2, V3)" "f(x, y)" ] testSubscript = testList "Subscript" [ t "x[0]" "x[E1]" "E1" "0" , t "x[y]" "E1[E2]" "E2[E1]" "y[x]" , t "x[(y)]" "E1[(E2)]" "E2[E1]" "y[x]" , t "x[y]" "V1[V2]" "V2[V1]" "y[x]" , t "x[(y)]" "V1[(V2)]" "V2[V1]" "y[x]" ] testTuple = testList "Tuple" [ t "()" "E1" "E1" "()" , t "(x,)" "(E1,)" "(E1,)" "(x,)" , t "(x, y)" "(E1, E2)" "(E2, E1)" "(y, x)" , t "(x,)" "(V1,)" "(V1,)" "(x,)" , t "(x, y)" "(V1, V2)" "(V2, V1)" "(y, x)" ] testListComp = testList "ListComp" [ t "[x for x in xs]" "[E1 for E1 in E2]" "[E1 for E1 in E2]" "[x for x in xs]" , t "[f(x) for x in xs]" "[E1(E2) for E2 in E3]" "map(E1, E3)" "map(f, xs)" -- This isn't actually a valid transformation , t "[(x, y) for x in xs for y in ys]" "[E1 for E2 in E3 for E4 in E5]" "[E1 for (E2, E4) in zip(E3, E5)]" "[(x, y) for (x, y) in zip(xs, ys)]" , t "[f(x) for x in xs]" "[E1(E2) for E2 in E3]" "map(E1, E3)" "map(f, xs)" , t "[x for x in xs if f(x)]" "[E1 for E1 in E2 if E3(E1)]" "filter(E3, E2)" "filter(f, xs)" , t "[x for x in xs if x]" "[E1 for E1 in E2 if E1]" "filter(None, E2)" "filter(None, xs)" , t "[f(x) for x in xs]" "[V1(V2) for V2 in V3]" "map(V1, V3)" "map(f, xs)" , t "[x for x in xs if f(x)]" "[V1 for V1 in V2 if V3(V1)]" "filter(V3, V2)" "filter(f, xs)" , t "[x for x in xs if x]" "[V1 for V1 in V2 if V1]" "filter(None, V2)" "filter(None, xs)" ]
philipturnbull/quenelle
test/TestReplace.hs
gpl-2.0
5,709
0
25
1,737
1,303
668
635
118
7
module Data.FileQ ( f ) where import Language.Haskell.TH (stringE) import Language.Haskell.TH.Quote (QuasiQuoter (QuasiQuoter), quoteDec, quoteExp, quoteFile, quotePat, quoteType) f :: QuasiQuoter f = quoteFile QuasiQuoter { quoteDec = undefined, quoteExp = stringE, quotePat = undefined, quoteType = undefined }
khalilfazal/IANA
src/Data/FileQ.hs
gpl-2.0
344
0
7
70
92
59
33
10
1
-- Copyright (C) 2001, 2004 Ian Lynagh <igloo@earth.li> -- -- 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, 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; see the file COPYING. If not, write to -- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, -- Boston, MA 02110-1301, USA. -- name shadowing disabled because a,b,c,d,e are shadowed loads in step 4 {-# OPTIONS_GHC -fno-warn-name-shadowing #-} {-# LANGUAGE CPP #-} -- | -- Module : Darcs.Util.Crypt.SHA1 -- Copyright : 2001, 2004 Ian Lynagh <igloo@earth.li> -- License : GPL -- Maintainer : darcs-devel@darcs.net -- Stability : experimental -- Portability : portable module Darcs.Util.Crypt.SHA1 ( sha1PS, SHA1(..), showAsHex ) where import Darcs.Util.ByteString (unsafeWithInternals) import qualified Data.ByteString as B (ByteString, pack, length, concat) import Data.Binary ( Binary(..) ) import Data.Char (intToDigit) import Data.Bits (xor, (.&.), (.|.), complement, rotateL, shiftL, shiftR) import Data.Word (Word8, Word32) import Foreign.Ptr (Ptr, castPtr) import Foreign.Marshal.Array (advancePtr) import Foreign.Storable (peek, poke) import System.IO.Unsafe (unsafePerformIO) data SHA1 = SHA1 !Word32 !Word32 !Word32 !Word32 !Word32 deriving (Eq,Ord) data XYZ = XYZ !Word32 !Word32 !Word32 instance Show SHA1 where show (SHA1 a b c d e) = concatMap showAsHex [a, b, c, d, e] instance Binary SHA1 where put (SHA1 a b c d e) = put a >> put b >> put c >> put d >> put e get = do a <- get ; b <- get ; c <- get ; d <- get ; e <- get ; return (SHA1 a b c d e) sha1PS:: B.ByteString -> SHA1 sha1PS s = abcde' where s1_2 = sha1Step12PadLength s abcde = sha1Step3Init abcde' = unsafePerformIO $ unsafeWithInternals s1_2 (\ptr len -> do let ptr' = castPtr ptr #ifndef BIGENDIAN fiddleEndianness ptr' len #endif sha1Step4Main abcde ptr' len) fiddleEndianness :: Ptr Word32 -> Int -> IO () fiddleEndianness p 0 = p `seq` return () fiddleEndianness p n = do x <- peek p poke p $ shiftL x 24 .|. shiftL (x .&. 0xff00) 8 .|. (shiftR x 8 .&. 0xff00) .|. shiftR x 24 fiddleEndianness (p `advancePtr` 1) (n - 4) -- sha1Step12PadLength assumes the length is at most 2^61. -- This seems reasonable as the Int used to represent it is normally 32bit, -- but obviously could go wrong with large inputs on 64bit machines. -- The B.ByteString library should probably move to Word64s if this is an -- issue, though. sha1Step12PadLength :: B.ByteString -> B.ByteString sha1Step12PadLength s = let len = B.length s num_nuls = (55 - len) `mod` 64 padding = 128:replicate num_nuls 0 len_w8s = reverse $ sizeSplit 8 (fromIntegral len*8) in B.concat [s, B.pack padding, B.pack len_w8s] sizeSplit :: Int -> Integer -> [Word8] sizeSplit 0 _ = [] sizeSplit p n = fromIntegral d:sizeSplit (p-1) n' where (n', d) = divMod n 256 sha1Step3Init :: SHA1 sha1Step3Init = SHA1 0x67452301 0xefcdab89 0x98badcfe 0x10325476 0xc3d2e1f0 sha1Step4Main :: SHA1 -> Ptr Word32 -> Int -> IO SHA1 sha1Step4Main abcde _ 0 = return $! abcde sha1Step4Main (SHA1 a0@a b0@b c0@c d0@d e0@e) s len = do (e, b) <- doit f1 0x5a827999 (x 0) a b c d e (d, a) <- doit f1 0x5a827999 (x 1) e a b c d (c, e) <- doit f1 0x5a827999 (x 2) d e a b c (b, d) <- doit f1 0x5a827999 (x 3) c d e a b (a, c) <- doit f1 0x5a827999 (x 4) b c d e a (e, b) <- doit f1 0x5a827999 (x 5) a b c d e (d, a) <- doit f1 0x5a827999 (x 6) e a b c d (c, e) <- doit f1 0x5a827999 (x 7) d e a b c (b, d) <- doit f1 0x5a827999 (x 8) c d e a b (a, c) <- doit f1 0x5a827999 (x 9) b c d e a (e, b) <- doit f1 0x5a827999 (x 10) a b c d e (d, a) <- doit f1 0x5a827999 (x 11) e a b c d (c, e) <- doit f1 0x5a827999 (x 12) d e a b c (b, d) <- doit f1 0x5a827999 (x 13) c d e a b (a, c) <- doit f1 0x5a827999 (x 14) b c d e a (e, b) <- doit f1 0x5a827999 (x 15) a b c d e (d, a) <- doit f1 0x5a827999 (m 16) e a b c d (c, e) <- doit f1 0x5a827999 (m 17) d e a b c (b, d) <- doit f1 0x5a827999 (m 18) c d e a b (a, c) <- doit f1 0x5a827999 (m 19) b c d e a (e, b) <- doit f2 0x6ed9eba1 (m 20) a b c d e (d, a) <- doit f2 0x6ed9eba1 (m 21) e a b c d (c, e) <- doit f2 0x6ed9eba1 (m 22) d e a b c (b, d) <- doit f2 0x6ed9eba1 (m 23) c d e a b (a, c) <- doit f2 0x6ed9eba1 (m 24) b c d e a (e, b) <- doit f2 0x6ed9eba1 (m 25) a b c d e (d, a) <- doit f2 0x6ed9eba1 (m 26) e a b c d (c, e) <- doit f2 0x6ed9eba1 (m 27) d e a b c (b, d) <- doit f2 0x6ed9eba1 (m 28) c d e a b (a, c) <- doit f2 0x6ed9eba1 (m 29) b c d e a (e, b) <- doit f2 0x6ed9eba1 (m 30) a b c d e (d, a) <- doit f2 0x6ed9eba1 (m 31) e a b c d (c, e) <- doit f2 0x6ed9eba1 (m 32) d e a b c (b, d) <- doit f2 0x6ed9eba1 (m 33) c d e a b (a, c) <- doit f2 0x6ed9eba1 (m 34) b c d e a (e, b) <- doit f2 0x6ed9eba1 (m 35) a b c d e (d, a) <- doit f2 0x6ed9eba1 (m 36) e a b c d (c, e) <- doit f2 0x6ed9eba1 (m 37) d e a b c (b, d) <- doit f2 0x6ed9eba1 (m 38) c d e a b (a, c) <- doit f2 0x6ed9eba1 (m 39) b c d e a (e, b) <- doit f3 0x8f1bbcdc (m 40) a b c d e (d, a) <- doit f3 0x8f1bbcdc (m 41) e a b c d (c, e) <- doit f3 0x8f1bbcdc (m 42) d e a b c (b, d) <- doit f3 0x8f1bbcdc (m 43) c d e a b (a, c) <- doit f3 0x8f1bbcdc (m 44) b c d e a (e, b) <- doit f3 0x8f1bbcdc (m 45) a b c d e (d, a) <- doit f3 0x8f1bbcdc (m 46) e a b c d (c, e) <- doit f3 0x8f1bbcdc (m 47) d e a b c (b, d) <- doit f3 0x8f1bbcdc (m 48) c d e a b (a, c) <- doit f3 0x8f1bbcdc (m 49) b c d e a (e, b) <- doit f3 0x8f1bbcdc (m 50) a b c d e (d, a) <- doit f3 0x8f1bbcdc (m 51) e a b c d (c, e) <- doit f3 0x8f1bbcdc (m 52) d e a b c (b, d) <- doit f3 0x8f1bbcdc (m 53) c d e a b (a, c) <- doit f3 0x8f1bbcdc (m 54) b c d e a (e, b) <- doit f3 0x8f1bbcdc (m 55) a b c d e (d, a) <- doit f3 0x8f1bbcdc (m 56) e a b c d (c, e) <- doit f3 0x8f1bbcdc (m 57) d e a b c (b, d) <- doit f3 0x8f1bbcdc (m 58) c d e a b (a, c) <- doit f3 0x8f1bbcdc (m 59) b c d e a (e, b) <- doit f2 0xca62c1d6 (m 60) a b c d e (d, a) <- doit f2 0xca62c1d6 (m 61) e a b c d (c, e) <- doit f2 0xca62c1d6 (m 62) d e a b c (b, d) <- doit f2 0xca62c1d6 (m 63) c d e a b (a, c) <- doit f2 0xca62c1d6 (m 64) b c d e a (e, b) <- doit f2 0xca62c1d6 (m 65) a b c d e (d, a) <- doit f2 0xca62c1d6 (m 66) e a b c d (c, e) <- doit f2 0xca62c1d6 (m 67) d e a b c (b, d) <- doit f2 0xca62c1d6 (m 68) c d e a b (a, c) <- doit f2 0xca62c1d6 (m 69) b c d e a (e, b) <- doit f2 0xca62c1d6 (m 70) a b c d e (d, a) <- doit f2 0xca62c1d6 (m 71) e a b c d (c, e) <- doit f2 0xca62c1d6 (m 72) d e a b c (b, d) <- doit f2 0xca62c1d6 (m 73) c d e a b (a, c) <- doit f2 0xca62c1d6 (m 74) b c d e a (e, b) <- doit f2 0xca62c1d6 (m 75) a b c d e (d, a) <- doit f2 0xca62c1d6 (m 76) e a b c d (c, e) <- doit f2 0xca62c1d6 (m 77) d e a b c (b, d) <- doit f2 0xca62c1d6 (m 78) c d e a b (a, c) <- doit f2 0xca62c1d6 (m 79) b c d e a let abcde' = SHA1 (a0 + a) (b0 + b) (c0 + c) (d0 + d) (e0 + e) sha1Step4Main abcde' (s `advancePtr` 16) (len - 64) where {-# INLINE f1 #-} f1 (XYZ x y z) = (x .&. y) .|. (complement x .&. z) {-# INLINE f2 #-} f2 (XYZ x y z) = x `xor` y `xor` z {-# INLINE f3 #-} f3 (XYZ x y z) = (x .&. y) .|. (x .&. z) .|. (y .&. z) {-# INLINE x #-} x n = peek (s `advancePtr` n) {-# INLINE m #-} m n = do let base = s `advancePtr` (n .&. 15) x0 <- peek base x1 <- peek (s `advancePtr` ((n - 14) .&. 15)) x2 <- peek (s `advancePtr` ((n - 8) .&. 15)) x3 <- peek (s `advancePtr` ((n - 3) .&. 15)) let res = rotateL (x0 `xor` x1 `xor` x2 `xor` x3) 1 poke base res return res {-# INLINE doit #-} doit f k i a b c d e = a `seq` c `seq` do i' <- i return (rotateL a 5 + f (XYZ b c d) + e + i' + k, rotateL b 30) showAsHex :: Word32 -> String showAsHex n = showIt 8 n "" where showIt :: Int -> Word32 -> String -> String showIt 0 _ r = r showIt i x r = case quotRem x 16 of (y, z) -> let c = intToDigit (fromIntegral z) in c `seq` showIt (i-1) y (c:r)
DavidAlphaFox/darcs
src/Darcs/Util/Crypt/SHA1.hs
gpl-2.0
9,467
0
18
3,141
4,475
2,296
2,179
183
2
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE OverloadedStrings #-} module Text.Lit.C3js (chart) where import qualified Text.Pandoc.Builder as P import qualified Data.Aeson as A import Data.Aeson (toJSON, encode) import Data.Typeable (Typeable) import Text.Lit.Report (ConfigVar, fromTag, modify, get, Report) import Data.ByteString.Lazy.Char8 (unpack) import Data.HashMap.Strict (insert) data ChartCountTag = ChartCountTag deriving Typeable chartCount :: ConfigVar Int chartCount = fromTag ChartCountTag 0 chart :: A.ToJSON a => a -> Report P.Block chart ch = do count <- get chartCount modify chartCount (+1) let (A.Object obj) = toJSON ch chartName = "_chart_" ++ show count obj' = insert "bindto" (toJSON $ "#" ++ chartName) obj element = "<div id=\"" ++ chartName ++ "\"></div>" json = unpack $ encode obj' script = "<script>c3.generate(" ++ json ++ ");</script>" return $ P.RawBlock (P.Format "html") $ element ++ script
andersjel/hlit
hlit-c3js/src/Text/Lit/C3js.hs
gpl-3.0
973
0
13
172
303
167
136
24
1
module Language.FIRRTL.Parser.Expression ( expr ) where import Control.Applicative import qualified Data.Char as C import Data.List (foldl', intersperse) import Data.Text (Text, append, unpack) import Text.Parser.Expression import Text.Parser.Token hiding (binary, octal, hexadecimal) import Text.Trifecta hiding (octal, hexadecimal, integer) import Language.FIRRTL.Parser.Common import Language.FIRRTL.Syntax expr :: (Monad m, TokenParsing m) => m Expr expr = term >>= sub sub :: (Monad m, TokenParsing m) => Expr -> m Expr sub e = do msub <- optional (dot <|> symbolic '[') case msub of (Just c) -> sub =<< if c == '.' then SubField e <$> identifier else SubAccess e <$> (expr <* symbolic ']') Nothing -> pure e term :: (Monad m, TokenParsing m) => m Expr term = (Lit <$> (fromInteger <$> natural) <?> "natural integer") -- <|> (G <$> constant <?> "ground value") <|> ref <|> mux <|> valid <|> op <|> parens expr -- unfortunately Text.Parser.Token does not export this function -- https://hackage.haskell.org/package/parsers-0.12.4/docs/src/Text-Parser-Token.html#number number :: TokenParsing m => Integer -> m Char -> m Integer number base baseDigit = foldl' (\x d -> base*x + toInteger (C.digitToInt d)) 0 <$> some baseDigit binary, octal, hexadecimal :: TokenParsing m => m Integer binary = number 2 (oneOf "01") octal = number 8 (oneOf "01234567") hexadecimal = number 16 (satisfy C.isHexDigit) data S = S | U sign :: (Monad m, TokenParsing m) => m S sign = reserved "UInt" *> pure U <|> reserved "SInt" *> pure S size :: (Monad m, TokenParsing m) => m (Maybe Int) size = optional (angles $ fromInteger <$> natural) neg :: (Monad m, TokenParsing m) => m Integer -> m Integer neg p = do min <- optional (symbolic '-') case min of Just _ -> negate <$> p Nothing -> p value :: (Monad m, TokenParsing m) => m Int value = parens (fromInteger <$> (integer <|> between (char '"') (char '"') (char 'b' *> neg binary <|> char 'o' *> neg octal <|> char 'h' *> neg hexadecimal))) constant :: (Monad m, TokenParsing m) => m Ground constant = do s <- sign msize <- size val <- value let calc = ceiling $ logBase 2.0 (fromIntegral val) dcons <- case s of U -> if val < 0 then unexpected "Expected unsigned integer" else pure UInt _ -> pure SInt -- check size size <- case msize of (Just s) -> if s < calc then unexpected $ "Provided bit width is smaller than the " ++ "number of bits required to represent specified value" else pure s Nothing -> pure calc pure $ dcons size val ref :: (Monad m, TokenParsing m) => m Expr ref = Ref <$> identifier <?> "Reference" mux :: (Monad m, TokenParsing m) => m Expr mux = do reserved "mux" <?> "Multiplexor keyword" args <- parens $ commaSep expr if length args /= 3 then unexpected "Expected 3 arguments to multiplexor" else let [cond, a, b] = args in pure $ Mux cond a b valid :: (Monad m, TokenParsing m) => m Expr valid = do reserved "validif" <?> "Conditional validity" args <- parens $ commaSep expr if length args /= 2 then unexpected "Expected 2 arguments to conditional validity" else let [cond, arg] = args in pure $ Valid cond arg -- generic function parser? -- op :: (Monad m, TokenParsing m) => String -> [m a] -> m Prim -- op keyword args = do -- reserved keyword <?> ("Primitive operation: " ++ keyword) -- symbolic '(' -- a <- sequence (intersperse comma args) -- symbolic ')' -- pure $ Op a twoExpr :: (Monad m, TokenParsing m) => Text -> (Expr -> Expr -> Prim) -> m Prim twoExpr keyword cons = cons <$> (reserved keyword *> symbolic '(' *> expr <* comma) <*> (expr <* symbolic ')') <?> unpack (append keyword " primitive operation") oneExpr :: (Monad m, TokenParsing m) => Text -> (Expr -> Prim) -> m Prim oneExpr keyword cons = cons <$> (reserved keyword *> parens expr) <?> unpack (append keyword " primitive operation") intExpr :: (Monad m, TokenParsing m) => Text -> (Expr -> Int -> Prim) -> m Prim intExpr keyword cons = cons <$> (reserved keyword *> symbolic '(' *> expr <* comma) <*> (fromInteger <$> natural <* symbolic ')') <?> unpack (append keyword " primitive operation") twoIntExpr :: (Monad m, TokenParsing m) => Text -> (Expr -> Int -> Int -> Prim) -> m Prim twoIntExpr keyword cons = cons <$> (reserved keyword *> symbolic '(' *> expr <* comma) <*> (fromInteger <$> natural <* comma) <*> (fromInteger <$> natural <* symbolic ')') <?> unpack (append keyword " primitive operation") op :: (Monad m, TokenParsing m) => m Expr op = Op <$> (twoExpr "add" Add <|> twoExpr "sub" Sub <|> twoExpr "mul" Mul <|> twoExpr "div" Div <|> twoExpr "mod" Mod <|> twoExpr "lt" Lt <|> twoExpr "leq" Leq <|> twoExpr "gt" Gt <|> twoExpr "geq" Geq <|> twoExpr "eq" Eq <|> twoExpr "neq" Neq <|> twoExpr "dshl" DShl <|> twoExpr "dshr" DShr <|> twoExpr "and" And <|> twoExpr "or" Or <|> twoExpr "cat" Cat <|> oneExpr "asUInt" AsUnsigned <|> oneExpr "asSInt" AsSigned <|> oneExpr "asClock" AsClock <|> oneExpr "cvt" Cvt <|> oneExpr "neg" Neg <|> oneExpr "not" Not <|> oneExpr "xor" Xor <|> oneExpr "andr" AndR <|> oneExpr "orr" OrR <|> oneExpr "xorr" XorR <|> intExpr "pad" Pad <|> intExpr "shl" Shl <|> intExpr "shr" Shr <|> intExpr "head" Head <|> intExpr "tail" Tail <|> twoIntExpr "bits" Bits)
quivade/screwdriver
src/Language/FIRRTL/Parser/Expression.hs
gpl-3.0
5,697
0
38
1,467
1,955
979
976
148
5
{-# LANGUAGE DeriveDataTypeable #-} module Ampersand.Basics.PandocExtended ( PandocFormat(..) , Markup(..) , aMarkup2String , string2Blocks ) where import Ampersand.Basics.Languages import Ampersand.Basics.Prelude import Ampersand.Basics.Unique import Ampersand.Basics.Version import Data.Data import qualified Data.Text as Text import Text.Pandoc hiding (Meta) data PandocFormat = HTML | ReST | LaTeX | Markdown deriving (Eq, Show, Ord, Enum, Bounded) data Markup = Markup { amLang :: Lang -- No Maybe here! In the A-structure, it will be defined by the default if the P-structure does not define it. In the P-structure, the language is optional. , amPandoc :: [Block] } deriving (Show, Eq, Ord, Typeable, Data) instance Unique Markup where showUnique = show -- | a way to show the pandoc in a default way. We currently use Markdown for this purpose. aMarkup2String :: Markup -> String aMarkup2String = blocks2String . amPandoc where blocks2String :: [Block] -> String blocks2String ec = case runPure $ writeMarkdown def (Pandoc nullMeta ec) of Left pandocError -> fatal $ "Pandoc error: "++show pandocError Right txt -> Text.unpack txt -- | use a suitable format to read generated strings. if you have just normal text, ReST is fine. -- | defaultPandocReader getOpts should be used on user-defined strings. string2Blocks :: PandocFormat -> String -> [Block] string2Blocks defaultformat str = case runPure $ theParser (Text.pack (removeCRs str)) of Left err -> fatal ("Proper error handling of Pandoc is still TODO." ++"\n This particular error is cause by some "++show defaultformat++" in your script:" ++"\n"++show err) Right (Pandoc _ blocks) -> blocks where theParser = case defaultformat of Markdown -> readMarkdown def ReST -> readRST def HTML -> readHtml def LaTeX -> readLaTeX def removeCRs :: String -> String removeCRs [] = [] removeCRs ('\r' :'\n' : xs) = '\n' : removeCRs xs removeCRs (c:xs) = c:removeCRs xs
AmpersandTarski/ampersand
src/Ampersand/Basics/PandocExtended.hs
gpl-3.0
2,250
0
14
621
501
270
231
44
7
module Main where import Data.Array (Array, array, Ix) import Data.List.Split (splitOn) import System.IO import qualified Data.Vector as V import Data.Vector (Vector) import Data.Maybe import Data.List import Town import TravellingSalesPerson import ConvexHull -- | Reads towns from tab seperated format to the Town type -- e.g 1 Abbeyfeale 52.386 -9.294 readTown :: String -> Town readTown = makeTown . splitOn "\t" where makeTown town = Town (townId town) (name town) (coords town) False townId = (read :: String -> Int) . (!! 0) name = (!! 1) coords a = apply (read :: String -> Double) ((a !! 2), (a !! 3)) --readTownsArray :: (Enum i, Num i, Ix i) => FilePath -> IO (Array i Town) --readTownsArray fileName = openFile fileName ReadMode >>= hGetContents >>= -- return . array (1,80) . (zip [1..80]) . map readTown . lines -- | reads from a file into a Vector of Towns readTownsVector :: FilePath -> IO (Vector Town) readTownsVector fileName = openFile fileName ReadMode >>= hGetContents >>= return . V.fromList . map readTown . lines -- | Worst possible way of converting the list of points in the convex hull to -- a list of town ids. by searching for each one -- n^2 for life! searchTowns :: Vector Town -> Point Double -> Maybe Town searchTowns vector point = V.find (\x -> point == coords x) vector main :: IO () main = do townList <- readTownsVector "Towns.csv" {->>= distanceMatrix-} print . intercalate "." . map (show . fromJust . fmap townId) . map (searchTowns townList) . convexHull . V.toList . fmap coords $ townList
Jiggins/Travelling-Sales-Person
Main.hs
gpl-3.0
1,598
0
16
328
416
225
191
27
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FlexibleInstances #-} module Config.Reservation where import Config.Class(ConfigClass(..), readInclude, lookupInt, lookupInteger, lookupText, lookupString,lookupWord) import Config.Env(Env(..)) data ReservationCommandArg = ArgDevice | ArgChannel | ArgDurationSec | ArgDestFilePath deriving (Show) data ReservationConfig = ReservationConfig { marginStart :: Word, scriptFilePath :: FilePath } deriving (Show) scriptArgs = [ArgDevice,ArgChannel,ArgDurationSec,ArgDestFilePath] defaultReservationConfig :: ReservationConfig defaultReservationConfig = ReservationConfig { marginStart = 3, scriptFilePath = "recpt1.sh" } instance ConfigClass ReservationConfig where defaultConfig env = return defaultReservationConfig objectToConfig obj dflt = ReservationConfig { marginStart = marginStart `or'` (lookupWord "marginStart"), scriptFilePath = scriptFilePath `or'` (lookupString "scriptFilePath") } where mor' = mor dflt obj or' = Config.Class.or dflt obj
shinjiro-itagaki/shinjirecs
shinjirecs-api/src/Config/Reservation.hs
gpl-3.0
1,103
0
10
174
239
144
95
24
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.IAM.Types.Product -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- module Network.AWS.IAM.Types.Product where import Network.AWS.IAM.Types.Sum import Network.AWS.Prelude -- | Contains information about an AWS access key. -- -- This data type is used as a response element in the CreateAccessKey and -- ListAccessKeys actions. -- -- The 'SecretAccessKey' value is returned only in response to -- CreateAccessKey. You can get a secret access key only when you first -- create an access key; you cannot recover the secret access key later. If -- you lose a secret access key, you must create a new access key. -- -- /See:/ 'accessKey' smart constructor. data AccessKey = AccessKey' { _akCreateDate :: !(Maybe ISO8601) , _akUserName :: !Text , _akAccessKeyId :: !Text , _akStatus :: !StatusType , _akSecretAccessKey :: !(Sensitive Text) } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'AccessKey' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'akCreateDate' -- -- * 'akUserName' -- -- * 'akAccessKeyId' -- -- * 'akStatus' -- -- * 'akSecretAccessKey' accessKey :: Text -- ^ 'akUserName' -> Text -- ^ 'akAccessKeyId' -> StatusType -- ^ 'akStatus' -> Text -- ^ 'akSecretAccessKey' -> AccessKey accessKey pUserName_ pAccessKeyId_ pStatus_ pSecretAccessKey_ = AccessKey' { _akCreateDate = Nothing , _akUserName = pUserName_ , _akAccessKeyId = pAccessKeyId_ , _akStatus = pStatus_ , _akSecretAccessKey = _Sensitive # pSecretAccessKey_ } -- | The date when the access key was created. akCreateDate :: Lens' AccessKey (Maybe UTCTime) akCreateDate = lens _akCreateDate (\ s a -> s{_akCreateDate = a}) . mapping _Time; -- | The name of the IAM user that the access key is associated with. akUserName :: Lens' AccessKey Text akUserName = lens _akUserName (\ s a -> s{_akUserName = a}); -- | The ID for this access key. akAccessKeyId :: Lens' AccessKey Text akAccessKeyId = lens _akAccessKeyId (\ s a -> s{_akAccessKeyId = a}); -- | The status of the access key. 'Active' means the key is valid for API -- calls, while 'Inactive' means it is not. akStatus :: Lens' AccessKey StatusType akStatus = lens _akStatus (\ s a -> s{_akStatus = a}); -- | The secret key used to sign requests. akSecretAccessKey :: Lens' AccessKey Text akSecretAccessKey = lens _akSecretAccessKey (\ s a -> s{_akSecretAccessKey = a}) . _Sensitive; instance FromXML AccessKey where parseXML x = AccessKey' <$> (x .@? "CreateDate") <*> (x .@ "UserName") <*> (x .@ "AccessKeyId") <*> (x .@ "Status") <*> (x .@ "SecretAccessKey") -- | Contains information about the last time an AWS access key was used. -- -- This data type is used as a response element in the GetAccessKeyLastUsed -- action. -- -- /See:/ 'accessKeyLastUsed' smart constructor. data AccessKeyLastUsed = AccessKeyLastUsed' { _akluLastUsedDate :: !ISO8601 , _akluServiceName :: !Text , _akluRegion :: !Text } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'AccessKeyLastUsed' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'akluLastUsedDate' -- -- * 'akluServiceName' -- -- * 'akluRegion' accessKeyLastUsed :: UTCTime -- ^ 'akluLastUsedDate' -> Text -- ^ 'akluServiceName' -> Text -- ^ 'akluRegion' -> AccessKeyLastUsed accessKeyLastUsed pLastUsedDate_ pServiceName_ pRegion_ = AccessKeyLastUsed' { _akluLastUsedDate = _Time # pLastUsedDate_ , _akluServiceName = pServiceName_ , _akluRegion = pRegion_ } -- | The date and time, in -- <http://www.iso.org/iso/iso8601 ISO 8601 date-time format>, when the -- access key was most recently used. This field is null when: -- -- - The user does not have an access key. -- -- - An access key exists but has never been used, at least not since IAM -- started tracking this information on April 22nd, 2015. -- -- - There is no sign-in data associated with the user -- akluLastUsedDate :: Lens' AccessKeyLastUsed UTCTime akluLastUsedDate = lens _akluLastUsedDate (\ s a -> s{_akluLastUsedDate = a}) . _Time; -- | The name of the AWS service with which this access key was most recently -- used. This field is null when: -- -- - The user does not have an access key. -- -- - An access key exists but has never been used, at least not since IAM -- started tracking this information on April 22nd, 2015. -- -- - There is no sign-in data associated with the user -- akluServiceName :: Lens' AccessKeyLastUsed Text akluServiceName = lens _akluServiceName (\ s a -> s{_akluServiceName = a}); -- | The AWS region where this access key was most recently used. This field -- is null when: -- -- - The user does not have an access key. -- -- - An access key exists but has never been used, at least not since IAM -- started tracking this information on April 22nd, 2015. -- -- - There is no sign-in data associated with the user -- -- For more information about AWS regions, see -- <http://docs.aws.amazon.com/general/latest/gr/rande.html Regions and Endpoints> -- in the Amazon Web Services General Reference. akluRegion :: Lens' AccessKeyLastUsed Text akluRegion = lens _akluRegion (\ s a -> s{_akluRegion = a}); instance FromXML AccessKeyLastUsed where parseXML x = AccessKeyLastUsed' <$> (x .@ "LastUsedDate") <*> (x .@ "ServiceName") <*> (x .@ "Region") -- | Contains information about an AWS access key, without its secret key. -- -- This data type is used as a response element in the ListAccessKeys -- action. -- -- /See:/ 'accessKeyMetadata' smart constructor. data AccessKeyMetadata = AccessKeyMetadata' { _akmStatus :: !(Maybe StatusType) , _akmCreateDate :: !(Maybe ISO8601) , _akmUserName :: !(Maybe Text) , _akmAccessKeyId :: !(Maybe Text) } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'AccessKeyMetadata' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'akmStatus' -- -- * 'akmCreateDate' -- -- * 'akmUserName' -- -- * 'akmAccessKeyId' accessKeyMetadata :: AccessKeyMetadata accessKeyMetadata = AccessKeyMetadata' { _akmStatus = Nothing , _akmCreateDate = Nothing , _akmUserName = Nothing , _akmAccessKeyId = Nothing } -- | The status of the access key. 'Active' means the key is valid for API -- calls; 'Inactive' means it is not. akmStatus :: Lens' AccessKeyMetadata (Maybe StatusType) akmStatus = lens _akmStatus (\ s a -> s{_akmStatus = a}); -- | The date when the access key was created. akmCreateDate :: Lens' AccessKeyMetadata (Maybe UTCTime) akmCreateDate = lens _akmCreateDate (\ s a -> s{_akmCreateDate = a}) . mapping _Time; -- | The name of the IAM user that the key is associated with. akmUserName :: Lens' AccessKeyMetadata (Maybe Text) akmUserName = lens _akmUserName (\ s a -> s{_akmUserName = a}); -- | The ID for this access key. akmAccessKeyId :: Lens' AccessKeyMetadata (Maybe Text) akmAccessKeyId = lens _akmAccessKeyId (\ s a -> s{_akmAccessKeyId = a}); instance FromXML AccessKeyMetadata where parseXML x = AccessKeyMetadata' <$> (x .@? "Status") <*> (x .@? "CreateDate") <*> (x .@? "UserName") <*> (x .@? "AccessKeyId") -- | Contains information about an attached policy. -- -- An attached policy is a managed policy that has been attached to a user, -- group, or role. This data type is used as a response element in the -- ListAttachedGroupPolicies, ListAttachedRolePolicies, -- ListAttachedUserPolicies, and GetAccountAuthorizationDetails actions. -- -- For more information about managed policies, refer to -- <http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html Managed Policies and Inline Policies> -- in the /Using IAM/ guide. -- -- /See:/ 'attachedPolicy' smart constructor. data AttachedPolicy = AttachedPolicy' { _apPolicyName :: !(Maybe Text) , _apPolicyARN :: !(Maybe Text) } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'AttachedPolicy' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'apPolicyName' -- -- * 'apPolicyARN' attachedPolicy :: AttachedPolicy attachedPolicy = AttachedPolicy' { _apPolicyName = Nothing , _apPolicyARN = Nothing } -- | The friendly name of the attached policy. apPolicyName :: Lens' AttachedPolicy (Maybe Text) apPolicyName = lens _apPolicyName (\ s a -> s{_apPolicyName = a}); -- | Undocumented member. apPolicyARN :: Lens' AttachedPolicy (Maybe Text) apPolicyARN = lens _apPolicyARN (\ s a -> s{_apPolicyARN = a}); instance FromXML AttachedPolicy where parseXML x = AttachedPolicy' <$> (x .@? "PolicyName") <*> (x .@? "PolicyArn") -- | Contains information about a condition context key. It includes the name -- of the key and specifies the value (or values, if the context key -- supports multiple values) to use in the simulation. This information is -- used when evaluating the 'Condition' elements of the input policies. -- -- This data type is used as an input parameter to 'SimulatePolicy'. -- -- /See:/ 'contextEntry' smart constructor. data ContextEntry = ContextEntry' { _ceContextKeyValues :: !(Maybe [Text]) , _ceContextKeyName :: !(Maybe Text) , _ceContextKeyType :: !(Maybe ContextKeyTypeEnum) } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'ContextEntry' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ceContextKeyValues' -- -- * 'ceContextKeyName' -- -- * 'ceContextKeyType' contextEntry :: ContextEntry contextEntry = ContextEntry' { _ceContextKeyValues = Nothing , _ceContextKeyName = Nothing , _ceContextKeyType = Nothing } -- | The value (or values, if the condition context key supports multiple -- values) to provide to the simulation for use when the key is referenced -- by a 'Condition' element in an input policy. ceContextKeyValues :: Lens' ContextEntry [Text] ceContextKeyValues = lens _ceContextKeyValues (\ s a -> s{_ceContextKeyValues = a}) . _Default . _Coerce; -- | The full name of a condition context key, including the service prefix. -- For example, 'aws:SourceIp' or 's3:VersionId'. ceContextKeyName :: Lens' ContextEntry (Maybe Text) ceContextKeyName = lens _ceContextKeyName (\ s a -> s{_ceContextKeyName = a}); -- | The data type of the value (or values) specified in the -- 'ContextKeyValues' parameter. ceContextKeyType :: Lens' ContextEntry (Maybe ContextKeyTypeEnum) ceContextKeyType = lens _ceContextKeyType (\ s a -> s{_ceContextKeyType = a}); instance ToQuery ContextEntry where toQuery ContextEntry'{..} = mconcat ["ContextKeyValues" =: toQuery (toQueryList "member" <$> _ceContextKeyValues), "ContextKeyName" =: _ceContextKeyName, "ContextKeyType" =: _ceContextKeyType] -- | Contains the results of a simulation. -- -- This data type is used by the return parameter of 'SimulatePolicy'. -- -- /See:/ 'evaluationResult' smart constructor. data EvaluationResult = EvaluationResult' { _erMatchedStatements :: !(Maybe [Statement]) , _erMissingContextValues :: !(Maybe [Text]) , _erEvalActionName :: !Text , _erEvalResourceName :: !Text , _erEvalDecision :: !PolicyEvaluationDecisionType } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'EvaluationResult' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'erMatchedStatements' -- -- * 'erMissingContextValues' -- -- * 'erEvalActionName' -- -- * 'erEvalResourceName' -- -- * 'erEvalDecision' evaluationResult :: Text -- ^ 'erEvalActionName' -> Text -- ^ 'erEvalResourceName' -> PolicyEvaluationDecisionType -- ^ 'erEvalDecision' -> EvaluationResult evaluationResult pEvalActionName_ pEvalResourceName_ pEvalDecision_ = EvaluationResult' { _erMatchedStatements = Nothing , _erMissingContextValues = Nothing , _erEvalActionName = pEvalActionName_ , _erEvalResourceName = pEvalResourceName_ , _erEvalDecision = pEvalDecision_ } -- | A list of the statements in the input policies that determine the result -- for this scenario. Remember that even if multiple statements allow the -- action on the resource, if only one statement denies that action, then -- the explicit deny overrides any allow, and the deny statement is the -- only entry included in the result. erMatchedStatements :: Lens' EvaluationResult [Statement] erMatchedStatements = lens _erMatchedStatements (\ s a -> s{_erMatchedStatements = a}) . _Default . _Coerce; -- | A list of context keys that are required by the included input policies -- but that were not provided by one of the input parameters. To discover -- the context keys used by a set of policies, you can call -- GetContextKeysForCustomPolicy or GetContextKeysForPrincipalPolicy. -- -- If the response includes any keys in this list, then the reported -- results might be untrustworthy because the simulation could not -- completely evaluate all of the conditions specified in the policies that -- would occur in a real world request. erMissingContextValues :: Lens' EvaluationResult [Text] erMissingContextValues = lens _erMissingContextValues (\ s a -> s{_erMissingContextValues = a}) . _Default . _Coerce; -- | The name of the API action tested on the indicated resource. erEvalActionName :: Lens' EvaluationResult Text erEvalActionName = lens _erEvalActionName (\ s a -> s{_erEvalActionName = a}); -- | The ARN of the resource that the indicated API action was tested on. erEvalResourceName :: Lens' EvaluationResult Text erEvalResourceName = lens _erEvalResourceName (\ s a -> s{_erEvalResourceName = a}); -- | The result of the simulation. erEvalDecision :: Lens' EvaluationResult PolicyEvaluationDecisionType erEvalDecision = lens _erEvalDecision (\ s a -> s{_erEvalDecision = a}); instance FromXML EvaluationResult where parseXML x = EvaluationResult' <$> (x .@? "MatchedStatements" .!@ mempty >>= may (parseXMLList "member")) <*> (x .@? "MissingContextValues" .!@ mempty >>= may (parseXMLList "member")) <*> (x .@ "EvalActionName") <*> (x .@ "EvalResourceName") <*> (x .@ "EvalDecision") -- | Contains the response to a successful GetContextKeysForPrincipalPolicy -- or GetContextKeysForCustomPolicy request. -- -- /See:/ 'getContextKeysForPolicyResponse' smart constructor. newtype GetContextKeysForPolicyResponse = GetContextKeysForPolicyResponse' { _gckfpContextKeyNames :: Maybe [Text] } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'GetContextKeysForPolicyResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gckfpContextKeyNames' getContextKeysForPolicyResponse :: GetContextKeysForPolicyResponse getContextKeysForPolicyResponse = GetContextKeysForPolicyResponse' { _gckfpContextKeyNames = Nothing } -- | The list of context keys that are used in the 'Condition' elements of -- the input policies. gckfpContextKeyNames :: Lens' GetContextKeysForPolicyResponse [Text] gckfpContextKeyNames = lens _gckfpContextKeyNames (\ s a -> s{_gckfpContextKeyNames = a}) . _Default . _Coerce; instance FromXML GetContextKeysForPolicyResponse where parseXML x = GetContextKeysForPolicyResponse' <$> (x .@? "ContextKeyNames" .!@ mempty >>= may (parseXMLList "member")) -- | Contains information about an IAM group entity. -- -- This data type is used as a response element in the following actions: -- -- - CreateGroup -- - GetGroup -- - ListGroups -- -- /See:/ 'group'' smart constructor. data Group = Group' { _gPath :: !Text , _gGroupName :: !Text , _gGroupId :: !Text , _gARN :: !Text , _gCreateDate :: !ISO8601 } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'Group' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gPath' -- -- * 'gGroupName' -- -- * 'gGroupId' -- -- * 'gARN' -- -- * 'gCreateDate' group' :: Text -- ^ 'gPath' -> Text -- ^ 'gGroupName' -> Text -- ^ 'gGroupId' -> Text -- ^ 'gARN' -> UTCTime -- ^ 'gCreateDate' -> Group group' pPath_ pGroupName_ pGroupId_ pARN_ pCreateDate_ = Group' { _gPath = pPath_ , _gGroupName = pGroupName_ , _gGroupId = pGroupId_ , _gARN = pARN_ , _gCreateDate = _Time # pCreateDate_ } -- | The path to the group. For more information about paths, see -- <http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html IAM Identifiers> -- in the /Using IAM/ guide. gPath :: Lens' Group Text gPath = lens _gPath (\ s a -> s{_gPath = a}); -- | The friendly name that identifies the group. gGroupName :: Lens' Group Text gGroupName = lens _gGroupName (\ s a -> s{_gGroupName = a}); -- | The stable and unique string identifying the group. For more information -- about IDs, see -- <http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html IAM Identifiers> -- in the /Using IAM/ guide. gGroupId :: Lens' Group Text gGroupId = lens _gGroupId (\ s a -> s{_gGroupId = a}); -- | The Amazon Resource Name (ARN) specifying the group. For more -- information about ARNs and how to use them in policies, see -- <http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html IAM Identifiers> -- in the /Using IAM/ guide. gARN :: Lens' Group Text gARN = lens _gARN (\ s a -> s{_gARN = a}); -- | The date and time, in -- <http://www.iso.org/iso/iso8601 ISO 8601 date-time format>, when the -- group was created. gCreateDate :: Lens' Group UTCTime gCreateDate = lens _gCreateDate (\ s a -> s{_gCreateDate = a}) . _Time; instance FromXML Group where parseXML x = Group' <$> (x .@ "Path") <*> (x .@ "GroupName") <*> (x .@ "GroupId") <*> (x .@ "Arn") <*> (x .@ "CreateDate") -- | Contains information about an IAM group, including all of the group\'s -- policies. -- -- This data type is used as a response element in the -- GetAccountAuthorizationDetails action. -- -- /See:/ 'groupDetail' smart constructor. data GroupDetail = GroupDetail' { _gdARN :: !(Maybe Text) , _gdPath :: !(Maybe Text) , _gdCreateDate :: !(Maybe ISO8601) , _gdGroupId :: !(Maybe Text) , _gdGroupPolicyList :: !(Maybe [PolicyDetail]) , _gdGroupName :: !(Maybe Text) , _gdAttachedManagedPolicies :: !(Maybe [AttachedPolicy]) } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'GroupDetail' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gdARN' -- -- * 'gdPath' -- -- * 'gdCreateDate' -- -- * 'gdGroupId' -- -- * 'gdGroupPolicyList' -- -- * 'gdGroupName' -- -- * 'gdAttachedManagedPolicies' groupDetail :: GroupDetail groupDetail = GroupDetail' { _gdARN = Nothing , _gdPath = Nothing , _gdCreateDate = Nothing , _gdGroupId = Nothing , _gdGroupPolicyList = Nothing , _gdGroupName = Nothing , _gdAttachedManagedPolicies = Nothing } -- | Undocumented member. gdARN :: Lens' GroupDetail (Maybe Text) gdARN = lens _gdARN (\ s a -> s{_gdARN = a}); -- | The path to the group. For more information about paths, see -- <http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html IAM Identifiers> -- in the /Using IAM/ guide. gdPath :: Lens' GroupDetail (Maybe Text) gdPath = lens _gdPath (\ s a -> s{_gdPath = a}); -- | The date and time, in -- <http://www.iso.org/iso/iso8601 ISO 8601 date-time format>, when the -- group was created. gdCreateDate :: Lens' GroupDetail (Maybe UTCTime) gdCreateDate = lens _gdCreateDate (\ s a -> s{_gdCreateDate = a}) . mapping _Time; -- | The stable and unique string identifying the group. For more information -- about IDs, see -- <http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html IAM Identifiers> -- in the /Using IAM/ guide. gdGroupId :: Lens' GroupDetail (Maybe Text) gdGroupId = lens _gdGroupId (\ s a -> s{_gdGroupId = a}); -- | A list of the inline policies embedded in the group. gdGroupPolicyList :: Lens' GroupDetail [PolicyDetail] gdGroupPolicyList = lens _gdGroupPolicyList (\ s a -> s{_gdGroupPolicyList = a}) . _Default . _Coerce; -- | The friendly name that identifies the group. gdGroupName :: Lens' GroupDetail (Maybe Text) gdGroupName = lens _gdGroupName (\ s a -> s{_gdGroupName = a}); -- | A list of the managed policies attached to the group. gdAttachedManagedPolicies :: Lens' GroupDetail [AttachedPolicy] gdAttachedManagedPolicies = lens _gdAttachedManagedPolicies (\ s a -> s{_gdAttachedManagedPolicies = a}) . _Default . _Coerce; instance FromXML GroupDetail where parseXML x = GroupDetail' <$> (x .@? "Arn") <*> (x .@? "Path") <*> (x .@? "CreateDate") <*> (x .@? "GroupId") <*> (x .@? "GroupPolicyList" .!@ mempty >>= may (parseXMLList "member")) <*> (x .@? "GroupName") <*> (x .@? "AttachedManagedPolicies" .!@ mempty >>= may (parseXMLList "member")) -- | Contains information about an instance profile. -- -- This data type is used as a response element in the following actions: -- -- - CreateInstanceProfile -- -- - GetInstanceProfile -- -- - ListInstanceProfiles -- -- - ListInstanceProfilesForRole -- -- -- /See:/ 'instanceProfile' smart constructor. data InstanceProfile = InstanceProfile' { _ipPath :: !Text , _ipInstanceProfileName :: !Text , _ipInstanceProfileId :: !Text , _ipARN :: !Text , _ipCreateDate :: !ISO8601 , _ipRoles :: ![Role] } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'InstanceProfile' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ipPath' -- -- * 'ipInstanceProfileName' -- -- * 'ipInstanceProfileId' -- -- * 'ipARN' -- -- * 'ipCreateDate' -- -- * 'ipRoles' instanceProfile :: Text -- ^ 'ipPath' -> Text -- ^ 'ipInstanceProfileName' -> Text -- ^ 'ipInstanceProfileId' -> Text -- ^ 'ipARN' -> UTCTime -- ^ 'ipCreateDate' -> InstanceProfile instanceProfile pPath_ pInstanceProfileName_ pInstanceProfileId_ pARN_ pCreateDate_ = InstanceProfile' { _ipPath = pPath_ , _ipInstanceProfileName = pInstanceProfileName_ , _ipInstanceProfileId = pInstanceProfileId_ , _ipARN = pARN_ , _ipCreateDate = _Time # pCreateDate_ , _ipRoles = mempty } -- | The path to the instance profile. For more information about paths, see -- <http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html IAM Identifiers> -- in the /Using IAM/ guide. ipPath :: Lens' InstanceProfile Text ipPath = lens _ipPath (\ s a -> s{_ipPath = a}); -- | The name identifying the instance profile. ipInstanceProfileName :: Lens' InstanceProfile Text ipInstanceProfileName = lens _ipInstanceProfileName (\ s a -> s{_ipInstanceProfileName = a}); -- | The stable and unique string identifying the instance profile. For more -- information about IDs, see -- <http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html IAM Identifiers> -- in the /Using IAM/ guide. ipInstanceProfileId :: Lens' InstanceProfile Text ipInstanceProfileId = lens _ipInstanceProfileId (\ s a -> s{_ipInstanceProfileId = a}); -- | The Amazon Resource Name (ARN) specifying the instance profile. For more -- information about ARNs and how to use them in policies, see -- <http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html IAM Identifiers> -- in the /Using IAM/ guide. ipARN :: Lens' InstanceProfile Text ipARN = lens _ipARN (\ s a -> s{_ipARN = a}); -- | The date when the instance profile was created. ipCreateDate :: Lens' InstanceProfile UTCTime ipCreateDate = lens _ipCreateDate (\ s a -> s{_ipCreateDate = a}) . _Time; -- | The role associated with the instance profile. ipRoles :: Lens' InstanceProfile [Role] ipRoles = lens _ipRoles (\ s a -> s{_ipRoles = a}) . _Coerce; instance FromXML InstanceProfile where parseXML x = InstanceProfile' <$> (x .@ "Path") <*> (x .@ "InstanceProfileName") <*> (x .@ "InstanceProfileId") <*> (x .@ "Arn") <*> (x .@ "CreateDate") <*> (x .@? "Roles" .!@ mempty >>= parseXMLList "member") -- | Contains the user name and password create date for a user. -- -- This data type is used as a response element in the CreateLoginProfile -- and GetLoginProfile actions. -- -- /See:/ 'loginProfile' smart constructor. data LoginProfile = LoginProfile' { _lpPasswordResetRequired :: !(Maybe Bool) , _lpUserName :: !Text , _lpCreateDate :: !ISO8601 } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'LoginProfile' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lpPasswordResetRequired' -- -- * 'lpUserName' -- -- * 'lpCreateDate' loginProfile :: Text -- ^ 'lpUserName' -> UTCTime -- ^ 'lpCreateDate' -> LoginProfile loginProfile pUserName_ pCreateDate_ = LoginProfile' { _lpPasswordResetRequired = Nothing , _lpUserName = pUserName_ , _lpCreateDate = _Time # pCreateDate_ } -- | Specifies whether the user is required to set a new password on next -- sign-in. lpPasswordResetRequired :: Lens' LoginProfile (Maybe Bool) lpPasswordResetRequired = lens _lpPasswordResetRequired (\ s a -> s{_lpPasswordResetRequired = a}); -- | The name of the user, which can be used for signing in to the AWS -- Management Console. lpUserName :: Lens' LoginProfile Text lpUserName = lens _lpUserName (\ s a -> s{_lpUserName = a}); -- | The date when the password for the user was created. lpCreateDate :: Lens' LoginProfile UTCTime lpCreateDate = lens _lpCreateDate (\ s a -> s{_lpCreateDate = a}) . _Time; instance FromXML LoginProfile where parseXML x = LoginProfile' <$> (x .@? "PasswordResetRequired") <*> (x .@ "UserName") <*> (x .@ "CreateDate") -- | Contains information about an MFA device. -- -- This data type is used as a response element in the ListMFADevices -- action. -- -- /See:/ 'mfaDevice' smart constructor. data MFADevice = MFADevice' { _mdUserName :: !Text , _mdSerialNumber :: !Text , _mdEnableDate :: !ISO8601 } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'MFADevice' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'mdUserName' -- -- * 'mdSerialNumber' -- -- * 'mdEnableDate' mfaDevice :: Text -- ^ 'mdUserName' -> Text -- ^ 'mdSerialNumber' -> UTCTime -- ^ 'mdEnableDate' -> MFADevice mfaDevice pUserName_ pSerialNumber_ pEnableDate_ = MFADevice' { _mdUserName = pUserName_ , _mdSerialNumber = pSerialNumber_ , _mdEnableDate = _Time # pEnableDate_ } -- | The user with whom the MFA device is associated. mdUserName :: Lens' MFADevice Text mdUserName = lens _mdUserName (\ s a -> s{_mdUserName = a}); -- | The serial number that uniquely identifies the MFA device. For virtual -- MFA devices, the serial number is the device ARN. mdSerialNumber :: Lens' MFADevice Text mdSerialNumber = lens _mdSerialNumber (\ s a -> s{_mdSerialNumber = a}); -- | The date when the MFA device was enabled for the user. mdEnableDate :: Lens' MFADevice UTCTime mdEnableDate = lens _mdEnableDate (\ s a -> s{_mdEnableDate = a}) . _Time; instance FromXML MFADevice where parseXML x = MFADevice' <$> (x .@ "UserName") <*> (x .@ "SerialNumber") <*> (x .@ "EnableDate") -- | Contains information about a managed policy, including the policy\'s -- ARN, versions, and the number of principal entities (users, groups, and -- roles) that the policy is attached to. -- -- This data type is used as a response element in the -- GetAccountAuthorizationDetails action. -- -- For more information about managed policies, see -- <http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html Managed Policies and Inline Policies> -- in the /Using IAM/ guide. -- -- /See:/ 'managedPolicyDetail' smart constructor. data ManagedPolicyDetail = ManagedPolicyDetail' { _mpdPolicyName :: !(Maybe Text) , _mpdARN :: !(Maybe Text) , _mpdUpdateDate :: !(Maybe ISO8601) , _mpdPolicyId :: !(Maybe Text) , _mpdPath :: !(Maybe Text) , _mpdPolicyVersionList :: !(Maybe [PolicyVersion]) , _mpdCreateDate :: !(Maybe ISO8601) , _mpdIsAttachable :: !(Maybe Bool) , _mpdDefaultVersionId :: !(Maybe Text) , _mpdAttachmentCount :: !(Maybe Int) , _mpdDescription :: !(Maybe Text) } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'ManagedPolicyDetail' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'mpdPolicyName' -- -- * 'mpdARN' -- -- * 'mpdUpdateDate' -- -- * 'mpdPolicyId' -- -- * 'mpdPath' -- -- * 'mpdPolicyVersionList' -- -- * 'mpdCreateDate' -- -- * 'mpdIsAttachable' -- -- * 'mpdDefaultVersionId' -- -- * 'mpdAttachmentCount' -- -- * 'mpdDescription' managedPolicyDetail :: ManagedPolicyDetail managedPolicyDetail = ManagedPolicyDetail' { _mpdPolicyName = Nothing , _mpdARN = Nothing , _mpdUpdateDate = Nothing , _mpdPolicyId = Nothing , _mpdPath = Nothing , _mpdPolicyVersionList = Nothing , _mpdCreateDate = Nothing , _mpdIsAttachable = Nothing , _mpdDefaultVersionId = Nothing , _mpdAttachmentCount = Nothing , _mpdDescription = Nothing } -- | The friendly name (not ARN) identifying the policy. mpdPolicyName :: Lens' ManagedPolicyDetail (Maybe Text) mpdPolicyName = lens _mpdPolicyName (\ s a -> s{_mpdPolicyName = a}); -- | Undocumented member. mpdARN :: Lens' ManagedPolicyDetail (Maybe Text) mpdARN = lens _mpdARN (\ s a -> s{_mpdARN = a}); -- | The date and time, in -- <http://www.iso.org/iso/iso8601 ISO 8601 date-time format>, when the -- policy was last updated. -- -- When a policy has only one version, this field contains the date and -- time when the policy was created. When a policy has more than one -- version, this field contains the date and time when the most recent -- policy version was created. mpdUpdateDate :: Lens' ManagedPolicyDetail (Maybe UTCTime) mpdUpdateDate = lens _mpdUpdateDate (\ s a -> s{_mpdUpdateDate = a}) . mapping _Time; -- | The stable and unique string identifying the policy. -- -- For more information about IDs, see -- <http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html IAM Identifiers> -- in the /Using IAM/ guide. mpdPolicyId :: Lens' ManagedPolicyDetail (Maybe Text) mpdPolicyId = lens _mpdPolicyId (\ s a -> s{_mpdPolicyId = a}); -- | The path to the policy. -- -- For more information about paths, see -- <http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html IAM Identifiers> -- in the /Using IAM/ guide. mpdPath :: Lens' ManagedPolicyDetail (Maybe Text) mpdPath = lens _mpdPath (\ s a -> s{_mpdPath = a}); -- | A list containing information about the versions of the policy. mpdPolicyVersionList :: Lens' ManagedPolicyDetail [PolicyVersion] mpdPolicyVersionList = lens _mpdPolicyVersionList (\ s a -> s{_mpdPolicyVersionList = a}) . _Default . _Coerce; -- | The date and time, in -- <http://www.iso.org/iso/iso8601 ISO 8601 date-time format>, when the -- policy was created. mpdCreateDate :: Lens' ManagedPolicyDetail (Maybe UTCTime) mpdCreateDate = lens _mpdCreateDate (\ s a -> s{_mpdCreateDate = a}) . mapping _Time; -- | Specifies whether the policy can be attached to an IAM user, group, or -- role. mpdIsAttachable :: Lens' ManagedPolicyDetail (Maybe Bool) mpdIsAttachable = lens _mpdIsAttachable (\ s a -> s{_mpdIsAttachable = a}); -- | The identifier for the version of the policy that is set as the default -- (operative) version. -- -- For more information about policy versions, see -- <http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-versions.html Versioning for Managed Policies> -- in the /Using IAM/ guide. mpdDefaultVersionId :: Lens' ManagedPolicyDetail (Maybe Text) mpdDefaultVersionId = lens _mpdDefaultVersionId (\ s a -> s{_mpdDefaultVersionId = a}); -- | The number of principal entities (users, groups, and roles) that the -- policy is attached to. mpdAttachmentCount :: Lens' ManagedPolicyDetail (Maybe Int) mpdAttachmentCount = lens _mpdAttachmentCount (\ s a -> s{_mpdAttachmentCount = a}); -- | A friendly description of the policy. mpdDescription :: Lens' ManagedPolicyDetail (Maybe Text) mpdDescription = lens _mpdDescription (\ s a -> s{_mpdDescription = a}); instance FromXML ManagedPolicyDetail where parseXML x = ManagedPolicyDetail' <$> (x .@? "PolicyName") <*> (x .@? "Arn") <*> (x .@? "UpdateDate") <*> (x .@? "PolicyId") <*> (x .@? "Path") <*> (x .@? "PolicyVersionList" .!@ mempty >>= may (parseXMLList "member")) <*> (x .@? "CreateDate") <*> (x .@? "IsAttachable") <*> (x .@? "DefaultVersionId") <*> (x .@? "AttachmentCount") <*> (x .@? "Description") -- | Contains the Amazon Resource Name (ARN) for an IAM OpenID Connect -- provider. -- -- /See:/ 'openIdConnectProviderListEntry' smart constructor. newtype OpenIdConnectProviderListEntry = OpenIdConnectProviderListEntry' { _oicpleARN :: Maybe Text } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'OpenIdConnectProviderListEntry' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'oicpleARN' openIdConnectProviderListEntry :: OpenIdConnectProviderListEntry openIdConnectProviderListEntry = OpenIdConnectProviderListEntry' { _oicpleARN = Nothing } -- | Undocumented member. oicpleARN :: Lens' OpenIdConnectProviderListEntry (Maybe Text) oicpleARN = lens _oicpleARN (\ s a -> s{_oicpleARN = a}); instance FromXML OpenIdConnectProviderListEntry where parseXML x = OpenIdConnectProviderListEntry' <$> (x .@? "Arn") -- | Contains information about the account password policy. -- -- This data type is used as a response element in the -- GetAccountPasswordPolicy action. -- -- /See:/ 'passwordPolicy' smart constructor. data PasswordPolicy = PasswordPolicy' { _ppExpirePasswords :: !(Maybe Bool) , _ppMinimumPasswordLength :: !(Maybe Nat) , _ppRequireNumbers :: !(Maybe Bool) , _ppPasswordReusePrevention :: !(Maybe Nat) , _ppRequireLowercaseCharacters :: !(Maybe Bool) , _ppMaxPasswordAge :: !(Maybe Nat) , _ppHardExpiry :: !(Maybe Bool) , _ppRequireSymbols :: !(Maybe Bool) , _ppRequireUppercaseCharacters :: !(Maybe Bool) , _ppAllowUsersToChangePassword :: !(Maybe Bool) } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'PasswordPolicy' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ppExpirePasswords' -- -- * 'ppMinimumPasswordLength' -- -- * 'ppRequireNumbers' -- -- * 'ppPasswordReusePrevention' -- -- * 'ppRequireLowercaseCharacters' -- -- * 'ppMaxPasswordAge' -- -- * 'ppHardExpiry' -- -- * 'ppRequireSymbols' -- -- * 'ppRequireUppercaseCharacters' -- -- * 'ppAllowUsersToChangePassword' passwordPolicy :: PasswordPolicy passwordPolicy = PasswordPolicy' { _ppExpirePasswords = Nothing , _ppMinimumPasswordLength = Nothing , _ppRequireNumbers = Nothing , _ppPasswordReusePrevention = Nothing , _ppRequireLowercaseCharacters = Nothing , _ppMaxPasswordAge = Nothing , _ppHardExpiry = Nothing , _ppRequireSymbols = Nothing , _ppRequireUppercaseCharacters = Nothing , _ppAllowUsersToChangePassword = Nothing } -- | Specifies whether IAM users are required to change their password after -- a specified number of days. ppExpirePasswords :: Lens' PasswordPolicy (Maybe Bool) ppExpirePasswords = lens _ppExpirePasswords (\ s a -> s{_ppExpirePasswords = a}); -- | Minimum length to require for IAM user passwords. ppMinimumPasswordLength :: Lens' PasswordPolicy (Maybe Natural) ppMinimumPasswordLength = lens _ppMinimumPasswordLength (\ s a -> s{_ppMinimumPasswordLength = a}) . mapping _Nat; -- | Specifies whether to require numbers for IAM user passwords. ppRequireNumbers :: Lens' PasswordPolicy (Maybe Bool) ppRequireNumbers = lens _ppRequireNumbers (\ s a -> s{_ppRequireNumbers = a}); -- | Specifies the number of previous passwords that IAM users are prevented -- from reusing. ppPasswordReusePrevention :: Lens' PasswordPolicy (Maybe Natural) ppPasswordReusePrevention = lens _ppPasswordReusePrevention (\ s a -> s{_ppPasswordReusePrevention = a}) . mapping _Nat; -- | Specifies whether to require lowercase characters for IAM user -- passwords. ppRequireLowercaseCharacters :: Lens' PasswordPolicy (Maybe Bool) ppRequireLowercaseCharacters = lens _ppRequireLowercaseCharacters (\ s a -> s{_ppRequireLowercaseCharacters = a}); -- | The number of days that an IAM user password is valid. ppMaxPasswordAge :: Lens' PasswordPolicy (Maybe Natural) ppMaxPasswordAge = lens _ppMaxPasswordAge (\ s a -> s{_ppMaxPasswordAge = a}) . mapping _Nat; -- | Specifies whether IAM users are prevented from setting a new password -- after their password has expired. ppHardExpiry :: Lens' PasswordPolicy (Maybe Bool) ppHardExpiry = lens _ppHardExpiry (\ s a -> s{_ppHardExpiry = a}); -- | Specifies whether to require symbols for IAM user passwords. ppRequireSymbols :: Lens' PasswordPolicy (Maybe Bool) ppRequireSymbols = lens _ppRequireSymbols (\ s a -> s{_ppRequireSymbols = a}); -- | Specifies whether to require uppercase characters for IAM user -- passwords. ppRequireUppercaseCharacters :: Lens' PasswordPolicy (Maybe Bool) ppRequireUppercaseCharacters = lens _ppRequireUppercaseCharacters (\ s a -> s{_ppRequireUppercaseCharacters = a}); -- | Specifies whether IAM users are allowed to change their own password. ppAllowUsersToChangePassword :: Lens' PasswordPolicy (Maybe Bool) ppAllowUsersToChangePassword = lens _ppAllowUsersToChangePassword (\ s a -> s{_ppAllowUsersToChangePassword = a}); instance FromXML PasswordPolicy where parseXML x = PasswordPolicy' <$> (x .@? "ExpirePasswords") <*> (x .@? "MinimumPasswordLength") <*> (x .@? "RequireNumbers") <*> (x .@? "PasswordReusePrevention") <*> (x .@? "RequireLowercaseCharacters") <*> (x .@? "MaxPasswordAge") <*> (x .@? "HardExpiry") <*> (x .@? "RequireSymbols") <*> (x .@? "RequireUppercaseCharacters") <*> (x .@? "AllowUsersToChangePassword") -- | Contains information about a managed policy. -- -- This data type is used as a response element in the CreatePolicy, -- GetPolicy, and ListPolicies actions. -- -- For more information about managed policies, refer to -- <http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html Managed Policies and Inline Policies> -- in the /Using IAM/ guide. -- -- /See:/ 'policy' smart constructor. data Policy = Policy' { _pPolicyName :: !(Maybe Text) , _pARN :: !(Maybe Text) , _pUpdateDate :: !(Maybe ISO8601) , _pPolicyId :: !(Maybe Text) , _pPath :: !(Maybe Text) , _pCreateDate :: !(Maybe ISO8601) , _pIsAttachable :: !(Maybe Bool) , _pDefaultVersionId :: !(Maybe Text) , _pAttachmentCount :: !(Maybe Int) , _pDescription :: !(Maybe Text) } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'Policy' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pPolicyName' -- -- * 'pARN' -- -- * 'pUpdateDate' -- -- * 'pPolicyId' -- -- * 'pPath' -- -- * 'pCreateDate' -- -- * 'pIsAttachable' -- -- * 'pDefaultVersionId' -- -- * 'pAttachmentCount' -- -- * 'pDescription' policy :: Policy policy = Policy' { _pPolicyName = Nothing , _pARN = Nothing , _pUpdateDate = Nothing , _pPolicyId = Nothing , _pPath = Nothing , _pCreateDate = Nothing , _pIsAttachable = Nothing , _pDefaultVersionId = Nothing , _pAttachmentCount = Nothing , _pDescription = Nothing } -- | The friendly name (not ARN) identifying the policy. pPolicyName :: Lens' Policy (Maybe Text) pPolicyName = lens _pPolicyName (\ s a -> s{_pPolicyName = a}); -- | Undocumented member. pARN :: Lens' Policy (Maybe Text) pARN = lens _pARN (\ s a -> s{_pARN = a}); -- | The date and time, in -- <http://www.iso.org/iso/iso8601 ISO 8601 date-time format>, when the -- policy was last updated. -- -- When a policy has only one version, this field contains the date and -- time when the policy was created. When a policy has more than one -- version, this field contains the date and time when the most recent -- policy version was created. pUpdateDate :: Lens' Policy (Maybe UTCTime) pUpdateDate = lens _pUpdateDate (\ s a -> s{_pUpdateDate = a}) . mapping _Time; -- | The stable and unique string identifying the policy. -- -- For more information about IDs, see -- <http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html IAM Identifiers> -- in the /Using IAM/ guide. pPolicyId :: Lens' Policy (Maybe Text) pPolicyId = lens _pPolicyId (\ s a -> s{_pPolicyId = a}); -- | The path to the policy. -- -- For more information about paths, see -- <http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html IAM Identifiers> -- in the /Using IAM/ guide. pPath :: Lens' Policy (Maybe Text) pPath = lens _pPath (\ s a -> s{_pPath = a}); -- | The date and time, in -- <http://www.iso.org/iso/iso8601 ISO 8601 date-time format>, when the -- policy was created. pCreateDate :: Lens' Policy (Maybe UTCTime) pCreateDate = lens _pCreateDate (\ s a -> s{_pCreateDate = a}) . mapping _Time; -- | Specifies whether the policy can be attached to an IAM user, group, or -- role. pIsAttachable :: Lens' Policy (Maybe Bool) pIsAttachable = lens _pIsAttachable (\ s a -> s{_pIsAttachable = a}); -- | The identifier for the version of the policy that is set as the default -- version. pDefaultVersionId :: Lens' Policy (Maybe Text) pDefaultVersionId = lens _pDefaultVersionId (\ s a -> s{_pDefaultVersionId = a}); -- | The number of entities (users, groups, and roles) that the policy is -- attached to. pAttachmentCount :: Lens' Policy (Maybe Int) pAttachmentCount = lens _pAttachmentCount (\ s a -> s{_pAttachmentCount = a}); -- | A friendly description of the policy. -- -- This element is included in the response to the GetPolicy operation. It -- is not included in the response to the ListPolicies operation. pDescription :: Lens' Policy (Maybe Text) pDescription = lens _pDescription (\ s a -> s{_pDescription = a}); instance FromXML Policy where parseXML x = Policy' <$> (x .@? "PolicyName") <*> (x .@? "Arn") <*> (x .@? "UpdateDate") <*> (x .@? "PolicyId") <*> (x .@? "Path") <*> (x .@? "CreateDate") <*> (x .@? "IsAttachable") <*> (x .@? "DefaultVersionId") <*> (x .@? "AttachmentCount") <*> (x .@? "Description") -- | Contains information about an IAM policy, including the policy document. -- -- This data type is used as a response element in the -- GetAccountAuthorizationDetails action. -- -- /See:/ 'policyDetail' smart constructor. data PolicyDetail = PolicyDetail' { _pdPolicyDocument :: !(Maybe Text) , _pdPolicyName :: !(Maybe Text) } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'PolicyDetail' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pdPolicyDocument' -- -- * 'pdPolicyName' policyDetail :: PolicyDetail policyDetail = PolicyDetail' { _pdPolicyDocument = Nothing , _pdPolicyName = Nothing } -- | The policy document. pdPolicyDocument :: Lens' PolicyDetail (Maybe Text) pdPolicyDocument = lens _pdPolicyDocument (\ s a -> s{_pdPolicyDocument = a}); -- | The name of the policy. pdPolicyName :: Lens' PolicyDetail (Maybe Text) pdPolicyName = lens _pdPolicyName (\ s a -> s{_pdPolicyName = a}); instance FromXML PolicyDetail where parseXML x = PolicyDetail' <$> (x .@? "PolicyDocument") <*> (x .@? "PolicyName") -- | Contains information about a group that a managed policy is attached to. -- -- This data type is used as a response element in the -- ListEntitiesForPolicy action. -- -- For more information about managed policies, refer to -- <http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html Managed Policies and Inline Policies> -- in the /Using IAM/ guide. -- -- /See:/ 'policyGroup' smart constructor. newtype PolicyGroup = PolicyGroup' { _pgGroupName :: Maybe Text } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'PolicyGroup' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pgGroupName' policyGroup :: PolicyGroup policyGroup = PolicyGroup' { _pgGroupName = Nothing } -- | The name (friendly name, not ARN) identifying the group. pgGroupName :: Lens' PolicyGroup (Maybe Text) pgGroupName = lens _pgGroupName (\ s a -> s{_pgGroupName = a}); instance FromXML PolicyGroup where parseXML x = PolicyGroup' <$> (x .@? "GroupName") -- | Contains information about a role that a managed policy is attached to. -- -- This data type is used as a response element in the -- ListEntitiesForPolicy action. -- -- For more information about managed policies, refer to -- <http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html Managed Policies and Inline Policies> -- in the /Using IAM/ guide. -- -- /See:/ 'policyRole' smart constructor. newtype PolicyRole = PolicyRole' { _prRoleName :: Maybe Text } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'PolicyRole' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'prRoleName' policyRole :: PolicyRole policyRole = PolicyRole' { _prRoleName = Nothing } -- | The name (friendly name, not ARN) identifying the role. prRoleName :: Lens' PolicyRole (Maybe Text) prRoleName = lens _prRoleName (\ s a -> s{_prRoleName = a}); instance FromXML PolicyRole where parseXML x = PolicyRole' <$> (x .@? "RoleName") -- | Contains information about a user that a managed policy is attached to. -- -- This data type is used as a response element in the -- ListEntitiesForPolicy action. -- -- For more information about managed policies, refer to -- <http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html Managed Policies and Inline Policies> -- in the /Using IAM/ guide. -- -- /See:/ 'policyUser' smart constructor. newtype PolicyUser = PolicyUser' { _puUserName :: Maybe Text } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'PolicyUser' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'puUserName' policyUser :: PolicyUser policyUser = PolicyUser' { _puUserName = Nothing } -- | The name (friendly name, not ARN) identifying the user. puUserName :: Lens' PolicyUser (Maybe Text) puUserName = lens _puUserName (\ s a -> s{_puUserName = a}); instance FromXML PolicyUser where parseXML x = PolicyUser' <$> (x .@? "UserName") -- | Contains information about a version of a managed policy. -- -- This data type is used as a response element in the CreatePolicyVersion, -- GetPolicyVersion, ListPolicyVersions, and GetAccountAuthorizationDetails -- actions. -- -- For more information about managed policies, refer to -- <http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html Managed Policies and Inline Policies> -- in the /Using IAM/ guide. -- -- /See:/ 'policyVersion' smart constructor. data PolicyVersion = PolicyVersion' { _pvVersionId :: !(Maybe Text) , _pvCreateDate :: !(Maybe ISO8601) , _pvDocument :: !(Maybe Text) , _pvIsDefaultVersion :: !(Maybe Bool) } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'PolicyVersion' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pvVersionId' -- -- * 'pvCreateDate' -- -- * 'pvDocument' -- -- * 'pvIsDefaultVersion' policyVersion :: PolicyVersion policyVersion = PolicyVersion' { _pvVersionId = Nothing , _pvCreateDate = Nothing , _pvDocument = Nothing , _pvIsDefaultVersion = Nothing } -- | The identifier for the policy version. -- -- Policy version identifiers always begin with 'v' (always lowercase). -- When a policy is created, the first policy version is 'v1'. pvVersionId :: Lens' PolicyVersion (Maybe Text) pvVersionId = lens _pvVersionId (\ s a -> s{_pvVersionId = a}); -- | The date and time, in -- <http://www.iso.org/iso/iso8601 ISO 8601 date-time format>, when the -- policy version was created. pvCreateDate :: Lens' PolicyVersion (Maybe UTCTime) pvCreateDate = lens _pvCreateDate (\ s a -> s{_pvCreateDate = a}) . mapping _Time; -- | The policy document. -- -- The policy document is returned in the response to the GetPolicyVersion -- and GetAccountAuthorizationDetails operations. It is not returned in the -- response to the CreatePolicyVersion or ListPolicyVersions operations. pvDocument :: Lens' PolicyVersion (Maybe Text) pvDocument = lens _pvDocument (\ s a -> s{_pvDocument = a}); -- | Specifies whether the policy version is set as the policy\'s default -- version. pvIsDefaultVersion :: Lens' PolicyVersion (Maybe Bool) pvIsDefaultVersion = lens _pvIsDefaultVersion (\ s a -> s{_pvIsDefaultVersion = a}); instance FromXML PolicyVersion where parseXML x = PolicyVersion' <$> (x .@? "VersionId") <*> (x .@? "CreateDate") <*> (x .@? "Document") <*> (x .@? "IsDefaultVersion") -- | Contains the row and column of a location of a 'Statement' element in a -- policy document. -- -- This data type is used as a member of the 'Statement' type. -- -- /See:/ 'position' smart constructor. data Position = Position' { _pLine :: !(Maybe Int) , _pColumn :: !(Maybe Int) } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'Position' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pLine' -- -- * 'pColumn' position :: Position position = Position' { _pLine = Nothing , _pColumn = Nothing } -- | The line containing the specified position in the document. pLine :: Lens' Position (Maybe Int) pLine = lens _pLine (\ s a -> s{_pLine = a}); -- | The column in the line containing the specified position in the -- document. pColumn :: Lens' Position (Maybe Int) pColumn = lens _pColumn (\ s a -> s{_pColumn = a}); instance FromXML Position where parseXML x = Position' <$> (x .@? "Line") <*> (x .@? "Column") -- | Contains information about an IAM role. -- -- This data type is used as a response element in the following actions: -- -- - CreateRole -- -- - GetRole -- -- - ListRoles -- -- -- /See:/ 'role' smart constructor. data Role = Role' { _rAssumeRolePolicyDocument :: !(Maybe Text) , _rPath :: !Text , _rRoleName :: !Text , _rRoleId :: !Text , _rARN :: !Text , _rCreateDate :: !ISO8601 } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'Role' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'rAssumeRolePolicyDocument' -- -- * 'rPath' -- -- * 'rRoleName' -- -- * 'rRoleId' -- -- * 'rARN' -- -- * 'rCreateDate' role :: Text -- ^ 'rPath' -> Text -- ^ 'rRoleName' -> Text -- ^ 'rRoleId' -> Text -- ^ 'rARN' -> UTCTime -- ^ 'rCreateDate' -> Role role pPath_ pRoleName_ pRoleId_ pARN_ pCreateDate_ = Role' { _rAssumeRolePolicyDocument = Nothing , _rPath = pPath_ , _rRoleName = pRoleName_ , _rRoleId = pRoleId_ , _rARN = pARN_ , _rCreateDate = _Time # pCreateDate_ } -- | The policy that grants an entity permission to assume the role. rAssumeRolePolicyDocument :: Lens' Role (Maybe Text) rAssumeRolePolicyDocument = lens _rAssumeRolePolicyDocument (\ s a -> s{_rAssumeRolePolicyDocument = a}); -- | The path to the role. For more information about paths, see -- <http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html IAM Identifiers> -- in the /Using IAM/ guide. rPath :: Lens' Role Text rPath = lens _rPath (\ s a -> s{_rPath = a}); -- | The friendly name that identifies the role. rRoleName :: Lens' Role Text rRoleName = lens _rRoleName (\ s a -> s{_rRoleName = a}); -- | The stable and unique string identifying the role. For more information -- about IDs, see -- <http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html IAM Identifiers> -- in the /Using IAM/ guide. rRoleId :: Lens' Role Text rRoleId = lens _rRoleId (\ s a -> s{_rRoleId = a}); -- | The Amazon Resource Name (ARN) specifying the role. For more information -- about ARNs and how to use them in policies, see -- <http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html IAM Identifiers> -- in the /Using IAM/ guide. rARN :: Lens' Role Text rARN = lens _rARN (\ s a -> s{_rARN = a}); -- | The date and time, in -- <http://www.iso.org/iso/iso8601 ISO 8601 date-time format>, when the -- role was created. rCreateDate :: Lens' Role UTCTime rCreateDate = lens _rCreateDate (\ s a -> s{_rCreateDate = a}) . _Time; instance FromXML Role where parseXML x = Role' <$> (x .@? "AssumeRolePolicyDocument") <*> (x .@ "Path") <*> (x .@ "RoleName") <*> (x .@ "RoleId") <*> (x .@ "Arn") <*> (x .@ "CreateDate") -- | Contains information about an IAM role, including all of the role\'s -- policies. -- -- This data type is used as a response element in the -- GetAccountAuthorizationDetails action. -- -- /See:/ 'roleDetail' smart constructor. data RoleDetail = RoleDetail' { _rdAssumeRolePolicyDocument :: !(Maybe Text) , _rdARN :: !(Maybe Text) , _rdPath :: !(Maybe Text) , _rdInstanceProfileList :: !(Maybe [InstanceProfile]) , _rdCreateDate :: !(Maybe ISO8601) , _rdRoleName :: !(Maybe Text) , _rdRoleId :: !(Maybe Text) , _rdRolePolicyList :: !(Maybe [PolicyDetail]) , _rdAttachedManagedPolicies :: !(Maybe [AttachedPolicy]) } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'RoleDetail' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'rdAssumeRolePolicyDocument' -- -- * 'rdARN' -- -- * 'rdPath' -- -- * 'rdInstanceProfileList' -- -- * 'rdCreateDate' -- -- * 'rdRoleName' -- -- * 'rdRoleId' -- -- * 'rdRolePolicyList' -- -- * 'rdAttachedManagedPolicies' roleDetail :: RoleDetail roleDetail = RoleDetail' { _rdAssumeRolePolicyDocument = Nothing , _rdARN = Nothing , _rdPath = Nothing , _rdInstanceProfileList = Nothing , _rdCreateDate = Nothing , _rdRoleName = Nothing , _rdRoleId = Nothing , _rdRolePolicyList = Nothing , _rdAttachedManagedPolicies = Nothing } -- | The trust policy that grants permission to assume the role. rdAssumeRolePolicyDocument :: Lens' RoleDetail (Maybe Text) rdAssumeRolePolicyDocument = lens _rdAssumeRolePolicyDocument (\ s a -> s{_rdAssumeRolePolicyDocument = a}); -- | Undocumented member. rdARN :: Lens' RoleDetail (Maybe Text) rdARN = lens _rdARN (\ s a -> s{_rdARN = a}); -- | The path to the role. For more information about paths, see -- <http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html IAM Identifiers> -- in the /Using IAM/ guide. rdPath :: Lens' RoleDetail (Maybe Text) rdPath = lens _rdPath (\ s a -> s{_rdPath = a}); -- | Undocumented member. rdInstanceProfileList :: Lens' RoleDetail [InstanceProfile] rdInstanceProfileList = lens _rdInstanceProfileList (\ s a -> s{_rdInstanceProfileList = a}) . _Default . _Coerce; -- | The date and time, in -- <http://www.iso.org/iso/iso8601 ISO 8601 date-time format>, when the -- role was created. rdCreateDate :: Lens' RoleDetail (Maybe UTCTime) rdCreateDate = lens _rdCreateDate (\ s a -> s{_rdCreateDate = a}) . mapping _Time; -- | The friendly name that identifies the role. rdRoleName :: Lens' RoleDetail (Maybe Text) rdRoleName = lens _rdRoleName (\ s a -> s{_rdRoleName = a}); -- | The stable and unique string identifying the role. For more information -- about IDs, see -- <http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html IAM Identifiers> -- in the /Using IAM/ guide. rdRoleId :: Lens' RoleDetail (Maybe Text) rdRoleId = lens _rdRoleId (\ s a -> s{_rdRoleId = a}); -- | A list of inline policies embedded in the role. These policies are the -- role\'s access (permissions) policies. rdRolePolicyList :: Lens' RoleDetail [PolicyDetail] rdRolePolicyList = lens _rdRolePolicyList (\ s a -> s{_rdRolePolicyList = a}) . _Default . _Coerce; -- | A list of managed policies attached to the role. These policies are the -- role\'s access (permissions) policies. rdAttachedManagedPolicies :: Lens' RoleDetail [AttachedPolicy] rdAttachedManagedPolicies = lens _rdAttachedManagedPolicies (\ s a -> s{_rdAttachedManagedPolicies = a}) . _Default . _Coerce; instance FromXML RoleDetail where parseXML x = RoleDetail' <$> (x .@? "AssumeRolePolicyDocument") <*> (x .@? "Arn") <*> (x .@? "Path") <*> (x .@? "InstanceProfileList" .!@ mempty >>= may (parseXMLList "member")) <*> (x .@? "CreateDate") <*> (x .@? "RoleName") <*> (x .@? "RoleId") <*> (x .@? "RolePolicyList" .!@ mempty >>= may (parseXMLList "member")) <*> (x .@? "AttachedManagedPolicies" .!@ mempty >>= may (parseXMLList "member")) -- | Contains the list of SAML providers for this account. -- -- /See:/ 'sAMLProviderListEntry' smart constructor. data SAMLProviderListEntry = SAMLProviderListEntry' { _samlpleARN :: !(Maybe Text) , _samlpleCreateDate :: !(Maybe ISO8601) , _samlpleValidUntil :: !(Maybe ISO8601) } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'SAMLProviderListEntry' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'samlpleARN' -- -- * 'samlpleCreateDate' -- -- * 'samlpleValidUntil' sAMLProviderListEntry :: SAMLProviderListEntry sAMLProviderListEntry = SAMLProviderListEntry' { _samlpleARN = Nothing , _samlpleCreateDate = Nothing , _samlpleValidUntil = Nothing } -- | The Amazon Resource Name (ARN) of the SAML provider. samlpleARN :: Lens' SAMLProviderListEntry (Maybe Text) samlpleARN = lens _samlpleARN (\ s a -> s{_samlpleARN = a}); -- | The date and time when the SAML provider was created. samlpleCreateDate :: Lens' SAMLProviderListEntry (Maybe UTCTime) samlpleCreateDate = lens _samlpleCreateDate (\ s a -> s{_samlpleCreateDate = a}) . mapping _Time; -- | The expiration date and time for the SAML provider. samlpleValidUntil :: Lens' SAMLProviderListEntry (Maybe UTCTime) samlpleValidUntil = lens _samlpleValidUntil (\ s a -> s{_samlpleValidUntil = a}) . mapping _Time; instance FromXML SAMLProviderListEntry where parseXML x = SAMLProviderListEntry' <$> (x .@? "Arn") <*> (x .@? "CreateDate") <*> (x .@? "ValidUntil") -- | Contains information about an SSH public key. -- -- This data type is used as a response element in the GetSSHPublicKey and -- UploadSSHPublicKey actions. -- -- /See:/ 'sshPublicKey' smart constructor. data SSHPublicKey = SSHPublicKey' { _spkUploadDate :: !(Maybe ISO8601) , _spkUserName :: !Text , _spkSSHPublicKeyId :: !Text , _spkFingerprint :: !Text , _spkSSHPublicKeyBody :: !Text , _spkStatus :: !StatusType } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'SSHPublicKey' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'spkUploadDate' -- -- * 'spkUserName' -- -- * 'spkSSHPublicKeyId' -- -- * 'spkFingerprint' -- -- * 'spkSSHPublicKeyBody' -- -- * 'spkStatus' sshPublicKey :: Text -- ^ 'spkUserName' -> Text -- ^ 'spkSSHPublicKeyId' -> Text -- ^ 'spkFingerprint' -> Text -- ^ 'spkSSHPublicKeyBody' -> StatusType -- ^ 'spkStatus' -> SSHPublicKey sshPublicKey pUserName_ pSSHPublicKeyId_ pFingerprint_ pSSHPublicKeyBody_ pStatus_ = SSHPublicKey' { _spkUploadDate = Nothing , _spkUserName = pUserName_ , _spkSSHPublicKeyId = pSSHPublicKeyId_ , _spkFingerprint = pFingerprint_ , _spkSSHPublicKeyBody = pSSHPublicKeyBody_ , _spkStatus = pStatus_ } -- | The date and time, in -- <http://www.iso.org/iso/iso8601 ISO 8601 date-time format>, when the SSH -- public key was uploaded. spkUploadDate :: Lens' SSHPublicKey (Maybe UTCTime) spkUploadDate = lens _spkUploadDate (\ s a -> s{_spkUploadDate = a}) . mapping _Time; -- | The name of the IAM user associated with the SSH public key. spkUserName :: Lens' SSHPublicKey Text spkUserName = lens _spkUserName (\ s a -> s{_spkUserName = a}); -- | The unique identifier for the SSH public key. spkSSHPublicKeyId :: Lens' SSHPublicKey Text spkSSHPublicKeyId = lens _spkSSHPublicKeyId (\ s a -> s{_spkSSHPublicKeyId = a}); -- | The MD5 message digest of the SSH public key. spkFingerprint :: Lens' SSHPublicKey Text spkFingerprint = lens _spkFingerprint (\ s a -> s{_spkFingerprint = a}); -- | The SSH public key. spkSSHPublicKeyBody :: Lens' SSHPublicKey Text spkSSHPublicKeyBody = lens _spkSSHPublicKeyBody (\ s a -> s{_spkSSHPublicKeyBody = a}); -- | The status of the SSH public key. 'Active' means the key can be used for -- authentication with an AWS CodeCommit repository. 'Inactive' means the -- key cannot be used. spkStatus :: Lens' SSHPublicKey StatusType spkStatus = lens _spkStatus (\ s a -> s{_spkStatus = a}); instance FromXML SSHPublicKey where parseXML x = SSHPublicKey' <$> (x .@? "UploadDate") <*> (x .@ "UserName") <*> (x .@ "SSHPublicKeyId") <*> (x .@ "Fingerprint") <*> (x .@ "SSHPublicKeyBody") <*> (x .@ "Status") -- | Contains information about an SSH public key, without the key\'s body or -- fingerprint. -- -- This data type is used as a response element in the ListSSHPublicKeys -- action. -- -- /See:/ 'sshPublicKeyMetadata' smart constructor. data SSHPublicKeyMetadata = SSHPublicKeyMetadata' { _spkmUserName :: !Text , _spkmSSHPublicKeyId :: !Text , _spkmStatus :: !StatusType , _spkmUploadDate :: !ISO8601 } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'SSHPublicKeyMetadata' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'spkmUserName' -- -- * 'spkmSSHPublicKeyId' -- -- * 'spkmStatus' -- -- * 'spkmUploadDate' sshPublicKeyMetadata :: Text -- ^ 'spkmUserName' -> Text -- ^ 'spkmSSHPublicKeyId' -> StatusType -- ^ 'spkmStatus' -> UTCTime -- ^ 'spkmUploadDate' -> SSHPublicKeyMetadata sshPublicKeyMetadata pUserName_ pSSHPublicKeyId_ pStatus_ pUploadDate_ = SSHPublicKeyMetadata' { _spkmUserName = pUserName_ , _spkmSSHPublicKeyId = pSSHPublicKeyId_ , _spkmStatus = pStatus_ , _spkmUploadDate = _Time # pUploadDate_ } -- | The name of the IAM user associated with the SSH public key. spkmUserName :: Lens' SSHPublicKeyMetadata Text spkmUserName = lens _spkmUserName (\ s a -> s{_spkmUserName = a}); -- | The unique identifier for the SSH public key. spkmSSHPublicKeyId :: Lens' SSHPublicKeyMetadata Text spkmSSHPublicKeyId = lens _spkmSSHPublicKeyId (\ s a -> s{_spkmSSHPublicKeyId = a}); -- | The status of the SSH public key. 'Active' means the key can be used for -- authentication with an AWS CodeCommit repository. 'Inactive' means the -- key cannot be used. spkmStatus :: Lens' SSHPublicKeyMetadata StatusType spkmStatus = lens _spkmStatus (\ s a -> s{_spkmStatus = a}); -- | The date and time, in -- <http://www.iso.org/iso/iso8601 ISO 8601 date-time format>, when the SSH -- public key was uploaded. spkmUploadDate :: Lens' SSHPublicKeyMetadata UTCTime spkmUploadDate = lens _spkmUploadDate (\ s a -> s{_spkmUploadDate = a}) . _Time; instance FromXML SSHPublicKeyMetadata where parseXML x = SSHPublicKeyMetadata' <$> (x .@ "UserName") <*> (x .@ "SSHPublicKeyId") <*> (x .@ "Status") <*> (x .@ "UploadDate") -- | Contains information about a server certificate. -- -- This data type is used as a response element in the GetServerCertificate -- action. -- -- /See:/ 'serverCertificate' smart constructor. data ServerCertificate = ServerCertificate' { _sCertificateChain :: !(Maybe Text) , _sServerCertificateMetadata :: !ServerCertificateMetadata , _sCertificateBody :: !Text } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'ServerCertificate' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'sCertificateChain' -- -- * 'sServerCertificateMetadata' -- -- * 'sCertificateBody' serverCertificate :: ServerCertificateMetadata -- ^ 'sServerCertificateMetadata' -> Text -- ^ 'sCertificateBody' -> ServerCertificate serverCertificate pServerCertificateMetadata_ pCertificateBody_ = ServerCertificate' { _sCertificateChain = Nothing , _sServerCertificateMetadata = pServerCertificateMetadata_ , _sCertificateBody = pCertificateBody_ } -- | The contents of the public key certificate chain. sCertificateChain :: Lens' ServerCertificate (Maybe Text) sCertificateChain = lens _sCertificateChain (\ s a -> s{_sCertificateChain = a}); -- | The meta information of the server certificate, such as its name, path, -- ID, and ARN. sServerCertificateMetadata :: Lens' ServerCertificate ServerCertificateMetadata sServerCertificateMetadata = lens _sServerCertificateMetadata (\ s a -> s{_sServerCertificateMetadata = a}); -- | The contents of the public key certificate. sCertificateBody :: Lens' ServerCertificate Text sCertificateBody = lens _sCertificateBody (\ s a -> s{_sCertificateBody = a}); instance FromXML ServerCertificate where parseXML x = ServerCertificate' <$> (x .@? "CertificateChain") <*> (x .@ "ServerCertificateMetadata") <*> (x .@ "CertificateBody") -- | Contains information about a server certificate without its certificate -- body, certificate chain, and private key. -- -- This data type is used as a response element in the -- UploadServerCertificate and ListServerCertificates actions. -- -- /See:/ 'serverCertificateMetadata' smart constructor. data ServerCertificateMetadata = ServerCertificateMetadata' { _scmUploadDate :: !(Maybe ISO8601) , _scmExpiration :: !(Maybe ISO8601) , _scmPath :: !Text , _scmServerCertificateName :: !Text , _scmServerCertificateId :: !Text , _scmARN :: !Text } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'ServerCertificateMetadata' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'scmUploadDate' -- -- * 'scmExpiration' -- -- * 'scmPath' -- -- * 'scmServerCertificateName' -- -- * 'scmServerCertificateId' -- -- * 'scmARN' serverCertificateMetadata :: Text -- ^ 'scmPath' -> Text -- ^ 'scmServerCertificateName' -> Text -- ^ 'scmServerCertificateId' -> Text -- ^ 'scmARN' -> ServerCertificateMetadata serverCertificateMetadata pPath_ pServerCertificateName_ pServerCertificateId_ pARN_ = ServerCertificateMetadata' { _scmUploadDate = Nothing , _scmExpiration = Nothing , _scmPath = pPath_ , _scmServerCertificateName = pServerCertificateName_ , _scmServerCertificateId = pServerCertificateId_ , _scmARN = pARN_ } -- | The date when the server certificate was uploaded. scmUploadDate :: Lens' ServerCertificateMetadata (Maybe UTCTime) scmUploadDate = lens _scmUploadDate (\ s a -> s{_scmUploadDate = a}) . mapping _Time; -- | The date on which the certificate is set to expire. scmExpiration :: Lens' ServerCertificateMetadata (Maybe UTCTime) scmExpiration = lens _scmExpiration (\ s a -> s{_scmExpiration = a}) . mapping _Time; -- | The path to the server certificate. For more information about paths, -- see -- <http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html IAM Identifiers> -- in the /Using IAM/ guide. scmPath :: Lens' ServerCertificateMetadata Text scmPath = lens _scmPath (\ s a -> s{_scmPath = a}); -- | The name that identifies the server certificate. scmServerCertificateName :: Lens' ServerCertificateMetadata Text scmServerCertificateName = lens _scmServerCertificateName (\ s a -> s{_scmServerCertificateName = a}); -- | The stable and unique string identifying the server certificate. For -- more information about IDs, see -- <http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html IAM Identifiers> -- in the /Using IAM/ guide. scmServerCertificateId :: Lens' ServerCertificateMetadata Text scmServerCertificateId = lens _scmServerCertificateId (\ s a -> s{_scmServerCertificateId = a}); -- | The Amazon Resource Name (ARN) specifying the server certificate. For -- more information about ARNs and how to use them in policies, see -- <http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html IAM Identifiers> -- in the /Using IAM/ guide. scmARN :: Lens' ServerCertificateMetadata Text scmARN = lens _scmARN (\ s a -> s{_scmARN = a}); instance FromXML ServerCertificateMetadata where parseXML x = ServerCertificateMetadata' <$> (x .@? "UploadDate") <*> (x .@? "Expiration") <*> (x .@ "Path") <*> (x .@ "ServerCertificateName") <*> (x .@ "ServerCertificateId") <*> (x .@ "Arn") -- | Contains information about an X.509 signing certificate. -- -- This data type is used as a response element in the -- UploadSigningCertificate and ListSigningCertificates actions. -- -- /See:/ 'signingCertificate' smart constructor. data SigningCertificate = SigningCertificate' { _scUploadDate :: !(Maybe ISO8601) , _scUserName :: !Text , _scCertificateId :: !Text , _scCertificateBody :: !Text , _scStatus :: !StatusType } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'SigningCertificate' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'scUploadDate' -- -- * 'scUserName' -- -- * 'scCertificateId' -- -- * 'scCertificateBody' -- -- * 'scStatus' signingCertificate :: Text -- ^ 'scUserName' -> Text -- ^ 'scCertificateId' -> Text -- ^ 'scCertificateBody' -> StatusType -- ^ 'scStatus' -> SigningCertificate signingCertificate pUserName_ pCertificateId_ pCertificateBody_ pStatus_ = SigningCertificate' { _scUploadDate = Nothing , _scUserName = pUserName_ , _scCertificateId = pCertificateId_ , _scCertificateBody = pCertificateBody_ , _scStatus = pStatus_ } -- | The date when the signing certificate was uploaded. scUploadDate :: Lens' SigningCertificate (Maybe UTCTime) scUploadDate = lens _scUploadDate (\ s a -> s{_scUploadDate = a}) . mapping _Time; -- | The name of the user the signing certificate is associated with. scUserName :: Lens' SigningCertificate Text scUserName = lens _scUserName (\ s a -> s{_scUserName = a}); -- | The ID for the signing certificate. scCertificateId :: Lens' SigningCertificate Text scCertificateId = lens _scCertificateId (\ s a -> s{_scCertificateId = a}); -- | The contents of the signing certificate. scCertificateBody :: Lens' SigningCertificate Text scCertificateBody = lens _scCertificateBody (\ s a -> s{_scCertificateBody = a}); -- | The status of the signing certificate. 'Active' means the key is valid -- for API calls, while 'Inactive' means it is not. scStatus :: Lens' SigningCertificate StatusType scStatus = lens _scStatus (\ s a -> s{_scStatus = a}); instance FromXML SigningCertificate where parseXML x = SigningCertificate' <$> (x .@? "UploadDate") <*> (x .@ "UserName") <*> (x .@ "CertificateId") <*> (x .@ "CertificateBody") <*> (x .@ "Status") -- | Contains the response to a successful SimulatePrincipalPolicy or -- SimulateCustomPolicy request. -- -- /See:/ 'simulatePolicyResponse' smart constructor. data SimulatePolicyResponse = SimulatePolicyResponse' { _spEvaluationResults :: !(Maybe [EvaluationResult]) , _spMarker :: !(Maybe Text) , _spIsTruncated :: !(Maybe Bool) } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'SimulatePolicyResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'spEvaluationResults' -- -- * 'spMarker' -- -- * 'spIsTruncated' simulatePolicyResponse :: SimulatePolicyResponse simulatePolicyResponse = SimulatePolicyResponse' { _spEvaluationResults = Nothing , _spMarker = Nothing , _spIsTruncated = Nothing } -- | The results of the simulation. spEvaluationResults :: Lens' SimulatePolicyResponse [EvaluationResult] spEvaluationResults = lens _spEvaluationResults (\ s a -> s{_spEvaluationResults = a}) . _Default . _Coerce; -- | When 'IsTruncated' is 'true', this element is present and contains the -- value to use for the 'Marker' parameter in a subsequent pagination -- request. spMarker :: Lens' SimulatePolicyResponse (Maybe Text) spMarker = lens _spMarker (\ s a -> s{_spMarker = a}); -- | A flag that indicates whether there are more items to return. If your -- results were truncated, you can make a subsequent pagination request -- using the 'Marker' request parameter to retrieve more items. Note that -- IAM might return fewer than the 'MaxItems' number of results even when -- there are more results available. We recommend that you check -- 'IsTruncated' after every call to ensure that you receive all of your -- results. spIsTruncated :: Lens' SimulatePolicyResponse (Maybe Bool) spIsTruncated = lens _spIsTruncated (\ s a -> s{_spIsTruncated = a}); instance FromXML SimulatePolicyResponse where parseXML x = SimulatePolicyResponse' <$> (x .@? "EvaluationResults" .!@ mempty >>= may (parseXMLList "member")) <*> (x .@? "Marker") <*> (x .@? "IsTruncated") -- | Contains a reference to a 'Statement' element in a policy document that -- determines the result of the simulation. -- -- This data type is used by the 'MatchedStatements' member of the -- 'EvaluationResult' type. -- -- /See:/ 'statement' smart constructor. data Statement = Statement' { _sSourcePolicyType :: !(Maybe PolicySourceType) , _sSourcePolicyId :: !(Maybe Text) , _sEndPosition :: !(Maybe Position) , _sStartPosition :: !(Maybe Position) } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'Statement' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'sSourcePolicyType' -- -- * 'sSourcePolicyId' -- -- * 'sEndPosition' -- -- * 'sStartPosition' statement :: Statement statement = Statement' { _sSourcePolicyType = Nothing , _sSourcePolicyId = Nothing , _sEndPosition = Nothing , _sStartPosition = Nothing } -- | The type of the policy. sSourcePolicyType :: Lens' Statement (Maybe PolicySourceType) sSourcePolicyType = lens _sSourcePolicyType (\ s a -> s{_sSourcePolicyType = a}); -- | The identifier of the policy that was provided as an input. sSourcePolicyId :: Lens' Statement (Maybe Text) sSourcePolicyId = lens _sSourcePolicyId (\ s a -> s{_sSourcePolicyId = a}); -- | The row and column of the end of a 'Statement' in an IAM policy. sEndPosition :: Lens' Statement (Maybe Position) sEndPosition = lens _sEndPosition (\ s a -> s{_sEndPosition = a}); -- | The row and column of the beginning of the 'Statement' in an IAM policy. sStartPosition :: Lens' Statement (Maybe Position) sStartPosition = lens _sStartPosition (\ s a -> s{_sStartPosition = a}); instance FromXML Statement where parseXML x = Statement' <$> (x .@? "SourcePolicyType") <*> (x .@? "SourcePolicyId") <*> (x .@? "EndPosition") <*> (x .@? "StartPosition") -- | Contains information about an IAM user entity. -- -- This data type is used as a response element in the following actions: -- -- - CreateUser -- -- - GetUser -- -- - ListUsers -- -- -- /See:/ 'user' smart constructor. data User = User' { _uPasswordLastUsed :: !(Maybe ISO8601) , _uPath :: !Text , _uUserName :: !Text , _uUserId :: !Text , _uARN :: !Text , _uCreateDate :: !ISO8601 } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'User' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'uPasswordLastUsed' -- -- * 'uPath' -- -- * 'uUserName' -- -- * 'uUserId' -- -- * 'uARN' -- -- * 'uCreateDate' user :: Text -- ^ 'uPath' -> Text -- ^ 'uUserName' -> Text -- ^ 'uUserId' -> Text -- ^ 'uARN' -> UTCTime -- ^ 'uCreateDate' -> User user pPath_ pUserName_ pUserId_ pARN_ pCreateDate_ = User' { _uPasswordLastUsed = Nothing , _uPath = pPath_ , _uUserName = pUserName_ , _uUserId = pUserId_ , _uARN = pARN_ , _uCreateDate = _Time # pCreateDate_ } -- | The date and time, in -- <http://www.iso.org/iso/iso8601 ISO 8601 date-time format>, when the -- user\'s password was last used to sign in to an AWS website. For a list -- of AWS websites that capture a user\'s last sign-in time, see the -- <http://docs.aws.amazon.com/IAM/latest/UserGuide/credential-reports.html Credential Reports> -- topic in the /Using IAM/ guide. If a password is used more than once in -- a five-minute span, only the first use is returned in this field. This -- field is null (not present) when: -- -- - The user does not have a password -- -- - The password exists but has never been used (at least not since IAM -- started tracking this information on October 20th, 2014 -- -- - there is no sign-in data associated with the user -- -- This value is returned only in the GetUser and ListUsers actions. uPasswordLastUsed :: Lens' User (Maybe UTCTime) uPasswordLastUsed = lens _uPasswordLastUsed (\ s a -> s{_uPasswordLastUsed = a}) . mapping _Time; -- | The path to the user. For more information about paths, see -- <http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html IAM Identifiers> -- in the /Using IAM/ guide. uPath :: Lens' User Text uPath = lens _uPath (\ s a -> s{_uPath = a}); -- | The friendly name identifying the user. uUserName :: Lens' User Text uUserName = lens _uUserName (\ s a -> s{_uUserName = a}); -- | The stable and unique string identifying the user. For more information -- about IDs, see -- <http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html IAM Identifiers> -- in the /Using IAM/ guide. uUserId :: Lens' User Text uUserId = lens _uUserId (\ s a -> s{_uUserId = a}); -- | The Amazon Resource Name (ARN) that identifies the user. For more -- information about ARNs and how to use ARNs in policies, see -- <http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html IAM Identifiers> -- in the /Using IAM/ guide. uARN :: Lens' User Text uARN = lens _uARN (\ s a -> s{_uARN = a}); -- | The date and time, in -- <http://www.iso.org/iso/iso8601 ISO 8601 date-time format>, when the -- user was created. uCreateDate :: Lens' User UTCTime uCreateDate = lens _uCreateDate (\ s a -> s{_uCreateDate = a}) . _Time; instance FromXML User where parseXML x = User' <$> (x .@? "PasswordLastUsed") <*> (x .@ "Path") <*> (x .@ "UserName") <*> (x .@ "UserId") <*> (x .@ "Arn") <*> (x .@ "CreateDate") -- | Contains information about an IAM user, including all the user\'s -- policies and all the IAM groups the user is in. -- -- This data type is used as a response element in the -- GetAccountAuthorizationDetails action. -- -- /See:/ 'userDetail' smart constructor. data UserDetail = UserDetail' { _udGroupList :: !(Maybe [Text]) , _udARN :: !(Maybe Text) , _udPath :: !(Maybe Text) , _udCreateDate :: !(Maybe ISO8601) , _udUserName :: !(Maybe Text) , _udUserId :: !(Maybe Text) , _udUserPolicyList :: !(Maybe [PolicyDetail]) , _udAttachedManagedPolicies :: !(Maybe [AttachedPolicy]) } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'UserDetail' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'udGroupList' -- -- * 'udARN' -- -- * 'udPath' -- -- * 'udCreateDate' -- -- * 'udUserName' -- -- * 'udUserId' -- -- * 'udUserPolicyList' -- -- * 'udAttachedManagedPolicies' userDetail :: UserDetail userDetail = UserDetail' { _udGroupList = Nothing , _udARN = Nothing , _udPath = Nothing , _udCreateDate = Nothing , _udUserName = Nothing , _udUserId = Nothing , _udUserPolicyList = Nothing , _udAttachedManagedPolicies = Nothing } -- | A list of IAM groups that the user is in. udGroupList :: Lens' UserDetail [Text] udGroupList = lens _udGroupList (\ s a -> s{_udGroupList = a}) . _Default . _Coerce; -- | Undocumented member. udARN :: Lens' UserDetail (Maybe Text) udARN = lens _udARN (\ s a -> s{_udARN = a}); -- | The path to the user. For more information about paths, see -- <http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html IAM Identifiers> -- in the /Using IAM/ guide. udPath :: Lens' UserDetail (Maybe Text) udPath = lens _udPath (\ s a -> s{_udPath = a}); -- | The date and time, in -- <http://www.iso.org/iso/iso8601 ISO 8601 date-time format>, when the -- user was created. udCreateDate :: Lens' UserDetail (Maybe UTCTime) udCreateDate = lens _udCreateDate (\ s a -> s{_udCreateDate = a}) . mapping _Time; -- | The friendly name identifying the user. udUserName :: Lens' UserDetail (Maybe Text) udUserName = lens _udUserName (\ s a -> s{_udUserName = a}); -- | The stable and unique string identifying the user. For more information -- about IDs, see -- <http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_Identifiers.html IAM Identifiers> -- in the /Using IAM/ guide. udUserId :: Lens' UserDetail (Maybe Text) udUserId = lens _udUserId (\ s a -> s{_udUserId = a}); -- | A list of the inline policies embedded in the user. udUserPolicyList :: Lens' UserDetail [PolicyDetail] udUserPolicyList = lens _udUserPolicyList (\ s a -> s{_udUserPolicyList = a}) . _Default . _Coerce; -- | A list of the managed policies attached to the user. udAttachedManagedPolicies :: Lens' UserDetail [AttachedPolicy] udAttachedManagedPolicies = lens _udAttachedManagedPolicies (\ s a -> s{_udAttachedManagedPolicies = a}) . _Default . _Coerce; instance FromXML UserDetail where parseXML x = UserDetail' <$> (x .@? "GroupList" .!@ mempty >>= may (parseXMLList "member")) <*> (x .@? "Arn") <*> (x .@? "Path") <*> (x .@? "CreateDate") <*> (x .@? "UserName") <*> (x .@? "UserId") <*> (x .@? "UserPolicyList" .!@ mempty >>= may (parseXMLList "member")) <*> (x .@? "AttachedManagedPolicies" .!@ mempty >>= may (parseXMLList "member")) -- | Contains information about a virtual MFA device. -- -- /See:/ 'virtualMFADevice' smart constructor. data VirtualMFADevice = VirtualMFADevice' { _vmdQRCodePNG :: !(Maybe (Sensitive Base64)) , _vmdBase32StringSeed :: !(Maybe (Sensitive Base64)) , _vmdUser :: !(Maybe User) , _vmdEnableDate :: !(Maybe ISO8601) , _vmdSerialNumber :: !Text } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'VirtualMFADevice' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'vmdQRCodePNG' -- -- * 'vmdBase32StringSeed' -- -- * 'vmdUser' -- -- * 'vmdEnableDate' -- -- * 'vmdSerialNumber' virtualMFADevice :: Text -- ^ 'vmdSerialNumber' -> VirtualMFADevice virtualMFADevice pSerialNumber_ = VirtualMFADevice' { _vmdQRCodePNG = Nothing , _vmdBase32StringSeed = Nothing , _vmdUser = Nothing , _vmdEnableDate = Nothing , _vmdSerialNumber = pSerialNumber_ } -- | A QR code PNG image that encodes -- 'otpauth:\/\/totp\/$virtualMFADeviceName\'$AccountName?secret=$Base32String' -- where '$virtualMFADeviceName' is one of the create call arguments, -- 'AccountName' is the user name if set (otherwise, the account ID -- otherwise), and 'Base32String' is the seed in Base32 format. The -- 'Base32String' value is Base64-encoded. -- -- /Note:/ This 'Lens' automatically encodes and decodes Base64 data, -- despite what the AWS documentation might say. -- The underlying isomorphism will encode to Base64 representation during -- serialisation, and decode from Base64 representation during deserialisation. -- This 'Lens' accepts and returns only raw unencoded data. vmdQRCodePNG :: Lens' VirtualMFADevice (Maybe ByteString) vmdQRCodePNG = lens _vmdQRCodePNG (\ s a -> s{_vmdQRCodePNG = a}) . mapping (_Sensitive . _Base64); -- | The Base32 seed defined as specified in -- <http://www.ietf.org/rfc/rfc3548.txt RFC3548>. The 'Base32StringSeed' is -- Base64-encoded. -- -- /Note:/ This 'Lens' automatically encodes and decodes Base64 data, -- despite what the AWS documentation might say. -- The underlying isomorphism will encode to Base64 representation during -- serialisation, and decode from Base64 representation during deserialisation. -- This 'Lens' accepts and returns only raw unencoded data. vmdBase32StringSeed :: Lens' VirtualMFADevice (Maybe ByteString) vmdBase32StringSeed = lens _vmdBase32StringSeed (\ s a -> s{_vmdBase32StringSeed = a}) . mapping (_Sensitive . _Base64); -- | Undocumented member. vmdUser :: Lens' VirtualMFADevice (Maybe User) vmdUser = lens _vmdUser (\ s a -> s{_vmdUser = a}); -- | The date and time on which the virtual MFA device was enabled. vmdEnableDate :: Lens' VirtualMFADevice (Maybe UTCTime) vmdEnableDate = lens _vmdEnableDate (\ s a -> s{_vmdEnableDate = a}) . mapping _Time; -- | The serial number associated with 'VirtualMFADevice'. vmdSerialNumber :: Lens' VirtualMFADevice Text vmdSerialNumber = lens _vmdSerialNumber (\ s a -> s{_vmdSerialNumber = a}); instance FromXML VirtualMFADevice where parseXML x = VirtualMFADevice' <$> (x .@? "QRCodePNG") <*> (x .@? "Base32StringSeed") <*> (x .@? "User") <*> (x .@? "EnableDate") <*> (x .@ "SerialNumber")
olorin/amazonka
amazonka-iam/gen/Network/AWS/IAM/Types/Product.hs
mpl-2.0
91,056
0
18
19,019
15,538
9,126
6,412
1,468
1
module Graphics.Drawable (Drawable) where -- An object that can be draw over a surface class Drawable a where draw :: a -> IO ()
trbecker/haskell-musings
Drawable/src/Graphics/Drawable.hs
unlicense
130
0
9
25
35
19
16
3
0
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="ru-RU"> <title>Active Scan Rules - Alpha | ZAP Extension</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Индекс</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Поиск</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
secdec/zap-extensions
addOns/ascanrulesAlpha/src/main/javahelp/org/zaproxy/zap/extension/ascanrulesAlpha/resources/help_ru_RU/helpset_ru_RU.hs
apache-2.0
997
95
29
162
437
224
213
-1
-1
module Chase where import Data.Map (Map) import qualified Data.Map as M import Data.Array import Data.Maybe (mapMaybe,catMaybes) import Data.List (maximumBy,delete) import Data.Ord (comparing) import Debug.Trace -- Colloborate Diffusion -- http://en.wikipedia.org/wiki/Antiobjects type Desirability = Double type Scent = Double type Point = (Int,Int) data Agent = Goal Desirability | Pursuer | Path Scent | Obstacle deriving (Eq,Show) data Environment = Environment { board :: Map Point [Agent] , size :: Int , pursuers :: [Point] , goal :: Point } deriving Show diffusionRate :: Double diffusionRate = 0.1 scent :: Agent -> Scent scent (Path s) = s scent (Goal s) = s scent _ = 0 zeroScent :: Agent -> Agent zeroScent (Path s) = Path 0 zeroScent x = x zeroScents :: [Agent] -> [Agent] zeroScents (x:xs) = zeroScent x : xs zeroScents x = x topScent :: [Agent] -> Scent topScent (x:xs) = scent x topScent _ = 0 addPoint :: Point -> Point -> Point addPoint (x,y) (dx,dy) = (x+dx,y+dy) -- |Builds a basic environment createEnvironment :: Int -> Environment createEnvironment s = Environment b s [(1,1),(s-1,s-1)] (mx,my) where (mx,my) = (s `div` 2, s `div` 2) b = M.fromList [((x,y),mkAgent x y) | x <- [0..s], y <- [0..s] ] mkAgent x y | x == 0 || y == 0 || x == s || y == s = [Obstacle] | x == mx && y == my = [Goal 1000,Path 0] | x == 1 && y == 1 = [Pursuer, Path 0] | x == (s-1) && y == (s-1) = [Pursuer,Path 0] | otherwise = [Path 0] update :: Environment -> Environment update e@(Environment b s _ _) = updatePursuers (e { board = c }) where c = M.fromList [((x,y), diffusePoint' (x,y) c b) | y <- [0..s], x <- [0..s]] -- TODO simplify? canMove :: Maybe [Agent] -> Bool canMove (Just (Path _:xs)) = True canMove _ = False flipObstacle :: Point -> Environment -> Environment flipObstacle p e | head x /= Obstacle = e { board = M.insert p (Obstacle:x) b } | null (tail x) = e | otherwise = e { board = M.insert p (tail x) b } where b = board e x = b M.! p -- |Hides the scent underneath flipPursuer :: Point -> Environment -> Environment flipPursuer p e | head x /= Pursuer = e { board = M.insert p (Pursuer:x) b , pursuers = p : pursuers e } | null (tail x) = e | otherwise = e { board = M.insert p (tail x) b , pursuers = delete p (pursuers e) } where b = board e x = b M.! p move :: Map Point [Agent] -> Point -> Point -> Map Point [Agent] move e src tgt = M.insert src (zeroScents $ tail srcA) (M.insert tgt (head srcA : e M.! tgt) e) where srcA = e M.! src moveGoal :: Point -> Environment -> Environment moveGoal p e | targetSuitable = e { board = move b (goal e) dest , goal = dest } | otherwise = e where b = board e dest = addPoint p (goal e) targetSuitable = canMove $ M.lookup dest b updatePursuers :: Environment -> Environment updatePursuers env = foldl updatePursuer env (pursuers env) -- Ensure we only move if there is a better scent available updatePursuer :: Environment -> Point -> Environment updatePursuer e p | null n = e | otherwise = e { board = move b p m , pursuers = m : delete p (pursuers e) } where b = board e currentScent = topScent (b M.! p) n = filter (\x -> topScent (b M.! x) >= currentScent ) $ filter (canMove . (`M.lookup` b)) $ neighbouringPoints p -- can simplify here m = maximumBy (\x y -> comparing (scent . head) (b M.! x) (b M.! y)) n diffusePoint' :: Point -> Map Point [Agent] -> Map Point [Agent] -> [Agent] diffusePoint' p xs originalGrid = diffusePoint (originalGrid M.! p) (neighbours' xs originalGrid p) neighbouringPoints :: Point -> [Point] neighbouringPoints p = map (addPoint p) [(-1,0), (0,-1), (1,0), (0, 1)] neighbours' :: Map Point [Agent] -> Map Point [Agent] -> Point -> [Agent] neighbours' xs m p = map head $ catMaybes [M.lookup (addPoint p (-1, 0 )) xs ,M.lookup (addPoint p (0 , -1)) xs ,M.lookup (addPoint p (1 , 0) ) m ,M.lookup (addPoint p (0 , 1) ) m] neighbours :: Map Point [Agent] -> Point -> [Agent] neighbours m p = map head $ mapMaybe (`M.lookup` m) (neighbouringPoints p) diffusePoint :: [Agent] -> [Agent] -> [Agent] diffusePoint (Path d:r) n = (Path $ diffusedScent d n) : r diffusePoint p _ = p diffusedScent :: Scent -> [Agent] -> Scent diffusedScent s xs = s + diffusionRate * sum (map (\x -> scent x - s) xs)
fffej/haskellprojects
chase/Chase.hs
bsd-2-clause
4,934
0
16
1,551
2,112
1,127
985
106
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE FlexibleContexts #-} module Radiation.Parsers.Internal.WithAttoparsec where import Control.Monad (forM_) import Data.Attoparsec.ByteString.Char8 as BP import Data.Attoparsec.ByteString.Lazy as Lazy import qualified Data.ByteString as BS import qualified Data.ByteString.Char8 as BSC import qualified Data.ByteString.Lazy as BSL import Radiation.Parsers hiding (Parser) import qualified Data.Map as Map import qualified Data.Set as Set import Vim import My.Utils withParsing :: Parser a -> (a -> VimM ()) -> BSL.ByteString -> VimM () withParsing parser trans filestr = case Lazy.parse parser filestr of {- The parsing failed. -} Lazy.Fail _ _ err -> vlog Error $ "Unable to parse: " +>+ BSC.pack err {- The parsing succeeded and handle the correct result -} Lazy.Done _ val -> vlog Info "Matches found" >> trans val >> vlog Debug "Finished running parser" withParsingMap :: Parser (Map.Map String (Set.Set BS.ByteString)) -> BSL.ByteString -> VimM () withParsingMap parserm = withParsing parserm def where def :: Map.Map String (Set.Set BS.ByteString) -> VimM() def val = forM_ (Map.toList val) $ \(hi,v) -> (syn Keyword (BSC.pack hi) (Set.toList v) :: VimM())
jrahm/Radiation
src/Radiation/Parsers/Internal/WithAttoparsec.hs
bsd-2-clause
1,360
0
13
322
385
211
174
28
2
module Problem39 where isPythagoreanTriples :: Int -> Int -> Int -> Bool isPythagoreanTriples a b c = a^2 + b^2 == c^2 pythagorianTriples :: Int -> [(Int, Int, Int)] pythagorianTriples n = [(a, b, c) | a <- [1..(n`div`3)], let rest = n - a, b <- [a..(rest`div`2)], let c = rest - b, isPythagoreanTriples a b c] maxN :: (Ord a, Ord b) => (a -> b) -> [a] -> a maxN f xs = snd . maximum $ zip (map f xs) xs main :: IO () main = print $ maxN (length.pythagorianTriples) [3..1000]
noraesae/euler
src/Problem39.hs
bsd-3-clause
624
0
10
244
280
152
128
13
1
module Data.Functor.Plus where import Data.Functor.Alt class Alt f => Plus f where zero :: f a
tonymorris/type-class
src/Data/Functor/Plus.hs
bsd-3-clause
102
0
7
23
37
20
17
5
0
{- - Intel Concurrent Collections for Haskell - Copyright (c) 2010, Intel Corporation. - - This program is free software; you can redistribute it and/or modify it - under the terms and conditions of the GNU Lesser General Public License, - version 2.1, as published by the Free Software Foundation. - - This program is distributed in the hope it will be useful, but WITHOUT - ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for - more details. - - You should have received a copy of the GNU Lesser General Public License along with - this program; if not, write to the Free Software Foundation, Inc., - 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. - -} -- Author: Ryan Newton -- #include <haskell_cnc.h> -- This demonstrates the normal (NOT #include) method of loading CnC: import Intel.Cnc6 -- Here's an odd little hello world where we communicate the two words -- to a computational step which puts them together. myStep items tag = do word1 <- get items "left" word2 <- get items "right" put items "result" (word1 ++ word2 ++ show tag) cncGraph = do tags <- newTagCol items <- newItemCol prescribe tags (myStep items) initialize$ do put items "left" "Hello " put items "right" "World " putt tags 99 finalize$ do get items "result" main = putStrLn (runGraph cncGraph)
rrnewton/Haskell-CnC
examples/hello_world.hs
bsd-3-clause
1,471
5
10
328
182
77
105
16
1
-- TODO MUCH Faster rendering. -- TODO GHCJS? -- TODO Record more data. -- TODO Lists instead of structs/bools? -- This: [Calories, Teeth, OneMeal] -- Instad of: emptyMeal {calories=True, teeth=True, oneMeal=True} -- Yeah! Then just score with (length . nub). {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE NoMonomorphismRestriction #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE UnicodeSyntax #-} {-# LANGUAGE OverloadedLists #-} module Main(main) where import August import AugustData (august) import Data.Monoid.Unicode import Data.Set (Set) import qualified Data.Set as S import Data.Typeable import Diagrams.Backend.SVG.CmdLine import Diagrams.Prelude hiding (stretch) import Diagrams.TwoD.Text type IntMap a = [(Int,a)] type Month d = IntMap d good,bad,meh ∷ Double → Entry (good,bad,meh) = (Good . Just, Bad . Just, Meh . Just) fourSquares ∷ (Eq (N b), Fractional (N b), Traversable (V b), Semigroup b, Additive (V b), Transformable b, Juxtaposable b, HasOrigin b, Alignable b, V b ~ V2) ⇒ Four b → b fourSquares (Four a b c d) = ((a === c) ||| (b === d)) # center # scale 0.5 txtSquare ∷ (RealFloat n, Typeable n, Renderable (Path V2 n) b, Renderable (Text n) b) ⇒ String → Colour Double → QDiagram b V2 n Any txtSquare t color = (text t # bold # scale(0.4)) ⊕ (square 1 # fc color) symSquare ∷ (RealFloat n, Typeable n, Renderable (Path V2 n) b, Renderable (Diagrams.TwoD.Text.Text n) b) ⇒ String → Colour Double → QDiagram b V2 n Any symSquare t color = (text t # bold # scale(1/2)) ⊕ (square 1 # fc color) showNum ∷ Double → String showNum d = if noPoint then show (i `div` 10) else show d where i ∷ Int = round (d*10) noPoint = 0 == (i `mod` 10) dispEntry ∷ Entry → Diagram B dispEntry (Good (Just n)) = txtSquare (showNum n) forestgreen dispEntry (Good Nothing) = symSquare "✓" forestgreen dispEntry (Meh (Just n)) = txtSquare (showNum n) tomato dispEntry (Meh Nothing) = symSquare "·" tomato dispEntry (Bad (Just n)) = txtSquare (showNum n) firebrick dispEntry (Bad Nothing) = symSquare "✗" firebrick dispEntry NA = txtSquare "⊥" darkgrey dispEntry Idk = txtSquare "¿" lightgrey colLabel ∷ String → Diagram B colLabel l = (text l # scale (2/3)) ⊕ (square 1 # scaleY 1 # fc darkseagreen) rowLabel ∷ String → Diagram B rowLabel "" = square 1 # scaleX 4 # lwG 0 rowLabel l = (text l # scale (2/3)) ⊕ (square 1 # scaleX 4 # fc darkseagreen) sheetLabel ∷ String → Diagram B sheetLabel l = (text l # scale (2/3)) ⊕ (square 1 # scaleY 1 # scaleX 4 # fc darkseagreen) rowLabels ∷ String → Diagram B rowLabels month = vcat (square 1 # lwG 0 : sheetLabel month # lwG (1/40) : rowNames) where rowNames = lwG (1/40) . rowLabel <$> [ "canto", "meals", "fit", "blocks", "org", "", "wakeTime", "getup" , "get-started", "weight", "waist", "squat", "bench", "dead", "chin" , "press", "purdy" ] pointEntry ∷ Maybe Int → Entry pointEntry Nothing = Idk pointEntry (Just x) | x<1 = bad $ fromIntegral x pointEntry (Just x) | x<2 = bad $ fromIntegral x pointEntry (Just x) | x<3 = meh $ fromIntegral x pointEntry (Just x) | x<4 = meh $ fromIntegral x pointEntry (Just x) = good $ fromIntegral x -- dispPoint = dispEntry . pointEntry dispPoint ∷ Maybe Int → Diagram B dispPoint = dispEntry . pointEntry dispPoint' ∷ Maybe Int → Diagram B dispPoint' Nothing = dispEntry Idk dispPoint' (Just i) = (text (showNum $ fromIntegral i) # bold # scale(2/3)) ⊕ (square 1 # fc color) where color = case i of x | x<1 → firebrick x | x<2 → firebrick x | x<3 → tomato x | x<4 → tomato _ → forestgreen dAugMeals ∷ Four (Maybe Int) → QDiagram B V2 Double Any dAugMeals = fourSquares . fmap (lwG(1/80) . dispPoint') dispAugustDay ∷ Int → August.Day → Diagram B dispAugustDay dayNum day = case day of August.Day{..} → vcat [ square 1 # lwG 0 , colLabel (show dayNum) # lwG (1/40) , dispPoint (score <$> canto) # lwG (1/80) , dAugMeals (fmap score <$> meals) , dispPoint (score <$> fit) # lwG (1/80) , dispPoint (score <$> blocks) # lwG (1/80) , dispPoint (score <$> org) # lwG (1/80) , square 1 # lwG 0 , dispEntry wakeUp # lwG (1/80) , dispEntry getUp # lwG (1/80) , dispEntry getStarted # lwG (1/80) , dispEntry weight # lwG (1/80) , dispEntry waist # lwG (1/80) , dispEntry squat # lwG (1/80) , dispEntry bench # lwG (1/80) , dispEntry dead # lwG (1/80) , dispEntry chin # lwG (1/80) , dispEntry press # lwG (1/80) , dispEntry purdy # lwG (1/80) ] dispAugust ∷ Month August.Day → Diagram B dispAugust m = rowLabels "August" ||| (hcat $ (\(i,d) → dispAugustDay i d) <$> m) main ∷ IO () main = mainWith $ dispAugust august -- August ---------------------------------------------------------------------- score ∷ Set a → Int score = fromIntegral . S.size
bsummer4/chart
src/Main.hs
bsd-3-clause
6,219
0
13
2,190
2,162
1,105
1,057
111
5
{-# LANGUAGE FlexibleContexts #-} module Ex4 where import Data.Vector import Control.Monad.Random hiding (fromList) import Ex3 randomVec :: Random a => Int -> Rnd (Vector a) randomVec = randomVec' (\x -> getRandom) randomVecR :: Random a => Int -> (a, a) -> Rnd (Vector a) randomVecR i r = randomVec' (\x -> getRandomR r) i randomVec' f i = fromList <$> traverse f [0 .. i]
bobbyrauchenberg/haskellCourse
src/Ex4.hs
bsd-3-clause
379
0
10
69
152
82
70
10
1
{-# LANGUAGE OverloadedStrings, BangPatterns, RecordWildCards, ViewPatterns, DoAndIfThenElse, PatternGuards, ScopedTypeVariables, TupleSections #-} {-# OPTIONS_GHC -fwarn-incomplete-patterns #-} -- | HTTP downloader tailored for web-crawler needs. -- -- * Handles all possible http-conduit exceptions and returns -- human readable error messages. -- -- * Handles some web server bugs (returning @deflate@ data instead of @gzip@, -- invalid @gzip@ encoding). -- -- * Uses OpenSSL instead of @tls@ package (since @tls@ doesn't handle all sites). -- -- * Ignores invalid SSL sertificates. -- -- * Receives data in 32k chunks internally to reduce memory fragmentation -- on many parallel downloads. -- -- * Download timeout. -- -- * Total download size limit. -- -- * Returns HTTP headers for subsequent redownloads -- and handles @Not modified@ results. -- -- * Can be used with external DNS resolver (hsdns-cache for example). -- -- * Keep-alive connections pool (thanks to http-conduit). -- -- Typical workflow in crawler: -- -- @ -- withDnsCache $ \ c -> withDownloader $ \ d -> do -- ... -- got URL from queue -- ra <- resolveA c $ hostNameFromUrl url -- case ra of -- Left err -> ... -- uh oh, bad host -- Right ha -> do -- ... -- crawler politeness stuff (rate limits, queues) -- dr <- download d url (Just ha) opts -- case dr of -- DROK dat redownloadOptions -> -- ... -- analyze data, save redownloadOpts for next download -- DRRedirect .. -> ... -- DRNotModified -> ... -- DRError e -> ... -- @ -- -- It's highly recommended to use -- <http://hackage.haskell.org/package/concurrent-dns-cache> -- (preferably with single resolver pointing to locally running BIND) -- for DNS resolution since @getAddrInfo@ used in @http-conduit@ can be -- buggy and ineffective when it needs to resolve many hosts per second for -- a long time. -- module Network.HTTP.Conduit.Downloader ( -- * Download operations urlGetContents, urlGetContentsPost , download, post, downloadG, rawDownload , DownloadResult(..), RawDownloadResult(..), DownloadOptions -- * Downloader , DownloaderSettings(..) , Downloader, withDownloader, withDownloaderSettings, newDownloader -- * Utils , postRequest, sinkByteString ) where import Control.Monad.Trans import qualified Data.ByteString.Lazy.Char8 as BL import qualified Data.ByteString.Char8 as B import qualified Data.ByteString.Internal as B import Control.Monad import qualified Control.Exception as E import Data.Default as C import Data.String import Data.Char import Data.Maybe import Data.List import Foreign import qualified Network.Socket as NS -- import qualified Network.TLS as TLS -- import qualified Network.Connection as NC import qualified OpenSSL as SSL import qualified OpenSSL.Session as SSL import qualified Network.HTTP.Types as N import qualified Network.HTTP.Conduit as C import Network.HTTP.Client.Internal (makeConnection, Connection) import qualified Control.Monad.Trans.Resource as C import qualified Data.Conduit as C import System.Timeout.Lifted import Codec.Compression.Zlib.Raw as Deflate import Network.URI -- import ADNS.Cache import Data.Time.Format import Data.Time.Clock import Data.Time.Clock.POSIX -- | Result of 'download' operation. data DownloadResult = DROK B.ByteString DownloadOptions -- ^ Successful download with data and options for next download. | DRRedirect String -- ^ Redirect URL | DRError String -- ^ Error | DRNotModified -- ^ HTTP 304 Not Modified deriving (Show, Read, Eq) -- | Result of 'rawDownload' operation. data RawDownloadResult = RawDownloadResult { rdrStatus :: N.Status , rdrHttpVersion :: N.HttpVersion , rdrHeaders :: N.ResponseHeaders , rdrBody :: B.ByteString , rdrCookieJar :: C.CookieJar } deriving (Show, Eq) -- | @If-None-Match@ and/or @If-Modified-Since@ headers. type DownloadOptions = [String] -- | Settings used in downloader. data DownloaderSettings = DownloaderSettings { dsUserAgent :: B.ByteString -- ^ User agent string. Default: @\"Mozilla\/5.0 (compatible; HttpConduitDownloader\/1.0; +http:\/\/hackage.haskell.org\/package\/http-conduit-downloader)\"@. -- -- Be a good crawler. Provide your User-Agent please. , dsTimeout :: Int -- ^ Download timeout. Default: 30 seconds. , dsManagerSettings :: C.ManagerSettings -- ^ Conduit 'Manager' settings. -- Default: ManagerSettings with SSL certificate checks removed. , dsMaxDownloadSize :: Int -- ^ Download size limit in bytes. Default: 10MB. } -- http://wiki.apache.org/nutch/OptimizingCrawls -- use 10 seconds as default timeout (too small). instance Default DownloaderSettings where def = DownloaderSettings { dsUserAgent = "Mozilla/5.0 (compatible; HttpConduitDownloader/1.0; +http://hackage.haskell.org/package/http-conduit-downloader)" , dsTimeout = 30 , dsManagerSettings = C.tlsManagerSettings { C.managerTlsConnection = -- IO (Maybe HostAddress -> String -> Int -> IO Connection) getOpenSSLConnection } -- (C.mkManagerSettings tls Nothing) -- { C.managerTlsConnection = -- -- IO (Maybe HostAddress -> String -> Int -> IO Connection) -- getTlsConnection (Just tls) -- } -- C.def { C.managerCheckCerts = -- \ _ _ _ -> return TLS.CertificateUsageAccept } , dsMaxDownloadSize = 10*1024*1024 } -- where tls = NC.TLSSettingsSimple True False False -- tls package doesn't handle some sites: -- https://github.com/vincenthz/hs-tls/issues/53 -- using OpenSSL instead getOpenSSLConnection :: IO (Maybe NS.HostAddress -> String -> Int -> IO Connection) getOpenSSLConnection = do ctx <- SSL.context return $ \ mbha host port -> do sock <- case mbha of Nothing -> openSocketByName host port Just ha -> openSocket ha port ssl <- SSL.connection ctx sock SSL.connect ssl makeConnection (SSL.read ssl bufSize `E.catch` \ (_ :: SSL.ConnectionAbruptlyTerminated) -> return "" ) (SSL.write ssl) -- Closing an SSL connection gracefully involves writing/reading -- on the socket. But when this is called the socket might be -- already closed, and we get a @ResourceVanished@. (NS.sClose sock `E.catch` \(_ :: E.IOException) -> return ()) -- ((SSL.shutdown ssl SSL.Bidirectional >> return ()) `E.catch` \(_ :: E.IOException) -> return ()) -- segmentation fault in GHCi with SSL.shutdown / tryShutdown SSL.Unidirectional -- hang with SSL.Bidirectional -- Network.HTTP.Client.TLS.getTlsConnection with ability to use HostAddress -- since Network.Connection.connectTo uses Network.connectTo that uses -- getHostByName (passed HostAddress is ignored) -- getTlsConnection :: Maybe NC.TLSSettings -- -- -> Maybe NC.SockSettings -- -> IO (Maybe NS.HostAddress -> String -> Int -> IO Connection) -- getTlsConnection tls = do -- context <- NC.initConnectionContext -- return $ \ mbha host port -> do -- cf <- case mbha of -- Nothing -> return $ NC.connectTo context -- Just ha -> do -- sock <- openSocket ha port -- handle <- NS.socketToHandle sock ReadWriteMode -- return $ NC.connectFromHandle context handle -- conn <- cf $ NC.ConnectionParams -- { NC.connectionHostname = host -- , NC.connectionPort = fromIntegral port -- , NC.connectionUseSecure = tls -- , NC.connectionUseSocks = Nothing -- sock -- } -- convertConnection conn -- where -- convertConnection conn = makeConnection -- (NC.connectionGetChunk conn) -- (NC.connectionPut conn) -- -- Closing an SSL connection gracefully involves writing/reading -- -- on the socket. But when this is called the socket might be -- -- already closed, and we get a @ResourceVanished@. -- (NC.connectionClose conn `E.catch` \(_ :: E.IOException) -> return ()) -- slightly modified Network.HTTP.Client.Connection.openSocketConnection openSocket :: NS.HostAddress -> Int -- ^ port -> IO NS.Socket openSocket ha port = openSocket' $ NS.AddrInfo { NS.addrFlags = [] , NS.addrFamily = NS.AF_INET , NS.addrSocketType = NS.Stream , NS.addrProtocol = 6 -- tcp , NS.addrAddress = NS.SockAddrInet (toEnum port) ha , NS.addrCanonName = Nothing } openSocket' :: NS.AddrInfo -> IO NS.Socket openSocket' addr = do E.bracketOnError (NS.socket (NS.addrFamily addr) (NS.addrSocketType addr) (NS.addrProtocol addr)) (NS.sClose) (\sock -> do NS.setSocketOption sock NS.NoDelay 1 NS.connect sock (NS.addrAddress addr) return sock) openSocketByName :: Show a => NS.HostName -> a -> IO NS.Socket openSocketByName host port = do let hints = NS.defaultHints { NS.addrFlags = []-- [NS.AI_ADDRCONFIG, NS.AI_NUMERICSERV] , NS.addrFamily = NS.AF_INET , NS.addrSocketType = NS.Stream , NS.addrProtocol = 6 -- tcp } (addrInfo:_) <- NS.getAddrInfo (Just hints) (Just host) (Just $ show port) openSocket' addrInfo -- | Keeps http-conduit 'Manager' and 'DownloaderSettings'. data Downloader = Downloader { manager :: C.Manager , settings :: DownloaderSettings } -- | Create a 'Downloader' with settings. newDownloader :: DownloaderSettings -> IO Downloader newDownloader s = do SSL.withOpenSSL $ return () -- init in case it wasn't initialized yet m <- C.newManager $ dsManagerSettings s return $ Downloader m s -- | Create a new 'Downloader', use it in the provided function, -- and then release it. withDownloader :: (Downloader -> IO a) -> IO a withDownloader = withDownloaderSettings def -- | Create a new 'Downloader' with provided settings, -- use it in the provided function, and then release it. withDownloaderSettings :: DownloaderSettings -> (Downloader -> IO a) -> IO a withDownloaderSettings s f = f =<< newDownloader s parseUrl :: String -> Either E.SomeException C.Request parseUrl = C.parseUrl . takeWhile (/= '#') -- | Perform download download :: Downloader -> String -- ^ URL -> Maybe NS.HostAddress -- ^ Optional resolved 'HostAddress' -> DownloadOptions -> IO DownloadResult download = downloadG return -- | Perform HTTP POST. post :: Downloader -> String -> Maybe NS.HostAddress -> B.ByteString -> IO DownloadResult post d url ha dat = downloadG (return . postRequest dat) d url ha [] -- | Make HTTP POST request. postRequest :: B.ByteString -> C.Request -> C.Request postRequest dat rq = rq { C.method = N.methodPost , C.requestBody = C.RequestBodyBS dat } -- | Generic version of 'download' -- with ability to modify http-conduit 'Request'. downloadG :: -- m ~ C.ResourceT IO (C.Request -> C.ResourceT IO C.Request) -- ^ Function to modify 'Request' -- (e.g. sign or make 'postRequest') -> Downloader -> String -- ^ URL -> Maybe NS.HostAddress -- ^ Optional resolved 'HostAddress' -> DownloadOptions -> IO (DownloadResult) downloadG f d u h o = fmap fst $ rawDownload f d u h o -- | Even more generic version of 'download', which returns 'RawDownloadResult'. -- 'RawDownloadResult' is optional since it can not be determined on timeouts -- and connection errors. rawDownload :: -- m ~ C.ResourceT IO (C.Request -> C.ResourceT IO C.Request) -- ^ Function to modify 'Request' -- (e.g. sign or make 'postRequest') -> Downloader -> String -- ^ URL -> Maybe NS.HostAddress -- ^ Optional resolved 'HostAddress' -> DownloadOptions -> IO (DownloadResult, Maybe RawDownloadResult) rawDownload f (Downloader {..}) url hostAddress opts = case parseUrl url of Left e -> fmap (, Nothing) $ maybe (return $ DRError $ show e) (httpExceptionToDR url) (E.fromException e) Right rq -> do let rq1 = rq { C.requestHeaders = [("Accept", "*/*") ,("User-Agent", dsUserAgent settings) ] ++ map toHeader opts ++ C.requestHeaders rq , C.redirectCount = 0 , C.responseTimeout = Nothing -- We have timeout for connect and downloading -- while http-conduit timeouts only when waits for -- headers. , C.hostAddress = hostAddress , C.checkStatus = \ _ _ _ -> Nothing } disableCompression rq' = rq' { C.requestHeaders = ("Accept-Encoding", "") : C.requestHeaders rq' } req' <- C.runResourceT $ f rq1 let dl req firstTime = do r <- C.runResourceT (timeout (dsTimeout settings * 1000000) $ do r <- C.http req manager mbb <- C.responseBody r C.$$+- sinkByteString (dsMaxDownloadSize settings) -- liftIO $ print ("sink", mbb) case mbb of Just b -> do let c = C.responseStatus r h = C.responseHeaders r d = tryDeflate h b curTime <- liftIO $ getCurrentTime return (makeDownloadResultC curTime url c h d , Just $ RawDownloadResult { rdrStatus = c , rdrHttpVersion = C.responseVersion r , rdrHeaders = h , rdrBody = d , rdrCookieJar = C.responseCookieJar r }) Nothing -> return (DRError "Too much data", Nothing)) `E.catch` (fmap (Just . (, Nothing)) . httpExceptionToDR url) -- `E.catch` -- (return . Just . handshakeFailed) `E.catch` (return . (Just . (, Nothing)) . someException) case r of Just (DRError e, _) | ("EOF reached" `isSuffixOf` e || e == "Invalid HTTP status line:\n" || e == "Incomplete headers" ) && firstTime -> dl req False -- "EOF reached" or empty HTTP status line -- can happen on servers that fails to -- implement HTTP/1.1 persistent connections. -- Try again -- https://github.com/snoyberg/http-conduit/issues/89 -- Fixed in -- https://github.com/snoyberg/http-conduit/issues/117 | "ZlibException" `isPrefixOf` e && firstTime -> -- some sites return junk instead of gzip data. -- retrying without compression dl (disableCompression req) False _ -> return $ fromMaybe (DRError "Timeout", Nothing) r dl req' True where toHeader :: String -> N.Header toHeader h = let (a,b) = break (== ':') h in (fromString a, fromString (tail b)) -- handshakeFailed (TLS.Terminated _ e tlsError) = -- DRError $ "SSL terminated:\n" ++ show tlsError -- handshakeFailed (TLS.HandshakeFailed tlsError) = -- DRError $ "SSL handshake failed:\n" ++ show tlsError -- handshakeFailed TLS.ConnectionNotEstablished = -- DRError $ "SSL connection not established" someException :: E.SomeException -> DownloadResult someException e = case show e of "<<timeout>>" -> DRError "Timeout" s -> DRError s tryDeflate headers b | Just d <- lookup "Content-Encoding" headers , B.map toLower d == "deflate" = BL.toStrict $ Deflate.decompress $ BL.fromStrict b | otherwise = b httpExceptionToDR :: Monad m => String -> C.HttpException -> m DownloadResult httpExceptionToDR url exn = return $ case exn of C.StatusCodeException c h _ -> -- trace "exception" $ makeDownloadResultC (posixSecondsToUTCTime 0) url c h "" C.InvalidUrlException _ e -> DRError $ "Invalid URL: " ++ e C.TooManyRedirects _ -> DRError "Too many redirects" C.UnparseableRedirect _ -> DRError "Unparseable redirect" C.TooManyRetries -> DRError "Too many retries" C.HttpParserException e -> DRError $ "HTTP parser error: " ++ e C.HandshakeFailed -> DRError "Handshake failed" C.OverlongHeaders -> DRError "Overlong HTTP headers" C.ResponseTimeout -> DRError "Timeout" C.FailedConnectionException _host _port -> DRError "Connection failed" C.FailedConnectionException2 _ _ _ exn' -> DRError $ "Connection failed: " ++ show exn' C.InvalidDestinationHost _ -> DRError "Invalid destination host" C.HttpZlibException e -> DRError $ show e C.ExpectedBlankAfter100Continue -> DRError "Expected blank after 100 (Continue)" C.InvalidStatusLine l -> DRError $ "Invalid HTTP status line:\n" ++ B.unpack l C.NoResponseDataReceived -> DRError "No response data received" C.TlsException e -> DRError $ "TLS exception:\n" ++ show e C.InvalidHeader h -> DRError $ "Invalid HTTP header:\n" ++ B.unpack h C.InternalIOException e -> case show e of "<<timeout>>" -> DRError "Timeout" s -> DRError s C.ProxyConnectException _ _ _ -> DRError "Can't connect to proxy" C.ResponseBodyTooShort _ _ -> DRError "Response body too short" C.InvalidChunkHeaders -> DRError "Invalid chunk headers" C.TlsNotSupported -> DRError "TLS not supported" C.IncompleteHeaders -> DRError "Incomplete headers" C.InvalidProxyEnvironmentVariable n v -> DRError $ "Invalid proxy environment variable " ++ show n ++ "=" ++ show v C.ResponseLengthAndChunkingBothUsed -> DRError "Response-Length and chunking both used" bufSize :: Int bufSize = 32 * 1024 - overhead -- Copied from Data.ByteString.Lazy. where overhead = 2 * sizeOf (undefined :: Int) newBuf :: IO B.ByteString newBuf = do fp <- B.mallocByteString bufSize return $ B.PS fp 0 0 addBs :: [B.ByteString] -> B.ByteString -> B.ByteString -> IO ([B.ByteString], B.ByteString) addBs acc (B.PS bfp _ bl) (B.PS sfp offs sl) = do let cpSize = min (bufSize - bl) sl bl' = bl + cpSize withForeignPtr bfp $ \ dst -> withForeignPtr sfp $ \ src -> B.memcpy (dst `plusPtr` bl) (src `plusPtr` offs) (toEnum cpSize) if bl' == bufSize then do buf' <- newBuf -- print ("filled", cpSize) addBs (B.PS bfp 0 bufSize : acc) buf' (B.PS sfp (offs + cpSize) (sl - cpSize)) else do -- print ("ok", cpSize, bl') return (acc, B.PS bfp 0 bl') -- | Sink data using 32k buffers to reduce memory fragmentation. -- Returns 'Nothing' if downloaded too much data. sinkByteString :: MonadIO m => Int -> C.Sink B.ByteString m (Maybe B.ByteString) sinkByteString limit = do buf <- liftIO $ newBuf go 0 [] buf where go len acc buf = do mbinp <- C.await case mbinp of Just inp -> do (acc', buf') <- liftIO $ addBs acc buf inp let len' = len + B.length inp if len' > limit then return Nothing else go len' acc' buf' Nothing -> do return $ Just $ B.concat $ reverse (buf:acc) makeDownloadResultC :: UTCTime -> String -> N.Status -> N.ResponseHeaders -> B.ByteString -> DownloadResult makeDownloadResultC curTime url c headers b = do if N.statusCode c == 304 then DRNotModified else if N.statusCode c `elem` [ 300 -- Multiple choices , 301 -- Moved permanently , 302 -- Found , 303 -- See other , 307 -- Temporary redirect ] then case lookup "location" headers of Just (B.unpack -> loc) -> redirect $ relUri (takeWhile (/= '#') $ dropWhile (== ' ') loc) -- ^ Location can be relative and contain #fragment _ -> DRError $ "Redirect status, but no Location field\n" ++ B.unpack (N.statusMessage c) ++ "\n" ++ unlines (map show headers) else if N.statusCode c >= 300 then DRError $ "HTTP " ++ show (N.statusCode c) ++ " " ++ B.unpack (N.statusMessage c) else DROK b (redownloadOpts [] headers) where redirect r -- | r == url = DRError $ "HTTP redirect to the same url?" | otherwise = DRRedirect r redownloadOpts acc [] = reverse acc redownloadOpts _ (("Pragma", B.map toLower -> tag) : _) | "no-cache" `B.isInfixOf` tag = [] redownloadOpts _ (("Cache-Control", B.map toLower -> tag) : _) | any (`B.isInfixOf` tag) ["no-cache", "no-store", "must-revalidate", "max-age=0"] = [] redownloadOpts acc (("Expires", time):xs) | ts <- B.unpack time , Just t <- parseHttpTime ts , t > curTime = redownloadOpts acc xs | otherwise = [] -- expires is non-valid or in the past redownloadOpts acc (("ETag", tag):xs) = redownloadOpts (("If-None-Match: " ++ B.unpack tag) : acc) xs redownloadOpts acc (("Last-Modified", time):xs) | ts <- B.unpack time , Just t <- parseHttpTime ts , t <= curTime = -- use only valid timestamps redownloadOpts (("If-Modified-Since: " ++ B.unpack time) : acc) xs redownloadOpts acc (_:xs) = redownloadOpts acc xs fixNonAscii = escapeURIString (\ x -> ord x <= 0x7f && x `notElem` (" []{}|\"" :: String)) . trimString relUri (fixNonAscii -> r) = fromMaybe r $ fmap (($ "") . uriToString id) $ liftM2 relativeTo (parseURIReference r) (parseURI $ fixNonAscii url) -- fmap utcTimeToPOSIXSeconds $ tryParseTime :: [String] -> String -> Maybe UTCTime tryParseTime formats string = foldr mplus Nothing $ map (\ fmt -> parseTimeM True defaultTimeLocale fmt (trimString string)) formats trimString :: String -> String trimString = reverse . dropWhile isSpace . reverse . dropWhile isSpace parseHttpTime :: String -> Maybe UTCTime parseHttpTime = tryParseTime ["%a, %e %b %Y %k:%M:%S %Z" -- Sun, 06 Nov 1994 08:49:37 GMT ,"%A, %e-%b-%y %k:%M:%S %Z" -- Sunday, 06-Nov-94 08:49:37 GMT ,"%a %b %e %k:%M:%S %Y" -- Sun Nov 6 08:49:37 1994 ] -- | Download single URL with default 'DownloaderSettings'. -- Fails if result is not 'DROK'. urlGetContents :: String -> IO B.ByteString urlGetContents url = withDownloader $ \ d -> do r <- download d url Nothing [] case r of DROK c _ -> return c e -> fail $ "urlGetContents " ++ show url ++ ": " ++ show e -- | Post data and download single URL with default 'DownloaderSettings'. -- Fails if result is not 'DROK'. urlGetContentsPost :: String -> B.ByteString -> IO B.ByteString urlGetContentsPost url dat = withDownloader $ \ d -> do r <- post d url Nothing dat case r of DROK c _ -> return c e -> fail $ "urlGetContentsPost " ++ show url ++ ": " ++ show e
pavelkogan/http-conduit-downloader
Network/HTTP/Conduit/Downloader.hs
bsd-3-clause
24,986
0
34
7,989
4,731
2,523
2,208
376
27
{-# LANGUAGE LambdaCase #-} {- | The __TUI__ (__T__ext __U__ser __I__nterface) works like the command line of the OS-shell or GHCi. This example runs a 'UI.Dialogui.voidController' using TUI: >>> let setup = writeLn "Hello" <> writeLn "World" >>> runTUI setup voidController Hello World > ^D Bye! >>> (As you can see, app was stopped by pressing the @Ctrl+D@) -} module UI.Dialogui.TUI (runTUI) where import System.IO (hFlush, stdout) import System.IO.Error (catchIOError, isEOFError) import UI.Dialogui type TUIState a = State String a tuiOutput :: Output (TUIState a -> TUIState a) tuiOutput = Output { writeTo = \msg -> modUIState (++ msg) , clearOutput = modUIState (const []) , scrollTo = const id -- TUI can't scroll } {- | Returns the 'UI.Dialogui.UI', which preforms some setup (list of Action's) just before starting the interaction with User. -} runTUI :: [Action a] -- ^ Setup -> UI a -- ^ Resulting UI runTUI setup ctl = loop . perform tuiOutput setup . state "" =<< initialize ctl where loop s | finished s = finalize ctl (ctlState s) >> putStrLn "\nBye!" | otherwise = do putStr (uiState s) let s' = modUIState (const []) s mbInput <- getInput loop =<< maybe (return $ finish s') (\input -> do actions <- communicate ctl (ctlState s') input return $ perform tuiOutput actions s' ) mbInput getInput :: IO (Maybe String) getInput = catchIOError (putStr "> " >> hFlush stdout >> Just <$> getLine) $ \e -> if isEOFError e then return Nothing else ioError e
astynax/dialogui
src/UI/Dialogui/TUI.hs
bsd-3-clause
1,691
0
19
474
407
207
200
39
2
module ProjectEuler.Problem073 (solution073) where endNumerator :: Int -> Int endNumerator d = if 2 * n < d then n else n - 1 where n = quot d 2 countForDenominator :: Int -> Int countForDenominator d = countForDenominator' (1 + quot d 3) 0 where countForDenominator' n count = if n > endNum then count else countForDenominator' (n + 1) (if 1 == gcd d n then count + 1 else count) endNum = endNumerator d genericSolution :: Int -> Integer genericSolution = toInteger . sum . map countForDenominator . enumFromTo 4 solution073 :: Integer solution073 = genericSolution 12000
guillaume-nargeot/project-euler-haskell
src/ProjectEuler/Problem073.hs
bsd-3-clause
629
0
12
156
207
109
98
16
3
module MagentoTest where import Data.Maybe (fromJust) import Test.Tasty import Test.Tasty.HUnit import Text.Printf (printf) import System.FilePath.Posix import qualified Magento root :: String root = "/magento/root" module_ :: String module_ = "Foo_Bar" tests :: TestTree tests = testGroup "Magento" [ moduleTests , baseDirTests ] moduleTests :: TestTree moduleTests = testGroup "Modules" [ testCase "Parse module namespace" modNamespace , testCase "Parse module name" modName , testCase "Get module directory (core)" coreModule , testCase "Get module directory (community)" communityModule , testCase "Get module directory (local)" localModule ] where modNamespace = Magento.getModuleNamespace module_ @?= ((Just "Foo") :: Maybe String) modName = Magento.getModuleName module_ @?= ((Just "Bar") :: Maybe String) modulePath cp m = root </> "app/code" </> cp </> (fromJust $ Magento.getModuleNamespace m) </> (fromJust $ Magento.getModuleName m) caseModuleDir cp = Magento.getModuleDir root cp module_ @?= ((Just (modulePath cp module_)) :: Maybe FilePath) coreModule = caseModuleDir "core" communityModule = caseModuleDir "community" localModule = caseModuleDir "local" baseDirTests :: TestTree baseDirTests = testGroup "Base Dir" cases where funcBaseDir d extra = Magento.getBaseDir root d @?= ((Just (root ++ extra ++ d)) :: Maybe FilePath) caseBase f l = [testCase (printf "getBaseDir (%s)" name) (f name) | name <- l] funcBaseBaseDir d = funcBaseDir d "/" funcBaseAppDir d = funcBaseDir d "/app/" funcBaseVarDir d = funcBaseDir d "/var/" funcBaseMediaDir d = funcBaseDir d "/media/" caseBaseBaseDir = caseBase funcBaseBaseDir ["app", "lib", "media", "skin", "var"] caseBaseAppDir = caseBase funcBaseAppDir ["code", "design", "etc", "locale"] caseBaseVarDir = caseBase funcBaseVarDir ["tmp", "cache", "log", "session", "export"] caseBaseMediaDir = caseBase funcBaseMediaDir ["upload"] cases = caseBaseBaseDir ++ caseBaseAppDir ++ caseBaseVarDir ++ caseBaseMediaDir
dxtr/hagento
test/MagentoTest.hs
bsd-3-clause
2,126
0
13
414
577
307
270
41
1
module Feldspar.Multicore.Compile.Parallella.Access where import Data.TypedStruct import Feldspar.Multicore.Compile.Parallella.Imports import Language.C.Monad as C (CEnv, CGen, Flags (..), defaultCEnv, runCGen) import Language.C.Syntax as C (Type) import Language.Embedded.Expression (VarId) import qualified Language.Embedded.Imperative.CMD as Imp -------------------------------------------------------------------------------- -- Access lower Feldspar data representation layer -------------------------------------------------------------------------------- mkArrayRef :: (ArrayWrapper arr, PrimType a) => VarId -> Length -> arr (Data a) mkArrayRef n l = wrapArr $ Arr 0 (value l) $ Single $ Imp.ArrComp n arrayRefName :: ArrayWrapper arr => arr (Data a) -> VarId arrayRefName (unwrapArr -> (Arr _ _ (Single (Imp.ArrComp name)))) = name -------------------------------------------------------------------------------- -- Access to C code generator and types -------------------------------------------------------------------------------- cGen :: C.CGen a -> (a, C.CEnv) cGen = flip C.runCGen (C.defaultCEnv C.Flags) isCTypeOf :: PrimType' a => proxy a -> C.Type -> Bool isCTypeOf ty cty = cty == cTypeOf ty cTypeOf :: PrimType' a => proxy a -> C.Type cTypeOf = fst . cGen . compType (Proxy :: Proxy PrimType')
kmate/raw-feldspar-mcs
src/Feldspar/Multicore/Compile/Parallella/Access.hs
bsd-3-clause
1,328
0
14
164
362
201
161
-1
-1
{-# LANGUAGE BangPatterns, DeriveDataTypeable, DeriveGeneric, FlexibleInstances, MultiParamTypeClasses #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} module Web.RTBBidder.Protocol.Adx.BidRequest.AdSlot.NonBrowserSource (NonBrowserSource(..)) where import Prelude ((+), (/), (.)) import qualified Prelude as Prelude' import qualified Data.Typeable as Prelude' import qualified GHC.Generics as Prelude' import qualified Data.Data as Prelude' import qualified Text.ProtocolBuffers.Header as P' data NonBrowserSource = UNDECLARED_SOURCE | DESKTOP_APP deriving (Prelude'.Read, Prelude'.Show, Prelude'.Eq, Prelude'.Ord, Prelude'.Typeable, Prelude'.Data, Prelude'.Generic) instance P'.Mergeable NonBrowserSource instance Prelude'.Bounded NonBrowserSource where minBound = UNDECLARED_SOURCE maxBound = DESKTOP_APP instance P'.Default NonBrowserSource where defaultValue = UNDECLARED_SOURCE toMaybe'Enum :: Prelude'.Int -> P'.Maybe NonBrowserSource toMaybe'Enum 0 = Prelude'.Just UNDECLARED_SOURCE toMaybe'Enum 1 = Prelude'.Just DESKTOP_APP toMaybe'Enum _ = Prelude'.Nothing instance Prelude'.Enum NonBrowserSource where fromEnum UNDECLARED_SOURCE = 0 fromEnum DESKTOP_APP = 1 toEnum = P'.fromMaybe (Prelude'.error "hprotoc generated code: toEnum failure for type Web.RTBBidder.Protocol.Adx.BidRequest.AdSlot.NonBrowserSource") . toMaybe'Enum succ UNDECLARED_SOURCE = DESKTOP_APP succ _ = Prelude'.error "hprotoc generated code: succ failure for type Web.RTBBidder.Protocol.Adx.BidRequest.AdSlot.NonBrowserSource" pred DESKTOP_APP = UNDECLARED_SOURCE pred _ = Prelude'.error "hprotoc generated code: pred failure for type Web.RTBBidder.Protocol.Adx.BidRequest.AdSlot.NonBrowserSource" instance P'.Wire NonBrowserSource where wireSize ft' enum = P'.wireSize ft' (Prelude'.fromEnum enum) wirePut ft' enum = P'.wirePut ft' (Prelude'.fromEnum enum) wireGet 14 = P'.wireGetEnum toMaybe'Enum wireGet ft' = P'.wireGetErr ft' wireGetPacked 14 = P'.wireGetPackedEnum toMaybe'Enum wireGetPacked ft' = P'.wireGetErr ft' instance P'.GPB NonBrowserSource instance P'.MessageAPI msg' (msg' -> NonBrowserSource) NonBrowserSource where getVal m' f' = f' m' instance P'.ReflectEnum NonBrowserSource where reflectEnum = [(0, "UNDECLARED_SOURCE", UNDECLARED_SOURCE), (1, "DESKTOP_APP", DESKTOP_APP)] reflectEnumInfo _ = P'.EnumInfo (P'.makePNF (P'.pack ".Adx.BidRequest.AdSlot.NonBrowserSource") ["Web", "RTBBidder", "Protocol"] ["Adx", "BidRequest", "AdSlot"] "NonBrowserSource") ["Web", "RTBBidder", "Protocol", "Adx", "BidRequest", "AdSlot", "NonBrowserSource.hs"] [(0, "UNDECLARED_SOURCE"), (1, "DESKTOP_APP")] instance P'.TextType NonBrowserSource where tellT = P'.tellShow getT = P'.getRead
hiratara/hs-rtb-bidder
src/Web/RTBBidder/Protocol/Adx/BidRequest/AdSlot/NonBrowserSource.hs
bsd-3-clause
2,866
0
11
457
636
351
285
59
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} module Numeric.Quotient where import Data.Finite import Data.Function import Data.Ord import Data.Proxy import Data.Quotient import GHC.TypeLits import Numeric.Natural data Mod :: Nat -> * instance (KnownNat m, Integral n) => Equiv (Mod m) n where type EquivClass (Mod m) n = Finite m toEquivClass _ = finite . (`mod` natVal (Proxy :: Proxy m)) . fromIntegral fromEquivClass _ = fromInteger . getFinite data Diff data Natural2 = N2 Natural Natural deriving (Show, Eq, Read) instance Equiv Diff Natural2 where type EquivClass Diff Natural2 = Integer toEquivClass _ (N2 x y) = fromIntegral x - fromIntegral y fromEquivClass _ n | n >= 0 = N2 (fromIntegral n) 0 | otherwise = N2 0 (fromIntegral (negate n))
mstksg/quotiented
src/Numeric/Quotient.hs
bsd-3-clause
1,090
0
11
275
291
156
135
-1
-1
{-# OPTIONS_GHC -fno-warn-tabs #-} import Common import Hex import Xor main = do putStrLn "=== Challange3 ===" putStrLn $ vecToStr $ xorWithSingleByte enc $ breakSingleKeyXor enc where enc = hexDecode "1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736"
andrewcchen/matasano-cryptopals-solutions
set1/Challange3.hs
bsd-3-clause
278
2
9
37
60
26
34
8
1
module Experiment (experiment, generators) where import Data.Monoid import Control.Arrow import Simulation.Aivika import Simulation.Aivika.Experiment import Simulation.Aivika.Experiment.Chart import qualified Simulation.Aivika.Results.Transform as T -- | The simulation specs. specs = Specs { spcStartTime = 0.0, spcStopTime = 500.0, spcDT = 0.1, spcMethod = RungeKutta4, spcGeneratorType = SimpleGenerator } -- | The experiment. experiment :: Experiment experiment = defaultExperiment { experimentSpecs = specs, experimentRunCount = 1000, -- experimentRunCount = 10, experimentTitle = "Machine Tool with Breakdowns" } jobsCompleted = T.ArrivalTimer $ resultByName "jobsCompleted" jobsInterrupted = resultByName "jobsInterrupted" inputQueue = T.Queue $ resultByName "inputQueue" machineProcessing = T.Server $ resultByName "machineProcessing" jobsCompletedCount = T.samplingStatsCount $ T.arrivalProcessingTime jobsCompleted processingTime :: ResultTransform processingTime = T.tr $ T.arrivalProcessingTime jobsCompleted waitTime :: ResultTransform waitTime = T.tr $ T.queueWaitTime inputQueue queueCount :: ResultTransform queueCount = T.queueCount inputQueue queueCountStats :: ResultTransform queueCountStats = T.tr $ T.queueCountStats inputQueue processingFactor :: ResultTransform processingFactor = T.serverProcessingFactor machineProcessing generators :: ChartRendering r => [WebPageGenerator r] generators = [outputView defaultExperimentSpecsView, outputView defaultInfoView, outputView $ defaultFinalStatsView { finalStatsTitle = "Machine Tool With Breakdowns", finalStatsSeries = jobsCompletedCount <> jobsInterrupted }, outputView $ defaultDeviationChartView { deviationChartTitle = "The Wait Time (chart)", deviationChartWidth = 1000, deviationChartRightYSeries = waitTime }, outputView $ defaultFinalStatsView { finalStatsTitle = "The Wait Time (statistics)", finalStatsSeries = waitTime }, outputView $ defaultDeviationChartView { deviationChartTitle = "The Queue Size (chart)", deviationChartWidth = 1000, deviationChartRightYSeries = queueCount <> queueCountStats }, outputView $ defaultFinalStatsView { finalStatsTitle = "The Queue Size (statistics)", finalStatsSeries = queueCountStats }, outputView $ defaultDeviationChartView { deviationChartTitle = "The Processing Time (chart)", deviationChartWidth = 1000, deviationChartRightYSeries = processingTime }, outputView $ defaultFinalStatsView { finalStatsTitle = "The Processing Time (statistics)", finalStatsSeries = processingTime }, outputView $ defaultDeviationChartView { deviationChartTitle = "The Machine Load (chart)", deviationChartWidth = 1000, deviationChartRightYSeries = processingFactor }, outputView $ defaultFinalHistogramView { finalHistogramTitle = "The Machine Load (histogram)", finalHistogramWidth = 1000, finalHistogramSeries = processingFactor }, outputView $ defaultFinalStatsView { finalStatsTitle = "The Machine Load (statistics)", finalStatsSeries = processingFactor } ]
dsorokin/aivika-experiment-chart
examples/MachineBreakdowns/Experiment.hs
bsd-3-clause
3,253
0
9
602
562
334
228
79
1
module Ciphers where import Data.Char charToRight :: Int -> Char -> Char charToRight n x | ord x >= 97 && ord x <= 122 = go n x ['a'..'z'] 97 | ord x >= 65 && ord x <= 90 = go n x ['A'..'Z'] 65 | otherwise = x where go nn xx xxs off | ord xx - off + nn < 0 = go nn xx xxs (off - 26) | ord xx - off + nn > 25 = go nn xx xxs (off + 26) | otherwise = xxs !! (ord xx - off + nn) inCaesar :: Int -> String -> String inCaesar n = map (charToRight n) unCaesar :: Int -> String -> String unCaesar n = map (charToRight $ negate n) vigenere :: (Int -> Int) -> String -> String -> String vigenere switch baseKeys baseExs = case (baseKeys, baseExs) of (_, "") -> "" ("", xs) -> xs (bks, bxs) -> go bks bxs [] where go keys exs acc = case (keys, exs) of (_, []) -> acc ([], xs) -> go baseKeys xs acc (k:ks, x:xs) -> goAgain k ks x xs where goAgain k ks x xs | x `elem` ['A'..'Z'] = go ks xs (acc ++ [charToRight (switch (ord k - 65)) x]) | x `elem` ['a'..'z'] = go ks xs (acc ++ [charToRight (switch (ord k - 97)) x]) | otherwise = go keys xs (acc ++ [x]) inVig :: String -> String -> String inVig = vigenere id unVig :: String -> String -> String unVig = vigenere negate -- unVig "ally" $ inVig "ally" "meet at dawn"
dmvianna/ciphers
src/Ciphers.hs
bsd-3-clause
1,802
0
25
871
681
346
335
42
5
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE OverloadedStrings #-} module Main where import qualified Data.Text as T import Snap import Snap.Snaplet.Heist import Snap.Snaplet.Auth import Snap.Snaplet.Auth.Backends.JsonFile import Snap.Snaplet.Session import Snap.Snaplet.Session.Backends.CookieSession import Snap.Blaze (blaze) import Text.Blaze.Html5 ((!)) import qualified Text.Blaze.Html5 as H import qualified Text.Blaze.Html5.Attributes as A data App = App { _heist :: Snaplet (Heist App) , _auth :: Snaplet (AuthManager App) , _sess :: Snaplet SessionManager } makeLenses [''App] instance HasHeist App where heistLens = subSnaplet heist appInit :: SnapletInit App App appInit = makeSnaplet "snaplet-auth-example" "Snaplet Auth Example" Nothing $ do hs <- nestSnaplet "heist" heist $ heistInit "templates" ss <- nestSnaplet "session" sess $ initCookieSessionManager "session_key.txt" "COOKIE" Nothing as <- nestSnaplet "auth" auth $ initJsonFileAuthManager defAuthSettings sess "users.json" addRoutes [ ("/a/login", with auth $ loginHandler) , ("/a/logout", with auth $ logoutHandler) , ("/a/register", with auth $ registerHandler) , ("/", namePage) ] wrapHandlers (<|> heistServe) return $ App hs as ss namePage :: Handler App App () namePage = do mu <- with auth currentUser blaze $ do H.h1 "Snaplet Auth Example" case mu of Just u -> H.div $ do H.toHtml $ "Welcome " `T.append` userLogin u `T.append` ". " H.a ! A.href "/a/logout" $ "Logout" Nothing -> do H.h2 "Login" H.form ! A.method "POST" ! A.action "/a/login" $ do H.label ! A.for "login" $ "Username: " H.input ! A.type_ "text" ! A.name "login" ! A.id "login" ! A.value "" H.label ! A.for "login" $ "Password: " H.input ! A.type_ "password" ! A.name "password" ! A.id "password" ! A.value "" H.label ! A.for "login" $ "Remember me: " H.input ! A.type_ "checkbox" ! A.name "remember" ! A.id "remember" ! A.value "" H.input ! A.type_ "submit" ! A.value "Login" H.h2 "Register" H.form ! A.method "POST" ! A.action "/a/register" $ do H.label ! A.for "login" $ "Username: " H.input ! A.type_ "text" ! A.name "login" ! A.id "login" ! A.value "" H.label ! A.for "login" $ "Password: " H.input ! A.type_ "password" ! A.name "password" ! A.id "password" ! A.value "" H.input ! A.type_ "submit" ! A.value "Register" loginHandler :: Handler App (AuthManager App) () loginHandler = do loginUser "login" "password" (Just "remember") onFailure onSuccess where onFailure _ = blaze "Login and password don't match." onSuccess = do mu <- currentUser case mu of Just _ -> redirect' "/" 303 Nothing -> blaze "Can't happen" logoutHandler :: Handler App (AuthManager App) () logoutHandler = do logout redirect' "/" 303 registerHandler :: Handler App (AuthManager App) () registerHandler = do authUser <- registerUser "login" "password" blaze $ H.toHtml $ show authUser main :: IO () main = serveSnaplet defaultConfig appInit
noteed/snaplet-auth-example
snaplet-auth-example.hs
bsd-3-clause
3,524
0
23
1,082
1,086
529
557
97
2
{-# LANGUAGE CPP #-} {-# LANGUAGE OverloadedStrings #-} module Bead.Persistence.SQL.Assignment where import Control.Applicative import Control.Monad.IO.Class import Data.Maybe import qualified Data.Text as Text import Data.Time hiding (TimeZone) import Database.Persist.Sql import qualified Bead.Domain.Entities as Domain import qualified Bead.Domain.Relationships as Domain import qualified Bead.Domain.Shared.Evaluation as Domain import Bead.Persistence.SQL.Class import Bead.Persistence.SQL.Entities import Bead.Persistence.SQL.JSON #ifdef TEST import qualified Data.Set as Set import Bead.Persistence.SQL.Course import Bead.Persistence.SQL.Group import Bead.Persistence.SQL.MySQLTestRunner import Bead.Persistence.SQL.TestData import Test.Tasty.TestSet (ioTest, shrink, equals) #endif -- * Assignment toDomainAssignmentValue ent = Domain.Assignment (Text.unpack $ assignmentName ent) (Text.unpack $ assignmentDescription ent) (decodeAssignmentType $ assignmentType ent) (assignmentStart ent) (assignmentEnd ent) (decodeEvalConfig $ assignmentEvalConfig ent) fromDomainAssignmentValue createdTime = Domain.assignmentCata $ \name desc type_ start end cfg -> Assignment (Text.pack name) (Text.pack desc) (encodeAssignmentType type_) start end createdTime (encodeEvalConfig cfg) -- Lists all the assignments in the database assignmentKeys :: Persist [Domain.AssignmentKey] assignmentKeys = map toDomainKey <$> selectAssignmentKeys where selectAssignmentKeys :: Persist [Key Assignment] selectAssignmentKeys = selectKeysList [] [] -- Save the assignment into the database saveAssignment :: Domain.Assignment -> Persist Domain.AssignmentKey saveAssignment assignment = do now <- liftIO $ getCurrentTime key <- insert (fromDomainAssignmentValue now assignment) return $! toDomainKey key -- Load the assignment from the database loadAssignment :: Domain.AssignmentKey -> Persist Domain.Assignment loadAssignment key = do mAsg <- get (toEntityKey key) return $! maybe (persistError "loadAssignment" $ "No assignment is found. " ++ show key) toDomainAssignmentValue mAsg -- Modify the assignment in the database for the given key modifyAssignment :: Domain.AssignmentKey -> Domain.Assignment -> Persist () modifyAssignment key assignment = do update (toEntityKey key) $ Domain.withAssignment assignment $ \name desc type_ start end cfg -> [ AssignmentName =. Text.pack name , AssignmentDescription =. Text.pack desc , AssignmentType =. encodeAssignmentType type_ , AssignmentStart =. start , AssignmentEnd =. end , AssignmentEvalConfig =. encodeEvalConfig cfg ] -- Lists all the assignment that are created for the given course courseAssignments :: Domain.CourseKey -> Persist [Domain.AssignmentKey] courseAssignments courseKey = do assignments <- selectList [AssignmentsOfCourseCourse ==. toEntityKey courseKey] [] return $! map (toDomainKey . assignmentsOfCourseAssignment . entityVal) assignments -- Lists all the assignment that are created for the given group groupAssignments :: Domain.GroupKey -> Persist [Domain.AssignmentKey] groupAssignments groupKey = do assignments <- selectList [AssignmentsOfGroupGroup ==. toEntityKey groupKey] [] return $! map (toDomainKey . assignmentsOfGroupAssignment . entityVal) assignments -- Save the assignment for the given course saveCourseAssignment :: Domain.CourseKey -> Domain.Assignment -> Persist Domain.AssignmentKey saveCourseAssignment courseKey assignment = do now <- liftIO $ getCurrentTime key <- insert (fromDomainAssignmentValue now assignment) insertUnique (AssignmentsOfCourse (toEntityKey courseKey) key) return $! toDomainKey key -- Save the assignment for the given group saveGroupAssignment :: Domain.GroupKey -> Domain.Assignment -> Persist Domain.AssignmentKey saveGroupAssignment groupKey assignment = do now <- liftIO $ getCurrentTime key <- insert (fromDomainAssignmentValue now assignment) insertUnique (AssignmentsOfGroup (toEntityKey groupKey) key) return $! toDomainKey key -- Returns (Just courseKey) the course key of the assignment if the assignment -- is a course assignment otherwise Nothing courseOfAssignment :: Domain.AssignmentKey -> Persist (Maybe Domain.CourseKey) courseOfAssignment key = do courses <- selectList [AssignmentsOfCourseAssignment ==. toEntityKey key] [] return $! fmap (toDomainKey . assignmentsOfCourseCourse . entityVal) (listToMaybe courses) -- Returns (Just groupKey) the group key of the assignment if the assignment -- is a group assignment otherwise Nothing groupOfAssignment :: Domain.AssignmentKey -> Persist (Maybe Domain.GroupKey) groupOfAssignment key = do groups <- selectList [AssignmentsOfGroupAssignment ==. toEntityKey key] [] return $! fmap (toDomainKey . assignmentsOfGroupGroup . entityVal) (listToMaybe groups) -- Returns all the submissions for the given assignment -- TODO: Test submissionsForAssignment :: Domain.AssignmentKey -> Persist [Domain.SubmissionKey] submissionsForAssignment key = do submissions <- selectList [SubmissionsOfAssignmentAssignment ==. toEntityKey key] [] return $! map (toDomainKey . submissionsOfAssignmentSubmission . entityVal) submissions -- Returns when the assignment was saved first, the modification of an assignment -- does not change the time stamp assignmentCreatedTime :: Domain.AssignmentKey -> Persist UTCTime assignmentCreatedTime key = do mAsg <- get (toEntityKey key) return $! maybe (persistError "assignmentCreatedTime" $ "no assignment is found" ++ show key) assignmentCreated mAsg -- Returns the test case of the assignment is if there is any attached. -- returns (Just key) if there is, otherwise Nothing testCaseOfAssignment :: Domain.AssignmentKey -> Persist (Maybe Domain.TestCaseKey) testCaseOfAssignment key = do testCases <- selectList [TestCaseOfAssignmentAssignment ==. toEntityKey key] [] return $! fmap (toDomainKey . testCaseOfAssignmentTestCase . entityVal) (listToMaybe testCases) #ifdef TEST assignmentTests = do shrink "Assignment end-to-end story" (do ioTest "Assignment end-to-end test" $ runSql $ do c <- saveCourse course g <- saveGroup c group ca <- saveCourseAssignment c asg ga <- saveGroupAssignment g asg casg' <- loadAssignment ca equals asg casg' "The saved and loaded course assignment were different." cca <- courseOfAssignment ca equals (Just c) cca "The course assignment has no appropiate course" cga <- groupOfAssignment ca equals Nothing cga "The course assignment had a group" t1 <- assignmentCreatedTime ca modifyAssignment ca asg2 t2 <- assignmentCreatedTime ca casg2 <- loadAssignment ca equals asg2 casg2 "The course assignment modification has failed" equals t1 t2 "The creation time of the course assignment has changed" gasg' <- loadAssignment ga equals asg gasg' "The saved and loaded group assignment were different." cga <- courseOfAssignment ga equals Nothing cga "The group assignment had course" gga <- groupOfAssignment ga equals (Just g) gga "The group assignment had no group" t1 <- assignmentCreatedTime ga modifyAssignment ga asg2 t2 <- assignmentCreatedTime ga gasg2 <- loadAssignment ga equals asg2 gasg2 "The course assignment modification has failed" equals t1 t2 "The creation time of the group assignment has changed" ) (do ioTest "Save and load course assignment" $ runSql $ do c <- saveCourse course ca <- saveCourseAssignment c asg casg' <- loadAssignment ca equals asg casg' "The saved and loaded course assignment were different." cca <- courseOfAssignment ca equals (Just c) cca "The course assignment has no appropiate course" cga <- groupOfAssignment ca equals Nothing cga "The course assignment had a group" ioTest "Save and load group assignment" $ runSql $ do c <- saveCourse course g <- saveGroup c group ga <- saveGroupAssignment g asg gasg' <- loadAssignment ga equals asg gasg' "The saved and loaded group assignment were different." cca <- courseOfAssignment ga equals Nothing cca "The group assignment had a course" cga <- groupOfAssignment ga equals (Just g) cga "The group assignment had no appropiate group" ioTest "Modify course assignment" $ runSql $ do c <- saveCourse course ca <- saveCourseAssignment c asg t1 <- assignmentCreatedTime ca modifyAssignment ca asg2 t2 <- assignmentCreatedTime ca asg' <- loadAssignment ca equals asg2 asg' "The modification of the course assignment has failed" equals t1 t2 "The creation time of the course assignment has changed" ioTest "Modify group assignment" $ runSql $ do c <- saveCourse course g <- saveGroup c group ga <- saveGroupAssignment g asg t1 <- assignmentCreatedTime ga modifyAssignment ga asg2 t2 <- assignmentCreatedTime ga asg' <- loadAssignment ga equals asg2 asg' "The modification of the group assignment has failed" equals t1 t2 "The creation time of the group assignment has changed" ) ioTest "List course assignments" $ runSql $ do c <- saveCourse course as <- courseAssignments c equals [] as "The course had some assignment after the creation" a1 <- saveCourseAssignment c asg as <- courseAssignments c equals (Set.fromList [a1]) (Set.fromList as) "The course had different assignment set" a2 <- saveCourseAssignment c asg as <- courseAssignments c equals (Set.fromList [a1,a2]) (Set.fromList as) "The course had different assignment set" ioTest "List group assignments" $ runSql $ do c <- saveCourse course g <- saveGroup c group as <- groupAssignments g equals [] as "The group had some assignment after the creation" a1 <- saveGroupAssignment g asg as <- groupAssignments g equals (Set.fromList [a1]) (Set.fromList as) "The group had different assignment set" a2 <- saveGroupAssignment g asg as <- groupAssignments g equals (Set.fromList [a1,a2]) (Set.fromList as) "The group had different assignment set" #endif
andorp/bead
src/Bead/Persistence/SQL/Assignment.hs
bsd-3-clause
10,868
0
16
2,512
2,428
1,152
1,276
104
1
{-# LANGUAGE CPP #-} {-# LANGUAGE OverloadedStrings #-} module Program.Mighty.Process ( getMightyPid ) where import Control.Monad.Trans.Resource (runResourceT) import Data.ByteString.Char8 (ByteString) import qualified Data.ByteString.Char8 as BS import Data.Conduit import qualified Data.Conduit.Binary as CB import qualified Data.Conduit.List as CL import Data.Conduit.Process import Data.Function import Data.List import System.Posix.Types ---------------------------------------------------------------- data PsResult = PsResult { uid :: ByteString , pid :: ProcessID , ppid :: ProcessID , command :: ByteString } deriving (Eq, Show) toPsResult :: [ByteString] -> PsResult toPsResult (a:b:c:_:_:_:_:h:_) = PsResult { uid = a , pid = maybe 0 (fromIntegral . fst) $ BS.readInt b , ppid = maybe 0 (fromIntegral . fst) $ BS.readInt c , command = h } toPsResult _ = PsResult "unknown" 0 0 "unknown" ---------------------------------------------------------------- runPS :: IO [PsResult] runPS = snd <$> runResourceT (sourceCmdWithConsumer "ps -ef" consumer) where consumer = CB.lines .| CL.map BS.words .| CL.map toPsResult .| CL.filter mighty .| CL.consume commandName = last . split '/' . command mighty ps = "mighty" `BS.isInfixOf` name && not ("mightyctl" `BS.isInfixOf` name) where name = commandName ps ---------------------------------------------------------------- findParent :: [PsResult] -> [PsResult] findParent ps = deleteAloneChild $ masters ++ candidates where iAmMaster p = ppid p == 1 masters = filter iAmMaster ps rest = filter (not.iAmMaster) ps candidates = map head $ filter (\xs -> length xs == 1) -- master is alone $ groupBy ((==) `on` ppid) $ sortOn ppid rest deleteAloneChild :: [PsResult] -> [PsResult] deleteAloneChild [] = [] deleteAloneChild (p:ps) = p : deleteAloneChild (filter noParent ps) where parent = pid p noParent x = ppid x /= parent ---------------------------------------------------------------- -- | Getting the process id of a running Mighty. getMightyPid :: IO [ProcessID] getMightyPid = map pid . findParent <$> runPS ---------------------------------------------------------------- split :: Char -> ByteString -> [ByteString] split _ "" = [] split c s = case BS.break (c==) s of ("",r) -> split c (BS.tail r) (s',"") -> [s'] (s',r) -> s' : split c (BS.tail r)
kazu-yamamoto/mighttpd2
Program/Mighty/Process.hs
bsd-3-clause
2,546
0
14
559
778
429
349
60
3
{-# LANGUAGE TypeFamilies #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE EmptyDataDecls #-} {-# LANGUAGE UndecidableInstances, OverlappingInstances, FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE DeriveFunctor, DeriveFoldable, DeriveTraversable #-} {-# LANGUAGE ExistentialQuantification #-} ----------------------------------------------------------------------------- -- | -- Module : MuTerm.Framework.DotRep -- Copyright : (c) muterm development team -- License : see LICENSE -- -- Maintainer : jiborra@dsic.upv.es -- Stability : unstable -- Portability : non-portable -- -- ----------------------------------------------------------------------------- module MuTerm.Framework.DotRep ( module MuTerm.Framework.DotRep, module Data.GraphViz.Attributes) where import Control.Applicative import qualified Data.Graph import Data.GraphViz.Attributes import Data.Graph.Inductive --import Data.Graph.Inductive.Tree import Data.Suitable import Text.PrettyPrint.HughesPJClass import MuTerm.Framework.Proof import Debug.Hoed.Observe class DotRep a where dot, dotSimple :: a -> DotGr dotSimple = dot dot = dotSimple -- | Dummy default instance instance Pretty a => DotRep a where dot x = Text (pPrint x) [] type DotGr = DotGrF (Gr [Attribute] [Attribute]) data DotGrF a = Text Doc [Attribute] | Nodes { nodes :: a , legend :: Maybe (Doc,[Attribute]) , attributes :: [Attribute] , incoming, outgoing :: Node} defaultDot x = Text (pPrint x) [] mkColor x = [ColorName x] label l = Label (StrLabel ('\"' : renderDot l ++ "\"")) renderDot :: Doc -> String renderDot doc = concatMap escapeNewLines txt where txt = renderStyle style{lineLength=80} (doc <> text "\\l") escapeNewLines '\n' = "\\l" escapeNewLines c = [c] -- ------------------------ -- *Info constraints -- ------------------------ -- | Dot instance witness newtype DotF a = DotF a deriving (Functor, DotRep, Pretty) instance Applicative DotF where pure = DotF DotF f <*> DotF a = DotF (f a) data instance Constraints DotF a = DotRep a => DotConstraint instance DotRep p => Suitable DotF p where constraints = DotConstraint instance DotRep (SomeInfo DotF) where dot (SomeInfo p) = withConstraintsOf p $ \DotConstraint -> dot p dotSimple (SomeInfo p) = withConstraintsOf p $ \DotConstraint -> dotSimple p -- Tuple instances -- instance DotRep (SomeInfo (DotInfo, a)) where -- dot (SomeInfo (p::p)) = withInfoOf p $ \(DotInfo :^: (_::InfoConstraints a p)) -> dot p -- dotSimple (SomeInfo (p::p)) = withInfoOf p $ \(DotInfo :^: (_::InfoConstraints a p)) -> dotSimple p -- instance DotRep (SomeInfo (a,DotInfo)) where -- dot (SomeInfo (p::p)) = withInfoOf p $ \((x::InfoConstraints a p) :^: DotInfo) -> dot p -- dotSimple (SomeInfo (p::p)) = withInfoOf p $ \((x::InfoConstraints a p) :^: DotInfo) -> dotSimple p
pepeiborra/muterm-framework-charts
MuTerm/Framework/DotRep.hs
bsd-3-clause
3,035
0
11
585
567
322
245
47
2
module Day18 where import qualified Data.HashMap.Strict as M import Data.Maybe {- Day 18: Like a GIF For Your Yard -} type Coord = (Int,Int) data LightStatus = LightOpen | LightClosed deriving (Show, Eq) type Grid = M.HashMap Coord LightStatus parseGrid :: String -> Grid parseGrid = fst . foldl parseChar (M.empty, (0,0)) where parseChar (z,(_,y)) '\n' = (z, (0,y+1)) parseChar (z,c@(x,y)) '#' = (M.insert c LightOpen z, (x+1,y)) parseChar (z,c@(x,y)) '.' = (M.insert c LightClosed z, (x+1,y)) parseChar _ _ = error "parsing error" countNeighborsOn :: Coord -> Grid -> Int countNeighborsOn (x,y) g = length $ filter (==LightOpen) [ fromMaybe LightClosed $ M.lookup (x-1,y-1) g , fromMaybe LightClosed $ M.lookup (x,y-1) g , fromMaybe LightClosed $ M.lookup (x+1,y-1) g , fromMaybe LightClosed $ M.lookup (x+1,y) g , fromMaybe LightClosed $ M.lookup (x+1,y+1) g , fromMaybe LightClosed $ M.lookup (x,y+1) g , fromMaybe LightClosed $ M.lookup (x-1,y+1) g , fromMaybe LightClosed $ M.lookup (x-1,y) g ] step :: Grid -> Grid step g = M.mapWithKey f g where f c LightOpen = case countNeighborsOn c g of 2 -> LightOpen 3 -> LightOpen _ -> LightClosed f c LightClosed = case countNeighborsOn c g of 3 -> LightOpen _ -> LightClosed stepX :: Int -> Grid -> Grid stepX n g = iterate step g !! n countLights :: Grid -> Int countLights = M.size . M.filter (==LightOpen) day18 :: IO () day18 = do fileStr <- readFile "resources/day18.txt" print $ countLights $ stepX 100 $ parseGrid fileStr {- Part Two -} cornerify :: Grid -> Grid cornerify = M.adjust (const LightOpen) (0,0) . M.adjust (const LightOpen) (0,99) . M.adjust (const LightOpen) (99,0) . M.adjust (const LightOpen) (99,99) stepX' :: Int -> Grid -> Grid stepX' n g = iterate (cornerify . step) (cornerify g) !! n day18' :: IO () day18' = do fileStr <- readFile "resources/day18.txt" print $ countLights $ stepX' 100 $ parseGrid fileStr
Rydgel/advent-of-code
src/Day18.hs
bsd-3-clause
2,144
0
11
575
924
491
433
50
5
{-# LANGUAGE CPP, BangPatterns, DoAndIfThenElse, RecordWildCards #-} {-# LANGUAGE DeriveDataTypeable, GeneralizedNewtypeDeriving #-} ------------------------------------------------------------------------------ -- | -- Module: Database.PostgreSQL.Simple.Internal -- Copyright: (c) 2011-2015 Leon P Smith -- License: BSD3 -- Maintainer: Leon P Smith <leon@melding-monads.com> -- Stability: experimental -- -- Internal bits. This interface is less stable and can change at any time. -- In particular this means that while the rest of the postgresql-simple -- package endeavors to follow the package versioning policy, this module -- does not. Also, at the moment there are things in here that aren't -- particularly internal and are exported elsewhere; these will eventually -- disappear from this module. -- ------------------------------------------------------------------------------ module Database.PostgreSQL.Simple.Internal where import Control.Applicative import Control.Exception import Control.Concurrent.MVar import Control.Monad(MonadPlus(..)) import Data.ByteString(ByteString) import qualified Data.ByteString as B import qualified Data.ByteString.Char8 as B8 import Data.ByteString.Builder ( Builder, byteString ) import Data.Char (ord) import Data.Int (Int64) import qualified Data.IntMap as IntMap import Data.IORef import Data.Maybe(fromMaybe) import Data.Monoid import Data.String import qualified Data.Text as T import qualified Data.Text.Encoding as TE import Data.Typeable import Data.Word import Database.PostgreSQL.LibPQ(Oid(..)) import qualified Database.PostgreSQL.LibPQ as PQ import Database.PostgreSQL.LibPQ(ExecStatus(..)) import Database.PostgreSQL.Simple.Compat ( toByteString ) import Database.PostgreSQL.Simple.Ok import Database.PostgreSQL.Simple.ToField (Action(..), inQuotes) import Database.PostgreSQL.Simple.Types (Query(..)) import Database.PostgreSQL.Simple.TypeInfo.Types(TypeInfo) import Control.Monad.Trans.State.Strict import Control.Monad.Trans.Reader import Control.Monad.Trans.Class import GHC.IO.Exception #if !defined(mingw32_HOST_OS) import Control.Concurrent(threadWaitRead, threadWaitWrite) #endif -- | A Field represents metadata about a particular field -- -- You don't particularly want to retain these structures for a long -- period of time, as they will retain the entire query result, not -- just the field metadata data Field = Field { result :: !PQ.Result , column :: {-# UNPACK #-} !PQ.Column , typeOid :: {-# UNPACK #-} !PQ.Oid -- ^ This returns the type oid associated with the column. Analogous -- to libpq's @PQftype@. } type TypeInfoCache = IntMap.IntMap TypeInfo data Connection = Connection { connectionHandle :: {-# UNPACK #-} !(MVar PQ.Connection) , connectionObjects :: {-# UNPACK #-} !(MVar TypeInfoCache) , connectionTempNameCounter :: {-# UNPACK #-} !(IORef Int64) } deriving (Typeable) instance Eq Connection where x == y = connectionHandle x == connectionHandle y data SqlError = SqlError { sqlState :: ByteString , sqlExecStatus :: ExecStatus , sqlErrorMsg :: ByteString , sqlErrorDetail :: ByteString , sqlErrorHint :: ByteString } deriving (Show, Typeable) fatalError :: ByteString -> SqlError fatalError msg = SqlError "" FatalError msg "" "" instance Exception SqlError -- | Exception thrown if 'query' is used to perform an @INSERT@-like -- operation, or 'execute' is used to perform a @SELECT@-like operation. data QueryError = QueryError { qeMessage :: String , qeQuery :: Query } deriving (Eq, Show, Typeable) instance Exception QueryError -- | Exception thrown if a 'Query' could not be formatted correctly. -- This may occur if the number of \'@?@\' characters in the query -- string does not match the number of parameters provided. data FormatError = FormatError { fmtMessage :: String , fmtQuery :: Query , fmtParams :: [ByteString] } deriving (Eq, Show, Typeable) instance Exception FormatError data ConnectInfo = ConnectInfo { connectHost :: String , connectPort :: Word16 , connectUser :: String , connectPassword :: String , connectDatabase :: String } deriving (Eq,Read,Show,Typeable) -- | Default information for setting up a connection. -- -- Defaults are as follows: -- -- * Server on @localhost@ -- -- * Port on @5432@ -- -- * User @postgres@ -- -- * No password -- -- * Database @postgres@ -- -- Use as in the following example: -- -- > connect defaultConnectInfo { connectHost = "db.example.com" } defaultConnectInfo :: ConnectInfo defaultConnectInfo = ConnectInfo { connectHost = "127.0.0.1" , connectPort = 5432 , connectUser = "postgres" , connectPassword = "" , connectDatabase = "" } -- | Connect with the given username to the given database. Will throw -- an exception if it cannot connect. connect :: ConnectInfo -> IO Connection connect = connectPostgreSQL . postgreSQLConnectionString -- | Attempt to make a connection based on a libpq connection string. -- See <http://www.postgresql.org/docs/9.3/static/libpq-connect.html#LIBPQ-CONNSTRING> -- for more information. Also note that environment variables also affect -- parameters not provided, parameters provided as the empty string, and a -- few other things; see <http://www.postgresql.org/docs/9.3/static/libpq-envars.html> -- for details. Here is an example with some of the most commonly used -- parameters: -- -- > host='db.somedomain.com' port=5432 ... -- -- This attempts to connect to @db.somedomain.com:5432@. Omitting the port -- will normally default to 5432. -- -- On systems that provide unix domain sockets, omitting the host parameter -- will cause libpq to attempt to connect via unix domain sockets. -- The default filesystem path to the socket is constructed from the -- port number and the @DEFAULT_PGSOCKET_DIR@ constant defined in the -- @pg_config_manual.h@ header file. Connecting via unix sockets tends -- to use the @peer@ authentication method, which is very secure and -- does not require a password. -- -- On Windows and other systems without unix domain sockets, omitting -- the host will default to @localhost@. -- -- > ... dbname='postgres' user='postgres' password='secret \' \\ pw' -- -- This attempts to connect to a database named @postgres@ with -- user @postgres@ and password @secret \' \\ pw@. Backslash -- characters will have to be double-quoted in literal Haskell strings, -- of course. Omitting @dbname@ and @user@ will both default to the -- system username that the client process is running as. -- -- Omitting @password@ will default to an appropriate password found -- in the @pgpass@ file, or no password at all if a matching line is -- not found. See -- <http://www.postgresql.org/docs/9.3/static/libpq-pgpass.html> for -- more information regarding this file. -- -- As all parameters are optional and the defaults are sensible, the -- empty connection string can be useful for development and -- exploratory use, assuming your system is set up appropriately. -- -- On Unix, such a setup would typically consist of a local -- postgresql server listening on port 5432, as well as a system user, -- database user, and database sharing a common name, with permissions -- granted to the user on the database. -- -- On Windows, in addition you will either need @pg_hba.conf@ -- to specify the use of the @trust@ authentication method for -- the connection, which may not be appropriate for multiuser -- or production machines, or you will need to use a @pgpass@ file -- with the @password@ or @md5@ authentication methods. -- -- See <http://www.postgresql.org/docs/9.3/static/client-authentication.html> -- for more information regarding the authentication process. -- -- SSL/TLS will typically "just work" if your postgresql server supports or -- requires it. However, note that libpq is trivially vulnerable to a MITM -- attack without setting additional SSL parameters in the connection string. -- In particular, @sslmode@ needs to be set to @require@, @verify-ca@, or -- @verify-full@ in order to perform certificate validation. When @sslmode@ -- is @require@, then you will also need to specify a @sslrootcert@ file, -- otherwise no validation of the server's identity will be performed. -- Client authentication via certificates is also possible via the -- @sslcert@ and @sslkey@ parameters. connectPostgreSQL :: ByteString -> IO Connection connectPostgreSQL connstr = do conn <- connectdb connstr stat <- PQ.status conn case stat of PQ.ConnectionOk -> do connectionHandle <- newMVar conn connectionObjects <- newMVar (IntMap.empty) connectionTempNameCounter <- newIORef 0 let wconn = Connection{..} version <- PQ.serverVersion conn let settings | version < 80200 = "SET datestyle TO ISO;SET client_encoding TO UTF8" | otherwise = "SET datestyle TO ISO;SET client_encoding TO UTF8;SET standard_conforming_strings TO on" _ <- execute_ wconn settings return wconn _ -> do msg <- maybe "connectPostgreSQL error" id <$> PQ.errorMessage conn throwIO $ fatalError msg connectdb :: ByteString -> IO PQ.Connection #if defined(mingw32_HOST_OS) connectdb = PQ.connectdb #else connectdb conninfo = do conn <- PQ.connectStart conninfo loop conn where funcName = "Database.PostgreSQL.Simple.connectPostgreSQL" loop conn = do status <- PQ.connectPoll conn case status of PQ.PollingFailed -> throwLibPQError conn "connection failed" PQ.PollingReading -> do mfd <- PQ.socket conn case mfd of Nothing -> throwIO $! fdError funcName Just fd -> do threadWaitRead fd loop conn PQ.PollingWriting -> do mfd <- PQ.socket conn case mfd of Nothing -> throwIO $! fdError funcName Just fd -> do threadWaitWrite fd loop conn PQ.PollingOk -> return conn #endif -- | Turns a 'ConnectInfo' data structure into a libpq connection string. postgreSQLConnectionString :: ConnectInfo -> ByteString postgreSQLConnectionString connectInfo = fromString connstr where connstr = str "host=" connectHost $ num "port=" connectPort $ str "user=" connectUser $ str "password=" connectPassword $ str "dbname=" connectDatabase $ [] str name field | null value = id | otherwise = showString name . quote value . space where value = field connectInfo num name field | value <= 0 = id | otherwise = showString name . shows value . space where value = field connectInfo quote str rest = '\'' : foldr delta ('\'' : rest) str where delta c cs = case c of '\\' -> '\\' : '\\' : cs '\'' -> '\\' : '\'' : cs _ -> c : cs space [] = [] space xs = ' ':xs oid2int :: Oid -> Int oid2int (Oid x) = fromIntegral x {-# INLINE oid2int #-} exec :: Connection -> ByteString -> IO PQ.Result #if defined(mingw32_HOST_OS) exec conn sql = withConnection conn $ \h -> do mres <- PQ.exec h sql case mres of Nothing -> throwLibPQError h "PQexec returned no results" Just res -> return res #else exec conn sql = withConnection conn $ \h -> do success <- PQ.sendQuery h sql if success then awaitResult h Nothing else throwLibPQError h "PQsendQuery failed" where awaitResult h mres = do mfd <- PQ.socket h case mfd of Nothing -> throwIO $! fdError "Database.PostgreSQL.Simple.Internal.exec" Just fd -> do threadWaitRead fd _ <- PQ.consumeInput h -- FIXME? getResult h mres getResult h mres = do isBusy <- PQ.isBusy h if isBusy then awaitResult h mres else do mres' <- PQ.getResult h case mres' of Nothing -> case mres of Nothing -> throwLibPQError h "PQgetResult returned no results" Just res -> return res Just res -> do status <- PQ.resultStatus res case status of PQ.EmptyQuery -> getResult h mres' PQ.CommandOk -> getResult h mres' PQ.TuplesOk -> getResult h mres' PQ.CopyOut -> return res PQ.CopyIn -> return res PQ.BadResponse -> getResult h mres' PQ.NonfatalError -> getResult h mres' PQ.FatalError -> getResult h mres' #endif -- | A version of 'execute' that does not perform query substitution. execute_ :: Connection -> Query -> IO Int64 execute_ conn q@(Query stmt) = do result <- exec conn stmt finishExecute conn q result finishExecute :: Connection -> Query -> PQ.Result -> IO Int64 finishExecute _conn q result = do status <- PQ.resultStatus result case status of PQ.EmptyQuery -> throwIO $ QueryError "execute: Empty query" q PQ.CommandOk -> do ncols <- PQ.nfields result if ncols /= 0 then throwIO $ QueryError ("execute resulted in " ++ show ncols ++ "-column result") q else do nstr <- PQ.cmdTuples result return $ case nstr of Nothing -> 0 -- is this appropriate? Just str -> toInteger str PQ.TuplesOk -> do ncols <- PQ.nfields result throwIO $ QueryError ("execute resulted in " ++ show ncols ++ "-column result") q PQ.CopyOut -> throwIO $ QueryError "execute: COPY TO is not supported" q PQ.CopyIn -> throwIO $ QueryError "execute: COPY FROM is not supported" q PQ.BadResponse -> throwResultError "execute" result status PQ.NonfatalError -> throwResultError "execute" result status PQ.FatalError -> throwResultError "execute" result status where toInteger str = B8.foldl' delta 0 str where delta acc c = if '0' <= c && c <= '9' then 10 * acc + fromIntegral (ord c - ord '0') else error ("finishExecute: not an int: " ++ B8.unpack str) throwResultError :: ByteString -> PQ.Result -> PQ.ExecStatus -> IO a throwResultError _ result status = do errormsg <- fromMaybe "" <$> PQ.resultErrorField result PQ.DiagMessagePrimary detail <- fromMaybe "" <$> PQ.resultErrorField result PQ.DiagMessageDetail hint <- fromMaybe "" <$> PQ.resultErrorField result PQ.DiagMessageHint state <- maybe "" id <$> PQ.resultErrorField result PQ.DiagSqlstate throwIO $ SqlError { sqlState = state , sqlExecStatus = status , sqlErrorMsg = errormsg , sqlErrorDetail = detail , sqlErrorHint = hint } disconnectedError :: SqlError disconnectedError = fatalError "connection disconnected" -- | Atomically perform an action with the database handle, if there is one. withConnection :: Connection -> (PQ.Connection -> IO a) -> IO a withConnection Connection{..} m = do withMVar connectionHandle $ \conn -> do if PQ.isNullConnection conn then throwIO disconnectedError else m conn close :: Connection -> IO () close Connection{..} = mask $ \restore -> (do conn <- takeMVar connectionHandle restore (PQ.finish conn) `finally` do putMVar connectionHandle =<< PQ.newNullConnection ) newNullConnection :: IO Connection newNullConnection = do connectionHandle <- newMVar =<< PQ.newNullConnection connectionObjects <- newMVar IntMap.empty connectionTempNameCounter <- newIORef 0 return Connection{..} data Row = Row { row :: {-# UNPACK #-} !PQ.Row , rowresult :: !PQ.Result } newtype RowParser a = RP { unRP :: ReaderT Row (StateT PQ.Column Conversion) a } deriving ( Functor, Applicative, Alternative, Monad ) liftRowParser :: IO a -> RowParser a liftRowParser = RP . lift . lift . liftConversion newtype Conversion a = Conversion { runConversion :: Connection -> IO (Ok a) } liftConversion :: IO a -> Conversion a liftConversion m = Conversion (\_ -> Ok <$> m) instance Functor Conversion where fmap f m = Conversion $ \conn -> (fmap . fmap) f (runConversion m conn) instance Applicative Conversion where pure a = Conversion $ \_conn -> pure (pure a) mf <*> ma = Conversion $ \conn -> do okf <- runConversion mf conn case okf of Ok f -> (fmap . fmap) f (runConversion ma conn) Errors errs -> return (Errors errs) instance Alternative Conversion where empty = Conversion $ \_conn -> pure empty ma <|> mb = Conversion $ \conn -> do oka <- runConversion ma conn case oka of Ok _ -> return oka Errors _ -> (oka <|>) <$> runConversion mb conn instance Monad Conversion where #if !(MIN_VERSION_base(4,8,0)) return = pure #endif m >>= f = Conversion $ \conn -> do oka <- runConversion m conn case oka of Ok a -> runConversion (f a) conn Errors err -> return (Errors err) instance MonadPlus Conversion where mzero = empty mplus = (<|>) conversionMap :: (Ok a -> Ok b) -> Conversion a -> Conversion b conversionMap f m = Conversion $ \conn -> f <$> runConversion m conn conversionError :: Exception err => err -> Conversion a conversionError err = Conversion $ \_ -> return (Errors [SomeException err]) newTempName :: Connection -> IO Query newTempName Connection{..} = do !n <- atomicModifyIORef connectionTempNameCounter (\n -> let !n' = n+1 in (n', n')) return $! Query $ B8.pack $ "temp" ++ show n -- FIXME? What error should getNotification and getCopyData throw? fdError :: ByteString -> IOError fdError funcName = IOError { ioe_handle = Nothing, ioe_type = ResourceVanished, ioe_location = B8.unpack funcName, ioe_description = "failed to fetch file descriptor", ioe_errno = Nothing, ioe_filename = Nothing } libPQError :: ByteString -> IOError libPQError desc = IOError { ioe_handle = Nothing, ioe_type = OtherError, ioe_location = "libpq", ioe_description = B8.unpack desc, ioe_errno = Nothing, ioe_filename = Nothing } throwLibPQError :: PQ.Connection -> ByteString -> IO a throwLibPQError conn default_desc = do msg <- maybe default_desc id <$> PQ.errorMessage conn throwIO $! libPQError msg fmtError :: String -> Query -> [Action] -> a fmtError msg q xs = throw FormatError { fmtMessage = msg , fmtQuery = q , fmtParams = map twiddle xs } where twiddle (Plain b) = toByteString b twiddle (Escape s) = s twiddle (EscapeByteA s) = s twiddle (EscapeIdentifier s) = s twiddle (Many ys) = B.concat (map twiddle ys) fmtErrorBs :: Query -> [Action] -> ByteString -> a fmtErrorBs q xs msg = fmtError (T.unpack $ TE.decodeUtf8 msg) q xs -- | Quote bytestring or throw 'FormatError' quote :: Query -> [Action] -> Either ByteString ByteString -> Builder quote q xs = either (fmtErrorBs q xs) (inQuotes . byteString) buildAction :: Connection -- ^ Connection for string escaping -> Query -- ^ Query for message error -> [Action] -- ^ List of parameters for message error -> Action -- ^ Action to build -> IO Builder buildAction _ _ _ (Plain b) = pure b buildAction conn q xs (Escape s) = quote q xs <$> escapeStringConn conn s buildAction conn q xs (EscapeByteA s) = quote q xs <$> escapeByteaConn conn s buildAction conn q xs (EscapeIdentifier s) = either (fmtErrorBs q xs) byteString <$> escapeIdentifier conn s buildAction conn q xs (Many ys) = mconcat <$> mapM (buildAction conn q xs) ys checkError :: PQ.Connection -> Maybe a -> IO (Either ByteString a) checkError _ (Just x) = return $ Right x checkError c Nothing = Left . maybe "" id <$> PQ.errorMessage c escapeWrap :: (PQ.Connection -> ByteString -> IO (Maybe ByteString)) -> Connection -> ByteString -> IO (Either ByteString ByteString) escapeWrap f conn s = withConnection conn $ \c -> f c s >>= checkError c escapeStringConn :: Connection -> ByteString -> IO (Either ByteString ByteString) escapeStringConn = escapeWrap PQ.escapeStringConn escapeIdentifier :: Connection -> ByteString -> IO (Either ByteString ByteString) escapeIdentifier = escapeWrap PQ.escapeIdentifier escapeByteaConn :: Connection -> ByteString -> IO (Either ByteString ByteString) escapeByteaConn = escapeWrap PQ.escapeByteaConn
tolysz/postgresql-simple
src/Database/PostgreSQL/Simple/Internal.hs
bsd-3-clause
22,496
0
19
6,651
3,999
2,114
1,885
372
13
module Network.XmlPush.Tls.Client ( TlsArgs(..) ) where import Data.X509 import Data.X509.CertificateStore import Network.PeyoTLS.Client import Text.XML.Pipe data TlsArgs = TlsArgs { serverName :: String, checkServerName :: Bool, checkCertificate :: XmlNode -> Maybe (SignedCertificate -> Bool), cipherSuites :: [CipherSuite], certificateAuthorities :: CertificateStore, keyChains :: [(CertSecretKey, CertificateChain)] }
YoshikuniJujo/xml-push
src/Network/XmlPush/Tls/Client.hs
bsd-3-clause
433
18
12
55
129
80
49
13
0
-- | This module is a convenience module that re-exports all the other Aurora -- configuration. Due to field name conflicts, not all fields may be exported, -- but in most common cases, you can get away with just: -- -- > import Aurora.Config -- -- In some rarer cases, you may need to add these two imports as well: -- -- > import qualified Aurora.Job as Job -- For `constraints` and `name` fields -- > import qualified Aurora.Task as Task -- For `max_failures` and `name` fields -- -- Here is an example of how to build a minimal Aurora `Job` using the provided -- types: -- -- > {-# LANGUAGE OverloadedStrings #-} -- > -- > import Aurora.Config -- > -- > job :: Job -- > job = _Job -- > { task = _Task -- > { processes = -- > [ _Process -- > { name = "hello" -- > , cmdline = "echo Hello, world!" -- > } -- > ] -- > , resources = _Resources -- > { cpu = 1 -- > , ram = 1 * gb -- > , disk = 1 * gb -- > } -- > } -- > , role = "example-role" -- > , cluster = "example-cluster" -- > , environment = "devel" -- > } -- -- You can then render the above `Job` to a valid Aurora configuration file using -- `renderJobs`: -- -- >>> Data.Text.IO.putStrLn (renderJobs [job]) -- jobs = [ Job( task = Task( processes = [ Process( name = "hello" -- , cmdline = "echo Hello, world!")] -- , resources = Resources( cpu = 1.0 -- , ram = 1073741824 -- , disk = 1073741824)) -- , role = "example-role" -- , cluster = "example-cluster" -- , environment = "devel")] -- -- Some things to note: -- -- * The `Optional` type implements `IsString`, so you can use a string literal -- wherever you see `Optional` `Text` -- * The `Optional` type implements `Num`, so you can use a numeric literal where -- you see `Optional` `Integer` or `Optional` `Double` -- * Any `Optional` field that you leave `empty` will not be rendered in the final -- Aurora config, using whatever Aurora defaults to for that field -- -- To learn more about what all the types and fields mean, read the Aurora -- configuration reference here: -- -- <http://aurora.incubator.apache.org/documentation/latest/configuration-reference/> module Aurora.Config ( -- * Render renderJobs -- * Job , Job(..) , _Job -- ** Task , Task(..) , _Task -- *** Process , Process(..) , _Process -- *** Constraint , Constraint(..) , _Constraint -- *** Resources , Resources(..) , _Resources -- ** UpdateConfig , UpdateConfig(..) , _UpdateConfig -- ** HealthCheckConfig , HealthCheckConfig(..) , _HealthCheckConfig -- ** Container , Container(..) , _Container -- *** Docker , Docker(..) , _Docker -- * Optional , Optional(..) -- * Constants , bytes , kb , mb , gb , tb -- * Re-exports , Text ) where import Data.Text (Text) import Aurora.Constants import Aurora.Constraint import Aurora.Container import Aurora.Docker import Aurora.HealthCheckConfig import Aurora.Job hiding (constraints, name) import Aurora.Optional import Aurora.Process import Aurora.Resources import Aurora.Task hiding (max_failures, name) import Aurora.UpdateConfig
Gabriel439/Haskell-Aurora-Library
src/Aurora/Config.hs
bsd-3-clause
3,541
0
5
1,102
286
215
71
39
0
{-# LANGUAGE CPP #-} module TcInteract ( solveSimpleGivens, -- Solves [EvVar],GivenLoc solveSimpleWanteds -- Solves Cts ) where #include "HsVersions.h" import BasicTypes ( infinity, IntWithInf, intGtLimit ) import HsTypes ( hsIPNameFS ) import FastString import TcCanonical import TcFlatten import VarSet import Type import Kind ( isKind ) import InstEnv( DFunInstType, lookupInstEnv, instanceDFunId ) import CoAxiom( sfInteractTop, sfInteractInert ) import Var import TcType import Name import PrelNames ( knownNatClassName, knownSymbolClassName, callStackTyConKey, typeableClassName ) import TysWiredIn ( ipClass, typeNatKind, typeSymbolKind ) import Id( idType ) import CoAxiom ( Eqn, CoAxiom(..), CoAxBranch(..), fromBranches ) import Class import TyCon import DataCon( dataConWrapId ) import FunDeps import FamInst import FamInstEnv import Inst( tyVarsOfCt ) import Unify ( tcUnifyTyWithTFs ) import TcEvidence import Outputable import TcRnTypes import TcSMonad import Bag import MonadUtils ( concatMapM ) import Data.List( partition, foldl', deleteFirstsBy ) import SrcLoc import VarEnv import Control.Monad import Maybes( isJust ) import Pair (Pair(..)) import Unique( hasKey ) import DynFlags import Util {- ********************************************************************** * * * Main Interaction Solver * * * ********************************************************************** Note [Basic Simplifier Plan] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 1. Pick an element from the WorkList if there exists one with depth less than our context-stack depth. 2. Run it down the 'stage' pipeline. Stages are: - canonicalization - inert reactions - spontaneous reactions - top-level intreactions Each stage returns a StopOrContinue and may have sideffected the inerts or worklist. The threading of the stages is as follows: - If (Stop) is returned by a stage then we start again from Step 1. - If (ContinueWith ct) is returned by a stage, we feed 'ct' on to the next stage in the pipeline. 4. If the element has survived (i.e. ContinueWith x) the last stage then we add him in the inerts and jump back to Step 1. If in Step 1 no such element exists, we have exceeded our context-stack depth and will simply fail. Note [Unflatten after solving the simple wanteds] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We unflatten after solving the wc_simples of an implication, and before attempting to float. This means that * The fsk/fmv flatten-skolems only survive during solveSimples. We don't need to worry about them across successive passes over the constraint tree. (E.g. we don't need the old ic_fsk field of an implication. * When floating an equality outwards, we don't need to worry about floating its associated flattening constraints. * Another tricky case becomes easy: Trac #4935 type instance F True a b = a type instance F False a b = b [w] F c a b ~ gamma (c ~ True) => a ~ gamma (c ~ False) => b ~ gamma Obviously this is soluble with gamma := F c a b, and unflattening will do exactly that after solving the simple constraints and before attempting the implications. Before, when we were not unflattening, we had to push Wanted funeqs in as new givens. Yuk! Another example that becomes easy: indexed_types/should_fail/T7786 [W] BuriedUnder sub k Empty ~ fsk [W] Intersect fsk inv ~ s [w] xxx[1] ~ s [W] forall[2] . (xxx[1] ~ Empty) => Intersect (BuriedUnder sub k Empty) inv ~ Empty Note [Running plugins on unflattened wanteds] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ There is an annoying mismatch between solveSimpleGivens and solveSimpleWanteds, because the latter needs to fiddle with the inert set, unflatten and zonk the wanteds. It passes the zonked wanteds to runTcPluginsWanteds, which produces a replacement set of wanteds, some additional insolubles and a flag indicating whether to go round the loop again. If so, prepareInertsForImplications is used to remove the previous wanteds (which will still be in the inert set). Note that prepareInertsForImplications will discard the insolubles, so we must keep track of them separately. -} solveSimpleGivens :: CtLoc -> [EvVar] -> TcS Cts -- Solves the givens, adding them to the inert set -- Returns any insoluble givens, which represent inaccessible code, -- taking those ones out of the inert set solveSimpleGivens loc givens | null givens -- Shortcut for common case = return emptyCts | otherwise = do { go (map mk_given_ct givens) ; takeGivenInsolubles } where mk_given_ct ev_id = mkNonCanonical (CtGiven { ctev_evar = ev_id , ctev_pred = evVarPred ev_id , ctev_loc = loc }) go givens = do { solveSimples (listToBag givens) ; new_givens <- runTcPluginsGiven ; when (notNull new_givens) (go new_givens) } solveSimpleWanteds :: Cts -> TcS WantedConstraints -- NB: 'simples' may contain /derived/ equalities, floated -- out from a nested implication. So don't discard deriveds! solveSimpleWanteds simples = do { traceTcS "solveSimples {" (ppr simples) ; dflags <- getDynFlags ; (n,wc) <- go 1 (solverIterations dflags) (emptyWC { wc_simple = simples }) ; traceTcS "solveSimples end }" $ vcat [ ptext (sLit "iterations =") <+> ppr n , ptext (sLit "residual =") <+> ppr wc ] ; return wc } where go :: Int -> IntWithInf -> WantedConstraints -> TcS (Int, WantedConstraints) go n limit wc | n `intGtLimit` limit = failTcS (hang (ptext (sLit "solveSimpleWanteds: too many iterations") <+> parens (ptext (sLit "limit =") <+> ppr limit)) 2 (vcat [ ptext (sLit "Set limit with -fsolver-iterations=n; n=0 for no limit") , ptext (sLit "Simples =") <+> ppr simples , ptext (sLit "WC =") <+> ppr wc ])) | isEmptyBag (wc_simple wc) = return (n,wc) | otherwise = do { -- Solve (unif_count, wc1) <- solve_simple_wanteds wc -- Run plugins ; (rerun_plugin, wc2) <- runTcPluginsWanted wc1 -- See Note [Running plugins on unflattened wanteds] ; if unif_count == 0 && not rerun_plugin then return (n, wc2) -- Done else do { traceTcS "solveSimple going round again:" (ppr rerun_plugin) ; go (n+1) limit wc2 } } -- Loop solve_simple_wanteds :: WantedConstraints -> TcS (Int, WantedConstraints) -- Try solving these constraints -- Affects the unification state (of course) but not the inert set solve_simple_wanteds (WC { wc_simple = simples1, wc_insol = insols1, wc_impl = implics1 }) = nestTcS $ do { solveSimples simples1 ; (implics2, tv_eqs, fun_eqs, insols2, others) <- getUnsolvedInerts ; (unif_count, unflattened_eqs) <- reportUnifications $ unflatten tv_eqs fun_eqs -- See Note [Unflatten after solving the simple wanteds] ; return ( unif_count , WC { wc_simple = others `andCts` unflattened_eqs , wc_insol = insols1 `andCts` insols2 , wc_impl = implics1 `unionBags` implics2 }) } {- Note [The solveSimpleWanteds loop] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Solving a bunch of simple constraints is done in a loop, (the 'go' loop of 'solveSimpleWanteds'): 1. Try to solve them; unflattening may lead to improvement that was not exploitable during solving 2. Try the plugin 3. If step 1 did improvement during unflattening; or if the plugin wants to run again, go back to step 1 Non-obviously, improvement can also take place during the unflattening that takes place in step (1). See TcFlatten, See Note [Unflattening can force the solver to iterate] -} -- The main solver loop implements Note [Basic Simplifier Plan] --------------------------------------------------------------- solveSimples :: Cts -> TcS () -- Returns the final InertSet in TcS -- Has no effect on work-list or residual-implications -- The constraints are initially examined in left-to-right order solveSimples cts = {-# SCC "solveSimples" #-} do { updWorkListTcS (\wl -> foldrBag extendWorkListCt wl cts) ; solve_loop } where solve_loop = {-# SCC "solve_loop" #-} do { sel <- selectNextWorkItem ; case sel of Nothing -> return () Just ct -> do { runSolverPipeline thePipeline ct ; solve_loop } } -- | Extract the (inert) givens and invoke the plugins on them. -- Remove solved givens from the inert set and emit insolubles, but -- return new work produced so that 'solveSimpleGivens' can feed it back -- into the main solver. runTcPluginsGiven :: TcS [Ct] runTcPluginsGiven = do { plugins <- getTcPlugins ; if null plugins then return [] else do { givens <- getInertGivens ; if null givens then return [] else do { p <- runTcPlugins plugins (givens,[],[]) ; let (solved_givens, _, _) = pluginSolvedCts p ; updInertCans (removeInertCts solved_givens) ; mapM_ emitInsoluble (pluginBadCts p) ; return (pluginNewCts p) } } } -- | Given a bag of (flattened, zonked) wanteds, invoke the plugins on -- them and produce an updated bag of wanteds (possibly with some new -- work) and a bag of insolubles. The boolean indicates whether -- 'solveSimpleWanteds' should feed the updated wanteds back into the -- main solver. runTcPluginsWanted :: WantedConstraints -> TcS (Bool, WantedConstraints) runTcPluginsWanted wc@(WC { wc_simple = simples1, wc_insol = insols1, wc_impl = implics1 }) | isEmptyBag simples1 = return (False, wc) | otherwise = do { plugins <- getTcPlugins ; if null plugins then return (False, wc) else do { given <- getInertGivens ; simples1 <- zonkSimples simples1 -- Plugin requires zonked inputs ; let (wanted, derived) = partition isWantedCt (bagToList simples1) ; p <- runTcPlugins plugins (given, derived, wanted) ; let (_, _, solved_wanted) = pluginSolvedCts p (_, unsolved_derived, unsolved_wanted) = pluginInputCts p new_wanted = pluginNewCts p -- SLPJ: I'm deeply suspicious of this -- ; updInertCans (removeInertCts $ solved_givens ++ solved_deriveds) ; mapM_ setEv solved_wanted ; return ( notNull (pluginNewCts p) , WC { wc_simple = listToBag new_wanted `andCts` listToBag unsolved_wanted `andCts` listToBag unsolved_derived , wc_insol = listToBag (pluginBadCts p) `andCts` insols1 , wc_impl = implics1 } ) } } where setEv :: (EvTerm,Ct) -> TcS () setEv (ev,ct) = case ctEvidence ct of CtWanted {ctev_evar = evar} -> setWantedEvBind evar ev _ -> panic "runTcPluginsWanted.setEv: attempt to solve non-wanted!" -- | A triple of (given, derived, wanted) constraints to pass to plugins type SplitCts = ([Ct], [Ct], [Ct]) -- | A solved triple of constraints, with evidence for wanteds type SolvedCts = ([Ct], [Ct], [(EvTerm,Ct)]) -- | Represents collections of constraints generated by typechecker -- plugins data TcPluginProgress = TcPluginProgress { pluginInputCts :: SplitCts -- ^ Original inputs to the plugins with solved/bad constraints -- removed, but otherwise unmodified , pluginSolvedCts :: SolvedCts -- ^ Constraints solved by plugins , pluginBadCts :: [Ct] -- ^ Constraints reported as insoluble by plugins , pluginNewCts :: [Ct] -- ^ New constraints emitted by plugins } getTcPlugins :: TcS [TcPluginSolver] getTcPlugins = do { tcg_env <- getGblEnv; return (tcg_tc_plugins tcg_env) } -- | Starting from a triple of (given, derived, wanted) constraints, -- invoke each of the typechecker plugins in turn and return -- -- * the remaining unmodified constraints, -- * constraints that have been solved, -- * constraints that are insoluble, and -- * new work. -- -- Note that new work generated by one plugin will not be seen by -- other plugins on this pass (but the main constraint solver will be -- re-invoked and they will see it later). There is no check that new -- work differs from the original constraints supplied to the plugin: -- the plugin itself should perform this check if necessary. runTcPlugins :: [TcPluginSolver] -> SplitCts -> TcS TcPluginProgress runTcPlugins plugins all_cts = foldM do_plugin initialProgress plugins where do_plugin :: TcPluginProgress -> TcPluginSolver -> TcS TcPluginProgress do_plugin p solver = do result <- runTcPluginTcS (uncurry3 solver (pluginInputCts p)) return $ progress p result progress :: TcPluginProgress -> TcPluginResult -> TcPluginProgress progress p (TcPluginContradiction bad_cts) = p { pluginInputCts = discard bad_cts (pluginInputCts p) , pluginBadCts = bad_cts ++ pluginBadCts p } progress p (TcPluginOk solved_cts new_cts) = p { pluginInputCts = discard (map snd solved_cts) (pluginInputCts p) , pluginSolvedCts = add solved_cts (pluginSolvedCts p) , pluginNewCts = new_cts ++ pluginNewCts p } initialProgress = TcPluginProgress all_cts ([], [], []) [] [] discard :: [Ct] -> SplitCts -> SplitCts discard cts (xs, ys, zs) = (xs `without` cts, ys `without` cts, zs `without` cts) without :: [Ct] -> [Ct] -> [Ct] without = deleteFirstsBy eqCt eqCt :: Ct -> Ct -> Bool eqCt c c' = case (ctEvidence c, ctEvidence c') of (CtGiven pred _ _, CtGiven pred' _ _) -> pred `eqType` pred' (CtWanted pred _ _, CtWanted pred' _ _) -> pred `eqType` pred' (CtDerived pred _ , CtDerived pred' _ ) -> pred `eqType` pred' (_ , _ ) -> False add :: [(EvTerm,Ct)] -> SolvedCts -> SolvedCts add xs scs = foldl' addOne scs xs addOne :: SolvedCts -> (EvTerm,Ct) -> SolvedCts addOne (givens, deriveds, wanteds) (ev,ct) = case ctEvidence ct of CtGiven {} -> (ct:givens, deriveds, wanteds) CtDerived{} -> (givens, ct:deriveds, wanteds) CtWanted {} -> (givens, deriveds, (ev,ct):wanteds) type WorkItem = Ct type SimplifierStage = WorkItem -> TcS (StopOrContinue Ct) runSolverPipeline :: [(String,SimplifierStage)] -- The pipeline -> WorkItem -- The work item -> TcS () -- Run this item down the pipeline, leaving behind new work and inerts runSolverPipeline pipeline workItem = do { initial_is <- getTcSInerts ; traceTcS "Start solver pipeline {" $ vcat [ ptext (sLit "work item = ") <+> ppr workItem , ptext (sLit "inerts = ") <+> ppr initial_is] ; bumpStepCountTcS -- One step for each constraint processed ; final_res <- run_pipeline pipeline (ContinueWith workItem) ; final_is <- getTcSInerts ; case final_res of Stop ev s -> do { traceFireTcS ev s ; traceTcS "End solver pipeline (discharged) }" (ptext (sLit "inerts =") <+> ppr final_is) ; return () } ContinueWith ct -> do { traceFireTcS (ctEvidence ct) (ptext (sLit "Kept as inert")) ; traceTcS "End solver pipeline (kept as inert) }" $ vcat [ ptext (sLit "final_item =") <+> ppr ct , pprTvBndrs (varSetElems $ tyVarsOfCt ct) , ptext (sLit "inerts =") <+> ppr final_is] ; addInertCan ct } } where run_pipeline :: [(String,SimplifierStage)] -> StopOrContinue Ct -> TcS (StopOrContinue Ct) run_pipeline [] res = return res run_pipeline _ (Stop ev s) = return (Stop ev s) run_pipeline ((stg_name,stg):stgs) (ContinueWith ct) = do { traceTcS ("runStage " ++ stg_name ++ " {") (text "workitem = " <+> ppr ct) ; res <- stg ct ; traceTcS ("end stage " ++ stg_name ++ " }") empty ; run_pipeline stgs res } {- Example 1: Inert: {c ~ d, F a ~ t, b ~ Int, a ~ ty} (all given) Reagent: a ~ [b] (given) React with (c~d) ==> IR (ContinueWith (a~[b])) True [] React with (F a ~ t) ==> IR (ContinueWith (a~[b])) False [F [b] ~ t] React with (b ~ Int) ==> IR (ContinueWith (a~[Int]) True [] Example 2: Inert: {c ~w d, F a ~g t, b ~w Int, a ~w ty} Reagent: a ~w [b] React with (c ~w d) ==> IR (ContinueWith (a~[b])) True [] React with (F a ~g t) ==> IR (ContinueWith (a~[b])) True [] (can't rewrite given with wanted!) etc. Example 3: Inert: {a ~ Int, F Int ~ b} (given) Reagent: F a ~ b (wanted) React with (a ~ Int) ==> IR (ContinueWith (F Int ~ b)) True [] React with (F Int ~ b) ==> IR Stop True [] -- after substituting we re-canonicalize and get nothing -} thePipeline :: [(String,SimplifierStage)] thePipeline = [ ("canonicalization", TcCanonical.canonicalize) , ("interact with inerts", interactWithInertsStage) , ("top-level reactions", topReactionsStage) ] {- ********************************************************************************* * * The interact-with-inert Stage * * ********************************************************************************* Note [The Solver Invariant] ~~~~~~~~~~~~~~~~~~~~~~~~~~~ We always add Givens first. So you might think that the solver has the invariant If the work-item is Given, then the inert item must Given But this isn't quite true. Suppose we have, c1: [W] beta ~ [alpha], c2 : [W] blah, c3 :[W] alpha ~ Int After processing the first two, we get c1: [G] beta ~ [alpha], c2 : [W] blah Now, c3 does not interact with the the given c1, so when we spontaneously solve c3, we must re-react it with the inert set. So we can attempt a reaction between inert c2 [W] and work-item c3 [G]. It *is* true that [Solver Invariant] If the work-item is Given, AND there is a reaction then the inert item must Given or, equivalently, If the work-item is Given, and the inert item is Wanted/Derived then there is no reaction -} -- Interaction result of WorkItem <~> Ct type StopNowFlag = Bool -- True <=> stop after this interaction interactWithInertsStage :: WorkItem -> TcS (StopOrContinue Ct) -- Precondition: if the workitem is a CTyEqCan then it will not be able to -- react with anything at this stage. interactWithInertsStage wi = do { inerts <- getTcSInerts ; let ics = inert_cans inerts ; case wi of CTyEqCan {} -> interactTyVarEq ics wi CFunEqCan {} -> interactFunEq ics wi CIrredEvCan {} -> interactIrred ics wi CDictCan {} -> interactDict ics wi _ -> pprPanic "interactWithInerts" (ppr wi) } -- CHoleCan are put straight into inert_frozen, so never get here -- CNonCanonical have been canonicalised data InteractResult = IRKeep -- Keep the existing inert constraint in the inert set | IRReplace -- Replace the existing inert constraint with the work item | IRDelete -- Delete the existing inert constraint from the inert set instance Outputable InteractResult where ppr IRKeep = ptext (sLit "keep") ppr IRReplace = ptext (sLit "replace") ppr IRDelete = ptext (sLit "delete") solveOneFromTheOther :: CtEvidence -- Inert -> CtEvidence -- WorkItem -> TcS (InteractResult, StopNowFlag) -- Preconditions: -- 1) inert and work item represent evidence for the /same/ predicate -- 2) ip/class/irred evidence (no coercions) only solveOneFromTheOther ev_i ev_w | isDerived ev_w -- Work item is Derived; just discard it = return (IRKeep, True) | isDerived ev_i -- The inert item is Derived, we can just throw it away, = return (IRDelete, False) -- The ev_w is inert wrt earlier inert-set items, -- so it's safe to continue on from this point | CtWanted { ctev_loc = loc_w } <- ev_w , prohibitedSuperClassSolve (ctEvLoc ev_i) loc_w = return (IRDelete, False) | CtWanted { ctev_evar = ev_id } <- ev_w -- Inert is Given or Wanted = do { setWantedEvBind ev_id (ctEvTerm ev_i) ; return (IRKeep, True) } | CtWanted { ctev_loc = loc_i } <- ev_i -- Work item is Given , prohibitedSuperClassSolve (ctEvLoc ev_w) loc_i = return (IRKeep, False) -- Just discard the un-usable Given -- This never actually happens because -- Givens get processed first | CtWanted { ctev_evar = ev_id } <- ev_i -- Work item is Given = do { setWantedEvBind ev_id (ctEvTerm ev_w) ; return (IRReplace, True) } -- So they are both Given -- See Note [Replacement vs keeping] | lvl_i == lvl_w = do { binds <- getTcEvBindsMap ; return (same_level_strategy binds, True) } | otherwise -- Both are Given, levels differ = return (different_level_strategy, True) where pred = ctEvPred ev_i loc_i = ctEvLoc ev_i loc_w = ctEvLoc ev_w lvl_i = ctLocLevel loc_i lvl_w = ctLocLevel loc_w different_level_strategy | isIPPred pred, lvl_w > lvl_i = IRReplace | lvl_w < lvl_i = IRReplace | otherwise = IRKeep same_level_strategy binds -- Both Given | GivenOrigin (InstSC s_i) <- ctLocOrigin loc_i = case ctLocOrigin loc_w of GivenOrigin (InstSC s_w) | s_w < s_i -> IRReplace | otherwise -> IRKeep _ -> IRReplace | GivenOrigin (InstSC {}) <- ctLocOrigin loc_w = IRKeep | has_binding binds ev_w , not (has_binding binds ev_i) = IRReplace | otherwise = IRKeep has_binding binds ev = isJust (lookupEvBind binds (ctEvId ev)) {- Note [Replacement vs keeping] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When we have two Given constraints both of type (C tys), say, which should we keep? More subtle than you might think! * Constraints come from different levels (different_level_strategy) - For implicit parameters we want to keep the innermost (deepest) one, so that it overrides the outer one. See Note [Shadowing of Implicit Parameters] - For everything else, we want to keep the outermost one. Reason: that makes it more likely that the inner one will turn out to be unused, and can be reported as redundant. See Note [Tracking redundant constraints] in TcSimplify. It transpires that using the outermost one is reponsible for an 8% performance improvement in nofib cryptarithm2, compared to just rolling the dice. I didn't investigate why. * Constaints coming from the same level (i.e. same implication) - Always get rid of InstSC ones if possible, since they are less useful for solving. If both are InstSC, choose the one with the smallest TypeSize See Note [Solving superclass constraints] in TcInstDcls - Keep the one that has a non-trivial evidence binding. Example: f :: (Eq a, Ord a) => blah then we may find [G] d3 :: Eq a [G] d2 :: Eq a with bindings d3 = sc_sel (d1::Ord a) We want to discard d2 in favour of the superclass selection from the Ord dictionary. Why? See Note [Tracking redundant constraints] in TcSimplify again. * Finally, when there is still a choice, use IRKeep rather than IRReplace, to avoid unnecessary munging of the inert set. Doing the depth-check for implicit parameters, rather than making the work item always overrride, is important. Consider data T a where { T1 :: (?x::Int) => T Int; T2 :: T a } f :: (?x::a) => T a -> Int f T1 = ?x f T2 = 3 We have a [G] (?x::a) in the inert set, and at the pattern match on T1 we add two new givens in the work-list: [G] (?x::Int) [G] (a ~ Int) Now consider these steps - process a~Int, kicking out (?x::a) - process (?x::Int), the inner given, adding to inert set - process (?x::a), the outer given, overriding the inner given Wrong! The depth-check ensures that the inner implicit parameter wins. (Actually I think that the order in which the work-list is processed means that this chain of events won't happen, but that's very fragile.) ********************************************************************************* * * interactIrred * * ********************************************************************************* -} -- Two pieces of irreducible evidence: if their types are *exactly identical* -- we can rewrite them. We can never improve using this: -- if we want ty1 :: Constraint and have ty2 :: Constraint it clearly does not -- mean that (ty1 ~ ty2) interactIrred :: InertCans -> Ct -> TcS (StopOrContinue Ct) interactIrred inerts workItem@(CIrredEvCan { cc_ev = ev_w }) | let pred = ctEvPred ev_w (matching_irreds, others) = partitionBag (\ct -> ctPred ct `tcEqType` pred) (inert_irreds inerts) , (ct_i : rest) <- bagToList matching_irreds , let ctev_i = ctEvidence ct_i = ASSERT( null rest ) do { (inert_effect, stop_now) <- solveOneFromTheOther ctev_i ev_w ; case inert_effect of IRKeep -> return () IRDelete -> updInertIrreds (\_ -> others) IRReplace -> updInertIrreds (\_ -> others `snocCts` workItem) -- These const upd's assume that solveOneFromTheOther -- has no side effects on InertCans ; if stop_now then return (Stop ev_w (ptext (sLit "Irred equal") <+> parens (ppr inert_effect))) ; else continueWith workItem } | otherwise = continueWith workItem interactIrred _ wi = pprPanic "interactIrred" (ppr wi) {- ********************************************************************************* * * interactDict * * ********************************************************************************* -} interactDict :: InertCans -> Ct -> TcS (StopOrContinue Ct) interactDict inerts workItem@(CDictCan { cc_ev = ev_w, cc_class = cls, cc_tyargs = tys }) -- don't ever try to solve CallStack IPs directly from other dicts, -- we always build new dicts instead. -- See Note [Overview of implicit CallStacks] | Just mkEvCs <- isCallStackIP (ctEvLoc ev_w) cls tys , isWanted ev_w = do let ev_cs = case lookupInertDict inerts cls tys of Just ev | isGiven ev -> mkEvCs (ctEvTerm ev) _ -> mkEvCs (EvCallStack EvCsEmpty) -- now we have ev_cs :: CallStack, but the evidence term should -- be a dictionary, so we have to coerce ev_cs to a -- dictionary for `IP ip CallStack` let ip_ty = mkClassPred cls tys let ev_tm = mkEvCast (EvCallStack ev_cs) (TcCoercion $ wrapIP ip_ty) addSolvedDict ev_w cls tys setWantedEvBind (ctEvId ev_w) ev_tm stopWith ev_w "Wanted CallStack IP" | Just ctev_i <- lookupInertDict inerts cls tys = do { (inert_effect, stop_now) <- solveOneFromTheOther ctev_i ev_w ; case inert_effect of IRKeep -> return () IRDelete -> updInertDicts $ \ ds -> delDict ds cls tys IRReplace -> updInertDicts $ \ ds -> addDict ds cls tys workItem ; if stop_now then return (Stop ev_w (ptext (sLit "Dict equal") <+> parens (ppr inert_effect))) else continueWith workItem } | cls == ipClass , isGiven ev_w = interactGivenIP inerts workItem | otherwise = do { addFunDepWork inerts ev_w cls ; continueWith workItem } interactDict _ wi = pprPanic "interactDict" (ppr wi) addFunDepWork :: InertCans -> CtEvidence -> Class -> TcS () -- Add derived constraints from type-class functional dependencies. addFunDepWork inerts work_ev cls = mapBagM_ add_fds (findDictsByClass (inert_dicts inerts) cls) -- No need to check flavour; fundeps work between -- any pair of constraints, regardless of flavour -- Importantly we don't throw workitem back in the -- worklist because this can cause loops (see #5236) where work_pred = ctEvPred work_ev work_loc = ctEvLoc work_ev add_fds inert_ct = emitFunDepDeriveds $ improveFromAnother derived_loc inert_pred work_pred -- We don't really rewrite tys2, see below _rewritten_tys2, so that's ok -- NB: We do create FDs for given to report insoluble equations that arise -- from pairs of Givens, and also because of floating when we approximate -- implications. The relevant test is: typecheck/should_fail/FDsFromGivens.hs where inert_pred = ctPred inert_ct inert_loc = ctLoc inert_ct derived_loc = work_loc { ctl_origin = FunDepOrigin1 work_pred work_loc inert_pred inert_loc } {- ********************************************************************** * * Implicit parameters * * ********************************************************************** -} interactGivenIP :: InertCans -> Ct -> TcS (StopOrContinue Ct) -- Work item is Given (?x:ty) -- See Note [Shadowing of Implicit Parameters] interactGivenIP inerts workItem@(CDictCan { cc_ev = ev, cc_class = cls , cc_tyargs = tys@(ip_str:_) }) = do { updInertCans $ \cans -> cans { inert_dicts = addDict filtered_dicts cls tys workItem } ; stopWith ev "Given IP" } where dicts = inert_dicts inerts ip_dicts = findDictsByClass dicts cls other_ip_dicts = filterBag (not . is_this_ip) ip_dicts filtered_dicts = addDictsByClass dicts cls other_ip_dicts -- Pick out any Given constraints for the same implicit parameter is_this_ip (CDictCan { cc_ev = ev, cc_tyargs = ip_str':_ }) = isGiven ev && ip_str `tcEqType` ip_str' is_this_ip _ = False interactGivenIP _ wi = pprPanic "interactGivenIP" (ppr wi) -- | Is the constraint for an implicit CallStack parameter? -- i.e. (IP "name" CallStack) isCallStackIP :: CtLoc -> Class -> [Type] -> Maybe (EvTerm -> EvCallStack) isCallStackIP loc cls tys | cls == ipClass , [_ip_name, ty] <- tys , Just (tc, _) <- splitTyConApp_maybe ty , tc `hasKey` callStackTyConKey = occOrigin (ctLocOrigin loc) | otherwise = Nothing where locSpan = ctLocSpan loc -- We only want to grab constraints that arose due to the use of an IP or a -- function call. See Note [Overview of implicit CallStacks] occOrigin (OccurrenceOf n) = Just (EvCsPushCall n locSpan) occOrigin (IPOccOrigin n) = Just (EvCsTop ('?' `consFS` hsIPNameFS n) locSpan) occOrigin _ = Nothing {- Note [Shadowing of Implicit Parameters] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider the following example: f :: (?x :: Char) => Char f = let ?x = 'a' in ?x The "let ?x = ..." generates an implication constraint of the form: ?x :: Char => ?x :: Char Furthermore, the signature for `f` also generates an implication constraint, so we end up with the following nested implication: ?x :: Char => (?x :: Char => ?x :: Char) Note that the wanted (?x :: Char) constraint may be solved in two incompatible ways: either by using the parameter from the signature, or by using the local definition. Our intention is that the local definition should "shadow" the parameter of the signature, and we implement this as follows: when we add a new *given* implicit parameter to the inert set, it replaces any existing givens for the same implicit parameter. This works for the normal cases but it has an odd side effect in some pathological programs like this: -- This is accepted, the second parameter shadows f1 :: (?x :: Int, ?x :: Char) => Char f1 = ?x -- This is rejected, the second parameter shadows f2 :: (?x :: Int, ?x :: Char) => Int f2 = ?x Both of these are actually wrong: when we try to use either one, we'll get two incompatible wnated constraints (?x :: Int, ?x :: Char), which would lead to an error. I can think of two ways to fix this: 1. Simply disallow multiple constratits for the same implicit parameter---this is never useful, and it can be detected completely syntactically. 2. Move the shadowing machinery to the location where we nest implications, and add some code here that will produce an error if we get multiple givens for the same implicit parameter. ********************************************************************** * * interactFunEq * * ********************************************************************** -} interactFunEq :: InertCans -> Ct -> TcS (StopOrContinue Ct) -- Try interacting the work item with the inert set interactFunEq inerts workItem@(CFunEqCan { cc_ev = ev, cc_fun = tc , cc_tyargs = args, cc_fsk = fsk }) | Just (CFunEqCan { cc_ev = ev_i, cc_fsk = fsk_i }) <- matching_inerts = if ev_i `canDischarge` ev then -- Rewrite work-item using inert do { traceTcS "reactFunEq (discharge work item):" $ vcat [ text "workItem =" <+> ppr workItem , text "inertItem=" <+> ppr ev_i ] ; reactFunEq ev_i fsk_i ev fsk ; stopWith ev "Inert rewrites work item" } else -- Rewrite inert using work-item ASSERT2( ev `canDischarge` ev_i, ppr ev $$ ppr ev_i ) do { traceTcS "reactFunEq (rewrite inert item):" $ vcat [ text "workItem =" <+> ppr workItem , text "inertItem=" <+> ppr ev_i ] ; updInertFunEqs $ \ feqs -> insertFunEq feqs tc args workItem -- Do the updInertFunEqs before the reactFunEq, so that -- we don't kick out the inertItem as well as consuming it! ; reactFunEq ev fsk ev_i fsk_i ; stopWith ev "Work item rewrites inert" } | otherwise -- Try improvement = do { improveLocalFunEqs loc inerts tc args fsk ; continueWith workItem } where loc = ctEvLoc ev funeqs = inert_funeqs inerts matching_inerts = findFunEqs funeqs tc args interactFunEq _ workItem = pprPanic "interactFunEq" (ppr workItem) improveLocalFunEqs :: CtLoc -> InertCans -> TyCon -> [TcType] -> TcTyVar -> TcS () -- Generate derived improvement equalities, by comparing -- the current work item with inert CFunEqs -- E.g. x + y ~ z, x + y' ~ z => [D] y ~ y' improveLocalFunEqs loc inerts fam_tc args fsk | not (null improvement_eqns) = do { traceTcS "interactFunEq improvements: " $ vcat [ ptext (sLit "Eqns:") <+> ppr improvement_eqns , ptext (sLit "Candidates:") <+> ppr funeqs_for_tc , ptext (sLit "TvEqs:") <+> ppr tv_eqs ] ; mapM_ (unifyDerived loc Nominal) improvement_eqns } | otherwise = return () where tv_eqs = inert_model inerts funeqs = inert_funeqs inerts funeqs_for_tc = findFunEqsByTyCon funeqs fam_tc rhs = lookupFlattenTyVar tv_eqs fsk -------------------- improvement_eqns | Just ops <- isBuiltInSynFamTyCon_maybe fam_tc = -- Try built-in families, notably for arithmethic concatMap (do_one_built_in ops) funeqs_for_tc | Injective injective_args <- familyTyConInjectivityInfo fam_tc = -- Try improvement from type families with injectivity annotations concatMap (do_one_injective injective_args) funeqs_for_tc | otherwise = [] -------------------- do_one_built_in ops (CFunEqCan { cc_tyargs = iargs, cc_fsk = ifsk }) = sfInteractInert ops args rhs iargs (lookupFlattenTyVar tv_eqs ifsk) do_one_built_in _ _ = pprPanic "interactFunEq 1" (ppr fam_tc) -------------------- -- See Note [Type inference for type families with injectivity] do_one_injective injective_args (CFunEqCan { cc_tyargs = iargs, cc_fsk = ifsk }) | rhs `tcEqType` lookupFlattenTyVar tv_eqs ifsk = [Pair arg iarg | (arg, iarg, True) <- zip3 args iargs injective_args ] | otherwise = [] do_one_injective _ _ = pprPanic "interactFunEq 2" (ppr fam_tc) ------------- lookupFlattenTyVar :: InertModel -> TcTyVar -> TcType -- ^ Look up a flatten-tyvar in the inert nominal TyVarEqs; -- this is used only when dealing with a CFunEqCan lookupFlattenTyVar model ftv = case lookupVarEnv model ftv of Just (CTyEqCan { cc_rhs = rhs, cc_eq_rel = NomEq }) -> rhs _ -> mkTyVarTy ftv reactFunEq :: CtEvidence -> TcTyVar -- From this :: F tys ~ fsk1 -> CtEvidence -> TcTyVar -- Solve this :: F tys ~ fsk2 -> TcS () reactFunEq from_this fsk1 (CtGiven { ctev_evar = evar, ctev_loc = loc }) fsk2 = do { let fsk_eq_co = mkTcSymCo (mkTcCoVarCo evar) `mkTcTransCo` ctEvCoercion from_this -- :: fsk2 ~ fsk1 fsk_eq_pred = mkTcEqPred (mkTyVarTy fsk2) (mkTyVarTy fsk1) ; new_ev <- newGivenEvVar loc (fsk_eq_pred, EvCoercion fsk_eq_co) ; emitWorkNC [new_ev] } reactFunEq from_this fuv1 ev fuv2 = do { traceTcS "reactFunEq" (ppr from_this $$ ppr fuv1 $$ ppr ev $$ ppr fuv2) ; dischargeFmv ev fuv2 (ctEvCoercion from_this) (mkTyVarTy fuv1) ; traceTcS "reactFunEq done" (ppr from_this $$ ppr fuv1 $$ ppr ev $$ ppr fuv2) } {- Note [Type inference for type families with injectivity] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Suppose we have a type family with an injectivity annotation: type family F a b = r | r -> b Then if we have two CFunEqCan constraints for F with the same RHS F s1 t1 ~ rhs F s2 t2 ~ rhs then we can use the injectivity to get a new Derived constraint on the injective argument [D] t1 ~ t2 That in turn can help GHC solve constraints that would otherwise require guessing. For example, consider the ambiguity check for f :: F Int b -> Int We get the constraint [W] F Int b ~ F Int beta where beta is a unification variable. Injectivity lets us pick beta ~ b. Injectivity information is also used at the call sites. For example: g = f True gives rise to [W] F Int b ~ Bool from which we can derive b. This requires looking at the defining equations of a type family, ie. finding equation with a matching RHS (Bool in this example) and infering values of type variables (b in this example) from the LHS patterns of the matching equation. For closed type families we have to perform additional apartness check for the selected equation to check that the selected is guaranteed to fire for given LHS arguments. These new constraints are simply *Derived* constraints; they have no evidence. We could go further and offer evidence from decomposing injective type-function applications, but that would require new evidence forms, and an extension to FC, so we don't do that right now (Dec 14). See also Note [Injective type families] in TyCon Note [Cache-caused loops] ~~~~~~~~~~~~~~~~~~~~~~~~~ It is very dangerous to cache a rewritten wanted family equation as 'solved' in our solved cache (which is the default behaviour or xCtEvidence), because the interaction may not be contributing towards a solution. Here is an example: Initial inert set: [W] g1 : F a ~ beta1 Work item: [W] g2 : F a ~ beta2 The work item will react with the inert yielding the _same_ inert set plus: i) Will set g2 := g1 `cast` g3 ii) Will add to our solved cache that [S] g2 : F a ~ beta2 iii) Will emit [W] g3 : beta1 ~ beta2 Now, the g3 work item will be spontaneously solved to [G] g3 : beta1 ~ beta2 and then it will react the item in the inert ([W] g1 : F a ~ beta1). So it will set g1 := g ; sym g3 and what is g? Well it would ideally be a new goal of type (F a ~ beta2) but remember that we have this in our solved cache, and it is ... g2! In short we created the evidence loop: g2 := g1 ; g3 g3 := refl g1 := g2 ; sym g3 To avoid this situation we do not cache as solved any workitems (or inert) which did not really made a 'step' towards proving some goal. Solved's are just an optimization so we don't lose anything in terms of completeness of solving. Note [Efficient Orientation] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Suppose we are interacting two FunEqCans with the same LHS: (inert) ci :: (F ty ~ xi_i) (work) cw :: (F ty ~ xi_w) We prefer to keep the inert (else we pass the work item on down the pipeline, which is a bit silly). If we keep the inert, we will (a) discharge 'cw' (b) produce a new equality work-item (xi_w ~ xi_i) Notice the orientation (xi_w ~ xi_i) NOT (xi_i ~ xi_w): new_work :: xi_w ~ xi_i cw := ci ; sym new_work Why? Consider the simplest case when xi1 is a type variable. If we generate xi1~xi2, porcessing that constraint will kick out 'ci'. If we generate xi2~xi1, there is less chance of that happening. Of course it can and should still happen if xi1=a, xi1=Int, say. But we want to avoid it happening needlessly. Similarly, if we *can't* keep the inert item (because inert is Wanted, and work is Given, say), we prefer to orient the new equality (xi_i ~ xi_w). Note [Carefully solve the right CFunEqCan] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ---- OLD COMMENT, NOW NOT NEEDED ---- because we now allow multiple ---- wanted FunEqs with the same head Consider the constraints c1 :: F Int ~ a -- Arising from an application line 5 c2 :: F Int ~ Bool -- Arising from an application line 10 Suppose that 'a' is a unification variable, arising only from flattening. So there is no error on line 5; it's just a flattening variable. But there is (or might be) an error on line 10. Two ways to combine them, leaving either (Plan A) c1 :: F Int ~ a -- Arising from an application line 5 c3 :: a ~ Bool -- Arising from an application line 10 or (Plan B) c2 :: F Int ~ Bool -- Arising from an application line 10 c4 :: a ~ Bool -- Arising from an application line 5 Plan A will unify c3, leaving c1 :: F Int ~ Bool as an error on the *totally innocent* line 5. An example is test SimpleFail16 where the expected/actual message comes out backwards if we use the wrong plan. The second is the right thing to do. Hence the isMetaTyVarTy test when solving pairwise CFunEqCan. ********************************************************************** * * interactTyVarEq * * ********************************************************************** -} interactTyVarEq :: InertCans -> Ct -> TcS (StopOrContinue Ct) -- CTyEqCans are always consumed, so always returns Stop interactTyVarEq inerts workItem@(CTyEqCan { cc_tyvar = tv , cc_rhs = rhs , cc_ev = ev , cc_eq_rel = eq_rel }) | (ev_i : _) <- [ ev_i | CTyEqCan { cc_ev = ev_i, cc_rhs = rhs_i } <- findTyEqs inerts tv , ev_i `canDischarge` ev , rhs_i `tcEqType` rhs ] = -- Inert: a ~ b -- Work item: a ~ b do { setEvBindIfWanted ev (ctEvTerm ev_i) ; stopWith ev "Solved from inert" } | Just tv_rhs <- getTyVar_maybe rhs , (ev_i : _) <- [ ev_i | CTyEqCan { cc_ev = ev_i, cc_rhs = rhs_i } <- findTyEqs inerts tv_rhs , ev_i `canDischarge` ev , rhs_i `tcEqType` mkTyVarTy tv ] = -- Inert: a ~ b -- Work item: b ~ a do { setEvBindIfWanted ev (EvCoercion (mkTcSymCo (ctEvCoercion ev_i))) ; stopWith ev "Solved from inert (r)" } | otherwise = do { tclvl <- getTcLevel ; if canSolveByUnification tclvl ev eq_rel tv rhs then do { solveByUnification ev tv rhs ; n_kicked <- kickOutAfterUnification tv ; return (Stop ev (ptext (sLit "Solved by unification") <+> ppr_kicked n_kicked)) } else do { traceTcS "Can't solve tyvar equality" (vcat [ text "LHS:" <+> ppr tv <+> dcolon <+> ppr (tyVarKind tv) , ppWhen (isMetaTyVar tv) $ nest 4 (text "TcLevel of" <+> ppr tv <+> text "is" <+> ppr (metaTyVarTcLevel tv)) , text "RHS:" <+> ppr rhs <+> dcolon <+> ppr (typeKind rhs) , text "TcLevel =" <+> ppr tclvl ]) ; addInertEq workItem ; return (Stop ev (ptext (sLit "Kept as inert"))) } } interactTyVarEq _ wi = pprPanic "interactTyVarEq" (ppr wi) -- @trySpontaneousSolve wi@ solves equalities where one side is a -- touchable unification variable. -- Returns True <=> spontaneous solve happened canSolveByUnification :: TcLevel -> CtEvidence -> EqRel -> TcTyVar -> Xi -> Bool canSolveByUnification tclvl gw eq_rel tv xi | ReprEq <- eq_rel -- we never solve representational equalities this way. = False | isGiven gw -- See Note [Touchables and givens] = False | isTouchableMetaTyVar tclvl tv = case metaTyVarInfo tv of SigTv -> is_tyvar xi _ -> True | otherwise -- Untouchable = False where is_tyvar xi = case tcGetTyVar_maybe xi of Nothing -> False Just tv -> case tcTyVarDetails tv of MetaTv { mtv_info = info } -> case info of SigTv -> True _ -> False SkolemTv {} -> True FlatSkol {} -> False RuntimeUnk -> True solveByUnification :: CtEvidence -> TcTyVar -> Xi -> TcS () -- Solve with the identity coercion -- Precondition: kind(xi) is a sub-kind of kind(tv) -- Precondition: CtEvidence is Wanted or Derived -- Precondition: CtEvidence is nominal -- Returns: workItem where -- workItem = the new Given constraint -- -- NB: No need for an occurs check here, because solveByUnification always -- arises from a CTyEqCan, a *canonical* constraint. Its invariants -- say that in (a ~ xi), the type variable a does not appear in xi. -- See TcRnTypes.Ct invariants. -- -- Post: tv is unified (by side effect) with xi; -- we often write tv := xi solveByUnification wd tv xi = do { let tv_ty = mkTyVarTy tv ; traceTcS "Sneaky unification:" $ vcat [text "Unifies:" <+> ppr tv <+> ptext (sLit ":=") <+> ppr xi, text "Coercion:" <+> pprEq tv_ty xi, text "Left Kind is:" <+> ppr (typeKind tv_ty), text "Right Kind is:" <+> ppr (typeKind xi) ] ; let xi' = defaultKind xi -- We only instantiate kind unification variables -- with simple kinds like *, not OpenKind or ArgKind -- cf TcUnify.uUnboundKVar ; unifyTyVar tv xi' ; setEvBindIfWanted wd (EvCoercion (mkTcNomReflCo xi')) } ppr_kicked :: Int -> SDoc ppr_kicked 0 = empty ppr_kicked n = parens (int n <+> ptext (sLit "kicked out")) {- Note [Avoid double unifications] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The spontaneous solver has to return a given which mentions the unified unification variable *on the left* of the equality. Here is what happens if not: Original wanted: (a ~ alpha), (alpha ~ Int) We spontaneously solve the first wanted, without changing the order! given : a ~ alpha [having unified alpha := a] Now the second wanted comes along, but he cannot rewrite the given, so we simply continue. At the end we spontaneously solve that guy, *reunifying* [alpha := Int] We avoid this problem by orienting the resulting given so that the unification variable is on the left. [Note that alternatively we could attempt to enforce this at canonicalization] See also Note [No touchables as FunEq RHS] in TcSMonad; avoiding double unifications is the main reason we disallow touchable unification variables as RHS of type family equations: F xis ~ alpha. ************************************************************************ * * * Functional dependencies, instantiation of equations * * ************************************************************************ When we spot an equality arising from a functional dependency, we now use that equality (a "wanted") to rewrite the work-item constraint right away. This avoids two dangers Danger 1: If we send the original constraint on down the pipeline it may react with an instance declaration, and in delicate situations (when a Given overlaps with an instance) that may produce new insoluble goals: see Trac #4952 Danger 2: If we don't rewrite the constraint, it may re-react with the same thing later, and produce the same equality again --> termination worries. To achieve this required some refactoring of FunDeps.hs (nicer now!). -} emitFunDepDeriveds :: [FunDepEqn CtLoc] -> TcS () emitFunDepDeriveds fd_eqns = mapM_ do_one_FDEqn fd_eqns where do_one_FDEqn (FDEqn { fd_qtvs = tvs, fd_eqs = eqs, fd_loc = loc }) | null tvs -- Common shortcut = mapM_ (unifyDerived loc Nominal) eqs | otherwise = do { (subst, _) <- instFlexiTcS tvs -- Takes account of kind substitution ; mapM_ (do_one_eq loc subst) eqs } do_one_eq loc subst (Pair ty1 ty2) = unifyDerived loc Nominal $ Pair (Type.substTy subst ty1) (Type.substTy subst ty2) {- ********************************************************************** * * The top-reaction Stage * * ********************************************************************** -} topReactionsStage :: WorkItem -> TcS (StopOrContinue Ct) topReactionsStage wi = do { tir <- doTopReact wi ; case tir of ContinueWith wi -> continueWith wi Stop ev s -> return (Stop ev (ptext (sLit "Top react:") <+> s)) } doTopReact :: WorkItem -> TcS (StopOrContinue Ct) -- The work item does not react with the inert set, so try interaction with top-level -- instances. Note: -- -- (a) The place to add superclasses in not here in doTopReact stage. -- Instead superclasses are added in the worklist as part of the -- canonicalization process. See Note [Adding superclasses]. doTopReact work_item = do { traceTcS "doTopReact" (ppr work_item) ; case work_item of CDictCan {} -> do { inerts <- getTcSInerts ; doTopReactDict inerts work_item } CFunEqCan {} -> doTopReactFunEq work_item _ -> -- Any other work item does not react with any top-level equations continueWith work_item } -------------------- doTopReactDict :: InertSet -> Ct -> TcS (StopOrContinue Ct) -- Try to use type-class instance declarations to simplify the constraint doTopReactDict inerts work_item@(CDictCan { cc_ev = fl, cc_class = cls , cc_tyargs = xis }) | isGiven fl -- Never use instances for Given constraints = do { try_fundep_improvement ; continueWith work_item } | Just ev <- lookupSolvedDict inerts cls xis -- Cached = do { setEvBindIfWanted fl (ctEvTerm ev); ; stopWith fl "Dict/Top (cached)" } | isDerived fl -- Use type-class instances for Deriveds, in the hope -- of generating some improvements -- C.f. Example 3 of Note [The improvement story] -- It's easy because no evidence is involved = do { dflags <- getDynFlags ; lkup_inst_res <- matchClassInst dflags inerts cls xis dict_loc ; case lkup_inst_res of GenInst preds _ s -> do { emitNewDeriveds dict_loc preds ; unless s $ insertSafeOverlapFailureTcS work_item ; stopWith fl "Dict/Top (solved)" } NoInstance -> do { -- If there is no instance, try improvement try_fundep_improvement ; continueWith work_item } } | otherwise -- Wanted, but not cached = do { dflags <- getDynFlags ; lkup_inst_res <- matchClassInst dflags inerts cls xis dict_loc ; case lkup_inst_res of GenInst theta mk_ev s -> do { addSolvedDict fl cls xis ; unless s $ insertSafeOverlapFailureTcS work_item ; solve_from_instance theta mk_ev } NoInstance -> do { try_fundep_improvement ; continueWith work_item } } where dict_pred = mkClassPred cls xis dict_loc = ctEvLoc fl dict_origin = ctLocOrigin dict_loc deeper_loc = zap_origin (bumpCtLocDepth dict_loc) zap_origin loc -- After applying an instance we can set ScOrigin to -- infinity, so that prohibitedSuperClassSolve never fires | ScOrigin {} <- dict_origin = setCtLocOrigin loc (ScOrigin infinity) | otherwise = loc solve_from_instance :: [TcPredType] -> ([EvId] -> EvTerm) -> TcS (StopOrContinue Ct) -- Precondition: evidence term matches the predicate workItem solve_from_instance theta mk_ev | null theta = do { traceTcS "doTopReact/found nullary instance for" $ ppr fl ; setWantedEvBind (ctEvId fl) (mk_ev []) ; stopWith fl "Dict/Top (solved, no new work)" } | otherwise = do { checkReductionDepth deeper_loc dict_pred ; traceTcS "doTopReact/found non-nullary instance for" $ ppr fl ; evc_vars <- mapM (newWantedEvVar deeper_loc) theta ; setWantedEvBind (ctEvId fl) (mk_ev (map (ctEvId . fst) evc_vars)) ; emitWorkNC (freshGoals evc_vars) ; stopWith fl "Dict/Top (solved, more work)" } -- We didn't solve it; so try functional dependencies with -- the instance environment, and return -- See also Note [Weird fundeps] try_fundep_improvement = do { traceTcS "try_fundeps" (ppr work_item) ; instEnvs <- getInstEnvs ; emitFunDepDeriveds $ improveFromInstEnv instEnvs mk_ct_loc dict_pred } mk_ct_loc :: PredType -- From instance decl -> SrcSpan -- also from instance deol -> CtLoc mk_ct_loc inst_pred inst_loc = dict_loc { ctl_origin = FunDepOrigin2 dict_pred dict_origin inst_pred inst_loc } doTopReactDict _ w = pprPanic "doTopReactDict" (ppr w) -------------------- doTopReactFunEq :: Ct -> TcS (StopOrContinue Ct) doTopReactFunEq work_item = do { fam_envs <- getFamInstEnvs ; do_top_fun_eq fam_envs work_item } do_top_fun_eq :: FamInstEnvs -> Ct -> TcS (StopOrContinue Ct) do_top_fun_eq fam_envs work_item@(CFunEqCan { cc_ev = old_ev, cc_fun = fam_tc , cc_tyargs = args , cc_fsk = fsk }) | Just (ax_co, rhs_ty) <- reduceTyFamApp_maybe fam_envs Nominal fam_tc args -- Look up in top-level instances, or built-in axiom -- See Note [MATCHING-SYNONYMS] = reduce_top_fun_eq old_ev fsk (TcCoercion ax_co) rhs_ty | otherwise = do { improveTopFunEqs (ctEvLoc old_ev) fam_envs fam_tc args fsk ; continueWith work_item } do_top_fun_eq _ w = pprPanic "doTopReactFunEq" (ppr w) reduce_top_fun_eq :: CtEvidence -> TcTyVar -> TcCoercion -> TcType -> TcS (StopOrContinue Ct) -- Found an applicable top-level axiom: use it to reduce reduce_top_fun_eq old_ev fsk ax_co rhs_ty | Just (tc, tc_args) <- tcSplitTyConApp_maybe rhs_ty , isTypeFamilyTyCon tc , tc_args `lengthIs` tyConArity tc -- Short-cut = shortCutReduction old_ev fsk ax_co tc tc_args -- Try shortcut; see Note [Short cut for top-level reaction] | isGiven old_ev -- Not shortcut = do { let final_co = mkTcSymCo (ctEvCoercion old_ev) `mkTcTransCo` ax_co -- final_co :: fsk ~ rhs_ty ; new_ev <- newGivenEvVar deeper_loc (mkTcEqPred (mkTyVarTy fsk) rhs_ty, EvCoercion final_co) ; emitWorkNC [new_ev] -- Non-cannonical; that will mean we flatten rhs_ty ; stopWith old_ev "Fun/Top (given)" } -- So old_ev is Wanted or Derived | not (fsk `elemVarSet` tyVarsOfType rhs_ty) = do { dischargeFmv old_ev fsk ax_co rhs_ty ; traceTcS "doTopReactFunEq" $ vcat [ text "old_ev:" <+> ppr old_ev , nest 2 (text ":=") <+> ppr ax_co ] ; stopWith old_ev "Fun/Top (wanted)" } | otherwise -- We must not assign ufsk := ...ufsk...! = do { alpha_ty <- newFlexiTcSTy (tyVarKind fsk) ; let pred = mkTcEqPred alpha_ty rhs_ty ; new_ev <- case old_ev of CtWanted {} -> do { ev <- newWantedEvVarNC loc pred ; updWorkListTcS (extendWorkListEq (mkNonCanonical ev)) ; return ev } CtDerived {} -> do { ev <- newDerivedNC loc pred ; updWorkListTcS (extendWorkListDerived loc ev) ; return ev } _ -> pprPanic "reduce_top_fun_eq" (ppr old_ev) -- By emitting this as non-canonical, we deal with all -- flattening, occurs-check, and ufsk := ufsk issues ; let final_co = ax_co `mkTcTransCo` mkTcSymCo (ctEvCoercion new_ev) -- ax_co :: fam_tc args ~ rhs_ty -- ev :: alpha ~ rhs_ty -- ufsk := alpha -- final_co :: fam_tc args ~ alpha ; dischargeFmv old_ev fsk final_co alpha_ty ; traceTcS "doTopReactFunEq (occurs)" $ vcat [ text "old_ev:" <+> ppr old_ev , nest 2 (text ":=") <+> ppr final_co , text "new_ev:" <+> ppr new_ev ] ; stopWith old_ev "Fun/Top (wanted)" } where loc = ctEvLoc old_ev deeper_loc = bumpCtLocDepth loc improveTopFunEqs :: CtLoc -> FamInstEnvs -> TyCon -> [TcType] -> TcTyVar -> TcS () improveTopFunEqs loc fam_envs fam_tc args fsk = do { model <- getInertModel ; eqns <- improve_top_fun_eqs fam_envs fam_tc args (lookupFlattenTyVar model fsk) ; mapM_ (unifyDerived loc Nominal) eqns } improve_top_fun_eqs :: FamInstEnvs -> TyCon -> [TcType] -> TcType -> TcS [Eqn] improve_top_fun_eqs fam_envs fam_tc args rhs_ty | Just ops <- isBuiltInSynFamTyCon_maybe fam_tc = return (sfInteractTop ops args rhs_ty) -- see Note [Type inference for type families with injectivity] | isOpenTypeFamilyTyCon fam_tc , Injective injective_args <- familyTyConInjectivityInfo fam_tc = -- it is possible to have several compatible equations in an open type -- family but we only want to derive equalities from one such equation. concatMapM (injImproveEqns injective_args) (take 1 $ buildImprovementData (lookupFamInstEnvByTyCon fam_envs fam_tc) fi_tys fi_rhs (const Nothing)) | Just ax <- isClosedSynFamilyTyConWithAxiom_maybe fam_tc , Injective injective_args <- familyTyConInjectivityInfo fam_tc = concatMapM (injImproveEqns injective_args) $ buildImprovementData (fromBranches (co_ax_branches ax)) cab_lhs cab_rhs Just | otherwise = return [] where buildImprovementData :: [a] -- axioms for a TF (FamInst or CoAxBranch) -> (a -> [Type]) -- get LHS of an axiom -> (a -> Type) -- get RHS of an axiom -> (a -> Maybe CoAxBranch) -- Just => apartness check required -> [( [Type], TvSubst, TyVarSet, Maybe CoAxBranch )] -- Result: -- ( [arguments of a matching axiom] -- , RHS-unifying substitution -- , axiom variables without substitution -- , Maybe matching axiom [Nothing - open TF, Just - closed TF ] ) buildImprovementData axioms axiomLHS axiomRHS wrap = [ (ax_args, subst, unsubstTvs, wrap axiom) | axiom <- axioms , let ax_args = axiomLHS axiom , let ax_rhs = axiomRHS axiom , Just subst <- [tcUnifyTyWithTFs False ax_rhs rhs_ty] , let tvs = tyVarsOfTypes ax_args notInSubst tv = not (tv `elemVarEnv` getTvSubstEnv subst) unsubstTvs = filterVarSet notInSubst tvs ] injImproveEqns :: [Bool] -> ([Type], TvSubst, TyVarSet, Maybe CoAxBranch) -> TcS [Eqn] injImproveEqns inj_args (ax_args, theta, unsubstTvs, cabr) = do (theta', _) <- instFlexiTcS (varSetElems unsubstTvs) let subst = theta `unionTvSubst` theta' return [ Pair arg (substTy subst ax_arg) | case cabr of Just cabr' -> apartnessCheck (substTys subst ax_args) cabr' _ -> True , (arg, ax_arg, True) <- zip3 args ax_args inj_args ] shortCutReduction :: CtEvidence -> TcTyVar -> TcCoercion -> TyCon -> [TcType] -> TcS (StopOrContinue Ct) -- See Note [Top-level reductions for type functions] shortCutReduction old_ev fsk ax_co fam_tc tc_args | isGiven old_ev = ASSERT( ctEvEqRel old_ev == NomEq ) do { (xis, cos) <- flattenManyNom old_ev tc_args -- ax_co :: F args ~ G tc_args -- cos :: xis ~ tc_args -- old_ev :: F args ~ fsk -- G cos ; sym ax_co ; old_ev :: G xis ~ fsk ; new_ev <- newGivenEvVar deeper_loc ( mkTcEqPred (mkTyConApp fam_tc xis) (mkTyVarTy fsk) , EvCoercion (mkTcTyConAppCo Nominal fam_tc cos `mkTcTransCo` mkTcSymCo ax_co `mkTcTransCo` ctEvCoercion old_ev) ) ; let new_ct = CFunEqCan { cc_ev = new_ev, cc_fun = fam_tc, cc_tyargs = xis, cc_fsk = fsk } ; emitWorkCt new_ct ; stopWith old_ev "Fun/Top (given, shortcut)" } | otherwise = ASSERT( not (isDerived old_ev) ) -- Caller ensures this ASSERT( ctEvEqRel old_ev == NomEq ) do { (xis, cos) <- flattenManyNom old_ev tc_args -- ax_co :: F args ~ G tc_args -- cos :: xis ~ tc_args -- G cos ; sym ax_co ; old_ev :: G xis ~ fsk -- new_ev :: G xis ~ fsk -- old_ev :: F args ~ fsk := ax_co ; sym (G cos) ; new_ev ; new_ev <- newWantedEvVarNC deeper_loc (mkTcEqPred (mkTyConApp fam_tc xis) (mkTyVarTy fsk)) ; setWantedEvBind (ctEvId old_ev) (EvCoercion (ax_co `mkTcTransCo` mkTcSymCo (mkTcTyConAppCo Nominal fam_tc cos) `mkTcTransCo` ctEvCoercion new_ev)) ; let new_ct = CFunEqCan { cc_ev = new_ev, cc_fun = fam_tc, cc_tyargs = xis, cc_fsk = fsk } ; emitWorkCt new_ct ; stopWith old_ev "Fun/Top (wanted, shortcut)" } where loc = ctEvLoc old_ev deeper_loc = bumpCtLocDepth loc dischargeFmv :: CtEvidence -> TcTyVar -> TcCoercion -> TcType -> TcS () -- (dischargeFmv x fmv co ty) -- [W] ev :: F tys ~ fmv -- co :: F tys ~ xi -- Precondition: fmv is not filled, and fuv `notElem` xi -- -- Then set fmv := xi, -- set ev := co -- kick out any inert things that are now rewritable -- -- Does not evaluate 'co' if 'ev' is Derived dischargeFmv ev fmv co xi = ASSERT2( not (fmv `elemVarSet` tyVarsOfType xi), ppr ev $$ ppr fmv $$ ppr xi ) do { setEvBindIfWanted ev (EvCoercion co) ; unflattenFmv fmv xi ; n_kicked <- kickOutAfterUnification fmv ; traceTcS "dischargeFmv" (ppr fmv <+> equals <+> ppr xi $$ ppr_kicked n_kicked) } {- Note [Top-level reductions for type functions] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ c.f. Note [The flattening story] in TcFlatten Suppose we have a CFunEqCan F tys ~ fmv/fsk, and a matching axiom. Here is what we do, in four cases: * Wanteds: general firing rule (work item) [W] x : F tys ~ fmv instantiate axiom: ax_co : F tys ~ rhs Then: Discharge fmv := alpha Discharge x := ax_co ; sym x2 New wanted [W] x2 : alpha ~ rhs (Non-canonical) This is *the* way that fmv's get unified; even though they are "untouchable". NB: it can be the case that fmv appears in the (instantiated) rhs. In that case the new Non-canonical wanted will be loopy, but that's ok. But it's good reason NOT to claim that it is canonical! * Wanteds: short cut firing rule Applies when the RHS of the axiom is another type-function application (work item) [W] x : F tys ~ fmv instantiate axiom: ax_co : F tys ~ G rhs_tys It would be a waste to create yet another fmv for (G rhs_tys). Instead (shortCutReduction): - Flatten rhs_tys (cos : rhs_tys ~ rhs_xis) - Add G rhs_xis ~ fmv to flat cache (note: the same old fmv) - New canonical wanted [W] x2 : G rhs_xis ~ fmv (CFunEqCan) - Discharge x := ax_co ; G cos ; x2 * Givens: general firing rule (work item) [G] g : F tys ~ fsk instantiate axiom: ax_co : F tys ~ rhs Now add non-canonical given (since rhs is not flat) [G] (sym g ; ax_co) : fsk ~ rhs (Non-canonical) * Givens: short cut firing rule Applies when the RHS of the axiom is another type-function application (work item) [G] g : F tys ~ fsk instantiate axiom: ax_co : F tys ~ G rhs_tys It would be a waste to create yet another fsk for (G rhs_tys). Instead (shortCutReduction): - Flatten rhs_tys: flat_cos : tys ~ flat_tys - Add new Canonical given [G] (sym (G flat_cos) ; co ; g) : G flat_tys ~ fsk (CFunEqCan) Note [Cached solved FunEqs] ~~~~~~~~~~~~~~~~~~~~~~~~~~~ When trying to solve, say (FunExpensive big-type ~ ty), it's important to see if we have reduced (FunExpensive big-type) before, lest we simply repeat it. Hence the lookup in inert_solved_funeqs. Moreover we must use `canDischarge` because both uses might (say) be Wanteds, and we *still* want to save the re-computation. Note [MATCHING-SYNONYMS] ~~~~~~~~~~~~~~~~~~~~~~~~ When trying to match a dictionary (D tau) to a top-level instance, or a type family equation (F taus_1 ~ tau_2) to a top-level family instance, we do *not* need to expand type synonyms because the matcher will do that for us. Note [RHS-FAMILY-SYNONYMS] ~~~~~~~~~~~~~~~~~~~~~~~~~~ The RHS of a family instance is represented as yet another constructor which is like a type synonym for the real RHS the programmer declared. Eg: type instance F (a,a) = [a] Becomes: :R32 a = [a] -- internal type synonym introduced F (a,a) ~ :R32 a -- instance When we react a family instance with a type family equation in the work list we keep the synonym-using RHS without expansion. Note [FunDep and implicit parameter reactions] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Currently, our story of interacting two dictionaries (or a dictionary and top-level instances) for functional dependencies, and implicit paramters, is that we simply produce new Derived equalities. So for example class D a b | a -> b where ... Inert: d1 :g D Int Bool WorkItem: d2 :w D Int alpha We generate the extra work item cv :d alpha ~ Bool where 'cv' is currently unused. However, this new item can perhaps be spontaneously solved to become given and react with d2, discharging it in favour of a new constraint d2' thus: d2' :w D Int Bool d2 := d2' |> D Int cv Now d2' can be discharged from d1 We could be more aggressive and try to *immediately* solve the dictionary using those extra equalities, but that requires those equalities to carry evidence and derived do not carry evidence. If that were the case with the same inert set and work item we might dischard d2 directly: cv :w alpha ~ Bool d2 := d1 |> D Int cv But in general it's a bit painful to figure out the necessary coercion, so we just take the first approach. Here is a better example. Consider: class C a b c | a -> b And: [Given] d1 : C T Int Char [Wanted] d2 : C T beta Int In this case, it's *not even possible* to solve the wanted immediately. So we should simply output the functional dependency and add this guy [but NOT its superclasses] back in the worklist. Even worse: [Given] d1 : C T Int beta [Wanted] d2: C T beta Int Then it is solvable, but its very hard to detect this on the spot. It's exactly the same with implicit parameters, except that the "aggressive" approach would be much easier to implement. Note [Weird fundeps] ~~~~~~~~~~~~~~~~~~~~ Consider class Het a b | a -> b where het :: m (f c) -> a -> m b class GHet (a :: * -> *) (b :: * -> *) | a -> b instance GHet (K a) (K [a]) instance Het a b => GHet (K a) (K b) The two instances don't actually conflict on their fundeps, although it's pretty strange. So they are both accepted. Now try [W] GHet (K Int) (K Bool) This triggers fundeps from both instance decls; [D] K Bool ~ K [a] [D] K Bool ~ K beta And there's a risk of complaining about Bool ~ [a]. But in fact the Wanted matches the second instance, so we never get as far as the fundeps. Trac #7875 is a case in point. Note [Overriding implicit parameters] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider f :: (?x::a) -> Bool -> a g v = let ?x::Int = 3 in (f v, let ?x::Bool = True in f v) This should probably be well typed, with g :: Bool -> (Int, Bool) So the inner binding for ?x::Bool *overrides* the outer one. Hence a work-item Given overrides an inert-item Given. -} {- ******************************************************************* * * Class lookup * * **********************************************************************-} -- | Indicates if Instance met the Safe Haskell overlapping instances safety -- check. -- -- See Note [Safe Haskell Overlapping Instances] in TcSimplify -- See Note [Safe Haskell Overlapping Instances Implementation] in TcSimplify type SafeOverlapping = Bool data LookupInstResult = NoInstance | GenInst [TcPredType] ([EvId] -> EvTerm) SafeOverlapping instance Outputable LookupInstResult where ppr NoInstance = text "NoInstance" ppr (GenInst ev _ s) = text "GenInst" <+> ppr ev <+> ss where ss = text $ if s then "[safe]" else "[unsafe]" matchClassInst :: DynFlags -> InertSet -> Class -> [Type] -> CtLoc -> TcS LookupInstResult matchClassInst dflags inerts clas tys loc -- First check whether there is an in-scope Given that could -- match this constraint. In that case, do not use top-level -- instances. See Note [Instance and Given overlap] | not (xopt Opt_IncoherentInstances dflags) , let matchable_givens = matchableGivens loc pred inerts , not (isEmptyBag matchable_givens) = do { traceTcS "Delaying instance application" $ vcat [ text "Work item=" <+> pprClassPred clas tys , text "Potential matching givens:" <+> ppr matchable_givens ] ; return NoInstance } where pred = mkClassPred clas tys matchClassInst dflags _ clas tys loc = do { traceTcS "matchClassInst" $ vcat [ text "pred =" <+> ppr (mkClassPred clas tys) ] ; res <- match_class_inst dflags clas tys loc ; traceTcS "matchClassInst result" $ ppr res ; return res } match_class_inst :: DynFlags -> Class -> [Type] -> CtLoc -> TcS LookupInstResult match_class_inst dflags clas tys loc | cls_name == knownNatClassName = matchKnownNat clas tys | cls_name == knownSymbolClassName = matchKnownSymbol clas tys | isCTupleClass clas = matchCTuple clas tys | cls_name == typeableClassName = matchTypeable clas tys | otherwise = matchInstEnv dflags clas tys loc where cls_name = className clas {- Note [Instance and Given overlap] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Example, from the OutsideIn(X) paper: instance P x => Q [x] instance (x ~ y) => R y [x] wob :: forall a b. (Q [b], R b a) => a -> Int g :: forall a. Q [a] => [a] -> Int g x = wob x This will generate the impliation constraint: Q [a] => (Q [beta], R beta [a]) If we react (Q [beta]) with its top-level axiom, we end up with a (P beta), which we have no way of discharging. On the other hand, if we react R beta [a] with the top-level we get (beta ~ a), which is solvable and can help us rewrite (Q [beta]) to (Q [a]) which is now solvable by the given Q [a]. The solution is that: In matchClassInst (and thus in topReact), we return a matching instance only when there is no Given in the inerts which is unifiable to this particular dictionary. We treat any meta-tyvar as "unifiable" for this purpose, *including* untouchable ones The end effect is that, much as we do for overlapping instances, we delay choosing a class instance if there is a possibility of another instance OR a given to match our constraint later on. This fixes Trac #4981 and #5002. Other notes: * The check is done *first*, so that it also covers classes with built-in instance solving, such as - constraint tuples - natural numbers - Typeable * The given-overlap problem is arguably not easy to appear in practice due to our aggressive prioritization of equality solving over other constraints, but it is possible. I've added a test case in typecheck/should-compile/GivenOverlapping.hs * Another "live" example is Trac #10195; another is #10177. * We ignore the overlap problem if -XIncoherentInstances is in force: see Trac #6002 for a worked-out example where this makes a difference. * Moreover notice that our goals here are different than the goals of the top-level overlapping checks. There we are interested in validating the following principle: If we inline a function f at a site where the same global instance environment is available as the instance environment at the definition site of f then we should get the same behaviour. But for the Given Overlap check our goal is just related to completeness of constraint solving. -} {- ******************************************************************* * * Class lookup in the instance environment * * **********************************************************************-} matchInstEnv :: DynFlags -> Class -> [Type] -> CtLoc -> TcS LookupInstResult matchInstEnv dflags clas tys loc = do { instEnvs <- getInstEnvs ; let safeOverlapCheck = safeHaskell dflags `elem` [Sf_Safe, Sf_Trustworthy] (matches, unify, unsafeOverlaps) = lookupInstEnv True instEnvs clas tys safeHaskFail = safeOverlapCheck && not (null unsafeOverlaps) ; case (matches, unify, safeHaskFail) of -- Nothing matches ([], _, _) -> do { traceTcS "matchClass not matching" $ vcat [ text "dict" <+> ppr pred ] ; return NoInstance } -- A single match (& no safe haskell failure) ([(ispec, inst_tys)], [], False) -> do { let dfun_id = instanceDFunId ispec ; traceTcS "matchClass success" $ vcat [text "dict" <+> ppr pred, text "witness" <+> ppr dfun_id <+> ppr (idType dfun_id) ] -- Record that this dfun is needed ; match_one (null unsafeOverlaps) dfun_id inst_tys } -- More than one matches (or Safe Haskell fail!). Defer any -- reactions of a multitude until we learn more about the reagent (matches, _, _) -> do { traceTcS "matchClass multiple matches, deferring choice" $ vcat [text "dict" <+> ppr pred, text "matches" <+> ppr matches] ; return NoInstance } } where pred = mkClassPred clas tys match_one :: SafeOverlapping -> DFunId -> [DFunInstType] -> TcS LookupInstResult -- See Note [DFunInstType: instantiating types] in InstEnv match_one so dfun_id mb_inst_tys = do { checkWellStagedDFun pred dfun_id loc ; (tys, theta) <- instDFunType dfun_id mb_inst_tys ; return $ GenInst theta (EvDFunApp dfun_id tys) so } {- ******************************************************************** * * Class lookup for CTuples * * ***********************************************************************-} matchCTuple :: Class -> [Type] -> TcS LookupInstResult matchCTuple clas tys -- (isCTupleClass clas) holds = return (GenInst tys tuple_ev True) -- The dfun *is* the data constructor! where data_con = tyConSingleDataCon (classTyCon clas) tuple_ev = EvDFunApp (dataConWrapId data_con) tys {- ******************************************************************** * * Class lookup for Literals * * ***********************************************************************-} matchKnownNat :: Class -> [Type] -> TcS LookupInstResult matchKnownNat clas [ty] -- clas = KnownNat | Just n <- isNumLitTy ty = makeLitDict clas ty (EvNum n) matchKnownNat _ _ = return NoInstance matchKnownSymbol :: Class -> [Type] -> TcS LookupInstResult matchKnownSymbol clas [ty] -- clas = KnownSymbol | Just n <- isStrLitTy ty = makeLitDict clas ty (EvStr n) matchKnownSymbol _ _ = return NoInstance makeLitDict :: Class -> Type -> EvLit -> TcS LookupInstResult -- makeLitDict adds a coercion that will convert the literal into a dictionary -- of the appropriate type. See Note [KnownNat & KnownSymbol and EvLit] -- in TcEvidence. The coercion happens in 2 steps: -- -- Integer -> SNat n -- representation of literal to singleton -- SNat n -> KnownNat n -- singleton to dictionary -- -- The process is mirrored for Symbols: -- String -> SSymbol n -- SSymbol n -> KnownSymbol n -} makeLitDict clas ty evLit | Just (_, co_dict) <- tcInstNewTyCon_maybe (classTyCon clas) [ty] -- co_dict :: KnownNat n ~ SNat n , [ meth ] <- classMethods clas , Just tcRep <- tyConAppTyCon_maybe -- SNat $ funResultTy -- SNat n $ dropForAlls -- KnownNat n => SNat n $ idType meth -- forall n. KnownNat n => SNat n , Just (_, co_rep) <- tcInstNewTyCon_maybe tcRep [ty] -- SNat n ~ Integer , let ev_tm = mkEvCast (EvLit evLit) (mkTcSymCo (mkTcTransCo co_dict co_rep)) = return $ GenInst [] (\_ -> ev_tm) True | otherwise = panicTcS (text "Unexpected evidence for" <+> ppr (className clas) $$ vcat (map (ppr . idType) (classMethods clas))) {- ******************************************************************** * * Class lookup for Typeable * * ***********************************************************************-} -- | Assumes that we've checked that this is the 'Typeable' class, -- and it was applied to the correct argument. matchTypeable :: Class -> [Type] -> TcS LookupInstResult matchTypeable clas [k,t] -- clas = Typeable -- For the first two cases, See Note [No Typeable for polytypes or qualified types] | isForAllTy k = return NoInstance -- Polytype | isJust (tcSplitPredFunTy_maybe t) = return NoInstance -- Qualified type -- Now cases that do work | k `eqType` typeNatKind = doTyLit knownNatClassName t | k `eqType` typeSymbolKind = doTyLit knownSymbolClassName t | Just (_, ks) <- splitTyConApp_maybe t -- See Note [Typeable (T a b c)] , all isGroundKind ks = doTyConApp t | Just (f,kt) <- splitAppTy_maybe t = doTyApp clas t f kt matchTypeable _ _ = return NoInstance doTyConApp :: Type -> TcS LookupInstResult -- Representation for type constructor applied to some (ground) kinds doTyConApp ty = return $ GenInst [] (\_ -> EvTypeable ty EvTypeableTyCon) True -- Representation for concrete kinds. We just use the kind itself, -- but first check to make sure that it is "simple" (i.e., made entirely -- out of kind constructors). isGroundKind :: KindOrType -> Bool -- Return True if (a) k is a kind and (b) it is a ground kind isGroundKind k = isKind k && is_ground k where is_ground k | Just (_, ks) <- splitTyConApp_maybe k = all is_ground ks | otherwise = False doTyApp :: Class -> Type -> Type -> KindOrType -> TcS LookupInstResult -- Representation for an application of a type to a type-or-kind. -- This may happen when the type expression starts with a type variable. -- Example (ignoring kind parameter): -- Typeable (f Int Char) --> -- (Typeable (f Int), Typeable Char) --> -- (Typeable f, Typeable Int, Typeable Char) --> (after some simp. steps) -- Typeable f doTyApp clas ty f tk | isKind tk = return NoInstance -- We can't solve until we know the ctr. | otherwise = return $ GenInst [mk_typeable_pred clas f, mk_typeable_pred clas tk] (\[t1,t2] -> EvTypeable ty $ EvTypeableTyApp (EvId t1) (EvId t2)) True -- Emit a `Typeable` constraint for the given type. mk_typeable_pred :: Class -> Type -> PredType mk_typeable_pred clas ty = mkClassPred clas [ typeKind ty, ty ] -- Typeable is implied by KnownNat/KnownSymbol. In the case of a type literal -- we generate a sub-goal for the appropriate class. See #10348 for what -- happens when we fail to do this. doTyLit :: Name -> Type -> TcS LookupInstResult doTyLit kc t = do { kc_clas <- tcLookupClass kc ; let kc_pred = mkClassPred kc_clas [ t ] mk_ev [ev] = EvTypeable t $ EvTypeableTyLit $ EvId ev mk_ev _ = panic "doTyLit" ; return (GenInst [kc_pred] mk_ev True) } {- Note [Typeable (T a b c)] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ For type applications we always decompose using binary application, vai doTyApp, until we get to a *kind* instantiation. Exmaple Proxy :: forall k. k -> * To solve Typeable (Proxy (* -> *) Maybe) we - First decompose with doTyApp, to get (Typeable (Proxy (* -> *))) and Typeable Maybe - Then sovle (Typeable (Proxy (* -> *))) with doTyConApp If we attempt to short-cut by solving it all at once, via doTyCOnAPp Note [No Typeable for polytypes or qualified types] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We do not support impredicative typeable, such as Typeable (forall a. a->a) Typeable (Eq a => a -> a) Typeable (() => Int) Typeable (((),()) => Int) See Trac #9858. For forall's the case is clear: we simply don't have a TypeRep for them. For qualified but not polymorphic types, like (Eq a => a -> a), things are murkier. But: * We don't need a TypeRep for these things. TypeReps are for monotypes only. * Perhaps we could treat `=>` as another type constructor for `Typeable` purposes, and thus support things like `Eq Int => Int`, however, at the current state of affairs this would be an odd exception as no other class works with impredicative types. For now we leave it off, until we have a better story for impredicativity. -}
elieux/ghc
compiler/typecheck/TcInteract.hs
bsd-3-clause
87,201
29
22
25,708
12,810
6,621
6,189
-1
-1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} module GitLab.Issue where import Data.Monoid (mconcat) import qualified Data.Text.Encoding as TE import Data.Conduit import Network.HTTP.Conduit import Web.PathPieces (toPathPiece) import GitLab.Rest (restSource) import GitLab.Types listIssues :: (MonadBaseControl IO m, MonadResource m) => Source (GitLabT m) Issue listIssues = restSource $ \request -> request { path = "/issues" } listProjectIssues :: (MonadBaseControl IO m, MonadResource m) => ProjectId -> Source (GitLabT m) Issue listProjectIssues projId = restSource $ \request -> request { path = TE.encodeUtf8 $ mconcat [ "/projects/" , toPathPiece projId , "/issues" ] }
maoe/gitlab
src/GitLab/Issue.hs
bsd-3-clause
746
0
12
138
201
115
86
24
1
{-# LANGUAGE Rank2Types #-} {-# LANGUAGE TypeFamilies #-} -- | Methods that operate on 'SscGlobalState' and 'VssCertificatesMap'. module Pos.DB.Ssc.State.Global ( -- * Certs getGlobalCerts , getStableCerts -- * Global state , sscLoadGlobalState , sscGetGlobalState ) where import Formatting (build, sformat, (%)) import Universum import Pos.Chain.Genesis as Genesis (Config) import Pos.Chain.Ssc (MonadSscMem, SscGlobalState (..), VssCertificatesMap (..), getStableCertsPure, sgsVssCertificates, sscRunGlobalQuery) import qualified Pos.Chain.Ssc as Ssc import Pos.Core (EpochIndex (..), SlotId (..)) import Pos.DB (MonadDBRead) import qualified Pos.DB.Ssc.GState as DB import Pos.Util.Wlog (WithLogger, logDebug, logInfo) ---------------------------------------------------------------------------- -- Certs ---------------------------------------------------------------------------- getGlobalCerts :: (MonadSscMem ctx m, MonadIO m) => SlotId -> m VssCertificatesMap getGlobalCerts sl = sscRunGlobalQuery $ Ssc.certs . Ssc.setLastKnownSlot sl <$> view sgsVssCertificates -- | Get stable VSS certificates for given epoch. getStableCerts :: (MonadSscMem ctx m, MonadIO m) => Genesis.Config -> EpochIndex -> m VssCertificatesMap getStableCerts genesisConfig epoch = getStableCertsPure genesisConfig epoch <$> sscRunGlobalQuery (view sgsVssCertificates) ---------------------------------------------------------------------------- -- Seed ---------------------------------------------------------------------------- -- | Load global state from DB by recreating it from recent blocks. sscLoadGlobalState :: (MonadDBRead m, WithLogger m) => m SscGlobalState sscLoadGlobalState = do logDebug "Loading SSC global state" gs <- DB.getSscGlobalState gs <$ logInfo (sformat ("Loaded SSC state: " %build) gs) sscGetGlobalState :: (MonadSscMem ctx m, MonadIO m) => m SscGlobalState sscGetGlobalState = sscRunGlobalQuery ask
input-output-hk/pos-haskell-prototype
db/src/Pos/DB/Ssc/State/Global.hs
mit
2,170
0
12
464
392
230
162
43
1
{-# LANGUAGE OverloadedStrings #-} module Config where {- import Control.Lens import Control.Monad.State.Strict (runState) import Data.Aeson (Value, decode) import Data.Aeson.Lens (key) import Data.Default (def) import Data.Maybe (fromJust, isJust) import Data.Text (Text) import Protolude hiding (runState) import Qi.Config.AWS (Config (..)) import Qi.Config.CfTemplate (render) import Qi.Program.Config.Interface (ConfigProgram) import Qi.Program.Config.Interpreters.Build (interpret, unQiConfig) import Util appName :: Text appName = "testApp" getResources :: Value -> Value getResources = getValueUnderKey "Resources" getOutputs :: Value -> Value getOutputs = getValueUnderKey "Outputs" getTemplate :: Config -> Value getTemplate cfg = fromJust (decode $ render cfg) getConfig :: ConfigProgram () -> Config getConfig cp = snd . (`runState` def{_namePrefix = appName}) . unQiConfig $ interpret cp -}
ababkin/qmuli
tests/Config.hs
mit
1,259
0
2
464
6
5
1
2
0
{-# LANGUAGE DeriveTraversable, GeneralizedNewtypeDeriving, DeriveDataTypeable #-} -- | -- Copyright : (c) 2010 Benedikt Schmidt -- License : GPL v3 (see LICENSE) -- -- Maintainer : Benedikt Schmidt <beschmi@gmail.com> -- Portability : GHC only -- -- Types and instances to handle series of disjunctions and conjunctions. module Logic.Connectives where -- import Data.Monoid -- import Data.Foldable -- import Data.Traversable import Data.Typeable import Data.Generics import Data.Binary import Control.Basics import Control.Monad.Disj import Control.DeepSeq -- | A conjunction of atoms of type a. newtype Conj a = Conj { getConj :: [a] } deriving (Monoid, Foldable, Traversable, Eq, Ord, Show, Binary, Functor, Applicative, Monad, Alternative, MonadPlus, Typeable, Data, NFData) -- | A disjunction of atoms of type a. newtype Disj a = Disj { getDisj :: [a] } deriving (Monoid, Foldable, Traversable, Eq, Ord, Show, Binary, Functor, Applicative, Monad, Alternative, MonadPlus, Typeable, Data, NFData) instance MonadDisj Disj where contradictoryBecause _ = Disj mzero disjunction m1 m2 = Disj $ getDisj m1 `mplus` getDisj m2
samscott89/tamarin-prover
lib/utils/src/Logic/Connectives.hs
gpl-3.0
1,180
0
8
217
256
147
109
17
0
module LayoutBad5 where x = let y = 4 z = 5 } in 6
roberth/uu-helium
test/parser/LayoutBad5.hs
gpl-3.0
76
1
8
40
27
15
12
-1
-1
module Data.Map.Extended ( module Data.Map , setMapIntersection , unionWithM ) where import Data.Map import Data.Set (Set) import Prelude setMapIntersection :: Ord k => Set k -> Map k a -> Map k a setMapIntersection s m = m `intersection` fromSet (const ()) s unionWithM :: (Applicative f, Ord k) => (a -> a -> f a) -> Map k a -> Map k a -> f (Map k a) unionWithM f m0 m1 = fromAscList <$> go (toAscList m0) (toAscList m1) where go [] ns = pure ns go ms [] = pure ms go ((k0,v0):ms) ((k1,v1):ns) | k0 < k1 = ((k0,v0):) <$> go ms ((k1,v1):ns) | k1 < k0 = ((k1,v1):) <$> go ((k0,v0):ms) ns | otherwise = (:) . (,) k0 <$> f v0 v1 <*> go ms ns
lamdu/lamdu
src/Data/Map/Extended.hs
gpl-3.0
740
0
12
232
395
207
188
21
3