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
|
|---|---|---|---|---|---|
module UnionFind(UF, Replacement((:>)), newSym, (=:=), rep, frozen, runUF, S, isRep) where
import Prelude hiding (min)
import Control.Monad.State.Strict
import Data.IntMap(IntMap)
import qualified Data.IntMap as IntMap
data S = S {
links :: IntMap Int,
sym :: Int
}
type UF = State S
data Replacement = Int :> Int
runUF :: Int -> UF a -> a
runUF numSyms m = fst (runState m (S IntMap.empty numSyms))
modifyLinks f = modify (\s -> s { links = f (links s) })
modifySym f = modify (\s -> s { sym = f (sym s) })
putLinks l = modifyLinks (const l)
newSym :: UF Int
newSym = do
s <- get
modifySym (+1)
return (sym s)
(=:=) :: Int -> Int -> UF (Maybe Replacement)
s =:= t | s == t = return Nothing
s =:= t = do
rs <- rep s
rt <- rep t
if (rs /= rt) then do
modifyLinks (IntMap.insert rs rt)
return (Just (rs :> rt))
else return Nothing
rep :: Int -> UF Int
rep t = do
m <- fmap links get
case IntMap.lookup t m of
Nothing -> return t
Just t' -> do
r <- rep t'
when (t' /= r) $ modifyLinks (IntMap.insert t r)
return r
isRep :: Int -> UF Bool
isRep t = do
t' <- frozen (rep t)
return (t == t')
frozen :: UF a -> UF a
frozen x = fmap (evalState x) get
|
jystic/QuickSpec
|
qs1/UnionFind.hs
|
Haskell
|
bsd-3-clause
| 1,225
|
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances #-}
module Sys.CreateProcess(
CreateProcess(..)
, AsCreateProcess(..)
, AsWorkingDirectory(..)
, AsEnvironment(..)
, AsStdin(..)
, AsStdout(..)
, AsStderr(..)
, AsCloseDescriptors(..)
, AsCreateGroup(..)
, AsDelegateCtrlC(..)
) where
import Control.Applicative(Applicative)
import Control.Category(Category(id, (.)))
import Control.Lens(Optic', Profunctor, lens, from, iso, (#))
import Data.Bool(Bool)
import Data.Eq(Eq)
import Data.Functor(Functor)
import Data.Maybe(Maybe)
import Data.String(String)
import Prelude(Show)
import Sys.CmdSpec(CmdSpec, AsCmdSpec(_CmdSpec), AsExecutableName(_ExecutableName), AsExecutableArguments(_ExecutableArguments), AsShellCommand(_ShellCommand), AsRawCommand(_RawCommand))
import Sys.StdStream(StdStream, AsStdStream(_StdStream))
import System.FilePath(FilePath)
import System.Posix.Types(GroupID, UserID)
import qualified System.Process as Process
-- | Data type representing a process.
--
-- /see 'System.Process.CreateProcess'/.
data CreateProcess =
CreateProcess
CmdSpec
(Maybe FilePath)
(Maybe [(String,String)])
StdStream
StdStream
StdStream
Bool
Bool
Bool
Bool
Bool
Bool
(Maybe GroupID)
(Maybe UserID)
deriving (Eq, Show)
-- | Types that related to @CreateProcess@.
class AsCreateProcess p f s where
_CreateProcess ::
Optic' p f s CreateProcess
instance AsCreateProcess p f CreateProcess where
_CreateProcess =
id
instance (Profunctor p, Functor f) => AsCreateProcess p f Process.CreateProcess where
_CreateProcess =
iso
(\(Process.CreateProcess s p e i o r d g c x1 x2 x3 x4 x5) ->
CreateProcess (from _CmdSpec # s) p e (from _StdStream # i) (from _StdStream # o) (from _StdStream # r) d g c x1 x2 x3 x4 x5)
(\(CreateProcess s p e i o r d g c x1 x2 x3 x4 x5) ->
Process.CreateProcess (_CmdSpec # s) p e (_StdStream # i) (_StdStream # o) (_StdStream # r) d g c x1 x2 x3 x4 x5)
instance Functor f => AsCmdSpec (->) f CreateProcess where
_CmdSpec =
lens
(\(CreateProcess s _ _ _ _ _ _ _ _ _ _ _ _ _) -> s)
(\(CreateProcess _ p e i o r d g c x1 x2 x3 x4 x5) s -> CreateProcess s p e i o r d g c x1 x2 x3 x4 x5)
instance Applicative f => AsExecutableName (->) f CreateProcess where
_ExecutableName =
_CmdSpec . _ExecutableName
instance Applicative f => AsExecutableArguments (->) f CreateProcess where
_ExecutableArguments =
_CmdSpec . _ExecutableArguments
instance Applicative f => AsShellCommand (->) f CreateProcess where
_ShellCommand =
_CmdSpec . _ShellCommand
instance Applicative f => AsRawCommand (->) f CreateProcess where
_RawCommand =
_CmdSpec . _RawCommand
-- | Types that relate to a (maybe) working directory.
class AsWorkingDirectory p f s where
_WorkingDirectory ::
Optic' p f s (Maybe FilePath)
instance AsWorkingDirectory p f (Maybe FilePath) where
_WorkingDirectory =
id
instance Functor f => AsWorkingDirectory (->) f CreateProcess where
_WorkingDirectory =
lens
(\(CreateProcess _ p _ _ _ _ _ _ _ _ _ _ _ _) -> p)
(\(CreateProcess s _ e i o r d g c x1 x2 x3 x4 x5) p -> CreateProcess s p e i o r d g c x1 x2 x3 x4 x5)
-- | Types that relate to an environment.
class AsEnvironment p f s where
_Environment ::
Optic' p f s (Maybe [(String, String)])
instance AsEnvironment p f (Maybe [(String, String)]) where
_Environment =
id
instance Functor f => AsEnvironment (->) f CreateProcess where
_Environment =
lens
(\(CreateProcess _ _ e _ _ _ _ _ _ _ _ _ _ _) -> e)
(\(CreateProcess s p _ i o r d g c x1 x2 x3 x4 x5) e -> CreateProcess s p e i o r d g c x1 x2 x3 x4 x5)
-- | Types that relate to a standard input stream.
class AsStdin p f s where
_Stdin ::
Optic' p f s StdStream
instance AsStdin p f StdStream where
_Stdin =
id
instance Functor f => AsStdin (->) f CreateProcess where
_Stdin =
lens
(\(CreateProcess _ _ _ i _ _ _ _ _ _ _ _ _ _) -> i)
(\(CreateProcess s p e _ o r d g c x1 x2 x3 x4 x5) i -> CreateProcess s p e i o r d g c x1 x2 x3 x4 x5)
-- | Types that relate to a standard output stream.
class AsStdout p f s where
_Stdout ::
Optic' p f s StdStream
instance AsStdout p f StdStream where
_Stdout =
id
instance Functor f => AsStdout (->) f CreateProcess where
_Stdout =
lens
(\(CreateProcess _ _ _ _ o _ _ _ _ _ _ _ _ _) -> o)
(\(CreateProcess s p e i _ r d g c x1 x2 x3 x4 x5) o -> CreateProcess s p e i o r d g c x1 x2 x3 x4 x5)
-- | Types that relate to a standard error stream.
class AsStderr p f s where
_Stderr ::
Optic' p f s StdStream
instance AsStderr p f StdStream where
_Stderr =
id
instance Functor f => AsStderr (->) f CreateProcess where
_Stderr =
lens
(\(CreateProcess _ _ _ _ _ r _ _ _ _ _ _ _ _) -> r)
(\(CreateProcess s p e i o _ d g c x1 x2 x3 x4 x5) r -> CreateProcess s p e i o r d g c x1 x2 x3 x4 x5)
-- | Types that relate to closing descriptors.
class AsCloseDescriptors p f s where
_CloseDescriptors ::
Optic' p f s Bool
instance AsCloseDescriptors p f Bool where
_CloseDescriptors =
id
instance Functor f => AsCloseDescriptors (->) f CreateProcess where
_CloseDescriptors =
lens
(\(CreateProcess _ _ _ _ _ _ d _ _ _ _ _ _ _) -> d)
(\(CreateProcess s p e i o r _ g c x1 x2 x3 x4 x5) d -> CreateProcess s p e i o r d g c x1 x2 x3 x4 x5)
-- | Types that relate to creating groups.
class AsCreateGroup p f s where
_CreateGroup ::
Optic' p f s Bool
instance AsCreateGroup p f Bool where
_CreateGroup =
id
instance Functor f => AsCreateGroup (->) f CreateProcess where
_CreateGroup =
lens
(\(CreateProcess _ _ _ _ _ _ _ g _ _ _ _ _ _) -> g)
(\(CreateProcess s p e i o r d _ c x1 x2 x3 x4 x5) g-> CreateProcess s p e i o r d g c x1 x2 x3 x4 x5)
-- | Types that relate to delegating CTRL-C.
class AsDelegateCtrlC p f s where
_DelegateCtrlC ::
Optic' p f s Bool
instance AsDelegateCtrlC p f Bool where
_DelegateCtrlC =
id
instance Functor f => AsDelegateCtrlC (->) f CreateProcess where
_DelegateCtrlC =
lens
(\(CreateProcess _ _ _ _ _ _ _ _ c _ _ _ _ _) -> c)
(\(CreateProcess s p e i o r d g _ x1 x2 x3 x4 x5) c -> CreateProcess s p e i o r d g c x1 x2 x3 x4 x5)
|
NICTA/sys-process
|
src/Sys/CreateProcess.hs
|
Haskell
|
bsd-3-clause
| 6,412
|
-----------------------------------------------------------------------------
-- |
-- Module : Data.Digest.MD5
-- Copyright : (c) Dominic Steinitz 2004
-- License : BSD-style (see the file ReadMe.tex)
--
-- Maintainer : dominic.steinitz@blueyonder.co.uk
-- Stability : experimental
-- Portability : portable
--
-- Takes the MD5 module supplied by Ian Lynagh and wraps it so it
-- takes [Octet] and returns [Octet] where the length of the result
-- is always 16.
-- See <http://web.comlab.ox.ac.uk/oucl/work/ian.lynagh/>
-- and <http://www.ietf.org/rfc/rfc1321.txt>.
--
-----------------------------------------------------------------------------
module Network.HTTP.MD5
( hash
, Octet
) where
import Data.List (unfoldr)
import Data.Word (Word8)
import Numeric (readHex)
import Network.HTTP.MD5Aux (md5s, Str(Str))
type Octet = Word8
-- | Take [Octet] and return [Octet] according to the standard.
-- The length of the result is always 16 octets or 128 bits as required
-- by the standard.
hash :: [Octet] -> [Octet]
hash xs =
unfoldr f $ md5s $ Str $ map (toEnum . fromIntegral) xs
where f :: String -> Maybe (Octet,String)
f [] = Nothing
f [x] = f ['0',x]
f (x:y:zs) = Just (a,zs)
where [(a,_)] = readHex (x:y:[])
|
astro/HTTPbis
|
Network/HTTP/MD5.hs
|
Haskell
|
bsd-3-clause
| 1,331
|
module ParserSpec where
import qualified Data.Vector as Vec
import Function
import qualified Library as Lib
import Parser
import Test.Hspec
import Text.Trifecta
toEither :: Result a -> Either String a
toEither (Success a) = Right a
toEither (Failure e) = Left $ show e
fSin = simpleFunc "sin" $ Right . sin
fLog = simpleFunc "log" $ Right . log
fExp = simpleFunc "exp" $ Right . exp
suite :: SpecWith ()
suite = do
describe "Ignore junk" $ do
let parse p = toEither . parseString (parseInput p) mempty
let value = some letter
let twoValues = do
v1 <- value
skipJunk
v2 <- value
return (v1, v2)
it "none" $
parse value "value" `shouldBe` Right "value"
it "before" $
parse value "# junk\n\n\n# junk2\n\nvalue" `shouldBe` Right "value"
it "after" $
parse value "value\n\n#junk\n\n#junk2\n\n" `shouldBe` Right "value"
it "around" $
parse value "# junk\n\n\n# junk2\n\nvalue\n\n#junk\n\n#junk2\n\n"
`shouldBe` Right "value"
it "between" $
parse twoValues "value\n\n#junk\n\n#junk2\n\nvalued"
`shouldBe` Right ("value", "valued")
describe "Parsing decimal" $ do
let parse = toEither . parseString parseDecimal mempty
it "just int" $
parse "5" `shouldBe` Right 5
it "just real" $
parse "3.43" `shouldBe` Right 3.43
it "with preceding spaces" $
parse " \t 4" `shouldBe` Right 4
describe "Parse function" $ do
let parse p s = toEither (parseString p mempty s)
it "constant" $
parse parseFunction "345" `shouldBe` Right (Function "345" (const $ Right 345))
it "x" $
parse parseFunction "x" `shouldBe` Right (Function "x0" $ Right . (Vec.! 0))
it "x1" $
parse parseFunction "x1" `shouldBe` Right (Function "x1" $ Right . (Vec.! 1))
it "x3" $
parse parseFunction "x3" `shouldBe` Right (Function "x3" $ Right . (Vec.! 3))
it "sin" $
parse parseFunction "sin" `shouldBe` Right fSin
it "log" $
parse parseFunction "log" `shouldBe` Right fLog
it "exp" $
parse parseFunction "exp" `shouldBe` Right fExp
it "power" $
parse parseExpression "cos(x0)^x1" `shouldBe` Right (Function "cos(x0)^x1" (\v -> Right $ cos (v Vec.! 0) ** (v Vec.! 1)))
it "composition sin(x0)" $
parse parseExpression "sin(x0)" `shouldBe` Right fSin
it "composition sin(log(x0))" $
parse parseExpression "sin(log(x0))" `shouldBe` Right (compose fSin fLog)
it "of sum of funcs" $
parse parseExpression "sin(x0)+log(x0)" `shouldBe` Right (simpleFunc "sin(x0)+log(x0)" (\x -> Right $ sin x + log x))
it "of fraction of funcs" $
parse parseExpression "sin(x0)/exp(x0)" `shouldBe` Right (simpleFunc "sin(x0)/exp(x0)" (\x -> Right $ sin x / exp x))
it "with different vars" $
parse parseExpression "x0*x1*x2" `shouldBe` Right (Function "x0*x1*x2" (\v -> Right $ v Vec.! 0 * v Vec.! 1 * v Vec.! 2))
it "with multiple ( and )" $ do
let expr = "(x0-(x1*x2))+sin((x0*x1)-(x0-x1))"
parse parseExpression expr `shouldBe` Right (Function expr (\v -> let
x0 = v Vec.! 0
x1 = v Vec.! 1
x2 = v Vec.! 2
in Right $ (x0 - (x1*x2)) + sin ((x0*x1) - (x0 - x1)) ))
describe "Parsing list" $ do
let parse p s = toEither (parseString (parseList p) mempty s)
it "of ints" $
parse parseDecimal "1\n2\r3\n\r4\n" `shouldBe` Right [1, 2, 3, 4]
describe "Parsing vector" $ do
let parse p s = Vec.toList <$> toEither (parseString (parseVector p) mempty s)
it "of ints" $
parse parseDecimal "1 2 3" `shouldBe` Right [1, 2, 3]
it "of floats with tabs and trailing space" $
parse parseDecimal "4.9\t8.3\t9 10.5 \t" `shouldBe` Right [4.9, 8.3, 9, 10.5]
it "of funcs" $
parse parseExpression "1 2 sin(x0) exp(x0)+sin(log(x0))" `shouldBe` Right
[ Function "1" (const $ Right 1)
, Function "2" (const $ Right 2)
, fSin
, simpleFunc "exp(x0)+sin(log(x0))" (\x -> Right $ exp x + sin (log x))
]
describe "Parsing matrix" $ do
let parse p s = fmap Vec.toList <$> toEither (parseString (parseVectors p) mempty s)
let testMatrix = Right [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
it "of ints" $
parse parseDecimal "1 2 3\n4 5 6\n7 8 9" `shouldBe` testMatrix
it "with trailing eol" $
parse parseDecimal "1 2 3\n4 5 6\n7 8 9\n" `shouldBe` testMatrix
it "of funcs" $
parse parseExpression "1 4 sin(x0)\n5 6 exp(sin(x0))\n9 10 x0/9" `shouldBe` Right
[ [Function "1" (const $ Right 1), Function "4" (const $ Right 4), fSin]
, [Function "5" (const $ Right 5), Function "6" (const $ Right 6), simpleFunc "exp(sin(x0))" (Right . exp . sin)]
, [Function "9" (const $ Right 9), Function "10" (const $ Right 10), simpleFunc "x0/9" $ Right . (/9)]
]
it "of funcs2" $
parse parseExpression "1 2 4 sin(x0)+log(x1)\n0 3 5 x2*x1\n2 1 9 0" `shouldBe` Right
[ [Function "1" (const $ Right 1), Function "2" (const $ Right 2), Function "4" (const $ Right 4), Function "sin(x0)+log(x1)" (\v -> Right $ sin (v Vec.! 0) + log (v Vec.! 1))]
, [Function "0" (const $ Right 0), Function "3" (const $ Right 3), Function "5" (const $ Right 5), Function "x2*x1" (\v -> Right $ (v Vec.! 2) * (v Vec.! 1))]
, [Function "2" (const $ Right 2), Function "1" (const $ Right 1), Function "9" (const $ Right 9), Function "0" (const $ Right 0)]
]
|
hrsrashid/nummet
|
tests/ParserSpec.hs
|
Haskell
|
bsd-3-clause
| 5,553
|
module Main (main) where
import System.Environment
import CAN
main :: IO ()
main = do
args <- getArgs
case args of
"-h" : _ -> help
"--help" : _ -> help
["--std", id, payload] -> do
initCAN
bus <- openBus 0 Standard
sendMsg bus $ Msg (read id) (toPayload $ read payload)
closeBus bus
[id, payload] -> do
initCAN
bus <- openBus 0 Extended
sendMsg bus $ Msg (read id) (toPayload $ read payload)
closeBus bus
_ -> help
help :: IO ()
help = putStrLn $ unlines
[ ""
, "NAME"
, " cansend - puts a message on a CAN bus"
, ""
, "SYNOPSIS"
, " cansend [--std] id payload"
, ""
, "ARGUMENTS"
, " --std Set to standard CAN with 500K. Default is extended CAN with 250K."
, ""
]
|
tomahawkins/ecu
|
src/CANSend.hs
|
Haskell
|
bsd-3-clause
| 778
|
-- Copyright (c) 1998 Chris Okasaki.
-- See COPYRIGHT file for terms and conditions.
module AssocDefaults
where
import Prelude hiding (null,map,lookup,foldr,foldl,foldr1,foldl1,filter)
import Assoc
import qualified Sequence as S
-- import qualified ListSeq as L
fromSeqUsingInsertSeq ::
(AssocX m k,S.Sequence seq) => seq (k,a) -> m k a
fromSeqUsingInsertSeq kvs = insertSeq kvs empty
insertSeqUsingFoldr ::
(AssocX m k,S.Sequence seq) => seq (k,a) -> m k a -> m k a
insertSeqUsingFoldr kvs m = S.foldr (uncurry insert) m kvs
unionSeqUsingReduce :: (AssocX m k,S.Sequence seq) => seq (m k a) -> m k a
unionSeqUsingReduce ms = S.reducel union empty ms
deleteSeqUsingFoldr :: (AssocX m k,S.Sequence seq) => seq k -> m k a -> m k a
deleteSeqUsingFoldr ks m = S.foldr delete m ks
countUsingMember :: AssocX m k => m k a -> k -> Int
countUsingMember m k = if member m k then 1 else 0
lookupAllUsingLookupM :: (AssocX m k,S.Sequence seq) => m k a -> k -> seq a
lookupAllUsingLookupM m k = case lookupM m k of
Just x -> S.single x
Nothing -> S.empty
lookupWithDefaultUsingLookupM :: AssocX m k => a -> m k a -> k -> a
lookupWithDefaultUsingLookupM d m k = case lookupM m k of
Just x -> x
Nothing -> d
partitionUsingFilter :: AssocX m k => (a -> Bool) -> m k a -> (m k a,m k a)
partitionUsingFilter f m = (filter f m, filter (not . f) m)
elementsUsingFold :: (AssocX m k,S.Sequence seq) => m k a -> seq a
elementsUsingFold = fold S.cons S.empty
insertWithUsingLookupM ::
FiniteMapX m k => (a -> a -> a) -> k -> a -> m k a -> m k a
insertWithUsingLookupM f k x m =
case lookupM m k of
Nothing -> insert k x m
Just y -> insert k (f x y) m
fromSeqWithUsingInsertSeqWith ::
(FiniteMapX m k,S.Sequence seq) => (a -> a -> a) -> seq (k,a) -> m k a
fromSeqWithUsingInsertSeqWith f kvs = insertSeqWith f kvs empty
fromSeqWithKeyUsingInsertSeqWithKey ::
(FiniteMapX m k,S.Sequence seq) => (k -> a -> a -> a) -> seq (k,a) -> m k a
fromSeqWithKeyUsingInsertSeqWithKey f kvs = insertSeqWithKey f kvs empty
insertWithKeyUsingInsertWith ::
FiniteMapX m k => (k -> a -> a -> a) -> k -> a -> m k a -> m k a
insertWithKeyUsingInsertWith f k = insertWith (f k) k
insertSeqWithUsingInsertWith ::
(FiniteMapX m k,S.Sequence seq) =>
(a -> a -> a) -> seq (k,a) -> m k a -> m k a
insertSeqWithUsingInsertWith f kvs m =
S.foldr (uncurry (insertWith f)) m kvs
insertSeqWithKeyUsingInsertWithKey ::
(FiniteMapX m k,S.Sequence seq) =>
(k -> a -> a -> a) -> seq (k,a) -> m k a -> m k a
insertSeqWithKeyUsingInsertWithKey f kvs m =
S.foldr (uncurry (insertWithKey f)) m kvs
unionSeqWithUsingReduce ::
(FiniteMapX m k,S.Sequence seq) => (a -> a -> a) -> seq (m k a) -> m k a
unionSeqWithUsingReduce f ms = S.reducel (unionWith f) empty ms
unionSeqWithUsingFoldr ::
(FiniteMapX m k,S.Sequence seq) => (a -> a -> a) -> seq (m k a) -> m k a
unionSeqWithUsingFoldr f ms = S.foldr (unionWith f) empty ms
toSeqUsingFoldWithKey :: (Assoc m k,S.Sequence seq) => m k a -> seq (k,a)
toSeqUsingFoldWithKey = foldWithKey conspair S.empty
where conspair k v kvs = S.cons (k,v) kvs
keysUsingFoldWithKey :: (Assoc m k,S.Sequence seq) => m k a -> seq k
keysUsingFoldWithKey = foldWithKey conskey S.empty
where conskey k v ks = S.cons k ks
unionWithUsingInsertWith ::
FiniteMap m k => (a -> a -> a) -> m k a -> m k a -> m k a
unionWithUsingInsertWith f m1 m2 = foldWithKey (insertWith f) m2 m1
unionWithKeyUsingInsertWithKey ::
FiniteMap m k => (k -> a -> a -> a) -> m k a -> m k a -> m k a
unionWithKeyUsingInsertWithKey f m1 m2 = foldWithKey (insertWithKey f) m2 m1
unionSeqWithKeyUsingReduce ::
(FiniteMap m k,S.Sequence seq) =>
(k -> a -> a -> a) -> seq (m k a) -> m k a
unionSeqWithKeyUsingReduce f ms = S.reducel (unionWithKey f) empty ms
unionSeqWithKeyUsingFoldr ::
(FiniteMap m k,S.Sequence seq) =>
(k -> a -> a -> a) -> seq (m k a) -> m k a
unionSeqWithKeyUsingFoldr f ms = S.foldr (unionWithKey f) empty ms
intersectWithUsingLookupM ::
FiniteMap m k => (a -> b -> c) -> m k a -> m k b -> m k c
intersectWithUsingLookupM f m1 m2 = foldWithKey ins empty m1
where ins k x m = case lookupM m2 k of
Nothing -> m
Just y -> insert k (f x y) m
intersectWithKeyUsingLookupM ::
FiniteMap m k => (k -> a -> b -> c) -> m k a -> m k b -> m k c
intersectWithKeyUsingLookupM f m1 m2 = foldWithKey ins empty m1
where ins k x m = case lookupM m2 k of
Nothing -> m
Just y -> insert k (f k x y) m
differenceUsingDelete :: FiniteMap m k => m k a -> m k b -> m k a
differenceUsingDelete m1 m2 = foldWithKey del m1 m2
where del k _ m = delete k m
subsetUsingSubsetEq :: FiniteMapX m k => m k a -> m k b -> Bool
subsetUsingSubsetEq m1 m2 = subsetEq m1 m2 && size m1 < size m2
subsetEqUsingMember :: FiniteMap m k => m k a -> m k b -> Bool
subsetEqUsingMember m1 m2 = foldWithKey mem True m1
where mem k _ b = member m2 k && b
|
OS2World/DEV-UTIL-HUGS
|
oldlib/AssocDefaults.hs
|
Haskell
|
bsd-3-clause
| 5,161
|
{-# LANGUAGE BangPatterns #-}
module Language.Hakaru.Tests.ImportanceSampler where
import Data.Dynamic
import Language.Hakaru.Distribution
import Test.QuickCheck.Monadic
testBeta = undefined
mu a b = a / (a + b)
var a b = a*b / ((sqr $ a + b) * (a + b + 1))
where sqr x = x * x
|
zaxtax/hakaru-old
|
Language/Hakaru/Tests/Distribution.hs
|
Haskell
|
bsd-3-clause
| 284
|
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ViewPatterns #-}
module Cgs (
main
) where
import Cgs.Args (runParseArgsIO, CgsOptions(..))
import Control.Exception (assert)
import Control.Monad ((<=<))
import Control.Monad.Identity (runIdentity)
import Control.Monad.ListM (takeWhileM)
import Control.Monad.State.Lazy (evalState, modify, gets)
import Data.List (isPrefixOf)
import Data.Tagged (untag)
import Hoops.Lex (runLexer)
import Hoops.Match
import Hoops.SyntaxToken
import Language.Cpp.Pretty (pretty)
import System.Directory (getCurrentDirectory, createDirectoryIfMissing)
import System.Exit (exitFailure)
import System.FilePath ((</>))
import System.IO (stderr, hPutStrLn)
import Text.Indent (indent, IndentMode(DropOldTabs), Tagged, CodeGen)
import Text.Parsec (ParseError)
import Transform.Expand (expand)
import Transform.Extract (extract, ExtractOptions)
import Transform.Flatten (flatten)
import Transform.Merge (merge)
import Transform.Nop (removeNopPairs, removeUnusedDefines)
main :: IO ()
main = do
mCgsOpts <- runParseArgsIO
case mCgsOpts of
Left err -> badArgs err
Right cgsOpts -> do
let getOpt f = runIdentity $ f cgsOpts
tokss <- mapM (lexCode <=< readFile) $ getOpt cgsFiles
let content = catMainContent tokss
content' <- runExtract (cgsExtractOpts cgsOpts) content
let cgsContent = cgs content'
cgsContents = chunkStmts (cgsChunkSize cgsOpts) cgsContent
tus = zipWith compileTranslationUnit [0 ..] cgsContents
mapM_ (putStrLn . reindent . pretty expandHoops) tus
badArgs :: ParseError -> IO ()
badArgs err = hPutStrLn stderr $ show err
compileTranslationUnit :: Int -> [SyntaxToken Hoops] -> [SyntaxToken Hoops]
compileTranslationUnit unitId tokens = prelude ++ tokens ++ prologue
where
code = either (const $ assert False undefined) id . runLexer
codeChain = "code_chain_" ++ show unitId
prelude = code $ unlines $ [
"#include \"cgs.h\"\n",
"int " ++ codeChain ++ " () {\n" ]
prologue = code $ unlines [
"return 0;",
"}\n" ]
data ChunkState = ChunkState {
consumedStmts :: Int,
braceBalance :: Int
}
chunkByM :: (Monad m) => (a -> m Bool) -> [a] -> m [[a]]
chunkByM _ [] = return []
chunkByM p (x:xs) = do
keep <- p x
xss <- chunkByM p xs
let xss' = case xss of
ys : yss -> (x:ys) : yss
[] -> [[x]]
return $ if keep
then xss'
else [] : xss'
chunkStmts :: Int -> [SyntaxToken Hoops] -> [[SyntaxToken Hoops]]
chunkStmts chunkSize = flip evalState baseSt . chunkByM chunker
where
baseSt = ChunkState {
consumedStmts = 0,
braceBalance = 0 }
chunker token = do
balance <- gets braceBalance
numConsumed <- gets consumedStmts
placeInCurrChunk <- if balance == 0 && numConsumed >= chunkSize
then do
modify $ \st -> st { consumedStmts = 0 }
return False
else return True
case token of
Punctuation (unpunc -> ";") -> do
modify $ \st -> st { consumedStmts = consumedStmts st + 1 }
Punctuation (unpunc -> "{") -> do
modify $ \st -> st { braceBalance = braceBalance st + 1 }
Punctuation (unpunc -> "}") -> do
modify $ \st -> st { braceBalance = braceBalance st - 1 }
_ -> return ()
return placeInCurrChunk
reindent :: String -> String
reindent = untag . (indent DropOldTabs :: String -> Tagged CodeGen String)
runExtract :: ExtractOptions -> [SyntaxToken Hoops] -> IO [SyntaxToken Hoops]
runExtract opts toks = do
cwd <- getCurrentDirectory
let extractDir = cwd </> "extract"
createDirectoryIfMissing True extractDir
extract opts extractDir toks
cgs :: [SyntaxToken Hoops] -> [SyntaxToken Hoops]
cgs = id
. iterateMaybe (fmap merge . removeNopPairs)
. merge
. flatten
. removeUnusedDefines
. iterateMaybe removeNopPairs
. expand
iterateMaybe :: (a -> Maybe a) -> a -> a
iterateMaybe f x = case f x of
Nothing -> x
Just y -> iterateMaybe f y
lexCode :: Code -> IO [SyntaxToken Hoops]
lexCode code = case runLexer code of
Left err -> print err >> exitFailure
Right ts -> return ts
catMainContent :: [[SyntaxToken Hoops]] -> [SyntaxToken Hoops]
catMainContent = concatMap extractMainContent
extractMainContent :: [SyntaxToken Hoops] -> [SyntaxToken Hoops]
extractMainContent = let
mainFunc = match "int main ($!args) {"
codeChainSig = match "int $var ($!args) {"
codeChainVar = isPrefixOf "code_chain_"
codeChainFunc tokens = case tokens of
(codeChainSig -> CapturesRest [Identifier (codeChainVar -> True)] rest) -> Rest rest
_ -> NoRest
dropBoringDecls = match $ concat [
"char string_buffer[256];",
"float ff;",
"int ii;",
"long ll;",
"HC_KEY key;",
"float matrix[16];" ]
go tokens = case extractBody tokens of
(dropBoringDecls -> Rest rest) -> rest
ts -> ts
in \tokens -> case tokens of
(mainFunc -> Rest rest) -> go rest
(codeChainFunc -> Rest rest) -> go rest
_ : rest -> extractMainContent rest
[] -> []
extractBody :: [SyntaxToken Hoops] -> [SyntaxToken Hoops]
extractBody = flip evalState (0 :: Int) . takeWhileM f
where
f token = case token of
Punctuation (unpunc -> sym) -> case sym of
"{" -> modify (+ 1) >> return True
"}" -> modify (subtract 1) >> gets (>= 0)
_ -> return True
Keyword (unkw -> name) -> return $ case name of
"return" -> False
_ -> True
Identifier name -> return $ not $ "code_chain_" `isPrefixOf` name
_ -> return True
|
thomaseding/cgs
|
src/Cgs.hs
|
Haskell
|
bsd-3-clause
| 6,013
|
{-# LANGUAGE FlexibleInstances #-}
module Language.Haskell.GhcMod.Types where
-- | Output style.
data OutputStyle = LispStyle -- ^ S expression style.
| PlainStyle -- ^ Plain textstyle.
-- | The type for line separator. Historically, a Null string is used.
newtype LineSeparator = LineSeparator String
data Options = Options {
outputStyle :: OutputStyle
, hlintOpts :: [String]
, ghcOpts :: [String]
-- | If 'True', 'browse' also returns operators.
, operators :: Bool
-- | If 'True', 'browse' also returns types.
, detailed :: Bool
-- | If 'True', 'browse' will return fully qualified name
, qualified :: Bool
-- | Whether or not Template Haskell should be expanded.
, expandSplice :: Bool
-- | Line separator string.
, lineSeparator :: LineSeparator
-- | Package id of module
, packageId :: Maybe String
}
-- | A default 'Options'.
defaultOptions :: Options
defaultOptions = Options {
outputStyle = PlainStyle
, hlintOpts = []
, ghcOpts = []
, operators = False
, detailed = False
, qualified = False
, expandSplice = False
, lineSeparator = LineSeparator "\0"
, packageId = Nothing
}
----------------------------------------------------------------
convert :: ToString a => Options -> a -> String
convert Options{ outputStyle = LispStyle } = toLisp
convert Options{ outputStyle = PlainStyle } = toPlain
class ToString a where
toLisp :: a -> String
toPlain :: a -> String
instance ToString [String] where
toLisp = addNewLine . toSexp True
toPlain = unlines
instance ToString [((Int,Int,Int,Int),String)] where
toLisp = addNewLine . toSexp False . map toS
where
toS x = "(" ++ tupToString x ++ ")"
toPlain = unlines . map tupToString
toSexp :: Bool -> [String] -> String
toSexp False ss = "(" ++ unwords ss ++ ")"
toSexp True ss = "(" ++ unwords (map quote ss) ++ ")"
tupToString :: ((Int,Int,Int,Int),String) -> String
tupToString ((a,b,c,d),s) = show a ++ " "
++ show b ++ " "
++ show c ++ " "
++ show d ++ " "
++ quote s
quote :: String -> String
quote x = "\"" ++ x ++ "\""
addNewLine :: String -> String
addNewLine = (++ "\n")
----------------------------------------------------------------
-- | The environment where this library is used.
data Cradle = Cradle {
-- | The directory where this library is executed.
cradleCurrentDir :: FilePath
-- | The directory where a cabal file is found.
, cradleCabalDir :: Maybe FilePath
-- | The file name of the found cabal file.
, cradleCabalFile :: Maybe FilePath
-- | The package db options. ([\"-no-user-package-db\",\"-package-db\",\"\/foo\/bar\/i386-osx-ghc-7.6.3-packages.conf.d\"])
, cradlePackageDbOpts :: [GHCOption]
, cradlePackages :: [Package]
} deriving (Eq, Show)
----------------------------------------------------------------
-- | A single GHC command line option.
type GHCOption = String
-- | An include directory for modules.
type IncludeDir = FilePath
-- | A package name.
type PackageBaseName = String
-- | A package name and its ID.
type Package = (PackageBaseName, Maybe String)
-- | Haskell expression.
type Expression = String
-- | Module name.
type ModuleString = String
data CheckSpeed = Slow | Fast
-- | Option information for GHC
data CompilerOptions = CompilerOptions {
ghcOptions :: [GHCOption] -- ^ Command line options
, includeDirs :: [IncludeDir] -- ^ Include directories for modules
, depPackages :: [Package] -- ^ Dependent package names
} deriving (Eq, Show)
|
vikraman/ghc-mod
|
Language/Haskell/GhcMod/Types.hs
|
Haskell
|
bsd-3-clause
| 3,690
|
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree. An additional grant
-- of patent rights can be found in the PATENTS file in the same directory.
module Duckling.Distance.CS.Tests
( tests ) where
import Data.String
import Test.Tasty
import Duckling.Dimensions.Types
import Duckling.Distance.CS.Corpus
import Duckling.Testing.Asserts
tests :: TestTree
tests = testGroup "CS Tests"
[ makeCorpusTest [This Distance] corpus
]
|
rfranek/duckling
|
tests/Duckling/Distance/CS/Tests.hs
|
Haskell
|
bsd-3-clause
| 588
|
import ConllReader
import Control.Monad
import Data.List.Split (splitOn)
import Data.Maybe
import System.Console.ParseArgs
import System.Exit
import System.IO
import Text.Printf
arg =
[ Arg 0 Nothing Nothing (argDataRequired "corpus" ArgtypeString)
"corpus in CoNLL format" ]
main :: IO ()
main = do
args <- parseArgsIO ArgsComplete arg
case getArg args 0 of
Nothing -> do
usageError args "Missing input file."
exitFailure
Just f -> readCorpus f >>= putStr . showCorpus
|
jsnajder/conll-corpus
|
src/conll-filter.hs
|
Haskell
|
bsd-3-clause
| 508
|
-- | Changes to alex's grammar:
--
-- * All sets include their unicode equivalents by default
--
-- * @%language MultiParamTypeClasses@ to allow language extensions in code fragments
--
-- * The @%wrapper@ directive doesn\'t make sense any more and so is removed
--
-- * Since it is parsed by TH, some fixities in code fragments may not work
--
-- * TODO: %infixl 4 -, etc. to introduce fixities
--
-- * TODO: allow the end user to supply an %encoding directive to get
-- ascii, latin1, utf-8, ucs-2, or ucs-4 lexers
--
-- * TODO: add a directive to allow "." to match "\n"
--
-- * @\u{...}@ as an alias for @\x{...}@ (char escape)
--
-- * optional braces on @\x{...}@, @\o{...}@ and @\u{....}@
--
-- * Haskell escape codes be used @\STX@ (these do not conflict with @\X@, or @\P@)
--
-- * @\p{....}@ for unicode block, category and posix classes (set escape)
--
-- * @\P{....}@ for the negation of the same (set escape)
--
-- * @\s@, posix space shorthand (set escape)
--
-- * @\w@, posix word shorthand (set escape)
--
-- * @\d@, posix digit shorthand (set escape)
--
-- * @\X@, grapheme recognition to recognize (an entire character with its modifiers)
-- works like a unicode . except that it matches "\n" (regexp escape)
--
-- * @\&@ is added as a Haskell-like synonym for () (regexp escape)
module Text.Luthor.Parser
( P
, MacroState
, initialMacroState
, scanner
) where
import Data.Char
import Data.CharSet (CharSet)
import qualified Data.CharSet.Posix.Unicode as Posix
import Data.Map (Map)
import qualified Data.Map as Map
import Text.ParserCombinators.Parsec.Char
import Text.ParserCombinators.Parsec.Language
import qualified Text.ParserCombinators.Parsec.Token as T
import Control.Applicative
import Language.Haskell.Exts.Extension as Haskell
import Language.Haskell.Exts.Parser as Haskell
import Language.Haskell.Meta.Syntax.Translate as Meta
data Code = Code String TH.Exp
data MacroState = MacroState
{ setMacroDefs :: Map String CharSet
, regExpMacroDefs :: Map String RegExp
, haskellExtensions :: [Extension]
}
defaultMacroState = MacroState
{ setMacroDefs =
, regExpMacroDefs = Map/empty
, haskellExtensions = [ QuasiQuotes, TemplateHaskell ]
}
type P = CharParser MacroState
-- | lexical scanner
scanner :: P (Scanner Code String)
scanner = do
whitespace
many directive
many macroDef
name <- optional identifier
operator ":-"
rules <- many rule
return $ Scanner name rules
-- directives
directive :: P ()
directive = do
operator "%"
directiveBody
<?> "directive"
directiveBody :: P ()
directiveBody = languageDirectiveBody
<?> "directive body"
languageDirectiveBody :: P ()
languageDirectiveBody = do
try $ identifier "language"
ext <- languageExtension
modify $ \s -> s { haskellExtensions = ext : haskellExtensions s }
languageExtension :: P Haskell.Extension
languageExtension = do
st <- getParserState
ident <- identifier
case [ x | (x,"") <- reads ident ] of
(x:_) -> return x
[] -> do
setParserState st
fail $ "Unknown language extension: " ++ ident
<?> "language extension"
-- macro definitions
macroDef :: P ()
macroDef = setMacroDef <|> regExpMacroDef
<?> "macro definition"
setMacroDef :: P ()
setMacroDef = do
m <- setMacroId
operator '='
s <- set
modify (\st-> st { setMacroDefs = insert m s (setMacroDefs st) }
regExpMacroDef :: P ()
regExpMacroDef = do
m <- regExpMacro
operator '='
r <- regExp
modify (\st-> st { regExpMacroDefs = insert m r (regExpMacroDefs st) }
-- set parsing
set :: P CharSet
set = set0 `sepBy` lexeme (char "#")
<?> "set"
set0 :: P CharSet
set0 = complementedSet0
<|> bracketedSet -- '['
<|> setMacro -- $...
<|> dot -- .
<|> (char '\\' >> setEscapeCode) -- \p{...} \P{...}
<|> rangeSet -- a \u{1234}
xor :: Bool -> Bool -> Bool
xor True False = True
xor False True = True
xor _ _ = False
setEscape = do
char '\\'
setEscapeCode
-- uses look-ahead on '\\'
setEscapeCode :: P CharSet
setEscapeCode = do
code <- oneOf "pP"
st <- getParserState
clazz <- ident <|> braces $ noneOf "}"
<?> "character class"
let (careted, cs) = case clazz of
'^' : rest -> (True, rest)
rest -> (False, rest)
case lookupCategoryCharSet cs `mplus`
lookupBlockCharSet cs `mplus`
lookupPosixUnicodeCharSet cs of
Just c -> return $ if careted `xor` code == 'P'
then complement c
else c
Nothing -> do
setParserState st
fail $ "Unknown character class: " ++ clazz
<|> do char "d"; return Posix.digit
<|> do char "s"; return Posix.space
<|> do char "w"; return Posix.word
<|> do
ch <- charEscape
rangeSetK ch
<?> "set escape code"
dot :: P CharSet
dot = do
char '.'
return $ complement (CharSet.singleton '\n')
rangeSet :: P CharSet
rangeSet = do
lower <- character
rangeSet0 lower
rangeSetK :: Char -> P CharSet
rangeSetK lower = do
r <- optional $ do
lexeme (char '-')
character
case r of
Just upper -> return $ range lower upper
_ -> return $ singleton lower
setMacroId :: P String
setMacroId = do
char '$'
bracedIdent
<?> "character set macro"
setMacro :: P CharSet
setMacro = do
st <- getParserState
macro <- setMacroId
smacs <- gets setMacroDefs
case lookup macro smacs of
Just s -> return s
_ -> do
setParserState st
fail $ "Unknown set macro: " ++ macro
bracketedSet :: P CharSet
bracketedSet = do
brackets $ do
caret <- optional (lexeme (char '^'))
ss <- many set
let s = mconcat ss
case caret of
Just _ -> complement s
_ -> s
complementedSet0 :: P CharSet
complementedSet0 = do
lexeme (char '~') -- allow this to be part of a larger operator
complement <$> set0
nonspecialCharSet :: CharSet
nonspecialCharSet = CharSet.delete '%' (graphicCharSet \\ specialCharSet)
-- Rule parsing
startCodes = P [String]
startCodes = angles (startCode `sepBy` comma)
<?> "start codes"
startCode :: P String
startCode = identifier
<|> lexeme (char '0') >> return "0"
tokenDef :: P [Rule Code String]
tokenDef = do cs <- startCodes
rule cs
<|> do t <- token
rule []
tokens :: P [Token]
tokens = braces (many token)
<|> fmap return token
data LeftContext
= LeftNone
| LeftSet CharSet
data Token = Token LeftContext RegExp RightContext Action
token :: P Token
token = do
l <- optional pre
b <- regExp
r <- optional post
rh <- rhs
return (Token l b r rh)
alt :: P RegExp
alt = foldr1 (:%%) <$> many1 term
term :: P RegExp
term = do
re <- regExp0
reps <- optional rep
case reps of
Just f -> f re
Nothing -> re
regExp :: P RegExp
regExp = alt `sepBy1` lexeme (char '|')
rep :: P (RegExp -> RegExp)
rep = lexeme (char '*') >> return Star
<|> lexeme (char '+') >> return Plus
<|> lexeme (char '?') >> return Ques
<|> braces $ do
d <- decimal
opt <- optional (lexeme (char ',') >> optional decimal)
return $ repeat_rng d opt
where
repeat_rng :: Int -> Maybe (Maybe Int) -> RegExp -> RegExp
repeat_rng n (Nothing) re = foldr (:%%) Eps (replicate n re)
repeat_rng n (Just Nothing) re = foldr (:%%) (Star re) (replicate n re)
repeat_rng n (Just (Just m)) re = intl :%% rst
where
intl = repeat_rng n Nothing re
rst = foldr (\re re' -> Ques (re :%% re')) Eps (replicate (m-n) re)
regExp0 :: P RegExp
regExp0 = fromMaybe Eps <$> parens (optional regExp)
<|> foldr (\x y -> x :%% Ch (singleton y)) Eps <$> stringLiteral
<|> regExpMacro
<|> regExpEscape -- have to try this before set below consumes '\\'
<|> Ch <$> set
-- thought: this could be expressed as a built-in regexp @X instead
regExpEscape :: P RegExp
regExpEscape = do
char '\\'
regExpEscapeCode
regExpEscapeCode = regExpGraphemeEscapeCode
<|> regExpEmptyEscapeCode
<|> Ch <$> setEscapeCode
<?> "regexp escape code"
regExpGraphemeEscapeCode :: RegExp
regExpGraphemeEscapeCode = do
lexeme (char 'X')
return $ Ch (complement mark) :%% Star (Ch mark)
regExpEmptyEscapeCode = do
lexeme (char '&')
return Eps
customParseMode :: [Haskell.Extension] -> Haskell.ParseMode
customParseMode exts = Haskell.defaultParseMode
{ parseFileNae = ""
, extensions = exts
, ignoreLanguagePragmas = False
, fixities = baseFixities
}
data Code = Code String TH.Exp
-- TODO: more gracefully handle nested '{'s
-- TODO: fix haskell-src-exts to give tighter location reporting
code :: P Code
code = do
st <- getParserState
fragment <- braces $ many $ noneOf "}"
exts <- get haskellExtensions
result <- Haskell.parseExpWithMode (customParseMode exts) fragment
case result of
Haskell.ParseOk a -> return $ Code fragment (Meta.toExp a)
Haskell.ParseFailed _loc reason -> do
setParserState st
fail reason
rule :: [startCodes] -> P (Rule Code startCodes)
rule startCodes =
Rule `fmap` optional pre
`ap` regExp
`ap` (fromMaybe NoPost <$> optional post)
`ap` ruleMaybeCode
<?> "rule"
pre :: P CharSet
pre = try $ do
p <- optional set
lexeme (char '^')
case p of
Just x -> return x
Nothing -> return newLineSet
post :: P (Post Code RegExp)
post
= do lexeme (char '$')
return $ PostRegExp (Ch newLineSet)
<|> do lexeme (char '/')
postRegExp <|> postCode
ruleMaybeCode :: P (Maybe Code)
ruleMaybeCode = Just <$> code
<|> do lexeme (char ';')
return Nothing
-- | character lexeme
-- Unfortunately, we have to replicate much of this from Text.ParserCombinators.Parsec.Token because the parsers there do not export enough of the interim combinators used
character :: P Char
character = charEscape <|> charLetter
<?> "character"
charLetter :: P Char
charLetter = satisfy (\x -> x `member` (graphicCharSet \\ specialCharSet))
charEscape :: P Char
charEscape = char '\\' >> charEscapeCode
charEscapeCode :: P Char
charEscapeCode
= charEsc
<|> charNum
<|> charAscii
<|> charControl
<|> charQuote
<?> "character escape code"
charQuote :: P Char
charQuote = satisfy (`CharSet.member` (specialCharSet `union` Category.separator))
charControl :: P Char
charControl = do
char '^'
code <- upper
return $! toEnum (fromEnum code - fromEnum 'A')
charNum :: P Char
charNum = do
code <- decimal -- cannot be braced, or it will conflict with \{
<|> do char 'o'; maybeBraces $ number 8 octDigit
<|> do oneOf "xu"; maybeBraces $ number 16 hexDigit
return $! toEnum code
foldDigits :: Int -> String -> Int
foldDigits base digits =
foldl (\x d -> base * x + toInteger (digitToInt d)) 0
number :: Int -> P Char -> P Int
number base baseDigit = do
digits <- many1 baseDigit
return $! foldDigits base digits
charEsc :: P Char
charEsc = choice $ map parseEsc escMap
where
parseEsc (c,code) = do
char c
return code
charAscii :: CharParser st Char
charAscii = choice (map parseAscii asciiMap)
where
parseAscii (asc,code) = try $ do string asc; return code
escMap :: [(Char,Char)]
escMap = zip ("abfnrtv\\\"\'") ("\a\b\f\n\r\t\v\\\"\'")
asciiMap :: [(String,Char)]
asciiMap = zip (ascii3codes ++ ascii2codes) (ascii3 ++ ascii2)
ascii2codes = ["BS","HT","LF","VT","FF","CR","SO","SI","EM",
"FS","GS","RS","US","SP"]
ascii3codes = ["NUL","SOH","STX","ETX","EOT","ENQ","ACK","BEL",
"DLE","DC1","DC2","DC3","DC4","NAK","SYN","ETB",
"CAN","SUB","ESC","DEL"]
ascii2 = ['\BS','\HT','\LF','\VT','\FF','\CR','\SO','\SI',
'\EM','\FS','\GS','\RS','\US','\SP']
ascii3 = ['\NUL','\SOH','\STX','\ETX','\EOT','\ENQ','\ACK',
'\BEL','\DLE','\DC1','\DC2','\DC3','\DC4','\NAK',
'\SYN','\ETB','\CAN','\SUB','\ESC','\DEL']
-- * Utility 'Charset's
newlineCharSet :: CharSet
newlineCharSet = CharSet.singleton '\n'
specialCharSet :: CharSet
specialCharSet = CharSet.fromList ".;,$|*+?#~-{}()[]^/"
spaceCharSet :: CharSet
spaceCharSet = Posix.space
printableCharSet :: CharSet
printableCharSet = Posix.print
graphicCharSet :: CharSet
graphicCharSet = printableCharSet \\ spaceCharSet
-- * "Free" TokenParser parsers
language = makeTokenParser haskellStyle
identifier = T.identifier language
reserved = T.reserved language
stringLiteral = T.stringLiteral language
natural = T.natural language
integer = T.integer language
lexeme = T.lexeme language
whiteSpace = T.whiteSpace language
parens = T.parens language
braces = T.braces language
angles = T.angles language
-- * Useful combinators
bracedIdentifier :: P String
bracedIdentifier
= identifier
<|> braces identifier
<?> "braced identifier"
|
ekmett/luthor
|
Text/Luthor/Parser.hs
|
Haskell
|
bsd-3-clause
| 13,475
|
module SpatulaStart where
import Rumpus
start :: Start
start entityID = do
chan <- traverseM (use (wldComponents . myPdPatch . at entityID)) $ \patch -> do
pd <- view wlsPd
toDyn <$> makeReceiveChan pd (local patch "freq")
return chan
|
lukexi/rumpus
|
util/DevScenes/scenes-old/spatula/SpatulaStart.hs
|
Haskell
|
bsd-3-clause
| 260
|
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Data.Semigroup ((<>))
import qualified Data.Text as Text
import qualified Data.Text.IO as Text
import Options.Applicative
import System.Environment (getEnvironment)
import qualified Web.JWT as JWT
import qualified Data.Time.Clock.POSIX as Clock
import AccessControl
import JwtAuth
data Config = Config
{ configJwtSecret :: Maybe JWT.Signer
, configExpiresSeconds :: Maybe Integer
, configWhitelist :: [AuthPath]
}
type EnvironmentConfig = [(String, String)]
main :: IO ()
main = do
env <- getEnvironment
config <- execParser (configInfo env)
now <- Clock.getPOSIXTime
let joseHeader = JWT.JOSEHeader
{ JWT.typ = Just "JWT"
, JWT.cty = Nothing
, JWT.alg = Just JWT.HS256
, JWT.kid = Nothing
}
let access = IcepeakClaim (configWhitelist config)
claims = addIcepeakClaim access $ JWT.JWTClaimsSet
{ JWT.iss = Nothing
, JWT.sub = Nothing
, JWT.aud = Nothing
, JWT.exp = fmap (\secs -> realToFrac secs + now) (configExpiresSeconds config) >>= JWT.numericDate
, JWT.nbf = Nothing
, JWT.iat = Nothing
, JWT.jti = Nothing
, JWT.unregisteredClaims = mempty
}
token = case configJwtSecret config of
Nothing -> JWT.encodeUnsigned claims joseHeader
Just key -> JWT.encodeSigned key joseHeader claims
Text.putStrLn token
configParser :: EnvironmentConfig -> Parser Config
configParser environment = Config
<$> optional (
secretOption (long "jwt-secret"
<> metavar "JWT_SECRET"
<> environ "JWT_SECRET"
<> short 's'
<> help "Secret used for signing the JWT, defaults to the value of the JWT_SECRET environment variable if present. If no secret is passed, JWT tokens are not signed."))
<*> optional(
option auto (long "expires"
<> short 'e'
<> metavar "EXPIRES_SECONDS"
<> help "Generate a token that expires in EXPIRES_SECONDS seconds from now."))
<*> many (option authPathReader
(long "path"
<> short 'p'
<> metavar "PATH:MODES"
<> help "Adds the PATH to the whitelist, allowing the access modes MODES. MODES can be 'r' (read), 'w' (write) or 'rw' (read/write). This option may be used more than once."
))
where
environ var = foldMap value (lookup var environment)
secretOption m = JWT.hmacSecret . Text.pack <$> strOption m
configInfo :: EnvironmentConfig -> ParserInfo Config
configInfo environment = info parser description
where
parser = helper <*> configParser environment
description = fullDesc <>
header "Icepeak Token Generator - Generates and signs JSON Web Tokens for authentication and authorization in Icepeak."
authPathReader :: ReadM AuthPath
authPathReader = eitherReader (go . Text.pack) where
go input = let (pathtxt, modetxt) = Text.breakOn ":" input
modeEither | modetxt == ":r" = Right [ModeRead]
| modetxt == ":w" = Right [ModeWrite]
| modetxt == ":rw" = Right [ModeRead, ModeWrite]
| otherwise = Left $ "Invalid mode: " ++ Text.unpack modetxt
pathComponents = filter (not . Text.null) $ Text.splitOn "/" pathtxt
in AuthPath pathComponents <$> modeEither
|
channable/icepeak
|
server/app/IcepeakTokenGen/Main.hs
|
Haskell
|
bsd-3-clause
| 3,623
|
-- | Provides definitions of associated Legendre functions used in spherical harmonic models.
module Math.SphericalHarmonics.AssociatedLegendre
(
associatedLegendreFunction
, schmidtSemiNormalizedAssociatedLegendreFunction
)
where
import Data.Poly (VPoly, eval, deriv)
import Data.Poly.Orthogonal (legendre)
import Data.Euclidean (Field, WrappedFractional(..))
-- definition from http://www.mathworks.com/help/matlab/ref/legendre.html#f89-998354
-- | Computes the associated Legendre function of degree 'n' and order 'm'.
-- Note that the resulting function may not be a polynomial, as when `m` is odd it involves a fractional power of `x`.
-- As used in the geodesy and magnetics literature, these functions do not include the Condon-Shortley phase.
associatedLegendreFunction :: (Floating a, Ord a) => Int -- ^ Degree 'n' of the desired associated Legendre function.
-> Int -- ^ Order 'm' of the desired associated Legendre function.
-> a -> a
associatedLegendreFunction n m = f
where
f x = nonPolyTerm x * unwrapFractional (eval p' (WrapFractional x))
nonPolyTerm x = (1 - x * x) ** (fromIntegral m / 2)
p' = iterate deriv p !! m
p :: (Eq t, Field t) => VPoly t
p = legendre !! n
-- definition from http://www.mathworks.com/help/matlab/ref/legendre.html#f89-998354
-- | Computes the Schmidt semi-normalized associated Legendre function of degree 'n' and order 'm'.
-- As used in the geodesy and magnetics literature, these functions do not include the Condon-Shortley phase.
schmidtSemiNormalizedAssociatedLegendreFunction :: (Floating a, Ord a) => Int -- ^ Degree 'n' of the desired function.
-> Int -- ^ Order 'm' of the desired function.
-> a -> a
schmidtSemiNormalizedAssociatedLegendreFunction n 0 = associatedLegendreFunction n 0
schmidtSemiNormalizedAssociatedLegendreFunction n m = (* factor) . associatedLegendreFunction n m
where
factor = (sqrt $ 2 / rawFactor)
rawFactor = fromIntegral $ rawFactor' (fromIntegral n) (fromIntegral m)
rawFactor' :: Integer -> Integer -> Integer
rawFactor' n m = product . map (max 1) $ enumFromTo (n - m + 1) (n + m)
|
dmcclean/igrf
|
src/Math/SphericalHarmonics/AssociatedLegendre.hs
|
Haskell
|
bsd-3-clause
| 2,251
|
module Main where
import Data.Sequence as S
import Data.List
import Data.Foldable
import System.IO
import Prelude as P
import qualified Data.Text as T
import Control.Lens
import Types
import MeshGenerator
import Linear
import FractalSurface
import MarchingCubes
sphere :: V3 Double -> Double
sphere v = norm v - 1.0
boxAxis :: Double -> V3 Double -> Double
boxAxis lim v | maxAxis v > lim && minAxis v < (-lim) = max (maxAxis v - lim) (-(minAxis v + lim))
boxAxis lim v | minAxis v < (-lim) = (-(minAxis v + lim))
boxAxis lim v | maxAxis v > lim = maxAxis v - lim
boxAxis lim v | otherwise = max (maxAxis v - lim) (-(minAxis v + lim))
minAxis :: V3 Double -> Double
minAxis v = min (min (v ^._x) (v ^._y)) (v ^._z)
maxAxis :: V3 Double -> Double
maxAxis v = max (max (v ^._x) (v ^._y)) (v ^._z)
mandelBulb8 :: V3 Double -> Double
--mandelBulb8 = mandelBulb 7 3.0 (V3 (-0.20) (-0.80) (-0.4))
mandelBulb8 = mandelBulb 7 9.0 (V3 (-0.9) (0.1) (-0.2)) --many saturn discs
--mandelBulb8 = mandelBulb 15 2.0 (V3 0.7 (-0.7) 0.45) --chalice
main :: IO ()
main = do
--meshToObj testSquare "testSquare.obj"
--print testSquare
--print $ squareGrid 3
--print $ radialGrid 4
let maxTriNum = 65534
{-
let meshListRadial = splitMeshAt maxTriNum (radialGrid 250) :: [Mesh Double]
print $ P.length meshListRadial
print $ "Radial number of vertices: " ++ show (P.map meshVertLength meshListRadial)
print $ "Radial number of triangles: " ++ show (P.map meshTrisLength meshListRadial)
P.mapM_ (\(index, mesh) -> meshToObj mesh ("radialGrid250_" ++ show index ++ ".obj")) (P.zip [0, 1..] meshListRadial)
let meshListSquare = splitMeshAt maxTriNum (squareGrid 500) :: [Mesh Double]
print $ P.length meshListSquare
print $ "Square number of vertices: " ++ show (P.map meshVertLength meshListSquare)
print $ "Square number of triangles: " ++ show (P.map meshTrisLength meshListSquare)
P.mapM_ (\(index, mesh) -> meshToObj mesh ("squareGrid500_" ++ show index ++ ".obj")) (P.zip [0, 1..] meshListSquare)
-}
let minNum = -2.0
let maxNum = 2.0
let minCorner = V3 minNum minNum minNum :: V3 Double
let maxCorner = V3 maxNum maxNum maxNum :: V3 Double
--let sphereIndepMesh = marchingCubesGrid sphere 0.0 200 minCorner maxCorner
--let sphereIndepMesh = marchingCubesGrid sphere 0.0 50 minCorner maxCorner
--let sphereMesh = independentTriangleMeshToMeshUnCompressed sphereIndepMesh
--let meshListSphere = splitMeshAt maxTriNum sphereMesh :: [Mesh Double]
--P.mapM_ (\(index, mesh) -> meshToObj mesh ("sphereMesh_" ++ show index ++ ".obj")) (P.zip [0, 1..] meshListSphere)
--meshToObj sphereMesh "sphereMesh.obj"
--let boxIndepMesh = marchingCubesGrid (boxAxis 0.8) 0.0 50 minCorner maxCorner
--let boxMesh = independentTriangleMeshToMeshUnCompressed boxIndepMesh
--meshToObj boxMesh "boxMesh.obj"
let mandelIndepMesh = marchingCubesGrid mandelBulb8 0.0 200 minCorner maxCorner
let mandelMesh = independentTriangleMeshToMeshUnCompressed mandelIndepMesh
meshToObj mandelMesh "mandel8Mesh.obj"
|
zobot/MeshGenerator
|
src/Main.hs
|
Haskell
|
bsd-3-clause
| 3,113
|
-----------------------------------------------------------------------------
-- |
-- Module : TestSuite.Puzzles.Euler185
-- Copyright : (c) Levent Erkok
-- License : BSD3
-- Maintainer : erkokl@gmail.com
-- Stability : experimental
--
-- Test suite for Data.SBV.Examples.Puzzles.Euler185
-----------------------------------------------------------------------------
module TestSuite.Puzzles.Euler185(tests) where
import Data.SBV.Examples.Puzzles.Euler185
import Utils.SBVTestFramework
-- Test suite
tests :: TestTree
tests =
testGroup "Puzzles.Euler185"
[ goldenVsStringShow "euler185" (allSat euler185)
]
|
josefs/sbv
|
SBVTestSuite/TestSuite/Puzzles/Euler185.hs
|
Haskell
|
bsd-3-clause
| 640
|
module FizzBuzzKata.Day2 (fizzbuzz) where
fizzbuzz :: [Int] -> [String]
fizzbuzz [] = []
fizzbuzz (n:ns)
| isFizz n
&& isBuzz n = "fizz!buzz!" : fizzbuzz ns
| isFizz n = "fizz!" : fizzbuzz ns
| isBuzz n = "buzz!" : fizzbuzz ns
| otherwise = show n : fizzbuzz ns
where
isFizz :: Int -> Bool
isFizz num = num `isDivisible` 3 || elem '3' (show num)
isBuzz :: Int -> Bool
isBuzz num = num `isDivisible` 5 || elem '5' (show num)
isDivisible :: Int -> Int -> Bool
isDivisible num m = num `mod` m == 0
|
Alex-Diez/haskell-tdd-kata
|
old-katas/src/FizzBuzzKata/Day2.hs
|
Haskell
|
bsd-3-clause
| 648
|
module Wholemeal
where
fun1 :: [Integer] -> Integer
fun1 = product . map (\x -> x - 2) . filter even
fun2 :: Integer -> Integer
fun2 1 = 0
fun2 n
| even n = n + fun2 (n `div` 2)
| otherwise = fun2 (3 * n + 1)
fun3 :: Integer -> Integer
fun3 = sum . filter even . takeWhile (>1) . iterate (\x -> if even x then x `div` 2 else 3 * x + 1)
data Tree a = Leaf
| Node Integer (Tree a) a (Tree a)
--foldTree :: [a] -> Tree a
|
richard12511/bobs-orders
|
app/Wholemeal.hs
|
Haskell
|
bsd-3-clause
| 466
|
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Finance.Exchange.OrderBook
( OrderBook
-- , BookedOrder (..)
, MatchedOrder (..)
, emptyBook
, bookOrder
, drain
) where
import Data.Heap as H
import Finance.Exchange.Types
class MarketPrice offerPrice where
-- | Adjust order price based on available offer. Returns Nothing if offer price can not be matched.
matchPrice :: offerPrice -> OrderPrice (Market offerPrice) -> Maybe (OrderPrice (Market offerPrice))
-- | Price asked by seller
newtype AskPrice market = AskPrice (OrderPrice market)
type instance Market (AskPrice market) = market
deriving instance Show (OrderPrice market) => Show (AskPrice market)
deriving instance (Eq (OrderPrice market)) => Eq (AskPrice market)
-- | Ask price is ordered from lower to higher value with market price on the bottom (indicating that market will always match first)
instance (Ord (Money market)) => Ord (AskPrice market) where
(AskPrice Market) `compare` (AskPrice Market) = EQ
(AskPrice Market) `compare` _ = LT
_ `compare` (AskPrice Market) = GT
(AskPrice (Limit a)) `compare` (AskPrice (Limit b)) = a `compare` b
-- | Matching ask price against order will return ask price if it lower or Nothing if ask price is higher than limit.
instance (Ord (Money market)) => MarketPrice (AskPrice market) where
(AskPrice Market) `matchPrice` Market = Just Market
(AskPrice ask) `matchPrice` Market = Just ask
(AskPrice Market) `matchPrice` lim = Just lim
(AskPrice (Limit ask)) `matchPrice` (Limit lim) = if ask <= lim then Just (Limit ask) else Nothing
-- | Price offered by buyer
newtype BidPrice market = BidPrice (OrderPrice market)
type instance Market (BidPrice market) = market
deriving instance Show (OrderPrice market) => Show (BidPrice market)
deriving instance (Eq (OrderPrice market)) => Eq (BidPrice market)
-- | Big is ordered from lower to higher value with market price on the top (indicating that market will always match first)
instance (Ord (Money market)) => Ord (BidPrice market) where
(BidPrice Market) `compare` (BidPrice Market) = EQ
(BidPrice Market) `compare` _ = GT
_ `compare` (BidPrice Market) = LT
(BidPrice (Limit a)) `compare` (BidPrice (Limit b)) = a `compare` b
-- | Matching bid price against order will return bid price if it higher or Nothing if bid price is lower than limit.
instance (Ord (Money market)) => MarketPrice (BidPrice market) where
-- | Calculate execution price if favor to seller
(BidPrice Market) `matchPrice` Market = Just Market
(BidPrice bid) `matchPrice` Market = Just bid
(BidPrice Market) `matchPrice` lim = Just lim
(BidPrice (Limit bid)) `matchPrice` (Limit lim) = if bid >= lim then Just (Limit bid) else Nothing
-- | Booked order parametrized by price (can be either buing or selling order depending on price type)
data BookedOrder price = BookedOrder
{ _bookedId :: OrderId (Market price)
, _bookedAmount :: Amount (Market price)
, _bookedPrice :: price
}
deriving instance (Eq (OrderId (Market price)), Eq (Amount (Market price)), Eq price) => Eq (BookedOrder price)
deriving instance (Show (OrderId (Market price)), Show (Amount (Market price)), Show price) => Show (BookedOrder price)
instance (Eq (BookedOrder (AskPrice market)), Ord (OrderId market), Ord (Money market)) => Ord (BookedOrder (AskPrice market)) where
a `compare` b = case _bookedPrice a `compare` _bookedPrice b of
EQ -> (_bookedId a) `compare` (_bookedId b)
other -> other
instance (Eq (BookedOrder (BidPrice market)), Ord (OrderId market), Ord (Money market)) => Ord (BookedOrder (BidPrice market)) where
-- price comparison reversed to place order with highest bid price on a top of priority queue
a `compare` b = case _bookedPrice b `compare` _bookedPrice a of
EQ -> (_bookedId a) `compare` (_bookedId b)
other -> other
data MatchedOrder market = MatchedOrder
{ _matchedId1 :: OrderId market
, _matchedId2 :: OrderId market
, _matchedAmount :: Amount market
, _matchedPrice :: OrderPrice market
}
deriving instance (Show (OrderId market), Show (Amount market), Show (OrderPrice market)) => Show (MatchedOrder market)
data OrderBook market = OrderBook
{ _asking :: Heap (BookedOrder (AskPrice market)) -- TODO: rename to _bying/_selling
, _bidding :: Heap (BookedOrder (BidPrice market))
}
emptyBook :: OrderBook market
emptyBook = OrderBook { _asking = H.empty
, _bidding = H.empty
}
deriving instance (Show (OrderId market), Show (Money market), Show (Amount market), Show (InstrumentId market)) => Show (OrderBook market)
-- | Provide generic interface for booking bid and ask ordres
-- TODO: needs better name
-- основное назначение:
-- 1. разобрать deal book на orders offers
-- 2. конвертировать OrderPrice в OrderPriceOf book (чтобы добавлять его в нужную кучу)
-- 3. собрать deal book из orders offers (вот это пока не очень получается)
class ( -- FuckingProlog (OrderPriceOf book) (OfferPriceOf book) ~ book
-- , DealBookOf (OrderPriceOf book) ~ book
-- , Market (OrderPriceOf book) ~ Market book
-- , Market (OfferPriceOf book) ~ Market book
Market orderPrice ~ Market book
, Market offerPrice ~ Market book
--, DealBookOf (orderPrice) ~ book
) => DealBook book orderPrice offerPrice | book -> orderPrice, book -> offerPrice, orderPrice -> book, offerPrice -> book where
-- | Order price (Bid for buyind Ask for selling)
-- type OrderPriceOf book :: *
-- | Offer price (Ask for buyind Bid for selling)
-- type OfferPriceOf book :: *
-- | Construct order book from offers and orders halves (depending on order type can be either buy/sell or sell/buy)
-- эта штука не тайпчекается на ghc 7.10 потому что параметры не определяют тип буки
-- хотя он нам и не нужен, нам market нужен
-- короче на фундепах работает, но надо будет потом переделать этот ёбаный ужас
orderBook :: Heap (BookedOrder orderPrice) -> Heap (BookedOrder offerPrice) -> OrderBook (Market book)
-- | Get offers from book (sell offers when buying or buy offers when selling)
offers :: book -> Heap (BookedOrder offerPrice)
-- | Get orders from book (buy orderd when buying of sell orders when selling)
orders :: book -> Heap (BookedOrder orderPrice)
-- | Wrap order price to Bid or Ask price depending on deal
dealPrice :: OrderPrice (Market book) -> orderPrice
type family DealBookOf orderPrice :: *
type family FuckingProlog orderPrice offerPrice :: *
newtype Buying market = Buying { unBuying :: OrderBook market }
type instance Market (Buying market) = market
instance DealBook (Buying market) (BidPrice market) (AskPrice market) where
-- type OrderPriceOf (Buying market) = BidPrice market
-- type OfferPriceOf (Buying market) = AskPrice market
orderBook bidding asking = OrderBook { _asking = asking, _bidding = bidding }
offers = _asking . unBuying
orders = _bidding . unBuying
dealPrice = BidPrice
type instance DealBookOf (BidPrice market) = Buying market
type instance FuckingProlog (BidPrice market) (AskPrice market) = Buying market
newtype Selling market = Selling { unSelling :: OrderBook market }
type instance Market (Selling market) = market
instance DealBook (Selling market) (AskPrice market) (BidPrice market) where
-- type OrderPriceOf (Selling market) = AskPrice market
-- type OfferPriceOf (Selling market) = BidPrice market
orderBook asking bidding = OrderBook { _asking = asking, _bidding = bidding }
offers = _bidding . unSelling
orders = _asking . unSelling
dealPrice = AskPrice
type instance DealBookOf (AskPrice market) = Selling market
type instance FuckingProlog (AskPrice market) (BidPrice market) = Selling market
bookOrder :: (Num (Amount market), Ord (Amount market), Ord (Money market), Ord (OrderId market))
=> OrderId market -- replace with order tag (market agnostic depends on upstream engine)
-> BuyOrSell
-> OrderPrice market
-> Amount market
-> OrderBook market
-> ([MatchedOrder market], OrderBook market)
bookOrder orderId buyOrSell price amount = case buyOrSell of
Buy -> bookOrder' orderId price amount . Buying
Sell -> bookOrder' orderId price amount . Selling
bookOrder' :: forall book orderPrice offerPrice . ( DealBook book orderPrice offerPrice
, Num (Amount (Market book))
, Ord (Amount (Market book))
--, Ord (BookedOrder (OrderPriceOf book))
--, Ord (BookedOrder (OfferPriceOf book))
--, MarketPrice (OfferPriceOf book)
, Ord (BookedOrder (orderPrice))
, Ord (BookedOrder (offerPrice))
, MarketPrice (offerPrice)
)
=> OrderId (Market book)
-> OrderPrice (Market book)
-> Amount (Market book)
-> book
-> ([MatchedOrder (Market book)], OrderBook (Market book))
bookOrder' orderId price amount book = go [] amount (offers book)
where
--go :: [MatchedOrder (Market (OfferPriceOf book))]
-- -> Amount (Market (OfferPriceOf book))
-- -> Heap (BookedOrder (OfferPriceOf book))
-- -> ([MatchedOrder (Market (OfferPriceOf book))], OrderBook (Market book))
go matchedOrders 0 xs = (matchedOrders, orderBook (orders book) xs)
go matchedOrders remain xs = case tryGetPrice price xs of
Just (execPrice, offer, otherOffers) ->
let matchedOrder matchedamount = MatchedOrder { _matchedId1 = orderId
, _matchedId2 = _bookedId offer
, _matchedAmount = matchedamount
, _matchedPrice = execPrice
}
orderAmount = _bookedAmount offer
in case remain - orderAmount of
shortage | shortage > 0 -> go (matchedOrder orderAmount : matchedOrders) shortage otherOffers
| otherwise -> ( matchedOrder remain : matchedOrders
, orderBook (orders book) (H.insert offer { _bookedAmount = -shortage } otherOffers) )
Nothing ->
let newOrder = BookedOrder { _bookedId = orderId
, _bookedAmount = remain
, _bookedPrice = dealPrice price
}
in (matchedOrders, orderBook (H.insert newOrder $ orders book) xs)
tryGetPrice :: ( Ord (BookedOrder offerPrice)
, MarketPrice offerPrice )
=> OrderPrice (Market offerPrice)
-> Heap (BookedOrder offerPrice)
-> Maybe (OrderPrice (Market offerPrice), BookedOrder offerPrice, Heap (BookedOrder offerPrice))
tryGetPrice lim xs = do
(offer, heap) <- H.uncons xs
execPrice <- matchPrice (_bookedPrice offer) lim
return (execPrice, offer, heap)
drain :: (Num (Amount market), Ord (Amount market), Ord (Money market), Ord (OrderId market))
=> OrderId market -- replace with order tag (market agnostic depends on upstream engine)
-> BuyOrSell
-> OrderPrice market
-> OrderBook market
-> ([MatchedOrder market], OrderBook market)
drain orderId buyOrSell price = case buyOrSell of
Buy -> drain' orderId price . Buying
Sell -> drain' orderId price . Selling
drain' :: ( DealBook book orderPrice offerPrice
--, Ord (BookedOrder (OrderPriceOf book))
--, Ord (BookedOrder (OfferPriceOf book))
--, MarketPrice (OfferPriceOf book )
, Ord (BookedOrder (orderPrice))
, Ord (BookedOrder (offerPrice))
, MarketPrice (offerPrice )
)
=> OrderId (Market book)
-> OrderPrice (Market book)
-> book
-> ([MatchedOrder (Market book)], OrderBook (Market book))
drain' orderId price book = go [] (offers book)
where
go matchedOrders xs = case tryGetPrice price xs of
Just (execPrice, offer, otherOffers) ->
let matchedOrder = MatchedOrder { _matchedId1 = orderId
, _matchedId2 = _bookedId offer
, _matchedAmount = _bookedAmount offer
, _matchedPrice = execPrice
}
in go (matchedOrder : matchedOrders) otherOffers
Nothing -> (matchedOrders, orderBook (orders book) xs)
|
schernichkin/exchange
|
src/Finance/Exchange/OrderBook.hs
|
Haskell
|
bsd-3-clause
| 13,633
|
{-# LANGUAGE TemplateHaskell #-}
module RRTTest (tests) where
import Test.Framework
import Test.Framework.Providers.QuickCheck2 (testProperty)
import Test.Framework.TH (testGroupGenerator)
import Test.QuickCheck.Property ((==>))
import Data.MetricSpace
import Data.RRT
tests :: Test
tests = $(testGroupGenerator)
prop_num_streams_eq_num_nodes stream = length tree == length stream
where config = Config (controlEdgeProp (+)) [0] distance
tree = maybeSearch config stream
types = (stream :: [(Integer, [Integer])])
prop_failed_means_empty_tree stream = null tree
where config = Config (const $ const Nothing) [0] distance
tree = search config stream
types = (stream :: [(Integer, [Integer])])
|
jdmarble/rrt
|
test/RRTTest.hs
|
Haskell
|
bsd-3-clause
| 749
|
{-# LANGUAGE OverloadedStrings #-}
module TW.CodeGen.Flow
( makeFileName, makeModule
)
where
import TW.Ast
import TW.BuiltIn
import TW.JsonRepr
import Data.Monoid
import System.FilePath
import qualified Data.List as L
import qualified Data.Text as T
makeFileName :: ModuleName -> FilePath
makeFileName (ModuleName parts) =
(L.foldl' (</>) "" $ map T.unpack parts) ++ ".js"
makeModule :: Module -> T.Text
makeModule m =
T.unlines
[ "/* @flow */"
, "// This file was auto generated by typed-wire. Do not modify by hand"
, "// Module Name: " <> printModuleName (m_name m) <> ""
, ""
, T.intercalate "\n" (map makeImport $ m_imports m)
, ""
, T.intercalate "\n" (map makeTypeDef $ m_typeDefs m)
, ""
]
makeImport :: ModuleName -> T.Text
makeImport m =
"import " <> printModuleName m <> ";"
makeTypeDef :: TypeDef -> T.Text
makeTypeDef td =
case td of
TypeDefEnum ed ->
makeEnumDef ed
TypeDefStruct sd ->
makeStructDef sd
makeStructDef :: StructDef -> T.Text
makeStructDef sd =
T.unlines
[ "export type " <> makeTypeName (sd_name sd) (sd_args sd) <> " ="
, " {| " <> T.intercalate "\n , " (map makeStructField $ sd_fields sd)
, " |}"
, ""
]
makeStructField :: StructField -> T.Text
makeStructField sf =
(unFieldName $ sf_name sf) <> " : " <> (makeType $ sf_type sf)
makeEnumDef :: EnumDef -> T.Text
makeEnumDef ed =
T.unlines
[ "export type " <> makeTypeName (ed_name ed) (ed_args ed)
, " = " <> T.intercalate "\n | " (map makeEnumChoice $ ed_choices ed)
, ""
]
makeEnumChoice :: EnumChoice -> T.Text
makeEnumChoice ec =
let constr = unChoiceName $ ec_name ec
tag = camelTo2 '_' $ T.unpack constr
fieldVal =
case ec_arg ec of
Nothing -> "true"
Just arg -> makeType arg
in "{|" <> T.pack tag <> ": " <> fieldVal <> "|}"
makeTypeName :: TypeName -> [TypeVar] -> T.Text
makeTypeName tname targs =
let types = T.intercalate ", " (map unTypeVar targs)
in unTypeName tname <> (if null targs then types else ("<" <> types <> ">"))
makeType :: Type -> T.Text
makeType t =
case isBuiltIn t of
Nothing ->
case t of
TyVar (TypeVar x) -> x
TyCon qt args ->
let ty = makeQualTypeName qt
in case args of
[] -> ty
_ -> ty <> "<" <> T.intercalate ", " (map makeType args) <> ">"
Just (bi, tvars)
| bi == tyString -> "string"
| bi == tyInt -> "number"
| bi == tyBool -> "boolean"
| bi == tyFloat -> "number"
| bi == tyDateTime -> "Date"
| bi == tyTime -> "Date"
| bi == tyDate -> "Date"
| bi == tyMaybe -> "(? " <> T.intercalate " " (map makeType tvars) <> ")"
| bi == tyList -> "Array<" <> T.intercalate " " (map makeType tvars) <> ">"
| bi == tyBytes -> "UInt8Array" -- TODO: CHECK
| otherwise ->
error $ "Flow: Unimplemented built in type: " ++ show t
makeQualTypeName :: QualTypeName -> T.Text
makeQualTypeName qtn =
case unModuleName $ qtn_module qtn of
[] -> ty
_ -> printModuleName (qtn_module qtn) <> "." <> ty
where
ty = unTypeName $ qtn_type qtn
|
agrafix/typed-wire
|
src/TW/CodeGen/Flow.hs
|
Haskell
|
mit
| 3,368
|
square :: (Num a) => a -> a
square n = n * n
isDivisor :: (Integral a) => a -> a -> Bool
isDivisor a b = b `mod` a == 0
findDivisor :: (Integral a) => a -> a -> a
findDivisor divisor n
| square divisor > n = n
| isDivisor divisor n = divisor
| otherwise = findDivisor (divisor + 1) n
smallestDivisor :: (Integral a) => a -> a
smallestDivisor = findDivisor 2
prime :: (Integral a) => a -> Bool
prime n = n == smallestDivisor n
no = prime 4
yes = prime 3
|
slideclick/sicp-examples
|
chapters/1/1.2.6/smallest-divisor.hs
|
Haskell
|
mit
| 486
|
factorial :: Integer -> Integer
factorial 0 = 1
factorial n = n * factorial (n - 1)
|
Sergey-Pravdyukov/Homeworks
|
term4/hw1/1/1.hs
|
Haskell
|
mit
| 83
|
{-# LANGUAGE ViewPatterns #-}
-- | Specification of Pos.Chain.Lrc.OBFT (which is basically a pure
-- version of 'Pos.DB.Lrc.OBFT').
module Test.Pos.Chain.Lrc.ObftRoundRobinSpec
( spec
) where
import Universum hiding (sort)
import Data.List.NonEmpty (sort, (!!))
import Test.Hspec (Spec, describe)
import Test.Hspec.QuickCheck (modifyMaxSuccess, prop)
import Test.QuickCheck (Property, (===))
import Pos.Chain.Lrc (getEpochSlotLeaderScheduleObftPure,
getSlotLeaderObftPure)
import Pos.Core (EpochIndex, SlotCount, SlotId, flattenEpochOrSlot)
import Test.Pos.Chain.Lrc.StakeAndHolder (StakeAndHolder (..))
import Test.Pos.Core.Arbitrary (genPositiveSlotCount)
spec :: Spec
spec = do
describe "Pos.Chain.Lrc.OBFT" $ do
describe "Round-robin" $ do
modifyMaxSuccess (const 10000) $ do
prop description_rrListLength
(rrListLength <$> genPositiveSlotCount)
prop description_rrCorrectSlotLeader
(rrCorrectSlotLeader <$> genPositiveSlotCount)
where
description_rrListLength =
"the amount of stakeholders is the same as the number of slots in an epoch"
description_rrCorrectSlotLeader =
"the correct slot leader is chosen given any epoch and slot"
rrListLength
:: SlotCount
-> EpochIndex
-> StakeAndHolder
-> Property
rrListLength epochSlotCount epochIndex (getNoStake -> (_, stakes)) = do
length (getEpochSlotLeaderScheduleObftPure epochIndex epochSlotCount stakeholders)
=== fromIntegral epochSlotCount
where
stakeholders = case nonEmpty (map fst stakes) of
Just s -> s
Nothing -> error "rrListLength: Empty list of stakeholders"
rrCorrectSlotLeader
:: SlotCount
-> SlotId
-> StakeAndHolder
-> Property
rrCorrectSlotLeader epochSlotCount slotId (getNoStake -> (_, stakes)) = do
actualSlotLeader === expectedSlotLeader
where
stakeholders = case nonEmpty (map fst stakes) of
Just s -> s
Nothing -> error "rrCorrectSlotLeader: Empty list of stakeholders"
flatSlotId = flattenEpochOrSlot epochSlotCount slotId
expectedSlotLeaderIndex =
(fromIntegral flatSlotId :: Int) `mod` (length stakeholders)
expectedSlotLeader = (sort stakeholders) !! expectedSlotLeaderIndex
actualSlotLeader = getSlotLeaderObftPure slotId epochSlotCount stakeholders
|
input-output-hk/pos-haskell-prototype
|
chain/test/Test/Pos/Chain/Lrc/ObftRoundRobinSpec.hs
|
Haskell
|
mit
| 2,466
|
--
--
--
-----------------
-- Exercise 4.23.
-----------------
--
--
--
module E'4'23 where
import Test.QuickCheck ( quickCheck )
-- Subsection 4.5 (extended definition) ...
regions' :: Integer -> Integer
regions' n
| n < 0 = 0
| n == 0 = 1
| otherwise = regions' ( n - 1 ) + n
-- Subsection 4.5 ...
sumFun :: (Integer -> Integer) -> Integer -> Integer
sumFun f n
| n == 0 = f 0
| otherwise = sumFun f ( n - 1 ) + f n
-- ...
regionsFun :: Integer -> Integer
regionsFun n
= n
regions :: Integer -> Integer
regions n
| n < 0 = 0
| otherwise = ( sumFun regionsFun n ) + 1
-- Other solution:
regions2 :: Integer -> Integer
regions2 n
| n < 0 = 0
| otherwise = ( sumFun id n ) + 1
prop_regions :: Integer -> Bool
prop_regions n
= ( regions n ) == ( regions' n )
-- GHCi> quickCheck prop_regions
-- +++ OK, passed 100 tests.
|
pascal-knodel/haskell-craft
|
_/links/E'4'23.hs
|
Haskell
|
mit
| 924
|
{-# LANGUAGE NoImplicitPrelude #-}
module Stack.Options.DockerParser where
import Data.Char
import Data.List (intercalate)
import qualified Data.Text as T
import Distribution.Version (anyVersion)
import Options.Applicative
import Options.Applicative.Args
import Options.Applicative.Builder.Extra
import Stack.Constants
import Stack.Docker
import qualified Stack.Docker as Docker
import Stack.Prelude
import Stack.Options.Utils
import Stack.Types.Version
import Stack.Types.Docker
-- | Options parser configuration for Docker.
dockerOptsParser :: Bool -> Parser DockerOptsMonoid
dockerOptsParser hide0 =
DockerOptsMonoid
<$> pure (Any False)
<*> firstBoolFlags dockerCmdName
"using a Docker container. --docker implies 'system-ghc: true'"
hide
<*> fmap First
((Just . DockerMonoidRepo) <$> option str (long (dockerOptName dockerRepoArgName) <>
hide <>
metavar "NAME" <>
help "Docker repository name") <|>
(Just . DockerMonoidImage) <$> option str (long (dockerOptName dockerImageArgName) <>
hide <>
metavar "IMAGE" <>
help "Exact Docker image ID (overrides docker-repo)") <|>
pure Nothing)
<*> firstBoolFlags (dockerOptName dockerRegistryLoginArgName)
"registry requires login"
hide
<*> firstStrOption (long (dockerOptName dockerRegistryUsernameArgName) <>
hide <>
metavar "USERNAME" <>
help "Docker registry username")
<*> firstStrOption (long (dockerOptName dockerRegistryPasswordArgName) <>
hide <>
metavar "PASSWORD" <>
help "Docker registry password")
<*> firstBoolFlags (dockerOptName dockerAutoPullArgName)
"automatic pulling latest version of image"
hide
<*> firstBoolFlags (dockerOptName dockerDetachArgName)
"running a detached Docker container"
hide
<*> firstBoolFlags (dockerOptName dockerPersistArgName)
"not deleting container after it exits"
hide
<*> firstStrOption (long (dockerOptName dockerContainerNameArgName) <>
hide <>
metavar "NAME" <>
help "Docker container name")
<*> argsOption (long (dockerOptName dockerRunArgsArgName) <>
hide <>
value [] <>
metavar "'ARG1 [ARG2 ...]'" <>
help "Additional options to pass to 'docker run'")
<*> many (option auto (long (dockerOptName dockerMountArgName) <>
hide <>
metavar "(PATH | HOST-PATH:CONTAINER-PATH)" <>
completer dirCompleter <>
help ("Mount volumes from host in container " ++
"(may specify multiple times)")))
<*> many (option str (long (dockerOptName dockerEnvArgName) <>
hide <>
metavar "NAME=VALUE" <>
help ("Set environment variable in container " ++
"(may specify multiple times)")))
<*> optionalFirst (absFileOption
(long (dockerOptName dockerDatabasePathArgName) <>
hide <>
metavar "PATH" <>
help "Location of image usage tracking database"))
<*> optionalFirst (option (eitherReader' parseDockerStackExe)
(let specialOpts =
[ dockerStackExeDownloadVal
, dockerStackExeHostVal
, dockerStackExeImageVal
] in
long(dockerOptName dockerStackExeArgName) <>
hide <>
metavar (intercalate "|" (specialOpts ++ ["PATH"])) <>
completer (listCompleter specialOpts <> fileCompleter) <>
help (concat [ "Location of "
, stackProgName
, " executable used in container" ])))
<*> firstBoolFlags (dockerOptName dockerSetUserArgName)
"setting user in container to match host"
hide
<*> pure (IntersectingVersionRange anyVersion)
where
dockerOptName optName = dockerCmdName ++ "-" ++ T.unpack optName
firstStrOption = optionalFirst . option str
hide = hideMods hide0
-- | Parser for docker cleanup arguments.
dockerCleanupOptsParser :: Parser Docker.CleanupOpts
dockerCleanupOptsParser =
Docker.CleanupOpts <$>
(flag' Docker.CleanupInteractive
(short 'i' <>
long "interactive" <>
help "Show cleanup plan in editor and allow changes (default)") <|>
flag' Docker.CleanupImmediate
(short 'y' <>
long "immediate" <>
help "Immediately execute cleanup plan") <|>
flag' Docker.CleanupDryRun
(short 'n' <>
long "dry-run" <>
help "Display cleanup plan but do not execute") <|>
pure Docker.CleanupInteractive) <*>
opt (Just 14) "known-images" "LAST-USED" <*>
opt Nothing "unknown-images" "CREATED" <*>
opt (Just 0) "dangling-images" "CREATED" <*>
opt Nothing "stopped-containers" "CREATED" <*>
opt Nothing "running-containers" "CREATED"
where opt def' name mv =
fmap Just
(option auto
(long name <>
metavar (mv ++ "-DAYS-AGO") <>
help ("Remove " ++
toDescr name ++
" " ++
map toLower (toDescr mv) ++
" N days ago" ++
case def' of
Just n -> " (default " ++ show n ++ ")"
Nothing -> ""))) <|>
flag' Nothing
(long ("no-" ++ name) <>
help ("Do not remove " ++
toDescr name ++
case def' of
Just _ -> ""
Nothing -> " (default)")) <|>
pure def'
toDescr = map (\c -> if c == '-' then ' ' else c)
|
MichielDerhaeg/stack
|
src/Stack/Options/DockerParser.hs
|
Haskell
|
bsd-3-clause
| 6,868
|
{-# LANGUAGE Haskell2010, OverloadedStrings #-}
{-# LINE 1 "Network/Wai/EventSource.hs" #-}
{-|
A WAI adapter to the HTML5 Server-Sent Events API.
-}
module Network.Wai.EventSource (
ServerEvent(..),
eventSourceAppChan,
eventSourceAppIO
) where
import Data.Function (fix)
import Control.Concurrent.Chan (Chan, dupChan, readChan)
import Control.Monad.IO.Class (liftIO)
import Network.HTTP.Types (status200, hContentType)
import Network.Wai (Application, responseStream)
import Network.Wai.EventSource.EventStream
-- | Make a new WAI EventSource application reading events from
-- the given channel.
eventSourceAppChan :: Chan ServerEvent -> Application
eventSourceAppChan chan req sendResponse = do
chan' <- liftIO $ dupChan chan
eventSourceAppIO (readChan chan') req sendResponse
-- | Make a new WAI EventSource application reading events from
-- the given IO action.
eventSourceAppIO :: IO ServerEvent -> Application
eventSourceAppIO src _ sendResponse =
sendResponse $ responseStream
status200
[(hContentType, "text/event-stream")]
$ \sendChunk flush -> fix $ \loop -> do
se <- src
case eventToBuilder se of
Nothing -> return ()
Just b -> sendChunk b >> flush >> loop
|
phischu/fragnix
|
tests/packages/scotty/Network.Wai.EventSource.hs
|
Haskell
|
bsd-3-clause
| 1,337
|
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="ro-RO">
<title>Requester</title>
<maps>
<homeID>requester</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
kingthorin/zap-extensions
|
addOns/requester/src/main/javahelp/help_ro_RO/helpset_ro_RO.hs
|
Haskell
|
apache-2.0
| 960
|
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE DeriveDataTypeable #-}
-- | Versions for packages.
module Stack.Types.Version
(Version
,Cabal.VersionRange -- TODO in the future should have a newtype wrapper
,MajorVersion (..)
,getMajorVersion
,fromMajorVersion
,parseMajorVersionFromString
,versionParser
,parseVersion
,parseVersionFromString
,versionString
,versionText
,toCabalVersion
,fromCabalVersion
,mkVersion
,versionRangeText
,withinRange)
where
import Control.Applicative
import Control.DeepSeq
import Control.Monad.Catch
import Data.Aeson.Extended
import Data.Attoparsec.ByteString.Char8
import Data.Binary (Binary)
import Data.ByteString (ByteString)
import qualified Data.ByteString.Char8 as S8
import Data.Data
import Data.Hashable
import Data.List
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Text (Text)
import qualified Data.Text as T
import Data.Vector.Binary ()
import Data.Vector.Unboxed (Vector)
import qualified Data.Vector.Unboxed as V
import Data.Word
import Distribution.Text (disp)
import qualified Distribution.Version as Cabal
import GHC.Generics
import Language.Haskell.TH
import Language.Haskell.TH.Syntax
import Prelude -- Fix warning: Word in Prelude from base-4.8.
import Text.PrettyPrint (render)
-- | A parse fail.
data VersionParseFail =
VersionParseFail ByteString
| NotAMajorVersion Version
deriving (Typeable)
instance Exception VersionParseFail
instance Show VersionParseFail where
show (VersionParseFail bs) = "Invalid version: " ++ show bs
show (NotAMajorVersion v) = concat
[ "Not a major version: "
, versionString v
, ", expecting exactly two numbers (e.g. 7.10)"
]
-- | A package version.
newtype Version =
Version {unVersion :: Vector Word}
deriving (Eq,Ord,Typeable,Data,Generic,Binary,NFData)
-- | The first two components of a version.
data MajorVersion = MajorVersion !Word !Word
deriving (Typeable, Eq, Ord)
instance Show MajorVersion where
show (MajorVersion x y) = concat [show x, ".", show y]
instance ToJSON MajorVersion where
toJSON = toJSON . fromMajorVersion
-- | Parse major version from @String@
parseMajorVersionFromString :: MonadThrow m => String -> m MajorVersion
parseMajorVersionFromString s = do
Version v <- parseVersionFromString s
if V.length v == 2
then return $ getMajorVersion (Version v)
else throwM $ NotAMajorVersion (Version v)
instance FromJSON MajorVersion where
parseJSON = withText "MajorVersion"
$ either (fail . show) return
. parseMajorVersionFromString
. T.unpack
instance FromJSON a => FromJSON (Map MajorVersion a) where
parseJSON val = do
m <- parseJSON val
fmap Map.fromList $ mapM go $ Map.toList m
where
go (k, v) = do
k' <- either (fail . show) return $ parseMajorVersionFromString k
return (k', v)
-- | Returns the first two components, defaulting to 0 if not present
getMajorVersion :: Version -> MajorVersion
getMajorVersion (Version v) =
case V.length v of
0 -> MajorVersion 0 0
1 -> MajorVersion (V.head v) 0
_ -> MajorVersion (V.head v) (v V.! 1)
-- | Convert a two-component version into a @Version@
fromMajorVersion :: MajorVersion -> Version
fromMajorVersion (MajorVersion x y) = Version $ V.fromList [x, y]
instance Hashable Version where
hashWithSalt i = hashWithSalt i . V.toList . unVersion
instance Lift Version where
lift (Version n) =
appE (conE 'Version)
(appE (varE 'V.fromList)
(listE (map (litE . IntegerL . fromIntegral)
(V.toList n))))
instance Show Version where
show (Version v) =
intercalate "."
(map show (V.toList v))
instance ToJSON Version where
toJSON = toJSON . versionText
instance FromJSON Version where
parseJSON j =
do s <- parseJSON j
case parseVersionFromString s of
Nothing ->
fail ("Couldn't parse package version: " ++ s)
Just ver -> return ver
-- | Attoparsec parser for a package version from bytestring.
versionParser :: Parser Version
versionParser =
do ls <- ((:) <$> num <*> many num')
let !v = V.fromList ls
return (Version v)
where num = decimal
num' = point *> num
point = satisfy (== '.')
-- | Convenient way to parse a package version from a bytestring.
parseVersion :: MonadThrow m => ByteString -> m Version
parseVersion x = go x
where go =
either (const (throwM (VersionParseFail x))) return .
parseOnly (versionParser <* endOfInput)
-- | Migration function.
parseVersionFromString :: MonadThrow m => String -> m Version
parseVersionFromString =
parseVersion . S8.pack
-- | Get a string representation of a package version.
versionString :: Version -> String
versionString (Version v) =
intercalate "."
(map show (V.toList v))
-- | Get a string representation of a package version.
versionText :: Version -> Text
versionText (Version v) =
T.intercalate
"."
(map (T.pack . show)
(V.toList v))
-- | Convert to a Cabal version.
toCabalVersion :: Version -> Cabal.Version
toCabalVersion (Version v) =
Cabal.Version (map fromIntegral (V.toList v)) []
-- | Convert from a Cabal version.
fromCabalVersion :: Cabal.Version -> Version
fromCabalVersion (Cabal.Version vs _) =
let !v = V.fromList (map fromIntegral vs)
in Version v
-- | Make a package version.
mkVersion :: String -> Q Exp
mkVersion s =
case parseVersionFromString s of
Nothing -> error ("Invalid package version: " ++ show s)
Just pn -> [|pn|]
-- | Display a version range
versionRangeText :: Cabal.VersionRange -> Text
versionRangeText = T.pack . render . disp
-- | Check if a version is within a version range.
withinRange :: Version -> Cabal.VersionRange -> Bool
withinRange v r = toCabalVersion v `Cabal.withinRange` r
|
CRogers/stack
|
src/Stack/Types/Version.hs
|
Haskell
|
bsd-3-clause
| 6,337
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TupleSections #-}
module Stack.FileWatch
( fileWatch
, printExceptionStderr
) where
import Blaze.ByteString.Builder (toLazyByteString, copyByteString)
import Blaze.ByteString.Builder.Char.Utf8 (fromShow)
import Control.Concurrent.Async (race_)
import Control.Concurrent.STM
import Control.Exception (Exception)
import Control.Exception.Enclosed (tryAny)
import Control.Monad (forever, unless)
import qualified Data.ByteString.Lazy as L
import qualified Data.Map.Strict as Map
import Data.Monoid ((<>))
import Data.Set (Set)
import qualified Data.Set as Set
import Data.String (fromString)
import Data.Traversable (forM)
import Path
import System.FSNotify
import System.IO (stderr)
-- | Print an exception to stderr
printExceptionStderr :: Exception e => e -> IO ()
printExceptionStderr e =
L.hPut stderr $ toLazyByteString $ fromShow e <> copyByteString "\n"
-- | Run an action, watching for file changes
--
-- The action provided takes a callback that is used to set the files to be
-- watched. When any of those files are changed, we rerun the action again.
fileWatch :: ((Set (Path Abs File) -> IO ()) -> IO ())
-> IO ()
fileWatch inner = withManager $ \manager -> do
dirtyVar <- newTVarIO True
watchVar <- newTVarIO Map.empty
let onChange = atomically $ writeTVar dirtyVar True
setWatched :: Set (Path Abs File) -> IO ()
setWatched files = do
watch0 <- readTVarIO watchVar
let actions = Map.mergeWithKey
keepListening
stopListening
startListening
watch0
newDirs
watch1 <- forM (Map.toList actions) $ \(k, mmv) -> do
mv <- mmv
return $
case mv of
Nothing -> Map.empty
Just v -> Map.singleton k v
atomically $ writeTVar watchVar $ Map.unions watch1
where
newDirs = Map.fromList $ map (, ())
$ Set.toList
$ Set.map parent files
keepListening _dir listen () = Just $ return $ Just listen
stopListening = Map.map $ \f -> do
() <- f
return Nothing
startListening = Map.mapWithKey $ \dir () -> do
let dir' = fromString $ toFilePath dir
listen <- watchDir manager dir' (const True) (const onChange)
return $ Just listen
let watchInput = do
line <- getLine
unless (line == "quit") $ do
case line of
"help" -> do
putStrLn ""
putStrLn "help: display this help"
putStrLn "quit: exit"
putStrLn "build: force a rebuild"
putStrLn "watched: display watched directories"
"build" -> onChange
"watched" -> do
watch <- readTVarIO watchVar
mapM_ (putStrLn . toFilePath) (Map.keys watch)
_ -> putStrLn $ "Unknown command: " ++ show line
watchInput
race_ watchInput $ forever $ do
atomically $ do
dirty <- readTVar dirtyVar
check dirty
writeTVar dirtyVar False
eres <- tryAny $ inner setWatched
case eres of
Left e -> printExceptionStderr e
Right () -> putStrLn "Success! Waiting for next file change."
putStrLn "Type help for available commands"
|
CRogers/stack
|
src/Stack/FileWatch.hs
|
Haskell
|
bsd-3-clause
| 3,671
|
import Control.Concurrent
import Control.Exception
-- check that async exceptions are restored to their previous
-- state after an exception is raised and handled.
main = do
main_thread <- myThreadId
m1 <- newEmptyMVar
m2 <- newEmptyMVar
m3 <- newEmptyMVar
forkIO (do
takeMVar m1
throwTo main_thread (ErrorCall "foo")
takeMVar m2
throwTo main_thread (ErrorCall "bar")
putMVar m3 ()
)
(do
mask $ \restore -> do
(do putMVar m1 ()
restore (
-- unblocked, "foo" delivered to "caught1"
myDelay 100000
)
) `Control.Exception.catch`
\e -> putStrLn ("caught1: " ++ show (e::SomeException))
putMVar m2 ()
-- blocked here, "bar" can't be delivered
(sum [1..10000] `seq` return ())
`Control.Exception.catch`
\e -> putStrLn ("caught2: " ++ show (e::SomeException))
-- unblocked here, "bar" delivered to "caught3"
takeMVar m3
)
`Control.Exception.catch`
\e -> putStrLn ("caught3: " ++ show (e::SomeException))
-- compensate for the fact that threadDelay is non-interruptible
-- on Windows with the threaded RTS in 6.6.
myDelay usec = do
m <- newEmptyMVar
forkIO $ do threadDelay usec; putMVar m ()
takeMVar m
|
urbanslug/ghc
|
testsuite/tests/concurrent/should_run/conc017a.hs
|
Haskell
|
bsd-3-clause
| 1,238
|
{-# LANGUAGE ForeignFunctionInterface #-}
module Main where
-- Test for #1648
import Foreign
import Data.Int
import Data.Word
f :: Int64 -> IO Int64
f x = return $ x + 1
g :: Word64 -> IO Word64
g x = return $ x + 2
type WCall = Word64 -> IO Word64
foreign import ccall "wrapper" mkWCall :: WCall -> IO (FunPtr WCall)
foreign import ccall "dynamic" call_w :: FunPtr WCall -> WCall
type ICall = Int64 -> IO Int64
foreign import ccall "wrapper" mkICall :: ICall -> IO (FunPtr ICall)
foreign import ccall "dynamic" call_i :: FunPtr ICall -> ICall
main = do
fp <- mkICall f
call_i fp 3 >>= print
fp <- mkWCall g
call_w fp 4 >>= print
|
tibbe/ghc
|
testsuite/tests/ffi/should_run/ffi019.hs
|
Haskell
|
bsd-3-clause
| 645
|
{-# OPTIONS_GHC -fdefer-type-errors #-}
module Main where
data Foo = MkFoo
data Bar = MkBar Foo deriving Show
main = do { print True; print (MkBar MkFoo) }
|
siddhanathan/ghc
|
testsuite/tests/deriving/should_run/T9576.hs
|
Haskell
|
bsd-3-clause
| 160
|
module Main where
import System.Environment
import Text.ParserCombinators.Parsec hiding (spaces)
main :: IO ()
main = do args <- getArgs
putStrLn (readExpr (args !! 0))
symbol :: Parser Char
symbol = oneOf "!$%&|*+-/:<=>?@^_~#"
readExpr :: String -> String
readExpr input = case parse symbol "lisp" input of
Left err -> "No match: " ++ show err
Right val -> "Found value"
|
tismith/tlisp
|
write-yourself-a-scheme/listings/listing3.1.hs
|
Haskell
|
mit
| 394
|
{-# LANGUAGE OverloadedStrings #-}
module WordProblem (answer) where
import Data.Text (pack)
import Data.List (foldl')
import Control.Applicative -- (pure, (<|>), (<$>), (<*>), (<*), (*>))
import Data.Attoparsec.Text
( Parser, signed, decimal, space, maybeResult, parse, many' )
import Prelude
answerParser :: Parser Int
answerParser = do
n <- "What is " *> signed decimal
ops <- many' (space *> operation)
"?" *> pure (foldl' (flip ($)) n ops)
answer :: String -> Maybe Int
answer = maybeResult . parse answerParser . pack
operation :: Parser (Int -> Int)
operation = (flip <$> operator) <* space <*> signed decimal
operator :: Parser (Int -> Int -> Int)
operator = "plus" *> pure (+) <|>
"minus" *> pure (-) <|>
"multiplied by" *> pure (*) <|>
"divided by" *> pure div
|
stevejb71/xhaskell
|
wordy/example.hs
|
Haskell
|
mit
| 836
|
-- Copyright 2017 Maximilian Huber <oss@maximilian-huber.de>
-- SPDX-License-Identifier: MIT
{-# OPTIONS_GHC -W -fwarn-unused-imports -fno-warn-missing-signatures #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE FlexibleContexts #-}
module XMonad.MyConfig
( runMyConfig
, composeMyConfig
) where
import System.Environment ( getExecutablePath, getArgs, )
import Control.Monad ( when )
import XMonad
import XMonad.Util.Replace ( replace )
--------------------------------------------------------------------------------
-- MyConfig
import XMonad.MyConfig.Core ( coreConfig, applyMyRestartKBs )
import XMonad.MyConfig.MyManageHookLayer ( applyMyManageHook )
import XMonad.MyConfig.Scratchpads ( applyMyScratchpads )
import XMonad.MyConfig.ToggleFollowFocus ( applyMyFollowFocus )
import XMonad.MyConfig.Notify ( applyMyUrgencyHook )
import XMonad.MyConfig.MyLayoutLayer ( applyMyLayoutModifications )
import XMonad.MyConfig.MyLogHookLayer ( getXMProcs, applyMyLogHook )
-- runMyConfig :: IO ()
-- runMyConfig = do
-- xmprocs <-getXMProcs
-- executablePath <- getExecutablePath
-- xmonad $ composeMyConfig xmprocs executablePath
runMyConfig :: IO ()
runMyConfig = do
args <- getArgs
when ("--myreplace" `elem` args) $ do
putStrLn "try to replace current window manager ..."
replace
xmprocs <- getXMProcs
executablePath <- getExecutablePath
putStrLn ("try to launch: " ++ executablePath)
launch $ composeMyConfig xmprocs executablePath
composeMyConfig xmprocs executablePath = let
layers :: (LayoutClass a Window) => [XConfig a -> XConfig a]
layers = [ applyMyLayoutModifications
, applyMyRestartKBs executablePath
, applyMyManageHook
, applyMyUrgencyHook
, applyMyScratchpads
, applyMyFollowFocus
, applyMyLogHook xmprocs
]
in foldl (\ c f -> f c) coreConfig layers
|
maximilianhuber/myconfig
|
xmonad/lib/XMonad/MyConfig.hs
|
Haskell
|
mit
| 1,920
|
module Symmath.Functiontable where
import Text.Printf
import Text.PrettyPrint
import qualified Data.Map.Strict as M
import Symmath.Terms
import Symmath.Eval
data FuncValue = Value Double | Undefined
instance Show FuncValue where
show (Value n) = show n
show Undefined = "undef"
-- Use show on the returned Docs to format (render) them.
---- Simple number lists.
functionEval :: Double -> Double -> SymTerm -> Char -> [FuncValue]
functionEval from ival term indep = map evalForX [from,from+ival..]
where evalForX x = case evalTermP term (M.insert indep x M.empty) of
Left _ -> Undefined
Right y -> Value y
------------ Functions using defaults --------------------
-- Uses default values for field width, accuracy and the independent variable
defaultFunctionTable :: Double -> Double -> Double -> SymTerm -> Doc
defaultFunctionTable from to ival term = multipleFunctionsDefault from to ival [term]
multipleFunctionsDefault :: Double -> Double -> Double -> [SymTerm] -> Doc
multipleFunctionsDefault from to ival terms = multipleFunctions from to ival width acc terms indep
where width = 15
acc = 4
indep = 'x'
----------- non-default-using functions -------------------
functionTable :: Double -> Double -> Double -> Int -> Int -> SymTerm -> Char -> Doc
functionTable from to ival width acc term indep = multipleFunctions from to ival width acc [term] indep
multipleFunctions :: Double -> Double -> Double -> Int -> Int -> [SymTerm] -> Char -> Doc
multipleFunctions from to ival width acc terms indep = foldr1 ($$) . (header:) . map (foldr1 (<+>) . calcLine) $ [from,(from+ival)..to]
where header = colHeads $$ headSepLine
colHeads = foldr1 (<+>) . map (text . printf ('%':show width++"s") . show) $ terms'
headSepLine = foldr1 (<+>) $ replicate (length terms') (text . replicate width $ '-')
calcLine x = map (calcFunc x) terms'
calcFunc x term = case evalTermP term (M.insert indep x M.empty) of
Right y -> printfFuncValue width acc $ Value y
Left _ -> printfFuncValue width acc Undefined
terms' = (Variable indep):terms
-- Util
printfFuncValue :: Int -> Int -> FuncValue -> Doc
printfFuncValue width _ Undefined = text $ printf ('%':show width++"s") "undef"
printfFuncValue width acc (Value n) = text $ printf ('%':show width++"."++show acc++"f") n
|
Spheniscida/symmath
|
Symmath/Functiontable.hs
|
Haskell
|
mit
| 2,477
|
-- Countdown example from chapter 11 of Programming in Haskell,
-- Graham Hutton, Cambridge University Press, 2007. With help
-- from chapter 20 of Pearls of Functional Algorithm Design,
-- Richard Bird, Cambridge University Press, 2010.
import System.CPUTime
import Numeric
import System.IO
-- Expressions
-- -----------
data Op = Add | Sub | Mul | Div
valid :: Op -> Int -> Int -> Bool
valid Add _ _ = True
valid Sub x y = x > y
valid Mul _ _ = True
valid Div x y = x `mod` y == 0
apply :: Op -> Int -> Int -> Int
apply Add x y = x + y
apply Sub x y = x - y
apply Mul x y = x * y
apply Div x y = x `div` y
data Expr = Val Int | App Op Expr Expr
values :: Expr -> [Int]
values (Val n) = [n]
values (App _ l r) = values l ++ values r
eval :: Expr -> [Int]
eval (Val n) = [n | n > 0]
eval (App o l r) = [apply o x y | x <- eval l
, y <- eval r
, valid o x y]
-- Combinatorial functions
-- -----------------------
subs :: [a] -> [[a]]
subs [] = [[]]
subs (x:xs) = yss ++ map (x:) yss
where yss = subs xs
interleave :: a -> [a] -> [[a]]
interleave x [] = [[x]]
interleave x (y:ys) = (x:y:ys) : map (y:) (interleave x ys)
perms :: [a] -> [[a]]
perms [] = [[]]
perms (x:xs) = concat (map (interleave x) (perms xs))
-- Exercise 0
--
choices :: [a] -> [[a]]
choices xs = [zs | ys <- subs xs, zs <- perms ys]
-- Exercise 1
--
removeone :: Eq a => a -> [a] -> [a]
removeone x [] = []
removeone x (y:ys) | x == y = ys
| otherwise = y : removeone x ys
-- Exercise 2
--
isChoice :: Eq a => [a] -> [a] -> Bool
isChoice [] _ = True
isChoice (x:xs) [] = False
isChoice (x:xs) ys = elem x ys && isChoice xs (removeone x ys)
-- Formalising the problem
-- -----------------------
solution :: Expr -> [Int] -> Int -> Bool
solution e ns n = elem (values e) (choices ns) && eval e == [n]
-- Brute force solution
-- --------------------
-- Exercise 3
--
split :: [a] -> [([a],[a])]
split [] = []
split [_] = []
split (x:xs) = ([x], xs) : [(x : ls, rs) | (ls, rs) <- split xs]
-- import Test.QuickCheck
-- quickCheck ((\xs -> let ys = split xs in all (\t -> fst t ++ snd t == xs) ys) :: [Int] -> Bool)
exprs :: [Int] -> [Expr]
exprs [] = []
exprs [n] = [Val n]
exprs ns = [e | (ls,rs) <- split ns
, l <- exprs ls
, r <- exprs rs
, e <- combine l r]
combine :: Expr -> Expr -> [Expr]
combine l r = [App o l r | o <- ops]
ops :: [Op]
ops = [Add,Sub,Mul,Div]
solutions :: [Int] -> Int -> [Expr]
solutions ns n = [e | ns' <- choices ns
, e <- exprs ns'
, eval e == [n]]
-- Combining generation and evaluation
-- -----------------------------------
type Result = (Expr,Int)
results :: [Int] -> [Result]
results [] = []
results [n] = [(Val n,n) | n > 0]
results ns = [res | (ls,rs) <- split ns
, lx <- results ls
, ry <- results rs
, res <- combine' lx ry]
combine' :: Result -> Result -> [Result]
combine' (l,x) (r,y) = [(App o l r, apply o x y) | o <- ops
, valid o x y]
solutions' :: [Int] -> Int -> [Expr]
solutions' ns n = [e | ns' <- choices ns
, (e,m) <- results ns'
, m == n]
-- Exploiting numeric properties
-- -----------------------------
valid' :: Op -> Int -> Int -> Bool
valid' Add x y = x <= y
valid' Sub x y = x > y
valid' Mul x y = x /= 1 && y /= 1 && x <= y
valid' Div x y = y /= 1 && x `mod` y == 0
results' :: [Int] -> [Result]
results' [] = []
results' [n] = [(Val n,n) | n > 0]
results' ns = [res | (ls,rs) <- split ns
, lx <- results' ls
, ry <- results' rs
, res <- combine'' lx ry]
combine'' :: Result -> Result -> [Result]
combine'' (l,x) (r,y) = [(App o l r, apply o x y) | o <- ops
, valid' o x y]
solutions'' :: [Int] -> Int -> [Expr]
solutions'' ns n = [e | ns' <- choices ns
, (e,m) <- results' ns'
, m == n]
-- Interactive version for testing
-- -------------------------------
instance Show Op where
show Add = "+"
show Sub = "-"
show Mul = "*"
show Div = "/"
instance Show Expr where
show (Val n) = show n
show (App o l r) = bracket l ++ show o ++ bracket r
where
bracket (Val n) = show n
bracket e = "(" ++ show e ++ ")"
showtime :: Integer -> String
showtime t = showFFloat (Just 3)
(fromIntegral t / (10^12)) " seconds"
display :: [Expr] -> IO ()
display es = do t0 <- getCPUTime
if null es then
do t1 <- getCPUTime
putStr "\nThere are no solutions, verified in "
putStr (showtime (t1 - t0))
else
do t1 <- getCPUTime
putStr "\nOne possible solution is "
putStr (show (head es))
putStr ", found in "
putStr (showtime (t1 - t0))
putStr "\n\nPress return to continue searching..."
getLine
putStr "\n"
t2 <- getCPUTime
if null (tail es) then
putStr "There are no more solutions"
else
do sequence [print e | e <- tail es]
putStr "\nThere were "
putStr (show (length es))
putStr " solutions in total, found in "
t3 <- getCPUTime
putStr (showtime ((t1 - t0) + (t3 - t2)))
putStr ".\n\n"
main :: IO ()
main = do hSetBuffering stdout NoBuffering
putStrLn "\nCOUNTDOWN NUMBERS GAME SOLVER"
putStrLn "-----------------------------\n"
putStr "Enter the given numbers : "
ns <- readLn
putStr "Enter the target number : "
n <- readLn
display (solutions'' ns n)
|
anwb/fp-one-on-one
|
lecture-10-hw.hs
|
Haskell
|
mit
| 8,958
|
module Data.DirectoryTreeSpec where
import qualified Data.Aeson as AE
import qualified Data.Aeson.Encode.Pretty as AE
import qualified Data.ByteString.Lazy.Char8 as BS
import Data.Tree
import Data.DirectoryTree
import Data.Either (isRight)
import Test.Hspec
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "JSON (de)serialization" $
it "can be encoded and decoded from JSON" $ do
let encodedJson = BS.unpack . prettyEncode $ testTree
let decodedJson = AE.eitherDecode (BS.pack encodedJson) :: Either String DirectoryTree
{- putStrLn encodedJson -}
{- case decodedJson of -}
{- (Left err) -> putStrLn err -}
{- (Right val) -> putStr $ show decodedJson -}
isRight decodedJson `shouldBe` True
testTree :: DirectoryTree
testTree = DirectoryTree rootNode
rootNode = Node (FileDescription "features" "features") [creatures]
creatures = Node (FileDescription "creatures" "features/creatures") [swampThing, wolfman]
swampThing = Node (FileDescription "swamp-thing" "features/creatures/swamp-thing") [
Node (FileDescription "vegetable-mind-control.feature" "features/creatures/swamp-thing/vegetable-mind-control.feature") [],
Node (FileDescription "limb-regeneration.feature" "features/creatures/swamp-thing/limb-regeneration.feature") []
]
wolfman = Node (FileDescription "wolfman" "features/creatures/wolfman") [
Node (FileDescription "shape-shifting.feature" "features/creatures/wolfman/shape-shifting.feature") [],
Node (FileDescription "animal-instincts.feature" "features/creatures/wolfman/animal-instincts.feature") []
]
prettyEncode :: AE.ToJSON a => a -> BS.ByteString
prettyEncode = AE.encodePretty' prettyConfig
prettyConfig :: AE.Config
prettyConfig = AE.Config { AE.confIndent = 2, AE.confCompare = mempty }
|
gust/feature-creature
|
legacy/lib/test/Data/DirectoryTreeSpec.hs
|
Haskell
|
mit
| 1,802
|
{-# htermination intersect :: [Ordering] -> [Ordering] -> [Ordering] #-}
import List
|
ComputationWithBoundedResources/ara-inference
|
doc/tpdb_trs/Haskell/full_haskell/List_intersect_7.hs
|
Haskell
|
mit
| 85
|
{-# LANGUAGE OverloadedStrings #-}
import SMTLib1.QF_AUFBV as BV
import System.Process
import System.IO
main :: IO ()
main =
do let txt = show (pp script)
putStrLn txt
putStrLn (replicate 80 '-')
-- putStrLn =<< readProcess "yices" ["-smt", "-tc"] txt
putStrLn =<< readProcess "yices" ["-f"] txt
script :: Script
script = Script "Test"
[ logic "QF_AUFBV"
, constDef "a" (tBitVec 8)
, goal (BV.concat (bv 1 8) (bv 3 8) === bv 259 16)
]
script1 :: Script
script1 = Script "Test"
[ logic "QF_BV"
, constDef "x" (tBitVec 8)
, assume (c "x" === bv 0 8)
, goal (c "x" === bv 256 8)
]
c x = App x []
|
yav/smtLib
|
test/Test1.hs
|
Haskell
|
mit
| 641
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE OverloadedStrings #-}
module Json.UserSpec (spec) where
import Data.Aeson.Lens
import Lastfm
import Lastfm.User
import Test.Hspec
import SpecHelper
spec :: Spec
spec = do
it "getRecentStations" $
privately (getRecentStations <*> user "liblastfm" <* limit 10)
`shouldHaveJson`
key "recentstations".key "station".values.key "name"._String
it "getRecommendedArtists" $
privately (getRecommendedArtists <* limit 10)
`shouldHaveJson`
key "recommendations".key "artist".values.key "name"._String
it "getRecommendedEvents" $
privately (getRecommendedEvents <* limit 10)
`shouldHaveJson`
key "events".key "event".key "url"._String
it "shout" $
shouldHaveJson_ . privately $
shout <*> user "liblastfm" <*> message "test message"
it "getArtistTracks" $
publicly (getArtistTracks <*> user "smpcln" <*> artist "Dvar")
`shouldHaveJson`
key "artisttracks".key "track".values.key "name"._String
it "getBannedTracks" $
publicly (getBannedTracks <*> user "smpcln" <* limit 10)
`shouldHaveJson`
key "bannedtracks".key "track".values.key "name"._String
it "getEvents" $
publicly (getEvents <*> user "chansonnier" <* limit 5)
`shouldHaveJson`
key "events".key "event".values.key "venue".key "url"._String
it "getFriends" $
publicly (getFriends <*> user "smpcln" <* limit 10)
`shouldHaveJson`
key "friends".key "user".values.key "name"._String
it "getPlayCount" $
publicly (getInfo <*> user "smpcln")
`shouldHaveJson`
key "user".key "playcount"._String
it "getGetLovedTracks" $
publicly (getLovedTracks <*> user "smpcln" <* limit 10)
`shouldHaveJson`
key "lovedtracks".key "track".values.key "name"._String
it "getNeighbours" $
publicly (getNeighbours <*> user "smpcln" <* limit 10)
`shouldHaveJson`
key "neighbours".key "user".values.key "name"._String
it "getNewReleases" $
publicly (getNewReleases <*> user "rj")
`shouldHaveJson`
key "albums".key "album".values.key "url"._String
it "getPastEvents" $
publicly (getPastEvents <*> user "mokele" <* limit 5)
`shouldHaveJson`
key "events".key "event".values.key "url"._String
it "getPersonalTags" $
publicly (getPersonalTags <*> user "crackedcore" <*> tag "rhythmic noise" <*> taggingType "artist" <* limit 10)
`shouldHaveJson`
key "taggings".key "artists".key "artist".values.key "name"._String
it "getPlaylists" $
publicly (getPlaylists <*> user "mokele")
`shouldHaveJson`
key "playlists".key "playlist".values.key "title"._String
it "getRecentTracks" $
publicly (getRecentTracks <*> user "smpcln" <* limit 10)
`shouldHaveJson`
key "recenttracks".key "track".values.key "name"._String
it "getShouts" $
publicly (getShouts <*> user "smpcln" <* limit 2)
`shouldHaveJson`
key "shouts".key "shout".values.key "body"._String
it "getTopAlbums" $
publicly (getTopAlbums <*> user "smpcln" <* limit 5)
`shouldHaveJson`
key "topalbums".key "album".values.key "artist".key "name"._String
it "getTopArtists" $
publicly (getTopArtists <*> user "smpcln" <* limit 5)
`shouldHaveJson`
key "topartists".key "artist".values.key "name"._String
it "getTopTags" $
publicly (getTopTags <*> user "smpcln" <* limit 10)
`shouldHaveJson`
key "toptags".key "tag".values.key "name"._String
it "getTopTracks" $
publicly (getTopTracks <*> user "smpcln" <* limit 10)
`shouldHaveJson`
key "toptracks".key "track".values.key "url"._String
it "getWeeklyAlbumChart" $
publicly (getWeeklyAlbumChart <*> user "smpcln")
`shouldHaveJson`
key "weeklyalbumchart".key "album".values.key "url"._String
it "getWeeklyArtistChart" $
publicly (getWeeklyArtistChart <*> user "smpcln")
`shouldHaveJson`
key "weeklyartistchart".key "artist".values.key "url"._String
it "getWeeklyChartList" $
publicly (getWeeklyChartList <*> user "smpcln")
`shouldHaveJson`
key "weeklychartlist".key "chart".values.key "from"._String
it "getWeeklyTrackChart" $
publicly (getWeeklyTrackChart <*> user "smpcln")
`shouldHaveJson`
key "weeklytrackchart".key "track".values.key "url"._String
|
supki/liblastfm
|
test/api/Json/UserSpec.hs
|
Haskell
|
mit
| 4,242
|
{-|
Module : Database.Orville.PostgreSQL.Internal.Expr.NameExpr
Copyright : Flipstone Technology Partners 2016-2018
License : MIT
-}
{-# LANGUAGE OverloadedStrings #-}
module Database.Orville.PostgreSQL.Internal.Expr.NameExpr where
import Data.String
import Database.Orville.PostgreSQL.Internal.MappendCompat ((<>))
import Database.Orville.PostgreSQL.Internal.Expr.Expr
import Database.Orville.PostgreSQL.Internal.QueryKey
type NameExpr = Expr NameForm
data NameForm = NameForm
{ nameFormTable :: Maybe String
, nameFormName :: String
} deriving (Eq, Ord)
instance IsString NameForm where
fromString str = NameForm {nameFormTable = Nothing, nameFormName = str}
instance QualifySql NameForm where
qualified form table = form {nameFormTable = Just table}
instance QueryKeyable NameForm where
queryKey = QKField . unescapedName
instance GenerateSql NameForm where
generateSql (NameForm Nothing name) = "\"" <> rawSql name <> "\""
generateSql (NameForm (Just table) name) =
"\"" <> rawSql table <> "\".\"" <> rawSql name <> "\""
unescapedName :: NameForm -> String
unescapedName (NameForm Nothing name) = name
unescapedName (NameForm (Just table) name) = table <> "." <> name
|
flipstone/orville
|
orville-postgresql/src/Database/Orville/PostgreSQL/Internal/Expr/NameExpr.hs
|
Haskell
|
mit
| 1,208
|
{-# LANGUAGE NoMonomorphismRestriction, OverloadedStrings #-}
import Text.XML.HXT.Core
import Data.List
import Text.HandsomeSoup
import System.Random
import System.Environment
import Network.HTTP.Base
import System.Process
import Network.HTTP.Enumerator
import Network.HTTP.Types (methodPost)
import qualified Data.ByteString.Lazy.Char8 as L
main :: IO ()
main = do args <- getArgs
case length args of
0 -> putStrLn help
_ -> do gen <- newStdGen
wpList <- wallpapers (args !! 0) (args !! 1)
wp <- wallpaper $ wpList !! head (randomRs (0, length wpList) gen)
createProcess $ shell ("feh --bg-scale " ++ head wp)
putStrLn $ wp !! 1
help :: String
help = "Usage: randwp tag resolution"
wallpapers :: String -> String -> IO [String]
wallpapers q res = do html <- request q res
let doc = parseHtml $ L.unpack html
contents <- runX $ doc >>> css "a" ! "href"
return $ filter ("wallpaper" `isInfixOf`) contents
wallpaper :: String -> IO [String]
wallpaper url = do doc <- fromUrl url
runX $ getWp doc
getWp doc = doc >>> css "div" >>>
hasAttrValue "id" (== "bigwall") >>>
css "img" ! "src" <+> css "img" ! "alt"
request q res = do req0 <- parseUrl "http://wallbase.cc/search/"
let req = req0 { method = methodPost
, requestHeaders = [("Content-Type", "application/x-www-form-urlencoded")]
, requestBody = RequestBodyLBS $ mkPost q res
}
res <- withManager $ httpLbs req
return $ responseBody res
mkPost :: String -> String -> L.ByteString
mkPost q res = L.pack $ "query=" ++ urlEncode q ++ "&res=" ++ res ++ "&res_opt=gteq"
|
Okasu/randwp
|
RandWP.hs
|
Haskell
|
mit
| 1,923
|
module HaskHOL.Lib.CalcNum.Pre where
import HaskHOL.Core hiding (base)
import HaskHOL.Deductive
import HaskHOL.Lib.Nums
import HaskHOL.Lib.Arith
import HaskHOL.Lib.WF
-- Build up lookup table for numeral conversions.
tmZero, tmBIT0, tmBIT1, tmM, tmN, tmP, tmAdd, tmSuc :: WFCtxt thry => HOL cls thry HOLTerm
tmZero = serve [wf| _0 |]
tmBIT0 = serve [wf| BIT0 |]
tmBIT1 = serve [wf| BIT1 |]
tmM = serve [wf| m:num |]
tmN = serve [wf| n:num |]
tmP = serve [wf| p:num |]
tmAdd = serve [wf| (+) |]
tmSuc = serve [wf| SUC |]
mkClauses :: WFCtxt thry => Bool -> HOLTerm -> HOL cls thry (HOLThm, Int)
mkClauses sucflag t =
do tmSuc' <- tmSuc
tm <- if sucflag then mkComb tmSuc' t else return t
th1 <- runConv (convPURE_REWRITE
[thmARITH_ADD, thmARITH_SUC, thmARITH_0]) tm
tm1 <- patadj =<< rand (concl th1)
tmAdd' <- toHTm tmAdd
tmP' <- toHTm tmP
tmM' <- toHTm tmM
if not (tmAdd' `freeIn` tm1)
then return (th1, if tmM' `freeIn` tm1 then 0 else 1)
else do ptm <- rand =<< rand =<< rand =<< rand tm1
ptm' <- mkEq ptm tmP'
tmc <- mkEq ptm' =<< mkEq tm =<< subst [(ptm, tmP')] tm1
th <- ruleEQT_ELIM =<<
runConv (convREWRITE [ thmARITH_ADD
, thmARITH_SUC
, thmARITH_0
, thmBITS_INJ]) tmc
return (th, if tmSuc' `freeIn` tm1 then 3 else 2)
where patadj :: WFCtxt thry => HOLTerm -> HOL cls thry HOLTerm
patadj tm =
do tms <- mapM (pairMapM toHTm)
[ (serve [wf| SUC m |], serve [wf| SUC (m + _0) |])
, (serve [wf| SUC n |], serve [wf| SUC (_0 + n) |])]
subst tms tm
starts :: WFCtxt thry => HOL cls thry [HOLTerm]
starts =
do ms <- bases tmM
ns <- bases tmN
allpairsV (\ mtm ntm -> mkComb (mkComb tmAdd mtm) ntm) ms ns
where allpairsV :: Monad m => (a -> b -> m c) -> [a] -> [b] -> m [c]
allpairsV _ [] _ = return []
allpairsV f (h:t) ys =
do t' <- allpairsV f t ys
foldrM (\ x a -> do h' <- f h x
return (h' : a)) t' ys
bases :: (WFCtxt thry, HOLTermRep tm cls thry)
=> tm -> HOL cls thry [HOLTerm]
bases pv =
do v <- toHTm pv
v0 <- mkComb tmBIT0 v
v1 <- mkComb tmBIT1 v
part2 <- mapM (`mkCompnumeral` v) [8..15]
part1 <- mapM (subst [(v1, v0)]) part2
tmZero' <- toHTm tmZero
part0 <- mapM (`mkCompnumeral` tmZero') [0..15]
return $! part0 ++ part1 ++ part2
mkCompnumeral :: WFCtxt thry => Int -> HOLTerm -> HOL cls thry HOLTerm
mkCompnumeral 0 base = return base
mkCompnumeral k base =
do t <- mkCompnumeral (k `div` 2) base
if k `mod` 2 == 1
then mkComb tmBIT1 t
else mkComb tmBIT0 t
convNUM_SHIFT_pths0' :: WFCtxt thry => HOL cls thry HOLThm
convNUM_SHIFT_pths0' = cacheProof "convNUM_SHIFT_pths0'" ctxtWF .
prove [txt| (n = _0 + p * b <=>
BIT0(BIT0(BIT0(BIT0 n))) =
_0 + BIT0(BIT0(BIT0(BIT0 p))) * b) /\
(n = _0 + p * b <=>
BIT1(BIT0(BIT0(BIT0 n))) =
BIT1 _0 + BIT0(BIT0(BIT0(BIT0 p))) * b) /\
(n = _0 + p * b <=>
BIT0(BIT1(BIT0(BIT0 n))) =
BIT0(BIT1 _0) + BIT0(BIT0(BIT0(BIT0 p))) * b) /\
(n = _0 + p * b <=>
BIT1(BIT1(BIT0(BIT0 n))) =
BIT1(BIT1 _0) + BIT0(BIT0(BIT0(BIT0 p))) * b) /\
(n = _0 + p * b <=>
BIT0(BIT0(BIT1(BIT0 n))) =
BIT0(BIT0(BIT1 _0)) + BIT0(BIT0(BIT0(BIT0 p))) * b) /\
(n = _0 + p * b <=>
BIT1(BIT0(BIT1(BIT0 n))) =
BIT1(BIT0(BIT1 _0)) + BIT0(BIT0(BIT0(BIT0 p))) * b) /\
(n = _0 + p * b <=>
BIT0(BIT1(BIT1(BIT0 n))) =
BIT0(BIT1(BIT1 _0)) + BIT0(BIT0(BIT0(BIT0 p))) * b) /\
(n = _0 + p * b <=>
BIT1(BIT1(BIT1(BIT0 n))) =
BIT1(BIT1(BIT1 _0)) + BIT0(BIT0(BIT0(BIT0 p))) * b) /\
(n = _0 + p * b <=>
BIT0(BIT0(BIT0(BIT1 n))) =
BIT0(BIT0(BIT0(BIT1 _0))) + BIT0(BIT0(BIT0(BIT0 p))) * b) /\
(n = _0 + p * b <=>
BIT1(BIT0(BIT0(BIT1 n))) =
BIT1(BIT0(BIT0(BIT1 _0))) + BIT0(BIT0(BIT0(BIT0 p))) * b) /\
(n = _0 + p * b <=>
BIT0(BIT1(BIT0(BIT1 n))) =
BIT0(BIT1(BIT0(BIT1 _0))) + BIT0(BIT0(BIT0(BIT0 p))) * b) /\
(n = _0 + p * b <=>
BIT1(BIT1(BIT0(BIT1 n))) =
BIT1(BIT1(BIT0(BIT1 _0))) + BIT0(BIT0(BIT0(BIT0 p))) * b) /\
(n = _0 + p * b <=>
BIT0(BIT0(BIT1(BIT1 n))) =
BIT0(BIT0(BIT1(BIT1 _0))) + BIT0(BIT0(BIT0(BIT0 p))) * b) /\
(n = _0 + p * b <=>
BIT1(BIT0(BIT1(BIT1 n))) =
BIT1(BIT0(BIT1(BIT1 _0))) + BIT0(BIT0(BIT0(BIT0 p))) * b) /\
(n = _0 + p * b <=>
BIT0(BIT1(BIT1(BIT1 n))) =
BIT0(BIT1(BIT1(BIT1 _0))) + BIT0(BIT0(BIT0(BIT0 p))) * b) /\
(n = _0 + p * b <=>
BIT1(BIT1(BIT1(BIT1 n))) =
BIT1(BIT1(BIT1(BIT1 _0))) + BIT0(BIT0(BIT0(BIT0 p))) * b) |] $
tacSUBST1 (ruleMESON [defNUMERAL] [txt| _0 = 0 |]) `_THEN`
tacMP (ruleREWRITE [ruleGSYM thmMULT_2] thmBIT0) `_THEN`
tacMP (ruleREWRITE [ruleGSYM thmMULT_2] thmBIT1) `_THEN`
tacABBREV [txt| two = 2 |] `_THEN`
_DISCH_THEN (\ th -> tacREWRITE [th]) `_THEN`
_DISCH_THEN (\ th -> tacREWRITE [th]) `_THEN`
_FIRST_X_ASSUM (tacSUBST1 . ruleSYM) `_THEN`
tacREWRITE [ thmADD_CLAUSES, thmSUC_INJ
, thmEQ_MULT_LCANCEL, thmARITH_EQ
, ruleGSYM thmLEFT_ADD_DISTRIB, ruleGSYM thmMULT_ASSOC ]
convNUM_UNSHIFT_puths1' :: WFCtxt thry => HOL cls thry HOLThm
convNUM_UNSHIFT_puths1' = cacheProof "convNUM_UNSHIFT_puths1'" ctxtWF .
prove [txt| (a + p * b = n <=>
BIT0(BIT0(BIT0(BIT0 a))) + BIT0(BIT0(BIT0(BIT0 p))) * b =
BIT0(BIT0(BIT0(BIT0 n)))) /\
(a + p * b = n <=>
BIT1(BIT0(BIT0(BIT0 a))) + BIT0(BIT0(BIT0(BIT0 p))) * b =
BIT1(BIT0(BIT0(BIT0 n)))) /\
(a + p * b = n <=>
BIT0(BIT1(BIT0(BIT0 a))) + BIT0(BIT0(BIT0(BIT0 p))) * b =
BIT0(BIT1(BIT0(BIT0 n)))) /\
(a + p * b = n <=>
BIT1(BIT1(BIT0(BIT0 a))) + BIT0(BIT0(BIT0(BIT0 p))) * b =
BIT1(BIT1(BIT0(BIT0 n)))) /\
(a + p * b = n <=>
BIT0(BIT0(BIT1(BIT0 a))) + BIT0(BIT0(BIT0(BIT0 p))) * b =
BIT0(BIT0(BIT1(BIT0 n)))) /\
(a + p * b = n <=>
BIT1(BIT0(BIT1(BIT0 a))) + BIT0(BIT0(BIT0(BIT0 p))) * b =
BIT1(BIT0(BIT1(BIT0 n)))) /\
(a + p * b = n <=>
BIT0(BIT1(BIT1(BIT0 a))) + BIT0(BIT0(BIT0(BIT0 p))) * b =
BIT0(BIT1(BIT1(BIT0 n)))) /\
(a + p * b = n <=>
BIT1(BIT1(BIT1(BIT0 a))) + BIT0(BIT0(BIT0(BIT0 p))) * b =
BIT1(BIT1(BIT1(BIT0 n)))) /\
(a + p * b = n <=>
BIT0(BIT0(BIT0(BIT1 a))) + BIT0(BIT0(BIT0(BIT0 p))) * b =
BIT0(BIT0(BIT0(BIT1 n)))) /\
(a + p * b = n <=>
BIT1(BIT0(BIT0(BIT1 a))) + BIT0(BIT0(BIT0(BIT0 p))) * b =
BIT1(BIT0(BIT0(BIT1 n)))) /\
(a + p * b = n <=>
BIT0(BIT1(BIT0(BIT1 a))) + BIT0(BIT0(BIT0(BIT0 p))) * b =
BIT0(BIT1(BIT0(BIT1 n)))) /\
(a + p * b = n <=>
BIT1(BIT1(BIT0(BIT1 a))) + BIT0(BIT0(BIT0(BIT0 p))) * b =
BIT1(BIT1(BIT0(BIT1 n)))) /\
(a + p * b = n <=>
BIT0(BIT0(BIT1(BIT1 a))) + BIT0(BIT0(BIT0(BIT0 p))) * b =
BIT0(BIT0(BIT1(BIT1 n)))) /\
(a + p * b = n <=>
BIT1(BIT0(BIT1(BIT1 a))) + BIT0(BIT0(BIT0(BIT0 p))) * b =
BIT1(BIT0(BIT1(BIT1 n)))) /\
(a + p * b = n <=>
BIT0(BIT1(BIT1(BIT1 a))) + BIT0(BIT0(BIT0(BIT0 p))) * b =
BIT0(BIT1(BIT1(BIT1 n)))) /\
(a + p * b = n <=>
BIT1(BIT1(BIT1(BIT1 a))) + BIT0(BIT0(BIT0(BIT0 p))) * b =
BIT1(BIT1(BIT1(BIT1 n)))) |] $
tacSUBST1 (ruleMESON [defNUMERAL] [txt| _0 = 0 |]) `_THEN`
tacMP (ruleREWRITE [ruleGSYM thmMULT_2] thmBIT0) `_THEN`
tacMP (ruleREWRITE [ruleGSYM thmMULT_2] thmBIT1) `_THEN`
tacABBREV [txt| two = 2 |] `_THEN`
_DISCH_THEN (\ th -> tacREWRITE[th]) `_THEN`
_DISCH_THEN (\ th -> tacREWRITE[th]) `_THEN`
_FIRST_X_ASSUM (tacSUBST1 . ruleSYM) `_THEN`
tacREWRITE [ thmADD_CLAUSES, thmSUC_INJ
, thmEQ_MULT_LCANCEL, thmARITH_EQ
, ruleGSYM thmLEFT_ADD_DISTRIB
, ruleGSYM thmMULT_ASSOC
]
|
ecaustin/haskhol-math
|
src/HaskHOL/Lib/CalcNum/Pre.hs
|
Haskell
|
bsd-2-clause
| 9,511
|
module Main where
import System.Console.CmdArgs
import Application.Hoodle.Database.ProgType
import Application.Hoodle.Database.Command
main :: IO ()
main = do
putStrLn "hoodle-db"
param <- cmdArgs mode
commandLineProcess param
|
wavewave/hoodle-db
|
exe/hoodle-db.hs
|
Haskell
|
bsd-2-clause
| 238
|
module NeighboursSpec where
import Neighbours
import Test.Hspec
spec :: Spec
spec = describe "neighbours" $ do
describe "leftCell" $ do
it "the left cell of a left-most cell is always dead (top)" $ do
leftCell 0 0 [[1,0,0],[0,0,0],[0,0,0]] `shouldBe` 0
it "the left cell of a left-most cell is always dead (middle)" $ do
leftCell 1 0 [[0,0,0],[1,0,0],[0,0,0]] `shouldBe` 0
it "the left cell of a left-most cell is always dead (buttom)" $ do
leftCell 2 0 [[0,0,0],[0,0,0],[1,0,0]] `shouldBe` 0
it "has a living left neighbour" $ do
leftCell 0 1 [[1,1,0],[0,0,0],[0,0,0]] `shouldBe` 1
it "has a living left neighbour" $ do
leftCell 1 1 [[0,0,0],[1,1,0],[0,0,0]] `shouldBe` 1
it "has a living left neighbour" $ do
leftCell 2 1 [[0,0,0],[0,0,0],[1,1,0]] `shouldBe` 1
it "has a living left neighbour" $ do
leftCell 0 2 [[0,1,1],[0,0,0],[0,0,0]] `shouldBe` 1
it "has a living left neighbour" $ do
leftCell 1 2 [[0,0,0],[0,1,1],[0,0,0]] `shouldBe` 1
it "has a living left neighbour" $ do
leftCell 2 2 [[0,0,0],[0,0,0],[0,1,1]] `shouldBe` 1
describe "rightCell" $ do
it "the right cell of a right-most cell is always dead (top)" $ do
rightCell 0 2 [[0,0,1],[0,0,0],[0,0,0]] `shouldBe` 0
it "the right cell of a right-most cell is always dead (middle)" $ do
rightCell 1 2 [[0,0,0],[0,0,1],[0,0,0]] `shouldBe` 0
it "the right cell of a right-most cell is always dead (buttom)" $ do
rightCell 2 2 [[0,0,0],[0,0,0],[0,0,1]] `shouldBe` 0
it "has a living right neighbour" $ do
rightCell 0 1 [[0,1,1],[0,0,0],[0,0,0]] `shouldBe` 1
it "has a living right neighbour" $ do
rightCell 1 1 [[0,0,0],[0,1,1],[0,0,0]] `shouldBe` 1
it "has a living right neighbour" $ do
rightCell 2 1 [[0,0,0],[0,0,0],[0,1,1]] `shouldBe` 1
it "has a living right neighbour" $ do
rightCell 0 0 [[1,1,0],[0,0,0],[0,0,0]] `shouldBe` 1
it "has a living right neighbour" $ do
rightCell 1 0 [[0,0,0],[1,1,0],[0,0,0]] `shouldBe` 1
it "has a living right neighbour" $ do
rightCell 2 0 [[0,0,0],[0,0,0],[1,1,0]] `shouldBe` 1
describe "upperCell" $ do
it "the upper cell of a top-most cell is always dead" $ do
upperCell 0 0 [[1,0,0],[0,0,0],[0,0,0]] `shouldBe` 0
it "the upper cell of a top-most cell is always dead" $ do
upperCell 0 1 [[0,1,0],[0,0,0],[0,0,0]] `shouldBe` 0
it "the upper cell of a top-most cell is always dead" $ do
upperCell 0 2 [[0,0,1],[0,0,0],[0,0,0]] `shouldBe` 0
it "has a living upper neighbour" $ do
upperCell 1 0 [[1,0,0],[1,0,0],[0,0,0]] `shouldBe` 1
it "has a living upper neighbour" $ do
upperCell 1 1 [[0,1,0],[0,1,0],[0,0,0]] `shouldBe` 1
it "has a living upper neighbour" $ do
upperCell 1 2 [[0,0,1],[0,0,1],[0,0,0]] `shouldBe` 1
it "has a living upper neighbour" $ do
upperCell 2 0 [[0,0,0],[1,0,0],[1,0,0]] `shouldBe` 1
it "has a living upper neighbour" $ do
upperCell 2 1 [[0,0,0],[0,1,0],[0,1,0]] `shouldBe` 1
it "has a living upper neighbour" $ do
upperCell 2 2 [[0,0,0],[0,0,1],[0,0,1]] `shouldBe` 1
describe "lowerCell" $ do
it "the lower cell of a bottom-most cell is always dead" $ do
lowerCell 2 0 [[0,0,0],[0,0,0],[1,0,0]] `shouldBe` 0
it "the lower cell of a bottom-most cell is always dead" $ do
lowerCell 2 1 [[0,0,0],[0,0,0],[0,1,0]] `shouldBe` 0
it "the lower cell of a bottom-most cell is always dead" $ do
lowerCell 2 2 [[0,0,0],[0,0,0],[0,0,1]] `shouldBe` 0
it "has a living lower neighbour" $ do
lowerCell 0 0 [[1,0,0],[1,0,0],[0,0,0]] `shouldBe` 1
it "has a living lower neighbour" $ do
lowerCell 0 1 [[0,1,0],[0,1,0],[0,0,0]] `shouldBe` 1
it "has a living lower neighbour" $ do
lowerCell 0 2 [[0,0,1],[0,0,1],[0,0,0]] `shouldBe` 1
it "has a living lower neighbour" $ do
lowerCell 1 0 [[0,0,0],[1,0,0],[1,0,0]] `shouldBe` 1
it "has a living lower neighbour" $ do
lowerCell 1 1 [[0,0,0],[0,1,0],[0,1,0]] `shouldBe` 1
it "has a living lower neighbour" $ do
lowerCell 1 2 [[0,0,0],[0,0,1],[0,0,1]] `shouldBe` 1
describe "upperLeftCell" $ do
it "the upper-left cell of a left-most cell is always dead" $ do
upperLeftCell 0 0 [[1,0,0],[0,0,0],[0,0,0]] `shouldBe` 0
it "the upper-left cell of a left-most cell is always dead" $ do
upperLeftCell 1 0 [[0,0,0],[1,0,0],[0,0,0]] `shouldBe` 0
it "the upper-left cell of a left-most cell is always dead" $ do
upperLeftCell 1 0 [[0,0,0],[0,0,0],[1,0,0]] `shouldBe` 0
it "has a living neighbour" $ do
upperLeftCell 1 1 [[1,0,0],[0,1,0],[0,0,0]] `shouldBe` 1
it "has a living neighbour" $ do
upperLeftCell 2 1 [[0,0,0],[1,0,0],[0,1,0]] `shouldBe` 1
it "has a living neighbour" $ do
upperLeftCell 1 2 [[0,1,0],[0,0,1],[0,0,0]] `shouldBe` 1
it "has a living neighbour" $ do
upperLeftCell 2 2 [[0,0,0],[0,1,0],[0,0,1]] `shouldBe` 1
describe "lowerRightCell" $ do
it "the lower-right cell of a right-most cell is always dead" $ do
lowerRightCell 0 2 [[0,0,1],[0,0,0],[0,0,0]] `shouldBe` 0
it "the lower-right cell of a right-most cell is always dead" $ do
lowerRightCell 1 2 [[0,0,0],[0,0,1],[0,0,0]] `shouldBe` 0
it "the lower-right cell of a right-most cell is always dead" $ do
lowerRightCell 2 2 [[0,0,0],[0,0,0],[0,0,1]] `shouldBe` 0
it "has a living neighbour" $ do
lowerRightCell 0 0 [[1,0,0],[0,1,0],[0,0,0]] `shouldBe` 1
it "has a living neighbour" $ do
lowerRightCell 1 0 [[0,0,0],[1,0,0],[0,1,0]] `shouldBe` 1
it "has a living neighbour" $ do
lowerRightCell 0 1 [[0,1,0],[0,0,1],[0,0,0]] `shouldBe` 1
it "has a living neighbour" $ do
lowerRightCell 1 1 [[0,0,0],[0,1,0],[0,0,1]] `shouldBe` 1
describe "upperRightCell" $ do
it "the upper-right cell of a right-most cell is always dead" $ do
upperRightCell 0 2 [[0,0,1],[0,0,0],[0,0,0]] `shouldBe` 0
it "the upper-right cell of a right-most cell is always dead" $ do
upperRightCell 1 2 [[0,0,0],[0,0,1],[0,0,0]] `shouldBe` 0
it "the upper-right cell of a right-most cell is always dead" $ do
upperRightCell 2 2 [[0,0,0],[0,0,0],[0,0,1]] `shouldBe` 0
it "has a living neighbour" $ do
upperRightCell 1 1 [[0,0,1],[0,1,0],[0,0,0]] `shouldBe` 1
it "has a living neighbour" $ do
upperRightCell 1 0 [[0,1,0],[1,0,0],[0,0,0]] `shouldBe` 1
it "has a living neighbour" $ do
upperRightCell 2 1 [[0,0,0],[0,0,1],[0,1,0]] `shouldBe` 1
it "has a living neighbour" $ do
upperRightCell 2 0 [[0,0,0],[0,1,0],[1,0,0]] `shouldBe` 1
describe "lowerLeftCell" $ do
it "the lower-left cell of a left-most cell is always dead" $ do
lowerLeftCell 0 0 [[1,0,0],[0,0,0],[0,0,0]] `shouldBe` 0
it "the lower-left cell of a left-most cell is always dead" $ do
lowerLeftCell 1 0 [[0,0,0],[1,0,0],[0,0,0]] `shouldBe` 0
it "the lower-left cell of a left-most cell is always dead" $ do
lowerLeftCell 2 0 [[0,0,0],[0,0,0],[1,0,0]] `shouldBe` 0
it "has a living neighbour" $ do
lowerLeftCell 0 1 [[0,1,0],[1,0,0],[0,0,0]] `shouldBe` 1
it "has a living neighbour" $ do
lowerLeftCell 0 2 [[0,0,1],[0,1,0],[0,0,0]] `shouldBe` 1
it "has a living neighbour" $ do
lowerLeftCell 1 1 [[0,0,0],[0,1,0],[1,0,0]] `shouldBe` 1
it "has a living neighbour" $ do
lowerLeftCell 1 2 [[0,0,0],[0,0,1],[0,1,0]] `shouldBe` 1
describe "neighboursOfCell" $ do
it "a cell with two neighbours (left, right)" $ do
neighboursOfCell 0 1 [[1,1,1],[0,0,0],[0,0,0]] `shouldBe` 2
it "a cell with two neighbours (up, down)" $ do
neighboursOfCell 1 1 [[0,1,0],[0,1,0],[0,1,0]] `shouldBe` 2
it "a cell with eight neighbours (all directions)" $ do
neighboursOfCell 1 1 [[1,1,1],[1,1,1],[1,1,1]] `shouldBe` 8
it "left corner cell with three neighbours" $ do
neighboursOfCell 0 0 [[1,1,0],[1,1,0],[0,0,0]] `shouldBe` 3
it "left corner cell with three neighbours" $ do
neighboursOfCell 2 0 [[0,0,0],[1,1,0],[1,1,0]] `shouldBe` 3
it "right corner cell with three neighbours" $ do
neighboursOfCell 0 2 [[0,1,1],[0,1,1],[0,0,0]] `shouldBe` 3
it "right corner cell with three neighbours" $ do
neighboursOfCell 2 2 [[0,0,0],[0,1,1],[0,1,1]] `shouldBe` 3
describe "zipBoardWithIndices" $ do
it "add indices" $ do
zipBoardWithIndices 0 0 [[0,0,0],[0,0,0],[0,0,0]] `shouldBe` [[(0,0,0),(0,1,0),(0,2,0)],
[(1,0,0),(1,1,0),(1,2,0)],
[(2,0,0),(2,1,0),(2,2,0)]]
describe "zipRowWithIndices" $ do
it "add indices" $ do
zipRowWithIndices 1 0 [0,0,0] `shouldBe` [(1,0,0), (1,1,0), (1,2,0)]
describe "neighbours" $ do
it "no living cells -> no neighbours" $ do
neighbours [[0,0,0],[0,0,0],[0,0,0]] `shouldBe` [[0,0,0],[0,0,0],[0,0,0]]
it "neighbours in a row" $ do
neighbours [[1,1,1],[0,0,0],[0,0,0]] `shouldBe` [[1,2,1],[2,3,2],[0,0,0]]
it "neighbours in a col" $ do
neighbours [[0,1,0],[0,1,0],[0,1,0]] `shouldBe` [[2,1,2],[3,2,3],[2,1,2]]
describe "nextGeneration" $ do
it "no living cells -> no living cells" $ do
nextGeneration [[0,0,0],[0,0,0],[0,0,0]] `shouldBe` [[0,0,0],[0,0,0],[0,0,0]]
describe "notInBounds" $ do
it "col too small" $ do
notInBounds 0 (-1) [[0,0,0],[0,0,0],[0,0,0]] `shouldBe` True
it "row too small" $ do
notInBounds (-1) 0 [[0,0,0],[0,0,0],[0,0,0]] `shouldBe` True
it "col and row too small" $ do
notInBounds (-1) (-1) [[0,0,0],[0,0,0],[0,0,0]] `shouldBe` True
it "col too big" $ do
notInBounds 0 3 [[0,0,0],[0,0,0],[0,0,0]] `shouldBe` True
it "row too big" $ do
notInBounds 3 0 [[0,0,0],[0,0,0],[0,0,0]] `shouldBe` True
it "col and row too big" $ do
notInBounds 3 3 [[0,0,0],[0,0,0],[0,0,0]] `shouldBe` True
|
supersven/game-of-life
|
test/NeighboursSpec.hs
|
Haskell
|
bsd-2-clause
| 10,080
|
{-# LANGUAGE DeriveGeneric, FlexibleContexts #-}
-- | The following module is responsible for general types used
-- throughout the system.
module Torrent (
-- * Types
InfoHash
, PeerId
, AnnounceURL
, TorrentState(..)
, TorrentInfo(..)
, PieceNum
, PieceSize
, PieceMap
, PiecesDoneMap
, PieceInfo(..)
, BlockSize
, Block(..)
, Capabilities(..)
-- * Interface
, bytesLeft
, defaultBlockSize
, defaultOptimisticSlots
, defaultPort
, mkPeerId
, mkTorrentInfo
)
where
import Control.Applicative
import Control.DeepSeq
import Data.Array
import Data.List
import Data.Maybe (fromMaybe)
import qualified Data.ByteString as B
import qualified Data.Map as M
import Data.Word
import GHC.Generics
import Numeric
import System.Random
import System.Random.Shuffle
import Test.QuickCheck
import Protocol.BCode
import Digest
import Version
-- | The type of Infohashes as used in torrents. These are identifiers
-- of torrents
type InfoHash = Digest
-- | The peerId is the ID of a client. It is used to identify clients
-- from each other
type PeerId = String
-- | The internal type of Announce URLs
type AnnounceURL = B.ByteString
-- | Internal type for a torrent. It identifies a torrent in various places of the system.
data TorrentInfo = TorrentInfo {
infoHash :: InfoHash,
pieceCount :: Int, -- Number of pieces in torrent
announceURLs :: [[AnnounceURL]]
} deriving Show
data TorrentState = Seeding | Leeching
deriving (Show, Generic)
instance NFData TorrentState
----------------------------------------------------------------------
-- Capabilities
data Capabilities = Fast | Extended
deriving (Show, Eq)
-- PIECES
----------------------------------------------------------------------
type PieceNum = Int
type PieceSize = Int
data PieceInfo = PieceInfo {
offset :: !Integer, -- ^ Offset of the piece, might be greater than Int
len :: !Integer, -- ^ Length of piece; usually a small value
digest :: !B.ByteString -- ^ Digest of piece; taken from the .torret file
} deriving (Eq, Show)
type PieceMap = Array PieceNum PieceInfo
-- | The PiecesDoneMap is a map which is true if we have the piece and false otherwise
type PiecesDoneMap = M.Map PieceNum Bool
-- | Return the amount of bytes left on a torrent given what pieces are done and the
-- map of the shape of the torrent in question.
bytesLeft :: PiecesDoneMap -> PieceMap -> Integer
bytesLeft done pm =
foldl' (\accu (k,v) ->
case M.lookup k done of
Just False -> (len v) + accu
_ -> accu) 0 $ Data.Array.assocs pm
-- BLOCKS
----------------------------------------------------------------------
type BlockSize = Int
data Block = Block { blockOffset :: !Int -- ^ offset of this block within the piece
, blockSize :: !BlockSize -- ^ size of this block within the piece
} deriving (Eq, Ord, Show)
instance NFData Block where
rnf (Block bo sz) = rnf bo `seq` rnf sz `seq` ()
instance Arbitrary Block where
arbitrary = Block <$> pos <*> pos
where pos = choose (0, 4294967296 - 1)
defaultBlockSize :: BlockSize
defaultBlockSize = 16384 -- Bytes
-- | Default number of optimistic slots
defaultOptimisticSlots :: Int
defaultOptimisticSlots = 2
-- | Default port to communicate on
defaultPort :: Word16
defaultPort = 1579
-- | Convert a BCode block into its corresponding TorrentInfo block, perhaps
-- failing in the process.
mkTorrentInfo :: BCode -> IO TorrentInfo
mkTorrentInfo bc = do
(ann, np) <- case queryInfo bc of Nothing -> fail "Could not create torrent info"
Just x -> return x
ih <- hashInfoDict bc
let alist = fromMaybe [[ann]] $ announceList bc
-- BEP012 says that lists of URL inside each tier must be shuffled
gen <- newStdGen
let alist' = map (\xs -> shuffle' xs (length xs) gen) alist
return TorrentInfo { infoHash = ih, pieceCount = np, announceURLs = alist'}
where
queryInfo b =
do ann <- announce b
np <- numberPieces b
return (ann, np)
-- | Create a new PeerId for this client
mkPeerId :: StdGen -> PeerId
mkPeerId gen = header ++ take (20 - length header) ranString
where randomList :: Int -> StdGen -> [Int]
randomList n = take n . unfoldr (Just . random)
rs = randomList 10 gen
ranString = concatMap (\i -> showHex (abs i) "") rs
header = "-CT" ++ protoVersion ++ "-"
|
abhin4v/combinatorrent
|
src/Torrent.hs
|
Haskell
|
bsd-2-clause
| 4,565
|
{-# LANGUAGE PatternSynonyms #-}
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.GL.APPLE.TextureRange
-- Copyright : (c) Sven Panne 2019
-- License : BSD3
--
-- Maintainer : Sven Panne <svenpanne@gmail.com>
-- Stability : stable
-- Portability : portable
--
--------------------------------------------------------------------------------
module Graphics.GL.APPLE.TextureRange (
-- * Extension Support
glGetAPPLETextureRange,
gl_APPLE_texture_range,
-- * Enums
pattern GL_STORAGE_CACHED_APPLE,
pattern GL_STORAGE_PRIVATE_APPLE,
pattern GL_STORAGE_SHARED_APPLE,
pattern GL_TEXTURE_RANGE_LENGTH_APPLE,
pattern GL_TEXTURE_RANGE_POINTER_APPLE,
pattern GL_TEXTURE_STORAGE_HINT_APPLE,
-- * Functions
glGetTexParameterPointervAPPLE,
glTextureRangeAPPLE
) where
import Graphics.GL.ExtensionPredicates
import Graphics.GL.Tokens
import Graphics.GL.Functions
|
haskell-opengl/OpenGLRaw
|
src/Graphics/GL/APPLE/TextureRange.hs
|
Haskell
|
bsd-3-clause
| 956
|
import Data.Binary (decode)
import Data.Binary.Put (putWord16host, runPut)
import Data.Word (Word8)
littleEndian :: Bool
littleEndian = (decode . runPut $ putWord16host 42 :: Word8) == 42
main :: IO ()
main | littleEndian = putStrLn "LittleEndian"
| otherwise = putStrLn "BigEndian"
|
nikai3d/ce-challenges
|
moderate/endian.hs
|
Haskell
|
bsd-3-clause
| 293
|
module Monad.Free where
import qualified Prelude as P
import Data.Constraint
import Data.Proxy
import Data.Tagged
import Category
import Functor
import Coproduct
import Monad
import NatTr
import NatTr.Coproduct
data Free f a where
Free :: FMap f (Free f a) -> Free f a
Pure :: EndoFunctorOf f (->) => a -> Free f a
freeT :: EndoFunctorOf f (->) => NatTr (->) (->) (f :.: Ftag (Free f)) (Ftag (Free f))
freeT = NatTr (Tagged Free)
pureT :: EndoFunctorOf f (->) => NatTr (->) (->) Id (Ftag (Free f))
pureT = NatTr (Tagged Pure)
unfreeT :: forall f. EndoFunctorOf f (->) => NatTr (->) (->) (Ftag (Free f)) ((f :.: Ftag (Free f)) :+: Id)
unfreeT = NatTr (Tagged t) where
t :: forall a. Free f a -> FMap ((f :.: Ftag (Free f)) :+: Id) a
t (Free f) = appNat inj1 f
t (Pure a) = appNat inj2 a
instance EndoFunctorOf f (->) => P.Functor (Free f) where
fmap t = go where
go (Free f) = Free (proxy morphMap (Proxy :: Proxy f) go f)
go (Pure a) = Pure (t a)
instance EndoFunctorOf f (->) => P.Monad (Free f) where
f >>= t = go f where
go (Free x) = Free (proxy morphMap (Proxy :: Proxy f) go x)
go (Pure a) = t a
return = Pure
data FreeM = FreeM
instance Functor FreeM ('KProxy :: KProxy (* -> *)) where
type Domain FreeM = NatTr (->) (->)
type Codomain FreeM = MonadMorph (->)
type FMap FreeM f = Ftag (Free f)
morphMap = Tagged (\t -> case observeObjects t of Dict -> f t) where
f t = MonadMorph go where
go = coproduct (freeT . compNat t go) pureT . unfreeT
|
ian-mi/extended-categories
|
Monad/Free.hs
|
Haskell
|
bsd-3-clause
| 1,560
|
{-# LANGUAGE NoMonomorphismRestriction #-}
module Main (main) where
import Test.QuickCheck
import Test.Framework (Test, defaultMain, testGroup)
import Test.Framework.Providers.QuickCheck2 (testProperty)
import Test.XBeeTestSupport
import Data.Word
import Data.ByteString (ByteString,pack,unpack)
import qualified Data.ByteString as BS
import Data.Serialize
import System.Hardware.XBee.Command
import Control.Monad
ser :: Serialize s => s -> [Word8]
ser = BS.unpack . runPut . put
serParseTest s = runGet get (runPut $ put s) == Right s
parse :: Serialize s => [Word8] -> Either String s
parse = runGet get . BS.pack
-- FrameId
frameIdLoopsAroundAfter255 = nextFrame (frameForId 255) == frameId
frameIdSerializeParse :: Word8 -> Bool
frameIdSerializeParse v = serParseTest (frameForId v)
frameIdParseWord8 w = runGet get (BS.singleton w) == Right (frameForId w)
-- Command name
commandNameSerializeParse a b = serParseTest (commandName a b)
commandNameExampleDH = parse [0x44, 0x48] == Right (commandName 'D' 'H')
-- Modem status
modemStatusSerialize =
ser HardwareReset == [0]
&& ser WatchdogTimerReset == [1]
&& ser Associated == [2]
&& ser Disassociated == [3]
&& ser SyncLost == [4]
&& ser CoordinatorRealignment == [5]
&& ser CoordinatorStarted == [6]
modemStatusSerializeParse :: ModemStatus -> Bool
modemStatusSerializeParse = serParseTest
-- Command status
commandStatusSerialize =
ser CmdOK == [0]
&& ser CmdError == [1]
&& ser CmdInvalidCommand == [2]
&& ser CmdInvalidParameter == [3]
commandStatusSerializeParse :: CommandStatus -> Bool
commandStatusSerializeParse = serParseTest
-- Address
address64SerializeParse :: Address64 -> Bool
address64SerializeParse = serParseTest
address16SerializeParse :: Address16 -> Bool
address16SerializeParse = serParseTest
-- Transmit status
transmitStatusSerialize =
ser TransmitSuccess == [0]
&& ser TransmitNoAck == [1]
&& ser TransmitCcaFailure == [2]
&& ser TransmitPurged == [3]
transmitStatusSerializeParse :: TransmitStatus -> Bool
transmitStatusSerializeParse = serParseTest
-- Signal Strength
signalStrengthSerializeParse :: SignalStrength -> Bool
signalStrengthSerializeParse = serParseTest
signalStrengthExample = parse [0x28] == Right (fromDbm (-40))
-- Command In
modemStatusUpdateSerializeParse s = serParseTest (ModemStatusUpdate s)
modemStatusUpdateParseExample = parse [0x8A, 0x01] == Right (ModemStatusUpdate WatchdogTimerReset)
atCommandResponseSerializeParse f cmd st val = serParseTest (ATCommandResponse f cmd st val)
atCommandResponseExample = parse [0x88, 0x52, 0x4D, 0x59, 0x00, 0x23, 0x12] ==
Right (ATCommandResponse (frameForId 0x52) (commandName 'M' 'Y') CmdOK $ pack [0x23, 0x12])
remoteAtCommandResponseSerializeParse f a64 a16 cmd st val = serParseTest $
RemoteATCommandResponse f a64 a16 cmd st val
remoteAtCommandResponseExample = parse [0x97, 0x52,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF,
0xFF, 0xFE,
0x4D, 0x59, 0x00, 0x23, 0x12] ==
Right (RemoteATCommandResponse (frameForId 0x52) broadcastAddress disabledAddress (commandName 'M' 'Y') CmdOK $ pack [0x23, 0x12])
transmitResponseSerializeParse f s = serParseTest (TransmitResponse f s)
transmitResponseExample = parse [0x89, 0x10, 0x00] ==
Right (TransmitResponse (frameForId 0x10) TransmitSuccess)
receive64SerializeParse from ss ack bc d = serParseTest $ Receive64 from ss ack bc d
receive64Example :: ByteString -> Bool
receive64Example d = parse ([0x80,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x28, 0x00] ++ unpack d) ==
Right (Receive64 (Address64 0x0102030405060708) (fromDbm (-40)) False False d)
receive16SerializeParse from ss ack bc d = serParseTest $ Receive16 from ss ack bc d
receive16Example :: ByteString -> Bool
receive16Example d = parse ([0x81,
0x01, 0x02,
0x28, 0x00] ++ unpack d) ==
Right (Receive16 (Address16 0x0102) (fromDbm (-40)) False False d)
-- Command Out
someData = pack [5..8]
atCommandSerializeParse f cmd d = serParseTest (ATCommand f cmd d)
atCommandExample = parse [0x08, 0x01, 0x44, 0x4C, 0x05, 0x06, 0x07, 0x08] ==
Right (ATCommand (frameForId 1) (commandName 'D' 'L') someData)
atQueueCommandSerializeParse f cmd d = serParseTest (ATQueueCommand f cmd d)
atQueueCommandExample = parse [0x09, 0x01, 0x44, 0x4C, 0x05, 0x06, 0x07, 0x08] ==
Right (ATQueueCommand (frameForId 1) (commandName 'D' 'L') someData)
remoteAtCommand64SerializeParse f adr b cmd d = serParseTest (RemoteATCommand64 f adr b cmd d)
remoteAtCommand64Example = parse [0x17, 0x01,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0xFF, 0xFE,
0x02,
0x44, 0x4C,
0x05, 0x06, 0x07, 0x08] ==
Right (RemoteATCommand64 (frameForId 1) (Address64 0x0102030405060708) True (commandName 'D' 'L') someData)
remoteAtCommand16SerializeParse f adr b cmd d = serParseTest (RemoteATCommand16 f adr b cmd d)
remoteAtCommand16Example = parse [0x17, 0x01,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF,
0x01, 0x02,
0x02,
0x44, 0x4C,
0x05, 0x06, 0x07, 0x08] ==
Right (RemoteATCommand16 (frameForId 1) (Address16 0x0102) True (commandName 'D' 'L') someData)
transmit64SerializeParse f adr da bc d = serParseTest (Transmit64 f adr da bc d)
transmit64Example = parse [0x00, 0x02,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x00,
0x09, 0x08, 0x07] ==
Right (Transmit64 (frameForId 2) (Address64 0x0102030405060708) False False $ pack [0x09, 0x08, 0x07])
transmit16SerializeParse f adr da bc d = serParseTest (Transmit16 f adr da bc d)
transmit16Example = parse [0x01, 0x03,
0x01, 0x02,
0x00,
0x09, 0x08, 0x07] ==
Right (Transmit16 (frameForId 3) (Address16 0x0102) False False $ pack [0x09, 0x08, 0x07])
--Main
main = defaultMain tests
tests :: [Test]
tests = [
testGroup "FrameId" [
testProperty "loops around after 255" frameIdLoopsAroundAfter255,
testProperty "serialize and parse yield original value" frameIdSerializeParse,
testProperty "can parse single Word8" frameIdParseWord8
],
testGroup "ModemStatus" [
testProperty "values are correctly serialized" modemStatusSerialize,
testProperty "serialize and then parse yields original value" modemStatusSerializeParse
],
testGroup "CommandName" [
testProperty "serialize and then parse yields original value" commandNameSerializeParse,
testProperty "value DH is parsed correctly" commandNameExampleDH
],
testGroup "CommandStatus" [
testProperty "values are correctly serialized" commandStatusSerialize,
testProperty "serialize and then parse yields original value" commandStatusSerializeParse
],
testGroup "SignalStrength" [
testProperty "serialize and then parse yields original value" signalStrengthSerializeParse,
testProperty "value -40 (=0x28) is parsed correctly" signalStrengthExample
],
testGroup "TransmitStatus" [
testProperty "values are correctly serialized" transmitStatusSerialize,
testProperty "serialize and then parse yields original value" transmitStatusSerializeParse
],
testGroup "Address64" [
testProperty "serialize and then parse yields original value" address64SerializeParse
],
testGroup "Address16" [
testProperty "serialize and then parse yields original value" address16SerializeParse
],
testGroup "CommandIn" [
testProperty "ModemStatusUpdate serialize & parse yields original" modemStatusUpdateSerializeParse,
testProperty "ModemStatusUpdate example works" modemStatusUpdateParseExample,
testProperty "ATCommandResponse serialize & parse yields original" atCommandResponseSerializeParse,
testProperty "ATCommandResponse example works" atCommandResponseExample,
testProperty "RemoteATCommandResponse serialize & parse yields original" remoteAtCommandResponseSerializeParse,
testProperty "RemoteATCommandResponse example works" remoteAtCommandResponseExample,
testProperty "TransmitResponse serialize & parse yields original" transmitResponseSerializeParse,
testProperty "TransmitResponse example works" transmitResponseExample,
testProperty "Receive64 serialize & parse yields original" receive64SerializeParse,
testProperty "Receive64 example works" receive64Example,
testProperty "Receive16 serialize & parse yields original" receive16SerializeParse,
testProperty "Receive16 example works" receive16Example
],
testGroup "CommandOut" [
testProperty "ATCommand serialize & parse yields original" atCommandSerializeParse,
testProperty "ATCommand example works" atCommandExample,
testProperty "ATQueueCommand serialize & parse yields original" atQueueCommandSerializeParse,
testProperty "ATQueueCommand example works" atQueueCommandExample,
testProperty "RemoteATCommand64 serialize & parse yields original" remoteAtCommand64SerializeParse,
testProperty "RemoteATCommand64 example works" remoteAtCommand64Example,
testProperty "RemoteATCommand16 serialize & parse yields original" remoteAtCommand16SerializeParse,
testProperty "RemoteATCommand16 example works" remoteAtCommand16Example,
testProperty "Transmit64 serialize & parse yields original" transmit64SerializeParse,
testProperty "Transmit64 example works" transmit64Example,
testProperty "Transmit16 serialize & parse yields original" transmit16SerializeParse,
testProperty "Transmit16 example works" transmit16Example
]]
|
msiegenthaler/haskell-xbee
|
test/CommandTest.hs
|
Haskell
|
bsd-3-clause
| 9,904
|
-- Shake Generator for wiki pages
{-# LANGUAGE CPP #-}
module Main where
import Prelude hiding ((*>))
import Control.Concurrent
import Data.Char
import qualified Data.List as L
import Development.Shake hiding (doesFileExist)
import qualified Development.Shake as Shake
import Development.Shake.FilePath
import System.Directory
import System.IO
import System.Process
import Web.Browser
-- TO test: ghci wiki-suite/Draw_Canvas.hs -idist/build/autogen/:.:wiki-suite
import qualified Arc
import qualified Bezier_Curve
import qualified Bounce
import qualified Circle
import qualified Clipping_Region
import qualified Color_Fill
import qualified Color_Square
import qualified Custom_Shape
import qualified Custom_Transform
import qualified Draw_Canvas
import qualified Draw_Device
import qualified Draw_Image
import qualified Favicon
import qualified Font_Size_and_Style
import qualified Get_Image_Data_URL
import qualified Global_Alpha
import qualified Global_Composite_Operations
import qualified Grayscale
import qualified Image_Crop
import qualified Image_Loader
import qualified Image_Size
import qualified Is_Point_In_Path
import qualified Key_Read
import qualified Line
import qualified Line_Cap
import qualified Line_Color
import qualified Line_Join
import qualified Line_Width
import qualified Linear_Gradient
import qualified Load_Image_Data_URL
import qualified Load_Image_Data_URL_2
import qualified Miter_Limit
import qualified Path
import qualified Pattern
import qualified Quadratic_Curve
import qualified Radial_Gradient
import qualified Rectangle
import qualified Red_Line
import qualified Rotate_Transform
import qualified Rotating_Square
import qualified Rounded_Corners
import qualified Scale_Transform
import qualified Semicircle
import qualified Shadow
import qualified Square
import qualified Text_Align
import qualified Text_Baseline
import qualified Text_Color
import qualified Text_Metrics
import qualified Text_Stroke
import qualified Text_Wrap
import qualified Tic_Tac_Toe
import qualified Translate_Transform
import System.Environment
main :: IO ()
main = do
args <- getArgs
main2 args
main2 :: [String] -> IO ()
main2 ["Arc"] = Arc.main
main2 ["Bezier_Curve"] = Bezier_Curve.main
main2 ["Bounce"] = Bounce.main
main2 ["Circle"] = Circle.main
main2 ["Clipping_Region"] = Clipping_Region.main
main2 ["Color_Fill"] = Color_Fill.main
main2 ["Color_Square"] = Color_Square.main
main2 ["Custom_Shape"] = Custom_Shape.main
main2 ["Draw_Canvas"] = Draw_Canvas.main
main2 ["Draw_Device"] = Draw_Device.main
main2 ["Draw_Image"] = Draw_Image.main
main2 ["Favicon"] = Favicon.main
main2 ["Font_Size_and_Style"] = Font_Size_and_Style.main
main2 ["Get_Image_Data_URL"] = Get_Image_Data_URL.main
main2 ["Global_Alpha"] = Global_Alpha.main
main2 ["Global_Composite_Operations"] = Global_Composite_Operations.main
main2 ["Grayscale"] = Grayscale.main
main2 ["Image_Crop"] = Image_Crop.main
main2 ["Image_Loader"] = Image_Loader.main
main2 ["Miter_Limit"] = Miter_Limit.main
main2 ["Image_Size"] = Image_Size.main
main2 ["Is_Point_In_Path"] = Is_Point_In_Path.main
main2 ["Key_Read"] = Key_Read.main
main2 ["Line"] = Line.main
main2 ["Line_Cap"] = Line_Cap.main
main2 ["Line_Color"] = Line_Color.main
main2 ["Line_Join"] = Line_Join.main
main2 ["Line_Width"] = Line_Width.main
main2 ["Linear_Gradient"] = Linear_Gradient.main
main2 ["Load_Image_Data_URL"] = Load_Image_Data_URL.main
main2 ["Load_Image_Data_URL_2"] = Load_Image_Data_URL_2.main
main2 ["Path"] = Path.main
main2 ["Pattern"] = Pattern.main
main2 ["Quadratic_Curve"] = Quadratic_Curve.main
main2 ["Radial_Gradient"] = Radial_Gradient.main
main2 ["Rectangle"] = Rectangle.main
main2 ["Red_Line"] = Red_Line.main
main2 ["Rotating_Square"] = Rotating_Square.main
main2 ["Rounded_Corners"] = Rounded_Corners.main
main2 ["Semicircle"] = Semicircle.main
main2 ["Shadow"] = Shadow.main
main2 ["Square"] = Square.main
main2 ["Text_Align"] = Text_Align.main
main2 ["Text_Baseline"] = Text_Baseline.main
main2 ["Text_Color"] = Text_Color.main
main2 ["Text_Metrics"] = Text_Metrics.main
main2 ["Text_Stroke"] = Text_Stroke.main
main2 ["Text_Wrap"] = Text_Wrap.main
main2 ["Tic_Tac_Toe"] = Tic_Tac_Toe.main
main2 ["Translate_Transform"] = Translate_Transform.main
main2 ["Scale_Transform"] = Scale_Transform.main
main2 ["Rotate_Transform"] = Rotate_Transform.main
main2 ["Custom_Transform"] = Custom_Transform.main
main2 ["clean"] = do
_ <- createProcess $ shell "rm blank-canvas.wiki/images/*.png blank-canvas.wiki/images/*.gif blank-canvas.wiki/examples/*.hs"
return ()
main2 args = shakeArgs shakeOptions $ do
if null args then do
want ["blank-canvas.wiki/images/" ++ nm ++ ".gif" | nm <- movies ]
want ["blank-canvas.wiki/images/" ++ nm ++ ".png" | nm <- examples ++ tutorial]
want ["blank-canvas.wiki/examples/" ++ nm ++ ".hs" | nm <- movies ++ examples ++ tutorial]
want ["blank-canvas.wiki/" ++ toMinus nm ++ ".md" | nm <- movies ++ examples ++ tutorial]
else return ()
["blank-canvas.wiki/images/*.png", "blank-canvas.wiki/images/*.gif"] |%> \out -> do
let nm = takeBaseName out
liftIO $ print (out,nm)
liftIO $ removeFiles ("blank-canvas.wiki/tmp") ["*.png"]
need [ "blank-canvas.wiki/" ++ toMinus nm ++ ".md" ]
let haskell_file = nm ++ ".hs"
let haskell_path = wiki_suite ++ "/" ++ haskell_file
need [ haskell_path, "blank-canvas.wiki/examples/" ++ haskell_file ]
liftIO $ print nm
txt <- Shake.readFile' $ haskell_path
let (w,h) = head $
[ case words ln of
[_,_,_,n] -> read n
_ -> (512,384)
| ln <- lines txt
, "import" `L.isPrefixOf` ln && "Wiki" `L.isInfixOf` ln
] ++ [(512,384) :: (Int, Int)]
sequence_ [
do (_,_,_,ghc) <- liftIO $
createProcess (proc "stack" ["exec","wiki-suite",nm])
-- wait a second, for things to start
liftIO $ threadDelay (1 * 1000 * 1000)
_ <-liftIO $ openBrowser $ "http://localhost:3000/?height=" ++ show (h) ++ "&width=" ++ show (w) ++ hd
-- wait for haskell program to stop
liftIO $ waitForProcess ghc | hd <- [("")] ++ if nm == "Text_Wrap" then [("&hd")] else [] ]
return ()
"blank-canvas.wiki/examples/*.hs" %> \ out -> do
liftIO $ print "*hs"
liftIO $ print out
let haskell_file = takeFileName out
liftIO $ print "before read file"
txt <- Shake.readFile' $ wiki_suite ++ "/" ++ haskell_file
liftIO $ print "after read file"
let new = reverse
$ dropWhile (all isSpace)
$ reverse
[ if "module" `L.isPrefixOf` ln
then "module Main where"
else ln
| ln <- lines txt
, not ("wiki $" `L.isInfixOf` ln) -- remove the wiki stuff
, not ("import" `L.isPrefixOf` ln && "Wiki" `L.isInfixOf` ln)
]
writeFileChanged out (unlines $ map (untabify 0) new)
"blank-canvas.wiki/*.md" %> \ out -> do
b <- Shake.doesFileExist out
-- liftIO $ print b
txts <- liftIO $ if b then do
h <- openFile out ReadMode
let loop = do
b' <- hIsEOF h
if b'
then return []
else do
ln <- hGetLine h
lns <- loop
return (ln : lns)
txts <- loop
hClose h
return txts
else return []
-- liftIO $ print txts
let p = not . (code_header `L.isPrefixOf`)
let textToKeep = takeWhile p txts
let haskell_file = map (\ c -> if c == '-' then '_' else c)
$ replaceExtension (takeFileName out) ".hs"
liftIO $ print haskell_file
txt <- Shake.readFile' $ "blank-canvas.wiki/examples/" ++ haskell_file
let new = unlines $
[ t | t <- textToKeep
] ++
[code_header] ++
lines txt ++
[code_footer]
-- liftIO $ putStrLn new
writeFileChanged out new
-- to clean: rm images/*png images/*gif examples/*hs
-- */
movies :: [String]
movies = ["Rotating_Square","Tic_Tac_Toe","Bounce","Key_Read","Square"]
examples :: [String]
examples = ["Red_Line","Favicon"]
++ ["Color_Square"]
tutorial :: [String]
tutorial = ["Line", "Line_Width", "Line_Color", "Line_Cap","Miter_Limit"]
++ ["Arc","Quadratic_Curve","Bezier_Curve"]
++ ["Path","Line_Join","Rounded_Corners","Is_Point_In_Path"]
++ ["Custom_Shape","Rectangle","Circle","Semicircle"]
++ ["Color_Fill","Linear_Gradient","Radial_Gradient","Pattern"]
++ ["Draw_Image","Image_Size","Image_Crop","Image_Loader", "Draw_Canvas", "Draw_Device"]
++ ["Font_Size_and_Style","Text_Color","Text_Stroke","Text_Align","Text_Baseline","Text_Metrics","Text_Wrap"]
++ ["Translate_Transform","Scale_Transform","Rotate_Transform","Custom_Transform"]
++ ["Shadow","Global_Alpha","Clipping_Region","Global_Composite_Operations"]
++ ["Grayscale","Get_Image_Data_URL","Load_Image_Data_URL"]
++ ["Load_Image_Data_URL_2"]
wiki_dir :: String
wiki_dir = "."
toMinus :: String -> String
toMinus = map (\ c -> if c == '_' then '-' else c)
untabify :: Int -> String -> String
untabify _ [] = []
untabify n (c:cs) | c == '\t' = let t = 8 - n `mod` 8 in take t (cycle " ") ++ untabify (n + t) cs
| otherwise = c : untabify (n + 1) cs
code_header :: String
code_header = "````Haskell"
code_footer :: String
code_footer = "````"
wiki_suite :: String
wiki_suite = "wiki-suite"
|
ku-fpg/blank-canvas
|
wiki-suite/Main.hs
|
Haskell
|
bsd-3-clause
| 10,241
|
-- Copyright 2019 Google LLC
--
-- Use of this source code is governed by a BSD-style
-- license that can be found in the LICENSE file or at
-- https://developers.google.com/open-source/licenses/bsd
{-# LANGUAGE CPP #-}
module GHC.SourceGen.Type.Internal where
import GHC.Hs (GhcPs)
#if MIN_VERSION_ghc(9,0,0)
import GHC.Hs.Type as Types
import GHC.Types.SrcLoc (unLoc)
#else
import GHC.Hs.Type as Types
import SrcLoc (unLoc)
#endif
import GHC.SourceGen.Syntax.Internal
mkQTyVars :: [HsTyVarBndr'] -> LHsQTyVars'
mkQTyVars vars = withPlaceHolder
$ noExt (withPlaceHolder HsQTvs)
$ map mkLocated vars
sigType :: HsType' -> LHsSigType'
#if MIN_VERSION_ghc(9,2,0)
sigType = mkLocated . noExt HsSig (noExt HsOuterImplicit) . mkLocated
#else
sigType = withPlaceHolder . noExt (withPlaceHolder Types.HsIB) . builtLoc
#endif
-- TODO: GHC >= 8.6 provides parenthesizeHsType. For consistency with
-- older versions, we're implementing our own parenthesis-wrapping.
-- Once we stop supporting GHC-8.4, we can switch to that implementation.
parenthesizeTypeForApp, parenthesizeTypeForOp, parenthesizeTypeForFun
:: LHsType GhcPs -> LHsType GhcPs
parenthesizeTypeForApp t
| needsParenForApp (unLoc t) = parTy t
| otherwise = t
parenthesizeTypeForOp t
| needsParenForOp (unLoc t) = parTy t
| otherwise = t
parenthesizeTypeForFun t
| needsParenForFun (unLoc t) = parTy t
| otherwise = t
needsParenForFun, needsParenForOp, needsParenForApp
:: HsType' -> Bool
needsParenForFun t = case t of
HsForAllTy{} -> True
HsQualTy{} -> True
HsFunTy{} -> True
_ -> False
needsParenForOp t = case t of
HsOpTy{} -> True
_ -> needsParenForFun t
needsParenForApp t = case t of
HsAppTy {} -> True
_ -> needsParenForOp t
parTy :: LHsType GhcPs -> LHsType GhcPs
parTy = mkLocated . withEpAnnNotUsed HsParTy
sigWcType :: HsType' -> LHsSigWcType'
sigWcType = noExt (withPlaceHolder Types.HsWC) . sigType
wcType :: HsType' -> LHsWcType'
wcType = noExt (withPlaceHolder Types.HsWC) . mkLocated
patSigType :: HsType' -> HsPatSigType'
#if MIN_VERSION_ghc(9,2,0)
patSigType = withEpAnnNotUsed mkHsPatSigType . mkLocated
#elif MIN_VERSION_ghc(9,0,0)
patSigType = mkHsPatSigType . builtLoc
#else
patSigType = sigWcType
#endif
|
google/ghc-source-gen
|
src/GHC/SourceGen/Type/Internal.hs
|
Haskell
|
bsd-3-clause
| 2,294
|
module Language.Haskell.GhcMod.Boot where
import Control.Applicative ((<$>))
import CoreMonad (liftIO, liftIO)
import Language.Haskell.GhcMod.Browse
import Language.Haskell.GhcMod.Flag
import Language.Haskell.GhcMod.Lang
import Language.Haskell.GhcMod.List
import Language.Haskell.GhcMod.Monad
import Language.Haskell.GhcMod.Types
-- | Printing necessary information for front-end booting.
bootInfo :: Options -> IO String
bootInfo opt = runGhcMod opt $ boot
-- | Printing necessary information for front-end booting.
boot :: GhcMod String
boot = do
opt <- options
mods <- modules
langs <- liftIO $ listLanguages opt
flags <- liftIO $ listFlags opt
pre <- concat <$> mapM browse preBrowsedModules
return $ mods ++ langs ++ flags ++ pre
preBrowsedModules :: [String]
preBrowsedModules = [
"Prelude"
, "Control.Applicative"
, "Control.Exception"
, "Control.Monad"
, "Data.Char"
, "Data.List"
, "Data.Maybe"
, "System.IO"
]
|
darthdeus/ghc-mod-ng
|
Language/Haskell/GhcMod/Boot.hs
|
Haskell
|
bsd-3-clause
| 974
|
{-# LANGUAGE TypeFamilies, TypeOperators #-}
-------------------------------------------------------------------------------------------
-- |
-- Module : Control.Category.Object
-- Copyright: 2010-2012 Edward Kmett
-- License : BSD
--
-- Maintainer : Edward Kmett <ekmett@gmail.com>
-- Stability : experimental
-- Portability: non-portable (either class-associated types or MPTCs with fundeps)
--
-- This module declares the 'HasTerminalObject' and 'HasInitialObject' classes.
--
-- These are both special cases of the idea of a (co)limit.
-------------------------------------------------------------------------------------------
module Control.Categorical.Object
( HasTerminalObject(..)
, HasInitialObject(..)
) where
import Control.Category
-- | The @Category (~>)@ has a terminal object @Terminal (~>)@ such that for all objects @a@ in @(~>)@,
-- there exists a unique morphism from @a@ to @Terminal (~>)@.
class Category k => HasTerminalObject k where
type Terminal k :: *
terminate :: a `k` Terminal k
-- | The @Category (~>)@ has an initial (coterminal) object @Initial (~>)@ such that for all objects
-- @a@ in @(~>)@, there exists a unique morphism from @Initial (~>) @ to @a@.
class Category k => HasInitialObject k where
type Initial k :: *
initiate :: Initial k `k` a
|
ekmett/categories
|
old/src/Control/Categorical/Object.hs
|
Haskell
|
bsd-3-clause
| 1,318
|
import Test.Cabal.Prelude
main = cabalTest $ do
expectBroken 4477 $ do
cabal' "new-run" ["foo"] >>= assertOutputContains "Hello World"
|
mydaum/cabal
|
cabal-testsuite/PackageTests/NewBuild/T4477/cabal.test.hs
|
Haskell
|
bsd-3-clause
| 147
|
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ImplicitParams #-}
module MLModules where
import Prelude hiding (Monoid)
-- We can represent a module dependencies with our fake modules!
-- This means submodules!
--
-- The only thing is I cannot have type associators be named the same thing
-- These type families are globally scoped.
class Semigroup m where
type T m
(<>) :: (?m :: m) => T m -> T m -> T m
-- | Monoid is a submodule of Semigroup
class Semigroup m => Monoid m where
type T' m
zero :: (?m :: m) => T' m
data Add = Add
instance Semigroup Add where
type T Add = Int
(<>) = (+)
instance Monoid Add where
type T' Add = Int
zero = 0
foo :: Int
foo = zero <> zero
where
?m = Add
|
sleexyz/haskell-fun
|
MLModulesSubmodule.hs
|
Haskell
|
bsd-3-clause
| 794
|
module PackageTests.Tests(tests) where
import PackageTests.PackageTester
import qualified PackageTests.BenchmarkStanza.Check
import qualified PackageTests.TestStanza.Check
import qualified PackageTests.DeterministicAr.Check
import qualified PackageTests.TestSuiteTests.ExeV10.Check
import Control.Monad
import Data.Version
import Test.Tasty (TestTree, testGroup, mkTimeout, localOption)
import Test.Tasty.HUnit (testCase)
-- TODO: turn this into a "test-defining writer monad".
-- This will let us handle scoping gracefully.
tests :: SuiteConfig -> [TestTree]
tests config =
tail [ undefined
---------------------------------------------------------------------
-- * External tests
-- Test that Cabal parses 'benchmark' sections correctly
, tc "BenchmarkStanza" PackageTests.BenchmarkStanza.Check.suite
-- Test that Cabal parses 'test' sections correctly
, tc "TestStanza" PackageTests.TestStanza.Check.suite
-- Test that Cabal determinstically generates object archives
, tc "DeterministicAr" PackageTests.DeterministicAr.Check.suite
---------------------------------------------------------------------
-- * Test suite tests
, testGroup "TestSuiteTests"
-- Test exitcode-stdio-1.0 test suites (and HPC)
[ testGroup "ExeV10"
(PackageTests.TestSuiteTests.ExeV10.Check.tests config)
-- Test detailed-0.9 test suites
, testGroup "LibV09" $
let
tcs :: FilePath -> TestM a -> TestTree
tcs name m
= testCase name (runTestM config ("TestSuiteTests/LibV09")
(Just name) m)
in -- Test if detailed-0.9 builds correctly
[ tcs "Build" $ cabal_build ["--enable-tests"]
-- Tests for #2489, stdio deadlock
, localOption (mkTimeout $ 10 ^ (8 :: Int))
. tcs "Deadlock" $ do
cabal_build ["--enable-tests"]
shouldFail $ cabal "test" []
]
]
---------------------------------------------------------------------
-- * Inline tests
-- Test if exitcode-stdio-1.0 benchmark builds correctly
, tc "BenchmarkExeV10" $ cabal_build ["--enable-benchmarks"]
-- Test --benchmark-option(s) flags on ./Setup bench
, tc "BenchmarkOptions" $ do
cabal_build ["--enable-benchmarks"]
cabal "bench" [ "--benchmark-options=1 2 3" ]
cabal "bench" [ "--benchmark-option=1"
, "--benchmark-option=2"
, "--benchmark-option=3"
]
-- Test --test-option(s) flags on ./Setup test
, tc "TestOptions" $ do
cabal_build ["--enable-tests"]
cabal "test" ["--test-options=1 2 3"]
cabal "test" [ "--test-option=1"
, "--test-option=2"
, "--test-option=3"
]
-- Test attempt to have executable depend on internal
-- library, but cabal-version is too old.
, tc "BuildDeps/InternalLibrary0" $ do
r <- shouldFail $ cabal' "configure" []
-- Should tell you how to enable the desired behavior
let sb = "library which is defined within the same package."
assertOutputContains sb r
-- Test executable depends on internal library.
, tc "BuildDeps/InternalLibrary1" $ cabal_build []
-- Test that internal library is preferred to an installed on
-- with the same name and version
, tc "BuildDeps/InternalLibrary2" $ internal_lib_test "internal"
-- Test that internal library is preferred to an installed on
-- with the same name and LATER version
, tc "BuildDeps/InternalLibrary3" $ internal_lib_test "internal"
-- Test that an explicit dependency constraint which doesn't
-- match the internal library causes us to use external library
, tc "BuildDeps/InternalLibrary4" $ internal_lib_test "installed"
-- Test "old build-dep behavior", where we should get the
-- same package dependencies on all targets if cabal-version
-- is sufficiently old.
, tc "BuildDeps/SameDepsAllRound" $ cabal_build []
-- Test "new build-dep behavior", where each target gets
-- separate dependencies. This tests that an executable
-- dep does not leak into the library.
, tc "BuildDeps/TargetSpecificDeps1" $ do
cabal "configure" []
r <- shouldFail $ cabal' "build" []
assertBool "error should be in MyLibrary.hs" $
resultOutput r =~ "^MyLibrary.hs:"
assertBool "error should be \"Could not find module `Text\\.PrettyPrint\"" $
resultOutput r =~ "Could not find module.*Text\\.PrettyPrint"
-- This is a control on TargetSpecificDeps1; it should
-- succeed.
, tc "BuildDeps/TargetSpecificDeps2" $ cabal_build []
-- Test "new build-dep behavior", where each target gets
-- separate dependencies. This tests that an library
-- dep does not leak into the executable.
, tc "BuildDeps/TargetSpecificDeps3" $ do
cabal "configure" []
r <- shouldFail $ cabal' "build" []
assertBool "error should be in lemon.hs" $
resultOutput r =~ "^lemon.hs:"
assertBool "error should be \"Could not find module `Text\\.PrettyPrint\"" $
resultOutput r =~ "Could not find module.*Text\\.PrettyPrint"
-- Test that Paths module is generated and available for executables.
, tc "PathsModule/Executable" $ cabal_build []
-- Test that Paths module is generated and available for libraries.
, tc "PathsModule/Library" $ cabal_build []
-- Check that preprocessors (hsc2hs) are run
, tc "PreProcess" $ cabal_build ["--enable-tests", "--enable-benchmarks"]
-- Check that preprocessors that generate extra C sources are handled
, tc "PreProcessExtraSources" $ cabal_build ["--enable-tests", "--enable-benchmarks"]
-- Test building a vanilla library/executable which uses Template Haskell
, tc "TemplateHaskell/vanilla" $ cabal_build []
-- Test building a profiled library/executable which uses Template Haskell
-- (Cabal has to build the non-profiled version first)
, tc "TemplateHaskell/profiling" $ cabal_build ["--enable-library-profiling", "--enable-profiling"]
-- Test building a dynamic library/executable which uses Template
-- Haskell
, tc "TemplateHaskell/dynamic" $ cabal_build ["--enable-shared", "--enable-executable-dynamic"]
-- Test building an executable whose main() function is defined in a C
-- file
, tc "CMain" $ cabal_build []
-- Test build when the library is empty, for #1241
, tc "EmptyLib" $
withPackage "empty" $ cabal_build []
-- Test that "./Setup haddock" works correctly
, tc "Haddock" $ do
dist_dir <- distDir
let haddocksDir = dist_dir </> "doc" </> "html" </> "Haddock"
cabal "configure" []
cabal "haddock" []
let docFiles
= map (haddocksDir </>)
["CPP.html", "Literate.html", "NoCPP.html", "Simple.html"]
mapM_ (assertFindInFile "For hiding needles.") docFiles
-- Test that Haddock with a newline in synopsis works correctly, #3004
, tc "HaddockNewline" $ do
cabal "configure" []
cabal "haddock" []
-- Test that Cabal properly orders GHC flags passed to GHC (when
-- there are multiple ghc-options fields.)
, tc "OrderFlags" $ cabal_build []
-- Test that reexported modules build correctly
-- TODO: should also test that they import OK!
, tc "ReexportedModules" $ do
whenGhcVersion (>= Version [7,9] []) $ cabal_build []
-- Test that Cabal computes different IPIDs when the source changes.
, tc "UniqueIPID" . withPackageDb $ do
withPackage "P1" $ cabal "configure" []
withPackage "P2" $ cabal "configure" []
withPackage "P1" $ cabal "build" []
withPackage "P1" $ cabal "build" [] -- rebuild should work
r1 <- withPackage "P1" $ cabal' "register" ["--print-ipid", "--inplace"]
withPackage "P2" $ cabal "build" []
r2 <- withPackage "P2" $ cabal' "register" ["--print-ipid", "--inplace"]
let exIPID s = takeWhile (/= '\n') $
head . filter (isPrefixOf $ "UniqueIPID-0.1-") $ (tails s)
when ((exIPID $ resultOutput r1) == (exIPID $ resultOutput r2)) $
assertFailure $ "cabal has not calculated different Installed " ++
"package ID when source is changed."
, tc "DuplicateModuleName" $ do
cabal_build ["--enable-tests"]
r1 <- shouldFail $ cabal' "test" ["foo"]
assertOutputContains "test B" r1
assertOutputContains "test A" r1
r2 <- shouldFail $ cabal' "test" ["foo2"]
assertOutputContains "test C" r2
assertOutputContains "test A" r2
, tc "TestNameCollision" $ do
withPackageDb $ do
withPackage "parent" $ cabal_install []
withPackage "child" $ do
cabal_build ["--enable-tests"]
cabal "test" []
-- Test that Cabal can choose flags to disable building a component when that
-- component's dependencies are unavailable. The build should succeed without
-- requiring the component's dependencies or imports.
, tc "BuildableField" $ do
r <- cabal' "configure" ["-v"]
assertOutputContains "Flags chosen: build-exe=False" r
cabal "build" []
]
where
-- Shared test function for BuildDeps/InternalLibrary* tests.
internal_lib_test expect = withPackageDb $ do
withPackage "to-install" $ cabal_install []
cabal_build []
r <- runExe' "lemon" []
assertEqual
("executable should have linked with the " ++ expect ++ " library")
("foofoomyLibFunc " ++ expect)
(concat $ lines (resultOutput r))
tc :: FilePath -> TestM a -> TestTree
tc name m
= testCase name (runTestM config name Nothing m)
|
lukexi/cabal
|
Cabal/tests/PackageTests/Tests.hs
|
Haskell
|
bsd-3-clause
| 9,655
|
-- |
-- Support for source code annotation feature of GHC. That is the ANN pragma.
--
-- (c) The University of Glasgow 2006
-- (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
--
module Annotations (
-- * Main Annotation data types
Annotation(..),
AnnTarget(..), CoreAnnTarget,
getAnnTargetName_maybe,
-- * AnnEnv for collecting and querying Annotations
AnnEnv,
mkAnnEnv, extendAnnEnvList, plusAnnEnv, emptyAnnEnv, findAnns,
deserializeAnns
) where
import Module ( Module )
import Name
import Outputable
import Serialized
import UniqFM
import Unique
import Data.Maybe
import Data.Typeable
import Data.Word ( Word8 )
-- | Represents an annotation after it has been sufficiently desugared from
-- it's initial form of 'HsDecls.AnnDecl'
data Annotation = Annotation {
ann_target :: CoreAnnTarget, -- ^ The target of the annotation
ann_value :: Serialized -- ^ 'Serialized' version of the annotation that
-- allows recovery of its value or can
-- be persisted to an interface file
}
-- | An annotation target
data AnnTarget name
= NamedTarget name -- ^ We are annotating something with a name:
-- a type or identifier
| ModuleTarget Module -- ^ We are annotating a particular module
-- | The kind of annotation target found in the middle end of the compiler
type CoreAnnTarget = AnnTarget Name
instance Functor AnnTarget where
fmap f (NamedTarget nm) = NamedTarget (f nm)
fmap _ (ModuleTarget mod) = ModuleTarget mod
-- | Get the 'name' of an annotation target if it exists.
getAnnTargetName_maybe :: AnnTarget name -> Maybe name
getAnnTargetName_maybe (NamedTarget nm) = Just nm
getAnnTargetName_maybe _ = Nothing
instance Uniquable name => Uniquable (AnnTarget name) where
getUnique (NamedTarget nm) = getUnique nm
getUnique (ModuleTarget mod) = deriveUnique (getUnique mod) 0
-- deriveUnique prevents OccName uniques clashing with NamedTarget
instance Outputable name => Outputable (AnnTarget name) where
ppr (NamedTarget nm) = text "Named target" <+> ppr nm
ppr (ModuleTarget mod) = text "Module target" <+> ppr mod
instance Outputable Annotation where
ppr ann = ppr (ann_target ann)
-- | A collection of annotations
-- Can't use a type synonym or we hit bug #2412 due to source import
newtype AnnEnv = MkAnnEnv (UniqFM [Serialized])
-- | An empty annotation environment.
emptyAnnEnv :: AnnEnv
emptyAnnEnv = MkAnnEnv emptyUFM
-- | Construct a new annotation environment that contains the list of
-- annotations provided.
mkAnnEnv :: [Annotation] -> AnnEnv
mkAnnEnv = extendAnnEnvList emptyAnnEnv
-- | Add the given annotation to the environment.
extendAnnEnvList :: AnnEnv -> [Annotation] -> AnnEnv
extendAnnEnvList (MkAnnEnv env) anns
= MkAnnEnv $ addListToUFM_C (++) env $
map (\ann -> (getUnique (ann_target ann), [ann_value ann])) anns
-- | Union two annotation environments.
plusAnnEnv :: AnnEnv -> AnnEnv -> AnnEnv
plusAnnEnv (MkAnnEnv env1) (MkAnnEnv env2) = MkAnnEnv $ plusUFM_C (++) env1 env2
-- | Find the annotations attached to the given target as 'Typeable'
-- values of your choice. If no deserializer is specified,
-- only transient annotations will be returned.
findAnns :: Typeable a => ([Word8] -> a) -> AnnEnv -> CoreAnnTarget -> [a]
findAnns deserialize (MkAnnEnv ann_env)
= (mapMaybe (fromSerialized deserialize))
. (lookupWithDefaultUFM ann_env [])
-- | Deserialize all annotations of a given type. This happens lazily, that is
-- no deserialization will take place until the [a] is actually demanded and
-- the [a] can also be empty (the UniqFM is not filtered).
deserializeAnns :: Typeable a => ([Word8] -> a) -> AnnEnv -> UniqFM [a]
deserializeAnns deserialize (MkAnnEnv ann_env)
= mapUFM (mapMaybe (fromSerialized deserialize)) ann_env
|
nomeata/ghc
|
compiler/main/Annotations.hs
|
Haskell
|
bsd-3-clause
| 4,023
|
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# OPTIONS -fno-warn-orphans #-}
module PropGenerators
( arbitraryPropWithVarsAndSize
, arbitraryPropWithVars
, boundShrinkProp
) where
import PropositionalPrelude
import Prop
import Test.QuickCheck (Arbitrary, arbitrary, shrink, Gen, oneof, elements,
choose, sized)
-- | Generate an arbitrary proposition.
arbitraryPropWithVarsAndSize
:: forall v.
[v] -- ^ the possible values to use for variables
-> Int -- ^ some natural number for the size of the generated term
-> Gen (Prop v)
arbitraryPropWithVarsAndSize [] = const $ elements [PFalse, PTrue]
arbitraryPropWithVarsAndSize vs = go
where
go :: Int -> Gen (Prop v)
go maxNodes
| maxNodes <= 1 = oneof terms
| maxNodes <= 2 = oneof (terms ++ [ PNot <$> go (maxNodes - 1)])
| maxNodes <= 3 = oneof (terms ++ [ PNot <$> go (maxNodes - 1)
, binary PXor, binary PXnor ])
| otherwise = oneof (terms ++ [ PNot <$> go (maxNodes - 1)
, binary PXor, binary PXnor
, binary PAnd, binary PNand
, binary POr, binary PNor
, ternary PIte ] )
where
terms :: [Gen (Prop v)]
terms = map return (PFalse : PTrue : map PVar vs)
binary cons = cons <$> go (maxNodes `div` 2) <*> go (maxNodes `div` 2)
ternary cons = cons <$> go (maxNodes `div` 3) <*> go (maxNodes `div` 3) <*> go (maxNodes `div` 3)
arbitraryPropWithVars :: [v] -> Gen (Prop v)
arbitraryPropWithVars = sized . arbitraryPropWithVarsAndSize
boundShrinkProp :: (Ord v, Arbitrary v) => Int -> Prop v -> [Prop v]
boundShrinkProp bound prop
| bound <= 0 = []
| otherwise =
case prop of
PFalse -> []
PTrue -> []
PVar i -> [ PVar i' | i' <- shrink i ] ++ [ PFalse, PTrue ]
PNot p -> p : boundShrinkProp bound' p ++
[ PNot p' | p' <- boundShrinkProp bound' p ] ++
[ PFalse, PTrue ]
PAnd p1 p2 -> bin PAnd p1 p2
PNand p1 p2 -> bin PNand p1 p2
POr p1 p2 -> bin POr p1 p2
PNor p1 p2 -> bin PNor p1 p2
PXor p1 p2 -> bin PXor p1 p2
PXnor p1 p2 -> bin PXnor p1 p2
PIte p1 p2 p3 -> PFalse : PTrue : p1 : p2 : p3 :
[ PIte p1' p2' p3' | p1' <- boundShrinkProp bound' p1
, p2' <- boundShrinkProp bound' p2
, p3' <- boundShrinkProp bound' p3
]
where
bound' = pred bound
bin op p1 p2 = [ op p1' p2' | p1' <- boundShrinkProp bound' p1
, p2' <- boundShrinkProp bound' p2 ] ++
[ op p1' p2 | p1' <- boundShrinkProp bound' p1 ] ++
[ op p1 p2' | p2' <- boundShrinkProp bound' p2 ] ++
[ p1, p2, PFalse, PTrue ]
instance Arbitrary (Prop Int) where
--arbitrary = do
-- nVars <- choose (0, 10)
-- mVar <- choose (nVars, 100)
-- indexes <- vectorOf nVars (choose (0, mVar))
-- arbitraryPropWithVars indexes
arbitrary = do
mVar <- choose (0, 14)
arbitraryPropWithVars [0..mVar]
shrink prop = do
let newVars = zip (vars prop) [0..]
p <- [fmap (\v -> fromJust (lookup v newVars)) prop, prop]
boundShrinkProp 3 p
|
bradlarsen/hs-cudd
|
test/PropGenerators.hs
|
Haskell
|
bsd-3-clause
| 3,517
|
-- 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.
module Duckling.Numeral.KO.Tests
( tests ) where
import Prelude
import Data.String
import Test.Tasty
import Duckling.Dimensions.Types
import Duckling.Numeral.KO.Corpus
import Duckling.Testing.Asserts
tests :: TestTree
tests = testGroup "KO Tests"
[ makeCorpusTest [Seal Numeral] corpus
]
|
facebookincubator/duckling
|
tests/Duckling/Numeral/KO/Tests.hs
|
Haskell
|
bsd-3-clause
| 504
|
#!/usr/local/bin/runhaskell
{-# LANGUAGE DeriveDataTypeable #-}
import Text.Hastache
import Text.Hastache.Context
import qualified Data.Text.Lazy.IO as TL
import Data.Data
import Data.Generics
main = hastacheStr defaultConfig (encodeStr template) context >>= TL.putStrLn
-- begin example
data Book = Book {
title :: String,
publicationYear :: Integer
} deriving (Data, Typeable)
data Life = Life {
born :: Integer,
died :: Integer
} deriving (Data, Typeable)
data Writer = Writer {
name :: String,
life :: Life,
books :: [Book]
} deriving (Data, Typeable)
template = concat [
"Name: {{name}} ({{life.born}} - {{life.died}})\n",
"{{#life}}\n",
"Born: {{born}}\n",
"Died: {{died}}\n",
"{{/life}}\n",
"Bibliography:\n",
"{{#books}}\n",
" {{title}} ({{publicationYear}})\n",
"{{/books}}\n"
]
context = mkGenericContext Writer {
name = "Mikhail Bulgakov",
life = Life 1891 1940,
books = [
Book "Heart of a Dog" 1987,
Book "Notes of a country doctor" 1926,
Book "The Master and Margarita" 1967]
}
|
lymar/hastache
|
examples/genericsBig.hs
|
Haskell
|
bsd-3-clause
| 1,235
|
module Main where
import Scraper
import Formatter
import System.Environment (getArgs)
import Data.Maybe
import Text.HTML.Scalpel
import Control.Monad (when)
import Data.List
import System.Console.ParseArgs
run :: String -> String -> IO()
run outputpath uri = do
putStrLn "Scraping..."
maybeitems <- scrapeURL uri items
items <- return $ fromMaybe [] maybeitems
res <- return . name2doc $ items
writeFile outputpath res
putStrLn $ "Done. Output is in " ++ outputpath
options = [Arg "outfile" (Just 'o') (Just "out") (argDataDefaulted "output file path" ArgtypeString "./out.txt") "output file.",
Arg "url" Nothing Nothing (argDataRequired "url" ArgtypeString) "URL to parse"]
main :: IO()
main = do
a <- parseArgsIO ArgsComplete options
let url = fromJust $ getArg a "url"
let outfile = fromJust $ getArg a "outfile"
run outfile url
|
tsukimizake/haddock2anki
|
app/Main.hs
|
Haskell
|
bsd-3-clause
| 891
|
{-# OPTIONS_GHC -Wall #-}
module Main where
import Data.Proxy
import OfflinePlay
import qualified Punter.Connector as Connector
main :: IO ()
main = runPunterOffline (Proxy :: Proxy Connector.Punter)
|
nobsun/icfpc2017
|
hs/app/connector.hs
|
Haskell
|
bsd-3-clause
| 202
|
import TestDatas (int1, stringHello)
import Test.QuickCheck.Simple (Test, boolTest, qcTest, defaultMain)
main :: IO ()
main = defaultMain tests
prop_int1 :: Bool
prop_int1 = int1 == 1
prop_stringHello :: Bool
prop_stringHello = stringHello == "Hello 2017-01-02 12:34:56"
prop_show_read :: Int -> Bool
prop_show_read i = read (show i) == (i :: Int)
tests :: [Test]
tests = [ boolTest "int1" prop_int1
, boolTest "stringHello" prop_stringHello
, qcTest "show read" prop_show_read
]
|
khibino/travis-ci-haskell
|
pkg-a/tests/useQuickCheckSimple.hs
|
Haskell
|
bsd-3-clause
| 531
|
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE ForeignFunctionInterface #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE TupleSections #-}
{-|
HAProxy proxying protocol support (see
<http://haproxy.1wt.eu/download/1.5/doc/proxy-protocol.txt>) for applications
using io-streams. The proxy protocol allows information about a networked peer
(like remote address and port) to be propagated through a forwarding proxy that
is configured to speak this protocol.
This approach is safer than other alternatives like injecting a special HTTP
header (like "X-Forwarded-For") because the data is sent out of band, requests
without the proxy header fail, and proxy data cannot be spoofed by the client.
-}
module System.IO.Streams.Network.HAProxy
(
-- * Proxying requests.
behindHAProxy
, behindHAProxyWithLocalInfo
, decodeHAProxyHeaders
-- * Information about proxied requests.
, ProxyInfo
, socketToProxyInfo
, makeProxyInfo
, getSourceAddr
, getDestAddr
, getFamily
, getSocketType
) where
------------------------------------------------------------------------------
import Control.Applicative ((<|>))
import Control.Monad (void, when)
import Data.Attoparsec.ByteString (anyWord8)
import Data.Attoparsec.ByteString.Char8 (Parser, char, decimal, skipWhile, string, take, takeWhile1)
import Data.Bits (unsafeShiftR, (.&.))
import qualified Data.ByteString as S8
import Data.ByteString.Char8 (ByteString)
import qualified Data.ByteString.Char8 as S
import qualified Data.ByteString.Unsafe as S
import Data.Word (Word16, Word32, Word8)
import Foreign.C.Types (CUInt (..), CUShort (..))
import Foreign.Ptr (castPtr)
import Foreign.Storable (peek)
import qualified Network.Socket as N
import Prelude hiding (take)
import System.IO.Streams (InputStream, OutputStream)
import qualified System.IO.Streams as Streams
import qualified System.IO.Streams.Attoparsec as Streams
import System.IO.Streams.Network.Internal.Address (getSockAddr)
import System.IO.Unsafe (unsafePerformIO)
#if !MIN_VERSION_base(4,8,0)
import Control.Applicative ((<$>))
#endif
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- | Make a 'ProxyInfo' from a connected socket.
socketToProxyInfo :: N.Socket -> N.SockAddr -> IO ProxyInfo
socketToProxyInfo s sa = do
da <- N.getSocketName s
let (N.MkSocket _ _ !sty _ _) = s
return $! makeProxyInfo sa da (addrFamily sa) sty
------------------------------------------------------------------------------
-- | Parses the proxy headers emitted by HAProxy and runs a user action with
-- the origin/destination socket addresses provided by HAProxy. Will throw a
-- 'Sockets.ParseException' if the protocol header cannot be parsed properly.
--
-- We support version 1.5 of the protocol (both the "old" text protocol and the
-- "new" binary protocol.). Typed data fields after the addresses are not (yet)
-- supported.
--
behindHAProxy :: N.Socket -- ^ A socket you've just accepted
-> N.SockAddr -- ^ and its peer address
-> (ProxyInfo
-> InputStream ByteString
-> OutputStream ByteString
-> IO a)
-> IO a
behindHAProxy socket sa m = do
pinfo <- socketToProxyInfo socket sa
sockets <- Streams.socketToStreams socket
behindHAProxyWithLocalInfo pinfo sockets m
------------------------------------------------------------------------------
-- | Like 'behindHAProxy', but allows the socket addresses and input/output
-- streams to be passed in instead of created based on an input 'Socket'.
-- Useful for unit tests.
--
behindHAProxyWithLocalInfo
:: ProxyInfo -- ^ local socket info
-> (InputStream ByteString, OutputStream ByteString) -- ^ socket streams
-> (ProxyInfo
-> InputStream ByteString
-> OutputStream ByteString
-> IO a) -- ^ user function
-> IO a
behindHAProxyWithLocalInfo localProxyInfo (is, os) m = do
proxyInfo <- decodeHAProxyHeaders localProxyInfo is
m proxyInfo is os
------------------------------------------------------------------------------
decodeHAProxyHeaders :: ProxyInfo -> (InputStream ByteString) -> IO ProxyInfo
decodeHAProxyHeaders localProxyInfo is0 = do
-- 536 bytes as per spec
is <- Streams.throwIfProducesMoreThan 536 is0
(!isOld, !mbOldInfo) <- Streams.parseFromStream
(((True,) <$> parseOldHaProxy)
<|> return (False, Nothing)) is
if isOld
then maybe (return localProxyInfo)
(\(srcAddr, srcPort, destAddr, destPort, f) -> do
(_, s) <- getSockAddr srcPort srcAddr
(_, d) <- getSockAddr destPort destAddr
return $! makeProxyInfo s d f $ getSocketType localProxyInfo)
mbOldInfo
else Streams.parseFromStream (parseNewHaProxy localProxyInfo) is
------------------------------------------------------------------------------
-- | Stores information about the proxied request.
data ProxyInfo = ProxyInfo {
_sourceAddr :: N.SockAddr
, _destAddr :: N.SockAddr
, _family :: N.Family
, _sockType :: N.SocketType
} deriving (Show)
------------------------------------------------------------------------------
-- | Gets the 'N.Family' of the proxied request (i.e. IPv4/IPv6/Unix domain
-- sockets).
getFamily :: ProxyInfo -> N.Family
getFamily p = _family p
------------------------------------------------------------------------------
-- | Gets the 'N.SocketType' of the proxied request (UDP/TCP).
getSocketType :: ProxyInfo -> N.SocketType
getSocketType p = _sockType p
------------------------------------------------------------------------------
-- | Gets the network address of the source node for this request (i.e. the
-- client).
getSourceAddr :: ProxyInfo -> N.SockAddr
getSourceAddr p = _sourceAddr p
------------------------------------------------------------------------------
-- | Gets the network address of the destination node for this request (i.e. the
-- client).
getDestAddr :: ProxyInfo -> N.SockAddr
getDestAddr p = _destAddr p
------------------------------------------------------------------------------
-- | Makes a 'ProxyInfo' object.
makeProxyInfo :: N.SockAddr -- ^ the source address
-> N.SockAddr -- ^ the destination address
-> N.Family -- ^ the socket family
-> N.SocketType -- ^ the socket type
-> ProxyInfo
makeProxyInfo srcAddr destAddr f st = ProxyInfo srcAddr destAddr f st
------------------------------------------------------------------------------
parseFamily :: Parser (Maybe N.Family)
parseFamily = (string "TCP4" >> return (Just N.AF_INET))
<|> (string "TCP6" >> return (Just N.AF_INET6))
<|> (string "UNKNOWN" >> return Nothing)
------------------------------------------------------------------------------
parseOldHaProxy :: Parser (Maybe (ByteString, Int, ByteString, Int, N.Family))
parseOldHaProxy = do
string "PROXY "
gotFamily <- parseFamily
case gotFamily of
Nothing -> skipWhile (/= '\r') >> string "\r\n" >> return Nothing
(Just f) -> do
char ' '
srcAddress <- takeWhile1 (/= ' ')
char ' '
destAddress <- takeWhile1 (/= ' ')
char ' '
srcPort <- decimal
char ' '
destPort <- decimal
string "\r\n"
return $! Just $! (srcAddress, srcPort, destAddress, destPort, f)
------------------------------------------------------------------------------
protocolHeader :: ByteString
protocolHeader = S8.pack [ 0x0D, 0x0A, 0x0D, 0x0A, 0x00, 0x0D
, 0x0A, 0x51, 0x55, 0x49, 0x54, 0x0A ]
{-# NOINLINE protocolHeader #-}
------------------------------------------------------------------------------
parseNewHaProxy :: ProxyInfo -> Parser ProxyInfo
parseNewHaProxy localProxyInfo = do
string protocolHeader
versionAndCommand <- anyWord8
let version = (versionAndCommand .&. 0xF0) `unsafeShiftR` 4
let command = (versionAndCommand .&. 0xF) :: Word8
when (version /= 0x2) $ fail $ "Invalid protocol version: " ++ show version
when (command > 1) $ fail $ "Invalid command: " ++ show command
protocolAndFamily <- anyWord8
let family = (protocolAndFamily .&. 0xF0) `unsafeShiftR` 4
let protocol = (protocolAndFamily .&. 0xF) :: Word8
-- VALUES FOR FAMILY
-- 0x0 : AF_UNSPEC : the connection is forwarded for an unknown,
-- unspecified or unsupported protocol. The sender should use this family
-- when sending LOCAL commands or when dealing with unsupported protocol
-- families. The receiver is free to accept the connection anyway and use
-- the real endpoint addresses or to reject it. The receiver should ignore
-- address information.
-- 0x1 : AF_INET : the forwarded connection uses the AF_INET address family
-- (IPv4). The addresses are exactly 4 bytes each in network byte order,
-- followed by transport protocol information (typically ports).
-- 0x2 : AF_INET6 : the forwarded connection uses the AF_INET6 address
-- family (IPv6). The addresses are exactly 16 bytes each in network byte
-- order, followed by transport protocol information (typically ports).
--
-- 0x3 : AF_UNIX : the forwarded connection uses the AF_UNIX address family
-- (UNIX). The addresses are exactly 108 bytes each.
socketType <- toSocketType protocol
addressLen <- ntohs <$> snarf16
case () of
!_ | command == 0x0 || family == 0x0 || protocol == 0x0 -- LOCAL
-> handleLocal addressLen
| family == 0x1 -> handleIPv4 addressLen socketType
| family == 0x2 -> handleIPv6 addressLen socketType
#ifndef WINDOWS
| family == 0x3 -> handleUnix addressLen socketType
#endif
| otherwise -> fail $ "Bad family " ++ show family
where
toSocketType 0 = return $! N.Stream
toSocketType 1 = return $! N.Stream
toSocketType 2 = return $! N.Datagram
toSocketType _ = fail "bad protocol"
handleLocal addressLen = do
-- skip N bytes and return the original addresses
when (addressLen > 500) $ fail $ "suspiciously long address "
++ show addressLen
void $ take (fromIntegral addressLen)
return localProxyInfo
handleIPv4 addressLen socketType = do
when (addressLen < 12) $ fail $ "bad address length "
++ show addressLen
++ " for IPv4"
let nskip = addressLen - 12
srcAddr <- snarf32
destAddr <- snarf32
srcPort <- ntohs <$> snarf16
destPort <- ntohs <$> snarf16
void $ take $ fromIntegral nskip
-- Note: we actually want the brain-dead constructors here
let sa = N.SockAddrInet (fromIntegral srcPort) srcAddr
let sb = N.SockAddrInet (fromIntegral destPort) destAddr
return $! makeProxyInfo sa sb (addrFamily sa) socketType
handleIPv6 addressLen socketType = do
let scopeId = 0 -- means "reserved", kludge alert!
let flow = 0
when (addressLen < 36) $ fail $ "bad address length "
++ show addressLen
++ " for IPv6"
let nskip = addressLen - 36
s1 <- ntohl <$> snarf32
s2 <- ntohl <$> snarf32
s3 <- ntohl <$> snarf32
s4 <- ntohl <$> snarf32
d1 <- ntohl <$> snarf32
d2 <- ntohl <$> snarf32
d3 <- ntohl <$> snarf32
d4 <- ntohl <$> snarf32
sp <- ntohs <$> snarf16
dp <- ntohs <$> snarf16
void $ take $ fromIntegral nskip
let sa = N.SockAddrInet6 (fromIntegral sp) flow (s1, s2, s3, s4) scopeId
let sb = N.SockAddrInet6 (fromIntegral dp) flow (d1, d2, d3, d4) scopeId
return $! makeProxyInfo sa sb (addrFamily sa) socketType
#ifndef WINDOWS
handleUnix addressLen socketType = do
when (addressLen < 216) $ fail $ "bad address length "
++ show addressLen
++ " for unix"
addr1 <- take 108
addr2 <- take 108
void $ take $ fromIntegral $ addressLen - 216
let sa = N.SockAddrUnix (toUnixPath addr1)
let sb = N.SockAddrUnix (toUnixPath addr2)
return $! makeProxyInfo sa sb (addrFamily sa) socketType
toUnixPath = S.unpack . fst . S.break (=='\x00')
#endif
foreign import ccall unsafe "iostreams_ntohs" c_ntohs :: CUShort -> CUShort
foreign import ccall unsafe "iostreams_ntohl" c_ntohl :: CUInt -> CUInt
ntohs :: Word16 -> Word16
ntohs = fromIntegral . c_ntohs . fromIntegral
ntohl :: Word32 -> Word32
ntohl = fromIntegral . c_ntohl . fromIntegral
snarf32 :: Parser Word32
snarf32 = do
s <- take 4
return $! unsafePerformIO $! S.unsafeUseAsCString s $ peek . castPtr
snarf16 :: Parser Word16
snarf16 = do
s <- take 2
return $! unsafePerformIO $! S.unsafeUseAsCString s $ peek . castPtr
addrFamily :: N.SockAddr -> N.Family
addrFamily s = case s of
(N.SockAddrInet _ _) -> N.AF_INET
(N.SockAddrInet6 _ _ _ _) -> N.AF_INET6
#ifndef WINDOWS
(N.SockAddrUnix _ ) -> N.AF_UNIX
#endif
_ -> error "unknown family"
|
23Skidoo/io-streams-haproxy
|
src/System/IO/Streams/Network/HAProxy.hs
|
Haskell
|
bsd-3-clause
| 14,487
|
module CNC.IntegrationTests where
import CNC.Declarative
import CNC.HCode
import Data.Complex
import Control.Monad
flake_side = do
[p1,p2,p3,p4,p5] <- declarePoints 5
xSize p1 p2 1
len p2 p3 1
len p3 p4 1
xAngle p2 p3 (pi / 3)
xAngle p3 p4 (- pi / 3)
xSize p4 p5 1
renderPolygon :: Int -> Path -> HCode ()
renderPolygon n path = render_side 0 path n
where
render_side p0 path 0 = return ()
render_side p0 path k = do
let d = deltaPath path
renderPath (posToExpr p0) path
render_side (p0 + d) (rotate (- 2*pi / fromIntegral n) path) (k-1)
test1 = do putStrLn "a snowflake"
print $ (figure flake_side)
putHCode $ renderPolygon 3 (figure flake_side)
integrationTests = do
putStrLn "Integration tests"
test1
|
akamaus/gcodec
|
test/CNC/IntegrationTests.hs
|
Haskell
|
bsd-3-clause
| 777
|
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE InstanceSigs #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE ViewPatterns #-}
module EZConfig (spec) where
import Control.Arrow (first, (>>>))
import Data.Coerce
import Foreign.C.Types (CUInt(..))
import Test.Hspec
import Test.Hspec.QuickCheck
import Test.QuickCheck
import XMonad
import XMonad.Prelude
import XMonad.Util.EZConfig
import XMonad.Util.Parser
spec :: Spec
spec = do
prop "prop_decodePreservation" prop_decodePreservation
prop "prop_encodePreservation" prop_encodePreservation
context "parseKey" $ do
let prepare = unzip . map (first surround)
testParseKey (ns, ks) = traverse (runParser parseKey) ns `shouldBe` Just ks
it "parses all regular keys" $ testParseKey (unzip regularKeys )
it "parses all function keys" $ testParseKey (prepare functionKeys )
it "parses all special keys" $ testParseKey (prepare specialKeys )
it "parses all multimedia keys" $ testParseKey (prepare multimediaKeys)
context "parseModifier" $ do
it "parses all combinations of modifiers" $
nub . map sort <$> traverse (runParser (many $ parseModifier def))
modifiers
`shouldBe` Just [[ shiftMask, controlMask
, mod1Mask, mod1Mask -- def M and M1
, mod2Mask, mod3Mask, mod4Mask, mod5Mask
]]
-- Checking for regressions
describe "readKeySequence" $
it "Fails on the non-existent key M-10" $
readKeySequence def "M-10" `shouldBe` Nothing
-- | Parsing preserves all info that printing does.
prop_encodePreservation :: KeyString -> Property
prop_encodePreservation (coerce -> s) = parse s === (parse . pp =<< parse s)
where parse = runParser (parseKeySequence def)
pp = unwords . map keyToString
-- | Printing preserves all info that parsing does.
prop_decodePreservation :: NonEmptyList (AKeyMask, AKeySym) -> Property
prop_decodePreservation (getNonEmpty >>> coerce -> xs) =
Just (pp xs) === (fmap pp . parse $ pp xs)
where parse = runParser (parseKeySequence def)
pp = unwords . map keyToString
-- | QuickCheck can handle the 8! combinations just fine.
modifiers :: [String]
modifiers = map concat $ permutations mods
mods :: [String]
mods = ["M-", "C-", "S-", "M1-", "M2-", "M3-", "M4-", "M5-"]
surround :: String -> String
surround s = "<" <> s <> ">"
-----------------------------------------------------------------------
-- Newtypes and Arbitrary instances
newtype AKeyMask = AKeyMask KeyMask
deriving newtype (Show)
instance Arbitrary AKeyMask where
arbitrary :: Gen AKeyMask
arbitrary = fmap (coerce . sum . nub) . listOf . elements $
[noModMask, shiftMask, controlMask, mod1Mask, mod2Mask, mod3Mask, mod4Mask, mod5Mask]
newtype AKeySym = AKeySym KeySym
deriving newtype (Show)
instance Arbitrary AKeySym where
arbitrary :: Gen AKeySym
arbitrary = elements . coerce . map snd $ regularKeys <> allSpecialKeys
newtype KeyString = KeyString String
deriving newtype (Show)
instance Arbitrary KeyString where
arbitrary :: Gen KeyString
arbitrary = coerce . unwords <$> listOf keybinding
where
keybinding :: Gen String
keybinding = do
let keyStr = map fst $ regularKeys <> allSpecialKeys
mks <- nub <$> listOf (elements ("" : mods))
k <- elements keyStr
ks <- listOf . elements $ keyStr
pure $ concat mks <> k <> " " <> unwords ks
|
xmonad/xmonad-contrib
|
tests/EZConfig.hs
|
Haskell
|
bsd-3-clause
| 3,567
|
module Wow1 where
import Haskore.Melody
import Haskore.Music as M
import Haskore.Basic.Duration as D
import Haskore.Basic.Duration
import Snippet
import Prelude as P
import Haskore.Music.GeneralMIDI
import Haskore.Basic.Interval
flute_base = [
cs 1 qn, fs 1 qn, fs 1 en, e 1 en, fs 1 hn, fs 1 en, gs 1 en
]
flute_var_1 = [
a 1 qn, b 1 qn, a 1 qn, gs 1 en, fs 1 en, e 1 hn
]
flute_var_2 = [
a 1 qn, e 1 en, cs 1 en, a 1 qn, gs 1 dhn
]
flute_var_3 = [
a 1 qn, fs 1 qn, a 1 qn, b 1 dqn, a 1 en, gs 1 qn, fs 1 dwn
]
t1 = play_with PanFlute . line $ map (\x -> x ()) $
concat [
flute_base,
flute_var_1,
flute_base,
flute_var_2,
flute_base,
flute_var_1,
flute_var_3
]
wow_1 = export_to' "wow_1" 1 $ changeTempo 3 $ transpose octave $ t1
main = wow_1
|
nfjinjing/haskore-guide
|
src/wow_1.hs
|
Haskell
|
bsd-3-clause
| 806
|
{-# language CPP #-}
-- | = Name
--
-- XR_MSFT_unbounded_reference_space - instance extension
--
-- = Specification
--
-- See
-- <https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#XR_MSFT_unbounded_reference_space XR_MSFT_unbounded_reference_space>
-- in the main specification for complete information.
--
-- = Registered Extension Number
--
-- 39
--
-- = Revision
--
-- 1
--
-- = Extension and Version Dependencies
--
-- - Requires OpenXR 1.0
--
-- = See Also
--
-- No cross-references are available
--
-- = Document Notes
--
-- For more information, see the
-- <https://www.khronos.org/registry/OpenXR/specs/1.0/html/xrspec.html#XR_MSFT_unbounded_reference_space OpenXR Specification>
--
-- This page is a generated document. Fixes and changes should be made to
-- the generator scripts, not directly.
module OpenXR.Extensions.XR_MSFT_unbounded_reference_space ( MSFT_unbounded_reference_space_SPEC_VERSION
, pattern MSFT_unbounded_reference_space_SPEC_VERSION
, MSFT_UNBOUNDED_REFERENCE_SPACE_EXTENSION_NAME
, pattern MSFT_UNBOUNDED_REFERENCE_SPACE_EXTENSION_NAME
) where
import Data.String (IsString)
type MSFT_unbounded_reference_space_SPEC_VERSION = 1
-- No documentation found for TopLevel "XR_MSFT_unbounded_reference_space_SPEC_VERSION"
pattern MSFT_unbounded_reference_space_SPEC_VERSION :: forall a . Integral a => a
pattern MSFT_unbounded_reference_space_SPEC_VERSION = 1
type MSFT_UNBOUNDED_REFERENCE_SPACE_EXTENSION_NAME = "XR_MSFT_unbounded_reference_space"
-- No documentation found for TopLevel "XR_MSFT_UNBOUNDED_REFERENCE_SPACE_EXTENSION_NAME"
pattern MSFT_UNBOUNDED_REFERENCE_SPACE_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a
pattern MSFT_UNBOUNDED_REFERENCE_SPACE_EXTENSION_NAME = "XR_MSFT_unbounded_reference_space"
|
expipiplus1/vulkan
|
openxr/src/OpenXR/Extensions/XR_MSFT_unbounded_reference_space.hs
|
Haskell
|
bsd-3-clause
| 2,016
|
module Libv10
( main'
) where
-- v10 : Fill in the division team mapping and other data
import Control.Monad
import qualified Data.Map.Strict as Map
import Data.List
import Data.Maybe
import Data.Ord
import System.Environment
import Text.Parsec
import Text.Parsec.String
import Text.Printf
-- data ----------------------------------------------------
-- Ranking information - team rank, team name
data Ranking = Ranking
{ rRank :: Int
, rTeam :: String
} deriving Show
-- Result information - division, average, standard deviation
data Result = Result
{ rDivision :: String
, rAverage :: Double
, rStdDev :: Double
} deriving Show
-- parsing -------------------------------------------------
-- Parse out a single ranking from the file
rankingParser :: Parser Ranking
rankingParser = do
many space
rank <- many1 digit
many space
team <- many1 alphaNum
newline
return (Ranking (read rank) team)
-- Parse out all of the rankings
rankingsParser :: Parser [Ranking]
rankingsParser = many1 rankingParser
-- Take a file and produce a list of team rankings
parseRankings :: String -> IO [Ranking]
parseRankings file =
parseFromFile rankingsParser file >>= either undefined return
-- calculating ---------------------------------------------
-- >> AFC divisions
afcEast, afcWest, afcSouth, afcNorth :: String
afcEast = "AFC East"
afcWest = "AFC West"
afcSouth = "AFC South"
afcNorth = "AFC North"
-- >> NFC divisions
nfcEast, nfcWest, nfcSouth, nfcNorth :: String
nfcEast = "NFC East"
nfcWest = "NFC West"
nfcSouth = "NFC South"
nfcNorth = "NFC North"
-- >> Map teams to their divisions
teamDivisionMap :: Map.Map String String
teamDivisionMap = Map.fromList
[ ("PATRIOTS", afcEast)
, ("JETS", afcEast)
, ("DOLPHINS", afcEast)
, ("BILLS", afcEast)
, ("BENGALS", afcNorth)
, ("BROWNS", afcNorth)
, ("STEELERS", afcNorth)
, ("RAVENS", afcNorth)
, ("BRONCOS", afcWest)
, ("RAIDERS", afcWest)
, ("CHARGERS", afcWest)
, ("CHIEFS", afcWest)
, ("JAGUARS", afcSouth)
, ("TITANS", afcSouth)
, ("TEXANS", afcSouth)
, ("COLTS", afcSouth)
, ("FALCONS", nfcSouth)
, ("PANTHERS", nfcSouth)
, ("BUCCANEERS", nfcSouth)
, ("SAINTS", nfcSouth)
, ("PACKERS", nfcNorth)
, ("VIKINGS", nfcNorth)
, ("LIONS", nfcNorth)
, ("BEARS", nfcNorth)
, ("COWBOYS", nfcEast)
, ("REDSKINS", nfcEast)
, ("GIANTS", nfcEast)
, ("EAGLES", nfcEast)
, ("CARDINALS", nfcWest)
, ("RAMS", nfcWest)
, ("49ERS", nfcWest)
, ("SEAHAWKS", nfcWest)
]
-- Lookup a team's division - assume well-formed data files :o
teamToDivision :: String -> String
teamToDivision team =
fromJust (Map.lookup team teamDivisionMap)
-- Convert a ranking to a (division, rank) tuple
rankingToDivision :: Ranking -> (String, Int)
rankingToDivision ranking =
(teamToDivision (rTeam ranking), rRank ranking)
-- Group sort - collect values with identical keys
groupSort :: Ord k => [(k, v)] -> [(k, [v])]
groupSort kvs = Map.toList (Map.fromListWith (++) [(k, [v]) | (k, v) <- kvs])
-- Turn the rankings into a (division, [rank]) tuple
rankingsToDivisions :: [Ranking] -> [(String, [Int])]
rankingsToDivisions rankings =
groupSort (map rankingToDivision rankings)
-- Average a number of rankings
average :: [Int] -> Double
average rankings = realToFrac (sum rankings) / genericLength rankings
-- Standard deviation of rankings group
stdDev :: [Int] -> Double
stdDev rankings = sqrt (sum (map f rankings) / genericLength rankings) where
f ranking = (realToFrac ranking - average rankings) ** 2
-- Produce a result from division and [rank]
calculateResult :: (String, [Int]) -> Result
calculateResult (division, rankings) =
Result division (average rankings) (stdDev rankings)
-- Take teams rankings and calculate results
calculateResults :: [Ranking] -> [Result]
calculateResults rankings =
sortBy (comparing rAverage) (map calculateResult (rankingsToDivisions rankings))
-- main ----------------------------------------------------
-- Combine the parsing and calculating
parseAndCalculate :: String -> IO [Result]
parseAndCalculate file = do
rankings <- parseRankings file
return (calculateResults rankings)
-- Collect results from all the files
parseAndCalculateAll :: [String] -> IO [(String, [Result])]
parseAndCalculateAll files =
forM files $ \file -> do
results <- parseAndCalculate file
return (file, results)
-- Print out a result
printResult :: Result -> IO ()
printResult result =
printf "%-10s %10.2f %10.2f\n" (rDivision result) (rAverage result) (rStdDev result)
-- Print out all the results
inputsToOutputs :: [(String, [Result])] -> IO ()
inputsToOutputs results =
forM_ results $ \(file, results') -> do
putStrLn file
forM_ results' printResult
putStrLn ""
-- Program Entry - pass file args as inputs
main' :: IO ()
main' = do
args <- getArgs
results <- parseAndCalculateAll args
inputsToOutputs results
|
mfine/hs-talks
|
src/Libv10.hs
|
Haskell
|
bsd-3-clause
| 5,032
|
{-# LANGUAGE DeriveDataTypeable #-}
{-# OPTIONS_GHC -fno-warn-missing-fields #-}
{-# OPTIONS_GHC -fno-warn-missing-signatures #-}
{-# OPTIONS_GHC -fno-warn-name-shadowing #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-----------------------------------------------------------------
-- Autogenerated by Thrift Compiler (0.7.0-dev) --
-- --
-- DO NOT EDIT UNLESS YOU ARE SURE YOU KNOW WHAT YOU ARE DOING --
-----------------------------------------------------------------
module Thrift.Content_Consts where
import Prelude ( Bool(..), Enum, Double, String, Maybe(..),
Eq, Show, Ord,
return, length, IO, fromIntegral, fromEnum, toEnum,
(&&), (||), (==), (++), ($), (-) )
import Control.Exception
import Data.ByteString.Lazy
import Data.Int
import Data.Typeable ( Typeable )
import qualified Data.Map as Map
import qualified Data.Set as Set
import Thrift
import Thrift.Content_Types
|
csabahruska/GFXDemo
|
Thrift/Content_Consts.hs
|
Haskell
|
bsd-3-clause
| 1,066
|
-- |
-- Module : $Header$
-- Copyright : (c) 2013-2015 Galois, Inc.
-- License : BSD3
-- Maintainer : cryptol@galois.com
-- Stability : provisional
-- Portability : portable
{-# LANGUAGE Safe #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE PatternGuards #-}
module Cryptol.TypeCheck.Solver.CrySAT
( withScope, withSolver
, assumeProps, simplifyProps, getModel
, check
, Solver, logger
, DefinedProp(..)
, debugBlock
, DebugLog(..)
, prepareConstraints
) where
import qualified Cryptol.TypeCheck.AST as Cry
import Cryptol.TypeCheck.InferTypes(Goal(..), SolverConfig(..))
import qualified Cryptol.TypeCheck.Subst as Cry
import Cryptol.TypeCheck.Solver.Numeric.AST
import Cryptol.TypeCheck.Solver.Numeric.ImportExport
import Cryptol.TypeCheck.Solver.Numeric.Defined
import Cryptol.TypeCheck.Solver.Numeric.Simplify
import Cryptol.TypeCheck.Solver.Numeric.SimplifyExpr(crySimpExpr)
import Cryptol.TypeCheck.Solver.Numeric.NonLin
import Cryptol.TypeCheck.Solver.Numeric.SMT
import Cryptol.Utils.PP -- ( Doc )
import Cryptol.Utils.Panic ( panic )
import MonadLib
import Data.Maybe ( mapMaybe, fromMaybe )
import Data.Either ( partitionEithers )
import Data.List(nub)
import qualified Data.Map as Map
import Data.Foldable ( any, all )
import qualified Data.Set as Set
import Data.IORef ( IORef, newIORef, readIORef, modifyIORef',
atomicModifyIORef' )
import Prelude hiding (any,all)
import qualified SimpleSMT as SMT
-- | We use this to remember what we simplified
newtype SimpProp = SimpProp { unSimpProp :: Prop }
simpProp :: Prop -> SimpProp
simpProp p = SimpProp (crySimplify p)
-- | 'dpSimpProp' and 'dpSimpExprProp' should be logically equivalent,
-- to each other, and to whatever 'a' represents (usually 'a' is a 'Goal').
data DefinedProp a = DefinedProp
{ dpData :: a
-- ^ Optional data to associate with prop.
-- Often, the original `Goal` from which the prop was extracted.
, dpSimpProp :: SimpProp
{- ^ Fully simplified: may mention ORs, and named non-linear terms.
These are what we send to the prover, and we don't attempt to
convert them back into Cryptol types. -}
, dpSimpExprProp :: Prop
{- ^ A version of the proposition where just the expression terms
have been simplified. These should not contain ORs or named non-linear
terms because we want to import them back into Crytpol types. -}
}
instance HasVars SimpProp where
apSubst su (SimpProp p) = do p1 <- apSubst su p
let p2 = crySimplify p1
guard (p1 /= p2)
return (SimpProp p2)
apSubstDefinedProp :: (Prop -> a -> a) ->
Subst -> DefinedProp a -> Maybe (DefinedProp a)
apSubstDefinedProp updCt su DefinedProp { .. } =
do s1 <- apSubst su dpSimpProp
return $ case apSubst su dpSimpExprProp of
Nothing -> DefinedProp { dpSimpProp = s1, .. }
Just p1 -> DefinedProp { dpSimpProp = s1
, dpSimpExprProp = p1
, dpData = updCt p1 dpData
}
{- | Check if the given constraint is guaranteed to be well-defined.
This means that it cannot be instantiated in a way that would result in
undefined behaviour.
This estimate is consevative:
* if we return `Right`, then the property is definately well-defined
* if we return `Left`, then we don't know if the property is well-defined
If the property is well-defined, then we also simplify it.
-}
checkDefined1 :: Solver -> (Prop -> a -> a) ->
(a,Prop) -> IO (Either (a,Prop) (DefinedProp a))
checkDefined1 s updCt (ct,p) =
do proved <- prove s defCt
return $
if proved
then Right $
case crySimpPropExprMaybe p of
Nothing -> DefinedProp { dpData = ct
, dpSimpExprProp = p
, dpSimpProp = simpProp p
}
Just p' -> DefinedProp { dpData = updCt p' ct
, dpSimpExprProp = p'
, dpSimpProp = simpProp p'
}
else Left (ct,p)
where
SimpProp defCt = simpProp (cryDefinedProp p)
prepareConstraints ::
Solver -> (Prop -> a -> a) ->
[(a,Prop)] -> IO (Either [a] ([a], [DefinedProp a], Subst, [Prop]))
prepareConstraints s updCt cs =
do res <- mapM (checkDefined1 s updCt) cs
let (unknown,ok) = partitionEithers res
goStep1 unknown ok Map.empty []
where
getImps ok = withScope s $
do mapM_ (assert s . dpSimpProp) ok
check s
mapEither f = partitionEithers . map f
apSuUnk su (x,p) =
case apSubst su p of
Nothing -> Left (x,p)
Just p1 -> Right (updCt p1 x, p1)
apSuOk su p = case apSubstDefinedProp updCt su p of
Nothing -> Left p
Just p1 -> Right p1
apSubst' su x = fromMaybe x (apSubst su x)
goStep1 unknown ok su sgs =
do let (ok1, moreSu) = improveByDefnMany updCt ok
go unknown ok1 (composeSubst moreSu su) (map (apSubst' moreSu) sgs)
go unknown ok su sgs =
do mb <- getImps ok
case mb of
Nothing ->
do bad <- minimizeContradictionSimpDef s ok
return (Left bad)
Just (imps,subGoals)
| not (null okNew) -> goStep1 unknown (okNew ++ okOld) newSu newGs
| otherwise ->
do res <- mapM (checkDefined1 s updCt) unkNew
let (stillUnk,nowOk) = partitionEithers res
if null nowOk
then return (Right ( map fst (unkNew ++ unkOld)
, ok, newSu, newGs))
else goStep1 (stillUnk ++ unkOld) (nowOk ++ ok) newSu newGs
where (okOld, okNew) = mapEither (apSuOk imps) ok
(unkOld,unkNew) = mapEither (apSuUnk imps) unknown
newSu = composeSubst imps su
newGs = nub (subGoals ++ map (apSubst' su) sgs)
-- XXX: inefficient
-- | Simplify a bunch of well-defined properties.
-- * Eliminates properties that are implied by the rest.
-- * Does not modify the set of assumptions.
simplifyProps :: Solver -> [DefinedProp a] -> IO [a]
simplifyProps s props =
debugBlock s "Simplifying properties" $
withScope s (go [] props)
where
go survived [] = return survived
go survived (DefinedProp { dpSimpProp = SimpProp PTrue } : more) =
go survived more
go survived (p : more) =
case dpSimpProp p of
SimpProp PTrue -> go survived more
SimpProp p' ->
do proved <- withScope s $ do mapM_ (assert s . dpSimpProp) more
prove s p'
if proved
then go survived more
else do assert s (SimpProp p')
go (dpData p : survived) more
-- | Add the given constraints as assumptions.
-- * We assume that the constraints are well-defined.
-- * Modifies the set of assumptions.
assumeProps :: Solver -> [Cry.Prop] -> IO [SimpProp]
assumeProps s props =
do let ps = mapMaybe exportProp props
let simpProps = map simpProp (map cryDefinedProp ps ++ ps)
mapM_ (assert s) simpProps
return simpProps
-- XXX: Instead of asserting one at a time, perhaps we should
-- assert a conjunction. That way, we could simplify the whole thing
-- in one go, and would avoid having to assert 'true' many times.
-- | Given a list of propositions that together lead to a contradiction,
-- find a sub-set that still leads to a contradiction (but is smaller).
minimizeContradictionSimpDef :: Solver -> [DefinedProp a] -> IO [a]
minimizeContradictionSimpDef s ps = start [] ps
where
start bad todo =
do res <- SMT.check (solver s)
case res of
SMT.Unsat -> return (map dpData bad)
_ -> do solPush s
go bad [] todo
go _ _ [] = panic "minimizeContradiction"
$ ("No contradiction" : map (show . ppProp . dpSimpExprProp) ps)
go bad prev (d : more) =
do assert s (dpSimpProp d)
res <- SMT.check (solver s)
case res of
SMT.Unsat -> do solPop s
assert s (dpSimpProp d)
start (d : bad) prev
_ -> go bad (d : prev) more
improveByDefnMany :: (Prop -> a -> a) ->
[DefinedProp a] -> ([DefinedProp a], Subst)
improveByDefnMany updCt = go [] Map.empty
where
mbSu su x = case apSubstDefinedProp updCt su x of
Nothing -> Left x
Just y -> Right y
go todo su (p : ps) =
let p1 = fromMaybe p (apSubstDefinedProp updCt su p)
in case improveByDefn p1 of
Just (x,e) ->
go todo (composeSubst (Map.singleton x e) su) ps
-- `p` is solved, so ignore
Nothing -> go (p1 : todo) su ps
go todo su [] =
let (same,changed) = partitionEithers (map (mbSu su) todo)
in case changed of
[] -> (same, fmap crySimpExpr su)
_ -> go same su changed
{- | If we see an equation: `?x = e`, and:
* ?x is a unification variable
* `e` is "zonked" (substitution is fully applied)
* ?x does not appear in `e`.
then, we can improve `?x` to `e`.
-}
improveByDefn :: DefinedProp a -> Maybe (Name,Expr)
improveByDefn p =
case dpSimpExprProp p of
Var x :== e
| isUV x -> tryToBind x e
e :== Var x
| isUV x -> tryToBind x e
_ -> Nothing
where
tryToBind x e
| x `Set.member` cryExprFVS e = Nothing
| otherwise = Just (x,e)
isUV (UserName (Cry.TVFree {})) = True
isUV _ = False
{- | Attempt to find a substituion that, when applied, makes all of the
given properties hold. -}
getModel :: Solver -> [Cry.Prop] -> IO (Maybe Cry.Subst)
getModel s props = withScope s $
do ps <- assumeProps s props
res <- SMT.check (solver s)
let vars = Set.toList $ Set.unions $ map (cryPropFVS . unSimpProp) ps
case res of
SMT.Sat ->
do vs <- getVals (solver s) vars
-- This is guaranteed to be a model only for the *linear*
-- properties, so now we check if it works for the rest too.
let su1 = fmap K vs
ps1 = [ fromMaybe p (apSubst su1 p) | SimpProp p <- ps ]
ok p = case crySimplify p of
PTrue -> True
_ -> False
su2 = Cry.listSubst
[ (x, numTy v) | (UserName x, v) <- Map.toList vs ]
return (guard (all ok ps1) >> return su2)
_ -> return Nothing
where
numTy Inf = Cry.tInf
numTy (Nat k) = Cry.tNum k
--------------------------------------------------------------------------------
-- | An SMT solver, and some info about declared variables.
data Solver = Solver
{ solver :: SMT.Solver
-- ^ The actual solver
, declared :: IORef VarInfo
-- ^ Information about declared variables, and assumptions in scope.
, logger :: SMT.Logger
-- ^ For debugging
}
-- | Keeps track of declared variables and non-linear terms.
data VarInfo = VarInfo
{ curScope :: Scope
, otherScopes :: [Scope]
} deriving Show
data Scope = Scope
{ scopeNames :: [Name]
-- ^ Variables declared in this scope (not counting the ones from
-- previous scopes).
, scopeNonLinS :: NonLinS
{- ^ These are the non-linear terms mentioned in the assertions
that are currently asserted (including ones from previous scopes). -}
} deriving Show
scopeEmpty :: Scope
scopeEmpty = Scope { scopeNames = [], scopeNonLinS = initialNonLinS }
scopeElem :: Name -> Scope -> Bool
scopeElem x Scope { .. } = x `elem` scopeNames
scopeInsert :: Name -> Scope -> Scope
scopeInsert x Scope { .. } = Scope { scopeNames = x : scopeNames, .. }
-- | Given a *simplified* prop, separate linear and non-linear parts
-- and return the linear ones.
scopeAssert :: SimpProp -> Scope -> ([SimpProp],Scope)
scopeAssert (SimpProp p) Scope { .. } =
let (ps1,s1) = nonLinProp scopeNonLinS p
in (map SimpProp ps1, Scope { scopeNonLinS = s1, .. })
-- | No scopes.
viEmpty :: VarInfo
viEmpty = VarInfo { curScope = scopeEmpty, otherScopes = [] }
-- | Check if a name is any of the scopes.
viElem :: Name -> VarInfo -> Bool
viElem x VarInfo { .. } = any (x `scopeElem`) (curScope : otherScopes)
-- | Add a name to a scope.
viInsert :: Name -> VarInfo -> VarInfo
viInsert x VarInfo { .. } = VarInfo { curScope = scopeInsert x curScope, .. }
-- | Add an assertion to the current scope. Returns the linear part.
viAssert :: SimpProp -> VarInfo -> (VarInfo, [SimpProp])
viAssert p VarInfo { .. } = ( VarInfo { curScope = s1, .. }, p1)
where (p1, s1) = scopeAssert p curScope
-- | Enter a scope.
viPush :: VarInfo -> VarInfo
viPush VarInfo { .. } =
VarInfo { curScope = scopeEmpty { scopeNonLinS = scopeNonLinS curScope }
, otherScopes = curScope : otherScopes
}
-- | Exit a scope.
viPop :: VarInfo -> VarInfo
viPop VarInfo { .. } = case otherScopes of
c : cs -> VarInfo { curScope = c, otherScopes = cs }
_ -> panic "viPop" ["no more scopes"]
-- | All declared names, that have not been "marked".
-- These are the variables whose values we are interested in.
viUnmarkedNames :: VarInfo -> [ Name ]
viUnmarkedNames VarInfo { .. } = concatMap scopeNames scopes
where scopes = curScope : otherScopes
-- | All known non-linear terms.
getNLSubst :: Solver -> IO Subst
getNLSubst Solver { .. } =
do VarInfo { .. } <- readIORef declared
return $ nonLinSubst $ scopeNonLinS curScope
-- | Execute a computation with a fresh solver instance.
withSolver :: SolverConfig -> (Solver -> IO a) -> IO a
withSolver SolverConfig { .. } k =
do logger <- if solverVerbose > 0 then SMT.newLogger 0 else return quietLogger
let smtDbg = if solverVerbose > 1 then Just logger else Nothing
solver <- SMT.newSolver solverPath solverArgs smtDbg
_ <- SMT.setOptionMaybe solver ":global-decls" "false"
SMT.setLogic solver "QF_LIA"
declared <- newIORef viEmpty
a <- k Solver { .. }
_ <- SMT.stop solver
return a
where
quietLogger = SMT.Logger { SMT.logMessage = \_ -> return ()
, SMT.logLevel = return 0
, SMT.logSetLevel= \_ -> return ()
, SMT.logTab = return ()
, SMT.logUntab = return ()
}
solPush :: Solver -> IO ()
solPush Solver { .. } =
do SMT.push solver
SMT.logTab logger
modifyIORef' declared viPush
solPop :: Solver -> IO ()
solPop Solver { .. } =
do modifyIORef' declared viPop
SMT.logUntab logger
SMT.pop solver
-- | Execute a computation in a new solver scope.
withScope :: Solver -> IO a -> IO a
withScope s k =
do solPush s
a <- k
solPop s
return a
-- | Declare a variable.
declareVar :: Solver -> Name -> IO ()
declareVar s@Solver { .. } a =
do done <- fmap (a `viElem`) (readIORef declared)
unless done $
do e <- SMT.declare solver (smtName a) SMT.tInt
let fin_a = smtFinName a
fin <- SMT.declare solver fin_a SMT.tBool
SMT.assert solver (SMT.geq e (SMT.int 0))
nlSu <- getNLSubst s
modifyIORef' declared (viInsert a)
case Map.lookup a nlSu of
Nothing -> return ()
Just e' ->
do let finDef = crySimplify (Fin e')
mapM_ (declareVar s) (Set.toList (cryPropFVS finDef))
SMT.assert solver $
SMT.eq fin (ifPropToSmtLib (desugarProp finDef))
-- | Add an assertion to the current context.
-- INVARIANT: Assertion is simplified.
assert :: Solver -> SimpProp -> IO ()
assert _ (SimpProp PTrue) = return ()
assert s@Solver { .. } p@(SimpProp p0) =
do debugLog s ("Assuming: " ++ show (ppProp p0))
ps1' <- atomicModifyIORef' declared (viAssert p)
let ps1 = map unSimpProp ps1'
vs = Set.toList $ Set.unions $ map cryPropFVS ps1
mapM_ (declareVar s) vs
mapM_ (SMT.assert solver . ifPropToSmtLib . desugarProp) ps1
-- | Try to prove a property. The result is 'True' when we are sure that
-- the property holds, and 'False' otherwise. In other words, getting `False`
-- *does not* mean that the proposition does not hold.
prove :: Solver -> Prop -> IO Bool
prove _ PTrue = return True
prove s@(Solver { .. }) p =
debugBlock s ("Proving: " ++ show (ppProp p)) $
withScope s $
do assert s (simpProp (Not p))
res <- SMT.check solver
case res of
SMT.Unsat -> debugLog s "Proved" >> return True
SMT.Unknown -> debugLog s "Not proved" >> return False -- We are not sure
SMT.Sat -> debugLog s "Not proved" >> return False
-- XXX: If the answer is Sat, it is possible that this is a
-- a fake example, as we need to evaluate the nonLinear constraints.
-- If they are all satisfied, then we have a genuine counter example.
-- Otherwise, we could look for another one...
{- | Check if the current set of assumptions is satisfiable, and find
some facts that must hold in any models of the current assumptions.
Returns `Nothing` if the currently asserted constraints are known to
be unsatisfiable.
Returns `Just (su, sub-goals)` is the current set is satisfiable.
* The `su` is a substitution that may be applied to the current constraint
set without loosing generality.
* The `sub-goals` are additional constraints that must hold if the
constraint set is to be satisfiable.
-}
check :: Solver -> IO (Maybe (Subst, [Prop]))
check s@Solver { .. } =
do res <- SMT.check solver
case res of
SMT.Unsat ->
do debugLog s "Not satisfiable"
return Nothing
SMT.Unknown ->
do debugLog s "Unknown"
return (Just (Map.empty, []))
SMT.Sat ->
do debugLog s "Satisfiable"
(impMap,sideConds) <- debugBlock s "Computing improvements"
(getImpSubst s)
return (Just (impMap, sideConds))
{- | Assuming that we are in a satisfiable state, try to compute an
improving substitution. We also return additional constraints that must
hold for the currently asserted propositions to hold.
-}
getImpSubst :: Solver -> IO (Subst,[Prop])
getImpSubst s@Solver { .. } =
do names <- viUnmarkedNames `fmap` readIORef declared
m <- getVals solver names
(impSu,sideConditions) <- cryImproveModel solver logger m
nlSu <- getNLSubst s
let isNonLinName (SysName {}) = True
isNonLinName (UserName {}) = False
(nlFacts, vFacts) = Map.partitionWithKey (\k _ -> isNonLinName k) impSu
(vV, vNL) = Map.partition noNLVars vFacts
nlSu1 = fmap (doAppSubst vV) nlSu
(vNL_su,vNL_eqs) = Map.partitionWithKey goodDef
$ fmap (doAppSubst nlSu1) vNL
nlSu2 = fmap (doAppSubst vNL_su) nlSu1
nlLkp x = case Map.lookup x nlSu2 of
Just e -> e
Nothing -> panic "getImpSubst"
[ "Missing NL variable:", show x ]
allSides =
[ Var a :== e | (a,e) <- Map.toList vNL_eqs ] ++
[ nlLkp x :== doAppSubst nlSu2 e | (x,e) <- Map.toList nlFacts ] ++
[ doAppSubst nlSu2 si | si <- sideConditions ]
theImpSu = composeSubst vNL_su vV
debugBlock s "Improvments" $
do debugBlock s "substitution" $
mapM_ (debugLog s . dump) (Map.toList theImpSu)
debugBlock s "side-conditions" $ debugLog s allSides
return (theImpSu, allSides)
where
goodDef k e = not (k `Set.member` cryExprFVS e)
isNLVar (SysName _) = True
isNLVar _ = False
noNLVars e = all (not . isNLVar) (cryExprFVS e)
dump (x,e) = show (ppProp (Var x :== e))
--------------------------------------------------------------------------------
debugBlock :: Solver -> String -> IO a -> IO a
debugBlock s@Solver { .. } name m =
do debugLog s name
SMT.logTab logger
a <- m
SMT.logUntab logger
return a
class DebugLog t where
debugLog :: Solver -> t -> IO ()
debugLogList :: Solver -> [t] -> IO ()
debugLogList s ts = case ts of
[] -> debugLog s "(none)"
_ -> mapM_ (debugLog s) ts
instance DebugLog Char where
debugLog s x = SMT.logMessage (logger s) (show x)
debugLogList s x = SMT.logMessage (logger s) x
instance DebugLog a => DebugLog [a] where
debugLog = debugLogList
instance DebugLog a => DebugLog (Maybe a) where
debugLog s x = case x of
Nothing -> debugLog s "(nothing)"
Just a -> debugLog s a
instance DebugLog Doc where
debugLog s x = debugLog s (show x)
instance DebugLog Cry.Type where
debugLog s x = debugLog s (pp x)
instance DebugLog Goal where
debugLog s x = debugLog s (goal x)
instance DebugLog Cry.Subst where
debugLog s x = debugLog s (pp x)
instance DebugLog Prop where
debugLog s x = debugLog s (ppProp x)
|
ntc2/cryptol
|
src/Cryptol/TypeCheck/Solver/CrySAT.hs
|
Haskell
|
bsd-3-clause
| 21,839
|
module GHCJS.DOM.HTMLInputElement where
data HTMLInputElement = HTMLInputElement
class IsHTMLInputElement a
instance IsHTMLInputElement HTMLInputElement
ghcjs_dom_html_input_element_step_up = undefined
htmlInputElementStepUp = undefined
ghcjs_dom_html_input_element_step_down = undefined
htmlInputElementStepDown = undefined
ghcjs_dom_html_input_element_check_validity = undefined
htmlInputElementCheckValidity = undefined
ghcjs_dom_html_input_element_set_custom_validity = undefined
htmlInputElementSetCustomValidity = undefined
ghcjs_dom_html_input_element_select = undefined
htmlInputElementSelect = undefined
ghcjs_dom_html_input_element_set_range_text = undefined
htmlInputElementSetRangeText = undefined
ghcjs_dom_html_input_element_set_range_text4 = undefined
htmlInputElementSetRangeText4 = undefined
ghcjs_dom_html_input_element_set_value_for_user = undefined
htmlInputElementSetValueForUser = undefined
ghcjs_dom_html_input_element_set_accept = undefined
htmlInputElementSetAccept = undefined
ghcjs_dom_html_input_element_get_accept = undefined
htmlInputElementGetAccept = undefined
ghcjs_dom_html_input_element_set_alt = undefined
htmlInputElementSetAlt = undefined
ghcjs_dom_html_input_element_get_alt = undefined
htmlInputElementGetAlt = undefined
ghcjs_dom_html_input_element_set_autocomplete = undefined
htmlInputElementSetAutocomplete = undefined
ghcjs_dom_html_input_element_get_autocomplete = undefined
htmlInputElementGetAutocomplete = undefined
ghcjs_dom_html_input_element_set_autofocus = undefined
htmlInputElementSetAutofocus = undefined
ghcjs_dom_html_input_element_get_autofocus = undefined
htmlInputElementGetAutofocus = undefined
ghcjs_dom_html_input_element_set_default_checked = undefined
htmlInputElementSetDefaultChecked = undefined
ghcjs_dom_html_input_element_get_default_checked = undefined
htmlInputElementGetDefaultChecked = undefined
ghcjs_dom_html_input_element_set_checked = undefined
htmlInputElementSetChecked = undefined
ghcjs_dom_html_input_element_get_checked = undefined
htmlInputElementGetChecked = undefined
ghcjs_dom_html_input_element_set_dir_name = undefined
htmlInputElementSetDirName = undefined
ghcjs_dom_html_input_element_get_dir_name = undefined
htmlInputElementGetDirName = undefined
ghcjs_dom_html_input_element_set_disabled = undefined
htmlInputElementSetDisabled = undefined
ghcjs_dom_html_input_element_get_disabled = undefined
htmlInputElementGetDisabled = undefined
ghcjs_dom_html_input_element_get_form = undefined
htmlInputElementGetForm = undefined
ghcjs_dom_html_input_element_set_files = undefined
htmlInputElementSetFiles = undefined
ghcjs_dom_html_input_element_get_files = undefined
htmlInputElementGetFiles = undefined
ghcjs_dom_html_input_element_set_form_action = undefined
htmlInputElementSetFormAction = undefined
ghcjs_dom_html_input_element_get_form_action = undefined
htmlInputElementGetFormAction = undefined
ghcjs_dom_html_input_element_set_form_enctype = undefined
htmlInputElementSetFormEnctype = undefined
ghcjs_dom_html_input_element_get_form_enctype = undefined
htmlInputElementGetFormEnctype = undefined
ghcjs_dom_html_input_element_set_form_method = undefined
htmlInputElementSetFormMethod = undefined
ghcjs_dom_html_input_element_get_form_method = undefined
htmlInputElementGetFormMethod = undefined
ghcjs_dom_html_input_element_set_form_no_validate = undefined
htmlInputElementSetFormNoValidate = undefined
ghcjs_dom_html_input_element_get_form_no_validate = undefined
htmlInputElementGetFormNoValidate = undefined
ghcjs_dom_html_input_element_set_form_target = undefined
htmlInputElementSetFormTarget = undefined
ghcjs_dom_html_input_element_get_form_target = undefined
htmlInputElementGetFormTarget = undefined
ghcjs_dom_html_input_element_set_height = undefined
htmlInputElementSetHeight = undefined
ghcjs_dom_html_input_element_get_height = undefined
htmlInputElementGetHeight = undefined
ghcjs_dom_html_input_element_set_indeterminate = undefined
htmlInputElementSetIndeterminate = undefined
ghcjs_dom_html_input_element_get_indeterminate = undefined
htmlInputElementGetIndeterminate = undefined
ghcjs_dom_html_input_element_get_list = undefined
htmlInputElementGetList = undefined
ghcjs_dom_html_input_element_set_max = undefined
htmlInputElementSetMax = undefined
ghcjs_dom_html_input_element_get_max = undefined
htmlInputElementGetMax = undefined
ghcjs_dom_html_input_element_set_max_length = undefined
htmlInputElementSetMaxLength = undefined
ghcjs_dom_html_input_element_get_max_length = undefined
htmlInputElementGetMaxLength = undefined
ghcjs_dom_html_input_element_set_min = undefined
htmlInputElementSetMin = undefined
ghcjs_dom_html_input_element_get_min = undefined
htmlInputElementGetMin = undefined
ghcjs_dom_html_input_element_set_multiple = undefined
htmlInputElementSetMultiple = undefined
ghcjs_dom_html_input_element_get_multiple = undefined
htmlInputElementGetMultiple = undefined
ghcjs_dom_html_input_element_set_name = undefined
htmlInputElementSetName = undefined
ghcjs_dom_html_input_element_get_name = undefined
htmlInputElementGetName = undefined
ghcjs_dom_html_input_element_set_pattern = undefined
htmlInputElementSetPattern = undefined
ghcjs_dom_html_input_element_get_pattern = undefined
htmlInputElementGetPattern = undefined
ghcjs_dom_html_input_element_set_placeholder = undefined
htmlInputElementSetPlaceholder = undefined
ghcjs_dom_html_input_element_get_placeholder = undefined
htmlInputElementGetPlaceholder = undefined
ghcjs_dom_html_input_element_set_read_only = undefined
htmlInputElementSetReadOnly = undefined
ghcjs_dom_html_input_element_get_read_only = undefined
htmlInputElementGetReadOnly = undefined
ghcjs_dom_html_input_element_set_required = undefined
htmlInputElementSetRequired = undefined
ghcjs_dom_html_input_element_get_required = undefined
htmlInputElementGetRequired = undefined
ghcjs_dom_html_input_element_set_size = undefined
htmlInputElementSetSize = undefined
ghcjs_dom_html_input_element_get_size = undefined
htmlInputElementGetSize = undefined
ghcjs_dom_html_input_element_set_src = undefined
htmlInputElementSetSrc = undefined
ghcjs_dom_html_input_element_get_src = undefined
htmlInputElementGetSrc = undefined
ghcjs_dom_html_input_element_set_step = undefined
htmlInputElementSetStep = undefined
ghcjs_dom_html_input_element_get_step = undefined
htmlInputElementGetStep = undefined
ghcjs_dom_html_input_element_set_default_value = undefined
htmlInputElementSetDefaultValue = undefined
ghcjs_dom_html_input_element_get_default_value = undefined
htmlInputElementGetDefaultValue = undefined
ghcjs_dom_html_input_element_set_value = undefined
htmlInputElementSetValue = undefined
ghcjs_dom_html_input_element_get_value = undefined
htmlInputElementGetValue = undefined
ghcjs_dom_html_input_element_set_value_as_number = undefined
htmlInputElementSetValueAsNumber = undefined
ghcjs_dom_html_input_element_get_value_as_number = undefined
htmlInputElementGetValueAsNumber = undefined
ghcjs_dom_html_input_element_set_width = undefined
htmlInputElementSetWidth = undefined
ghcjs_dom_html_input_element_get_width = undefined
htmlInputElementGetWidth = undefined
ghcjs_dom_html_input_element_get_will_validate = undefined
htmlInputElementGetWillValidate = undefined
ghcjs_dom_html_input_element_get_validity = undefined
htmlInputElementGetValidity = undefined
ghcjs_dom_html_input_element_get_validation_message = undefined
htmlInputElementGetValidationMessage = undefined
ghcjs_dom_html_input_element_get_labels = undefined
htmlInputElementGetLabels = undefined
ghcjs_dom_html_input_element_set_align = undefined
htmlInputElementSetAlign = undefined
ghcjs_dom_html_input_element_get_align = undefined
htmlInputElementGetAlign = undefined
ghcjs_dom_html_input_element_set_use_map = undefined
htmlInputElementSetUseMap = undefined
ghcjs_dom_html_input_element_get_use_map = undefined
htmlInputElementGetUseMap = undefined
ghcjs_dom_html_input_element_set_incremental = undefined
htmlInputElementSetIncremental = undefined
ghcjs_dom_html_input_element_get_incremental = undefined
htmlInputElementGetIncremental = undefined
ghcjs_dom_html_input_element_set_autocorrect = undefined
htmlInputElementSetAutocorrect = undefined
ghcjs_dom_html_input_element_get_autocorrect = undefined
htmlInputElementGetAutocorrect = undefined
ghcjs_dom_html_input_element_set_autocapitalize = undefined
htmlInputElementSetAutocapitalize = undefined
ghcjs_dom_html_input_element_get_autocapitalize = undefined
htmlInputElementGetAutocapitalize = undefined
ghcjs_dom_html_input_element_set_capture = undefined
htmlInputElementSetCapture = undefined
ghcjs_dom_html_input_element_get_capture = undefined
htmlInputElementGetCapture = undefined
castToHTMLInputElement = undefined
gTypeHTMLInputElement = undefined
toHTMLInputElement = undefined
|
mightybyte/reflex-dom-stubs
|
src/GHCJS/DOM/HTMLInputElement.hs
|
Haskell
|
bsd-3-clause
| 8,767
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
module Web.Spock.Api.Client (callEndpoint, callEndpoint') where
import qualified Data.Aeson as A
import qualified Data.ByteString.Lazy as BSL
import Data.HVect
import qualified Data.HVect as HV
import qualified Data.JSString as J
import qualified Data.JSString.Text as J
import qualified Data.Text.Encoding as T
import JavaScript.Web.XMLHttpRequest
import Web.Spock.Api
type Header = (J.JSString, J.JSString)
-- | Call an 'Endpoint' defined using the @Spock-api@ package passing extra headers
callEndpoint' ::
forall p i o.
(HasRep (MaybeToList i), HasRep p) =>
Endpoint p i o ->
[Header] ->
HVectElim p (HVectElim (MaybeToList i) (IO (Maybe o)))
callEndpoint' ep extraHeaders =
HV.curry $ \hv -> HV.curry (callEndpointCore' ep extraHeaders hv)
-- | Call an 'Endpoint' defined using the @Spock-api@ package
callEndpoint ::
forall p i o.
(HasRep (MaybeToList i), HasRep p) =>
Endpoint p i o ->
HVectElim p (HVectElim (MaybeToList i) (IO (Maybe o)))
callEndpoint ep = callEndpoint' ep []
data EndpointCall p i o = EndpointCall
{ epc_point :: !(Endpoint p i o),
epc_headers :: ![Header],
epc_params :: !(HVect p),
epc_body :: !(HVect (MaybeToList i))
}
callEndpointCore' ::
forall p i o.
Endpoint p i o ->
[Header] ->
HVect p ->
HVect (MaybeToList i) ->
IO (Maybe o)
callEndpointCore' ep hdrs hv b = callEndpointCore (EndpointCall ep hdrs hv b)
callEndpointCore :: forall p i o. EndpointCall p i o -> IO (Maybe o)
callEndpointCore call =
case call of
EndpointCall (MethodPost Proxy path) hdrs params (body :&: HNil) ->
do
let rt = J.textToJSString $ renderRoute path params
bodyText = J.textToJSString $ T.decodeUtf8 $ BSL.toStrict $ A.encode body
req =
Request
{ reqMethod = POST,
reqURI = rt,
reqLogin = Nothing,
reqHeaders = (("Content-Type", "application/json;charset=UTF-8") : hdrs),
reqWithCredentials = False,
reqData = StringData bodyText
}
runJsonReq req
EndpointCall (MethodPut Proxy path) hdrs params (body :&: HNil) ->
do
let rt = J.textToJSString $ renderRoute path params
bodyText = J.textToJSString $ T.decodeUtf8 $ BSL.toStrict $ A.encode body
req =
Request
{ reqMethod = PUT,
reqURI = rt,
reqLogin = Nothing,
reqHeaders = (("Content-Type", "application/json;charset=UTF-8") : hdrs),
reqWithCredentials = False,
reqData = StringData bodyText
}
runJsonReq req
EndpointCall (MethodGet path) hdrs params HNil ->
do
let rt = J.textToJSString $ renderRoute path params
req =
Request
{ reqMethod = GET,
reqURI = rt,
reqLogin = Nothing,
reqHeaders = hdrs,
reqWithCredentials = False,
reqData = NoData
}
runJsonReq req
runJsonReq :: A.FromJSON o => Request -> IO (Maybe o)
runJsonReq req =
do
response <- xhrText req
case (status response, contents response) of
(200, Just txt) ->
do
let res = A.eitherDecodeStrict' (T.encodeUtf8 txt)
case res of
Left errMsg ->
do
putStrLn errMsg
pure Nothing
Right val ->
pure (Just val)
_ -> pure Nothing
|
agrafix/Spock
|
Spock-api-ghcjs/src/Web/Spock/Api/Client.hs
|
Haskell
|
bsd-3-clause
| 3,862
|
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.GL.IBM.MultimodeDrawArrays
-- Copyright : (c) Sven Panne 2019
-- License : BSD3
--
-- Maintainer : Sven Panne <svenpanne@gmail.com>
-- Stability : stable
-- Portability : portable
--
--------------------------------------------------------------------------------
module Graphics.GL.IBM.MultimodeDrawArrays (
-- * Extension Support
glGetIBMMultimodeDrawArrays,
gl_IBM_multimode_draw_arrays,
-- * Functions
glMultiModeDrawArraysIBM,
glMultiModeDrawElementsIBM
) where
import Graphics.GL.ExtensionPredicates
import Graphics.GL.Functions
|
haskell-opengl/OpenGLRaw
|
src/Graphics/GL/IBM/MultimodeDrawArrays.hs
|
Haskell
|
bsd-3-clause
| 676
|
{-# LANGUAGE CPP #-}
{-# LANGUAGE UnicodeSyntax #-}
module Shake.It.C.Make
( make
, configure
, nmake
, vcshell
) where
import Control.Monad
import Shake.It.Core
import System.Environment
configure ∷ [String] → IO ()
configure α = rawSystem "configure" α >>= checkExitCode
make ∷ [String] → IO ()
make α = rawSystem "make" α >>= checkExitCode
vcshell ∷ [String] → IO String
nmake ∷ [String] → IO ()
#if ( defined(mingw32_HOST_OS) || defined(__MINGW32__) )
vcshell [x] = do
common ← getEnv $ "VS" ++ x ++ "COMNTOOLS"
return $ common </> ".." </> ".."
</> "VC"
</> "vcvarsall.bat"
vcshell (x:xs) = do
vcx ← vcshell [x]
if vcx /= [] then return vcx
else vcshell xs
vcshell [] = return []
nmake α = rawSystem "nmake" α >>= checkExitCode
#else
vcshell _ = return []
nmake _ = return ()
#endif
|
Heather/Shake.it.off
|
src/Shake/It/C/Make.hs
|
Haskell
|
bsd-3-clause
| 938
|
{-# LANGUAGE OverloadedStrings #-}
-------------------------------------------------------------------------------
-- |
-- Module : Generator.Primer.Modern
-- Copyright : (c) 2016 Michael Carpenter
-- License : BSD3
-- Maintainer : Michael Carpenter <oldmanmike.dev@gmail.com>
-- Stability : experimental
-- Portability : portable
--
-------------------------------------------------------------------------------
module Generator.Primer.Modern
( primeModernProtocol
) where
import Data.List
import Generator.Parser
import Generator.Primer.Common
import Generator.Types
primeModernProtocol :: ExtractedVersion
-> ExtractedModernProtocol
-> Either String ModernProtocol
primeModernProtocol ev ep = do
let v = mkProtocolVersion ev
let lstGettersAndBoundTos =
[ modernClientBoundHandshaking , modernServerBoundHandshaking
, modernClientBoundStatus , modernServerBoundStatus
, modernClientBoundLogin , modernServerBoundLogin
, modernClientBoundPlay , modernServerBoundPlay
]
let lstMaybeMetadata =
fmap
(\getter -> getMetadataSection . getter $ ep)
lstGettersAndBoundTos
let lstMaybeNames =
(fmap . fmap)
getNameMap
lstMaybeMetadata
let lstMaybeIds =
(fmap . fmap)
getIdMap
lstMaybeMetadata
let lstLstPackets =
fmap
(\getter -> getPacketSection . getter $ ep)
lstGettersAndBoundTos
let lstPacketSectionMetadata =
zip4
lstMaybeNames
lstMaybeIds
lstLstPackets
((concat . repeat) [ClientBound,ServerBound])
let maybePrimedProto =
fmap sequence $ sequence
$ fmap
(\(a,b,c,d) ->
mkPacketSection
<$> a -- names map
<*> b -- ids map
<*> return c -- packet list
<*> return d -- packet direction
)
lstPacketSectionMetadata
case maybePrimedProto of
Nothing -> Left "Error: Something went wrong!"
Just primedProto ->
case primedProto of
Nothing -> Left "Error: Packet section primer failure!"
Just primedSections -> do
Right $ ModernProtocol
v
(primedSections !! 0)
(primedSections !! 1)
(primedSections !! 2)
(primedSections !! 3)
(primedSections !! 4)
(primedSections !! 5)
(primedSections !! 6)
(primedSections !! 7)
where
mkPacketSection nMap idMap pktLst boundTo =
fmap (sortOn pId) $ sequence $
fmap
(\x -> mkPacket nMap idMap pktLst (ePacketName x) boundTo)
pktLst
|
oldmanmike/hs-minecraft-protocol
|
generate/src/Generator/Primer/Modern.hs
|
Haskell
|
bsd-3-clause
| 2,953
|
{-# LANGUAGE DataKinds, PolyKinds, TypeFamilies, TypeOperators, OverloadedStrings #-}
module Database.Edis.Command.Hash where
import Database.Edis.Type
import Database.Edis.Helper
import Data.ByteString (ByteString)
import Data.Proxy (Proxy)
import Data.Serialize (Serialize, encode)
import Data.Type.Bool
import Database.Redis as Redis hiding (decode)
import GHC.TypeLits
--------------------------------------------------------------------------------
-- Hashes
--------------------------------------------------------------------------------
hdel :: (KnownSymbol k, KnownSymbol f, HashOrNX xs k)
=> Proxy k -> Proxy f
-> Edis xs (DelHash xs k f) (Either Reply Integer)
hdel key field = Edis $ Redis.hdel (encodeKey key) [encodeKey field]
hexists :: (KnownSymbol k, KnownSymbol f, HashOrNX xs k)
=> Proxy k -> Proxy f
-> Edis xs xs (Either Reply Bool)
hexists key field = Edis $ Redis.hexists (encodeKey key) (encodeKey field)
hget :: (KnownSymbol k, KnownSymbol f, Serialize x
, 'Just (StringOf x) ~ GetHash xs k f)
=> Proxy k -> Proxy f
-> Edis xs xs (Either Reply (Maybe x))
hget key field = Edis $ Redis.hget (encodeKey key) (encodeKey field) >>= decodeAsMaybe
hincrby :: (KnownSymbol k, KnownSymbol f, HashOrNX xs k)
=> Proxy k -> Proxy f -> Integer
-> Edis xs (SetHash xs k f Integer) (Either Reply Integer)
hincrby key field n = Edis $ Redis.hincrby (encodeKey key) (encodeKey field) n
hincrbyfloat :: (KnownSymbol k, KnownSymbol f, HashOrNX xs k)
=> Proxy k -> Proxy f -> Double
-> Edis xs (SetHash xs k f Double) (Either Reply Double)
hincrbyfloat key field n = Edis $ Redis.hincrbyfloat (encodeKey key) (encodeKey field) n
hkeys :: (KnownSymbol k, HashOrNX xs k)
=> Proxy k
-> Edis xs xs (Either Reply [ByteString])
hkeys key = Edis $ Redis.hkeys (encodeKey key)
hlen :: (KnownSymbol k, HashOrNX xs k)
=> Proxy k
-> Edis xs xs (Either Reply Integer)
hlen key = Edis $ Redis.hlen (encodeKey key)
hset :: (KnownSymbol k, KnownSymbol f, Serialize x, HashOrNX xs k)
=> Proxy k -> Proxy f -> x
-> Edis xs (SetHash xs k f (StringOf x)) (Either Reply Bool)
hset key field val = Edis $ Redis.hset (encodeKey key) (encodeKey field) (encode val)
hsetnx :: (KnownSymbol k, KnownSymbol f, Serialize x, HashOrNX xs k)
=> Proxy k -> Proxy f -> x
-> Edis xs (If (MemHash xs k f) xs (SetHash xs k f (StringOf x))) (Either Reply Bool)
hsetnx key field val = Edis $ Redis.hsetnx (encodeKey key) (encodeKey field) (encode val)
|
banacorn/tredis
|
src/Database/Edis/Command/Hash.hs
|
Haskell
|
mit
| 2,619
|
{-# LANGUAGE RecordWildCards, ViewPatterns, TupleSections, PatternGuards #-}
module General.Log(
Log, logCreate, logNone, logAddMessage, logAddEntry,
Summary(..), logSummary,
) where
import Control.Concurrent.Extra
import Control.Applicative
import System.IO
import Data.Time.Calendar
import Data.Time.Clock
import Numeric.Extra
import Control.Monad.Extra
import qualified Data.Set as Set
import qualified Data.Map.Strict as Map
import qualified Data.ByteString.Lazy.Char8 as LBS
import Data.Monoid
import General.Util
import Data.Maybe
import Data.List
import Data.IORef
import Prelude
data Log = Log
{logOutput :: Maybe (Var Handle)
,logCurrent :: IORef (Map.Map Day SummaryI)
,logInteresting :: String -> Bool
}
showTime :: UTCTime -> String
showTime = showUTCTime "%Y-%m-%dT%H:%M:%S%Q"
logNone :: IO Log
logNone = do ref <- newIORef Map.empty; return $ Log Nothing ref (const False)
logCreate :: Either Handle FilePath -> (String -> Bool) -> IO Log
logCreate store interesting = do
(h, old) <- case store of
Left h -> return (h, Map.empty)
Right file -> do
mp <- withFile file ReadMode $ \h -> do
src <- LBS.hGetContents h
let xs = mapMaybe (parseLogLine interesting) $ LBS.lines $ src
return $! foldl' (\mp (k,v) -> Map.alter (Just . maybe v (<> v)) k mp) Map.empty xs
(,mp) <$> openFile file AppendMode
hSetBuffering h LineBuffering
var <- newVar h
ref <- newIORef old
return $ Log (Just var) ref interesting
logAddMessage :: Log -> String -> IO ()
logAddMessage Log{..} msg = do
time <- showTime <$> getCurrentTime
whenJust logOutput $ \var -> withVar var $ \h ->
hPutStrLn h $ time ++ " - " ++ msg
logAddEntry :: Log -> String -> String -> Double -> Maybe String -> IO ()
logAddEntry Log{..} user question taken err = do
time <- getCurrentTime
let add v = atomicModifyIORef logCurrent $ \mp -> (Map.alter (Just . maybe v (<> v)) (utctDay time) mp, ())
if logInteresting question then
add $ SummaryI (Set.singleton user) 1 taken (toAverage taken) (if isJust err then 1 else 0)
else if isJust err then
add mempty{iErrors=1}
else
return ()
whenJust logOutput $ \var -> withVar var $ \h ->
hPutStrLn h $ unwords $ [showTime time, user, showDP 3 taken, question] ++
maybeToList (fmap ((++) "ERROR: " . unwords . words) err)
-- Summary collapsed
data Summary = Summary
{summaryDate :: Day
,summaryUsers :: Int
,summaryUses :: Int
,summarySlowest :: Double
,summaryAverage :: Double
,summaryErrors :: Int
}
-- Summary accumulating
data SummaryI = SummaryI
{iUsers :: !(Set.Set String) -- number of distinct users
,iUses :: !Int -- number of uses
,iSlowest :: !Double -- slowest result
,iAverage :: !(Average Double) -- average result
,iErrors :: !Int -- number of errors
}
instance Monoid SummaryI where
mempty = SummaryI Set.empty 0 0 (toAverage 0) 0
mappend (SummaryI x1 x2 x3 x4 x5) (SummaryI y1 y2 y3 y4 y5) =
SummaryI (f x1 y1) (x2+y2) (max x3 y3) (x4 <> y4) (x5+y5)
-- more efficient union for the very common case of a single element
where f x y | Set.size x == 1 = Set.insert (head $ Set.toList x) y
| Set.size y == 1 = Set.insert (head $ Set.toList y) x
| otherwise = Set.union x y
summarize :: Day -> SummaryI -> Summary
summarize date SummaryI{..} = Summary date (Set.size iUsers) iUses iSlowest (fromAverage iAverage) iErrors
parseLogLine :: (String -> Bool) -> LBS.ByteString -> Maybe (Day, SummaryI)
parseLogLine interesting (LBS.words -> time:user:dur:query:err)
| user /= LBS.pack "-"
, Just [a, b, c] <- fmap (map fst) $ mapM LBS.readInt $ LBS.split '-' $ LBS.takeWhile (/= 'T') time
= Just (fromGregorian (fromIntegral a) b c, SummaryI
(if use then Set.singleton $ LBS.unpack user else Set.empty)
(if use then 1 else 0)
(if use then dur2 else 0)
(toAverage $ if use then dur2 else 0)
(if [LBS.pack "ERROR:"] `isPrefixOf` err then 1 else 0))
where use = interesting $ LBS.unpack query
dur2 = let s = LBS.unpack dur in fromMaybe 0 $
if '.' `elem` s then readMaybe s else (/ 1000) . intToDouble <$> readMaybe s
parseLogLine _ _ = Nothing
logSummary :: Log -> IO [Summary]
logSummary Log{..} = map (uncurry summarize) . Map.toAscList <$> readIORef logCurrent
|
BartAdv/hoogle
|
src/General/Log.hs
|
Haskell
|
bsd-3-clause
| 4,539
|
{-# LANGUAGE BangPatterns #-}
-- A simple wc-like program using Data.Iteratee.
-- Demonstrates a few different ways of composing iteratees.
module Main where
import Prelude as P
import Data.Iteratee
import Data.Iteratee.Char as C
import qualified Data.Iteratee as I
import qualified Data.ByteString.Char8 as BC
import Data.Word
import Data.Char
import Data.ListLike as LL
import System.Environment
-- | An iteratee to calculate the number of characters in a stream.
-- Very basic, assumes ASCII, not particularly efficient.
numChars :: (Monad m, ListLike s el) => I.Iteratee s m Int
numChars = I.length
-- | An iteratee to calculate the number of words in a stream of Word8's.
-- this operates on a Word8 stream in order to use ByteStrings.
--
-- This function converts the stream of Word8s into a stream of words,
-- then counts the words with Data.Iteratee.length
-- This is the equivalent of "length . BC.words".
numWords :: Monad m => I.Iteratee BC.ByteString m Int
numWords = I.joinI $ enumWordsBS I.length
-- | Count the number of lines, in the same manner as numWords.
numLines :: Monad m => I.Iteratee BC.ByteString m Int
numLines = I.joinI $ enumLinesBS I.length
-- | A much more efficient numLines using the foldl' iteratee.
-- Rather than converting a stream, this simply counts newline characters.
numLines2 :: Monad m => I.Iteratee BC.ByteString m Int
numLines2 = I.foldl' step 0
where
step !acc el = if el == (fromIntegral $ ord '\n') then acc + 1 else acc
-- | Combine multiple iteratees into a single unit using "enumPair".
-- The iteratees combined with enumPair are run in parallel.
-- Any number of iteratees can be joined with multiple enumPair's.
twoIter :: Monad m => I.Iteratee BC.ByteString m (Int, Int)
twoIter = numLines2 `I.zip` numChars
main = do
f:_ <- getArgs
words <- fileDriverVBuf 65536 twoIter f
print words
|
iteloo/tsuru-sample
|
iteratee-0.8.9.6/Examples/word.hs
|
Haskell
|
bsd-3-clause
| 1,862
|
{-# LANGUAGE ScopedTypeVariables #-}
module Main where
import GHC.Conc
import Control.Exception
-- Create trivial invariants using a single TVar
main = do
putStr "\nStarting\n"
x <- atomically ( newTVar 42 )
putStr "\nAdding trivially true invariant (no TVar access)\n"
atomically ( alwaysSucceeds ( return 1 ) )
putStr "\nAdding trivially true invariant (no TVar access)\n"
atomically ( always ( return True ) )
putStr "\nAdding a trivially true invariant (TVar access)\n"
atomically ( alwaysSucceeds ( readTVar x ) )
putStr "\nAdding an invariant that's false when attempted to be added\n"
Control.Exception.catch (atomically ( do writeTVar x 100
alwaysSucceeds ( do v <- readTVar x
if (v == 100) then throw (ErrorCall "URK") else return () )
writeTVar x 0 ) )
(\(e::SomeException) -> putStr ("Caught: " ++ (show e) ++ "\n"))
putStr "\nWriting to a TVar watched by a trivially true invariant\n"
atomically ( writeTVar x 17 )
putStr "\nAdding a second trivially true invariant (same TVar access)\n"
atomically ( alwaysSucceeds ( readTVar x ) )
putStr "\nWriting to a TVar watched by both trivially true invariants\n"
atomically ( writeTVar x 18 )
putStr "\nAdding a trivially false invariant (no TVar access)\n"
Control.Exception.catch (atomically ( alwaysSucceeds ( throw (ErrorCall "Exn raised in invariant") ) ) )
(\(e::SomeException) -> putStr ("Caught: " ++ (show e) ++ "\n"))
putStr "\nAdding a trivially false invariant (no TVar access)\n"
Control.Exception.catch (atomically ( always ( throw (ErrorCall "Exn raised in invariant") ) ) )
(\(e::SomeException) -> putStr ("Caught: " ++ (show e) ++ "\n"))
putStr "\nAdding a trivially false invariant (no TVar access)\n"
Control.Exception.catch (atomically ( always ( return False ) ) )
(\(e::SomeException) -> putStr ("Caught: " ++ (show e) ++ "\n"))
putStr "\nAdding a trivially false invariant (with TVar access)\n"
Control.Exception.catch (atomically (
alwaysSucceeds ( do t <- readTVar x
throw (ErrorCall "Exn raised in invariant") ) ) )
(\(e::SomeException) -> putStr ("Caught: " ++ (show e) ++ "\n"))
putStr "\nAdding a third invariant true if TVar != 42\n"
atomically ( alwaysSucceeds ( do t <- readTVar x
if (t == 42) then throw (ErrorCall "Exn raised in invariant") else return () ) )
putStr "\nViolating third invariant by setting TVar to 42\n"
Control.Exception.catch (atomically ( writeTVar x 42 ) )
(\(e::SomeException) -> putStr ("Caught: " ++ (show e) ++ "\n"))
putStr "\nChecking final TVar contents\n"
t <- atomically ( readTVar x )
putStr ("Final value = " ++ (show t) ++ "\n")
putStr "\nDone\n"
|
gridaphobe/packages-stm
|
tests/stm060.hs
|
Haskell
|
bsd-3-clause
| 2,923
|
{-# LANGUAGE ParallelListComp, BangPatterns #-}
import Solver
import Graphics.Gloss
import System.Environment
import Data.Maybe
import qualified Data.Vector as V
import qualified Data.Vector.Unboxed as VU
main :: IO ()
main
= do args <- getArgs
mainWithArgs args
mainWithArgs :: [String] -> IO ()
mainWithArgs [solverName,depthStr]
= let -- The solver we're using to calculate the acclerations.
solver = fromMaybe (error $ unlines
[ "unknown solver " ++ show solverName
, "choose one of " ++ (show $ map fst solvers) ])
$ lookup solverName solvers
depth = read depthStr
in mainGloss depth solver 400
mainWithArgs [solverName] = mainWithArgs [solverName,"4"]
mainWithArgs _ = putStrLn "Usage: rotations <vector|vectorised> <depth>"
-- | Run the simulation in a gloss window.
mainGloss
:: Int -- ^ Depth
-> Solver -- ^ Fn to calculate accels of each point.
-> Int -- ^ Size of window.
-> IO ()
mainGloss depth solver windowSize
= let draw t
= let pts = solver depth (realToFrac t)
in Color white $ Pictures $ map drawPoint $ VU.toList pts
in animate
(InWindow "Silly" -- window name
(windowSize, windowSize) -- window size
(10, 10)) -- window position
black -- background color
draw -- fn to convert a world to a picture
pointSize = 4
drawPoint :: (Double, Double) -> Picture
drawPoint (x, y)
= Translate (realToFrac x * 50) (realToFrac y * 50)
$ ThickCircle (pointSize / 2) pointSize
|
mainland/dph
|
dph-examples/examples/spectral/Rotation/MainGloss.hs
|
Haskell
|
bsd-3-clause
| 1,901
|
{-# LANGUAGE Haskell98, CPP, DeriveDataTypeable, ForeignFunctionInterface, TypeSynonymInstances #-}
{-# LINE 1 "dist/dist-sandbox-261cd265/build/Network/Socket.hs" #-}
{-# LINE 1 "Network/Socket.hsc" #-}
{-# LANGUAGE CPP, ScopedTypeVariables #-}
{-# LINE 2 "Network/Socket.hsc" #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
-----------------------------------------------------------------------------
-- |
-- Module : Network.Socket
-- Copyright : (c) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/network/LICENSE)
--
-- Maintainer : libraries@haskell.org
-- Stability : provisional
-- Portability : portable
--
-- The "Network.Socket" module is for when you want full control over
-- sockets. Essentially the entire C socket API is exposed through
-- this module; in general the operations follow the behaviour of the C
-- functions of the same name (consult your favourite Unix networking book).
--
-- A higher level interface to networking operations is provided
-- through the module "Network".
--
-----------------------------------------------------------------------------
{-# LINE 24 "Network/Socket.hsc" #-}
-- In order to process this file, you need to have ccall defined.
module Network.Socket
(
-- * Types
Socket(..)
, Family(..)
, isSupportedFamily
, SocketType(..)
, isSupportedSocketType
, SockAddr(..)
, isSupportedSockAddr
, SocketStatus(..)
, HostAddress
, hostAddressToTuple
, tupleToHostAddress
{-# LINE 42 "Network/Socket.hsc" #-}
, HostAddress6
, hostAddress6ToTuple
, tupleToHostAddress6
, FlowInfo
, ScopeID
{-# LINE 48 "Network/Socket.hsc" #-}
, htonl
, ntohl
, ShutdownCmd(..)
, ProtocolNumber
, defaultProtocol
, PortNumber(..)
-- PortNumber is used non-abstractly in Network.BSD. ToDo: remove
-- this use and make the type abstract.
-- * Address operations
, HostName
, ServiceName
{-# LINE 63 "Network/Socket.hsc" #-}
, AddrInfo(..)
, AddrInfoFlag(..)
, addrInfoFlagImplemented
, defaultHints
, getAddrInfo
, NameInfoFlag(..)
, getNameInfo
{-# LINE 76 "Network/Socket.hsc" #-}
-- * Socket operations
, socket
{-# LINE 80 "Network/Socket.hsc" #-}
, socketPair
{-# LINE 82 "Network/Socket.hsc" #-}
, connect
, bind
, listen
, accept
, getPeerName
, getSocketName
{-# LINE 90 "Network/Socket.hsc" #-}
-- get the credentials of our domain socket peer.
, getPeerCred
{-# LINE 95 "Network/Socket.hsc" #-}
{-# LINE 96 "Network/Socket.hsc" #-}
, socketPort
, socketToHandle
-- ** Sending and receiving data
-- *** Sending and receiving with String
-- $sendrecv
, send
, sendTo
, recv
, recvFrom
, recvLen
-- *** Sending and receiving with a buffer
, sendBuf
, recvBuf
, sendBufTo
, recvBufFrom
-- ** Misc
, inet_addr
, inet_ntoa
, shutdown
, close
-- ** Predicates on sockets
, isConnected
, isBound
, isListening
, isReadable
, isWritable
-- * Socket options
, SocketOption(..)
, isSupportedSocketOption
, getSocketOption
, setSocketOption
-- * File descriptor transmission
{-# LINE 138 "Network/Socket.hsc" #-}
, sendFd
, recvFd
{-# LINE 142 "Network/Socket.hsc" #-}
-- * Special constants
, aNY_PORT
, iNADDR_ANY
{-# LINE 147 "Network/Socket.hsc" #-}
, iN6ADDR_ANY
{-# LINE 149 "Network/Socket.hsc" #-}
, sOMAXCONN
, sOL_SOCKET
{-# LINE 152 "Network/Socket.hsc" #-}
, sCM_RIGHTS
{-# LINE 154 "Network/Socket.hsc" #-}
, maxListenQueue
-- * Initialisation
, withSocketsDo
-- * Very low level operations
-- in case you ever want to get at the underlying file descriptor..
, fdSocket
, mkSocket
, setNonBlockIfNeeded
-- * Deprecated aliases
-- $deprecated-aliases
, bindSocket
, sClose
, sIsConnected
, sIsBound
, sIsListening
, sIsReadable
, sIsWritable
-- * Internal
-- | The following are exported ONLY for use in the BSD module and
-- should not be used anywhere else.
, packFamily
, unpackFamily
, packSocketType
) where
import Data.Bits
import Data.Functor
import Data.List (foldl')
import Data.Maybe (isJust)
import Data.Word (Word8, Word32)
import Foreign.Ptr (Ptr, castPtr, nullPtr)
import Foreign.Storable (Storable(..))
import Foreign.C.Error
import Foreign.C.String (CString, withCString, withCStringLen, peekCString, peekCStringLen)
import Foreign.C.Types (CUInt, CChar)
import Foreign.C.Types (CInt(..), CSize(..))
import Foreign.Marshal.Alloc ( alloca, allocaBytes )
import Foreign.Marshal.Array ( peekArray )
import Foreign.Marshal.Utils ( maybeWith, with )
import System.IO
import Control.Monad (liftM, when)
import Control.Concurrent.MVar
import Data.Typeable
import System.IO.Error
import GHC.Conc (threadWaitRead, threadWaitWrite)
import GHC.Conc (closeFdWith)
{-# LINE 217 "Network/Socket.hsc" #-}
{-# LINE 220 "Network/Socket.hsc" #-}
import qualified GHC.IO.Device
import GHC.IO.Handle.FD
import GHC.IO.Exception
import GHC.IO
import qualified System.Posix.Internals
import Network.Socket.Internal
import Network.Socket.Types
import Prelude -- Silence AMP warnings
-- | Either a host name e.g., @\"haskell.org\"@ or a numeric host
-- address string consisting of a dotted decimal IPv4 address or an
-- IPv6 address e.g., @\"192.168.0.1\"@.
type HostName = String
type ServiceName = String
-- ----------------------------------------------------------------------------
-- On Windows, our sockets are not put in non-blocking mode (non-blocking
-- is not supported for regular file descriptors on Windows, and it would
-- be a pain to support it only for sockets). So there are two cases:
--
-- - the threaded RTS uses safe calls for socket operations to get
-- non-blocking I/O, just like the rest of the I/O library
--
-- - with the non-threaded RTS, only some operations on sockets will be
-- non-blocking. Reads and writes go through the normal async I/O
-- system. accept() uses asyncDoProc so is non-blocking. A handful
-- of others (recvFrom, sendFd, recvFd) will block all threads - if this
-- is a problem, -threaded is the workaround.
--
-----------------------------------------------------------------------------
-- Socket types
{-# LINE 265 "Network/Socket.hsc" #-}
-- | Smart constructor for constructing a 'Socket'. It should only be
-- called once for every new file descriptor. The caller must make
-- sure that the socket is in non-blocking mode. See
-- 'setNonBlockIfNeeded'.
mkSocket :: CInt
-> Family
-> SocketType
-> ProtocolNumber
-> SocketStatus
-> IO Socket
mkSocket fd fam sType pNum stat = do
mStat <- newMVar stat
withSocketsDo $ return ()
return (MkSocket fd fam sType pNum mStat)
fdSocket :: Socket -> CInt
fdSocket (MkSocket fd _ _ _ _) = fd
-- | This is the default protocol for a given service.
defaultProtocol :: ProtocolNumber
defaultProtocol = 0
-----------------------------------------------------------------------------
-- SockAddr
instance Show SockAddr where
{-# LINE 294 "Network/Socket.hsc" #-}
showsPrec _ (SockAddrUnix str) = showString str
{-# LINE 296 "Network/Socket.hsc" #-}
showsPrec _ (SockAddrInet port ha)
= showString (unsafePerformIO (inet_ntoa ha))
. showString ":"
. shows port
{-# LINE 301 "Network/Socket.hsc" #-}
showsPrec _ addr@(SockAddrInet6 port _ _ _)
= showChar '['
. showString (unsafePerformIO $
fst `liftM` getNameInfo [NI_NUMERICHOST] True False addr >>=
maybe (fail "showsPrec: impossible internal error") return)
. showString "]:"
. shows port
{-# LINE 309 "Network/Socket.hsc" #-}
{-# LINE 310 "Network/Socket.hsc" #-}
showsPrec _ (SockAddrCan ifidx) = shows ifidx
{-# LINE 312 "Network/Socket.hsc" #-}
-----------------------------------------------------------------------------
-- Connection Functions
-- In the following connection and binding primitives. The names of
-- the equivalent C functions have been preserved where possible. It
-- should be noted that some of these names used in the C library,
-- \tr{bind} in particular, have a different meaning to many Haskell
-- programmers and have thus been renamed by appending the prefix
-- Socket.
-- | Create a new socket using the given address family, socket type
-- and protocol number. The address family is usually 'AF_INET',
-- 'AF_INET6', or 'AF_UNIX'. The socket type is usually 'Stream' or
-- 'Datagram'. The protocol number is usually 'defaultProtocol'.
-- If 'AF_INET6' is used and the socket type is 'Stream' or 'Datagram',
-- the 'IPv6Only' socket option is set to 0 so that both IPv4 and IPv6
-- can be handled with one socket.
--
-- >>> let hints = defaultHints { addrFlags = [AI_NUMERICHOST, AI_NUMERICSERV], addrSocketType = Stream }
-- >>> addr:_ <- getAddrInfo (Just hints) (Just "127.0.0.1") (Just "5000")
-- >>> sock@(MkSocket _ fam stype _ _) <- socket (addrFamily addr) (addrSocketType addr) (addrProtocol addr)
-- >>> fam
-- AF_INET
-- >>> stype
-- Stream
-- >>> bind sock (addrAddress addr)
-- >>> getSocketName sock
-- 127.0.0.1:5000
socket :: Family -- Family Name (usually AF_INET)
-> SocketType -- Socket Type (usually Stream)
-> ProtocolNumber -- Protocol Number (getProtocolByName to find value)
-> IO Socket -- Unconnected Socket
socket family stype protocol = do
c_stype <- packSocketTypeOrThrow "socket" stype
fd <- throwSocketErrorIfMinus1Retry "Network.Socket.socket" $
c_socket (packFamily family) c_stype protocol
setNonBlockIfNeeded fd
socket_status <- newMVar NotConnected
withSocketsDo $ return ()
let sock = MkSocket fd family stype protocol socket_status
{-# LINE 354 "Network/Socket.hsc" #-}
-- The default value of the IPv6Only option is platform specific,
-- so we explicitly set it to 0 to provide a common default.
{-# LINE 362 "Network/Socket.hsc" #-}
when (family == AF_INET6 && (stype == Stream || stype == Datagram)) $
setSocketOption sock IPv6Only 0 `onException` close sock
{-# LINE 365 "Network/Socket.hsc" #-}
{-# LINE 366 "Network/Socket.hsc" #-}
return sock
-- | Build a pair of connected socket objects using the given address
-- family, socket type, and protocol number. Address family, socket
-- type, and protocol number are as for the 'socket' function above.
-- Availability: Unix.
{-# LINE 373 "Network/Socket.hsc" #-}
socketPair :: Family -- Family Name (usually AF_INET or AF_INET6)
-> SocketType -- Socket Type (usually Stream)
-> ProtocolNumber -- Protocol Number
-> IO (Socket, Socket) -- unnamed and connected.
socketPair family stype protocol = do
allocaBytes (2 * sizeOf (1 :: CInt)) $ \ fdArr -> do
c_stype <- packSocketTypeOrThrow "socketPair" stype
_rc <- throwSocketErrorIfMinus1Retry "Network.Socket.socketpair" $
c_socketpair (packFamily family) c_stype protocol fdArr
[fd1,fd2] <- peekArray 2 fdArr
s1 <- mkNonBlockingSocket fd1
s2 <- mkNonBlockingSocket fd2
return (s1,s2)
where
mkNonBlockingSocket fd = do
setNonBlockIfNeeded fd
stat <- newMVar Connected
withSocketsDo $ return ()
return (MkSocket fd family stype protocol stat)
foreign import ccall unsafe "socketpair"
c_socketpair :: CInt -> CInt -> CInt -> Ptr CInt -> IO CInt
{-# LINE 396 "Network/Socket.hsc" #-}
-- | Set the socket to nonblocking, if applicable to this platform.
--
-- Depending on the platform this is required when using sockets from file
-- descriptors that are passed in through 'recvFd' or other means.
setNonBlockIfNeeded :: CInt -> IO ()
setNonBlockIfNeeded fd =
System.Posix.Internals.setNonBlockingFD fd True
-----------------------------------------------------------------------------
-- Binding a socket
-- | Bind the socket to an address. The socket must not already be
-- bound. The 'Family' passed to @bind@ must be the
-- same as that passed to 'socket'. If the special port number
-- 'aNY_PORT' is passed then the system assigns the next available
-- use port.
bind :: Socket -- Unconnected Socket
-> SockAddr -- Address to Bind to
-> IO ()
bind (MkSocket s _family _stype _protocol socketStatus) addr = do
modifyMVar_ socketStatus $ \ status -> do
if status /= NotConnected
then
ioError $ userError $
"Network.Socket.bind: can't bind to socket with status " ++ show status
else do
withSockAddr addr $ \p_addr sz -> do
_status <- throwSocketErrorIfMinus1Retry "Network.Socket.bind" $
c_bind s p_addr (fromIntegral sz)
return Bound
-----------------------------------------------------------------------------
-- Connecting a socket
-- | Connect to a remote socket at address.
connect :: Socket -- Unconnected Socket
-> SockAddr -- Socket address stuff
-> IO ()
connect sock@(MkSocket s _family _stype _protocol socketStatus) addr = withSocketsDo $ do
modifyMVar_ socketStatus $ \currentStatus -> do
if currentStatus /= NotConnected && currentStatus /= Bound
then
ioError $ userError $
errLoc ++ ": can't connect to socket with status " ++ show currentStatus
else do
withSockAddr addr $ \p_addr sz -> do
let connectLoop = do
r <- c_connect s p_addr (fromIntegral sz)
if r == -1
then do
{-# LINE 449 "Network/Socket.hsc" #-}
err <- getErrno
case () of
_ | err == eINTR -> connectLoop
_ | err == eINPROGRESS -> connectBlocked
-- _ | err == eAGAIN -> connectBlocked
_otherwise -> throwSocketError errLoc
{-# LINE 458 "Network/Socket.hsc" #-}
else return ()
connectBlocked = do
threadWaitWrite (fromIntegral s)
err <- getSocketOption sock SoError
if (err == 0)
then return ()
else throwSocketErrorCode errLoc (fromIntegral err)
connectLoop
return Connected
where
errLoc = "Network.Socket.connect: " ++ show sock
-----------------------------------------------------------------------------
-- Listen
-- | Listen for connections made to the socket. The second argument
-- specifies the maximum number of queued connections and should be at
-- least 1; the maximum value is system-dependent (usually 5).
listen :: Socket -- Connected & Bound Socket
-> Int -- Queue Length
-> IO ()
listen (MkSocket s _family _stype _protocol socketStatus) backlog = do
modifyMVar_ socketStatus $ \ status -> do
if status /= Bound
then
ioError $ userError $
"Network.Socket.listen: can't listen on socket with status " ++ show status
else do
throwSocketErrorIfMinus1Retry_ "Network.Socket.listen" $
c_listen s (fromIntegral backlog)
return Listening
-----------------------------------------------------------------------------
-- Accept
--
-- A call to `accept' only returns when data is available on the given
-- socket, unless the socket has been set to non-blocking. It will
-- return a new socket which should be used to read the incoming data and
-- should then be closed. Using the socket returned by `accept' allows
-- incoming requests to be queued on the original socket.
-- | Accept a connection. The socket must be bound to an address and
-- listening for connections. The return value is a pair @(conn,
-- address)@ where @conn@ is a new socket object usable to send and
-- receive data on the connection, and @address@ is the address bound
-- to the socket on the other end of the connection.
accept :: Socket -- Queue Socket
-> IO (Socket, -- Readable Socket
SockAddr) -- Peer details
accept sock@(MkSocket s family stype protocol status) = do
currentStatus <- readMVar status
okay <- isAcceptable sock
if not okay
then
ioError $ userError $
"Network.Socket.accept: can't accept socket (" ++
show (family, stype, protocol) ++ ") with status " ++
show currentStatus
else do
let sz = sizeOfSockAddrByFamily family
allocaBytes sz $ \ sockaddr -> do
{-# LINE 537 "Network/Socket.hsc" #-}
with (fromIntegral sz) $ \ ptr_len -> do
{-# LINE 539 "Network/Socket.hsc" #-}
new_sock <- throwSocketErrorIfMinus1RetryMayBlock "Network.Socket.accept"
(threadWaitRead (fromIntegral s))
(c_accept4 s sockaddr ptr_len (2048))
{-# LINE 542 "Network/Socket.hsc" #-}
{-# LINE 547 "Network/Socket.hsc" #-}
{-# LINE 548 "Network/Socket.hsc" #-}
addr <- peekSockAddr sockaddr
new_status <- newMVar Connected
return ((MkSocket new_sock family stype protocol new_status), addr)
{-# LINE 562 "Network/Socket.hsc" #-}
-----------------------------------------------------------------------------
-- ** Sending and receiving data
-- $sendrecv
--
-- Do not use the @send@ and @recv@ functions defined in this section
-- in new code, as they incorrectly represent binary data as a Unicode
-- string. As a result, these functions are inefficient and may lead
-- to bugs in the program. Instead use the @send@ and @recv@
-- functions defined in the "Network.Socket.ByteString" module.
-----------------------------------------------------------------------------
-- sendTo & recvFrom
-- | Send data to the socket. The recipient can be specified
-- explicitly, so the socket need not be in a connected state.
-- Returns the number of bytes sent. Applications are responsible for
-- ensuring that all data has been sent.
--
-- NOTE: blocking on Windows unless you compile with -threaded (see
-- GHC ticket #1129)
{-# WARNING sendTo "Use sendTo defined in \"Network.Socket.ByteString\"" #-}
sendTo :: Socket -- (possibly) bound/connected Socket
-> String -- Data to send
-> SockAddr
-> IO Int -- Number of Bytes sent
sendTo sock xs addr = do
withCStringLen xs $ \(str, len) -> do
sendBufTo sock str len addr
-- | Send data to the socket. The recipient can be specified
-- explicitly, so the socket need not be in a connected state.
-- Returns the number of bytes sent. Applications are responsible for
-- ensuring that all data has been sent.
sendBufTo :: Socket -- (possibly) bound/connected Socket
-> Ptr a -> Int -- Data to send
-> SockAddr
-> IO Int -- Number of Bytes sent
sendBufTo sock@(MkSocket s _family _stype _protocol _status) ptr nbytes addr = do
withSockAddr addr $ \p_addr sz -> do
liftM fromIntegral $
throwSocketErrorWaitWrite sock "Network.Socket.sendTo" $
c_sendto s ptr (fromIntegral $ nbytes) 0{-flags-}
p_addr (fromIntegral sz)
-- | Receive data from the socket. The socket need not be in a
-- connected state. Returns @(bytes, nbytes, address)@ where @bytes@
-- is a @String@ of length @nbytes@ representing the data received and
-- @address@ is a 'SockAddr' representing the address of the sending
-- socket.
--
-- NOTE: blocking on Windows unless you compile with -threaded (see
-- GHC ticket #1129)
{-# WARNING recvFrom "Use recvFrom defined in \"Network.Socket.ByteString\"" #-}
recvFrom :: Socket -> Int -> IO (String, Int, SockAddr)
recvFrom sock nbytes =
allocaBytes nbytes $ \ptr -> do
(len, sockaddr) <- recvBufFrom sock ptr nbytes
str <- peekCStringLen (ptr, len)
return (str, len, sockaddr)
-- | Receive data from the socket, writing it into buffer instead of
-- creating a new string. The socket need not be in a connected
-- state. Returns @(nbytes, address)@ where @nbytes@ is the number of
-- bytes received and @address@ is a 'SockAddr' representing the
-- address of the sending socket.
--
-- NOTE: blocking on Windows unless you compile with -threaded (see
-- GHC ticket #1129)
recvBufFrom :: Socket -> Ptr a -> Int -> IO (Int, SockAddr)
recvBufFrom sock@(MkSocket s family _stype _protocol _status) ptr nbytes
| nbytes <= 0 = ioError (mkInvalidRecvArgError "Network.Socket.recvFrom")
| otherwise =
withNewSockAddr family $ \ptr_addr sz -> do
alloca $ \ptr_len -> do
poke ptr_len (fromIntegral sz)
len <- throwSocketErrorWaitRead sock "Network.Socket.recvFrom" $
c_recvfrom s ptr (fromIntegral nbytes) 0{-flags-}
ptr_addr ptr_len
let len' = fromIntegral len
if len' == 0
then ioError (mkEOFError "Network.Socket.recvFrom")
else do
flg <- isConnected sock
-- For at least one implementation (WinSock 2), recvfrom() ignores
-- filling in the sockaddr for connected TCP sockets. Cope with
-- this by using getPeerName instead.
sockaddr <-
if flg then
getPeerName sock
else
peekSockAddr ptr_addr
return (len', sockaddr)
-----------------------------------------------------------------------------
-- send & recv
-- | Send data to the socket. The socket must be connected to a remote
-- socket. Returns the number of bytes sent. Applications are
-- responsible for ensuring that all data has been sent.
--
-- Sending data to closed socket may lead to undefined behaviour.
{-# WARNING send "Use send defined in \"Network.Socket.ByteString\"" #-}
send :: Socket -- Bound/Connected Socket
-> String -- Data to send
-> IO Int -- Number of Bytes sent
send sock xs = withCStringLen xs $ \(str, len) ->
sendBuf sock (castPtr str) len
-- | Send data to the socket. The socket must be connected to a remote
-- socket. Returns the number of bytes sent. Applications are
-- responsible for ensuring that all data has been sent.
--
-- Sending data to closed socket may lead to undefined behaviour.
sendBuf :: Socket -- Bound/Connected Socket
-> Ptr Word8 -- Pointer to the data to send
-> Int -- Length of the buffer
-> IO Int -- Number of Bytes sent
sendBuf sock@(MkSocket s _family _stype _protocol _status) str len = do
liftM fromIntegral $
{-# LINE 695 "Network/Socket.hsc" #-}
throwSocketErrorWaitWrite sock "Network.Socket.sendBuf" $
c_send s str (fromIntegral len) 0{-flags-}
{-# LINE 698 "Network/Socket.hsc" #-}
-- | Receive data from the socket. The socket must be in a connected
-- state. This function may return fewer bytes than specified. If the
-- message is longer than the specified length, it may be discarded
-- depending on the type of socket. This function may block until a
-- message arrives.
--
-- Considering hardware and network realities, the maximum number of
-- bytes to receive should be a small power of 2, e.g., 4096.
--
-- For TCP sockets, a zero length return value means the peer has
-- closed its half side of the connection.
--
-- Receiving data from closed socket may lead to undefined behaviour.
{-# WARNING recv "Use recv defined in \"Network.Socket.ByteString\"" #-}
recv :: Socket -> Int -> IO String
recv sock l = fst <$> recvLen sock l
{-# WARNING recvLen "Use recvLen defined in \"Network.Socket.ByteString\"" #-}
recvLen :: Socket -> Int -> IO (String, Int)
recvLen sock nbytes =
allocaBytes nbytes $ \ptr -> do
len <- recvBuf sock ptr nbytes
s <- peekCStringLen (castPtr ptr,len)
return (s, len)
-- | Receive data from the socket. The socket must be in a connected
-- state. This function may return fewer bytes than specified. If the
-- message is longer than the specified length, it may be discarded
-- depending on the type of socket. This function may block until a
-- message arrives.
--
-- Considering hardware and network realities, the maximum number of
-- bytes to receive should be a small power of 2, e.g., 4096.
--
-- For TCP sockets, a zero length return value means the peer has
-- closed its half side of the connection.
--
-- Receiving data from closed socket may lead to undefined behaviour.
recvBuf :: Socket -> Ptr Word8 -> Int -> IO Int
recvBuf sock@(MkSocket s _family _stype _protocol _status) ptr nbytes
| nbytes <= 0 = ioError (mkInvalidRecvArgError "Network.Socket.recvBuf")
| otherwise = do
len <-
{-# LINE 749 "Network/Socket.hsc" #-}
throwSocketErrorWaitRead sock "Network.Socket.recvBuf" $
c_recv s (castPtr ptr) (fromIntegral nbytes) 0{-flags-}
{-# LINE 752 "Network/Socket.hsc" #-}
let len' = fromIntegral len
if len' == 0
then ioError (mkEOFError "Network.Socket.recvBuf")
else return len'
-- ---------------------------------------------------------------------------
-- socketPort
--
-- The port number the given socket is currently connected to can be
-- determined by calling $port$, is generally only useful when bind
-- was given $aNY\_PORT$.
socketPort :: Socket -- Connected & Bound Socket
-> IO PortNumber -- Port Number of Socket
socketPort sock@(MkSocket _ AF_INET _ _ _) = do
(SockAddrInet port _) <- getSocketName sock
return port
{-# LINE 771 "Network/Socket.hsc" #-}
socketPort sock@(MkSocket _ AF_INET6 _ _ _) = do
(SockAddrInet6 port _ _ _) <- getSocketName sock
return port
{-# LINE 775 "Network/Socket.hsc" #-}
socketPort (MkSocket _ family _ _ _) =
ioError $ userError $
"Network.Socket.socketPort: address family '" ++ show family ++
"' not supported."
-- ---------------------------------------------------------------------------
-- getPeerName
-- Calling $getPeerName$ returns the address details of the machine,
-- other than the local one, which is connected to the socket. This is
-- used in programs such as FTP to determine where to send the
-- returning data. The corresponding call to get the details of the
-- local machine is $getSocketName$.
getPeerName :: Socket -> IO SockAddr
getPeerName (MkSocket s family _ _ _) = do
withNewSockAddr family $ \ptr sz -> do
with (fromIntegral sz) $ \int_star -> do
throwSocketErrorIfMinus1Retry_ "Network.Socket.getPeerName" $
c_getpeername s ptr int_star
_sz <- peek int_star
peekSockAddr ptr
getSocketName :: Socket -> IO SockAddr
getSocketName (MkSocket s family _ _ _) = do
withNewSockAddr family $ \ptr sz -> do
with (fromIntegral sz) $ \int_star -> do
throwSocketErrorIfMinus1Retry_ "Network.Socket.getSocketName" $
c_getsockname s ptr int_star
peekSockAddr ptr
-----------------------------------------------------------------------------
-- Socket Properties
-- | Socket options for use with 'setSocketOption' and 'getSocketOption'.
--
-- The existence of a constructor does not imply that the relevant option
-- is supported on your system: see 'isSupportedSocketOption'
data SocketOption
= Debug -- ^ SO_DEBUG
| ReuseAddr -- ^ SO_REUSEADDR
| Type -- ^ SO_TYPE
| SoError -- ^ SO_ERROR
| DontRoute -- ^ SO_DONTROUTE
| Broadcast -- ^ SO_BROADCAST
| SendBuffer -- ^ SO_SNDBUF
| RecvBuffer -- ^ SO_RCVBUF
| KeepAlive -- ^ SO_KEEPALIVE
| OOBInline -- ^ SO_OOBINLINE
| TimeToLive -- ^ IP_TTL
| MaxSegment -- ^ TCP_MAXSEG
| NoDelay -- ^ TCP_NODELAY
| Cork -- ^ TCP_CORK
| Linger -- ^ SO_LINGER
| ReusePort -- ^ SO_REUSEPORT
| RecvLowWater -- ^ SO_RCVLOWAT
| SendLowWater -- ^ SO_SNDLOWAT
| RecvTimeOut -- ^ SO_RCVTIMEO
| SendTimeOut -- ^ SO_SNDTIMEO
| UseLoopBack -- ^ SO_USELOOPBACK
| UserTimeout -- ^ TCP_USER_TIMEOUT
| IPv6Only -- ^ IPV6_V6ONLY
| CustomSockOpt (CInt, CInt)
deriving (Show, Typeable)
-- | Does the 'SocketOption' exist on this system?
isSupportedSocketOption :: SocketOption -> Bool
isSupportedSocketOption = isJust . packSocketOption
-- | For a socket option, return Just (level, value) where level is the
-- corresponding C option level constant (e.g. SOL_SOCKET) and value is
-- the option constant itself (e.g. SO_DEBUG)
-- If either constant does not exist, return Nothing.
packSocketOption :: SocketOption -> Maybe (CInt, CInt)
packSocketOption so =
-- The Just here is a hack to disable GHC's overlapping pattern detection:
-- the problem is if all constants are present, the fallback pattern is
-- redundant, but if they aren't then it isn't. Hence we introduce an
-- extra pattern (Nothing) that can't possibly happen, so that the
-- fallback is always (in principle) necessary.
-- I feel a little bad for including this, but such are the sacrifices we
-- make while working with CPP - excluding the fallback pattern correctly
-- would be a serious nuisance.
-- (NB: comments elsewhere in this file refer to this one)
case Just so of
{-# LINE 862 "Network/Socket.hsc" #-}
{-# LINE 863 "Network/Socket.hsc" #-}
Just Debug -> Just ((1), (1))
{-# LINE 864 "Network/Socket.hsc" #-}
{-# LINE 865 "Network/Socket.hsc" #-}
{-# LINE 866 "Network/Socket.hsc" #-}
Just ReuseAddr -> Just ((1), (2))
{-# LINE 867 "Network/Socket.hsc" #-}
{-# LINE 868 "Network/Socket.hsc" #-}
{-# LINE 869 "Network/Socket.hsc" #-}
Just Type -> Just ((1), (3))
{-# LINE 870 "Network/Socket.hsc" #-}
{-# LINE 871 "Network/Socket.hsc" #-}
{-# LINE 872 "Network/Socket.hsc" #-}
Just SoError -> Just ((1), (4))
{-# LINE 873 "Network/Socket.hsc" #-}
{-# LINE 874 "Network/Socket.hsc" #-}
{-# LINE 875 "Network/Socket.hsc" #-}
Just DontRoute -> Just ((1), (5))
{-# LINE 876 "Network/Socket.hsc" #-}
{-# LINE 877 "Network/Socket.hsc" #-}
{-# LINE 878 "Network/Socket.hsc" #-}
Just Broadcast -> Just ((1), (6))
{-# LINE 879 "Network/Socket.hsc" #-}
{-# LINE 880 "Network/Socket.hsc" #-}
{-# LINE 881 "Network/Socket.hsc" #-}
Just SendBuffer -> Just ((1), (7))
{-# LINE 882 "Network/Socket.hsc" #-}
{-# LINE 883 "Network/Socket.hsc" #-}
{-# LINE 884 "Network/Socket.hsc" #-}
Just RecvBuffer -> Just ((1), (8))
{-# LINE 885 "Network/Socket.hsc" #-}
{-# LINE 886 "Network/Socket.hsc" #-}
{-# LINE 887 "Network/Socket.hsc" #-}
Just KeepAlive -> Just ((1), (9))
{-# LINE 888 "Network/Socket.hsc" #-}
{-# LINE 889 "Network/Socket.hsc" #-}
{-# LINE 890 "Network/Socket.hsc" #-}
Just OOBInline -> Just ((1), (10))
{-# LINE 891 "Network/Socket.hsc" #-}
{-# LINE 892 "Network/Socket.hsc" #-}
{-# LINE 893 "Network/Socket.hsc" #-}
Just Linger -> Just ((1), (13))
{-# LINE 894 "Network/Socket.hsc" #-}
{-# LINE 895 "Network/Socket.hsc" #-}
{-# LINE 896 "Network/Socket.hsc" #-}
Just ReusePort -> Just ((1), (15))
{-# LINE 897 "Network/Socket.hsc" #-}
{-# LINE 898 "Network/Socket.hsc" #-}
{-# LINE 899 "Network/Socket.hsc" #-}
Just RecvLowWater -> Just ((1), (18))
{-# LINE 900 "Network/Socket.hsc" #-}
{-# LINE 901 "Network/Socket.hsc" #-}
{-# LINE 902 "Network/Socket.hsc" #-}
Just SendLowWater -> Just ((1), (19))
{-# LINE 903 "Network/Socket.hsc" #-}
{-# LINE 904 "Network/Socket.hsc" #-}
{-# LINE 905 "Network/Socket.hsc" #-}
Just RecvTimeOut -> Just ((1), (20))
{-# LINE 906 "Network/Socket.hsc" #-}
{-# LINE 907 "Network/Socket.hsc" #-}
{-# LINE 908 "Network/Socket.hsc" #-}
Just SendTimeOut -> Just ((1), (21))
{-# LINE 909 "Network/Socket.hsc" #-}
{-# LINE 910 "Network/Socket.hsc" #-}
{-# LINE 913 "Network/Socket.hsc" #-}
{-# LINE 914 "Network/Socket.hsc" #-}
{-# LINE 915 "Network/Socket.hsc" #-}
{-# LINE 916 "Network/Socket.hsc" #-}
Just TimeToLive -> Just ((0), (2))
{-# LINE 917 "Network/Socket.hsc" #-}
{-# LINE 918 "Network/Socket.hsc" #-}
{-# LINE 919 "Network/Socket.hsc" #-}
{-# LINE 920 "Network/Socket.hsc" #-}
{-# LINE 921 "Network/Socket.hsc" #-}
Just MaxSegment -> Just ((6), (2))
{-# LINE 922 "Network/Socket.hsc" #-}
{-# LINE 923 "Network/Socket.hsc" #-}
{-# LINE 924 "Network/Socket.hsc" #-}
Just NoDelay -> Just ((6), (1))
{-# LINE 925 "Network/Socket.hsc" #-}
{-# LINE 926 "Network/Socket.hsc" #-}
{-# LINE 927 "Network/Socket.hsc" #-}
Just UserTimeout -> Just ((6), (18))
{-# LINE 928 "Network/Socket.hsc" #-}
{-# LINE 929 "Network/Socket.hsc" #-}
{-# LINE 930 "Network/Socket.hsc" #-}
Just Cork -> Just ((6), (3))
{-# LINE 931 "Network/Socket.hsc" #-}
{-# LINE 932 "Network/Socket.hsc" #-}
{-# LINE 933 "Network/Socket.hsc" #-}
{-# LINE 934 "Network/Socket.hsc" #-}
{-# LINE 935 "Network/Socket.hsc" #-}
Just IPv6Only -> Just ((41), (26))
{-# LINE 936 "Network/Socket.hsc" #-}
{-# LINE 937 "Network/Socket.hsc" #-}
{-# LINE 938 "Network/Socket.hsc" #-}
Just (CustomSockOpt opt) -> Just opt
_ -> Nothing
-- | Return the option level and option value if they exist,
-- otherwise throw an error that begins "Network.Socket." ++ the String
-- parameter
packSocketOption' :: String -> SocketOption -> IO (CInt, CInt)
packSocketOption' caller so = maybe err return (packSocketOption so)
where
err = ioError . userError . concat $ ["Network.Socket.", caller,
": socket option ", show so, " unsupported on this system"]
-- | Set a socket option that expects an Int value.
-- There is currently no API to set e.g. the timeval socket options
setSocketOption :: Socket
-> SocketOption -- Option Name
-> Int -- Option Value
-> IO ()
setSocketOption (MkSocket s _ _ _ _) so v = do
(level, opt) <- packSocketOption' "setSocketOption" so
with (fromIntegral v) $ \ptr_v -> do
throwSocketErrorIfMinus1_ "Network.Socket.setSocketOption" $
c_setsockopt s level opt ptr_v
(fromIntegral (sizeOf (undefined :: CInt)))
return ()
-- | Get a socket option that gives an Int value.
-- There is currently no API to get e.g. the timeval socket options
getSocketOption :: Socket
-> SocketOption -- Option Name
-> IO Int -- Option Value
getSocketOption (MkSocket s _ _ _ _) so = do
(level, opt) <- packSocketOption' "getSocketOption" so
alloca $ \ptr_v ->
with (fromIntegral (sizeOf (undefined :: CInt))) $ \ptr_sz -> do
throwSocketErrorIfMinus1Retry_ "Network.Socket.getSocketOption" $
c_getsockopt s level opt ptr_v ptr_sz
fromIntegral `liftM` peek ptr_v
{-# LINE 980 "Network/Socket.hsc" #-}
-- | Returns the processID, userID and groupID of the socket's peer.
--
-- Only available on platforms that support SO_PEERCRED or GETPEEREID(3)
-- on domain sockets.
-- GETPEEREID(3) returns userID and groupID. processID is always 0.
getPeerCred :: Socket -> IO (CUInt, CUInt, CUInt)
getPeerCred sock = do
{-# LINE 988 "Network/Socket.hsc" #-}
let fd = fdSocket sock
let sz = (12)
{-# LINE 990 "Network/Socket.hsc" #-}
allocaBytes sz $ \ ptr_cr ->
with (fromIntegral sz) $ \ ptr_sz -> do
_ <- ($) throwSocketErrorIfMinus1Retry "Network.Socket.getPeerCred" $
c_getsockopt fd (1) (17) ptr_cr ptr_sz
{-# LINE 994 "Network/Socket.hsc" #-}
pid <- ((\hsc_ptr -> peekByteOff hsc_ptr 0)) ptr_cr
{-# LINE 995 "Network/Socket.hsc" #-}
uid <- ((\hsc_ptr -> peekByteOff hsc_ptr 4)) ptr_cr
{-# LINE 996 "Network/Socket.hsc" #-}
gid <- ((\hsc_ptr -> peekByteOff hsc_ptr 8)) ptr_cr
{-# LINE 997 "Network/Socket.hsc" #-}
return (pid, uid, gid)
{-# LINE 1002 "Network/Socket.hsc" #-}
{-# LINE 1017 "Network/Socket.hsc" #-}
{-# LINE 1018 "Network/Socket.hsc" #-}
{-# LINE 1024 "Network/Socket.hsc" #-}
-- sending/receiving ancillary socket data; low-level mechanism
-- for transmitting file descriptors, mainly.
sendFd :: Socket -> CInt -> IO ()
sendFd sock outfd = do
_ <- ($) throwSocketErrorWaitWrite sock "Network.Socket.sendFd" $
c_sendFd (fdSocket sock) outfd
-- Note: If Winsock supported FD-passing, thi would have been
-- incorrect (since socket FDs need to be closed via closesocket().)
closeFd outfd
-- | Receive a file descriptor over a domain socket. Note that the resulting
-- file descriptor may have to be put into non-blocking mode in order to be
-- used safely. See 'setNonBlockIfNeeded'.
recvFd :: Socket -> IO CInt
recvFd sock = do
theFd <- throwSocketErrorWaitRead sock "Network.Socket.recvFd" $
c_recvFd (fdSocket sock)
return theFd
foreign import ccall unsafe "sendFd" c_sendFd :: CInt -> CInt -> IO CInt
foreign import ccall unsafe "recvFd" c_recvFd :: CInt -> IO CInt
{-# LINE 1047 "Network/Socket.hsc" #-}
-- ---------------------------------------------------------------------------
-- Utility Functions
aNY_PORT :: PortNumber
aNY_PORT = 0
-- | The IPv4 wild card address.
iNADDR_ANY :: HostAddress
iNADDR_ANY = htonl (0)
{-# LINE 1058 "Network/Socket.hsc" #-}
-- | Converts the from host byte order to network byte order.
foreign import ccall unsafe "htonl" htonl :: Word32 -> Word32
-- | Converts the from network byte order to host byte order.
foreign import ccall unsafe "ntohl" ntohl :: Word32 -> Word32
{-# LINE 1065 "Network/Socket.hsc" #-}
-- | The IPv6 wild card address.
iN6ADDR_ANY :: HostAddress6
iN6ADDR_ANY = (0, 0, 0, 0)
{-# LINE 1070 "Network/Socket.hsc" #-}
sOMAXCONN :: Int
sOMAXCONN = 128
{-# LINE 1073 "Network/Socket.hsc" #-}
sOL_SOCKET :: Int
sOL_SOCKET = 1
{-# LINE 1076 "Network/Socket.hsc" #-}
{-# LINE 1078 "Network/Socket.hsc" #-}
sCM_RIGHTS :: Int
sCM_RIGHTS = 1
{-# LINE 1080 "Network/Socket.hsc" #-}
{-# LINE 1081 "Network/Socket.hsc" #-}
-- | This is the value of SOMAXCONN, typically 128.
-- 128 is good enough for normal network servers but
-- is too small for high performance servers.
maxListenQueue :: Int
maxListenQueue = sOMAXCONN
-- -----------------------------------------------------------------------------
data ShutdownCmd
= ShutdownReceive
| ShutdownSend
| ShutdownBoth
deriving Typeable
sdownCmdToInt :: ShutdownCmd -> CInt
sdownCmdToInt ShutdownReceive = 0
sdownCmdToInt ShutdownSend = 1
sdownCmdToInt ShutdownBoth = 2
-- | Shut down one or both halves of the connection, depending on the
-- second argument to the function. If the second argument is
-- 'ShutdownReceive', further receives are disallowed. If it is
-- 'ShutdownSend', further sends are disallowed. If it is
-- 'ShutdownBoth', further sends and receives are disallowed.
shutdown :: Socket -> ShutdownCmd -> IO ()
shutdown (MkSocket s _ _ _ _) stype = do
throwSocketErrorIfMinus1Retry_ "Network.Socket.shutdown" $
c_shutdown s (sdownCmdToInt stype)
return ()
-- -----------------------------------------------------------------------------
-- | Close the socket. Sending data to or receiving data from closed socket
-- may lead to undefined behaviour.
close :: Socket -> IO ()
close (MkSocket s _ _ _ socketStatus) = do
modifyMVar_ socketStatus $ \ status ->
case status of
ConvertedToHandle ->
ioError (userError ("close: converted to a Handle, use hClose instead"))
Closed ->
return status
_ -> closeFdWith (closeFd . fromIntegral) (fromIntegral s) >> return Closed
-- -----------------------------------------------------------------------------
-- | Determines whether 'close' has been used on the 'Socket'. This
-- does /not/ indicate any status about the socket beyond this. If the
-- socket has been closed remotely, this function can still return
-- 'True'.
isConnected :: Socket -> IO Bool
isConnected (MkSocket _ _ _ _ status) = do
value <- readMVar status
return (value == Connected)
-- -----------------------------------------------------------------------------
-- Socket Predicates
isBound :: Socket -> IO Bool
isBound (MkSocket _ _ _ _ status) = do
value <- readMVar status
return (value == Bound)
isListening :: Socket -> IO Bool
isListening (MkSocket _ _ _ _ status) = do
value <- readMVar status
return (value == Listening)
isReadable :: Socket -> IO Bool
isReadable (MkSocket _ _ _ _ status) = do
value <- readMVar status
return (value == Listening || value == Connected)
isWritable :: Socket -> IO Bool
isWritable = isReadable -- sort of.
isAcceptable :: Socket -> IO Bool
{-# LINE 1160 "Network/Socket.hsc" #-}
isAcceptable (MkSocket _ AF_UNIX x _ status)
| x == Stream || x == SeqPacket = do
value <- readMVar status
return (value == Connected || value == Bound || value == Listening)
isAcceptable (MkSocket _ AF_UNIX _ _ _) = return False
{-# LINE 1166 "Network/Socket.hsc" #-}
isAcceptable (MkSocket _ _ _ _ status) = do
value <- readMVar status
return (value == Connected || value == Listening)
-- -----------------------------------------------------------------------------
-- Internet address manipulation routines:
inet_addr :: String -> IO HostAddress
inet_addr ipstr = withSocketsDo $ do
withCString ipstr $ \str -> do
had <- c_inet_addr str
if had == -1
then ioError $ userError $
"Network.Socket.inet_addr: Malformed address: " ++ ipstr
else return had -- network byte order
inet_ntoa :: HostAddress -> IO String
inet_ntoa haddr = withSocketsDo $ do
pstr <- c_inet_ntoa haddr
peekCString pstr
-- | Turns a Socket into an 'Handle'. By default, the new handle is
-- unbuffered. Use 'System.IO.hSetBuffering' to change the buffering.
--
-- Note that since a 'Handle' is automatically closed by a finalizer
-- when it is no longer referenced, you should avoid doing any more
-- operations on the 'Socket' after calling 'socketToHandle'. To
-- close the 'Socket' after 'socketToHandle', call 'System.IO.hClose'
-- on the 'Handle'.
socketToHandle :: Socket -> IOMode -> IO Handle
socketToHandle s@(MkSocket fd _ _ _ socketStatus) mode = do
modifyMVar socketStatus $ \ status ->
if status == ConvertedToHandle
then ioError (userError ("socketToHandle: already a Handle"))
else do
h <- fdToHandle' (fromIntegral fd) (Just GHC.IO.Device.Stream) True (show s) mode True{-bin-}
hSetBuffering h NoBuffering
return (ConvertedToHandle, h)
-- | Pack a list of values into a bitmask. The possible mappings from
-- value to bit-to-set are given as the first argument. We assume
-- that each value can cause exactly one bit to be set; unpackBits will
-- break if this property is not true.
packBits :: (Eq a, Num b, Bits b) => [(a, b)] -> [a] -> b
packBits mapping xs = foldl' pack 0 mapping
where pack acc (k, v) | k `elem` xs = acc .|. v
| otherwise = acc
-- | Unpack a bitmask into a list of values.
unpackBits :: (Num b, Bits b) => [(a, b)] -> b -> [a]
-- Be permissive and ignore unknown bit values. At least on OS X,
-- getaddrinfo returns an ai_flags field with bits set that have no
-- entry in <netdb.h>.
unpackBits [] _ = []
unpackBits ((k,v):xs) r
| r .&. v /= 0 = k : unpackBits xs (r .&. complement v)
| otherwise = unpackBits xs r
-----------------------------------------------------------------------------
-- Address and service lookups
{-# LINE 1233 "Network/Socket.hsc" #-}
-- | Flags that control the querying behaviour of 'getAddrInfo'.
-- For more information, see <https://tools.ietf.org/html/rfc3493#page-25>
data AddrInfoFlag =
-- | The list of returned 'AddrInfo' values will
-- only contain IPv4 addresses if the local system has at least
-- one IPv4 interface configured, and likewise for IPv6.
-- (Only some platforms support this.)
AI_ADDRCONFIG
-- | If 'AI_ALL' is specified, return all matching IPv6 and
-- IPv4 addresses. Otherwise, this flag has no effect.
-- (Only some platforms support this.)
| AI_ALL
-- | The 'addrCanonName' field of the first returned
-- 'AddrInfo' will contain the "canonical name" of the host.
| AI_CANONNAME
-- | The 'HostName' argument /must/ be a numeric
-- address in string form, and network name lookups will not be
-- attempted.
| AI_NUMERICHOST
-- | The 'ServiceName' argument /must/ be a port
-- number in string form, and service name lookups will not be
-- attempted. (Only some platforms support this.)
| AI_NUMERICSERV
-- | If no 'HostName' value is provided, the network
-- address in each 'SockAddr'
-- will be left as a "wild card", i.e. as either 'iNADDR_ANY'
-- or 'iN6ADDR_ANY'. This is useful for server applications that
-- will accept connections from any client.
| AI_PASSIVE
-- | If an IPv6 lookup is performed, and no IPv6
-- addresses are found, IPv6-mapped IPv4 addresses will be
-- returned. (Only some platforms support this.)
| AI_V4MAPPED
deriving (Eq, Read, Show, Typeable)
aiFlagMapping :: [(AddrInfoFlag, CInt)]
aiFlagMapping =
[
{-# LINE 1274 "Network/Socket.hsc" #-}
(AI_ADDRCONFIG, 32),
{-# LINE 1275 "Network/Socket.hsc" #-}
{-# LINE 1278 "Network/Socket.hsc" #-}
{-# LINE 1279 "Network/Socket.hsc" #-}
(AI_ALL, 16),
{-# LINE 1280 "Network/Socket.hsc" #-}
{-# LINE 1283 "Network/Socket.hsc" #-}
(AI_CANONNAME, 2),
{-# LINE 1284 "Network/Socket.hsc" #-}
(AI_NUMERICHOST, 4),
{-# LINE 1285 "Network/Socket.hsc" #-}
{-# LINE 1286 "Network/Socket.hsc" #-}
(AI_NUMERICSERV, 1024),
{-# LINE 1287 "Network/Socket.hsc" #-}
{-# LINE 1290 "Network/Socket.hsc" #-}
(AI_PASSIVE, 1),
{-# LINE 1291 "Network/Socket.hsc" #-}
{-# LINE 1292 "Network/Socket.hsc" #-}
(AI_V4MAPPED, 8)
{-# LINE 1293 "Network/Socket.hsc" #-}
{-# LINE 1296 "Network/Socket.hsc" #-}
]
-- | Indicate whether the given 'AddrInfoFlag' will have any effect on
-- this system.
addrInfoFlagImplemented :: AddrInfoFlag -> Bool
addrInfoFlagImplemented f = packBits aiFlagMapping [f] /= 0
data AddrInfo =
AddrInfo {
addrFlags :: [AddrInfoFlag],
addrFamily :: Family,
addrSocketType :: SocketType,
addrProtocol :: ProtocolNumber,
addrAddress :: SockAddr,
addrCanonName :: Maybe String
}
deriving (Eq, Show, Typeable)
instance Storable AddrInfo where
sizeOf _ = 48
{-# LINE 1316 "Network/Socket.hsc" #-}
alignment _ = alignment (undefined :: CInt)
peek p = do
ai_flags <- ((\hsc_ptr -> peekByteOff hsc_ptr 0)) p
{-# LINE 1320 "Network/Socket.hsc" #-}
ai_family <- ((\hsc_ptr -> peekByteOff hsc_ptr 4)) p
{-# LINE 1321 "Network/Socket.hsc" #-}
ai_socktype <- ((\hsc_ptr -> peekByteOff hsc_ptr 8)) p
{-# LINE 1322 "Network/Socket.hsc" #-}
ai_protocol <- ((\hsc_ptr -> peekByteOff hsc_ptr 12)) p
{-# LINE 1323 "Network/Socket.hsc" #-}
ai_addr <- ((\hsc_ptr -> peekByteOff hsc_ptr 24)) p >>= peekSockAddr
{-# LINE 1324 "Network/Socket.hsc" #-}
ai_canonname_ptr <- ((\hsc_ptr -> peekByteOff hsc_ptr 32)) p
{-# LINE 1325 "Network/Socket.hsc" #-}
ai_canonname <- if ai_canonname_ptr == nullPtr
then return Nothing
else liftM Just $ peekCString ai_canonname_ptr
socktype <- unpackSocketType' "AddrInfo.peek" ai_socktype
return (AddrInfo
{
addrFlags = unpackBits aiFlagMapping ai_flags,
addrFamily = unpackFamily ai_family,
addrSocketType = socktype,
addrProtocol = ai_protocol,
addrAddress = ai_addr,
addrCanonName = ai_canonname
})
poke p (AddrInfo flags family socketType protocol _ _) = do
c_stype <- packSocketTypeOrThrow "AddrInfo.poke" socketType
((\hsc_ptr -> pokeByteOff hsc_ptr 0)) p (packBits aiFlagMapping flags)
{-# LINE 1345 "Network/Socket.hsc" #-}
((\hsc_ptr -> pokeByteOff hsc_ptr 4)) p (packFamily family)
{-# LINE 1346 "Network/Socket.hsc" #-}
((\hsc_ptr -> pokeByteOff hsc_ptr 8)) p c_stype
{-# LINE 1347 "Network/Socket.hsc" #-}
((\hsc_ptr -> pokeByteOff hsc_ptr 12)) p protocol
{-# LINE 1348 "Network/Socket.hsc" #-}
-- stuff below is probably not needed, but let's zero it for safety
((\hsc_ptr -> pokeByteOff hsc_ptr 16)) p (0::CSize)
{-# LINE 1352 "Network/Socket.hsc" #-}
((\hsc_ptr -> pokeByteOff hsc_ptr 24)) p nullPtr
{-# LINE 1353 "Network/Socket.hsc" #-}
((\hsc_ptr -> pokeByteOff hsc_ptr 32)) p nullPtr
{-# LINE 1354 "Network/Socket.hsc" #-}
((\hsc_ptr -> pokeByteOff hsc_ptr 40)) p nullPtr
{-# LINE 1355 "Network/Socket.hsc" #-}
-- | Flags that control the querying behaviour of 'getNameInfo'.
-- For more information, see <https://tools.ietf.org/html/rfc3493#page-30>
data NameInfoFlag =
-- | Resolve a datagram-based service name. This is
-- required only for the few protocols that have different port
-- numbers for their datagram-based versions than for their
-- stream-based versions.
NI_DGRAM
-- | If the hostname cannot be looked up, an IO error is thrown.
| NI_NAMEREQD
-- | If a host is local, return only the hostname part of the FQDN.
| NI_NOFQDN
-- | The name of the host is not looked up.
-- Instead, a numeric representation of the host's
-- address is returned. For an IPv4 address, this will be a
-- dotted-quad string. For IPv6, it will be colon-separated
-- hexadecimal.
| NI_NUMERICHOST
-- | The name of the service is not
-- looked up. Instead, a numeric representation of the
-- service is returned.
| NI_NUMERICSERV
deriving (Eq, Read, Show, Typeable)
niFlagMapping :: [(NameInfoFlag, CInt)]
niFlagMapping = [(NI_DGRAM, 16),
{-# LINE 1383 "Network/Socket.hsc" #-}
(NI_NAMEREQD, 8),
{-# LINE 1384 "Network/Socket.hsc" #-}
(NI_NOFQDN, 4),
{-# LINE 1385 "Network/Socket.hsc" #-}
(NI_NUMERICHOST, 1),
{-# LINE 1386 "Network/Socket.hsc" #-}
(NI_NUMERICSERV, 2)]
{-# LINE 1387 "Network/Socket.hsc" #-}
-- | Default hints for address lookup with 'getAddrInfo'. The values
-- of the 'addrAddress' and 'addrCanonName' fields are 'undefined',
-- and are never inspected by 'getAddrInfo'.
--
-- >>> addrFlags defaultHints
-- []
-- >>> addrFamily defaultHints
-- AF_UNSPEC
-- >>> addrSocketType defaultHints
-- NoSocketType
-- >>> addrProtocol defaultHints
-- 0
defaultHints :: AddrInfo
defaultHints = AddrInfo {
addrFlags = [],
addrFamily = AF_UNSPEC,
addrSocketType = NoSocketType,
addrProtocol = defaultProtocol,
addrAddress = undefined,
addrCanonName = undefined
}
-- | Resolve a host or service name to one or more addresses.
-- The 'AddrInfo' values that this function returns contain 'SockAddr'
-- values that you can pass directly to 'connect' or
-- 'bind'.
--
-- This function is protocol independent. It can return both IPv4 and
-- IPv6 address information.
--
-- The 'AddrInfo' argument specifies the preferred query behaviour,
-- socket options, or protocol. You can override these conveniently
-- using Haskell's record update syntax on 'defaultHints', for example
-- as follows:
--
-- >>> let hints = defaultHints { addrFlags = [AI_NUMERICHOST], addrSocketType = Stream }
--
-- You must provide a 'Just' value for at least one of the 'HostName'
-- or 'ServiceName' arguments. 'HostName' can be either a numeric
-- network address (dotted quad for IPv4, colon-separated hex for
-- IPv6) or a hostname. In the latter case, its addresses will be
-- looked up unless 'AI_NUMERICHOST' is specified as a hint. If you
-- do not provide a 'HostName' value /and/ do not set 'AI_PASSIVE' as
-- a hint, network addresses in the result will contain the address of
-- the loopback interface.
--
-- If the query fails, this function throws an IO exception instead of
-- returning an empty list. Otherwise, it returns a non-empty list
-- of 'AddrInfo' values.
--
-- There are several reasons why a query might result in several
-- values. For example, the queried-for host could be multihomed, or
-- the service might be available via several protocols.
--
-- Note: the order of arguments is slightly different to that defined
-- for @getaddrinfo@ in RFC 2553. The 'AddrInfo' parameter comes first
-- to make partial application easier.
--
-- >>> addr:_ <- getAddrInfo (Just hints) (Just "127.0.0.1") (Just "http")
-- >>> addrAddress addr
-- 127.0.0.1:80
getAddrInfo :: Maybe AddrInfo -- ^ preferred socket type or protocol
-> Maybe HostName -- ^ host name to look up
-> Maybe ServiceName -- ^ service name to look up
-> IO [AddrInfo] -- ^ resolved addresses, with "best" first
getAddrInfo hints node service = withSocketsDo $
maybeWith withCString node $ \c_node ->
maybeWith withCString service $ \c_service ->
maybeWith with filteredHints $ \c_hints ->
alloca $ \ptr_ptr_addrs -> do
ret <- c_getaddrinfo c_node c_service c_hints ptr_ptr_addrs
case ret of
0 -> do ptr_addrs <- peek ptr_ptr_addrs
ais <- followAddrInfo ptr_addrs
c_freeaddrinfo ptr_addrs
return ais
_ -> do err <- gai_strerror ret
ioError (ioeSetErrorString
(mkIOError NoSuchThing "Network.Socket.getAddrInfo" Nothing
Nothing) err)
-- Leaving out the service and using AI_NUMERICSERV causes a
-- segfault on OS X 10.8.2. This code removes AI_NUMERICSERV
-- (which has no effect) in that case.
where
{-# LINE 1480 "Network/Socket.hsc" #-}
filteredHints = hints
{-# LINE 1482 "Network/Socket.hsc" #-}
followAddrInfo :: Ptr AddrInfo -> IO [AddrInfo]
followAddrInfo ptr_ai | ptr_ai == nullPtr = return []
| otherwise = do
a <- peek ptr_ai
as <- ((\hsc_ptr -> peekByteOff hsc_ptr 40)) ptr_ai >>= followAddrInfo
{-# LINE 1489 "Network/Socket.hsc" #-}
return (a:as)
foreign import ccall safe "hsnet_getaddrinfo"
c_getaddrinfo :: CString -> CString -> Ptr AddrInfo -> Ptr (Ptr AddrInfo)
-> IO CInt
foreign import ccall safe "hsnet_freeaddrinfo"
c_freeaddrinfo :: Ptr AddrInfo -> IO ()
gai_strerror :: CInt -> IO String
{-# LINE 1501 "Network/Socket.hsc" #-}
gai_strerror n = c_gai_strerror n >>= peekCString
foreign import ccall safe "gai_strerror"
c_gai_strerror :: CInt -> IO CString
{-# LINE 1508 "Network/Socket.hsc" #-}
withCStringIf :: Bool -> Int -> (CSize -> CString -> IO a) -> IO a
withCStringIf False _ f = f 0 nullPtr
withCStringIf True n f = allocaBytes n (f (fromIntegral n))
-- | Resolve an address to a host or service name.
-- This function is protocol independent.
-- The list of 'NameInfoFlag' values controls query behaviour.
--
-- If a host or service's name cannot be looked up, then the numeric
-- form of the address or service will be returned.
--
-- If the query fails, this function throws an IO exception.
--
-- Example:
-- @
-- (hostName, _) <- getNameInfo [] True False myAddress
-- @
getNameInfo :: [NameInfoFlag] -- ^ flags to control lookup behaviour
-> Bool -- ^ whether to look up a hostname
-> Bool -- ^ whether to look up a service name
-> SockAddr -- ^ the address to look up
-> IO (Maybe HostName, Maybe ServiceName)
getNameInfo flags doHost doService addr = withSocketsDo $
withCStringIf doHost (1025) $ \c_hostlen c_host ->
{-# LINE 1535 "Network/Socket.hsc" #-}
withCStringIf doService (32) $ \c_servlen c_serv -> do
{-# LINE 1536 "Network/Socket.hsc" #-}
withSockAddr addr $ \ptr_addr sz -> do
ret <- c_getnameinfo ptr_addr (fromIntegral sz) c_host c_hostlen
c_serv c_servlen (packBits niFlagMapping flags)
case ret of
0 -> do
let peekIf doIf c_val = if doIf
then liftM Just $ peekCString c_val
else return Nothing
host <- peekIf doHost c_host
serv <- peekIf doService c_serv
return (host, serv)
_ -> do err <- gai_strerror ret
ioError (ioeSetErrorString
(mkIOError NoSuchThing "Network.Socket.getNameInfo" Nothing
Nothing) err)
foreign import ccall safe "hsnet_getnameinfo"
c_getnameinfo :: Ptr SockAddr -> CInt{-CSockLen???-} -> CString -> CSize -> CString
-> CSize -> CInt -> IO CInt
{-# LINE 1556 "Network/Socket.hsc" #-}
mkInvalidRecvArgError :: String -> IOError
mkInvalidRecvArgError loc = ioeSetErrorString (mkIOError
InvalidArgument
loc Nothing Nothing) "non-positive length"
mkEOFError :: String -> IOError
mkEOFError loc = ioeSetErrorString (mkIOError EOF loc Nothing Nothing) "end of file"
-- ---------------------------------------------------------------------------
-- foreign imports from the C library
foreign import ccall unsafe "hsnet_inet_ntoa"
c_inet_ntoa :: HostAddress -> IO (Ptr CChar)
foreign import ccall unsafe "inet_addr"
c_inet_addr :: Ptr CChar -> IO HostAddress
foreign import ccall unsafe "shutdown"
c_shutdown :: CInt -> CInt -> IO CInt
closeFd :: CInt -> IO ()
closeFd fd = throwSocketErrorIfMinus1_ "Network.Socket.close" $ c_close fd
{-# LINE 1581 "Network/Socket.hsc" #-}
foreign import ccall unsafe "close"
c_close :: CInt -> IO CInt
{-# LINE 1587 "Network/Socket.hsc" #-}
foreign import ccall unsafe "socket"
c_socket :: CInt -> CInt -> CInt -> IO CInt
foreign import ccall unsafe "bind"
c_bind :: CInt -> Ptr SockAddr -> CInt{-CSockLen???-} -> IO CInt
foreign import ccall unsafe "connect"
c_connect :: CInt -> Ptr SockAddr -> CInt{-CSockLen???-} -> IO CInt
{-# LINE 1595 "Network/Socket.hsc" #-}
foreign import ccall unsafe "accept4"
c_accept4 :: CInt -> Ptr SockAddr -> Ptr CInt{-CSockLen???-} -> CInt -> IO CInt
{-# LINE 1601 "Network/Socket.hsc" #-}
foreign import ccall unsafe "listen"
c_listen :: CInt -> CInt -> IO CInt
{-# LINE 1610 "Network/Socket.hsc" #-}
foreign import ccall unsafe "send"
c_send :: CInt -> Ptr a -> CSize -> CInt -> IO CInt
foreign import ccall unsafe "sendto"
c_sendto :: CInt -> Ptr a -> CSize -> CInt -> Ptr SockAddr -> CInt -> IO CInt
foreign import ccall unsafe "recv"
c_recv :: CInt -> Ptr CChar -> CSize -> CInt -> IO CInt
foreign import ccall unsafe "recvfrom"
c_recvfrom :: CInt -> Ptr a -> CSize -> CInt -> Ptr SockAddr -> Ptr CInt -> IO CInt
foreign import ccall unsafe "getpeername"
c_getpeername :: CInt -> Ptr SockAddr -> Ptr CInt -> IO CInt
foreign import ccall unsafe "getsockname"
c_getsockname :: CInt -> Ptr SockAddr -> Ptr CInt -> IO CInt
foreign import ccall unsafe "getsockopt"
c_getsockopt :: CInt -> CInt -> CInt -> Ptr CInt -> Ptr CInt -> IO CInt
foreign import ccall unsafe "setsockopt"
c_setsockopt :: CInt -> CInt -> CInt -> Ptr CInt -> CInt -> IO CInt
{-# LINE 1633 "Network/Socket.hsc" #-}
-- ---------------------------------------------------------------------------
-- * Deprecated aliases
-- $deprecated-aliases
--
-- These aliases are deprecated and should not be used in new code.
-- They will be removed in some future version of the package.
{-# DEPRECATED bindSocket "use 'bind'" #-}
-- | Deprecated alias for 'bind'.
bindSocket :: Socket -- Unconnected Socket
-> SockAddr -- Address to Bind to
-> IO ()
bindSocket = bind
{-# DEPRECATED sClose "use 'close'" #-}
-- | Deprecated alias for 'close'.
sClose :: Socket -> IO ()
sClose = close
{-# DEPRECATED sIsConnected "use 'isConnected'" #-}
-- | Deprecated alias for 'isConnected'.
sIsConnected :: Socket -> IO Bool
sIsConnected = isConnected
{-# DEPRECATED sIsBound "use 'isBound'" #-}
-- | Deprecated alias for 'isBound'.
sIsBound :: Socket -> IO Bool
sIsBound = isBound
{-# DEPRECATED sIsListening "use 'isListening'" #-}
-- | Deprecated alias for 'isListening'.
sIsListening :: Socket -> IO Bool
sIsListening = isListening
{-# DEPRECATED sIsReadable "use 'isReadable'" #-}
-- | Deprecated alias for 'isReadable'.
sIsReadable :: Socket -> IO Bool
sIsReadable = isReadable
{-# DEPRECATED sIsWritable "use 'isWritable'" #-}
-- | Deprecated alias for 'isWritable'.
sIsWritable :: Socket -> IO Bool
sIsWritable = isWritable
|
phischu/fragnix
|
tests/packages/scotty/Network.Socket.hs
|
Haskell
|
bsd-3-clause
| 60,647
|
{-# LANGUAGE BangPatterns, DeriveDataTypeable, RecordWildCards #-}
-- |
-- Module : Criterion.Analysis
-- Copyright : (c) 2009-2014 Bryan O'Sullivan
--
-- License : BSD-style
-- Maintainer : bos@serpentine.com
-- Stability : experimental
-- Portability : GHC
--
-- Analysis code for benchmarks.
module Criterion.Analysis
(
Outliers(..)
, OutlierEffect(..)
, OutlierVariance(..)
, SampleAnalysis(..)
, analyseSample
, scale
, analyseMean
, countOutliers
, classifyOutliers
, noteOutliers
, outlierVariance
, resolveAccessors
, validateAccessors
, regress
) where
import Control.Arrow (second)
import Control.Monad (unless, when)
import Control.Monad.Reader (ask)
import Control.Monad.Trans
import Control.Monad.Trans.Except
import Criterion.IO.Printf (note, prolix)
import Criterion.Measurement (secs, threshold)
import Criterion.Monad (Criterion, getGen, getOverhead)
import Criterion.Types
import Data.Int (Int64)
import Data.Maybe (fromJust)
import Data.Monoid (Monoid(..))
import Statistics.Function (sort)
import Statistics.Quantile (weightedAvg)
import Statistics.Regression (bootstrapRegress, olsRegress)
import Statistics.Resampling (resample)
import Statistics.Sample (mean)
import Statistics.Sample.KernelDensity (kde)
import Statistics.Types (Estimator(..), Sample)
import System.Random.MWC (GenIO)
import qualified Data.List as List
import qualified Data.Map as Map
import qualified Data.Vector as V
import qualified Data.Vector.Generic as G
import qualified Data.Vector.Unboxed as U
import qualified Statistics.Resampling.Bootstrap as B
-- | Classify outliers in a data set, using the boxplot technique.
classifyOutliers :: Sample -> Outliers
classifyOutliers sa = U.foldl' ((. outlier) . mappend) mempty ssa
where outlier e = Outliers {
samplesSeen = 1
, lowSevere = if e <= loS && e < hiM then 1 else 0
, lowMild = if e > loS && e <= loM then 1 else 0
, highMild = if e >= hiM && e < hiS then 1 else 0
, highSevere = if e >= hiS && e > loM then 1 else 0
}
!loS = q1 - (iqr * 3)
!loM = q1 - (iqr * 1.5)
!hiM = q3 + (iqr * 1.5)
!hiS = q3 + (iqr * 3)
q1 = weightedAvg 1 4 ssa
q3 = weightedAvg 3 4 ssa
ssa = sort sa
iqr = q3 - q1
-- | Compute the extent to which outliers in the sample data affect
-- the sample mean and standard deviation.
outlierVariance :: B.Estimate -- ^ Bootstrap estimate of sample mean.
-> B.Estimate -- ^ Bootstrap estimate of sample
-- standard deviation.
-> Double -- ^ Number of original iterations.
-> OutlierVariance
outlierVariance µ σ a = OutlierVariance effect desc varOutMin
where
( effect, desc ) | varOutMin < 0.01 = (Unaffected, "no")
| varOutMin < 0.1 = (Slight, "slight")
| varOutMin < 0.5 = (Moderate, "moderate")
| otherwise = (Severe, "severe")
varOutMin = (minBy varOut 1 (minBy cMax 0 µgMin)) / σb2
varOut c = (ac / a) * (σb2 - ac * σg2) where ac = a - c
σb = B.estPoint σ
µa = B.estPoint µ / a
µgMin = µa / 2
σg = min (µgMin / 4) (σb / sqrt a)
σg2 = σg * σg
σb2 = σb * σb
minBy f q r = min (f q) (f r)
cMax x = fromIntegral (floor (-2 * k0 / (k1 + sqrt det)) :: Int)
where
k1 = σb2 - a * σg2 + ad
k0 = -a * ad
ad = a * d
d = k * k where k = µa - x
det = k1 * k1 - 4 * σg2 * k0
-- | Count the total number of outliers in a sample.
countOutliers :: Outliers -> Int64
countOutliers (Outliers _ a b c d) = a + b + c + d
{-# INLINE countOutliers #-}
-- | Display the mean of a 'Sample', and characterise the outliers
-- present in the sample.
analyseMean :: Sample
-> Int -- ^ Number of iterations used to
-- compute the sample.
-> Criterion Double
analyseMean a iters = do
let µ = mean a
_ <- note "mean is %s (%d iterations)\n" (secs µ) iters
noteOutliers . classifyOutliers $ a
return µ
-- | Multiply the 'Estimate's in an analysis by the given value, using
-- 'B.scale'.
scale :: Double -- ^ Value to multiply by.
-> SampleAnalysis -> SampleAnalysis
scale f s@SampleAnalysis{..} = s {
anMean = B.scale f anMean
, anStdDev = B.scale f anStdDev
}
-- | Perform an analysis of a measurement.
analyseSample :: Int -- ^ Experiment number.
-> String -- ^ Experiment name.
-> V.Vector Measured -- ^ Sample data.
-> ExceptT String Criterion Report
analyseSample i name meas = do
Config{..} <- ask
overhead <- lift getOverhead
let ests = [Mean,StdDev]
-- The use of filter here throws away very-low-quality
-- measurements when bootstrapping the mean and standard
-- deviations. Without this, the numbers look nonsensical when
-- very brief actions are measured.
stime = measure (measTime . rescale) .
G.filter ((>= threshold) . measTime) . G.map fixTime .
G.tail $ meas
fixTime m = m { measTime = measTime m - overhead / 2 }
n = G.length meas
s = G.length stime
_ <- lift $ prolix "bootstrapping with %d of %d samples (%d%%)\n"
s n ((s * 100) `quot` n)
gen <- lift getGen
rs <- mapM (\(ps,r) -> regress gen ps r meas) $
((["iters"],"time"):regressions)
resamps <- liftIO $ resample gen ests resamples stime
let [estMean,estStdDev] = B.bootstrapBCA confInterval stime ests resamps
ov = outlierVariance estMean estStdDev (fromIntegral n)
an = SampleAnalysis {
anRegress = rs
, anOverhead = overhead
, anMean = estMean
, anStdDev = estStdDev
, anOutlierVar = ov
}
return Report {
reportNumber = i
, reportName = name
, reportKeys = measureKeys
, reportMeasured = meas
, reportAnalysis = an
, reportOutliers = classifyOutliers stime
, reportKDEs = [uncurry (KDE "time") (kde 128 stime)]
}
-- | Regress the given predictors against the responder.
--
-- Errors may be returned under various circumstances, such as invalid
-- names or lack of needed data.
--
-- See 'olsRegress' for details of the regression performed.
regress :: GenIO
-> [String] -- ^ Predictor names.
-> String -- ^ Responder name.
-> V.Vector Measured
-> ExceptT String Criterion Regression
regress gen predNames respName meas = do
when (G.null meas) $
throwE "no measurements"
accs <- ExceptT . return $ validateAccessors predNames respName
let unmeasured = [n | (n, Nothing) <- map (second ($ G.head meas)) accs]
unless (null unmeasured) $
throwE $ "no data available for " ++ renderNames unmeasured
let (r:ps) = map ((`measure` meas) . (fromJust .) . snd) accs
Config{..} <- ask
(coeffs,r2) <- liftIO $
bootstrapRegress gen resamples confInterval olsRegress ps r
return Regression {
regResponder = respName
, regCoeffs = Map.fromList (zip (predNames ++ ["y"]) (G.toList coeffs))
, regRSquare = r2
}
singleton :: [a] -> Bool
singleton [_] = True
singleton _ = False
-- | Given a list of accessor names (see 'measureKeys'), return either
-- a mapping from accessor name to function or an error message if
-- any names are wrong.
resolveAccessors :: [String]
-> Either String [(String, Measured -> Maybe Double)]
resolveAccessors names =
case unresolved of
[] -> Right [(n, a) | (n, Just (a,_)) <- accessors]
_ -> Left $ "unknown metric " ++ renderNames unresolved
where
unresolved = [n | (n, Nothing) <- accessors]
accessors = flip map names $ \n -> (n, Map.lookup n measureAccessors)
-- | Given predictor and responder names, do some basic validation,
-- then hand back the relevant accessors.
validateAccessors :: [String] -- ^ Predictor names.
-> String -- ^ Responder name.
-> Either String [(String, Measured -> Maybe Double)]
validateAccessors predNames respName = do
when (null predNames) $
Left "no predictors specified"
let names = respName:predNames
dups = map head . filter (not . singleton) .
List.group . List.sort $ names
unless (null dups) $
Left $ "duplicated metric " ++ renderNames dups
resolveAccessors names
renderNames :: [String] -> String
renderNames = List.intercalate ", " . map show
-- | Display a report of the 'Outliers' present in a 'Sample'.
noteOutliers :: Outliers -> Criterion ()
noteOutliers o = do
let frac n = (100::Double) * fromIntegral n / fromIntegral (samplesSeen o)
check :: Int64 -> Double -> String -> Criterion ()
check k t d = when (frac k > t) $
note " %d (%.1g%%) %s\n" k (frac k) d
outCount = countOutliers o
when (outCount > 0) $ do
_ <- note "found %d outliers among %d samples (%.1g%%)\n"
outCount (samplesSeen o) (frac outCount)
check (lowSevere o) 0 "low severe"
check (lowMild o) 1 "low mild"
check (highMild o) 1 "high mild"
check (highSevere o) 0 "high severe"
|
paulolieuthier/criterion
|
Criterion/Analysis.hs
|
Haskell
|
bsd-2-clause
| 9,668
|
{-# LANGUAGE DeriveDataTypeable #-}
module Main
( main
) where
import Test.Tasty
import Test.Tasty.Options
import Data.Proxy
import Data.Typeable
import Distribution.Simple.Utils
import Distribution.Verbosity
import Distribution.Compat.Time
import qualified UnitTests.Distribution.Compat.CreatePipe
import qualified UnitTests.Distribution.Compat.ReadP
import qualified UnitTests.Distribution.Compat.Time
import qualified UnitTests.Distribution.Simple.Program.Internal
import qualified UnitTests.Distribution.Simple.Utils
import qualified UnitTests.Distribution.System
import qualified UnitTests.Distribution.Utils.NubList
import qualified UnitTests.Distribution.Version (versionTests)
tests :: Int -> TestTree
tests mtimeChangeCalibrated =
askOption $ \(OptionMtimeChangeDelay mtimeChangeProvided) ->
let mtimeChange = if mtimeChangeProvided /= 0
then mtimeChangeProvided
else mtimeChangeCalibrated
in
testGroup "Unit Tests" $
[ testGroup "Distribution.Compat.CreatePipe"
UnitTests.Distribution.Compat.CreatePipe.tests
, testGroup "Distribution.Compat.ReadP"
UnitTests.Distribution.Compat.ReadP.tests
, testGroup "Distribution.Compat.Time"
(UnitTests.Distribution.Compat.Time.tests mtimeChange)
, testGroup "Distribution.Simple.Program.Internal"
UnitTests.Distribution.Simple.Program.Internal.tests
, testGroup "Distribution.Simple.Utils"
UnitTests.Distribution.Simple.Utils.tests
, testGroup "Distribution.Utils.NubList"
UnitTests.Distribution.Utils.NubList.tests
, testGroup "Distribution.System"
UnitTests.Distribution.System.tests
, testGroup "Distribution.Version"
UnitTests.Distribution.Version.versionTests
]
extraOptions :: [OptionDescription]
extraOptions =
[ Option (Proxy :: Proxy OptionMtimeChangeDelay)
]
newtype OptionMtimeChangeDelay = OptionMtimeChangeDelay Int
deriving Typeable
instance IsOption OptionMtimeChangeDelay where
defaultValue = OptionMtimeChangeDelay 0
parseValue = fmap OptionMtimeChangeDelay . safeRead
optionName = return "mtime-change-delay"
optionHelp = return $ "How long to wait before attempting to detect"
++ "file modification, in microseconds"
main :: IO ()
main = do
(mtimeChange, mtimeChange') <- calibrateMtimeChangeDelay
let toMillis :: Int -> Double
toMillis x = fromIntegral x / 1000.0
notice normal $ "File modification time resolution calibration completed, "
++ "maximum delay observed: "
++ (show . toMillis $ mtimeChange ) ++ " ms. "
++ "Will be using delay of " ++ (show . toMillis $ mtimeChange')
++ " for test runs."
defaultMainWithIngredients
(includingOptions extraOptions : defaultIngredients)
(tests mtimeChange')
|
thomie/cabal
|
Cabal/tests/UnitTests.hs
|
Haskell
|
bsd-3-clause
| 2,833
|
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE BangPatterns, NoImplicitPrelude #-}
-- Copyright (c) 2008, Ralf Hinze
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions
-- are met:
--
-- * Redistributions of source code must retain the above
-- copyright notice, this list of conditions and the following
-- disclaimer.
--
-- * Redistributions in binary form must reproduce the above
-- copyright notice, this list of conditions and the following
-- disclaimer in the documentation and/or other materials
-- provided with the distribution.
--
-- * The names of the contributors may not be used to endorse or
-- promote products derived from this software without specific
-- prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
-- FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
-- COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
-- INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
-- (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
-- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
-- HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
-- STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
-- OF THE POSSIBILITY OF SUCH DAMAGE.
-- | A /priority search queue/ (henceforth /queue/) efficiently
-- supports the operations of both a search tree and a priority queue.
-- An 'Elem'ent is a product of a key, a priority, and a
-- value. Elements can be inserted, deleted, modified and queried in
-- logarithmic time, and the element with the least priority can be
-- retrieved in constant time. A queue can be built from a list of
-- elements, sorted by keys, in linear time.
--
-- This implementation is due to Ralf Hinze with some modifications by
-- Scott Dillard and Johan Tibell.
--
-- * Hinze, R., /A Simple Implementation Technique for Priority Search
-- Queues/, ICFP 2001, pp. 110-121
--
-- <http://citeseer.ist.psu.edu/hinze01simple.html>
module GHC.Event.PSQ
(
-- * Binding Type
Elem(..)
, Key
, Prio
-- * Priority Search Queue Type
, PSQ
-- * Query
, size
, null
, lookup
-- * Construction
, empty
, singleton
-- * Insertion
, insert
-- * Delete/Update
, delete
, adjust
-- * Conversion
, toList
, toAscList
, toDescList
, fromList
-- * Min
, findMin
, deleteMin
, minView
, atMost
) where
import GHC.Base hiding (empty)
import GHC.Num (Num(..))
import GHC.Show (Show(showsPrec))
import GHC.Event.Unique (Unique)
-- | @E k p@ binds the key @k@ with the priority @p@.
data Elem a = E
{ key :: {-# UNPACK #-} !Key
, prio :: {-# UNPACK #-} !Prio
, value :: a
} deriving (Eq, Show)
------------------------------------------------------------------------
-- | A mapping from keys @k@ to priorites @p@.
type Prio = Double
type Key = Unique
data PSQ a = Void
| Winner {-# UNPACK #-} !(Elem a)
!(LTree a)
{-# UNPACK #-} !Key -- max key
deriving (Eq, Show)
-- | /O(1)/ The number of elements in a queue.
size :: PSQ a -> Int
size Void = 0
size (Winner _ lt _) = 1 + size' lt
-- | /O(1)/ True if the queue is empty.
null :: PSQ a -> Bool
null Void = True
null (Winner _ _ _) = False
-- | /O(log n)/ The priority and value of a given key, or Nothing if
-- the key is not bound.
lookup :: Key -> PSQ a -> Maybe (Prio, a)
lookup k q = case tourView q of
Null -> Nothing
Single (E k' p v)
| k == k' -> Just (p, v)
| otherwise -> Nothing
tl `Play` tr
| k <= maxKey tl -> lookup k tl
| otherwise -> lookup k tr
------------------------------------------------------------------------
-- Construction
empty :: PSQ a
empty = Void
-- | /O(1)/ Build a queue with one element.
singleton :: Key -> Prio -> a -> PSQ a
singleton k p v = Winner (E k p v) Start k
------------------------------------------------------------------------
-- Insertion
-- | /O(log n)/ Insert a new key, priority and value in the queue. If
-- the key is already present in the queue, the associated priority
-- and value are replaced with the supplied priority and value.
insert :: Key -> Prio -> a -> PSQ a -> PSQ a
insert k p v q = case q of
Void -> singleton k p v
Winner (E k' p' v') Start _ -> case compare k k' of
LT -> singleton k p v `play` singleton k' p' v'
EQ -> singleton k p v
GT -> singleton k' p' v' `play` singleton k p v
Winner e (RLoser _ e' tl m tr) m'
| k <= m -> insert k p v (Winner e tl m) `play` (Winner e' tr m')
| otherwise -> (Winner e tl m) `play` insert k p v (Winner e' tr m')
Winner e (LLoser _ e' tl m tr) m'
| k <= m -> insert k p v (Winner e' tl m) `play` (Winner e tr m')
| otherwise -> (Winner e' tl m) `play` insert k p v (Winner e tr m')
------------------------------------------------------------------------
-- Delete/Update
-- | /O(log n)/ Delete a key and its priority and value from the
-- queue. When the key is not a member of the queue, the original
-- queue is returned.
delete :: Key -> PSQ a -> PSQ a
delete k q = case q of
Void -> empty
Winner (E k' p v) Start _
| k == k' -> empty
| otherwise -> singleton k' p v
Winner e (RLoser _ e' tl m tr) m'
| k <= m -> delete k (Winner e tl m) `play` (Winner e' tr m')
| otherwise -> (Winner e tl m) `play` delete k (Winner e' tr m')
Winner e (LLoser _ e' tl m tr) m'
| k <= m -> delete k (Winner e' tl m) `play` (Winner e tr m')
| otherwise -> (Winner e' tl m) `play` delete k (Winner e tr m')
-- | /O(log n)/ Update a priority at a specific key with the result
-- of the provided function. When the key is not a member of the
-- queue, the original queue is returned.
adjust :: (Prio -> Prio) -> Key -> PSQ a -> PSQ a
adjust f k q0 = go q0
where
go q = case q of
Void -> empty
Winner (E k' p v) Start _
| k == k' -> singleton k' (f p) v
| otherwise -> singleton k' p v
Winner e (RLoser _ e' tl m tr) m'
| k <= m -> go (Winner e tl m) `unsafePlay` (Winner e' tr m')
| otherwise -> (Winner e tl m) `unsafePlay` go (Winner e' tr m')
Winner e (LLoser _ e' tl m tr) m'
| k <= m -> go (Winner e' tl m) `unsafePlay` (Winner e tr m')
| otherwise -> (Winner e' tl m) `unsafePlay` go (Winner e tr m')
{-# INLINE adjust #-}
------------------------------------------------------------------------
-- Conversion
-- | /O(n*log n)/ Build a queue from a list of key/priority/value
-- tuples. If the list contains more than one priority and value for
-- the same key, the last priority and value for the key is retained.
fromList :: [Elem a] -> PSQ a
fromList = foldr (\(E k p v) q -> insert k p v q) empty
-- | /O(n)/ Convert to a list of key/priority/value tuples.
toList :: PSQ a -> [Elem a]
toList = toAscList
-- | /O(n)/ Convert to an ascending list.
toAscList :: PSQ a -> [Elem a]
toAscList q = seqToList (toAscLists q)
toAscLists :: PSQ a -> Sequ (Elem a)
toAscLists q = case tourView q of
Null -> emptySequ
Single e -> singleSequ e
tl `Play` tr -> toAscLists tl <> toAscLists tr
-- | /O(n)/ Convert to a descending list.
toDescList :: PSQ a -> [ Elem a ]
toDescList q = seqToList (toDescLists q)
toDescLists :: PSQ a -> Sequ (Elem a)
toDescLists q = case tourView q of
Null -> emptySequ
Single e -> singleSequ e
tl `Play` tr -> toDescLists tr <> toDescLists tl
------------------------------------------------------------------------
-- Min
-- | /O(1)/ The element with the lowest priority.
findMin :: PSQ a -> Maybe (Elem a)
findMin Void = Nothing
findMin (Winner e _ _) = Just e
-- | /O(log n)/ Delete the element with the lowest priority. Returns
-- an empty queue if the queue is empty.
deleteMin :: PSQ a -> PSQ a
deleteMin Void = Void
deleteMin (Winner _ t m) = secondBest t m
-- | /O(log n)/ Retrieve the binding with the least priority, and the
-- rest of the queue stripped of that binding.
minView :: PSQ a -> Maybe (Elem a, PSQ a)
minView Void = Nothing
minView (Winner e t m) = Just (e, secondBest t m)
secondBest :: LTree a -> Key -> PSQ a
secondBest Start _ = Void
secondBest (LLoser _ e tl m tr) m' = Winner e tl m `play` secondBest tr m'
secondBest (RLoser _ e tl m tr) m' = secondBest tl m `play` Winner e tr m'
-- | /O(r*(log n - log r))/ Return a list of elements ordered by
-- key whose priorities are at most @pt@.
atMost :: Prio -> PSQ a -> ([Elem a], PSQ a)
atMost pt q = let (sequ, q') = atMosts pt q
in (seqToList sequ, q')
atMosts :: Prio -> PSQ a -> (Sequ (Elem a), PSQ a)
atMosts !pt q = case q of
(Winner e _ _)
| prio e > pt -> (emptySequ, q)
Void -> (emptySequ, Void)
Winner e Start _ -> (singleSequ e, Void)
Winner e (RLoser _ e' tl m tr) m' ->
let (sequ, q') = atMosts pt (Winner e tl m)
(sequ', q'') = atMosts pt (Winner e' tr m')
in (sequ <> sequ', q' `play` q'')
Winner e (LLoser _ e' tl m tr) m' ->
let (sequ, q') = atMosts pt (Winner e' tl m)
(sequ', q'') = atMosts pt (Winner e tr m')
in (sequ <> sequ', q' `play` q'')
------------------------------------------------------------------------
-- Loser tree
type Size = Int
data LTree a = Start
| LLoser {-# UNPACK #-} !Size
{-# UNPACK #-} !(Elem a)
!(LTree a)
{-# UNPACK #-} !Key -- split key
!(LTree a)
| RLoser {-# UNPACK #-} !Size
{-# UNPACK #-} !(Elem a)
!(LTree a)
{-# UNPACK #-} !Key -- split key
!(LTree a)
deriving (Eq, Show)
size' :: LTree a -> Size
size' Start = 0
size' (LLoser s _ _ _ _) = s
size' (RLoser s _ _ _ _) = s
left, right :: LTree a -> LTree a
left Start = moduleError "left" "empty loser tree"
left (LLoser _ _ tl _ _ ) = tl
left (RLoser _ _ tl _ _ ) = tl
right Start = moduleError "right" "empty loser tree"
right (LLoser _ _ _ _ tr) = tr
right (RLoser _ _ _ _ tr) = tr
maxKey :: PSQ a -> Key
maxKey Void = moduleError "maxKey" "empty queue"
maxKey (Winner _ _ m) = m
lloser, rloser :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a
lloser k p v tl m tr = LLoser (1 + size' tl + size' tr) (E k p v) tl m tr
rloser k p v tl m tr = RLoser (1 + size' tl + size' tr) (E k p v) tl m tr
------------------------------------------------------------------------
-- Balancing
-- | Balance factor
omega :: Int
omega = 4
lbalance, rbalance :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a
lbalance k p v l m r
| size' l + size' r < 2 = lloser k p v l m r
| size' r > omega * size' l = lbalanceLeft k p v l m r
| size' l > omega * size' r = lbalanceRight k p v l m r
| otherwise = lloser k p v l m r
rbalance k p v l m r
| size' l + size' r < 2 = rloser k p v l m r
| size' r > omega * size' l = rbalanceLeft k p v l m r
| size' l > omega * size' r = rbalanceRight k p v l m r
| otherwise = rloser k p v l m r
lbalanceLeft :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a
lbalanceLeft k p v l m r
| size' (left r) < size' (right r) = lsingleLeft k p v l m r
| otherwise = ldoubleLeft k p v l m r
lbalanceRight :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a
lbalanceRight k p v l m r
| size' (left l) > size' (right l) = lsingleRight k p v l m r
| otherwise = ldoubleRight k p v l m r
rbalanceLeft :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a
rbalanceLeft k p v l m r
| size' (left r) < size' (right r) = rsingleLeft k p v l m r
| otherwise = rdoubleLeft k p v l m r
rbalanceRight :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a
rbalanceRight k p v l m r
| size' (left l) > size' (right l) = rsingleRight k p v l m r
| otherwise = rdoubleRight k p v l m r
lsingleLeft :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a
lsingleLeft k1 p1 v1 t1 m1 (LLoser _ (E k2 p2 v2) t2 m2 t3)
| p1 <= p2 = lloser k1 p1 v1 (rloser k2 p2 v2 t1 m1 t2) m2 t3
| otherwise = lloser k2 p2 v2 (lloser k1 p1 v1 t1 m1 t2) m2 t3
lsingleLeft k1 p1 v1 t1 m1 (RLoser _ (E k2 p2 v2) t2 m2 t3) =
rloser k2 p2 v2 (lloser k1 p1 v1 t1 m1 t2) m2 t3
lsingleLeft _ _ _ _ _ _ = moduleError "lsingleLeft" "malformed tree"
rsingleLeft :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a
rsingleLeft k1 p1 v1 t1 m1 (LLoser _ (E k2 p2 v2) t2 m2 t3) =
rloser k1 p1 v1 (rloser k2 p2 v2 t1 m1 t2) m2 t3
rsingleLeft k1 p1 v1 t1 m1 (RLoser _ (E k2 p2 v2) t2 m2 t3) =
rloser k2 p2 v2 (rloser k1 p1 v1 t1 m1 t2) m2 t3
rsingleLeft _ _ _ _ _ _ = moduleError "rsingleLeft" "malformed tree"
lsingleRight :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a
lsingleRight k1 p1 v1 (LLoser _ (E k2 p2 v2) t1 m1 t2) m2 t3 =
lloser k2 p2 v2 t1 m1 (lloser k1 p1 v1 t2 m2 t3)
lsingleRight k1 p1 v1 (RLoser _ (E k2 p2 v2) t1 m1 t2) m2 t3 =
lloser k1 p1 v1 t1 m1 (lloser k2 p2 v2 t2 m2 t3)
lsingleRight _ _ _ _ _ _ = moduleError "lsingleRight" "malformed tree"
rsingleRight :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a
rsingleRight k1 p1 v1 (LLoser _ (E k2 p2 v2) t1 m1 t2) m2 t3 =
lloser k2 p2 v2 t1 m1 (rloser k1 p1 v1 t2 m2 t3)
rsingleRight k1 p1 v1 (RLoser _ (E k2 p2 v2) t1 m1 t2) m2 t3
| p1 <= p2 = rloser k1 p1 v1 t1 m1 (lloser k2 p2 v2 t2 m2 t3)
| otherwise = rloser k2 p2 v2 t1 m1 (rloser k1 p1 v1 t2 m2 t3)
rsingleRight _ _ _ _ _ _ = moduleError "rsingleRight" "malformed tree"
ldoubleLeft :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a
ldoubleLeft k1 p1 v1 t1 m1 (LLoser _ (E k2 p2 v2) t2 m2 t3) =
lsingleLeft k1 p1 v1 t1 m1 (lsingleRight k2 p2 v2 t2 m2 t3)
ldoubleLeft k1 p1 v1 t1 m1 (RLoser _ (E k2 p2 v2) t2 m2 t3) =
lsingleLeft k1 p1 v1 t1 m1 (rsingleRight k2 p2 v2 t2 m2 t3)
ldoubleLeft _ _ _ _ _ _ = moduleError "ldoubleLeft" "malformed tree"
ldoubleRight :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a
ldoubleRight k1 p1 v1 (LLoser _ (E k2 p2 v2) t1 m1 t2) m2 t3 =
lsingleRight k1 p1 v1 (lsingleLeft k2 p2 v2 t1 m1 t2) m2 t3
ldoubleRight k1 p1 v1 (RLoser _ (E k2 p2 v2) t1 m1 t2) m2 t3 =
lsingleRight k1 p1 v1 (rsingleLeft k2 p2 v2 t1 m1 t2) m2 t3
ldoubleRight _ _ _ _ _ _ = moduleError "ldoubleRight" "malformed tree"
rdoubleLeft :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a
rdoubleLeft k1 p1 v1 t1 m1 (LLoser _ (E k2 p2 v2) t2 m2 t3) =
rsingleLeft k1 p1 v1 t1 m1 (lsingleRight k2 p2 v2 t2 m2 t3)
rdoubleLeft k1 p1 v1 t1 m1 (RLoser _ (E k2 p2 v2) t2 m2 t3) =
rsingleLeft k1 p1 v1 t1 m1 (rsingleRight k2 p2 v2 t2 m2 t3)
rdoubleLeft _ _ _ _ _ _ = moduleError "rdoubleLeft" "malformed tree"
rdoubleRight :: Key -> Prio -> a -> LTree a -> Key -> LTree a -> LTree a
rdoubleRight k1 p1 v1 (LLoser _ (E k2 p2 v2) t1 m1 t2) m2 t3 =
rsingleRight k1 p1 v1 (lsingleLeft k2 p2 v2 t1 m1 t2) m2 t3
rdoubleRight k1 p1 v1 (RLoser _ (E k2 p2 v2) t1 m1 t2) m2 t3 =
rsingleRight k1 p1 v1 (rsingleLeft k2 p2 v2 t1 m1 t2) m2 t3
rdoubleRight _ _ _ _ _ _ = moduleError "rdoubleRight" "malformed tree"
-- | Take two pennants and returns a new pennant that is the union of
-- the two with the precondition that the keys in the first tree are
-- strictly smaller than the keys in the second tree.
play :: PSQ a -> PSQ a -> PSQ a
Void `play` t' = t'
t `play` Void = t
Winner e@(E k p v) t m `play` Winner e'@(E k' p' v') t' m'
| p <= p' = Winner e (rbalance k' p' v' t m t') m'
| otherwise = Winner e' (lbalance k p v t m t') m'
{-# INLINE play #-}
-- | A version of 'play' that can be used if the shape of the tree has
-- not changed or if the tree is known to be balanced.
unsafePlay :: PSQ a -> PSQ a -> PSQ a
Void `unsafePlay` t' = t'
t `unsafePlay` Void = t
Winner e@(E k p v) t m `unsafePlay` Winner e'@(E k' p' v') t' m'
| p <= p' = Winner e (rloser k' p' v' t m t') m'
| otherwise = Winner e' (lloser k p v t m t') m'
{-# INLINE unsafePlay #-}
data TourView a = Null
| Single {-# UNPACK #-} !(Elem a)
| (PSQ a) `Play` (PSQ a)
tourView :: PSQ a -> TourView a
tourView Void = Null
tourView (Winner e Start _) = Single e
tourView (Winner e (RLoser _ e' tl m tr) m') =
Winner e tl m `Play` Winner e' tr m'
tourView (Winner e (LLoser _ e' tl m tr) m') =
Winner e' tl m `Play` Winner e tr m'
------------------------------------------------------------------------
-- Utility functions
moduleError :: String -> String -> a
moduleError fun msg = errorWithoutStackTrace ("GHC.Event.PSQ." ++ fun ++ ':' : ' ' : msg)
{-# NOINLINE moduleError #-}
------------------------------------------------------------------------
-- Hughes's efficient sequence type
newtype Sequ a = Sequ ([a] -> [a])
emptySequ :: Sequ a
emptySequ = Sequ (\as -> as)
singleSequ :: a -> Sequ a
singleSequ a = Sequ (\as -> a : as)
(<>) :: Sequ a -> Sequ a -> Sequ a
Sequ x1 <> Sequ x2 = Sequ (\as -> x1 (x2 as))
infixr 5 <>
seqToList :: Sequ a -> [a]
seqToList (Sequ x) = x []
-- | @since 4.3.1.0
instance Show a => Show (Sequ a) where
showsPrec d a = showsPrec d (seqToList a)
|
snoyberg/ghc
|
libraries/base/GHC/Event/PSQ.hs
|
Haskell
|
bsd-3-clause
| 18,113
|
module AmortizedQueue where
import Prelude hiding (head)
data AbsQueue a = AQ { front :: [a]
, rear :: [a] }
{-@ data AbsQueue a = AQ { front :: [a]
, rear :: {v:[a] | size v <= size front} } @-}
{-@ die :: {v:String | false} -> a @-}
die :: String -> a
die x = error x
{-@ measure size @-}
size :: [a] -> Int
size [] = 0
size (x:xs) = 1 + size xs
{-@ measure qsize @-}
qsize :: AbsQueue a -> Int
qsize (AQ xs ys) = size xs + size ys
{-@ invariant {v:[a] | size v >= 0} @-}
{-@ invariant {v:AbsQueue a | qsize v >= 0} @-}
{-@ type NEList a = {v:[a] | size v > 0} @-}
{-@ type NEQueue a = {v:AbsQueue a | qsize v > 0} @-}
makeQueue :: [a] -> [a] -> AbsQueue a
makeQueue f b
| size b <= size f = AQ f b
| otherwise = AQ (f ++ reverse b) []
{- measure qhead @-}
{-@ qhead :: NEQueue a -> a @-}
qhead (AQ f _) = head f
qhead _ = die "never"
{- measure head @-}
{-@ head :: NEList a -> a @-}
head (x:_) = x
-- head _ = die "never"
{- toList :: q:AbsQueue a -> {v:[a] | 0 < len v => head v = front q} @-}
toList :: AbsQueue a -> [a]
toList = undefined
-- forall q :: AbsQueue a, xs:: [a], x::a.
-- not (isEmpty(q)) && asList(q) == xs =>
{-
import leon.lang._
import leon.annotation._
object AmortizedQueue {
sealed abstract class List
case class Cons(head : Int, tail : List) extends List
case object Nil extends List
sealed abstract class AbsQueue
case class Queue(front : List, rear : List) extends AbsQueue
def size(list : List) : Int = (list match {
case Nil => 0
case Cons(_, xs) => 1 + size(xs)
}) ensuring(_ >= 0)
def content(l: List) : Set[Int] = l match {
case Nil => Set.empty[Int]
case Cons(x, xs) => Set(x) ++ content(xs)
}
def asList(queue : AbsQueue) : List = queue match {
case Queue(front, rear) => concat(front, reverse(rear))
}
def concat(l1 : List, l2 : List) : List = (l1 match {
case Nil => l2
case Cons(x,xs) => Cons(x, concat(xs, l2))
}) ensuring (res => size(res) == size(l1) + size(l2) && content(res) == content(l1) ++ content(l2))
def isAmortized(queue : AbsQueue) : Boolean = queue match {
case Queue(front, rear) => size(front) >= size(rear)
}
def isEmpty(queue : AbsQueue) : Boolean = queue match {
case Queue(Nil, Nil) => true
case _ => false
}
def reverse(l : List) : List = (l match {
case Nil => Nil
case Cons(x, xs) => concat(reverse(xs), Cons(x, Nil))
}) ensuring (content(_) == content(l))
def amortizedQueue(front : List, rear : List) : AbsQueue = {
if (size(rear) <= size(front))
Queue(front, rear)
else
Queue(concat(front, reverse(rear)), Nil)
} ensuring(isAmortized(_))
def enqueue(queue : AbsQueue, elem : Int) : AbsQueue = (queue match {
case Queue(front, rear) => amortizedQueue(front, Cons(elem, rear))
}) ensuring(isAmortized(_))
def tail(queue : AbsQueue) : AbsQueue = {
require(isAmortized(queue) && !isEmpty(queue))
queue match {
case Queue(Cons(f, fs), rear) => amortizedQueue(fs, rear)
}
} ensuring (isAmortized(_))
def front(queue : AbsQueue) : Int = {
require(isAmortized(queue) && !isEmpty(queue))
queue match {
case Queue(Cons(f, _), _) => f
}
}
@induct
def propFront(queue : AbsQueue, list : List) : Boolean = {
require(!isEmpty(queue) && isAmortized(queue))
if (asList(queue) == list) {
list match {
case Cons(x, _) => front(queue) == x
}
} else
true
} holds
def enqueueAndFront(queue : AbsQueue, elem : Int) : Boolean = {
if (isEmpty(queue))
front(enqueue(queue, elem)) == elem
else
true
} holds
def enqueueDequeueThrice(queue : AbsQueue, e1 : Int, e2 : Int, e3 : Int) : Boolean = {
if (isEmpty(queue)) {
val q1 = enqueue(queue, e1)
val q2 = enqueue(q1, e2)
val q3 = enqueue(q2, e3)
val e1prime = front(q3)
val q4 = tail(q3)
val e2prime = front(q4)
val q5 = tail(q4)
val e3prime = front(q5)
e1 == e1prime && e2 == e2prime && e3 == e3prime
} else
true
} holds
}
-}
|
abakst/liquidhaskell
|
tests/todo/AmortizedQueue.hs
|
Haskell
|
bsd-3-clause
| 4,228
|
{-# LANGUAGE CPP, TupleSections #-}
{-# OPTIONS_GHC -fno-cse #-}
-- -fno-cse is needed for GLOBAL_VAR's to behave properly
-----------------------------------------------------------------------------
--
-- Static flags
--
-- Static flags can only be set once, on the command-line. Inside GHC,
-- each static flag corresponds to a top-level value, usually of type Bool.
--
-- (c) The University of Glasgow 2005
--
-----------------------------------------------------------------------------
module StaticFlags (
-- entry point
parseStaticFlags,
staticFlags,
initStaticOpts,
discardStaticFlags,
-- Output style options
opt_PprStyle_Debug,
opt_NoDebugOutput,
-- optimisation opts
opt_NoStateHack,
opt_NoOptCoercion,
-- For the parser
addOpt, removeOpt, v_opt_C_ready,
-- For options autocompletion
flagsStatic, flagsStaticNames
) where
#include "HsVersions.h"
import CmdLineParser
import FastString
import SrcLoc
import Util
import Panic
import Control.Monad
import Data.IORef
import System.IO.Unsafe ( unsafePerformIO )
-----------------------------------------------------------------------------
-- Static flags
-- | Parses GHC's static flags from a list of command line arguments.
--
-- These flags are static in the sense that they can be set only once and they
-- are global, meaning that they affect every instance of GHC running;
-- multiple GHC threads will use the same flags.
--
-- This function must be called before any session is started, i.e., before
-- the first call to 'GHC.withGhc'.
--
-- Static flags are more of a hack and are static for more or less historical
-- reasons. In the long run, most static flags should eventually become
-- dynamic flags.
--
-- XXX: can we add an auto-generated list of static flags here?
--
parseStaticFlags :: [Located String] -> IO ([Located String], [Located String])
parseStaticFlags = parseStaticFlagsFull flagsStatic
-- | Parse GHC's static flags as @parseStaticFlags@ does. However it also
-- takes a list of available static flags, such that certain flags can be
-- enabled or disabled through this argument.
parseStaticFlagsFull :: [Flag IO] -> [Located String]
-> IO ([Located String], [Located String])
parseStaticFlagsFull flagsAvailable args = do
ready <- readIORef v_opt_C_ready
when ready $ throwGhcExceptionIO (ProgramError "Too late for parseStaticFlags: call it before runGhc or runGhcT")
(leftover, errs, warns) <- processArgs flagsAvailable args
-- See Note [Handling errors when parsing commandline flags]
unless (null errs) $ throwGhcExceptionIO $
errorsToGhcException . map (("on the commandline", ) . unLoc) $ errs
-- see sanity code in staticOpts
writeIORef v_opt_C_ready True
return (leftover, warns)
-- holds the static opts while they're being collected, before
-- being unsafely read by unpacked_static_opts below.
GLOBAL_VAR(v_opt_C, [], [String])
GLOBAL_VAR(v_opt_C_ready, False, Bool)
staticFlags :: [String]
staticFlags = unsafePerformIO $ do
ready <- readIORef v_opt_C_ready
if (not ready)
then panic "Static flags have not been initialised!\n Please call GHC.parseStaticFlags early enough."
else readIORef v_opt_C
-- All the static flags should appear in this list. It describes how each
-- static flag should be processed. Two main purposes:
-- (a) if a command-line flag doesn't appear in the list, GHC can complain
-- (b) a command-line flag may remove, or add, other flags; e.g. the "-fno-X"
-- things
--
-- The common (PassFlag addOpt) action puts the static flag into the bunch of
-- things that are searched up by the top-level definitions like
-- opt_foo = lookUp (fsLit "-dfoo")
-- Note that ordering is important in the following list: any flag which
-- is a prefix flag (i.e. HasArg, Prefix, OptPrefix, AnySuffix) will override
-- flags further down the list with the same prefix.
-- see Note [Updating flag description in the User's Guide] in DynFlags
flagsStatic :: [Flag IO]
flagsStatic = [
------ Debugging ----------------------------------------------------
defFlag "dppr-debug" (PassFlag addOptEwM)
, defFlag "dno-debug-output" (PassFlag addOptEwM)
-- rest of the debugging flags are dynamic
------ Compiler flags -----------------------------------------------
-- All other "-fno-<blah>" options cancel out "-f<blah>" on the hsc cmdline
, defFlag "fno-"
(PrefixPred (\s -> isStaticFlag ("f"++s)) (\s -> removeOptEwM ("-f"++s)))
-- Pass all remaining "-f<blah>" options to hsc
, defFlag "f" (AnySuffixPred isStaticFlag addOptEwM)
]
isStaticFlag :: String -> Bool
isStaticFlag f = f `elem` flagsStaticNames
-- see Note [Updating flag description in the User's Guide] in DynFlags
flagsStaticNames :: [String]
flagsStaticNames = [
"fno-state-hack",
"fno-opt-coercion"
]
-- We specifically need to discard static flags for clients of the
-- GHC API, since they can't be safely reparsed or reinitialized. In general,
-- the existing flags do nothing other than control debugging and some low-level
-- optimizer phases, so for the most part this is OK.
--
-- See GHC issue #8276: http://ghc.haskell.org/trac/ghc/ticket/8276#comment:37
discardStaticFlags :: [String] -> [String]
discardStaticFlags = filter (\x -> x `notElem` flags)
where flags = [ "-fno-state-hack"
, "-fno-opt-coercion"
, "-dppr-debug"
, "-dno-debug-output"
]
initStaticOpts :: IO ()
initStaticOpts = writeIORef v_opt_C_ready True
addOpt :: String -> IO ()
addOpt = consIORef v_opt_C
removeOpt :: String -> IO ()
removeOpt f = do
fs <- readIORef v_opt_C
writeIORef v_opt_C $! filter (/= f) fs
type StaticP = EwM IO
addOptEwM :: String -> StaticP ()
addOptEwM = liftEwM . addOpt
removeOptEwM :: String -> StaticP ()
removeOptEwM = liftEwM . removeOpt
packed_static_opts :: [FastString]
packed_static_opts = map mkFastString staticFlags
lookUp :: FastString -> Bool
lookUp sw = sw `elem` packed_static_opts
-- debugging options
-- see Note [Updating flag description in the User's Guide] in DynFlags
opt_PprStyle_Debug :: Bool
opt_PprStyle_Debug = lookUp (fsLit "-dppr-debug")
opt_NoDebugOutput :: Bool
opt_NoDebugOutput = lookUp (fsLit "-dno-debug-output")
opt_NoStateHack :: Bool
opt_NoStateHack = lookUp (fsLit "-fno-state-hack")
opt_NoOptCoercion :: Bool
opt_NoOptCoercion = lookUp (fsLit "-fno-opt-coercion")
{-
-- (lookup_str "foo") looks for the flag -foo=X or -fooX,
-- and returns the string X
lookup_str :: String -> Maybe String
lookup_str sw
= case firstJusts (map (stripPrefix sw) staticFlags) of
Just ('=' : str) -> Just str
Just str -> Just str
Nothing -> Nothing
lookup_def_int :: String -> Int -> Int
lookup_def_int sw def = case (lookup_str sw) of
Nothing -> def -- Use default
Just xx -> try_read sw xx
lookup_def_float :: String -> Float -> Float
lookup_def_float sw def = case (lookup_str sw) of
Nothing -> def -- Use default
Just xx -> try_read sw xx
try_read :: Read a => String -> String -> a
-- (try_read sw str) tries to read s; if it fails, it
-- bleats about flag sw
try_read sw str
= case reads str of
((x,_):_) -> x -- Be forgiving: ignore trailing goop, and alternative parses
[] -> throwGhcException (UsageError ("Malformed argument " ++ str ++ " for flag " ++ sw))
-- ToDo: hack alert. We should really parse the arguments
-- and announce errors in a more civilised way.
-}
|
acowley/ghc
|
compiler/main/StaticFlags.hs
|
Haskell
|
bsd-3-clause
| 7,834
|
module Utilities (toBinary, fl) where
import Stream
import Data.Ratio
-- Convert from an Integer to its signed-digit representation
toBinary :: Integer -> Stream
toBinary 0 = [0]
toBinary x = toBinary t ++ [x `mod` 2]
where t = x `div` 2
fl :: Stream -> Stream
fl (x:xs) = (f x):xs
where f 0 = 1
f 1 = 0
|
ryantm/ghc
|
testsuite/tests/concurrent/prog001/Utilities.hs
|
Haskell
|
bsd-3-clause
| 328
|
{-# LANGUAGE OverloadedStrings #-}
{-|
Module : Examples.AllPrimitives
Description : Predefined network: allPrimitives.
Copyright : (c) Sanne Woude 2015
Predefined network: allPrimitives.
-}
module Examples.AllPrimitives (allPrimitives) where
import Madl.Network
import Examples.TypesAndFunctions
import Utils.Text
-- | The allPrimitives network, with or without a deadlock.
allPrimitives :: Bool -> MadlNetwork
allPrimitives dl = mkNetwork (NSpec components channels ports) where
src0 = Source "src0" (if dl then reqAndRsp else rsp)
src1 = Source "src1" req
fork = Fork "fork"
merge0 = Merge "merge0"
queue0 = Queue "queue0" 2
queue1 = Queue "queue1" 2
switch = Switch "switch" [isRsp, isReq]
join = ControlJoin "join"
merge1 = Merge "merge1"
sink = Sink "sink"
src0_fork = "src0_fork"
fork_queue0 = "fork_queue0"
fork_merge0 = "fork_merge0"
src1_merge0 = "src1_merge0"
merge0_queue1 = "merge0_queue1"
queue0_join = "queue0_join"
queue1_switch = "queue1_switch"
switch_join = "switch_join"
join_merge1 = "join_merge1"
switch_merge1 = "switch_merge1"
merge1_sink = "merge1_sink"
src0_o = ("src0" , "src0_fork")
src1_o = ("src1" , "src1_merge0")
fork_i = ("src0_fork" , "fork")
fork_a = ("fork" , "fork_queue0")
fork_b = ("fork" , "fork_merge0")
merge0_a = ("fork_merge0" , "merge0")
merge0_b = ("src1_merge0" , "merge0")
merge0_o = ("merge0" , "merge0_queue1")
queue0_i = ("fork_queue0" , "queue0")
queue0_o = ("queue0" , "queue0_join")
queue1_i = ("merge0_queue1" , "queue1")
queue1_o = ("queue1" , "queue1_switch")
switch_i = ("queue1_switch" , "switch")
switch_a = ("switch" , "switch_join")
switch_b = ("switch" , "switch_merge1")
join_a = ("queue0_join" , "join")
join_b = ("switch_join" , "join")
join_o = ("join" , "join_merge1")
merge1_a = ("join_merge1" , "merge1")
merge1_b = ("switch_merge1" , "merge1")
merge1_o = ("merge1" , "merge1_sink")
sink_i = ("merge1_sink" , "sink")
components =
map C [src0, src1, fork, merge0, queue0, queue1, switch, join, merge1, sink]
channels =
map Channel [src0_fork, fork_queue0, fork_merge0, src1_merge0, merge0_queue1, queue0_join, queue1_switch, switch_join, join_merge1, switch_merge1, merge1_sink]
ports :: [(Text, Text)]
ports = [src0_o, src1_o, fork_i, fork_a, fork_b, merge0_a, merge0_b, merge0_o, queue0_i, queue0_o, queue1_i, queue1_o, switch_i, switch_a, switch_b, join_a, join_b, join_o, merge1_a, merge1_b, merge1_o, sink_i]
|
julienschmaltz/madl
|
examples/Examples/AllPrimitives.hs
|
Haskell
|
mit
| 2,842
|
-- Peano numbers
-- https://www.codewars.com/kata/5779b0f0ec883247b2000117
module Haskell.Codewars.Peano where
import Prelude hiding (even, odd, div, compare, Num, Int, Integer, Float, Double, Rational, Word)
data Peano = Zero | Succ Peano deriving (Eq, Show)
add, sub, mul, div :: Peano -> Peano -> Peano
add p1 Zero = p1
add Zero p2 = p2
add p1 (Succ p2) = add (Succ p1) p2
sub p1 Zero = p1
sub Zero _ = error "negative number"
sub (Succ p1) (Succ p2) = sub p1 p2
mul Zero _ = Zero
mul _ Zero = Zero
mul p1 (Succ Zero) = p1
mul (Succ Zero) p2 = p2
mul p1 (Succ p2) = add p1 (mul p1 p2)
div _ Zero = error "divide by 0"
div p1 (Succ Zero) = p1
div Zero _ = Zero
div p1 p2 | compare p1 p2 == LT = Zero
| otherwise = Succ (div (sub p1 p2) p2)
even, odd :: Peano -> Bool
even Zero = True
even (Succ p1) = not . even $ p1
odd = not . even
compare :: Peano -> Peano -> Ordering
compare Zero Zero = EQ
compare Zero (Succ _) = LT
compare (Succ _) Zero = GT
compare (Succ p1) (Succ p2) = compare p1 p2
|
gafiatulin/codewars
|
src/5 kyu/Peano.hs
|
Haskell
|
mit
| 1,014
|
module Language.Rebeca.Fold.Erlang.Simulation where
import Control.Monad.Reader
import Control.Monad.State
import Language.Fold
import Language.Erlang.Builder
import Language.Erlang.Syntax
import qualified Language.Rebeca.Absrebeca as R
import Language.Rebeca.Algebra
import Language.Rebeca.Fold
import Language.Rebeca.Fold.Erlang.Refinement
simulationAlgebra = refinementAlgebra {
modelF = \envs rcs mai -> do
envs' <- sequence envs
setEnvVars envs'
rcs' <- sequence rcs
mai' <- mai
moduleName <- getModuleName
rtfactor <- getRtFactor
monitor <- getMonitor
let opts = [ ("monitor", tupleE [atomE "monitor", listE []])
, ("program", tupleE [atomE moduleName, atomE "main", listE [varE "Args"]])
, ("time_limit", numberE 1200)
, ("algorithm", tupleE [atomE "mce_alg_simulation", atomE "void"])
]
let sim = Function "simulate" [varP "Args"] (Apply (moduleE "mce" "start") [RecordCreate "mce_opts" (if monitor then opts else (drop 1 opts))])
return (Program (Module moduleName)
[Export ["main/1", "simulate/1"]]
[ Import "$MCERLANG_HOME/languages/erlang/src/include/state.hrl"
, Import "$MCERLANG_HOME/languages/erlang/src/include/process.hrl"
, Import "$MCERLANG_HOME/languages/erlang/src/include/node.hrl"
, Import "$MCERLANG_HOME/src/include/mce_opts.hrl" ]
[Define "RT_FACTOR" (num rtfactor)]
(concat rcs' ++ [mai', sim]))
, reactiveClassF = \id _ kr sv msi ms -> do
setKnownRebecs []
setStateVars []
id' <- id
kr' <- kr
setKnownRebecs kr'
sv' <- sv
setStateVars (map (\(_, id, _) -> id) sv')
msi' <- msi
ms' <- sequence ms
let initialsv = Assign (varP "StateVars") (Apply (moduleE "dict" "from_list") [listE (map (\(_, i, d) -> tupleE [atomE i, either atomE (\x -> x) d]) sv')])
initiallv = Assign (varP "LocalVars") (Apply (moduleE "dict" "new") [])
probeState = Apply (moduleE "mce_erl" "probe_state") [varE "InstanceName", varE "NewStateVars"]
recurs = Apply (atomE id') [varE "Env", varE "InstanceName", varE "KnownRebecs", varE "NewStateVars"]
return ([ Function id' [varP "Env", varP "InstanceName"] $
Receive [ Match (tupleP (map varP kr')) Nothing $
Apply (atomE id') [ varE "Env", varE "InstanceName"
, Apply (moduleE "dict" "from_list") [listE (map (\k -> tupleE [atomE k, varE k]) kr')]
]]
, Function id' [varP "Env", varP "InstanceName", varP "KnownRebecs"] $
Seq (Seq initialsv (Seq initiallv (Assign (tupleP [varP "NewStateVars", varP "_"]) (Receive [msi'])))) (Seq probeState recurs)
, Function id' [varP "Env", varP "InstanceName", varP "KnownRebecs", varP "StateVars"] $
Seq (Seq initiallv (Assign (tupleP [varP "NewStateVars", varP "_"]) (Receive ms'))) (Seq probeState recurs)
])
, msgSrvF = \id tps stms -> do
setLocalVars []
id' <- id
tps' <- sequence tps
stms' <- sequence stms
let patterns = tupleP [tupleP [varP "Sender", varP "TT", varP "DL"], atomP id', tupleP (map (varP . snd) tps')]
pred = InfixExp OpLOr (InfixExp OpEq (varE "DL") (atomE "inf")) (InfixExp OpLEq (Apply (moduleE "rebeca" "now") []) (varE "DL"))
probe = Apply (moduleE "mce_erl" "probe") [atomE "drop", atomE id']
return (Match patterns Nothing (Case pred [ Match (atomP "true") Nothing (formatReceive id' $ apply $ reverse stms')
, Match (atomP "false") Nothing (Seq probe (formatDrop id' retstm))]))
}
runSimulate :: R.Model -> ReaderT CompilerConf (State CompilerState) Program
runSimulate model = fold simulationAlgebra model
translateSimulation :: String -> Integer -> Bool -> R.Model -> Program
translateSimulation modelName rtfactor monitor model = evalState (runReaderT (runSimulate model) (initialConf {moduleName = modelName, rtfactor = rtfactor, monitor = monitor })) initialState
|
arnihermann/timedreb2erl
|
src/Language/Rebeca/Fold/Erlang/Simulation.hs
|
Haskell
|
mit
| 4,296
|
-- | Options/Parsing
module Vaultaire.Collector.Nagios.Perfdata.Options where
import Vaultaire.Collector.Nagios.Perfdata.Types
import Options.Applicative
parseOptions :: IO NagiosOptions
parseOptions = execParser optionParser
-- | Parser which include all help info
optionParser :: ParserInfo NagiosOptions
optionParser =
info (helper <*> collectorOptions)
(fullDesc <>
progDesc "Vaultaire collector for Nagios perfdata files, can run with mod_gearman" <>
header "vaultaire-collector-nagios - writes datapoints from Nagios perfdata files to Vaultaire. Can run in daemon mode using the gearman protocol"
)
-- | The parser for all options for nagios-perfdata
collectorOptions :: Parser NagiosOptions
collectorOptions = NagiosOptions
<$> switch
(long "normalise-metrics"
<> short 's'
<> help "Normalise metrics to base SI units")
<*> switch
(long "gearman"
<> short 'g'
<> help "Run in gearman mode")
<*> strOption
(long "gearman-host"
<> short 'h'
<> value "localhost"
<> metavar "GEARMANHOST"
<> help "Hostname of Gearman server.")
<*> strOption
(long "gearman-port"
<> short 'p'
<> value "4730"
<> metavar "GEARMANPORT"
<> help "Port number Gearman server is listening on.")
<*> strOption
(long "function-name"
<> short 'f'
<> value "check_results"
<> metavar "FUNCTION-NAME"
<> help "Name of function to register with Gearman server.")
<*> strOption
(long "key-file"
<> short 'k'
<> value ""
<> metavar "KEY-FILE"
<> help "File from which to read AES key to decrypt check results. If unspecified, results are assumed to be in cleartext.")
<*> switch
(long "telemetry"
<> short 't'
<> help "Run telemetry")
<*> strOption
(long "telemetry-host"
<> value "127.0.0.1"
<> metavar "TELEMETRYHOST"
<> help "Host to send telemetry data to")
<*> strOption
(long "telemetry-port"
<> value "9447"
<> metavar "TELEMETRYPORT"
<> help "Port to use for telemetry.")
|
anchor/vaultaire-collector-nagios
|
lib/Vaultaire/Collector/Nagios/Perfdata/Options.hs
|
Haskell
|
mit
| 2,266
|
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.WebKitCSSViewportRule
(js_getStyle, getStyle, WebKitCSSViewportRule,
castToWebKitCSSViewportRule, gTypeWebKitCSSViewportRule)
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 WebKitCSSViewportRule -> IO (JSRef CSSStyleDeclaration)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitCSSViewportRule.style Mozilla WebKitCSSViewportRule.style documentation>
getStyle ::
(MonadIO m) =>
WebKitCSSViewportRule -> m (Maybe CSSStyleDeclaration)
getStyle self
= liftIO
((js_getStyle (unWebKitCSSViewportRule self)) >>= fromJSRef)
|
plow-technologies/ghcjs-dom
|
src/GHCJS/DOM/JSFFI/Generated/WebKitCSSViewportRule.hs
|
Haskell
|
mit
| 1,467
|
{-# htermination transpose :: [[a]] -> [[a]] #-}
import List
|
ComputationWithBoundedResources/ara-inference
|
doc/tpdb_trs/Haskell/full_haskell/List_transpose_1.hs
|
Haskell
|
mit
| 61
|
{-# LANGUAGE LambdaCase #-}
module Language.Bison.Summary.Parser
( parseRules
) where
import Language.Bison.Summary.Parser.Lexer
import Language.Bison.Summary.Syntax
import Text.Parsec
import Text.Parsec.Prim
import Text.Parsec.Pos
import Text.Parsec.Error
import Control.Applicative hiding ((<|>), optional)
import Control.Monad
import qualified Data.Map as Map
type Parser = Parsec [Loc Token] ()
parseRules :: SourceName -> String -> Either ParseError [Rule]
parseRules src stream = postproc <$> parseAs rules src stream
postproc :: [Rule] -> [Rule]
postproc rules = [ Rule name rhss'
| (name, rhss) <- Map.toList rulesMap
, let rhss' = map (map resolve) rhss
]
where
rulesMap = Map.unionsWith (++)
[ Map.singleton name rhss
| Rule name rhss <- rules
]
isTerminal s = RuleName s `Map.notMember` rulesMap
resolve (Nonterminal (RuleName name)) | isTerminal name = Terminal name
resolve element = element
parseAs :: Parser a -> SourceName -> String -> Either ParseError a
parseAs p src stream = case scanner stream of
Left err -> Left $ newErrorMessage
(Message $ unwords ["lexer failed:", err])
(newPos src 0 0)
Right tokens -> runParser p () src tokens
rules :: Parser [Rule]
rules = skipMany eor >> rule `endBy` many1 eor
rule :: Parser Rule
rule = Rule <$> name <* colon <*> (alt `sepBy` bar) <?> "grammar rule"
alt :: Parser [Element]
alt = (directive "empty" *> pure []) <|>
(many1 element) <?>
"grammar alternative"
element :: Parser Element
element = (Nonterminal <$> name) <|>
(Lit <$> charLit) <?>
"grammar element"
name :: Parser Name
name = tok $ \case
Id s -> return $ RuleName s
Meta s -> return $ MetaName s
_ -> Nothing
charLit :: Parser Char
charLit = tok $ \case
CharLit c -> return c
_ -> Nothing
colon :: Parser ()
colon = tok $ \case
Colon -> return ()
_ -> Nothing
bar :: Parser ()
bar = tok $ \case
Bar -> return ()
_ -> Nothing
eor :: Parser ()
eor = tok $ \case
EOR -> return ()
_ -> Nothing
directive :: String -> Parser ()
directive s = tok $ \case
Directive s' -> guard (s == s')
_ -> Nothing
tok :: (Show t) => (t -> Maybe a) -> Parsec [Loc t] s a
tok f = do
src <- sourceName <$> getPosition
let fromLoc (SrcLoc line col) = newPos src line col
token (show . unLoc) (fromLoc . getLoc) (f . unLoc)
|
gergoerdi/bison-parser
|
src/Language/Bison/Summary/Parser.hs
|
Haskell
|
mit
| 2,509
|
import Text.ParserCombinators.Parsec
import qualified Data.Map as M
import Text.Parsec.Error (messageString, errorMessages)
import Data.Text (pack, unpack, strip)
import Data.Monoid
type TextLine = String
type Name = String
data ActionType = FoulCommit
| GenericAction String
| ActionType Player
deriving (Show)
data Event = Time String
| Action String ActionType
| Unknown String
| Error [String]
deriving (Show)
data Player = Player { madeShot :: Int, missedShot :: Int, defRebound :: Int, offRebound :: Int , foulCommit :: Int, made3ptShot :: Int, missed3ptShot :: Int, steal :: Int, turnover :: Int, madeLayup :: Int, missedLayup :: Int, foulAgainst :: Int}
deriving (Show)
type Players = M.Map Name Player
defaultPlayer = Player{madeShot=0, missedShot=0, defRebound=0, offRebound=0, foulCommit=0, made3ptShot=0, missed3ptShot=0, steal=0, turnover=0, madeLayup=0, missedLayup=0, foulAgainst=0}
defensiveReboundPlayer = defaultPlayer {defRebound=1}
offensiveReboundPlayer = defaultPlayer {offRebound=1}
madeShotPlayer = defaultPlayer {madeShot=1}
missedShotPlayer = defaultPlayer {missedShot=1}
foulCommitPlayer = defaultPlayer {foulCommit=1}
foulAgainstPlayer = defaultPlayer {foulAgainst=1}
made3ptShotPlayer = defaultPlayer {made3ptShot=1}
missed3ptShotPlayer = defaultPlayer {missed3ptShot=1}
stealPlayer = defaultPlayer {steal=1}
turnoverPlayer = defaultPlayer {turnover=1}
playerAppend :: Player -> Player -> Player
playerAppend (Player a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 a11 a12) (Player b1 b2 b3 b4 b5 b6 b7 b8 b9 b10 b11 b12) = Player (a1+b1) (a2+b2) (a3+b3) (a4+b4) (a5+b5) (a6+b6) (a7+b7) (a8 + b8) (a9+b9) (a10+b10) (a11+b11) (a12+b12)
instance Monoid Player where
mempty = defaultPlayer
mappend = (playerAppend)
-- s <- readFile "/home/smu/code/fun-with-haskell/testfile.txt"
-- parse parseLines "bl" s
main = do
s <- readFile "/home/smu/code/fun-with-haskell/testfile.txt"
let res = parse parseLines "test" s
print $ (filter (knownEvent) (extractResult res))
mainGame = do
s <- readFile "/home/smu/code/fun-with-haskell/testfile.txt"
let res = parse parseLines "test" s
print $ playGame M.empty $ extractResult res
playGame :: Players -> [Event] -> Players
playGame p [] = p
playGame p g = foldl updatePlayer p g
updatePlayer :: Players -> Event -> Players
updatePlayer p (Action name (ActionType player)) = M.insertWith (mappend) name player p
updatePlayer p _ = p
knownEvent :: Event -> Bool
knownEvent (Action _ (ActionType _)) = False
knownEvent _ = True
extractResult :: Either ParseError [Event] -> [Event]
extractResult (Right x) = x
extractResult (Left y) = [Error (map (messageString) (errorMessages y))]
trimSpaces :: String -> String
trimSpaces x = unpack $ strip $ pack x
parseLines :: Parser [Event]
parseLines = many parseLine
parseLine :: Parser Event
parseLine = do
s <- try parseAction <|> try parseTime <|> parseUnknown
newline
return s
parseTime :: Parser Event
parseTime = do
s <- many (noneOf ".")
string ". min"
return $ Time s
parseAction :: Parser Event
parseAction = do
spaces
name <- many (noneOf "-")
char '-'
spaces
action <- try parseMissed3pt <|> try parseFoul <|> try parseRebound <|> try parseSteal <|> try parseTurnover <|> parseGenericAction --try parseMissed3pt <|> try parseMade3pt <|> parseGenericAction
return (Action (trimSpaces name) action)
parseFoul :: Parser ActionType
parseFoul = try parseFoulAgainst <|> parseFoulCommit
parseFoulCommit :: Parser ActionType
parseFoulCommit = do
string "foul"
s <- many (noneOf "\n")
return $ ActionType foulCommitPlayer
parseSubstitution :: Parser String
parseSubstitution = do
s <- many (oneOf "ABCDEFGHIJKLMNOPQRSTUVWXYZ -")
s1 <- many (noneOf " ")
string " replaces "
s2 <- many (noneOf "\n")
return s
parseFoulAgainst :: Parser ActionType
parseFoulAgainst = do
string "foul against"
s <- many (noneOf "\n")
return $ ActionType foulAgainstPlayer
parseSteal :: Parser ActionType
parseSteal = do
string "steal"
s <- many (noneOf "\n")
return $ ActionType stealPlayer
parseTurnover :: Parser ActionType
parseTurnover = do
string "turnover"
s<- many (noneOf "\n")
return $ ActionType turnoverPlayer
parseGenericAction :: Parser ActionType
parseGenericAction = do
s <- many (noneOf "\n")
return $ GenericAction s
parseRebound :: Parser ActionType
parseRebound = do
s <- try parseDefRebound <|> try parseOffRebound
return s
parseDefRebound :: Parser ActionType
parseDefRebound = do
string "defensive rebound"
s <- many (noneOf "\n")
return $ ActionType defensiveReboundPlayer
parseOffRebound :: Parser ActionType
parseOffRebound = do
string "offensive rebound"
s <- many (noneOf "\n")
return $ ActionType offensiveReboundPlayer
parseMissed3pt :: Parser ActionType
parseMissed3pt = do
string "missed 3-pointer"
s <- many (noneOf "\n")
return $ ActionType missed3ptShotPlayer
parseMade3pt :: Parser ActionType
parseMade3pt = do
string "made 3-pointer"
return $ ActionType made3ptShotPlayer
parseUnknown :: Parser Event
parseUnknown = do
s <- many (noneOf "\n")
return $ Unknown s
|
ddccffvv/fun-with-haskell
|
belgie_parser.hs
|
Haskell
|
mit
| 5,711
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.