code
stringlengths
2
1.05M
repo_name
stringlengths
5
101
path
stringlengths
4
991
language
stringclasses
3 values
license
stringclasses
5 values
size
int64
2
1.05M
-- | Unsafe coerce. module Unsafe.Coerce where import FFI unsafeCoerce :: a -> b unsafeCoerce = ffi "%1"
beni55/fay
fay-base/src/Unsafe/Coerce.hs
Haskell
bsd-3-clause
108
module Network.MPD.Applicative ( Command , runCommand -- * Querying MPD's status , module Network.MPD.Applicative.Status -- * Playback options , module Network.MPD.Applicative.PlaybackOptions -- * Controlling playback , module Network.MPD.Applicative.PlaybackControl -- * The current playlist , module Network.MPD.Applicative.CurrentPlaylist -- * Stored playlists , module Network.MPD.Applicative.StoredPlaylists -- * The music database , module Network.MPD.Applicative.Database -- * Stickers , module Network.MPD.Applicative.Stickers -- * Connection settings , module Network.MPD.Applicative.Connection -- * Audio output devices , module Network.MPD.Applicative.Output -- * Reflection , module Network.MPD.Applicative.Reflection -- * Mounting , module Network.MPD.Applicative.Mount -- * Client-to-client , module Network.MPD.Applicative.ClientToClient ) where import Network.MPD.Applicative.Internal import Network.MPD.Applicative.ClientToClient import Network.MPD.Applicative.Connection import Network.MPD.Applicative.CurrentPlaylist import Network.MPD.Applicative.Database import Network.MPD.Applicative.Mount import Network.MPD.Applicative.Output import Network.MPD.Applicative.PlaybackControl import Network.MPD.Applicative.PlaybackOptions import Network.MPD.Applicative.Reflection import Network.MPD.Applicative.Status import Network.MPD.Applicative.Stickers import Network.MPD.Applicative.StoredPlaylists
matthewleon/libmpd-haskell
src/Network/MPD/Applicative.hs
Haskell
mit
1,428
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE MultiWayIf #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TupleSections #-} module HERMIT.Dictionary.Induction ( -- * Induction externals , caseSplitOnR ) where import Control.Arrow import Control.Monad import Data.String import HERMIT.Context import HERMIT.Core import HERMIT.External import HERMIT.GHC import HERMIT.Kure import HERMIT.Lemma import HERMIT.Name import HERMIT.Dictionary.Common import HERMIT.Dictionary.Local.Case hiding (externals) import HERMIT.Dictionary.Undefined hiding (externals) ------------------------------------------------------------------------------ externals :: [External] externals = [ external "induction" (promoteClauseR . caseSplitOnR True . cmpHN2Var :: HermitName -> RewriteH LCore) [ "Induct on specified value quantifier." ] , external "prove-by-cases" (promoteClauseR . caseSplitOnR False . cmpHN2Var :: HermitName -> RewriteH LCore) [ "Case split on specified value quantifier." ] ] ------------------------------------------------------------------------------ -- TODO: revisit design here to make one level caseSplitOnR :: Bool -> (Id -> Bool) -> RewriteH Clause caseSplitOnR induction idPred = withPatFailMsg "induction can only be performed on universally quantified terms." $ do let p b = idPred b && isId b (bs, cl) <- arr collectQs guardMsg (any p bs) "specified identifier is not universally quantified in this lemma. (Induction cannot be performed on type quantifiers.)" let (as,b:bs') = break p bs -- safe because above guard guardMsg (not (any p bs')) "multiple matching quantifiers." ue <- mkUndefinedValT (varType b) -- undefined case cases <- liftM (ue:) $ constT $ caseExprsForM $ varToCoreExpr b let newBs = as ++ bs' substructural = filter (typeAlphaEq (varType b) . varType) go [] = return [] go (e:es) = do let cl' = substClause b e cl fvs = varSetElems $ delVarSetList (localFreeVarsExpr e) newBs -- Generate induction hypotheses for the recursive cases. antes <- if induction then forM (zip [(0::Int)..] $ substructural fvs) $ \ (i,b') -> withVarsInScope fvs $ transform $ \ c q -> let nm = fromString $ "ind-hyp-" ++ show i in liftM ((nm,) . discardUniVars) $ instClause (boundVars c) (==b) (Var b') q else return [] rs <- go es return $ mkForall fvs (foldr (uncurry Impl) cl' antes) : rs qs <- go cases return $ mkForall newBs $ foldr1 Conj qs
ku-fpg/hermit
src/HERMIT/Dictionary/Induction.hs
Haskell
bsd-2-clause
2,691
module Nat where import Prelude hiding ((+)) data Nat = Zero | Succ Nat deriving (Eq,Show) (+) :: Nat -> Nat -> Nat Zero + n = n (Succ m) + n = Succ (m + n) toNat :: Integer -> Nat toNat 0 = Zero toNat n = Succ (toNat (pred n)) fromNat :: Nat -> Integer fromNat Zero = 0 fromNat (Succ n) = succ (fromNat n)
conal/hermit
examples/fib-stream/Nat.hs
Haskell
bsd-2-clause
315
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE DeriveGeneric #-} module RWPAS.Actor ( sentinelActor , Actor() , ActorID , ActorAppearance(..) -- * Appearance, position, AI , appearance , position , actorName , ai -- * Hit points , hurt , actorHitPoints , emptyHitPoints , hitPointsCritical , hitPointsHealthy , HasHitPoints(..) , HitPoints() , isDeadByHitPoints ) where import Control.Lens import Data.Data import Data.SafeCopy import Data.Text ( Text ) import GHC.Generics import RWPAS.SafeCopyOrphanInstances() import {-# SOURCE #-} RWPAS.Control import {-# SOURCE #-} RWPAS.Control.Types import Linear.V2 data Actor = Actor { _position :: !ActorPosition , _appearance :: !ActorAppearance , _ai :: !AI , _actorName :: !Text , _actorHitPoints :: !(Maybe HitPoints) } deriving ( Eq, Ord, Show, Typeable, Generic ) data ActorAppearance = PlayerCharacter | BeastFrog deriving ( Eq, Ord, Show, Read, Typeable, Data, Generic, Enum ) type ActorID = Int type ActorPosition = V2 Int data HitPoints = HitPoints { _hp :: !Int , _maxHp :: !Int } deriving ( Eq, Ord, Show, Read, Typeable, Data, Generic ) makeLenses ''Actor makeClassy ''HitPoints deriveSafeCopy 0 'base ''Actor deriveSafeCopy 0 'base ''ActorAppearance deriveSafeCopy 0 'base ''HitPoints class HasActor a where actor :: Lens' a Actor instance HasActor Actor where actor = lens id (\_ new -> new) -- | Sentinel actor. Not meant to be used as-is, take it and modify it to be a -- proper actor. sentinelActor :: Text -> Actor sentinelActor name = Actor { _position = V2 0 0 , _appearance = PlayerCharacter , _ai = sentinelAI , _actorName = name , _actorHitPoints = Nothing } isDeadByHitPoints :: HasHitPoints a => a -> Bool isDeadByHitPoints thing = thing^.hitPoints.hp <= 0 || thing^.hitPoints.maxHp <= 0 emptyHitPoints :: HitPoints emptyHitPoints = HitPoints { _hp = 0 , _maxHp = 0 } hurt :: Int -> Actor -> Actor hurt points actor = case actor^.actorHitPoints of Nothing -> actor Just hitp -> actor & actorHitPoints .~ (Just $ hitp & hp -~ points) hitPointsCritical :: HasHitPoints a => a -> Bool hitPointsCritical thing = thing^.hitPoints.hp <= (thing^.hitPoints.maxHp `div` 3) hitPointsHealthy :: HasHitPoints a => a -> Bool hitPointsHealthy thing = thing^.hitPoints.hp >= (thing^.hitPoints.maxHp `div` 3 + thing^.hitPoints.maxHp `div` 3)
Noeda/rwpas
src/RWPAS/Actor.hs
Haskell
mit
2,485
module Nifty.BEB where import Nifty.Message import Control.Exception import Network.Socket hiding (send) import Network.Socket.ByteString (sendAll) import qualified Data.ByteString as L broadcastOnce :: (L.ByteString, L.ByteString) -- (message content, history) -> Char -> [Socket] -> IO () broadcastOnce m pId eSockets = do broadcastOneMessage (assembleMessage m) eSockets where assembleMessage (c, h) = serializeForwardedMessage c pId h broadcastOneMessage :: L.ByteString -> [Socket] -> IO () broadcastOneMessage m sos = do -- putStrLn $ "Sending message " ++ (show m) ++ " to all" mapM_ (\s -> (sendWithError s m) `catch` hndl) sos sendWithError :: Socket -> L.ByteString -> IO () sendWithError sock msg = do sendAll sock msg hndl :: IOError -> IO () hndl _ = -- putStrLn $ "Error sending on socket; some processes are down? " ++( show e) return ()
adizere/nifty-urb
src/Nifty/BEB.hs
Haskell
mit
1,017
-- Unsafe functions -- ref: https://wiki.haskell.org/Unsafe_functions unsafePerformIO :: IO a -> a unsafeInterleaveIO :: IO a -> IO a unsafeInterleaveST :: ST s a -> ST s a unsafeIOToST :: IO a -> ST s a unsafeIOToSTM :: IO a -> STM a unsafeFreeze, unsafeThaw unsafeCoerce# :: a -> b seq :: a -> b -> b -- Unsafe functions can break type safety (unsafeCoerce#, unsafePerformIO), interfere with lazy IO (unsafeInterleaveIO), or break parametricity (seq). Their use (except in the case of seq) would require some kind of assurance on the part of the programmer that what they're doing is safe. -- "unsafe" is also a keyword which can be used in a foreign import declaration. (FFI)
Airtnp/Freshman_Simple_Haskell_Lib
Idioms/Unsafe-functions.hs
Haskell
mit
687
----------------------------------------------------------------------------- -- | -- Module : Algebra.Graph.Test.Graph -- Copyright : (c) Andrey Mokhov 2016-2022 -- License : MIT (see the file LICENSE) -- Maintainer : andrey.mokhov@gmail.com -- Stability : experimental -- -- Testsuite for "Algebra.Graph" and polymorphic functions defined in -- "Algebra.Graph.HigherKinded.Class". ----------------------------------------------------------------------------- module Algebra.Graph.Test.Graph ( -- * Testsuite testGraph ) where import Data.Either import Algebra.Graph import Algebra.Graph.Test import Algebra.Graph.Test.API (toIntAPI, graphAPI) import Algebra.Graph.Test.Generic import Algebra.Graph.ToGraph (reachable) import qualified Data.Graph as KL tPoly :: Testsuite Graph Ord tPoly = ("Graph.", graphAPI) t :: TestsuiteInt Graph t = fmap toIntAPI tPoly type G = Graph Int testGraph :: IO () testGraph = do putStrLn "\n============ Graph ============" test "Axioms of graphs" (axioms @G) test "Theorems of graphs" (theorems @G) testBasicPrimitives t testIsSubgraphOf t testToGraph t testSize t testGraphFamilies t testTransformations t testInduceJust tPoly ---------------------------------------------------------------- -- Generic relational composition tests, plus an additional one testCompose t test "size (compose x y) <= edgeCount x + edgeCount y + 1" $ \(x :: G) y -> size (compose x y) <= edgeCount x + edgeCount y + 1 ---------------------------------------------------------------- putStrLn "\n============ Graph.(===) ============" test " x === x == True" $ \(x :: G) -> (x === x) == True test " x === x + empty == False" $ \(x :: G) -> (x === x + empty)== False test "x + y === x + y == True" $ \(x :: G) y -> (x + y === x + y) == True test "1 + 2 === 2 + 1 == False" $ (1 + 2 === 2 + (1 :: G)) == False test "x + y === x * y == False" $ \(x :: G) y -> (x + y === x * y) == False testMesh tPoly testTorus tPoly testDeBruijn tPoly testSplitVertex t testBind t testSimplify t testBox tPoly putStrLn "\n============ Graph.sparsify ============" test "sort . reachable x == sort . rights . reachable (Right x) . sparsify" $ \x (y :: G) -> (sort . reachable x) y == (sort . rights . reachable (Right x) . sparsify) y test "vertexCount (sparsify x) <= vertexCount x + size x + 1" $ \(x :: G) -> vertexCount (sparsify x) <= vertexCount x + size x + 1 test "edgeCount (sparsify x) <= 3 * size x" $ \(x :: G) -> edgeCount (sparsify x) <= 3 * size x test "size (sparsify x) <= 3 * size x" $ \(x :: G) -> size (sparsify x) <= 3 * size x putStrLn "\n============ Graph.sparsifyKL ============" test "sort . reachable k == sort . filter (<= n) . flip reachable k . sparsifyKL n" $ \(Positive n) -> do let pairs = (,) <$> choose (1, n) <*> choose (1, n) k <- choose (1, n) es <- listOf pairs let x = vertices [1..n] `overlay` edges es return $ (sort . reachable k) x == (sort . filter (<= n) . flip KL.reachable k . sparsifyKL n) x test "length (vertices $ sparsifyKL n x) <= vertexCount x + size x + 1" $ \(Positive n) -> do let pairs = (,) <$> choose (1, n) <*> choose (1, n) es <- listOf pairs let x = vertices [1..n] `overlay` edges es return $ length (KL.vertices $ sparsifyKL n x) <= vertexCount x + size x + 1 test "length (edges $ sparsifyKL n x) <= 3 * size x" $ \(Positive n) -> do let pairs = (,) <$> choose (1, n) <*> choose (1, n) es <- listOf pairs let x = vertices [1..n] `overlay` edges es return $ length (KL.edges $ sparsifyKL n x) <= 3 * size x putStrLn "\n============ Graph.context ============" test "context (const False) x == Nothing" $ \x -> context (const False) (x :: G) == Nothing test "context (== 1) (edge 1 2) == Just (Context [ ] [2 ])" $ context (== 1) (edge 1 2 :: G) == Just (Context [ ] [2 ]) test "context (== 2) (edge 1 2) == Just (Context [1 ] [ ])" $ context (== 2) (edge 1 2 :: G) == Just (Context [1 ] [ ]) test "context (const True ) (edge 1 2) == Just (Context [1 ] [2 ])" $ context (const True ) (edge 1 2 :: G) == Just (Context [1 ] [2 ]) test "context (== 4) (3 * 1 * 4 * 1 * 5) == Just (Context [3,1] [1,5])" $ context (== 4) (3 * 1 * 4 * 1 * 5 :: G) == Just (Context [3,1] [1,5]) putStrLn "\n============ Graph.buildg ============" test "buildg (\\e _ _ _ -> e) == empty" $ buildg (\e _ _ _ -> e) == (empty :: G) test "buildg (\\_ v _ _ -> v x) == vertex x" $ \(x :: Int) -> buildg (\_ v _ _ -> v x) == vertex x test "buildg (\\e v o c -> o (foldg e v o c x) (foldg e v o c y)) == overlay x y" $ \(x :: G) y -> buildg (\e v o c -> o (foldg e v o c x) (foldg e v o c y)) == overlay x y test "buildg (\\e v o c -> c (foldg e v o c x) (foldg e v o c y)) == connect x y" $ \(x :: G) y -> buildg (\e v o c -> c (foldg e v o c x) (foldg e v o c y)) == connect x y test "buildg (\\e v o _ -> foldr o e (map v xs)) == vertices xs" $ \(xs :: [Int]) -> buildg (\e v o _ -> foldr o e (map v xs)) == vertices xs test "buildg (\\e v o c -> foldg e v o (flip c) g) == transpose g" $ \(g :: G) -> buildg (\e v o c -> foldg e v o (flip c) g) == transpose g
snowleopard/alga
test/Algebra/Graph/Test/Graph.hs
Haskell
mit
6,109
{-# LANGUAGE OverloadedStrings #-} module Config.Internal.RabbitMQ ( RabbitMQConfig (..) , readRabbitMQConfig ) where import Data.Text (Text, pack) import System.Environment (getEnv) data RabbitMQConfig = RabbitMQConfig { getHost :: Text , getPath :: Text , getUser :: Text , getPass :: Text , getExchangeName :: Text } deriving (Show, Read, Eq) readRabbitMQConfig :: IO RabbitMQConfig readRabbitMQConfig = RabbitMQConfig <$> getEnvAsText "FC_RABBITMQ_HOST" <*> getEnvAsText "FC_RABBITMQ_PATH" <*> getEnvAsText "FC_RABBITMQ_USER" <*> getEnvAsText "FC_RABBITMQ_PASS" <*> getEnvAsText "FC_RABBITMQ_EXCHANGE_NAME" getEnvAsText :: String -> IO Text getEnvAsText varName = pack <$> (getEnv varName)
gust/feature-creature
legacy/lib/Config/Internal/RabbitMQ.hs
Haskell
mit
808
import Text.Parsec import Text.Parsec.String import Data.Maybe (fromJust) value :: Char -> Int value c = fromJust . lookup c $ [ ('I', 1), ('V', 5), ('X', 10), ('L', 50), ('C', 100), ('D', 500), ('M', 1000)] single :: Char -> Parser Int single c = do x <- many (char c) return $ length x * value c pair :: Char -> Char -> Parser Int pair small big = do string $ small:big:"" return $ value big - value small roman :: Parser Int roman = do m <- single 'M' d <- single 'D' c <- try (pair 'C' 'M') <|> try (pair 'C' 'D') <|> (single 'C') l <- single 'L' x <- try (pair 'X' 'C') <|> try (pair 'X' 'L') <|> (single 'X') v <- single 'V' i <- try (pair 'I' 'X') <|> try (pair 'I' 'V') <|> (single 'I') eof return $ m + d + c + l + x + v + i main = do print $ parse roman "fail" "XVII" print $ parse roman "fail" "IV" print $ parse roman "fail" "IX" print $ parse roman "fail" "MMCDXLVI"
Russell91/roman
09.hs
Haskell
mit
981
{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE RankNTypes, GADTs #-} -- This module requires GHC 8 to compile. module Lang where import Common import DataDynamic -- | This module defines a simple untyped language using the Dynamic module. -- ======================================================================================= -- Simple untyped language. data Exp where Lam :: String -> Exp -> Exp -- ^ Function abstraction as \x . e (:@) :: Exp -> Exp -> Exp -- ^ Function application (e1 e2) Bin :: BinOp -> Exp -> Exp -> Exp -- ^ Binary operator. Uni :: UniOp -> Exp -> Exp Lit :: forall t. (LangType t) => t -> Exp -- ^ literal. Var :: String -> Exp -- ^ Variable. If :: Exp -> Exp -> Exp -> Exp -- ^ Conditional branching. Nill :: Exp -- ^ lists. -- Notice we can use Haskell's let and where syntax to define expressions. -- Useful for debugging and simple viewing. instance Show Exp where show (Lam str e) = "(Lam " ++ str ++ " " ++ show e ++ ")" show (e1 :@ e2) = "(" ++ show e1 ++ " @ " ++ show e2 ++ ")" show (Bin op e1 e2) = "(" ++ show op ++ " " ++ show e1 ++ " " ++ show e2 ++ ")" show (Uni op e) = "(" ++ show op ++ " " ++ show e ++ ")" show (Lit x) = "Lit " ++ show x show (Var x) = "(Var " ++ x ++ ")" show (If e1 e2 e3) = "(If " ++ show e1 ++ " " ++ show e2 ++ " " ++ show e3 ++ ")" show Nill = "[]" -- No alpha equivalance here :/ instance Eq Exp where Lam s e == Lam s' e' = s == s' && e == e' e1 :@ e2 == e1' :@ e2' = e1 == e1' && e2 == e2' Bin op e1 e2 == Bin op' e1' e2' = op == op' && e1 == e1' && e2 == e2' Uni op e == Uni op' e' = op == op' && e == e' -- There has to be a better way to do this? Lit x == Lit x' = toDynamic x == toDynamic x' Var s == Var s' = s == s' If e1 e2 e3 == If e1' e2' e3' = e1 == e1' && e2 == e2' && e3 == e3' Nill == Nill = True _ == _ = False -- =======================================================================================
plclub/cis670-16fa
projects/DynamicLang/src/Lang.hs
Haskell
mit
2,007
module Minibas.Util ( totalScore , quarterUrls , buildScoreData , buildGameData , buildGameData' ) where import Import import Control.Lens ((^.)) import qualified Data.List as L (foldl, sortOn, (!!)) import qualified Data.Map as M (Map, lookup) import Data.Maybe (fromJust) import Data.Time.LocalTime (utcToLocalZonedTime) import Jabara.Persist.Util (toMap, toRecord) import Jabara.Util (listToListMap) import Jabara.Yesod.Util (getResourcePath) totalScore :: [Entity Score] -> (Int, Int) totalScore = L.foldl (\(a,b) (Entity _ score) -> let as = score^.scoreTeamAPoint bs = score^.scoreTeamBPoint in (a+as,b+bs) ) (0,0) quarterUrls :: (MonadHandler m, HandlerSite m ~ App) => GameId -> m [Text] quarterUrls gameId = do firstUrl <- getResourcePath $ GameScoreFirstR gameId secondUrl <- getResourcePath $ GameScoreSecondR gameId thirdUrl <- getResourcePath $ GameScoreThirdR gameId fourthUrl <- getResourcePath $ GameScoreFourthR gameId extraUrl <- getResourcePath $ GameScoreExtraR gameId pure [firstUrl, secondUrl, thirdUrl, fourthUrl, extraUrl] buildScoreData :: (MonadHandler m, HandlerSite m ~ App) => GameId -> Entity Score -> m ScoreData buildScoreData gameId (Entity key score) = do urls <- quarterUrls gameId url <- do let idx = fromEnum $ score^.scoreQuarter pure (urls L.!! idx) pure $ ScoreData { _scoreDataId = key , _scoreDataGame = gameId , _scoreDataQuarter = score^.scoreQuarter , _scoreDataTeamAPoint = score^.scoreTeamAPoint , _scoreDataTeamBPoint = score^.scoreTeamBPoint , _scoreDataLock = score^.scoreLock , _scoreDataUrlBase = url } buildGameData :: (MonadHandler m, HandlerSite m ~ App) => [Entity League] -> [Entity Team] -> [Entity Score] -> Entity Game -> m GameData buildGameData leagues teams scores game = buildGameData' (toMap leagues) (toMap teams) (listToListMap (_scoreGame.toRecord) scores) game buildGameData' :: (MonadHandler m, HandlerSite m ~ App) => M.Map LeagueId League -> M.Map TeamId Team -> M.Map GameId [Entity Score] -> Entity Game -> m GameData buildGameData' leagueMap teamMap scoreMap (Entity gameId game) = do urlBase <- getResourcePath $ GameR gameId urlEdit <- getResourcePath $ GameUiR gameId let scores = L.sortOn (_scoreQuarter.toRecord) $ fromJust $ M.lookup gameId scoreMap total = totalScore scores league = getFromMap (game^.gameLeague) leagueMap teamA = getFromMap (game^.gameTeamA) teamMap teamB = getFromMap (game^.gameTeamB) teamMap scores' <- mapM (buildScoreData gameId) scores date <- liftIO $ utcToLocalZonedTime $ game^.gameDate pure $ GameData { _gameDataId = gameId , _gameDataName = game^.gameName , _gameDataPlace = game^.gamePlace , _gameDataLeague = league , _gameDataLeagueName = (toRecord league)^.leagueName , _gameDataTeamA = teamA , _gameDataTeamAName = (toRecord teamA)^.teamName , _gameDataTeamBName = (toRecord teamB)^.teamName , _gameDataTeamB = teamB , _gameDataTeamAScore = fst total , _gameDataTeamBScore = snd total , _gameDataUrlBase = urlBase , _gameDataUrlEdit = urlEdit , _gameDataDate = date , _gameDataScoreList = scores' } where getFromMap :: PersistEntity r => Key r -> Map (Key r) r -> Entity r getFromMap key entityMap = Entity key $ fromJust $ M.lookup key entityMap
jabaraster/minibas-web
Minibas/Util.hs
Haskell
mit
4,054
{-# Language TemplateHaskell #-} module Labyrinth.Move where import Control.Lens hiding (Action) import Labyrinth.Map data MoveDirection = Towards Direction | Next deriving (Eq) type ActionCondition = String data Action = Go { _amdirection :: MoveDirection } | Shoot { _asdirection :: Direction } | Grenade { _agdirection :: Direction } | Surrender | Conditional { _acif :: ActionCondition , _acthen :: [Action] , _acelse :: [Action] } deriving (Eq) makeLenses ''Action goTowards :: Direction -> Action goTowards = Go . Towards data QueryType = BulletCount | GrenadeCount | PlayerHealth | TreasureCarried deriving (Eq) data Move = Move { _mactions :: [Action] } | ChoosePosition { _mcposition :: Position } | ReorderCell { _mrposition :: Position } | Query { _mqueries :: [QueryType] } | Say { _msstext :: String } deriving (Eq) makeLenses ''Move data CellTypeResult = LandR | ArmoryR | HospitalR | PitR | RiverR | RiverDeltaR deriving (Eq) ctResult :: CellType -> CellTypeResult ctResult Land = LandR ctResult Armory = ArmoryR ctResult Hospital = HospitalR ctResult (Pit _) = PitR ctResult (River _) = RiverR ctResult RiverDelta = RiverDeltaR data TreasureResult = TurnedToAshesR | TrueTreasureR deriving (Eq) data CellEvents = CellEvents { _foundBullets :: Int , _foundGrenades :: Int , _foundTreasures :: Int , _transportedTo :: Maybe CellTypeResult } deriving (Eq) makeLenses ''CellEvents noEvents :: CellEvents noEvents = CellEvents { _foundBullets = 0 , _foundGrenades = 0 , _foundTreasures = 0 , _transportedTo = Nothing } data GoResult = Went { _onto :: CellTypeResult , _wevents :: CellEvents } | WentOutside { _treasureResult :: Maybe TreasureResult } | HitWall { _hitr :: CellEvents } | LostOutside | InvalidMovement deriving (Eq) makeLenses ''GoResult data ShootResult = ShootOK | Scream | NoBullets | Forbidden deriving (Eq, Show) data GrenadeResult = GrenadeOK | NoGrenades deriving (Eq, Show) data ChoosePositionResult = ChosenOK | ChooseAgain deriving (Eq) data ReorderCellResult = ReorderOK { _ronto :: CellTypeResult , _revents :: CellEvents } | ReorderForbidden {} deriving (Eq) makeLenses ''ReorderCellResult data QueryResult = BulletCountR { _qrbullets :: Int } | GrenadeCountR { _qrgrenades :: Int } | HealthR { _qrhealth :: Health } | TreasureCarriedR { _qrtreasure :: Bool } deriving (Eq) makeLenses ''QueryResult data StartResult = StartR { _splayer :: PlayerId , _scell :: CellTypeResult , _sevents :: CellEvents } deriving (Eq) makeLenses ''StartResult data ActionResult = GoR GoResult | ShootR ShootResult | GrenadeR GrenadeResult | Surrendered | WoundedAlert PlayerId Health | ChoosePositionR ChoosePositionResult | ReorderCellR ReorderCellResult | QueryR QueryResult | GameStarted [StartResult] | Draw | WrongTurn | InvalidMove deriving (Eq) data MoveResult = MoveRes [ActionResult] deriving (Eq)
koterpillar/labyrinth
src/Labyrinth/Move.hs
Haskell
mit
4,391
module Monad where import Control.Monad.Except (ExceptT, runExceptT) import Control.Monad.Reader (ReaderT, runReaderT) import Text.Parsec (ParseError) import Config.Types -- | The base monad type Sparker = ExceptT SparkError (ReaderT SparkConfig IO) runSparker :: SparkConfig -> Sparker a -> IO (Either SparkError a) runSparker conf func = runReaderT (runExceptT func) conf data SparkError = ParseError ParseError | PreCompileError [PreCompileError] | CompileError CompileError | DeployError DeployError | UnpredictedError String deriving (Show, Eq) type CompileError = String type PreCompileError = String type DeployError = String
badi/super-user-spark
src/Monad.hs
Haskell
mit
757
{-# LANGUAGE OverloadedStrings #-} module DarkSky.Client ( getForecast , httpRequest ) where import DarkSky.Request import DarkSky.Response (Response) import Data.ByteString.Char8 (pack) import Network.HTTP.Simple as HTTP getForecast :: DarkSky.Request.Request -> IO DarkSky.Response.Response getForecast request = getResponseBody <$> httpJSON (httpRequest request) httpRequest :: DarkSky.Request.Request -> HTTP.Request httpRequest r = setRequestQueryString queryParameters . setRequestPath (pack $ path r) . setRequestHost "api.darksky.net" . setRequestPort 443 . setRequestSecure True $ defaultRequest where queryParameters = convert <$> parameters r convert (key', value') = (pack key', Just $ pack value')
peterstuart/dark-sky
src/DarkSky/Client.hs
Haskell
mit
739
{------------------------------------------------------------------------------ uPuppet: Main program ------------------------------------------------------------------------------} import UPuppet.Errors import UPuppet.Options import UPuppet.CState import UPuppet.AST import UPuppet.Catalog import UPuppet.Parser import UPuppet.Eval import UPuppet.ShowAST import UPuppet.ShowCatalog import UPuppet.ShowJSON import System.Environment (getArgs) import System.IO (hPutStr, stderr) import System.Exit (exitWith, ExitCode(..), exitSuccess) {------------------------------------------------------------------------------ main program ------------------------------------------------------------------------------} main = do -- command line args (opts, files) <- getArgs >>= parseOptions -- process each file on the command line status <- mapM (compileAndSave opts) files -- return failure if any of the compilations fails if (and status) then exitSuccess else exitWith (ExitFailure 1) {------------------------------------------------------------------------------ parse/evaluate/render source from file ------------------------------------------------------------------------------} compile :: CState -> IO (Either Errors String) compile st = do -- parse src <- readFile $ srcPath (sOpts st) astOrError <- parsePuppet st src case astOrError of Right ast -> evaluate st ast Left errs -> return $ Left errs where -- evaluate evaluate :: CState -> AST -> IO (Either Errors String) evaluate st ast = case (format (sOpts st)) of AST_FORMAT -> return $ Right $ showAST st ast otherwise -> do catalogOrError <- evalPuppet st ast case catalogOrError of Right catalog -> render st catalog Left errs -> return $ Left errs -- render render :: CState -> Catalog -> IO (Either Errors String) render st catalog = case (format $ sOpts st) of CATALOG_FORMAT -> return $ Right $ showCatalog st catalog JSON_FORMAT -> return $ Right $ showJSON st catalog otherwise -> error "unsupported output format" {------------------------------------------------------------------------------ compile and save to file (or report errors) ------------------------------------------------------------------------------} compileAndSave :: Opts -> String -> IO (Bool) compileAndSave opts path = do let opts' = opts { srcPath=path } let st = newState opts' resultOrError <- compile st case resultOrError of Left errs -> do hPutStr stderr $ showErrors errs return False Right result -> do let dstPath = outputPath opts' if (dstPath == "-") then putStrLn result else writeFile dstPath (result++"\n") return True
dcspaul/uPuppet
Src/uPuppet.hs
Haskell
mit
2,694
module Control.Monad.Classes.Zoom where import Control.Applicative import Control.Monad import Control.Monad.Trans.Class import Control.Monad.Base import Control.Monad.IO.Class import Control.Monad.Trans.Control import Control.Monad.Classes.Core import Control.Monad.Classes.Effects import Control.Monad.Classes.Reader import Control.Monad.Classes.State import Control.Monad.Classes.Writer import Control.Monad.Classes.Proxied import Data.Functor.Identity import Data.Monoid newtype ZoomT big small m a = ZoomT (Proxied (VLLens big small) m a) deriving (Functor, Applicative, Alternative, Monad, MonadPlus, MonadTrans, MonadBase b, MonadIO) newtype VLLens big small = VLLens (forall f . Functor f => (small -> f small) -> big -> f big) vlGet :: VLLens b a -> b -> a vlGet (VLLens l) s = getConst (l Const s) vlSet :: VLLens b a -> a -> b -> b vlSet (VLLens l) v s = runIdentity (l (\_ -> Identity v) s) -- N.B. applies function eagerly vlMod' :: VLLens b a -> (a -> a) -> b -> b vlMod' (VLLens l) f s = runIdentity (l (\x -> Identity $! f x) s) runZoom :: forall big small m a . (forall f. Functor f => (small -> f small) -> big -> f big) -> ZoomT big small m a -> m a runZoom l a = reify (VLLens l) $ \px -> case a of ZoomT (Proxied f) -> f px type instance CanDo (ZoomT big small m) eff = ZoomCanDo small eff type family ZoomCanDo s eff where ZoomCanDo s (EffState s) = 'True ZoomCanDo s (EffReader s) = 'True ZoomCanDo s (EffWriter s) = 'True ZoomCanDo s eff = 'False instance MonadReader big m => MonadReaderN 'Zero small (ZoomT big small m) where askN _ = ZoomT $ Proxied $ \px -> vlGet (reflect px) `liftM` ask instance MonadState big m => MonadStateN 'Zero small (ZoomT big small m) where stateN _ f = ZoomT $ Proxied $ \px -> let l = reflect px in state $ \s -> case f (vlGet l s) of (a, t') -> (a, vlSet l t' s) instance (MonadState big m, Monoid small) => MonadWriterN 'Zero small (ZoomT big small m) where tellN _ w = ZoomT $ Proxied $ \px -> let l = reflect px in state $ \s -> let s' = vlMod' l (<> w) s in s' `seq` ((), s') instance MonadTransControl (ZoomT big small) where type StT (ZoomT big small) a = a liftWith = defaultLiftWith ZoomT (\(ZoomT a) -> a) restoreT = defaultRestoreT ZoomT instance MonadBaseControl b m => MonadBaseControl b (ZoomT big small m) where type StM (ZoomT big small m) a = StM m a liftBaseWith = defaultLiftBaseWith restoreM = defaultRestoreM
feuerbach/monad-classes
Control/Monad/Classes/Zoom.hs
Haskell
mit
2,504
module Problem6 ( isPalindrome ) where isPalindrome :: (Eq a) => [a] -> Bool isPalindrome str = (reverse str) == str
chanind/haskell-99-problems
Problem6.hs
Haskell
mit
117
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-} module GHCJS.DOM.JSFFI.Generated.CSSFontFaceRule (js_getStyle, getStyle, CSSFontFaceRule, castToCSSFontFaceRule, gTypeCSSFontFaceRule) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord) import Data.Typeable (Typeable) import GHCJS.Types (JSRef(..), JSString, castRef) import GHCJS.Foreign (jsNull) import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..)) import GHCJS.Marshal (ToJSRef(..), FromJSRef(..)) import GHCJS.Marshal.Pure (PToJSRef(..), PFromJSRef(..)) import Control.Monad.IO.Class (MonadIO(..)) import Data.Int (Int64) import Data.Word (Word, Word64) import GHCJS.DOM.Types import Control.Applicative ((<$>)) import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName) import GHCJS.DOM.Enums foreign import javascript unsafe "$1[\"style\"]" js_getStyle :: JSRef CSSFontFaceRule -> IO (JSRef CSSStyleDeclaration) -- | <https://developer.mozilla.org/en-US/docs/Web/API/CSSFontFaceRule.style Mozilla CSSFontFaceRule.style documentation> getStyle :: (MonadIO m) => CSSFontFaceRule -> m (Maybe CSSStyleDeclaration) getStyle self = liftIO ((js_getStyle (unCSSFontFaceRule self)) >>= fromJSRef)
plow-technologies/ghcjs-dom
src/GHCJS/DOM/JSFFI/Generated/CSSFontFaceRule.hs
Haskell
mit
1,396
{-# LANGUAGE PackageImports #-} import "tomato" Application (getApplicationDev) import Network.Wai.Handler.Warp (runSettings, defaultSettings, settingsPort) import Control.Concurrent (forkIO) import System.Directory (doesFileExist, removeFile) import System.Exit (exitSuccess) import Control.Concurrent (threadDelay) main :: IO () main = do putStrLn "Starting devel application" (port, app) <- getApplicationDev forkIO $ runSettings defaultSettings { settingsPort = port } app loop loop :: IO () loop = do threadDelay 100000 e <- doesFileExist "dist/devel-terminate" if e then terminateDevel else loop terminateDevel :: IO () terminateDevel = exitSuccess
twopoint718/tomato
devel.hs
Haskell
bsd-2-clause
700
{-# LANGUAGE Arrows #-} module OSM.XML (parseXMLFile) where import Data.Int (Int64) import Text.XML.HXT.Core import qualified OSM import qualified Data.Map.Strict as Map import qualified Data.Text as T tagElementToKeyValue :: ArrowXml t => t XmlTree (OSM.TagKey, T.Text) tagElementToKeyValue = proc el -> do key <- getAttrValue "k" -< el value <- getAttrValue "v" -< el returnA -< (OSM.TagKey (T.pack key), T.pack value) topLevelTag :: ArrowXml t => String -> t XmlTree XmlTree topLevelTag tag = getChildren >>> hasName "osm" /> hasName tag getOSMTags :: ArrowXml t => t XmlTree OSM.Tags getOSMTags = listA (getChildren >>> hasName "tag" >>> tagElementToKeyValue) >>> arr Map.fromList getOSMID :: ArrowXml a => a XmlTree Int64 getOSMID = getAttrValue "id" >>> arr read getOSMNode :: ArrowXml t => t XmlTree (OSM.Node ()) getOSMNode = topLevelTag "node" >>> proc x -> do nodeId <- getOSMID -< x tags <- getOSMTags -< x latS <- getAttrValue "lat" -< x lonS <- getAttrValue "lon" -< x let lat = read latS let lon = read lonS returnA -< OSM.node (OSM.NodeID nodeId) tags (OSM.Coordinates { OSM.latitude = lat, OSM.longitude = lon }) getOSMWayNodes :: ArrowXml t => t XmlTree [OSM.NodeID] getOSMWayNodes = listA $ getChildren >>> hasName "nd" >>> getAttrValue "ref" >>> arr read >>> arr OSM.NodeID getOSMWay :: ArrowXml t => t XmlTree (OSM.Way ()) getOSMWay = topLevelTag "way" >>> proc x -> do wayId <- getOSMID -< x tags <- getOSMTags -< x nodes <- getOSMWayNodes -< x returnA -< OSM.way (OSM.WayID wayId) tags nodes elementIdByType :: String -> Int64 -> OSM.ElementID elementIdByType "node" i = OSM.ElementNodeID (OSM.NodeID i) elementIdByType "way" i = OSM.ElementWayID (OSM.WayID i) elementIdByType "relation" i = OSM.ElementRelationID (OSM.RelationID i) elementIdByType t _ = error $ "Invalid type " ++ t getOSMRelationMembers :: ArrowXml t => t XmlTree [OSM.RelationMember] getOSMRelationMembers = listA $ getChildren >>> hasName "member" >>> proc x -> do elIdS <- getAttrValue "ref" -< x typeS <- getAttrValue "type" -< x role <- getAttrValue "role" -< x let elId = read elIdS let elementId = elementIdByType typeS elId returnA -< OSM.RelationMember elementId (OSM.RelationRole (T.pack role)) getOSMRelation :: ArrowXml t => t XmlTree (OSM.Relation ()) getOSMRelation = topLevelTag "relation" >>> proc x -> do relationId <- getOSMID -< x tags <- getOSMTags -< x members <- getOSMRelationMembers -< x returnA -< OSM.relation (OSM.RelationID relationId) tags members listToMap :: (Ord i) => [OSM.Element i p v] -> Map.Map i (OSM.Element i p v) listToMap list = Map.fromList $ map (\o -> (OSM.id o, o)) list getOSMEverything :: ArrowXml t => t XmlTree (OSM.Dataset ()) getOSMEverything = proc x -> do nodes <- listA getOSMNode -< x ways <- listA getOSMWay -< x relations <- listA getOSMRelation -< x let nodesMap = listToMap nodes let waysMap = listToMap ways let relationsMap = listToMap relations returnA -< OSM.Dataset nodesMap waysMap relationsMap parseXMLFile :: String -> IO (OSM.Dataset ()) parseXMLFile filename = do results <- runX (readDocument [] filename >>> getOSMEverything) return (case results of [result] -> result _ -> error "No result")
kolen/ptwatch
src/OSM/XML.hs
Haskell
bsd-2-clause
3,325
{-# LANGUAGE Arrows #-} {-# LANGUAGE FlexibleContexts #-} module Main where import qualified QuickCheck import Opaleye (Column, Nullable, Query, QueryArr, (.==), (.>)) import qualified Opaleye as O import qualified Database.PostgreSQL.Simple as PGS import qualified Data.Profunctor.Product.Default as D import qualified Data.Profunctor.Product as PP import qualified Data.Profunctor as P import qualified Data.Ord as Ord import qualified Data.List as L import Data.Monoid ((<>)) import qualified Data.String as String import qualified System.Exit as Exit import qualified System.Environment as Environment import qualified Control.Applicative as A import qualified Control.Arrow as Arr import Control.Arrow ((&&&), (***), (<<<), (>>>)) import GHC.Int (Int64) -- { Set your test database info here. Then invoke the 'main' -- function to run the tests, or just use 'cabal test'. The test -- database must already exist and the test user must have -- permissions to modify it. connectInfo :: PGS.ConnectInfo connectInfo = PGS.ConnectInfo { PGS.connectHost = "localhost" , PGS.connectPort = 25433 , PGS.connectUser = "tom" , PGS.connectPassword = "tom" , PGS.connectDatabase = "opaleye_test" } connectInfoTravis :: PGS.ConnectInfo connectInfoTravis = PGS.ConnectInfo { PGS.connectHost = "localhost" , PGS.connectPort = 5432 , PGS.connectUser = "postgres" , PGS.connectPassword = "" , PGS.connectDatabase = "opaleye_test" } -- } {- Status ====== The tests here are very superficial and pretty much the bare mininmum that needs to be tested. Future ====== The overall approach to testing should probably go as follows. 1. Test all individual units of functionality by running them on a table and checking that they produce the expected result. This type of testing is amenable to the QuickCheck approach if we reimplement the individual units of functionality in Haskell. 2. Test that "the denotation is an arrow morphism" is correct. I think in combination with 1. this is all that will be required to demonstrate that the library is correct. "The denotation is an arrow morphism" means that for each arrow operation, the denotation preserves the operation. If we have f :: QueryArr wiresa wiresb then [f] should be something like [f] :: a -> IO [b] f as = runQuery (toValues as >>> f) For example, take the operation >>>. We need to check that [f >>> g] = [f] >>> [g] for all f and g, where [] means the denotation. We would also want to check that [id] = id and [first f] = first [f] I think checking these operations is sufficient because all the other QueryArr operations are implemented in terms of them. (Here I'm taking a slight liberty as `a -> IO [b]` is not directly an arrow, but it could be made one straightforwardly. (For the laws to be satisfied, perhaps we have to assume that the IO actions commute.)) I don't think this type of testing is amenable to QuickCheck. It seems we have to check the properties for arbitrary arrows indexed by arbitrary types. I don't think QuickCheck supports this sort of randomised testing. Note ---- This seems to be equivalent to just reimplementing Opaleye in Haskell-side terms and comparing the results of queries run in both ways. -} twoIntTable :: String -> O.Table (Column O.PGInt4, Column O.PGInt4) (Column O.PGInt4, Column O.PGInt4) twoIntTable n = O.Table n (PP.p2 (O.required "column1", O.required "column2")) table1 :: O.Table (Column O.PGInt4, Column O.PGInt4) (Column O.PGInt4, Column O.PGInt4) table1 = twoIntTable "table1" table1F :: O.Table (Column O.PGInt4, Column O.PGInt4) (Column O.PGInt4, Column O.PGInt4) table1F = fmap (\(col1, col2) -> (col1 + col2, col1 - col2)) table1 -- This is implicitly testing our ability to handle upper case letters in table names. table2 :: O.Table (Column O.PGInt4, Column O.PGInt4) (Column O.PGInt4, Column O.PGInt4) table2 = twoIntTable "TABLE2" table3 :: O.Table (Column O.PGInt4, Column O.PGInt4) (Column O.PGInt4, Column O.PGInt4) table3 = twoIntTable "table3" table4 :: O.Table (Column O.PGInt4, Column O.PGInt4) (Column O.PGInt4, Column O.PGInt4) table4 = twoIntTable "table4" table5 :: O.Table (Maybe (Column O.PGInt4), Maybe (Column O.PGInt4)) (Column O.PGInt4, Column O.PGInt4) table5 = O.TableWithSchema "public" "table5" (PP.p2 (O.optional "column1", O.optional "column2")) table6 :: O.Table (Column O.PGText, Column O.PGText) (Column O.PGText, Column O.PGText) table6 = O.Table "table6" (PP.p2 (O.required "column1", O.required "column2")) tableKeywordColNames :: O.Table (Column O.PGInt4, Column O.PGInt4) (Column O.PGInt4, Column O.PGInt4) tableKeywordColNames = O.Table "keywordtable" (PP.p2 (O.required "column", O.required "where")) table1Q :: Query (Column O.PGInt4, Column O.PGInt4) table1Q = O.queryTable table1 table2Q :: Query (Column O.PGInt4, Column O.PGInt4) table2Q = O.queryTable table2 table3Q :: Query (Column O.PGInt4, Column O.PGInt4) table3Q = O.queryTable table3 table6Q :: Query (Column O.PGText, Column O.PGText) table6Q = O.queryTable table6 table1dataG :: Num a => [(a, a)] table1dataG = [ (1, 100) , (1, 100) , (1, 200) , (2, 300) ] table1data :: [(Int, Int)] table1data = table1dataG table1columndata :: [(Column O.PGInt4, Column O.PGInt4)] table1columndata = table1dataG table2dataG :: Num a => [(a, a)] table2dataG = [ (1, 100) , (3, 400) ] table2data :: [(Int, Int)] table2data = table2dataG table2columndata :: [(Column O.PGInt4, Column O.PGInt4)] table2columndata = table2dataG table3dataG :: Num a => [(a, a)] table3dataG = [ (1, 50) ] table3data :: [(Int, Int)] table3data = table3dataG table3columndata :: [(Column O.PGInt4, Column O.PGInt4)] table3columndata = table3dataG table4dataG :: Num a => [(a, a)] table4dataG = [ (1, 10) , (2, 20) ] table4data :: [(Int, Int)] table4data = table4dataG table4columndata :: [(Column O.PGInt4, Column O.PGInt4)] table4columndata = table4dataG table6data :: [(String, String)] table6data = [("xy", "a"), ("z", "a"), ("more text", "a")] table6columndata :: [(Column O.PGText, Column O.PGText)] table6columndata = map (\(column1, column2) -> (O.pgString column1, O.pgString column2)) table6data -- We have to quote the table names here because upper case letters in -- table names are treated as lower case unless the name is quoted! dropAndCreateTable :: String -> (String, [String]) -> PGS.Query dropAndCreateTable columnType (t, cols) = String.fromString drop_ where drop_ = "DROP TABLE IF EXISTS \"public\".\"" ++ t ++ "\";" ++ "CREATE TABLE \"public\".\"" ++ t ++ "\"" ++ " (" ++ commas cols ++ ");" integer c = ("\"" ++ c ++ "\"" ++ " " ++ columnType) commas = L.intercalate "," . map integer dropAndCreateTableInt :: (String, [String]) -> PGS.Query dropAndCreateTableInt = dropAndCreateTable "integer" dropAndCreateTableText :: (String, [String]) -> PGS.Query dropAndCreateTableText = dropAndCreateTable "text" -- We have to quote the table names here because upper case letters in -- table names are treated as lower case unless the name is quoted! dropAndCreateTableSerial :: (String, [String]) -> PGS.Query dropAndCreateTableSerial (t, cols) = String.fromString drop_ where drop_ = "DROP TABLE IF EXISTS \"public\".\"" ++ t ++ "\";" ++ "CREATE TABLE \"public\".\"" ++ t ++ "\"" ++ " (" ++ commas cols ++ ");" integer c = ("\"" ++ c ++ "\"" ++ " SERIAL") commas = L.intercalate "," . map integer type Table_ = (String, [String]) -- This should ideally be derived from the table definition above columns2 :: String -> Table_ columns2 t = (t, ["column1", "column2"]) -- This should ideally be derived from the table definition above tables :: [Table_] tables = map columns2 ["table1", "TABLE2", "table3", "table4"] ++ [("keywordtable", ["column", "where"])] serialTables :: [Table_] serialTables = map columns2 ["table5"] dropAndCreateDB :: PGS.Connection -> IO () dropAndCreateDB conn = do mapM_ execute tables _ <- executeTextTable mapM_ executeSerial serialTables where execute = PGS.execute_ conn . dropAndCreateTableInt executeTextTable = (PGS.execute_ conn . dropAndCreateTableText . columns2) "table6" executeSerial = PGS.execute_ conn . dropAndCreateTableSerial type Test = PGS.Connection -> IO Bool testG :: D.Default O.QueryRunner wires haskells => Query wires -> ([haskells] -> b) -> PGS.Connection -> IO b testG q p conn = do result <- O.runQuery conn q return (p result) testSelect :: Test testSelect = testG table1Q (\r -> L.sort table1data == L.sort r) testProduct :: Test testProduct = testG query (\r -> L.sort (A.liftA2 (,) table1data table2data) == L.sort r) where query = table1Q &&& table2Q testRestrict :: Test testRestrict = testG query (\r -> filter ((== 1) . fst) (L.sort table1data) == L.sort r) where query = proc () -> do t <- table1Q -< () O.restrict -< fst t .== 1 Arr.returnA -< t testNum :: Test testNum = testG query expected where query :: Query (Column O.PGInt4) query = proc () -> do t <- table1Q -< () Arr.returnA -< op t expected = \r -> L.sort (map op table1data) == L.sort r op :: Num a => (a, a) -> a op (x, y) = abs (x - 5) * signum (x - 4) * (y * y + 1) testDiv :: Test testDiv = testG query expected where query :: Query (Column O.PGFloat8) query = proc () -> do t <- Arr.arr (O.doubleOfInt *** O.doubleOfInt) <<< table1Q -< () Arr.returnA -< op t expected r = L.sort (map (op . toDoubles) table1data) == L.sort r op :: Fractional a => (a, a) -> a -- Choosing 0.5 here as it should be exactly representable in -- floating point op (x, y) = y / x * 0.5 toDoubles :: (Int, Int) -> (Double, Double) toDoubles = fromIntegral *** fromIntegral -- TODO: need to implement and test case_ returning tuples testCase :: Test testCase = testG q (== expected) where q :: Query (Column O.PGInt4) q = table1Q >>> proc (i, j) -> do Arr.returnA -< O.case_ [(j .== 100, 12), (i .== 1, 21)] 33 expected :: [Int] expected = [12, 12, 21, 33] testDistinct :: Test testDistinct = testG (O.distinct table1Q) (\r -> L.sort (L.nub table1data) == L.sort r) -- FIXME: the unsafeCoerceColumn is currently needed because the type -- changes required for aggregation are not currently dealt with by -- Opaleye. aggregateCoerceFIXME :: QueryArr (Column O.PGInt4) (Column O.PGInt8) aggregateCoerceFIXME = Arr.arr aggregateCoerceFIXME' aggregateCoerceFIXME' :: Column a -> Column O.PGInt8 aggregateCoerceFIXME' = O.unsafeCoerceColumn testAggregate :: Test testAggregate = testG (Arr.second aggregateCoerceFIXME <<< O.aggregate (PP.p2 (O.groupBy, O.sum)) table1Q) (\r -> [(1, 400) :: (Int, Int64), (2, 300)] == L.sort r) testAggregateFunction :: Test testAggregateFunction = testG (Arr.second aggregateCoerceFIXME <<< O.aggregate (PP.p2 (O.groupBy, O.sum)) (fmap (\(x, y) -> (x + 1, y)) table1Q)) (\r -> [(2, 400) :: (Int, Int64), (3, 300)] == L.sort r) testAggregateProfunctor :: Test testAggregateProfunctor = testG q expected where q = O.aggregate (PP.p2 (O.groupBy, countsum)) table1Q expected r = [(1, 1200) :: (Int, Int64), (2, 300)] == L.sort r countsum = P.dimap (\x -> (x,x)) (\(x, y) -> aggregateCoerceFIXME' x * y) (PP.p2 (O.sum, O.count)) testStringArrayAggregate :: Test testStringArrayAggregate = testG q expected where q = O.aggregate (PP.p2 (O.arrayAgg, O.min)) table6Q expected r = [(map fst table6data, minimum (map snd table6data))] == r testStringAggregate :: Test testStringAggregate = testG q expected where q = O.aggregate (PP.p2 ((O.stringAgg . O.pgString) "_", O.groupBy)) table6Q expected r = [( (foldl1 (\x y -> x ++ "_" ++ y) . map fst) table6data , head (map snd table6data))] == r testOrderByG :: O.Order (Column O.PGInt4, Column O.PGInt4) -> ((Int, Int) -> (Int, Int) -> Ordering) -> Test testOrderByG orderQ order = testG (O.orderBy orderQ table1Q) (L.sortBy order table1data ==) testOrderBy :: Test testOrderBy = testOrderByG (O.desc snd) (flip (Ord.comparing snd)) testOrderBy2 :: Test testOrderBy2 = testOrderByG (O.desc fst <> O.asc snd) (flip (Ord.comparing fst) <> Ord.comparing snd) testOrderBySame :: Test testOrderBySame = testOrderByG (O.desc fst <> O.asc fst) (flip (Ord.comparing fst) <> Ord.comparing fst) testLOG :: (Query (Column O.PGInt4, Column O.PGInt4) -> Query (Column O.PGInt4, Column O.PGInt4)) -> ([(Int, Int)] -> [(Int, Int)]) -> Test testLOG olQ ol = testG (olQ (orderQ table1Q)) (ol (order table1data) ==) where orderQ = O.orderBy (O.desc snd) order = L.sortBy (flip (Ord.comparing snd)) testLimit :: Test testLimit = testLOG (O.limit 2) (take 2) testOffset :: Test testOffset = testLOG (O.offset 2) (drop 2) testLimitOffset :: Test testLimitOffset = testLOG (O.limit 2 . O.offset 2) (take 2 . drop 2) testOffsetLimit :: Test testOffsetLimit = testLOG (O.offset 2 . O.limit 2) (drop 2 . take 2) testDistinctAndAggregate :: Test testDistinctAndAggregate = testG q expected where q = O.distinct table1Q &&& (Arr.second aggregateCoerceFIXME <<< O.aggregate (PP.p2 (O.groupBy, O.sum)) table1Q) expected r = L.sort r == L.sort expectedResult expectedResult = A.liftA2 (,) (L.nub table1data) [(1 :: Int, 400 :: Int64), (2, 300)] one :: Query (Column O.PGInt4) one = Arr.arr (const (1 :: Column O.PGInt4)) -- The point of the "double" tests is to ensure that we do not -- introduce name clashes in the operations which create new column names testDoubleG :: (Eq haskells, D.Default O.QueryRunner columns haskells) => (QueryArr () (Column O.PGInt4) -> QueryArr () columns) -> [haskells] -> Test testDoubleG q expected1 = testG (q one &&& q one) (== expected2) where expected2 = A.liftA2 (,) expected1 expected1 testDoubleDistinct :: Test testDoubleDistinct = testDoubleG O.distinct [1 :: Int] testDoubleAggregate :: Test testDoubleAggregate = testDoubleG (O.aggregate O.count) [1 :: Int64] testDoubleLeftJoin :: Test testDoubleLeftJoin = testDoubleG lj [(1 :: Int, Just (1 :: Int))] where lj :: Query (Column O.PGInt4) -> Query (Column O.PGInt4, Column (Nullable O.PGInt4)) lj q = O.leftJoin q q (uncurry (.==)) testDoubleValues :: Test testDoubleValues = testDoubleG v [1 :: Int] where v :: Query (Column O.PGInt4) -> Query (Column O.PGInt4) v _ = O.values [1] testDoubleUnionAll :: Test testDoubleUnionAll = testDoubleG u [1 :: Int, 1] where u q = q `O.unionAll` q aLeftJoin :: Query ((Column O.PGInt4, Column O.PGInt4), (Column (Nullable O.PGInt4), Column (Nullable O.PGInt4))) aLeftJoin = O.leftJoin table1Q table3Q (\(l, r) -> fst l .== fst r) testLeftJoin :: Test testLeftJoin = testG aLeftJoin (== expected) where expected :: [((Int, Int), (Maybe Int, Maybe Int))] expected = [ ((1, 100), (Just 1, Just 50)) , ((1, 100), (Just 1, Just 50)) , ((1, 200), (Just 1, Just 50)) , ((2, 300), (Nothing, Nothing)) ] testLeftJoinNullable :: Test testLeftJoinNullable = testG q (== expected) where q :: Query ((Column O.PGInt4, Column O.PGInt4), ((Column (Nullable O.PGInt4), Column (Nullable O.PGInt4)), (Column (Nullable O.PGInt4), Column (Nullable O.PGInt4)))) q = O.leftJoin table3Q aLeftJoin cond cond (x, y) = fst x .== fst (fst y) expected :: [((Int, Int), ((Maybe Int, Maybe Int), (Maybe Int, Maybe Int)))] expected = [ ((1, 50), ((Just 1, Just 100), (Just 1, Just 50))) , ((1, 50), ((Just 1, Just 100), (Just 1, Just 50))) , ((1, 50), ((Just 1, Just 200), (Just 1, Just 50))) ] testThreeWayProduct :: Test testThreeWayProduct = testG q (== expected) where q = A.liftA3 (,,) table1Q table2Q table3Q expected = A.liftA3 (,,) table1data table2data table3data testValues :: Test testValues = testG (O.values values) (values' ==) where values :: [(Column O.PGInt4, Column O.PGInt4)] values = [ (1, 10) , (2, 100) ] values' :: [(Int, Int)] values' = [ (1, 10) , (2, 100) ] {- FIXME: does not yet work testValuesDouble :: Test testValuesDouble = testG (O.values values) (values' ==) where values :: [(Column O.PGInt4, Column O.PGFloat8)] values = [ (1, 10.0) , (2, 100.0) ] values' :: [(Int, Double)] values' = [ (1, 10.0) , (2, 100.0) ] -} testValuesEmpty :: Test testValuesEmpty = testG (O.values values) (values' ==) where values :: [Column O.PGInt4] values = [] values' :: [Int] values' = [] testUnionAll :: Test testUnionAll = testG (table1Q `O.unionAll` table2Q) (\r -> L.sort (table1data ++ table2data) == L.sort r) testTableFunctor :: Test testTableFunctor = testG (O.queryTable table1F) (result ==) where result = fmap (\(col1, col2) -> (col1 + col2, col1 - col2)) table1data -- TODO: This is getting too complicated testUpdate :: Test testUpdate conn = do _ <- O.runUpdate conn table4 update cond result <- runQueryTable4 if result /= expected then return False else do _ <- O.runDelete conn table4 condD resultD <- runQueryTable4 if resultD /= expectedD then return False else do returned <- O.runInsertReturning conn table4 insertT returning _ <- O.runInsertMany conn table4 insertTMany resultI <- runQueryTable4 return ((resultI == expectedI) && (returned == expectedR)) where update (x, y) = (x + y, x - y) cond (_, y) = y .> 15 condD (x, _) = x .> 20 expected :: [(Int, Int)] expected = [ (1, 10) , (22, -18)] expectedD :: [(Int, Int)] expectedD = [(1, 10)] runQueryTable4 = O.runQuery conn (O.queryTable table4) insertT :: (Column O.PGInt4, Column O.PGInt4) insertT = (1, 2) insertTMany :: [(Column O.PGInt4, Column O.PGInt4)] insertTMany = [(20, 30), (40, 50)] expectedI :: [(Int, Int)] expectedI = [(1, 10), (1, 2), (20, 30), (40, 50)] returning (x, y) = x - y expectedR :: [Int] expectedR = [-1] testKeywordColNames :: Test testKeywordColNames conn = do let q :: IO [(Int, Int)] q = O.runQuery conn (O.queryTable tableKeywordColNames) _ <- q return True testInsertSerial :: Test testInsertSerial conn = do _ <- O.runInsert conn table5 (Just 10, Just 20) _ <- O.runInsert conn table5 (Just 30, Nothing) _ <- O.runInsert conn table5 (Nothing, Nothing) _ <- O.runInsert conn table5 (Nothing, Just 40) resultI <- O.runQuery conn (O.queryTable table5) return (resultI == expected) where expected :: [(Int, Int)] expected = [ (10, 20) , (30, 1) , (1, 2) , (2, 40) ] allTests :: [Test] allTests = [testSelect, testProduct, testRestrict, testNum, testDiv, testCase, testDistinct, testAggregate, testAggregateFunction, testAggregateProfunctor, testStringAggregate, testOrderBy, testOrderBy2, testOrderBySame, testLimit, testOffset, testLimitOffset, testOffsetLimit, testDistinctAndAggregate, testDoubleDistinct, testDoubleAggregate, testDoubleLeftJoin, testDoubleValues, testDoubleUnionAll, testLeftJoin, testLeftJoinNullable, testThreeWayProduct, testValues, testValuesEmpty, testUnionAll, testTableFunctor, testUpdate, testKeywordColNames, testInsertSerial ] -- Environment.getEnv throws an exception on missing environment variable! getEnv :: String -> IO (Maybe String) getEnv var = do environment <- Environment.getEnvironment return (lookup var environment) -- Using an envvar is unpleasant, but it will do for now. travis :: IO Bool travis = do travis' <- getEnv "TRAVIS" return (case travis' of Nothing -> False Just "yes" -> True Just _ -> False) main :: IO () main = do travis' <- travis let connectInfo' = if travis' then connectInfoTravis else connectInfo conn <- PGS.connect connectInfo' dropAndCreateDB conn let insert (writeable, columndata) = mapM_ (O.runInsert conn writeable) columndata mapM_ insert [ (table1, table1columndata) , (table2, table2columndata) , (table3, table3columndata) , (table4, table4columndata) ] insert (table6, table6columndata) -- Need to run quickcheck after table data has been inserted QuickCheck.run conn results <- mapM ($ conn) allTests print results let passed = and results putStrLn (if passed then "All passed" else "Failure") Exit.exitWith (if passed then Exit.ExitSuccess else Exit.ExitFailure 1)
benkolera/haskell-opaleye
Test/Test.hs
Haskell
bsd-3-clause
22,190
{-# LANGUAGE CPP, ScopedTypeVariables, NoImplicitPrelude #-} -- | Compatibility module to work around differences in the -- types of functions between pandoc < 2.0 and pandoc >= 2.0. module Text.CSL.Compat.Pandoc ( writeMarkdown, writePlain, writeNative, writeHtmlString, readNative, readHtml, readMarkdown, readLaTeX, fetchItem, pipeProcess ) where import Prelude import qualified Control.Exception as E import System.Exit (ExitCode) import Data.ByteString.Lazy as BL import Data.ByteString as B import Data.Text (Text) import Text.Pandoc (Extension (..), Pandoc, ReaderOptions(..), WrapOption(..), WriterOptions(..), def, pandocExtensions) import qualified Text.Pandoc as Pandoc import qualified Text.Pandoc.Process import qualified Data.Text as T import Text.Pandoc.MIME (MimeType) import Text.Pandoc.Error (PandocError) import Text.Pandoc.Class (runPure, runIO) import qualified Text.Pandoc.Class (fetchItem) import Control.Monad.Except (runExceptT, lift) import Text.Pandoc.Extensions (extensionsFromList, disableExtension) readHtml :: Text -> Pandoc readHtml = either mempty id . runPure . Pandoc.readHtml def{ readerExtensions = extensionsFromList [Ext_native_divs, Ext_native_spans, Ext_raw_html, Ext_smart] } readMarkdown :: Text -> Pandoc readMarkdown = either mempty id . runPure . Pandoc.readMarkdown def{ readerExtensions = pandocExtensions, readerStandalone = True } readLaTeX :: Text -> Pandoc readLaTeX = either mempty id . runPure . Pandoc.readLaTeX def{ readerExtensions = extensionsFromList [Ext_raw_tex, Ext_smart] } readNative :: Text -> Pandoc readNative = either mempty id . runPure . Pandoc.readNative def writeMarkdown, writePlain, writeNative, writeHtmlString :: Pandoc -> Text writeMarkdown = either mempty id . runPure . Pandoc.writeMarkdown def{ writerExtensions = disableExtension Ext_smart $ disableExtension Ext_bracketed_spans $ disableExtension Ext_raw_attribute $ pandocExtensions, writerWrapText = WrapNone } writePlain = either mempty id . runPure . Pandoc.writePlain def writeNative = either mempty id . runPure . Pandoc.writeNative def{ writerTemplate = Just mempty } writeHtmlString = either mempty id . runPure . Pandoc.writeHtml4String def{ writerExtensions = extensionsFromList [Ext_native_divs, Ext_native_spans, Ext_raw_html], writerWrapText = WrapPreserve } pipeProcess :: Maybe [(String, String)] -> FilePath -> [String] -> BL.ByteString -> IO (ExitCode,BL.ByteString) pipeProcess = Text.Pandoc.Process.pipeProcess fetchItem :: String -> IO (Either E.SomeException (B.ByteString, Maybe MimeType)) fetchItem s = do res <- runIO $ runExceptT $ lift $ Text.Pandoc.Class.fetchItem $ T.pack s return $ case res of Left e -> Left (E.toException e) Right (Left (e :: PandocError)) -> Left (E.toException e) Right (Right r) -> Right r
jgm/pandoc-citeproc
compat/Text/CSL/Compat/Pandoc.hs
Haskell
bsd-3-clause
3,016
module Main where import System.IO import System.Environment import System.Exit import Config import Store import Twitter main :: IO () main = do config <- getConfig articles <- unpostedArticles def let keys = twKeys (cfg_consumer_key config) (cfg_consumer_secret config) (cfg_access_token config) (cfg_access_token_secret config) mapM_ (post keys) articles where getConfig :: IO Config getConfig = getArgs >>= eachCase eachCase args | n == 1 = loadConfig $ args !! 0 | otherwise = do hPutStrLn stderr "Usage: ndpost config_file" exitFailure where n = length args
yunomu/nicodicbot
src/NdPost.hs
Haskell
bsd-3-clause
687
module Codegen.Monad ( ) where import Control.Monad.Trans.Class import Control.Monad.Writer import LLVM.General.AST import Core.Unique newtype GeneratorT m a = GeneratorT { runGeneratorT' :: WriterT [Definition] m a } deriving (Functor, Applicative, Monad) class MonadGenerator m where newDefinition :: Definition -> m () instance MonadGenerator (GeneratorT m) where newDefinition = GeneratorT . tell . pure instance MonadTrans GeneratorT where lift = GeneratorT runGeneratorT :: UniqueT m a -> m a runGeneratorT = flip evalStateT 0 . runUniqueT' instance MonadUnique m => MonadUnique (StateT s m) where uid = lift uid instance MonadUnique m => MonadUnique (ReaderT s m) where uid = lift uid instance MonadUnique m => MonadUnique (WriterT s m) where uid = lift uid instance MonadUnique m => MonadUnique (ExceptT e m) where uid = lift uid type Generator = UniqueT (Writer [Definition])
abbradar/dnohs
src/Codegen/Monad.hs
Haskell
bsd-3-clause
944
{-# LANGUAGE OverloadedStrings #-} module Data.Text.ExtraTest (test_tests) where import Elm.Utils ((|>)) import Test.Tasty import Test.Tasty.HUnit import Data.Text.Extra test_tests :: TestTree test_tests = testGroup "Data.Text.ExtraTest" [ testCase "when there is no span of the given character" $ longestSpanOf '*' "stars exist only where you believe" |> assertEqual "" NoSpan , testCase "when the given character is present" $ longestSpanOf '*' "it's here -> * <-" |> assertEqual "" (Span 1) , testCase "only counts the longest span" $ longestSpanOf '*' "it's here -> ** <-, not here: *" |> assertEqual "" (Span 2) ]
avh4/elm-format
avh4-lib/test/Data/Text/ExtraTest.hs
Haskell
bsd-3-clause
704
module Main where import Tkhs import Parser import System.Environment import System.IO.UTF8 as U import qualified Zipper import Data.Maybe main :: IO () main = getArgs >>= U.readFile . headOrUsage >>= either (error . show) (runP presentation . fromJust . Zipper.fromList . (++[T ["[End of Slide]"]])) . parseSlides headOrUsage :: [String] -> String headOrUsage ls | null ls = error "Usage: tkhs [presentation]" | otherwise = head ls
nonowarn/tkhs
src/Main.hs
Haskell
bsd-3-clause
518
module Util.HTML.Attributes where import Util.HTML action, align, alt, autocomplete, background, border, charset, checked, _class, cols, colspan, content, enctype, for, height, href, http_equiv, _id, maxlength, method, name, placeholder, role, rows, rowspan, selected, size, src, style, tabindex, target, title, _type, value, width :: String -> Attribute action = makeAttr "action" align = makeAttr "align" alt = makeAttr "alt" autocomplete = makeAttr "autocomplete" background = makeAttr "background" border = makeAttr "border" charset = makeAttr "charset" checked = makeAttr "checked" _class = makeAttr "class" cols = makeAttr "cols" colspan = makeAttr "colspan" content = makeAttr "content" enctype = makeAttr "enctype" for = makeAttr "for" height = makeAttr "height" href = makeAttr "href" http_equiv = makeAttr "http-equiv" _id = makeAttr "id" maxlength = makeAttr "maxlength" method = makeAttr "method" name = makeAttr "name" placeholder = makeAttr "placeholder" role = makeAttr "role" rows = makeAttr "rows" rowspan = makeAttr "rowspan" selected = makeAttr "selected" size = makeAttr "size" src = makeAttr "src" style = makeAttr "style" tabindex = makeAttr "tabindex" target = makeAttr "target" title = makeAttr "title" _type = makeAttr "type" value = makeAttr "value" width = makeAttr "width"
johanneshilden/liquid-epsilon
Util/HTML/Attributes.hs
Haskell
bsd-3-clause
1,642
module Main where import System.Console.GetOpt import System.Environment import qualified TextUI as TUI data Flag = Help | Text TUI.Config options :: [OptDescr Flag] options = [ Option ['?','h'] ["help"] (NoArg Help) "Help message." , Option ['t'] ["text"] (OptArg textConfig "uc") "Use text user interface with options: u(nicode), c(olors)." ] textConfig :: Maybe String -> Flag textConfig Nothing = Text $ TUI.Config { TUI.colors = False, TUI.unicode = False } textConfig (Just opts) = let unicode = elem 'u' opts colors = elem 'c' opts in Text $ TUI.Config { TUI.colors = colors, TUI.unicode = unicode } doOptions :: [Flag] -> IO () doOptions [] = TUI.newGame $ TUI.Config { TUI.colors = False, TUI.unicode = False } doOptions [Help] = putStrLn $ usage doOptions [Text config] = TUI.newGame config doOptions _ = do putStrLn $ "There must be exactly one option specified." putStrLn $ usage usage :: String usage = usageInfo "Usage: FreeCell [options]" options main :: IO () main = do args <- getArgs case getOpt Permute options args of (o, [], []) -> doOptions o (_, n, []) -> do putStrLn $ concat $ map ("Unknown option: " ++) n putStrLn $ usage (_, _, errs) -> do putStrLn $ concat errs ++ usage --let config = TUI.Config { TUI.colors = True, TUI.unicode = True } --TextUI.newGame config
sakhnik/FreeCell
Main.hs
Haskell
bsd-3-clause
1,539
-- Copyright (c) 2011, Colin Hill -- | Implementation of ridged multi-fractal noise. -- -- Example of use: -- -- @ --main = putStrLn (\"Noise value at (1, 2, 3): \" ++ show x) -- where seed = 1 -- octaves = 5 -- scale = 0.005 -- frequency = 1 -- lacunarity = 2 -- ridgedNoise = ridged seed octaves scale frequency lacunarity -- x = noiseValue ridgedNoise (1, 2, 3) -- @ module Numeric.Noise.Ridged ( Ridged, ridged, noiseValue ) where import Numeric.Noise import Data.Bits ((.&.)) import Data.Vector.Unboxed (Vector, fromList, (!)) -- | A ridged multi-fractal noise function. data Ridged = Ridged Seed Int Double Double Double (Vector Double) -- | Constructs a ridged multi-fractal noise function given a seed, number of octaves, scale, -- frequency, and lacunarity. ridged :: Seed -> Int -> Double -> Double -> Double -> Ridged ridged seed octs scale freq lac = ridgedNoise where specWeights = computeSpecWeights octs lac ridgedNoise = Ridged seed octs scale freq lac specWeights instance Noise Ridged where noiseValue ridgedNoise xyz = clamp noise (-1) 1 where Ridged _ octs scale freq _ _ = ridgedNoise xyz' = pmap (* (scale * freq)) xyz noise = ridgedNoiseValue ridgedNoise octs 1 xyz' * 1.25 - 1 -- | Computes the noise value for a ridged multi-fractal noise function given the octave number, -- the weight, and the point. ridgedNoiseValue :: Ridged -> Int -> Double -> Point -> Double ridgedNoiseValue _ 0 _ _ = 0 ridgedNoiseValue ridgedNoise oct weight xyz = noise + noise' where Ridged seed octs _ _ lac specWeights = ridgedNoise oct' = oct - 1 xyz' = pmap (* lac) xyz seed' = (seed + (octs - oct)) .&. 0x7fffffff signal = (offset - abs (coherentNoise seed' xyz)) * weight * weight weight' = clamp (signal * gain) 0 1 noise = signal * (specWeights ! (octs - oct)) noise' = ridgedNoiseValue ridgedNoise oct' weight' xyz' gain = 2 offset = 1 -- | Computes the spectral weight for each oct given the number of octs and the lac. computeSpecWeights :: Int -> Double -> Vector Double computeSpecWeights octs lac = fromList (computeSpecWeights' octs lac 1) -- | Helper for 'computeSpecWeights'. computeSpecWeights' :: Int -> Double -> Double -> [Double] computeSpecWeights' 0 _ _ = [] computeSpecWeights' oct lac freq = weight : weights where freq' = freq * lac oct' = oct - 1 weight = freq ** (-1) weights = computeSpecWeights' oct' lac freq'
colinhect/hsnoise
src/Numeric/Noise/Ridged.hs
Haskell
bsd-3-clause
2,686
import Debug.Trace import Test.Hspec import Test.Hspec.QuickCheck import Test.QuickCheck import Text.Unidecode main :: IO () main = hspec spec spec = describe "unidecode" $ do it "doesn't hurt ascii text" $ do unidecode 'a' `shouldBe` "a" it "doesn't crash" $ property $ \x -> unidecode x == unidecode x it "strips out non-ASCII text" $ do concatMap unidecode "五十音順" `shouldBe` ""
mwotton/unidecode
test/Spec.hs
Haskell
bsd-3-clause
463
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE MultiWayIf #-} module Game.Monsters.MGladiator where import Control.Lens (use, preuse, ix, (^.), (.=), (%=), zoom, (&), (.~), (%~)) import Control.Monad (when, unless, liftM, void) import Data.Bits ((.&.), (.|.)) import Data.Maybe (isJust) import Linear (V3(..), normalize, norm, _z) import qualified Data.Vector as V import {-# SOURCE #-} Game.GameImportT import Game.LevelLocalsT import Game.GameLocalsT import Game.CVarT import Game.SpawnTempT import Game.EntityStateT import Game.EdictT import Game.MMoveT import Game.GClientT import Game.MoveInfoT import Game.ClientPersistantT import Game.ClientRespawnT import Game.MonsterInfoT import Game.PlayerStateT import Types import QuakeRef import QuakeState import CVarVariables import Game.Adapters import qualified Constants import qualified Game.GameAI as GameAI import qualified Game.GameMisc as GameMisc import qualified Game.GameUtil as GameUtil import qualified Game.Monster as Monster import qualified Game.Monsters.MFlash as MFlash import qualified Util.Lib as Lib import qualified Util.Math3D as Math3D modelScale :: Float modelScale = 1.0 frameStand1 :: Int frameStand1 = 0 frameStand7 :: Int frameStand7 = 6 frameWalk1 :: Int frameWalk1 = 7 frameWalk16 :: Int frameWalk16 = 22 frameRun1 :: Int frameRun1 = 23 frameRun6 :: Int frameRun6 = 28 frameMelee1 :: Int frameMelee1 = 29 frameMelee17 :: Int frameMelee17 = 45 frameAttack1 :: Int frameAttack1 = 46 frameAttack9 :: Int frameAttack9 = 54 framePain1 :: Int framePain1 = 55 framePain6 :: Int framePain6 = 60 frameDeath1 :: Int frameDeath1 = 61 frameDeath22 :: Int frameDeath22 = 82 framePainUp1 :: Int framePainUp1 = 83 framePainUp7 :: Int framePainUp7 = 89 gladiatorIdle :: EntThink gladiatorIdle = GenericEntThink "gladiator_idle" $ \selfRef -> do sound <- use $ gameBaseGlobals.gbGameImport.giSound soundIdle <- use $ mGladiatorGlobals.mGladiatorSoundIdle sound (Just selfRef) Constants.chanVoice soundIdle 1 Constants.attnIdle 0 return True gladiatorSight :: EntInteract gladiatorSight = GenericEntInteract "gladiator_sight" $ \selfRef _ -> do sound <- use $ gameBaseGlobals.gbGameImport.giSound soundSight <- use $ mGladiatorGlobals.mGladiatorSoundSight sound (Just selfRef) Constants.chanVoice soundSight 1 Constants.attnNorm 0 return True gladiatorSearch :: EntThink gladiatorSearch = GenericEntThink "gladiator_search" $ \selfRef -> do sound <- use $ gameBaseGlobals.gbGameImport.giSound soundSearch <- use $ mGladiatorGlobals.mGladiatorSoundSearch sound (Just selfRef) Constants.chanVoice soundSearch 1 Constants.attnNorm 0 return True gladiatorCleaverSwing :: EntThink gladiatorCleaverSwing = GenericEntThink "gladiator_cleaver_swing" $ \selfRef -> do sound <- use $ gameBaseGlobals.gbGameImport.giSound soundCleaverSwing <- use $ mGladiatorGlobals.mGladiatorSoundCleaverSwing sound (Just selfRef) Constants.chanWeapon soundCleaverSwing 1 Constants.attnNorm 0 return True gladiatorFramesStand :: V.Vector MFrameT gladiatorFramesStand = V.fromList [ MFrameT (Just GameAI.aiStand) 0 Nothing , MFrameT (Just GameAI.aiStand) 0 Nothing , MFrameT (Just GameAI.aiStand) 0 Nothing , MFrameT (Just GameAI.aiStand) 0 Nothing , MFrameT (Just GameAI.aiStand) 0 Nothing , MFrameT (Just GameAI.aiStand) 0 Nothing , MFrameT (Just GameAI.aiStand) 0 Nothing ] gladiatorMoveStand :: MMoveT gladiatorMoveStand = MMoveT "gladiatorMoveStand" frameStand1 frameStand7 gladiatorFramesStand Nothing gladiatorStand :: EntThink gladiatorStand = GenericEntThink "gladiator_stand" $ \selfRef -> do modifyRef selfRef (\v -> v & eMonsterInfo.miCurrentMove .~ Just gladiatorMoveStand) return True gladiatorFramesWalk :: V.Vector MFrameT gladiatorFramesWalk = V.fromList [ MFrameT (Just GameAI.aiWalk) 15 Nothing , MFrameT (Just GameAI.aiWalk) 7 Nothing , MFrameT (Just GameAI.aiWalk) 6 Nothing , MFrameT (Just GameAI.aiWalk) 5 Nothing , MFrameT (Just GameAI.aiWalk) 2 Nothing , MFrameT (Just GameAI.aiWalk) 0 Nothing , MFrameT (Just GameAI.aiWalk) 2 Nothing , MFrameT (Just GameAI.aiWalk) 8 Nothing , MFrameT (Just GameAI.aiWalk) 12 Nothing , MFrameT (Just GameAI.aiWalk) 8 Nothing , MFrameT (Just GameAI.aiWalk) 5 Nothing , MFrameT (Just GameAI.aiWalk) 5 Nothing , MFrameT (Just GameAI.aiWalk) 2 Nothing , MFrameT (Just GameAI.aiWalk) 2 Nothing , MFrameT (Just GameAI.aiWalk) 1 Nothing , MFrameT (Just GameAI.aiWalk) 8 Nothing ] gladiatorMoveWalk :: MMoveT gladiatorMoveWalk = MMoveT "gladiatorMoveWalk" frameWalk1 frameWalk16 gladiatorFramesWalk Nothing gladiatorWalk :: EntThink gladiatorWalk = GenericEntThink "gladiator_walk" $ \selfRef -> do modifyRef selfRef (\v -> v & eMonsterInfo.miCurrentMove .~ Just gladiatorMoveWalk) return True gladiatorFramesRun :: V.Vector MFrameT gladiatorFramesRun = V.fromList [ MFrameT (Just GameAI.aiRun) 23 Nothing , MFrameT (Just GameAI.aiRun) 14 Nothing , MFrameT (Just GameAI.aiRun) 14 Nothing , MFrameT (Just GameAI.aiRun) 21 Nothing , MFrameT (Just GameAI.aiRun) 12 Nothing , MFrameT (Just GameAI.aiRun) 13 Nothing ] gladiatorMoveRun :: MMoveT gladiatorMoveRun = MMoveT "gladiatorMoveRun" frameRun1 frameRun6 gladiatorFramesRun Nothing gladiatorRun :: EntThink gladiatorRun = GenericEntThink "gladiator_run" $ \selfRef -> do self <- readRef selfRef let action = if (self^.eMonsterInfo.miAIFlags) .&. Constants.aiStandGround /= 0 then gladiatorMoveStand else gladiatorMoveRun modifyRef selfRef (\v -> v & eMonsterInfo.miCurrentMove .~ Just action) return True gladiatorMelee :: EntThink gladiatorMelee = GenericEntThink "GladiatorMelee" $ \selfRef -> do modifyRef selfRef (\v -> v & eMonsterInfo.miCurrentMove .~ Just gladiatorMoveAttackMelee) return True gladiatorFramesAttackMelee :: V.Vector MFrameT gladiatorFramesAttackMelee = V.fromList [ MFrameT (Just GameAI.aiCharge) 0 Nothing , MFrameT (Just GameAI.aiCharge) 0 Nothing , MFrameT (Just GameAI.aiCharge) 0 Nothing , MFrameT (Just GameAI.aiCharge) 0 Nothing , MFrameT (Just GameAI.aiCharge) 0 (Just gladiatorCleaverSwing) , MFrameT (Just GameAI.aiCharge) 0 Nothing , MFrameT (Just GameAI.aiCharge) 0 (Just gladiatorMelee) , MFrameT (Just GameAI.aiCharge) 0 Nothing , MFrameT (Just GameAI.aiCharge) 0 Nothing , MFrameT (Just GameAI.aiCharge) 0 Nothing , MFrameT (Just GameAI.aiCharge) 0 (Just gladiatorCleaverSwing) , MFrameT (Just GameAI.aiCharge) 0 Nothing , MFrameT (Just GameAI.aiCharge) 0 Nothing , MFrameT (Just GameAI.aiCharge) 0 (Just gladiatorMelee) , MFrameT (Just GameAI.aiCharge) 0 Nothing , MFrameT (Just GameAI.aiCharge) 0 Nothing , MFrameT (Just GameAI.aiCharge) 0 Nothing ] gladiatorMoveAttackMelee :: MMoveT gladiatorMoveAttackMelee = MMoveT "gladiatorMoveAttackMelee" frameMelee1 frameMelee17 gladiatorFramesAttackMelee (Just gladiatorRun) gladiatorAttackMelee :: EntThink gladiatorAttackMelee = GenericEntThink "gladiator_melee" $ \selfRef -> do modifyRef selfRef (\v -> v & eMonsterInfo.miCurrentMove .~ Just gladiatorMoveAttackMelee) return True gladiatorGun :: EntThink gladiatorGun = GenericEntThink "GladiatorGun" $ \selfRef -> do self <- readRef selfRef let (Just forward, Just right, _) = Math3D.angleVectors (self^.eEntityState.esAngles) True True False start = Math3D.projectSource (self^.eEntityState.esOrigin) (MFlash.monsterFlashOffset V.! Constants.mz2GladiatorRailgun1) forward right -- calc direction to where we targeted dir = normalize ((self^.ePos1) - start) Monster.monsterFireRailgun selfRef start dir 50 100 Constants.mz2GladiatorRailgun1 return True gladiatorFramesAttackGun :: V.Vector MFrameT gladiatorFramesAttackGun = V.fromList [ MFrameT (Just GameAI.aiCharge) 0 Nothing , MFrameT (Just GameAI.aiCharge) 0 Nothing , MFrameT (Just GameAI.aiCharge) 0 Nothing , MFrameT (Just GameAI.aiCharge) 0 (Just gladiatorGun) , MFrameT (Just GameAI.aiCharge) 0 Nothing , MFrameT (Just GameAI.aiCharge) 0 Nothing , MFrameT (Just GameAI.aiCharge) 0 Nothing , MFrameT (Just GameAI.aiCharge) 0 Nothing , MFrameT (Just GameAI.aiCharge) 0 Nothing ] gladiatorMoveAttackGun :: MMoveT gladiatorMoveAttackGun = MMoveT "gladiatorMoveAttackGun" frameAttack1 frameAttack9 gladiatorFramesAttackGun (Just gladiatorRun) gladiatorAttack :: EntThink gladiatorAttack = GenericEntThink "gladiator_attack" $ \selfRef -> do self <- readRef selfRef let Just enemyRef = self^.eEnemy enemy <- readRef enemyRef -- a small safe zone let v = (self^.eEntityState.esOrigin) - (enemy^.eEntityState.esOrigin) range = norm v if range <= fromIntegral Constants.meleeDistance + 32 then return True else do sound <- use $ gameBaseGlobals.gbGameImport.giSound soundGun <- use $ mGladiatorGlobals.mGladiatorSoundGun sound (Just selfRef) Constants.chanWeapon soundGun 1 Constants.attnNorm 0 let V3 a b c = enemy^.eEntityState.esOrigin pos1 = V3 a b (c + fromIntegral (enemy^.eViewHeight)) modifyRef selfRef (\v -> v & ePos1 .~ pos1 & eMonsterInfo.miCurrentMove .~ Just gladiatorMoveAttackGun) return True gladiatorFramesPain :: V.Vector MFrameT gladiatorFramesPain = V.fromList [ MFrameT (Just GameAI.aiMove) 0 Nothing , MFrameT (Just GameAI.aiMove) 0 Nothing , MFrameT (Just GameAI.aiMove) 0 Nothing , MFrameT (Just GameAI.aiMove) 0 Nothing , MFrameT (Just GameAI.aiMove) 0 Nothing , MFrameT (Just GameAI.aiMove) 0 Nothing ] gladiatorMovePain :: MMoveT gladiatorMovePain = MMoveT "gladiatorMovePain" framePain1 framePain6 gladiatorFramesPain (Just gladiatorRun) gladiatorFramesPainAir :: V.Vector MFrameT gladiatorFramesPainAir = V.fromList [ MFrameT (Just GameAI.aiMove) 0 Nothing , MFrameT (Just GameAI.aiMove) 0 Nothing , MFrameT (Just GameAI.aiMove) 0 Nothing , MFrameT (Just GameAI.aiMove) 0 Nothing , MFrameT (Just GameAI.aiMove) 0 Nothing , MFrameT (Just GameAI.aiMove) 0 Nothing , MFrameT (Just GameAI.aiMove) 0 Nothing ] gladiatorMovePainAir :: MMoveT gladiatorMovePainAir = MMoveT "gladiatorMovePainAir" framePainUp1 framePainUp7 gladiatorFramesPainAir (Just gladiatorRun) gladiatorPain :: EntPain gladiatorPain = GenericEntPain "gladiator_pain" $ \selfRef _ _ _ -> do self <- readRef selfRef when ((self^.eHealth) < (self^.eMaxHealth) `div` 2) $ modifyRef selfRef (\v -> v & eEntityState.esSkinNum .~ 1) levelTime <- use $ gameBaseGlobals.gbLevel.llTime if levelTime < (self^.ePainDebounceTime) then do when (isJust (self^.eMonsterInfo.miCurrentMove)) $ do let Just currentMove = self^.eMonsterInfo.miCurrentMove when ((self^.eVelocity._z) > 100 && (currentMove^.mmId) == "gladiatorMovePain") $ modifyRef selfRef (\v -> v & eMonsterInfo.miCurrentMove .~ Just gladiatorMovePainAir) else do modifyRef selfRef (\v -> v & ePainDebounceTime .~ levelTime + 3) r <- Lib.randomF soundPain <- if r < 0.5 then use $ mGladiatorGlobals.mGladiatorSoundPain1 else use $ mGladiatorGlobals.mGladiatorSoundPain2 sound <- use $ gameBaseGlobals.gbGameImport.giSound sound (Just selfRef) Constants.chanVoice soundPain 1 Constants.attnNorm 0 skillValue <- liftM (^.cvValue) skillCVar unless (skillValue == 3) $ do -- no pain anims in nightmare let currentMove = if (self^.eVelocity._z) > 100 then gladiatorMovePainAir else gladiatorMovePain modifyRef selfRef (\v -> v & eMonsterInfo.miCurrentMove .~ Just currentMove) gladiatorDead :: EntThink gladiatorDead = GenericEntThink "gladiator_dead" $ \selfRef -> do modifyRef selfRef (\v -> v & eMins .~ V3 (-16) (-16) (-24) & eMaxs .~ V3 16 16 (-8) & eMoveType .~ Constants.moveTypeToss & eSvFlags %~ (.|. Constants.svfDeadMonster) & eNextThink .~ 0) linkEntity <- use $ gameBaseGlobals.gbGameImport.giLinkEntity linkEntity selfRef return True gladiatorFramesDeath :: V.Vector MFrameT gladiatorFramesDeath = V.fromList [ MFrameT (Just GameAI.aiMove) 0 Nothing , MFrameT (Just GameAI.aiMove) 0 Nothing , MFrameT (Just GameAI.aiMove) 0 Nothing , MFrameT (Just GameAI.aiMove) 0 Nothing , MFrameT (Just GameAI.aiMove) 0 Nothing , MFrameT (Just GameAI.aiMove) 0 Nothing , MFrameT (Just GameAI.aiMove) 0 Nothing , MFrameT (Just GameAI.aiMove) 0 Nothing , MFrameT (Just GameAI.aiMove) 0 Nothing , MFrameT (Just GameAI.aiMove) 0 Nothing , MFrameT (Just GameAI.aiMove) 0 Nothing , MFrameT (Just GameAI.aiMove) 0 Nothing , MFrameT (Just GameAI.aiMove) 0 Nothing , MFrameT (Just GameAI.aiMove) 0 Nothing , MFrameT (Just GameAI.aiMove) 0 Nothing , MFrameT (Just GameAI.aiMove) 0 Nothing , MFrameT (Just GameAI.aiMove) 0 Nothing , MFrameT (Just GameAI.aiMove) 0 Nothing , MFrameT (Just GameAI.aiMove) 0 Nothing , MFrameT (Just GameAI.aiMove) 0 Nothing , MFrameT (Just GameAI.aiMove) 0 Nothing , MFrameT (Just GameAI.aiMove) 0 Nothing ] gladiatorMoveDeath :: MMoveT gladiatorMoveDeath = MMoveT "gladiatorMoveDeath" frameDeath1 frameDeath22 gladiatorFramesDeath (Just gladiatorDead) gladiatorDie :: EntDie gladiatorDie = GenericEntDie "gladiator_die" $ \selfRef _ _ damage _ -> do self <- readRef selfRef gameImport <- use $ gameBaseGlobals.gbGameImport let soundIndex = gameImport^.giSoundIndex sound = gameImport^.giSound if | (self^.eHealth) <= (self^.eGibHealth) -> do -- check for gib soundIdx <- soundIndex (Just "misc/udeath.wav") sound (Just selfRef) Constants.chanVoice soundIdx 1 Constants.attnNorm 0 GameMisc.throwGib selfRef "models/objects/gibs/bone/tris.md2" damage Constants.gibOrganic GameMisc.throwGib selfRef "models/objects/gibs/bone/tris.md2" damage Constants.gibOrganic GameMisc.throwGib selfRef "models/objects/gibs/sm_meat/tris.md2" damage Constants.gibOrganic GameMisc.throwGib selfRef "models/objects/gibs/sm_meat/tris.md2" damage Constants.gibOrganic GameMisc.throwGib selfRef "models/objects/gibs/sm_meat/tris.md2" damage Constants.gibOrganic GameMisc.throwGib selfRef "models/objects/gibs/sm_meat/tris.md2" damage Constants.gibOrganic GameMisc.throwHead selfRef "models/objects/gibs/head2/tris.md2" damage Constants.gibOrganic modifyRef selfRef (\v -> v & eDeadFlag .~ Constants.deadDead) | (self^.eDeadFlag) == Constants.deadDead -> return () | otherwise -> do -- regular death soundDie <- use $ mGladiatorGlobals.mGladiatorSoundDie sound (Just selfRef) Constants.chanVoice soundDie 1 Constants.attnNorm 0 modifyRef selfRef (\v -> v & eDeadFlag .~ Constants.deadDead & eTakeDamage .~ Constants.damageYes & eMonsterInfo.miCurrentMove .~ Just gladiatorMoveDeath) {- - QUAKED monster_gladiator (1 .5 0) (-32 -32 -24) (32 32 64) Ambush - Trigger_Spawn Sight -} spMonsterGladiator :: Ref EdictT -> Quake () spMonsterGladiator selfRef = do deathmatchValue <- liftM (^.cvValue) deathmatchCVar if deathmatchValue /= 0 then GameUtil.freeEdict selfRef else do gameImport <- use $ gameBaseGlobals.gbGameImport let soundIndex = gameImport^.giSoundIndex modelIndex = gameImport^.giModelIndex linkEntity = gameImport^.giLinkEntity soundIndex (Just "gladiator/pain.wav") >>= (mGladiatorGlobals.mGladiatorSoundPain1 .=) soundIndex (Just "gladiator/gldpain2.wav") >>= (mGladiatorGlobals.mGladiatorSoundPain2 .=) soundIndex (Just "gladiator/glddeth2.wav") >>= (mGladiatorGlobals.mGladiatorSoundDie .=) soundIndex (Just "gladiator/railgun.wav") >>= (mGladiatorGlobals.mGladiatorSoundGun .=) soundIndex (Just "gladiator/melee1.wav") >>= (mGladiatorGlobals.mGladiatorSoundCleaverSwing .=) soundIndex (Just "gladiator/melee2.wav") >>= (mGladiatorGlobals.mGladiatorSoundCleaverHit .=) soundIndex (Just "gladiator/melee3.wav") >>= (mGladiatorGlobals.mGladiatorSoundCleaverMiss .=) soundIndex (Just "gladiator/gldidle1.wav") >>= (mGladiatorGlobals.mGladiatorSoundIdle .=) soundIndex (Just "gladiator/gldsrch1.wav") >>= (mGladiatorGlobals.mGladiatorSoundSearch .=) soundIndex (Just "gladiator/sight.wav") >>= (mGladiatorGlobals.mGladiatorSoundSight .=) modelIdx <- modelIndex (Just "models/monsters/gladiatr/tris.md2") modifyRef selfRef (\v -> v & eMoveType .~ Constants.moveTypeStep & eSolid .~ Constants.solidBbox & eEntityState.esModelIndex .~ modelIdx & eMins .~ V3 (-32) (-32) (-24) & eMaxs .~ V3 32 32 64 & eHealth .~ 400 & eGibHealth .~ (-175) & eMass .~ 400 & ePain .~ Just gladiatorPain & eDie .~ Just gladiatorDie & eMonsterInfo.miStand .~ Just gladiatorStand & eMonsterInfo.miWalk .~ Just gladiatorWalk & eMonsterInfo.miRun .~ Just gladiatorRun & eMonsterInfo.miDodge .~ Nothing & eMonsterInfo.miAttack .~ Just gladiatorAttack & eMonsterInfo.miMelee .~ Just gladiatorAttackMelee & eMonsterInfo.miSight .~ Just gladiatorSight & eMonsterInfo.miIdle .~ Just gladiatorIdle & eMonsterInfo.miSearch .~ Just gladiatorSearch) linkEntity selfRef modifyRef selfRef (\v -> v & eMonsterInfo.miCurrentMove .~ Just gladiatorMoveStand & eMonsterInfo.miScale .~ modelScale) void $ think GameAI.walkMonsterStart selfRef
ksaveljev/hake-2
src/Game/Monsters/MGladiator.hs
Haskell
bsd-3-clause
19,821
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} module Graphics.Blank.DeviceContext where import Control.Concurrent.STM import Data.Set (Set) import Data.Text.Lazy (Text, toStrict) import Graphics.Blank.Events import Graphics.Blank.JavaScript import Graphics.Blank.Instr import Prelude.Compat -- import TextShow (Builder, toText) --import qualified Web.Scotty.Comet as KC import Network.JavaScript as JS -- | 'DeviceContext' is the abstract handle into a specific 2D context inside a browser. -- Note that the JavaScript API concepts of -- @<https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D CanvasRenderingContext2D>@ and -- @<https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement HTMLCanvasElement>@ -- are conflated in @blank-canvas@. Therefore, there is no -- @<https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/getContext getContext()>@ method; -- rather, @getContext()@ is implied (when using 'send'). data DeviceContext = DeviceContext { theComet :: JS.Engine -- ^ The mechanisms for sending commands , eventQueue :: EventQueue -- ^ A single (typed) event queue , ctx_width :: !Int , ctx_height :: !Int , ctx_devicePixelRatio :: !Double , localFiles :: TVar (Set Text) -- ^ approved local files , weakRemoteMonad :: Bool -- ^ use a weak remote monad for debugging } instance Image DeviceContext where jsImage = jsImage . deviceCanvasContext width = fromIntegral . ctx_width height = fromIntegral . ctx_height deviceCanvasContext :: DeviceContext -> CanvasContext deviceCanvasContext cxt = CanvasContext Nothing (ctx_width cxt) (ctx_height cxt) -- | 'devicePixelRatio' returns the device's pixel ratio as used. Typically, the -- browser ignores @devicePixelRatio@ in the canvas, which can make fine details -- and text look fuzzy. Using the query @?hd@ on the URL, @blank-canvas@ attempts -- to use the native @devicePixelRatio@, and if successful, 'devicePixelRatio' will -- return a number other than 1. You can think of 'devicePixelRatio' as the line -- width to use to make lines look one pixel wide. devicePixelRatio :: DeviceContext -> Double devicePixelRatio = ctx_devicePixelRatio -- | Internal command to send a message to the canvas. sendToCanvas :: DeviceContext -> Instr -> IO () sendToCanvas cxt cmds = do print "sendToCanvas" -- KC.send (theComet cxt) . toStrict . toLazyText $ surround "syncToFrame(function(){" "});" <> cmds -- | Wait for any event. Blocks. wait :: DeviceContext -> IO Event wait c = atomically $ readTChan (eventQueue c) -- | 'flush' all the current events, returning them all to the user. Never blocks. flush :: DeviceContext -> IO [Event] flush cxt = atomically $ loop where loop = do b <- isEmptyTChan (eventQueue cxt) if b then return [] else do e <- readTChan (eventQueue cxt) es <- loop return (e : es)
ku-fpg/blank-canvas
Graphics/Blank/DeviceContext.hs
Haskell
bsd-3-clause
3,158
{-# LANGUAGE RecordWildCards #-} module Day7 where import Data.List import Data.List.Split data IP = IP { supernet :: [String] , hypernet :: [String] } input :: IO String input = readFile "day7" parse :: String -> IP parse s = IP (map head parts) (concatMap tail parts) where parts = chunksOf 2 $ splitOneOf "[]" s load :: String -> [IP] load = map parse . lines isAbba :: String -> Bool isAbba [a, b, c, d] = a == d && b == c && a /= b hasAbba :: String -> Bool hasAbba = any isAbba . map (take 4) . drop 4 . reverse . tails hasTls :: IP -> Bool hasTls IP{..} = any hasAbba supernet && not (any hasAbba hypernet) solve1 :: [IP] -> Int solve1 = length . filter hasTls isAba :: String -> Bool isAba [a, b, c] = a == c && a /= b findAbas :: String -> [String] findAbas = filter isAba . map (take 3) . drop 3 . reverse . tails toBab :: String -> String toBab [a, b, _] = [b, a, b] hasSsl :: IP -> Bool hasSsl IP{..} = not . null $ intersect abas babs where abas = concatMap findAbas supernet babs = concatMap (map toBab . findAbas) hypernet solve2 :: [IP] -> Int solve2 = length . filter hasSsl
mbernat/aoc16-haskell
src/Day7.hs
Haskell
bsd-3-clause
1,137
module Interpret ( interpret ) where import Ast import Control.Monad.Trans.State import Data.Map (Map) import qualified Data.Map as M import Control.Monad import Control.Monad.IO.Class import Control.Arrow (first) interpret :: Program -> IO (Maybe String) interpret p = let ftab = buildFunctionTable p in case M.lookup "main" ftab of Nothing -> return $ Just "function \"main\" is not defined" Just main -> do result <- evalStateT (runEvalLisp (call main [])) (ftab, ftab) case result of Left e -> return $ Just e _ -> return Nothing ---- type SymTab = Map String Value type FunTab = SymTab data Value = IntVal Integer | BoolVal Bool | ArrayVal [Value] | LambdaVal [Identifier] [Expr] instance Show Value where show (IntVal a) = show a show (BoolVal a) = show a show (ArrayVal a) = "[" ++ unwords (map show a) ++ "]" show (LambdaVal params body) = show $ Lambda params body instance Num Value where (IntVal a) + (IntVal b) = IntVal $ a + b _ + _ = error "Type error: Should have been caught by the type checker" (IntVal a) - (IntVal b) = IntVal $ a - b _ - _ = error "Type error: Should have been caught by the type checker" (IntVal a) * (IntVal b) = IntVal $ a * b _ * _ = error "Type error: Should have been caught by the type checker" abs (IntVal a) = IntVal $ abs a abs _ = error "Type error: Should have been caught by the type checker" signum (IntVal a) = IntVal $ signum a signum _ = error "Type error: Should have been caught by the type checker" fromInteger = IntVal . fromInteger instance Ord Value where compare (IntVal a) (IntVal b) = compare a b compare (BoolVal a) (BoolVal b) = compare a b compare _ _ = error "Type error: Should have been caught by the type checker" instance Eq Value where (==) (IntVal a) (IntVal b) = a == b (==) (BoolVal a) (BoolVal b) = a == b (==) _ _ = error "Type error: Should have been caught by the type checker" evalExprs :: [Expr] -> StateT (SymTab, FunTab) IO (Either String Value) evalExprs [] = return $ Left "No expressions to evaluate" evalExprs [e] = runEvalLisp $ eval e evalExprs (e : es) = do e' <- runEvalLisp $ eval e case e' of Left err' -> return $ Left err' Right _ -> evalExprs es bindArgs :: (Monad a) => [(Identifier, Value)] -> StateT (SymTab, FunTab) a () bindArgs [] = return () bindArgs ((p, a) : rest) = do update $ first $ M.insert p a bindArgs rest update :: Monad m => (a -> a) -> StateT a m () update f = do s <- get let s' = f s put s' eval :: Expr -> EvalLisp Value eval (IntLit a) = return $ IntVal a eval (Ref a) = EvalLisp $ do (vtab, ftab) <- get runEvalLisp $ case M.lookup a vtab of Just x -> EvalLisp $ return $ Right x Nothing -> case M.lookup a ftab of Just x -> EvalLisp $ return $ Right x Nothing -> err $ a ++ " is undefined" eval (Plus a b) = (+) <$> eval a <*> eval b eval (Minus a b) = (-) <$> eval a <*> eval b eval (Times a b) = (*) <$> eval a <*> eval b eval (Greater a b) = ((BoolVal .) . (>)) <$> eval a <*> eval b eval (GreaterEq a b) = ((BoolVal .) . (>=)) <$> eval a <*> eval b eval (Less a b) = ((BoolVal .) . (<)) <$> eval a <*> eval b eval (LessEq a b) = ((BoolVal .) . (<=)) <$> eval a <*> eval b eval (Eq a b) = ((BoolVal .) . (==)) <$> eval a <*> eval b eval (NotEq a b) = ((BoolVal .) . (/=)) <$> eval a <*> eval b eval (And a b) = boolValAnd <$> eval a <*> eval b eval (Or a b) = boolValOr <$> eval a <*> eval b eval (Not a) = boolValNot <$> eval a eval (If cond thenB elseB) = do cond' <- eval cond case cond' of (BoolVal True) -> eval thenB _ -> eval elseB eval (Call e params) = do e' <- eval e params' <- mapM eval params call e' params' eval (Lambda args body) = return $ LambdaVal args body eval (Array elements) = do x <- mapM eval elements return $ ArrayVal x eval (Print a) = do a' <- eval a liftIO $ print a' return a' eval (Let [] body) = EvalLisp $ evalExprs body eval (Let ((i, e) : bindings) body) = do v <- eval e EvalLisp $ do update $ first $ M.insert i v runEvalLisp $ eval (Let bindings body) call :: Value -> [Value] -> EvalLisp Value call (LambdaVal params _) args | length params /= length args = err "Wrong number of arguments" call (LambdaVal params body) args = EvalLisp $ do prev@(_, funs) <- get put (M.empty, funs) bindArgs $ zip params args result <- evalExprs body put prev return result call (ArrayVal vals) [IntVal n] = case vals `safeIdx` fromIntegral n of Nothing -> err "Array index failure" Just x -> return x call (ArrayVal _) _ = err "Wrong number of arguments to array" call i _ = err $ show i ++ " is not a function" safeIdx :: [a] -> Int -> Maybe a safeIdx [] _ = Nothing safeIdx (x : _) 0 = Just x safeIdx (_ : rest) n = safeIdx rest (n - 1) boolValNot :: Value -> Value boolValNot (BoolVal a) = BoolVal $ not a boolValNot _ = error "Type error: Should have been caught by the type checker" boolValAnd :: Value -> Value -> Value boolValAnd (BoolVal a) (BoolVal b) = BoolVal $ a && b boolValAnd _ _ = error "Type error: Should have been caught by the type checker" boolValOr :: Value -> Value -> Value boolValOr (BoolVal a) (BoolVal b) = BoolVal $ a || b boolValOr _ _ = error "Type error: Should have been caught by the type checker" buildFunctionTable :: [Function] -> SymTab buildFunctionTable = M.fromList . map (\f -> (funName f, LambdaVal (funArgs f) (funBody f))) -- | EvalLisp helper type newtype EvalLisp a = EvalLisp { runEvalLisp :: StateT (SymTab, FunTab) IO (Either String a) } instance Functor EvalLisp where fmap f (EvalLisp x) = EvalLisp $ do x' <- x return $ do x'' <- x' return $ f x'' instance Applicative EvalLisp where pure = EvalLisp . pure . Right (EvalLisp f) <*> (EvalLisp x) = EvalLisp $ do f' <- f x' <- x return $ do f'' <- f' x'' <- x' return $ f'' x'' err :: String -> EvalLisp a err = EvalLisp . return . Left instance Monad EvalLisp where return = pure (EvalLisp x) >>= f = EvalLisp $ do x' <- x case x' of Left e -> return $ Left e Right x'' -> runEvalLisp $ f x'' instance MonadIO EvalLisp where liftIO x = EvalLisp $ do x' <- liftIO x return $ Right x'
davidpdrsn/alisp
src/Interpret.hs
Haskell
bsd-3-clause
6,671
------------------------------------------------------------------------ -- | -- Module : Data.CSV.BatchAverage -- Copyright : (c) Amy de Buitléir 2014 -- License : BSD-style -- Maintainer : amy@nualeargais.ie -- Stability : experimental -- Portability : portable -- -- Groups the records of a CSV into fixed-size batches, calculates -- the average of each column in a batch, and prints the averages. -- The last batch may be smaller than the others, depending on the batch -- size. ------------------------------------------------------------------------ import Data.List import Data.List.Split import Factory.Math.Statistics (getMean) import System.Environment(getArgs) fromCSV :: String -> ([String], [[Double]]) fromCSV xss = extractValues . tokenise $ xss toCSVLine :: Show a => [a] -> String toCSVLine = intercalate "," . map show tokenise :: String -> [[String]] tokenise = map (splitOn ",") . lines extractValues :: [[String]] -> ([String], [[Double]]) extractValues xss = (headings, values) where (headings:xs) = xss values = map (map read) xs mapColumns :: ([Double] -> Double) -> [[Double]] -> [Double] mapColumns f xss = map f . transpose $ xss main :: IO () main = do args <- getArgs let n = read . head $ args (hs,xss) <- fmap fromCSV getContents putStrLn . intercalate "," $ hs let yss = map (mapColumns getMean) . chunksOf n $ xss mapM_ putStrLn . map toCSVLine $ yss
mhwombat/amy-csv
src/Data/CSV/BatchAverage.hs
Haskell
bsd-3-clause
1,433
{-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} module Ivory.ModelCheck.CVC4 where import qualified Data.ByteString.Char8 as B import Data.Int import Data.List (intersperse) import Data.Monoid import Data.String import Data.Word import Prelude hiding (exp) import Ivory.Language.Syntax.Concrete.Location import Ivory.Language.Syntax.Concrete.Pretty -------------------------------------------------------------------------------- type Var = String type Func = String -------------------------------------------------------------------------------- -- Concrete syntax class Concrete a where concrete :: a -> B.ByteString instance Concrete B.ByteString where concrete = id instance Concrete String where concrete = B.pack instance Concrete SrcLoc where concrete = concrete . prettyPrint . pretty data ConcreteList = forall a. Concrete a => CL a -- Specialization clBS :: B.ByteString -> ConcreteList clBS = CL -------------------------------------------------------------------------------- -- Statements data Statement = TypeDecl String [(Var, Type)] | VarDecl Var Type | Assert (Located Expr) | Query (Located Expr) -- Arbitrary statement constructed by-hand. | forall a . Concrete a => Statement a instance Concrete Statement where concrete (TypeDecl ty []) = statement [CL ty, clBS ":", clBS "TYPE"] concrete (TypeDecl ty fs) = statement [CL ty, clBS ":", clBS "TYPE", clBS "= [#", fieldList fs, clBS "#]"] concrete (VarDecl v ty) = statement [CL v, clBS ":", CL ty] concrete (Assert (Located loc exp)) = statement [clBS "ASSERT", CL exp, clBS ";\t %", CL loc] concrete (Query (Located loc exp)) = statement [clBS "QUERY", CL exp, clBS ";\t %", CL loc] concrete (Statement a) = statement [CL a] statement :: [ConcreteList] -> B.ByteString statement as = let unList (CL a) = concrete a in let toks = B.unwords (map unList as) in B.snoc toks ';' fieldList :: [(Var,Type)] -> ConcreteList fieldList fs = clBS $ B.intercalate ", " [concrete v <> " : " <> concrete t | (v,t) <- fs] typeDecl :: String -> [(Var,Type)] -> Statement typeDecl = TypeDecl varDecl :: Var -> Type -> Statement varDecl = VarDecl assert :: Located Expr -> Statement assert = Assert query :: Located Expr -> Statement query = Query -------------------------------------------------------------------------------- -- Expressions and literals instance Concrete Float where concrete = concrete . show instance Concrete Double where concrete = concrete . show instance Concrete Integer where concrete = concrete . show instance Concrete Int where concrete = concrete . show data Type = Void | Integer | Real | Char | Bool | Struct String | Array Type | Opaque deriving (Show, Read, Eq) instance Concrete Type where concrete Bool = "BOOLEAN" concrete Real = "REAL" concrete Integer = "INT" concrete (Array t) = "ARRAY INT OF " <> concrete t concrete (Struct name) = B.pack name concrete _ = "INT" -- error $ "unexpected type: " ++ show t data Expr = Var Var -- Boolean expressions | T | F | Not Expr | And Expr Expr | Or Expr Expr | Impl Expr Expr | Equiv Expr Expr | Eq Expr Expr | Le Expr Expr | Leq Expr Expr | Ge Expr Expr | Geq Expr Expr -- Numeric expressions | forall a . (Show a, Concrete a, Num a) => NumLit a | Add Expr Expr | Sub Expr Expr | Mod Expr Integer -- CVC4 can handle mod-by-constant | Call Func [Expr] | Store Expr Expr | StoreMany Expr [(Expr,Expr)] | Field Expr Expr | Index Expr Expr -- Store (Index 4 (Field "bFoo" "var0")) 5 -- var0 WITH .bFoo[4] := 5 -- Index 5 (Index 1) "var0") -- var0[1][5] deriving instance Show Expr substExpr :: [(Var, Expr)] -> Expr -> Expr substExpr su = go where go (Var v) = case lookup v su of Nothing -> Var v Just e -> e go (Not e) = Not (go e) go (And x y) = And (go x) (go y) go (Or x y) = Or (go x) (go y) go (Impl x y) = Impl (go x) (go y) go (Equiv x y) = Equiv (go x) (go y) go (Eq x y) = Eq (go x) (go y) go (Le x y) = Le (go x) (go y) go (Leq x y) = Leq (go x) (go y) go (Ge x y) = Ge (go x) (go y) go (Geq x y) = Geq (go x) (go y) go (Add x y) = Add (go x) (go y) go (Sub x y) = Sub (go x) (go y) go (Mod x y) = Mod (go x) y go (Call f es) = Call f (map go es) go (Store s e) = Store (go s) (go e) go (StoreMany a ies) = StoreMany (go a) (map (\(i,e) -> (go i, go e)) ies) go (Field f e) = Field (go f) (go e) go (Index i e) = Index (go i) (go e) go e = e leaf :: Expr -> Bool leaf exp = case exp of (Var _) -> True T -> True F -> True (NumLit _) -> True _ -> False parens :: Expr -> B.ByteString parens exp = if leaf exp then concrete exp else '(' `B.cons` (concrete exp `B.snoc` ')') instance Concrete Expr where concrete (Var v) = concrete v concrete T = "TRUE" concrete F = "FALSE" concrete (Not e) = B.unwords ["NOT", parens e] concrete (And e0 e1) = B.unwords [parens e0, "AND", parens e1] concrete (Or e0 e1) = B.unwords [parens e0, "OR" , parens e1] concrete (Impl e0 e1) = B.unwords [parens e0, "=>" , parens e1] concrete (Equiv e0 e1) = B.unwords [parens e0, "<=>", parens e1] concrete (Eq e0 e1) = B.unwords [parens e0, "=" , parens e1] concrete (Le e0 e1) = B.unwords [parens e0, "<" , parens e1] concrete (Leq e0 e1) = B.unwords [parens e0, "<=" , parens e1] concrete (Ge e0 e1) = B.unwords [parens e0, ">" , parens e1] concrete (Geq e0 e1) = B.unwords [parens e0, ">=" , parens e1] concrete (NumLit n) = concrete n concrete (Add e0 e1) = B.unwords [parens e0, "+", parens e1] concrete (Sub e0 e1) = B.unwords [parens e0, "-", parens e1] concrete (Mod e x) = B.unwords [parens e, "MOD", concrete x] concrete (Call f args) = concrete f `B.append` ('(' `B.cons` (args' `B.snoc` ')')) where args' = B.unwords $ intersperse "," (map concrete args) concrete (Store s e) = v <> " WITH " <> f <> " := " <> concrete e where (v,f) = B.break (`elem` (".[" :: String)) (concrete s) -- concrete (Store a i e) = concrete a <> " WITH " -- <> B.concat (map concrete i) -- <> " := " <> concrete e concrete (StoreMany a ies) = concrete a <> " WITH " <> B.intercalate ", " [ f <> " := " <> concrete e | (i,e) <- ies , let f = B.dropWhile (not . (`elem` (".[" :: String))) (concrete i) ] concrete (Field f e) = concrete e <> "." <> concrete f concrete (Index i e) = concrete e <> "[" <> concrete i <> "]" -- concrete (Select e ss) = concrete e <> B.concat (map concrete ss) -- concrete (Load a i) = concrete a <> "[" <> concrete i <> "]" -- instance Concrete Selector where -- concrete (Field f) = "." <> concrete f -- concrete (Index i) = "[" <> concrete i <> "]" var :: Var -> Expr var = Var true :: Expr true = T false :: Expr false = F not' :: Expr -> Expr not' = Not (.&&) :: Expr -> Expr -> Expr (.&&) = And (.||) :: Expr -> Expr -> Expr (.||) = Or (.=>) :: Expr -> Expr -> Expr (.=>) T e = e (.=>) x y = Impl x y (.<=>) :: Expr -> Expr -> Expr (.<=>) = Equiv (.==) :: Expr -> Expr -> Expr (.==) = Eq (.<) :: Expr -> Expr -> Expr (.<) = Le (.<=) :: Expr -> Expr -> Expr (.<=) = Leq (.>) :: Expr -> Expr -> Expr (.>) = Ge (.>=) :: Expr -> Expr -> Expr (.>=) = Geq (.+) :: Expr -> Expr -> Expr (.+) = Add (.-) :: Expr -> Expr -> Expr (.-) = Sub (.%) :: Expr -> Integer -> Expr (.%) = Mod lit :: (Show a, Concrete a, Num a) => a -> Expr lit = NumLit intLit :: Integer -> Expr intLit = lit realLit :: Double -> Expr realLit = lit call :: Func -> [Expr] -> Expr call = Call store :: Expr -> Expr -> Expr store = Store storeMany :: Expr -> [(Expr,Expr)] -> Expr storeMany = StoreMany field :: Expr -> Expr -> Expr field = Field index :: Expr -> Expr -> Expr index = Index -------------------------------------------------------------------------------- -- CVC4 Lib ---------------------------------------- -- Bounded int types boundedFunc :: forall a . (Show a, Integral a, Bounded a) => Func -> a -> Statement boundedFunc f _sz = Statement $ B.unwords [ B.pack f, ":", "INT", "->", "BOOLEAN" , "=", "LAMBDA", "(x:INT)", ":" , exp (toInt minBound) (toInt maxBound) ] where toInt a = fromIntegral (a :: a) x = var "x" exp l h = concrete $ (intLit l .<= x) .&& (x .<= intLit h) word8, word16, word32, word64, int8, int16, int32, int64 :: Func word8 = "word8" word16 = "word16" word32 = "word32" word64 = "word64" int8 = "int8" int16 = "int16" int32 = "int32" int64 = "int64" word8Bound :: Statement word8Bound = boundedFunc word8 (0 :: Word8) word16Bound :: Statement word16Bound = boundedFunc word16 (0 :: Word16) word32Bound :: Statement word32Bound = boundedFunc word32 (0 :: Word32) word64Bound :: Statement word64Bound = boundedFunc word64 (0 :: Word64) int8Bound :: Statement int8Bound = boundedFunc int8 (0 :: Int8) int16Bound :: Statement int16Bound = boundedFunc int16 (0 :: Int16) int32Bound :: Statement int32Bound = boundedFunc int32 (0 :: Int32) int64Bound :: Statement int64Bound = boundedFunc int64 (0 :: Int64) ---------------------------------------- -- Mod modAbs :: Func modAbs = "mod" -- | Abstraction: a % b (C semantics) implies -- -- ( ((a >= 0) && (a % b >= 0) && (a % b < b) && (a % b <= a)) -- || ((a < 0) && (a % b <= 0) && (a % b > b) && (a % b >= a))) -- -- a % b is abstracted with a fresh var v. modFunc :: Statement modFunc = Statement $ B.unwords [ B.pack modAbs, ":", "(INT, INT)", "->", "INT" ] modExp :: Expr -> Expr -> Expr -> Expr modExp v a b = ((a .>= z) .&& (v .>= z) .&& (v .< b) .&& (v .<= a)) .|| ((a .< z) .&& (v .<= z) .&& (v .> b) .&& (v .>= a)) where z = intLit 0 ---------------------------------------- -- Mul mulAbs :: Func mulAbs = "mul" mulFunc :: Statement mulFunc = Statement $ B.unwords [ B.pack mulAbs, ":", "(INT, INT)", "->", "INT" ] mulExp :: Expr -> Expr -> Expr -> Expr mulExp v a b = (((a .== z) .|| (b .== z)) .=> (v .== z)) .&& ((a .== o) .=> (v .== b)) .&& ((b .== o) .=> (v .== a)) .&& (((a .> o) .&& (b .> o)) .=> ((v .> a) .&& (v .> b))) where z = intLit 0 o = intLit 1 ---------------------------------------- -- Div divAbs :: Func divAbs = "div" divFunc :: Statement divFunc = Statement $ B.unwords [ B.pack divAbs, ":", "(INT, INT)", "->", "INT" ] divExp :: Expr -> Expr -> Expr -> Expr divExp v a b = ((b .== o) .=> (v .== a)) .&& ((a .== z) .=> (v .== z)) .&& (((a .>= o) .&& (b .> o)) .=> ((v .>= z) .&& (v .< a))) where z = intLit 0 o = intLit 1 cvc4Lib :: [Statement] cvc4Lib = [ word8Bound, word16Bound, word32Bound, word64Bound , int8Bound, int16Bound, int32Bound, int64Bound , modFunc, mulFunc, divFunc ] -------------------------------------------------------------------------------- -- Testing foo :: Statement foo = assert . noLoc $ (intLit 3 .== var "x") .&& (var "x" .< intLit 4)
Hodapp87/ivory
ivory-model-check/src/Ivory/ModelCheck/CVC4.hs
Haskell
bsd-3-clause
11,945
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE TypeSynonymInstances #-} module DirectoryServer where import Control.Monad.Trans.Except import Control.Monad.Trans.Resource import Control.Monad.IO.Class import Data.Aeson import Data.Aeson.TH import Data.Bson.Generic import GHC.Generics import Network.Wai hiding(Response) import Network.Wai.Handler.Warp import Network.Wai.Logger import Servant import Servant.API import Servant.Client import System.IO import System.Directory import System.Environment (getArgs, getProgName, lookupEnv) import System.Log.Formatter import System.Log.Handler (setFormatter) import System.Log.Handler.Simple import System.Log.Handler.Syslog import System.Log.Logger import Data.Bson.Generic import qualified Data.List as DL import Data.Maybe (catMaybes) import Data.Text (pack, unpack) import Data.Time.Clock (UTCTime, getCurrentTime) import Data.Time.Format (defaultTimeLocale, formatTime) import Database.MongoDB import Control.Monad (when) import Network.HTTP.Client (newManager, defaultManagerSettings) manager = newManager defaultManagerSettings data File = File { fileName :: FilePath, fileContent :: String } deriving (Eq, Show, Generic) instance ToJSON File instance FromJSON File data Response = Response{ response :: String } deriving (Eq, Show, Generic) instance ToJSON Response instance FromJSON Response data FileServer = FileServer{ id :: String, fsaddress :: String, fsport :: String } deriving (Eq, Show, Generic) instance ToJSON FileServer instance FromJSON FileServer instance ToBSON FileServer instance FromBSON FileServer data FileMapping = FileMapping{ fmfileName :: String, fmaddress :: String, fmport :: String } deriving (Eq, Show, Generic) instance ToJSON FileServer instance FromJSON FileServer instance ToBSON FileServer instance FromBSON FileServer type ApiHandler = ExceptT ServantErr IO serverport :: String serverport = "7008" serverhost :: String serverhost = "localhost" type DirectoryApi = "join" :> ReqBody '[JSON] FileServer :> Post '[JSON] Response :<|> "open" :> Capture "fileName" String :> Get '[JSON] File :<|> "close" :> ReqBody '[JSON] File :> Post '[JSON] Response type FileApi = "files" :> Get '[JSON] [FilePath] :<|> "download" :> Capture "fileName" String :> Get '[JSON] File :<|> "upload" :> ReqBody '[JSON] File :> Post '[JSON] Response -- :<|> fileApi :: Proxy FileApi fileApi = Proxy files:: ClientM [FilePath] download :: String -> ClientM File upload :: File -> ClientM Response files :<|> download :<|> upload = client fileApi getFilesQuery :: ClientM[FilePath] getFilesQuery = do get_files <- files return(get_files) downloadQuery :: String -> ClientM File downloadQuery fname = do get_download <- download (fname) return(get_download) directoryApi :: Proxy DirectoryApi directoryApi = Proxy server :: Server DirectoryApi server = fsJoin :<|> DirectoryServer.openFile :<|> closeFile directoryApp :: Application directoryApp = serve directoryApi server mkApp :: IO() mkApp = do run (read (serverport) ::Int) directoryApp storefs:: FileServer -> Bool storefs fs@(FileServer key _ _) = liftIO $ do warnLog $ "Storing file under key " ++ key ++ "." withMongoDbConnection $ upsert (select ["id" =: key] "FILESERVER_RECORD") $ toBSON fs return True storefm :: FileMapping -> Bool storefm fm@(FileMapping key _ _) = liftIO $ do warnLog $ "Storing file under key " ++ key ++ "." withMongoDbConnection $ upsert (select ["id" =: key] "FILEMAPPING_RECORD") $ toBSON fm return True getStoreFm :: FileServer -> Bool getStoreFm fs = do manager <- newManager defaultManagerSettings res <- runClientM getFilesQuery (ClientEnv manager (BaseUrl Http (fsaddress fs) (read(fsport fs)) "")) case res of Left err -> putStrLn $ "Error: " ++ show err Right response -> map (storefm (fsaddress fs) (fsport fs)) response return True fsJoin :: FileServer -> ApiHandler Response fsJoin fs = do bool <- storefs fs bool2 <- getStoreFm fs return (Response "Success") searchFileMappings :: String -> Maybe FileMapping searchFileMappings key = liftIO $ do warnLog $ "Searching for value for key: " ++ key withMongoDbConnection $ do docs <- find (select ["fmfileName" =: key] "FILEMAPPING_RECORD") >>= drainCursor file <- head $ DL.map (\ b -> fromBSON b :: Maybe FileMapping) docs return file openFileQuery :: String -> FileMapping -> File openFileQuery key fm = do manager <- newManager defaultManagerSettings res <- runClientM (downloadQuery key) (ClientEnv manager (BaseUrl Http (fmaddress fm) (read(fmport fm)) "")) case res of Left err -> putStrLn $ "Error: " ++ show err Right response -> return response openFile :: String -> ApiHandler File openFile key = do fm <- searchFileMappings key case fm of Nothing -> putStrLn $ "Error: " ++ "File not found" Just filemapping -> do file <- openFileQuery key filemapping return file -- | Logging stuff iso8601 :: UTCTime -> String iso8601 = formatTime defaultTimeLocale "%FT%T%q%z" -- global loggin functions debugLog, warnLog, errorLog :: String -> IO () debugLog = doLog debugM warnLog = doLog warningM errorLog = doLog errorM noticeLog = doLog noticeM doLog f s = getProgName >>= \ p -> do t <- getCurrentTime f p $ (iso8601 t) ++ " " ++ s withLogging act = withStdoutLogger $ \aplogger -> do lname <- getProgName llevel <- logLevel updateGlobalLogger lname (setLevel $ case llevel of "WARNING" -> WARNING "ERROR" -> ERROR _ -> DEBUG) act aplogger -- | Mongodb helpers... -- | helper to open connection to mongo database and run action -- generally run as follows: -- withMongoDbConnection $ do ... -- withMongoDbConnection :: Action IO a -> IO a withMongoDbConnection act = do ip <- mongoDbIp port <- mongoDbPort database <- mongoDbDatabase pipe <- connect (host ip) ret <- runResourceT $ liftIO $ access pipe master (pack database) act Database.MongoDB.close pipe return ret -- | helper method to ensure we force extraction of all results -- note how it is defined recursively - meaning that draincursor' calls itself. -- the purpose is to iterate through all documents returned if the connection is -- returning the documents in batch mode, meaning in batches of retruned results with more -- to come on each call. The function recurses until there are no results left, building an -- array of returned [Document] drainCursor :: Cursor -> Action IO [Document] drainCursor cur = drainCursor' cur [] where drainCursor' cur res = do batch <- nextBatch cur if null batch then return res else drainCursor' cur (res ++ batch) -- | Environment variable functions, that return the environment variable if set, or -- default values if not set. -- | The IP address of the mongoDB database that devnostics-rest uses to store and access data mongoDbIp :: IO String mongoDbIp = defEnv "MONGODB_IP" Prelude.id "database" True -- | The port number of the mongoDB database that devnostics-rest uses to store and access data mongoDbPort :: IO Integer mongoDbPort = defEnv "MONGODB_PORT" read 27017 False -- 27017 is the default mongodb port -- | The name of the mongoDB database that devnostics-rest uses to store and access data mongoDbDatabase :: IO String mongoDbDatabase = defEnv "MONGODB_DATABASE" Prelude.id "USEHASKELLDB" True -- | Determines log reporting level. Set to "DEBUG", "WARNING" or "ERROR" as preferred. Loggin is -- provided by the hslogger library. logLevel :: IO String logLevel = defEnv "LOG_LEVEL" Prelude.id "DEBUG" True -- | Helper function to simplify the setting of environment variables -- function that looks up environment variable and returns the result of running funtion fn over it -- or if the environment variable does not exist, returns the value def. The function will optionally log a -- warning based on Boolean tag defEnv :: Show a => String -- Environment Variable name -> (String -> a) -- function to process variable string (set as 'id' if not needed) -> a -- default value to use if environment variable is not set -> Bool -- True if we should warn if environment variable is not set -> IO a defEnv env fn def doWarn = lookupEnv env >>= \ e -> case e of Just s -> return $ fn s Nothing -> do when doWarn (doLog warningM $ "Environment variable: " ++ env ++ " is not set. Defaulting to " ++ (show def)) return def
Garygunn94/DFS
DirectoryServer/.stack-work/intero/intero16528ftM.hs
Haskell
bsd-3-clause
9,535
{-# LANGUAGE OverloadedStrings #-} -- | module Main where import Cache import Commands import qualified System.Process as P import Options.Applicative import qualified Data.Text as T import qualified Data.Text.IO as T import Shelly (shelly, Sh, fromText, FilePath) import Data.Monoid (mconcat) import Prelude hiding (FilePath) main :: IO () main = execParser hscacheInfo >>= shelly . hscache hscache :: Options -> Sh () hscache (Options ghc (Freeze args)) = freeze ghc args hscache (Options _ (AddSource dirs)) = addSourceCmd dirs hscache (Options _ Build) = build hscache (Options _ Install) = install hscache (Options _ (Exec args)) = exec args hscache (Options _ Repl) = repl hscache (Options _ Shell) = nix_shell hscacheInfo :: ParserInfo Options hscacheInfo = info (helper <*> optionsParser) (fullDesc <> progDesc "Fast sandboxed Haskell builds. Sandboxed builds of Haskell packages, using Cabal's dependency solver. Cache built packages indexed by all their transitive dependencies." <> header "hscache - fast sandboxed Haskell builds") data Options = Options GHC -- ^ GHC version, as Nix attribute Command data Command = Freeze [T.Text] | AddSource [FilePath] | Build | Install | Exec [T.Text] | Repl | Shell optionsParser :: Parser Options optionsParser = Options <$> ghcParser <*> commandParser commandParser :: Parser Command commandParser = subparser $ mconcat [ command "freeze" $ info (Freeze <$> many (argument text (metavar "CONSTRAINTS..."))) $ progDesc "Pick versions for all dependencies." , command "add-source" $ info (AddSource <$> some (argument filepath (metavar "DIRS..."))) $ progDesc "Make one or more local package available." , command "build" $ info (pure Build) $ progDesc "compile all configured components" , command "install" $ info (pure Install) $ progDesc "install executables on user path" , command "exec" $ info (Exec <$> some (argument text (metavar "COMMANDS..."))) $ progDesc "Give a command access to the sandbox package repository." , command "repl" $ info (pure Repl) $ progDesc "Open GHCi with access to sandbox packages." , command "shell" $ (info (pure Shell) $ progDesc "Launch a sub-shell with access to sandbox packages.") ] ghcParser :: Parser GHC ghcParser = GHC . T.pack <$> strOption ( short 'w' <> long "with-ghc" <> long "with-compiler" <> help "Nix attr for the GHC version: eg, ghc7101" <> metavar "GHC" <> showDefault <> value "ghc784" ) filepath :: ReadM FilePath filepath = fromText . T.pack <$> str text :: ReadM T.Text text = T.pack <$> str
bergey/hscache
src/Main.hs
Haskell
bsd-3-clause
2,821
module Problem37 where import Prime main :: IO () main = print . sum . take 11 . filter truncablePrime $ [11 ..] truncablePrime :: Int -> Bool truncablePrime n | n < 10 = isPrimeNaive n | otherwise = isPrimeNaive n && leftTruncablePrime n && rightTruncablePrime n leftTruncablePrime :: Int -> Bool leftTruncablePrime n | n < 10 = isPrimeNaive n | otherwise = isPrimeNaive n && (leftTruncablePrime . read . tail . show $ n) rightTruncablePrime :: Int -> Bool rightTruncablePrime n | n < 10 = isPrimeNaive n | otherwise = isPrimeNaive n && rightTruncablePrime (n `div` 10)
adityagupta1089/Project-Euler-Haskell
src/problems/Problem37.hs
Haskell
bsd-3-clause
609
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} module Main where import Control.Monad (mzero) import Data.Aeson import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as BL import Data.Char (chr) import qualified Data.Map as M import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.Encoding as T import Network.HTTP.Conduit hiding (Request, queryString) import Network.HTTP.Types (Query, status200) import Network.Wai import Network.Wai.Handler.Warp (run) import URI.ByteString.QQ import URI.ByteString (serializeURIRef') import Keys (fitbitKey) import Network.OAuth.OAuth2 ------------------------------------------------------------------------------ data FitbitUser = FitbitUser { userId :: Text , userName :: Text , userAge :: Int } deriving (Show, Eq) instance FromJSON FitbitUser where parseJSON (Object o) = FitbitUser <$> ((o .: "user") >>= (.: "encodedId")) <*> ((o .: "user") >>= (.: "fullName")) <*> ((o .: "user") >>= (.: "age")) parseJSON _ = mzero instance ToJSON FitbitUser where toJSON (FitbitUser fid name age) = object [ "id" .= fid , "name" .= name , "age" .= age ] ------------------------------------------------------------------------------ main :: IO () main = do print $ serializeURIRef' $ appendQueryParams [("state", state), ("scope", "profile")] $ authorizationUrl fitbitKey putStrLn "visit the url to continue" run 9988 application state :: B.ByteString state = "testFitbitApi" application :: Application application request respond = do response <- handleRequest requestPath request respond $ responseLBS status200 [("Content-Type", "text/plain")] response where requestPath = T.intercalate "/" $ pathInfo request handleRequest :: Text -> Request -> IO BL.ByteString handleRequest "favicon.ico" _ = return "" handleRequest _ request = do mgr <- newManager tlsManagerSettings token <- getApiToken mgr $ getApiCode request print token user <- getApiUser mgr (accessToken token) print user return $ encode user getApiCode :: Request -> ExchangeToken getApiCode request = case M.lookup "code" queryMap of Just code -> ExchangeToken $ T.decodeUtf8 $ code Nothing -> error "request doesn't include code" where queryMap = convertQueryToMap $ queryString request getApiToken :: Manager -> ExchangeToken -> IO (OAuth2Token) getApiToken mgr code = do result <- doJSONPostRequest mgr fitbitKey url $ body ++ [("state", state)] case result of Right token -> return token Left e -> error $ lazyBSToString e where (url, body) = accessTokenUrl fitbitKey code getApiUser :: Manager -> AccessToken -> IO (FitbitUser) getApiUser mgr token = do result <- authGetJSON mgr token [uri|https://api.fitbit.com/1/user/-/profile.json|] case result of Right user -> return user Left e -> error $ lazyBSToString e convertQueryToMap :: Query -> M.Map B.ByteString B.ByteString convertQueryToMap query = M.fromList $ map normalize query where normalize (k, Just v) = (k, v) normalize (k, Nothing) = (k, B.empty) lazyBSToString :: BL.ByteString -> String lazyBSToString s = map (chr . fromIntegral) (BL.unpack s)
reactormonk/hoauth2
example/Fitbit/test.hs
Haskell
bsd-3-clause
3,662
{-# LANGUAGE BangPatterns, ScopedTypeVariables, RecordWildCards #-} -- | -- Module : AI.HNN.Recurrent.Network -- Copyright : (c) 2012 Gatlin Johnson -- License : LGPL -- Maintainer : rokenrol@gmail.com -- Stability : experimental -- Portability : GHC -- -- An implementation of recurrent neural networks in pure Haskell. -- -- A network is an adjacency matrix of connection weights, the number of -- neurons, the number of inputs, and the threshold values for each neuron. -- -- E.g., -- -- > module Main where -- > -- > import AI.HNN.Recurrent.Network -- > -- > main = do -- > let numNeurons = 3 -- > numInputs = 1 -- > thresholds = replicate numNeurons 0.5 -- > inputs = [[0.38], [0.75]] -- > adj = [ 0.0, 0.0, 0.0, -- > 0.9, 0.8, 0.0, -- > 0.0, 0.1, 0.0 ] -- > n <- createNetwork numNeurons numInputs adj thresholds :: IO (Network Double) -- > output <- evalNet n inputs sigmoid -- > putStrLn $ "Output: " ++ (show output) -- -- This creates a network with three neurons (one of which is an input), an -- arbitrary connection / weight matrix, and arbitrary thresholds for each neuron. -- Then, we evaluate the network with an arbitrary input. -- -- For the purposes of this library, the outputs returned are the values of all -- the neurons except the inputs. Conceptually, in a recurrent net *any* -- non-input neuron can be treated as an output, so we let you decide which -- ones matter. module AI.HNN.Recurrent.Network ( -- * Network type Network, createNetwork, weights, size, nInputs, thresh, -- * Evaluation functions computeStep, evalNet, -- * Misc sigmoid ) where import System.Random.MWC import Control.Monad import Numeric.LinearAlgebra hiding (i) import Foreign.Storable as F -- | Our recurrent neural network data Network a = Network { weights :: !(Matrix a) , size :: {-# UNPACK #-} !Int , nInputs :: {-# UNPACK #-} !Int , thresh :: !(Vector a) } deriving Show -- | Creates a network with an adjacency matrix of your choosing, specified as -- an unboxed vector. You also must supply a vector of threshold values. createNetwork :: (Variate a, Fractional a, Storable a) => Int -- ^ number of total neurons neurons (input and otherwise) -> Int -- ^ number of inputs -> [a] -- ^ flat weight matrix -> [a] -- ^ threshold (bias) values for each neuron -> IO (Network a) -- ^ a new network createNetwork n m matrix thresh = return $! Network ( (n><n) matrix ) n m (n |> thresh) -- | Evaluates a network with the specified function and list of inputs -- precisely one time step. This is used by `evalNet` which is probably a -- more convenient interface for client applications. computeStep :: (Variate a, Num a, F.Storable a, Product a) => Network a -- ^ Network to evaluate input -> Vector a -- ^ vector of pre-existing state -> (a -> a) -- ^ activation function -> Vector a -- ^ list of inputs -> Vector a -- ^ new state vector computeStep (Network{..}) state activation input = mapVector activation $! zipVectorWith (-) (weights <> prefixed) thresh where prefixed = Numeric.LinearAlgebra.vjoin [ input, (subVector nInputs (size-nInputs) state) ] {-# INLINE prefixed #-} -- | Iterates over a list of input vectors in sequence and computes one time -- step for each. evalNet :: (Num a, Variate a, Fractional a, Product a) => Network a -- ^ Network to evaluate inputs -> [[a]] -- ^ list of input lists -> (a -> a) -- ^ activation function -> IO (Vector a) -- ^ output state vector evalNet n@(Network{..}) inputs activation = do s <- foldM (\x -> computeStepM n x activation) state inputsV return $! subVector nInputs (size-nInputs) s where state = fromList $ replicate size 0.0 {-# INLINE state #-} computeStepM _ s a i = return $ computeStep n s a i {-# INLINE computeStepM #-} inputsV = map (fromList) inputs {-# INLINE inputsV #-} -- | It's a simple, differentiable sigmoid function. sigmoid :: Floating a => a -> a sigmoid !x = 1 / (1 + exp (-x)) {-# INLINE sigmoid #-}
fffej/hnn
AI/HNN/Recurrent/Network.hs
Haskell
bsd-3-clause
4,375
{- foo bar a) foo foo b) bar bar baa -} {- foo bar * @foo * @bar baa -} {- foo bar > foo > bar baa -}
itchyny/vim-haskell-indent
test/comment/list.out.hs
Haskell
mit
126
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} -- Module: Gpg.EditKey -- -- Edit keys with Gpg's interactive mode module Gpg.EditKey where import Control.Monad import qualified Control.Exception as Ex import Control.Applicative import qualified Data.Text.Encoding as Text import Control.Monad.Trans.Free import Data.ByteString (ByteString) import qualified Data.ByteString as BS import Data.IORef import Data.Monoid import Data.Text (Text) import qualified Data.Text as Text import qualified Data.Text.IO as Text import System.Posix import Foreign.Ptr import Control.Monad.Trans import System.IO import Bindings import Gpg.Basic fdWrite' :: Fd -> ByteString -> IO ByteCount fdWrite' fd bs = BS.useAsCStringLen bs $ \(ptr, len) -> fdWriteBuf fd (castPtr ptr) (fromIntegral len) runEditAction :: Ctx -> Key -> GpgM () -> IO ByteString runEditAction ctx key action = do ref <- newIORef action editKey ctx key $ cb ref where cb :: IORef (GpgM ()) -> EditCallback cb _ StatusGotIt "" fd = fdWrite' fd "\n" >> return noError cb ref sc ln fd@(Fd fdInt) = do GpgM st <- readIORef ref go =<< runFreeT st where go (Pure ()) = return $ Error ErrUser1 ErrSourceUser1 "" go (Free (GpgError e)) = Ex.throwIO (MethodError e) go (Free (Send txt cont)) = do writeIORef ref (GpgM cont) case (fdInt, txt) of (-1, "") -> return noError (-1, _) -> return $ Error ErrUser2 ErrSourceUser1 "" _ -> fdWrite' fd (Text.encodeUtf8 txt <> "\n") >> return noError go (Free (GetState f)) = go =<< runFreeT (f sc ln) data RevocationReason = NoReason | Compromised | Superseeded | NoLongerUsed deriving (Eq, Show, Enum) -- | Revoke a key revoke :: Ctx -> Key -> RevocationReason -> Text -> IO ByteString revoke ctx key reason reasonText = runEditAction ctx key $ do expectAndSend (StatusGetLine, "keyedit.prompt") "revkey" expectAndSend (StatusGetBool, "keyedit.revoke.subkey.okay") "y" let reasonCode = Text.pack . show $ fromEnum reason expectAndSend (StatusGetLine, "ask_revocation_reason.code") reasonCode forM_ (Text.lines reasonText) $ \line -> do expect StatusGetLine "ask_revocation_reason.text" send line expectAndSend (StatusGetLine, "ask_revocation_reason.text") "" expectAndSend (StatusGetBool, "ask_revocation_reason.okay") "y" getPassphrase quit liftIO . print =<< getState return ()
Philonous/pontarius-gpg
src/Gpg/EditKey.hs
Haskell
mit
2,786
{-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TypeOperators #-} module Qi.Program.SQS.Lang where import Control.Monad.Freer import Data.Aeson (FromJSON, ToJSON) import qualified Data.ByteString.Lazy as LBS import Network.AWS.SQS import Protolude import Qi.AWS.SQS import Qi.Config.AWS.SQS import Qi.Config.Identifier import Qi.Core.Curry import Qi.Program.Gen.Lang data SqsEff r where SendSqsMessage :: ToJSON a => SqsQueueId -> a -> SqsEff () ReceiveSqsMessage :: FromJSON a => SqsQueueId -> SqsEff [(a, ReceiptHandle)] DeleteSqsMessage :: SqsQueueId -> ReceiptHandle -> SqsEff () sendSqsMessage :: (Member SqsEff effs, ToJSON a) => SqsQueueId -> a -> Eff effs () sendSqsMessage = send .: SendSqsMessage receiveSqsMessage :: (Member SqsEff effs, FromJSON a) => SqsQueueId -> Eff effs [(a, ReceiptHandle)] -- the json body and the receipt handle receiveSqsMessage = send . ReceiveSqsMessage deleteSqsMessage :: (Member SqsEff effs) => SqsQueueId -> ReceiptHandle -> Eff effs () deleteSqsMessage = send .: DeleteSqsMessage
ababkin/qmuli
library/Qi/Program/SQS/Lang.hs
Haskell
mit
1,453
-- | Specification for Pos.Chain.Ssc.GodTossing.Toss.Pure module Test.Pos.Ssc.Toss.PureSpec ( spec ) where import Universum import qualified Crypto.Random as Rand import Data.Default (def) import Test.Hspec (Spec, describe) import Test.Hspec.QuickCheck (modifyMaxSuccess, prop) import Test.QuickCheck (Arbitrary (..), Gen, Property, forAll, listOf, suchThat, (===)) import Test.QuickCheck.Arbitrary.Generic (genericArbitrary, genericShrink) import Pos.Chain.Ssc (InnerSharesMap, Opening, SignedCommitment, VssCertificate (..)) import qualified Pos.Chain.Ssc as Toss import Pos.Core (EpochOrSlot, StakeholderId, addressHash) import Test.Pos.Core.Arbitrary () import Test.Pos.Infra.Arbitrary.Ssc () spec :: Spec spec = describe "Toss" $ do let smaller n = modifyMaxSuccess (const n) describe "PureToss" $ smaller 30 $ do prop "Adding and deleting a signed commitment in the 'PureToss' monad is the\ \ same as doing nothing" putDelCommitment prop "Adding and deleting an opening in the 'PureToss' monad is the same as doing\ \ nothing" putDelOpening prop "Adding and deleting a share in the 'PureToss' monad is the same as doing\ \ nothing" putDelShare data TossAction = PutCommitment SignedCommitment | PutOpening StakeholderId Opening | PutShares StakeholderId InnerSharesMap | PutCertificate VssCertificate | ResetCO | ResetShares | DelCommitment StakeholderId | DelOpening StakeholderId | DelShares StakeholderId | SetEpochOrSlot EpochOrSlot deriving (Show, Eq, Generic) instance Arbitrary TossAction where arbitrary = genericArbitrary shrink = genericShrink actionToMonad :: Toss.MonadToss m => TossAction -> m () actionToMonad (PutCommitment sc) = Toss.putCommitment sc actionToMonad (PutOpening sid o) = Toss.putOpening sid o actionToMonad (PutShares sid ism) = Toss.putShares sid ism actionToMonad (PutCertificate v) = Toss.putCertificate v actionToMonad ResetCO = Toss.resetCO actionToMonad ResetShares = Toss.resetShares actionToMonad (DelCommitment sid) = Toss.delCommitment sid actionToMonad (DelOpening sid) = Toss.delOpening sid actionToMonad (DelShares sid) = Toss.delShares sid actionToMonad (SetEpochOrSlot eos) = Toss.setEpochOrSlot eos emptyTossSt :: Toss.SscGlobalState emptyTossSt = def perform :: [TossAction] -> Toss.PureToss () perform = mapM_ actionToMonad -- | Type synonym used for convenience. This quintuple is used to pass the randomness -- needed to run 'PureToss' actions to the testing property. type TossTestInfo = (Word64, Word64, Word64, Word64, Word64) -- | Operational equivalence operator in the 'PureToss' monad. To be used when -- equivalence between two sequences of actions in 'PureToss' is to be tested/proved. (==^) :: [TossAction] -> [TossAction] -> Gen TossAction -> TossTestInfo -> Property t1 ==^ t2 = \prefixGen ttInfo -> forAll ((listOf prefixGen) :: Gen [TossAction]) $ \prefix -> forAll (arbitrary :: Gen [TossAction]) $ \suffix -> let applyAction x = view _2 . fst . Rand.withDRG (Rand.drgNewTest ttInfo) . Toss.runPureToss emptyTossSt $ (perform $ prefix ++ x ++ suffix) in applyAction t1 === applyAction t2 {- A note on the following tests ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The reason these tests have to pass a custom generator for the prefix of the action list to '(==^)' is that in each case, there is a particular sequence of actions for which the property does not hold. Using one of the following tests as an example: Let 'o, o´ :: Opening' such that 'o /= o´'. This sequence of actions in the 'PureToss' monad: [PutOpening sid o´, PutOpening sid o, DelOpening sid] is not, in operational semantics terms, equal to the sequence [PutOpening sid o´] It is instead equivalent to [] Because these actions are performed from left to right, performing an insertion with the same key several times without deleting it in between those insertions means only the last insertion actually matters for these tests. As such, prefixes with an insertion with the same key as the action being tested in the property will cause it to fail. -} putDelCommitment :: SignedCommitment -> TossTestInfo -> Property putDelCommitment sc = let actionPrefixGen = arbitrary `suchThat` (\case PutCommitment sc' -> sc ^. _1 /= sc'^. _1 _ -> True) in ([PutCommitment sc, DelCommitment $ addressHash $ sc ^. _1] ==^ []) actionPrefixGen putDelOpening :: StakeholderId -> Opening -> TossTestInfo -> Property putDelOpening sid o = let actionPrefixGen = arbitrary `suchThat` (\case PutOpening sid' _ -> sid /= sid' _ -> True) in ([PutOpening sid o, DelOpening sid] ==^ []) actionPrefixGen putDelShare :: StakeholderId -> InnerSharesMap -> TossTestInfo -> Property putDelShare sid ism = let actionPrefixGen = arbitrary `suchThat` (\case PutShares sid' _ -> sid' /= sid _ -> True) in ([PutShares sid ism, DelShares sid] ==^ []) actionPrefixGen
input-output-hk/pos-haskell-prototype
lib/test/Test/Pos/Ssc/Toss/PureSpec.hs
Haskell
mit
5,450
--ProbabFP.hs --Author: Chad Myles --Date: 9/26/16 module Probab ( Dist, unit, uniformDist, weightedDist, toList, mergeEqual, possibilities, probabilityOf, adjoin, distFil, transform, combine, duplicate ) where import Data.List data Dist a = Dist [(a, Float)] deriving( Show) instance Functor Dist where fmap f (Dist xs) = Dist (map (\(x,p) -> (f x, p)) xs) --TODO: make sure sum of Floats = 1 and none are negative -- -- Public Interface -- unit :: a -> Dist a uniformDist :: [a] -> Dist a weightedDist :: [(a, Float)] -> Dist a toList :: Dist a -> [(a, Float)] mergeEqual :: Eq a => Dist a -> Dist a possibilities :: Eq a => Dist a -> [a] probabilityOf :: Eq a => Dist a -> (a -> Bool) -> Float adjoin :: (a -> Dist b) -> Dist a -> Dist (a,b) distFil :: (a -> Bool) -> Dist a -> Dist a transform :: (a -> Dist b) -> Dist a-> Dist b combine :: Dist a -> Dist b -> Dist (a, b) duplicate :: Integral a => a -> Dist b -> Dist [b] -- -- Implementation of Public Interface -- --unit :: a -> Dist a unit x = Dist [(x,1.0)] --uniformDist :: [a] -> Dist a uniformDist xs = Dist (map (\ x -> (x, (1.0 / len))) xs) where len = fromIntegral (length xs) --weightedDist :: [(a, Float)] -> Dist a weightedDist xs = Dist xs --toList :: Dist a -> [(a, Float)] toList (Dist valList ) = valList --mergeEqual :: Eq a => [(a, Float)] -> [(a, Float)] mergeEqual xs = let distinct = possibilities xs in weightedDist (map (\y -> (y, (foldl (\acc (b,c) ->if (b == y) then (acc + c) else acc) 0.0 (toList xs)))) distinct) --possibilites :: Eq a => Dist a -> [a] possibilities xs = let firsts = map (\(a,b) -> a) (toList xs) in nub firsts --probabilityOf :: Eq a => [(a, Float)] -> a -> Float probabilityOf xs f = foldl (\acc (a, b) -> if (f a) then (acc + b) else (acc)) 0.0 (toList (mergeEqual xs)) --adjoin :: (a -> Dist b) -> Dist a -> Dist (a,b) adjoin f (Dist xs) = let wrapped = map (\(k, p) -> let (Dist res) = f k in map (\(k',p') -> ((k,k'), p*p')) res) xs in Dist (concat wrapped) --distFil :: (a -> Bool) -> Dist a -> Dist a distFil f xs = let intermed = filter (\ x -> f (fst x)) (toList xs) in weightedDist (map (\ (x,y) -> (x, y * (1.0 / totalProb(intermed)))) intermed) --transform :: (a -> Dist b) -> Dist a -> Dist b transform f xs = --create ([(b, Float)], Float) list let intermed = (map (\(a, b) -> ((toList (f a)), b)) (toList xs)) in weightedDist (concat (map (\(a, b) -> (map (\(c,d) -> (c, b*d)) a)) intermed)) --combine :: Dist a -> Dist b -> Dist (a, b) combine xs ys = weightedDist (concat (map (\ x -> map (\ y -> ((fst x, fst y), snd x * snd y)) (toList ys)) (toList xs))) --duplicate :: Dist a -> Int -> Dist [a] duplicate num xs = if (num == 1) then weightedDist (map (\(a,b) -> ([a], b)) (toList xs)) else weightedDist (map (\((a,b),c) -> (a:b,c)) (toList (combine xs (duplicate (num-1) xs)))) -- -- Private functions -- totalProb :: [(a,Float)] -> Float totalProb xs = foldl (\acc (a,b) -> acc + b) 0.0 xs
seabornloyalis/probabilistic-haskell
ProbabFP.hs
Haskell
mit
3,417
module Main where main :: IO () main = putStrLn "Hello, World!"
nixdog/helloworld
haskell.hs
Haskell
apache-2.0
69
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE NoImplicitPrelude, AutoDeriveTypeable, MagicHash, ExistentialQuantification #-} {-# OPTIONS_GHC -funbox-strict-fields #-} {-# OPTIONS_HADDOCK hide #-} ----------------------------------------------------------------------------- -- | -- Module : GHC.IO.Exception -- Copyright : (c) The University of Glasgow, 2009 -- License : see libraries/base/LICENSE -- -- Maintainer : libraries@haskell.org -- Stability : internal -- Portability : non-portable -- -- IO-related Exception types and functions -- ----------------------------------------------------------------------------- module GHC.IO.Exception ( BlockedIndefinitelyOnMVar(..), blockedIndefinitelyOnMVar, BlockedIndefinitelyOnSTM(..), blockedIndefinitelyOnSTM, Deadlock(..), AllocationLimitExceeded(..), allocationLimitExceeded, AssertionFailed(..), SomeAsyncException(..), asyncExceptionToException, asyncExceptionFromException, AsyncException(..), stackOverflow, heapOverflow, ArrayException(..), ExitCode(..), ioException, ioError, IOError, IOException(..), IOErrorType(..), userError, assertError, unsupportedOperation, untangle, ) where import GHC.Base import GHC.List import GHC.IO import GHC.Show import GHC.Read import GHC.Exception import GHC.IO.Handle.Types import Foreign.C.Types import Data.Typeable ( Typeable, cast ) -- ------------------------------------------------------------------------ -- Exception datatypes and operations -- |The thread is blocked on an @MVar@, but there are no other references -- to the @MVar@ so it can't ever continue. data BlockedIndefinitelyOnMVar = BlockedIndefinitelyOnMVar deriving Typeable instance Exception BlockedIndefinitelyOnMVar instance Show BlockedIndefinitelyOnMVar where showsPrec _ BlockedIndefinitelyOnMVar = showString "thread blocked indefinitely in an MVar operation" blockedIndefinitelyOnMVar :: SomeException -- for the RTS blockedIndefinitelyOnMVar = toException BlockedIndefinitelyOnMVar ----- -- |The thread is waiting to retry an STM transaction, but there are no -- other references to any @TVar@s involved, so it can't ever continue. data BlockedIndefinitelyOnSTM = BlockedIndefinitelyOnSTM deriving Typeable instance Exception BlockedIndefinitelyOnSTM instance Show BlockedIndefinitelyOnSTM where showsPrec _ BlockedIndefinitelyOnSTM = showString "thread blocked indefinitely in an STM transaction" blockedIndefinitelyOnSTM :: SomeException -- for the RTS blockedIndefinitelyOnSTM = toException BlockedIndefinitelyOnSTM ----- -- |There are no runnable threads, so the program is deadlocked. -- The @Deadlock@ exception is raised in the main thread only. data Deadlock = Deadlock deriving Typeable instance Exception Deadlock instance Show Deadlock where showsPrec _ Deadlock = showString "<<deadlock>>" ----- -- |This thread has exceeded its allocation limit. See -- 'GHC.Conc.setAllocationCounter' and -- 'GHC.Conc.enableAllocationLimit'. -- -- @since 4.8.0.0 data AllocationLimitExceeded = AllocationLimitExceeded deriving Typeable instance Exception AllocationLimitExceeded instance Show AllocationLimitExceeded where showsPrec _ AllocationLimitExceeded = showString "allocation limit exceeded" allocationLimitExceeded :: SomeException -- for the RTS allocationLimitExceeded = toException AllocationLimitExceeded ----- -- |'assert' was applied to 'False'. data AssertionFailed = AssertionFailed String deriving Typeable instance Exception AssertionFailed instance Show AssertionFailed where showsPrec _ (AssertionFailed err) = showString err ----- -- |Superclass for asynchronous exceptions. -- -- @since 4.7.0.0 data SomeAsyncException = forall e . Exception e => SomeAsyncException e deriving Typeable instance Show SomeAsyncException where show (SomeAsyncException e) = show e instance Exception SomeAsyncException -- |@since 4.7.0.0 asyncExceptionToException :: Exception e => e -> SomeException asyncExceptionToException = toException . SomeAsyncException -- |@since 4.7.0.0 asyncExceptionFromException :: Exception e => SomeException -> Maybe e asyncExceptionFromException x = do SomeAsyncException a <- fromException x cast a -- |Asynchronous exceptions. data AsyncException = StackOverflow -- ^The current thread\'s stack exceeded its limit. -- Since an exception has been raised, the thread\'s stack -- will certainly be below its limit again, but the -- programmer should take remedial action -- immediately. | HeapOverflow -- ^The program\'s heap is reaching its limit, and -- the program should take action to reduce the amount of -- live data it has. Notes: -- -- * It is undefined which thread receives this exception. -- -- * GHC currently does not throw 'HeapOverflow' exceptions. | ThreadKilled -- ^This exception is raised by another thread -- calling 'Control.Concurrent.killThread', or by the system -- if it needs to terminate the thread for some -- reason. | UserInterrupt -- ^This exception is raised by default in the main thread of -- the program when the user requests to terminate the program -- via the usual mechanism(s) (e.g. Control-C in the console). deriving (Eq, Ord, Typeable) instance Exception AsyncException where toException = asyncExceptionToException fromException = asyncExceptionFromException -- | Exceptions generated by array operations data ArrayException = IndexOutOfBounds String -- ^An attempt was made to index an array outside -- its declared bounds. | UndefinedElement String -- ^An attempt was made to evaluate an element of an -- array that had not been initialized. deriving (Eq, Ord, Typeable) instance Exception ArrayException -- for the RTS stackOverflow, heapOverflow :: SomeException stackOverflow = toException StackOverflow heapOverflow = toException HeapOverflow instance Show AsyncException where showsPrec _ StackOverflow = showString "stack overflow" showsPrec _ HeapOverflow = showString "heap overflow" showsPrec _ ThreadKilled = showString "thread killed" showsPrec _ UserInterrupt = showString "user interrupt" instance Show ArrayException where showsPrec _ (IndexOutOfBounds s) = showString "array index out of range" . (if not (null s) then showString ": " . showString s else id) showsPrec _ (UndefinedElement s) = showString "undefined array element" . (if not (null s) then showString ": " . showString s else id) -- ----------------------------------------------------------------------------- -- The ExitCode type -- We need it here because it is used in ExitException in the -- Exception datatype (above). -- | Defines the exit codes that a program can return. data ExitCode = ExitSuccess -- ^ indicates successful termination; | ExitFailure Int -- ^ indicates program failure with an exit code. -- The exact interpretation of the code is -- operating-system dependent. In particular, some values -- may be prohibited (e.g. 0 on a POSIX-compliant system). deriving (Eq, Ord, Read, Show, Typeable) instance Exception ExitCode ioException :: IOException -> IO a ioException err = throwIO err -- | Raise an 'IOError' in the 'IO' monad. ioError :: IOError -> IO a ioError = ioException -- --------------------------------------------------------------------------- -- IOError type -- | The Haskell 2010 type for exceptions in the 'IO' monad. -- Any I\/O operation may raise an 'IOError' instead of returning a result. -- For a more general type of exception, including also those that arise -- in pure code, see "Control.Exception.Exception". -- -- In Haskell 2010, this is an opaque type. type IOError = IOException -- |Exceptions that occur in the @IO@ monad. -- An @IOException@ records a more specific error type, a descriptive -- string and maybe the handle that was used when the error was -- flagged. data IOException = IOError { ioe_handle :: Maybe Handle, -- the handle used by the action flagging -- the error. ioe_type :: IOErrorType, -- what it was. ioe_location :: String, -- location. ioe_description :: String, -- error type specific information. ioe_errno :: Maybe CInt, -- errno leading to this error, if any. ioe_filename :: Maybe FilePath -- filename the error is related to. } deriving Typeable instance Exception IOException instance Eq IOException where (IOError h1 e1 loc1 str1 en1 fn1) == (IOError h2 e2 loc2 str2 en2 fn2) = e1==e2 && str1==str2 && h1==h2 && loc1==loc2 && en1==en2 && fn1==fn2 -- | An abstract type that contains a value for each variant of 'IOError'. data IOErrorType -- Haskell 2010: = AlreadyExists | NoSuchThing | ResourceBusy | ResourceExhausted | EOF | IllegalOperation | PermissionDenied | UserError -- GHC only: | UnsatisfiedConstraints | SystemError | ProtocolError | OtherError | InvalidArgument | InappropriateType | HardwareFault | UnsupportedOperation | TimeExpired | ResourceVanished | Interrupted instance Eq IOErrorType where x == y = isTrue# (getTag x ==# getTag y) instance Show IOErrorType where showsPrec _ e = showString $ case e of AlreadyExists -> "already exists" NoSuchThing -> "does not exist" ResourceBusy -> "resource busy" ResourceExhausted -> "resource exhausted" EOF -> "end of file" IllegalOperation -> "illegal operation" PermissionDenied -> "permission denied" UserError -> "user error" HardwareFault -> "hardware fault" InappropriateType -> "inappropriate type" Interrupted -> "interrupted" InvalidArgument -> "invalid argument" OtherError -> "failed" ProtocolError -> "protocol error" ResourceVanished -> "resource vanished" SystemError -> "system error" TimeExpired -> "timeout" UnsatisfiedConstraints -> "unsatisified constraints" -- ultra-precise! UnsupportedOperation -> "unsupported operation" -- | Construct an 'IOError' value with a string describing the error. -- The 'fail' method of the 'IO' instance of the 'Monad' class raises a -- 'userError', thus: -- -- > instance Monad IO where -- > ... -- > fail s = ioError (userError s) -- userError :: String -> IOError userError str = IOError Nothing UserError "" str Nothing Nothing -- --------------------------------------------------------------------------- -- Showing IOErrors instance Show IOException where showsPrec p (IOError hdl iot loc s _ fn) = (case fn of Nothing -> case hdl of Nothing -> id Just h -> showsPrec p h . showString ": " Just name -> showString name . showString ": ") . (case loc of "" -> id _ -> showString loc . showString ": ") . showsPrec p iot . (case s of "" -> id _ -> showString " (" . showString s . showString ")") -- Note the use of "lazy". This means that -- assert False (throw e) -- will throw the assertion failure rather than e. See trac #5561. assertError :: Addr# -> Bool -> a -> a assertError str predicate v | predicate = lazy v | otherwise = throw (AssertionFailed (untangle str "Assertion failed")) unsupportedOperation :: IOError unsupportedOperation = (IOError Nothing UnsupportedOperation "" "Operation is not supported" Nothing Nothing) {- (untangle coded message) expects "coded" to be of the form "location|details" It prints location message details -} untangle :: Addr# -> String -> String untangle coded message = location ++ ": " ++ message ++ details ++ "\n" where coded_str = unpackCStringUtf8# coded (location, details) = case (span not_bar coded_str) of { (loc, rest) -> case rest of ('|':det) -> (loc, ' ' : det) _ -> (loc, "") } not_bar c = c /= '|'
green-haskell/ghc
libraries/base/GHC/IO/Exception.hs
Haskell
bsd-3-clause
12,430
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE NoImplicitPrelude, MagicHash, ImplicitParams #-} {-# LANGUAGE RankNTypes, PolyKinds, DataKinds #-} {-# OPTIONS_HADDOCK not-home #-} ----------------------------------------------------------------------------- -- | -- Module : GHC.Err -- Copyright : (c) The University of Glasgow, 1994-2002 -- License : see libraries/base/LICENSE -- -- Maintainer : cvs-ghc@haskell.org -- Stability : internal -- Portability : non-portable (GHC extensions) -- -- The "GHC.Err" module defines the code for the wired-in error functions, -- which have a special type in the compiler (with \"open tyvars\"). -- -- We cannot define these functions in a module where they might be used -- (e.g., "GHC.Base"), because the magical wired-in type will get confused -- with what the typechecker figures out. -- ----------------------------------------------------------------------------- module GHC.Err( absentErr, error, errorWithoutStackTrace, undefined ) where import GHC.Types (Char, RuntimeRep) import GHC.Stack.Types import GHC.Prim import GHC.Integer () -- Make sure Integer and Natural are compiled first import GHC.Natural () -- because GHC depends on it in a wired-in way -- so the build system doesn't see the dependency. -- See Note [Depend on GHC.Integer] and -- Note [Depend on GHC.Natural] in GHC.Base. import {-# SOURCE #-} GHC.Exception ( errorCallWithCallStackException , errorCallException ) -- | 'error' stops execution and displays an error message. error :: forall (r :: RuntimeRep). forall (a :: TYPE r). HasCallStack => [Char] -> a error s = raise# (errorCallWithCallStackException s ?callStack) -- Bleh, we should be using 'GHC.Stack.callStack' instead of -- '?callStack' here, but 'GHC.Stack.callStack' depends on -- 'GHC.Stack.popCallStack', which is partial and depends on -- 'error'.. Do as I say, not as I do. -- | A variant of 'error' that does not produce a stack trace. -- -- @since 4.9.0.0 errorWithoutStackTrace :: forall (r :: RuntimeRep). forall (a :: TYPE r). [Char] -> a errorWithoutStackTrace s = raise# (errorCallException s) -- Note [Errors in base] -- ~~~~~~~~~~~~~~~~~~~~~ -- As of base-4.9.0.0, `error` produces a stack trace alongside the -- error message using the HasCallStack machinery. This provides -- a partial stack trace, containing the call-site of each function -- with a HasCallStack constraint. -- -- In base, however, the only functions that have such constraints are -- error and undefined, so the stack traces from partial functions in -- base will never contain a call-site in user code. Instead we'll -- usually just get the actual call to error. Base functions already -- have a good habit of providing detailed error messages, including the -- name of the offending partial function, so the partial stack-trace -- does not provide any extra information, just noise. Thus, we export -- the callstack-aware error, but within base we use the -- errorWithoutStackTrace variant for more hygienic error messages. -- | A special case of 'error'. -- It is expected that compilers will recognize this and insert error -- messages which are more appropriate to the context in which 'undefined' -- appears. undefined :: forall (r :: RuntimeRep). forall (a :: TYPE r). HasCallStack => a undefined = error "Prelude.undefined" -- | Used for compiler-generated error message; -- encoding saves bytes of string junk. absentErr :: a absentErr = errorWithoutStackTrace "Oops! The program has entered an `absent' argument!\n"
sdiehl/ghc
libraries/base/GHC/Err.hs
Haskell
bsd-3-clause
3,686
{-# OPTIONS_GHC -funbox-strict-fields #-} module RestyScript.Emitter.Stats ( Stats, emit, emitJSON ) where import RestyScript.AST import Text.JSON data Stats = Stats { modelList :: ![String], funcList :: ![String], selectedMax :: !Int, joinedMax :: !Int, comparedCount :: !Int, queryCount :: !Int } deriving (Ord, Eq, Show) instance JSON Stats where showJSON st = JSObject $ toJSObject [ ("modelList", showList $ modelList st), ("funcList", showList $ funcList st), ("selectedMax", showJSON $ selectedMax st), ("joinedMax", showJSON $ joinedMax st), ("comparedCount", showJSON $ comparedCount st), ("queryCount", showJSON $ queryCount st)] where showList = JSArray . map showJSON readJSON = undefined si = Stats { modelList = [], funcList = [], selectedMax = 0, joinedMax = 0, comparedCount = 0, queryCount = 0 } findModel :: RSVal -> Stats -> Stats findModel (Model (Symbol n)) st = st { modelList = [n] } findModel (Model (Variable _ n)) st = st { modelList = ['$':n] } findModel _ st = st findFunc :: RSVal -> Stats -> Stats findFunc (FuncCall (Symbol func) _) st = st { funcList = func : (funcList st) } findFunc (FuncCall (Variable _ func) _) st = st { funcList = ('$':func) : (funcList st) } findFunc _ st = st findSelected :: RSVal -> Stats -> Stats findSelected (Select lst) st = st { selectedMax = length lst } findSelected _ st = st findJoined :: RSVal -> Stats -> Stats findJoined (From lst) st = st { joinedMax = length lst } findJoined _ st = st findQuery :: RSVal -> Stats -> Stats findQuery (Query _) st = st { queryCount = 1 } findQuery _ st = st findCompared :: RSVal -> Stats -> Stats findCompared (Compare _ _ _) st = st { comparedCount = 1 } findCompared _ st = st visit :: RSVal -> Stats visit node = foldr (\f st -> f node st) si [findModel, findFunc, findSelected, findJoined, findCompared, findQuery] merge :: Stats -> Stats -> Stats merge a b = Stats { modelList = (modelList a) ++ (modelList b), funcList = (funcList a) ++ (funcList b), selectedMax = max (selectedMax a) (selectedMax b), joinedMax = max (joinedMax a) (joinedMax b), comparedCount = comparedCount a + comparedCount b, queryCount = queryCount a + queryCount b } emit :: RSVal -> Stats emit = traverse visit merge emitJSON :: RSVal -> String emitJSON = encode . emit
beni55/old-openresty
haskell/src/RestyScript/Emitter/Stats.hs
Haskell
bsd-3-clause
2,506
{- $Id: AFRPTestsSwitch.hs,v 1.2 2003/11/10 21:28:58 antony Exp $ ****************************************************************************** * A F R P * * * * Module: AFRPTestsSwitch * * Purpose: Test cases for switch * * Authors: Antony Courtney and Henrik Nilsson * * * * Copyright (c) Yale University, 2003 * * * ****************************************************************************** -} module AFRPTestsSwitch (switch_tr, switch_trs) where import FRP.Yampa import FRP.Yampa.EventS import FRP.Yampa.Internals (Event(NoEvent, Event)) import AFRPTestsCommon ------------------------------------------------------------------------------ -- Test cases for switch and dSwitch ------------------------------------------------------------------------------ switch_inp1 = deltaEncode 1.0 $ [1.0, 1.0, 1.0, 2.0, 3.0, 3.0, 4.0, 4.0, 4.0, 5.0, 6.0, 6.0, 7.0, 7.0, 7.0, 8.0] ++ repeat 9.0 switch_t0 = take 18 $ embed (switch switch_t0a $ \x -> switch (switch_t0b x) $ \x -> switch (switch_t0c x) $ \x -> switch (switch_t0c x) $ \x -> switch (switch_t0d x) $ \x -> switch (switch_t0e x) $ \x -> switch (switch_t0e x) $ switch_t0final) switch_inp1 switch_t0a :: SF Double (Double, Event Int) switch_t0a = localTime >>> arr dup >>> second (arr (>= 3.0) >>> edge >>> arr (`tag` 17)) switch_t0b :: Int -> SF Double (Double, Event Int) switch_t0b x = localTime >>> arr dup >>> second (arr (>= 3.0) >>> edge >>> arr (`tag` (23 + x))) -- This should raise an event IMMEDIATELY: no time should pass. switch_t0c :: Num b => b -> SF a (a, Event b) switch_t0c x = arr dup >>> second (now (x + 1)) switch_t0d x = (arr (+ (fromIntegral x))) &&& (arr (>= 7.0) >>> edge) -- This should raise an event IMMEDIATELY: no time should pass. switch_t0e :: b -> SF a (a, Event a) switch_t0e _ = arr dup >>> second snap switch_t0final :: Double -> SF Double Double switch_t0final x = arr (+x) switch_t0r = [0.0, 1.0, 2.0, -- switch_t0a 0.0, 1.0, 2.0, -- switch_t0b 46.0, 46.0, 46.0, 47.0, 48.0, 48.0, -- switch_t0d 14.0, 14.0, 14.0, 15.0, 16.0, 16.0 -- switch_t0final ] switch_t1 = take 32 $ embed (switch_t1rec 42.0) switch_inp1 -- Outputs current input, local time, and the value of the initializing -- argument until some time has passed (determined by integrating a constant), -- at which point an event occurs. switch_t1a :: Double -> SF Double ((Double,Double,Double), Event ()) switch_t1a x = (arr dup >>> second localTime >>> arr (\(a,t) -> (a,t,x))) &&& (constant 0.5 >>> integral >>> (arr (>= (2.0 :: Double)) -- Used to work with no sig. >>> edge)) -- This should raise an event IMMEDIATELY: no time should pass. switch_t1b :: b -> SF a ((Double,Double,Double), Event a) switch_t1b _ = constant (-999.0,-999.0,-999.0) &&& snap switch_t1rec :: Double -> SF Double (Double,Double,Double) switch_t1rec x = switch (switch_t1a x) $ \x -> switch (switch_t1b x) $ \x -> switch (switch_t1b x) $ switch_t1rec switch_t1r = [(1.0,0.0,42.0), (1.0,1.0,42.0), (1.0,2.0,42.0), (2.0,3.0,42.0), (3.0,0.0,3.0), (3.0,1.0,3.0), (4.0,2.0,3.0), (4.0,3.0,3.0), (4.0,0.0,4.0), (5.0,1.0,4.0), (6.0,2.0,4.0), (6.0,3.0,4.0), (7.0,0.0,7.0), (7.0,1.0,7.0), (7.0,2.0,7.0), (8.0,3.0,7.0), (9.0,0.0,9.0), (9.0,1.0,9.0), (9.0,2.0,9.0), (9.0,3.0,9.0), (9.0,0.0,9.0), (9.0,1.0,9.0), (9.0,2.0,9.0), (9.0,3.0,9.0), (9.0,0.0,9.0), (9.0,1.0,9.0), (9.0,2.0,9.0), (9.0,3.0,9.0), (9.0,0.0,9.0), (9.0,1.0,9.0), (9.0,2.0,9.0), (9.0,3.0,9.0)] switch_t2 = take 18 $ embed (dSwitch switch_t0a $ \x -> dSwitch (switch_t0b x) $ \x -> dSwitch (switch_t0c x) $ \x -> dSwitch (switch_t0c x) $ \x -> dSwitch (switch_t0d x) $ \x -> dSwitch (switch_t0e x) $ \x -> dSwitch (switch_t0e x) $ switch_t0final) switch_inp1 switch_t2r = [0.0, 1.0, 2.0, -- switch_t0a 3.0, 1.0, 2.0, -- switch_t0b 3.0, 46.0, 46.0, 47.0, 48.0, 48.0, -- switch_t0d 49.0, 14.0, 14.0, 15.0, 16.0, 16.0 -- switch_t0final ] switch_t3 = take 32 $ embed (switch_t3rec 42.0) switch_inp1 switch_t3rec :: Double -> SF Double (Double,Double,Double) switch_t3rec x = dSwitch (switch_t1a x) $ \x -> dSwitch (switch_t1b x) $ \x -> dSwitch (switch_t1b x) $ switch_t3rec switch_t3r = [(1.0,0.0,42.0), (1.0,1.0,42.0), (1.0,2.0,42.0), (2.0,3.0,42.0), (3.0,4.0,42.0), (3.0,1.0,3.0), (4.0,2.0,3.0), (4.0,3.0,3.0), (4.0,4.0,3.0), (5.0,1.0,4.0), (6.0,2.0,4.0), (6.0,3.0,4.0), (7.0,4.0,4.0), (7.0,1.0,7.0), (7.0,2.0,7.0), (8.0,3.0,7.0), (9.0,4.0,7.0), (9.0,1.0,9.0), (9.0,2.0,9.0), (9.0,3.0,9.0), (9.0,4.0,9.0), (9.0,1.0,9.0), (9.0,2.0,9.0), (9.0,3.0,9.0), (9.0,4.0,9.0), (9.0,1.0,9.0), (9.0,2.0,9.0), (9.0,3.0,9.0), (9.0,4.0,9.0), (9.0,1.0,9.0), (9.0,2.0,9.0), (9.0,3.0,9.0)] -- The correct strictness properties of dSwitch are crucial here. -- switch does not work. switch_t4 = take 25 $ embed (loop $ dSwitch switch_t4a $ \_ -> dSwitch switch_t4a $ \_ -> dSwitch switch_t4a $ \_ -> switch_t4final ) (deltaEncode 1.0 (repeat ())) switch_t4a :: SF (a, Double) ((Double, Double), Event ()) switch_t4a = (constant 1.0 >>> integral >>> arr dup) &&& (arr (\ (_, x) -> x >= 5.0) >>> edge) switch_t4final :: SF (a, Double) (Double, Double) switch_t4final = constant 0.1 >>> integral >>> arr dup switch_t4r = [0.0, 1.0, 2.0, 3.0, 4.0, -- switch_t4a 5.0, 1.0, 2.0, 3.0, 4.0, -- switch_t4a 5.0, 1.0, 2.0, 3.0, 4.0, -- switch_t4a 5.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9 -- switch_t4final ] impulseIntegral2 :: VectorSpace a s => SF (a, Event a) a impulseIntegral2 = switch (first integral >>> arr (\(a, ea) -> (a, fmap (^+^ a) ea))) impulseIntegral2' where impulseIntegral2' :: VectorSpace a s => a -> SF (a, Event a) a impulseIntegral2' a = switch ((integral >>> arr (^+^ a)) *** notYet >>> arr (\(a, ea) -> (a, fmap (^+^ a) ea))) impulseIntegral2' switch_t5 :: [Double] switch_t5 = take 50 $ embed impulseIntegral2 (deltaEncode 0.1 (zip (repeat 1.0) evSeq)) where evSeq = replicate 9 NoEvent ++ [Event 10.0] ++ replicate 9 NoEvent ++ [Event (-10.0)] ++ evSeq switch_t5r = [ 0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 10.9, 11.0, 11.1, 11.2, 11.3, 11.4, 11.5, 11.6, 11.7, 11.8, 1.9, 2.0, 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 2.8, 12.9, 13.0, 13.1, 13.2, 13.3, 13.4, 13.5, 13.6, 13.7, 13.8, 3.9, 4.0, 4.1, 4.2, 4.3, 4.4, 4.5, 4.6, 4.7, 4.8, 14.9] switch_trs = [ switch_t0 ~= switch_t0r, switch_t1 ~= switch_t1r, switch_t2 ~= switch_t2r, switch_t3 ~= switch_t3r, switch_t4 ~= switch_t4r, switch_t5 ~= switch_t5r ] switch_tr = and switch_trs
meimisaki/Yampa
tests/AFRPTestsSwitch.hs
Haskell
bsd-3-clause
7,509
------------------------------------------------------------------------- -- -- QCStoreTest.hs -- -- QuickCheck tests for stores. -- -- (c) Addison-Wesley, 1996-2011. -- ------------------------------------------------------------------------- module QCStoreTest where import StoreTest import Test.QuickCheck prop_Update1 :: Char -> Integer -> Store -> Bool prop_Update1 ch int st = value (update st ch int) ch == int prop_Update2 :: Char -> Char -> Integer -> Store -> Bool prop_Update2 ch1 ch2 int st = ch1 == ch2 || value (update st ch2 int) ch1 == value st ch1 prop_Initial :: Char -> Bool prop_Initial ch = value initial ch == 0
c089/haskell-craft3e
Chapter16/QCStoreTest.hs
Haskell
mit
707
{-# LANGUAGE PatternGuards, CPP, ForeignFunctionInterface #-} ----------------------------------------------------------------------------- -- -- (c) The University of Glasgow 2004-2009. -- -- Package management tool -- ----------------------------------------------------------------------------- module HastePkg708 (main) where import Distribution.InstalledPackageInfo.Binary() import qualified Distribution.Simple.PackageIndex as PackageIndex import Distribution.ModuleName hiding (main) import Distribution.InstalledPackageInfo import Distribution.Compat.ReadP import Distribution.ParseUtils import Distribution.Package hiding (depends) import Distribution.Text import Distribution.Version import System.FilePath as FilePath import qualified System.FilePath.Posix as FilePath.Posix import System.Process import System.Directory ( getAppUserDataDirectory, createDirectoryIfMissing, getModificationTime ) import Text.Printf import Prelude import System.Console.GetOpt import qualified Control.Exception as Exception import Data.Maybe import Data.Char ( isSpace, toLower ) import Data.Ord (comparing) import Control.Applicative (Applicative(..)) import Control.Monad import System.Directory ( doesDirectoryExist, getDirectoryContents, doesFileExist, renameFile, removeFile, getCurrentDirectory ) import System.Exit ( exitWith, ExitCode(..) ) import System.Environment ( getArgs, getProgName, getEnv ) import System.IO import System.IO.Error import Data.List import Control.Concurrent import qualified Data.ByteString.Lazy as B import qualified Data.Binary as Bin import qualified Data.Binary.Get as Bin -- Haste-specific import Haste.Environment import Haste.Version import System.Info (os) import qualified Control.Shell as Sh #if defined(mingw32_HOST_OS) -- mingw32 needs these for getExecDir import Foreign import Foreign.C #endif #ifdef mingw32_HOST_OS import GHC.ConsoleHandler #else import System.Posix hiding (fdToHandle) #endif #if defined(GLOB) import qualified System.Info(os) #endif #if !defined(mingw32_HOST_OS) && !defined(BOOTSTRAPPING) import System.Console.Terminfo as Terminfo #endif #ifdef mingw32_HOST_OS # if defined(i386_HOST_ARCH) # define WINDOWS_CCONV stdcall # elif defined(x86_64_HOST_ARCH) # define WINDOWS_CCONV ccall # else # error Unknown mingw32 arch # endif #endif -- ----------------------------------------------------------------------------- -- Entry point main :: IO () main = do args <- getArgs case args of ["relocate", pkg] -> do Sh.shell (relocate packages pkg) >> exitWith ExitSuccess _ -> return () case getOpt Permute (flags ++ deprecFlags) args of (cli,_,[]) | FlagHelp `elem` cli -> do prog <- getProgramName bye (usageInfo (usageHeader prog) flags) (cli,_,[]) | FlagVersion `elem` cli -> bye ourCopyright (cli,_,[]) | FlagNumericVersion `elem` cli -> bye $ showVersion hasteVersion ++ "\n" (cli,_,[]) | FlagNumericGhcVersion `elem` cli -> bye $ showVersion ghcVersion ++ "\n" (cli,nonopts,[]) -> case getVerbosity Normal cli of Right v -> runit v cli nonopts Left err -> die err (_,_,errors) -> do prog <- getProgramName die (concat errors ++ shortUsage prog) where packages = ["--global-package-db=" ++ pkgSysDir, "--package-db=" ++ pkgSysDir, "--package-db=" ++ pkgUserDir] -- ----------------------------------------------------------------------------- -- Command-line syntax data Flag = FlagUser | FlagGlobal | FlagHelp | FlagVersion | FlagNumericVersion | FlagNumericGhcVersion | FlagConfig FilePath | FlagGlobalConfig FilePath | FlagForce | FlagForceFiles | FlagAutoGHCiLibs | FlagExpandEnvVars | FlagExpandPkgroot | FlagNoExpandPkgroot | FlagSimpleOutput | FlagNamesOnly | FlagIgnoreCase | FlagNoUserDb | FlagVerbosity (Maybe String) deriving Eq flags :: [OptDescr Flag] flags = [ Option [] ["user"] (NoArg FlagUser) "use the current user's package database", Option [] ["global"] (NoArg FlagGlobal) "use the global package database", Option ['f'] ["package-db"] (ReqArg FlagConfig "FILE/DIR") "use the specified package database", Option [] ["package-conf"] (ReqArg FlagConfig "FILE/DIR") "use the specified package database (DEPRECATED)", Option [] ["global-package-db"] (ReqArg FlagGlobalConfig "DIR") "location of the global package database", Option [] ["no-user-package-db"] (NoArg FlagNoUserDb) "never read the user package database", Option [] ["no-user-package-conf"] (NoArg FlagNoUserDb) "never read the user package database (DEPRECATED)", Option [] ["force"] (NoArg FlagForce) "ignore missing dependencies, directories, and libraries", Option [] ["force-files"] (NoArg FlagForceFiles) "ignore missing directories and libraries only", Option ['g'] ["auto-ghci-libs"] (NoArg FlagAutoGHCiLibs) "automatically build libs for GHCi (with register)", Option [] ["expand-env-vars"] (NoArg FlagExpandEnvVars) "expand environment variables (${name}-style) in input package descriptions", Option [] ["expand-pkgroot"] (NoArg FlagExpandPkgroot) "expand ${pkgroot}-relative paths to absolute in output package descriptions", Option [] ["no-expand-pkgroot"] (NoArg FlagNoExpandPkgroot) "preserve ${pkgroot}-relative paths in output package descriptions", Option ['?'] ["help"] (NoArg FlagHelp) "display this help and exit", Option ['V'] ["version"] (NoArg FlagVersion) "output version information and exit", Option [] ["numeric-version"] (NoArg FlagNumericVersion) "output version number and exit", Option [] ["numeric-ghc-version"] (NoArg FlagNumericGhcVersion) "output GHC version number and exit", Option [] ["simple-output"] (NoArg FlagSimpleOutput) "print output in easy-to-parse format for some commands", Option [] ["names-only"] (NoArg FlagNamesOnly) "only print package names, not versions; can only be used with list --simple-output", Option [] ["ignore-case"] (NoArg FlagIgnoreCase) "ignore case for substring matching", Option ['v'] ["verbose"] (OptArg FlagVerbosity "Verbosity") "verbosity level (0-2, default 1)" ] data Verbosity = Silent | Normal | Verbose deriving (Show, Eq, Ord) getVerbosity :: Verbosity -> [Flag] -> Either String Verbosity getVerbosity v [] = Right v getVerbosity _ (FlagVerbosity Nothing : fs) = getVerbosity Verbose fs getVerbosity _ (FlagVerbosity (Just "0") : fs) = getVerbosity Silent fs getVerbosity _ (FlagVerbosity (Just "1") : fs) = getVerbosity Normal fs getVerbosity _ (FlagVerbosity (Just "2") : fs) = getVerbosity Verbose fs getVerbosity _ (FlagVerbosity v : _) = Left ("Bad verbosity: " ++ show v) getVerbosity v (_ : fs) = getVerbosity v fs deprecFlags :: [OptDescr Flag] deprecFlags = [ -- put deprecated flags here ] ourCopyright :: String ourCopyright = "Haste package manager version " ++ showVersion hasteVersion ++ "\n" shortUsage :: String -> String shortUsage prog = "For usage information see '" ++ prog ++ " --help'." usageHeader :: String -> String usageHeader prog = substProg prog $ "Usage:\n" ++ " $p init {path}\n" ++ " Create and initialise a package database at the location {path}.\n" ++ " Packages can be registered in the new database using the register\n" ++ " command with --package-db={path}. To use the new database with GHC,\n" ++ " use GHC's -package-db flag.\n" ++ "\n" ++ " $p register {filename | -}\n" ++ " Register the package using the specified installed package\n" ++ " description. The syntax for the latter is given in the $p\n" ++ " documentation. The input file should be encoded in UTF-8.\n" ++ "\n" ++ " $p update {filename | -}\n" ++ " Register the package, overwriting any other package with the\n" ++ " same name. The input file should be encoded in UTF-8.\n" ++ "\n" ++ " $p unregister {pkg-id}\n" ++ " Unregister the specified package.\n" ++ "\n" ++ " $p expose {pkg-id}\n" ++ " Expose the specified package.\n" ++ "\n" ++ " $p hide {pkg-id}\n" ++ " Hide the specified package.\n" ++ "\n" ++ " $p trust {pkg-id}\n" ++ " Trust the specified package.\n" ++ "\n" ++ " $p distrust {pkg-id}\n" ++ " Distrust the specified package.\n" ++ "\n" ++ " $p list [pkg]\n" ++ " List registered packages in the global database, and also the\n" ++ " user database if --user is given. If a package name is given\n" ++ " all the registered versions will be listed in ascending order.\n" ++ " Accepts the --simple-output flag.\n" ++ "\n" ++ " $p dot\n" ++ " Generate a graph of the package dependencies in a form suitable\n" ++ " for input for the graphviz tools. For example, to generate a PDF" ++ " of the dependency graph: ghc-pkg dot | tred | dot -Tpdf >pkgs.pdf" ++ "\n" ++ " $p find-module {module}\n" ++ " List registered packages exposing module {module} in the global\n" ++ " database, and also the user database if --user is given.\n" ++ " All the registered versions will be listed in ascending order.\n" ++ " Accepts the --simple-output flag.\n" ++ "\n" ++ " $p latest {pkg-id}\n" ++ " Prints the highest registered version of a package.\n" ++ "\n" ++ " $p check\n" ++ " Check the consistency of package dependencies and list broken packages.\n" ++ " Accepts the --simple-output flag.\n" ++ "\n" ++ " $p describe {pkg}\n" ++ " Give the registered description for the specified package. The\n" ++ " description is returned in precisely the syntax required by $p\n" ++ " register.\n" ++ "\n" ++ " $p field {pkg} {field}\n" ++ " Extract the specified field of the package description for the\n" ++ " specified package. Accepts comma-separated multiple fields.\n" ++ "\n" ++ " $p dump\n" ++ " Dump the registered description for every package. This is like\n" ++ " \"ghc-pkg describe '*'\", except that it is intended to be used\n" ++ " by tools that parse the results, rather than humans. The output is\n" ++ " always encoded in UTF-8, regardless of the current locale.\n" ++ "\n" ++ " $p recache\n" ++ " Regenerate the package database cache. This command should only be\n" ++ " necessary if you added a package to the database by dropping a file\n" ++ " into the database directory manually. By default, the global DB\n" ++ " is recached; to recache a different DB use --user or --package-db\n" ++ " as appropriate.\n" ++ "\n" ++ " Substring matching is supported for {module} in find-module and\n" ++ " for {pkg} in list, describe, and field, where a '*' indicates\n" ++ " open substring ends (prefix*, *suffix, *infix*).\n" ++ "\n" ++ " When asked to modify a database (register, unregister, update,\n"++ " hide, expose, and also check), ghc-pkg modifies the global database by\n"++ " default. Specifying --user causes it to act on the user database,\n"++ " or --package-db can be used to act on another database\n"++ " entirely. When multiple of these options are given, the rightmost\n"++ " one is used as the database to act upon.\n"++ "\n"++ " Commands that query the package database (list, tree, latest, describe,\n"++ " field) operate on the list of databases specified by the flags\n"++ " --user, --global, and --package-db. If none of these flags are\n"++ " given, the default is --global --user.\n"++ "\n" ++ " The following optional flags are also accepted:\n" substProg :: String -> String -> String substProg _ [] = [] substProg prog ('$':'p':xs) = prog ++ substProg prog xs substProg prog (c:xs) = c : substProg prog xs -- ----------------------------------------------------------------------------- -- Do the business data Force = NoForce | ForceFiles | ForceAll | CannotForce deriving (Eq,Ord) data PackageArg = Id PackageIdentifier | Substring String (String->Bool) runit :: Verbosity -> [Flag] -> [String] -> IO () runit verbosity cli nonopts = do installSignalHandlers -- catch ^C and clean up prog <- getProgramName let force | FlagForce `elem` cli = ForceAll | FlagForceFiles `elem` cli = ForceFiles | otherwise = NoForce auto_ghci_libs = FlagAutoGHCiLibs `elem` cli expand_env_vars= FlagExpandEnvVars `elem` cli mexpand_pkgroot= foldl' accumExpandPkgroot Nothing cli where accumExpandPkgroot _ FlagExpandPkgroot = Just True accumExpandPkgroot _ FlagNoExpandPkgroot = Just False accumExpandPkgroot x _ = x splitFields fields = unfoldr splitComma (',':fields) where splitComma "" = Nothing splitComma fs = Just $ break (==',') (tail fs) substringCheck :: String -> Maybe (String -> Bool) substringCheck "" = Nothing substringCheck "*" = Just (const True) substringCheck [_] = Nothing substringCheck (h:t) = case (h, init t, last t) of ('*',s,'*') -> Just (isInfixOf (f s) . f) ('*',_, _ ) -> Just (isSuffixOf (f t) . f) ( _ ,s,'*') -> Just (isPrefixOf (f (h:s)) . f) _ -> Nothing where f | FlagIgnoreCase `elem` cli = map toLower | otherwise = id #if defined(GLOB) glob x | System.Info.os=="mingw32" = do -- glob echoes its argument, after win32 filename globbing (_,o,_,_) <- runInteractiveCommand ("glob "++x) txt <- hGetContents o return (read txt) glob x | otherwise = return [x] #endif -- -- first, parse the command case nonopts of #if defined(GLOB) -- dummy command to demonstrate usage and permit testing -- without messing things up; use glob to selectively enable -- windows filename globbing for file parameters -- register, update, FlagGlobalConfig, FlagConfig; others? ["glob", filename] -> do print filename glob filename >>= print #endif ["init", filename] -> initPackageDB filename verbosity cli ["register", filename] -> registerPackage filename verbosity cli auto_ghci_libs expand_env_vars False force ["update", filename] -> registerPackage filename verbosity cli auto_ghci_libs expand_env_vars True force ["unregister", pkgid_str] -> do pkgid <- readGlobPkgId pkgid_str unregisterPackage pkgid verbosity cli force ["expose", pkgid_str] -> do pkgid <- readGlobPkgId pkgid_str exposePackage pkgid verbosity cli force ["hide", pkgid_str] -> do pkgid <- readGlobPkgId pkgid_str hidePackage pkgid verbosity cli force ["trust", pkgid_str] -> do pkgid <- readGlobPkgId pkgid_str trustPackage pkgid verbosity cli force ["distrust", pkgid_str] -> do pkgid <- readGlobPkgId pkgid_str distrustPackage pkgid verbosity cli force ["list"] -> do listPackages verbosity cli Nothing Nothing ["list", pkgid_str] -> case substringCheck pkgid_str of Nothing -> do pkgid <- readGlobPkgId pkgid_str listPackages verbosity cli (Just (Id pkgid)) Nothing Just m -> listPackages verbosity cli (Just (Substring pkgid_str m)) Nothing ["dot"] -> do showPackageDot verbosity cli ["find-module", moduleName] -> do let match = maybe (==moduleName) id (substringCheck moduleName) listPackages verbosity cli Nothing (Just match) ["latest", pkgid_str] -> do pkgid <- readGlobPkgId pkgid_str latestPackage verbosity cli pkgid ["describe", pkgid_str] -> do pkgarg <- case substringCheck pkgid_str of Nothing -> liftM Id (readGlobPkgId pkgid_str) Just m -> return (Substring pkgid_str m) describePackage verbosity cli pkgarg (fromMaybe False mexpand_pkgroot) ["field", pkgid_str, fields] -> do pkgarg <- case substringCheck pkgid_str of Nothing -> liftM Id (readGlobPkgId pkgid_str) Just m -> return (Substring pkgid_str m) describeField verbosity cli pkgarg (splitFields fields) (fromMaybe True mexpand_pkgroot) ["check"] -> do checkConsistency verbosity cli ["dump"] -> do dumpPackages verbosity cli (fromMaybe False mexpand_pkgroot) ["recache"] -> do recache verbosity cli [] -> do die ("missing command\n" ++ shortUsage prog) (_cmd:_) -> do die ("command-line syntax error\n" ++ shortUsage prog) parseCheck :: ReadP a a -> String -> String -> IO a parseCheck parser str what = case [ x | (x,ys) <- readP_to_S parser str, all isSpace ys ] of [x] -> return x _ -> die ("cannot parse \'" ++ str ++ "\' as a " ++ what) readGlobPkgId :: String -> IO PackageIdentifier readGlobPkgId str = parseCheck parseGlobPackageId str "package identifier" parseGlobPackageId :: ReadP r PackageIdentifier parseGlobPackageId = parse +++ (do n <- parse _ <- string "-*" return (PackageIdentifier{ pkgName = n, pkgVersion = globVersion })) -- globVersion means "all versions" globVersion :: Version globVersion = Version{ versionBranch=[], versionTags=["*"] } -- ----------------------------------------------------------------------------- -- Package databases -- Some commands operate on a single database: -- register, unregister, expose, hide, trust, distrust -- however these commands also check the union of the available databases -- in order to check consistency. For example, register will check that -- dependencies exist before registering a package. -- -- Some commands operate on multiple databases, with overlapping semantics: -- list, describe, field data PackageDB = PackageDB { location, locationAbsolute :: !FilePath, -- We need both possibly-relative and definately-absolute package -- db locations. This is because the relative location is used as -- an identifier for the db, so it is important we do not modify it. -- On the other hand we need the absolute path in a few places -- particularly in relation to the ${pkgroot} stuff. packages :: [InstalledPackageInfo] } type PackageDBStack = [PackageDB] -- A stack of package databases. Convention: head is the topmost -- in the stack. allPackagesInStack :: PackageDBStack -> [InstalledPackageInfo] allPackagesInStack = concatMap packages getPkgDatabases :: Verbosity -> Bool -- we are modifying, not reading -> Bool -- read caches, if available -> Bool -- expand vars, like ${pkgroot} and $topdir -> [Flag] -> IO (PackageDBStack, -- the real package DB stack: [global,user] ++ -- DBs specified on the command line with -f. Maybe FilePath, -- which one to modify, if any PackageDBStack) -- the package DBs specified on the command -- line, or [global,user] otherwise. This -- is used as the list of package DBs for -- commands that just read the DB, such as 'list'. getPkgDatabases verbosity modify use_cache expand_vars my_flags = do -- first we determine the location of the global package config. On Windows, -- this is found relative to the ghc-pkg.exe binary, whereas on Unix the -- location is passed to the binary using the --global-package-db flag by the -- wrapper script. let err_msg = "missing --global-package-db option, location of global package database unknown\n" global_conf <- case [ f | FlagGlobalConfig f <- my_flags ] of [] -> do mb_dir <- getLibDir case mb_dir of Nothing -> die err_msg Just dir -> do r <- lookForPackageDBIn dir case r of Nothing -> die ("Can't find package database in " ++ dir) Just path -> return path fs -> return (last fs) -- The value of the $topdir variable used in some package descriptions -- Note that the way we calculate this is slightly different to how it -- is done in ghc itself. We rely on the convention that the global -- package db lives in ghc's libdir. top_dir <- absolutePath (takeDirectory global_conf) let no_user_db = FlagNoUserDb `elem` my_flags mb_user_conf <- if no_user_db then return Nothing else do r <- lookForPackageDBIn hasteUserDir case r of Nothing -> return (Just (pkgUserDir, False)) Just f -> return (Just (f, True)) -- If the user database doesn't exist, and this command isn't a -- "modify" command, then we won't attempt to create or use it. let sys_databases | Just (user_conf,user_exists) <- mb_user_conf, modify || user_exists = [user_conf, global_conf] | otherwise = [global_conf] e_pkg_path <- tryIO (System.Environment.getEnv "HASTE_PACKAGE_PATH") let env_stack = case e_pkg_path of Left _ -> sys_databases Right path | last cs == "" -> init cs ++ sys_databases | otherwise -> cs where cs = parseSearchPath path -- The "global" database is always the one at the bottom of the stack. -- This is the database we modify by default. virt_global_conf = last env_stack let db_flags = [ f | Just f <- map is_db_flag my_flags ] where is_db_flag FlagUser | Just (user_conf, _user_exists) <- mb_user_conf = Just user_conf is_db_flag FlagGlobal = Just virt_global_conf is_db_flag (FlagConfig f) = Just f is_db_flag _ = Nothing let flag_db_names | null db_flags = env_stack | otherwise = reverse (nub db_flags) -- For a "modify" command, treat all the databases as -- a stack, where we are modifying the top one, but it -- can refer to packages in databases further down the -- stack. -- -f flags on the command line add to the database -- stack, unless any of them are present in the stack -- already. let final_stack = filter (`notElem` env_stack) [ f | FlagConfig f <- reverse my_flags ] ++ env_stack -- the database we actually modify is the one mentioned -- rightmost on the command-line. let to_modify | not modify = Nothing | null db_flags = Just virt_global_conf | otherwise = Just (last db_flags) db_stack <- sequence [ do db <- readParseDatabase verbosity mb_user_conf use_cache db_path if expand_vars then return (mungePackageDBPaths top_dir db) else return db | db_path <- final_stack ] let flag_db_stack = [ db | db_name <- flag_db_names, db <- db_stack, location db == db_name ] return (db_stack, to_modify, flag_db_stack) lookForPackageDBIn :: FilePath -> IO (Maybe FilePath) lookForPackageDBIn dir = do let path_dir = dir </> "package.conf.d" exists_dir <- doesDirectoryExist path_dir if exists_dir then return (Just path_dir) else do let path_file = dir </> "package.conf" exists_file <- doesFileExist path_file if exists_file then return (Just path_file) else return Nothing readParseDatabase :: Verbosity -> Maybe (FilePath,Bool) -> Bool -- use cache -> FilePath -> IO PackageDB readParseDatabase verbosity mb_user_conf use_cache path -- the user database (only) is allowed to be non-existent | Just (user_conf,False) <- mb_user_conf, path == user_conf = mkPackageDB [] | otherwise = do e <- tryIO $ getDirectoryContents path case e of Left _ -> do pkgs <- parseMultiPackageConf verbosity path mkPackageDB pkgs Right fs | not use_cache -> ignore_cache (const $ return ()) | otherwise -> do let cache = path </> cachefilename tdir <- getModificationTime path e_tcache <- tryIO $ getModificationTime cache case e_tcache of Left ex -> do when (verbosity > Normal) $ warn ("warning: cannot read cache file " ++ cache ++ ": " ++ show ex) ignore_cache (const $ return ()) Right tcache -> do let compareTimestampToCache file = when (verbosity >= Verbose) $ do tFile <- getModificationTime file compareTimestampToCache' file tFile compareTimestampToCache' file tFile = do let rel = case tcache `compare` tFile of LT -> " (NEWER than cache)" GT -> " (older than cache)" EQ -> " (same as cache)" warn ("Timestamp " ++ show tFile ++ " for " ++ file ++ rel) when (verbosity >= Verbose) $ do warn ("Timestamp " ++ show tcache ++ " for " ++ cache) compareTimestampToCache' path tdir if tcache >= tdir then do when (verbosity > Normal) $ infoLn ("using cache: " ++ cache) pkgs <- myReadBinPackageDB cache let pkgs' = map convertPackageInfoIn pkgs mkPackageDB pkgs' else do when (verbosity >= Normal) $ do warn ("WARNING: cache is out of date: " ++ cache) warn "Use 'ghc-pkg recache' to fix." ignore_cache compareTimestampToCache where ignore_cache :: (FilePath -> IO ()) -> IO PackageDB ignore_cache checkTime = do let confs = filter (".conf" `isSuffixOf`) fs doFile f = do checkTime f parseSingletonPackageConf verbosity f pkgs <- mapM doFile $ map (path </>) confs mkPackageDB pkgs where mkPackageDB pkgs = do path_abs <- absolutePath path return PackageDB { location = path, locationAbsolute = path_abs, packages = pkgs } -- read the package.cache file strictly, to work around a problem with -- bytestring 0.9.0.x (fixed in 0.9.1.x) where the file wasn't closed -- after it has been completely read, leading to a sharing violation -- later. myReadBinPackageDB :: FilePath -> IO [InstalledPackageInfoString] myReadBinPackageDB filepath = do h <- openBinaryFile filepath ReadMode sz <- hFileSize h b <- B.hGet h (fromIntegral sz) hClose h return $ Bin.runGet Bin.get b parseMultiPackageConf :: Verbosity -> FilePath -> IO [InstalledPackageInfo] parseMultiPackageConf verbosity file = do when (verbosity > Normal) $ infoLn ("reading package database: " ++ file) str <- readUTF8File file let pkgs = map convertPackageInfoIn $ read str Exception.evaluate pkgs `catchError` \e-> die ("error while parsing " ++ file ++ ": " ++ show e) parseSingletonPackageConf :: Verbosity -> FilePath -> IO InstalledPackageInfo parseSingletonPackageConf verbosity file = do when (verbosity > Normal) $ infoLn ("reading package config: " ++ file) readUTF8File file >>= fmap fst . parsePackageInfo cachefilename :: FilePath cachefilename = "package.cache" mungePackageDBPaths :: FilePath -> PackageDB -> PackageDB mungePackageDBPaths top_dir db@PackageDB { packages = pkgs } = db { packages = map (mungePackagePaths top_dir pkgroot) pkgs } where pkgroot = takeDirectory (locationAbsolute db) -- It so happens that for both styles of package db ("package.conf" -- files and "package.conf.d" dirs) the pkgroot is the parent directory -- ${pkgroot}/package.conf or ${pkgroot}/package.conf.d/ -- TODO: This code is duplicated in compiler/main/Packages.lhs mungePackagePaths :: FilePath -> FilePath -> InstalledPackageInfo -> InstalledPackageInfo -- Perform path/URL variable substitution as per the Cabal ${pkgroot} spec -- (http://www.haskell.org/pipermail/libraries/2009-May/011772.html) -- Paths/URLs can be relative to ${pkgroot} or ${pkgrooturl}. -- The "pkgroot" is the directory containing the package database. -- -- Also perform a similar substitution for the older GHC-specific -- "$topdir" variable. The "topdir" is the location of the ghc -- installation (obtained from the -B option). mungePackagePaths top_dir pkgroot pkg = pkg { importDirs = munge_paths (importDirs pkg), includeDirs = munge_paths (includeDirs pkg), libraryDirs = munge_paths (libraryDirs pkg), frameworkDirs = munge_paths (frameworkDirs pkg), haddockInterfaces = munge_paths (haddockInterfaces pkg), -- haddock-html is allowed to be either a URL or a file haddockHTMLs = munge_paths (munge_urls (haddockHTMLs pkg)) } where munge_paths = map munge_path munge_urls = map munge_url munge_path p | Just p' <- stripVarPrefix "${pkgroot}" p = pkgroot ++ p' | Just p' <- stripVarPrefix "$topdir" p = top_dir ++ p' | otherwise = p munge_url p | Just p' <- stripVarPrefix "${pkgrooturl}" p = toUrlPath pkgroot p' | Just p' <- stripVarPrefix "$httptopdir" p = toUrlPath top_dir p' | otherwise = p toUrlPath r p = "file:///" -- URLs always use posix style '/' separators: ++ FilePath.Posix.joinPath (r : -- We need to drop a leading "/" or "\\" -- if there is one: dropWhile (all isPathSeparator) (FilePath.splitDirectories p)) -- We could drop the separator here, and then use </> above. However, -- by leaving it in and using ++ we keep the same path separator -- rather than letting FilePath change it to use \ as the separator stripVarPrefix var path = case stripPrefix var path of Just [] -> Just [] Just cs@(c : _) | isPathSeparator c -> Just cs _ -> Nothing -- ----------------------------------------------------------------------------- -- Creating a new package DB initPackageDB :: FilePath -> Verbosity -> [Flag] -> IO () initPackageDB filename verbosity _flags = do let eexist = die ("cannot create: " ++ filename ++ " already exists") b1 <- doesFileExist filename when b1 eexist b2 <- doesDirectoryExist filename when b2 eexist filename_abs <- absolutePath filename changeDB verbosity [] PackageDB { location = filename, locationAbsolute = filename_abs, packages = [] } -- ----------------------------------------------------------------------------- -- Registering registerPackage :: FilePath -> Verbosity -> [Flag] -> Bool -- auto_ghci_libs -> Bool -- expand_env_vars -> Bool -- update -> Force -> IO () registerPackage input verbosity my_flags auto_ghci_libs expand_env_vars update force = do (db_stack, Just to_modify, _flag_dbs) <- getPkgDatabases verbosity True True False{-expand vars-} my_flags let db_to_operate_on = my_head "register" $ filter ((== to_modify).location) db_stack -- when (auto_ghci_libs && verbosity >= Silent) $ warn "Warning: --auto-ghci-libs is deprecated and will be removed in GHC 7.4" -- s <- case input of "-" -> do when (verbosity >= Normal) $ info "Reading package info from stdin ... " -- fix the encoding to UTF-8, since this is an interchange format hSetEncoding stdin utf8 getContents f -> do when (verbosity >= Normal) $ info ("Reading package info from " ++ show f ++ " ... ") readUTF8File f expanded <- if expand_env_vars then expandEnvVars s force else return s (pkg, ws) <- parsePackageInfo expanded when (verbosity >= Normal) $ infoLn "done." -- report any warnings from the parse phase _ <- reportValidateErrors [] ws (display (sourcePackageId pkg) ++ ": Warning: ") Nothing -- validate the expanded pkg, but register the unexpanded pkgroot <- absolutePath (takeDirectory to_modify) let top_dir = takeDirectory (location (last db_stack)) pkg_expanded = mungePackagePaths top_dir pkgroot pkg let truncated_stack = dropWhile ((/= to_modify).location) db_stack -- truncate the stack for validation, because we don't allow -- packages lower in the stack to refer to those higher up. validatePackageConfig pkg_expanded verbosity truncated_stack auto_ghci_libs update force let removes = [ RemovePackage p | p <- packages db_to_operate_on, sourcePackageId p == sourcePackageId pkg ] -- changeDB verbosity (removes ++ [AddPackage pkg]) db_to_operate_on parsePackageInfo :: String -> IO (InstalledPackageInfo, [ValidateWarning]) parsePackageInfo str = case parseInstalledPackageInfo str of ParseOk warnings ok -> return (ok, ws) where ws = [ msg | PWarning msg <- warnings , not ("Unrecognized field pkgroot" `isPrefixOf` msg) ] ParseFailed err -> case locatedErrorMsg err of (Nothing, s) -> die s (Just l, s) -> die (show l ++ ": " ++ s) -- ----------------------------------------------------------------------------- -- Making changes to a package database data DBOp = RemovePackage InstalledPackageInfo | AddPackage InstalledPackageInfo | ModifyPackage InstalledPackageInfo changeDB :: Verbosity -> [DBOp] -> PackageDB -> IO () changeDB verbosity cmds db = do let db' = updateInternalDB db cmds isfile <- doesFileExist (location db) if isfile then writeNewConfig verbosity (location db') (packages db') else do createDirectoryIfMissing True (location db) changeDBDir verbosity cmds db' updateInternalDB :: PackageDB -> [DBOp] -> PackageDB updateInternalDB db cmds = db{ packages = foldl do_cmd (packages db) cmds } where do_cmd pkgs (RemovePackage p) = filter ((/= installedPackageId p) . installedPackageId) pkgs do_cmd pkgs (AddPackage p) = p : pkgs do_cmd pkgs (ModifyPackage p) = do_cmd (do_cmd pkgs (RemovePackage p)) (AddPackage p) changeDBDir :: Verbosity -> [DBOp] -> PackageDB -> IO () changeDBDir verbosity cmds db = do mapM_ do_cmd cmds updateDBCache verbosity db where do_cmd (RemovePackage p) = do let file = location db </> display (installedPackageId p) <.> "conf" when (verbosity > Normal) $ infoLn ("removing " ++ file) removeFileSafe file do_cmd (AddPackage p) = do let file = location db </> display (installedPackageId p) <.> "conf" when (verbosity > Normal) $ infoLn ("writing " ++ file) writeFileUtf8Atomic file (showInstalledPackageInfo p) do_cmd (ModifyPackage p) = do_cmd (AddPackage p) updateDBCache :: Verbosity -> PackageDB -> IO () updateDBCache verbosity db = do let filename = location db </> cachefilename when (verbosity > Normal) $ infoLn ("writing cache " ++ filename) writeBinaryFileAtomic filename (map convertPackageInfoOut (packages db)) `catchIO` \e -> if isPermissionError e then die (filename ++ ": you don't have permission to modify this file") else ioError e #ifndef mingw32_HOST_OS status <- getFileStatus filename setFileTimes (location db) (accessTime status) (modificationTime status) #endif -- ----------------------------------------------------------------------------- -- Exposing, Hiding, Trusting, Distrusting, Unregistering are all similar exposePackage :: PackageIdentifier -> Verbosity -> [Flag] -> Force -> IO () exposePackage = modifyPackage (\p -> ModifyPackage p{exposed=True}) hidePackage :: PackageIdentifier -> Verbosity -> [Flag] -> Force -> IO () hidePackage = modifyPackage (\p -> ModifyPackage p{exposed=False}) trustPackage :: PackageIdentifier -> Verbosity -> [Flag] -> Force -> IO () trustPackage = modifyPackage (\p -> ModifyPackage p{trusted=True}) distrustPackage :: PackageIdentifier -> Verbosity -> [Flag] -> Force -> IO () distrustPackage = modifyPackage (\p -> ModifyPackage p{trusted=False}) unregisterPackage :: PackageIdentifier -> Verbosity -> [Flag] -> Force -> IO () unregisterPackage = modifyPackage RemovePackage modifyPackage :: (InstalledPackageInfo -> DBOp) -> PackageIdentifier -> Verbosity -> [Flag] -> Force -> IO () modifyPackage fn pkgid verbosity my_flags force = do (db_stack, Just _to_modify, _flag_dbs) <- getPkgDatabases verbosity True{-modify-} True{-use cache-} False{-expand vars-} my_flags (db, ps) <- fmap head $ findPackagesByDB db_stack (Id pkgid) let db_name = location db pkgs = packages db pids = map sourcePackageId ps cmds = [ fn pkg | pkg <- pkgs, sourcePackageId pkg `elem` pids ] new_db = updateInternalDB db cmds old_broken = brokenPackages (allPackagesInStack db_stack) rest_of_stack = filter ((/= db_name) . location) db_stack new_stack = new_db : rest_of_stack new_broken = map sourcePackageId (brokenPackages (allPackagesInStack new_stack)) newly_broken = filter (`notElem` map sourcePackageId old_broken) new_broken -- when (not (null newly_broken)) $ dieOrForceAll force ("unregistering " ++ display pkgid ++ " would break the following packages: " ++ unwords (map display newly_broken)) changeDB verbosity cmds db recache :: Verbosity -> [Flag] -> IO () recache verbosity my_flags = do (db_stack, Just to_modify, _flag_dbs) <- getPkgDatabases verbosity True{-modify-} False{-no cache-} False{-expand vars-} my_flags let db_to_operate_on = my_head "recache" $ filter ((== to_modify).location) db_stack -- changeDB verbosity [] db_to_operate_on -- ----------------------------------------------------------------------------- -- Listing packages listPackages :: Verbosity -> [Flag] -> Maybe PackageArg -> Maybe (String->Bool) -> IO () listPackages verbosity my_flags mPackageName mModuleName = do let simple_output = FlagSimpleOutput `elem` my_flags (db_stack, _, flag_db_stack) <- getPkgDatabases verbosity False True{-use cache-} False{-expand vars-} my_flags let db_stack_filtered -- if a package is given, filter out all other packages | Just this <- mPackageName = [ db{ packages = filter (this `matchesPkg`) (packages db) } | db <- flag_db_stack ] | Just match <- mModuleName = -- packages which expose mModuleName [ db{ packages = filter (match `exposedInPkg`) (packages db) } | db <- flag_db_stack ] | otherwise = flag_db_stack db_stack_sorted = [ db{ packages = sort_pkgs (packages db) } | db <- db_stack_filtered ] where sort_pkgs = sortBy cmpPkgIds cmpPkgIds pkg1 pkg2 = case pkgName p1 `compare` pkgName p2 of LT -> LT GT -> GT EQ -> pkgVersion p1 `compare` pkgVersion p2 where (p1,p2) = (sourcePackageId pkg1, sourcePackageId pkg2) stack = reverse db_stack_sorted match `exposedInPkg` pkg = any match (map display $ exposedModules pkg) pkg_map = allPackagesInStack db_stack broken = map sourcePackageId (brokenPackages pkg_map) show_normal PackageDB{ location = db_name, packages = pkg_confs } = do hPutStrLn stdout (db_name ++ ":") if null pp_pkgs then hPutStrLn stdout " (no packages)" else hPutStrLn stdout $ unlines (map (" " ++) pp_pkgs) where -- Sort using instance Ord PackageId pp_pkgs = map pp_pkg . sortBy (comparing installedPackageId) $ pkg_confs pp_pkg p | sourcePackageId p `elem` broken = printf "{%s}" doc | exposed p = doc | otherwise = printf "(%s)" doc where doc | verbosity >= Verbose = printf "%s (%s)" pkg ipid | otherwise = pkg where InstalledPackageId ipid = installedPackageId p pkg = display (sourcePackageId p) show_simple = simplePackageList my_flags . allPackagesInStack when (not (null broken) && not simple_output && verbosity /= Silent) $ do prog <- getProgramName warn ("WARNING: there are broken packages. Run '" ++ prog ++ " check' for more details.") if simple_output then show_simple stack else do #if defined(mingw32_HOST_OS) || defined(BOOTSTRAPPING) mapM_ show_normal stack #else let show_colour withF db = mconcat $ map (<#> termText "\n") $ (termText (location db) : map (termText " " <#>) (map pp_pkg (packages db))) where pp_pkg p | sourcePackageId p `elem` broken = withF Red doc | exposed p = doc | otherwise = withF Blue doc where doc | verbosity >= Verbose = termText (printf "%s (%s)" pkg ipid) | otherwise = termText pkg where InstalledPackageId ipid = installedPackageId p pkg = display (sourcePackageId p) is_tty <- hIsTerminalDevice stdout if not is_tty then mapM_ show_normal stack else do tty <- Terminfo.setupTermFromEnv case Terminfo.getCapability tty withForegroundColor of Nothing -> mapM_ show_normal stack Just w -> runTermOutput tty $ mconcat $ map (show_colour w) stack #endif simplePackageList :: [Flag] -> [InstalledPackageInfo] -> IO () simplePackageList my_flags pkgs = do let showPkg = if FlagNamesOnly `elem` my_flags then display . pkgName else display -- Sort using instance Ord PackageId strs = map showPkg $ sort $ map sourcePackageId pkgs when (not (null pkgs)) $ hPutStrLn stdout $ concat $ intersperse " " strs showPackageDot :: Verbosity -> [Flag] -> IO () showPackageDot verbosity myflags = do (_, _, flag_db_stack) <- getPkgDatabases verbosity False True{-use cache-} False{-expand vars-} myflags let all_pkgs = allPackagesInStack flag_db_stack ipix = PackageIndex.fromList all_pkgs putStrLn "digraph {" let quote s = '"':s ++ "\"" mapM_ putStrLn [ quote from ++ " -> " ++ quote to | p <- all_pkgs, let from = display (sourcePackageId p), depid <- depends p, Just dep <- [PackageIndex.lookupInstalledPackageId ipix depid], let to = display (sourcePackageId dep) ] putStrLn "}" -- ----------------------------------------------------------------------------- -- Prints the highest (hidden or exposed) version of a package latestPackage :: Verbosity -> [Flag] -> PackageIdentifier -> IO () latestPackage verbosity my_flags pkgid = do (_, _, flag_db_stack) <- getPkgDatabases verbosity False True{-use cache-} False{-expand vars-} my_flags ps <- findPackages flag_db_stack (Id pkgid) case ps of [] -> die "no matches" _ -> show_pkg . maximum . map sourcePackageId $ ps where show_pkg pid = hPutStrLn stdout (display pid) -- ----------------------------------------------------------------------------- -- Describe describePackage :: Verbosity -> [Flag] -> PackageArg -> Bool -> IO () describePackage verbosity my_flags pkgarg expand_pkgroot = do (_, _, flag_db_stack) <- getPkgDatabases verbosity False True{-use cache-} expand_pkgroot my_flags dbs <- findPackagesByDB flag_db_stack pkgarg doDump expand_pkgroot [ (pkg, locationAbsolute db) | (db, pkgs) <- dbs, pkg <- pkgs ] dumpPackages :: Verbosity -> [Flag] -> Bool -> IO () dumpPackages verbosity my_flags expand_pkgroot = do (_, _, flag_db_stack) <- getPkgDatabases verbosity False True{-use cache-} expand_pkgroot my_flags doDump expand_pkgroot [ (pkg, locationAbsolute db) | db <- flag_db_stack, pkg <- packages db ] doDump :: Bool -> [(InstalledPackageInfo, FilePath)] -> IO () doDump expand_pkgroot pkgs = do -- fix the encoding to UTF-8, since this is an interchange format hSetEncoding stdout utf8 putStrLn $ intercalate "---\n" [ if expand_pkgroot then showInstalledPackageInfo pkg else showInstalledPackageInfo pkg ++ pkgrootField | (pkg, pkgloc) <- pkgs , let pkgroot = takeDirectory pkgloc pkgrootField = "pkgroot: " ++ show pkgroot ++ "\n" ] -- PackageId is can have globVersion for the version findPackages :: PackageDBStack -> PackageArg -> IO [InstalledPackageInfo] findPackages db_stack pkgarg = fmap (concatMap snd) $ findPackagesByDB db_stack pkgarg findPackagesByDB :: PackageDBStack -> PackageArg -> IO [(PackageDB, [InstalledPackageInfo])] findPackagesByDB db_stack pkgarg = case [ (db, matched) | db <- db_stack, let matched = filter (pkgarg `matchesPkg`) (packages db), not (null matched) ] of [] -> die ("cannot find package " ++ pkg_msg pkgarg) ps -> return ps where pkg_msg (Id pkgid) = display pkgid pkg_msg (Substring pkgpat _) = "matching " ++ pkgpat matches :: PackageIdentifier -> PackageIdentifier -> Bool pid `matches` pid' = (pkgName pid == pkgName pid') && (pkgVersion pid == pkgVersion pid' || not (realVersion pid)) realVersion :: PackageIdentifier -> Bool realVersion pkgid = versionBranch (pkgVersion pkgid) /= [] -- when versionBranch == [], this is a glob matchesPkg :: PackageArg -> InstalledPackageInfo -> Bool (Id pid) `matchesPkg` pkg = pid `matches` sourcePackageId pkg (Substring _ m) `matchesPkg` pkg = m (display (sourcePackageId pkg)) -- ----------------------------------------------------------------------------- -- Field describeField :: Verbosity -> [Flag] -> PackageArg -> [String] -> Bool -> IO () describeField verbosity my_flags pkgarg fields expand_pkgroot = do (_, _, flag_db_stack) <- getPkgDatabases verbosity False True{-use cache-} expand_pkgroot my_flags fns <- mapM toField fields ps <- findPackages flag_db_stack pkgarg mapM_ (selectFields fns) ps where showFun = if FlagSimpleOutput `elem` my_flags then showSimpleInstalledPackageInfoField else showInstalledPackageInfoField toField f = case showFun f of Nothing -> die ("unknown field: " ++ f) Just fn -> return fn selectFields fns pinfo = mapM_ (\fn->putStrLn (fn pinfo)) fns -- ----------------------------------------------------------------------------- -- Check: Check consistency of installed packages checkConsistency :: Verbosity -> [Flag] -> IO () checkConsistency verbosity my_flags = do (db_stack, _, _) <- getPkgDatabases verbosity True True{-use cache-} True{-expand vars-} my_flags -- check behaves like modify for the purposes of deciding which -- databases to use, because ordering is important. let simple_output = FlagSimpleOutput `elem` my_flags let pkgs = allPackagesInStack db_stack checkPackage p = do (_,es,ws) <- runValidate $ checkPackageConfig p verbosity db_stack False True if null es then do when (not simple_output) $ do _ <- reportValidateErrors [] ws "" Nothing return () return [] else do when (not simple_output) $ do reportError ("There are problems in package " ++ display (sourcePackageId p) ++ ":") _ <- reportValidateErrors es ws " " Nothing return () return [p] broken_pkgs <- concat `fmap` mapM checkPackage pkgs let filterOut pkgs1 pkgs2 = filter not_in pkgs2 where not_in p = sourcePackageId p `notElem` all_ps all_ps = map sourcePackageId pkgs1 let not_broken_pkgs = filterOut broken_pkgs pkgs (_, trans_broken_pkgs) = closure [] not_broken_pkgs all_broken_pkgs = broken_pkgs ++ trans_broken_pkgs when (not (null all_broken_pkgs)) $ do if simple_output then simplePackageList my_flags all_broken_pkgs else do reportError ("\nThe following packages are broken, either because they have a problem\n"++ "listed above, or because they depend on a broken package.") mapM_ (hPutStrLn stderr . display . sourcePackageId) all_broken_pkgs when (not (null all_broken_pkgs)) $ exitWith (ExitFailure 1) closure :: [InstalledPackageInfo] -> [InstalledPackageInfo] -> ([InstalledPackageInfo], [InstalledPackageInfo]) closure pkgs db_stack = go pkgs db_stack where go avail not_avail = case partition (depsAvailable avail) not_avail of ([], not_avail') -> (avail, not_avail') (new_avail, not_avail') -> go (new_avail ++ avail) not_avail' depsAvailable :: [InstalledPackageInfo] -> InstalledPackageInfo -> Bool depsAvailable pkgs_ok pkg = null dangling where dangling = filter (`notElem` pids) (depends pkg) pids = map installedPackageId pkgs_ok -- we want mutually recursive groups of package to show up -- as broken. (#1750) brokenPackages :: [InstalledPackageInfo] -> [InstalledPackageInfo] brokenPackages pkgs = snd (closure [] pkgs) -- ----------------------------------------------------------------------------- -- Manipulating package.conf files type InstalledPackageInfoString = InstalledPackageInfo_ String convertPackageInfoOut :: InstalledPackageInfo -> InstalledPackageInfoString convertPackageInfoOut (pkgconf@(InstalledPackageInfo { exposedModules = e, hiddenModules = h })) = pkgconf{ exposedModules = map display e, hiddenModules = map display h } convertPackageInfoIn :: InstalledPackageInfoString -> InstalledPackageInfo convertPackageInfoIn (pkgconf@(InstalledPackageInfo { exposedModules = e, hiddenModules = h })) = pkgconf{ exposedModules = map convert e, hiddenModules = map convert h } where convert = fromJust . simpleParse writeNewConfig :: Verbosity -> FilePath -> [InstalledPackageInfo] -> IO () writeNewConfig verbosity filename ipis = do when (verbosity >= Normal) $ info "Writing new package config file... " createDirectoryIfMissing True $ takeDirectory filename let shown = concat $ intersperse ",\n " $ map (show . convertPackageInfoOut) ipis fileContents = "[" ++ shown ++ "\n]" writeFileUtf8Atomic filename fileContents `catchIO` \e -> if isPermissionError e then die (filename ++ ": you don't have permission to modify this file") else ioError e when (verbosity >= Normal) $ infoLn "done." ----------------------------------------------------------------------------- -- Sanity-check a new package config, and automatically build GHCi libs -- if requested. type ValidateError = (Force,String) type ValidateWarning = String newtype Validate a = V { runValidate :: IO (a, [ValidateError],[ValidateWarning]) } instance Functor Validate where fmap = liftM instance Applicative Validate where pure = return (<*>) = ap instance Monad Validate where return a = V $ return (a, [], []) m >>= k = V $ do (a, es, ws) <- runValidate m (b, es', ws') <- runValidate (k a) return (b,es++es',ws++ws') verror :: Force -> String -> Validate () verror f s = V (return ((),[(f,s)],[])) vwarn :: String -> Validate () vwarn s = V (return ((),[],["Warning: " ++ s])) liftIO :: IO a -> Validate a liftIO k = V (k >>= \a -> return (a,[],[])) -- returns False if we should die reportValidateErrors :: [ValidateError] -> [ValidateWarning] -> String -> Maybe Force -> IO Bool reportValidateErrors es ws prefix mb_force = do mapM_ (warn . (prefix++)) ws oks <- mapM report es return (and oks) where report (f,s) | Just force <- mb_force = if (force >= f) then do reportError (prefix ++ s ++ " (ignoring)") return True else if f < CannotForce then do reportError (prefix ++ s ++ " (use --force to override)") return False else do reportError err return False | otherwise = do reportError err return False where err = prefix ++ s validatePackageConfig :: InstalledPackageInfo -> Verbosity -> PackageDBStack -> Bool -- auto-ghc-libs -> Bool -- update, or check -> Force -> IO () validatePackageConfig pkg verbosity db_stack auto_ghci_libs update force = do (_,es,ws) <- runValidate $ checkPackageConfig pkg verbosity db_stack auto_ghci_libs update ok <- reportValidateErrors es ws (display (sourcePackageId pkg) ++ ": ") (Just force) when (not ok) $ exitWith (ExitFailure 1) checkPackageConfig :: InstalledPackageInfo -> Verbosity -> PackageDBStack -> Bool -- auto-ghc-libs -> Bool -- update, or check -> Validate () checkPackageConfig pkg verbosity db_stack auto_ghci_libs update = do checkInstalledPackageId pkg db_stack update checkPackageId pkg checkDuplicates db_stack pkg update mapM_ (checkDep db_stack) (depends pkg) checkDuplicateDepends (depends pkg) mapM_ (checkDir False "import-dirs") (importDirs pkg) mapM_ (checkDir True "library-dirs") (libraryDirs pkg) mapM_ (checkDir True "include-dirs") (includeDirs pkg) mapM_ (checkDir True "framework-dirs") (frameworkDirs pkg) mapM_ (checkFile True "haddock-interfaces") (haddockInterfaces pkg) mapM_ (checkDirURL True "haddock-html") (haddockHTMLs pkg) checkModules pkg -- TODO: move jsmod directory structure into single jslib file? -- mapM_ (checkHSLib verbosity (libraryDirs pkg) auto_ghci_libs) (hsLibraries pkg) -- ToDo: check these somehow? -- extra_libraries :: [String], -- c_includes :: [String], checkInstalledPackageId :: InstalledPackageInfo -> PackageDBStack -> Bool -> Validate () checkInstalledPackageId ipi db_stack update = do let ipid@(InstalledPackageId str) = installedPackageId ipi when (null str) $ verror CannotForce "missing id field" let dups = [ p | p <- allPackagesInStack db_stack, installedPackageId p == ipid ] when (not update && not (null dups)) $ verror CannotForce $ "package(s) with this id already exist: " ++ unwords (map (display.packageId) dups) -- When the package name and version are put together, sometimes we can -- end up with a package id that cannot be parsed. This will lead to -- difficulties when the user wants to refer to the package later, so -- we check that the package id can be parsed properly here. checkPackageId :: InstalledPackageInfo -> Validate () checkPackageId ipi = let str = display (sourcePackageId ipi) in case [ x :: PackageIdentifier | (x,ys) <- readP_to_S parse str, all isSpace ys ] of [_] -> return () [] -> verror CannotForce ("invalid package identifier: " ++ str) _ -> verror CannotForce ("ambiguous package identifier: " ++ str) checkDuplicates :: PackageDBStack -> InstalledPackageInfo -> Bool -> Validate () checkDuplicates db_stack pkg update = do let pkgid = sourcePackageId pkg pkgs = packages (head db_stack) -- -- Check whether this package id already exists in this DB -- when (not update && (pkgid `elem` map sourcePackageId pkgs)) $ verror CannotForce $ "package " ++ display pkgid ++ " is already installed" let uncasep = map toLower . display dups = filter ((== uncasep pkgid) . uncasep) (map sourcePackageId pkgs) when (not update && not (null dups)) $ verror ForceAll $ "Package names may be treated case-insensitively in the future.\n"++ "Package " ++ display pkgid ++ " overlaps with: " ++ unwords (map display dups) checkDir, checkFile, checkDirURL :: Bool -> String -> FilePath -> Validate () checkDir = checkPath False True checkFile = checkPath False False checkDirURL = checkPath True True checkPath :: Bool -> Bool -> Bool -> String -> FilePath -> Validate () checkPath url_ok is_dir warn_only thisfield d | url_ok && ("http://" `isPrefixOf` d || "https://" `isPrefixOf` d) = return () | url_ok , Just d' <- stripPrefix "file://" d = checkPath False is_dir warn_only thisfield d' -- Note: we don't check for $topdir/${pkgroot} here. We rely on these -- variables having been expanded already, see mungePackagePaths. | isRelative d = verror ForceFiles $ thisfield ++ ": " ++ d ++ " is a relative path which " ++ "makes no sense (as there is nothing for it to be " ++ "relative to). You can make paths relative to the " ++ "package database itself by using ${pkgroot}." -- relative paths don't make any sense; #4134 | otherwise = do there <- liftIO $ if is_dir then doesDirectoryExist d else doesFileExist d when (not there) $ let msg = thisfield ++ ": " ++ d ++ " doesn't exist or isn't a " ++ if is_dir then "directory" else "file" in if warn_only then vwarn msg else verror ForceFiles msg checkDep :: PackageDBStack -> InstalledPackageId -> Validate () checkDep db_stack pkgid | pkgid `elem` pkgids = return () | otherwise = verror ForceAll ("dependency \"" ++ display pkgid ++ "\" doesn't exist") where all_pkgs = allPackagesInStack db_stack pkgids = map installedPackageId all_pkgs checkDuplicateDepends :: [InstalledPackageId] -> Validate () checkDuplicateDepends deps | null dups = return () | otherwise = verror ForceAll ("package has duplicate dependencies: " ++ unwords (map display dups)) where dups = [ p | (p:_:_) <- group (sort deps) ] checkHSLib :: Verbosity -> [String] -> Bool -> String -> Validate () checkHSLib verbosity dirs auto_ghci_libs lib = do let batch_lib_file = "lib" ++ lib ++ ".a" filenames = ["lib" ++ lib ++ ".a", "lib" ++ lib ++ ".p_a", "lib" ++ lib ++ "-ghc" ++ showVersion ghcVersion ++ ".so", "lib" ++ lib ++ "-ghc" ++ showVersion ghcVersion ++ ".dylib", lib ++ "-ghc" ++ showVersion ghcVersion ++ ".dll"] m <- liftIO $ doesFileExistOnPath filenames dirs case m of Nothing -> verror ForceFiles ("cannot find any of " ++ show filenames ++ " on library path") Just dir -> liftIO $ checkGHCiLib verbosity dir batch_lib_file lib auto_ghci_libs doesFileExistOnPath :: [FilePath] -> [FilePath] -> IO (Maybe FilePath) doesFileExistOnPath filenames paths = go fullFilenames where fullFilenames = [ (path, path </> filename) | filename <- filenames , path <- paths ] go [] = return Nothing go ((p, fp) : xs) = do b <- doesFileExist fp if b then return (Just p) else go xs checkModules :: InstalledPackageInfo -> Validate () checkModules pkg = do mapM_ findModule (exposedModules pkg ++ hiddenModules pkg) where findModule modl = -- there's no interface file for GHC.Prim unless (modl == fromString "GHC.Prim") $ do let files = [ toFilePath modl <.> extension | extension <- ["hi", "p_hi", "dyn_hi" ] ] m <- liftIO $ doesFileExistOnPath files (importDirs pkg) when (isNothing m) $ verror ForceFiles ("cannot find any of " ++ show files) checkGHCiLib :: Verbosity -> String -> String -> String -> Bool -> IO () checkGHCiLib verbosity batch_lib_dir batch_lib_file lib auto_build | auto_build = autoBuildGHCiLib verbosity batch_lib_dir batch_lib_file ghci_lib_file | otherwise = return () where ghci_lib_file = lib <.> "o" -- automatically build the GHCi version of a batch lib, -- using ld --whole-archive. autoBuildGHCiLib :: Verbosity -> String -> String -> String -> IO () autoBuildGHCiLib verbosity dir batch_file ghci_file = do let ghci_lib_file = dir ++ '/':ghci_file batch_lib_file = dir ++ '/':batch_file when (verbosity >= Normal) $ info ("building GHCi library " ++ ghci_lib_file ++ "...") #if defined(darwin_HOST_OS) r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"-all_load",batch_lib_file] #elif defined(mingw32_HOST_OS) execDir <- getLibDir r <- rawSystem (maybe "" (++"/gcc-lib/") execDir++"ld") ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file] #else r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file] #endif when (r /= ExitSuccess) $ exitWith r when (verbosity >= Normal) $ infoLn (" done.") -- ----------------------------------------------------------------------------- -- Searching for modules #if not_yet findModules :: [FilePath] -> IO [String] findModules paths = mms <- mapM searchDir paths return (concat mms) searchDir path prefix = do fs <- getDirectoryEntries path `catchIO` \_ -> return [] searchEntries path prefix fs searchEntries path prefix [] = return [] searchEntries path prefix (f:fs) | looks_like_a_module = do ms <- searchEntries path prefix fs return (prefix `joinModule` f : ms) | looks_like_a_component = do ms <- searchDir (path </> f) (prefix `joinModule` f) ms' <- searchEntries path prefix fs return (ms ++ ms') | otherwise searchEntries path prefix fs where (base,suffix) = splitFileExt f looks_like_a_module = suffix `elem` haskell_suffixes && all okInModuleName base looks_like_a_component = null suffix && all okInModuleName base okInModuleName c #endif -- --------------------------------------------------------------------------- -- expanding environment variables in the package configuration expandEnvVars :: String -> Force -> IO String expandEnvVars str0 force = go str0 "" where go "" acc = return $! reverse acc go ('$':'{':str) acc | (var, '}':rest) <- break close str = do value <- lookupEnvVar var go rest (reverse value ++ acc) where close c = c == '}' || c == '\n' -- don't span newlines go (c:str) acc = go str (c:acc) lookupEnvVar :: String -> IO String lookupEnvVar "pkgroot" = return "${pkgroot}" -- these two are special, lookupEnvVar "pkgrooturl" = return "${pkgrooturl}" -- we don't expand them lookupEnvVar nm = catchIO (System.Environment.getEnv nm) (\ _ -> do dieOrForceAll force ("Unable to expand variable " ++ show nm) return "") ----------------------------------------------------------------------------- getProgramName :: IO String getProgramName = liftM (`withoutSuffix` ".bin") getProgName where str `withoutSuffix` suff | suff `isSuffixOf` str = take (length str - length suff) str | otherwise = str bye :: String -> IO a bye s = putStr s >> exitWith ExitSuccess die :: String -> IO a die = dieWith 1 dieWith :: Int -> String -> IO a dieWith ec s = do prog <- getProgramName reportError (prog ++ ": " ++ s) exitWith (ExitFailure ec) dieOrForceAll :: Force -> String -> IO () dieOrForceAll ForceAll s = ignoreError s dieOrForceAll _other s = dieForcible s warn :: String -> IO () warn = reportError -- send info messages to stdout infoLn :: String -> IO () infoLn = putStrLn info :: String -> IO () info = putStr ignoreError :: String -> IO () ignoreError s = reportError (s ++ " (ignoring)") reportError :: String -> IO () reportError s = do hFlush stdout; hPutStrLn stderr s dieForcible :: String -> IO () dieForcible s = die (s ++ " (use --force to override)") my_head :: String -> [a] -> a my_head s [] = error s my_head _ (x : _) = x getLibDir :: IO (Maybe String) getLibDir = return $ Just hasteSysDir ----------------------------------------- -- Adapted from ghc/compiler/utils/Panic installSignalHandlers :: IO () installSignalHandlers = do threadid <- myThreadId let interrupt = Exception.throwTo threadid (Exception.ErrorCall "interrupted") -- #if !defined(mingw32_HOST_OS) _ <- installHandler sigQUIT (Catch interrupt) Nothing _ <- installHandler sigINT (Catch interrupt) Nothing return () #else -- GHC 6.3+ has support for console events on Windows -- NOTE: running GHCi under a bash shell for some reason requires -- you to press Ctrl-Break rather than Ctrl-C to provoke -- an interrupt. Ctrl-C is getting blocked somewhere, I don't know -- why --SDM 17/12/2004 let sig_handler ControlC = interrupt sig_handler Break = interrupt sig_handler _ = return () _ <- installHandler (Catch sig_handler) return () #endif #if mingw32_HOST_OS || mingw32_TARGET_OS throwIOIO :: Exception.IOException -> IO a throwIOIO = Exception.throwIO #endif catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a catchIO = Exception.catch catchError :: IO a -> (String -> IO a) -> IO a catchError io handler = io `Exception.catch` handler' where handler' (Exception.ErrorCall err) = handler err tryIO :: IO a -> IO (Either Exception.IOException a) tryIO = Exception.try writeBinaryFileAtomic :: Bin.Binary a => FilePath -> a -> IO () writeBinaryFileAtomic targetFile obj = withFileAtomic targetFile $ \h -> do hSetBinaryMode h True B.hPutStr h (Bin.encode obj) writeFileUtf8Atomic :: FilePath -> String -> IO () writeFileUtf8Atomic targetFile content = withFileAtomic targetFile $ \h -> do hSetEncoding h utf8 hPutStr h content -- copied from Cabal's Distribution.Simple.Utils, except that we want -- to use text files here, rather than binary files. withFileAtomic :: FilePath -> (Handle -> IO ()) -> IO () withFileAtomic targetFile write_content = do (newFile, newHandle) <- openNewFile targetDir template do write_content newHandle hClose newHandle #if mingw32_HOST_OS || mingw32_TARGET_OS renameFile newFile targetFile -- If the targetFile exists then renameFile will fail `catchIO` \err -> do exists <- doesFileExist targetFile if exists then do removeFileSafe targetFile -- Big fat hairy race condition renameFile newFile targetFile -- If the removeFile succeeds and the renameFile fails -- then we've lost the atomic property. else throwIOIO err #else renameFile newFile targetFile #endif `Exception.onException` do hClose newHandle removeFileSafe newFile where template = targetName <.> "tmp" targetDir | null targetDir_ = "." | otherwise = targetDir_ --TODO: remove this when takeDirectory/splitFileName is fixed -- to always return a valid dir (targetDir_,targetName) = splitFileName targetFile openNewFile :: FilePath -> String -> IO (FilePath, Handle) openNewFile dir template = do -- this was added to System.IO in 6.12.1 -- we must use this version because the version below opens the file -- in binary mode. openTempFileWithDefaultPermissions dir template -- | The function splits the given string to substrings -- using 'isSearchPathSeparator'. parseSearchPath :: String -> [FilePath] parseSearchPath path = split path where split :: String -> [String] split s = case rest' of [] -> [chunk] _:rest -> chunk : split rest where chunk = case chunk' of #ifdef mingw32_HOST_OS ('\"':xs@(_:_)) | last xs == '\"' -> init xs #endif _ -> chunk' (chunk', rest') = break isSearchPathSeparator s readUTF8File :: FilePath -> IO String readUTF8File file = do h <- openFile file ReadMode -- fix the encoding to UTF-8 hSetEncoding h utf8 hGetContents h -- removeFileSave doesn't throw an exceptions, if the file is already deleted removeFileSafe :: FilePath -> IO () removeFileSafe fn = removeFile fn `catchIO` \ e -> when (not $ isDoesNotExistError e) $ ioError e absolutePath :: FilePath -> IO FilePath absolutePath path = return . normalise . (</> path) =<< getCurrentDirectory -- | Only global packages may be marked as relocatable! -- May break horribly for general use, only reliable for Haste base packages. relocate :: [String] -> String -> Sh.Shell () relocate packages pkg = do pi <- Sh.run hastePkgBinary (packages ++ ["describe", pkg]) "" Sh.run_ hastePkgBinary (packages ++ ["update", "-", "--force", "--global"]) (reloc pi) where reloc = unlines . map fixPath . lines fixPath s | isKey "library-dirs: " s = prefix s "library-dirs" importDir | isKey "import-dirs: " s = prefix s "import-dirs" importDir | isKey "haddock-interfaces: " s = prefix s "haddock-interfaces" importDir | isKey "haddock-html: " s = prefix s "haddock-html" importDir | isKey "include-dirs: " s = "include-dirs: " ++ includeDir | otherwise = s prefix s pfx path = pfx ++ ": " ++ path </> stripPrefix s stripPrefix = joinPath . dropWhile (not . isKey pkg) . splitPath isKey _ "" = False isKey key str = and $ zipWith (==) key str importDir = "${pkgroot}" includeDir = "${pkgroot}" </> "include"
szatkus/haste-compiler
utils/haste-pkg/HastePkg708.hs
Haskell
bsd-3-clause
72,226
{-# LANGUAGE TemplateHaskell, TypeFamilies, PolyKinds #-} module T9692 where import Data.Kind (Type) import Language.Haskell.TH hiding (Type) import Language.Haskell.TH.Syntax hiding (Type) import Language.Haskell.TH.Ppr import System.IO class C a where data F a (b :: k) :: Type instance C Int where data F Int x = FInt x $( do info <- qReify (mkName "F") runIO $ putStrLn $ pprint info runIO $ hFlush stdout return [])
sdiehl/ghc
testsuite/tests/th/T9692.hs
Haskell
bsd-3-clause
460
#!/usr/bin/env runhaskell {-| This Haskell script prints a random quote from my quote collection in `data/finished.yaml`. I email myself quotes every few days with a cron job piping the output of this to a command-line mailing program (mutt). Appropriate packages can be installed with `cabal`. Brandon Amos http://bamos.github.io 2015/04/24 -} {-# LANGUAGE DeriveGeneric, DeriveAnyClass #-} import Data.Aeson -- For parsing YAML with FromJSON. import Data.Maybe (catMaybes, fromJust) import Data.Random (sample) import Data.Random.Extras (choice) -- From `random-extras` package. import Data.Yaml (decode) -- From `yaml` package. import GHC.Generics import qualified Data.ByteString.Char8 as BS data Quote = Quote { -- String for Roman numerals. -- Warning: Integer page numbers cause silent -- parsing errors. page :: String ,content :: String} deriving (Show,Generic,FromJSON) data Book = Book {author :: String ,title :: String ,finished :: String ,rating :: Int ,quotes :: Maybe [Quote] ,notes :: Maybe [String]} deriving (Show,Generic,FromJSON) -- Produce a formatted string for a quote. getQuote :: Book -> Quote -> String getQuote book quote = concat [show $ content quote ,"\n\nFrom page " ,page quote ," of " ,show $ title book ," by " ,author book] -- Format all of the quotes of a book. getQuotes :: Book -> Maybe [String] getQuotes book = (map $ getQuote book) <$> quotes book getAllQuotes :: [Book] -> [String] getAllQuotes books = concat . catMaybes . map getQuotes $ books main = do yamlData <- BS.readFile "data/finished.yaml" let mBooks = Data.Yaml.decode yamlData :: Maybe [Book] case mBooks of Just books -> putStrLn =<< randomQuote where randomQuote = sample $ choice quotes quotes = getAllQuotes $ books Nothing -> putStrLn "Unable to parse YAML document."
BIPOC-Books/BIPOC-Books.github.io
scripts/random-quote.hs
Haskell
mit
2,086
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE NoImplicitPrelude, DeriveDataTypeable, MagicHash #-} {-# OPTIONS_GHC -funbox-strict-fields #-} {-# OPTIONS_HADDOCK hide #-} ----------------------------------------------------------------------------- -- | -- Module : GHC.IO.Exception -- Copyright : (c) The University of Glasgow, 2009 -- License : see libraries/base/LICENSE -- -- Maintainer : libraries@haskell.org -- Stability : internal -- Portability : non-portable -- -- IO-related Exception types and functions -- ----------------------------------------------------------------------------- module GHC.IO.Exception ( BlockedIndefinitelyOnMVar(..), blockedIndefinitelyOnMVar, BlockedIndefinitelyOnSTM(..), blockedIndefinitelyOnSTM, Deadlock(..), AssertionFailed(..), AsyncException(..), stackOverflow, heapOverflow, ArrayException(..), ExitCode(..), ioException, ioError, IOError, IOException(..), IOErrorType(..), userError, assertError, unsupportedOperation, untangle, ) where import GHC.Base import GHC.List import GHC.IO import GHC.Show import GHC.Read import GHC.Exception import Data.Maybe import GHC.IO.Handle.Types import Foreign.C.Types import Data.Typeable ( Typeable ) -- ------------------------------------------------------------------------ -- Exception datatypes and operations -- |The thread is blocked on an @MVar@, but there are no other references -- to the @MVar@ so it can't ever continue. data BlockedIndefinitelyOnMVar = BlockedIndefinitelyOnMVar deriving Typeable instance Exception BlockedIndefinitelyOnMVar instance Show BlockedIndefinitelyOnMVar where showsPrec _ BlockedIndefinitelyOnMVar = showString "thread blocked indefinitely in an MVar operation" blockedIndefinitelyOnMVar :: SomeException -- for the RTS blockedIndefinitelyOnMVar = toException BlockedIndefinitelyOnMVar ----- -- |The thread is waiting to retry an STM transaction, but there are no -- other references to any @TVar@s involved, so it can't ever continue. data BlockedIndefinitelyOnSTM = BlockedIndefinitelyOnSTM deriving Typeable instance Exception BlockedIndefinitelyOnSTM instance Show BlockedIndefinitelyOnSTM where showsPrec _ BlockedIndefinitelyOnSTM = showString "thread blocked indefinitely in an STM transaction" blockedIndefinitelyOnSTM :: SomeException -- for the RTS blockedIndefinitelyOnSTM = toException BlockedIndefinitelyOnSTM ----- -- |There are no runnable threads, so the program is deadlocked. -- The @Deadlock@ exception is raised in the main thread only. data Deadlock = Deadlock deriving Typeable instance Exception Deadlock instance Show Deadlock where showsPrec _ Deadlock = showString "<<deadlock>>" ----- -- |'assert' was applied to 'False'. data AssertionFailed = AssertionFailed String deriving Typeable instance Exception AssertionFailed instance Show AssertionFailed where showsPrec _ (AssertionFailed err) = showString err ----- -- |Asynchronous exceptions. data AsyncException = StackOverflow -- ^The current thread\'s stack exceeded its limit. -- Since an exception has been raised, the thread\'s stack -- will certainly be below its limit again, but the -- programmer should take remedial action -- immediately. | HeapOverflow -- ^The program\'s heap is reaching its limit, and -- the program should take action to reduce the amount of -- live data it has. Notes: -- -- * It is undefined which thread receives this exception. -- -- * GHC currently does not throw 'HeapOverflow' exceptions. | ThreadKilled -- ^This exception is raised by another thread -- calling 'Control.Concurrent.killThread', or by the system -- if it needs to terminate the thread for some -- reason. | UserInterrupt -- ^This exception is raised by default in the main thread of -- the program when the user requests to terminate the program -- via the usual mechanism(s) (e.g. Control-C in the console). deriving (Eq, Ord, Typeable) instance Exception AsyncException -- | Exceptions generated by array operations data ArrayException = IndexOutOfBounds String -- ^An attempt was made to index an array outside -- its declared bounds. | UndefinedElement String -- ^An attempt was made to evaluate an element of an -- array that had not been initialized. deriving (Eq, Ord, Typeable) instance Exception ArrayException stackOverflow, heapOverflow :: SomeException -- for the RTS stackOverflow = toException StackOverflow heapOverflow = toException HeapOverflow instance Show AsyncException where showsPrec _ StackOverflow = showString "stack overflow" showsPrec _ HeapOverflow = showString "heap overflow" showsPrec _ ThreadKilled = showString "thread killed" showsPrec _ UserInterrupt = showString "user interrupt" instance Show ArrayException where showsPrec _ (IndexOutOfBounds s) = showString "array index out of range" . (if not (null s) then showString ": " . showString s else id) showsPrec _ (UndefinedElement s) = showString "undefined array element" . (if not (null s) then showString ": " . showString s else id) -- ----------------------------------------------------------------------------- -- The ExitCode type -- We need it here because it is used in ExitException in the -- Exception datatype (above). -- | Defines the exit codes that a program can return. data ExitCode = ExitSuccess -- ^ indicates successful termination; | ExitFailure Int -- ^ indicates program failure with an exit code. -- The exact interpretation of the code is -- operating-system dependent. In particular, some values -- may be prohibited (e.g. 0 on a POSIX-compliant system). deriving (Eq, Ord, Read, Show, Typeable) instance Exception ExitCode ioException :: IOException -> IO a ioException err = throwIO err -- | Raise an 'IOError' in the 'IO' monad. ioError :: IOError -> IO a ioError = ioException -- --------------------------------------------------------------------------- -- IOError type -- | The Haskell 98 type for exceptions in the 'IO' monad. -- Any I\/O operation may raise an 'IOError' instead of returning a result. -- For a more general type of exception, including also those that arise -- in pure code, see "Control.Exception.Exception". -- -- In Haskell 98, this is an opaque type. type IOError = IOException -- |Exceptions that occur in the @IO@ monad. -- An @IOException@ records a more specific error type, a descriptive -- string and maybe the handle that was used when the error was -- flagged. data IOException = IOError { ioe_handle :: Maybe Handle, -- the handle used by the action flagging -- the error. ioe_type :: IOErrorType, -- what it was. ioe_location :: String, -- location. ioe_description :: String, -- error type specific information. ioe_errno :: Maybe CInt, -- errno leading to this error, if any. ioe_filename :: Maybe FilePath -- filename the error is related to. } deriving Typeable instance Exception IOException instance Eq IOException where (IOError h1 e1 loc1 str1 en1 fn1) == (IOError h2 e2 loc2 str2 en2 fn2) = e1==e2 && str1==str2 && h1==h2 && loc1==loc2 && en1==en2 && fn1==fn2 -- | An abstract type that contains a value for each variant of 'IOError'. data IOErrorType -- Haskell 98: = AlreadyExists | NoSuchThing | ResourceBusy | ResourceExhausted | EOF | IllegalOperation | PermissionDenied | UserError -- GHC only: | UnsatisfiedConstraints | SystemError | ProtocolError | OtherError | InvalidArgument | InappropriateType | HardwareFault | UnsupportedOperation | TimeExpired | ResourceVanished | Interrupted instance Eq IOErrorType where x == y = isTrue# (getTag x ==# getTag y) instance Show IOErrorType where showsPrec _ e = showString $ case e of AlreadyExists -> "already exists" NoSuchThing -> "does not exist" ResourceBusy -> "resource busy" ResourceExhausted -> "resource exhausted" EOF -> "end of file" IllegalOperation -> "illegal operation" PermissionDenied -> "permission denied" UserError -> "user error" HardwareFault -> "hardware fault" InappropriateType -> "inappropriate type" Interrupted -> "interrupted" InvalidArgument -> "invalid argument" OtherError -> "failed" ProtocolError -> "protocol error" ResourceVanished -> "resource vanished" SystemError -> "system error" TimeExpired -> "timeout" UnsatisfiedConstraints -> "unsatisified constraints" -- ultra-precise! UnsupportedOperation -> "unsupported operation" -- | Construct an 'IOError' value with a string describing the error. -- The 'fail' method of the 'IO' instance of the 'Monad' class raises a -- 'userError', thus: -- -- > instance Monad IO where -- > ... -- > fail s = ioError (userError s) -- userError :: String -> IOError userError str = IOError Nothing UserError "" str Nothing Nothing -- --------------------------------------------------------------------------- -- Showing IOErrors instance Show IOException where showsPrec p (IOError hdl iot loc s _ fn) = (case fn of Nothing -> case hdl of Nothing -> id Just h -> showsPrec p h . showString ": " Just name -> showString name . showString ": ") . (case loc of "" -> id _ -> showString loc . showString ": ") . showsPrec p iot . (case s of "" -> id _ -> showString " (" . showString s . showString ")") -- Note the use of "lazy". This means that -- assert False (throw e) -- will throw the assertion failure rather than e. See trac #5561. assertError :: Addr# -> Bool -> a -> a assertError str predicate v | predicate = lazy v | otherwise = throw (AssertionFailed (untangle str "Assertion failed")) unsupportedOperation :: IOError unsupportedOperation = (IOError Nothing UnsupportedOperation "" "Operation is not supported" Nothing Nothing) {- (untangle coded message) expects "coded" to be of the form "location|details" It prints location message details -} untangle :: Addr# -> String -> String untangle coded message = location ++ ": " ++ message ++ details ++ "\n" where coded_str = unpackCStringUtf8# coded (location, details) = case (span not_bar coded_str) of { (loc, rest) -> case rest of ('|':det) -> (loc, ' ' : det) _ -> (loc, "") } not_bar c = c /= '|'
beni55/haste-compiler
libraries/ghc-7.8/base/GHC/IO/Exception.hs
Haskell
bsd-3-clause
11,036
{-# LANGUAGE GADTs #-} module CmmSink ( cmmSink ) where import Cmm import CmmOpt import BlockId import CmmLive import CmmUtils import Hoopl import CodeGen.Platform import Platform (isARM, platformArch) import DynFlags import UniqFM import PprCmm () import Data.List (partition) import qualified Data.Set as Set import Data.Maybe -- ----------------------------------------------------------------------------- -- Sinking and inlining -- This is an optimisation pass that -- (a) moves assignments closer to their uses, to reduce register pressure -- (b) pushes assignments into a single branch of a conditional if possible -- (c) inlines assignments to registers that are mentioned only once -- (d) discards dead assignments -- -- This tightens up lots of register-heavy code. It is particularly -- helpful in the Cmm generated by the Stg->Cmm code generator, in -- which every function starts with a copyIn sequence like: -- -- x1 = R1 -- x2 = Sp[8] -- x3 = Sp[16] -- if (Sp - 32 < SpLim) then L1 else L2 -- -- we really want to push the x1..x3 assignments into the L2 branch. -- -- Algorithm: -- -- * Start by doing liveness analysis. -- -- * Keep a list of assignments A; earlier ones may refer to later ones. -- Currently we only sink assignments to local registers, because we don't -- have liveness information about global registers. -- -- * Walk forwards through the graph, look at each node N: -- -- * If it is a dead assignment, i.e. assignment to a register that is -- not used after N, discard it. -- -- * Try to inline based on current list of assignments -- * If any assignments in A (1) occur only once in N, and (2) are -- not live after N, inline the assignment and remove it -- from A. -- -- * If an assignment in A is cheap (RHS is local register), then -- inline the assignment and keep it in A in case it is used afterwards. -- -- * Otherwise don't inline. -- -- * If N is assignment to a local register pick up the assignment -- and add it to A. -- -- * If N is not an assignment to a local register: -- * remove any assignments from A that conflict with N, and -- place them before N in the current block. We call this -- "dropping" the assignments. -- -- * An assignment conflicts with N if it: -- - assigns to a register mentioned in N -- - mentions a register assigned by N -- - reads from memory written by N -- * do this recursively, dropping dependent assignments -- -- * At an exit node: -- * drop any assignments that are live on more than one successor -- and are not trivial -- * if any successor has more than one predecessor (a join-point), -- drop everything live in that successor. Since we only propagate -- assignments that are not dead at the successor, we will therefore -- eliminate all assignments dead at this point. Thus analysis of a -- join-point will always begin with an empty list of assignments. -- -- -- As a result of above algorithm, sinking deletes some dead assignments -- (transitively, even). This isn't as good as removeDeadAssignments, -- but it's much cheaper. -- ----------------------------------------------------------------------------- -- things that we aren't optimising very well yet. -- -- ----------- -- (1) From GHC's FastString.hashStr: -- -- s2ay: -- if ((_s2an::I64 == _s2ao::I64) >= 1) goto c2gn; else goto c2gp; -- c2gn: -- R1 = _s2au::I64; -- call (I64[Sp])(R1) args: 8, res: 0, upd: 8; -- c2gp: -- _s2cO::I64 = %MO_S_Rem_W64(%MO_UU_Conv_W8_W64(I8[_s2aq::I64 + (_s2an::I64 << 0)]) + _s2au::I64 * 128, -- 4091); -- _s2an::I64 = _s2an::I64 + 1; -- _s2au::I64 = _s2cO::I64; -- goto s2ay; -- -- a nice loop, but we didn't eliminate the silly assignment at the end. -- See Note [dependent assignments], which would probably fix this. -- This is #8336 on Trac. -- -- ----------- -- (2) From stg_atomically_frame in PrimOps.cmm -- -- We have a diamond control flow: -- -- x = ... -- | -- / \ -- A B -- \ / -- | -- use of x -- -- Now x won't be sunk down to its use, because we won't push it into -- both branches of the conditional. We certainly do have to check -- that we can sink it past all the code in both A and B, but having -- discovered that, we could sink it to its use. -- -- ----------------------------------------------------------------------------- type Assignment = (LocalReg, CmmExpr, AbsMem) -- Assignment caches AbsMem, an abstraction of the memory read by -- the RHS of the assignment. type Assignments = [Assignment] -- A sequence of assignements; kept in *reverse* order -- So the list [ x=e1, y=e2 ] means the sequence of assignments -- y = e2 -- x = e1 cmmSink :: DynFlags -> CmmGraph -> CmmGraph cmmSink dflags graph = ofBlockList (g_entry graph) $ sink mapEmpty $ blocks where liveness = cmmLocalLiveness dflags graph getLive l = mapFindWithDefault Set.empty l liveness blocks = postorderDfs graph join_pts = findJoinPoints blocks sink :: BlockEnv Assignments -> [CmmBlock] -> [CmmBlock] sink _ [] = [] sink sunk (b:bs) = -- pprTrace "sink" (ppr lbl) $ blockJoin first final_middle final_last : sink sunk' bs where lbl = entryLabel b (first, middle, last) = blockSplit b succs = successors last -- Annotate the middle nodes with the registers live *after* -- the node. This will help us decide whether we can inline -- an assignment in the current node or not. live = Set.unions (map getLive succs) live_middle = gen_kill dflags last live ann_middles = annotate dflags live_middle (blockToList middle) -- Now sink and inline in this block (middle', assigs) = walk dflags ann_middles (mapFindWithDefault [] lbl sunk) fold_last = constantFoldNode dflags last (final_last, assigs') = tryToInline dflags live fold_last assigs -- We cannot sink into join points (successors with more than -- one predecessor), so identify the join points and the set -- of registers live in them. (joins, nonjoins) = partition (`mapMember` join_pts) succs live_in_joins = Set.unions (map getLive joins) -- We do not want to sink an assignment into multiple branches, -- so identify the set of registers live in multiple successors. -- This is made more complicated because when we sink an assignment -- into one branch, this might change the set of registers that are -- now live in multiple branches. init_live_sets = map getLive nonjoins live_in_multi live_sets r = case filter (Set.member r) live_sets of (_one:_two:_) -> True _ -> False -- Now, drop any assignments that we will not sink any further. (dropped_last, assigs'') = dropAssignments dflags drop_if init_live_sets assigs' drop_if a@(r,rhs,_) live_sets = (should_drop, live_sets') where should_drop = conflicts dflags a final_last || not (isTrivial dflags rhs) && live_in_multi live_sets r || r `Set.member` live_in_joins live_sets' | should_drop = live_sets | otherwise = map upd live_sets upd set | r `Set.member` set = set `Set.union` live_rhs | otherwise = set live_rhs = foldRegsUsed dflags extendRegSet emptyRegSet rhs final_middle = foldl blockSnoc middle' dropped_last sunk' = mapUnion sunk $ mapFromList [ (l, filterAssignments dflags (getLive l) assigs'') | l <- succs ] {- TODO: enable this later, when we have some good tests in place to measure the effect and tune it. -- small: an expression we don't mind duplicating isSmall :: CmmExpr -> Bool isSmall (CmmReg (CmmLocal _)) = True -- isSmall (CmmLit _) = True isSmall (CmmMachOp (MO_Add _) [x,y]) = isTrivial x && isTrivial y isSmall (CmmRegOff (CmmLocal _) _) = True isSmall _ = False -} -- -- We allow duplication of trivial expressions: registers (both local and -- global) and literals. -- isTrivial :: DynFlags -> CmmExpr -> Bool isTrivial _ (CmmReg (CmmLocal _)) = True isTrivial dflags (CmmReg (CmmGlobal r)) = -- see Note [Inline GlobalRegs?] if isARM (platformArch (targetPlatform dflags)) then True -- CodeGen.Platform.ARM does not have globalRegMaybe else isJust (globalRegMaybe (targetPlatform dflags) r) -- GlobalRegs that are loads from BaseReg are not trivial isTrivial _ (CmmLit _) = True isTrivial _ _ = False -- -- annotate each node with the set of registers live *after* the node -- annotate :: DynFlags -> LocalRegSet -> [CmmNode O O] -> [(LocalRegSet, CmmNode O O)] annotate dflags live nodes = snd $ foldr ann (live,[]) nodes where ann n (live,nodes) = (gen_kill dflags n live, (live,n) : nodes) -- -- Find the blocks that have multiple successors (join points) -- findJoinPoints :: [CmmBlock] -> BlockEnv Int findJoinPoints blocks = mapFilter (>1) succ_counts where all_succs = concatMap successors blocks succ_counts :: BlockEnv Int succ_counts = foldr (\l -> mapInsertWith (+) l 1) mapEmpty all_succs -- -- filter the list of assignments to remove any assignments that -- are not live in a continuation. -- filterAssignments :: DynFlags -> LocalRegSet -> Assignments -> Assignments filterAssignments dflags live assigs = reverse (go assigs []) where go [] kept = kept go (a@(r,_,_):as) kept | needed = go as (a:kept) | otherwise = go as kept where needed = r `Set.member` live || any (conflicts dflags a) (map toNode kept) -- Note that we must keep assignments that are -- referred to by other assignments we have -- already kept. -- ----------------------------------------------------------------------------- -- Walk through the nodes of a block, sinking and inlining assignments -- as we go. -- -- On input we pass in a: -- * list of nodes in the block -- * a list of assignments that appeared *before* this block and -- that are being sunk. -- -- On output we get: -- * a new block -- * a list of assignments that will be placed *after* that block. -- walk :: DynFlags -> [(LocalRegSet, CmmNode O O)] -- nodes of the block, annotated with -- the set of registers live *after* -- this node. -> Assignments -- The current list of -- assignments we are sinking. -- Earlier assignments may refer -- to later ones. -> ( Block CmmNode O O -- The new block , Assignments -- Assignments to sink further ) walk dflags nodes assigs = go nodes emptyBlock assigs where go [] block as = (block, as) go ((live,node):ns) block as | shouldDiscard node live = go ns block as -- discard dead assignment | Just a <- shouldSink dflags node2 = go ns block (a : as1) | otherwise = go ns block' as' where node1 = constantFoldNode dflags node (node2, as1) = tryToInline dflags live node1 as (dropped, as') = dropAssignmentsSimple dflags (\a -> conflicts dflags a node2) as1 block' = foldl blockSnoc block dropped `blockSnoc` node2 -- -- Heuristic to decide whether to pick up and sink an assignment -- Currently we pick up all assignments to local registers. It might -- be profitable to sink assignments to global regs too, but the -- liveness analysis doesn't track those (yet) so we can't. -- shouldSink :: DynFlags -> CmmNode e x -> Maybe Assignment shouldSink dflags (CmmAssign (CmmLocal r) e) | no_local_regs = Just (r, e, exprMem dflags e) where no_local_regs = True -- foldRegsUsed (\_ _ -> False) True e shouldSink _ _other = Nothing -- -- discard dead assignments. This doesn't do as good a job as -- removeDeadAsssignments, because it would need multiple passes -- to get all the dead code, but it catches the common case of -- superfluous reloads from the stack that the stack allocator -- leaves behind. -- -- Also we catch "r = r" here. You might think it would fall -- out of inlining, but the inliner will see that r is live -- after the instruction and choose not to inline r in the rhs. -- shouldDiscard :: CmmNode e x -> LocalRegSet -> Bool shouldDiscard node live = case node of CmmAssign r (CmmReg r') | r == r' -> True CmmAssign (CmmLocal r) _ -> not (r `Set.member` live) _otherwise -> False toNode :: Assignment -> CmmNode O O toNode (r,rhs,_) = CmmAssign (CmmLocal r) rhs dropAssignmentsSimple :: DynFlags -> (Assignment -> Bool) -> Assignments -> ([CmmNode O O], Assignments) dropAssignmentsSimple dflags f = dropAssignments dflags (\a _ -> (f a, ())) () dropAssignments :: DynFlags -> (Assignment -> s -> (Bool, s)) -> s -> Assignments -> ([CmmNode O O], Assignments) dropAssignments dflags should_drop state assigs = (dropped, reverse kept) where (dropped,kept) = go state assigs [] [] go _ [] dropped kept = (dropped, kept) go state (assig : rest) dropped kept | conflict = go state' rest (toNode assig : dropped) kept | otherwise = go state' rest dropped (assig:kept) where (dropit, state') = should_drop assig state conflict = dropit || any (conflicts dflags assig) dropped -- ----------------------------------------------------------------------------- -- Try to inline assignments into a node. tryToInline :: DynFlags -> LocalRegSet -- set of registers live after this -- node. We cannot inline anything -- that is live after the node, unless -- it is small enough to duplicate. -> CmmNode O x -- The node to inline into -> Assignments -- Assignments to inline -> ( CmmNode O x -- New node , Assignments -- Remaining assignments ) tryToInline dflags live node assigs = go usages node [] assigs where usages :: UniqFM Int -- Maps each LocalReg to a count of how often it is used usages = foldLocalRegsUsed dflags addUsage emptyUFM node go _usages node _skipped [] = (node, []) go usages node skipped (a@(l,rhs,_) : rest) | cannot_inline = dont_inline | occurs_none = discard -- Note [discard during inlining] | occurs_once = inline_and_discard | isTrivial dflags rhs = inline_and_keep | otherwise = dont_inline where inline_and_discard = go usages' inl_node skipped rest where usages' = foldLocalRegsUsed dflags addUsage usages rhs discard = go usages node skipped rest dont_inline = keep node -- don't inline the assignment, keep it inline_and_keep = keep inl_node -- inline the assignment, keep it keep node' = (final_node, a : rest') where (final_node, rest') = go usages' node' (l:skipped) rest usages' = foldLocalRegsUsed dflags (\m r -> addToUFM m r 2) usages rhs -- we must not inline anything that is mentioned in the RHS -- of a binding that we have already skipped, so we set the -- usages of the regs on the RHS to 2. cannot_inline = skipped `regsUsedIn` rhs -- Note [dependent assignments] || l `elem` skipped || not (okToInline dflags rhs node) l_usages = lookupUFM usages l l_live = l `elemRegSet` live occurs_once = not l_live && l_usages == Just 1 occurs_none = not l_live && l_usages == Nothing inl_node = mapExpDeep inline node -- mapExpDeep is where the inlining actually takes place! where inline (CmmReg (CmmLocal l')) | l == l' = rhs inline (CmmRegOff (CmmLocal l') off) | l == l' = cmmOffset dflags rhs off -- re-constant fold after inlining inline (CmmMachOp op args) = cmmMachOpFold dflags op args inline other = other -- Note [dependent assignments] -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- -- If our assignment list looks like -- -- [ y = e, x = ... y ... ] -- -- We cannot inline x. Remember this list is really in reverse order, -- so it means x = ... y ...; y = e -- -- Hence if we inline x, the outer assignment to y will capture the -- reference in x's right hand side. -- -- In this case we should rename the y in x's right-hand side, -- i.e. change the list to [ y = e, x = ... y1 ..., y1 = y ] -- Now we can go ahead and inline x. -- -- For now we do nothing, because this would require putting -- everything inside UniqSM. -- -- One more variant of this (#7366): -- -- [ y = e, y = z ] -- -- If we don't want to inline y = e, because y is used many times, we -- might still be tempted to inline y = z (because we always inline -- trivial rhs's). But of course we can't, because y is equal to e, -- not z. -- Note [discard during inlining] -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- Opportunities to discard assignments sometimes appear after we've -- done some inlining. Here's an example: -- -- x = R1; -- y = P64[x + 7]; -- z = P64[x + 15]; -- /* z is dead */ -- R1 = y & (-8); -- -- The x assignment is trivial, so we inline it in the RHS of y, and -- keep both x and y. z gets dropped because it is dead, then we -- inline y, and we have a dead assignment to x. If we don't notice -- that x is dead in tryToInline, we end up retaining it. addUsage :: UniqFM Int -> LocalReg -> UniqFM Int addUsage m r = addToUFM_C (+) m r 1 regsUsedIn :: [LocalReg] -> CmmExpr -> Bool regsUsedIn [] _ = False regsUsedIn ls e = wrapRecExpf f e False where f (CmmReg (CmmLocal l)) _ | l `elem` ls = True f (CmmRegOff (CmmLocal l) _) _ | l `elem` ls = True f _ z = z -- we don't inline into CmmUnsafeForeignCall if the expression refers -- to global registers. This is a HACK to avoid global registers -- clashing with C argument-passing registers, really the back-end -- ought to be able to handle it properly, but currently neither PprC -- nor the NCG can do it. See Note [Register parameter passing] -- See also StgCmmForeign:load_args_into_temps. okToInline :: DynFlags -> CmmExpr -> CmmNode e x -> Bool okToInline dflags expr node@(CmmUnsafeForeignCall{}) = not (globalRegistersConflict dflags expr node) okToInline _ _ _ = True -- ----------------------------------------------------------------------------- -- | @conflicts (r,e) node@ is @False@ if and only if the assignment -- @r = e@ can be safely commuted past statement @node@. conflicts :: DynFlags -> Assignment -> CmmNode O x -> Bool conflicts dflags (r, rhs, addr) node -- (1) node defines registers used by rhs of assignment. This catches -- assignments and all three kinds of calls. See Note [Sinking and calls] | globalRegistersConflict dflags rhs node = True | localRegistersConflict dflags rhs node = True -- (2) node uses register defined by assignment | foldRegsUsed dflags (\b r' -> r == r' || b) False node = True -- (3) a store to an address conflicts with a read of the same memory | CmmStore addr' e <- node , memConflicts addr (loadAddr dflags addr' (cmmExprWidth dflags e)) = True -- (4) an assignment to Hp/Sp conflicts with a heap/stack read respectively | HeapMem <- addr, CmmAssign (CmmGlobal Hp) _ <- node = True | StackMem <- addr, CmmAssign (CmmGlobal Sp) _ <- node = True | SpMem{} <- addr, CmmAssign (CmmGlobal Sp) _ <- node = True -- (5) foreign calls clobber heap: see Note [Foreign calls clobber heap] | CmmUnsafeForeignCall{} <- node, memConflicts addr AnyMem = True -- (6) native calls clobber any memory | CmmCall{} <- node, memConflicts addr AnyMem = True -- (7) otherwise, no conflict | otherwise = False -- Returns True if node defines any global registers that are used in the -- Cmm expression globalRegistersConflict :: DynFlags -> CmmExpr -> CmmNode e x -> Bool globalRegistersConflict dflags expr node = foldRegsDefd dflags (\b r -> b || regUsedIn dflags (CmmGlobal r) expr) False node -- Returns True if node defines any local registers that are used in the -- Cmm expression localRegistersConflict :: DynFlags -> CmmExpr -> CmmNode e x -> Bool localRegistersConflict dflags expr node = foldRegsDefd dflags (\b r -> b || regUsedIn dflags (CmmLocal r) expr) False node -- Note [Sinking and calls] -- ~~~~~~~~~~~~~~~~~~~~~~~~ -- -- We have three kinds of calls: normal (CmmCall), safe foreign (CmmForeignCall) -- and unsafe foreign (CmmUnsafeForeignCall). We perform sinking pass after -- stack layout (see Note [Sinking after stack layout]) which leads to two -- invariants related to calls: -- -- a) during stack layout phase all safe foreign calls are turned into -- unsafe foreign calls (see Note [Lower safe foreign calls]). This -- means that we will never encounter CmmForeignCall node when running -- sinking after stack layout -- -- b) stack layout saves all variables live across a call on the stack -- just before making a call (remember we are not sinking assignments to -- stack): -- -- L1: -- x = R1 -- P64[Sp - 16] = L2 -- P64[Sp - 8] = x -- Sp = Sp - 16 -- call f() returns L2 -- L2: -- -- We will attempt to sink { x = R1 } but we will detect conflict with -- { P64[Sp - 8] = x } and hence we will drop { x = R1 } without even -- checking whether it conflicts with { call f() }. In this way we will -- never need to check any assignment conflicts with CmmCall. Remember -- that we still need to check for potential memory conflicts. -- -- So the result is that we only need to worry about CmmUnsafeForeignCall nodes -- when checking conflicts (see Note [Unsafe foreign calls clobber caller-save registers]). -- This assumption holds only when we do sinking after stack layout. If we run -- it before stack layout we need to check for possible conflicts with all three -- kinds of calls. Our `conflicts` function does that by using a generic -- foldRegsDefd and foldRegsUsed functions defined in DefinerOfRegs and -- UserOfRegs typeclasses. -- -- An abstraction of memory read or written. data AbsMem = NoMem -- no memory accessed | AnyMem -- arbitrary memory | HeapMem -- definitely heap memory | StackMem -- definitely stack memory | SpMem -- <size>[Sp+n] {-# UNPACK #-} !Int {-# UNPACK #-} !Int -- Having SpMem is important because it lets us float loads from Sp -- past stores to Sp as long as they don't overlap, and this helps to -- unravel some long sequences of -- x1 = [Sp + 8] -- x2 = [Sp + 16] -- ... -- [Sp + 8] = xi -- [Sp + 16] = xj -- -- Note that SpMem is invalidated if Sp is changed, but the definition -- of 'conflicts' above handles that. -- ToDo: this won't currently fix the following commonly occurring code: -- x1 = [R1 + 8] -- x2 = [R1 + 16] -- .. -- [Hp - 8] = x1 -- [Hp - 16] = x2 -- .. -- because [R1 + 8] and [Hp - 8] are both HeapMem. We know that -- assignments to [Hp + n] do not conflict with any other heap memory, -- but this is tricky to nail down. What if we had -- -- x = Hp + n -- [x] = ... -- -- the store to [x] should be "new heap", not "old heap". -- Furthermore, you could imagine that if we started inlining -- functions in Cmm then there might well be reads of heap memory -- that was written in the same basic block. To take advantage of -- non-aliasing of heap memory we will have to be more clever. -- Note [Foreign calls clobber heap] -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- -- It is tempting to say that foreign calls clobber only -- non-heap/stack memory, but unfortunately we break this invariant in -- the RTS. For example, in stg_catch_retry_frame we call -- stmCommitNestedTransaction() which modifies the contents of the -- TRec it is passed (this actually caused incorrect code to be -- generated). -- -- Since the invariant is true for the majority of foreign calls, -- perhaps we ought to have a special annotation for calls that can -- modify heap/stack memory. For now we just use the conservative -- definition here. -- -- Some CallishMachOp imply a memory barrier e.g. AtomicRMW and -- therefore we should never float any memory operations across one of -- these calls. bothMems :: AbsMem -> AbsMem -> AbsMem bothMems NoMem x = x bothMems x NoMem = x bothMems HeapMem HeapMem = HeapMem bothMems StackMem StackMem = StackMem bothMems (SpMem o1 w1) (SpMem o2 w2) | o1 == o2 = SpMem o1 (max w1 w2) | otherwise = StackMem bothMems SpMem{} StackMem = StackMem bothMems StackMem SpMem{} = StackMem bothMems _ _ = AnyMem memConflicts :: AbsMem -> AbsMem -> Bool memConflicts NoMem _ = False memConflicts _ NoMem = False memConflicts HeapMem StackMem = False memConflicts StackMem HeapMem = False memConflicts SpMem{} HeapMem = False memConflicts HeapMem SpMem{} = False memConflicts (SpMem o1 w1) (SpMem o2 w2) | o1 < o2 = o1 + w1 > o2 | otherwise = o2 + w2 > o1 memConflicts _ _ = True exprMem :: DynFlags -> CmmExpr -> AbsMem exprMem dflags (CmmLoad addr w) = bothMems (loadAddr dflags addr (typeWidth w)) (exprMem dflags addr) exprMem dflags (CmmMachOp _ es) = foldr bothMems NoMem (map (exprMem dflags) es) exprMem _ _ = NoMem loadAddr :: DynFlags -> CmmExpr -> Width -> AbsMem loadAddr dflags e w = case e of CmmReg r -> regAddr dflags r 0 w CmmRegOff r i -> regAddr dflags r i w _other | regUsedIn dflags (CmmGlobal Sp) e -> StackMem | otherwise -> AnyMem regAddr :: DynFlags -> CmmReg -> Int -> Width -> AbsMem regAddr _ (CmmGlobal Sp) i w = SpMem i (widthInBytes w) regAddr _ (CmmGlobal Hp) _ _ = HeapMem regAddr _ (CmmGlobal CurrentTSO) _ _ = HeapMem -- important for PrimOps regAddr dflags r _ _ | isGcPtrType (cmmRegType dflags r) = HeapMem -- yay! GCPtr pays for itself regAddr _ _ _ _ = AnyMem {- Note [Inline GlobalRegs?] Should we freely inline GlobalRegs? Actually it doesn't make a huge amount of difference either way, so we *do* currently treat GlobalRegs as "trivial" and inline them everywhere, but for what it's worth, here is what I discovered when I (SimonM) looked into this: Common sense says we should not inline GlobalRegs, because when we have x = R1 the register allocator will coalesce this assignment, generating no code, and simply record the fact that x is bound to $rbx (or whatever). Furthermore, if we were to sink this assignment, then the range of code over which R1 is live increases, and the range of code over which x is live decreases. All things being equal, it is better for x to be live than R1, because R1 is a fixed register whereas x can live in any register. So we should neither sink nor inline 'x = R1'. However, not inlining GlobalRegs can have surprising consequences. e.g. (cgrun020) c3EN: _s3DB::P64 = R1; _c3ES::P64 = _s3DB::P64 & 7; if (_c3ES::P64 >= 2) goto c3EU; else goto c3EV; c3EU: _s3DD::P64 = P64[_s3DB::P64 + 6]; _s3DE::P64 = P64[_s3DB::P64 + 14]; I64[Sp - 8] = c3F0; R1 = _s3DE::P64; P64[Sp] = _s3DD::P64; inlining the GlobalReg gives: c3EN: if (R1 & 7 >= 2) goto c3EU; else goto c3EV; c3EU: I64[Sp - 8] = c3F0; _s3DD::P64 = P64[R1 + 6]; R1 = P64[R1 + 14]; P64[Sp] = _s3DD::P64; but if we don't inline the GlobalReg, instead we get: _s3DB::P64 = R1; if (_s3DB::P64 & 7 >= 2) goto c3EU; else goto c3EV; c3EU: I64[Sp - 8] = c3F0; R1 = P64[_s3DB::P64 + 14]; P64[Sp] = P64[_s3DB::P64 + 6]; This looks better - we managed to inline _s3DD - but in fact it generates an extra reg-reg move: .Lc3EU: movq $c3F0_info,-8(%rbp) movq %rbx,%rax movq 14(%rbx),%rbx movq 6(%rax),%rax movq %rax,(%rbp) because _s3DB is now live across the R1 assignment, we lost the benefit of coalescing. Who is at fault here? Perhaps if we knew that _s3DB was an alias for R1, then we would not sink a reference to _s3DB past the R1 assignment. Or perhaps we *should* do that - we might gain by sinking it, despite losing the coalescing opportunity. Sometimes not inlining global registers wins by virtue of the rule about not inlining into arguments of a foreign call, e.g. (T7163) this is what happens when we inlined F1: _s3L2::F32 = F1; _c3O3::F32 = %MO_F_Mul_W32(F1, 10.0 :: W32); (_s3L7::F32) = call "ccall" arg hints: [] result hints: [] rintFloat(_c3O3::F32); but if we don't inline F1: (_s3L7::F32) = call "ccall" arg hints: [] result hints: [] rintFloat(%MO_F_Mul_W32(_s3L2::F32, 10.0 :: W32)); -}
urbanslug/ghc
compiler/cmm/CmmSink.hs
Haskell
bsd-3-clause
29,851
module Models.Task where import Control.Monad.IO.Class (MonadIO, liftIO) import Control.Monad.Logger (NoLoggingT, runNoLoggingT) import Control.Monad.Trans.Resource (ResourceT, runResourceT) import Data.Text (Text) import Data.Time (UTCTime) import Database.Persist (Entity, Key, SelectOpt(LimitTo), (=.), deleteWhere, selectList) import Database.Persist.Sql (SqlBackend, ToBackendKey, delete, insert, toSqlKey, update) import Database.Persist.Sqlite (SqlPersistT, runSqlConn, withSqliteConn) import Database.Persist.TH (mkMigrate, mkPersist, persistLowerCase, share, sqlSettings) import Database.Persist.Types (PersistValue(PersistInt64)) share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase| Task title String content Text createdAt UTCTime done Bool deriving Show |] runDb :: SqlPersistT (ResourceT (NoLoggingT IO)) a -> IO a runDb query = runNoLoggingT . runResourceT . withSqliteConn "dev.sqlite3" . runSqlConn $ query readTasks :: IO [Entity Task] readTasks = (runDb $ selectList [] [LimitTo 10]) saveTask :: MonadIO m => String -> Text -> UTCTime -> m (Key Task) saveTask title content time = liftIO $ runDb $ insert $ Task title content time False toKey :: ToBackendKey SqlBackend a => Integer -> Key a toKey i = toSqlKey $ fromIntegral (i :: Integer) markTaskAsDone :: MonadIO m => Integer -> UTCTime -> m () markTaskAsDone id_ time = liftIO $ runDb $ update (toKey id_ :: TaskId) [TaskDone =. True] deleteTask :: MonadIO m => Integer -> m () deleteTask id_ = liftIO $ runDb $ delete (toKey id_ :: TaskId)
quephird/todo.hs
src/Models/Task.hs
Haskell
mit
1,563
module Logic.Data.Units where import Logic.Types import qualified Data.Map as Map import Control.Lens unitsBase :: Map.Map UnitType UnitData unitsBase = Map.fromList [ (UnitType 1, marine) ] marine = UnitData { _maxHp = 50, _attackValue = 8, _attackSpeed = 0.5, _movementSpeed = 0.5 }
HarvestGame/logic-prototype
src/Logic/Data/Units.hs
Haskell
mit
331
-- -- -- ------------------ -- Exercise 13.24. ------------------ -- -- -- module E'13'24 where
pascal-knodel/haskell-craft
Chapter 13/E'13'24.hs
Haskell
mit
106
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} -- | Copyright 2014-2015 Anchor Systems, Pty Ltd and Others -- -- The code in this file, and the program it is a part of, is -- made available to you by its authors as open source software: -- you can redistribute it and/or modify it under the terms of -- the 3-clause BSD licence. -- -- /Description/ -- This module defines the Result type and how it's presented. -- module Borel.Types.Result ( -- * Query results Result , ResponseItem(..) , respResource, respResourceID, respVal , mkItem -- * Convenient , uomVal ) where import Control.Applicative import Control.Lens hiding ((.=)) import Control.Monad import Data.Aeson hiding (Result) import Data.Csv (FromRecord, ToRecord, parseRecord, record, toField, toRecord, (.!)) import Data.Text (Text) import qualified Data.Vector as V import Data.Word import Ceilometer.Tags import Vaultaire.Types import Borel.Error import Borel.Types.Metric import Borel.Types.UOM type Result = (Metric, Word64) type Val = (UOM, Word64) data ResponseItem = ResponseItem { _respResource :: Text , _respResourceID :: Text , _respVal :: Val } deriving (Eq, Show, Read) makeLenses ''ResponseItem instance FromJSON ResponseItem where parseJSON (Object x) = ResponseItem <$> x .: "resource" <*> x .: "resource-id" <*> ((,) <$> x .: "uom" <*> x .: "quantity") parseJSON _ = mzero instance ToJSON ResponseItem where toJSON (ResponseItem n i (u,x)) = object [ "resource" .= n , "resource-id" .= i , "uom" .= u , "quantity" .= x ] instance FromRecord ResponseItem where parseRecord v | V.length v == 4 = ResponseItem <$> v .! 0 <*> v .! 1 <*> ((,) <$> v .! 2 <*> v .! 3) | otherwise = mzero instance ToRecord ResponseItem where toRecord (ResponseItem n i (u,v)) = record [ toField n , toField i , toField u , toField v ] mkItem :: SourceDict -> Result -> ResponseItem mkItem sd (metric, quantity) = let name = pretty metric uid = stopBorelError $ lookupSD keyResourceID sd in ResponseItem name uid (uom metric, quantity) -- Some convenient traversals uomVal :: Lens' ResponseItem Val uomVal f (ResponseItem x y v) = ResponseItem x y <$> f v
anchor/borel
lib/Borel/Types/Result.hs
Haskell
mit
2,690
{-# LANGUAGE GeneralizedNewtypeDeriving #-} {- | Module : Orville.PostgreSQL.Expr.Where.ValueExpression Copyright : Flipstone Technology Partners 2016-2021 License : MIT -} module Orville.PostgreSQL.Internal.Expr.ValueExpression ( ValueExpression, columnReference, valueExpression, rowValueConstructor, ) where import qualified Data.List.NonEmpty as NE import Orville.PostgreSQL.Internal.Expr.Name (ColumnName) import qualified Orville.PostgreSQL.Internal.RawSql as RawSql import Orville.PostgreSQL.Internal.SqlValue (SqlValue) newtype ValueExpression = ValueExpression RawSql.RawSql deriving (RawSql.SqlExpression) columnReference :: ColumnName -> ValueExpression columnReference = ValueExpression . RawSql.toRawSql valueExpression :: SqlValue -> ValueExpression valueExpression = ValueExpression . RawSql.parameter rowValueConstructor :: NE.NonEmpty ValueExpression -> ValueExpression rowValueConstructor elements = ValueExpression $ RawSql.leftParen <> RawSql.intercalate RawSql.comma elements <> RawSql.rightParen
flipstone/orville
orville-postgresql-libpq/src/Orville/PostgreSQL/Internal/Expr/ValueExpression.hs
Haskell
mit
1,066
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} -- | -- Module: Network.SIP.Parser.ResponseLine -- Description: Response line parser. -- Copyright: Copyright (c) 2015-2016 Jan Sipr -- License: MIT module Network.SIP.Parser.ResponseLine ( firstLineParser ) where import Control.Applicative ((<*)) import Control.Monad ((>>=), return, fail) import Data.Attoparsec.ByteString.Char8 (char, decimal) import Data.Attoparsec.ByteString (Parser, takeByteString) import Data.Bool ((&&), otherwise) import Data.Function (($), (.)) import Data.Functor (fmap) import Data.List (lookup) import Data.Maybe (maybe) import Data.Monoid ((<>)) import Data.Ord ((<), (>=)) import Data.Text.Encoding (decodeUtf8) import Data.Tuple (fst, snd) import Text.Show (show) import Network.SIP.Parser.SipVersion (sipVersionParser) import Network.SIP.Type.Message (MessageType(Response)) import Network.SIP.Type.ResponseStatus ( ResponseCode(Unknown) , Status(Status) , UnknownResponseCode ( Unknown_1xx , Unknown_2xx , Unknown_3xx , Unknown_4xx , Unknown_5xx , Unknown_6xx ) , responseStatusMap ) firstLineParser :: Parser MessageType firstLineParser = do _ <- sipVersionParser <* char ' ' code <- (decimal <* char ' ') >>= typeStatusCode statusMsg <- fmap decodeUtf8 takeByteString return . Response $ Status code statusMsg where typeStatusCode c = maybe (unknownStatusCode c) return $ lookup c $ fmap (\x -> (fst $ snd x, fst x)) responseStatusMap unknownStatusCode c | c >= 100 && c < 200 = return $ Unknown Unknown_1xx | c < 300 = return $ Unknown Unknown_2xx | c < 400 = return $ Unknown Unknown_3xx | c < 500 = return $ Unknown Unknown_4xx | c < 600 = return $ Unknown Unknown_5xx | c < 700 = return $ Unknown Unknown_6xx | otherwise = fail $ "Status code must be bettwen <100 - 699>, but this one is: " <> show c
Siprj/ragnarok
src/Network/SIP/Parser/ResponseLine.hs
Haskell
mit
2,017
-- Copyright (C) 2014 Google Inc. All rights reserved. -- -- Licensed under the Apache License, Version 2.0 (the "License"); you may not -- use this file except in compliance with the License. You may obtain a copy -- of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -- WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -- License for the specific language governing permissions and limitations -- under the License. module Gemstone.Maths where -- | Modified Moving Average. mma :: Fractional a => a -> a -> a mma new old = (19 * old + new) / 20
MostAwesomeDude/gemstone
Gemstone/Maths.hs
Haskell
mit
739
a = fmap (+1) $ read "[1]" :: [Int] b = (fmap . fmap) (++ "lol") (Just ["Hi,","Hello"]) -- same as (*2) . (\x -> x - 2) c = fmap (*2) (\x -> x - 2) d = fmap ((return '1'++) . show) (\x -> [x,1..3]) e :: IO Integer e = let ioi = readIO "1" :: IO Integer --changed = fmap read $ fmap ("123"++) $ fmap show ioi changed = fmap (read . ("123"++) . show) ioi in fmap (*3) changed
JustinUnger/haskell-book
ch16/functor-ex1.hs
Haskell
mit
399
{-- Copyright (c) 2012 Gorka Suárez García 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. --} -- *************************************************************** -- Primes example application -- Make: ghc -main-is Primes Primes.hs -- *************************************************************** module Primes (main) where squareRoot :: (Integral a) => a -> a squareRoot x = truncate $ sqrt $ fromIntegral x multipleOf :: (Integral a) => a -> a -> Bool multipleOf a b = (mod a b) == 0 isPrime :: (Integral a) => a -> Bool isPrime 2 = True isPrime n = not $ or [multipleOf n x | x <- 2:[3,5..upperLimit]] where upperLimit = squareRoot n + 1 primeTest n = do putStrLn (show n ++ " is prime?") putStrLn (show $ isPrime n) main = primeTest 1234567891
gorkinovich/Haskell
Others/Primes.hs
Haskell
mit
1,751
{-# htermination (compareChar :: Char -> Char -> Ordering) #-} import qualified Prelude data MyBool = MyTrue | MyFalse data List a = Cons a (List a) | Nil data Char = Char MyInt ; data MyInt = Pos Nat | Neg Nat ; data Nat = Succ Nat | Zero ; data Ordering = LT | EQ | GT ; primCmpNat :: Nat -> Nat -> Ordering; primCmpNat Zero Zero = EQ; primCmpNat Zero (Succ y) = LT; primCmpNat (Succ x) Zero = GT; primCmpNat (Succ x) (Succ y) = primCmpNat x y; primCmpInt :: MyInt -> MyInt -> Ordering; primCmpInt (Pos Zero) (Pos Zero) = EQ; primCmpInt (Pos Zero) (Neg Zero) = EQ; primCmpInt (Neg Zero) (Pos Zero) = EQ; primCmpInt (Neg Zero) (Neg Zero) = EQ; primCmpInt (Pos x) (Pos y) = primCmpNat x y; primCmpInt (Pos x) (Neg y) = GT; primCmpInt (Neg x) (Pos y) = LT; primCmpInt (Neg x) (Neg y) = primCmpNat y x; primCmpChar :: Char -> Char -> Ordering; primCmpChar (Char x) (Char y) = primCmpInt x y; compareChar :: Char -> Char -> Ordering compareChar = primCmpChar;
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/basic_haskell/compare_4.hs
Haskell
mit
993
module SSH.Key ( KeyBox , PublicKey(..) , PrivateKey(..) , parseKey , serialiseKey , publicKeys , privateKeys , putPublicKey ) where import Control.Applicative ((<$>), (<*>)) import Control.Monad (unless, replicateM) import Data.Binary.Get (Get, getWord32be, getByteString, getRemainingLazyByteString) import Data.Binary.Put (Put, putWord32be, putByteString) import qualified Data.ByteString as B import qualified Data.ByteString.Base64 as B64 import qualified Data.ByteString.Char8 as BC import Data.ByteString.Lazy (toStrict) import Data.Monoid ((<>)) import SSH.Types (getWord32be', getString, putString, runStrictGet, runStrictPut) data KeyBox = KeyBox { ciphername :: B.ByteString , _kdfname :: B.ByteString , _kdfoptions :: B.ByteString , keycount :: Int , boxPublicKeys :: B.ByteString , boxPrivateKeys :: B.ByteString } deriving (Show) auth_magic :: B.ByteString auth_magic = "openssh-key-v1\000" expected_padding :: B.ByteString expected_padding = BC.pack ['\001'..'\377'] armor_start :: B.ByteString armor_start = "-----BEGIN OPENSSH PRIVATE KEY-----" armor_end :: B.ByteString armor_end = "-----END OPENSSH PRIVATE KEY-----" data PublicKey = Ed25519PublicKey { publicKeyData :: B.ByteString } deriving (Show) data PrivateKey = Ed25519PrivateKey { publicKey :: PublicKey , privateKeyData :: B.ByteString , privateKeyComment :: B.ByteString } deriving (Show) dearmorPrivateKey :: B.ByteString -> Either String B.ByteString dearmorPrivateKey = B64.decode . B.concat . takeWhile (/= armor_end) . drop 1 . dropWhile (/= armor_start) . BC.lines armorPrivateKey :: B.ByteString -> B.ByteString armorPrivateKey k = armor_start <> "\n" <> B64.joinWith "\n" 70 (B64.encode k) <> armor_end <> "\n" getKeyBox :: Get KeyBox getKeyBox = do magic <- getByteString (B.length auth_magic) unless (magic == auth_magic) (fail "Magic does not match") cn <- getString unless (cn == "none") (fail "Unsupported cipher") kn <- getString unless (kn == "none") (fail "Unsupported kdf") ko <- getString unless (ko == "") (fail "Invalid kdf options") count <- getWord32be' publicData <- getString privateData <- getString return $ KeyBox cn kn ko count publicData privateData putKeyBox :: PrivateKey -> Put putKeyBox key = do putByteString auth_magic putString "none" putString "none" putString "" putWord32be 1 putPublicKeys [publicKey key] putPrivateKeys [key] publicKeys :: KeyBox -> [PublicKey] publicKeys box = flip runStrictGet (boxPublicKeys box) $ replicateM (keycount box) $ do keyType <- getString case keyType of "ssh-ed25519" -> Ed25519PublicKey <$> getString _ -> fail "Unsupported key type" putPublicKeys :: [PublicKey] -> Put putPublicKeys = putString . runStrictPut . mapM_ putPublicKey putPublicKey :: PublicKey -> Put putPublicKey (Ed25519PublicKey k) = do putString "ssh-ed25519" putString k getPrivateKey :: Get PrivateKey getPrivateKey = do keyType <- getString case keyType of "ssh-ed25519" -> Ed25519PrivateKey <$> (Ed25519PublicKey <$> getString) <*> getString <*> getString _ -> fail "Unsupported key type" putPrivateKey :: PrivateKey -> Put putPrivateKey (Ed25519PrivateKey pk k c) = do putString "ssh-ed25519" putString (publicKeyData pk) putString k putString c getPrivateKeys :: Int -> Get [PrivateKey] getPrivateKeys count = do checkint1 <- getWord32be checkint2 <- getWord32be unless (checkint1 == checkint2) (fail "Decryption failed") keys <- replicateM count getPrivateKey padding <- toStrict <$> getRemainingLazyByteString unless (B.take (B.length padding) expected_padding == padding) (fail "Incorrect padding") return keys putPrivateKeys :: [PrivateKey] -> Put putPrivateKeys keys = putString . pad 8 . runStrictPut $ do putWord32be 0 putWord32be 0 mapM_ putPrivateKey keys where pad a s | B.length s `rem` a == 0 = s | otherwise = s <> B.take (a - B.length s `rem` a) expected_padding privateKeys :: KeyBox -> [PrivateKey] privateKeys box | ciphername box == "none" = runStrictGet (getPrivateKeys $ keycount box) (boxPrivateKeys box) | otherwise = error "Unsupported encryption type" parseKey :: BC.ByteString -> Either String KeyBox parseKey = fmap (runStrictGet getKeyBox) . dearmorPrivateKey serialiseKey :: PrivateKey -> B.ByteString serialiseKey = armorPrivateKey . runStrictPut . putKeyBox
mithrandi/ssh-key-generator
SSH/Key.hs
Haskell
mit
4,843
-- | Traversing mutable vectors. module Data.Vector.Generic.Mutable.Loops where import Control.Monad.Primitive import Data.Vector.Generic.Mutable as MG type Loop m v a = v (PrimState m) a -> (a -> m ()) -> m () type ILoop m v a = v (PrimState m) a -> (Int -> a -> m ()) -> m () {-# INLINE iForM_ #-} iForM_ :: (MG.MVector v a, PrimMonad m) => ILoop m v a iForM_ v f = for' 0 (MG.length v) $ \i -> MG.unsafeRead v i >>= f i {-# INLINE forM_ #-} forM_ :: (MG.MVector v a, PrimMonad m) => Loop m v a forM_ v = iForM_ v . const -- @forM_ [0 .. n-1]@ somehow runs out of memory for' i n f | i == n = return () for' i n f = f i >> for' (i+1) n f
Lysxia/twentyseven
src/Data/Vector/Generic/Mutable/Loops.hs
Haskell
mit
645
module Main ( main ) where import OpenGLRenderer import Utils import Utils.GL import Tiles import Tiles.Renderer import TestTiles as TT import TestRenderer import Data.Map (fromList) import Data.IORef import Graphics.UI.GLUT hiding (Point) player1 = Owner "1" "xxPLAYERxx" player2 = Owner "2" "__player__" coords :: [TileId] coords = [Point x y | x <- [0, 5], y <- [0, 1]] --coords = do -- x <- [0, 1] -- y <- [0, 1] -- return $ Coordinate x y --coords = [0, 1] >>= ( -- \x -> [0, 1] >>= ( -- \y -> -- return $ Coordinate x y -- ) -- ) tls :: [TT.Tile] tls = [ Tile (Point 0 0) Sea (Nothing, Storm) [] , Tile (Point 0 1) Sea (Nothing, Storm) [] , Tile (Point 1 0) Sea (Nothing, Rain) [] , Tile (Point 1 1) Sea (Nothing, Storm) [] , Tile (Point 2 0) Sea (Nothing, Rain) [] , Tile (Point 2 1) Sea (Nothing, Storm) [] , Tile (Point 3 0) Sea (Nothing, Rain) [] , Tile (Point 3 1) Plain (Just player1, Cloudy) [] , Tile (Point 4 0) Hill (Just player2, Rain) [] , Tile (Point 4 1) Mountain (Nothing, Sunny) [] ] neighbours :: Neighbours TileId neighbours = fromList $ map f tls where f = \(Tile id _ _ _) -> (id, filter (id /=) coords) type World = TT.Map world :: World world = Tiles.Map (mkTiles tls) Main.neighbours reshaped :: ReshapeCallback --Mutator World reshaped size = do putStrLn $ "viewport" viewport $= (mkPosition 0 0, mkSize 400 400) -- size postRedisplay Nothing mkPosition :: Int -> Int -> Position mkPosition x y = Position (glInt x) (glInt y) mkSize :: Int -> Int -> Size mkSize w h = Size (glInt w) (glInt h) keyCallbacks :: Maybe (Window -> IORef(Camera Int) -> KeyboardCallback) keyCallbacks = Just $ \w -> \cRef -> \key pos -> case key of '\ESC' -> do destroyWindow w _ -> return () --putStrLn $ "key " ++ show key keySpecialCallbacks :: Maybe (Window -> IORef(Camera Int) -> SpecialCallback) keySpecialCallbacks = Just $ \w -> \cRef -> \key pos -> case key of KeyUp -> moveCamera cRef Main.Up KeyRight -> moveCamera cRef Main.Right KeyDown -> moveCamera cRef Main.Down KeyLeft -> moveCamera cRef Main.Left _ -> return () initialCamera = Rect { topLeft = Point 0 0 , bottomRight = Point 5 5 } data Direction = Left | Right | Up | Down deriving Show moveCamera :: IORef (Camera Int) -> Direction -> IO() moveCamera cameraRef dir = do camera <- readIORef cameraRef putStrLn $ "dir = " ++ show dir let updCamera fx fy = Rect ptT ptB where ffx g = fx . x . g $ camera ffy g = fy . y . g $ camera ptT = Point (ffx topLeft) (ffy topLeft) ptB = Point (ffx bottomRight) (ffy bottomRight) let id x = x let minus1 x = x - 1 let plus1 x = x + 1 let nCamera = case dir of Main.Left -> updCamera minus1 id Main.Right -> updCamera plus1 id Main.Up -> updCamera id plus1 Main.Down -> updCamera id minus1 writeIORef cameraRef nCamera postRedisplay Nothing cameraVar :: IO( IORef (Camera Int) ) cameraVar = newIORef initialCamera render :: IORef (Camera Int) -> Renderer World render cameraRef = do renderMap before after cameraRef where before = do clear [ColorBuffer] loadIdentity color $ rgb2GLcolor 255 255 255 renderPrimitive Quads $ tileQuad (1 :: GLfloat) after = flush callbacks = Callbacks{ callReshape = Nothing , callKey = keyCallbacks , callSpecKey = keySpecialCallbacks } main :: IO() main = run cameraVar render Nothing callbacks world
fehu/hgt
tiles-test/src/Main.hs
Haskell
mit
4,728
{- -- LoGoff system -} module Logoff where import Datatypes import Data.Maybe {------------------------------------------------------------------------------} -- Axiom block {------------------------------------------------------------------------------} -- isAx verifies if a sequent is an Ax-type axiom isAx :: Sequent -> Bool isAx (RFocus (IStruct (P (Positive i))) (P (Positive o))) = o == i isAx _ = False -- isCoAx verifies if a sequent is a CoAx-type axiom isCoAx :: Sequent -> Bool isCoAx (LFocus (N (Negative i)) (OStruct (N (Negative o)))) = o == i isCoAx _ = False {------------------------------------------------------------------------------} -- Focusing block -- Note that if the functions can't treat the given sequent, they return it {------------------------------------------------------------------------------} -- Defocus right (or top-down focus right) defocusR :: Sequent -> Sequent defocusR (RFocus i (P o)) = Neutral i (OStruct (P o)) defocusR s = s -- Inverse defocus right (top-down focus right) idefocusR :: Sequent -> Sequent idefocusR (Neutral i (OStruct (P o))) = RFocus i (P o) idefocusR s = s -- Defocus left (or top-down focus left) defocusL :: Sequent -> Sequent defocusL (LFocus (N i) o) = Neutral (IStruct (N i)) o defocusL s = s -- Inverse defocus left (top-down focus left) idefocusL :: Sequent -> Sequent idefocusL (Neutral (IStruct (N i)) o) = LFocus (N i) o idefocusL s = s -- Focus right (or top-down defocus right) focusR :: Sequent -> Sequent focusR (Neutral i (OStruct (N o))) = RFocus i (N o) focusR s = s -- Inverse focus right (top-down defocus right) ifocusR :: Sequent -> Sequent ifocusR (RFocus i (N o)) = Neutral i (OStruct (N o)) ifocusR s = s -- Focus left (or top-down defocus left) focusL :: Sequent -> Sequent focusL (Neutral (IStruct (P i)) o) = LFocus (P i) o focusL s = s -- Inverse focus left (top-down defocus left) ifocusL :: Sequent -> Sequent ifocusL (LFocus (P i) o) = Neutral (IStruct (P i)) o ifocusL s = s {------------------------------------------------------------------------------} -- Monotonicity block -- Note that if the functions can't treat the given sequent, they return the -- left one {------------------------------------------------------------------------------} -- Tensor - introduces tensor monoTensor :: Sequent -> Sequent -> Sequent monoTensor (RFocus xi xo) (RFocus yi yo) = RFocus (STensor xi yi) (P (Tensor xo yo)) monoTensor l r = l -- Sum - introduces sum monoSum :: Sequent -> Sequent -> Sequent monoSum (LFocus xi xo) (LFocus yi yo) = LFocus (N (Sum xi yi)) (SSum xo yo) monoSum l r = l -- Left division - introduces LDiv monoLDiv :: Sequent -> Sequent -> Sequent monoLDiv (RFocus xi xo) (LFocus yi yo) = LFocus (N (LDiv xo yi)) (SLDiv xi yo) monoLDiv l r = l -- Right division - introduces RDiv monoRDiv :: Sequent -> Sequent -> Sequent monoRDiv (LFocus yi yo) (RFocus xi xo) = LFocus (N (RDiv yi xo)) (SRDiv yo xi) monoRDiv l r = l -- Left difference - introduces LDiff monoLDiff :: Sequent -> Sequent -> Sequent monoLDiff (LFocus yi yo) (RFocus xi xo) = RFocus (SLDiff yo xi) (P (LDiff yi xo)) monoLDiff l r = l -- Right difference - introduces RDiff monoRDiff :: Sequent -> Sequent -> Sequent monoRDiff (RFocus xi xo) (LFocus yi yo) = RFocus (SRDiff xi yo) (P (RDiff xo yi)) monoRDiff l r = l {------------------------------------------------------------------------------} -- Inverse monotonicity block -- Note that if the functions can't treat the given sequent, they return it {------------------------------------------------------------------------------} -- Tensor - removes tensor iMonoTensor :: Sequent -> (Sequent, Sequent) iMonoTensor (RFocus (STensor xi yi) (P (Tensor xo yo))) = (RFocus xi xo, RFocus yi yo) iMonoTensor s = (s,s) -- Sum - removes sum iMonoSum :: Sequent -> (Sequent, Sequent) iMonoSum (LFocus (N (Sum xi yi)) (SSum xo yo)) = (LFocus xi xo, LFocus yi yo) iMonoSum s = (s,s) -- Left division - removes LDiv iMonoLDiv :: Sequent -> (Sequent, Sequent) iMonoLDiv (LFocus (N (LDiv xo yi)) (SLDiv xi yo)) = (RFocus xi xo, LFocus yi yo) iMonoLDiv s = (s,s) -- Right division - removes RDiv iMonoRDiv :: Sequent -> (Sequent, Sequent) iMonoRDiv (LFocus (N (RDiv yi xo)) (SRDiv yo xi)) = (LFocus yi yo, RFocus xi xo) iMonoRDiv s = (s,s) -- Left difference - removes LDiff iMonoLDiff :: Sequent -> (Sequent, Sequent) iMonoLDiff (RFocus (SLDiff yo xi) (P (LDiff yi xo))) = (LFocus yi yo, RFocus xi xo) iMonoLDiff s = (s,s) -- Right difference - removes RDiff iMonoRDiff :: Sequent -> (Sequent, Sequent) iMonoRDiff (RFocus (SRDiff xi yo) (P (RDiff xo yi))) = (RFocus xi xo, LFocus yi yo) iMonoRDiff s = (s,s) {------------------------------------------------------------------------------} -- Residuation block -- Note that if the functions can't treat the given sequent, they return it {------------------------------------------------------------------------------} -- residuate1 - Downwards R1 rule residuate1 :: Int -> Sequent -> Sequent residuate1 1 (Neutral x (SRDiv z y)) = Neutral (STensor x y) z residuate1 2 (Neutral (STensor x y) z) = Neutral y (SLDiv x z) residuate1 _ s = s -- residuate1i - Upwards (inverted) R1 rule residuate1i :: Int -> Sequent -> Sequent residuate1i 2 (Neutral y (SLDiv x z)) = Neutral (STensor x y) z residuate1i 1 (Neutral (STensor x y) z) = Neutral x (SRDiv z y) residuate1i _ s = s -- residuate2 - Downwards R2 rule residuate2 :: Int -> Sequent -> Sequent residuate2 1 (Neutral (SLDiff y z) x) = Neutral z (SSum y x) residuate2 2 (Neutral z (SSum y x)) = Neutral (SRDiff z x) y residuate2 _ s = s -- residuate2i - Upwards (inverted) R2 rule residuate2i :: Int -> Sequent -> Sequent residuate2i 2 (Neutral (SRDiff z x) y) = Neutral z (SSum y x) residuate2i 1 (Neutral z (SSum y x)) = Neutral (SLDiff y z) x residuate2i _ s = s {------------------------------------------------------------------------------} -- Rewrite block -- Note that if the functions can't treat the given sequent, they return it {------------------------------------------------------------------------------} -- rewriteL - rewrites tensor, left and right difference (structure to logical) rewriteL :: Sequent -> Sequent rewriteL (Neutral (STensor (IStruct x) (IStruct y)) o) = Neutral (IStruct (P (Tensor x y))) o rewriteL (Neutral (SRDiff (IStruct x) (OStruct y)) o) = Neutral (IStruct (P (RDiff x y))) o rewriteL (Neutral (SLDiff (OStruct x) (IStruct y)) o) = Neutral (IStruct (P (LDiff x y))) o rewriteL s = s -- rewriteR - rewrites sum, left and right division (structure to logical) rewriteR :: Sequent -> Sequent rewriteR (Neutral i (SSum (OStruct x) (OStruct y))) = Neutral i (OStruct (N (Sum x y))) rewriteR (Neutral i (SRDiv (OStruct x) (IStruct y))) = Neutral i (OStruct (N (RDiv x y))) rewriteR (Neutral i (SLDiv (IStruct x) (OStruct y))) = Neutral i (OStruct (N (LDiv x y))) rewriteR s = s -- rewriteLi - rewrites tensor, left and right difference (logical to structure) rewriteLi :: Sequent -> Sequent rewriteLi (Neutral (IStruct (P (Tensor x y))) o) = Neutral (STensor (IStruct x) (IStruct y)) o rewriteLi (Neutral (IStruct (P (RDiff x y))) o) = Neutral (SRDiff (IStruct x) (OStruct y)) o rewriteLi (Neutral (IStruct (P (LDiff x y))) o) = Neutral (SLDiff (OStruct x) (IStruct y)) o rewriteLi s = s -- rewriteRi - rewrites sum, left and right division (logical to structure) rewriteRi :: Sequent -> Sequent rewriteRi (Neutral i (OStruct (N (Sum x y)))) = Neutral i (SSum (OStruct x) (OStruct y)) rewriteRi (Neutral i (OStruct (N (RDiv x y)))) = Neutral i (SRDiv (OStruct x) (IStruct y)) rewriteRi (Neutral i (OStruct (N (LDiv x y)))) = Neutral i (SLDiv (IStruct x) (OStruct y)) rewriteRi s = s {------------------------------------------------------------------------------} -- Top-Down solver block {------------------------------------------------------------------------------} -- tdSolve - Master Top-Down solver -- Also, yay maybe monad tdSolve :: Sequent -> Maybe ProofTree tdSolve s | isAx s = Just (Ax s) | isCoAx s = Just (CoAx s) | otherwise = case tdSolveRewrite s of Nothing -> case tdSolveMono s of Nothing -> case tdSolveFocus s of Nothing -> case tdSolveRes tdSolveResHelperList s of Nothing -> Nothing pt -> pt pt -> pt pt -> pt pt -> pt -- tdSolveHelperSpecial - master-solver following a residuation step to prevent -- residuation looping tdSolveHelperSpecial :: Residuation -> Sequent -> Maybe ProofTree tdSolveHelperSpecial res s | isAx s = Just (Ax s) | isCoAx s = Just (CoAx s) | otherwise = case tdSolveRewrite s of Nothing -> case tdSolveMono s of Nothing -> case tdSolveFocus s of Nothing -> case tdSolveRes (tdSolveResHelperPermit res) s of Nothing -> Nothing pt -> pt pt -> pt pt -> pt pt -> pt -- tdSolveRewrite - solves rewriting tdSolveRewrite :: Sequent -> Maybe ProofTree tdSolveRewrite s = let list = [(rewriteLi, RewriteL), (rewriteRi, RewriteR)] complist = map (\(f,o) -> (f s, o)) list res = dropWhile (\(ns, _) -> s == ns) complist in case res of ((ns, o):_) -> case tdSolve ns of (Just pt) -> Just (Unary s o pt) otherwise -> Nothing [] -> Nothing -- tdSolveFocus - solves focusing tdSolveFocus :: Sequent -> Maybe ProofTree tdSolveFocus s = let list = [(idefocusR, DeFocusR), (idefocusL, DeFocusL), (ifocusR, FocusR), (ifocusL, FocusL)] complist = map (\(f,o) -> (f s, o)) list res = dropWhile (\(ns, _) -> s == ns) complist in case res of ((ns, o):_) -> case tdSolve ns of (Just pt) -> Just (Unary s o pt) otherwise -> Nothing [] -> Nothing -- tdSolveMono - solves inverse monotonicity tdSolveMono :: Sequent -> Maybe ProofTree tdSolveMono s = let list = [(iMonoTensor, MonoTensor), (iMonoSum, MonoSum), (iMonoLDiv, MonoLDiv), (iMonoRDiv, MonoRDiv), (iMonoLDiff, MonoLDiff), (iMonoRDiff, MonoRDiff)] complist = map (\(f,o) -> (f s, o)) list res = dropWhile (\((ns,_), _) -> s == ns) complist in case res of (((ns1, ns2), o):_) -> case tdSolve ns1 of (Just pt1) -> case tdSolve ns2 of (Just pt2) -> Just (Binary s o pt1 pt2) otherwise -> Nothing otherwise -> Nothing [] -> Nothing -- tdSolveRes - solves residuation tdSolveRes :: [(Sequent -> Sequent, Residuation)] -> Sequent -> Maybe ProofTree tdSolveRes permit s = let complist = map (\(f, o) -> (f s, o)) permit residuations = [(ns, o) | (ns,o) <- complist, ns /= s] in case tdSolveResHelperOptions residuations of Nothing -> Nothing (Just (pt, res)) -> Just (Unary s (Res res) pt) -- tdSolveResHelperOptions - solves residuation, handles the actual branching tdSolveResHelperOptions :: [(Sequent, Residuation)] -> Maybe (ProofTree, Residuation) tdSolveResHelperOptions [] = Nothing tdSolveResHelperOptions ((s, res):xs) = case tdSolveHelperSpecial (tdSolveResHelperGetInverse res) s of Nothing -> tdSolveResHelperOptions xs (Just pt) -> Just (pt, res) -- tdSolveResHelperPermit - calculates new permit-list tdSolveResHelperPermit :: Residuation -> [(Sequent -> Sequent, Residuation)] tdSolveResHelperPermit res = filter (\(f, r) -> r /= res) tdSolveResHelperList -- tdSolveResHelperGetInverse tdSolveResHelperGetInverse :: Residuation -> Residuation tdSolveResHelperGetInverse (Res1 i) = Res1i i tdSolveResHelperGetInverse (Res1i i) = Res1 i tdSolveResHelperGetInverse (Res2 i) = Res2i i tdSolveResHelperGetInverse (Res2i i) = Res2 i -- tdSolveResHelperList - list of functions and operation mappings tdSolveResHelperList :: [(Sequent -> Sequent, Residuation)] tdSolveResHelperList = [(f i,o i) | (f,o) <- [(residuate1, Res1), (residuate2, Res2), (residuate1i, Res1i), (residuate2i, Res2i)], i <- [1,2]] {------------------------------------------------------------------------------} -- Bottom-up solver block {------------------------------------------------------------------------------} -- buSolve - master bottom-up solver -- First argument is the target string/type pair. Second is the master Lexicon buSolve :: LexItem -> Lexicon -> Maybe ProofTree buSolve (ts, tt) le = let le' = buDeriveLexicon (words ts) le pps = buPartial le' in case buCombine pps of (Just (ps, pt)) -> case buCoerce tt pt of (Just pt) -> let s = buExtractSequent pt s' = focusR s in if s' /= s then Just (Unary s' FocusR pt) else Nothing Nothing -> Nothing Nothing -> Nothing -- buDeriveLexicon - Builds the relevant Lexicon for the given target buDeriveLexicon :: [String] -> Lexicon -> Lexicon buDeriveLexicon [] _ = [] buDeriveLexicon (w:ws) ls = case buDeriveLexiconHelper w ls of [] -> [] (l:_) -> l : buDeriveLexicon ws ls -- buDeriveLexiconHelper - Runs the lexicon for each word buDeriveLexiconHelper :: String -> Lexicon -> Lexicon buDeriveLexiconHelper "" _ = [] buDeriveLexiconHelper _ [] = [] buDeriveLexiconHelper w (l@(s,_):ls) | w == s = [l] | otherwise = buDeriveLexiconHelper w ls -- buPartial - Generates partial proof trees for the derived lexicon buPartial :: Lexicon -> [PartialProof] buPartial [] = [] buPartial ((s,t):ls) = case tdSolve (buInsertionSequent t) of (Just pt) -> (s,pt) : buPartial ls Nothing -> [] -- buInsertionSequent - Generates the "insertion sequent"; the point where a -- lexical term enters the proof tree buInsertionSequent :: Formula -> Sequent buInsertionSequent f = rewriteRi (Neutral (IStruct f) (OStruct f)) -- buCombine - Combines the partial proofs to build a whole proof tree buCombine :: [PartialProof] -> Maybe PartialProof buCombine [] = Nothing buCombine [x] = Just x buCombine (l:r:xs) = case buCombinePair l r of (Just p) -> buCombine (p:xs) Nothing -> let p = buCombine (r:xs) in case p of (Just p) -> buCombine (l:[p]) Nothing -> Nothing -- buCombinePair - Attempts to combine a pair of partial proofs buCombinePair :: PartialProof -> PartialProof -> Maybe PartialProof buCombinePair (ls, lt) (rs, rt) = if buHasInsertion lt || buHasInsertion rt then case buCombinePairEval lt rt of (Just pt) -> Just (ls ++ " " ++ rs, pt) Nothing -> case buCombinePairEval rt lt of (Just pt) -> Just (ls ++ " " ++ rs, pt) Nothing -> Nothing else Nothing -- buCombinePairEval - Tries to attach the right tree to the left tree buCombinePairEval :: ProofTree -> ProofTree -> Maybe ProofTree buCombinePairEval lt rt = let ts = buCombineHelperGetType lt in case buCombinePairCoerce ts rt of (Just (pt, t)) -> case buCombinePairStitch t lt pt of (Just pt) -> Just (buRehash pt) Nothing -> Nothing Nothing -> Nothing -- buCombinePairCoerce - Tries to coerce all insertion sequent types buCombinePairCoerce :: [Formula] -> ProofTree -> Maybe (ProofTree, Formula) buCombinePairCoerce [] _ = Nothing buCombinePairCoerce (t:ts) pt = case buCoerce t pt of (Just pt) -> Just (pt, t) Nothing -> buCombinePairCoerce ts pt -- buCombinePairStitch - Stitches the right tree into the left where the right -- left tree has an insertion sequent of the given type buCombinePairStitch :: Formula -> ProofTree -> ProofTree -> Maybe ProofTree buCombinePairStitch t (Unary x o (Unary s DeFocusL lt)) rt = if buHelperExtractType s == Just t then Just (Unary x o rt) else case buCombinePairStitch t lt rt of (Just pt) -> Just (Unary x o (Unary s DeFocusL pt)) Nothing -> Nothing buCombinePairStitch t (Unary x o (Unary s DeFocusR lt)) rt = if buHelperExtractType s == Just t then Just (Unary x o rt) else case buCombinePairStitch t lt rt of (Just pt) -> Just (Unary x o (Unary s DeFocusR pt)) Nothing -> Nothing buCombinePairStitch t (Unary x o pt) rt = case buCombinePairStitch t pt rt of (Just pt) -> Just (Unary x o pt) Nothing -> Nothing buCombinePairStitch t (Binary x o pt1 pt2) rt = case buCombinePairStitch t pt1 rt of (Just pt) -> Just (Binary x o pt pt2) Nothing -> case buCombinePairStitch t pt2 rt of (Just pt) -> Just (Binary x o pt1 pt) Nothing -> Nothing buCombinePairStitch _ _ _ = Nothing -- buCombineHelperGetType - Gets the desired type of all insertion sequents buCombineHelperGetType :: ProofTree -> [Formula] buCombineHelperGetType (Unary _ _ (Unary s DeFocusL pt)) = case buHelperExtractType s of (Just t) -> t : buCombineHelperGetType pt Nothing -> buCombineHelperGetType pt buCombineHelperGetType (Unary _ _ (Unary s DeFocusR pt)) = case buHelperExtractType s of (Just t) -> t : buCombineHelperGetType pt Nothing -> buCombineHelperGetType pt buCombineHelperGetType (Unary _ _ pt) = buCombineHelperGetType pt buCombineHelperGetType (Binary _ _ pt1 pt2) = case buCombineHelperGetType pt1 of [] -> case buCombineHelperGetType pt2 of [] -> [] l -> l l -> l buCombineHelperGetType _ = [] -- buHelperExtractType -- Extracts the type from the sequent buHelperExtractType :: Sequent -> Maybe Formula buHelperExtractType (Neutral _ (OStruct f)) = Just f buHelperExtractType _ = Nothing -- buHasInsertion - Recursively searches a proof tree for insertion sequents buHasInsertion :: ProofTree -> Bool buHasInsertion (Ax _) = False buHasInsertion (CoAx _) = False buHasInsertion (Unary _ _ (Unary _ DeFocusL _)) = True buHasInsertion (Unary _ _ (Unary _ DeFocusR _)) = True buHasInsertion (Unary _ _ pt) = buHasInsertion pt buHasInsertion (Binary _ _ pt1 pt2) = buHasInsertion pt1 || buHasInsertion pt2 -- buCoerce - Attempts to force a proof tree to match a given type buCoerce :: Formula -> ProofTree -> Maybe ProofTree buCoerce t pt@(Unary s _ _) = case buCoerceTrivial t pt of (Just pt) -> Just pt otherwise -> let complist = map (\(f, o) -> (f s, o)) tdSolveResHelperList residuations = [(ns, o) | (ns,o) <- complist, ns /= s] in case buCoerceEval t residuations of (Just (s, res)) -> Just (Unary s (Res res) pt) Nothing -> Nothing -- buCoerceTrivial - Tests if coercion is needed buCoerceTrivial :: Formula -> ProofTree -> Maybe ProofTree buCoerceTrivial t pt@(Unary s _ _) = case buHelperExtractType s of (Just f) -> if f == t then Just pt else Nothing otherwise -> Nothing -- buCoerceEval - Evaluates a list of residuations buCoerceEval :: Formula -> [(Sequent, Residuation)] -> Maybe (Sequent, Residuation) buCoerceEval _ [] = Nothing buCoerceEval t ((s, res):xs) = case buHelperExtractType s of (Just f) -> if f == t then Just (s, res) else buCoerceEval t xs otherwise -> Nothing -- buRehash - Recursively rebuilds a proof tree to match combined trees buRehash :: ProofTree -> ProofTree buRehash pt = case pt of Ax {} -> pt CoAx {} -> pt Unary {} -> buRehashUnary pt Binary {} -> buRehashBinary pt -- buExtractSequent - Extracts the sequent from a proof-tree step buExtractSequent :: ProofTree -> Sequent buExtractSequent (Ax s) = s buExtractSequent (CoAx s) = s buExtractSequent (Unary s _ _) = s buExtractSequent (Binary s _ _ _) = s -- buRehashUnary - Rehashes unary steps in proof trees buRehashUnary :: ProofTree -> ProofTree buRehashUnary (Unary _ o pt) = let pt' = buRehash pt s = buExtractSequent pt' in Unary (buRehashUnaryEval s o) o pt' -- buRehashUnaryEval - Evaluates new unary sequents buRehashUnaryEval :: Sequent -> Operation -> Sequent buRehashUnaryEval s o = case o of DeFocusL -> defocusL s DeFocusR -> defocusR s FocusL -> focusL s FocusR -> focusR s RewriteL -> rewriteL s RewriteR -> rewriteR s (Res r) -> case r of (Res1 i) -> residuate1 i s (Res1i i) -> residuate1i i s (Res2 i) -> residuate2 i s (Res2i i) -> residuate2i i s -- buRehashBinary - Rehashes binary steps in proof trees buRehashBinary :: ProofTree -> ProofTree buRehashBinary (Binary _ o pt1 pt2) = let pt1' = buRehash pt1 pt2' = buRehash pt2 l = buExtractSequent pt1' r = buExtractSequent pt2' in Binary (buRehashBinaryEval l r o) o pt1' pt2' -- buRehashBinaryEval - Evaluates new binary sequents buRehashBinaryEval :: Sequent -> Sequent -> Operation -> Sequent buRehashBinaryEval l r o = case o of MonoTensor -> monoTensor l r MonoLDiff -> monoLDiff l r MonoRDiff -> monoRDiff l r MonoSum -> monoSum l r MonoLDiv -> monoLDiv l r MonoRDiv -> monoRDiv l r
DrSLDR/logoff
src/Logoff.hs
Haskell
mit
20,224
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE StrictData #-} {-# LANGUAGE TupleSections #-} -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancegroupconfig-scalingaction.html module Stratosphere.ResourceProperties.EMRInstanceGroupConfigScalingAction where import Stratosphere.ResourceImports import Stratosphere.ResourceProperties.EMRInstanceGroupConfigSimpleScalingPolicyConfiguration -- | Full data type definition for EMRInstanceGroupConfigScalingAction. See -- 'emrInstanceGroupConfigScalingAction' for a more convenient constructor. data EMRInstanceGroupConfigScalingAction = EMRInstanceGroupConfigScalingAction { _eMRInstanceGroupConfigScalingActionMarket :: Maybe (Val Text) , _eMRInstanceGroupConfigScalingActionSimpleScalingPolicyConfiguration :: EMRInstanceGroupConfigSimpleScalingPolicyConfiguration } deriving (Show, Eq) instance ToJSON EMRInstanceGroupConfigScalingAction where toJSON EMRInstanceGroupConfigScalingAction{..} = object $ catMaybes [ fmap (("Market",) . toJSON) _eMRInstanceGroupConfigScalingActionMarket , (Just . ("SimpleScalingPolicyConfiguration",) . toJSON) _eMRInstanceGroupConfigScalingActionSimpleScalingPolicyConfiguration ] -- | Constructor for 'EMRInstanceGroupConfigScalingAction' containing required -- fields as arguments. emrInstanceGroupConfigScalingAction :: EMRInstanceGroupConfigSimpleScalingPolicyConfiguration -- ^ 'emrigcsaSimpleScalingPolicyConfiguration' -> EMRInstanceGroupConfigScalingAction emrInstanceGroupConfigScalingAction simpleScalingPolicyConfigurationarg = EMRInstanceGroupConfigScalingAction { _eMRInstanceGroupConfigScalingActionMarket = Nothing , _eMRInstanceGroupConfigScalingActionSimpleScalingPolicyConfiguration = simpleScalingPolicyConfigurationarg } -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancegroupconfig-scalingaction.html#cfn-elasticmapreduce-instancegroupconfig-scalingaction-market emrigcsaMarket :: Lens' EMRInstanceGroupConfigScalingAction (Maybe (Val Text)) emrigcsaMarket = lens _eMRInstanceGroupConfigScalingActionMarket (\s a -> s { _eMRInstanceGroupConfigScalingActionMarket = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticmapreduce-instancegroupconfig-scalingaction.html#cfn-elasticmapreduce-instancegroupconfig-scalingaction-simplescalingpolicyconfiguration emrigcsaSimpleScalingPolicyConfiguration :: Lens' EMRInstanceGroupConfigScalingAction EMRInstanceGroupConfigSimpleScalingPolicyConfiguration emrigcsaSimpleScalingPolicyConfiguration = lens _eMRInstanceGroupConfigScalingActionSimpleScalingPolicyConfiguration (\s a -> s { _eMRInstanceGroupConfigScalingActionSimpleScalingPolicyConfiguration = a })
frontrowed/stratosphere
library-gen/Stratosphere/ResourceProperties/EMRInstanceGroupConfigScalingAction.hs
Haskell
mit
2,841
{- Copyright 2020 The CodeWorld Authors. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -} {-# LANGUAGE OverloadedStrings #-} -- | -- Functions an types for working with JWT bearer tokens module CodeWorld.Auth.Token ( AccessToken (..), Issuer (..), RefreshToken (..), accessToken, parseAccessToken, parseRefreshToken, refreshToken, renderAccessToken, renderRefreshToken, ) where import CodeWorld.Account (TokenId (..), UserId (..)) import CodeWorld.Auth.Time import Data.Aeson (Value (..)) import Data.Map (Map) import qualified Data.Map as Map (fromList, lookup) import Data.Text (Text) import qualified Data.Text as Text (pack, unpack) import Data.Time.Clock ( NominalDiffTime, UTCTime, addUTCTime, ) import Text.Read (readMaybe) import Web.JWT ( ClaimsMap (..), JWTClaimsSet (..), Signer (..), StringOrURI, claims, decodeAndVerifySignature, encodeSigned, stringOrURI, stringOrURIToText, unClaimsMap, ) import Prelude hiding (exp) newtype Issuer = Issuer Text deriving (Eq, Show) data TokenType = Access | Refresh deriving (Eq, Show) data AccessToken = AccessToken Issuer UTCTime UTCTime UserId data RefreshToken = RefreshToken Issuer UTCTime UTCTime UserId TokenId -- | Access token expiry period: access tokens vended by local auth -- system (via /signIn, /refreshToken) will expire after this time -- period: clients must then request a new access and refresh token -- using the /refreshToken API. accessTokenExpiryPeriod :: NominalDiffTime accessTokenExpiryPeriod = seconds 60 -- | Refresh token expiry period: refresh tokens expire after this -- time period at which the client is required to reauthenticate the -- user via the /signIn API. This is loosely equivalent to a -- traditional "session expiry period". refreshTokenExpiryPeriod :: NominalDiffTime refreshTokenExpiryPeriod = minutes 60 toStringOrURI :: Issuer -> Maybe StringOrURI toStringOrURI (Issuer issuerRaw) = stringOrURI issuerRaw valueText :: Value -> Maybe Text valueText (String s) = Just s valueText _ = Nothing accessToken :: Issuer -> UTCTime -> UserId -> AccessToken accessToken issuer issuedAt userId = let expiresAt = addUTCTime accessTokenExpiryPeriod issuedAt in AccessToken issuer issuedAt expiresAt userId refreshToken :: Issuer -> UTCTime -> UserId -> TokenId -> RefreshToken refreshToken issuer issuedAt userId tokenId = let expiresAt = addUTCTime refreshTokenExpiryPeriod issuedAt in RefreshToken issuer issuedAt expiresAt userId tokenId renderAccessToken :: Signer -> AccessToken -> Maybe Text renderAccessToken signer (AccessToken issuer issuedAt expiresAt userId) = renderHelper signer issuer issuedAt expiresAt userId $ Map.fromList [("token-type", String "access")] renderRefreshToken :: Signer -> RefreshToken -> Maybe Text renderRefreshToken signer (RefreshToken issuer issuedAt expiresAt userId (TokenId tokenId)) = renderHelper signer issuer issuedAt expiresAt userId $ Map.fromList [("token-type", String "refresh"), ("token-id", String $ (Text.pack . show) tokenId)] renderHelper :: Signer -> Issuer -> UTCTime -> UTCTime -> UserId -> Map Text Value -> Maybe Text renderHelper signer issuer issuedAt expiresAt (UserId userIdRaw) extraClaims = do issuedAtNum <- utcTimeToNumericDate issuedAt expiresAtNum <- utcTimeToNumericDate expiresAt let claimsSet = mempty { iss = toStringOrURI issuer, sub = stringOrURI (Text.pack userIdRaw), exp = Just expiresAtNum, iat = Just issuedAtNum, unregisteredClaims = ClaimsMap extraClaims } return $ encodeSigned signer mempty claimsSet parseAccessToken :: Signer -> Text -> Maybe AccessToken parseAccessToken signer j = do (tokenType, issuer, issuedAt, expiresAt, userId, _) <- parseHelper signer j case tokenType of Access -> Just $ AccessToken issuer issuedAt expiresAt userId _ -> Nothing parseRefreshToken :: Signer -> Text -> Maybe RefreshToken parseRefreshToken signer j = do (tokenType, issuer, issuedAt, expiresAt, userId, extraClaims) <- parseHelper signer j case tokenType of Refresh -> do tokenIdValue <- Map.lookup "token-id" extraClaims tokenIdRaw <- valueText tokenIdValue tokenId <- TokenId <$> readMaybe (Text.unpack tokenIdRaw) Just $ RefreshToken issuer issuedAt expiresAt userId tokenId _ -> Nothing parseHelper :: Signer -> Text -> Maybe (TokenType, Issuer, UTCTime, UTCTime, UserId, Map Text Value) parseHelper signer j = do jwt <- decodeAndVerifySignature signer j let c = claims jwt issuer <- (Issuer . stringOrURIToText) <$> iss c issuedAt <- numericDateToUTCTime <$> iat c expiresAt <- numericDateToUTCTime <$> exp c userId <- (UserId . Text.unpack . stringOrURIToText) <$> sub c let extraClaims = unClaimsMap $ unregisteredClaims c tokenTypeValue <- Map.lookup "token-type" extraClaims tokenTypeRaw <- valueText tokenTypeValue tokenType <- parseTokenType tokenTypeRaw return (tokenType, issuer, issuedAt, expiresAt, userId, extraClaims) where parseTokenType s | s == "access" = Just Access | s == "refresh" = Just Refresh | otherwise = Nothing
google/codeworld
codeworld-auth/src/CodeWorld/Auth/Token.hs
Haskell
apache-2.0
5,737
{-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE RecordWildCards #-} import Data.List import Data.Maybe import Data.Char hypotenuse a b = sqrt(a^2 + b^2) --Conditionals -- identifyCamel humps = if humps == 1 then "Dromeday" else "Bactrian" --Recursive Function -- increasing :: (Ord a) => [a] -> Bool increasing xs = if xs == [] then True else if tail xs == [] then True else if head xs <= head(tail xs) then increasing (tail xs) else False --Pattern matching -- incr[] = True incr[x] = True incr(x:y:ys) = x <= y && incr (y:ys) -- incr _ = True --Pattern Matching -- noVowels :: [Char] -> [Char] noVowels "" = "" noVowels (x:xs) = if x `elem` "aeiouAEIOU" then noVowels xs else x : noVowels xs watch :: Int -> [Char] watch 7 = "7 o'clock and ... SHARKNADO!" watch n = show n ++ " " ++ "o'clock and all's well" addOneToSum y z = let x = 1 in x + y + z --Recursion -- sumRange start end acc = if start > end then acc else sumRange (start + 1) end (acc + start) len :: [a] -> Int len [] = 0 len (_:xs) = 1 + len xs summ :: (Num a) => [a] -> a summ [] = 0 summ (x:xs) = x + summ xs --Functional Composition -- add10 value = value + 10 mult5 value = value * 5 mult5AfterAdd10 value = (mult5 . add10) value quote str = "'" ++ str ++ "'" findKeyError key = "Unable to find " ++ " " ++ (quote key) firstOrEmpty :: [[Char]] -> [Char] firstOrEmpty lst = if not(null lst) then head lst else "empty" --ADT-- Defined by two pieces of data -- -- A name for the type that will be used to represent its value -- A set of constructors that are used to create new values. -- These constructors may have arguments that will hold values of the specified types -- 1) Government organizations which are known by their name -- 2) Companies, for which you need to record its name, an identification number, a contact person -- and its position within the company hierachy -- 3) Individual clients, known by their name, surname and whether they want to receive further information -- about offers and discounts data Client = GovOrg String | Company String Integer Person String | Individual Person Bool deriving Show data Person = Person String String Gender deriving Show data Users = Organization String Integer Person String | User Bool deriving Show data Gender = Male | Female | Unknown deriving Show {-Using Records to define Data types-} data PersonR = PersonR {firstName :: String, lastName :: String} deriving Show data ClientR = GovOrgR {clientRName :: String} | CompanyR {clientRName ::String, companyId :: Integer, person :: PersonR, duty :: String} | IndividualR {person ::PersonR } deriving Show hungai = IndividualR {person = PersonR{lastName = "Hungai", firstName="Kevin"}} kevin = PersonR{firstName = "Hungai", lastName="Kevin"} --Functions using pattern matching greet :: ClientR -> String greet IndividualR {person = PersonR{ firstName = fn }} = "Hi," ++ " " ++ fn greet CompanyR { clientRName = c } = "Hello," ++ " " ++ c greet GovOrgR { } = "Welcome" {- Using named record puns -> # LANGUAGE NamedFieldPuns # -} greet2 IndividualR {person = PersonR {firstName}} = "Hi, " ++ " " ++ firstName greet2 CompanyR { clientRName } = "Hello," ++ " " ++ clientRName greet2 GovOrgR { } = "Welcome" {- Using named record puns with Record Wild Cards -> # LANGUAGE RecordWildCards # -} greet3 IndividualR {person=PersonR{..}} = "Hi," ++ " " ++ firstName greet3 CompanyR {..} = "Hello," ++ " " ++ clientRName greet3 GovOrgR { } = "Welcome" {-nameInCapitals :: PersonR -> PersonR nameInCapitals p@(PersonR{firstName = initial:rest}) = let newName = (toUpper initial):rest in p {firstName = newName} nameInCapitals p@(PersonR{firstName = " "}) = p -} clientName :: Client -> String clientName client = case client of GovOrg name -> name Company name _ _ _ -> name Individual person ads -> case person of Person fName lName gender -> fName ++ " " ++ lName companyName :: Client -> Maybe String companyName client = case client of Company name _ _ _ -> Just name _ -> Nothing fibonnaci :: Integer -> Integer fibonnaci n = case n of 0 -> 0 1 -> 1 _ -> fibonnaci (n-1) + fibonnaci (n-2) sorted [] = True sorted [_] = True sorted (x:r@(y:_)) = x < y && sorted r --Card ADT's data Rank = Ace | Two | Three | Four | Five | Six | Seven | Eight | Nine | Ten | Jack | Queen | King deriving (Eq,Ord,Bounded,Enum,Show,Read) data Suit = Spades | Hearts | Diamonds | Clubs deriving (Eq,Enum,Show,Read) data Card = Card Rank Suit deriving (Eq,Show,Read) type Hand = Card --Returns True if all consucutive pairs satisfy allPairs f [] = True allPairs f [x] = True allPairs f (x:y:ys) = f x y && allPairs f (y:ys) data ConnType = TCP | UDP data UseProxy = NoProxy | Proxy String data TimeOut = NoTimeOut | TimeOut Integer data ConnOptions = ConnOptions { connType :: ConnType ,connSpeed :: Integer ,connProxy :: UseProxy ,connCaching :: Bool ,connKeepAlive :: Bool ,connTimeOut :: TimeOut }
hungaikev/learning-haskell
Hello.hs
Haskell
apache-2.0
5,386
{-# LANGUAGE DeriveGeneric, StandaloneDeriving #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Main (main) where import Control.Applicative ((<|>)) import Control.Exception (IOException, catch) import Control.Monad (when) import Data.Foldable (traverse_) import Data.List (foldl') import Data.Traversable (for) import GHC.Generics (Generic) import Prelude () import Prelude.Compat import System.Directory (getDirectoryContents) import System.Exit (exitFailure) import System.FilePath import System.IO import Data.TreeDiff import Data.TreeDiff.Golden import qualified Options.Applicative as O import Documentation.Haddock.Types import qualified Documentation.Haddock.Parser as Parse type Doc id = DocH () id data Fixture = Fixture { fixtureName :: FilePath , fixtureOutput :: FilePath } deriving Show data Result = Result { _resultSuccess :: !Int , _resultTotal :: !Int } deriving Show combineResults :: Result -> Result -> Result combineResults (Result s t) (Result s' t') = Result (s + s') (t + t') readFixtures :: IO [Fixture] readFixtures = do let dir = "fixtures/examples" files <- getDirectoryContents dir let inputs = filter (\fp -> takeExtension fp == ".input") files return $ flip map inputs $ \fp -> Fixture { fixtureName = dir </> fp , fixtureOutput = dir </> fp -<.> "parsed" } goldenFixture :: String -> IO Expr -> IO Expr -> (Expr -> Expr -> IO (Maybe String)) -> (Expr -> IO ()) -> IO Result goldenFixture name expect actual cmp wrt = do putStrLn $ "running " ++ name a <- actual e <- expect `catch` handler a mres <- cmp e a case mres of Nothing -> return (Result 1 1) Just str -> do putStrLn str return (Result 0 1) where handler :: Expr -> IOException -> IO Expr handler a exc = do putStrLn $ "Caught " ++ show exc putStrLn "Accepting the test" wrt a return a runFixtures :: [Fixture] -> IO () runFixtures fixtures = do results <- for fixtures $ \(Fixture i o) -> do let name = takeBaseName i let readDoc = do input <- readFile i return (parseString input) ediffGolden goldenFixture name o readDoc case foldl' combineResults (Result 0 0) results of Result s t -> do putStrLn $ "Fixtures: success " ++ show s ++ "; total " ++ show t when (s /= t) exitFailure listFixtures :: [Fixture] -> IO () listFixtures = traverse_ $ \(Fixture i _) -> do let name = takeBaseName i putStrLn name acceptFixtures :: [Fixture] -> IO () acceptFixtures = traverse_ $ \(Fixture i o) -> do input <- readFile i let doc = parseString input let actual = show (prettyExpr $ toExpr doc) ++ "\n" writeFile o actual parseString :: String -> Doc String parseString = Parse.toRegular . _doc . Parse.parseParas Nothing data Cmd = CmdRun | CmdAccept | CmdList main :: IO () main = do hSetBuffering stdout NoBuffering -- For interleaved output when debugging runCmd =<< O.execParser opts where opts = O.info (O.helper <*> cmdParser) O.fullDesc cmdParser :: O.Parser Cmd cmdParser = cmdRun <|> cmdAccept <|> cmdList <|> pure CmdRun cmdRun = O.flag' CmdRun $ mconcat [ O.long "run" , O.help "Run parser fixtures" ] cmdAccept = O.flag' CmdAccept $ mconcat [ O.long "accept" , O.help "Run & accept parser fixtures" ] cmdList = O.flag' CmdList $ mconcat [ O.long "list" , O.help "List fixtures" ] runCmd :: Cmd -> IO () runCmd CmdRun = readFixtures >>= runFixtures runCmd CmdList = readFixtures >>= listFixtures runCmd CmdAccept = readFixtures >>= acceptFixtures ------------------------------------------------------------------------------- -- Orphans ------------------------------------------------------------------------------- deriving instance Generic (DocH mod id) instance (ToExpr mod, ToExpr id) => ToExpr (DocH mod id) deriving instance Generic (Header id) instance ToExpr id => ToExpr (Header id) deriving instance Generic (Hyperlink id) instance ToExpr id => ToExpr (Hyperlink id) deriving instance Generic (ModLink id) instance ToExpr id => ToExpr (ModLink id) deriving instance Generic Picture instance ToExpr Picture deriving instance Generic Example instance ToExpr Example deriving instance Generic (Table id) instance ToExpr id => ToExpr (Table id) deriving instance Generic (TableRow id) instance ToExpr id => ToExpr (TableRow id) deriving instance Generic (TableCell id) instance ToExpr id => ToExpr (TableCell id)
haskell/haddock
haddock-library/fixtures/Fixtures.hs
Haskell
bsd-2-clause
4,689
module NLP.Tools.Convenience (smap) where smap :: (b -> c) -> (a, b) -> (a, c) smap f (a,b) = (a,f b)
RoboNickBot/nlp-tools
src/NLP/Tools/Convenience.hs
Haskell
bsd-2-clause
103
{-# LANGUAGE StandaloneDeriving, TemplateHaskell, FlexibleContexts, DeriveTraversable #-} import Data.StructuralTraversal.Class import Data.StructuralTraversal.Instances import Data.StructuralTraversal.TH import Data.StructuralTraversal.Indexing import Data.Traversable import Control.Applicative import Control.Monad.Writer import Test.HUnit hiding (test) data Name a = Name String deriving (Show, Eq) data Lit a = IntLit Integer deriving (Show, Eq) data Expr a = LitExpr (Lit a) | Variable (Name a) | Neg (Ann Expr a) | Plus (Ann Expr a) (Ann Expr a) deriving (Show, Eq) data Instr a = Assign (Ann Expr a) (Ann Expr a) | Sequence (AnnList Instr a) deriving (Show, Eq) data Decl a = Procedure (Ann Name a) (Ann Instr a) deriving (Show, Eq) data Ann elem annot = Ann annot (elem annot) deriving (Show, Eq) instance StructuralTraversable elem => StructuralTraversable (Ann elem) where traverseUp desc asc f (Ann ann e) = flip Ann <$> (desc *> traverseUp desc asc f e <* asc) <*> f ann traverseDown desc asc f (Ann ann e) = Ann <$> f ann <*> (desc *> traverseDown desc asc f e <* asc) newtype AnnList e a = AnnList { fromAnnList :: [Ann e a] } deriving (Show, Eq) instance StructuralTraversable elem => StructuralTraversable (AnnList elem) where traverseUp desc asc f (AnnList ls) = AnnList <$> sequenceA (map (traverseUp desc asc f) ls) traverseDown desc asc f (AnnList ls) = AnnList <$> sequenceA (map (traverseDown desc asc f) ls) input = Ann () (Procedure (Ann () (Name "program1")) (Ann () (Sequence (AnnList [ Ann () (Assign (Ann () (Variable (Name "a"))) (Ann () (LitExpr (IntLit 1)))) , Ann () (Assign (Ann () (Variable (Name "v"))) (Ann () (Plus (Ann () (Variable (Name "b"))) (Ann () (LitExpr (IntLit 2)))))) ])))) expected = Ann [] (Procedure (Ann [0] (Name "program1")) (Ann [1] (Sequence (AnnList [ Ann [0,1] (Assign (Ann [0,0,1] (Variable (Name "a"))) (Ann [1,0,1] (LitExpr (IntLit 1)))) , Ann [1,1] (Assign (Ann [0,1,1] (Variable (Name "v"))) (Ann [1,1,1] (Plus (Ann [0,1,1,1] (Variable (Name "b"))) (Ann [1,1,1,1] (LitExpr (IntLit 2)))))) ])))) topDownRes :: [[Int]] topDownRes = execWriter $ traverseDown (return ()) (return ()) (tell . (:[])) expected topDownExpected :: [[Int]] topDownExpected = [[],[0],[1],[0,1],[0,0,1],[1,0,1],[1,1],[0,1,1],[1,1,1],[0,1,1,1],[1,1,1,1]] bottomUpRes :: [[Int]] bottomUpRes = execWriter $ traverseUp (return ()) (return ()) (tell . (:[])) expected bottomUpExpected :: [[Int]] bottomUpExpected = [[0],[0,0,1],[1,0,1],[0,1],[0,1,1],[0,1,1,1],[1,1,1,1],[1,1,1],[1,1],[1],[]] deriveStructTrav ''Lit deriveStructTrav ''Expr deriveStructTrav ''Instr deriveStructTrav ''Decl deriveStructTrav ''Name main :: IO () main = do assertEqual "The result of the transformation is not as expected" expected (indexedTraverse (\_ i -> i) input) assertEqual "The result of bottom-up traversal is not as expected" bottomUpExpected bottomUpRes assertEqual "The result of top-down traversal is not as expected" topDownExpected topDownRes
nboldi/structural-traversal
test/Example.hs
Haskell
bsd-3-clause
3,371
{-# LANGUAGE CPP #-} -- | Paths, host bitness and other environmental information about Haste. module Haste.Environment ( hasteSysDir, jsmodSysDir, hasteInstSysDir, pkgSysDir, pkgSysLibDir, jsDir, hasteUserDir, jsmodUserDir, hasteInstUserDir, pkgUserDir, pkgUserLibDir, hostWordSize, ghcLibDir, ghcBinary, ghcPkgBinary, hasteBinary, hastePkgBinary, hasteInstHisBinary, hasteInstBinary, hasteCopyPkgBinary, closureCompiler, portableHaste) where import System.IO.Unsafe import Data.Bits import Foreign.C.Types (CIntPtr) import Control.Shell import System.Environment (getExecutablePath) import System.Directory (findExecutable) import Paths_haste_compiler import GHC.Paths (libdir) import Config (cProjectVersion) import Data.Maybe (catMaybes) #if defined(PORTABLE) portableHaste :: Bool portableHaste = True -- | Haste system directory. Identical to @hasteUserDir@ unless built with -- -f portable. hasteSysDir :: FilePath hasteSysDir = joinPath . init . init . splitPath $ unsafePerformIO getExecutablePath ghcLibDir :: FilePath ghcLibDir = unsafePerformIO $ do Right out <- shell $ run ghcBinary ["--print-libdir"] "" return $ init out hasteBinDir :: FilePath hasteBinDir = hasteSysDir </> "bin" jsDir :: FilePath jsDir = hasteSysDir </> "js" #else portableHaste :: Bool portableHaste = False -- | Haste system directory. Identical to @hasteUserDir@ unless built with -- -f portable. hasteSysDir :: FilePath hasteSysDir = hasteUserDir ghcLibDir :: FilePath ghcLibDir = libdir hasteBinDir :: FilePath hasteBinDir = unsafePerformIO $ getBinDir jsDir :: FilePath jsDir = unsafePerformIO $ getDataDir #endif -- | Haste user directory. Usually ~/.haste. hasteUserDir :: FilePath Right hasteUserDir = unsafePerformIO . shell $ withAppDirectory "haste" return -- | Directory where user .jsmod files are stored. jsmodSysDir :: FilePath jsmodSysDir = hasteSysDir </> "jsmods" -- | Base directory for haste-inst; system packages. hasteInstSysDir :: FilePath hasteInstSysDir = hasteSysDir </> "libraries" -- | Base directory for Haste's system libraries. pkgSysLibDir :: FilePath pkgSysLibDir = hasteInstSysDir </> "lib" -- | Directory housing package information. pkgSysDir :: FilePath pkgSysDir = hasteSysDir </> "packages" -- | Directory where user .jsmod files are stored. jsmodUserDir :: FilePath jsmodUserDir = hasteUserDir </> "jsmods" -- | Base directory for haste-inst. hasteInstUserDir :: FilePath hasteInstUserDir = hasteUserDir </> "libraries" -- | Directory containing library information. pkgUserLibDir :: FilePath pkgUserLibDir = hasteInstUserDir </> "lib" -- | Directory housing package information. pkgUserDir :: FilePath pkgUserDir = hasteUserDir </> "packages" -- | Host word size in bits. hostWordSize :: Int #if __GLASGOW_HASKELL__ >= 708 hostWordSize = finiteBitSize (undefined :: CIntPtr) #else hostWordSize = bitSize (undefined :: CIntPtr) #endif -- | Path to the GHC binary. ghcBinary :: FilePath ghcBinary = unsafePerformIO $ do exes <- catMaybes `fmap` mapM findExecutable ["ghc-" ++ cProjectVersion, "ghc"] case exes of (exe:_) -> return exe _ -> error $ "No appropriate GHC executable in search path!\n" ++ "Are you sure you have GHC " ++ cProjectVersion ++ " installed?" -- | Path to the GHC binary. ghcPkgBinary :: FilePath ghcPkgBinary = unsafePerformIO $ do exes <- catMaybes `fmap` mapM findExecutable ["ghc-pkg-" ++ cProjectVersion, "ghc-pkg"] case exes of (exe:_) -> return exe _ -> error $ "No appropriate ghc-pkg executable in search path!\n" ++ "Are you sure you have GHC " ++ cProjectVersion ++ " installed?" -- | The main Haste compiler binary. hasteBinary :: FilePath hasteBinary = hasteBinDir </> "hastec" -- | Binary for haste-pkg. hastePkgBinary :: FilePath hastePkgBinary = hasteBinDir </> "haste-pkg" -- | Binary for haste-copy-pkg. hasteCopyPkgBinary :: FilePath hasteCopyPkgBinary = hasteBinDir </> "haste-copy-pkg" -- | Binary for haste-pkg. hasteInstBinary :: FilePath hasteInstBinary = hasteBinDir </> "haste-inst" -- | Binary for haste-install-his. hasteInstHisBinary :: FilePath hasteInstHisBinary = hasteBinDir </> "haste-install-his" -- | JAR for Closure compiler. closureCompiler :: FilePath closureCompiler = hasteBinDir </> "compiler.jar"
joelburget/haste-compiler
src/Haste/Environment.hs
Haskell
bsd-3-clause
4,455
{-# LANGUAGE OverloadedStrings #-} module Fragment ( readFragment, writeFragment, fragmentUpdateHash, TlsIo, evalTlsIo, liftIO, throwError, readCached, randomByteString, Partner(..), setVersion, setClientRandom, setServerRandom, getClientRandom, getServerRandom, getCipherSuite, cacheCipherSuite, flushCipherSuite, encryptRSA, generateKeys, finishedHash, clientVerifySign, updateSequenceNumberSmart, TlsServer, runOpen, tPut, tGetByte, tGetLine, tGet, tGetContent, tClose, debugPrintKeys, getRandomGen, setRandomGen, SecretKey(..), ) where import Prelude hiding (read) import Control.Applicative import qualified Data.ByteString as BS import TlsIo import Basic readFragment :: TlsIo cnt Fragment readFragment = do (ct, v, ebody) <- (,,) <$> readContentType <*> readVersion <*> readLen 2 body <- decryptBody ct v ebody return $ Fragment ct v body decryptBody :: ContentType -> Version -> BS.ByteString -> TlsIo cnt BS.ByteString decryptBody = decryptMessage Server writeFragment :: Fragment -> TlsIo cnt () writeFragment (Fragment ct v bs) = do cs <- isCiphered Client if cs then do eb <- encryptBody ct v bs writeContentType ct >> writeVersion v >> writeLen 2 eb else writeContentType ct >> writeVersion v >> writeLen 2 bs encryptBody :: ContentType -> Version -> BS.ByteString -> TlsIo cnt BS.ByteString encryptBody ct v body = do ret <- encryptMessage Client ct v body updateSequenceNumber Client return ret fragmentUpdateHash :: Fragment -> TlsIo cnt () fragmentUpdateHash (Fragment ContentTypeHandshake _ b) = updateHash b fragmentUpdateHash _ = return ()
YoshikuniJujo/forest
subprojects/tls-analysis/client/Fragment.hs
Haskell
bsd-3-clause
1,602
{-# LANGUAGE TupleSections, OverloadedStrings, QuasiQuotes, TemplateHaskell, TypeFamilies, RecordWildCards, DeriveGeneric ,MultiParamTypeClasses ,FlexibleInstances #-} module Protocol.ROC.PointTypes.PointType17 where import GHC.Generics import qualified Data.ByteString as BS import Data.Word import Data.Binary import Data.Binary.Get import Protocol.ROC.Float import Protocol.ROC.Utils data PointType17 = PointType17 { pointType17PointTag :: !PointType17PointTag ,pointType17IntFlag :: !PointType17IntFlag ,pointType17Data1 :: !PointType17Data1 ,pointType17Data2 :: !PointType17Data2 ,pointType17Data3 :: !PointType17Data3 ,pointType17Data4 :: !PointType17Data4 ,pointType17Data5 :: !PointType17Data5 ,pointType17Data6 :: !PointType17Data6 ,pointType17Data7 :: !PointType17Data7 ,pointType17Data8 :: !PointType17Data8 ,pointType17Data9 :: !PointType17Data9 ,pointType17Data10 :: !PointType17Data10 ,pointType17Data11 :: !PointType17Data11 ,pointType17Data12 :: !PointType17Data12 ,pointType17Data13 :: !PointType17Data13 ,pointType17Data14 :: !PointType17Data14 ,pointType17Data15 :: !PointType17Data15 ,pointType17Data16 :: !PointType17Data16 ,pointType17Data17 :: !PointType17Data17 ,pointType17Data18 :: !PointType17Data18 ,pointType17Data19 :: !PointType17Data19 ,pointType17Data20 :: !PointType17Data20 ,pointType17EnableSoftPntLog :: !PointType17EnableSoftPntLog } deriving (Read,Eq, Show, Generic) type PointType17PointTag = BS.ByteString type PointType17IntFlag = Word16 type PointType17Data1 = Float type PointType17Data2 = Float type PointType17Data3 = Float type PointType17Data4 = Float type PointType17Data5 = Float type PointType17Data6 = Float type PointType17Data7 = Float type PointType17Data8 = Float type PointType17Data9 = Float type PointType17Data10 = Float type PointType17Data11 = Float type PointType17Data12 = Float type PointType17Data13 = Float type PointType17Data14 = Float type PointType17Data15 = Float type PointType17Data16 = Float type PointType17Data17 = Float type PointType17Data18 = Float type PointType17Data19 = Float type PointType17Data20 = Float type PointType17EnableSoftPntLog = Bool pointType17Parser :: Get PointType17 pointType17Parser = do pointTag <- getByteString 10 intFlag <- getWord16le data1 <- getIeeeFloat32 data2 <- getIeeeFloat32 data3 <- getIeeeFloat32 data4 <- getIeeeFloat32 data5 <- getIeeeFloat32 data6 <- getIeeeFloat32 data7 <- getIeeeFloat32 data8 <- getIeeeFloat32 data9 <- getIeeeFloat32 data10 <- getIeeeFloat32 data11 <- getIeeeFloat32 data12 <- getIeeeFloat32 data13 <- getIeeeFloat32 data14 <- getIeeeFloat32 data15 <- getIeeeFloat32 data16 <- getIeeeFloat32 data17 <- getIeeeFloat32 data18 <- getIeeeFloat32 data19 <- getIeeeFloat32 data20 <- getIeeeFloat32 enableSoftPntLog <- anyButNull return $ PointType17 pointTag intFlag data1 data2 data3 data4 data5 data6 data7 data8 data9 data10 data11 data12 data13 data14 data15 data16 data17 data18 data19 data20 enableSoftPntLog
jqpeterson/roc-translator
src/Protocol/ROC/PointTypes/PointType17.hs
Haskell
bsd-3-clause
3,881
module Metrics.RegexTiming(timingRegex2) where import Metrics.Common import qualified Data.ByteString.Lazy.Char8 as B import Text.Regex.Base.RegexLike (matchAllText, MatchText) import Text.Regex.PCRE.ByteString.Lazy import qualified Data.Map as M import Data.Array as A import Data.List (groupBy) import Data.Function (on) import Data.Attoparsec.ByteString.Lazy import Data.Attoparsec.ByteString.Char8 (double) import qualified Data.Sequence as S select :: Ix i => [i] -> Array i a -> [a] select [] _ = [] select (x:xs) arr = arr A.! x : select xs arr match :: Regex -> B.ByteString -> [MatchText B.ByteString] match = {-# SCC "matchAllText" #-} matchAllText parseDouble :: B.ByteString -> Double parseDouble input = {-# SCC "parseDouble" #-} case parse double input of Done _ r -> r Fail _ _ _ -> 0 duration :: Int -> [MatchText B.ByteString] -> [Double] duration durationGroup matches = {-# SCC "duration" #-} map (parseDouble . fst . (A.! durationGroup)) matches name :: [Int] -> [MatchText B.ByteString] -> [B.ByteString] name nameSuffixes matches = {-# SCC "name" #-} map (B.intercalate (B.pack ".") . map fst . select nameSuffixes) matches pair :: ([b] -> t) -> [(a, b)] -> (a, t) pair _ [] = error "Internal error in timingRegex: pair applied to empty list" pair state durs@((name,_):_) = {-# SCC "pair" #-} (name, state (map snd durs)) durationByName :: [b] -> [B.ByteString] -> [[(B.ByteString, b)]] durationByName durations names = {-# SCC "byname" #-} case durations of [] -> [] _ -> case names of [] -> [zip (repeat B.empty) durations] _ -> groupBy ((==) `on` fst) (zip names durations) timingRegex2 :: Regex -> String -> Int -> [Int] -> B.ByteString -> MetricState timingRegex2 regex nameString durationGroup nameSuffixes input = Timings2 $ M.fromList $ map buildName states where buildName ~(suffix, metricStates) = (metricName, metricStates) where metricName | B.null suffix = nameString ++ "." ++ B.unpack suffix | otherwise = nameString matches = match regex input durations = duration durationGroup matches names = name nameSuffixes matches durationsByName = durationByName durations names states = map (\(k,v) -> (k, S.fromList v)) (map (pair id) durationsByName)
zsol/hlogster
Metrics/RegexTiming.hs
Haskell
bsd-3-clause
2,336
module Main where import Control.Concurrent (forkIO) import Control.Concurrent.Async import Control.Monad.IO.Class import Control.Monad.Trans.Resource import Data.Conduit (Sink, Conduit, Source, await, awaitForever, yield) import Data.Conduit.Async import qualified Data.Conduit.Combinators as DCC import Data.Conduit.Filesystem import Data.List import Data.Time.Clock import Foreign.Marshal.Alloc import System.Directory import System.Environment (getArgs) import System.FilePath import System.IO import System.Posix.Files bufSize :: Int bufSize = 464 readContents :: FilePath -> IO () readContents path = allocaBytes bufSize $ \buf -> withFile path ReadMode $ \h -> do hSetBinaryMode h True hSetBuffering h $ BlockBuffering $ Just bufSize _ <- hGetBuf h buf bufSize return () sink :: Sink FilePath IO () sink = awaitForever $ \path -> liftIO $ forkIO $ readContents path mark :: Int mark = 100 timer :: Int -> UTCTime -> Conduit FilePath IO FilePath timer total time = do x' <- await case x' of Just x -> do yield x if total `mod` mark == 0 then do newtime <- liftIO getCurrentTime let diff = diffUTCTime newtime time rate = truncate $ fromIntegral mark / diff :: Integer liftIO $ putStrLn $ show total ++ " total, " ++ show rate ++ " per second" timer (total + 1) newtime else timer (total + 1) time Nothing -> return () source :: FilePath -> Source IO FilePath source path = do contents <- liftIO $ map (path </>) . filter (not . isPrefixOf ".") <$> getDirectoryContents path statted <- liftIO $ zip contents <$> mapConcurrently getFileStatus contents let (dirs', files') = partition (isDirectory . snd) statted dirs = map fst dirs' files = map fst files' DCC.yieldMany files mapM_ source dirs crawl :: FilePath -> IO () crawl path = do --let source = sourceDirectoryDeep False path time <- getCurrentTime source path =$=& timer 1 time $$& sink main :: IO () main = do args <- getArgs case args of [path] -> crawl path _ -> crawl "." return ()
sweeks-imvu/bullshit
src/Main.hs
Haskell
bsd-3-clause
2,126
{-# LANGUAGE CPP, NoImplicitPrelude, FlexibleContexts #-} #if __GLASGOW_HASKELL__ >= 702 {-# LANGUAGE Safe #-} #endif ------------------------------------------------------------------------------- -- | -- Module : System.Timeout.Lifted -- Copyright : (c) The University of Glasgow 2007 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : libraries@haskell.org -- Stability : experimental -- Portability : non-portable -- -- Attach a timeout event to monadic computations -- which are instances of 'MonadBaseControl'. -- ------------------------------------------------------------------------------- module System.Timeout.Lifted ( timeout ) where -- from base: import Prelude ( (.) ) import Data.Int ( Int ) import Data.Maybe ( Maybe(Nothing, Just), maybe ) import Control.Monad ( (>>=), return, liftM ) import System.IO ( IO ) import qualified System.Timeout as T ( timeout ) -- from monad-control: import Control.Monad.Trans.Control ( MonadBaseControl, restoreM, liftBaseWith ) #include "inlinable.h" -- | Generalized version of 'T.timeout'. -- -- Note that when the given computation times out any side effects of @m@ are -- discarded. When the computation completes within the given time the -- side-effects are restored on return. timeout :: MonadBaseControl IO m => Int -> m a -> m (Maybe a) timeout t m = liftBaseWith (\runInIO -> T.timeout t (runInIO m)) >>= maybe (return Nothing) (liftM Just . restoreM) {-# INLINABLE timeout #-}
basvandijk/lifted-base
System/Timeout/Lifted.hs
Haskell
bsd-3-clause
1,610
{-# LANGUAGE ConstraintKinds, FlexibleContexts, RankNTypes, OverloadedStrings #-} {-# LANGUAGE UndecidableInstances, ScopedTypeVariables, AllowAmbiguousTypes #-} ----------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------- -- | -- | Module : All functions used to find score -- | Author : Xiao Ling -- | Date : 8/17/2016 -- | --------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------- module Score ( count -- * todo: this function is easily abused , countp , w1 , w2 , s1 , s2 , p1 , p2 ) where import Control.Monad.State import Control.Monad.Trans.Reader import Data.Conduit import Data.Text (Text, unpack, pack) import Data.Attoparsec.Text hiding (count) import Lib import Core import Query {----------------------------------------------------------------------------- Score ------------------------------------------------------------------------------} w1 :: String -> String -> ReaderT Config IO Output w1 a1 a2 = do p_ws <- pattern weakStrong sumCount $ (\p -> p (S a1) (S a2)) <$> p_ws s1 :: String -> String -> ReaderT Config IO Output s1 a1 a2 = do p_sw <- pattern strongWeak sumCount $ (\p -> p (S a1) (S a2)) <$> p_sw w2 :: String -> String -> ReaderT Config IO Output w2 = flip w1 s2 :: String -> String -> ReaderT Config IO Output s2 = flip s1 p1 :: ReaderT Config IO Output p1 = do p_ws <- pattern weakStrong sumCount $ (\p -> p Star Star) <$> p_ws p2 :: ReaderT Config IO Output p2 = do p_sw <- pattern strongWeak sumCount $ (\p -> p Star Star) <$> p_sw {----------------------------------------------------------------------------- Count ------------------------------------------------------------------------------} -- * sum the results of multiple `count`s -- * and sum their counts, list all results sumCount :: [Parser Text] -> ReaderT Config IO Output sumCount ps = do rrs <- mapM countp ps let ns = fst <$> rrs let rs = snd <$> rrs return (sum ns, concat rs) -- * `count` for occurences of some phrase among ngram files countp :: Parser Text -> ReaderT Config IO Output countp phrase = do con <- ask (n, ts) <- phrase `query` (ngrams con) return (n,ts) -- * `count` occurences of some word `w` -- * in onegram file count :: String -> ReaderT Config IO Output count w = do let word = compile' w con <- ask (n, ts) <- word `query` [onegram con] return (n,ts)
lingxiao/GoodGreatIntensity
src/Score.hs
Haskell
bsd-3-clause
2,707
module Graphics where import Prelude import FPPrac.Graphics import System.FilePath (splitPath, dropExtension) data Thickness = Thin | Thick deriving (Eq,Show) alphabet = ['a'..'z'] type Node = (Char,Color,Point) type Edge = (Char,Char,Color,Int) data Graph = Graph { name :: String , directed :: Bool , weighted :: Bool , nodes :: [Node] , edges :: [Edge] } deriving (Eq,Show) data EdgeDrawingData = EdgeDrawingData { edgeStartpunt :: Point -- | (tx,ty): startpunt van edge , edgeEndpunt :: Point -- | (px,py): eindpunt van edge , innerPijlpunt :: Point -- | (qx,qy): binnenhoek van pijlpunt , achterPijlpunt :: Point -- | (sx,sy): achterpunten van pijlpunt , breedtePijlpunt :: Point -- | (wx,wy): breedte pijlputn , edgeDikte :: Point -- | (dx,dy): dikte van de edge , weightAfstand :: Point -- | (ax,ay): afstand gewicht tot pijlpunt , weightMidden :: Point -- | (mx,my): midden van edge } edgeWidthThin = 1 edgeWidthThick = 1.5 nodeRadius = 15 weightDistance = 6 arrowHeight = 20 arrowDepth = 9 arrowWidth = 9 lblBoxW = 20 lblBoxH = 19 lblHshift = 8 lblVshift = -6 bottomLineHeight = 25 bottomTextHeight = 10 allEdgeDrawingData thickness graph (lbl1,lbl2,col,wght) = EdgeDrawingData { edgeStartpunt = (tx,ty) -- startpunt van edge , edgeEndpunt = (px,py) -- eindpunt van edge , innerPijlpunt = (qx,qy) -- binnenhoek van pijlpunt , achterPijlpunt = (sx,sy) -- achterpunten van pijlpunt , breedtePijlpunt = (wx,wy) -- breedte pijlpunt , edgeDikte = (dx,dy) -- dikte van de edge , weightAfstand = (ax,ay) -- afstand gewicht tot pijlpunt , weightMidden = (mx,my) -- midden van edge } where Graph {directed=directed,nodes=nodes} = graph (x1,y1) = head [ (x,y) | (lbl,_,(x,y)) <- nodes, lbl==lbl1 ] (x2,y2) = head [ (x,y) | (lbl,_,(x,y)) <- nodes, lbl==lbl2 ] rico = (y2-y1) / (x2-x1) alpha | x2 > x1 = atan rico | x2 == x1 && y2 > y1 = pi/2 | x2 < x1 = pi + atan rico | x2 == x1 && y2 <= y1 = 3*pi/2 sina = sin alpha cosa = cos alpha (xr1,yr1) = (nodeRadius * cosa , nodeRadius * sina) (tx ,ty ) = (x1+xr1,y1+yr1) -- start of edge (px ,py ) = (x2-xr1,y2-yr1) -- outer arrow point (xr2,yr2) = (arrowDepth * cosa , arrowDepth * sina) (qx,qy) = (px-xr2,py-yr2) -- inner arrow point (xh ,yh ) = (arrowHeight * cosa , arrowHeight * sina) (sx ,sy ) = (px-xh,py-yh) -- back arrowpoints (wx ,wy ) = (arrowWidth * sina , arrowWidth * cosa) -- width of arrowpoint (dx ,dy ) | thickness == Thick = (edgeWidthThick * sina , edgeWidthThick * cosa) | otherwise = (edgeWidthThin * sina , edgeWidthThin * cosa) -- edge thickness (xwd,ywd) = (weightDistance * cosa , weightDistance * sina) (ax ,ay ) = (px-xwd,py-ywd) -- distance of weight from arrowpoint (mx ,my ) = ((x2+x1)/2,(y2+y1)/2) -- mid of (undirected) edge drawNode :: Node -> Picture drawNode (lbl,col,(x,y)) = Pictures [ Translate x y $ Color col $ circleSolid r , Translate x y $ Color black $ Circle r , Translate (x-lblHshift) (y+lblVshift) $ Color black $ Scale 0.15 0.15 $ Text [lbl] ] where r = nodeRadius drawEdgeTemp :: Color -> (Point,Point) -> Picture drawEdgeTemp col (p1,p2) = Color col $ Line [p1,p2] drawEdge :: Graph -> Edge -> Picture drawEdge graph edge | directed = Pictures [ Color col $ Polygon [ (tx+dx,ty-dy), (tx-dx,ty+dy), (qx-dx,qy+dy), (qx+dx,qy-dy), (tx+dx,ty-dy) ] , Color white $ Polygon [ (px+dx,py-dy), (px-dx,py+dy), (qx-dx,qy+dy), (qx+dx,qy-dy), (px+dx,py-dy) ] , Color col $ Polygon [ (px,py), (sx-wx,sy+wy), (qx,qy), (sx+wx,sy-wy), (px,py) ] ] | otherwise = Color col $ Polygon [ (tx+dx,ty-dy), (tx-dx,ty+dy), (px-dx,py+dy), (px+dx,py-dy), (tx+dx,ty-dy) ] where Graph {directed=directed} = graph (_,_,col,_) = edge EdgeDrawingData { edgeStartpunt = (tx,ty) -- startpunt van edge , edgeEndpunt = (px,py) -- eindpunt van edge , innerPijlpunt = (qx,qy) -- binnenhoek van pijlpunt , achterPijlpunt = (sx,sy) -- achterpunten van pijlpunt , breedtePijlpunt = (wx,wy) -- breedte pijlpunt , edgeDikte = (dx,dy) -- dikte van de edge } = allEdgeDrawingData Thin graph edge drawThickEdge :: Graph -> Edge -> Picture drawThickEdge graph edge | directed = Pictures [ Color col $ Polygon [ (tx+dx,ty-dy), (tx-dx,ty+dy), (qx-dx,qy+dy), (qx+dx,qy-dy), (tx+dx,ty-dy) ] , Color white $ Polygon [ (px+dx,py-dy), (px-dx,py+dy), (qx-dx,qy+dy), (qx+dx,qy-dy), (px+dx,py-dy) ] , Color col $ Polygon [ (px,py), (sx-wx,sy+wy), (qx,qy), (sx+wx,sy-wy), (px,py) ] ] | otherwise = Color col $ Polygon [ (tx+dx,ty-dy), (tx-dx,ty+dy), (px-dx,py+dy), (px+dx,py-dy), (tx+dx,ty-dy) ] where Graph {directed=directed} = graph (_,_,col,_) = edge EdgeDrawingData { edgeStartpunt = (tx,ty) -- startpunt van edge , edgeEndpunt = (px,py) -- eindpunt van edge , innerPijlpunt = (qx,qy) -- binnenhoek van pijlpunt , achterPijlpunt = (sx,sy) -- achterpunten van pijlpunt , breedtePijlpunt = (wx,wy) -- breedte pijlpunt , edgeDikte = (dx,dy) -- dikte van de edge } = allEdgeDrawingData Thick graph edge drawWeight :: Graph -> Edge -> Picture drawWeight graph edge | not weighted = Blank | directed = Pictures [ Translate ax ay $ Color white $ rectangleSolid lblBoxW lblBoxH , Translate (ax-lblHshift) (ay+lblVshift) $ Color black $ Scale 0.11 0.11 $ Text (show wght) ] | otherwise = Pictures [ Translate mx my $ Color white $ rectangleSolid lblBoxW lblBoxH , Translate (mx-lblHshift) (my+lblVshift) $ Color black $ Scale 0.11 0.11 $ Text (show wght) ] where Graph {directed=directed,weighted=weighted}=graph (_,_,_,wght) = edge EdgeDrawingData { weightAfstand = (ax,ay) -- afstand gewicht tot pijlpunt , weightMidden = (mx,my) -- midden van edge } = allEdgeDrawingData Thin graph edge drawGraph :: Graph -> Picture drawGraph graph = Pictures $ Color white (rectangleSolid 800 564) : (map drawNode nodes) ++ (map (drawEdge graph) edges) ++ (map (drawWeight graph) edges) where Graph {name=name,nodes=nodes,edges=edges}=graph drawBottomLine :: Graph -> Picture drawBottomLine graph = Pictures [ Translate 0 (-300 + bottomLineHeight / 2) $ Color white $ rectangleSolid 800 bottomLineHeight , Color black $ Line [(-400,height1),(400,height1)] , Color black $ Line [(-240,height1),(-240,-300)] , Color black $ Line [(100,height1),(100,-300)] , Translate (-392) height2 $ Color black $ Scale 0.11 0.11 $ Text "create:" , Translate (-332) height2 $ Color red $ Scale 0.11 0.11 $ Text $ (case (name graph) of "" -> "" ; xs -> dropExtension $ last $ splitPath xs) , Translate (-235) height2 $ Color black $ Scale 0.11 0.11 $ Text "click: node; drag: edge; double: remove node" , Translate 120 height2 $ Color black $ Scale 0.11 0.11 $ Text "[n]ew; [r]ead; [s]ave; save [a]s; prac[6]" ] where height1 = -300 + bottomLineHeight height2 = -300 + bottomTextHeight
christiaanb/fpprac
examples/Graphics.hs
Haskell
bsd-3-clause
8,201
module Logging ( logInfo , logDebug , logError ) where import Control.Monad ( when ) import Data.Monoid ( (<>) ) import Data.Time import Lens.Simple ( (^.) ) import qualified Configuration as C getTime :: IO String getTime = formatTime defaultTimeLocale "%F %H:%M:%6Q" <$> getCurrentTime logInfo :: String -> IO () logInfo message = do t <- getTime putStrLn $ t <> " INFO: " <> message logDebug :: C.ImprovizConfig -> String -> IO () logDebug config message = when (config ^. C.debug) $ do t <- getTime putStrLn $ t <> " DEBUG: " <> message logError :: String -> IO () logError message = do t <- getTime putStrLn $ t <> " ERROR: " <> message
rumblesan/proviz
src/Logging.hs
Haskell
bsd-3-clause
780
module Sex ( Sex (..) ) where data Sex = M | F deriving (Eq, Show, Ord)
satai/FrozenBeagle
Simulation/Lib/src/Sex.hs
Haskell
bsd-3-clause
81
{-# LANGUAGE TypeSynonymInstances #-} -- -- IO.hs -- -- Basic input and output of expressions. -- -- Gregory Wright, 22 April 2011 -- module Math.Symbolic.Wheeler.IO where import Control.Monad.Identity import Text.Parsec import Text.Parsec.Expr as Ex import Text.Parsec.Language import Text.Parsec.String import qualified Text.Parsec.Token as P import Math.Symbolic.Wheeler.Canonicalize --import Math.Symbolic.Wheeler.CanonicalizeDebug import Math.Symbolic.Wheeler.Function import {-# SOURCE #-} Math.Symbolic.Wheeler.Expr import Math.Symbolic.Wheeler.Numeric import Math.Symbolic.Wheeler.Symbol -- -- Read an expression from a string. -- -- Parse an expression. Formerly, certain transformations -- that put subexpressions into canonical form -- were done on the fly. This is no longer the case. The -- string is converted to an unsimplified expression, and -- you must invoke the "canonicalize" function explicitly. readExpr :: String -> Expr readExpr = canonicalize . runLex wheelerDef :: P.LanguageDef st wheelerDef = P.LanguageDef { P.commentStart = "{-" , P.commentEnd = "-}" , P.commentLine = "--" , P.nestedComments = True , P.identStart = letter <|> char '\\' , P.identLetter = letter <|> char '\'' , P.opStart = P.opLetter emptyDef , P.opLetter = oneOf ":!#$%&*+./<=>?@\\^|-~" , P.reservedOpNames= [] , P.reservedNames = [] , P.caseSensitive = True } lexer :: P.TokenParser () lexer = P.makeTokenParser (wheelerDef { P.reservedOpNames = ["^", "*", "/", "+", "-", "!", "**", "sqrt"] }) whiteSpace :: Parser () whiteSpace = P.whiteSpace lexer lexeme :: Parser a -> Parser a lexeme = P.lexeme lexer symbol :: String -> Parser String symbol = P.symbol lexer integer :: Parser Integer integer = P.integer lexer natural :: Parser Integer natural = P.natural lexer float :: Parser Double float = P.float lexer parens :: Parser a -> Parser a parens = P.parens lexer semi :: Parser String semi = P.semi lexer identifier :: Parser String identifier = P.identifier lexer reserved :: String -> Parser () reserved = P.reserved lexer reservedOp :: String -> Parser () reservedOp = P.reservedOp lexer commaList :: Parser a -> Parser [ a ] commaList = P.commaSep lexer expr :: Parser Expr expr = buildExpressionParser table factor <?> "expression" table :: [[ Operator String () Identity Expr ]] table = [[ inOp "**" (**) AssocRight] ,[ preOp "-" negate, preOp "+" id, preOp "sqrt" sqrt ] ,[ inOp "*" (*) AssocLeft, inOp "/" (/) AssocLeft ] ,[ inOp "+" (+) AssocLeft, inOp "-" (-) AssocLeft ] ] where preOp s f = Ex.Prefix (do { reservedOp s; return f } <?> "prefix operator") inOp s f assoc = Ex.Infix (do { reservedOp s; return f } <?> "infix operator") assoc factor :: Parser Expr factor = try application <|> parens expr <|> numericConst <|> do { x <- identifier; return (Symbol (simpleSymbol x)) } <?> "simple expresion" application :: Parser Expr application = do { f <- reservedFunction ; whiteSpace ; arg <- expr ; return (Applic f arg) } -- Note that the order is important. Function names that are -- prefixes of the other function names must be listed later. reservedFunction :: Parser Function reservedFunction = do { _ <- try $ string "asinh"; return Asinh } <|> do { _ <- try $ string "acosh"; return Acosh } <|> do { _ <- try $ string "atanh"; return Atanh } <|> do { _ <- try $ string "asin"; return Asin } <|> do { _ <- try $ string "acos"; return Acos } <|> do { _ <- try $ string "atan"; return Atan } <|> do { _ <- try $ string "sinh"; return Sinh } <|> do { _ <- try $ string "cosh"; return Cosh } <|> do { _ <- try $ string "tanh"; return Tanh } <|> do { _ <- try $ string "sin"; return Sin } <|> do { _ <- try $ string "cos"; return Cos } <|> do { _ <- try $ string "tan"; return Tan } <|> do { _ <- try $ string "abs"; return Abs } <|> do { _ <- try $ string "signum"; return Signum } <|> do { _ <- try $ string "log"; return Log } <|> do { _ <- try $ string "exp"; return Exp } numericConst :: Parser Expr numericConst = do { x <- integer; return (Const (I x)) } runLex :: String -> Expr runLex input = let result = parse ( do { whiteSpace ; x <- expr ; eof ; return x }) "" input in case result of Right ex -> ex Left err -> error (show err)
gwright83/Wheeler
src/Math/Symbolic/Wheeler/IO.hs
Haskell
bsd-3-clause
5,099
{-# LANGUAGE QuasiQuotes #-} module Main where import Test.Hspec import Test.QuickCheck import Test.QuickCheck.Instances import Data.Aeson as A import qualified Data.Text as T import qualified Data.Bson as B import Text.RawString.QQ import Data.Maybe import Data.Either import Transfuser.Lib import Transfuser.Types import Transfuser.Types.Arbitrary import Transfuser.Sql.Encoder main :: IO () main = hspec $ do describe "MongoDB JSON query language" $ do -- General parsing it "Any query expression will encode to SQL AST" $ property $ \expr -> isRight $ findToSqlText expr it "Any find expression will encode to SQL" $ property $ \expr -> isRight $ queryToSQL expr -- Specific examples it "Example query 1 parses" $ do isJust (decode eg1 :: Maybe QueryExpr) `shouldBe` True it "Example find expression 1 parses" $ do isJust (decode eg2 :: Maybe FindExpr) `shouldBe` True -- Single expression decoding it "encodes default equality" $ property $ \a b -> fromJSON (object [ a .= b ]) == A.Success (ExprConstr $ OpEQ a (B.String b)) it "encodes equality with $eq" $ property $ \a b -> fromJSON (object [ a .= object [ "$eq" .= b ] ]) == A.Success (ExprConstr $ OpEQ a (B.String b)) it "encodes logical and" $ property $ \a b c d -> fromJSON (object [ "$and" .= [object [a .= b], object [c .= d]] ]) == A.Success (ExprAND [ ExprConstr $ OpEQ a (B.String b) , ExprConstr $ OpEQ c (B.String d) ]) ------------------------------------------------------------------------------ eg1 = [r|{"$and": [ {"tracking_id.asic_id": "AAAA"}, {"membrane_summary": {"$exists": true}}, {"$or": [ {"context_tags": {"$exists": false}}, {"$and": [ {"context_tags.department": "qc"}, {"context_tags.experiment_type": "full_pore_insertion"} ]} ]} ]} |] eg2 = [r| { "collection": "col1", "projection": {"a": 1, "b": 1, "c": 1}, "query": {"$or": [ {"context_tags": {"$exists": false}}, {"$and": [ {"context_tags.department": "qc"}, {"context_tags.experiment_type": "full_pore_insertion"} ]} ]} } |]
stephenpascoe/mongo-sql
test/Spec.hs
Haskell
bsd-3-clause
2,384
{-# OPTIONS_HADDOCK hide #-} {-# LANGUAGE ExistentialQuantification #-} module Network.TLS.Crypto ( HashContext , HashCtx , hashInit , hashUpdate , hashUpdateSSL , hashFinal , module Network.TLS.Crypto.DH , module Network.TLS.Crypto.ECDH -- * Hash , hash , Hash(..) , hashName , hashDigestSize , hashBlockSize -- * key exchange generic interface , PubKey(..) , PrivKey(..) , PublicKey , PrivateKey , kxEncrypt , kxDecrypt , kxSign , kxVerify , KxError(..) ) where import qualified Crypto.Hash as H import qualified Data.ByteString as B import qualified Data.ByteArray as B (convert) import Data.ByteString (ByteString) import Crypto.Random import qualified Crypto.PubKey.DSA as DSA import qualified Crypto.PubKey.RSA as RSA import qualified Crypto.PubKey.RSA.PKCS15 as RSA import Data.X509 (PrivKey(..), PubKey(..)) import Network.TLS.Crypto.DH import Network.TLS.Crypto.ECDH import Data.ASN1.Types import Data.ASN1.Encoding import Data.ASN1.BinaryEncoding (DER(..), BER(..)) {-# DEPRECATED PublicKey "use PubKey" #-} type PublicKey = PubKey {-# DEPRECATED PrivateKey "use PrivKey" #-} type PrivateKey = PrivKey data KxError = RSAError RSA.Error | KxUnsupported deriving (Show) -- functions to use the hidden class. hashInit :: Hash -> HashContext hashInit MD5 = HashContext $ ContextSimple (H.hashInit :: H.Context H.MD5) hashInit SHA1 = HashContext $ ContextSimple (H.hashInit :: H.Context H.SHA1) hashInit SHA224 = HashContext $ ContextSimple (H.hashInit :: H.Context H.SHA224) hashInit SHA256 = HashContext $ ContextSimple (H.hashInit :: H.Context H.SHA256) hashInit SHA384 = HashContext $ ContextSimple (H.hashInit :: H.Context H.SHA384) hashInit SHA512 = HashContext $ ContextSimple (H.hashInit :: H.Context H.SHA512) hashInit SHA1_MD5 = HashContextSSL H.hashInit H.hashInit hashUpdate :: HashContext -> B.ByteString -> HashCtx hashUpdate (HashContext (ContextSimple h)) b = HashContext $ ContextSimple (H.hashUpdate h b) hashUpdate (HashContextSSL sha1Ctx md5Ctx) b = HashContextSSL (H.hashUpdate sha1Ctx b) (H.hashUpdate md5Ctx b) hashUpdateSSL :: HashCtx -> (B.ByteString,B.ByteString) -- ^ (for the md5 context, for the sha1 context) -> HashCtx hashUpdateSSL (HashContext _) _ = error "internal error: update SSL without a SSL Context" hashUpdateSSL (HashContextSSL sha1Ctx md5Ctx) (b1,b2) = HashContextSSL (H.hashUpdate sha1Ctx b2) (H.hashUpdate md5Ctx b1) hashFinal :: HashCtx -> B.ByteString hashFinal (HashContext (ContextSimple h)) = B.convert $ H.hashFinalize h hashFinal (HashContextSSL sha1Ctx md5Ctx) = B.concat [B.convert (H.hashFinalize md5Ctx), B.convert (H.hashFinalize sha1Ctx)] data Hash = MD5 | SHA1 | SHA224 | SHA256 | SHA384 | SHA512 | SHA1_MD5 deriving (Show,Eq) data HashContext = HashContext ContextSimple | HashContextSSL (H.Context H.SHA1) (H.Context H.MD5) instance Show HashContext where show _ = "hash-context" data ContextSimple = forall alg . H.HashAlgorithm alg => ContextSimple (H.Context alg) type HashCtx = HashContext hash :: Hash -> B.ByteString -> B.ByteString hash MD5 b = B.convert . (H.hash :: B.ByteString -> H.Digest H.MD5) $ b hash SHA1 b = B.convert . (H.hash :: B.ByteString -> H.Digest H.SHA1) $ b hash SHA224 b = B.convert . (H.hash :: B.ByteString -> H.Digest H.SHA224) $ b hash SHA256 b = B.convert . (H.hash :: B.ByteString -> H.Digest H.SHA256) $ b hash SHA384 b = B.convert . (H.hash :: B.ByteString -> H.Digest H.SHA384) $ b hash SHA512 b = B.convert . (H.hash :: B.ByteString -> H.Digest H.SHA512) $ b hash SHA1_MD5 b = B.concat [B.convert (md5Hash b), B.convert (sha1Hash b)] where sha1Hash :: B.ByteString -> H.Digest H.SHA1 sha1Hash = H.hash md5Hash :: B.ByteString -> H.Digest H.MD5 md5Hash = H.hash hashName :: Hash -> String hashName = show hashDigestSize :: Hash -> Int hashDigestSize MD5 = 16 hashDigestSize SHA1 = 20 hashDigestSize SHA224 = 28 hashDigestSize SHA256 = 32 hashDigestSize SHA384 = 48 hashDigestSize SHA512 = 64 hashDigestSize SHA1_MD5 = 36 hashBlockSize :: Hash -> Int hashBlockSize MD5 = 64 hashBlockSize SHA1 = 64 hashBlockSize SHA224 = 64 hashBlockSize SHA256 = 64 hashBlockSize SHA384 = 128 hashBlockSize SHA512 = 128 hashBlockSize SHA1_MD5 = 64 {- key exchange methods encrypt and decrypt for each supported algorithm -} generalizeRSAError :: Either RSA.Error a -> Either KxError a generalizeRSAError (Left e) = Left (RSAError e) generalizeRSAError (Right x) = Right x kxEncrypt :: MonadRandom r => PublicKey -> ByteString -> r (Either KxError ByteString) kxEncrypt (PubKeyRSA pk) b = generalizeRSAError `fmap` RSA.encrypt pk b kxEncrypt _ _ = return (Left KxUnsupported) kxDecrypt :: MonadRandom r => PrivateKey -> ByteString -> r (Either KxError ByteString) kxDecrypt (PrivKeyRSA pk) b = generalizeRSAError `fmap` RSA.decryptSafer pk b kxDecrypt _ _ = return (Left KxUnsupported) -- Verify that the signature matches the given message, using the -- public key. -- kxVerify :: PublicKey -> Hash -> ByteString -> ByteString -> Bool kxVerify (PubKeyRSA pk) alg msg sign = rsaVerifyHash alg pk msg sign kxVerify (PubKeyDSA pk) _ msg signBS = case dsaToSignature signBS of Just sig -> DSA.verify H.SHA1 pk sig msg _ -> False where dsaToSignature :: ByteString -> Maybe DSA.Signature dsaToSignature b = case decodeASN1' BER b of Left _ -> Nothing Right asn1 -> case asn1 of Start Sequence:IntVal r:IntVal s:End Sequence:_ -> Just $ DSA.Signature { DSA.sign_r = r, DSA.sign_s = s } _ -> Nothing kxVerify _ _ _ _ = False -- Sign the given message using the private key. -- kxSign :: MonadRandom r => PrivateKey -> Hash -> ByteString -> r (Either KxError ByteString) kxSign (PrivKeyRSA pk) hashAlg msg = generalizeRSAError `fmap` rsaSignHash hashAlg pk msg kxSign (PrivKeyDSA pk) _ msg = do sign <- DSA.sign pk H.SHA1 msg return (Right $ encodeASN1' DER $ dsaSequence sign) where dsaSequence sign = [Start Sequence,IntVal (DSA.sign_r sign),IntVal (DSA.sign_s sign),End Sequence] --kxSign g _ _ _ = -- (Left KxUnsupported, g) rsaSignHash :: MonadRandom m => Hash -> RSA.PrivateKey -> ByteString -> m (Either RSA.Error ByteString) rsaSignHash SHA1_MD5 pk msg = RSA.signSafer noHash pk msg rsaSignHash MD5 pk msg = RSA.signSafer (Just H.MD5) pk msg rsaSignHash SHA1 pk msg = RSA.signSafer (Just H.SHA1) pk msg rsaSignHash SHA224 pk msg = RSA.signSafer (Just H.SHA224) pk msg rsaSignHash SHA256 pk msg = RSA.signSafer (Just H.SHA256) pk msg rsaSignHash SHA384 pk msg = RSA.signSafer (Just H.SHA384) pk msg rsaSignHash SHA512 pk msg = RSA.signSafer (Just H.SHA512) pk msg rsaVerifyHash :: Hash -> RSA.PublicKey -> ByteString -> ByteString -> Bool rsaVerifyHash SHA1_MD5 = RSA.verify noHash rsaVerifyHash MD5 = RSA.verify (Just H.MD5) rsaVerifyHash SHA1 = RSA.verify (Just H.SHA1) rsaVerifyHash SHA224 = RSA.verify (Just H.SHA224) rsaVerifyHash SHA256 = RSA.verify (Just H.SHA256) rsaVerifyHash SHA384 = RSA.verify (Just H.SHA384) rsaVerifyHash SHA512 = RSA.verify (Just H.SHA512) noHash :: Maybe H.MD5 noHash = Nothing
AaronFriel/hs-tls
core/Network/TLS/Crypto.hs
Haskell
bsd-3-clause
7,539
{-# LANGUAGE PatternGuards #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ViewPatterns #-} {-# LANGUAGE QuasiQuotes #-} -- | Main entry point to hindent. -- -- hindent module Main where import HIndent import HIndent.Types import Control.Applicative import Control.Applicative.QQ.Idiom import Data.List import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.Lazy.Builder as T import qualified Data.Text.Lazy.IO as T import Data.Version (showVersion) import Descriptive import Descriptive.Options import GHC.Tuple import Language.Haskell.Exts.Annotated hiding (Style,style) import Paths_hindent (version) import System.Environment import Text.Read -- | Main entry point. main :: IO () main = do args <- getArgs case consume options (map T.pack args) of Succeeded (style,exts) -> T.interact (either error T.toLazyText . reformat style (Just exts)) Failed (Wrap (Stopped Version) _) -> putStrLn ("hindent " ++ showVersion version) _ -> error (T.unpack (textDescription (describe options []))) -- | Options that stop the argument parser. data Stoppers = Version deriving (Show) -- | Program options. options :: Monad m => Consumer [Text] (Option Stoppers) m (Style,[Extension]) options = ver *> [i|(,) style exts|] where ver = stop (flag "version" "Print the version" Version) style = [i|makeStyle (constant "--style" "Style to print with" () *> foldr1 (<|>) (map (\s -> constant (styleName s) (styleDescription s) s) styles)) lineLen|] exts = fmap getExtensions (many (prefix "X" "Language extension")) lineLen = fmap (>>= (readMaybe . T.unpack)) (optional (arg "line-length" "Desired length of lines")) makeStyle s mlen = case mlen of Nothing -> s Just len -> s {styleDefConfig = (styleDefConfig s) {configMaxColumns = len}} -------------------------------------------------------------------------------- -- Extensions stuff stolen from hlint -- | Consume an extensions list from arguments. getExtensions :: [Text] -> [Extension] getExtensions = foldl f defaultExtensions . map T.unpack where f _ "Haskell98" = [] f a ('N':'o':x) | Just x' <- readExtension x = delete x' a f a x | Just x' <- readExtension x = x' : delete x' a f _ x = error $ "Unknown extension: " ++ x -- | Parse an extension. readExtension :: String -> Maybe Extension readExtension x = case classifyExtension x of UnknownExtension _ -> Nothing x' -> Just x' -- | Default extensions. defaultExtensions :: [Extension] defaultExtensions = [e | e@EnableExtension{} <- knownExtensions] \\ map EnableExtension badExtensions -- | Extensions which steal too much syntax. badExtensions :: [KnownExtension] badExtensions = [Arrows -- steals proc ,TransformListComp -- steals the group keyword ,XmlSyntax, RegularPatterns -- steals a-b ,UnboxedTuples -- breaks (#) lens operator -- ,QuasiQuotes -- breaks [x| ...], making whitespace free list comps break ]
adamse/hindent
src/main/Main.hs
Haskell
bsd-3-clause
3,616
module Types.Common ( sanitizeUserText , sanitizeUserText' , sanitizeChar ) where import Prelude () import Prelude.MH import qualified Data.Text as T import Network.Mattermost.Types ( UserText, unsafeUserText ) sanitizeUserText :: UserText -> T.Text sanitizeUserText = sanitizeUserText' . unsafeUserText sanitizeUserText' :: T.Text -> T.Text sanitizeUserText' t = T.replace "\ESC" "<ESC>" $ T.replace "\t" " " t sanitizeChar :: Char -> T.Text sanitizeChar '\ESC' = "<ESC>" sanitizeChar '\t' = " " sanitizeChar c = T.singleton c
aisamanra/matterhorn
src/Types/Common.hs
Haskell
bsd-3-clause
550
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. {-# LANGUAGE GADTs #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE NoRebindableSyntax #-} module Duckling.Numeral.AR.EG.Rules (rules) where import Data.Maybe import Prelude import qualified Data.HashMap.Strict as HashMap import Duckling.Dimensions.Types import Duckling.Numeral.AR.EG.Helpers ( digitsMap , parseArabicDoubleFromText , parseArabicIntegerFromText ) import Duckling.Numeral.Helpers import Duckling.Numeral.Types (NumeralData (..)) import Duckling.Regex.Types import Duckling.Types import qualified Duckling.Numeral.Types as TNumeral ruleInteger2 :: Rule ruleInteger2 = Rule { name = "integer 2" , pattern = [ regex "[إأا]?تني[ي]?ن" ] , prod = \_ -> integer 2 } ruleInteger3 :: Rule ruleInteger3 = Rule { name = "integer 3" , pattern = [ regex "تلات[هة]?" ] , prod = \_ -> integer 3 } ruleInteger8 :: Rule ruleInteger8 = Rule { name = "integer 8" , pattern = [ regex "تمان(ي[هة])?" ] , prod = \_ -> integer 8 } ruleInteger11 :: Rule ruleInteger11 = Rule { name = "integer 11" , pattern = [ regex "(إأا)?حداشر" ] , prod = \_ -> integer 11 } ruleInteger12 :: Rule ruleInteger12 = Rule { name = "integer 12" , pattern = [ regex "[إأا]?[تط]ناشر" ] , prod = \_ -> integer 12 } ruleInteger13 :: Rule ruleInteger13 = Rule { name = "integer 13" , pattern = [ regex "[تط]ل(ا)?[تط]اشر" ] , prod = \_ -> integer 13 } ruleInteger14 :: Rule ruleInteger14 = Rule { name = "integer 14" , pattern = [ regex "[إأا]ربع[تط]اشر" ] , prod = \_ -> integer 14 } ruleInteger15 :: Rule ruleInteger15 = Rule { name = "integer 15" , pattern = [ regex "خمس[تط]اشر" ] , prod = \_ -> integer 15 } ruleInteger16 :: Rule ruleInteger16 = Rule { name = "integer 16" , pattern = [ regex "س[تط]اشر" ] , prod = \_ -> integer 16 } ruleInteger17 :: Rule ruleInteger17 = Rule { name = "integer 17" , pattern = [ regex "سبع[تط]اشر" ] , prod = \_ -> integer 17 } ruleInteger18 :: Rule ruleInteger18 = Rule { name = "integer 18" , pattern = [ regex "[تط]من[تط]اشر" ] , prod = \_ -> integer 18 } ruleInteger19 :: Rule ruleInteger19 = Rule { name = "integer 19" , pattern = [ regex "تسع[تط]اشر" ] , prod = \_ -> integer 19 } ruleInteger30_80 :: Rule ruleInteger30_80 = Rule { name = "integer (30, 80)" , pattern = [ regex "([تط]لا[تط]|[تط]مان)(ين)" ] , prod = \tokens -> case tokens of Token RegexMatch (GroupMatch (match:_)):_ -> (* 10) <$> HashMap.lookup match digitsMap >>= integer _ -> Nothing } ruleInteger100 :: Rule ruleInteger100 = Rule { name = "integer (100)" , pattern = [ regex "مي[هةت]" ] , prod = const $ integer 100 } ruleInteger200 :: Rule ruleInteger200 = Rule { name = "integer (200)" , pattern = [ regex "م(ي)?تين" ] , prod = const $ integer 200 } ruleInteger300 :: Rule ruleInteger300 = Rule { name = "integer (300)" , pattern = [ regex "([تط]و?لا?[تط]و?)مي[هةت]" ] , prod = const $ integer 300 } ruleInteger400 :: Rule ruleInteger400 = Rule { name = "integer (400)" , pattern = [ regex "(رو?بعو?)مي[هةت]" ] , prod = const $ integer 400 } ruleInteger500 :: Rule ruleInteger500 = Rule { name = "integer (500)" , pattern = [ regex "(خو?مسو?)مي[هةت]" ] , prod = const $ integer 500 } ruleInteger600 :: Rule ruleInteger600 = Rule { name = "integer (600)" , pattern = [ regex "(سو?تو?)مي[هةت]" ] , prod = const $ integer 600 } ruleInteger700 :: Rule ruleInteger700 = Rule { name = "integer (700)" , pattern = [ regex "(سو?بعو?)مي[هةت]" ] , prod = const $ integer 700 } ruleInteger800 :: Rule ruleInteger800 = Rule { name = "integer (800)" , pattern = [ regex "([تط]و?منو?)مي[هةت]" ] , prod = const $ integer 800 } ruleInteger900 :: Rule ruleInteger900 = Rule { name = "integer (900)" , pattern = [ regex "([تط]و?سعو?)مي[هةت]" ] , prod = const $ integer 900 } ruleInteger101_999 :: Rule ruleInteger101_999 = Rule { name = "integer 101..999" , pattern = [ oneOf [100, 200 .. 900] , regex "\\s" , oneOf $ map (+) [10, 20 .. 90] <*> [1..9] ] , prod = \tokens -> case tokens of (Token Numeral NumeralData{TNumeral.value = v1}: _: Token Numeral NumeralData{TNumeral.value = v2}: _) -> double $ v1 + v2 _ -> Nothing } ruleInteger3000 :: Rule ruleInteger3000 = Rule { name = "integer (3000)" , pattern = [ regex "([تط]لا?[تط])( ?[اآ])?لاف" ] , prod = const $ integer 3000 } ruleInteger4000 :: Rule ruleInteger4000 = Rule { name = "integer (4000)" , pattern = [ regex "[أا]ربع(ت| ?[اآ])لاف" ] , prod = const $ integer 4000 } ruleInteger5000 :: Rule ruleInteger5000 = Rule { name = "integer (5000)" , pattern = [ regex "خمس(ت| ?[اآ])لاف" ] , prod = const $ integer 5000 } ruleInteger6000 :: Rule ruleInteger6000 = Rule { name = "integer (6000)" , pattern = [ regex "س(ت| ?[اآ])لاف" ] , prod = const $ integer 6000 } ruleInteger7000 :: Rule ruleInteger7000 = Rule { name = "integer (7000)" , pattern = [ regex "سبع(ت| ?[اآ])لاف" ] , prod = const $ integer 7000 } ruleInteger8000 :: Rule ruleInteger8000 = Rule { name = "integer (8000)" , pattern = [ regex "[تط]م[ا]?ن(ت| ?[اآ])لاف" ] , prod = const $ integer 8000 } ruleInteger9000 :: Rule ruleInteger9000 = Rule { name = "integer (9000)" , pattern = [ regex "([تط]سع)(ت| ?[اآ])لاف" ] , prod = const $ integer 9000 } rules :: [Rule] rules = [ ruleInteger2 , ruleInteger3 , ruleInteger8 , ruleInteger11 , ruleInteger12 , ruleInteger13 , ruleInteger14 , ruleInteger15 , ruleInteger16 , ruleInteger17 , ruleInteger18 , ruleInteger19 , ruleInteger30_80 , ruleInteger100 , ruleInteger200 , ruleInteger300 , ruleInteger400 , ruleInteger500 , ruleInteger600 , ruleInteger700 , ruleInteger800 , ruleInteger900 , ruleInteger101_999 , ruleInteger3000 , ruleInteger4000 , ruleInteger5000 , ruleInteger6000 , ruleInteger7000 , ruleInteger8000 , ruleInteger9000 ]
facebookincubator/duckling
Duckling/Numeral/AR/EG/Rules.hs
Haskell
bsd-3-clause
6,691
{- n! means n × (n − 1) × ... × 3 × 2 × 1 For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800, and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27. Find the sum of the digits in the number 100! -} import Data.Char fact :: Integer -> Integer fact n = product [1..n] digit_sum :: Int digit_sum = sum . map digitToInt . show . fact $ 100 main :: IO () main = do putStrLn . show $ digit_sum
bgwines/project-euler
src/solved/problem20.hs
Haskell
bsd-3-clause
433
module Bounded where import Base instance Bounded () where minBound = () maxBound = () instance (Bounded a, Bounded b) => Bounded (a,b) where minBound = (minBound, minBound) maxBound = (maxBound, maxBound) instance (Bounded a, Bounded b, Bounded c) => Bounded (a,b,c) where minBound = (minBound, minBound, minBound) maxBound = (maxBound, maxBound, maxBound) instance (Bounded a, Bounded b, Bounded c, Bounded d) => Bounded (a,b,c,d) where minBound = (minBound, minBound, minBound,minBound) maxBound = (maxBound, maxBound, maxBound, maxBound) instance (Bounded a, Bounded b, Bounded c, Bounded d,Bounded e) => Bounded (a,b,c,d,e) where minBound = (minBound, minBound, minBound,minBound, minBound) maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound) instance (Bounded a, Bounded b, Bounded c, Bounded d,Bounded e, Bounded f) => Bounded (a,b,c,d,e,f) where minBound = (minBound, minBound, minBound,minBound, minBound, minBound) maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound) instance (Bounded a, Bounded b, Bounded c, Bounded d,Bounded e, Bounded f, Bounded g) => Bounded (a,b,c,d,e,f,g) where minBound = (minBound, minBound, minBound,minBound, minBound, minBound, minBound) maxBound = (maxBound, maxBound, maxBound, maxBound, maxBound, maxBound, maxBound)
rodrigogribeiro/mptc
src/Libs/Bounded.hs
Haskell
bsd-3-clause
1,366
{-# LANGUAGE OverloadedStrings #-} import Control.Monad import Control.Concurrent import System.IO import Text.XML.Pipe import Network import HttpPullSv main :: IO () main = do soc <- listenOn $ PortNumber 80 forever $ do (h, _, _) <- accept soc void . forkIO $ testPusher (undefined :: HttpPullSv Handle) (One h) (isPoll, endPoll) isPoll :: XmlNode -> Bool isPoll (XmlNode (_, "poll") _ _ _) = True isPoll _ = False endPoll :: XmlNode endPoll = XmlNode (nullQ "nothing") [] [] []
YoshikuniJujo/forest
subprojects/xml-push/testHttpPullSv.hs
Haskell
bsd-3-clause
495
{-# LANGUAGE ForeignFunctionInterface #-} {-# CFILES csrc/gsl_interp.c #-} -- | Cubic-spline interpolation (natural boundary conditions) with the GNU Scientific Library -- -- All @Double@ @Vector@ types are @Unboxed@ - conversion to @Storable@ @CDouble@ is performed internally. -- -- TODO: Possible improvements include wrapping the 'InterpStructPtr' in a -- @ForeignPtr@ and registering the 'interpFree' function as a finalizer. -- For now, I prefer to handle the deallocation explicitly. In addition, leaving -- the 'InterpStructPtr' as a plain @Ptr@ type alias keeps the evaluation -- functions out of the @IO@ Monad (no requirement to use @withForeignPtr@) -- or alternatively from using @unsafeForeignPtrToPtr@ excessively. module Math.GSLInterp ( InterpStruct (..) , InterpStructPtr , interpInit , interpFree , interpEval , interpEvalDeriv , interpEvalSecondDeriv , interpEvalInteg ) where import Foreign.C import Foreign.Ptr import Foreign.ForeignPtr hiding (unsafeForeignPtrToPtr) import Foreign.ForeignPtr.Unsafe (unsafeForeignPtrToPtr) import qualified Data.Vector.Storable as S import qualified Data.Vector.Unboxed as V import Control.Monad (unless) import Text.Printf -- | Unit-like type representing foreign interpolant structure data InterpStruct = InterpStruct -- | Convenient type alias for pointer to foreign interpolant structure type InterpStructPtr = Ptr InterpStruct -- FFI interfaces for wrapper code (C) foreign import ccall "gsl_interp_init_wrapper" gslInterpInit :: Ptr CDouble -> Ptr CDouble -> CInt -> CDouble -> IO InterpStructPtr foreign import ccall "gsl_interp_free_wrapper" gslInterpFree :: InterpStructPtr -> IO () foreign import ccall "gsl_interp_eval_wrapper" gslInterpEval :: InterpStructPtr -> CDouble -> CDouble foreign import ccall "gsl_interp_eval_deriv_wrapper" gslInterpEvalDeriv :: InterpStructPtr -> CDouble -> CDouble foreign import ccall "gsl_interp_eval_deriv2_wrapper" gslInterpEvalSecondDeriv :: InterpStructPtr -> CDouble -> CDouble foreign import ccall "gsl_interp_eval_integ_wrapper" gslInterpEvalInteg :: InterpStructPtr -> CDouble -> CDouble -> CDouble -- Helpers used below -- Converts an Unboxed Vector of Doubles to a Storable Vector of CDoubles toStorable :: V.Vector Double -> S.Vector CDouble toStorable = S.map realToFrac . S.convert -- Converts a function of type CDouble -> CDouble to one of Double -> Double wrapDouble :: (CDouble -> CDouble) -> Double -> Double wrapDouble f = realToFrac . f . realToFrac -- Converts a function of type CDouble -> CDouble -> CDouble to one of Double -> Double -> Double wrapDouble3 :: (CDouble -> CDouble -> CDouble) -> Double -> Double -> Double wrapDouble3 f x = wrapDouble $ f (realToFrac x) -- | Initialization of a GSL cubic-spline interpolant -- -- Fails on: (1) memory-allocation failure within the C-based wrapper; or (2) unequal dimension of user-supplied abscissa and ordinate vectors. interpInit :: V.Vector Double -- ^ Unboxed @Vector@ of abscissae -> V.Vector Double -- ^ Unboxed @Vector@ of ordinates -> Double -- ^ Fill-value returned on bounds errors -> IO (Maybe InterpStructPtr) -- ^ @Maybe@ pointer to the resulting interpolant structure (returns @Nothing@ on failure) interpInit xs ys v = do -- convert to S.Vector CDouble, extract ForeignPtrs let (fpx,nx) = S.unsafeToForeignPtr0 . toStorable $ xs (fpy,ny) = S.unsafeToForeignPtr0 . toStorable $ ys -- check for dimension mismatch if nx /= ny then printf "Error [interpInit]: vector dimension mismatch: %i /= %i\n" nx ny >> return Nothing else do -- initialize foreign interpolant state structure interp <- gslInterpInit (unsafeForeignPtrToPtr fpx) (unsafeForeignPtrToPtr fpy) (fromIntegral ny) (realToFrac v) -- ensure the ForeignPtrs live until _after_ call to gslInterpInit touchForeignPtr fpx touchForeignPtr fpy -- check for failure and return if interp == nullPtr then printf "Error [interpInit]: init returned null pointer\n" >> return Nothing else return . Just $ interp -- | Free storage associated with the foreign interpolant structure interpFree :: InterpStructPtr -> IO () interpFree p = unless (p == nullPtr) (gslInterpFree p) -- | Evaluate the cubic spline interpolant associated with the supplied interpolant structure interpEval :: InterpStructPtr -- ^ Foreign interpolant structure -> Double -- ^ x-value -> Double -- ^ interpolated y-value interpEval = wrapDouble . gslInterpEval -- | Evaluate the first derivative of the cubic spline interpolant associated with the supplied interpolant structure interpEvalDeriv :: InterpStructPtr -- ^ Foreign interpolant structure -> Double -- ^ x-value -> Double -- ^ derivative interpEvalDeriv = wrapDouble . gslInterpEvalDeriv -- | Evaluate the second derivative of the cubic spline interpolant associated with the supplied interpolant structure interpEvalSecondDeriv :: InterpStructPtr -- ^ Foreign interpolant structure -> Double -- ^ x-value -> Double -- ^ second derivative interpEvalSecondDeriv = wrapDouble . gslInterpEvalSecondDeriv -- | Evaluate the defintie integral of the cubic spline interpolant associated with the supplied interpolant structure within the specified range interpEvalInteg :: InterpStructPtr -- ^ Foreign interpolant structure -> Double -- ^ x-value of lower integration bound -> Double -- ^ x-value of upper integration bound -> Double -- ^ integral interpEvalInteg = wrapDouble3 . gslInterpEvalInteg
swfrench/GSLInterp
src/Math/GSLInterp.hs
Haskell
bsd-3-clause
5,691
{-#LANGUAGE TemplateHaskell #-} module Parser.Rename (runRename) where import Data.DataType import Control.Lens import qualified Data.Map.Strict as M import Control.Monad.State import Control.Monad.Except data Buffer = Buffer { _counter :: Int , _upper :: M.Map String Int , _current :: M.Map String Int , _vars :: [IntVar] } makeLenses '' Buffer initialBuffer = Buffer 0 M.empty M.empty [] type Rename = StateT Buffer Stage declVar :: LitVar -> Rename IntVar declVar (Var x pos) = do test <- uses current (M.member x) if test then throw (NameCollition x pos) else do now <- use counter counter += 1 current %= M.insert x now let newV = Slot now x pos vars %= (newV :) return newV useVar :: LitVar -> Rename IntVar useVar (Var x pos) = do cur <- use current upp <- use upper let find = M.lookup x case (find cur, find upp) of (Just a, _) -> return (Slot a x pos) (Nothing, Just a) -> return (Slot a x pos) _ -> throw (NotInScope x pos) -- | restore state after exec the action restore :: Rename a -> Rename a restore ac = do old <- get res <- ac newCont <- use counter put (counter .~ newCont $ old) return res descend :: Rename () descend = do cur <- use current upper %= M.union cur current .= M.empty vars .= [] renameExpr :: LitExpr -> Rename RenamedExpr renameExpr (Id var) = fmap Id (useVar var) renameExpr (AppFun fun args) = do newf <- useVar fun newArgs <- mapM renameExpr args return (AppFun newf newArgs) renameExpr (Plus e1 e2) = renameTwo Plus e1 e2 renameExpr (Minus e1 e2) = renameTwo Minus e1 e2 renameExpr (Mult e1 e2) = renameTwo Mult e1 e2 renameExpr (Div e1 e2) = renameTwo Div e1 e2 renameExpr (Num n) = return (Num n) renameTwo f e1 e2 = do newE1 <- renameExpr e1 newE2 <- renameExpr e2 return (f newE1 newE2) renameCommand :: LitCommand -> Rename RenamedCommand renameCommand (Decl vars) = fmap Decl (mapM declVar vars) renameCommand (Value ex) = fmap Value (renameExpr ex) renameCommand (Func f paras pro) = do newF <- declVar f restore $ do descend newParas <- mapM declVar paras newPro <- renameProgram pro freed <- use vars return $ Record newF newParas newPro freed renameCommand (LetBe var ex) = do newVar <- useVar var newEx <- renameExpr ex return (LetBe newVar newEx) renameCommand (RunFun fun args) = do newFun <- useVar fun newArgs <- mapM renameExpr args return (RunFun newFun newArgs) renameCommand (Return ex) = fmap Return (renameExpr ex) renameCommand (Read var) = fmap Read (useVar var) renameCommand (Print ex) = fmap Print (renameExpr ex) renameProgram ::LitProgram -> Rename RenamedProgram renameProgram = mapM renameCommand runRename :: LitProgram -> Stage RenamedProgram runRename pro = evalStateT (renameProgram pro) initialBuffer
jyh1/mini
src/Parser/Rename.hs
Haskell
bsd-3-clause
2,846
module Watch.Spew where import Data.Foldable import Data.List.NonEmpty import qualified Data.Map as M import System.Console.ANSI import System.FilePath import System.FilePath.Glob import Watch.Types showConcerns :: Refs -> IO () showConcerns cMap = forM_ (M.toList cMap) $ \ (file, d :| ds) -> do setSGR [SetColor Foreground Dull Yellow] putStrLn file setSGR [SetColor Foreground Dull Black] putStr " -> " setSGR [Reset] putStrLn (comp d) forM_ ds $ \ t -> putStrLn $ " " ++ comp t where comp = uncurry (\ a b -> a </> decompile b)
pikajude/src-watch
src/Watch/Spew.hs
Haskell
bsd-3-clause
601