code
stringlengths 5
1.03M
| repo_name
stringlengths 5
90
| path
stringlengths 4
158
| license
stringclasses 15
values | size
int64 5
1.03M
| n_ast_errors
int64 0
53.9k
| ast_max_depth
int64 2
4.17k
| n_whitespaces
int64 0
365k
| n_ast_nodes
int64 3
317k
| n_ast_terminals
int64 1
171k
| n_ast_nonterminals
int64 1
146k
| loc
int64 -1
37.3k
| cycloplexity
int64 -1
1.31k
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|
module Purecoin.Network.TestNet
( magic, port, difficulty
, Chain, startBlockChain
) where
import Data.Word (Word8)
import Purecoin.Core.DataTypes (Difficulty, fromTarget)
import Purecoin.Core.BlockChain (BlockChain, newChain)
magic :: [Word8]
magic = [0xFA, 0xBF, 0xB5, 0xDA]
port :: Num a => a
port = 18333
difficulty :: Difficulty
difficulty = fromTarget (0x7fff8 * 2^208)
newtype Chain = Chain Chain
startBlockChain :: BlockChain Chain
Just startBlockChain = newChain 1 (read $ "2011-02-02 23:16:42 UTC") difficulty 384568319
|
laanwj/Purecoin
|
Purecoin/Network/TestNet.hs
|
mit
| 557
| 0
| 8
| 97
| 169
| 99
| 70
| 15
| 1
|
module Util.Tuple where
mapSnd :: (b -> c) -> [(a,b)] -> [(a,c)]
mapSnd f [] = []
mapSnd f ((a,b):xs) = (a,f b):(mapSnd f xs)
mapFst :: (a -> c) -> [(a,b)] -> [(c,b)]
mapFst f [] = []
mapFst f ((a,b):xs) = (f a,b):(mapFst f xs)
fork :: (a -> b) -> (a -> c) -> a -> (b, c)
fork f g x = (f x, g x)
|
sgord512/Utilities
|
Util/Tuple.hs
|
mit
| 300
| 0
| 8
| 74
| 259
| 145
| 114
| 9
| 1
|
--
--
import Data.Char (isNumber,isSpace)
import Data.List (partition)
import Control.Monad (liftM,liftM2)
--- maybe2: returns Just if both maybes are a Just or nothing otherwise
maybe2 :: Maybe a -> Maybe b -> Maybe (a,b)
maybe2 = liftM2 (,)
--- expressions
data Expr = Var | Value Int | Cval Int Expr |
Add Expr Expr | Sub Expr Expr |
Div Expr Expr -- deriving Show
--- displaying equations
display :: Expr -> String
display Var = "x"
display (Value n) = show n
display (Cval n e) = show n ++ display e
display (Add l r) = display l ++ "+" ++ display r
display (Sub l r) = display l ++ "-" ++ display r
display (Div x y) = display x ++ "/" ++ display y
instance Show Expr where
show = display
--interpreting equations
eval :: Expr -> Double -> Double
eval Var n = n
eval (Value n) _ = fromIntegral n
eval (Cval n e) m = fromIntegral n * eval e m
eval (Add l r) m = eval l m + eval r m
eval (Sub l r) m = eval l m - eval r m
eval (Div l r) m = eval l m / eval r m
-- equality of linear equations
eEqual :: Expr -> Expr -> Bool
eEqual e1 e2 = eval e1 0 == eval e2 0 && eval e1 1 == eval e2 1
instance Eq Expr where
(==) = (eEqual)
-- is the expression a variable
isVar :: Expr -> Bool
isVar Var = True
isVar (Cval _ Var) = True
isVar x = False
isNeg :: Expr -> Bool
isNeg (Value n) = n < 0
isNeg (Cval n _ ) = n < 0
isNeg _ = False
-- if the expression has a value
isVal :: Expr -> Bool
isVal (Value _) = True
isVal _ = False
canComp :: Expr -> Expr -> Bool
canComp l r = (isVar l && isVar r) || (isVal l && isVal r)
--
isVSubs, isLSubs :: Expr -> Bool
isVSubs (Sub a b)
| canComp a b = True
| isVar a = isVSubs b
| otherwise = False
isVSubs _ = False
isLSubs (Sub a b)
| canComp a b = True
| isVal a = isLSubs b
| otherwise = False
isLSubs _ = False
--- rewrites (Sub a (Sub b (Sub c) d) k) -> Sub (Sub a b) (Sub (Sub c d) k)
--- if a b c and d are the same type
trnSubs :: Expr -> Expr
trnSubs s@(Sub a b)
| canComp a b = s
| otherwise = case b of
Sub p q -> if canComp a p
then (Sub (Sub a p) (trnSubs q))
else case p of
Add r s -> if canComp a r
then Sub (Sub a r) (Add s (trnAdd q))
else (Sub a (trnAdd b))
_ -> (Sub a (trnSubs b))
_ -> Sub a (trnSubs b)
trnSubs xs = xs
--- rewrites (Add a (Add b (Add c) d) k) -> Add (Add a b) (Add (Add c d) k)
--- if a b c and d are the same type
trnAdd :: Expr -> Expr
trnAdd s@(Add a b)
| canComp a b = s
| otherwise = case b of
Add p q -> if canComp a p
then (Add (Add a p) (trnAdd q))
else
case p of
Sub r s -> if canComp a r
then Add (Add a r) (Sub s (trnAdd q))
else (Add a (trnAdd b))
_ -> (Add a (trnAdd b))
_ -> Add a (trnAdd b)
trnAdd xs = xs
nComp :: Expr -> Bool
nComp l = not (isVar l || isVal l)
-- sytactic equality for comaparing operations
sEqual :: Expr -> Expr -> Bool
sEqual Var Var = True
sEqual (Value n) (Value m) = m == n
sEqual (Cval n l) (Cval m r) = n == m && sEqual l r
sEqual (Add l r) (Add ll rr) = sEqual l ll && sEqual r rr
sEqual (Sub l r) (Sub ll rr) = sEqual l ll && sEqual r rr
sEqual (Div a b) (Div c d) = sEqual a c && sEqual c b
sEqual _ _ = False
-------------------------------------------------------------------------
--- Some Arithmetic operations
-------------------------------------------------------------------------
-- grouping
group :: Expr -> Expr
group (Add l (Add ll r))
| isVar r && isVar ll = Add (add $ Add r ll) (group l)
| isVar r = Add r (group $ Add l ll)
| isVar ll = Add ll (group $ Add l r)
| isVal l && isVal ll = Add (group r) $ Add l ll
| isVal l = Add (group $ Add ll r) l
| isVal ll = Add (group $ Add l r) ll
| otherwise = Add (group l) (group $ Add ll r)
group (Add (Add l ll) r) = group $ Add l (group $ Add ll r)
--
group (Sub l (Sub q Var)) = (Add (Cval (-1) Var) (group $ Sub l q))
group (Sub l (Sub q (Cval n r))) = (Add (Cval (-n) r) (group $ Sub l q))
group (Sub l (Sub Var q)) = (Add (Cval (-1) Var) (group $ Sub l q))
group (Sub l (Sub (Cval n r) q)) = (Add (Cval (-n) r) (group $ Sub l q))
group (Sub l (Sub q r))
| canComp l q && (not $ canComp r q ) = Sub (Sub l q) $ group r
| canComp l r && (not $ canComp r q ) =
Sub l (Sub r q)
| otherwise = Sub l (group $ Sub q r)
--
group (Sub (Sub l q) r)
| canComp l q && canComp r q = Sub l (Sub l q)
--
group (Add (Sub l ll) (Sub a b))
| canComp l ll = group $ Add (sub $ Sub l ll) (Sub a b)
| canComp a b = group $ Add (Sub l ll) (sub $ Sub a b)
| isVar l && isVar b = Add (Sub l b) (Sub a ll)
| isVar l && isVar a = Sub (Add l a) (Sub ll b)
| isVar ll && isVar a = Add (Sub a ll) (Sub l b)
| isVar ll && isVar b = group $ Sub (Add l a) (add $ Add ll b)
--
| isVal l && isVal b = Add (Sub a ll) (Sub l b)
| isVal l && isVal a = group $ Sub (add $ Add l a) (Sub ll b)
| isVal ll && isVal a = group $ Add (sub $ Sub a ll) (Sub l b)
| isVal ll && isVal b = group $ Sub (Add l a) (add $ Add ll b)
| otherwise = Sub (group $ Add l a) (group $ Add ll b)
--}
group (Add l (Sub ll r))
| canComp l ll = Sub (Add l ll) $ group r
| canComp l r = Add (Sub l r) $ group ll
| isVal l = Add (group $ Sub ll r) l
| isVar l = Add l (group $ Sub ll r)
| otherwise = Add (group l) (group $ Sub ll r)
--}
group (Add (Sub l ll) r)
| canComp l r = Sub (Add l r) ll
| otherwise = Add (Sub l ll) $ group r
--
group (Sub l (Add ll r))
| canComp l r = Add (Sub l r) $ group ll
| otherwise = Sub (group l) $ group (Add ll r)
group (Sub l r) = Sub (group l) (group r)
--
group (Add l (Value n))
| (isVal l || isVar l) && n < 0 = Sub l (Value (-n))
| otherwise = Add (group l) (Value n)
group (Add l (Cval n r))
| (isVal l || isVar l) && n < 0 = Sub l (Cval (-n) r)
| otherwise = Add l (Cval n r)
group (Add l r) = Add (group l) (group r)
group xs = xs
-- adding
add :: Expr -> Expr
add (Add Var Var) = Cval 2 Var
add (Add (Value n) (Value m)) = Value (n+m)
add (Add (Cval n Var) (Cval m Var)) = Cval (n+m) Var
add (Add (Add (Sub l r) k) q) = add $ Add (Sub l r) (add $ Add k q)
add (Add Var (Cval n Var))
| n == 0 = Var
| otherwise = Cval (n+1) Var
add (Add (Cval n Var) Var)
| n == 0 = Var
| otherwise = Cval (n+1) Var
--
add (Add l (Cval n k))
| n == 0 = l
| otherwise = Add (Cval n k) (add l)
add (Add (Cval n k) l)
| n == 0 = l
| otherwise = Add (Cval n Var) (add l)
---
add (Add (Add l r) k) = Add (add $ Add l r) (add k)
-- add sub
add (Sub (Add l ll) r) = Sub (add $ Add l ll) (add r)
add (Add (Sub l r) k)
| canComp l r = Add (sub $ Sub l r) $ add k
| canComp k r = Add (add l) (sub $ Sub k r)
| canComp l k = Sub (add $ Add l k) (add r)
| otherwise = Add (Sub (add l) (add r)) (add k)
add (Add l (Sub k r))
| canComp l k = Sub (add (Add l k)) $ add r
| canComp l r = Sub (add $ Add l (add k)) $ r
| otherwise = Add (add l) (add $ Sub (add k) $ add r)
--
add (Sub l (Add ll r)) = Sub (add l) (add $ Add (add ll) $ add r)
add (Add l (Add r k))
| canComp l r = Add (add $ Add l r) (add k)
| canComp l k = Add (add r) (add $ Add l k)
| otherwise = Add (add l) (add $ Add (add r) (add k))
--}
add (Sub l r) = Sub (add l) (add r)
add (Add l r) = Add (add l) (add r)
add xs = xs
--subtracting
sub :: Expr -> Expr
sub (Sub Var Var) = Value 0
sub (Sub (Value n) (Value m)) = Value (n-m)
sub (Sub (Cval n Var) (Cval m Var)) = Cval (n-m) Var
sub (Sub Var (Cval n Var))
| n == 1 = Value 0
| otherwise = Cval (1 - n) Var
sub (Sub (Cval n Var) Var)
| n == 1 = Value 0
| otherwise = Cval (n-1) Var
sub (Sub l (q@(Sub r k)))
| isVSubs q || isLSubs q = sub $ Sub l (add $ sub2add q)
| canComp l k && (not $ canComp r k) = sub $ Sub (sub $ Sub l k) r
| canComp r k = sub $ Sub l (add $ Add r k)
| otherwise = sub $ Sub l (sub $ Sub r k)
sub (Sub q@(Sub l r) k)
| isVSubs q || isLSubs q = sub $ Sub (add $ sub2add q) (sub k)
| otherwise = sub $ Sub (sub $ Sub l r) $ sub k
-- |
sub (Sub l (Add k r))
| canComp l k = Add (sub $ Sub l k) r
| canComp k r && (not $ isVar l) = Sub (sub l) (add $ Add r k)
| canComp k r && (not $ isVal l) = Sub (sub l) (add $ Add r k)
| otherwise = Sub (sub l) (sub $ Add k r)
--
sub (Add l (Sub r k)) = Add (sub l) (sub $ Sub r k)
sub (Add (Sub l r) k) = Add (sub $ Sub l r) (sub k)
sub (Sub (Add l r) k) -- = Add l (sub $ Sub r k)
| canComp l k && (not $ isVar r) = Add (sub $ Sub l k) r
| canComp l k && (not $ isVal r) = Add (sub $ Sub l k) r
| canComp r k && (not $ isVar l) = Add l (sub $ Sub r k)
| canComp r k && (not $ isVal l) = Add l (sub $ Sub r k)
| otherwise = Sub (sub $ Add l r) (sub k)
sub (Add l r) = Add (sub l) (sub r)
sub (Sub l r) = Sub (sub l) (sub r)
--
sub xs = xs
--
--
sub2add :: Expr -> Expr
sub2add (Sub a b) = Add (sub2add a) (sub2add b)
sub2add xs = xs
--- simplify
simplify = simplify' 1 -- :: Int -> Expr -> Expr
simplify' :: Int -> Expr -> Expr
simplify' n ex
| normFrm ex = remZero ex
| n > 100 = remZero ex
| otherwise = simplify' (n + 1) $ (group . sub . trnSubs . add . trnAdd . group . remZero) ex
where
-- rewites expressions with zeros
remZero :: Expr -> Expr
remZero (Cval 0 l) = Value 0
remZero (Add l (Value 0)) = l
remZero (Add (Cval 0 _) l) = l
remZero (Add l (Cval 0 _)) = l
remZero (Add (Value 0) l) = l
remZero (Sub l (Value 0)) = l
remZero (Sub (Cval 0 _) (Value n)) = Value (-n)
remZero (Sub (Value 0) Var) = (Cval (-1) Var)
remZero (Sub (Value 0) (Cval n l)) = (Cval (-n) l)
remZero xs = xs
--
normFrm :: Expr -> Bool
normFrm Var = True
normFrm (Value _) = True
normFrm (Cval _ _) = True
normFrm (Div _ _) = True
normFrm (Add Var (Value _)) = True
normFrm (Add (Cval _ _) (Value _)) = True
normFrm (Add (Value _) Var) = True
normFrm (Add (Value _) (Cval _ _)) = True
normFrm (Sub Var (Value _)) = True
normFrm (Sub (Cval _ _) (Value _)) = True
normFrm (Sub (Value _) Var) = True
normFrm (Sub (Value _) (Cval _ _)) = True
normFrm _ = False
-------------------------------------------------------------------------
---parsing a string to equations
parseString :: String -> Maybe Expr
parseString xs
| null xs = Nothing
| xs == "x" = Just Var
| all isNumber xs = Just (Value $ read xs)
| elem '+' xs =
let (front,ys) = span (/= '+') xs in
case maybe2 (parseString front) (parseString $ dropWhile (== '+') ys) of
Nothing -> Nothing
Just (aa,bb) -> Just (Add aa bb)
| elem '-' xs =
let (front,ys) = span (/= '-') xs in
if null front then
case (parseString $ dropWhile (== '-') ys) of
Just (Value n) -> Just $ Value (-1 * n)
Just (Cval n bb) -> Just $ Cval (-1 * n) bb
_ -> Nothing
else
case maybe2 (parseString front) (parseString $ dropWhile (== '-') ys) of
Nothing -> Nothing
Just (aa,bb) -> Just (Sub aa bb)
| elem '/' xs =
let (front,ys) = span (/= '/') xs in
case maybe2 (parseString front) (parseString $ dropWhile (== '/') ys) of
Just (Value aa, Value bb) -> Just (Div (Value aa) (Value bb))
_ -> Nothing
| any (== 'x') xs =
let (front,back) = span isNumber xs in
case back of
"x" -> if null front then
Just Var
else if (all isNumber front) then
Just $ Cval (read front) Var
else Nothing
_ -> Nothing
| otherwise = Nothing
--parseString' = liftM group . parseString
-- such strings
switchY b x xs = if b then (x : xs) else "y"
plusMinus :: Bool -> String -> String
plusMinus _ "" = ""
plusMinus b ('+':'-':xs) = switchY b '-' $ plusMinus b xs
plusMinus b ('-':'+':xs) = switchY b '-' []
plusMinus b ('-':'-':xs) = switchY False '+' []
plusMinus b ('+':'+':xs) = switchY False '+' []
plusMinus b (x:xs) = x : plusMinus b xs
-- applying the parser to a string
parseResult :: (Expr -> Expr) -> String -> Either String String
parseResult f str =
case (liftM f . parseString . plusMinus False . filter (not . isSpace)) str of
Nothing -> Right "Invalid string entered. "
Just eq -> Left $ display eq
--------------------------------------------------------------------------
-- equations are pairs of expressions representing LHS and RHS
data Equation = Eqn Expr Expr
instance Show Equation where
show (Eqn a b) = show a ++" = "++ show b
-- parsing equations: parse the lhs and rhs using parsesString above.
parseEqString :: String -> Maybe Equation
parseEqString str
| not (elem '=' str) = Nothing
| otherwise =
let (lhs,rhs) = span (/= '=') $ filter (not . isSpace) str
in liftM (uncurry Eqn) $ maybe2 (parseString lhs) (parseString $ dropWhile (== '=') rhs)
--- is equation expressed as a solution
solved :: Equation -> Bool
solved (Eqn Var (Value _)) = True
solved (Eqn Var (Div (Value _) (Value _))) = True
solved _ = False
--- rules for division
divide :: Equation -> Equation
divide l@(Eqn (Cval n Var) (Value m))
| n < 0 && m < 0 = Eqn Var (Div (Value (-m)) (Value (-n)))
| n < 0 = Eqn Var (Div (Value (-m)) (Value (-n)))
| m == 0 = if n /= 0 then (Eqn Var (Value 0)) else l
| m == n = (Eqn Var (Value 1))
| n == 1 = (Eqn Var (Value m))
| otherwise = Eqn Var (Div (Value m) (Value n))
divide (Eqn (Cval n Var) (Div (Value m) (Value o))) = Eqn Var (Div (Value m) (Value $ o * m))
divide eq = eq
-- can div
canDiv :: Equation -> Bool
canDiv (Eqn (Cval n Var) (Value m)) = True
canDiv (Eqn (Cval n Var) (Div (Value m) (Value o))) = True
canDiv _ = False
-----
data Loc = WAdd | WSub | Sg deriving (Eq , Show)
-- execute a transposition
transpose :: Equation -> (Equation,(Equation,String))
transpose eq@(Eqn el er) =
case locVar True er of --
Just (Sg, l) -> ( Eqn (Sub el l) (simplify $ Sub er l) ,
(Eqn (simplify $ Sub el l) (simplify $ Sub er l), "Subtracting"))
Just (WSub, l) -> (Eqn (Add l el) (simplify $ Add l er),
(Eqn (simplify $ Add l el) (simplify $ Add l er) , "Adding"))
Just (WAdd, l) -> (Eqn (Add (negV l) el) (simplify $ Sub l er),
(Eqn (simplify $ Add el (negV l)) (simplify $ Sub l er) , "Adding"))
Nothing -> case locVar False el of
Just (Sg, l) -> (Eqn (simplify $ Sub el l) (Sub er l),
(Eqn (simplify $ Sub el l) (simplify $ Sub er l), "Subtracting"))
Just (WSub, l) -> (Eqn (simplify $ Add l el) ( Add er l),
(Eqn (simplify $ Add l el) (simplify $ Add er l),"Adding"))
Just (WAdd, l) -> (Eqn (simplify $ Sub l el) (Sub er l),
(Eqn (simplify $ Sub l el) (simplify $ Sub er l), "Subtracting"))
Nothing -> (eq, (eq,""))
where
--- locating values and variables for transposing
negV :: Expr -> Expr
negV Var = Cval (-1) Var
negV (Cval n a) = Cval (-n) a
negV xs = xs
-- locVar True for variables and locVar False for values
locVar :: Bool -> Expr -> Maybe (Loc , Expr)
locVar True Var = Just (Sg, Var)
locVar False (Value n) = Just (Sg, Value n)
locVar True (Cval n Var) = Just (Sg, Cval n Var)
locVar b (Sub l r) =
case (locVar b l) of
Nothing -> case locVar b r of
Just (sg, ys) -> Just (WSub, ys)
{-if sg == Sg then
case r of
-- Sub _ _ -> Just (WAdd, ys)
_ -> Just (WSub, ys)
else
Just (WSub, ys) --}
_ -> Nothing
Just (sg, ys) -> if sg == Sg then
case l of
Sub _ _ -> Just (WSub, ys)
_ -> Just (WAdd, ys)
else
Just (WSub, ys)
locVar b (Add l r) =
case (locVar b l) of
Nothing -> case locVar b r of
Just (sg, ys) -> if sg == Sg then
Just (WAdd, ys)
else
Just (sg, ys)
_ -> Nothing
Just (sg, ys) -> if sg == Sg then
Just (WAdd, ys)
else
Just (sg, ys)
locVar _ _ = Nothing
-------------------------------------------------------------------------------------------
---------------------- solving an equation -----------------------
-- we generate a list of steps taken to solve the equation, so we can easily trace the
-- steps by printing out the list
solveEqnl :: Equation -> [(Equation, String)]
solveEqnl eq@(Eqn Var (Div _ (Value 0))) = [(eq,"undefined")]
solveEqnl eqn
| solved eqn = []
| canDiv eqn = let deqn = divide eqn in [(deqn,"Dividing")] ++ solveEqnl deqn
| canTrans eqn = let (aeq, (teqn,str)) = transpose eqn in
[(aeq,"Transposing"),(teqn,str) ] ++ solveEqnl teqn
| otherwise = case appAddSub eqn of
(eq , Nothing) -> solveEqnl eq
(eq, Just str) -> [(eq,str)] ++ solveEqnl eq
where
--
addEq :: Equation -> Equation
addEq (Eqn a b) = Eqn (add a) (add b)
--
subEq :: Equation -> Equation
subEq (Eqn a b) = Eqn (sub a) (sub b)
--
sEnEql :: Equation -> Equation -> Bool
sEnEql (Eqn el er) (Eqn ea eb) = sEqual el ea && sEqual er eb
--
canTrans :: Equation -> Bool
canTrans (Eqn el er) = isDVal el || isDVar er
where
isDVal , isDVar :: Expr -> Bool
isDVal (Sub l r) = isDVal l || isDVal r
isDVal (Add l r) = isDVal l || isDVal r
isDVal ex = isVal ex
--
isDVar (Sub l r) = isDVar l || isDVar r
isDVar (Add l r) = isDVar l || isDVar r
isDVar ex = isVar ex
---
appAddSub :: Equation -> (Equation, Maybe String)
appAddSub eqn =
let aeqn = addEq eqn
seqn = subEq eqn
in
if sEnEql eqn aeqn then
if sEnEql eqn seqn then
(eqn , Nothing)
else (seqn , Just "Subtracting")
else
(aeqn, Just "Adding")
--- solving equation from an input string
runSolvr :: String -> IO ()
runSolvr str = do
let ms = liftM solveEqnl $ parseEqString str
case ms of
-- we use take 15 here for debugging reasons, in case we end up with an infininte loop
Just xs -> mapM_ (\(a,b) ->putStrLn (show a ++ " " ++ b)) $ take 15 xs
Nothing -> print "error in input"
main :: IO ()
main = do
putStr "\ESC[2J"
putStr "\ESC[0;0H"
putStrLn " SIMPLE EQUATION SOLVER (solves equations like: ax + b = cx + d)"
let str1 = "\nEnter the equation to solve : "
let str2 = "-----------------------------------------------------------------"
putStrLn (str2 ++ str1)
getLine >>= runSolvr
--- try again
print "Press enter to try again"
c <- getChar
if c == '\n' then main else return ()
|
rawlep/EQS
|
esit2.hs
|
mit
| 25,990
| 0
| 18
| 12,857
| 9,856
| 4,848
| 5,008
| 420
| 22
|
{-# LANGUAGE QuasiQuotes #-}
module View.Memberships where
import Model
import View.Helpers
import View.Layout
membershipsShowView :: Entity Person -> Entity Membership -> Html
membershipsShowView (Entity personId person) (Entity id m) = layout [shamlet|
^{membershipHeader person}
<div>
$if membershipActive m
Active
$else
Inactive
\ -
<a href="/people/#{personId}/membership/#{id}/edit">
Edit
<div>
<a href="/memberships/#{id}/payments">
Manage Payments
|]
membershipsNewView :: Entity Person -> View Text -> Html
membershipsNewView (Entity personId person) view = layout [shamlet|
^{membershipHeader person}
<form action="/people/#{personId}/membership" method="POST">
^{membershipFields view}
<input type="submit" value="save">
|]
membershipsEditView :: Entity Person -> Entity Membership -> View Text -> Html
membershipsEditView (Entity personId person) (Entity id _) view = layout [shamlet|
^{membershipHeader person}
<form action="/people/#{personId}/membership/#{id}" method="POST">
^{membershipFields view}
<input type="submit" value="save">
|]
membershipHeader :: Person -> Html
membershipHeader person = [shamlet|
<h1>
Membership for
#{personFirstName person}
#{personLastName person}
|]
membershipFields :: View Text -> Html
membershipFields view = [shamlet|
^{checkboxField "active" "Active" view}
|]
|
flipstone/glados
|
src/View/Memberships.hs
|
mit
| 1,430
| 0
| 8
| 262
| 222
| 121
| 101
| 15
| 1
|
module Sllar.Heredoc where
import Language.Haskell.TH
import Language.Haskell.TH.Quote
heredoc :: QuasiQuoter
heredoc = QuasiQuoter stringE undefined undefined undefined
|
grsmv/sllar
|
src/Sllar/Heredoc.hs
|
mit
| 172
| 0
| 5
| 19
| 38
| 23
| 15
| 5
| 1
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticbeanstalk-application-maxcountrule.html
module Stratosphere.ResourceProperties.ElasticBeanstalkApplicationMaxCountRule where
import Stratosphere.ResourceImports
-- | Full data type definition for ElasticBeanstalkApplicationMaxCountRule.
-- See 'elasticBeanstalkApplicationMaxCountRule' for a more convenient
-- constructor.
data ElasticBeanstalkApplicationMaxCountRule =
ElasticBeanstalkApplicationMaxCountRule
{ _elasticBeanstalkApplicationMaxCountRuleDeleteSourceFromS3 :: Maybe (Val Bool)
, _elasticBeanstalkApplicationMaxCountRuleEnabled :: Maybe (Val Bool)
, _elasticBeanstalkApplicationMaxCountRuleMaxCount :: Maybe (Val Integer)
} deriving (Show, Eq)
instance ToJSON ElasticBeanstalkApplicationMaxCountRule where
toJSON ElasticBeanstalkApplicationMaxCountRule{..} =
object $
catMaybes
[ fmap (("DeleteSourceFromS3",) . toJSON) _elasticBeanstalkApplicationMaxCountRuleDeleteSourceFromS3
, fmap (("Enabled",) . toJSON) _elasticBeanstalkApplicationMaxCountRuleEnabled
, fmap (("MaxCount",) . toJSON) _elasticBeanstalkApplicationMaxCountRuleMaxCount
]
-- | Constructor for 'ElasticBeanstalkApplicationMaxCountRule' containing
-- required fields as arguments.
elasticBeanstalkApplicationMaxCountRule
:: ElasticBeanstalkApplicationMaxCountRule
elasticBeanstalkApplicationMaxCountRule =
ElasticBeanstalkApplicationMaxCountRule
{ _elasticBeanstalkApplicationMaxCountRuleDeleteSourceFromS3 = Nothing
, _elasticBeanstalkApplicationMaxCountRuleEnabled = Nothing
, _elasticBeanstalkApplicationMaxCountRuleMaxCount = Nothing
}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticbeanstalk-application-maxcountrule.html#cfn-elasticbeanstalk-application-maxcountrule-deletesourcefroms3
ebamcrDeleteSourceFromS3 :: Lens' ElasticBeanstalkApplicationMaxCountRule (Maybe (Val Bool))
ebamcrDeleteSourceFromS3 = lens _elasticBeanstalkApplicationMaxCountRuleDeleteSourceFromS3 (\s a -> s { _elasticBeanstalkApplicationMaxCountRuleDeleteSourceFromS3 = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticbeanstalk-application-maxcountrule.html#cfn-elasticbeanstalk-application-maxcountrule-enabled
ebamcrEnabled :: Lens' ElasticBeanstalkApplicationMaxCountRule (Maybe (Val Bool))
ebamcrEnabled = lens _elasticBeanstalkApplicationMaxCountRuleEnabled (\s a -> s { _elasticBeanstalkApplicationMaxCountRuleEnabled = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-elasticbeanstalk-application-maxcountrule.html#cfn-elasticbeanstalk-application-maxcountrule-maxcount
ebamcrMaxCount :: Lens' ElasticBeanstalkApplicationMaxCountRule (Maybe (Val Integer))
ebamcrMaxCount = lens _elasticBeanstalkApplicationMaxCountRuleMaxCount (\s a -> s { _elasticBeanstalkApplicationMaxCountRuleMaxCount = a })
|
frontrowed/stratosphere
|
library-gen/Stratosphere/ResourceProperties/ElasticBeanstalkApplicationMaxCountRule.hs
|
mit
| 3,065
| 0
| 12
| 254
| 356
| 203
| 153
| 32
| 1
|
{-# LANGUAGE FlexibleContexts #-}
{-|
Module : PostgREST.Auth
Description : PostgREST authorization functions.
This module provides functions to deal with the JWT authorization (http://jwt.io).
It also can be used to define other authorization functions,
in the future Oauth, LDAP and similar integrations can be coded here.
Authentication should always be implemented in an external service.
In the test suite there is an example of simple login function that can be used for a
very simple authentication system inside the PostgreSQL database.
-}
module PostgREST.Auth (
setRole
, claimsToSQL
, jwtClaims
, tokenJWT
) where
import Control.Monad (join)
import Data.Aeson (Value (..), Object)
import Data.Aeson.Types (emptyObject, emptyArray)
import Data.Vector as V (null, head)
import Data.Map as M (fromList, toList)
import Data.Monoid ((<>))
import Data.String.Conversions (cs)
import Data.Text (Text)
import Data.Time.Clock (NominalDiffTime)
import PostgREST.PgQuery (pgFmtLit, pgFmtIdent, unquoted)
import qualified Web.JWT as JWT
import qualified Data.HashMap.Lazy as H
{-|
Receives a map of JWT claims and returns a list
of PostgreSQL statements to set the claims as user defined GUCs.
Except if we have a claim called role,
this one is mapped to a SET ROLE statement.
In case there is any problem decoding the JWT it returns Nothing.
-}
claimsToSQL :: JWT.ClaimsMap -> [Text]
claimsToSQL = map setVar . toList
where
setVar ("role", String val) = setRole val
setVar (k, val) = "set local postgrest.claims." <> pgFmtIdent k <>
" = " <> valueToVariable val <> ";"
valueToVariable = pgFmtLit . unquoted
{-|
Receives the JWT secret (from config) and a JWT and
returns a map of JWT claims
In case there is any problem decoding the JWT it returns Nothing.
-}
jwtClaims :: Text -> Text -> NominalDiffTime -> Maybe JWT.ClaimsMap
jwtClaims secret input time =
case join $ claim JWT.exp of
Just expires ->
if JWT.secondsSinceEpoch expires > time
then customClaims
else Nothing
_ -> customClaims
where
decoded = JWT.decodeAndVerifySignature (JWT.secret secret) input
claim :: (JWT.JWTClaimsSet -> a) -> Maybe a
claim prop = prop . JWT.claims <$> decoded
customClaims = claim JWT.unregisteredClaims
-- | Receives the name of a role and returns a SET ROLE statement
setRole :: Text -> Text
setRole role = "set local role " <> cs (pgFmtLit role) <> ";"
{-|
Receives the JWT secret (from config) and a JWT and a JSON value
and returns a signed JWT.
-}
tokenJWT :: Text -> Value -> Text
tokenJWT secret (Array a) = JWT.encodeSigned JWT.HS256 (JWT.secret secret)
JWT.def { JWT.unregisteredClaims = fromHashMap o }
where
Object o = if V.null a then emptyObject else V.head a
fromHashMap :: Object -> JWT.ClaimsMap
fromHashMap = M.fromList . H.toList
tokenJWT secret _ = tokenJWT secret emptyArray
|
calebmer/postgrest
|
src/PostgREST/Auth.hs
|
mit
| 3,286
| 0
| 11
| 937
| 582
| 322
| 260
| 45
| 3
|
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE DataKinds #-}
module Web.Apiary.Authenticate
( I.Auth
, I.AuthConfig(..), I.Provider(..)
, I.OpenId_(..), I.OpenId, pOpenId
-- * initializer
, initAuth, initAuthWith, initAuthWithManager
-- * handler
, authHandler
-- * filter
, authorized, authorized'
-- * action
, I.authLogout
-- ** getter
, authConfig, authProviders, authRoutes
) where
import Web.Apiary
import qualified Web.Apiary.Authenticate.Internal as I
import qualified Network.Routing.Dict as Dict
import qualified Network.HTTP.Client as Client
import Network.HTTP.Client.TLS(tlsManagerSettings)
import Web.Apiary.Session
import Control.Monad
import Control.Monad.Trans.Control
import Control.Monad.Apiary.Filter(Filter)
import qualified Data.Text as T
import qualified Data.ByteString as S
import GHC.TypeLits.Compat(KnownSymbol)
import Data.Apiary.Extension
pOpenId :: Proxy I.OpenId
pOpenId = Proxy
initAuthWithManager :: (Has (Session I.OpenId m) exts, MonadBaseControl IO m)
=> Client.Manager -> I.AuthConfig
-> Initializer m exts (I.Auth ': exts)
initAuthWithManager mgr conf = initializer' $ return (I.Auth mgr conf)
initAuthWith :: (Has (Session I.OpenId m) exts, MonadBaseControl IO m)
=> Client.ManagerSettings -> I.AuthConfig
-> Initializer m exts (I.Auth ': exts)
initAuthWith ms conf = initializerBracket' $ \m ->
control $ \run -> Client.withManager ms (\mgr -> run . m $ I.Auth mgr conf)
initAuth :: (Has (Session I.OpenId m) exts, MonadBaseControl IO m)
=> I.AuthConfig -> Initializer m exts (I.Auth ': exts)
initAuth = initAuthWith tlsManagerSettings
-- | default auth handlers. since 0.8.0.0.
authHandler :: (Monad m, MonadIO actM, Has I.Auth exts, Has (Session I.OpenId actM) exts)
=> ApiaryT exts prms actM m ()
authHandler = getExt (Proxy :: Proxy I.Auth) >>= I.authHandler
authorized' :: (Has (Session I.OpenId actM) exts, KnownSymbol key, Monad actM, key Dict.</ kvs)
=> proxy key
-> Filter exts actM m kvs (key := I.OpenId ': kvs)
authorized' ky = session' ky (Proxy :: Proxy I.OpenId)
-- | filter which check whether logged in or not, and get id. since 0.7.0.0.
authorized :: (Has (Session I.OpenId actM) exts, Monad actM, "auth" Dict.</ kvs)
=> Filter exts actM m kvs ("auth" := I.OpenId ': kvs)
authorized = authorized' (Proxy :: Proxy "auth")
authConfig :: (Has I.Auth exts, Monad m) => ActionT exts prms m I.AuthConfig
authConfig = I.config `liftM` getExt (Proxy :: Proxy I.Auth)
authProviders :: (Has I.Auth exts, Monad m) => ActionT exts prms m [(T.Text, I.Provider)]
authProviders = I.authProviders `liftM` getExt (Proxy :: Proxy I.Auth)
-- | get authenticate routes: (title, route). since 0.7.0.0.
authRoutes :: (Has I.Auth exts, Monad m) => ActionT exts prms m [(T.Text, S.ByteString)]
authRoutes = I.authRoutes `liftM` getExt (Proxy :: Proxy I.Auth)
|
philopon/apiary
|
apiary-authenticate/src/Web/Apiary/Authenticate.hs
|
mit
| 3,112
| 0
| 14
| 606
| 981
| 548
| 433
| -1
| -1
|
{-# LANGUAGE OverloadedStrings #-}
module Lexer where
import Prelude hiding (takeWhile)
import qualified Data.Text as Text
import qualified Data.Text.IO as Text
import Data.Text(Text)
import Control.Applicative((<|>))
import Data.Functor(($>))
import Data.Char(isSpace, isUpper, isAlphaNum)
import Data.Traversable(mapAccumL)
import Syntax
-- NOTE strict combinators are used
-- however <$!> instead of fmap would decrease performance
import Data.Attoparsec.Text(char, satisfy, takeWhile, takeWhile1,
many', sepBy1', match, parse, endOfInput, parseOnly,
hexadecimal, double, Parser)
{-
This module converts text to a list of lexemes
Inspired by the Haskell2010 report
-}
lexlex path s =
fmap withIndentTokens (parseOnly (program path) s)
{-# INLINE lexlex #-}
lexFileDebug path =
fmap (parse (program path)) (Text.readFile path)
lexFileDebug2 path =
fmap (fmap (fmap extractLexeme) . lexlex path)
(Text.readFile path)
lexDebug = parseOnly (program "")
{- Layout -}
layout ls@(LocatedLexeme (Indent n) pos:ts) (m:ms)
| n == m = semi pos : layout ts (m:ms)
| n < m = close pos : layout ls ms
| otherwise = layout ts (m:ms)
layout (LocatedLexeme (Block n) pos:ts) (m:ms)
| n > m = open pos : layout ts (n : m : ms)
layout (LocatedLexeme (Block n) pos:ts) []
| n > 0 = open pos : layout ts [n]
-- NOTE Removed. Allows only explicit empty blocks
--layout (LocatedLexeme (Block n) pos:ts) ms =
-- open pos : close pos :
-- layout (LocatedLexeme (Indent n) pos:ts) ms
layout (t@(LocatedLexeme (Reserved l) _):ts) (0:ms)
| l == "}" = t : layout ts ms
layout (t@(LocatedLexeme (Reserved l) _):_) _
| l == "}" = error ("Layout: Explicit "
++ prettyLocated t ++ " without open brace.")
layout (t@(LocatedLexeme (Reserved l) _):ts) ms
| l == "{" = t : layout ts (0:ms)
-- NOTE Parser rule left out.
layout (t:ts) ms = t:layout ts ms
layout [] [] = []
layout [] (_:ms) = close builtinLocation : layout [] ms
{-# INLINE layout #-}
semi pos = LocatedLexeme (Reserved ";") pos
open pos = LocatedLexeme (Reserved "{") pos
close pos = LocatedLexeme (Reserved "}") pos
isLayout (LocatedLexeme (Reserved t) _)
| elem t ["let", "where", "of"] = True
isLayout _ = False
-- add 1 because counting columns starts from 1
indLength ws = Text.length (last (Text.split (=='\n') ws)) + 1
getBlock (LocatedLexeme (Whitespace ws) pos) =
LocatedLexeme (Block (indLength ws)) pos
getBlock (LocatedLexeme _ pos) =
error ("getBlock impossible case at " ++ pretty pos)
getIndent (LocatedLexeme (Whitespace ws) pos) =
LocatedLexeme (Indent (indLength ws)) pos
getIndent (LocatedLexeme _ pos) =
error ("getIndent impossible case at " ++ pretty pos)
followedByOpen rest = case dropWhile isWhite rest of
(LocatedLexeme (Reserved t) _:_) | t == "{" -> True
_ -> False
-- TODO find the logic error in here
--insertIndentTokens (l:rest)
-- | isWhite l && not (isSignificantWhite l) =
-- insertIndentTokens rest
insertIndentTokens (l:rest@(r:rs))
| isLayout l && followedByOpen rest = l:insertIndentTokens rest
| isLayout l = l:getBlock r:insertIndentTokens rs
| isSignificantWhite l && isSignificantWhite r =
insertIndentTokens rest
| isSignificantWhite l && isWhite r = insertIndentTokens (l:rs)
insertIndentTokens (l:rest)
| isSignificantWhite l = getIndent l:insertIndentTokens rest
| isWhite l = insertIndentTokens rest
| otherwise = l:insertIndentTokens rest
insertIndentTokens [] = []
{-# INLINE insertIndentTokens #-}
-- Cut the open and close braces
cut xs = init (tail xs)
withIndentTokens ls = cut (layout (
LocatedLexeme (Block 1) builtinLocation : insertIndentTokens ls) [])
{-# INLINE withIndentTokens #-}
isWhite (LocatedLexeme (Whitespace _) _) = True
isWhite (LocatedLexeme (Comment _) _) = True
isWhite _ = False
isSignificantWhite (LocatedLexeme (Whitespace ws) _) =
Text.any (=='\n') ws
isSignificantWhite _ = False
{- Locations -}
advance (Position l _) '\n' =
Position (l + 1) 1
advance (Position l c) _ =
Position l (c + 1)
initialPosition = Position 1 1
oneOf :: String -> Parser Char
oneOf xs = satisfy (\x -> elem x xs)
{-# INLINE oneOf #-}
data LocatedLexeme = LocatedLexeme Lexeme Location
deriving (Show)
extractLocation (LocatedLexeme _ p) = p
extractLexeme (LocatedLexeme l _) = l
prettyLocated (LocatedLexeme l p) = show l ++ " " ++ pretty p
data Lexeme
= Reserved Text
| Whitespace Text
| Double Double
| Integer Int
| String Text
| Varid [Text] Text
| Varsym [Text] Text
| Conid [Text] Text
| Comment Text
| Block Int
| Indent Int
deriving (Show)
{-
Attoparsec does not have location information,
but match returns the input that was consumed by a parser
the position is calculated from the input and passed to the next parser
-}
located path lexemes = snd (mapAccumL (\startPosition (parsed, result) ->
let
endPosition = Text.foldl' advance startPosition parsed
location = Location startPosition endPosition path
locatedLexeme = LocatedLexeme result location
in (endPosition, locatedLexeme)) initialPosition lexemes)
{-# INLINE located #-}
program path = fmap (located path)
(many' (match (whitespace <|> lexeme)) <* endOfInput)
lexeme = literal <|> special <|> qident
{-# INLINE lexeme #-}
-- NOTE . was addded
-- it is part of for example forall a. a
special = fmap (Reserved . Text.singleton) (oneOf "(),;[]`{}.")
{-# INLINE special #-}
-- TODO multi-line comments
whitespace = whitechars <|> hashcomment <|> slashcomment
{-# INLINE whitespace #-}
whitechars = fmap Whitespace (takeWhile1 isSpace)
{-# INLINE whitechars #-}
-- NOTE in contrast to the report this does not consume a newline
hashcomment = fmap Comment (char '#' *> takeWhile (/='\n'))
{-# INLINE hashcomment #-}
slashcomment = fmap Comment (char '/' *> char '/' *> takeWhile (/='\n'))
{-# INLINE slashcomment #-}
qident = fmap (\ms -> makeIdent (init ms) (last ms))
(sepBy1' (ident <|> varsym) (char '.'))
{-# INLINE qident #-}
-- TODO improve this check
-- qualifiers have to start with an uppercase qualifier
makeIdent ms i | any (firstIs (not . isUpper)) ms =
error ("Bad qualifier for identifier " ++ show i)
makeIdent [] i | elem i reserved = Reserved i
makeIdent ms i | firstIs isUpper i = Conid ms i
makeIdent ms i | firstIs isSym i = Varsym ms i
makeIdent ms i = Varid ms i
{-# INLINE makeIdent #-}
{- Identifiers -}
reserved = ["alias", "enum", "type", "forall", "await",
"import", "module", "fun", "let", "in", "where", "case", "of",
"if", "then", "else", "infix", "infixl", "infixr", "as", "_",
":", "=", "->", "|"]
ident = takeWhile1 (\x -> isAlphaNum x || x == '_')
{-# INLINE ident #-}
varsym = takeWhile1 isSym
{-# INLINE varsym #-}
{- Literal -}
literal = number <|> hexdecimal <|> verbatim
{-# INLINE literal #-}
hexdecimal = fmap Integer
(char '0' *> oneOf "xX" *> hexadecimal)
{-# INLINE hexdecimal #-}
-- TODO parse integers
-- attoparsec parses a decimal as a double
-- for example 3 is parsed as 3.0
number = fmap Double double
{-# INLINE number #-}
verbatim = fmap (String . Text.pack)
(char '"' *> many' (stringChar <|> escapeSeq) <* char '"')
{-# INLINE verbatim #-}
stringChar = satisfy (\x -> x /='"' && x /= '\\')
{-# INLINE stringChar #-}
escapeSeq = char '\\' *> (char '\\' <|> char '\"' <|>
char 'n' $> '\n' <|> char 'r' $> '\r' <|> char 't' $> '\t')
{-# INLINE escapeSeq #-}
|
kindl/Hypatia
|
src/Lexer.hs
|
mit
| 7,519
| 0
| 15
| 1,521
| 2,507
| 1,294
| 1,213
| 162
| 2
|
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.VideoTrackList
(js_item, item, js_getTrackById, getTrackById, js_getLength,
getLength, js_getSelectedIndex, getSelectedIndex, change, addTrack,
removeTrack, VideoTrackList, castToVideoTrackList,
gTypeVideoTrackList)
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[\"item\"]($2)" js_item ::
JSRef VideoTrackList -> Word -> IO (JSRef VideoTrack)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/VideoTrackList.item Mozilla VideoTrackList.item documentation>
item ::
(MonadIO m) => VideoTrackList -> Word -> m (Maybe VideoTrack)
item self index
= liftIO ((js_item (unVideoTrackList self) index) >>= fromJSRef)
foreign import javascript unsafe "$1[\"getTrackById\"]($2)"
js_getTrackById ::
JSRef VideoTrackList -> JSString -> IO (JSRef VideoTrack)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/VideoTrackList.getTrackById Mozilla VideoTrackList.getTrackById documentation>
getTrackById ::
(MonadIO m, ToJSString id) =>
VideoTrackList -> id -> m (Maybe VideoTrack)
getTrackById self id
= liftIO
((js_getTrackById (unVideoTrackList self) (toJSString id)) >>=
fromJSRef)
foreign import javascript unsafe "$1[\"length\"]" js_getLength ::
JSRef VideoTrackList -> IO Word
-- | <https://developer.mozilla.org/en-US/docs/Web/API/VideoTrackList.length Mozilla VideoTrackList.length documentation>
getLength :: (MonadIO m) => VideoTrackList -> m Word
getLength self = liftIO (js_getLength (unVideoTrackList self))
foreign import javascript unsafe "$1[\"selectedIndex\"]"
js_getSelectedIndex :: JSRef VideoTrackList -> IO Int
-- | <https://developer.mozilla.org/en-US/docs/Web/API/VideoTrackList.selectedIndex Mozilla VideoTrackList.selectedIndex documentation>
getSelectedIndex :: (MonadIO m) => VideoTrackList -> m Int
getSelectedIndex self
= liftIO (js_getSelectedIndex (unVideoTrackList self))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/VideoTrackList.onchange Mozilla VideoTrackList.onchange documentation>
change :: EventName VideoTrackList Event
change = unsafeEventName (toJSString "change")
-- | <https://developer.mozilla.org/en-US/docs/Web/API/VideoTrackList.onaddtrack Mozilla VideoTrackList.onaddtrack documentation>
addTrack :: EventName VideoTrackList Event
addTrack = unsafeEventName (toJSString "addtrack")
-- | <https://developer.mozilla.org/en-US/docs/Web/API/VideoTrackList.onremovetrack Mozilla VideoTrackList.onremovetrack documentation>
removeTrack :: EventName VideoTrackList Event
removeTrack = unsafeEventName (toJSString "removetrack")
|
plow-technologies/ghcjs-dom
|
src/GHCJS/DOM/JSFFI/Generated/VideoTrackList.hs
|
mit
| 3,471
| 28
| 11
| 452
| 741
| 428
| 313
| 51
| 1
|
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE UnicodeSyntax #-}
module Control.Monad.Open.Class
( MonadOpen(..)
, Op(..)
) where
import Control.Applicative
import Control.Monad.Except
import Control.Monad.List
import Control.Monad.Reader
import Control.Monad.Trans.Identity
import Control.Monad.Trans.Cont
import Control.Monad.Trans.Maybe
import qualified Control.Monad.RWS.Strict as Strict
import qualified Control.Monad.RWS.Lazy as Lazy
import qualified Control.Monad.Writer.Strict as Strict
import qualified Control.Monad.Writer.Lazy as Lazy
import qualified Control.Monad.State.Strict as Strict
import qualified Control.Monad.State.Lazy as Lazy
import Data.Monoid
-- | To know @'MonadOpen' a b m@ is to have a function @a → m b@ which serves
-- as a recursive call to the ambient open operation. The @'MonadOpen' a b m@
-- judgement presupposes @'Monad' m@.
--
class Monad m ⇒ MonadOpen a b m | m → a b where
-- | A recursive call to the ambient open operation.
call ∷ a → m b
-- | The type of open operations from @a@ to @b@ in modality @m@; when
-- @'Alternative' m@ is evident, then such operations may be composed
-- horizontally via a 'Monoid' instance.
newtype Op a m b = Op { _op ∷ a → m b }
instance Alternative m ⇒ Monoid (Op a m b) where
mempty = Op $ \_ → empty
mappend (Op f) (Op g) = Op $ \x → f x <|> g x
instance MonadOpen a b m ⇒ MonadOpen a b (ReaderT r m) where
call = lift . call
instance (Monoid w, MonadOpen a b m) ⇒ MonadOpen a b (Strict.WriterT w m) where
call = lift . call
instance (Monoid w, MonadOpen a b m) ⇒ MonadOpen a b (Lazy.WriterT w m) where
call = lift . call
instance MonadOpen a b m ⇒ MonadOpen a b (Strict.StateT s m) where
call = lift . call
instance MonadOpen a b m ⇒ MonadOpen a b (Lazy.StateT s m) where
call = lift . call
instance (Monoid w, MonadOpen a b m) ⇒ MonadOpen a b (Strict.RWST r w s m) where
call = lift . call
instance (Monoid w, MonadOpen a b m) ⇒ MonadOpen a b (Lazy.RWST r w s m) where
call = lift . call
instance MonadOpen a b m ⇒ MonadOpen a b (ExceptT e m) where
call = lift . call
instance MonadOpen a b m ⇒ MonadOpen a b (IdentityT m) where
call = lift . call
instance MonadOpen a b m ⇒ MonadOpen a b (ContT r m) where
call = lift . call
instance MonadOpen a b m ⇒ MonadOpen a b (ListT m) where
call = lift . call
instance MonadOpen a b m ⇒ MonadOpen a b (MaybeT m) where
call = lift . call
|
jonsterling/hs-monad-open
|
src/Control/Monad/Open/Class.hs
|
mit
| 2,692
| 0
| 9
| 504
| 818
| 457
| 361
| 56
| 0
|
{-# LANGUAGE GADTs #-}
{-# LANGUAGE StandaloneDeriving #-}
module RPG.Spell where
import qualified Data.Map.Strict as Map
data SpellType a where
MagicMissile :: SpellType ()
Drain :: SpellType ()
Shield :: SpellType Int
Poison :: SpellType Int
Recharge :: SpellType Int
deriving instance Show (SpellType a)
deriving instance Eq (SpellType a)
deriving instance Ord (SpellType a)
data SpellStats =
SpellStats { spCost :: Int
, spEnemyHP :: Int
, spPlayerHP :: Int
, spPlayerMana :: Int
, spPlayerArmor :: Int
} deriving (Show, Eq)
data Spell = Now (SpellType ())
| Later (SpellType Int)
deriving (Show, Eq, Ord)
data Effect =
Effect { eSpell :: SpellType Int
, eStats :: SpellStats
, eDuration :: Int
} deriving (Show, Eq)
type Effects = Map.Map (SpellType Int) Effect
mt :: SpellStats
mt = SpellStats 0 0 0 0 0
getStats :: SpellType a -> SpellStats
getStats x = case x of
MagicMissile -> mt { spCost = 53, spEnemyHP = -4 }
Drain -> mt { spCost = 73, spEnemyHP = -2, spPlayerHP = 2 }
Shield -> mt { spCost = 113, spPlayerArmor = 7 }
Poison -> mt { spCost = 173, spEnemyHP = -3 }
Recharge -> mt { spCost = 229, spPlayerMana = 101 }
getDuration :: SpellType Int -> Int
getDuration x = case x of
Shield -> 6
Poison -> 6
Recharge -> 5
getEffect :: SpellType Int -> Effect
getEffect x = Effect x (getStats x) (getDuration x)
cost :: Spell -> Int
cost x =
case x of
Now s -> f s
Later s -> f s
where f = spCost . getStats
spells = [ Now MagicMissile
, Now Drain
, Later Shield
, Later Poison
, Later Recharge]
validSequence :: [Spell] -> Bool
validSequence spells' = notInRange (Later Shield) 2 && notInRange (Later Poison) 2 && notInRange (Later Recharge) 2
where notInRange x n = and [all (\(a,b) -> a /= b || (a == b && a /= x)) (zip (shifted i) spells') | i <- [1..n]]
shifted n = drop n spells'
-- getSequenceOf :: Int -> IO [Spell]
-- getSequenceOf i = do
-- xs <- runRVar (choices i spells) StdRandom
-- if validSequence xs
-- then return xs
-- else getSequenceOf i
-- spellSequences :: IO [[Spell]]
-- spellSequences = return [[ Later Shield
-- , Later Recharge
-- , Later Poison
-- , Later Shield
-- , Later Recharge
-- , Later Poison
-- , Later Shield
-- , Later Recharge
-- , Later Poison
-- , Later Shield
-- , Later Recharge
-- , Later Poison
-- , Now MagicMissile
-- , Now MagicMissile
-- ]]
-- spellSequences :: IO [[Spell]]
-- spellSequences =
-- fmap concat . forM [13..13] $ \i ->
-- replicateM 1000 (getSequenceOf i)
|
corajr/adventofcode2015
|
22/src/RPG/Spell.hs
|
mit
| 3,016
| 0
| 16
| 1,050
| 777
| 431
| 346
| 60
| 5
|
{-# LANGUAGE DeriveDataTypeable, OverloadedStrings #-}
import XMonad
import qualified XMonad.StackSet as W
import qualified XMonad.Actions.Search as S
import XMonad.Actions.Promote
import XMonad.Actions.UpdatePointer
import XMonad.Config.Desktop
import XMonad.Config.Xfce
import XMonad.Hooks.DBusLog
import XMonad.Hooks.EwmhDesktops
import XMonad.Hooks.ManageHelpers
import XMonad.Hooks.Place
import XMonad.Hooks.UrgencyHook
import XMonad.Layout.Accordion
import XMonad.Layout.Drawer
import XMonad.Layout.Grid
import XMonad.Layout.Tabbed
import XMonad.Layout.DwmStyle
import XMonad.Layout.MultiToggle
import XMonad.Layout.MultiToggle.Instances
import XMonad.Layout.NoBorders hiding (Never)
import XMonad.Layout.PerWorkspace
import XMonad.Layout.Renamed
import XMonad.Layout.ShowWName
import XMonad.Prompt
import XMonad.Prompt.Man
import XMonad.Util.EZConfig
import XMonad.Util.NamedScratchpad
import XMonad.Util.AutoUpdateLog
import qualified Network.MPD as M
import qualified Network.MPD.Commands.Extensions as M
import qualified XMonad.Util.MPD as M
main = xmonad $ myUrgencyHook myConfig
myUrgencyHook = withUrgencyHookC NoUrgencyHook urgencyConfig
{ suppressWhen = Visible
}
myConfig = (\c -> c
{ modMask = mod4Mask
, startupHook = do
return ()
autoUpdateLog 1
connectDBusSession
startupHook c
, layoutHook = myLayouts
, logHook = do
updatePointer $ Relative 0.9 0.9
dbusLogWithPP myPrettyPrinter
ewmhDesktopsLogHookCustom namedScratchpadFilterOutWorkspace
, manageHook = myManageHook <+> manageHook c
, handleEventHook = updateLogEventHook <+> ewmhDesktopsEventHookCustom namedScratchpadFilterOutWorkspace
, workspaces = ["web", "2", "3", "4", "mail", "chat"]
, normalBorderColor = "#1d1d1d"
, focusedBorderColor = "#4894E3"
, focusFollowsMouse = True
, clickJustFocuses = False
, keys = myKeys <+> keys c
}) xfceConfig
myKeys c = mkKeymap c $
[ ("M-<Return>", promote)
, ("M-r", sendMessage $ Toggle MIRROR)
, ("<XF86AudioPrev>", M.withMPDX $ M.previous)
, ("<XF86AudioPlay>", M.withMPDX $ M.toggle)
, ("<XF86AudioNext>", M.withMPDX $ M.next)
, ("M-m", M.ncmpcKeys' defaultXPConfig $ mkKeymap c
[ ("M-m", namedScratchpadAction myScratchpads "ncmpcpp")
])
, ("M-s t", namedScratchpadAction myScratchpads "todo")
, ("M-s p", namedScratchpadAction myScratchpads "htop")
, ("M-s m", manPrompt defaultXPConfig)
] ++
[ ("M-s " ++ k, S.promptSearch defaultXPConfig f) | (k, f) <- searchList ] ++
[ ("M-S-s " ++ k, S.selectSearch f) | (k, f) <- searchList ]
where
searchList =
[ ("g", S.google)
, ("h", S.hoogle)
, ("w", S.wikipedia)
, ("v", S.youtube)
, ("e", S.wiktionary)
, ("a", S.alpha)
, ("x", S.multi)
]
myScratchpads =
[ termPad "ncmpcpp" "-e music" (customFloating $ W.RationalRect 0.25 0.25 0.5 0.5)
, termPad "todo" "" (customFloating $ W.RationalRect 0.75 0.1 0.25 0.8)
, termPad "htop" "-e htop" (customFloating $ W.RationalRect 0.55 0.1 0.45 0.8)
]
where
termPad n c p = NS n
( "Terminal --role=" ++ n
++ " --title=" ++ n
++ " " ++ c
) (windowRole =? n) p
windowRole = stringProperty "WM_WINDOW_ROLE"
myPrettyPrinter = dbusPP
{ ppOrder = \ (_:l:_:e) -> l:e
, ppExtras = [ M.nowPlaying, M.songTimeInfo, M.statusString ]
}
myManageHook = composeAll
[ isFullscreen --> doFullFloat
, namedScratchpadManageHook myScratchpads
, transience'
, associateWith "web" ["Firefox"]
, associateWith "chat" ["Pidgin", "Skype", "Konversation"]
, associateWith "mail" ["Thunderbird"]
, forClasses ["Xfrun4", "Xfce4-appfinder"] $ placeHook (smart (0.5, 0.5)) <+> doFloat
, isNotification --> doIgnore
]
where
forClasses clsx ac = composeAll [ className =? c --> ac | c <- clsx]
associateWith ws clsx = forClasses clsx $ doShift ws
isNotification = isInProperty "_NET_WM_WINDOW_TYPE" "_NET_WM_WINDOW_TYPE_NOTIFICATION"
myLayouts =
desktopLayoutModifiers $
showWName $
smartBorders $
renamed [CutWordsLeft 1] $
dwmStyle shrinkText defaultTheme $
onWorkspace "chat" (renamed [CutWordsLeft 2] chatLayouts) $
layouts
where
layouts = (mkToggle (single MIRROR) $ tall ||| Grid ||| Accordion) ||| tabbed
chatLayouts =
(drawer skype) `onLeft`
((drawer pidgin) `onRight` (Mirror Grid ||| tabbed))
tall = Tall 1 (3/100) (1/2)
tabbed = renamed [Replace "Tabbed"] simpleTabbed
pidgin = Title "Buddy List"
skype =
(ClassName "Skype") `And`
(Not $ Role "ConversationsWindow") `And`
(Not $ Title "Options")
drawer = simpleDrawer 0.01 (1/5)
|
jdpage/xmonad-config
|
xmonad.hs
|
mit
| 4,938
| 0
| 14
| 1,168
| 1,363
| 772
| 591
| 123
| 1
|
module Irg.Lab3.Initialize (initialize) where
--import qualified Graphics.GL.Compatibility33 as GL
import qualified Graphics.UI.GLUT as GLUT
import Graphics.UI.GLUT (($=))
--import Data.IORef
import Irg.Lab3.Utility
initialize :: GameState -> ReshapeCallback -> DisplayCallback -> KeyboardCallback -> MouseCallback -> IO ()
initialize gameState reshapeCallback displayCallback keyboardCallback mouseCallback = do
_ <- GLUT.initialize "irg" []
GLUT.initialWindowPosition $= GLUT.Position 100 100
GLUT.initialWindowSize $= GLUT.Size 800 800
GLUT.initialDisplayMode $= [GLUT.RGBAMode, GLUT.DoubleBuffered]
GLUT.actionOnWindowClose $= GLUT.MainLoopReturns
_ <- GLUT.createWindow "irg"
GLUT.reshapeCallback $= Just (reshapeCallback gameState)
GLUT.displayCallback $= (displayCallback gameState 0.0)
GLUT.keyboardCallback $= Just (keyboardCallback gameState)
GLUT.mouseCallback $= Just (mouseCallback gameState)
print "Start end"
GLUT.get GLUT.initState >>= print
GLUT.get GLUT.glVersion >>= print
GLUT.mainLoop
|
DominikDitoIvosevic/Uni
|
IRG/src/Irg/Lab3/Initialize.hs
|
mit
| 1,040
| 0
| 11
| 135
| 288
| 142
| 146
| 20
| 1
|
{-# LANGUAGE ForeignFunctionInterface #-}
module Printf (printfHack) where
-- This module is an evil hack to get printf in haskell.
-- Text.Printf doesn't work, because variable numbers of arguments (at run
-- time) aren't possible (I think).
import Foreign
import Foreign.C
import Foreign.LibFFI
printfHack :: String -> [Int] -> IO Int
printfHack fmt args = do
ret <- callFFI printf retCInt $
argString fmt : map (argCInt . fromIntegral) args
return $ fromIntegral ret
foreign import ccall "&printf"
printf :: FunPtr (CString -> IO CInt)
|
tomjnixon/Whilecmp
|
src/Printf.hs
|
mit
| 549
| 4
| 11
| 95
| 129
| 68
| 61
| 12
| 1
|
module Feature.QueryLimitedSpec where
import Network.Wai (Application)
import Network.Wai.Test (SResponse (simpleHeaders, simpleStatus))
import Network.HTTP.Types
import Test.Hspec
import Test.Hspec.Wai
import Test.Hspec.Wai.JSON
import Protolude hiding (get)
import SpecHelper
spec :: SpecWith Application
spec =
describe "Requesting many items with server limits enabled" $ do
it "restricts results" $
get "/items"
`shouldRespondWith` [json| [{"id":1},{"id":2}] |]
{ matchStatus = 200
, matchHeaders = ["Content-Range" <:> "0-1/*"]
}
it "respects additional client limiting" $ do
r <- request methodGet "/items"
(rangeHdrs $ ByteRangeFromTo 0 0) ""
liftIO $ do
simpleHeaders r `shouldSatisfy`
matchHeader "Content-Range" "0-0/*"
simpleStatus r `shouldBe` ok200
it "limit works on all levels" $
get "/users?select=id,tasks(id)&order=id.asc&tasks.order=id.asc"
`shouldRespondWith` [json|[{"id":1,"tasks":[{"id":1},{"id":2}]},{"id":2,"tasks":[{"id":5},{"id":6}]}]|]
{ matchStatus = 200
, matchHeaders = ["Content-Range" <:> "0-1/*"]
}
it "limit is not applied to parent embeds" $
get "/tasks?select=id,project(id)&id=gt.5"
`shouldRespondWith` [json|[{"id":6,"project":{"id":3}},{"id":7,"project":{"id":4}}]|]
{ matchStatus = 200
, matchHeaders = ["Content-Range" <:> "0-1/*"]
}
|
diogob/postgrest
|
test/Feature/QueryLimitedSpec.hs
|
mit
| 1,483
| 0
| 15
| 345
| 295
| 168
| 127
| -1
| -1
|
module Main where
import qualified Data.ByteString.Lazy as BL
import Mozart.Composition
main :: IO ()
main = do
configuration <- BL.getContents
template <- BL.readFile "test/template.html"
page <- compose configuration template
putStrLn page
|
wildlyinaccurate/mozart
|
src/Main.hs
|
mit
| 261
| 0
| 9
| 50
| 72
| 37
| 35
| 9
| 1
|
-- sum two numbers
import Haste.HPlay.View
import Control.Applicative
main= runBody sumTwo
sumTwo :: Widget ()
sumTwo = p "This widget sum two numbers and append the result. Using applicative and monadic expressions" ++>
(p <<< do
r <- (+) <$> fromStr "first number" ++> br
++> inputInt Nothing `fire` OnKeyUp ! atr "size" "7" <++ br
<*> fromStr "second number " ++> br
++> (inputInt Nothing ! atr "size" "7" `validate` less10 `fire` OnKeyUp ) <++ br
p <<< fromStr "result: " ++> b (show r) ++> return())
where
less10 x= if x < 10 then return Nothing else return . Just $ b " no more than 10 please"
|
agocorona/tryhplay
|
examples/sumtwonumbers-copy.hs
|
gpl-3.0
| 681
| 0
| 21
| 191
| 210
| 106
| 104
| 12
| 2
|
{-
This file is part of The Simple Nice Manual Generator.
The Simple Nice Manual Generator is free software: you can
redistribute it and/or modify it under the terms of the GNU
General Public License as published by the Free Software Foundation,
either version 3 of the License, or any later version.
The Simple Nice Manual Generator is distributed in the hope that it
will be useful, but WITHOUT ANY WARRANTY; without even the implied
warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with The Simple Nice Manual Generator.
If not, see <http://www.gnu.org/licenses/>
-}
-- | Create simple syntax highlighting plugins
module Text.Syntax.Simple where
import Manual.Structure
import Data.Dynamic
import Data.Either
import Text.Parsec
import Text.Parsec.String
import Text.Parsec.Prim
import Text.XHtml.Strict
import Error.Report
import Control.Exception hiding (try)
import Control.Monad
-- | Create a simple plugin which highlights keywords.
highlight :: String -- ^ The name of the plugin
-> [(String, String, String)] -- ^ The first is the keyword, second the class, third the returned string (allowing the keyword to be transformed)
-> Dynamic
highlight name = toDyn . associate_keywords name
-- | Associate keywords with a class
associate_keywords :: String -- ^ The name of the plugin
-> [(String, String, String)] -- ^ The first is the keyword, second the class, third the returned string (allowing the keyword to be transformed)
-> SyntaxHighlighter
associate_keywords name key_assoc str =
either perror id $ parse (keyword_or_plain key_assoc) "" str
where
perror e =
throw $ error_lines ["Programmer error in plugin '" ++ name ++ "'"
,"<Begin input>"
,str
,"<End input>"] $ report e
-- | Plain text or highlight
keyword_or_plain :: [(String, String, String)] -- ^ The first is the keyword, second the class, third the returned string (allowing the keyword to be transformed)
-> Parser (String, String, String)
keyword_or_plain key_assoc = plain_acc ""
where
plain_acc acc =
try key_ahead <|> plain
where
key_ahead = do
lookAhead $ grab_keys key_assoc
if null acc
then grab_keys key_assoc
else do
i <- getInput
return ("", accum, i)
plain =
(do c <- anyChar
plain_acc $ c : acc) <|> (eof >> return ("", accum, ""))
accum = stringToHtmlString $ reverse acc
-- | Parse one of many keyworsd
grab_keys :: [(String, String, String)] -- ^ The first is the keyword, second the class, third the returned string (allowing the keyword to be transformed)
-> Parser (String, String, String)
grab_keys = msum . map (try . grab_key)
-- | Parse one keyword
grab_key :: (String, String, String) -- ^ The first is the keyword, second the class, third the returned string (allowing the keyword to be transformed)
-> Parser (String, String, String)
grab_key (keyword, cls, ret) = do
string keyword
i <- getInput
return (cls, ret, i)
|
elginer/snm
|
Text/Syntax/Simple.hs
|
gpl-3.0
| 3,350
| 0
| 15
| 863
| 528
| 295
| 233
| 50
| 2
|
{-# LANGUAGE OverloadedStrings #-}
----------------------------------------------------------------------
-- |
-- Module : Text.Doc.Writer.Core
-- Copyright : 2015-2017 Mathias Schenner,
-- 2015-2016 Language Science Press.
-- License : GPL-3
--
-- Maintainer : mschenner.dev@gmail.com
-- Stability : experimental
-- Portability : GHC
--
-- Common types and utilities for writers.
----------------------------------------------------------------------
module Text.Doc.Writer.Core
( -- * XML generation
el
, leaf
, attr
, (<!>)
, withXmlDeclaration
, withXhtml11Doctype
-- * Lifted monoid functions
, (<+>)
, ($<>)
, (<>$)
, memptyR
, mconcatR
, foldMapR
, unlessR
) where
import Control.Applicative
import Data.Monoid
import Data.Text (Text)
import qualified Data.Text as T
import Text.Blaze (Markup, Attribute, AttributeValue, textTag, (!), preEscapedText)
import Text.Blaze.Internal (Attributable, customLeaf, customParent, attribute)
---------- Generate XML Markup
-- | Create element with content from tag name.
el :: Text -> Markup -> Markup
el = customParent . textTag
-- | Create self-closing empty element from tag name.
leaf :: Text -> Markup
leaf = flip customLeaf True . textTag
-- | Create attribute from name and value.
attr :: Text -> AttributeValue -> Attribute
attr n = attribute (textTag n) (textTag (" " <> n <> "=\""))
infixl 5 <!>
-- | Lifted attribute setter.
(<!>) :: (Functor f, Attributable h) => f h -> Attribute -> f h
(<!>) = flip (fmap . flip (!))
-- | Prefix XML declaration.
withXmlDeclaration :: Markup -> Markup
withXmlDeclaration =
(preEscapedText "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" <>)
-- | Prefix XHTML 1.1 doctype declaration.
withXhtml11Doctype :: Markup -> Markup
withXhtml11Doctype = (preEscapedText xhtml11Doctype <>)
where
xhtml11Doctype = T.unlines
[ "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\""
, " \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">" ]
---------- Lifted monoid functions
-- These are mainly intended for monads atop 'Markup'.
infixl 5 <+>
infixr 5 $<>
infixl 5 <>$
-- | Lifted mappend.
(<+>) :: (Applicative f, Monoid a) => f a -> f a -> f a
(<+>) = liftA2 mappend
-- | Lifted mappend, apply pure to left value.
($<>) :: (Functor f, Monoid a) => a -> f a -> f a
($<>) = fmap . mappend
-- | Lifted mappend, apply pure to right value.
(<>$) :: (Functor f, Monoid a) => f a -> a -> f a
(<>$) = flip (fmap . flip mappend)
-- | Lifted mempty.
memptyR :: (Applicative f, Monoid a) => f a
memptyR = pure mempty
-- | Lifted mconcat.
mconcatR :: (Applicative f, Monoid a) => [f a] -> f a
mconcatR = foldr (<+>) memptyR
-- | Specialized foldMap.
foldMapR :: (Applicative f, Monoid b) => (a -> f b) -> [a] -> f b
foldMapR f = mconcatR . map f
-- | Conditional insertion of a monoid value.
unlessR :: (Applicative f, Monoid a) => Bool -> f a -> f a
unlessR True = const memptyR
unlessR False = id
|
synsem/texhs
|
src/Text/Doc/Writer/Core.hs
|
gpl-3.0
| 2,965
| 0
| 10
| 564
| 736
| 427
| 309
| 57
| 1
|
{-|
A ledger-compatible @register@ command.
-}
{-# LANGUAGE CPP, OverloadedStrings #-}
module Hledger.Cli.Commands.Register (
registermode
,register
,postingsReportAsText
,postingsReportItemAsText
-- ,showPostingWithBalanceForVty
,tests_Hledger_Cli_Commands_Register
) where
import Data.List
import Data.Maybe
-- import Data.Text (Text)
import qualified Data.Text as T
import System.Console.CmdArgs.Explicit
import Text.CSV
import Test.HUnit
import Hledger
import Hledger.Cli.CliOptions
import Hledger.Cli.Utils
registermode = (defCommandMode $ ["register"] ++ aliases) {
modeHelp = "show postings and running total. With --date2, show and sort by secondary date instead." `withAliases` aliases
,modeGroupFlags = Group {
groupUnnamed = [
flagNone ["cumulative"] (\opts -> setboolopt "change" opts)
"show running total from report start date (default)"
,flagNone ["historical","H"] (\opts -> setboolopt "historical" opts)
"show historical running total/balance (includes postings before report start date)\n "
,flagNone ["average","A"] (\opts -> setboolopt "average" opts)
"show running average of posting amounts instead of total (implies --empty)"
,flagNone ["related","r"] (\opts -> setboolopt "related" opts) "show postings' siblings instead"
,flagReq ["width","w"] (\s opts -> Right $ setopt "width" s opts) "N"
("set output width (default: " ++
#ifdef mingw32_HOST_OS
show defaultWidth
#else
"terminal width"
#endif
++ " or $COLUMNS). -wN,M sets description width as well."
)
]
++ outputflags
,groupHidden = []
,groupNamed = [generalflagsgroup1]
}
}
where aliases = ["r","reg"]
-- | Print a (posting) register report.
register :: CliOpts -> Journal -> IO ()
register opts@CliOpts{reportopts_=ropts} j = do
d <- getCurrentDay
let fmt = outputFormatFromOpts opts
render | fmt=="csv" = const ((++"\n") . printCSV . postingsReportAsCsv)
| otherwise = postingsReportAsText
writeOutput opts $ render opts $ postingsReport ropts (queryFromOpts d ropts) j
postingsReportAsCsv :: PostingsReport -> CSV
postingsReportAsCsv (_,is) =
["txnidx","date","description","account","amount","total"]
:
map postingsReportItemAsCsvRecord is
postingsReportItemAsCsvRecord :: PostingsReportItem -> Record
postingsReportItemAsCsvRecord (_, _, _, p, b) = [idx,date,desc,acct,amt,bal]
where
idx = show $ maybe 0 tindex $ ptransaction p
date = showDate $ postingDate p -- XXX csv should show date2 with --date2
desc = T.unpack $ maybe "" tdescription $ ptransaction p
acct = bracket $ T.unpack $ paccount p
where
bracket = case ptype p of
BalancedVirtualPosting -> (\s -> "["++s++"]")
VirtualPosting -> (\s -> "("++s++")")
_ -> id
amt = showMixedAmountOneLineWithoutPrice $ pamount p
bal = showMixedAmountOneLineWithoutPrice b
-- | Render a register report as plain text suitable for console output.
postingsReportAsText :: CliOpts -> PostingsReport -> String
postingsReportAsText opts (_,items) = unlines $ map (postingsReportItemAsText opts amtwidth balwidth) items
where
amtwidth = maximumStrict $ 12 : map (strWidth . showMixedAmount . itemamt) items
balwidth = maximumStrict $ 12 : map (strWidth . showMixedAmount . itembal) items
itemamt (_,_,_,Posting{pamount=a},_) = a
itembal (_,_,_,_,a) = a
tests_postingsReportAsText = [
"postingsReportAsText" ~: do
-- "unicode in register layout" ~: do
j <- readJournal'
"2009/01/01 * медвежья шкура\n расходы:покупки 100\n актив:наличные\n"
let opts = defreportopts
(postingsReportAsText defcliopts $ postingsReport opts (queryFromOpts (parsedate "2008/11/26") opts) j) `is` unlines
["2009/01/01 медвежья шкура расходы:покупки 100 100"
," актив:наличные -100 0"]
]
-- | Render one register report line item as plain text. Layout is like so:
-- @
-- <---------------- width (specified, terminal width, or 80) -------------------->
-- date (10) description account amount (12) balance (12)
-- DDDDDDDDDD dddddddddddddddddddd aaaaaaaaaaaaaaaaaaa AAAAAAAAAAAA AAAAAAAAAAAA
-- @
-- If description's width is specified, account will use the remaining space.
-- Otherwise, description and account divide up the space equally.
--
-- With a report interval, the layout is like so:
-- @
-- <---------------- width (specified, terminal width, or 80) -------------------->
-- date (21) account amount (12) balance (12)
-- DDDDDDDDDDDDDDDDDDDDD aaaaaaaaaaaaaaaaaaaaaaaaaaaaa AAAAAAAAAAAA AAAAAAAAAAAA
-- @
--
-- date and description are shown for the first posting of a transaction only.
--
-- Returns a string which can be multi-line, eg if the running balance
-- has multiple commodities. Does not yet support formatting control
-- like balance reports.
--
postingsReportItemAsText :: CliOpts -> Int -> Int -> PostingsReportItem -> String
postingsReportItemAsText opts preferredamtwidth preferredbalwidth (mdate, menddate, mdesc, p, b) =
-- use elide*Width to be wide-char-aware
-- trace (show (totalwidth, datewidth, descwidth, acctwidth, amtwidth, balwidth)) $
intercalate "\n" $
[concat [fitString (Just datewidth) (Just datewidth) True True date
," "
,fitString (Just descwidth) (Just descwidth) True True desc
," "
,fitString (Just acctwidth) (Just acctwidth) True True acct
," "
,fitString (Just amtwidth) (Just amtwidth) True False amtfirstline
," "
,fitString (Just balwidth) (Just balwidth) True False balfirstline
]]
++
[concat [spacer
,fitString (Just amtwidth) (Just amtwidth) True False a
," "
,fitString (Just balwidth) (Just balwidth) True False b
]
| (a,b) <- zip amtrest balrest
]
where
-- calculate widths
(totalwidth,mdescwidth) = registerWidthsFromOpts opts
(datewidth, date) = case (mdate,menddate) of
(Just _, Just _) -> (21, showDateSpan (DateSpan mdate menddate))
(Nothing, Just _) -> (21, "")
(Just d, Nothing) -> (10, showDate d)
_ -> (10, "")
(amtwidth, balwidth)
| shortfall <= 0 = (preferredamtwidth, preferredbalwidth)
| otherwise = (adjustedamtwidth, adjustedbalwidth)
where
mincolwidth = 2 -- columns always show at least an ellipsis
maxamtswidth = max 0 (totalwidth - (datewidth + 1 + mincolwidth + 2 + mincolwidth + 2 + 2))
shortfall = (preferredamtwidth + preferredbalwidth) - maxamtswidth
amtwidthproportion = fromIntegral preferredamtwidth / fromIntegral (preferredamtwidth + preferredbalwidth)
adjustedamtwidth = round $ amtwidthproportion * fromIntegral maxamtswidth
adjustedbalwidth = maxamtswidth - adjustedamtwidth
remaining = totalwidth - (datewidth + 1 + 2 + amtwidth + 2 + balwidth)
(descwidth, acctwidth)
| hasinterval = (0, remaining - 2)
| otherwise = (w, remaining - 2 - w)
where
hasinterval = isJust menddate
w = fromMaybe ((remaining - 2) `div` 2) mdescwidth
-- gather content
desc = fromMaybe "" mdesc
acct = parenthesise $ T.unpack $ elideAccountName awidth $ paccount p
where
(parenthesise, awidth) =
case ptype p of
BalancedVirtualPosting -> (\s -> "["++s++"]", acctwidth-2)
VirtualPosting -> (\s -> "("++s++")", acctwidth-2)
_ -> (id,acctwidth)
amt = showMixedAmountWithoutPrice $ pamount p
bal = showMixedAmountWithoutPrice b
-- alternate behaviour, show null amounts as 0 instead of blank
-- amt = if null amt' then "0" else amt'
-- bal = if null bal' then "0" else bal'
(amtlines, ballines) = (lines amt, lines bal)
(amtlen, ballen) = (length amtlines, length ballines)
numlines = max 1 (max amtlen ballen)
(amtfirstline:amtrest) = take numlines $ amtlines ++ repeat "" -- posting amount is top-aligned
(balfirstline:balrest) = take numlines $ replicate (numlines - ballen) "" ++ ballines -- balance amount is bottom-aligned
spacer = replicate (totalwidth - (amtwidth + 2 + balwidth)) ' '
tests_Hledger_Cli_Commands_Register :: Test
tests_Hledger_Cli_Commands_Register = TestList
tests_postingsReportAsText
|
ony/hledger
|
hledger/Hledger/Cli/Commands/Register.hs
|
gpl-3.0
| 8,872
| 0
| 18
| 2,258
| 2,016
| 1,103
| 913
| 130
| 6
|
-- Eval.hs
-- Copyright 2015 Remy E. Goldschmidt <taktoa@gmail.com>
-- This file is part of HsCalculator.
-- HsCalculator is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- HsCalculator is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY-- without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with HsCalculator. If not, see <http://www.gnu.org/licenses/>.
module Eval where
import qualified Data.IntMap.Strict as IM (insert, lookup)
import qualified Data.Map.Strict as M (insert, lookup)
import Data.Maybe (fromMaybe)
import Expr
addVar :: EClosure -> Name -> Expr -> EClosure
addVar (Clsr e (addr, s) ()) n v = Clsr e' s' ()
where
addr' = addr + 1
e' = M.insert n addr' e
s' = (addr', IM.insert addr' v s)
refVar :: EClosure -> Name -> Expr
refVar (Clsr e (_, s) ()) n = fromMaybe err $ M.lookup n e >>= flip IM.lookup s
where
err = error ("Undefined variable: " ++ show n)
applyLam :: EClosure -> Name -> Expr -> Expr -> Closure
applyLam c n r v = wrap c' r
where
c' = addVar c n v
applyMu :: EClosure -> Name -> Expr -> Expr -> Closure
applyMu c n r v = wrap c' (EApp r v)
where
c' = addVar c n (EMu n r)
step' :: EClosure -> Expr -> Closure
--- Base cases for stepping arithmetic expressions
step' c (ENeg (ERat i)) = wrap c $ ERat (-i)
step' c (ERcp (ERat i)) = wrap c $ ERat (recip i)
step' c (EAdd (ERat i1) (ERat i2)) = wrap c $ ERat (i1 + i2)
step' c (EMul (ERat i1) (ERat i2)) = wrap c $ ERat (i1 * i2)
--- Base cases for booleans and conditionals
step' c (ELE (ERat i1) (ERat i2)) = wrap c $ ETF (i1 <= i2)
step' c (EIf (ETF True) e1 _) = wrap c $ e1
step' c (EIf (ETF False) _ e2) = wrap c $ e2
--- Base cases for variable lookup
step' c (ERef n) = wrap c $ refVar c n
--- Lambda application
step' c (EApp (ELam n r) v) = case v of
ERat{} -> applyLam c n r v
ETF{} -> applyLam c n r v
ELam{} -> applyLam c n r v
EMu{} -> applyLam c n r v
_ -> wrap c $ EApp (ELam n r) (fwrap c v)
--- Mu application
step' c (EApp (EMu n r) v) = case v of
ERat{} -> applyMu c n r v
ETF{} -> applyMu c n r v
ELam{} -> applyMu c n r v
EMu{} -> applyMu c n r v
_ -> wrap c $ EApp (EMu n r) (fwrap c v)
--- Strictness cases
step' c (ENeg e) = wrap c $ ENeg (fwrap c e)
step' c (ERcp e) = wrap c $ ERcp (fwrap c e)
step' c (EAdd e1 e2) = wrap c $ EAdd (fwrap c e1) (fwrap c e2)
step' c (EMul e1 e2) = wrap c $ EMul (fwrap c e1) (fwrap c e2)
step' c (ELE e1 e2) = wrap c $ ELE (fwrap c e1) (fwrap c e2)
step' c (EIf b e1 e2) = wrap c $ EIf (fwrap c b) e1 e2
step' c (EApp a v) = wrap c $ EApp (fwrap c a) v
--- Don't reduce anything that cannot be reduced
step' c e = wrap c $ e
step :: Closure -> Closure
step (Clsr e s v) = step' (Clsr e s ()) v
eval' :: Closure -> Closure
eval' i
| i == s = s
| otherwise = eval' s
where
s = step i
force :: Closure -> Expr
force = getExpr . eval'
wrap :: GClosure a -> Expr -> Closure
wrap (Clsr e s _) = Clsr e s
fwrap :: GClosure a -> Expr -> Expr
fwrap c = force . wrap c
getExpr :: Closure -> Expr
getExpr (Clsr _ _ e) = e
eval :: Expr -> Expr
eval = force . return
|
taktoa/HsCalculator
|
src/Eval.hs
|
gpl-3.0
| 4,105
| 0
| 11
| 1,457
| 1,516
| 763
| 753
| 65
| 9
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Docs (docsApp) where
import Data.Aeson (toJSON)
import Data.ByteString.Lazy (ByteString)
import Data.Monoid ((<>))
import Data.Text.Lazy (pack, toStrict, fromStrict)
import Data.Text.Lazy.Encoding (encodeUtf8)
import Database.Persist (Entity(..))
import Database.Persist.Sql (toSqlKey)
import Network.HTTP.Types.Status (ok200)
import Network.Wai (Application, responseLBS)
import Servant
import Servant.Docs
import CMark (commonmarkToHtml)
import Api
import Config
import Models
import Types
type DocsAPI = Api.API :<|> ("docs" :> Raw)
docsApp :: Config -> Application
docsApp cfg = serve docsApi $ docsReaderServer cfg
docsApi :: Proxy DocsAPI
docsApi = Proxy
docsReaderServer :: Config -> Server DocsAPI
docsReaderServer cfg = enter (readerToEither cfg) Api.server :<|> serveDocs
where serveDocs _ respond =
respond $ responseLBS ok200 [("Content-Type", "text/html")] docsBS
docsBS :: ByteString
docsBS = encodeUtf8 . renderMarkdown . pack . markdown . docsWithIntros [intro] $ pretty api
where renderMarkdown = fromStrict . commonmarkToHtml [] . toStrict
intro = DocIntro "OM Backend Docs"
[ "This is the Servant REST API Documentation for OM, the " <>
"Enlightened Order Manager."
, "Enjoy!"
]
instance ToSample () where
toSamples _ = noSamples
-- Path Documentation
instance ToCapture (Capture "id" (PKey Product)) where
toCapture _ =
DocCapture "id"
"(integer) primary key of a Product"
instance ToCapture (Capture "id" (PKey Category)) where
toCapture _ =
DocCapture "id"
"(integer) primary key of a Category"
instance ToCapture (Capture "id" (PKey ProductVariant)) where
toCapture _ =
DocCapture "id"
"(integer) primary key of a Product Variant"
-- API Examples
cat1 :: Category
cat1 = Category "TV Shows" "Stuff thats around X-Files quality." Nothing
cat2 :: Category
cat2 = Category "Vegetables" "Tables that like to vege." (Just $ toSqlKey 96)
instance ToSample (JSONObject (Entity Category)) where
toSamples _ = singleSample . JSONObject $ Entity (toSqlKey 42) cat1
instance ToSample (JSONObject Category) where
toSamples _ = singleSample $ JSONObject cat1
instance ToSample (Sideloaded (Entity Category)) where
toSamples _ = singleSample $ Sideloaded
( JSONList [Entity (toSqlKey 96) cat1, Entity (toSqlKey 42) cat2]
, toJSON $ JSONList [Entity (toSqlKey 22) prod1, Entity (toSqlKey 11) prod2]
)
prod1 :: Product
prod1 = Product "Scully's Fire Peppers" "They look like little red alien babys."
(toSqlKey 96) True False True True
prod2 :: Product
prod2 = Product "Mulder's Mad Mushrooms" "Eat enough and everyone will call you 'Spooky'."
(toSqlKey 96) True False True True
instance ToSample (JSONObject (Entity Product)) where
toSamples _ = singleSample . JSONObject $ Entity (toSqlKey 42) prod1
instance ToSample (JSONObject Product) where
toSamples _ = singleSample $ JSONObject prod1
instance ToSample (Sideloaded (Entity Product)) where
toSamples _ = singleSample $ Sideloaded
( JSONList [Entity (toSqlKey 42) prod1]
, mergeObjects (JSONList [Entity (toSqlKey 96) cat1])
(JSONList [ Entity (toSqlKey 1337) variant1
, Entity (toSqlKey 9001) variant2])
)
variant1 :: ProductVariant
variant1 = ProductVariant (toSqlKey 42) "1001A" 2500 250 30
variant2 :: ProductVariant
variant2 = ProductVariant (toSqlKey 42) "1001B" 125 750 20
instance ToSample (JSONObject ProductVariant) where
toSamples _ = singleSample $ JSONObject variant1
instance ToSample (JSONObject (Entity ProductVariant)) where
toSamples _ = singleSample . JSONObject $ Entity (toSqlKey 69) variant1
instance ToSample (Sideloaded (Entity ProductVariant)) where
toSamples _ = singleSample $ Sideloaded
( JSONList [Entity (toSqlKey 77) variant1]
, toJSON $ JSONList [Entity (toSqlKey 42) prod1]
)
|
Southern-Exposure-Seed-Exchange/Order-Manager-Prototypes
|
servant/src/Docs.hs
|
gpl-3.0
| 4,538
| 0
| 15
| 1,159
| 1,179
| 616
| 563
| 94
| 1
|
-- Simple Fay program for drawing a barnsley fern
-- values are hardcoded because I'm lazy and still
-- trying to work out how to use Fay
--
-- Robert 'Probie' Offner
import Prelude
import FFI
data IFS = IFS [(Probability, Transition)]
deriving Show
data Transition = Affine Double Double Double Double Double Double
-- | Möbius (Complex Double) (Complex Double) (Complex Double) (Complex Double)
-- Fay doesn't support complex numbers
deriving Show
type Probability = Double
buildIFS :: [(Probability, Transition)] -> IFS
buildIFS trans = IFS $ (\(x,y) -> zip (cdf x) y) $ unzip trans
where cdf [] = []
cdf (x:xs) = x : map (+ x) (cdf xs)
simulateIFS :: IFS -> (Double,Double) -> [Probability] -> [(Double,Double)]
simulateIFS _ _ [] = []
simulateIFS ifs xn (p:ps) = let xn' = applyTransition (chooseTransition p ifs) xn in
xn' : simulateIFS ifs xn' ps
koch = buildIFS $
[ (0.25, Affine (1/3) 0 0 (1/3) 0 0)
, (0.25, Affine (1/3) 0 0 (1/3) (2/3) 0)
, (0.25, Affine (1/6) (-(sqrt 3) / 6) ((sqrt 3) / 6) (1/6) (1/3) 0)
, (0.25, Affine (1/6) ((sqrt 3) / 6) (-(sqrt 3) / 6) (1/6) (0.5) (sqrt 3 / 6))
]
chooseTransition :: Probability -> IFS -> Transition
chooseTransition p (IFS x) = chooseTransition' p x
chooseTransition' _ [(_,x)] = x
chooseTransition' p ((p',x):xs) = if p <= p' then x else chooseTransition' p xs
applyTransition :: Transition -> (Double,Double) -> (Double,Double)
applyTransition (Affine a b c d e f) (x,y) = (a*x + b*y + e, c*x + d*y + f)
randDouble :: Fay Double
randDouble = ffi "Math.random()"
main = do
x <- newRef 0
y <- newRef 0
setFillStyle "#000000"
ffi "document.getElementById(\"fractal\").getContext(\"2d\").fillRect(0,0, 800, 600)" :: Fay ()
setFillStyle "#FFFFFF"
setInterval 400 (drawStuff 30 x y )
drawStuff :: Int -> Ref Double -> Ref Double -> Fay ()
drawStuff 0 x y = return ()
drawStuff n x y = do
p <- randDouble
xval <- readRef x
yval <- readRef y
let (x', y') = applyTransition (chooseTransition p koch) (xval, yval)
drawDot x' y'
let x'' = (x' * (-0.5) - (0.5 * ((sqrt 3) * y'))) + 0.5
let y'' = ((sqrt 3) * x' * 0.5 - (y'/2)) - (sqrt 3) /2
drawDot x'' y''
drawDot (1 - x'') y''
writeRef x x'
writeRef y y'
drawStuff (n-1) x y
drawDot :: Double -> Double -> Fay ()
drawDot = ffi "document.getElementById(\"fractal\").getContext(\"2d\").fillRect((%1)*400 + 200, 200 - %2 * 400, 1, 1)"
setFillStyle :: String -> Fay ()
setFillStyle = ffi "document.getElementById(\"fractal\").getContext(\"2d\").fillStyle=%1"
setInterval :: Int -> Fay () -> Fay ()
setInterval = ffi "setInterval(%2,%1)"
-- Refs
-- This will be provided in the fay package by default.
data Canvas
data Context
data Ref a
instance Show (Ref a)
newRef :: a -> Fay (Ref a)
newRef = ffi "new Fay$$Ref(%1)"
writeRef :: Ref a -> a -> Fay ()
writeRef = ffi "Fay$$writeRef(%1,%2)"
readRef :: Ref a -> Fay a
readRef = ffi "Fay$$readRef(%1)"
|
LudvikGalois/Fay-IFS
|
Snowflake.hs
|
gpl-3.0
| 3,106
| 0
| 18
| 768
| 1,252
| 650
| 602
| -1
| -1
|
{-# LANGUAGE OverloadedStrings #-}
module SimpleRequestTest where
import Data.ByteString.Char8 ( ByteString )
import qualified Data.ByteString.Char8 as BS
import Data.Maybe
import Network.HTTP
import Network.URI
import Test.HUnit
makeRequest :: String -> Request ByteString
makeRequest url =
Request { rqURI = fromJust (parseURI url)
, rqMethod = GET
, rqHeaders = []
, rqBody = "" }
testSimpleRequest :: Assertion
testSimpleRequest = do
res <- simpleHTTP (makeRequest "http://localhost:5000/Naive.hs")
case res of
Left err -> do
error (show err)
Right rsp -> do
text <- BS.readFile "Naive.hs"
rspBody rsp @?= text
|
scvalex/dissemina2
|
Test/SimpleRequestTest.hs
|
gpl-3.0
| 710
| 0
| 14
| 182
| 187
| 100
| 87
| 23
| 2
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.TagManager.Accounts.Containers.Workspaces.Folders.Delete
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Deletes a GTM Folder.
--
-- /See:/ <https://developers.google.com/tag-manager Tag Manager API Reference> for @tagmanager.accounts.containers.workspaces.folders.delete@.
module Network.Google.Resource.TagManager.Accounts.Containers.Workspaces.Folders.Delete
(
-- * REST Resource
AccountsContainersWorkspacesFoldersDeleteResource
-- * Creating a Request
, accountsContainersWorkspacesFoldersDelete
, AccountsContainersWorkspacesFoldersDelete
-- * Request Lenses
, acwfdXgafv
, acwfdUploadProtocol
, acwfdPath
, acwfdAccessToken
, acwfdUploadType
, acwfdCallback
) where
import Network.Google.Prelude
import Network.Google.TagManager.Types
-- | A resource alias for @tagmanager.accounts.containers.workspaces.folders.delete@ method which the
-- 'AccountsContainersWorkspacesFoldersDelete' request conforms to.
type AccountsContainersWorkspacesFoldersDeleteResource
=
"tagmanager" :>
"v2" :>
Capture "path" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :> Delete '[JSON] ()
-- | Deletes a GTM Folder.
--
-- /See:/ 'accountsContainersWorkspacesFoldersDelete' smart constructor.
data AccountsContainersWorkspacesFoldersDelete =
AccountsContainersWorkspacesFoldersDelete'
{ _acwfdXgafv :: !(Maybe Xgafv)
, _acwfdUploadProtocol :: !(Maybe Text)
, _acwfdPath :: !Text
, _acwfdAccessToken :: !(Maybe Text)
, _acwfdUploadType :: !(Maybe Text)
, _acwfdCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'AccountsContainersWorkspacesFoldersDelete' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'acwfdXgafv'
--
-- * 'acwfdUploadProtocol'
--
-- * 'acwfdPath'
--
-- * 'acwfdAccessToken'
--
-- * 'acwfdUploadType'
--
-- * 'acwfdCallback'
accountsContainersWorkspacesFoldersDelete
:: Text -- ^ 'acwfdPath'
-> AccountsContainersWorkspacesFoldersDelete
accountsContainersWorkspacesFoldersDelete pAcwfdPath_ =
AccountsContainersWorkspacesFoldersDelete'
{ _acwfdXgafv = Nothing
, _acwfdUploadProtocol = Nothing
, _acwfdPath = pAcwfdPath_
, _acwfdAccessToken = Nothing
, _acwfdUploadType = Nothing
, _acwfdCallback = Nothing
}
-- | V1 error format.
acwfdXgafv :: Lens' AccountsContainersWorkspacesFoldersDelete (Maybe Xgafv)
acwfdXgafv
= lens _acwfdXgafv (\ s a -> s{_acwfdXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
acwfdUploadProtocol :: Lens' AccountsContainersWorkspacesFoldersDelete (Maybe Text)
acwfdUploadProtocol
= lens _acwfdUploadProtocol
(\ s a -> s{_acwfdUploadProtocol = a})
-- | GTM Folder\'s API relative path. Example:
-- accounts\/{account_id}\/containers\/{container_id}\/workspaces\/{workspace_id}\/folders\/{folder_id}
acwfdPath :: Lens' AccountsContainersWorkspacesFoldersDelete Text
acwfdPath
= lens _acwfdPath (\ s a -> s{_acwfdPath = a})
-- | OAuth access token.
acwfdAccessToken :: Lens' AccountsContainersWorkspacesFoldersDelete (Maybe Text)
acwfdAccessToken
= lens _acwfdAccessToken
(\ s a -> s{_acwfdAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
acwfdUploadType :: Lens' AccountsContainersWorkspacesFoldersDelete (Maybe Text)
acwfdUploadType
= lens _acwfdUploadType
(\ s a -> s{_acwfdUploadType = a})
-- | JSONP
acwfdCallback :: Lens' AccountsContainersWorkspacesFoldersDelete (Maybe Text)
acwfdCallback
= lens _acwfdCallback
(\ s a -> s{_acwfdCallback = a})
instance GoogleRequest
AccountsContainersWorkspacesFoldersDelete
where
type Rs AccountsContainersWorkspacesFoldersDelete =
()
type Scopes AccountsContainersWorkspacesFoldersDelete
=
'["https://www.googleapis.com/auth/tagmanager.edit.containers"]
requestClient
AccountsContainersWorkspacesFoldersDelete'{..}
= go _acwfdPath _acwfdXgafv _acwfdUploadProtocol
_acwfdAccessToken
_acwfdUploadType
_acwfdCallback
(Just AltJSON)
tagManagerService
where go
= buildClient
(Proxy ::
Proxy
AccountsContainersWorkspacesFoldersDeleteResource)
mempty
|
brendanhay/gogol
|
gogol-tagmanager/gen/Network/Google/Resource/TagManager/Accounts/Containers/Workspaces/Folders/Delete.hs
|
mpl-2.0
| 5,459
| 0
| 16
| 1,168
| 706
| 413
| 293
| 109
| 1
|
module Game.Toliman.Internal.Lens (
module Control.Lens,
use,
assign, (.=),
(%=),
access,
store, (.*=),
(%*=),
accessPrism
) where
import Data.Monoid as Monoid (First)
import Data.Functor ((<$>))
import Monad.State as State (MonadState(..), gets, modify)
import Control.Lens hiding (use, assign, (.=), (%=))
import Monad.Ref (MonadRef(..), modifyRef)
use :: MonadState s m => Getting a s a -> m a
use l = gets $ view l
assign :: (MonadState s m, Functor m) => ASetter s s a b -> b -> m ()
assign l b = State.modify (l .~ b)
(.=) :: (MonadState s m, Functor m) => ASetter s s a b -> b -> m ()
(.=) = assign
(%=) :: (Profunctor p, MonadState s m) => Setting p s s a b -> p a b -> m ()
l %= f = State.modify (l %~ f)
access :: (MonadRef s m) => Getting a s a -> m a
access l = (^. l) <$> getRef
store :: (MonadRef s m) => ASetter s s a b -> b -> m ()
store l b = modifyRef (l .~ b)
(.*=) :: (MonadRef s m) => ASetter s s a b -> b -> m ()
(.*=) = store
(%*=) :: (Profunctor p, MonadRef s m) => Setting p s s a b -> p a b -> m ()
l %*= f = modifyRef (l %~ f)
accessPrism :: (MonadRef s m) => Getting (Monoid.First a) s a -> m (Maybe a)
accessPrism l = (^? l) <$> getRef
|
duncanburke/toliman-core
|
src/Game/Toliman/Internal/Lens.hs
|
mpl-2.0
| 1,196
| 0
| 10
| 283
| 661
| 363
| 298
| 32
| 1
|
{-# LANGUAGE GADTs, KindSignatures, DeriveDataTypeable,
FlexibleInstances, ConstraintKinds,
PatternGuards, TemplateHaskell #-}
module EnvTypes where
import Nat
import Data.Function (on)
import Data.Typeable (Typeable)
import Test.QuickCheck
import Test.Feat
type EqShow a = (Eq a,Show a,Arbitrary a)
data Sigma :: (* -> *) -> * where
Si :: EqShow a => r a -> Sigma r
data Exists :: (* -> *) -> * where
Val :: EqShow a => r a -> a -> Exists r
type Repr' = Exists Repr
type Ty' = Sigma Repr
-- Representations of our types.
-- Putting Eq and Show here simplifies those instances for Repr a bit
data Repr a where
Unit :: Repr ()
Nat :: Repr Nat
PInt :: Repr PInt
Bool :: Repr Bool
List :: EqShow a => Repr a -> Repr [a]
Maybe :: EqShow a => Repr a -> Repr (Maybe a)
TupTy :: (EqShow a,EqShow b) => Repr a -> Repr b -> Repr (a,b)
TyVar :: Repr Int
-- ^ Should this contain more information?
deriving Typeable
-- The more number of units, the more boring this type is to test
data URepr
= UUnit () () ()
| UNat
| UPInt
| UBool () ()
| UList URepr
| UMaybe URepr ()
| UTupTy URepr URepr ()
| UTyVar () () ()
deriving Typeable
deriveEnumerable ''URepr
toTy :: URepr -> Ty'
toTy u = case u of
UUnit{} -> Si Unit
UNat -> Si Nat
UPInt -> Si PInt
UBool{} -> Si Bool
UList a | Si a' <- toTy a -> Si (List a')
UMaybe a _ | Si a' <- toTy a -> Si (Maybe a')
UTupTy a b _ | Si a' <- toTy a
, Si b' <- toTy b -> Si (TupTy a' b')
UTyVar{} -> Si TyVar
enumTy' :: Enumerate Ty'
enumTy' = fmap toTy enumerate
{-# ANN enumTy's "HLint: ignore Use camelCase" #-}
enumTy's :: Enumerate [Ty']
enumTy's = fmap (map toTy) enumerate
showRepr :: Repr a -> String
showRepr r = case r of
Unit -> "Unit"
Nat -> "Nat"
PInt -> "PInt"
Bool -> "Bool"
List a -> "List " ++ showRepr a
Maybe a -> "Maybe " ++ showRepr a
TupTy a b -> "TupTy " ++ showRepr a ++ " " ++ showRepr b
TyVar -> "TyVar"
showRepr' :: Repr' -> String
showRepr' (Val r x) = "Val " ++ showRepr r ++ " " ++ show x
instance Show Ty' where
show (Si r) = case r of
Unit -> "()"
Nat -> "Nat"
PInt -> "Int"
Bool -> "Bool"
List a -> "[" ++ show (Si a) ++ "]"
Maybe a -> "Maybe " ++ show (Si a)
TupTy a b -> "(" ++ show (Si a) ++ "," ++ show (Si b) ++ ")"
TyVar -> "a"
type Con' = Sigma Con
data Con a where
TT :: Con ()
Zero :: Con Nat
Succ :: Con Nat
Pos :: Con PInt
Neg :: Con PInt
Tru :: Con Bool
Fls :: Con Bool
Nil :: EqShow a => Repr a -> Con [a]
Cons :: Con [a]
Jst :: Con (Maybe a)
Ntng :: EqShow a => Repr a -> Con (Maybe a)
Tup :: Con (a,b)
infoCon' :: Con' -> (Int,String)
infoCon' c = case c of
Si TT -> (0,"()")
Si Zero -> (1,"Zero")
Si Succ -> (2,"Succ")
Si Nil{} -> (3,"Nil")
Si Cons -> (4,"Cons")
Si Pos -> (5,"Pos")
Si Neg -> (6,"Neg")
Si Jst -> (7,"Just")
Si Ntng{} -> (8,"Nothing")
Si Tru -> (9,"True")
Si Fls -> (10,"False")
Si Tup -> (11,"Tup")
instance Eq Con' where
(==) = (==) `on` (fst . infoCon')
instance Ord Con' where
compare = compare `on` (fst . infoCon')
instance Show Con' where
show = snd . infoCon'
instance Show (Exists a) where
show (Val _ x) = show x
shrinkRepr' :: Repr' -> [Repr']
shrinkRepr' (Val r x) = map (Val r) (shrink x)
data Equal :: * -> * -> * where
Refl :: Equal a a
(==?) :: Repr a -> Repr b -> Maybe (Equal a b)
Unit ==? Unit = Just Refl
Nat ==? Nat = Just Refl
PInt ==? PInt = Just Refl
Bool ==? Bool = Just Refl
TyVar ==? TyVar = Just Refl
Maybe a ==? Maybe b | Just Refl <- a ==? b = Just Refl
List a ==? List b | Just Refl <- a ==? b = Just Refl
TupTy a u ==? TupTy b v | Just Refl <- a ==? b
, Just Refl <- u ==? v = Just Refl
_ ==? _ = Nothing
instance Eq (Exists Repr) where
Val s u == Val t v = case s ==? t of
Just Refl -> u == v
Nothing -> False
|
danr/structural-induction
|
test/EnvTypes.hs
|
lgpl-3.0
| 4,261
| 95
| 9
| 1,423
| 1,783
| 906
| 877
| 130
| 12
|
module List where
import Prelude hiding (Fractional, Functor, fmap)
import Functor
data List a = Nil | Cons a (List a) deriving (Read, Show)
data Fractional = Fraction Int Int
|
SPbAU-ProgrammingParadigms/materials
|
haskell_2/List.hs
|
unlicense
| 178
| 0
| 8
| 32
| 65
| 39
| 26
| 5
| 0
|
-----------------------------------------------------------------------------
-- |
-- Module : Point
-- License : Unlicense
--
-- Maintainer : mail@johannesewald.de
-- Stability : unstable
-- Portability : portable
--
-- The Point data type.
--
-----------------------------------------------------------------------------
module Point (
Point
) where
{-|
A tuple of x and y which describe a point in a 2-dimensional space.
-}
type Point = (Float, Float)
|
jhnns/haskell-experiments
|
src/Point.hs
|
unlicense
| 486
| 0
| 5
| 90
| 34
| 27
| 7
| 3
| 0
|
module Git.Command.ShSetup (run) where
run :: [String] -> IO ()
run args = return ()
|
wereHamster/yag
|
Git/Command/ShSetup.hs
|
unlicense
| 85
| 0
| 7
| 15
| 42
| 23
| 19
| 3
| 1
|
{- |
Module : Codec.Goat.ValueFrame.Decode
Description : Value decompression
Copyright : (c) Daniel Lovasko, 2016-2017
License : BSD3
Maintainer : Daniel Lovasko <daniel.lovasko@gmail.com>
Stability : stable
Portability : portable
Decoding of the compressed frame form into raw value points.
-}
module Codec.Goat.ValueFrame.Decode
( valueDecode
) where
import Data.Bits
import Data.Bits.Floating
import Data.List
import Data.List.Split
import Data.Word
import qualified Data.ByteString as B
import Codec.Goat.ValueFrame.Types
import Codec.Goat.Util
-- | Helper type to hold the decoding context.
type Context = ([Bool], (Int, Int)) -- ^ available bits & bounds
-- | Unpack value points from the succinct frame.
valueDecode :: ValueFrame -- ^ succinct frame form
-> [Float] -- ^ value points
valueDecode (ValueFrame Nothing _ _ ) = []
valueDecode (ValueFrame (Just x) len bs)
| B.null bs || len == 0 = [coerceToFloat x]
| otherwise = map coerceToFloat (x:xors)
where
xors = drop 1 $ scanl xor x ws :: [Word32]
ws = unfoldr decode (bits, (16, 16)) :: [Word32]
bits = genericTake len (unpackBits bs) :: [Bool]
-- | Decode a single XORed value.
decode :: Context -- ^ current context
-> Maybe (Word32, Context) -- ^ decoded value & new context
decode (False:xs, bounds) = Just (0, (xs, bounds))
decode (True:False:xs, bounds) = Just $ inside bounds xs
decode (True:True:xs, _ ) = Just $ outside xs
decode (_, _ ) = Nothing
-- | Handling of the within-bounds decoding case.
inside :: (Int, Int) -- ^ current bounds
-> [Bool] -- ^ bits
-> (Word32, Context) -- ^ decoded number & context
inside bounds@(lead, trail) xs = (fromBools number, (ys, bounds))
where
number = surround (lead, trail) bits
(bits, ys) = splitAt (32 - lead - trail) xs
-- | Handling of the out-of-bounds decoding case.
outside :: [Bool] -- ^ bits
-> (Word32, Context) -- ^ decoded number & context
outside xs = (fromBools number, (ys, (lead, trail)))
where
[lead, size] = map fromBools $ splitPlaces ([5, 6] :: [Int]) xs
trail = 32 - lead - size
number = surround (lead, trail) bits
(bits, ys) = splitAt size (drop 11 xs)
-- | Surround a list of bools with False elements.
surround :: (Int, Int) -- ^ leading and trailing count
-> [Bool] -- ^ old list
-> [Bool] -- ^ new list
surround (lead, trail) = (replicate lead False ++) . (++ replicate trail False)
|
lovasko/goat
|
src/Codec/Goat/ValueFrame/Decode.hs
|
bsd-2-clause
| 2,578
| 0
| 11
| 648
| 717
| 413
| 304
| 43
| 1
|
-----------------------------------------------------------------------------
-- |
-- Module : Haddock.Backends.Html
-- Copyright : (c) Simon Marlow 2003-2006,
-- David Waern 2006-2009,
-- Mark Lentczner 2010,
-- Mateusz Kowalczyk 2013
-- License : BSD-like
--
-- Maintainer : haddock@projects.haskell.org
-- Stability : experimental
-- Portability : portable
-----------------------------------------------------------------------------
{-# LANGUAGE CPP #-}
module Haddock.Backends.Xhtml (
ppHtml, copyHtmlBits,
ppHtmlIndex, ppHtmlContents,
) where
import Prelude hiding (div)
import Haddock.Backends.Xhtml.Decl
import Haddock.Backends.Xhtml.DocMarkup
import Haddock.Backends.Xhtml.Layout
import Haddock.Backends.Xhtml.Names
import Haddock.Backends.Xhtml.Themes
import Haddock.Backends.Xhtml.Types
import Haddock.Backends.Xhtml.Utils
import Haddock.ModuleTree
import Haddock.Types
import Haddock.Version
import Haddock.Utils
import Text.XHtml hiding ( name, title, p, quote )
import Haddock.GhcUtils
import Control.Monad ( when, unless )
import Data.Char ( toUpper )
import Data.List ( sortBy, groupBy, intercalate, isPrefixOf )
import Data.Maybe
import System.FilePath hiding ( (</>) )
import System.Directory
import Data.Map ( Map )
import qualified Data.Map as Map hiding ( Map )
import qualified Data.Set as Set hiding ( Set )
import Data.Function
import Data.Ord ( comparing )
import DynFlags (Language(..))
import GHC hiding ( NoLink, moduleInfo )
import Name
import Module
--------------------------------------------------------------------------------
-- * Generating HTML documentation
--------------------------------------------------------------------------------
ppHtml :: DynFlags
-> String -- ^ Title
-> Maybe String -- ^ Package
-> [Interface]
-> FilePath -- ^ Destination directory
-> Maybe (MDoc GHC.RdrName) -- ^ Prologue text, maybe
-> Themes -- ^ Themes
-> Maybe String -- ^ The mathjax URL (--mathjax)
-> SourceURLs -- ^ The source URL (--source)
-> WikiURLs -- ^ The wiki URL (--wiki)
-> Maybe String -- ^ The contents URL (--use-contents)
-> Maybe String -- ^ The index URL (--use-index)
-> Bool -- ^ Whether to use unicode in output (--use-unicode)
-> QualOption -- ^ How to qualify names
-> Bool -- ^ Output pretty html (newlines and indenting)
-> IO ()
ppHtml dflags doctitle maybe_package ifaces odir prologue
themes maybe_mathjax_url maybe_source_url maybe_wiki_url
maybe_contents_url maybe_index_url unicode
qual debug = do
let
visible_ifaces = filter visible ifaces
visible i = OptHide `notElem` ifaceOptions i
when (isNothing maybe_contents_url) $
ppHtmlContents dflags odir doctitle maybe_package
themes maybe_mathjax_url maybe_index_url maybe_source_url maybe_wiki_url
(map toInstalledIface visible_ifaces)
False -- we don't want to display the packages in a single-package contents
prologue debug (makeContentsQual qual)
when (isNothing maybe_index_url) $
ppHtmlIndex odir doctitle maybe_package
themes maybe_contents_url maybe_source_url maybe_wiki_url
(map toInstalledIface visible_ifaces) debug
mapM_ (ppHtmlModule odir doctitle themes
maybe_source_url maybe_wiki_url
maybe_contents_url maybe_index_url unicode qual debug) visible_ifaces
copyHtmlBits :: FilePath -> FilePath -> Themes -> IO ()
copyHtmlBits odir libdir themes = do
let
libhtmldir = joinPath [libdir, "html"]
copyCssFile f = copyFile f (combine odir (takeFileName f))
copyLibFile f = copyFile (joinPath [libhtmldir, f]) (joinPath [odir, f])
mapM_ copyCssFile (cssFiles themes)
mapM_ copyLibFile [ jsFile, framesFile ]
headHtml :: String -> Maybe String -> Themes -> Maybe String -> Html
headHtml docTitle miniPage themes mathjax_url =
header << [
meta ! [httpequiv "Content-Type", content "text/html; charset=UTF-8"],
thetitle << docTitle,
styleSheet themes,
script ! [src jsFile, thetype "text/javascript"] << noHtml,
script ! [src mjUrl, thetype "text/javascript"] << noHtml,
script ! [thetype "text/javascript"]
-- NB: Within XHTML, the content of script tags needs to be
-- a <![CDATA[ section. Will break if the miniPage name could
-- have "]]>" in it!
<< primHtml (
"//<![CDATA[\nwindow.onload = function () {pageLoad();"
++ setSynopsis ++ "};\n//]]>\n")
]
where
setSynopsis = maybe "" (\p -> "setSynopsis(\"" ++ p ++ "\");") miniPage
mjUrl = maybe "https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML" id mathjax_url
srcButton :: SourceURLs -> Maybe Interface -> Maybe Html
srcButton (Just src_base_url, _, _, _) Nothing =
Just (anchor ! [href src_base_url] << "Source")
srcButton (_, Just src_module_url, _, _) (Just iface) =
let url = spliceURL (Just $ ifaceOrigFilename iface)
(Just $ ifaceMod iface) Nothing Nothing src_module_url
in Just (anchor ! [href url] << "Source")
srcButton _ _ =
Nothing
wikiButton :: WikiURLs -> Maybe Module -> Maybe Html
wikiButton (Just wiki_base_url, _, _) Nothing =
Just (anchor ! [href wiki_base_url] << "User Comments")
wikiButton (_, Just wiki_module_url, _) (Just mdl) =
let url = spliceURL Nothing (Just mdl) Nothing Nothing wiki_module_url
in Just (anchor ! [href url] << "User Comments")
wikiButton _ _ =
Nothing
contentsButton :: Maybe String -> Maybe Html
contentsButton maybe_contents_url
= Just (anchor ! [href url] << "Contents")
where url = fromMaybe contentsHtmlFile maybe_contents_url
indexButton :: Maybe String -> Maybe Html
indexButton maybe_index_url
= Just (anchor ! [href url] << "Index")
where url = fromMaybe indexHtmlFile maybe_index_url
bodyHtml :: String -> Maybe Interface
-> SourceURLs -> WikiURLs
-> Maybe String -> Maybe String
-> Html -> Html
bodyHtml doctitle iface
maybe_source_url maybe_wiki_url
maybe_contents_url maybe_index_url
pageContent =
body << [
divPackageHeader << [
unordList (catMaybes [
srcButton maybe_source_url iface,
wikiButton maybe_wiki_url (ifaceMod <$> iface),
contentsButton maybe_contents_url,
indexButton maybe_index_url])
! [theclass "links", identifier "page-menu"],
nonEmptySectionName << doctitle
],
divContent << pageContent,
divFooter << paragraph << (
"Produced by " +++
(anchor ! [href projectUrl] << toHtml projectName) +++
(" version " ++ projectVersion)
)
]
moduleInfo :: Interface -> Html
moduleInfo iface =
let
info = ifaceInfo iface
doOneEntry :: (String, HaddockModInfo GHC.Name -> Maybe String) -> Maybe HtmlTable
doOneEntry (fieldName, field) =
field info >>= \a -> return (th << fieldName <-> td << a)
entries :: [HtmlTable]
entries = mapMaybe doOneEntry [
("Copyright",hmi_copyright),
("License",hmi_license),
("Maintainer",hmi_maintainer),
("Stability",hmi_stability),
("Portability",hmi_portability),
("Safe Haskell",hmi_safety),
("Language", lg)
] ++ extsForm
where
lg inf = case hmi_language inf of
Nothing -> Nothing
Just Haskell98 -> Just "Haskell98"
Just Haskell2010 -> Just "Haskell2010"
extsForm
| OptShowExtensions `elem` ifaceOptions iface =
let fs = map (dropOpt . show) (hmi_extensions info)
in case map stringToHtml fs of
[] -> []
[x] -> extField x -- don't use a list for a single extension
xs -> extField $ unordList xs ! [theclass "extension-list"]
| otherwise = []
where
extField x = return $ th << "Extensions" <-> td << x
dropOpt x = if "Opt_" `isPrefixOf` x then drop 4 x else x
in
case entries of
[] -> noHtml
_ -> table ! [theclass "info"] << aboves entries
--------------------------------------------------------------------------------
-- * Generate the module contents
--------------------------------------------------------------------------------
ppHtmlContents
:: DynFlags
-> FilePath
-> String
-> Maybe String
-> Themes
-> Maybe String
-> Maybe String
-> SourceURLs
-> WikiURLs
-> [InstalledInterface] -> Bool -> Maybe (MDoc GHC.RdrName)
-> Bool
-> Qualification -- ^ How to qualify names
-> IO ()
ppHtmlContents dflags odir doctitle _maybe_package
themes mathjax_url maybe_index_url
maybe_source_url maybe_wiki_url ifaces showPkgs prologue debug qual = do
let tree = mkModuleTree dflags showPkgs
[(instMod iface, toInstalledDescription iface) | iface <- ifaces]
html =
headHtml doctitle Nothing themes mathjax_url +++
bodyHtml doctitle Nothing
maybe_source_url maybe_wiki_url
Nothing maybe_index_url << [
ppPrologue qual doctitle prologue,
ppModuleTree qual tree
]
createDirectoryIfMissing True odir
writeFile (joinPath [odir, contentsHtmlFile]) (renderToString debug html)
-- XXX: think of a better place for this?
ppHtmlContentsFrame odir doctitle themes ifaces debug
ppPrologue :: Qualification -> String -> Maybe (MDoc GHC.RdrName) -> Html
ppPrologue _ _ Nothing = noHtml
ppPrologue qual title (Just doc) =
divDescription << (h1 << title +++ docElement thediv (rdrDocToHtml qual doc))
ppModuleTree :: Qualification -> [ModuleTree] -> Html
ppModuleTree qual ts =
divModuleList << (sectionName << "Modules" +++ mkNodeList qual [] "n" ts)
mkNodeList :: Qualification -> [String] -> String -> [ModuleTree] -> Html
mkNodeList qual ss p ts = case ts of
[] -> noHtml
_ -> unordList (zipWith (mkNode qual ss) ps ts)
where
ps = [ p ++ '.' : show i | i <- [(1::Int)..]]
mkNode :: Qualification -> [String] -> String -> ModuleTree -> Html
mkNode qual ss p (Node s leaf pkg srcPkg short ts) =
htmlModule <+> shortDescr +++ htmlPkg +++ subtree
where
modAttrs = case (ts, leaf) of
(_:_, False) -> collapseControl p True "module"
(_, _ ) -> [theclass "module"]
cBtn = case (ts, leaf) of
(_:_, True) -> thespan ! collapseControl p True "" << spaceHtml
(_, _ ) -> noHtml
-- We only need an explicit collapser button when the module name
-- is also a leaf, and so is a link to a module page. Indeed, the
-- spaceHtml is a minor hack and does upset the layout a fraction.
htmlModule = thespan ! modAttrs << (cBtn +++
if leaf
then ppModule (mkModule (stringToUnitId (fromMaybe "" pkg))
(mkModuleName mdl))
else toHtml s
)
mdl = intercalate "." (reverse (s:ss))
shortDescr = maybe noHtml (origDocToHtml qual) short
htmlPkg = maybe noHtml (thespan ! [theclass "package"] <<) srcPkg
subtree = mkNodeList qual (s:ss) p ts ! collapseSection p True ""
-- | Turn a module tree into a flat list of full module names. E.g.,
-- @
-- A
-- +-B
-- +-C
-- @
-- becomes
-- @["A", "A.B", "A.B.C"]@
flatModuleTree :: [InstalledInterface] -> [Html]
flatModuleTree ifaces =
map (uncurry ppModule' . head)
. groupBy ((==) `on` fst)
. sortBy (comparing fst)
$ mods
where
mods = [ (moduleString mdl, mdl) | mdl <- map instMod ifaces ]
ppModule' txt mdl =
anchor ! [href (moduleHtmlFile mdl), target mainFrameName]
<< toHtml txt
ppHtmlContentsFrame :: FilePath -> String -> Themes
-> [InstalledInterface] -> Bool -> IO ()
ppHtmlContentsFrame odir doctitle themes ifaces debug = do
let mods = flatModuleTree ifaces
html =
headHtml doctitle Nothing themes Nothing +++
miniBody << divModuleList <<
(sectionName << "Modules" +++
ulist << [ li ! [theclass "module"] << m | m <- mods ])
createDirectoryIfMissing True odir
writeFile (joinPath [odir, frameIndexHtmlFile]) (renderToString debug html)
--------------------------------------------------------------------------------
-- * Generate the index
--------------------------------------------------------------------------------
ppHtmlIndex :: FilePath
-> String
-> Maybe String
-> Themes
-> Maybe String
-> SourceURLs
-> WikiURLs
-> [InstalledInterface]
-> Bool
-> IO ()
ppHtmlIndex odir doctitle _maybe_package themes
maybe_contents_url maybe_source_url maybe_wiki_url ifaces debug = do
let html = indexPage split_indices Nothing
(if split_indices then [] else index)
createDirectoryIfMissing True odir
when split_indices $ do
mapM_ (do_sub_index index) initialChars
-- Let's add a single large index as well for those who don't know exactly what they're looking for:
let mergedhtml = indexPage False Nothing index
writeFile (joinPath [odir, subIndexHtmlFile merged_name]) (renderToString debug mergedhtml)
writeFile (joinPath [odir, indexHtmlFile]) (renderToString debug html)
where
indexPage showLetters ch items =
headHtml (doctitle ++ " (" ++ indexName ch ++ ")") Nothing themes Nothing +++
bodyHtml doctitle Nothing
maybe_source_url maybe_wiki_url
maybe_contents_url Nothing << [
if showLetters then indexInitialLetterLinks else noHtml,
if null items then noHtml else
divIndex << [sectionName << indexName ch, buildIndex items]
]
indexName ch = "Index" ++ maybe "" (\c -> " - " ++ [c]) ch
merged_name = "All"
buildIndex items = table << aboves (map indexElt items)
-- an arbitrary heuristic:
-- too large, and a single-page will be slow to load
-- too small, and we'll have lots of letter-indexes with only one
-- or two members in them, which seems inefficient or
-- unnecessarily hard to use.
split_indices = length index > 150
indexInitialLetterLinks =
divAlphabet <<
unordList (map (\str -> anchor ! [href (subIndexHtmlFile str)] << str) $
[ [c] | c <- initialChars
, any ((==c) . toUpper . head . fst) index ] ++
[merged_name])
-- todo: what about names/operators that start with Unicode
-- characters?
-- Exports beginning with '_' can be listed near the end,
-- presumably they're not as important... but would be listed
-- with non-split index!
initialChars = [ 'A'..'Z' ] ++ ":!#$%&*+./<=>?@\\^|-~" ++ "_"
do_sub_index this_ix c
= unless (null index_part) $
writeFile (joinPath [odir, subIndexHtmlFile [c]]) (renderToString debug html)
where
html = indexPage True (Just c) index_part
index_part = [(n,stuff) | (n,stuff) <- this_ix, toUpper (head n) == c]
index :: [(String, Map GHC.Name [(Module,Bool)])]
index = sortBy cmp (Map.toAscList full_index)
where cmp (n1,_) (n2,_) = comparing (map toUpper) n1 n2
-- for each name (a plain string), we have a number of original HsNames that
-- it can refer to, and for each of those we have a list of modules
-- that export that entity. Each of the modules exports the entity
-- in a visible or invisible way (hence the Bool).
full_index :: Map String (Map GHC.Name [(Module,Bool)])
full_index = Map.fromListWith (flip (Map.unionWith (++)))
(concatMap getIfaceIndex ifaces)
getIfaceIndex iface =
[ (getOccString name
, Map.fromList [(name, [(mdl, name `Set.member` visible)])])
| name <- instExports iface ]
where
mdl = instMod iface
visible = Set.fromList (instVisibleExports iface)
indexElt :: (String, Map GHC.Name [(Module,Bool)]) -> HtmlTable
indexElt (str, entities) =
case Map.toAscList entities of
[(nm,entries)] ->
td ! [ theclass "src" ] << toHtml str <->
indexLinks nm entries
many_entities ->
td ! [ theclass "src" ] << toHtml str <-> td << spaceHtml </>
aboves (zipWith (curry doAnnotatedEntity) [1..] many_entities)
doAnnotatedEntity :: (Integer, (Name, [(Module, Bool)])) -> HtmlTable
doAnnotatedEntity (j,(nm,entries))
= td ! [ theclass "alt" ] <<
toHtml (show j) <+> parens (ppAnnot (nameOccName nm)) <->
indexLinks nm entries
ppAnnot n | not (isValOcc n) = toHtml "Type/Class"
| isDataOcc n = toHtml "Data Constructor"
| otherwise = toHtml "Function"
indexLinks nm entries =
td ! [ theclass "module" ] <<
hsep (punctuate comma
[ if visible then
linkId mdl (Just nm) << toHtml (moduleString mdl)
else
toHtml (moduleString mdl)
| (mdl, visible) <- entries ])
--------------------------------------------------------------------------------
-- * Generate the HTML page for a module
--------------------------------------------------------------------------------
ppHtmlModule
:: FilePath -> String -> Themes
-> SourceURLs -> WikiURLs
-> Maybe String -> Maybe String -> Bool -> QualOption
-> Bool -> Interface -> IO ()
ppHtmlModule odir doctitle themes
maybe_source_url maybe_wiki_url
maybe_contents_url maybe_index_url unicode qual debug iface = do
let
mdl = ifaceMod iface
aliases = ifaceModuleAliases iface
mdl_str = moduleString mdl
real_qual = makeModuleQual qual aliases mdl
html =
headHtml mdl_str (Just $ "mini_" ++ moduleHtmlFile mdl) themes Nothing +++
bodyHtml doctitle (Just iface)
maybe_source_url maybe_wiki_url
maybe_contents_url maybe_index_url << [
divModuleHeader << (moduleInfo iface +++ (sectionName << mdl_str)),
ifaceToHtml maybe_source_url maybe_wiki_url iface unicode real_qual
]
createDirectoryIfMissing True odir
writeFile (joinPath [odir, moduleHtmlFile mdl]) (renderToString debug html)
ppHtmlModuleMiniSynopsis odir doctitle themes iface unicode real_qual debug
ppHtmlModuleMiniSynopsis :: FilePath -> String -> Themes
-> Interface -> Bool -> Qualification -> Bool -> IO ()
ppHtmlModuleMiniSynopsis odir _doctitle themes iface unicode qual debug = do
let mdl = ifaceMod iface
html =
headHtml (moduleString mdl) Nothing themes Nothing +++
miniBody <<
(divModuleHeader << sectionName << moduleString mdl +++
miniSynopsis mdl iface unicode qual)
createDirectoryIfMissing True odir
writeFile (joinPath [odir, "mini_" ++ moduleHtmlFile mdl]) (renderToString debug html)
ifaceToHtml :: SourceURLs -> WikiURLs -> Interface -> Bool -> Qualification -> Html
ifaceToHtml maybe_source_url maybe_wiki_url iface unicode qual
= ppModuleContents qual exports (not . null $ ifaceRnOrphanInstances iface) +++
description +++
synopsis +++
divInterface (maybe_doc_hdr +++ bdy +++ orphans)
where
exports = numberSectionHeadings (ifaceRnExportItems iface)
-- todo: if something has only sub-docs, or fn-args-docs, should
-- it be measured here and thus prevent omitting the synopsis?
has_doc ExportDecl { expItemMbDoc = (Documentation mDoc mWarning, _) } = isJust mDoc || isJust mWarning
has_doc (ExportNoDecl _ _) = False
has_doc (ExportModule _) = False
has_doc _ = True
no_doc_at_all = not (any has_doc exports)
description | isNoHtml doc = doc
| otherwise = divDescription $ sectionName << "Description" +++ doc
where doc = docSection Nothing qual (ifaceRnDoc iface)
-- omit the synopsis if there are no documentation annotations at all
synopsis
| no_doc_at_all = noHtml
| otherwise
= divSynopsis $
paragraph ! collapseControl "syn" False "caption" << "Synopsis" +++
shortDeclList (
mapMaybe (processExport True linksInfo unicode qual) exports
) ! (collapseSection "syn" False "" ++ collapseToggle "syn")
-- if the documentation doesn't begin with a section header, then
-- add one ("Documentation").
maybe_doc_hdr
= case exports of
[] -> noHtml
ExportGroup {} : _ -> noHtml
_ -> h1 << "Documentation"
bdy =
foldr (+++) noHtml $
mapMaybe (processExport False linksInfo unicode qual) exports
orphans =
ppOrphanInstances linksInfo (ifaceRnOrphanInstances iface) False unicode qual
linksInfo = (maybe_source_url, maybe_wiki_url)
miniSynopsis :: Module -> Interface -> Bool -> Qualification -> Html
miniSynopsis mdl iface unicode qual =
divInterface << concatMap (processForMiniSynopsis mdl unicode qual) exports
where
exports = numberSectionHeadings (ifaceRnExportItems iface)
processForMiniSynopsis :: Module -> Bool -> Qualification -> ExportItem DocName
-> [Html]
processForMiniSynopsis mdl unicode qual ExportDecl { expItemDecl = L _loc decl0 } =
((divTopDecl <<).(declElem <<)) <$> case decl0 of
TyClD d -> let b = ppTyClBinderWithVarsMini mdl d in case d of
(FamDecl decl) -> [ppTyFamHeader True False decl unicode qual]
(DataDecl{}) -> [keyword "data" <+> b]
(SynDecl{}) -> [keyword "type" <+> b]
(ClassDecl {}) -> [keyword "class" <+> b]
SigD (TypeSig lnames _) ->
map (ppNameMini Prefix mdl . nameOccName . getName . unLoc) lnames
_ -> []
processForMiniSynopsis _ _ qual (ExportGroup lvl _id txt) =
[groupTag lvl << docToHtml Nothing qual (mkMeta txt)]
processForMiniSynopsis _ _ _ _ = []
ppNameMini :: Notation -> Module -> OccName -> Html
ppNameMini notation mdl nm =
anchor ! [ href (moduleNameUrl mdl nm)
, target mainFrameName ]
<< ppBinder' notation nm
ppTyClBinderWithVarsMini :: Module -> TyClDecl DocName -> Html
ppTyClBinderWithVarsMini mdl decl =
let n = tcdName decl
ns = tyvarNames $ tcdTyVars decl -- it's safe to use tcdTyVars, see code above
in ppTypeApp n [] ns (\is_infix -> ppNameMini is_infix mdl . nameOccName . getName) ppTyName
ppModuleContents :: Qualification
-> [ExportItem DocName]
-> Bool -- ^ Orphans sections
-> Html
ppModuleContents qual exports orphan
| null sections && not orphan = noHtml
| otherwise = contentsDiv
where
contentsDiv = divTableOfContents << (
sectionName << "Contents" +++
unordList (sections ++ orphanSection))
(sections, _leftovers{-should be []-}) = process 0 exports
orphanSection
| orphan = [ linkedAnchor "section.orphans" << "Orphan instances" ]
| otherwise = []
process :: Int -> [ExportItem DocName] -> ([Html],[ExportItem DocName])
process _ [] = ([], [])
process n items@(ExportGroup lev id0 doc : rest)
| lev <= n = ( [], items )
| otherwise = ( html:secs, rest2 )
where
html = linkedAnchor (groupId id0)
<< docToHtmlNoAnchors (Just id0) qual (mkMeta doc) +++ mk_subsections ssecs
(ssecs, rest1) = process lev rest
(secs, rest2) = process n rest1
process n (_ : rest) = process n rest
mk_subsections [] = noHtml
mk_subsections ss = unordList ss
-- we need to assign a unique id to each section heading so we can hyperlink
-- them from the contents:
numberSectionHeadings :: [ExportItem DocName] -> [ExportItem DocName]
numberSectionHeadings = go 1
where go :: Int -> [ExportItem DocName] -> [ExportItem DocName]
go _ [] = []
go n (ExportGroup lev _ doc : es)
= ExportGroup lev (show n) doc : go (n+1) es
go n (other:es)
= other : go n es
processExport :: Bool -> LinksInfo -> Bool -> Qualification
-> ExportItem DocName -> Maybe Html
processExport _ _ _ _ ExportDecl { expItemDecl = L _ (InstD _) } = Nothing -- Hide empty instances
processExport summary _ _ qual (ExportGroup lev id0 doc)
= nothingIf summary $ groupHeading lev id0 << docToHtml (Just id0) qual (mkMeta doc)
processExport summary links unicode qual (ExportDecl decl doc subdocs insts fixities splice)
= processDecl summary $ ppDecl summary links decl doc insts fixities subdocs splice unicode qual
processExport summary _ _ qual (ExportNoDecl y [])
= processDeclOneLiner summary $ ppDocName qual Prefix True y
processExport summary _ _ qual (ExportNoDecl y subs)
= processDeclOneLiner summary $
ppDocName qual Prefix True y
+++ parenList (map (ppDocName qual Prefix True) subs)
processExport summary _ _ qual (ExportDoc doc)
= nothingIf summary $ docSection_ Nothing qual doc
processExport summary _ _ _ (ExportModule mdl)
= processDeclOneLiner summary $ toHtml "module" <+> ppModule mdl
nothingIf :: Bool -> a -> Maybe a
nothingIf True _ = Nothing
nothingIf False a = Just a
processDecl :: Bool -> Html -> Maybe Html
processDecl True = Just
processDecl False = Just . divTopDecl
processDeclOneLiner :: Bool -> Html -> Maybe Html
processDeclOneLiner True = Just
processDeclOneLiner False = Just . divTopDecl . declElem
groupHeading :: Int -> String -> Html -> Html
groupHeading lev id0 = groupTag lev ! [identifier (groupId id0)]
groupTag :: Int -> Html -> Html
groupTag lev
| lev == 1 = h1
| lev == 2 = h2
| lev == 3 = h3
| otherwise = h4
|
randen/haddock
|
haddock-api/src/Haddock/Backends/Xhtml.hs
|
bsd-2-clause
| 26,014
| 1
| 21
| 6,739
| 7,047
| 3,632
| 3,415
| 497
| 7
|
{-# LANGUAGE FlexibleInstances, DeriveDataTypeable #-}
module Model (
-- Model
infoHashByName,
Torrent (..),
torrentByName,
purgeTorrent,
DirectoryEntry (..),
getDirectory,
-- Model.Query
QueryPage (..),
-- Model.Stats
StatsValue (..),
getCounter,
addCounter,
getGauge,
-- Model.Download
InfoHash (..),
infoHashToHex,
Download (..),
recentDownloads,
popularDownloads,
mostDownloaded,
userDownloads,
enclosureDownloads,
feedDownloads,
-- Model.Item
Item (..),
groupDownloads,
userItemImage,
-- Model.User
UserName (..),
UserDetails (..),
userDetailsByName,
setUserDetails,
UserSalt (..),
userSalt,
setUserSalted,
registerUser,
userByEmail,
-- Model.Feed
FeedXml (..),
feedXml,
feedEnclosures,
enclosureErrors,
FeedInfo (..),
userFeed,
userFeeds,
userFeedInfo,
addUserFeed,
deleteUserFeed,
FeedDetails (..),
userFeedDetails,
setUserFeedDetails,
-- Model.Token
Token (..),
generateToken,
validateToken,
peekToken
) where
import Prelude
import Data.Convertible
import Data.Text (Text)
import Database.HDBC
import Data.Time
import Data.Data (Typeable)
import qualified Data.ByteString.Char8 as BC
import Control.Applicative
import Utils
import Model.Query
import Model.Download
import Model.Item
import Model.Feed
import Model.User
import Model.Token
import Model.Stats
infoHashByName :: UserName -> Text -> Text -> Query InfoHash
infoHashByName user slug name =
query "SELECT \"info_hash\" FROM user_feeds JOIN enclosures USING (feed) JOIN enclosure_torrents USING (url) JOIN torrents USING (info_hash) WHERE user_feeds.\"user\"=? AND user_feeds.\"slug\"=? AND torrents.\"name\"=?" [toSql user, toSql slug, toSql name]
data Torrent = Torrent {
torrentInfoHash :: InfoHash,
torrentName :: Text,
torrentSize :: Integer,
torrentTorrent :: BC.ByteString
} deriving (Show, Typeable)
instance Convertible [SqlValue] Torrent where
safeConvert (info_hash:name:size:torrent:[]) =
Torrent <$>
safeFromSql info_hash <*>
safeFromSql name <*>
safeFromSql size <*>
pure (fromBytea torrent)
safeConvert vals = convError "Torrent" vals
torrentByName :: UserName -> Text -> Text -> Query Torrent
torrentByName user slug name =
query "SELECT \"info_hash\", \"name\", \"size\", \"torrent\" FROM user_feeds JOIN enclosures USING (feed) JOIN enclosure_torrents USING (url) JOIN torrents USING (info_hash) WHERE user_feeds.\"user\"=? AND user_feeds.\"slug\"=? AND torrents.\"name\"=?" [toSql user, toSql slug, toSql name]
purgeTorrent :: IConnection conn =>
UserName -> Text -> Text -> conn -> IO Int
purgeTorrent user slug name db =
(fromSql . head . head) `fmap`
quickQuery' db "SELECT * FROM purge_download(?, ?, ?)"
[toSql user, toSql slug, toSql name]
data DirectoryEntry = DirectoryEntry
{ dirUser :: UserName
, dirUserTitle :: Text
, dirUserImage :: Text
, dirFeedSlug :: Text
, dirFeedTitle :: Text
, dirFeedLang :: Text
, dirFeedTypes :: Text
} deriving (Show, Typeable)
instance Convertible [SqlValue] DirectoryEntry where
safeConvert (user:userTitle:userImage:
feedSlug:feedTitle:feedLang:feedTypes:[]) =
DirectoryEntry <$>
safeFromSql user <*>
safeFromSql userTitle <*>
(fixUrl <$> safeFromSql userImage) <*>
safeFromSql feedSlug <*>
safeFromSql feedTitle <*>
safeFromSql feedLang <*>
safeFromSql feedTypes
safeConvert vals = convError "DirectoryEntry" vals
getDirectory :: Query DirectoryEntry
getDirectory =
query "SELECT \"user\", COALESCE(\"title\", \"user\"), COALESCE(\"image\", ''), \"slug\", COALESCE(\"feed_title\", \"slug\"), COALESCE(\"lang\", ''), array_to_string(\"types\", ',') FROM directory" []
|
jannschu/bitlove-ui
|
Model.hs
|
bsd-2-clause
| 3,837
| 0
| 15
| 745
| 845
| 486
| 359
| -1
| -1
|
module Yesod.FeedTypes
( Feed (..)
, FeedEntry (..)
) where
import Text.Hamlet (Html)
import Data.Time.Clock (UTCTime)
import Data.Text (Text)
-- | The overal feed
data Feed url = Feed
{ feedTitle :: Text
, feedLinkSelf :: url
, feedLinkHome :: url
-- | note: currently only used for Rss
, feedDescription :: Html
-- | note: currently only used for Rss, possible values:
-- <http://www.rssboard.org/rss-language-codes>
, feedLanguage :: Text
, feedUpdated :: UTCTime
, feedEntries :: [FeedEntry url]
}
-- | Each feed entry
data FeedEntry url = FeedEntry
{ feedEntryLink :: url
, feedEntryUpdated :: UTCTime
, feedEntryTitle :: Text
, feedEntryContent :: Html
}
|
chreekat/yesod
|
yesod-newsfeed/Yesod/FeedTypes.hs
|
bsd-2-clause
| 788
| 0
| 10
| 233
| 150
| 98
| 52
| 19
| 0
|
{-# LANGUAGE GADTs, Rank2Types, TypeOperators, ViewPatterns #-}
module NuElim (
NuElimProof(..),
NuElimDataProof(),
NuElim(..), mkNuElimData,
mapNames
) where
--import Data.Data
import Data.Binding.Hobbits
import Language.Haskell.TH hiding (Name)
import qualified Language.Haskell.TH as TH
--import Unsafe.Coerce (unsafeCoerce)
import Control.Monad.State
-- "proofs" that type a is an allowed type for nu-elimination; i.e.,
-- that the multi-binding of an Mb ctx a can be eliminated by nuWithElim
data NuElimProof a where
NuElimName :: NuElimProof (Name a)
NuElimMb :: NuElimProof a -> NuElimProof (Mb ctx a)
NuElimFun :: NuElimProof a -> NuElimProof b -> NuElimProof (a -> b)
NuElimData :: NuElimDataProof a -> NuElimProof a
data NuElimDataProof a =
NuElimDataProof (forall ctx. MapC Name ctx -> MapC Name ctx -> a -> a)
-- the NuElim class and some useful instances
class NuElim a where
nuElimProof :: NuElimProof a
instance NuElim (Name a) where
nuElimProof = NuElimName
instance (NuElim a, NuElim b) => NuElim (a -> b) where
nuElimProof = NuElimFun nuElimProof nuElimProof
instance NuElim a => NuElim (Mb ctx a) where
nuElimProof = NuElimMb nuElimProof
instance NuElim a => NuElim [a] where
nuElimProof = NuElimData (NuElimDataProof $ (\c1 c2 -> map (mapNames c1 c2)))
-- map the names in one MapC to the corresponding ones in another
mapNamesPf :: NuElimProof a -> MapC Name ctx -> MapC Name ctx -> a -> a
mapNamesPf NuElimName Nil Nil n = n
mapNamesPf NuElimName (names :> m) (names' :> m') n =
case cmpName m n of
Just Refl -> m'
Nothing -> mapNamesPf NuElimName names names' n
mapNamesPf (NuElimMb nuElim) names names' x = undefined -- FIXME!
mapNamesPf (NuElimFun nuElimIn nuElimOut) names names' f =
(mapNamesPf nuElimOut names names') . f . (mapNamesPf nuElimIn names' names)
mapNamesPf (NuElimData (NuElimDataProof mapFun)) names names' x =
mapFun names names' x
-- just like mapNamesPf, except use the NuElim class
mapNames :: NuElim a => MapC Name ctx -> MapC Name ctx -> a -> a
mapNames = mapNamesPf nuElimProof
-- now we define some TH to create NuElimDataProofs
natsFrom i = i : natsFrom (i+1)
fst3 :: (a,b,c) -> a
fst3 (x,_,_) = x
snd3 :: (a,b,c) -> b
snd3 (_,y,_) = y
thd3 :: (a,b,c) -> c
thd3 (_,_,z) = z
type Names = (TH.Name, TH.Name, TH.Name, TH.Name)
mapNamesType a = [t| forall ctx. MapC Name ctx -> MapC Name ctx -> $a -> $a |]
mkNuElimData :: Q [Dec] -> Q [Dec]
mkNuElimData declsQ =
do decls <- declsQ
(cxt, cType, tName, constrs, tyvars) <- getNuElimInfo decls
fName <- newName "f"
x1Name <- newName "x1"
x2Name <- newName "x2"
clauses <- mapM (getClause (tName, fName, x1Name, x2Name)) constrs
mapNamesT <- mapNamesType (return cType)
return [InstanceD
cxt (AppT (ConT ''NuElim) cType)
[ValD (VarP 'nuElimProof)
(NormalB
$ AppE (ConE 'NuElimData)
$ AppE (ConE 'NuElimDataProof)
$ LetE [SigD fName
$ ForallT (map PlainTV tyvars) cxt mapNamesT,
FunD fName clauses]
(VarE fName)) []]]
{-
return (LetE
[SigD fName
(ForallT tyvars reqCxt
$ foldl AppT ArrowT
[foldl AppT (ConT conName)
(map tyVarToType tyvars)]),
FunD fname clauses]
(VarE fname))
-}
where
-- get the name from a data type
getTCtor t = getTCtorHelper t t []
getTCtorHelper (ConT tName) topT tyvars = Just (topT, tName, tyvars)
getTCtorHelper (AppT t1 (VarT var)) topT tyvars =
getTCtorHelper t1 topT (tyvars ++ [var])
getTCtorHelper (SigT t1 _) topT tyvars = getTCtorHelper t1 topT tyvars
getTCtorHelper _ _ _ = Nothing
-- fail for getNuElimInfo
getNuElimInfoFail t =
fail ("mkNuElimData: " ++ show t
++ " is not a NuElim instance for a (G)ADT applied to 0 or more type vars")
-- get info for conName
getNuElimInfo topT@[InstanceD cxt
(AppT (ConT nuElim)
(getTCtor -> Just (t, tName, tyvars))) _]
| nuElim == ''NuElim =
reify tName >>= \info ->
case info of
TyConI (DataD _ _ _ constrs _) ->
return (cxt, t, tName, constrs, tyvars)
_ -> getNuElimInfoFail topT
getNuElimInfo t = getNuElimInfoFail t
-- get a list of Clauses, one for each constructor in constrs
getClauses :: Names -> [Con] -> Q [Clause]
getClauses names constrs = mapM (getClause names) constrs
getClause :: Names -> Con -> Q Clause
getClause names (NormalC cName cTypes) =
getClauseHelper names (map snd cTypes)
(natsFrom 0)
(\l -> ConP cName (map (VarP . fst3) l))
(\l -> foldl AppE (ConE cName) (map fst3 l))
getClause names (RecC cName cVarTypes) =
getClauseHelper names (map thd3 cVarTypes)
(map fst3 cVarTypes)
(\l -> RecP cName
(map (\(var,_,field) -> (field, VarP var)) l))
(\l -> RecConE cName
(map (\(exp,_,field) -> (field, exp)) l))
getClause names (InfixC cType1 cName cType2) =
undefined -- FIXME
getClause names (ForallC _ _ con) = getClause names con
getClauseHelper :: Names -> [Type] -> [a] ->
([(TH.Name,Type,a)] -> Pat) ->
([(Exp,Type,a)] -> Exp) ->
Q Clause
getClauseHelper names@(tName, fName, x1Name, x2Name) cTypes cData pFun eFun =
do varNames <- mapM (newName . ("x" ++) . show . fst)
$ zip (natsFrom 0) cTypes
let varsTypesData = zip3 varNames cTypes cData
let expsTypesData = map (mkExpTypeData names) varsTypesData
return $ Clause [(VarP x1Name), (VarP x2Name), (pFun varsTypesData)]
(NormalB $ eFun expsTypesData) []
mkExpTypeData :: Names -> (TH.Name,Type,a) -> (Exp,Type,a)
mkExpTypeData (tName, fName, x1Name, x2Name)
(varName, getTCtor -> Just (t, tName', _), cData)
| tName == tName' =
-- the type of the arg is the same as the (G)ADT we are
-- recursing over; apply the recursive function
(foldl AppE (VarE fName)
[(VarE x1Name), (VarE x2Name), (VarE varName)],
t, cData)
mkExpTypeData (tName, fName, x1Name, x2Name) (varName, t, cData) =
-- the type of the arg is not the same as the (G)ADT; call mapNames
(foldl AppE (VarE 'mapNames)
[(VarE x1Name), (VarE x2Name), (VarE varName)],
t, cData)
-- FIXME: old stuff below
type CxtStateQ a = StateT Cxt Q a
-- create a NuElimDataProof for a (G)ADT
mkNuElimDataProofOld :: Q TH.Name -> Q Exp
mkNuElimDataProofOld conNameQ =
do conName <- conNameQ
(cxt, name, tyvars, constrs) <- getNuElimInfo conName
(clauses, reqCxt) <- runStateT (getClauses cxt name tyvars constrs) []
fname <- newName "f"
return (LetE
[SigD fname
(ForallT tyvars reqCxt
$ foldl AppT ArrowT
[foldl AppT (ConT conName)
(map tyVarToType tyvars)]),
FunD fname clauses]
(VarE fname))
where
-- convert a TyVar to a Name
tyVarToType (PlainTV n) = VarT n
tyVarToType (KindedTV n _) = VarT n
-- get info for conName
getNuElimInfo conName =
reify conName >>= \info ->
case info of
TyConI (DataD cxt name tyvars constrs _) ->
return (cxt, name, tyvars, constrs)
_ -> fail ("mkNuElimDataProof: " ++ show conName
++ " is not a (G)ADT")
{-
-- report failure
getNuElimInfoFail t =
fail ("mkNuElimDataProof: " ++ show t
++ " is not a fully applied (G)ADT")
getNuElimInfo (ConT conName) topT =
reify conName >>= \info ->
case info of
TyConI (DataD cxt name tyvars constrs _) ->
return (cxt, name, tyvars, constrs)
_ -> getNuElimInfoFail topT
getNuElimInfo (AppT t _) topT = getNuElimInfo t topT
getNuElimInfo (SigT t _) topT = getNuElimInfo t topT
getNuElimInfo _ topT = getNuElimInfoFail topT
-}
-- get a list of Clauses, one for each constructor in constrs
getClauses :: Cxt -> TH.Name -> [TyVarBndr] -> [Con] -> CxtStateQ [Clause]
getClauses cxt name tyvars constrs =
mapM (getClause cxt name tyvars []) constrs
getClause :: Cxt -> TH.Name -> [TyVarBndr] -> [TyVarBndr] -> Con ->
CxtStateQ Clause
getClause cxt name tyvars locTyvars (NormalC cName cTypes) =
getClauseHelper cxt name tyvars locTyvars (map snd cTypes)
(natsFrom 0)
(\l -> ConP cName (map (VarP . fst3) l))
(\l -> foldl AppE (ConE cName) (map (VarE . fst3) l))
getClause cxt name tyvars locTyvars (RecC cName cVarTypes) =
getClauseHelper cxt name tyvars locTyvars (map thd3 cVarTypes)
(map fst3 cVarTypes)
(\l -> RecP cName
(map (\(var,_,field) -> (field, VarP var)) l))
(\l -> RecConE cName
(map (\(var,_,field) -> (field, VarE var)) l))
getClause cxt name tyvars locTyvars (InfixC cType1 cName cType2) =
undefined -- FIXME
getClause cxt name tyvars locTyvars (ForallC tyvars2 cxt2 con) =
getClause (cxt ++ cxt2) name tyvars (locTyvars ++ tyvars2) con
getClauseHelper :: Cxt -> TH.Name -> [TyVarBndr] -> [TyVarBndr] ->
[Type] -> [a] ->
([(TH.Name,Type,a)] -> Pat) ->
([(TH.Name,Type,a)] -> Exp) ->
CxtStateQ Clause
getClauseHelper cxt name tyvars locTyvars cTypes cData pFun eFun =
do varNames <- mapM (lift . newName . ("x" ++) . show . fst)
$ zip (natsFrom 0) cTypes
() <- ensureCxt cxt locTyvars cTypes
let varsTypesData = zip3 varNames cTypes cData
return $ Clause [(pFun varsTypesData)]
(NormalB $ eFun varsTypesData) []
-- ensure that NuElim a holds for each type a in cTypes
ensureCxt :: Cxt -> [TyVarBndr] -> [Type] -> CxtStateQ ()
ensureCxt cxt locTyvars cTypes =
foldM (const (ensureCxt1 cxt locTyvars)) () cTypes
-- FIXME: it is not possible (or, at least, not easy) to determine
-- if NuElim a is implied from a current Cxt... so we just add
-- everything we need to the returned Cxt, except for
ensureCxt1 :: Cxt -> [TyVarBndr] -> Type -> CxtStateQ ()
ensureCxt1 cxt locTyvars t = undefined
{-
ensureCxt1 cxt locTyvars t = do
curCxt = get
let fullCxt = cxt ++ curCxt
isOk <- isNuElim fullCxt
isNuElim
-}
|
eddywestbrook/hobbits
|
archival/NuElim.hs
|
bsd-3-clause
| 11,687
| 0
| 19
| 4,104
| 3,262
| 1,718
| 1,544
| -1
| -1
|
sumOfDigit :: Integer -> Integer
sumOfDigit 0 = 0
sumOfDigit x = (x `mod` 10) + (sumOfDigit (x `div` 10))
main = print (sumOfDigit (2 ^ 1000))
|
foreverbell/project-euler-solutions
|
src/16.hs
|
bsd-3-clause
| 144
| 0
| 9
| 28
| 75
| 41
| 34
| 4
| 1
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE ForeignFunctionInterface #-}
{-# LANGUAGE JavaScriptFFI #-}
{-# LANGUAGE PackageImports #-}
-- |Crypto algorithms of the Keccak family (SHA3/SHAKE), with support for GHCJS.
module Data.Digest.Keccak (sha3_256, shake_128) where
import qualified Data.ByteString as B
#ifdef ghcjs_HOST_OS
import GHCJS.Marshal
import GHCJS.Types
import System.IO.Unsafe
#else
import qualified "cryptonite" Crypto.Hash as S
import qualified Data.ByteArray as S
#endif
--import qualified Data.ByteString as B
-- $setup
-- >>> :set -XOverloadedStrings
-- >>> import ZM.Pretty
-- >>> import Data.String
-- >>>
{- |Return the specified number of bytes of the SHAKE-128 hash of the provided byte string
>>> shake_128 8 B.empty == B.pack [127, 156, 43, 164, 232, 143, 130, 125]
True
>>> shake_128 32 (B.pack [1..10]) == B.pack [142,56,168,122,207,188,35,211,233,209,95,158,63,91,102,156,114,204,22,38,177,105,130,116,173,114,190,153,159,101,10,150]
True
>>> let i = B.pack [1..10] in shake_128 4 i == B.take 4 (shake_128 32 i)
True
-}
shake_128 :: Int -> B.ByteString -> B.ByteString
shake_128 numBytes bs | numBytes <=0 || numBytes > 32 = error "shake128: Invalid number of bytes"
| otherwise = shake_128_ numBytes bs
-- |Return the specified number of bytes of the SHA-3 hash of the provided byte string
sha3_256 :: Int -> B.ByteString -> B.ByteString
sha3_256 numBytes bs | numBytes <=0 || numBytes > 32 = error "sha3_256: Invalid number of bytes"
| otherwise = sha3_256_ numBytes bs
#ifdef ghcjs_HOST_OS
-- CHECK: is it necessary to pack/unpack the ByteStrings?
shake_128_ :: Int -> B.ByteString -> B.ByteString
shake_128_ numBytes = stat (js_shake128 $ numBytes*8) numBytes -- 256)
sha3_256_ :: Int -> B.ByteString -> B.ByteString
sha3_256_ = stat js_sha3_256
stat :: (JSVal -> JSVal) -> Int -> B.ByteString -> B.ByteString
stat f n bs = unsafePerformIO $ do
jbs <- toJSVal $ B.unpack $ bs
Just bs' <- fromJSVal $ f jbs
return . B.take n . B.pack $ bs'
-- PROB: these references will be scrambled by the `closure` compiler, as they are not static functions but are setup dynamically by the sha3.hs library
foreign import javascript unsafe "shake_128.array($2, $1)" js_shake128 :: Int -> JSVal -> JSVal
--foreign import javascript unsafe "sha3_224.array($1)" js_sha3_224 :: JSVal -> JSVal
foreign import javascript unsafe "sha3_256.array($1)" js_sha3_256 :: JSVal -> JSVal
-- foreign import javascript unsafe "keccak_256.array($1)" js_keccak256 :: JSVal -> JSVal
-- foreign import javascript unsafe "(window == undefined ? global : window)['keccak_256']['array']($1)" js_keccak256 :: JSVal -> JSVal
#else
shake_128_ :: Int -> B.ByteString -> B.ByteString
shake_128_ = stat (S.SHAKE128 :: S.SHAKE128 256)
sha3_256_ :: Int -> B.ByteString -> B.ByteString
sha3_256_ = stat S.SHA3_256
stat
:: (S.ByteArrayAccess ba, S.HashAlgorithm alg) =>
alg -> Int -> ba -> B.ByteString
stat f numBytes = B.take numBytes . S.convert . S.hashWith f
#endif
|
tittoassini/typed
|
src/Data/Digest/Keccak.hs
|
bsd-3-clause
| 3,172
| 7
| 13
| 633
| 397
| 214
| 183
| 23
| 1
|
{-|
Module : Data.DepthElement
Description : A `DepthElement` is a `Text` object with 'depth' so that it can
be unfolded into a `Tree`
Copyright : (c) Michael Klein, 2016
License : BSD3
Maintainer : lambdamichael(at)gmail.com
-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE FlexibleContexts #-}
module Data.DepthElement ( Depth(..)
, DepthElement(..)
, DepthElemShow(..)
, baseDepth
, parseDepthElement
, initialSplit
, splitOnDepth
, forestDepthElements
, treeDepthElements
, unfoldDepthTree
) where
import Control.Applicative ( Alternative(..)
)
import Data.Monoid ( (<>)
)
import Data.Text ( Text
)
import Data.Text.Builder.Utils ( unlinesb
)
import Data.Tree ( Forest
, Tree(..)
, unfoldForest
)
import Data.Attoparsec.Text ( Parser
, many1
, string
)
import Data.Attoparsec.Text.Utils ( takeLine
)
import Data.List.Split ( keepDelimsL
, split
, whenElt
)
import TextShow ( TextShow(..)
, fromText
)
-- | This is the depth of an element in a `Tree`
-- If `Nat` were faster, this would use it instead of `Int`
newtype Depth = Depth Int deriving (Enum, Eq, Ord)
-- | The lowest valid depth (@0@)
baseDepth :: Depth
baseDepth = Depth 0
-- | This is a _very_ approximate inverse to the parser
instance TextShow Depth where
showb (Depth 0) = fromText "├── "
showb (Depth d) = mconcat $ spaces ++ [fromText "├── "]
where
spaces = replicate (d - 1) $ fromText " "
-- | An element with depth
data DepthElement a = DepthElem { depth :: Depth
, dElem :: a
}
instance Eq (DepthElement a) where
(==) x y = (==) (depth x) (depth y)
instance TextShow a => TextShow (DepthElement a) where
showb (DepthElem d x) = showb d <> showb x
-- | This is the character sequence for a middle branch
midBranch :: Parser Text
midBranch = string "├── "
-- | This is the character sequence for left-padding a branch
preBranch :: Parser Text
preBranch = string "│ "
-- | This is the character sequence for the last branch
endBranch :: Parser Text
endBranch = string "└── "
-- | This is the sequence of spces for left-padding a branch
branchSpaces :: Parser Text
branchSpaces = string " "
-- | Use the above branch parsers to get the depth of a branch in a tree
parseDepth :: Parser Int
parseDepth = do
units <- many1 $ midBranch <|> preBranch <|> endBranch <|> branchSpaces
return . length $ units
-- | Parse a complete line from a printed tree
parseDepthElement :: Parser (DepthElement Text)
parseDepthElement = do
d <- parseDepth
e <- takeLine
return $ DepthElem (Depth d) e
-- | Split a list of `DepthElement`s according to `depth`
splitOnDepth :: [DepthElement a] -> [[DepthElement a]]
splitOnDepth (x:xs) = split (keepDelimsL $ whenElt (== x)) (x:xs)
splitOnDepth _ = []
-- | The unfolder used by `unfoldDepthTree`, treating the head of the list
-- as the root of the input tree implicitly
unfolder :: [DepthElement Text] -> (Text, [[DepthElement Text]])
unfolder (x:xs) = (dElem x, splitOnDepth xs)
unfolder _ = ("" , [] )
-- | Begin splitting up the `DepthElement`s for unfolding
initialSplit :: [DepthElement a] -> [[DepthElement a]]
initialSplit = split $ keepDelimsL $ whenElt ((Depth 1 ==) . depth)
-- | Unfold `DepthElement` into a forest
unfoldDepthTree :: [[DepthElement Text]] -> Forest Text
unfoldDepthTree = unfoldForest unfolder
class ToDepthElements t where
type ToDepthElem t
toDepthElements :: t -> [DepthElement (ToDepthElem t)]
depthToDepthElements :: Depth -> t -> [DepthElement (ToDepthElem t)]
toDepthElements = depthToDepthElements baseDepth
{-# MINIMAL depthToDepthElements #-}
instance ToDepthElements (Forest a) where
type ToDepthElem (Forest a) = a
depthToDepthElements = forestDepthElements
instance (a ~ a) => ToDepthElements (Tree a) where
type ToDepthElem (Tree a) = a
depthToDepthElements = treeDepthElements
-- | To make the `TextShow` instance not an orphan
newtype DepthElemShow a = DepthElemShow { _unDepthElemShow :: a}
instance (TextShow (ToDepthElem t), ToDepthElements t) => TextShow (DepthElemShow t) where
showb = unlinesb . toDepthElements . _unDepthElemShow
-- | Convert a forest to a list of `DepthElement`s, given an initial depth
forestDepthElements :: Depth -> Forest a -> [DepthElement a]
forestDepthElements d = (>>= treeDepthElements d)
-- | `forestDepthElements` for `Tree`s
treeDepthElements :: Depth -> Tree a -> [DepthElement a]
treeDepthElements d ~(Node l s) = DepthElem d l : forestDepthElements (succ d) s
|
michaeljklein/git-details
|
src/Data/DepthElement.hs
|
bsd-3-clause
| 5,654
| 0
| 12
| 1,849
| 1,132
| 626
| 506
| 91
| 1
|
{-# LANGUAGE DeriveGeneric, KindSignatures,
FlexibleInstances, TypeOperators, TypeSynonymInstances,
MultiParamTypeClasses, FunctionalDependencies, OverlappingInstances,
ScopedTypeVariables, EmptyDataDecls, DefaultSignatures,
UndecidableInstances, FlexibleContexts, StandaloneDeriving, IncoherentInstances,
DeriveDataTypeable #-}
module Language.C.Simple.CValue (
CValue(..),
ToCValue(..),
FromCValue(..),
Side(..),
UnionPath(..),
PrimitiveValue(..)
)
where
import Data.Word
import Data.Data
import GHC.Generics
import Foreign.C.Types
import Control.Applicative
import Data.List
import Data.DList (DList, toList)
import Data.Monoid (mappend)
import Debug.Trace
import Debug.Trace.Helpers
import Data.Tuple.Select
import Control.Monad ((<=<))
import Data.Binary
debug = False
traceDebug msg x = if debug
then trace msg x
else x
-- | A step in union path
data Side = Lft
| Rght
deriving(Show, Eq, Read, Ord, Data, Typeable, Generic)
-- | This is used for the conversion from a CValue back to Haskell type. Ideally it should be
-- and index, but unforunately this does not work with the way Generics creates its :+: binary tree.
-- I'm leaving it here for now, but I might find a more elegant way to handle this.
type UnionPath = [Side]
deriving instance Data CChar
deriving instance Data CSChar
deriving instance Data CUChar
deriving instance Data CShort
deriving instance Data CUShort
deriving instance Data CInt
deriving instance Data CUInt
deriving instance Data CLong
deriving instance Data CULong
deriving instance Data CPtrdiff
deriving instance Data CSize
deriving instance Data CWchar
deriving instance Data CSigAtomic
deriving instance Data CLLong
deriving instance Data CULLong
deriving instance Data CIntPtr
deriving instance Data CUIntPtr
deriving instance Data CIntMax
deriving instance Data CUIntMax
deriving instance Data CClock
deriving instance Data CTime
deriving instance Data CUSeconds
deriving instance Data CSUSeconds
deriving instance Data CFloat
deriving instance Data CDouble
-- | Primitive C values
data PrimitiveValue = PChar CChar
| PSChar CSChar
| PUChar CUChar
| PShort CShort
| PUShort CUShort
| PInt CInt
| PUInt CUInt
| PLong CLong
| PULong CULong
| PPtrdiff CPtrdiff
| PSize CSize
| PWchar CWchar
| PSigAtomic CSigAtomic
| PLLong CLLong
| PULLong CULLong
| PIntPtr CIntPtr
| PUIntPtr CUIntPtr
| PIntMax CIntMax
| PUIntMax CUIntMax
| PClock CClock
| PTime CTime
| PUSeconds CUSeconds
| PSUSeconds CSUSeconds
| PFloat CFloat
| PDouble CDouble
deriving(Eq, Show, Read, Ord, Data, Typeable, Generic)
-- | A generic C value
data CValue = VStruct [CValue]
| VUnion UnionPath CValue
| VPrimitive PrimitiveValue
| VArray [CValue]
| VMember CValue
| Void
deriving(Show, Eq, Read, Ord, Data, Typeable, Generic)
------------------------------------------------------------------------------------
-- | ToCValue Class
------------------------------------------------------------------------------------
class ToCValue a where
toCValue :: a -> CValue
default toCValue :: (Generic a, GToCValue (Rep a)) => a -> CValue
toCValue a = gToCValue (from a)
------------------------------------------------------------------------------------
-- Primitive Instances
------------------------------------------------------------------------------------
instance ToCValue CFloat where
toCValue = VPrimitive . PFloat
instance ToCValue CDouble where
toCValue = VPrimitive . PDouble
instance ToCValue CChar where
toCValue = VPrimitive . PChar
instance ToCValue CSChar where
toCValue = VPrimitive . PSChar
instance ToCValue CUChar where
toCValue = VPrimitive . PUChar
instance ToCValue CShort where
toCValue = VPrimitive . PShort
instance ToCValue CUShort where
toCValue = VPrimitive . PUShort
instance ToCValue CInt where
toCValue = VPrimitive . PInt
instance ToCValue CUInt where
toCValue = VPrimitive . PUInt
instance ToCValue CLong where
toCValue = VPrimitive . PLong
instance ToCValue CULong where
toCValue = VPrimitive . PULong
instance ToCValue CPtrdiff where
toCValue = VPrimitive . PPtrdiff
instance ToCValue CSize where
toCValue = VPrimitive . PSize
instance ToCValue CWchar where
toCValue = VPrimitive . PWchar
instance ToCValue CSigAtomic where
toCValue = VPrimitive . PSigAtomic
instance ToCValue CLLong where
toCValue = VPrimitive . PLLong
instance ToCValue CULLong where
toCValue = VPrimitive . PULLong
instance ToCValue CIntPtr where
toCValue = VPrimitive . PIntPtr
instance ToCValue CUIntPtr where
toCValue = VPrimitive . PUIntPtr
instance ToCValue CIntMax where
toCValue = VPrimitive . PIntMax
instance ToCValue CUIntMax where
toCValue = VPrimitive . PUIntMax
instance ToCValue CClock where
toCValue = VPrimitive . PClock
instance ToCValue CTime where
toCValue = VPrimitive . PTime
instance ToCValue CUSeconds where
toCValue = VPrimitive . PUSeconds
instance ToCValue CSUSeconds where
toCValue = VPrimitive . PSUSeconds
-------------------------------------- Other Instances -----------------------------
instance ToCValue a => ToCValue [a] where
toCValue = VArray . map toCValue
------------------------------------------------------------------------------------
-- Derive from this to convert a Haskell Type to a CValue
------------------------------------------------------------------------------------
--convert
class GToCValue f where
gToCValue :: f a -> CValue
instance GToCValue U1 where
gToCValue U1 = Void
instance (Datatype d, DispatchConstructor a, GToCValueList a) => GToCValue (D1 d a) where
gToCValue = dispatchCon . unM1 . traceDebug "GToCValue (D1 d a)"
instance (Constructor c, GToCValue a) => GToCValue (C1 c a) where
gToCValue = gToCValue . unM1 . traceDebug "GToCValue (C1 c a)"
instance (Selector s, GToCValue a) => GToCValue (S1 s a) where
gToCValue = gToCValue . unM1 . traceDebug "GToCValue (S1 s a)"
instance (ToCValue a) => GToCValue (K1 i a) where
gToCValue = toCValue . unK1 . traceDebug "GToCValue (K1 i a)"
instance (GToCValue a, GToCValue b, GConArgToLit a, GConArgToLit b) => GToCValue (a :*: b) where
gToCValue = VStruct . toList . gConArgToLit . traceDebug "GToCValue (a :*: b)"
-- Ripped from Aeson
--
class GConArgToLit f where
gConArgToLit :: f a -> DList CValue
instance (GConArgToLit a, GConArgToLit b) => GConArgToLit (a :*: b) where
gConArgToLit (a :*: b) = gConArgToLit a `mappend` (gConArgToLit $ traceDebug "GConArgToLit (a :*: b)" b)
instance (Selector s, GToCValue a) => GConArgToLit (S1 s a) where
gConArgToLit a = pure (VMember $ gToCValue $ traceDebug "GConArgToLit a" a)
--------------------------------------------------------------------------------
class DispatchConstructor f where dispatchCon :: f a -> CValue
class DispatchConstructor' b f where dispatchCon' :: Tagged b (f a -> CValue)
instance (IsSum f b, DispatchConstructor' b f, GToCValueList f) => DispatchConstructor f where
dispatchCon = unTagged (dispatchCon' :: Tagged b (f a -> CValue))
instance (GToCValueList a) => DispatchConstructor' True a where
dispatchCon' = Tagged (toSum . traceDebug "DispatchConstructor' True a")
toSum :: (GToCValueList f) => f a -> CValue
toSum x = result where
result = VUnion index ctype
(index, ctype) = toUnionPathValue $ gToCValueList $ traceDebug "GToCValue (a :+: b)" x
instance (GToCValue f) => DispatchConstructor' False f where
dispatchCon' = Tagged (VUnion [Lft] . gToCValue . traceDebug "DispatchConstructor' False f")
--------------------------------------------------------------------------------
data True
data False
newtype Tagged s b = Tagged {unTagged :: b}
data CValueList = LeftSucc CValueList
| RightSucc CValueList
| Nil CValue
--http://www.haskell.org/haskellwiki/GHC/AdvancedOverlap
--To pick an instance based on the context
class GToCValueList f where gToCValueList :: f a -> CValueList
class GToCValueList' b f where gToCValueList' :: Tagged b (f a -> CValueList)
instance (IsSum f b, GToCValueList' b f) => GToCValueList f where
gToCValueList = unTagged (gToCValueList' :: Tagged b (f a -> CValueList))
instance (GToCValue f) => GToCValueList' False f where
gToCValueList' = Tagged (Nil . gToCValue)
instance (GToCValueList a, GToCValueList b) => GToCValueList' True (a :+: b) where
gToCValueList' = Tagged $ \x -> case x of
R1 x -> RightSucc (gToCValueList $ traceDebug "NilR" x)
L1 x -> LeftSucc (gToCValueList $ traceDebug "Succ" x)
toUnionPath :: CValueList -> UnionPath
toUnionPath (LeftSucc x) = Lft:(toUnionPath $ traceDebug "LeftSucc" x)
toUnionPath (RightSucc x) = Rght:(toUnionPath $ traceDebug "RightSucc" x)
toUnionPath (Nil _) = []
retrieveValue :: CValueList -> CValue
retrieveValue (RightSucc x) = retrieveValue x
retrieveValue (LeftSucc x) = retrieveValue x
retrieveValue (Nil x) = x
toUnionPathValue :: CValueList -> (UnionPath, CValue)
toUnionPathValue x = (toUnionPath x, retrieveValue x)
---------------------------------------------------------------------------------
-- | Derive from this to convert from a CValue to Haskell type
---------------------------------------------------------------------------------
class FromCValue a where
fromCValue :: CValue -> Either String a
default fromCValue :: (Generic a, GFromCValue (Rep a)) => CValue -> Either String a
fromCValue = fmap to . gFromCValue . traceDebug "fromCValue"
------------------------------------Instances-------------------------------------
instance FromCValue PrimitiveValue where
fromCValue (VPrimitive x) = Right $ traceDebug "FromCValue PrimitiveValue" x
fromCValue x = Left $ show x ++ " is not a VPrimitive"
instance FromCValue CSChar where
fromCValue x = fromPSChar <$> fromCValue x
instance FromCValue CUChar where
fromCValue x = fromPUChar <$> fromCValue x
instance FromCValue CShort where
fromCValue x = fromPShort <$> fromCValue x
instance FromCValue CUShort where
fromCValue x = fromPUShort <$> fromCValue x
instance FromCValue CInt where
fromCValue x = fromPInt <$> fromCValue x
instance FromCValue CUInt where
fromCValue x = fromPUInt <$> fromCValue x
instance FromCValue CLong where
fromCValue x = fromPLong <$> fromCValue x
instance FromCValue CULong where
fromCValue x = fromPULong <$> fromCValue x
instance FromCValue CPtrdiff where
fromCValue x = fromPPtrdiff <$> fromCValue x
instance FromCValue CSize where
fromCValue x = fromPSize <$> fromCValue x
instance FromCValue CWchar where
fromCValue x = fromPWchar <$> fromCValue x
instance FromCValue CSigAtomic where
fromCValue x = fromPSigAtomic <$> fromCValue x
instance FromCValue CLLong where
fromCValue x = fromPLLong <$> fromCValue x
instance FromCValue CULLong where
fromCValue x = fromPULLong <$> fromCValue x
instance FromCValue CIntPtr where
fromCValue x = fromPIntPtr <$> fromCValue x
instance FromCValue CUIntPtr where
fromCValue x = fromPUIntPtr <$> fromCValue x
instance FromCValue CIntMax where
fromCValue x = fromPIntMax <$> fromCValue x
instance FromCValue CUIntMax where
fromCValue x = fromPUIntMax <$> fromCValue x
instance FromCValue CClock where
fromCValue x = fromPClock <$> fromCValue x
instance FromCValue CTime where
fromCValue x = fromPTime <$> fromCValue x
instance FromCValue CUSeconds where
fromCValue x = fromPUSeconds <$> fromCValue x
instance FromCValue CSUSeconds where
fromCValue x = fromPSUSeconds <$> fromCValue x
instance FromCValue CFloat where
fromCValue x = fromPFloat <$> fromCValue x
instance FromCValue CDouble where
fromCValue x = fromPDouble <$> fromCValue x
-------------------------------------- Other Instances ---------------------------------
instance FromCValue a => FromCValue [a] where
fromCValue (VArray xs) = mapM fromCValue xs
------------------------------------------------------------------------------------
-- Generic FromCValue Class
------------------------------------------------------------------------------------
{-
This should start with the D1
and basically follow the format above
-}
class GFromCValue f where
gFromCValue :: CValue -> Either String (f a)
instance GFromCValue U1 where
gFromCValue Void = Right U1
gFromCValue x = Left $ "could not convert from " ++ show x ++ " to the unit type"
instance (Datatype d, ConsFromCValue a, GFromSum a) => GFromCValue (D1 d a) where
gFromCValue = fmap (\x -> traceDebug ("GFromCValue (D1 d a)" ++ datatypeName x) x) . fmap M1 . consParseCValue
instance (Constructor c, GFromCValue a) => GFromCValue (C1 c a) where
gFromCValue = fmap (\x -> traceDebug ("GFromCValue (C1 d a)" ++ conName x) x) . fmap M1 . gFromCValue
instance (Selector s, GFromCValue a) => GFromCValue (S1 s a) where
gFromCValue = fmap (traceDebug "GFromCValue (S1 d a)") . fmap M1 . gFromCValue
instance (FromCValue a) => GFromCValue (K1 i a) where
gFromCValue = fmap K1 . fromCValue . traceDebug "GFromCValue (K1 i a)"
instance (GFromCValue a, GFromCValue b, GFromProduct a, GFromProduct b) => GFromCValue (a :*: b) where
gFromCValue (VStruct xs) = gParseProduct $ traceDebug "GFromCValue (a :*: b)" xs
gFromCValue x = Left $ "could not convert from " ++ show x ++ " to a product type"
--------------------------------------------------------------------------------
class ConsFromCValue f where consParseCValue :: CValue -> Either String (f a)
class ConsFromCValue' b f where consParseCValue' :: Tagged b (CValue -> Either String (f a))
instance (IsSum f b, ConsFromCValue' b f, GFromSum f) => ConsFromCValue f where
consParseCValue = unTagged (consParseCValue' :: Tagged b (CValue -> Either String (f a)) )
instance (GFromSum f) => ConsFromCValue' True f where
consParseCValue' = Tagged parseSum
parseSum :: (GFromSum f) => CValue -> Either String (f a )
parseSum (VUnion index x) = gParseSum index $ traceDebug "parseSum" x
parseSum x = Left $ "a sum type must be a union not" ++ show x
instance (GFromCValue f) => ConsFromCValue' False f where
consParseCValue' = Tagged (gFromCValue <=< (fromUnionE . traceDebug "ConsFromCValue' False f") )
fromUnionE :: CValue -> Either String CValue
fromUnionE (VUnion _ x) = Right x
fromUnionE x = Left $ "could not convert from " ++ show x ++ " to a union type"
----------------------------------------------------------------------------------------
class GFromProduct f where
gParseProduct :: [CValue] -> Either String (f a)
instance (GFromProduct a, GFromProduct b) => GFromProduct (a :*: b) where
gParseProduct [] = Left "parse product can't work with empty lists"
gParseProduct xs = (:*:) <$> gParseProduct firstHalf
<*> (gParseProduct $ traceDebug "GFromProduct (a :*: b)" secondHalf) where
firstHalf = take (length xs `div` 2) xs
secondHalf = drop (length xs `div` 2) xs
instance (Selector s, GFromCValue a) => GFromProduct (S1 s a) where
gParseProduct ((VMember x):[]) = gFromCValue $ traceDebug "GFromProduct (S1 s a)" x
gParseProduct x = Left $ "could not convert from " ++ show x ++ " to a selector or member"
----------------------------------------------------------------------------------------
class GFromSum f where
gParseSum :: UnionPath -> CValue -> Either String (f a)
instance (GFromSum a, GFromSum b) => GFromSum (a :+: b) where
gParseSum (Lft:[]) x = L1 <$> (gParseSum [] $ traceDebug "gParseSum L1 []" x)
gParseSum (Rght:[]) x = R1 <$> (gParseSum [] $ traceDebug "gParseSum R1 []" x)
gParseSum (Lft:ys) x = L1 <$> (gParseSum ys $ traceDebug "gParseSum L1" x)
gParseSum (Rght:ys) x = R1 <$> (gParseSum ys $ traceDebug "gParseSum R1" x)
instance (GFromCValue f) => GFromSum f where
gParseSum _ x = gFromCValue $ traceDebug "GFromSum (f)" x
------------------------------------------------------------------------------------------
class IsSum (f :: * -> *) b | f -> b
instance (IsSum f b) => IsSum (M1 S s f) b
instance (IsSum f b) => IsSum (M1 C c f) b
instance (IsSum f b) => IsSum (M1 D c f) b
instance IsSum (f :+: g) True
instance IsSum (f :*: g) False
instance IsSum (K1 i c) False
instance IsSum U1 False
fromPChar :: PrimitiveValue -> CChar
fromPChar (PChar x1) = x1
fromPChar _ = error "fromPChar failed, not a PChar"
fromPSChar :: PrimitiveValue -> CSChar
fromPSChar (PSChar x1) = x1
fromPSChar _ = error "fromPSChar failed, not a PSChar"
fromPUChar :: PrimitiveValue -> CUChar
fromPUChar (PUChar x1) = x1
fromPUChar _ = error "fromPUChar failed, not a PUChar"
fromPShort :: PrimitiveValue -> CShort
fromPShort (PShort x1) = x1
fromPShort _ = error "fromPShort failed, not a PShort"
fromPUShort :: PrimitiveValue -> CUShort
fromPUShort (PUShort x1) = x1
fromPUShort _ = error "fromPUShort failed, not a PUShort"
fromPInt :: PrimitiveValue -> CInt
fromPInt (PInt x1) = x1
fromPInt _ = error "fromPInt failed, not a PInt"
fromPUInt :: PrimitiveValue -> CUInt
fromPUInt (PUInt x1) = x1
fromPUInt _ = error "fromPUInt failed, not a PUInt"
fromPLong :: PrimitiveValue -> CLong
fromPLong (PLong x1) = x1
fromPLong _ = error "fromPLong failed, not a PLong"
fromPULong :: PrimitiveValue -> CULong
fromPULong (PULong x1) = x1
fromPULong _ = error "fromPULong failed, not a PULong"
fromPPtrdiff :: PrimitiveValue -> CPtrdiff
fromPPtrdiff (PPtrdiff x1) = x1
fromPPtrdiff _ = error "fromPPtrdiff failed, not a PPtrdiff"
fromPSize :: PrimitiveValue -> CSize
fromPSize (PSize x1) = x1
fromPSize _ = error "fromPSize failed, not a PSize"
fromPWchar :: PrimitiveValue -> CWchar
fromPWchar (PWchar x1) = x1
fromPWchar _ = error "fromPWchar failed, not a PWchar"
fromPSigAtomic :: PrimitiveValue -> CSigAtomic
fromPSigAtomic (PSigAtomic x1) = x1
fromPSigAtomic _ = error "fromPSigAtomic failed, not a PSigAtomic"
fromPLLong :: PrimitiveValue -> CLLong
fromPLLong (PLLong x1) = x1
fromPLLong _ = error "fromPLLong failed, not a PLLong"
fromPULLong :: PrimitiveValue -> CULLong
fromPULLong (PULLong x1) = x1
fromPULLong _ = error "fromPULLong failed, not a PULLong"
fromPIntPtr :: PrimitiveValue -> CIntPtr
fromPIntPtr (PIntPtr x1) = x1
fromPIntPtr _ = error "fromPIntPtr failed, not a PIntPtr"
fromPUIntPtr :: PrimitiveValue -> CUIntPtr
fromPUIntPtr (PUIntPtr x1) = x1
fromPUIntPtr _ = error "fromPUIntPtr failed, not a PUIntPtr"
fromPIntMax :: PrimitiveValue -> CIntMax
fromPIntMax (PIntMax x1) = x1
fromPIntMax _ = error "fromPIntMax failed, not a PIntMax"
fromPUIntMax :: PrimitiveValue -> CUIntMax
fromPUIntMax (PUIntMax x1) = x1
fromPUIntMax _ = error "fromPUIntMax failed, not a PUIntMax"
fromPClock :: PrimitiveValue -> CClock
fromPClock (PClock x1) = x1
fromPClock _ = error "fromPClock failed, not a PClock"
fromPTime :: PrimitiveValue -> CTime
fromPTime (PTime x1) = x1
fromPTime _ = error "fromPTime failed, not a PTime"
fromPUSeconds :: PrimitiveValue -> CUSeconds
fromPUSeconds (PUSeconds x1) = x1
fromPUSeconds _ = error "fromPUSeconds failed, not a PUSeconds"
fromPSUSeconds :: PrimitiveValue -> CSUSeconds
fromPSUSeconds (PSUSeconds x1) = x1
fromPSUSeconds _ = error "fromPSUSeconds failed, not a PSUSeconds"
fromPFloat :: PrimitiveValue -> CFloat
fromPFloat (PFloat x1) = x1
fromPFloat _ = error "fromPFloat failed, not a PFloat"
fromPDouble :: PrimitiveValue -> CDouble
fromPDouble (PDouble x1) = x1
fromPDouble _ = error "fromPDouble failed, not a PDouble"
fromVStruct :: CValue -> [CValue]
fromVStruct (VStruct x1) = x1
fromVStruct _ = error "fromVStruct failed, not a VStruct"
fromVUnion :: CValue -> ([Side], CValue)
fromVUnion (VUnion x1 x2) = (x1, x2)
fromVUnion _ = error "fromVUnion failed, not a VUnion"
fromVPrimitive :: CValue -> PrimitiveValue
fromVPrimitive (VPrimitive x1) = x1
fromVPrimitive _ = error "fromVPrimitive failed, not a VPrimitive"
fromVArray :: CValue -> [CValue]
fromVArray (VArray x1) = x1
fromVArray _ = error "fromVArray failed, not a VArray"
fromVMember :: CValue -> CValue
fromVMember (VMember x1) = x1
fromVMember _ = error "fromVMember failed, not a VMember"
fromVoid :: CValue -> ()
fromVoid Void = ()
fromVoid _ = error "fromVoid failed, not a Void"
|
jfischoff/simple-c-value
|
src/Language/C/Simple/CValue.hs
|
bsd-3-clause
| 21,305
| 0
| 14
| 4,592
| 5,573
| 2,868
| 2,705
| -1
| -1
|
{-# LANGUAGE ScopedTypeVariables #-}
import Language.Porter
import Control.Applicative
main :: IO ()
main = (unlines . map stem . lines) <$> getContents >>= putStr
|
mwotton/porter
|
Tests/TestPorter.hs
|
bsd-3-clause
| 168
| 0
| 10
| 28
| 49
| 26
| 23
| 5
| 1
|
import Lseed.Data
import Lseed.Data.Functions
import Lseed.DB
import Lseed.Grammar.Parse
import Lseed.Mainloop
import Control.Applicative
import Control.Monad
import Text.Printf
import System.Environment
getDBGarden conf = spread <$> map compileDBCode <$> getCodeToRun conf
where spread gs = zipWith (\(u,n,g) p ->
Planted ((fromIntegral p + 0.5) / l)
u
n
g
inititalPlant
) gs [0..]
where l = fromIntegral (length gs)
compileDBCode dbc =
case parseGrammar "" (dbcCode dbc) of
Left err -> error (show err)
Right grammarFile -> (dbcUserID dbc, dbcUserName dbc, grammarFile)
dbc2genome = either (error.show) id . parseGrammar "" . dbcCode
getDBUpdate conf planted = maybe (genome planted) dbc2genome <$>
getUpdatedCodeFromDB conf (plantOwner planted)
scoringObs conf = nullObserver {
obFinished = \garden -> do
forM_ garden $ \planted -> do
printf "Plant from %d at %.4f: Total size %.4f\n"
(plantOwner planted)
(plantPosition planted)
(plantLength (phenotype planted))
addFinishedSeasonResults conf garden
}
main = do
args <- getArgs
case args of
[conf] -> do
lseedMainLoop False
(scoringObs conf)
(GardenSource (getDBGarden conf) (getDBUpdate conf) (return Nothing))
30
_ -> do
putStrLn "L-Seed DB client application."
putStrLn "Please pass DB configuration file on the command line."
|
nomeata/L-seed
|
src/dbscorer.hs
|
bsd-3-clause
| 1,416
| 29
| 18
| 312
| 476
| 239
| 237
| 44
| 2
|
{-# OPTIONS -cpp #-}
module API where
import AltData.Typeable
data Interface = Interface {
function :: String
}
instance Typeable Interface where
#if __GLASGOW_HASKELL__ >= 603
typeOf i = mkTyConApp (mkTyCon "API.Interface") []
#else
typeOf i = mkAppTy (mkTyCon "API.Interface") []
#endif
plugin :: Interface
plugin = Interface { function = "goodbye" }
|
abuiles/turbinado-blog
|
tmp/dependencies/hs-plugins-1.3.1/testsuite/dynload/simple/api/API.hs
|
bsd-3-clause
| 380
| 0
| 8
| 80
| 75
| 44
| 31
| 9
| 1
|
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeApplications #-}
-- | Directory
module Haskus.System.Linux.FileSystem.Directory
( sysGetDirectoryEntries
, sysCreateDirectory
, sysRemoveDirectory
, DirectoryEntry(..)
, DirectoryEntryHeader(..)
, DirectoryEntryType (..)
, listDirectory
)
where
import Haskus.Format.Binary.BitSet as BitSet
import Haskus.Format.Binary.Word
import Haskus.Format.Binary.Enum
import Haskus.Format.Binary.Ptr
import Haskus.Format.Binary.Storable
import Haskus.Format.String
import Haskus.System.Linux.ErrorCode
import Haskus.System.Linux.Handle
import Haskus.System.Linux.Syscalls
import Haskus.System.Linux.FileSystem
import Haskus.Utils.Flow
import Haskus.Utils.Types.Generics (Generic)
sysCreateDirectory :: MonadInIO m => Maybe Handle -> FilePath -> FilePermissions -> Bool -> FlowT '[ErrorCode] m ()
sysCreateDirectory fd path perm sticky = do
let
opt = if sticky
then BitSet.fromList [FileOptSticky]
else BitSet.empty
mode = makeMode FileTypeDirectory perm opt
call path' = case fd of
Nothing -> liftIO $ syscall_mkdir path' mode
Just (Handle fd') -> liftIO $ syscall_mkdirat fd' path' mode
withCString path call >>= checkErrorCode_
sysRemoveDirectory :: MonadInIO m => FilePath -> FlowT '[ErrorCode] m ()
sysRemoveDirectory path = withCString path $ \path' ->
checkErrorCode_ =<< liftIO (syscall_rmdir path')
data DirectoryEntryHeader = DirectoryEntryHeader
{ dirInod :: Word64 -- ^ Inode number
, dirOffset :: Int64 -- ^ Offset of the next entry
, dirLength :: Word16 -- ^ Length of the entry
, dirFileTyp :: Word8 -- ^ Type of file
} deriving (Generic,Storable)
data DirectoryEntry = DirectoryEntry
{ entryInode :: Word64
, entryType :: DirectoryEntryType
, entryName :: FilePath
} deriving (Show)
-- | Entry type
--
-- From dirent.h (d_type)
data DirectoryEntryType
= TypeUnknown
| TypeFIFO
| TypeCharDevice
| TypeDirectory
| TypeBlockDevice
| TypeRegularFile
| TypeSymbolicLink
| TypeSocket
| TypeWhiteOut
deriving (Show,Eq,Enum)
instance CEnum DirectoryEntryType where
fromCEnum = \case
TypeUnknown -> 0
TypeFIFO -> 1
TypeCharDevice -> 2
TypeDirectory -> 4
TypeBlockDevice -> 6
TypeRegularFile -> 8
TypeSymbolicLink -> 10
TypeSocket -> 12
TypeWhiteOut -> 14
toCEnum = \case
0 -> TypeUnknown
1 -> TypeFIFO
2 -> TypeCharDevice
4 -> TypeDirectory
6 -> TypeBlockDevice
8 -> TypeRegularFile
10 -> TypeSymbolicLink
12 -> TypeSocket
14 -> TypeWhiteOut
e -> error ("Invalid DirectoryEntryType: " ++ show (fromIntegral e :: Word8))
-- | getdents64 syscall
--
-- Linux doesn't provide a stateless API: the offset in the file (i.e. the
-- iterator in the directory contents) is shared by everyone using the file
-- descriptor...
--
-- TODO: propose a "pgetdents64" syscall for Linux with an additional offset
-- (like pread, pwrite)
sysGetDirectoryEntries :: MonadInIO m => Handle -> Word -> FlowT '[ErrorCode] m [DirectoryEntry]
sysGetDirectoryEntries (Handle fd) buffersize = do
let
readEntries p n
| n < sizeOfT @DirectoryEntryHeader = return []
| otherwise = do
hdr <- peek p
let
len = fromIntegral (dirLength hdr)
sizede = sizeOfT @DirectoryEntryHeader
namepos = p `indexPtr'` sizede
nextpos = p `indexPtr'` len
nextlen = n - len
name <- peekCString (castPtr namepos)
let x = DirectoryEntry (dirInod hdr) (toCEnum (dirFileTyp hdr)) name
xs <- readEntries nextpos nextlen
-- filter deleted files
if dirInod hdr /= 0
then return (x:xs)
else return xs
allocaArray buffersize $ \(ptr :: Ptr Word8) -> do
nread <- checkErrorCode =<< liftIO (syscall_getdents64 fd (castPtr ptr) (fromIntegral buffersize))
readEntries (castPtr ptr) (fromIntegral nread)
-- | Return the content of a directory
--
-- Warning: reading concurrently the same file descriptor returns mixed up
-- results because of the stateful kernel interface
listDirectory :: MonadInIO m => Handle -> FlowT '[ErrorCode] m [DirectoryEntry]
listDirectory fd = do
-- Return at the beginning of the directory
sysSeek' fd 0 SeekSet
-- Read contents using a given buffer size
-- If another thread changes the current position in the directory file
-- descriptor, the returned list can be corrupted (redundant entries or
-- missing ones)
rec []
where
bufferSize = 2 * 1024 * 1024
-- filter unwanted "directories"
filtr x = nam /= "." && nam /= ".."
where nam = entryName x
rec xs = do
sysGetDirectoryEntries fd bufferSize >>= \case
[] -> return xs
ks -> rec (filter filtr ks ++ xs)
|
hsyl20/ViperVM
|
haskus-system/src/lib/Haskus/System/Linux/FileSystem/Directory.hs
|
bsd-3-clause
| 5,336
| 0
| 20
| 1,443
| 1,169
| 631
| 538
| 119
| 3
|
{-# LANGUAGE OverloadedStrings #-}
module Stashh.Table where
import Stashh.AnsiColor
import Data.Time.Clock.POSIX
import Data.Time.Clock
import Data.Time.Format
import System.Locale
import System.IO.Unsafe
import Control.Applicative
import Data.Maybe
import Data.Monoid
import Data.List (transpose, intercalate, intersperse, stripPrefix)
import Data.Text.ICU.Char
-- a type for records
data A = A { make :: String
, model :: String
, years :: [Int] }
deriving Show
-- a type for fill functions
type Filler = Int -> String -> String
-- a type for describing table columns
data ColDesc t = ColDesc { colTitleFill :: Filler
, colTitle :: String
, colValueFill :: Filler
, colColor :: String -> String
, colValue :: t -> String
}
-- functions that fill a string (s) to a given width (n) by adding pad
-- character (c) to align left, right, or center
fillLeft c n s = s ++ replicate (n - eawLength s) c
fillRight c n s = replicate (n - eawLength s) c ++ s
fillCenter c n s = replicate l c ++ s ++ replicate r c
where x = n - eawLength s
l = x `div` 2
r = x - l
-- functions that fill with spaces
left = fillLeft ' '
right = fillRight ' '
center = fillCenter ' '
-- calculate string width with consideration about EastAsianWidth
eawLength :: String -> Int
eawLength = sum . (map eawWidth) . removeEscapeSequence
eawWidth :: Char -> Int
eawWidth c = case property EastAsianWidth c of
EANeutral -> 1
EAAmbiguous -> 2
EAHalf -> 1
EAFull -> 2
EANarrow -> 1
EAWide -> 2
EACount -> 2
-- converts a list of items into a table according to a list
-- of column descriptors
showTable :: [ColDesc t] -> [t] -> String
showTable cs ts =
let header = map colTitle cs
rows = [[colValue c t | c <- cs] | t <- ts]
widths = [maximum $ map eawLength col | col <- transpose $ header : rows]
separator = intercalate "-+-" [replicate width '-' | width <- widths]
fillCols fill color cols = intercalate " | " [color c $ fill c width col | (c, width, col) <- zip3 cs widths cols]
in
unlines $ fillCols colTitleFill colColor header : separator : map (fillCols colValueFill colColor) rows
class TableDef t where
columnsDef :: [ColDesc t]
renderTable :: (TableDef t) => [t] -> String
renderTable ts = showTable columnsDef ts
class PagingDef t where
paging_start :: t -> Int
paging_size :: t -> Int
paging_limit :: t -> Int
paging_last :: t -> Bool
pagingInfo :: (PagingDef t) => t -> String
pagingInfo t = concat $ intersperse " / " $ map printPair ps
where
printPair p = (fst p) <> ":" <> (snd p)
ps =
[ ("start", show $ paging_start t)
, ("size", show $ paging_size t)
, ("limit", show $ paging_limit t)
, ("isLastPage", show $ paging_last t)
]
showWithMax :: Int -> (t -> String) -> t -> String
showWithMax max f t = foldl appends "" (f t)
where
appends s c = if (((eawLength s) + (eawWidth c)) > max) then s else s <> [c]
showMaybe :: (Show a) => (t -> Maybe a) -> t -> String
showMaybe f t = fromMaybe "" $ show <$> (f t)
showTime :: (t -> Int) -> t -> String
showTime f t = formatTime defaultTimeLocale "%F %X" $ posixSecondsToUTCTime $ time
where
time = ((fromIntegral (f t)) / 1000) :: POSIXTime
showTimeAgo :: (t -> Int) -> t -> String
showTimeAgo f t = case diff of
0 -> "just now"
n | 1 <= n && n <= 59 -> (show n) <> "seconds ago"
n | 60 <= n && n <= 119 -> "1 minute age"
n | 120 <= n && n <= 3540 -> (show $ quot n 60) <> "minutes ago"
n | 3541 <= n && n <= 7100 -> "1 hour ago"
n | 7101 <= n && n <= 82800 -> (show $ quot (n + 99) 3600) <> "hours ago"
n | 82801 <= n && n <= 172000 -> "1 day ago"
n -> (show $ quot (n + 800) 86400) <> "days ago"
where
time = ((fromIntegral (f t)) / 1000) :: POSIXTime
current = unsafePerformIO getPOSIXTime
diff = truncate (current - time)
showRef :: (t -> String) -> t -> String
showRef f t = fromMaybe (f t) $ stripPrefix "refs/heads/" (f t)
showRefWithMax :: Int -> (t -> String) -> t -> String
showRefWithMax max f t = take max $ fromMaybe (f t) $ stripPrefix "refs/heads/" (f t)
|
yuroyoro/stashh
|
src/Stashh/Table.hs
|
bsd-3-clause
| 4,340
| 0
| 14
| 1,211
| 1,570
| 825
| 745
| 93
| 8
|
{-# LANGUAGE DeriveFunctor #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Tests (
tests
, testId
) where
import Control.Applicative
import Data.Increments
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
import Data.IntSet (IntSet)
import qualified Data.IntSet as IntSet
import Data.Map (Map)
import qualified Data.Map as Map
import Test.Framework (Test, testGroup)
import Test.Framework.Providers.QuickCheck2
import Test.QuickCheck
-- test that creating then applying a diff is equivalent to the identity
-- function
testId :: (Incremental a, Eq a) => a -> a -> Bool
testId prev this =
let diff = changes prev this
new = applyChanges prev diff
in this == new
tests :: [Test]
tests =
[ testGroup "primitive types"
[ testProperty "Int" $ idForType pInt
, testProperty "Char" $ idForType pChar
, testProperty "Integer" $ idForType pInteger
]
, testGroup "Tuples"
[ testProperty "(Int,Int)" $ idForType $ pTup pInt pInt
, testProperty "(Int,Char)" $ idForType $ pTup pInt pInt
]
, testProperty "Maybe Int" $ idForType $ pMaybe pInt
, testGroup "Either"
[ testProperty "Either Int Char" $ idForType $ pEither pInt pChar
, testProperty "Either Integer Integer" $ idForType $ pEither pInteger pInteger
]
, testGroup "Containers"
[ testProperty "String" $ idForType $ pList pChar
, testProperty "[Integer]" $ idForType $ pList pInteger
, testProperty "Map String Integer" $ idForType $ pMap (pList pChar) pInteger
, testProperty "IntMap String" $ idForType $ pIntMap (pList pChar)
, testProperty "Set [Int]" $ idForType $ pSet (pList pInt)
, testProperty "IntSet" $ idForType pIntSet
]
]
data Proxy p = Proxy deriving (Functor)
idForType :: (Eq p, Incremental p) => Proxy p -> p -> p -> Bool
idForType _ = testId
pInt :: Proxy Int
pInt = Proxy
pChar :: Proxy Char
pChar = Proxy
pInteger :: Proxy Integer
pInteger = Proxy
pTup :: Proxy a -> Proxy b -> Proxy (a,b)
pTup _ _ = Proxy
pMaybe :: Proxy a -> Proxy (Maybe a)
pMaybe _ = Proxy
pEither :: Proxy a -> Proxy b -> Proxy (Either a b)
pEither _ _ = Proxy
pList :: Proxy a -> Proxy [a]
pList _ = Proxy
pMap :: Proxy a -> Proxy b -> Proxy (Map a b)
pMap _ _ = Proxy
pIntMap :: Proxy a -> Proxy (IntMap a)
pIntMap _ = Proxy
pIntSet :: Proxy (IntSet)
pIntSet = Proxy
pSet :: Proxy a -> Proxy (IntSet)
pSet _ = Proxy
instance (Arbitrary a, Arbitrary b, Ord a) => Arbitrary (Map a b) where
arbitrary = Map.fromList <$> arbitrary
instance (Arbitrary b) => Arbitrary (IntMap b) where
arbitrary = IntMap.fromList <$> arbitrary
instance Arbitrary (IntSet) where
arbitrary = IntSet.fromList <$> arbitrary
|
JohnLato/increments
|
tests/Tests.hs
|
bsd-3-clause
| 2,727
| 0
| 11
| 600
| 913
| 473
| 440
| 72
| 1
|
{-# LANGUAGE DeriveDataTypeable, GeneralizedNewtypeDeriving #-}
module Oracles.LookupInPath (
lookupInPath, lookupInPathOracle
) where
import Base
newtype LookupInPath = LookupInPath String
deriving (Show, Typeable, Eq, Hashable, Binary, NFData)
-- | Fetches the absolute FilePath to a given FilePath from the
-- Oracle.
commandPath :: FilePath -> Action FilePath
commandPath = askOracle . LookupInPath
-- | Lookup a @command@ in @PATH@ environment.
lookupInPath :: FilePath -> Action FilePath
lookupInPath c
| c /= takeFileName c = return c
| otherwise = commandPath c
lookupInPathOracle :: Rules ()
lookupInPathOracle = do
o <- newCache $ \c -> do
envPaths <- wordsWhen (== ':') <$> getEnvWithDefault "" "PATH"
let candidates = map (-/- c) envPaths
-- this will crash if we do not find any valid candidate.
fullCommand <- head <$> filterM doesFileExist candidates
putOracle $ "Found '" ++ c ++ "' at " ++ "'" ++ fullCommand ++ "'"
return fullCommand
_ <- addOracle $ \(LookupInPath c) -> o c
return ()
|
quchen/shaking-up-ghc
|
src/Oracles/LookupInPath.hs
|
bsd-3-clause
| 1,099
| 0
| 17
| 253
| 280
| 140
| 140
| 22
| 1
|
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
-}
module VarEnv (
-- * Var, Id and TyVar environments (maps)
VarEnv, IdEnv, TyVarEnv, CoVarEnv, TyCoVarEnv,
-- ** Manipulating these environments
emptyVarEnv, unitVarEnv, mkVarEnv, mkVarEnv_Directly,
elemVarEnv, varEnvElts,
extendVarEnv, extendVarEnv_C, extendVarEnv_Acc, extendVarEnv_Directly,
extendVarEnvList,
plusVarEnv, plusVarEnv_C, plusVarEnv_CD, alterVarEnv,
delVarEnvList, delVarEnv, delVarEnv_Directly,
minusVarEnv, intersectsVarEnv,
lookupVarEnv, lookupVarEnv_NF, lookupWithDefaultVarEnv,
mapVarEnv, zipVarEnv,
modifyVarEnv, modifyVarEnv_Directly,
isEmptyVarEnv,
elemVarEnvByKey, lookupVarEnv_Directly,
filterVarEnv, filterVarEnv_Directly, restrictVarEnv,
partitionVarEnv,
-- * Deterministic Var environments (maps)
DVarEnv, DIdEnv, DTyVarEnv,
-- ** Manipulating these environments
emptyDVarEnv,
dVarEnvElts,
extendDVarEnv, extendDVarEnv_C,
lookupDVarEnv,
isEmptyDVarEnv, foldDVarEnv,
mapDVarEnv,
modifyDVarEnv,
alterDVarEnv,
plusDVarEnv_C,
unitDVarEnv,
delDVarEnv,
delDVarEnvList,
partitionDVarEnv,
anyDVarEnv,
-- * The InScopeSet type
InScopeSet,
-- ** Operations on InScopeSets
emptyInScopeSet, mkInScopeSet, delInScopeSet,
extendInScopeSet, extendInScopeSetList, extendInScopeSetSet,
getInScopeVars, lookupInScope, lookupInScope_Directly,
unionInScope, elemInScopeSet, uniqAway,
varSetInScope,
-- * The RnEnv2 type
RnEnv2,
-- ** Operations on RnEnv2s
mkRnEnv2, rnBndr2, rnBndrs2, rnBndr2_var,
rnOccL, rnOccR, inRnEnvL, inRnEnvR, rnOccL_maybe, rnOccR_maybe,
rnBndrL, rnBndrR, nukeRnEnvL, nukeRnEnvR, rnSwap,
delBndrL, delBndrR, delBndrsL, delBndrsR,
addRnInScopeSet,
rnEtaL, rnEtaR,
rnInScope, rnInScopeSet, lookupRnInScope,
rnEnvL, rnEnvR,
-- * TidyEnv and its operation
TidyEnv,
emptyTidyEnv
) where
import OccName
import Var
import VarSet
import UniqFM
import UniqDFM
import Unique
import Util
import Maybes
import Outputable
import StaticFlags
{-
************************************************************************
* *
In-scope sets
* *
************************************************************************
-}
-- | A set of variables that are in scope at some point
-- "Secrets of the Glasgow Haskell Compiler inliner" Section 3. provides
-- the motivation for this abstraction.
data InScopeSet = InScope (VarEnv Var) {-# UNPACK #-} !Int
-- The (VarEnv Var) is just a VarSet. But we write it like
-- this to remind ourselves that you can look up a Var in
-- the InScopeSet. Typically the InScopeSet contains the
-- canonical version of the variable (e.g. with an informative
-- unfolding), so this lookup is useful.
--
-- INVARIANT: the VarEnv maps (the Unique of) a variable to
-- a variable with the same Unique. (This was not
-- the case in the past, when we had a grevious hack
-- mapping var1 to var2.
--
-- The Int is a kind of hash-value used by uniqAway
-- For example, it might be the size of the set
-- INVARIANT: it's not zero; we use it as a multiplier in uniqAway
instance Outputable InScopeSet where
ppr (InScope s _) = text "InScope"
<+> braces (fsep (map (ppr . Var.varName) (varSetElems s)))
-- In-scope sets get big, and with -dppr-debug
-- the output is overwhelming
emptyInScopeSet :: InScopeSet
emptyInScopeSet = InScope emptyVarSet 1
getInScopeVars :: InScopeSet -> VarEnv Var
getInScopeVars (InScope vs _) = vs
mkInScopeSet :: VarEnv Var -> InScopeSet
mkInScopeSet in_scope = InScope in_scope 1
extendInScopeSet :: InScopeSet -> Var -> InScopeSet
extendInScopeSet (InScope in_scope n) v = InScope (extendVarEnv in_scope v v) (n + 1)
extendInScopeSetList :: InScopeSet -> [Var] -> InScopeSet
extendInScopeSetList (InScope in_scope n) vs
= InScope (foldl (\s v -> extendVarEnv s v v) in_scope vs)
(n + length vs)
extendInScopeSetSet :: InScopeSet -> VarEnv Var -> InScopeSet
extendInScopeSetSet (InScope in_scope n) vs
= InScope (in_scope `plusVarEnv` vs) (n + sizeUFM vs)
delInScopeSet :: InScopeSet -> Var -> InScopeSet
delInScopeSet (InScope in_scope n) v = InScope (in_scope `delVarEnv` v) n
elemInScopeSet :: Var -> InScopeSet -> Bool
elemInScopeSet v (InScope in_scope _) = v `elemVarEnv` in_scope
-- | Look up a variable the 'InScopeSet'. This lets you map from
-- the variable's identity (unique) to its full value.
lookupInScope :: InScopeSet -> Var -> Maybe Var
lookupInScope (InScope in_scope _) v = lookupVarEnv in_scope v
lookupInScope_Directly :: InScopeSet -> Unique -> Maybe Var
lookupInScope_Directly (InScope in_scope _) uniq
= lookupVarEnv_Directly in_scope uniq
unionInScope :: InScopeSet -> InScopeSet -> InScopeSet
unionInScope (InScope s1 _) (InScope s2 n2)
= InScope (s1 `plusVarEnv` s2) n2
varSetInScope :: VarSet -> InScopeSet -> Bool
varSetInScope vars (InScope s1 _) = vars `subVarSet` s1
-- | @uniqAway in_scope v@ finds a unique that is not used in the
-- in-scope set, and gives that to v.
uniqAway :: InScopeSet -> Var -> Var
-- It starts with v's current unique, of course, in the hope that it won't
-- have to change, and thereafter uses a combination of that and the hash-code
-- found in the in-scope set
uniqAway in_scope var
| var `elemInScopeSet` in_scope = uniqAway' in_scope var -- Make a new one
| otherwise = var -- Nothing to do
uniqAway' :: InScopeSet -> Var -> Var
-- This one *always* makes up a new variable
uniqAway' (InScope set n) var
= try 1
where
orig_unique = getUnique var
try k
| debugIsOn && (k > 1000)
= pprPanic "uniqAway loop:" (ppr k <+> text "tries" <+> ppr var <+> int n)
| uniq `elemVarSetByKey` set = try (k + 1)
| debugIsOn && opt_PprStyle_Debug && (k > 3)
= pprTrace "uniqAway:" (ppr k <+> text "tries" <+> ppr var <+> int n)
setVarUnique var uniq
| otherwise = setVarUnique var uniq
where
uniq = deriveUnique orig_unique (n * k)
{-
************************************************************************
* *
Dual renaming
* *
************************************************************************
-}
-- | When we are comparing (or matching) types or terms, we are faced with
-- \"going under\" corresponding binders. E.g. when comparing:
--
-- > \x. e1 ~ \y. e2
--
-- Basically we want to rename [@x@ -> @y@] or [@y@ -> @x@], but there are lots of
-- things we must be careful of. In particular, @x@ might be free in @e2@, or
-- y in @e1@. So the idea is that we come up with a fresh binder that is free
-- in neither, and rename @x@ and @y@ respectively. That means we must maintain:
--
-- 1. A renaming for the left-hand expression
--
-- 2. A renaming for the right-hand expressions
--
-- 3. An in-scope set
--
-- Furthermore, when matching, we want to be able to have an 'occurs check',
-- to prevent:
--
-- > \x. f ~ \y. y
--
-- matching with [@f@ -> @y@]. So for each expression we want to know that set of
-- locally-bound variables. That is precisely the domain of the mappings 1.
-- and 2., but we must ensure that we always extend the mappings as we go in.
--
-- All of this information is bundled up in the 'RnEnv2'
data RnEnv2
= RV2 { envL :: VarEnv Var -- Renaming for Left term
, envR :: VarEnv Var -- Renaming for Right term
, in_scope :: InScopeSet } -- In scope in left or right terms
-- The renamings envL and envR are *guaranteed* to contain a binding
-- for every variable bound as we go into the term, even if it is not
-- renamed. That way we can ask what variables are locally bound
-- (inRnEnvL, inRnEnvR)
mkRnEnv2 :: InScopeSet -> RnEnv2
mkRnEnv2 vars = RV2 { envL = emptyVarEnv
, envR = emptyVarEnv
, in_scope = vars }
addRnInScopeSet :: RnEnv2 -> VarEnv Var -> RnEnv2
addRnInScopeSet env vs
| isEmptyVarEnv vs = env
| otherwise = env { in_scope = extendInScopeSetSet (in_scope env) vs }
rnInScope :: Var -> RnEnv2 -> Bool
rnInScope x env = x `elemInScopeSet` in_scope env
rnInScopeSet :: RnEnv2 -> InScopeSet
rnInScopeSet = in_scope
-- | Retrieve the left mapping
rnEnvL :: RnEnv2 -> VarEnv Var
rnEnvL = envL
-- | Retrieve the right mapping
rnEnvR :: RnEnv2 -> VarEnv Var
rnEnvR = envR
rnBndrs2 :: RnEnv2 -> [Var] -> [Var] -> RnEnv2
-- ^ Applies 'rnBndr2' to several variables: the two variable lists must be of equal length
rnBndrs2 env bsL bsR = foldl2 rnBndr2 env bsL bsR
rnBndr2 :: RnEnv2 -> Var -> Var -> RnEnv2
-- ^ @rnBndr2 env bL bR@ goes under a binder @bL@ in the Left term,
-- and binder @bR@ in the Right term.
-- It finds a new binder, @new_b@,
-- and returns an environment mapping @bL -> new_b@ and @bR -> new_b@
rnBndr2 env bL bR = fst $ rnBndr2_var env bL bR
rnBndr2_var :: RnEnv2 -> Var -> Var -> (RnEnv2, Var)
-- ^ Similar to 'rnBndr2' but returns the new variable as well as the
-- new environment
rnBndr2_var (RV2 { envL = envL, envR = envR, in_scope = in_scope }) bL bR
= (RV2 { envL = extendVarEnv envL bL new_b -- See Note
, envR = extendVarEnv envR bR new_b -- [Rebinding]
, in_scope = extendInScopeSet in_scope new_b }, new_b)
where
-- Find a new binder not in scope in either term
new_b | not (bL `elemInScopeSet` in_scope) = bL
| not (bR `elemInScopeSet` in_scope) = bR
| otherwise = uniqAway' in_scope bL
-- Note [Rebinding]
-- If the new var is the same as the old one, note that
-- the extendVarEnv *deletes* any current renaming
-- E.g. (\x. \x. ...) ~ (\y. \z. ...)
--
-- Inside \x \y { [x->y], [y->y], {y} }
-- \x \z { [x->x], [y->y, z->x], {y,x} }
rnBndrL :: RnEnv2 -> Var -> (RnEnv2, Var)
-- ^ Similar to 'rnBndr2' but used when there's a binder on the left
-- side only.
rnBndrL (RV2 { envL = envL, envR = envR, in_scope = in_scope }) bL
= (RV2 { envL = extendVarEnv envL bL new_b
, envR = envR
, in_scope = extendInScopeSet in_scope new_b }, new_b)
where
new_b = uniqAway in_scope bL
rnBndrR :: RnEnv2 -> Var -> (RnEnv2, Var)
-- ^ Similar to 'rnBndr2' but used when there's a binder on the right
-- side only.
rnBndrR (RV2 { envL = envL, envR = envR, in_scope = in_scope }) bR
= (RV2 { envR = extendVarEnv envR bR new_b
, envL = envL
, in_scope = extendInScopeSet in_scope new_b }, new_b)
where
new_b = uniqAway in_scope bR
rnEtaL :: RnEnv2 -> Var -> (RnEnv2, Var)
-- ^ Similar to 'rnBndrL' but used for eta expansion
-- See Note [Eta expansion]
rnEtaL (RV2 { envL = envL, envR = envR, in_scope = in_scope }) bL
= (RV2 { envL = extendVarEnv envL bL new_b
, envR = extendVarEnv envR new_b new_b -- Note [Eta expansion]
, in_scope = extendInScopeSet in_scope new_b }, new_b)
where
new_b = uniqAway in_scope bL
rnEtaR :: RnEnv2 -> Var -> (RnEnv2, Var)
-- ^ Similar to 'rnBndr2' but used for eta expansion
-- See Note [Eta expansion]
rnEtaR (RV2 { envL = envL, envR = envR, in_scope = in_scope }) bR
= (RV2 { envL = extendVarEnv envL new_b new_b -- Note [Eta expansion]
, envR = extendVarEnv envR bR new_b
, in_scope = extendInScopeSet in_scope new_b }, new_b)
where
new_b = uniqAway in_scope bR
delBndrL, delBndrR :: RnEnv2 -> Var -> RnEnv2
delBndrL rn@(RV2 { envL = env, in_scope = in_scope }) v
= rn { envL = env `delVarEnv` v, in_scope = in_scope `extendInScopeSet` v }
delBndrR rn@(RV2 { envR = env, in_scope = in_scope }) v
= rn { envR = env `delVarEnv` v, in_scope = in_scope `extendInScopeSet` v }
delBndrsL, delBndrsR :: RnEnv2 -> [Var] -> RnEnv2
delBndrsL rn@(RV2 { envL = env, in_scope = in_scope }) v
= rn { envL = env `delVarEnvList` v, in_scope = in_scope `extendInScopeSetList` v }
delBndrsR rn@(RV2 { envR = env, in_scope = in_scope }) v
= rn { envR = env `delVarEnvList` v, in_scope = in_scope `extendInScopeSetList` v }
rnOccL, rnOccR :: RnEnv2 -> Var -> Var
-- ^ Look up the renaming of an occurrence in the left or right term
rnOccL (RV2 { envL = env }) v = lookupVarEnv env v `orElse` v
rnOccR (RV2 { envR = env }) v = lookupVarEnv env v `orElse` v
rnOccL_maybe, rnOccR_maybe :: RnEnv2 -> Var -> Maybe Var
-- ^ Look up the renaming of an occurrence in the left or right term
rnOccL_maybe (RV2 { envL = env }) v = lookupVarEnv env v
rnOccR_maybe (RV2 { envR = env }) v = lookupVarEnv env v
inRnEnvL, inRnEnvR :: RnEnv2 -> Var -> Bool
-- ^ Tells whether a variable is locally bound
inRnEnvL (RV2 { envL = env }) v = v `elemVarEnv` env
inRnEnvR (RV2 { envR = env }) v = v `elemVarEnv` env
lookupRnInScope :: RnEnv2 -> Var -> Var
lookupRnInScope env v = lookupInScope (in_scope env) v `orElse` v
nukeRnEnvL, nukeRnEnvR :: RnEnv2 -> RnEnv2
-- ^ Wipe the left or right side renaming
nukeRnEnvL env = env { envL = emptyVarEnv }
nukeRnEnvR env = env { envR = emptyVarEnv }
rnSwap :: RnEnv2 -> RnEnv2
-- ^ swap the meaning of left and right
rnSwap (RV2 { envL = envL, envR = envR, in_scope = in_scope })
= RV2 { envL = envR, envR = envL, in_scope = in_scope }
{-
Note [Eta expansion]
~~~~~~~~~~~~~~~~~~~~
When matching
(\x.M) ~ N
we rename x to x' with, where x' is not in scope in
either term. Then we want to behave as if we'd seen
(\x'.M) ~ (\x'.N x')
Since x' isn't in scope in N, the form (\x'. N x') doesn't
capture any variables in N. But we must nevertheless extend
the envR with a binding [x' -> x'], to support the occurs check.
For example, if we don't do this, we can get silly matches like
forall a. (\y.a) ~ v
succeeding with [a -> v y], which is bogus of course.
************************************************************************
* *
Tidying
* *
************************************************************************
-}
-- | When tidying up print names, we keep a mapping of in-scope occ-names
-- (the 'TidyOccEnv') and a Var-to-Var of the current renamings
type TidyEnv = (TidyOccEnv, VarEnv Var)
emptyTidyEnv :: TidyEnv
emptyTidyEnv = (emptyTidyOccEnv, emptyVarEnv)
{-
************************************************************************
* *
\subsection{@VarEnv@s}
* *
************************************************************************
-}
type VarEnv elt = UniqFM elt
type IdEnv elt = VarEnv elt
type TyVarEnv elt = VarEnv elt
type TyCoVarEnv elt = VarEnv elt
type CoVarEnv elt = VarEnv elt
emptyVarEnv :: VarEnv a
mkVarEnv :: [(Var, a)] -> VarEnv a
mkVarEnv_Directly :: [(Unique, a)] -> VarEnv a
zipVarEnv :: [Var] -> [a] -> VarEnv a
unitVarEnv :: Var -> a -> VarEnv a
alterVarEnv :: (Maybe a -> Maybe a) -> VarEnv a -> Var -> VarEnv a
extendVarEnv :: VarEnv a -> Var -> a -> VarEnv a
extendVarEnv_C :: (a->a->a) -> VarEnv a -> Var -> a -> VarEnv a
extendVarEnv_Acc :: (a->b->b) -> (a->b) -> VarEnv b -> Var -> a -> VarEnv b
extendVarEnv_Directly :: VarEnv a -> Unique -> a -> VarEnv a
plusVarEnv :: VarEnv a -> VarEnv a -> VarEnv a
extendVarEnvList :: VarEnv a -> [(Var, a)] -> VarEnv a
lookupVarEnv_Directly :: VarEnv a -> Unique -> Maybe a
filterVarEnv_Directly :: (Unique -> a -> Bool) -> VarEnv a -> VarEnv a
delVarEnv_Directly :: VarEnv a -> Unique -> VarEnv a
partitionVarEnv :: (a -> Bool) -> VarEnv a -> (VarEnv a, VarEnv a)
restrictVarEnv :: VarEnv a -> VarSet -> VarEnv a
delVarEnvList :: VarEnv a -> [Var] -> VarEnv a
delVarEnv :: VarEnv a -> Var -> VarEnv a
minusVarEnv :: VarEnv a -> VarEnv b -> VarEnv a
intersectsVarEnv :: VarEnv a -> VarEnv a -> Bool
plusVarEnv_C :: (a -> a -> a) -> VarEnv a -> VarEnv a -> VarEnv a
plusVarEnv_CD :: (a -> a -> a) -> VarEnv a -> a -> VarEnv a -> a -> VarEnv a
mapVarEnv :: (a -> b) -> VarEnv a -> VarEnv b
modifyVarEnv :: (a -> a) -> VarEnv a -> Var -> VarEnv a
varEnvElts :: VarEnv a -> [a]
isEmptyVarEnv :: VarEnv a -> Bool
lookupVarEnv :: VarEnv a -> Var -> Maybe a
filterVarEnv :: (a -> Bool) -> VarEnv a -> VarEnv a
lookupVarEnv_NF :: VarEnv a -> Var -> a
lookupWithDefaultVarEnv :: VarEnv a -> a -> Var -> a
elemVarEnv :: Var -> VarEnv a -> Bool
elemVarEnvByKey :: Unique -> VarEnv a -> Bool
elemVarEnv = elemUFM
elemVarEnvByKey = elemUFM_Directly
alterVarEnv = alterUFM
extendVarEnv = addToUFM
extendVarEnv_C = addToUFM_C
extendVarEnv_Acc = addToUFM_Acc
extendVarEnv_Directly = addToUFM_Directly
extendVarEnvList = addListToUFM
plusVarEnv_C = plusUFM_C
plusVarEnv_CD = plusUFM_CD
delVarEnvList = delListFromUFM
delVarEnv = delFromUFM
minusVarEnv = minusUFM
intersectsVarEnv e1 e2 = not (isEmptyVarEnv (e1 `intersectUFM` e2))
plusVarEnv = plusUFM
lookupVarEnv = lookupUFM
filterVarEnv = filterUFM
lookupWithDefaultVarEnv = lookupWithDefaultUFM
mapVarEnv = mapUFM
mkVarEnv = listToUFM
mkVarEnv_Directly= listToUFM_Directly
emptyVarEnv = emptyUFM
varEnvElts = eltsUFM
unitVarEnv = unitUFM
isEmptyVarEnv = isNullUFM
lookupVarEnv_Directly = lookupUFM_Directly
filterVarEnv_Directly = filterUFM_Directly
delVarEnv_Directly = delFromUFM_Directly
partitionVarEnv = partitionUFM
restrictVarEnv env vs = filterVarEnv_Directly keep env
where
keep u _ = u `elemVarSetByKey` vs
zipVarEnv tyvars tys = mkVarEnv (zipEqual "zipVarEnv" tyvars tys)
lookupVarEnv_NF env id = case lookupVarEnv env id of
Just xx -> xx
Nothing -> panic "lookupVarEnv_NF: Nothing"
{-
@modifyVarEnv@: Look up a thing in the VarEnv,
then mash it with the modify function, and put it back.
-}
modifyVarEnv mangle_fn env key
= case (lookupVarEnv env key) of
Nothing -> env
Just xx -> extendVarEnv env key (mangle_fn xx)
modifyVarEnv_Directly :: (a -> a) -> UniqFM a -> Unique -> UniqFM a
modifyVarEnv_Directly mangle_fn env key
= case (lookupUFM_Directly env key) of
Nothing -> env
Just xx -> addToUFM_Directly env key (mangle_fn xx)
-- Deterministic VarEnv
-- See Note [Deterministic UniqFM] in UniqDFM for explanation why we need
-- DVarEnv.
type DVarEnv elt = UniqDFM elt
type DIdEnv elt = DVarEnv elt
type DTyVarEnv elt = DVarEnv elt
emptyDVarEnv :: DVarEnv a
emptyDVarEnv = emptyUDFM
dVarEnvElts :: DVarEnv a -> [a]
dVarEnvElts = eltsUDFM
extendDVarEnv :: DVarEnv a -> Var -> a -> DVarEnv a
extendDVarEnv = addToUDFM
lookupDVarEnv :: DVarEnv a -> Var -> Maybe a
lookupDVarEnv = lookupUDFM
foldDVarEnv :: (a -> b -> b) -> b -> DVarEnv a -> b
foldDVarEnv = foldUDFM
mapDVarEnv :: (a -> b) -> DVarEnv a -> DVarEnv b
mapDVarEnv = mapUDFM
alterDVarEnv :: (Maybe a -> Maybe a) -> DVarEnv a -> Var -> DVarEnv a
alterDVarEnv = alterUDFM
plusDVarEnv_C :: (a -> a -> a) -> DVarEnv a -> DVarEnv a -> DVarEnv a
plusDVarEnv_C = plusUDFM_C
unitDVarEnv :: Var -> a -> DVarEnv a
unitDVarEnv = unitUDFM
delDVarEnv :: DVarEnv a -> Var -> DVarEnv a
delDVarEnv = delFromUDFM
delDVarEnvList :: DVarEnv a -> [Var] -> DVarEnv a
delDVarEnvList = delListFromUDFM
isEmptyDVarEnv :: DVarEnv a -> Bool
isEmptyDVarEnv = isNullUDFM
extendDVarEnv_C :: (a -> a -> a) -> DVarEnv a -> Var -> a -> DVarEnv a
extendDVarEnv_C = addToUDFM_C
modifyDVarEnv :: (a -> a) -> DVarEnv a -> Var -> DVarEnv a
modifyDVarEnv mangle_fn env key
= case (lookupDVarEnv env key) of
Nothing -> env
Just xx -> extendDVarEnv env key (mangle_fn xx)
partitionDVarEnv :: (a -> Bool) -> DVarEnv a -> (DVarEnv a, DVarEnv a)
partitionDVarEnv = partitionUDFM
anyDVarEnv :: (a -> Bool) -> DVarEnv a -> Bool
anyDVarEnv = anyUDFM
|
vikraman/ghc
|
compiler/basicTypes/VarEnv.hs
|
bsd-3-clause
| 20,922
| 0
| 14
| 5,513
| 4,643
| 2,563
| 2,080
| 314
| 2
|
{-# LANGUAGE GADTs #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeOperators #-}
{-|
Module: Control.Remote.Haxl
Copyright: (C) 2016, The University of Kansas
License: BSD-style (see the file LICENSE)
Maintainer: Justin Dawson (jdawson@ku.edu)
Stability: Alpha
Portability: GHC
-}
module Control.Remote.Haxl
( -- * Remote Haxl
RemoteHaxlMonad
-- * The primitive lift function
, query
-- * The run functions
, RunHaxlMonad(runHaxlMonad)
, runWeakMonad
, runApplicativeMonad
) where
import Control.Monad.Trans.Class
import Control.Monad.Trans.State.Strict
import qualified Control.Remote.Applicative as A
import Control.Remote.Packet.Applicative as A
import Control.Remote.Packet.Weak as Weak
import Control.Remote.Haxl.Types as T
import Control.Applicative
import Control.Remote.Applicative.Types as T
import Control.Monad
import Control.Natural
import Debug.Trace
-- | promote a procedure into the remote monad
query :: q a -> RemoteHaxlMonad q a
query = Appl . A.query
-- | 'RunHaxlMonad' is the overloading for choosing the appropriate bundling strategy for a monad.
class RunHaxlMonad f where
-- | This overloaded function chooses the appropriate bundling strategy
-- based on the type of the handler your provide.
runHaxlMonad :: (Monad m) => (f q :~> m) -> (RemoteHaxlMonad q :~> m)
instance RunHaxlMonad WeakPacket where
runHaxlMonad = runWeakMonad
instance RunHaxlMonad ApplicativePacket where
runHaxlMonad = runApplicativeMonad
-- | This is a remote monad combinator, that takes an implementation
-- of a remote applicative, splits the monad into applicatives
-- without any merge stragegy, and uses the remote applicative.
-- Every '>>=' will generate a call to the 'RemoteHaxlApplicative'
-- handler; as well as one terminating call.
-- Using 'runBindeeMonad' with a 'runWeakApplicative' gives the weakest remote monad.
runMonadSkeleton :: (Monad m) => (RemoteHaxlApplicative q :~> m) -> (RemoteHaxlMonad q :~> m)
runMonadSkeleton f = wrapNT $ \ case
Appl g -> unwrapNT f g
Bind g k -> (runMonadSkeleton f # g) >>= \ a -> runMonadSkeleton f # (k a)
Ap' g h -> (runMonadSkeleton f # g) <*> (runMonadSkeleton f # h)
-- | This is the classic weak remote monad, or technically the
-- weak remote applicative weak remote monad.
runWeakMonad :: (Monad m) => (WeakPacket q :~> m) -> (RemoteHaxlMonad q :~> m)
runWeakMonad = runMonadSkeleton . A.runHaxlWeakApplicative
-- | The is the strong applicative strong remote monad. It bundles
-- packets (of type 'RemoteHaxlApplicative') as large as possible,
-- including over some monadic binds.
runApplicativeMonad :: forall m q . (Monad m) => (A.ApplicativePacket q :~> m) -> (RemoteHaxlMonad q :~> m)
runApplicativeMonad (NT rf) = wrapNT $ \ p -> do
(r,h) <- runStateT (go2 (helper p)) (pure ())
rf $ pk $ h -- should we stub out the call with only 'Pure'?
return r
where
go2 :: forall a . RemoteHaxlMonad q a -> StateT (T.RemoteHaxlApplicative q ()) m a
go2 (Appl app) = go app
go2 (Bind app k) = go2 app >>= \ a -> go2 (k a)
go2 (Ap' x y) = go2 x <*> go2 y
go :: forall a . T.RemoteHaxlApplicative q a -> StateT (T.RemoteHaxlApplicative q ()) m a
go ap = case superApplicative ap of
Nothing -> do
ap' <- get
put (pure ())
lift $ rf $ (pk (ap' *> ap))
Just a -> do
modify (\ ap' -> ap' <* ap)
return a
superApplicative :: T.RemoteHaxlApplicative q a -> Maybe a
superApplicative (T.Pure a) = pure a
superApplicative (T.Query p) = Nothing
superApplicative (T.Ap g h) = superApplicative g <*> superApplicative h
-- It all comes down to this. Converting quickly between T.RemoteHaxlApplicative and ApplicativePacket.
pk :: T.RemoteHaxlApplicative q a -> ApplicativePacket q a
pk (T.Pure a) = A.Pure a
pk (T.Query q) = A.Query q
pk (T.Ap g h) = A.Zip ($) (pk g) (pk h)
helper:: RemoteHaxlMonad q a -> RemoteHaxlMonad q a
helper (Ap' x@(Ap' _ _) y@(Ap' _ _)) = trace "1" $ helper x <*> helper y
helper (Ap' (Bind m1 k1) (Bind m2 k2) ) = trace "2" $ liftA2 (,) (helper m1) (helper m2) >>= \(x1,x2) ->helper ( k1 x1) <*> helper (k2 x2)
helper (Ap' (Bind m1 k1) app) = trace "3" $ liftA2 (,) (helper m1) (helper app) >>= \(x1,x2) -> helper (k1 x1) <*> (pure x2)
helper (Ap' (Ap' app (Bind m1 k1)) (Bind m2 k2)) = trace "4" $ liftA3 (,,) (helper app) (helper m1) (helper m2) >>= \(x1,x2,x3) -> (pure x1 <*> k1 x2) <*> helper (k2 x3)
helper (Bind m k) = trace "5" $ (helper m) >>= \ x -> helper (k x)
helper x = x
|
jtdawso/remote-haxl
|
src/Control/Remote/Haxl.hs
|
bsd-3-clause
| 4,843
| 0
| 16
| 1,161
| 1,433
| 747
| 686
| 74
| 13
|
{-# LANGUAGE OverloadedStrings #-}
module Variants where
import Types (
Repository,
Package(Package),
Version(Version),VersionNode,
Variant(Variant),VariantNode,
PackageDescription,Configuration(Configuration),
FinalizedPackageDescription)
import Web.Neo (NeoT,newNode,addNodeLabel,setNodeProperty,newEdge)
import Database.PipesGremlin (PG,scatter)
import Data.Aeson (toJSON)
import qualified Data.Version as V (Version(Version))
import Distribution.PackageDescription (FlagAssignment)
import Distribution.PackageDescription.Parse (readPackageDescription)
import Distribution.PackageDescription.Configuration (finalizePackageDescription)
import Distribution.Verbosity (silent)
import Distribution.System (Platform(Platform),Arch(I386),OS(Linux))
import Distribution.Compiler (CompilerId(CompilerId),CompilerFlavor(GHC))
import Distribution.Package (Dependency)
import Control.Monad (forM)
import Control.Monad.IO.Class (MonadIO,liftIO)
import Control.Monad.Trans (lift)
import Data.Map ((!))
variantPG :: (MonadIO m) => Repository -> (Version,VersionNode) -> PG m (Variant,VariantNode)
variantPG repository (version,versionnode) = do
variant@(Variant _ configuration) <- variants repository version >>= scatter
variantnode <- lift (insertVariant configuration versionnode)
return (variant,variantnode)
variants :: (MonadIO m) => Repository -> Version -> m [Variant]
variants repository version = do
description <- loadPackageDescription repository version
forM (configurations description) (\configuration ->
return (Variant version configuration))
loadPackageDescription :: (MonadIO m) => Repository -> Version -> m PackageDescription
loadPackageDescription repository version = do
let (Version (Package packagename) versionnumber) = version
packagedirectory = repository ! packagename ! versionnumber
cabalfilepath = packagedirectory ++ packagename ++ ".cabal"
liftIO (readPackageDescription silent cabalfilepath)
configurations :: PackageDescription -> [Configuration]
configurations packagedescription = case cabalConfigure packagedescription of
Left _ ->
[]
Right (_,flagassignment) ->
[Configuration flagassignment defaultPlatform defaultCompiler]
defaultPlatform :: Platform
defaultPlatform = Platform I386 Linux
defaultCompiler :: CompilerId
defaultCompiler = CompilerId GHC (V.Version [7,6,3] [])
cabalConfigure :: PackageDescription -> Either [Dependency] (FinalizedPackageDescription,FlagAssignment)
cabalConfigure = finalizePackageDescription [] (const True) defaultPlatform defaultCompiler []
insertVariant :: (Monad m) => Configuration -> VersionNode -> NeoT m VariantNode
insertVariant configuration versionnode = do
variantnode <- newNode
addNodeLabel "Variant" variantnode
setNodeProperty "configuration" (toJSON (show configuration)) variantnode
_ <- newEdge "VARIANT" versionnode variantnode
return variantnode
|
phischu/cabal-analysis
|
src/Variants.hs
|
bsd-3-clause
| 2,967
| 0
| 13
| 400
| 815
| 450
| 365
| 59
| 2
|
{-# LANGUAGE OverloadedStrings #-}
module LocalDiscoverySpec where
import Test.Hspec
import Ssb.Discovery
import Ssb.Address
import Ssb.Key
import Data.Maybe
import Data.ByteString
peerDiscoveryMessage = "net:192.168.25.11:8008~shs:opBinLmYiID9SMEoZJPH60LmduSYAR7J00P7/Gj9vHw="
spec :: Spec
spec =
describe "LocalPeerDiscovery" $ do
it "should be able to parse a local peer discovery broadcast message" $ do
let (Just discovery) = parseDiscoveryMessage peerDiscoveryMessage
(address discovery) `shouldBe` (Address "192.168.25.11" 8008)
(exportPublicKey $ publicKey discovery) `shouldBe` "opBinLmYiID9SMEoZJPH60LmduSYAR7J00P7/Gj9vHw="
|
bkil-syslogng/haskell-scuttlebutt
|
test/LocalDiscoverySpec.hs
|
bsd-3-clause
| 662
| 0
| 15
| 91
| 128
| 68
| 60
| 16
| 1
|
-- ------------------------------------------------------------
{- |
Module : Yuuko.Text.XML.HXT.DOM.MimeTypes
Copyright : Copyright (C) 2008 Uwe Schmidt
License : MIT
Maintainer : Uwe Schmidt (uwe@fh-wedel.de)
Stability : experimental
Portability: portable
mime type related data and functions
-}
-- ------------------------------------------------------------
module Yuuko.Text.XML.HXT.DOM.MimeTypes
where
import Control.Monad ( mplus )
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as C
import Data.Char
import Data.List
import qualified Data.Map as M
import Data.Maybe
import Yuuko.Text.XML.HXT.DOM.MimeTypeDefaults
-- ------------------------------------------------------------
type MimeTypeTable = M.Map String String
-- ------------------------------------------------------------
-- mime types
--
-- see RFC \"http:\/\/www.rfc-editor.org\/rfc\/rfc3023.txt\"
application_xhtml,
application_xml,
application_xml_external_parsed_entity,
application_xml_dtd,
text_html,
text_xml,
text_xml_external_parsed_entity :: String
application_xhtml = "application/xhtml+xml"
application_xml = "application/xml"
application_xml_external_parsed_entity = "application/xml-external-parsed-entity"
application_xml_dtd = "application/xml-dtd"
text_html = "text/html"
text_xml = "text/xml"
text_xml_external_parsed_entity = "text/xml-external-parsed-entity"
isTextMimeType :: String -> Bool
isTextMimeType = ("text/" `isPrefixOf`)
isHtmlMimeType :: String -> Bool
isHtmlMimeType t = t == text_html
isXmlMimeType :: String -> Bool
isXmlMimeType t = ( t `elem` [ application_xhtml
, application_xml
, application_xml_external_parsed_entity
, application_xml_dtd
, text_xml
, text_xml_external_parsed_entity
]
||
"+xml" `isSuffixOf` t -- application/mathml+xml
) -- or image/svg+xml
defaultMimeTypeTable :: MimeTypeTable
defaultMimeTypeTable = M.fromList mimeTypeDefaults
extensionToMimeType :: String -> MimeTypeTable -> String
extensionToMimeType e = fromMaybe "" . lookupMime
where
lookupMime t = M.lookup e t -- try exact match
`mplus`
M.lookup (map toLower e) t -- else try lowercase match
`mplus`
M.lookup (map toUpper e) t -- else try uppercase match
-- ------------------------------------------------------------
readMimeTypeTable :: FilePath -> IO MimeTypeTable
readMimeTypeTable inp = do
cb <- B.readFile inp
return . M.fromList . parseMimeTypeTable . C.unpack $ cb
parseMimeTypeTable :: String -> [(String, String)]
parseMimeTypeTable = concat
. map buildPairs
. map words
. filter (not . ("#" `isPrefixOf`))
. filter (not . all (isSpace))
. lines
where
buildPairs :: [String] -> [(String, String)]
buildPairs [] = []
buildPairs (mt:exts) = map (\ x -> (x, mt)) $ exts
-- ------------------------------------------------------------
|
nfjinjing/yuuko
|
src/Yuuko/Text/XML/HXT/DOM/MimeTypes.hs
|
bsd-3-clause
| 3,134
| 78
| 11
| 673
| 631
| 365
| 266
| 60
| 2
|
{- |
Copyright: 2002, Simon Marlow.
Copyright: 2006, Bjorn Bringert.
Copyright: 2009, Henning Thielemann.
-}
module Network.MoHWS.Part.UserDirectory (Configuration, desc, ) where
import qualified Network.MoHWS.Module as Module
import qualified Network.MoHWS.Module.Description as ModuleDesc
import qualified Network.MoHWS.Server.Context as ServerContext
import Network.MoHWS.Logger.Error (debug, )
import qualified Network.MoHWS.Configuration as Config
import qualified Network.MoHWS.Configuration.Accessor as ConfigA
import qualified Network.MoHWS.Configuration.Parser as ConfigParser
import qualified Data.Accessor.Basic as Accessor
import Data.Accessor.Basic ((.>))
import Control.Monad (mzero, guard, )
import Control.Monad.Trans.Maybe (MaybeT(MaybeT), )
import System.IO.Error (catchIOError, )
import System.Posix (homeDirectory, getUserEntryForName, )
desc :: ModuleDesc.T body Configuration
desc =
ModuleDesc.empty {
ModuleDesc.name = "userdirectory",
ModuleDesc.load = return . funs,
ModuleDesc.configParser = parser,
ModuleDesc.setDefltConfig = const defltConfig
}
data Configuration =
Configuration {
userDir_ :: String
}
defltConfig :: Configuration
defltConfig =
Configuration {
userDir_ = ""
}
userDir :: Accessor.T Configuration String
userDir =
Accessor.fromSetGet (\x c -> c{userDir_ = x}) userDir_
parser :: ConfigParser.T st Configuration
parser =
ConfigParser.field "userdirectory" p_userDir
p_userDir :: ConfigParser.T st Configuration
p_userDir =
ConfigParser.set (ConfigA.extension .> userDir) $ ConfigParser.stringLiteral
funs :: ServerContext.T Configuration -> Module.T body
funs st =
Module.empty {
Module.translatePath = translatePath st
}
translatePath :: ServerContext.T Configuration -> String -> String -> MaybeT IO FilePath
translatePath st _host ('/':'~':userpath) =
do let conf = ServerContext.config st
(usr, path) = break (=='/') userpath
dir = userDir_ $ Config.extension conf
guard $ not $ null $ dir
debug st $ "looking for user: " ++ show usr
ent <-
MaybeT $ flip catchIOError (const $ return Nothing) $
fmap Just (getUserEntryForName usr)
let p = '/': homeDirectory ent ++ '/':dir ++ path
debug st $ "userdir path: " ++ p
return p
translatePath _ _ _ = mzero
|
xpika/mohws
|
src/Network/MoHWS/Part/UserDirectory.hs
|
bsd-3-clause
| 2,354
| 0
| 14
| 428
| 638
| 361
| 277
| 55
| 1
|
{-# LANGUAGE
TypeOperators
, OverloadedStrings
#-}
module Xml.Tonic.Transform
( (:~>)
, construct
, destruct
, transform
)
where
import Control.Arrow.List
import Control.Category
import Data.Text.Lazy (Text)
import Prelude hiding ((.), id)
import Xml.Tonic.Arrow
import Xml.Tonic.Types (Node)
import qualified Data.Text.Lazy as T
-- | Prettier way to write down the ListArrow type.
type a :~> b = ListArrow a b
-- | Construct an XML representation from some value using a list arrow.
construct :: (a :~> Node) -> a -> Text
construct tr = T.concat . runListArrow (printXml . tr)
-- | Destruct an XML representation to some values using a list arrow.
--
-- For example, if you want to select the 'src' attributes for all the 'img'
-- tags in your XML document you can use the following construction:
--
-- > sources :: Text -> [Text]
-- > sources = destruct (deep (attr "src" . elem "img") . isElem)
-- >
-- > ghci> :set -XOverloadedStrings
-- > ghci> sources "<div><img src=a.png/><a><img src=b.jpg/></a></div>"
-- > ["a.png","b.jpg"]
destruct :: (Node :~> a) -> Text -> [a]
destruct tr = runListArrow (tr . parseXml)
-- | Transform an XML representation using a list arrow.
transform :: (Node :~> Node) -> Text -> Text
transform tr = T.concat . runListArrow (printXml . tr . parseXml)
-- renameULs :: Text -> Text
-- renameULs = transform (elemNode . processTopDownWhen id remove . isElem)
-- where remove = filterA (notA (isA (=="ul") . name))
-- test = renameULs "<div><ul><li>hallo</li><li/></ul><p><ul/></p></div>"
-- test = renameULs "<div><ol><li>hallo</li><li/></ol><p><ol/></p></div>"
|
sebastiaanvisser/tonic
|
src/Xml/Tonic/Transform.hs
|
bsd-3-clause
| 1,636
| 0
| 9
| 294
| 252
| 156
| 96
| 22
| 1
|
--{-# LANGUAGE TypeFamilies #-}
module ExistentialFamilies where
import Control.Monad.ST (runST,ST)
un :: ()
un = runST f where
f = return un :: ST s ()
|
phischu/fragnix
|
tests/quick/ExistentialFamilies/ExistentialFamilies.hs
|
bsd-3-clause
| 159
| 0
| 8
| 32
| 54
| 31
| 23
| 5
| 1
|
{-#LANGUAGE MagicHash, TemplateHaskell, DeriveDataTypeable, StandaloneDeriving, GeneralizedNewtypeDeriving #-}
-- BangPatterns, ScopedTypeVariables, ViewPatterns, KindSignatures
import Language.Haskell.TH.Syntax
( Exp(..), Pat(..), Stmt(..), Type(..), Dec(..),
Range(..), Lit(..), Kind(..),
Body(..), Guard(..), Con(..), Match(..),
Name(..), mkName, NameFlavour(..), NameSpace(..),
Clause(..), Pragma(..), FamFlavour(..),
Pred(..), TyVarBndr(..),
Foreign, Callconv(..), FunDep(..),
Safety(..), Strict(..), InlineSpec(..))
-- testing-feat
import Test.Feat
import Test.Feat.Access
import Test.Feat.Modifiers
-- template-haskell
import Language.Haskell.TH.Syntax.Internals(OccName(OccName), ModName(ModName), PkgName)
import Language.Haskell.TH.Ppr(pprint,Ppr)
-- haskell-src-meta
import Language.Haskell.Meta(toExp)
-- haskell-src-exts
import qualified Language.Haskell.Exts as E
-- quickcheck
import Test.QuickCheck hiding (NonEmpty, (><))
--base
import Data.Typeable(Typeable)
import Data.Ord
import Data.List
-- smallcheck
import Test.SmallCheck.Series hiding (Nat)
import Test.SmallCheck
{-
-- Currently both of these spit out a lot of errors unless we disable a few of the
-- buggier constructors (which we have done below).
test_parsesAll = ioAll 15 report_parses
-- | Test (at most) 10000 values of each size up to size 100.
test_parsesBounded = ioBounded 10000 100 report_parses
test_parsesBounded' = ioFeat (boundedWith enumerate 1000) report_parses
report_parses e = case prop_parsesM e of
Nothing -> return ()
Just s -> do
putStrLn "Failure:"
putStrLn (pprint e)
print e
putStrLn s
putStrLn ""
prop_parsesM e = case myParse $ pprint (e :: Exp) :: E.ParseResult E.Exp of
E.ParseOk _ -> Nothing
E.ParseFailed _ s -> Just s
test_cycleAll = ioAll 15 report_cycle
test_cycleBounded = ioBounded 10000 100 report_cycle
report_cycle e = case prop_cycle e of
Nothing -> return ()
Just (ee,ex) -> do
putStrLn "Failure:"
putStrLn (pprint ex)
print ex
putStrLn (E.prettyPrint ee)
putStrLn ""
-- Round-trip property: TH -> String -> HSE -> TH
-- Uses haskell-src-meta for HSE -> TH
prop_cycle :: Exp -> Maybe (E.Exp,Exp)
prop_cycle e = case myParse $ pprint (e :: Exp) :: E.ParseResult E.Exp of
E.ParseOk hse -> if e == toExp hse then Nothing else Just $ (hse, toExp hse)
E.ParseFailed _ s -> Nothing -- Parse failures do not count as errors!
-- Haskell parser
myParse :: String -> E.ParseResult E.Exp
myParse = E.parseWithMode E.defaultParseMode{E.extensions =
[ E.BangPatterns
, E.ScopedTypeVariables
, E.ViewPatterns
, E.KindSignatures
, E.ExplicitForAll
, E.TypeFamilies
]}
-}
-- We define both SmallCheck and Feat enumerators for comparison.
c1 :: (Serial a, Enumerable a) => (a -> b) -> (Enumerate b, Series b)
c1 f = (unary f,cons1 f)
c0 f = (nullary f, cons0 f)
instance (Serial a, Serial b) => Serial (FreePair a b) where
series = map Free . (series >< series)
coseries = undefined
toSel :: [(Enumerate b, Series b)] -> Enumerate b
toSel xs = consts $ map fst xs
toSerial :: [(Enumerate b, Series b)] -> Series b
toSerial xs = foldl1 (\/) $ map snd xs
-- These statements are always expressions
newtype ExpStmt = ExpStmt Exp deriving Typeable
-- Declarations allowed in where clauses
newtype WhereDec = WhereDec{unWhere :: Dec} deriving Typeable
-- Lowecase names
newtype LcaseN = LcaseN {lcased :: Name} deriving Typeable
-- Uppercase names
newtype UpcaseName = UpcaseName {ucased :: Name} deriving Typeable
newtype BindN = BindN Name deriving Typeable
instance (Enumerable a, Serial a) => Serial (NonEmpty a) where
series = toSerial [c1 $ NonEmpty . funcurry (:)]
coseries = undefined
instance (Serial a, Infinite a) => Serial (Nat a) where
series = map (\(N a) -> Nat a) . series
coseries = undefined
newtype CPair a b = CPair {cPair :: (a,b)} deriving Typeable
instance (Enumerable a, Serial a,Enumerable b, Serial b) => Serial (CPair a b) where
series = toSerial [c1 $ CPair . funcurry (,)]
coseries = undefined
instance (Serial a,Enumerable a,Enumerable b, Serial b) => Enumerable (CPair a b) where
enumerate = toSel [c1 $ CPair . funcurry (,)]
cExp =
[c1 $ VarE . lcased
,c1 $ ConE . ucased
,c1 LitE
,c1 $ funcurry AppE
,c1 $ \(ExpStmt a,o) -> InfixE (Just a) (either ConE VarE o) Nothing
,c1 $ \(ExpStmt a,o) -> InfixE Nothing (either ConE VarE o) (Just a)
,c1 $ \(a,o,b) -> InfixE (Just a) (either ConE VarE o) (Just b)
-- ,c1 $ funcurry $ funcurry $ \a o b -> UInfixE a (VarE o) b
-- ,c1 $ funcurry $ funcurry $ \a o b -> UInfixE a (ConE o) b
-- ,c1 ParensE
,c1 $ funcurry $ LamE . nonEmpty
,c1 $ \(x1,x2,xs) -> TupE (x1:x2:xs)
-- ,c1 UnboxedTupE
,c1 $ funcurry $ funcurry CondE
,c1 $ \(d,ds,e) -> LetE (map unWhere $ d:ds) e -- DISABLED BUGGY EMPTY LETS
,c1 $ \(e,NonEmpty m) -> CaseE e m
,c1 $ \(e,ss) -> DoE (ss ++ [NoBindS e])
,c1 $ (\((p,e),(CPair (xs,e'))) -> CompE ([BindS p e] ++ xs ++ [NoBindS e']))
-- ,c1 ArithSeqE -- BUGGY!
,c1 ListE
-- ,c1 $ funcurry SigE -- BUGGY!
,c1 $ \(e,x) -> RecConE e $ map unCase (nonEmpty x)
,c1 $ \(e,fe) -> RecUpdE e $ map unCase (nonEmpty fe)
]
instance Enumerable Exp where
enumerate = toSel cExp
instance Serial Exp where
series = toSerial cExp
coseries = undefined
unCase (LcaseN n,e) = (n,e)
cExpStmt =
[ c1 $ ExpStmt . VarE
, c1 $ ExpStmt . ConE
, c1 $ ExpStmt . LitE
, c1 $ \(e1,e2) -> ExpStmt (AppE e1 e2)
, c1 $ ExpStmt . LitE
-- , c1 parS
-- Removed paralell comprehensions
]
instance Enumerable ExpStmt where
enumerate = toSel cExpStmt
instance Serial ExpStmt where
series = toSerial cExpStmt
coseries = undefined
cPat =
[ c1 LitP
, c1 $ \(BindN n) -> VarP n
, c1 TupP
, c1 $ \(UpcaseName n,ps) -> ConP n ps
, c1 $ \(p1,UpcaseName n,p2) -> InfixP p1 n p2
, c1 TildeP
-- , c1 $ \(LcaseN n) -> BangP $ VarP n
, c1 $ \(BindN n,p) -> AsP n p
, c0 WildP
, c1 $ \(UpcaseName e,x) -> RecP e (map (\(BindN n, p) -> (n,p)) (nonEmpty x))
, c1 ListP
-- , c1 $ funcurry SigP -- BUGGY!
-- , c1 $ funcurry ViewP -- BUGGY!
]
instance Enumerable Pat where
enumerate = toSel cPat
instance Serial Pat where
series = toSerial cPat
coseries = undefined
-- deriveEnumerable ''Match -- Should remove decs
cMatch =
[c1 $ funcurry $ funcurry $ \x y ds -> Match x y (map unWhere ds)
]
instance Enumerable Match where
enumerate = toSel cMatch
instance Serial Match where
series = toSerial cMatch
coseries = undefined
cStmt =
[ c1 $ funcurry BindS
, c1 $ \(d) -> LetS $ map unWhere $ nonEmpty d
, c1 $ NoBindS
-- , c1 parS
-- Removed paralell comprehensions
]
instance Enumerable Stmt where
enumerate = toSel cStmt
instance Serial Stmt where
series = toSerial cStmt
coseries = undefined
cName = [ c1 (funcurry Name) ]
instance Enumerable Name where
enumerate = toSel cName
instance Serial Name where
series = toSerial cName
coseries = undefined
cType =
[c1 $ funcurry $ funcurry $ (\(x) -> ForallT (nonEmpty x))
,c1 $ \(BindN a) -> VarT a
,c1 $ \(UpcaseName a) -> ConT a
,c1 $ \n -> TupleT (abs n)
,c0 ArrowT
,c0 ListT
,c1 $ funcurry AppT
-- ,c1 $ funcurry SigT -- BUGGY!
]
instance Enumerable Type where
enumerate = toSel cType
instance Serial Type where
series = toSerial cType
coseries = undefined
-- deriveEnumerable ''Dec
cWhereDec =
[ c1 $ \(n,c) -> WhereDec $ FunD n (nonEmpty c)
, c1 $ \(n,p,wds) -> WhereDec $ ValD n p (map unWhere wds)
, c1 $ \(BindN a,b) -> WhereDec $ SigD a b
-- , c1 $ WhereDec . PragmaD -- Removed pragmas
-- , c1 parS -- Removed paralell comprehensions
]
instance Enumerable WhereDec where
enumerate = toSel cWhereDec
instance Serial WhereDec where
series = toSerial cWhereDec
coseries = undefined
cLit =
[ c1 StringL
, c1 CharL -- TODO: Fair char generation
, c1 $ IntegerL . nat
-- , c1 RationalL -- BUGGY!
-- Removed primitive litterals
]
instance Enumerable Lit where
enumerate = toSel cLit
instance Serial Lit where
series = toSerial cLit
coseries = undefined
cClause =
[c1 $ funcurry (funcurry $ \ps bs ds -> Clause ps bs (map unWhere ds))]
instance Enumerable Clause where
enumerate = toSel cClause
instance Serial Clause where
series = toSerial cClause
coseries = undefined
-- deriveEnumerable ''Pred
cPred =
[ c1 $ funcurry ClassP
, c1 $ funcurry EqualP
]
instance Enumerable Pred where
enumerate = toSel cPred
instance Serial Pred where
series = toSerial cPred
coseries = undefined
-- deriveEnumerable ''TyVarBndr
cTyVarBndr =
[ c1 $ PlainTV
, c1 $ funcurry KindedTV
]
instance Enumerable TyVarBndr where
enumerate = toSel cTyVarBndr
instance Serial TyVarBndr where
series = toSerial cTyVarBndr
coseries = undefined
cKind =
[c0 StarK
,c1 (funcurry ArrowK)
]
instance Enumerable Kind where
enumerate = toSel cKind
instance Serial Kind where
series = toSerial cKind
coseries = undefined
cBody =
[ c1 NormalB
, c1 $ \(x) -> GuardedB (nonEmpty x)
-- Removed primitive litterals
]
instance Enumerable Body where
enumerate = toSel cBody
instance Serial Body where
series = toSerial cBody
coseries = undefined
cGuard =
[c1 $ NormalG
,c1 $ \(s) -> PatG (nonEmpty s)
]
instance Enumerable Guard where
enumerate = toSel cGuard
instance Serial Guard where
series = toSerial cGuard
coseries = undefined
cCallconv = [c0 CCall, c0 StdCall]
instance Enumerable Callconv where
enumerate = toSel cCallconv
instance Serial Callconv where
series = toSerial cCallconv
coseries = undefined
cSafety = [c0 Unsafe, c0 Safe, c0 Interruptible]
instance Enumerable Safety where
enumerate = toSel cSafety
instance Serial Safety where
series = toSerial cSafety
coseries = undefined
cStrict = [c0 IsStrict, c0 NotStrict, c0 Unpacked]
instance Enumerable Strict where
enumerate = toSel cStrict
instance Serial Strict where
series = toSerial cStrict
coseries = undefined
cInlineSpec = [c1 (funcurry $ funcurry $ InlineSpec)]
instance Enumerable InlineSpec where
enumerate = toSel cInlineSpec
instance Serial InlineSpec where
series = toSerial cInlineSpec
coseries = undefined
cOccName =
[ c0 $ OccName "Con"
, c0 $ OccName "var"
]
instance Enumerable OccName where
enumerate = toSel cOccName
instance Serial OccName where
series = toSerial cOccName
coseries = undefined
cBindN = [c0 $ BindN $ Name (OccName "var") NameS]
instance Enumerable BindN where
enumerate = toSel cBindN
instance Serial BindN where
series = toSerial cBindN
coseries = undefined
cLcaseN = [c1 $ \nf -> LcaseN $ Name (OccName "var") nf]
instance Enumerable LcaseN where
enumerate = toSel cLcaseN
instance Serial LcaseN where
series = toSerial cLcaseN
coseries = undefined
cUpcaseName = [c1 $ \nf -> UpcaseName $ Name (OccName "Con") nf]
instance Serial UpcaseName where
series = toSerial cUpcaseName
coseries = undefined
instance Enumerable UpcaseName where
enumerate = toSel cUpcaseName
cModName = [c0 $ ModName "M", c0 $ ModName "C.M"]
instance Enumerable ModName where
enumerate = toSel cModName
instance Serial ModName where
series = toSerial cModName
coseries = undefined
cRange =
[ c1 FromR
, c1 (funcurry FromThenR)
, c1 (funcurry FromToR)
, c1 (funcurry $ funcurry FromThenToR)
]
instance Enumerable Range where
enumerate = toSel cRange
instance Serial Range where
series = toSerial cRange
coseries = undefined
cNameFlavour = (
[ c1 NameQ
-- , funcurry $ funcurry NameG
-- , \(I# x) -> NameU x
-- , \(I# x) -> NameL x
, c0 NameS
])
instance Enumerable NameFlavour where
enumerate = toSel cNameFlavour
instance Serial NameFlavour where
series = toSerial cNameFlavour
coseries = undefined
-- main = test_parsesBounded
-- or test_parsesAll, but that takes much longer to find bugs
eExp :: Enumerate Exp
eExp = toSel cExp
|
patrikja/testing-feat
|
examples/template-haskell/th.hs
|
bsd-3-clause
| 12,070
| 25
| 14
| 2,599
| 3,662
| 1,976
| 1,686
| 277
| 1
|
module Debug.PacketParsing.Parsing
( restruct ) where
import Net.Packet (InPacket, toInPack, listArray)
import qualified Data.ByteString as B
restruct :: B.ByteString -> InPacket
restruct pk = toInPack $ listArray (0, B.length pk - 1) (B.unpack pk)
|
rlupton20/vanguard-dataplane
|
app/Debug/PacketParsing/Parsing.hs
|
gpl-3.0
| 252
| 0
| 10
| 37
| 87
| 50
| 37
| 6
| 1
|
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.EFS.ModifyMountTargetSecurityGroups
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Modifies the set of security groups in effect for a mount target.
--
-- When you create a mount target, Amazon EFS also creates a new network
-- interface (see CreateMountTarget). This operation replaces the security
-- groups in effect for the network interface associated with a mount
-- target, with the 'SecurityGroups' provided in the request. This
-- operation requires that the network interface of the mount target has
-- been created and the life cycle state of the mount target is not
-- \"deleted\".
--
-- The operation requires permissions for the following actions:
--
-- - 'elasticfilesystem:ModifyMountTargetSecurityGroups' action on the
-- mount target\'s file system.
-- - 'ec2:ModifyNetworkInterfaceAttribute' action on the mount target\'s
-- network interface.
--
-- /See:/ <http://docs.aws.amazon.com/directoryservice/latest/devguide/API_ModifyMountTargetSecurityGroups.html AWS API Reference> for ModifyMountTargetSecurityGroups.
module Network.AWS.EFS.ModifyMountTargetSecurityGroups
(
-- * Creating a Request
modifyMountTargetSecurityGroups
, ModifyMountTargetSecurityGroups
-- * Request Lenses
, mmtsgSecurityGroups
, mmtsgMountTargetId
-- * Destructuring the Response
, modifyMountTargetSecurityGroupsResponse
, ModifyMountTargetSecurityGroupsResponse
) where
import Network.AWS.EFS.Types
import Network.AWS.EFS.Types.Product
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
-- | /See:/ 'modifyMountTargetSecurityGroups' smart constructor.
data ModifyMountTargetSecurityGroups = ModifyMountTargetSecurityGroups'
{ _mmtsgSecurityGroups :: !(Maybe [Text])
, _mmtsgMountTargetId :: !Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ModifyMountTargetSecurityGroups' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'mmtsgSecurityGroups'
--
-- * 'mmtsgMountTargetId'
modifyMountTargetSecurityGroups
:: Text -- ^ 'mmtsgMountTargetId'
-> ModifyMountTargetSecurityGroups
modifyMountTargetSecurityGroups pMountTargetId_ =
ModifyMountTargetSecurityGroups'
{ _mmtsgSecurityGroups = Nothing
, _mmtsgMountTargetId = pMountTargetId_
}
-- | An array of up to five VPC security group IDs.
mmtsgSecurityGroups :: Lens' ModifyMountTargetSecurityGroups [Text]
mmtsgSecurityGroups = lens _mmtsgSecurityGroups (\ s a -> s{_mmtsgSecurityGroups = a}) . _Default . _Coerce;
-- | The ID of the mount target whose security groups you want to modify.
mmtsgMountTargetId :: Lens' ModifyMountTargetSecurityGroups Text
mmtsgMountTargetId = lens _mmtsgMountTargetId (\ s a -> s{_mmtsgMountTargetId = a});
instance AWSRequest ModifyMountTargetSecurityGroups
where
type Rs ModifyMountTargetSecurityGroups =
ModifyMountTargetSecurityGroupsResponse
request = putJSON eFS
response
= receiveNull
ModifyMountTargetSecurityGroupsResponse'
instance ToHeaders ModifyMountTargetSecurityGroups
where
toHeaders = const mempty
instance ToJSON ModifyMountTargetSecurityGroups where
toJSON ModifyMountTargetSecurityGroups'{..}
= object
(catMaybes
[("SecurityGroups" .=) <$> _mmtsgSecurityGroups])
instance ToPath ModifyMountTargetSecurityGroups where
toPath ModifyMountTargetSecurityGroups'{..}
= mconcat
["/2015-02-01/mount-targets/",
toBS _mmtsgMountTargetId, "/security-groups"]
instance ToQuery ModifyMountTargetSecurityGroups
where
toQuery = const mempty
-- | /See:/ 'modifyMountTargetSecurityGroupsResponse' smart constructor.
data ModifyMountTargetSecurityGroupsResponse =
ModifyMountTargetSecurityGroupsResponse'
deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ModifyMountTargetSecurityGroupsResponse' with the minimum fields required to make a request.
--
modifyMountTargetSecurityGroupsResponse
:: ModifyMountTargetSecurityGroupsResponse
modifyMountTargetSecurityGroupsResponse =
ModifyMountTargetSecurityGroupsResponse'
|
fmapfmapfmap/amazonka
|
amazonka-efs/gen/Network/AWS/EFS/ModifyMountTargetSecurityGroups.hs
|
mpl-2.0
| 4,941
| 11
| 13
| 894
| 469
| 292
| 177
| 68
| 1
|
{-# LANGUAGE OverloadedStrings #-}
module Main where
-- import Data.Default (def)
-- import qualified Text.Pandoc.Writers.Native as P
-- import System.Environment (getArgs)
import qualified Data.ByteString.Lazy as B hiding (putStrLn)
import qualified Data.ByteString.Lazy.Char8 as B (putStrLn)
import qualified Data.Text.IO as T
import Data.Monoid ((<>))
import Data.List (isSuffixOf)
import Control.Monad (when, forM_)
import System.FilePath ((</>))
import Control.Lens
import Zeppelin as Z
import Databricks as D
import Notebook as N
import Pandoc as P
import Utils
import Options.Applicative as Opt
type SourceFormat = String -> B.ByteString -> Either String [(String, N.Notebook)]
type TargetFormat = [(String, N.Notebook)] -> [(String, B.ByteString)]
databricksDBCSource :: SourceFormat
databricksDBCSource f x = over (each . _2) D.toNotebook <$> fromByteStringArchive x
-- databricksDBCSource f x = concatMapM (uncurry databricksJSONSource) jsonFiles
-- where archive = Zip.toArchive x
-- jsonPaths = filter isJSON (Zip.filesInArchive archive)
-- isJSON :: FilePath -> Bool
-- isJSON f = let f' = map C.toLower f
-- in any (`isSuffixOf` f') [".scala", ".py", ".r", ".sql"]
-- jsonFiles = map extract jsonPaths
-- extract f = let Just e = Zip.findEntryByPath f archive
-- in (f, Zip.fromEntry e)
databricksJSONSource :: SourceFormat
databricksJSONSource f x = (singleton . D.toNotebook) <$> D.fromByteString x
where singleton y = [(f, y)]
zeppelinSource :: SourceFormat
zeppelinSource f x = (singleton . Z.toNotebook) <$> Z.fromByteString x
where singleton y = [(f, y)]
sourceFormat :: Parser SourceFormat
sourceFormat = parseFormat <$> sourceFormat'
where parseFormat "databricks" = databricksDBCSource
parseFormat "databricks-json" = databricksJSONSource
parseFormat "zeppelin" = zeppelinSource
parseFormat _ = error "Unknown source format"
sourceFormat' = strOption ( long "from"
<> short 'f'
<> metavar "FROM"
<> help "Format to convert from" )
databricksJSONTarget :: TargetFormat
databricksJSONTarget = over (each . _2) compile
where compile = D.toByteString . D.fromNotebook
zeppelinTarget :: TargetFormat
zeppelinTarget = over (each . _1) (swapExtension ".json") . over (each . _2) compile
where compile = Z.toByteString . Z.fromNotebook
markdownTarget :: TargetFormat
markdownTarget = over (each . _1) (swapExtension ".md") . over (each . _2) compile
where compile = P.toMarkdown . P.fromNotebook
targetFormat :: Parser TargetFormat
targetFormat = parseFormat <$> targetFormat'
where parseFormat "databricks-json" = databricksJSONTarget
parseFormat "zeppelin" = zeppelinTarget
parseFormat "markdown" = markdownTarget
parseFormat _ = error "Unknown target format"
targetFormat' = strOption ( long "to"
<> short 't'
<> metavar "TO"
<> help "Format to convert to" )
inputPaths :: Parser [FilePath]
inputPaths = some (Opt.argument str (metavar "INPUTS..."))
outputPath :: Parser FilePath
outputPath = strOption (long "out" <> short 'o' <> metavar "OUTPUT")
data Run = Run { from :: SourceFormat, to :: TargetFormat, inputs :: [FilePath], output :: Maybe FilePath }
run :: Parser Run
run = Run <$> sourceFormat <*> targetFormat <*> inputPaths <*> optional outputPath
opts :: ParserInfo Run
opts = info (run <**> helper)
( fullDesc
<> progDesc "Convert between different notebook formats" )
main :: IO ()
main = do
(Run from to inputs output) <- execParser opts
inputStreams <- if null inputs
then do stream <- B.getContents
return [("stdin", stream)]
else do streams <- mapM B.readFile inputs
return (zip inputs streams)
let attempt = to <$> concatMapM (uncurry from) inputStreams
results = either (error . show) id attempt
when (null results) (error "Nothing to output.")
case output of
Nothing -> case results of
[(_, x)] -> B.putStrLn x
_ -> error "Cannot output multiple files to stdout"
Just o -> forM_ results $ \(f, x) -> do
ensureCanBeCreated (o </> f)
B.writeFile (o </> f) x
|
raazesh-sainudiin/scalable-data-science
|
babel/pinot/src/Main.hs
|
unlicense
| 4,453
| 0
| 16
| 1,119
| 1,125
| 606
| 519
| 84
| 4
|
<?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="sq-AL">
<title>Python Scripting</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>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>
|
veggiespam/zap-extensions
|
addOns/jython/src/main/javahelp/org/zaproxy/zap/extension/jython/resources/help_sq_AL/helpset_sq_AL.hs
|
apache-2.0
| 962
| 79
| 66
| 157
| 409
| 207
| 202
| -1
| -1
|
module Backtracking where
fun = do (\x -> do renderWithDrawable)
|
Atsky/haskell-idea-plugin
|
data/haskellParserTests/Backtracking.hs
|
apache-2.0
| 66
| 0
| 10
| 11
| 23
| 13
| 10
| 2
| 1
|
-- |
-- Module : Crypto.Internal.Imports
-- License : BSD-style
-- Maintainer : Vincent Hanquez <vincent@snarc.org>
-- Stability : experimental
-- Portability : unknown
--
{-# LANGUAGE CPP #-}
module Crypto.Internal.Imports
( module X
) where
import Data.Word as X
#if !(MIN_VERSION_base(4,11,0))
import Data.Semigroup as X (Semigroup(..))
#endif
import Control.Applicative as X
import Control.Monad as X (forM, forM_, void)
import Control.Arrow as X (first, second)
import Crypto.Internal.DeepSeq as X
|
vincenthz/cryptonite
|
Crypto/Internal/Imports.hs
|
bsd-3-clause
| 571
| 0
| 6
| 137
| 94
| 68
| 26
| 9
| 0
|
{-# LANGUAGE TemplateHaskell #-}
-- | Game rules and assorted game setup data.
module Content.RuleKind ( cdefs ) where
import Language.Haskell.TH.Syntax
import System.FilePath
-- Cabal
import qualified Paths_LambdaHack as Self (getDataFileName, version)
import Game.LambdaHack.Common.ContentDef
import Game.LambdaHack.Common.Vector
import Game.LambdaHack.Content.RuleKind
cdefs :: ContentDef RuleKind
cdefs = ContentDef
{ getSymbol = rsymbol
, getName = rname
, getFreq = rfreq
, validateSingle = validateSingleRuleKind
, validateAll = validateAllRuleKind
, content =
[standard]
}
standard :: RuleKind
standard = RuleKind
{ rsymbol = 's'
, rname = "standard LambdaHack ruleset"
, rfreq = [("standard", 100)]
-- Check whether one position is accessible from another.
-- Precondition: the two positions are next to each other
-- and the target tile is walkable. For LambdaHack we forbid
-- diagonal movement to and from doors.
, raccessible = Nothing
, raccessibleDoor =
Just $ \spos tpos -> not $ isDiagonal $ spos `vectorToFrom` tpos
, rtitle = "LambdaHack"
, rpathsDataFile = Self.getDataFileName
, rpathsVersion = Self.version
-- The strings containing the default configuration file
-- included from config.ui.default.
, rcfgUIName = "config.ui"
, rcfgUIDefault = $(do
let path = "GameDefinition" </> "config.ui" <.> "default"
qAddDependentFile path
x <- qRunIO (readFile path)
lift x)
-- ASCII art for the Main Menu. Only pure 7-bit ASCII characters are
-- allowed. The picture should be exactly 24 rows by 80 columns,
-- plus an extra frame (of any characters) that is ignored.
-- For a different screen size, the picture is centered and the outermost
-- rows and columns cloned. When displayed in the Main Menu screen,
-- it's overwritten with the game version string and keybinding strings.
-- The game version string begins and ends with a space and is placed
-- in the very bottom right corner. The keybindings overwrite places
-- marked with 25 left curly brace signs '{' in a row. The sign is forbidden
-- everywhere else. A specific number of such places with 25 left braces
-- are required, at most one per row, and all are overwritten
-- with text that is flushed left and padded with spaces.
-- The Main Menu is displayed dull white on black.
-- TODO: Show highlighted keybinding in inverse video or bright white on grey
-- background. The spaces that pad keybindings are not highlighted.
, rmainMenuArt = $(do
let path = "GameDefinition/MainMenu.ascii"
qAddDependentFile path
x <- qRunIO (readFile path)
lift x)
, rfirstDeathEnds = False
, rfovMode = Digital
, rwriteSaveClips = 500
, rleadLevelClips = 100
, rscoresFile = "scores"
, rsavePrefix = "save"
, rnearby = 20
}
|
Concomitant/LambdaHack
|
GameDefinition/Content/RuleKind.hs
|
bsd-3-clause
| 2,884
| 0
| 15
| 620
| 384
| 237
| 147
| 46
| 1
|
module BuckConverter where
import Tuura.Concept.STG
--ZC late scenario definition using concepts
circuit uv oc zc gp gp_ack gn gn_ack =
chargeFunc <> uvFunc <> uvReact <> zcLate <> initialise zc False
where
interface = inputs [uv, oc, zc, gp_ack, gn_ack] <> outputs [gp, gn]
zcLate = rise uv ~> rise zc <> fall zc ~> fall uv
--Must be redefined as auto re-use of concepts is yet to be implemented
uvFunc = rise uv ~> rise gp <> rise uv ~> fall gn
ocFunc = rise oc ~> fall gp <> rise oc ~> rise gn
uvReact = rise gp_ack ~> fall uv <> fall gn_ack ~> fall uv
ocReact = fall gp_ack ~> fall oc <> rise gn_ack ~> fall oc
environmentConstraint = me uv oc
noShortcircuit = me gp gn <> fall gn_ack ~> rise gp <> fall gp_ack ~> rise gn
gpHandshake = handshake gp gp_ack
gnHandshake = handshake gn gn_ack
initialState = initialise0 [uv, oc, zc, gp, gp_ack] <> initialise1 [gn, gn_ack]
chargeFunc = interface <> ocFunc <> ocReact <> environmentConstraint <>
noShortcircuit <> gpHandshake <> gnHandshake <> initialState
|
tuura/concepts
|
examples/zcLate_scenario.hs
|
bsd-3-clause
| 1,094
| 0
| 13
| 270
| 373
| 186
| 187
| 17
| 1
|
main = drop 0 x
|
mpickering/hlint-refactor
|
tests/examples/Default77.hs
|
bsd-3-clause
| 15
| 0
| 5
| 4
| 11
| 5
| 6
| 1
| 1
|
{-
******************************************************************************
* H M T C *
* *
* Module: MTIR *
* Purpose: MiniTriangle Internal Representation *
* (typechecked AST with semantical annotations) *
* Authors: Henrik Nilsson *
* *
* Copyright (c) Henrik Nilsson, 2006 - 2014 *
* *
******************************************************************************
-}
-- | MiniTriangle Internal Representation. The definitions mirror the
-- AST, but the program should be type correct at this stage and semantical
-- annotations have been added. In particular, variables are represented
-- by symbols (with name, type info, and source position) as opposed to just
-- their names.
module MTIR (
-- MTIR types
MTIR (..), -- Not abstract. Instances: HasSrcPos.
Command (..), -- Not abstract. Instances: HasSrcPos.
Expression (..), -- Not abstract. Instances: HasSrcPos.
Declaration (..), -- Not abstract. Instances: HasSrcPos.
MTInt, -- Representation type for MiniTriangle integers.
MTChr -- Representation type for MiniTriangle characters.
) where
-- HMTC module imports
import SrcPos
import Name
import Type
import Symbol (IntTermSym)
-- | Internal representation of MiniTriangle Programs
data MTIR = MTIR { mtirCmd :: Command }
instance HasSrcPos MTIR where
srcPos = cmdSrcPos . mtirCmd
-- | Internal representation of syntactic category Command
data Command
-- | Assignment
= CmdAssign {
caVar :: Expression, -- ^ Assigned variable
caVal :: Expression, -- ^ Right-hand side expression
cmdSrcPos :: SrcPos
}
-- | Procedure call
| CmdCall {
ccProc :: Expression, -- ^ Called procedure
ccArgs :: [Expression], -- ^ Arguments
cmdSrcPos :: SrcPos
}
-- | Command sequence (block)
| CmdSeq {
csCmds :: [Command], -- ^ Commands
cmdSrcPos :: SrcPos
}
-- | Conditional command
| CmdIf {
ciCondThens :: [(Expression,
Command)], -- ^ Conditional branches
ciMbElse :: Maybe Command, -- ^ Optional else-branch
cmdSrcPos :: SrcPos
}
-- | While-loop
| CmdWhile {
cwCond :: Expression, -- ^ Loop-condition
cwBody :: Command, -- ^ Loop-body
cmdSrcPos :: SrcPos
}
| CmdRepeat {
crBody :: Command, -- ^ Loop-body
crCond :: Expression, -- ^ Loop-condition
cmdSrcPos :: SrcPos
}
-- | Let-command
| CmdLet {
clDecls :: [Declaration], -- ^ Declarations
clBody :: Command, -- ^ Let-body
cmdSrcPos :: SrcPos
}
instance HasSrcPos Command where
srcPos = cmdSrcPos
-- | Internal representation of syntactic category Expression
data Expression
-- | Literal Boolean
= ExpLitBool {
elbVal :: Bool, -- ^ Literal Boolean.
expType :: Type, -- ^ Type
expSrcPos :: SrcPos
}
-- | Literal integer
| ExpLitInt {
eliVal :: MTInt, -- ^ Literal integer.
expType :: Type, -- ^ Type
expSrcPos :: SrcPos
}
-- | Literal character
| ExpLitChr {
elcVal :: MTChr, -- ^ Literal character.
expType :: Type, -- ^ Type
expSrcPos :: SrcPos
}
-- | External reference (procedure/function)
| ExpExtRef {
eerVal :: Name, -- ^ Name of external entity.
expType :: Type, -- ^ Type
expSrcPos :: SrcPos
}
-- | Variable reference
| ExpVar {
evVar :: IntTermSym, -- ^ Referenced variable (symbol!)
expType :: Type, -- ^ Type
expSrcPos :: SrcPos
}
-- | Dereferencing of reference variable
| ExpDeref {
edArg :: Expression, -- ^ Argument
expType :: Type, -- ^ Type (after dereferencing)
expSrcPos :: SrcPos
}
-- | Function or n-ary operator application
| ExpApp {
eaFun :: Expression, -- ^ Applied function or operator
eaArgs :: [Expression], -- ^ Arguments
expType :: Type, -- ^ Type (of application)
expSrcPos :: SrcPos
}
-- | Conditional expression
| ExpCond {
ecCond :: Expression, -- ^ Condition
ecTrue :: Expression, -- ^ Value if condition is true
ecFalse :: Expression, -- ^ Value if condition is false
expType :: Type, -- ^ Type (of conditional expression)
expSrcPos :: SrcPos
}
-- | Array expression
| ExpAry {
eaElts :: [Expression], -- ^ Array elements
expType :: Type,
expSrcPos :: SrcPos
}
-- | Array indexing
| ExpIx {
eiAry :: Expression, -- ^ Array expression
eiIx :: Expression, -- ^ Indexing expression
expType :: Type,
expSrcPos :: SrcPos
}
-- | Record expression
| ExpRcd {
erFldDefs :: [(Name,Expression)], -- ^ Record field definitions;
-- assumed to be sorted by name
expType :: Type,
expSrcPos :: SrcPos
}
-- | Record projection
| ExpPrj {
epRcd :: Expression, -- ^ Record expression
epFld :: Name, -- ^ Field to project out
expType :: Type,
expSrcPos :: SrcPos
}
instance HasSrcPos Expression where
srcPos = expSrcPos
-- | Internal representation of syntactic category Declaration
-- (Most of these are also definitions. Note that symbols carry the types.)
data Declaration
-- | Constant declaration
= DeclConst {
dcConst :: IntTermSym, -- ^ Declared constant (symbol!)
dcVal :: Expression -- ^ Value of defined constant
}
-- | Variable declaration
| DeclVar {
dvVar :: IntTermSym, -- ^ Declared variable (symbol!)
dvMbVal :: Maybe Expression -- ^ Initial value of declared
-- variable, if any
}
-- | Function declaration
| DeclFun {
dfFun :: IntTermSym, -- ^ Declared function (symbol!)
dfArgs :: [IntTermSym], -- ^ Formal arguments (with types)
dfBody :: Expression -- ^ Function boody
}
-- | Procedure declaration
| DeclProc {
dpProc :: IntTermSym, -- ^ Declared procedure (symbol!)
dpArgs :: [IntTermSym], -- ^ Formal arguments (with types)
dpBody :: Command -- ^ Procedure boody
}
instance HasSrcPos Declaration where
srcPos (DeclConst {dcConst = s}) = srcPos s
srcPos (DeclVar {dvVar = s}) = srcPos s
srcPos (DeclFun {dfFun = s}) = srcPos s
srcPos (DeclProc {dpProc = s}) = srcPos s
|
jbracker/supermonad-plugin
|
examples/monad/hmtc/original/MTIR.hs
|
bsd-3-clause
| 7,692
| 0
| 10
| 3,128
| 904
| 601
| 303
| 121
| 0
|
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE OverloadedStrings #-}
module Database.Persist.Types.Base where
import qualified Data.Aeson as A
import Control.Exception (Exception)
import Web.PathPieces (PathPiece (..))
import Control.Monad.Trans.Error (Error (..))
import Data.Typeable (Typeable)
import Data.Text (Text, pack)
import qualified Data.Text as T
import qualified Data.Text.Encoding as TE
import Data.Text.Encoding.Error (lenientDecode)
import qualified Data.ByteString.Base64 as B64
import qualified Data.Vector as V
import Control.Arrow (second)
import Data.Time (Day, TimeOfDay, UTCTime)
import Data.Int (Int64)
import qualified Data.Text.Read
import Data.ByteString (ByteString, foldl')
import Data.Bits (shiftL, shiftR)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS8
import Data.Map (Map)
import qualified Data.HashMap.Strict as HM
import Data.Word (Word32)
import Numeric (showHex, readHex)
#if MIN_VERSION_aeson(0, 7, 0)
import qualified Data.Scientific
#else
import qualified Data.Attoparsec.Number as AN
#endif
-- | A 'Checkmark' should be used as a field type whenever a
-- uniqueness constraint should guarantee that a certain kind of
-- record may appear at most once, but other kinds of records may
-- appear any number of times.
--
-- /NOTE:/ You need to mark any @Checkmark@ fields as @nullable@
-- (see the following example).
--
-- For example, suppose there's a @Location@ entity that
-- represents where a user has lived:
--
-- @
-- Location
-- user UserId
-- name Text
-- current Checkmark nullable
--
-- UniqueLocation user current
-- @
--
-- The @UniqueLocation@ constraint allows any number of
-- 'Inactive' @Location@s to be @current@. However, there may be
-- at most one @current@ @Location@ per user (i.e., either zero
-- or one per user).
--
-- This data type works because of the way that SQL treats
-- @NULL@able fields within uniqueness constraints. The SQL
-- standard says that @NULL@ values should be considered
-- different, so we represent 'Inactive' as SQL @NULL@, thus
-- allowing any number of 'Inactive' records. On the other hand,
-- we represent 'Active' as @TRUE@, so the uniqueness constraint
-- will disallow more than one 'Active' record.
--
-- /Note:/ There may be DBMSs that do not respect the SQL
-- standard's treatment of @NULL@ values on uniqueness
-- constraints, please check if this data type works before
-- relying on it.
--
-- The SQL @BOOLEAN@ type is used because it's the smallest data
-- type available. Note that we never use @FALSE@, just @TRUE@
-- and @NULL@. Provides the same behavior @Maybe ()@ would if
-- @()@ was a valid 'PersistField'.
data Checkmark = Active
-- ^ When used on a uniqueness constraint, there
-- may be at most one 'Active' record.
| Inactive
-- ^ When used on a uniqueness constraint, there
-- may be any number of 'Inactive' records.
deriving (Eq, Ord, Read, Show, Enum, Bounded)
instance PathPiece Checkmark where
toPathPiece = pack . show
fromPathPiece txt =
case reads (T.unpack txt) of
[(a, "")] -> Just a
_ -> Nothing
data IsNullable = Nullable !WhyNullable
| NotNullable
deriving (Eq, Show)
-- | The reason why a field is 'nullable' is very important. A
-- field that is nullable because of a @Maybe@ tag will have its
-- type changed from @A@ to @Maybe A@. OTOH, a field that is
-- nullable because of a @nullable@ tag will remain with the same
-- type.
data WhyNullable = ByMaybeAttr
| ByNullableAttr
deriving (Eq, Show)
data EntityDef = EntityDef
{ entityHaskell :: !HaskellName
, entityDB :: !DBName
, entityId :: !FieldDef
, entityAttrs :: ![Attr]
, entityFields :: ![FieldDef]
, entityUniques :: ![UniqueDef]
, entityForeigns:: ![ForeignDef]
, entityDerives :: ![Text]
, entityExtra :: !(Map Text [ExtraLine])
, entitySum :: !Bool
}
deriving (Show, Eq, Read, Ord)
entityPrimary :: EntityDef -> Maybe CompositeDef
entityPrimary t = case fieldReference (entityId t) of
CompositeRef c -> Just c
_ -> Nothing
entityKeyFields :: EntityDef -> [FieldDef]
entityKeyFields ent = case entityPrimary ent of
Nothing -> [entityId ent]
Just pdef -> compositeFields pdef
type ExtraLine = [Text]
newtype HaskellName = HaskellName { unHaskellName :: Text }
deriving (Show, Eq, Read, Ord)
newtype DBName = DBName { unDBName :: Text }
deriving (Show, Eq, Read, Ord)
type Attr = Text
data FieldType
= FTTypeCon (Maybe Text) Text
-- ^ Optional module and name.
| FTApp FieldType FieldType
| FTList FieldType
deriving (Show, Eq, Read, Ord)
data FieldDef = FieldDef
{ fieldHaskell :: !HaskellName -- ^ name of the field
, fieldDB :: !DBName
, fieldType :: !FieldType
, fieldSqlType :: !SqlType
, fieldAttrs :: ![Attr] -- ^ user annotations for a field
, fieldStrict :: !Bool -- ^ a strict field in the data type. Default: true
, fieldReference :: !ReferenceDef
}
deriving (Show, Eq, Read, Ord)
-- | There are 3 kinds of references
-- 1) composite (to fields that exist in the record)
-- 2) single field
-- 3) embedded
data ReferenceDef = NoReference
| ForeignRef !HaskellName !FieldType
-- ^ A ForeignRef has a late binding to the EntityDef it references via HaskellName and has the Haskell type of the foreign key in the form of FieldType
| EmbedRef EmbedEntityDef
| CompositeRef CompositeDef
| SelfReference
-- ^ A SelfReference stops an immediate cycle which causes non-termination at compile-time (issue #311).
deriving (Show, Eq, Read, Ord)
-- | An EmbedEntityDef is the same as an EntityDef
-- But it is only used for fieldReference
-- so it only has data needed for embedding
data EmbedEntityDef = EmbedEntityDef
{ embeddedHaskell :: !HaskellName
, embeddedFields :: ![EmbedFieldDef]
} deriving (Show, Eq, Read, Ord)
-- | An EmbedFieldDef is the same as a FieldDef
-- But it is only used for embeddedFields
-- so it only has data needed for embedding
data EmbedFieldDef = EmbedFieldDef
{ emFieldDB :: !DBName
, emFieldEmbed :: Maybe EmbedEntityDef
, emFieldCycle :: Maybe HaskellName
-- ^ 'emFieldEmbed' can create a cycle (issue #311)
-- when a cycle is detected, 'emFieldEmbed' will be Nothing
-- and 'emFieldCycle' will be Just
}
deriving (Show, Eq, Read, Ord)
toEmbedEntityDef :: EntityDef -> EmbedEntityDef
toEmbedEntityDef ent = embDef
where
embDef = EmbedEntityDef
{ embeddedHaskell = entityHaskell ent
, embeddedFields = map toEmbedFieldDef $ entityFields ent
}
toEmbedFieldDef :: FieldDef -> EmbedFieldDef
toEmbedFieldDef field =
EmbedFieldDef { emFieldDB = fieldDB field
, emFieldEmbed = case fieldReference field of
EmbedRef em -> Just em
SelfReference -> Just embDef
_ -> Nothing
, emFieldCycle = case fieldReference field of
SelfReference -> Just $ entityHaskell ent
_ -> Nothing
}
data UniqueDef = UniqueDef
{ uniqueHaskell :: !HaskellName
, uniqueDBName :: !DBName
, uniqueFields :: ![(HaskellName, DBName)]
, uniqueAttrs :: ![Attr]
}
deriving (Show, Eq, Read, Ord)
data CompositeDef = CompositeDef
{ compositeFields :: ![FieldDef]
, compositeAttrs :: ![Attr]
}
deriving (Show, Eq, Read, Ord)
-- | Used instead of FieldDef
-- to generate a smaller amount of code
type ForeignFieldDef = (HaskellName, DBName)
data ForeignDef = ForeignDef
{ foreignRefTableHaskell :: !HaskellName
, foreignRefTableDBName :: !DBName
, foreignConstraintNameHaskell :: !HaskellName
, foreignConstraintNameDBName :: !DBName
, foreignFields :: ![(ForeignFieldDef, ForeignFieldDef)] -- this entity plus the primary entity
, foreignAttrs :: ![Attr]
, foreignNullable :: Bool
}
deriving (Show, Eq, Read, Ord)
data PersistException
= PersistError Text -- ^ Generic Exception
| PersistMarshalError Text
| PersistInvalidField Text
| PersistForeignConstraintUnmet Text
| PersistMongoDBError Text
| PersistMongoDBUnsupported Text
deriving (Show, Typeable)
instance Exception PersistException
instance Error PersistException where
strMsg = PersistError . pack
-- | A raw value which can be stored in any backend and can be marshalled to
-- and from a 'PersistField'.
data PersistValue = PersistText Text
| PersistByteString ByteString
| PersistInt64 Int64
| PersistDouble Double
| PersistRational Rational
| PersistBool Bool
| PersistDay Day
| PersistTimeOfDay TimeOfDay
| PersistUTCTime UTCTime
| PersistNull
| PersistList [PersistValue]
| PersistMap [(Text, PersistValue)]
| PersistObjectId ByteString -- ^ Intended especially for MongoDB backend
| PersistDbSpecific ByteString -- ^ Using 'PersistDbSpecific' allows you to use types specific to a particular backend
-- For example, below is a simple example of the PostGIS geography type:
--
-- @
-- data Geo = Geo ByteString
--
-- instance PersistField Geo where
-- toPersistValue (Geo t) = PersistDbSpecific t
--
-- fromPersistValue (PersistDbSpecific t) = Right $ Geo $ Data.ByteString.concat ["'", t, "'"]
-- fromPersistValue _ = Left "Geo values must be converted from PersistDbSpecific"
--
-- instance PersistFieldSql Geo where
-- sqlType _ = SqlOther "GEOGRAPHY(POINT,4326)"
--
-- toPoint :: Double -> Double -> Geo
-- toPoint lat lon = Geo $ Data.ByteString.concat ["'POINT(", ps $ lon, " ", ps $ lat, ")'"]
-- where ps = Data.Text.pack . show
-- @
--
-- If Foo has a geography field, we can then perform insertions like the following:
--
-- @
-- insert $ Foo (toPoint 44 44)
-- @
--
deriving (Show, Read, Eq, Typeable, Ord)
instance PathPiece PersistValue where
fromPathPiece t =
case Data.Text.Read.signed Data.Text.Read.decimal t of
Right (i, t')
| T.null t' -> Just $ PersistInt64 i
_ -> case reads $ T.unpack t of
[(fks, "")] -> Just $ PersistList fks
_ -> Just $ PersistText t
toPathPiece x =
case fromPersistValueText x of
Left e -> error $ T.unpack e
Right y -> y
fromPersistValueText :: PersistValue -> Either Text Text
fromPersistValueText (PersistText s) = Right s
fromPersistValueText (PersistByteString bs) =
Right $ TE.decodeUtf8With lenientDecode bs
fromPersistValueText (PersistInt64 i) = Right $ T.pack $ show i
fromPersistValueText (PersistDouble d) = Right $ T.pack $ show d
fromPersistValueText (PersistRational r) = Right $ T.pack $ show r
fromPersistValueText (PersistDay d) = Right $ T.pack $ show d
fromPersistValueText (PersistTimeOfDay d) = Right $ T.pack $ show d
fromPersistValueText (PersistUTCTime d) = Right $ T.pack $ show d
fromPersistValueText PersistNull = Left "Unexpected null"
fromPersistValueText (PersistBool b) = Right $ T.pack $ show b
fromPersistValueText (PersistList _) = Left "Cannot convert PersistList to Text"
fromPersistValueText (PersistMap _) = Left "Cannot convert PersistMap to Text"
fromPersistValueText (PersistObjectId _) = Left "Cannot convert PersistObjectId to Text"
fromPersistValueText (PersistDbSpecific _) = Left "Cannot convert PersistDbSpecific to Text"
instance A.ToJSON PersistValue where
toJSON (PersistText t) = A.String $ T.cons 's' t
toJSON (PersistByteString b) = A.String $ T.cons 'b' $ TE.decodeUtf8 $ B64.encode b
toJSON (PersistInt64 i) = A.Number $ fromIntegral i
toJSON (PersistDouble d) = A.Number $
#if MIN_VERSION_aeson(0, 7, 0)
Data.Scientific.fromFloatDigits
#else
AN.D
#endif
d
toJSON (PersistRational r) = A.String $ T.pack $ 'r' : show r
toJSON (PersistBool b) = A.Bool b
toJSON (PersistTimeOfDay t) = A.String $ T.pack $ 't' : show t
toJSON (PersistUTCTime u) = A.String $ T.pack $ 'u' : show u
toJSON (PersistDay d) = A.String $ T.pack $ 'd' : show d
toJSON PersistNull = A.Null
toJSON (PersistList l) = A.Array $ V.fromList $ map A.toJSON l
toJSON (PersistMap m) = A.object $ map (second A.toJSON) m
toJSON (PersistDbSpecific b) = A.String $ T.cons 'p' $ TE.decodeUtf8 $ B64.encode b
toJSON (PersistObjectId o) =
A.toJSON $ showChar 'o' $ showHexLen 8 (bs2i four) $ showHexLen 16 (bs2i eight) ""
where
(four, eight) = BS8.splitAt 4 o
-- taken from crypto-api
bs2i :: ByteString -> Integer
bs2i bs = foldl' (\i b -> (i `shiftL` 8) + fromIntegral b) 0 bs
{-# INLINE bs2i #-}
-- showHex of n padded with leading zeros if necessary to fill d digits
-- taken from Data.BSON
showHexLen :: (Show n, Integral n) => Int -> n -> ShowS
showHexLen d n = showString (replicate (d - sigDigits n) '0') . showHex n where
sigDigits 0 = 1
sigDigits n' = truncate (logBase (16 :: Double) $ fromIntegral n') + 1
instance A.FromJSON PersistValue where
parseJSON (A.String t0) =
case T.uncons t0 of
Nothing -> fail "Null string"
Just ('p', t) -> either (fail "Invalid base64") (return . PersistDbSpecific)
$ B64.decode $ TE.encodeUtf8 t
Just ('s', t) -> return $ PersistText t
Just ('b', t) -> either (fail "Invalid base64") (return . PersistByteString)
$ B64.decode $ TE.encodeUtf8 t
Just ('t', t) -> fmap PersistTimeOfDay $ readMay t
Just ('u', t) -> fmap PersistUTCTime $ readMay t
Just ('d', t) -> fmap PersistDay $ readMay t
Just ('r', t) -> fmap PersistRational $ readMay t
Just ('o', t) -> maybe (fail "Invalid base64") (return . PersistObjectId) $
fmap (i2bs (8 * 12) . fst) $ headMay $ readHex $ T.unpack t
Just (c, _) -> fail $ "Unknown prefix: " ++ [c]
where
headMay [] = Nothing
headMay (x:_) = Just x
readMay :: (Read a, Monad m) => T.Text -> m a
readMay t =
case reads $ T.unpack t of
(x, _):_ -> return x
[] -> fail "Could not read"
-- taken from crypto-api
-- |@i2bs bitLen i@ converts @i@ to a 'ByteString' of @bitLen@ bits (must be a multiple of 8).
i2bs :: Int -> Integer -> BS.ByteString
i2bs l i = BS.unfoldr (\l' -> if l' < 0 then Nothing else Just (fromIntegral (i `shiftR` l'), l' - 8)) (l-8)
{-# INLINE i2bs #-}
#if MIN_VERSION_aeson(0, 7, 0)
parseJSON (A.Number n) = return $
if fromInteger (floor n) == n
then PersistInt64 $ floor n
else PersistDouble $ fromRational $ toRational n
#else
parseJSON (A.Number (AN.I i)) = return $ PersistInt64 $ fromInteger i
parseJSON (A.Number (AN.D d)) = return $ PersistDouble d
#endif
parseJSON (A.Bool b) = return $ PersistBool b
parseJSON A.Null = return $ PersistNull
parseJSON (A.Array a) = fmap PersistList (mapM A.parseJSON $ V.toList a)
parseJSON (A.Object o) =
fmap PersistMap $ mapM go $ HM.toList o
where
go (k, v) = fmap ((,) k) $ A.parseJSON v
-- | A SQL data type. Naming attempts to reflect the underlying Haskell
-- datatypes, eg SqlString instead of SqlVarchar. Different SQL databases may
-- have different translations for these types.
data SqlType = SqlString
| SqlInt32
| SqlInt64
| SqlReal
| SqlNumeric Word32 Word32
| SqlBool
| SqlDay
| SqlTime
| SqlDayTime -- ^ Always uses UTC timezone
| SqlBlob
| SqlOther T.Text -- ^ a backend-specific name
deriving (Show, Read, Eq, Typeable, Ord)
data PersistFilter = Eq | Ne | Gt | Lt | Ge | Le | In | NotIn
| BackendSpecificFilter T.Text
deriving (Read, Show)
data UpdateException = KeyNotFound String
| UpsertError String
deriving Typeable
instance Show UpdateException where
show (KeyNotFound key) = "Key not found during updateGet: " ++ key
show (UpsertError msg) = "Error during upsert: " ++ msg
instance Exception UpdateException
data OnlyUniqueException = OnlyUniqueException String deriving Typeable
instance Show OnlyUniqueException where
show (OnlyUniqueException uniqueMsg) =
"Expected only one unique key, got " ++ uniqueMsg
instance Exception OnlyUniqueException
data PersistUpdate = Assign | Add | Subtract | Multiply | Divide
| BackendSpecificUpdate T.Text
deriving (Read, Show)
|
mitchellwrosen/persistent
|
persistent/Database/Persist/Types/Base.hs
|
mit
| 17,328
| 0
| 18
| 4,633
| 3,793
| 2,070
| 1,723
| 347
| 4
|
{-# LANGUAGE ExplicitForAll #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeInType #-}
{-# LANGUAGE TypeApplications #-}
module ExplicitForAllRules1 where
import Data.Proxy
import Data.Kind
-- From Proposal 0007 (w/ fix to "example")
{-# RULES
"example" forall a b. forall. map @a @b f = f
"example2" forall a. forall (x :: a). id' x = x
#-}
{-# NOINLINE f #-}
f :: a -> b
f = undefined
id' :: a -> a
id' x = x
{-# NOINLINE id' #-}
-- More tests
{-# RULES
"example3" forall (a :: Type -> Type) (b :: a Int) c. forall x y. g @(Proxy b) @(Proxy c) x y = ()
"example4" forall (a :: Bool) (b :: Proxy a). forall x. g @(Proxy b) @() x = id' @()
"example5" forall (a :: Type). forall. h @a = id' @a
"example5" forall k (c :: k). forall (x :: Proxy c). id' @(Proxy c) x = x
#-}
{-# NOINLINE g #-}
g :: a -> b -> ()
g _ _ = ()
{-# NOINLINE h #-}
h :: a -> a
h x = x
-- Should NOT have a parse error :(
{-# RULES "example6" forall a forall. g a forall = () #-}
-- Should generate a warning
{-# RULES "example7" forall a b. forall (x :: a). id' x = x #-}
|
sdiehl/ghc
|
testsuite/tests/rename/should_compile/ExplicitForAllRules1.hs
|
bsd-3-clause
| 1,119
| 0
| 7
| 252
| 107
| 67
| 40
| 31
| 1
|
<?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="ar-SA">
<title>Sequence Scanner | ZAP Extension</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>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>
|
thc202/zap-extensions
|
addOns/sequence/src/main/javahelp/org/zaproxy/zap/extension/sequence/resources/help_ar_SA/helpset_ar_SA.hs
|
apache-2.0
| 977
| 78
| 66
| 159
| 413
| 209
| 204
| -1
| -1
|
<?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="it-IT">
<title>Active Scan Rules - Alpha | ZAP Extension</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Ricerca</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>
|
thc202/zap-extensions
|
addOns/ascanrulesAlpha/src/main/javahelp/org/zaproxy/zap/extension/ascanrulesAlpha/resources/help_it_IT/helpset_it_IT.hs
|
apache-2.0
| 987
| 78
| 67
| 162
| 420
| 212
| 208
| -1
| -1
|
module PatternMatch6 where
g = (\(y:ys) -> (case y of
p | p == 45 -> 12
_ -> 52))
f x = (\(p:ps) -> (case p of
x | x == 45 -> 12
_ -> 52))
|
kmate/HaRe
|
old/testing/foldDef/PatternMatch6.hs
|
bsd-3-clause
| 205
| 0
| 14
| 104
| 105
| 56
| 49
| 7
| 2
|
module FunIn4 where
main :: Int
main
= sum [x + 4 | let foo y = [1 .. 4]
foo_y = undefined,
x <- (foo foo_y)]
|
kmate/HaRe
|
old/testing/addOneParameter/FunIn4_AstOut.hs
|
bsd-3-clause
| 136
| 6
| 12
| 53
| 60
| 34
| 26
| 6
| 1
|
{-# LANGUAGE TemplateHaskell #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-| Unittests for ganeti-htools.
-}
{-
Copyright (C) 2009, 2010, 2011, 2012 Google Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
-}
module Test.Ganeti.HTools.Loader (testHTools_Loader) where
import Test.QuickCheck
import qualified Data.IntMap as IntMap
import qualified Data.Map as Map
import Data.List
import System.Time (ClockTime(..))
import Test.Ganeti.TestHelper
import Test.Ganeti.TestCommon
import Test.Ganeti.HTools.Node ()
import qualified Ganeti.BasicTypes as BasicTypes
import qualified Ganeti.HTools.Container as Container
import qualified Ganeti.HTools.Loader as Loader
import qualified Ganeti.HTools.Node as Node
prop_lookupNode :: [(String, Int)] -> String -> String -> Property
prop_lookupNode ktn inst node =
Loader.lookupNode nl inst node ==? Map.lookup node nl
where nl = Map.fromList ktn
prop_lookupInstance :: [(String, Int)] -> String -> Property
prop_lookupInstance kti inst =
Loader.lookupInstance il inst ==? Map.lookup inst il
where il = Map.fromList kti
prop_assignIndices :: Property
prop_assignIndices =
-- generate nodes with unique names
forAll (arbitrary `suchThat`
(\nodes ->
let names = map Node.name nodes
in length names == length (nub names))) $ \nodes ->
let (nassoc, kt) =
Loader.assignIndices (map (\n -> (Node.name n, n)) nodes)
in Map.size nassoc == length nodes &&
Container.size kt == length nodes &&
(null nodes || maximum (IntMap.keys kt) == length nodes - 1)
-- | Checks that the number of primary instances recorded on the nodes
-- is zero.
prop_mergeData :: [Node.Node] -> Bool
prop_mergeData ns =
let na = Container.fromList $ map (\n -> (Node.idx n, n)) ns
in case Loader.mergeData [] [] [] [] (TOD 0 0)
(Loader.emptyCluster {Loader.cdNodes = na}) of
BasicTypes.Bad _ -> False
BasicTypes.Ok (Loader.ClusterData _ nl il _ _) ->
let nodes = Container.elems nl
instances = Container.elems il
in (sum . map (length . Node.pList)) nodes == 0 &&
null instances
-- | Check that compareNameComponent on equal strings works.
prop_compareNameComponent_equal :: String -> Bool
prop_compareNameComponent_equal s =
BasicTypes.compareNameComponent s s ==
BasicTypes.LookupResult BasicTypes.ExactMatch s
-- | Check that compareNameComponent on prefix strings works.
prop_compareNameComponent_prefix :: NonEmptyList Char -> String -> Bool
prop_compareNameComponent_prefix (NonEmpty s1) s2 =
BasicTypes.compareNameComponent (s1 ++ "." ++ s2) s1 ==
BasicTypes.LookupResult BasicTypes.PartialMatch s1
testSuite "HTools/Loader"
[ 'prop_lookupNode
, 'prop_lookupInstance
, 'prop_assignIndices
, 'prop_mergeData
, 'prop_compareNameComponent_equal
, 'prop_compareNameComponent_prefix
]
|
vladimir-ipatov/ganeti
|
test/hs/Test/Ganeti/HTools/Loader.hs
|
gpl-2.0
| 3,565
| 0
| 20
| 704
| 780
| 423
| 357
| 60
| 2
|
{-# LANGUAGE TemplateHaskell #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-| Unittests for ganeti-htools.
-}
{-
Copyright (C) 2009, 2010, 2011, 2012 Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Test.Ganeti.HTools.CLI (testHTools_CLI) where
import Test.HUnit
import Test.QuickCheck
import Control.Monad
import Data.List
import Text.Printf (printf)
import Test.Ganeti.TestHelper
import Test.Ganeti.TestCommon
import Test.Ganeti.Common
import Ganeti.BasicTypes
import Ganeti.HTools.CLI as CLI
import qualified Ganeti.HTools.Program.Main as Program
import qualified Ganeti.HTools.Types as Types
{-# ANN module "HLint: ignore Use camelCase" #-}
-- | Test correct parsing.
prop_parseISpec :: String -> Int -> Int -> Int -> Maybe Int -> Property
prop_parseISpec descr dsk mem cpu spn =
let (str, spn') = case spn of
Nothing -> (printf "%d,%d,%d" dsk mem cpu::String, 1)
Just spn'' ->
(printf "%d,%d,%d,%d" dsk mem cpu spn''::String, spn'')
in parseISpecString descr str ==? Ok (Types.RSpec cpu mem dsk spn')
-- | Test parsing failure due to wrong section count.
prop_parseISpecFail :: String -> Property
prop_parseISpecFail descr =
forAll (choose (0,100) `suchThat` (not . flip elem [3, 4])) $ \nelems ->
forAll (replicateM nelems arbitrary) $ \values ->
let str = intercalate "," $ map show (values::[Int])
in case parseISpecString descr str of
Ok v -> failTest $ "Expected failure, got " ++ show v
_ -> passTest
-- | Test a few string arguments.
prop_string_arg :: String -> Property
prop_string_arg argument =
let args = [ (oDataFile, optDataFile)
, (oDynuFile, optDynuFile)
, (oSaveCluster, optSaveCluster)
, (oPrintCommands, optShowCmds)
, (genOLuxiSocket "", optLuxi)
, (oIAllocSrc, optIAllocSrc)
]
in conjoin $ map (\(o, opt) ->
checkOpt Just defaultOptions
failTest (const (==?)) Just (argument, o, opt)) args
-- | Test a few positive arguments.
prop_numeric_arg :: Positive Double -> Property
prop_numeric_arg (Positive argument) =
let args = [ (oMaxCpu, optMcpu)
, (oMinDisk, Just . optMdsk)
, (oMinGain, Just . optMinGain)
, (oMinGainLim, Just . optMinGainLim)
, (oMinScore, Just . optMinScore)
]
in conjoin $
map (\(x, y) -> checkOpt (Just . show) defaultOptions
failTest (const (==?)) Just (argument, x, y)) args
-- | Test a few boolean arguments.
case_bool_arg :: Assertion
case_bool_arg =
mapM_ (checkOpt (const Nothing) defaultOptions assertFailure
assertEqual id)
[ (False, oDiskMoves, optDiskMoves)
, (False, oInstMoves, optInstMoves)
, (True, oEvacMode, optEvacMode)
, (True, oExecJobs, optExecJobs)
, (True, oNoHeaders, optNoHeaders)
, (True, oNoSimulation, optNoSimulation)
]
-- | Tests a few invalid arguments.
case_wrong_arg :: Assertion
case_wrong_arg =
mapM_ (passFailOpt defaultOptions assertFailure (return ()))
[ (oSpindleUse, "-1", "1")
, (oSpindleUse, "a", "1")
, (oMaxCpu, "-1", "1")
, (oMinDisk, "a", "1")
, (oMinGainLim, "a", "1")
, (oMaxSolLength, "x", "10")
, (oStdSpec, "no-such-spec", "1,1,1")
, (oTieredSpec, "no-such-spec", "1,1,1")
]
-- | Test that all binaries support some common options.
case_stdopts :: Assertion
case_stdopts =
mapM_ (\(name, (_, o, a, _)) -> do
o' <- o
checkEarlyExit defaultOptions name
(o' ++ genericOpts) a) Program.personalities
testSuite "HTools/CLI"
[ 'prop_parseISpec
, 'prop_parseISpecFail
, 'prop_string_arg
, 'prop_numeric_arg
, 'case_bool_arg
, 'case_wrong_arg
, 'case_stdopts
]
|
apyrgio/snf-ganeti
|
test/hs/Test/Ganeti/HTools/CLI.hs
|
bsd-2-clause
| 5,256
| 0
| 16
| 1,335
| 1,039
| 606
| 433
| 87
| 2
|
module HiddenInstancesB (Foo, Bar) where
import HiddenInstancesA
|
DavidAlphaFox/ghc
|
utils/haddock/html-test/src/HiddenInstancesB.hs
|
bsd-3-clause
| 65
| 0
| 4
| 7
| 15
| 10
| 5
| 2
| 0
|
{-# LANGUAGE ForeignFunctionInterface, MagicHash #-}
module T12076lit where
-- This test-case demonstrates that cpeApp's collect_args can
-- be invoked on a literal
import Foreign.C
import Foreign
import GHC.Exts
main = do let y = Ptr "LOL"#
x <- strlen y
x2 <- strlen y -- don't inline y
case (x,x2) of
(3,3) -> putStrLn "Yes"
_ -> putStrLn "No"
foreign import ccall unsafe "strlen"
strlen :: Ptr a -> IO Int
|
olsner/ghc
|
testsuite/tests/simplCore/should_compile/T12076lit.hs
|
bsd-3-clause
| 470
| 0
| 10
| 131
| 119
| 62
| 57
| 13
| 2
|
{-# LANGUAGE OverloadedStrings #-}
module Main (main) where
import Control.Applicative
import Control.Monad
import qualified Data.ByteString.Char8 as B8
import System.Environment
import System.Exit
import qualified System.IO as IO
import Kafka
main :: IO ()
main = do
args <- getArgs
when (null args) $ do
putStrLn "USAGE: consoleProducer TOPIC"
exitFailure
let topic = Topic (B8.pack $ head args)
withConnection "localhost" 9092 $ \conn ->
whileM_ (not <$> IO.isEOF) $ do
line <- B8.getLine
produce conn [Produce topic 0 [line]]
whileM_ :: Monad m => m Bool -> m a -> m ()
whileM_ cond action = loop
where
loop = do
x <- cond
when x (action >> loop)
|
abhinav/kafka-client
|
examples/consoleProducer.hs
|
mit
| 766
| 0
| 15
| 222
| 254
| 129
| 125
| 25
| 1
|
-- Copyright 2017 Maximilian Huber <oss@maximilian-huber.de>
-- SPDX-License-Identifier: MIT
-- stolen from: https://wiki.haskell.org/Xmonad/Config_archive/adamvo's_xmonad.hs
module XMonad.MyConfig.ToggleFollowFocus
( applyMyFollowFocus
) where
import XMonad
import qualified XMonad.Util.ExtensibleState as XS
import XMonad.Actions.UpdatePointer ( updatePointer )
import Data.Monoid
import XMonad.Util.EZConfig (additionalKeys)
import XMonad.MyConfig.Common
applyMyFollowFocus :: XConfig a -> XConfig a
applyMyFollowFocus c = c { handleEventHook = focusFollow <+> handleEventHook c
, logHook = updatePointerIfFollowFoucs >> logHook c
, focusFollowsMouse = False
} `additionalKeys` (mapToWithModM c [((m__, xK_s), toggleFF)])
-- Toggle follow Mouse
-- from: http://www.haskell.org/haskellwiki/Xmonad/Config_archive/adamvo's_xmonad.hs
-- A nice little example of extensiblestate
newtype FocusFollow = FocusFollow {getFocusFollow :: Bool} deriving (Typeable,Read,Show)
instance ExtensionClass FocusFollow where
initialValue = FocusFollow True
extensionType = PersistentExtension
-- this eventHook is the same as from xmonad for handling crossing events
focusFollow :: Event -> X All
focusFollow e@(CrossingEvent {ev_window=w, ev_event_type=t})
| t == enterNotify, ev_mode e == notifyNormal =
whenX (XS.gets getFocusFollow) (focus w) >> return (All True)
focusFollow _ = return (All True)
-- updatePointerIfFollowFoucs
updatePointerIfFollowFoucs :: X()
updatePointerIfFollowFoucs = whenX (XS.gets getFocusFollow) $
updatePointer (0.5,0.5) (0.5,0.5)
toggleFF :: X()
toggleFF = XS.modify $ FocusFollow . not . getFocusFollow
|
maximilianhuber/myconfig
|
xmonad/lib/XMonad/MyConfig/ToggleFollowFocus.hs
|
mit
| 1,788
| 0
| 10
| 350
| 387
| 217
| 170
| 27
| 1
|
module Backend.PrettyPrint (prettyPrint) where
import Control.Monad.Reader
import Control.Monad.State
import Control.Monad.Writer
import Data.List
import Frontend.Values
import Frontend.Primitives
import Backend.AST
import Internal
-- Pretty print
prettyPrint :: LProgram -> String
prettyPrint decls = intercalate "\n\n" $ map (runPP . ppDecl) decls
type IsNewline = Bool
type Indent = Bool
type PP a = StateT IsNewline (ReaderT Indent (Writer String)) a
runPP :: PP a -> String
runPP = execWriter . flip runReaderT False . flip evalStateT True
indentString :: String
indentString = "\t"
withIndent :: PP a -> PP a
withIndent m = local (const True) m
newline :: PP ()
newline = do
isNewline <- get
unless isNewline $ do
indent <- asks $ \i -> if i then indentString else ""
tell $ '\n' : indent
put True
write :: String -> PP ()
write s = tell s >> put False
ppDecl :: LDecl -> PP ()
ppDecl (LFunDecl t n args blocks) = do
newline
write $ show t ++ " " ++ show n
write $ "(" ++ intercalate ", " (map showBinder args) ++ ")"
mapM_ ppBlock blocks
ppBlock :: LBlock -> PP ()
ppBlock (LBlock label args statements transfur) = do
newline
write $ show label
unless (null args) $
write $ "(" ++ intercalate ", " (map showBinder args) ++ ")"
write $ ":"
withIndent $ mapM_ ppStatement statements
withIndent $ ppTransfur transfur
ppTransfur :: LTransfur -> PP ()
ppTransfur (LReturn n) = do
newline
write $ "return " ++ show n
ppTransfur (LIf cmp n1 n2 l1 l2) = do
newline
write $ "if " ++ show n1 ++ " " ++ show cmp ++ " " ++ show n2 ++ ", "
write $ show l1 ++ ", " ++ show l2
ppTransfur (LMatch n alts default') = do
newline
write $ "match " ++ show n ++ ", "
write $ "[" ++ intercalate ", " (map (\(i, l)-> '#' : show i ++ " " ++ show l) alts) ++ "]"
ppTransfur (LGoto label ns) = do
newline
write $ "goto " ++ show label ++ ", " ++ intercalate ", " (map show ns)
ppTransfur (LTailCall n ns) = do
newline
write $ "tailcall " ++ show n ++ ", " ++ intercalate ", " (map show ns)
ppStatement :: LStatement -> PP ()
ppStatement (b, inst) = do
newline
write $ showBinder b ++ " <- "
ppInst inst
ppInst :: LInst -> PP ()
ppInst (LVar n) = write $ show n
ppInst (LValue v) = write $ show v
ppInst (LCall n ns) =
write $ "call " ++ show n ++ ", " ++ intercalate ", " (map show ns)
ppInst (LOp (Cmp cmp) [n1, n2]) =
write $ show n1 ++ " " ++ show cmp ++ " " ++ show n2
ppInst (LOp (Arith Minus) [n]) =
write $ show Minus ++ " " ++ show n ++ " "
ppInst (LOp (Arith op) [n1, n2]) =
write $ show n1 ++ " " ++ show op ++ " " ++ show n2
ppInst (LOp (FArith FMinus) [n]) =
write $ show Minus ++ " " ++ show n ++ " "
ppInst (LOp (FArith op) [n1, n2]) =
write $ show n1 ++ " " ++ show op ++ " " ++ show n2
ppInst (LCon tag ns) = do
write $ ('#' : show tag) ++ " "
case ns of
[] -> return ()
[n] -> write $ show n
_ -> write $ "(" ++ intercalate ", " (map show ns) ++ ")"
ppInst (LTuple ns) =
write $ "(" ++ intercalate ", " (map show ns) ++ ")"
ppInst (LProj i n) =
write $ "proj" ++ show i ++ " " ++ show n
ppInst (LExtCall s ns) =
write $ ('%' : s) ++ " " ++ intercalate ", " (map show ns)
ppInst (LCast _ n) =
write $ "cast" ++ " " ++ show n
showBinder :: LBinder -> String
showBinder (n, t) = show t ++ " " ++ show n
|
alpicola/mel
|
src/Backend/PrettyPrint.hs
|
mit
| 3,325
| 0
| 17
| 805
| 1,579
| 767
| 812
| 98
| 3
|
{-# LANGUAGE NamedFieldPuns, RecordWildCards, GeneralizedNewtypeDeriving #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE BangPatterns #-}
module Galua.Micro.Type.Monad
( -- * Analysis
AnalysisM, GlobalBlockName(..)
, allPaths, singlePath
-- ** Backtracking
, impossible, options
-- ** Global state
, getGlobal, setGlobal
-- * Single function
-- ** Blocks
, BlockM, inBlock
-- ** Functions
, newFunId, setCurFun
, PrimImpl(..)
, getPrim
-- * Single block
, curStmt, continue
-- ** References
, newRefId, readRefId, writeRefId
-- ** Tables
, newTableId, getTable, setTable, getTableMeta
-- ** Locals
, assign, getReg, getUpVal
, getList, setList
, getLocal
, -- ** Continuations
Cont, getCont, setCont, CallsiteId, initialCaller
, -- ** Errors
raisesError
, -- * Top values
anyTableId, anyRefId, anyFunId
, -- * Logging
logTrace, logError
) where
import Data.Map ( Map )
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Data.Vector as Vector
import qualified MonadLib as M
import MonadLib hiding (raises,sets,sets_,ask,get)
import Galua.Micro.AST
import Galua.Micro.Type.Value
import qualified Galua.Code as Code
class Monad m => AnalysisM m where
ask :: m RO
sets :: (AnalysisS -> (a,AnalysisS)) -> m a
options :: [a] -> m a
-- | Consider all paths through the code.
-- More preciese, but also more expensive.
newtype AllPaths a = AllPaths (ReaderT RO (StateT AnalysisS []) a)
deriving (Functor,Applicative,Monad)
-- | Consier only one path through the code, joining alternatives.
-- Less precise, but a bit cheaper.
newtype SinglePath a = SinglePath (ReaderT RO (ChoiceT (StateT AnalysisS Id)) a)
deriving (Functor,Applicative,Monad)
instance AnalysisM AllPaths where
ask = AllPaths M.ask
sets = AllPaths . M.sets
options = AllPaths . lift . lift
instance AnalysisM SinglePath where
ask = SinglePath M.ask
sets = SinglePath . M.sets
options = SinglePath . lift . msum . map return
get :: AnalysisM m => m AnalysisS
get = sets $ \s -> (s,s)
sets_ :: AnalysisM m => (AnalysisS -> AnalysisS) -> m ()
sets_ f = sets $ \s -> ((),f s)
-- | Infromation about code in the environemnt.
data RO = RO
{ roCode :: Map FunId MicroFunction
, roPrims :: Map CFun PrimImpl
}
-- | A primitive: given the state and some arguments, return an update
-- state, and either an exception or a list of restuls.
newtype PrimImpl = PrimImpl
(forall m. AnalysisM m => GlobalState -> List Value ->
m (Either Value (List Value), GlobalState))
-- | The state of the analysis.
data AnalysisS = AnalysisS
{ rwStates :: !(Map GlobalBlockName State)
-- ^ Known states at the entries of blocks.
, rwRaises :: !(Map GlobalBlockName Value)
, logLines :: [String]
}
--------------------------------------------------------------------------------
impossible :: AnalysisM m => m a
impossible = options []
allPaths ::
Map FunId MicroFunction ->
Map CFun PrimImpl ->
AllPaths a ->
[ (a, Map GlobalBlockName State , Map GlobalBlockName Value, [String]) ]
allPaths funs prims (AllPaths m) =
[ (a, rwStates rw, rwRaises rw, reverse (logLines rw))
| (a,!rw) <- runStateT initS $ runReaderT ro m ]
where
initS = AnalysisS { rwStates = Map.empty
, rwRaises = Map.empty
, logLines = []
}
ro = RO { roCode = funs, roPrims = prims }
singlePath ::
Map FunId MicroFunction ->
Map CFun PrimImpl ->
SinglePath a ->
([a], Map GlobalBlockName State, Map GlobalBlockName Value, [String])
singlePath funs prims (SinglePath m) = (as, rwStates rw, rwRaises rw, reverse(logLines rw))
where
(as,!rw) = runId $ runStateT initS $ findAll $ runReaderT ro m
initS = AnalysisS { rwStates = Map.empty
, rwRaises = Map.empty
, logLines = []
}
ro = RO { roCode = funs, roPrims = prims }
--------------------------------------------------------------------------------
{- | Enter a block with with a particular state.
If we've already done the analysis for this state (i.e., adding it
to the old state does not produce any new information), then we don't
do anything. -}
tryEnterBlockAt :: AnalysisM m => GlobalBlockName -> State -> m BlockS
tryEnterBlockAt loc sCur =
do AnalysisS { rwStates = states } <- get
let GlobalBlockName caller (QualifiedBlockName curFun b) = loc
sOld = Map.findWithDefault bottom loc states
case addNewInfo sCur sOld of
Just sNew ->
do sets_ $ \AnalysisS { .. } ->
AnalysisS { rwStates = Map.insert loc sNew rwStates, .. }
RO { roCode } <- ask
let ss = case Map.lookup curFun roCode of
Just f ->
case Map.lookup b (functionCode f) of
Just b1 -> b1
Nothing -> error $ "The block is missing: " ++
show b ++
"\nI'm in function: " ++
Code.funIdString curFun
Nothing ->
error $ "The current function is missing: " ++
show curFun
return BlockS { rwCurBlock = b
, rwCurOpCode = 0
, rwStatements = ss
, rwCurState = sNew
, rwCurFunId = curFun
, rwCurCallsite = caller
}
_ -> impossible
runBlockM :: AnalysisM m => BlockS -> BlockM a -> m (a, State)
runBlockM s (BlockM m) = do (a,rw) <- runStateT s m
return (a, rwCurState rw)
inBlock :: AnalysisM m => GlobalBlockName -> State -> BlockM a -> m (a, State)
inBlock b s m =
do s1 <- tryEnterBlockAt b s
runBlockM s1 m
--------------------------------------------------------------------------------
newtype BlockM a = BlockM (forall m. AnalysisM m => StateT BlockS m a)
instance Functor BlockM where
fmap = liftM
instance Applicative BlockM where
pure a = BlockM (return a)
(<*>) = ap
instance Monad BlockM where
BlockM m >>= f = BlockM (do a <- m
let BlockM m1 = f a
m1)
instance AnalysisM BlockM where
ask = BlockM (lift ask)
sets f = BlockM (lift (sets f))
options os = BlockM (lift (options os))
getPrim :: AnalysisM m => CFun -> m (Maybe PrimImpl)
getPrim ptr =
do RO { roPrims } <- ask
return (Map.lookup ptr roPrims)
data BlockS = BlockS
{ rwCurBlock :: !BlockName
, rwCurOpCode :: !Int
, rwStatements :: !Block
, rwCurState :: !State
, rwCurFunId :: !FunId -- ^ Current function that is executed.
, rwCurCallsite :: !CallsiteId -- ^ Where we were called from.
}
--------------------------------------------------------------------------------
-- Errors
raisesError :: Value -> BlockM ()
raisesError v =
do BlockS { rwCurBlock } <- BlockM M.get
blockRaisesError rwCurBlock v
blockRaisesError :: BlockName -> Value -> BlockM ()
blockRaisesError _ v =
do gb <- getCurGlobalBlockName
sets_ $ \a -> a { rwRaises = Map.insertWith (\/) gb v (rwRaises a) }
--------------------------------------------------------------------------------
-- Continuations, for functions calls
data Cont = Cont { plFun :: FunId
, plBlock :: BlockName
, plPC :: Int
, plStmts :: Block
, plLocals :: LocalState
, plCallsite :: CallsiteId
}
getCont :: BlockM (CallsiteId, Cont)
getCont = do BlockS { .. } <- BlockM M.get
let callsiteId = CallsiteId (QualifiedBlockName rwCurFunId rwCurBlock) rwCurOpCode
cont = Cont
{ plFun = rwCurFunId
, plCallsite = rwCurCallsite
, plBlock = rwCurBlock
, plPC = rwCurOpCode
, plStmts = rwStatements
, plLocals = localState rwCurState
}
return (callsiteId, cont)
setCont :: Cont -> BlockM ()
setCont Cont { .. } =
BlockM $
M.sets_ $ \s -> s { rwCurBlock = plBlock
, rwCurCallsite = plCallsite
, rwCurOpCode = plPC
, rwStatements = plStmts
, rwCurFunId = plFun
, rwCurState = (rwCurState s) { localState = plLocals }
}
--------------------------------------------------------------------------------
curStmt :: BlockM (Either (BlockStmt Stmt) (BlockStmt EndStmt))
curStmt = BlockM $ do BlockS { rwStatements, rwCurOpCode } <- M.get
case blockBody rwStatements Vector.!? rwCurOpCode of
Just s -> return (Left s)
Nothing -> return (Right (blockEnd rwStatements))
continue :: BlockM ()
continue = BlockM $ M.sets_ $ \s -> s { rwCurOpCode = 1 + rwCurOpCode s }
--------------------------------------------------------------------------------
-- Manipulating the state
getState :: BlockM State
getState = BlockM $ do BlockS { rwCurState } <- M.get
return rwCurState
setState :: State -> BlockM ()
setState s = BlockM $ M.sets_ $ \b -> b { rwCurState = s }
updState :: (State -> State) -> BlockM ()
updState f = do s <- getState
setState (f s)
getGlobal :: BlockM GlobalState
getGlobal = globalState <$> getState
setGlobal :: GlobalState -> BlockM ()
setGlobal g = updState $ \State { .. } -> State { globalState = g, .. }
updGlobal :: (GlobalState -> GlobalState) -> BlockM ()
updGlobal f = do g <- getGlobal
setGlobal (f g)
getLocal :: BlockM LocalState
getLocal = localState <$> getState
setLocal :: LocalState -> BlockM ()
setLocal l = updState $ \State { .. } -> State { localState = l, .. }
updLocal :: (LocalState -> LocalState) -> BlockM ()
updLocal f = do l <- getLocal
setLocal (f l)
--------------------------------------------------------------------------------
-- Working with local values.
assign :: Reg -> RegVal -> BlockM ()
assign r v = updLocal $ \LocalState { env, .. } ->
LocalState { env = Map.insert r v env, .. }
-- Does not return bottom
getReg :: Reg -> BlockM RegVal
getReg r = do LocalState { env } <- getLocal
case Map.lookup r env of
Nothing -> impossible
Just v -> return v
getList :: ListReg -> BlockM (List Value)
getList r =
do LocalState { argReg, listReg } <- getLocal
return $! case r of
ListReg -> listReg
ArgReg -> argReg
setList :: ListReg -> List Value -> BlockM ()
setList r vs = updLocal $ \s ->
case r of
ListReg -> s { listReg = vs }
ArgReg -> s { argReg = vs }
-- Does not return bottom
getUpVal :: UpIx -> BlockM RegVal
getUpVal u = do LocalState { upvals } <- getLocal
let r = Map.findWithDefault Top u upvals
{- NOTE: generally, upvalues should not be missing, however,
if we are analyzing some source code, and we have no info
about the up-values, it is simpler to pass an empty map,
rather than a map full of Top. -}
return (RegRef r)
--------------------------------------------------------------------------------
-- Tables
anyTableId :: BlockM TableId
anyTableId =
do GlobalState { tables } <- getGlobal
options $ Map.keys tables
newTableId :: BlockM TableId
newTableId =
do BlockS { rwCurOpCode } <- BlockM M.get
gb <- getCurGlobalBlockName
let tid = TableId gb rwCurOpCode
writeTableId tid emptyTable
return tid
where
emptyTable = TableV { tableFields = fConst (basic Nil)
, tableKeys = bottom
, tableValues = basic Nil
, tableMeta = basic Nil
}
readTableId :: TableId -> BlockM TableV
readTableId l = do GlobalState { tables } <- getGlobal
case Map.lookup l tables of
Just v | v /= bottom -> return v
_ -> impossible
writeTableId :: TableId -> TableV -> BlockM ()
writeTableId t v = updGlobal $ \GlobalState { tables, .. } ->
GlobalState { tables = Map.insert t v tables
, .. }
{- NOTE: Modifying "Top" values.
"Top" is used when we are doing a partial analysis, and we don't know
anything about a value. So, when we modify such a value, we could
be modifying any of the currently known values of that type,
*OR* some other external value that we did not know about.
This is why we add the `return ()` csae, indicating that
*nothing* gets modified.
-}
-- See: Modifying "Top" values
setTable :: WithTop TableId -> Value -> Value -> BlockM ()
setTable mb vi v =
case mb of
NotTop l -> doSetTable l
Top -> join $ options [ doSetTable =<< anyTableId, return () ]
where
doSetTable l =
do t <- readTableId l
writeTableId l (setTableEntry (vi,v) t)
getTable :: WithTop TableId -> SingleV -> BlockM Value
getTable Top _ = return topVal
getTable (NotTop l) ti =
do TableV { .. } <- readTableId l
return $ case ti of
StringValue (NotTop xx) -> appFun tableFields xx
StringValue Top -> appAll tableFields
_ | ti `elem` valueCases tableKeys -> tableValues
| otherwise -> basic Nil
getTableMeta :: WithTop TableId -> BlockM Value
getTableMeta Top = return (basic Nil \/ fromSingleV (TableValue Top))
getTableMeta (NotTop l) =
do TableV { .. } <- readTableId l
return tableMeta
--------------------------------------------------------------------------------
-- References
anyRefId :: BlockM RefId
anyRefId =
do GlobalState { heap } <- getGlobal
options $ Map.keys heap
newRefId :: Value -> BlockM RefId
newRefId v =
do BlockS { rwCurOpCode } <- BlockM M.get
gb <- getCurGlobalBlockName
let ref = RefId gb rwCurOpCode
writeRefId (Just ref) v
return ref
readRefId :: Maybe RefId -> BlockM Value
readRefId Nothing = return topVal
readRefId (Just l) = do GlobalState { heap } <- getGlobal
case Map.lookup l heap of
Just v | v /= bottom -> return v
_ -> impossible
-- See: Modifying "Top" values
writeRefId :: Maybe RefId -> Value -> BlockM ()
writeRefId mb v =
case mb of
Just r -> upd r
Nothing -> join $ options [ upd =<< anyRefId, return () ]
where
upd r = updGlobal $ \GlobalState { heap, .. } ->
GlobalState { heap = Map.insert r v heap, .. }
--------------------------------------------------------------------------------
-- Closures
-- | Allocate a new function, given a prototype, and some references.
newFunId :: Int -> [RefId] -> BlockM ClosureId
newFunId proto refs =
do BlockS { rwCurOpCode } <- BlockM M.get
gb <- getCurGlobalBlockName
let ref = ClosureId gb rwCurOpCode
curFun <- getCurFun
let clo = FunV { functionUpVals = Map.fromList (zipWith up [ 0 .. ] refs)
, functionFID = OneValue (LuaFunImpl (subFun curFun proto))
}
updGlobal $ \GlobalState { functions, .. } ->
GlobalState { functions = Map.insert ref clo functions, .. }
return ref
where
up n r = (Code.UpIx n, NotTop (Set.singleton r))
anyFunId :: BlockM ClosureId
anyFunId =
do GlobalState { functions } <- getGlobal
options $ Map.keys functions
--------------------------------------------------------------------------------
-- Current function
getCurFun :: BlockM FunId
getCurFun = do BlockS { rwCurFunId } <- BlockM M.get
return rwCurFunId
setCurFun :: FunId -> BlockM ()
setCurFun fid = BlockM $ M.sets_ $ \s -> s { rwCurFunId = fid }
getCurGlobalBlockName :: BlockM GlobalBlockName
getCurGlobalBlockName =
do BlockS{..} <- BlockM M.get
return (GlobalBlockName rwCurCallsite (QualifiedBlockName rwCurFunId rwCurBlock))
------------------------------------------------------------------------
-- Logging
logError :: String -> BlockM ()
logError = logTrace -- TODO: severities
logTrace :: String -> BlockM ()
logTrace msg = BlockM $ lift $ sets_ $ \s ->
let msgs = logLines s
in msgs `seq` s { logLines = msg : msgs }
|
GaloisInc/galua
|
galua-jit/src/Galua/Micro/Type/Monad.hs
|
mit
| 17,200
| 0
| 24
| 5,397
| 4,592
| 2,384
| 2,208
| 352
| 4
|
module Hogldev.RandomTexture (
RandomTexture(..)
, textureBind
, textureLoad
) where
import Control.Monad (replicateM)
import Foreign.Marshal.Array (withArray)
import System.Random
import Graphics.Rendering.OpenGL
newtype RandomTexture = RandomTexture TextureObject
textureBind :: RandomTexture -> TextureUnit -> IO ()
textureBind (RandomTexture textureObject) textureUnit = do
activeTexture $= textureUnit
textureBinding Texture2D $= Just textureObject
textureLoad :: GLint -> IO RandomTexture
textureLoad size = do
texture <- genObjectName
textureBinding Texture2D $= Just texture
textureData <- replicateM (fromIntegral textureSize)
(randomRIO (0, 1)) :: IO [GLfloat]
withArray textureData $ \ptr ->
texImage2D Texture2D NoProxy 0 RGB32F (TextureSize2D size size) 0
(PixelData RGB Float ptr)
textureFilter Texture2D $= ((Linear', Nothing), Linear')
textureWrapMode Texture2D S $= (Repeated, Repeat)
textureWrapMode Texture2D T $= (Repeated, Repeat)
textureBinding Texture2D $= Nothing
return (RandomTexture texture)
where
textureSize = size * size * 3
|
triplepointfive/hogldev
|
common/Hogldev/RandomTexture.hs
|
mit
| 1,152
| 0
| 11
| 224
| 337
| 172
| 165
| 28
| 1
|
{-# LANGUAGE OverloadedStrings #-}
module OrderByTest where
import qualified Data.Map as M
import qualified Data.Text as T
import qualified Database.Orville.PostgreSQL as O
import qualified Database.Orville.PostgreSQL.Select as S
import qualified TestDB as TestDB
import Control.Monad (void)
import Data.Int (Int64)
import Database.Orville.PostgreSQL.Expr (aliased, qualified)
import Test.Tasty (TestTree, testGroup)
import Test.Tasty.HUnit (assertEqual, testCase)
test_order_by :: TestTree
test_order_by =
TestDB.withOrvilleRun $ \run ->
testGroup
"Order by queries"
[ testCase "Sort Ascending" $ do
run (TestDB.reset schema)
void $ run (O.insertRecord orderTable foobarOrder)
void $ run (O.insertRecord orderTable anotherFoobarOrder)
void $ run (O.insertRecord orderTable orderNamedAlice)
result <- run (O.findRecordsBy orderTable customerFkIdField $
O.order orderNameField O.Ascending
)
let lookupResult =
case M.lookup (CustomerId 2) result of
Just res -> fmap orderName res
Nothing -> []
assertEqual
"Order returned didn't match expected result"
[ orderName orderNamedAlice
, orderName anotherFoobarOrder
]
lookupResult
, testCase "Sort Descending" $ do
run (TestDB.reset schema)
void $ run (O.insertRecord orderTable foobarOrder)
void $ run (O.insertRecord orderTable anotherFoobarOrder)
void $ run (O.insertRecord orderTable orderNamedAlice)
result <- run (O.findRecordsBy orderTable customerFkIdField $
O.order orderNameField O.Descending
)
let lookupResult =
case M.lookup (CustomerId 2) result of
Just res -> fmap orderName res
Nothing -> []
assertEqual
"Order returned didn't match expected result"
[ orderName anotherFoobarOrder
, orderName orderNamedAlice
]
lookupResult
]
data CompleteOrder = CompleteOrder
{ order :: T.Text
, customer :: T.Text
} deriving (Eq, Show)
completeOrderSelect :: O.SelectOptions -> S.Select CompleteOrder
completeOrderSelect = S.selectQuery buildCompleteOrder orderCustomerFrom
buildCompleteOrder :: O.FromSql CompleteOrder
buildCompleteOrder =
CompleteOrder <$>
O.col
(S.selectField orderNameField `qualified` "order" `aliased` "order_name") <*>
O.col
(S.selectField customerNameField `qualified` "customer" `aliased`
"customer_name")
orderCustomerFrom :: S.FromClause
orderCustomerFrom =
S.fromClauseRaw
"FROM \"order\" INNER JOIN \"customer\" ON \"order\".\"customer_id\" = \"customer\".\"id\""
schema :: O.SchemaDefinition
schema = [O.Table orderTable, O.Table customerTable]
-- Order definitions
orderTable :: O.TableDefinition Order Order OrderId
orderTable =
O.mkTableDefinition $
O.TableParams
{ O.tblName = "order"
, O.tblPrimaryKey = O.primaryKey orderIdField
, O.tblMapper =
Order <$> O.attrField orderId orderIdField <*>
O.attrField customerFkId customerFkIdField <*>
O.attrField orderName orderNameField
, O.tblGetKey = orderId
, O.tblSafeToDelete = []
, O.tblComments = O.noComments
}
orderIdField :: O.FieldDefinition O.NotNull OrderId
orderIdField =
O.int64Field "id" `O.withConversion`
O.convertSqlType unOrderId OrderId
customerFkIdField :: O.FieldDefinition O.NotNull CustomerId
customerFkIdField =
O.int64Field "customer_id" `O.withConversion`
O.convertSqlType unCustomerId CustomerId
orderNameField :: O.FieldDefinition O.NotNull OrderName
orderNameField =
O.textField "name" 255 `O.withConversion`
O.convertSqlType unOrderName OrderName
data Order = Order
{ orderId :: OrderId
, customerFkId :: CustomerId
, orderName :: OrderName
} deriving (Show, Eq)
newtype OrderId = OrderId
{ unOrderId :: Int64
} deriving (Show, Eq)
newtype OrderName = OrderName
{ unOrderName :: T.Text
} deriving (Show, Eq)
foobarOrder :: Order
foobarOrder =
Order
{ orderId = OrderId 1
, customerFkId = CustomerId 1
, orderName = OrderName "foobar"
}
anotherFoobarOrder :: Order
anotherFoobarOrder =
Order
{ orderId = OrderId 3
, customerFkId = CustomerId 2
, orderName = OrderName "Foobar"
}
orderNamedAlice :: Order
orderNamedAlice =
Order
{ orderId = OrderId 2
, customerFkId = CustomerId 2
, orderName = OrderName "Alice"
}
orderNameSelect :: O.SelectOptions -> S.Select OrderName
orderNameSelect = S.selectQuery buildOrderName orderNameFrom
buildOrderName :: O.FromSql OrderName
buildOrderName = OrderName <$> O.col (S.selectField orderNameField)
orderNameFrom :: S.FromClause
orderNameFrom = S.fromClauseTable orderTable
-- Customer definitions
customerTable :: O.TableDefinition Customer Customer CustomerId
customerTable =
O.mkTableDefinition $
O.TableParams
{ O.tblName = "customer"
, O.tblPrimaryKey = O.primaryKey customerIdField
, O.tblMapper =
Customer <$> O.attrField customerId customerIdField <*>
O.attrField customerName customerNameField
, O.tblGetKey = customerId
, O.tblSafeToDelete = []
, O.tblComments = O.noComments
}
customerIdField :: O.FieldDefinition O.NotNull CustomerId
customerIdField =
O.int64Field "id" `O.withConversion`
O.convertSqlType unCustomerId CustomerId
customerNameField :: O.FieldDefinition O.NotNull CustomerName
customerNameField =
O.textField "name" 255 `O.withConversion`
O.convertSqlType unCustomerName CustomerName
data Customer = Customer
{ customerId :: CustomerId
, customerName :: CustomerName
} deriving (Show, Eq)
newtype CustomerId = CustomerId
{ unCustomerId :: Int64
} deriving (Show, Eq, Ord)
newtype CustomerName = CustomerName
{ unCustomerName :: T.Text
} deriving (Show, Eq)
|
flipstone/orville
|
orville-postgresql/test/OrderByTest.hs
|
mit
| 6,039
| 0
| 18
| 1,390
| 1,486
| 796
| 690
| 159
| 3
|
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TemplateHaskell #-}
module Dupes.Actions (
update,
listAll,
listDuplicates,
removeInPaths,
removeSuffixes,
testGroup,
DuplicateAction,
) where
import Control.Monad
import Data.List (isPrefixOf)
import Dupes.FileHash (FileHash)
import Dupes.Index (Index)
import qualified Dupes.Index as Index
import Dupes.Repository (Repository)
import qualified Dupes.Repository as Repository
import Dupes.WorkingDirectory
import PathSpec (PathSpec)
import qualified PathSpec
import Pipes
import qualified Pipes.Path as Path
import qualified Pipes.Prelude as P
import Pipes.Safe
import System.Directory (removeFile)
import System.FilePath
import Test.Tasty.HUnit
import Test.Tasty.QuickCheck
import Test.Tasty.TH
data UpdatedIndexEntry = UpdatedIndexEntry FilePath
deriving Show
update :: Repository -> Producer UpdatedIndexEntry (SafeT IO) ()
update repository = hoist liftBase $ Index.withIndex (Repository.indexPath repository) $ \index ->
walk (Repository.workingDirectory repository) >->
P.filter isFileEntry >->
P.map Path.getPath >->
P.map (makeRelativePath (Repository.workingDirectory repository)) >->
P.mapM (\path -> Index.updateFile index path >> return (UpdatedIndexEntry path))
where
isFileEntry (Path.FileEntry _ _) = True
isFileEntry _ = False
listAll :: Repository -> Producer FilePath (SafeT IO) ()
listAll repository = Index.withIndex (Repository.indexPath repository) Index.listAll
listDuplicates :: Repository -> Producer (FilePath, FileHash) (SafeT IO) ()
listDuplicates repository = Index.withIndex (Repository.indexPath repository) Index.listDuplicates
data DuplicateAction = KeepDuplicate FilePath
| RemoveDuplicate FilePath
deriving Show
removeInPaths :: Repository -> [PathSpec] -> Bool -> Producer FilePath (SafeT IO) ()
removeInPaths repository pathspecs dryRun = Index.withIndex (Repository.indexPath repository)
(removeInPaths' pathspecs dryRun)
removeInPaths' :: [PathSpec] -> Bool -> Index -> Producer FilePath (SafeT IO) ()
removeInPaths' pathspecs dryRun index = for hashesWithDuplicates removeForHash >->
P.filter actionIsRemove >->
P.map extractPath >->
P.mapM removePath
where
actionIsRemove (RemoveDuplicate _) = True
actionIsRemove _ = False
extractPath (RemoveDuplicate path) = path
removePath :: FilePath -> SafeT IO FilePath
removePath path = unless dryRun (removePath' path) >> return path
removePath' :: FilePath -> SafeT IO ()
removePath' path = liftBase (removeFile path >> Index.deleteEntryByPath index path)
removeForHash :: FileHash -> Producer DuplicateAction (SafeT IO) ()
removeForHash hash = do
areAnyOutside <- lift $ anyOutside hash
when areAnyOutside (removeAllMatchingFor hash)
anyOutside :: FileHash -> (SafeT IO) Bool
anyOutside hash = pAny' (not . pathSpecMatches) (listFilesWithHash hash)
pAny' :: Monad m => (a -> Bool) -> Producer a m () -> m Bool
pAny' f producer = P.fold (||) False id (producer >-> P.map f)
removeAllMatchingFor :: FileHash -> Producer DuplicateAction (SafeT IO) ()
removeAllMatchingFor hash = listFilesWithHash hash >-> removeProducerByPredicate pathSpecMatches
pathSpecMatches path = any (`PathSpec.matches` path) pathspecs
hashesWithDuplicates = Index.listHashesWithDuplicates index
listFilesWithHash = Index.listFilesWithHash index
data DuplicateSet m a = DuplicateSet FileHash (Producer FilePath m a)
removeSuffixes :: Repository -> Producer DuplicateAction (SafeT IO) ()
removeSuffixes = undefined
data KeepChoice = KeepLeft
| KeepRight
| KeepBoth
removeSuffix :: FilePath -> FilePath -> KeepChoice
removeSuffix leftPath rightPath =
if leftPath `baseNameIsPrefixOf` rightPath
then KeepLeft
else KeepBoth
removeByPredicate :: (a -> Bool) -> a -> a -> KeepChoice
removeByPredicate test left right
| test left = KeepRight
| test right = KeepLeft
| otherwise = KeepBoth
removeProducerByPredicate :: Monad m => (FilePath -> Bool) -> Pipe FilePath DuplicateAction m ()
removeProducerByPredicate f = P.map
(\path -> if f path
then RemoveDuplicate path
else KeepDuplicate path)
removeMatching :: [PathSpec] -> FilePath -> FilePath -> KeepChoice
removeMatching pathspecs =
removeByPredicate (\path -> any (`PathSpec.matches` path) pathspecs)
removeMatching'' :: Monad m => forall r. Producer FilePath m r -> Producer DuplicateAction m r
removeMatching'' = undefined
data DuplicateMatchResult a = DuplicateMatches a
| DoesNotMatch a
matches' :: a -> [PathSpec] -> DuplicateMatchResult a
matches' = undefined
{-|
remove :: Mode -> IO ()
remove (PathSpecs pathSpecs) = removeDupes . matchingAnyOf $ pathSpecs
where
matchingAnyOf :: [PathSpec] -> Condition
matchingAnyOf = Any <$> map Matches
remove Suffixes = removeDupes' (Holds hasPrefixDupe)
where
hasPrefixDupe file = dupes file >>= lift . P.any (`fileBaseNameIsPrefixOf` file)
fileBaseNameIsPrefixOf a b = getFilePath a `baseNameIsPrefixOf` getFilePath b
-}
prop_baseNameIsPrefixOf_nameWithSuffix :: FilePath -> String -> Bool
prop_baseNameIsPrefixOf_nameWithSuffix path suffix =
(validPath ++ ".ext") `baseNameIsPrefixOf` (validPath ++ nameSuffix ++ ".ext")
where
validPath = filter (not . isExtSeparator) path
nameSuffix = filter (not . isExtSeparator) $ filter (not . isPathSeparator) suffix
case_baseNameIsNotPrefixOf_differentDirectoriesSameName =
False @=? "/parent.ext" `baseNameIsPrefixOf` "/parent/file.ext"
case_baseNameIsNotPrefixOf_differentExtensions =
False @=? "file.ext" `baseNameIsPrefixOf` "file.ext2"
case_baseNameIsNotPrefixOf_multiSegmentExtension =
False @=? "file.gz" `baseNameIsPrefixOf` "file.tar.gz"
baseNameIsPrefixOf :: FilePath -> FilePath -> Bool
baseNameIsPrefixOf path1 path2 =
let (dir1, filename1) = splitFileName path1
(dir2, filename2) = splitFileName path2
(basename1, ext1) = splitExtensions filename1
(basename2, ext2) = splitExtensions filename2
in basename1 `isPrefixOf` basename2 && ext1 == ext2 && dir1 `equalFilePath` dir2
testGroup = $(testGroupGenerator)
|
danstiner/dupes
|
src/Dupes/Actions.hs
|
mit
| 6,713
| 0
| 14
| 1,570
| 1,648
| 867
| 781
| 124
| 2
|
module Dusky.IntensityRater
( determineRegionalIntensity
) where
import Codec.Picture.Types
import Data.List
import qualified Data.Map.Strict as Map
import Dusky.Locality
toPercent :: Float -> Int
toPercent = round . (* 100)
takeWeightedAverage :: [(Float, Int)] -> Float
takeWeightedAverage values = foldr weightedSum 0 values / fromIntegral totalCount
where weightedSum (v, count) acc = acc + (fromIntegral count * v)
totalCount = foldr ((+) . snd) 0 values
findBestFits :: [PixelRGBA8]
-> Map.Map PixelRGBA8 Int
-> Map.Map Float Int
findBestFits intensities pixelFreqs = Map.foldrWithKey foldFn (Map.fromList []) pixelFreqs
where foldFn key value acc = Map.insert (bestFitIntensity key intensities) value acc
bestFitIntensity :: PixelRGBA8 -> [PixelRGBA8] -> Float
bestFitIntensity _ [] = 0
bestFitIntensity pixel intensities = asProportion
. snd
. minimum
$ zip (map (takeDelta pixel) intensities) [1..]
where asProportion index = 1 - (fromIntegral index / fromIntegral (length intensities))
takeDelta (PixelRGBA8 r1 g1 b1 _) (PixelRGBA8 r2 g2 b2 _) =
abs ( fromIntegral r1 - fromIntegral r2 ) +
abs ( fromIntegral g1 - fromIntegral g2 ) +
abs ( fromIntegral b1 - fromIntegral b2 )
getIntensities :: Image PixelRGBA8 -> [PixelRGBA8]
getIntensities = nub . flip selectRegion intensityPalette
where intensityPalette = Rectangle (1340, 143) (1340, 935)
countFrequencies :: [PixelRGBA8] -> Map.Map PixelRGBA8 Int
countFrequencies pixels = Map.fromListWith (+) (map (\p -> (p, 1)) pixels)
removeBlackPixels :: [PixelRGBA8] -> [PixelRGBA8]
removeBlackPixels = filter notBlack
where notBlack (PixelRGBA8 r g b _) = not (r == 0 && g == 0 && b == 0)
selectRegion :: (Pixel a)
=> Image a
-> RegionShape
-> [a]
selectRegion image shape = map (pixelAt' image) (coordsForRegion shape)
where pixelAt' image' (x, y) = pixelAt image' x y
determineRegionalIntensity :: Image PixelRGBA8 -> RegionShape -> Int
determineRegionalIntensity image shape = toPercent
. takeWeightedAverage
. Map.toList
. findBestFits (getIntensities image)
. countFrequencies
. removeBlackPixels
$ selectRegion image shape
|
cmwilhelm/dusky
|
src/Dusky/IntensityRater.hs
|
mit
| 2,602
| 0
| 13
| 818
| 764
| 397
| 367
| 50
| 1
|
module Graphics.Urho3D.Scene(
module X
) where
import Graphics.Urho3D.Scene.Component as X
import Graphics.Urho3D.Scene.CustomLogicComponent as X
import Graphics.Urho3D.Scene.Events as X
import Graphics.Urho3D.Scene.LogicComponent as X
import Graphics.Urho3D.Scene.Node as X
import Graphics.Urho3D.Scene.Scene as X
|
Teaspot-Studio/Urho3D-Haskell
|
src/Graphics/Urho3D/Scene.hs
|
mit
| 321
| 0
| 4
| 36
| 67
| 51
| 16
| 8
| 0
|
{-# LANGUAGE CPP #-}
module GHCJS.DOM.SVGFECompositeElement (
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
module GHCJS.DOM.JSFFI.Generated.SVGFECompositeElement
#else
#endif
) where
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
import GHCJS.DOM.JSFFI.Generated.SVGFECompositeElement
#else
#endif
|
plow-technologies/ghcjs-dom
|
src/GHCJS/DOM/SVGFECompositeElement.hs
|
mit
| 376
| 0
| 5
| 33
| 33
| 26
| 7
| 4
| 0
|
module ByteString.TreeBuilder.Poker where
import ByteString.TreeBuilder.Prelude
import Foreign hiding (void)
import qualified Data.ByteString as A
import qualified Data.ByteString.Internal as B
import qualified Foreign as D
import qualified ByteString.TreeBuilder.Tree as E
-- |
-- Write the given bytes into the pointer and
-- return a pointer incremented by the amount of written bytes.
pokeBytes :: ByteString -> Ptr Word8 -> IO (Ptr Word8)
pokeBytes (B.PS foreignPointer offset length) pointer =
do
withForeignPtr foreignPointer $ \pointer' ->
B.memcpy pointer (plusPtr pointer' offset) length
pure (plusPtr pointer length)
-- |
-- Write the given bytes into the pointer and
-- return a pointer decremented by the amount of written bytes.
pokeBytesMinus :: ByteString -> Ptr Word8 -> IO (Ptr Word8)
pokeBytesMinus (B.PS foreignPointer offset length) pointer =
do
withForeignPtr foreignPointer $ \pointer' ->
B.memcpy targetPointer (plusPtr pointer' offset) length
pure targetPointer
where
targetPointer =
plusPtr pointer (negate length)
pokeTree :: E.Tree -> D.Ptr Word8 -> IO (D.Ptr Word8)
pokeTree tree ptr =
case tree of
E.Leaf bytes -> pokeBytes bytes ptr
E.Branch tree1 tree2 -> pokeTree tree1 ptr >>= pokeTree tree2
E.Empty -> pure ptr
|
nikita-volkov/bytestring-tree-builder
|
library/ByteString/TreeBuilder/Poker.hs
|
mit
| 1,309
| 0
| 11
| 244
| 353
| 184
| 169
| 27
| 3
|
-- Just some built-in test scenes for debugging purposes
module TestScenes where
import Colour
import Light
import SparseVoxelOctree
import Vector
import BoundingBox
import Primitive
import Matrix
import Material
import Camera
testSvo :: SparseOctree
testSvo = build (sphereOverlapsBox spherePos sphereRadius) (sphereContainsPoint spherePos sphereRadius) (Vector 140 140 190 1, Vector 360 360 410 1) maxRecursion minDimension
where
spherePos = Vector 250 250 300 1
sphereRadius = 100
maxRecursion = 100
minDimension = 5
sphereOverlapsBox pos r box
| overlapsSphere box pos r = 1
| otherwise = 0
sphereContainsPoint pos r p | p `distance` pos <= r = 1
| otherwise = 0
svoTestScene :: [Object]
svoTestScene = [Object (SparseOctreeModel testSvo) defaultMaterial identity]
svoLeafBoxes :: [Object]
svoLeafBoxes = map (\x -> Object (Box x) defaultMaterial identity) (enumerateLeafBoxes testSvo)
boxTestScene :: [Object]
boxTestScene = [Object (Box (Vector (-50) (-50) (-50) 0, Vector 50 50 50 0)) defaultMaterial identity]
testSceneCamera :: Camera
testSceneCamera = withVectors (Vector 0 0 (-400.0) 1.0) xaxis yaxis zaxis 45.0 10000
testSceneLights :: [Light]
testSceneLights = [
QuadLight (CommonLightData (Colour 500 500 500 0) True) (Vector 0.0 200.0 (-300.0) 1.0) 1000 (Vector 1000.0 0.0 0.0 0.0) (Vector 0.0 0.0 1000.0 0.0)
]
|
TomHammersley/HaskellRenderer
|
app/src/TestScenes.hs
|
gpl-2.0
| 1,415
| 0
| 12
| 281
| 465
| 247
| 218
| 32
| 1
|
import Fay.Builder (defaultFayHook)
main = defaultFayHook
|
bneijt/fay-builder-example
|
Setup.hs
|
gpl-3.0
| 58
| 0
| 5
| 6
| 16
| 9
| 7
| 2
| 1
|
-- grid is a game written in Haskell
-- Copyright (C) 2018 karamellpelle@hotmail.com
--
-- This file is part of grid.
--
-- grid is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- grid is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with grid. If not, see <http://www.gnu.org/licenses/>.
--
module Game.Grid.Helpers.Camera
(
cameraEatCameraCommand,
cameraToPath,
cameraToPathTranslate,
cameraToPathTurn,
cameraSetPath,
cameraCurrentView,
cameraViewAlpha,
cameraToView,
cameraToViewTicks,
cameraToView',
cameraToViewTicks',
cameraSetView,
cameraIsAtView,
cameraTurn,
cameraTurnIdeal,
cameraToTurn,
cameraToTurnTicks,
cameraSetTurn,
cameraIsAtTurn,
cameraToTurnView,
cameraSetTurnView,
) where
import MyPrelude
import Game
import Game.Grid.GridWorld
import Game.Grid.Helpers.Path
--------------------------------------------------------------------------------
--
cameraEatCameraCommand :: Camera -> CameraCommand -> Camera
cameraEatCameraCommand cam cmd =
let turn = if cameracommandTurnIsAdd cmd
then cameracommandTurn cmd `mappend` cameraTurnIdeal cam
else cameracommandTurn cmd
view = if cameracommandViewIsAdd cmd
then cameracommandView cmd `mappend` cameraCurrentView cam
else cameracommandView cmd
in let cam' = cameraToTurn cam (cameracommandTurnSpeed cmd) turn
in if cameracommandViewIsAdd cmd
then cameraToView' cam' (cameracommandViewSpeed cmd) view
else cameraToView cam' (cameracommandViewSpeed cmd) view
--------------------------------------------------------------------------------
-- Camera + Path
-- | follow path by translation and turning
-- fixme: see StepDT
cameraToPath :: Camera -> Path -> Camera
cameraToPath camera path =
cameraToPathTurn (cameraToPathTranslate camera path) path
-- | follow path by translation
-- fixme: see StepDT
cameraToPathTranslate :: Camera -> Path -> Camera
cameraToPathTranslate camera path =
let node' = if pathWaiting path
then pathNode path
else pathNodeNext path
in if cameraNodeIdeal camera == node'
then camera
else camera
{
--cameraNode = cameraNodeIdeal camera,
cameraNodeIdeal = node',
cameraNodeAlpha = pathAlpha path,
cameraNodeSpeed = pathSpeed path
}
-- | follow path by turning
-- fixme: see StepDT
cameraToPathTurn :: Camera -> Path -> Camera
cameraToPathTurn camera path =
let turn = cameraTurnIdeal camera
turn' = pathTurn path
in if turn == turn'
then camera
else let b = cameraTurnB camera
b' = cameraTurnBIdeal camera
balpha = cameraTurnBAlpha camera
a = cameraTurnA camera
a' = cameraTurnAIdeal camera
aalpha = cameraTurnAAlpha camera
in camera
{
cameraTurnBIdeal = turn',
cameraTurnB = b',
cameraTurnBAlpha = 0.0, -- if pathAlpha path, then discontiuos roll!
cameraTurnASpeed = pathSpeed path * valueGridPathTurnSpeed,
cameraTurnBSpeed = pathSpeed path * valueGridPathTurnSpeed,
cameraTurnAIdeal = mempty,
cameraTurnA = turnInverse b' `mappend` b,
cameraTurnAAlpha = balpha
}
-- | set camera to path position and orientation
cameraSetPath :: Camera -> Path -> Camera
cameraSetPath camera path =
camera
{
cameraNode = pathNode path,
cameraNodeIdeal = pathNodeNext path,
cameraNodeAlpha = pathAlpha path,
cameraNodeSpeed = if pathWaiting path then 0.0 else pathSpeed path,
cameraTurnB = pathTurn path,
cameraTurnBIdeal = pathTurn path,
cameraTurnBAlpha = 1.0,
cameraTurnBSpeed = valueGridPathTurnSpeed * pathSpeed path, -- ??
cameraTurnA = mempty,
cameraTurnAIdeal = mempty,
cameraTurnAAlpha = 1.0,
cameraTurnASpeed = valueGridPathTurnSpeed * pathSpeed path -- ??
}
--------------------------------------------------------------------------------
-- Camera + Turn
cameraTurn :: Camera -> Turn
cameraTurn cam =
cameraTurnB cam `mappend` cameraTurnA cam
cameraTurnIdeal :: Camera -> Turn
cameraTurnIdeal cam =
cameraTurnBIdeal cam `mappend` cameraTurnAIdeal cam
cameraSetTurn :: Camera -> Turn -> Camera
cameraSetTurn camera turn =
camera
{
cameraTurnBIdeal = turn,
cameraTurnB = turn,
cameraTurnAIdeal = mempty,
cameraTurnA = mempty
}
cameraIsAtTurn :: Camera -> Bool
cameraIsAtTurn camera =
1.0 <= (cameraTurnAAlpha camera) &&
1.0 <= (cameraTurnBAlpha camera)
cameraToTurnTicks :: Camera -> Float -> Turn -> Camera
cameraToTurnTicks camera ticks turn =
cameraToTurn camera (1.0 / ticks) turn
cameraToTurn :: Camera -> Float -> Turn -> Camera
cameraToTurn camera speed turn =
let b = cameraTurnB camera
b' = cameraTurnBIdeal camera
balpha = cameraTurnBAlpha camera
a = cameraTurnA camera
a' = cameraTurnAIdeal camera
aalpha = cameraTurnAAlpha camera
in camera
{
cameraTurnBIdeal = turn,
cameraTurnB = b',
cameraTurnBAlpha = 0.0,
cameraTurnBSpeed = speed,
cameraTurnAIdeal = mempty,
cameraTurnA = turnInverse b' `mappend` b,
cameraTurnAAlpha = balpha,
cameraTurnASpeed = speed
}
--------------------------------------------------------------------------------
-- Camera + View
cameraViewAlpha :: Camera -> Float
cameraViewAlpha camera =
0.33333333 * (cameraViewAAlpha camera +
cameraViewBAlpha camera +
cameraViewCAlpha camera)
cameraCurrentView :: Camera -> View
cameraCurrentView camera =
let View a b c = cameraView camera
View a' b' c' = cameraViewIdeal camera
a0 = smooth a a' $ cameraViewAAlpha camera
b0 = smooth b b' $ cameraViewBAlpha camera
c0 = smooth c c' $ cameraViewCAlpha camera
in View a0 b0 c0
cameraToView :: Camera -> Float -> View -> Camera
cameraToView camera speed (View a1 b1 c1) =
case cameraCurrentView camera of
View a0 b0 c0 ->
cameraToView' camera speed $ View (shortest a0 a1)
(shortest b0 b1)
c1
where
shortest x x' =
let pos = modulo x (x + tau) x'
neg = modulo x' (x' + tau) x
in if pos <= neg
then x + pos
else x - neg
cameraToViewTicks :: Camera -> Float -> View -> Camera
cameraToViewTicks camera ticks view =
cameraToView camera (1.0 / ticks) view
-- | to view strictly
cameraToView' :: Camera -> Float -> View -> Camera
cameraToView' camera speed view =
camera
{
cameraView = cameraCurrentView camera,
cameraViewIdeal = view,
cameraViewAAlpha = 0.0,
cameraViewAAlphaIdeal = 1.0,
cameraViewASpeed = speed,
cameraViewBAlpha = 0.0,
cameraViewBAlphaIdeal = 1.0,
cameraViewBSpeed = speed,
cameraViewCAlpha = 0.0,
cameraViewCAlphaIdeal = 1.0,
cameraViewCSpeed = speed
}
cameraSetView :: Camera -> View -> Camera
cameraSetView camera view =
camera
{
cameraView = view,
cameraViewIdeal = view
}
cameraToViewTicks' :: Camera -> Tick -> View -> Camera
cameraToViewTicks' camera ticks view =
cameraToView' camera (1.0 / rTF ticks) view
cameraIsAtView :: Camera -> Bool
cameraIsAtView camera =
cameraViewAAlpha camera == cameraViewAAlphaIdeal camera &&
cameraViewBAlpha camera == cameraViewBAlphaIdeal camera &&
cameraViewCAlpha camera == cameraViewCAlphaIdeal camera
--------------------------------------------------------------------------------
--
cameraToTurnView :: Camera -> Float -> Turn -> View -> Camera
cameraToTurnView cam speed turn view =
cameraToView (cameraToTurn cam speed turn) speed view
cameraSetTurnView :: Camera -> Turn -> View -> Camera
cameraSetTurnView camera turn view =
cameraSetView (cameraSetTurn camera turn) view
--------------------------------------------------------------------------------
--
cameraToNode :: Camera -> Float -> Node -> Camera
cameraToNode camera speed node =
camera
{
cameraNode = cameraNodeIdeal camera,
cameraNodeIdeal = node,
cameraNodeAlpha = 0.0,
cameraNodeSpeed = speed
}
cameraSetNode :: Camera -> Node -> Camera
cameraSetNode camera node =
camera
{
cameraNode = node,
cameraNodeIdeal = node,
cameraNodeAlpha = 0.0
}
cameraToNodeTicks :: Camera -> Float -> Node -> Camera
cameraToNodeTicks camera ticks node =
cameraToNode camera (1.0 / ticks) node
cameraIsAtNode :: Camera -> Bool
cameraIsAtNode camera =
1.0 <= cameraNodeAlpha camera
|
karamellpelle/grid
|
source/Game/Grid/Helpers/Camera.hs
|
gpl-3.0
| 9,677
| 0
| 13
| 2,733
| 1,936
| 1,051
| 885
| 207
| 4
|
module Portage.Host
( getInfo -- :: IO [(String, String)]
, LocalInfo(..)
) where
import Util (run_cmd)
import Data.Maybe (fromJust, isJust, catMaybes)
import Control.Applicative ( (<$>) )
import qualified System.Directory as D
import System.FilePath ((</>))
import System.IO
data LocalInfo =
LocalInfo { distfiles_dir :: String
, overlay_list :: [FilePath]
, portage_dir :: FilePath
} deriving (Read, Show)
defaultInfo :: LocalInfo
defaultInfo = LocalInfo { distfiles_dir = "/usr/portage/distfiles"
, overlay_list = []
, portage_dir = "/usr/portage"
}
-- query paludis and then emerge
getInfo :: IO LocalInfo
getInfo = fromJust `fmap`
performMaybes [ readConfig
, performMaybes [ getPaludisInfo
, fmap parse_emerge_output <$> (run_cmd "emerge --info")
, return (Just defaultInfo)
] >>= showAnnoyingWarning
]
where performMaybes [] = return Nothing
performMaybes (act:acts) =
do r <- act
if isJust r
then return r
else performMaybes acts
showAnnoyingWarning :: Maybe LocalInfo -> IO (Maybe LocalInfo)
showAnnoyingWarning info = do
hPutStr stderr $ unlines [ "-- Consider creating ~/" ++ hackport_config ++ " file with contents:"
, show info
, "-- It will speed hackport startup time a bit."
]
return info
-- relative to home dir
hackport_config :: FilePath
hackport_config = ".hackport" </> "repositories"
--------------------------
-- fastest: config reading
--------------------------
readConfig :: IO (Maybe LocalInfo)
readConfig =
do home_dir <- D.getHomeDirectory
let config_path = home_dir </> hackport_config
exists <- D.doesFileExist config_path
case exists of
True -> read <$> readFile config_path
False -> return Nothing
----------
-- Paludis
----------
getPaludisInfo :: IO (Maybe LocalInfo)
getPaludisInfo = fmap parsePaludisInfo <$> run_cmd "cave info"
parsePaludisInfo :: String -> LocalInfo
parsePaludisInfo text =
let chunks = splitBy (=="") . lines $ text
repositories = catMaybes (map parseRepository chunks)
in fromJust (mkLocalInfo repositories)
where
parseRepository :: [String] -> Maybe (String, (String, String))
parseRepository [] = Nothing
parseRepository (firstLine:lns) = do
name <- case words firstLine of
["Repository", nm] -> return (init nm)
_ -> fail "not a repository chunk"
let dict = [ (head ln, unwords (tail ln)) | ln <- map words lns ]
location <- lookup "location" dict
distfiles <- lookup "distdir" dict
return (name, (location, distfiles))
mkLocalInfo :: [(String, (String, String))] -> Maybe LocalInfo
mkLocalInfo repos = do
(gentooLocation, gentooDistfiles) <- lookup "gentoo" repos
let overlays = [ loc | (_, (loc, _dist)) <- repos ]
return (LocalInfo
{ distfiles_dir = gentooDistfiles
, portage_dir = gentooLocation
, overlay_list = overlays
})
splitBy :: (a -> Bool) -> [a] -> [[a]]
splitBy _ [] = []
splitBy c lst =
let (x,xs) = break c lst
(_,xs') = span c xs
in x : splitBy c xs'
---------
-- Emerge
---------
parse_emerge_output :: String -> LocalInfo
parse_emerge_output raw_data =
foldl updateInfo defaultInfo $ lines raw_data
where updateInfo info str =
case (break (== '=') str) of
("DISTDIR", '=':value)
-> info{distfiles_dir = unquote value}
("PORTDIR", '=':value)
-> info{portage_dir = unquote value}
("PORTDIR_OVERLAY", '=':value)
-> info{overlay_list = words $ unquote value}
_ -> info
unquote = init . tail
|
Heather/hackport
|
Portage/Host.hs
|
gpl-3.0
| 4,121
| 0
| 16
| 1,334
| 1,104
| 590
| 514
| 91
| 4
|
module GameTypes
( Common (..),
Game (..),
State (..),
Status (..)
) where
import UI.NCurses
import Data.ConfigFile
import Space
import Keyboard
import LevelMap
import Beast
import Dialogue
data Common = Common {
stdscr :: Window,
mainWin :: Window,
msgWin :: Window,
mapPath :: FilePath,
rulesPath :: FilePath,
confPath :: Maybe FilePath,
keyboard :: Keyboard
}
data Game = Game {
m :: LevelMap,
player :: Beast,
monsters :: Monsters,
rules :: ConfigParser,
dialogue :: Dialogue
}
data State = State {
common :: Common,
game :: Game,
status :: Status,
todo :: Curses ()
}
data Status = MainGame | InDialogue | Dead | Quit | Load | Starting | Action deriving (Show, Eq) -- Action is used when we have to determine the status
|
nobrakal/TheBlackCurse
|
src/GameTypes.hs
|
gpl-3.0
| 783
| 0
| 10
| 183
| 227
| 145
| 82
| 32
| 0
|
{-# LANGUAGE NamedFieldPuns #-}
module Language.Slicer.Monad.Repl
( ReplM, runRepl, getTyCtx, getGamma, getEvalState, setEvalState
, addDataDefn, addBinding
) where
import Language.Slicer.Absyn
import qualified Language.Slicer.Core as C ( Value, Type )
import Language.Slicer.Env
import Language.Slicer.Monad.Eval hiding ( addBinding, getEvalState
, setEvalState )
import qualified Language.Slicer.Monad.Eval as E ( addBinding )
import Control.Monad.State.Strict
-- | REPL monad contains a state on top of IO
type ReplM = StateT ReplState IO
-- | REPL state
data ReplState = ReplState
{ tyCtxS :: TyCtx -- ^ Data type declarations
, gammaS :: Env C.Type -- ^ Context Γ, stores variable types
, evalS :: EvalState -- ^ Evaluation monad state. Contains
-- environment ρ (variable values) and
-- reference store
}
-- | Empty REPL state. Used when starting the REPL
emptyState :: ReplState
emptyState = ReplState { tyCtxS = emptyTyCtx
, gammaS = emptyEnv
, evalS = emptyEvalState }
-- | Get data type declarations
getTyCtx :: ReplM TyCtx
getTyCtx = do
ReplState { tyCtxS } <- get
return tyCtxS
-- | Get context
getGamma :: ReplM (Env C.Type)
getGamma = do
ReplState { gammaS } <- get
return gammaS
-- | Get environment
getEvalState :: ReplM EvalState
getEvalState = do
ReplState { evalS } <- get
return evalS
setEvalState :: EvalState -> ReplM ()
setEvalState newEvalSt = do
replState <- get
put $ replState { evalS = newEvalSt }
-- | Add new data definition
addDataDefn :: TyCtx -> ReplM ()
addDataDefn newCtx = do
st@(ReplState { tyCtxS }) <- get
put $ st { tyCtxS = unionTyCtx tyCtxS newCtx }
-- | Add new binding (name + value + type)
addBinding :: Var -> C.Value -> C.Type -> ReplM ()
addBinding var val ty = do
replState@(ReplState { evalS, gammaS }) <- get
let evalS' = E.addBinding evalS var val
newGamma = updateEnv gammaS var ty
put $ replState { evalS = evalS', gammaS = newGamma }
-- | Run REPL monad
runRepl :: ReplM () -> IO ()
runRepl repl = evalStateT repl emptyState
|
jstolarek/slicer
|
src/Language/Slicer/Monad/Repl.hs
|
gpl-3.0
| 2,310
| 0
| 11
| 661
| 544
| 305
| 239
| 48
| 1
|
-- This module is loaded as part of the Prelude
module Pic(
Pic(NoPic, Line, Rect, Poly, Ellipse, PicText, PicImage, SelRect, PicAction,
Trans, Super, Animation, Interaction),
Font(Serif, SansSerif, Monospaced, Dialog, DialogInput),
Format(NoFormat, Format),
Color(RGB, Transparent),
black, blue, green, cyan, red, magenta, yellow, white,
lightGray, gray, darkGray,
trans,
invColor, lighten, darken,
imageFile, scaleImage, imageSize, picFile,
fontSize,
defaultFmt
) where {
import Midi; -- Note that this is _not_ reexported
-- Primitives
primitive primImageFile :: String -> Image;
primitive primScaleImage :: Int -> Int -> Image -> Image;
primitive primImageSize :: Image -> (Int, Int);
primitive primFontSize :: Format -> (Int, Int);
data Pic
= NoPic
| Line {x :: Int, y :: Int, color :: Color}
| Rect {width :: Int, height :: Int, bgColor :: Color, edgeColor :: Color}
| Poly {vertices :: [(Int, Int)], bgColor :: Color, edgeColor :: Color}
| Ellipse {width :: Int, height :: Int, bgColor :: Color, edgeColor :: Color}
| PicText {format :: Format, text :: String}
| PicImage {img :: Image}
| SelRect {width :: Int, height :: Int, bgColor :: Color, edgeColor :: Color}
| PicAction {width :: Int, height :: Int, bgColor :: Color, edgeColor :: Color, action :: Action}
| Trans {x :: Int, y :: Int, pic :: Pic}
| Super {lower :: Pic, upper :: Pic} -- The second is superimposed on the first
| Animation {fn :: Int -> Pic}
| Interaction {s0 :: state, fn :: Time -> Int -> Int -> Bool -> state -> (state, Pic)};
data Font
= Serif | SansSerif | Monospaced | Dialog | DialogInput;
data Format
= NoFormat
| Format {font :: Font, ptSize :: Int, fgColor :: Color, isBold :: Bool, isItalic :: Bool};
data Color
= RGB Int Int Int -- The Red, Green and Blue components, each in the range (0 .. 255)
| Transparent;
-- Bindings for primitive values
-- for Image
imageFile :: String -> Image;
imageFile = primImageFile;
-- The expression
-- scaleImage width height image
-- yields a new image scaled to the given size. If either dimension is negative, then the
-- image aspect ratio is maintained.
scaleImage :: Int -> Int -> Image -> Image;
scaleImage = primScaleImage;
imageSize :: Image -> (Int, Int);
imageSize = primImageSize;
-- Note that this function reflects the behaviour of the particular physical device (screen, printer, ...)
-- on which rendering takes place.
fontSize :: Format -> (Int, Int);
fontSize = primFontSize;
-- Bindings for derived values
off = 0;
on = 255;
black = RGB off off off;
blue = RGB off off on ;
green = RGB off on off;
cyan = RGB off on on ;
red = RGB on off off;
magenta = RGB on off on ;
yellow = RGB on on off;
white = RGB on on on ;
lightGray = RGB 192 192 192;
gray = RGB 128 128 128;
darkGray = RGB 64 64 64;
trans = Transparent;
lighten, darken :: Color -> Color;
lighten c = case c of {
Transparent -> Transparent;
RGB r g b -> RGB (more r) (more g) (more b)
};
darken c = case c of {
Transparent -> Transparent;
RGB r g b -> RGB (less r) (less g) (less b)
};
picFile :: String -> Pic;
picFile = PicImage . imageFile;
defaultFmt :: Format;
defaultFmt = Format SansSerif 16 darkGray False False;
-- This internal constant determines the amount by which colours are lightened or darkened.
delta = 50;
less, more :: Int -> Int;
less n = max off (n - delta);
more n = min on (n + delta);
invColor :: Color -> Color;
invColor c = case c of {
Transparent -> Transparent;
RGB r g b -> RGB (on - r) (on - g) (on - b)
}
}
|
ckaestne/CIDE
|
CIDE_Language_Haskell/test/fromviral/Pic.hs
|
gpl-3.0
| 4,707
| 43
| 10
| 1,896
| 992
| 638
| 354
| -1
| -1
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.CloudResourceManager.TagValues.List
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Lists all TagValues for a specific TagKey.
--
-- /See:/ <https://cloud.google.com/resource-manager Cloud Resource Manager API Reference> for @cloudresourcemanager.tagValues.list@.
module Network.Google.Resource.CloudResourceManager.TagValues.List
(
-- * REST Resource
TagValuesListResource
-- * Creating a Request
, tagValuesList
, TagValuesList
-- * Request Lenses
, tvlParent
, tvlXgafv
, tvlUploadProtocol
, tvlAccessToken
, tvlUploadType
, tvlPageToken
, tvlPageSize
, tvlCallback
) where
import Network.Google.Prelude
import Network.Google.ResourceManager.Types
-- | A resource alias for @cloudresourcemanager.tagValues.list@ method which the
-- 'TagValuesList' request conforms to.
type TagValuesListResource =
"v3" :>
"tagValues" :>
QueryParam "parent" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "pageToken" Text :>
QueryParam "pageSize" (Textual Int32) :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] ListTagValuesResponse
-- | Lists all TagValues for a specific TagKey.
--
-- /See:/ 'tagValuesList' smart constructor.
data TagValuesList =
TagValuesList'
{ _tvlParent :: !(Maybe Text)
, _tvlXgafv :: !(Maybe Xgafv)
, _tvlUploadProtocol :: !(Maybe Text)
, _tvlAccessToken :: !(Maybe Text)
, _tvlUploadType :: !(Maybe Text)
, _tvlPageToken :: !(Maybe Text)
, _tvlPageSize :: !(Maybe (Textual Int32))
, _tvlCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'TagValuesList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'tvlParent'
--
-- * 'tvlXgafv'
--
-- * 'tvlUploadProtocol'
--
-- * 'tvlAccessToken'
--
-- * 'tvlUploadType'
--
-- * 'tvlPageToken'
--
-- * 'tvlPageSize'
--
-- * 'tvlCallback'
tagValuesList
:: TagValuesList
tagValuesList =
TagValuesList'
{ _tvlParent = Nothing
, _tvlXgafv = Nothing
, _tvlUploadProtocol = Nothing
, _tvlAccessToken = Nothing
, _tvlUploadType = Nothing
, _tvlPageToken = Nothing
, _tvlPageSize = Nothing
, _tvlCallback = Nothing
}
-- | Required. Resource name for TagKey, parent of the TagValues to be
-- listed, in the format \`tagKeys\/123\`.
tvlParent :: Lens' TagValuesList (Maybe Text)
tvlParent
= lens _tvlParent (\ s a -> s{_tvlParent = a})
-- | V1 error format.
tvlXgafv :: Lens' TagValuesList (Maybe Xgafv)
tvlXgafv = lens _tvlXgafv (\ s a -> s{_tvlXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
tvlUploadProtocol :: Lens' TagValuesList (Maybe Text)
tvlUploadProtocol
= lens _tvlUploadProtocol
(\ s a -> s{_tvlUploadProtocol = a})
-- | OAuth access token.
tvlAccessToken :: Lens' TagValuesList (Maybe Text)
tvlAccessToken
= lens _tvlAccessToken
(\ s a -> s{_tvlAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
tvlUploadType :: Lens' TagValuesList (Maybe Text)
tvlUploadType
= lens _tvlUploadType
(\ s a -> s{_tvlUploadType = a})
-- | Optional. A pagination token returned from a previous call to
-- \`ListTagValues\` that indicates where this listing should continue
-- from.
tvlPageToken :: Lens' TagValuesList (Maybe Text)
tvlPageToken
= lens _tvlPageToken (\ s a -> s{_tvlPageToken = a})
-- | Optional. The maximum number of TagValues to return in the response. The
-- server allows a maximum of 300 TagValues to return. If unspecified, the
-- server will use 100 as the default.
tvlPageSize :: Lens' TagValuesList (Maybe Int32)
tvlPageSize
= lens _tvlPageSize (\ s a -> s{_tvlPageSize = a}) .
mapping _Coerce
-- | JSONP
tvlCallback :: Lens' TagValuesList (Maybe Text)
tvlCallback
= lens _tvlCallback (\ s a -> s{_tvlCallback = a})
instance GoogleRequest TagValuesList where
type Rs TagValuesList = ListTagValuesResponse
type Scopes TagValuesList =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/cloud-platform.read-only"]
requestClient TagValuesList'{..}
= go _tvlParent _tvlXgafv _tvlUploadProtocol
_tvlAccessToken
_tvlUploadType
_tvlPageToken
_tvlPageSize
_tvlCallback
(Just AltJSON)
resourceManagerService
where go
= buildClient (Proxy :: Proxy TagValuesListResource)
mempty
|
brendanhay/gogol
|
gogol-resourcemanager/gen/Network/Google/Resource/CloudResourceManager/TagValues/List.hs
|
mpl-2.0
| 5,592
| 0
| 18
| 1,325
| 889
| 515
| 374
| 123
| 1
|
module RunnerX where
import TrmX
import qualified Data.List as L
import qualified Data.Set as S
import RewritingX
import AlphaX (solveAlpha)
import ConstraintsX
import SetofSets
import AuxFnRwX
runAlpha:: ProbCtx -> String
runAlpha (ctx, prob) = case solveAlpha prob of
S.Set Nothing -> "False"
fc -> if derives ctx fc
then "True"
else "True, when adding " ++ showCtx (S.difference fc ctx) ++ "\n"
runRw:: Rw -> TrmCtx -> [Rule] -> Either String (Ctx, [Trm])
runRw rw trm@(fc,t) rls
| L.null msg = Right steps
| otherwise = Left msg
where msg=test t rls
steps= rewrites rw trm rls
test :: Trm -> [Rule] -> String
test t rls =foldr ((++) . validity) rls ++ ground t
|
susoDominguez/eNominalTerms-Alpha
|
RunnerX.hs
|
unlicense
| 863
| 0
| 14
| 313
| 276
| 149
| 127
| 23
| 3
|
foldl' :: (a -> b -> a) -> a -> [b] -> a
foldl' _ zero [] = zero
foldl' step zero (x:xs) =
let new = step zero x
in new `seq` foldl' step new xs
|
EricYT/Haskell
|
src/strictFoldl.hs
|
apache-2.0
| 154
| 0
| 9
| 46
| 94
| 48
| 46
| 5
| 1
|
import Sandbox.Partitions (Partition, partitionsWithMaxPart)
import Helpers.Subsets (eachPair)
data HeightSequence = EdgeRooted (Partition, Partition) | VertexRooted Partition deriving (Show)
-- A000677
-- heightSequenceOfEdgeRootedTree :: Int -> Int -> [(Partition, Partition)]
heightSequenceOfEdgeRootedTree n k = map EdgeRooted $ equal ++ unequal where
equal = equalHeightEdgeRootedPartions n k
unequal = concatMap f (unequalParititonPairSizes (n - 2*k)) where
f (a,b) = [(k:p1, k:p2) | p1 <- partitionsWithMaxPart a k, p2 <- partitionsWithMaxPart b k]
unequalParititonPairSizes n = map (\i -> (n-i, i)) [0..(n-1)`div` 2]
equalHeightEdgeRootedPartions n k
| odd n = []
| otherwise = map (\p -> (p, p)) ps ++ eachPair ps where
ps = map (k:) $ partitionsWithMaxPart ((n - 2*k) `div` 2) k
heightSequenceOfVertexRootedTree n k = map VertexRooted $ map ([k,k]++) $ partitionsWithMaxPart (n-2*k) k
trees 1 = [VertexRooted []]
trees 2 = [EdgeRooted ([], [])]
trees n = vRooted ++ eRooted ++ concatMap (trees') [1..n-1] where
vRooted = concatMap (heightSequenceOfVertexRootedTree (n-1)) [1..(n-1) `div` 2]
eRooted = concatMap (heightSequenceOfEdgeRootedTree (n-2)) [1..(n-2) `div` 2]
trees' n = vRooted ++ eRooted where
vRooted = concatMap (heightSequenceOfVertexRootedTree (n-1)) [2..(n-1) `div` 2]
eRooted = concatMap (heightSequenceOfEdgeRootedTree (n-2)) [2..(n-2) `div` 2]
|
peterokagey/haskellOEIS
|
src/Sandbox/Greta/DegreeSequence.hs
|
apache-2.0
| 1,407
| 0
| 13
| 221
| 623
| 336
| 287
| 21
| 1
|
{- Math.hs
- Direct implementation of Linear algebra routines.
- Specific sizes (3x1,4x1,3x3,4x4) allow us to do fast analytical implementations.
-
- Timothy A. Chagnon
- CS 636 - Spring 2009
-}
module Math where
import Control.Parallel.Strategies hiding (dot)
import Control.DeepSeq
import Debug.Trace
tshow :: Show a => String -> a -> a
tshow x y = trace (x ++ " " ++ (show y)) y
-- Synonym for Real number type
type RealT = Double
-- Degrees to Radians
deg2rad :: RealT -> RealT
deg2rad d = d * pi / 180
--------------------------------------------------------------------------------
-- 3x1 Vector
--------------------------------------------------------------------------------
data Vec3f = Vec3f !RealT !RealT !RealT
deriving (Show, Eq)
-- Required for parListChunk
instance NFData Vec3f where
rnf (Vec3f x y z) = rnf x `seq` rnf y `seq` rnf z
instance Num Vec3f where
Vec3f a b c + Vec3f d e f = Vec3f (a+d) (b+e) (c+f)
Vec3f a b c - Vec3f d e f = Vec3f (a-d) (b-e) (c-f)
(*) = cross
abs = norm
signum (Vec3f 0 0 0) = zeroVec3f
signum v = norm v
fromInteger i = Vec3f (fromInteger i) (fromInteger i) (fromInteger i)
vec3f = Vec3f
zeroVec3f :: Vec3f
zeroVec3f = Vec3f 0 0 0
svMul :: RealT -> Vec3f -> Vec3f
svMul s (Vec3f a b c) = Vec3f (s*a) (s*b) (s*c)
dot :: Vec3f -> Vec3f -> RealT
dot (Vec3f a b c) (Vec3f d e f) = a*d + b*e + c*f
cross :: Vec3f -> Vec3f -> Vec3f
cross (Vec3f a b c) (Vec3f d e f) = Vec3f (b*f-c*e) (c*d-a*f) (a*e-b*d)
mag :: Vec3f -> RealT
mag v = sqrt (magSq v)
magSq :: Vec3f -> RealT
magSq (Vec3f a b c) = (a*a + b*b + c*c)
norm :: Vec3f -> Vec3f
norm v = (1/(mag v)) `svMul` v
(.*) :: Vec3f -> Vec3f -> Vec3f
Vec3f a b c .* Vec3f d e f = Vec3f (a*d) (b*e) (c*f)
-- Reduce Vec4f to Vec3f, divide by w
point3f :: Vec4f -> Vec3f
point3f (Vec4f _ _ _ 0) = error "point3f divide by zero"
point3f (Vec4f x y z w) = Vec3f (x/w) (y/w) (z/w)
-- Reduce Vec4f to Vec3f, ignore w
direction3f :: Vec4f -> Vec3f
direction3f (Vec4f x y z _) = Vec3f x y z
-- Return elements as a 3-tuple
vec3fElts :: Vec3f -> (RealT, RealT, RealT)
vec3fElts (Vec3f x y z) = (x,y,z)
-- Dot product clamped to 0
dot0 :: Vec3f -> Vec3f -> RealT
dot0 v1 v2 = max 0 (dot v1 v2)
-- zipWith for Vec3f
zipWith3f :: (RealT -> RealT -> RealT) -> Vec3f -> Vec3f -> Vec3f
zipWith3f g (Vec3f a b c) (Vec3f d e f) = Vec3f (g a d) (g b e) (g c f)
-- Element extraction
v3x, v3y, v3z :: Vec3f -> RealT
v3x (Vec3f x _ _) = x
v3y (Vec3f _ y _) = y
v3z (Vec3f _ _ z) = z
--------------------------------------------------------------------------------
-- 4x1 Vector
--------------------------------------------------------------------------------
data Vec4f = Vec4f !RealT !RealT !RealT !RealT
deriving (Show, Eq)
instance Num Vec4f where
Vec4f a b c d + Vec4f e f g h = Vec4f (a+e) (b+f) (c+g) (d+h)
Vec4f a b c d - Vec4f e f g h = Vec4f (a-e) (b-f) (c-g) (d-h)
(*) = error "Vec4f multiplication not implemented"
abs = norm4f
signum (Vec4f 0 0 0 0) = zeroVec4f
signum v = norm4f v
fromInteger i = Vec4f (fromInteger i) (fromInteger i) (fromInteger i) (fromInteger i)
vec4f = Vec4f
zeroVec4f :: Vec4f
zeroVec4f = Vec4f 0 0 0 0
svMul4f :: RealT -> Vec4f -> Vec4f
svMul4f s (Vec4f a b c d) = Vec4f (s*a) (s*b) (s*c) (s*d)
dot4f :: Vec4f -> Vec4f -> RealT
dot4f (Vec4f a b c d) (Vec4f e f g h) = a*e + b*f + c*g + d*h
mag4f :: Vec4f -> RealT
mag4f v = sqrt (magSq4f v)
magSq4f :: Vec4f -> RealT
magSq4f (Vec4f a b c d) = (a*a + b*b + c*c + d*d)
norm4f :: Vec4f -> Vec4f
norm4f v = (1/(mag4f v)) `svMul4f` v
-- Raise Vec3f to Vec4f with w=1
point4f :: Vec3f -> Vec4f
point4f (Vec3f x y z) = Vec4f x y z 1
-- Raise Vec3f to Vec4f with w=0
direction4f :: Vec3f -> Vec4f
direction4f (Vec3f x y z) = Vec4f x y z 0
-- Indexing
(!.) :: Vec4f -> Int -> RealT
(Vec4f e0 e1 e2 e3) !. 0 = e0
(Vec4f e0 e1 e2 e3) !. 1 = e1
(Vec4f e0 e1 e2 e3) !. 2 = e2
(Vec4f e0 e1 e2 e3) !. 3 = e3
(Vec4f e0 e1 e2 e3) !. _ = error "Invalid index to (!) Mat4f"
-- Transform a Vec3f point using a Mat4f tranformation matrix
transformPt :: Mat4f -> Vec3f -> Vec3f
transformPt t v = point3f (t `mvMul` (point4f v))
-- Transform a Vec3f direction using a Mat4f tranformation matrix
transformDir :: Mat4f -> Vec3f -> Vec3f
transformDir t v = direction3f (t `mvMul` (direction4f v))
--------------------------------------------------------------------------------
-- 4x4 Matrix
--------------------------------------------------------------------------------
data Mat4f = Mat4f !Vec4f !Vec4f !Vec4f !Vec4f
deriving (Show, Eq)
mat4f = Mat4f
-- Matrix-Vector Multiplication
mvMul :: Mat4f -> Vec4f -> Vec4f
mvMul (Mat4f r1 r2 r3 r4) v = Vec4f (r1 `dot4f` v) (r2 `dot4f` v) (r3 `dot4f` v) (r4 `dot4f` v)
-- Matrix-Matrix Multiplication
mmMul :: Mat4f -> Mat4f -> Mat4f
mmMul (Mat4f r1 r2 r3 r4) m2 =
let (Mat4f t1 t2 t3 t4) = transpose4f m2 in
Mat4f (Vec4f (r1 `dot4f` t1) (r1 `dot4f` t2) (r1 `dot4f` t3) (r1 `dot4f` t4))
(Vec4f (r2 `dot4f` t1) (r2 `dot4f` t2) (r2 `dot4f` t3) (r2 `dot4f` t4))
(Vec4f (r3 `dot4f` t1) (r3 `dot4f` t2) (r3 `dot4f` t3) (r3 `dot4f` t4))
(Vec4f (r4 `dot4f` t1) (r4 `dot4f` t2) (r4 `dot4f` t3) (r4 `dot4f` t4))
-- Matrix Transpose
transpose4f :: Mat4f -> Mat4f
transpose4f (Mat4f (Vec4f r11 r12 r13 r14)
(Vec4f r21 r22 r23 r24)
(Vec4f r31 r32 r33 r34)
(Vec4f r41 r42 r43 r44)) =
Mat4f (Vec4f r11 r21 r31 r41)
(Vec4f r12 r22 r32 r42)
(Vec4f r13 r23 r33 r43)
(Vec4f r14 r24 r34 r44)
-- Identity Matrix
id4f :: Mat4f
id4f = Mat4f (Vec4f 1 0 0 0)
(Vec4f 0 1 0 0)
(Vec4f 0 0 1 0)
(Vec4f 0 0 0 1)
-- Indexing
(!|) :: Mat4f -> Int -> Vec4f
(Mat4f r0 r1 r2 r3) !| 0 = r0
(Mat4f r0 r1 r2 r3) !| 1 = r1
(Mat4f r0 r1 r2 r3) !| 2 = r2
(Mat4f r0 r1 r2 r3) !| 3 = r3
(Mat4f r0 r1 r2 r3) !| _ = error "Invalid index to (!!) Mat4f"
--------------------------------------------------------------------------------
-- 3x3 Column Matrix
--------------------------------------------------------------------------------
data ColMat3f = ColMat3f !Vec3f !Vec3f !Vec3f
deriving (Show, Eq)
colMat3f = ColMat3f
-- Determinant of a 3x3 column matrix
detMat3f :: ColMat3f -> RealT
detMat3f (ColMat3f a b c) =
let (Vec3f ax ay az) = a in
let (Vec3f bx by bz) = b in
let (Vec3f cx cy cz) = c in
ax*(by*cz - cy*bz) + bx*(cy*az - ay*cz) + cx*(ay*bz - by*az)
|
tchagnon/cs636-raytracer
|
a3/Math.hs
|
apache-2.0
| 6,859
| 0
| 19
| 1,847
| 2,919
| 1,531
| 1,388
| 159
| 1
|
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
module Main where
import Control.Applicative
import Control.Error
import Control.Monad (forM_)
import qualified Data.ByteString.Char8 as BS
import qualified Data.Configurator as C
import Data.Configurator.Types
import Data.Data
import Data.DList (toList)
import Data.Monoid
import qualified Data.Text as T
import qualified Data.Text.Lazy as TL
import Data.Time
import Github.Api
import Github.Data
import Github.Review
import Github.Review.Format
import Network (PortID(..))
import qualified Network.Mail.Mime as Mime
import Network.Mail.SMTP
import Network.Mail.SMTP.TLS
import Network.Socket (HostName, PortNumber(..))
import System.Console.CmdArgs
import System.Environment
import System.Exit
import System.Locale (defaultTimeLocale)
import Text.Blaze.Html.Renderer.Text (renderHtml)
import Text.Parsec (parse)
import Text.ParserCombinators.Parsec.Rfc2822 (NameAddr(..), address_list, name_addr)
-- Command-line parsing.
data CliConfig = CliConfig { config :: String }
deriving (Show, Data, Typeable)
gitReviewCliArgs :: CliConfig
gitReviewCliArgs = CliConfig { config = def &= help "The configuration file." }
&= summary "GitReview v0"
-- Configuration file.
data GitReviewConfig = GitReviewConfig
{ samplePeriod :: !Int
, sampleN :: !Int
, ghAccount :: !GithubAccount
, ghPausePeriod :: !Int
, emailAddresses :: ![NameAddr]
, retrySettings :: !GitReviewRetry
, smtpHost :: !HostName
, smtpPort :: !Int
, smtpUser :: !UserName
, smtpPassword :: !Password
} deriving (Show)
data GitReviewRetry = GitReviewRetry
{ numRetries :: !Int
, backoff :: !Bool
, baseDelay :: !Int
, accumErrors :: !Int
} deriving (Show)
getReviewConfig :: Config -> GithubInteraction GitReviewConfig
getReviewConfig cfg =
GitReviewConfig <$> lookupIO cfg 1 "sample.period"
<*> lookupIO cfg 10 "sample.n"
<*> getGithubAccount cfg
<*> lookupIO cfg 1 "github.pause"
<*> getEmailAddresses cfg
<*> getRetrySettings cfg
<*> lookupT "Missing config: smtp.host" "smtp.host"
<*> lookupT "Missing config: smtp.port" "smtp.port"
<*> lookupT "Missing config: smtp.user" "smtp.user"
<*> lookupT "Missing config: smtp.password" "smtp.password"
where lookupT msg name = ghIO (C.lookup cfg name)
>>= hoistEitherT . noteT (UserError msg) . hoistMaybe
lookupIO :: Configured a => Config -> a -> Name -> GithubInteraction a
lookupIO cfg def = liftIO . C.lookupDefault def cfg
getRetrySettings :: Config -> GithubInteraction GitReviewRetry
getRetrySettings cfg =
GitReviewRetry <$> lookupIO cfg 5 "retry.numRetries"
<*> lookupIO cfg True "retry.backoff"
<*> lookupIO cfg 50 "retry.baseDelay"
<*> lookupIO cfg 1 "retry.accumErrors"
getEmailAddresses :: Config -> GithubInteraction [NameAddr]
getEmailAddresses cfg = do
addrStr <- hoistGH (noteError <$> lookupEmail)
insertEither $ parseAddr addrStr
where noteError = note (UserError "No target.email in config.")
lookupEmail = C.lookup cfg "target.email"
parseAddr = ghError . parse address_list ""
getGithubAccount :: Config -> GithubInteraction GithubAccount
getGithubAccount cfg =
hoistGH ( note (UserError "You must set either the organization or account.")
. listToMaybe
. catMaybes
<$> sequence [ fmap GithubOrgName <$> C.lookup cfg "github.organization"
, fmap GithubUserName <$> C.lookup cfg "github.account"
])
-- Getting the commit
getGithubCommit :: GitReviewConfig -> GithubAuth -> GithubInteraction RepoCommit
getGithubCommit GitReviewConfig{..} auth = do
limit <- liftIO
$ offsetByDays (fromIntegral samplePeriod)
<$> getCurrentTime
cs <- getAccountRepos ghAccount >>=
mapM (`getCommits` sampleN)
hoistEitherT
. fmapLT (UserError . T.unpack)
. pickRandom
. getAfterOrMinimum (getCommitDate . snd) limit sampleN
. sortByCommitDate
$ concat cs
where getCommits = getAllRepoCommits' (Just auth) (Just ghPausePeriod)
-- Utilities
ghError :: Show a => Either a b -> Either Error b
ghError = fmapL (UserError . show)
ghErrorT :: Show a => EitherT a IO b -> GithubInteraction b
ghErrorT = hoistEitherT . fmapLT (UserError . show)
ghIO :: IO a -> GithubInteraction a
ghIO = ghErrorT . tryIO
-- Sending mail
getDateStr :: GithubInteraction T.Text
getDateStr = do
t <- ghIO (utcToLocalTime <$> getCurrentTimeZone <*> getCurrentTime)
return . T.pack $ formatTime defaultTimeLocale "%c" t
wrapAndParse :: String -> GithubInteraction Address
wrapAndParse user = toAddress <$> ( insertEither
. ghError
. parse name_addr ""
$ "<" <> user <> ">")
toAddress :: NameAddr -> Address
toAddress NameAddr{..} =
Address (T.pack <$> nameAddr_name) $ T.pack nameAddr_addr
sendCommit :: GitReviewConfig -> Repo -> Commit -> GithubInteraction ()
sendCommit GitReviewConfig{..} r c = do
dateStr <- getDateStr
from <- wrapAndParse smtpUser
ghIO . forM_ emailAddresses $ \to ->
let to' = toAddress to
in commentEmail to' from ("Commit to review for " <> dateStr) r c >>=
sendMailTls' smtpHost smtpPort smtpUser smtpPassword
sendError :: GitReviewConfig -> Error -> [TaskName] -> GithubInteraction ()
sendError GitReviewConfig{..} err tasks = do
dateStr <- getDateStr
from <- wrapAndParse smtpUser
ghIO . forM_ emailAddresses $ \to ->
let (asText, asHtml) = formatError err tasks
in Mime.simpleMail (toAddress to) from
("ERROR: Retreiving commits to review for " <> dateStr)
(TL.fromStrict asText)
(renderHtml asHtml)
[] >>=
sendMailTls' smtpHost smtpPort smtpUser smtpPassword
sendResults :: GitReviewConfig
-> Either Error (Repo, Commit)
-> [TaskName]
-> GithubInteraction ()
sendResults cfg (Right (r, c)) _ = sendCommit cfg r c
sendResults cfg (Left err) tasks = sendError cfg err tasks
-- Main
main :: IO ()
main = do
(retCode, _) <- runGithubInteraction 1 def def def $ do
cfg <- getReviewConfig
=<< ghIO ( C.load
=<< (:[]) . C.Required . config
<$> cmdArgs gitReviewCliArgs)
auth <- hoistGH . fmap (fmapL UserError) . runEitherT $
GithubBasicAuth <$> scriptIO (BS.pack <$> getEnv "GITHUB_USER")
<*> scriptIO (BS.pack <$> getEnv "GITHUB_PASSWD")
let GitReviewRetry{..} = retrySettings cfg
(result, log) <- ghIO . runGithubInteraction accumErrors numRetries backoff baseDelay $
getGithubCommit cfg auth
sendResults cfg result log
case retCode of
Left err -> putStrLn ("ERROR: " <> show err) >> exitWith (ExitFailure 1)
Right _ -> putStrLn "ok"
|
erochest/gitreview
|
GitReview.hs
|
apache-2.0
| 8,146
| 0
| 20
| 2,752
| 1,940
| 997
| 943
| 194
| 2
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.