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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
import Test.HUnit
import BinomialHeap
main =
let
q01 :: BinomialHeap Int
q01 = empty
q02 = insert q01 3
q03 = insert q02 0
q04 = insert q03 6
q05 = insert q04 2
q06 = insert q05 4
q07 = insert q06 7
q08 = insert q07 0
q09 = insert q08 0
Just (v1, q10) = deleteMin q09
Just (v2, q11) = deleteMin q10
Just (v3, q12) = deleteMin q11
Just (v4, q13) = deleteMin q12
Just (v5, q14) = deleteMin q13
Just (v6, q15) = deleteMin q14
Just (v7, q16) = deleteMin q15
Just (v8, q17) = deleteMin q16
test1 = TestCase (assertEqual "v1 should be 0." (0) (v1))
test2 = TestCase (assertEqual "v2 should be 0." (0) (v2))
test3 = TestCase (assertEqual "v3 should be 0." (0) (v3))
test4 = TestCase (assertEqual "v4 should be 2." (2) (v4))
test5 = TestCase (assertEqual "v5 should be 3." (3) (v5))
test6 = TestCase (assertEqual "v6 should be 4." (4) (v6))
test7 = TestCase (assertEqual "v7 should be 6." (6) (v7))
test8 = TestCase (assertEqual "v8 should be 7." (7) (v8))
in
runTestTT $ TestList [test1,test2,test3,test4,test5,test6,test7,test8]
|
cshung/MiscLab
|
Haskell99/BinomialHeap.test.hs
|
mit
| 1,139 | 0 | 12 | 303 | 480 | 252 | 228 | 31 | 1 |
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE EmptyDataDecls #-}
module Web.Readability.Api (
saveEntry
) where
import Web.Blog.Type (Url)
import Data.Text (Text)
import Data.Maybe (fromJust)
import Control.Monad (mzero)
import Data.Aeson
import Network.HTTP.Conduit (simpleHttp)
import Control.Monad.IO.Class (liftIO)
import Control.Applicative ((<$>),(<*>))
import Database.Persist
import Database.Persist.Sqlite
import Database.Persist.TH
import System.Environment (getEnv)
baseUrl :: Url
baseUrl = "https://readability.com/api/content/v1/parser"
dbname :: Text
dbname = "entry.sqlite3"
getToken :: IO String
getToken = getEnv "READABILITY_API_TOKEN"
share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase|
ReaderApiResponse
content Text
domain String
author Text Maybe
url String
shortUrl String
title Text
excerpt Text
direction String
wordCount Int
totalPages Int
datePublished String Maybe
dek Text Maybe
leadImageUrl String Maybe
nextPageId Int Maybe
renderedPages Int
UniqueReaderApiResponse url
deriving Show
|]
instance FromJSON ReaderApiResponse where
parseJSON (Object v) = ReaderApiResponse <$>
v .: "content" <*>
v .: "domain" <*>
v .:? "author" <*>
v .: "url" <*>
v .: "short_url" <*>
v .: "title" <*>
v .: "excerpt" <*>
v .: "direction" <*>
v .: "word_count" <*>
v .: "total_pages" <*>
v .:? "date_published" <*>
v .:? "dek" <*>
v .:? "lead_image_url" <*>
v .:? "next_page_id" <*>
v .: "rendered_pages"
parseJSON _ = mzero
saveEntry :: Url -> IO ()
saveEntry entry_url =
runSqlite dbname $ do
runMigration migrateAll
entries <- selectList ([ReaderApiResponseUrl ==. entry_url]::[Filter ReaderApiResponse]) [LimitTo 1]
if null entries
then do
b <- liftIO $ httpGetAndJson entry_url
insert b
liftIO $ putStrLn $ readerApiResponseUrl b
else error "already saved."
return ()
httpGetAndJson :: Url -> IO ReaderApiResponse
httpGetAndJson entry_url = do
token <- getToken
a <- simpleHttp $ baseUrl ++ "?url=" ++ entry_url ++ "&token=" ++ token
let b = fromJust $ decode a :: ReaderApiResponse
return b
|
suzuki-shin/blogtools
|
Web/Readability/Api.hs
|
mit
| 2,813 | 0 | 35 | 860 | 554 | 294 | 260 | 66 | 2 |
{-# htermination approxRational :: (Ratio Int) -> (Ratio Int) -> Rational #-}
|
ComputationWithBoundedResources/ara-inference
|
doc/tpdb_trs/Haskell/full_haskell/Prelude_approxRational_3.hs
|
mit
| 78 | 0 | 2 | 12 | 3 | 2 | 1 | 1 | 0 |
module CoreLang.TInst
(
eval
, compile
, showResults
)
where
import CoreLang.Utils
import CoreLang.Language
import CoreLang.ISeq
import Data.Maybe (fromMaybe)
type TiState = (TiStack, TiDump, TiHeap, TiGlobals, TiStats)
type TiStack = [Addr]
data TiDump = DummyTiDump
initialTiDump :: TiDump
initialTiDump = DummyTiDump
type TiHeap = Heap Node
data Node = NAp Addr Addr
| NSupercomb Name [Name] CoreExpr
| NNum Int
| NInd Addr
type TiGlobals = [(Name, Addr)]
type TiStats = Int
tiStatInitial :: TiStats
tiStatInitial = 0
tiStatIncStep :: TiStats -> TiStats
tiStatIncStep s = s+1
tiStatGetSteps :: TiStats -> Int
tiStatGetSteps s = s
applyToStats :: (TiStats -> TiStats) -> TiState -> TiState
applyToStats f (stack, dump, heap, scDefs, stats) =
(stack, dump, heap, scDefs, f stats)
-- |Converts a Core AST into an initial state.
compile :: CoreProgram -> TiState
compile program =
(initialStack, initialTiDump, initialHeap, globals, tiStatInitial)
where scDefs = program ++ preludeDefs ++ extraPreludeDefs
(initialHeap, globals) = buildInitialHeap scDefs
initialStack = [addrOfMain]
addrOfMain = fromMaybe (error "main is not defined") $ lookup "main" globals
extraPreludeDefs :: CoreProgram
extraPreludeDefs = []
buildInitialHeap :: [CoreScDefn] -> (TiHeap, TiGlobals)
buildInitialHeap scDefs = mapAccuml allocateSc hInitial scDefs
allocateSc :: TiHeap -> CoreScDefn -> (TiHeap, (Name, Addr))
allocateSc heap (name, args, body) =
(heap', (name, addr))
where (heap', addr) = hAlloc heap (NSupercomb name args body)
-- |Evaluates a state, produces a trace.
eval :: TiState -> [TiState]
eval state = state : restStates
where restStates | tiFinal state = []
| otherwise = eval nextState
nextState = doAdmin (step state)
doAdmin :: TiState -> TiState
doAdmin state = applyToStats tiStatIncStep state
tiFinal :: TiState -> Bool
tiFinal ([soleAddr], dump, heap, globals, stats) =
isDataNode (hLookup heap soleAddr)
tiFinal ([], dump, heap, globals, stats) = error "Empty stack!"
tiFinal state = False
isDataNode :: Node -> Bool
isDataNode (NNum _) = True
isDataNode _ = False
step :: TiState -> TiState
step state = dispatch (hLookup heap (head stack))
where (stack, dump, heap, globals, stats) = state
dispatch (NNum n) = numStep state n
dispatch (NAp a1 a2) = apStep state a1 a2
dispatch (NSupercomb sc args body) = scStep state sc args body
dispatch (NInd a1) = step (a1:(tail stack), dump, heap, globals, stats)
numStep :: TiState -> Int -> TiState
numStep state n = error "Number applied as a function!"
apStep :: TiState -> Addr -> Addr -> TiState
apStep (stack, dump, heap, globals, stats) a1 a2 =
(a1 : stack, dump, heap, globals, stats)
scStep :: TiState -> Name -> [Name] -> CoreExpr -> TiState
scStep (stack, dump, heap, globals, stats) scName argNames body =
(newStack, dump, newHeap2, globals, stats)
where newStack = resultAddr : (drop (length argNames+1) stack)
(newHeap, resultAddr) = instantiate body heap env
aN = stack !! (length argNames)
newHeap2 = hUpdate newHeap aN (NInd resultAddr)
env = argBindings ++ globals
argBindings = zip argNames (getArgs heap stack)
getArgs :: TiHeap -> TiStack -> [Addr]
getArgs heap (sc:stack) =
map getArg stack
where getArg addr = arg where (NAp fun arg) = hLookup heap addr
instantiate :: CoreExpr -> TiHeap -> TiGlobals -> (TiHeap, Addr)
instantiate (ENum n) heap env = hAlloc heap (NNum n)
instantiate (EAp e1 e2) heap env =
hAlloc heap2 (NAp a1 a2)
where (heap1, a1) = instantiate e1 heap env
(heap2, a2) = instantiate e2 heap1 env
instantiate (EVar v) heap env =
(heap, fromMaybe (error $ "Undefined name " ++ show v) $ lookup v env)
instantiate (EConstr tag arity) heap env =
instantiateConstr tag arity heap env
instantiate (ELet isrec defs body) heap env =
instantiateLet isrec defs body heap env
instantiate (ECase e alts) heap env =
error "Can't instantiate case exprs"
instantiateConstr :: Int -> Int -> TiHeap -> TiGlobals -> (TiHeap, Addr)
instantiateConstr tag arity heap env =
error "Can't instantiate constructors yet"
instantiateLet :: IsRec -> [(Name, CoreExpr)]
-> CoreExpr
-> TiHeap
-> TiGlobals
-> (TiHeap, Addr)
instantiateLet _ [] body heap env
= instantiate body heap env
instantiateLet False (def:defs) body heap env
= let (name, expr) = def
(newHeap, addr) = instantiate expr heap env
in instantiateLet False defs body newHeap ((name, addr):env)
instantiateLet True defs body heap env
= let names = map fst defs
exprs = map snd defs
-- Notice the interesting mutual recursion here.
-- This is only possible because of Haskell's laziness.
(newHeap, addrs) =
mapAccuml (\hp e -> instantiate e hp augEnv) heap exprs
augEnv = (zip names addrs)++env
in instantiate body newHeap augEnv
-- |Converts a list of 'TiState' into formatted string.
showResults :: [TiState] -> String
showResults states =
iDisplay $ iConcat [ iLayn (map showState states)
, showStats (last states) ]
showState :: TiState -> Iseq
showState (stack, dump, heap, globals, stats) =
iConcat [ showStack heap stack, iNewline,
showHeap heap ]
showHeap :: TiHeap -> Iseq
showHeap heap =
iConcat [
iStr "Heap [",
iIndent (iInterleave iNewline (map showHeapItem addresses)),
iStr "]"
]
where addresses = hAddresses heap
showHeapItem addr =
iConcat [
showFWAddr addr, iStr ": ",
showNode $ hLookup heap addr
]
showStack :: TiHeap -> TiStack -> Iseq
showStack heap stack =
iConcat [
iStr "Stk [",
iIndent (iInterleave iNewline (map showStackItem stack)),
iStr "]"
]
where
showStackItem addr =
iConcat [ showFWAddr addr, iStr ": ",
showStkNode heap (hLookup heap addr) ]
showStkNode :: TiHeap -> Node -> Iseq
showStkNode heap (NAp funAddr argAddr) =
iConcat [ iStr "NAp ", showFWAddr funAddr,
iStr " ", showFWAddr argAddr, iStr " (",
showNode (hLookup heap argAddr), iStr ")" ]
showStkNode heap node = showNode node
showNode :: Node -> Iseq
showNode (NAp a1 a2) =
iConcat [ iStr "NAp ", showFWAddr a1,
iStr " ", showFWAddr a2 ]
showNode (NSupercomb name args body) =
iStr ("NSupercomb " ++ name)
showNode (NNum n) = (iStr "NNum ") `iAppend` (iFWNum 3 n)
showNode (NInd ind) = (iStr "NInd ") `iAppend` (iFWNum 3 ind)
showAddr :: Addr -> Iseq
showAddr addr = iStr $ show addr
showFWAddr :: Addr -> Iseq
showFWAddr addr =
iStr (space (4 - length str) ++ str)
where str = show addr
showStats :: TiState -> Iseq
showStats (stack, dump, heap, globals, stats) =
iConcat [ iNewline, iNewline, iStr "Total number of steps = ",
iNum (tiStatGetSteps stats) ]
|
hengchu/CoreLang
|
CoreLang/TInst.hs
|
mit
| 7,004 | 0 | 12 | 1,658 | 2,434 | 1,293 | 1,141 | 172 | 4 |
{-# LANGUAGE RecordWildCards #-}
module MachineLearning.Hopfield
(HopfieldNet(..),
initialize,
initializeWith,
activity,
train,
associate,
(//),
energy) where
import Control.Monad
import Control.Monad.Random hiding (fromList)
import Data.Packed.Matrix
import Data.Packed.ST
import Data.Packed.Vector
import Foreign.Storable
import Numeric.Container
data HopfieldNet = HopfieldNet { state :: Vector Float
, weights :: Matrix Float
} deriving (Show)
activity :: (Floating a, Ord a) => a -> a
activity activation = if activation <= 0 then -1.0 else 1.0
initialize :: Int -> HopfieldNet
initialize n = HopfieldNet (fromList (replicate n 0)) ((n >< n) (repeat 0))
initializeWith :: Matrix Float -> HopfieldNet
initializeWith patterns = train state patterns
where
state = initialize (cols patterns)
(//) :: Foreign.Storable.Storable a => Vector a -> [(Int, a)] -> Vector a
vec // mutations = runSTVector $ thawVector vec >>= mutate
where
mutate mv = forM_ mutations (modify mv) >> return mv
modify mv (idx, value) = modifyVector mv idx (const value)
update' :: HopfieldNet -> Int -> HopfieldNet
update' HopfieldNet{..} neuron = HopfieldNet newState weights
where
newState = state // [(neuron, activity activation)]
activation = (toColumns weights !! neuron) <.> state
update :: MonadRandom m => HopfieldNet -> m HopfieldNet
update n = liftM (update' n) $ getRandomR (0, (dim . state) n - 1)
train :: HopfieldNet -> Matrix Float -> HopfieldNet
train HopfieldNet{..} patterns = HopfieldNet state (add weights updates)
where
updates = buildMatrix n n weight
n = dim state
scalingFactor = 1.0 / fromIntegral (rows patterns)
weight (i, j) = (toColumns patterns !! i) <.> (toColumns patterns !! j)
* scalingFactor
settle
:: (Enum b, Num b, MonadRandom m) =>
HopfieldNet -> b -> m HopfieldNet
settle net iterations = foldM (\state _ -> update state) net [1..iterations]
associate :: MonadRandom m => HopfieldNet -> Int -> Vector Float -> m (Vector Float)
associate net iterations pattern =
liftM state $ settle (net { state = pattern }) iterations
energy :: HopfieldNet -> Float
energy HopfieldNet{..} = -0.5 * (mXv weights state <.> state)
|
ajtulloch/hopfield-networks
|
MachineLearning/Hopfield.hs
|
mit
| 2,422 | 0 | 11 | 620 | 829 | 436 | 393 | -1 | -1 |
{-|
Module : Lipschitz
Description : Omejitev funkcij z premicami (koeficientom pravimo Lipschitzove konstante)
Copyright : (c) Andrej Borštnik, Barbara Bajcer, 2015
Maintainer : [email protected], [email protected]
Stability : experimental
Računanje vrednosti funkcije in konstant, ki lokalno omejujejo to funkcijo.
-}
module Lipschitz.Lipschitz
( L(..)
, constL
, idL
, sqr
, integral
, integralZ
, integralS
)
where
import Control.Applicative
instance Num b => Num (a -> b) where
fromInteger = pure . fromInteger
negate = fmap negate
(+) = liftA2 (+)
(*) = liftA2 (*)
abs = fmap abs
signum = fmap signum
instance Fractional b => Fractional (a -> b) where
fromRational = pure . fromRational
recip = fmap recip
instance Floating b => Floating (a -> b) where
pi = pure pi
sqrt = fmap sqrt
exp = fmap exp
log = fmap log
sin = fmap sin
cos = fmap cos
asin = fmap asin
atan = fmap atan
acos = fmap acos
sinh = fmap sinh
cosh = fmap cosh
asinh = fmap asinh
acosh = fmap acosh
atanh = fmap atanh
-- |Struktura L predstavlja točko, zgornjo konstanto (desno od točke), spodnjo konstanto ter okolico, kjer premici omejujeta funkcijo (levi eps in desni eps).
data L a = L a a a a a
instance (Show a) => Show (L a) where
show (L a b c d e) = "L " ++ show a ++ " " ++ show b ++ " " ++ show c ++ " " ++ show d ++ " " ++ show e
infinity :: Fractional a => a
infinity = 1/0
-- |@constL@ je konstantna fukncija.
constL :: Fractional a => a -> L a
constL x = L x 0 0 infinity infinity
-- | @idL@ je identična funkcija.
idL :: Fractional a => a -> L a
idL x = L x 1 1 infinity infinity
-- |
sqr :: Num a => a -> a
sqr a = a * a
-- it is beneficial to use points with the same eps, because we lose the least precision
instance (Fractional a, Ord a) => Num (L a) where
fromInteger = constL . fromInteger
L a au al aeps1 aeps2 + L b bu bl beps1 beps2 = L (a + b) (au + bu) (al + bl) eps1 eps2 where
eps1
| (aeps1 == infinity && aeps2 == infinity && au == 0 && al == 0) = beps1
| (beps1 == infinity && beps2 == infinity && bu == 0 && bl == 0) = aeps1
| otherwise = (aeps1 + beps1)/2
eps2
| (aeps1 == infinity && aeps2 == infinity && au == 0 && al == 0) = beps2
| (beps1 == infinity && beps2 == infinity && bu == 0 && bl == 0) = aeps2
| otherwise = (aeps2 + beps2)/2
L a au al aeps1 aeps2 * L b bu bl beps1 beps2 = L (a * b) u l eps1 eps2 where
eps1
| (aeps1 == infinity && aeps2 == infinity && au == 0 && al == 0) = min aeps1 beps1
| (beps1 == infinity && beps2 == infinity && bu == 0 && bl == 0) = min aeps1 beps1
| otherwise = (aeps1 + beps1)/2
eps2
| (aeps1 == infinity && aeps2 == infinity && au == 0 && al == 0) = min aeps2 beps2
| (beps1 == infinity && beps2 == infinity && bu == 0 && bl == 0) = min aeps2 beps2
| otherwise = (aeps2 + beps2)/2
u1
| (aeps1 == infinity && aeps2 == infinity && au == 0 && al == 0) = a*bu
| (beps1 == infinity && beps2 == infinity && bu == 0 && bl == 0) = b*au
| otherwise = max (au * bu * eps2 + au * b + bu * a) (max (al * bl * eps2 + al * b + bl * a) (max (- al * bu * eps1 + al * b + bu * a) (- au * bl * eps1 + au * b + bl * a)))
l1
| (aeps1 == infinity && aeps2 == infinity && au == 0 && al == 0) = bl*a
| (beps1 == infinity && beps2 == infinity && bu == 0 && bl == 0) = al*b
| otherwise = min (au * bl * eps2 + au * b + bl * a) (min (al * bu * eps2 + al * b + bu * a) (min (- al * bl * eps1 + al * b + bl * a) (- au * bu * eps1 + au * b + bu * a)))
u
| (au < infinity && bu < infinity) = u1
| otherwise = infinity
l
|(al > - infinity && bl > - infinity) = l1
| otherwise = - infinity
negate (L a au al eps1 eps2) = L (-a) (-al) (-au) eps1 eps2
signum (L a au al eps1 eps2) = L (signum a) 0 0 eps1 eps2
abs (L a au al eps1 eps2) = L (abs a) c (-c) eps1 eps2 where
c = max (abs au) (abs al)
instance (Fractional a, Ord a) => Fractional (L a) where
fromRational = constL . fromRational
-- Razlaga:
-- foreach x \in [0, eps]. al * x <= f (a + x) - f a <= au * x
-- because 1 / f (a + x) - 1 / f a = f a - f (a + x) / f a * f (a + x), we have
-- - au * x / fmax / f a <= 1 / f (a + x) - 1 / f a <= - al * x / fmin / f a
-- podobno za x \in [- eps, 0]
recip (L a au al e1 e2) = L (recip a) u l eps1 eps2 where
amin = min (a - au * e1) (a + al * e2)
amax = max (a + au * e2) (a - al * e1)
eps1
| (a > 0) = min a (a - amin)
| otherwise = a - amin
eps2
| (a < 0) = min (- a) (amax - a)
| otherwise = amax - a
l
| (a == infinity || eps1 == infinity || eps2 == infinity || a == - infinity || a == 0) = -infinity
| otherwise = (max (- au) (- al)) / amax / a
u
| (a == infinity || eps1 == infinity || eps2 == infinity || a == - infinity || a == 0) = infinity
| otherwise = (min (- al) (- au)) / amin / a
mod1 :: (Num a, Ord a) => a -> a -> a
mod1 x y = if x <= y && x >= 0 then x else if x > 0 then mod1 (x - y) y else mod1 (x + y) y
instance (Floating a, Ord a) => Floating (L a) where
pi = constL pi
exp (L a au al e1 e2) = L (exp a) u l eps1 eps2 where
amin = min (a - au * e1) (a + al * e2)
amax = max (a + au * e2) (a - al * e1)
eps1 = a - amin
eps2 = amax - a
l
| (a == infinity || eps1 == infinity || eps2 == infinity || a == - infinity) = -infinity
| otherwise = (exp a - exp (a - eps1)) / eps1
u
| (a == infinity || eps1 == infinity || eps2 == infinity || a == - infinity) = infinity
| otherwise = (exp (a + eps2) - exp a) / eps2
log (L a au al e1 e2) = L (log a) u l eps1 eps2 where
amin = min (a - au * e1) (a + al * e2)
amax = max (a + au * e2) (a - al * e1)
eps1
| (a > 0) = min a (a - amin)
| otherwise = a - amin
eps2
| (a < 0) = min (- a) (amax - a)
| otherwise = amax - a
l
| (a <= 0) = infinity/infinity
| (eps1 == infinity || eps2 == infinity || a == infinity) = 0
| otherwise = (log (a + eps2) - log a) / eps2
u
| (a <= 0) = infinity/infinity
| (eps1 == infinity || eps2 == infinity || a == infinity) = infinity
| otherwise = (log a - log (a - eps1)) / eps1
sqrt (L a au al e1 e2) = L (sqrt a) u l eps1 eps2 where
amin = min (a - au * e1) (a + al * e2)
amax = max (a + au * e2) (a - al * e1)
eps1
| (a > 0) = min a (a - amin)
| otherwise = a - amin
eps2
| (a < 0) = min (- a) (amax - a)
| otherwise = amax - a
l
| (a < 0) = infinity/infinity
| (eps1 == infinity || a == infinity || a == 0) = 0
| otherwise = (sqrt (a + eps2) - sqrt a) / eps2
u
| (a < 0) = infinity/infinity
| (eps1 == infinity || a == infinity || a == 0) = infinity
| otherwise = (sqrt a - sqrt (a - eps1)) / eps1
sin (L a au al e1 e2) = L (sin a) u l eps1 eps2 where
amin = min (a - au * e1) (a + al * e2)
amax = max (a + au * e2) (a - al * e1)
eps1 = a - amin
eps2 = amax - a
u = 1
-- if eps > pi/4 then
-- 1
-- else if amin `mod1` (2 * pi) >= 0 && amax `mod1` (2 * pi) <= pi/2 then
-- (sin a - sin amin) / eps
-- else if amin `mod1` (2 * pi) >= pi/2 && amax `mod1` (2 * pi) <= pi then
-- (sin a - sin amin) / eps
-- else if amin `mod1` (2 * pi) >= pi && amax `mod1` (2 * pi) <= 3 * pi / 2 then
-- (sin amax - sin a) / eps
-- else if amin `mod1` (2 * pi) >= 3 * pi / 2 && amax `mod1` (2 * pi) <= 2 * pi then
-- (sin amax - sin a) / eps
-- else 1
l = -1
-- if eps > pi/4 then
-- -1
-- else if amin `mod1` (2 * pi) >= 0 && amax `mod1` (2 * pi) <= pi/2 then
-- (sin amax - sin a) / eps
-- else if amin `mod1` (2 * pi) >= pi/2 && amax `mod1` (2 * pi) <= pi then
-- (sin amax - sin a) / eps
-- else if amin `mod1` (2 * pi) >= pi && amax `mod1` (2 * pi) <= 3 * pi / 2 then
-- (sin a - sin amin) / eps
-- else if amin `mod1` (2 * pi) >= 3 * pi / 2 && amax `mod1` (2 * pi) <= 2 * pi then
-- (sin a - sin amin) / eps
-- else -1
-- if eps >= pi/4 then
-- au1 = 1 -- to se tudi da izboljšat
-- al1 = - 1 -- to je samo spodnja meja, lahko se jo še izboljšat, sploh če epx < pi
-- else
-- if amin `mod` (2 * pi) >= 0 && amax `mod` (2 * pi) <= pi/2 then
-- al1 = (sin amax - a) / eps
-- au1 = (a - sin amin) / eps
-- else if amin `mod` (2 * pi) >= pi/2 && amax `mod` (2 * pi) <= pi then
-- al1 = (sin amax - a) / eps
-- au1 = (a - sin amin) / eps
-- else if amin `mod` (2 * pi) >= pi && amax `mod` (2 * pi) <= 3 * pi / 2
-- au1 = (sin amax - a) / eps
-- al1 = (a - sin amin) / eps
-- else if amin `mod` (2 * pi) >= 3 * pi / 2 && amax `mod` (2 * pi) <= 2 * pi
-- au1 = (sin amax - a) / eps
-- al1 = (a - sin amin) / eps
-- kaj pa če je čez več intervalov?
cos (L a au al e1 e2) = L (cos a) u l eps1 eps2 where
amin = min (a - au * e1) (a + al * e2)
amax = max (a + au * e2) (a - al * e1)
eps1 = a - amin
eps2 = amax - a
u = 1
l = -1
asin (L a au al e1 e2) = L (asin a) u l eps1 eps2 where
amin = min (a - au * e1) (a + al * e2)
amax = max (a + au * e2) (a - al * e1)
eps1
| (a > -1) = min (a + 1) (a - amin)
| otherwise = a - amin
eps2
| (a < 1) = min (1 - a) (amax - a)
| otherwise = amax - a
l
| (a <= -1) = infinity/infinity
| (eps1 == infinity || eps2 == infinity) = infinity
| otherwise = infinity -- TEŽAVE, KER ODVOD NI MONOTON
u
| (a >= 1) = infinity/infinity
| (eps1 == infinity || eps2 == infinity) = infinity
| otherwise = infinity -- TEŽAVE, KER ODVOD NI MONOTON
acos (L a au al e1 e2) = L (acos a) u l eps1 eps2 where
amin = min (a - au * e1) (a + al * e2)
amax = max (a + au * e2) (a - al * e1)
eps1
| (a > -1) = min (a + 1) (a - amin)
| otherwise = a - amin
eps2
| (a < 1) = min (1 - a) (amax - a)
| otherwise = amax - a
l
| (a <= -1) = infinity/infinity
| (eps1 == infinity || eps2 == infinity) = infinity
| otherwise = infinity -- TEŽAVE, KER ODVOD NI MONOTON
u
| (a >= 1) = infinity/infinity
| (eps1 == infinity || eps2 == infinity) = infinity
| otherwise = infinity -- TEŽAVE, KER ODVOD NI MONOTON
atan (L a al au e1 e2) = L (atan a) u l eps1 eps2 where
amin = min (a - au * e1) (a + al * e2)
amax = max (a + au * e2) (a - al * e1)
eps1
| (a > -pi) = min (a + pi) (a - amin)
| otherwise = a - amin
eps2
| (a < pi) = min (pi - a) (amax - a)
| otherwise = amax - a
u
| (eps1 == infinity || eps2 == infinity || a == infinity || a == - infinity) = 1
| otherwise = 1 -- TEŽAVE, KER ODVOD NI MONOTON
l
| (eps1 == infinity || eps2 == infinity || a == infinity || a == - infinity) = 0
| otherwise = 0 -- TEŽAVE, KER ODVOD NI MONOTON
sinh x = (exp x - exp (-x)) / 2
cosh x = (exp x + exp (-x)) / 2
tanh x = sinh x / cosh x
asinh x = log (x + sqrt (sqr x + 1))
acosh x = log (x + sqrt (x - 1) * sqrt (x + 1))
atanh x = log (1 + x) / 2 - log (1 - x) / 2
instance Eq a => Eq (L a) where
L a _ _ _ _ == L b _ _ _ _ = (a == b)
rread :: L a -> (a, a, a)
rread (L a au al eps1 eps2) = (a, au, al)
rread1 :: L a -> (a, a, a, a, a)
rread1 (L a au al eps1 eps2) = (a, au, al, eps1, eps2)
lip :: (Floating a, Ord a) =>(L a -> L a) -> a -> a -> a -> L a
lip f a e1 e2 = f (L a 1 1 e1 e2)
-- |Izračuna približek za določeni integral podane funkcije s korakom h.
integral :: (Floating a, Ord a) => (L a -> L a) -> a -> a -> a -> a
integral f a1 a2 h = if a2 <= a1 then 0 else a + integral f (a1 + h) a2 h where
interval = if (a2 - a1 < h) then (a2 - a1) / 2 else h / 2
(x, u, l, e1, e2) = rread1 (f (L (a1 + interval) 1 1 interval interval))
zgornja = x * (e1 + e2) - e1 * l * e1 / 2 + e2 * u * e2 / 2
spodnja = x * (e1 + e2) - e1 * u * e1 / 2 + e2 * l * e2 / 2
a = (zgornja + spodnja) / 2
-- |Izračuna (približno) zgornjo mejo za določeni integral podane funkcije s korakom h.
integralZ :: (Floating a, Ord a) => (L a -> L a) -> a -> a -> a -> a
integralZ f a1 a2 h = if a2 <= a1 then 0 else a + integralZ f (a1 + h) a2 h where
interval = if (a2 - a1 < h) then (a2 - a1) / 2 else h / 2
(x, u, l, e1, e2) = rread1 (f (L (a1 + interval) 1 1 interval interval))
a = x * (e1 + e2) - e1 * l * e1 / 2 + e2 * u * e2 / 2
-- |Izračuna (približno) spodnjo mejo za določeni integral podane funkcije s korakom h.
integralS :: (Floating a, Ord a) => (L a -> L a) -> a -> a -> a -> a
integralS f a1 a2 h = if a2 <= a1 then 0 else a + integralS f (a1 + h) a2 h where
interval = if (a2 - a1 < h) then (a2 - a1) / 2 else h / 2
(x, u, l, e1, e2) = rread1 (f (L (a1 + interval) 1 1 interval interval))
a = x * (e1 + e2) - e1 * u * e1 / 2 + e2 * l * e2 / 2
f0 :: Floating a => a -> a
f0 z = 3 * z
f1 :: Floating a => a -> a
f1 z = 1 / (1 / z)
f2 :: Floating a => a -> a
f2 z = 5 * z * z
f3 :: Floating a => a -> a
f3 z = sqrt (2 * (1 / (1 / z)))
f4 :: Floating a => a -> a
f4 z = sqrt (z)
f5 :: Floating a => a -> a
f5 z = sqr (cos z)
f7 :: Floating a => a -> a
f7 z = (cos z)
f8 :: Floating a => a -> a
f8 z = 1 - sqr (cos z)
f9 z = z*z*z*z - 5*z*z*z + 2*z*z - 1
f10 :: Floating a => a -> a
f10 z = exp z * sin z
f11 :: Floating a => a -> a
f11 z = sqr (sqr z) + 6 * (sqr z) * z + 2 * (sqr z) + 71
|
andrejborstnik/Samodejno-odvajanje
|
Lipschitz/Lipschitz/lipschitz.hs
|
mit
| 13,124 | 63 | 22 | 3,998 | 6,158 | 3,196 | 2,962 | 264 | 3 |
-- | <http://strava.github.io/api/v3/uploads/>
module Strive.Actions.Uploads
( uploadActivity
, getUpload
) where
import Data.ByteString (ByteString)
import Network.HTTP.Client (RequestBody (RequestBodyBS), requestBody)
import Network.HTTP.Types (Query, methodPost, toQuery)
import Strive.Aliases (Extension, Result, UploadId)
import Strive.Client (Client)
import Strive.Internal.HTTP (buildRequest, get, handleResponse, performRequest)
import Strive.Options (UploadActivityOptions)
import Strive.Types (UploadStatus)
-- | <http://strava.github.io/api/v3/uploads/#post-file>
uploadActivity :: Client -> ByteString -> Extension -> UploadActivityOptions -> IO (Result UploadStatus)
uploadActivity client body dataType options = do
initialRequest <- buildRequest methodPost client resource query
let request = initialRequest
{ requestBody = RequestBodyBS body
}
response <- performRequest client request
return (handleResponse response)
where
resource = "api/v3/uploads"
query = toQuery
[ ("data_type", dataType)
] ++ toQuery options
-- | <http://strava.github.io/api/v3/uploads/#get-status>
getUpload :: Client -> UploadId -> IO (Result UploadStatus)
getUpload client uploadId = get client resource query
where
resource = "api/v3/uploads/" ++ show uploadId
query = [] :: Query
|
liskin/strive
|
library/Strive/Actions/Uploads.hs
|
mit
| 1,326 | 0 | 12 | 189 | 327 | 181 | 146 | 26 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeOperators #-}
module Game.Play.Api where
import Servant ((:<|>), (:>), JSON, Post, ReqBody)
import Game.Api.Types (ErrorOr)
import Game.Play.Api.Types (PlaceBetRq, PlayCardRq)
import Game.Types (Game)
type Routes =
PlayCard
:<|> PlaceBet
type PlayCard = "playCard" :> ReqBody '[JSON] PlayCardRq :> Post '[JSON] (ErrorOr Game)
type PlaceBet = "placeBet" :> ReqBody '[JSON] PlaceBetRq :> Post '[JSON] (ErrorOr Game)
|
rubenmoor/skull
|
skull-server/src/Game/Play/Api.hs
|
mit
| 546 | 0 | 9 | 148 | 159 | 95 | 64 | 12 | 0 |
{-# LANGUAGE DeriveDataTypeable, PatternGuards, MultiParamTypeClasses, ScopedTypeVariables, TemplateHaskell, ImpredicativeTypes, FlexibleContexts #-}
module Main where
import Data.List
import BlazeHtml hiding (time, name)
import Data.Generics
import Data.Char
import Data.Maybe
import Data.Map (Map)
import qualified Data.Map as Map
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
import Debug.Trace
import System.Time
import Data.Time.Calendar
import Types
import Generics
import WebViewPrim
import WebViewLib
import HtmlLib
import Control.Monad.State
import Server
import System.IO.Unsafe (unsafePerformIO) -- just for calendar stuff
import TemplateHaskell
import Database
import ClientWebView
import ReservationUtils
main :: IO ()
main = server 8102 "Reservations" rootViews ["Reservations.css"] "ReservationsDB.txt" mkInitialDatabase users
-- the webviews here are phantom typed, so we need rootView to get rid of the phantom types
rootViews = [ mkRootView "" mkMainRootView -- combined view of restaurant and client
, mkRootView "client" mkClientWrapperView -- for running in a browser by itself or on an iPhone/iPad
, mkRootView "embeddedClient" mkClientView -- for running in an iFrame
, mkRootView "restaurant" mkRestaurantWrapperView -- for running in a browser by itself or on an iPad/iPhone
, mkRootView "embeddedRestaurant" mkRestaurantView -- for running in an iFrame
, mkRootView "test" mkTestView1
]
-- TODO: id's here?
-- TODO: fix the sessionId stuff
-- TODO: find good names for root, main, etc.
-- TODO: sessionId? put this in an environment? or maybe the WebViewM monad?
data TestView1 =
TestView1 (Widget (EditAction Database)) (Widget (Button Database)) String String
deriving (Eq, Show, Typeable)
instance Initial TestView1 where
initial = TestView1 initial initial initial initial
-- pass client state back with an edit action
-- seems easier than using JSVar's below
mkTestView1 = mkWebView $
\vid (TestView1 ea _ status _) ->
do { ea <- mkEditActionEx $ \args -> do { debugLn $ "edit action executed "++show args
; viewEdit vid $ (\(TestView1 a b _ d) -> TestView1 a b (head args) d)
}
-- todo: need a way to enforce that ea is put in the webview
; b <- mkButton "Test" True $ return ()
; return $ TestView1 ea b status $
-- "console.log('test script running');" ++
jsDeclareVar vid "clientState" "2" ++
onClick b (jsVar vid "clientState" ++"++;" ++
callServerEditAction ea [jsVar vid "clientState","2"])
}
instance Presentable TestView1 where
present (TestView1 ea b status scr) = vList [toHtml status, present b] +++ mkScript scr
instance Storeable Database TestView1 where
-- trying to handle passing back client state by using a JSVar
data TestView2 =
TestView2 (Widget (JSVar Database)) (Widget (Button Database)) String String
deriving (Eq, Show, Typeable)
instance Initial TestView2 where
initial = TestView2 initial initial initial initial
mkTestView2 = mkWebView $
\vid (TestView2 oldXVar@(Widget _ _ (JSVar _ _ v)) _ status _) ->
do { x <- mkJSVar "x" (if v == "" then "6" else v)
-- todo Even though the initial value is only assigned once to the client variable, it is also
-- used to store the value at server side, so we need to check if it has a value and assign if not
-- this is not okay. keep separate field for initializer?
; b <- mkButton "Test" True $ do { xval <- getJSVarContents x
; debugLn $ "value of js var is "++xval
; viewEdit vid $ (\(TestView2 a b _ d) -> TestView2 a b xval d)
}
; return $ TestView2 x b status $
-- "console.log('test script running');" ++
onClick b (refJSVar x++"++"{-++";console.log("++refJSVar x++");"-} ++
"queueCommand('SetC ("++show (getViewId x)++") \"'+"++refJSVar x++"+'\"');"++
"queueCommand('ButtonC ("++show (getViewId b)++")');")
}
-- todo: reusing goes wrong in this case: ; nrOfPeopleVar <- mkJSVar "x" $ show $ getJSVarValue oldNrOfPeopleVar
--extra escape chars are added on each iteration. (this was in a webview that was re-presented constantly)
refJSVar (Widget _ _ (JSVar viewId name _)) = name++viewIdSuffix viewId
instance Presentable TestView2 where
present (TestView2 x b status scr) = vList [toHtml status, present b] +++ present x +++ mkScript scr
instance Storeable Database TestView2 where
-- Main ----------------------------------------------------------------------
data MainView =
MainView (WV ClientView) (WV RestaurantView)
deriving (Eq, Show, Typeable)
instance Initial MainView where
initial = MainView initial initial
mkMainRootView = mkWebView $
\vid (MainView _ _) ->
do { clientView <- mkClientView
; restaurantView <- mkRestaurantView
; return $ MainView clientView restaurantView
}
appBgColor = Rgb 0xf8 0xf8 0xf8
dayColor = Rgb 0xf0 0xf0 0xf0 -- todo: these are background colors rather than colors
selectedDayColor = Rgb 0x80 0xb0 0xff
todayColor = Rgb 0x90 0x90 0x90
hourColor = Rgb 0xd0 0xd0 0xd0
selectedHourColor = Rgb 0x80 0xb0 0xff
reservationColor = Rgb 0xf8 0xf8 0xf8
selectedReservationColor = selectedDayColor
instance Presentable MainView where
present (MainView cv rv) =
mkClassDiv "CombinedWrapperParent" $ mkPage [] $ mkClassDiv "CombinedWrapperView" $
hListEx [] [ roundedBoxed (Just $ appBgColor) $ present rv
, hSpace 50
, roundedBoxed (Just $ appBgColor) $ present cv
]
instance Storeable Database MainView where
-- Main ----------------------------------------------------------------------
-- Extra indirection, so we can style restaurant views that are not part of the combined view or embedded in an iFrame.
data RestaurantWrapperView = RestaurantWrapperView (WV RestaurantView) deriving (Eq, Show, Typeable)
instance Initial RestaurantWrapperView where
initial = RestaurantWrapperView initial
mkRestaurantWrapperView = mkWebView $
\vid (RestaurantWrapperView _) ->
do { restaurantView <- mkRestaurantView
; return $ RestaurantWrapperView restaurantView
}
instance Presentable RestaurantWrapperView where
present (RestaurantWrapperView fv) =
mkClassDiv "RestaurantWrapperParent" $ mkPage [] $ mkClassDiv "RestaurantWrapperView" $ present fv
instance Storeable Database RestaurantWrapperView where
data RestaurantView =
RestaurantView (Maybe Date) (Int,Int) (Widget (Button Database)) (Widget (Button Database))
[[(WV CalendarDayView,String, Widget (EditAction Database))]] (WV DayView) (WV HourView) (WV ReservationView) String
deriving (Eq, Show, Typeable)
instance Initial RestaurantView where
initial = RestaurantView initial (initial,initial) initial initial [] initial initial initial initial
modifyViewedDate :: ((Int,Int) -> (Int,Int)) -> RestaurantView -> RestaurantView
modifyViewedDate f (RestaurantView d my lb nb weeks dayView hourView reservationView script) =
RestaurantView d (f my) lb nb weeks dayView hourView reservationView script
mkRestaurantView = mkWebView $
\vid (RestaurantView oldMSelectedDate viewedMonthYear' _ _ _ _ _ _ _) ->
do { clockTime <- liftIO getClockTime
; ct <- liftIO $ toCalendarTime clockTime
; let today@(_, currentMonth, currentYear) = dateFromCalendarTime ct
now = (ctHour ct, ctMin ct)
viewedMonthYear@(viewedMonth,viewedYear) = if viewedMonthYear'==(0,0) then (currentMonth, currentYear) else viewedMonthYear'
(lastMonth, lastMonthYear) = decreaseMonth viewedMonthYear
(nextMonth, nextMonthYear) = increaseMonth viewedMonthYear
nrOfDaysInLastMonth = gregorianMonthLength (fromIntegral lastMonthYear) lastMonth
nrOfDaysInThisMonth = gregorianMonthLength (fromIntegral viewedYear) viewedMonth
firstDayOfMonth = weekdayForDate (1, viewedMonth, viewedYear)
; let daysOfLastMonth = reverse $ take (firstDayOfMonth-1) [nrOfDaysInLastMonth,nrOfDaysInLastMonth-1..]
; let daysOfThisMonth = [1..nrOfDaysInThisMonth]
; let daysOfNextMonth = [1..]
; let calendarDaysOfLastMonth = [(d,lastMonth, lastMonthYear) | d <- daysOfLastMonth]
; let calendarDaysOfThisMonth = [(d,viewedMonth, viewedYear) | d <- daysOfThisMonth]
; let calendarDaysOfNextMonth = [(d,nextMonth, nextMonthYear) | d <- daysOfNextMonth]
; let calendarDays = take (7*6) $ calendarDaysOfLastMonth ++ calendarDaysOfThisMonth ++ calendarDaysOfNextMonth
; let selectScripts = [jsCallFunction vid "selectDay" [show i]| i <- [0..length calendarDays -1]]
; selects <- mapM (selectDateEdit vid) calendarDays
; reservations <- fmap Map.elems $ withDb $ \db -> allReservations db
; -- hack
; let mSelectedDate =
case oldMSelectedDate of
Just selectedDate -> oldMSelectedDate
Nothing -> Just today
; let calendarDayViewForDate date@(_,m,_) = mkCalendarDayView date (Just date==mSelectedDate) (date==today) (m==viewedMonth) $
[r | r@(Reservation _ d _ _ _ _) <- reservations, date==d]
; calendarDayViews <- mapM calendarDayViewForDate calendarDays
; let weeks = daysToWeeks $ zip3 calendarDayViews selectScripts selects
; let reservationsSelectedDay = filter ((==mSelectedDate). Just . date) reservations
; lastButton <- mkButton (showMonth lastMonth) True $ viewEdit vid $ modifyViewedDate decreaseMonth
; nextButton <- mkButton (showMonth nextMonth) True $ viewEdit vid $ modifyViewedDate increaseMonth
; reservationView <- mkReservationView vid
; hourView <- mkHourView vid (getViewId reservationView) []
; dayView <- mkDayView vid (getViewId hourView) reservationsSelectedDay
; return $ RestaurantView mSelectedDate (viewedMonth, viewedYear) lastButton nextButton weeks dayView hourView reservationView $ jsScript
[ {-"console.log(\"restaurant script\")"
,-} jsFunction vid "load" []
[ {-jsLog "'Load restaurant view'" -- TODO: in future version that is completely dynamic, check for selectedDayObj == null
,-} jsIfElse (jsVar vid "selectedDayObj"++".selectedDate && "++jsVar vid "selectedHourIx" ++"!=null")
[ "$('#betweenPlaceholder').text('Reservations on '+"++ jsVar vid "selectedDayObj"++".selectedDate.day+' '+"++ jsVar vid "selectedDayObj"++".selectedDate.month" ++
"+' between '+("++jsVar vid "selectedHourIx"++"+18)+'h and '+("++jsVar vid "selectedHourIx"++"+18+1)+'h')"
]
[ "$('#betweenPlaceholder').html(' ')"
]
, jsFor "i=0; i<6*7; i++" -- TODO: hard coded, not nice, is there a length we can use?
[ "$('#calDayView_'+i).css('background-color',("++jsVar vid "selectedDayIx"++"==i)?'"++htmlColor selectedDayColor++"'"++
":'"++htmlColor dayColor++"')"
]
, jsCallFunction (getViewId dayView) "load" []
]
, jsFunction vid "selectDay" ["i"]
[ jsAssignVar vid "selectedDayIx" "i"
, jsAssignVar vid "selectedHourIx" "null"
, jsAssignVar vid "selectedReservationIx" "null"
, jsCallFunction vid "load" []
]
, jsDeclareVar vid "selectedDayIx" "null" -- null is no selection
, jsDeclareVar vid "selectedHourIx" "null" -- null is no selection
, jsDeclareVar vid "selectedReservationIx" "null" -- null is no selection
, jsAssignVar vid "selectedDayIx" $ case mSelectedDate of
Nothing -> "null"
Just dt -> case elemIndex dt calendarDays of
Nothing -> "null"
Just i -> show i
, jsAssignVar vid "selectedDayObj" (mkDay mSelectedDate reservationsSelectedDay)
, jsDeclareVar vid "selectedHourObj" "null" -- null is no selection
, jsDeclareVar vid "selectedReservationObj" "null" -- null is no selection
, jsAssignVar vid "selectedHourIx" (let resHours = sort $ map (fst . time) $ filter ((\d -> Just d ==mSelectedDate) . date) reservations
in if null resHours then "0" else show $ head resHours - 18)
, jsAssignVar vid "selectedReservationIx" "0"
, jsCallFunction vid "load" []
]
}
where selectDateEdit vid d = mkEditAction $ viewEdit vid $
\(RestaurantView _ my lb nb weeks dayView hourView reservationView script) ->
RestaurantView (Just d) my lb nb weeks dayView hourView reservationView script
{-
[ { hourEntry: nrOfRes(nrOfPeople)
, reservations: [{listEntry:name+nr reservation:{name: nrOfPeople: .. }]
} ]
-}
mkDay mSelectedDate reservationsDay =
mkJson [("selectedDate", case mSelectedDate of
Nothing -> "null"
Just (d,m,y) -> mkJson [("day",show d),("month",show $ showMonth m)]
)
,("hours", jsArr [ let reservationsHour = filter ((==hr). fst . time) reservationsDay
nrOfReservations = length reservationsHour
nrOfPeopleInHour = sum $ map nrOfPeople reservationsHour
in mkJson [ ("hourEntry", show $ if nrOfReservations == 0 then "" else show nrOfReservations++" ("++ show nrOfPeopleInHour ++")")
, ("reservations", jsArr $ mkHour reservationsHour)]
| hr <- [18..24]]
)]
mkHour reservationsHour = [ mkJson [ ("reservationEntry", show $ showTime (time res)++" - "++
name res ++ " ("++show (nrOfPeople res)++")")
, ("reservation",mkReservation res)
]
| res <- reservationsHour ]
mkReservation (Reservation rid date time name nrOfPeople comment) = mkJson [ ("reservationId", show $ show rid), ("date",show (showDate date)), ("time", show (showTime time))
, ("name",show name), ("nrOfPeople", show nrOfPeople),("comment",show comment)]
{- day: mark today
mark different months, mark appointments
-}
instance Presentable RestaurantView where
present (RestaurantView mSelectedDate (currentMonth, currentYear) lastButton nextButton weeks dayView hourView reservationView script) =
with [ style "font-family:arial", class_ "RestaurantView" ] $
(vList $
[ mkClassDiv "CalendarHeader" $
xp $ row [ h $ present lastButton
, flexSpace
, h $ withStyle "font-weight:bold" $ toHtml $ showMonth currentMonth ++ " "++show currentYear
, flexSpace
, h $ present nextButton
]
, vSpace 5
, mkTableEx [cellpadding "0", cellspacing "0", style "border-collapse:collapse; text-align:center"] [] [style "border: 1px solid #909090"]
(header :
[ [ ([{- withEditActionAttr selectionAction-} strAttr "onClick" $ "addSpinner('hourView');"++ -- todo refs are hardcoded!
selectScript++
";queueCommand('PerformEditActionC ("++show (getViewId selectionAction)++") []')"]
, with [id_ $ toValue $ "calDayView_"++show (i*7+j)] $ present dayView)
| (j,(dayView, selectScript, selectionAction)) <- zip [0..] week]
| (i,week) <- zip [0..] weeks ]
)
] ++
[ present dayView
, vSpace 15
, withStyle "font-size:80%" $
with [id_ "betweenPlaceholder"] "uninitialized 'between' placeholder"
, vSpace 6
, present hourView
, vSpace 15
, present reservationView
]) +++ mkScript script
where header = [ ([], toHtml $ showShortDay d) | d <- [1..7] ]
instance Storeable Database RestaurantView where
-- CalendarDay ----------------------------------------------------------------------
data CalendarDayView =
CalendarDayView Date Bool Bool Bool [Reservation]
deriving (Eq, Show, Typeable)
instance Initial CalendarDayView where
initial = CalendarDayView (initial, initial, initial) initial initial initial initial
mkCalendarDayView date isSelected isToday isThisMonth reservations = mkWebView $
\vid (CalendarDayView _ _ _ _ _) ->
do { return $ CalendarDayView date isSelected isToday isThisMonth reservations
}
instance Presentable CalendarDayView where
present (CalendarDayView date@(day, month, year) isSelected isToday isThisMonth reservations) =
-- we use a margin of 3 together with the varying cell background to show today
-- doing this with borders is awkward as they resize the table
conditionallyBoxed isToday 2 (htmlColor todayColor) $
mkTableEx [ width "44px", height "36", cellpadding "0", cellspacing "0"
, style $ "margin:2px"] [] []
[[ ([valign "top"] ++ if isThisMonth then [] else [style "color: #808080"], toHtml (show day)) ]
,[ ([style "font-size:80%; color:#0000ff"], if not $ null reservations then toHtml $ show (length reservations) ++ " (" ++ show (sum $ map nrOfPeople reservations)++")" else nbsp) ]
]
-- TODO: make Rgb for standard html colors, make rgbH for (rgbH 0xffffff)
-- check slow down after running for a while
conditionallyBoxed cond width color elt =
if cond then div_!*[style $ "border:solid; border-color:"++color++"; border-width:"++show width++"px;"] << elt
else div_!*[style $ "padding:"++show width++"px;"] << elt
instance Storeable Database CalendarDayView where
-----------------------------------------------------------------------------
data DayView =
DayView [String] [Reservation] String
deriving (Eq, Show, Typeable)
instance Initial DayView where
initial = DayView initial initial initial
-- the bar with hours under the calendar
mkDayView :: ViewId -> ViewId -> [Reservation] -> WebViewM Database (WV DayView)
mkDayView restaurantViewId hourViewId dayReservations = mkWebView $
\vid (DayView _ _ _) ->
do { let selectHourActions = map (selectHourEdit vid) [18..24]
; return $ DayView selectHourActions dayReservations $
jsScript [ jsFunction vid "load" [] $
let selDayObj = jsVar restaurantViewId "selectedDayObj"
in [ {-jsLog "'Load day view called'"
,-} jsIfElse selDayObj
[ -- don't have to load for now, since view is presented by server
-- show selected hour
jsFor ("i=0; i<"++selDayObj++".hours.length; i++")
[ "$('#hourOfDayView_'+i).css('background-color',("++jsVar restaurantViewId "selectedHourIx"++"==i)?'"++htmlColor selectedHourColor++"'"++
":'"++htmlColor hourColor++"')"
] -- todo: reference to hourOfDay is hard coded
{-, jsLog $ "'SelectedHourIx is '+"++ jsVar restaurantViewId "selectedHourIx"-}
, jsIfElse (jsVar restaurantViewId "selectedHourIx"++"!=null")
[ jsAssignVar restaurantViewId "selectedHourObj" $ selDayObj ++".hours["++jsVar restaurantViewId "selectedHourIx"++"]"
]
[ jsAssignVar restaurantViewId "selectedHourObj" "null" ]
]
[] -- will not occur now, since day is given by server (if it occurs, also set selectedHourObj to null, see mkHourView)
, jsCallFunction hourViewId "load" []
{-
, jsLog $jsVar restaurantViewId "selectedHourIx"
, jsIf (jsVar restaurantViewId "selectedHourIx"++"!=null")
[ "var hourObject = "++jsVar restaurantViewId "hourObjects"++"["++jsVar restaurantViewId "selectedHourIx"++"]"
, "console.log('Hour entry is'+hourObject.hourEntry)"
, jsFor "i=0; i<hourObject.reservations.length; i++"
[ "console.log('item:'+hourObject.reservations[i].reservationEntry)" ]
] -}
]
]
}
where selectHourEdit dayViewId h = jsAssignVar restaurantViewId "selectedHourIx" (show $ h-18) ++";"++
jsAssignVar restaurantViewId "selectedReservationIx" "0" ++";"++
jsCallFunction restaurantViewId "load" [] -- because the label changes, we need to load restaurant view
instance Presentable DayView where
present (DayView selectHourActions dayReservations script) =
mkTableEx [width "100%", cellpadding "0", cellspacing "0", style "border-collapse:collapse; font-size:80%"] [] []
[[ ([id_ . toValue $ "hourOfDayView_"++show (hr-18)
, strAttr "onClick" sa -- todo: don't like this onClick here
, style $ "border: 1px solid #909090; background-color: #d0d0d0"]
, presentHour hr) | (sa,hr) <- zip selectHourActions [18..24] ]] +++ mkScript script
where presentHour hr = --withBgColor (Rgb 255 255 0) $
vListEx [width "48px"] -- needs to be smaller than alotted hour cell, but larger than width of "xx(xx)"
[ toHtml $ show hr++"h"
, withStyle "font-size:80%; text-align:center; color:#0000ff" $
let ressAtHr = filter ((==hr) . fst . time) dayReservations
in if not $ null ressAtHr then toHtml $ show (length ressAtHr) ++ " (" ++ show (sum $ map nrOfPeople ressAtHr)++")" else nbsp
]
instance Storeable Database DayView where
-----------------------------------------------------------------------------
data HourView =
HourView[String] [Reservation] String
deriving (Eq, Show, Typeable)
instance Initial HourView where
initial = HourView initial initial initial
-- the list of reservations for a certain hour
mkHourView :: ViewId -> ViewId -> [Reservation] -> WebViewM Database (WV HourView)
mkHourView restaurantViewId reservationViewId hourReservations = mkWebView $
\vid (HourView _ _ _) ->
do { let selectReservationActions = map (selectReservationEdit vid) [0..19]
; return $ HourView selectReservationActions hourReservations $
jsScript [ jsFunction vid "load" [] $
let selHourObj = jsVar restaurantViewId "selectedHourObj"
in [ {-"console.log('Load hour view called')"
, jsLog $ "'SelectedHourIx is '+"++ jsVar restaurantViewId "selectedHourIx"
, jsLog $ "'SelectedHour is '+"++ selHourObj
,-} jsIfElse selHourObj
[ -- jsLog $ "'Hour object not null'",
-- if selection is below reservation list make the selectedReservationIx null
jsIf (jsVar restaurantViewId "selectedReservationIx"++">="++selHourObj++".reservations.length")
[ jsAssignVar restaurantViewId "selectedReservationIx" "null" ]
-- load hour and show selected reservation
, jsFor ("i=0; i<"++selHourObj++".reservations.length; i++")
[ {-"console.log('item:'+"++selHourObj++".reservations[i].reservationEntry)"
,-} "$('#reservationLine_'+i).css('background-color',("++jsVar restaurantViewId "selectedReservationIx"++"==i)?'"++htmlColor selectedReservationColor++"'"++
":'"++htmlColor reservationColor++"')"
, "$('#reservationEntry_'+i).text("++selHourObj++".reservations[i].reservationEntry)"
]
-- clear the other entries
, jsFor ("i="++selHourObj++".reservations.length; i<20; i++")
[ "$('#reservationEntry_'+i).text('')"
, "$('#reservationLine_'+i).css('background-color','"++htmlColor reservationColor++"')"
]
, jsIfElse (jsVar restaurantViewId "selectedReservationIx"++"!=null")
[ jsAssignVar restaurantViewId "selectedReservationObj" $ selHourObj ++".reservations["++jsVar restaurantViewId "selectedReservationIx"++"].reservation"
]
[ jsAssignVar restaurantViewId "selectedReservationObj" "null" ]
]
-- empty reservation list, set selectedReservationObj to nul
[ {-jsLog "'Hour object null'"
,-} jsFor ("i=0; i<20; i++") -- duplicated code
[ "$('#reservationEntry_'+i).text('')"
, "$('#reservationLine_'+i).css('background-color','"++htmlColor reservationColor++"')"
]
, jsAssignVar restaurantViewId "selectedReservationObj" "null"
]
, jsCallFunction reservationViewId "load" []
]
]
}
where selectReservationEdit hourViewId i = jsAssignVar restaurantViewId "selectedReservationIx" (show $ i) ++";"++
jsCallFunction hourViewId "load" []
instance Presentable HourView where
present (HourView selectReservationActions hourReservations script) =
(with [id_ "hourView"] $ -- in separate div, because spinners on scrolling elements cause scrollbars to be shown
boxedEx 1 0 $ withStyle "height:90px;overflow:auto" $
mkTableEx [width "100%", cellpadding "0", cellspacing "0", style "border-collapse:collapse"] [] [] $
[ [ ([id_ . toValue $ "reservationLine_"++show i
, strAttr "onClick" sa -- todo: don't like this onClick here
, style $ "border: 1px solid #909090"]
, hList [nbsp, with [id_ . toValue $ "reservationEntry_"++show i] $ "reservationEntry"]) ]
| (i,sa) <- zip [0..] selectReservationActions
]) +++ mkScript script
instance Storeable Database HourView where
-----------------------------------------------------------------------------
data ReservationView =
ReservationView (Widget (Button Database)) (Widget (EditAction Database)) String
deriving (Eq, Show, Typeable)
instance Initial ReservationView where
initial = ReservationView initial initial initial
mkReservationView restaurantViewId = mkWebView $
\vid (ReservationView _ _ _) ->
do { removeButton <- mkButton "x" True $ return ()
; db <- getDb
; removeAction <- mkEditActionEx $ \[reservationId] ->
let resId = read reservationId
in case Map.lookup resId (allReservations db) of
Nothing -> return ()
Just res -> confirmEdit ("Are you sure you wish to delete the reservation for "++name res++" at "++showTime (time res)++"?") $
modifyDb $ removeReservation resId
; return $ ReservationView removeButton removeAction $ jsScript
[ jsFunction vid "load" [] $
let selRes = jsVar restaurantViewId "selectedReservationObj"
in [ {-"console.log(\"Load reservation view called\")"
,-} onClick removeButton $ callServerEditAction removeAction [jsVar restaurantViewId "selectedReservationObj" ++".reservationId"]
, jsIfElse selRes
[ {-"console.log(\"date\"+"++selRes++".date)"
, "console.log(\"time\"+"++selRes++".time)"
,-} "$(\"#reservationView\").css(\"color\",\"black\")"
, jsGetElementByIdRef (widgetGetViewRef removeButton)++".disabled = false"
, "$(\"#dateField\").text("++selRes++".date)"
, "$(\"#nameField\").text("++selRes++".name)"
, "$(\"#timeField\").text("++selRes++".time)"
, "$(\"#nrOfPeopleField\").text("++selRes++".nrOfPeople)"
, "$(\"#commentField\").text("++selRes++".comment)"
]
[ "$(\"#reservationView\").css(\"color\",\"grey\")"
, jsGetElementByIdRef (widgetGetViewRef removeButton)++".disabled = true"
, "$(\"#dateField\").text(\"\")"
, "$(\"#nameField\").text(\"\")"
, "$(\"#timeField\").text(\"\")"
, "$(\"#nrOfPeopleField\").text(\"\")"
, "$(\"#commentField\").text(\"\")"
-- , "console.log(\"not set\")"
]
]
]
}
-- todo comment has hard-coded width. make constant for this
instance Presentable ReservationView where
present (ReservationView removeButton _ script) = (withStyle "background-color:#f0f0f0" $ boxed $
vListEx [ id_ "reservationView"]
[ hListEx [width "100%"] [ hList [ "Reservation date: ",nbsp
, with [colorAttr reservationColor] $ with [id_ "dateField"] $ noHtml ]
, with [align "right"] $ mkClassDiv "RemoveButton" $ present removeButton]
, hList [ "Time:",nbsp, with [colorAttr reservationColor] $ with [id_ "timeField"] $ noHtml]
, hList [ "Name:",nbsp, with [colorAttr reservationColor] $ with [id_ "nameField"] $ noHtml]
, hList [ "Nr. of people:",nbsp, with [colorAttr reservationColor] $ with [id_ "nrOfPeopleField"] $ noHtml ]
, "Comment:"
, boxedEx 1 0 $ withStyle ("padding-left:4px;height:70px; width:356px; overflow:auto; color:" ++ htmlColor reservationColor) $ with [id_ "commentField"] $
noHtml
]) +++ mkScript script
where reservationColor = Rgb 0x00 0x00 0xff
instance Storeable Database ReservationView where
instance MapWebView Database Reservation
deriveMapWebViewDb ''Database ''DayView
deriveMapWebViewDb ''Database ''HourView
deriveMapWebViewDb ''Database ''CalendarDayView
deriveMapWebViewDb ''Database ''ReservationView
deriveMapWebViewDb ''Database ''RestaurantView
deriveMapWebViewDb ''Database ''RestaurantWrapperView
deriveMapWebViewDb ''Database ''MainView
deriveMapWebViewDb ''Database ''TestView1
deriveMapWebViewDb ''Database ''TestView2
{-
Bug that seems to add views with number 23 all the time (probably the date)
Redirect webviews.oblomov.com doesn't work in iframe, figure out why not.
Make sure reservations are sorted on time
Fix overflows when many reservations on one day are made
Please enter your name
Please enter number of people
Please select a date
Please select a time (red is not available)
Enter a comment or (confirm reservation)
add time that reservation was made
-- nice way to access db in EditM (now done with (_,_,db,_,_) <- get)
-- TODO accessing text fields and getting a reuse using getStrVal and getTextContents) is hacky and error prone
-- Figure out a general way to handle init and reuse
-- e.g. for a name field, if we have an initial name, when do we set it? checking for "" is not possible, as the user may
-- clear the name, which should not cause init
-- Init and reuse on non-widgets is also hacky, see mSelectedDate in clientView
-- Button style cannot be changed by parent element, so we need a way to specify the style at the button
Right now, this is hacked in by adding a style element to button, which causes part of the presentation to be
specified outside the present instance.
Find a good way for this, and see what other widgets have the problem. Maybe a combination of styles is possible?
Or maybe just have buttons always be max size and require them to be made minimal on presentation?
-- todo: check setting selections (date on today is now a hack, whole calendar should be based on selected rather than today)
-- currently res selection is done on present and hour selection is done on init and change of selected Day
-- find a good mechanism to do these selections
-- todo: split restaurant view, check where selections should live
Ideas:
Maybe change background when nothing is selected (or foreground for reservation fields)
Hover!
Standard tables that have css stuff for alignment etc. so no need to specify styles for each td
-}
|
Oblosys/webviews
|
src/exec/Reservations/Main.hs
|
mit
| 34,173 | 1 | 27 | 10,157 | 6,808 | 3,508 | 3,300 | 401 | 6 |
--file KMC-haskell/graphFuncs.hs
--module for performing operations on graphs
module KMC.Graph
(
Infinitable(..)
, breadthSearch
, permute
, goodMappings
, confirmMappings
)
where
import qualified Data.Vector as V
import qualified Data.Vector.Mutable as MV
import qualified Data.List as L
import GHC.Prim
import qualified FIFO as F
import KMC.Types
import qualified KMC.Lattice as KL
import qualified KMC.States as KS
import Data.Maybe
import Debug.Trace
-- Type synonmys, maybe newtype works better
type DistArr = V.Vector (Infinitable Int)
type ColourArr = V.Vector Colour
type VMatrix a = V.Vector (V.Vector a)
-- data structures. Values for the search algorithm
data Colour = White | Grey | Black deriving(Eq,Show)
-- Infinite value for distances not calculated. Included
-- so searches under a distance d do not return unsearched
-- point. Avoids doing silly things with negative numbers
data Infinitable a = Inf | Reg a deriving(Eq, Show)
instance Ord a => Ord (Infinitable a) where
compare Inf Inf = EQ
compare Inf _ = GT
compare _ Inf = LT
compare (Reg a) (Reg b) = compare a b
--------------------
--Exported Functions
--------------------
--Breath first search until a target depth returning the indicies
--of the vertices within that depth form the source point
--MAIN
breadthSearch :: Lattice -> Int -> Int -> V.Vector Int
breadthSearch lattice s td =
let aL = lGraph lattice
cA = setColour (V.replicate (V.length aL) White) s Grey
dA = setDist (V.replicate (V.length aL) Inf ) s (Reg 0)
q = F.enqueue s F.empty
in whileBit lattice q cA dA td
--COMPONENT
--While the queue has stuff in it this calls itself recursively
whileBit :: Lattice -> F.FIFO Int -> ColourArr -> DistArr -> Int -> V.Vector Int
whileBit lattice q cA dA td =
let ((e:es),q') = F.remove 1 q
in case e of
Just u -> if (checkDist dA u) < Reg td
then
let nL = KL.getNeighbours lattice u
(cA',dA',q'') = ifBit nL cA dA u q'
in whileBit lattice q'' cA' dA' td
else whileBit lattice q' cA dA td
Nothing -> V.findIndices p cA
where p x = (x /= White)
--COMPONENT
--Assuming we are interested in the Nth node this adds it to the search
ifBit :: [Int] -> ColourArr -> DistArr -> Int -> F.FIFO Int
-> (ColourArr, DistArr, F.FIFO Int)
ifBit [] cA dA u q =
let cA' = setColour cA u Black
in (cA',dA,q)
ifBit nL@(n:nt) cA dA u q=
case checkColour cA n of
White ->
let cA' = setColour cA n Grey
du = checkDist dA u
dA' = setDist dA n (incInf du)
q' = F.enqueue n q
in ifBit nt cA' dA' u q'
_ -> ifBit nt cA dA u q
--MAIN
--Find all the permutation matricies of a given matrix m
--Used for subgraph isomorphisms in Ullmann's algorithm
--Returns a list of paths where the nth entry in a path is
--the index of the entry in the subgraph that maps to
--the nth member of the reaction graph
permute :: VMatrix Int -> [[Int]]
permute m = map reverse $ goForth [] emptyq (-1) [] m where
emptyq = V.replicate (V.length m) []
--COMPONENT
--Proceed a depth enqueing possibilities at that depth for testing
--or accept a complete path and test the next terminating sequence.
goForth :: [Int] -> V.Vector [Int] -> Int -> [[Int]] -> VMatrix Int -> [[Int]]
goForth path queue depth successfulPaths m =
let newDepth = depth+1
areOnes = V.toList $ V.findIndices (==1) $ m V.! newDepth
newQueue = writeQ queue newDepth areOnes
in case compare newDepth $ (V.length m) -1 of
GT -> let successfulPaths' = path : successfulPaths
in goNext (tail path) queue depth successfulPaths' m
_ -> goNext path newQueue newDepth successfulPaths m
--Is the index being considered unique to the sequence
decide path@(p:pt) queue depth sPs m =
case p `elem` pt of
True -> goNext pt queue depth sPs m
False -> goForth path queue depth sPs m
--Grab the next element for examination form the queue or
--goBack if this level is tested completely for the current path
goNext path queue depth sPs m =
let (e,q') = deQ queue depth
in case e of
Just e' -> decide (e':path) q' depth sPs m
Nothing -> goBack path q' depth sPs m
--Return one depth and consider the relevant element OR terminate
--returning the paths that were completed
goBack path queue depth sPs m =
let newDepth = depth -1
in case newDepth of
-1 -> sPs
_ -> goNext (tail path) queue newDepth sPs m
deQ queue depth = (e,q) where
(e,es) = takeFrom (queue V.! depth)
q = writeQ queue depth es
takeFrom [] = (Nothing, [])
takeFrom (x:xs) = (Just x, xs)
------------------
--Helper Functions
------------------
-- increments Infinitable ints
incInf :: Infinitable Int -> Infinitable Int
incInf (Reg x) = Reg (x+1)
-- make the initial colours array for an Adj List
mkColourArr :: AdjList -> ColourArr
mkColourArr adjList = V.replicate (V.length adjList) White
mkDistArr :: AdjList -> DistArr
mkDistArr adjList = V.replicate (V.length adjList) (Inf :: Infinitable Int)
--Fetch neighbours of the ith entry
checkColour :: ColourArr -> Int -> Colour
checkColour colourArr i = colourArr V.! i
setColour :: ColourArr -> Int -> Colour -> ColourArr
setColour colourArr i c= V.modify (\v -> MV.write v i c) colourArr
checkDist :: DistArr -> Int -> Infinitable Int
checkDist distArr i = distArr V.! i
setDist :: DistArr -> Int -> Infinitable Int -> DistArr
setDist distArr i d = V.modify (\v -> MV.write v i d) distArr
-- VMatrix helpers
mapOnAll :: (a -> b) -> VMatrix a -> VMatrix b
mapOnAll f matrix = V.map (V.map f) matrix
-- destructive update on row i with f
mapOnRow :: Int -> (a -> a) -> VMatrix a -> VMatrix a
mapOnRow i f matrix = V.modify ((\sv v -> MV.write v i sv) $ V.map f $ matrix V.! i) matrix
getColumn j matrix = V.map (V.! j) matrix
-- In place update of a Vector (FILO) at queue corresponding to depth
writeQ queue depth qs = V.modify (\v -> MV.write v depth qs) queue
-- WORKING
makeM :: Reaction -> Lattice -> VMatrix Int
makeM reaction lattice =
onlyOnes statesCheck degreeCheck where
statesCheck = tsdMat (iState reaction) (lState lattice)
degreeCheck = degMat (iGraph reaction) (lGraph lattice)
extractSubLattice :: Lattice -> V.Vector Int -> Lattice
extractSubLattice lat vs = Lattice subgraph subState V.empty V.empty where
vL = V.toList vs
subgraph = V.fromList $ cleanNeighbours vL $ KL.getManyNeighbours lat vL
subState = V.fromList $ KL.getManyState lat vL
dummyTimes = V.replicate (V.length subgraph) 0.0
--WARNING CHANGED 15-05-25 with types update
-- This is effectively a lookup table of(iLarge,iReaction)
-- it's actually a list of lookup tables for the possible
-- reactions.
mappings :: V.Vector Int -> [[Int]] -> V.Vector [(Int,Int)]
mappings v rMs = V.fromList $ map (flip zip [0..]) iLarge where
iLarge = map (map (v V.!)) rMs
cleanNeighbours :: [Int] -> [Neighbours] -> [Neighbours]
cleanNeighbours vertices adjLists = map (L.intersect vertices) adjLists
-- Crudely just making N matricies of 1 or 0 for passing/failing
-- the test. Then multiply elementwise to get the final m. Can be made
-- more efficient by carrying out expensive tests only on relevant entries
-- last
checkDegrees rG sG i j =
let degSG = length $ sG V.! j
degRG = length $ rG V.! i
in case compare degSG degRG of
LT -> 0
_ -> 1
-- Rows are entries in the reaction, columns are entries in the subgraph
degMat :: AdjList -> AdjList -> VMatrix Int
degMat aLrG aLsG =
V.generate rows (\i -> V.generate columns
(\j -> checkDegrees aLrG aLsG i j)) where
rows = V.length aLrG
columns = V.length aLsG
tsdCheck rG sG i j =
let tsdSG = sG V.! j
tsdRG = rG V.! i
in case tsdSG == tsdRG of
True -> 1
False -> 0
tsdMat :: StateArray -> StateArray -> VMatrix Int
tsdMat sArG sAsG =
V.generate rows (\i -> V.generate columns
(\j -> tsdCheck sArG sAsG i j)) where
rows = V.length sArG
columns = V.length sAsG
onlyOnes :: VMatrix Int -> VMatrix Int -> VMatrix Int
onlyOnes m1 m2 = zipVMwith (*) m1 m2
zipVMwith :: (a -> b -> c) -> (VMatrix a -> VMatrix b -> VMatrix c)
zipVMwith f = V.zipWith (V.zipWith f)
goodMappings :: Lattice -> Reaction -> Int -> V.Vector [(Int,Int)]
goodMappings lattice reaction source =
let targetD = (patternLevel reaction) V.! matchIndex
stateSource = KL.getState lattice source
(Just matchIndex) = V.findIndex (== stateSource) (iState reaction)
vertices = breadthSearch lattice source targetD
subLattice = extractSubLattice lattice vertices
m = makeM reaction subLattice
rawMaps = permute m
checkedMaps = pathCheck subLattice reaction vertices rawMaps
latSites = map snd $ KS.entityLocations (lState lattice)
reacSites = map snd $ KS.entityLocations (iState reaction)
validMaps = confirmMappings latSites reacSites checkedMaps
in mappings vertices validMaps
-- Test to see if for a given map (Vr->Vl) there exists (Er->El)
pathCheck l r vertices maps =
let verts = V.toList vertices
rNeighbours = V.toList $ iGraph r
neighbours = lGraph l
iL_iS_table = zip verts [0..] -- for converting neighbours in subgraph
subNeighbours = V.map (map (flip lookup iL_iS_table)) neighbours
-- V [Maybe Int]]
edgeMaps = map (map (subNeighbours V.!)) maps
iR_iS_table = map (flip zip [0..]) maps
maybeEdges x y = map (map ((=<<) (flip lookup x))) y
reactionEdges = map (map catMaybes) $ zipWith maybeEdges iR_iS_table edgeMaps -- contains neighbours in terms of R
test1 = map (testCondensor rNeighbours) reactionEdges
bleh = zipWith testSuccessCheck test1 maps
in filter (not.null) bleh
-- Need to make sure mapped points are connected. Also Oxygen returns valid maaps no idea why not being mapped at all.
subsetTest x y = map (\a -> map (a `subsetOf`) y) x
testCondensor x y = L.and $ L.foldl'
(\acc a -> zipWith (||) acc a) [False,False ..] $ subsetTest x y
testSuccessCheck b v
| b == True = v
| otherwise = []
xs `subsetOf` ys = null $ filter (not . (`elem` ys)) xs
rToS :: [Int] -> [(Int,Int)] -> [Maybe Int]
rToS r_sites lUL = map (flip lookup lUL) r_sites
cleanInvalidMaps :: [Maybe Int] -> [Int]
cleanInvalidMaps rs
| (Nothing `elem` rs) == True = []
| otherwise = map (\(Just x) -> x) rs
-- I don't actually know what this does
confirmMappings :: [[Int]] -> [[Int]] -> [[Int]] -> [[Int]]
confirmMappings _ _ [] = []
confirmMappings latSites reacSites (rM:rMs) =
let lUL = zip [0..] rM
rInTermsOfS = map (cleanInvalidMaps . flip rToS lUL) reacSites
-- This mess is for reducing checking all the mappings to a single T/F
lowFold l = L.foldl' -- changed high to and I think that's right
(\acc a -> (|| acc).(== l).(L.intersect l) $ a) False
highFold list = L.foldl'
(\acc x -> (&& acc).(flip lowFold list) $ x) True
in case (highFold latSites rInTermsOfS) of
True -> rM : confirmMappings latSites reacSites rMs
False -> confirmMappings latSites reacSites rMs
|
NaevaTheCat/KMC-haskell
|
src/KMC/Graph.hs
|
mit
| 11,760 | 3 | 16 | 3,131 | 3,721 | 1,936 | 1,785 | 206 | 3 |
module Haskrypto.Modular(
Modular(..),
inverse,
power,
extendedEuclidean,
randomNumber,
genRandomFermatPrime,
fermatPrimalityTest,
findFermatPrime,
nextCoprime,
gcd',
squareRoot,
modular,
nextSafePrime,
legendreSymbol,
isSafeFermatPrime
)where
import System.Random
import Data.Bool
import Debug.Trace
import GHC.Exception
import GHC.Stack
import Data.List
-- HCN -> Highly Composite Number
hcn_for_fermat_test = 720720
data Modular t = Modular{
val :: t,
field :: t
}
modular :: (Integral t) => t -> t -> Modular t
modular v' m = Modular v m
where
v = mod v' m
instance (Show t) => Show (Modular t) where
show (Modular a n) = "(" ++ show a ++ " mod " ++ show n ++")"
instance (Eq t) => Eq (Modular t) where
(Modular a _) == (Modular b _) = a == b
(Modular a _) /= (Modular b _) = a /= b
instance (Ord t) => Ord (Modular t) where
(Modular a _) `compare` (Modular b _) = a `compare` b
instance (Integral t, Ord t) => Num (Modular t) where
(Modular a n) + (Modular b m) =
if m == n
then
(modular ((a + b) `mod` n) n)
else
error "Operating numbers with diferent modulus"
(Modular a n) - (Modular b m) =
if m==n
then
(modular ((a + n- b)`mod` n) n)
else
error "Operating numbers with diferent modulus"
(Modular a n) * (Modular b m) =
if m==n
then
(modular ((a * b)`mod` n) n)
else
error "Operating numbers with diferent modulus"
abs m = m
signum m = 1
instance (Integral t, Ord t) => Fractional (Modular t) where
a / x = a * (inverse x)
fromRational m = error "Can't create a modular from rational"
inverse :: (Integral t) => Modular t -> Modular t
inverse (Modular a n) =
if gcd' == 1
then
(modular inverse_a n)
else
error $ "GCD is not 1"
where
(gcd', inverse_a, _) = extendedEuclidean a n
extendedEuclidean :: (Integral a) => a -> a -> (a,a,a)
extendedEuclidean a 0 = (a, 1, 0)
extendedEuclidean a b = (d, y, x - (a`div`b) * y) where
(d, x, y) = extendedEuclidean b $ mod a b
power :: (Integral a) => (Modular a) -> a -> (Modular a)
power (Modular _ n) 0 = (Modular 1 n)
power (Modular a n) 1 = (Modular a n)
power a p = ap
where
ap = x * x * (power a (mod p 2))
x = power a $ div p 2
fermatPrimalityTest :: Integer -> Bool
fermatPrimalityTest p = power (modular a p) p == modular a p
where a = hcn_for_fermat_test
genRandomFermatPrime n gen = findFermatPrime $ randomNumber n gen
findFermatPrime n
| even n = findFermatPrime $ n + 1
| otherwise =
if fermatPrimalityTest n
then
n
else
findFermatPrime (n + 2)
randomNumber :: Int -> StdGen -> Integer
randomNumber n gen = read $ take n $ randomRs ('0', '9') gen :: Integer
nextCoprime e n = if gcd' e n == 1 then e else nextCoprime (e + 1) n
gcd' a 0 = a
gcd' a b = gcd' b $ mod a b
isSafeFermatPrime :: Integer -> Bool
isSafeFermatPrime p = fermatPrimalityTest p && fermatPrimalityTest q
where q = (p - 1) `div` 2
nextSafePrime :: Integer -> Integer
nextSafePrime a
| a `mod` 2 == 0 = nextSafePrime' (a+1)
| otherwise = nextSafePrime' a
nextSafePrime' :: Integer -> Integer
nextSafePrime' a
| isSafeFermatPrime (2*a+1) = a
| otherwise = nextSafePrime' (a+2) `debug` (show a)
where debug = flip trace
squareRoot :: Modular Integer -> Modular Integer
squareRoot m@(Modular y p)
| isSafeFermatPrime p = comprobate_sqrt root m
| otherwise = error "I don't know how to calculate it"
where
a = val $ inverse (Modular 2 q)
q = (p - 1) `div` 2
root = power m a
legendreSymbol :: Integer -> Integer -> Integer
legendreSymbol a p = if (val $ (Modular a p) ^ (div p 2)) == 1
then (-1)
else 1
comprobate_sqrt y1 y2
| y1 * y1 == y2 = y1
| otherwise = error $ "Error while calculating squareRoot of " ++ show y1
|
TachoMex/Haskrypto
|
src/Haskrypto/Modular.hs
|
mit
| 4,163 | 0 | 13 | 1,298 | 1,664 | 865 | 799 | 111 | 2 |
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE OverloadedStrings #-}
module Update where
import Control.Exception
import Control.Applicative
import Control.Monad
import Control.Monad.IO.Class
import Control.Monad.Catch
import Data.Maybe
import Data.Conduit
import qualified Data.Conduit.List as CL
import qualified Data.HashMap.Strict as H
import Text.XML.Pugi
import qualified Data.ByteString.Char8 as S
import Network.HTTP.Conduit as HTTP
import Network.HTTP.Types
import qualified Data.Aeson as JSON
import qualified Data.Text.Encoding as T
import qualified Data.Text.Lazy as TL
import qualified Data.Text.Lazy.Encoding as TL
import qualified Data.ByteString.Lazy as L
import qualified StorePackage
import Data.List
import Data.Function
import Network.HTTP.Date
import qualified Distribution.PackageDescription as D
import qualified Distribution.PackageDescription.Configuration as D
import qualified Distribution.PackageDescription.Parse as D
import Data.Time
import System.Locale
data Recent = Recent
{ recentName :: S.ByteString
, recentVersion :: S.ByteString
, recentTime :: UTCTime
} deriving (Show, Ord, Eq)
parseRecents :: Document -> [Recent]
parseRecents = map maximum . groupBy ((==) `on` recentName) . sort .
mapMaybe getElem . nodeSetToList . selectNodes [xpath|/rss/channel/item|]
where
getElem (Left n) = do
(pkg, v) <- S.break (== ' ') . text <$> child "title" n
pub <- child "pubDate" n >>= parseTime defaultTimeLocale rfc822DateFormat . S.unpack . text
guard . not $ S.null v
return $ Recent pkg (S.tail v) pub
getElem _ = Nothing
newtype Version = Version { unVersion :: S.ByteString }
instance JSON.FromJSON Version where
parseJSON (JSON.Object o) = o JSON..: "fields" >>= \case
(JSON.Object o') -> o' JSON..: "version" >>= \case
v:_ -> return $ Version (T.encodeUtf8 v)
_ -> mzero
_ -> mzero
parseJSON _ = mzero
checkStatusP :: (Int -> Bool) -> Status -> RequestHeaders -> CookieJar -> Maybe SomeException
checkStatusP p s@(Status sci _) hs j =
if p sci
then Nothing
else Just $ toException $ StatusCodeException s hs j
getStoredVersion :: MonadIO m => Request -> S.ByteString -> Manager -> m (Maybe S.ByteString)
getStoredVersion req pkg mgr = do
res <- httpLbs req
{ HTTP.path = "/find_hackage/packages/" `S.append` pkg
, queryString = "?fields=version"
, checkStatus = checkStatusP (\c -> (200 <= c && c < 300) || c == 404)
} mgr
if responseStatus res == status404
then return Nothing
else return . fmap unVersion $ JSON.decode (responseBody res)
isNewer :: MonadIO m => Request -> Recent -> Manager -> m Bool
isNewer req (Recent pkg v _) mgr = maybe True (v /=) `liftM` getStoredVersion req pkg mgr
fetchCabalFile :: MonadIO m => Request -> Manager -> Recent -> m (Maybe D.PackageDescription)
fetchCabalFile req mgr (Recent pkg ver _) = do
res <- httpLbs req { HTTP.path = S.concat ["/package/", pkg, "-", ver, "/", pkg, ".cabal"] } mgr
return $ case D.parsePackageDescription (TL.unpack . TL.decodeUtf8 $ responseBody res) of
D.ParseOk _ pd -> Just (D.flattenPackageDescription pd)
_ -> Nothing
updater :: (Functor m, MonadThrow m, MonadIO m) => Maybe HTTPDate -> Request -> Manager -> m [(D.PackageDescription, UTCTime)]
updater snc baseReq mgr = do
hackage <- parseUrl "http://hackage.haskell.org/packages/recent.rss"
rss <- flip httpLbs mgr $ case snc of
Nothing -> hackage
Just t -> hackage { requestHeaders = ("If-Modified-Since", formatHTTPDate t) : requestHeaders hackage
, checkStatus = checkStatusP (\c -> (200 <= c && c < 300) || c == 304)
}
if responseStatus rss == status304
then return []
else case parse def $ (L.toStrict $ responseBody rss) of
Right doc -> do
upds <- filterM (\r -> isNewer baseReq r mgr) $ parseRecents doc
pds <- catMaybes `liftM` mapM (\r -> fmap (,recentTime r) <$> fetchCabalFile hackage mgr r) upds
CL.sourceList pds $$ StorePackage.sinkStoreElasticsearch 100 False H.empty baseReq mgr
return pds
Left _ -> return []
|
philopon/find-hackage
|
src/Update.hs
|
mit
| 4,447 | 0 | 22 | 1,055 | 1,404 | 753 | 651 | 94 | 4 |
module H99.Q11to20
( tests11to20
) where
import Test.Tasty
import Test.Tasty.HUnit as HU
import H99.Q1to10 (encode)
{-| Problem 11.
Modify the result of problem 10 in such a way that if an element has no duplicates it is
simply copied into the result list. Only elements with duplicates are transferred as (N E) lists.
-}
data EncodedElem a = Single a | Multiple Int a deriving (Show, Eq)
encodeModified :: (Eq a) => [a] -> [EncodedElem a]
encodeModified xs = map (\(c, x) -> if c > 1 then Multiple c x else Single x) $ encode xs
problem11 :: TestTree
problem11 = testGroup "Problem 11" [ testCase "encodeModified \"aaaabccaadeeee\"" $
encodeModified "aaaabccaadeeee" @?= [Multiple 4 'a',Single 'b',Multiple 2 'c',
Multiple 2 'a',Single 'd',Multiple 4 'e']
, testCase "encodeModified []" $
encodeModified ([] :: [Int]) @?= []
]
tests11to20 :: TestTree
tests11to20 = testGroup "Q11 - 20"
[ problem11 ]
|
izmailoff/haskell-h99
|
src/H99/Q11to20.hs
|
mit
| 1,184 | 0 | 11 | 432 | 266 | 145 | 121 | 17 | 2 |
module Sync.MerkleTree.Util.Communication
( send,
receive,
)
where
import qualified Data.ByteString as BS
import Data.Bytes.Put (runPutS)
import Data.Bytes.Serial (Serial, deserialize, serialize)
import qualified Data.Serialize as CES
import System.IO.Streams (InputStream, OutputStream, read, unRead, write)
import Prelude hiding (read)
-- | Deserialize value from inputstream
receive :: (Serial a) => InputStream BS.ByteString -> IO a
receive input = go (CES.Partial $ CES.runGetPartial deserialize)
where
go (CES.Fail err _bs) = fail err
go (CES.Partial f) =
do
x <- read input
case x of
Nothing -> (go $ f BS.empty)
Just x'
| BS.null x' -> go (CES.Partial f)
| otherwise -> go (f x')
go (CES.Done r bs) = unRead bs input >> return r
-- | Serialize value to OutputStream
send :: (Serial a) => OutputStream BS.ByteString -> a -> IO ()
send out msg = do
write (Just $ runPutS $ serialize msg) out
write (Just "") out -- flush underlying handle
|
ekarayel/sync-mht
|
src/Sync/MerkleTree/Util/Communication.hs
|
mit
| 1,040 | 0 | 16 | 246 | 378 | 198 | 180 | 25 | 4 |
import Control.Arrow
churchNumber :: (Arrow a) => Int -> a b b -> a b b
churchNumber n f = if n == 0 then returnA else f >>> churchNumber (n - 1) f
a = churchNumber 3 (+1) 0
|
luochen1990/my-utils.hs
|
churchNumber.hs
|
mit
| 177 | 0 | 9 | 43 | 92 | 48 | 44 | 4 | 2 |
{-# LANGUAGE PartialTypeSignatures #-}
{-# LANGUAGE TypeFamilies #-}
module Problem07 (partA, partB) where
import Text.Megaparsec
import Text.Megaparsec.String
import Data.Monoid
import Data.Maybe
partA = partAString <$> readFile inputLocation
partB = partBString <$> readFile inputLocation
inputLocation = "input/input7.txt"
data IP = IP {
notHyper :: [String]
, hyper :: [String]
}
deriving (Eq,Show)
mkNotHyper s = IP [s] []
mkHyper s = IP [] [s]
instance Monoid IP where
mempty = IP [] []
mappend (IP a b) (IP c d) = IP (a <> c) (b <> d)
parseIP :: Parser IP
parseIP = helper mempty
where helper s = do
a <- fmap mkNotHyper <$> optional (many lowerChar)
case a of
Nothing -> return s
Just x -> do
b <- fmap mkHyper <$> optional (between (char '[') (char ']') (many lowerChar))
case b of
Nothing -> return $ s <> x
Just y -> helper (s <> x <> y)
containsABBA :: Eq a => [a] -> Bool
containsABBA (a : b : c : d : xs) = (a == d && b == c && a /= b) || containsABBA (b : c : d : xs)
containsABBA _ = False
getABA :: Eq a => [a] -> [(a,a)]
getABA (a : b : c : xs)
| (a == c && a /= b) = (a,b) : getABA (b : c : xs)
| otherwise = getABA (b : c : xs)
getABA _ = []
flipTuple (a,b) = (b,a)
hasSSL :: IP -> Bool
hasSSL (IP nh h) = or $ (==) <$> aba <*> bab
where aba = foldMap getABA nh
bab = map flipTuple $ foldMap getABA h
hasTLS :: IP -> Bool
hasTLS (IP nh h) = any containsABBA nh && not (any containsABBA h)
partAString = fmap (length . filter hasTLS) <$> mapM (parse parseIP "") . lines
partBString = fmap (length . filter hasSSL) <$> mapM (parse parseIP "") . lines
|
edwardwas/adventOfCodeTwo
|
src/Problem07.hs
|
mit
| 1,772 | 0 | 20 | 524 | 803 | 412 | 391 | 47 | 3 |
-- Solve the map-coloring problem [Section 4.2, Map coloring, on page 87] using
-- Haskell.
module Main (mapColoring) where
colors = ["red", "green", "blue"]
mapColoring =
[
(["MS", ms], ["TN", tn], ["AL", al], ["GA", ga], ["FL", fl]) |
ms <- colors,
tn <- colors,
al <- colors,
ga <- colors,
fl <- colors,
fl /= ga,
fl /= al,
al /= ga,
al /= ms,
al /= tn,
ms /= tn,
ga /= tn
]
|
ryanplusplus/seven-languages-in-seven-weeks
|
haskell/day1/map_coloring.hs
|
mit
| 469 | 0 | 7 | 166 | 174 | 100 | 74 | 17 | 1 |
{-# LANGUAGE ScopedTypeVariables, ViewPatterns, MultiParamTypeClasses, FlexibleInstances, FunctionalDependencies #-}
{-|
Module : Labyrinth.Maze
Description : maze typeclass
Copyright : (c) deweyvm 2014
License : MIT
Maintainer : deweyvm
Stability : experimental
Portability : unknown
A maze and associated typeclass for doing fancier things with specific
types of graphs.
-}
module Labyrinth.Maze(
Maze(..),
Node(..),
Invertible(..),
Border(..),
isNode,
getCoord
) where
import Labyrinth.Graph
data Node a b = Node a b
| Solid b
| OutOfBounds b
deriving (Ord, Eq)
isNode :: Node a b -> Bool
isNode (Node _ _) = True
isNode _ = False
getCoord :: Node a b -> b
getCoord (Node _ x) = x
getCoord (Solid x) = x
getCoord (OutOfBounds x) = x
{- | A graph where some nodes are passable but others are not.
A maze also has a notion a border, made up of nodes which
are considered out of bounds.
a - the underlying collection type
b - the element representing nodes in the graph
c - the coordinate indexing nodes -}
class (Functor a, Graph a b c) => Maze a b c | a -> c where
-- | Get adjacent nodes to a given vertex
getAdjacent :: a b -> c -> [(Node b c, Float)]
getNode :: a b -> c -> Node b c
isHardBound :: a b -> c -> Bool
-- | Returns the passability of the given node.
isPassable :: a b -> c -> Bool
isPassable g coord = (isNode . snd) $ (,) coord $ getNode g coord
{- | A graph with a notion of a border which can be expanded.
a - the underlying collection type
b - the element representing nodes in the graph
c - the coordinate indexing nodes -}
class Border a b c | a -> c where
addBorder :: a b
-> b
-> (a b, c -> c)
-- | Represents (bijectively) invertible elements.
class Invertible a where
invert :: a -> a
|
deweyvm/labyrinth
|
src/Labyrinth/Maze.hs
|
mit
| 1,886 | 0 | 11 | 502 | 407 | 221 | 186 | 32 | 1 |
{- |
Module : $Header$
Description : Signature for propositional logic
Copyright : (c) Dominik Luecke, Uni Bremen 2007
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : experimental
Portability : portable
Definition of signatures for propositional logic
Ref.
Till Mossakowski, Joseph Goguen, Razvan Diaconescu, Andrzej Tarlecki.
What is a Logic?.
In Jean-Yves Beziau (Ed.), Logica Universalis, pp. 113-@133. Birkhaeuser.
2005.
-}
module Propositional.Sign
(Sign (..) -- Propositional Signatures
, id2SimpleId
, pretty -- pretty printing
, isLegalSignature -- is a signature ok?
, addToSig -- adds an id to the given Signature
, unite -- union of signatures
, emptySig -- empty signature
, isSubSigOf -- is subsiganture?
, sigDiff -- Difference of Signatures
, sigUnion -- Union for Logic.Logic
) where
import qualified Data.Set as Set
import Common.Id
import Common.Result
import Common.Doc
import Common.DocUtils
{- | Datatype for propositional Signatures
Signatures are just sets -}
newtype Sign = Sign {items :: Set.Set Id} deriving (Eq, Ord, Show)
instance Pretty Sign where
pretty = printSign
id2SimpleId :: Id -> Token
id2SimpleId i = case filter (not . isPlace) $ getTokens i of
[] -> error "id2SimpleId"
c : _ -> c
{- | determines whether a signature is vaild
all sets are ok, so glued to true -}
isLegalSignature :: Sign -> Bool
isLegalSignature _ = True
-- | pretty printing for Signatures
printSign :: Sign -> Doc
printSign s =
hsep [text "prop", sepByCommas $ map pretty $ Set.toList $ items s]
-- | Adds an Id to the signature
addToSig :: Sign -> Id -> Sign
addToSig sig tok = Sign {items = Set.insert tok $ items sig}
-- | Union of signatures
unite :: Sign -> Sign -> Sign
unite sig1 sig2 = Sign {items = Set.union (items sig1) $ items sig2}
-- | The empty signature
emptySig :: Sign
emptySig = Sign {items = Set.empty}
-- | Determines if sig1 is subsignature of sig2
isSubSigOf :: Sign -> Sign -> Bool
isSubSigOf sig1 sig2 = Set.isSubsetOf (items sig1) $ items sig2
-- | difference of Signatures
sigDiff :: Sign -> Sign -> Sign
sigDiff sig1 sig2 = Sign {items = Set.difference (items sig1) $ items sig2}
{- | union of Signatures
or do I have to care about more things here? -}
sigUnion :: Sign -> Sign -> Result Sign
sigUnion s1 = Result [Diag Debug "All fine sigUnion" nullRange]
. Just . unite s1
|
nevrenato/HetsAlloy
|
Propositional/Sign.hs
|
gpl-2.0
| 2,666 | 0 | 10 | 705 | 510 | 280 | 230 | 41 | 2 |
{-|
This is the new parser module built using the @parsec@ parser
cominator library.
I think the option parsers should probably be moved to L.P.FileParser
-}
module Language.Pepa.Parser
( parseRateArrayOption
, parseRateOption
, parseActionArrayOption
, parseCommaSeparatedLowers
, parseRateExprOption
, blindRun
, wholeParser
-- * Individual parser definitions
, pepaModel
, pepaComponent
, pepaBeginProcessDef
, pepaComponentDef
, pepaActionId
, pepaComponentId
, pepaRateId
, pepaRateDefId
, pepaRate
, pepaRateExp
, exprParser
, rateExprIdent
-- * Utility functions or parsers
, maybeOption
, forgivingFloat
-- * Identifier parsers
, nameSpace
, upperId
, lowerId
, upperOrLowerId
, wholeNameSpaceId
-- * The token parser parsers which use the lexer specific to pepa
, whiteSpace
, reserved
, reservedOp
, intParser
, symbol
, stringLiteral
, comma
, braces
, angles
, parens
, natural
, naturalOrFloat
, squares
)
where
{- Standard imported libraries -}
import Control.Monad
( liftM )
import qualified Data.Maybe as Maybe
import Text.ParserCombinators.Parsec
( Parser
, CharParser
, GenParser
, parse
, ( <|> )
, ( <?> )
, try
, eof
, alphaNum
, char
, upper
, lower
, optional
, many
, many1
, sepBy
, sepBy1
, notFollowedBy
)
import qualified Text.ParserCombinators.Parsec.Token as StdToken
import Text.ParserCombinators.Parsec.Expr
( buildExpressionParser
, Assoc ( .. )
, Operator ( .. )
)
import Text.ParserCombinators.Parsec.Language
( haskellStyle )
{- Local imported libraries -}
import qualified Language.Pepa.PrivateTokenParser as PrvToken
import Language.Pepa.QualifiedName
( QualifiedName ( .. ) )
import Language.Pepa.Rates
( RateIdentifier
, RateExpr ( .. )
, Rate ( .. )
)
import qualified Language.Pepa.Syntax as Syntax
import Language.Pepa.Syntax
( ActionIdentifier
, ParsedModel ( .. )
, ParsedDefinition ( .. )
, ParsedComposition
, ParsedComponent ( .. )
, CooperationSet ( .. )
, Transition ( .. )
, ParsedTrans
, ParsedPriority
, defaultPepaPriority
, ParsedComponentId
, ParsedRate
, ParsedAction ( .. )
, nameOfAction
)
{- End of imports -}
{-|
Blindly runs the given parser expecting it to succeed.
The first argument is the error string to give to the failure
function 'error' in the event that the parser fails.
This function is most useful for simple parsers within the program
such as the parsing of command line options.
Note that the actual parse error returned from the parser itself is
ignored, hence the user will not recieve a potentially useful message
such as 'expecting open bracket'.
-}
blindRun :: String -> Parser a -> String -> a
blindRun err p input =
case (parse p "" input) of
Left err2 -> error (err ++ ": " ++ show err2)
Right x -> x
{-|
When parsing options or fields from web or gui inputs you need to
be sure of parsing the whole string. In addition you need to be
sure of ignoring leading white space. This turns a simple parser
into such a parser. It is therefore good for turning parsers meant
for part of a whole file parser (for example an expression parser)
into one suitable for option/field parsing.
-}
wholeParser :: Parser a -> Parser a
wholeParser parser =
do whiteSpace
x <- parser
eof
return x
{-
We now begin with the utility parsers that are used out with the
main parser for pepa files. These include for example the parsing
of command line options.
Parses the rate command line option argument, which is of the form
@ r=0.5,1.5,6.9 @
the integer given as the first argument is used to select which
value of the comma separated list of values is returned.
-}
{-|
The action list parser will produce a list of parsed actions but
these are not just identifiers, so we have to map them into identifiers.
We probably should store them in the command line options as parsed actions.
-}
parseActionArrayOption :: String -> [ ActionIdentifier ]
parseActionArrayOption input =
map nameOfAction actions
where
err = "error parsing a pepa action list option"
actions = blindRun err pepaActionList input
{-|
Parses in a list of comma separated names which all begin
with a lower case letter.
The first argument is the error to give the second
the input.
-}
parseCommaSeparatedLowers :: String -> String -> [ String ]
parseCommaSeparatedLowers err =
blindRun err $ sepBy lowerId comma
{-|
In contrast to that below, when parsing a rate option
(as opposed to a rate array option) there is only one
double to return rather than a list of double from which to
choose using the process identifier.
-}
parseRateOption :: String -> (RateIdentifier, Double)
parseRateOption input =
blindRun err rateOptionParser input
where err = "error parsing a rate constant option"
rateOptionParser :: Parser (RateIdentifier, Double)
rateOptionParser =
do ident <- pepaRateId
char '='
number <- forgivingFloat
return (ident, number)
{-|
Allows the parsing of a rate option where the rate is set to a
rate expression rather than a simple constant.
-}
parseRateExprOption :: String -> (RateIdentifier, RateExpr)
parseRateExprOption input =
blindRun err rateExprOptionParser input
where err = "error parsing a rate expression option"
rateExprOptionParser :: Parser (RateIdentifier, RateExpr)
rateExprOptionParser =
do ident <- pepaRateId
char '='
expr <- pepaRateExp
eof
return (ident, expr)
{-|
Parse a rate array option, such as
@ --rates r=0.1,0.2,0.3,0.4,0.5 @
-}
parseRateArrayOption :: String -> (RateIdentifier, [Double])
parseRateArrayOption input =
blindRun err rateArrayOptionParser input
where err = "error parsing a rate constant array option"
rateArrayOptionParser :: Parser (RateIdentifier, [Double])
rateArrayOptionParser =
do ident <- pepaRateId
char '='
numbers <- rateNumberList
return (ident, numbers)
{-
The rate number list can either be a list of floating point numbers
separated by commas, or a stepped number list.
So it looks like either
@ r=0.2,0.4,0.6,0.8 @
or
@ r=0.2..0.8:0.2 @
So to parse this we have to parse the first number, since in either case
we are expecting a number. After this we can decide, if we see a comma then
a comma list is following if we see a dot then a stepped list is following.
Note that the first number is passed in to create the remainder parsers and
that is why we needn't return it in the return expression because it will
already be incorporated into the results of the two parsers.
-}
rateNumberList :: Parser [Double]
rateNumberList =
do first <- floatNumber
( steppedNumberList first) <|> ( commaFloatNumberList first )
{-
There is a known bug involved with this, it comes from how Haskell
does double addition. It comes from the representation of doubles
in particular that of @0.2@. The upshot is that something like
@0.1 + 0.2@ produces @0.3000000000000004@, which obviously looks
very bad as a result. I will fix this using a floor function to take
the number to the nearest say six decimal places.
-}
steppedNumberList :: Double -> Parser [Double]
steppedNumberList start =
do char '.'
char '.'
end <- floatNumber
char ':'
step <- floatNumber
return (computeNumberList start end step)
where
computeNumberList :: Double -> Double -> Double -> [Double]
computeNumberList current end step
| current > end = []
| otherwise =
current : (computeNumberList (current + step) end step)
{-
A parser for a whole pepa model.
-}
pepaModel :: Parser ParsedModel
pepaModel =
do definitions <- pepaDefinitionList
composition <- pepaComponent
let rateSpecs = Syntax.filterRateSpecifications definitions
processDefs = Syntax.filterProcessDefintions definitions
virtualComps = Syntax.filterVirtualComps definitions
return ParsedModel { modelRateSpecs = rateSpecs
, modelProcessDefs = processDefs
, modelVirtualComps = virtualComps
, modelSystemEqn = composition
}
pepaDefinitionList :: Parser [ ParsedDefinition () ]
pepaDefinitionList = many1 pepaDefinition
{-
A pepa model definition, basically can be either a rate definition,
a process concentration definition or the definition of a
sequential process. Currently though we parse process concentration
definition as a rate definition because they are indistinguishable
from the point of view of the parser and sort it out in the semantic
analysis. But see below that I think it would be nice to separate
them out syntactically.
-}
pepaDefinition :: Parser (ParsedDefinition ())
pepaDefinition =
followedBy (pepaRateDef <|> pepaComponentDef) $ symbol ";"
{-
Process concentration definitions are parsed as rate definitions
and we sort it out after parsing, the reason is that it is a bit
awkward to distinguish between the two, importantly because
the identifiers are of the same style. It may be worth considering
changing this actually. We could for example have a syntax something
like [-concentration p = 0-], unfortunately concentration seems like
a rather long key word, perhaps instead [-rate r = 0.1-].
-}
pepaRateDef :: Parser (ParsedDefinition a)
pepaRateDef =
do ident <- pepaRateDefId
symbol "="
expr <- pepaRateExp
return $ RateDef (ident, expr)
{-
A parser for a component definition, so basically a component
identifier set equal to a *sequential* component expression.
Note the slightly questionable use of the [-try-] parser
combinator here. The purpose is that the main composition at
the end may not be surrounded by parentheses. It may for example
be [-P <> P-], if it is, and we didn't use [-try-] to parse the
identifier and the [-=-] sign then *this* parser would successfully
parse the [-P-] identifier and then fail because there is no [-=-]
sign. This would cause the [-pepaModel-] parser to come out of the
[-many1 pepaDefinition-] and attempt to parse the main composition,
*however* the input [-P-] has already been 'eaten' by this parser.
Using [-try-] here means that if we fail because the [-=-] sign is
not present then we will put the [-P-] (or whatever the component
identifier is) back on to the input and allow the main composition
to be parsed.
-}
pepaComponentDef :: Parser (ParsedDefinition a)
pepaComponentDef =
do ident <- pepaBeginProcessDef
let realDef = do component <- pepaComponent
return $ ProcessDef (ident, component)
virtualDef = do rexpr <- squares pepaRateExp
return $ VirtualDef (ident, rexpr)
realDef <|> virtualDef
pepaBeginProcessDef :: Parser ParsedComponentId
pepaBeginProcessDef =
try $ do optional $ symbol "#"
ident <- pepaProcessDefId
symbol "="
return ident
{-
Parser for components.
I'm now not so sure that 'buildExpressionParser' is the way to go
here because of the slight difficulty of parsing a prefix
component. Also doing this means that we allow the parsing of
for example @ (a,r).(P <> P) @ which is obvious nonsense.
I think the better way to go is build up the parser myself,
for now though this isn't working too badly.
Also I tried putting in a 'Prefix' line in the @compTable@,
in order to parse prefix components rather than having them
as a @compFactor@ but I couldn't get that to work.
UPDATE: I think now the better way to go is to just have two
separate parsers one for prefix and one for parallel.
The problem is that in general both are acceptable, since
we have parallel definitions.
-}
pepaComponent :: Parser ParsedComposition
pepaComponent =
buildExpressionParser compTable compFactor
<?> "Pepa component"
where
compTable = [ [ Postfix arrayTail ]
, [ Infix compSum AssocLeft ]
, [ Postfix hideTail ]
, [ Infix (twoBars <|> angledActions) AssocLeft ]
]
-- Some pepa tools force @P || P@ to mean cooperation
-- over the empty set of actions, so we allow this
-- in addition to @P <> P@ just so that a model does not
-- need to be written twice.
twoBars :: Parser (ParsedComponent -> ParsedComponent -> ParsedComponent)
twoBars = do symbol "||"
return $ makeCoop (ActionSet [])
angledActions :: Parser ( ParsedComponent -> ParsedComponent
-> ParsedComponent)
angledActions =
angles $ (do reserved "*"
return $ makeCoop WildCard
) <|>
(do actions <- pepaActionList
return $ makeCoop (ActionSet actions)
)
makeCoop :: CooperationSet -> ParsedComponent
-> ParsedComponent -> ParsedComponent
makeCoop coopSet left = Cooperation left coopSet
compSum :: Parser (ParsedComponent -> ParsedComponent -> ParsedComponent)
compSum = do symbol "+"
return ComponentSum
hideTail = do symbol "/"
actions <- braces pepaActionList
return $ makeHide actions
makeHide :: [ParsedAction] -> ParsedComponent -> ParsedComponent
makeHide actions left = Hiding left actions
compFactor = (try pepaConditional)
<|> (try pepaPrefix)
<|> stopProcess
<|> processName
<|> parens pepaComponent
<?> "simple process composition"
stopProcess :: Parser ParsedComponent
stopProcess = do reserved "Stop"
return StopProcess
processName :: Parser ParsedComponent
processName = do ident <- pepaComponentId
return $ IdProcess ident
-- Okay I'm not completely sure about having 'pepaComponent' as the
-- second alternative to a 'pepaPrefix'.
-- As you can see I previously had just a simple
-- ident component there, but I would quite like to allow things such as
-- @ (r, 1.0).(P + Q) @
-- I think the use of 'try' here *may* be very inefficient.
pepaPrefix :: Parser ParsedComponent
pepaPrefix =
do mTrans <- pepaTrans
symbol "."
right <- ((try pepaPrefix) <|> compFactor)
return $ PrefixComponent mTrans right
-- Pepa conditionals are simple if-thens, note no else.
pepaConditional :: Parser ParsedComponent
pepaConditional =
do reserved "if"
rCond <- exprParser
reserved "then"
right <- ((try pepaPrefix) <|> compFactor)
return $ CondBehaviour rCond right
{-
A process tail is only afixable to a process name and allows
the user to specify an array of processes. In addition to the number
of processes to run in parallel the user can specify a list of actions
on which the processes should cooperate. There are two styles for this
@ P[3][a,b] @ is an array of 3 @P@ processes cooperating over
the actions @a@ and @b@.
@ P[3, {a, b}] @ is an alternative style for the same thing.
-}
arrayTail :: Parser (ParsedComponent -> ParsedComponent)
arrayTail = do symbol "["
size <- exprParser
end <- (do comma
actions <- maybeOption $ braces pepaActionList
symbol "]"
return actions
) <|>
(do symbol "]"
maybeOption $ squares pepaActionList
)
return $ addArrayTail size end
addArrayTail :: RateExpr -> Maybe [ ParsedAction ]
-> ParsedComponent -> ParsedComponent
addArrayTail size mActs proc = ProcessArray proc size mActs
{-
A parser for a pepa transitions.
The first parser accepts the standard @(a, r)@ still of transition,
however we can also put in just a single action name (which is
lowercase so should not conflict with process identifiers) this is
an immediate action and is shorthand for @(a, immediate)@
-}
pepaTrans :: Parser ParsedTrans
pepaTrans =
normalBracketed -- so a normal bracketed (a,r) style transition
<|>
quickTrans -- or a single action identifier which will be performed
-- as an immediate action, ag @ tau.P @
where
normalBracketed :: Parser ParsedTrans
normalBracketed =
parens $ do action <- pepaAction
priority <- maybeOption pepaPriority
comma
rate <- pepaRate
return $ makeTrans action priority rate
quickTrans :: Parser ParsedTrans
quickTrans =
do action <- pepaAction
priority <- maybeOption pepaPriority
return $ makeTrans action priority ( RateImmediate $ Creal 1 )
makeTrans :: ParsedAction -> Maybe ParsedPriority
-> ParsedRate -> ParsedTrans
makeTrans action mPriority rate =
Transition { pepaTransAction = action
, pepaTransCoalsced = []
, pepaTransPriority = priority
, pepaTransRate = rate
, pepaTransConditions = []
}
where
priority = Maybe.fromMaybe defaultPepaPriority mPriority
{-
Parses a priority which may be affixed to the end of a
(semi-markov) pepa action
-}
pepaPriority :: Parser ParsedPriority
pepaPriority = squares intParser
{-
Parses a rate. Unfortunately we have to use 'try'
This is because both immediate and infty may actually be rate expressions.
The simple case they might must be named longer, eg it might be the rate
expression: @immediate_rate * r1@ if we didn't use 'try' then the
@rateImm@ parser would consume the word @immediate@.
Similarly for @rateTop@ it would consume @infty@ if confronted with
the rate @infty_like_rate@.
-}
pepaRate :: Parser ParsedRate
pepaRate =
(try rateTop)
<|>
(try rateImm)
<|>
timed
where
rateTop :: Parser ParsedRate
rateTop = do (reserved "infty" <|> reserved "_" <|> reserved "T" )
mWeight <- maybeOption pepaRateExp
let weight = Maybe.fromMaybe (Creal 1.0) mWeight
return $ RateTop weight
-- It may look like we can easily combine rate immediate and
-- timed rate, just parse a rate expression and then detect if
-- there is a tail on the end. But we may have an immediate
-- rate without a weighting. Such as "(a, immediate) . P"
rateImm :: Parser ParsedRate
rateImm = do reserved "immediate"
colon
mWeight <- maybeOption pepaRateExp
let weight = Maybe.fromMaybe (Creal 1.0) mWeight
return $ RateImmediate weight
timed :: Parser ParsedRate
timed = liftM RateTimed pepaRateExp
{-
We build a parser for rate expressions using parsec's expression
parser building library. Best really to look at the parsec
documentation, but briefly the [-buildExpressionParser-] takes
two arguments, the first is a table of operators where each row
represents an operator precedence. The second argument is the parser
for the basic terms, that is non-decomposable terms.
This is quite good, it does not allow an immediate rate to be part of
a binary rate expression, so for example one cannot have
@ r * 2:immediate @ as this is obvious nonsense. However because the
@condRate@ parser explictly calls 'pepaRateExp' rather than being built
up from the @rateTable@ it is still possible to have something like:
@ if P then 2:immediate else 1:immediate @
which might be useful is perhaps a bit difficult to compile.
-}
pepaRateExp :: Parser RateExpr
pepaRateExp = exprParser
{-
This parses a small sub-set of C expressions which should be okay for rate
expressions. It allows both upper and lower cased identifiers.
-}
exprParser :: Parser RateExpr
exprParser =
(buildExpressionParser exprTable exprFactor )
<?> "expression"
where
exprTable = [ [ Prefix cNot ]
, [ op "*" Cmult AssocLeft
, op "/" Cdiv AssocLeft
]
, [ op "+" Cadd AssocLeft
, op "-" Csub AssocLeft
]
, [ op ">" Cgt AssocLeft
, op ">=" Cge AssocLeft
, op "<" Clt AssocLeft
, op "<=" Cle AssocLeft
, op "==" Ceq AssocLeft
, cNotEqual
]
, [ op "||" Cor AssocLeft ]
, [ op "&&" Cand AssocLeft ]
]
op :: String -> (RateExpr -> RateExpr -> RateExpr)
-> Assoc -> Operator Char () RateExpr
op opString f = Infix (reservedOp opString >> return f)
-- We allow "exp != exp" as a synonym for
-- "!(exp == exp)" because this is actually quite
-- convenient.
cNotEqual :: Operator Char () RateExpr
cNotEqual = Infix ( do reservedOp "!="
return noEq) AssocLeft
where
noEq :: RateExpr -> RateExpr -> RateExpr
noEq r1 = Cnot . Ceq r1
cNot :: Parser (RateExpr -> RateExpr)
cNot = (reservedOp "!") >> (return Cnot)
-- Hmm, actually think that both of if then else and the min
-- functions should be a 'try'
exprFactor = parens exprParser
<|> rateIfThenElse
<|> minfunction
<|> (liftM Cident rateExprIdent)
<|> exprNumber
<?> "simple expression"
-- Parses a conditional rate
rateIfThenElse :: Parser RateExpr
rateIfThenElse =
do reserved "if"
rCond <- exprParser
reserved "then"
left <- exprParser
reserved "else"
right <- exprParser
return $ Cifte rCond left right
minfunction :: Parser RateExpr
minfunction =
do reserved "min"
parens $ do left <- exprParser
comma
right <- exprParser
return $ Cminimum left right
exprNumber :: Parser RateExpr
exprNumber =
liftM doubleOfEitherNum naturalOrFloat
where
doubleOfEitherNum :: Either Integer Double -> RateExpr
doubleOfEitherNum (Left i) = Cconstant $ fromIntegral i
doubleOfEitherNum (Right d) = Creal d
-- | Parses a name which maybe used within a rate expression.
-- Note that that means it may be a component name since it may
-- be a functional rate.
-- This in turn means that it may be a string literal.
rateExprIdent :: Parser QualifiedName
rateExprIdent = pepaRateId <|> pepaComponentId
{-
A pepa action should be either an action identifier or a tau of
an action identifier, for now though only action identifiers
are parsed.
-}
pepaAction :: Parser ParsedAction
pepaAction =
(liftM Tau (symbol "`" >> pepaActionId ))
<|>
(liftM Action pepaActionId)
{-
Pepa action list, separated by commas.
-}
pepaActionList :: Parser [ParsedAction]
pepaActionList = sepBy pepaAction comma
{-
The parsers for the simple elements of a pepa file. By that I mean here is
where we define what a rate identifier, and a process identifier is,
for example.
-}
{-
Rate identifiers begin with a lower case letter.
We also take this opportunity to prefix the rate with a name.
@todo{Rate identifiers should of course be stored as
'Language.Pepa.Syntax.QualifiedName' that way we can give good error
messages (and come to think of it logging information).
Note: if/once we update things so that we do not syntactically
separate rate names from process names (ie rate names *could* be
upper case) then this would become a slightly simpler parser
since the option bit could be the tail.
-}
pepaRateId :: Parser RateIdentifier
pepaRateId =
-- attempt to parser an upper name followed by the
-- namespace separator ::
do namespace <- maybeOption $ followedBy upperId coloncolon
case namespace of
-- If we couldn't do that then just parse a lower case
-- rate name.
Nothing -> liftM Unqualified lowerId
-- if we could recursively parse a possible namespace
-- rate name.
Just p -> liftM (NameSpaceId p) pepaRateId
{-
But if it is the start of a definition then it can of course only
be a non-namespaced name.
-}
pepaRateDefId :: Parser RateIdentifier
pepaRateDefId =
liftM Unqualified lowerId
{-| Action identifiers begin with a lower case letter -}
pepaActionId :: Parser ActionIdentifier
pepaActionId = liftM Unqualified (lowerId <|> stringLiteral)
{-| Component identifiers begin with an upper case letter
This is currently equal to a name space, meaning that you can
use srmc component names in a pepa model but they do NOT have
the same meaning.
-}
pepaComponentId :: Parser ParsedComponentId
pepaComponentId = nameSpace
{-
Similarly as for rate definitions, for component definitions the
name must be a non-namespaced one.
-}
pepaProcessDefId :: Parser ParsedComponentId
pepaProcessDefId =
liftM Unqualified ( upperId <|> stringLiteral )
{-
This subsection contains a few generally useful parsers.
These include things like a lowercase identifier.
The main parser can then use these by for example setting a rate identifier
to be a lowercase identifier.
Note that below we also allow single colons, but I think that will only
ever be for names beginning with an upper case letter. The reason is
that we use colon for labels in probes so an activity name cannot
contain a colon other wise the probe
a:start, b:stop
will be parsed as just two names in sequences, ie
"a:start", "b:stop".
-}
alphaNumUnderScore :: Parser Char
alphaNumUnderScore =
alphaNum <|> char '_'
{-
Note here we also allow colon, provided it is not followed by another colon.
The reason for this is that we want to allow species names in biopepa such
as, E:S, but we also want to stop at the first colon if the name is a
separated name in srmc such as
UEDIN::Ftp
This might be a bit of a perfomance hit, in which case I can just
parse all names as a single name and then later divide up by
double colons (this is what I probably should do).
-}
alphaNumUnderScoreColon :: Parser Char
alphaNumUnderScoreColon =
alphaNumUnderScore <|> singleColon
singleColon :: Parser Char
singleColon = try $ do char ':'
notFollowedBy $ char ':'
return ':'
{-| Srmc style namespace names, these must have the component part
start with a capital letter so this could also be a component
name.
-}
nameSpace :: Parser QualifiedName
nameSpace =
do ident <- ( upperId <|> stringLiteral )
idTail <- maybeOption $ coloncolon >> pepaComponentId
return $ addTail ident idTail
where
addTail :: String -> Maybe ParsedComponentId -> ParsedComponentId
addTail ident Nothing = Unqualified ident
addTail ident (Just p) = NameSpaceId ident p
{-|
Parse a whole name space name as a string.
-}
wholeNameSpaceId :: Parser String
wholeNameSpaceId =
followedBy ( many1 (alphaNumUnderScore <|> (char ':')) )
whiteSpace
upperOrLowerId :: Parser String
upperOrLowerId = upperId <|> lowerId
lowerId :: Parser String
lowerId = do firstChar <- lower
restChars <- many alphaNumUnderScore
whiteSpace
return (firstChar : restChars)
upperId :: Parser String
upperId = do firstChar <- upper
restChars <- many alphaNumUnderScoreColon
whiteSpace
return (firstChar : restChars)
floatNumber :: Parser Double
floatNumber = StdToken.float lexer
{-
'forgivingFloat' is the same as 'floatNumber' except that as
a short hand for a whole number one can leave off the decimal
-}
forgivingFloat :: Parser Double
forgivingFloat =
liftM doubleOfEitherNum naturalOrFloat
where
doubleOfEitherNum :: Either Integer Double -> Double
doubleOfEitherNum (Left i) = fromInteger i
doubleOfEitherNum (Right d) = d
{-
A comma separated list of floating point numbers
-}
floatNumberList :: Parser [Double]
floatNumberList = sepBy1 floatNumber comma
{-
A comma separated list of floating point numbers, may not
seem necessary but for example there are cases where there
are several options all of which begin with a floating point
number, if one of the options is a list then we have to parse
the rest of the list with this.
For example, the [- --rates -] option, accepts either
[- r=1.2,1.3,1.4,1.5 -]
or
[- r=1.2..1.5:0.1 -]
In both cases it starts with an initial floating point number,
then we have to decide whether we parse a list if a comma
follows or the range and step if two dots follow.
-}
commaFloatNumberList :: Double -> Parser [Double]
commaFloatNumberList first =
do comma
numbers <- floatNumberList
return (first : numbers)
{-|
This parser combinator should be in the parsec library
but I can't find exactly this.
-}
maybeOption :: GenParser tok st a -> GenParser tok st (Maybe a)
maybeOption p =
(liftM Just (try p))
<|>
(return Nothing)
-- option Nothing $ liftM Just (try p)
{-|
Used for the (relatively) common case where we wish to parse
an object and then terminate it with some object (usually a single
token for example a semi-colon).
This is often written as something like:
@ do c <- commandParser
symbol ";"
return c
@
-}
followedBy :: Parser a -> Parser b -> Parser a
followedBy p q =
do result <- p
q
return result
{-
Token Parser Stuff !!!
The token parser essentially allows us to forget about the
whitespace.
The following definition of 'lexer' is required for the token
parser stuff to work.
What I should do is comment this better.
Note: Although command line options are less likely to contain spaces
since a space generally separates out a command line option it
is still possible that they contain spaces by quoting an option
for example we could have
@ ipc --rates "r = 1.2 .. 2.1 : 0.1" ... @
as a command line, hence there are spaces within the arguments
to the @--rates @ option.
-}
lexer :: StdToken.TokenParser ()
lexer =
PrvToken.makeTokenParser langDef
where
langDef1 = PrvToken.translateLanguageDef haskellStyle
langDef = langDef1 { PrvToken.reservedOpNames = reservedOperators
, PrvToken.reservedNames = pepaNames
, PrvToken.commentLine = [ "%", "//" ]
, PrvToken.commentStart = "{-"
, PrvToken.commentEnd = "-}"
}
pepaNames = [ "else"
, "if"
, "infty"
, "then"
, "immediate"
, "_"
--, "stop"
]
reservedOperators = [ "*"
, "/"
, "+"
, "-"
-- Probe operators
, "?"
]
{-
For convenience we alias some of the common token parsers.
Along with a couple commented out because we do not use them
currently but may at some point.
-}
whiteSpace :: CharParser () ()
whiteSpace = StdToken.whiteSpace lexer
--lexeme :: CharParser () a -> CharParser () a
--lexeme = StdToken.lexeme lexer
symbol :: String -> CharParser () String
symbol = StdToken.symbol lexer
natural :: CharParser () Integer
natural = StdToken.natural lexer
naturalOrFloat :: CharParser () (Either Integer Double)
naturalOrFloat = StdToken.naturalOrFloat lexer
integer :: CharParser () Integer
integer = StdToken.integer lexer
intParser :: CharParser () Int
intParser = liftM fromInteger integer
stringLiteral :: CharParser () String
stringLiteral = StdToken.stringLiteral lexer
parens :: CharParser () a -> CharParser () a
parens = StdToken.parens lexer
angles :: CharParser () a -> CharParser () a
angles = StdToken.angles lexer
squares :: CharParser () a -> CharParser () a
squares = StdToken.squares lexer
braces :: CharParser () a -> CharParser () a
braces = StdToken.braces lexer
--semi :: CharParser () String
--semi = StdToken.semi lexer
comma :: CharParser () String
comma = StdToken.comma lexer
colon :: CharParser () String
colon = symbol ":" -- StdToken.colon lexer
coloncolon :: CharParser () String
coloncolon = colon >> colon
--identifier :: CharParser () String
--identifier = StdToken.identifier lexer
reserved :: String -> CharParser () ()
reserved = StdToken.reserved lexer
reservedOp :: String -> CharParser () ()
reservedOp = StdToken.reservedOp lexer
|
allanderek/ipclib
|
Language/Pepa/Parser.hs
|
gpl-2.0
| 33,085 | 0 | 16 | 8,843 | 4,564 | 2,362 | 2,202 | 505 | 2 |
-- grid is a game written in Haskell
-- Copyright (C) 2018 [email protected]
--
-- This file is part of grid.
--
-- grid is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- grid is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with grid. If not, see <http://www.gnu.org/licenses/>.
--
module Game.Run.RunWorld.OutputState.Plain
(
OutputState (..),
makeOutputState,
) where
import MyPrelude
import Game
data OutputState =
OutputState
{
outputstateColorIx :: !UInt,
outputstateColorIx' :: !UInt,
outputstateAlpha :: !Float
}
makeOutputState :: MEnv' OutputState
makeOutputState = do
return OutputState
{
outputstateColorIx = 0,
outputstateColorIx' = 0,
outputstateAlpha = 0.0
}
|
karamellpelle/grid
|
source/Game/Run/RunWorld/OutputState/Plain.hs
|
gpl-3.0
| 1,272 | 0 | 9 | 315 | 115 | 77 | 38 | 23 | 1 |
module Pudding.Utilities.VectorFunctions
( pairApply
) where
import qualified Data.Vector.Unboxed as U
pairApply :: (U.Unbox a, U.Unbox b)
=> (b -> b -> b)
-> b
-> (a -> a -> b)
-> (U.Vector a)
-> b
pairApply combine neutral f v = U.ifoldl'
(\acc i p -> U.foldl' (\acc' q -> combine acc' $ f p q)
acc
(U.drop (i + 1) v))
neutral
v
|
jfulseca/Pudding
|
src/Pudding/Utilities/VectorFunctions.hs
|
gpl-3.0
| 419 | 0 | 12 | 153 | 174 | 94 | 80 | 15 | 1 |
{-|
Module : Hypercube.Config
Description : Configuration data of hypercube
Copyright : (c) Jaro Reinders, 2017
License : GPL-3
Maintainer : [email protected]
This file contains all configuration variables like @chunkSize@ and @renderDistance@.
TODO: Eventually we want this file to be dynamically loaded at startup.
-}
module Hypercube.Config where
import Hypercube.Types
import Linear
-- The size of a chunk. For example a chunkSize of 16 means that each chunk is a 16x16x16 cube of blocks.
chunkSize :: Int
chunkSize = 16
-- The number of chunks that gets loaded in any given direction.
-- for example a render distance of 4 would render a 4x4x4 cube of chunks around the user.
renderDistance :: Int
renderDistance = 10
-- The function that generates the landscape
generatingF :: V3 Int -> Block
generatingF = hourglass
-- An empty hourglass shape
hourglass :: V3 Int -> Block
hourglass (V3 x y z) = if y*y >= x*x + z*z then Air else Stone
-- A field of equally sized small hills and valleys made from the sine function
sinefield :: V3 Int -> Block
sinefield (V3 x y z)
| fromIntegral y < (8 :: Double) * sin ((fromIntegral x / 16) * pi) * sin ((fromIntegral z / 16) * pi) = Stone
| otherwise = Air
|
noughtmare/hypercube
|
src/Hypercube/Config.hs
|
gpl-3.0
| 1,237 | 0 | 15 | 240 | 222 | 119 | 103 | 15 | 2 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Model.DriveCommand
( DriveCommand (..)
) where
import Data.Aeson
import GHC.Generics
import Test.QuickCheck
data DriveCommand = DriveCommand
{ direction :: Float
, speed :: Float
} deriving (Show, Eq, Generic)
instance FromJSON DriveCommand
instance ToJSON DriveCommand
instance Arbitrary DriveCommand where
arbitrary = DriveCommand <$> arbitrary <*> arbitrary
|
massimo-zaniboni/netrobots
|
robot_examples/haskell-servant/rest_api/lib/Model/DriveCommand.hs
|
gpl-3.0
| 565 | 0 | 8 | 96 | 106 | 62 | 44 | 18 | 0 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.FactCheckTools.Types.Product
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
module Network.Google.FactCheckTools.Types.Product where
import Network.Google.FactCheckTools.Types.Sum
import Network.Google.Prelude
-- | Information about the claim.
--
-- /See:/ 'googleFactcheckingFactchecktoolsV1alpha1Claim' smart constructor.
data GoogleFactcheckingFactchecktoolsV1alpha1Claim =
GoogleFactcheckingFactchecktoolsV1alpha1Claim'
{ _gffvcText :: !(Maybe Text)
, _gffvcClaimReview :: !(Maybe [GoogleFactcheckingFactchecktoolsV1alpha1ClaimReview])
, _gffvcClaimDate :: !(Maybe DateTime')
, _gffvcClaimant :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'GoogleFactcheckingFactchecktoolsV1alpha1Claim' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gffvcText'
--
-- * 'gffvcClaimReview'
--
-- * 'gffvcClaimDate'
--
-- * 'gffvcClaimant'
googleFactcheckingFactchecktoolsV1alpha1Claim
:: GoogleFactcheckingFactchecktoolsV1alpha1Claim
googleFactcheckingFactchecktoolsV1alpha1Claim =
GoogleFactcheckingFactchecktoolsV1alpha1Claim'
{ _gffvcText = Nothing
, _gffvcClaimReview = Nothing
, _gffvcClaimDate = Nothing
, _gffvcClaimant = Nothing
}
-- | The claim text. For instance, \"Crime has doubled in the last 2 years.\"
gffvcText :: Lens' GoogleFactcheckingFactchecktoolsV1alpha1Claim (Maybe Text)
gffvcText
= lens _gffvcText (\ s a -> s{_gffvcText = a})
-- | One or more reviews of this claim (namely, a fact-checking article).
gffvcClaimReview :: Lens' GoogleFactcheckingFactchecktoolsV1alpha1Claim [GoogleFactcheckingFactchecktoolsV1alpha1ClaimReview]
gffvcClaimReview
= lens _gffvcClaimReview
(\ s a -> s{_gffvcClaimReview = a})
. _Default
. _Coerce
-- | The date that the claim was made.
gffvcClaimDate :: Lens' GoogleFactcheckingFactchecktoolsV1alpha1Claim (Maybe UTCTime)
gffvcClaimDate
= lens _gffvcClaimDate
(\ s a -> s{_gffvcClaimDate = a})
. mapping _DateTime
-- | A person or organization stating the claim. For instance, \"John Doe\".
gffvcClaimant :: Lens' GoogleFactcheckingFactchecktoolsV1alpha1Claim (Maybe Text)
gffvcClaimant
= lens _gffvcClaimant
(\ s a -> s{_gffvcClaimant = a})
instance FromJSON
GoogleFactcheckingFactchecktoolsV1alpha1Claim
where
parseJSON
= withObject
"GoogleFactcheckingFactchecktoolsV1alpha1Claim"
(\ o ->
GoogleFactcheckingFactchecktoolsV1alpha1Claim' <$>
(o .:? "text") <*> (o .:? "claimReview" .!= mempty)
<*> (o .:? "claimDate")
<*> (o .:? "claimant"))
instance ToJSON
GoogleFactcheckingFactchecktoolsV1alpha1Claim
where
toJSON
GoogleFactcheckingFactchecktoolsV1alpha1Claim'{..}
= object
(catMaybes
[("text" .=) <$> _gffvcText,
("claimReview" .=) <$> _gffvcClaimReview,
("claimDate" .=) <$> _gffvcClaimDate,
("claimant" .=) <$> _gffvcClaimant])
-- | Information about the claim rating.
--
-- /See:/ 'googleFactcheckingFactchecktoolsV1alpha1ClaimRating' smart constructor.
data GoogleFactcheckingFactchecktoolsV1alpha1ClaimRating =
GoogleFactcheckingFactchecktoolsV1alpha1ClaimRating'
{ _gffvcrWorstRating :: !(Maybe (Textual Int32))
, _gffvcrRatingExplanation :: !(Maybe Text)
, _gffvcrRatingValue :: !(Maybe (Textual Int32))
, _gffvcrImageURL :: !(Maybe Text)
, _gffvcrBestRating :: !(Maybe (Textual Int32))
, _gffvcrTextualRating :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'GoogleFactcheckingFactchecktoolsV1alpha1ClaimRating' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gffvcrWorstRating'
--
-- * 'gffvcrRatingExplanation'
--
-- * 'gffvcrRatingValue'
--
-- * 'gffvcrImageURL'
--
-- * 'gffvcrBestRating'
--
-- * 'gffvcrTextualRating'
googleFactcheckingFactchecktoolsV1alpha1ClaimRating
:: GoogleFactcheckingFactchecktoolsV1alpha1ClaimRating
googleFactcheckingFactchecktoolsV1alpha1ClaimRating =
GoogleFactcheckingFactchecktoolsV1alpha1ClaimRating'
{ _gffvcrWorstRating = Nothing
, _gffvcrRatingExplanation = Nothing
, _gffvcrRatingValue = Nothing
, _gffvcrImageURL = Nothing
, _gffvcrBestRating = Nothing
, _gffvcrTextualRating = Nothing
}
-- | For numeric ratings, the worst value possible in the scale from worst to
-- best. Corresponds to \`ClaimReview.reviewRating.worstRating\`.
gffvcrWorstRating :: Lens' GoogleFactcheckingFactchecktoolsV1alpha1ClaimRating (Maybe Int32)
gffvcrWorstRating
= lens _gffvcrWorstRating
(\ s a -> s{_gffvcrWorstRating = a})
. mapping _Coerce
-- | Corresponds to \`ClaimReview.reviewRating.ratingExplanation\`.
gffvcrRatingExplanation :: Lens' GoogleFactcheckingFactchecktoolsV1alpha1ClaimRating (Maybe Text)
gffvcrRatingExplanation
= lens _gffvcrRatingExplanation
(\ s a -> s{_gffvcrRatingExplanation = a})
-- | A numeric rating of this claim, in the range worstRating — bestRating
-- inclusive. Corresponds to \`ClaimReview.reviewRating.ratingValue\`.
gffvcrRatingValue :: Lens' GoogleFactcheckingFactchecktoolsV1alpha1ClaimRating (Maybe Int32)
gffvcrRatingValue
= lens _gffvcrRatingValue
(\ s a -> s{_gffvcrRatingValue = a})
. mapping _Coerce
-- | Corresponds to \`ClaimReview.reviewRating.image\`.
gffvcrImageURL :: Lens' GoogleFactcheckingFactchecktoolsV1alpha1ClaimRating (Maybe Text)
gffvcrImageURL
= lens _gffvcrImageURL
(\ s a -> s{_gffvcrImageURL = a})
-- | For numeric ratings, the best value possible in the scale from worst to
-- best. Corresponds to \`ClaimReview.reviewRating.bestRating\`.
gffvcrBestRating :: Lens' GoogleFactcheckingFactchecktoolsV1alpha1ClaimRating (Maybe Int32)
gffvcrBestRating
= lens _gffvcrBestRating
(\ s a -> s{_gffvcrBestRating = a})
. mapping _Coerce
-- | The truthfulness rating as a human-readible short word or phrase.
-- Corresponds to \`ClaimReview.reviewRating.alternateName\`.
gffvcrTextualRating :: Lens' GoogleFactcheckingFactchecktoolsV1alpha1ClaimRating (Maybe Text)
gffvcrTextualRating
= lens _gffvcrTextualRating
(\ s a -> s{_gffvcrTextualRating = a})
instance FromJSON
GoogleFactcheckingFactchecktoolsV1alpha1ClaimRating
where
parseJSON
= withObject
"GoogleFactcheckingFactchecktoolsV1alpha1ClaimRating"
(\ o ->
GoogleFactcheckingFactchecktoolsV1alpha1ClaimRating'
<$>
(o .:? "worstRating") <*> (o .:? "ratingExplanation")
<*> (o .:? "ratingValue")
<*> (o .:? "imageUrl")
<*> (o .:? "bestRating")
<*> (o .:? "textualRating"))
instance ToJSON
GoogleFactcheckingFactchecktoolsV1alpha1ClaimRating
where
toJSON
GoogleFactcheckingFactchecktoolsV1alpha1ClaimRating'{..}
= object
(catMaybes
[("worstRating" .=) <$> _gffvcrWorstRating,
("ratingExplanation" .=) <$>
_gffvcrRatingExplanation,
("ratingValue" .=) <$> _gffvcrRatingValue,
("imageUrl" .=) <$> _gffvcrImageURL,
("bestRating" .=) <$> _gffvcrBestRating,
("textualRating" .=) <$> _gffvcrTextualRating])
-- | Information about the claim review author.
--
-- /See:/ 'googleFactcheckingFactchecktoolsV1alpha1ClaimReviewAuthor' smart constructor.
data GoogleFactcheckingFactchecktoolsV1alpha1ClaimReviewAuthor =
GoogleFactcheckingFactchecktoolsV1alpha1ClaimReviewAuthor'
{ _gffvcraImageURL :: !(Maybe Text)
, _gffvcraName :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'GoogleFactcheckingFactchecktoolsV1alpha1ClaimReviewAuthor' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gffvcraImageURL'
--
-- * 'gffvcraName'
googleFactcheckingFactchecktoolsV1alpha1ClaimReviewAuthor
:: GoogleFactcheckingFactchecktoolsV1alpha1ClaimReviewAuthor
googleFactcheckingFactchecktoolsV1alpha1ClaimReviewAuthor =
GoogleFactcheckingFactchecktoolsV1alpha1ClaimReviewAuthor'
{_gffvcraImageURL = Nothing, _gffvcraName = Nothing}
-- | Corresponds to \`ClaimReview.author.image\`.
gffvcraImageURL :: Lens' GoogleFactcheckingFactchecktoolsV1alpha1ClaimReviewAuthor (Maybe Text)
gffvcraImageURL
= lens _gffvcraImageURL
(\ s a -> s{_gffvcraImageURL = a})
-- | Name of the organization that is publishing the fact check. Corresponds
-- to \`ClaimReview.author.name\`.
gffvcraName :: Lens' GoogleFactcheckingFactchecktoolsV1alpha1ClaimReviewAuthor (Maybe Text)
gffvcraName
= lens _gffvcraName (\ s a -> s{_gffvcraName = a})
instance FromJSON
GoogleFactcheckingFactchecktoolsV1alpha1ClaimReviewAuthor
where
parseJSON
= withObject
"GoogleFactcheckingFactchecktoolsV1alpha1ClaimReviewAuthor"
(\ o ->
GoogleFactcheckingFactchecktoolsV1alpha1ClaimReviewAuthor'
<$> (o .:? "imageUrl") <*> (o .:? "name"))
instance ToJSON
GoogleFactcheckingFactchecktoolsV1alpha1ClaimReviewAuthor
where
toJSON
GoogleFactcheckingFactchecktoolsV1alpha1ClaimReviewAuthor'{..}
= object
(catMaybes
[("imageUrl" .=) <$> _gffvcraImageURL,
("name" .=) <$> _gffvcraName])
-- | Response from searching fact-checked claims.
--
-- /See:/ 'googleFactcheckingFactchecktoolsV1alpha1FactCheckedClaimSearchResponse' smart constructor.
data GoogleFactcheckingFactchecktoolsV1alpha1FactCheckedClaimSearchResponse =
GoogleFactcheckingFactchecktoolsV1alpha1FactCheckedClaimSearchResponse'
{ _gffvfccsrNextPageToken :: !(Maybe Text)
, _gffvfccsrClaims :: !(Maybe [GoogleFactcheckingFactchecktoolsV1alpha1Claim])
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'GoogleFactcheckingFactchecktoolsV1alpha1FactCheckedClaimSearchResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gffvfccsrNextPageToken'
--
-- * 'gffvfccsrClaims'
googleFactcheckingFactchecktoolsV1alpha1FactCheckedClaimSearchResponse
:: GoogleFactcheckingFactchecktoolsV1alpha1FactCheckedClaimSearchResponse
googleFactcheckingFactchecktoolsV1alpha1FactCheckedClaimSearchResponse =
GoogleFactcheckingFactchecktoolsV1alpha1FactCheckedClaimSearchResponse'
{_gffvfccsrNextPageToken = Nothing, _gffvfccsrClaims = Nothing}
-- | The next pagination token in the Search response. It should be used as
-- the \`page_token\` for the following request. An empty value means no
-- more results.
gffvfccsrNextPageToken :: Lens' GoogleFactcheckingFactchecktoolsV1alpha1FactCheckedClaimSearchResponse (Maybe Text)
gffvfccsrNextPageToken
= lens _gffvfccsrNextPageToken
(\ s a -> s{_gffvfccsrNextPageToken = a})
-- | The list of claims and all of their associated information.
gffvfccsrClaims :: Lens' GoogleFactcheckingFactchecktoolsV1alpha1FactCheckedClaimSearchResponse [GoogleFactcheckingFactchecktoolsV1alpha1Claim]
gffvfccsrClaims
= lens _gffvfccsrClaims
(\ s a -> s{_gffvfccsrClaims = a})
. _Default
. _Coerce
instance FromJSON
GoogleFactcheckingFactchecktoolsV1alpha1FactCheckedClaimSearchResponse
where
parseJSON
= withObject
"GoogleFactcheckingFactchecktoolsV1alpha1FactCheckedClaimSearchResponse"
(\ o ->
GoogleFactcheckingFactchecktoolsV1alpha1FactCheckedClaimSearchResponse'
<$>
(o .:? "nextPageToken") <*>
(o .:? "claims" .!= mempty))
instance ToJSON
GoogleFactcheckingFactchecktoolsV1alpha1FactCheckedClaimSearchResponse
where
toJSON
GoogleFactcheckingFactchecktoolsV1alpha1FactCheckedClaimSearchResponse'{..}
= object
(catMaybes
[("nextPageToken" .=) <$> _gffvfccsrNextPageToken,
("claims" .=) <$> _gffvfccsrClaims])
-- | A generic empty message that you can re-use to avoid defining duplicated
-- empty messages in your APIs. A typical example is to use it as the
-- request or the response type of an API method. For instance: service Foo
-- { rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); } The
-- JSON representation for \`Empty\` is empty JSON object \`{}\`.
--
-- /See:/ 'googleProtobufEmpty' smart constructor.
data GoogleProtobufEmpty =
GoogleProtobufEmpty'
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'GoogleProtobufEmpty' with the minimum fields required to make a request.
--
googleProtobufEmpty
:: GoogleProtobufEmpty
googleProtobufEmpty = GoogleProtobufEmpty'
instance FromJSON GoogleProtobufEmpty where
parseJSON
= withObject "GoogleProtobufEmpty"
(\ o -> pure GoogleProtobufEmpty')
instance ToJSON GoogleProtobufEmpty where
toJSON = const emptyObject
-- | Information about the publisher.
--
-- /See:/ 'googleFactcheckingFactchecktoolsV1alpha1Publisher' smart constructor.
data GoogleFactcheckingFactchecktoolsV1alpha1Publisher =
GoogleFactcheckingFactchecktoolsV1alpha1Publisher'
{ _gffvpName :: !(Maybe Text)
, _gffvpSite :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'GoogleFactcheckingFactchecktoolsV1alpha1Publisher' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gffvpName'
--
-- * 'gffvpSite'
googleFactcheckingFactchecktoolsV1alpha1Publisher
:: GoogleFactcheckingFactchecktoolsV1alpha1Publisher
googleFactcheckingFactchecktoolsV1alpha1Publisher =
GoogleFactcheckingFactchecktoolsV1alpha1Publisher'
{_gffvpName = Nothing, _gffvpSite = Nothing}
-- | The name of this publisher. For instance, \"Awesome Fact Checks\".
gffvpName :: Lens' GoogleFactcheckingFactchecktoolsV1alpha1Publisher (Maybe Text)
gffvpName
= lens _gffvpName (\ s a -> s{_gffvpName = a})
-- | Host-level site name, without the protocol or \"www\" prefix. For
-- instance, \"awesomefactchecks.com\". This value of this field is based
-- purely on the claim review URL.
gffvpSite :: Lens' GoogleFactcheckingFactchecktoolsV1alpha1Publisher (Maybe Text)
gffvpSite
= lens _gffvpSite (\ s a -> s{_gffvpSite = a})
instance FromJSON
GoogleFactcheckingFactchecktoolsV1alpha1Publisher
where
parseJSON
= withObject
"GoogleFactcheckingFactchecktoolsV1alpha1Publisher"
(\ o ->
GoogleFactcheckingFactchecktoolsV1alpha1Publisher'
<$> (o .:? "name") <*> (o .:? "site"))
instance ToJSON
GoogleFactcheckingFactchecktoolsV1alpha1Publisher
where
toJSON
GoogleFactcheckingFactchecktoolsV1alpha1Publisher'{..}
= object
(catMaybes
[("name" .=) <$> _gffvpName,
("site" .=) <$> _gffvpSite])
-- | Information about the claim author.
--
-- /See:/ 'googleFactcheckingFactchecktoolsV1alpha1ClaimAuthor' smart constructor.
data GoogleFactcheckingFactchecktoolsV1alpha1ClaimAuthor =
GoogleFactcheckingFactchecktoolsV1alpha1ClaimAuthor'
{ _gffvcaSameAs :: !(Maybe Text)
, _gffvcaImageURL :: !(Maybe Text)
, _gffvcaName :: !(Maybe Text)
, _gffvcaJobTitle :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'GoogleFactcheckingFactchecktoolsV1alpha1ClaimAuthor' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gffvcaSameAs'
--
-- * 'gffvcaImageURL'
--
-- * 'gffvcaName'
--
-- * 'gffvcaJobTitle'
googleFactcheckingFactchecktoolsV1alpha1ClaimAuthor
:: GoogleFactcheckingFactchecktoolsV1alpha1ClaimAuthor
googleFactcheckingFactchecktoolsV1alpha1ClaimAuthor =
GoogleFactcheckingFactchecktoolsV1alpha1ClaimAuthor'
{ _gffvcaSameAs = Nothing
, _gffvcaImageURL = Nothing
, _gffvcaName = Nothing
, _gffvcaJobTitle = Nothing
}
-- | Corresponds to \`ClaimReview.itemReviewed.author.sameAs\`.
gffvcaSameAs :: Lens' GoogleFactcheckingFactchecktoolsV1alpha1ClaimAuthor (Maybe Text)
gffvcaSameAs
= lens _gffvcaSameAs (\ s a -> s{_gffvcaSameAs = a})
-- | Corresponds to \`ClaimReview.itemReviewed.author.image\`.
gffvcaImageURL :: Lens' GoogleFactcheckingFactchecktoolsV1alpha1ClaimAuthor (Maybe Text)
gffvcaImageURL
= lens _gffvcaImageURL
(\ s a -> s{_gffvcaImageURL = a})
-- | A person or organization stating the claim. For instance, \"John Doe\".
-- Corresponds to \`ClaimReview.itemReviewed.author.name\`.
gffvcaName :: Lens' GoogleFactcheckingFactchecktoolsV1alpha1ClaimAuthor (Maybe Text)
gffvcaName
= lens _gffvcaName (\ s a -> s{_gffvcaName = a})
-- | Corresponds to \`ClaimReview.itemReviewed.author.jobTitle\`.
gffvcaJobTitle :: Lens' GoogleFactcheckingFactchecktoolsV1alpha1ClaimAuthor (Maybe Text)
gffvcaJobTitle
= lens _gffvcaJobTitle
(\ s a -> s{_gffvcaJobTitle = a})
instance FromJSON
GoogleFactcheckingFactchecktoolsV1alpha1ClaimAuthor
where
parseJSON
= withObject
"GoogleFactcheckingFactchecktoolsV1alpha1ClaimAuthor"
(\ o ->
GoogleFactcheckingFactchecktoolsV1alpha1ClaimAuthor'
<$>
(o .:? "sameAs") <*> (o .:? "imageUrl") <*>
(o .:? "name")
<*> (o .:? "jobTitle"))
instance ToJSON
GoogleFactcheckingFactchecktoolsV1alpha1ClaimAuthor
where
toJSON
GoogleFactcheckingFactchecktoolsV1alpha1ClaimAuthor'{..}
= object
(catMaybes
[("sameAs" .=) <$> _gffvcaSameAs,
("imageUrl" .=) <$> _gffvcaImageURL,
("name" .=) <$> _gffvcaName,
("jobTitle" .=) <$> _gffvcaJobTitle])
-- | Information about a claim review.
--
-- /See:/ 'googleFactcheckingFactchecktoolsV1alpha1ClaimReview' smart constructor.
data GoogleFactcheckingFactchecktoolsV1alpha1ClaimReview =
GoogleFactcheckingFactchecktoolsV1alpha1ClaimReview'
{ _gLanguageCode :: !(Maybe Text)
, _gURL :: !(Maybe Text)
, _gTextualRating :: !(Maybe Text)
, _gTitle :: !(Maybe Text)
, _gPublisher :: !(Maybe GoogleFactcheckingFactchecktoolsV1alpha1Publisher)
, _gReviewDate :: !(Maybe DateTime')
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'GoogleFactcheckingFactchecktoolsV1alpha1ClaimReview' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gLanguageCode'
--
-- * 'gURL'
--
-- * 'gTextualRating'
--
-- * 'gTitle'
--
-- * 'gPublisher'
--
-- * 'gReviewDate'
googleFactcheckingFactchecktoolsV1alpha1ClaimReview
:: GoogleFactcheckingFactchecktoolsV1alpha1ClaimReview
googleFactcheckingFactchecktoolsV1alpha1ClaimReview =
GoogleFactcheckingFactchecktoolsV1alpha1ClaimReview'
{ _gLanguageCode = Nothing
, _gURL = Nothing
, _gTextualRating = Nothing
, _gTitle = Nothing
, _gPublisher = Nothing
, _gReviewDate = Nothing
}
-- | The language this review was written in. For instance, \"en\" or \"de\".
gLanguageCode :: Lens' GoogleFactcheckingFactchecktoolsV1alpha1ClaimReview (Maybe Text)
gLanguageCode
= lens _gLanguageCode
(\ s a -> s{_gLanguageCode = a})
-- | The URL of this claim review.
gURL :: Lens' GoogleFactcheckingFactchecktoolsV1alpha1ClaimReview (Maybe Text)
gURL = lens _gURL (\ s a -> s{_gURL = a})
-- | Textual rating. For instance, \"Mostly false\".
gTextualRating :: Lens' GoogleFactcheckingFactchecktoolsV1alpha1ClaimReview (Maybe Text)
gTextualRating
= lens _gTextualRating
(\ s a -> s{_gTextualRating = a})
-- | The title of this claim review, if it can be determined.
gTitle :: Lens' GoogleFactcheckingFactchecktoolsV1alpha1ClaimReview (Maybe Text)
gTitle = lens _gTitle (\ s a -> s{_gTitle = a})
-- | The publisher of this claim review.
gPublisher :: Lens' GoogleFactcheckingFactchecktoolsV1alpha1ClaimReview (Maybe GoogleFactcheckingFactchecktoolsV1alpha1Publisher)
gPublisher
= lens _gPublisher (\ s a -> s{_gPublisher = a})
-- | The date the claim was reviewed.
gReviewDate :: Lens' GoogleFactcheckingFactchecktoolsV1alpha1ClaimReview (Maybe UTCTime)
gReviewDate
= lens _gReviewDate (\ s a -> s{_gReviewDate = a}) .
mapping _DateTime
instance FromJSON
GoogleFactcheckingFactchecktoolsV1alpha1ClaimReview
where
parseJSON
= withObject
"GoogleFactcheckingFactchecktoolsV1alpha1ClaimReview"
(\ o ->
GoogleFactcheckingFactchecktoolsV1alpha1ClaimReview'
<$>
(o .:? "languageCode") <*> (o .:? "url") <*>
(o .:? "textualRating")
<*> (o .:? "title")
<*> (o .:? "publisher")
<*> (o .:? "reviewDate"))
instance ToJSON
GoogleFactcheckingFactchecktoolsV1alpha1ClaimReview
where
toJSON
GoogleFactcheckingFactchecktoolsV1alpha1ClaimReview'{..}
= object
(catMaybes
[("languageCode" .=) <$> _gLanguageCode,
("url" .=) <$> _gURL,
("textualRating" .=) <$> _gTextualRating,
("title" .=) <$> _gTitle,
("publisher" .=) <$> _gPublisher,
("reviewDate" .=) <$> _gReviewDate])
-- | Fields for an individual \`ClaimReview\` element. Except for
-- sub-messages that group fields together, each of these fields correspond
-- those in https:\/\/schema.org\/ClaimReview. We list the precise mapping
-- for each field.
--
-- /See:/ 'googleFactcheckingFactchecktoolsV1alpha1ClaimReviewMarkup' smart constructor.
data GoogleFactcheckingFactchecktoolsV1alpha1ClaimReviewMarkup =
GoogleFactcheckingFactchecktoolsV1alpha1ClaimReviewMarkup'
{ _gffvcrmRating :: !(Maybe GoogleFactcheckingFactchecktoolsV1alpha1ClaimRating)
, _gffvcrmClaimAuthor :: !(Maybe GoogleFactcheckingFactchecktoolsV1alpha1ClaimAuthor)
, _gffvcrmURL :: !(Maybe Text)
, _gffvcrmClaimAppearances :: !(Maybe [Text])
, _gffvcrmClaimLocation :: !(Maybe Text)
, _gffvcrmClaimFirstAppearance :: !(Maybe Text)
, _gffvcrmClaimDate :: !(Maybe Text)
, _gffvcrmClaimReviewed :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'GoogleFactcheckingFactchecktoolsV1alpha1ClaimReviewMarkup' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gffvcrmRating'
--
-- * 'gffvcrmClaimAuthor'
--
-- * 'gffvcrmURL'
--
-- * 'gffvcrmClaimAppearances'
--
-- * 'gffvcrmClaimLocation'
--
-- * 'gffvcrmClaimFirstAppearance'
--
-- * 'gffvcrmClaimDate'
--
-- * 'gffvcrmClaimReviewed'
googleFactcheckingFactchecktoolsV1alpha1ClaimReviewMarkup
:: GoogleFactcheckingFactchecktoolsV1alpha1ClaimReviewMarkup
googleFactcheckingFactchecktoolsV1alpha1ClaimReviewMarkup =
GoogleFactcheckingFactchecktoolsV1alpha1ClaimReviewMarkup'
{ _gffvcrmRating = Nothing
, _gffvcrmClaimAuthor = Nothing
, _gffvcrmURL = Nothing
, _gffvcrmClaimAppearances = Nothing
, _gffvcrmClaimLocation = Nothing
, _gffvcrmClaimFirstAppearance = Nothing
, _gffvcrmClaimDate = Nothing
, _gffvcrmClaimReviewed = Nothing
}
-- | Info about the rating of this claim review.
gffvcrmRating :: Lens' GoogleFactcheckingFactchecktoolsV1alpha1ClaimReviewMarkup (Maybe GoogleFactcheckingFactchecktoolsV1alpha1ClaimRating)
gffvcrmRating
= lens _gffvcrmRating
(\ s a -> s{_gffvcrmRating = a})
-- | Info about the author of this claim.
gffvcrmClaimAuthor :: Lens' GoogleFactcheckingFactchecktoolsV1alpha1ClaimReviewMarkup (Maybe GoogleFactcheckingFactchecktoolsV1alpha1ClaimAuthor)
gffvcrmClaimAuthor
= lens _gffvcrmClaimAuthor
(\ s a -> s{_gffvcrmClaimAuthor = a})
-- | This field is optional, and will default to the page URL. We provide
-- this field to allow you the override the default value, but the only
-- permitted override is the page URL plus an optional anchor link (\"page
-- jump\"). Corresponds to \`ClaimReview.url\`
gffvcrmURL :: Lens' GoogleFactcheckingFactchecktoolsV1alpha1ClaimReviewMarkup (Maybe Text)
gffvcrmURL
= lens _gffvcrmURL (\ s a -> s{_gffvcrmURL = a})
-- | A list of links to works in which this claim appears, aside from the one
-- specified in \`claim_first_appearance\`. Corresponds to
-- \`ClaimReview.itemReviewed[\'type=Claim].appearance.url\`.
gffvcrmClaimAppearances :: Lens' GoogleFactcheckingFactchecktoolsV1alpha1ClaimReviewMarkup [Text]
gffvcrmClaimAppearances
= lens _gffvcrmClaimAppearances
(\ s a -> s{_gffvcrmClaimAppearances = a})
. _Default
. _Coerce
-- | The location where this claim was made. Corresponds to
-- \`ClaimReview.itemReviewed.name\`.
gffvcrmClaimLocation :: Lens' GoogleFactcheckingFactchecktoolsV1alpha1ClaimReviewMarkup (Maybe Text)
gffvcrmClaimLocation
= lens _gffvcrmClaimLocation
(\ s a -> s{_gffvcrmClaimLocation = a})
-- | A link to a work in which this claim first appears. Corresponds to
-- \`ClaimReview.itemReviewed[\'type=Claim].firstAppearance.url\`.
gffvcrmClaimFirstAppearance :: Lens' GoogleFactcheckingFactchecktoolsV1alpha1ClaimReviewMarkup (Maybe Text)
gffvcrmClaimFirstAppearance
= lens _gffvcrmClaimFirstAppearance
(\ s a -> s{_gffvcrmClaimFirstAppearance = a})
-- | The date when the claim was made or entered public discourse.
-- Corresponds to \`ClaimReview.itemReviewed.datePublished\`.
gffvcrmClaimDate :: Lens' GoogleFactcheckingFactchecktoolsV1alpha1ClaimReviewMarkup (Maybe Text)
gffvcrmClaimDate
= lens _gffvcrmClaimDate
(\ s a -> s{_gffvcrmClaimDate = a})
-- | A short summary of the claim being evaluated. Corresponds to
-- \`ClaimReview.claimReviewed\`.
gffvcrmClaimReviewed :: Lens' GoogleFactcheckingFactchecktoolsV1alpha1ClaimReviewMarkup (Maybe Text)
gffvcrmClaimReviewed
= lens _gffvcrmClaimReviewed
(\ s a -> s{_gffvcrmClaimReviewed = a})
instance FromJSON
GoogleFactcheckingFactchecktoolsV1alpha1ClaimReviewMarkup
where
parseJSON
= withObject
"GoogleFactcheckingFactchecktoolsV1alpha1ClaimReviewMarkup"
(\ o ->
GoogleFactcheckingFactchecktoolsV1alpha1ClaimReviewMarkup'
<$>
(o .:? "rating") <*> (o .:? "claimAuthor") <*>
(o .:? "url")
<*> (o .:? "claimAppearances" .!= mempty)
<*> (o .:? "claimLocation")
<*> (o .:? "claimFirstAppearance")
<*> (o .:? "claimDate")
<*> (o .:? "claimReviewed"))
instance ToJSON
GoogleFactcheckingFactchecktoolsV1alpha1ClaimReviewMarkup
where
toJSON
GoogleFactcheckingFactchecktoolsV1alpha1ClaimReviewMarkup'{..}
= object
(catMaybes
[("rating" .=) <$> _gffvcrmRating,
("claimAuthor" .=) <$> _gffvcrmClaimAuthor,
("url" .=) <$> _gffvcrmURL,
("claimAppearances" .=) <$> _gffvcrmClaimAppearances,
("claimLocation" .=) <$> _gffvcrmClaimLocation,
("claimFirstAppearance" .=) <$>
_gffvcrmClaimFirstAppearance,
("claimDate" .=) <$> _gffvcrmClaimDate,
("claimReviewed" .=) <$> _gffvcrmClaimReviewed])
-- | Holds one or more instances of \`ClaimReview\` markup for a webpage.
--
-- /See:/ 'googleFactcheckingFactchecktoolsV1alpha1ClaimReviewMarkupPage' smart constructor.
data GoogleFactcheckingFactchecktoolsV1alpha1ClaimReviewMarkupPage =
GoogleFactcheckingFactchecktoolsV1alpha1ClaimReviewMarkupPage'
{ _gffvcrmpVersionId :: !(Maybe Text)
, _gffvcrmpPublishDate :: !(Maybe Text)
, _gffvcrmpName :: !(Maybe Text)
, _gffvcrmpClaimReviewAuthor :: !(Maybe GoogleFactcheckingFactchecktoolsV1alpha1ClaimReviewAuthor)
, _gffvcrmpPageURL :: !(Maybe Text)
, _gffvcrmpClaimReviewMarkups :: !(Maybe [GoogleFactcheckingFactchecktoolsV1alpha1ClaimReviewMarkup])
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'GoogleFactcheckingFactchecktoolsV1alpha1ClaimReviewMarkupPage' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gffvcrmpVersionId'
--
-- * 'gffvcrmpPublishDate'
--
-- * 'gffvcrmpName'
--
-- * 'gffvcrmpClaimReviewAuthor'
--
-- * 'gffvcrmpPageURL'
--
-- * 'gffvcrmpClaimReviewMarkups'
googleFactcheckingFactchecktoolsV1alpha1ClaimReviewMarkupPage
:: GoogleFactcheckingFactchecktoolsV1alpha1ClaimReviewMarkupPage
googleFactcheckingFactchecktoolsV1alpha1ClaimReviewMarkupPage =
GoogleFactcheckingFactchecktoolsV1alpha1ClaimReviewMarkupPage'
{ _gffvcrmpVersionId = Nothing
, _gffvcrmpPublishDate = Nothing
, _gffvcrmpName = Nothing
, _gffvcrmpClaimReviewAuthor = Nothing
, _gffvcrmpPageURL = Nothing
, _gffvcrmpClaimReviewMarkups = Nothing
}
-- | The version ID for this markup. Except for update requests, this field
-- is output-only and should not be set by the user.
gffvcrmpVersionId :: Lens' GoogleFactcheckingFactchecktoolsV1alpha1ClaimReviewMarkupPage (Maybe Text)
gffvcrmpVersionId
= lens _gffvcrmpVersionId
(\ s a -> s{_gffvcrmpVersionId = a})
-- | The date when the fact check was published. Similar to the URL,
-- semantically this is a page-level field, and each \`ClaimReview\` on
-- this page will contain the same value. Corresponds to
-- \`ClaimReview.datePublished\`
gffvcrmpPublishDate :: Lens' GoogleFactcheckingFactchecktoolsV1alpha1ClaimReviewMarkupPage (Maybe Text)
gffvcrmpPublishDate
= lens _gffvcrmpPublishDate
(\ s a -> s{_gffvcrmpPublishDate = a})
-- | The name of this \`ClaimReview\` markup page resource, in the form of
-- \`pages\/{page_id}\`. Except for update requests, this field is
-- output-only and should not be set by the user.
gffvcrmpName :: Lens' GoogleFactcheckingFactchecktoolsV1alpha1ClaimReviewMarkupPage (Maybe Text)
gffvcrmpName
= lens _gffvcrmpName (\ s a -> s{_gffvcrmpName = a})
-- | Info about the author of this claim review. Similar to the above,
-- semantically these are page-level fields, and each \`ClaimReview\` on
-- this page will contain the same values.
gffvcrmpClaimReviewAuthor :: Lens' GoogleFactcheckingFactchecktoolsV1alpha1ClaimReviewMarkupPage (Maybe GoogleFactcheckingFactchecktoolsV1alpha1ClaimReviewAuthor)
gffvcrmpClaimReviewAuthor
= lens _gffvcrmpClaimReviewAuthor
(\ s a -> s{_gffvcrmpClaimReviewAuthor = a})
-- | The URL of the page associated with this \`ClaimReview\` markup. While
-- every individual \`ClaimReview\` has its own URL field, semantically
-- this is a page-level field, and each \`ClaimReview\` on this page will
-- use this value unless individually overridden. Corresponds to
-- \`ClaimReview.url\`
gffvcrmpPageURL :: Lens' GoogleFactcheckingFactchecktoolsV1alpha1ClaimReviewMarkupPage (Maybe Text)
gffvcrmpPageURL
= lens _gffvcrmpPageURL
(\ s a -> s{_gffvcrmpPageURL = a})
-- | A list of individual claim reviews for this page. Each item in the list
-- corresponds to one \`ClaimReview\` element.
gffvcrmpClaimReviewMarkups :: Lens' GoogleFactcheckingFactchecktoolsV1alpha1ClaimReviewMarkupPage [GoogleFactcheckingFactchecktoolsV1alpha1ClaimReviewMarkup]
gffvcrmpClaimReviewMarkups
= lens _gffvcrmpClaimReviewMarkups
(\ s a -> s{_gffvcrmpClaimReviewMarkups = a})
. _Default
. _Coerce
instance FromJSON
GoogleFactcheckingFactchecktoolsV1alpha1ClaimReviewMarkupPage
where
parseJSON
= withObject
"GoogleFactcheckingFactchecktoolsV1alpha1ClaimReviewMarkupPage"
(\ o ->
GoogleFactcheckingFactchecktoolsV1alpha1ClaimReviewMarkupPage'
<$>
(o .:? "versionId") <*> (o .:? "publishDate") <*>
(o .:? "name")
<*> (o .:? "claimReviewAuthor")
<*> (o .:? "pageUrl")
<*> (o .:? "claimReviewMarkups" .!= mempty))
instance ToJSON
GoogleFactcheckingFactchecktoolsV1alpha1ClaimReviewMarkupPage
where
toJSON
GoogleFactcheckingFactchecktoolsV1alpha1ClaimReviewMarkupPage'{..}
= object
(catMaybes
[("versionId" .=) <$> _gffvcrmpVersionId,
("publishDate" .=) <$> _gffvcrmpPublishDate,
("name" .=) <$> _gffvcrmpName,
("claimReviewAuthor" .=) <$>
_gffvcrmpClaimReviewAuthor,
("pageUrl" .=) <$> _gffvcrmpPageURL,
("claimReviewMarkups" .=) <$>
_gffvcrmpClaimReviewMarkups])
-- | Response from listing \`ClaimReview\` markup.
--
-- /See:/ 'googleFactcheckingFactchecktoolsV1alpha1ListClaimReviewMarkupPagesResponse' smart constructor.
data GoogleFactcheckingFactchecktoolsV1alpha1ListClaimReviewMarkupPagesResponse =
GoogleFactcheckingFactchecktoolsV1alpha1ListClaimReviewMarkupPagesResponse'
{ _gffvlcrmprNextPageToken :: !(Maybe Text)
, _gffvlcrmprClaimReviewMarkupPages :: !(Maybe [GoogleFactcheckingFactchecktoolsV1alpha1ClaimReviewMarkupPage])
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'GoogleFactcheckingFactchecktoolsV1alpha1ListClaimReviewMarkupPagesResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gffvlcrmprNextPageToken'
--
-- * 'gffvlcrmprClaimReviewMarkupPages'
googleFactcheckingFactchecktoolsV1alpha1ListClaimReviewMarkupPagesResponse
:: GoogleFactcheckingFactchecktoolsV1alpha1ListClaimReviewMarkupPagesResponse
googleFactcheckingFactchecktoolsV1alpha1ListClaimReviewMarkupPagesResponse =
GoogleFactcheckingFactchecktoolsV1alpha1ListClaimReviewMarkupPagesResponse'
{ _gffvlcrmprNextPageToken = Nothing
, _gffvlcrmprClaimReviewMarkupPages = Nothing
}
-- | The next pagination token in the Search response. It should be used as
-- the \`page_token\` for the following request. An empty value means no
-- more results.
gffvlcrmprNextPageToken :: Lens' GoogleFactcheckingFactchecktoolsV1alpha1ListClaimReviewMarkupPagesResponse (Maybe Text)
gffvlcrmprNextPageToken
= lens _gffvlcrmprNextPageToken
(\ s a -> s{_gffvlcrmprNextPageToken = a})
-- | The result list of pages of \`ClaimReview\` markup.
gffvlcrmprClaimReviewMarkupPages :: Lens' GoogleFactcheckingFactchecktoolsV1alpha1ListClaimReviewMarkupPagesResponse [GoogleFactcheckingFactchecktoolsV1alpha1ClaimReviewMarkupPage]
gffvlcrmprClaimReviewMarkupPages
= lens _gffvlcrmprClaimReviewMarkupPages
(\ s a -> s{_gffvlcrmprClaimReviewMarkupPages = a})
. _Default
. _Coerce
instance FromJSON
GoogleFactcheckingFactchecktoolsV1alpha1ListClaimReviewMarkupPagesResponse
where
parseJSON
= withObject
"GoogleFactcheckingFactchecktoolsV1alpha1ListClaimReviewMarkupPagesResponse"
(\ o ->
GoogleFactcheckingFactchecktoolsV1alpha1ListClaimReviewMarkupPagesResponse'
<$>
(o .:? "nextPageToken") <*>
(o .:? "claimReviewMarkupPages" .!= mempty))
instance ToJSON
GoogleFactcheckingFactchecktoolsV1alpha1ListClaimReviewMarkupPagesResponse
where
toJSON
GoogleFactcheckingFactchecktoolsV1alpha1ListClaimReviewMarkupPagesResponse'{..}
= object
(catMaybes
[("nextPageToken" .=) <$> _gffvlcrmprNextPageToken,
("claimReviewMarkupPages" .=) <$>
_gffvlcrmprClaimReviewMarkupPages])
|
brendanhay/gogol
|
gogol-factchecktools/gen/Network/Google/FactCheckTools/Types/Product.hs
|
mpl-2.0
| 37,107 | 0 | 18 | 7,544 | 5,048 | 2,914 | 2,134 | 644 | 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.DLP.Projects.Locations.InspectTemplates.Get
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Gets an InspectTemplate. See
-- https:\/\/cloud.google.com\/dlp\/docs\/creating-templates to learn more.
--
-- /See:/ <https://cloud.google.com/dlp/docs/ Cloud Data Loss Prevention (DLP) API Reference> for @dlp.projects.locations.inspectTemplates.get@.
module Network.Google.Resource.DLP.Projects.Locations.InspectTemplates.Get
(
-- * REST Resource
ProjectsLocationsInspectTemplatesGetResource
-- * Creating a Request
, projectsLocationsInspectTemplatesGet
, ProjectsLocationsInspectTemplatesGet
-- * Request Lenses
, plitgXgafv
, plitgUploadProtocol
, plitgAccessToken
, plitgUploadType
, plitgName
, plitgCallback
) where
import Network.Google.DLP.Types
import Network.Google.Prelude
-- | A resource alias for @dlp.projects.locations.inspectTemplates.get@ method which the
-- 'ProjectsLocationsInspectTemplatesGet' request conforms to.
type ProjectsLocationsInspectTemplatesGetResource =
"v2" :>
Capture "name" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] GooglePrivacyDlpV2InspectTemplate
-- | Gets an InspectTemplate. See
-- https:\/\/cloud.google.com\/dlp\/docs\/creating-templates to learn more.
--
-- /See:/ 'projectsLocationsInspectTemplatesGet' smart constructor.
data ProjectsLocationsInspectTemplatesGet =
ProjectsLocationsInspectTemplatesGet'
{ _plitgXgafv :: !(Maybe Xgafv)
, _plitgUploadProtocol :: !(Maybe Text)
, _plitgAccessToken :: !(Maybe Text)
, _plitgUploadType :: !(Maybe Text)
, _plitgName :: !Text
, _plitgCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsLocationsInspectTemplatesGet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'plitgXgafv'
--
-- * 'plitgUploadProtocol'
--
-- * 'plitgAccessToken'
--
-- * 'plitgUploadType'
--
-- * 'plitgName'
--
-- * 'plitgCallback'
projectsLocationsInspectTemplatesGet
:: Text -- ^ 'plitgName'
-> ProjectsLocationsInspectTemplatesGet
projectsLocationsInspectTemplatesGet pPlitgName_ =
ProjectsLocationsInspectTemplatesGet'
{ _plitgXgafv = Nothing
, _plitgUploadProtocol = Nothing
, _plitgAccessToken = Nothing
, _plitgUploadType = Nothing
, _plitgName = pPlitgName_
, _plitgCallback = Nothing
}
-- | V1 error format.
plitgXgafv :: Lens' ProjectsLocationsInspectTemplatesGet (Maybe Xgafv)
plitgXgafv
= lens _plitgXgafv (\ s a -> s{_plitgXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
plitgUploadProtocol :: Lens' ProjectsLocationsInspectTemplatesGet (Maybe Text)
plitgUploadProtocol
= lens _plitgUploadProtocol
(\ s a -> s{_plitgUploadProtocol = a})
-- | OAuth access token.
plitgAccessToken :: Lens' ProjectsLocationsInspectTemplatesGet (Maybe Text)
plitgAccessToken
= lens _plitgAccessToken
(\ s a -> s{_plitgAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
plitgUploadType :: Lens' ProjectsLocationsInspectTemplatesGet (Maybe Text)
plitgUploadType
= lens _plitgUploadType
(\ s a -> s{_plitgUploadType = a})
-- | Required. Resource name of the organization and inspectTemplate to be
-- read, for example
-- \`organizations\/433245324\/inspectTemplates\/432452342\` or
-- projects\/project-id\/inspectTemplates\/432452342.
plitgName :: Lens' ProjectsLocationsInspectTemplatesGet Text
plitgName
= lens _plitgName (\ s a -> s{_plitgName = a})
-- | JSONP
plitgCallback :: Lens' ProjectsLocationsInspectTemplatesGet (Maybe Text)
plitgCallback
= lens _plitgCallback
(\ s a -> s{_plitgCallback = a})
instance GoogleRequest
ProjectsLocationsInspectTemplatesGet
where
type Rs ProjectsLocationsInspectTemplatesGet =
GooglePrivacyDlpV2InspectTemplate
type Scopes ProjectsLocationsInspectTemplatesGet =
'["https://www.googleapis.com/auth/cloud-platform"]
requestClient
ProjectsLocationsInspectTemplatesGet'{..}
= go _plitgName _plitgXgafv _plitgUploadProtocol
_plitgAccessToken
_plitgUploadType
_plitgCallback
(Just AltJSON)
dLPService
where go
= buildClient
(Proxy ::
Proxy ProjectsLocationsInspectTemplatesGetResource)
mempty
|
brendanhay/gogol
|
gogol-dlp/gen/Network/Google/Resource/DLP/Projects/Locations/InspectTemplates/Get.hs
|
mpl-2.0
| 5,502 | 0 | 15 | 1,145 | 701 | 412 | 289 | 108 | 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.Directory.ChromeosDevices.List
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Retrieve all Chrome OS Devices of a customer (paginated)
--
-- /See:/ <https://developers.google.com/admin-sdk/directory/ Admin Directory API Reference> for @directory.chromeosdevices.list@.
module Network.Google.Resource.Directory.ChromeosDevices.List
(
-- * REST Resource
ChromeosDevicesListResource
-- * Creating a Request
, chromeosDevicesList
, ChromeosDevicesList
-- * Request Lenses
, cdlOrderBy
, cdlCustomerId
, cdlSortOrder
, cdlQuery
, cdlProjection
, cdlPageToken
, cdlMaxResults
) where
import Network.Google.Directory.Types
import Network.Google.Prelude
-- | A resource alias for @directory.chromeosdevices.list@ method which the
-- 'ChromeosDevicesList' request conforms to.
type ChromeosDevicesListResource =
"admin" :>
"directory" :>
"v1" :>
"customer" :>
Capture "customerId" Text :>
"devices" :>
"chromeos" :>
QueryParam "orderBy" ChromeosDevicesListOrderBy :>
QueryParam "sortOrder" ChromeosDevicesListSortOrder
:>
QueryParam "query" Text :>
QueryParam "projection" ChromeosDevicesListProjection
:>
QueryParam "pageToken" Text :>
QueryParam "maxResults" (Textual Int32) :>
QueryParam "alt" AltJSON :>
Get '[JSON] ChromeOSDevices
-- | Retrieve all Chrome OS Devices of a customer (paginated)
--
-- /See:/ 'chromeosDevicesList' smart constructor.
data ChromeosDevicesList = ChromeosDevicesList'
{ _cdlOrderBy :: !(Maybe ChromeosDevicesListOrderBy)
, _cdlCustomerId :: !Text
, _cdlSortOrder :: !(Maybe ChromeosDevicesListSortOrder)
, _cdlQuery :: !(Maybe Text)
, _cdlProjection :: !(Maybe ChromeosDevicesListProjection)
, _cdlPageToken :: !(Maybe Text)
, _cdlMaxResults :: !(Maybe (Textual Int32))
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'ChromeosDevicesList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cdlOrderBy'
--
-- * 'cdlCustomerId'
--
-- * 'cdlSortOrder'
--
-- * 'cdlQuery'
--
-- * 'cdlProjection'
--
-- * 'cdlPageToken'
--
-- * 'cdlMaxResults'
chromeosDevicesList
:: Text -- ^ 'cdlCustomerId'
-> ChromeosDevicesList
chromeosDevicesList pCdlCustomerId_ =
ChromeosDevicesList'
{ _cdlOrderBy = Nothing
, _cdlCustomerId = pCdlCustomerId_
, _cdlSortOrder = Nothing
, _cdlQuery = Nothing
, _cdlProjection = Nothing
, _cdlPageToken = Nothing
, _cdlMaxResults = Nothing
}
-- | Column to use for sorting results
cdlOrderBy :: Lens' ChromeosDevicesList (Maybe ChromeosDevicesListOrderBy)
cdlOrderBy
= lens _cdlOrderBy (\ s a -> s{_cdlOrderBy = a})
-- | Immutable id of the Google Apps account
cdlCustomerId :: Lens' ChromeosDevicesList Text
cdlCustomerId
= lens _cdlCustomerId
(\ s a -> s{_cdlCustomerId = a})
-- | Whether to return results in ascending or descending order. Only of use
-- when orderBy is also used
cdlSortOrder :: Lens' ChromeosDevicesList (Maybe ChromeosDevicesListSortOrder)
cdlSortOrder
= lens _cdlSortOrder (\ s a -> s{_cdlSortOrder = a})
-- | Search string in the format given at
-- http:\/\/support.google.com\/chromeos\/a\/bin\/answer.py?hl=en&answer=1698333
cdlQuery :: Lens' ChromeosDevicesList (Maybe Text)
cdlQuery = lens _cdlQuery (\ s a -> s{_cdlQuery = a})
-- | Restrict information returned to a set of selected fields.
cdlProjection :: Lens' ChromeosDevicesList (Maybe ChromeosDevicesListProjection)
cdlProjection
= lens _cdlProjection
(\ s a -> s{_cdlProjection = a})
-- | Token to specify next page in the list
cdlPageToken :: Lens' ChromeosDevicesList (Maybe Text)
cdlPageToken
= lens _cdlPageToken (\ s a -> s{_cdlPageToken = a})
-- | Maximum number of results to return. Default is 100
cdlMaxResults :: Lens' ChromeosDevicesList (Maybe Int32)
cdlMaxResults
= lens _cdlMaxResults
(\ s a -> s{_cdlMaxResults = a})
. mapping _Coerce
instance GoogleRequest ChromeosDevicesList where
type Rs ChromeosDevicesList = ChromeOSDevices
type Scopes ChromeosDevicesList =
'["https://www.googleapis.com/auth/admin.directory.device.chromeos",
"https://www.googleapis.com/auth/admin.directory.device.chromeos.readonly"]
requestClient ChromeosDevicesList'{..}
= go _cdlCustomerId _cdlOrderBy _cdlSortOrder
_cdlQuery
_cdlProjection
_cdlPageToken
_cdlMaxResults
(Just AltJSON)
directoryService
where go
= buildClient
(Proxy :: Proxy ChromeosDevicesListResource)
mempty
|
rueshyna/gogol
|
gogol-admin-directory/gen/Network/Google/Resource/Directory/ChromeosDevices/List.hs
|
mpl-2.0
| 5,772 | 0 | 21 | 1,436 | 818 | 473 | 345 | 120 | 1 |
module Handler.BrowsePageSpec (spec) where
import TestImport
spec :: Spec
spec = withApp $ do
describe "getBrowsePageR" $ do
error "Spec not implemented: getBrowsePageR"
|
learnyou/lypaste
|
test/Handler/BrowsePageSpec.hs
|
agpl-3.0
| 186 | 0 | 11 | 39 | 44 | 23 | 21 | 6 | 1 |
{- arch-tag: AnyDBM tests main file
Copyright (C) 2004-2005 John Goerzen <[email protected]>
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-}
module AnyDBMtest(mf, generic_persist_test, generic_test, tests) where
import Test.HUnit
import Data.List.Utils
import System.IO.HVFS
import System.IO.HVFS.InstanceHelpers
import Database.AnyDBM
import Database.AnyDBM.StringDBM
import Database.AnyDBM.MapDBM
import System.Directory
import System.IO.HVFS.Utils
import System.FilePath
import Data.HashTable
import Data.List(sort)
import Control.Exception(finally)
mf :: AnyDBM a => IO b -> (b -> IO a) -> String -> (a -> Assertion) -> Test
mf initfunc openfunc msg code =
TestLabel msg $ TestCase $ do i <- initfunc
h <- openfunc i
finally (code h) (closeA h)
infix 1 @>=?
(@>=?) :: (Eq a, Show a) => a -> IO a -> Assertion
(@>=?) exp res = do r <- res
exp @=? r
deleteall h = do k <- keysA h
mapM_ (deleteA h) k
[] @>=? keysA h
weirdl = sort $ [("", "empty"),
("foo\nbar", "v1\0v2"),
("v3,v4", ""),
("k\0ey", "\xFF")]
createdir = TestCase $ createDirectory "testtmp"
removedir = TestCase $ recursiveRemove SystemFS "testtmp"
generic_test initfunc openfunc =
let f = mf initfunc openfunc in
[
createdir
,f "empty" $ \h -> do [] @>=? keysA h
[] @>=? valuesA h
[] @>=? toListA h
Nothing @>=? lookupA h "foo"
,f "basic" $ \h -> do insertA h "key" "value"
(Just "value") @>=? lookupA h "key"
[("key", "value")] @>=? toListA h
insertA h "key" "v2"
[("key", "v2")] @>=? toListA h
deleteA h "key"
[] @>=? toListA h
,f "mult" $ \h -> do insertListA h [("1", "2"), ("3", "4"), ("5", "6")]
[("1", "2"), ("3", "4"), ("5", "6")] @>=?
(toListA h >>= return . sort)
["1", "3", "5"] @>=? (keysA h >>= return . sort)
["2", "4", "6"] @>=? (valuesA h >>= return . sort)
deleteall h
,f "weirdchars" $ \h -> do insertListA h weirdl
weirdl @>=? (toListA h >>= return . sort)
deleteall h
,removedir
]
generic_persist_test initfunc openfunc =
let f = mf initfunc openfunc in
[
createdir
,f "empty" deleteall
,f "weirdpop" $ \h -> insertListA h weirdl
,f "weirdcheck" $ \h -> do weirdl @>=? (toListA h >>= return . sort)
deleteall h
insertA h "key" "value"
,f "step3" $ \h -> do [("key", "value")] @>=? (toListA h >>= return . sort)
insertA h "key" "v2"
insertA h "z" "y"
,f "step4" $ \h -> do [("key", "v2"), ("z", "y")] @>=?
(toListA h >>= return . sort)
,f "cleanupdb" deleteall
,removedir
]
test_hashtable = generic_test (return ())
(\_ -> ((new (==) hashString)::IO (HashTable String String)))
test_mapdbm = generic_test (return ())
(\_ -> newMapDBM)
test_stringdbm = generic_persist_test (return SystemFS)
(\f -> openStringVDBM f (joinPath ["testtmp", "StringDBM"]) ReadWriteMode)
++
generic_test (return SystemFS)
(\f -> openStringVDBM f (joinPath ["testtmp", "StringDBM"]) ReadWriteMode)
tests = TestList [TestLabel "HashTable" (TestList test_hashtable),
TestLabel "StringDBM" (TestList test_stringdbm),
TestLabel "MapDBM" (TestList test_mapdbm)
]
|
jgoerzen/anydbm
|
testsrc/AnyDBMtest.hs
|
lgpl-2.1
| 4,744 | 0 | 16 | 1,757 | 1,264 | 656 | 608 | 85 | 1 |
module Claim where
import Text.Parsec hiding (upper,lower)
import Text.Parsec.String
parse s = Text.Parsec.parse claim "<>" s
-- | specification: http://cbr.uibk.ac.at/competition/rules.php
data Claim = MAYBE
| WORST_CASE (Quest Lower) (Quest Upper)
| YES
| NO
data Quest a = None | Some a
data Lower = Omega Integer | NON_POLY
data Upper = O Integer | POLY
instance Show Upper where
show POLY = "POLY"
show (O n) = "O(n^" ++ show n ++ ")"
instance Show Lower where
show NON_POLY = "NON_POLY"
show (Omega n) = "Omega(n^" ++ show n ++ ")"
instance Show a => Show (Quest a) where
show None = "?"
show (Some a) = show a
instance Show Claim where
show MAYBE = "MAYBE"
show (WORST_CASE lo up) = "WORST_CASE(" ++ show lo ++ "," ++ show up ++ ")"
show YES = "YES"
show NO = "NO"
claim :: Parser Claim
claim = spaces *> (
( reserved "MAYBE" *> return MAYBE )
<|> ( reserved "YES" *> return YES )
<|> ( reserved "NO" *> return NO )
<|> ( reserved "WORST_CASE" *> parens ( WORST_CASE <$> quest lower <*> (comma *> quest upper) ) )
) <* eof
quest p = ( reserved "?" >> return None ) <|> ( Some <$> p )
lower = ( reserved "NON_POLY" *> return NON_POLY )
<|> ( reserved "Omega" *> ( Omega <$> parens degree ) )
upper = ( reserved "POLY" *> return POLY )
<|> ( reserved "O" *> (O <$> parens degree ) )
degree = ( reserved "1" *> return 0 )
<|> ( reserved "n" >> reserved "^" *> natural )
reserved :: String -> Parser String
reserved s = string s <* spaces
comma :: Parser String
comma = reserved ","
parens :: Parser r -> Parser r
parens p = reserved "(" *> p <* reserved ")"
natural :: Parser Integer
natural = foldr1 (\ x y -> 10*x+y)
<$> many1 ( ( \ c -> fromIntegral $ fromEnum c - fromEnum '0') <$> digit )
|
jwaldmann/ceta-postproc
|
src/Claim.hs
|
lgpl-3.0
| 1,777 | 0 | 16 | 417 | 727 | 368 | 359 | 48 | 1 |
import Data.List (genericIndex)
trees :: [Integer]
trees = 1 : 1 : 2 : map f [3..]
where f n = sum $ map (\x -> (trees !! (pred x)) * (trees !! (n - x))) [1..n]
answer = flip mod 100000007 . (!!) trees
main = do
t <- readLn
c <- getContents
putStr . unlines . map show . map answer . map read . take t $ lines c
|
itsbruce/hackerrank
|
func/memo/numberOfBSTs.hs
|
unlicense
| 329 | 0 | 15 | 89 | 187 | 95 | 92 | 9 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module OmekaIpsum.Options
( options
, execParser
) where
import qualified Data.ByteString.UTF8 as B8
import qualified Data.Text as T
import Data.Version
import Options.Applicative
import OmekaIpsum.Types
import Paths_omeka_ipsum
versionStr :: String
versionStr = showVersion version
authOptions' :: Parser (Maybe OmekaAuth)
authOptions' = liftA2 OmekaAuth
<$> optional (option (return . B8.fromString)
( short 'u' <> long "user"
<> help "The Omeka admin user name."))
<*> optional (option (return . B8.fromString)
( short 'p' <> long "password"
<> help "The Omeka admin password."))
configOptions' :: Parser OIOptions
configOptions' = Config
<$> authOptions'
configOptions :: ParserInfo OIOptions
configOptions =
info (helper <*> configOptions')
( fullDesc
<> progDesc "Dump a sample, default configuration file.")
generateOptions' :: Parser OIOptions
generateOptions' = Generate
<$> authOptions'
<*> optional (strOption ( short 'c' <> long "config" <> metavar "CONFIG_FILE"
<> help "A configuration file."))
<*> option auto ( short 'n' <> long "n" <> metavar "COUNT"
<> help "The number of Omeka items to generate.")
generateOptions :: ParserInfo OIOptions
generateOptions =
info (helper <*> generateOptions')
( fullDesc
<> progDesc "Generate random data and insert it into Omeka.")
options' :: Parser OIOptions
options' = subparser ( command "config" configOptions
<> command "generate" generateOptions
)
options :: ParserInfo OIOptions
options = info (helper <*> options')
( fullDesc
<> progDesc "Generates random content for testing Omeka themes and plugins."
<> header ("omeka-ipsum " ++ versionStr ++ " Random item generator.")
)
|
erochest/omeka-ipsum
|
src/OmekaIpsum/Options.hs
|
apache-2.0
| 2,212 | 0 | 14 | 773 | 439 | 225 | 214 | 48 | 1 |
{-# LANGUAGE ExistentialQuantification, GADTs #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE ParallelListComp #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-} -- for debugging
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
-- | An implementation of concurrent finite maps based on skip lists. Only
-- supports lookup and insertions, not modifications or removals.
--
-- Skip lists are a probabilistic data structure that roughly approximate
-- balanced trees. At the bottom layer is a standard linked list representation
-- of a finite map. Above this is some number of "index" lists that provide
-- shortcuts to the layer below them. When a key/value pair is added, it is
-- always added to the bottom layer, and is added with exponentially decreasing
-- probability to each index layer above it.
--
-- Skip lists are a very good match for lock-free programming, since the
-- linearization point can be taken as insertion into the bottom list, and index
-- nodes can be added *afterward* in a best-effort style (i.e., if there is
-- contention to add them, we can simply walk away, with the effect that the
-- probability of appearing in an index is partly a function of contention.)
--
-- To implement skip lists in Haskell, we use a GADT to represent the layers,
-- each of which has a different type (since it indexes the layer below it).
module Data.Concurrent.SkipListMap (
SLMap(), newSLMap, find, PutResult(..), putIfAbsent, putIfAbsentToss, foldlWithKey, counts,
-- map: is not exposed, because it has that FINISHME for now... [2013.10.01]
debugShow,
-- * Slicing SLMaps
SLMapSlice(Slice), toSlice, splitSlice, sliceSize
)
where
import Control.Monad
import Control.Monad.IO.Class
import Control.Exception (assert)
import Data.Concurrent.Internal.MonadToss
-- import Control.LVish (Par)
-- import Control.LVish.Unsafe () -- FOR MonadIO INSTANCE! FIXME. We can't keep this from escaping.
import Data.Maybe (fromMaybe)
import Data.IORef
import qualified Data.Concurrent.LinkedMap as LM
import Prelude hiding (map)
import qualified Prelude as P
import qualified Data.Concurrent.Map.Class as C
--------------------------------------------------------------------------------
-- | The GADT representation. The type @t@ gives the type of nodes at a given
-- level in the skip list.
data SLMap_ k v t where
Bottom :: LM.LMap k v -> SLMap_ k v (LM.LMap k v)
Index :: LM.LMap k (t, v) -> SLMap_ k v t -> SLMap_ k v (LM.LMap k (t, v))
-- The complete multi-level SLMap always keeps a pointer to the bottom level (the
-- second field).
data SLMap k v = forall t. SLMap (SLMap_ k v t) (LM.LMap k v)
-- | A portion of an SLMap between two keys. If the upper-bound is missing, that
-- means "go to the end". The optional lower bound is used to "lazily" prune the
-- fronts each layer. The reason for this is that we don't want to reallocate an
-- IORef spine and prematurely prune all lower layers IF we're simply going to
-- split again before actually enumerating the contents.
data SLMapSlice k v = Slice (SLMap k v)
!(Maybe k) -- Lower bound.
!(Maybe k) -- Upper bound.
-- | Physical identity
instance Eq (SLMap k v) where
SLMap _ lm1 == SLMap _ lm2 = lm1 == lm2
-- | Create a new skip list with the given number of levels.
newSLMap :: Int -> IO (SLMap k v)
newSLMap 0 = do
lm <- LM.newLMap
return $ SLMap (Bottom lm) lm
newSLMap n = do
SLMap slm lmBottom <- newSLMap (n-1)
lm <- LM.newLMap
return $ SLMap (Index lm slm) lmBottom
-- | Attempt to locate a key in the map.
find :: Ord k => SLMap k v -> k -> IO (Maybe v)
find (SLMap slm _) k = find_ slm Nothing k
-- Helper for @find@.
find_ :: Ord k => SLMap_ k v t -> Maybe t -> k -> IO (Maybe v)
-- At the bottom level: just lift the find from LinkedMap
find_ (Bottom m) shortcut k = do
searchResult <- LM.find (fromMaybe m shortcut) k
case searchResult of
LM.Found v -> return $ Just v
LM.NotFound _tok -> return Nothing
-- At an indexing level: attempt to use the index to shortcut into the level
-- below.
find_ (Index m slm) shortcut k = do
searchResult <- LM.find (fromMaybe m shortcut) k
case searchResult of
LM.Found (_, v) ->
return $ Just v -- the key is in the index itself; we're outta here
LM.NotFound tok -> case LM.value tok of
Just (m', _) -> find_ slm (Just m') k -- there's an index node
-- preceeding our key; use it to
-- shortcut into the level below.
Nothing -> find_ slm Nothing k -- no smaller key in the index,
-- so start at the beginning of
-- the level below.
data PutResult v = Added v | Found v
-- {-# SPECIALIZE putIfAbsent :: (Ord k) => SLMap k v -> k -> Par e s v -> Par e s (PutResult v) #-}
{-# INLINABLE putIfAbsent_ #-}
-- | Adds a key/value pair if the key is not present, all within a given monad.
-- Returns the value now associated with the key in the map.
putIfAbsent :: (Ord k, MonadIO m, MonadToss m) =>
SLMap k v -- ^ The map
-> k -- ^ The key to lookup/insert
-> m v -- ^ A computation of the value to insert
-> m (PutResult v)
putIfAbsent (SLMap slm _) k vc =
putIfAbsent_ slm Nothing k vc toss $ \_ _ -> return ()
-- {-# SPECIALIZE putIfAbsentToss :: (Ord k) => SLMap k v -> k -> Par e s v -> Par e s Bool -> Par e s (PutResult v) #-}
{-# INLINABLE putIfAbsentToss #-}
-- | Adds a key/value pair if the key is not present, all within a given monad.
-- Returns the value now associated with the key in the map.
putIfAbsentToss :: (Ord k, MonadIO m) => SLMap k v -- ^ The map
-> k -- ^ The key to lookup/insert
-> m v -- ^ A computation of the value to insert
-> m Bool -- ^ An explicit, thread-local coin to toss
-> m (PutResult v)
putIfAbsentToss (SLMap slm _) k vc coin =
putIfAbsent_ slm Nothing k vc coin $ \_ _ -> return ()
-- Helper for putIfAbsent
putIfAbsent_ :: (Ord k, MonadIO m) =>
SLMap_ k v t -- ^ The map
-> Maybe t -- ^ A shortcut into this skiplist level
-> k -- ^ The key to lookup/insert
-> m v -- ^ A computation of the value to insert
-> m Bool -- ^ A (thread-local) coin tosser
-> (t -> v -> m ()) -- ^ A thunk for inserting into the higher
-- levels of the skiplist
-> m (PutResult v)
-- At the bottom level, we use a retry loop around the find/tryInsert functions
-- provided by LinkedMap
putIfAbsent_ (Bottom m) shortcut k vc0 _coin install = retryLoop vc0 where
-- The retry loop; ensures that vc is only executed once
retryLoop vc = do
searchResult <- liftIO $ LM.find (fromMaybe m shortcut) k
case searchResult of
LM.Found v -> return $ Found v
LM.NotFound tok -> do
v <- vc
maybeMap <- liftIO $ LM.tryInsert tok v
case maybeMap of
Just m' -> do
install m' v -- all set on the bottom level, now try indices
return $ Added v
Nothing -> retryLoop $ return v -- next time around, remember the value to insert
-- At an index level; try to shortcut into the level below, while remembering
-- where we were so that we can insert index nodes later on
putIfAbsent_ (Index m slm) shortcut k vc coin install = do
searchResult <- liftIO $ LM.find (fromMaybe m shortcut) k
case searchResult of
LM.Found (_, v) -> return $ Found v -- key is in the index; bail out
LM.NotFound tok ->
let install' mBelow v = do -- to add an index node here,
shouldAdd <- coin -- first, see if we (probabilistically) should
when shouldAdd $ do
maybeHere <- liftIO $ LM.tryInsert tok (mBelow, v) -- then, try it!
case maybeHere of
Just mHere -> install mHere v -- if we succeed, keep inserting
-- into the levels above us
Nothing -> return () -- otherwise, oh well; we tried.
in case LM.value tok of
Just (m', _) -> putIfAbsent_ slm (Just m') k vc coin install'
Nothing -> putIfAbsent_ slm Nothing k vc coin install'
-- | Concurrently fold over all key/value pairs in the map within the given
-- monad, in increasing key order. Inserts that arrive concurrently may or may
-- not be included in the fold.
--
-- Strict in the accumulator.
foldlWithKey :: Monad m => (forall x . IO x -> m x) ->
(a -> k -> v -> m a) -> a -> SLMap k v -> m a
foldlWithKey liftio f !a (SLMap _ !lm) = LM.foldlWithKey liftio f a lm
-- | Create an identical copy of an (unchanging) SLMap with the keys unchanged and
-- the values replaced by the result of applying the provided function.
-- map :: MonadIO m => (a -> b) -> SLMap k a -> m (SLMap k b)
_map :: MonadIO m => (a -> a) -> SLMap k a -> m (SLMap k a)
_map fn (SLMap (Bottom lm) _lm2) = do
lm' <- LM.map fn lm
return$! SLMap (Bottom lm') lm'
_map fn (SLMap (Index lm slm) lmbot) = do
SLMap _slm2 _bot2 <- _map fn (SLMap slm lmbot)
_lm2 <- LM.map (\(t,a) -> (t,fn a)) lm
error "FINISHME -- SkipListMap.map"
-- return$! SLMap (Index lm2 slm2) bot2
-- | Returns the sizes of the skiplist levels; for performance debugging.
counts :: SLMap k v -> IO [Int]
counts (SLMap slm _) = counts_ slm
counts_ :: SLMap_ k v t -> IO [Int]
counts_ (Bottom m) = do
c <- LM.foldlWithKey id (\n _ _ -> return (n+1)) 0 m
return [c]
counts_ (Index m slm) = do
c <- LM.foldlWithKey id (\n _ _ -> return (n+1)) 0 m
cs <- counts_ slm
return $ c:cs
-- | Create a slice corresponding to the entire (non-empty) map.
toSlice :: SLMap k v -> SLMapSlice k v
toSlice mp = Slice mp Nothing Nothing
instance Show (LM.LMap k v) where
show _ = "<LinkedMap>"
instance Show (LM.LMList k v) where
show _ = "<LinkedMapList>"
-- | Attempt to split a slice of an SLMap. If there are not enough elements to form
-- two slices, this retruns Nothing.
splitSlice :: forall k v . (Show k, Ord k) =>
SLMapSlice k v -> IO (Maybe (SLMapSlice k v, SLMapSlice k v))
splitSlice sl0@(Slice (SLMap index lmbot) mstart mend) = do
res <- loop index
case res of
Just (x,y) -> do sz1 <- fmap (P.map fst) $ sliceToList sl0
sz2 <- fmap (P.map fst) $ sliceToList x
sz3 <- fmap (P.map fst) $ sliceToList y
putStrLn $ "Splitslice! size " ++(show sz1) ++" out szs "++(show (sz2,sz3))
++ " mstart/end "++show (mstart,mend)
Nothing -> return ()
return res
where
loop :: SLMap_ k v t -> IO (Maybe (SLMapSlice k v, SLMapSlice k v))
loop (Bottom (LM.LMap lm)) = do
putStrLn "AT BOT"
lm' <- readIORef lm
lm'' <- case mstart of
Nothing -> return lm'
Just strtK -> LM.dropUntil strtK lm'
res <- LM.halve mend lm''
-- DEBUG:
putStrLn $ "halve RES -> "++show res
case res of
Nothing -> return Nothing
Just x -> dosplit (SLMap (Bottom (LM.LMap lm)) (LM.LMap lm))
(\ tlboxed -> SLMap (Bottom tlboxed) tlboxed) x
loop orig@(Index (LM.LMap m) slm) = do
indm <- readIORef m
indm' <- case mstart of
Nothing -> return indm
Just strtK -> LM.dropUntil strtK indm
-- Halve *this* level of the index, and use that as a fast way to split everything below.
res <- LM.halve mend indm'
case res of
-- Case 1: This level isn't big enough to split, keep going down. Note that we don't
-- reconstruct the higher level, for splitting we don't care about it:
Nothing -> loop slm
-- Case 2: Do the split but use the full lmbot on the right
-- (lazy pruning of the head elements):
Just x -> dosplit (SLMap orig lmbot)
(\ tlboxed -> SLMap (Index tlboxed slm) lmbot) x
-- Create the left and right slices when halving is successful.
dosplit :: SLMap k v -> (LM.LMap k tmp -> SLMap k v) ->
(Int, Int, LM.LMList k tmp) ->
IO (Maybe (SLMapSlice k v, SLMapSlice k v))
dosplit lmap mkRight (lenL, lenR, tlseg) =
assert (lenL > 0) $ assert (lenR > 0) $ do
putStrLn $ "Halved lengths "++show (lenL,lenR)
-- We don't really want to allocate just for slicing... but alas we need new
-- IORef boxes here. We lazily prune the head of the lower levels, but we
-- don't want to throw away the work we've done traversing to this point in "loop":
tlboxed <- newIORef tlseg
_tmp <- fmap length $ LM.toList (LM.LMap tlboxed)
let (LM.Node tlhead _ _) = tlseg
rmap = mkRight (LM.LMap tlboxed )
rslice = Slice rmap (Just tlhead) mend
lslice = Slice lmap Nothing (Just tlhead)
return $! Just $! (lslice, rslice)
-- | /O(N)/ measure the length of the bottom tier.
sliceSize :: Ord k => SLMapSlice k v -> IO Int
sliceSize slc = do
ls <- sliceToList slc
return $! length ls
sliceToList :: Ord k => SLMapSlice k v -> IO [(k,v)]
sliceToList (Slice (SLMap _ lmbot) mstart mend) = do
ls <- LM.toList lmbot
-- We SHOULD use the index layers to shortcut to a start, then stop at the end.
return $! [ pr | pr@(k,_v) <- ls, strtCheck k, endCheck k ] -- Inefficient!
where
strtCheck = case mstart of
Just strt -> \ k -> k >= strt
Nothing -> \ _ -> True
endCheck = case mend of
Just end -> \ k -> k < end
Nothing -> \ _ -> True
-- | Print a slice with each layer on a line.
debugShow :: forall k v . (Ord k, Show k, Show v) => SLMapSlice k v -> IO String
debugShow (Slice (SLMap index _lmbot) mstart mend) =
do lns <- loop index
let len = length lns
return $ unlines [ "["++show i++"] "++l | l <- lns | i <- reverse [0::Int ..len-1] ]
where
startCheck = case mstart of
Just start -> \ k -> k >= start
Nothing -> \ _ -> True
endCheck = case mend of
Just end -> \ k -> k < end
Nothing -> \ _ -> True
loop :: SLMap_ k v t -> IO [String]
loop (Bottom lm) = do
ls <- LM.toList lm
return [ unwords $ [ if endCheck k && startCheck k
then show i++":"++show k++","++show v
else "_"
| i <- [0::Int ..]
| (k,v) <- ls
-- , startCheck k
] ]
loop (Index indm slm) = do
ls <- LM.toList indm
strs <- forM [ (i,tup) | i <- [(0::Int)..] | tup@(_k,_) <- ls ] $ -- , startCheck k
\ (ix, (key, (_shortcut::t, val))) -> do
-- Peek at the next layer down:
{-
case (slm::SLMap_ k v t) of
Index (nxt::LM.LMap k (t2,v)) _ -> do
-- Could not deduce (t3 ~ IORef (LM.LMList k (t3, v)))
lmlst <- readIORef nxt
LM.findIndex lmlst lmlst
-- Bottom x -> x
-}
if endCheck key && startCheck key
then return $ show ix++":"++show key++","++show val
else return "_"
rest <- loop slm
return $ unwords strs : rest
--------------------------------------------------------------------------------
defaultLevels :: Int
defaultLevels = 8
-- | SLMap's can provide an instance of the generic concurrent map interface.
instance C.ConcurrentInsertMap SLMap where
type Key SLMap k = (Ord k)
-- type Key SLMap = Ord
{-# INLINABLE new #-}
new = newSLMap defaultLevels
{-# INLINABLE newSized #-}
-- Here we base the number of index levels on the expected size:
newSized n = newSLMap (ceiling (logBase 2 (fromIntegral n) :: Double))
{-# INLINABLE insert #-}
insert mp k v = do
res <- putIfAbsent mp k (return v)
case res of
Added _ -> return ()
Found _ -> error "Could not insert into SLMap, key already present!"
{-# INLINABLE lookup #-}
lookup = find
-- | This is an O(N) estimateSize:
estimateSize (SLMap _ bot) = C.estimateSize bot
|
rrnewton/concurrent-skiplist
|
src/Data/Concurrent/SkipListMap.hs
|
apache-2.0
| 16,650 | 4 | 24 | 5,018 | 4,115 | 2,091 | 2,024 | 245 | 7 |
{-# LANGUAGE DeriveDataTypeable #-}
module MapGen.IO
(
ImageFormat(..)
, toFile
, renderKdTree
)
where
import MapGen.Floor
import MapGen.KdTree as KdTree
import MapGen.Space
import Data.Data
import Control.Monad.ST
import Graphics.Rendering.Cairo
import Prelude as P
data ImageFormat = SVG | PNG deriving (Data, Typeable, Show)
toFile :: FilePath -> ImageFormat -> KdTree -> Width -> Height
-> [Render ()]
-> IO ()
toFile file' format kdt w h renderDecorations =
let w' = fromIntegral w
h' = fromIntegral h
file = file' ++ case format of SVG -> ".svg"; PNG -> ".png"
renderImage = do
render w' h' kdt
sequence_ renderDecorations
in case format of
SVG -> withSVGSurface file (w'*0.8) (h'*0.8) $ flip renderWith $ renderImage
PNG -> withImageSurface FormatRGB24 w h $ \surface -> do
renderWith surface renderImage
surfaceWriteToPNG surface file
render :: Double -> Double -> KdTree -> Render ()
render w h kdt = do
-- Background
setSourceRGB 0 0 0
rectangle 0 0 w h
fill
-- Line configuration
setLineWidth 1
-- Render kd-tree
renderKdTree kdt
renderKdTree :: KdTree -> Render ()
renderKdTree = KdTree.mapM_ r
where r (Leaf q) = do setSourceRGB 0.5 0.5 0.5; renderQuad q
r (Node l c1 c2) = do
setSourceRGB 1 1 1
renderQuad $ Quad (o l) (d l)
coords :: Line -> (Double, Double, Double, Double)
coords (Line (Vec2 x1 y1) (Vec2 x2 y2)) =
(fromIntegral x1, fromIntegral y1
,fromIntegral x2, fromIntegral y2)
renderQuad :: Quad -> Render ()
renderQuad (Quad (Vec2 x1 y1) (Vec2 x2 y2)) = do
let w = x2-x1+1; h = y2-y1+1
rectangle (db x1) (db y1) (db w) (db h)
fill
db = fromIntegral
|
jeannekamikaze/mapgen
|
MapGen/IO.hs
|
bsd-2-clause
| 1,922 | 0 | 14 | 616 | 676 | 342 | 334 | 52 | 3 |
module Data.PGN (
PGN(..),
Result(..),
pgnParser,
showPgn,
-- resultOrMoveParser should only be exposed in an internals-only module?
resultOrMoveParser
) where
import Control.Applicative hiding (many, optional, (<|>))
import Control.Arrow
import Control.Monad
import Data.Char
import Data.List
import Data.List.Split
import Data.Maybe
import Data.SAN
import Text.Parsec as P
import Text.Parsec.Language (emptyDef)
import qualified Text.Parsec.Token as P
-- TODO: separated annotations like "1. d4 $9" as well
data PGN = PGN {
pgnTags :: [Tag],
pgnMoves :: [(Move, Annotation)],
pgnResult :: Result
}
deriving (Eq, Show)
type Tag = (String, String)
data Result = WhiteWin | BlackWin | DrawnGame | OtherResult
deriving (Eq, Show, Enum, Ord)
lexer :: P.TokenParser ()
lexer = P.makeTokenParser emptyDef {
P.commentStart = "{",
P.commentEnd = "}",
P.commentLine = ";",
P.nestedComments = False
}
-- Bind the lexical parsers at top-level.
whiteSpace :: Parsec String () ()
whiteSpace = P.whiteSpace lexer
decimal :: Parsec String () Integer
decimal = P.decimal lexer
lexeme :: Parsec String () a -> Parsec String () a
lexeme = P.lexeme lexer
-- Parsec String () for a PGN symbol token.
pgnSymbol :: Parsec String () String
pgnSymbol = lexeme $ do
first <- alphaNum
rest <- many (alphaNum <|> P.oneOf "_+#=:-")
return (first:rest)
-- Parsec String () for a PGN string token.
pgnString :: Parsec String () String
pgnString = lexeme $ between (char '"') (char '"') (many pgnStringChar)
-- Parsec String () for characters inside a string token.
pgnStringChar :: Parsec String () Char
pgnStringChar = do
c <- satisfy (\c -> isPrint c && c /= '"')
if c == '\\'
then P.oneOf "\\\""
else return c
pgnTagName :: Parsec String () String
pgnTagName = lexeme . liftM2 (:) alphaNum . many $ alphaNum <|> char '_'
pgnInteger :: Parsec String () Integer
pgnInteger = lexeme decimal
tagParser :: Parsec String () Tag
tagParser = liftM2 (,)
(lexeme (char '[') >> pgnTagName)
(pgnString <* lexeme (char ']'))
-- We should check the move numbers? But what is best way to deal with
-- misnumbered input anyway?
resultOrMoveParser :: Parsec String () (Either Result (Move, Annotation))
resultOrMoveParser = (string "*" >> return (Left OtherResult))
<|> do
num <- pgnInteger
case num of
0 -> (string "-1" >> return (Left BlackWin)) <|> moveAfterNum (Just num)
1 -> (string "-0" >> return (Left WhiteWin)) <|>
(string "/2-1/2" >> return (Left DrawnGame)) <|>
moveAfterNum (Just num)
_ -> moveAfterNum $ Just num
<|> (moveAfterNum =<< optionMaybe pgnInteger)
where
moveAfterNum (Just n) = lexeme (skipMany (char '.')) >> moveAfterNum Nothing
moveAfterNum Nothing = Right <$> lexeme moveAnnParser
showResult BlackWin = "0-1"
showResult WhiteWin = "1-0"
showResult DrawnGame = "1/2-1/2"
stopOnLeft :: (Monad m) => m (Either d a) -> m (d, [a])
stopOnLeft p = p >>= \ res -> case res of
Left stopRes -> return (stopRes, [])
Right rRes -> second (rRes:) `liftM` stopOnLeft p
pgnParser :: Parsec String () PGN
pgnParser = whiteSpace >> do
tags <- many tagParser
(result, moves) <- stopOnLeft resultOrMoveParser <* whiteSpace
return $ PGN tags moves result
showPgn (PGN tags moves result) =
concatMap (\ (t, v) -> "[" ++ t ++ " \"" ++ v ++ "\"]\n")
(tags ++ [("Result", resStr)]) ++
-- todo: annotations
intercalate " "
(concat . zipWith (\ n l -> (show n ++ ".") : l) [1..] . splitEvery 2 $
map (showMove . fst) moves) ++
" " ++ resStr
where
resStr = showResult result
|
dancor/pgn
|
src/Data/PGN.hs
|
bsd-2-clause
| 3,603 | 0 | 19 | 730 | 1,279 | 676 | 603 | 91 | 4 |
module SemanticData (MyType, defaultValue, makeUMns, makeMlt, makeDiv, makeAdd, makeSub, makeId) where
type MyType = Integer
defaultValue = 0
makeAdd x y = x + y
makeSub x y = x - y
makeMlt x y = x * y
makeDiv x y = div x y
makeId x = x
makeUMns x = -x
|
marionette-of-u/kp19pp
|
sample/haskell/SemanticData.hs
|
bsd-2-clause
| 266 | 0 | 5 | 67 | 116 | 64 | 52 | 9 | 1 |
module HEP.Automation.MadGraph.Model.Common where
mtop :: Double
-- mtop = 174.3
mtop = 172.0 -- value from FeynRules default param_card.dat : alphaS = 0.1184
gstrong :: Double
gstrong = 1.22 -- value from FeynRules default param_card.dat : alphaS = 0.1184
|
wavewave/madgraph-auto-model
|
src/HEP/Automation/MadGraph/Model/Common.hs
|
bsd-2-clause
| 272 | 0 | 4 | 54 | 32 | 22 | 10 | 5 | 1 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
module Mismi.EC2.Commands (
findSecurityGroupByName
) where
import Control.Lens (view, (.~))
import Mismi.Amazonka
import Mismi.EC2.Data
import Mismi.EC2.Amazonka
import P
findSecurityGroupByName :: SecurityGroupName -> AWS (Maybe SecurityGroupId)
findSecurityGroupByName (SecurityGroupName n) = do
r <- send $ describeSecurityGroups & dsgsFilters .~ [filter' "group-name" & fValues .~ [n]]
return . fmap (SecurityGroupId . view sgGroupId) . listToMaybe . view dsgrsSecurityGroups $ r
|
ambiata/mismi
|
mismi-ec2/src/Mismi/EC2/Commands.hs
|
bsd-3-clause
| 621 | 0 | 14 | 132 | 152 | 83 | 69 | 13 | 1 |
import WiringHs
import Control.Concurrent.Thread.Delay
import Control.Monad
pinI, pinO :: Pin
pinI = Pin 4
pinO = Pin 3
main :: IO ()
main = do
set <- wiringPiSetup Pins
when (not set) $ error "Couldn't set the GPIO."
pinMode pinI Input
pinMode pinO Output
setInterrupt pinI Rising (putStrLn "I felt something here!")
forM_ [1..10] $ \n -> do
putStr ("pin " ++ show n ++ " is ")
digitalRead (Pin n) >>= putStrLn . show
forM_ [1..10] $ \i -> do
putStrLn $ "Cycle " ++ show (i :: Int)
digitalWrite pinO Low
delay 950000
digitalWrite pinO High
delay 50000
putStrLn "End"
digitalWrite pinO Low
|
lostbean/radio-fm69
|
test/TestPi.hs
|
bsd-3-clause
| 642 | 0 | 15 | 157 | 257 | 119 | 138 | 24 | 1 |
{-# LANGUAGE NoImplicitPrelude #-}
-- |
-- Module: $HEADER$
-- Description: Read and parse configuration files.
-- Copyright: (c) 2015 Peter Trško
-- License: BSD3
--
-- Maintainer: [email protected]
-- Stability: experimental
-- Portability: NoImplicitPrelude
--
-- Read and parse configuration files.
module Main.ConfigFile
( defaultConfigFileName
, readConfigFile
, readUserConfigFile
, readConfigFile'
, getMenuItems
)
where
import Control.Monad (Monad((>>=), return), (=<<))
import Data.Bool (otherwise)
import Data.Either (Either(Left, Right))
import Data.Eq (Eq((==)))
import Data.Foldable (Foldable, foldlM)
import Data.Function (const)
import Data.Functor ((<$>))
import Data.Monoid (Monoid(mempty), (<>))
import Data.String (String)
import System.IO (IO, FilePath)
import Data.ByteString (readFile)
import System.Directory (doesFileExist)
import Control.Lens ((^.))
import Data.Aeson (eitherDecodeStrict')
import Main.Type.Options (Options)
import Main.Type.Options.Lens (configFile)
import Main.Type.MenuItem (MenuItems)
-- | Default configuration file name.
--
-- @
-- 'defaultConfigFileName' = \"toolbox-menu.json\"
-- @
defaultConfigFileName :: FilePath
defaultConfigFileName = "toolbox-menu.json"
-- | Generalized implementation of 'readConfigFile' and 'readUserConfigFile'.
readConfigFileImpl
:: (Options -> FilePath)
-- ^ Get configuration file path supplied by the user. See e.g.
-- 'configFile'.
-> (FilePath -> IO FilePath)
-- ^ Get absoulete file path for relative path to a config file. This is
-- where 'Paths.toolbox.getDataFileName' would be used.
-> Options
-> IO (Either String MenuItems)
readConfigFileImpl g f opts = readConfigFile' =<< case g opts of
fileName@(c : _)
| c == '/' -> return fileName
-- Leave absolute path as it is.
| otherwise -> f fileName
-- Find config file using provided funcion in case of relative path.
"" -> f defaultConfigFileName
-- Empty path means "use default configuration file."
-- | Read configuration file either one provided with the installation or one
-- supplied by the user on command line.
readConfigFile
:: (FilePath -> IO FilePath)
-- ^ Get absoulete file path for relative path to a config file. This is
-- where 'Paths.toolbox.getDataFileName' would be used.
-> Options
-> IO (Either String MenuItems)
readConfigFile = readConfigFileImpl (^. configFile)
-- | Read user configuration file. This differs from system configuration file.
readUserConfigFile
:: (FilePath -> IO FilePath)
-> Options
-> IO (Either String MenuItems)
readUserConfigFile = readConfigFileImpl (const "")
-- | Read and parse configuration file (JSON). If configuration file doesn't
-- exist then @Right 'mempty' :: Either String 'MenuItems'@ is returned.
readConfigFile' :: FilePath -> IO (Either String MenuItems)
readConfigFile' file = do
fileExist <- doesFileExist file
if fileExist
then eitherDecodeStrict' <$> readFile file
else return (Right mempty)
-- | Gather menu items from various side-effect sources and handle error cases.
getMenuItems
:: Foldable f
=> Options
-> (String -> IO MenuItems)
-- ^ Error handling function.
-> f (Options -> IO (Either String MenuItems))
-> IO MenuItems
getMenuItems opts onError = foldlM go mempty
where
go :: MenuItems -> (Options -> IO (Either String MenuItems)) -> IO MenuItems
go items f = f opts >>= processResult items
processResult :: MenuItems -> Either String MenuItems -> IO MenuItems
processResult items r = case r of
Right x -> return (items <> x)
Left msg -> onError msg
|
trskop/toolbox-tray-icon
|
src/Main/ConfigFile.hs
|
bsd-3-clause
| 3,737 | 0 | 14 | 752 | 757 | 426 | 331 | 65 | 2 |
module Language.Mojito.Inference.Substitution where
import Data.List (intersect, nub, union, (\\))
import Language.Mojito.Syntax.Types
import Language.Mojito.Inference.Context
----------------------------------------------------------------------
-- Substitution
----------------------------------------------------------------------
close :: Constrained -> Context -> Type
close k g = Type as k
where as = tv k \\ tv' g
-- Returns the list of type variables in a simple type.
vars :: Simple -> [String]
vars (TyVar a) = [a]
vars (TyCon _) = []
vars (TyApp a b) = vars a `union` vars b
-- Returns the free type variables of a type, simple type, constraint,
-- list of constraints.
class TV a where tv :: a -> [String]
instance TV a => TV [a] where
tv ts = nub $ concatMap tv ts
instance TV Simple where
tv = vars
instance TV Constraint where
tv (Constraint _ t) = vars t
instance TV Constrained where
tv (Constrained cs t) = tv cs `union` vars t
instance TV Type where
tv (Type as c) = tv c \\ as
-- Returns the free type variables of a typing context.
tv' :: Context -> [String]
tv' g = nub $ concatMap (tv . snd) (ctxAssoc g)
quantified :: Simple -> Type
quantified t = Type (tv t) $ Constrained [] t
-- A (type) substitution is a function from type variables to
-- simple types or type constructor that differs from the identity
-- function only on finitely
-- many variable (definition from Camarao 1999, Type Inference for
-- Overloading without Restrictions, Declarations or Annotations).
-- It is represented by an association list. Applying the
-- substitution to a type is done by looking up the type from the
-- association-list. If it is not found, it is returned as-is.
-- A substitution can also be applied to a type environment.
-- Instead of modifying the environment each time a new substitution
-- is computed, the substitution is applied when an identifer is
-- looked up (see the function 'retrieve').
type Substitution = [(String,Simple)]
showSubstitution :: Substitution -> String
showSubstitution = unlines . map (\(a,b) -> a ++ " -> " ++ showSimple b)
idSubstitution :: Substitution
idSubstitution = []
fromList :: [(String,Simple)] -> Substitution
fromList = id
-- Builds a substitution which replace the first argument
-- by the second.
replace :: String -> Simple -> Substitution
replace a t = [(a,t)]
-- The \dag LaTeX symbol, which 'shadows' a substitution by
-- another. Here, it is implemented by the fact that a lookup
-- in a association-list will return the first match.
dag :: [(String, (Simple,Simple))] -> [(String, (Simple,Simple))] -> [(String, (Simple,Simple))]
dag s1 s2 = s2 ++ s1
class Subs a where subs :: Substitution -> a -> a
instance Subs a => Subs [a] where
subs s = map (subs s)
instance (Subs a, Subs b) => Subs (a,b) where
subs s (a,b) = (subs s a, subs s b)
-- Apply a substitution to a simple type.
instance Subs Simple where
subs [] t = t
subs s t = case t of
TyVar a -> maybe t id $ lookup a s
TyCon _ -> t
TyApp a b -> subs s a `TyApp` subs s b
instance Subs Constraint where
subs [] c = c
subs s (Constraint o t) = Constraint o (subs s t)
instance Subs Constrained where
subs [] c = c
subs s (Constrained cs t) = Constrained (subs s cs) (subs s t)
instance Subs Type where
subs [] t = t
subs s (Type as c) =
let s' = filter f s
f = not . (`elem` as) . fst
in Type as (subs s' c)
subs' :: Substitution -> Context -> Context
subs' s g = Context (map (\(a,b) -> (a, s `subs` b)) $ ctxAssoc g)
comp :: String -> Substitution -> Substitution -> Substitution
comp msg ts1 ts2 = foldr f ts2 ts1
where f t ts = ext (fst t) (snd t) ts
-- adds a new pair to the substitution, and "performs" it in-place.
ext :: String -> Simple -> [(String,Simple)] -> [(String,Simple)]
ext t1 t2 ts = case lookup t1 ts of
Nothing -> case t2 of
TyCon _ -> (t1,t2) : rep t1 t2 ts
TyApp _ _ -> (t1,t2) : rep t1 t2 ts
TyVar a -> case lookup a ts of
Nothing -> (t1,t2) : rep t1 t2 ts
Just t3 -> (t1,t3) : rep t1 t3 ts
Just _ -> error $ "comp: " ++ show t1 ++ " is already present in : " ++ show ts ++ " to be replaced by " ++ show t2 ++ " -- " ++ msg
rep a b cs = let g (x,y) = (x, [(a,b)] `subs` y)
in map g cs
intersectSubs :: [Substitution] -> Substitution
intersectSubs [] = error $ "intersectSubs called on empty set"
intersectSubs [s] = s
intersectSubs (s:bigs) = s `restrict` v
where v = [fst a | a <- s, b <- s', a == b]
s' = intersectSubs bigs
-- TODO QuickCheck Property: the application of a substitution S to s
-- (si stands for sigma) is capture-free if tv(Ss) == tv(S(tv(s))).
----------------------------------------------------------------------
-- Restriction
----------------------------------------------------------------------
-- Restriction of a substitution to a set of type variables.
restrict :: Substitution -> [String] -> Substitution
restrict s vs = filter f s
where f = (`elem` vs) . fst
-- Restriction of a set of constraints to a set of type variables.
restr :: [Constraint] -> [String] -> [Constraint]
restr [] _ = []
restr [Constraint o t] vs | tv t `intersect` vs == [] = []
| otherwise = [Constraint o t]
restr (c:cs) vs = restr [c] vs `union` restr cs vs
-- Closure of restricting a set of constraints to a set of
-- type variables.
restr' :: [Constraint] -> [String] -> [Constraint]
restr' k vs | null (v \\ vs )= k'
| otherwise = restr' k v
where k' = k `restr` vs
v = tv k'
restrictCtx :: Context -> String -> Context
restrictCtx (Context xs) s = Context $ filter ((== s) . fst) xs
|
noteed/mojito
|
Language/Mojito/Inference/Substitution.hs
|
bsd-3-clause
| 5,819 | 0 | 17 | 1,384 | 1,885 | 1,005 | 880 | 97 | 5 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE TemplateHaskell #-}
module Main where
import Control.Exception (SomeException, try)
import qualified Data.Text as T
import Snap.Http.Server
import Snap.Snaplet
import Snap.Core
import System.IO
import Site
import Snap.Loader.Prod
{-|
This is the entry point for this web server application. It supports
easily switching between interpreting source and running statically
compiled code.
In either mode, the generated program should be run from the root of
the project tree. When it is run, it locates its templates, static
content, and source files in development mode, relative to the current
working directory.
When compiled with the development flag, only changes to the
libraries, your cabal file, or this file should require a recompile to
be picked up. Everything else is interpreted at runtime. There are a
few consequences of this.
First, this is much slower. Running the interpreter takes a
significant chunk of time (a couple tenths of a second on the author's
machine, at this time), regardless of the simplicity of the loaded
code. In order to recompile and re-load server state as infrequently
as possible, the source directories are watched for updates, as are
any extra directories specified below.
Second, the generated server binary is MUCH larger, since it links in
the GHC API (via the hint library).
Third, and the reason you would ever want to actually compile with
development mode, is that it enables a faster development cycle. You
can simply edit a file, save your changes, and hit reload to see your
changes reflected immediately.
When this is compiled without the development flag, all the actions
are statically compiled in. This results in faster execution, a
smaller binary size, and having to recompile the server for any code
change.
-}
main :: IO ()
main = do
-- depending on the version of loadSnapTH in scope, this either
-- enables dynamic reloading, or compiles it without. The last
-- argument to loadSnapTH is a list of additional directories to
-- watch for changes to trigger reloads in development mode. It
-- doesn't need to include source directories, those are picked up
-- automatically by the splice.
(conf, site, cleanup) <- $(loadSnapTH [| getConf |]
'getActions
["resources/templates"])
_ <- try $ httpServe conf $ site :: IO (Either SomeException ())
cleanup
-- | This action loads the config used by this application. The
-- loaded config is returned as the first element of the tuple
-- produced by the loadSnapTH Splice. The type is not solidly fixed,
-- though it must be an IO action that produces the same type as
-- 'getActions' takes. It also must be an instance of Typeable. If
-- the type of this is changed, a full recompile will be needed to
-- pick up the change, even in development mode.
--
-- This action is only run once, regardless of whether development or
-- production mode is in use.
getConf :: IO (Config Snap ())
getConf = commandLineConfig defaultConfig
-- | This function generates the the site handler and cleanup action
-- from the configuration. In production mode, this action is only
-- run once. In development mode, this action is run whenever the
-- application is reloaded.
--
-- Development mode also makes sure that the cleanup actions are run
-- appropriately before shutdown. The cleanup action returned from
-- loadSnapTH should still be used after the server has stopped
-- handling requests, as the cleanup actions are only automatically
-- run when a reload is triggered.
--
-- This sample doesn't actually use the config passed in, but more
-- sophisticated code might.
getActions :: Config Snap () -> IO (Snap (), IO ())
getActions _ = do
(msgs, site, cleanup) <- runSnaplet app
hPutStrLn stderr $ T.unpack msgs
return (site, cleanup)
|
tomgr/webcspm
|
src/Main.hs
|
bsd-3-clause
| 3,925 | 0 | 11 | 786 | 288 | 169 | 119 | 25 | 1 |
{-# LANGUAGE QuasiQuotes #-}
import LiquidHaskell
import Language.Haskell.Liquid.Prelude
-- gpp :: Monad m => m Int -> m Int
gpp z = do x <- z
return $ liquidAssert (x >= 0) (x + 1)
gpp' z n = do x <- z n
return $ liquidAssert (x >= 0) (x + 1)
myabs :: Int -> Int
myabs x | x >= 0 = x
| otherwise = 0-x
myabsM :: Monad m => Int -> m Int
myabsM x | x >= 0 = return $ x
| otherwise = return $ 0-x
posM :: Monad m => m Int
posM = return $ myabs $ choose 0
xM, yM :: Monad m => m Int
yM = gpp posM
xM = gpp' myabsM $ choose 0
|
spinda/liquidhaskell
|
tests/gsoc15/unknown/pos/monad5.hs
|
bsd-3-clause
| 588 | 2 | 10 | 195 | 273 | 132 | 141 | 18 | 1 |
module Main where
import qualified Test.HUnit as HUnit
import HTMLSpec
import NWASpec
import NWAHTMLSpec
main :: IO ()
main = do {
putStrLn "\nTesting HTML Parsing";
htmlcounts <- HUnit.runTestTT htmltests;
putStrLn $ show htmlcounts;
putStrLn "\nTesting Nested Word Automaton";
nwacounts <- HUnit.runTestTT nwatests;
putStrLn $ show nwacounts;
putStrLn "\nTesting Nested Word Automaton on HTML";
nwahtmlcounts <- HUnit.runTestTT nwahtmltests;
putStrLn $ show nwahtmlcounts;
return ()
}
|
katydid/nwe
|
test/Spec.hs
|
bsd-3-clause
| 535 | 0 | 9 | 113 | 139 | 70 | 69 | 17 | 1 |
{-# LANGUAGE FlexibleContexts, FlexibleInstances #-}
module Data.Functor.Listable
( Listable(..)
, cons0
, cons1
, cons2
, cons3
, cons4
, cons5
, cons6
, (\/)
, (><)
, Listable1(..)
, tiers1
, Listable2(..)
, tiers2
, liftCons1
, liftCons2
, liftCons3
, ListableF(..)
, embedTiers
, nameTiers
, uncurryr3
, uncurryr4
) where
import Data.Functor.Foldable hiding (Mu)
import Expr
import Test.LeanCheck
class Listable1 l where
liftTiers :: [[a]] -> [[l a]]
tiers1 :: (Listable a, Listable1 l) => [[l a]]
tiers1 = liftTiers tiers
class Listable2 l where
liftTiers2 :: [[a]] -> [[b]] -> [[l a b]]
tiers2 :: (Listable a, Listable b, Listable2 l) => [[l a b]]
tiers2 = liftTiers2 tiers tiers
liftCons1 :: [[a]] -> (a -> b) -> [[b]]
liftCons1 tiers f = mapT f tiers `addWeight` 1
liftCons2 :: [[a]] -> [[b]] -> (a -> b -> c) -> [[c]]
liftCons2 tiers1 tiers2 f = mapT (uncurry f) (productWith (,) tiers1 tiers2) `addWeight` 1
liftCons3 :: [[a]] -> [[b]] -> [[c]] -> (a -> b -> c -> d) -> [[d]]
liftCons3 tiers1 tiers2 tiers3 f = mapT (uncurry3 f) (productWith (\ x (y, z) -> (x, y, z)) tiers1 (liftCons2 tiers2 tiers3 (,)) ) `addWeight` 1
where uncurry3 f (a, b, c) = f a b c
-- | Convenient wrapper for 'Listable1' type constructors and 'Listable' types, where a 'Listable' instance would necessarily be orphaned.
newtype ListableF f a = ListableF { unListableF :: f a }
deriving Show
embedTiers :: (Listable1 (Base t), Corecursive t) => [[t]]
embedTiers = liftCons1 (liftTiers embedTiers) embed
nameTiers :: [[Name]]
nameTiers = cons1 I \/ cons1 N
uncurryr3 :: (a -> b -> c -> d) -> (a, (b, c)) -> d
uncurryr3 f (a, (b, c)) = f a b c
uncurryr4 :: (a -> b -> c -> d -> e) -> (a, (b, (c, d))) -> e
uncurryr4 f (a, (b, (c, d))) = f a b c d
-- Instances
instance Listable1 Maybe where
liftTiers tiers = cons0 Nothing \/ liftCons1 tiers Just
instance Listable1 [] where
liftTiers tiers = cons0 [] \/ liftCons2 tiers (liftTiers tiers) (:)
instance Listable2 (,) where
liftTiers2 = productWith (,)
instance Listable a => Listable1 ((,) a) where
liftTiers = liftTiers2 tiers
instance Listable2 ExprF where
liftTiers2 nameTiers ts
= liftCons1 (liftTiers ts) Product
\/ liftCons1 (liftTiers ts) Sum
\/ liftCons3 nameTiers ts ts Pi
\/ liftCons3 nameTiers ts ts Mu
\/ liftCons3 nameTiers ts ts Sigma
\/ cons0 Type
\/ liftCons2 nameTiers ts Abs
\/ liftCons1 nameTiers Var
\/ liftCons2 ts ts App
\/ liftCons2 ts (abs `mapT` tiers) Inj
\/ liftCons2 ts (liftTiers ts) Case
\/ liftCons1 (liftTiers ts) Tuple
\/ liftCons2 ts (abs `mapT` tiers) At
\/ liftCons3 nameTiers ts ts Let
\/ liftCons2 ts ts As
instance Listable1 (ExprF Name) where
liftTiers = liftTiers2 nameTiers
instance (Listable1 f, Listable a) => Listable (ListableF f a) where
tiers = ListableF `mapT` tiers1
|
robrix/surface
|
test/Data/Functor/Listable.hs
|
bsd-3-clause
| 2,858 | 0 | 22 | 597 | 1,244 | 686 | 558 | 81 | 1 |
module NaturalHorn
(
module X
) where
import NHorn.NaturalHorn as X
import NHorn.NaturalHornExts as X
import NHorn.NaturalHornPretty as X
import NHorn.Sequent as X(Sequent, createSeq, ErrSec, Theory(..))
import NHorn.LaCarte as X
|
esengie/algebraic-checker
|
src/NaturalHorn.hs
|
bsd-3-clause
| 244 | 0 | 6 | 44 | 63 | 44 | 19 | 8 | 0 |
module Four where
import Data.Hash.MD5
import Data.List (find)
import Data.Maybe (fromJust)
import Data.String.Utils
-- "abcdef609043" Hashes to "000001dbbfa"
-- value ++ (show 5)
hashString :: String -> Int -> String
hashString value seed = md5s $ Str (value ++ show seed)
bruteForce :: String -> String -> Int
bruteForce prefix seed = fromJust $ find (startswith prefix . hashString seed) [0..]
four :: IO (Int, Int)
four = do
initialValue <- strip <$> readFile "input/4.txt"
return ( bruteForce "00000" initialValue
, bruteForce "000000" initialValue )
|
purcell/adventofcodeteam
|
app/Four.hs
|
bsd-3-clause
| 631 | 0 | 9 | 160 | 181 | 96 | 85 | 14 | 1 |
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleContexts, AllowAmbiguousTypes #-}
{-# LANGUAGE TypeOperators, TypeApplications, GADTs, DataKinds, ScopedTypeVariables, GeneralizedNewtypeDeriving #-}
{-# LANGUAGE RankNTypes #-}
{-{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE TypeFamilyDependencies #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE InstanceSigs #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE DataKinds, EmptyDataDecls, TypeOperators, ExistentialQuantification, RankNTypes, DefaultSignatures,ScopedTypeVariables,
GADTs, DuplicateRecordFields, PatternSynonyms, DeriveTraversable, DeriveGeneric, DeriveDataTypeable, DeriveLift, StandaloneDeriving, DeriveAnyClass, MultiParamTypeClasses, TypeApplications #-}
-}
module GRIN.Parser.ParseEffect where
import Control.Monad.Freer
import Control.Monad.Freer.Internal (NonDet, Eff(..), decomp, qApp, qComp )
import Control.Monad.Freer.Fresh
import qualified Control.Monad.Freer.State as S
import Text.Megaparsec.Prim hiding (runParser)
import Data.Set as E
import Data.Kind
import Data.Semigroup
import GHC.Generics
import Data.Data
import Text.Megaparsec.Error (ErrorItem, ParseError(..), ErrorComponent)
import qualified Data.List.NonEmpty as NE
newtype Hints t = Hints [Set (ErrorItem t)] deriving (Semigroup, Monoid)
{-
toHints :: ParseError t e -> Hints t
toHints err = Hints hints
where hints = if E.null msgs then [] else [msgs]
msgs = errorExpected err
{-# INLINE toHints #-}
withHints :: Ord (Token s)
=> Hints (Token s) -- ^ Hints to use
-> (ParseError (Token s) e -> State s -> m b) -- ^ Continuation to influence
-> ParseError (Token s) e -- ^ First argument of resulting continuation
-> State s -- ^ Second argument of resulting continuation
-> m b
withHints (Hints ps') c e@(ParseError pos us ps xs) =
if E.null us && E.null ps && not (E.null xs)
then c e
else c (ParseError pos us (E.unions (ps : ps')) xs)
{-# INLINE withHints #-}
accHints
:: Hints t -- ^ 'Hints' to add
-> (a -> State s -> Hints t -> m b) -- ^ An “OK” continuation to alter
-> a -- ^ First argument of resulting continuation
-> State s -- ^ Second argument of resulting continuation
-> Hints t -- ^ Third argument of resulting continuation
-> m b
accHints hs1 c x s hs2 = c x s (hs1 <> hs2)
{-# INLINE accHints #-}
refreshLastHint :: Hints t -> Maybe (ErrorItem t) -> Hints t
refreshLastHint (Hints []) _ = Hints []
refreshLastHint (Hints (_:xs)) Nothing = Hints xs
refreshLastHint (Hints (_:xs)) (Just m) = Hints (E.singleton m : xs)
{-# INLINE refreshLastHint #-}
data ParsecEffect e s a where
ConsumedOK :: a -> State s -> Hints (Token s) -> ParsecEffect e s a
ConsumedError :: ParseError (Token s) e -> State s -> ParsecEffect e s (ParseError (Token s) e)
EmptyOK :: a -> State s -> Hints (Token s) -> ParsecEffect e s a
EmptyError :: ParseError (Token s) e -> State s -> ParsecEffect e s (ParseError (Token s) e)
cok :: forall e s a b effs rest . (ErrorComponent e, Stream s, Member (ParsecEffect e s) effs) => a -> State s -> Hints (Token s) -> Eff effs a
cok a s h = send @(ParsecEffect e s) (ConsumedOK a s h)
cerr :: forall e s effs. (ErrorComponent e, Stream s, Member (ParsecEffect e s) effs) => ParseError (Token s) e -> State s -> Eff effs (ParseError (Token s) e)
cerr e s= send @(ParsecEffect e s) (ConsumedError e s)
eok :: forall e s a b effs rest . (ErrorComponent e, Stream s, Member (ParsecEffect e s) effs) => a -> State s -> Hints (Token s) -> Eff effs a
eok a s h = send @(ParsecEffect e s) (EmptyOK a s h)
eerr :: forall e s effs. (ErrorComponent e, Stream s, Member (ParsecEffect e s) effs) => ParseError (Token s) e -> State s -> Eff effs (ParseError (Token s) e)
eerr e s = send @(ParsecEffect e s) (EmptyError e s)
failure :: forall e s effs. (ErrorComponent e, Stream s, Member (ParsecEffect e s) effs, Member (S.State (State s)) effs) => Set (ErrorItem (Token s)) -> Set (ErrorItem (Token s)) -> Set e -> Eff effs (ParseError (Token s) e)
failure us ps xs = do
s@(State _ pos _ _) <- S.get @(State s)
eerr (ParseError pos us ps xs) s
label :: forall e s effs a . (ErrorComponent e, Stream s, Member (ParsecEffect e s) effs, Member (S.State (State s)) effs) => String -> Eff effs a -> Eff effs a
label l p = do
s <- S.get @(State s)
let el = Label <$> NE.nonEmpty l
cl = Label . (NE.fromList "the rest of "<>) <$> NE.nonEmpty l
error "unimplemented"
-}
data Parser e s a where
Failure :: Set (ErrorItem (Token s)) -> Set (ErrorItem (Token s)) -> Set e -> Parser e s a
Label :: Member (Parser e s) effs => String -> Eff effs a -> Parser e s a
Hidden :: Member (Parser e s) effs => Eff effs a -> Parser e s a
Try :: Member (Parser e s) effs => Eff effs a -> Parser e s a
LookAhead :: Member (Parser e s) effs => Eff effs a -> Parser e s a
NotFollowedBy :: Member (Parser e s) effs => Eff effs a -> Parser e s ()
WithRecovery :: Member (Parser e s) effs => (ParseError (Token s) e -> Eff effs a) -> Eff effs a -> Parser e s a
Observing :: Member (Parser e s) effs => Eff effs a -> Parser e s (Either (ParseError (Token s) e) a)
EOF :: Parser e s ()
Token :: (Token s -> Either (Set (ErrorItem (Token s)), Set (ErrorItem (Token s)), Set e) a) -> Maybe (Token s) -> Parser e s a
Tokens :: (Token s -> Token s -> Bool) -> [Token s] -> Parser e s [Token s]
GetParserState :: Parser e s (State s)
UpdateParserState :: (State s -> State s) -> Parser e s ()
class MPC e s (effs :: [* -> *]) | effs -> e s where
type C e s effs :: Constraint
instance MPC e s ((Parser e s) : rest) where
type C e s ((Parser e s) : rest) = Member (Parser e s) ((Parser e s) : rest)
instance Member (Parser e s) rest => MPC e s (h : rest) where
type C e s (h : rest) = Member (Parser e s) (h : rest)
instance (ErrorComponent e, Stream s, Member (Parser e s) effs, Member NonDet effs) => MonadParsec e s (Eff effs) where
failure a b c = send @(Parser e s) (Failure a b c)
label a b = send @(Parser e s) (Label :: String -> Eff effs a -> Parser e s a) a b
hidden a = send @(Parser e s) (Hidden a)
try a = send @(Parser e s) (Try a)
lookAhead a = send @(Parser e s) (LookAhead a)
notFollowedBy a = send @(Parser e s) (NotFollowedBy a)
withRecovery a b = send @(Parser e s) (WithRecovery a b)
observing a = send @(Parser e s) (Observing a)
eof = send @(Parser e s) EOF
token a b = send @(Parser e s) (Token a b)
tokens a b = send @(Parser e s) (Tokens a b)
getParserState = send @(Parser e s) GetParserState
updateParserState a = send @(Parser e s) (UpdateParserState a)
runParser :: forall e s effs a . Eff (Parser e s ': effs) a -> State s -> Eff effs (State s, Either (ParseError (Token s) e) a)
runParser (Val x) s = return (s, Right x)
runParser (E u q) s= case decomp u of
Right (Failure a b c) -> _ a b c -- runParser (qApp q (_ a b c)) s
|
spacekitteh/libgrin
|
src/GRIN/Parser/ParseEffect.hs
|
bsd-3-clause
| 7,217 | 0 | 15 | 1,522 | 1,570 | 809 | 761 | 59 | 1 |
module DnoList.Sysop where
import Data.Char
import Data.Maybe
import Data.Proxy
import Data.Monoid
import Control.Monad
import Data.Text (Text)
import Network.Wai.Handler.Warp (run)
import Servant.API
import Servant.Server
import Servant.Client
import Control.Monad.Trans.Either
import Control.Monad.Trans.Class
import Control.Monad.IO.Class
import Control.Monad.Logger
import Database.Persist.Postgresql (withPostgresqlPool)
import Database.Esqueleto
import Control.Monad.Trans.Control
import Data.Aeson.TH
import DnoList.Types
import DnoList.Database
data UserInfo = UserInfo { userInfoId :: UserId
, userInfoName :: Text
, userInfoAdmin :: Bool
}
$(deriveJSON defaultOptions { fieldLabelModifier = map toLower . drop 8 } ''UserInfo)
type SysopAPI = "lists" :> Get '[JSON] [(ListId, Text)]
:<|> "lists" :> ReqBody '[JSON] List :> Post '[JSON] ListId
:<|> "lists" :> Capture "listid" ListId :> Get '[JSON] List
:<|> "lists" :> Capture "listid" ListId :> "subscribers" :> Get '[JSON] [(UserId, Text)]
:<|> "lists" :> Capture "listid" ListId :> "delete" :> ReqBody '[JSON] UserId :> Post '[JSON] ()
:<|> "lists" :> Capture "listid" ListId :> "subscribe" :> Capture "clientid" UserId :> Put '[JSON] ()
:<|> "lists" :> Capture "listid" ListId :> "unsubscribe" :> Capture "clientid" UserId :> Put '[JSON] ()
:<|> "users" :> Get '[JSON] [(UserId, Text)]
:<|> "users" :> Capture "userid" UserId :> Get '[JSON] UserInfo
:<|> "users" :> Capture "userid" UserId :> "subscriptions" :> Get '[JSON] [(ListId, Text)]
:<|> "users" :> "by-name" :> Capture "username" Text :> Get '[JSON] UserInfo
sysopServer :: ConnectionPool -> Server SysopAPI
sysopServer pool =
listList
:<|> listCreate
:<|> listShow
:<|> listSubscribers
:<|> listDelete
:<|> listSubscribe
:<|> listUnsubscribe
:<|> userList
:<|> userShow
:<|> userSubscriptions
:<|> userShowName
where listList = run $ do
r <- select $ from $ \list -> return list
return $ map (\(Entity id l) -> (id, listName l)) r
listCreate list = run $ insert list
listShow lid = run $ maybe (lift $ left err404) return =<< get lid
listSubscribers lid = run $ do
r <- select $ from $ \(subscr `InnerJoin` user) -> do
on $ subscr^.SubscriptionUser ==. user^.UserId
where_ $ subscr^.SubscriptionList ==. val lid
return user
return $ map (\(Entity id u) -> (id, userName u)) r
listDelete lid uid = run $ do
list <- maybe (lift $ left err404) return =<< get lid
user <- maybe (lift $ left err404) return =<< get uid
lift $ unless (listOwner list == uid || userAdmin user) $ left err403
delete $ from $ \order -> where_ $ order^.OrderList ==. val lid
delete $ from $ \list -> where_ $ list^.ListId ==. val lid
listSubscribe lid uid = run $ insert_ $ Subscription lid uid
listUnsubscribe lid uid = run $ do
r <- deleteCount $ from $ \subscr ->
where_ $ subscr^.SubscriptionUser ==. val uid &&. subscr^.SubscriptionList ==. val lid
lift $ when (r == 0) $ left err404
userList = run $ do
r <- select $ from $ \user -> return user
return $ map (\(Entity id u) -> (id, userName u)) r
userShow uid = run $ do
r <- maybe (lift $ left err404) return =<< get uid
return UserInfo { userInfoId = uid
, userInfoName = userName r
, userInfoAdmin = userAdmin r
}
userSubscriptions uid = run $ do
r <- select $ from $ \(subscr `InnerJoin` list) -> do
on $ subscr^.SubscriptionList ==. list^.ListId
where_ $ subscr^.SubscriptionUser ==. val uid
return list
return $ map (\(Entity id u) -> (id, listName u)) r
userShowName uname = run $ do
rs <- select $ from $ \user -> do
where_ $ user^.UserName ==. val uname
return user
Entity uid r <- lift $ maybe (left err404) return $ listToMaybe rs
return UserInfo { userInfoId = uid
, userInfoName = userName r
, userInfoAdmin = userAdmin r
}
run :: MonadBaseControl IO m => SqlPersistT m a -> m a
run = flip runSqlPool pool
( getAllLists
:<|> createList
:<|> getList
:<|> getListSubscribers
:<|> deleteList
:<|> subscribeList
:<|> unsubscribeList
:<|> getAllUsers
:<|> getUser
) = client (Proxy :: Proxy SysopAPI) $ BaseUrl Http "database" 8081
runSysop :: Settings -> IO ()
runSysop settings =
runStderrLoggingT $
withPostgresqlPool (database settings) 4 $ \pool -> liftIO $ do
run 8081 $ serve (Proxy :: Proxy SysopAPI) (sysopServer pool)
|
abbradar/dnolist
|
src/DnoList/Sysop.hs
|
bsd-3-clause
| 5,013 | 0 | 46 | 1,495 | 1,722 | 869 | 853 | -1 | -1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
module Distribution.Solver.Modular.Linking (
addLinking
, validateLinking
) where
import Prelude hiding (pi)
import Control.Exception (assert)
import Control.Monad.Reader
import Control.Monad.State
import Data.Maybe (catMaybes)
import Data.Map (Map, (!))
import Data.List (intercalate)
import Data.Set (Set)
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.Traversable as T
#if !MIN_VERSION_base(4,8,0)
import Control.Applicative
#endif
import Distribution.Solver.Modular.Assignment
import Distribution.Solver.Modular.Dependency
import Distribution.Solver.Modular.Flag
import Distribution.Solver.Modular.Index
import Distribution.Solver.Modular.Package
import Distribution.Solver.Modular.Tree
import qualified Distribution.Solver.Modular.PSQ as P
import qualified Distribution.Solver.Modular.ConflictSet as CS
import Distribution.Solver.Types.OptionalStanza
import Distribution.Solver.Types.PackagePath
import Distribution.Solver.Types.ComponentDeps (Component)
{-------------------------------------------------------------------------------
Add linking
-------------------------------------------------------------------------------}
type RelatedGoals = Map (PN, I) [PackagePath]
type Linker = Reader RelatedGoals
-- | Introduce link nodes into tree tree
--
-- Linking is a traversal of the solver tree that adapts package choice nodes
-- and adds the option to link wherever appropriate: Package goals are called
-- "related" if they are for the same version of the same package (but have
-- different prefixes). A link option is available in a package choice node
-- whenever we can choose an instance that has already been chosen for a related
-- goal at a higher position in the tree.
--
-- The code here proceeds by maintaining a finite map recording choices that
-- have been made at higher positions in the tree. For each pair of package name
-- and instance, it stores the prefixes at which we have made a choice for this
-- package instance. Whenever we make a choice, we extend the map. Whenever we
-- find a choice, we look into the map in order to find out what link options we
-- have to add.
addLinking :: Tree QGoalReason -> Tree QGoalReason
addLinking = (`runReader` M.empty) . cata go
where
go :: TreeF QGoalReason (Linker (Tree QGoalReason)) -> Linker (Tree QGoalReason)
-- The only nodes of interest are package nodes
go (PChoiceF qpn gr cs) = do
env <- ask
cs' <- T.sequence $ P.mapWithKey (goP qpn) cs
let newCs = concatMap (linkChoices env qpn) (P.toList cs')
return $ PChoice qpn gr (cs' `P.union` P.fromList newCs)
go _otherwise =
innM _otherwise
-- Recurse underneath package choices. Here we just need to make sure
-- that we record the package choice so that it is available below
goP :: QPN -> POption -> Linker (Tree QGoalReason) -> Linker (Tree QGoalReason)
goP (Q pp pn) (POption i Nothing) = local (M.insertWith (++) (pn, i) [pp])
goP _ _ = alreadyLinked
linkChoices :: RelatedGoals -> QPN -> (POption, Tree QGoalReason) -> [(POption, Tree QGoalReason)]
linkChoices related (Q _pp pn) (POption i Nothing, subtree) =
map aux (M.findWithDefault [] (pn, i) related)
where
aux :: PackagePath -> (POption, Tree QGoalReason)
aux pp = (POption i (Just pp), subtree)
linkChoices _ _ (POption _ (Just _), _) =
alreadyLinked
alreadyLinked :: a
alreadyLinked = error "addLinking called on tree that already contains linked nodes"
{-------------------------------------------------------------------------------
Validation
Validation of links is a separate pass that's performed after normal
validation. Validation of links checks that if the tree indicates that a
package is linked, then everything underneath that choice really matches the
package we have linked to.
This is interesting because it isn't unidirectional. Consider that we've
chosen a.foo to be version 1 and later decide that b.foo should link to a.foo.
Now foo depends on bar. Because a.foo and b.foo are linked, it's required that
a.bar and b.bar are also linked. However, it's not required that we actually
choose a.bar before b.bar. Goal choice order is relatively free. It's possible
that we choose a.bar first, but also possible that we choose b.bar first. In
both cases, we have to recognize that we have freedom of choice for the first
of the two, but no freedom of choice for the second.
This is what LinkGroups are all about. Using LinkGroup, we can record (in the
situation above) that a.bar and b.bar need to be linked even if we haven't
chosen either of them yet.
-------------------------------------------------------------------------------}
data ValidateState = VS {
vsIndex :: Index
, vsLinks :: Map QPN LinkGroup
, vsFlags :: FAssignment
, vsStanzas :: SAssignment
, vsQualifyOptions :: QualifyOptions
}
deriving Show
type Validate = Reader ValidateState
-- | Validate linked packages
--
-- Verify that linked packages have
--
-- * Linked dependencies,
-- * Equal flag assignments
-- * Equal stanza assignments
validateLinking :: Index -> Tree QGoalReason -> Tree QGoalReason
validateLinking index = (`runReader` initVS) . cata go
where
go :: TreeF QGoalReason (Validate (Tree QGoalReason)) -> Validate (Tree QGoalReason)
go (PChoiceF qpn gr cs) =
PChoice qpn gr <$> T.sequence (P.mapWithKey (goP qpn) cs)
go (FChoiceF qfn gr t m cs) =
FChoice qfn gr t m <$> T.sequence (P.mapWithKey (goF qfn) cs)
go (SChoiceF qsn gr t cs) =
SChoice qsn gr t <$> T.sequence (P.mapWithKey (goS qsn) cs)
-- For the other nodes we just recurse
go (GoalChoiceF cs) = GoalChoice <$> T.sequence cs
go (DoneF revDepMap) = return $ Done revDepMap
go (FailF conflictSet failReason) = return $ Fail conflictSet failReason
-- Package choices
goP :: QPN -> POption -> Validate (Tree QGoalReason) -> Validate (Tree QGoalReason)
goP qpn@(Q _pp pn) opt@(POption i _) r = do
vs <- ask
let PInfo deps _ _ = vsIndex vs ! pn ! i
qdeps = qualifyDeps (vsQualifyOptions vs) qpn deps
case execUpdateState (pickPOption qpn opt qdeps) vs of
Left (cs, err) -> return $ Fail cs (DependenciesNotLinked err)
Right vs' -> local (const vs') r
-- Flag choices
goF :: QFN -> Bool -> Validate (Tree QGoalReason) -> Validate (Tree QGoalReason)
goF qfn b r = do
vs <- ask
case execUpdateState (pickFlag qfn b) vs of
Left (cs, err) -> return $ Fail cs (DependenciesNotLinked err)
Right vs' -> local (const vs') r
-- Stanza choices (much the same as flag choices)
goS :: QSN -> Bool -> Validate (Tree QGoalReason) -> Validate (Tree QGoalReason)
goS qsn b r = do
vs <- ask
case execUpdateState (pickStanza qsn b) vs of
Left (cs, err) -> return $ Fail cs (DependenciesNotLinked err)
Right vs' -> local (const vs') r
initVS :: ValidateState
initVS = VS {
vsIndex = index
, vsLinks = M.empty
, vsFlags = M.empty
, vsStanzas = M.empty
, vsQualifyOptions = defaultQualifyOptions index
}
{-------------------------------------------------------------------------------
Updating the validation state
-------------------------------------------------------------------------------}
type Conflict = (ConflictSet QPN, String)
newtype UpdateState a = UpdateState {
unUpdateState :: StateT ValidateState (Either Conflict) a
}
deriving (Functor, Applicative, Monad)
instance MonadState ValidateState UpdateState where
get = UpdateState $ get
put st = UpdateState $ do
assert (lgInvariant $ vsLinks st) $ return ()
put st
lift' :: Either Conflict a -> UpdateState a
lift' = UpdateState . lift
conflict :: Conflict -> UpdateState a
conflict = lift' . Left
execUpdateState :: UpdateState () -> ValidateState -> Either Conflict ValidateState
execUpdateState = execStateT . unUpdateState
pickPOption :: QPN -> POption -> FlaggedDeps Component QPN -> UpdateState ()
pickPOption qpn (POption i Nothing) _deps = pickConcrete qpn i
pickPOption qpn (POption i (Just pp')) deps = pickLink qpn i pp' deps
pickConcrete :: QPN -> I -> UpdateState ()
pickConcrete qpn@(Q pp _) i = do
vs <- get
case M.lookup qpn (vsLinks vs) of
-- Package is not yet in a LinkGroup. Create a new singleton link group.
Nothing -> do
let lg = lgSingleton qpn (Just $ PI pp i)
updateLinkGroup lg
-- Package is already in a link group. Since we are picking a concrete
-- instance here, it must by definition be the canonical package.
Just lg ->
makeCanonical lg qpn i
pickLink :: QPN -> I -> PackagePath -> FlaggedDeps Component QPN -> UpdateState ()
pickLink qpn@(Q _pp pn) i pp' deps = do
vs <- get
-- The package might already be in a link group
-- (because one of its reverse dependencies is)
let lgSource = case M.lookup qpn (vsLinks vs) of
Nothing -> lgSingleton qpn Nothing
Just lg -> lg
-- Find the link group for the package we are linking to
--
-- Since the builder never links to a package without having first picked a
-- concrete instance for that package, and since we create singleton link
-- groups for concrete instances, this link group must exist (and must
-- in fact already have a canonical member).
let target = Q pp' pn
lgTarget = vsLinks vs ! target
-- Verify here that the member we add is in fact for the same package and
-- matches the version of the canonical instance. However, violations of
-- these checks would indicate a bug in the linker, not a true conflict.
let sanityCheck :: Maybe (PI PackagePath) -> Bool
sanityCheck Nothing = False
sanityCheck (Just (PI _ canonI)) = pn == lgPackage lgTarget && i == canonI
assert (sanityCheck (lgCanon lgTarget)) $ return ()
-- Merge the two link groups (updateLinkGroup will propagate the change)
lgTarget' <- lift' $ lgMerge [] lgSource lgTarget
updateLinkGroup lgTarget'
-- Make sure all dependencies are linked as well
linkDeps target [P qpn] deps
makeCanonical :: LinkGroup -> QPN -> I -> UpdateState ()
makeCanonical lg qpn@(Q pp _) i =
case lgCanon lg of
-- There is already a canonical member. Fail.
Just _ ->
conflict ( CS.insert (P qpn) (lgConflictSet lg)
, "cannot make " ++ showQPN qpn
++ " canonical member of " ++ showLinkGroup lg
)
Nothing -> do
let lg' = lg { lgCanon = Just (PI pp i) }
updateLinkGroup lg'
-- | Link the dependencies of linked parents.
--
-- When we decide to link one package against another we walk through the
-- package's direct depedencies and make sure that they're all linked to each
-- other by merging their link groups (or creating new singleton link groups if
-- they don't have link groups yet). We do not need to do this recursively,
-- because having the direct dependencies in a link group means that we must
-- have already made or will make sooner or later a link choice for one of these
-- as well, and cover their dependencies at that point.
linkDeps :: QPN -> [Var QPN] -> FlaggedDeps Component QPN -> UpdateState ()
linkDeps target = \blame deps -> do
-- linkDeps is called in two places: when we first link one package to
-- another, and when we discover more dependencies of an already linked
-- package after doing some flag assignment. It is therefore important that
-- flag assignments cannot influence _how_ dependencies are qualified;
-- fortunately this is a documented property of 'qualifyDeps'.
rdeps <- requalify deps
go blame deps rdeps
where
go :: [Var QPN] -> FlaggedDeps Component QPN -> FlaggedDeps Component QPN -> UpdateState ()
go = zipWithM_ . go1
go1 :: [Var QPN] -> FlaggedDep Component QPN -> FlaggedDep Component QPN -> UpdateState ()
go1 blame dep rdep = case (dep, rdep) of
(Simple (Dep qpn _) _, ~(Simple (Dep qpn' _) _)) -> do
vs <- get
let lg = M.findWithDefault (lgSingleton qpn Nothing) qpn $ vsLinks vs
lg' = M.findWithDefault (lgSingleton qpn' Nothing) qpn' $ vsLinks vs
lg'' <- lift' $ lgMerge blame lg lg'
updateLinkGroup lg''
(Flagged fn _ t f, ~(Flagged _ _ t' f')) -> do
vs <- get
case M.lookup fn (vsFlags vs) of
Nothing -> return () -- flag assignment not yet known
Just True -> go (F fn:blame) t t'
Just False -> go (F fn:blame) f f'
(Stanza sn t, ~(Stanza _ t')) -> do
vs <- get
case M.lookup sn (vsStanzas vs) of
Nothing -> return () -- stanza assignment not yet known
Just True -> go (S sn:blame) t t'
Just False -> return () -- stanza not enabled; no new deps
-- For extensions and language dependencies, there is nothing to do.
-- No choice is involved, just checking, so there is nothing to link.
-- The same goes for for pkg-config constraints.
(Simple (Ext _) _, _) -> return ()
(Simple (Lang _) _, _) -> return ()
(Simple (Pkg _ _) _, _) -> return ()
requalify :: FlaggedDeps Component QPN -> UpdateState (FlaggedDeps Component QPN)
requalify deps = do
vs <- get
return $ qualifyDeps (vsQualifyOptions vs) target (unqualifyDeps deps)
pickFlag :: QFN -> Bool -> UpdateState ()
pickFlag qfn b = do
modify $ \vs -> vs { vsFlags = M.insert qfn b (vsFlags vs) }
verifyFlag qfn
linkNewDeps (F qfn) b
pickStanza :: QSN -> Bool -> UpdateState ()
pickStanza qsn b = do
modify $ \vs -> vs { vsStanzas = M.insert qsn b (vsStanzas vs) }
verifyStanza qsn
linkNewDeps (S qsn) b
-- | Link dependencies that we discover after making a flag choice.
--
-- When we make a flag choice for a package, then new dependencies for that
-- package might become available. If the package under consideration is in a
-- non-trivial link group, then these new dependencies have to be linked as
-- well. In linkNewDeps, we compute such new dependencies and make sure they are
-- linked.
linkNewDeps :: Var QPN -> Bool -> UpdateState ()
linkNewDeps var b = do
vs <- get
let (qpn@(Q pp pn), Just i) = varPI var
PInfo deps _ _ = vsIndex vs ! pn ! i
qdeps = qualifyDeps (vsQualifyOptions vs) qpn deps
lg = vsLinks vs ! qpn
(parents, newDeps) = findNewDeps vs qdeps
linkedTo = S.delete pp (lgMembers lg)
forM_ (S.toList linkedTo) $ \pp' -> linkDeps (Q pp' pn) (P qpn : parents) newDeps
where
findNewDeps :: ValidateState -> FlaggedDeps comp QPN -> ([Var QPN], FlaggedDeps Component QPN)
findNewDeps vs = concatMapUnzip (findNewDeps' vs)
findNewDeps' :: ValidateState -> FlaggedDep comp QPN -> ([Var QPN], FlaggedDeps Component QPN)
findNewDeps' _ (Simple _ _) = ([], [])
findNewDeps' vs (Flagged qfn _ t f) =
case (F qfn == var, M.lookup qfn (vsFlags vs)) of
(True, _) -> ([F qfn], if b then t else f)
(_, Nothing) -> ([], []) -- not yet known
(_, Just b') -> let (parents, deps) = findNewDeps vs (if b' then t else f)
in (F qfn:parents, deps)
findNewDeps' vs (Stanza qsn t) =
case (S qsn == var, M.lookup qsn (vsStanzas vs)) of
(True, _) -> ([S qsn], if b then t else [])
(_, Nothing) -> ([], []) -- not yet known
(_, Just b') -> let (parents, deps) = findNewDeps vs (if b' then t else [])
in (S qsn:parents, deps)
updateLinkGroup :: LinkGroup -> UpdateState ()
updateLinkGroup lg = do
verifyLinkGroup lg
modify $ \vs -> vs {
vsLinks = M.fromList (map aux (S.toList (lgMembers lg)))
`M.union` vsLinks vs
}
where
aux pp = (Q pp (lgPackage lg), lg)
{-------------------------------------------------------------------------------
Verification
-------------------------------------------------------------------------------}
verifyLinkGroup :: LinkGroup -> UpdateState ()
verifyLinkGroup lg =
case lgInstance lg of
-- No instance picked yet. Nothing to verify
Nothing ->
return ()
-- We picked an instance. Verify flags and stanzas
-- TODO: The enumeration of OptionalStanza names is very brittle;
-- if a constructor is added to the datatype we won't notice it here
Just i -> do
vs <- get
let PInfo _deps finfo _ = vsIndex vs ! lgPackage lg ! i
flags = M.keys finfo
stanzas = [TestStanzas, BenchStanzas]
forM_ flags $ \fn -> do
let flag = FN (PI (lgPackage lg) i) fn
verifyFlag' flag lg
forM_ stanzas $ \sn -> do
let stanza = SN (PI (lgPackage lg) i) sn
verifyStanza' stanza lg
verifyFlag :: QFN -> UpdateState ()
verifyFlag (FN (PI qpn@(Q _pp pn) i) fn) = do
vs <- get
-- We can only pick a flag after picking an instance; link group must exist
verifyFlag' (FN (PI pn i) fn) (vsLinks vs ! qpn)
verifyStanza :: QSN -> UpdateState ()
verifyStanza (SN (PI qpn@(Q _pp pn) i) sn) = do
vs <- get
-- We can only pick a stanza after picking an instance; link group must exist
verifyStanza' (SN (PI pn i) sn) (vsLinks vs ! qpn)
-- | Verify that all packages in the link group agree on flag assignments
--
-- For the given flag and the link group, obtain all assignments for the flag
-- that have already been made for link group members, and check that they are
-- equal.
verifyFlag' :: FN PN -> LinkGroup -> UpdateState ()
verifyFlag' (FN (PI pn i) fn) lg = do
vs <- get
let flags = map (\pp' -> FN (PI (Q pp' pn) i) fn) (S.toList (lgMembers lg))
vals = map (`M.lookup` vsFlags vs) flags
if allEqual (catMaybes vals) -- We ignore not-yet assigned flags
then return ()
else conflict ( CS.fromList (map F flags) `CS.union` lgConflictSet lg
, "flag " ++ show fn ++ " incompatible"
)
-- | Verify that all packages in the link group agree on stanza assignments
--
-- For the given stanza and the link group, obtain all assignments for the
-- stanza that have already been made for link group members, and check that
-- they are equal.
--
-- This function closely mirrors 'verifyFlag''.
verifyStanza' :: SN PN -> LinkGroup -> UpdateState ()
verifyStanza' (SN (PI pn i) sn) lg = do
vs <- get
let stanzas = map (\pp' -> SN (PI (Q pp' pn) i) sn) (S.toList (lgMembers lg))
vals = map (`M.lookup` vsStanzas vs) stanzas
if allEqual (catMaybes vals) -- We ignore not-yet assigned stanzas
then return ()
else conflict ( CS.fromList (map S stanzas) `CS.union` lgConflictSet lg
, "stanza " ++ show sn ++ " incompatible"
)
{-------------------------------------------------------------------------------
Link groups
-------------------------------------------------------------------------------}
-- | Set of packages that must be linked together
--
-- A LinkGroup is between several qualified package names. In the validation
-- state, we maintain a map vsLinks from qualified package names to link groups.
-- There is an invariant that for all members of a link group, vsLinks must map
-- to the same link group. The function updateLinkGroup can be used to
-- re-establish this invariant after creating or expanding a LinkGroup.
data LinkGroup = LinkGroup {
-- | The name of the package of this link group
lgPackage :: PN
-- | The canonical member of this link group (the one where we picked
-- a concrete instance). Once we have picked a canonical member, all
-- other packages must link to this one.
--
-- We may not know this yet (if we are constructing link groups
-- for dependencies)
, lgCanon :: Maybe (PI PackagePath)
-- | The members of the link group
, lgMembers :: Set PackagePath
-- | The set of variables that should be added to the conflict set if
-- something goes wrong with this link set (in addition to the members
-- of the link group itself)
, lgBlame :: ConflictSet QPN
}
deriving (Show, Eq)
-- | Invariant for the set of link groups: every element in the link group
-- must be pointing to the /same/ link group
lgInvariant :: Map QPN LinkGroup -> Bool
lgInvariant links = all invGroup (M.elems links)
where
invGroup :: LinkGroup -> Bool
invGroup lg = allEqual $ map (`M.lookup` links) members
where
members :: [QPN]
members = map (`Q` lgPackage lg) $ S.toList (lgMembers lg)
-- | Package version of this group
--
-- This is only known once we have picked a canonical element.
lgInstance :: LinkGroup -> Maybe I
lgInstance = fmap (\(PI _ i) -> i) . lgCanon
showLinkGroup :: LinkGroup -> String
showLinkGroup lg =
"{" ++ intercalate "," (map showMember (S.toList (lgMembers lg))) ++ "}"
where
showMember :: PackagePath -> String
showMember pp = case lgCanon lg of
Just (PI pp' _i) | pp == pp' -> "*"
_otherwise -> ""
++ case lgInstance lg of
Nothing -> showQPN (qpn pp)
Just i -> showPI (PI (qpn pp) i)
qpn :: PackagePath -> QPN
qpn pp = Q pp (lgPackage lg)
-- | Creates a link group that contains a single member.
lgSingleton :: QPN -> Maybe (PI PackagePath) -> LinkGroup
lgSingleton (Q pp pn) canon = LinkGroup {
lgPackage = pn
, lgCanon = canon
, lgMembers = S.singleton pp
, lgBlame = CS.empty
}
lgMerge :: [Var QPN] -> LinkGroup -> LinkGroup -> Either Conflict LinkGroup
lgMerge blame lg lg' = do
canon <- pick (lgCanon lg) (lgCanon lg')
return LinkGroup {
lgPackage = lgPackage lg
, lgCanon = canon
, lgMembers = lgMembers lg `S.union` lgMembers lg'
, lgBlame = CS.unions [CS.fromList blame, lgBlame lg, lgBlame lg']
}
where
pick :: Eq a => Maybe a -> Maybe a -> Either Conflict (Maybe a)
pick Nothing Nothing = Right Nothing
pick (Just x) Nothing = Right $ Just x
pick Nothing (Just y) = Right $ Just y
pick (Just x) (Just y) =
if x == y then Right $ Just x
else Left ( CS.unions [
CS.fromList blame
, lgConflictSet lg
, lgConflictSet lg'
]
, "cannot merge " ++ showLinkGroup lg
++ " and " ++ showLinkGroup lg'
)
lgConflictSet :: LinkGroup -> ConflictSet QPN
lgConflictSet lg =
CS.fromList (map aux (S.toList (lgMembers lg)))
`CS.union` lgBlame lg
where
aux pp = P (Q pp (lgPackage lg))
{-------------------------------------------------------------------------------
Auxiliary
-------------------------------------------------------------------------------}
allEqual :: Eq a => [a] -> Bool
allEqual [] = True
allEqual [_] = True
allEqual (x:y:ys) = x == y && allEqual (y:ys)
concatMapUnzip :: (a -> ([b], [c])) -> [a] -> ([b], [c])
concatMapUnzip f = (\(xs, ys) -> (concat xs, concat ys)) . unzip . map f
|
thomie/cabal
|
cabal-install/Distribution/Solver/Modular/Linking.hs
|
bsd-3-clause
| 23,716 | 0 | 21 | 6,079 | 5,993 | 3,087 | 2,906 | 333 | 11 |
-----------------------------------------------------------------------------
-- |
-- Module : XMonad.Actions.TiledWindowDragging
-- Description : Change the position of windows by dragging them.
-- Copyright : (c) 2020 Leon Kowarschick
-- License : BSD3-style (see LICENSE)
--
-- Maintainer : Leon Kowarschick. <[email protected]>
-- Stability : unstable
-- Portability : unportable
--
-- Provides an action that allows you to change the position of windows by dragging them around.
--
-----------------------------------------------------------------------------
module XMonad.Actions.TiledWindowDragging
(
-- * Usage
-- $usage
dragWindow
)
where
import XMonad
import XMonad.Prelude
import qualified XMonad.StackSet as W
import XMonad.Layout.DraggingVisualizer
-- $usage
-- You can use this module with the following in your @~\/.xmonad\/xmonad.hs@:
--
-- > import XMonad.Actions.TiledWindowDragging
-- > import XMonad.Layout.DraggingVisualizer
--
-- then edit your 'layoutHook' by adding the draggingVisualizer to your layout:
--
-- > myLayout = draggingVisualizer $ layoutHook def
--
-- Then add a mouse binding for 'dragWindow':
--
-- > , ((modMask .|. shiftMask, button1), dragWindow)
--
-- For detailed instructions on editing your mouse bindings, see
-- "XMonad.Doc.Extending#Editing_mouse_bindings".
-- | Create a mouse binding for this to be able to drag your windows around.
-- You need "XMonad.Layout.DraggingVisualizer" for this to look good.
dragWindow :: Window -> X ()
dragWindow window = whenX (isClient window) $ withDisplay $ \dpy ->
withWindowAttributes dpy window $ \wa -> do
focus window
(offsetX, offsetY) <- getPointerOffset window
let (winX, winY, winWidth, winHeight) = getWindowPlacement wa
mouseDrag
(\posX posY ->
let rect = Rectangle (fi (fi winX + (posX - fi offsetX)))
(fi (fi winY + (posY - fi offsetY)))
(fi winWidth)
(fi winHeight)
in sendMessage $ DraggingWindow window rect
)
(sendMessage DraggingStopped >> performWindowSwitching window)
-- | get the pointer offset relative to the given windows root coordinates
getPointerOffset :: Window -> X (Int, Int)
getPointerOffset win = do
(_, _, _, oX, oY, _, _, _) <- withDisplay (\d -> io $ queryPointer d win)
return (fi oX, fi oY)
-- | return a tuple of windowX, windowY, windowWidth, windowHeight
getWindowPlacement :: WindowAttributes -> (Int, Int, Int, Int)
getWindowPlacement wa = (fi $ wa_x wa, fi $ wa_y wa, fi $ wa_width wa, fi $ wa_height wa)
performWindowSwitching :: Window -> X ()
performWindowSwitching win = do
root <- asks theRoot
(_, _, selWin, _, _, _, _, _) <- withDisplay (\d -> io $ queryPointer d root)
ws <- gets windowset
let allWindows = W.index ws
when ((win `elem` allWindows) && (selWin `elem` allWindows)) $ do
let allWindowsSwitched = map (switchEntries win selWin) allWindows
(ls, t : rs) <- pure $ break (== win) allWindowsSwitched
let newStack = W.Stack t (reverse ls) rs
windows $ W.modify' $ const newStack
where
switchEntries a b x | x == a = b
| x == b = a
| otherwise = x
|
xmonad/xmonad-contrib
|
XMonad/Actions/TiledWindowDragging.hs
|
bsd-3-clause
| 3,457 | 0 | 25 | 911 | 743 | 398 | 345 | 41 | 1 |
module Test.Feat.Class
( Enumerable(..)
, nullary
, unary
, funcurry
, shared
, consts
) where
import Control.Enumerable
-- compatability
{-# DEPRECATED nullary "use c0 instead" #-}
-- nullary :: x -> Memoizable f x
nullary x = c0 x
{-# DEPRECATED unary "use c1 instead" #-}
-- unary :: (Enumerable a, MemoSized f) => (a -> x) -> f x
unary x = c1 x
{-# DEPRECATED shared "use access instead" #-}
shared :: (Sized f, Enumerable a, Typeable f) => Shareable f a
shared = access
funcurry = uncurry
{-# DEPRECATED consts "use datatype instead" #-}
--consts :: (Typeable a, MemoSized f) => [f a] -> Closed (f a)
consts xs = datatype xs
|
patrikja/testing-feat
|
Test/Feat/Class.hs
|
bsd-3-clause
| 683 | 0 | 6 | 168 | 118 | 69 | 49 | 18 | 1 |
-- -*- mode: haskell -*-
{-# LANGUAGE TemplateHaskell #-}
module PCProblem.Konfig where
import PCProblem.Type
import Autolib.ToDoc
import Autolib.Reader
data Konfig =
Konfig { instanz :: PCP
, folge :: Folge -- ^ achtung, falschrum! (damit wir vorn dranbauen)
, tief :: Int -- ^ im Suchbaum (= Länge der Folge)
, oben :: String -- ^ einer von beiden soll leer sein
, unten :: String -- ^ d. h. gemeinsame präfixe werden abgeschnitten
}
-- | zum schnelleren vergleichen
wesen :: Konfig -> ( Int, Int, String, String )
wesen k = ( length $ oben k, length $ unten k
, oben k , unten k
)
instance Eq Konfig where
k1 == k2 = wesen k1 == wesen k2
instance Ord Konfig where
compare k1 k2 = compare ( wesen k1 ) ( wesen k2 )
$(derives [makeReader, makeToDoc] [''Konfig])
instance Show Konfig where show = render . toDoc
instance Read Konfig where readsPrec = parsec_readsPrec
|
florianpilz/autotool
|
src/PCProblem/Konfig.hs
|
gpl-2.0
| 935 | 4 | 9 | 224 | 249 | 138 | 111 | 21 | 1 |
{-# LANGUAGE UndecidableInstances, TypeFamilies, BangPatterns, Rank2Types
, ExistentialQuantification, PatternGuards, ScopedTypeVariables
, MultiParamTypeClasses, GADTs
#-}
{-# OPTIONS_GHC -Wall #-}
----------------------------------------------------------------------
-- |
-- Module : Shady.Language.Reify
-- Copyright : (c) Conal Elliott 2009
-- License : AGPLv3
--
-- Maintainer : [email protected]
-- Stability : experimental
--
-- Discover representation sharing in expressions
-- Variation on Andy Gill's Data.Reify.
----------------------------------------------------------------------
module Shady.Language.Reify (reifyGraph) where
import Control.Concurrent.MVar
-- import Control.Monad
import System.Mem.StableName
import Data.IntMap as M
import Shady.Language.Exp
import Shady.Language.Graph
data StableBind = forall a. HasType a => StableBind NodeId (StableName (E a))
-- | 'reifyGraph' takes a data structure that admits 'MuRef', and returns
-- a 'Graph' that contains the dereferenced nodes, with their children as
-- integers rather than recursive values.
reifyGraph :: HasType a => E a -> IO (Graph a)
reifyGraph e = do rt1 <- newMVar M.empty
rt2 <- newMVar []
root <- findNodes rt1 rt2 e
binds <- readMVar rt2
return (Graph binds (Tid root typeT))
findNodes :: HasType a =>
MVar (IntMap [StableBind])
-> MVar [Bind]
-> E a -> IO NodeId
findNodes rt1 rt2 ea =
do nextI <- newMVar 0
let newIndex = modifyMVar nextI (\ n -> return (n+1,n))
loop :: HasType b => E b -> IO NodeId
loop !eb = do
st <- makeStableName eb
tab <- takeMVar rt1
case mylookup st tab of
Just i -> do putMVar rt1 tab
return $ i
Nothing ->
do i <- newIndex
putMVar rt1 $
M.insertWith (++) (hashStableName st) [StableBind i st] tab
res <- mapDeRef loop eb
tab' <- takeMVar rt2
putMVar rt2 $ Bind i res : tab'
return i
in loop ea
mylookup :: forall a. HasType a =>
StableName (E a) -> IntMap [StableBind] -> Maybe NodeId
mylookup sta tab =
M.lookup (hashStableName sta) tab >>= llookup
where
tya :: Type a
tya = typeT
llookup :: [StableBind] -> Maybe NodeId
llookup [] = Nothing
llookup (StableBind i stb : binds')
| Just Refl <- tya `tyEq` typeOf2 stb, sta == stb = Just i
| otherwise = llookup binds'
|
sseefried/shady-gen
|
src/Shady/Language/Reify.hs
|
agpl-3.0
| 2,730 | 0 | 21 | 887 | 674 | 331 | 343 | 51 | 2 |
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="ru-RU">
<title>SVN Digger Files</title>
<maps>
<homeID>svndigger</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>
|
secdec/zap-extensions
|
addOns/svndigger/src/main/javahelp/help_ru_RU/helpset_ru_RU.hs
|
apache-2.0
| 967 | 77 | 66 | 157 | 409 | 207 | 202 | -1 | -1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE CPP #-}
module Test.Foundation.Number
( testNumber
, testNumberRefs
) where
import Foundation
import Foundation.Check
import qualified Prelude
testIntegral :: forall a . (Arbitrary a, Show a, IsIntegral a, Integral a, Typeable a)
=> Proxy a -> Test
testIntegral _ = Group "Integral"
[ Property "FromIntegral(Integer(a)) == a" $ \(a :: a) -> fromInteger (toInteger a) === a
]
testEqOrd :: forall a . (Arbitrary a, Show a, Eq a, Ord a, IsIntegral a, Typeable a)
=> Proxy a -> Test
testEqOrd _ = Group "Property"
[ Property "Eq" $ \(a :: a) -> a === a
-- , Property "Ne" $ \(a :: a) (b :: a) -> if a === w
, Property "Show" $ \(a :: a) -> show a === show (toInteger a)
, Property "Ord" $ \(a :: a) (b :: a) -> compare a b === (compare `on` toInteger) a b
, Property "<" $ \(a :: a) (b :: a) -> case compare a b of
LT -> propertyCompare "<" (<) a b
GT -> propertyCompare "<" (<) b a
EQ -> propertyCompare "not <" ((not .) . (<)) a b `propertyAnd`
propertyCompare "not <" ((not .) . (<)) b a
]
testAdditive :: forall a . (Show a, Eq a, Additive a, Arbitrary a, Typeable a)
=> Proxy a -> Test
testAdditive _ = Group "Additive"
[ Property "a + azero == a" $ \(a :: a) -> a + azero === a
, Property "azero + a == a" $ \(a :: a) -> azero + a === a
, Property "a + b == b + a" $ \(a :: a) (b :: a) -> a + b === b + a
]
testMultiplicative :: forall a . (Show a, Eq a, IsIntegral a, Integral a, Multiplicative a, Arbitrary a, Typeable a)
=> Proxy a -> Test
testMultiplicative _ = Group "Multiplicative"
[ Property "a * 1 == a" $ \(a :: a) -> a * midentity === a
, Property "1 * a == a" $ \(a :: a) -> midentity * a === a
, Property "multiplication commutative" $ \(a :: a) (b :: a) -> a * b == b * a
, Property "a * b == Integer(a) * Integer(b)" $ \(a :: a) (b :: a) -> a * b == fromInteger (toInteger a * toInteger b)
]
testDividible :: forall a . (Show a, Eq a, IsIntegral a, IDivisible a, Arbitrary a, Typeable a)
=> Proxy a -> Test
testDividible _ = Group "Divisible"
[ Property "(x `div` y) * y + (x `mod` y) == x" $ \(a :: a) b ->
if b == 0 then True === True
else a === (a `div` b) * b + (a `mod` b)
]
testOperatorPrecedence :: forall a . (Show a, Eq a, Prelude.Num a, IsIntegral a, Additive a, Subtractive a, Multiplicative a, Difference a ~ a, Arbitrary a, Typeable a)
=> Proxy a -> Test
testOperatorPrecedence _ = Group "Precedence"
[ Property "+ and - (1)" $ \(a :: a) (b :: a) (c :: a) -> (a + b - c) === ((a + b) - c)
, Property "+ and - (2)" $ \(a :: a) (b :: a) (c :: a) -> (a - b + c) === ((a - b) + c)
, Property "+ and * (1)" $ \(a :: a) (b :: a) (c :: a) -> (a + b * c) === (a + (b * c))
, Property "+ and * (2)" $ \(a :: a) (b :: a) (c :: a) -> (a * b + c) === ((a * b) + c)
, Property "- and * (1)" $ \(a :: a) (b :: a) (c :: a) -> (a - b * c) === (a - (b * c))
, Property "- and * (2)" $ \(a :: a) (b :: a) (c :: a) -> (a * b - c) === ((a * b) - c)
, Property "* and ^ (1)" $ \(a :: a) (b :: Natural) (c :: a) -> (a ^ b * c) === ((a ^ b) * c)
, Property "* and ^ (2)" $ \(a :: a) (c :: Natural) (b :: a) -> (a * b ^ c) === (a * (b ^ c))
]
testNumber :: (Show a, Eq a, Prelude.Num a, IsIntegral a, Additive a, Multiplicative a, Subtractive a, Difference a ~ a, IDivisible a, Arbitrary a, Typeable a)
=> String -> Proxy a -> Test
testNumber name proxy = Group name
[ testIntegral proxy
, testEqOrd proxy
, testAdditive proxy
, testMultiplicative proxy
, testDividible proxy
, testOperatorPrecedence proxy
]
testNumberRefs :: [Test]
testNumberRefs =
[ testNumber "Int" (Proxy :: Proxy Int)
, testNumber "Int8" (Proxy :: Proxy Int8)
, testNumber "Int16" (Proxy :: Proxy Int16)
, testNumber "Int32" (Proxy :: Proxy Int32)
, testNumber "Int64" (Proxy :: Proxy Int64)
, testNumber "Integer" (Proxy :: Proxy Integer)
, testNumber "Word" (Proxy :: Proxy Word)
, testNumber "Word8" (Proxy :: Proxy Word8)
, testNumber "Word16" (Proxy :: Proxy Word16)
, testNumber "Word32" (Proxy :: Proxy Word32)
, testNumber "Word64" (Proxy :: Proxy Word64)
, testNumber "Word128" (Proxy :: Proxy Word128)
, testNumber "Word256" (Proxy :: Proxy Word256)
]
|
vincenthz/hs-foundation
|
foundation/tests/Test/Foundation/Number.hs
|
bsd-3-clause
| 4,792 | 0 | 16 | 1,465 | 2,016 | 1,077 | 939 | 81 | 3 |
{-# LANGUAGE TemplateHaskellQuotes #-}
{-# LANGUAGE MultiParamTypeClasses #-}
module Main (main) where
import Language.Haskell.TH
u1 :: a
u1 = undefined
u2 :: a
u2 = undefined
f :: a
f = undefined
(.+.) :: a
(.+.) = undefined
main :: IO ()
main = do runQ [| f u1 u2 |] >>= p
runQ [| u1 `f` u2 |] >>= p
runQ [| (.+.) u1 u2 |] >>= p
runQ [| u1 .+. u2 |] >>= p
runQ [| (:) u1 u2 |] >>= p
runQ [| u1 : u2 |] >>= p
runQ [| \((:) x xs) -> x |] >>= p
runQ [| \(x : xs) -> x |] >>= p
runQ [d| class Foo a b where
foo :: a -> b |] >>= p
runQ [| \x -> (x, 1 `x` 2) |] >>= p
runQ [| \(+) -> ((+), 1 + 2) |] >>= p
runQ [| (f, 1 `f` 2) |] >>= p
runQ [| ((.+.), 1 .+. 2) |] >>= p
p :: Ppr a => a -> IO ()
p = putStrLn . pprint
|
mpickering/ghc-exactprint
|
tests/examples/ghc8/TH_ppr1.hs
|
bsd-3-clause
| 867 | 0 | 8 | 336 | 276 | 155 | 121 | -1 | -1 |
#!/usr/bin/env runhaskell
-- |
-- Module : $Header$
-- Copyright : (c) 2013-2014 Galois, Inc.
-- License : BSD3
-- Maintainer : [email protected]
-- Stability : provisional
-- Portability : portable
import Cryptol.Parser
import Cryptol.Parser.AST(noPos)
import System.Process(readProcess)
main :: IO ()
main =
do txt <- getContents
putStrLn =<< readProcess "ppsh" ["--html"]
(show $ dropLoc $ parseProgram Layout txt)
dropLoc (Right a) = Right (noPos a)
dropLoc (Left a) = Left a
|
TomMD/cryptol
|
utils/CryAST.hs
|
bsd-3-clause
| 534 | 0 | 11 | 125 | 130 | 70 | 60 | 10 | 1 |
module Main where
import Data.Char
import Data.List
import System.IO
data Test = Expr String
| Test [String] String
deriving Show
isExpr (Expr{}) = True
isExpr _ = False
main = do src <- readFile "../System/FilePath/Internal.hs"
let tests = concatMap getTest $ zip [1..] (lines src)
writeFile "FilePath_Test.hs" (prefix ++ genTests tests)
prefix = unlines
["import AutoTest"
,"import qualified System.FilePath.Windows as W"
,"import qualified System.FilePath.Posix as P"
,"main = do"
]
getTest :: (Int,String) -> [(Int,Test)]
getTest (line,xs) | "-- > " `isPrefixOf` xs = f $ drop 5 xs
where
f x | "Windows:" `isPrefixOf` x = let res = grabTest (drop 8 x) in [g "W" res]
| "Posix:" `isPrefixOf` x = let res = grabTest (drop 6 x) in [g "P" res]
| otherwise = let res = grabTest x in [g "W" res, g "P" res]
g p (Expr x) = (line,Expr (h p x))
g p (Test a x) = (line,Test a (h p x))
h p x = joinLex $ map (addPrefix p) $ makeValid $ splitLex x
getTest _ = []
addPrefix :: String -> String -> String
addPrefix pre str | str `elem` fpops || (all isAlpha str && length str > 1 && not (str `elem` prelude))
= pre ++ "." ++ str
| otherwise = str
prelude = ["elem","uncurry","snd","fst","not","null","if","then","else"
,"True","False","concat","isPrefixOf","isSuffixOf"]
fpops = ["</>","<.>"]
grabTest :: String -> Test
grabTest x = if null free then Expr x else Test free x
where
free = sort $ nub [x | x <- lexs, length x == 1, all isAlpha x]
lexs = splitLex x
splitLex :: String -> [String]
splitLex x = case lex x of
[("","")] -> []
[(x,y)] -> x : splitLex y
y -> error $ "GenTests.splitLex, " ++ show x ++ " -> " ++ show y
-- Valid a => z ===> (\a -> z) (makeValid a)
makeValid :: [String] -> [String]
makeValid ("Valid":a:"=>":z) = "(\\":a:"->":z ++ ")":"(":"makeValid":a:")":[]
makeValid x = x
joinLex :: [String] -> String
joinLex = unwords
-- would be concat, but GHC has 'issues'
rejoinTests :: [String] -> String
rejoinTests xs = unlines $
[" block" ++ show i | i <- [1..length res]] ++
concat (zipWith rejoin [1..] res)
where
res = divide xs
divide [] = []
divide x = a : divide b
where (a,b) = splitAt 50 x
rejoin n xs = ("block" ++ show n ++ " = do") : xs
genTests :: [(Int, Test)] -> String
genTests xs = rejoinTests $ concatMap f $ zip [1..] (one++many)
where
(one,many) = partition (isExpr . snd) xs
f (tno,(lno,test)) =
[" putStrLn \"Test " ++ show tno ++ ", from line " ++ show lno ++ "\""
," " ++ genTest test]
-- the result must be a line of the type "IO ()"
genTest :: Test -> String
genTest (Expr x) = "constTest (" ++ x ++ ")"
genTest (Test free x) = "quickSafe (\\" ++ concatMap ((' ':) . f) free ++ " -> (" ++ x ++ "))"
where
f [a] | a >= 'x' = "(QFilePath " ++ [a] ++ ")"
f x = x
|
thomie/filepath
|
tests/GenTests.hs
|
bsd-3-clause
| 3,147 | 0 | 14 | 970 | 1,300 | 678 | 622 | 67 | 3 |
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE TransformListComp #-}
module Fun00012 where
data instance A = M { unA :: T -> A }
data instance B where
K :: D -> B
f = [ (x, y) | x <- xs,
y <- ys,
then sortWith ]
g = [ (x, y) | x <- xs,
y <- ys,
then sortWith by (x + y) ]
h = [ (x, y) | x <- xs,
y <- ys,
then group using permutations ]
i = [ (x, y) | x <- xs,
y <- ys,
then group by (x + y) using groupWith ]
{-# RULES "f" f True = False #-}
|
charleso/intellij-haskforce
|
tests/gold/parser/Fun00012.hs
|
apache-2.0
| 592 | 0 | 10 | 246 | 210 | 120 | 90 | 20 | 1 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# OPTIONS -fno-warn-unused-do-bind #-}
-- | Package identifier (name-version).
module Stack.Types.PackageIdentifier
( PackageIdentifier(..)
, PackageIdentifierRevision(..)
, CabalHash
, mkCabalHashFromSHA256
, computeCabalHash
, showCabalHash
, CabalFileInfo(..)
, toTuple
, fromTuple
, parsePackageIdentifier
, parsePackageIdentifierFromString
, parsePackageIdentifierRevision
, packageIdentifierParser
, packageIdentifierString
, packageIdentifierRevisionString
, packageIdentifierText
, toCabalPackageIdentifier
, fromCabalPackageIdentifier
, StaticSHA256
, mkStaticSHA256FromText
, mkStaticSHA256FromFile
, mkStaticSHA256FromDigest
, staticSHA256ToText
, staticSHA256ToBase16
, staticSHA256ToRaw
)
where
import Stack.Prelude
import Crypto.Hash.Conduit (hashFile)
import Crypto.Hash as Hash (hashlazy, Digest, SHA256)
import Data.Aeson.Extended
import Data.Attoparsec.Text as A
import qualified Data.ByteArray
import qualified Data.ByteArray.Encoding as Mem
import qualified Data.ByteString.Lazy as L
import qualified Data.Text as T
import Data.Text.Encoding (decodeUtf8, encodeUtf8)
import qualified Distribution.Package as C
import Stack.StaticBytes
import Stack.Types.PackageName
import Stack.Types.Version
-- | A parse fail.
data PackageIdentifierParseFail
= PackageIdentifierParseFail Text
| PackageIdentifierRevisionParseFail Text
deriving (Typeable)
instance Show PackageIdentifierParseFail where
show (PackageIdentifierParseFail bs) = "Invalid package identifier: " ++ show bs
show (PackageIdentifierRevisionParseFail bs) = "Invalid package identifier (with optional revision): " ++ show bs
instance Exception PackageIdentifierParseFail
-- | A pkg-ver combination.
data PackageIdentifier = PackageIdentifier
{ -- | Get the name part of the identifier.
packageIdentifierName :: !PackageName
-- | Get the version part of the identifier.
, packageIdentifierVersion :: !Version
} deriving (Eq,Ord,Generic,Data,Typeable)
instance NFData PackageIdentifier where
rnf (PackageIdentifier !p !v) =
seq (rnf p) (rnf v)
instance Hashable PackageIdentifier
instance Store PackageIdentifier
instance Show PackageIdentifier where
show = show . packageIdentifierString
instance ToJSON PackageIdentifier where
toJSON = toJSON . packageIdentifierString
instance FromJSON PackageIdentifier where
parseJSON = withText "PackageIdentifier" $ \t ->
case parsePackageIdentifier t of
Left e -> fail $ show (e, t)
Right x -> return x
-- | A 'PackageIdentifier' combined with optionally specified Hackage
-- cabal file revision.
data PackageIdentifierRevision = PackageIdentifierRevision
{ pirIdent :: !PackageIdentifier
, pirRevision :: !CabalFileInfo
} deriving (Eq,Ord,Generic,Data,Typeable)
instance NFData PackageIdentifierRevision where
rnf (PackageIdentifierRevision !i !c) =
seq (rnf i) (rnf c)
instance Hashable PackageIdentifierRevision
instance Store PackageIdentifierRevision
instance Show PackageIdentifierRevision where
show = show . packageIdentifierRevisionString
instance ToJSON PackageIdentifierRevision where
toJSON = toJSON . packageIdentifierRevisionString
instance FromJSON PackageIdentifierRevision where
parseJSON = withText "PackageIdentifierRevision" $ \t ->
case parsePackageIdentifierRevision t of
Left e -> fail $ show (e, t)
Right x -> return x
-- | A cryptographic hash of a Cabal file.
newtype CabalHash = CabalHash { unCabalHash :: StaticSHA256 }
deriving (Generic, Show, Eq, NFData, Data, Typeable, Ord, Store, Hashable)
-- | A SHA256 hash, stored in a static size for more efficient
-- serialization with store.
newtype StaticSHA256 = StaticSHA256 Bytes32
deriving (Generic, Show, Eq, NFData, Data, Typeable, Ord, Hashable, Store)
-- | Generate a 'StaticSHA256' value from a base16-encoded SHA256 hash.
mkStaticSHA256FromText :: Text -> Either SomeException StaticSHA256
mkStaticSHA256FromText t =
mapLeft (toException . stringException) (Mem.convertFromBase Mem.Base16 (encodeUtf8 t))
>>= either (Left . toE) (Right . StaticSHA256)
. toStaticExact
. (id :: ByteString -> ByteString)
where
toE e = toException $ stringException $ concat
[ "Unable to convert "
, show t
, " into SHA256: "
, show e
]
-- | Generate a 'StaticSHA256' value from the contents of a file.
mkStaticSHA256FromFile :: MonadIO m => Path Abs File -> m StaticSHA256
mkStaticSHA256FromFile fp = liftIO $ mkStaticSHA256FromDigest <$> hashFile (toFilePath fp)
mkStaticSHA256FromDigest :: Hash.Digest Hash.SHA256 -> StaticSHA256
mkStaticSHA256FromDigest digest
= StaticSHA256
$ either impureThrow id
$ toStaticExact
(Data.ByteArray.convert digest :: ByteString)
-- | Convert a 'StaticSHA256' into a base16-encoded SHA256 hash.
staticSHA256ToText :: StaticSHA256 -> Text
staticSHA256ToText = decodeUtf8 . staticSHA256ToBase16
-- | Convert a 'StaticSHA256' into a base16-encoded SHA256 hash.
staticSHA256ToBase16 :: StaticSHA256 -> ByteString
staticSHA256ToBase16 (StaticSHA256 x) = Mem.convertToBase Mem.Base16 x
staticSHA256ToRaw :: StaticSHA256 -> ByteString
staticSHA256ToRaw (StaticSHA256 x) = Data.ByteArray.convert x
-- | Generate a 'CabalHash' value from a base16-encoded SHA256 hash.
mkCabalHashFromSHA256 :: Text -> Either SomeException CabalHash
mkCabalHashFromSHA256 = fmap CabalHash . mkStaticSHA256FromText
-- | Convert a 'CabalHash' into a base16-encoded SHA256 hash.
cabalHashToText :: CabalHash -> Text
cabalHashToText = staticSHA256ToText . unCabalHash
-- | Compute a 'CabalHash' value from a cabal file's contents.
computeCabalHash :: L.ByteString -> CabalHash
computeCabalHash = CabalHash . mkStaticSHA256FromDigest . Hash.hashlazy
showCabalHash :: CabalHash -> Text
showCabalHash = T.append (T.pack "sha256:") . cabalHashToText
-- | Information on the contents of a cabal file
data CabalFileInfo
= CFILatest
-- ^ Take the latest revision of the cabal file available. This
-- isn't reproducible at all, but the running assumption (not
-- necessarily true) is that cabal file revisions do not change
-- semantics of the build.
| CFIHash
!(Maybe Int) -- file size in bytes
!CabalHash
-- ^ Identify by contents of the cabal file itself
| CFIRevision !Word
-- ^ Identify by revision number, with 0 being the original and
-- counting upward.
deriving (Generic, Show, Eq, Ord, Data, Typeable)
instance Store CabalFileInfo
instance NFData CabalFileInfo
instance Hashable CabalFileInfo
-- | Convert from a package identifier to a tuple.
toTuple :: PackageIdentifier -> (PackageName,Version)
toTuple (PackageIdentifier n v) = (n,v)
-- | Convert from a tuple to a package identifier.
fromTuple :: (PackageName,Version) -> PackageIdentifier
fromTuple (n,v) = PackageIdentifier n v
-- | A parser for a package-version pair.
packageIdentifierParser :: Parser PackageIdentifier
packageIdentifierParser =
do name <- packageNameParser
char '-'
version <- versionParser
return (PackageIdentifier name version)
-- | Convenient way to parse a package identifier from a 'Text'.
parsePackageIdentifier :: MonadThrow m => Text -> m PackageIdentifier
parsePackageIdentifier x = go x
where go =
either (const (throwM (PackageIdentifierParseFail x))) return .
parseOnly (packageIdentifierParser <* endOfInput)
-- | Convenience function for parsing from a 'String'.
parsePackageIdentifierFromString :: MonadThrow m => String -> m PackageIdentifier
parsePackageIdentifierFromString =
parsePackageIdentifier . T.pack
-- | Parse a 'PackageIdentifierRevision'
parsePackageIdentifierRevision :: MonadThrow m => Text -> m PackageIdentifierRevision
parsePackageIdentifierRevision x = go x
where
go =
either (const (throwM (PackageIdentifierRevisionParseFail x))) return .
parseOnly (parser <* endOfInput)
parser = PackageIdentifierRevision
<$> packageIdentifierParser
<*> (cfiHash <|> cfiRevision <|> pure CFILatest)
cfiHash = do
_ <- string $ T.pack "@sha256:"
hash' <- A.takeWhile (/= ',')
hash'' <- either (\e -> fail $ "Invalid SHA256: " ++ show e) return
$ mkCabalHashFromSHA256 hash'
msize <- optional $ do
_ <- A.char ','
A.decimal
A.endOfInput
return $ CFIHash msize hash''
cfiRevision = do
_ <- string $ T.pack "@rev:"
y <- A.decimal
A.endOfInput
return $ CFIRevision y
-- | Get a string representation of the package identifier; name-ver.
packageIdentifierString :: PackageIdentifier -> String
packageIdentifierString (PackageIdentifier n v) = show n ++ "-" ++ show v
-- | Get a string representation of the package identifier with revision; name-ver[@hashtype:hash[,size]].
packageIdentifierRevisionString :: PackageIdentifierRevision -> String
packageIdentifierRevisionString (PackageIdentifierRevision ident cfi) =
concat $ packageIdentifierString ident : rest
where
rest =
case cfi of
CFILatest -> []
CFIHash msize hash' ->
"@sha256:"
: T.unpack (cabalHashToText hash')
: showSize msize
CFIRevision rev -> ["@rev:", show rev]
showSize Nothing = []
showSize (Just int) = [',' : show int]
-- | Get a Text representation of the package identifier; name-ver.
packageIdentifierText :: PackageIdentifier -> Text
packageIdentifierText = T.pack . packageIdentifierString
toCabalPackageIdentifier :: PackageIdentifier -> C.PackageIdentifier
toCabalPackageIdentifier x =
C.PackageIdentifier
(toCabalPackageName (packageIdentifierName x))
(toCabalVersion (packageIdentifierVersion x))
fromCabalPackageIdentifier :: C.PackageIdentifier -> PackageIdentifier
fromCabalPackageIdentifier (C.PackageIdentifier name version) =
PackageIdentifier
(fromCabalPackageName name)
(fromCabalVersion version)
|
anton-dessiatov/stack
|
src/Stack/Types/PackageIdentifier.hs
|
bsd-3-clause
| 10,288 | 0 | 15 | 1,877 | 2,113 | 1,117 | 996 | 221 | 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>Custom Payloads Add-on</title>
<maps>
<homeID>custompayloads</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/custompayloads/src/main/javahelp/org/zaproxy/zap/extension/custompayloads/resources/help_sq_AL/helpset_sq_AL.hs
|
apache-2.0
| 978 | 77 | 67 | 157 | 413 | 209 | 204 | -1 | -1 |
module MultiMatchesIn1 where
--The application of a function is replaced by the right-hand side of the definition,
--with actual parameters replacing formals.
--In this example, unfold the first 'sq' in 'sumSquares'
--This example aims to test unfolding a function application with multiple matches.
sumSquares x y = (case x of
0 -> 0
x -> sq x) + sq y
sq 0=0
sq x=x^pow
pow=2
|
kmate/HaRe
|
old/testing/foldDef/MultiMatchesIn1_TokOut.hs
|
bsd-3-clause
| 425 | 0 | 10 | 113 | 72 | 39 | 33 | 7 | 2 |
-- | File Manager demo.
-- Author : Andy Stewart
-- Copyright : (c) 2010 Andy Stewart <[email protected]>
-- | This simple file-manager base on gio.
--
module Main where
import Control.Monad
import Data.Maybe
import Graphics.UI.Gtk
import Graphics.UI.Gtk.General.IconTheme
import Graphics.UI.Gtk.ModelView
import System.GIO
import System.Glib.GDateTime
import System.Glib.GError
import System.Locale
import System.Time
import Text.Printf
import qualified Data.ByteString.UTF8 as UTF8
data FMInfo = FMInfo {
fIcon :: Pixbuf, -- icon
fName :: String, -- file name
fDesc :: String, -- mime type description
fSize :: Integer, -- file size
fTime :: ClockTime -- modified time
}
-- | Main.
main :: IO ()
main = do
-- Init.
initGUI
-- Create window.
window <- windowNew
windowSetDefaultSize window 900 600
windowSetPosition window WinPosCenter
scrolledWindow <- scrolledWindowNew Nothing Nothing
window `containerAdd` scrolledWindow
-- Get file infos under specify directory.
infos <- directoryGetFileInfos "/"
-- Get FMInfo.
fInfos <- mapM (\info -> do
-- Get Icon.
icon <- fileInfoGetIcon info
iconTheme <- iconThemeGetDefault
iconInfo <- iconThemeLookupByGIcon iconTheme icon 24 IconLookupUseBuiltin
pixbuf <- case iconInfo of
Just ii -> iconInfoLoadIcon ii
Nothing -> liftM fromJust $ iconThemeLoadIcon iconTheme "unknown" 24 IconLookupUseBuiltin
let
-- Get file name.
name = fromJust $ fileInfoGetName info
-- File size.
size = toInteger $ fileInfoGetSize info
-- File modified time.
time = gTimeValToClockTime $ fileInfoGetModificationTime info
-- File mime description.
Just contentType = fileInfoGetContentType info
desc = contentTypeGetDescription contentType
return $ FMInfo pixbuf (UTF8.toString name) desc size time
) infos
-- Initialize tree view.
store <- listStoreNew fInfos
tv <- treeViewNewWithModel store
scrolledWindow `containerAdd` tv
-- List Icons.
tvc <- treeViewColumnNew
set tvc [ treeViewColumnTitle := "Icon"
, treeViewColumnResizable := True ]
treeViewAppendColumn tv tvc
icon <- cellRendererPixbufNew
treeViewColumnPackStart tvc icon True
cellLayoutSetAttributes tvc icon store $ \FMInfo { fIcon = icon } ->
[ cellPixbuf := icon ]
-- List Name.
tvc <- treeViewColumnNew
set tvc [ treeViewColumnTitle := "Name"
, treeViewColumnResizable := True ]
treeViewAppendColumn tv tvc
name <- cellRendererTextNew
treeViewColumnPackStart tvc name True
cellLayoutSetAttributes tvc name store $ \FMInfo { fName = name } ->
[ cellText := name ]
-- List file mime description.
tvc <- treeViewColumnNew
set tvc [ treeViewColumnTitle := "Description"
, treeViewColumnResizable := True ]
treeViewAppendColumn tv tvc
desc <- cellRendererTextNew
treeViewColumnPackStart tvc desc True
cellLayoutSetAttributes tvc desc store $ \FMInfo { fDesc = desc } ->
[ cellText := desc ]
-- List file size.
tvc <- treeViewColumnNew
set tvc [ treeViewColumnTitle := "Size"
, treeViewColumnResizable := True ]
treeViewAppendColumn tv tvc
size <- cellRendererTextNew
treeViewColumnPackStart tvc size True
cellLayoutSetAttributes tvc size store $ \FMInfo { fSize = size } ->
[ cellText := formatFileSizeForDisplay size
, cellXAlign := 1.0]
-- List modified time.
tvc <- treeViewColumnNew
set tvc [ treeViewColumnTitle := "Modified"
, treeViewColumnResizable := True ]
treeViewAppendColumn tv tvc
time <- cellRendererTextNew
treeViewColumnPackStart tvc time True
cellLayoutSetAttributes tvc time store $ \FMInfo { fTime = time } ->
[ cellText :=> do
calTime <- toCalendarTime time
return (formatCalendarTime defaultTimeLocale "%Y/%m/%d %T" calTime)]
-- Show window.
window `onDestroy` mainQuit
widgetShowAll window
mainGUI
directoryGetFileInfos :: FilePath -> IO [FileInfo]
directoryGetFileInfos directory = do
let dir = fileFromPath (UTF8.fromString directory)
enumerator <- fileEnumerateChildren dir "*" [] Nothing
fileEnumeratorGetFileInfos enumerator
fileEnumeratorGetFileInfos :: FileEnumeratorClass enumerator => enumerator -> IO [FileInfo]
fileEnumeratorGetFileInfos enum = do
fileInfo <- fileEnumeratorNextFile enum Nothing
case fileInfo of
Just info -> do
infos <- fileEnumeratorGetFileInfos enum
return $ info : infos
Nothing -> return []
formatFileSizeForDisplay :: Integer -> String
formatFileSizeForDisplay size
| size < 2 ^ 10 = humanSize 1 ++ " bytes"
| size < 2 ^ 20 = humanSize (2 ^ 10) ++ " KB"
| size < 2 ^ 30 = humanSize (2 ^ 20) ++ " MB"
| size < 2 ^ 40 = humanSize (2 ^ 30) ++ " GB"
| size < 2 ^ 50 = humanSize (2 ^ 40) ++ " TB"
| size < 2 ^ 60 = humanSize (2 ^ 50) ++ " PB"
| size < 2 ^ 70 = humanSize (2 ^ 60) ++ " EB"
| size < 2 ^ 80 = humanSize (2 ^ 70) ++ " ZB"
| size < 2 ^ 90 = humanSize (2 ^ 80) ++ " YB"
| size < 2 ^ 100 = humanSize (2 ^ 90) ++ " NB"
| size < 2 ^ 110 = humanSize (2 ^ 100) ++ " DB"
where humanSize base = printf "%.1f" (integralToDouble size / base) :: String
integralToDouble :: Integral a => a -> Double
integralToDouble v = fromIntegral v :: Double
gTimeValToClockTime :: GTimeVal -> ClockTime
gTimeValToClockTime GTimeVal {gTimeValSec = seconds
,gTimeValUSec = microseconds} =
TOD (toInteger seconds) (toInteger microseconds * 1000)
|
k0001/gtk2hs
|
gio/demo/FileManager.hs
|
gpl-3.0
| 5,935 | 0 | 18 | 1,629 | 1,544 | 764 | 780 | 125 | 2 |
module T14487 where
import T14487A hiding (duplicateName)
test = X duplicateName
duplicateName = 5
|
sdiehl/ghc
|
testsuite/tests/rename/should_compile/T14487.hs
|
bsd-3-clause
| 102 | 0 | 5 | 17 | 26 | 16 | 10 | 4 | 1 |
-- !!! Importing unknown module
module M where
import N
|
forked-upstream-packages-for-ghcjs/ghc
|
testsuite/tests/module/mod1.hs
|
bsd-3-clause
| 56 | 0 | 3 | 10 | 8 | 6 | 2 | 2 | 0 |
module Futhark.CodeGen.ImpGen.Multicore.SegRed
( compileSegRed,
compileSegRed',
)
where
import Control.Monad
import qualified Futhark.CodeGen.ImpCode.Multicore as Imp
import Futhark.CodeGen.ImpGen
import Futhark.CodeGen.ImpGen.Multicore.Base
import Futhark.IR.MCMem
import Futhark.Util (chunks)
import Prelude hiding (quot, rem)
type DoSegBody = (([(SubExp, [Imp.TExp Int64])] -> MulticoreGen ()) -> MulticoreGen ())
-- | Generate code for a SegRed construct
compileSegRed ::
Pat MCMem ->
SegSpace ->
[SegBinOp MCMem] ->
KernelBody MCMem ->
TV Int32 ->
MulticoreGen Imp.Code
compileSegRed pat space reds kbody nsubtasks =
compileSegRed' pat space reds nsubtasks $ \red_cont ->
compileStms mempty (kernelBodyStms kbody) $ do
let (red_res, map_res) = splitAt (segBinOpResults reds) $ kernelBodyResult kbody
sComment "save map-out results" $ do
let map_arrs = drop (segBinOpResults reds) $ patElems pat
zipWithM_ (compileThreadResult space) map_arrs map_res
red_cont $ zip (map kernelResultSubExp red_res) $ repeat []
-- | Like 'compileSegRed', but where the body is a monadic action.
compileSegRed' ::
Pat MCMem ->
SegSpace ->
[SegBinOp MCMem] ->
TV Int32 ->
DoSegBody ->
MulticoreGen Imp.Code
compileSegRed' pat space reds nsubtasks kbody
| [_] <- unSegSpace space =
nonsegmentedReduction pat space reds nsubtasks kbody
| otherwise =
segmentedReduction pat space reds kbody
-- | A SegBinOp with auxiliary information.
data SegBinOpSlug = SegBinOpSlug
{ slugOp :: SegBinOp MCMem,
-- | The array in which we write the intermediate results, indexed
-- by the flat/physical thread ID.
slugResArrs :: [VName]
}
slugBody :: SegBinOpSlug -> Body MCMem
slugBody = lambdaBody . segBinOpLambda . slugOp
slugParams :: SegBinOpSlug -> [LParam MCMem]
slugParams = lambdaParams . segBinOpLambda . slugOp
slugNeutral :: SegBinOpSlug -> [SubExp]
slugNeutral = segBinOpNeutral . slugOp
slugShape :: SegBinOpSlug -> Shape
slugShape = segBinOpShape . slugOp
accParams, nextParams :: SegBinOpSlug -> [LParam MCMem]
accParams slug = take (length (slugNeutral slug)) $ slugParams slug
nextParams slug = drop (length (slugNeutral slug)) $ slugParams slug
nonsegmentedReduction ::
Pat MCMem ->
SegSpace ->
[SegBinOp MCMem] ->
TV Int32 ->
DoSegBody ->
MulticoreGen Imp.Code
nonsegmentedReduction pat space reds nsubtasks kbody = collect $ do
thread_res_arrs <- groupResultArrays "reduce_stage_1_tid_res_arr" (tvSize nsubtasks) reds
let slugs1 = zipWith SegBinOpSlug reds thread_res_arrs
nsubtasks' = tvExp nsubtasks
reductionStage1 space slugs1 kbody
reds2 <- renameSegBinOp reds
let slugs2 = zipWith SegBinOpSlug reds2 thread_res_arrs
reductionStage2 pat space nsubtasks' slugs2
reductionStage1 ::
SegSpace ->
[SegBinOpSlug] ->
DoSegBody ->
MulticoreGen ()
reductionStage1 space slugs kbody = do
let (is, ns) = unzip $ unSegSpace space
ns' = map toInt64Exp ns
flat_idx <- dPrim "iter" int64
-- Create local accumulator variables in which we carry out the
-- sequential reduction of this function. If we are dealing with
-- vectorised operators, then this implies a private allocation. If
-- the original operand type of the reduction is a memory block,
-- then our hands are unfortunately tied, and we have to use exactly
-- that memory. This is likely to be slow.
(slug_local_accs, prebody) <- collect' $ do
dScope Nothing $ scopeOfLParams $ concatMap slugParams slugs
forM slugs $ \slug -> do
let shape = segBinOpShape $ slugOp slug
forM (zip (accParams slug) (slugNeutral slug)) $ \(p, ne) -> do
-- Declare accumulator variable.
acc <-
case paramType p of
Prim pt
| shape == mempty ->
tvVar <$> dPrim "local_acc" pt
| otherwise ->
sAllocArray "local_acc" pt shape DefaultSpace
_ ->
pure $ paramName p
-- Now neutral-initialise the accumulator.
sLoopNest (slugShape slug) $ \vec_is ->
copyDWIMFix acc vec_is ne []
pure acc
fbody <- collect $ do
zipWithM_ dPrimV_ is $ unflattenIndex ns' $ tvExp flat_idx
kbody $ \all_red_res -> do
let all_red_res' = segBinOpChunks (map slugOp slugs) all_red_res
forM_ (zip3 all_red_res' slugs slug_local_accs) $ \(red_res, slug, local_accs) ->
sLoopNest (slugShape slug) $ \vec_is -> do
let lamtypes = lambdaReturnType $ segBinOpLambda $ slugOp slug
-- Load accum params
sComment "Load accum params" $
forM_ (zip3 (accParams slug) local_accs lamtypes) $
\(p, local_acc, t) ->
when (primType t) $
copyDWIMFix (paramName p) [] (Var local_acc) vec_is
sComment "Load next params" $
forM_ (zip (nextParams slug) red_res) $ \(p, (res, res_is)) ->
copyDWIMFix (paramName p) [] res (res_is ++ vec_is)
sComment "Red body" $
compileStms mempty (bodyStms $ slugBody slug) $
forM_ (zip local_accs $ map resSubExp $ bodyResult $ slugBody slug) $
\(local_acc, se) ->
copyDWIMFix local_acc vec_is se []
postbody <- collect $
forM_ (zip slugs slug_local_accs) $ \(slug, local_accs) ->
forM (zip (slugResArrs slug) local_accs) $ \(acc, local_acc) ->
copyDWIMFix acc [Imp.le64 $ segFlat space] (Var local_acc) []
free_params <- freeParams (prebody <> fbody <> postbody) (segFlat space : [tvVar flat_idx])
let (body_allocs, fbody') = extractAllocations fbody
emit $ Imp.Op $ Imp.ParLoop "segred_stage_1" (tvVar flat_idx) (body_allocs <> prebody) fbody' postbody free_params $ segFlat space
reductionStage2 ::
Pat MCMem ->
SegSpace ->
Imp.TExp Int32 ->
[SegBinOpSlug] ->
MulticoreGen ()
reductionStage2 pat space nsubtasks slugs = do
let per_red_pes = segBinOpChunks (map slugOp slugs) $ patElems pat
phys_id = Imp.le64 (segFlat space)
sComment "neutral-initialise the output" $
forM_ (zip (map slugOp slugs) per_red_pes) $ \(red, red_res) ->
forM_ (zip red_res $ segBinOpNeutral red) $ \(pe, ne) ->
sLoopNest (segBinOpShape red) $ \vec_is ->
copyDWIMFix (patElemName pe) vec_is ne []
dScope Nothing $ scopeOfLParams $ concatMap slugParams slugs
sFor "i" nsubtasks $ \i' -> do
mkTV (segFlat space) int64 <-- i'
sComment "Apply main thread reduction" $
forM_ (zip slugs per_red_pes) $ \(slug, red_res) ->
sLoopNest (slugShape slug) $ \vec_is -> do
sComment "load acc params" $
forM_ (zip (accParams slug) red_res) $ \(p, pe) ->
copyDWIMFix (paramName p) [] (Var $ patElemName pe) vec_is
sComment "load next params" $
forM_ (zip (nextParams slug) (slugResArrs slug)) $ \(p, acc) ->
copyDWIMFix (paramName p) [] (Var acc) (phys_id : vec_is)
sComment "red body" $
compileStms mempty (bodyStms $ slugBody slug) $
forM_ (zip red_res $ map resSubExp $ bodyResult $ slugBody slug) $
\(pe, se') -> copyDWIMFix (patElemName pe) vec_is se' []
-- Each thread reduces over the number of segments
-- each of which is done sequentially
-- Maybe we should select the work of the inner loop
-- based on n_segments and dimensions etc.
segmentedReduction ::
Pat MCMem ->
SegSpace ->
[SegBinOp MCMem] ->
DoSegBody ->
MulticoreGen Imp.Code
segmentedReduction pat space reds kbody =
collect $ do
n_par_segments <- dPrim "segment_iter" $ IntType Int64
body <- compileSegRedBody n_par_segments pat space reds kbody
free_params <- freeParams body (segFlat space : [tvVar n_par_segments])
let (body_allocs, body') = extractAllocations body
emit $ Imp.Op $ Imp.ParLoop "segmented_segred" (tvVar n_par_segments) body_allocs body' mempty free_params $ segFlat space
compileSegRedBody ::
TV Int64 ->
Pat MCMem ->
SegSpace ->
[SegBinOp MCMem] ->
DoSegBody ->
MulticoreGen Imp.Code
compileSegRedBody n_segments pat space reds kbody = do
let (is, ns) = unzip $ unSegSpace space
ns_64 = map toInt64Exp ns
inner_bound = last ns_64
n_segments' = tvExp n_segments
let per_red_pes = segBinOpChunks reds $ patElems pat
-- Perform sequential reduce on inner most dimension
collect $ do
flat_idx <- dPrimVE "flat_idx" $ n_segments' * inner_bound
zipWithM_ dPrimV_ is $ unflattenIndex ns_64 flat_idx
sComment "neutral-initialise the accumulators" $
forM_ (zip per_red_pes reds) $ \(pes, red) ->
forM_ (zip pes (segBinOpNeutral red)) $ \(pe, ne) ->
sLoopNest (segBinOpShape red) $ \vec_is ->
copyDWIMFix (patElemName pe) (map Imp.le64 (init is) ++ vec_is) ne []
sComment "main body" $ do
dScope Nothing $ scopeOfLParams $ concatMap (lambdaParams . segBinOpLambda) reds
sFor "i" inner_bound $ \i -> do
zipWithM_
(<--)
(map (`mkTV` int64) $ init is)
(unflattenIndex (init ns_64) (sExt64 n_segments'))
dPrimV_ (last is) i
kbody $ \all_red_res -> do
let red_res' = chunks (map (length . segBinOpNeutral) reds) all_red_res
forM_ (zip3 per_red_pes reds red_res') $ \(pes, red, res') ->
sLoopNest (segBinOpShape red) $ \vec_is -> do
sComment "load accum" $ do
let acc_params = take (length (segBinOpNeutral red)) $ (lambdaParams . segBinOpLambda) red
forM_ (zip acc_params pes) $ \(p, pe) ->
copyDWIMFix (paramName p) [] (Var $ patElemName pe) (map Imp.le64 (init is) ++ vec_is)
sComment "load new val" $ do
let next_params = drop (length (segBinOpNeutral red)) $ (lambdaParams . segBinOpLambda) red
forM_ (zip next_params res') $ \(p, (res, res_is)) ->
copyDWIMFix (paramName p) [] res (res_is ++ vec_is)
sComment "apply reduction" $ do
let lbody = (lambdaBody . segBinOpLambda) red
compileStms mempty (bodyStms lbody) $
sComment "write back to res" $
forM_ (zip pes $ map resSubExp $ bodyResult lbody) $
\(pe, se') -> copyDWIMFix (patElemName pe) (map Imp.le64 (init is) ++ vec_is) se' []
|
HIPERFIT/futhark
|
src/Futhark/CodeGen/ImpGen/Multicore/SegRed.hs
|
isc
| 10,414 | 0 | 38 | 2,642 | 3,264 | 1,604 | 1,660 | 210 | 2 |
coeffs<-(readFile "b.txt" >>= return.map read.lines :: IO [Double])
pts <- readFile "test">>=return.map (map (read::String->Double)).map words.take 21.drop 1.lines
zipWith (\[x,y] [a,b,c,d] -> (a+b*x+c*x^2+d*x^3-y)/y) (tail pts) cs
|
ducis/haskell-numerical-analysis-examples
|
G/check.hs
|
mit
| 235 | 2 | 18 | 28 | 171 | 87 | 84 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
module Y2017.M11.D21.Solution where
{--
Okey-dokey. From yesterday's exercise, we're returning full articles with
key-phrases and ranked and everything!
Boss-man: I don't need full article text, just a summary of the first 140
characters. And remove the special characters. And drop the key-phrases: we
don't need that in the front-end.
Okay, then! Let's do that!
From yesterday's results, do the above. Capice?
--}
import Control.Monad ((>=>))
import Data.Aeson hiding (Value)
import Data.Aeson.Encode.Pretty (encodePretty)
import qualified Data.ByteString.Lazy.Char8 as BL
import Data.Maybe (mapMaybe)
import Data.Time
-- below imports available 1HaskellADay git repository
import Control.Logic.Frege ((<<-))
import Control.Scan.Config
import Store.SQL.Connection (withConnection)
import Y2017.M11.D01.Solution -- for special character filtration
import Y2017.M11.D03.Solution -- for Strength
import Y2017.M11.D06.Solution hiding (title) -- for Value
import Y2017.M11.D07.Solution hiding (title) -- for Recommendation
import Y2017.M11.D20.Solution -- for article sets filtered by keyword search
data Brief =
Summarized { briefIdx :: Integer, date :: Maybe Day,
title, summary :: String,
viewCount :: Maybe Integer,
rank :: Value Strength }
deriving (Eq, Show)
rec2brief :: SpecialCharTable -> Recommendation -> Maybe Brief
rec2brief chrs (Scored idx tit txt dt _ _ vc score) =
txt >>= \summ ->
return (Summarized idx (pure dt) (refineString chrs tit)
(summarize chrs summ) vc (VAL score))
summarize :: SpecialCharTable -> String -> String
summarize = refineString -- having the rec read a summary now
-- summarize truncates the full text to the first 140 characters, because we're
-- HALF of a tweet. ... yup.
{--
JSON structure is:
article_id
article_date
article_title
article_summary
article_rank
article_view_count
--}
instance ToJSON Brief where
toJSON brief =
object ["article_id" .= briefIdx brief, "article_date" .= date brief,
"article_title" .= title brief, "article_summary" .= summary brief,
"article_rank" .= val2float (rank brief),
"article_view_count" .= viewCount brief]
{--
Good idea, but the types returned from (Brief -> a) are different.
(zipWith (.=) (map ("article_" ++) (words "id date title summary rank"))
--}
{-- BONUS -----------------------------------------------------------------
Write an app that does just like yesterday's app does: returns a set of articles
from a set of keyword filters, but this time returns briefs-as-JSON
--}
main' :: [String] -> IO ()
main' keywords = do
homeDir <- home
special <- readSpecialChars (homeDir ++ "/.specialChars.prop")
withConnection (flip recs keywords >=>
BL.putStrLn . encodePretty . mapMaybe (rec2brief special))
|
geophf/1HaskellADay
|
exercises/HAD/Y2017/M11/D21/Solution.hs
|
mit
| 2,903 | 0 | 12 | 549 | 511 | 293 | 218 | -1 | -1 |
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
module Language.LSP.Types.Completion where
import qualified Data.Aeson as A
import Data.Aeson.TH
import Data.Scientific ( Scientific )
import Data.Text ( Text )
import Language.LSP.Types.Command
import Language.LSP.Types.Common
import Language.LSP.Types.MarkupContent
import Language.LSP.Types.Progress
import Language.LSP.Types.TextDocument
import Language.LSP.Types.Utils
import Language.LSP.Types.WorkspaceEdit
import Language.LSP.Types.Location (Range)
data CompletionItemKind = CiText
| CiMethod
| CiFunction
| CiConstructor
| CiField
| CiVariable
| CiClass
| CiInterface
| CiModule
| CiProperty
| CiUnit
| CiValue
| CiEnum
| CiKeyword
| CiSnippet
| CiColor
| CiFile
| CiReference
| CiFolder
| CiEnumMember
| CiConstant
| CiStruct
| CiEvent
| CiOperator
| CiTypeParameter
deriving (Read,Show,Eq,Ord)
instance A.ToJSON CompletionItemKind where
toJSON CiText = A.Number 1
toJSON CiMethod = A.Number 2
toJSON CiFunction = A.Number 3
toJSON CiConstructor = A.Number 4
toJSON CiField = A.Number 5
toJSON CiVariable = A.Number 6
toJSON CiClass = A.Number 7
toJSON CiInterface = A.Number 8
toJSON CiModule = A.Number 9
toJSON CiProperty = A.Number 10
toJSON CiUnit = A.Number 11
toJSON CiValue = A.Number 12
toJSON CiEnum = A.Number 13
toJSON CiKeyword = A.Number 14
toJSON CiSnippet = A.Number 15
toJSON CiColor = A.Number 16
toJSON CiFile = A.Number 17
toJSON CiReference = A.Number 18
toJSON CiFolder = A.Number 19
toJSON CiEnumMember = A.Number 20
toJSON CiConstant = A.Number 21
toJSON CiStruct = A.Number 22
toJSON CiEvent = A.Number 23
toJSON CiOperator = A.Number 24
toJSON CiTypeParameter = A.Number 25
instance A.FromJSON CompletionItemKind where
parseJSON (A.Number 1) = pure CiText
parseJSON (A.Number 2) = pure CiMethod
parseJSON (A.Number 3) = pure CiFunction
parseJSON (A.Number 4) = pure CiConstructor
parseJSON (A.Number 5) = pure CiField
parseJSON (A.Number 6) = pure CiVariable
parseJSON (A.Number 7) = pure CiClass
parseJSON (A.Number 8) = pure CiInterface
parseJSON (A.Number 9) = pure CiModule
parseJSON (A.Number 10) = pure CiProperty
parseJSON (A.Number 11) = pure CiUnit
parseJSON (A.Number 12) = pure CiValue
parseJSON (A.Number 13) = pure CiEnum
parseJSON (A.Number 14) = pure CiKeyword
parseJSON (A.Number 15) = pure CiSnippet
parseJSON (A.Number 16) = pure CiColor
parseJSON (A.Number 17) = pure CiFile
parseJSON (A.Number 18) = pure CiReference
parseJSON (A.Number 19) = pure CiFolder
parseJSON (A.Number 20) = pure CiEnumMember
parseJSON (A.Number 21) = pure CiConstant
parseJSON (A.Number 22) = pure CiStruct
parseJSON (A.Number 23) = pure CiEvent
parseJSON (A.Number 24) = pure CiOperator
parseJSON (A.Number 25) = pure CiTypeParameter
parseJSON _ = mempty
data CompletionItemTag
-- | Render a completion as obsolete, usually using a strike-out.
= CitDeprecated
| CitUnknown Scientific
deriving (Eq, Ord, Show, Read)
instance A.ToJSON CompletionItemTag where
toJSON CitDeprecated = A.Number 1
toJSON (CitUnknown i) = A.Number i
instance A.FromJSON CompletionItemTag where
parseJSON (A.Number 1) = pure CitDeprecated
parseJSON _ = mempty
data CompletionItemTagsClientCapabilities =
CompletionItemTagsClientCapabilities
{ -- | The tag supported by the client.
_valueSet :: List CompletionItemTag
} deriving (Show, Read, Eq)
deriveJSON lspOptions ''CompletionItemTagsClientCapabilities
data CompletionItemResolveClientCapabilities =
CompletionItemResolveClientCapabilities
{ -- | The properties that a client can resolve lazily.
_properties :: List Text
} deriving (Show, Read, Eq)
deriveJSON lspOptions ''CompletionItemResolveClientCapabilities
{-|
How whitespace and indentation is handled during completion
item insertion.
@since 3.16.0
-}
data InsertTextMode =
-- | The insertion or replace strings is taken as it is. If the
-- value is multi line the lines below the cursor will be
-- inserted using the indentation defined in the string value.
-- The client will not apply any kind of adjustments to the
-- string.
AsIs
-- | The editor adjusts leading whitespace of new lines so that
-- they match the indentation up to the cursor of the line for
-- which the item is accepted.
--
-- Consider a line like this: <2tabs><cursor><3tabs>foo. Accepting a
-- multi line completion item is indented using 2 tabs and all
-- following lines inserted will be indented using 2 tabs as well.
| AdjustIndentation
deriving (Read,Show,Eq)
instance A.ToJSON InsertTextMode where
toJSON AsIs = A.Number 1
toJSON AdjustIndentation = A.Number 2
instance A.FromJSON InsertTextMode where
parseJSON (A.Number 1) = pure AsIs
parseJSON (A.Number 2) = pure AdjustIndentation
parseJSON _ = mempty
data CompletionItemInsertTextModeClientCapabilities =
CompletionItemInsertTextModeClientCapabilities
{ _valueSet :: List InsertTextMode
} deriving (Show, Read, Eq)
deriveJSON lspOptions ''CompletionItemInsertTextModeClientCapabilities
data CompletionItemClientCapabilities =
CompletionItemClientCapabilities
{ -- | Client supports snippets as insert text.
--
-- A snippet can define tab stops and placeholders with `$1`, `$2` and
-- `${3:foo}`. `$0` defines the final tab stop, it defaults to the end of
-- the snippet. Placeholders with equal identifiers are linked, that is
-- typing in one will update others too.
_snippetSupport :: Maybe Bool
-- | Client supports commit characters on a completion item.
, _commitCharactersSupport :: Maybe Bool
-- | Client supports the follow content formats for the documentation
-- property. The order describes the preferred format of the client.
, _documentationFormat :: Maybe (List MarkupKind)
-- | Client supports the deprecated property on a completion item.
, _deprecatedSupport :: Maybe Bool
-- | Client supports the preselect property on a completion item.
, _preselectSupport :: Maybe Bool
-- | Client supports the tag property on a completion item. Clients
-- supporting tags have to handle unknown tags gracefully. Clients
-- especially need to preserve unknown tags when sending a
-- completion item back to the server in a resolve call.
--
-- @since 3.15.0
, _tagSupport :: Maybe CompletionItemTagsClientCapabilities
-- | Client supports insert replace edit to control different behavior if
-- completion item is inserted in the text or should replace text.
--
-- @since 3.16.0
, _insertReplaceSupport :: Maybe Bool
-- | Indicates which properties a client can resolve lazily on a
-- completion item. Before version 3.16.0 only the predefined properties
-- `documentation` and `details` could be resolved lazily.
--
-- @since 3.16.0
, _resolveSupport :: Maybe CompletionItemResolveClientCapabilities
-- | The client supports the `insertTextMode` property on
-- a completion item to override the whitespace handling mode
-- as defined by the client (see `insertTextMode`).
--
-- @since 3.16.0
, _insertTextModeSupport :: Maybe CompletionItemInsertTextModeClientCapabilities
} deriving (Show, Read, Eq)
deriveJSON lspOptions ''CompletionItemClientCapabilities
data CompletionItemKindClientCapabilities =
CompletionItemKindClientCapabilities
{ -- | The completion item kind values the client supports. When this
-- property exists the client also guarantees that it will
-- handle values outside its set gracefully and falls back
-- to a default value when unknown.
_valueSet :: Maybe (List CompletionItemKind)
}
deriving (Show, Read, Eq)
deriveJSON lspOptions ''CompletionItemKindClientCapabilities
data CompletionClientCapabilities =
CompletionClientCapabilities
{ _dynamicRegistration :: Maybe Bool -- ^ Whether completion supports dynamic
-- registration.
, _completionItem :: Maybe CompletionItemClientCapabilities
, _completionItemKind :: Maybe CompletionItemKindClientCapabilities
, _contextSupport :: Maybe Bool
} deriving (Show, Read, Eq)
deriveJSON lspOptions ''CompletionClientCapabilities
-- -------------------------------------
data InsertTextFormat
= PlainText -- ^The primary text to be inserted is treated as a plain string.
| Snippet
-- ^ The primary text to be inserted is treated as a snippet.
--
-- A snippet can define tab stops and placeholders with `$1`, `$2`
-- and `${3:foo}`. `$0` defines the final tab stop, it defaults to
-- the end of the snippet. Placeholders with equal identifiers are linked,
-- that is typing in one will update others too.
--
-- See also: https://github.com/Microsoft/vscode/blob/master/src/vs/editor/contrib/snippet/common/snippet.md
deriving (Show, Read, Eq)
instance A.ToJSON InsertTextFormat where
toJSON PlainText = A.Number 1
toJSON Snippet = A.Number 2
instance A.FromJSON InsertTextFormat where
parseJSON (A.Number 1) = pure PlainText
parseJSON (A.Number 2) = pure Snippet
parseJSON _ = mempty
data CompletionDoc = CompletionDocString Text
| CompletionDocMarkup MarkupContent
deriving (Show, Read, Eq)
deriveJSON lspOptionsUntagged ''CompletionDoc
data InsertReplaceEdit =
InsertReplaceEdit
{ _newText :: Text -- ^ The string to be inserted.
, _insert :: Range -- ^ The range if the insert is requested
, _repalce :: Range -- ^ The range if the replace is requested.
}
deriving (Read,Show,Eq)
deriveJSON lspOptions ''InsertReplaceEdit
data CompletionEdit = CompletionEditText TextEdit | CompletionEditInsertReplace InsertReplaceEdit
deriving (Read,Show,Eq)
deriveJSON lspOptionsUntagged ''CompletionEdit
data CompletionItem =
CompletionItem
{ _label :: Text -- ^ The label of this completion item. By default also
-- the text that is inserted when selecting this
-- completion.
, _kind :: Maybe CompletionItemKind
, _tags :: Maybe (List CompletionItemTag) -- ^ Tags for this completion item.
, _detail :: Maybe Text -- ^ A human-readable string with additional
-- information about this item, like type or
-- symbol information.
, _documentation :: Maybe CompletionDoc -- ^ A human-readable string that represents
-- a doc-comment.
, _deprecated :: Maybe Bool -- ^ Indicates if this item is deprecated.
, _preselect :: Maybe Bool
-- ^ Select this item when showing.
-- *Note* that only one completion item can be selected and that the
-- tool / client decides which item that is. The rule is that the *first*
-- item of those that match best is selected.
, _sortText :: Maybe Text -- ^ A string that should be used when filtering
-- a set of completion items. When `falsy` the
-- label is used.
, _filterText :: Maybe Text -- ^ A string that should be used when
-- filtering a set of completion items. When
-- `falsy` the label is used.
, _insertText :: Maybe Text -- ^ A string that should be inserted a
-- document when selecting this completion.
-- When `falsy` the label is used.
, _insertTextFormat :: Maybe InsertTextFormat
-- ^ The format of the insert text. The format applies to both the
-- `insertText` property and the `newText` property of a provided
-- `textEdit`.
, _insertTextMode :: Maybe InsertTextMode
-- ^ How whitespace and indentation is handled during completion
-- item insertion. If not provided the client's default value depends on
-- the @textDocument.completion.insertTextMode@ client capability.
, _textEdit :: Maybe CompletionEdit
-- ^ An edit which is applied to a document when selecting this
-- completion. When an edit is provided the value of `insertText` is
-- ignored.
--
-- *Note:* The range of the edit must be a single line range and it
-- must contain the position at which completion has been requested.
, _additionalTextEdits :: Maybe (List TextEdit)
-- ^ An optional array of additional text edits that are applied when
-- selecting this completion. Edits must not overlap with the main edit
-- nor with themselves.
, _commitCharacters :: Maybe (List Text)
-- ^ An optional set of characters that when pressed while this completion
-- is active will accept it first and then type that character. *Note*
-- that all commit characters should have `length=1` and that superfluous
-- characters will be ignored.
, _command :: Maybe Command
-- ^ An optional command that is executed *after* inserting this
-- completion. *Note* that additional modifications to the current
-- document should be described with the additionalTextEdits-property.
, _xdata :: Maybe A.Value -- ^ An data entry field that is preserved on a
-- completion item between a completion and a
-- completion resolve request.
} deriving (Read,Show,Eq)
deriveJSON lspOptions ''CompletionItem
-- | Represents a collection of 'CompletionItem's to be presented in the editor.
data CompletionList =
CompletionList
{ _isIncomplete :: Bool -- ^ This list it not complete. Further typing
-- should result in recomputing this list.
, _items :: List CompletionItem -- ^ The completion items.
} deriving (Read,Show,Eq)
deriveJSON lspOptions ''CompletionList
-- | How a completion was triggered
data CompletionTriggerKind = -- | Completion was triggered by typing an identifier (24x7 code
-- complete), manual invocation (e.g Ctrl+Space) or via API.
CtInvoked
-- | Completion was triggered by a trigger character specified by
-- the `triggerCharacters` properties of the `CompletionRegistrationOptions`.
| CtTriggerCharacter
-- | Completion was re-triggered as the current completion list is incomplete.
| CtTriggerForIncompleteCompletions
-- | An unknown 'CompletionTriggerKind' not yet supported in haskell-lsp.
| CtUnknown Scientific
deriving (Read, Show, Eq)
instance A.ToJSON CompletionTriggerKind where
toJSON CtInvoked = A.Number 1
toJSON CtTriggerCharacter = A.Number 2
toJSON CtTriggerForIncompleteCompletions = A.Number 3
toJSON (CtUnknown x) = A.Number x
instance A.FromJSON CompletionTriggerKind where
parseJSON (A.Number 1) = pure CtInvoked
parseJSON (A.Number 2) = pure CtTriggerCharacter
parseJSON (A.Number 3) = pure CtTriggerForIncompleteCompletions
parseJSON (A.Number x) = pure (CtUnknown x)
parseJSON _ = mempty
makeExtendingDatatype "CompletionOptions" [''WorkDoneProgressOptions]
[ ("_triggerCharacters", [t| Maybe [Text] |])
, ("_allCommitCharacters", [t| Maybe [Text] |])
, ("_resolveProvider", [t| Maybe Bool|])
]
deriveJSON lspOptions ''CompletionOptions
makeExtendingDatatype "CompletionRegistrationOptions"
[ ''TextDocumentRegistrationOptions
, ''CompletionOptions
]
[]
deriveJSON lspOptions ''CompletionRegistrationOptions
data CompletionContext =
CompletionContext
{ _triggerKind :: CompletionTriggerKind -- ^ How the completion was triggered.
, _triggerCharacter :: Maybe Text
-- ^ The trigger character (a single character) that has trigger code complete.
-- Is undefined if `triggerKind !== CompletionTriggerKind.TriggerCharacter`
}
deriving (Read, Show, Eq)
deriveJSON lspOptions ''CompletionContext
makeExtendingDatatype "CompletionParams"
[ ''TextDocumentPositionParams
, ''WorkDoneProgressParams
, ''PartialResultParams
]
[ ("_context", [t| Maybe CompletionContext |]) ]
deriveJSON lspOptions ''CompletionParams
|
alanz/haskell-lsp
|
lsp-types/src/Language/LSP/Types/Completion.hs
|
mit
| 17,788 | 0 | 11 | 5,103 | 2,650 | 1,431 | 1,219 | 248 | 0 |
module Types.BCrypt
( BCrypt, hashPassword, validatePassword
) where
-- Prelude.
import ClassyPrelude hiding (hash)
import qualified Crypto.KDF.BCrypt as BC
import Database.Persist.Sql
import Katip (KatipContext, Severity (..), logStr,
logTM)
-- Local imports.
import Logging
--------------------------------------------------------------------------------
-- | Newtype wrapper for passwords hashed using BCrypt.
newtype BCrypt
= BCrypt
{ unBCrypt :: Text
} deriving (Eq, PersistField, PersistFieldSql, Show)
--------------------------------------------------------------------------------
-- | Produce a hashed output, given some plaintext input.
hashPassword :: MonadIO m => Text -> m BCrypt
hashPassword pass =
let hash = liftIO $ BC.hashPassword 12 $ encodeUtf8 pass
in BCrypt . decodeUtf8 <$> hash
-- | Validate that the plaintext is equivalent to a hashed @BCrypt@, log any
-- validation failures.
validatePassword
:: (MonadReader r m, HasLogState r, KatipContext m)
=> Text -> BCrypt -> m Bool
validatePassword pass' hash' = do
let pass = encodeUtf8 pass'
hash = encodeUtf8 . unBCrypt $ hash'
isValid = BC.validatePasswordEither pass hash
case isValid of
Left e -> addNamespace "password_validation" $ do
$(logTM) ErrorS
$ "Password validation failed with [[ "
<> logStr e
<> " ]]"
pure False
Right v -> pure v
|
jkachmar/servant-persistent-realworld
|
src/Types/BCrypt.hs
|
mit
| 1,515 | 0 | 18 | 380 | 319 | 171 | 148 | -1 | -1 |
-- When greatest is less than smallest
-- http://www.codewars.com/kata/55f2a1c2cb3c95af75000045/
module Kata.WhenGreatestIsLessThanSmallest where
greatest :: Integer -> Integer -> Integer -> Integer
greatest x y n = ((n - 1) `div` (lcm x y)) * lcm x y
smallest :: Integer -> Integer -> Integer -> Integer
smallest x y n = ((n `div` (lcm x y)) + 1) * lcm x y
|
gafiatulin/codewars
|
src/6 kyu/WhenGreatestIsLessThanSmallest.hs
|
mit
| 360 | 0 | 11 | 64 | 132 | 72 | 60 | 5 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-
replaces description on the NSDate object with swizzleDescription
pdfkiths[master*] % dist/build/testswizzle/testswizzle
2013-09-16 14:22:50 +0000
Succesfully swizzled
No soup for you
[1] 50767 segmentation fault dist/build/testswizzle/testswizzle
-}
module Main where
import Cocoa
import Cocoa.NSObject
import Cocoa.NSString
import Swizzle
import Control.Concurrent(forkIO)
{-# NOINLINE swizzleDescription #-}
swizzleDescription :: SwizzleVoid
swizzleDescription _ _ = do
putStrLn "No soup for you"
main :: IO ()
main = do
pool <- newAutoreleasePool
_ <- forkIO startRunloop
str <- toNSString $ ("NSDate" $<- "alloc") >>= \str -> str $<- "init"
description str >>= putStrLn
swizzleHSMethod (idVal str) "description" swizzleDescription
description str >>= putStrLn
delAutoreleasePool pool
return ()
|
aktowns/pdfkiths
|
examples/testswizzle.hs
|
mit
| 869 | 0 | 11 | 137 | 167 | 83 | 84 | 21 | 1 |
{-# htermination decodeFloat :: Float -> (Integer,Int) #-}
|
ComputationWithBoundedResources/ara-inference
|
doc/tpdb_trs/Haskell/full_haskell/Prelude_decodeFloat_1.hs
|
mit
| 59 | 0 | 2 | 8 | 3 | 2 | 1 | 1 | 0 |
{-# LANGUAGE OverloadedStrings #-}
module KirstieUtilSpec where
import Test.Hspec
import Control.Exception
import Control.Monad
import Data.Text (Text)
import Data.List (sort, nub)
import Data.Time.Clock
import Database.MongoDB hiding (sort)
import Web.Kirstie.Model
import Web.Kirstie.Util
import Util
spec :: Spec
spec = do
describe "Web.Kirstie.Util.parseArgs" $ do
it "parse arguments" $ do
let args = ["foo", "--bar", "--baz", "qux", "-quux", "foobar"
, "foobaz"]
expect = [ ("quux",["foobaz","foobar"]), ("baz",["qux"]), ("bar",[])
, ("no label",["foo"]) ]
parseArgs args `shouldBe` expect
describe "Web.Kirstie.Util.articleToTArticle" $ do
it "Article" $ do
let article = minimal { articleTags = ["foo", "bar baz"] }
tArticle = TArticle { title = minimal
, aid = "0"
, pubdate = TPubdate { date = "1858-11-17"
, year = "1858"
, month = "Nov"
, day = "17" }
, tags = [ TTag "foo" "foo"
, TTag "bar baz" "bar%20baz" ]
, content = minimal
, lastmod = "1858-11-17T00:00:00Z" }
articleToTArticle article `shouldBe` tArticle
describe "Web.Kirstie.Util.safeRead" $ do
it "readable string" $ do
(safeRead "400" :: Maybe Int) `shouldBe` Just 400
it "non readable string" $ do
(safeRead "foo" :: Maybe Int) `shouldBe` Nothing
it "mixed string" $ do
(safeRead "4oo" :: Maybe Int) `shouldBe` Just 4
describe "Web.Kirstie.Util.strErr" $ do
it "Left Error" $ do
let e = Left $ userError "foo" :: Either IOError String
strError e `shouldBe` Left "user error (foo)"
it "Right" $ do
let e = Right "foo" :: Either String String
strError e `shouldBe` Right "foo"
describe "Web.Kirstie.Util.filenameEncode" $ do
it "no necessary to encode" $ do
filenameEncode "foo bar" `shouldBe` "foo bar"
it "'\\0'" $ do
filenameEncode "foo\0bar" `shouldBe` "foo-bar"
it "'\NUL'" $ do
filenameEncode "foo\NULbar" `shouldBe` "foo-bar"
it "'/'" $ do
filenameEncode "foo/bar" `shouldBe` "foo-bar"
describe "Web.Kirstie.Util.rfcTime" $ do
it "1858-11-17 00:00:00 UTC" $ do
rfcTime minimal `shouldBe` "1858-11-17T00:00:00Z"
|
hekt/blog-system
|
test/KirstieUtilSpec.hs
|
mit
| 2,654 | 0 | 19 | 954 | 685 | 357 | 328 | 61 | 1 |
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
module Language.LSP.Types.CodeAction where
import Data.Aeson.TH
import Data.Aeson.Types
import Data.Default
import Data.Text ( Text )
import Language.LSP.Types.Command
import Language.LSP.Types.Diagnostic
import Language.LSP.Types.Common
import Language.LSP.Types.Location
import Language.LSP.Types.Progress
import Language.LSP.Types.TextDocument
import Language.LSP.Types.Utils
import Language.LSP.Types.WorkspaceEdit
data CodeActionKind
= -- | Empty kind.
CodeActionEmpty
| -- | Base kind for quickfix actions: @quickfix@.
CodeActionQuickFix
| -- | Base kind for refactoring actions: @refactor@.
CodeActionRefactor
| -- | Base kind for refactoring extraction actions: @refactor.extract@.
-- Example extract actions:
--
-- - Extract method
-- - Extract function
-- - Extract variable
-- - Extract interface from class
-- - ...
CodeActionRefactorExtract
| -- | Base kind for refactoring inline actions: @refactor.inline@.
--
-- Example inline actions:
--
-- - Inline function
-- - Inline variable
-- - Inline constant
-- - ...
CodeActionRefactorInline
| -- | Base kind for refactoring rewrite actions: @refactor.rewrite@.
--
-- Example rewrite actions:
--
-- - Convert JavaScript function to class
-- - Add or remove parameter
-- - Encapsulate field
-- - Make method static
-- - Move method to base class
-- - ...
CodeActionRefactorRewrite
| -- | Base kind for source actions: @source@.
--
-- Source code actions apply to the entire file.
CodeActionSource
| -- | Base kind for an organize imports source action: @source.organizeImports@.
CodeActionSourceOrganizeImports
| CodeActionUnknown Text
deriving (Read, Show, Eq)
instance ToJSON CodeActionKind where
toJSON CodeActionEmpty = String ""
toJSON CodeActionQuickFix = String "quickfix"
toJSON CodeActionRefactor = String "refactor"
toJSON CodeActionRefactorExtract = String "refactor.extract"
toJSON CodeActionRefactorInline = String "refactor.inline"
toJSON CodeActionRefactorRewrite = String "refactor.rewrite"
toJSON CodeActionSource = String "source"
toJSON CodeActionSourceOrganizeImports = String "source.organizeImports"
toJSON (CodeActionUnknown s) = String s
instance FromJSON CodeActionKind where
parseJSON (String "") = pure CodeActionEmpty
parseJSON (String "quickfix") = pure CodeActionQuickFix
parseJSON (String "refactor") = pure CodeActionRefactor
parseJSON (String "refactor.extract") = pure CodeActionRefactorExtract
parseJSON (String "refactor.inline") = pure CodeActionRefactorInline
parseJSON (String "refactor.rewrite") = pure CodeActionRefactorRewrite
parseJSON (String "source") = pure CodeActionSource
parseJSON (String "source.organizeImports") = pure CodeActionSourceOrganizeImports
parseJSON (String s) = pure (CodeActionUnknown s)
parseJSON _ = mempty
-- -------------------------------------
data CodeActionKindClientCapabilities =
CodeActionKindClientCapabilities
{ -- | The code action kind values the client supports. When this
-- property exists the client also guarantees that it will
-- handle values outside its set gracefully and falls back
-- to a default value when unknown.
_valueSet :: List CodeActionKind
} deriving (Show, Read, Eq)
deriveJSON lspOptions ''CodeActionKindClientCapabilities
instance Default CodeActionKindClientCapabilities where
def = CodeActionKindClientCapabilities (List allKinds)
where allKinds = [ CodeActionQuickFix
, CodeActionRefactor
, CodeActionRefactorExtract
, CodeActionRefactorInline
, CodeActionRefactorRewrite
, CodeActionSource
, CodeActionSourceOrganizeImports
]
data CodeActionLiteralSupport =
CodeActionLiteralSupport
{ _codeActionKind :: CodeActionKindClientCapabilities -- ^ The code action kind is support with the following value set.
} deriving (Show, Read, Eq)
deriveJSON lspOptions ''CodeActionLiteralSupport
data CodeActionResolveClientCapabilities =
CodeActionResolveClientCapabilities
{ _properties :: List Text -- ^ The properties that a client can resolve lazily.
} deriving (Show, Read, Eq)
deriveJSON lspOptions ''CodeActionResolveClientCapabilities
data CodeActionClientCapabilities = CodeActionClientCapabilities
{ -- | Whether code action supports dynamic registration.
_dynamicRegistration :: Maybe Bool,
-- | The client support code action literals as a valid response
-- of the `textDocument/codeAction` request.
-- Since 3.8.0
_codeActionLiteralSupport :: Maybe CodeActionLiteralSupport,
-- | Whether code action supports the `isPreferred` property. Since LSP 3.15.0
_isPreferredSupport :: Maybe Bool,
-- | Whether code action supports the `disabled` property.
--
-- @since 3.16.0
_disabledSupport :: Maybe Bool,
-- | Whether code action supports the `data` property which is
-- preserved between a `textDocument/codeAction` and a
-- `codeAction/resolve` request.
--
-- @since 3.16.0
_dataSupport :: Maybe Bool,
-- | Whether the client supports resolving additional code action
-- properties via a separate `codeAction/resolve` request.
--
-- @since 3.16.0
_resolveSupport :: Maybe CodeActionResolveClientCapabilities,
-- | Whether the client honors the change annotations in
-- text edits and resource operations returned via the
-- `CodeAction#edit` property by for example presenting
-- the workspace edit in the user interface and asking
-- for confirmation.
--
-- @since 3.16.0
_honorsChangeAnnotations :: Maybe Bool
}
deriving (Show, Read, Eq)
deriveJSON lspOptions ''CodeActionClientCapabilities
-- -------------------------------------
makeExtendingDatatype "CodeActionOptions" [''WorkDoneProgressOptions]
[("_codeActionKinds", [t| Maybe (List CodeActionKind) |]), ("_resolveProvider", [t| Maybe Bool |]) ]
deriveJSON lspOptions ''CodeActionOptions
makeExtendingDatatype "CodeActionRegistrationOptions"
[ ''TextDocumentRegistrationOptions
, ''CodeActionOptions
] []
deriveJSON lspOptions ''CodeActionRegistrationOptions
-- -------------------------------------
-- | Contains additional diagnostic information about the context in which a
-- code action is run.
data CodeActionContext = CodeActionContext
{ -- | An array of diagnostics known on the client side overlapping the range provided to the
-- @textDocument/codeAction@ request. They are provided so that the server knows which
-- errors are currently presented to the user for the given range. There is no guarantee
-- that these accurately reflect the error state of the resource. The primary parameter
-- to compute code actions is the provided range.
_diagnostics :: List Diagnostic
-- | Requested kind of actions to return.
--
-- Actions not of this kind are filtered out by the client before being shown. So servers
-- can omit computing them.
, _only :: Maybe (List CodeActionKind)
}
deriving (Read, Show, Eq)
deriveJSON lspOptions ''CodeActionContext
makeExtendingDatatype "CodeActionParams"
[ ''WorkDoneProgressParams
, ''PartialResultParams
]
[ ("_textDocument", [t|TextDocumentIdentifier|]),
("_range", [t|Range|]),
("_context", [t|CodeActionContext|])
]
deriveJSON lspOptions ''CodeActionParams
newtype Reason = Reason {_reason :: Text}
deriving (Read, Show, Eq)
deriveJSON lspOptions ''Reason
-- | A code action represents a change that can be performed in code, e.g. to fix a problem or
-- to refactor code.
--
-- A CodeAction must set either '_edit' and/or a '_command'. If both are supplied,
-- the '_edit' is applied first, then the '_command' is executed.
data CodeAction =
CodeAction
{ -- | A short, human-readable, title for this code action.
_title :: Text,
-- | The kind of the code action. Used to filter code actions.
_kind :: Maybe CodeActionKind,
-- | The diagnostics that this code action resolves.
_diagnostics :: Maybe (List Diagnostic),
-- | Marks this as a preferred action. Preferred actions are used by the `auto fix` command and can be targeted
-- by keybindings.
--
-- A quick fix should be marked preferred if it properly addresses the underlying error.
-- A refactoring should be marked preferred if it is the most reasonable choice of actions to take.
--
-- Since LSP 3.15.0
_isPreferred :: Maybe Bool,
_disabled :: Maybe Reason, -- ^ Marks that the code action cannot currently be applied.
-- | The workspace edit this code action performs.
_edit :: Maybe WorkspaceEdit,
-- | A command this code action executes. If a code action
-- provides an edit and a command, first the edit is
-- executed and then the command.
_command :: Maybe Command,
-- | A data entry field that is preserved on a code action between
-- a `textDocument/codeAction` and a `codeAction/resolve` request.
--
-- @since 3.16.0
_xdata :: Maybe Value
}
deriving (Read, Show, Eq)
deriveJSON lspOptions ''CodeAction
|
alanz/haskell-lsp
|
lsp-types/src/Language/LSP/Types/CodeAction.hs
|
mit
| 9,813 | 0 | 11 | 2,298 | 1,161 | 677 | 484 | 117 | 0 |
{-# LANGUAGE DeriveDataTypeable, RecordWildCards #-}
-- module Sgd.Svm.Main where
import qualified Data.ByteString.Lazy.Char8 as C
import System.Console.CmdArgs
import System.Environment (getArgs, withArgs)
import System.Exit
import Control.Monad (when)
import qualified Sgd.Svm.Read as R
import qualified Sgd.Svm.Train as T
import qualified Sgd.Svm.LossFun as L
data SgdOpts = SgdOpts
{ trainFile :: String
, testFile :: String
, lambda :: Double
, epochs :: Int
, dontnormalize :: Bool
--, directory :: FilePath
} deriving (Data, Typeable, Show, Eq)
sgdOpts :: SgdOpts
sgdOpts = SgdOpts
{ trainFile = def &= argPos 0 &= typ "TRAINING-FILE"
, testFile = def &=typ "TESTING-FILE" &= help "Testing data"
, lambda = 1e-5 &= help "Regularization parameter, default 1e-5"
, epochs = 5 &= help "Number of training epochs, default 5"
, dontnormalize = False &= help "Not normalize the L2 norm of patterns, default normalize"
}
getOpts :: IO SgdOpts
getOpts = cmdArgs $ sgdOpts
-- &= verbosityArgs [explicit, name "Verbose", name "V"] []
&= versionArg [explicit, name "version", name "v", summary _PROGRAM_INFO]
&= summary (_PROGRAM_INFO ++ ", " ++ _COPYRIGHT)
&= help _PROGRAM_ABOUT
&= helpArg [explicit, name "help", name "h"]
&= program _PROGRAM_NAME
--TODO, also describe trainfile, testfile format!!!
_PROGRAM_NAME = "svmsgd"
_PROGRAM_VERSION = "0.0.1"
_PROGRAM_INFO = _PROGRAM_NAME ++ " version " ++ _PROGRAM_VERSION
_PROGRAM_ABOUT = "svm + sgd + haskell"
_COPYRIGHT = "(C) Dazhuo Li 2013"
main :: IO ()
main = do
args <- getArgs
-- If the user did not specify any arguments, pretend as "--help" was given
opts <- (if null args then withArgs ["--help"] else id) getOpts
optionHandler opts
-- Before directly calling your main program, you should warn your user about incorrect arguments, if any.
optionHandler :: SgdOpts -> IO ()
optionHandler opts@SgdOpts{..} = do
-- Take the opportunity here to weed out ugly, malformed, or invalid arguments.
-- TODO also check trianFile is file
when (null trainFile) $ putStrLn "--trainFile is blank!" >> exitWith (ExitFailure 1)
when (lambda <= 0 || lambda > 10000) $ putStrLn "--lambda must be in (0, 1e4]" >> exitWith (ExitFailure 1)
when (epochs <= 0 || epochs > 1000000) $ putStrLn "--epochs must be in (0, 1e6]" >> exitWith (ExitFailure 1)
-- When you're done, pass the (corrected, or not) options to your actual program.
--putStrLn $ "hello train file , " ++ trainFile ++ "!"
--putStrLn $ "hello lambda, " ++ (show lambda) ++ " years old."
exec opts
exec opts@SgdOpts{..} = do
contents <- C.readFile trainFile
--putStrLn "hello"
let dat = case R.read contents :: Maybe [R.Sample Int] of
Nothing -> error "Wrong input format"
Just x -> if dontnormalize
then x
else R.normalizeEachSample x
--print dat
--putStrLn "hello2"
let model = T.train L.logLoss dat lambda epochs
--let predLoss = T.testMany (L.loss L.logLoss ) dat lambda model
print model
--print predLoss
|
daz-li/svm_sgd_haskell
|
src/Sgd/Svm/Main.hs
|
mit
| 3,191 | 0 | 15 | 743 | 699 | 372 | 327 | 55 | 3 |
-- Idiom brackets
-- ref: https://wiki.haskell.org/Idiom_brackets
-- f <$> x <*> y
-- Since f is not a pure function, it's f :: a -> b -> m c. The correct form would be
-- join $ f <$> x <*> y
-- f a b = [a+b]
-- join $ f <$> [1] <*> [2] = [3]
-- Idiom brakcets
-- Type class hackery to eliminate the 'join':
class Applicative i => Idiomatic i f g | g -> f i where
idiomatic :: i f -> g
iI :: Idiomatic i f g => f -> g
iI = idiomatic . pure
data Ii = Ii
instance Applicative i => Idiomatic i x (Ii -> i x) where
idiomatic xi Ii = xi
instance Idiomatic i f g => Idiomatic i (s -> f) (i s -> g) where
idiomatic sfi si = idiomatic (sfi <*> si)
-- iI f x y Ii = f <$> x <*> y
data Ji = Ji
instance (Monad i, Applicative i) => Idiomatic i (i x) (Ji -> i x) where
idiomatic xii Ji = join xii
-- iI f x y Ji = join $ f <$> x <*> y
data J = J
instance (Monad i, Idiomatic i f g) => Idiomatic i (i f) (J -> g) where
idiomatic fii J = idiomatic (join fii)
-- so you can insert joins wherever you like, thus:
-- iI f x y J z Ii
-- = join (f <$> x <*> y) <*> z
-- = do {x' <- x; y' <- y; f' <- f x y; z' <- z; return (f' z')}
|
Airtnp/Freshman_Simple_Haskell_Lib
|
Idioms/Idiom-brackets.hs
|
mit
| 1,169 | 0 | 8 | 330 | 323 | 171 | 152 | -1 | -1 |
module Day21Spec (spec) where
import Day21
import Test.Hspec
main :: IO ()
main = hspec spec
sampleInput :: String
sampleInput = unlines
[ "swap position 4 with position 0"
, "swap letter d with letter b"
, "reverse positions 0 through 4"
, "rotate left 1 step"
, "move position 1 to position 4"
, "move position 3 to position 0"
, "rotate based on position of letter b"
, "rotate based on position of letter d"
]
spec :: Spec
spec = do
describe "swapPositionInstruction" $ do
it "scramble 'swap position 4 with position 0' works on 'abcde'" $ do
scramble "abcde" (parseInput "swap position 4 with position 0") `shouldBe` "ebcda"
it "unscramble 'swap position 4 with position 0' works on 'ebcda'" $ do
unscramble "ebcda" (parseInput "swap position 4 with position 0") `shouldBe` "abcde"
describe "swapLetterInstruction" $ do
it "scramble 'swap letter d with letter b' works on 'ebcda'" $ do
scramble "ebcda" (parseInput "swap letter d with letter b") `shouldBe` "edcba"
it "unscramble 'swap letter d with letter b' works on 'edcba'" $ do
unscramble "edcba" (parseInput "swap letter d with letter b") `shouldBe` "ebcda"
describe "reverseInstruction" $ do
it "scramble 'reverse positions 0 through 4' works on 'edcba'" $ do
scramble "edcba" (parseInput "reverse positions 0 through 4") `shouldBe` "abcde"
it "unscramble 'reverse positions 0 through 4' works on 'abcde'" $ do
unscramble "abcde" (parseInput "reverse positions 0 through 4") `shouldBe` "edcba"
it "scramble 'reverse positions 1 through 3' works on 'abcde'" $ do
scramble "abcde" (parseInput "reverse positions 1 through 3") `shouldBe` "adcbe"
it "unscramble 'reverse positions 1 through 3' works on 'adcbe'" $ do
unscramble "adcbe" (parseInput "reverse positions 1 through 3") `shouldBe` "abcde"
describe "rotateLeftInstruction" $ do
it "scramble 'rotate left 1 step' works on 'abcde'" $ do
scramble "abcde" (parseInput "rotate left 1 step") `shouldBe` "bcdea"
it "unscramble 'rotate left 1 step' works on 'bcdea'" $ do
unscramble "bcdea" (parseInput "rotate left 1 step") `shouldBe` "abcde"
describe "rotateRightInstruction" $ do
it "scramble 'rotate right 2 steps' works on 'abcde'" $ do
scramble "abcde" (parseInput "rotate right 2 steps") `shouldBe` "deabc"
it "unscramble 'rotate right 2 steps' works on 'deabc'" $ do
unscramble "deabc" (parseInput "rotate right 2 steps") `shouldBe` "abcde"
describe "moveInstruction" $ do
it "scramble 'move position 1 to position 4' works on 'bcdea'" $ do
scramble "bcdea" (parseInput "move position 1 to position 4") `shouldBe` "bdeac"
it "unscramble 'move position 1 to position 4' works on 'bdeac'" $ do
unscramble "bdeac" (parseInput "move position 1 to position 4") `shouldBe` "bcdea"
it "scramble 'move position 3 to position 0' works on 'bdeac'" $ do
scramble "bdeac" (parseInput "move position 3 to position 0") `shouldBe` "abdec"
it "unscramble 'move position 3 to position 0' works on 'abdec'" $ do
unscramble "abdec" (parseInput "move position 3 to position 0") `shouldBe` "bdeac"
describe "rotatePositionInstruction" $ do
it "scramble 'rotate based on position of letter b' works on 'abdec'" $ do
scramble "abdec" (parseInput "rotate based on position of letter b") `shouldBe` "ecabd"
it "scramble 'rotate based on position of letter d' works on 'ecabd'" $ do
scramble "ecabd" (parseInput "rotate based on position of letter d") `shouldBe` "decab"
-- note that unscramble does not work on 5-character passwords for rotatePositionInstruction
it "unscramble 'rotate based on position of letter h' works on 'habcdefg'" $ do
unscramble "habcdefg" (parseInput "rotate based on position of letter h") `shouldBe` "abcdefgh"
it "unscramble 'rotate based on position of letter a' works on 'habcdefg'" $ do
unscramble "habcdefg" (parseInput "rotate based on position of letter a") `shouldBe` "abcdefgh"
it "unscramble 'rotate based on position of letter d' works on 'efghabcd'" $ do
unscramble "efghabcd" (parseInput "rotate based on position of letter d") `shouldBe` "abcdefgh"
describe "scramble" $ do
it "works on sample input" $ do
scramble "abcde" (parseInput sampleInput) `shouldBe` "decab"
describe "day21" $ do
it "works for actual input" $ do
actualInput <- readFile "inputs/day21.txt"
day21 actualInput `shouldBe` "dgfaehcb"
describe "day21'" $ do
it "works for actual input" $ do
actualInput <- readFile "inputs/day21.txt"
day21' actualInput `shouldBe` "fdhgacbe"
|
brianshourd/adventOfCode2016
|
test/Day21Spec.hs
|
mit
| 4,972 | 0 | 16 | 1,261 | 907 | 426 | 481 | 77 | 1 |
module Hackup.Config.Fields where
import Data.Text (Text, pack)
newtype ConfigField = ConfigField { fieldName :: String } deriving (Show, Eq, Ord)
fieldText :: ConfigField -> Text
fieldText = pack . fieldName
rootDirField :: ConfigField
rootDirField = ConfigField "rootDir"
defaultKeepField :: ConfigField
defaultKeepField = ConfigField "keep"
sectionArchiveNameField :: ConfigField
sectionArchiveNameField = ConfigField "archive"
sectionArchiveDirField :: ConfigField
sectionArchiveDirField = ConfigField "targetDir"
sectionKeepField :: ConfigField
sectionKeepField = ConfigField "keep"
sectionBaseDirField :: ConfigField
sectionBaseDirField = ConfigField "baseDir"
sectionItemsField :: ConfigField
sectionItemsField = ConfigField "contents"
sectionBeforeField :: ConfigField
sectionBeforeField = ConfigField "before"
sectionAfterField :: ConfigField
sectionAfterField = ConfigField "after"
commandField :: ConfigField
commandField = ConfigField "command"
commandWorkingDirField :: ConfigField
commandWorkingDirField = ConfigField "workingDir"
commandIgnoreFailureField :: ConfigField
commandIgnoreFailureField = ConfigField "ignoreFailure"
|
chwthewke/hackup
|
src/Hackup/Config/Fields.hs
|
mit
| 1,168 | 0 | 6 | 140 | 222 | 124 | 98 | 29 | 1 |
module Feature.RangeSpec where
import qualified Data.ByteString.Lazy as BL
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
defaultRange :: BL.ByteString
defaultRange = [json| { "min": 0, "max": 15 } |]
emptyRange :: BL.ByteString
emptyRange = [json| { "min": 2, "max": 2 } |]
spec :: SpecWith Application
spec = do
describe "POST /rpc/getitemrange" $ do
context "without range headers" $ do
context "with response under server size limit" $
it "returns whole range with status 200" $
post "/rpc/getitemrange" defaultRange `shouldRespondWith` 200
context "when I don't want the count" $ do
it "returns range Content-Range with */* for empty range" $
request methodPost "/rpc/getitemrange" [] emptyRange
`shouldRespondWith` [json| [] |] {matchHeaders = ["Content-Range" <:> "*/*"]}
it "returns range Content-Range with range/*" $
request methodPost "/rpc/getitemrange" [] defaultRange
`shouldRespondWith` [json| [{"id":1},{"id":2},{"id":3},{"id":4},{"id":5},{"id":6},{"id":7},{"id":8},{"id":9},{"id":10},{"id":11},{"id":12},{"id":13},{"id":14},{"id":15}] |]
{ matchHeaders = ["Content-Range" <:> "0-14/*"] }
context "with range headers" $ do
context "of acceptable range" $ do
it "succeeds with partial content" $ do
r <- request methodPost "/rpc/getitemrange"
(rangeHdrs $ ByteRangeFromTo 0 1) defaultRange
liftIO $ do
simpleHeaders r `shouldSatisfy`
matchHeader "Content-Range" "0-1/*"
simpleStatus r `shouldBe` ok200
it "understands open-ended ranges" $
request methodPost "/rpc/getitemrange"
(rangeHdrs $ ByteRangeFrom 0) defaultRange
`shouldRespondWith` 200
it "returns an empty body when there are no results" $
request methodPost "/rpc/getitemrange"
(rangeHdrs $ ByteRangeFromTo 0 1) emptyRange
`shouldRespondWith` "[]"
{ matchStatus = 200
, matchHeaders = ["Content-Range" <:> "*/*"]
}
it "allows one-item requests" $ do
r <- request methodPost "/rpc/getitemrange"
(rangeHdrs $ ByteRangeFromTo 0 0) defaultRange
liftIO $ do
simpleHeaders r `shouldSatisfy`
matchHeader "Content-Range" "0-0/*"
simpleStatus r `shouldBe` ok200
it "handles ranges beyond collection length via truncation" $ do
r <- request methodPost "/rpc/getitemrange"
(rangeHdrs $ ByteRangeFromTo 10 100) defaultRange
liftIO $ do
simpleHeaders r `shouldSatisfy`
matchHeader "Content-Range" "10-14/*"
simpleStatus r `shouldBe` ok200
context "of invalid range" $ do
it "fails with 416 for offside range" $
request methodPost "/rpc/getitemrange"
(rangeHdrs $ ByteRangeFromTo 1 0) emptyRange
`shouldRespondWith` 416
it "refuses a range with nonzero start when there are no items" $
request methodPost "/rpc/getitemrange"
(rangeHdrsWithCount $ ByteRangeFromTo 1 2) emptyRange
`shouldRespondWith` "[]"
{ matchStatus = 416
, matchHeaders = ["Content-Range" <:> "*/0"]
}
it "refuses a range requesting start past last item" $
request methodPost "/rpc/getitemrange"
(rangeHdrsWithCount $ ByteRangeFromTo 100 199) defaultRange
`shouldRespondWith` "[]"
{ matchStatus = 416
, matchHeaders = ["Content-Range" <:> "*/15"]
}
describe "GET /items" $ do
context "without range headers" $ do
context "with response under server size limit" $
it "returns whole range with status 200" $
get "/items" `shouldRespondWith` 200
context "when I don't want the count" $ do
it "returns range Content-Range with /*" $
request methodGet "/menagerie"
[("Prefer", "count=none")] ""
`shouldRespondWith` "[]"
{ matchStatus = 200
, matchHeaders = ["Content-Range" <:> "*/*"]
}
it "returns range Content-Range with range/*" $
request methodGet "/items?order=id"
[("Prefer", "count=none")] ""
`shouldRespondWith` [json| [{"id":1},{"id":2},{"id":3},{"id":4},{"id":5},{"id":6},{"id":7},{"id":8},{"id":9},{"id":10},{"id":11},{"id":12},{"id":13},{"id":14},{"id":15}] |]
{ matchHeaders = ["Content-Range" <:> "0-14/*"] }
it "returns range Content-Range with range/* even using other filters" $
request methodGet "/items?id=eq.1&order=id"
[("Prefer", "count=none")] ""
`shouldRespondWith` [json| [{"id":1}] |]
{ matchHeaders = ["Content-Range" <:> "0-0/*"] }
context "with limit/offset parameters" $ do
it "no parameters return everything" $
get "/items?select=id&order=id.asc"
`shouldRespondWith`
[json|[{"id":1},{"id":2},{"id":3},{"id":4},{"id":5},{"id":6},{"id":7},{"id":8},{"id":9},{"id":10},{"id":11},{"id":12},{"id":13},{"id":14},{"id":15}]|]
{ matchStatus = 200
, matchHeaders = ["Content-Range" <:> "0-14/*"]
}
it "top level limit with parameter" $
get "/items?select=id&order=id.asc&limit=3"
`shouldRespondWith` [json|[{"id":1},{"id":2},{"id":3}]|]
{ matchStatus = 200
, matchHeaders = ["Content-Range" <:> "0-2/*"]
}
it "headers override get parameters" $
request methodGet "/items?select=id&order=id.asc&limit=3"
(rangeHdrs $ ByteRangeFromTo 0 1) ""
`shouldRespondWith` [json|[{"id":1},{"id":2}]|]
{ matchStatus = 200
, matchHeaders = ["Content-Range" <:> "0-1/*"]
}
it "limit works on all levels" $
get "/clients?select=id,projects(id,tasks(id))&order=id.asc&limit=1&projects.order=id.asc&projects.limit=2&projects.tasks.order=id.asc&projects.tasks.limit=1"
`shouldRespondWith`
[json|[{"id":1,"projects":[{"id":1,"tasks":[{"id":1}]},{"id":2,"tasks":[{"id":3}]}]}]|]
{ matchStatus = 200
, matchHeaders = ["Content-Range" <:> "0-0/*"]
}
it "limit and offset works on first level" $
get "/items?select=id&order=id.asc&limit=3&offset=2"
`shouldRespondWith` [json|[{"id":3},{"id":4},{"id":5}]|]
{ matchStatus = 200
, matchHeaders = ["Content-Range" <:> "2-4/*"]
}
it "succeeds if offset equals 0 as a no-op" $
get "/items?select=id&offset=0"
`shouldRespondWith`
[json|[{"id":1},{"id":2},{"id":3},{"id":4},{"id":5},{"id":6},{"id":7},{"id":8},{"id":9},{"id":10},{"id":11},{"id":12},{"id":13},{"id":14},{"id":15}]|]
{ matchStatus = 200
, matchHeaders = ["Content-Range" <:> "0-14/*"]
}
it "succeeds if offset is negative as a no-op" $
get "/items?select=id&offset=-4"
`shouldRespondWith`
[json|[{"id":1},{"id":2},{"id":3},{"id":4},{"id":5},{"id":6},{"id":7},{"id":8},{"id":9},{"id":10},{"id":11},{"id":12},{"id":13},{"id":14},{"id":15}]|]
{ matchStatus = 200
, matchHeaders = ["Content-Range" <:> "0-14/*"]
}
it "fails if limit equals 0" $
get "/items?select=id&limit=0"
`shouldRespondWith` [json|{"message":"HTTP Range error"}|]
{ matchStatus = 416
, matchHeaders = [matchContentTypeJson]
}
it "fails if limit is negative" $
get "/items?select=id&limit=-1"
`shouldRespondWith` [json|{"message":"HTTP Range error"}|]
{ matchStatus = 416
, matchHeaders = [matchContentTypeJson]
}
context "with range headers" $ do
context "of acceptable range" $ do
it "succeeds with partial content" $ do
r <- request methodGet "/items"
(rangeHdrs $ ByteRangeFromTo 0 1) ""
liftIO $ do
simpleHeaders r `shouldSatisfy`
matchHeader "Content-Range" "0-1/*"
simpleStatus r `shouldBe` ok200
it "understands open-ended ranges" $
request methodGet "/items"
(rangeHdrs $ ByteRangeFrom 0) ""
`shouldRespondWith` 200
it "returns an empty body when there are no results" $
request methodGet "/menagerie"
(rangeHdrs $ ByteRangeFromTo 0 1) ""
`shouldRespondWith` "[]"
{ matchStatus = 200
, matchHeaders = ["Content-Range" <:> "*/*"]
}
it "allows one-item requests" $ do
r <- request methodGet "/items"
(rangeHdrs $ ByteRangeFromTo 0 0) ""
liftIO $ do
simpleHeaders r `shouldSatisfy`
matchHeader "Content-Range" "0-0/*"
simpleStatus r `shouldBe` ok200
it "handles ranges beyond collection length via truncation" $ do
r <- request methodGet "/items"
(rangeHdrs $ ByteRangeFromTo 10 100) ""
liftIO $ do
simpleHeaders r `shouldSatisfy`
matchHeader "Content-Range" "10-14/*"
simpleStatus r `shouldBe` ok200
context "of invalid range" $ do
it "fails with 416 for offside range" $
request methodGet "/items"
(rangeHdrs $ ByteRangeFromTo 1 0) ""
`shouldRespondWith` 416
it "refuses a range with nonzero start when there are no items" $
request methodGet "/menagerie"
(rangeHdrsWithCount $ ByteRangeFromTo 1 2) ""
`shouldRespondWith` "[]"
{ matchStatus = 416
, matchHeaders = ["Content-Range" <:> "*/0"]
}
it "refuses a range requesting start past last item" $
request methodGet "/items"
(rangeHdrsWithCount $ ByteRangeFromTo 100 199) ""
`shouldRespondWith` "[]"
{ matchStatus = 416
, matchHeaders = ["Content-Range" <:> "*/15"]
}
|
diogob/postgrest
|
test/Feature/RangeSpec.hs
|
mit
| 10,546 | 0 | 23 | 3,209 | 1,902 | 1,003 | 899 | -1 | -1 |
-- |
-- Module: Math.NumberTheory.Powers.FourthTests
-- Copyright: (c) 2016 Andrew Lelechenko
-- Licence: MIT
-- Maintainer: Andrew Lelechenko <[email protected]>
-- Stability: Provisional
--
-- Tests for Math.NumberTheory.Powers.Fourth
--
{-# LANGUAGE CPP #-}
{-# OPTIONS_GHC -fno-warn-type-defaults #-}
module Math.NumberTheory.Powers.FourthTests
( testSuite
) where
import Test.Tasty
import Test.Tasty.HUnit
import Data.Maybe
#if MIN_VERSION_base(4,8,0)
#else
import Data.Word
#endif
import Math.NumberTheory.Powers.Fourth
import Math.NumberTheory.TestUtils
#include "MachDeps.h"
-- | Check that 'integerFourthRoot' returns the largest integer @m@ with @m^4 <= n@.
--
-- (m + 1) ^ 4 /= n && (m + 1) ^ 3 >= n `div` (m + 1)
-- means
-- (m + 1) ^ 4 > n
-- but without overflow for bounded types
integerFourthRootProperty :: Integral a => NonNegative a -> Bool
integerFourthRootProperty (NonNegative n) = m >= 0 && m ^ 4 <= n && (m + 1) ^ 4 /= n && (m + 1) ^ 3 >= n `div` (m + 1)
where
m = integerFourthRoot n
-- | Specialized to trigger 'biSqrtInt'.
integerFourthRootProperty_Int :: NonNegative Int -> Bool
integerFourthRootProperty_Int = integerFourthRootProperty
-- | Specialized to trigger 'biSqrtWord'.
integerFourthRootProperty_Word :: NonNegative Word -> Bool
integerFourthRootProperty_Word = integerFourthRootProperty
-- | Specialized to trigger 'biSqrtIgr'.
integerFourthRootProperty_Integer :: NonNegative Integer -> Bool
integerFourthRootProperty_Integer = integerFourthRootProperty
-- | Check that 'integerFourthRoot' returns the largest integer @m@ with @m^4 <= n@, , where @n@ has form @k@^4-1.
integerFourthRootProperty2 :: Integral a => NonNegative a -> Bool
integerFourthRootProperty2 (NonNegative k) = n < 0 || m >= 0 && m ^ 4 <= n && (m + 1) ^ 4 /= n && (m + 1) ^ 3 >= n `div` (m + 1)
where
n = k ^ 4 - 1
m = integerFourthRoot n
-- | Specialized to trigger 'biSqrtInt.
integerFourthRootProperty2_Int :: NonNegative Int -> Bool
integerFourthRootProperty2_Int = integerFourthRootProperty2
-- | Specialized to trigger 'biSqrtWord'.
integerFourthRootProperty2_Word :: NonNegative Word -> Bool
integerFourthRootProperty2_Word = integerFourthRootProperty2
#if WORD_SIZE_IN_BITS == 64
-- | Check that 'integerFourthRoot' of 2^60-1 is 2^15-1, not 2^15.
integerFourthRootSpecialCase1_Int :: Assertion
integerFourthRootSpecialCase1_Int =
assertEqual "integerFourthRoot" (integerFourthRoot (maxBound `div` 8 :: Int)) (2 ^ 15 - 1)
-- | Check that 'integerFourthRoot' of 2^60-1 is 2^15-1, not 2^15.
integerFourthRootSpecialCase1_Word :: Assertion
integerFourthRootSpecialCase1_Word =
assertEqual "integerFourthRoot" (integerFourthRoot (maxBound `div` 16 :: Word)) (2 ^ 15 - 1)
-- | Check that 'integerFourthRoot' of 2^64-1 is 2^16-1, not 2^16.
integerFourthRootSpecialCase2 :: Assertion
integerFourthRootSpecialCase2 =
assertEqual "integerFourthRoot" (integerFourthRoot (maxBound :: Word)) (2 ^ 16 - 1)
#endif
-- | Check that 'integerFourthRoot'' returns the largest integer @m@ with @m^4 <= n@.
integerFourthRoot'Property :: Integral a => NonNegative a -> Bool
integerFourthRoot'Property (NonNegative n) = m >= 0 && m ^ 4 <= n && (m + 1) ^ 4 /= n && (m + 1) ^ 3 >= n `div` (m + 1)
where
m = integerFourthRoot' n
-- | Check that the number 'isFourthPower' iff its 'integerFourthRoot' is exact.
isFourthPowerProperty :: Integral a => AnySign a -> Bool
isFourthPowerProperty (AnySign n) = (n < 0 && not t) || (n /= m ^ 4 && not t) || (n == m ^ 4 && t)
where
t = isFourthPower n
m = integerFourthRoot n
-- | Check that the number 'isFourthPower'' iff its 'integerFourthRoot'' is exact.
isFourthPower'Property :: Integral a => NonNegative a -> Bool
isFourthPower'Property (NonNegative n) = (n /= m ^ 4 && not t) || (n == m ^ 4 && t)
where
t = isFourthPower' n
m = integerFourthRoot' n
-- | Check that 'exactFourthRoot' returns an exact integer root of fourth power
-- and is consistent with 'isFourthPower'.
exactFourthRootProperty :: Integral a => AnySign a -> Bool
exactFourthRootProperty (AnySign n) = case exactFourthRoot n of
Nothing -> not (isFourthPower n)
Just m -> isFourthPower n && n == m ^ 4
-- | Check that 'isPossibleFourthPower' is consistent with 'exactFourthRoot'.
isPossibleFourthPowerProperty :: Integral a => NonNegative a -> Bool
isPossibleFourthPowerProperty (NonNegative n) = t || not t && isNothing m
where
t = isPossibleFourthPower n
m = exactFourthRoot n
testSuite :: TestTree
testSuite = testGroup "Fourth"
[ testGroup "integerFourthRoot"
[ testIntegralProperty "generic" integerFourthRootProperty
, testSmallAndQuick "generic Int" integerFourthRootProperty_Int
, testSmallAndQuick "generic Word" integerFourthRootProperty_Word
, testSmallAndQuick "generic Integer" integerFourthRootProperty_Integer
, testIntegralProperty "almost Fourth" integerFourthRootProperty2
, testSmallAndQuick "almost Fourth Int" integerFourthRootProperty2_Int
, testSmallAndQuick "almost Fourth Word" integerFourthRootProperty2_Word
#if WORD_SIZE_IN_BITS == 64
, testCase "maxBound / 8 :: Int" integerFourthRootSpecialCase1_Int
, testCase "maxBound / 16 :: Word" integerFourthRootSpecialCase1_Word
, testCase "maxBound :: Word" integerFourthRootSpecialCase2
#endif
]
, testIntegralProperty "integerFourthRoot'" integerFourthRoot'Property
, testIntegralProperty "isFourthPower" isFourthPowerProperty
, testIntegralProperty "isFourthPower'" isFourthPower'Property
, testIntegralProperty "exactFourthRoot" exactFourthRootProperty
, testIntegralProperty "isPossibleFourthPower" isPossibleFourthPowerProperty
]
|
cfredric/arithmoi
|
test-suite/Math/NumberTheory/Powers/FourthTests.hs
|
mit
| 5,790 | 0 | 17 | 1,024 | 1,131 | 606 | 525 | 61 | 2 |
module Main where
import qualified Language.Wasm.Entry as Entry
main :: IO ()
main = Entry.main
|
haskell-wasm/wasm
|
exec/Main.hs
|
mit
| 98 | 0 | 6 | 17 | 30 | 19 | 11 | 4 | 1 |
-- ID: RNA
-- Name: Transcribing DNA into RNA
-- Author: Samuel Jackson
-- Email: [email protected]
--replace any occurance of T with the letter U
transcribe :: String -> String
transcribe xs = map replace xs
where
replace :: Char -> Char
replace x
| x == 'T' = 'U'
| otherwise = x
main:: IO ()
main = do
line <- getLine
putStrLn $ transcribe line
|
samueljackson92/rosalind
|
src/RNA_transcribing_DNA_to_RNA.hs
|
gpl-2.0
| 398 | 2 | 9 | 109 | 100 | 49 | 51 | 10 | 1 |
--
-- Copyright (c) 2013-2019 Nicola Bonelli <[email protected]>
--
-- 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
--
module CGrep.Strategy.Cpp.Tokenizer (search) where
import qualified Data.ByteString.Char8 as C
import qualified CGrep.Parser.Cpp.Token as Cpp
import Control.Monad.Trans.Reader ( reader )
import Control.Monad.IO.Class ( MonadIO(liftIO) )
import CGrep.Filter
( ContextFilter(getFilterComment), mkContextFilter, contextFilter )
import CGrep.Lang ( getFileLang )
import CGrep.Common
import CGrep.Output ( Output, mkOutput )
import CGrep.Distance ( (~==) )
import Data.List ( isSuffixOf, isInfixOf, isPrefixOf )
import Reader ( OptionT )
import Options
import Debug ( putStrLevel1, putStrLevel2, putStrLevel3 )
import Util ( notNull )
search :: FilePath -> [Text8] -> OptionT IO [Output]
search f ps = do
opt <- reader snd
text <- liftIO $ getTargetContents f
let filename = getTargetName f
-- transform text
let filt = (mkContextFilter opt) { getFilterComment = False }
let [text''', _ , text', _] = scanr ($) text [ expandMultiline opt
, contextFilter (getFileLang opt filename) filt
, ignoreCase opt
]
putStrLevel1 $ "strategy : running C/C++ token search on " ++ filename ++ "..."
let quick = all notNull $ shallowSearch ps text'
runSearch opt filename quick $ do
-- parse source code, get the Cpp.Token list...
let tokens = Cpp.tokenizer text'''
-- context-filterting...
tokens'= filter (Cpp.tokenFilter Cpp.TokenFilter { Cpp.filtIdentifier = identifier opt,
Cpp.filtDirective = directive opt,
Cpp.filtKeyword = keyword opt,
Cpp.filtHeader = header opt,
Cpp.filtString = string opt,
Cpp.filtNumber = number opt,
Cpp.filtChar = char opt,
Cpp.filtOper = oper opt}) tokens
-- filter tokens...
tokens'' = cppTokenFilter opt (map C.unpack ps) tokens'
-- convert Cpp.Tokens to CGrep.Tokens
matches = map (\t -> let off = fromIntegral (Cpp.toOffset t) in (off, Cpp.toString t)) tokens'' :: [(Int, String)]
putStrLevel2 $ "tokens : " ++ show tokens
putStrLevel2 $ "tokens' : " ++ show tokens'
putStrLevel2 $ "tokens'' : " ++ show tokens''
putStrLevel2 $ "matches : " ++ show matches
putStrLevel3 $ "---\n" ++ C.unpack text''' ++ "\n---"
mkOutput filename text text''' matches
cppTokenFilter :: Options -> [String] -> [Cpp.Token] -> [Cpp.Token]
cppTokenFilter opt patterns tokens
| edit_dist opt = filter (\t -> any (\p -> p ~== Cpp.toString t) patterns) tokens
| word_match opt = filter ((`elem` patterns) . Cpp.toString) tokens
| prefix_match opt = filter ((\t -> any (`isPrefixOf`t) patterns) . Cpp.toString) tokens
| suffix_match opt = filter ((\t -> any (`isSuffixOf`t) patterns) . Cpp.toString) tokens
| otherwise = filter ((\t -> any (`isInfixOf` t) patterns) . Cpp.toString) tokens
|
awgn/cgrep
|
src/CGrep/Strategy/Cpp/Tokenizer.hs
|
gpl-2.0
| 4,214 | 0 | 23 | 1,370 | 940 | 512 | 428 | 52 | 1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeFamilies #-}
module Point (Point(..)) where
import Control.Monad (liftM)
import qualified Data.Vector.Generic.Mutable as M
import qualified Data.Vector.Generic as G
import qualified Data.Vector.Unboxed.Base as U
import Foreign.Ptr (castPtr)
import Foreign.Storable (Storable(..))
data Point = Point {
pX :: {-# UNPACK #-} !Double
, pY :: {-# UNPACK #-} !Double
} deriving (Eq, Show)
instance Storable Point where
sizeOf _ = 2 * sizeOf (undefined::Double)
{-# INLINE sizeOf #-}
alignment _ = alignment (undefined::Double)
{-# INLINE alignment #-}
poke ptr (Point x y) = poke ptr' x >> pokeElemOff ptr' 1 y
where ptr' = castPtr ptr
{-# INLINE poke #-}
peek ptr = Point <$> peek ptr' <*> peekElemOff ptr' 1
where ptr' = castPtr ptr
{-# INLINE peek #-}
data instance U.Vector Point = V_Point !Int (U.Vector Double)
data instance U.MVector s Point = MV_Point !Int (U.MVector s Double)
instance U.Unbox Point
instance M.MVector U.MVector Point where
basicLength (MV_Point n _) = n
basicUnsafeSlice m n (MV_Point _ v) = MV_Point n (M.basicUnsafeSlice (2*m) (2*n) v)
basicOverlaps (MV_Point _ v) (MV_Point _ u) = M.basicOverlaps v u
basicUnsafeNew n = liftM (MV_Point n) (M.basicUnsafeNew (2*n))
basicUnsafeRead (MV_Point _ v) i =
do let o = 2*i
x <- M.basicUnsafeRead v o
y <- M.basicUnsafeRead v (o+1)
return (Point x y)
basicUnsafeWrite (MV_Point _ v) i (Point x y) =
do let o = 2*i
M.basicUnsafeWrite v o x
M.basicUnsafeWrite v (o+1) y
#if MIN_VERSION_vector(0,11,0)
basicInitialize (MV_Point _ v) = M.basicInitialize v
#endif
instance G.Vector U.Vector Point where
basicUnsafeFreeze (MV_Point n v) = liftM ( V_Point n) (G.basicUnsafeFreeze v)
basicUnsafeThaw ( V_Point n v) = liftM (MV_Point n) (G.basicUnsafeThaw v)
basicLength ( V_Point n _) = n
basicUnsafeSlice m n (V_Point _ v) = V_Point n (G.basicUnsafeSlice (2*m) (2*n) v)
basicUnsafeIndexM (V_Point _ v) i =
do let o = 2*i
x <- G.basicUnsafeIndexM v o
y <- G.basicUnsafeIndexM v (o+1)
return (Point x y)
|
meteogrid/hs-multivac
|
src/Point.hs
|
gpl-2.0
| 2,186 | 0 | 11 | 474 | 864 | 443 | 421 | 56 | 0 |
{-# OPTIONS_GHC -Wall -Werror -i.. #-}
{-# LANGUAGE GADTs, RankNTypes #-}
module HIR.DeadAssignmentElimination(deadAssignmentEliminationPass,
runDeadAssignmentElimination) where
import Compiler.Hoopl
import qualified Data.Maybe as Mby
import qualified Data.List as L
import qualified Data.Set as S
import HIR.HIR
import Utils.Common
type DAEFact = S.Set SSAVar
daeLattice :: DataflowLattice DAEFact
daeLattice = DataflowLattice {
fact_name = "Dead Code Elimination",
fact_bot = S.empty,
fact_join = optimizedUnion
} where
optimizedUnion _ (OldFact old) (NewFact new)
| S.null new = (NoChange, old)
| otherwise = (SomeChange, old `S.union` new)
transferDAE :: BwdTransfer HNode DAEFact
transferDAE = mkBTransfer3 closeOpen openOpen openClose
where
closeOpen _ = id
openOpen node f =
let rVars = getHVarsRead node
wVars = getHVarsWritten node
clearDefinedVars = L.foldl (flip S.delete) f wVars
in L.foldl (flip S.insert) clearDefinedVars rVars
openClose :: HNode O C -> FactBase DAEFact -> DAEFact
openClose node fBase =
let rVars = getHVarsRead node
wVars = getHVarsWritten node
totalFacts = S.unions $ map getFact $ successors node
clearDefinedVars = L.foldl (flip S.delete) totalFacts wVars
in L.foldl (flip S.insert) clearDefinedVars rVars
where getFact lbl = Mby.fromMaybe S.empty $ mapLookup lbl fBase
eliminateDeadAssignments :: forall m. FuelMonad m => BwdRewrite m HNode DAEFact
eliminateDeadAssignments = mkBRewrite3 closeOpen openOpen openClose
where
closeOpen _ _ = return Nothing
openClose _ _ = return Nothing
openOpen node facts = if any (`S.member` facts) (getHVarsWritten node)
then return Nothing
else return $ Just emptyGraph
deadAssignmentEliminationPass :: FuelMonad m => BwdPass m HNode DAEFact
deadAssignmentEliminationPass = BwdPass {
bp_lattice = daeLattice,
bp_transfer = transferDAE,
bp_rewrite = eliminateDeadAssignments
}
runDeadAssignmentElimination :: HFunction -> M HFunction
runDeadAssignmentElimination hFunc = do
(body, _, _) <- analyzeAndRewriteBwd deadAssignmentEliminationPass
(JustC [hFnEntry hFunc]) (hFnBody hFunc) $
mapSingleton (hFnEntry hFunc) S.empty
return hFunc{hFnBody = body}
|
sanjoy/echoes
|
src/HIR/DeadAssignmentElimination.hs
|
gpl-3.0
| 2,402 | 0 | 14 | 558 | 656 | 342 | 314 | 53 | 2 |
module ProjectEuler where
import Data.List
import Test.QuickCheck
import Control.Monad
import Data.Bits
prime :: Integer -> Bool
prime n = n > 1 && all (\ x -> rem n x /= 0) xs
where xs = takeWhile (\ y -> y^2 <= n) primes
primes :: [Integer]
primes = 2 : filter prime [3..]
-- Reusing the prime method from the lecture
-- Time spent: 30 min (on both)
-- 10: simply sum until 2.000.000
solution10 :: Integer
solution10 = sum ( takeWhile (< 2000000) primes )
-- 9: try to create a list and using guards to set the values and the constraints
-- next simply multiply them and get the first (and only) element
solution9 :: Integer
solution9 = head [a * b * c | a <- [1..1000], b <- [a..1000], let c = 1000 - a -b, a^2 + b^2 == c^2]
-- 49: create a list of primes between 1000 and 10000
-- generate a tuple which differs by 3330 and are ale in the primes1000 list
-- check for permutations with built-in elem and permutations function
-- Time spent: 20 min
primes1000 :: [Integer]
primes1000 = dropWhile (< 1000) $ takeWhile (< 10000) primes
digits :: Integer -> [Int]
digits = map (read . return) . show
isPermutation :: (Integer, Integer, Integer) -> Bool
isPermutation (a, b, c) = elem (digits b) (permutations (digits a)) && elem (digits c) (permutations (digits a))
result :: (Integer, Integer, Integer) -> String
result (a, b, c) = (show a) ++ (show b) ++ (show c)
solution49 :: String
solution49 = result $ last $ filter isPermutation [(a , b, c) | a <- primes1000, let b = a + 3330, let c = b + 3330, b `elem` primes1000, c `elem` primes1000]
|
vdweegen/UvA-Software_Testing
|
Lab1/Willem/ProjectEuler.hs
|
gpl-3.0
| 1,560 | 0 | 12 | 309 | 551 | 304 | 247 | 24 | 1 |
module Eval where
import qualified Data.Map as Map
import Data.List (foldl', null, isSuffixOf)
import Data.List.Split (splitOn, splitWhen)
import Data.Maybe (fromJust, mapMaybe, isJust)
import Control.Monad.State
import Control.Monad.State.Lazy (StateT(..), runStateT, liftIO, modify, get, put)
import System.Exit (exitSuccess, exitFailure, exitWith, ExitCode(..))
import qualified System.IO as SysIO
import System.Directory (doesFileExist, canonicalizePath, createDirectoryIfMissing, getCurrentDirectory, getHomeDirectory, setCurrentDirectory)
import System.Process (readProcess, readProcessWithExitCode)
import Control.Concurrent (forkIO)
import qualified Data.Map as Map
import Data.Maybe (fromJust, mapMaybe, isJust)
import Control.Monad
import Control.Exception
import qualified Text.Parsec as Parsec
import qualified Text.Parsec.Error as ParsecError
import Debug.Trace
import Parsing
import Emit
import Obj
import Types
import Infer
import Deftype
import ColorText
import Template
import Util
import Commands
import Expand
import Lookup
import Qualify
import TypeError
import Concretize
-- | Dynamic (REPL) evaluation of XObj:s (s-expressions)
eval :: Env -> XObj -> StateT Context IO (Either EvalError XObj)
eval env xobj =
case obj xobj of
--case obj (trace ("\nEval " ++ pretty xobj ++ ", obj: " ++ show (obj xobj)) xobj) of
Lst _ -> evalList xobj
Arr _ -> evalArray xobj
Sym _ _ -> evalSymbol xobj
_ -> return (Right xobj)
where
evalList :: XObj -> StateT Context IO (Either EvalError XObj)
evalList listXObj@(XObj (Lst xobjs) i t) =
case xobjs of
[] ->
return (Right xobj)
[XObj (Sym (SymPath [] "quote") _) _ _, target] ->
return (Right target)
[XObj (Sym (SymPath [] "file") _) _ _] ->
case i of
Just info -> return (Right (XObj (Str (infoFile info)) i t))
Nothing -> return (Left (EvalError ("No information about object " ++ pretty xobj)))
[XObj (Sym (SymPath [] "line") _) _ _] ->
case i of
Just info ->
return (Right (XObj (Num IntTy (fromIntegral (infoLine info))) i t))
Nothing ->
return (Left (EvalError ("No information about object " ++ pretty xobj)))
[XObj (Sym (SymPath [] "column") _) _ _] ->
case i of
Just info ->
return (Right (XObj (Num IntTy (fromIntegral (infoColumn info))) i t))
Nothing ->
return (Left (EvalError ("No information about object " ++ pretty xobj)))
[XObj (Sym (SymPath [] "file") _) _ _, XObj _ infoToCheck _] ->
case infoToCheck of
Just info -> return (Right (XObj (Str (infoFile info)) i t))
Nothing -> return (Left (EvalError ("No information about object " ++ pretty xobj)))
[XObj (Sym (SymPath [] "line") _) _ _, XObj _ infoToCheck _] ->
case infoToCheck of
Just info ->
return (Right (XObj (Num IntTy (fromIntegral (infoLine info))) i t))
Nothing ->
return (Left (EvalError ("No information about object " ++ pretty xobj)))
[XObj (Sym (SymPath [] "column") _) _ _, XObj _ infoToCheck _] ->
case infoToCheck of
Just info ->
return (Right (XObj (Num IntTy (fromIntegral (infoColumn info))) i t))
Nothing ->
return (Left (EvalError ("No information about object " ++ pretty xobj)))
XObj Do _ _ : rest ->
do evaledList <- fmap sequence (mapM (eval env) rest)
case evaledList of
Left e -> return (Left e)
Right ok ->
case ok of
[] -> return (Left (EvalError "No forms in 'do' statement."))
_ -> return (Right (last ok))
XObj (Sym (SymPath [] "list") _) _ _ : rest ->
do evaledList <- fmap sequence (mapM (eval env) rest)
return $ do okList <- evaledList
Right (XObj (Lst okList) i t)
XObj (Sym (SymPath [] "array") _) _ _ : rest ->
do evaledArray <- fmap sequence (mapM (eval env) rest)
return $ do okEvaledArray <- evaledArray
Right (XObj (Arr okEvaledArray) i t)
-- 'and' and 'or' are defined here because they are expected to short circuit
[XObj (Sym (SymPath ["Dynamic"] "and") _) _ _, a, b] ->
do evaledA <- eval env a
evaledB <- eval env b
return $ do okA <- evaledA
case okA of
XObj (Bol ab) _ _ ->
if ab
then do okB <- evaledB
case okB of
XObj (Bol bb) _ _ ->
if bb then Right trueXObj else Right falseXObj
_ ->
Left (EvalError ("Can't perform logical operation (and) on " ++ pretty okB))
else Right falseXObj
_ ->
Left (EvalError ("Can't perform logical operation (and) on " ++ pretty okA))
[XObj (Sym (SymPath ["Dynamic"] "or") _) _ _, a, b] ->
do evaledA <- eval env a
evaledB <- eval env b
return $ do okA <- evaledA
case okA of
XObj (Bol ab) _ _ ->
if ab
then Right trueXObj
else do okB <- evaledB
case okB of
XObj (Bol bb) _ _ ->
if bb then Right trueXObj else Right falseXObj
_ ->
Left (EvalError ("Can't perform logical operation (or) on " ++ pretty okB))
_ ->
Left (EvalError ("Can't perform logical operation (or) on " ++ pretty okA))
[XObj If _ _, condition, ifTrue, ifFalse] ->
do evaledCondition <- eval env condition
case evaledCondition of
Right okCondition ->
case obj okCondition of
Bol b -> if b
then eval env ifTrue
else eval env ifFalse
_ -> return (Left (EvalError ("Non-boolean expression in if-statement: " ++ pretty okCondition)))
Left err -> return (Left err)
[defnExpr@(XObj Defn _ _), name, args, body] ->
specialCommandDefine xobj
[defExpr@(XObj Def _ _), name, expr] ->
specialCommandDefine xobj
[theExpr@(XObj The _ _), typeXObj, value] ->
do evaledValue <- expandAll eval env value -- TODO: Why expand all here?
return $ do okValue <- evaledValue
Right (XObj (Lst [theExpr, typeXObj, okValue]) i t)
[letExpr@(XObj Let _ _), XObj (Arr bindings) bindi bindt, body] ->
if even (length bindings)
then do bind <- mapM (\(n, x) -> do x' <- eval env x
return $ do okX <- x'
(Right [n, okX]))
(pairwise bindings)
let innerEnv = Env Map.empty (Just env) (Just "LET") [] InternalEnv 0
let okBindings = sequence bind
case okBindings of
(Left err) -> return (Left err)
Right binds -> do
let envWithBindings = foldl' (\e [(XObj (Sym (SymPath _ n) _) _ _), x] -> extendEnv e n x)
innerEnv
binds
evaledBody <- eval envWithBindings body
return $ do okBody <- evaledBody
Right okBody
else return (Left (EvalError ("Uneven number of forms in let-statement: " ++ pretty xobj)))
XObj (Sym (SymPath [] "register-type") _) _ _ : XObj (Sym (SymPath _ typeName) _) _ _ : rest ->
specialCommandRegisterType typeName rest
XObj (Sym (SymPath _ "register-type") _) _ _ : _ ->
return (Left (EvalError (show "Invalid ars to 'register-type': " ++ pretty xobj)))
XObj (Sym (SymPath [] "deftype") _) _ _ : nameXObj : rest ->
specialCommandDeftype nameXObj rest
[XObj (Sym (SymPath [] "register") _) _ _, XObj (Sym (SymPath _ name) _) _ _, typeXObj] ->
specialCommandRegister name typeXObj Nothing
[XObj (Sym (SymPath [] "register") _) _ _, XObj (Sym (SymPath _ name) _) _ _, typeXObj, XObj (Str overrideName) _ _] ->
specialCommandRegister name typeXObj (Just overrideName)
XObj (Sym (SymPath [] "register") _) _ _ : _ ->
return (Left (EvalError ("Invalid args to 'register' command: " ++ pretty xobj)))
[XObj (Sym (SymPath [] "definterface") _) _ _, nameXObj@(XObj (Sym _ _) _ _), typeXObj] ->
specialCommandDefinterface nameXObj typeXObj
XObj (Sym (SymPath [] "definterface") _) _ _ : _ ->
return (Left (EvalError ("Invalid args to 'definterface' command: " ++ pretty xobj)))
[XObj (Sym (SymPath [] "defdynamic") _) _ _, (XObj (Sym (SymPath [] name) _) _ _), params, body] ->
specialCommandDefdynamic name params body
XObj (Sym (SymPath [] "defdynamic") _) _ _ : _ ->
return (Left (EvalError ("Invalid args to 'defdynamic' command: " ++ pretty xobj)))
[XObj (Sym (SymPath [] "defmacro") _) _ _, (XObj (Sym (SymPath [] name) _) _ _), params, body] ->
specialCommandDefmacro name params body
XObj (Sym (SymPath [] "defmacro") _) _ _ : _ ->
return (Left (EvalError ("Invalid args to 'defmacro' command: " ++ pretty xobj)))
XObj (Sym (SymPath [] "defmodule") _) _ _ : (XObj (Sym (SymPath [] moduleName) _) _ _) : innerExpressions ->
specialCommandDefmodule xobj moduleName innerExpressions
XObj (Sym (SymPath [] "defmodule") _) _ _ : _ ->
return (Left (EvalError ("Invalid args to 'defmodule' command: " ++ pretty xobj)))
[XObj (Sym (SymPath [] "info") _) _ _, target@(XObj (Sym path @(SymPath _ name) _) _ _)] ->
specialCommandInfo target
XObj (Sym (SymPath [] "info") _) _ _ : _ ->
return (Left (EvalError ("Invalid args to 'info' command: " ++ pretty xobj)))
[XObj (Sym (SymPath [] "type") _) _ _, target] ->
specialCommandType target
XObj (Sym (SymPath [] "type") _) _ _ : _ ->
return (Left (EvalError ("Invalid args to 'type' command: " ++ pretty xobj)))
[XObj (Sym (SymPath [] "meta-set!") _) _ _, target@(XObj (Sym path @(SymPath _ name) _) _ _), (XObj (Str key) _ _), value] ->
specialCommandMetaSet path key value
XObj (Sym (SymPath [] "meta-set!") _) _ _ : _ ->
return (Left (EvalError ("Invalid args to 'meta-set!' command: " ++ pretty xobj)))
[XObj (Sym (SymPath [] "meta") _) _ _, target@(XObj (Sym path @(SymPath _ name) _) _ _), (XObj (Str key) _ _)] ->
specialCommandMetaGet path key
XObj (Sym (SymPath [] "meta") _) _ _ : _ ->
return (Left (EvalError ("Invalid args to 'meta' command: " ++ pretty xobj)))
[XObj (Sym (SymPath [] "members") _) _ _, target] ->
specialCommandMembers target
XObj (Sym (SymPath [] "members") _) _ _ : _ ->
return (Left (EvalError ("Invalid args to 'members' command: " ++ pretty xobj)))
[XObj (Sym (SymPath [] "use") _) _ _, xobj@(XObj (Sym path _) _ _)] ->
specialCommandUse xobj path
XObj (Sym (SymPath [] "use") _) _ _ : _ ->
return (Left (EvalError ("Invalid args to 'use' command: " ++ pretty xobj)))
XObj With _ _ : xobj@(XObj (Sym path _) _ _) : forms ->
specialCommandWith xobj path forms
XObj With _ _ : _ ->
return (Left (EvalError ("Invalid args to 'with.' command: " ++ pretty xobj)))
f:args -> do evaledF <- eval env f
case evaledF of
Right (XObj (Lst [XObj Dynamic _ _, _, XObj (Arr params) _ _, body]) _ _) ->
case checkMatchingNrOfArgs f params args of
Left err -> return (Left err)
Right () ->
do evaledArgs <- fmap sequence (mapM (eval env) args)
case evaledArgs of
Right okArgs -> apply env body params okArgs
Left err -> return (Left err)
Right (XObj (Lst [XObj Macro _ _, _, XObj (Arr params) _ _, body]) _ _) ->
case checkMatchingNrOfArgs f params args of
Left err ->
return (Left err)
Right () ->
-- Replace info so that the macro which is called gets the source location info of the expansion site.
let replacedBody = (replaceSourceInfoOnXObj (info xobj) body)
in apply env replacedBody params args
Right (XObj (Lst [XObj (Command callback) _ _, _]) _ _) ->
do evaledArgs <- fmap sequence (mapM (eval env) args)
case evaledArgs of
Right okArgs -> getCommand callback okArgs
Left err -> return (Left err)
_ ->
return (Left (EvalError ("Can't eval non-macro / non-dynamic function '" ++ pretty f ++ "' in " ++
pretty xobj ++ " at " ++ prettyInfoFromXObj xobj)))
evalList _ = error "Can't eval non-list in evalList."
evalSymbol :: XObj -> StateT Context IO (Either EvalError XObj)
evalSymbol xobj@(XObj (Sym path@(SymPath pathStrings name) _) _ _) =
case lookupInEnv (SymPath ("Dynamic" : pathStrings) name) env of -- A slight hack!
Just (_, Binder _ found) -> return (Right found) -- use the found value
Nothing ->
case lookupInEnv path env of
Just (_, Binder _ found) -> return (Right found)
Nothing -> return (Left (EvalError ("Can't find symbol '" ++ show path ++ "' at " ++ prettyInfoFromXObj xobj)))
evalSymbol _ = error "Can't eval non-symbol in evalSymbol."
evalArray :: XObj -> StateT Context IO (Either EvalError XObj)
evalArray (XObj (Arr xobjs) i t) =
do evaledXObjs <- fmap sequence (mapM (eval env) xobjs)
return $ do okXObjs <- evaledXObjs
Right (XObj (Arr okXObjs) i t)
evalArray _ = error "Can't eval non-array in evalArray."
-- | Make sure the arg list is the same length as the parameter list
checkMatchingNrOfArgs :: XObj -> [XObj] -> [XObj] -> Either EvalError ()
checkMatchingNrOfArgs xobj params args =
let usesRestArgs = not (null (filter isRestArgSeparator (map getName params)))
paramLen = if usesRestArgs then length params - 2 else length params
argsLen = length args
expected =
if usesRestArgs
then "at least " ++ show paramLen
else show paramLen
in if (usesRestArgs && argsLen > paramLen) || (paramLen == argsLen)
then Right ()
else Left (EvalError ("Wrong nr of arguments in call to '" ++ pretty xobj ++ "' at " ++ prettyInfoFromXObj xobj ++
", expected " ++ expected ++ " but got " ++ show argsLen ++ "."
))
-- | Apply a function to some arguments. The other half of 'eval'.
apply :: Env -> XObj -> [XObj] -> [XObj] -> StateT Context IO (Either EvalError XObj)
apply env body params args =
let insideEnv = Env Map.empty (Just env) Nothing [] InternalEnv 0
allParams = map getName params
[properParams, restParams] = case splitWhen isRestArgSeparator allParams of
[a, b] -> [a, b]
[a] -> [a, []]
_ -> error ("Invalid split of args: " ++ joinWith "," allParams)
n = length properParams
insideEnv' = foldl' (\e (p, x) -> extendEnv e p x) insideEnv (zip properParams (take n args))
insideEnv'' = if null restParams
then insideEnv'
else extendEnv insideEnv'
(head restParams)
(XObj (Lst (drop n args)) Nothing Nothing)
result = eval insideEnv'' body
in result
-- | Is a string the 'rest' separator for arguments to dynamic functions / macros
isRestArgSeparator :: String -> Bool
isRestArgSeparator ":rest" = True
isRestArgSeparator _ = False
-- | Print a found binder.
found binder =
liftIO $ do putStrLnWithColor White (show binder)
return dynamicNil
-- | Print error message for binder that wasn't found.
notFound :: ExecutionMode -> XObj -> SymPath -> StateT Context IO (Either EvalError XObj)
notFound execMode xobj path =
do fppl <- fmap (projectFilePathPrintLength . contextProj) get
return $ Left $ EvalError $ case execMode of
Check -> machineReadableInfoFromXObj fppl xobj ++ (" Can't find '" ++ show path ++ "'")
_ -> "Can't find '" ++ show path ++ "'"
-- | A command at the REPL
-- | TODO: Is it possible to remove the error cases?
data ReplCommand = ReplParseError String XObj
| ReplEval XObj
| ListOfCallbacks [CommandCallback]
-- | Parses a string and then converts the resulting forms to commands, which are evaluated in order.
executeString :: Bool -> Context -> String -> String -> IO Context
executeString doCatch ctx input fileName = if doCatch then catch exec (catcher ctx) else exec
where exec = case parse input fileName of
Left parseError ->
let sourcePos = Parsec.errorPos parseError
parseErrorXObj = XObj (Lst []) (Just dummyInfo { infoFile = fileName
, infoLine = Parsec.sourceLine sourcePos
, infoColumn = Parsec.sourceColumn sourcePos
}) Nothing
in executeCommand ctx (ReplParseError (replaceChars (Map.fromList [('\n', " ")]) (show parseError)) parseErrorXObj)
Right xobjs -> foldM folder ctx xobjs
-- | Used by functions that has a series of forms to evaluate and need to fold over them (producing a new Context in the end)
folder :: Context -> XObj -> IO Context
folder context xobj =
do cmd <- objToCommand context xobj
executeCommand context cmd
-- | Take a ReplCommand and execute it.
executeCommand :: Context -> ReplCommand -> IO Context
executeCommand ctx@(Context env typeEnv pathStrings proj lastInput execMode) cmd =
do when (isJust (envModuleName env)) $
error ("Global env module name is " ++ fromJust (envModuleName env) ++ " (should be Nothing).")
case cmd of
ReplEval xobj ->
do (result, newCtx) <- runStateT (eval env xobj) ctx
case result of
Left e ->
reportExecutionError newCtx (show e)
Right (XObj (Lst []) _ _) ->
-- Nil result won't print
do return newCtx
Right result@(XObj (Arr _) _ _) ->
do putStrLnWithColor Yellow ("=> " ++ (pretty result))
return newCtx
Right evaled ->
do -- HACK?! The result after evalution might be a list that
-- constitutes a 'def' or 'defn'. So let's evaluate again
-- to make it stick in the environment.
-- To log the intermediate result:
-- putStrLnWithColor Yellow ("-> " ++ (pretty evaled))
(result', newCtx') <- runStateT (eval env evaled) newCtx
case result' of
Left e ->
reportExecutionError newCtx' (show e)
Right (XObj (Lst []) _ _) ->
return newCtx' -- Once again, don't print nil result
Right okResult' ->
do putStrLnWithColor Yellow ("=> " ++ (pretty okResult'))
return newCtx'
-- TODO: This is a weird case:
ReplParseError e xobj ->
do let msg = ("[PARSE ERROR] " ++ e)
fppl = projectFilePathPrintLength (contextProj ctx)
case contextExecMode ctx of
Check -> putStrLn ((machineReadableInfoFromXObj fppl xobj) ++ " " ++ msg)
_ -> putStrLnWithColor Red msg
throw CancelEvaluationException
ListOfCallbacks callbacks -> foldM (\ctx' cb -> callCallbackWithArgs ctx' cb []) ctx callbacks
reportExecutionError :: Context -> String -> IO Context
reportExecutionError ctx errorMessage =
case contextExecMode ctx of
Check ->
do putStrLn errorMessage
return ctx
_ ->
do putStrLnWithColor Red errorMessage
throw CancelEvaluationException
-- | Call a CommandCallback.
callCallbackWithArgs :: Context -> CommandCallback -> [XObj] -> IO Context
callCallbackWithArgs ctx callback args =
do (ret, newCtx) <- runStateT (callback args) ctx
case ret of
Left err -> throw (EvalException err)
Right _ -> return newCtx
-- | Convert an XObj to a ReplCommand so that it can be executed dynamically.
-- | TODO: Does this function need the Context?
objToCommand :: Context -> XObj -> IO ReplCommand
objToCommand ctx (XObj (Sym (SymPath [] (':' : text)) _) _ _) =
return (ListOfCallbacks (mapMaybe charToCommand text))
objToCommand ctx xobj =
return (ReplEval xobj)
-- | Generate commands from shortcut characters (i.e. 'b' = build)
charToCommand :: Char -> Maybe CommandCallback
charToCommand 'x' = Just commandRunExe
charToCommand 'r' = Just commandReload
charToCommand 'b' = Just commandBuild
charToCommand 'c' = Just commandCat
charToCommand 'e' = Just commandListBindings
charToCommand 'h' = Just commandHelp
charToCommand 'p' = Just commandProject
charToCommand 'q' = Just commandQuit
charToCommand _ = Just (\_ -> return dynamicNil)
-- | Decides what to do when the evaluation fails for some reason.
catcher :: Context -> CarpException -> IO Context
catcher ctx exception =
case exception of
(ShellOutException message returnCode) ->
do putStrLnWithColor Red ("[RUNTIME ERROR] " ++ message)
stop returnCode
CancelEvaluationException ->
stop 1
EvalException evalError ->
do putStrLnWithColor Red ("[EVAL ERROR] " ++ show evalError)
stop 1
where stop returnCode =
case contextExecMode ctx of
Repl -> return ctx
Build -> exitWith (ExitFailure returnCode)
Install _ -> exitWith (ExitFailure returnCode)
BuildAndRun -> exitWith (ExitFailure returnCode)
Check -> exitWith ExitSuccess
existingMeta :: Env -> XObj -> MetaData
existingMeta globalEnv xobj =
case lookupInEnv (getPath xobj) globalEnv of
Just (_, Binder meta _) -> meta
Nothing -> emptyMeta
-- | Sort different kinds of definitions into the globalEnv or the typeEnv.
define :: Bool -> Context -> XObj -> IO Context
define hidden ctx@(Context globalEnv typeEnv _ proj _ _) annXObj =
let previousType =
case lookupInEnv (getPath annXObj) globalEnv of
Just (_, Binder _ found) -> ty found
Nothing -> Nothing
previousMeta = existingMeta globalEnv annXObj
adjustedMeta = if hidden
then previousMeta { getMeta = Map.insert "hidden" trueXObj (getMeta previousMeta) }
else previousMeta
in case annXObj of
XObj (Lst (XObj (Defalias _) _ _ : _)) _ _ ->
--putStrLnWithColor Yellow (show (getPath annXObj) ++ " : " ++ show annXObj)
return (ctx { contextTypeEnv = TypeEnv (envInsertAt (getTypeEnv typeEnv) (getPath annXObj) (Binder adjustedMeta annXObj)) })
XObj (Lst (XObj (Typ _) _ _ : _)) _ _ ->
return (ctx { contextTypeEnv = TypeEnv (envInsertAt (getTypeEnv typeEnv) (getPath annXObj) (Binder adjustedMeta annXObj)) })
_ ->
do case Map.lookup "sig" (getMeta adjustedMeta) of
Just foundSignature ->
do let Just sigTy = xobjToTy foundSignature
when (not (areUnifiable (forceTy annXObj) sigTy)) $
throw $ EvalException (EvalError ("Definition at " ++ prettyInfoFromXObj annXObj ++ " does not match 'sig' annotation " ++
show sigTy ++ ", actual type is " ++ show (forceTy annXObj)))
Nothing ->
return ()
--putStrLnWithColor Blue (show (getPath annXObj) ++ " : " ++ showMaybeTy (ty annXObj) ++ (if hidden then " [HIDDEN]" else ""))
when (projectEchoC proj) $
putStrLn (toC All annXObj)
case previousType of
Just previousTypeUnwrapped ->
when (not (areUnifiable (forceTy annXObj) previousTypeUnwrapped)) $
do putStrWithColor Blue ("[WARNING] Definition at " ++ prettyInfoFromXObj annXObj ++ " changed type of '" ++ show (getPath annXObj) ++
"' from " ++ show previousTypeUnwrapped ++ " to " ++ show (forceTy annXObj))
putStrLnWithColor White "" -- To restore color for sure.
Nothing -> return ()
case registerDefnOrDefInInterfaceIfNeeded ctx annXObj of
Left err ->
do case contextExecMode ctx of
Check -> let fppl = projectFilePathPrintLength (contextProj ctx)
in putStrLn ((machineReadableInfoFromXObj fppl annXObj) ++ " " ++ err)
_ -> putStrLnWithColor Red err
return ctx
Right ctx' ->
return (ctx' { contextGlobalEnv = envInsertAt globalEnv (getPath annXObj) (Binder adjustedMeta annXObj) })
-- | Ensure that a 'def' / 'defn' has registered with an interface (if they share the same name).
registerDefnOrDefInInterfaceIfNeeded :: Context -> XObj -> Either String Context
registerDefnOrDefInInterfaceIfNeeded ctx xobj =
case xobj of
XObj (Lst [XObj Defn _ _, XObj (Sym path _) _ _, _, _]) _ (Just t) ->
-- This is a function, does it belong to an interface?
registerInInterfaceIfNeeded ctx path t
XObj (Lst [XObj Def _ _, XObj (Sym path _) _ _, _]) _ (Just t) ->
-- Global variables can also be part of an interface
registerInInterfaceIfNeeded ctx path t
_ ->
return ctx
-- | Registers a definition with an interface, if it isn't already registerd.
registerInInterfaceIfNeeded :: Context -> SymPath -> Ty -> Either String Context
registerInInterfaceIfNeeded ctx path@(SymPath _ name) definitionSignature =
let typeEnv = (getTypeEnv (contextTypeEnv ctx))
in case lookupInEnv (SymPath [] name) typeEnv of
Just (_, Binder _ (XObj (Lst [XObj (Interface interfaceSignature paths) ii it, isym]) i t)) ->
if areUnifiable interfaceSignature definitionSignature
then let updatedInterface = XObj (Lst [XObj (Interface interfaceSignature (addIfNotPresent path paths)) ii it, isym]) i t
in return $ ctx { contextTypeEnv = TypeEnv (extendEnv typeEnv name updatedInterface) }
else Left ("[INTERFACE ERROR] " ++ show path ++ " : " ++ show definitionSignature ++
" doesn't match the interface signature " ++ show interfaceSignature)
Just (_, Binder _ x) ->
error ("A non-interface named '" ++ name ++ "' was found in the type environment: " ++ show x)
Nothing ->
return ctx
-- | SPECIAL FORM COMMANDS (needs to get access to unevaluated arguments, which makes them "special forms" in Lisp lingo)
specialCommandDefine :: XObj -> StateT Context IO (Either EvalError XObj)
specialCommandDefine xobj =
do ctx <- get
let pathStrings = contextPath ctx
globalEnv = contextGlobalEnv ctx
typeEnv = contextTypeEnv ctx
innerEnv = getEnv globalEnv pathStrings
expansionResult <- expandAll eval globalEnv xobj
ctxAfterExpansion <- get
case expansionResult of
Left err -> return (Left (EvalError (show err)))
Right expanded ->
let xobjFullPath = setFullyQualifiedDefn expanded (SymPath pathStrings (getName xobj))
xobjFullSymbols = setFullyQualifiedSymbols typeEnv globalEnv innerEnv xobjFullPath
in case annotate typeEnv globalEnv xobjFullSymbols of
Left err ->
case contextExecMode ctx of
Check ->
let fppl = projectFilePathPrintLength (contextProj ctx)
in return (Left (EvalError (joinWith "\n" (machineReadableErrorStrings fppl err))))
_ ->
return (Left (EvalError (show err)))
Right (annXObj, annDeps) ->
do ctxWithDeps <- liftIO $ foldM (define True) ctxAfterExpansion annDeps
ctxWithDef <- liftIO $ define False ctxWithDeps annXObj
put ctxWithDef
return dynamicNil
specialCommandRegisterType :: String -> [XObj] -> StateT Context IO (Either EvalError XObj)
specialCommandRegisterType typeName rest =
do ctx <- get
let pathStrings = contextPath ctx
globalEnv = contextGlobalEnv ctx
typeEnv = contextTypeEnv ctx
innerEnv = getEnv globalEnv pathStrings
path = SymPath pathStrings typeName
typeDefinition = XObj (Lst [XObj ExternalType Nothing Nothing, XObj (Sym path Symbol) Nothing Nothing]) Nothing (Just TypeTy)
i = Nothing
preExistingModule = case lookupInEnv (SymPath pathStrings typeName) globalEnv of
Just (_, Binder _ (XObj (Mod found) _ _)) -> Just found
_ -> Nothing
case rest of
[] ->
do put (ctx { contextTypeEnv = TypeEnv (extendEnv (getTypeEnv typeEnv) typeName typeDefinition) })
return dynamicNil
members ->
case bindingsForRegisteredType typeEnv globalEnv pathStrings typeName members i preExistingModule of
Left errorMessage ->
return (Left (EvalError (show errorMessage)))
Right (typeModuleName, typeModuleXObj, deps) ->
let ctx' = (ctx { contextGlobalEnv = envInsertAt globalEnv (SymPath pathStrings typeModuleName) (Binder emptyMeta typeModuleXObj)
, contextTypeEnv = TypeEnv (extendEnv (getTypeEnv typeEnv) typeName typeDefinition)
})
in do contextWithDefs <- liftIO $ foldM (define True) ctx' deps
put contextWithDefs
return dynamicNil
specialCommandDeftype :: XObj -> [XObj] -> StateT Context IO (Either EvalError XObj)
specialCommandDeftype nameXObj@(XObj (Sym (SymPath _ typeName) _) _ _) rest =
deftypeInternal nameXObj typeName [] rest
specialCommandDeftype (XObj (Lst (nameXObj@(XObj (Sym (SymPath _ typeName) _) _ _) : typeVariables)) _ _) rest =
deftypeInternal nameXObj typeName typeVariables rest
deftypeInternal :: XObj -> String -> [XObj] -> [XObj] -> StateT Context IO (Either EvalError XObj)
deftypeInternal nameXObj typeName typeVariableXObjs rest =
do ctx <- get
let pathStrings = contextPath ctx
env = contextGlobalEnv ctx
typeEnv = contextTypeEnv ctx
typeVariables = sequence (map xobjToTy typeVariableXObjs)
preExistingModule = case lookupInEnv (SymPath pathStrings typeName) env of
Just (_, Binder _ (XObj (Mod found) _ _)) -> Just found
_ -> Nothing
case (nameXObj, typeVariables) of
(XObj (Sym (SymPath _ typeName) _) i _, Just okTypeVariables) ->
case moduleForDeftype typeEnv env pathStrings typeName okTypeVariables rest i preExistingModule of
Right (typeModuleName, typeModuleXObj, deps) ->
let structTy = (StructTy typeName okTypeVariables)
typeDefinition =
-- NOTE: The type binding is needed to emit the type definition and all the member functions of the type.
XObj (Lst (XObj (Typ structTy) Nothing Nothing :
XObj (Sym (SymPath pathStrings typeName) Symbol) Nothing Nothing :
rest)
) i (Just TypeTy)
ctx' = (ctx { contextGlobalEnv = envInsertAt env (SymPath pathStrings typeModuleName) (Binder emptyMeta typeModuleXObj)
, contextTypeEnv = TypeEnv (extendEnv (getTypeEnv typeEnv) typeName typeDefinition)
})
in do ctxWithDeps <- liftIO (foldM (define True) ctx' deps)
let ctxWithInterfaceRegistrations =
foldM (\context (path, sig) -> registerInInterfaceIfNeeded context path sig) ctxWithDeps
[((SymPath (pathStrings ++ [typeModuleName]) "str"), FuncTy [(RefTy structTy)] StringTy)
,((SymPath (pathStrings ++ [typeModuleName]) "copy"), FuncTy [RefTy structTy] structTy)]
case ctxWithInterfaceRegistrations of
Left err -> liftIO (putStrLnWithColor Red err)
Right ok -> put ok
return dynamicNil
Left errorMessage ->
return (Left (EvalError ("Invalid type definition for '" ++ pretty nameXObj ++ "'. " ++ errorMessage)))
(_, Nothing) ->
return (Left (EvalError ("Invalid type variables for type definition: " ++ pretty nameXObj)))
_ ->
return (Left (EvalError ("Invalid name for type definition: " ++ pretty nameXObj)))
specialCommandRegister :: String -> XObj -> Maybe String -> StateT Context IO (Either EvalError XObj)
specialCommandRegister name typeXObj overrideName =
do ctx <- get
let pathStrings = contextPath ctx
globalEnv = contextGlobalEnv ctx
case xobjToTy typeXObj of
Just t -> let path = SymPath pathStrings name
registration = XObj (Lst [XObj (External overrideName) Nothing Nothing,
XObj (Sym path Symbol) Nothing Nothing])
(info typeXObj) (Just t)
meta = existingMeta globalEnv registration
env' = envInsertAt globalEnv path (Binder meta registration)
in case registerInInterfaceIfNeeded ctx path t of
Left err ->
let prefix = case contextExecMode ctx of
Check -> let fppl = projectFilePathPrintLength (contextProj ctx)
in machineReadableInfoFromXObj fppl typeXObj ++ " "
_ -> ""
in return (Left (EvalError (prefix ++ err)))
Right ctx' ->
do put (ctx' { contextGlobalEnv = env' })
return dynamicNil
Nothing ->
return (Left (EvalError ("Can't understand type when registering '" ++ name ++ "'")))
specialCommandDefinterface :: XObj -> XObj -> StateT Context IO (Either EvalError XObj)
specialCommandDefinterface nameXObj@(XObj (Sym path@(SymPath [] name) _) _ _) typeXObj =
do ctx <- get
let env = contextGlobalEnv ctx
typeEnv = getTypeEnv (contextTypeEnv ctx)
case xobjToTy typeXObj of
Just t ->
case lookupInEnv path typeEnv of
Just (_, Binder _ (XObj (Lst (XObj (Interface foundType _) _ _ : _)) _ _)) ->
-- The interface already exists, so it will be left as-is.
if foundType == t
then return dynamicNil
else liftIO $ do putStrLn ("[FORBIDDEN] Tried to change the type of interface '" ++ show path ++ "' from " ++ show foundType ++ " to " ++ show t)
return dynamicNil
Nothing ->
let interface = defineInterface name t [] (info nameXObj)
typeEnv' = TypeEnv (envInsertAt typeEnv (SymPath [] name) (Binder emptyMeta interface))
in do put (ctx { contextTypeEnv = typeEnv' })
return dynamicNil
Nothing ->
return (Left (EvalError ("Invalid type for interface '" ++ name ++ "': " ++
pretty typeXObj ++ " at " ++ prettyInfoFromXObj typeXObj ++ ".")))
specialCommandDefdynamic :: String -> XObj -> XObj -> StateT Context IO (Either EvalError XObj)
specialCommandDefdynamic name params body =
do ctx <- get
let pathStrings = contextPath ctx
globalEnv = contextGlobalEnv ctx
path = SymPath pathStrings name
dynamic = XObj (Lst [XObj Dynamic Nothing Nothing, XObj (Sym path Symbol) Nothing Nothing, params, body]) (info body) (Just DynamicTy)
meta = existingMeta globalEnv dynamic
put (ctx { contextGlobalEnv = envInsertAt globalEnv path (Binder meta dynamic) })
return dynamicNil
specialCommandDefmacro :: String -> XObj -> XObj -> StateT Context IO (Either EvalError XObj)
specialCommandDefmacro name params body =
do ctx <- get
let pathStrings = contextPath ctx
globalEnv = contextGlobalEnv ctx
path = SymPath pathStrings name
macro = XObj (Lst [XObj Macro Nothing Nothing, XObj (Sym path Symbol) Nothing Nothing, params, body]) (info body) (Just MacroTy)
meta = existingMeta globalEnv macro
put (ctx { contextGlobalEnv = envInsertAt globalEnv path (Binder meta macro) })
return dynamicNil
specialCommandDefmodule :: XObj -> String -> [XObj] -> StateT Context IO (Either EvalError XObj)
specialCommandDefmodule xobj moduleName innerExpressions =
do ctx <- get
let pathStrings = contextPath ctx
env = contextGlobalEnv ctx
typeEnv = contextTypeEnv ctx
lastInput = contextLastInput ctx
execMode = contextExecMode ctx
proj = contextProj ctx
result <- case lookupInEnv (SymPath pathStrings moduleName) env of
Just (_, Binder _ (XObj (Mod _) _ _)) ->
do let ctx' = (Context env typeEnv (pathStrings ++ [moduleName]) proj lastInput execMode) -- use { = } syntax instead
ctxAfterModuleAdditions <- liftIO $ foldM folder ctx' innerExpressions
put (popModulePath ctxAfterModuleAdditions)
return dynamicNil -- TODO: propagate errors...
Just _ ->
return (Left (EvalError ("Can't redefine '" ++ moduleName ++ "' as module.")))
Nothing ->
do let parentEnv = getEnv env pathStrings
innerEnv = Env (Map.fromList []) (Just parentEnv) (Just moduleName) [] ExternalEnv 0
newModule = XObj (Mod innerEnv) (info xobj) (Just ModuleTy)
globalEnvWithModuleAdded = envInsertAt env (SymPath pathStrings moduleName) (Binder emptyMeta newModule)
ctx' = Context globalEnvWithModuleAdded typeEnv (pathStrings ++ [moduleName]) proj lastInput execMode -- TODO: also change
ctxAfterModuleDef <- liftIO $ foldM folder ctx' innerExpressions
put (popModulePath ctxAfterModuleDef)
return dynamicNil
case result of
Left err -> return (Left err)
Right _ -> return dynamicNil
specialCommandInfo :: XObj -> StateT Context IO (Either EvalError XObj)
specialCommandInfo target@(XObj (Sym path@(SymPath _ name) _) _ _) =
do ctx <- get
let env = contextGlobalEnv ctx
typeEnv = contextTypeEnv ctx
proj = contextProj ctx
execMode = contextExecMode ctx
printer allowLookupInALL binderPair itIsAnErrorNotToFindIt =
case binderPair of
Just (_, binder@(Binder _ x@(XObj _ (Just i) _))) ->
do putStrLnWithColor White (show binder ++ "\nDefined at " ++ prettyInfo i)
when (projectPrintTypedAST proj) $ putStrLnWithColor Yellow (prettyTyped x)
return ()
Just (_, binder@(Binder _ x)) ->
do putStrLnWithColor White (show binder)
when (projectPrintTypedAST proj) $ putStrLnWithColor Yellow (prettyTyped x)
return ()
Nothing ->
if allowLookupInALL
then case multiLookupALL name env of
[] ->
do when itIsAnErrorNotToFindIt $
putStrLn $
case execMode of
Check -> let fppl = projectFilePathPrintLength (contextProj ctx)
in machineReadableInfoFromXObj fppl target ++ (" Can't find '" ++ show path ++ "'")
_ -> strWithColor Red ("Can't find '" ++ show path ++ "'")
return ()
binders ->
do mapM_ (\(env, binder@(Binder _ (XObj _ i _))) ->
case i of
Just i' -> putStrLnWithColor White (show binder ++ " Defined at " ++ prettyInfo i')
Nothing -> putStrLnWithColor White (show binder))
binders
return ()
else return ()
case path of
SymPath [] _ ->
-- First look in the type env, then in the global env:
do case lookupInEnv path (getTypeEnv typeEnv) of
Nothing -> liftIO (printer True (lookupInEnv path env) True)
found -> do liftIO (printer True found True) -- this will print the interface itself
liftIO (printer True (lookupInEnv path env) False) -- this will print the locations of the implementers of the interface
return dynamicNil
qualifiedPath ->
do case lookupInEnv path env of
Nothing -> notFound execMode target path
found -> do liftIO (printer False found True)
return dynamicNil
specialCommandType :: XObj -> StateT Context IO (Either EvalError XObj)
specialCommandType target =
do ctx <- get
let env = contextGlobalEnv ctx
execMode = contextExecMode ctx
case target of
XObj (Sym path@(SymPath [] name) _) _ _ ->
case lookupInEnv path env of
Just (_, binder) ->
found binder
Nothing ->
case multiLookupALL name env of
[] ->
notFound execMode target path
binders ->
liftIO $ do mapM_ (\(env, binder) -> putStrLnWithColor White (show binder)) binders
return dynamicNil
XObj (Sym qualifiedPath _) _ _ ->
case lookupInEnv qualifiedPath env of
Just (_, binder) ->
found binder
Nothing ->
notFound execMode target qualifiedPath
_ ->
liftIO $ do putStrLnWithColor Red ("Can't get the type of non-symbol: " ++ pretty target)
return dynamicNil
specialCommandMembers :: XObj -> StateT Context IO (Either EvalError XObj)
specialCommandMembers target =
do ctx <- get
let typeEnv = contextTypeEnv ctx
case target of
XObj (Sym path@(SymPath [] name) _) _ _ ->
case lookupInEnv path (getTypeEnv typeEnv) of
Just (_, Binder _ (XObj (Lst (XObj (Typ structTy) Nothing Nothing :
XObj (Sym (SymPath pathStrings typeName) Symbol) Nothing Nothing :
XObj (Arr members) _ _ :
[]))
_ _))
->
return (Right (XObj (Arr (map (\(a, b) -> (XObj (Lst [a, b]) Nothing Nothing)) (pairwise members))) Nothing Nothing))
_ ->
return (Left (EvalError ("Can't find a struct type named '" ++ name ++ "' in type environment.")))
_ ->
return (Left (EvalError ("Can't get the members of non-symbol: " ++ pretty target)))
specialCommandUse :: XObj -> SymPath -> StateT Context IO (Either EvalError XObj)
specialCommandUse xobj path =
do ctx <- get
let pathStrings = contextPath ctx
env = contextGlobalEnv ctx
e = getEnv env pathStrings
useThese = envUseModules e
e' = if path `elem` useThese then e else e { envUseModules = path : useThese }
innerEnv = getEnv env pathStrings -- Duplication of e?
case lookupInEnv path innerEnv of
Just (_, Binder _ _) ->
do put $ ctx { contextGlobalEnv = envReplaceEnvAt env pathStrings e' }
return dynamicNil
Nothing ->
return (Left (EvalError ("Can't find a module named '" ++ show path ++ "' at " ++ prettyInfoFromXObj xobj ++ ".")))
specialCommandWith :: XObj -> SymPath -> [XObj] -> StateT Context IO (Either EvalError XObj)
specialCommandWith xobj path forms =
do ctx <- get
let pathStrings = contextPath ctx
env = contextGlobalEnv ctx
typeEnv = contextTypeEnv ctx
useThese = envUseModules env
env' = if path `elem` useThese then env else env { envUseModules = path : useThese }
ctx' = ctx { contextGlobalEnv = env' }
ctxAfter <- liftIO $ foldM folder ctx' forms
let envAfter = contextGlobalEnv ctxAfter
ctxAfter' = ctx { contextGlobalEnv = envAfter { envUseModules = useThese } } -- This will undo ALL use:s made inside the 'with'.
put ctxAfter'
return dynamicNil
-- | Set meta data for a Binder
specialCommandMetaSet :: SymPath -> String -> XObj -> StateT Context IO (Either EvalError XObj)
specialCommandMetaSet path key value =
do ctx <- get
let pathStrings = contextPath ctx
globalEnv = contextGlobalEnv ctx
case lookupInEnv (consPath pathStrings path) globalEnv of
Just (_, binder@(Binder _ xobj)) ->
-- | Set meta on existing binder
setMetaOn ctx binder
Nothing ->
case path of
-- | If the path is unqualified, create a binder and set the meta on that one. This enables docstrings before function exists.
(SymPath [] name) ->
setMetaOn ctx (Binder emptyMeta (XObj (Lst [XObj (External Nothing) Nothing Nothing,
XObj (Sym (SymPath pathStrings name) Symbol) Nothing Nothing])
(Just dummyInfo)
(Just (VarTy "a"))))
(SymPath _ _) ->
return (Left (EvalError ("Special command 'meta-set!' failed, can't find '" ++ show path ++ "'.")))
where
setMetaOn :: Context -> Binder -> StateT Context IO (Either EvalError XObj)
setMetaOn ctx binder@(Binder metaData xobj) =
do let globalEnv = contextGlobalEnv ctx
newMetaData = MetaData (Map.insert key value (getMeta metaData))
xobjPath = getPath xobj
newBinder = binder { binderMeta = newMetaData }
newEnv = envInsertAt globalEnv xobjPath newBinder
--liftIO (putStrLn ("Added meta data on " ++ show xobjPath ++ ", '" ++ key ++ "' = " ++ pretty value))
put (ctx { contextGlobalEnv = newEnv })
return dynamicNil
-- | Get meta data for a Binder
specialCommandMetaGet :: SymPath -> String -> StateT Context IO (Either EvalError XObj)
specialCommandMetaGet path key =
do ctx <- get
let pathStrings = contextPath ctx
globalEnv = contextGlobalEnv ctx
case lookupInEnv (consPath pathStrings path) globalEnv of
Just (_, Binder metaData _) ->
case Map.lookup key (getMeta metaData) of
Just foundValue ->
return (Right foundValue)
Nothing ->
return dynamicNil
Nothing ->
return (Left (EvalError ("Special command 'meta' failed, can't find '" ++ show path ++ "'.")))
-- | "NORMAL" COMMANDS (just like the ones in Command.hs, but these need access to 'eval', etc.)
-- | Command for loading a Carp file.
commandLoad :: CommandCallback
commandLoad [xobj@(XObj (Str path) _ _)] =
do ctx <- get
home <- liftIO $ getHomeDirectory
let proj = contextProj ctx
libDir = home ++ "/" ++ projectLibDir proj
carpDir = projectCarpDir proj
fullSearchPaths =
path :
("./" ++ path) : -- the path from the current directory
map (++ "/" ++ path) (projectCarpSearchPaths proj) ++ -- user defined search paths
[carpDir ++ "/core/" ++ path] ++
[libDir ++ "/" ++ path]
-- putStrLn ("Full search paths = " ++ show fullSearchPaths)
existingPaths <- liftIO (filterM doesFileExist fullSearchPaths)
case existingPaths of
[] ->
if elem '@' path
then tryInstall path
else return $ invalidPath ctx path
firstPathFound : _ ->
do canonicalPath <- liftIO (canonicalizePath firstPathFound)
let alreadyLoaded = projectAlreadyLoaded proj
if canonicalPath `elem` alreadyLoaded
then do --liftIO (putStrLn ("Ignoring 'load' command for already loaded file '" ++ canonicalPath ++ "'"))
return ()
else do contents <- liftIO $ do --putStrLn ("Will load '" ++ canonicalPath ++ "'")
handle <- SysIO.openFile canonicalPath SysIO.ReadMode
SysIO.hSetEncoding handle SysIO.utf8
SysIO.hGetContents handle
let files = projectFiles proj
files' = if canonicalPath `elem` files
then files
else files ++ [canonicalPath]
proj' = proj { projectFiles = files', projectAlreadyLoaded = canonicalPath : alreadyLoaded }
newCtx <- liftIO $ executeString True (ctx { contextProj = proj' }) contents canonicalPath
put newCtx
return dynamicNil
where
fppl ctx =
projectFilePathPrintLength (contextProj ctx)
invalidPath ctx path =
Left $ EvalError $
(case contextExecMode ctx of
Check ->
(machineReadableInfoFromXObj (fppl ctx) xobj) ++ " Invalid path: '" ++ path ++ "'"
_ -> "Invalid path: '" ++ path ++ "'") ++
"\n\nIf you tried loading an external package, try appending a version string (like `@master`)."
invalidPathWith ctx path stderr =
Left $ EvalError $
(case contextExecMode ctx of
Check ->
(machineReadableInfoFromXObj (fppl ctx) xobj) ++ " Invalid path: '" ++ path ++ "'"
_ -> "Invalid path: '" ++ path ++ "'") ++
"\n\nTried interpreting statement as git import, but got: " ++ stderr
tryInstall path =
let split = splitOn "@" path
in tryInstallWithCheckout (joinWith "@" (init split)) (last split)
fromURL url =
let split = splitOn "/" url
fst = split !! 0
in if elem fst ["https:", "http:"]
then joinWith "/" (tail split)
else
if elem '@' fst
then joinWith "/" (joinWith "@" (tail (splitOn "@" fst)) : tail split)
else url
tryInstallWithCheckout path toCheckout = do
ctx <- get
home <- liftIO $ getHomeDirectory
let proj = contextProj ctx
let libDir = home ++ "/" ++ projectLibDir proj
let fpath = libDir ++ "/" ++ fromURL path ++ "/" ++ toCheckout
cur <- liftIO $ getCurrentDirectory
_ <- liftIO $ createDirectoryIfMissing True fpath
_ <- liftIO $ setCurrentDirectory fpath
_ <- liftIO $ readProcessWithExitCode "git" ["init"] ""
_ <- liftIO $ readProcessWithExitCode "git" ["remote", "add", "origin", path] ""
(x0, _, stderr0) <- liftIO $ readProcessWithExitCode "git" ["fetch"] ""
case x0 of
ExitFailure _ -> do
_ <- liftIO $ setCurrentDirectory cur
return $ invalidPathWith ctx path stderr0
ExitSuccess -> do
(x1, _, stderr1) <- liftIO $ readProcessWithExitCode "git" ["checkout", toCheckout] ""
_ <- liftIO $ setCurrentDirectory cur
case x1 of
ExitSuccess ->
let fName = last (splitOn "/" path)
realName' = if isSuffixOf ".git" fName
then take (length fName - 4) fName
else fName
realName = if isSuffixOf ".carp" realName'
then realName'
else realName' ++ ".carp"
fileToLoad = fpath ++ "/" ++ realName
mainToLoad = fpath ++ "/main.carp"
in do
res <- commandLoad [XObj (Str fileToLoad) Nothing Nothing]
case res of
ret@(Right _) -> return ret
Left _ -> commandLoad [XObj (Str mainToLoad) Nothing Nothing]
ExitFailure _ -> do
return $ invalidPathWith ctx path stderr1
commandLoad [x] =
return $ Left (EvalError ("Invalid args to 'load' command: " ++ pretty x))
-- | Load several files in order.
loadFiles :: Context -> [FilePath] -> IO Context
loadFiles ctxStart filesToLoad = foldM folder ctxStart filesToLoad
where folder :: Context -> FilePath -> IO Context
folder ctx file =
callCallbackWithArgs ctx commandLoad [XObj (Str file) Nothing Nothing]
-- | Command for reloading all files in the project (= the files that has been loaded before).
commandReload :: CommandCallback
commandReload args =
do ctx <- get
let paths = projectFiles (contextProj ctx)
f :: Context -> FilePath -> IO Context
f context filepath = do let proj = contextProj context
alreadyLoaded = projectAlreadyLoaded proj
if filepath `elem` alreadyLoaded
then do --liftIO (putStrLn ("Ignoring reload for already loaded file '" ++ filepath ++ "'"))
return context
else do --liftIO (putStrLn ("Reloading '" ++ filepath ++ "'"))
contents <- readFile filepath
let proj' = proj { projectAlreadyLoaded = filepath : alreadyLoaded }
executeString False (context { contextProj = proj' }) contents filepath
newCtx <- liftIO (foldM f ctx paths)
put newCtx
return dynamicNil
-- | Command for expanding a form and its macros.
commandExpand :: CommandCallback
commandExpand [xobj] =
do ctx <- get
result <- expandAll eval (contextGlobalEnv ctx) xobj
case result of
Left e ->
return (Left e)
Right expanded ->
liftIO $ do putStrLnWithColor Yellow (pretty expanded)
return dynamicNil
-- | This function will show the resulting C code from an expression.
-- | i.e. (Int.+ 2 3) => "_0 = 2 + 3"
commandC :: CommandCallback
commandC [xobj] =
do ctx <- get
let globalEnv = contextGlobalEnv ctx
typeEnv = contextTypeEnv ctx
result <- expandAll eval globalEnv xobj
case result of
Left err -> return (Left (EvalError (show err)))
Right expanded ->
case annotate typeEnv globalEnv (setFullyQualifiedSymbols typeEnv globalEnv globalEnv expanded) of
Left err -> return (Left (EvalError (show err)))
Right (annXObj, annDeps) ->
do liftIO (printC annXObj)
liftIO (mapM printC annDeps)
return dynamicNil
-- | Helper function for commandC
printC :: XObj -> IO ()
printC xobj =
case checkForUnresolvedSymbols xobj of
Left e ->
putStrLnWithColor Red (show e ++ ", can't print resulting code.\n")
Right _ ->
putStrLnWithColor Green (toC All xobj)
|
eriksvedang/Carp
|
src/Eval.hs
|
mpl-2.0
| 57,414 | 3 | 30 | 19,875 | 16,401 | 8,042 | 8,359 | 981 | 83 |
{-# 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.AndroidEnterprise.Users.SetAvailableProductSet
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Modifies the set of products that a user is entitled to access (referred
-- to as *whitelisted* products). Only products that are approved or
-- products that were previously approved (products with revoked approval)
-- can be whitelisted.
--
-- /See:/ <https://developers.google.com/android/work/play/emm-api Google Play EMM API Reference> for @androidenterprise.users.setAvailableProductSet@.
module Network.Google.Resource.AndroidEnterprise.Users.SetAvailableProductSet
(
-- * REST Resource
UsersSetAvailableProductSetResource
-- * Creating a Request
, usersSetAvailableProductSet
, UsersSetAvailableProductSet
-- * Request Lenses
, usapsXgafv
, usapsUploadProtocol
, usapsEnterpriseId
, usapsAccessToken
, usapsUploadType
, usapsPayload
, usapsUserId
, usapsCallback
) where
import Network.Google.AndroidEnterprise.Types
import Network.Google.Prelude
-- | A resource alias for @androidenterprise.users.setAvailableProductSet@ method which the
-- 'UsersSetAvailableProductSet' request conforms to.
type UsersSetAvailableProductSetResource =
"androidenterprise" :>
"v1" :>
"enterprises" :>
Capture "enterpriseId" Text :>
"users" :>
Capture "userId" Text :>
"availableProductSet" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] ProductSet :>
Put '[JSON] ProductSet
-- | Modifies the set of products that a user is entitled to access (referred
-- to as *whitelisted* products). Only products that are approved or
-- products that were previously approved (products with revoked approval)
-- can be whitelisted.
--
-- /See:/ 'usersSetAvailableProductSet' smart constructor.
data UsersSetAvailableProductSet =
UsersSetAvailableProductSet'
{ _usapsXgafv :: !(Maybe Xgafv)
, _usapsUploadProtocol :: !(Maybe Text)
, _usapsEnterpriseId :: !Text
, _usapsAccessToken :: !(Maybe Text)
, _usapsUploadType :: !(Maybe Text)
, _usapsPayload :: !ProductSet
, _usapsUserId :: !Text
, _usapsCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'UsersSetAvailableProductSet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'usapsXgafv'
--
-- * 'usapsUploadProtocol'
--
-- * 'usapsEnterpriseId'
--
-- * 'usapsAccessToken'
--
-- * 'usapsUploadType'
--
-- * 'usapsPayload'
--
-- * 'usapsUserId'
--
-- * 'usapsCallback'
usersSetAvailableProductSet
:: Text -- ^ 'usapsEnterpriseId'
-> ProductSet -- ^ 'usapsPayload'
-> Text -- ^ 'usapsUserId'
-> UsersSetAvailableProductSet
usersSetAvailableProductSet pUsapsEnterpriseId_ pUsapsPayload_ pUsapsUserId_ =
UsersSetAvailableProductSet'
{ _usapsXgafv = Nothing
, _usapsUploadProtocol = Nothing
, _usapsEnterpriseId = pUsapsEnterpriseId_
, _usapsAccessToken = Nothing
, _usapsUploadType = Nothing
, _usapsPayload = pUsapsPayload_
, _usapsUserId = pUsapsUserId_
, _usapsCallback = Nothing
}
-- | V1 error format.
usapsXgafv :: Lens' UsersSetAvailableProductSet (Maybe Xgafv)
usapsXgafv
= lens _usapsXgafv (\ s a -> s{_usapsXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
usapsUploadProtocol :: Lens' UsersSetAvailableProductSet (Maybe Text)
usapsUploadProtocol
= lens _usapsUploadProtocol
(\ s a -> s{_usapsUploadProtocol = a})
-- | The ID of the enterprise.
usapsEnterpriseId :: Lens' UsersSetAvailableProductSet Text
usapsEnterpriseId
= lens _usapsEnterpriseId
(\ s a -> s{_usapsEnterpriseId = a})
-- | OAuth access token.
usapsAccessToken :: Lens' UsersSetAvailableProductSet (Maybe Text)
usapsAccessToken
= lens _usapsAccessToken
(\ s a -> s{_usapsAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
usapsUploadType :: Lens' UsersSetAvailableProductSet (Maybe Text)
usapsUploadType
= lens _usapsUploadType
(\ s a -> s{_usapsUploadType = a})
-- | Multipart request metadata.
usapsPayload :: Lens' UsersSetAvailableProductSet ProductSet
usapsPayload
= lens _usapsPayload (\ s a -> s{_usapsPayload = a})
-- | The ID of the user.
usapsUserId :: Lens' UsersSetAvailableProductSet Text
usapsUserId
= lens _usapsUserId (\ s a -> s{_usapsUserId = a})
-- | JSONP
usapsCallback :: Lens' UsersSetAvailableProductSet (Maybe Text)
usapsCallback
= lens _usapsCallback
(\ s a -> s{_usapsCallback = a})
instance GoogleRequest UsersSetAvailableProductSet
where
type Rs UsersSetAvailableProductSet = ProductSet
type Scopes UsersSetAvailableProductSet =
'["https://www.googleapis.com/auth/androidenterprise"]
requestClient UsersSetAvailableProductSet'{..}
= go _usapsEnterpriseId _usapsUserId _usapsXgafv
_usapsUploadProtocol
_usapsAccessToken
_usapsUploadType
_usapsCallback
(Just AltJSON)
_usapsPayload
androidEnterpriseService
where go
= buildClient
(Proxy :: Proxy UsersSetAvailableProductSetResource)
mempty
|
brendanhay/gogol
|
gogol-android-enterprise/gen/Network/Google/Resource/AndroidEnterprise/Users/SetAvailableProductSet.hs
|
mpl-2.0
| 6,402 | 0 | 21 | 1,470 | 871 | 508 | 363 | 131 | 1 |
module Cortex.G23.GrandMonadStack
( LesserMonadStack
, GrandMonadStack
) where
import Control.Monad.State (StateT)
import Control.Monad.Error (ErrorT)
import Cortex.Common.Miranda
type LesserMonadStack = ErrorT String IO
-- State holds Miranda host and port.
type GrandMonadStack = StateT MirandaInfo LesserMonadStack
|
maarons/Cortex
|
G23/GrandMonadStack.hs
|
agpl-3.0
| 334 | 0 | 5 | 51 | 66 | 41 | 25 | 8 | 0 |
--------------------------------------------------------------------------------
-- $Id: SwishCommands.hs,v 1.14 2004/02/11 14:19:36 graham Exp $
--
-- Copyright (c) 2003, G. KLYNE. All rights reserved.
-- See end of this file for licence information.
--------------------------------------------------------------------------------
-- |
-- Module : SwishCommands
-- Copyright : (c) 2003, Graham Klyne
-- License : GPL V2
--
-- Maintainer : Graham Klyne
-- Stability : provisional
-- Portability : H98
--
-- SwishCommands: functions to deal with indivudual Swish command options.
--
--------------------------------------------------------------------------------
module Swish.HaskellRDF.SwishCommands
( swishFormat
, swishInput
, swishOutput
, swishMerge
, swishCompare
, swishGraphDiff
, swishScript
)
where
import Swish.HaskellRDF.SwishMonad
( SwishStateIO, SwishState(..)
, setFormat, setGraph
, resetInfo, resetError, setExitcode
, SwishFormat(..)
, swishError
, reportLine
)
import Swish.HaskellRDF.SwishScript
( parseScriptFromString
)
import Swish.HaskellRDF.GraphPartition
( GraphPartition(..)
, partitionGraph, comparePartitions
, partitionShowP
)
import Swish.HaskellRDF.RDFGraph
( RDFGraph, merge )
import Swish.HaskellRDF.N3Formatter
( formatGraphAsShowS )
import Swish.HaskellRDF.N3Parser
( parseN3fromString )
import Swish.HaskellRDF.GraphClass
( LDGraph(..)
, Label(..)
)
import Swish.HaskellUtils.ErrorM( ErrorM(..) )
import System.IO
( Handle, openFile, IOMode(..)
, hPutStr, hPutStrLn, hClose, hGetContents
, hIsReadable, hIsWritable
, stdin, stdout, stderr
)
import Control.Monad.Trans( MonadTrans(..) )
import Control.Monad.State
( modify, gets
)
import Data.Maybe
( Maybe(..), isJust, fromJust )
import Control.Monad
( when )
import System.Exit
( ExitCode(..) )
import System.IO.Error
------------------------------------------------------------
-- Set file format to supplied value
------------------------------------------------------------
swishFormat :: SwishFormat -> SwishStateIO ()
swishFormat fmt = modify $ setFormat fmt
------------------------------------------------------------
-- Read graph from named file
------------------------------------------------------------
swishInput :: String -> SwishStateIO ()
swishInput fnam =
do { maybegraph <- swishReadGraph fnam
; case maybegraph of
Just g -> modify $ setGraph g
_ -> return ()
}
------------------------------------------------------------
-- Merge graph from named file
------------------------------------------------------------
swishMerge :: String -> SwishStateIO ()
swishMerge fnam =
do { maybegraph <- swishReadGraph fnam
; case maybegraph of
Just g -> modify $ mergeGraph g
_ -> return ()
}
mergeGraph gr state = state { graph = newgr }
where
newgr = merge gr (graph state)
------------------------------------------------------------
-- Compare graph from named file
------------------------------------------------------------
swishCompare :: String -> SwishStateIO ()
swishCompare fnam =
do { maybegraph <- swishReadGraph fnam
; case maybegraph of
Just g -> compareGraph g
_ -> return ()
}
compareGraph :: RDFGraph -> SwishStateIO ()
compareGraph gr =
do { oldgr <- gets graph
; let exitCode = if gr == oldgr then ExitSuccess
else ExitFailure 1
; modify $ setExitcode exitCode
}
------------------------------------------------------------
-- Display graph differences from named file
------------------------------------------------------------
swishGraphDiff :: String -> SwishStateIO ()
swishGraphDiff fnam =
do { maybegraph <- swishReadGraph fnam
; case maybegraph of
Just g -> diffGraph g
_ -> return ()
}
diffGraph :: RDFGraph -> SwishStateIO ()
diffGraph gr =
do { oldgr <- gets graph
; let p1 = partitionGraph (getArcs oldgr)
; let p2 = partitionGraph (getArcs gr)
; let diffs = comparePartitions p1 p2
; maybehandleclose <- swishWriteFile "" -- null filename -> stdout
; case maybehandleclose of
Just (h,c) ->
do { swishOutputDiffs "" h diffs
; if c then lift $ hClose h else return ()
}
_ -> return ()
}
swishOutputDiffs :: (Label lb) =>
String -> Handle
-> [(Maybe (GraphPartition lb),Maybe (GraphPartition lb))]
-> SwishStateIO ()
swishOutputDiffs fnam hnd diffs =
do { lift $ hPutStrLn hnd ("Graph differences: "++show (length diffs))
; sequence_ $ map (swishOutputDiff fnam hnd) (zip [1..] diffs)
}
swishOutputDiff :: (Label lb) =>
String -> Handle
-> (Int,(Maybe (GraphPartition lb),Maybe (GraphPartition lb)))
-> SwishStateIO ()
swishOutputDiff fnam hnd (diffnum,(part1,part2)) =
do { lift $ hPutStrLn hnd ("---- Difference "++show diffnum++" ----")
; lift $ hPutStr hnd "Graph 1:"
; swishOutputPart fnam hnd part1
; lift $ hPutStr hnd "Graph 2:"
; swishOutputPart fnam hnd part2
}
swishOutputPart :: (Label lb) =>
String -> Handle -> Maybe (GraphPartition lb) -> SwishStateIO ()
swishOutputPart fnam hnd part =
do { let out = case part of
Just p -> partitionShowP "\n" p
Nothing -> "\n(No arcs)"
; lift $ hPutStrLn hnd out
}
------------------------------------------------------------
-- Execute script from named file
------------------------------------------------------------
swishScript :: String -> SwishStateIO ()
swishScript fnam =
do { scs <- swishReadScript fnam
; sequence_ (map swishCheckResult scs)
}
swishReadScript :: String -> SwishStateIO [SwishStateIO ()]
swishReadScript fnam =
do { maybefile <- swishOpenFile fnam
; case maybefile of
Just (h,i) ->
do { res <- swishParseScript fnam i
; lift $ hClose h
; return res
}
_ -> return []
}
swishParseScript ::
String -> String -> SwishStateIO [SwishStateIO ()]
swishParseScript fnam inp =
do { let base = if null fnam then Nothing else Just fnam
; let sres = parseScriptFromString base inp
; case sres of
Error err ->
do { swishError ("Script syntax error in file "++fnam++": "++err) 2
; return []
}
Result scs -> return scs
}
swishCheckResult :: SwishStateIO () -> SwishStateIO ()
swishCheckResult swishcommand =
do { swishcommand
; er <- gets errormsg
; when (isJust er) $
do { swishError (fromJust er) 5
; modify $ resetError
}
; ms <- gets infomsg
; when (isJust ms) $
do { reportLine (fromJust ms)
; modify $ resetInfo
}
}
------------------------------------------------------------
-- Output graph to named file
------------------------------------------------------------
swishOutput :: String -> SwishStateIO ()
swishOutput fnam =
do { maybehandleclose <- swishWriteFile fnam
; case maybehandleclose of
Just (h,c) ->
do { swishOutputGraph fnam h
; if c then lift $ hClose h else return ()
}
_ -> return ()
}
swishOutputGraph :: String -> Handle -> SwishStateIO ()
swishOutputGraph fnam hnd =
do { fmt <- gets $ format
; case fmt of
N3 -> swishFormatN3 fnam hnd
_ -> swishError
("Unsupported file format: "++(show fmt)) 4
}
swishFormatN3 :: String -> Handle -> SwishStateIO ()
swishFormatN3 fnam hnd =
do { out <- gets $ formatGraphAsShowS . graph
; lift $ hPutStr hnd (out "")
}
------------------------------------------------------------
-- Common input functions
------------------------------------------------------------
--
-- Keep the logic separate for reading file data and
-- parsing it to an RDF graph value.
swishReadGraph :: String -> SwishStateIO (Maybe RDFGraph)
swishReadGraph fnam =
do { maybefile <- swishOpenFile fnam
; case maybefile of
Just (h,i) ->
do { res <- swishParse fnam i
; lift $ hClose h
; return res
}
_ -> return Nothing
}
-- Open and read file, returning its handle and content, or Nothing
-- WARNING: the handle must not be closed until input is fully evaluated
swishOpenFile :: String -> SwishStateIO (Maybe (Handle,String))
swishOpenFile fnam =
do { (hnd,hop) <- lift $
if null fnam then
return (stdin,True)
else
do { o <- try (openFile fnam ReadMode)
; case o of
Left e -> return (stdin,False)
Right h -> return (h,True)
}
; hrd <- lift $ hIsReadable hnd
; res <- if hop && hrd then
do {
; fc <- lift $ hGetContents hnd
; return $ Just (hnd,fc)
}
else
do { lift $ hClose hnd
; swishError ("Cannot read file: "++fnam) 3
; return Nothing
}
; return res
}
swishParse :: String -> String -> SwishStateIO (Maybe RDFGraph)
swishParse fnam inp =
do { fmt <- gets $ format
; case fmt of
N3 -> swishParseN3 fnam inp
_ ->
do { swishError ("Unsupported file format: "++(show fmt)) 4
; return Nothing
}
}
swishParseN3 :: String -> String -> SwishStateIO (Maybe RDFGraph)
swishParseN3 fnam inp =
do { let pres = parseN3fromString inp
; case pres of
Error err ->
do { swishError ("N3 syntax error in file "++fnam++": "++err) 2
; return Nothing
}
Result gr -> return $ Just gr
}
-- Open file for writing, returning its handle, or Nothing
-- Also returned is a flag indicating whether or not the
-- handled should be closed when writing is done (if writing
-- to standard output, the handle should not be closed as the
-- run-time system should deal with that).
swishWriteFile :: String -> SwishStateIO (Maybe (Handle,Bool))
swishWriteFile fnam =
do { (hnd,hop,cls) <- lift $
if null fnam then
return (stdout,True,False)
else
do { o <- try (openFile fnam WriteMode)
; case o of
Left e -> return (stderr,False,False)
Right h -> return (h,True,True)
}
; hwt <- lift $ hIsWritable hnd
; if hop && hwt then
return $ Just (hnd,cls)
else
do { if cls then lift $ hClose hnd else return ()
; swishError ("Cannot write file: "++fnam) 3
; return Nothing
}
}
--------------------------------------------------------------------------------
--
-- Copyright (c) 2003, G. KLYNE. All rights reserved.
--
-- This file is part of Swish.
--
-- Swish 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.
--
-- Swish 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 Swish; if not, write to:
-- The Free Software Foundation, Inc.,
-- 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
--
--------------------------------------------------------------------------------
-- $Source: /file/cvsdev/HaskellRDF/SwishCommands.hs,v $
-- $Author: graham $
-- $Revision: 1.14 $
-- $Log: SwishCommands.hs,v $
-- Revision 1.14 2004/02/11 14:19:36 graham
-- Add graph-difference option to Swish
--
-- Revision 1.13 2003/12/11 19:11:07 graham
-- Script processor passes all initial tests.
--
-- Revision 1.12 2003/12/05 02:31:32 graham
-- Script parsing complete.
-- Some Swish script functions run successfully.
-- Command execution to be completed.
--
-- Revision 1.11 2003/12/04 02:53:27 graham
-- More changes to LookupMap functions.
-- SwishScript logic part complete, type-checks OK.
--
-- Revision 1.10 2003/12/01 18:51:38 graham
-- Described syntax for Swish script.
-- Created Swish scripting test data.
-- Edited export/import lists in Swish main program modules.
--
-- Revision 1.9 2003/09/24 18:50:53 graham
-- Revised module format to be Haddock compatible.
--
-- Revision 1.8 2003/06/03 19:24:13 graham
-- Updated all source modules to cite GNU Public Licence
--
-- Revision 1.7 2003/05/29 12:39:49 graham
-- Improved error handling for stand-alone swish program
--
-- Revision 1.6 2003/05/29 10:49:08 graham
-- Added and tested merge option (-m) for Swish program
--
-- Revision 1.5 2003/05/29 00:57:37 graham
-- Resolved swish performance problem, which turned out to an inefficient
-- method used by the parser to add arcs to a graph.
--
-- Revision 1.4 2003/05/28 17:39:30 graham
-- Trying to track down N3 formatter performance problem.
--
-- Revision 1.3 2003/05/23 00:03:55 graham
-- Added HUnit test module for swish program.
-- Greatly enhanced N3Formatter tests
--
-- Revision 1.2 2003/05/21 13:34:13 graham
-- Various N3 parser bug fixes.
-- Need to fix handling of :name terms.
--
-- Revision 1.1 2003/05/20 23:36:30 graham
-- Add new Swish modules
--
|
amccausl/Swish
|
Swish/HaskellRDF/SwishCommands.hs
|
lgpl-2.1
| 14,855 | 1 | 16 | 4,654 | 2,878 | 1,549 | 1,329 | 227 | 5 |
-- , pluginKey
-- , parseCategoryFile
-- , readCategoryFile
-- , getCategoryMap
-- , apiVersion
import System.FilePath
import Text.Regex
type Key = String
type Category = [String]
type CategoryMap = [(Key, Category)]
mkPluginKey :: FilePath -> String -> Key
mkPluginKey path name = (takeBaseName path) ++ ":" ++ name
pluginKey :: PluginDescriptor -> Key
pluginKey p = mkPluginKey (pluginLibraryPath p) (pluginIdentifier p)
-- Categories
parseCategoryFile :: String -> CategoryMap
parseCategoryFile =
mapMaybe (\x -> case matchCat x of
Just [key, cat] -> Just (key, splitCat cat)
_ -> Nothing) . lines
where
matchCat = matchRegex (mkRegex "^vamp:([^:]+:[^:]+)::(.*)")
splitCat = splitRegex (mkRegex "[\t ]*>[\t ]*")
readCategoryFile :: FilePath -> IO CategoryMap
readCategoryFile = liftM parseCategoryFile . readFile
getCategoryMap :: IO CategoryMap
getCategoryMap = getCategoryFiles >>= liftM concat . mapM readCategoryFile
|
kaoskorobase/hvamp
|
Sound/Analysis/Vamp/Category.hs
|
lgpl-3.0
| 1,038 | 0 | 14 | 241 | 268 | 144 | 124 | 20 | 2 |
module Data.Drasil.Units.PhysicalProperties where
import Data.Drasil.SI_Units (kilogram, m_3)
import Language.Drasil (UnitDefn, newUnit, (/:))
densityU :: UnitDefn
densityU = newUnit "density" $ kilogram /: m_3
|
JacquesCarette/literate-scientific-software
|
code/drasil-data/Data/Drasil/Units/PhysicalProperties.hs
|
bsd-2-clause
| 226 | 0 | 7 | 38 | 61 | 38 | 23 | 5 | 1 |
--
-- Copyright © 2015 Christian Marie <[email protected]>
--
-- The code in this file, and the program it is a part of, is
-- made available to you by its authors as open source software:
-- you can redistribute it and/or modify it under the terms of
-- the 3-clause BSD licence.
--
{-# LANGUAGE OverloadedStrings #-}
module Botlike.Automations.Examples
(
ex1
) where
import Botlike
import Control.Applicative
import Data.Monoid
import Data.String
import qualified Data.Text as Text
import qualified Text.Blaze.Html5 as H
import qualified Text.Digestive.Blaze.Html5 as H2
ex1 :: Automation f => f ()
ex1 =
input form template $ \x ->
locally_ (print x)
where
form = (,) <$> "name" .: text Nothing
<*> "mail" .: check "Empty" (not . Text.null) (text Nothing)
template :: View Html -> Html
template view = do
H2.form view "" $ do
label "name" view "Name: "
inputText "name" view
H.br
errorList "mail" view
label "mail" view "Email address: "
inputText "mail" view
H.br
inputSubmit "Unfurl the monad"
|
christian-marie/votnik
|
lib/Botlike/Automations/Examples.hs
|
bsd-3-clause
| 1,228 | 0 | 12 | 391 | 256 | 136 | 120 | 28 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE MultiParamTypeClasses #-}
module SDL.Input.Keyboard
( -- * Keyboard Modifiers
getModState
, KeyModifier(..)
, getKeyboardState
-- * Text Input
, startTextInput
, stopTextInput
-- * Screen Keyboard
, hasScreenKeyboardSupport
, isScreenKeyboardShown
-- * Scancodes
, getScancodeName
, Scancode(..)
-- * Keycodes
, Keycode(..)
-- * Keysym
, Keysym(..)
-- * Keycodes and Scancodes
, module SDL.Input.Keyboard.Codes
) where
import Control.Applicative
import Control.Monad.IO.Class (MonadIO, liftIO)
import Data.Bits
import Data.Data (Data)
import Data.Typeable
import Data.Word
import Foreign.C.String
import Foreign.Marshal.Alloc
import Foreign.Marshal.Array
import Foreign.Storable
import GHC.Generics (Generic)
import SDL.Input.Keyboard.Codes
import SDL.Internal.Numbered
import SDL.Internal.Types
import qualified Data.Vector as V
import qualified SDL.Raw.Enum as Raw
import qualified SDL.Raw.Event as Raw
import qualified SDL.Raw.Types as Raw
-- | Get the current key modifier state for the keyboard. The key modifier state is a mask special keys that are held down.
--
-- See @<https://wiki.libsdl.org/SDL_GetModState SDL_GetModState>@ for C documentation.
getModState :: (Functor m, MonadIO m) => m KeyModifier
getModState = fromNumber <$> Raw.getModState
-- | Information about which keys are currently held down. Use 'getModState' to generate this information.
data KeyModifier = KeyModifier
{ keyModifierLeftShift :: Bool
, keyModifierRightShift :: Bool
, keyModifierLeftCtrl :: Bool
, keyModifierRightCtrl :: Bool
, keyModifierLeftAlt :: Bool
, keyModifierRightAlt :: Bool
, keyModifierLeftGUI :: Bool
, keyModifierRightGUI :: Bool
, keyModifierNumLock :: Bool
, keyModifierCapsLock :: Bool
, keyModifierAltGr :: Bool
} deriving (Data, Eq, Ord, Read, Generic, Show, Typeable)
instance FromNumber KeyModifier Word32 where
fromNumber m' = let m = m' in KeyModifier
{ keyModifierLeftShift = m .&. Raw.KMOD_LSHIFT > 0
, keyModifierRightShift = m .&. Raw.KMOD_RSHIFT > 0
, keyModifierLeftCtrl = m .&. Raw.KMOD_LCTRL > 0
, keyModifierRightCtrl = m .&. Raw.KMOD_RCTRL > 0
, keyModifierLeftAlt = m .&. Raw.KMOD_LALT > 0
, keyModifierRightAlt = m .&. Raw.KMOD_RALT > 0
, keyModifierLeftGUI = m .&. Raw.KMOD_LGUI > 0
, keyModifierRightGUI = m .&. Raw.KMOD_RGUI > 0
, keyModifierNumLock = m .&. Raw.KMOD_NUM > 0
, keyModifierCapsLock = m .&. Raw.KMOD_CAPS > 0
, keyModifierAltGr = m .&. Raw.KMOD_MODE > 0
}
instance ToNumber KeyModifier Word32 where
toNumber m = foldr (.|.) 0
[ if keyModifierLeftShift m then Raw.KMOD_LSHIFT else 0
, if keyModifierRightShift m then Raw.KMOD_RSHIFT else 0
, if keyModifierLeftCtrl m then Raw.KMOD_LCTRL else 0
, if keyModifierRightCtrl m then Raw.KMOD_RCTRL else 0
, if keyModifierLeftAlt m then Raw.KMOD_LALT else 0
, if keyModifierRightAlt m then Raw.KMOD_RALT else 0
, if keyModifierLeftGUI m then Raw.KMOD_LGUI else 0
, if keyModifierRightGUI m then Raw.KMOD_RGUI else 0
, if keyModifierNumLock m then Raw.KMOD_NUM else 0
, if keyModifierCapsLock m then Raw.KMOD_CAPS else 0
, if keyModifierAltGr m then Raw.KMOD_MODE else 0
]
-- | Set the rectangle used to type text inputs and start accepting text input
-- events.
--
-- See @<https://wiki.libsdl.org/SDL_StartTextInput SDL_StartTextInput>@ for C documentation.
startTextInput :: MonadIO m => Raw.Rect -> m ()
startTextInput rect = liftIO $ do
alloca $ \ptr -> do
poke ptr rect
Raw.setTextInputRect ptr
Raw.startTextInput
-- | Stop receiving any text input events.
--
-- See @<https://wiki.libsdl.org/SDL_StopTextInput SDL_StopTextInput>@ for C documentation.
stopTextInput :: MonadIO m => m ()
stopTextInput = Raw.stopTextInput
-- | Check whether the platform has screen keyboard support.
--
-- See @<https://wiki.libsdl.org/SDL_HasScreenKeyboardSupport SDL_HasScreenKeyboardSupport>@ for C documentation.
hasScreenKeyboardSupport :: MonadIO m => m Bool
hasScreenKeyboardSupport = Raw.hasScreenKeyboardSupport
-- | Check whether the screen keyboard is shown for the given window.
--
-- See @<https://wiki.libsdl.org/SDL_IsScreenKeyboardShown SDL_IsScreenKeyboardShown>@ for C documentation.
isScreenKeyboardShown :: MonadIO m => Window -> m Bool
isScreenKeyboardShown (Window w) = Raw.isScreenKeyboardShown w
-- | Get a human-readable name for a scancode. If the scancode doesn't have a name this function returns the empty string.
--
-- See @<https://wiki.libsdl.org/SDL_GetScancodeName SDL_GetScancodeName>@ for C documentation.
getScancodeName :: MonadIO m => Scancode -> m String
getScancodeName scancode = liftIO $ do
name <- Raw.getScancodeName $ toNumber scancode
peekCString name
-- | Information about a key press or key release event.
data Keysym = Keysym
{ keysymScancode :: Scancode
-- ^ The keyboard 'Scancode'
, keysymKeycode :: Keycode
-- ^ SDL's virtual key representation for this key
, keysymModifier :: KeyModifier
-- ^ A set of modifiers that were held at the time this data was generated
} deriving (Data, Eq, Generic, Ord, Read, Show, Typeable)
-- | Get a snapshot of the current state of the keyboard.
--
-- This computation generates a mapping from 'Scancode' to 'Bool' - evaluating the function at specific 'Scancode's will inform you as to whether or not that key was held down when 'getKeyboardState' was called.
--
-- See @<https://wiki.libsdl.org/SDL_GetKeyboardState SDL_GetKeyboardState>@ for C documentation.
getKeyboardState :: MonadIO m => m (Scancode -> Bool)
getKeyboardState = liftIO $ do
alloca $ \nkeys -> do
keyptr <- Raw.getKeyboardState nkeys
n <- peek nkeys
keys <- V.fromList <$> peekArray (fromIntegral n) keyptr
return $ \scancode -> 1 == keys V.! fromIntegral (toNumber scancode)
|
svenkeidel/sdl2
|
src/SDL/Input/Keyboard.hs
|
bsd-3-clause
| 6,038 | 0 | 17 | 1,147 | 1,170 | 670 | 500 | 104 | 1 |
{-# LANGUAGE GeneralizedNewtypeDeriving, RecordWildCards, NamedFieldPuns, DeriveDataTypeable #-}
module Cards.Generic where
import Cards
import Cards.Common
import Cards.Pretty
import Data.List
import Data.Char
import Data.Set (Set)
import Data.Function (on)
import Data.Maybe
import Data.Data (Typeable)
import qualified Data.Set as Set
data GenCard = GenCard { ctype :: CardType
, name :: Name
, set :: CSet
, num :: Number
, rar :: Rarity
, keywords :: Keywords
, mcolor :: Maybe Color
, mcost :: Maybe Cost
, mreq :: Maybe Req
, mpower :: Maybe Power
, mboosted :: Maybe Power
, mpoints :: Maybe Points
, mpreqs :: Maybe ProblemReq
, text :: Text
} deriving (Eq, Ord, Typeable)
instance Show GenCard where
show = prettyShow.fromGeneric
toGeneric :: Card -> GenCard
toGeneric c@Mane{..} = let ctype = TMane
mcolor = Just color
mcost = Nothing
mpower = Just power
mreq = Nothing
mboosted = Just boosted
mpoints = Nothing
mpreqs = Nothing
in GenCard {..}
toGeneric c@Friend{..} = let ctype = TFriend
mcolor = Just color
mcost = Just cost
mreq = Just req
mpower = Just power
mboosted = Nothing
mpoints = Nothing
mpreqs = Nothing
in GenCard {..}
toGeneric c@Event{..} = let ctype = TEvent
mcolor = Just color
mcost = Just cost
mreq = Just req
mpower = Just power
mboosted = Nothing
mpoints = Nothing
mpreqs = Nothing
in GenCard {..}
toGeneric c@Resource{..} = let ctype = TResource
mcolor = Just color
mcost = Just cost
mreq = Just req
mpower = Just power
mboosted = Nothing
mpoints = Nothing
mpreqs = Nothing
in GenCard {..}
toGeneric c@Troublemaker{..} = let ctype = TTroublemaker
mcolor = Nothing
mcost = Nothing
mreq = Nothing
mpower = Just power
mboosted = Nothing
mpoints = Just points
mpreqs = Nothing
in GenCard {..}
toGeneric c@Problem{..} = let ctype = TProblem
mcolor = Nothing
mcost = Nothing
mreq = Nothing
mpower = Nothing
mboosted = Nothing
mpoints = Just points
mpreqs = Just preqs
in GenCard {..}
fromGeneric :: GenCard -> Card
fromGeneric c@GenCard{..} = case ctype of
TMane -> let color = fromJust mcolor
power = fromJust mpower
boosted = fromJust mboosted
in Mane {..}
TFriend -> let color = fromJust mcolor
cost = fromJust mcost
req = fromJust mreq
power = fromJust mpower
in Friend {..}
TEvent -> let color = fromJust mcolor
cost = fromJust mcost
req = fromJust mreq
power = fromJust mpower
in Event {..}
TResource -> let color = fromJust mcolor
cost = fromJust mcost
req = fromJust mreq
power = fromJust mpower
in Resource {..}
TTroublemaker -> let power = fromJust mpower
points = fromJust mpoints
in Troublemaker {..}
TProblem -> let points = fromJust mpoints
preqs = fromJust mpreqs
in Problem {..}
|
archaephyrryx/CCG-Project
|
src/CCG/Cards/Generic.hs
|
bsd-3-clause
| 4,793 | 0 | 12 | 2,617 | 975 | 522 | 453 | 111 | 6 |
module HttpStuff where
import Data.ByteString.Lazy hiding (map)
import Network.Wreq
a = "http://www.cnn.com"
urls :: [String]
urls = [ a ]
mappingGet :: [IO (Response ByteString)]
mappingGet = map get urls
traversedUrls :: IO [Response ByteString]
traversedUrls = traverse get urls
|
chengzh2008/hpffp
|
src/ch21-Traversable/httpStuff.hs
|
bsd-3-clause
| 286 | 0 | 8 | 44 | 93 | 53 | 40 | 10 | 1 |
{-# language MultiParamTypeClasses, FlexibleInstances, TypeOperators, OverlappingInstances #-}
module HList where
class In l ls where
-- | estrae l'elemento di tipo l
see :: ls -> l
-- | sostituisce l'elemento di tipo l
set :: l -> ls -> ls
instance In l (l,ls) where
see (l,_) = l
set l (_,ls) = (l,ls)
instance In l ls => In l (l',ls) where
see (_,ls) = see ls
set l (l',ls) = (l',set l ls)
instance {-# OVERLAPS #-} In l l where
see l = l
set l l' = l
-- | modifica l'elemento di tipo l
seeset :: In l ls
=> (l -> l) -- ^ modificatore
-> ls -- ^ struttura iniziale
-> ls -- ^ struttura finale
seeset f x = set (f $ see x) x
infixr 8 .<
-- | compositore di struttura, x <. y == (x,y)
(.<) :: l -> ls -> (l,ls)
(.<) = (,)
infixr 8 :*:
-- | compositore di tipi
type a :*: b = (a,b)
|
paolino/book-a-visit
|
common/HList.hs
|
bsd-3-clause
| 900 | 0 | 8 | 289 | 305 | 174 | 131 | 24 | 1 |
module Main where
import Test.DocTest
main :: IO ()
main = doctest [
"-isrc",
"src/Data/TreeMap.hs",
"src/Data/Accounting/Account.hs",
"src/Data/Accounting/Currency.hs",
"src/Data/Accounting/Transaction.hs"]
|
j-mueller/hldb
|
test/doctests.hs
|
bsd-3-clause
| 220 | 0 | 6 | 30 | 42 | 25 | 17 | 9 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.