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 Trustworthy #-} {-# LANGUAGE ForeignFunctionInterface #-} {-# LANGUAGE MagicHash, UnliftedFFITypes #-} ----------------------------------------------------------------------------- -- | -- Copyright : (C) 2013-15 Edward Kmett -- License : BSD-style (see the file LICENSE) -- Maintainer : Edward Kmett <[email protected]> -- Stability : experimental -- Portability : non-portable -- ----------------------------------------------------------------------------- module Succinct.Internal.PopCount ( popCountWord64 , VectorInternal(..) , vectorToInternal , vectorFromInternal , popCountSlice , popCountBitSlice , popCount512Bits , unsafeIndexInternal ) where import Control.Monad.ST import Data.Function (on) import Data.Primitive.ByteArray import qualified Data.Vector.Primitive as P import qualified Data.Vector.Primitive.Mutable as PM import Data.Word -- TODO(klao): it would be a little bit faster to import this as -- 'prim', cause then the code could literally be two processor -- instructions: -- __asm__("popcnt %%rbx, %%rbx\n\t" "jmp * (%%rbp)\n\t"); -- -- But, there's still some inefficiency around it (GHC saves the -- registers before jumping), so the gain is less than it could be. -- -- Also, foreign import prim kills the ghci for some reason, which -- makes development a hassle, so I stick with the simple solution for -- now. foreign import ccall unsafe "popcnt_w64" popCountWord64 :: Word64 -> Int foreign import ccall unsafe "popcnt_words" popCountNWords :: ByteArray# -> Int -> Int -> Int foreign import ccall unsafe "popcnt_bits" popCountNBits :: ByteArray# -> Int -> Int -> Int foreign import ccall unsafe "popcnt_512" popCount512 :: ByteArray# -> Int -> Int -- TODO(klao): get rid of this once P.Vector constructor is exposed data VectorInternal = VectorInternal {-# UNPACK #-} !Int {-# UNPACK #-} !Int {-# UNPACK #-} !ByteArray instance Eq VectorInternal where (==) = (==) `on` vectorFromInternal instance Ord VectorInternal where compare = compare `on` vectorFromInternal instance Show VectorInternal where showsPrec p = showsPrec p . vectorFromInternal vectorToInternal :: P.Vector Word64 -> VectorInternal vectorToInternal v = runST $ do PM.MVector off len mba <- P.unsafeThaw v ba <- unsafeFreezeByteArray mba return $ VectorInternal off len ba {-# INLINE vectorToInternal #-} vectorFromInternal :: VectorInternal -> P.Vector Word64 vectorFromInternal (VectorInternal off len ba) = runST $ do mba <- unsafeThawByteArray ba P.unsafeFreeze $ PM.MVector off len mba {-# INLINE vectorFromInternal #-} unsafeIndexInternal :: VectorInternal -> Int -> Word64 unsafeIndexInternal (VectorInternal off _ ba) i = indexByteArray ba (off + i) {-# INLINE unsafeIndexInternal #-} -- TODO(klao): create an index-checking version. popCountSlice :: VectorInternal -> Int -> Int -> Int popCountSlice (VectorInternal voff _ (ByteArray ba)) off len = popCountNWords ba (voff + off) len {-# INLINE popCountSlice #-} popCountBitSlice :: VectorInternal -> Int -> Int -> Int popCountBitSlice (VectorInternal voff _ (ByteArray ba)) off bitlen = popCountNBits ba (voff + off) bitlen {-# INLINE popCountBitSlice #-} popCount512Bits :: VectorInternal -> Int -> Int popCount512Bits (VectorInternal voff _ (ByteArray ba)) off = popCount512 ba (voff + off) {-# INLINE popCount512Bits #-}
Gabriel439/succinct
src/Succinct/Internal/PopCount.hs
bsd-2-clause
3,365
0
10
520
639
356
283
56
1
{-# OPTIONS_GHC -fno-implicit-prelude #-} ----------------------------------------------------------------------------- -- | -- Module : Numeric -- Copyright : (c) The University of Glasgow 2002 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : [email protected] -- Stability : provisional -- Portability : portable -- -- Odds and ends, mostly functions for reading and showing -- 'RealFloat'-like kind of values. -- ----------------------------------------------------------------------------- module Numeric ( -- * Showing showSigned, -- :: (Real a) => (a -> ShowS) -> Int -> a -> ShowS showIntAtBase, -- :: Integral a => a -> (a -> Char) -> a -> ShowS showInt, -- :: Integral a => a -> ShowS showHex, -- :: Integral a => a -> ShowS showOct, -- :: Integral a => a -> ShowS showEFloat, -- :: (RealFloat a) => Maybe Int -> a -> ShowS showFFloat, -- :: (RealFloat a) => Maybe Int -> a -> ShowS showGFloat, -- :: (RealFloat a) => Maybe Int -> a -> ShowS showFloat, -- :: (RealFloat a) => a -> ShowS floatToDigits, -- :: (RealFloat a) => Integer -> a -> ([Int], Int) -- * Reading -- | /NB:/ 'readInt' is the \'dual\' of 'showIntAtBase', -- and 'readDec' is the \`dual\' of 'showInt'. -- The inconsistent naming is a historical accident. readSigned, -- :: (Real a) => ReadS a -> ReadS a readInt, -- :: (Integral a) => a -> (Char -> Bool) -- -> (Char -> Int) -> ReadS a readDec, -- :: (Integral a) => ReadS a readOct, -- :: (Integral a) => ReadS a readHex, -- :: (Integral a) => ReadS a readFloat, -- :: (RealFloat a) => ReadS a lexDigits, -- :: ReadS String -- * Miscellaneous fromRat, -- :: (RealFloat a) => Rational -> a ) where #ifdef __GLASGOW_HASKELL__ import GHC.Base import GHC.Read import GHC.Real import GHC.Float import GHC.Num import GHC.Show import Data.Maybe import Text.ParserCombinators.ReadP( ReadP, readP_to_S, pfail ) import qualified Text.Read.Lex as L #else import Data.Char #endif #ifdef __HUGS__ import Hugs.Prelude import Hugs.Numeric #endif #ifdef __GLASGOW_HASKELL__ -- ----------------------------------------------------------------------------- -- Reading -- | Reads an /unsigned/ 'Integral' value in an arbitrary base. readInt :: Num a => a -- ^ the base -> (Char -> Bool) -- ^ a predicate distinguishing valid digits in this base -> (Char -> Int) -- ^ a function converting a valid digit character to an 'Int' -> ReadS a readInt base isDigit valDigit = readP_to_S (L.readIntP base isDigit valDigit) -- | Read an unsigned number in octal notation. readOct :: Num a => ReadS a readOct = readP_to_S L.readOctP -- | Read an unsigned number in decimal notation. readDec :: Num a => ReadS a readDec = readP_to_S L.readDecP -- | Read an unsigned number in hexadecimal notation. -- Both upper or lower case letters are allowed. readHex :: Num a => ReadS a readHex = readP_to_S L.readHexP -- | Reads an /unsigned/ 'RealFrac' value, -- expressed in decimal scientific notation. readFloat :: RealFrac a => ReadS a readFloat = readP_to_S readFloatP readFloatP :: RealFrac a => ReadP a readFloatP = do tok <- L.lex case tok of L.Rat y -> return (fromRational y) L.Int i -> return (fromInteger i) other -> pfail -- It's turgid to have readSigned work using list comprehensions, -- but it's specified as a ReadS to ReadS transformer -- With a bit of luck no one will use it. -- | Reads a /signed/ 'Real' value, given a reader for an unsigned value. readSigned :: (Real a) => ReadS a -> ReadS a readSigned readPos = readParen False read' where read' r = read'' r ++ (do ("-",s) <- lex r (x,t) <- read'' s return (-x,t)) read'' r = do (str,s) <- lex r (n,"") <- readPos str return (n,s) -- ----------------------------------------------------------------------------- -- Showing -- | Show /non-negative/ 'Integral' numbers in base 10. showInt :: Integral a => a -> ShowS showInt n cs | n < 0 = error "Numeric.showInt: can't show negative numbers" | otherwise = go n cs where go n cs | n < 10 = case unsafeChr (ord '0' + fromIntegral n) of c@(C# _) -> c:cs | otherwise = case unsafeChr (ord '0' + fromIntegral r) of c@(C# _) -> go q (c:cs) where (q,r) = n `quotRem` 10 -- Controlling the format and precision of floats. The code that -- implements the formatting itself is in @PrelNum@ to avoid -- mutual module deps. {-# SPECIALIZE showEFloat :: Maybe Int -> Float -> ShowS, Maybe Int -> Double -> ShowS #-} {-# SPECIALIZE showFFloat :: Maybe Int -> Float -> ShowS, Maybe Int -> Double -> ShowS #-} {-# SPECIALIZE showGFloat :: Maybe Int -> Float -> ShowS, Maybe Int -> Double -> ShowS #-} -- | Show a signed 'RealFloat' value -- using scientific (exponential) notation (e.g. @2.45e2@, @1.5e-3@). -- -- In the call @'showEFloat' digs val@, if @digs@ is 'Nothing', -- the value is shown to full precision; if @digs@ is @'Just' d@, -- then at most @d@ digits after the decimal point are shown. showEFloat :: (RealFloat a) => Maybe Int -> a -> ShowS -- | Show a signed 'RealFloat' value -- using standard decimal notation (e.g. @245000@, @0.0015@). -- -- In the call @'showFFloat' digs val@, if @digs@ is 'Nothing', -- the value is shown to full precision; if @digs@ is @'Just' d@, -- then at most @d@ digits after the decimal point are shown. showFFloat :: (RealFloat a) => Maybe Int -> a -> ShowS -- | Show a signed 'RealFloat' value -- using standard decimal notation for arguments whose absolute value lies -- between @0.1@ and @9,999,999@, and scientific notation otherwise. -- -- In the call @'showGFloat' digs val@, if @digs@ is 'Nothing', -- the value is shown to full precision; if @digs@ is @'Just' d@, -- then at most @d@ digits after the decimal point are shown. showGFloat :: (RealFloat a) => Maybe Int -> a -> ShowS showEFloat d x = showString (formatRealFloat FFExponent d x) showFFloat d x = showString (formatRealFloat FFFixed d x) showGFloat d x = showString (formatRealFloat FFGeneric d x) #endif /* __GLASGOW_HASKELL__ */ -- --------------------------------------------------------------------------- -- Integer printing functions -- | Shows a /non-negative/ 'Integral' number using the base specified by the -- first argument, and the character representation specified by the second. showIntAtBase :: Integral a => a -> (Int -> Char) -> a -> ShowS showIntAtBase base toChr n r | base <= 1 = error ("Numeric.showIntAtBase: applied to unsupported base " ++ show base) | n < 0 = error ("Numeric.showIntAtBase: applied to negative number " ++ show n) | otherwise = showIt (quotRem n base) r where showIt (n,d) r = seq c $ -- stricter than necessary case n of 0 -> r' _ -> showIt (quotRem n base) r' where c = toChr (fromIntegral d) r' = c : r -- | Show /non-negative/ 'Integral' numbers in base 16. showHex :: Integral a => a -> ShowS showHex = showIntAtBase 16 intToDigit -- | Show /non-negative/ 'Integral' numbers in base 8. showOct :: Integral a => a -> ShowS showOct = showIntAtBase 8 intToDigit
alekar/hugs
packages/base/Numeric.hs
bsd-3-clause
7,397
42
15
1,711
1,241
680
561
36
2
module L07.Anagrams where import Data.Char import Data.List import Data.Function {- Functions you will need -- * fmap :: (a -> b) -> IO a -> IO b * readFile :: FilePath -> IO String * lines :: String -> [String] * permutations :: [a] -> [[a]] * intersectBy :: (a -> a -> Bool) -> [a] -> [a] -> [a] * toLower :: Char -> Char Functions that might help - * on :: (b -> b -> c) -> (a -> b) -> a -> a -> c -} -- Return all anagrams of the given string -- that appear in the given dictionary file. anagrams :: String -> FilePath -> IO [String] anagrams = error "todo" -- Compare two strings for equality, ignoring case equalIgnoringCase :: String -> String -> Bool equalIgnoringCase = error "todo"
juretta/course
src/L07/Anagrams.hs
bsd-3-clause
717
0
8
162
73
42
31
16
1
{-# LANGUAGE TypeApplications #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeInType #-} module T17008b where import Data.Kind type family ConstType1 (a :: Type) :: Type where ConstType1 _ = Type type family F1 (x :: ConstType1 a) :: Type where F1 @a (x :: ConstType1 a) = a type family F2 (x :: ConstType1 a) :: ConstType1 a where F2 @a (x :: ConstType1 a) = x :: ConstType1 a type F3 (x :: ConstType1 a) = a type F4 (x :: ConstType1 a) = x :: ConstType1 a type ConstType2 (a :: Type) = Type type family G1 (x :: ConstType2 a) :: Type where G1 @a (x :: ConstType2 a) = a type family G2 (x :: ConstType2 a) :: ConstType2 a where G2 @a (x :: ConstType2 a) = x :: ConstType1 a type G3 (x :: ConstType2 a) = a type G4 (x :: ConstType2 a) = x :: ConstType2 a type Id1 (a :: Type) = a type family H (a :: Type) :: Type where H (Id1 a) = a type family I (x :: Id1 a) :: Type where I (x :: Id1 a) = a type family Id2 (a :: Type) :: Type where Id2 a = a type family J (x :: Id2 a) :: Type where J (x :: Id2 a) = a
sdiehl/ghc
testsuite/tests/indexed-types/should_compile/T17008b.hs
bsd-3-clause
1,036
28
10
250
484
263
221
-1
-1
{-# LANGUAGE PatternGuards, ViewPatterns, DeriveDataTypeable #-} module General.Template( Template, templateFile, templateStr, templateApply, templateRender ) where import Data.Data import Data.Monoid import General.Str import Data.Generics.Uniplate.Data import Control.Applicative import System.IO.Unsafe import System.Directory import Data.IORef import Prelude --------------------------------------------------------------------- -- TREE DATA TYPE data Tree = Lam FilePath -- #{foo} defines a lambda | Var Str -- a real variable | App Tree [(Str, Tree)] -- applies a foo string to the lambda | Lit Str | List [Tree] deriving (Typeable,Data,Show) -- | Turn all Lam into Var/Lit treeRemoveLam :: Tree -> IO Tree treeRemoveLam = transformM f where f (Lam file) = List . parse <$> strReadFile file f x = return x parse x | Just (a,b) <- strSplitInfix (strPack "#{") x , Just (b,c) <- strSplitInfix (strPack "}") b = Lit a : Var b : parse c parse x = [Lit x] treeRemoveApp :: Tree -> Tree treeRemoveApp = f [] where f seen (App t xs) = f (xs ++ seen) t f seen (Var x) | Just t <- lookup x seen = f seen t f seen x = descend (f seen) x treeOptimise :: Tree -> Tree treeOptimise = transform f . treeRemoveApp where fromList (List xs) = xs; fromList x = [x] toList [x] = x; toList xs = List xs isLit (Lit x) = True; isLit _ = False fromLit (Lit x) = x f = toList . g . concatMap fromList . fromList g [] = [] g (x:xs) | not $ isLit x = x : g xs g xs = [Lit x | let x = mconcat $ map fromLit a, x /= mempty] ++ g b where (a,b) = span isLit xs treeEval :: Tree -> [Str] treeEval = f . treeRemoveApp where f (Lit x) = [x] f (List xs) = concatMap f xs f _ = [] --------------------------------------------------------------------- -- TEMPLATE DATA TYPE -- a tree, and a pre-optimised tree you can create data Template = Template Tree (IO Tree) {-# NOINLINE treeCache #-} treeCache :: Tree -> IO Tree treeCache t0 = unsafePerformIO $ do let files = [x | Lam x <- universe t0] ref <- newIORef ([], treeOptimise t0) return $ do (old,t) <- readIORef ref new <- mapM getModificationTime files if old == new then return t else do t <- treeOptimise <$> treeRemoveLam t0 writeIORef ref (new,t) return t templateTree :: Tree -> Template templateTree t = Template t $ treeCache t templateFile :: FilePath -> Template templateFile = templateTree . Lam templateStr :: LStr -> Template templateStr = templateTree . List . map Lit . lstrToChunks templateApply :: Template -> [(String, Template)] -> Template templateApply (Template t _) args = templateTree $ App t [(strPack a, b) | (a,Template b _) <- args] templateRender :: Template -> [(String, Template)] -> IO LStr templateRender (Template _ t) args = do t <- t let Template t2 _ = templateApply (Template t $ return t) args lstrFromChunks . treeEval <$> treeRemoveLam t2
wolftune/hoogle
src/General/Template.hs
bsd-3-clause
3,170
0
16
861
1,142
584
558
73
6
{-# LANGUAGE RebindableSyntax #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE DataKinds #-} --{-# LANGUAGE TypeOperators #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} -- Ignore our orphan instance in this file. {-# OPTIONS_GHC -fno-warn-orphans #-} -- Use the supermonad plugin. {-# OPTIONS_GHC -fplugin Control.Supermonad.Plugin #-} import Control.Supermonad.Prelude import qualified Control.Effect as E import Control.Effect ( Plus, Inv ) import Control.Effect.CounterNat import GHC.TypeLits instance Functor (Counter (s :: Nat)) where fmap f ma = ma E.>>= (E.return . f) instance (h ~ Plus Counter f g) => Bind (Counter (f :: Nat)) (Counter (g :: Nat)) (Counter (h :: Nat)) where type BindCts (Counter (f :: Nat)) (Counter (g :: Nat)) (Counter (h :: Nat)) = Inv Counter f g (>>=) = (E.>>=) instance Return (Counter (0 :: Nat)) where return = E.return instance (h ~ Plus Counter f g) => Applicative (Counter (f :: Nat)) (Counter (g :: Nat)) (Counter (h :: Nat)) where type ApplicativeCts (Counter (f :: Nat)) (Counter (g :: Nat)) (Counter (h :: Nat)) = Inv Counter f g mf <*> ma = mf E.>>= \f -> fmap f ma instance Fail (Counter (h :: Nat)) where fail = E.fail main :: IO () main = do print $ forget (limitedOp 1 2 3 4) -- 10 specialOp :: Int -> Int -> Counter 1 Int specialOp n m = tick (n + m) limitedOp :: Int -> Int -> Int -> Int -> Counter 3 Int limitedOp a b c d = do ab <- specialOp a b abc <- specialOp ab c specialOp abc d
jbracker/supermonad-plugin
examples/monad/effect/MainSupermonad3.hs
bsd-3-clause
1,502
1
10
299
580
315
265
34
1
import Control.Concurrent.MVar main = do mv <- forkIO $ do putMVar "one"
the-real-blackh/hexpat
test/dealloc.hs
bsd-3-clause
100
0
11
39
29
14
15
-1
-1
{-# LANGUAGE CPP #-} module Network.Wai.Handler.Warp.SendFile where import Data.ByteString (ByteString) import Network.Sendfile import Network.Socket (Socket) import qualified Network.Wai.Handler.Warp.FdCache as F import Network.Wai.Handler.Warp.Types defaultSendFile :: Socket -> FilePath -> Integer -> Integer -> IO () -> [ByteString] -> IO () defaultSendFile s path off len act hdr = sendfileWithHeader s path (PartOfFile off len) act hdr #if SENDFILEFD setSendFile :: Connection -> Maybe F.MutableFdCache -> Connection setSendFile conn Nothing = conn setSendFile conn (Just fdcs) = case connSendFileOverride conn of NotOverride -> conn Override s -> conn { connSendFile = sendFile fdcs s } sendFile :: F.MutableFdCache -> Socket -> FilePath -> Integer -> Integer -> IO () -> [ByteString] -> IO () sendFile fdcs s path off len act hdr = do (fd, fresher) <- F.getFd fdcs path sendfileFdWithHeader s fd (PartOfFile off len) (act>>fresher) hdr #else setSendFile :: Connection -> Maybe F.MutableFdCache -> Connection setSendFile conn _ = conn #endif
sol/wai
warp/Network/Wai/Handler/Warp/SendFile.hs
mit
1,075
0
13
177
332
177
155
11
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-missing-fields #-} {-# OPTIONS_GHC -fno-warn-missing-signatures #-} {-# OPTIONS_GHC -fno-warn-name-shadowing #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} ----------------------------------------------------------------- -- Autogenerated by Thrift -- -- -- DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING -- @generated ----------------------------------------------------------------- module TestService_Client(init) where import Data.IORef import Prelude ( Bool(..), Enum, Float, IO, Double, String, Maybe(..), Eq, Show, Ord, concat, error, fromIntegral, fromEnum, length, map, maybe, not, null, otherwise, return, show, toEnum, enumFromTo, Bounded, minBound, maxBound, seq, succ, pred, enumFrom, enumFromThen, enumFromThenTo, (.), (&&), (||), (==), (++), ($), (-), (>>=), (>>)) import qualified Control.Applicative as Applicative (ZipList(..)) import Control.Applicative ( (<*>) ) import qualified Control.DeepSeq as DeepSeq import qualified Control.Exception as Exception import qualified Control.Monad as Monad ( liftM, ap, when ) import qualified Data.ByteString.Lazy as BS import Data.Functor ( (<$>) ) import qualified Data.Hashable as Hashable import qualified Data.Int as Int import Data.List import qualified Data.Maybe as Maybe (catMaybes) import qualified Data.Text.Lazy.Encoding as Encoding ( decodeUtf8, encodeUtf8 ) import qualified Data.Text.Lazy as LT import qualified Data.Typeable as Typeable ( Typeable ) import qualified Data.HashMap.Strict as Map import qualified Data.HashSet as Set import qualified Data.Vector as Vector import qualified Test.QuickCheck.Arbitrary as Arbitrary ( Arbitrary(..) ) import qualified Test.QuickCheck as QuickCheck ( elements ) import qualified Thrift import qualified Thrift.Types as Types import qualified Thrift.Serializable as Serializable import qualified Thrift.Arbitraries as Arbitraries import qualified Module_Types import qualified TestService seqid = newIORef 0 init (ip,op) arg_int1 arg_int2 arg_int3 arg_int4 arg_int5 arg_int6 arg_int7 arg_int8 arg_int9 arg_int10 arg_int11 arg_int12 arg_int13 arg_int14 arg_int15 arg_int16 = do send_init op arg_int1 arg_int2 arg_int3 arg_int4 arg_int5 arg_int6 arg_int7 arg_int8 arg_int9 arg_int10 arg_int11 arg_int12 arg_int13 arg_int14 arg_int15 arg_int16 recv_init ip send_init op arg_int1 arg_int2 arg_int3 arg_int4 arg_int5 arg_int6 arg_int7 arg_int8 arg_int9 arg_int10 arg_int11 arg_int12 arg_int13 arg_int14 arg_int15 arg_int16 = do seq <- seqid seqn <- readIORef seq Thrift.writeMessage op ("init", Types.M_CALL, seqn) $ TestService.write_Init_args op (TestService.Init_args{TestService.init_args_int1=arg_int1,TestService.init_args_int2=arg_int2,TestService.init_args_int3=arg_int3,TestService.init_args_int4=arg_int4,TestService.init_args_int5=arg_int5,TestService.init_args_int6=arg_int6,TestService.init_args_int7=arg_int7,TestService.init_args_int8=arg_int8,TestService.init_args_int9=arg_int9,TestService.init_args_int10=arg_int10,TestService.init_args_int11=arg_int11,TestService.init_args_int12=arg_int12,TestService.init_args_int13=arg_int13,TestService.init_args_int14=arg_int14,TestService.init_args_int15=arg_int15,TestService.init_args_int16=arg_int16}) Thrift.tFlush (Thrift.getTransport op) recv_init ip = Thrift.readMessage ip $ \(fname,mtype,rseqid) -> do Monad.when (mtype == Types.M_EXCEPTION) $ Thrift.readAppExn ip >>= Exception.throw res <- TestService.read_Init_result ip return $ TestService.init_result_success res
LinusU/fbthrift
thrift/compiler/test/fixtures/service-fuzzer/gen-hs/TestService_Client.hs
apache-2.0
3,808
0
14
547
860
538
322
56
1
{-| Implementation of Utility functions for storage -} {- Copyright (C) 2013 Google Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} module Ganeti.Storage.Utils ( getStorageUnitsOfNodes , nodesWithValidConfig ) where import Ganeti.Config import Ganeti.Objects import Ganeti.Types import qualified Ganeti.Types as T import Control.Monad import Data.List (nub) import Data.Maybe import qualified Data.Map as M -- | Get the cluster's default storage unit for a given disk template getDefaultStorageKey :: ConfigData -> DiskTemplate -> Maybe StorageKey getDefaultStorageKey cfg T.DTDrbd8 = clusterVolumeGroupName $ configCluster cfg getDefaultStorageKey cfg T.DTPlain = clusterVolumeGroupName $ configCluster cfg getDefaultStorageKey cfg T.DTFile = Just (clusterFileStorageDir $ configCluster cfg) getDefaultStorageKey _ _ = Nothing -- | Get the cluster's default spindle storage unit getDefaultSpindleSU :: ConfigData -> (StorageType, Maybe StorageKey) getDefaultSpindleSU cfg = (T.StorageLvmPv, clusterVolumeGroupName $ configCluster cfg) -- | Get the cluster's storage units from the configuration getClusterStorageUnitRaws :: ConfigData -> [StorageUnitRaw] getClusterStorageUnitRaws cfg = foldSUs (nub (maybe_units ++ [spindle_unit])) where disk_templates = clusterEnabledDiskTemplates $ configCluster cfg storage_types = map diskTemplateToStorageType disk_templates maybe_units = zip storage_types (map (getDefaultStorageKey cfg) disk_templates) spindle_unit = getDefaultSpindleSU cfg -- | fold the storage unit list by sorting out the ones without keys foldSUs :: [(StorageType, Maybe StorageKey)] -> [StorageUnitRaw] foldSUs = foldr ff [] where ff (st, Just sk) acc = SURaw st sk : acc ff (_, Nothing) acc = acc -- | Gets the value of the 'exclusive storage' flag of the node getExclusiveStorage :: ConfigData -> Node -> Maybe Bool getExclusiveStorage cfg n = liftM ndpExclusiveStorage (getNodeNdParams cfg n) -- | Determines whether a node's config contains an 'exclusive storage' flag hasExclusiveStorageFlag :: ConfigData -> Node -> Bool hasExclusiveStorageFlag cfg = isJust . getExclusiveStorage cfg -- | Filter for nodes with a valid config nodesWithValidConfig :: ConfigData -> [Node] -> [Node] nodesWithValidConfig cfg = filter (hasExclusiveStorageFlag cfg) -- | Get the storage units of the node getStorageUnitsOfNode :: ConfigData -> Node -> [StorageUnit] getStorageUnitsOfNode cfg n = let clusterSUs = getClusterStorageUnitRaws cfg es = fromJust (getExclusiveStorage cfg n) in map (addParamsToStorageUnit es) clusterSUs -- | Get the storage unit map for all nodes getStorageUnitsOfNodes :: ConfigData -> [Node] -> M.Map String [StorageUnit] getStorageUnitsOfNodes cfg ns = M.fromList (map (\n -> (nodeUuid n, getStorageUnitsOfNode cfg n)) ns)
apyrgio/ganeti
src/Ganeti/Storage/Utils.hs
bsd-2-clause
4,069
0
11
647
625
334
291
46
2
{-# LANGUAGE TemplateHaskell #-} module StringsQQ (strings, longstring, typenames) where import Language.Haskell.TH import Language.Haskell.TH.Quote import Data.Char (toUpper) strings = QuasiQuoter { quotePat = undefined, quoteType = undefined, quoteExp = stringsExp, quoteDec = undefined } -- stringE = return . LitE . StringL stringsExp :: String -> Q Exp stringsExp = foldr (\x xs -> [e| $(x) : $(xs) |]) [e| [] |] . map delta . filter (not . null) . map words . lines where delta [(x:xs)] = [e| ( $(stringE $ x:xs ) , $(stringE $ toUpper x : xs ) ) |] delta [xs,ys] = [e| ( $(stringE xs) , $(stringE ys) ) |] longstring = QuasiQuoter { quotePat = undefined, quoteType = undefined, quoteExp = longstringExp, quoteDec = undefined } longstringExp ('\n':xs) = stringE xs longstringExp xs = stringE xs typenames = QuasiQuoter { quotePat = undefined, quoteType = undefined, quoteExp = typenamesExp, quoteDec = undefined } typenamesExp :: String -> Q Exp typenamesExp = foldr (\x xs -> [e| $(x) : $(xs) |]) [e| [] |] . map delta . filter (not . null) . map words . lines where delta [xs] = delta [xs,xs] delta [xs,ys] = [e| ( $(stringE xs) , $(stringE ys) ) |]
tomjaguarpaw/postgresql-simple
tools/StringsQQ.hs
bsd-3-clause
1,487
0
11
531
388
232
156
30
2
module RenameParamIn5 where merge :: (a -> a -> Ordering) -> [a] -> [a] -> [a] merge cmp xs [] = xs merge cmp [] ys = ys merge cmp (x:xs) (y:ys) = case x `cmp` y of GT -> y : merge cmp (x:xs) ys _ -> x : merge cmp xs (y:ys) {- mergeIt xs ys = merge compare xs ys -} mergeIt xs ys = (case (compare, xs, ys) of (cmp, xs, []) -> xs (cmp, [], ys) -> ys (cmp, (x : xs), (y : ys)) -> case x `cmp` y of GT -> y : (merge cmp (x : xs) ys) _ -> x : (merge cmp xs (y : ys))) {- select second occurrence of merge cmp (x:xs) ys to replace it with mergeIt xs (y:ys) -}
kmate/HaRe
old/testing/generativeFold/RenameParamIn5.hs
bsd-3-clause
748
0
16
326
308
170
138
15
4
{-# LANGUAGE DataKinds #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE UnboxedSums #-} {-# LANGUAGE UnboxedTuples #-} {-# LANGUAGE TypeFamilies #-} module KindSigs where import Data.Kind -- Kind annotation on type family instance equation type family Foo a where Foo a = Int :: Type -- Kind annotation on component of tuple type type Bar a = ( Int :: Type, Bool, Maybe a :: Type ) type Bar' a = (# Int :: Type, Bool, Maybe a :: Type #) -- Kind annotation on type of list type Baz = [ Int :: Type ] -- Kind annotation inside paren type qux :: (Int :: Type) -> Bool -> (() :: Type) qux _ _ = () -- Kind annotation on promoted lists and tuples type Quux = '[ True :: Bool ] type Quux' = [ True :: Bool, False :: Bool ] type Quuux b = '( [Int, Bool] :: [Type], b ) -- Kind annotation on the RHS of a type synonym type Sarsaparilla = Int :: Type -- Note that 'true :: Bool :: Type' won't parse - you need some parens true :: (Bool :: Type) true = True
sdiehl/ghc
testsuite/tests/parser/should_compile/KindSigs.hs
bsd-3-clause
959
16
9
205
245
145
100
-1
-1
module Lamdu.Data.Expression.Infer.Structure (add) where import Control.Applicative ((<$>), Applicative(..)) import Control.Lens.Operators import Control.Monad (void) import Control.Monad.Trans.Class (lift) import Control.Monad.Trans.State (StateT) import Control.MonadA (MonadA) import qualified Control.Lens as Lens import qualified Control.Monad.Trans.State as State import qualified Lamdu.Data.Expression as Expr import qualified Lamdu.Data.Expression.Utils as ExprUtil import qualified Lamdu.Data.Expression.Infer as Infer import qualified Lamdu.Data.Expression.Infer.UntilConflict as InferUntilConflict import qualified Lamdu.Data.Expression.Lens as ExprLens add :: (Ord def, MonadA m) => Infer.Loader def m -> Expr.Expression def (Infer.Inferred def, a) -> StateT (Infer.Context def) m (Expr.Expression def (Infer.Inferred def, a)) add loader expr = State.gets . Infer.derefExpr =<< addToNodes loader expr -- TODO: use Lens.outside addToNodes :: (Ord def, MonadA m) => Infer.Loader def m -> Expr.Expression def (Infer.Inferred def, a) -> StateT (Infer.Context def) m (Expr.Expression def (Infer.Node def, a)) addToNodes loader expr@(Expr.Expression body (inferred, a)) | Lens.has ExprLens.bodyHole body && Lens.has ExprLens.exprHole (Infer.iValue inferred) = do loaded <- lift . Infer.load loader Nothing . ExprUtil.structureForType . void $ Infer.iType inferred _ <- InferUntilConflict.inferAssertNoConflict "Structure.addToNode" loaded point pure $ expr <&> Lens._1 .~ point | otherwise = (`Expr.Expression` (point, a)) <$> (body & Lens.traversed %%~ addToNodes loader) where point = Infer.iNode inferred
aleksj/lamdu
Lamdu/Data/Expression/Infer/Structure.hs
gpl-3.0
1,683
0
14
255
547
307
240
40
1
import Control.Monad (unless,when) import Data.List (isInfixOf) import StackTest main :: IO () main = do stack [defaultResolverArg, "clean"] stack [defaultResolverArg, "init", "--force"] stackCheckStderr ["build", "also-has-exe-foo", "has-exe-foo"] (expectMessage buildMessage1) stackCheckStderr ["build", "has-exe-foo-too"] (expectMessage buildMessage2) expectMessage :: String -> String -> IO () expectMessage msg stderr = unless (msg `isInfixOf` stderr) (error $ "Expected a warning: \n" ++ show msg) buildMessage1 = unlines [ "Building several executables with the same name: 'also-has-exe-foo:foo', 'has-exe-foo:foo'." , "Only one of them will be available via 'stack exec' or locally installed." , "Other executables with the same name might be overwritten: 'has-exe-foo-too:foo'." ] buildMessage2 = unlines [ "Building executable 'has-exe-foo-too:foo'." , "Other executables with the same name might be overwritten: 'also-has-exe-foo:foo', 'has-exe-foo:foo'." ]
AndreasPK/stack
test/integration/tests/1198-multiple-exes-with-same-name/Main.hs
bsd-3-clause
1,097
0
9
245
199
107
92
26
1
{- © 2012 Johan Kiviniemi <[email protected]> Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -} {-# OPTIONS_GHC -fno-warn-orphans #-} module Network.Rcon.Tests.Serialize ( tests ) where import Network.Rcon.Serialize import Control.Applicative import qualified Data.ByteString as BS import Data.Serialize import Data.Word import Test.Framework (Test, testGroup) import Test.Framework.Providers.QuickCheck2 (testProperty) import Test.QuickCheck tests :: Test tests = testGroup "Network.Rcon.Tests.Serialize" [ testProperty "encodeDecodeQ" (againstQ prop_encodeDecode) , testProperty "encodeDecodeR" (againstR prop_encodeDecode) , testProperty "shortQ" (againstQ prop_short) , testProperty "shortR" (againstR prop_short) , testProperty "longQ" (againstQ prop_long) , testProperty "longR" (againstR prop_long) ] againstQ :: Testable a => (QueryPacket -> a) -> (QueryPacket -> a) againstQ = id againstR :: Testable a => (ResponsePacket -> a) -> (ResponsePacket -> a) againstR = id -- decode . encode ≡ Right prop_encodeDecode :: (Serialize a, Eq a) => a -> Bool prop_encodeDecode packet = (decode . encode) packet == Right packet -- Removing the last byte results in parse failure. prop_short :: Serialize a => a -> Bool prop_short = corrupt_prop BS.init -- Adding an extra byte results in parse failure. prop_long :: Serialize a => a -> Word8 -> Bool prop_long packet extra = corrupt_prop (`BS.snoc` extra) packet corrupt_prop :: Serialize a => (BS.ByteString -> BS.ByteString) -> a -> Bool corrupt_prop corrupt packet = isLeft $ (decode . corrupt . encode) packet `asTypeOf` Right packet isLeft :: Either a b -> Bool isLeft (Left _) = True isLeft _ = False instance Arbitrary QueryPacket where arbitrary = oneof [ AuthQ <$> arbitrary <*> nonNullBS , ExecCommandQ <$> arbitrary <*> nonNullBS ] shrink (AuthQ id_ pass) = AuthQ <$> shrink id_ <*> pure pass <|> AuthQ <$> pure id_ <*> shrinkNonNullBS pass shrink (ExecCommandQ id_ cmd) = ExecCommandQ <$> shrink id_ <*> pure cmd <|> ExecCommandQ <$> pure id_ <*> shrinkNonNullBS cmd <|> pure (AuthQ id_ cmd) instance Arbitrary ResponsePacket where arbitrary = oneof [ AuthR <$> arbitrary <*> nonNullBS , DataR <$> arbitrary <*> nonNullBS ] shrink (AuthR id_ data_) = AuthR <$> shrink id_ <*> pure data_ <|> AuthR <$> pure id_ <*> shrinkNonNullBS data_ shrink (DataR id_ data_) = DataR <$> shrink id_ <*> pure data_ <|> DataR <$> pure id_ <*> shrinkNonNullBS data_ <|> pure (AuthR id_ data_) nonNullBS :: Gen BS.ByteString nonNullBS = BS.pack <$> listOf (choose (1, maxBound)) shrinkNonNullBS :: BS.ByteString -> [BS.ByteString] shrinkNonNullBS = map (BS.pack . map unPositive) . shrink . map Positive . BS.unpack where unPositive (Positive a) = a -- vim:set et sw=2 sts=2:
ion1/rcon-haskell
Network/Rcon/Tests/Serialize.hs
isc
3,857
0
12
987
872
451
421
63
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE TemplateHaskell #-} module Data.FreeAgent.Types.QuickStart where import qualified Data.ByteString as BS import Control.Applicative ((<$>), (<*>), empty) import Control.Lens import Data.Aeson import Data.Aeson.TH import Data.Data data Company = Company { _company_start_date :: BS.ByteString -- 2010-07-01 , _currency :: BS.ByteString -- GBP , _sales_tax_registration_status :: BS.ByteString -- Registered , _mileage_units :: BS.ByteString -- miles , _type :: BS.ByteString -- UkLimitedCompany } deriving (Show, Data, Typeable) instance FromJSON Company where parseJSON (Object v) = Company <$> v .: "company_start_date" <*> v .: "currency" <*> v .: "sales_tax_registration_status" <*> v .: "mileage_units" <*> v .: "type" parseJSON _ = empty $(deriveToJSON tail ''Company) $(makeLenses ''Company)
perurbis/hfreeagent
src/Data/FreeAgent/Types/QuickStart.hs
mit
1,157
0
15
386
225
131
94
27
0
{-# LANGUAGE AllowAmbiguousTypes #-} {-# LANGUAGE CPP #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE InstanceSigs #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE OverloadedLists #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} #if __GLASGOW_HASKELL__ >= 804 {-# LANGUAGE PolyKinds #-} #endif -- Redundant constraint: api ~ someApiType n a -- in `apiArgName` {-# OPTIONS_GHC -Wno-redundant-constraints #-} -- | Some utilites for more flexible servant usage. module Pos.Util.Servant ( ApiHasArgClass (..) , ApiCanLogArg (..) , ModifiesApiRes (..) , VerbMod , ReportDecodeError (..) , CDecodeApiArg , OriginType , FromCType (..) , ToCType (..) , WithDefaultApiArg , HasLoggingServer (..) , ApiLoggingConfig (..) , ApiParamsLogInfo (..) , LoggingApi , LoggingApiRec , WithTruncatedLog (..) , HasTruncateLogPolicy (..) , _ApiParamsLogInfo , _ApiNoParamsLogInfo , addParamLogInfo , CQueryParam , CCapture , CReqBody , DReqBody , DCQueryParam , DQueryParam , DHeader , Flaggable (..) , CustomQueryFlag , HasCustomQueryFlagDescription(..) , serverHandlerL , serverHandlerL' , inRouteServer , applicationJson , applyLoggingToHandler , ValidJSON , Tag , TagDescription(..) , mapRouter , APIResponse(..) , single , Metadata(..) , UnknownError(..) , JsendException(..) ) where import Universum import Control.Exception.Safe (handleAny) import Control.Lens (Iso, iso, ix, makePrisms, (?~)) import Control.Monad.Except (ExceptT (..), MonadError (..)) import Data.Aeson (FromJSON (..), ToJSON (..), eitherDecode, encode, object, (.=)) import qualified Data.Aeson.Options as Aeson import Data.Aeson.TH (deriveJSON) import qualified Data.Char as Char import Data.Constraint ((\\)) import Data.Constraint.Forall (Forall, inst) import Data.Default (Default (..)) import Data.List (lookup) import Data.Reflection (Reifies (..), reflect) import Data.Swagger (NamedSchema (..), ParamAnySchema (..), ParamLocation (..), SwaggerType (..), ToSchema (..), allowEmptyValue, applyTagsFor, declareSchemaRef, defaultSchemaOptions, default_, description, genericDeclareNamedSchema, in_, name, operationsOf, paramSchema, properties, required, schema, toParamSchema, type_) import qualified Data.Swagger as S import qualified Data.Text as T import Data.Time.Clock.POSIX (getPOSIXTime) import Data.Typeable (typeOf, typeRep) import Formatting (bprint, build, builder, fconst, formatToString, sformat, shown, stext, string, (%)) import qualified Formatting.Buildable import Generics.SOP.TH (deriveGeneric) import GHC.IO.Unsafe (unsafePerformIO) import GHC.TypeLits (KnownSymbol, Symbol, symbolVal) import Network.HTTP.Types (hContentType, parseQueryText) import qualified Network.HTTP.Types as HTTPTypes import Network.Wai (rawQueryString) import Serokell.Util (listJsonIndent) import Serokell.Util.ANSI (Color (..), colorizeDull) import Servant.API ((:<|>) (..), (:>), Capture, Description, Header, OctetStream, QueryFlag, QueryParam, ReflectMethod (..), ReqBody, Summary, Verb) import Servant.API.ContentTypes (Accept (..), JSON, MimeRender (..), MimeUnrender (..)) import Servant.Client (Client, HasClient (..)) import Servant.Client.Core (RunClient) import Servant.Server (Handler (..), HasServer (..), ServantErr (..), Server) import qualified Servant.Server.Internal as SI import Servant.Swagger import Servant.Swagger.Internal import Test.QuickCheck import Pos.Infra.Util.LogSafe (BuildableSafe, SecuredText, buildSafe, logInfoSP, plainOrSecureF, secretOnlyF) import Pos.Util.Example (Example (..)) import Pos.Util.Jsend (HasDiagnostic (..), ResponseStatus (..), jsendErrorGenericParseJSON, jsendErrorGenericToJSON) import Pos.Util.Pagination import Pos.Util.Wlog (LoggerName, LoggerNameBox, usingLoggerName) ------------------------------------------------------------------------- -- Utility functions ------------------------------------------------------------------------- serverHandlerL :: Iso (Handler a) (Handler b) (ExceptT ServantErr IO a) (ExceptT ServantErr IO b) serverHandlerL = iso runHandler' Handler serverHandlerL' :: Iso (Handler a) (Handler b) (IO $ Either ServantErr a) (IO $ Either ServantErr b) serverHandlerL' = serverHandlerL . iso runExceptT ExceptT inRouteServer :: forall api api' ctx env. (Proxy api -> SI.Context ctx -> SI.Delayed env (Server api) -> SI.Router env) -> (Server api' -> Server api) -> (Proxy api' -> SI.Context ctx -> SI.Delayed env (Server api') -> SI.Router env) inRouteServer routing f = \_ ctx delayed -> routing Proxy ctx (fmap f delayed) ------------------------------------------------------------------------- -- General useful families ------------------------------------------------------------------------- -- | Extract right side of type application. type family ApplicationRS api where ApplicationRS (apiType a) = a -- | Proves info about argument specifier of servant API. class ApiHasArgClass api where -- | For arguments-specifiers of API, get argument type. -- E.g. @Capture "cap" Int@ -> @Int@. type ApiArg api :: * type ApiArg api = ApplicationRS api -- | Name of argument. -- E.g. name of argument specified by @Capture "nyan"@ is /nyan/. apiArgName :: Proxy api -> String default apiArgName -- Note [redundant constraint] -- GHC thinks 'api ~ someApiType n a' is a redundant constraint! -- It's not: it makes the 'KnownSymbol n' constraint useful. :: forall n someApiType a. (KnownSymbol n, api ~ someApiType n a) => Proxy api -> String apiArgName _ = formatToString ("'"%string%"' field") $ symbolVal (Proxy @n) class ServerT (subApi :> res) m ~ (ApiArg subApi -> ServerT res m) => ApiHasArgInvariant subApi res m instance ServerT (subApi :> res) m ~ (ApiArg subApi -> ServerT res m) => ApiHasArgInvariant subApi res m type ApiHasArg subApi res = ( ApiHasArgClass subApi , ApiHasArgInvariant subApi res Handler -- this one for common cases , Forall (ApiHasArgInvariant subApi res) -- and this is generalized one ) instance KnownSymbol s => ApiHasArgClass (Capture s a) instance KnownSymbol s => ApiHasArgClass (QueryFlag s) where type ApiArg (QueryFlag s) = Bool apiArgName :: Proxy (QueryFlag s) -> String apiArgName _ = formatToString ("'"%string%"' field") $ symbolVal (Proxy @s) instance KnownSymbol s => ApiHasArgClass (QueryParam s a) where type ApiArg (QueryParam s a) = Maybe a instance ApiHasArgClass (ReqBody ct a) where apiArgName _ = "request body" ------------------------------------------------------------------------- -- Mapping API result ------------------------------------------------------------------------- -- | Modifies result of API. class ModifiesApiRes t where type ApiModifiedRes t a :: * modifyApiResult :: Proxy t -> IO (Either ServantErr a) -> IO (Either ServantErr (ApiModifiedRes t a)) -- | Wrapper to modify result of API. -- @modType@ argument specifies transformation and should be instance of -- 'ModifiesApiRes'. data VerbMod (modType :: *) api instance ( HasServer (Verb mt st ct $ ApiModifiedRes mod a) ctx , HasServer (Verb mt st ct a) ctx , ModifiesApiRes mod ) => HasServer (VerbMod mod $ Verb (mt :: k1) (st :: Nat) (ct :: [*]) a) ctx where type ServerT (VerbMod mod $ Verb mt st ct a) m = ServerT (Verb mt st ct a) m route = inRouteServer @(Verb mt st ct $ ApiModifiedRes mod a) route $ serverHandlerL' %~ modifyApiResult (Proxy @mod) hoistServerWithContext _ pc nt s = hoistServerWithContext (Proxy :: Proxy (Verb mt st ct api)) pc nt s instance HasSwagger v => HasSwagger (VerbMod mod v) where toSwagger _ = toSwagger $ Proxy @v ------------------------------------------------------------------------- -- Mapping API arguments: client types decoding ------------------------------------------------------------------------- -- | For many types with nice structure there exists a /client type/, which is -- an intermediate representation between internal types and JSON. -- | This family maps /client types/ to their respective original types -- (e.g. @CAccountAddress@ -> @AccountAddress@). type family OriginType ctype :: * class FromCType c where -- | Way to decode from @CType@. decodeCType :: c -> Either Text (OriginType c) class ToCType c where -- | Way to encode to @CType@. encodeCType :: OriginType c -> c type instance OriginType (Maybe a) = Maybe $ OriginType a instance FromCType a => FromCType (Maybe a) where decodeCType = mapM decodeCType -- | Allows to throw error from anywhere within the internals of Servant API. class ReportDecodeError api where -- | Propagate error to servant handler. reportDecodeError :: Proxy api -> Text -> Server api instance ( ReportDecodeError res , ApiHasArg subApi res ) => ReportDecodeError (subApi :> res) where reportDecodeError _ err = \_ -> reportDecodeError (Proxy @res) err -- | Wrapper over API argument specifier which says to decode specified argument -- with 'decodeCType'. data CDecodeApiArg subApi instance ApiHasArgClass subApi => ApiHasArgClass (CDecodeApiArg subApi) where type ApiArg (CDecodeApiArg subApi) = OriginType (ApiArg subApi) apiArgName _ = apiArgName (Proxy @subApi) instance ( HasServer (subApi :> res) ctx , HasServer res ctx , ApiHasArg subApi res , FromCType (ApiArg subApi) , ReportDecodeError res ) => HasServer (CDecodeApiArg subApi :> res) ctx where type ServerT (CDecodeApiArg subApi :> res) m = OriginType (ApiArg subApi) -> ServerT res m route = inRouteServer @(subApi :> res) route $ \f a -> either reportE f $ decodeCType a where reportE err = reportDecodeError (Proxy @res) $ sformat ("(in "%string%") "%stext) (apiArgName $ Proxy @subApi) err hoistServerWithContext _ pc nt s = hoistServerWithContext (Proxy @res) pc nt . s instance HasSwagger (subApi :> res) => HasSwagger (CDecodeApiArg subApi :> res) where toSwagger _ = toSwagger (Proxy @(subApi :> res)) ------------------------------------------------------------------------- -- Mapping API arguments: defaults ------------------------------------------------------------------------- type family UnmaybeArg a where UnmaybeArg (Maybe a -> b) = a -> b type family Unmaybe a where Unmaybe (Maybe a) = a data WithDefaultApiArg subApi instance (ApiHasArgClass subApi, ApiArg subApi ~ Maybe b) => ApiHasArgClass (WithDefaultApiArg subApi) where type ApiArg (WithDefaultApiArg subApi) = Unmaybe (ApiArg subApi) apiArgName _ = apiArgName (Proxy @subApi) instance ( HasServer (subApi :> res) ctx , HasServer res ctx , ApiHasArg (WithDefaultApiArg subApi) res , Server (subApi :> res) ~ (Maybe c -> d) , Default c ) => HasServer (WithDefaultApiArg subApi :> res) ctx where type ServerT (WithDefaultApiArg subApi :> res) m = UnmaybeArg (ServerT (subApi :> res) m) route = inRouteServer @(subApi :> res) route $ \f a -> f $ fromMaybe def a -- The simpliest what we can do here is to delegate to -- @hoistServer (Proxy @res)@. -- However to perform that we need a knowledge of that -- @ServerT (withDefaultApiArg subApi :> res) m@ is a /function/ -- regardless of @m@. -- I.e. we have to set a constraint -- @forall m. ServerT (WithDefaultApiArg apiType :> res) m ~ (e -> d)@ -- (for some @e@ and @d@). -- However GHC doesn't allow @forall@ in constraints. -- -- But we can use 'Forall' thing instead. -- @Forall (ApiHasArgInvariant (WithDefaultApiArg apiType) a res)@ -- constraint is already provided here (see 'ApiHasArg' definition), -- so we can instantiate it's quantification parameter @m@ to concrete -- @m1@ and @m2@ required by this function, getting desired constraints. hoistServerWithContext _ pc (nt :: forall x. m1 x -> m2 x) s = hoistServerWithContext (Proxy @res) pc nt . s \\ inst @(ApiHasArgInvariant (WithDefaultApiArg subApi) res) @m1 \\ inst @(ApiHasArgInvariant (WithDefaultApiArg subApi) res) @m2 instance HasSwagger (subApi :> res) => HasSwagger (WithDefaultApiArg subApi :> res) where toSwagger _ = toSwagger (Proxy @(subApi :> res)) ------------------------------------------------------------------------- -- HasClient instances we need for benchmarking. ------------------------------------------------------------------------- instance HasClient m (subApi :> res) => HasClient m (CDecodeApiArg subApi :> res) where type Client m (CDecodeApiArg subApi :> res) = Client m (subApi :> res) clientWithRoute p _ req = clientWithRoute p (Proxy @(subApi :> res)) req hoistClientMonad pm _ f cl = hoistClientMonad pm (Proxy @(subApi :> res)) f cl instance HasClient m (subApi :> res) => HasClient m (WithDefaultApiArg subApi :> res) where type Client m (WithDefaultApiArg subApi :> res) = Client m (subApi :> res) clientWithRoute p _ req = clientWithRoute p (Proxy @(subApi :> res)) req hoistClientMonad pm _ f cl = hoistClientMonad pm (Proxy @(subApi :> res)) f cl instance (RunClient m, HasClient m (Verb mt st ct $ ApiModifiedRes mod a)) => HasClient m (VerbMod mod (Verb (mt :: k1) (st :: Nat) (ct :: [*]) a)) where type Client m (VerbMod mod (Verb mt st ct a)) = Client m (Verb mt st ct $ ApiModifiedRes mod a) clientWithRoute p _ req = clientWithRoute p (Proxy @(Verb mt st ct $ ApiModifiedRes mod a)) req hoistClientMonad pm _ f cl = hoistClientMonad pm (Proxy @(Verb mt st ct $ ApiModifiedRes mod a)) f cl ------------------------------------------------------------------------- -- Logging ------------------------------------------------------------------------- -- | Enables logging for server which serves given api. -- -- `config` is a type at which you have to specify 'ApiLoggingConfig' via -- reflection. This way was chosen because the least thing we need in -- config is 'LoggerName', and we want to have '<>' on 'LoggerName's thus -- 'KnownSymbol' is not enough. -- -- This logging will report -- -- * Request parameters, including request bodies -- * Truncated response (for exact meaning of /truncated/ see 'WithTruncatedLog') -- * If execution failed with error, it will be displayed -- * Details like request method and endpoint execution time -- -- If user makes request which can't be processed (e.g. with path to undefined -- endpoint which normally terminates with 404) it won't be logged. However, -- I don't find it a great problem, it may impede only in development or on -- getting acknowledged with api. data LoggingApi config api -- | Helper to traverse servant api and apply logging. data LoggingApiRec config api newtype ApiLoggingConfig = ApiLoggingConfig { apiLoggerName :: LoggerName } deriving Show -- | Used to incrementally collect info about passed parameters. data ApiParamsLogInfo -- | Parameters gathered at current stage = ApiParamsLogInfo [SecuredText] -- | Parameters collection failed with reason -- (e.g. decoding error) | ApiNoParamsLogInfo Text makePrisms ''ApiParamsLogInfo instance Default ApiParamsLogInfo where def = ApiParamsLogInfo mempty addParamLogInfo :: SecuredText -> ApiParamsLogInfo -> ApiParamsLogInfo addParamLogInfo paramInfo = _ApiParamsLogInfo %~ (paramInfo :) -- | When it comes to logging responses, returned data may be very large. -- Log space is valuable (already in testnet we got truncated logs), -- so we have to care about printing only whose data which may be useful. newtype WithTruncatedLog a = WithTruncatedLog a instance {-# OVERLAPPABLE #-} Buildable a => Buildable (WithTruncatedLog a) where build (WithTruncatedLog a) = bprint build a -- | When item list is going to be printed, we impose taking care of -- truncating. -- How much data to remain should depend on how big output may be, how can -- response change from call to call and how often related endpoints are called -- in practise. class HasTruncateLogPolicy a where truncateLogPolicy :: [a] -> [a] instance (Buildable (WithTruncatedLog a), HasTruncateLogPolicy a) => Buildable (WithTruncatedLog [a]) where build (WithTruncatedLog l) = do let lt = truncateLogPolicy l diff = length l - length lt mMore | diff == 0 = "" | otherwise = bprint ("\n and "%build%" entries more...") diff bprint (listJsonIndent 4%builder) (map WithTruncatedLog lt) mMore instance ( HasServer (LoggingApiRec config api) ctx , HasServer api ctx ) => HasServer (LoggingApi config api) ctx where type ServerT (LoggingApi config api) m = ServerT api m route = inRouteServer @(LoggingApiRec config api) route (def, ) hoistServerWithContext _ = hoistServerWithContext (Proxy :: Proxy api) -- | Version of 'HasServer' which is assumed to perform logging. -- It's helpful because 'ServerT (LoggingApi ...)' is already defined for us -- in actual 'HasServer' instance once and forever. class HasServer api ctx => HasLoggingServer config api ctx where routeWithLog :: Proxy (LoggingApiRec config api) -> SI.Context ctx -> SI.Delayed env (Server (LoggingApiRec config api)) -> SI.Router env instance HasLoggingServer config api ctx => HasServer (LoggingApiRec config api) ctx where type ServerT (LoggingApiRec config api) m = (ApiParamsLogInfo, ServerT api m) route = routeWithLog hoistServerWithContext _ pc nt s = hoistServerWithContext (Proxy :: Proxy api) pc nt <$> s instance ( HasLoggingServer config api1 ctx , HasLoggingServer config api2 ctx ) => HasLoggingServer config (api1 :<|> api2) ctx where routeWithLog = inRouteServer @(LoggingApiRec config api1 :<|> LoggingApiRec config api2) route $ \(paramsInfo, f1 :<|> f2) -> (paramsInfo, f1) :<|> (paramsInfo, f2) instance ( KnownSymbol path , HasLoggingServer config res ctx ) => HasLoggingServer config (path :> res) ctx where routeWithLog = inRouteServer @(path :> LoggingApiRec config res) route $ first updateParamsInfo where updateParamsInfo = let path = const . toText . symbolVal $ Proxy @path in addParamLogInfo path -- | Describes a way to log a single parameter. class ApiHasArgClass subApi => ApiCanLogArg subApi where type ApiArgToLog subApi :: * type ApiArgToLog subApi = ApiArg subApi toLogParamInfo :: BuildableSafe (ApiArgToLog subApi) => Proxy subApi -> ApiArg subApi -> SecuredText default toLogParamInfo :: BuildableSafe (ApiArg subApi) => Proxy subApi -> ApiArg subApi -> SecuredText toLogParamInfo _ param = \sl -> sformat (buildSafe sl) param instance KnownSymbol s => ApiCanLogArg (Capture s a) instance KnownSymbol s => ApiCanLogArg (QueryFlag s) instance ApiCanLogArg (ReqBody ct a) instance KnownSymbol cs => ApiCanLogArg (QueryParam cs a) where type ApiArgToLog (QueryParam cs a) = a toLogParamInfo _ mparam = \sl -> maybe noEntry (sformat $ buildSafe sl) mparam where noEntry = colorizeDull White "-" instance ( ApiHasArgClass subApi , ApiArg subApi ~ Maybe b , ApiCanLogArg subApi ) => ApiCanLogArg (WithDefaultApiArg subApi) where instance ( ApiCanLogArg subApi ) => ApiCanLogArg (CDecodeApiArg subApi) where paramRouteWithLog :: forall config api subApi res ctx env. ( api ~ (subApi :> res) , HasServer (subApi :> LoggingApiRec config res) ctx , ApiHasArg subApi res , ApiHasArg subApi (LoggingApiRec config res) , ApiCanLogArg subApi , BuildableSafe (ApiArgToLog subApi) ) => Proxy (LoggingApiRec config api) -> SI.Context ctx -> SI.Delayed env (Server (LoggingApiRec config api)) -> SI.Router env paramRouteWithLog = inRouteServer @(subApi :> LoggingApiRec config res) route $ \(paramsInfo, f) a -> (a `updateParamsInfo` paramsInfo, f a) where updateParamsInfo a = let paramVal = toLogParamInfo (Proxy @subApi) a paramName = apiArgName $ Proxy @subApi paramInfo = \sl -> sformat (string%": "%stext) paramName (paramVal sl) in addParamLogInfo paramInfo instance {-# OVERLAPPABLE #-} ( HasServer (subApi :> res) ctx , HasServer (subApi :> LoggingApiRec config res) ctx , ApiHasArg subApi res , ApiHasArg subApi (LoggingApiRec config res) , ApiCanLogArg subApi , BuildableSafe (ApiArgToLog subApi) ) => HasLoggingServer config (subApi :> res) ctx where routeWithLog = paramRouteWithLog instance {-# OVERLAPPING #-} HasLoggingServer config res ctx => HasLoggingServer config (Summary s :> res) ctx where routeWithLog = inRouteServer @(Summary s :> LoggingApiRec config res) route identity instance {-# OVERLAPPING #-} HasLoggingServer config res ctx => HasLoggingServer config (Description d :> res) ctx where routeWithLog = inRouteServer @(Description d :> LoggingApiRec config res) route identity -- | Unique identifier for request-response pair. newtype RequestId = RequestId Integer instance Buildable RequestId where build (RequestId id') = bprint ("#"%build) id' -- | We want all servant servers to have non-overlapping ids, -- so using singleton counter here. requestsCounter :: TVar Integer requestsCounter = unsafePerformIO $ newTVarIO 0 {-# NOINLINE requestsCounter #-} nextRequestId :: MonadIO m => m RequestId nextRequestId = atomically $ do modifyTVar' requestsCounter (+1) RequestId <$> readTVar requestsCounter -- | Modify an action so that it performs all the required logging. applyServantLogging :: ( MonadIO m , MonadCatch m , MonadError ServantErr m , Reifies config ApiLoggingConfig , ReflectMethod (method :: k) ) => Proxy config -> Proxy method -> ApiParamsLogInfo -> (a -> Text) -> m a -> m a applyServantLogging configP methodP paramsInfo showResponse action = do timer <- mkTimer reqId <- nextRequestId catchErrors reqId timer $ do reportRequest reqId res <- action reportResponse reqId timer res return res where method = decodeUtf8 $ reflectMethod methodP cmethod = flip colorizeDull method $ case method of "GET" -> Cyan "POST" -> Yellow "PUT" -> Blue "DELETE" -> Red _ -> Magenta mkTimer :: MonadIO m => m (m Text) mkTimer = do startTime <- liftIO getPOSIXTime return $ do endTime <- liftIO getPOSIXTime return $ sformat shown (endTime - startTime) inLogCtx :: LoggerNameBox m a -> m a inLogCtx logAction = do let ApiLoggingConfig{..} = reflect configP usingLoggerName apiLoggerName logAction eParamLogs :: Either Text SecuredText eParamLogs = case paramsInfo of ApiParamsLogInfo info -> Right $ \sl -> T.intercalate "\n" $ reverse info <&> \securedParamsInfo -> sformat (" "%stext%" "%stext) (colorizeDull White ":>") (securedParamsInfo sl) ApiNoParamsLogInfo why -> Left why reportRequest :: MonadIO m => RequestId -> m () reportRequest reqId = case eParamLogs of Left e -> inLogCtx $ logInfoSP $ \sl -> sformat ("\n"%stext%secretOnlyF sl (" "%stext)) (colorizeDull Red "Unexecuted request due to error") e Right paramLogs -> do inLogCtx $ logInfoSP $ \sl -> sformat ("\n"%stext%" "%stext%"\n"%build) cmethod (colorizeDull White $ "Request " <> pretty reqId) (paramLogs sl) responseTag reqId = "Response " <> pretty reqId reportResponse reqId timer resp = do durationText <- timer inLogCtx $ logInfoSP $ \sl -> sformat ("\n "%stext%" "%stext%" "%stext %plainOrSecureF sl (stext%stext) (fconst ""%fconst "")) (colorizeDull White $ responseTag reqId) (colorizeDull Green "OK") durationText (colorizeDull White " > ") (showResponse resp) catchErrors reqId st = flip catchError (servantErrHandler reqId st) . handleAny (exceptionsHandler reqId st) servantErrHandler reqId timer err = do durationText <- timer let errMsg = sformat (build%" "%string) (errHTTPCode err) (errReasonPhrase err) inLogCtx $ logInfoSP $ \_sl -> sformat ("\n "%stext%" "%stext%" "%stext) (colorizeDull White $ responseTag reqId) (colorizeDull Red errMsg) durationText throwError err exceptionsHandler reqId timer e = do durationText <- timer inLogCtx $ logInfoSP $ \_sl -> sformat ("\n "%stext%" "%shown%" "%stext) (colorizeDull Red $ responseTag reqId) e durationText throwM e applyLoggingToHandler :: forall config method a. ( Buildable (WithTruncatedLog a) , Reifies config ApiLoggingConfig , ReflectMethod method ) => Proxy config -> Proxy (method :: k) -> (ApiParamsLogInfo, Handler a) -> Handler a applyLoggingToHandler configP methodP (paramsInfo, handler) = handler & serverHandlerL %~ withLogging paramsInfo where display = sformat build . WithTruncatedLog withLogging params = applyServantLogging configP methodP params display instance ( HasServer (Verb mt st ct a) ctx , Reifies config ApiLoggingConfig , ReflectMethod mt , Buildable (WithTruncatedLog a) ) => HasLoggingServer config (Verb (mt :: k) (st :: Nat) (ct :: [*]) a) ctx where routeWithLog = inRouteServer @(Verb mt st ct a) route $ applyLoggingToHandler (Proxy @config) (Proxy @mt) instance ( HasServer (Verb mt st ct $ ApiModifiedRes mod a) ctx , HasServer (VerbMod mod (Verb mt st ct a)) ctx , ModifiesApiRes mod , ReflectMethod mt , Reifies config ApiLoggingConfig , Buildable (WithTruncatedLog $ ApiModifiedRes mod a) ) => HasLoggingServer config (VerbMod mod (Verb (mt :: k1) (st :: Nat) (ct :: [*]) a)) ctx where routeWithLog = -- TODO [CSM-466] avoid manually rewriting rule for composite api modification inRouteServer @(Verb mt st ct $ ApiModifiedRes mod a) route $ \(paramsInfo, handler) -> handler & serverHandlerL' %~ modifyApiResult (Proxy @mod) & applyLoggingToHandler (Proxy @config) (Proxy @mt) . (paramsInfo, ) instance ReportDecodeError api => ReportDecodeError (LoggingApiRec config api) where reportDecodeError _ msg = (ApiNoParamsLogInfo msg, reportDecodeError (Proxy @api) msg) ------------------------------------------------------------------------- -- Custom query flag ------------------------------------------------------------------------- -- This type is used as a helper to implement custom query flags. -- Instead of using `QueryFlag "some_flag"` which should serialize -- into boolean flag now we can say `CustomQueryFlag "some_flag" SomeFlag` -- where SomeFlag has instance of Flaggable. This way we won't be using -- Boolean type for all flags but we can implement custom type. data CustomQueryFlag (sym :: Symbol) flag instance ( KnownSymbol sym , HasSwagger sub , HasCustomQueryFlagDescription sym ) => HasSwagger (CustomQueryFlag sym flag :> sub) where toSwagger _ = toSwagger (Proxy :: Proxy sub) & addParam param & addDefaultResponse400 tname where tname = T.pack (symbolVal (Proxy :: Proxy sym)) param = mempty & name .~ tname & description .~ customDescription (Proxy @sym) & schema .~ ParamOther (mempty & in_ .~ ParamQuery & allowEmptyValue ?~ True & paramSchema .~ (toParamSchema (Proxy :: Proxy Bool) & default_ ?~ toJSON False)) class HasCustomQueryFlagDescription (sym :: Symbol) where customDescription :: Proxy sym -> Maybe Text customDescription _ = Nothing class Flaggable flag where toBool :: flag -> Bool fromBool :: Bool -> flag instance Flaggable Bool where toBool = identity fromBool = identity instance (KnownSymbol sym, HasServer api context, Flaggable flag) => HasServer (CustomQueryFlag sym flag :> api) context where type ServerT (CustomQueryFlag sym flag :> api) m = flag -> ServerT api m hoistServerWithContext _ pc nt s = hoistServerWithContext (Proxy @api) pc nt . s route Proxy context subserver = let querytext r = parseQueryText $ rawQueryString r param r = case lookup paramname (querytext r) of Just Nothing -> True -- param is there, with no value Just (Just v) -> examine v -- param with a value Nothing -> False -- param not in the query string in route (Proxy @api) context (SI.passToServer subserver $ fromBool . param) where paramname = toText $ symbolVal (Proxy @sym) examine v | v == "true" || v == "1" || v == "" = True | otherwise = False instance (KnownSymbol sym, Flaggable flag, HasClient m api) => HasClient m (CustomQueryFlag sym flag :> api) where type Client m (CustomQueryFlag sym flag :> api) = flag -> Client m api clientWithRoute p _ req = clientWithRoute p (Proxy @(QueryFlag sym :> api)) req . toBool hoistClientMonad pm _ f cl = \as -> hoistClientMonad pm (Proxy :: Proxy api) f (cl as) instance KnownSymbol s => ApiCanLogArg (CustomQueryFlag s a) instance KnownSymbol s => ApiHasArgClass (CustomQueryFlag s a) ------------------------------------------------------------------------- -- API construction Helpers ------------------------------------------------------------------------- type CQueryParam s a = CDecodeApiArg (QueryParam s a) type CCapture s a = CDecodeApiArg (Capture s a) type CReqBody c a = CDecodeApiArg (ReqBody c a) type DReqBody c a = WithDefaultApiArg (ReqBody c a) type DCQueryParam s a = WithDefaultApiArg (CDecodeApiArg $ QueryParam s a) type DQueryParam s a = WithDefaultApiArg (QueryParam s a) type DHeader s a = WithDefaultApiArg (Header s a) -- -- Creating a better user experience when it comes to errors. -- data ValidJSON deriving Typeable instance FromJSON a => MimeUnrender ValidJSON a where mimeUnrender _ bs = case eitherDecode bs of Left err -> Left $ decodeUtf8 $ encode (JSONValidationFailed $ toText err) Right v -> return v instance Accept ValidJSON where contentTypes _ = contentTypes (Proxy @ JSON) instance ToJSON a => MimeRender ValidJSON a where mimeRender _ = mimeRender (Proxy @ JSON) -- -- Error from parsing / validating JSON inputs -- newtype JSONValidationError = JSONValidationFailed Text deriving (Eq, Show, Generic) deriveGeneric ''JSONValidationError instance Exception JSONValidationError instance Arbitrary JSONValidationError where arbitrary = pure (JSONValidationFailed "JSON validation failed.") instance Buildable JSONValidationError where build _ = bprint "Couldn't decode a JSON input." instance ToJSON JSONValidationError where toJSON = jsendErrorGenericToJSON instance FromJSON JSONValidationError where parseJSON = jsendErrorGenericParseJSON instance HasDiagnostic JSONValidationError where getDiagnosticKey _ = "validationError" -- | An empty type which can be used to inject Swagger tags at the type level, -- directly in the Servant API. data Tag (tagName :: Symbol) (tagDescription :: TagDescription) data TagDescription = NoTagDescription | TagDescription Symbol -- | Instance of `HasServer` which erases the `Tag` from its routing, -- as the latter is needed only for Swagger. instance (HasServer subApi context) => HasServer (Tag name desc :> subApi) context where type ServerT (Tag name desc :> subApi) m = ServerT subApi m route _ = route (Proxy @subApi) hoistServerWithContext _ = hoistServerWithContext (Proxy @subApi) instance (HasClient m subApi) => HasClient m (Tag name desc :> subApi) where type Client m (Tag name desc :> subApi) = Client m subApi clientWithRoute pm _ = clientWithRoute pm (Proxy @subApi) hoistClientMonad pm _ f cl = hoistClientMonad pm (Proxy @subApi) f cl -- | Similar to 'instance HasServer', just skips 'Tags'. instance HasLoggingServer config subApi context => HasLoggingServer config (Tag name desc :> subApi) context where routeWithLog = mapRouter @(Tag name desc :> LoggingApiRec config subApi) route identity instance (KnownSymbol name, KnownSymbol desc, HasSwagger subApi) => HasSwagger (Tag name ('TagDescription desc) :> subApi) where toSwagger _ = let subApi = toSwagger (Proxy @subApi) tag = S.Tag (toText $ symbolVal $ Proxy @name) (Just $ toText $ symbolVal $ Proxy @desc) Nothing in subApi & applyTagsFor (operationsOf subApi) [tag] instance (KnownSymbol name, HasSwagger subApi) => HasSwagger (Tag name 'NoTagDescription :> subApi) where toSwagger _ = let subApi = toSwagger (Proxy @subApi) tag = S.Tag (toText $ symbolVal $ Proxy @name) Nothing Nothing in subApi & applyTagsFor (operationsOf subApi) [tag] -- | `mapRouter` is helper function used in order to transform one `HasServer` -- instance to another. It can be used to introduce custom request params type. -- See e. g. `WithDefaultApiArg` as an example of usage mapRouter :: forall api api' ctx env. (Proxy api -> SI.Context ctx -> SI.Delayed env (Server api) -> SI.Router env) -> (Server api' -> Server api) -> (Proxy api' -> SI.Context ctx -> SI.Delayed env (Server api') -> SI.Router env) mapRouter routing f = \_ ctx delayed -> routing Proxy ctx (fmap f delayed) -- | Extra information associated with an HTTP response. data Metadata = Metadata { metaPagination :: PaginationMetadata -- ^ Pagination-specific metadata } deriving (Show, Eq, Generic) deriveJSON Aeson.defaultOptions ''Metadata instance Arbitrary Metadata where arbitrary = Metadata <$> arbitrary instance Example Metadata instance ToSchema Metadata where declareNamedSchema = genericDeclareNamedSchema defaultSchemaOptions { S.fieldLabelModifier = over (ix 0) Char.toLower . drop 4 -- length "meta" } instance Buildable Metadata where build Metadata{..} = bprint ("{ pagination="%build%" }") metaPagination -- instance Example Metadata -- | An `APIResponse` models, unsurprisingly, a response (successful or not) -- produced by the wallet backend. -- Includes extra informations like pagination parameters etc. data APIResponse a = APIResponse { wrData :: a -- ^ The wrapped domain object. , wrStatus :: ResponseStatus -- ^ The <https://labs.omniti.com/labs/jsend jsend> status. , wrMeta :: Metadata -- ^ Extra metadata to be returned. } deriving (Show, Eq, Generic, Functor) deriveJSON Aeson.defaultOptions ''APIResponse instance Arbitrary a => Arbitrary (APIResponse a) where arbitrary = APIResponse <$> arbitrary <*> pure SuccessStatus <*> arbitrary instance ToJSON a => MimeRender OctetStream (APIResponse a) where mimeRender _ = encode instance (ToSchema a, Typeable a) => ToSchema (APIResponse a) where declareNamedSchema _ = do let a = Proxy @a tyName = toText $ map sanitize (show $ typeRep a :: String) sanitize c | c `elem` (":/?#[]@!$&'()*+,;=" :: String) = '_' | otherwise = c aRef <- declareSchemaRef a respRef <- declareSchemaRef (Proxy @ResponseStatus) metaRef <- declareSchemaRef (Proxy @Metadata) pure $ NamedSchema (Just $ "APIResponse-" <> tyName) $ mempty & type_ .~ SwaggerObject & required .~ ["data", "status", "meta"] & properties .~ [ ("data", aRef) , ("status", respRef) , ("meta", metaRef) ] instance Buildable a => Buildable (APIResponse a) where build APIResponse{..} = bprint ("\n\tstatus="%build %"\n\tmeta="%build %"\n\tdata="%build ) wrStatus wrMeta wrData instance Example a => Example (APIResponse a) where example = APIResponse <$> example <*> pure SuccessStatus <*> example -- | Creates a 'APIResponse' with just a single record into it. single :: a -> APIResponse a single theData = APIResponse { wrData = theData , wrStatus = SuccessStatus , wrMeta = Metadata (PaginationMetadata 1 (Page 1) (PerPage 1) 1) } -- | Generates the @Content-Type: application/json@ 'HTTP.Header'. applicationJson :: HTTPTypes.Header applicationJson = (hContentType, "application/json") -- | An error for representing unknown problems in the API. The Jsen newtype UnknownError = UnknownError Text deriving (Show, Generic) deriveGeneric ''UnknownError instance Exception UnknownError instance HasDiagnostic UnknownError where getDiagnosticKey _ = "unknownErrorMessage" instance ToJSON UnknownError where toJSON = jsendErrorGenericToJSON instance FromJSON UnknownError where parseJSON = jsendErrorGenericParseJSON -- | A newtype around 'SomeException' that provides a JSend compliant 'ToJSON' -- rendering. Use this only in debugging to provide a ToJSON instance for -- unknown exceptions. newtype JsendException = JsendException SomeException deriving (Show, Exception) instance ToJSON JsendException where toJSON (JsendException exn) = object [ "message" .= show @Text (typeOf exn) , "status" .= ErrorStatus , "diagnostic" .= object [ "debugException" .= show @Text exn ] ]
input-output-hk/pos-haskell-prototype
lib/src/Pos/Util/Servant.hs
mit
40,196
0
20
10,352
9,959
5,256
4,703
-1
-1
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE RankNTypes #-} module Puzzles where import Data.Holmes import Tower {- Sample puzzles -} config3 :: Config Holmes (Defined (Cell Int)) config3 = definedConfig (Board 3) {- (.) 2 . . . . . . . 1 2 3 3 1 2 2 3 1 -} -- restricted to Defined because `givens` uses `pure` to create single values to test against puzzle3 :: forall m. MonadCell m => [Prop m (Defined (Cell Int))] -> Prop m (Defined Bool) puzzle3 cells = and' [ and' (map (\(c, v) -> givenNum (toIndex board c) v cells) givens), and' (map (\i -> isTower i cells) towerIndexes), and' (map (\i -> not' $ isTower i cells) nonTowerIndexes), latinSquare' board cells, and' (map towerConstraint' towers) ] where board = Board 3 givens = [(Coord 1 0, 2)] towers = [Coord 0 0] towerIndexes = map (toIndex board) towers nonTowerIndexes = filter (not . flip elem towerIndexes) (boardIndexes board) towerConstraint' coord = towerConstraint board coord cells puzzle1 cells = towerConstraint (Board 1) (Coord 0 0) cells puzzle2 cells = and' [ latinSquare' (Board 2) cells, towerConstraint (Board 2) (Coord 0 0) cells ] -- let's start with our 4x4 puzzle: {- .OO. ...O .... .... -} config4 :: Config Holmes (Defined (Cell Int)) config4 = definedConfig (Board 4) puzzle4 :: ( Mapping f c, c (Cell v), c v, c Bool, EqR (f v) (f Bool), Eq v, OrdR (f v) (f Bool), Num v, Num (f v), SumR (f v), MonadCell m ) => [Prop m (f (Cell v))] -> Prop m (f Bool) puzzle4 cells = and' [ and' (map (\i -> isTower i cells) towerIndexes), and' (map (\i -> not' $ isTower i cells) nonTowerIndexes), latinSquare' board cells, and' (map towerConstraint' towers) ] where board = Board 4 towers = [Coord 0 1, Coord 0 2, Coord 1 3] towerIndexes = map (toIndex board) towers nonTowerIndexes = filter (not . flip elem towerIndexes) (boardIndexes board) towerConstraint' coord = towerConstraint board coord cells {- Example puzzle from the GP instructions 4 . . . . . 1 (4) . . . (3) . (.) . . . (.) 1 . . . . . 2 -} config5 :: Config Holmes (Defined (Cell Int)) config5 = definedConfig (Board 5) puzzle5 :: forall m. MonadCell m => [Prop m (Defined (Cell Int))] -> Prop m (Defined Bool) puzzle5 cells = and' [ and' (map (\(c, v) -> givenNum (toIndex board c) v cells) givens), and' (map (\i -> isTower i cells) towerIndexes), and' (map (\i -> not' $ isTower i cells) nonTowerIndexes), latinSquare' board cells, and' (map towerConstraint' towers) ] where board = Board 5 givens = [(Coord 0 0, 4), (Coord 1 1, 1), (Coord 1 2, 4), (Coord 2 1, 3), (Coord 3 3, 1), (Coord 4 4, 2)] towers = [Coord 1 2, Coord 2 1, Coord 2 3, Coord 3 2] towerIndexes = map (toIndex board) towers nonTowerIndexes = filter (not . flip elem towerIndexes) (boardIndexes board) towerConstraint' coord = towerConstraint board coord cells
robx/puzzles
towerdefence/src/Puzzles.hs
mit
3,097
0
14
832
1,220
628
592
-1
-1
{-# LANGUAGE NoImplicitPrelude #-} module System.ImportGraph.GetIface where import BinIface import ClassyPrelude import GHC import System.Process import TcRnMonad findIfaces :: Ghc [ModIface] findIfaces = do his <- liftIO findHiFiles _ <- setSessionDynFlags =<< getSessionDynFlags mapM getIface his findHiFiles :: IO [FilePath] findHiFiles = lines <$> readProcess "find" ["-iname", "*.hi"] "" getIface :: FilePath -> Ghc ModIface getIface filename = do hsc_env <- getSession liftIO . initTcRnIf 's' hsc_env () () $ readBinIface IgnoreHiWay QuietBinIFaceReading filename
ncaq/haskell-import-graph
lib/System/ImportGraph/GetIface.hs
mit
633
0
10
137
161
83
78
18
1
module Network.IRC.Client.Type ( Net , Bot(..)) where import Control.Monad.Reader import System.IO import Network.TLS import Data.Maybe import System.Log.FastLogger -- | The 'Net' monad, a wrapper over IO, carrying the bot's immutable state. type Net = ReaderT Bot IO data Bot = Bot { socket :: Handle , tlsCtx :: Maybe TLSCtx , logger :: LoggerSet }
cosmo0920/hs-IRC
Network/IRC/Client/Type.hs
mit
386
0
9
90
89
56
33
12
0
module Eight where cattyConny :: String -> String -> String cattyConny x y = x ++ " mrow " ++ y -- fill in the types -- flip :: (a -> b -> c) -> b -> a -> c flippy :: String -> String -> String flippy = flip cattyConny appedCatty :: String -> String appedCatty = cattyConny "woops" frappe :: String -> String frappe = flippy "haha" dividedBy :: Integral a => a -> a -> (a, a) dividedBy num denom = go num denom 0 where go n d count | n < d = (count, n) | otherwise = go (n - d) d (count + 1) rSum :: (Eq a, Num a) => a -> a rSum x = go 1 x where go n x | x == 0 = 0 | x == n = n | otherwise = n + (go (n + 1) x) rMul :: (Integral a) => a -> a -> a rMul x y = go x y where go x y | x == 0 = 0 | otherwise = y + (go (x - 1) y) data DividedResult a = Result (a, a) | DividedByZero deriving Show dividedBy' :: Integral a => a -> a -> DividedResult a dividedBy' num denom = go num denom 0 1 where go n d count sign | d == 0 = DividedByZero | n < 0 = go (-n) d count (-sign) | d < 0 = go n (-d) count (-sign) | n < d = Result ((sign * count), n) | otherwise = go (n - d) d (count + 1) sign mc91 :: Integral a => a -> a mc91 x = go x where go n | n > 100 = n - 10 | n <= 100 = go (go (n + 11))
mudphone/HaskellBook
src/Eight.hs
mit
1,387
0
12
509
677
341
336
42
1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE LambdaCase #-} -- | A resource Slot filled with a 'YageResource'. Slotted 'YageResource's are freed when a new -- 'YageResource' replaces the old one. module Yage.Resource.Slot ( -- * Resource Slot Slot, mkSlot, slot, modifyM ) where import Yage.Lens import Yage.Prelude hiding (Index , atomicModifyIORef', newIORef , readIORef, modifyIORef , modifyIORef') import Data.Acquire as Acquire import Control.Monad.Trans.Resource as Acquire import Data.IORef import Yage.Resource.YageResource import Quine.StateVar newtype Slot a = Slot (IORef (Either (YageResource a) (ReleaseKey, a))) mkSlot :: YageResource a -> YageResource (Slot a) mkSlot aq = mkAcquire (fmap Slot . newIORef . Left $ aq) free where free (Slot ref) = get ref >>= \case Left _ -> return () Right (key,_) -> release key slot :: MonadResource m => Slot a -> YageResource a -> m () slot (Slot ref) aq = liftIO $ atomicModifyIORef' ref (\val -> (Left aq, val)) >>= \case Left _ -> return () Right (key,_) -> release key modifyM :: MonadResource m => Slot a -> (a -> YageResource a) -> m () modifyM s m = do x <- get s slot s (m x) -- danger it dupes resources -- readSlotResource :: Slot a -> YageResource a -- readSlotResource (Slot ref) = io (readIORef ref) >>= either id (return . snd) instance MonadIO m => HasSetter (Slot a) (YageResource a) m where (Slot ref) $= yr = liftIO $ atomicModifyIORef' ref (\val -> (Left yr, val)) >>= \case Left _ -> return () Right (key,_) -> release key instance MonadResource m => HasGetter (Slot a) m a where get (Slot ref) = do eval <- liftIO $ readIORef ref case eval of Left aq -> allocateAcquire aq >>= \val -> liftIO $ atomicModifyIORef' ref $ \_ -> (Right val,snd val) Right (_,res) -> return res instance MonadResource m => HasUpdate (Slot a) a m where (Slot ref) $~ f = liftIO $ modifyIORef ref $ bimap (fmap f) (over _2 f) (Slot ref) $~! f = liftIO $ modifyIORef' ref $ bimap (fmap f) (over _2 f)
MaxDaten/yage
src/Yage/Resource/Slot.hs
mit
2,595
0
16
772
784
402
382
49
2
{-# LANGUAGE OverloadedStrings #-} module Nauva.CSS.Helpers where import Data.Text (Text) import qualified Data.Text as T import Control.Monad.Writer.Lazy import Nauva.CSS.Types vh :: Int -> CSSValue vh n = CSSValue $ T.pack $ show n ++ "vh" px :: (Show a) => a -> CSSValue px n = CSSValue $ T.pack $ show n ++ "px" rem :: (Show a) => a -> CSSValue rem n = CSSValue $ T.pack $ show n ++ "rem" pct :: (Show a) => a -> CSSValue pct n = CSSValue $ T.pack $ show n ++ "%" fontFamily_ :: Writer [CSSDeclaration] () -> Writer [Statement] () fontFamily_ v = tell [SEmit $ DFontFamily $ execWriter v] before :: Writer [Statement] () -> Writer [Statement] () before style = tell [SSuffix "::before" style] after :: Writer [Statement] () -> Writer [Statement] () after style = tell [SSuffix "::after" style] onHover :: Writer [Statement] () -> Writer [Statement] () onHover style = tell [SSuffix ":hover" style] onActive :: Writer [Statement] () -> Writer [Statement] () onActive style = tell [SSuffix ":active" style] firstChild :: Writer [Statement] () -> Writer [Statement] () firstChild style = tell [SSuffix ":first-child" style] lastChild :: Writer [Statement] () -> Writer [Statement] () lastChild style = tell [SSuffix ":last-child" style] media :: Text -> Writer [Statement] () -> Writer [Statement] () media m style = tell [SCondition (CMedia m) style]
wereHamster/nauva
pkg/hs/nauva-css/src/Nauva/CSS/Helpers.hs
mit
1,406
0
9
280
604
311
293
30
1
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} module Web.YahooPortfolioManager.Handlers where import Control.Applicative import Control.Monad.Trans (liftIO) import Data.Text (Text, pack) import qualified Data.YahooPortfolioManager.DbAdapter as YD import qualified Data.YahooPortfolioManager.Types as YT import Text.Hamlet (hamletFile) import Text.Printf import Web.YahooPortfolioManager.Forms import Web.YahooPortfolioManager.Foundation import Yesod ypmLayout :: Yesod master => Html -> HtmlUrl (Route master) -> HandlerT YPMS (HandlerT master IO) Html ypmLayout title widget = do -- Need to lift the child site url to the parent site in order -- to create links within the subsite: see use of toParent in -- sidebar.hamlet (http://www.yesodweb.com/blog/2013/03/big-subsite-rewrite) toParent <- getRouteToParent let content = widget lift $ defaultLayout $ do setTitle title toWidget $(hamletFile "Web/YahooPortfolioManager/templates/sidebar.hamlet") data Percent = Percent (Maybe Double) deriving Show class Format a where format :: a -> Text instance Format [Char] where format = pack instance Format Double where format x = pack $ printf "%.2f" x instance Format a => Format (Maybe a) where format (Just x) = format x format Nothing = "-" instance Format Percent where format (Percent (Just x)) = format $ 100.0 * x format (Percent Nothing) = "-" getYpmHomeR :: Yesod master => HandlerT YPMS (HandlerT master IO) Html getYpmHomeR = do toParent <- getRouteToParent ypmLayout "Portfolio Monitor - Home" $(hamletFile "Web/YahooPortfolioManager/templates/ypmHome.hamlet") getYpmCurrentHoldingsR :: Yesod master => HandlerT YPMS (HandlerT master IO) Html getYpmCurrentHoldingsR = do position <- liftIO $ YD.withConnection YD.fetchPositions toParent <- getRouteToParent ypmLayout "Portfolio Monitor - Holdings" $ do $(hamletFile "Web/YahooPortfolioManager/templates/holdings.hamlet") getYpmDividendsR :: Yesod master => HandlerT YPMS (HandlerT master IO) Html getYpmDividendsR = do dividend <- liftIO $ YD.withConnection YD.fetchDividends toParent <- getRouteToParent ypmLayout "Portfolio Monitor - Dividends" $ do $(hamletFile "Web/YahooPortfolioManager/templates/dividends.hamlet") fetchValue :: YD.Connection -> IO [YT.Portfolio] fetchValue conn = do symbols <- YD.fetchSymbols conn YD.populateQuotesTable conn symbols YD.updateFx conn YD.fetchPortfolio conn getYpmCurrentValueR :: Yesod master => HandlerT YPMS (HandlerT master IO) Html getYpmCurrentValueR = do position <- liftIO $ YD.withConnection fetchValue ypmLayout "Portfolio Monitor - Current Value" $ do $(hamletFile "Web/YahooPortfolioManager/templates/value.hamlet") getYpmAddTransactionR :: Yesod master => HandlerT YPMS (HandlerT master IO) Html getYpmAddTransactionR = do toParent <- getRouteToParent ypmLayout "Portfolio Monitor - Add Transaction" $ do $(hamletFile "Web/YahooPortfolioManager/templates/addTransaction.hamlet") getYpmInputTransactionR :: Yesod master => HandlerT YPMS (HandlerT master IO) Html getYpmInputTransactionR = do position <- runInputGet $ YT.Position <$> ireq (textToStringField symbolField) "possymbol" <*> ireq currencyField "poscurrency" <*> ireq dateField "posdate" <*> ireq doubleField "posposition" <*> ireq doubleField "posstrike" liftIO . YD.withConnection $ (flip YD.insertPosition) position getYpmCurrentHoldingsR getYpmAddDividendR :: Yesod master => HandlerT YPMS (HandlerT master IO) Html getYpmAddDividendR = do toParent <- getRouteToParent ypmLayout "Portfolio Monitor - Add Dividend" $ do $(hamletFile "Web/YahooPortfolioManager/templates/addDividend.hamlet") getYpmInputDividendR :: Yesod master => HandlerT YPMS (HandlerT master IO) Html getYpmInputDividendR = do dividend <- runInputGet $ YT.Dividend <$> ireq (textToStringField symbolField) "divSymbol" <*> ireq doubleField "divDiv" <*> ireq dateField "divDate" liftIO . YD.withConnection $ (flip YD.insertDividend) dividend getYpmDividendsR
lhoghu/intranet
Web/YahooPortfolioManager/Handlers.hs
mit
4,480
0
15
936
1,052
511
541
95
1
module Equinox.ConSat ( C -- :: * -> *; Functor, Monad , Lit(..) -- :: *; Eq, Ord, Show , Con -- :: *; Eq, Ord, Show , Weight -- :: * , wapp , weight , run -- :: C a -> IO a , lift -- :: IO a -> C a , contradiction -- :: C () , newLit -- :: C Sat.Lit , newCon -- :: String -> Weight -> C Con , neg -- :: Lit -> Lit , getValue -- :: Lit -> C (Maybe Bool) , getRep -- :: Con -> C Con , getModelValue -- :: Lit -> C Bool -- use only after model has been found! , getModelRep -- :: Con -> C Con -- use only after model has been found! , addClause -- :: [Lit] -> C () , solve -- :: Flags -> [Lit] -> C Bool , simplify -- :: C () ) where {- Equinox -- Copyright (c) 2003-2007, Koen Claessen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -} import qualified Sat import Flags import Data.Set( Set ) import qualified Data.Set as S import Data.Map( Map ) import qualified Data.Map as M import Control.Monad import Data.List( intersperse ) import System.IO data Lit = Lit Sat.Lit | Con :=: Con | Con :/=: Con | Bool Bool instance Eq Lit where l1 == l2 = l1 `compare` l2 == EQ instance Ord Lit where Lit l1 `compare` Lit l2 = l1 `compare` l2 (a1 :=: b1) `compare` (a2 :=: b2) = upair a1 b1 `compare` upair a2 b2 (a1 :/=: b1) `compare` (a2 :/=: b2) = upair a1 b1 `compare` upair a2 b2 Bool b1 `compare` Bool b2 = b1 `compare` b2 Bool _ `compare` _ = LT _ `compare` Bool _ = GT Lit _ `compare` _ = LT _ `compare` Lit _ = GT (_ :=: _) `compare` _ = LT _ `compare` (_ :=: _) = GT instance Show Lit where show (Lit x) = show x show (s :=: t) = show s ++ " = " ++ show t show (s :/=: t) = show s ++ " != " ++ show t show (Bool True) = "$true" show (Bool False) = "$false" upair :: Ord a => a -> a -> (a,a) upair x y | x <= y = (x,y) | otherwise = (y,x) neg :: Lit -> Lit neg (Lit x) = Lit (Sat.neg x) neg (a :=: b) = a :/=: b neg (a :/=: b) = a :=: b neg (Bool b) = Bool (not b) data Weight = MkWeight{ depth :: !Int, siz :: !Int } deriving ( Eq, Ord ) wapp :: [Weight] -> Weight wapp ws = MkWeight (1 + maximum (0 : map depth ws)) (1 + sum (map siz ws)) -- Debugging ON {- data Con = Con !Weight !Int String weight :: Con -> Weight weight (Con w _ _) = w con :: Int -> Weight -> String -> Con con n w s = Con w n s instance Eq Con where Con _ n1 _ == Con _ n2 _ = n1 == n2 instance Ord Con where Con w1 n1 _ `compare` Con w2 n2 _ = (w1,n1) `compare` (w2,n2) instance Show Con where show (Con _ _ s) = s -- ++ "#" ++ show n -} -- Debugging OFF -- {- data Con = Con !Weight !Int deriving ( Ord ) instance Eq Con where Con _ n1 == Con _ n2 = n1 == n2 weight :: Con -> Weight weight (Con w _) = w con :: Int -> Weight -> String -> Con con n w s = Con w n instance Show Con where show (Con _ n) = "#" ++ show n -- -} data State = MkState { counter :: Int , compares :: Map (Con,Con) Sat.Lit , reps :: Map Con Con , model :: Con -> Con } state0 :: State state0 = MkState { counter = 0 , compares = M.empty , reps = M.empty , model = error "model inspected before solve" } newtype C a = MkC (State -> Sat.S (a, State)) instance Functor C where fmap f (MkC m) = MkC (fmap (\(x,s) -> (f x,s)) . m) instance Monad C where return x = MkC (\s -> return (x,s)) MkC m1 >>= k = MkC (\s0 -> do (x,s1) <- m1 s0 let MkC m2 = k x m2 s1 ) run :: C a -> IO a run (MkC m) = do (x,_) <- Sat.run (m state0) return x getState :: C State getState = MkC (\s -> return (s,s)) setState :: State -> C () setState s = MkC (\_ -> return ((),s)) liftS :: Sat.S a -> C a liftS m = MkC (\s -> do x <- m; return (x,s)) lift :: IO a -> C a lift io = liftS (Sat.lift io) contradiction :: C () contradiction = liftS Sat.contradiction newLit :: C Lit newLit = Lit `fmap` liftS Sat.newLit getEqLit :: Con -> Con -> C Lit getEqLit a b = do a' <- getRep a b' <- getRep b case a' `compare` b' of LT -> getLit' a' b' EQ -> return (Bool True) GT -> getLit' b' a' where getLit' a b = MkC (\s -> case M.lookup (a,b) (compares s) of Just l -> do return (Lit l, s) Nothing -> do l <- Sat.newLit return ( Lit l , s{ compares = M.insert (a,b) l (compares s) } ) ) newCon :: String -> Weight -> C Con newCon x w = MkC (\s -> let n = counter s n' = n+1 c = con n w x in n' `seq` c `seq` return (c, s{ counter = n' }) ) getValue :: Lit -> C (Maybe Bool) getValue (Lit x) = liftS (Sat.getValue x) getValue (a :=: b) = checkEqual a b getValue (a :/=: b) = fmap (fmap not) (checkEqual a b) getValue (Bool b) = return (Just b) getModelValue :: Lit -> C Bool getModelValue (Lit x) = liftS (Sat.getModelValue x) getModelValue (a :=: b) = checkModelEqual a b getModelValue (a :/=: b) = fmap not (checkModelEqual a b) getModelValue (Bool b) = return b checkEqual = undefined getRep :: Con -> C Con getRep a = do s <- getState (a',s') <- rep s a setState s' return a' where rep s a = case M.lookup a (reps s) of Nothing -> do return (a,s) Just a' -> do (a'',s') <- rep s a' return (a'', s{ reps = M.insert a a'' (reps s) }) setRep :: Con -> Con -> C () setRep a b = do a' <- getRep a b' <- getRep b s <- getState case a' `compare` b' of LT -> setState s{ reps = M.insert b' a' (reps s) } EQ -> return () GT -> setState s{ reps = M.insert a' b' (reps s) } checkModelEqual :: Con -> Con -> C Bool checkModelEqual a b = MkC (\s -> return (model s a == model s b, s) ) getModelRep :: Con -> C Con getModelRep a = do a' <- getRep a MkC (\s -> return (model s a', s)) norm :: Lit -> C Lit norm (a :=: b) = getEqLit a b norm (a :/=: b) = neg `fmap` getEqLit a b norm x = return x addClause :: [Lit] -> C () addClause xs = do --lift (putStr (showClause xs ++ ".")) xs' <- (filter (/= Bool False)) `fmap` sequence [ simp x | x <- xs ] case xs' of _ | Bool True `elem` xs' -> do --lift (putStrLn (" [=> $true]")) --lift (hFlush stdout) return () [a :=: b] -> do --lift (putStrLn (" [=> " ++ show b ++ " := " ++ show a ++ "]")) --lift (hFlush stdout) setRep a b _ -> do xs'' <- sequence [ norm x | x <- xs' ] --lift (putStrLn "") --lift (hFlush stdout) liftS (Sat.addClause [ x | Lit x <- xs'' ]) return () where simp (a :=: b) = do a' <- getRep a b' <- getRep b return $ case a' `compare` b' of LT -> a' :=: b' EQ -> Bool True GT -> b' :=: a' simp (a :/=: b) = neg `fmap` simp (a :=: b) simp l = return l showClause c = concat . intersperse " | " . map show $ c solve :: Flags -> [Lit] -> C Bool solve flags xs = do xs' <- sequence [ norm x | x <- xs ] if Bool False `elem` xs' then return False else sat [ x | Lit x <- xs' ] where put v s = when (v <= verbose flags) $ lift $ do putStr s; hFlush stdout putLn v s = when (v <= verbose flags) $ lift $ do putStrLn s; hFlush stdout sat xs = do putLn 4 "--> ConSat: solving..." b <- liftS (Sat.solve xs) if b then check xs else return False check xs = do putLn 4 "--> ConSat: checking..." -- gather & set permanent positive equalities s <- getState peqs <- getPeqs [] (M.toList (compares s)) sequence_ [ do putLn 4 ("[" ++ show b ++ " :~ " ++ show a ++ "]") setRep a b | (a,b) <- peqs ] -- gather & rebuild compares table info (eqs,neqs,comps) <- getEqNeq [] [] [] (M.toList (compares s)) let compares' = M.toList $ M.fromListWith (++) [ (ab,[x]) | (ab,x) <- comps ] bs1 <- sequence [ or `fmap` if a /= b then sequence [ do putLn 4 ( "T2: (" ++ show a ++ " :=: " ++ show b ++ ") <=> " ++ show x ++ " <=> " ++ show y ) liftS $ Sat.addClause [Sat.neg x, y] liftS $ Sat.addClause [x, Sat.neg y] return True | y <- ys ] else sequence [ do putLn 4 ( "T1: (" ++ show a ++ " :=: " ++ show a ++ ") <=> " ++ show y ) liftS $ Sat.addClause [y] return True | y <- x:ys ] | ((a,b),x:ys) <- compares' ] s <- getState setState s{ compares = M.fromList [ (ab,x) | (ab@(a,b),x:_) <- compares' , a /= b ] } let eqTab = classes M.empty eqs graph = M.fromListWith S.union [ (x,S.singleton y) | (x,y) <- eqs ++ map swap eqs ] swap (x,y) = (y,x) bs2 <- sequence [ if x' /= y' then do return False else do put 1 "T: " addClause ((x :=: y) : [ x :/=: y | (x,y) <- p ]) return True | (x,y) <- neqs , let x' = rep eqTab x y' = rep eqTab y p = bfs graph x y ] if or bs1 || or bs2 then do sat xs else do setState (s{ model = rep eqTab }) return True getPeqs peqs [] = do return peqs getPeqs peqs ((ab,x):abxs) = do mb <- liftS (Sat.getValue x) case mb of Just True -> do --lift (putStrLn ("top-true: " ++ show x ++ " " ++ show ab)) getPeqs (ab:peqs) abxs _ -> do getPeqs peqs abxs getEqNeq eqs neqs comps [] = do return (eqs,neqs,comps) getEqNeq eqs neqs comps (((a,b),x):abxs) = do a' <- getRep a b' <- getRep b let ab | a' < b = (a',b') | otherwise = (b',a') comps' = (ab,x):comps bl <- liftS (Sat.getModelValue x) if bl then getEqNeq (ab:eqs) neqs comps' abxs else getEqNeq eqs (ab:neqs) comps' abxs rep eqTab x = case M.lookup x eqTab of Just x' -> x' Nothing -> x classes eqTab [] = cut eqTab (M.keys eqTab) where cut eqTab0 [] = eqTab0 cut eqTab0 (x:xs) = cut eqTab1 xs where (eqTab1,_) = find eqTab0 x classes eqTab0 ((x,y):eqs) = case x' `compare` y' of LT -> classes (M.insert y' x' eqTab2) eqs EQ -> classes eqTab2 eqs GT -> classes (M.insert x' y' eqTab2) eqs where (eqTab1,x') = find eqTab0 x (eqTab2,y') = find eqTab1 y find eqTab0 x0 = case M.lookup x0 eqTab0 of Just x1 | x1 == x2 -> (eqTab0,x1) | otherwise -> (M.insert x0 x2 eqTab1,x2) where (eqTab1,x2) = find eqTab0 x1 Nothing -> (eqTab0,x0) bfs :: Map Con (Set Con) -> Con -> Con -> [(Con,Con)] bfs graph x y = bfs' M.empty [(x,x)] [] where bfs' backs ((x,z):xys) xys' | x == y = path (M.insert x z backs) [] y bfs' backs ((x,z):xys) xys' | M.lookup x backs == Nothing = bfs' (M.insert x z backs) xys ([(v,x) | v <- neighbors x] ++ xys') bfs' backs (_:xys) xys' = bfs' backs xys xys' bfs' backs [] [] = error "bfs: no path!" bfs' backs [] xys' = bfs' backs (reverse xys') [] neighbors x = case M.lookup x graph of Just xs -> S.toList xs Nothing -> error "bfs: not a node!" path backs p y | x == y = p | otherwise = case M.lookup y backs of Just z -> path backs ((z,y):p) z Nothing -> error "bfs: no backwards path!" simplify :: Bool -> Bool -> C Bool simplify a b = liftS (Sat.simplify a b)
msakai/folkung
Haskell/Equinox/ConSat.hs
mit
13,826
0
27
5,328
5,071
2,571
2,500
351
22
{-| Copyright (c) 2014 Maciej Bendkowski Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -} module TranslatorTest where import Control.Monad (liftM2) import Data.Set (null) import Data.Maybe (fromJust) import Test.QuickCheck import CLLCTranslator import qualified LC import qualified CL -- Closed LC trees with bounded size arbLCTerm :: Integral a => a -> Gen LC.Term arbLCTerm n = let x = head LC.vars in liftM2 (LC.Abs) (return x) (arbLCTerm' [x] n) where arbLCTerm' :: Integral a => [String] -> a -> Gen LC.Term arbLCTerm' boundVars 0 = elements $ map (\s -> LC.Var s) boundVars arbLCTerm' boundVars k = let x = LC.freshVariable boundVars in frequency [(1, elements $ map (\s -> LC.Var s) boundVars), (3, liftM2 (LC.App) (arbLCTerm' boundVars (k `div` 2)) (arbLCTerm' boundVars (k `div` 2))), (3, liftM2 (LC.Abs) (return x) (arbLCTerm' (x : boundVars) (k - 1)))] -- random LC tree generator instance Arbitrary LC.Term where arbitrary = sized $ arbLCTerm -- generated LC terms are closed prop_ClosedTerms :: LC.Term -> Property prop_ClosedTerms t = collect (LC.size t) $ Data.Set.null (LC.freeVars t) -- LC to CL translation preserves extensional equality prop_LCCLTranslation :: LC.Term -> Property prop_LCCLTranslation t = collect (LC.size t) $ (toCL' t) `CL.reducesTo` (clNF $ toCL' $ lcNF t) where toCL' :: LC.Term -> CL.Term toCL' t' = fromJust $ toCL t' lcNF :: LC.Term -> LC.Term lcNF t' = last $ LC.boundNormalForm 250 t' clNF :: CL.Term -> CL.Term clNF t' = last $ CL.boundNormalForm 250 t' suite :: [([Char], LC.Term -> Property)] suite = [("Generated LC terms are closed", prop_ClosedTerms), ("LC to CL translation preserves extensional equality", prop_LCCLTranslation)] -- test runner main :: IO () main = mapM_ (\(s, a) -> do putStr $ s ++ " " quickCheck a) suite
maciej-bendkowski/LCCLUtils
src/TranslatorTest.hs
mit
3,178
0
17
866
676
362
314
38
2
module Latex where import Data.List import DataTypes import Data.Monoid import TP type Latex = String proof2latex :: BinTree DecoratedSequent -> Latex proof2latex t = aux t where aux (Leaf lab s) = "\\RightLabel{$" ++ lab2latex lab ++ "$}" ++ "\\AxiomC{$" ++ decoratedSeq2latex s ++ "$}" aux (Unary lab s t) = aux t ++ "\\RightLabel{$" ++ lab2latex lab ++ "$}" ++ "\\UnaryInfC{$" ++ decoratedSeq2latex s ++ "$}" aux (Branch lab l s r) = aux l ++ aux r ++ "\\RightLabel{$" ++ lab2latex lab ++ "$}" ++ "\\BinaryInfC{$" ++ decoratedSeq2latex s ++ "$}" lab2latex :: Label -> Latex lab2latex Id = "id" lab2latex LImplL = "\\backslash L" lab2latex LImplR = "\\backslash R" lab2latex RImplL = "/ L" lab2latex RImplR = "/ R" lab2latex (MonL t) = "\\lozenge L_{" ++ t ++ "}" lab2latex (MonR t) = "\\lozenge R_{" ++ t ++ "}" lab2latex TensL = "\\otimes L" lab2latex TensR = "\\otimes R" lambda2latex :: LambdaTerm -> Latex lambda2latex (C c) = c lambda2latex (V n) | n < length sanevars && n >= 0 = sanevars !! n | otherwise = "v" ++ show n lambda2latex (Lambda x b) = "\\lambda " ++ lambda2latex x ++ "." ++ lambda2latex b lambda2latex (Eta t f) = "\\eta_{" ++ t ++ "}(" ++ lambda2latex f ++ ")" lambda2latex (App f@(Lambda _ _) a) = "(" ++ lambda2latex f ++ ")(" ++ lambda2latex a ++ ")" lambda2latex (App f@(Bind _ _ _) a) = "(" ++ lambda2latex f ++ ")(" ++ lambda2latex a ++ ")" lambda2latex (App f a) = lambda2latex f ++ "(" ++ lambda2latex a ++ ")" lambda2latex (Bind t m k) = lambda2latex m ++ " \\star_{" ++ t ++ "} " ++ lambda2latex k lambda2latex (Pair a b) = "\\langle" ++ lambda2latex a ++ "," ++ lambda2latex b ++ "\\rangle" lambda2latex (FirstProjection a) = "\\pi_1(" ++ lambda2latex a ++ ")" lambda2latex (SecondProjection a) = "\\pi_2(" ++ lambda2latex a ++ ")" decoratedSeq2latex :: DecoratedSequent -> Latex decoratedSeq2latex (gamma,c) = mconcat left ++ " \\vdash " ++ f c where left = intersperse ", " $ map f gamma f (DF _ lt f) = lambda2latex (betaReduce $ monadReduce $ etaReduce $ lt) ++ " : " ++ formula2latex f formula2latex :: Formula -> Latex formula2latex (Atom a) = a formula2latex (Var x) = x formula2latex (M _ (Atom a)) = "\\lozenge " ++ a formula2latex (M _ (Var x)) = "\\lozenge " ++ x formula2latex (M _ f) = "\\lozenge(" ++ formula2latex f ++ ")" formula2latex (P (Atom a) f) = a ++ " \\otimes " ++ formula2latex f formula2latex (P (Var a) f) = a ++ " \\otimes " ++ formula2latex f formula2latex (P d@(M _ _) f) = formula2latex d ++ " \\otimes " ++ formula2latex f formula2latex (P a b) = "(" ++ formula2latex a ++ ") \\otimes " ++ formula2latex b formula2latex (LI f g) = parentheses f (formula2latex f) ++ " \\backslash " ++ parentheses g (formula2latex g) formula2latex (RI f g) = parentheses g (formula2latex g) ++ " / " ++ parentheses f (formula2latex f) parentheses :: Formula -> Latex -> Latex parentheses (RI _ _) h = "(" ++ h ++ ")" parentheses (LI _ _) h = "(" ++ h ++ ")" parentheses _ h = h
gianlucagiorgolo/lambek-monad
Latex.hs
mit
3,168
54
14
782
1,303
638
665
99
3
----------------------------------------------------------------------------- -- | -- Module : Data.EXT2.Info -- Copyright : (C) 2015 Braden Walters, -- 2015 Ricky Elrod -- License : MIT (see LICENSE file) -- Maintainer : Braden Walters <[email protected]>, -- Ricky Elrod <[email protected]> -- Stability : experimental -- Portability : ghc -- -- This module contains functions and types for dealing with ext2\'s concept of -- inodes. module Data.EXT2.Info ( ext2Info , ext2Debug ) where import Control.Lens import Data.EXT2.BlockGroupDescriptor import Data.EXT2.Directory import Data.EXT2.Info.Types import Data.EXT2.Integrity.BlockGroupDescriptor import Data.EXT2.Integrity.Inode import Data.EXT2.Integrity.Superblock import Data.EXT2.Superblock as Superblock import Data.EXT2.UsageBitmaps import Data.Functor import qualified Data.Vector as V import System.IO ext2Info :: Handle -> IO (Either EXT2Error EXT2Info) ext2Info handle = do superblockOrErr <- fetchSuperblock handle case superblockOrErr of Left err -> return $ Left err Right superblock -> do superblockCopiesOrErr <- fetchSuperblockCopies handle superblock case superblockCopiesOrErr of Left err -> return $ Left err Right superblockCopies -> do bgdTable <- fetchBGDT superblock handle bgdTableCopies <- fetchBGDTCopies superblock superblockCopies handle usageBitmaps <- fetchUsageBitmaps superblock bgdTable handle fsTreeMay <- buildFsTree handle superblock bgdTable case fsTreeMay of Just fsTree -> maybe (Right <$> generateInfo handle superblock bgdTable fsTree) (return . Left) (checkConsistency superblock superblockCopies bgdTable bgdTableCopies usageBitmaps fsTree) Nothing -> return $ Left GeneralError checkConsistency :: Superblock -> SuperblockCopies -> BlockGroupDescriptorTable -> BlockGroupDescriptorTableCopies -> (BlockUsageBitmap, InodeUsageBitmap) -> FsItem -> Maybe EXT2Error checkConsistency sb sbCopies bgdTable bgdTableCopies (_, inodeUsage) fsTree = either Just (const Nothing) doCheck where doCheck = do superblockCopiesConsistency sb sbCopies bgdTableCopiesConsistency bgdTable bgdTableCopies usedInodesReachable inodeUsage fsTree reachableInodesUsed inodeUsage fsTree generateInfo :: Handle -> Superblock -> BlockGroupDescriptorTable -> FsItem -> IO EXT2Info generateInfo _ sb bgdTable fsRoot = return EXT2Info { ext2TotalSize = sb ^. to fileSystemSize, ext2UsedFileSpaceSize = sb ^. to fileSystemSize - sb ^. to freeFileSystemSize, ext2UnusedFileSpaceSize = sb ^. to freeFileSystemSize, ext2NumInodes = sb ^. inodesCount, ext2NumFiles = countFiles fsRoot, ext2NumDirectories = V.foldl (+) 0 (V.map bgdNumDirectories bgdTable), ext2NumBlockGroups = Superblock.numBlockGroups sb, ext2BlockSize = sb ^. logBlockSize, ext2StateClean = sb ^. state == StateClean } {-# INLINE generateInfo #-} ext2Debug :: Handle -> IO () ext2Debug handle = do superblockOrErr <- fetchSuperblock handle case superblockOrErr of Left _ -> error "Superblock failure." Right superblock -> printSuperblockInfo handle superblock printSuperblockInfo :: Handle -> Superblock -> IO () printSuperblockInfo handle superblock = do putStrLn "Superblock is:" print superblock bgdTable <- fetchBGDT superblock handle V.zipWithM_ (printBGDInfo handle superblock) bgdTable (V.enumFromN 0 (V.length bgdTable)) printSuperblockCopyInfo handle superblock printRootDir handle superblock bgdTable printSuperblockCopyInfo :: Handle -> Superblock -> IO () printSuperblockCopyInfo handle superblock = do putStrLn "Superblock copies are:" superblocks <- fetchSuperblockCopies handle superblock case superblocks of Left ext2error -> print ext2error Right copies -> do mapM_ print copies bgdTableCopies <- fetchBGDTCopies superblock copies handle mapM_ (\tbl -> V.zipWithM_ (printBGDInfo handle superblock) tbl (V.enumFromN 0 (V.length tbl))) bgdTableCopies printBGDInfo :: Handle -> Superblock -> BlockGroupDescriptor -> Integer -> IO () printBGDInfo _ _ bgd num = do putStrLn ("Block Group Descriptor " ++ show num) print bgd printRootDir :: Handle -> Superblock -> BlockGroupDescriptorTable -> IO () printRootDir handle superblock bgdTable = do tree <- buildFsTree handle superblock bgdTable case tree of Just fsTree -> print fsTree Nothing -> error "Could not walk filesystem."
meoblast001/ext2-info
src/Data/EXT2/Info.hs
mit
4,820
0
23
1,113
1,095
543
552
98
4
module Graph.Parse ( parse ) where import Control.Monad (guard) import Data.Graph import Text.Parsec (anyToken, notFollowedBy) import qualified Text.Parsec as TP import Text.Parsec.Char (char) import Text.Parsec.Utils (nat) import Text.Read (readMaybe) -- | 'parse' parses the given 'String' into a 'Graph' according to the file -- format given for task 1 at http://www.ics.uci.edu/~wayne/research/students/ -- -- /"The first line of the file is N, the number of nodes. You will name the/ -- /nodes from 0 through N-1. The remaining lines will have two integers per/ -- /line, representing an edge."/ -- -- prop> parse "10\n0 2\n1 0" == Just (buildG (0, 9) [(0, 2), (1, 0)]) -- -- prop> parse "5" == Just (buildG (0, 4) []) -- -- Trailing new lines: -- -- prop> parse "5" == Just (buildG (0, 4) []) -- -- prop> parse "10\n0 2\n1 0\n" == Just (buildG (0, 9) [(0, 2), (1, 0)]) -- -- Invalid: -- -- prop> parse "5a" == Nothing -- -- prop> parse "5\n0 1a" == Nothing -- parse :: String -> Maybe Graph parse dat = case lines dat of [] -> Nothing (sizeStr:edgesStr) -> do bnds <- parseNodes sizeStr >>= getBounds edgs <- mapM parseEdge edgesStr pure $ buildG bnds edgs parseNodes :: String -> Maybe Int parseNodes sizeStr = do n <- readMaybe sizeStr :: Maybe Integer guard (n > 0 || n < fromIntegral (maxBound :: Int)) pure $ fromIntegral n parseEdge :: String -> Maybe Edge parseEdge edgeStr = let numbers = do n1 <- nat char ' ' n2 <- nat notFollowedBy anyToken pure (n1, n2) in case TP.parse numbers "" edgeStr of Left _ -> Nothing Right e -> pure e getBounds :: Int -> Maybe Bounds getBounds i = do -- Must be a natural number. i.e. we can't have a negative number of nodes. guard (i > 0) case i of 0 -> pure (0, 0) n -> pure (0, n - 1)
samgd/graph
src/Graph/Parse.hs
mit
1,955
0
12
540
442
233
209
39
2
{-# LANGUAGE TemplateHaskell #-} {-# OPTIONS_GHC -fno-warn-orphans #-} {-| Unittests for ganeti-htools. -} {- Copyright (C) 2009, 2010, 2011, 2012, 2013 Google Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -} module Test.Ganeti.Rpc (testRpc) where import Test.QuickCheck import Test.QuickCheck.Monadic (monadicIO, run, stop) import Control.Applicative import qualified Data.Map as Map import Test.Ganeti.TestHelper import Test.Ganeti.TestCommon import Test.Ganeti.Objects () import qualified Ganeti.Rpc as Rpc import qualified Ganeti.Objects as Objects instance Arbitrary Rpc.RpcCallAllInstancesInfo where arbitrary = Rpc.RpcCallAllInstancesInfo <$> arbitrary instance Arbitrary Rpc.RpcCallInstanceList where arbitrary = Rpc.RpcCallInstanceList <$> arbitrary instance Arbitrary Rpc.RpcCallNodeInfo where arbitrary = Rpc.RpcCallNodeInfo <$> arbitrary <*> arbitrary <*> pure Map.empty -- | Monadic check that, for an offline node and a call that does not -- offline nodes, we get a OfflineNodeError response. -- FIXME: We need a way of generalizing this, running it for -- every call manually will soon get problematic prop_noffl_request_allinstinfo :: Rpc.RpcCallAllInstancesInfo -> Property prop_noffl_request_allinstinfo call = forAll (arbitrary `suchThat` Objects.nodeOffline) $ \node -> monadicIO $ do res <- run $ Rpc.executeRpcCall [node] call stop $ res ==? [(node, Left Rpc.OfflineNodeError)] prop_noffl_request_instlist :: Rpc.RpcCallInstanceList -> Property prop_noffl_request_instlist call = forAll (arbitrary `suchThat` Objects.nodeOffline) $ \node -> monadicIO $ do res <- run $ Rpc.executeRpcCall [node] call stop $ res ==? [(node, Left Rpc.OfflineNodeError)] prop_noffl_request_nodeinfo :: Rpc.RpcCallNodeInfo -> Property prop_noffl_request_nodeinfo call = forAll (arbitrary `suchThat` Objects.nodeOffline) $ \node -> monadicIO $ do res <- run $ Rpc.executeRpcCall [node] call stop $ res ==? [(node, Left Rpc.OfflineNodeError)] testSuite "Rpc" [ 'prop_noffl_request_allinstinfo , 'prop_noffl_request_instlist , 'prop_noffl_request_nodeinfo ]
damoxc/ganeti
test/hs/Test/Ganeti/Rpc.hs
gpl-2.0
2,786
0
14
445
464
260
204
38
1
{-# LANGUAGE MultiParamTypeClasses #-} {- | Module : ./Propositional/Logic_Propositional.hs Description : Instance of class Logic for propositional logic Copyright : (c) Dominik Luecke, Uni Bremen 2007 License : GPLv2 or higher, see LICENSE.txt Maintainer : [email protected] Stability : experimental Portability : non-portable (imports Logic.Logic) Instance of class Logic for the propositional logic Also the instances for Syntax and Category. -} {- Ref. http://en.wikipedia.org/wiki/Propositional_logic Till Mossakowski, Joseph Goguen, Razvan Diaconescu, Andrzej Tarlecki. What is a Logic?. In Jean-Yves Beziau (Ed.), Logica Universalis, pp. 113-@133. Birkhaeuser. 2005. -} module Propositional.Logic_Propositional where import ATC.ProofTree () import Logic.Logic import Propositional.Sign import Propositional.Morphism import Propositional.AS_BASIC_Propositional import Propositional.ATC_Propositional () import Propositional.Fold import Propositional.Symbol as Symbol import Propositional.Parse_AS_Basic import Propositional.Analysis import Propositional.Sublogic as Sublogic import Propositional.ProveWithTruthTable import Propositional.Prove import Propositional.Conservativity import Propositional.ProveMinisat import Common.ProverTools import Common.Consistency import Common.ProofTree import Common.Id import qualified Data.Map as Map import Data.Monoid -- | Lid for propositional logic data Propositional = Propositional deriving Show instance Language Propositional where description _ = "Propositional Logic\n" ++ "for more information please refer to\n" ++ "http://en.wikipedia.org/wiki/Propositional_logic" -- | Instance of Category for propositional logic instance Category Sign Morphism where -- Identity morhpism ide = idMor -- Returns the domain of a morphism dom = source -- Returns the codomain of a morphism cod = target -- check if morphism is inclusion isInclusion = Map.null . propMap -- tests if the morphism is ok legal_mor = isLegalMorphism -- composition of morphisms composeMorphisms = composeMor -- | Instance of Sentences for propositional logic instance Sentences Propositional FORMULA Sign Morphism Symbol where negation Propositional = Just . negForm nullRange -- returns the set of symbols sym_of Propositional = singletonList . symOf -- returns the symbol map symmap_of Propositional = getSymbolMap -- returns the name of a symbol sym_name Propositional = getSymbolName symKind Propositional _ = "prop" -- translation of sentences along signature morphism map_sen Propositional = mapSentence -- there is nothing to leave out simplify_sen Propositional _ = simplify instance Monoid BASIC_SPEC where mempty = Basic_spec [] mappend (Basic_spec l1) (Basic_spec l2) = Basic_spec $ l1 ++ l2 -- - | Syntax of Propositional logic instance Syntax Propositional BASIC_SPEC Symbol SYMB_ITEMS SYMB_MAP_ITEMS where parsersAndPrinters Propositional = addSyntax "Hets" (basicSpec, pretty) $ makeDefault (basicSpec, pretty) parse_symb_items Propositional = Just symbItems parse_symb_map_items Propositional = Just symbMapItems -- | Instance of Logic for propositional logc instance Logic Propositional PropSL -- Sublogics BASIC_SPEC -- basic_spec FORMULA -- sentence SYMB_ITEMS -- symb_items SYMB_MAP_ITEMS -- symb_map_items Sign -- sign Morphism -- morphism Symbol -- symbol Symbol -- raw_symbol ProofTree -- proof_tree where -- hybridization parse_basic_sen Propositional = Just $ const impFormula stability Propositional = Stable top_sublogic Propositional = Sublogic.top all_sublogics Propositional = sublogics_all empty_proof_tree Propositional = emptyProofTree -- supplied provers provers Propositional = [zchaffProver, minisatProver Minisat, minisatProver Minisat2, ttProver] cons_checkers Propositional = [ propConsChecker, minisatConsChecker Minisat , minisatConsChecker Minisat2, ttConsistencyChecker] conservativityCheck Propositional = [ ConservativityChecker "sKizzo" (checkBinary "sKizzo") conserCheck , ConservativityChecker "Truth Tables" (return Nothing) ttConservativityChecker] -- | Static Analysis for propositional logic instance StaticAnalysis Propositional BASIC_SPEC -- basic_spec FORMULA -- sentence SYMB_ITEMS -- symb_items SYMB_MAP_ITEMS -- symb_map_items Sign -- sign Morphism -- morphism Symbol -- symbol Symbol -- raw_symbol where basic_analysis Propositional = Just basicPropositionalAnalysis sen_analysis Propositional = Just pROPsen_analysis empty_signature Propositional = emptySig is_subsig Propositional = isSubSigOf subsig_inclusion Propositional s = return . inclusionMap s signature_union Propositional = sigUnion symbol_to_raw Propositional = symbolToRaw id_to_raw Propositional = idToRaw matches Propositional = Symbol.matches stat_symb_items Propositional _ = mkStatSymbItems stat_symb_map_items Propositional _ _ = mkStatSymbMapItem morphism_union Propositional = morphismUnion induced_from_morphism Propositional = inducedFromMorphism induced_from_to_morphism Propositional = inducedFromToMorphism signature_colimit Propositional = signatureColimit -- | Sublogics instance SemiLatticeWithTop PropSL where lub = sublogics_max top = Sublogic.top instance MinSublogic PropSL BASIC_SPEC where minSublogic = sl_basic_spec bottom instance MinSublogic PropSL Sign where minSublogic = sl_sig bottom instance SublogicName PropSL where sublogicName = sublogics_name instance MinSublogic PropSL FORMULA where minSublogic = sl_form bottom instance MinSublogic PropSL Symbol where minSublogic = sl_sym bottom instance MinSublogic PropSL SYMB_ITEMS where minSublogic = sl_symit bottom instance MinSublogic PropSL Morphism where minSublogic = sl_mor bottom instance MinSublogic PropSL SYMB_MAP_ITEMS where minSublogic = sl_symmap bottom instance ProjectSublogicM PropSL Symbol where projectSublogicM = prSymbolM instance ProjectSublogic PropSL Sign where projectSublogic = prSig instance ProjectSublogic PropSL Morphism where projectSublogic = prMor instance ProjectSublogicM PropSL SYMB_MAP_ITEMS where projectSublogicM = prSymMapM instance ProjectSublogicM PropSL SYMB_ITEMS where projectSublogicM = prSymM instance ProjectSublogic PropSL BASIC_SPEC where projectSublogic = prBasicSpec instance ProjectSublogicM PropSL FORMULA where projectSublogicM = prFormulaM
spechub/Hets
Propositional/Logic_Propositional.hs
gpl-2.0
7,242
0
9
1,737
1,050
570
480
137
0
{-# LANGUAGE OverloadedStrings #-} -- | All hardcoded names in the compiler should go in here -- the convention is -- v_foo for values -- tc_foo for type constructors -- dc_foo for data constructors -- s_foo for sort names -- rt_foo for raw names -- class_foo for classes module Name.Names(module Name.Names,module Name.Prim) where import Char(isDigit) import Name.Name import Name.Prim import Name.VConsts instance TypeNames Name where tInt = tc_Int tBool = tc_Bool tInteger = tc_Integer tChar = tc_Char tUnit = tc_Unit tIntzh = rt_bits32 tEnumzh = rt_bits16 tCharzh = tc_Char_ -- tWorld__ = tc_World__ --No tuple instance because it is easy to get the namespace wrong. use 'nameTuple' --instance ToTuple Name where -- toTuple n = toName DataConstructor (toTuple n :: (String,String)) nameTuple _ n | n < 2 = error "attempt to create tuple of length < 2" nameTuple t n = toName t $ (toTuple n:: (String,String)) -- Qual (HsIdent ("(" ++ replicate (n - 1) ',' ++ ")")) unboxedNameTuple t n = toName t $ "(#" ++ show n ++ "#)" fromUnboxedNameTuple n = case show n of '(':'#':xs | (ns@(_:_),"#)") <- span isDigit xs -> return (read ns::Int) _ -> fail $ "Not unboxed tuple: " ++ show n instance FromTupname Name where fromTupname name | m == Module "Jhc.Prim.Prim" = fromTupname (nn::String) where (_,(m,nn)) = fromName name fromTupname _ = fail "not a tuple" -- quasi-kinds (placeholders for existential kinds) s_Quest = toName SortName (Module "Jhc@","?"::String) s_QuestQuest = toName SortName (Module "Jhc@","??"::String) s_StarBang = toName SortName (Module "Jhc@","*!"::String) s_Any = toName SortName (Module "Jhc@","ANY"::String) u_instance = toName UnknownType (Module "Jhc@","instance"::String) sFuncNames = FuncNames { func_equals = v_equals, func_fromInteger = v_fromInteger, func_fromInt = v_fromInt, func_fromRational = v_fromRational, func_negate = v_negate, func_runExpr = v_runExpr, func_runMain = v_runMain, func_runNoWrapper = v_runNoWrapper, func_runRaw = v_runRaw }
dec9ue/jhc_copygc
src/Name/Names.hs
gpl-2.0
2,099
0
15
411
521
290
231
40
2
{- ============================================================================ | Copyright 2011 Matthew D. Steele <[email protected]> | | | | This file is part of Fallback. | | | | Fallback is free software: you can redistribute it and/or modify it under | | the terms of the GNU General Public License as published by the Free | | Software Foundation, either version 3 of the License, or (at your option) | | any later version. | | | | Fallback 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 Fallback. If not, see <http://www.gnu.org/licenses/>. | ============================================================================ -} {-# LANGUAGE ForeignFunctionInterface #-} module HSMain (fallback_sdl_main) where import Fallback.Main (sdlMain) ------------------------------------------------------------------------------- foreign export ccall fallback_sdl_main :: IO () fallback_sdl_main :: IO () fallback_sdl_main = sdlMain -------------------------------------------------------------------------------
mdsteele/fallback
src/HSMain.hs
gpl-3.0
1,823
0
7
710
53
32
21
6
1
import Network.Socket import Network.Multicast main = withSocketsDo $ do sock <- multicastReceiver "224.0.0.99" 9999 let loop = do ( msg, _, addr ) <- recvFrom sock 1024 putStrLn ("from: " ++ show addr ++ " text = " ++ msg) sendTo sock "Pong" addr loop in loop
alexginzburg/dprfs
src/multicast-receive.hs
gpl-3.0
273
0
18
59
104
49
55
9
1
module DoubleAuction.Run ( runDoubleAuctionSteps, runDoubleAuctionDebug ) where import FRP.Yampa import DoubleAuction.Model import DoubleAuction.Init import FRP.FrABS import Text.Printf import System.IO rngSeed = 42 t = 1.0 agentCount = 10 dt = 1000 updateStrat = Parallel -- NOTE: would not work correctly when using Sequential traversion shuffleAgents = False -- TODO: repair runDoubleAuctionSteps :: IO () runDoubleAuctionSteps = do hSetBuffering stdout NoBuffering params <- initSimulation updateStrat Nothing Nothing shuffleAgents (Just rngSeed) (initAdefs, initEnv) <- initDoubleAuction agentCount let asenv = simulateTime initAdefs initEnv params dt t let (_, asFinal, _) = last asenv mapM printTraderAgent asFinal return () runDoubleAuctionDebug :: IO () runDoubleAuctionDebug = do hSetBuffering stdout NoBuffering params <- initSimulation updateStrat Nothing Nothing shuffleAgents (Just rngSeed) (initAdefs, initEnv) <- initDoubleAuction agentCount simulateDebug initAdefs initEnv params dt renderFunc where renderFunc :: Bool -> (Time, [DAAgentObservable], DAEnvironment) -> IO Bool renderFunc _ (_, aobs, env) = mapM_ printTraderAgent aobs >> (return False) printTraderAgent :: DAAgentObservable -> IO () printTraderAgent (aid, s) | isTrader $ s = do let cash = daTraderCash s let assets = daTraderAssets s let loansTaken = daTraderLoansTaken s let loansGiven = daTraderLoansGiven s putStrLn $ "Agent " ++ (show aid) ++ ": cash = " ++ (printf "%.2f" cash) ++ " assets = " ++ (printf "%.2f" assets) ++ " loans taken = " ++ (printf "%.2f" loansTaken) ++ " loans given = " ++ (printf "%.2f" loansGiven) return () | otherwise = return ()
thalerjonathan/phd
coding/libraries/chimera/examples/ABS/DoubleAuction/Run.hs
gpl-3.0
2,025
0
18
615
527
262
265
49
1
(->) a b
hmemcpy/milewski-ctfp-pdf
src/content/1.7/code/haskell/snippet19.hs
gpl-3.0
8
1
7
2
13
5
8
-1
-1
{-# LANGUAGE Arrows #-} module Zombies.Agent ( zombie, human ) where import Zombies.Model import FRP.FrABS import FRP.Yampa import Data.List import Control.Monad.Trans.State import Control.Monad.IfElse import Debug.Trace agentCoordToPatchCoord :: ZombiesEnvironment -> State ZombiesAgentOut Discrete2dCoord agentCoordToPatchCoord (as, ap, _) = agentStateFieldM zAgentCoord >>= \coord -> return $ cont2dTransDisc2d ap as coord humanBehaviourM :: ZombiesEnvironment -> Double -> ZombiesAgentIn -> State ZombiesAgentOut ZombiesEnvironment humanBehaviourM e@(as, ap, an) _ ain = do updateAgentStateM (\s -> s { zAgentRole = Human }) originPatch <- agentCoordToPatchCoord e let ns = neighbours originPatch True ap ns' <- agentRandomShuffleM ns let sortedNs = sortBy sortPatchesByZombies ns' let (_, (_, maxZombiesCount)) = last sortedNs ifThenElse (maxZombiesCount > 0) -- read: any zombies within neighbourhood (do let fewestZombiesPatch = fst . head $ sortedNs energy <- agentStateFieldM zHumanEnergyLevel ifThenElse (energy > 0) (flee originPatch fewestZombiesPatch e) (resetEnergy >> return e)) (return e) where resetEnergy :: State ZombiesAgentOut () resetEnergy = updateAgentStateM (\s -> s { zHumanEnergyLevel = zHumanEnergyInit s }) reduceEnergy :: State ZombiesAgentOut () reduceEnergy = updateAgentStateM (\s -> s { zHumanEnergyLevel = zHumanEnergyLevel s - 1 }) flee :: Discrete2dCoord -> Discrete2dCoord -> ZombiesEnvironment -> State ZombiesAgentOut ZombiesEnvironment flee originPatch targetPatch e@(as, ap, an) | originPatch == targetPatch = return e | otherwise = do coord <- agentStateFieldM zAgentCoord let coord' = stepTo as humanSpeed coord (disc2dToCont2d targetPatch) updateAgentStateM (\s -> s { zAgentCoord = coord' }) reduceEnergy aid <- agentIdM let ap0 = updateCellAt originPatch (removeHuman aid) ap let ap1 = updateCellAt targetPatch (addHuman aid) ap0 return (as, ap1, an) zombieBehaviourM :: ZombiesEnvironment -> Double -> ZombiesAgentIn -> State ZombiesAgentOut ZombiesEnvironment zombieBehaviourM e@(as, ap, an) _ ain = do updateAgentStateM (\s -> s { zAgentRole = Zombie }) coord <- agentStateFieldM zAgentCoord originPatch <- agentCoordToPatchCoord e let ns = neighbours originPatch True ap ns' <- agentRandomShuffleM ns let sortedNs = sortBy sortPatchesByHumans ns' let patch@(maxHumanCoord, (hs, _)) = last sortedNs e' <- moveTowards originPatch maxHumanCoord e infect patch e' where moveTowards :: Discrete2dCoord -> Discrete2dCoord -> ZombiesEnvironment -> State ZombiesAgentOut ZombiesEnvironment moveTowards originPatch targetPatch e | originPatch == targetPatch = return e | otherwise = do coord <- agentStateFieldM zAgentCoord let coord' = stepTo as zombieSpeed coord (disc2dToCont2d targetPatch) updateAgentStateM (\s -> s { zAgentCoord = coord' }) let ap0 = updateCellAt originPatch decZombie ap let ap1 = updateCellAt targetPatch incZombie ap0 return (as, ap1, an) infect :: Discrete2dCell ZombiesPatch -> ZombiesEnvironment -> State ZombiesAgentOut ZombiesEnvironment infect (_, ([], _)) e = return e -- no humans on this patch infect (coord, (hs, _)) e@(as, ap, an) = do h <- agentRandomPickM hs sendMessageToM h Infect let ap0 = updateCellAt coord (removeHuman h) ap let ap1 = updateCellAt coord incZombie ap0 return (as, ap1, an) ------------------------------------------------------------------------------------------------------------------------ -- BEHAVIOURS ------------------------------------------------------------------------------------------------------------------------ human :: ZombiesAgentBehaviour human = transitionOnMessage Infect (agentMonadic humanBehaviourM) (agentMonadic zombieBehaviourM) zombie :: ZombiesAgentBehaviour zombie = agentMonadic zombieBehaviourM ------------------------------------------------------------------------------------------------------------------------
thalerjonathan/phd
coding/libraries/chimera/examples/ABS/Zombies/Agent.hs
gpl-3.0
4,896
4
15
1,513
1,161
584
577
94
2
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Compute.RegionInstanceGroupManagers.List -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Retrieves the list of managed instance groups that are contained within -- the specified region. -- -- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.regionInstanceGroupManagers.list@. module Network.Google.Resource.Compute.RegionInstanceGroupManagers.List ( -- * REST Resource RegionInstanceGroupManagersListResource -- * Creating a Request , regionInstanceGroupManagersList , RegionInstanceGroupManagersList -- * Request Lenses , rigmlOrderBy , rigmlProject , rigmlFilter , rigmlRegion , rigmlPageToken , rigmlMaxResults ) where import Network.Google.Compute.Types import Network.Google.Prelude -- | A resource alias for @compute.regionInstanceGroupManagers.list@ method which the -- 'RegionInstanceGroupManagersList' request conforms to. type RegionInstanceGroupManagersListResource = "compute" :> "v1" :> "projects" :> Capture "project" Text :> "regions" :> Capture "region" Text :> "instanceGroupManagers" :> QueryParam "orderBy" Text :> QueryParam "filter" Text :> QueryParam "pageToken" Text :> QueryParam "maxResults" (Textual Word32) :> QueryParam "alt" AltJSON :> Get '[JSON] RegionInstanceGroupManagerList -- | Retrieves the list of managed instance groups that are contained within -- the specified region. -- -- /See:/ 'regionInstanceGroupManagersList' smart constructor. data RegionInstanceGroupManagersList = RegionInstanceGroupManagersList' { _rigmlOrderBy :: !(Maybe Text) , _rigmlProject :: !Text , _rigmlFilter :: !(Maybe Text) , _rigmlRegion :: !Text , _rigmlPageToken :: !(Maybe Text) , _rigmlMaxResults :: !(Textual Word32) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'RegionInstanceGroupManagersList' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'rigmlOrderBy' -- -- * 'rigmlProject' -- -- * 'rigmlFilter' -- -- * 'rigmlRegion' -- -- * 'rigmlPageToken' -- -- * 'rigmlMaxResults' regionInstanceGroupManagersList :: Text -- ^ 'rigmlProject' -> Text -- ^ 'rigmlRegion' -> RegionInstanceGroupManagersList regionInstanceGroupManagersList pRigmlProject_ pRigmlRegion_ = RegionInstanceGroupManagersList' { _rigmlOrderBy = Nothing , _rigmlProject = pRigmlProject_ , _rigmlFilter = Nothing , _rigmlRegion = pRigmlRegion_ , _rigmlPageToken = Nothing , _rigmlMaxResults = 500 } -- | Sorts list results by a certain order. By default, results are returned -- in alphanumerical order based on the resource name. You can also sort -- results in descending order based on the creation timestamp using -- orderBy=\"creationTimestamp desc\". This sorts results based on the -- creationTimestamp field in reverse chronological order (newest result -- first). Use this to sort resources like operations so that the newest -- operation is returned first. Currently, only sorting by name or -- creationTimestamp desc is supported. rigmlOrderBy :: Lens' RegionInstanceGroupManagersList (Maybe Text) rigmlOrderBy = lens _rigmlOrderBy (\ s a -> s{_rigmlOrderBy = a}) -- | Project ID for this request. rigmlProject :: Lens' RegionInstanceGroupManagersList Text rigmlProject = lens _rigmlProject (\ s a -> s{_rigmlProject = a}) -- | Sets a filter expression for filtering listed resources, in the form -- filter={expression}. Your {expression} must be in the format: field_name -- comparison_string literal_string. The field_name is the name of the -- field you want to compare. Only atomic field types are supported -- (string, number, boolean). The comparison_string must be either eq -- (equals) or ne (not equals). The literal_string is the string value to -- filter to. The literal value must be valid for the type of field you are -- filtering by (string, number, boolean). For string fields, the literal -- value is interpreted as a regular expression using RE2 syntax. The -- literal value must match the entire field. For example, to filter for -- instances that do not have a name of example-instance, you would use -- filter=name ne example-instance. You can filter on nested fields. For -- example, you could filter on instances that have set the -- scheduling.automaticRestart field to true. Use filtering on nested -- fields to take advantage of labels to organize and search for results -- based on label values. To filter on multiple expressions, provide each -- separate expression within parentheses. For example, -- (scheduling.automaticRestart eq true) (zone eq us-central1-f). Multiple -- expressions are treated as AND expressions, meaning that resources must -- match all expressions to pass the filters. rigmlFilter :: Lens' RegionInstanceGroupManagersList (Maybe Text) rigmlFilter = lens _rigmlFilter (\ s a -> s{_rigmlFilter = a}) -- | Name of the region scoping this request. rigmlRegion :: Lens' RegionInstanceGroupManagersList Text rigmlRegion = lens _rigmlRegion (\ s a -> s{_rigmlRegion = a}) -- | Specifies a page token to use. Set pageToken to the nextPageToken -- returned by a previous list request to get the next page of results. rigmlPageToken :: Lens' RegionInstanceGroupManagersList (Maybe Text) rigmlPageToken = lens _rigmlPageToken (\ s a -> s{_rigmlPageToken = a}) -- | The maximum number of results per page that should be returned. If the -- number of available results is larger than maxResults, Compute Engine -- returns a nextPageToken that can be used to get the next page of results -- in subsequent list requests. rigmlMaxResults :: Lens' RegionInstanceGroupManagersList Word32 rigmlMaxResults = lens _rigmlMaxResults (\ s a -> s{_rigmlMaxResults = a}) . _Coerce instance GoogleRequest RegionInstanceGroupManagersList where type Rs RegionInstanceGroupManagersList = RegionInstanceGroupManagerList type Scopes RegionInstanceGroupManagersList = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/compute", "https://www.googleapis.com/auth/compute.readonly"] requestClient RegionInstanceGroupManagersList'{..} = go _rigmlProject _rigmlRegion _rigmlOrderBy _rigmlFilter _rigmlPageToken (Just _rigmlMaxResults) (Just AltJSON) computeService where go = buildClient (Proxy :: Proxy RegionInstanceGroupManagersListResource) mempty
rueshyna/gogol
gogol-compute/gen/Network/Google/Resource/Compute/RegionInstanceGroupManagers/List.hs
mpl-2.0
7,665
0
19
1,653
753
452
301
112
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Compute.NodeTypes.AggregatedList -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Retrieves an aggregated list of node types. -- -- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.nodeTypes.aggregatedList@. module Network.Google.Resource.Compute.NodeTypes.AggregatedList ( -- * REST Resource NodeTypesAggregatedListResource -- * Creating a Request , nodeTypesAggregatedList , NodeTypesAggregatedList -- * Request Lenses , ntalIncludeAllScopes , ntalReturnPartialSuccess , ntalOrderBy , ntalProject , ntalFilter , ntalPageToken , ntalMaxResults ) where import Network.Google.Compute.Types import Network.Google.Prelude -- | A resource alias for @compute.nodeTypes.aggregatedList@ method which the -- 'NodeTypesAggregatedList' request conforms to. type NodeTypesAggregatedListResource = "compute" :> "v1" :> "projects" :> Capture "project" Text :> "aggregated" :> "nodeTypes" :> QueryParam "includeAllScopes" Bool :> QueryParam "returnPartialSuccess" Bool :> QueryParam "orderBy" Text :> QueryParam "filter" Text :> QueryParam "pageToken" Text :> QueryParam "maxResults" (Textual Word32) :> QueryParam "alt" AltJSON :> Get '[JSON] NodeTypeAggregatedList -- | Retrieves an aggregated list of node types. -- -- /See:/ 'nodeTypesAggregatedList' smart constructor. data NodeTypesAggregatedList = NodeTypesAggregatedList' { _ntalIncludeAllScopes :: !(Maybe Bool) , _ntalReturnPartialSuccess :: !(Maybe Bool) , _ntalOrderBy :: !(Maybe Text) , _ntalProject :: !Text , _ntalFilter :: !(Maybe Text) , _ntalPageToken :: !(Maybe Text) , _ntalMaxResults :: !(Textual Word32) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'NodeTypesAggregatedList' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ntalIncludeAllScopes' -- -- * 'ntalReturnPartialSuccess' -- -- * 'ntalOrderBy' -- -- * 'ntalProject' -- -- * 'ntalFilter' -- -- * 'ntalPageToken' -- -- * 'ntalMaxResults' nodeTypesAggregatedList :: Text -- ^ 'ntalProject' -> NodeTypesAggregatedList nodeTypesAggregatedList pNtalProject_ = NodeTypesAggregatedList' { _ntalIncludeAllScopes = Nothing , _ntalReturnPartialSuccess = Nothing , _ntalOrderBy = Nothing , _ntalProject = pNtalProject_ , _ntalFilter = Nothing , _ntalPageToken = Nothing , _ntalMaxResults = 500 } -- | Indicates whether every visible scope for each scope type (zone, region, -- global) should be included in the response. For new resource types added -- after this field, the flag has no effect as new resource types will -- always include every visible scope for each scope type in response. For -- resource types which predate this field, if this flag is omitted or -- false, only scopes of the scope types where the resource type is -- expected to be found will be included. ntalIncludeAllScopes :: Lens' NodeTypesAggregatedList (Maybe Bool) ntalIncludeAllScopes = lens _ntalIncludeAllScopes (\ s a -> s{_ntalIncludeAllScopes = a}) -- | Opt-in for partial success behavior which provides partial results in -- case of failure. The default value is false. ntalReturnPartialSuccess :: Lens' NodeTypesAggregatedList (Maybe Bool) ntalReturnPartialSuccess = lens _ntalReturnPartialSuccess (\ s a -> s{_ntalReturnPartialSuccess = a}) -- | Sorts list results by a certain order. By default, results are returned -- in alphanumerical order based on the resource name. You can also sort -- results in descending order based on the creation timestamp using -- \`orderBy=\"creationTimestamp desc\"\`. This sorts results based on the -- \`creationTimestamp\` field in reverse chronological order (newest -- result first). Use this to sort resources like operations so that the -- newest operation is returned first. Currently, only sorting by \`name\` -- or \`creationTimestamp desc\` is supported. ntalOrderBy :: Lens' NodeTypesAggregatedList (Maybe Text) ntalOrderBy = lens _ntalOrderBy (\ s a -> s{_ntalOrderBy = a}) -- | Project ID for this request. ntalProject :: Lens' NodeTypesAggregatedList Text ntalProject = lens _ntalProject (\ s a -> s{_ntalProject = a}) -- | A filter expression that filters resources listed in the response. The -- expression must specify the field name, a comparison operator, and the -- value that you want to use for filtering. The value must be a string, a -- number, or a boolean. The comparison operator must be either \`=\`, -- \`!=\`, \`>\`, or \`\<\`. For example, if you are filtering Compute -- Engine instances, you can exclude instances named \`example-instance\` -- by specifying \`name != example-instance\`. You can also filter nested -- fields. For example, you could specify \`scheduling.automaticRestart = -- false\` to include instances only if they are not scheduled for -- automatic restarts. You can use filtering on nested fields to filter -- based on resource labels. To filter on multiple expressions, provide -- each separate expression within parentheses. For example: \`\`\` -- (scheduling.automaticRestart = true) (cpuPlatform = \"Intel Skylake\") -- \`\`\` By default, each expression is an \`AND\` expression. However, -- you can include \`AND\` and \`OR\` expressions explicitly. For example: -- \`\`\` (cpuPlatform = \"Intel Skylake\") OR (cpuPlatform = \"Intel -- Broadwell\") AND (scheduling.automaticRestart = true) \`\`\` ntalFilter :: Lens' NodeTypesAggregatedList (Maybe Text) ntalFilter = lens _ntalFilter (\ s a -> s{_ntalFilter = a}) -- | Specifies a page token to use. Set \`pageToken\` to the -- \`nextPageToken\` returned by a previous list request to get the next -- page of results. ntalPageToken :: Lens' NodeTypesAggregatedList (Maybe Text) ntalPageToken = lens _ntalPageToken (\ s a -> s{_ntalPageToken = a}) -- | The maximum number of results per page that should be returned. If the -- number of available results is larger than \`maxResults\`, Compute -- Engine returns a \`nextPageToken\` that can be used to get the next page -- of results in subsequent list requests. Acceptable values are \`0\` to -- \`500\`, inclusive. (Default: \`500\`) ntalMaxResults :: Lens' NodeTypesAggregatedList Word32 ntalMaxResults = lens _ntalMaxResults (\ s a -> s{_ntalMaxResults = a}) . _Coerce instance GoogleRequest NodeTypesAggregatedList where type Rs NodeTypesAggregatedList = NodeTypeAggregatedList type Scopes NodeTypesAggregatedList = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/compute", "https://www.googleapis.com/auth/compute.readonly"] requestClient NodeTypesAggregatedList'{..} = go _ntalProject _ntalIncludeAllScopes _ntalReturnPartialSuccess _ntalOrderBy _ntalFilter _ntalPageToken (Just _ntalMaxResults) (Just AltJSON) computeService where go = buildClient (Proxy :: Proxy NodeTypesAggregatedListResource) mempty
brendanhay/gogol
gogol-compute/gen/Network/Google/Resource/Compute/NodeTypes/AggregatedList.hs
mpl-2.0
8,222
0
20
1,763
842
503
339
123
1
x *** y = x
lspitzner/brittany
data/Test75.hs
agpl-3.0
12
0
5
5
12
5
7
1
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} -- | -- How to run Databrary Actions. -- -- This module is the foundation of the site. It provides a method for packaging -- up route actions into 'Wai.Application's (which is effectively the HTTP -- transport layer), as well as a method for packaging them into background -- threads. module Action.Run ( -- * \"Framework\" code actionApp , forkAction -- * Declaring authentication needs for Actions , withAuth , withoutAuth , withReAuth -- * The underlying type , Action ) where import Control.Concurrent (ThreadId, forkFinally) import Control.Exception (SomeException) import Control.Monad.Reader (ReaderT(..), withReaderT, local) import Data.Time (getCurrentTime) import Network.HTTP.Types (hDate, hCacheControl, methodHead) import qualified Network.Wai as Wai import Has import HTTP import Service.DB import Service.Types import Service.Log import Model.Identity import Model.Id.Types import Model.Party.Types import HTTP.Request import Context import Action.Types import Action.Request import Action.Response -- | -- Transform a web request to a lower-level action. -- -- Given an action that runs in a top-level Handler, build the necessary context -- for that action, and run in it in the base-level ActionContextM -- -- Handler has a richer context: it has all of ActionContext, plus Identity and -- the Wai Request. withHandler :: forall a . Request -- ^ The wai request to handle -> Identity -- ^ The identity to use for this action -> Handler a -- ^ The action to perform -> ActionContextM a -- ^ The base-level control access to the system withHandler waiReq identity h = let (handler :: ReaderT RequestContext IO a) = unHandler h in withReaderT (\(c :: ActionContext) -> RequestContext c waiReq identity) handler -- | Authentication requirements for an 'Action'. data NeedsAuthentication = NeedsAuthentication | DoesntNeedAuthentication -- | This type captures both the authentication needs and the handler for a -- route. -- -- It extends ActionRoute, which already has most info about a route and how to -- serve it, to include the authentication requirement. data Action = Action { _actionAuthentication :: !NeedsAuthentication , _actionM :: !(Handler Response) } -- | Convert an Action into a Wai.Application. -- -- This is the 3rd level of the Databrary \"web framework\". It runs the -- requested action with some resolved identity to build the HTTP response. See -- 'actionRouteApp' for level 2, and 'servantApp' for level 1. -- -- TODO: For converting to Servant, this whole function should be duplicated by -- new combinators. -- -- For instance, there is a section (in the second 'let', within the do) where -- headers are added to the response. Servant requires us to put that in the -- type, which can be easily done. We can even make a combinator for looking up -- auth results and logging access. After all that, we should be able to create -- something with HoistServer that will run the rest of the (Databrary) Handler. -- -- But then we'll have to map the Response (Action ~ ReaderT RequestContext IO -- Response) into something else! And how do we catch exceptions? Plain old -- catch blocks? And what do we convert exceptions into? actionApp :: Service -- ^ All the low-level system capabilities -> Action -- ^ Action to run -> Wai.Application -- ^ Callback for Wai actionApp service (Action needsAuth act) waiReq waiSend = let isdb = isDatabraryClient waiReq authenticatedAct :: ActionContextM (Identity, Response) authenticatedAct = do sec <- peek conn <- peek identity <- fetchIdent sec conn waiReq needsAuth waiResponse <- ReaderT -- runResult unwraps the short-circuit machinery from -- "Action.Response", returning IO Response. $ \actCtx -> runResult (runHandler act (RequestContext actCtx waiReq identity)) return (identity, waiResponse) in do ts <- getCurrentTime (identityUsed, waiResponse) <- runContextM authenticatedAct service logAccess ts waiReq (extractFromIdentifiedSessOrDefault Nothing (Just . (show :: Id Party -> String) . view) identityUsed) waiResponse (serviceLogs service) let waiResponse' = Wai.mapResponseHeaders (((hDate, formatHTTPTimestamp ts) :) . (if isdb then ((hCacheControl, "no-cache") :) else id)) waiResponse waiSend $ if Wai.requestMethod waiReq == methodHead then emptyResponse (Wai.responseStatus waiResponse') (Wai.responseHeaders waiResponse') else waiResponse' -- | Special-purpose context for determing the user's identity. We don't need -- the full Handler for that, and since this is sensitive work, we don't want to -- just cheat and use it anyway. data IdContext = IdContext { ctxReq :: Wai.Request , ctxSec :: Secret , ctxConn :: DBConn } instance Has Wai.Request IdContext where view = ctxReq instance Has Secret IdContext where view = ctxSec instance Has DBConn IdContext where view = ctxConn -- | Look up the user's identity (or don't) fetchIdent :: Secret -- ^ Session key -> DBConn -- ^ For querying the session table -> Wai.Request -- ^ FIXME: Why the entire request? Can we narrow the scope? What is -- actually needed is the session cookie. -> NeedsAuthentication -- ^ Whether or not to actually do the lookup. -- -- FIXME: This seems like an unncessary complication. -> ActionContextM Identity fetchIdent sec con waiReq = \case NeedsAuthentication -> runReaderT determineIdentity (IdContext waiReq sec con) DoesntNeedAuthentication -> return IdentityNotNeeded -- | Run a Handler action in the background (IO). -- -- A new ActionContextM is built, with a fresh guaranteed db connection and -- timestamp, via 'runContextM' forkAction :: Handler a -- ^ Handler action to run -> RequestContext -- ^ Original context -- -- The background action inherits this context's 'Request' and 'Service'. -> (Either SomeException a -> IO ()) -- ^ Cleanup to run when the action exits -> IO ThreadId forkAction h reqCtx = forkFinally $ runContextM (withHandler req ident h) srv where req = contextRequest reqCtx ident = requestIdentity reqCtx srv = contextService (requestContext reqCtx) -- | Tag an 'Action' as needing to know whether or not the user is -- authenticated. This simply triggers an extra session lookup in 'actionApp'. withAuth :: Handler Response -- ^ The handler for the route -> Action -- ^ The bundled action withAuth = Action NeedsAuthentication -- | Tag an 'Action' as not needing auth. See note at 'withAuth'. withoutAuth :: Handler Response -> Action withoutAuth = Action DoesntNeedAuthentication -- | This may be like a 'su' that allows running an action as a different -- identity. withReAuth :: SiteAuth -- ^ The identity to assume -> Handler a -- ^ The action to perform as the assumed identity -- -- Note that one might argue for an indexed form of 'Handler' here, a la -- Selda and subqueries. -> Handler a -- ^ The re-authenticated action, packaged into the original context withReAuth u = Handler . local (\a -> a { requestIdentity = ReIdentified u }) . unHandler
databrary/databrary
src/Action/Run.hs
agpl-3.0
7,726
0
18
1,883
1,061
603
458
-1
-1
-- This is a simple hello world propgram, which renders "hello world" as text import GEGL import qualified System.Environment as E main :: IO () main = do args <- E.getArgs str <- if null args then return "woo!" else return $ unwords args gegl_init putStrLn str gegl <- gegl_node_new putStrLn "new root node" display <- gegl_node_new_child gegl (pngSaveOperation [Property "path" (PropertyString "examples/example00.png")]) putStrLn "first child" over <- gegl_node_new_child gegl defaultOverOperation putStrLn "over node" text <- gegl_node_new_child gegl (textOperation [ Property "string" $ PropertyString str , Property "color" $ PropertyColor $ RGB 1 0 0 , Property "size" $ PropertyDouble 40 ]) putStrLn "text node" gegl_node_link_many [over, display] putStrLn "link over and display" gegl_node_connect_to text "output" over "aux" putStrLn "connect text to over" gegl_node_process display putStrLn "process display" gegl_exit putStrLn "good night"
nek0/gegl
examples/example00.hs
lgpl-3.0
1,036
0
14
216
271
120
151
30
2
import System.Exit (exitFailure) import Data.Algorithm.Diff.Gestalt import Data.Algorithm.Diff (Diff(..)) main :: IO () main = if diff "diff" "riffs" == [First "d", Second "r", Both "iff" "iff", Second "s"] then return () else exitFailure
chrismwendt/diff-gestalt
test/Spec.hs
unlicense
244
0
8
38
96
53
43
7
2
-- Page 97 #1 import Data.Char (digitToInt) asInt :: String -> Int asInt [] = error "Cannot convert the empty string" asInt '-' = error "Cannot convert a single empty string" asInt ('-':str) = -1 * (asInt str) asInt str = foldl (\memo it -> memo * 10 + it) 0 (map (digitToInt) str)
RobertFischer/real-world-haskell
ch04/AsInt.hs
unlicense
284
0
9
56
116
60
56
6
1
import Data.Monoid -- isBigGang is used to explain Writer monad isBigGang :: Int -> (Bool, String) isBigGang x = (x > 9, "Compared gang size to 9.") -- if we want to feed the (Bool, String) value to isBigGang, we have to do extra work -- here we create a function called "applyLog", just similar to "applyMaybe" created previously applyLog :: (Monoid m) => (a, m) -> (a -> (b, m)) -> (b, m) applyLog (x, log) f = let (y, newLog) = f x in (y, log `mappend` newLog) -- addDrink is used to explain Monoid tuple type Food = String type Price = Sum Int addDrink :: Food -> (Food, Price) addDrink "beans" = ("milk", Sum 25) addDrink "jerky" = ("whiskey", Sum 99) addDrink _ = ("beer", Sum 30)
Oscarzhao/haskell
learnyouahaskell/monads/applyXxx.hs
apache-2.0
691
0
10
135
220
126
94
11
1
{-# LANGUAGE CPP #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} -- | -- Metadata for SAML V2.0 -- -- <http://docs.oasis-open.org/security/saml/v2.0/saml-metadata-2.0-os.pdf saml-metadata-2.0-os> §2 module SAML2.Metadata.Metadata where import Data.Foldable (fold) import qualified Network.URI as URI import qualified Text.XML.HXT.Arrow.Pickle.Schema as XPS import SAML2.Lens import SAML2.XML import qualified Text.XML.HXT.Arrow.Pickle.Xml.Invertible as XP import qualified SAML2.XML.Schema as XS import qualified SAML2.XML.Signature.Types as DS import qualified SAML2.XML.Encryption as XEnc import SAML2.Core.Namespaces import SAML2.Core.Versioning import SAML2.Core.Identifiers import qualified SAML2.Core.Assertions as SAML import SAML2.Bindings.Identifiers ns :: Namespace ns = mkNamespace "md" $ samlURN SAML20 ["metadata"] xpElem :: String -> XP.PU a -> XP.PU a xpElem = xpTrimElemNS ns -- |§2.2.1 type EntityID = AnyURI xpEntityID :: XP.PU EntityID xpEntityID = XS.xpAnyURI -- XXX maxLength=1024 -- |§2.2.2 data Endpoint = Endpoint { endpointBinding :: IdentifiedURI Binding , endpointLocation :: AnyURI , endpointResponseLocation :: Maybe AnyURI , endpointAttrs :: Nodes , endpointXML :: Nodes } deriving (Eq, Show) instance XP.XmlPickler Endpoint where xpickle = [XP.biCase| ((((b, l), r), a), x) <-> Endpoint b l r a x|] XP.>$< (XP.xpAttr "Binding" XP.xpickle XP.>*< XP.xpAttr "Location" XS.xpAnyURI XP.>*< XP.xpAttrImplied "ResponseLocation" XS.xpAnyURI XP.>*< XP.xpAnyAttrs XP.>*< XP.xpList xpTrimAnyElem) -- |§2.2.3 data IndexedEndpoint = IndexedEndpoint { indexedEndpoint :: Endpoint , indexedEndpointIndex :: XS.UnsignedShort , indexedEndpointIsDefault :: XS.Boolean } deriving (Eq, Show) instance XP.XmlPickler IndexedEndpoint where xpickle = [XP.biCase| ((i, d), e) <-> IndexedEndpoint e i d|] XP.>$< (XP.xpAttr "index" XS.xpUnsignedShort XP.>*< XP.xpDefault False (XP.xpAttr "isDefault" XS.xpBoolean) XP.>*< XP.xpickle) data Localized a = Localized { localizedLang :: XS.Language , localized :: a } deriving (Eq, Show) xpLocalized :: XP.PU a -> XP.PU (Localized a) xpLocalized p = [XP.biCase| (l, x) <-> Localized l x|] XP.>$< (xpXmlLang XP.>*< p) -- |§2.2.4 type LocalizedName = Localized XS.String instance XP.XmlPickler LocalizedName where xpickle = xpLocalized XS.xpString -- |§2.2.5 type LocalizedURI = Localized XS.AnyURI instance XP.XmlPickler LocalizedURI where xpickle = xpLocalized XS.xpAnyURI data Metadata = EntityDescriptor { entityID :: EntityID , metadataID :: Maybe XS.ID , metadataValidUntil :: Maybe XS.DateTime , metadataCacheDuration :: Maybe XS.Duration , entityAttrs :: Nodes , metadataSignature :: Maybe DS.Signature , metadataExtensions :: Extensions , entityDescriptors :: Descriptors , entityOrganization :: Maybe Organization , entityContactPerson :: [Contact] , entityAditionalMetadataLocation :: [AdditionalMetadataLocation] } -- ^§2.3.2 | EntitiesDescriptor { metadataID :: Maybe XS.ID , metadataValidUntil :: Maybe XS.DateTime , metadataCacheDuration :: Maybe XS.Duration , entitiesName :: Maybe XS.String , metadataSignature :: Maybe DS.Signature , metadataExtensions :: Extensions , entities :: List1 Metadata } -- ^§2.3.1 deriving (Eq, Show) instance XP.XmlPickler Metadata where xpickle = [XP.biCase| Left ((((((((((e, i), vu), cd), xa), sig), ext), desc), org), cp), aml) <-> EntityDescriptor e i vu cd xa sig ext desc org cp aml Right ((((((i, vu), cd), n), sig), ext), l) <-> EntitiesDescriptor i vu cd n sig ext l|] XP.>$< (xpElem "EntityDescriptor" (XP.xpAttr "entityID" xpEntityID XP.>*< XP.xpAttrImplied "ID" XS.xpID XP.>*< XP.xpAttrImplied "validUntil" XS.xpDateTime XP.>*< XP.xpAttrImplied "cacheDuration" XS.xpDuration XP.>*< XP.xpAnyAttrs XP.>*< XP.xpickle XP.>*< XP.xpickle XP.>*< XP.xpickle XP.>*< XP.xpickle XP.>*< XP.xpList XP.xpickle XP.>*< XP.xpList XP.xpickle) XP.>|< xpElem "EntitiesDescriptor" (XP.xpAttrImplied "ID" XS.xpID XP.>*< XP.xpAttrImplied "validUntil" XS.xpDateTime XP.>*< XP.xpAttrImplied "cacheDuration" XS.xpDuration XP.>*< XP.xpAttrImplied "Name" XS.xpString XP.>*< XP.xpickle XP.>*< XP.xpickle XP.>*< xpList1 XP.xpickle)) instance DS.Signable Metadata where signature' = $(fieldLens 'metadataSignature) signedID = fold . metadataID -- |§2.3.1 empty list means missing newtype Extensions = Extensions{ extensions :: Nodes } deriving (Eq, Show #if MIN_VERSION_base(4,11,0) , Semigroup #endif , Monoid) instance XP.XmlPickler Extensions where xpickle = XP.xpDefault (Extensions []) $ xpElem "Extensions" $ [XP.biCase| x <-> Extensions x|] XP.>$< (XP.xpList1 xpTrimAnyElem) data Descriptors = Descriptors{ descriptors :: List1 Descriptor } | AffiliationDescriptor { affiliationDescriptorAffiliationOwnerID :: EntityID , affiliationDescriptorID :: Maybe XS.ID , affiliationDescriptorValidUntil :: Maybe XS.DateTime , affiliationDescriptorCacheDuration :: Maybe XS.Duration , affiliationDescriptorAttrs :: Nodes , affiliationDescriptorSignature :: Maybe DS.Signature , affiliationDescriptorExtensions :: Extensions , affiliationDescriptorAffiliateMember :: List1 EntityID , affiliationDescriptorKeyDescriptor :: [KeyDescriptor] } -- ^§2.5 deriving (Eq, Show) instance XP.XmlPickler Descriptors where xpickle = [XP.biCase| Left l <-> Descriptors l Right ((((((((o, i), vu), cd), a), sig), ext), am), kd) <-> AffiliationDescriptor o i vu cd a sig ext am kd|] XP.>$< (xpList1 XP.xpickle XP.>|< xpElem "AffiliationDescriptor" (XP.xpAttr "affiliationOwnerID" xpEntityID XP.>*< XP.xpAttrImplied "ID" XS.xpID XP.>*< XP.xpAttrImplied "validUntil" XS.xpDateTime XP.>*< XP.xpAttrImplied "cacheDuration" XS.xpDuration XP.>*< XP.xpAnyAttrs XP.>*< XP.xpickle XP.>*< XP.xpickle XP.>*< xpList1 (xpElem "AffiliateMember" xpEntityID) XP.>*< XP.xpList XP.xpickle)) data Descriptor = Descriptor { descriptorRole :: !RoleDescriptor } -- ^§2.4.1 | IDPSSODescriptor { descriptorRole :: !RoleDescriptor , descriptorSSO :: !SSODescriptor , descriptorWantAuthnRequestsSigned :: XS.Boolean , descriptorSingleSignOnService :: List1 Endpoint , descriptorNameIDMappingService :: [Endpoint] , descriptorAssertionIDRequestService :: [Endpoint] , descriptorAttributeProfile :: [XS.AnyURI] , descriptorAttribute :: [SAML.Attribute] } -- ^§2.4.3 | SPSSODescriptor { descriptorRole :: !RoleDescriptor , descriptorSSO :: !SSODescriptor , descriptorAuthnRequestsSigned :: XS.Boolean , descriptorWantAssertionsSigned :: XS.Boolean , descriptorAssertionConsumerService :: List1 IndexedEndpoint , descriptorAttributeConsumingService :: [AttributeConsumingService] } -- ^§2.4.4 | AuthnAuthorityDescriptor { descriptorRole :: !RoleDescriptor , descriptorAuthnQueryService :: List1 Endpoint , descriptorAssertionIDRequestService :: [Endpoint] , descriptorNameIDFormat :: [IdentifiedURI NameIDFormat] } -- ^§2.4.5 | AttributeAuthorityDescriptor { descriptorRole :: !RoleDescriptor , descriptorAttributeService :: List1 Endpoint , descriptorAssertionIDRequestService :: [Endpoint] , descriptorNameIDFormat :: [IdentifiedURI NameIDFormat] , descriptorAttributeProfile :: [XS.AnyURI] , descriptorAttribute :: [SAML.Attribute] } -- ^§2.4.7 | PDPDescriptor { descriptorRole :: !RoleDescriptor , descriptorAuthzService :: List1 Endpoint , descriptorAssertionIDRequestService :: [Endpoint] , descriptorNameIDFormat :: [IdentifiedURI NameIDFormat] } -- ^§2.4.6 deriving (Eq, Show) instance XP.XmlPickler Descriptor where xpickle = [XP.biCase| Left (Left (Left (Left (Left r)))) <-> Descriptor r Left (Left (Left (Left (Right (((((((ws, r), s), sso), nim), air), ap), a))))) <-> IDPSSODescriptor r s ws sso nim air ap a Left (Left (Left (Right (((((a, w), r), s), e), t)))) <-> SPSSODescriptor r s a w e t Left (Left (Right (((r, a), s), n))) <-> AuthnAuthorityDescriptor r a s n Left (Right (((((r, a), s), n), tp), t)) <-> AttributeAuthorityDescriptor r a s n tp t Right (((r, a), s), n) <-> PDPDescriptor r a s n|] XP.>$< (xpElem "RoleDescriptor" XP.xpickle XP.>|< xpElem "IDPSSODescriptor" (XP.xpDefault False (XP.xpAttr "WantAuthnRequestsSigned" XS.xpBoolean) XP.>*< XP.xpickle XP.>*< XP.xpickle XP.>*< xpList1 (xpElem "SingleSignOnService" XP.xpickle) XP.>*< XP.xpList (xpElem "NameIDMappingService" XP.xpickle) XP.>*< XP.xpList (xpElem "AssertionIDRequestService" XP.xpickle) XP.>*< XP.xpList (xpElem "AttributeProfile" XS.xpAnyURI) XP.>*< XP.xpList XP.xpickle) XP.>|< xpElem "SPSSODescriptor" (XP.xpDefault False (XP.xpAttr "AuthnRequestsSigned" XS.xpBoolean) XP.>*< XP.xpDefault False (XP.xpAttr "WantAssertionsSigned" XS.xpBoolean) XP.>*< XP.xpickle XP.>*< XP.xpickle XP.>*< xpList1 (xpElem "AssertionConsumerService" XP.xpickle) XP.>*< XP.xpList XP.xpickle) XP.>|< xpElem "AuthnAuthorityDescriptor" (XP.xpickle XP.>*< xpList1 (xpElem "AuthnQueryService" XP.xpickle) XP.>*< XP.xpList (xpElem "AssertionIDRequestService" XP.xpickle) XP.>*< XP.xpList (xpElem "NameIDFormat" XP.xpickle)) XP.>|< xpElem "AttributeAuthorityDescriptor" (XP.xpickle XP.>*< xpList1 (xpElem "AttributeService" XP.xpickle) XP.>*< XP.xpList (xpElem "AssertionIDRequestService" XP.xpickle) XP.>*< XP.xpList (xpElem "NameIDFormat" XP.xpickle) XP.>*< XP.xpList (xpElem "AttributeProfile" XS.xpAnyURI) XP.>*< XP.xpList XP.xpickle) XP.>|< xpElem "PDPDescriptor" (XP.xpickle XP.>*< xpList1 (xpElem "AuthzService" XP.xpickle) XP.>*< XP.xpList (xpElem "AssertionIDRequestService" XP.xpickle) XP.>*< XP.xpList (xpElem "NameIDFormat" XP.xpickle))) -- |§2.3.2.1 data Organization = Organization { organizationAttrs :: Nodes , organizationExtensions :: Extensions , organizationName :: List1 LocalizedName , organizationDisplayName :: List1 LocalizedName , organizationURL :: List1 LocalizedURI } deriving (Eq, Show) instance XP.XmlPickler Organization where xpickle = xpElem "Organization" $ [XP.biCase| ((((a, e), n), d), u) <-> Organization a e n d u|] XP.>$< (XP.xpAnyAttrs XP.>*< XP.xpickle XP.>*< xpList1 (xpElem "OrganizationName" XP.xpickle) XP.>*< xpList1 (xpElem "OrganizationDisplayName" XP.xpickle) XP.>*< xpList1 (xpElem "OrganizationURL" XP.xpickle)) -- |§2.3.2.2 data Contact = ContactPerson { contactType :: ContactType , contactAttrs :: Nodes , contactExtensions :: Extensions , contactCompany :: Maybe XS.String , contactGivenName :: Maybe XS.String , contactSurName :: Maybe XS.String , contactEmailAddress :: [XS.AnyURI] , contactTelephoneNumber :: [XS.String] } deriving (Eq, Show) instance XP.XmlPickler Contact where xpickle = xpElem "ContactPerson" $ [XP.biCase| (((((((t, a), ext), c), g), s), e), tn) <-> ContactPerson t a ext c g s e tn|] XP.>$< (XP.xpAttr "contactType" XP.xpickle XP.>*< XP.xpAnyAttrs XP.>*< XP.xpickle XP.>*< XP.xpOption (xpElem "Company" XS.xpString) XP.>*< XP.xpOption (xpElem "GivenName" XS.xpString) XP.>*< XP.xpOption (xpElem "SurName" XS.xpString) XP.>*< XP.xpList (xpElem "EmailAddress" XS.xpAnyURI) XP.>*< XP.xpList (xpElem "TelephoneNumber" XS.xpString)) data ContactType = ContactTypeTechnical | ContactTypeSupport | ContactTypeAdministrative | ContactTypeBilling | ContactTypeOther deriving (Eq, Enum, Bounded, Show) instance Identifiable XString ContactType where identifier ContactTypeTechnical = "technical" identifier ContactTypeSupport = "support" identifier ContactTypeAdministrative = "administrative" identifier ContactTypeBilling = "billing" identifier ContactTypeOther = "other" instance XP.XmlPickler ContactType where xpickle = xpIdentifier (XP.xpTextDT (XPS.scDT (namespaceURIString ns) "ContactTypeType" [])) "ContactTypeType" -- |§2.3.2.3 data AdditionalMetadataLocation = AdditionalMetadataLocation { additionalMetadataLocationNamespace :: XS.AnyURI , additionalMetadataLocation :: XS.AnyURI } deriving (Eq, Show) instance XP.XmlPickler AdditionalMetadataLocation where xpickle = xpElem "AdditionalMetadataLocation" $ [XP.biCase| (n, l) <-> AdditionalMetadataLocation n l|] XP.>$< (XP.xpAttr "namespace" XS.xpAnyURI XP.>*< XS.xpAnyURI) -- |§2.4.1 data RoleDescriptor = RoleDescriptor { roleDescriptorID :: Maybe XS.ID , roleDescriptorValidUntil :: Maybe XS.DateTime , roleDescriptorCacheDuration :: Maybe XS.Duration , roleDescriptorProtocolSupportEnumeration :: [XS.AnyURI] , roleDescriptorErrorURL :: Maybe XS.AnyURI , roleDescriptorAttrs :: Nodes , roleDescriptorSignature :: Maybe DS.Signature , roleDescriptorExtensions :: Extensions , roleDescriptorKeyDescriptor :: [KeyDescriptor] , roleDescriptorOrganization :: Maybe Organization , roleDescriptorContactPerson :: [Contact] } deriving (Eq, Show) instance XP.XmlPickler RoleDescriptor where xpickle = [XP.biCase| ((((((((((i, vu), cd), ps), eu), a), sig), ext), key), org), cp) <-> RoleDescriptor i vu cd ps eu a sig ext key org cp|] XP.>$< (XP.xpAttrImplied "ID" XS.xpID XP.>*< XP.xpAttrImplied "validUntil" XS.xpDateTime XP.>*< XP.xpAttrImplied "cacheDuration" XS.xpDuration XP.>*< XP.xpAttr "protocolSupportEnumeration" xpAnyURIList XP.>*< XP.xpAttrImplied "errorURL" XS.xpAnyURI XP.>*< XP.xpAnyAttrs XP.>*< XP.xpickle XP.>*< XP.xpickle XP.>*< XP.xpList XP.xpickle XP.>*< XP.xpOption XP.xpickle XP.>*< XP.xpList XP.xpickle) where xpAnyURIList = XP.xpWrapEither ( mapM (maybe (Left "invalid anyURI") Right . URI.parseURIReference) . words , tail . foldr ((.) (' ':) . URI.uriToString id) "" ) $ XP.xpTextDT $ XPS.scDT (namespaceURIString ns) "anyURIListType" [] instance DS.Signable RoleDescriptor where signature' = $(fieldLens 'roleDescriptorSignature) signedID = fold . roleDescriptorID -- |§2.4.1.1 data KeyDescriptor = KeyDescriptor { keyDescriptorUse :: KeyTypes , keyDescriptorKeyInfo :: DS.KeyInfo , keyDescriptorEncryptionMethod :: [XEnc.EncryptionMethod] } deriving (Eq, Show) instance XP.XmlPickler KeyDescriptor where xpickle = xpElem "KeyDescriptor" $ [XP.biCase| ((t, i), m) <-> KeyDescriptor t i m|] XP.>$< (XP.xpDefault KeyTypeBoth (XP.xpAttr "use" XP.xpickle) XP.>*< XP.xpickle XP.>*< XP.xpList (xpElem "EncryptionMethod" XEnc.xpEncryptionMethodType)) data KeyTypes = KeyTypeSigning | KeyTypeEncryption | KeyTypeBoth deriving (Eq, Enum, Bounded, Show) -- |Does the second KeyTypes include the first type of use? keyType :: KeyTypes -> KeyTypes -> Bool keyType _ KeyTypeBoth = True keyType k t = k == t instance Identifiable XString KeyTypes where identifier KeyTypeSigning = "signing" identifier KeyTypeEncryption = "encryption" identifier KeyTypeBoth = "" identifiedValues = [KeyTypeEncryption, KeyTypeSigning] instance XP.XmlPickler KeyTypes where xpickle = xpIdentifier (XP.xpTextDT (XPS.scDT (namespaceURIString ns) "KeyTypes" [])) "KeyTypes" -- |§2.4.2 data SSODescriptor = SSODescriptor { ssoDescriptorArtifactResolutionService :: [IndexedEndpoint] , ssoDescriptorSingleLogoutService :: [Endpoint] , ssoDescriptorManageNameIDService :: [Endpoint] , ssoDescriptorNameIDFormat :: [IdentifiedURI NameIDFormat] } deriving (Eq, Show) instance XP.XmlPickler SSODescriptor where xpickle = [XP.biCase| (((a, s), m), n) <-> SSODescriptor a s m n|] XP.>$< (XP.xpList (xpElem "ArtifactResolutionService" XP.xpickle) XP.>*< XP.xpList (xpElem "SingleLogoutService" XP.xpickle) XP.>*< XP.xpList (xpElem "ManageNameIDService" XP.xpickle) XP.>*< XP.xpList (xpElem "NameIDFormat" XP.xpickle)) -- |§2.4.4.1 data AttributeConsumingService = AttributeConsumingService { attributeConsumingServiceIndex :: XS.UnsignedShort , attributeConsumingServiceIsDefault :: Bool , attributeConsumingServiceServiceName :: List1 LocalizedName , attributeConsumingServiceServiceDescription :: [LocalizedName] , attributeConsumingServiceRequestedAttribute :: List1 RequestedAttribute } deriving (Eq, Show) instance XP.XmlPickler AttributeConsumingService where xpickle = xpElem "AttributeConsumingService" $ [XP.biCase| ((((i, d), sn), sd), ra) <-> AttributeConsumingService i d sn sd ra|] XP.>$< (XP.xpAttr "index" XS.xpUnsignedShort XP.>*< XP.xpDefault False (XP.xpAttr "isDefault" XS.xpBoolean) XP.>*< xpList1 (xpElem "ServiceName" XP.xpickle) XP.>*< XP.xpList (xpElem "ServiceDescription" XP.xpickle) XP.>*< xpList1 XP.xpickle) -- |§2.4.4.1.1 data RequestedAttribute = RequestedAttribute { requestedAttribute :: !SAML.Attribute , requestedAttributeIsRequired :: Bool } deriving (Eq, Show) instance XP.XmlPickler RequestedAttribute where xpickle = xpElem "RequestedAttribute" $ [XP.biCase| (r, a) <-> RequestedAttribute a r|] XP.>$< (XP.xpDefault False (XP.xpAttr "isRequired" XS.xpBoolean) XP.>*< SAML.xpAttributeType)
dylex/hsaml2
SAML2/Metadata/Metadata.hs
apache-2.0
17,930
0
25
3,352
4,145
2,250
1,895
393
1
-- | Allow the defines file to indicate dings that will zero out a section. module Grade.Score.Zeroing (zeroing) where import qualified Text.Trifecta as T import Grade.Types (ExSecCallback(..), SecCallback(..)) data Zeroing a = Zeroed | Earned a deriving (Show) instance Monoid a => Monoid (Zeroing a) where mempty = Earned mempty mappend Zeroed _ = Zeroed mappend _ Zeroed = Zeroed mappend (Earned l) (Earned r) = Earned (l `mappend` r) parseZeroed :: (T.TokenParsing f, Monoid sds) => f () -- ^ How do we parse a zeroizing ding? -> f (sdt,sds) -- ^ What is the underlying ding parser? -> f (Zeroing sdt, sds) parseZeroed pz pd = T.choice [ -- Try parsing a zeroizing form T.try pz *> pure (Zeroed, mempty) , -- Otherwise, invoke the underlying parser (\(a,b) -> (Earned a, b)) <$> pd ] printZeroed :: (sds -> sat -> sdt -> Maybe String) -> sds -> sat -> Zeroing sdt -> Maybe String printZeroed po ss sa r = case r of Zeroed -> Just "Score set to 0" Earned v -> po ss sa v scoreZeroed :: (sds -> sat -> sdt -> Either String Double) -> sds -> sat -> Zeroing sdt -> Either String Double scoreZeroed ug ss sa r = case r of Zeroed -> Right 0.0 Earned r' -> ug ss sa r' zeroing :: (T.TokenParsing f) => f () -> ExSecCallback f -> ExSecCallback f zeroing pz shp = case shp of ExSecCB (SC us up uo ug um) -> ExSecCB (SC us (parseZeroed pz up) (printZeroed uo) (scoreZeroed ug) um)
nwf/grade
lib/Grade/Score/Zeroing.hs
bsd-2-clause
1,713
0
12
599
560
291
269
37
2
{-# LANGUAGE NoImplicitPrelude #-} module Stack.Options.ConfigParser where import Data.Char import Options.Applicative import Options.Applicative.Builder.Extra import Path import Stack.Constants import Stack.Options.BuildMonoidParser import Stack.Options.DockerParser import Stack.Options.GhcBuildParser import Stack.Options.GhcVariantParser import Stack.Options.NixParser import Stack.Options.Utils import Stack.Prelude import Stack.Types.Config import qualified System.FilePath as FilePath -- | Command-line arguments parser for configuration. configOptsParser :: FilePath -> GlobalOptsContext -> Parser ConfigMonoid configOptsParser currentDir hide0 = (\stackRoot workDir buildOpts dockerOpts nixOpts systemGHC installGHC arch ghcVariant ghcBuild jobs includes libs overrideGccPath overrideHpack skipGHCCheck skipMsys localBin setupInfoLocations modifyCodePage allowDifferentUser dumpLogs colorWhen snapLoc -> mempty { configMonoidStackRoot = stackRoot , configMonoidWorkDir = workDir , configMonoidBuildOpts = buildOpts , configMonoidDockerOpts = dockerOpts , configMonoidNixOpts = nixOpts , configMonoidSystemGHC = systemGHC , configMonoidInstallGHC = installGHC , configMonoidSkipGHCCheck = skipGHCCheck , configMonoidArch = arch , configMonoidGHCVariant = ghcVariant , configMonoidGHCBuild = ghcBuild , configMonoidJobs = jobs , configMonoidExtraIncludeDirs = includes , configMonoidExtraLibDirs = libs , configMonoidOverrideGccPath = overrideGccPath , configMonoidOverrideHpack = overrideHpack , configMonoidSkipMsys = skipMsys , configMonoidLocalBinPath = localBin , configMonoidSetupInfoLocations = setupInfoLocations , configMonoidModifyCodePage = modifyCodePage , configMonoidAllowDifferentUser = allowDifferentUser , configMonoidDumpLogs = dumpLogs , configMonoidColorWhen = colorWhen , configMonoidSnapshotLocation = snapLoc }) <$> optionalFirst (absDirOption ( long stackRootOptionName <> metavar (map toUpper stackRootOptionName) <> help ("Absolute path to the global stack root directory " ++ "(Overrides any STACK_ROOT environment variable)") <> hide )) <*> optionalFirst (option (eitherReader (mapLeft showWorkDirError . parseRelDir)) ( long "work-dir" <> metavar "WORK-DIR" <> completer (pathCompleterWith (defaultPathCompleterOpts { pcoAbsolute = False, pcoFileFilter = const False })) <> help ("Relative path of work directory " ++ "(Overrides any STACK_WORK environment variable, default is '.stack-work')") <> hide )) <*> buildOptsMonoidParser hide0 <*> dockerOptsParser True <*> nixOptsParser True <*> firstBoolFlagsNoDefault "system-ghc" "using the system installed GHC (on the PATH) if it is available and its version matches. Disabled by default." hide <*> firstBoolFlagsTrue "install-ghc" "downloading and installing GHC if necessary (can be done manually with stack setup)" hide <*> optionalFirst (strOption ( long "arch" <> metavar "ARCH" <> help "System architecture, e.g. i386, x86_64" <> hide )) <*> optionalFirst (ghcVariantParser (hide0 /= OuterGlobalOpts)) <*> optionalFirst (ghcBuildParser (hide0 /= OuterGlobalOpts)) <*> optionalFirst (option auto ( long "jobs" <> short 'j' <> metavar "JOBS" <> help "Number of concurrent jobs to run" <> hide )) <*> many ((currentDir FilePath.</>) <$> strOption ( long "extra-include-dirs" <> metavar "DIR" <> completer dirCompleter <> help "Extra directories to check for C header files" <> hide )) <*> many ((currentDir FilePath.</>) <$> strOption ( long "extra-lib-dirs" <> metavar "DIR" <> completer dirCompleter <> help "Extra directories to check for libraries" <> hide )) <*> optionalFirst (absFileOption ( long "with-gcc" <> metavar "PATH-TO-GCC" <> help "Use gcc found at PATH-TO-GCC" <> hide )) <*> optionalFirst (strOption ( long "with-hpack" <> metavar "HPACK" <> help "Use HPACK executable (overrides bundled Hpack)" <> hide )) <*> firstBoolFlagsFalse "skip-ghc-check" "skipping the GHC version and architecture check" hide <*> firstBoolFlagsFalse "skip-msys" "skipping the local MSYS installation (Windows only)" hide <*> optionalFirst ((currentDir FilePath.</>) <$> strOption ( long "local-bin-path" <> metavar "DIR" <> completer dirCompleter <> help "Install binaries to DIR" <> hide )) <*> many ( strOption ( long "setup-info-yaml" <> help "Alternate URL or relative / absolute path for stack dependencies" <> metavar "URL" )) <*> firstBoolFlagsTrue "modify-code-page" "setting the codepage to support UTF-8 (Windows only)" hide <*> firstBoolFlagsNoDefault "allow-different-user" ("permission for users other than the owner of the stack root " ++ "directory to use a stack installation (POSIX only) " ++ "(default: true inside Docker, otherwise false)") hide <*> fmap toDumpLogs (firstBoolFlagsNoDefault "dump-logs" "dump the build output logs for local packages to the console (default: dump warning logs)" hide) <*> optionalFirst (option readColorWhen ( long "color" <> long "colour" <> metavar "WHEN" <> completeWith ["always", "never", "auto"] <> help "Specify when to use color in output; WHEN is 'always', \ \'never', or 'auto'. On Windows versions before Windows \ \10, for terminals that do not support color codes, the \ \default is 'never'; color may work on terminals that \ \support color codes" <> hide )) <*> optionalFirst (strOption ( long "snapshot-location-base" <> help "The base location of LTS/Nightly snapshots" <> metavar "URL" )) where hide = hideMods (hide0 /= OuterGlobalOpts) toDumpLogs (First (Just True)) = First (Just DumpAllLogs) toDumpLogs (First (Just False)) = First (Just DumpNoLogs) toDumpLogs (First Nothing) = First Nothing showWorkDirError err = show err ++ "\nNote that --work-dir must be a relative child directory, because work-dirs outside of the package are not supported by Cabal." ++ "\nSee https://github.com/commercialhaskell/stack/issues/2954"
juhp/stack
src/Stack/Options/ConfigParser.hs
bsd-3-clause
7,563
0
41
2,513
1,177
609
568
157
3
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, TypeFamilies, EmptyDataDecls #-} -- | Concurrency for Haste. Includes MVars, forking, Ajax and more. module Haste.Concurrent ( module Haste.Concurrent.Monad, module Ajax, Recv, Send, Inbox, Outbox, MBox, receive, spawn, statefully, (!), (<!), wait ) where import Haste.Concurrent.Monad import Haste.Concurrent.Ajax as Ajax import Haste.Callback -- | Wait for n milliseconds. wait :: Int -> CIO () wait ms = do v <- newEmptyMVar liftIO $ setTimeout' ms $ putMVar v () takeMVar v instance GenericCallback (CIO ()) CIO where type CB (CIO ()) = IO () mkcb toIO m = toIO m mkIOfier _ = return concurrent -- | An MBox is a read/write-only MVar, depending on its first type parameter. -- Used to communicate with server processes. newtype MBox t a = MBox (MVar a) data Recv data Send type Inbox = MBox Recv type Outbox = MBox Send -- | Block until a message arrives in a mailbox, then return it. receive :: MonadConc m => Inbox a -> m a receive (MBox mv) = liftConc $ takeMVar mv -- | Creates a generic process and returns a MBox which may be used to pass -- messages to it. -- While it is possible for a process created using spawn to transmit its -- inbox to someone else, this is a very bad idea; don't do it. spawn :: MonadConc m => (Inbox a -> m ()) -> m (Outbox a) spawn f = do p <- liftConc newEmptyMVar fork $ f (MBox p) return (MBox p) -- | Creates a generic stateful process. This process is a function taking a -- state and an event argument, returning an updated state or Nothing. -- @statefully@ creates a @MBox@ that is used to pass events to the process. -- Whenever a value is written to this MBox, that value is passed to the -- process function together with the function's current state. -- If the process function returns Nothing, the process terminates. -- If it returns a new state, the process again blocks on the event MBox, -- and will use the new state to any future calls to the server function. statefully :: MonadConc m => st -> (st -> evt -> m (Maybe st)) -> m (Outbox evt) statefully initialState handler = do spawn $ loop initialState where loop st p = do mresult <- liftConc (receive p) >>= handler st case mresult of Just st' -> loop st' p _ -> return () -- | Write a value to a MBox. Named after the Erlang message sending operator, -- as both are intended for passing messages to processes. -- This operation does not block until the message is delivered, but returns -- immediately. (!) :: MonadConc m => Outbox a -> a -> m () MBox m ! x = liftConc $ forkIO $ putMVar m x -- | Perform a Client computation, then write its return value to the given -- pipe. Mnemonic: the operator is a combination of <- and !. -- Just like @(!)@, this operation is non-blocking. (<!) :: MonadConc m => Outbox a -> m a -> m () p <! m = do x <- m ; p ! x
joelburget/haste-compiler
libraries/haste-lib/src/Haste/Concurrent.hs
bsd-3-clause
2,957
0
13
668
641
334
307
-1
-1
module Main where import Idris.AbsSyntax import Idris.Core.TT import Idris.ElabDecls import Idris.Main import Idris.ModeCommon import Idris.REPL import IRTS.CodegenOCaml import IRTS.Compiler import System.Environment import System.Exit import Paths_idris_ocaml data Opts = Opts { inputs :: [FilePath], output :: FilePath } showUsage = do putStrLn "Usage: idris-ocaml <ibc-files> [-o <output-file>]" exitWith ExitSuccess getOpts :: IO Opts getOpts = do xs <- getArgs return $ process (Opts [] "a.ml") xs where process opts ("-o":o:xs) = process (opts { output = o }) xs process opts ("--yes-really":xs) = process opts xs -- TODO process opts (x:xs) = process (opts { inputs = x:inputs opts }) xs process opts [] = opts c_main :: Opts -> Idris () c_main opts = do elabPrims loadInputs (inputs opts) Nothing mainProg <- elabMain ir <- compile (Via IBCFormat "ocaml") (output opts) (Just mainProg) runIO $ codegenOCaml ir main :: IO () main = do opts <- getOpts if (null (inputs opts)) then showUsage else runMain (c_main opts)
ziman/idris-ocaml
src/Main.hs
bsd-3-clause
1,202
0
12
335
399
206
193
34
4
module Main where import Nouns import Data.ByteString.Lazy.Char8 (pack) import Data.Char import Data.Maybe import Data.Text (unpack) import Network.HTTP.Types (status200, status404) import Network.Wai import Network.Wai.Handler.Warp (run) import Network.Wai.Middleware.Gzip (gzip, def) import System.Environment import System.Random port_number :: Int port_number = 5002 lastN :: Int -> [a] -> [a] lastN n xs = foldl (const . drop 1) xs (drop n xs) getFirstLetter :: [String] -> Maybe Char getFirstLetter [] = Nothing getFirstLetter (x:_) = Just (head x) getRandomElement :: [String] -> IO String getRandomElement xs = do index <- randomRIO (0, (length xs) - 1) return (xs !! index) generateName :: Maybe Char -> IO String generateName Nothing = getRandomElement prefix generateName initial = getRandomElement $ prefixByLetter (fromJust initial) berrify :: String -> String berrify str | "berry" == lastN 5 str = str | otherwise = str ++ "berry" capitalize :: String -> String capitalize [] = [] capitalize (x:xs) = (toUpper x):xs response :: [String] -> IO String response args = do name <- generateName $ getFirstLetter args adjective <- getRandomElement adjectives return ((capitalize adjective) ++ " " ++ (capitalize (berrify name))) application :: Application application request respond = do let args = map unpack $ pathInfo request let isFavicon = ((args /= []) && (args!!0 == "favicon.ico")) let _status = if isFavicon then status404 else status200 msg <- response args respond $ responseLBS _status [("Content-Type", "text/plain")] (pack (msg ++ "\n")) main :: IO () main = do env <- getEnvironment let port = maybe port_number read $ lookup "PORT" env putStrLn ("Server started at http://127.0.0.1:" ++ (show port)) run port $ gzip def application
nicolasbrugneaux/hack-berry
src/Main.hs
bsd-3-clause
1,848
0
14
354
702
360
342
51
2
{-# LANGUAGE ExtendedDefaultRules #-} {-# LANGUAGE PatternGuards #-} {-# LANGUAGE ViewPatterns #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS -fno-warn-type-defaults #-} -- | Try Haskell! module TryHaskell where import Control.Arrow ((***)) import Control.Applicative ((<$>),(<|>)) import Control.Concurrent import Control.Monad import Control.Monad.Trans import Data.Aeson as Aeson import Data.Bifunctor import Data.ByteString (ByteString) import Data.ByteString.Lazy (fromChunks) import qualified Data.ByteString.Lazy as L (ByteString) import qualified Data.Cache.LRU.IO as LRU import Data.HashMap.Strict (HashMap) import qualified Data.HashMap.Strict as M import Data.Hashable import Data.Map (Map) import qualified Data.Map as Map import Data.Maybe import Data.Monoid import Data.Text (unpack) import qualified Data.Text as S import Data.Text.Encoding (decodeUtf8) import Data.Text.Lazy (Text) import qualified Data.Text.Lazy as T import Data.Time import Lucid import Lucid.Bootstrap import Prelude hiding (div,head) import PureIO (Interrupt(..),Output(..),Input(..),IOException(..)) import Safe import Snap.Core import Snap.Http.Server hiding (Config) import Snap.Util.FileServe import System.Environment (getEnvironment, lookupEnv) import System.Exit import System.IO (stderr, hPutStrLn) import System.Process.Text.Lazy data EvalResult = ErrorResult !Text | SuccessResult !(Text,Text,Text) ![Text] !(Map FilePath String) | GetInputResult ![Text] !(Map FilePath String) deriving (Show,Eq) data Stats = Stats { statsUsers :: !(HashMap ByteString UTCTime) } type Cache = LRU.AtomicLRU (ByteString, ByteString) Value -- | Setup the server threads and state. setupServer :: IO ((MVar Stats,ThreadId), Cache) setupServer = do checkMuEval mCacheLimit <- (readMay =<<) <$> lookupEnv "CACHE_LIMIT" cache <- LRU.newAtomicLRU (mCacheLimit <|> Just 1000) stats <- newMVar (Stats mempty) expire <- forkIO (expireVisitors stats) return ((stats,expire),cache) -- | Start a web server. startServer :: Cache -> MVar Stats -> IO () startServer cache stats = do env <- getEnvironment static <- return "static" let port = maybe 4001 read $ lookup "PORT" env let config = setPort port . setAccessLog ConfigNoLog . setErrorLog ConfigNoLog . setVerbose False httpServe (config defaultConfig) (dispatch static cache stats) -- | Ensure mueval is available and working checkMuEval :: IO () checkMuEval = do result <- mueval False "()" case result of Left err | err /= "()" -> die err _ -> return () where die err = do hPutStrLn stderr ("ERROR: mueval " ++ msg err) exitFailure msg err | T.null err = "failed to start" | otherwise = "startup failure:\n" ++ T.unpack err -- | Dispatch on the routes. dispatch :: FilePath -> Cache -> MVar Stats -> Snap () dispatch static cache stats = route [("/static",serveDirectory static) ,("/eval",eval cache stats) ,("/users",users stats) ,("/",home stats)] -- | Write out the list of current users. users :: MVar Stats -> Snap () users statsv = do stats <- liftIO (readMVar statsv) writeLBS (encode (map (show . hash *** epoch) (M.toList (statsUsers stats)))) where epoch :: UTCTime -> Integer epoch = read . formatTime defaultTimeLocale "%s" -- | Log the current user's visit to the stats table. logVisit :: MVar Stats -> Snap ByteString logVisit stats = do ipHeaderFilter addr <- fmap rqRemoteAddr getRequest now <- liftIO getCurrentTime let updateStats (Stats u) = Stats (M.insert addr now u) liftIO (modifyMVar_ stats (return . updateStats)) return addr -- | Reap visitors that have been inactive for one minute. expireVisitors :: MVar Stats -> IO () expireVisitors stats = forever (do threadDelay (1000 * 1000 * 15) now <- getCurrentTime modifyMVar_ stats (return . Stats . M.filter (not . (>60) . diffUTCTime now) . statsUsers)) -- | Evaluate the given expression. eval :: Cache -> MVar Stats -> Snap () eval cache stats = do mex <- getParam "exp" args <- getParam "args" case mex of Nothing -> error "exp expected" Just ex -> do let key = (ex,fromMaybe "" args) logit ex args liftIO (cachedEval key cache args ex) >>= jsonp where logit ex _ = do ip <- logVisit stats now <- liftIO getCurrentTime liftIO (appendFile "/tmp/tryhaskell-log" (show now ++ " " ++ S.unpack (decodeUtf8 ip) ++ "> " ++ (S.unpack . decodeUtf8) ex ++ "\n")) -- | Read from the cache for the given expression (and context), or -- otherwise generate the JSON. cachedEval :: (Eq k, Ord k) => k -> LRU.AtomicLRU k Value -> Maybe ByteString -> ByteString -> IO Value cachedEval key cache args ex = do mCached <- LRU.lookup key cache case mCached of Just cached -> return cached Nothing -> do o <- case getArgs of Nothing -> muevalToJson ex mempty mempty Just (is,fs) -> muevalToJson ex is fs case o of (Object i) | Just _ <- M.lookup "error" i -> return () _ -> LRU.insert key o cache return o where getArgs = fmap toLazy args >>= decode -- | Output a JSON value, possibly wrapping it in a callback if one -- was requested. jsonp :: Value -> Snap () jsonp o = do mcallback <- getParam "callback" writeLBS (case mcallback of Nothing -> encode o Just c -> toLazy c <> "(" <> encode o <> ");") -- | Evaluate the given expression and return the result as a JSON value. muevalToJson :: MonadIO m => ByteString -> [String] -> Map FilePath String -> m Value muevalToJson ex is fs = do result <- liftIO (muevalOrType (unpack (decodeUtf8 ex)) is fs) case result of ErrorResult "can't find file: Imports.hs\n" -> muevalToJson ex is fs ErrorResult e -> return (codify (ErrorResult (if e == "" then helpfulMsg else e))) _ -> return (codify result) where helpfulMsg = "No result, evaluator might've been \ \killed due to heavy traffic. Retry?" codify result = Aeson.object (case result of ErrorResult err -> [("error" .= err)] SuccessResult (expr,typ,value') stdouts files -> [("success" .= Aeson.object [("value" .= value') ,("expr" .= expr) ,("type" .= typ) ,("stdout" .= stdouts) ,("files" .= files)])] GetInputResult stdouts files -> [("stdout" .= stdouts) ,("files" .= files)]) -- | Strict bystring to lazy. toLazy :: ByteString -> L.ByteString toLazy = fromChunks . return -- | Try to evaluate the given expression. If there's a mueval error -- (i.e. a compile error), then try just getting the type of the -- expression. muevalOrType :: String -> [String] -> Map FilePath String -> IO EvalResult muevalOrType e is fs = do typeResult <- mueval True e case typeResult of Left err -> return (ErrorResult err) Right (expr,typ,_) -> if T.isPrefixOf "IO " typ then muevalIO e is fs else do evalResult <- mueval False e case evalResult of Left err -> if T.isPrefixOf "No instance for" err || T.isPrefixOf "Ambiguous " err then return (SuccessResult (expr,typ,"") mempty fs) else return (ErrorResult err) Right (_,_,val) -> return (SuccessResult (expr,typ,val) mempty fs) -- | Try to evaluate the expression as a (pure) IO action, if it type -- checks and evaluates, then we're going to enter a potential -- (referentially transparent) back-and-forth between the server and -- the client. -- -- It handles stdin/stdout and files. muevalIO :: String -> [String] -> Map FilePath String -> IO EvalResult muevalIO e is fs = do result <- mueval False ("runTryHaskellIO " ++ show (convert (Input is fs)) ++ " (" ++ e ++ ")") case result of Left err -> return (ErrorResult err) Right (_,_,readMay . T.unpack -> Just r) -> ioResult e (bimap (second oconvert) (second oconvert) r) _ -> return (ErrorResult "Problem running IO.") where convert (Input os fs') = (os,Map.toList fs') oconvert (os,fs') = Output os (Map.fromList fs') -- | Extract an eval result from the IO reply. ioResult :: String -> Either (Interrupt,Output) (String,Output) -> IO EvalResult ioResult e r = case r of Left i -> case i of (InterruptException ex,_) -> return (ErrorResult (case ex of UserError err -> T.pack err FileNotFound fp -> T.pack ("File not found: " <> fp) DirectoryNotFound fp -> T.pack ("Directory not found: " <> fp))) (InterruptStdin,Output os fs) -> return (GetInputResult (map T.pack os) fs) Right (value',Output os fs) -> do typ <- mueval True e return (case typ of Left err -> ErrorResult err Right (_,iotyp,_) -> SuccessResult (T.pack e,iotyp,T.pack value') (map T.pack os) fs) -- | Evaluate the given expression and return either an error or an -- (expr,type,value) triple. mueval :: Bool -> String -> IO (Either Text (Text,Text,Text)) mueval typeOnly e = do env <- getEnvironment importsfp <- return "Imports.hs" let timeout = maybe "1" id $ lookup "MUEVAL_TIMEOUT" env options = ["-i","-t",timeout,"--expression",e] ++ ["--no-imports","-l",importsfp] ++ ["--type-only" | typeOnly] (status,out,err) <- readProcessWithExitCode "mueval" options "" case status of ExitSuccess -> case T.lines out of [e',typ,value'] | T.pack e == e' -> return (Right (T.pack e,typ,value')) _ -> do appendFile "/tmp/tryhaskell-log" (e ++ " -> " ++ show out ++ " (bad output)" ++ "\n") return (Left ("Unable to get type and value of expression: " <> T.pack e)) ExitFailure{} -> case T.lines out of [e',_typ,value'] | T.pack e == e' -> return (Left value') [e',_typ] | T.pack e == e' -> return (Left "Evaluation killed!") _ -> return (Left (out <> if out == "" then err <> " " <> T.pack (show status) else "")) -- | The home page. home :: MVar Stats -> Snap () home stats = do void (logVisit stats) writeLazyText (renderText (html_ (do head_ headContent body_ bodyContent))) where headContent = do title_ "Try Haskell! An interactive tutorial in your browser" meta_ [charset_ "utf-8"] css "//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" css "/static/css/tryhaskell.css" css "//fonts.googleapis.com/css?family=Merriweather" css url = link_ [rel_ "stylesheet",type_ "text/css",href_ url] -- | Content of the body. bodyContent :: Html () bodyContent = do container_ (row_ (span12_ (do bodyUsers bodyHeader))) warningArea consoleArea bodyFooter scripts -- | The active users display. bodyUsers :: Html () bodyUsers = div_ [class_ "active-users"] (div_ "Active users") -- | The header. bodyHeader :: Html () bodyHeader = div_ [class_ "haskell-icon-container"] (a_ [href_ "/"] (table_ (tr_ (do td_ (p_ [class_ "haskell-icon"] mempty) td_ [class_ "try-haskell"] "Try Haskell")))) -- | An area for warnings (e.g. cookie warning) warningArea :: Html () warningArea = div_ [class_ "warnings"] (container_ (row_ (do noscript_ (span6_ [id_ "cookie-warning"] (div_ [class_ "alert alert-error"] "JavaScript is required. Please enable it.")) span6_ [style_ "display:none",id_ "cookie-warning"] (div_ [class_ "alert alert-error"] "Cookies are required. Please enable them.") span6_ [style_ "display:none",id_ "storage-warning"] (div_ [class_ "alert alert-error"] "Local storage is required. Please enable it.")))) -- | The white area in the middle. consoleArea :: Html () consoleArea = div_ [class_ "console"] (container_ (row_ (do span6_ [id_ "console"] mempty span6_ [id_ "guide"] mempty))) -- | The footer with links and such. bodyFooter :: Html () bodyFooter = footer_ (container_ (row_ (span12_ (p_ [class_ "muted credit"] links)))) where links = do "Try " a_ [href_ "https://haskell-lang.org/"] "Haskell" " in your browser! " "An interactive tutorial by " a_ [href_ "http://chrisdone.com"] "Chris Done" -- | Scripts; jquery, console, tryhaskell, ga, the usual. scripts :: Html () scripts = do script_ [src_ "//code.jquery.com/jquery-2.0.3.min.js"] "" script_ [src_ "/static/js/jquery.console.js"] "" script_ [src_ "/static/js/tryhaskell.js"] "" script_ [src_ "/static/js/tryhaskell.pages.js"] "" script_ "var gaJsHost = ((\"https:\" == document.location.protocol) ? \"https://ssl.\" : \"http://www.\");\ \document.write(unescape(\"%3Cscript src='\" + gaJsHost + \"google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E\"));" script_ "try {\ \var pageTracker2 = _gat._getTracker(\"UA-7443395-14\");\ \pageTracker2._setDomainName(\"none\");\ \pageTracker2._setAllowLinker(true);\ \pageTracker2._trackPageview(location.pathname + location.search + location.hash);\ \window.ga_tracker = pageTracker2;\ \} catch(err) {}"
chrisdone/tryhaskell
src/TryHaskell.hs
bsd-3-clause
15,385
0
22
5,126
4,070
2,048
2,022
-1
-1
module HVG.SVGState where import Text.Printf import Data.List import Control.Monad import Debug.Trace import HVG.Type import HVG.Geometry data SVGState = SVGState { svgTrans :: Trans , svgCursor :: Pos } initSVGState :: SVGState initSVGState = SVGState identityTrans (Pos 0 0) setTr :: Trans -> Builder info SVGState draw () setTr trans = modifyStructState $ \ctx -> ctx{svgTrans = trans} appTr :: Trans -> Builder info SVGState draw () appTr trans = modifyStructState $ \ctx -> ctx{svgTrans = appTrans (svgTrans ctx) trans} getTr :: Builder info SVGState draw Trans getTr = svgTrans <$> getStructState setCur :: Pos -> Builder info SVGState draw () setCur pos = modifyStructState $ \ctx -> ctx{svgCursor = pos} getCur :: Builder info SVGState draw Pos getCur = svgCursor <$> getStructState -------------------- type SVGDrawing = [Contour] type ContourDrawing = [Path] data PathDrawing = PathDrawing {-# UNPACK #-} !Pos -- begin pos [Segment] -- each seg without begin instance Monoid PathDrawing where mempty = PathDrawing (Pos 0 0) [] --mempty = PathDrawing (appTrans tr (Pos 0 0)) [] PathDrawing begin1 segs1 `mappend` PathDrawing begin2 segs2 = PathDrawing begin1 (segs1 ++ segs2) newtype Contour = Contour [Path] data Path = Path {-# UNPACK #-} !Pos [Segment] data Segment = LineSeg {-# UNPACK #-} !Pos | BezierSeg {-# UNPACK #-} !Pos {-# UNPACK #-} !Pos {-# UNPACK #-} !Pos deriving Show segmentCommand :: Segment -> String segmentCommand (LineSeg p) = printf "L %f" p segmentCommand (BezierSeg c1 c2 p) = printf "C %f %f %f" c1 c2 p pathCommand :: Path -> String pathCommand path@(Path beginPos segs) = printf "M %f\n " beginPos ++ pathCommandHalf path pathCommandHalf :: Path -> String pathCommandHalf (Path _ segs) = intercalate "\n " $ map segmentCommand segs contourCommand :: Contour -> String contourCommand (Contour []) = "" contourCommand (Contour (p:ps)) = pathCommand p ++ join (map (\hp -> ' ' : pathCommandHalf hp) ps) ++ " Z" svgCommand :: SVGDrawing -> String svgCommand [] = "" svgCommand cs = "<path d=\"\n " ++ intercalate "\n\n " (map contourCommand cs) ++ "\n\" fill-rule=\"evenodd\" fill=\"green\" />" instance TransAppable Segment where appTrans trans (LineSeg p) = LineSeg (appTrans trans p) appTrans trans (BezierSeg c1 c2 p) = BezierSeg (appTrans trans c1) (appTrans trans c2) (appTrans trans p) appInvTrans trans (LineSeg p) = LineSeg (appInvTrans trans p) appInvTrans trans (BezierSeg c1 c2 p) = BezierSeg (appInvTrans trans c1) (appInvTrans trans c2) (appInvTrans trans p) contour :: Builder info SVGState ContourDrawing () -> Builder info SVGState SVGDrawing () contour buildContour = do ctx <- getStructState appendAgingState [Contour (fst $ execBuilder buildContour ctx)] pathMightReverse :: (Path -> Path) -> Pos -> Builder info SVGState PathDrawing () -> Builder info SVGState ContourDrawing () pathMightReverse rev beginPos buildPath = local $ do appTr $ transition beginPos ctx <- getStructState tr <- getTr let PathDrawing beginPos segs = fst $ execBuilder buildPath ctx appendAgingState [rev $ Path (appTrans tr beginPos) segs] path :: Pos -> Builder info SVGState PathDrawing () -> Builder info SVGState ContourDrawing () path = pathMightReverse id p :: Double -> Double -> Builder info SVGState PathDrawing () -> Builder info SVGState ContourDrawing () p x y = path (Pos x y) rpath :: Pos -> Builder info SVGState PathDrawing () -> Builder info SVGState ContourDrawing () rpath = pathMightReverse reversePath rp :: Double -> Double -> Builder info SVGState PathDrawing () -> Builder info SVGState ContourDrawing () rp x y = rpath (Pos x y) reversePath :: Path -> Path reversePath (Path beginPos segs) = go beginPos segs [] where go beginPos segs trailing = case segs of [] -> Path beginPos trailing (LineSeg endPos : segs) -> go endPos segs (LineSeg beginPos : trailing) (BezierSeg c1 c2 endPos : segs) -> go endPos segs (BezierSeg c2 c1 beginPos : trailing) line :: Pos -> Builder info SVGState PathDrawing () line pos = do tr <- getTr appendAgingState $ PathDrawing undefined [appTrans tr (LineSeg pos)] appTr $ transition pos l :: Double -> Double -> Builder info SVGState PathDrawing () l x y = line (Pos x y) bezier :: Pos -> Pos -> Pos -> Builder info SVGState PathDrawing () bezier c1 c2 pos = do tr <- getTr appendAgingState $ PathDrawing undefined [appTrans tr (BezierSeg c1 c2 pos)] appTr $ transition pos b :: Double -> Double -> Double -> Double -> Double -> Double -> Builder info SVGState PathDrawing () b x1 y1 x2 y2 x y = bezier (Pos x1 y1) (Pos x2 y2) (Pos x y) arc :: Pos -> Angle -> Builder info SVGState PathDrawing () arc endPos angle = do tr <- getTr let beginPos = Pos 0 0 arcSegs = gen (abs angle) beginPos endPos [] where radius' = distance beginPos endPos / 2 / sin (unRad angle / 2) radius = trace ("radius = " ++ show radius') radius' stringRadiusTurn = if unRad angle > 0 then turnRightDis else turnLeftDis --centerPos' = ((radius * cos (unRad angle / 2)) `scaleDis` stringRadiusTurn (unitDis $ dis endPos beginPos)) `movePos` midPos beginPos endPos --centerPos' = ((radius * cos (unRad angle / 2)) `scaleDis` turnRightDis (unitDis $ dis endPos beginPos)) `movePos` midPos beginPos endPos centerPos' = ((radius * cos (unRad angle / 2)) `scaleDis` turnLeftDis (unitDis $ dis endPos beginPos)) `movePos` midPos beginPos endPos centerPos = trace ("center=" ++ show centerPos') centerPos' -- <circle cx="19.3" cy="15.7" r="1" fill="red"/> gen angle beginPos endPos laterSegs | unDeg angle > 45 --, let sepPos' = stringRadiusTurn (scaleDis radius $ unitDis $ dis beginPos endPos) `movePos` centerPos , let sepPos = turnLeftDis (scaleDis radius $ unitDis $ dis beginPos endPos) `movePos` centerPos --, let sepPos = trace ("sepPos = " ++ show sepPos') sepPos' , let halfAngle = angle / 2 = gen halfAngle beginPos sepPos (gen halfAngle sepPos endPos laterSegs) | otherwise , let stringDir' = unitDis (dis beginPos endPos) , let stringDir = trace ("stringDir=" ++ show stringDir') stringDir' --, let radiusDir = stringRadiusTurn stringDir , let radiusDir' = turnLeftDis stringDir , let radiusDir = trace ("radiusDir=" ++ show radiusDir') radiusDir' , let rRefScale' = cos (unRad angle / 2) , let sRefScale' = sin (unRad angle / 2) , let rRefScale = trace ("rRefScale=" ++ show rRefScale') rRefScale' , let sRefScale = trace ("sRefScale=" ++ show sRefScale') sRefScale' , let rShiftScale' = (4 - rRefScale) / 3 * radius , let sShiftScale' = (1 - rRefScale) * (3 - rRefScale) / (3 * sRefScale) * radius , let rShiftScale = trace ("rShiftScale=" ++ show rShiftScale') rShiftScale' , let sShiftScale = trace ("sShiftScale=" ++ show sShiftScale') sShiftScale' , let rShift = rShiftScale `scaleDis` radiusDir , let sShift = sShiftScale `scaleDis` stringDir , let c0' = rShift `movePos` centerPos , let c0 = trace ("c0=" ++ show c0') c0' , let c1 = (revDis sShift `movePos` c0) , let c2 = (sShift `movePos` c0) = BezierSeg c1 c2 endPos : laterSegs appendAgingState $ PathDrawing undefined (map (appTrans tr) arcSegs) appTr $ transition endPos a :: Double -> Double -> Double -> Builder info SVGState PathDrawing () a x y deg = arc (Pos x y) (Deg deg) -- class TransAppable a => IsSegment a where -- segCmds :: a -> String -- data Seg = forall seg. IsSegment seg => Seg seg -- -- newtype SegPos = SegPosData {unSegPos :: Pos} deriving TransAppable -- pattern SegPos x y = SegPosData (Pos x y) -- -- instance PrintfArg SegPos where -- formatArg (SegPos x y) fmt suffix = formatArg x fmt $ "," ++ formatArg y fmt suffix -- -- data CloseSeg = CloseSeg -- instance TransAppable CloseSeg where -- appTrans _ _ = CloseSeg -- appInvTrans _ _ = CloseSeg -- instance IsSegment CloseSeg where -- segCmds _ = "Z" -- -- newtype BeginSeg = BeginSeg SegPos -- pattern BeginSegPos x y = BeginSeg (SegPos x y) -- instance TransAppable BeginSeg where -- appTrans trans (BeginSeg pos) = BeginSeg $ appTrans trans pos -- appInvTrans trans (BeginSeg pos) = BeginSeg $ appInvTrans trans pos -- instance IsSegment BeginSeg where -- segCmds (BeginSeg pos) = printf "M %f" pos -- -- newtype LineSeg = LineSeg SegPos -- pattern LineSegPos x y = LineSeg (SegPos x y) -- instance TransAppable LineSeg where -- appTrans trans (LineSeg pos) = LineSeg $ appTrans trans pos -- appInvTrans trans (LineSeg pos) = LineSeg $ appInvTrans trans pos -- instance IsSegment LineSeg where -- segCmds (LineSeg pos) = printf "L %f" pos -- -- data BezierSeg = BezierSeg -- {-# UNPACK #-} !SegPos -- {-# UNPACK #-} !SegPos -- {-# UNPACK #-} !SegPos -- pattern BezierSegPos x1 y1 x2 y2 x y = BezierSeg -- (SegPos x1 y1) -- (SegPos x2 y2) -- (SegPos x y) -- instance TransAppable BezierSeg where -- appTrans trans (BezierSeg c1 c2 pos) = -- BezierSeg (appTrans trans c1) (appTrans trans c2) (appTrans trans pos) -- appInvTrans trans (BezierSeg c1 c2 pos) = -- BezierSeg (appInvTrans trans c1) (appInvTrans trans c2) (appInvTrans trans pos) -- instance IsSegment BezierSeg where -- segCmds (BezierSeg c1 c2 pos) = printf "C %f %f %f" c1 c2 pos -- -- data ArcSeg = ArcSeg [BezierSeg] -- arcSeg :: SegPos -> SegPos -> Angle -> ArcSeg -- arcSeg (SegPosData beginPos) (SegPosData endPos) angle = ArcSeg (gen (abs angle) beginPos endPos []) where -- radius' = distance beginPos endPos / 2 / sin (unRad angle / 2) -- radius = trace ("radius = " ++ show radius') radius' -- -- stringRadiusTurn = if unRad angle > 0 then turnRightDis else turnLeftDis -- -- --centerPos' = ((radius * cos (unRad angle / 2)) `scaleDis` stringRadiusTurn (unitDis $ dis endPos beginPos)) `movePos` midPos beginPos endPos -- --centerPos' = ((radius * cos (unRad angle / 2)) `scaleDis` turnRightDis (unitDis $ dis endPos beginPos)) `movePos` midPos beginPos endPos -- centerPos' = ((radius * cos (unRad angle / 2)) `scaleDis` turnLeftDis (unitDis $ dis endPos beginPos)) `movePos` midPos beginPos endPos -- centerPos = trace ("center=" ++ show centerPos') centerPos' -- -- -- <circle cx="19.3" cy="15.7" r="1" fill="red"/> -- gen angle beginPos endPos laterSegs -- | unDeg angle > 45 -- --, let sepPos' = stringRadiusTurn (scaleDis radius $ unitDis $ dis beginPos endPos) `movePos` centerPos -- , let sepPos = turnLeftDis (scaleDis radius $ unitDis $ dis beginPos endPos) `movePos` centerPos -- --, let sepPos = trace ("sepPos = " ++ show sepPos') sepPos' -- , let halfAngle = angle / 2 -- = gen halfAngle beginPos sepPos (gen halfAngle sepPos endPos laterSegs) -- | otherwise -- , let stringDir' = unitDis (dis beginPos endPos) -- , let stringDir = trace ("stringDir=" ++ show stringDir') stringDir' -- --, let radiusDir = stringRadiusTurn stringDir -- , let radiusDir' = turnLeftDis stringDir -- , let radiusDir = trace ("radiusDir=" ++ show radiusDir') radiusDir' -- , let rRefScale' = cos (unRad angle / 2) -- , let sRefScale' = sin (unRad angle / 2) -- , let rRefScale = trace ("rRefScale=" ++ show rRefScale') rRefScale' -- , let sRefScale = trace ("sRefScale=" ++ show sRefScale') sRefScale' -- , let rShiftScale' = (4 - rRefScale) / 3 * radius -- , let sShiftScale' = (1 - rRefScale) * (3 - rRefScale) / (3 * sRefScale) * radius -- , let rShiftScale = trace ("rShiftScale=" ++ show rShiftScale') rShiftScale' -- , let sShiftScale = trace ("sShiftScale=" ++ show sShiftScale') sShiftScale' -- , let rShift = rShiftScale `scaleDis` radiusDir -- , let sShift = sShiftScale `scaleDis` stringDir -- , let c0' = rShift `movePos` centerPos -- , let c0 = trace ("c0=" ++ show c0') c0' -- , let c1 = SegPosData (revDis sShift `movePos` c0) -- , let c2 = SegPosData (sShift `movePos` c0) -- = BezierSeg c1 c2 (SegPosData endPos) : laterSegs -- instance TransAppable ArcSeg where -- appTrans trans (ArcSeg bs) = ArcSeg $ map (appTrans trans) bs -- appInvTrans trans (ArcSeg bs) = ArcSeg $ map (appInvTrans trans) bs -- instance IsSegment ArcSeg where -- segCmds (ArcSeg bs) = intercalate "\n" (map segCmds bs)
CindyLinz/Haskell-HVG
src/HVG/SVGState.hs
bsd-3-clause
12,302
0
21
2,488
2,657
1,379
1,278
-1
-1
{-# LANGUAGE PatternGuards #-} module Idris.DSL where import Data.Generics.Uniplate.Data (transform) import Idris.AbsSyntax import Idris.Core.TT import Idris.Core.Evaluate import Control.Monad.State.Strict import Debug.Trace debindApp :: SyntaxInfo -> PTerm -> PTerm debindApp syn t = debind (dsl_bind (dsl_info syn)) t dslify :: SyntaxInfo -> IState -> PTerm -> PTerm dslify syn i = transform dslifyApp where dslifyApp (PApp fc (PRef _ f) [a]) | [d] <- lookupCtxt f (idris_dsls i) = desugar (syn { dsl_info = d }) i (getTm a) dslifyApp t = t desugar :: SyntaxInfo -> IState -> PTerm -> PTerm desugar syn i t = let t' = expandSugar (dsl_info syn) t in dslify syn i t' mkTTName :: FC -> Name -> PTerm mkTTName fc n = let mkList fc [] = PRef fc (sNS (sUN "Nil") ["List", "Prelude"]) mkList fc (x:xs) = PApp fc (PRef fc (sNS (sUN "::") ["List", "Prelude"])) [ pexp (stringC x) , pexp (mkList fc xs)] stringC = PConstant fc . Str . str intC = PConstant fc . I reflm n = sNS (sUN n) ["Reflection", "Language"] in case n of UN nm -> PApp fc (PRef fc (reflm "UN")) [ pexp (stringC nm)] NS nm ns -> PApp fc (PRef fc (reflm "NS")) [ pexp (mkTTName fc nm) , pexp (mkList fc ns)] MN i nm -> PApp fc (PRef fc (reflm "MN")) [ pexp (intC i) , pexp (stringC nm)] otherwise -> PRef fc $ reflm "NErased" expandSugar :: DSL -> PTerm -> PTerm expandSugar dsl (PLam fc n nfc ty tm) | Just lam <- dsl_lambda dsl = let sc = PApp fc lam [ pexp (mkTTName fc n) , pexp (var dsl n tm 0)] in expandSugar dsl sc expandSugar dsl (PLam fc n nfc ty tm) = PLam fc n nfc (expandSugar dsl ty) (expandSugar dsl tm) expandSugar dsl (PLet fc n nfc ty v tm) | Just letb <- dsl_let dsl = let sc = PApp (fileFC "(dsl)") letb [ pexp (mkTTName fc n) , pexp v , pexp (var dsl n tm 0)] in expandSugar dsl sc expandSugar dsl (PLet fc n nfc ty v tm) = PLet fc n nfc (expandSugar dsl ty) (expandSugar dsl v) (expandSugar dsl tm) expandSugar dsl (PPi p n fc ty tm) | Just pi <- dsl_pi dsl = let sc = PApp (fileFC "(dsl)") pi [ pexp (mkTTName (fileFC "(dsl)") n) , pexp ty , pexp (var dsl n tm 0)] in expandSugar dsl sc expandSugar dsl (PPi p n fc ty tm) = PPi p n fc (expandSugar dsl ty) (expandSugar dsl tm) expandSugar dsl (PApp fc t args) = PApp fc (expandSugar dsl t) (map (fmap (expandSugar dsl)) args) expandSugar dsl (PAppBind fc t args) = PAppBind fc (expandSugar dsl t) (map (fmap (expandSugar dsl)) args) expandSugar dsl (PCase fc s opts) = PCase fc (expandSugar dsl s) (map (pmap (expandSugar dsl)) opts) expandSugar dsl (PIfThenElse fc c t f) = PApp fc (PRef NoFC (sUN "ifThenElse")) [ PExp 0 [] (sMN 0 "condition") $ expandSugar dsl c , PExp 0 [] (sMN 0 "whenTrue") $ expandSugar dsl t , PExp 0 [] (sMN 0 "whenFalse") $ expandSugar dsl f ] expandSugar dsl (PPair fc p l r) = PPair fc p (expandSugar dsl l) (expandSugar dsl r) expandSugar dsl (PDPair fc p l t r) = PDPair fc p (expandSugar dsl l) (expandSugar dsl t) (expandSugar dsl r) expandSugar dsl (PAlternative a as) = PAlternative a (map (expandSugar dsl) as) expandSugar dsl (PHidden t) = PHidden (expandSugar dsl t) expandSugar dsl (PNoImplicits t) = PNoImplicits (expandSugar dsl t) expandSugar dsl (PUnifyLog t) = PUnifyLog (expandSugar dsl t) expandSugar dsl (PDisamb ns t) = PDisamb ns (expandSugar dsl t) expandSugar dsl (PReturn fc) = dsl_return dsl expandSugar dsl (PRewrite fc r t ty) = PRewrite fc r (expandSugar dsl t) ty expandSugar dsl (PGoal fc r n sc) = PGoal fc (expandSugar dsl r) n (expandSugar dsl sc) expandSugar dsl (PDoBlock ds) = expandSugar dsl $ debind (dsl_bind dsl) (block (dsl_bind dsl) ds) where block b [DoExp fc tm] = tm block b [a] = PElabError (Msg "Last statement in do block must be an expression") block b (DoBind fc n nfc tm : rest) = PApp fc b [pexp tm, pexp (PLam fc n nfc Placeholder (block b rest))] block b (DoBindP fc p tm alts : rest) = PApp fc b [pexp tm, pexp (PLam fc (sMN 0 "bpat") NoFC Placeholder (PCase fc (PRef fc (sMN 0 "bpat")) ((p, block b rest) : alts)))] block b (DoLet fc n nfc ty tm : rest) = PLet fc n nfc ty tm (block b rest) block b (DoLetP fc p tm : rest) = PCase fc tm [(p, block b rest)] block b (DoExp fc tm : rest) = PApp fc b [pexp tm, pexp (PLam fc (sMN 0 "bindx") NoFC Placeholder (block b rest))] block b _ = PElabError (Msg "Invalid statement in do block") expandSugar dsl (PIdiom fc e) = expandSugar dsl $ unIdiom (dsl_apply dsl) (dsl_pure dsl) fc e expandSugar dsl (PRunElab fc tm) = PRunElab fc $ expandSugar dsl tm expandSugar dsl t = t -- | Replace DSL-bound variable in a term var :: DSL -> Name -> PTerm -> Int -> PTerm var dsl n t i = v' i t where v' i (PRef fc x) | x == n = case dsl_var dsl of Nothing -> PElabError (Msg "No 'variable' defined in dsl") Just v -> PApp fc v [pexp (mkVar fc i)] v' i (PLam fc n nfc ty sc) | Nothing <- dsl_lambda dsl = PLam fc n nfc ty (v' i sc) | otherwise = PLam fc n nfc (v' i ty) (v' (i + 1) sc) v' i (PLet fc n nfc ty val sc) | Nothing <- dsl_let dsl = PLet fc n nfc (v' i ty) (v' i val) (v' i sc) | otherwise = PLet fc n nfc (v' i ty) (v' i val) (v' (i + 1) sc) v' i (PPi p n fc ty sc) | Nothing <- dsl_pi dsl = PPi p n fc (v' i ty) (v' i sc) | otherwise = PPi p n fc (v' i ty) (v' (i+1) sc) v' i (PTyped l r) = PTyped (v' i l) (v' i r) v' i (PApp f x as) = PApp f (v' i x) (fmap (fmap (v' i)) as) v' i (PCase f t as) = PCase f (v' i t) (fmap (pmap (v' i)) as) v' i (PPair f p l r) = PPair f p (v' i l) (v' i r) v' i (PDPair f p l t r) = PDPair f p (v' i l) (v' i t) (v' i r) v' i (PAlternative a as) = PAlternative a $ map (v' i) as v' i (PHidden t) = PHidden (v' i t) v' i (PIdiom f t) = PIdiom f (v' i t) v' i (PDoBlock ds) = PDoBlock (map (fmap (v' i)) ds) v' i (PNoImplicits t) = PNoImplicits (v' i t) v' i t = t mkVar fc 0 = case index_first dsl of Nothing -> PElabError (Msg "No index_first defined") Just f -> setFC fc f mkVar fc n = case index_next dsl of Nothing -> PElabError (Msg "No index_next defined") Just f -> PApp fc f [pexp (mkVar fc (n-1))] setFC fc (PRef _ n) = PRef fc n setFC fc (PApp _ f xs) = PApp fc (setFC fc f) (map (fmap (setFC fc)) xs) setFC fc t = t unIdiom :: PTerm -> PTerm -> FC -> PTerm -> PTerm unIdiom ap pure fc e@(PApp _ _ _) = let f = getFn e in mkap (getFn e) where getFn (PApp fc f args) = (PApp fc pure [pexp f], args) getFn f = (f, []) mkap (f, []) = f mkap (f, a:as) = mkap (PApp fc ap [pexp f, a], as) unIdiom ap pure fc e = PApp fc pure [pexp e] debind :: PTerm -> PTerm -> PTerm -- For every arg which is an AppBind, lift it out debind b tm = let (tm', (bs, _)) = runState (db' tm) ([], 0) in bindAll (reverse bs) tm' where db' :: PTerm -> State ([(Name, FC, PTerm)], Int) PTerm db' (PAppBind _ (PApp fc t args) []) = db' (PAppBind fc t args) db' (PAppBind fc t args) = do args' <- dbs args (bs, n) <- get let nm = sUN ("_bindApp" ++ show n) put ((nm, fc, PApp fc t args') : bs, n+1) return (PRef fc nm) db' (PApp fc t args) = do t' <- db' t args' <- mapM dbArg args return (PApp fc t' args') db' (PLam fc n nfc ty sc) = return (PLam fc n nfc ty (debind b sc)) db' (PLet fc n nfc ty v sc) = do v' <- db' v return (PLet fc n nfc ty v' (debind b sc)) db' (PCase fc s opts) = do s' <- db' s return (PCase fc s' (map (pmap (debind b)) opts)) db' (PPair fc p l r) = do l' <- db' l r' <- db' r return (PPair fc p l' r') db' (PDPair fc p l t r) = do l' <- db' l r' <- db' r return (PDPair fc p l' t r') db' (PRunElab fc t) = fmap (PRunElab fc) (db' t) db' t = return t dbArg a = do t' <- db' (getTm a) return (a { getTm = t' }) dbs [] = return [] dbs (a : as) = do let t = getTm a t' <- db' t as' <- dbs as return (a { getTm = t' } : as') bindAll [] tm = tm bindAll ((n, fc, t) : bs) tm = PApp fc b [pexp t, pexp (PLam fc n NoFC Placeholder (bindAll bs tm))]
BartAdv/Idris-dev
src/Idris/DSL.hs
bsd-3-clause
9,471
0
17
3,478
4,490
2,196
2,294
187
21
module Utils.THExpander.Types where data Env = Env {_envType :: EnvType, _ignoredFiles :: [FilePath], --relative to dirToExpand paths of ignored files _ignoredDirs :: [FilePath], --relative to dirToExpand paths of ignored dirs _dirsNotToCopy :: [FilePath], --relative to dirToExpand paths of dirs that should not be copied to expansion dir _thModules :: [String], _dirToExpand :: String, _expandTo :: String, _qualifyAs :: [(String, String)]} deriving (Eq, Show) data EnvType = Stack | Cabal | Plain deriving (Eq, Show)
AnkalagonBlack/th-expander
src/Utils/THExpander/Types.hs
bsd-3-clause
567
12
10
121
135
85
50
10
0
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} ----------------------------------------------------------------------------- -- | -- Module : Distribution.Compiler -- Copyright : Isaac Jones 2003-2004 -- License : BSD3 -- -- Maintainer : [email protected] -- Portability : portable -- -- This has an enumeration of the various compilers that Cabal knows about. It -- also specifies the default compiler. Sadly you'll often see code that does -- case analysis on this compiler flavour enumeration like: -- -- > case compilerFlavor comp of -- > GHC -> GHC.getInstalledPackages verbosity packageDb progconf -- > JHC -> JHC.getInstalledPackages verbosity packageDb progconf -- -- Obviously it would be better to use the proper 'Compiler' abstraction -- because that would keep all the compiler-specific code together. -- Unfortunately we cannot make this change yet without breaking the -- 'UserHooks' api, which would break all custom @Setup.hs@ files, so for the -- moment we just have to live with this deficiency. If you're interested, see -- ticket #57. module Distribution.Compiler ( -- * Compiler flavor CompilerFlavor(..), buildCompilerId, buildCompilerFlavor, defaultCompilerFlavor, parseCompilerFlavorCompat, -- * Compiler id CompilerId(..), -- * Compiler info CompilerInfo(..), unknownCompilerInfo, AbiTag(..), abiTagString ) where import Distribution.Compat.Binary (Binary) import Data.Data (Data) import Data.Typeable (Typeable) import Data.Maybe (fromMaybe) import Distribution.Version (Version(..)) import GHC.Generics (Generic) import Language.Haskell.Extension (Language, Extension) import qualified System.Info (compilerName, compilerVersion) import Distribution.Text (Text(..), display) import qualified Distribution.Compat.ReadP as Parse import qualified Text.PrettyPrint as Disp import Text.PrettyPrint ((<>)) import qualified Data.Char as Char (toLower, isDigit, isAlphaNum) import Control.Monad (when) data CompilerFlavor = GHC | GHCJS | ETA | NHC | YHC | Hugs | HBC | Helium | JHC | LHC | UHC | HaskellSuite String -- string is the id of the actual compiler | OtherCompiler String deriving (Generic, Show, Read, Eq, Ord, Typeable, Data) instance Binary CompilerFlavor knownCompilerFlavors :: [CompilerFlavor] knownCompilerFlavors = [GHC, GHCJS, ETA, NHC, YHC, Hugs, HBC, Helium, JHC, LHC, UHC] instance Text CompilerFlavor where disp (OtherCompiler name) = Disp.text name disp (HaskellSuite name) = Disp.text name disp NHC = Disp.text "nhc98" disp other = Disp.text (lowercase (show other)) parse = do comp <- Parse.munch1 Char.isAlphaNum when (all Char.isDigit comp) Parse.pfail return (classifyCompilerFlavor comp) classifyCompilerFlavor :: String -> CompilerFlavor classifyCompilerFlavor s = fromMaybe (OtherCompiler s) $ lookup (lowercase s) compilerMap where compilerMap = [ (display compiler, compiler) | compiler <- knownCompilerFlavors ] --TODO: In some future release, remove 'parseCompilerFlavorCompat' and use -- ordinary 'parse'. Also add ("nhc", NHC) to the above 'compilerMap'. -- | Like 'classifyCompilerFlavor' but compatible with the old ReadS parser. -- -- It is compatible in the sense that it accepts only the same strings, -- eg "GHC" but not "ghc". However other strings get mapped to 'OtherCompiler'. -- The point of this is that we do not allow extra valid values that would -- upset older Cabal versions that had a stricter parser however we cope with -- new values more gracefully so that we'll be able to introduce new value in -- future without breaking things so much. -- parseCompilerFlavorCompat :: Parse.ReadP r CompilerFlavor parseCompilerFlavorCompat = do comp <- Parse.munch1 Char.isAlphaNum when (all Char.isDigit comp) Parse.pfail case lookup comp compilerMap of Just compiler -> return compiler Nothing -> return (OtherCompiler comp) where compilerMap = [ (show compiler, compiler) | compiler <- knownCompilerFlavors , compiler /= YHC ] buildCompilerFlavor :: CompilerFlavor buildCompilerFlavor = classifyCompilerFlavor System.Info.compilerName buildCompilerVersion :: Version buildCompilerVersion = System.Info.compilerVersion buildCompilerId :: CompilerId buildCompilerId = CompilerId buildCompilerFlavor buildCompilerVersion -- | The default compiler flavour to pick when compiling stuff. This defaults -- to the compiler used to build the Cabal lib. -- -- However if it's not a recognised compiler then it's 'Nothing' and the user -- will have to specify which compiler they want. -- defaultCompilerFlavor :: Maybe CompilerFlavor defaultCompilerFlavor = Just ETA -- case buildCompilerFlavor of -- OtherCompiler _ -> Nothing -- _ -> Just buildCompilerFlavor -- ------------------------------------------------------------ -- * Compiler Id -- ------------------------------------------------------------ data CompilerId = CompilerId CompilerFlavor Version deriving (Eq, Generic, Ord, Read, Show) instance Binary CompilerId instance Text CompilerId where disp (CompilerId f (Version [] _)) = disp f disp (CompilerId f v) = disp f <> Disp.char '-' <> disp v parse = do flavour <- parse version <- (Parse.char '-' >> parse) Parse.<++ return (Version [] []) return (CompilerId flavour version) lowercase :: String -> String lowercase = map Char.toLower -- ------------------------------------------------------------ -- * Compiler Info -- ------------------------------------------------------------ -- | Compiler information used for resolving configurations. Some fields can be -- set to Nothing to indicate that the information is unknown. data CompilerInfo = CompilerInfo { compilerInfoId :: CompilerId, -- ^ Compiler flavour and version. compilerInfoAbiTag :: AbiTag, -- ^ Tag for distinguishing incompatible ABI's on the same architecture/os. compilerInfoCompat :: Maybe [CompilerId], -- ^ Other implementations that this compiler claims to be compatible with, if known. compilerInfoLanguages :: Maybe [Language], -- ^ Supported language standards, if known. compilerInfoExtensions :: Maybe [Extension] -- ^ Supported extensions, if known. } deriving (Generic, Show, Read) instance Binary CompilerInfo data AbiTag = NoAbiTag | AbiTag String deriving (Generic, Show, Read) instance Binary AbiTag instance Text AbiTag where disp NoAbiTag = Disp.empty disp (AbiTag tag) = Disp.text tag parse = do tag <- Parse.munch (\c -> Char.isAlphaNum c || c == '_') if null tag then return NoAbiTag else return (AbiTag tag) abiTagString :: AbiTag -> String abiTagString NoAbiTag = "" abiTagString (AbiTag tag) = tag -- | Make a CompilerInfo of which only the known information is its CompilerId, -- its AbiTag and that it does not claim to be compatible with other -- compiler id's. unknownCompilerInfo :: CompilerId -> AbiTag -> CompilerInfo unknownCompilerInfo compilerId abiTag = CompilerInfo compilerId abiTag (Just []) Nothing Nothing
typelead/epm
Cabal/Distribution/Compiler.hs
bsd-3-clause
7,280
0
15
1,395
1,291
726
565
102
2
module Angel.LogSpec (spec) where import Angel.Log import Data.Time import Data.Time.Calendar (fromGregorian) import Data.Time.LocalTime (timeOfDayToTime, TimeOfDay(..), TimeZone(..), ZonedTime(..)) import SpecHelper spec :: Spec spec = do describe "cleanCalendar" $ do it "formats the time correctly" $ cleanCalendar dateTime `shouldBe` "2012/09/12 03:14:59" --where time = CalendarTime 2012 September 12 3 14 59 0 Tuesday 263 "Pacific" -25200 True where dateTime = ZonedTime localTime zone localTime = LocalTime day tod day = fromGregorian 2012 9 12 tod = TimeOfDay 3 14 59 zone = TimeZone (-420) False "PDT"
zalora/Angel
test/Angel/LogSpec.hs
bsd-3-clause
760
0
12
234
170
96
74
18
1
{-# OPTIONS_GHC -fno-warn-incomplete-patterns #-} module Handler.Project where import Import import qualified Data.Text as T import System.Directory import Text.Blaze.Internal (preEscapedText) getNewProjectR :: Handler Html getNewProjectR = do u <- requireAuth now <- liftIO getCurrentTime let inintstatuses = "!未着手#赤\n着手#緑\n完了#灰\n=却下#灰\n保留\n議論\n報告" :: Text (y,_,_) = toGregorian $ utctDay now eyears = [entryStartYear..y+5] help = $(widgetFile "help") defaultLayout $ do setTitleI MsgCreateNewProject $(widgetFile "newproject") postNewProjectR :: Handler Html postNewProjectR = do uid <- requireAuthId (name, desc, sts) <- runInputPost $ (,,) <$> ireq textField "name" <*> ireq textareaField "description" <*> ireq textareaField "statuses" now <- liftIO getCurrentTime pid <- runDB $ do pid <- insert $ Project { projectName=name , projectIssuecounter=0 , projectDescription=desc , projectStatuses=sts , projectTerminated=False , projectCuser=uid , projectCdate=now , projectUdate=now } _ <- insert $ Participants { participantsProject=pid , participantsUser=uid , participantsReceivemail=True , participantsCdate=now } return pid redirect $ ProjectR pid getProjectR :: ProjectId -> Handler Html getProjectR pid = do uid <- requireAuthId let help = $(widgetFile "help") prj <- runDB $ get404 pid defaultLayout $ do setTitle $ preEscapedText $ projectName prj $(widgetFile "project") postProjectR :: ProjectId -> Handler () postProjectR pid = do (nm, ds, tm, st) <- runInputPost $ (,,,) <$> ireq textField "name" <*> ireq textareaField "description" <*> ireq boolField "terminated" <*> ireq textareaField "statuses" now <- liftIO getCurrentTime runDB $ do prj <- get404 pid let prj' = prj { projectName = nm , projectDescription = ds , projectTerminated = tm , projectStatuses = st , projectUdate = now } replace pid prj' redirect $ ProjectR pid deleteProjectR :: ProjectId -> Handler Value deleteProjectR pid = do u <- requireAuth deleted <- runDB $ do if isAdmin (entityVal u) then do -- delete participants deleteWhere [ParticipantsProject ==. pid] -- delete comments comments <- selectList [CommentProject ==. pid] [] deleteWhere [CommentProject ==. pid] -- delete & remove files let fids = filter (/=Nothing) $ map (commentAttached.entityVal) comments forM_ fids $ \(Just fid) -> do f <- get404 fid let uid = fileHeaderCreator f s3dir' = s3dir </> T.unpack (toPathPiece uid) s3fp = s3dir' </> T.unpack (toPathPiece fid) delete fid liftIO $ removeFile s3fp -- delete issues deleteWhere [IssueProject ==. pid] -- delete project delete pid return True else do issues <- selectList [IssueProject ==. pid] [] if null issues then do deleteWhere [ParticipantsProject ==. pid] delete pid return True else return False cacheSeconds 10 -- FIXME returnJson $ if deleted then object ["deleted" .= show pid] else object ["error" .= ("このプロジェクトは削除できませんでした." :: Text)]
cutsea110/BISocie
Handler/Project.hs
bsd-3-clause
3,880
0
24
1,352
991
494
497
-1
-1
{-# LANGUAGE FlexibleContexts #-} module Karamaan.Opaleye.Table where import Karamaan.Opaleye.QueryArr (Query, next, tagWith, simpleQueryArr) import Database.HaskellDB.PrimQuery (PrimQuery(Project, BaseTable), PrimExpr(AttrExpr), Attribute, Assoc) import Karamaan.Opaleye.TableColspec (TableColspec, TableColspecP, runWriterOfColspec, runPackMapOfColspec, tableColspecOfTableColspecP, WireMaker, runWireMaker) import Data.Profunctor.Product.Default (Default, def) import Control.Arrow ((***)) import Karamaan.Plankton ((.:)) -- For specifying the columns as Strings data TableSpec a = TableSpec a String -- For specifying the columns as Wires data Table a = Table String a tableOfTableSpec :: WireMaker a b -> TableSpec a -> Table b tableOfTableSpec wireMaker (TableSpec cols name) = Table name wireCols where wireCols = runWireMaker wireMaker cols tableOfTableSpecDef :: Default WireMaker a b => TableSpec a -> Table b tableOfTableSpecDef = tableOfTableSpec def -- For typeclass resolution it seems best to force the arguments to be -- the same. Users can always use makeTableT to get more flexibility -- if they want. makeTableTDef :: Default TableColspecP a a => Table a -> Query a makeTableTDef = makeTableT def -- I don't know if this should be deprecated or not. Should we force -- everything to go through a Table? makeTableDef :: (Default WireMaker a b, Default TableColspecP b b) => a -> String -> Query b makeTableDef = makeTableTDef . tableOfTableSpec def .: TableSpec makeTableT :: TableColspecP a b -> Table a -> Query b makeTableT colspec (Table name cols) = makeTableQueryColspec colspec cols name makeTableQueryColspec :: TableColspecP a b -> a -> String -> Query b makeTableQueryColspec = makeTable .: tableColspecOfTableColspecP -- makeTable is informally deprecated, but Values.hs still uses it, -- so I don't want to deprecate it with a pragma yet. --{-# DEPRECATED makeTable "Use 'makeTableT' or 'makeTableTDef' instead" #-} makeTable :: TableColspec a -> String -> Query a makeTable colspec = makeTable' colspec (zip x x) where x = runWriterOfColspec colspec makeTable' :: TableColspec a -> [(String, String)] -> String -> Query a makeTable' colspec cols table_name = simpleQueryArr f where f ((), t0) = (retwires, primQuery, next t0) where (retwires, primQuery) = makeTable'' colspec cols table_name (tagWith t0) -- TODO: this needs tidying makeTable'' :: TableColspec a -> [(String, String)] -> String -> (String -> String) -> (a, PrimQuery) makeTable'' colspec cols table_name tag' = let basetablecols :: [String] basetablecols = map snd cols makeAssoc :: (String, String) -> (Attribute, PrimExpr) makeAssoc = tag' *** AttrExpr projcols :: Assoc projcols = map makeAssoc cols q :: PrimQuery q = Project projcols (BaseTable table_name basetablecols) in (runPackMapOfColspec colspec tag', q)
dbp/karamaan-opaleye
Karamaan/Opaleye/Table.hs
bsd-3-clause
3,111
0
11
696
745
407
338
-1
-1
module Gittins.Pretty ( prettyLog , summary ) where import Prelude hiding ((<$>)) import Gittins.Config import Gittins.Process import Gittins.Types import Text.PrettyPrint.ANSI.Leijen hiding (list) summary :: String -> String -> String -> Doc summary header body err = cyan (text header) <> (if null err then empty else line <> text err) <> (if null body then empty else line <> text body) summariseRepo :: Repository -> Doc summariseRepo (Repository n p _) = fillBreak 15 (cyan $ text n) <> brackets (text p) prettyLog :: LogMessage -> Doc prettyLog msg = (<> line) $ case msg of AlreadyRegistered path -> text $ "Path [" ++ path ++ "] is already registered." NotRegistered path -> text $ "Path [" ++ path ++ "] does not appear to be registered." NotAGitRepository path -> text $ "Path [" ++ path ++ "] does not appear to be a Git working tree and so has not been registered." ++ "\nRun with -f|--force to register it anyway." Registering path -> text "Registering " <> brackets (text path) Unregistering path -> text $ "Unregistering [" ++ path ++ "]" GitOutput repo output -> let ProcessResult _ out err = output in summary (repoName repo) out err PullSummary unsuccessful successful -> let listRepos rs = case rs of [] -> Nothing _ -> Just $ list' $ map (text . repoName) rs in int (length successful) <+> text "repositories updated" <+?> listRepos successful <> dot <$?> fmap (\s -> int (length unsuccessful) <+> text "repositories could not be updated" <+> s <> dot) (listRepos unsuccessful) RepositoriesSummary rs -> vcat $ map summariseRepo rs ProcessError e -> text e list' :: [Doc] -> Doc list' = encloseSep lparen rparen comma infix 7 <+?> (<+?>) :: Doc -> Maybe Doc -> Doc l <+?> Just r = l <+> r l <+?> Nothing = l infix 7 <$?> (<$?>) :: Doc -> Maybe Doc -> Doc l <$?> Just r = l <$> r l <$?> Nothing = l
bmjames/gittins
src/Gittins/Pretty.hs
bsd-3-clause
1,995
0
20
506
676
338
338
-1
-1
module SpecHelper where import Data.Foldable import Data.IORef import qualified Data.Sequence as S import qualified Data.Text as T import Snap import Snap.Snaplet.Heist import Snap.Snaplet.Session.Backends.CookieSession import qualified Snap.Test as ST import Test.Hspec import Wikirick.Application import qualified Wikirick.Backends.JSONConnection as J import qualified Wikirick.Backends.Repository as R import qualified Wikirick.Backends.URLMapper as U import Wikirick.Import import Wikirick.JSONConnection import Wikirick.Repository mustNotBeCalled :: String -> a mustNotBeCalled name = error $ "must not be called: " <> name repositoryMock :: Repository repositoryMock = Repository { _fetchArticle = mustNotBeCalled "fetchArticle" , _fetchRevision = mustNotBeCalled "fetchRevision" , _postArticle = mustNotBeCalled "postArticle" , _fetchAllArticleTitles = mustNotBeCalled "fetchAllArticleTitles" } jsonConnectionMock :: JSONConnection jsonConnectionMock = JSONConnection { _parseJSON = mustNotBeCalled "parseJSON" , _responseJSON = mustNotBeCalled "responseJSON" } mockedApp :: R.Repository -> SnapletInit App App mockedApp repo' = makeSnaplet "" "" Nothing $ App <$> nestSnaplet "" heist (heistInit "templates") <*> nestSnaplet "" sess (initCookieSessionManager "site_key_test.txt" "sess" Nothing) <*> nestSnaplet "" json J.initJSONConnection <*> nestSnaplet "" repo (R.initRepository repo') <*> nestSnaplet "" urlReceiver (U.initURLReceiver $ U.initURLMapper "/") data Spy a = Spy { logValue :: MonadIO m => a -> m () , mustBeLogged :: (Show a, Eq a) => [a] -> Expectation } newSpy :: IO (Spy a) newSpy = do values <- newIORef S.empty return Spy { logValue = \v -> liftIO $ modifyIORef values (|> v) , mustBeLogged = \expectations -> do vs <- readIORef values toList vs `shouldBe` expectations } type Response' = Either T.Text Response mustBeRight :: MonadIO m => Response' -> m Response mustBeRight = liftIO . either (fail . T.unpack) pure shouldHaveStatus :: Response' -> Int -> Expectation shouldHaveStatus res st = do res' <- mustBeRight res rspStatus res' `shouldBe` st xhr :: Monad m => ST.RequestBuilder m () xhr = ST.addHeader "X-Requested-With" "XMLHttpRequest"
keitax/wikirick
spec/SpecHelper.hs
bsd-3-clause
2,266
0
14
376
629
342
287
57
1
-- File: Optimal4.hs -- Author: Adam Juraszek -- Purpose: Partly generated map of optimal second guesses for 4 cards answers. -- Source: https://github.com/juriad/Cardguess module Optimal4 where import Common import Data.Map as Map optimal4 :: Map.Map Feedback Selection optimal4 = Map.fromList [ ( ( 0 , 0 , 0 , 0 , 0 ) , [Card Heart R7 , Card Heart R8 , Card Spade R7 , Card Spade R8] ) , ( ( 0 , 0 , 0 , 0 , 1 ) , [Card Diamond R8 , Card Spade R6 , Card Spade R7 , Card Spade R8] ) , ( ( 0 , 0 , 0 , 0 , 2 ) , [Card Diamond R7 , Card Diamond R8 , Card Spade R7 , Card Spade R8] ) , ( ( 0 , 0 , 0 , 0 , 3 ) , [Card Club R8 , Card Diamond R7 , Card Diamond R8 , Card Spade R8] ) , ( ( 0 , 0 , 0 , 0 , 4 ) , [Card Club R7 , Card Club R8 , Card Diamond R7 , Card Diamond R8] ) , ( ( 0 , 0 , 0 , 1 , 0 ) , [Card Spade R6 , Card Spade R7 , Card Spade R8 , Card Spade Ace] ) , ( ( 0 , 0 , 0 , 1 , 1 ) , [Card Diamond Ace , Card Spade R6 , Card Spade R7 , Card Spade R8] ) , ( ( 0 , 0 , 0 , 1 , 2 ) , [Card Diamond R8 , Card Diamond Ace , Card Spade R7 , Card Spade R8] ) , ( ( 0 , 0 , 0 , 1 , 3 ) , [Card Club Ace , Card Diamond R7 , Card Diamond R8 , Card Spade R8] ) , ( ( 0 , 0 , 0 , 1 , 4 ) , [Card Club R8 , Card Club Jack , Card Diamond R7 , Card Diamond R8] ) , ( ( 0 , 0 , 0 , 2 , 0 ) , [Card Spade R7 , Card Spade R8 , Card Spade King , Card Spade Ace] ) , ( ( 0 , 0 , 0 , 2 , 1 ) , [Card Diamond Ace , Card Spade R7 , Card Spade R8 , Card Spade Ace] ) , ( ( 0 , 0 , 0 , 2 , 2 ) , [Card Diamond King , Card Diamond Ace , Card Spade R7 , Card Spade R8] ) , ( ( 0 , 0 , 0 , 2 , 3 ) , [Card Club Ace , Card Diamond R8 , Card Diamond Ace , Card Spade R8] ) , ( ( 0 , 0 , 0 , 2 , 4 ) , [Card Club R8 , Card Club Jack , Card Diamond R8 , Card Diamond Jack] ) , ( ( 0 , 0 , 0 , 3 , 0 ) , [Card Spade R8 , Card Spade Queen , Card Spade King , Card Spade Ace] ) , ( ( 0 , 0 , 0 , 3 , 1 ) , [Card Diamond Ace , Card Spade R8 , Card Spade King , Card Spade Ace] ) , ( ( 0 , 0 , 0 , 3 , 2 ) , [Card Diamond King , Card Diamond Ace , Card Spade R8 , Card Spade Ace] ) , ( ( 0 , 0 , 0 , 3 , 3 ) , [Card Club Ace , Card Diamond King , Card Diamond Ace , Card Spade R8] ) , ( ( 0 , 0 , 0 , 3 , 4 ) , [Card Club King , Card Club Ace , Card Diamond R8 , Card Diamond Ace] ) , ( ( 0 , 0 , 0 , 4 , 0 ) , [Card Spade Jack , Card Spade Queen , Card Spade King , Card Spade Ace] ) , ( ( 0 , 0 , 0 , 4 , 1 ) , [Card Diamond Ace , Card Spade Queen , Card Spade King , Card Spade Ace] ) , ( ( 0 , 0 , 0 , 4 , 2 ) , [Card Diamond King , Card Diamond Ace , Card Spade King , Card Spade Ace] ) , ( ( 0 , 0 , 0 , 4 , 3 ) , [Card Club Ace , Card Diamond King , Card Diamond Ace , Card Spade Ace] ) , ( ( 0 , 0 , 0 , 4 , 4 ) , [Card Club King , Card Club Ace , Card Diamond King , Card Diamond Ace] ) , ( ( 0 , 0 , 1 , 0 , 0 ) , [Card Spade R6 , Card Spade R7 , Card Spade R8 , Card Spade R10] ) , ( ( 0 , 0 , 1 , 0 , 1 ) , [Card Diamond R8 , Card Spade R7 , Card Spade R8 , Card Spade R10] ) , ( ( 0 , 0 , 1 , 0 , 2 ) , [Card Diamond R7 , Card Diamond R8 , Card Spade R8 , Card Spade R10] ) , ( ( 0 , 0 , 1 , 0 , 3 ) , [Card Club R10 , Card Diamond R7 , Card Diamond R8 , Card Spade R10] ) , ( ( 0 , 0 , 1 , 0 , 4 ) , [Card Club R8 , Card Club R10 , Card Diamond R7 , Card Diamond R8] ) , ( ( 0 , 0 , 1 , 1 , 0 ) , [Card Spade R7 , Card Spade R8 , Card Spade R10 , Card Spade Ace] ) , ( ( 0 , 0 , 1 , 1 , 1 ) , [Card Diamond Ace , Card Spade R7 , Card Spade R8 , Card Spade R10] ) , ( ( 0 , 0 , 1 , 1 , 2 ) , [Card Diamond R8 , Card Diamond Ace , Card Spade R8 , Card Spade R10] ) , ( ( 0 , 0 , 1 , 1 , 3 ) , [Card Club Ace , Card Diamond R7 , Card Diamond R8 , Card Spade R10] ) , ( ( 0 , 0 , 1 , 1 , 4 ) , [Card Club R8 , Card Club R10 , Card Diamond R8 , Card Diamond Jack] ) , ( ( 0 , 0 , 1 , 2 , 0 ) , [Card Spade R8 , Card Spade R10 , Card Spade King , Card Spade Ace] ) , ( ( 0 , 0 , 1 , 2 , 1 ) , [Card Diamond Ace , Card Spade R8 , Card Spade R10 , Card Spade Ace] ) , ( ( 0 , 0 , 1 , 2 , 2 ) , [Card Diamond King , Card Diamond Ace , Card Spade R8 , Card Spade R10] ) , ( ( 0 , 0 , 1 , 2 , 3 ) , [Card Club Ace , Card Diamond R8 , Card Diamond Ace , Card Spade R10] ) , ( ( 0 , 0 , 1 , 2 , 4 ) , [Card Club R10 , Card Club Jack , Card Diamond R8 , Card Diamond Jack] ) , ( ( 0 , 0 , 1 , 3 , 0 ) , [Card Spade R10 , Card Spade Queen , Card Spade King , Card Spade Ace] ) , ( ( 0 , 0 , 1 , 3 , 1 ) , [Card Diamond Ace , Card Spade R10 , Card Spade King , Card Spade Ace] ) , ( ( 0 , 0 , 1 , 3 , 2 ) , [Card Diamond King , Card Diamond Ace , Card Spade R10 , Card Spade Ace] ) , ( ( 0 , 0 , 1 , 3 , 3 ) , [Card Club Ace , Card Diamond King , Card Diamond Ace , Card Spade R10] ) , ( ( 0 , 0 , 1 , 3 , 4 ) , [Card Club R10 , Card Club Queen , Card Diamond Jack , Card Diamond Queen] ) , ( ( 0 , 0 , 2 , 0 , 0 ) , [Card Spade R7 , Card Spade R8 , Card Spade R9 , Card Spade R10] ) , ( ( 0 , 0 , 2 , 0 , 1 ) , [Card Diamond R8 , Card Spade R8 , Card Spade R9 , Card Spade R10] ) , ( ( 0 , 0 , 2 , 0 , 2 ) , [Card Diamond R7 , Card Diamond R8 , Card Spade R9 , Card Spade R10] ) , ( ( 0 , 0 , 2 , 0 , 3 ) , [Card Club R10 , Card Diamond R7 , Card Diamond R8 , Card Spade R9] ) , ( ( 0 , 0 , 2 , 0 , 4 ) , [Card Club R8 , Card Club R10 , Card Diamond R5 , Card Diamond R8] ) , ( ( 0 , 0 , 2 , 1 , 0 ) , [Card Spade R8 , Card Spade R9 , Card Spade R10 , Card Spade Ace] ) , ( ( 0 , 0 , 2 , 1 , 1 ) , [Card Diamond Ace , Card Spade R8 , Card Spade R9 , Card Spade R10] ) , ( ( 0 , 0 , 2 , 1 , 2 ) , [Card Diamond R8 , Card Diamond Ace , Card Spade R9 , Card Spade R10] ) , ( ( 0 , 0 , 2 , 1 , 3 ) , [Card Club Ace , Card Diamond R5 , Card Diamond R8 , Card Spade R10] ) , ( ( 0 , 0 , 2 , 1 , 4 ) , [Card Club R10 , Card Club Jack , Card Diamond R5 , Card Diamond R8] ) , ( ( 0 , 0 , 2 , 2 , 0 ) , [Card Spade R9 , Card Spade R10 , Card Spade King , Card Spade Ace] ) , ( ( 0 , 0 , 2 , 2 , 1 ) , [Card Diamond Ace , Card Spade R9 , Card Spade R10 , Card Spade Ace] ) , ( ( 0 , 0 , 2 , 2 , 2 ) , [Card Diamond King , Card Diamond Ace , Card Spade R9 , Card Spade R10] ) , ( ( 0 , 0 , 2 , 2 , 3 ) , [Card Club Ace , Card Diamond R5 , Card Diamond Ace , Card Spade R10] ) , ( ( 0 , 0 , 2 , 2 , 4 ) , [Card Club R10 , Card Club Ace , Card Diamond R5 , Card Diamond Ace] ) , ( ( 0 , 0 , 3 , 0 , 0 ) , [Card Heart R9 , Card Heart R10 , Card Spade R9 , Card Spade R10] ) , ( ( 0 , 0 , 3 , 0 , 1 ) , [Card Diamond R8 , Card Spade R5 , Card Spade R9 , Card Spade R10] ) , ( ( 0 , 0 , 3 , 0 , 2 ) , [Card Diamond R5 , Card Diamond R8 , Card Spade R9 , Card Spade R10] ) , ( ( 0 , 0 , 3 , 0 , 3 ) , [Card Club R10 , Card Diamond R5 , Card Diamond R8 , Card Spade R9] ) , ( ( 0 , 0 , 3 , 1 , 0 ) , [Card Spade R5 , Card Spade R9 , Card Spade R10 , Card Spade Ace] ) , ( ( 0 , 0 , 3 , 1 , 1 ) , [Card Diamond Ace , Card Spade R5 , Card Spade R9 , Card Spade R10] ) , ( ( 0 , 0 , 3 , 1 , 2 ) , [Card Diamond R5 , Card Diamond Ace , Card Spade R9 , Card Spade R10] ) , ( ( 0 , 0 , 3 , 1 , 3 ) , [Card Club R10 , Card Diamond R5 , Card Diamond Ace , Card Spade R9] ) , ( ( 0 , 0 , 4 , 0 , 0 ) , [Card Heart R9 , Card Spade R5 , Card Spade R9 , Card Spade R10] ) , ( ( 0 , 0 , 4 , 0 , 1 ) , [Card Diamond R5 , Card Heart R9 , Card Spade R9 , Card Spade R10] ) , ( ( 0 , 0 , 4 , 0 , 2 ) , [Card Club R10 , Card Diamond R5 , Card Heart R9 , Card Spade R9] ) , ( ( 0 , 1 , 0 , 0 , 0 ) , [Card Spade R4 , Card Spade R6 , Card Spade R7 , Card Spade R8] ) , ( ( 0 , 1 , 0 , 0 , 1 ) , [Card Diamond R8 , Card Spade R4 , Card Spade R7 , Card Spade R8] ) , ( ( 0 , 1 , 0 , 0 , 2 ) , [Card Diamond R7 , Card Diamond R8 , Card Spade R4 , Card Spade R8] ) , ( ( 0 , 1 , 0 , 0 , 3 ) , [Card Club R8 , Card Diamond R7 , Card Diamond R8 , Card Spade R4] ) , ( ( 0 , 1 , 0 , 0 , 4 ) , [Card Club R6 , Card Club R7 , Card Diamond R4 , Card Diamond R7] ) , ( ( 0 , 1 , 0 , 1 , 0 ) , [Card Spade R4 , Card Spade R7 , Card Spade R8 , Card Spade Ace] ) , ( ( 0 , 1 , 0 , 1 , 1 ) , [Card Diamond Ace , Card Spade R4 , Card Spade R7 , Card Spade R8] ) , ( ( 0 , 1 , 0 , 1 , 2 ) , [Card Diamond R8 , Card Diamond Ace , Card Spade R4 , Card Spade R8] ) , ( ( 0 , 1 , 0 , 1 , 3 ) , [Card Club Ace , Card Diamond R7 , Card Diamond R8 , Card Spade R4] ) , ( ( 0 , 1 , 0 , 1 , 4 ) , [Card Club R8 , Card Club Ace , Card Diamond R4 , Card Diamond R8] ) , ( ( 0 , 1 , 0 , 2 , 0 ) , [Card Spade R4 , Card Spade R8 , Card Spade King , Card Spade Ace] ) , ( ( 0 , 1 , 0 , 2 , 1 ) , [Card Diamond Ace , Card Spade R4 , Card Spade R8 , Card Spade Ace] ) , ( ( 0 , 1 , 0 , 2 , 2 ) , [Card Diamond King , Card Diamond Ace , Card Spade R4 , Card Spade R8] ) , ( ( 0 , 1 , 0 , 2 , 3 ) , [Card Club Ace , Card Diamond R8 , Card Diamond Ace , Card Spade R4] ) , ( ( 0 , 1 , 0 , 2 , 4 ) , [Card Club King , Card Club Ace , Card Diamond R4 , Card Diamond R8] ) , ( ( 0 , 1 , 0 , 3 , 0 ) , [Card Spade R4 , Card Spade Queen , Card Spade King , Card Spade Ace] ) , ( ( 0 , 1 , 0 , 3 , 1 ) , [Card Diamond Ace , Card Spade R4 , Card Spade King , Card Spade Ace] ) , ( ( 0 , 1 , 0 , 3 , 2 ) , [Card Diamond King , Card Diamond Ace , Card Spade R4 , Card Spade Ace] ) , ( ( 0 , 1 , 0 , 3 , 3 ) , [Card Club Ace , Card Diamond King , Card Diamond Ace , Card Spade R4] ) , ( ( 0 , 1 , 0 , 3 , 4 ) , [Card Club King , Card Club Ace , Card Diamond R4 , Card Diamond Ace] ) , ( ( 0 , 1 , 1 , 0 , 0 ) , [Card Spade R4 , Card Spade R7 , Card Spade R8 , Card Spade R10] ) , ( ( 0 , 1 , 1 , 0 , 1 ) , [Card Diamond R8 , Card Spade R4 , Card Spade R8 , Card Spade R10] ) , ( ( 0 , 1 , 1 , 0 , 2 ) , [Card Diamond R7 , Card Diamond R8 , Card Spade R4 , Card Spade R10] ) , ( ( 0 , 1 , 1 , 0 , 3 ) , [Card Club R10 , Card Diamond R7 , Card Diamond R8 , Card Spade R4] ) , ( ( 0 , 1 , 1 , 0 , 4 ) , [Card Club R4 , Card Club R6 , Card Diamond R5 , Card Diamond R6] ) , ( ( 0 , 1 , 1 , 1 , 0 ) , [Card Spade R4 , Card Spade R8 , Card Spade R10 , Card Spade Ace] ) , ( ( 0 , 1 , 1 , 1 , 1 ) , [Card Diamond Ace , Card Spade R4 , Card Spade R8 , Card Spade R10] ) , ( ( 0 , 1 , 1 , 1 , 2 ) , [Card Diamond R8 , Card Diamond Ace , Card Spade R4 , Card Spade R10] ) , ( ( 0 , 1 , 1 , 1 , 3 ) , [Card Club Ace , Card Diamond R5 , Card Diamond R8 , Card Spade R4] ) , ( ( 0 , 1 , 1 , 1 , 4 ) , [Card Club R10 , Card Club Ace , Card Diamond R4 , Card Diamond R8] ) , ( ( 0 , 1 , 1 , 2 , 0 ) , [Card Spade R4 , Card Spade R10 , Card Spade King , Card Spade Ace] ) , ( ( 0 , 1 , 1 , 2 , 1 ) , [Card Diamond Ace , Card Spade R4 , Card Spade R10 , Card Spade Ace] ) , ( ( 0 , 1 , 1 , 2 , 2 ) , [Card Diamond King , Card Diamond Ace , Card Spade R4 , Card Spade R10] ) , ( ( 0 , 1 , 1 , 2 , 3 ) , [Card Club Ace , Card Diamond R5 , Card Diamond Ace , Card Spade R4] ) , ( ( 0 , 1 , 1 , 2 , 4 ) , [Card Club R10 , Card Club Jack , Card Diamond R4 , Card Diamond Jack] ) , ( ( 0 , 1 , 2 , 0 , 0 ) , [Card Spade R4 , Card Spade R8 , Card Spade R9 , Card Spade R10] ) , ( ( 0 , 1 , 2 , 0 , 1 ) , [Card Diamond R8 , Card Spade R4 , Card Spade R9 , Card Spade R10] ) , ( ( 0 , 1 , 2 , 0 , 2 ) , [Card Diamond R5 , Card Diamond R8 , Card Spade R4 , Card Spade R10] ) , ( ( 0 , 1 , 2 , 0 , 3 ) , [Card Club R10 , Card Diamond R5 , Card Diamond R8 , Card Spade R4] ) , ( ( 0 , 1 , 2 , 0 , 4 ) , [Card Club R8 , Card Club R10 , Card Diamond R4 , Card Diamond R5] ) , ( ( 0 , 1 , 2 , 1 , 0 ) , [Card Spade R4 , Card Spade R9 , Card Spade R10 , Card Spade Ace] ) , ( ( 0 , 1 , 2 , 1 , 1 ) , [Card Diamond Ace , Card Spade R4 , Card Spade R9 , Card Spade R10] ) , ( ( 0 , 1 , 2 , 1 , 2 ) , [Card Diamond R5 , Card Diamond Ace , Card Spade R4 , Card Spade R10] ) , ( ( 0 , 1 , 2 , 1 , 3 ) , [Card Club Ace , Card Diamond R4 , Card Diamond R5 , Card Spade R10] ) , ( ( 0 , 1 , 2 , 1 , 4 ) , [Card Club R10 , Card Club Jack , Card Diamond R4 , Card Diamond R5] ) , ( ( 0 , 1 , 3 , 0 , 0 ) , [Card Spade R4 , Card Spade R5 , Card Spade R9 , Card Spade R10] ) , ( ( 0 , 1 , 3 , 0 , 1 ) , [Card Diamond R5 , Card Spade R4 , Card Spade R9 , Card Spade R10] ) , ( ( 0 , 1 , 3 , 0 , 2 ) , [Card Diamond R4 , Card Diamond R5 , Card Spade R9 , Card Spade R10] ) , ( ( 0 , 1 , 3 , 0 , 3 ) , [Card Club R10 , Card Diamond R2 , Card Diamond R5 , Card Spade R9] ) , ( ( 0 , 2 , 0 , 0 , 0 ) , [Card Spade R3 , Card Spade R4 , Card Spade R7 , Card Spade R8] ) , ( ( 0 , 2 , 0 , 0 , 1 ) , [Card Diamond R8 , Card Spade R3 , Card Spade R4 , Card Spade R8] ) , ( ( 0 , 2 , 0 , 0 , 2 ) , [Card Diamond R7 , Card Diamond R8 , Card Spade R3 , Card Spade R4] ) , ( ( 0 , 2 , 0 , 0 , 3 ) , [Card Club R8 , Card Diamond R4 , Card Diamond R8 , Card Spade R4] ) , ( ( 0 , 2 , 0 , 0 , 4 ) , [Card Club R4 , Card Club R6 , Card Diamond R4 , Card Diamond R6] ) , ( ( 0 , 2 , 0 , 1 , 0 ) , [Card Spade R3 , Card Spade R4 , Card Spade R8 , Card Spade Ace] ) , ( ( 0 , 2 , 0 , 1 , 1 ) , [Card Diamond Ace , Card Spade R3 , Card Spade R4 , Card Spade R8] ) , ( ( 0 , 2 , 0 , 1 , 2 ) , [Card Diamond R8 , Card Diamond Ace , Card Spade R3 , Card Spade R4] ) , ( ( 0 , 2 , 0 , 1 , 3 ) , [Card Club Ace , Card Diamond R4 , Card Diamond R8 , Card Spade R4] ) , ( ( 0 , 2 , 0 , 1 , 4 ) , [Card Club R8 , Card Club Ace , Card Diamond R3 , Card Diamond R4] ) , ( ( 0 , 2 , 0 , 2 , 0 ) , [Card Spade R3 , Card Spade R4 , Card Spade King , Card Spade Ace] ) , ( ( 0 , 2 , 0 , 2 , 1 ) , [Card Diamond Ace , Card Spade R3 , Card Spade R4 , Card Spade Ace] ) , ( ( 0 , 2 , 0 , 2 , 2 ) , [Card Diamond King , Card Diamond Ace , Card Spade R3 , Card Spade R4] ) , ( ( 0 , 2 , 0 , 2 , 3 ) , [Card Club Ace , Card Diamond R4 , Card Diamond Ace , Card Spade R4] ) , ( ( 0 , 2 , 0 , 2 , 4 ) , [Card Club R4 , Card Club Jack , Card Diamond R4 , Card Diamond Jack] ) , ( ( 0 , 2 , 1 , 0 , 0 ) , [Card Spade R3 , Card Spade R4 , Card Spade R8 , Card Spade R10] ) , ( ( 0 , 2 , 1 , 0 , 1 ) , [Card Diamond R8 , Card Spade R3 , Card Spade R4 , Card Spade R10] ) , ( ( 0 , 2 , 1 , 0 , 2 ) , [Card Diamond R5 , Card Diamond R8 , Card Spade R3 , Card Spade R4] ) , ( ( 0 , 2 , 1 , 0 , 3 ) , [Card Club R10 , Card Diamond R4 , Card Diamond R8 , Card Spade R4] ) , ( ( 0 , 2 , 1 , 0 , 4 ) , [Card Club R4 , Card Club R6 , Card Diamond R4 , Card Diamond R5] ) , ( ( 0 , 2 , 1 , 1 , 0 ) , [Card Spade R3 , Card Spade R4 , Card Spade R10 , Card Spade Ace] ) , ( ( 0 , 2 , 1 , 1 , 1 ) , [Card Diamond Ace , Card Spade R3 , Card Spade R4 , Card Spade R10] ) , ( ( 0 , 2 , 1 , 1 , 2 ) , [Card Diamond R5 , Card Diamond Ace , Card Spade R3 , Card Spade R4] ) , ( ( 0 , 2 , 1 , 1 , 3 ) , [Card Club Ace , Card Diamond R4 , Card Diamond R5 , Card Spade R4] ) , ( ( 0 , 2 , 1 , 1 , 4 ) , [Card Club R4 , Card Club Jack , Card Diamond R4 , Card Diamond R5] ) , ( ( 0 , 2 , 2 , 0 , 0 ) , [Card Spade R3 , Card Spade R4 , Card Spade R9 , Card Spade R10] ) , ( ( 0 , 2 , 2 , 0 , 1 ) , [Card Diamond R5 , Card Spade R3 , Card Spade R4 , Card Spade R10] ) , ( ( 0 , 2 , 2 , 0 , 2 ) , [Card Diamond R4 , Card Diamond R5 , Card Spade R4 , Card Spade R10] ) , ( ( 0 , 2 , 2 , 0 , 3 ) , [Card Club R10 , Card Diamond R4 , Card Diamond R5 , Card Spade R4] ) , ( ( 0 , 2 , 2 , 0 , 4 ) , [Card Club R4 , Card Club R10 , Card Diamond R4 , Card Diamond R5] ) , ( ( 0 , 3 , 0 , 0 , 0 ) , [Card Spade R2 , Card Spade R3 , Card Spade R4 , Card Spade R8] ) , ( ( 0 , 3 , 0 , 0 , 1 ) , [Card Diamond R8 , Card Spade R2 , Card Spade R3 , Card Spade R4] ) , ( ( 0 , 3 , 0 , 0 , 2 ) , [Card Diamond R4 , Card Diamond R8 , Card Spade R3 , Card Spade R4] ) , ( ( 0 , 3 , 0 , 0 , 3 ) , [Card Club R8 , Card Diamond R3 , Card Diamond R4 , Card Spade R4] ) , ( ( 0 , 3 , 0 , 0 , 4 ) , [Card Club R4 , Card Club R6 , Card Diamond R3 , Card Diamond R4] ) , ( ( 0 , 3 , 0 , 1 , 0 ) , [Card Spade R2 , Card Spade R3 , Card Spade R4 , Card Spade Ace] ) , ( ( 0 , 3 , 0 , 1 , 1 ) , [Card Diamond Ace , Card Spade R2 , Card Spade R3 , Card Spade R4] ) , ( ( 0 , 3 , 0 , 1 , 2 ) , [Card Diamond R4 , Card Diamond Ace , Card Spade R3 , Card Spade R4] ) , ( ( 0 , 3 , 0 , 1 , 3 ) , [Card Club Ace , Card Diamond R3 , Card Diamond R4 , Card Spade R4] ) , ( ( 0 , 3 , 0 , 1 , 4 ) , [Card Club R4 , Card Club Jack , Card Diamond R3 , Card Diamond R4] ) , ( ( 0 , 3 , 1 , 0 , 0 ) , [Card Spade R2 , Card Spade R3 , Card Spade R4 , Card Spade R10] ) , ( ( 0 , 3 , 1 , 0 , 1 ) , [Card Diamond R5 , Card Spade R2 , Card Spade R3 , Card Spade R4] ) , ( ( 0 , 3 , 1 , 0 , 2 ) , [Card Diamond R4 , Card Diamond R5 , Card Spade R3 , Card Spade R4] ) , ( ( 0 , 3 , 1 , 0 , 3 ) , [Card Club R10 , Card Diamond R3 , Card Diamond R4 , Card Spade R4] ) , ( ( 0 , 3 , 1 , 0 , 4 ) , [Card Club R3 , Card Club R4 , Card Diamond R4 , Card Diamond R5] ) , ( ( 0 , 4 , 0 , 0 , 0 ) , [Card Heart R3 , Card Heart R4 , Card Spade R3 , Card Spade R4] ) , ( ( 0 , 4 , 0 , 0 , 1 ) , [Card Diamond R4 , Card Spade R2 , Card Spade R3 , Card Spade R4] ) , ( ( 0 , 4 , 0 , 0 , 2 ) , [Card Diamond R3 , Card Diamond R4 , Card Spade R3 , Card Spade R4] ) , ( ( 0 , 4 , 0 , 0 , 3 ) , [Card Club R4 , Card Diamond R3 , Card Diamond R4 , Card Spade R4] ) , ( ( 0 , 4 , 0 , 0 , 4 ) , [Card Club R3 , Card Club R4 , Card Diamond R3 , Card Diamond R4] ) , ( ( 1 , 0 , 1 , 0 , 1 ) , [Card Diamond R10 , Card Spade R7 , Card Spade R8 , Card Spade R10] ) , ( ( 1 , 0 , 1 , 0 , 2 ) , [Card Diamond R8 , Card Diamond R10 , Card Spade R8 , Card Spade R10] ) , ( ( 1 , 0 , 1 , 0 , 3 ) , [Card Club R10 , Card Diamond R8 , Card Diamond R10 , Card Spade R10] ) , ( ( 1 , 0 , 1 , 0 , 4 ) , [Card Club R5 , Card Club R6 , Card Diamond R5 , Card Diamond R6] ) , ( ( 1 , 0 , 1 , 1 , 1 ) , [Card Diamond R10 , Card Spade R8 , Card Spade R10 , Card Spade Ace] ) , ( ( 1 , 0 , 1 , 1 , 2 ) , [Card Diamond R10 , Card Diamond Ace , Card Spade R8 , Card Spade R10] ) , ( ( 1 , 0 , 1 , 1 , 3 ) , [Card Club Ace , Card Diamond R8 , Card Diamond R10 , Card Spade R10] ) , ( ( 1 , 0 , 1 , 1 , 4 ) , [Card Club R8 , Card Club Jack , Card Diamond R8 , Card Diamond R10] ) , ( ( 1 , 0 , 1 , 2 , 1 ) , [Card Diamond R10 , Card Spade R10 , Card Spade King , Card Spade Ace] ) , ( ( 1 , 0 , 1 , 2 , 2 ) , [Card Diamond R10 , Card Diamond Ace , Card Spade R10 , Card Spade Ace] ) , ( ( 1 , 0 , 1 , 2 , 3 ) , [Card Club Ace , Card Diamond R10 , Card Diamond Ace , Card Spade R10] ) , ( ( 1 , 0 , 1 , 2 , 4 ) , [Card Club R10 , Card Club Jack , Card Diamond R10 , Card Diamond Jack] ) , ( ( 1 , 0 , 1 , 3 , 1 ) , [Card Diamond R10 , Card Spade Queen , Card Spade King , Card Spade Ace] ) , ( ( 1 , 0 , 1 , 3 , 2 ) , [Card Diamond R10 , Card Diamond Ace , Card Spade King , Card Spade Ace] ) , ( ( 1 , 0 , 1 , 3 , 3 ) , [Card Club Ace , Card Diamond R10 , Card Diamond Ace , Card Spade Ace] ) , ( ( 1 , 0 , 1 , 3 , 4 ) , [Card Club Jack , Card Club Queen , Card Diamond R10 , Card Diamond Queen] ) , ( ( 1 , 0 , 2 , 0 , 1 ) , [Card Diamond R10 , Card Spade R8 , Card Spade R9 , Card Spade R10] ) , ( ( 1 , 0 , 2 , 0 , 2 ) , [Card Diamond R8 , Card Diamond R10 , Card Spade R9 , Card Spade R10] ) , ( ( 1 , 0 , 2 , 0 , 3 ) , [Card Club R10 , Card Diamond R8 , Card Diamond R10 , Card Spade R9] ) , ( ( 1 , 0 , 2 , 0 , 4 ) , [Card Club R9 , Card Club R10 , Card Diamond R7 , Card Diamond R8] ) , ( ( 1 , 0 , 2 , 1 , 1 ) , [Card Diamond R10 , Card Spade R9 , Card Spade R10 , Card Spade Ace] ) , ( ( 1 , 0 , 2 , 1 , 2 ) , [Card Diamond R10 , Card Diamond Ace , Card Spade R9 , Card Spade R10] ) , ( ( 1 , 0 , 2 , 1 , 3 ) , [Card Club Ace , Card Diamond R8 , Card Diamond R10 , Card Spade R9] ) , ( ( 1 , 0 , 2 , 1 , 4 ) , [Card Club R10 , Card Club Ace , Card Diamond R8 , Card Diamond R9] ) , ( ( 1 , 0 , 2 , 2 , 1 ) , [Card Diamond R10 , Card Spade R9 , Card Spade King , Card Spade Ace] ) , ( ( 1 , 0 , 2 , 2 , 2 ) , [Card Diamond R10 , Card Diamond Ace , Card Spade R9 , Card Spade Ace] ) , ( ( 1 , 0 , 2 , 2 , 3 ) , [Card Club Ace , Card Diamond R10 , Card Diamond Ace , Card Spade R9] ) , ( ( 1 , 0 , 2 , 2 , 4 ) , [Card Club R10 , Card Club Jack , Card Diamond R9 , Card Diamond Jack] ) , ( ( 1 , 0 , 3 , 0 , 1 ) , [Card Diamond R10 , Card Spade R5 , Card Spade R9 , Card Spade R10] ) , ( ( 1 , 0 , 3 , 0 , 2 ) , [Card Diamond R8 , Card Diamond R10 , Card Spade R5 , Card Spade R9] ) , ( ( 1 , 0 , 3 , 0 , 3 ) , [Card Club R10 , Card Diamond R8 , Card Diamond R9 , Card Spade R9] ) , ( ( 1 , 0 , 3 , 0 , 4 ) , [Card Club R9 , Card Club R10 , Card Diamond R5 , Card Diamond R8] ) , ( ( 1 , 0 , 3 , 1 , 1 ) , [Card Diamond R10 , Card Spade R5 , Card Spade R9 , Card Spade Ace] ) , ( ( 1 , 0 , 3 , 1 , 2 ) , [Card Diamond R10 , Card Diamond Ace , Card Spade R5 , Card Spade R9] ) , ( ( 1 , 0 , 3 , 1 , 3 ) , [Card Club Ace , Card Diamond R5 , Card Diamond R10 , Card Spade R9] ) , ( ( 1 , 0 , 3 , 1 , 4 ) , [Card Club R10 , Card Club Ace , Card Diamond R5 , Card Diamond R9] ) , ( ( 1 , 0 , 4 , 0 , 1 ) , [Card Diamond R9 , Card Heart R10 , Card Spade R5 , Card Spade R9] ) , ( ( 1 , 0 , 4 , 0 , 2 ) , [Card Diamond R5 , Card Diamond R10 , Card Heart R9 , Card Spade R9] ) , ( ( 1 , 0 , 4 , 0 , 3 ) , [Card Club R10 , Card Diamond R5 , Card Diamond R9 , Card Spade R9] ) , ( ( 1 , 1 , 1 , 0 , 1 ) , [Card Diamond R10 , Card Spade R4 , Card Spade R8 , Card Spade R10] ) , ( ( 1 , 1 , 1 , 0 , 2 ) , [Card Diamond R8 , Card Diamond R10 , Card Spade R4 , Card Spade R10] ) , ( ( 1 , 1 , 1 , 0 , 3 ) , [Card Club R10 , Card Diamond R8 , Card Diamond R10 , Card Spade R4] ) , ( ( 1 , 1 , 1 , 0 , 4 ) , [Card Club R5 , Card Club R6 , Card Diamond R4 , Card Diamond R6] ) , ( ( 1 , 1 , 1 , 1 , 1 ) , [Card Diamond R10 , Card Spade R4 , Card Spade R10 , Card Spade Ace] ) , ( ( 1 , 1 , 1 , 1 , 2 ) , [Card Diamond R10 , Card Diamond Ace , Card Spade R4 , Card Spade R10] ) , ( ( 1 , 1 , 1 , 1 , 3 ) , [Card Club Ace , Card Diamond R8 , Card Diamond R10 , Card Spade R4] ) , ( ( 1 , 1 , 1 , 1 , 4 ) , [Card Club R10 , Card Club Ace , Card Diamond R4 , Card Diamond R10] ) , ( ( 1 , 1 , 1 , 2 , 1 ) , [Card Diamond R10 , Card Spade R4 , Card Spade King , Card Spade Ace] ) , ( ( 1 , 1 , 1 , 2 , 2 ) , [Card Diamond R10 , Card Diamond Ace , Card Spade R4 , Card Spade Ace] ) , ( ( 1 , 1 , 1 , 2 , 3 ) , [Card Club Ace , Card Diamond R10 , Card Diamond Ace , Card Spade R4] ) , ( ( 1 , 1 , 1 , 2 , 4 ) , [Card Club R5 , Card Club Jack , Card Diamond R4 , Card Diamond Jack] ) , ( ( 1 , 1 , 2 , 0 , 1 ) , [Card Diamond R10 , Card Spade R4 , Card Spade R9 , Card Spade R10] ) , ( ( 1 , 1 , 2 , 0 , 2 ) , [Card Diamond R8 , Card Diamond R10 , Card Spade R4 , Card Spade R9] ) , ( ( 1 , 1 , 2 , 0 , 3 ) , [Card Club R10 , Card Diamond R8 , Card Diamond R9 , Card Spade R4] ) , ( ( 1 , 1 , 2 , 0 , 4 ) , [Card Club R9 , Card Club R10 , Card Diamond R4 , Card Diamond R8] ) , ( ( 1 , 1 , 2 , 1 , 1 ) , [Card Diamond R10 , Card Spade R4 , Card Spade R9 , Card Spade Ace] ) , ( ( 1 , 1 , 2 , 1 , 2 ) , [Card Diamond R10 , Card Diamond Ace , Card Spade R4 , Card Spade R9] ) , ( ( 1 , 1 , 2 , 1 , 3 ) , [Card Club Ace , Card Diamond R5 , Card Diamond R10 , Card Spade R4] ) , ( ( 1 , 1 , 2 , 1 , 4 ) , [Card Club R10 , Card Club Ace , Card Diamond R4 , Card Diamond R9] ) , ( ( 1 , 1 , 3 , 0 , 1 ) , [Card Diamond R10 , Card Spade R4 , Card Spade R5 , Card Spade R9] ) , ( ( 1 , 1 , 3 , 0 , 2 ) , [Card Diamond R5 , Card Diamond R10 , Card Spade R4 , Card Spade R9] ) , ( ( 1 , 1 , 3 , 0 , 3 ) , [Card Club R10 , Card Diamond R5 , Card Diamond R9 , Card Spade R4] ) , ( ( 1 , 1 , 3 , 0 , 4 ) , [Card Club R9 , Card Club R10 , Card Diamond R2 , Card Diamond R5] ) , ( ( 1 , 2 , 1 , 0 , 1 ) , [Card Diamond R10 , Card Spade R3 , Card Spade R4 , Card Spade R10] ) , ( ( 1 , 2 , 1 , 0 , 2 ) , [Card Diamond R8 , Card Diamond R10 , Card Spade R3 , Card Spade R4] ) , ( ( 1 , 2 , 1 , 0 , 3 ) , [Card Club R10 , Card Diamond R4 , Card Diamond R10 , Card Spade R4] ) , ( ( 1 , 2 , 1 , 0 , 4 ) , [Card Club R4 , Card Club R5 , Card Diamond R4 , Card Diamond R5] ) , ( ( 1 , 2 , 1 , 1 , 1 ) , [Card Diamond R10 , Card Spade R3 , Card Spade R4 , Card Spade Ace] ) , ( ( 1 , 2 , 1 , 1 , 2 ) , [Card Diamond R10 , Card Diamond Ace , Card Spade R3 , Card Spade R4] ) , ( ( 1 , 2 , 1 , 1 , 3 ) , [Card Club Ace , Card Diamond R4 , Card Diamond R10 , Card Spade R4] ) , ( ( 1 , 2 , 1 , 1 , 4 ) , [Card Club R4 , Card Club Jack , Card Diamond R4 , Card Diamond R10] ) , ( ( 1 , 2 , 2 , 0 , 1 ) , [Card Diamond R10 , Card Spade R3 , Card Spade R4 , Card Spade R9] ) , ( ( 1 , 2 , 2 , 0 , 2 ) , [Card Diamond R5 , Card Diamond R10 , Card Spade R3 , Card Spade R4] ) , ( ( 1 , 2 , 2 , 0 , 3 ) , [Card Club R10 , Card Diamond R4 , Card Diamond R9 , Card Spade R4] ) , ( ( 1 , 2 , 2 , 0 , 4 ) , [Card Club R4 , Card Club R9 , Card Diamond R4 , Card Diamond R5] ) , ( ( 1 , 3 , 1 , 0 , 1 ) , [Card Diamond R10 , Card Spade R2 , Card Spade R3 , Card Spade R4] ) , ( ( 1 , 3 , 1 , 0 , 2 ) , [Card Diamond R4 , Card Diamond R10 , Card Spade R3 , Card Spade R4] ) , ( ( 1 , 3 , 1 , 0 , 3 ) , [Card Club R9 , Card Diamond R3 , Card Diamond R4 , Card Spade R4] ) , ( ( 1 , 3 , 1 , 0 , 4 ) , [Card Club R4 , Card Club R5 , Card Diamond R3 , Card Diamond R4] ) , ( ( 2 , 0 , 2 , 0 , 2 ) , [Card Diamond R9 , Card Diamond R10 , Card Spade R8 , Card Spade R10] ) , ( ( 2 , 0 , 2 , 0 , 3 ) , [Card Club R10 , Card Diamond R9 , Card Diamond R10 , Card Spade R10] ) , ( ( 2 , 0 , 2 , 0 , 4 ) , [Card Club R8 , Card Club R9 , Card Diamond R8 , Card Diamond R9] ) , ( ( 2 , 0 , 2 , 1 , 2 ) , [Card Diamond R9 , Card Diamond R10 , Card Spade R10 , Card Spade Ace] ) , ( ( 2 , 0 , 2 , 1 , 3 ) , [Card Club Ace , Card Diamond R9 , Card Diamond R10 , Card Spade R10] ) , ( ( 2 , 0 , 2 , 1 , 4 ) , [Card Club R10 , Card Club Ace , Card Diamond R9 , Card Diamond R10] ) , ( ( 2 , 0 , 2 , 2 , 2 ) , [Card Diamond R9 , Card Diamond R10 , Card Spade King , Card Spade Ace] ) , ( ( 2 , 0 , 2 , 2 , 3 ) , [Card Club Ace , Card Diamond R9 , Card Diamond R10 , Card Spade Ace] ) , ( ( 2 , 0 , 2 , 2 , 4 ) , [Card Club R9 , Card Club Jack , Card Diamond R9 , Card Diamond Jack] ) , ( ( 2 , 0 , 3 , 0 , 2 ) , [Card Diamond R9 , Card Diamond R10 , Card Spade R9 , Card Spade R10] ) , ( ( 2 , 0 , 3 , 0 , 3 ) , [Card Club R10 , Card Diamond R9 , Card Diamond R10 , Card Spade R9] ) , ( ( 2 , 0 , 3 , 0 , 4 ) , [Card Club R9 , Card Club R10 , Card Diamond R5 , Card Diamond R10] ) , ( ( 2 , 0 , 3 , 1 , 2 ) , [Card Diamond R9 , Card Diamond R10 , Card Spade R9 , Card Spade Ace] ) , ( ( 2 , 0 , 3 , 1 , 3 ) , [Card Club Ace , Card Diamond R9 , Card Diamond R10 , Card Spade R9] ) , ( ( 2 , 0 , 3 , 1 , 4 ) , [Card Club R9 , Card Club R10 , Card Diamond R9 , Card Diamond Jack] ) , ( ( 2 , 0 , 4 , 0 , 2 ) , [Card Club R5 , Card Diamond R10 , Card Heart R9 , Card Spade R9] ) , ( ( 2 , 0 , 4 , 0 , 3 ) , [Card Club R9 , Card Diamond R5 , Card Diamond R9 , Card Spade R10] ) , ( ( 2 , 0 , 4 , 0 , 4 ) , [Card Club R9 , Card Club R10 , Card Diamond R5 , Card Diamond R9] ) , ( ( 2 , 1 , 2 , 0 , 2 ) , [Card Diamond R9 , Card Diamond R10 , Card Spade R4 , Card Spade R10] ) , ( ( 2 , 1 , 2 , 0 , 3 ) , [Card Club R10 , Card Diamond R9 , Card Diamond R10 , Card Spade R4] ) , ( ( 2 , 1 , 2 , 0 , 4 ) , [Card Club R9 , Card Club R10 , Card Diamond R4 , Card Diamond R10] ) , ( ( 2 , 1 , 2 , 1 , 2 ) , [Card Diamond R9 , Card Diamond R10 , Card Spade R4 , Card Spade Ace] ) , ( ( 2 , 1 , 2 , 1 , 3 ) , [Card Club Ace , Card Diamond R9 , Card Diamond R10 , Card Spade R4] ) , ( ( 2 , 1 , 2 , 1 , 4 ) , [Card Club R9 , Card Club Ace , Card Diamond R4 , Card Diamond R10] ) , ( ( 2 , 1 , 3 , 0 , 2 ) , [Card Diamond R9 , Card Diamond R10 , Card Spade R4 , Card Spade R9] ) , ( ( 2 , 1 , 3 , 0 , 3 ) , [Card Club R9 , Card Diamond R5 , Card Diamond R10 , Card Spade R4] ) , ( ( 2 , 1 , 3 , 0 , 4 ) , [Card Club R4 , Card Club R9 , Card Diamond R5 , Card Diamond R9] ) , ( ( 2 , 2 , 2 , 0 , 2 ) , [Card Diamond R9 , Card Diamond R10 , Card Spade R3 , Card Spade R4] ) , ( ( 2 , 2 , 2 , 0 , 3 ) , [Card Club R9 , Card Diamond R4 , Card Diamond R10 , Card Spade R4] ) , ( ( 2 , 2 , 2 , 0 , 4 ) , [Card Club R4 , Card Club R9 , Card Diamond R4 , Card Diamond R9] ) , ( ( 3 , 0 , 3 , 0 , 3 ) , [Card Club R9 , Card Diamond R9 , Card Diamond R10 , Card Spade R10] ) , ( ( 3 , 0 , 3 , 0 , 4 ) , [Card Club R9 , Card Club R10 , Card Diamond R9 , Card Diamond R10] ) , ( ( 3 , 0 , 3 , 1 , 3 ) , [Card Club R9 , Card Diamond R9 , Card Diamond R10 , Card Spade Jack] ) , ( ( 3 , 0 , 3 , 1 , 4 ) , [Card Club R9 , Card Club Jack , Card Diamond R9 , Card Diamond R10] ) , ( ( 3 , 0 , 4 , 0 , 3 ) , [Card Club R9 , Card Diamond R5 , Card Diamond R9 , Card Diamond R10] ) , ( ( 3 , 1 , 3 , 0 , 3 ) , [Card Club R5 , Card Club R9 , Card Diamond R9 , Card Spade R4] ) , ( ( 3 , 1 , 3 , 0 , 4 ) , [Card Club R5 , Card Club R9 , Card Diamond R4 , Card Diamond R9] ) , ( ( 4 , 0 , 4 , 0 , 4 ) , [Card Club R5 , Card Club R9 , Card Diamond R9 , Card Diamond R10] ) ]
hikui/Cardguess
src/Optimal4.hs
mit
30,846
0
9
10,956
16,112
9,209
6,903
579
1
{-# LANGUAGE TemplateHaskell #-} module NFA.Nerode.Congruent.Instance where import Autolib.Reader import Autolib.ToDoc import Convert.Language import Autolib.Exp import Autolib.NFA ( NFAC ) import Data.Typeable data NFAC c Int => Instance c = Instance { language :: Language c , goal :: [c] , wanted :: Int , minimal_length :: Int } deriving ( Typeable ) $(derives [makeReader, makeToDoc] [''Instance]) example :: Instance Char example = Instance { language = Convert.Language.example , goal = "ab" , wanted = 4 , minimal_length = 6 } -- local variables: -- mode: haskell -- end;
florianpilz/autotool
src/NFA/Nerode/Congruent/Instance.hs
gpl-2.0
696
0
9
205
168
102
66
-1
-1
import Drawing import Exercises import Geometry main = drawPicture myPicture myPicture points = message "Right triangle ABC" {- & faint ( drawPointLabel b' "B'" & drawSegment (b,b') ) -} & drawPointsLabels [a,b,c] ["A","B","C"] & drawSegment (a,b) & drawSegment (b,c) & drawSegment (c,a) where [a,b',c] = take 3 points b = projection (a,b') c
alphalambda/hsmath
src/Learn/Geometry/ex16righttriangle.hs
gpl-2.0
412
0
10
122
134
74
60
12
1
-- Bug: reported by Jan Scheffczyk, November 2004. verzahne :: ( [a] -> [a] -> Bool) -> [a] -> [a] -> [a] verzahne _ xs [] = xs verzahne _ [] ys = ys verzahne le (x:xs) (y:ys) | x `le` y = x : (verzahne le xs (y:ys)) |otherwise = y : (verzahne le (x:xs) ys)
roberth/uu-helium
test/typeerrors/Examples/Verzahne.hs
gpl-3.0
269
0
10
68
162
86
76
6
1
{-# 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.S3.HeadBucket -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- This operation is useful to determine if a bucket exists and you have -- permission to access it. -- -- /See:/ <http://docs.aws.amazon.com/AmazonS3/latest/API/HeadBucket.html AWS API Reference> for HeadBucket. module Network.AWS.S3.HeadBucket ( -- * Creating a Request headBucket , HeadBucket -- * Request Lenses , hbBucket -- * Destructuring the Response , headBucketResponse , HeadBucketResponse ) where import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response import Network.AWS.S3.Types import Network.AWS.S3.Types.Product -- | /See:/ 'headBucket' smart constructor. newtype HeadBucket = HeadBucket' { _hbBucket :: BucketName } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'HeadBucket' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'hbBucket' headBucket :: BucketName -- ^ 'hbBucket' -> HeadBucket headBucket pBucket_ = HeadBucket' { _hbBucket = pBucket_ } -- | Undocumented member. hbBucket :: Lens' HeadBucket BucketName hbBucket = lens _hbBucket (\ s a -> s{_hbBucket = a}); instance AWSRequest HeadBucket where type Rs HeadBucket = HeadBucketResponse request = head' s3 response = receiveNull HeadBucketResponse' instance ToHeaders HeadBucket where toHeaders = const mempty instance ToPath HeadBucket where toPath HeadBucket'{..} = mconcat ["/", toBS _hbBucket] instance ToQuery HeadBucket where toQuery = const mempty -- | /See:/ 'headBucketResponse' smart constructor. data HeadBucketResponse = HeadBucketResponse' deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'HeadBucketResponse' with the minimum fields required to make a request. -- headBucketResponse :: HeadBucketResponse headBucketResponse = HeadBucketResponse'
fmapfmapfmap/amazonka
amazonka-s3/gen/Network/AWS/S3/HeadBucket.hs
mpl-2.0
2,658
0
9
548
340
208
132
48
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Module : Network.AWS.StorageGateway.CancelArchival -- Copyright : (c) 2013-2014 Brendan Hay <[email protected]> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <[email protected]> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | Cancels archiving of a virtual tape to the virtual tape shelf (VTS) after the -- archiving process is initiated. -- -- <http://docs.aws.amazon.com/storagegateway/latest/APIReference/API_CancelArchival.html> module Network.AWS.StorageGateway.CancelArchival ( -- * Request CancelArchival -- ** Request constructor , cancelArchival -- ** Request lenses , caGatewayARN , caTapeARN -- * Response , CancelArchivalResponse -- ** Response constructor , cancelArchivalResponse -- ** Response lenses , carTapeARN ) where import Network.AWS.Data (Object) import Network.AWS.Prelude import Network.AWS.Request.JSON import Network.AWS.StorageGateway.Types import qualified GHC.Exts data CancelArchival = CancelArchival { _caGatewayARN :: Text , _caTapeARN :: Text } deriving (Eq, Ord, Read, Show) -- | 'CancelArchival' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'caGatewayARN' @::@ 'Text' -- -- * 'caTapeARN' @::@ 'Text' -- cancelArchival :: Text -- ^ 'caGatewayARN' -> Text -- ^ 'caTapeARN' -> CancelArchival cancelArchival p1 p2 = CancelArchival { _caGatewayARN = p1 , _caTapeARN = p2 } caGatewayARN :: Lens' CancelArchival Text caGatewayARN = lens _caGatewayARN (\s a -> s { _caGatewayARN = a }) -- | The Amazon Resource Name (ARN) of the virtual tape you want to cancel -- archiving for. caTapeARN :: Lens' CancelArchival Text caTapeARN = lens _caTapeARN (\s a -> s { _caTapeARN = a }) newtype CancelArchivalResponse = CancelArchivalResponse { _carTapeARN :: Maybe Text } deriving (Eq, Ord, Read, Show, Monoid) -- | 'CancelArchivalResponse' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'carTapeARN' @::@ 'Maybe' 'Text' -- cancelArchivalResponse :: CancelArchivalResponse cancelArchivalResponse = CancelArchivalResponse { _carTapeARN = Nothing } -- | The Amazon Resource Name (ARN) of the virtual tape for which archiving was -- canceled. carTapeARN :: Lens' CancelArchivalResponse (Maybe Text) carTapeARN = lens _carTapeARN (\s a -> s { _carTapeARN = a }) instance ToPath CancelArchival where toPath = const "/" instance ToQuery CancelArchival where toQuery = const mempty instance ToHeaders CancelArchival instance ToJSON CancelArchival where toJSON CancelArchival{..} = object [ "GatewayARN" .= _caGatewayARN , "TapeARN" .= _caTapeARN ] instance AWSRequest CancelArchival where type Sv CancelArchival = StorageGateway type Rs CancelArchival = CancelArchivalResponse request = post "CancelArchival" response = jsonResponse instance FromJSON CancelArchivalResponse where parseJSON = withObject "CancelArchivalResponse" $ \o -> CancelArchivalResponse <$> o .:? "TapeARN"
kim/amazonka
amazonka-storagegateway/gen/Network/AWS/StorageGateway/CancelArchival.hs
mpl-2.0
3,908
0
9
866
523
317
206
63
1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} module Tyckiting.AI where import Prelude () import Prelude.Compat import Control.Arrow.Transformer.Automaton import Control.Monad.Random (RandT, runRandT) import Control.Monad.RWS (MonadReader (..), MonadWriter (..), RWS, runRWS) import Data.Aeson (FromJSON (..), withObject, (.:)) import System.Random.TF (TFGen, mkSeedUnix, seedTFGen) import Tyckiting.Action import Tyckiting.Event import Tyckiting.Position import Tyckiting.Types data GameConfig = GameConfig { cfgBotCount :: Word , cfgFieldRadius :: Distance , cfgMove :: Word , cfgStartHp :: Word , cfgCannon :: Word , cfgRadar :: Word , cfgSee :: Word , cfgMaxRound :: RoundNumber , cfgLoopTime :: Word } deriving (Show, Read) instance FromJSON GameConfig where parseJSON = withObject "GameConfig object" $ \v -> GameConfig <$> v .: "bots" <*> v .: "fieldRadius" <*> v .: "move" <*> v .: "startHp" <*> v .: "cannon" <*> v .: "radar" <*> v .: "see" <*> (RoundNumber <$> v .: "maxCount") <*> v .: "loopTime" -- | Game state. TBD data GameState = GameState { gsRoundNumber :: RoundNumber , gsGameConfig :: GameConfig , gsYourTeam :: Team WithHpAndPos , gsOtherTeams :: [Team WithNoExtra] } deriving (Show) instance FromJSON GameState where parseJSON = withObject "GameState object" $ \v -> GameState <$> v .: "roundId" <*> v .: "config" <*> v .: "you" <*> v .: "otherTeams" -- | Immutable (per-turn) context. type GameContext = (GameState, [Event]) -- | AI type is @(GameState, [Event], UserState) -> (Move, UserState, [String])@. -- Yet everything is hidden into monad transformer stack type AIMonad us = RWS (GameState, [Event]) [String] us runAIMonad :: AIMonad us a -> GameContext -> us -> (a, us, [String]) runAIMonad = runRWS type NDAIMonad us = RandT TFGen (AIMonad us) runNDAIMonad :: NDAIMonad us a -> GameContext -> us -> TFGen -> (a, us, [String], TFGen) runNDAIMonad m r s g = sliceIn $ runRWS (runRandT m g) r s where sliceIn ((a, g'), s', w') = (a, s', w', g') -- | Ask for this turn state. -- -- @ -- askGameState :: AIMonad us GameState -- askGameState :: NDAIMonad us GameState -- @ askGameState :: (Functor m, MonadReader GameContext m) => m GameState askGameState = fst <$> ask -- | Aks for the game config -- -- @ -- askGameConfig :: AIMonad us GameConfig -- askGameConfig :: NDAIMonad us GameConfig -- @ askGameConfig :: (Functor m, MonadReader GameContext m) => m GameConfig askGameConfig = gsGameConfig <$> askGameState -- | Ask for this turn's events. -- -- @ -- askEvents :: AIMonad us [Event] -- askEvents :: NDAIMonad us [Event] -- @ askEvents :: (Functor m, MonadReader GameContext m) => m [Event] askEvents = snd <$> ask -- | Add a string to be logged by client. -- -- @ -- tellLog :: String -> AIMonad us () -- tellLog :: String -> NDAIMonad us () -- @ tellLog :: MonadWriter [String] m => String -> m () tellLog str = tell [str] tellShow :: (MonadWriter [String] m, Show a) => a -> m () tellShow = tellLog . show type AI = GameConfig -> IO AIAutomaton type Response = [Action] mkAI :: AIMonad us Response -> (GameConfig -> IO us) -> AI mkAI aimonad mkInitialState gameConfig = aiToArrowAI aimonad `fmap` mkInitialState gameConfig mkNDAI :: NDAIMonad us Response -> (GameConfig -> IO us) -> AI mkNDAI aimonad mkInitialState gameConfig = ndaiToArrowAI aimonad <$> g <*> mkInitialState gameConfig where g = seedTFGen <$> mkSeedUnix -- | AI type with UserState hidden. type AIAutomaton = Automaton (->) GameContext (Response, [String]) runArrowAI :: AIAutomaton -> GameContext -> (Response, [String], AIAutomaton) runArrowAI (Automaton aut) ctx = sliceIn $ aut ctx where sliceIn ((a, b), c) = (a, b, c) -- | Transform `AIMonad` to non-existential function (i.e. hide user state from the type). aiToArrowAI :: AIMonad us Response -> us -> AIAutomaton aiToArrowAI ai initialState = Automaton $ auto initialState where auto us ctx = let (move, us', logs) = runAIMonad ai ctx us in ((move, logs), Automaton $ auto us') -- | Transform `NDAIMonad` to non-existential function. ndaiToArrowAI :: NDAIMonad us Response -> TFGen -> us -> AIAutomaton ndaiToArrowAI ai initialGen initialState = Automaton $ auto initialGen initialState where auto g us ctx = let (move, us', logs, g') = runNDAIMonad ai ctx us g in ((move, logs), Automaton $ auto g' us')
vvmann/tyckiting-bot
clients/haskell/src/Tyckiting/AI.hs
mit
4,634
0
24
1,041
1,287
728
559
90
1
{-# OPTIONS -fno-warn-tabs #-} -- The above warning supression flag is a temporary kludge. -- While working on this module you are encouraged to remove it and -- detab the module (please do the detabbing in a separate patch). See -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#TabsvsSpaces -- for details module Vectorise.Monad.Local ( readLEnv, setLEnv, updLEnv, localV, closedV, getBindName, inBind, lookupTyVarPA, defLocalTyVar, defLocalTyVarWithPA, localTyVars ) where import Vectorise.Monad.Base import Vectorise.Env import CoreSyn import Name import VarEnv import Var import FastString -- Local Environment ---------------------------------------------------------- -- | Project something from the local environment. readLEnv :: (LocalEnv -> a) -> VM a readLEnv f = VM $ \_ genv lenv -> return (Yes genv lenv (f lenv)) -- | Set the local environment. setLEnv :: LocalEnv -> VM () setLEnv lenv = VM $ \_ genv _ -> return (Yes genv lenv ()) -- | Update the enviroment using the provided function. updLEnv :: (LocalEnv -> LocalEnv) -> VM () updLEnv f = VM $ \_ genv lenv -> return (Yes genv (f lenv) ()) -- | Perform a computation in its own local environment. -- This does not alter the environment of the current state. localV :: VM a -> VM a localV p = do env <- readLEnv id x <- p setLEnv env return x -- | Perform a computation in an empty local environment. closedV :: VM a -> VM a closedV p = do env <- readLEnv id setLEnv (emptyLocalEnv { local_bind_name = local_bind_name env }) x <- p setLEnv env return x -- | Get the name of the local binding currently being vectorised. getBindName :: VM FastString getBindName = readLEnv local_bind_name -- | Run a vectorisation computation in a local environment, -- with this id set as the current binding. inBind :: Id -> VM a -> VM a inBind id p = do updLEnv $ \env -> env { local_bind_name = occNameFS (getOccName id) } p -- | Lookup a PA tyvars from the local environment. lookupTyVarPA :: Var -> VM (Maybe CoreExpr) lookupTyVarPA tv = readLEnv $ \env -> lookupVarEnv (local_tyvar_pa env) tv -- | Add a tyvar to the local environment. defLocalTyVar :: TyVar -> VM () defLocalTyVar tv = updLEnv $ \env -> env { local_tyvars = tv : local_tyvars env , local_tyvar_pa = local_tyvar_pa env `delVarEnv` tv } -- | Add mapping between a tyvar and pa dictionary to the local environment. defLocalTyVarWithPA :: TyVar -> CoreExpr -> VM () defLocalTyVarWithPA tv pa = updLEnv $ \env -> env { local_tyvars = tv : local_tyvars env , local_tyvar_pa = extendVarEnv (local_tyvar_pa env) tv pa } -- | Get the set of tyvars from the local environment. localTyVars :: VM [TyVar] localTyVars = readLEnv (reverse . local_tyvars)
nomeata/ghc
compiler/vectorise/Vectorise/Monad/Local.hs
bsd-3-clause
2,786
42
13
553
695
371
324
58
1
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 Desugaring exporessions. -} {-# LANGUAGE CPP #-} module DsExpr ( dsExpr, dsLExpr, dsLocalBinds, dsValBinds, dsLit ) where #include "HsVersions.h" import Match import MatchLit import DsBinds import DsGRHSs import DsListComp import DsUtils import DsArrows import DsMonad import Name import NameEnv import FamInstEnv( topNormaliseType ) #ifdef GHCI -- Template Haskell stuff iff bootstrapped import DsMeta #endif import HsSyn import Platform -- NB: The desugarer, which straddles the source and Core worlds, sometimes -- needs to see source types import TcType import Coercion ( Role(..) ) import TcEvidence import TcRnMonad import Type import CoreSyn import CoreUtils import CoreFVs import MkCore import DynFlags import CostCentre import Id import Module import VarSet import VarEnv import ConLike import DataCon import TysWiredIn import PrelNames import BasicTypes import Maybes import SrcLoc import Util import Bag import Outputable import FastString import IdInfo import Data.IORef ( atomicModifyIORef, modifyIORef ) import Control.Monad import GHC.Fingerprint {- ************************************************************************ * * dsLocalBinds, dsValBinds * * ************************************************************************ -} dsLocalBinds :: HsLocalBinds Id -> CoreExpr -> DsM CoreExpr dsLocalBinds EmptyLocalBinds body = return body dsLocalBinds (HsValBinds binds) body = dsValBinds binds body dsLocalBinds (HsIPBinds binds) body = dsIPBinds binds body ------------------------- dsValBinds :: HsValBinds Id -> CoreExpr -> DsM CoreExpr dsValBinds (ValBindsOut binds _) body = foldrM ds_val_bind body binds dsValBinds (ValBindsIn _ _) _ = panic "dsValBinds ValBindsIn" ------------------------- dsIPBinds :: HsIPBinds Id -> CoreExpr -> DsM CoreExpr dsIPBinds (IPBinds ip_binds ev_binds) body = do { ds_binds <- dsTcEvBinds ev_binds ; let inner = mkCoreLets ds_binds body -- The dict bindings may not be in -- dependency order; hence Rec ; foldrM ds_ip_bind inner ip_binds } where ds_ip_bind (L _ (IPBind ~(Right n) e)) body = do e' <- dsLExpr e return (Let (NonRec n e') body) ------------------------- ds_val_bind :: (RecFlag, LHsBinds Id) -> CoreExpr -> DsM CoreExpr -- Special case for bindings which bind unlifted variables -- We need to do a case right away, rather than building -- a tuple and doing selections. -- Silently ignore INLINE and SPECIALISE pragmas... ds_val_bind (NonRecursive, hsbinds) body | [L loc bind] <- bagToList hsbinds, -- Non-recursive, non-overloaded bindings only come in ones -- ToDo: in some bizarre case it's conceivable that there -- could be dict binds in the 'binds'. (See the notes -- below. Then pattern-match would fail. Urk.) strictMatchOnly bind = putSrcSpanDs loc (dsStrictBind bind body) -- Ordinary case for bindings; none should be unlifted ds_val_bind (_is_rec, binds) body = do { prs <- dsLHsBinds binds ; ASSERT2( not (any (isUnLiftedType . idType . fst) prs), ppr _is_rec $$ ppr binds ) case prs of [] -> return body _ -> return (Let (Rec prs) body) } -- Use a Rec regardless of is_rec. -- Why? Because it allows the binds to be all -- mixed up, which is what happens in one rare case -- Namely, for an AbsBind with no tyvars and no dicts, -- but which does have dictionary bindings. -- See notes with TcSimplify.inferLoop [NO TYVARS] -- It turned out that wrapping a Rec here was the easiest solution -- -- NB The previous case dealt with unlifted bindings, so we -- only have to deal with lifted ones now; so Rec is ok ------------------ dsStrictBind :: HsBind Id -> CoreExpr -> DsM CoreExpr dsStrictBind (AbsBinds { abs_tvs = [], abs_ev_vars = [] , abs_exports = exports , abs_ev_binds = ev_binds , abs_binds = lbinds }) body = do { let body1 = foldr bind_export body exports bind_export export b = bindNonRec (abe_poly export) (Var (abe_mono export)) b ; body2 <- foldlBagM (\body lbind -> dsStrictBind (unLoc lbind) body) body1 lbinds ; ds_binds <- dsTcEvBinds ev_binds ; return (mkCoreLets ds_binds body2) } dsStrictBind (FunBind { fun_id = L _ fun, fun_matches = matches, fun_co_fn = co_fn , fun_tick = tick, fun_infix = inf }) body -- Can't be a bang pattern (that looks like a PatBind) -- so must be simply unboxed = do { (args, rhs) <- matchWrapper (FunRhs (idName fun ) inf) matches ; MASSERT( null args ) -- Functions aren't lifted ; MASSERT( isIdHsWrapper co_fn ) ; let rhs' = mkOptTickBox tick rhs ; return (bindNonRec fun rhs' body) } dsStrictBind (PatBind {pat_lhs = pat, pat_rhs = grhss, pat_rhs_ty = ty }) body = -- let C x# y# = rhs in body -- ==> case rhs of C x# y# -> body do { rhs <- dsGuarded grhss ty ; let upat = unLoc pat eqn = EqnInfo { eqn_pats = [upat], eqn_rhs = cantFailMatchResult body } ; var <- selectMatchVar upat ; result <- matchEquations PatBindRhs [var] [eqn] (exprType body) ; return (bindNonRec var rhs result) } dsStrictBind bind body = pprPanic "dsLet: unlifted" (ppr bind $$ ppr body) ---------------------- strictMatchOnly :: HsBind Id -> Bool strictMatchOnly (AbsBinds { abs_binds = lbinds }) = anyBag (strictMatchOnly . unLoc) lbinds strictMatchOnly (PatBind { pat_lhs = lpat, pat_rhs_ty = rhs_ty }) = isUnLiftedType rhs_ty || isStrictLPat lpat || any (isUnLiftedType . idType) (collectPatBinders lpat) strictMatchOnly (FunBind { fun_id = L _ id }) = isUnLiftedType (idType id) strictMatchOnly _ = False -- I hope! Checked immediately by caller in fact {- ************************************************************************ * * \subsection[DsExpr-vars-and-cons]{Variables, constructors, literals} * * ************************************************************************ -} dsLExpr :: LHsExpr Id -> DsM CoreExpr dsLExpr (L loc e) = putSrcSpanDs loc $ dsExpr e dsExpr :: HsExpr Id -> DsM CoreExpr dsExpr (HsPar e) = dsLExpr e dsExpr (ExprWithTySigOut e _) = dsLExpr e dsExpr (HsVar var) = return (varToCoreExpr var) -- See Note [Desugaring vars] dsExpr (HsIPVar _) = panic "dsExpr: HsIPVar" dsExpr (HsLit lit) = dsLit lit dsExpr (HsOverLit lit) = dsOverLit lit dsExpr (HsWrap co_fn e) = do { e' <- dsExpr e ; wrapped_e <- dsHsWrapper co_fn e' ; dflags <- getDynFlags ; warnAboutIdentities dflags e' (exprType wrapped_e) ; return wrapped_e } dsExpr (NegApp expr neg_expr) = App <$> dsExpr neg_expr <*> dsLExpr expr dsExpr (HsLam a_Match) = uncurry mkLams <$> matchWrapper LambdaExpr a_Match dsExpr (HsLamCase arg matches) = do { arg_var <- newSysLocalDs arg ; ([discrim_var], matching_code) <- matchWrapper CaseAlt matches ; return $ Lam arg_var $ bindNonRec discrim_var (Var arg_var) matching_code } dsExpr (HsApp fun arg) = mkCoreAppDs <$> dsLExpr fun <*> dsLExpr arg dsExpr (HsUnboundVar _) = panic "dsExpr: HsUnboundVar" {- Note [Desugaring vars] ~~~~~~~~~~~~~~~~~~~~~~ In one situation we can get a *coercion* variable in a HsVar, namely the support method for an equality superclass: class (a~b) => C a b where ... instance (blah) => C (T a) (T b) where .. Then we get $dfCT :: forall ab. blah => C (T a) (T b) $dfCT ab blah = MkC ($c$p1C a blah) ($cop a blah) $c$p1C :: forall ab. blah => (T a ~ T b) $c$p1C ab blah = let ...; g :: T a ~ T b = ... } in g That 'g' in the 'in' part is an evidence variable, and when converting to core it must become a CO. Operator sections. At first it looks as if we can convert \begin{verbatim} (expr op) \end{verbatim} to \begin{verbatim} \x -> op expr x \end{verbatim} But no! expr might be a redex, and we can lose laziness badly this way. Consider \begin{verbatim} map (expr op) xs \end{verbatim} for example. So we convert instead to \begin{verbatim} let y = expr in \x -> op y x \end{verbatim} If \tr{expr} is actually just a variable, say, then the simplifier will sort it out. -} dsExpr (OpApp e1 op _ e2) = -- for the type of y, we need the type of op's 2nd argument mkCoreAppsDs <$> dsLExpr op <*> mapM dsLExpr [e1, e2] dsExpr (SectionL expr op) -- Desugar (e !) to ((!) e) = mkCoreAppDs <$> dsLExpr op <*> dsLExpr expr -- dsLExpr (SectionR op expr) -- \ x -> op x expr dsExpr (SectionR op expr) = do core_op <- dsLExpr op -- for the type of x, we need the type of op's 2nd argument let (x_ty:y_ty:_, _) = splitFunTys (exprType core_op) -- See comment with SectionL y_core <- dsLExpr expr x_id <- newSysLocalDs x_ty y_id <- newSysLocalDs y_ty return (bindNonRec y_id y_core $ Lam x_id (mkCoreAppsDs core_op [Var x_id, Var y_id])) dsExpr (ExplicitTuple tup_args boxity) = do { let go (lam_vars, args) (L _ (Missing ty)) -- For every missing expression, we need -- another lambda in the desugaring. = do { lam_var <- newSysLocalDs ty ; return (lam_var : lam_vars, Var lam_var : args) } go (lam_vars, args) (L _ (Present expr)) -- Expressions that are present don't generate -- lambdas, just arguments. = do { core_expr <- dsLExpr expr ; return (lam_vars, core_expr : args) } ; (lam_vars, args) <- foldM go ([], []) (reverse tup_args) -- The reverse is because foldM goes left-to-right ; return $ mkCoreLams lam_vars $ mkCoreConApps (tupleCon (boxityNormalTupleSort boxity) (length tup_args)) (map (Type . exprType) args ++ args) } dsExpr (HsSCC _ cc expr@(L loc _)) = do dflags <- getDynFlags if gopt Opt_SccProfilingOn dflags then do mod_name <- getModule count <- goptM Opt_ProfCountEntries uniq <- newUnique Tick (ProfNote (mkUserCC cc mod_name loc uniq) count True) <$> dsLExpr expr else dsLExpr expr dsExpr (HsCoreAnn _ _ expr) = dsLExpr expr dsExpr (HsCase discrim matches) = do { core_discrim <- dsLExpr discrim ; ([discrim_var], matching_code) <- matchWrapper CaseAlt matches ; return (bindNonRec discrim_var core_discrim matching_code) } -- Pepe: The binds are in scope in the body but NOT in the binding group -- This is to avoid silliness in breakpoints dsExpr (HsLet binds body) = do body' <- dsLExpr body dsLocalBinds binds body' -- We need the `ListComp' form to use `deListComp' (rather than the "do" form) -- because the interpretation of `stmts' depends on what sort of thing it is. -- dsExpr (HsDo ListComp stmts res_ty) = dsListComp stmts res_ty dsExpr (HsDo PArrComp stmts _) = dsPArrComp (map unLoc stmts) dsExpr (HsDo DoExpr stmts _) = dsDo stmts dsExpr (HsDo GhciStmtCtxt stmts _) = dsDo stmts dsExpr (HsDo MDoExpr stmts _) = dsDo stmts dsExpr (HsDo MonadComp stmts _) = dsMonadComp stmts dsExpr (HsIf mb_fun guard_expr then_expr else_expr) = do { pred <- dsLExpr guard_expr ; b1 <- dsLExpr then_expr ; b2 <- dsLExpr else_expr ; case mb_fun of Just fun -> do { core_fun <- dsExpr fun ; return (mkCoreApps core_fun [pred,b1,b2]) } Nothing -> return $ mkIfThenElse pred b1 b2 } dsExpr (HsMultiIf res_ty alts) | null alts = mkErrorExpr | otherwise = do { match_result <- liftM (foldr1 combineMatchResults) (mapM (dsGRHS IfAlt res_ty) alts) ; error_expr <- mkErrorExpr ; extractMatchResult match_result error_expr } where mkErrorExpr = mkErrorAppDs nON_EXHAUSTIVE_GUARDS_ERROR_ID res_ty (ptext (sLit "multi-way if")) {- \noindent \underline{\bf Various data construction things} ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -} dsExpr (ExplicitList elt_ty wit xs) = dsExplicitList elt_ty wit xs -- We desugar [:x1, ..., xn:] as -- singletonP x1 +:+ ... +:+ singletonP xn -- dsExpr (ExplicitPArr ty []) = do emptyP <- dsDPHBuiltin emptyPVar return (Var emptyP `App` Type ty) dsExpr (ExplicitPArr ty xs) = do singletonP <- dsDPHBuiltin singletonPVar appP <- dsDPHBuiltin appPVar xs' <- mapM dsLExpr xs return . foldr1 (binary appP) $ map (unary singletonP) xs' where unary fn x = mkApps (Var fn) [Type ty, x] binary fn x y = mkApps (Var fn) [Type ty, x, y] dsExpr (ArithSeq expr witness seq) = case witness of Nothing -> dsArithSeq expr seq Just fl -> do { ; fl' <- dsExpr fl ; newArithSeq <- dsArithSeq expr seq ; return (App fl' newArithSeq)} dsExpr (PArrSeq expr (FromTo from to)) = mkApps <$> dsExpr expr <*> mapM dsLExpr [from, to] dsExpr (PArrSeq expr (FromThenTo from thn to)) = mkApps <$> dsExpr expr <*> mapM dsLExpr [from, thn, to] dsExpr (PArrSeq _ _) = panic "DsExpr.dsExpr: Infinite parallel array!" -- the parser shouldn't have generated it and the renamer and typechecker -- shouldn't have let it through {- \noindent \underline{\bf Static Pointers} ~~~~~~~~~~~~~~~ \begin{verbatim} g = ... static f ... ==> sptEntry:N = StaticPtr (fingerprintString "pkgKey:module.sptEntry:N") (StaticPtrInfo "current pkg key" "current module" "sptEntry:0") f g = ... sptEntry:N \end{verbatim} -} dsExpr (HsStatic expr@(L loc _)) = do expr_ds <- dsLExpr expr let ty = exprType expr_ds n' <- mkSptEntryName loc static_binds_var <- dsGetStaticBindsVar staticPtrTyCon <- dsLookupTyCon staticPtrTyConName staticPtrInfoDataCon <- dsLookupDataCon staticPtrInfoDataConName staticPtrDataCon <- dsLookupDataCon staticPtrDataConName fingerprintDataCon <- dsLookupDataCon fingerprintDataConName dflags <- getDynFlags let (line, col) = case loc of RealSrcSpan r -> ( srcLocLine $ realSrcSpanStart r , srcLocCol $ realSrcSpanStart r ) _ -> (0, 0) srcLoc = mkCoreConApps (tupleCon BoxedTuple 2) [ Type intTy , Type intTy , mkIntExprInt dflags line, mkIntExprInt dflags col ] info <- mkConApp staticPtrInfoDataCon <$> (++[srcLoc]) <$> mapM mkStringExprFS [ packageKeyFS $ modulePackageKey $ nameModule n' , moduleNameFS $ moduleName $ nameModule n' , occNameFS $ nameOccName n' ] let tvars = varSetElems $ tyVarsOfType ty speTy = mkForAllTys tvars $ mkTyConApp staticPtrTyCon [ty] speId = mkExportedLocalId VanillaId n' speTy fp@(Fingerprint w0 w1) = fingerprintName $ idName speId fp_core = mkConApp fingerprintDataCon [ mkWord64LitWordRep dflags w0 , mkWord64LitWordRep dflags w1 ] sp = mkConApp staticPtrDataCon [Type ty, fp_core, info, expr_ds] liftIO $ modifyIORef static_binds_var ((fp, (speId, mkLams tvars sp)) :) putSrcSpanDs loc $ return $ mkTyApps (Var speId) (map mkTyVarTy tvars) where -- | Choose either 'Word64#' or 'Word#' to represent the arguments of the -- 'Fingerprint' data constructor. mkWord64LitWordRep dflags | platformWordSize (targetPlatform dflags) < 8 = mkWord64LitWord64 | otherwise = mkWordLit dflags . toInteger fingerprintName :: Name -> Fingerprint fingerprintName n = fingerprintString $ unpackFS $ concatFS [ packageKeyFS $ modulePackageKey $ nameModule n , fsLit ":" , moduleNameFS (moduleName $ nameModule n) , fsLit "." , occNameFS $ occName n ] {- \noindent \underline{\bf Record construction and update} ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ For record construction we do this (assuming T has three arguments) \begin{verbatim} T { op2 = e } ==> let err = /\a -> recConErr a T (recConErr t1 "M.lhs/230/op1") e (recConErr t1 "M.lhs/230/op3") \end{verbatim} @recConErr@ then converts its arugment string into a proper message before printing it as \begin{verbatim} M.lhs, line 230: missing field op1 was evaluated \end{verbatim} We also handle @C{}@ as valid construction syntax for an unlabelled constructor @C@, setting all of @C@'s fields to bottom. -} dsExpr (RecordCon (L _ data_con_id) con_expr rbinds) = do con_expr' <- dsExpr con_expr let (arg_tys, _) = tcSplitFunTys (exprType con_expr') -- A newtype in the corner should be opaque; -- hence TcType.tcSplitFunTys mk_arg (arg_ty, lbl) -- Selector id has the field label as its name = case findField (rec_flds rbinds) lbl of (rhs:rhss) -> ASSERT( null rhss ) dsLExpr rhs [] -> mkErrorAppDs rEC_CON_ERROR_ID arg_ty (ppr lbl) unlabelled_bottom arg_ty = mkErrorAppDs rEC_CON_ERROR_ID arg_ty Outputable.empty labels = dataConFieldLabels (idDataCon data_con_id) -- The data_con_id is guaranteed to be the wrapper id of the constructor con_args <- if null labels then mapM unlabelled_bottom arg_tys else mapM mk_arg (zipEqual "dsExpr:RecordCon" arg_tys labels) return (mkCoreApps con_expr' con_args) {- Record update is a little harder. Suppose we have the decl: \begin{verbatim} data T = T1 {op1, op2, op3 :: Int} | T2 {op4, op2 :: Int} | T3 \end{verbatim} Then we translate as follows: \begin{verbatim} r { op2 = e } ===> let op2 = e in case r of T1 op1 _ op3 -> T1 op1 op2 op3 T2 op4 _ -> T2 op4 op2 other -> recUpdError "M.lhs/230" \end{verbatim} It's important that we use the constructor Ids for @T1@, @T2@ etc on the RHSs, and do not generate a Core constructor application directly, because the constructor might do some argument-evaluation first; and may have to throw away some dictionaries. Note [Update for GADTs] ~~~~~~~~~~~~~~~~~~~~~~~ Consider data T a b where T1 { f1 :: a } :: T a Int Then the wrapper function for T1 has type $WT1 :: a -> T a Int But if x::T a b, then x { f1 = v } :: T a b (not T a Int!) So we need to cast (T a Int) to (T a b). Sigh. -} dsExpr expr@(RecordUpd record_expr (HsRecFields { rec_flds = fields }) cons_to_upd in_inst_tys out_inst_tys) | null fields = dsLExpr record_expr | otherwise = ASSERT2( notNull cons_to_upd, ppr expr ) do { record_expr' <- dsLExpr record_expr ; field_binds' <- mapM ds_field fields ; let upd_fld_env :: NameEnv Id -- Maps field name to the LocalId of the field binding upd_fld_env = mkNameEnv [(f,l) | (f,l,_) <- field_binds'] -- It's important to generate the match with matchWrapper, -- and the right hand sides with applications of the wrapper Id -- so that everything works when we are doing fancy unboxing on the -- constructor aguments. ; alts <- mapM (mk_alt upd_fld_env) cons_to_upd ; ([discrim_var], matching_code) <- matchWrapper RecUpd (MG { mg_alts = alts, mg_arg_tys = [in_ty] , mg_res_ty = out_ty, mg_origin = FromSource }) -- FromSource is not strictly right, but we -- want incomplete pattern-match warnings ; return (add_field_binds field_binds' $ bindNonRec discrim_var record_expr' matching_code) } where ds_field :: LHsRecField Id (LHsExpr Id) -> DsM (Name, Id, CoreExpr) -- Clone the Id in the HsRecField, because its Name is that -- of the record selector, and we must not make that a lcoal binder -- else we shadow other uses of the record selector -- Hence 'lcl_id'. Cf Trac #2735 ds_field (L _ rec_field) = do { rhs <- dsLExpr (hsRecFieldArg rec_field) ; let fld_id = unLoc (hsRecFieldId rec_field) ; lcl_id <- newSysLocalDs (idType fld_id) ; return (idName fld_id, lcl_id, rhs) } add_field_binds [] expr = expr add_field_binds ((_,b,r):bs) expr = bindNonRec b r (add_field_binds bs expr) -- Awkwardly, for families, the match goes -- from instance type to family type tycon = dataConTyCon (head cons_to_upd) in_ty = mkTyConApp tycon in_inst_tys out_ty = mkFamilyTyConApp tycon out_inst_tys mk_alt upd_fld_env con = do { let (univ_tvs, ex_tvs, eq_spec, theta, arg_tys, _) = dataConFullSig con subst = mkTopTvSubst (univ_tvs `zip` in_inst_tys) -- I'm not bothering to clone the ex_tvs ; eqs_vars <- mapM newPredVarDs (substTheta subst (eqSpecPreds eq_spec)) ; theta_vars <- mapM newPredVarDs (substTheta subst theta) ; arg_ids <- newSysLocalsDs (substTys subst arg_tys) ; let val_args = zipWithEqual "dsExpr:RecordUpd" mk_val_arg (dataConFieldLabels con) arg_ids mk_val_arg field_name pat_arg_id = nlHsVar (lookupNameEnv upd_fld_env field_name `orElse` pat_arg_id) inst_con = noLoc $ HsWrap wrap (HsVar (dataConWrapId con)) -- Reconstruct with the WrapId so that unpacking happens wrap = mkWpEvVarApps theta_vars <.> mkWpTyApps (mkTyVarTys ex_tvs) <.> mkWpTyApps [ty | (tv, ty) <- univ_tvs `zip` out_inst_tys , not (tv `elemVarEnv` wrap_subst) ] rhs = foldl (\a b -> nlHsApp a b) inst_con val_args -- Tediously wrap the application in a cast -- Note [Update for GADTs] wrap_co = mkTcTyConAppCo Nominal tycon [ lookup tv ty | (tv,ty) <- univ_tvs `zip` out_inst_tys ] lookup univ_tv ty = case lookupVarEnv wrap_subst univ_tv of Just co' -> co' Nothing -> mkTcReflCo Nominal ty wrap_subst = mkVarEnv [ (tv, mkTcSymCo (mkTcCoVarCo eq_var)) | ((tv,_),eq_var) <- eq_spec `zip` eqs_vars ] pat = noLoc $ ConPatOut { pat_con = noLoc (RealDataCon con) , pat_tvs = ex_tvs , pat_dicts = eqs_vars ++ theta_vars , pat_binds = emptyTcEvBinds , pat_args = PrefixCon $ map nlVarPat arg_ids , pat_arg_tys = in_inst_tys , pat_wrap = idHsWrapper } ; let wrapped_rhs | null eq_spec = rhs | otherwise = mkLHsWrap (mkWpCast (mkTcSubCo wrap_co)) rhs ; return (mkSimpleMatch [pat] wrapped_rhs) } -- Here is where we desugar the Template Haskell brackets and escapes -- Template Haskell stuff dsExpr (HsRnBracketOut _ _) = panic "dsExpr HsRnBracketOut" #ifdef GHCI dsExpr (HsTcBracketOut x ps) = dsBracket x ps #else dsExpr (HsTcBracketOut _ _) = panic "dsExpr HsBracketOut" #endif dsExpr (HsSpliceE _ s) = pprPanic "dsExpr:splice" (ppr s) -- Arrow notation extension dsExpr (HsProc pat cmd) = dsProcExpr pat cmd -- Hpc Support dsExpr (HsTick tickish e) = do e' <- dsLExpr e return (Tick tickish e') -- There is a problem here. The then and else branches -- have no free variables, so they are open to lifting. -- We need someway of stopping this. -- This will make no difference to binary coverage -- (did you go here: YES or NO), but will effect accurate -- tick counting. dsExpr (HsBinTick ixT ixF e) = do e2 <- dsLExpr e do { ASSERT(exprType e2 `eqType` boolTy) mkBinaryTickBox ixT ixF e2 } dsExpr (HsTickPragma _ _ expr) = do dflags <- getDynFlags if gopt Opt_Hpc dflags then panic "dsExpr:HsTickPragma" else dsLExpr expr -- HsSyn constructs that just shouldn't be here: dsExpr (ExprWithTySig {}) = panic "dsExpr:ExprWithTySig" dsExpr (HsBracket {}) = panic "dsExpr:HsBracket" dsExpr (HsQuasiQuoteE {}) = panic "dsExpr:HsQuasiQuoteE" dsExpr (HsArrApp {}) = panic "dsExpr:HsArrApp" dsExpr (HsArrForm {}) = panic "dsExpr:HsArrForm" dsExpr (EWildPat {}) = panic "dsExpr:EWildPat" dsExpr (EAsPat {}) = panic "dsExpr:EAsPat" dsExpr (EViewPat {}) = panic "dsExpr:EViewPat" dsExpr (ELazyPat {}) = panic "dsExpr:ELazyPat" dsExpr (HsType {}) = panic "dsExpr:HsType" dsExpr (HsDo {}) = panic "dsExpr:HsDo" findField :: [LHsRecField Id arg] -> Name -> [arg] findField rbinds lbl = [rhs | L _ (HsRecField { hsRecFieldId = id, hsRecFieldArg = rhs }) <- rbinds , lbl == idName (unLoc id) ] {- %-------------------------------------------------------------------- Note [Desugaring explicit lists] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Explicit lists are desugared in a cleverer way to prevent some fruitless allocations. Essentially, whenever we see a list literal [x_1, ..., x_n] we: 1. Find the tail of the list that can be allocated statically (say [x_k, ..., x_n]) by later stages and ensure we desugar that normally: this makes sure that we don't cause a code size increase by having the cons in that expression fused (see later) and hence being unable to statically allocate any more 2. For the prefix of the list which cannot be allocated statically, say [x_1, ..., x_(k-1)], we turn it into an expression involving build so that if we find any foldrs over it it will fuse away entirely! So in this example we will desugar to: build (\c n -> x_1 `c` x_2 `c` .... `c` foldr c n [x_k, ..., x_n] If fusion fails to occur then build will get inlined and (since we defined a RULE for foldr (:) []) we will get back exactly the normal desugaring for an explicit list. This optimisation can be worth a lot: up to 25% of the total allocation in some nofib programs. Specifically Program Size Allocs Runtime CompTime rewrite +0.0% -26.3% 0.02 -1.8% ansi -0.3% -13.8% 0.00 +0.0% lift +0.0% -8.7% 0.00 -2.3% Of course, if rules aren't turned on then there is pretty much no point doing this fancy stuff, and it may even be harmful. =======> Note by SLPJ Dec 08. I'm unconvinced that we should *ever* generate a build for an explicit list. See the comments in GHC.Base about the foldr/cons rule, which points out that (foldr k z [a,b,c]) may generate *much* less code than (a `k` b `k` c `k` z). Furthermore generating builds messes up the LHS of RULES. Example: the foldr/single rule in GHC.Base foldr k z [x] = ... We do not want to generate a build invocation on the LHS of this RULE! We fix this by disabling rules in rule LHSs, and testing that flag here; see Note [Desugaring RULE left hand sides] in Desugar To test this I've added a (static) flag -fsimple-list-literals, which makes all list literals be generated via the simple route. -} dsExplicitList :: PostTc Id Type -> Maybe (SyntaxExpr Id) -> [LHsExpr Id] -> DsM CoreExpr -- See Note [Desugaring explicit lists] dsExplicitList elt_ty Nothing xs = do { dflags <- getDynFlags ; xs' <- mapM dsLExpr xs ; let (dynamic_prefix, static_suffix) = spanTail is_static xs' ; if gopt Opt_SimpleListLiterals dflags -- -fsimple-list-literals || not (gopt Opt_EnableRewriteRules dflags) -- Rewrite rules off -- Don't generate a build if there are no rules to eliminate it! -- See Note [Desugaring RULE left hand sides] in Desugar || null dynamic_prefix -- Avoid build (\c n. foldr c n xs)! then return $ mkListExpr elt_ty xs' else mkBuildExpr elt_ty (mkSplitExplicitList dynamic_prefix static_suffix) } where is_static :: CoreExpr -> Bool is_static e = all is_static_var (varSetElems (exprFreeVars e)) is_static_var :: Var -> Bool is_static_var v | isId v = isExternalName (idName v) -- Top-level things are given external names | otherwise = False -- Type variables mkSplitExplicitList prefix suffix (c, _) (n, n_ty) = do { let suffix' = mkListExpr elt_ty suffix ; folded_suffix <- mkFoldrExpr elt_ty n_ty (Var c) (Var n) suffix' ; return (foldr (App . App (Var c)) folded_suffix prefix) } dsExplicitList elt_ty (Just fln) xs = do { fln' <- dsExpr fln ; list <- dsExplicitList elt_ty Nothing xs ; dflags <- getDynFlags ; return (App (App fln' (mkIntExprInt dflags (length xs))) list) } spanTail :: (a -> Bool) -> [a] -> ([a], [a]) spanTail f xs = (reverse rejected, reverse satisfying) where (satisfying, rejected) = span f $ reverse xs dsArithSeq :: PostTcExpr -> (ArithSeqInfo Id) -> DsM CoreExpr dsArithSeq expr (From from) = App <$> dsExpr expr <*> dsLExpr from dsArithSeq expr (FromTo from to) = do dflags <- getDynFlags warnAboutEmptyEnumerations dflags from Nothing to expr' <- dsExpr expr from' <- dsLExpr from to' <- dsLExpr to return $ mkApps expr' [from', to'] dsArithSeq expr (FromThen from thn) = mkApps <$> dsExpr expr <*> mapM dsLExpr [from, thn] dsArithSeq expr (FromThenTo from thn to) = do dflags <- getDynFlags warnAboutEmptyEnumerations dflags from (Just thn) to expr' <- dsExpr expr from' <- dsLExpr from thn' <- dsLExpr thn to' <- dsLExpr to return $ mkApps expr' [from', thn', to'] {- Desugar 'do' and 'mdo' expressions (NOT list comprehensions, they're handled in DsListComp). Basically does the translation given in the Haskell 98 report: -} dsDo :: [ExprLStmt Id] -> DsM CoreExpr dsDo stmts = goL stmts where goL [] = panic "dsDo" goL (L loc stmt:lstmts) = putSrcSpanDs loc (go loc stmt lstmts) go _ (LastStmt body _) stmts = ASSERT( null stmts ) dsLExpr body -- The 'return' op isn't used for 'do' expressions go _ (BodyStmt rhs then_expr _ _) stmts = do { rhs2 <- dsLExpr rhs ; warnDiscardedDoBindings rhs (exprType rhs2) ; then_expr2 <- dsExpr then_expr ; rest <- goL stmts ; return (mkApps then_expr2 [rhs2, rest]) } go _ (LetStmt binds) stmts = do { rest <- goL stmts ; dsLocalBinds binds rest } go _ (BindStmt pat rhs bind_op fail_op) stmts = do { body <- goL stmts ; rhs' <- dsLExpr rhs ; bind_op' <- dsExpr bind_op ; var <- selectSimpleMatchVarL pat ; let bind_ty = exprType bind_op' -- rhs -> (pat -> res1) -> res2 res1_ty = funResultTy (funArgTy (funResultTy bind_ty)) ; match <- matchSinglePat (Var var) (StmtCtxt DoExpr) pat res1_ty (cantFailMatchResult body) ; match_code <- handle_failure pat match fail_op ; return (mkApps bind_op' [rhs', Lam var match_code]) } go loc (RecStmt { recS_stmts = rec_stmts, recS_later_ids = later_ids , recS_rec_ids = rec_ids, recS_ret_fn = return_op , recS_mfix_fn = mfix_op, recS_bind_fn = bind_op , recS_rec_rets = rec_rets, recS_ret_ty = body_ty }) stmts = goL (new_bind_stmt : stmts) -- rec_ids can be empty; eg rec { print 'x' } where new_bind_stmt = L loc $ BindStmt (mkBigLHsPatTup later_pats) mfix_app bind_op noSyntaxExpr -- Tuple cannot fail tup_ids = rec_ids ++ filterOut (`elem` rec_ids) later_ids tup_ty = mkBigCoreTupTy (map idType tup_ids) -- Deals with singleton case rec_tup_pats = map nlVarPat tup_ids later_pats = rec_tup_pats rets = map noLoc rec_rets mfix_app = nlHsApp (noLoc mfix_op) mfix_arg mfix_arg = noLoc $ HsLam (MG { mg_alts = [mkSimpleMatch [mfix_pat] body] , mg_arg_tys = [tup_ty], mg_res_ty = body_ty , mg_origin = Generated }) mfix_pat = noLoc $ LazyPat $ mkBigLHsPatTup rec_tup_pats body = noLoc $ HsDo DoExpr (rec_stmts ++ [ret_stmt]) body_ty ret_app = nlHsApp (noLoc return_op) (mkBigLHsTup rets) ret_stmt = noLoc $ mkLastStmt ret_app -- This LastStmt will be desugared with dsDo, -- which ignores the return_op in the LastStmt, -- so we must apply the return_op explicitly go _ (ParStmt {}) _ = panic "dsDo ParStmt" go _ (TransStmt {}) _ = panic "dsDo TransStmt" handle_failure :: LPat Id -> MatchResult -> SyntaxExpr Id -> DsM CoreExpr -- In a do expression, pattern-match failure just calls -- the monadic 'fail' rather than throwing an exception handle_failure pat match fail_op | matchCanFail match = do { fail_op' <- dsExpr fail_op ; dflags <- getDynFlags ; fail_msg <- mkStringExpr (mk_fail_msg dflags pat) ; extractMatchResult match (App fail_op' fail_msg) } | otherwise = extractMatchResult match (error "It can't fail") mk_fail_msg :: DynFlags -> Located e -> String mk_fail_msg dflags pat = "Pattern match failure in do expression at " ++ showPpr dflags (getLoc pat) {- ************************************************************************ * * \subsection{Errors and contexts} * * ************************************************************************ -} -- Warn about certain types of values discarded in monadic bindings (#3263) warnDiscardedDoBindings :: LHsExpr Id -> Type -> DsM () warnDiscardedDoBindings rhs rhs_ty | Just (m_ty, elt_ty) <- tcSplitAppTy_maybe rhs_ty = do { warn_unused <- woptM Opt_WarnUnusedDoBind ; warn_wrong <- woptM Opt_WarnWrongDoBind ; when (warn_unused || warn_wrong) $ do { fam_inst_envs <- dsGetFamInstEnvs ; let norm_elt_ty = topNormaliseType fam_inst_envs elt_ty -- Warn about discarding non-() things in 'monadic' binding ; if warn_unused && not (isUnitTy norm_elt_ty) then warnDs (badMonadBind rhs elt_ty (ptext (sLit "-fno-warn-unused-do-bind"))) else -- Warn about discarding m a things in 'monadic' binding of the same type, -- but only if we didn't already warn due to Opt_WarnUnusedDoBind when warn_wrong $ do { case tcSplitAppTy_maybe norm_elt_ty of Just (elt_m_ty, _) | m_ty `eqType` topNormaliseType fam_inst_envs elt_m_ty -> warnDs (badMonadBind rhs elt_ty (ptext (sLit "-fno-warn-wrong-do-bind"))) _ -> return () } } } | otherwise -- RHS does have type of form (m ty), which is weird = return () -- but at lesat this warning is irrelevant badMonadBind :: LHsExpr Id -> Type -> SDoc -> SDoc badMonadBind rhs elt_ty flag_doc = vcat [ hang (ptext (sLit "A do-notation statement discarded a result of type")) 2 (quotes (ppr elt_ty)) , hang (ptext (sLit "Suppress this warning by saying")) 2 (quotes $ ptext (sLit "_ <-") <+> ppr rhs) , ptext (sLit "or by using the flag") <+> flag_doc ] {- ************************************************************************ * * \subsection{Static pointers} * * ************************************************************************ -} -- | Creates an name for an entry in the Static Pointer Table. -- -- The name has the form @sptEntry:<N>@ where @<N>@ is generated from a -- per-module counter. -- mkSptEntryName :: SrcSpan -> DsM Name mkSptEntryName loc = do uniq <- newUnique mod <- getModule occ <- mkWrapperName "sptEntry" return $ mkExternalName uniq mod occ loc where mkWrapperName what = do dflags <- getDynFlags thisMod <- getModule let -- Note [Generating fresh names for ccall wrapper] -- in compiler/typecheck/TcEnv.hs wrapperRef = nextWrapperNum dflags wrapperNum <- liftIO $ atomicModifyIORef wrapperRef $ \mod_env -> let num = lookupWithDefaultModuleEnv mod_env 0 thisMod in (extendModuleEnv mod_env thisMod (num+1), num) return $ mkVarOcc $ what ++ ":" ++ show wrapperNum
DavidAlphaFox/ghc
compiler/deSugar/DsExpr.hs
bsd-3-clause
38,233
48
25
11,456
7,920
4,040
3,880
-1
-1
{-# Language FlexibleInstances #-} {-# LANGUAGE OverloadedStrings #-} {-# Language TypeSynonymInstances #-} module Pretty ( ppdecl, ppexpr, ppsignature, pptype ) where import Type import Syntax import Infer import Text.PrettyPrint parensIf :: Bool -> Doc -> Doc parensIf True = parens parensIf False = id class Pretty p where ppr :: Int -> p -> Doc pp :: p -> Doc pp = ppr 0 instance Pretty Name where ppr _ x = text x instance Pretty TVar where ppr _ (TV x) = text x instance Pretty Type where ppr p (TArr _ a b) = (parensIf (isArrow a) (ppr p a)) <+> text "->" <+> ppr p b where isArrow TArr{} = True isArrow _ = False ppr p (TVar _ a) = ppr p a ppr _ (TCon _ a) = text a instance Pretty Expr where ppr p (Var _ a) = ppr p a ppr p (App _ a b) = parensIf (p > 0) $ ppr (p+1) a <+> ppr p b ppr p (Lam _ a b) = text "\\" <> ppr p a <+> text "->" <+> ppr p b ppr _ (Lit _ a) = int a instance Pretty Loc where ppr p (NoLoc) = "" ppr p (Located n) = int n instance Show TypeError where show (UnificationFail a la b lb) = concat [ "Cannot unify types: \n\t" , pptype a , "\n\tIntroduced at: " , (pploc la) , "\nwith \n\t" , pptype b , "\n\tIntroduced at: " , (pploc lb) ] show (InfiniteType (TV a) la b) = concat [ "Cannot construct the the infinite type: " , a , " = " , pptype b , "\n\tIntroduced at: " , (pploc la) ] show (Ambigious cs) = concat ["Cannot not match expected type: '" ++ pptype a ++ "' with actual type: '" ++ pptype b ++ "'\n" | (a,b) <- cs] show (UnboundVariable a) = "Not in scope: " ++ a pploc :: Loc -> String pploc = render . ppr 0 pptype :: Type -> String pptype = render . ppr 0 ppexpr :: Expr -> String ppexpr = render . ppr 0 ppsignature :: (String, Type) -> String ppsignature (a, b) = a ++ " : " ++ pptype b ppdecl :: (String, Expr) -> String ppdecl (a, b) = "let " ++ a ++ " = " ++ ppexpr b
yupferris/write-you-a-haskell
chapter9/provenance/Pretty.hs
mit
1,985
0
12
564
826
424
402
69
1
module IOPutStrLnUsed where import System.IO (putStrLn) main :: IO () main = putStrLn "test"
serokell/importify
test/test-data/base@basic/04-IOPutStrLnUsed.hs
mit
95
0
6
16
32
18
14
4
1
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE NoMonomorphismRestriction #-} module T15783B(f) where d = 0 f = [|| d ||]
sdiehl/ghc
testsuite/tests/th/T15783B.hs
bsd-3-clause
122
1
5
21
28
20
8
-1
-1
{-# LANGUAGE BangPatterns #-} -- This is a non-exposed internal module -- -- The code in this module has been ripped from containers-0.5.5.1:Data.Map.Base [1] almost -- verbatimely to avoid a dependency of 'template-haskell' on the containers package. -- -- [1] see https://hackage.haskell.org/package/containers-0.5.5.1 -- -- The original code is BSD-licensed and copyrighted by Daan Leijen, Andriy Palamarchuk, et al. module Language.Haskell.TH.Lib.Map ( Map , empty , insert , Language.Haskell.TH.Lib.Map.lookup ) where import Prelude data Map k a = Bin {-# UNPACK #-} !Size !k a !(Map k a) !(Map k a) | Tip type Size = Int empty :: Map k a empty = Tip {-# INLINE empty #-} singleton :: k -> a -> Map k a singleton k x = Bin 1 k x Tip Tip {-# INLINE singleton #-} size :: Map k a -> Int size Tip = 0 size (Bin sz _ _ _ _) = sz {-# INLINE size #-} lookup :: Ord k => k -> Map k a -> Maybe a lookup = go where go _ Tip = Nothing go !k (Bin _ kx x l r) = case compare k kx of LT -> go k l GT -> go k r EQ -> Just x {-# INLINABLE lookup #-} insert :: Ord k => k -> a -> Map k a -> Map k a insert = go where go :: Ord k => k -> a -> Map k a -> Map k a go !kx x Tip = singleton kx x go !kx x (Bin sz ky y l r) = case compare kx ky of LT -> balanceL ky y (go kx x l) r GT -> balanceR ky y l (go kx x r) EQ -> Bin sz kx x l r {-# INLINABLE insert #-} balanceL :: k -> a -> Map k a -> Map k a -> Map k a balanceL k x l r = case r of Tip -> case l of Tip -> Bin 1 k x Tip Tip (Bin _ _ _ Tip Tip) -> Bin 2 k x l Tip (Bin _ lk lx Tip (Bin _ lrk lrx _ _)) -> Bin 3 lrk lrx (Bin 1 lk lx Tip Tip) (Bin 1 k x Tip Tip) (Bin _ lk lx ll@(Bin _ _ _ _ _) Tip) -> Bin 3 lk lx ll (Bin 1 k x Tip Tip) (Bin ls lk lx ll@(Bin lls _ _ _ _) lr@(Bin lrs lrk lrx lrl lrr)) | lrs < ratio*lls -> Bin (1+ls) lk lx ll (Bin (1+lrs) k x lr Tip) | otherwise -> Bin (1+ls) lrk lrx (Bin (1+lls+size lrl) lk lx ll lrl) (Bin (1+size lrr) k x lrr Tip) (Bin rs _ _ _ _) -> case l of Tip -> Bin (1+rs) k x Tip r (Bin ls lk lx ll lr) | ls > delta*rs -> case (ll, lr) of (Bin lls _ _ _ _, Bin lrs lrk lrx lrl lrr) | lrs < ratio*lls -> Bin (1+ls+rs) lk lx ll (Bin (1+rs+lrs) k x lr r) | otherwise -> Bin (1+ls+rs) lrk lrx (Bin (1+lls+size lrl) lk lx ll lrl) (Bin (1+rs+size lrr) k x lrr r) (_, _) -> error "Failure in Data.Map.balanceL" | otherwise -> Bin (1+ls+rs) k x l r {-# NOINLINE balanceL #-} balanceR :: k -> a -> Map k a -> Map k a -> Map k a balanceR k x l r = case l of Tip -> case r of Tip -> Bin 1 k x Tip Tip (Bin _ _ _ Tip Tip) -> Bin 2 k x Tip r (Bin _ rk rx Tip rr@(Bin _ _ _ _ _)) -> Bin 3 rk rx (Bin 1 k x Tip Tip) rr (Bin _ rk rx (Bin _ rlk rlx _ _) Tip) -> Bin 3 rlk rlx (Bin 1 k x Tip Tip) (Bin 1 rk rx Tip Tip) (Bin rs rk rx rl@(Bin rls rlk rlx rll rlr) rr@(Bin rrs _ _ _ _)) | rls < ratio*rrs -> Bin (1+rs) rk rx (Bin (1+rls) k x Tip rl) rr | otherwise -> Bin (1+rs) rlk rlx (Bin (1+size rll) k x Tip rll) (Bin (1+rrs+size rlr) rk rx rlr rr) (Bin ls _ _ _ _) -> case r of Tip -> Bin (1+ls) k x l Tip (Bin rs rk rx rl rr) | rs > delta*ls -> case (rl, rr) of (Bin rls rlk rlx rll rlr, Bin rrs _ _ _ _) | rls < ratio*rrs -> Bin (1+ls+rs) rk rx (Bin (1+ls+rls) k x l rl) rr | otherwise -> Bin (1+ls+rs) rlk rlx (Bin (1+ls+size rll) k x l rll) (Bin (1+rrs+size rlr) rk rx rlr rr) (_, _) -> error "Failure in Data.Map.balanceR" | otherwise -> Bin (1+ls+rs) k x l r {-# NOINLINE balanceR #-} delta,ratio :: Int delta = 3 ratio = 2
sdiehl/ghc
libraries/template-haskell/Language/Haskell/TH/Lib/Map.hs
bsd-3-clause
3,991
0
21
1,413
2,024
1,016
1,008
85
8
module Fixme where {-@ instancesB :: Int -> Int @-} instancesB :: Int -> Int instancesB x = x
mightymoose/liquidhaskell
tests/parser/pos/TokensAsPrefixes.hs
bsd-3-clause
94
0
5
19
22
13
9
3
1
/* { dg-options "-I. -I $srcdir/gcc.dg/pch -Wno-deprecated" } */ #import "import-1a.h" #include "import-1b.h" #include "import-1c.h" #define IMPORT_1
SanDisk-Open-Source/SSD_Dashboard
uefi/gcc/gcc-4.6.3/gcc/testsuite/gcc.dg/pch/import-1.hs
gpl-2.0
150
4
6
17
23
14
9
1
0
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} module TCPOptions where import GHC.Generics import Data.Serialize import Data.Word import Data.List (intercalate) import Text.Printf import Control.Applicative import Data.ByteString.Char8 (ByteString, pack, unpack) data TCPOptions = TCPOptions [TCPOption] deriving (Eq, Ord, Show, Read, Generic) tcpOptionEND = 0 tcpOptionNOP = 1 tcpOptionMSS = 2 tcpOptionWS = 3 tcpOptionSackOK = 4 tcpOptionSack = 5 tcpOptionTS = 8 tcpOptionACR = 14 tcpOptionACD = 15 getOptions :: Get TCPOptions getOptions = do empty <- isEmpty case empty of True -> return $ TCPOptions [] False -> (\o (TCPOptions os) -> TCPOptions (o:os)) <$> getOption <*> getOptions getOption :: Get TCPOption getOption = do optionKind <- getWord8 case fromEnum optionKind of x | x == tcpOptionEND -> return OptionEND | x == tcpOptionNOP -> return OptionNOP | x == tcpOptionTS -> getOptionTS | x == tcpOptionSack -> getOptionSack | x == tcpOptionACD -> getWord8 >>= skip . (+ (-2)) . fromEnum >> return OptionACD | x == tcpOptionMSS -> getWord8 >> getWord16be >> return OptionMSS | x == tcpOptionWS -> getWord8 >> getWord8 >> return OptionWS | x == tcpOptionSackOK -> getWord8 >> return OptionSackOK | x == tcpOptionACR -> getWord8 >> getWord8 >> return OptionACR | otherwise -> return OptionUnknown getMoreOptions :: TCPOption -> Get TCPOptions getMoreOptions o = fmap (\(TCPOptions xs) -> TCPOptions (o:xs)) getOptions getOptionTS :: Get TCPOption getOptionTS = do optionLength <- fmap fromEnum $ getWord8 myTS <- getWord32be yrTS <- getWord32be return $ OptionTS myTS yrTS getSackPair = do bStart <- getWord32be bEnd <- getWord32be return (bStart, bEnd) getOptionSack :: Get TCPOption getOptionSack = do optionLength <- fmap fromEnum $ getWord8 case optionLength of x | x == 10 -> do (b0, b1) <- getSackPair return $ OptionSack1 b0 b1 | x == 18 -> do (b0, b1) <- getSackPair (c0, c1) <- getSackPair return $ OptionSack2 b0 b1 c0 c1 | x == 26 -> do (b0, b1) <- getSackPair (c0, c1) <- getSackPair (d0, d1) <- getSackPair return $ OptionSack3 b0 b1 c0 c1 d0 d1 | x == 34 -> do (b0, b1) <- getSackPair (c0, c1) <- getSackPair (d0, d1) <- getSackPair (e0, e1) <- getSackPair return $ OptionSack4 b0 b1 c0 c1 d0 d1 e0 e1 | otherwise -> fail "bad option sack" data TCPOption = OptionTS Word32 Word32 | OptionSack1 Word32 Word32 | OptionSack2 Word32 Word32 Word32 Word32 | OptionSack3 Word32 Word32 Word32 Word32 Word32 Word32 | OptionSack4 Word32 Word32 Word32 Word32 Word32 Word32 Word32 Word32 | OptionEND | OptionNOP | OptionSackOK | OptionACD | OptionMSS | OptionWS | OptionACR | OptionUnknown deriving (Eq, Ord, Show, Read, Generic) showOptionsLike :: TCPOptions -> String showOptionsLike (TCPOptions os) = intercalate "," . map showOptionLike $ os showOptionLike :: TCPOption -> String showOptionLike OptionNOP = "nop" showOptionLike OptionEND = "end" showOptionLike (OptionTS a b) = printf "TS val %d ecr %d" a b showOptionLike (OptionSack1 a0 a1) = printf "sack 1 {%d:%d}" a0 a1 showOptionLike (OptionSack2 a0 a1 b0 b1) = printf "sack 2 {%d:%d}{%d:%d}" a0 a1 b0 b1 showOptionLike (OptionSack3 a0 a1 b0 b1 c0 c1) = printf "sack 3 {%d:%d}{%d:%d}{%d:%d}" a0 a1 b0 b1 c0 c1 showOptionLike (OptionSack4 a0 a1 b0 b1 c0 c1 d0 d1) = printf "sack 4 {%d:%d}{%d:%d}{%d:%d}{%d:%d}" a0 a1 b0 b1 c0 c1 d0 d1 showOptionLike _ = "other" {- x | x == tcpOptionEND -> return getOptions -- return $ TCPOptions [] | x == tcpOptionNOP -> getOptions | x == tcpOptionTS -> getOptionTS >>= getMoreOptions | x == tcpOptionSack -> getOptionSack >>= getMoreOptions | x == tcpOptionACD -> getWord8 >>= skip . (+ (-2)) . fromEnum >> getOptions | x == tcpOptionMSS -> getWord8 >> getWord16be >> getOptions | x == tcpOptionWS -> getWord8 >> getWord8 >> getOptions | x == tcpOptionSackOK -> getWord8 >> getOptions | x == tcpOptionACR -> getWord8 >> getWord8 >> getOptions -} -- instance Serialize TCPOption instance Serialize TCPOptions where get = getOptions put = const $ return () testData :: ByteString testData = pack $ map toEnum [1, 1, 8, 10, 1, 2, 3, 4, 5, 6, 7, 8, 0]
mjansen/tcp-analyse
TCPOptions.hs
mit
4,542
0
16
1,142
1,322
673
649
107
2
module SpaceState.Common where import Data.List import Control.Monad.State as State import Prelude hiding (catch) import Entity import Camera import SpaceState.Game releaseKeys :: StateT SpaceState IO () releaseKeys = do setTurn 0 accelerate 0 -- prevent involuntary actions setZoomDelta 0 recoveryText :: String recoveryText = intercalate "\n" ["After ejecting from your space ship, you drifted in space", "until a friendly alien picked you up and took you with him", "to a nearby trading post, where you recovered some of your", "strength.", "", "After a long search, you manage to find a used ", "space ship, and embark on a new adventure..."] -- accelerate :: (MonadState SpaceState m) => GLdouble -> m () accelerate a = modify $ modTri $ modifyAcceleration (const (0.0, a, 0.0)) -- turn :: (MonadState SpaceState m) => GLdouble -> m () turn a = modify $ modTri $ modifyAngVelocity (+a) setTurn a = modify $ modTri $ modifyAngVelocity (const a) changeZoom a = modify $ modCameraState $ modCamZoomDelta (+a) setZoomDelta a = modify $ modCameraState $ modCamZoomDelta (const a)
anttisalonen/starrover2
src/SpaceState/Common.hs
mit
1,134
0
9
225
245
133
112
27
1
module Render ( renderDoc ) where import qualified Graphics.Svg as SVG import qualified Graphics.Svg.CssTypes as CSS import qualified Linear import Types import Transformation import SvgArcSegment import Approx import SVGExt import qualified CircularArc as CA import qualified BiArc as BA import qualified CubicBezier as B mapTuple :: (a -> b) -> (a, a) -> (b, b) mapTuple f (a1, a2) = (f a1, f a2) fromSvgPoint :: Int -> SVG.Point -> Point fromSvgPoint dpi (x,y) = (fromSvgNumber dpi x, fromSvgNumber dpi y) fromRPoint :: SVG.RPoint -> Point fromRPoint (Linear.V2 x y) = (x, y) toPoint :: Linear.V2 Double -> Point toPoint (Linear.V2 x y) = (x, y) fromPoint :: Point -> Linear.V2 Double fromPoint (x, y) = (Linear.V2 x y) -- TODO: em, percentage fromSvgNumber :: Int -> SVG.Number -> Double fromSvgNumber dpi num = fromNumber' (CSS.toUserUnit dpi num) where fromNumber' (SVG.Num n) = n fromNumber' _ = error "TODO: unhandled em or percentage" -- current point + control point -> mirrored control point mirrorControlPoint :: Point -> Point -> Point mirrorControlPoint (cx, cy) (cpx, cpy) = (cx + cx - cpx, cy + cy - cpy) -- convert a quadratic bezier to a cubic one bezierQ2C :: Point -> Point -> Point -> DrawOp bezierQ2C (qp0x, qp0y) (qp1x, qp1y) (qp2x, qp2y) = DBezierTo (qp0x + 2.0 / 3.0 * (qp1x - qp0x), qp0y + 2.0 / 3.0 * (qp1y - qp0y)) (qp2x + 2.0 / 3.0 * (qp1x - qp2x), qp2y + 2.0 / 3.0 * (qp1y - qp2y)) (qp2x, qp2y) toAbsolute :: (Double, Double) -> SVG.Origin -> (Double, Double) -> (Double, Double) toAbsolute _ SVG.OriginAbsolute p = p toAbsolute (cx,cy) SVG.OriginRelative (dx,dy) = (cx+dx, cy+dy) docTransform :: Int -> SVG.Document -> TransformationMatrix docTransform dpi doc = multiply mirrorTransform (viewBoxTransform $ SVG._viewBox doc) where viewBoxTransform (Just (vbx,vby,vbw,vbh)) = multiply (scaleTransform (w/vbw) (h/vbh)) (translateTransform (-vbx) (-vby)) viewBoxTransform Nothing = identityTransform mirrorTransform = mirrorYTransform w h (w, h) = (documentSize dpi doc) renderDoc :: Bool -> Int -> Double -> SVG.Document -> [GCodeOp] renderDoc generateBezier dpi resolution doc = stage2 $ renderTrees (docTransform dpi doc) (SVG._elements doc) where pxresolution = (fromIntegral dpi) / 2.45 / 10 * resolution -- TODO: make it tail recursive stage2 :: [DrawOp] -> [GCodeOp] stage2 dops = convert dops (Linear.V2 0 0) where convert [] _ = [] convert (DMoveTo p:ds) _ = GMoveTo p : convert ds (fromPoint p) convert (DLineTo p:ds) _ = GLineTo p : convert ds (fromPoint p) convert (DBezierTo c1 c2 p2:ds) cp | generateBezier = [GBezierTo c1 c2 p2] ++ convert ds (fromPoint p2) | otherwise = concatMap biarc2garc biarcs ++ convert ds (fromPoint p2) where biarcs = bezier2biarc (B.CubicBezier cp (fromPoint c1) (fromPoint c2) (fromPoint p2)) pxresolution biarc2garc (Left biarc) = [arc2garc (BA._a1 biarc), arc2garc (BA._a2 biarc)] biarc2garc (Right (Linear.V2 x y)) = [GLineTo (x,y)] arc2garc arc = GArcTo (toPoint (CA._c arc)) (toPoint (CA._p2 arc)) (CA.isClockwise arc) renderPathCommands :: Point -> Point -> Maybe Point -> [SVG.PathCommand] -> [DrawOp] renderPathCommands _ currentp _ (SVG.MoveTo origin (p:ps):ds) = DMoveTo ap : renderPathCommands ap ap Nothing (cont ps) where ap = toAbsolute currentp origin (fromRPoint p) cont [] = ds cont ps' = SVG.LineTo origin ps' : ds renderPathCommands firstp currentp _ (SVG.LineTo origin (p:ps):ds) = DLineTo ap : renderPathCommands firstp ap Nothing (cont ps) where ap = toAbsolute currentp origin (fromRPoint p) cont [] = ds cont ps' = SVG.LineTo origin ps' : ds renderPathCommands firstp (_, cy) _ (SVG.HorizontalTo SVG.OriginAbsolute (px:pxs):ds) = DLineTo ap : renderPathCommands firstp ap Nothing (cont pxs) where ap = (px,cy) cont [] = ds cont pxs' = SVG.HorizontalTo SVG.OriginAbsolute pxs' : ds renderPathCommands firstp (cx, cy) _ (SVG.HorizontalTo SVG.OriginRelative (dx:dxs):ds) = DLineTo ap : renderPathCommands firstp ap Nothing (cont dxs) where ap = (cx+dx,cy) cont [] = ds cont dxs' = SVG.HorizontalTo SVG.OriginRelative dxs' : ds renderPathCommands firstp (cx, _) _ (SVG.VerticalTo SVG.OriginAbsolute (py:pys):ds) = DLineTo ap : renderPathCommands firstp ap Nothing (cont pys) where ap = (cx,py) cont [] = ds cont pys' = SVG.VerticalTo SVG.OriginAbsolute pys' : ds renderPathCommands firstp (cx, cy) _ (SVG.VerticalTo SVG.OriginRelative (dy:dys):ds) = DLineTo ap : renderPathCommands firstp ap Nothing (cont dys) where ap = (cx,cy+dy) cont [] = ds cont dys' = SVG.VerticalTo SVG.OriginRelative dys' : ds renderPathCommands firstp currentp _ (SVG.CurveTo origin ((c1,c2,p):ps):ds) = DBezierTo ac1 ac2 ap : renderPathCommands firstp ap (Just ac2) (cont ps) where ap = toAbsolute currentp origin (fromRPoint p) ac1 = toAbsolute currentp origin (fromRPoint c1) ac2 = toAbsolute currentp origin (fromRPoint c2) cont [] = ds cont ps' = SVG.CurveTo origin ps' : ds renderPathCommands firstp currentp mbControlp (SVG.SmoothCurveTo origin ((c2,p):ps):ds) = DBezierTo ac1 ac2 ap : renderPathCommands firstp ap (Just ac2) (cont ps) where ap = toAbsolute currentp origin (fromRPoint p) ac1 = maybe ac2 (mirrorControlPoint currentp) mbControlp ac2 = toAbsolute currentp origin (fromRPoint c2) cont [] = ds cont ps' = SVG.SmoothCurveTo origin ps' : ds renderPathCommands firstp currentp _ (SVG.QuadraticBezier origin ((c1,p):ps):ds) = cbezier : renderPathCommands firstp ap (Just ac1) (cont ps) where ap = toAbsolute currentp origin (fromRPoint p) ac1 = toAbsolute currentp origin (fromRPoint c1) cbezier = bezierQ2C currentp ac1 ap cont [] = ds cont ps' = SVG.QuadraticBezier origin ps' : ds renderPathCommands firstp currentp mbControlp (SVG.SmoothQuadraticBezierCurveTo origin (p:ps):ds) = cbezier : renderPathCommands firstp ap (Just ac1) (cont ps) where ap = toAbsolute currentp origin (fromRPoint p) ac1 = maybe currentp (mirrorControlPoint currentp) mbControlp cbezier = bezierQ2C currentp ac1 ap cont [] = ds cont ps' = SVG.SmoothQuadraticBezierCurveTo origin ps' : ds renderPathCommands firstp currentp _ (SVG.EllipticalArc origin ((rx,ry,rot,largeArcFlag,sweepFlag,p):ps):ds) = convertSvgArc currentp rx ry rot largeArcFlag sweepFlag ap ++ renderPathCommands firstp ap Nothing (cont ps) where ap = toAbsolute currentp origin (fromRPoint p) cont [] = ds cont ps' = SVG.EllipticalArc origin ps' : ds renderPathCommands firstp@(fx,fy) (cx,cy) mbControlp (SVG.EndPath:ds) | fx /= cx || fy /= cy = DLineTo firstp : renderPathCommands firstp firstp mbControlp ds | otherwise = renderPathCommands firstp firstp mbControlp ds renderPathCommands _ _ _ _ = [] renderTree :: TransformationMatrix -> SVG.Tree -> [DrawOp] renderTree m (SVG.GroupTree g) = renderTrees (applyTransformations m (SVG._transform (SVG._groupDrawAttributes g))) (SVG._groupChildren g) renderTree m (SVG.PathTree p) = map (transformDrawOp tr) $ renderPathCommands (0,0) (0,0) Nothing (SVG._pathDefinition p) where tr = applyTransformations m (SVG._transform (SVG._pathDrawAttributes p)) renderTree m (SVG.RectangleTree r) | rx == 0.0 && ry == 0.0 = map (transformDrawOp tr) [DMoveTo (x,y), DLineTo (x+w,y), DLineTo (x+w,y+h), DLineTo (x,y+h), DLineTo (x,y)] | otherwise = map (transformDrawOp tr) ([DMoveTo (x,y+ry)] ++ convertSvgArc (x,y+ry) rx ry 0 False True (x+rx, y) ++ [DLineTo (x+w-rx,y)] ++ convertSvgArc (x+w-rx,y) rx ry 0 False True (x+w, y+ry) ++ [DLineTo (x+w,y+h-ry)] ++ convertSvgArc (x+w,y+h-ry) rx ry 0 False True (x+w-rx, y+h) ++ [DLineTo (x+rx,y+h)] ++ convertSvgArc (x+rx, y+h) rx ry 0 False True (x, y+h-ry) ++ [DLineTo (x,y+ry)]) where (x,y) = fromSvgPoint dpi (SVG._rectUpperLeftCorner r) w = fromSvgNumber dpi (SVG._rectWidth r) h = fromSvgNumber dpi (SVG._rectHeight r) (rx, ry) = mapTuple (fromSvgNumber dpi) (SVG._rectCornerRadius r) tr = applyTransformations m (SVG._transform (SVG._rectDrawAttributes r)) renderTree m (SVG.LineTree l) = [DMoveTo p1, DLineTo p2] where p1 = transformPoint tr (fromSvgPoint dpi (SVG._linePoint1 l)) p2 = transformPoint tr (fromSvgPoint dpi (SVG._linePoint2 l)) tr = applyTransformations m (SVG._transform (SVG._lineDrawAttributes l)) renderTree m (SVG.PolyLineTree l) = map (transformDrawOp tr) (DMoveTo p0:map DLineTo ps) where (p0:ps) = map (\(Linear.V2 x y) -> (x,y)) (SVG._polyLinePoints l) tr = applyTransformations m (SVG._transform (SVG._polyLineDrawAttributes l)) renderTree m (SVG.PolygonTree l) = map (transformDrawOp tr) (DMoveTo p0:map DLineTo (ps ++ [p0])) where (p0:ps) = map (\(Linear.V2 x y) -> (x,y)) (SVG._polygonPoints l) tr = applyTransformations m (SVG._transform (SVG._polygonDrawAttributes l)) renderTree m (SVG.EllipseTree e) = map (transformDrawOp tr) (DMoveTo (cx-rx,cy) : bs1++bs2++bs3++bs4) where bs1 = convertSvgArc (cx-rx, cy) rx ry 0 False True (cx, cy-ry) bs2 = convertSvgArc (cx, cy-ry) rx ry 0 False True (cx+rx, cy) bs3 = convertSvgArc (cx+rx, cy) rx ry 0 False True (cx, cy+ry) bs4 = convertSvgArc (cx, cy+ry) rx ry 0 False True (cx-rx, cy) (cx,cy) = fromSvgPoint dpi (SVG._ellipseCenter e) rx = fromSvgNumber dpi (SVG._ellipseXRadius e) ry = fromSvgNumber dpi (SVG._ellipseYRadius e) tr = applyTransformations m (SVG._transform (SVG._ellipseDrawAttributes e)) renderTree m (SVG.CircleTree c) = map (transformDrawOp tr) (DMoveTo (cx-r,cy) : bs1++bs2++bs3++bs4) where bs1 = convertSvgArc (cx-r, cy) r r 0 False True (cx, cy-r) bs2 = convertSvgArc (cx, cy-r) r r 0 False True (cx+r, cy) bs3 = convertSvgArc (cx+r, cy) r r 0 False True (cx, cy+r) bs4 = convertSvgArc (cx, cy+r) r r 0 False True (cx-r, cy) (cx,cy) = fromSvgPoint dpi (SVG._circleCenter c) r = fromSvgNumber dpi (SVG._circleRadius c) tr = applyTransformations m (SVG._transform (SVG._circleDrawAttributes c)) {- The rest: None, UseTree, SymbolTree, TextTree, ImageTree -} renderTree _ _ = [] renderTrees :: TransformationMatrix -> [SVG.Tree] -> [DrawOp] renderTrees m es = concat $ map (renderTree m) es
domoszlai/juicy-gcode
src/Render.hs
mit
12,279
0
21
3,913
4,563
2,374
2,189
183
36
-- | Text manipulation utilities. module Util.Text where import Prelude import qualified Data.Text as T -- | Joins a list of texts with the given text separating them. joinWith :: T.Text -> [T.Text] -> T.Text joinWith sep = T.concat . map (`T.append` sep) -- | Similar to joinWith, but doesn't add the separator at the end. joinWith' :: T.Text -> [T.Text] -> T.Text joinWith' sep = T.dropEnd (T.length sep) . T.concat . map (`T.append` sep)
MultiMC/Old-QuickMod.io
Util/Text.hs
mit
445
0
10
79
131
75
56
7
1
module Chapter5 where import Data.Char (ord, chr) import Data.Ix (inRange) factors n = [x | x <- [1 .. n], n `mod` x == 0] isPerfect n = n == sum (init (factors n)) -- Caesar code caesar :: Int -> String -> String caesar k = map f where f c | inRange ('a','z') c = tr 'a' k c | inRange ('A','Z') c = tr 'A' k c | otherwise = c unCaesar :: Int -> String -> String unCaesar k = caesar (-k) -- char addition tr :: Char -> Int -> Char -> Char tr base offset char = chr $ ord base + (ord char - ord base + offset) `mod` 26
ricca509/haskellFP101x
src/book/chapter5.hs
mit
548
0
11
147
281
146
135
15
1
module Writer where import Control.Monad data Writer s a = MkWriter [s] a instance Functor (Writer s) where fmap f (MkWriter ss x) = MkWriter ss (f x) instance Applicative (Writer s) where pure x = MkWriter [] x MkWriter ss f <*> MkWriter ss' x = MkWriter (ss ++ ss') (f x) instance Monad (Writer s) where (MkWriter ss x) >>= g = let (MkWriter ss' x') = g x in MkWriter (ss ++ ss') x' tell :: s -> Writer s () tell s = MkWriter [s] ()
NickAger/LearningHaskell
Monads and all that/Readers and Writers.hsproj/Writer.hs
mit
467
0
11
122
238
118
120
13
1
-- Problems/Problem037Spec.hs module Problems.Problem037Spec (main, spec) where import Test.Hspec import Problems.Problem037 main :: IO() main = hspec spec spec :: Spec spec = describe "Problem 37" $ it "Should evaluate to 748317" $ p37 `shouldBe` 748317
Sgoettschkes/learning
haskell/ProjectEuler/tests/Problems/Problem037Spec.hs
mit
270
0
8
51
73
41
32
9
1
import System.IO import Data.Char import Data.List import Data.Maybe --Define types for an easier reading type Line = [Int] type Column = [Int] type Vector = [Square] type Square = [Line] type Sudoku = [Vector] main = do let list = [] handle <- openFile "sudoku.txt" ReadMode contents <- hGetContents handle let singlewords = words contents list = singlewords let sudokus = stringsToSudokus $ stringToStrings $ removeText list let result = solveAll sudokus printSudokus $ map (\(Just x) -> x) (result) --print $ eulerAnswer $ solveAll sudokus hClose handle ------------------------------------------------------------------------------------------------------------------------ -- PARSING FILE -- ------------------------------------------------------------------------------------------------------------------------ removeText :: [String] -> [String] removeText l = filter (\x -> length x > 5) l stringToStrings :: [String] -> [[String]] stringToStrings l = aux l [] where aux [] acc = acc aux li acc = aux (drop 9 li) (acc ++ [take 9 li]) stringsToSudokus :: [[String]] -> [Sudoku] stringsToSudokus l = map (\x -> dataToSudoku $ stringToInt x) l ------------------------------------------------------------------------------------------------------------------------ -- DATA TO SUDOKU -- ------------------------------------------------------------------------------------------------------------------------ stringToInt :: [String] -> [Line] stringToInt s = map (\x -> map (digitToInt) x) s dataToLine :: [Line] -> [[Line]] dataToLine m = map (\l -> [take 3 l,drop 3 $ take 6 l, drop 6 $ take 9 l]) m --not very nice dataToSquare :: [Line] -> Vector dataToSquare m = map (\(l,c) -> map (\ligne -> ligne !! c ) $ take 3 $ drop (3*l) $ dataToLine m) [(i,j) | i <- [0..2], j <- [0..2]] dataToSudoku :: [Line] -> Sudoku dataToSudoku m = map (\(l) -> take 3 $ drop (3*l) $ dataToSquare m) [i | i <- [0..2]] ------------------------------------------------------------------------------------------------------------------------ -- SUDOKU -- ------------------------------------------------------------------------------------------------------------------------ transposeSudoku :: Sudoku -> Sudoku transposeSudoku s = map (\i -> getColumn i s) [i | i <- [0..2]] getColumn :: Int -> Sudoku -> Vector getColumn c s = [(getSquare 0 c s), (getSquare 1 c s), (getSquare 2 c s)] getSquare :: Int -> Int -> Sudoku -> Square getSquare l c s = (s !! l) !! c getVector :: Int -> Sudoku -> Vector getVector l s = s !! l getLineFromSquare :: Int -> Square -> Line getLineFromSquare l s = (s !! l) getColumnFromSquare :: Int -> Square -> Column getColumnFromSquare c s = getLineFromSquare c (transpose s) getElementFromSquare :: Int -> Int -> Square -> Int getElementFromSquare l c s = (s !! l) !! c getLineFromSudoku :: Int -> Sudoku -> Line getLineFromSudoku l s = concat (map (\sq -> getLineFromSquare (l `mod` 3) sq) (getVector (l `quot` 3) s)) getColumnFromSudoku :: Int -> Sudoku -> Line getColumnFromSudoku c s = concat (map (\sq -> getColumnFromSquare (c `mod` 3) sq) (getVector (c `quot` 3) (transposeSudoku(s)))) getElementFromSudoku :: Int -> Int -> Sudoku -> Int getElementFromSudoku x y s = getElementFromSquare (x `mod` 3) (y `mod` 3) (getSquare(x `quot` 3) (y `quot` 3) s) ------------------------------------------------------------------------------------------------------------------------ -- ALGO HELPER -- ------------------------------------------------------------------------------------------------------------------------ possibilitesInSquare :: Square -> [Int] possibilitesInSquare s = ([i | i <- [1..9]]) \\ (filter (>0) (concat(s))) possibilitesInLine :: Line -> [Int] possibilitesInLine l = ([i | i <- [1..9]]) \\ (filter (>0) l) possibilitesInColumn :: Column -> [Int] possibilitesInColumn c = ([i | i <- [1..9]]) \\ (filter (>0) c) possibilites :: Int -> Int -> Sudoku -> [Int] possibilites l c s = intersect (possibilitesInSquare (getSquare (l `quot` 3) (c `quot` 3) s)) (intersect (possibilitesInColumn (getColumnFromSudoku c s)) (possibilitesInLine (getLineFromSudoku l s))) searchMinPossibilites :: Sudoku -> (Int,Int,[Int]) searchMinPossibilites s = aux s 0 0 (-1) (-1) [1,2,3,4,5,6,7,8,9,0] where aux s 8 8 resx resy p = if (getElementFromSudoku 8 8 s) == 0 then if (length(possibilites 8 8 s) < length(p)) then (8,8,(possibilites 8 8 s)) else (resx,resy,p) else (resx,resy,p) aux s x 8 resx resy p = if (getElementFromSudoku x 8 s) == 0 then if (length(possibilites x 8 s) < length(p)) then aux s (x+1) 0 x 8 (possibilites x 8 s) else aux s (x+1) 0 resx resy p else aux s (x+1) 0 resx resy p aux s x y resx resy p = if (getElementFromSudoku x y s) == 0 then if (length(possibilites x y s) < length(p)) then aux s x (y+1) x y (possibilites x y s) else aux s x (y+1) resx resy p else aux s x (y+1) resx resy p replace :: a -> Int -> [a] -> [a] replace newVal pos list = take pos list ++ newVal : drop (pos+1) list playSudoku :: Int -> Int -> Int -> Sudoku -> Sudoku playSudoku v x y s = replace (replace (replace (replace v (y `mod` 3) (getLineFromSquare (x `mod` 3) (getSquare (x `quot` 3) (y `quot` 3) s)) ) (x `mod` 3) (getSquare (x `quot` 3) (y `quot` 3) s)) (y `quot` 3) (getVector (x `quot` 3) s)) (x `quot` 3) s --Woooow 231-length oneliner ... Here we "recursively" replace an element in the sudoku. From the sudoku we replace the vector, in the vector we replace the square, in the square we replace the line and in the line we replace the element (y) isComplete :: Sudoku -> Maybe Sudoku isComplete s = if ((foldr (+) 0 (concat (concat (concat s)))) == 405 ) then Just s else Nothing solveSudoku :: Sudoku -> Int -> Int -> [Int] -> Maybe Sudoku solveSudoku s (-1) (-1) _ = Just s solveSudoku s x y (p:[]) = let (xx,yy,pos) = (searchMinPossibilites (playSudoku p x y s)) in let res = (solveSudoku (playSudoku p x y s) xx yy pos) in if res == Nothing then Nothing else res solveSudoku s x y (p:ps) = let (xx,yy,pos) = (searchMinPossibilites (playSudoku p x y s)) in let res = (solveSudoku (playSudoku p x y s) xx yy pos) in if res == Nothing then let (xxx,yyy,poss) = (searchMinPossibilites (playSudoku (head ps) x y s)) in solveSudoku (playSudoku (head ps) x y s) xxx yyy poss else res solveSudoku s x y [] = let (xx,yy,p) = (searchMinPossibilites s) in Nothing ------------------------------------------------------------------------------------------------------------------------ -- Entry Point -- ------------------------------------------------------------------------------------------------------------------------ solve :: Sudoku -> Maybe Sudoku solve s = let (xx,yy,pos) = (searchMinPossibilites s) in solveSudoku s xx yy pos solveAll :: [Sudoku] -> [Maybe Sudoku] solveAll ss = map solve ss eulerAnswer :: [Maybe Sudoku] -> Int eulerAnswer s = foldr (+) 0 $ map (\[c,d,u] -> c*100+d*10+u) (map (\y -> getLineFromSquare 0 y) (map (\x -> getSquare 0 0 x) (map (\(Just x) -> x) (s)))) verifyAllSuokus :: [Maybe Sudoku] -> Int verifyAllSuokus ss = foldr (*) 1 (map (\s -> if isJust s then 1 else 0 ) ss) ------------------------------------------------------------------------------------------------------------------------ -- Printing a Sudoku -- ------------------------------------------------------------------------------------------------------------------------ printSudokus :: [Sudoku] -> IO() printSudokus ss = mapM_ printSudoku ss printSudoku :: Sudoku -> IO() printSudoku s = mapM_ (\i -> if i > 8 then print "-----------------" else print (getLineFromSudoku i s)) [i | i<-[0..9]]
fthomasmorel/Sudoku-solver
Sudoku.hs
mit
8,332
0
19
1,931
3,088
1,660
1,428
103
9
{-# LANGUAGE CPP #-} module GHCJS.DOM.WebKitNamespace ( #if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT) module GHCJS.DOM.JSFFI.Generated.WebKitNamespace #else #endif ) where #if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT) import GHCJS.DOM.JSFFI.Generated.WebKitNamespace #else #endif
plow-technologies/ghcjs-dom
src/GHCJS/DOM/WebKitNamespace.hs
mit
358
0
5
33
33
26
7
4
0
-- hooray for Haskell! Some basic functions and executions. Based off of Learn You a Haskell for Great Good -- compile with ghc -o intro intro.hs, then execute with ./intro -- the parens are needed because Haskell will attempt to pass doubleUs to print. Order of operations is FPEMDAS. Say that aloud and giggle. -- Alternatively $ can be used after print -- the do notation here forces individual execution and will be delved into further later main = do print ( 2 + 2 ) -- prints the number following 2 print ( succ 2 ) -- prints the number following 2 then multiplies by 2 print ( succ 2 * 2 ) -- multiplies 2 by 2 then prints the number following the result print ( succ (2 * 2))
heidtn/Haskell_Tutorials
intro.hs
mit
700
0
11
148
74
38
36
5
1
module Exercise where import Data.List type Node = Int type Graph = [(Node, [Node])] bereikbaar :: Node -> Graph -> [Node] bereikbaar n g = bereikbaar' n g [] bereikbaar' :: Node -> Graph -> [Node] -> [Node] bereikbaar' n g vns = concat [y : (bereikbaar' y g (y:vns)) | y <- (adjacentNodes n g) \\ vns] adjacentNodes :: Node -> Graph -> [Node] adjacentNodes _ [] = [] adjacentNodes n ((a, b):graph) | n == a = b | otherwise = adjacentNodes n graph duplicates :: [Node] -> Bool duplicates [] = False duplicates (n:ns) | n `elem` ns = True | otherwise = duplicates ns bevatCycle :: Graph -> Bool bevatCycle g = or (map (\n -> n `elem` (bereikbaar n g)) (allNodes g)) allNodes :: Graph -> [Node] allNodes [] = [] allNodes ((n,_):g) = [n] ++ (allNodes g)
tcoenraad/functioneel-programmeren
2012/opg3d.hs
mit
808
0
12
200
402
215
187
21
1
module Test.Scher ( module Test.Scher.Property ) where import Test.Scher.Property
m-alvarez/scher
Test/Scher.hs
mit
89
0
5
16
21
14
7
3
0
{-# LANGUAGE DeriveDataTypeable, FlexibleInstances, MultiParamTypeClasses, FlexibleContexts #-} module Code.Nocode where import Code.Formal import Challenger.Partial import Inter.Types import Inter.Quiz import Autolib.Reporter import Autolib.FiniteMap import Autolib.ToDoc import Autolib.Reader import Autolib.Util.Zufall import Data.Typeable import Data.List data Nocode = Nocode deriving ( Read, Show, Typeable ) instance OrderScore Nocode where scoringOrder _ = None -- ? instance Partial Nocode [( Char, String)] ( String,String ) where describe Nocode f = vcat [ text "Beweisen Sie, daß die Abbildung" , nest 4 $ text "f =" <+> toDoc ( listToFM f ) , text "kein Code ist:" , text "Geben Sie ein Wortpaar (u,v) mit u /= v und f(u) = f(v) an." ] initial Nocode f = let ks = keysFM $ listToFM f in ( take 2 ks, take 2 $ reverse ks ) partial Nocode f (u,v) = do when ( u == v ) $ reject $ text "die beiden Wörter sollen verschieden sein." total Nocode f0 (u,v) = do let f = listToFM f0 fu <- morph f u fv <- morph f v when ( fu /= fv ) $ reject $ text "die beiden Bilder sollen gleich sein." morph :: ( ToDoc [b], ToDoc [a], ToDoc a, Ord a ) => FiniteMap a [b] -> [a] -> Reporter [b] morph f u = do inform $ text "Das Bild von" <+> toDoc u fu <- fmap concat $ sequence $ do x <- u return $ case lookupFM f x of Nothing -> reject $ text "der Buchstabe" <+> toDoc x <+> text "hat kein Bild." Just fx -> return fx inform $ text "ist" <+> toDoc fu return fu instance ( ToDoc a, Reader a, Reader [a], Ord a , ToDoc b, Reader b, Eq b ) => Measure Nocode [( a, [b] )] ( [a],[a] ) where measure Nocode f (u,v) = fromIntegral $ length u + length v make_fixed = direct Nocode $ [ ('A', "00"), ('B',"001"),('C',"10"),('D',"01") ] ----------------------------------------------------------------------- make_quiz = quiz Nocode () roll_nocode :: IO ([ String ], [String]) roll_nocode = do ws <- sequence $ replicate 5 $ do l <- randomRIO ( 2, 5 ) someIO "01" l let ce = code_counter_examples ws return ( ws, take 1 ce ) `repeat_until` \ ( ws, ce) -> not (null ce) && length (head ce) >= 15 && length (nub $ concat ce) > 1 instance Generator Nocode () ([ String ], [String]) where generator _ conf key = roll_nocode instance Project Nocode ([ String ], [String]) [(Char,String)] where project _ ( ws, ce ) = zip [ 'A' .. ] ws
Erdwolf/autotool-bonn
src/Code/Nocode.hs
gpl-2.0
2,590
9
18
704
970
510
460
71
2
{- This module was generated from data in the Kate syntax highlighting file mips.xml, version 1.03, by Dominik Haumann ([email protected]) -} module Text.Highlighting.Kate.Syntax.Mips (highlight, parseExpression, syntaxName, syntaxExtensions) where import Text.Highlighting.Kate.Types import Text.Highlighting.Kate.Common import Text.ParserCombinators.Parsec hiding (State) import Control.Monad.State import Data.Char (isSpace) import qualified Data.Set as Set -- | Full name of language. syntaxName :: String syntaxName = "MIPS Assembler" -- | Filename extensions for this language. syntaxExtensions :: String syntaxExtensions = "*.s;" -- | Highlight source code using this syntax definition. highlight :: String -> [SourceLine] highlight input = evalState (mapM parseSourceLine $ lines input) startingState parseSourceLine :: String -> State SyntaxState SourceLine parseSourceLine = mkParseSourceLine (parseExpression Nothing) -- | Parse an expression using appropriate local context. parseExpression :: Maybe (String,String) -> KateParser Token parseExpression mbcontext = do (lang,cont) <- maybe currentContext return mbcontext result <- parseRules (lang,cont) optional $ do eof updateState $ \st -> st{ synStPrevChar = '\n' } pEndLine return result startingState = SyntaxState {synStContexts = [("MIPS Assembler","normal")], synStLineNumber = 0, synStPrevChar = '\n', synStPrevNonspace = False, synStContinuation = False, synStCaseSensitive = True, synStKeywordCaseSensitive = False, synStCaptures = []} pEndLine = do updateState $ \st -> st{ synStPrevNonspace = False } context <- currentContext contexts <- synStContexts `fmap` getState st <- getState if length contexts >= 2 then case context of _ | synStContinuation st -> updateState $ \st -> st{ synStContinuation = False } ("MIPS Assembler","normal") -> return () ("MIPS Assembler","string") -> return () _ -> return () else return () withAttribute attr txt = do when (null txt) $ fail "Parser matched no text" updateState $ \st -> st { synStPrevChar = last txt , synStPrevNonspace = synStPrevNonspace st || not (all isSpace txt) } return (attr, txt) list_type = Set.fromList $ words $ ".align .ascii .asciiz .byte .double .extern .float .globl .half .sdata .set .space .word" list_section = Set.fromList $ words $ ".data .kdata .ktext .text" list_hardware = Set.fromList $ words $ "abs.d abs.s add add.d add.s addi addiu addu and andi bc0f bc0t bc1f bc1t bc2f bc2t bc3f bc3t beq bgez bgezal bgtz blez bltz bltzal bne break c.eq.d c.eq.s c.seq.s c.seq.d c.ueq.s c.ueq.d c.olt.d c.olt.s c.ole.d c.ole.s c.ult.d c.ult.s c.ule.d c.ule.s c.le.d c.le.s c.lt.d c.lt.s c.un.s c.un.d cvt.d.s cvt.d.w cvt.s.d cvt.s.w cvt.w.d cvt.w.s div.d div.s j jal jalr jr lb lbu lh lhu lui lw lwc0 lwc1 lwc2 lwc3 lwl lwr mfc0 mfc1 mfc2 mfc3 mfhi mflo mtc0 mtc1 mtc2 mtc3 mthi mtlo mul.d mul.s mult multu nor or ori rfe sb sh sw swcl swl swr sll sllv slt slti sltiu sra srav srl srlv sub sub.d sub.s subu sw swc0 swc1 swc2 swc3 swl swr syscall xor xori" list_pseudo = Set.fromList $ words $ "abs b beqz bge bgeu bgt bgtu ble bleu blt bltu bnez div divu l.d l.s la ld li li.d li.s mfc0.d mfc1.d mfc2.d mfc3.d mov.d mov.s move mul mulo mulou neg neg.d neg.s negu nop not rem remu rol ror s.d s.s sd seq sge sgeu sgt sgtu sle sleu sne ulh ulhu ulw ush usw" list_register1 = Set.fromList $ words $ "$0 $1 $2 $3 $4 $5 $6 $7 $8 $9 $10 $11 $12 $13 $14 $15 $16 $17 $18 $19 $20 $21 $22 $23 $24 $25 $26 $27 $28 $29 $30 $31 $zero $t0 $t1 $t2 $t3 $t4 $t5 $t6 $t7 $t8 $t9" list_register2 = Set.fromList $ words $ "$v0 $v1 $a0 $a1 $a2 $a3 $k0 $k1 $at $gp $sp $fp $s0 $s1 $s2 $s3 $s4 $s5 $s6 $s7 $ra" list_fp = Set.fromList $ words $ "$f0 $f1 $f2 $f3 $f4 $f5 $f6 $f7 $f8 $f9 $f10 $f11 $f12 $f13 $f14 $f15 $f16 $f17 $f18 $f19 $f20 $f21 $f22 $f23 $f24 $f25 $f26 $f27 $f28 $f29 $f30 $f31" regex_'23'5cs'2aBEGIN'2e'2a'24 = compileRegex True "#\\s*BEGIN.*$" regex_'23'5cs'2aEND'2e'2a'24 = compileRegex True "#\\s*END.*$" regex_'23'2e'2a'24 = compileRegex True "#.*$" regex_'5b'5cw'5f'5c'2e'5d'2b'3a = compileRegex True "[\\w_\\.]+:" regex_'5c'5c'2e = compileRegex True "\\\\." parseRules ("MIPS Assembler","normal") = (((pKeyword " \n\t():!+,-<=>%&*/;?[]^{|}~\\" list_hardware >>= withAttribute KeywordTok)) <|> ((pKeyword " \n\t():!+,-<=>%&*/;?[]^{|}~\\" list_pseudo >>= withAttribute FunctionTok)) <|> ((pKeyword " \n\t():!+,-<=>%&*/;?[]^{|}~\\" list_register1 >>= withAttribute DataTypeTok)) <|> ((pKeyword " \n\t():!+,-<=>%&*/;?[]^{|}~\\" list_register2 >>= withAttribute DataTypeTok)) <|> ((pKeyword " \n\t():!+,-<=>%&*/;?[]^{|}~\\" list_fp >>= withAttribute FloatTok)) <|> ((pKeyword " \n\t():!+,-<=>%&*/;?[]^{|}~\\" list_section >>= withAttribute KeywordTok)) <|> ((pKeyword " \n\t():!+,-<=>%&*/;?[]^{|}~\\" list_type >>= withAttribute DataTypeTok)) <|> ((pFirstNonSpace >> pRegExpr regex_'23'5cs'2aBEGIN'2e'2a'24 >>= withAttribute RegionMarkerTok)) <|> ((pFirstNonSpace >> pRegExpr regex_'23'5cs'2aEND'2e'2a'24 >>= withAttribute RegionMarkerTok)) <|> ((pRegExpr regex_'23'2e'2a'24 >>= withAttribute CommentTok)) <|> ((pFirstNonSpace >> pRegExpr regex_'5b'5cw'5f'5c'2e'5d'2b'3a >>= withAttribute OtherTok)) <|> ((pDetectChar False '"' >>= withAttribute StringTok) >>~ pushContext ("MIPS Assembler","string")) <|> ((pFloat >>= withAttribute FloatTok)) <|> ((pHlCOct >>= withAttribute BaseNTok)) <|> ((pHlCHex >>= withAttribute BaseNTok)) <|> ((pInt >>= withAttribute DecValTok)) <|> (currentContext >>= \x -> guard (x == ("MIPS Assembler","normal")) >> pDefault >>= withAttribute NormalTok)) parseRules ("MIPS Assembler","string") = (((pRegExpr regex_'5c'5c'2e >>= withAttribute CharTok)) <|> ((pDetectChar False '"' >>= withAttribute StringTok) >>~ (popContext)) <|> (currentContext >>= \x -> guard (x == ("MIPS Assembler","string")) >> pDefault >>= withAttribute StringTok)) parseRules x = parseRules ("MIPS Assembler","normal") <|> fail ("Unknown context" ++ show x)
ambiata/highlighting-kate
Text/Highlighting/Kate/Syntax/Mips.hs
gpl-2.0
6,160
0
25
1,091
1,277
678
599
96
5
{-# OPTIONS -fglasgow-exts -fno-monomorphism-restriction #-} ---------------------------------------------------------------------------- -- | -- Module : Text.XML.Schema.Org.W3.N2001.XMLSchema_instance -- Copyright : (c) Simon Foster 2004 -- License : GPL version 2 (see COPYING) -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : non-portable (ghc >= 6 only) -- -- Haskell module for the XML Schema instance Schema. Essentially this is just -- an XSD type hook at the moment. -- -- @This file is part of HAIFA.@ -- -- @HAIFA is free software; you can redistribute it and\/or modify it under the terms of the -- GNU General Public License as published by the Free Software Foundation; either version 2 -- of the License, or (at your option) any later version.@ -- -- @HAIFA 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 HAIFA; if not, -- write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA@ ---------------------------------------------------------------------------- module Text.XML.Schema.Org.W3.N2001.XMLSchema_instance where import Text.XML.Serializer import Text.XML.HXT.Parser import qualified Text.XML.Schema.Org.W3.N2001.XMLSchema as XSD import Data.Maybe import Data.List import Data.Typeable import Data.Generics import Utils import Text.XML.HXT.Aliases thisNamespace = "http://www.w3.org/2001/XMLSchema-instance" tns = thisNamespace defaultPrefix = "xsi" hook xdb x = hookXSITypes tns xdb x hookXSITypes :: (Typeable a, Data a) => String -> XDB -> a -> XmlFilter hookXSITypes ns xdb x = let nst = getNST xdb; tm = getTypeMap xdb nsm = getNamespaceMap xdb ns = getModuleNS $ dataTypeOf x q = resolveQName nst (QN "" "type" ns) t = fromMaybe "" $ lookup (typeOf x) tm tq = resolveQName nst (QN "" t (fromMaybe "" $ lookup ns nsm)) in t ?? (addAttr (aName q) (aName tq), this) encoder = encodeNull decoder = decodeNull
twopoint718/haifa
src/Text/XML/Schema/Org/W3/N2001/XMLSchema_instance.hs
gpl-2.0
2,411
1
14
558
321
190
131
25
1
module Common where -- |Integer multiply. Multiplies integer by a factor given in a -- rational number. iMult :: (Integral a) => Rational -> a -> a iMult a b = round $ toRational b * a
zouppen/valo
new/Common.hs
gpl-3.0
185
0
7
37
49
27
22
3
1
{- This file is part of PhoneDirectory. Copyright (C) 2009 Michael Steele PhoneDirectory is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. PhoneDirectory 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 PhoneDirectory. If not, see <http://www.gnu.org/licenses/>. -} module TestUnitConversion where import Control.Applicative import Test.QuickCheck import UnitConversion prop_reflective_inch_pdf_conversion :: Inches -> Bool prop_reflective_inch_pdf_conversion i = abs(i' - i) < 0.0001 where i' = asInches . asPDFUnits . asInches . asPDFUnits $ i main :: IO () main = do putStrLn "Inches & PDFUnits: Reflective conversion." quickCheck prop_reflective_inch_pdf_conversion instance Arbitrary Inches where arbitrary = Inches <$> arbitrary shrink (Inches x) = map Inches (shrink x) instance Arbitrary PDFUnits where arbitrary = PDFUnits <$> arbitrary shrink (PDFUnits x) = map PDFUnits (shrink x)
mikesteele81/Phone-Directory
src/TestUnitConversion.hs
gpl-3.0
1,392
2
10
267
184
94
90
17
1
module DepProcessors.Npm ( findDefinitions, installFromDefinition, extractFilePath, NpmDefinition ) where import qualified DepProcessors.Data.Result as R import DepProcessors.ProcessorHelpers (getFileName, executeGenericProcessor, GenericProcessorConfig(..)) findDefinitions :: [FilePath] -> IO [NpmDefinition] findDefinitions files = return $ map NpmDefinition filtered where filtered = filter ((=="package.json") . getFileName) files installFromDefinition :: NpmDefinition -> IO R.Result installFromDefinition (NpmDefinition file) = executeGenericProcessor config file where config = GenericProcessorConfig { commandName = "npm", commandArguments = ["install"], depNotFoundRegex = "^npm http 404 https://registry.npmjs.org/(.+)" } extractFilePath :: NpmDefinition -> FilePath extractFilePath (NpmDefinition fp) = fp data NpmDefinition = NpmDefinition FilePath deriving Show
splondike/depcache
src/DepProcessors/Npm.hs
gpl-3.0
944
0
10
157
205
118
87
19
1
module Utils where inspect :: Show a => IO a -> IO () inspect = (=<<) print
ptitfred/slidecoding
demo/src/Utils.hs
gpl-3.0
77
0
8
18
38
20
18
3
1
-- grid is a game written in Haskell -- Copyright (C) 2018 [email protected] -- -- This file is part of grid. -- -- grid is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- grid 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 grid. If not, see <http://www.gnu.org/licenses/>. -- module Game.Run.Output.Plain.Screen ( outputScreenBegin, outputScreenBegin', outputScreenMain, outputScreenMain', outputScreenEnd, outputScreenEnd', outputScreenLevelMode, outputScreenPuzzleMode, outputScreenMemoryMode, outputScreenForeign, outputScreenAtFace', outputScreenAtFace''', outputScreenAToB, ) where import MyPrelude import Game import Game.Font import Game.Data.Color import Game.Grid import Game.Grid.Output import Game.Run.RunData import Game.Run.RunWorld import Game.Run.RunWorld.OutputState import Game.Run.Helpers import Game.Run.Iteration.State import Game.Run.Output.Plain.ShadeCube import Game.Run.Scene.Plain.ShadeCorners import OpenGL import OpenGL.Helpers -------------------------------------------------------------------------------- -- Begin outputScreenBegin :: GameData -> RunWorld -> IO () outputScreenBegin griddata run = do return () outputScreenBegin' :: GameData -> Mat4 -> Mat4 -> Mat4 -> s -> RunWorld -> b -> IO () outputScreenBegin' = outputScreenMain' -------------------------------------------------------------------------------- -- Main outputScreenMain :: GameData -> RunWorld -> IO () outputScreenMain gamedata run = return () outputScreenMain' :: GameData -> Mat4 -> Mat4 -> Mat4 -> s -> RunWorld -> b -> IO () outputScreenMain' gamedata proj modv normal s run b = do -- 3D -- let projmodv = proj `mappend` modv glEnable gl_DEPTH_TEST glEnable gl_CULL_FACE -- space box let colormap = griddataColorMap $ gamedataGridData gamedata ix = outputstateColorIx $ runOutputState run ix' = outputstateColorIx' $ runOutputState run alpha = outputstateAlpha $ runOutputState run shadeSpaceBoxColor (griddataShadeSpaceBox $ gamedataGridData gamedata) 1.0 projmodv proj valuePerspectiveRadius $ smoothColor (colormapAt colormap ix) (colormapAt colormap ix') alpha -- cube shadeCube (rundataShadeCube $ gamedataRunData gamedata) 1.0 projmodv normal run -- face names drawFaceNames gamedata 1.0 projmodv -- message path shadePathFatBegin (griddataShadePath $ gamedataGridData gamedata) 1.0 projmodv shadePathRadius (griddataShadePath $ gamedataGridData gamedata) valueRunPathRadius shadePathColor (griddataShadePath $ gamedataGridData gamedata) valueRunPathColor shadePathDrawPath0 (griddataShadePath $ gamedataGridData gamedata) (gridPath $ runGrid run) shadePathEnd (griddataShadePath $ gamedataGridData gamedata) -------------------------------------------------------------------------------- -- End outputScreenEnd :: GameData -> RunWorld -> IO () outputScreenEnd gamedata run = return () outputScreenEnd' :: GameData -> Mat4 -> Mat4 -> Mat4 -> s -> RunWorld -> b -> IO () outputScreenEnd' gamedata proj modv normal s run b = do return () -------------------------------------------------------------------------------- -- Faces outputScreenLevelMode :: GameData -> RunWorld -> IO () outputScreenLevelMode gamedata run = do return () outputScreenPuzzleMode :: GameData -> RunWorld -> IO () outputScreenPuzzleMode gamedata run = do return () outputScreenMemoryMode :: GameData -> RunWorld -> IO () outputScreenMemoryMode gamedata run = do return () outputScreenForeign :: GameData -> RunWorld -> IO () outputScreenForeign griddata run = do return () -------------------------------------------------------------------------------- -- AtFace outputScreenAtFace' :: GameData -> Mat4 -> Mat4 -> Mat4 -> AtFaceState -> RunWorld -> b -> IO () outputScreenAtFace' gamedata proj modv normal s run b = do -- 3D -- let projmodv = proj `mappend` modv glEnable gl_DEPTH_TEST glEnable gl_CULL_FACE -- space box let colormap = griddataColorMap $ gamedataGridData gamedata ix = outputstateColorIx $ runOutputState run ix' = outputstateColorIx' $ runOutputState run alpha = outputstateAlpha $ runOutputState run shadeSpaceBoxColor (griddataShadeSpaceBox $ gamedataGridData gamedata) 1.0 projmodv proj valuePerspectiveRadius $ smoothColor (colormapAt colormap ix) (colormapAt colormap ix') alpha -- cube shadeCube (rundataShadeCube $ gamedataRunData gamedata) 1.0 projmodv normal run -- face names let alpha = cameraViewAlpha $ runCamera run drawFaceNames gamedata (1.0 - alpha) projmodv -- message path shadePathFatBegin (griddataShadePath $ gamedataGridData gamedata) 1.0 projmodv shadePathRadius (griddataShadePath $ gamedataGridData gamedata) valueRunPathRadius shadePathColor (griddataShadePath $ gamedataGridData gamedata) valueRunPathColor shadePathDrawPath0 (griddataShadePath $ gamedataGridData gamedata) (gridPath $ runGrid run) shadePathEnd (griddataShadePath $ gamedataGridData gamedata) -- escape corners drawAtFaceCorners gamedata alpha projmodv s run outputScreenAtFace''' :: GameData -> Mat4 -> Mat4 -> Mat4 -> AtFaceState -> RunWorld -> b -> IO () outputScreenAtFace''' gamedata proj modv normal s run b = do -- 3D -- let projmodv = proj `mappend` modv glEnable gl_DEPTH_TEST glEnable gl_CULL_FACE -- space box let colormap = griddataColorMap $ gamedataGridData gamedata ix = outputstateColorIx $ runOutputState run ix' = outputstateColorIx' $ runOutputState run alpha = outputstateAlpha $ runOutputState run shadeSpaceBoxColor (griddataShadeSpaceBox $ gamedataGridData gamedata) 1.0 projmodv proj valuePerspectiveRadius $ smoothColor (colormapAt colormap ix) (colormapAt colormap ix') alpha -- cube shadeCube (rundataShadeCube $ gamedataRunData gamedata) 1.0 projmodv normal run -- face names let alpha = cameraViewAlpha $ runCamera run drawFaceNames gamedata alpha projmodv -- message path shadePathFatBegin (griddataShadePath $ gamedataGridData gamedata) 1.0 projmodv shadePathRadius (griddataShadePath $ gamedataGridData gamedata) valueRunPathRadius shadePathColor (griddataShadePath $ gamedataGridData gamedata) valueRunPathColor shadePathDrawPath0 (griddataShadePath $ gamedataGridData gamedata) (gridPath $ runGrid run) shadePathEnd (griddataShadePath $ gamedataGridData gamedata) -- escape corners drawAtFaceCorners gamedata (1.0 - alpha) projmodv s run -- | iterationMain' withouth face names outputScreenAToB :: GameData -> Mat4 -> Mat4 -> Mat4 -> s -> RunWorld -> b -> IO () outputScreenAToB gamedata proj modv normal s run b = do -- 3D -- let projmodv = proj `mappend` modv glEnable gl_DEPTH_TEST glEnable gl_CULL_FACE -- space box let colormap = griddataColorMap $ gamedataGridData gamedata ix = outputstateColorIx $ runOutputState run ix' = outputstateColorIx' $ runOutputState run alpha = outputstateAlpha $ runOutputState run shadeSpaceBoxColor (griddataShadeSpaceBox $ gamedataGridData gamedata) 1.0 projmodv proj valuePerspectiveRadius $ smoothColor (colormapAt colormap ix) (colormapAt colormap ix') alpha -- cube shadeCube (rundataShadeCube $ gamedataRunData gamedata) 1.0 projmodv normal run -- message path shadePathFatBegin (griddataShadePath $ gamedataGridData gamedata) 1.0 projmodv shadePathRadius (griddataShadePath $ gamedataGridData gamedata) valueRunPathRadius shadePathColor (griddataShadePath $ gamedataGridData gamedata) valueRunPathColor shadePathDrawPath0 (griddataShadePath $ gamedataGridData gamedata) (gridPath $ runGrid run) shadePathEnd (griddataShadePath $ gamedataGridData gamedata) -------------------------------------------------------------------------------- -- drawFaceNames :: GameData -> Float -> Mat4 -> IO () drawFaceNames gamedata alpha projmodv = do let fsh = gamedataFontShade gamedata ffd = gamedataFontData gamedata r = fI valueRunCubeRadius fontShade fsh alpha projmodv fontDrawDefault fsh ffd valueRunCubeFontSize valueRunCubeFontColor fontSetPlane3D fsh 0 0 1 0 1 0 fontDraw3DCentered fsh ffd (-r) 0 0 "LevelMode" --fontSetPlane3D fsh 1 0 0 0 1 0 --fontDraw3DCentered fsh ffd 0 0 (r) "Foreign" fontSetPlane3D fsh 0 0 (-1) 0 1 0 fontDraw3DCentered fsh ffd (r) 0 0 "PuzzleMode" fontSetPlane3D fsh (-1) 0 0 0 1 0 fontDraw3DCentered fsh ffd 0 0 (-r) "MemoryMode" drawAtFaceCorners :: GameData -> Float -> Mat4 -> AtFaceState -> RunWorld -> IO () drawAtFaceCorners gamedata alpha projmodv s run = do let Shape wth hth = sceneShape $ runScene run wth' = fI valueRunCubeRadius * wth hth' = fI valueRunCubeRadius * hth r = fI valueRunCubeRadius * 1.001 case atfacestateFace s of FaceLevelMode -> shadeCorners3D (rundataShadeCorners $ gamedataRunData gamedata) alpha projmodv (-r) (-hth') (-wth') (hth * valueSceneCornerSize) 0.0 0.0 (2.0 * wth') (wth * valueSceneCornerSize) 0.0 (2.0 * hth') 0.0 FacePuzzleMode -> shadeCorners3D (rundataShadeCorners $ gamedataRunData gamedata) alpha projmodv (r) (-hth') (wth') (hth * valueSceneCornerSize) 0.0 0.0 (-2.0 * wth') (wth * valueSceneCornerSize) 0.0 (2.0 * hth') 0.0 FaceMemoryMode -> shadeCorners3D (rundataShadeCorners $ gamedataRunData gamedata) alpha projmodv (wth') (-hth') (-r) (hth * valueSceneCornerSize) ((-2.0) * wth') 0.0 0.0 (wth * valueSceneCornerSize) 0.0 (2.0 * hth') 0.0 _ -> return ()
karamellpelle/grid
source/Game/Run/Output/Plain/Screen.hs
gpl-3.0
11,274
0
14
2,982
2,495
1,246
1,249
199
4
{-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE PatternSynonyms #-} -- | Data structures to keep track of some properties of the Ast structure. module Sara.Z3.AstWrapper ( ProofObligation , Assumption , FailureTrackableAst , empty , singleton , conjunct , conditionOn , runAst , runProofObligation , substituteFuncs , findFailure ) where import qualified Sara.Z3.Ast as A import Sara.Z3.CodeGenerator import Sara.Ast.Meta import Data.Maybe import Sara.Errors (VerifierFailureType) import Text.Parsec.Pos (SourcePos) import Z3.Monad import qualified Data.Map as M -- | Ast structure container for which a failure can be tracked to the failing part. data TrackableAst a = Singleton A.Ast a | Conjunction [TrackableAst a] | Condition A.Ast (TrackableAst a) deriving (Eq, Ord, Show) pattern Empty = Conjunction [] -- | A.Ast structure container for which a failure can be tracked. type FailureTrackableAst = TrackableAst (VerifierFailureType, SourcePos) class AstWrapper a b | a -> b where unwrap :: a -> TrackableAst b wrap :: TrackableAst b -> a -- | A.Ast Wrapper for proof obligations. -- We use this to store additional information with the A.Ast and to ensure better type safety. newtype ProofObligation = ProofObligation { unObl :: FailureTrackableAst } deriving (Eq, Ord, Show) -- | A.Ast Wrapper for assumptions. -- We use this to for better type safety. newtype Assumption = Assumption { unAss :: TrackableAst () } deriving (Eq, Ord, Show) instance AstWrapper ProofObligation (VerifierFailureType, SourcePos) where wrap = ProofObligation unwrap = unObl instance AstWrapper Assumption () where wrap = Assumption unwrap = unAss instance AstWrapper (TrackableAst b) b where unwrap = id wrap = id empty :: AstWrapper a b => a empty = wrap Empty singleton :: AstWrapper a b => A.Ast -> b -> a singleton ast = wrap . Singleton ast conjunct :: AstWrapper a b => [a] -> a conjunct as = wrap $ Conjunction $ concatMap extract $ map unwrap $ as where extract (Conjunction as) = as extract a = [a] conditionOn :: AstWrapper a b => A.Ast -> a -> a conditionOn ast = wrap . conditionOn' . unwrap where conditionOn' Empty = Empty conditionOn' a = Condition ast a runAst :: AstWrapper a b => a -> A.Ast runAst a = A.simplify $ runAst' (unwrap a) where runAst' (Conjunction as) = A.NaryOp A.And $ map runAst' as runAst' (Singleton ast _) = ast runAst' (Condition ast a) = A.BinOp A.Implies ast $ runAst' a runProofObligation :: ProofObligation -> FailureTrackableAst runProofObligation = unwrap substituteFuncs :: AstWrapper a b => M.Map A.AppMeta ([VariableMeta], A.Ast) -> a -> a substituteFuncs funcs = wrap . substituteFuncs' . unwrap where substituteFuncs' (Conjunction as) = Conjunction $ map substituteFuncs' as substituteFuncs' (Singleton ast a) = Singleton (A.substituteFuncs funcs ast) a substituteFuncs' (Condition ast a) = Condition (A.substituteFuncs funcs ast) (substituteFuncs' a) -- TODO Move this somewhere else. findFailure :: MonadZ3 z3 => Model -> TrackableAst a -> z3 (Maybe a) findFailure model (Singleton ast result) = do ast' <- codegen ast val <- evalBool model ast' case val of Nothing -> return Nothing Just True -> return Nothing Just False -> return $ Just result findFailure model (Conjunction subs) = do subFailures <- mapM (findFailure model) subs return $ listToMaybe $ catMaybes $ subFailures findFailure model (Condition cond sub) = do cond' <- codegen cond val <- evalBool model cond' case val of Nothing -> return Nothing Just True -> findFailure model sub Just False -> return Nothing
Lykos/Sara
src/lib/Sara/Z3/AstWrapper.hs
gpl-3.0
4,034
3
14
1,008
1,119
576
543
90
5
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.DLP.Projects.DlpJobs.Get -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Gets the latest state of a long-running DlpJob. See -- https:\/\/cloud.google.com\/dlp\/docs\/inspecting-storage and -- https:\/\/cloud.google.com\/dlp\/docs\/compute-risk-analysis to learn -- more. -- -- /See:/ <https://cloud.google.com/dlp/docs/ Cloud Data Loss Prevention (DLP) API Reference> for @dlp.projects.dlpJobs.get@. module Network.Google.Resource.DLP.Projects.DlpJobs.Get ( -- * REST Resource ProjectsDlpJobsGetResource -- * Creating a Request , projectsDlpJobsGet , ProjectsDlpJobsGet -- * Request Lenses , pdjgXgafv , pdjgUploadProtocol , pdjgAccessToken , pdjgUploadType , pdjgName , pdjgCallback ) where import Network.Google.DLP.Types import Network.Google.Prelude -- | A resource alias for @dlp.projects.dlpJobs.get@ method which the -- 'ProjectsDlpJobsGet' request conforms to. type ProjectsDlpJobsGetResource = "v2" :> Capture "name" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Get '[JSON] GooglePrivacyDlpV2DlpJob -- | Gets the latest state of a long-running DlpJob. See -- https:\/\/cloud.google.com\/dlp\/docs\/inspecting-storage and -- https:\/\/cloud.google.com\/dlp\/docs\/compute-risk-analysis to learn -- more. -- -- /See:/ 'projectsDlpJobsGet' smart constructor. data ProjectsDlpJobsGet = ProjectsDlpJobsGet' { _pdjgXgafv :: !(Maybe Xgafv) , _pdjgUploadProtocol :: !(Maybe Text) , _pdjgAccessToken :: !(Maybe Text) , _pdjgUploadType :: !(Maybe Text) , _pdjgName :: !Text , _pdjgCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ProjectsDlpJobsGet' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pdjgXgafv' -- -- * 'pdjgUploadProtocol' -- -- * 'pdjgAccessToken' -- -- * 'pdjgUploadType' -- -- * 'pdjgName' -- -- * 'pdjgCallback' projectsDlpJobsGet :: Text -- ^ 'pdjgName' -> ProjectsDlpJobsGet projectsDlpJobsGet pPdjgName_ = ProjectsDlpJobsGet' { _pdjgXgafv = Nothing , _pdjgUploadProtocol = Nothing , _pdjgAccessToken = Nothing , _pdjgUploadType = Nothing , _pdjgName = pPdjgName_ , _pdjgCallback = Nothing } -- | V1 error format. pdjgXgafv :: Lens' ProjectsDlpJobsGet (Maybe Xgafv) pdjgXgafv = lens _pdjgXgafv (\ s a -> s{_pdjgXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). pdjgUploadProtocol :: Lens' ProjectsDlpJobsGet (Maybe Text) pdjgUploadProtocol = lens _pdjgUploadProtocol (\ s a -> s{_pdjgUploadProtocol = a}) -- | OAuth access token. pdjgAccessToken :: Lens' ProjectsDlpJobsGet (Maybe Text) pdjgAccessToken = lens _pdjgAccessToken (\ s a -> s{_pdjgAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). pdjgUploadType :: Lens' ProjectsDlpJobsGet (Maybe Text) pdjgUploadType = lens _pdjgUploadType (\ s a -> s{_pdjgUploadType = a}) -- | Required. The name of the DlpJob resource. pdjgName :: Lens' ProjectsDlpJobsGet Text pdjgName = lens _pdjgName (\ s a -> s{_pdjgName = a}) -- | JSONP pdjgCallback :: Lens' ProjectsDlpJobsGet (Maybe Text) pdjgCallback = lens _pdjgCallback (\ s a -> s{_pdjgCallback = a}) instance GoogleRequest ProjectsDlpJobsGet where type Rs ProjectsDlpJobsGet = GooglePrivacyDlpV2DlpJob type Scopes ProjectsDlpJobsGet = '["https://www.googleapis.com/auth/cloud-platform"] requestClient ProjectsDlpJobsGet'{..} = go _pdjgName _pdjgXgafv _pdjgUploadProtocol _pdjgAccessToken _pdjgUploadType _pdjgCallback (Just AltJSON) dLPService where go = buildClient (Proxy :: Proxy ProjectsDlpJobsGetResource) mempty
brendanhay/gogol
gogol-dlp/gen/Network/Google/Resource/DLP/Projects/DlpJobs/Get.hs
mpl-2.0
4,865
0
15
1,075
701
412
289
102
1
{-# LANGUAGE OverloadedStrings #-} module Network.Haskoin.Crypto.Mnemonic.Units (tests) where import Data.ByteString (ByteString) import qualified Data.ByteString as BS import qualified Data.ByteString.Char8 as C import Data.Either (fromRight) import Data.List (isPrefixOf) import Data.Maybe (fromJust) import Data.String.Conversions (cs) import Network.Haskoin.Crypto import Network.Haskoin.Internals (fromMnemonic) import Network.Haskoin.Util import Test.Framework (Test, testGroup) import Test.Framework.Providers.HUnit (testCase) import Test.HUnit (assertBool, assertEqual) tests :: [Test] tests = [ testGroup "Entropy to mnemonic sentence" toMnemonicTest , testGroup "Mnemonic sentence to entropy" fromMnemonicTest , testGroup "Mnemonic sentence to seed" mnemonicToSeedTest , testGroup "Mnemonic sentence with invalid checksum" fromMnemonicInvalidTest , testGroup "Empty mnemonic sentence is invalid" [emptyMnemonicTest] ] toMnemonicTest :: [Test] toMnemonicTest = zipWith f ents mss where f e m = g (cs e) . assertEqual "" m . h $ e g = testCase h = fromRight (error "Could not decode mnemonic sentence") . toMnemonic . fromJust . decodeHex fromMnemonicTest :: [Test] fromMnemonicTest = zipWith f ents mss where f e = g (cs e) . assertEqual "" e . h g = testCase h = encodeHex . fromRight (error "Could not decode mnemonic sentence") . fromMnemonic mnemonicToSeedTest :: [Test] mnemonicToSeedTest = zipWith f mss seeds where f m s = g s . assertEqual "" s . h $ m g = testCase . (++ "...") . cs . BS.take 50 h = encodeHex . fromRight (error "Could not decode mnemonic seed") . mnemonicToSeed "TREZOR" fromMnemonicInvalidTest :: [Test] fromMnemonicInvalidTest = map f invalidMss where f m = g m . assertBool "" . h $ m g m = let ms = length (C.words m) msg = concat [ "[MS: ", show ms, "]" , cs (BS.take 50 m), "..." ] in testCase msg h m = case fromMnemonic m of Right _ -> False Left err -> "fromMnemonic: checksum failed:" `isPrefixOf` err emptyMnemonicTest :: Test emptyMnemonicTest = testCase "mnemonic sentence can not be empty" $ assertBool "" $ case fromMnemonic "" of Right _ -> False Left err -> "fromMnemonic: empty mnemonic" `isPrefixOf` err ents :: [ByteString] ents = [ "00000000000000000000000000000000" , "7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f" , "80808080808080808080808080808080" , "ffffffffffffffffffffffffffffffff" , "000000000000000000000000000000000000000000000000" , "7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f" , "808080808080808080808080808080808080808080808080" , "ffffffffffffffffffffffffffffffffffffffffffffffff" , "0000000000000000000000000000000000000000000000000000000000000000" , "7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f7f" , "8080808080808080808080808080808080808080808080808080808080808080" , "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" , "77c2b00716cec7213839159e404db50d" , "b63a9c59a6e641f288ebc103017f1da9f8290b3da6bdef7b" , "3e141609b97933b66a060dcddc71fad1d91677db872031e85f4c015c5e7e8982" , "0460ef47585604c5660618db2e6a7e7f" , "72f60ebac5dd8add8d2a25a797102c3ce21bc029c200076f" , "2c85efc7f24ee4573d2b81a6ec66cee209b2dcbd09d8eddc51e0215b0b68e416" , "eaebabb2383351fd31d703840b32e9e2" , "7ac45cfe7722ee6c7ba84fbc2d5bd61b45cb2fe5eb65aa78" , "4fa1a8bc3e6d80ee1316050e862c1812031493212b7ec3f3bb1b08f168cabeef" , "18ab19a9f54a9274f03e5209a2ac8a91" , "18a2e1d81b8ecfb2a333adcb0c17a5b9eb76cc5d05db91a4" , "15da872c95a13dd738fbf50e427583ad61f18fd99f628c417a61cf8343c90419" ] mss :: [Mnemonic] mss = [ "abandon abandon abandon abandon abandon abandon abandon abandon abandon\ \ abandon abandon about" , "legal winner thank year wave sausage worth useful legal winner thank\ \ yellow" , "letter advice cage absurd amount doctor acoustic avoid letter advice\ \ cage above" , "zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo wrong" , "abandon abandon abandon abandon abandon abandon abandon abandon abandon\ \ abandon abandon abandon abandon abandon abandon abandon abandon agent" , "legal winner thank year wave sausage worth useful legal winner thank\ \ year wave sausage worth useful legal will" , "letter advice cage absurd amount doctor acoustic avoid letter advice\ \ cage absurd amount doctor acoustic avoid letter always" , "zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo\ \ when" , "abandon abandon abandon abandon abandon abandon abandon abandon abandon\ \ abandon abandon abandon abandon abandon abandon abandon abandon abandon\ \ abandon abandon abandon abandon abandon art" , "legal winner thank year wave sausage worth useful legal winner thank\ \ year wave sausage worth useful legal winner thank year wave sausage\ \ worth title" , "letter advice cage absurd amount doctor acoustic avoid letter advice\ \ cage absurd amount doctor acoustic avoid letter advice cage absurd\ \ amount doctor acoustic bless" , "zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo\ \ zoo zoo zoo zoo zoo vote" , "jelly better achieve collect unaware mountain thought cargo oxygen act\ \ hood bridge" , "renew stay biology evidence goat welcome casual join adapt armor shuffle\ \ fault little machine walk stumble urge swap" , "dignity pass list indicate nasty swamp pool script soccer toe leaf photo\ \ multiply desk host tomato cradle drill spread actor shine dismiss\ \ champion exotic" , "afford alter spike radar gate glance object seek swamp infant panel\ \ yellow" , "indicate race push merry suffer human cruise dwarf pole review arch keep\ \ canvas theme poem divorce alter left" , "clutch control vehicle tonight unusual clog visa ice plunge glimpse\ \ recipe series open hour vintage deposit universe tip job dress radar\ \ refuse motion taste" , "turtle front uncle idea crush write shrug there lottery flower risk\ \ shell" , "kiss carry display unusual confirm curtain upgrade antique rotate hello\ \ void custom frequent obey nut hole price segment" , "exile ask congress lamp submit jacket era scheme attend cousin alcohol\ \ catch course end lucky hurt sentence oven short ball bird grab wing top" , "board flee heavy tunnel powder denial science ski answer betray cargo\ \ cat" , "board blade invite damage undo sun mimic interest slam gaze truly\ \ inherit resist great inject rocket museum chief" , "beyond stage sleep clip because twist token leaf atom beauty genius food\ \ business side grid unable middle armed observe pair crouch tonight away\ \ coconut" ] seeds :: [ByteString] seeds = [ "c55257c360c07c72029aebc1b53c05ed0362ada38ead3e3e9efa3708e53495531f09a69\ \87599d18264c1e1c92f2cf141630c7a3c4ab7c81b2f001698e7463b04" , "2e8905819b8723fe2c1d161860e5ee1830318dbf49a83bd451cfb8440c28bd6fa457fe1\ \296106559a3c80937a1c1069be3a3a5bd381ee6260e8d9739fce1f607" , "d71de856f81a8acc65e6fc851a38d4d7ec216fd0796d0a6827a3ad6ed5511a30fa280f1\ \2eb2e47ed2ac03b5c462a0358d18d69fe4f985ec81778c1b370b652a8" , "ac27495480225222079d7be181583751e86f571027b0497b5b5d11218e0a8a133325729\ \17f0f8e5a589620c6f15b11c61dee327651a14c34e18231052e48c069" , "035895f2f481b1b0f01fcf8c289c794660b289981a78f8106447707fdd9666ca06da5a9\ \a565181599b79f53b844d8a71dd9f439c52a3d7b3e8a79c906ac845fa" , "f2b94508732bcbacbcc020faefecfc89feafa6649a5491b8c952cede496c214a0c7b3c3\ \92d168748f2d4a612bada0753b52a1c7ac53c1e93abd5c6320b9e95dd" , "107d7c02a5aa6f38c58083ff74f04c607c2d2c0ecc55501dadd72d025b751bc27fe913f\ \fb796f841c49b1d33b610cf0e91d3aa239027f5e99fe4ce9e5088cd65" , "0cd6e5d827bb62eb8fc1e262254223817fd068a74b5b449cc2f667c3f1f985a76379b43\ \348d952e2265b4cd129090758b3e3c2c49103b5051aac2eaeb890a528" , "bda85446c68413707090a52022edd26a1c9462295029f2e60cd7c4f2bbd3097170af7a4\ \d73245cafa9c3cca8d561a7c3de6f5d4a10be8ed2a5e608d68f92fcc8" , "bc09fca1804f7e69da93c2f2028eb238c227f2e9dda30cd63699232578480a4021b146a\ \d717fbb7e451ce9eb835f43620bf5c514db0f8add49f5d121449d3e87" , "c0c519bd0e91a2ed54357d9d1ebef6f5af218a153624cf4f2da911a0ed8f7a09e2ef61a\ \f0aca007096df430022f7a2b6fb91661a9589097069720d015e4e982f" , "dd48c104698c30cfe2b6142103248622fb7bb0ff692eebb00089b32d22484e1613912f0\ \a5b694407be899ffd31ed3992c456cdf60f5d4564b8ba3f05a69890ad" , "b5b6d0127db1a9d2226af0c3346031d77af31e918dba64287a1b44b8ebf63cdd52676f6\ \72a290aae502472cf2d602c051f3e6f18055e84e4c43897fc4e51a6ff" , "9248d83e06f4cd98debf5b6f010542760df925ce46cf38a1bdb4e4de7d21f5c39366941\ \c69e1bdbf2966e0f6e6dbece898a0e2f0a4c2b3e640953dfe8b7bbdc5" , "ff7f3184df8696d8bef94b6c03114dbee0ef89ff938712301d27ed8336ca89ef9635da2\ \0af07d4175f2bf5f3de130f39c9d9e8dd0472489c19b1a020a940da67" , "65f93a9f36b6c85cbe634ffc1f99f2b82cbb10b31edc7f087b4f6cb9e976e9faf76ff41\ \f8f27c99afdf38f7a303ba1136ee48a4c1e7fcd3dba7aa876113a36e4" , "3bbf9daa0dfad8229786ace5ddb4e00fa98a044ae4c4975ffd5e094dba9e0bb289349db\ \e2091761f30f382d4e35c4a670ee8ab50758d2c55881be69e327117ba" , "fe908f96f46668b2d5b37d82f558c77ed0d69dd0e7e043a5b0511c48c2f1064694a956f\ \86360c93dd04052a8899497ce9e985ebe0c8c52b955e6ae86d4ff4449" , "bdfb76a0759f301b0b899a1e3985227e53b3f51e67e3f2a65363caedf3e32fde42a66c4\ \04f18d7b05818c95ef3ca1e5146646856c461c073169467511680876c" , "ed56ff6c833c07982eb7119a8f48fd363c4a9b1601cd2de736b01045c5eb8ab4f57b079\ \403485d1c4924f0790dc10a971763337cb9f9c62226f64fff26397c79" , "095ee6f817b4c2cb30a5a797360a81a40ab0f9a4e25ecd672a3f58a0b5ba0687c096a6b\ \14d2c0deb3bdefce4f61d01ae07417d502429352e27695163f7447a8c" , "6eff1bb21562918509c73cb990260db07c0ce34ff0e3cc4a8cb3276129fbcb300bddfe0\ \05831350efd633909f476c45c88253276d9fd0df6ef48609e8bb7dca8" , "f84521c777a13b61564234bf8f8b62b3afce27fc4062b51bb5e62bdfecb23864ee6ecf0\ \7c1d5a97c0834307c5c852d8ceb88e7c97923c0a3b496bedd4e5f88a9" , "b15509eaa2d09d3efd3e006ef42151b30367dc6e3aa5e44caba3fe4d3e352e65101fbdb\ \86a96776b91946ff06f8eac594dc6ee1d3e82a42dfe1b40fef6bcc3fd" ] invalidMss :: [Mnemonic] invalidMss = [ "abandon abandon abandon abandon abandon abandon abandon abandon abandon\ \ abandon abandon abandon" , "legal winner thank year wave sausage worth useful legal winner thank\ \ thank" , "letter advice cage absurd amount doctor acoustic avoid letter advice\ \ cage sausage" , "zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo" , "abandon abandon abandon abandon abandon abandon abandon abandon abandon\ \ abandon abandon abandon abandon abandon abandon abandon abandon abandon" , "legal winner thank year wave sausage worth useful legal winner thank\ \ year wave sausage worth useful legal letter" , "letter advice cage absurd amount doctor acoustic avoid letter advice\ \ cage absurd amount doctor acoustic avoid letter abandon" , "zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo\ \ zoo" , "abandon abandon abandon abandon abandon abandon abandon abandon abandon\ \ abandon abandon abandon abandon abandon abandon abandon abandon abandon\ \ abandon abandon abandon abandon abandon abandon" , "legal winner thank year wave sausage worth useful legal winner thank\ \ year wave sausage worth useful legal winner thank year wave sausage\ \ worth letter" , "letter advice cage absurd amount doctor acoustic avoid letter advice\ \ cage absurd amount doctor acoustic avoid letter advice cage absurd\ \ amount doctor acoustic letter" , "zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo\ \ zoo zoo zoo zoo zoo zoo" , "jelly better achieve collect unaware mountain thought cargo oxygen act\ \ hood zoo" , "renew stay biology evidence goat welcome casual join adapt armor shuffle\ \ fault little machine walk stumble urge zoo" , "dignity pass list indicate nasty swamp pool script soccer toe leaf photo\ \ multiply desk host tomato cradle drill spread actor shine dismiss\ \ champion zoo" , "afford alter spike radar gate glance object seek swamp infant panel\ \ zoo" , "indicate race push merry suffer human cruise dwarf pole review arch keep\ \ canvas theme poem divorce alter zoo" , "clutch control vehicle tonight unusual clog visa ice plunge glimpse\ \ recipe series open hour vintage deposit universe tip job dress radar\ \ refuse motion zoo" , "turtle front uncle idea crush write shrug there lottery flower risk\ \ zoo" , "kiss carry display unusual confirm curtain upgrade antique rotate hello\ \ void custom frequent obey nut hole price zoo" , "exile ask congress lamp submit jacket era scheme attend cousin alcohol\ \ catch course end lucky hurt sentence oven short ball bird grab wing zoo" , "board flee heavy tunnel powder denial science ski answer betray cargo\ \ zoo" , "board blade invite damage undo sun mimic interest slam gaze truly\ \ inherit resist great inject rocket museum zoo" , "beyond stage sleep clip because twist token leaf atom beauty genius food\ \ business side grid unable middle armed observe pair crouch tonight away\ \ zoo" ]
plaprade/haskoin
haskoin-core/test/Network/Haskoin/Crypto/Mnemonic/Units.hs
unlicense
14,018
0
16
2,832
1,023
590
433
163
2