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 System.Random
import Data.List
type Part = String
part1 :: [Part]
part1 = [
"Pol",
"Sand",
"Wester",
"Karl",
"Gustav",
"Nils",
"Lund" ]
part2 :: [Part]
part2 = [
"hem",
"man",
"sen",
"sson",
"gren" ]
count :: Int
count = 10 * (length part1 + length part2)
partFromList :: [String] -> Int -> String
partFromList list id = list !! (id `mod` length list)
nameFromIds :: Int -> Int -> String
nameFromIds id1 id2 = (partFromList part1 id1) ++ (partFromList part2 id2)
main :: IO ()
main = do
gen1 <- getStdGen
gen2 <- getStdGen
let list1 = map (`mod` length part1) (randoms gen1 :: [Int])
let list2 = map (`mod` length part2) (drop count $ randoms gen2 :: [Int])
let q = zip (take count list1) (take count list2)
let r = map (uncurry nameFromIds) q
mapM_ putStrLn $ (nub . sort) r
| carlmartus/helloworlds | haskell/names.hs | bsd-2-clause | 870 | 0 | 13 | 230 | 367 | 196 | 171 | 34 | 1 |
data List a = Empty | Cons a (List a) deriving (Show, Read, Eq, Ord)
-- record 语法
-- data List a = Empty | Cons { listHead :: a, listTail :: List a } deriving (Show, Read, Eq, Ord)
infixr 5 :-:
data List1 a = Empty1 | a :-: (List1 a) deriving (Show, Read, Eq, Ord)
-- make a function that adds two of our lists together.
-- infixr 5 ++
-- (++) :: [a] -> [a] -> [a]
-- [] ++ ys = ys
-- (x:xs) ++ ys = x : (xs ++ ys)
infixr 5 .++
(.++) :: List1 a -> List1 a -> List1 a
Empty1 .++ ys = ys
(x :-: xs) .++ ys = x :-: (xs .++ ys)
-- Binary Search Trees
data Tree a = EmptyTree | Node a (Tree a) (Tree a) deriving (Show, Read, Eq)
-- 写个函数, 参数为 tree 和一个新元素,并插入元素
-- 生成只有一个节点的树的函数
singleton :: a -> Tree a
singleton x = Node x EmptyTree EmptyTree
-- 插入新元素
treeInsert :: (Ord a) => a -> Tree a -> Tree a
treeInsert x EmptyTree = singleton x
treeInsert x (Node a left right)
-- if the element we're inserting is equal to the root element, just return a tree that's the same. 如果插入元素等于 根节点就返回该树
| x == a = Node x left right -- edge condition
| x < a = Node a (treeInsert x left) right
| x > a = Node a left (treeInsert x right)
-- 检查元素是否在树里
treeElem :: (Ord a ) => a -> Tree a -> Bool
treeElem x EmptyTree = False
treeElem x (Node a left right)
| x == a = True
| x < a = treeElem x left
| x > a = treeElem x right
-- foldr 中 treeInsert 是 fold function 参数为 list element 生成一个 new tree
-- EmptyTree 是 起始 accumulator.
| sharkspeed/dororis | languages/haskell/LYHGG/8-making-our-own-types-and-typeclasses/5-recursive-data-structures.hs | bsd-2-clause | 1,595 | 0 | 8 | 352 | 476 | 246 | 230 | 22 | 1 |
module Foundation where
import Prelude
import Yesod
import Yesod.Fay
import Yesod.Static
import Yesod.Auth
import Yesod.Auth.BrowserId
import Yesod.Auth.GoogleEmail
import Yesod.Default.Config
import Yesod.Default.Util (addStaticContentExternal)
import Network.HTTP.Conduit (Manager)
import qualified Settings
import Settings.Development (development)
import qualified Database.Persist.Store
import Settings.StaticFiles
import Database.Persist.GenericSql
import Settings (widgetFile, Extra (..))
import Model
import Text.Jasmine (minifym)
import Web.ClientSession (getKey)
import Text.Hamlet (hamletFile)
import SharedTypes
-- | The site argument for your application. This can be a good place to
-- keep settings and values requiring initialization before your application
-- starts running, such as database connections. Every handler will have
-- access to the data present here.
data App = App
{ settings :: AppConfig DefaultEnv Extra
, getStatic :: Static -- ^ Settings for static file serving.
, connPool :: Database.Persist.Store.PersistConfigPool Settings.PersistConfig -- ^ Database connection pool.
, httpManager :: Manager
, persistConfig :: Settings.PersistConfig
, fayCommandHandler :: CommandHandler App App
}
-- Set up i18n messages. See the message folder.
mkMessage "App" "messages" "en"
-- This is where we define all of the routes in our application. For a full
-- explanation of the syntax, please see:
-- http://www.yesodweb.com/book/handler
--
-- This function does three things:
--
-- * Creates the route datatype AppRoute. Every valid URL in your
-- application can be represented as a value of this type.
-- * Creates the associated type:
-- type instance Route App = AppRoute
-- * Creates the value resourcesApp which contains information on the
-- resources declared below. This is used in Handler.hs by the call to
-- mkYesodDispatch
--
-- What this function does *not* do is create a YesodSite instance for
-- App. Creating that instance requires all of the handler functions
-- for our application to be in scope. However, the handler functions
-- usually require access to the AppRoute datatype. Therefore, we
-- split these actions into two functions and place them in separate files.
mkYesodData "App" $(parseRoutesFile "config/routes")
type Form x = Html -> MForm App App (FormResult x, Widget)
-- Please see the documentation for the Yesod typeclass. There are a number
-- of settings which can be configured by overriding methods here.
instance Yesod App where
approot = ApprootMaster $ appRoot . settings
-- Store session data on the client in encrypted cookies,
-- default session idle timeout is 120 minutes
makeSessionBackend _ = do
key <- getKey "config/client_session_key.aes"
return . Just $ clientSessionBackend key 120
defaultLayout widget = do
master <- getYesod
mmsg <- getMessage
-- We break up the default layout into two components:
-- default-layout is the contents of the body tag, and
-- default-layout-wrapper is the entire page. Since the final
-- value passed to hamletToRepHtml cannot be a widget, this allows
-- you to use normal widget features in default-layout.
pc <- widgetToPageContent $ do
$(widgetFile "normalize")
addStylesheet $ StaticR css_bootstrap_css
$(widgetFile "default-layout")
hamletToRepHtml $(hamletFile "templates/default-layout-wrapper.hamlet")
-- This is done to provide an optimization for serving static files from
-- a separate domain. Please see the staticRoot setting in Settings.hs
urlRenderOverride y (StaticR s) =
Just $ uncurry (joinPath y (Settings.staticRoot $ settings y)) $ renderRoute s
urlRenderOverride _ _ = Nothing
-- The page to be redirected to when authentication is required.
authRoute _ = Just $ AuthR LoginR
-- This function creates static content files in the static folder
-- and names them based on a hash of their content. This allows
-- expiration dates to be set far in the future without worry of
-- users receiving stale content.
addStaticContent = addStaticContentExternal minifym base64md5 Settings.staticDir (StaticR . flip StaticRoute [])
-- Place Javascript at bottom of the body tag so the rest of the page loads first
jsLoader _ = BottomOfBody
-- What messages should be logged. The following includes all messages when
-- in development, and warnings and errors in production.
shouldLog _ _source level =
development || level == LevelWarn || level == LevelError
instance YesodJquery App
instance YesodFay App where
type YesodFayCommand App = Command
fayRoute = FaySiteR
yesodFayCommand render command = do
master <- getYesod
fayCommandHandler master render command
-- How to run database actions.
instance YesodPersist App where
type YesodPersistBackend App = SqlPersist
runDB f = do
master <- getYesod
Database.Persist.Store.runPool
(persistConfig master)
f
(connPool master)
instance YesodAuth App where
type AuthId App = UserId
-- Where to send a user after successful login
loginDest _ = HomeR
-- Where to send a user after logout
logoutDest _ = HomeR
getAuthId creds = runDB $ do
x <- getBy $ UniqueUser $ credsIdent creds
case x of
Just (Entity uid _) -> return $ Just uid
Nothing -> do
fmap Just $ insert $ User (credsIdent creds) Nothing
-- You can add other plugins like BrowserID, email or OAuth here
authPlugins _ = [authBrowserId, authGoogleEmail]
authHttpManager = httpManager
-- This instance is required to use forms. You can modify renderMessage to
-- achieve customized and internationalized form validation messages.
instance RenderMessage App FormMessage where
renderMessage _ _ = defaultFormMessage
-- | Get the 'Extra' value, used to hold data from the settings.yml file.
getExtra :: Handler Extra
getExtra = fmap (appExtra . settings) getYesod
-- Note: previous versions of the scaffolding included a deliver function to
-- send emails. Unfortunately, there are too many different options for us to
-- give a reasonable default. Instead, the information is available on the
-- wiki:
--
-- https://github.com/yesodweb/yesod/wiki/Sending-email
| snoyberg/photosorter | Foundation.hs | bsd-2-clause | 6,461 | 0 | 17 | 1,366 | 899 | 493 | 406 | -1 | -1 |
-- | Provides a simple, clean monad to write websocket servers in
{-# LANGUAGE BangPatterns, GeneralizedNewtypeDeriving, OverloadedStrings,
NoMonomorphismRestriction, Rank2Types, ScopedTypeVariables #-}
module Network.WebSockets.Monad
( WebSocketsOptions (..)
, defaultWebSocketsOptions
, WebSockets (..)
, runWebSockets
, runWebSocketsWith
, runWebSocketsHandshake
, runWebSocketsWithHandshake
, runWebSocketsWith'
, receive
, sendBuilder
, send
, Sink
, sendSink
, getSink
, getOptions
, getProtocol
, getVersion
, throwWsError
, catchWsError
, spawnPingThread
) where
import Control.Applicative (Applicative, (<$>))
import Control.Concurrent (forkIO, threadDelay)
import Control.Concurrent.MVar (MVar, modifyMVar_, newMVar)
import Control.Exception (Exception (..), SomeException, throw)
import Control.Monad (forever)
import Control.Monad.Reader (ReaderT, ask, runReaderT)
import Control.Monad.Trans (MonadIO, lift, liftIO)
import Data.Foldable (forM_)
import Blaze.ByteString.Builder (Builder)
import Data.ByteString (ByteString)
import Data.Enumerator (Enumerator, Iteratee, ($$), (>>==), (=$))
import qualified Blaze.ByteString.Builder as BB
import qualified Data.Attoparsec as A
import qualified Data.ByteString.Lazy as BL
import qualified Data.Attoparsec.Enumerator as AE
import qualified Data.Enumerator as E
import qualified Data.Enumerator.List as EL
import Network.WebSockets.Handshake
import Network.WebSockets.Handshake.Http
import Network.WebSockets.Protocol
import Network.WebSockets.Types
-- | Options for the WebSocket program
data WebSocketsOptions = WebSocketsOptions
{ onPong :: IO ()
}
-- | Default options
defaultWebSocketsOptions :: WebSocketsOptions
defaultWebSocketsOptions = WebSocketsOptions
{ onPong = return ()
}
-- | Environment in which the 'WebSockets' monad actually runs
data WebSocketsEnv p = WebSocketsEnv
{ envOptions :: WebSocketsOptions
, envSendBuilder :: Builder -> IO ()
, envSink :: Sink p
, envProtocol :: p
}
-- | Used for asynchronous sending.
newtype Sink p = Sink
{ unSink :: MVar (E.Iteratee (Message p) IO ())
}
-- | The monad in which you can write WebSocket-capable applications
newtype WebSockets p a = WebSockets
{ unWebSockets :: ReaderT (WebSocketsEnv p) (Iteratee (Message p) IO) a
} deriving (Applicative, Functor, Monad, MonadIO)
-- | Receives the initial client handshake, then behaves like 'runWebSockets'.
runWebSocketsHandshake :: Protocol p
=> Bool
-> (Request -> WebSockets p a)
-> Iteratee ByteString IO ()
-> Iteratee ByteString IO a
runWebSocketsHandshake = runWebSocketsWithHandshake defaultWebSocketsOptions
-- | Receives the initial client handshake, then behaves like
-- 'runWebSocketsWith'.
runWebSocketsWithHandshake :: Protocol p
=> WebSocketsOptions
-> Bool
-> (Request -> WebSockets p a)
-> Iteratee ByteString IO ()
-> Iteratee ByteString IO a
runWebSocketsWithHandshake opts isSecure goWs outIter = do
httpReq <- receiveIteratee $ decodeRequest isSecure
runWebSocketsWith opts httpReq goWs outIter
-- | Run a 'WebSockets' application on an 'Enumerator'/'Iteratee' pair, given
-- that you (read: your web server) has already received the HTTP part of the
-- initial request. If not, you might want to use 'runWebSocketsWithHandshake'
-- instead.
--
-- If the handshake failed, throws a 'HandshakeError'. Otherwise, executes the
-- supplied continuation. You should still send a response to the client
-- yourself.
runWebSockets :: Protocol p
=> RequestHttpPart
-> (Request -> WebSockets p a)
-> Iteratee ByteString IO ()
-> Iteratee ByteString IO a
runWebSockets = runWebSocketsWith defaultWebSocketsOptions
-- | Version of 'runWebSockets' which allows you to specify custom options
runWebSocketsWith :: forall p a. Protocol p
=> WebSocketsOptions
-> RequestHttpPart
-> (Request -> WebSockets p a)
-> Iteratee ByteString IO ()
-> Iteratee ByteString IO a
runWebSocketsWith opts httpReq goWs outIter = E.catchError ok $ \e -> do
-- If handshake went bad, send response
forM_ (fromException e) $ \he ->
let builder = encodeResponse $ responseError (undefined :: p) he
in liftIO $ makeBuilderSender outIter builder
-- Re-throw error
E.throwError e
where
-- Perform handshake, call runWebSocketsWith'
ok = do
(rq, p) <- handshake httpReq
runWebSocketsWith' opts p (goWs rq) outIter
runWebSocketsWith' :: Protocol p
=> WebSocketsOptions
-> p
-> WebSockets p a
-> Iteratee ByteString IO ()
-> Iteratee ByteString IO a
runWebSocketsWith' opts proto ws outIter = do
-- Create sink with a random source
let sinkIter = encodeMessages proto =$ builderToByteString =$ outIter
sink <- Sink <$> liftIO (newMVar sinkIter)
let sender = makeBuilderSender outIter
env = WebSocketsEnv opts sender sink proto
iter = runReaderT (unWebSockets ws) env
decodeMessages proto =$ iter
makeBuilderSender :: MonadIO m => Iteratee ByteString m b -> Builder -> m ()
makeBuilderSender outIter x = do
ok <- E.run $ singleton x $$ builderToByteString $$ outIter
case ok of
Left err -> throw err
Right _ -> return ()
-- | @spawnPingThread n@ spawns a thread which sends a ping every @n@ seconds
-- (if the protocol supports it). To be called after having sent the response.
spawnPingThread :: BinaryProtocol p => Int -> WebSockets p ()
spawnPingThread i = do
sink <- getSink
_ <- liftIO $ forkIO $ forever $ do
-- An ugly hack here. We first sleep before sending the first
-- ping, so the ping (hopefully) doesn't interfere with the
-- intitial request/response.
threadDelay (i * 1000 * 1000) -- seconds
sendSink sink $ ping ("Hi" :: ByteString)
return ()
-- | Receive arbitrary data.
receiveIteratee :: A.Parser a -> Iteratee ByteString IO a
receiveIteratee parser = do
eof <- E.isEOF
if eof
then E.throwError ConnectionClosed
else wrappingParseError . AE.iterParser $ parser
-- | Execute an iteratee, wrapping attoparsec-enumeratee's ParseError into the
-- ParseError constructor (which is a ConnectionError).
wrappingParseError :: (Monad m) => Iteratee a m b -> Iteratee a m b
wrappingParseError = flip E.catchError $ \e -> E.throwError $
maybe e (toException . ParseError) $ fromException e
-- | Receive a message
receive :: Protocol p => WebSockets p (Message p)
receive = liftIteratee $ do
mmsg <- EL.head
case mmsg of
Nothing -> E.throwError ConnectionClosed
Just msg -> return msg
-- | Send an arbitrary 'Builder'
sendBuilder :: Builder -> WebSockets p ()
sendBuilder builder = WebSockets $ do
sb <- envSendBuilder <$> ask
liftIO $ sb builder
-- | Low-level sending with an arbitrary 'T.Message'
send :: Protocol p => Message p -> WebSockets p ()
send msg = getSink >>= \sink -> liftIO $ sendSink sink msg
-- | Send a message to a sink. Might generate an exception if the underlying
-- connection is closed.
sendSink :: Sink p -> Message p -> IO ()
sendSink sink msg = modifyMVar_ (unSink sink) $ \iter -> do
step <- E.runIteratee $ singleton msg $$ iter
case step of
E.Error err -> throw err
_ -> return $! E.returnI step
-- | In case the user of the library wants to do asynchronous sending to the
-- socket, he can extract a 'Sink' and pass this value around, for example,
-- to other threads.
getSink :: Protocol p => WebSockets p (Sink p)
getSink = WebSockets $ envSink <$> ask
singleton :: Monad m => a -> Enumerator a m b
singleton c = E.checkContinue0 $ \_ f -> f (E.Chunks [c]) >>== E.returnI
-- TODO: Figure out why Blaze.ByteString.Enumerator.builderToByteString doesn't
-- work, then inform Simon or send a patch.
builderToByteString :: Monad m => E.Enumeratee Builder ByteString m a
builderToByteString = EL.concatMap $ BL.toChunks . BB.toLazyByteString
-- | Get the current configuration
getOptions :: WebSockets p WebSocketsOptions
getOptions = WebSockets $ ask >>= return . envOptions
-- | Get the underlying protocol
getProtocol :: WebSockets p p
getProtocol = WebSockets $ envProtocol <$> ask
-- | Find out the 'WebSockets' version used at runtime
getVersion :: Protocol p => WebSockets p String
getVersion = version <$> getProtocol
-- | Throw an iteratee error in the WebSockets monad
throwWsError :: (Exception e) => e -> WebSockets p a
throwWsError = liftIteratee . E.throwError
-- | Catch an iteratee error in the WebSockets monad
catchWsError :: WebSockets p a
-> (SomeException -> WebSockets p a)
-> WebSockets p a
catchWsError act c = WebSockets $ do
env <- ask
let it = peelWebSockets env $ act
cit = peelWebSockets env . c
lift $ it `E.catchError` cit
where
peelWebSockets env = flip runReaderT env . unWebSockets
-- | Lift an Iteratee computation to WebSockets
liftIteratee :: Iteratee (Message p) IO a -> WebSockets p a
liftIteratee = WebSockets . lift
| 0xfaded/websockets | src/Network/WebSockets/Monad.hs | bsd-3-clause | 9,538 | 0 | 17 | 2,293 | 2,149 | 1,137 | 1,012 | 172 | 2 |
data C_AAM = C_AAM
instance AAM C_AAM where
type Time C_AAM = Integer
type Addr C_AAM = (Integer, Name)
tzero C_AAM = 0
tick C_AAM _ t = t+1
alloc C_AAM x t = (t, x)
| davdar/quals | writeup-old/sections/03AAMByExample/04RecoveringConcrete/00AAM.hs | bsd-3-clause | 176 | 0 | 6 | 46 | 82 | 44 | 38 | -1 | -1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Numeric.Sparse.Types where
import Data.IntMap (IntMap)
import Data.Proxy
import GHC.TypeLits
import Numeric.Sparse.Internal
-- Sparse vector --------------------------------------------------------------
data SparseVector (n :: Nat) a = SV {vec :: !(IntMap a)}
deriving (Eq, Read)
instance (DIM n) => Functor (SparseVector n) where
fmap f v = v {vec = fmap f (vec v)}
instance (DIM n) => Foldable (SparseVector n) where
foldr f d v = foldr f d (vec v)
instance (Show a, Eq a, Num a, DIM n) => Show (SparseVector n a) where
show (SV v) = show (natInt (Proxy :: Proxy n)) ++ ": " ++ show v
-- Sparse matrix --------------------------------------------------------------
data SparseMatrix (n :: Nat) (m :: Nat) a = SM {mat :: !(IntMap (SparseVector m a))}
deriving (Eq, Show)
instance (DIM n, DIM m) => Functor (SparseMatrix m n) where
fmap f mx = mx {mat = fmap (fmap f) (mat mx)}
| mnick/hsparse | src/Numeric/Sparse/Types.hs | bsd-3-clause | 1,144 | 0 | 13 | 320 | 387 | 211 | 176 | 24 | 0 |
module Ttlv.ClientSpec where
import Kmip.Client
import Ttlv.Enum
import qualified Ttlv.Validator.Message as M
import qualified Ttlv.Validator.Objects
import Ttlv.Validator.Structures (runTtlvParser)
import Test.Hspec
spec :: Spec
spec = do
describe "Client" $ do
let req ttlv = runTtlvParser M.requestMessage (request ttlv) `shouldBe` Right (request ttlv)
describe "create" $ do
it "certificate default request" $ do
req [ create Certificate [] ]
describe "create key pair" $ do
it "key pair default request" $ do
req [ createKeyPair [] [] [] ]
describe "batch message" $ do
it "should generate batch" $ do
req [ create Certificate []
, createKeyPair [] [] [] ]
| nymacro/hs-kmip | tests/Ttlv/ClientSpec.hs | bsd-3-clause | 780 | 0 | 19 | 218 | 238 | 117 | 121 | 21 | 1 |
{-# LANGUAGE GADTs, FlexibleContexts, PatternGuards, TemplateHaskell #-}
module YaLedger.Processor.Duplicates
(deduplicate) where
import Control.Applicative ((<$>))
import Control.Monad.Exception
import qualified Data.Map as M
import Data.Dates
import Data.Decimal
import YaLedger.Types
import YaLedger.Kernel.Correspondence (match)
import YaLedger.Output.Pretty
import YaLedger.Exceptions
import YaLedger.Logger
import YaLedger.Processor.DateIndex
-- | Find matching deduplication rule
findDRule :: Ext Record -> [DeduplicationRule] -> Maybe ([CheckAttribute], Attributes, DAction)
findDRule erecord rules = go rules
where
go [] = Nothing
go (r:rs)
| checkDRule erecord r = Just (drCheckAttributes r, drOldRecordAttrs r, drAction r)
| otherwise = go rs
-- | Check if record is matched by rule
checkDRule :: Ext Record -> DeduplicationRule -> Bool
checkDRule erecord rule =
getAttributes erecord `match` drNewRecordAttrs rule
-- | Get first amount from record, if any
getRAmount :: Ext Record -> Maybe Amount
getRAmount r =
case getContent r of
Transaction (TEntry (UEntry dt cr _ _)) ->
Just $ head $ map postingValue dt ++ map postingValue cr
Transaction (TReconciliate _ _ x _ _) -> Just x
_ -> Nothing
getCreditAccount :: Ext Record -> Maybe AccountID
getCreditAccount r =
case getContent r of
Transaction (TEntry (UEntry dr cr corr _)) ->
case cr of
[] -> if null dr then Nothing else ((getID . fst) <$> corr)
(CPosting acc _ _: _) -> Just (getID acc)
_ -> Nothing
getDebitAccount :: Ext Record -> Maybe AccountID
getDebitAccount r =
case getContent r of
Transaction (TEntry (UEntry dr cr corr _)) ->
case dr of
[] -> if null cr then Nothing else ((getID . fst) <$> corr)
(DPosting acc _ _: _) -> Just (getID acc)
_ -> Nothing
-- | Search for record with matching attributes in list.
-- Returns (Maybe found record, all records except found).
matchBy :: DateIndex (Ext Record)
-> [CheckAttribute] -- ^ Attributes to match
-> Attributes -- ^ Attributes of old records
-> Ext Record -- ^ New record
-> [Ext Record] -- ^ All other records
-> (Maybe (Ext Record), [Ext Record])
matchBy index checks oldAttrs newRecord oldRecords
| (CDate dx:_) <- checks = $trace ("Matching " ++ show (extID newRecord) ++ " by " ++ show checks) $
case go (lookupDatePrev (getDate newRecord) dx index) of
Nothing -> $trace "No match found" (Nothing, oldRecords)
Just r -> $trace ("Match found: " ++ show r) (Just r, filter (r /=) oldRecords)
| otherwise = $trace ("Matching " ++ show (extID newRecord)) $
case go oldRecords of
Nothing -> (Nothing, oldRecords)
Just r -> (Just r, filter (r /=) oldRecords)
where
go [] = Nothing
go (r:rs) = $trace ("Comparing with " ++ show (extID r)) $
if (newRecord /= r) && checkAttrs oldAttrs r && all (matches r) checks
then Just r
else go rs
matches oldRecord (CDate d) =
$traceS (show (extID newRecord) ++ " DATE: " ++ show (getDate newRecord) ++ ", " ++ show (getDate oldRecord) ++ ": ") $
datesDifference (getDate newRecord) (getDate oldRecord) <= d
matches oldRecord (CAmount x) =
case (getRAmount newRecord, getRAmount oldRecord) of
(Just (a1 :# c1), Just (a2 :# c2)) ->
if c1 /= c2
then False
else $traceS (show (extID newRecord) ++ " CAmount: " ++ show a1 ++ ", " ++ show a2) $
if x == 0
then a1 == a2
else (max a1 a2) *. (fromIntegral x / 100.0) > (abs $ a1 - a2)
_ -> False
matches oldRecord CCreditAccount =
case (getCreditAccount newRecord, getCreditAccount oldRecord) of
(Just aid1, Just aid2) -> $traceS (show (extID newRecord) ++ " CACC: " ++ show aid1 ++ ", " ++ show aid2 ++ ": ") $ aid1 == aid2
(Nothing,Just _) -> $trace (show (extID newRecord) ++ " No credit account specified") False
(Nothing, Nothing) -> True
_ -> False
matches oldRecord CDebitAccount =
case (getDebitAccount newRecord, getDebitAccount oldRecord) of
(Just aid1, Just aid2) -> $traceS (show (extID newRecord) ++ " DACC: " ++ show aid1 ++ ", " ++ show aid2 ++ ": ") $ aid1 == aid2
(Nothing, Just _) -> $trace (show (extID newRecord) ++ " No debit account specified") False
(Nothing, Nothing) -> True
_ -> False
matches oldRecord (CAttribute name) =
case (getAttr name newRecord, getAttr name oldRecord) of
(Just v1, Just v2) -> v1 == v2
(Nothing, Nothing) -> True
_ -> False
-- | Set attributes from new record to old record
setAttributes :: [SetAttribute] -- ^ Which attributes to set
-> Ext Record -- ^ New record
-> Ext Record -- ^ Older record
-> Ext Record
setAttributes sets newRecord oldRecord = foldl apply oldRecord sets
where
apply :: Ext Record -> SetAttribute -> Ext Record
apply record (targetName := src)
| targetName == "date" = record {getDate = getDate newRecord}
| SExactly "date" <- src =
setAttr targetName (Exactly $ pPrint $ getDate newRecord) record
| SOptional "date" <- src =
setAttr targetName (Optional $ pPrint $ getDate newRecord) record
| SExactly sourceName <- src =
case getAttr sourceName newRecord of
Nothing -> record
Just value -> setAttr targetName (Exactly value) record
| SOptional sourceName <- src =
case getAttr sourceName newRecord of
Nothing -> record
Just value -> setAttr targetName (Optional value) record
| SFixed string <- src =
setAttr targetName (Exactly string) record
| otherwise = record
getAttr :: String -> Ext Record -> Maybe String
getAttr key rec = getString <$> M.lookup key (getAttributes rec)
setAttr :: String -> AttributeValue -> Ext Record -> Ext Record
setAttr name value rec =
rec {getAttributes = M.insert name value (getAttributes rec)}
checkAttrs :: Attributes -> Ext Record -> Bool
checkAttrs qry rec = all (matches $ getAttributes rec) (M.assocs qry)
where
matches attrs (name, avalue) =
case M.lookup name attrs of
Nothing -> False
Just val -> matchAV val avalue
-- | Apply all deduplication rules
deduplicate :: (Throws DuplicatedRecord l,
Throws InternalError l)
=> [DeduplicationRule] -- ^ List of deduplication rules
-> [Ext Record] -- ^ Source list of records
-> Ledger l [Ext Record]
deduplicate rules records = go $ reverse records
where
index = buildIndex records
go [] = return []
go (r:rs) =
case findDRule r rules of
Nothing -> $trace ("No rule for " ++ show (extID r)) $ (r:) <$> go rs
Just (checks, oldAttrs, action) ->
case matchBy index checks oldAttrs r rs of
(Nothing, _) -> (r:) <$> go rs
(Just old, other) ->
case action of
DError -> throw $ DuplicatedRecord
(pPrint r ++ "\nOld was:\n" ++ pPrint old)
(getLocation r)
DWarning -> do
$warning $ "Duplicated records:\n" ++ pPrint r ++
"\nOld was:\n" ++ pPrint old
(r:) <$> go rs
DDuplicate -> (r:) <$> go rs
DIgnoreNew -> go rs
DDeleteOld -> (r:) <$> go other
DSetAttributes sets ->
(setAttributes sets r old:) <$> go other
| portnov/yaledger | YaLedger/Processor/Duplicates.hs | bsd-3-clause | 8,017 | 0 | 22 | 2,556 | 2,586 | 1,287 | 1,299 | 158 | 20 |
import Control.Concurrent
import Control.Concurrent.STM
import Control.Concurrent.STM.Delay
import Control.Monad
import System.IO
spamDelays i = do
putStr $ "\r" ++ show i
hFlush stdout
d <- newDelay 100000000
threadDelay 1000
cancelDelay d
spamDelays $! i+1
main = spamDelays 1
| joeyadams/haskell-stm-delay | test/spamDelays.hs | bsd-3-clause | 305 | 0 | 8 | 63 | 98 | 47 | 51 | 13 | 1 |
module ProgramMain (
main
) where
import Data.List
import Data.Monoid
import System.Environment
main :: IO ()
main = do
[moduleName] <- getArgs >>= return . map (stripExt "hs")
putStrLn $ mainModuleText moduleName >>= expandTab 4
type Extension = String
stripExt :: Extension -> FilePath -> FilePath
stripExt ext file = maybe file id $ stripSuffix ext' file
where
ext' = case ext of
'.' : _ -> ext
_ -> '.' : ext
stripSuffix :: (Eq a) => [a] -> [a] -> Maybe [a]
stripSuffix suffix = fmap reverse . stripPrefix (reverse suffix) . reverse
expandTab :: Int -> Char -> String
expandTab n c = case c of
'\t' -> replicate n ' '
_ -> [c]
type ModuleName = String
mainModuleText :: ModuleName -> String
mainModuleText moduleName = unlines [
"module Main ("
, "\t main"
, "\t) where"
, ""
, ""
, "import qualified " ++ moduleName
, ""
, ""
, "main :: IO ()"
, "main = " ++ moduleName ++ ".main"
, ""
]
| thomaseding/main | src/ProgramMain.hs | bsd-3-clause | 1,005 | 0 | 11 | 283 | 337 | 179 | 158 | 35 | 2 |
module Data.GNG
( -- * Types
Input(len, add, mul)
, GNG
, NodeId
, EdgeId
-- * Settings
, GNGSettings
, def
, ageMax
, moveRatio1
, moveRatio2
, splitSpan
-- * Functions
, initialize
, modify
, update
-- * Outputs
, getNodes
, getEdges
) where
import Control.Applicative
import Control.Lens
import Control.Monad
import Control.Monad.State (State)
import qualified Control.Monad.State as State
import Data.Default
import Data.Foldable (foldr')
import Data.List
import Data.Maybe
import Data.Map (Map)
import qualified Data.Map as Map
import Safe
import Data.GNG.Input
import Data.GNG.Data
type StGNG a = State (GNG a)
initialize :: GNGSettings -> GNG a
initialize s = GNG (Map.empty) (Map.empty) 1 1 s 0
modify :: GNG a -> GNGSettings -> GNG a
modify gng s = gng&settings .~ s
newNodeId :: StGNG a NodeId
newNodeId = newId NodeId nodeSerial
newEdgeId :: StGNG a EdgeId
newEdgeId = newId EdgeId edgeSerial
newId :: (Int -> b) -> Getting Int (GNG a) Int -> StGNG a b
newId c serial = do
d <- State.gets $ c . (^.serial)
State.modify (&nodeSerial %~ inc)
return d
where
inc :: Int -> Int
inc = fromIntegral . (1+) . (fromIntegral::Int -> Integer)
update :: Input a => GNG a -> a -> GNG a
update gng input = State.execState (update' input) gng
update' :: Input a => a -> StGNG a ()
update' input = do
(n1, n2) <- neighborNodes input
case headMay (intersect (n1^.edgeIds) (n2^.edgeIds)) of
Nothing -> (^.edgeId) <$> newEdge n1 n2 >> return ()
Just eid -> modifyEdge (&age .~ 0) eid
moveNodes input n1
splitNodes
aging n1
splitNodes :: Input a => StGNG a ()
splitNodes = State.get >>= f
<$> (+1) . (^.splitPeriod)
<*> (\a -> a^.settings^.splitSpan)
<*> (^.nodes)
<*> (^.edges)
where
f sp ss ns es | sp < ss = return ()
| otherwise = do
State.modify $ (&splitPeriod .~ 0)
case headMay (intersect (n1^.edgeIds) (n2^.edgeIds)) >>= flip Map.lookup es of
Nothing -> return ()
Just e -> do
deleteEdges [e^.edgeId]
deleteEdgeFromNodes e
new <- newNode newValue
mapM_ (modifyNode (&moved .~ mh)) $ map (^.nodeId) [new, n1]
newEdges <- mapM (newEdge new) [n1, n2]
mapM_ (modifyEdge (&age .~ e^.age)) $ map (^.edgeId) newEdges
where
maximumByMoved = maximumBy (\a b -> compare (a^.moved) (b^.moved))
n1 = maximumByMoved $ Map.elems ns
n2 = maximumByMoved . getAll ns . map (otherNode n1) . getAll es $ n1^.edgeIds
mh = n1^.moved / 2
newValue = mul (add (n1^.value) (n2^.value)) 0.5
moveNodes :: Input a => a -> Node a -> StGNG a ()
moveNodes input node = do
gng <- State.get
let (nv, d) = move (node^.value) input (gng^.settings^.moveRatio1)
modifyNode (\n -> n&value .~ nv &moved %~ (+d)) (node^.nodeId)
nnids <- neighbors
forM_ nnids $ modifyNode $ f gng
where
neighbors = do
gng <- State.get
return
$ map (otherNode node)
$ getAll (gng^.edges)
$ (node^.edgeIds)
f gng n = n&value .~ v
&moved %~ (+d)
where
(v, d) = move (n^.value) input (gng^.settings^.moveRatio2)
otherNode :: Node a -> Edge -> NodeId
otherNode n e
| n^.nodeId == e^.left = e^.right
| n^.nodeId == e^.right = e^.left
| otherwise = error "invalid state"
getAll :: Ord k => Map k v -> [k] -> [v]
getAll m = catMaybes . map (flip Map.lookup m)
aging :: Input a => Node a -> StGNG a ()
aging node = do
let eids = node^.edgeIds
forM_ eids $ modifyEdge (&age %~ (+1))
excludeEdges eids
excludeEdges :: Input a => [EdgeId] -> StGNG a ()
excludeEdges eids = do
deades <- excludeEdges'
mapM deleteEdgeFromNodes deades
deleteIsolatedNodes
where
excludeEdges' = do
gng <- State.get
let es = gng^.edges
let deades = filter (\e -> e^.age > gng^.settings^.ageMax)
$ getAll es eids
let deadids = map (^.edgeId) deades
deleteEdges deadids
return deades
deleteIsolatedNodes = do
deadids <- State.gets (Map.keys . Map.filter (\n -> n^.edgeIds == []) . (^.nodes))
deleteNodes deadids
deleteEdgeFromNodes :: Edge -> StGNG a ()
deleteEdgeFromNodes edge = do
ns <- State.gets (^.nodes)
forM_ (map (^.nodeId) $ getAll ns [edge^.left, edge^.right])
$ modifyNode (&edgeIds %~ filter (/= edge^.edgeId))
deleteNodes :: [NodeId] -> StGNG a ()
deleteNodes nids = do
gng <- State.get
State.modify (&nodes .~ foldr' Map.delete (gng^.nodes) nids)
deleteEdges :: [EdgeId] -> StGNG a ()
deleteEdges eids = do
gng <- State.get
State.modify (&edges .~ foldl' (flip Map.delete) (gng^.edges) eids)
modifyNode :: (Node a -> Node a) -> NodeId -> StGNG a ()
modifyNode f nid = State.modify (&nodes %~ Map.adjust f nid)
modifyEdge :: (Edge -> Edge) -> EdgeId -> StGNG a ()
modifyEdge f eid = State.modify (&edges %~ Map.adjust f eid)
newEdge :: Node a -> Node a -> StGNG a Edge
newEdge n1 n2 = do
eid <- newEdgeId
let nid1 = n1^.nodeId
let nid2 = n2^.nodeId
let edge = Edge eid nid1 nid2 0
State.modify (&edges %~ Map.insert eid edge)
modifyNode (&edgeIds %~ (eid:)) nid1
modifyNode (&edgeIds %~ (eid:)) nid2
return edge
neighborNodes :: Input a => a -> StGNG a (Node a, Node a)
neighborNodes input = do
gng <- State.get
f (Map.elems (gng^.nodes)) input nothing nothing
where
f _ _ (Nothing, _) (Just _, _) = error "not reached"
f [] _ (Just n1, _) (Just n2, _) = return (n1, n2)
f [] i m1@(Just _, _) (Nothing, _) =
newNode i >>= \n -> f [] i m1 (Just n, infinity)
f [] i m1@(Nothing, _) _ =
newNode i >>= \n -> f [] i (Just n, infinity) m1
f (n:ns) i m1@(_, mx1) m2@(_, mx2) = if d < mx1
then f ns i (Just n, d) m1
else if d < mx2
then f ns i m1 (Just n, d)
else f ns i m1 m2
where
d = dist i (n^.value)
nothing = (Nothing, infinity)
infinity = 1 / 0 :: Double
newNode :: a -> StGNG a (Node a)
newNode i = do
nid <- newNodeId
let node = Node nid i [] 0
State.modify (&nodes %~ Map.insert nid node)
return node
| yunomu/gng | Data/GNG.hs | bsd-3-clause | 6,379 | 0 | 21 | 1,842 | 2,840 | 1,449 | 1,391 | 178 | 7 |
{-# LANGUAGE MonadComprehensions, BangPatterns, ScopedTypeVariables #-}
{-|
Module : Operations.WithExternalSymbols
Description : Contains FA operations. Each operation has one extra parameter to
pass an external alphabet which is used instead of the implicit
alphabet.
-}
module Operations.WithExternalSymbols
( isMacrostateAccepting
, post
, postForEachSymbol
, complete
, productUnion
, intersect
, determinize
, complement
, isEmpty
, isSubsetOf
, isUniversal
) where
import Types.Fa hiding (State, state, symbols)
import Helpers (andThen, guard)
import qualified Helpers
import Data.Set (Set)
import qualified Data.Set as Set
import Control.Monad.State hiding (guard, return)
import Control.Monad.Loops (whileM_)
-- |Converts String to a list of symbols.
charsToSymbols :: String -> [Symbol]
charsToSymbols =
fmap (: [])
-- |Determines whether a macro-state is accepting.
isMacrostateAccepting :: Ord sta => Fa sym sta -> Set sta -> Bool
isMacrostateAccepting fa states =
not $ null $ states `Set.intersection` finalStates fa
-- |Returns the post state of a state and a specific symbol.
post :: (Ord sym, Ord sta) => Fa sym sta -> Set sta -> sym -> Set sta
post fa currentStates symbol =
Set.map target $ Set.filter isApplicableTransition $ transitions fa
where
isApplicableTransition (Transition tSymbol source _) =
tSymbol == symbol && source `elem` currentStates
-- |Returns the post states for each symbol of the alphabet.
postForEachSymbol :: (Ord sym, Ord sta) => Fa sym sta -> Set sta -> Set sym -> Set (Set sta)
postForEachSymbol fa state =
Set.map (post fa state)
-- |Make a FA complete.
complete :: forall sym sta.( Ord sym, Ord sta) => Set sym -> Fa sym sta -> Fa sym (Set sta)
complete symbols fa@(Fa initialStates finalStates transitions) =
Fa init final trans
where
init = Set.map Set.singleton initialStates
final = Set.map Set.singleton finalStates
wrap :: Ord a => Set a -> Set (Set a)
wrap =
Set.map Set.singleton
wrapOrEmptySet :: Ord a => Set a -> Set (Set a)
wrapOrEmptySet elements =
if null elements
then Set.singleton Set.empty
else wrap elements
trans :: Ord sym => Set (Transition sym (Set sta))
trans =
symbols `andThen` (\symbol ->
Set.insert Set.empty (wrap $ states fa) `andThen` (\state ->
wrapOrEmptySet (post fa state symbol) `andThen` (\postState ->
Helpers.return $ Transition symbol state postState)))
-- |Creates a union of two FAs with product state ('sta1', 'sta2'). Note: Input FAs must be complete.
productUnion :: (Ord sym, Ord sta1, Ord sta2) => Set sym -> Fa sym sta1 -> Fa sym sta2 -> Fa sym (sta1, sta2)
productUnion symbols fa1@(Fa initialStates1 finalStates1 transitions1) fa2@(Fa initialStates2 finalStates2 transitions2) =
let
transitions =
symbols `andThen` (\symbol ->
transitions1 `andThen` (\(Transition symbol1 source1 target1) ->
transitions2 `andThen` (\(Transition symbol2 source2 target2) ->
guard (symbol1 == symbol && symbol2 == symbol) `andThen` (\_ ->
Helpers.return $ Transition symbol (source1, source2) (target1, target2)))))
in
Fa
(initialStates1 `andThen` (\initial1 -> initialStates2 `andThen` (\initial2 -> Helpers.return (initial1, initial2))))
(Set.union
(finalStates1 `andThen` (\final1 -> states fa2 `andThen` (\states2 -> Helpers.return (final1, states2))))
(states fa1 `andThen` (\states1 -> finalStates2 `andThen` (\final2 -> Helpers.return (states1, final2)))))
transitions
-- |Creates an intersection of two FAs.
intersect :: (Ord sym, Ord sta1, Ord sta2) => Set sym -> Fa sym sta1 -> Fa sym sta2 -> Fa sym (sta1, sta2)
intersect symbols (Fa initialStates1 finalStates1 transitions1) (Fa initialStates2 finalStates2 transitions2) =
let
transitions =
symbols `andThen` (\symbol ->
transitions1 `andThen` (\(Transition symbol1 source1 target1) ->
transitions2 `andThen` (\(Transition symbol2 source2 target2) ->
guard (symbol1 == symbol && symbol2 == symbol) `andThen` (\_ ->
Helpers.return $ Transition symbol (source1, source2) (target1, target2)))))
in
Fa
(initialStates1 `andThen` (\initial1 -> initialStates2 `andThen` (\initial2 -> Helpers.return (initial1, initial2))))
(finalStates1 `andThen` (\final1 -> finalStates2 `andThen` (\final2 -> Helpers.return (final1, final2))))
transitions
type Front sta = Set (Set sta)
type NewStates sta = Set (Set sta)
type NewTransitions sym sta = Set (Transition sym (Set sta))
type InnerState sym sta = (Front sta, NewStates sta, NewTransitions sym sta)
frontNotEmpty :: State (InnerState sym sta) Bool
frontNotEmpty = state $ \oldState@(!front, _, _) ->
(not $ null front, oldState)
moveRFromFrontToNewStates :: Ord sta => State (InnerState sym sta) (Set sta)
moveRFromFrontToNewStates = state $ \(!front, !newStates, !newTransitions) ->
let
r = Set.findMin front
front' = Set.delete r front
newStates' = Set.insert r newStates
in
(r, (front', newStates', newTransitions))
addStateAndTransitionsOfR :: (Ord sym, Ord sta) => Fa sym sta -> Set sym -> Set sta -> State (InnerState sym sta) ()
addStateAndTransitionsOfR fa symbols r = state $ \(!oldFront, !oldStates, !oldTransitions) ->
let
rWithSymbol = Set.map (\symbol -> (post fa r symbol, symbol)) symbols
r' = Set.map fst rWithSymbol
newTransitions = oldTransitions `Set.union` Set.map (\(newR, symbol) -> Transition symbol r newR) rWithSymbol
newFront = oldFront `Set.union` Set.filter (`Set.notMember` oldStates) r'
in
((), (newFront, oldStates, newTransitions))
whileBody :: (Ord sym, Ord sta) => Fa sym sta -> Set sym -> State (InnerState sym sta) ()
whileBody !fa !symbols =
moveRFromFrontToNewStates >>= addStateAndTransitionsOfR fa symbols
while :: (Ord sym, Ord sta) => Fa sym sta -> Set sym -> State (InnerState sym sta) (Fa sym (Set sta))
while fa@(Fa initialStates finalStates _) !symbols = do
whileM_ frontNotEmpty (whileBody fa symbols)
(_, newStates, newTransitions) <- get
Prelude.return $ Fa (Set.singleton initialStates) (newFinalStates newStates) newTransitions
where
newFinalStates = Set.filter $ not . Set.null . (`Set.intersection` finalStates)
-- |Converts a FA to an equivalent deterministic FA.
determinize :: (Ord sym, Ord sta) => Set sym -> Fa sym sta -> Fa sym (Set sta)
determinize !symbols !fa =
evalState (while fa symbols) (Set.singleton (initialStates fa), Set.empty, Set.empty)
-- |Creates a complement of a FA.
complement :: (Ord sym, Ord sta) => Set sym -> Fa sym sta -> Fa sym (Set sta)
complement symbols =
updateFinalStates . determinize symbols
where
updateFinalStates fa@(Fa initialStates finalStates transitions) =
Fa initialStates (states fa Set.\\ finalStates) transitions
-- |Checks whether a FA accepts an empty language.
isEmpty :: (Ord sym, Ord sta) => Set sym -> Fa sym sta -> Bool
isEmpty symbols =
not . hasTerminatingPath symbols
hasTerminatingPath :: forall sym sta. (Ord sym, Ord sta) => Set sym -> Fa sym sta -> Bool
hasTerminatingPath symbols fa =
not (null $ finalStates fa) && hasTerminatingPath' Set.empty (initialStates fa)
where
hasTerminatingPath' :: Set sta -> Set sta -> Bool
hasTerminatingPath' processed next
| null next = False
| not $ null $ next `Set.intersection` finalStates fa = True
| otherwise =
let
processed' = processed `Set.union` next
next' = newStates symbols fa next Set.\\ processed'
in
hasTerminatingPath' processed' next'
newStates :: Set sym -> Fa sym sta -> Set sta -> Set sta
newStates symbols fa states =
Helpers.unions $ postForEachSymbol fa states symbols
-- |Checks whether the first FA is subset of the second FA using the naive algorithm.
isSubsetOf :: (Ord sym, Ord sta) => Set sym -> Set sym -> Fa sym sta -> Fa sym sta -> Bool
isSubsetOf symbols1 symbols2 fa1 fa2 =
isEmpty combinedSymbols (intersect combinedSymbols fa1 (complement symbols2 fa2))
where
combinedSymbols =
symbols1 `Set.union` symbols2
-- |Checks whether a FA accepts all possible strings using the naive algorithm.
isUniversal :: (Ord sym, Ord sta) => Set sym -> Fa sym sta -> Bool
isUniversal symbols fa =
not (null $ states fa) && isSubsetOf symbols symbols universalFA fa
where
state = Set.findMin $ states fa
transitions = Set.map (\symbol -> Transition symbol state state) symbols
universalFA = Fa (Set.singleton state) (Set.singleton state) transitions
| jakubriha/automata | src/Operations/WithExternalSymbols.hs | bsd-3-clause | 8,718 | 0 | 23 | 1,824 | 2,914 | 1,536 | 1,378 | 149 | 2 |
-- |
-- Module: Main
-- Description: CommandWrapper subcommand for executing commands with a
-- predefined environment.
-- Copyright: (c) 2018-2020 Peter Trško
-- License: BSD3
--
-- Maintainer: [email protected]
-- Stability: experimental
-- Portability: GHC specific language extensions.
--
-- CommandWrapper subcommand for executing commands with a predefined
-- environment. Basically more advanced aliases. Most of the features should
-- come from using Dhall.
module Main (main)
where
import Prelude ((-), fromIntegral, maxBound, minBound)
import Control.Applicative ((<*>), empty, pure)
import Control.Monad ((>=>), (>>=), when)
import Data.Bool (Bool(False, True), (||), not, otherwise)
import Data.Eq ((==))
import Data.Foldable (any, asum, elem, foldMap, for_, length, mapM_, or)
import Data.Function (($), (.), const, id)
import Data.Functor ((<$>), (<&>), fmap)
import qualified Data.List as List (drop, filter, find, isPrefixOf, take)
import Data.Maybe (Maybe(Just, Nothing), fromMaybe, maybe)
import Data.Monoid (Endo(..), mconcat)
import Data.Ord ((<=))
import Data.Semigroup ((<>))
import Data.String (String, fromString)
import Data.Word (Word)
import GHC.Generics (Generic)
import Numeric.Natural (Natural)
import System.Environment (getArgs)
import System.Exit (ExitCode(ExitFailure, ExitSuccess), exitWith)
import System.IO (FilePath, IO, putStrLn)
import Text.Show (Show, show)
import qualified Data.CaseInsensitive as CaseInsensitive (mk)
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map (delete)
import Data.Text (Text)
import qualified Data.Text as Text (unpack)
import Data.Text.Prettyprint.Doc (Doc, (<+>), pretty)
import qualified Data.Text.Prettyprint.Doc as Pretty
import qualified Data.Text.Prettyprint.Doc.Render.Terminal as Pretty
( AnsiStyle
, Color(Magenta, White)
, color
, colorDull
)
import qualified Data.Text.Prettyprint.Doc.Util as Pretty (reflow)
import Dhall (FromDhall, ToDhall)
import qualified Dhall (auto, inject)
import qualified Dhall.Pretty as Dhall (CharacterSet(Unicode))
import qualified Options.Applicative as Options
( Parser
, auto
, flag'
, long
, option
, short
, strOption
, switch
, maybeReader
)
import Safe (atMay, headMay, lastDef)
import qualified System.Clock as Clock (Clock(Monotonic), TimeSpec, getTime)
import qualified System.Posix as Posix
( ProcessID
, ProcessStatus(Exited, Stopped, Terminated)
, forkProcess
, getProcessStatus
)
import qualified Turtle (procs) -- Get rid of dependency on turtle, use process.
import CommandWrapper.Core.Config.Shell (Shell)
import qualified CommandWrapper.Core.Config.Shell as Shell (parse)
import CommandWrapper.Core.Completion.EnvironmentVariables
( EnvironmentVariablesOptions(word, prefix)
, defEnvironmentVariablesOptions
, queryEnvironmentVariables
)
import CommandWrapper.Core.Completion.FileSystem
( FileSystemOptions
( appendSlashToSingleDirectoryResult
, expandTilde
, prefix
, word
)
, defFileSystemOptions
, queryFileSystem
)
import qualified CommandWrapper.Core.Dhall as Dhall (hPut)
import CommandWrapper.Core.Environment.Variable
( defaultCommandWrapperPrefix
, getCommandWrapperToolsetVarName
, getCommandWrapperVarName
, isVariableRemovedBeforeInvokingExternalCommand
)
import qualified CommandWrapper.Core.Help.Pretty as Help
import CommandWrapper.Core.Message (defaultLayoutOptions, hPutDoc)
import qualified CommandWrapper.Core.Options.Optparse as Options
( splitArguments
, splitArguments'
)
import qualified CommandWrapper.Subcommand.Prelude (SubcommandProps(..))
import CommandWrapper.Subcommand.Prelude
( Params(Params, colour, name, subcommand, verbosity)
, Result
, SubcommandProps(SubcommandProps)
, dieWith
, inputConfig
, out
, stderr
, stdout
, subcommandParams
, runSubcommand
)
import CommandWrapper.Toolset.Config.Command
( Command(..)
, ExecuteCommandError(..)
, NamedCommand(..)
, executeCommand
, isNamed
)
import CommandWrapper.Toolset.InternalSubcommand.Help
( SubcommandDescription(SubcommandDescription, name, description)
, TreeAnn(NodeDescription)
, TreeOptions(TreeOptions, delimiter, showDescription)
, commandTree
, treeAnnToAnsi
)
import DhallInput (defaultDhallInputParams, dhallInput, fromDhallInput)
newtype Config = Config
{ commands :: [NamedCommand]
-- TODO: Defaults for:
-- - Notifications
-- - Command line completion defaults
}
deriving stock (Generic)
deriving anyclass (FromDhall)
-- | Empty 'Config' used when there is no configuration file available.
defConfig :: Config
defConfig = Config
{ commands = []
}
data Action
= List
| Tree
| DryRun
| DryRunCompletion Word Shell
| Run Bool
| RunDhall Bool Text
defAction :: Action
defAction = Run False
data ExecParams = ExecParams
{ protocol :: Params
, config :: Config
, commandAndItsArguments :: [String]
}
deriving stock (Generic)
main :: IO ()
main = do
props <- subcommandProps
runSubcommand props \ExecParams{..} -> \case
List ->
listCommands protocol config ListOptions{showDescription = True}
Tree ->
showCommandTree protocol config TreeOptions
{ delimiter = '.'
, showDescription = True
}
DryRun ->
getExecutableCommand protocol config commandAndItsArguments
>>= printAsDhall protocol
DryRunCompletion idx shell -> do
getCompletionCommand protocol config shell idx commandAndItsArguments
>>= printAsDhall protocol
Run monitor ->
getExecutableCommand protocol config commandAndItsArguments
>>= executeAndMonitorCommand protocol MonitorOptions
{ monitor
, notificationMessage = "Action "
<> maybe "" (\s -> "'" <> fromString s <> "'")
(headMay commandAndItsArguments)
}
RunDhall monitor expression ->
runDhall protocol config
MonitorOptions
{ monitor
, notificationMessage = "Action "
}
RunDhallOptions
{ expression
-- There is no command name, only arguments.
, arguments = fromString <$> commandAndItsArguments
}
where
subcommandProps :: IO (SubcommandProps ExecParams Action)
subcommandProps = do
protocol <- subcommandParams
arguments <- getArgs
possiblyConfig <- inputConfig Dhall.auto protocol
pure SubcommandProps
{ preprocess = \ep args ->
let (opts, commandAndItsArguments) = Options.splitArguments args
in (ep{commandAndItsArguments}, opts)
, doCompletion
, helpMsg
, actionOptions = Endo . fmap <$> parseOptions
, defaultAction = Just defAction
, params = ExecParams
{ protocol
, config = fromMaybe defConfig possiblyConfig
, commandAndItsArguments = []
}
, arguments
}
getExecutableCommand :: Params -> Config -> [String] -> IO Command
getExecutableCommand params Config{commands} commandAndItsArguments =
case fromString <$> commandAndItsArguments of
[] ->
dieWith params stderr 1 "COMMAND: Missing argument."
name : arguments ->
getCommand params commands name arguments
getCompletionCommand
:: Params
-> Config
-> Shell
-> Word
-> [String]
-> IO (Maybe Command)
getCompletionCommand params config shell index = \case
[] ->
dieWith params stderr 1 "COMMAND: Missing argument."
name : arguments -> do
mkCmd <- getCompletion params config name
pure $ mkCmd
<*> pure shell
<*> pure (fromIntegral index)
<*> pure (fromString <$> arguments)
getCommand
:: Params
-> [NamedCommand]
-> Text
-> [Text]
-> IO Command
getCommand params@Params{verbosity, colour} commands expectedName arguments =
case List.find (isNamed expectedName) commands of
Nothing ->
dieWith params stderr 126
$ fromString (show expectedName) <> ": Unknown COMMAND."
Just NamedCommand{command} ->
pure (command verbosity colour arguments)
data MonitorOptions = MonitorOptions
{ monitor :: Bool
, notificationMessage :: Text
}
executeAndMonitorCommand :: Params -> MonitorOptions -> Command -> IO ()
executeAndMonitorCommand params MonitorOptions{..} command
| monitor = do
getDuration <- startDuration
pid <- Posix.forkProcess (executeCommand' params command)
exitCode <- getProcessStatus pid
duration <- getDuration
out params stdout
("Action took: " <> Pretty.viaShow duration <> Pretty.line)
-- TODO: Value of type `NotifyConfig` should be part of `Config`.
doNotifyWhen defNotifyConfig True notificationMessage exitCode
exitWith exitCode
| otherwise =
executeCommand' params command
where
getProcessStatus :: Posix.ProcessID -> IO ExitCode
getProcessStatus pid =
Posix.getProcessStatus True True pid >>= \case
Just (Posix.Exited exitCode) -> pure exitCode
Just Posix.Terminated{} -> pure (ExitFailure 1)
Just Posix.Stopped{} -> getProcessStatus pid
Nothing -> getProcessStatus pid
data NotifyConfig = NotifyConfig
{ icon :: ExitCode -> Maybe Text
, urgency :: ExitCode -> Maybe Urgency
, composeMessage :: Text -> ExitCode -> Text
, sound :: ExitCode -> Maybe FilePath
}
defNotifyConfig :: NotifyConfig
defNotifyConfig = NotifyConfig
{ icon = \status ->
Just if status == ExitSuccess
then "dialog-information"
else "dialog-error"
, urgency = \status ->
Just if status == ExitSuccess
then Low
else Normal
, composeMessage = \msg status -> mconcat
[ msg
, " "
, if status == ExitSuccess
then "finished."
else "failed."
]
, sound = \status ->
Just if status == ExitSuccess
then "/usr/share/sounds/freedesktop/stereo/dialog-information.oga"
else "/usr/share/sounds/freedesktop/stereo/dialog-error.oga"
}
data Urgency = Low | Normal | Critical
-- TODO:
--
-- - Use Haskell client to send notification instead of relying on external
-- application.
-- - Find another way how to play the message. Maybe even ask for notification
-- service if it supports sounds, and play sound ourselves only if it doesn't.
-- - Using external play command blocks until the sound is played, obviously,
-- however, this is not desired behaviour for application like this.
doNotifyWhen :: NotifyConfig -> Bool -> Text -> ExitCode -> IO ()
doNotifyWhen NotifyConfig{..} p notificationMessage status = when p do
execs "notify-send" (iconOpt <> urgencyOpt <> [msgArg])
for_ (sound status) \soundFile ->
execs "paplay" [fromString soundFile]
where
iconOpt = maybe [] (\i -> ["--icon=" <> i]) (icon status)
urgencyOpt =
maybe [] (\u -> ["--urgency=" <> urgencyToText u]) (urgency status)
msgArg = composeMessage notificationMessage status
execs cmd args = Turtle.procs cmd args empty
urgencyToText = \case
Low -> "low"
Normal -> "normal"
Critical -> "critical"
startDuration :: IO (IO Clock.TimeSpec)
startDuration = do
start <- getTime
pure do
end <- getTime
pure (end - start)
where
getTime = Clock.getTime Clock.Monotonic
executeCommand' :: Params -> Command -> IO ()
executeCommand' params = executeCommand fixEnvironment >=> \case
FailedToSetCurrentDirectory dir e ->
dieWith params stderr 1 (showing dir <> ": " <> showing e)
FailedToExecuteCommand cmd' _ _ _ e ->
dieWith params stderr 126 (showing cmd' <> ": " <> showing e)
where
showing :: Show a => a -> Text
showing = fromString . show
fixEnvironment :: Map String String -> Map String String
fixEnvironment = appEndo
$ foldMap (Endo . Map.delete . Text.unpack)
(subcommandVariablesToRemove <> toolsetVariablesToRemove)
where
subcommandVariablesToRemove =
getCommandWrapperVarName defaultCommandWrapperPrefix
<$> [minBound .. maxBound]
toolsetVariablesToRemove =
getCommandWrapperToolsetVarName defaultCommandWrapperPrefix
<$> List.filter isVariableRemovedBeforeInvokingExternalCommand
[minBound .. maxBound]
printAsDhall :: ToDhall a => Params -> a -> IO ()
printAsDhall Params{colour} =
Dhall.hPut colour Dhall.Unicode stdout Dhall.inject
data RunDhallOptions = RunDhallOptions
{ expression :: Text
, arguments :: [Text]
}
runDhall :: Params -> Config -> MonitorOptions -> RunDhallOptions -> IO ()
runDhall
params@Params{colour, verbosity}
Config{}
monitorOptions@MonitorOptions{notificationMessage}
RunDhallOptions{arguments, expression} = do
-- TODO: Handle dhall exceptions properly. Get inspired by `config`
-- subcommand.
mkCommand
<- fromDhallInput <$> dhallInput (defaultDhallInputParams expression)
let cmd@Command{command} = mkCommand verbosity colour arguments
monitorOptions' = monitorOptions
{ notificationMessage =
notificationMessage <> "'" <> fromString command <> "'"
}
executeAndMonitorCommand params monitorOptions' cmd
newtype ListOptions = ListOptions
{ showDescription :: Bool
}
data CommandAnn
= CommandName
| CommandDescription
listCommands :: Params -> Config -> ListOptions -> IO ()
listCommands Params{colour} Config{commands} ListOptions{..} =
putDoc $ Pretty.vsep (describe <$> commands) <> Pretty.line
where
describe :: NamedCommand -> Doc CommandAnn
describe NamedCommand{name, description} =
let commandName =
Pretty.annotate CommandName (pretty name)
commandDescription =
Pretty.annotate CommandDescription (pretty description)
in if showDescription
then commandName <+> commandDescription
else commandName
putDoc = hPutDoc defaultLayoutOptions toAnsi colour stdout
toAnsi = \case
CommandName -> Pretty.color Pretty.Magenta
CommandDescription -> Pretty.colorDull Pretty.White
showCommandTree :: Params -> Config -> TreeOptions -> IO ()
showCommandTree Params{colour} Config{commands} treeOptions =
putDoc (commandTree treeOptions descriptions <> Pretty.line)
where
descriptions :: [SubcommandDescription Text (Maybe (Doc TreeAnn))]
descriptions = commands <&> \NamedCommand{name, description} ->
SubcommandDescription
{ name = name
, description =
Pretty.annotate NodeDescription . pretty <$> description
}
putDoc = hPutDoc defaultLayoutOptions treeAnnToAnsi colour stdout
parseOptions :: Options.Parser (Action -> Action)
parseOptions = asum
[ Options.flag' (const (Run True)) (Options.long "notify")
, expressionOption <*> Options.switch (Options.long "notify")
, Options.flag' (const List) $ mconcat
[ Options.short 'l'
, Options.long "list"
, Options.long "ls"
]
, Options.flag' (const Tree) (Options.long "tree" <> Options.short 't')
, Options.flag' (\i s _ -> DryRunCompletion i s) (Options.long "print-completion")
<*> indexOption
<*> shellOption
, Options.flag' (const DryRun) (Options.long "print")
, pure id
]
where
expressionOption =
Options.strOption (Options.long "expression") <&> \expr m _ ->
RunDhall m expr
indexOption :: Options.Parser Word
indexOption = Options.option Options.auto (Options.long "index")
shellOption :: Options.Parser Shell
shellOption = Options.option
(Options.maybeReader (Shell.parse . CaseInsensitive.mk))
(Options.long "shell")
doCompletion :: ExecParams -> Word -> Shell -> [String] -> IO ()
doCompletion execParams index shell _ =
case Options.splitArguments' words of
(_, _, []) ->
completeExecSubcommand
(_, indexBound, commandName : commandArguments)
| not canCompleteCommand || index <= indexBound ->
completeExecSubcommand
| otherwise ->
doCommandCompletion protocol config shell commandName
(index - indexBound) commandArguments
where
ExecParams
{ protocol
, config = config@Config{commands}
, commandAndItsArguments = words
} = execParams
completeExecSubcommand :: IO ()
completeExecSubcommand
| "--expression=" `List.isPrefixOf` pat = do
-- TODO: Very similar code can be found in `config` (internal)
-- subcommand. Should this be somewhere in `command-wrapper-core`?
let prefix = "--expression="
pat' = List.drop (length prefix) pat
envPrefix = "env:"
hasPathPrefix = or
[ "./" `List.isPrefixOf` pat'
, "../" `List.isPrefixOf` pat'
, "~" `List.isPrefixOf` pat'
]
if
| envPrefix `List.isPrefixOf` pat' ->
-- Syntax `env:VARIABLE` is a valid import in Dhall.
queryEnvironmentVariables defEnvironmentVariablesOptions
{ word = List.drop (length envPrefix) pat'
, prefix = prefix <> envPrefix
}
| pat' == "." || pat' == ".." ->
printMatching ((prefix <>) <$> ["./", "../"])
| hasPathPrefix ->
-- File paths, even `~/some/path`, are valid Dhall
-- expressions. However, relative paths like `foo/bar` are
-- not, they need to start with `./` or `../`
queryFileSystem defFileSystemOptions
{ appendSlashToSingleDirectoryResult = True
, expandTilde = True
, prefix
, word = pat'
}
| otherwise ->
printMatching ((prefix <>) <$> ["./", "../", "~/", "env:"])
| hadListOrTreeOrHelp =
pure ()
| hadExpression, any (== "--notify") wordsBeforePattern =
pure ()
| hadExpression =
printMatching ["--notify"]
| hadNotifyOrPrint =
printMatching commandNames
| hadPrintCompletion =
printMatching (printCompletionOptions <> commandNames)
| otherwise =
printMatching (allOptions <> commandNames)
pat = fromMaybe (lastDef "" words) (atMay words (fromIntegral index))
printMatching = mapM_ putStrLn . List.filter (pat `List.isPrefixOf`)
wordsBeforePattern = List.take (fromIntegral index) words
commandNames = Text.unpack . (name :: NamedCommand -> Text) <$> commands
hadListOrTreeOrHelp = any
(`elem` ["-l", "--ls", "--list", "-t", "--tree", "-h", "--help"])
wordsBeforePattern
hadExpression = any ("--expression=" `List.isPrefixOf`) wordsBeforePattern
hadNotifyOrPrint = any (`elem` ["--notify", "--print"]) wordsBeforePattern
hadPrintCompletion = any (== "--print-completion") wordsBeforePattern
canCompleteCommand = not (hadListOrTreeOrHelp || hadExpression)
printCompletionOptions =
( if any ("--index=" `List.isPrefixOf`) wordsBeforePattern
then []
else ["--index="]
)
<> ( if any ("--shell=" `List.isPrefixOf`) wordsBeforePattern
then []
else ["--shell=" <> s | s <- ["bash", "fish", "zsh"]]
)
allOptions =
[ "-l", "--ls", "--list"
, "-t", "--tree"
, "--print"
, "--print-completion"
, "--expression="
, "--notify"
, "-h", "--help"
, "--"
]
doCommandCompletion
:: Params
-> Config
-> Shell
-> String
-- ^ Command name.
-> Word
-> [String]
-> IO ()
doCommandCompletion params config shell commandName index words =
getCompletion params config commandName >>= \case
Nothing ->
defaultCompletion
Just mkCompletionCommand ->
executeCommandCompletion params mkCompletionCommand shell index
words
where
-- TODO: Should this be the same default completion as shell does?
defaultCompletion = pure ()
getCompletion
:: Params
-> Config
-> String
-> IO (Maybe (Shell -> Natural -> [Text] -> Command))
getCompletion params Config{commands} commandName =
case List.find (isNamed (fromString commandName)) commands of
Nothing ->
dieWith params stderr 1
("'" <> fromString commandName <> "': Missing argument.")
Just NamedCommand{completion} ->
pure completion
executeCommandCompletion
:: Params
-> (Shell -> Natural -> [Text] -> Command)
-- ^ Function that constructs completion command, i.e. command that will be
-- executed to provide completion.
-> Shell
-> Word
-> [String]
-> IO ()
executeCommandCompletion params mkCommand shell index words =
executeCommand' params
(mkCommand shell (fromIntegral index) (fromString <$> words))
helpMsg :: ExecParams -> Pretty.Doc (Result Pretty.AnsiStyle)
helpMsg ExecParams{protocol = Params{name, subcommand}} = Pretty.vsep
[ Pretty.reflow "Execute a command with predefined environment and command\
\ line options."
, ""
, Help.usageSection name
[ subcommand'
<+> Pretty.brackets (Help.longOption "notify")
<+> Pretty.brackets (Help.metavar "--")
<+> Help.metavar "COMMAND"
<+> Pretty.brackets (Help.metavar "COMMAND_ARGUMENTS")
, subcommand' <+> Pretty.braces
( Help.longOption "list"
<> "|"
<> Help.longOption "ls"
<> "|"
<> Help.shortOption 'l'
<> "|"
<> Help.longOption "tree"
<> "|"
<> Help.shortOption 't'
)
, subcommand'
<+> Help.longOptionWithArgument "expression" "EXPRESSION"
<+> Pretty.brackets (Help.longOption "notify")
<+> Pretty.brackets (Help.metavar "--")
<+> Pretty.brackets (Help.metavar "COMMAND_ARGUMENTS")
, subcommand'
<+> Help.longOption "print"
<+> Pretty.brackets (Help.metavar "--")
<+> Help.metavar "COMMAND"
<+> Pretty.brackets (Help.metavar "COMMAND_ARGUMENTS")
, subcommand'
<+> Help.longOption "print-completion"
<+> Help.longOptionWithArgument "index" "NUM"
<+> Help.longOptionWithArgument "shell" "SHELL"
<+> Pretty.brackets (Help.metavar "--")
<+> Help.metavar "COMMAND"
<+> Pretty.brackets (Help.metavar "COMMAND_ARGUMENTS")
, subcommand' <+> Help.helpOptions
, "help" <+> Pretty.brackets (Help.longOption "man") <+> subcommand'
]
, Help.section ("Options" <> ":")
[ Help.optionDescription ["--list", "--ls", "-l"]
[ Pretty.reflow "List available", Help.metavar "COMMAND" <> "s."
]
, Help.optionDescription ["--tree", "-t"]
[ Pretty.reflow "List available", Help.metavar "COMMAND" <> "s"
, Pretty.reflow
"in tree-like form treating dots (`.`) as separators."
]
, Help.optionDescription ["--print"]
[ Pretty.reflow
"Print command as it will be executed in Dhall format."
]
, Help.optionDescription ["--print-completion"]
[ "Similar", "to", Help.longOption "print" <> ","
, Pretty.reflow
"but prints command that would be used to do command line\
\ completion if it was invoked. Additional options"
, Help.longOptionWithArgument "index" "NUM" <> ",", "and"
, Help.longOptionWithArgument "shell" "SHELL"
, Pretty.reflow
"are passed to the command line completion command."
]
, Help.optionDescription ["--expression=EXPRESSION"]
[ Pretty.reflow "Execute Dhall", Help.metavar "EXPRESSION" <> "."
, Pretty.reflow "Expected type of", Help.metavar "EXPRESSION"
, Pretty.reflow "is documented in"
, Help.value "command-wrapper-exec(1)"
, Pretty.reflow "manual page. It can be viewed by calling"
, Pretty.squotes
( Help.toolsetCommand name
("help" <+> "--man" <+> subcommand')
)
<> "."
]
, Help.optionDescription ["--notify"]
[ Pretty.reflow
"Send desktop notification when the command is done."
]
, Help.optionDescription ["--help", "-h"]
[ Pretty.reflow "Print this help and exit. Same as"
, Pretty.squotes
(Help.toolsetCommand name ("help" <+> subcommand')) <> "."
]
, Help.optionDescription ["COMMAND"]
[ Help.metavar "COMMAND" <+> Pretty.reflow "to execute."
]
, Help.optionDescription ["COMMAND_ARGUMENTS"]
[ Pretty.reflow "Additional arguments passed to"
<+> Help.metavar "COMMAND" <> "."
]
, Help.globalOptionsHelp name
]
]
where
subcommand' = fromString subcommand
| trskop/command-wrapper | command-wrapper/app-exec/Main.hs | bsd-3-clause | 26,427 | 0 | 22 | 7,677 | 6,034 | 3,296 | 2,738 | -1 | -1 |
{-# LANGUAGE PackageImports #-}
import "steveroggenkamp" Application (develMain)
import Prelude (IO)
main :: IO ()
main = develMain
| roggenkamps/steveroggenkamp.com | app/devel.hs | bsd-3-clause | 133 | 0 | 6 | 19 | 34 | 20 | 14 | 5 | 1 |
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeSynonymInstances #-}
module Physics.Falling3d.InertiaTensor3d
(
InertiaTensor3d(..),
InverseInertiaTensor3d(..),
)
where
import Data.Vect.Double.Base
import Physics.Falling.Dynamics.InertiaTensor
import Physics.Falling.Math.Transform
import Physics.Falling3d.Transform3d
newtype InertiaTensor3d = InertiaTensor3d Transform3d
deriving(Show)
newtype InverseInertiaTensor3d = InverseInertiaTensor3d Transform3d
deriving(Show)
instance InertiaTensor InertiaTensor3d InverseInertiaTensor3d Vec3 Transform3d where
inverseInertia (InertiaTensor3d inertia) = InverseInertiaTensor3d $ inverse inertia
instance InverseInertiaTensor InverseInertiaTensor3d Vec3 Transform3d where
applyToVector (InverseInertiaTensor3d i) v = i `deltaTransform` v
toWorldSpaceTensor (InverseInertiaTensor3d i) t it = InverseInertiaTensor3d $ t .*. i .*. it
| sebcrozet/falling3d | Physics/Falling3d/InertiaTensor3d.hs | bsd-3-clause | 983 | 0 | 8 | 177 | 182 | 106 | 76 | 19 | 0 |
--Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree.
{-# LANGUAGE GADTs #-}
module Duckling.Rules.NE
( defaultRules
, langRules
, localeRules
) where
import Duckling.Dimensions.Types
import Duckling.Locale
import Duckling.Types
import qualified Duckling.Numeral.NE.Rules as Numeral
defaultRules :: Seal Dimension -> [Rule]
defaultRules = langRules
localeRules :: Region -> Seal Dimension -> [Rule]
localeRules region (Seal (CustomDimension dim)) = dimLocaleRules region dim
localeRules _ _ = []
langRules :: Seal Dimension -> [Rule]
langRules (Seal AmountOfMoney) = []
langRules (Seal CreditCardNumber) = []
langRules (Seal Distance) = []
langRules (Seal Duration) = []
langRules (Seal Numeral) = Numeral.rules
langRules (Seal Email) = []
langRules (Seal Ordinal) = []
langRules (Seal PhoneNumber) = []
langRules (Seal Quantity) = []
langRules (Seal RegexMatch) = []
langRules (Seal Temperature) = []
langRules (Seal Time) = []
langRules (Seal TimeGrain) = []
langRules (Seal Url) = []
langRules (Seal Volume) = []
langRules (Seal (CustomDimension dim)) = dimLangRules NE dim
| facebookincubator/duckling | Duckling/Rules/NE.hs | bsd-3-clause | 1,242 | 0 | 9 | 194 | 408 | 216 | 192 | 31 | 1 |
------------------------------------------------------------------------------
-- | Core library components. Most anything that touches raw JMacro should
-- go in this module for now.
------------------------------------------------------------------------------
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TemplateHaskell #-}
module Graphics.HSD3.D3.Graph where
import Control.Lens hiding (index, transform)
import Control.Applicative
import Control.Monad.State
import Language.Javascript.JMacro
------------------------------------------------------------------------------
-- | State record for use in the `Graph` monad.
data GraphState s = GraphState {
_jstat :: JStat -> JStat,
_jCursor :: JExpr -> JExpr,
_jJoined :: Bool,
_userState :: s,
_varSeed :: Int
} deriving (Functor)
makeLenses ''GraphState
-- | Convenience method exposes a default GraphState for bootstraping
emptyState :: s -> GraphState s
emptyState s = GraphState {
_jstat = id,
_jCursor = id,
_jJoined = False,
_userState = s,
_varSeed = 0
}
newVar :: GraphT s a String
newVar = ("d3_" ++) . show <$> (varSeed <<%= (+1))
-- | The core data structure representing a graph computation.
newtype GraphT s a b =
Graph { unGraph :: State (GraphState s) b }
deriving (Functor, Applicative, MonadState (GraphState s), Monad)
--instance Monad (GraphT s a) where
-- (Graph x) >>= f = Graph $ do
-- x' <- x
-- unGraph $ f x'
-- return x = Graph $ return x
type Graph = GraphT ()
runGraph :: GraphT s a b -> GraphState s -> (b, GraphState s)
runGraph (Graph s) = runState s
fanout :: GraphT s a b -> GraphT s c b
fanout x = do
st <- get
let (b, st') = runGraph x st
put st'
return b
--fanin :: GraphT s [a] b -> GraphT s a b
--fanin = modify . runGraph
-- | Given a `Graph`, extracts the `JStat` that this Graph would have
-- rendered. Useful for compositional tools.
-- TODO there is probably a better way to do this.
extract :: GraphT s a b -> GraphT s a (b, JStat -> JStat)
extract gr = do
oldSt <- get
clear
gr' <- gr
newStat <- use jstat
seed <- use varSeed
put oldSt
varSeed .= seed
return (gr', newStat)
-- | The compliment to extract, `insert` appends a snippet of `JStat`
-- to the state of the current `Graph`.
insert :: JStat -> GraphT s a ()
insert js = insertCont $ \cont -> [jmacro|
`(js)`;
`(cont)`;
|]
-- | The compliment to extract, `insert` appends a snippet of `JStat`
-- to the state of the current `Graph`.
insertCont :: (JStat -> JStat) -> GraphT s a ()
insertCont js = jstat %= (. js)
-- | Clears the current JStat - for internal user only.
clear :: GraphT s a ()
clear = jstat .= id
-- | Convenience method for target
setTarget :: ToJExpr a => a -> GraphT s b ()
setTarget x = insert [jmacro|
var !__target__ = `(x)`;
|]
setData :: ToJExpr a => a -> GraphT s a ()
setData x = insert [jmacro|
var !__cursor__ = `(x)`;
|]
cursor :: JExpr
cursor = jsv "__cursor__"
target :: JExpr
target = jsv "__target__"
index :: JExpr
index = jsv "__index__"
group :: JExpr
group = jsv "__group__"
parent :: JExpr
parent = [jmacroE| d3.select(this.parentNode) |]
------------------------------------------------------------------------------
| Soostone/hs-d3 | src/Graphics/HSD3/D3/Graph.hs | bsd-3-clause | 3,414 | 0 | 10 | 763 | 760 | 422 | 338 | 68 | 1 |
{-# LANGUAGE LambdaCase #-}
module Jerimum.PostgreSQL.Types.DateTime
-- * Text codec
( parseDate
, formatDate
, parseTimeTz
, formatTimeTz
, parseTimeNoTz
, formatTimeNoTz
, parseTimestampTz
, formatTimestampTz
, parseTimestampNoTz
, formatTimestampNoTz
, fromTimestampNoTz
-- * CBOR codec
, dateEncoderV0
, dateDecoderV0
, timeTzEncoderV0
, timeTzDecoderV0
, timeNoTzEncoderV0
, timeNoTzDecoderV0
, timestampTzEncoderV0
, timestampTzDecoderV0
, timestampNoTzEncoderV0
, timestampNoTzDecoderV0
, tzEncoderV0
, tzDecoderV0
, encodeDate
, encodeTimeTz
, encodeTimeNoTz
, encodeTimestampTz
, encodeTimestampNoTz
-- * Value codec
, fromDate
, fromTimeTz
, fromTimeNoTz
, fromTimestampTz
, decodeTimestampTz
-- * Parsers/Builders
, dateParser
, buildDate
-- * Others
, timestamptzToUTCTime
) where
import qualified Codec.CBOR.Decoding as D
import qualified Codec.CBOR.Encoding as E
import Control.Applicative
import Control.Monad
import qualified Data.Attoparsec.Text as A
import qualified Data.ByteString.Lazy as L
import Data.Maybe
import Data.Monoid
import qualified Data.Text as T
import Data.Text.Lazy (toStrict)
import Data.Text.Lazy.Builder
import Data.Text.Lazy.Builder.Int
import Data.Time.Calendar (fromGregorian, fromGregorianValid)
import Data.Time.Clock
import Jerimum.PostgreSQL.Types
import Jerimum.PostgreSQL.Types.Encoding
v0 :: Version
v0 = 0
encodeDate :: Maybe Day -> E.Encoding
encodeDate = encodeWithVersion v0 dateEncoderV0
encodeTimeTz :: Maybe (TimeOfDay, Tz) -> E.Encoding
encodeTimeTz = encodeWithVersion v0 timeTzEncoderV0
encodeTimeNoTz :: Maybe TimeOfDay -> E.Encoding
encodeTimeNoTz = encodeWithVersion v0 timeNoTzEncoderV0
encodeTimestampTz :: Maybe (Day, TimeOfDay, Tz) -> E.Encoding
encodeTimestampTz = encodeWithVersion v0 timestampTzEncoderV0
encodeTimestampNoTz :: Maybe (Day, TimeOfDay) -> E.Encoding
encodeTimestampNoTz = encodeWithVersion v0 timestampNoTzEncoderV0
dateParser :: A.Parser Day
dateParser = do
year <- A.signed A.decimal
month <- between 1 12 (A.char '-' *> A.decimal)
day <- between 1 31 (A.char '-' *> A.decimal)
guard (isJust $ fromGregorianValid (fromIntegral year) month day)
pure (year, month, day)
timeNoTzParser :: A.Parser TimeOfDay
timeNoTzParser = do
hour <- between 0 23 A.decimal
minute <- between 0 59 (A.char ':' *> A.decimal)
second <- between 0 60 (A.char ':' *> A.decimal)
usecs <-
A.peekChar >>= \case
Just _ -> between 0 (pred 1000000) (A.char '.' *> A.decimal)
Nothing -> pure 0
pure (hour, minute, second, usecs)
timeTzParser :: A.Parser (TimeOfDay, Tz)
timeTzParser = (,) <$> timeNoTzParser <*> tzParser
timestampNoTzParser :: A.Parser (Day, TimeOfDay)
timestampNoTzParser = do
date <- dateParser
time <- (A.char ' ' <|> A.char 'T') *> timeNoTzParser
pure (date, time)
tzParser :: A.Parser Tz
tzParser = do
hh <- A.signed A.decimal
mm <-
A.peekChar >>= \case
Just ':' -> A.char ':' *> A.decimal
Just _ -> A.decimal
Nothing -> pure 0
guard $ isTzValid (abs hh) mm
pure (hh, sign hh * mm)
where
sign n
| n >= 0 = 1
| otherwise = -1
isTzValid 18 0 = True
isTzValid hh mm = hh >= 0 && hh < 18 && mm >= 0 && mm < 60
timestampTzParser :: A.Parser (Day, TimeOfDay, Tz)
timestampTzParser = do
(date, time) <- timestampNoTzParser
tz <- tzParser
pure (date, time, tz)
parseDate :: T.Text -> Maybe Day
parseDate = runParser "parseDate: parse error" dateParser
parseTimeNoTz :: T.Text -> Maybe TimeOfDay
parseTimeNoTz = runParser "parseTimeNoTz: parse error" timeNoTzParser
parseTimeTz :: T.Text -> Maybe (TimeOfDay, Tz)
parseTimeTz = runParser "parseTimeTz: parse error" timeTzParser
parseTimestampNoTz :: T.Text -> Maybe (Day, TimeOfDay)
parseTimestampNoTz =
runParser "parseTimestampNoTz: parse error" timestampNoTzParser
parseTimestampTz :: T.Text -> Maybe (Day, TimeOfDay, Tz)
parseTimestampTz = runParser "parseTimestampTz: parse error" timestampTzParser
buildDate :: Day -> Builder
buildDate (y, m, d) =
decimal y <> singleton '-' <> dec2 m <> singleton '-' <> dec2 d
buildTimeOfDay :: TimeOfDay -> Builder
buildTimeOfDay (h, m, s, us) =
dec2 h <> singleton ':' <> dec2 m <> singleton ':' <> dec2 s <> singleton '.' <>
decimal us
dec2 :: Integral a => a -> Builder
dec2 n
| n > (-10) && n < 0 = fromText "-0" <> decimal (abs n)
| n > 0 && n < 9 = singleton '0' <> decimal n
| otherwise = decimal n
buildTz :: Tz -> Builder
buildTz (hh, mm)
| hh >= 0 = singleton '+' <> dec2 hh <> singleton ':' <> dec2 mm
| otherwise = singleton '-' <> dec2 (abs hh) <> singleton ':' <> dec2 (abs mm)
formatDate :: Day -> T.Text
formatDate = toStrict . toLazyText . buildDate
formatTimeNoTz :: TimeOfDay -> T.Text
formatTimeNoTz = toStrict . toLazyText . buildTimeOfDay
formatTimeTz :: (TimeOfDay, Tz) -> T.Text
formatTimeTz (time, tz) =
toStrict (toLazyText (buildTimeOfDay time <> buildTz tz))
formatTimestampNoTz :: (Day, TimeOfDay) -> T.Text
formatTimestampNoTz (date, time) =
toStrict (toLazyText (buildDate date <> singleton 'T' <> buildTimeOfDay time))
formatTimestampTz :: (Day, TimeOfDay, Tz) -> T.Text
formatTimestampTz (date, time, tz) =
toStrict
(toLazyText
(buildDate date <> singleton 'T' <> buildTimeOfDay time <> buildTz tz))
between :: Ord a => a -> a -> A.Parser a -> A.Parser a
between a b parser = do
c <- parser
if c >= a && c <= b
then pure c
else fail "between"
fromDate :: Maybe Day -> Value
fromDate = mkValue (ScalarType TDate) encodeDate
fromTimeNoTz :: Maybe TimeOfDay -> Value
fromTimeNoTz = mkValue (ScalarType TTimeNoTz) encodeTimeNoTz
fromTimestampNoTz :: Maybe (Day, TimeOfDay) -> Value
fromTimestampNoTz = mkValue (ScalarType TTimestampNoTz) encodeTimestampNoTz
fromTimestampTz :: Maybe (Day, TimeOfDay, Tz) -> Value
fromTimestampTz = mkValue (ScalarType TTimestampTz) encodeTimestampTz
fromTimeTz :: Maybe (TimeOfDay, Tz) -> Value
fromTimeTz = mkValue (ScalarType TTimeTz) encodeTimeTz
decodeTimestampTz :: L.ByteString -> Either String (Maybe (Day, TimeOfDay, Tz))
decodeTimestampTz = runDecoder (decodeWithVersion decoder)
where
decoder v
| v == v0 = Just timestampTzDecoderV0
| otherwise = Nothing
dateEncoderV0 :: Day -> E.Encoding
dateEncoderV0 (y, m, d) =
E.encodeListLen 3 <> E.encodeInt32 (fromIntegral y) <>
E.encodeInt8 (fromIntegral m) <>
E.encodeInt8 (fromIntegral d)
dateDecoderV0 :: D.Decoder s Day
dateDecoderV0 = do
D.decodeListLenOf 3
y <- fromIntegral <$> D.decodeInt32
m <- fromIntegral <$> D.decodeInt8
d <- fromIntegral <$> D.decodeInt8
pure (y, m, d)
timeTzEncoderV0 :: (TimeOfDay, Tz) -> E.Encoding
timeTzEncoderV0 (time, tz) =
E.encodeListLen 2 <> timeNoTzEncoderV0 time <> tzEncoderV0 tz
timeTzDecoderV0 :: D.Decoder s (TimeOfDay, Tz)
timeTzDecoderV0 = do
D.decodeListLenOf 2
(,) <$> timeNoTzDecoderV0 <*> tzDecoderV0
timeNoTzEncoderV0 :: TimeOfDay -> E.Encoding
timeNoTzEncoderV0 (h, m, s, us) =
E.encodeListLen 4 <> E.encodeInt8 (fromIntegral h) <>
E.encodeInt8 (fromIntegral m) <>
E.encodeInt8 (fromIntegral s) <>
E.encodeInt32 (fromIntegral us)
timeNoTzDecoderV0 :: D.Decoder s TimeOfDay
timeNoTzDecoderV0 = do
D.decodeListLenOf 4
h <- fromIntegral <$> D.decodeInt8
m <- fromIntegral <$> D.decodeInt8
s <- fromIntegral <$> D.decodeInt8
us <- fromIntegral <$> D.decodeInt32
pure (h, m, s, us)
timestampNoTzEncoderV0 :: (Day, TimeOfDay) -> E.Encoding
timestampNoTzEncoderV0 (date, time) =
E.encodeListLen 2 <> dateEncoderV0 date <> timeNoTzEncoderV0 time
timestampNoTzDecoderV0 :: D.Decoder s (Day, TimeOfDay)
timestampNoTzDecoderV0 = do
D.decodeListLenOf 2
(,) <$> dateDecoderV0 <*> timeNoTzDecoderV0
timestampTzEncoderV0 :: (Day, TimeOfDay, Tz) -> E.Encoding
timestampTzEncoderV0 (date, time, tz) =
E.encodeListLen 2 <> dateEncoderV0 date <> timeTzEncoderV0 (time, tz)
timestampTzDecoderV0 :: D.Decoder s (Day, TimeOfDay, Tz)
timestampTzDecoderV0 = do
D.decodeListLenOf 2
date <- dateDecoderV0
(time, tz) <- timeTzDecoderV0
pure (date, time, tz)
tzEncoderV0 :: Tz -> E.Encoding
tzEncoderV0 (hh, mm) =
E.encodeListLen 2 <> E.encodeInt8 (fromIntegral hh) <>
E.encodeInt8 (fromIntegral mm)
tzDecoderV0 :: D.Decoder s Tz
tzDecoderV0 = do
D.decodeListLenOf 2
(,) <$> (fromIntegral <$> D.decodeInt8) <*> (fromIntegral <$> D.decodeInt8)
timestamptzToUTCTime :: (Day, TimeOfDay, Tz) -> UTCTime
timestamptzToUTCTime ((year, month, dayOfMonth), (hour, minute, second, usecond), (hh, mm)) =
let day = fromGregorian year month dayOfMonth
time =
fromIntegral usecond * 1000000 + fromIntegral second * 1000000000000 +
fromIntegral minute * 60 * 1000000000000 +
fromIntegral hour * 3600 * 1000000000000 +
fromIntegral mm * 60 * 1000000000000 +
fromIntegral hh * 3600 * 1000000000000
in UTCTime day (picosecondsToDiffTime time)
| dgvncsz0f/nws | src/Jerimum/PostgreSQL/Types/DateTime.hs | bsd-3-clause | 9,171 | 0 | 24 | 1,851 | 3,042 | 1,575 | 1,467 | 240 | 4 |
{-# OPTIONS -Wall -Werror #-}
-- #hide
module Data.Time.LocalTime.Format
(
-- * UNIX-style formatting
module Data.Time.LocalTime.Format
) where
import Data.Time.LocalTime.LocalTime
import Data.Time.LocalTime.TimeOfDay
import Data.Time.LocalTime.TimeZone
import Data.Time.Calendar.WeekDate
import Data.Time.Calendar.OrdinalDate
import Data.Time.Calendar
import Data.Time.Calendar.Private
import Data.Time.Clock
import Data.Time.Clock.POSIX
import System.Locale
import Data.Maybe
import Data.Char
-- <http://www.opengroup.org/onlinepubs/007908799/xsh/strftime.html>
class FormatTime t where
formatCharacter :: Char -> Maybe (TimeLocale -> t -> String)
-- | Substitute various time-related information for each %-code in the string, as per 'formatCharacter'.
--
-- For all types (note these three are done here, not by 'formatCharacter'):
--
-- [@%%@] @%@
--
-- [@%t@] tab
--
-- [@%n@] newline
--
-- For TimeZone (and ZonedTime and UTCTime):
--
-- [@%z@] timezone offset
--
-- [@%Z@] timezone name
--
-- For LocalTime (and ZonedTime and UTCTime):
--
-- [@%c@] as 'dateTimeFmt' @locale@ (e.g. @%a %b %e %H:%M:%S %Z %Y@)
--
-- For TimeOfDay (and LocalTime and ZonedTime and UTCTime):
--
-- [@%R@] same as @%H:%M@
--
-- [@%T@] same as @%H:%M:%S@
--
-- [@%X@] as 'timeFmt' @locale@ (e.g. @%H:%M:%S@)
--
-- [@%r@] as 'time12Fmt' @locale@ (e.g. @%I:%M:%S %p@)
--
-- [@%P@] day half from ('amPm' @locale@), converted to lowercase, @am@, @pm@
--
-- [@%p@] day half from ('amPm' @locale@), @AM@, @PM@
--
-- [@%H@] hour, 24-hour, leading 0 as needed, @00@ - @23@
--
-- [@%I@] hour, 12-hour, leading 0 as needed, @01@ - @12@
--
-- [@%k@] hour, 24-hour, leading space as needed, @ 0@ - @23@
--
-- [@%l@] hour, 12-hour, leading space as needed, @ 1@ - @12@
--
-- [@%M@] minute, @00@ - @59@
--
-- [@%S@] second with decimal part if not an integer, @00@ - @60.999999999999@
--
-- For UTCTime and ZonedTime:
--
-- [@%s@] number of seconds since the Unix epoch
--
-- For Day (and LocalTime and ZonedTime and UTCTime):
--
-- [@%D@] same as @%m\/%d\/%y@
--
-- [@%F@] same as @%Y-%m-%d@
--
-- [@%x@] as 'dateFmt' @locale@ (e.g. @%m\/%d\/%y@)
--
-- [@%Y@] year
--
-- [@%y@] last two digits of year, @00@ - @99@
--
-- [@%C@] century (being the first two digits of the year), @00@ - @99@
--
-- [@%B@] month name, long form ('fst' from 'months' @locale@), @January@ - @December@
--
-- [@%b@, @%h@] month name, short form ('snd' from 'months' @locale@), @Jan@ - @Dec@
--
-- [@%m@] month of year, leading 0 as needed, @01@ - @12@
--
-- [@%d@] day of month, leading 0 as needed, @01@ - @31@
--
-- [@%e@] day of month, leading space as needed, @ 1@ - @31@
--
-- [@%j@] day of year for Ordinal Date format, @001@ - @366@
--
-- [@%G@] year for Week Date format
--
-- [@%g@] last two digits of year for Week Date format, @00@ - @99@
--
-- [@%V@] week for Week Date format, @01@ - @53@
--
-- [@%u@] day for Week Date format, @1@ - @7@
--
-- [@%a@] day of week, short form ('snd' from 'wDays' @locale@), @Sun@ - @Sat@
--
-- [@%A@] day of week, long form ('fst' from 'wDays' @locale@), @Sunday@ - @Saturday@
--
-- [@%U@] week number of year, where weeks start on Sunday (as 'sundayStartWeek'), @01@ - @53@
--
-- [@%w@] day of week number, @0@ (= Sunday) - @6@ (= Saturday)
--
-- [@%W@] week number of year, where weeks start on Monday (as 'mondayStartWeek'), @01@ - @53@
formatTime :: (FormatTime t) => TimeLocale -> String -> t -> String
formatTime _ [] _ = ""
formatTime locale ('%':c:cs) t = (formatChar c) ++ (formatTime locale cs t) where
formatChar '%' = "%"
formatChar 't' = "\t"
formatChar 'n' = "\n"
formatChar _ = case (formatCharacter c) of
Just f -> f locale t
_ -> ""
formatTime locale (c:cs) t = c:(formatTime locale cs t)
instance FormatTime LocalTime where
formatCharacter 'c' = Just (\locale -> formatTime locale (dateTimeFmt locale))
formatCharacter c = case (formatCharacter c) of
Just f -> Just (\locale dt -> f locale (localDay dt))
Nothing -> case (formatCharacter c) of
Just f -> Just (\locale dt -> f locale (localTimeOfDay dt))
Nothing -> Nothing
instance FormatTime TimeOfDay where
-- Aggregate
formatCharacter 'R' = Just (\locale -> formatTime locale "%H:%M")
formatCharacter 'T' = Just (\locale -> formatTime locale "%H:%M:%S")
formatCharacter 'X' = Just (\locale -> formatTime locale (timeFmt locale))
formatCharacter 'r' = Just (\locale -> formatTime locale (time12Fmt locale))
-- AM/PM
formatCharacter 'P' = Just (\locale day -> map toLower ((if (todHour day) < 12 then fst else snd) (amPm locale)))
formatCharacter 'p' = Just (\locale day -> (if (todHour day) < 12 then fst else snd) (amPm locale))
-- Hour
formatCharacter 'H' = Just (\_ -> show2 . todHour)
formatCharacter 'I' = Just (\_ -> show2 . (\h -> (mod (h - 1) 12) + 1) . todHour)
formatCharacter 'k' = Just (\_ -> show2Space . todHour)
formatCharacter 'l' = Just (\_ -> show2Space . (\h -> (mod (h - 1) 12) + 1) . todHour)
-- Minute
formatCharacter 'M' = Just (\_ -> show2 . todMin)
-- Second
formatCharacter 'S' = Just (\_ -> show2Fixed . todSec)
-- Default
formatCharacter _ = Nothing
instance FormatTime ZonedTime where
formatCharacter 's' = Just (\_ zt -> show (truncate (utcTimeToPOSIXSeconds (zonedTimeToUTC zt)) :: Integer))
formatCharacter c = case (formatCharacter c) of
Just f -> Just (\locale dt -> f locale (zonedTimeToLocalTime dt))
Nothing -> case (formatCharacter c) of
Just f -> Just (\locale dt -> f locale (zonedTimeZone dt))
Nothing -> Nothing
instance FormatTime TimeZone where
formatCharacter 'z' = Just (\_ -> timeZoneOffsetString)
formatCharacter 'Z' = Just (\_ -> timeZoneName)
formatCharacter _ = Nothing
instance FormatTime Day where
-- Aggregate
formatCharacter 'D' = Just (\locale -> formatTime locale "%m/%d/%y")
formatCharacter 'F' = Just (\locale -> formatTime locale "%Y-%m-%d")
formatCharacter 'x' = Just (\locale -> formatTime locale (dateFmt locale))
-- Year Count
formatCharacter 'Y' = Just (\_ -> show . fst . toOrdinalDate)
formatCharacter 'y' = Just (\_ -> show2 . mod100 . fst . toOrdinalDate)
formatCharacter 'C' = Just (\_ -> show2 . div100 . fst . toOrdinalDate)
-- Month of Year
formatCharacter 'B' = Just (\locale -> fst . (\(_,m,_) -> (months locale) !! (m - 1)) . toGregorian)
formatCharacter 'b' = Just (\locale -> snd . (\(_,m,_) -> (months locale) !! (m - 1)) . toGregorian)
formatCharacter 'h' = Just (\locale -> snd . (\(_,m,_) -> (months locale) !! (m - 1)) . toGregorian)
formatCharacter 'm' = Just (\_ -> show2 . (\(_,m,_) -> m) . toGregorian)
-- Day of Month
formatCharacter 'd' = Just (\_ -> show2 . (\(_,_,d) -> d) . toGregorian)
formatCharacter 'e' = Just (\_ -> show2Space . (\(_,_,d) -> d) . toGregorian)
-- Day of Year
formatCharacter 'j' = Just (\_ -> show3 . snd . toOrdinalDate)
-- ISO 8601 Week Date
formatCharacter 'G' = Just (\_ -> show . (\(y,_,_) -> y) . toWeekDate)
formatCharacter 'g' = Just (\_ -> show2 . mod100 . (\(y,_,_) -> y) . toWeekDate)
formatCharacter 'V' = Just (\_ -> show2 . (\(_,w,_) -> w) . toWeekDate)
formatCharacter 'u' = Just (\_ -> show . (\(_,_,d) -> d) . toWeekDate)
-- Day of week
formatCharacter 'a' = Just (\locale -> snd . ((wDays locale) !!) . snd . sundayStartWeek)
formatCharacter 'A' = Just (\locale -> fst . ((wDays locale) !!) . snd . sundayStartWeek)
formatCharacter 'U' = Just (\_ -> show2 . fst . sundayStartWeek)
formatCharacter 'w' = Just (\_ -> show . snd . sundayStartWeek)
formatCharacter 'W' = Just (\_ -> show2 . fst . mondayStartWeek)
-- Default
formatCharacter _ = Nothing
instance FormatTime UTCTime where
formatCharacter c = fmap (\f locale t -> f locale (utcToZonedTime utc t)) (formatCharacter c)
| FranklinChen/hugs98-plus-Sep2006 | packages/time/Data/Time/LocalTime/Format.hs | bsd-3-clause | 7,685 | 6 | 17 | 1,374 | 2,134 | 1,188 | 946 | 86 | 5 |
{-# LANGUAGE LambdaCase #-}
module Tree where
pair (f, g) x = (f x, g x)
cross (f, g) (x, y) = (f x, g y)
compose (h, k) = h . k
data Tree a = Tip a | Bin (Tree a) (Tree a) deriving (Show, Eq)
tip = Tip
bin = uncurry Bin
foldt :: (a -> b, (b, b) -> b) -> Tree a -> b
foldt (f, g) (Tip a) = f a
foldt (f, g) (Bin tl tr) = g (foldt (f, g) tl, foldt (f, g) tr)
unfoldt :: (b -> Either a (b, b)) -> b -> Tree a
unfoldt phi x = case phi x of
Left a -> tip a
Right (tl, tr) -> bin (unfoldt phi tl, unfoldt phi tr)
gen = unfoldt phi
where
phi n = if n <= 0 then Left n else Right (n-1, n-1)
mapt f (Tip a) = tip (f a)
mapt f (Bin l r) = bin (mapt f l, mapt f r)
mapt' f = foldt (tip . f, bin . cross (id, id))
cat (x, y) = x ++ y
wrap = (:[])
cons = uncurry (:)
tips = foldt (wrap, cat)
tipcat = curry cat . tips
tips' t = foldt (curry cons, compose) t []
para (d, g) (Tip x) = d x
para (d, g) (Bin l r) = g (l, para (d, g) l) (r, para (d, g) r)
fixT f = \case
Tip x -> tip x
Bin xs ys -> bin (f xs, f ys)
idT = fixT idT
instance Functor Tree where
fmap = mapt
a <$ (Tip _) = tip a
a <$ (Bin l r) = bin (a <$ l, a <$ r)
-- | ref.) http://www.cs.nott.ac.uk/~pszvc/g52afp/functor_applicative.hs
instance Applicative Tree where
pure = eta
Tip f <*> x = fmap f x
Bin l r <*> x = bin (l <*> x, r <*> x)
-- | ref.) https://stackoverflow.com/questions/6798699/monad-instance-for-binary-tree
-- and answered by Edward Kmett
instance Monad Tree where
return = eta
m >>= f = mu (fmap f m)
-- Tip a >>= f = f a
-- Bin l r >>= f = Bin (l >>= f) (r >>= f)
test = do
x <- bin (tip 1,tip 2)
y <- bin (tip 'A',tip 'B')
return (x, y)
test' = bin (tip 1,tip 2) >>= \x -> bin (tip 'A',tip 'B') >>= \y -> return (x, y)
test2 = do
x <- bin (tip 1, bin (tip 2, tip 3))
y <- bin (tip 'A', tip 'B')
return (x, y)
test2' = bin (tip 1, bin (tip 2, tip 3)) >>= \x -> bin (tip 'A', tip 'B') >>= \y -> return (x, y)
test3 = do
x <- bin (tip 1, bin (tip 2, tip 3))
y <- bin (bin (tip 'A', tip 'B'), tip 'C')
return (x, y)
test3' = bin (tip 1, bin (tip 2, tip 3)) >>= \x -> bin (bin (tip 'A', tip 'B'), tip 'C') >>= \y -> return (x, y)
sample = bin (tip (bin (tip (bin (tip 1, tip 2)), tip (bin (tip 3, tip 4)))), tip (bin (tip (bin (tip 5, tip 6)), tip (bin (tip 7, tip 8)))))
-- bad implementation
-- eta = bin . pair (eta, eta)
--
-- a.k.a return
-- >>> let t2 = bin (tip 1, tip 2)
-- >>> t2
-- Bin (Tip 1) (Tip 2)
-- >>> eta t2
-- Tip (Bin (Tip 1) (Tip 2))
-- >>> fmap eta t2
-- Bin (Tip (Tip 1)) (Tip (Tip 2))
-- >>> mu . eta $ t2
-- Bin (Tip 1) (Tip 2)
-- >>> mu . fmap eta $ t2
-- Bin (Tip 1) (Tip 2)
eta = {- alpha . inl = [tip, bin] . inl = -} tip
-- a.k.a join
-- >>> let t1 = tip (bin (tip (tip 1), tip (bin (tip 2, tip 3))))
-- >>> t1
-- Tip (Bin (Tip (Tip 1)) (Tip (Bin (Tip 2) (Tip 3))))
-- >>> mu t1
-- Bin (Tip (Tip 1)) (Tip (Bin (Tip 2) (Tip 3)))
-- >>> mu . mu $ t1
-- Bin (Tip 1) (Bin (Tip 2) (Tip 3))
-- >>> fmap mu t1
-- Tip (Bin (Tip 1) (Bin (Tip 2) (Tip 3)))
-- >>> mu . fmap mu $ t1
-- Bin (Tip 1) (Bin (Tip 2) (Tip 3))
mu = {- (| id, alpha . inr |) = (| id, [tip, bin] . inr |) = -} foldt (id, bin)
| cutsea110/aop | src/Tree.hs | bsd-3-clause | 3,158 | 0 | 15 | 828 | 1,523 | 796 | 727 | 61 | 2 |
{-# OPTIONS_HADDOCK hide, prune #-}
module Handler.Mooc.Survey
( getSurveyR, postSurveyR
) where
import Import
import Yesod.Form.Bootstrap3
postSurveyR :: Handler Html
postSurveyR = do
((formResult, formWidget), formEnctype) <- runFormPost $ renderBootstrap3 BootstrapBasicForm testForm
case formResult of
FormSuccess answers -> do
muserId <- maybeAuthId
runDB . forM_ answers $ \(question, manswer) -> case manswer of
Nothing -> return ()
Just answer -> insert_ $ Survey muserId question answer
fullLayout Nothing "Qua-kit user survey" $ do
-- render all html
[whamlet|
<div class="row">
<div class="col-lg-9 col-md-9 col-sm-9 col-xs-9">
<div.card>
<div.card-main>
<div.card-header>
<div.card-inner.>
<h3.h5.margin-bottom-no.margin-top-no>
Thank you!
<div.card-inner>
Your answers have been saved.
|]
_ -> do
fullLayout Nothing "Qua-kit user survey" $ do
-- render all html
[whamlet|
<div class="row">
<div class="col-lg-9 col-md-9 col-sm-9 col-xs-9">
<div.card>
<div.card-main>
<div.card-header>
<div.card-inner.>
<h3.h5.margin-bottom-no.margin-top-no>
Dear edX student!
<div.card-inner>
<p>
Thank you for your participation in the course and in qua-kit series of exercises.
As you may know, qua-kit is an experimental educational and research platform.
<p>
You will help us a lot if you answer a series of questions related to your experience in qua-kit.
This should take not more than five minutes.
All questions are optional, so feel free to omit some of them if you do have difficulties with any.
<div.card>
<div.card-main>
<div.card-inner>
<form role=form method=post action=@{SurveyR} enctype=#{formEnctype}>
^{formWidget}
<button type="submit" .btn .btn-default>Submit
|]
getSurveyR :: Handler Html
getSurveyR = postSurveyR
testForm :: AForm Handler [(Text,Maybe Text)]
testForm = sequenceA
$ textInput "Your name"
: boolInput "Were you able to run the design exercise in a browser?"
: longTextInput "What kind of technical problems you did experience, if any?"
: intInput "How many times did you submit your design?"
: intInput "How many hours did you spend on your design in total?"
: boolInput "Do you agree with your final design rating (comared to others)?"
: boolInput "Do you feel the design rating is fair?"
: longTextInput "If you think rating is not fair, why?"
: boolInput "Did you change your design after any feedback from other students?"
: boolInput "Did you look at other design submissions in the gallery?"
: boolInput "Were the four design criteria useful for you? [Visibility, Centrality, Connectivity, Accessibility]"
: boolInput "Were the design criteria descriptions useful and understandable?"
: textInput "If you were asked to remove one criterion, which one would it be?"
: textInput "If you were asked to add one more criterion, which one would it be?"
: longTextInput "Could you comment on the criteria? Would you add some others or remove current ones?"
: longTextInput "Please, add any other comments or suggestions about the qua-kit design exercise here:"
: longTextInput "Please, add any other comments or suggestions about the qua-kit system here:"
: boolInput "Did you search for an additional information about the case study (it was a small district in Cape Town)?"
: longTextInput "What kind of contextual information did you use in your submission, if any?"
: longTextInput "We would like to change a case study for the next run of the course. Would you suggest any place?\
\ It must be a similar size and context existing settlement. Give a link to google map location and some reasoning, if you do not mind.\n\
\ [If we select your proposed location, we will credit the name you specified above]."
: longTextInput "Now, couple questsions regarding data collection exercise.\n\
\What could be changed / added to the website to improve data collection and/or its visualisation?\
\Please also explain why this would be an improvement."
: longTextInput "Would it be helpful to allow uploading pictures? Please also explain why this would be an improvement."
: []
textInput :: Text -> AForm Handler (Text,Maybe Text)
textInput n = (,) n <$> aopt textField (bfs n) Nothing
boolInput :: Text -> AForm Handler (Text,Maybe Text)
boolInput n = (,) n . fmap (pack . show) <$> aopt boolField (bfs n) Nothing
longTextInput :: Text -> AForm Handler (Text,Maybe Text)
longTextInput n = (,) n . fmap unTextarea <$> aopt textareaField (bfs n) Nothing
intInput :: Text -> AForm Handler (Text,Maybe Text)
intInput n = (,) n . fmap (pack . (show :: Int -> String)) <$> aopt intField (bfs n) Nothing
| achirkin/qua-kit | apps/hs/qua-server/src/Handler/Mooc/Survey.hs | mit | 5,610 | 0 | 28 | 1,775 | 656 | 325 | 331 | -1 | -1 |
{-# LANGUAGE DeriveDataTypeable #-}
{- |
Module : $Header$
Description : Signatures for CoCASL, as extension of CASL signatures
Copyright : (c) Till Mossakowski, Uni Bremen 2004
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : provisional
Portability : portable
Signatures for CoCASL, as extension of CASL signatures.
-}
module CoCASL.CoCASLSign where
import CASL.Sign
import CASL.AS_Basic_CASL (SORT)
import qualified Common.Lib.Rel as Rel
import qualified Common.Lib.MapSet as MapSet
import Data.Data
data CoCASLSign = CoCASLSign
{ sees :: Rel.Rel SORT
, constructs :: Rel.Rel SORT
, constructors :: OpMap
} deriving (Show, Eq, Ord, Typeable, Data)
emptyCoCASLSign :: CoCASLSign
emptyCoCASLSign = CoCASLSign Rel.empty Rel.empty MapSet.empty
closeConsRel :: CoCASLSign -> CoCASLSign
closeConsRel s =
s { constructs = Rel.transClosure $ constructs s
, sees = Rel.transClosure $ sees s }
addCoCASLSign :: CoCASLSign -> CoCASLSign -> CoCASLSign
addCoCASLSign a b = closeConsRel a
{ sees = Rel.union (sees a) $ sees b
, constructs = Rel.union (constructs a) $ constructs b
, constructors = addOpMapSet (constructors a) $ constructors b }
interCoCASLSign :: CoCASLSign -> CoCASLSign -> CoCASLSign
interCoCASLSign a b = closeConsRel a
{ sees = interRel (sees a) $ sees b
, constructs = interRel (constructs a) $ constructs b
, constructors = interOpMapSet (constructors a) $ constructors b }
diffCoCASLSign :: CoCASLSign -> CoCASLSign -> CoCASLSign
diffCoCASLSign a b = closeConsRel a
{ sees = Rel.difference (sees a) $ sees b
, constructs = Rel.difference (constructs a) $ constructs b
, constructors = diffOpMapSet (constructors a) $ constructors b }
isSubCoCASLSign :: CoCASLSign -> CoCASLSign -> Bool
isSubCoCASLSign a b =
Rel.isSubrelOf (sees a) (sees b)
&& Rel.isSubrelOf (constructs a) (constructs b)
&& isSubOpMap (constructors a) (constructors b)
| keithodulaigh/Hets | CoCASL/CoCASLSign.hs | gpl-2.0 | 1,981 | 0 | 11 | 358 | 554 | 290 | 264 | 38 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
module Numeric.Units.Dimensional.Parsing.Units
(
-- * Parsers
expression
, quantity
, unit
, number
-- * Customizing the Accepted Language
, LanguageDefinition(..)
, defaultLanguageDefinition
)
where
import Control.Applicative
import Control.Monad.Reader
import Data.ExactPi as E
import qualified Data.Foldable as F
import Data.HashSet (fromList)
import Data.Maybe (mapMaybe)
import Data.Text as T
import qualified Data.Map as Map
import Numeric.Units.Dimensional (one, (*~))
import Numeric.Units.Dimensional.Dynamic hiding ((*~), (*), (/), recip)
import qualified Numeric.Units.Dimensional.Dynamic as Dyn
import Numeric.Units.Dimensional.SIUnits
import Numeric.Units.Dimensional.UnitNames
import Numeric.Units.Dimensional.UnitNames.Languages
import Prelude hiding (exponent, recip)
import Text.Parser.Char
import Text.Parser.Combinators
import Text.Parser.Expression
import Text.Parser.Token
import Text.Parser.Token.Style (emptyOps)
import Text.Parser.Token.Highlight
import qualified Prelude as P
-- | A group of parameters defining a langauge of unit and quantity expressions.
data LanguageDefinition = LanguageDefinition
{ units :: [AnyUnit] -- ^ A list of units which may appear in 'quantity' or 'unit' expressions in the language.
, constants :: Map.Map Text (AnyQuantity ExactPi) -- ^ A list of constants which may appear in 'quantity' expressions in the language.
, unaryFunctions :: Map.Map Text (DynQuantity ExactPi -> DynQuantity ExactPi) -- ^ A list of unary functions which may be applied in 'expression's in the language.
, allowSuperscriptExponentiation :: Bool -- ^ 'True' if Unicode superscript exponents are to be permitted in the language.
}
defaultLanguageDefinition :: LanguageDefinition
defaultLanguageDefinition = LanguageDefinition
{ units = []
, constants = Map.fromList [ ("pi", demoteQuantity $ pi *~ one)
, ("tau", demoteQuantity $ (2 P.* pi) *~ one)
]
, unaryFunctions = Map.fromList [ ("abs", abs)
, ("signum", signum)
, ("sgn", signum)
, ("exp", exp)
, ("log", log)
, ("ln", log)
, ("sqrt", sqrt)
, ("sin", sin)
, ("cos", cos)
, ("tan", tan)
, ("asin", asin)
, ("acos", acos)
, ("atan", atan)
, ("sinh", sinh)
, ("cosh", cosh)
, ("tanh", tanh)
, ("asinh", asinh)
, ("acosh", acosh)
, ("atanh", atanh)
]
, allowSuperscriptExponentiation = True
}
-- | An expression may be made by combining 'quantity's with the arithmetic operators ^, *, /, +, -,
-- prefix negation, and any 'unaryFunctions' available in the supplied 'LanguageDefinition'.
expression :: (TokenParsing m, MonadReader LanguageDefinition m) => m (DynQuantity ExactPi)
expression = buildExpressionParser table term
<?> "expression"
term :: (MonadReader LanguageDefinition m, TokenParsing m) => m (DynQuantity ExactPi)
term = parens expression
<|> unaryFunctionApplication
<|> quantity
<?> "simple expression"
table :: (Monad m, TokenParsing m) => [[Operator m (DynQuantity ExactPi)]]
table = [ [preop "-" negate ]
, [binop "^" exponentiation AssocRight]
, [binop "*" (P.*) AssocLeft, binop "/" (P./) AssocLeft ]
, [binop "+" (+) AssocLeft, binop "-" (-) AssocLeft ]
]
binop :: (Monad m, TokenParsing m) => Text -> (a -> a -> a) -> Assoc -> Operator m a
binop n f assoc = Infix (f <$ reservedOp n) assoc
preop :: (Monad m, TokenParsing m) => Text -> (a -> a) -> Operator m a
preop n f = Prefix (f <$ reservedOp n)
-- When we raise a dynamic quantity to an exact dimensionless integer power, we can use the more dimensionally-lenient ^ operator.
-- When the exponent does not meet these conditions we fall back to the ** operator.
exponentiation :: DynQuantity ExactPi -> DynQuantity ExactPi -> DynQuantity ExactPi
exponentiation x y | Just y' <- y /~ demoteUnit' one, Just y'' <- toExactInteger y' = x P.^ y''
| otherwise = x ** y
unaryFunctionApplication :: (TokenParsing m, MonadReader LanguageDefinition m) => m (DynQuantity ExactPi)
unaryFunctionApplication = unaryFunction <*> parens expression
unaryFunction :: (TokenParsing m, MonadReader LanguageDefinition m) => m (DynQuantity ExactPi -> DynQuantity ExactPi)
unaryFunction = do
ufs <- asks unaryFunctions
choice $ fmap (\(n, f) -> f <$ reserved n) (Map.toList ufs)
-- | A quantity may be a 'number' with an optional 'unit' (the unit 'one' is otherwise implied), or it may be one
-- of the 'constants' available in the supplied 'LanguageDefinition'.
quantity :: (TokenParsing m, MonadReader LanguageDefinition m) => m (DynQuantity ExactPi)
quantity = constant
<|> (Dyn.*~) <$> numberWithPowers <*> unit
<|> makeQuantity <$> numberWithPowers
where
makeQuantity x | isExactZero x = polydimensionalZero
| otherwise = x Dyn.*~ demoteUnit' one
numberWithPowers :: (TokenParsing m, MonadReader LanguageDefinition m) => m ExactPi
numberWithPowers = token $ applyPowers <$> numberWithSuperscriptPower <*> many (symbolic '^' *> sign <*> decimal)
where
numberWithSuperscriptPower = do
useSuperscript <- asks allowSuperscriptExponentiation
if useSuperscript
then power <$> number <*> optional superscriptInteger
else number
applyPowers :: ExactPi -> [Integer] -> ExactPi
applyPowers x (n:ns) = (applyPowers x ns) ^^ n
applyPowers x _ = x
power :: ExactPi -> Maybe Integer -> ExactPi
power x (Just n) = x ^^ n
power x _ = x
unit :: (TokenParsing m, MonadReader LanguageDefinition m) => m AnyUnit
unit = prod <$> some oneUnit
where
prod :: [AnyUnit] -> AnyUnit
prod = F.foldl' (Dyn.*) (demoteUnit' one)
oneUnit :: (TokenParsing m, MonadReader LanguageDefinition m) => m AnyUnit
oneUnit = token $ applyPowers <$> unitWithSuperscriptPower <*> many (symbolic '^' *> sign <*> decimal)
applyPowers :: AnyUnit -> [Integer] -> AnyUnit
applyPowers u (n:ns) = power (applyPowers u ns) (Just n)
applyPowers u _ = u
unitWithSuperscriptPower :: (TokenParsing m, MonadReader LanguageDefinition m) => m AnyUnit
unitWithSuperscriptPower = power <$> bareUnit <*> optional superscriptInteger
power :: AnyUnit -> Maybe Integer -> AnyUnit
power u (Just n) = u Dyn.^ n
power u _ = u
bareUnit :: (CharParsing m, MonadReader LanguageDefinition m) => m AnyUnit
bareUnit = try fullAtomicUnit
<|> try abbreviatedAtomicUnit
<|> try prefixedFullUnit
<|> try prefixedAtomicUnit
tryApplyPrefix :: (Parsing m, Monad m) => m Prefix -> m AnyUnit -> m AnyUnit
tryApplyPrefix p u = do
p' <- p
u' <- u
case (Dyn.applyPrefix p' u') of
Nothing -> unexpected "Metric prefix applied to non-metric unit."
Just pu -> return pu
prefixedFullUnit :: (CharParsing m, MonadReader LanguageDefinition m) => m AnyUnit
prefixedFullUnit = tryApplyPrefix fullPrefix fullAtomicUnit
prefixedAtomicUnit :: (CharParsing m, MonadReader LanguageDefinition m) => m AnyUnit
prefixedAtomicUnit = tryApplyPrefix abbreviatedPrefix abbreviatedAtomicUnit
abbreviatedAtomicUnit :: (CharParsing m, MonadReader LanguageDefinition m) => m AnyUnit
abbreviatedAtomicUnit = atomicUnit internationalEnglishAbbreviation
fullAtomicUnit :: (CharParsing m, MonadReader LanguageDefinition m) => m AnyUnit
fullAtomicUnit = atomicUnit internationalEnglish
atomicUnit :: (CharParsing m, MonadReader LanguageDefinition m) => Language o -> m AnyUnit
atomicUnit l = do
us <- asks units
choice $ mapMaybe parseUnit us
where
parseUnit :: (CharParsing m) => AnyUnit -> Maybe (m AnyUnit)
parseUnit u = do
let n = name u
a <- asAtomic n
n' <- nameComponent l a
return $ u <$ string n' <* notFollowedBy letter
abbreviatedPrefix :: (CharParsing m) => m Prefix
abbreviatedPrefix = prefix internationalEnglishAbbreviation
fullPrefix :: (CharParsing m) => m Prefix
fullPrefix = prefix internationalEnglish
prefix :: (CharParsing m) => Language 'Required -> m Prefix
prefix l = choice $ fmap parsePrefix siPrefixes
where
parsePrefix :: (CharParsing m) => Prefix -> m Prefix
parsePrefix p = p <$ (string . requiredNameComponent l . prefixName $ p)
sign :: (TokenParsing m, Num a) => m (a -> a)
sign = highlight Operator
$ negate <$ char '-'
<|> id <$ char '+'
<|> pure id
number :: (TokenParsing m, MonadReader LanguageDefinition m) => m ExactPi
number = dimensionlessConstant
<|> convert <$> naturalOrScientific
where
convert (Left x) = realToFrac x
convert (Right x) = realToFrac x
dimensionlessConstant :: (TokenParsing m, MonadReader LanguageDefinition m) => m ExactPi
dimensionlessConstant = do
cs <- asks constants
let ps = fmap (uncurry makeConstant) . Map.toList $ Map.mapMaybe (Dyn./~ (demoteUnit' one)) cs
choice ps
where
makeConstant :: (TokenParsing m, MonadReader LanguageDefinition m) => Text -> ExactPi -> m ExactPi
makeConstant n v = v <$ reserved n
constant :: (TokenParsing m, MonadReader LanguageDefinition m) => m (DynQuantity ExactPi)
constant = do
cs <- asks constants
let ps = fmap (uncurry makeConstant) $ Map.toList cs
choice ps
where
makeConstant :: (TokenParsing m, MonadReader LanguageDefinition m) => Text -> AnyQuantity ExactPi -> m (DynQuantity ExactPi)
makeConstant n v = (demoteQuantity v) <$ reserved n
{-
Lexical Rules for Identifiers
-}
idStyle :: (TokenParsing m, MonadReader LanguageDefinition m) => m (IdentifierStyle m)
idStyle = do
ufs <- asks unaryFunctions
return $ IdentifierStyle
{ _styleName = "identifier"
, _styleReserved = fromList . fmap T.unpack $ (Map.keys ufs) ++ ["pi", "tau"]
, _styleStart = letter
, _styleLetter = alphaNum <|> char '_'
, _styleHighlight = Identifier
, _styleReservedHighlight = ReservedIdentifier
}
reserved :: (TokenParsing m, MonadReader LanguageDefinition m) => Text -> m ()
reserved n = do
s <- idStyle
reserveText s n
reservedOp :: (TokenParsing m, Monad m) => Text -> m ()
reservedOp = reserveText emptyOps
{-
Parsing Superscript Numbers
-}
superscriptInteger :: (CharParsing m, Integral a) => m a
superscriptInteger = superscriptSign <*> superscriptDecimal
superscriptSign :: (CharParsing m, Num a) => m (a -> a)
superscriptSign = negate <$ char '\x207b'
<|> id <$ char '\x207a'
<|> pure id
superscriptDecimal :: (CharParsing m, Num a) => m a
superscriptDecimal = F.foldl' (\x d -> (10 P.* x) P.+ d) 0 <$> some superscriptDigit
superscriptDigit :: (CharParsing m, Num a) => m a
superscriptDigit = 1 <$ char '¹'
<|> 2 <$ char '²'
<|> 3 <$ char '³'
<|> 4 <$ char '⁴'
<|> 5 <$ char '⁵'
<|> 6 <$ char '\x2076'
<|> 7 <$ char '\x2077'
<|> 8 <$ char '\x2078'
<|> 9 <$ char '\x2079'
<|> 0 <$ char '\x2070'
| dmcclean/dimensional-parsing | src/Numeric/Units/Dimensional/Parsing/Units.hs | bsd-3-clause | 12,945 | 2 | 24 | 4,226 | 3,274 | 1,735 | 1,539 | 220 | 4 |
{-# LANGUAGE CPP #-}
-- |Convenience interface for working with GLSL shader
-- programs. Provides an interface for setting attributes and
-- uniforms.
module Graphics.GLUtil.ShaderProgram
(-- * The ShaderProgram type
ShaderProgram(..),
-- * Simple shader programs utilizing a vertex shader and a fragment shader
simpleShaderProgram, simpleShaderProgramWith, simpleShaderExplicit,
simpleShaderProgramBS, simpleShaderProgramWithBS, simpleShaderExplicitBS,
loadShaderFamily,
-- * Explicit shader loading
loadShaderProgram, loadShaderProgramWith,
loadShaderProgramBS, loadShaderProgramWithBS,
-- * Working with ShaderProgram parameters
getAttrib, enableAttrib, setAttrib, setUniform, getUniform) where
import Prelude hiding (lookup)
#if __GLASGOW_HASKELL__ < 710
import Control.Applicative ((<$>), (<*>))
#endif
import qualified Data.ByteString as BS
import Data.List (find, findIndex, isSuffixOf)
import Data.Map.Strict (Map, fromList, lookup)
import Data.Maybe (isJust, isNothing, catMaybes)
import Graphics.GLUtil.Linear (AsUniform(..))
import Graphics.GLUtil.Shaders (loadShader, linkShaderProgram,
linkShaderProgramWith, loadShaderBS)
import Graphics.GLUtil.GLError (throwError)
import Graphics.Rendering.OpenGL
import System.Directory (doesFileExist)
import System.FilePath ((<.>))
-- |Representation of a GLSL shader program that has been compiled and
-- linked.
data ShaderProgram =
ShaderProgram { attribs :: Map String (AttribLocation, VariableType)
, uniforms :: Map String (UniformLocation, VariableType)
, program :: Program }
-- |Load a 'ShaderProgram' from a vertex and fragment shader source
-- files. the third argument is a tuple of the attribute names and
-- uniform names that will be set in this program. If all attributes
-- and uniforms are desired, consider using 'loadShaderProgram'.
simpleShaderExplicit :: FilePath -> FilePath -> ([String],[String])
-> IO ShaderProgram
simpleShaderExplicit = simpleShaderExplicit' loadShader
simpleShaderExplicitBS :: BS.ByteString -> BS.ByteString -> ([String],[String])
-> IO ShaderProgram
simpleShaderExplicitBS = simpleShaderExplicit' (loadShaderBS "ByteString literal")
simpleShaderExplicit' :: (ShaderType -> a -> IO Shader)
-> a -> a -> ([String],[String])
-> IO ShaderProgram
simpleShaderExplicit' load vsrc fsrc names =
do vs <- load VertexShader vsrc
fs <- load FragmentShader fsrc
p <- linkShaderProgram [vs,fs]
throwError
(attrs,unis) <- getExplicits p names
return $ ShaderProgram (fromList attrs) (fromList unis) p
-- |Load a 'ShaderProgram' from a vertex shader source file and a
-- fragment shader source file. The active attributes and uniforms in
-- the linked program are recorded in the 'ShaderProgram'.
simpleShaderProgram :: FilePath -> FilePath -> IO ShaderProgram
simpleShaderProgram vsrc fsrc =
simpleShaderProgramWith vsrc fsrc (\_ -> return ())
-- |Load a 'ShaderProgram' from vertex and fragment shader source
-- strings. The active attributes and uniforms in the linked program
-- are recorded in the 'ShaderProgram'.
simpleShaderProgramBS :: BS.ByteString -> BS.ByteString -> IO ShaderProgram
simpleShaderProgramBS vsrc fsrc =
simpleShaderProgramWithBS vsrc fsrc (\_ -> return ())
-- |Load a 'ShaderProgram' from a vertex shader source file and a
-- fragment shader source file. The active attributes and uniforms in
-- the linked program are recorded in the 'ShaderProgram'. The
-- supplied 'IO' function is applied to the new program after shader
-- objects are attached to the program, but before linking. This
-- supports the use of 'bindFragDataLocation' to map fragment shader
-- outputs.
simpleShaderProgramWith :: FilePath -> FilePath -> (Program -> IO ())
-> IO ShaderProgram
simpleShaderProgramWith vsrc fsrc m =
loadShaderProgramWith [(VertexShader, vsrc), (FragmentShader, fsrc)] m
-- |Load a 'ShaderProgram' from vertex and fragment shader source
-- strings. See 'simpleShaderProgramWith' for more information.
simpleShaderProgramWithBS :: BS.ByteString -> BS.ByteString
-> (Program -> IO ()) -> IO ShaderProgram
simpleShaderProgramWithBS vsrc fsrc m =
loadShaderProgramWithBS [(VertexShader, vsrc), (FragmentShader, fsrc)] m
loadShaderProgramWith :: [(ShaderType, FilePath)] -> (Program -> IO ())
-> IO ShaderProgram
loadShaderProgramWith = loadShaderProgramWith' loadShader
loadShaderProgramWithBS :: [(ShaderType, BS.ByteString)] -> (Program -> IO ())
-> IO ShaderProgram
loadShaderProgramWithBS = loadShaderProgramWith' (loadShaderBS "ByteString literal")
-- | Helper for @load*Program*@ variants.
loadShaderProgramWith' :: (ShaderType -> a -> IO Shader)
-> [(ShaderType, a)] -> (Program -> IO ())
-> IO ShaderProgram
loadShaderProgramWith' load sources m =
do p <- mapM (uncurry load) sources >>= flip linkShaderProgramWith m
throwError
(attrs,unis) <- getActives p
return $ ShaderProgram (fromList attrs) (fromList unis) p
-- |Load a 'ShaderProgram' from a list of individual shader program
-- files. The active attributes and uniforms in the linked program are
-- recorded in the 'ShaderProgram'
loadShaderProgram :: [(ShaderType, FilePath)] -> IO ShaderProgram
loadShaderProgram = flip loadShaderProgramWith (const (return ()))
-- | Load a 'ShaderProgram' from a list of individual shader program
-- source strings. The active attributes and uniforms in the linked program are
-- recorded in the 'ShaderProgram'
loadShaderProgramBS :: [(ShaderType, BS.ByteString)] -> IO ShaderProgram
loadShaderProgramBS = flip loadShaderProgramWithBS (const (return ()))
-- | Load a shader program from vertex, geometry, and fragment shaders
-- that all share the same root file name and the various conventional
-- extensions: \".vert\", \".geom\", and \".frag\". If a specific file
-- doesn't exist, such as a geometry shader, it is skipped. For
-- instance, @loadShaderFamily "simple"@ will load and compile,
-- \"simple.vert\" and \"simple.frag\" if those files exist.
loadShaderFamily :: FilePath -> IO ShaderProgram
loadShaderFamily root = mapM aux shaderTypes >>= loadShaderProgram . catMaybes
where shaderTypes = [ (VertexShader, "vert")
, (GeometryShader, "geom")
, (FragmentShader, "frag") ]
aux (tag, ext) = let f = root <.> ext
in doesFileExist f >>= \b -> return $
if b then Just (tag, f) else Nothing
-- | Get all attributes and uniforms used by a program. Note that
-- unused parameters may be elided by the compiler, and so will not be
-- considered as active.
getActives :: Program ->
IO ( [(String, (AttribLocation, VariableType))]
, [(String, (UniformLocation, VariableType))] )
getActives p =
(,) <$> (get (activeAttribs p) >>= mapM (aux (attribLocation p)))
<*> (get (activeUniforms p)
>>= mapM (aux (uniformLocation p) . on3 trimArray))
where aux f (_,t,name) = get (f name) >>= \l -> return (name, (l, t))
on3 f (a,b,c) = (a, b, f c)
-- An array uniform, foo, is sometimes given the name "foo" and
-- sometimes the name "foo[0]". We strip off the "[0]" if present.
trimArray n = if "[0]" `isSuffixOf` n then take (length n - 3) n else n
-- | Get the attribute and uniform locations associated with a list of
-- the names of each.
getExplicits :: Program -> ([String], [String]) ->
IO ( [(String, (AttribLocation, VariableType))]
, [(String, (UniformLocation, VariableType))] )
getExplicits p (anames, unames) =
do attrs <- get (activeAttribs p)
attrs' <- mapM (aux (get . (attribLocation p))) . checkJusts $
map (\a -> find (\(_,_,n) -> n == a) attrs) anames
unis <- get (activeUniforms p)
unis' <- mapM (aux (get . (uniformLocation p))) . checkJusts $
map (\u -> find (\(_,_,n) -> n == u) unis) unames
return (attrs', unis')
where aux f (_,t,n) = f n >>= \l -> return (n, (l,t))
checkJusts xs
| all isJust xs = catMaybes xs
| otherwise = let Just i = findIndex isNothing xs
in error $ "Missing GLSL variable: " ++ anames !! i
-- | Set a named uniform parameter associated with a particular shader
-- program.
setUniform :: AsUniform a => ShaderProgram -> String -> a -> IO ()
setUniform sp name = maybe (const (putStrLn warn >> return ()))
(flip asUniform . fst)
(lookup name $ uniforms sp)
where warn = "WARNING: uniform "++name++" is not active"
-- | Get the 'UniformLocation' associated with a named uniform
-- parameter.
getUniform :: ShaderProgram -> String -> UniformLocation
getUniform sp n = maybe (error msg) fst . lookup n $ uniforms sp
where msg = "Uniform "++show n++" is not active"
-- | Set a named vertex attribute's 'IntegerHandling' and
-- 'VertexArrayDescriptor'.
setAttrib :: ShaderProgram -> String ->
IntegerHandling -> VertexArrayDescriptor a -> IO ()
setAttrib sp name = maybe (\_ _ -> putStrLn warn >> return ())
(\(a,_) -> let vap = vertexAttribPointer a
in \ih vad -> (($= (ih, vad)) vap))
(lookup name $ attribs sp)
where warn = "WARNING: attrib "++name++" is not active"
-- | Get the 'AttribLocation' associated with a named vertex
-- attribute.
getAttrib :: ShaderProgram -> String -> AttribLocation
getAttrib sp n = maybe (error msg) fst . lookup n $ attribs sp
where msg = "Attrib "++show n++" is not active"
-- | Enable a named vertex attribute.
enableAttrib :: ShaderProgram -> String -> IO ()
enableAttrib sp name = maybe (return ())
(($= Enabled) . vertexAttribArray . fst)
(lookup name $ attribs sp)
| coghex/abridgefaraway | src/GLUtil/ShaderProgram.hs | bsd-3-clause | 10,118 | 0 | 16 | 2,289 | 2,363 | 1,291 | 1,072 | 131 | 2 |
{-# LANGUAGE FlexibleInstances
, FlexibleContexts
, MultiParamTypeClasses
, ScopedTypeVariables
, TypeSynonymInstances
, TypeFamilies
, GeneralizedNewtypeDeriving
#-}
-----------------------------------------------------------------------------
-- |
-- Module : Diagrams.Backend.Image
-- Copyright : (c) 2011 Lyndon Maydwell (see LICENSE)
-- License : BSD-style (see LICENSE)
-- Maintainer : [email protected]
--
-- An Image-AST diagrams backend
--
-- "Abstract diagrams are rendered to particular formats by backends. Each
-- backend/vector space combination must be an instance of the Backend class. A
-- minimal complete definition consists of the three associated types and
-- implementations for withStyle and doRender."
{-
class (HasLinearMap v, Monoid (Render b v)) => Backend b v where
withStyle ::
b -> Style -> Transformation v -> Render b v -> Render b v
doRender :: b -> Options b v -> Render b v -> Result b v
adjustDia ::
Monoid m =>
b -> Options b v -> AnnDiagram b v m -> AnnDiagram b v m
renderDia ::
(InnerSpace v, OrderedField (Scalar v), Monoid m) =>
b -> Options b v -> AnnDiagram b v m -> Result b v
-- Defined in Graphics.Rendering.Diagrams.Core
-}
module Diagrams.Backend.Image where
import Diagrams.Prelude
import qualified Diagrams.AST as AST
-- | Token for identifying this backend.
data ImageBackend = ImageBackend
instance HasLinearMap v => Backend ImageBackend v where
data Render ImageBackend v = SR AST.Image
type Result ImageBackend v = AST.Image
data Options ImageBackend v = ImageOpts
withStyle _ _ _ r = r -- XXX FIXME
doRender _ _ (SR r) = r -- Ignore options for now
instance Monoid (Render ImageBackend v) where
mempty = undefined
mappend = undefined
| sordina/Diagrams-AST | src/Diagrams/Backend/Image.hs | bsd-3-clause | 1,839 | 0 | 8 | 413 | 163 | 95 | 68 | 20 | 0 |
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
-}
{-# LANGUAGE CPP #-}
module VarSet (
-- * Var, Id and TyVar set types
VarSet, IdSet, TyVarSet, CoVarSet, TyCoVarSet,
-- ** Manipulating these sets
emptyVarSet, unitVarSet, mkVarSet,
extendVarSet, extendVarSetList, extendVarSet_C,
elemVarSet, varSetElems, subVarSet,
unionVarSet, unionVarSets, mapUnionVarSet,
intersectVarSet, intersectsVarSet, disjointVarSet,
isEmptyVarSet, delVarSet, delVarSetList, delVarSetByKey,
minusVarSet, foldVarSet, filterVarSet,
transCloVarSet, fixVarSet,
lookupVarSet, lookupVarSetByName,
mapVarSet, sizeVarSet, seqVarSet,
elemVarSetByKey, partitionVarSet,
-- * Deterministic Var set types
DVarSet, DIdSet, DTyVarSet, DTyCoVarSet,
-- ** Manipulating these sets
emptyDVarSet, unitDVarSet, mkDVarSet,
extendDVarSet, extendDVarSetList,
elemDVarSet, dVarSetElems, subDVarSet,
unionDVarSet, unionDVarSets, mapUnionDVarSet,
intersectDVarSet, intersectsDVarSet, disjointDVarSet,
isEmptyDVarSet, delDVarSet, delDVarSetList,
minusDVarSet, foldDVarSet, filterDVarSet,
transCloDVarSet,
sizeDVarSet, seqDVarSet,
partitionDVarSet,
) where
#include "HsVersions.h"
import Var ( Var, TyVar, CoVar, TyCoVar, Id )
import Unique
import Name ( Name )
import UniqSet
import UniqDSet
import UniqFM( disjointUFM )
import UniqDFM( disjointUDFM )
-- | A non-deterministic set of variables.
-- See Note [Deterministic UniqFM] in UniqDFM for explanation why it's not
-- deterministic and why it matters. Use DVarSet if the set eventually
-- gets converted into a list or folded over in a way where the order
-- changes the generated code, for example when abstracting variables.
type VarSet = UniqSet Var
type IdSet = UniqSet Id
type TyVarSet = UniqSet TyVar
type CoVarSet = UniqSet CoVar
type TyCoVarSet = UniqSet TyCoVar
emptyVarSet :: VarSet
intersectVarSet :: VarSet -> VarSet -> VarSet
unionVarSet :: VarSet -> VarSet -> VarSet
unionVarSets :: [VarSet] -> VarSet
mapUnionVarSet :: (a -> VarSet) -> [a] -> VarSet
-- ^ map the function oer the list, and union the results
varSetElems :: VarSet -> [Var]
unitVarSet :: Var -> VarSet
extendVarSet :: VarSet -> Var -> VarSet
extendVarSetList:: VarSet -> [Var] -> VarSet
elemVarSet :: Var -> VarSet -> Bool
delVarSet :: VarSet -> Var -> VarSet
delVarSetList :: VarSet -> [Var] -> VarSet
minusVarSet :: VarSet -> VarSet -> VarSet
isEmptyVarSet :: VarSet -> Bool
mkVarSet :: [Var] -> VarSet
foldVarSet :: (Var -> a -> a) -> a -> VarSet -> a
lookupVarSet :: VarSet -> Var -> Maybe Var
-- Returns the set element, which may be
-- (==) to the argument, but not the same as
lookupVarSetByName :: VarSet -> Name -> Maybe Var
mapVarSet :: (Var -> Var) -> VarSet -> VarSet
sizeVarSet :: VarSet -> Int
filterVarSet :: (Var -> Bool) -> VarSet -> VarSet
extendVarSet_C :: (Var->Var->Var) -> VarSet -> Var -> VarSet
delVarSetByKey :: VarSet -> Unique -> VarSet
elemVarSetByKey :: Unique -> VarSet -> Bool
partitionVarSet :: (Var -> Bool) -> VarSet -> (VarSet, VarSet)
emptyVarSet = emptyUniqSet
unitVarSet = unitUniqSet
extendVarSet = addOneToUniqSet
extendVarSetList= addListToUniqSet
intersectVarSet = intersectUniqSets
intersectsVarSet:: VarSet -> VarSet -> Bool -- True if non-empty intersection
disjointVarSet :: VarSet -> VarSet -> Bool -- True if empty intersection
subVarSet :: VarSet -> VarSet -> Bool -- True if first arg is subset of second
-- (s1 `intersectsVarSet` s2) doesn't compute s2 if s1 is empty;
-- ditto disjointVarSet, subVarSet
unionVarSet = unionUniqSets
unionVarSets = unionManyUniqSets
varSetElems = uniqSetToList
elemVarSet = elementOfUniqSet
minusVarSet = minusUniqSet
delVarSet = delOneFromUniqSet
delVarSetList = delListFromUniqSet
isEmptyVarSet = isEmptyUniqSet
mkVarSet = mkUniqSet
foldVarSet = foldUniqSet
lookupVarSet = lookupUniqSet
lookupVarSetByName = lookupUniqSet
mapVarSet = mapUniqSet
sizeVarSet = sizeUniqSet
filterVarSet = filterUniqSet
extendVarSet_C = addOneToUniqSet_C
delVarSetByKey = delOneFromUniqSet_Directly
elemVarSetByKey = elemUniqSet_Directly
partitionVarSet = partitionUniqSet
mapUnionVarSet get_set xs = foldr (unionVarSet . get_set) emptyVarSet xs
-- See comments with type signatures
intersectsVarSet s1 s2 = not (s1 `disjointVarSet` s2)
disjointVarSet s1 s2 = disjointUFM s1 s2
subVarSet s1 s2 = isEmptyVarSet (s1 `minusVarSet` s2)
fixVarSet :: (VarSet -> VarSet) -- Map the current set to a new set
-> VarSet -> VarSet
-- (fixVarSet f s) repeatedly applies f to the set s,
-- until it reaches a fixed point.
fixVarSet fn vars
| new_vars `subVarSet` vars = vars
| otherwise = fixVarSet fn new_vars
where
new_vars = fn vars
transCloVarSet :: (VarSet -> VarSet)
-- Map some variables in the set to
-- extra variables that should be in it
-> VarSet -> VarSet
-- (transCloVarSet f s) repeatedly applies f to new candidates, adding any
-- new variables to s that it finds thereby, until it reaches a fixed point.
--
-- The function fn could be (Var -> VarSet), but we use (VarSet -> VarSet)
-- for efficiency, so that the test can be batched up.
-- It's essential that fn will work fine if given new candidates
-- one at at time; ie fn {v1,v2} = fn v1 `union` fn v2
-- Use fixVarSet if the function needs to see the whole set all at once
transCloVarSet fn seeds
= go seeds seeds
where
go :: VarSet -- Accumulating result
-> VarSet -- Work-list; un-processed subset of accumulating result
-> VarSet
-- Specification: go acc vs = acc `union` transClo fn vs
go acc candidates
| isEmptyVarSet new_vs = acc
| otherwise = go (acc `unionVarSet` new_vs) new_vs
where
new_vs = fn candidates `minusVarSet` acc
seqVarSet :: VarSet -> ()
seqVarSet s = sizeVarSet s `seq` ()
-- Deterministic VarSet
-- See Note [Deterministic UniqFM] in UniqDFM for explanation why we need
-- DVarSet.
type DVarSet = UniqDSet Var
type DIdSet = UniqDSet Id
type DTyVarSet = UniqDSet TyVar
type DTyCoVarSet = UniqDSet TyCoVar
emptyDVarSet :: DVarSet
emptyDVarSet = emptyUniqDSet
unitDVarSet :: Var -> DVarSet
unitDVarSet = unitUniqDSet
mkDVarSet :: [Var] -> DVarSet
mkDVarSet = mkUniqDSet
extendDVarSet :: DVarSet -> Var -> DVarSet
extendDVarSet = addOneToUniqDSet
elemDVarSet :: Var -> DVarSet -> Bool
elemDVarSet = elementOfUniqDSet
dVarSetElems :: DVarSet -> [Var]
dVarSetElems = uniqDSetToList
subDVarSet :: DVarSet -> DVarSet -> Bool
subDVarSet s1 s2 = isEmptyDVarSet (s1 `minusDVarSet` s2)
unionDVarSet :: DVarSet -> DVarSet -> DVarSet
unionDVarSet = unionUniqDSets
unionDVarSets :: [DVarSet] -> DVarSet
unionDVarSets = unionManyUniqDSets
-- | Map the function over the list, and union the results
mapUnionDVarSet :: (a -> DVarSet) -> [a] -> DVarSet
mapUnionDVarSet get_set xs = foldr (unionDVarSet . get_set) emptyDVarSet xs
intersectDVarSet :: DVarSet -> DVarSet -> DVarSet
intersectDVarSet = intersectUniqDSets
-- | True if empty intersection
disjointDVarSet :: DVarSet -> DVarSet -> Bool
disjointDVarSet s1 s2 = disjointUDFM s1 s2
-- | True if non-empty intersection
intersectsDVarSet :: DVarSet -> DVarSet -> Bool
intersectsDVarSet s1 s2 = not (s1 `disjointDVarSet` s2)
isEmptyDVarSet :: DVarSet -> Bool
isEmptyDVarSet = isEmptyUniqDSet
delDVarSet :: DVarSet -> Var -> DVarSet
delDVarSet = delOneFromUniqDSet
minusDVarSet :: DVarSet -> DVarSet -> DVarSet
minusDVarSet = minusUniqDSet
foldDVarSet :: (Var -> a -> a) -> a -> DVarSet -> a
foldDVarSet = foldUniqDSet
filterDVarSet :: (Var -> Bool) -> DVarSet -> DVarSet
filterDVarSet = filterUniqDSet
sizeDVarSet :: DVarSet -> Int
sizeDVarSet = sizeUniqDSet
-- | Partition DVarSet according to the predicate given
partitionDVarSet :: (Var -> Bool) -> DVarSet -> (DVarSet, DVarSet)
partitionDVarSet = partitionUniqDSet
-- | Delete a list of variables from DVarSet
delDVarSetList :: DVarSet -> [Var] -> DVarSet
delDVarSetList = delListFromUniqDSet
seqDVarSet :: DVarSet -> ()
seqDVarSet s = sizeDVarSet s `seq` ()
-- | Add a list of variables to DVarSet
extendDVarSetList :: DVarSet -> [Var] -> DVarSet
extendDVarSetList = addListToUniqDSet
-- | transCloVarSet for DVarSet
transCloDVarSet :: (DVarSet -> DVarSet)
-- Map some variables in the set to
-- extra variables that should be in it
-> DVarSet -> DVarSet
-- (transCloDVarSet f s) repeatedly applies f to new candidates, adding any
-- new variables to s that it finds thereby, until it reaches a fixed point.
--
-- The function fn could be (Var -> DVarSet), but we use (DVarSet -> DVarSet)
-- for efficiency, so that the test can be batched up.
-- It's essential that fn will work fine if given new candidates
-- one at at time; ie fn {v1,v2} = fn v1 `union` fn v2
transCloDVarSet fn seeds
= go seeds seeds
where
go :: DVarSet -- Accumulating result
-> DVarSet -- Work-list; un-processed subset of accumulating result
-> DVarSet
-- Specification: go acc vs = acc `union` transClo fn vs
go acc candidates
| isEmptyDVarSet new_vs = acc
| otherwise = go (acc `unionDVarSet` new_vs) new_vs
where
new_vs = fn candidates `minusDVarSet` acc
| nushio3/ghc | compiler/basicTypes/VarSet.hs | bsd-3-clause | 9,743 | 0 | 10 | 2,188 | 1,844 | 1,062 | 782 | 173 | 1 |
{-# LANGUAGE MultiParamTypeClasses, TypeSynonymInstances, FlexibleInstances #-}
{- |
Module : $Header$
Description : Extension of CASL2SubCFOL to CoCASL
Copyright : (c) Till Mossakowski, C.Maeder, Uni Bremen 2006
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : provisional
Portability : non-portable (imports Logic.Comorphism)
coding out partiality, lifted to the level of CoCASL
-}
module Comorphisms.CoCASL2CoSubCFOL where
import Logic.Logic
import Logic.Comorphism
-- CoCASL
import CoCASL.Logic_CoCASL
import CoCASL.AS_CoCASL
import CoCASL.StatAna
import CoCASL.Sublogic
import CASL.Sublogic as SL
import CASL.AS_Basic_CASL
import CASL.Sign
import CASL.Morphism
import CASL.Fold
import CASL.Simplify
import Comorphisms.CASL2SubCFOL
import qualified Data.Map as Map
import qualified Data.Set as Set
import Common.AS_Annotation
import Common.ProofUtils
-- | The identity of the comorphism
data CoCASL2CoSubCFOL = CoCASL2CoSubCFOL deriving (Show)
instance Language CoCASL2CoSubCFOL -- default definition is okay
instance Comorphism CoCASL2CoSubCFOL
CoCASL CoCASL_Sublogics
C_BASIC_SPEC CoCASLFORMULA SYMB_ITEMS SYMB_MAP_ITEMS
CSign
CoCASLMor
Symbol RawSymbol ()
CoCASL CoCASL_Sublogics
C_BASIC_SPEC CoCASLFORMULA SYMB_ITEMS SYMB_MAP_ITEMS
CSign
CoCASLMor
Symbol RawSymbol () where
sourceLogic CoCASL2CoSubCFOL = CoCASL
sourceSublogic CoCASL2CoSubCFOL = SL.caslTop
targetLogic CoCASL2CoSubCFOL = CoCASL
mapSublogic CoCASL2CoSubCFOL sl = Just $
if has_part sl then sl
{ has_part = False -- partiality is coded out
, has_pred = True
, which_logic = max Horn $ which_logic sl
, has_eq = True} else sl
map_theory CoCASL2CoSubCFOL (sig, sens) =
let bsrts = sortsWithBottom (formulaTreatment defaultCASL2SubCFOL)
sig $ Set.unions $ map (botCoFormulaSorts . sentence) sens
e = encodeSig bsrts sig
sens1 = map (mapNamed mapFORMULA) $ generateAxioms
(uniqueBottom defaultCASL2SubCFOL) bsrts sig
sens2 = map (mapNamed (simplifyFormula simC_FORMULA
. codeCoFormula bsrts)) sens
in return (e, nameAndDisambiguate $ sens1 ++ sens2)
map_morphism CoCASL2CoSubCFOL mor@Morphism {msource = src, mtarget = tar} =
let mkBSrts s = sortsWithBottom
(formulaTreatment defaultCASL2SubCFOL) s Set.empty
in return mor
{ msource = encodeSig (mkBSrts src) src
, mtarget = encodeSig (mkBSrts tar) tar
, op_map = Map.map (\ (i, _) -> (i, Total)) $ op_map mor }
map_sentence CoCASL2CoSubCFOL sig sen =
return $ simplifyFormula simC_FORMULA $ codeCoFormula
(sortsWithBottom (formulaTreatment defaultCASL2SubCFOL)
sig $ botCoFormulaSorts sen) sen
map_symbol CoCASL2CoSubCFOL _ s =
Set.singleton s {symbType = totalizeSymbType $ symbType s}
has_model_expansion CoCASL2CoSubCFOL = True
is_weakly_amalgamable CoCASL2CoSubCFOL = True
codeCoRecord :: Set.Set SORT
-> Record C_FORMULA (FORMULA C_FORMULA) (TERM C_FORMULA)
codeCoRecord bsrts =
codeRecord (uniqueBottom defaultCASL2SubCFOL) bsrts $ codeC_FORMULA bsrts
codeCoFormula :: Set.Set SORT -> FORMULA C_FORMULA -> FORMULA C_FORMULA
codeCoFormula = foldFormula . codeCoRecord
codeC_FORMULA :: Set.Set SORT -> C_FORMULA -> C_FORMULA
codeC_FORMULA bsrts = foldC_Formula (codeCoRecord bsrts) mapCoRecord
{foldCoSort_gen_ax = \ _ s o b -> CoSort_gen_ax s (map totalizeOpSymb o) b}
simC_FORMULA :: C_FORMULA -> C_FORMULA
simC_FORMULA = foldC_Formula (simplifyRecord simC_FORMULA) mapCoRecord
botCoSorts :: C_FORMULA -> Set.Set SORT
botCoSorts =
foldC_Formula (botSorts botCoSorts) (constCoRecord Set.unions Set.empty)
botCoFormulaSorts :: FORMULA C_FORMULA -> Set.Set SORT
botCoFormulaSorts = foldFormula $ botSorts botCoSorts
| mariefarrell/Hets | Comorphisms/CoCASL2CoSubCFOL.hs | gpl-2.0 | 4,097 | 0 | 15 | 960 | 906 | 474 | 432 | 81 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : XMonad.Hooks.DebugStack
-- Copyright : (c) Brandon S Allbery KF8NH, 2012
-- License : BSD3-style (see LICENSE)
--
-- Maintainer : [email protected]
-- Stability : unstable
-- Portability : not portable
--
-- Dump the state of the 'StackSet'. A @logHook@ and @handleEventHook@ are
-- also provided.
--
-----------------------------------------------------------------------------
module XMonad.Hooks.DebugStack (debugStack
,debugStackString
,debugStackLogHook
,debugStackEventHook
) where
import XMonad.Core
import qualified XMonad.StackSet as W
import XMonad.Util.DebugWindow
import Graphics.X11.Types (Window)
import Graphics.X11.Xlib.Extras (Event)
import Control.Monad (foldM)
import Data.Map (toList)
import Data.Monoid (All(..))
-- | Print the state of the current window stack to @stderr@, which for most
-- installations goes to @~/.xsession-errors@. "XMonad.Util.DebugWindow"
-- is used to display the individual windows.
debugStack :: X ()
debugStack = debugStackString >>= trace
-- | The above packaged as a 'logHook'. (Currently this is identical.)
debugStackLogHook :: X ()
debugStackLogHook = debugStack
-- | The above packaged as a 'handleEventHook'. You almost certainly do not
-- want to use this unconditionally, as it will cause massive amounts of
-- output and possibly slow @xmonad@ down severely.
debugStackEventHook :: Event -> X All
debugStackEventHook _ = debugStack >> return (All True)
-- | Dump the state of the current 'StackSet' as a multiline 'String'.
-- @
-- stack [ mm
-- ,(*) ww
-- , ww
-- ]
-- float { ww
-- , ww
-- }
-- @
--
-- One thing I'm not sure of is where the zipper is when focus is on a
-- floating window.
debugStackString :: X String
debugStackString = withWindowSet $ \ws -> do
s <- emit "stack" ("[","]") (W.peek ws) $ W.index ws
f <- emit "float" ("{","}") (W.peek ws) $ map fst $ toList $ W.floating ws
return $ s ++ f
where
emit :: String -> (String,String) -> Maybe Window -> [Window] -> X String
emit title (lb,rb) _ [] = return $ title ++ " " ++ lb ++ rb ++ "]\n"
emit title (lb,rb) focused ws = do
(_,_,_,_,ss) <- foldM emit' (title,lb,rb,focused,"") ws
return $ ss ++
replicate (length title + 1) ' ' ++
rb ++
"\n"
emit' :: (String,String,String,Maybe Window,String)
-> Window
-> X (String,String,String,Maybe Window,String)
emit' (t,l,r,f,a) w = do
w' <- emit'' f w
return (replicate (length t) ' '
,',' : replicate (length l - 1) ' '
,r
,f
,a ++ t ++ " " ++ l ++ w' ++ "\n"
)
emit'' :: Maybe Window -> Window -> X String
emit'' focus win =
let fi f = if win == f then "(*) " else " "
in (maybe " " fi focus ++) `fmap` debugWindow win
| jthornber/XMonadContrib | XMonad/Hooks/DebugStack.hs | bsd-3-clause | 3,459 | 0 | 16 | 1,207 | 729 | 408 | 321 | 45 | 3 |
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="ar-SA">
<title>FuzzDB Files</title>
<maps>
<homeID>fuzzdb</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | kingthorin/zap-extensions | addOns/fuzzdb/src/main/javahelp/help_ar_SA/helpset_ar_SA.hs | apache-2.0 | 960 | 77 | 66 | 156 | 407 | 206 | 201 | -1 | -1 |
module Main where
import Control.Applicative ((<$>))
import Control.Monad (replicateM)
import qualified Data.HashMap.Strict as HM
import Data.List (delete)
import Data.Maybe
import Test.HUnit (Assertion, assert)
import Test.Framework (Test, defaultMain)
import Test.Framework.Providers.HUnit (testCase)
import Test.Framework.Providers.QuickCheck2 (testProperty)
import Test.QuickCheck
issue32 :: Assertion
issue32 = assert $ isJust $ HM.lookup 7 m'
where
ns = [0..16] :: [Int]
m = HM.fromList (zip ns (repeat []))
m' = HM.delete 10 m
------------------------------------------------------------------------
-- Issue #39
-- First regression
issue39 :: Assertion
issue39 = assert $ hm1 == hm2
where
hm1 = HM.fromList ([a, b] `zip` [1, 1 :: Int ..])
hm2 = HM.fromList ([b, a] `zip` [1, 1 :: Int ..])
a = (1, -1) :: (Int, Int)
b = (-1, 1) :: (Int, Int)
-- Second regression
newtype Keys = Keys [Int]
deriving Show
instance Arbitrary Keys where
arbitrary = sized $ \l -> do
pis <- replicateM (l+1) positiveInt
return (Keys $ prefixSum pis)
shrink (Keys ls) =
let l = length ls
in if l == 1
then []
else [ Keys (dropAt i ls) | i <- [0..l-1] ]
positiveInt :: Gen Int
positiveInt = (+1) . abs <$> arbitrary
prefixSum :: [Int] -> [Int]
prefixSum = loop 0
where
loop _ [] = []
loop prefix (l:ls) = let n = l + prefix
in n : loop n ls
dropAt :: Int -> [a] -> [a]
dropAt _ [] = []
dropAt i (l:ls) | i == 0 = ls
| otherwise = l : dropAt (i-1) ls
propEqAfterDelete :: Keys -> Bool
propEqAfterDelete (Keys keys) =
let keyMap = mapFromKeys keys
k = head keys
in HM.delete k keyMap == mapFromKeys (delete k keys)
mapFromKeys :: [Int] -> HM.HashMap Int ()
mapFromKeys keys = HM.fromList (zip keys (repeat ()))
------------------------------------------------------------------------
-- * Test list
tests :: [Test]
tests =
[
testCase "issue32" issue32
, testCase "issue39a" issue39
, testProperty "issue39b" propEqAfterDelete
]
------------------------------------------------------------------------
-- * Test harness
main :: IO ()
main = defaultMain tests
| pacak/cuddly-bassoon | unordered-containers-0.2.8.0/tests/Regressions.hs | bsd-3-clause | 2,248 | 0 | 13 | 535 | 834 | 460 | 374 | 59 | 2 |
module Risers where
{-@ LIQUID "--totality" @-}
{-@ predicate NonNull X = ((len X) > 0) @-}
{- risers :: (Ord a) => zs:[a] -> {v: [[a]] | ((NonNull zs) => (NonNull v)) } @-}
risers []
= []
risers [x]
= [[x]]
risers (x:y:etc)
= if x <= y then (x:s):ss else [x]:(s:ss)
where (s:ss) = risers [] -- insert partiality (y:etc)
| mightymoose/liquidhaskell | tests/neg/risers.hs | bsd-3-clause | 352 | 0 | 8 | 94 | 113 | 64 | 49 | 8 | 2 |
{-# LANGUAGE PolyKinds, TypeFamilies #-}
module Bug where
import GHC.Exts
class HasRep a where
type Rep a :: TYPE r
| sdiehl/ghc | testsuite/tests/indexed-types/should_compile/T12938.hs | bsd-3-clause | 121 | 0 | 7 | 25 | 29 | 17 | 12 | -1 | -1 |
-- | Imported by 'Threaded', since a TH splice can't be used in the
-- module where it is defined.
module Threaded_TH where
import Control.Concurrent (forkOS)
import Language.Haskell.TH.Syntax (Exp (LitE), Lit (IntegerL), Q, runIO)
-- | forkOS requires the threaded RTS, so this TH fails if haddock was
-- built without @-threaded@.
forkTH :: Q Exp
forkTH = do
_ <- runIO (forkOS (return ()))
return (LitE (IntegerL 0))
| Acidburn0zzz/haddock | html-test/src/Threaded_TH.hs | bsd-2-clause | 426 | 0 | 13 | 75 | 102 | 59 | 43 | 7 | 1 |
import Control.Monad
import Data.List
allAscii = ['a'..'z']
countGemStones = foldl intersect allAscii
main :: IO ()
main = do
n <- readLn :: IO Int
input <- replicateM n getLine
let ans = countGemStones input
print (length ans)
| mgrebenets/hackerrank | alg/strings/gem-stones.hs | mit | 247 | 0 | 10 | 57 | 95 | 46 | 49 | 10 | 1 |
module Feature.AndOrParamsSpec where
import Network.Wai (Application)
import Network.HTTP.Types
import Test.Hspec
import Test.Hspec.Wai
import Test.Hspec.Wai.JSON
import PostgREST.Config.PgVersion (PgVersion, pgVersion112)
import Protolude hiding (get)
import SpecHelper
spec :: PgVersion -> SpecWith ((), Application)
spec actualPgVersion =
describe "and/or params used for complex boolean logic" $ do
context "used with GET" $ do
context "or param" $ do
it "can do simple logic" $
get "/entities?or=(id.eq.1,id.eq.2)&select=id" `shouldRespondWith`
[json|[{ "id": 1 }, { "id": 2 }]|] { matchHeaders = [matchContentTypeJson] }
it "can negate simple logic" $
get "/entities?not.or=(id.eq.1,id.eq.2)&select=id" `shouldRespondWith`
[json|[{ "id": 3 }, { "id": 4 }]|] { matchHeaders = [matchContentTypeJson] }
it "can be combined with traditional filters" $
get "/entities?or=(id.eq.1,id.eq.2)&name=eq.entity 1&select=id" `shouldRespondWith`
[json|[{ "id": 1 }]|] { matchHeaders = [matchContentTypeJson] }
context "embedded levels" $ do
it "can do logic on the second level" $
get "/entities?child_entities.or=(id.eq.1,name.eq.child entity 2)&select=id,child_entities(id)" `shouldRespondWith`
[json|[
{"id": 1, "child_entities": [ { "id": 1 }, { "id": 2 } ] }, { "id": 2, "child_entities": []},
{"id": 3, "child_entities": []}, {"id": 4, "child_entities": []}
]|] { matchHeaders = [matchContentTypeJson] }
it "can do logic on the third level" $
get "/entities?child_entities.grandchild_entities.or=(id.eq.1,id.eq.2)&select=id,child_entities(id,grandchild_entities(id))"
`shouldRespondWith`
[json|[
{"id": 1, "child_entities": [
{ "id": 1, "grandchild_entities": [ { "id": 1 }, { "id": 2 } ]},
{ "id": 2, "grandchild_entities": []},
{ "id": 4, "grandchild_entities": []},
{ "id": 5, "grandchild_entities": []}
]},
{"id": 2, "child_entities": [
{ "id": 3, "grandchild_entities": []},
{ "id": 6, "grandchild_entities": []}
]},
{"id": 3, "child_entities": []},
{"id": 4, "child_entities": []}
]|]
context "and/or params combined" $ do
it "can be nested inside the same expression" $
get "/entities?or=(and(name.eq.entity 2,id.eq.2),and(name.eq.entity 1,id.eq.1))&select=id" `shouldRespondWith`
[json|[{ "id": 1 }, { "id": 2 }]|] { matchHeaders = [matchContentTypeJson] }
it "can be negated while nested" $
get "/entities?or=(not.and(name.eq.entity 2,id.eq.2),not.and(name.eq.entity 1,id.eq.1))&select=id" `shouldRespondWith`
[json|[{ "id": 1 }, { "id": 2 }, { "id": 3 }, { "id": 4 }]|] { matchHeaders = [matchContentTypeJson] }
it "can be combined unnested" $
get "/entities?and=(id.eq.1,name.eq.entity 1)&or=(id.eq.1,id.eq.2)&select=id" `shouldRespondWith`
[json|[{ "id": 1 }]|] { matchHeaders = [matchContentTypeJson] }
context "operators inside and/or" $ do
it "can handle eq and neq" $
get "/entities?and=(id.eq.1,id.neq.2))&select=id" `shouldRespondWith`
[json|[{ "id": 1 }]|] { matchHeaders = [matchContentTypeJson] }
it "can handle lt and gt" $
get "/entities?or=(id.lt.2,id.gt.3)&select=id" `shouldRespondWith`
[json|[{ "id": 1 }, { "id": 4 }]|] { matchHeaders = [matchContentTypeJson] }
it "can handle lte and gte" $
get "/entities?or=(id.lte.2,id.gte.3)&select=id" `shouldRespondWith`
[json|[{ "id": 1 }, { "id": 2 }, { "id": 3 }, { "id": 4 }]|] { matchHeaders = [matchContentTypeJson] }
it "can handle like and ilike" $
get "/entities?or=(name.like.*1,name.ilike.*ENTITY 2)&select=id" `shouldRespondWith`
[json|[{ "id": 1 }, { "id": 2 }]|] { matchHeaders = [matchContentTypeJson] }
it "can handle in" $
get "/entities?or=(id.in.(1,2),id.in.(3,4))&select=id" `shouldRespondWith`
[json|[{ "id": 1 }, { "id": 2 }, { "id": 3 }, { "id": 4 }]|] { matchHeaders = [matchContentTypeJson] }
it "can handle is" $
get "/entities?and=(name.is.null,arr.is.null)&select=id" `shouldRespondWith`
[json|[{ "id": 4 }]|] { matchHeaders = [matchContentTypeJson] }
it "can handle fts" $ do
get "/entities?or=(text_search_vector.fts.bar,text_search_vector.fts.baz)&select=id" `shouldRespondWith`
[json|[{ "id": 1 }, { "id": 2 }]|] { matchHeaders = [matchContentTypeJson] }
get "/tsearch?or=(text_search_vector.plfts(german).Art%20Spass, text_search_vector.plfts(french).amusant%20impossible, text_search_vector.fts(english).impossible)" `shouldRespondWith`
[json|[
{"text_search_vector": "'fun':5 'imposs':9 'kind':3" },
{"text_search_vector": "'amus':5 'fair':7 'impossibl':9 'peu':4" },
{"text_search_vector": "'art':4 'spass':5 'unmog':7"}
]|] { matchHeaders = [matchContentTypeJson] }
when (actualPgVersion >= pgVersion112) $
it "can handle wfts (websearch_to_tsquery)" $
get "/tsearch?or=(text_search_vector.plfts(german).Art,text_search_vector.plfts(french).amusant,text_search_vector.not.wfts(english).impossible)"
`shouldRespondWith`
[json|[
{"text_search_vector": "'also':2 'fun':3 'possibl':8" },
{"text_search_vector": "'ate':3 'cat':2 'fat':1 'rat':4" },
{"text_search_vector": "'amus':5 'fair':7 'impossibl':9 'peu':4" },
{"text_search_vector": "'art':4 'spass':5 'unmog':7" }
]|]
{ matchHeaders = [matchContentTypeJson] }
it "can handle cs and cd" $
get "/entities?or=(arr.cs.{1,2,3},arr.cd.{1})&select=id" `shouldRespondWith`
[json|[{ "id": 1 },{ "id": 3 }]|] { matchHeaders = [matchContentTypeJson] }
it "can handle range operators" $ do
get "/ranges?range=eq.[1,3]&select=id" `shouldRespondWith`
[json|[{ "id": 1 }]|] { matchHeaders = [matchContentTypeJson] }
get "/ranges?range=neq.[1,3]&select=id" `shouldRespondWith`
[json|[{ "id": 2 }, { "id": 3 }, { "id": 4 }]|] { matchHeaders = [matchContentTypeJson] }
get "/ranges?range=lt.[1,10]&select=id" `shouldRespondWith`
[json|[{ "id": 1 }]|] { matchHeaders = [matchContentTypeJson] }
get "/ranges?range=gt.[8,11]&select=id" `shouldRespondWith`
[json|[{ "id": 4 }]|] { matchHeaders = [matchContentTypeJson] }
get "/ranges?range=lte.[1,3]&select=id" `shouldRespondWith`
[json|[{ "id": 1 }]|] { matchHeaders = [matchContentTypeJson] }
get "/ranges?range=gte.[2,3]&select=id" `shouldRespondWith`
[json|[{ "id": 2 }, { "id": 3 }, { "id": 4 }]|] { matchHeaders = [matchContentTypeJson] }
get "/ranges?range=cs.[1,2]&select=id" `shouldRespondWith`
[json|[{ "id": 1 }]|] { matchHeaders = [matchContentTypeJson] }
get "/ranges?range=cd.[1,6]&select=id" `shouldRespondWith`
[json|[{ "id": 1 }, { "id": 2 }]|] { matchHeaders = [matchContentTypeJson] }
get "/ranges?range=ov.[0,4]&select=id" `shouldRespondWith`
[json|[{ "id": 1 }, { "id": 2 }]|] { matchHeaders = [matchContentTypeJson] }
get "/ranges?range=sl.[9,10]&select=id" `shouldRespondWith`
[json|[{ "id": 1 }, { "id": 2 }]|] { matchHeaders = [matchContentTypeJson] }
get "/ranges?range=sr.[3,4]&select=id" `shouldRespondWith`
[json|[{ "id": 3 }, { "id": 4 }]|] { matchHeaders = [matchContentTypeJson] }
get "/ranges?range=nxr.[4,7]&select=id" `shouldRespondWith`
[json|[{ "id": 1 }, { "id": 2 }]|] { matchHeaders = [matchContentTypeJson] }
get "/ranges?range=nxl.[4,7]&select=id" `shouldRespondWith`
[json|[{ "id": 3 }, { "id": 4 }]|] { matchHeaders = [matchContentTypeJson] }
get "/ranges?range=adj.(3,10]&select=id" `shouldRespondWith`
[json|[{ "id": 1 }]|] { matchHeaders = [matchContentTypeJson] }
it "can handle array operators" $ do
get "/entities?arr=eq.{1,2,3}&select=id" `shouldRespondWith`
[json|[{ "id": 3 }]|] { matchHeaders = [matchContentTypeJson] }
get "/entities?arr=neq.{1,2}&select=id" `shouldRespondWith`
[json|[{ "id": 1 }, { "id": 3 }]|] { matchHeaders = [matchContentTypeJson] }
get "/entities?arr=lt.{2,3}&select=id" `shouldRespondWith`
[json|[{ "id": 1 }, { "id": 2 }, { "id": 3 }]|] { matchHeaders = [matchContentTypeJson] }
get "/entities?arr=lt.{2,0}&select=id" `shouldRespondWith`
[json|[{ "id": 1 }, { "id": 2 }, { "id": 3 }]|] { matchHeaders = [matchContentTypeJson] }
get "/entities?arr=gt.{1,1}&select=id" `shouldRespondWith`
[json|[{ "id": 2 }, { "id": 3 }]|] { matchHeaders = [matchContentTypeJson] }
get "/entities?arr=gt.{3}&select=id" `shouldRespondWith`
[json|[]|] { matchHeaders = [matchContentTypeJson] }
get "/entities?arr=lte.{2,1}&select=id" `shouldRespondWith`
[json|[{ "id": 1 }, { "id": 2 }, { "id": 3 }]|] { matchHeaders = [matchContentTypeJson] }
get "/entities?arr=lte.{1,2,3}&select=id" `shouldRespondWith`
[json|[{ "id": 1 }, { "id": 2 }, { "id": 3 }]|] { matchHeaders = [matchContentTypeJson] }
get "/entities?arr=lte.{1,2}&select=id" `shouldRespondWith`
[json|[{ "id": 1 }, { "id": 2 }]|] { matchHeaders = [matchContentTypeJson] }
get "/entities?arr=cs.{1,2}&select=id" `shouldRespondWith`
[json|[{ "id": 2 }, { "id": 3 }]|] { matchHeaders = [matchContentTypeJson] }
get "/entities?arr=cd.{1,2,6}&select=id" `shouldRespondWith`
[json|[{ "id": 1 }, { "id": 2 }]|] { matchHeaders = [matchContentTypeJson] }
get "/entities?arr=ov.{3}&select=id" `shouldRespondWith`
[json|[{ "id": 3 }]|] { matchHeaders = [matchContentTypeJson] }
get "/entities?arr=ov.{2,3}&select=id" `shouldRespondWith`
[json|[{ "id": 2 }, { "id": 3 }]|] { matchHeaders = [matchContentTypeJson] }
context "operators with not" $ do
it "eq, cs, like can be negated" $
get "/entities?and=(arr.not.cs.{1,2,3},and(id.not.eq.2,name.not.like.*3))&select=id" `shouldRespondWith`
[json|[{ "id": 1}]|] { matchHeaders = [matchContentTypeJson] }
it "in, is, fts can be negated" $
get "/entities?and=(id.not.in.(1,3),and(name.not.is.null,text_search_vector.not.fts.foo))&select=id" `shouldRespondWith`
[json|[{ "id": 2}]|] { matchHeaders = [matchContentTypeJson] }
it "lt, gte, cd can be negated" $
get "/entities?and=(arr.not.cd.{1},or(id.not.lt.1,id.not.gte.3))&select=id" `shouldRespondWith`
[json|[{"id": 2}, {"id": 3}]|] { matchHeaders = [matchContentTypeJson] }
it "gt, lte, ilike can be negated" $
get "/entities?and=(name.not.ilike.*ITY2,or(id.not.gt.4,id.not.lte.1))&select=id" `shouldRespondWith`
[json|[{"id": 1}, {"id": 2}, {"id": 3}]|] { matchHeaders = [matchContentTypeJson] }
context "and/or params with quotes" $ do
it "eq can have quotes" $
get "/grandchild_entities?or=(name.eq.\"(grandchild,entity,4)\",name.eq.\"(grandchild,entity,5)\")&select=id" `shouldRespondWith`
[json|[{ "id": 4 }, { "id": 5 }]|] { matchHeaders = [matchContentTypeJson] }
it "like and ilike can have quotes" $
get "/grandchild_entities?or=(name.like.\"*ity,4*\",name.ilike.\"*ITY,5)\")&select=id" `shouldRespondWith`
[json|[{ "id": 4 }, { "id": 5 }]|] { matchHeaders = [matchContentTypeJson] }
it "in can have quotes" $
get "/grandchild_entities?or=(id.in.(\"1\",\"2\"),id.in.(\"3\",\"4\"))&select=id" `shouldRespondWith`
[json|[{ "id": 1 }, { "id": 2 }, { "id": 3 }, { "id": 4 }]|] { matchHeaders = [matchContentTypeJson] }
it "allows whitespace" $
get "/entities?and=( and ( id.in.( 1, 2, 3 ) , id.eq.3 ) , or ( id.eq.2 , id.eq.3 ) )&select=id" `shouldRespondWith`
[json|[{ "id": 3 }]|] { matchHeaders = [matchContentTypeJson] }
context "multiple and/or conditions" $ do
it "cannot have zero conditions" $
get "/entities?or=()" `shouldRespondWith`
[json|{
"details": "unexpected \")\" expecting field name (* or [a..z0..9_]), negation operator (not) or logic operator (and, or)",
"message": "\"failed to parse logic tree (())\" (line 1, column 4)"
}|] { matchStatus = 400, matchHeaders = [matchContentTypeJson] }
it "can have a single condition" $ do
get "/entities?or=(id.eq.1)&select=id" `shouldRespondWith`
[json|[{"id":1}]|] { matchHeaders = [matchContentTypeJson] }
get "/entities?and=(id.eq.1)&select=id" `shouldRespondWith`
[json|[{"id":1}]|] { matchHeaders = [matchContentTypeJson] }
it "can have three conditions" $ do
get "/grandchild_entities?or=(id.eq.1, id.eq.2, id.eq.3)&select=id" `shouldRespondWith`
[json|[{"id":1}, {"id":2}, {"id":3}]|] { matchHeaders = [matchContentTypeJson] }
get "/grandchild_entities?and=(id.in.(1,2), id.in.(3,1), id.in.(1,4))&select=id" `shouldRespondWith`
[json|[{"id":1}]|] { matchHeaders = [matchContentTypeJson] }
it "can have four conditions combining and/or" $ do
get "/grandchild_entities?or=( id.eq.1, id.eq.2, and(id.in.(1,3), id.in.(2,3)), id.eq.4 )&select=id" `shouldRespondWith`
[json|[{"id":1}, {"id":2}, {"id":3}, {"id":4}]|] { matchHeaders = [matchContentTypeJson] }
get "/grandchild_entities?and=( id.eq.1, not.or(id.eq.2, id.eq.3), id.in.(1,4), or(id.eq.1, id.eq.4) )&select=id" `shouldRespondWith`
[json|[{"id":1}]|] { matchHeaders = [matchContentTypeJson] }
context "used with POST" $
it "includes related data with filters" $
request methodPost "/child_entities?select=id,entities(id)&entities.or=(id.eq.2,id.eq.3)&entities.order=id"
[("Prefer", "return=representation")]
[json|[
{"id":7,"name":"entity 4","parent_id":1},
{"id":8,"name":"entity 5","parent_id":2},
{"id":9,"name":"entity 6","parent_id":3}
]|]
`shouldRespondWith`
[json|[{"id": 7, "entities":null}, {"id": 8, "entities": {"id": 2}}, {"id": 9, "entities": {"id": 3}}]|]
{ matchStatus = 201 }
context "used with PATCH" $
it "succeeds when using and/or params" $
request methodPatch "/grandchild_entities?or=(id.eq.1,id.eq.2)&select=id,name"
[("Prefer", "return=representation")]
[json|{ name : "updated grandchild entity"}|] `shouldRespondWith`
[json|[{ "id": 1, "name" : "updated grandchild entity"},{ "id": 2, "name" : "updated grandchild entity"}]|]
{ matchHeaders = [matchContentTypeJson] }
context "used with DELETE" $
it "succeeds when using and/or params" $
request methodDelete "/grandchild_entities?or=(id.eq.1,id.eq.2)&select=id,name"
[("Prefer", "return=representation")]
""
`shouldRespondWith`
[json|[{ "id": 1, "name" : "grandchild entity 1" },{ "id": 2, "name" : "grandchild entity 2" }]|]
it "can query columns that begin with and/or reserved words" $
get "/grandchild_entities?or=(and_starting_col.eq.smth, or_starting_col.eq.smth)" `shouldRespondWith` 200
it "fails when using IN without () and provides meaningful error message" $
get "/entities?or=(id.in.1,2,id.eq.3)" `shouldRespondWith`
[json|{
"details": "unexpected \"1\" expecting \"(\"",
"message": "\"failed to parse logic tree ((id.in.1,2,id.eq.3))\" (line 1, column 10)"
}|] { matchStatus = 400, matchHeaders = [matchContentTypeJson] }
it "fails on malformed query params and provides meaningful error message" $ do
get "/entities?or=)(" `shouldRespondWith`
[json|{
"details": "unexpected \")\" expecting \"(\"",
"message": "\"failed to parse logic tree ()()\" (line 1, column 3)"
}|] { matchStatus = 400, matchHeaders = [matchContentTypeJson] }
get "/entities?and=(ord(id.eq.1,id.eq.1),id.eq.2)" `shouldRespondWith`
[json|{
"details": "unexpected \"d\" expecting \"(\"",
"message": "\"failed to parse logic tree ((ord(id.eq.1,id.eq.1),id.eq.2))\" (line 1, column 7)"
}|] { matchStatus = 400, matchHeaders = [matchContentTypeJson] }
get "/entities?or=(id.eq.1,not.xor(id.eq.2,id.eq.3))" `shouldRespondWith`
[json|{
"details": "unexpected \"x\" expecting logic operator (and, or)",
"message": "\"failed to parse logic tree ((id.eq.1,not.xor(id.eq.2,id.eq.3)))\" (line 1, column 16)"
}|] { matchStatus = 400, matchHeaders = [matchContentTypeJson] }
| steve-chavez/postgrest | test/Feature/AndOrParamsSpec.hs | mit | 17,445 | 0 | 24 | 4,266 | 2,377 | 1,411 | 966 | -1 | -1 |
{- |
Module : DataAssociation.Utils
Description : Different utilities.
License : MIT
Stability : development
-}
module DataAssociation.Utils (
preservingArg
, sortingGroupBy
, allSubsetsOneShorter
, countSupported
, calculateSupport
, sufficientSupport
) where
import Control.Arrow ((&&&))
import Control.Monad
import Data.List
import Data.Function
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import GHC.Float
import DataAssociation.Definitions
-- I guess in Haskell should already exist a way to do it,
-- but I don't know it
-- | Preserves an argument and returns it, tupled with function's result
--
-- > preservingArg id x == (x, x)
preservingArg :: (a -> b) -> a -> (a, b)
preservingArg f a = (a, f a)
-- | Groups the elements of a list according to /discriminator function/
-- and applies /result function/ to each formed group
--
-- see <http://stackoverflow.com/questions/15412027/haskell-equivalent-to-scalas-groupby>
sortingGroupBy :: (Ord b) => (a -> b) -- ^ /discriminator function/
-> ([a] -> c) -- ^ /result function/
-> [a] -- ^ a list
-> [(b, c)] -- result of grouping and /result function/ application
sortingGroupBy f g = map (f . head &&& g)
. groupBy ((==) `on` f)
. sortBy (compare `on` f)
-----------------------------------------------------------------------------
-- | iven an itemset of length l, returns a set of itemsets of length (l - 1)
-- that are subsets of the original one.
allSubsetsOneShorter :: (Itemset set it) => set it -> [set it]
allSubsetsOneShorter set = liftM (`deleteItemAt` set) [0 .. setSize set - 1]
-- this equals to:
-- do i <- [0 .. setSize set - 1]
-- return $ deleteItemAt i set
-----------------------------------------------------------------------------
-- | Count the number of occurences of each set in the transactions.
-- An 'occurence' is when the set is a subset of the transaction.
countSupported :: (Ord (set it), Itemset set it) =>
[set it] -> [set it] -> Map (set it) Int
countSupported transactions sets = Map.fromList cl
where cl = do set <- sets
let cnt tr = if tr `contains` set then 1 else 0
let count = foldr (\tr acc -> acc + cnt tr) 0 transactions
return (set, count)
calculateSupport :: Int -- ^ total number of transactions
-> Int -- ^ number of occurences
-> Float -- ^ support
calculateSupport transactionsSize = (/ int2Float transactionsSize) . int2Float
sufficientSupport :: MinSupport
-> Int -- ^ total number of transactions
-> Int -- ^ number of occurences
-> Bool -- ^ has sufficient support?
sufficientSupport (MinSupport minsup) transactionsSize =
(>= minsup) . calculateSupport transactionsSize
| fehu/min-dat--a-priori | core/src/DataAssociation/Utils.hs | mit | 3,010 | 3 | 16 | 816 | 565 | 325 | 240 | -1 | -1 |
import System.Environment
import System.Exit
import Data.List
import Spiral
prettyPrint m = intercalate "\n" (map (intercalate "\t") mstr)
where mstr = map (map show) m
main = do
args <- getArgs
case args of
[] -> putStrLn $ "Exiting, need spiral size"
list | length list > 1 -> putStrLn $ "too many parameters"
[sizeString] -> do
let
size = read sizeString :: Integer
matrix = spiral size
putStrLn $ "spiral size " ++ (show size) ++ "\n" ++ prettyPrint matrix
| kirhgoff/haskell-sandbox | euler28/printer.hs | mit | 519 | 0 | 16 | 138 | 178 | 87 | 91 | 16 | 3 |
-- |
-- Module : HGE2D.AABBTree
-- Copyright : (c) 2016 Martin Buck
-- License : see LICENSE
--
-- Containing the definition and functions for an axis aligned bounding box tree
module HGE2D.AABBTree where
import HGE2D.Types
import HGE2D.Datas
import HGE2D.Classes
import HGE2D.Geometry
import HGE2D.Collision
import Data.Maybe
--------------------------------------------------------------------------------
-- | A bounding box tree for fast collision detection
data (HasBoundingBox a) => AABBTree a = AABBTreeEmpty
| AABBTreeLeaf [a] BoundingBox
| AABBTreeBranch (AABBTree a) (AABBTree a) BoundingBox
---TODO fmap
---TODO fmapRebuild
--------------------------------------------------------------------------------
-- | Builds an AABBTree from a list of elements with bounding boxes.
aaBBTreeBuild :: (HasBoundingBox a) => MaxDepth -> [a] -> AABBTree a
aaBBTreeBuild maxDepth xs = aaBBTreeBuildRec False 0 maxDepth xs
where
aaBBTreeBuildRec _ _ _ [] = AABBTreeEmpty
aaBBTreeBuildRec _ _ _ [x] = AABBTreeLeaf [x] (getBB x)
aaBBTreeBuildRec compX depth maxDepth xs | done = AABBTreeLeaf xs mergedBB
| otherwise = AABBTreeBranch (aaBBTreeBuildRec (not compX) (depth+1) maxDepth left)
(aaBBTreeBuildRec (not compX) (depth+1) maxDepth right)
mergedBB
where
done = depth >= maxDepth
mergedBB = mconcat bbs
bbs = map getBB xs
left = filter (isLeft . getBB) xs
right = filter (isRight . getBB) xs
splitPos = centerBB mergedBB
isLeft bb = (dim $ bbMin bb) < dim splitPos
isRight bb = (dim $ bbMax bb) >= dim splitPos
dim | compX = fst
| otherwise = snd
--------------------------------------------------------------------------------
-- | Finds all items of the tree which collide with the search item.
aaBBTreeCollisions :: (HasBoundingBox a, HasBoundingBox b) => b -> AABBTree a -> [a]
aaBBTreeCollisions _ AABBTreeEmpty = []
aaBBTreeCollisions search (AABBTreeLeaf xs _) = filter (doCollide search) xs
aaBBTreeCollisions search (AABBTreeBranch l r _) = (nodeResult l) ++ (nodeResult r)
where
nodeResult n | collides = aaBBTreeCollisions search n
| otherwise = []
where
collides = fromMaybe False mayCollide
mayCollide = fmap (doCollide search) mayBB
mayBB = case n of
AABBTreeEmpty -> Nothing
(AABBTreeLeaf _ x) -> Just x
(AABBTreeBranch _ _ x) -> Just x
--------------------------------------------------------------------------------
-- | Puts the elements of an AABBTree into a list.
aaBBTreeToList :: (HasBoundingBox a) => AABBTree a -> [a]
aaBBTreeToList AABBTreeEmpty = []
aaBBTreeToList (AABBTreeLeaf xs _) = xs
aaBBTreeToList (AABBTreeBranch l r _) = (aaBBTreeToList l) ++ (aaBBTreeToList r)
---TODO rebuild
---TODO filter
---TODO add
---TODO remove
{-
quadRebuild :: (Positioned a) => QuadTree a -> QuadTree a
quadFilter :: (Positioned a) => (a -> Bool) -> QuadTree a -> QuadTree a
-}
| I3ck/HGE2D | src/HGE2D/AABBTree.hs | mit | 3,431 | 0 | 13 | 1,042 | 739 | 385 | 354 | 44 | 3 |
{-
- Whidgle.Hoisting
-
- Describes hoisting for Whidgle.
-}
module Whidgle.Hoisting
( ioHoistWhidgle
) where
import Control.Monad.Reader
import Control.Monad.State
import System.IO.Unsafe
import Whidgle.Types
-- Hoists an IO morphism to a Whidgle one.
-- There's probably a clever mmorphy way to do this but I really only need this
-- operation in one or two places.
ioHoistWhidgle :: (IO a -> IO b) -> (Whidgle a -> Whidgle b)
ioHoistWhidgle ioA x = do
settings <- ask
st <- get
-- the Whidgle type currently doesn't support the lift operation
Whidgle . lift . lift $ (ioA (runWhidgle settings st x))
| Zekka/whidgle | src/Whidgle/Hoisting.hs | mit | 619 | 0 | 11 | 117 | 129 | 70 | 59 | 11 | 1 |
-- School of Haskell "Basics of Haskell" Chapter 2
-- https://www.schoolofhaskell.com/school/starting-with-haskell/basics-of-haskell/2-my-first-program
-- Exercise 3
-- Define a function that takes a segment and returns it's center point:
center :: ((Double, Double), (Double, Double)) -> (Double, Double)
center ((x1, y1), (x2, y2)) = ((x1 + x2)/2, (y1 + y2)/2)
main :: IO ()
main = print $ center ((1,2), (3, 4))
| chsm/code | hs/soh/basics/02-03.hs | mit | 418 | 0 | 8 | 63 | 132 | 80 | 52 | 4 | 1 |
{-# OPTIONS_GHC -fno-warn-missing-signatures #-}
module Grammar.Greek.Morph.Stage where
import Grammar.Common
import Grammar.Greek.Morph.Clitic.Stage (clitic)
import Grammar.Greek.Morph.Phoneme.Stage (phoneme)
morph
= clitic
<+> phoneme
| ancientlanguage/haskell-analysis | greek-morph/src/Grammar/Greek/Morph/Stage.hs | mit | 244 | 0 | 5 | 27 | 49 | 33 | 16 | 8 | 1 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DuplicateRecordFields #-}
module Glot.DockerRun
( RunRequest(..)
, RunRequestPayload(..)
, RunResult(..)
, Config(..)
, run
, Error(..)
, ErrorBody(..)
, formatError
, debugError
) where
import Import hiding (RunResult)
import qualified Data.List.NonEmpty as NonEmpty
import qualified GHC.Generics as GHC
import qualified Data.Aeson as Aeson
import qualified Network.HTTP.Req as Req
import qualified Glot.Snippet as Snippet
import qualified Control.Exception as Exception
import qualified Data.Bifunctor as Bifunctor
import qualified Network.HTTP.Client as Http
import qualified Network.HTTP.Types.Status as Status
import qualified Text.URI as URI
import qualified Glot.Language as Language
import Data.Function ((&))
data RunRequest = RunRequest
{ image :: Text
, payload :: RunRequestPayload
}
deriving (Show, GHC.Generic)
instance Aeson.ToJSON RunRequest
data RunRequestPayload = RunRequestPayload
{ language :: Language.Id
, files :: NonEmpty.NonEmpty Snippet.FilePayload
, stdin :: Maybe Text
, command :: Maybe Text
}
deriving (Show, GHC.Generic)
instance Aeson.ToJSON RunRequestPayload
data RunResult = RunResult
{ stdout :: Text
, stderr :: Text
, error :: Text
}
deriving (Show, GHC.Generic)
instance Aeson.FromJSON RunResult
instance Aeson.ToJSON RunResult
data Config = Config
{ accessToken :: ByteString
, baseUrl :: Text
, responseTimeout :: Int
}
run :: Config -> RunRequest -> IO (Either Error RunResult)
run Config{..} runRequest =
let
reqConfig =
Req.defaultHttpConfig
{ Req.httpConfigRedirectCount = 0
, Req.httpConfigCheckResponse = \_ _ _ -> Nothing
, Req.httpConfigRetryJudge = \_ _ -> False
, Req.httpConfigRetryJudgeException = \_ _ -> False
}
mkOptions :: Req.Option scheme -> Req.Option scheme
mkOptions urlOptions =
urlOptions
<> Req.header "X-Access-Token" accessToken
<> Req.responseTimeout (responseTimeout * 1000000)
runReq httpOrHttpsUrl = do
res <- Req.runReq reqConfig $ do
case httpOrHttpsUrl of
Left (httpUrl, urlOptions) ->
Req.req Req.POST httpUrl (Req.ReqBodyJson runRequest) Req.bsResponse (mkOptions urlOptions)
Right (httpsUrl, urlOptions) ->
Req.req Req.POST httpsUrl (Req.ReqBodyJson runRequest) Req.bsResponse (mkOptions urlOptions)
pure (handleResponse res)
in do
uri <- URI.mkURI (baseUrl <> "/run")
case Req.useURI uri of
Nothing -> do
pure $ Left ParseUrlError
Just httpOrHttpsUrl -> do
eitherResult <- Exception.try (runReq httpOrHttpsUrl)
case eitherResult of
Left exception ->
pure (Left $ HttpException exception)
Right e ->
pure e
handleResponse :: (Req.HttpResponse response, Req.HttpResponseBody response ~ ByteString) => response -> Either Error RunResult
handleResponse res =
let
body =
Req.responseBody res
in
if isSuccessStatus (Req.responseStatusCode res) then
Aeson.eitherDecodeStrict' body
& Bifunctor.first (DecodeSuccessResponseError body)
else
case Aeson.eitherDecodeStrict' body of
Right apiError ->
Left (ApiError apiError)
Left decodeError ->
Left (DecodeErrorResponseError body decodeError)
isSuccessStatus :: Int -> Bool
isSuccessStatus code =
code >= 200 && code <= 299
data Error
= ParseUrlError
| HttpException Req.HttpException
| DecodeSuccessResponseError ByteString String
| DecodeErrorResponseError ByteString String
| ApiError ErrorBody
debugError :: Error -> String
debugError err =
case err of
ParseUrlError ->
"ParseUrlError"
HttpException exception ->
"HttpException: " <> (show exception)
DecodeSuccessResponseError body reason ->
"DecodeSuccessResponseError: " <> (show reason) <> ", body: " <> (show body)
DecodeErrorResponseError body reason ->
"DecodeErrorResponseError: " <> (show reason) <> ", body: " <> (show body)
ApiError errorBody ->
"ApiError: " <> (show errorBody)
formatError :: Error -> String
formatError err =
case err of
ParseUrlError ->
"Invalid docker-run url"
HttpException exception ->
case exception of
Req.JsonHttpException reason ->
"Failed to decode json response from docker-run: " <> reason
Req.VanillaHttpException httpException ->
case httpException of
InvalidUrlException url reason ->
"Invalid request url: " <> url <> " (" <> reason <> ")"
HttpExceptionRequest _ exceptionContent ->
case exceptionContent of
Http.StatusCodeException response _ ->
"Unexpected status code in response from docker-run: " <> (show $ Status.statusCode $ Http.responseStatus response)
Http.TooManyRedirects _ ->
"Too many redirect"
Http.OverlongHeaders ->
"Header overflow from docker-run"
Http.ResponseTimeout ->
"docker-run took too long to return a response"
Http.ConnectionTimeout ->
"Attempting to connect to docker-run timed out"
Http.ConnectionFailure _ ->
"An exception occurred when trying to connect to docker-run"
Http.InvalidStatusLine _ ->
"The status line returned by docker-run could not be parsed"
Http.InvalidHeader _ ->
"The given response header line from docker-run could not be parsed"
Http.InvalidRequestHeader _ ->
"The given request header is not compliant"
Http.InternalException _ ->
"An exception was raised by an underlying library when performing the request"
Http.ProxyConnectException _ _ _ ->
"A non-200 status code was returned when trying to connect to the proxy server on the given host and port"
Http.NoResponseDataReceived ->
"No response data was received from the docker-run at all"
Http.TlsNotSupported ->
"Tls not supported"
Http.WrongRequestBodyStreamSize _ _ ->
"The request body provided did not match the expected size."
Http.ResponseBodyTooShort _ _ ->
"The returned response body from docker-run is too short"
Http.InvalidChunkHeaders ->
"A chunked response body had invalid headers"
Http.IncompleteHeaders ->
"An incomplete set of response headers were returned from docker-run"
Http.InvalidDestinationHost _ ->
"The host we tried to connect to is invalid"
Http.HttpZlibException _ ->
"An exception was thrown when inflating the response body from docker-run"
Http.InvalidProxyEnvironmentVariable _ _ ->
"Values in the proxy environment variable were invalid"
Http.ConnectionClosed ->
"Attempted to use a Connection which was already closed"
Http.InvalidProxySettings _ ->
"Proxy settings are not valid"
DecodeSuccessResponseError _ decodeError ->
show decodeError
DecodeErrorResponseError _ decodeError ->
show decodeError
ApiError errorBody ->
show errorBody
data ErrorBody = ErrorBody
{ error :: Text
, message :: Text
}
deriving (Show, GHC.Generic)
instance Aeson.ToJSON ErrorBody
instance Aeson.FromJSON ErrorBody
| prasmussen/glot-www | Glot/DockerRun.hs | mit | 9,069 | 0 | 21 | 3,509 | 1,588 | 829 | 759 | -1 | -1 |
module Lisp.StdLib(stdLib) where
import Lisp.Spefication
import Data.SyntaxIR
import Data.Map as M
-- # UTILITY
a |> f = f a
reduceFn fn acc elems = impl acc elems
where impl acc (n:ns) = impl (fn acc n) ns
impl acc [] = acc
functionFactory name onSingle onMultiple = func
where
func [] = wrongNumberArgsFor name
func (x:[]) = onSingle $ x
func xs = onMultiple xs
numId (Num x) = Num x
numId _ = numError
boolId (Boolean b) = (Boolean b)
boolId _ = boolError
naiveAdd name =
let adds (Num a) (Num b) = Num $ a + b
adds _ _ = numError
in functionFactory name numId (reduceFn adds (Num 0))
naiveMul name =
let muls (Num a) (Num b) = Num $ a * b
muls _ _ = numError
in functionFactory name numId (reduceFn muls (Num 1))
naiveSub name =
let onSingle (Num x) = Num $ -x
onSingle _ = numError
impl (x:xs) = reduceFn subs x xs
where subs (Num a) (Num b) = Num $ a - b
subs _ _ = numError
in functionFactory name onSingle impl
naiveDiv name =
let onSingle (Num x) = Num $ 1 / x
onSingle _ = numError
impl (x:xs) = reduceFn divs x xs
where divs (Num a) (Num b) = Num $ a / b
divs _ _ = numError
in functionFactory name onSingle impl
naiveOr name =
let impl (x:xs) = reduceFn ands x xs
where ands (Boolean a) (Boolean b) = Boolean $ a || b
ands _ _ = boolError
in functionFactory name boolId impl
naiveAnd name =
let impl (x:xs) = reduceFn ands x xs
where ands (Boolean a) (Boolean b) = Boolean $ a && b
ands _ _ = boolError
in functionFactory name boolId impl
-- # the standard library
type NatFunc = ([Char] -> [AST] -> AST)
type RefList = [(String, AST)]
define ref fn map = (ref, value):map
where value = Func (NatvFn (fn ref) ref)
stdLib :: Environment
stdLib = [M.fromList lib]
where
lib = []
|> (define "+" naiveAdd)
|> (define "-" naiveSub)
|> (define "*" naiveMul)
|> (define "/" naiveDiv)
|> (define "or" naiveOr)
|> (define "and" naiveAnd)
| AKST/lisp.hs | src/Lisp/StdLib.hs | mit | 2,259 | 0 | 14 | 784 | 948 | 475 | 473 | 61 | 3 |
-- Copyright (C) 2004-2005 David Roundy
--
-- 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, 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; see the file COPYING. If not, write to
-- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
-- Boston, MA 02110-1301, USA.
{-# LANGUAGE CPP, ScopedTypeVariables, MultiParamTypeClasses, FlexibleInstances, Rank2Types #-}
module Darcs.Repository.Match
(
getNonrangeMatch
, getPartialNonrangeMatch
, getFirstMatch
, getOnePatchset
) where
import Darcs.Patch.Match
( getNonrangeMatchS
, getFirstMatchS
, nonrangeMatcherIsTag
, getMatchingTag
, matchAPatchset
, nonrangeMatcher
, applyNInv
, hasIndexRange
, MatchFlag(..)
)
import Darcs.Patch.Bundle ( scanContextFile )
import Darcs.Patch.ApplyMonad ( ApplyMonad(..) )
import Darcs.Patch.Apply( ApplyState )
import Darcs.Patch ( RepoPatch )
import Darcs.Patch.Set ( PatchSet(..), SealedPatchSet, Origin )
import Darcs.Patch.Witnesses.Sealed ( seal )
import Darcs.Repository.Flags
( WithWorkingDir (WithWorkingDir) )
import Darcs.Repository.ApplyPatches ( DefaultIO, runDefault )
import Darcs.Repository.Internal
( Repository, readRepo, createPristineDirectoryTree )
import Storage.Hashed.Tree ( Tree )
import Darcs.Util.Path ( FileName, toFilePath )
#include "impossible.h"
getNonrangeMatch :: (ApplyMonad DefaultIO (ApplyState p), RepoPatch p, ApplyState p ~ Tree)
=> Repository p wR wU wT
-> [MatchFlag]
-> IO ()
getNonrangeMatch r = withRecordedMatch r . getMatch where
getMatch fs = case hasIndexRange fs of
Just (n, m) | n == m -> applyNInv (n-1)
| otherwise -> fail "Index range is not allowed for this command."
_ -> getNonrangeMatchS fs
getPartialNonrangeMatch :: (RepoPatch p, ApplyMonad DefaultIO (ApplyState p), ApplyState p ~ Tree)
=> Repository p wR wU wT
-> [MatchFlag]
-> [FileName]
-> IO ()
getPartialNonrangeMatch r fs _ =
withRecordedMatch r (getNonrangeMatchS fs)
getFirstMatch :: (ApplyMonad DefaultIO (ApplyState p), RepoPatch p, ApplyState p ~ Tree)
=> Repository p wR wU wT
-> [MatchFlag]
-> IO ()
getFirstMatch r fs = withRecordedMatch r (getFirstMatchS fs)
getOnePatchset :: (RepoPatch p, ApplyState p ~ Tree)
=> Repository p wR wU wT
-> [MatchFlag]
-> IO (SealedPatchSet p Origin)
getOnePatchset repository fs =
case nonrangeMatcher fs of
Just m -> do ps <- readRepo repository
if nonrangeMatcherIsTag fs
then return $ getMatchingTag m ps
else return $ matchAPatchset m ps
Nothing -> seal `fmap` (scanContextFile . toFilePath . context_f $ fs)
where context_f [] = bug "Couldn't match_nonrange_patchset"
context_f (Context f:_) = f
context_f (_:xs) = context_f xs
withRecordedMatch :: (RepoPatch p, ApplyState p ~ Tree)
=> Repository p wR wU wT
-> (PatchSet p Origin wR -> DefaultIO ())
-> IO ()
withRecordedMatch r job
= do createPristineDirectoryTree r "." WithWorkingDir
readRepo r >>= runDefault . job
| DavidAlphaFox/darcs | src/Darcs/Repository/Match.hs | gpl-2.0 | 3,869 | 0 | 13 | 1,034 | 862 | 464 | 398 | -1 | -1 |
{--
-- Natume -- an implementation of Kana-Kanji conversion in Haskell
-- Copyright (C) 2006-2012 Takayuki Usui
--
-- This program is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 2 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to the Free Software
-- Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--}
module Getopt (
Opt(OptFlg,OptArg,OptErr),getopt
) where
data Opt = OptFlg Char
| OptArg Char String
| OptErr String
deriving (Show)
isFlg :: Char -> String -> Bool
isFlg _ [] = False
isFlg c [x] = x == c
isFlg c (x:y:ys) = if x == c && y /= ':'
then True
else isFlg c (y:ys)
hasArg :: Char -> String -> Bool
hasArg _ [] = False
hasArg _ [_] = False
hasArg c (x:y:ys) = if x == c && y == ':'
then True
else hasArg c (y:ys)
getopt1 :: ([Opt],[String]) -> [String] -> String -> ([Opt],[String])
getopt1 (a1,a2) [] _ = (reverse a1,reverse a2)
getopt1 (a1,a2) (x:xs) opts =
case x of
"--" -> (reverse a1,(reverse a2)++xs)
('-':c:cs) ->
if isFlg c opts
then if null cs
then getopt1 ((OptFlg c):a1,a2) xs opts
else getopt1 ((OptFlg c):a1,a2) (('-':cs):xs) opts
else if hasArg c opts
then if null cs
then if null xs
then ([OptErr e1],[])
else let (y:ys) = xs in
case y of
('-':_) ->
([OptErr e1],[])
_ ->
getopt1 ((OptArg c y):a1,a2) ys opts
else getopt1 ((OptArg c cs):a1,a2) xs opts
else ([OptErr e2],[])
where
e1 = "argument is required for this option -- " ++ [c]
e2 = "unknown option -- " ++ [c]
_ ->
getopt1 (a1,x:a2) xs opts
getopt :: [String] -> String -> ([Opt],[String])
getopt args opts = getopt1 ([],[]) args opts
| takayuki/natume | Getopt.hs | gpl-2.0 | 2,583 | 0 | 21 | 912 | 739 | 405 | 334 | 48 | 9 |
module SW_liquid
( sw_liquid_n, sw_liquid_Veff, homogeneous_sw_liquid )
where
import Expression
import IdealGas ( idealgas, idealgas_of_veff, kT )
import WhiteBear ( gSigmaA, whitebear )
import FMT ( rad )
sigma :: Type a => Expression a
sigma = 2*rad
epsilon :: Type a => Expression a
epsilon = s_tex "epsilon" "\\epsilon"
ksig :: Expression KSpace
ksig = k*sigma
lamksig :: Expression KSpace
lamksig = lambda*k*sigma
lambda :: Type a => Expression a
lambda = s_tex "lambda" "\\lambda"
eps4pi :: Expression KSpace
eps4pi = epsilon*4*pi
n :: Expression RealSpace
n = r_var "n"
gsigma :: Expression RealSpace
gsigma = substitute ("n" === r_var "x") n gSigmaA
homogeneous_sw_liquid :: Expression Scalar
homogeneous_sw_liquid = makeHomogeneous $ substitute ("n" === r_var "x") (r_var "n") $
sw + whitebear + idealgas - integrate (n * s_var "mu")
sw_liquid_n :: Expression Scalar
sw_liquid_n = "ESW" === (substitute ("n" === r_var "x") (r_var "n") $
sw + whitebear + idealgas +
("external" === integrate (n * (r_var "Vext" - s_var "mu"))))
sw_liquid_Veff :: Expression Scalar
sw_liquid_Veff = substitute n ("n" === exp(- r_var "Veff"/kT)) $
substitute ("n" === r_var "x") ("n" === exp(- r_var "Veff"/kT)) $
sw + whitebear + idealgas_of_veff +
("external" === integrate (n * (r_var "Vext" - s_var "mu")))
sw :: Expression Scalar
sw = var "sw" "F_{\\text{sw}}" $
integrate $ var "swEdensity" "\\Phi_{SW}(r)" $
0.5*epsilon*n*ifft (n_g_phi0 + n_g_phi1 +
n_g_phi2 + n_g_phi3 + n_g_phi4)
n_g_phi0, n_g_phi1, n_g_phi2, n_g_phi3, n_g_phi4 :: Expression KSpace
n_g_phi0 = convolve_xi0phi_with (n * gsigma)
n_g_phi1 = convolve_xi1phi_with (n * (k11*(gsigma-1) + k21*(gsigma-1)**2 +
k31*(gsigma-1)**3 + k41*(gsigma-1)**4))
where k11 = -1.754
k21 = 0.027
k31 = 0.838
k41 = -0.178
n_g_phi2 = convolve_xi2phi_with (n * (k12*(gsigma-1) + k22*(gsigma-1)**2 +
k32*(gsigma-1)**3 + k42*(gsigma-1)**4))
where k12 = -2.243
k22 = 4.403
k32 = -2.48
k42 = 0.363
n_g_phi3 = convolve_xi3phi_with (n * (k13*(gsigma-1) + k23*(gsigma-1)**2 +
k33*(gsigma-1)**3 + k43*(gsigma-1)**4))
where k13 = 0.207
k23 = 0.712
k33 = -1.952
k43 = 1.046
n_g_phi4 = convolve_xi4phi_with (n * (k14*(gsigma-1) + k24*(gsigma-1)**2 +
k34*(gsigma-1)**3 + k44*(gsigma-1)**4))
where k14 = -0.002
k24 = -0.164
k34 = 0.324
k44 = -0.162
convolve_xi0phi_with :: Expression RealSpace -> Expression KSpace
convolve_xi0phi_with x = xi0phik * fft x
where xi0phik = var "xi0phik" "\\tilde{\\xi_0\\phi}(k)" $
-eps4pi * ((sin lamksig - sin ksig)/k**3 + (sigma*cos ksig - lambda*sigma*cos lamksig)/k**2)
convolve_xi1phi_with :: Expression RealSpace -> Expression KSpace
convolve_xi1phi_with x = xi1phik * fft x
where xi1phik = var "xi1phik" "\\tilde{\\xi_1\\phi}(k)" $
-eps4pi * ((2-lamksig*ksig*(lambda-1))*cos lamksig/(k**3*ksig)
-ksig*(sin ksig + (1-2*lambda)*sin lamksig)/(k**3*ksig)-2*cos ksig/(k**3*ksig))
convolve_xi2phi_with :: Expression RealSpace -> Expression KSpace
convolve_xi2phi_with x = xi2phik * fft x
where xi2phik = var "xi2phik" "\\tilde{\\xi_2\\phi}(k)" $
-eps4pi * (6*sin ksig/(k**3*ksig**2)
+ (ksig**2*(1-4*lambda+3*lambda**2)-6)*sin lamksig/(k**3*ksig**2)
- ksig*(4+lambda*(ksig**2*(lambda-1)**2-6))*cos lamksig/(k**3*ksig**2)
- 2*ksig*cos ksig/(k**3*ksig**2))
convolve_xi3phi_with :: Expression RealSpace -> Expression KSpace
convolve_xi3phi_with x = xi3phik * fft x
where xi3phik = var "xi3phik" "\\tilde{\\xi_3\\phi}(k)" $
-eps4pi*(ksig*(6*sin ksig
+ (18-24*lambda+ksig**2*(lambda-1)**2*(4*lambda-1))*sin lamksig)/(k**3*ksig**3)
+ (6*ksig**2*(lambda-1)*(2*lambda-1)
- lamksig*ksig**3*(lambda-1)**3-24)*cos lamksig/(k**3*ksig**3)
+ 24*cos ksig/(k**3*ksig**3))
convolve_xi4phi_with :: Expression RealSpace -> Expression KSpace
convolve_xi4phi_with x = xi4phik * fft x
where xi4phik = var "xi4phik" "\\tilde{\\xi_4\\phi}(k)" $
-eps4pi*(ksig**2*(lambda-1)*(36 - 60*lambda
+ ksig**2*(lambda-1)**2*(5*lambda-1))*sin lamksig/(k**3*ksig**4)
+ 120*(sin lamksig - sin ksig)/(k**3*ksig**4)
+ ksig*(24*cos ksig
- (24*(5*lambda-4) - 4*ksig**2*(lambda-1)**2*(5*lambda-2)
+ lamksig*ksig**3*(lambda-1)**4)*cos lamksig)/(k**3*ksig**4))
| droundy/deft | src/haskell/SW_liquid.hs | gpl-2.0 | 4,975 | 2 | 29 | 1,419 | 2,202 | 1,141 | 1,061 | 98 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module SerializingTreesToJsonSpec where
import Test.Hspec
import NodeEditor.Data
import NodeEditor.Serialize
import NodeEditor.Parser
spec = do
it "works for nodes" $ do
toJson (topLevelNodes $ treeFromText "line one")
`shouldBe`
"[{\"body\":\"line one\",\"id\":0}]"
| rickardlindberg/node-editor-2 | test/SerializingTreesToJsonSpec.hs | gpl-3.0 | 320 | 0 | 14 | 51 | 62 | 34 | 28 | 11 | 1 |
{-# OPTIONS_GHC -fno-warn-type-defaults #-}
-- remove the two benign defaults
-- | A simple color module for handling RGB and HSV representations of colors.
module Data.Color (
-- * Datatypes
RGB(..)
, HSV(..)
, rgbToHex
, hsvToHex
-- ** Predefined colors
, red
, green
, blue
-- ** Conversions
, rgbToGray
, hsvToGray
, rgbToHSV
, hsvToRGB
-- * Color Palettes
, colorGroups
, lightColorGroups
) where
{- IDEA: Provide color datastructure together with nice and usable color
- palettes for reporting various data
-}
import Numeric (showHex)
-- import Text.XHtml.Strict
-- import Text.XHtml.Table
data RGB a = RGB {
rgbR :: !a
, rgbG :: !a
, rgbB :: !a
}
deriving( Eq, Ord )
instance Show a => Show (RGB a) where
show (RGB r g b) = "RGB("++show r++", "++show g++", "++show b++")"
instance Functor RGB where
fmap f (RGB r g b) = RGB (f r) (f g) (f b)
red, green, blue :: Fractional t => RGB t
red = RGB 1.0 0.0 0.0
green = RGB 0.0 1.0 0.0
blue = RGB 0.0 0.0 1.0
data HSV a = HSV {
hsvH :: !a
, hsvS :: !a
, hsvV :: !a
}
deriving( Eq, Ord )
instance Show a => Show (HSV a) where
show (HSV h s v) = "HSV("++show h++", "++show s++", "++show v++")"
instance Functor HSV where
fmap f (HSV h s v) = HSV (f h) (f s) (f v)
------------------------------------------------------------------------------
-- Colorspace conversion
------------------------------------------------------------------------------
-- | RGB to HSV conversion.
-- Pre: 0 <= r,g,b <= 1
-- (Source: http://de.wikipedia.org/wiki/HSV-Farbraum)
rgbToHSV :: (Fractional t, Ord t) => RGB t -> HSV t
rgbToHSV (RGB r g b) = HSV h' s v
where
ub = max r (max g b)
lb = min r (min g b)
h | ub == lb = 0
| ub == r = 60 * ( (g-b)/(ub-lb))
| ub == g = 60 * (2 + (b-r)/(ub-lb))
| otherwise = 60 * (4 + (r-g)/(ub-lb))
h' | h < 0 = h + 360
| otherwise = h
s | ub == 0 = 0
| otherwise = (ub-lb)/ub
v = ub
-- | HSV to RGB conversion.
-- Pre: 0 <= h <= 360 and 0 <= s,v <= 1
-- (Source: http://de.wikipedia.org/wiki/HSV-Farbraum)
hsvToRGB :: RealFrac t => HSV t -> RGB t
hsvToRGB (HSV h s v) = case hIdx of
0 -> RGB v t p
1 -> RGB q v p
2 -> RGB p v t
3 -> RGB p q v
4 -> RGB t p v
5 -> RGB v p q
_ -> error "hsvToRGB: hue outside of range [0..360]"
where
hIdx = floor (h / 60)
f = h/60 - fromIntegral (hIdx::Int)
p = v*(1-s)
q = v*(1-s*f)
t = v*(1-s*(1-f))
hsvToGray :: Num t => HSV t -> HSV t
hsvToGray (HSV h _ v) = HSV h 0 v
rgbToGray :: Ord t => RGB t -> t
rgbToGray (RGB r g b) = max r (max g b)
------------------------------------------------------------------------------
-- String output
------------------------------------------------------------------------------
-- | Hexadecimal representation of an RGB value
rgbToHex :: RealFrac t => RGB t -> String
rgbToHex (RGB r g b) = ('#':) . showHex' r . showHex' g . showHex' b $ ""
where showHex' f
| i <= 15 = ('0':) . showHex i
| otherwise = showHex i
where
i :: Int
i = max 0 (min 255 (floor (256 * f)))
-- | Hexadecimal representation of an HSV value; i.e., of its corresponding RGB
-- value.
hsvToHex :: RealFrac t => HSV t -> [Char]
hsvToHex = rgbToHex . hsvToRGB
------------------------------------------------------------------------------
-- HSV Color Palettes
------------------------------------------------------------------------------
data ColorParams t = ColorParams {
cpScale :: !t
, cpZeroHue :: !t
, cpVBottom :: !t
, cpVRange :: !t
, cpSBottom :: !t
, cpSRange :: !t
}
deriving( Eq, Ord, Show )
-- | From a list of group sizes build a function assigning every element a
-- unique color, nicely distributed such that they are well differentiated both
-- using color and monochrome displays.
genColorGroups :: RealFrac t =>
ColorParams t
-> [Int] -- ^ List of group sizes.
-> [((Int,Int),(HSV t))]
genColorGroups (ColorParams {
cpScale = scale
, cpZeroHue = zeroHue
, cpVBottom = vBot, cpVRange = vRan
, cpSBottom = sBot, cpSRange = sRan
}) groups =
do
(groupIdx, groupSize) <- zip [0.. ] groups
elemIdx <- [0..groupSize - 1]
let h = toShiftedGroupHue groupIdx (fromIntegral elemIdx / fromIntegral groupSize)
v = vBot + vRan * toGroupHue groupIdx (fromIntegral elemIdx / fromIntegral groupSize)
s = sBot + sRan * toGroupHue groupIdx (fromIntegral elemIdx / fromIntegral groupSize)
color = HSV (360*h) s v
return ((groupIdx, elemIdx), color)
where
nGroups :: Int
nGroups = length groups
toGroupHue g h = (
fromIntegral g + -- base position
0.5 * (1 - scale) + -- left margin
(h * scale) -- position in margin
) / (fromIntegral nGroups)
toShiftedGroupHue g h =
snd . properFraction $ toGroupHue g h + 1 +
(zeroHue/360) - toGroupHue 0 0.5
-- | A good default style for the 'genColorGroups' color palette function. The
-- parameter shifts the hue for the first group.
colorGroupStyle :: Double -> ColorParams Double
colorGroupStyle zeroHue = ColorParams {
cpScale = 0.6
, cpZeroHue = zeroHue
, cpVBottom = 0.75, cpVRange = 0.2
, cpSBottom = 0.4, cpSRange = 0.00
}
-- | Build color groups according to the list of group sizes using the default
-- 'colorGroupStyle' for the function 'genColorGroups'.
colorGroups :: Double -> [Int] -> [((Int, Int), HSV Double)]
colorGroups zeroHue = genColorGroups (colorGroupStyle zeroHue)
-- | A good light color style for the @genColorGroups@ color palette
-- function. The parameter shifts the hue for the first group.
lightColorGroupStyle :: Double -> ColorParams Double
lightColorGroupStyle zeroHue = ColorParams {
cpScale = 0.6
, cpZeroHue = zeroHue
, cpVBottom = 0.8, cpVRange = 0.15
, cpSBottom = 0.3, cpSRange = 0.00
}
-- | Build color groups according to the list of group sizes using the
-- default light 'lightColorGroupStyle' for the function
-- 'genColorGroups'.
lightColorGroups :: Double -> [Int] -> [((Int, Int), HSV Double)]
lightColorGroups zeroHue = genColorGroups (lightColorGroupStyle zeroHue)
------------------------------------------------------------------------------
-- Testing: Html Table with group colors
------------------------------------------------------------------------------
{-
colorTable :: Double -> (HSV Double -> HSV Double) -> [Int] -> Html
colorTable zeroHue conv groups =
table . toHtml . besides $ map col [0..length groups-1]
where
col i = aboves [cell $ (td ! [getStyle i j]) (stringToHtml (show (i,j)))
| j <- [0..(groups !! i) - 1] ]
color = colorGroups zeroHue groups
getStyle i j = thestyle ("background-color: "++ hsvToHex (conv $ color i j))
colorFile :: Double -> FilePath -> [Int] -> IO ()
colorFile zeroHue outF groups = do
let html = colorTable zeroHue id groups +++
colorTable zeroHue hsvToGray groups
writeFile outF $ prettyHtml html
-}
| meiersi/scyther-proof | src/Data/Color.hs | gpl-3.0 | 7,152 | 0 | 15 | 1,751 | 1,963 | 1,047 | 916 | 154 | 7 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Context
( ActionContext(..)
, ActionContextM
, runContextM
, BackgroundContext(..)
, BackgroundContextM
, withBackgroundContextM
, SolrIndexingContext(..)
, SolrIndexingContextM
, mkSolrIndexingContext
) where
import Control.Monad.Trans.Reader (ReaderT(..), withReaderT)
import Control.Monad.Trans.Resource (InternalState, runResourceT, withInternalState)
import Data.Time (getCurrentTime)
import Has
import HTTP.Client
import Model.Time
import Model.Id.Types
import Model.Identity.Types
import Model.Party.Types
import Model.Permission.Types
import Service.Log
import Service.Types
import Service.DB
import Service.Entropy
import Service.Mail
import Service.Messages
import Service.Notification
import Service.Passwd
import Solr.Service
import Static.Service
import Ingest.Service
import Store.AV
import Store.Types
import Web.Types
-- | This is the context for when you don't have an identity, but you have a
-- fully initialized, "command line" access to the system.
data ActionContext = ActionContext
{ contextService :: !Service -- ^ All initialized services; "the imperative shell"
, contextTimestamp :: !Timestamp -- ^ When the ActionContextM action is running (i.e., NOW)
, contextResourceState :: !InternalState -- ^ Optimization for MonadResource
, contextDB :: !DBConn -- ^ The specific connection chosen for the running action?
}
instance Has Service ActionContext where
view = contextService
instance Has Service.Notification.Notifications ActionContext where
view = view . contextService
instance Has Solr.Service.Solr ActionContext where
view = view . contextService
instance Has Ingest.Service.Ingest ActionContext where
view = view . contextService
instance Has Static.Service.Static ActionContext where
view = view . contextService
instance Has HTTP.Client.HTTPClient ActionContext where
view = view . contextService
instance Has Web.Types.Web ActionContext where
view = view . contextService
instance Has Store.AV.AV ActionContext where
view = view . contextService
instance Has Store.Types.Storage ActionContext where
view = view . contextService
instance Has Service.Messages.Messages ActionContext where
view = view . contextService
instance Has Service.Log.Logs ActionContext where
view = view . contextService
instance Has Service.Mail.Mailer ActionContext where
view = serviceMailer . contextService
instance Has Service.Passwd.Passwd ActionContext where
view = view . contextService
instance Has Service.Entropy.Entropy ActionContext where
view = view . contextService
instance Has Secret ActionContext where
view = view . contextService
instance Has InternalState ActionContext where
view = contextResourceState
instance Has DBConn ActionContext where
view = contextDB
type ActionContextM a = ReaderT ActionContext IO a
-- | Perform an atomic action without an identity with a guaranteed database
-- connection and a fixed version of 'now'.
runContextM
:: ActionContextM a
-> Service
-> IO a
runContextM action rc = do
t <- getCurrentTime
runResourceT $ withInternalState $ \is ->
withDB (serviceDB rc) $ runReaderT action . ActionContext rc t is
-- | A ActionContext with no Identity.
newtype BackgroundContext = BackgroundContext { backgroundContext :: ActionContext }
deriving
( Has Service
, Has Notifications
, Has Solr
, Has Ingest
, Has HTTPClient
, Has Storage
, Has Logs
, Has DBConn
)
instance Has Timestamp BackgroundContext where
view = contextTimestamp . backgroundContext
instance Has Identity BackgroundContext where
view _ = IdentityNotNeeded
instance Has SiteAuth BackgroundContext where
view _ = view IdentityNotNeeded
instance Has Party BackgroundContext where
view _ = view IdentityNotNeeded
instance Has (Id Party) BackgroundContext where
view _ = view IdentityNotNeeded
instance Has Access BackgroundContext where
view _ = view IdentityNotNeeded
type BackgroundContextM a = ReaderT BackgroundContext IO a
withBackgroundContextM :: BackgroundContextM a -> ActionContextM a
withBackgroundContextM = withReaderT BackgroundContext
-- | A ActionContext with no Identity, for running Solr indexing.
data SolrIndexingContext = SolrIndexingContext
{ slcLogs :: !Logs
, slcHTTPClient :: !HTTPClient
, slcSolr :: !Solr
, slcDB :: !DBConn -- ^ The specific connection chosen for the running action?
}
instance Has Solr SolrIndexingContext where
view = slcSolr
instance Has Logs SolrIndexingContext where
view = slcLogs
instance Has HTTPClient SolrIndexingContext where
view = slcHTTPClient
instance Has DBConn SolrIndexingContext where
view = slcDB
instance Has Identity SolrIndexingContext where
view _ = IdentityNotNeeded
instance Has SiteAuth SolrIndexingContext where
view _ = view IdentityNotNeeded
instance Has Party SolrIndexingContext where
view _ = view IdentityNotNeeded
instance Has (Id Party) SolrIndexingContext where
view _ = view IdentityNotNeeded
instance Has Access SolrIndexingContext where
view _ = view IdentityNotNeeded
type SolrIndexingContextM a = ReaderT SolrIndexingContext IO a
-- | Build a simpler SolrIndexingContext from a complete ActionContext
mkSolrIndexingContext :: ActionContext -> SolrIndexingContext
mkSolrIndexingContext ac =
SolrIndexingContext {
slcLogs = (serviceLogs . contextService) ac
, slcHTTPClient = (serviceHTTPClient . contextService) ac
, slcSolr = (serviceSolr . contextService) ac
, slcDB = contextDB ac
}
| databrary/databrary | src/Context.hs | agpl-3.0 | 5,615 | 0 | 13 | 953 | 1,215 | 668 | 547 | -1 | -1 |
main = putStrLn $ show $ foldl1 (\x y -> lcm x y) [1..20]
| rohitjha/ProjectEuler | MPL/PE005.hs | unlicense | 58 | 0 | 9 | 14 | 39 | 20 | 19 | 1 | 1 |
{-# LANGUAGE UnicodeSyntax #-}
module Service where
import Network.HTTP.Server
import Network.HTTP.Server.Logger
import Codec.Binary.UTF8.String
import Data.List (intercalate)
import Data.List.Split (splitOn)
import Paths_burningbar (version)
import Data.Version (showVersion)
import Util
import Language
import Parse
import Swift
import Checker
srv = serverWith config process
where process _ url request = case rqMethod request of
POST → (return ∘ sendJSON OK ∘ toSwift ∘ decodeString ∘ rqBody) request
otherwise → return $ sendJSON BadRequest "[\"C:。ミ\"]"
sendJSON ∷ StatusCode → String → Response String
sendJSON s v = headers reponse
where reponse = (respond s ∷ Response String) { rspBody = text }
headers = insertHeader HdrContentLength (show $ length text)
∘ insertHeader HdrContentEncoding "UTF-8"
∘ insertHeader HdrContentType "application/json"
∘ insertHeader (HdrCustom "Access-Control-Allow-Origin") "*"
text = encodeString v
toSwift = toJSON ∘ checkOrGen
where toJSON (Right (e, i)) = "{ \"Entities\": \"" ⧺ escape e
⧺ "\", \"Interface\": \"" ⧺ escape i
⧺ "\", " ⧺ ver ⧺ "\"}"
toJSON (Left err) = "{ \"error\": \"" ⧺ escape err ⧺ "\", " ⧺ ver ⧺ "\"}"
checkOrGen rawSpec = let errors = checkSpec rawSpec in
if null errors then Right (gen rawSpec)
else Left errors
gen = translator (swift False "Transport" "Interface") ∘ parse
ver = "\"version\": \"" ⧺ showVersion version
config = defaultConfig { srvLog = stdLogger, srvPort = 9604, srvHost = "0.0.0.0" }
-- | escapes quotes and newlines
-- >>> escape "\"\n"
-- "\\\"\\n"
escape = replace "\"" "\\\"" ∘ replace "\n" "\\n"
-- | relace substring
-- >>> replace "a" "b" "ab"
-- "bb"
replace old new = intercalate new ∘ splitOn old
| cfr/burningbar | src/Service.hs | unlicense | 2,019 | 0 | 16 | 526 | 516 | 272 | 244 | 39 | 3 |
module Haskoin.Crypto.Base58.Tests (tests) where
import Test.QuickCheck.Property hiding ((.&.))
import Test.Framework
import Test.Framework.Providers.QuickCheck2
import Control.Monad.Identity
import Data.Maybe
import Data.Word
import Data.Bits
import Data.Binary
import Data.Binary.Get
import Data.Binary.Put
import qualified Data.ByteString as BS
import QuickCheckUtils
import Haskoin.Crypto.Base58
tests :: [Test]
tests =
[ testGroup "Address and Base58"
[ testProperty "decode58( encode58(i) ) = i" decodeEncode58
, testProperty "decode58Chk( encode58Chk(i) ) = i" decodeEncode58Check
]
]
decodeEncode58 :: BS.ByteString -> Bool
decodeEncode58 bs = case decodeBase58 (encodeBase58 bs) of
(Just r) -> r == bs
Nothing -> False
decodeEncode58Check :: BS.ByteString -> Bool
decodeEncode58Check bs = case decodeBase58Check (encodeBase58Check bs) of
(Just r) -> r == bs
Nothing -> False
| lynchronan/haskoin-crypto | testsuite/Haskoin/Crypto/Base58/Tests.hs | unlicense | 943 | 0 | 9 | 166 | 239 | 137 | 102 | 27 | 2 |
module HEP.Automation.Model.Client.Command where
import HEP.Automation.Model.Client.ProgType
import HEP.Automation.Model.Client.Job
import HEP.Automation.Model.Client.Config
import Data.Configurator
commandLineProcess :: Model_client -> IO ()
commandLineProcess (Create cfg mn) = do
putStrLn "create called"
mc <- getModelClientConfiguration =<< load [Required cfg]
maybe (error "cannot parse config") (flip startCreate mn) mc
commandLineProcess (Get cfg n) = do
putStrLn "get called"
mc <- getModelClientConfiguration =<< load [Required cfg]
maybe (error "cannot parse config") (flip startGet n) mc
commandLineProcess (Put cfg n mn) = do
putStrLn "put called"
mc <- getModelClientConfiguration =<< load [Required cfg]
maybe (error "cannot parse config") (\c-> startPut c n mn) mc
commandLineProcess (Delete cfg n) = do
putStrLn "delete called"
mc <- getModelClientConfiguration =<< load [Required cfg]
maybe (error "cannot parse config") (flip startDelete n) mc
commandLineProcess (GetList cfg) = do
putStrLn "getlist called"
mc <- getModelClientConfiguration =<< load [Required cfg]
maybe (error "cannot parse config") startGetList mc
| wavewave/model-client | lib/HEP/Automation/Model/Client/Command.hs | bsd-2-clause | 1,179 | 0 | 11 | 184 | 381 | 185 | 196 | 26 | 1 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE FlexibleInstances #-}
------------------------------------------------------------------------------
-- | This module defines our application's state type and an alias for its
-- handler monad.
module Application where
------------------------------------------------------------------------------
import Control.Lens
import Control.Monad.State
import Snap.Snaplet
import Snap.Snaplet.Heist
import Snap.Snaplet.Auth
import Snap.Snaplet.Session
import Snap.Snaplet.SqliteSimple
------------------------------------------------------------------------------
data App = App
{ _heist :: Snaplet (Heist App)
, _sess :: Snaplet SessionManager
, _db :: Snaplet Sqlite
, _auth :: Snaplet (AuthManager App)
}
makeLenses ''App
instance HasHeist App where
heistLens = subSnaplet heist
instance HasSqlite (Handler b App) where
getSqliteState = with db get
------------------------------------------------------------------------------
type AppHandler = Handler App App
| kylcarte/qclib | src/Application.hs | bsd-3-clause | 1,043 | 0 | 11 | 140 | 170 | 98 | 72 | 21 | 0 |
-----------------------------------------------------------------------------
-- |
-- Module : Plugins.Monitors.Mem
-- Copyright : (c) Andrea Rossato
-- License : BSD-style (see LICENSE)
--
-- Maintainer : Jose A. Ortega Ruiz <[email protected]>
-- Stability : unstable
-- Portability : unportable
--
-- A memory monitor for Xmobar
--
-----------------------------------------------------------------------------
module Plugins.Monitors.Mem (memConfig, runMem, totalMem, usedMem) where
import Plugins.Monitors.Common
memConfig :: IO MConfig
memConfig = mkMConfig
"Mem: <usedratio>% (<cache>M)" -- template
["usedbar", "freebar", "usedratio", "total",
"free", "buffer", "cache", "rest", "used"] -- available replacements
fileMEM :: IO String
fileMEM = readFile "/proc/meminfo"
parseMEM :: IO [Float]
parseMEM =
do file <- fileMEM
let content = map words $ take 4 $ lines file
[total, free, buffer, cache] = map (\line -> (read $ line !! 1 :: Float) / 1024) content
rest = free + buffer + cache
used = total - rest
usedratio = used / total
return [usedratio, total, free, buffer, cache, rest, used]
totalMem :: IO Float
totalMem = fmap ((*1024) . (!!1)) parseMEM
usedMem :: IO Float
usedMem = fmap ((*1024) . (!!6)) parseMEM
formatMem :: [Float] -> Monitor [String]
formatMem (r:xs) =
do let f = showDigits 0
rr = 100 * r
ub <- showPercentBar rr r
fb <- showPercentBar (100 - rr) (1 - r)
rs <- showPercentWithColors r
s <- mapM (showWithColors f) xs
return (ub:fb:rs:s)
formatMem _ = return $ replicate 9 "N/A"
runMem :: [String] -> Monitor String
runMem _ =
do m <- io parseMEM
l <- formatMem m
parseTemplate l
| raboof/xmobar | src/Plugins/Monitors/Mem.hs | bsd-3-clause | 1,786 | 0 | 16 | 428 | 532 | 288 | 244 | 37 | 1 |
module Distribution.Redo
( -- * Redo Monad
Redo, runRedo
, debug
, Status(..), status
, DepPath(..)
, getDeps, addDep, clearDeps
, checkForChanges
, clearStatus, recordChanged, recordNoChange, recordBuildFailure
-- * Environment
, Vars(..), varsFromEnv
-- ** Paths
, Scripts(..), findScript, ScriptPath, TargetBasePath
, ProjDir
, TargetPath, doesTargetExist
, workerProcess
, mkSkeleton, cleanSkeleton
, Result(..), isBadResult
) where
import Distribution.Redo.Util
import Distribution.Redo.Env
import Distribution.Redo.Monad
import System.Directory
import System.FilePath
import System.Exit
data Result = Skip | Run ExitCode | Bad String
isBadResult :: Result -> Bool
isBadResult (Bad _) = True
isBadResult Skip = False
isBadResult (Run ExitSuccess) = False
isBadResult (Run (ExitFailure _)) = True
| Zankoku-Okuno/redo | src/Distribution/Redo.hs | bsd-3-clause | 889 | 0 | 9 | 191 | 230 | 143 | 87 | 28 | 1 |
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, FlexibleContexts, NoMonomorphismRestriction #-}
class Num a
(+) :: Int -> Int -> Int
x + y = x
data IO a
type String = [Char]
length :: [a] -> Int
length [] = 0
length (x:xs) = 1 + length xs
filter :: (a -> Bool) -> [a] -> [a]
words :: String -> [String]
class Eq a where
(==) :: a -> a -> Bool
class Monad m where
return :: a -> m a
(>>=) :: m a -> (a -> m b) -> m b
print :: Show a => a -> String
class Show a where
show :: a -> String
instance Show Int
(.) :: (b -> c) -> (a -> b) -> a -> c
f . g = \x -> f (g x)
class Compose a b c e f where
(<.>) :: (b -> c) -> (a -> e) -> (a -> f)
instance Compose a b c b c where
(<.>) = (.)
instance Monad m => Compose a b c (m b) (m c) where
(<.>) f g a = g a >>= (return . f)
count :: String -> String -> Int
count w = length <.> filter (==w) <.> words
main :: IO ()
main = ((print <.> count) "1") "1 2 3 1 4"
| rodrigogribeiro/mptc | test/overloaded-compose.hs | bsd-3-clause | 948 | 0 | 11 | 260 | 513 | 273 | 240 | -1 | -1 |
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree. An additional grant
-- of patent rights can be found in the PATENTS file in the same directory.
{-# LANGUAGE OverloadedStrings #-}
module Duckling.Numeral.DE.Corpus
( corpus ) where
import Prelude
import Data.String
import Duckling.Lang
import Duckling.Numeral.Types
import Duckling.Resolve
import Duckling.Testing.Types
corpus :: Corpus
corpus = (testContext {lang = DE}, allExamples)
allExamples :: [Example]
allExamples = concat
[ examples (NumeralValue 0)
[ "0"
, "null"
]
, examples (NumeralValue 1)
[ "1"
, "eins"
]
, examples (NumeralValue 3)
[ "3"
, "Drei"
]
, examples (NumeralValue 30)
[ "30"
, "dreissig"
]
, examples (NumeralValue 33)
[ "33"
, "drei Und dreissig"
, "dreiunddreissig"
, "0033"
]
, examples (NumeralValue 14)
[ "14"
, "vierzehn"
]
, examples (NumeralValue 16)
[ "16"
, "sechzehn"
]
, examples (NumeralValue 17)
[ "17"
, "Siebzehn"
]
, examples (NumeralValue 18)
[ "18"
, "achtzehn"
]
, examples (NumeralValue 200)
[ "200"
, "zwei hundert"
]
, examples (NumeralValue 102)
[ "102"
, "Hundert zwei"
]
, examples (NumeralValue 1.1)
[ "1,1"
, "1 komma 1"
, "1,10"
, "01,10"
]
, examples (NumeralValue 0.77)
[ "0,77"
, ",77"
]
, examples (NumeralValue 100000)
[ "100.000"
, "100000"
, "100K"
, "100k"
]
, examples (NumeralValue 3000000)
[ "3M"
, "3000K"
, "3000000"
, "3.000.000"
]
, examples (NumeralValue 1200000)
[ "1.200.000"
, "1200000"
, "1,2M"
, "1200K"
, ",0012G"
]
, examples (NumeralValue (-1200000))
[ "- 1.200.000"
, "-1200000"
, "minus 1.200.000"
, "negativ 1200000"
, "-1,2M"
, "-1200K"
, "-,0012G"
]
, examples (NumeralValue 5000)
[ "5 tausend"
, "fünf tausend"
]
, examples (NumeralValue 200000)
[ "zwei hundert tausend"
]
, examples (NumeralValue 721012)
[ "sieben hundert einundzwanzig tausend zwölf"
]
, examples (NumeralValue 31256721)
[ "ein und dreissig millionen zwei hundert sechs und fünfzig tausend sieben hundert ein und zwanzig"
]
, examples (NumeralValue 1416.15)
[ "1416,15"
]
, examples (NumeralValue 1416.15)
[ "1.416,15"
]
, examples (NumeralValue 1000000.0)
[ "1.000.000,00"
]
]
| rfranek/duckling | Duckling/Numeral/DE/Corpus.hs | bsd-3-clause | 3,367 | 0 | 11 | 1,484 | 605 | 346 | 259 | 95 | 1 |
{-# LANGUAGE TemplateHaskell, DeriveDataTypeable #-}
module SerializeableSessions where
import Data.Generics --for deriving Typeable
import HAppS.State -- for deriving Serialize
import SerializeableUsers (UserName (..))
import qualified Data.Map as M
type SessionKey = Integer
newtype SessionData = SessionData {
sesUser :: UserName
} deriving (Read,Show,Eq,Typeable,Data,Ord)
instance Version SessionData
$(deriveSerialize ''SessionData)
data Sessions a = Sessions {unsession::M.Map SessionKey a}
deriving (Read,Show,Eq,Typeable,Data)
instance Version (Sessions a)
$(deriveSerialize ''Sessions)
| tphyahoo/happs-tutorial | src/SerializeableSessions.hs | bsd-3-clause | 775 | 0 | 10 | 243 | 173 | 97 | 76 | 16 | 0 |
{-# LANGUAGE DataKinds, GADTs, StandaloneDeriving #-}
module Page3 () where
import Data.Type.Natural
import Page2
type RB a n = Either (Red a n) (Black a n)
type RBCrumb a n = Either (RedCrumb a n) (BlackCrumb a (S n))
data RedCrumb a n where
RootCrumb :: RedCrumb a n
RedCrumb :: a -> (Black a n) -> (BlackCrumb a (S n)) -> RedCrumb a n
data BlackCrumb a n where
BlackCrumb :: a -> (RB a n) -> (RBCrumb a (S n)) -> BlackCrumb a (S n)
deriving instance Show a => Show (BlackCrumb a n)
deriving instance Show a => Show (RedCrumb a n)
type RBZip a n = Either (RedZip a n) (BlackZip a n)
data RedZip a n where
RedZip :: a -> (Black a n) -> (Black a n) -> (BlackCrumb a (S n)) -> RedZip a n
data BlackZip a n where
LeafZip :: (RBCrumb a n) -> BlackZip a Z
Black2Zip :: a -> (Black a n) -> (Black a n) -> (RBCrumb a (S n)) -> BlackZip a (S n)
Black3Zip :: a -> (Red a n) -> (Black a n) -> (RBCrumb a (S n)) -> BlackZip a (S n)
Black4Zip :: a -> (Red a n) -> (Red a n) -> (RBCrumb a (S n)) -> BlackZip a (S n)
deriving instance Show a => Show (BlackZip a n)
deriving instance Show a => Show (RedZip a n)
toRootZip :: Black a n -> BlackZip a n
toRootZip b = toBlackZip b (Left RootCrumb)
toBlackZip :: Black a n -> RBCrumb a n -> BlackZip a n
toBlackZip Leaf c = LeafZip $ c
toBlackZip (Black2 v l r) c = Black2Zip v l r c
toBlackZip (Black3 v l r) c = Black3Zip v l r c
toBlackZip (Black4 v l r) c = Black4Zip v l r c
toRedZip :: Red a n -> BlackCrumb a (S n) -> RedZip a n
toRedZip (Red v l r) c = RedZip v l r c
findLeafB :: (Ord a) => a -> BlackZip a n -> BlackZip a Z
findLeafB u z@(LeafZip c) = z
findLeafB u (Black2Zip v l r c)
| u < v = findLeafB u $ toBlackZip l (Right $ BlackCrumb v (Right r) c)
| otherwise = findLeafB u $ toBlackZip r (Right $ BlackCrumb v (Right l) c)
findLeafB u (Black3Zip v l r c)
| u < v = findLeafR u . toRedZip l $ BlackCrumb v (Right r) c
| otherwise = findLeafB u $ toBlackZip r (Right $ BlackCrumb v (Left l) c)
findLeafB u (Black4Zip v l r c)
| u < v = findLeafR u . toRedZip l $ BlackCrumb v (Left r) c
| otherwise = findLeafR u $ toRedZip r $ BlackCrumb v (Left r) c
findLeafR :: (Ord a) => a -> RedZip a n -> BlackZip a Z
findLeafR u (RedZip v l r c)
| u < v = findLeafB u $ toBlackZip l (Left $ RedCrumb v r c)
| otherwise = findLeafB u $ toBlackZip r (Left $ RedCrumb v l c)
-- inject :: a -> BlackZip a Z -> RedZip a Z
-- inject v (LeafZip c) = RedZip v Leaf Leaf c
| farrellm/dependent-rbtree | src/Page3.hs | bsd-3-clause | 2,473 | 34 | 23 | 610 | 1,227 | 617 | 610 | 47 | 1 |
{-# OPTIONS -fno-warn-tabs #-}
-- The above warning supression flag is a temporary kludge.
-- While working on this module you are encouraged to remove it and
-- detab the module (please do the detabbing in a separate patch). See
-- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#TabsvsSpaces
-- for details
module SPARC.CodeGen.CondCode (
getCondCode,
condIntCode,
condFltCode
)
where
import {-# SOURCE #-} SPARC.CodeGen.Gen32
import SPARC.CodeGen.Base
import SPARC.Instr
import SPARC.Regs
import SPARC.Cond
import SPARC.Imm
import SPARC.Base
import NCGMonad
import Size
import OldCmm
import OrdList
import Outputable
getCondCode :: CmmExpr -> NatM CondCode
getCondCode (CmmMachOp mop [x, y])
=
case mop of
MO_F_Eq W32 -> condFltCode EQQ x y
MO_F_Ne W32 -> condFltCode NE x y
MO_F_Gt W32 -> condFltCode GTT x y
MO_F_Ge W32 -> condFltCode GE x y
MO_F_Lt W32 -> condFltCode LTT x y
MO_F_Le W32 -> condFltCode LE x y
MO_F_Eq W64 -> condFltCode EQQ x y
MO_F_Ne W64 -> condFltCode NE x y
MO_F_Gt W64 -> condFltCode GTT x y
MO_F_Ge W64 -> condFltCode GE x y
MO_F_Lt W64 -> condFltCode LTT x y
MO_F_Le W64 -> condFltCode LE x y
MO_Eq _ -> condIntCode EQQ x y
MO_Ne _ -> condIntCode NE x y
MO_S_Gt _ -> condIntCode GTT x y
MO_S_Ge _ -> condIntCode GE x y
MO_S_Lt _ -> condIntCode LTT x y
MO_S_Le _ -> condIntCode LE x y
MO_U_Gt _ -> condIntCode GU x y
MO_U_Ge _ -> condIntCode GEU x y
MO_U_Lt _ -> condIntCode LU x y
MO_U_Le _ -> condIntCode LEU x y
_ -> pprPanic "SPARC.CodeGen.CondCode.getCondCode" (ppr (CmmMachOp mop [x,y]))
getCondCode other = pprPanic "SPARC.CodeGen.CondCode.getCondCode" (ppr other)
-- @cond(Int|Flt)Code@: Turn a boolean expression into a condition, to be
-- passed back up the tree.
condIntCode :: Cond -> CmmExpr -> CmmExpr -> NatM CondCode
condIntCode cond x (CmmLit (CmmInt y _))
| fits13Bits y
= do
(src1, code) <- getSomeReg x
let
src2 = ImmInt (fromInteger y)
code' = code `snocOL` SUB False True src1 (RIImm src2) g0
return (CondCode False cond code')
condIntCode cond x y = do
(src1, code1) <- getSomeReg x
(src2, code2) <- getSomeReg y
let
code__2 = code1 `appOL` code2 `snocOL`
SUB False True src1 (RIReg src2) g0
return (CondCode False cond code__2)
condFltCode :: Cond -> CmmExpr -> CmmExpr -> NatM CondCode
condFltCode cond x y = do
(src1, code1) <- getSomeReg x
(src2, code2) <- getSomeReg y
tmp <- getNewRegNat FF64
let
promote x = FxTOy FF32 FF64 x tmp
pk1 = cmmExprType x
pk2 = cmmExprType y
code__2 =
if pk1 `cmmEqType` pk2 then
code1 `appOL` code2 `snocOL`
FCMP True (cmmTypeSize pk1) src1 src2
else if typeWidth pk1 == W32 then
code1 `snocOL` promote src1 `appOL` code2 `snocOL`
FCMP True FF64 tmp src2
else
code1 `appOL` code2 `snocOL` promote src2 `snocOL`
FCMP True FF64 src1 tmp
return (CondCode True cond code__2)
| nomeata/ghc | compiler/nativeGen/SPARC/CodeGen/CondCode.hs | bsd-3-clause | 3,235 | 34 | 14 | 926 | 1,028 | 511 | 517 | 80 | 23 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveFoldable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE ImplicitParams #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE ViewPatterns #-}
{- |
Module : Verifier.SAW.TypedAST
Copyright : Galois, Inc. 2012-2015
License : BSD3
Maintainer : [email protected]
Stability : experimental
Portability : non-portable (language extensions)
-}
module Verifier.SAW.TypedAST
( -- * Module operations.
Module
, emptyModule
, ModuleName, mkModuleName
, moduleName
, preludeName
, ModuleDecl(..)
, moduleDecls
, allModuleDecls
, TypedDataType
, moduleDataTypes
, moduleImports
, findDataType
, TypedCtor
, moduleCtors
, findCtor
, TypedDef
, TypedDefEqn
, moduleDefs
, allModuleDefs
, findDef
, insImport
, insDataType
, insDef
, moduleActualDefs
, allModuleActualDefs
, modulePrimitives
, allModulePrimitives
, moduleAxioms
, allModuleAxioms
-- * Data types and defintiions.
, DataType(..)
, Ctor(..)
, GenericDef(..)
, Def
, DefQualifier(..)
, LocalDef
, localVarNames
, DefEqn(..)
, Pat(..)
, patBoundVarCount
, patUnusedVarCount
-- * Terms and associated operations.
, Term(..)
, incVars
, piArgCount
, TermF(..)
, FlatTermF(..)
, Termlike(..)
, zipWithFlatTermF
, freesTerm
, freesTermF
, termToPat
, LocalVarDoc
, emptyLocalVarDoc
, docShowLocalNames
, docShowLocalTypes
, TermPrinter
, Prec(..)
, ppAppParens
, ppTerm
, ppTermF
, ppTermF'
, ppFlatTermF
, ppRecordF
, ppTermDepth
-- * Primitive types.
, Sort, mkSort, sortOf, maxSort
, Ident(identModule, identName), mkIdent
, parseIdent
, isIdent
, ppIdent
, ppDefEqn
, DeBruijnIndex
, FieldName
, instantiateVarList
, ExtCns(..)
, VarIndex
-- * Utility functions
, BitSet
, commaSepList
, semiTermList
, ppParens
) where
import Control.Applicative hiding (empty)
import Control.Exception (assert)
import Control.Lens
import Data.Bits
import qualified Data.ByteString.UTF8 as BS
import Data.Char
#if !MIN_VERSION_base(4,8,0)
import Data.Foldable (Foldable)
#endif
import Data.Foldable (foldl', sum, all)
import Data.Hashable
import Data.List (intercalate)
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Vector (Vector)
import qualified Data.Vector as V
import Data.Word
import GHC.Generics (Generic)
import GHC.Exts (IsString(..))
import Text.PrettyPrint.ANSI.Leijen hiding ((<$>))
import qualified Text.PrettyPrint.ANSI.Leijen as Leijen ((<$>))
import qualified Text.PrettyPrint.ANSI.Leijen as PPL
import Prelude hiding (all, foldr, sum)
import Verifier.SAW.Utils (internalError, sumBy)
import qualified Verifier.SAW.TermNet as Net
(<<$>>) :: Doc -> Doc -> Doc
x <<$>> y = (PPL.<$>) x y
instance (Hashable k, Hashable a) => Hashable (Map k a) where
hashWithSalt x m = hashWithSalt x (Map.assocs m)
instance Hashable a => Hashable (Vector a) where
hashWithSalt x v = hashWithSalt x (V.toList v)
doublecolon :: Doc
doublecolon = colon <> colon
-- | Print a list of items separated by semicolons
semiTermList :: [Doc] -> Doc
semiTermList = hsep . fmap (<> semi)
commaSepList :: [Doc] -> Doc
commaSepList [] = empty
commaSepList [d] = d
commaSepList (d:l) = d <> comma <+> commaSepList l
-- | Add parenthesis around a document if condition is true.
ppParens :: Bool -> Doc -> Doc
ppParens b = if b then parens . align else id
newtype ModuleName = ModuleName BS.ByteString -- [String]
deriving (Eq, Ord, Generic)
instance Hashable ModuleName -- automatically derived
instance Show ModuleName where
show (ModuleName s) = BS.toString s
-- | Crete a module name given a list of strings with the top-most
-- module name given first.
mkModuleName :: [String] -> ModuleName
mkModuleName [] = error "internal: mkModuleName given empty module name"
mkModuleName nms = assert (all isCtor nms) $ ModuleName (BS.fromString s)
where s = intercalate "." (reverse nms)
isIdent :: String -> Bool
isIdent (c:l) = isAlpha c && all isIdChar l
isIdent [] = False
isCtor :: String -> Bool
isCtor (c:l) = isUpper c && all isIdChar l
isCtor [] = False
-- | Returns true if character can appear in identifier.
isIdChar :: Char -> Bool
isIdChar c = isAlphaNum c || (c == '_') || (c == '\'')
preludeName :: ModuleName
preludeName = mkModuleName ["Prelude"]
data Ident = Ident { identModule :: ModuleName
, identName :: String
}
deriving (Eq, Ord, Generic)
instance Hashable Ident -- automatically derived
instance Show Ident where
show (Ident m s) = shows m ('.' : s)
mkIdent :: ModuleName -> String -> Ident
mkIdent = Ident
-- | Parse a fully qualified identifier.
parseIdent :: String -> Ident
parseIdent s0 =
case reverse (breakEach s0) of
(_:[]) -> internalError $ "parseIdent given empty module name."
(nm:rMod) -> mkIdent (mkModuleName (reverse rMod)) nm
_ -> internalError $ "parseIdent given bad identifier " ++ show s0
where breakEach s =
case break (=='.') s of
(h,[]) -> [h]
(h,'.':r) -> h : breakEach r
_ -> internalError "parseIdent.breakEach failed"
instance IsString Ident where
fromString = parseIdent
newtype Sort = SortCtor { _sortIndex :: Integer }
deriving (Eq, Ord, Generic)
instance Hashable Sort -- automatically derived
instance Show Sort where
showsPrec p (SortCtor i) = showParen (p >= 10) (showString "sort " . shows i)
-- | Create sort for given integer.
mkSort :: Integer -> Sort
mkSort i | 0 <= i = SortCtor i
| otherwise = error "Negative index given to sort."
-- | Returns sort of the given sort.
sortOf :: Sort -> Sort
sortOf (SortCtor i) = SortCtor (i + 1)
-- | Returns the larger of the two sorts.
maxSort :: Sort -> Sort -> Sort
maxSort (SortCtor x) (SortCtor y) = SortCtor (max x y)
type DeBruijnIndex = Int
type FieldName = String
-- Patterns are used to match equations.
data Pat e = -- | Variable bound by pattern.
-- Variables may be bound in context in a different order than
-- a left-to-right traversal. The DeBruijnIndex indicates the order.
PVar String DeBruijnIndex e
-- | The
| PUnused DeBruijnIndex e
| PUnit
| PPair (Pat e) (Pat e)
| PRecord (Map FieldName (Pat e))
-- An arbitrary term that matches anything, but needs to be later
-- verified to be equivalent.
| PCtor Ident [Pat e]
deriving (Eq,Ord, Show, Functor, Foldable, Traversable, Generic)
instance Hashable e => Hashable (Pat e) -- automatically derived
patBoundVarCount :: Pat e -> DeBruijnIndex
patBoundVarCount p =
case p of
PVar{} -> 1
PUnused{} -> 0
PCtor _ l -> sumBy patBoundVarCount l
PUnit -> 0
PPair x y -> patBoundVarCount x + patBoundVarCount y
PRecord m -> sumBy patBoundVarCount m
patUnusedVarCount :: Pat e -> DeBruijnIndex
patUnusedVarCount p =
case p of
PVar{} -> 0
PUnused{} -> 1
PCtor _ l -> sumBy patUnusedVarCount l
PUnit -> 0
PPair x y -> patUnusedVarCount x + patUnusedVarCount y
PRecord m -> sumBy patUnusedVarCount m
patBoundVars :: Pat e -> [String]
patBoundVars p =
case p of
PVar s _ _ -> [s]
PCtor _ l -> concatMap patBoundVars l
PUnit -> []
PPair x y -> patBoundVars x ++ patBoundVars y
PRecord m -> concatMapOf folded patBoundVars m
_ -> []
lift2 :: (a -> b) -> (b -> b -> c) -> a -> a -> c
lift2 f h x y = h (f x) (f y)
data DefQualifier
= NoQualifier
| PrimQualifier
| AxiomQualifier
deriving (Eq,Ord,Show,Generic)
instance Hashable DefQualifier -- automatically derived
-- | A Definition contains an identifier, the type of the definition, and a list of equations.
data GenericDef n e =
Def { defIdent :: n
, defQualifier :: DefQualifier
, defType :: e
, defEqs :: [DefEqn e]
}
deriving (Eq, Ord, Show, Functor, Foldable, Traversable, Generic)
type Def = GenericDef Ident
type LocalDef = GenericDef String
instance (Hashable n, Hashable e) => Hashable (GenericDef n e) -- automatically derived
localVarNames :: LocalDef e -> [String]
localVarNames (Def nm _ _ _) = [nm]
data LocalVarDoc = LVD { docModuleName :: Map ModuleName String
, _docShowLocalNames :: Bool
, _docShowLocalTypes :: Bool
, docMap :: !(Map DeBruijnIndex Doc)
, docLvl :: !DeBruijnIndex
, docUsedMap :: Map String DeBruijnIndex
}
-- | Flag indicates doc should use local names (default True)
docShowLocalNames :: Simple Lens LocalVarDoc Bool
docShowLocalNames = lens _docShowLocalNames (\s v -> s { _docShowLocalNames = v })
-- | Flag indicates doc should print type for locals (default false)
docShowLocalTypes :: Simple Lens LocalVarDoc Bool
docShowLocalTypes = lens _docShowLocalTypes (\s v -> s { _docShowLocalTypes = v })
emptyLocalVarDoc :: LocalVarDoc
emptyLocalVarDoc = LVD { docModuleName = Map.empty
, _docShowLocalNames = True
, _docShowLocalTypes = False
, docMap = Map.empty
, docLvl = 0
, docUsedMap = Map.empty
}
freshVariant :: Map String a -> String -> String
freshVariant used name
| Map.member name used = freshVariant used (name ++ "'")
| otherwise = name
consBinding :: LocalVarDoc -> String -> LocalVarDoc
consBinding lvd i = lvd { docMap = Map.insert lvl (text i) m
, docLvl = lvl + 1
, docUsedMap = Map.insert i lvl (docUsedMap lvd)
}
where lvl = docLvl lvd
m = case Map.lookup i (docUsedMap lvd) of
Just pl -> Map.delete pl (docMap lvd)
Nothing -> docMap lvd
lookupDoc :: LocalVarDoc -> DeBruijnIndex -> Doc
lookupDoc lvd i
| lvd^.docShowLocalNames =
case Map.lookup lvl (docMap lvd) of
Just d -> d
Nothing -> text ('!' : show (i - docLvl lvd))
| otherwise = text ('!' : show i)
where lvl = docLvl lvd - i - 1
data DefEqn e
= DefEqn [Pat e] e -- ^ List of patterns and a right hand side
deriving (Functor, Foldable, Traversable, Generic, Show)
instance Hashable e => Hashable (DefEqn e) -- automatically derived
instance (Eq e) => Eq (DefEqn e) where
DefEqn xp xr == DefEqn yp yr = xp == yp && xr == yr
instance (Ord e) => Ord (DefEqn e) where
compare (DefEqn xp xr) (DefEqn yp yr) = compare (xp,xr) (yp,yr)
data Ctor n tp = Ctor { ctorName :: !n
-- | The type of the constructor (should contain no free variables).
, ctorType :: tp
}
deriving (Functor, Foldable, Traversable)
instance Eq n => Eq (Ctor n tp) where
(==) = lift2 ctorName (==)
instance Ord n => Ord (Ctor n tp) where
compare = lift2 ctorName compare
instance Show n => Show (Ctor n tp) where
show = show . ctorName
ppCtor :: TermPrinter e -> Ctor Ident e -> Doc
ppCtor f c = hang 2 $ group (ppIdent (ctorName c) <<$>> doublecolon <+> tp)
where lcls = emptyLocalVarDoc
tp = f lcls PrecLambda (ctorType c)
data DataType n t = DataType { dtName :: n
, dtType :: t
, dtCtors :: [Ctor n t]
, dtIsPrimitive :: Bool
}
deriving (Functor, Foldable, Traversable)
instance Eq n => Eq (DataType n t) where
(==) = lift2 dtName (==)
instance Ord n => Ord (DataType n t) where
compare = lift2 dtName compare
instance Show n => Show (DataType n t) where
show = show . dtName
ppDataType :: TermPrinter e -> DataType Ident e -> Doc
ppDataType f dt =
group $ (group ((text "data" <+> tc) <<$>> (text "where" <+> lbrace)))
<<$>>
vcat ((indent 2 . ppc) <$> dtCtors dt)
<$$>
rbrace
where lcls = emptyLocalVarDoc
sym = ppIdent (dtName dt)
tc = ppTypeConstraint f lcls sym (dtType dt)
ppc c = ppCtor f c <> semi
type VarIndex = Word64
-- NB: If you add constructors to FlatTermF, make sure you update
-- zipWithFlatTermF!
data FlatTermF e
= GlobalDef !Ident -- ^ Global variables are referenced by label.
-- Tuples are represented as nested pairs, grouped to the right,
-- terminated with unit at the end.
| UnitValue
| UnitType
| PairValue e e
| PairType e e
| PairLeft e
| PairRight e
| RecordValue (Map FieldName e)
| RecordType (Map FieldName e)
| RecordSelector e FieldName
| CtorApp !Ident ![e]
| DataTypeApp !Ident ![e]
| Sort !Sort
-- Primitive builtin values
-- | Natural number with given value (negative numbers are not allowed).
| NatLit !Integer
-- | Array value includes type of elements followed by elements.
| ArrayValue e (Vector e)
-- | Floating point literal
| FloatLit !Float
-- | Double precision floating point literal.
| DoubleLit !Double
-- | String literal.
| StringLit !String
-- | An external constant with a name.
| ExtCns !(ExtCns e)
deriving (Eq, Ord, Functor, Foldable, Traversable, Generic)
-- | An external constant with a name.
-- Names are necessarily unique, but the var index should be.
data ExtCns e = EC { ecVarIndex :: !VarIndex
, ecName :: !String
, ecType :: !e
}
deriving (Functor, Foldable, Traversable)
instance Eq (ExtCns e) where
x == y = ecVarIndex x == ecVarIndex y
instance Ord (ExtCns e) where
compare x y = compare (ecVarIndex x) (ecVarIndex y)
instance Hashable (ExtCns e) where
hashWithSalt x ec = hashWithSalt x (ecVarIndex ec)
instance Hashable e => Hashable (FlatTermF e) -- automatically derived
zipWithFlatTermF :: (x -> y -> z) -> FlatTermF x -> FlatTermF y -> Maybe (FlatTermF z)
zipWithFlatTermF f = go
where go (GlobalDef x) (GlobalDef y) | x == y = Just $ GlobalDef x
go UnitValue UnitValue = Just UnitValue
go UnitType UnitType = Just UnitType
go (PairValue x1 x2) (PairValue y1 y2) = Just (PairValue (f x1 y1) (f x2 y2))
go (PairType x1 x2) (PairType y1 y2) = Just (PairType (f x1 y1) (f x2 y2))
go (PairLeft x) (PairLeft y) = Just (PairLeft (f x y))
go (PairRight x) (PairRight y) = Just (PairLeft (f x y))
go (RecordValue mx) (RecordValue my)
| Map.keys mx == Map.keys my =
Just $ RecordValue $ Map.intersectionWith f mx my
go (RecordSelector x fx) (RecordSelector y fy)
| fx == fy = Just $ RecordSelector (f x y) fx
go (RecordType mx) (RecordType my)
| Map.keys mx == Map.keys my =
Just $ RecordType (Map.intersectionWith f mx my)
go (CtorApp cx lx) (CtorApp cy ly)
| cx == cy = Just $ CtorApp cx (zipWith f lx ly)
go (DataTypeApp dx lx) (DataTypeApp dy ly)
| dx == dy = Just $ DataTypeApp dx (zipWith f lx ly)
go (Sort sx) (Sort sy) | sx == sy = Just (Sort sx)
go (NatLit i) (NatLit j) | i == j = Just (NatLit i)
go (FloatLit fx) (FloatLit fy)
| fx == fy = Just $ FloatLit fx
go (DoubleLit fx) (DoubleLit fy)
| fx == fy = Just $ DoubleLit fx
go (StringLit s) (StringLit t) | s == t = Just (StringLit s)
go (ArrayValue tx vx) (ArrayValue ty vy)
| V.length vx == V.length vy = Just $ ArrayValue (f tx ty) (V.zipWith f vx vy)
go (ExtCns (EC xi xn xt)) (ExtCns (EC yi _ yt))
| xi == yi = Just (ExtCns (EC xi xn (f xt yt)))
go _ _ = Nothing
data TermF e
= FTermF !(FlatTermF e) -- ^ Global variables are referenced by label.
| App !e !e
| Lambda !String !e !e
| Pi !String !e !e
-- | List of bindings and the let expression itself.
-- Let expressions introduce variables for each identifier.
-- Let definitions are bound in the order they appear, e.g., the first symbol
-- is referred to by the largest deBruijnIndex within the let, and the last
-- symbol has index 0 within the let.
| Let [LocalDef e] !e
-- | Local variables are referenced by deBruijn index.
-- The type of the var is in the context of when the variable was bound.
| LocalVar !DeBruijnIndex
| Constant String !e !e -- ^ An abstract constant packaged with its definition and type.
deriving (Eq, Ord, Functor, Foldable, Traversable, Generic)
instance Hashable e => Hashable (TermF e) -- automatically derived.
class Termlike t where
unwrapTermF :: t -> TermF t
termToPat :: Termlike t => t -> Net.Pat
termToPat t =
case unwrapTermF t of
Constant d _ _ -> Net.Atom d
App t1 t2 -> Net.App (termToPat t1) (termToPat t2)
FTermF (GlobalDef d) -> Net.Atom (identName d)
FTermF (Sort s) -> Net.Atom ('*' : show s)
FTermF (NatLit n) -> Net.Atom (show n)
FTermF (DataTypeApp c ts) -> foldl Net.App (Net.Atom (identName c)) (map termToPat ts)
FTermF (CtorApp c ts) -> foldl Net.App (Net.Atom (identName c)) (map termToPat ts)
_ -> Net.Var
instance Net.Pattern Term where
toPat = termToPat
ppIdent :: Ident -> Doc
ppIdent i = text (show i)
ppTypeConstraint :: TermPrinter e -> LocalVarDoc -> Doc -> e -> Doc
ppTypeConstraint f lcls sym tp = hang 2 $ group (sym <<$>> doublecolon <+> f lcls PrecLambda tp)
ppDef :: LocalVarDoc -> Def Term -> Doc
ppDef lcls d = vcat (tpd : (ppDefEqn ppTerm lcls sym <$> (reverse $ defEqs d)))
where sym = ppIdent (defIdent d)
tpd = ppTypeConstraint ppTerm lcls sym (defType d) <> semi
ppLocalDef :: Applicative f
=> (LocalVarDoc -> Prec -> e -> f Doc)
-> LocalVarDoc -- ^ Context outside let
-> LocalVarDoc -- ^ Context inside let
-> LocalDef e
-> f Doc
ppLocalDef pp lcls lcls' (Def nm _qual tp eqs) =
ppd <$> (pptc <$> pp lcls PrecLambda tp)
<*> traverse (ppDefEqnF pp lcls' sym) (reverse eqs)
where sym = text nm
pptc tpd = hang 2 $ group (sym <<$>> doublecolon <+> tpd <> semi)
ppd tpd eqds = vcat (tpd : eqds)
ppDefEqn :: TermPrinter e -> LocalVarDoc -> Doc -> DefEqn e -> Doc
ppDefEqn pp lcls sym eq = runIdentity (ppDefEqnF pp' lcls sym eq)
where pp' l' p' e' = pure (pp l' p' e')
ppDefEqnF :: Applicative f
=> (LocalVarDoc -> Prec -> e -> f Doc)
-> LocalVarDoc -> Doc -> DefEqn e -> f Doc
ppDefEqnF f lcls sym (DefEqn pats rhs) =
ppEq <$> traverse ppPat' pats
-- Is this OK?
<*> f lcls' PrecNone rhs
-- <*> f lcls' PrecLambda rhs
where ppEq pd rhs' = group $ nest 2 (sym <+> (hsep (pd++[equals])) <<$>> rhs' <> semi)
lcls' = foldl' consBinding lcls (concatMap patBoundVars pats)
ppPat' = ppPat (f lcls') PrecArg
data Prec
= PrecNone -- ^ Nonterminal 'Term'
| PrecLambda -- ^ Nonterminal 'LTerm'
| PrecApp -- ^ Nonterminal 'AppTerm'
| PrecArg -- ^ Nonterminal 'AppArg'
deriving (Eq, Ord)
ppAppParens :: Prec -> Doc -> Doc
ppAppParens p d = ppParens (p > PrecApp) d
ppAppList :: Prec -> Doc -> [Doc] -> Doc
ppAppList _ sym [] = sym
ppAppList p sym l = ppAppParens p $ hsep (sym : l)
ppPat :: Applicative f
=> (Prec -> e -> f Doc)
-> Prec -> Pat e -> f Doc
ppPat f p pat =
case pat of
PVar i _ _ -> pure (text i)
PUnused{} -> pure (char '_')
PCtor c pl -> ppAppList p (ppIdent c) <$> traverse (ppPat f PrecArg) pl
PUnit -> pure $ text "()"
PPair x y -> ppParens (p > PrecApp) <$>
(infixDoc "#" <$> ppPat f PrecApp x <*> ppPat f PrecApp y)
PRecord m -> ppRecordF (ppPat f PrecNone) m
type TermPrinter e = LocalVarDoc -> Prec -> e -> Doc
ppRecordF :: Applicative f => (t -> f Doc) -> Map String t -> f Doc
ppRecordF pp m = braces . semiTermList <$> traverse ppFld (Map.toList m)
where ppFld (fld,v) = eqCat (text fld) <$> pp v
eqCat x y = group $ nest 2 (x <+> equals <<$>> y)
infixDoc :: String -> Doc -> Doc -> Doc
infixDoc s x y = x <+> text s <+> y
ppFlatTermF :: Applicative f => (Prec -> t -> f Doc) -> Prec -> FlatTermF t -> f Doc
ppFlatTermF pp prec tf =
case tf of
GlobalDef i -> pure $ ppIdent i
UnitValue -> pure $ text "()"
UnitType -> pure $ text "#()"
PairValue x y -> ppParens (prec > PrecApp) <$>
(infixDoc "#" <$> pp PrecApp x <*> pp PrecApp y)
PairType x y -> ppParens (prec > PrecApp) <$>
(infixDoc "*" <$> pp PrecApp x <*> pp PrecApp y)
PairLeft t -> ppParens (prec > PrecArg) . (<> (text ".L")) <$> pp PrecArg t
PairRight t -> ppParens (prec > PrecArg) . (<> (text ".R")) <$> pp PrecArg t
{-
TupleValue l -> tupled <$> traverse (pp PrecNone) l
TupleType l -> (char '#' <>) . tupled <$> traverse (pp PrecNone) l
TupleSelector t i -> ppParens (prec > PrecArg)
. (<> (char '.' <> int i)) <$> pp PrecArg t
-}
RecordValue m -> ppRecordF (pp PrecNone) m
RecordType m -> (char '#' <>) <$> ppRecordF (pp PrecNone) m
RecordSelector t f -> ppParens (prec > PrecArg)
. (<> (char '.' <> text f)) <$> pp PrecArg t
CtorApp c l -> ppAppList prec (ppIdent c) <$> traverse (pp PrecArg) l
DataTypeApp dt l -> ppAppList prec (ppIdent dt) <$> traverse (pp PrecArg) l
Sort s -> pure $ text (show s)
NatLit i -> pure $ integer i
ArrayValue _ vl -> list <$> traverse (pp PrecNone) (V.toList vl)
FloatLit v -> pure $ text (show v)
DoubleLit v -> pure $ text (show v)
StringLit s -> pure $ text (show s)
ExtCns (EC _ v _) -> pure $ text v
newtype Term = Term (TermF Term)
deriving (Eq)
instance Termlike Term where
unwrapTermF (Term tf) = tf
{-
asApp :: Term -> (Term, [Term])
asApp = go []
where go l (Term (FTermF (App t u))) = go (u:l) t
go l t = (t,l)
-}
-- | Returns the number of nested pi expressions.
piArgCount :: Term -> Int
piArgCount = go 0
where go i (Term (Pi _ _ rhs)) = go (i+1) rhs
go i _ = i
bitwiseOrOf :: (Bits a, Num a) => Fold s a -> s -> a
bitwiseOrOf fld = foldlOf' fld (.|.) 0
-- | A @BitSet@ represents a set of natural numbers.
-- Bit n is a 1 iff n is in the set.
type BitSet = Integer
freesPat :: Pat BitSet -> BitSet
freesPat p0 =
case p0 of
PVar _ i tp -> tp `shiftR` i
PUnused i tp -> tp `shiftR` i
PUnit -> 0
PPair x y -> freesPat x .|. freesPat y
PRecord pm -> bitwiseOrOf folded (freesPat <$> pm)
PCtor _ pl -> bitwiseOrOf folded (freesPat <$> pl)
freesDefEqn :: DefEqn BitSet -> BitSet
freesDefEqn (DefEqn pl rhs) =
bitwiseOrOf folded (freesPat <$> pl) .|. rhs `shiftR` pc
where pc = sum (patBoundVarCount <$> pl)
freesTermF :: TermF BitSet -> BitSet
freesTermF tf =
case tf of
FTermF ftf -> bitwiseOrOf folded ftf
App l r -> l .|. r
Lambda _name tp rhs -> tp .|. rhs `shiftR` 1
Pi _name lhs rhs -> lhs .|. rhs `shiftR` 1
Let lcls rhs ->
bitwiseOrOf (folded . folded) lcls' .|. rhs `shiftR` n
where n = length lcls
freesLocalDef :: LocalDef BitSet -> [BitSet]
freesLocalDef (Def _ _ tp eqs) =
tp : fmap ((`shiftR` n) . freesDefEqn) eqs
lcls' = freesLocalDef <$> lcls
LocalVar i -> bit i
Constant _ _ _ -> 0 -- assume rhs is a closed term
freesTerm :: Term -> BitSet
freesTerm (Term t) = freesTermF (fmap freesTerm t)
-- | @instantiateVars f l t@ substitutes each dangling bound variable
-- @LocalVar j t@ with the term @f i j t@, where @i@ is the number of
-- binders surrounding @LocalVar j t@.
instantiateVars :: (DeBruijnIndex -> DeBruijnIndex -> Term)
-> DeBruijnIndex -> Term -> Term
instantiateVars f initialLevel = go initialLevel
where goList :: DeBruijnIndex -> [Term] -> [Term]
goList _ [] = []
goList l (e:r) = go l e : goList (l+1) r
gof l ftf =
case ftf of
PairValue x y -> PairValue (go l x) (go l y)
PairType a b -> PairType (go l a) (go l b)
PairLeft x -> PairLeft (go l x)
PairRight x -> PairRight (go l x)
RecordValue m -> RecordValue $ go l <$> m
RecordSelector x fld -> RecordSelector (go l x) fld
RecordType m -> RecordType $ go l <$> m
CtorApp c ll -> CtorApp c (goList l ll)
DataTypeApp dt ll -> DataTypeApp dt (goList l ll)
_ -> ftf
go :: DeBruijnIndex -> Term -> Term
go l (Term tf) =
case tf of
FTermF ftf -> Term $ FTermF $ gof l ftf
App x y -> Term $ App (go l x) (go l y)
Constant _ _rhs _ -> Term tf -- assume rhs is a closed term, so leave it unchanged
Lambda i tp rhs -> Term $ Lambda i (go l tp) (go (l+1) rhs)
Pi i lhs rhs -> Term $ Pi i (go l lhs) (go (l+1) rhs)
Let defs r -> Term $ Let (procDef <$> defs) (go l' r)
where l' = l + length defs
procDef (Def sym qual tp eqs) = Def sym qual tp' eqs'
where tp' = go l tp
eqs' = procEq <$> eqs
procEq (DefEqn pats rhs) = DefEqn pats (go eql rhs)
where eql = l' + sum (patBoundVarCount <$> pats)
LocalVar i
| i < l -> Term $ LocalVar i
| otherwise -> f l i
-- | @incVars j k t@ increments free variables at least @j@ by @k@.
-- e.g., incVars 1 2 (C ?0 ?1) = C ?0 ?3
incVars :: DeBruijnIndex -> DeBruijnIndex -> Term -> Term
incVars _ 0 = id
incVars initialLevel j = assert (j > 0) $ instantiateVars fn initialLevel
where fn _ i = Term $ LocalVar (i+j)
-- | Substitute @ts@ for variables @[k .. k + length ts - 1]@ and
-- decrement all higher loose variables by @length ts@.
instantiateVarList :: DeBruijnIndex -> [Term] -> Term -> Term
instantiateVarList _ [] = id
instantiateVarList k ts = instantiateVars fn 0
where
l = length ts
-- Use terms to memoize instantiated versions of ts.
terms = [ [ incVars 0 i t | i <- [0..] ] | t <- ts ]
-- Instantiate variables [k .. k+l-1].
fn i j | j >= i + k + l = Term $ LocalVar (j - l)
| j >= i + k = (terms !! (j - i - k)) !! i
| otherwise = Term $ LocalVar j
-- ^ Specification in terms of @instantiateVar@ (by example):
-- @instantiateVarList 0 [x,y,z] t@ is the beta-reduced form of @Lam
-- (Lam (Lam t)) `App` z `App` y `App` x@, i.e. @instantiateVarList 0
-- [x,y,z] t == instantiateVar 0 x (instantiateVar 1 (incVars 0 1 y)
-- (instantiateVar 2 (incVars 0 2 z) t))@.
{-
-- | Substitute @t@ for variable 0 in @s@ and decrement all remaining
-- variables.
betaReduce :: Term -> Term -> Term
betaReduce s t = instantiateVar 0 t s
-}
-- | Pretty print a term with the given outer precedence.
ppTerm :: TermPrinter Term
ppTerm lcls p0 (Term t) = ppTermF ppTerm lcls p0 t
ppTermF :: TermPrinter t
-> TermPrinter (TermF t)
ppTermF pp lcls p tf = runIdentity (ppTermF' pp' lcls p tf)
where pp' l' p' t' = pure (pp l' p' t')
ppTermF' :: Applicative f
=> (LocalVarDoc -> Prec -> e -> f Doc)
-> LocalVarDoc
-> Prec
-> TermF e
-> f Doc
ppTermF' pp lcls p (FTermF tf) = (group . nest 2) <$> (ppFlatTermF (pp lcls) p tf)
ppTermF' pp lcls p (App l r) = ppApp <$> pp lcls PrecApp l <*> pp lcls PrecArg r
where ppApp l' r' = ppAppParens p $ group $ hang 2 $ l' Leijen.<$> r'
ppTermF' pp lcls p (Lambda name tp rhs) =
ppLam
<$> pp lcls PrecLambda tp
<*> pp lcls' PrecLambda rhs
where ppLam tp' rhs' =
ppParens (p > PrecLambda) $ group $ hang 2 $
text "\\" <> parens (text name' <> doublecolon <> tp')
<+> text "->" Leijen.<$> rhs'
name' = freshVariant (docUsedMap lcls) name
lcls' = consBinding lcls name'
ppTermF' pp lcls p (Pi name tp rhs) = ppPi <$> lhs <*> pp lcls' PrecLambda rhs
where ppPi lhs' rhs' = ppParens (p > PrecLambda) $ lhs' <<$>> text "->" <+> rhs'
lhs | name == "_" = (align . group . nest 2) <$> pp lcls PrecApp tp
| otherwise = (\tp' -> parens (text name' <+> doublecolon <+> align (group (nest 2 tp'))))
<$> pp lcls PrecLambda tp
name' = freshVariant (docUsedMap lcls) name
lcls' = consBinding lcls name'
ppTermF' pp lcls p (Let dl u) =
ppLet <$> traverse (ppLocalDef pp lcls lcls') dl
<*> pp lcls' PrecNone u
where ppLet dl' u' =
ppParens (p > PrecNone) $
text "let" <+> lbrace <+> align (vcat dl') <$$>
indent 4 rbrace <$$>
text " in" <+> u'
nms = concatMap localVarNames dl
lcls' = foldl' consBinding lcls nms
ppTermF' _pp lcls _p (LocalVar i)
-- | lcls^.docShowLocalTypes = pptc <$> pp lcls PrecLambda tp
| otherwise = pure d
where d = lookupDoc lcls i
-- pptc tpd = ppParens (p > PrecNone)
-- (d <> doublecolon <> tpd)
ppTermF' _ _ _ (Constant i _ _) = pure $ text i
ppTermDepth :: forall t. Termlike t => Int -> t -> Doc
ppTermDepth d0 = pp d0 emptyLocalVarDoc PrecNone
where
pp :: Int -> TermPrinter t
pp 0 _ _ _ = text "_"
pp d lcls p t = case unwrapTermF t of
App t1 t2 ->
ppAppParens p $ group $ hang 2 $
(pp d lcls PrecApp t1) Leijen.<$>
(pp (d-1) lcls PrecArg t2)
tf ->
ppTermF (pp (d-1)) lcls p tf
instance Show Term where
showsPrec _ t = shows $ ppTerm emptyLocalVarDoc PrecNone t
type TypedDataType = DataType Ident Term
type TypedCtor = Ctor Ident Term
type TypedDef = Def Term
type TypedDefEqn = DefEqn Term
data ModuleDecl = TypeDecl TypedDataType
| DefDecl TypedDef
data Module = Module {
moduleName :: !ModuleName
, _moduleImports :: !(Map ModuleName Module)
, moduleTypeMap :: !(Map String TypedDataType)
, moduleCtorMap :: !(Map String TypedCtor)
, moduleDefMap :: !(Map String TypedDef)
, moduleRDecls :: [ModuleDecl] -- ^ All declarations in reverse order they were added.
}
moduleImports :: Simple Lens Module (Map ModuleName Module)
moduleImports = lens _moduleImports (\m v -> m { _moduleImports = v })
instance Show Module where
show m = flip displayS "" $ renderPretty 0.8 80 $
vcat $ concat $ fmap (map (<> line)) $
[ fmap ppImport (Map.keys (m^.moduleImports))
, fmap ppdecl (moduleRDecls m)
]
where ppImport nm = text $ "import " ++ show nm
ppdecl (TypeDecl d) = ppDataType ppTerm d
ppdecl (DefDecl d) = ppDef emptyLocalVarDoc d
emptyModule :: ModuleName -> Module
emptyModule nm =
Module { moduleName = nm
, _moduleImports = Map.empty
, moduleTypeMap = Map.empty
, moduleCtorMap = Map.empty
, moduleDefMap = Map.empty
, moduleRDecls = []
}
findDataType :: Module -> Ident -> Maybe TypedDataType
findDataType m i = do
m' <- findDeclaringModule m (identModule i)
Map.lookup (identName i) (moduleTypeMap m')
-- | @insImport i m@ returns module obtained by importing @i@ into @m@.
insImport :: Module -> Module -> Module
insImport i = moduleImports . at (moduleName i) ?~ i
insDataType :: Module -> TypedDataType -> Module
insDataType m dt
| identModule (dtName dt) == moduleName m =
m { moduleTypeMap = Map.insert (identName (dtName dt)) dt (moduleTypeMap m)
, moduleCtorMap = foldl' insCtor (moduleCtorMap m) (dtCtors dt)
, moduleRDecls = TypeDecl dt : moduleRDecls m
}
| otherwise = internalError "insDataType given datatype from another module."
where insCtor m' c = Map.insert (identName (ctorName c)) c m'
-- | Data types defined in module.
moduleDataTypes :: Module -> [TypedDataType]
moduleDataTypes = Map.elems . moduleTypeMap
-- | Ctors defined in module.
moduleCtors :: Module -> [TypedCtor]
moduleCtors = Map.elems . moduleCtorMap
findDeclaringModule :: Module -> ModuleName -> Maybe Module
findDeclaringModule m nm
| moduleName m == nm = Just m
| otherwise = m^.moduleImports^.at nm
findCtor :: Module -> Ident -> Maybe TypedCtor
findCtor m i = do
m' <- findDeclaringModule m (identModule i)
Map.lookup (identName i) (moduleCtorMap m')
moduleDefs :: Module -> [TypedDef]
moduleDefs = Map.elems . moduleDefMap
allModuleDefs :: Module -> [TypedDef]
allModuleDefs m = concatMap moduleDefs (m : Map.elems (m^.moduleImports))
findDef :: Module -> Ident -> Maybe TypedDef
findDef m i = do
m' <- findDeclaringModule m (identModule i)
Map.lookup (identName i) (moduleDefMap m')
insDef :: Module -> Def Term -> Module
insDef m d
| identModule (defIdent d) == moduleName m =
m { moduleDefMap = Map.insert (identName (defIdent d)) d (moduleDefMap m)
, moduleRDecls = DefDecl d : moduleRDecls m
}
| otherwise = internalError "insDef given def from another module."
moduleDecls :: Module -> [ModuleDecl]
moduleDecls = reverse . moduleRDecls
allModuleDecls :: Module -> [ModuleDecl]
allModuleDecls m = concatMap moduleDecls (m : Map.elems (m^.moduleImports))
modulePrimitives :: Module -> [TypedDef]
modulePrimitives m =
[ def
| DefDecl def <- moduleDecls m
, defQualifier def == PrimQualifier
]
moduleAxioms :: Module -> [TypedDef]
moduleAxioms m =
[ def
| DefDecl def <- moduleDecls m
, defQualifier def == AxiomQualifier
]
moduleActualDefs :: Module -> [TypedDef]
moduleActualDefs m =
[ def
| DefDecl def <- moduleDecls m
, defQualifier def == NoQualifier
]
allModulePrimitives :: Module -> [TypedDef]
allModulePrimitives m =
[ def
| DefDecl def <- allModuleDecls m
, defQualifier def == PrimQualifier
]
allModuleAxioms :: Module -> [TypedDef]
allModuleAxioms m =
[ def
| DefDecl def <- allModuleDecls m
, defQualifier def == AxiomQualifier
]
allModuleActualDefs :: Module -> [TypedDef]
allModuleActualDefs m =
[ def
| DefDecl def <- allModuleDecls m
, defQualifier def == NoQualifier
]
| iblumenfeld/saw-core | src/Verifier/SAW/TypedAST.hs | bsd-3-clause | 34,429 | 5 | 18 | 9,555 | 11,366 | 5,808 | 5,558 | -1 | -1 |
module Process.Console
( start
) where
import Prelude hiding (init)
import Control.Concurrent
import Control.Concurrent.STM
import Control.Monad.Reader
import Control.Monad.State
import Process
import Process.ConsoleChan
import qualified Process.Status
import Process.StatusChan
data PConf = PConf
{ cCmdChan :: CommandChannel
, cOutChan :: TChan String
}
data PState = PState
{ sReaderTid :: ThreadId
, sWriterTid :: ThreadId
}
instance Logging PConf where
logName _ = "Process.Console"
init :: IO (PConf, PState)
init = do
cmdChan <- newTChanIO
outChan <- newTChanIO
readerId <- readerProcess cmdChan
writerId <- writerProcess outChan
let conf = PConf cmdChan outChan
state = PState readerId writerId
return (conf, state)
start :: TMVar () -> StatusChannel -> IO ThreadId
start waitMutex statusChan = do
(conf, state) <- init
spawnProcess conf state (catchProcess loop stop)
where
loop = do
cmdChan <- asks cCmdChan
outChan <- asks cOutChan
command <- liftIO . atomically $ readTChan cmdChan
case command of
Quit -> liftIO . atomically $ putTMVar waitMutex ()
Help -> liftIO . atomically $ writeTChan outChan helpMessage
Show -> do
ret <- liftIO newEmptyTMVarIO
liftIO . atomically $ writeTChan statusChan (RequestAllTorrents ret)
status <- liftIO . atomically $ takeTMVar ret
liftIO . atomically $ writeTChan outChan (show status)
(Unknown cmd) -> liftIO . atomically $ writeTChan outChan $ "Неизвестная комманда: " ++ cmd
loop
stop :: Process PConf PState ()
stop = do
readerTid <- gets sReaderTid
writerTid <- gets sWriterTid
liftIO $ killThread readerTid
liftIO $ killThread writerTid
helpMessage :: String
helpMessage = concat
[ "Command Help:\n" , "\n"
, " help - Show this help\n"
, " quit - Quit the program\n"
, " show - Show the current downloading status\n"
]
writerProcess :: TChan String -> IO ThreadId
writerProcess outChan = do
forkIO $ proc outChan
where
proc outChan = forever $ do
message <- atomically . readTChan $ outChan
putStrLn message
readerProcess :: CommandChannel -> IO ThreadId
readerProcess cmdChan = do
forkIO $ proc cmdChan
where
proc cmdChan = forever $ do
line <- getLine
atomically . writeTChan cmdChan $
case line of
"help" -> Help
"quit" -> Quit
"show" -> Show
cmd -> Unknown cmd
| artems/htorr | src/Process/Console.hs | bsd-3-clause | 2,671 | 0 | 17 | 779 | 729 | 359 | 370 | 75 | 4 |
module Text.Document.PluginRegister (pluginRegister) where
import Text.Document.Plugin
import Text.Document.Core.Type
import Text.Document.Plugin.HsColour
import Text.Document.Plugin.Formula
import Text.Document.Plugin.TOC
pluginRegister :: [Plugin Document Syn_Document]
pluginRegister = [
formulaPlugin
, hscolourPlugin
, tocPlugin
]
| sebastiaanvisser/orchid-doc | src/Text/Document/PluginRegister.hs | bsd-3-clause | 350 | 0 | 6 | 42 | 73 | 48 | 25 | 11 | 1 |
{-# OPTIONS_HADDOCK not-home #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE RankNTypes #-}
-- | Internal constructors and helper functions. Note that no guarantees are
-- given for stability of these interfaces.
module Network.Wai.Internal where
import Blaze.ByteString.Builder (Builder)
import qualified Data.ByteString as B
import Data.Text (Text)
import Data.Typeable (Typeable)
import Data.Vault.Lazy (Vault)
import Data.Word (Word64)
import qualified Network.HTTP.Types as H
import Network.Socket (SockAddr)
-- | Information on the request sent by the client. This abstracts away the
-- details of the underlying implementation.
data Request = Request {
-- | Request method such as GET.
requestMethod :: H.Method
-- | HTTP version such as 1.1.
, httpVersion :: H.HttpVersion
-- | Extra path information sent by the client. The meaning varies slightly
-- depending on backend; in a standalone server setting, this is most likely
-- all information after the domain name. In a CGI application, this would be
-- the information following the path to the CGI executable itself.
-- Do not modify this raw value- modify pathInfo instead.
, rawPathInfo :: B.ByteString
-- | If no query string was specified, this should be empty. This value
-- /will/ include the leading question mark.
-- Do not modify this raw value- modify queryString instead.
, rawQueryString :: B.ByteString
-- | A list of header (a pair of key and value) in an HTTP request.
, requestHeaders :: H.RequestHeaders
-- | Was this request made over an SSL connection?
--
-- Note that this value will /not/ tell you if the client originally made
-- this request over SSL, but rather whether the current connection is SSL.
-- The distinction lies with reverse proxies. In many cases, the client will
-- connect to a load balancer over SSL, but connect to the WAI handler
-- without SSL. In such a case, @isSecure@ will be @False@, but from a user
-- perspective, there is a secure connection.
, isSecure :: Bool
-- | The client\'s host information.
, remoteHost :: SockAddr
-- | Path info in individual pieces- the url without a hostname/port and
-- without a query string, split on forward slashes.
, pathInfo :: [Text]
-- | Parsed query string information
, queryString :: H.Query
-- | Get the next chunk of the body. Returns an empty bytestring when the
-- body is fully consumed.
, requestBody :: IO B.ByteString
-- | A location for arbitrary data to be shared by applications and middleware.
, vault :: Vault
-- | The size of the request body. In the case of a chunked request body,
-- this may be unknown.
--
-- Since 1.4.0
, requestBodyLength :: RequestBodyLength
-- | The value of the Host header in a HTTP request.
--
-- Since 2.0.0
, requestHeaderHost :: Maybe B.ByteString
-- | The value of the Range header in a HTTP request.
--
-- Since 2.0.0
, requestHeaderRange :: Maybe B.ByteString
}
deriving (Typeable)
-- | The strange structure of the third field or ResponseSource is to allow for
-- exception-safe resource allocation. As an example:
--
-- > app :: Application
-- > app _ = return $ ResponseSource status200 [] $ \f -> bracket
-- > (putStrLn "Allocation" >> return 5)
-- > (\i -> putStrLn $ "Cleaning up: " ++ show i)
-- > (\_ -> f $ do
-- > yield $ Chunk $ fromByteString "Hello "
-- > yield $ Chunk $ fromByteString "World!")
data Response
= ResponseFile H.Status H.ResponseHeaders FilePath (Maybe FilePart)
| ResponseBuilder H.Status H.ResponseHeaders Builder
| ResponseStream H.Status H.ResponseHeaders StreamingBody
| ResponseRaw (IO B.ByteString -> (B.ByteString -> IO ()) -> IO ()) Response
deriving Typeable
-- | Represents a streaming HTTP response body. It's a function of two
-- parameters; the first parameter provides a means of sending another chunk of
-- data, and the second parameter provides a means of flushing the data to the
-- client.
--
-- Since 3.0.0
type StreamingBody = (Builder -> IO ()) -> IO () -> IO ()
-- | The size of the request body. In the case of chunked bodies, the size will
-- not be known.
--
-- Since 1.4.0
data RequestBodyLength = ChunkedBody | KnownLength Word64
-- | Information on which part to be sent.
-- Sophisticated application handles Range (and If-Range) then
-- create 'FilePart'.
data FilePart = FilePart
{ filePartOffset :: Integer
, filePartByteCount :: Integer
, filePartFileSize :: Integer
} deriving Show
-- | A special datatype to indicate that the WAI handler has received the
-- response. This is to avoid the need for Rank2Types in the definition of
-- Application.
--
-- It is /highly/ advised that only WAI handlers import and use the data
-- constructor for this data type.
--
-- Since 3.0.0
data ResponseReceived = ResponseReceived
deriving Typeable
| beni55/wai | wai/Network/Wai/Internal.hs | mit | 5,189 | 0 | 13 | 1,257 | 475 | 310 | 165 | 44 | 0 |
module Goats where
-- for cardinality, it means that
-- unary constructors are the identity function
data Animals = Animals Int deriving (Eq, Show)
-- tooManyGoats :: Int -> Bool
-- tooManyGoats n = n > 42
newtype Goats =
Goats Int deriving (Eq, Show)
newtype Cows =
Cows Int deriving (Eq, Show)
tooManyGoats :: Goats -> Bool
tooManyGoats (Goats n) = n > 42
tooManyCows :: Cows -> Bool
tooManyCows (Cows n) = n > 5
cows :: Cows -- Int
cows = Cows 4
goats :: Goats -- Int
-- can't supply Int because the type equation
-- was already satisfied in the newtype so the kind
-- went from * -> * to * there.
goats = Goats 37
class TooMany a where
tooMany :: a -> Bool
-- *this* is the instance of TooMany Int
instance TooMany Int where
tooMany n = n > 42
-- but there *is no* instance of TooMany Double
instance TooMany Goats where
tooMany (Goats n) = n > 43 | brodyberg/Notes | ProjectRosalind.hsproj/LearnHaskell/lib/HaskellBook/GoatsChapter11.hs | mit | 876 | 0 | 8 | 193 | 217 | 121 | 96 | 20 | 1 |
{- |
Module : $Header$
Description : alpha-conversion (renaming of bound variables) for CASL formulas
Copyright : (c) Christian Maeder, Uni Bremen 2005
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : provisional
Portability : portable
uniquely rename variables in quantified formulas to allow for
a formula equality modulo alpha conversion
-}
module CASL.AlphaConvert (alphaEquiv, convertFormula) where
import CASL.AS_Basic_CASL
import CASL.Fold
import CASL.Utils
import CASL.Quantification
import qualified Data.Map as Map
import Common.Id
convertRecord :: Int -> (f -> f) -> Record f (FORMULA f) (TERM f)
convertRecord n mf = (mapRecord mf)
{ foldQuantification = \ orig _ _ _ _ ->
let Quantification q vs qf ps = orig
nvs = flatVAR_DECLs vs
mkVar i = mkSimpleId $ 'v' : show i
rvs = map mkVar [n .. ]
nf = replaceVarsF (Map.fromList $ zipWith ( \ (v, s) i ->
(v, Qual_var i s ps)) nvs rvs) mf
$ convertFormula (n + length nvs) mf qf
in foldr ( \ (v, s) cf ->
Quantification q [Var_decl [v] s ps] cf ps)
nf $ zip rvs $ map snd nvs
}
{- | uniquely rename variables in quantified formulas and always
quantify only over a single variable -}
convertFormula :: Int -> (f -> f) -> FORMULA f -> FORMULA f
convertFormula n = foldFormula . convertRecord n
-- | formula equality modulo alpha conversion
alphaEquiv :: Eq f => (f -> f) -> FORMULA f -> FORMULA f -> Bool
alphaEquiv mf f1 f2 =
convertFormula 1 mf f1 == convertFormula 1 mf f2
| nevrenato/Hets_Fork | CASL/AlphaConvert.hs | gpl-2.0 | 1,641 | 0 | 20 | 425 | 435 | 227 | 208 | 25 | 1 |
-- This file is part of HamSql
--
-- Copyright 2014-2016 by it's authors.
-- Some rights reserved. See COPYING, AUTHORS.
module Database.HamSql.Internal.Option where
import Control.Monad.Trans.Reader
import Data.Monoid
import Options.Applicative
import Options.Applicative.Builder.Internal (HasMetavar, HasValue)
import Options.Applicative.Types
-- helper functions
boolFlag :: Mod FlagFields Bool -> Parser Bool
boolFlag = flag False True
val :: (HasMetavar f, HasValue f) => String -> Mod f String
val xs = value xs <> metavar ("\"" ++ xs ++ "\"")
-- Global
parserInfoHamsql :: ParserInfo Command
parserInfoHamsql =
info
(helper <*> parserCommand)
(fullDesc <>
progDesc "A YamSql interpreter and smart executor." <>
header "hamsql - YamSql interperter written in Haskell")
-- Command
data Command
= Install OptCommon OptCommonDb OptInstall
| Upgrade OptCommon OptCommonDb
| Yamsql OptCommonDb OptYamsql
| Doc OptCommon OptDoc
| NoCommand OptNoCommand
deriving (Show)
parserCommand :: Parser Command
parserCommand =
subparser
(command
"install"
(info
(parserCmdInstall <**> helper)
(progDesc "Installs the setup on a database from scratch.")) <>
command
"upgrade"
(info
(parserCmdUpgrade <**> helper)
(progDesc "Upgrades an existing setup on a database.")) <>
command
"yamsql"
(info (parserCmdYamsql <**> helper) (progDesc "Output yamsql")) <>
command
"doc"
(info
(parserCmdDoc <**> helper)
(progDesc "Produces a documentation of the setup."))) <|>
parserOptNoCommand
parserCmdInstall :: Parser Command
parserCmdInstall =
Install <$> parserOptCommon <*> parserOptCommonDb <*> parserOptInstall
parserCmdUpgrade :: Parser Command
parserCmdUpgrade = Upgrade <$> parserOptCommon <*> parserOptCommonDb
parserCmdYamsql :: Parser Command
parserCmdYamsql = Yamsql <$> parserOptCommonDb <*> parserOptYamsql
parserCmdDoc :: Parser Command
parserCmdDoc = Doc <$> parserOptCommon <*> parserOptDoc
-- Commons
data OptCommon =
OptCommon
{ optSetup :: FilePath
, optVerbose :: Bool
, optDebug :: Bool
}
deriving (Show)
parserOptCommon :: Parser OptCommon
parserOptCommon =
OptCommon <$>
strOption
(long "setup" <>
short 's' <>
help "Setup file (YAML). If '-' is supplied, the setup is read from STDIN." <>
val "setup.yml" <> action "file -X '!*.yml'" <> action "directory") <*>
boolFlag (long "verbose" <> short 'v' <> help "Verbose") <*>
boolFlag (long "debug" <> help "Debug")
-- Commons Execute
data OptCommonDb =
OptCommonDb
{ optEmulate :: Bool
, optPrint :: Bool
, optConnection :: String
, optPermitDataDeletion :: Bool
, optSqlLog :: Maybe FilePath
, optSqlLogHideRollbacks :: Bool
}
deriving (Show)
justStr :: ReadM (Maybe String)
justStr = Just <$> ReadM ask
parserOptCommonDb :: Parser OptCommonDb
parserOptCommonDb =
OptCommonDb <$>
boolFlag (long "emulate" <> short 'e' <> help "Perform changes but rollback") <*>
boolFlag
(long "print" <> short 'p' <> help "Print SQL code instead of executing") <*>
strOption
(long "connection" <>
short 'c' <> help "Database connection URI" <> val "postgresql://") <*>
boolFlag
(long "permit-data-deletion" <> help "Permit deletion of columns and tables") <*>
option
justStr
(long "sql-log" <>
help
("If specified, log SQL statements to given file. " <>
"Existing logfiles will be extended, not deleted.") <>
value Nothing <> metavar "<log file>") <*>
boolFlag
(long "sql-log-hide-rollbacks" <>
help
"Hide ROLLBACK and SAVEPOINT statements. Useful for creating migration code via --log-sql.")
-- Command Install
data OptInstall =
OptInstall
{ optDeleteExistingDatabase :: Bool
, optDeleteResidualRoles :: Bool
}
deriving (Show)
parserOptInstall :: Parser OptInstall
parserOptInstall =
OptInstall <$>
boolFlag
(long "delete-existing-database" <>
short 'd' <> help "Delete database if it allready exists") <*>
boolFlag (long "delete-residual-roles" <> help "Delete residual roles")
data OptYamsql =
OptYamsql
{ optYamsqlDir :: FilePath
}
deriving (Show)
parserOptYamsql :: Parser OptYamsql
parserOptYamsql = OptYamsql <$> strArgument (help "Out dir")
-- Command NoCommand
data OptNoCommand =
OptNoCommand
{ optVersion :: Bool
}
deriving (Show)
parserOptNoCommand :: Parser Command
parserOptNoCommand =
NoCommand . OptNoCommand <$>
flag' True (long "version" <> help "Prints program version")
-- Command Doc
data OptDoc =
OptDoc
{ optOutputDir :: FilePath
, optTemplate :: FilePath
}
deriving (Show)
parserOptDoc :: Parser OptDoc
parserOptDoc =
OptDoc <$>
strOption
(long "output-dir" <>
short 'o' <> help "Output directory" <> val "docs/" <> action "directory") <*>
strOption
(long "template" <>
short 't' <>
help "Template file (DEFAULT.rst is loading a building template.)" <>
val "DEFAULT.rst" <>
action "file -X '!*.html'" <>
action "file -X '!*.md'" <> action "file -X '!*.rst'" <> action "directory")
| qua-bla/hamsql | src/Database/HamSql/Internal/Option.hs | gpl-3.0 | 5,214 | 0 | 15 | 1,135 | 1,206 | 621 | 585 | 148 | 1 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
-- |
-- This deals with files that are ready to ingest.
--
module Ambiata.Cli.Processing (
availableFiles
, moveToArchive
, uploadAction
, processReady
, fileAddress
, uploadReady
) where
import Ambiata.Cli.Data
import Control.Lens (over, set)
import Control.Monad.IO.Class (liftIO)
import Control.Monad.Reader (local)
import qualified Data.Text as T
import Mismi
import Mismi.Amazonka (serviceRetry, retryAttempts, exponentBase, configure)
import Mismi.S3
import Mismi.S3.Amazonka (s3)
import P
import System.Directory
import System.FilePath hiding ((</>))
import System.IO
import X.Control.Monad.Trans.Either
-- |
-- Upload the files that are in the processing dir, and move to archive when done.
--
uploadReady :: IncomingDir -> Region -> UploadAccess -> EitherT AmbiataError IO [ArchivedFile]
uploadReady dir r (UploadAccess (TemporaryAccess (TemporaryCreds k s sess) a)) = do
env' <- setDebugging <$> getDebugging <*> newEnvFromCreds r k s (Just sess)
let
env = configure (over serviceRetry (set retryAttempts 10 . set exponentBase 0.6) s3) env'
bimapEitherT AmbiataAWSUploadError id $ runAWS env
. local (configureRetries 10)
$ processReady dir a
processReady :: IncomingDir -> Address -> AWS [ArchivedFile]
processReady dir a = do
files <- liftIO $ availableFiles dir
mapM (uploadAction dir a) files
uploadAction :: IncomingDir -> Address -> ProcessingFile -> AWS ArchivedFile
uploadAction dir a f@(ProcessingFile fname) = do
uploadWithModeOrFail Overwrite fpath (fileAddress f a)
liftIO $ moveToArchive dir f
where
fpath = toWorkingPath dir Processing <//> T.unpack fname
fileAddress :: ProcessingFile -> Address -> Address
fileAddress (ProcessingFile fname) (Address b k) =
Address b (k // Key fname)
-- |
-- Stuff ready to go
--
availableFiles :: IncomingDir -> IO [ProcessingFile]
availableFiles dir = do
fileList <- (getDirectoryContents $ d) >>= filterM (doesFileExist . (<//>) d)
pure $ (ProcessingFile . T.pack) <$> fileList
where
d = toWorkingPath dir Processing
moveToArchive :: IncomingDir -> ProcessingFile -> IO ArchivedFile
moveToArchive dir (ProcessingFile fname) = do
renameFile (toWorkingPath dir Processing <//> T.unpack fname)
(toWorkingPath dir Archive <//> T.unpack fname)
pure $ ArchivedFile fname
(<//>) :: FilePath -> FilePath -> FilePath
(<//>) = combine
| ambiata/tatooine-cli | src/Ambiata/Cli/Processing.hs | apache-2.0 | 2,674 | 0 | 15 | 611 | 729 | 387 | 342 | -1 | -1 |
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE DeriveGeneric #-}
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Client.InstallPlan
-- Copyright : (c) Duncan Coutts 2008
-- License : BSD-like
--
-- Maintainer : [email protected]
-- Stability : provisional
-- Portability : portable
--
-- Package installation plan
--
-----------------------------------------------------------------------------
module Distribution.Client.InstallPlan (
InstallPlan,
SolverInstallPlan,
GenericInstallPlan,
PlanPackage,
SolverPlanPackage,
GenericPlanPackage(..),
-- * Operations on 'InstallPlan's
new,
toList,
mapPreservingGraph,
configureInstallPlan,
ready,
processing,
completed,
failed,
remove,
preexisting,
preinstalled,
showPlanIndex,
showInstallPlan,
-- * Checking validity of plans
valid,
closed,
consistent,
acyclic,
-- ** Details on invalid plans
PlanProblem(..),
showPlanProblem,
problems,
-- ** Querying the install plan
dependencyClosure,
reverseDependencyClosure,
topologicalOrder,
reverseTopologicalOrder,
) where
import Distribution.InstalledPackageInfo
( InstalledPackageInfo )
import Distribution.Package
( PackageIdentifier(..), PackageName(..), Package(..)
, HasUnitId(..), UnitId(..) )
import Distribution.Client.Types
( BuildSuccess, BuildFailure
, ConfiguredPackage(..), ConfiguredId(..)
, UnresolvedPkgLoc
, GenericReadyPackage(..) )
import Distribution.Version
( Version )
import Distribution.Simple.PackageIndex
( PackageIndex )
import qualified Distribution.Simple.Configure as Configure
import qualified Distribution.Simple.Setup as Cabal
import qualified Distribution.PackageDescription as PD
import qualified Distribution.Simple.PackageIndex as PackageIndex
import qualified Distribution.Client.PlanIndex as PlanIndex
import Distribution.Text
( display )
import Distribution.Solver.Types.ComponentDeps (ComponentDeps)
import qualified Distribution.Solver.Types.ComponentDeps as CD
import Distribution.Solver.Types.PackageFixedDeps
import Distribution.Solver.Types.Settings
import Distribution.Solver.Types.SolverPackage
-- TODO: Need this when we compute final UnitIds
-- import qualified Distribution.Simple.Configure as Configure
import Data.List
( foldl', intercalate )
import Data.Maybe
( fromMaybe, catMaybes )
import qualified Data.Graph as Graph
import Data.Graph (Graph)
import qualified Data.Tree as Tree
import Distribution.Compat.Binary (Binary(..))
import GHC.Generics
import Control.Exception
( assert )
import qualified Data.Map as Map
import qualified Data.Traversable as T
-- When cabal tries to install a number of packages, including all their
-- dependencies it has a non-trivial problem to solve.
--
-- The Problem:
--
-- In general we start with a set of installed packages and a set of source
-- packages.
--
-- Installed packages have fixed dependencies. They have already been built and
-- we know exactly what packages they were built against, including their exact
-- versions.
--
-- Source package have somewhat flexible dependencies. They are specified as
-- version ranges, though really they're predicates. To make matters worse they
-- have conditional flexible dependencies. Configuration flags can affect which
-- packages are required and can place additional constraints on their
-- versions.
--
-- These two sets of package can and usually do overlap. There can be installed
-- packages that are also available as source packages which means they could
-- be re-installed if required, though there will also be packages which are
-- not available as source and cannot be re-installed. Very often there will be
-- extra versions available than are installed. Sometimes we may like to prefer
-- installed packages over source ones or perhaps always prefer the latest
-- available version whether installed or not.
--
-- The goal is to calculate an installation plan that is closed, acyclic and
-- consistent and where every configured package is valid.
--
-- An installation plan is a set of packages that are going to be used
-- together. It will consist of a mixture of installed packages and source
-- packages along with their exact version dependencies. An installation plan
-- is closed if for every package in the set, all of its dependencies are
-- also in the set. It is consistent if for every package in the set, all
-- dependencies which target that package have the same version.
-- Note that plans do not necessarily compose. You might have a valid plan for
-- package A and a valid plan for package B. That does not mean the composition
-- is simultaneously valid for A and B. In particular you're most likely to
-- have problems with inconsistent dependencies.
-- On the other hand it is true that every closed sub plan is valid.
-- | Packages in an install plan
--
-- NOTE: 'ConfiguredPackage', 'GenericReadyPackage' and 'GenericPlanPackage'
-- intentionally have no 'PackageInstalled' instance. `This is important:
-- PackageInstalled returns only library dependencies, but for package that
-- aren't yet installed we know many more kinds of dependencies (setup
-- dependencies, exe, test-suite, benchmark, ..). Any functions that operate on
-- dependencies in cabal-install should consider what to do with these
-- dependencies; if we give a 'PackageInstalled' instance it would be too easy
-- to get this wrong (and, for instance, call graph traversal functions from
-- Cabal rather than from cabal-install). Instead, see 'PackageFixedDeps'.
data GenericPlanPackage ipkg srcpkg iresult ifailure
= PreExisting ipkg
| Configured srcpkg
| Processing (GenericReadyPackage srcpkg)
| Installed (GenericReadyPackage srcpkg) (Maybe ipkg) iresult
| Failed srcpkg ifailure
deriving (Eq, Show, Generic)
instance (Binary ipkg, Binary srcpkg, Binary iresult, Binary ifailure)
=> Binary (GenericPlanPackage ipkg srcpkg iresult ifailure)
type PlanPackage = GenericPlanPackage
InstalledPackageInfo (ConfiguredPackage UnresolvedPkgLoc)
BuildSuccess BuildFailure
type SolverPlanPackage = GenericPlanPackage
InstalledPackageInfo (SolverPackage UnresolvedPkgLoc)
BuildSuccess BuildFailure
instance (Package ipkg, Package srcpkg) =>
Package (GenericPlanPackage ipkg srcpkg iresult ifailure) where
packageId (PreExisting ipkg) = packageId ipkg
packageId (Configured spkg) = packageId spkg
packageId (Processing rpkg) = packageId rpkg
packageId (Installed rpkg _ _) = packageId rpkg
packageId (Failed spkg _) = packageId spkg
instance (PackageFixedDeps srcpkg,
PackageFixedDeps ipkg) =>
PackageFixedDeps (GenericPlanPackage ipkg srcpkg iresult ifailure) where
depends (PreExisting pkg) = depends pkg
depends (Configured pkg) = depends pkg
depends (Processing pkg) = depends pkg
depends (Installed pkg _ _) = depends pkg
depends (Failed pkg _) = depends pkg
instance (HasUnitId ipkg, HasUnitId srcpkg) =>
HasUnitId
(GenericPlanPackage ipkg srcpkg iresult ifailure) where
installedUnitId (PreExisting ipkg ) = installedUnitId ipkg
installedUnitId (Configured spkg) = installedUnitId spkg
installedUnitId (Processing rpkg) = installedUnitId rpkg
-- NB: defer to the actual installed package info in this case
installedUnitId (Installed _ (Just ipkg) _) = installedUnitId ipkg
installedUnitId (Installed rpkg _ _) = installedUnitId rpkg
installedUnitId (Failed spkg _) = installedUnitId spkg
data GenericInstallPlan ipkg srcpkg iresult ifailure = GenericInstallPlan {
planIndex :: !(PlanIndex ipkg srcpkg iresult ifailure),
planIndepGoals :: !IndependentGoals,
-- | Cached (lazily) graph
--
-- The 'Graph' representation works in terms of integer node ids, so we
-- have to keep mapping to and from our meaningful nodes, which of course
-- are package ids.
--
planGraph :: Graph,
planGraphRev :: Graph, -- ^ Reverse deps, transposed
planPkgIdOf :: Graph.Vertex -> UnitId, -- ^ mapping back to package ids
planVertexOf :: UnitId -> Graph.Vertex -- ^ mapping into node ids
}
-- | Much like 'planPkgIdOf', but mapping back to full packages.
planPkgOf :: GenericInstallPlan ipkg srcpkg iresult ifailure
-> Graph.Vertex
-> GenericPlanPackage ipkg srcpkg iresult ifailure
planPkgOf plan v =
case PackageIndex.lookupUnitId (planIndex plan)
(planPkgIdOf plan v) of
Just pkg -> pkg
Nothing -> error "InstallPlan: internal error: planPkgOf lookup failed"
-- | 'GenericInstallPlan' that the solver produces. We'll "run this" in
-- order to compute the 'UnitId's for everything we want to build.
type SolverInstallPlan = GenericInstallPlan
InstalledPackageInfo (SolverPackage UnresolvedPkgLoc)
-- Technically, these are not used here, but
-- setting the type this way makes it easier
-- to run some operations.
BuildSuccess BuildFailure
-- | Conversion of 'SolverInstallPlan' to 'InstallPlan'.
-- Similar to 'elaboratedInstallPlan'
configureInstallPlan :: SolverInstallPlan -> InstallPlan
configureInstallPlan solverPlan =
flip mapPreservingGraph solverPlan $ \mapDep planpkg ->
case planpkg of
PreExisting pkg ->
PreExisting pkg
Configured pkg ->
Configured (configureSolverPackage mapDep pkg)
_ -> error "configureInstallPlan: unexpected package state"
where
configureSolverPackage :: (UnitId -> UnitId)
-> SolverPackage UnresolvedPkgLoc
-> ConfiguredPackage UnresolvedPkgLoc
configureSolverPackage mapDep spkg =
ConfiguredPackage {
confPkgId = SimpleUnitId
$ Configure.computeComponentId
Cabal.NoFlag
(packageId spkg)
(PD.CLibName (display (pkgName (packageId spkg))))
-- TODO: this is a hack that won't work for Backpack.
(map ((\(SimpleUnitId cid0) -> cid0) . confInstId)
(CD.libraryDeps deps))
(solverPkgFlags spkg),
confPkgSource = solverPkgSource spkg,
confPkgFlags = solverPkgFlags spkg,
confPkgStanzas = solverPkgStanzas spkg,
confPkgDeps = deps
}
where
deps = fmap (map (configureSolverId mapDep)) (solverPkgDeps spkg)
configureSolverId mapDep sid =
ConfiguredId {
confSrcId = packageId sid, -- accurate!
confInstId = mapDep (installedUnitId sid)
}
-- | 'GenericInstallPlan' specialised to most commonly used types.
type InstallPlan = GenericInstallPlan
InstalledPackageInfo (ConfiguredPackage UnresolvedPkgLoc)
BuildSuccess BuildFailure
type PlanIndex ipkg srcpkg iresult ifailure =
PackageIndex (GenericPlanPackage ipkg srcpkg iresult ifailure)
invariant :: (HasUnitId ipkg, PackageFixedDeps ipkg,
HasUnitId srcpkg, PackageFixedDeps srcpkg)
=> GenericInstallPlan ipkg srcpkg iresult ifailure -> Bool
invariant plan =
valid (planIndepGoals plan)
(planIndex plan)
-- | Smart constructor that deals with caching the 'Graph' representation.
--
mkInstallPlan :: (HasUnitId ipkg, PackageFixedDeps ipkg,
HasUnitId srcpkg, PackageFixedDeps srcpkg)
=> PlanIndex ipkg srcpkg iresult ifailure
-> IndependentGoals
-> GenericInstallPlan ipkg srcpkg iresult ifailure
mkInstallPlan index indepGoals =
GenericInstallPlan {
planIndex = index,
planIndepGoals = indepGoals,
-- lazily cache the graph stuff:
planGraph = graph,
planGraphRev = Graph.transposeG graph,
planPkgIdOf = vertexToPkgId,
planVertexOf = fromMaybe noSuchPkgId . pkgIdToVertex
}
where
(graph, vertexToPkgId, pkgIdToVertex) =
PlanIndex.dependencyGraph index
noSuchPkgId = internalError "package is not in the graph"
internalError :: String -> a
internalError msg = error $ "InstallPlan: internal error: " ++ msg
instance (HasUnitId ipkg, PackageFixedDeps ipkg,
HasUnitId srcpkg, PackageFixedDeps srcpkg,
Binary ipkg, Binary srcpkg, Binary iresult, Binary ifailure)
=> Binary (GenericInstallPlan ipkg srcpkg iresult ifailure) where
put GenericInstallPlan {
planIndex = index,
planIndepGoals = indepGoals
} = put (index, indepGoals)
get = do
(index, indepGoals) <- get
return $! mkInstallPlan index indepGoals
showPlanIndex :: (HasUnitId ipkg, HasUnitId srcpkg)
=> PlanIndex ipkg srcpkg iresult ifailure -> String
showPlanIndex index =
intercalate "\n" (map showPlanPackage (PackageIndex.allPackages index))
where showPlanPackage p =
showPlanPackageTag p ++ " "
++ display (packageId p) ++ " ("
++ display (installedUnitId p) ++ ")"
showInstallPlan :: (HasUnitId ipkg, HasUnitId srcpkg)
=> GenericInstallPlan ipkg srcpkg iresult ifailure -> String
showInstallPlan = showPlanIndex . planIndex
showPlanPackageTag :: GenericPlanPackage ipkg srcpkg iresult ifailure -> String
showPlanPackageTag (PreExisting _) = "PreExisting"
showPlanPackageTag (Configured _) = "Configured"
showPlanPackageTag (Processing _) = "Processing"
showPlanPackageTag (Installed _ _ _) = "Installed"
showPlanPackageTag (Failed _ _) = "Failed"
-- | Build an installation plan from a valid set of resolved packages.
--
new :: (HasUnitId ipkg, PackageFixedDeps ipkg,
HasUnitId srcpkg, PackageFixedDeps srcpkg)
=> IndependentGoals
-> PlanIndex ipkg srcpkg iresult ifailure
-> Either [PlanProblem ipkg srcpkg iresult ifailure]
(GenericInstallPlan ipkg srcpkg iresult ifailure)
new indepGoals index =
case problems indepGoals index of
[] -> Right (mkInstallPlan index indepGoals)
probs -> Left probs
toList :: GenericInstallPlan ipkg srcpkg iresult ifailure
-> [GenericPlanPackage ipkg srcpkg iresult ifailure]
toList = PackageIndex.allPackages . planIndex
-- | Remove packages from the install plan. This will result in an
-- error if there are remaining packages that depend on any matching
-- package. This is primarily useful for obtaining an install plan for
-- the dependencies of a package or set of packages without actually
-- installing the package itself, as when doing development.
--
remove :: (HasUnitId ipkg, PackageFixedDeps ipkg,
HasUnitId srcpkg, PackageFixedDeps srcpkg)
=> (GenericPlanPackage ipkg srcpkg iresult ifailure -> Bool)
-> GenericInstallPlan ipkg srcpkg iresult ifailure
-> Either [PlanProblem ipkg srcpkg iresult ifailure]
(GenericInstallPlan ipkg srcpkg iresult ifailure)
remove shouldRemove plan =
new (planIndepGoals plan) newIndex
where
newIndex = PackageIndex.fromList $
filter (not . shouldRemove) (toList plan)
-- | The packages that are ready to be installed. That is they are in the
-- configured state and have all their dependencies installed already.
-- The plan is complete if the result is @[]@.
--
ready :: forall ipkg srcpkg iresult ifailure. PackageFixedDeps srcpkg
=> GenericInstallPlan ipkg srcpkg iresult ifailure
-> [GenericReadyPackage srcpkg]
ready plan = assert check readyPackages
where
check = if null readyPackages && null processingPackages
then null configuredPackages
else True
configuredPackages = [ pkg | Configured pkg <- toList plan ]
processingPackages = [ pkg | Processing pkg <- toList plan]
readyPackages :: [GenericReadyPackage srcpkg]
readyPackages = catMaybes (map (lookupReadyPackage plan) configuredPackages)
lookupReadyPackage :: forall ipkg srcpkg iresult ifailure.
PackageFixedDeps srcpkg
=> GenericInstallPlan ipkg srcpkg iresult ifailure
-> srcpkg
-> Maybe (GenericReadyPackage srcpkg)
lookupReadyPackage plan pkg = do
_ <- hasAllInstalledDeps pkg
return (ReadyPackage pkg)
where
hasAllInstalledDeps :: srcpkg -> Maybe (ComponentDeps [ipkg])
hasAllInstalledDeps = T.mapM (mapM isInstalledDep) . depends
isInstalledDep :: UnitId -> Maybe ipkg
isInstalledDep pkgid =
case PackageIndex.lookupUnitId (planIndex plan) pkgid of
Just (PreExisting ipkg) -> Just ipkg
Just (Configured _) -> Nothing
Just (Processing _) -> Nothing
Just (Installed _ (Just ipkg) _) -> Just ipkg
Just (Installed _ Nothing _) -> internalError (depOnNonLib pkgid)
Just (Failed _ _) -> internalError depOnFailed
Nothing -> internalError incomplete
incomplete = "install plan is not closed"
depOnFailed = "configured package depends on failed package"
depOnNonLib dep = "the configured package "
++ display (packageId pkg)
++ " depends on a non-library package "
++ display dep
-- | Marks packages in the graph as currently processing (e.g. building).
--
-- * The package must exist in the graph and be in the configured state.
--
processing :: (HasUnitId ipkg, PackageFixedDeps ipkg,
HasUnitId srcpkg, PackageFixedDeps srcpkg)
=> [GenericReadyPackage srcpkg]
-> GenericInstallPlan ipkg srcpkg iresult ifailure
-> GenericInstallPlan ipkg srcpkg iresult ifailure
processing pkgs plan = assert (invariant plan') plan'
where
plan' = plan {
planIndex = PackageIndex.merge (planIndex plan) processingPkgs
}
processingPkgs = PackageIndex.fromList [Processing pkg | pkg <- pkgs]
-- | Marks a package in the graph as completed. Also saves the build result for
-- the completed package in the plan.
--
-- * The package must exist in the graph and be in the processing state.
-- * The package must have had no uninstalled dependent packages.
--
completed :: (HasUnitId ipkg, PackageFixedDeps ipkg,
HasUnitId srcpkg, PackageFixedDeps srcpkg)
=> UnitId
-> Maybe ipkg -> iresult
-> GenericInstallPlan ipkg srcpkg iresult ifailure
-> GenericInstallPlan ipkg srcpkg iresult ifailure
completed pkgid mipkg buildResult plan = assert (invariant plan') plan'
where
plan' = plan {
planIndex = PackageIndex.insert installed
. PackageIndex.deleteUnitId pkgid
$ planIndex plan
}
installed = Installed (lookupProcessingPackage plan pkgid) mipkg buildResult
-- | Marks a package in the graph as having failed. It also marks all the
-- packages that depended on it as having failed.
--
-- * The package must exist in the graph and be in the processing
-- state.
--
failed :: (HasUnitId ipkg, PackageFixedDeps ipkg,
HasUnitId srcpkg, PackageFixedDeps srcpkg)
=> UnitId -- ^ The id of the package that failed to install
-> ifailure -- ^ The build result to use for the failed package
-> ifailure -- ^ The build result to use for its dependencies
-> GenericInstallPlan ipkg srcpkg iresult ifailure
-> GenericInstallPlan ipkg srcpkg iresult ifailure
failed pkgid buildResult buildResult' plan = assert (invariant plan') plan'
where
-- NB: failures don't update IPIDs
plan' = plan {
planIndex = PackageIndex.merge (planIndex plan) failures
}
ReadyPackage srcpkg = lookupProcessingPackage plan pkgid
failures = PackageIndex.fromList
$ Failed srcpkg buildResult
: [ Failed pkg' buildResult'
| Just pkg' <- map checkConfiguredPackage
$ packagesThatDependOn plan pkgid ]
-- | Lookup the reachable packages in the reverse dependency graph.
--
packagesThatDependOn :: GenericInstallPlan ipkg srcpkg iresult ifailure
-> UnitId
-> [GenericPlanPackage ipkg srcpkg iresult ifailure]
packagesThatDependOn plan pkgid = map (planPkgOf plan)
. tail
. Graph.reachable (planGraphRev plan)
. planVertexOf plan
$ pkgid
-- | Lookup a package that we expect to be in the processing state.
--
lookupProcessingPackage :: GenericInstallPlan ipkg srcpkg iresult ifailure
-> UnitId
-> GenericReadyPackage srcpkg
lookupProcessingPackage plan pkgid =
case PackageIndex.lookupUnitId (planIndex plan) pkgid of
Just (Processing pkg) -> pkg
_ -> internalError $ "not in processing state or no such pkg " ++
display pkgid
-- | Check a package that we expect to be in the configured or failed state.
--
checkConfiguredPackage :: (Package srcpkg, Package ipkg)
=> GenericPlanPackage ipkg srcpkg iresult ifailure
-> Maybe srcpkg
checkConfiguredPackage (Configured pkg) = Just pkg
checkConfiguredPackage (Failed _ _) = Nothing
checkConfiguredPackage pkg =
internalError $ "not configured or no such pkg " ++ display (packageId pkg)
-- | Replace a ready package with a pre-existing one. The pre-existing one
-- must have exactly the same dependencies as the source one was configured
-- with.
--
preexisting :: (HasUnitId ipkg, PackageFixedDeps ipkg,
HasUnitId srcpkg, PackageFixedDeps srcpkg)
=> UnitId
-> ipkg
-> GenericInstallPlan ipkg srcpkg iresult ifailure
-> GenericInstallPlan ipkg srcpkg iresult ifailure
preexisting pkgid ipkg plan = assert (invariant plan') plan'
where
plan' = plan {
planIndex = PackageIndex.insert (PreExisting ipkg)
-- ...but be sure to use the *old* IPID for the lookup for
-- the preexisting record
. PackageIndex.deleteUnitId pkgid
$ planIndex plan
}
-- | Replace a ready package with an installed one. The installed one
-- must have exactly the same dependencies as the source one was configured
-- with.
--
preinstalled :: (HasUnitId ipkg, PackageFixedDeps ipkg,
HasUnitId srcpkg, PackageFixedDeps srcpkg)
=> UnitId
-> Maybe ipkg -> iresult
-> GenericInstallPlan ipkg srcpkg iresult ifailure
-> GenericInstallPlan ipkg srcpkg iresult ifailure
preinstalled pkgid mipkg buildResult plan = assert (invariant plan') plan'
where
plan' = plan { planIndex = PackageIndex.insert installed (planIndex plan) }
Just installed = do
Configured pkg <- PackageIndex.lookupUnitId (planIndex plan) pkgid
rpkg <- lookupReadyPackage plan pkg
return (Installed rpkg mipkg buildResult)
-- | Transform an install plan by mapping a function over all the packages in
-- the plan. It can consistently change the 'UnitId' of all the packages,
-- while preserving the same overall graph structure.
--
-- The mapping function has a few constraints on it for correct operation.
-- The mapping function /may/ change the 'UnitId' of the package, but it
-- /must/ also remap the 'UnitId's of its dependencies using ths supplied
-- remapping function. Apart from this consistent remapping it /may not/
-- change the structure of the dependencies.
--
mapPreservingGraph :: (HasUnitId ipkg,
HasUnitId srcpkg,
HasUnitId ipkg', PackageFixedDeps ipkg',
HasUnitId srcpkg', PackageFixedDeps srcpkg')
=> ( (UnitId -> UnitId)
-> GenericPlanPackage ipkg srcpkg iresult ifailure
-> GenericPlanPackage ipkg' srcpkg' iresult' ifailure')
-> GenericInstallPlan ipkg srcpkg iresult ifailure
-> GenericInstallPlan ipkg' srcpkg' iresult' ifailure'
mapPreservingGraph f plan =
mkInstallPlan (PackageIndex.fromList pkgs')
(planIndepGoals plan)
where
-- The package mapping function may change the UnitId. So we
-- walk over the packages in dependency order keeping track of these
-- package id changes and use it to supply the correct set of package
-- dependencies as an extra input to the package mapping function.
(_, pkgs') = foldl' f' (Map.empty, []) (reverseTopologicalOrder plan)
f' (ipkgidMap, pkgs) pkg = (ipkgidMap', pkg' : pkgs)
where
pkg' = f (mapDep ipkgidMap) pkg
ipkgidMap'
| ipkgid /= ipkgid' = Map.insert ipkgid ipkgid' ipkgidMap
| otherwise = ipkgidMap
where
ipkgid = installedUnitId pkg
ipkgid' = installedUnitId pkg'
mapDep ipkgidMap ipkgid = Map.findWithDefault ipkgid ipkgid ipkgidMap
-- ------------------------------------------------------------
-- * Checking validity of plans
-- ------------------------------------------------------------
-- | A valid installation plan is a set of packages that is 'acyclic',
-- 'closed' and 'consistent'. Also, every 'ConfiguredPackage' in the
-- plan has to have a valid configuration (see 'configuredPackageValid').
--
-- * if the result is @False@ use 'problems' to get a detailed list.
--
valid :: (HasUnitId ipkg, PackageFixedDeps ipkg,
HasUnitId srcpkg, PackageFixedDeps srcpkg)
=> IndependentGoals
-> PlanIndex ipkg srcpkg iresult ifailure
-> Bool
valid indepGoals index =
null $ problems indepGoals index
data PlanProblem ipkg srcpkg iresult ifailure =
PackageMissingDeps (GenericPlanPackage ipkg srcpkg iresult ifailure)
[PackageIdentifier]
| PackageCycle [GenericPlanPackage ipkg srcpkg iresult ifailure]
| PackageInconsistency PackageName [(PackageIdentifier, Version)]
| PackageStateInvalid (GenericPlanPackage ipkg srcpkg iresult ifailure)
(GenericPlanPackage ipkg srcpkg iresult ifailure)
showPlanProblem :: (Package ipkg, Package srcpkg)
=> PlanProblem ipkg srcpkg iresult ifailure -> String
showPlanProblem (PackageMissingDeps pkg missingDeps) =
"Package " ++ display (packageId pkg)
++ " depends on the following packages which are missing from the plan: "
++ intercalate ", " (map display missingDeps)
showPlanProblem (PackageCycle cycleGroup) =
"The following packages are involved in a dependency cycle "
++ intercalate ", " (map (display.packageId) cycleGroup)
showPlanProblem (PackageInconsistency name inconsistencies) =
"Package " ++ display name
++ " is required by several packages,"
++ " but they require inconsistent versions:\n"
++ unlines [ " package " ++ display pkg ++ " requires "
++ display (PackageIdentifier name ver)
| (pkg, ver) <- inconsistencies ]
showPlanProblem (PackageStateInvalid pkg pkg') =
"Package " ++ display (packageId pkg)
++ " is in the " ++ showPlanState pkg
++ " state but it depends on package " ++ display (packageId pkg')
++ " which is in the " ++ showPlanState pkg'
++ " state"
where
showPlanState (PreExisting _) = "pre-existing"
showPlanState (Configured _) = "configured"
showPlanState (Processing _) = "processing"
showPlanState (Installed _ _ _) = "installed"
showPlanState (Failed _ _) = "failed"
-- | For an invalid plan, produce a detailed list of problems as human readable
-- error messages. This is mainly intended for debugging purposes.
-- Use 'showPlanProblem' for a human readable explanation.
--
problems :: (HasUnitId ipkg, PackageFixedDeps ipkg,
HasUnitId srcpkg, PackageFixedDeps srcpkg)
=> IndependentGoals
-> PlanIndex ipkg srcpkg iresult ifailure
-> [PlanProblem ipkg srcpkg iresult ifailure]
problems indepGoals index =
[ PackageMissingDeps pkg
(catMaybes
(map
(fmap packageId . PackageIndex.lookupUnitId index)
missingDeps))
| (pkg, missingDeps) <- PlanIndex.brokenPackages index ]
++ [ PackageCycle cycleGroup
| cycleGroup <- PlanIndex.dependencyCycles index ]
++ [ PackageInconsistency name inconsistencies
| (name, inconsistencies) <-
PlanIndex.dependencyInconsistencies indepGoals index ]
++ [ PackageStateInvalid pkg pkg'
| pkg <- PackageIndex.allPackages index
, Just pkg' <- map (PackageIndex.lookupUnitId index)
(CD.flatDeps (depends pkg))
, not (stateDependencyRelation pkg pkg') ]
-- | The graph of packages (nodes) and dependencies (edges) must be acyclic.
--
-- * if the result is @False@ use 'PackageIndex.dependencyCycles' to find out
-- which packages are involved in dependency cycles.
--
acyclic :: (HasUnitId ipkg, PackageFixedDeps ipkg,
HasUnitId srcpkg, PackageFixedDeps srcpkg)
=> PlanIndex ipkg srcpkg iresult ifailure -> Bool
acyclic = null . PlanIndex.dependencyCycles
-- | An installation plan is closed if for every package in the set, all of
-- its dependencies are also in the set. That is, the set is closed under the
-- dependency relation.
--
-- * if the result is @False@ use 'PackageIndex.brokenPackages' to find out
-- which packages depend on packages not in the index.
--
closed :: (PackageFixedDeps ipkg,
PackageFixedDeps srcpkg)
=> PlanIndex ipkg srcpkg iresult ifailure -> Bool
closed = null . PlanIndex.brokenPackages
-- | An installation plan is consistent if all dependencies that target a
-- single package name, target the same version.
--
-- This is slightly subtle. It is not the same as requiring that there be at
-- most one version of any package in the set. It only requires that of
-- packages which have more than one other package depending on them. We could
-- actually make the condition even more precise and say that different
-- versions are OK so long as they are not both in the transitive closure of
-- any other package (or equivalently that their inverse closures do not
-- intersect). The point is we do not want to have any packages depending
-- directly or indirectly on two different versions of the same package. The
-- current definition is just a safe approximation of that.
--
-- * if the result is @False@ use 'PackageIndex.dependencyInconsistencies' to
-- find out which packages are.
--
consistent :: (HasUnitId ipkg, PackageFixedDeps ipkg,
HasUnitId srcpkg, PackageFixedDeps srcpkg)
=> PlanIndex ipkg srcpkg iresult ifailure -> Bool
consistent = null . PlanIndex.dependencyInconsistencies (IndependentGoals False)
-- | The states of packages have that depend on each other must respect
-- this relation. That is for very case where package @a@ depends on
-- package @b@ we require that @dependencyStatesOk a b = True@.
--
stateDependencyRelation :: GenericPlanPackage ipkg srcpkg iresult ifailure
-> GenericPlanPackage ipkg srcpkg iresult ifailure
-> Bool
stateDependencyRelation (PreExisting _) (PreExisting _) = True
stateDependencyRelation (Configured _) (PreExisting _) = True
stateDependencyRelation (Configured _) (Configured _) = True
stateDependencyRelation (Configured _) (Processing _) = True
stateDependencyRelation (Configured _) (Installed _ _ _) = True
stateDependencyRelation (Processing _) (PreExisting _) = True
stateDependencyRelation (Processing _) (Installed _ _ _) = True
stateDependencyRelation (Installed _ _ _) (PreExisting _) = True
stateDependencyRelation (Installed _ _ _) (Installed _ _ _) = True
stateDependencyRelation (Failed _ _) (PreExisting _) = True
-- failed can depends on configured because a package can depend on
-- several other packages and if one of the deps fail then we fail
-- but we still depend on the other ones that did not fail:
stateDependencyRelation (Failed _ _) (Configured _) = True
stateDependencyRelation (Failed _ _) (Processing _) = True
stateDependencyRelation (Failed _ _) (Installed _ _ _) = True
stateDependencyRelation (Failed _ _) (Failed _ _) = True
stateDependencyRelation _ _ = False
-- | Compute the dependency closure of a package in a install plan
--
dependencyClosure :: GenericInstallPlan ipkg srcpkg iresult ifailure
-> [UnitId]
-> [GenericPlanPackage ipkg srcpkg iresult ifailure]
dependencyClosure plan =
map (planPkgOf plan)
. concatMap Tree.flatten
. Graph.dfs (planGraph plan)
. map (planVertexOf plan)
reverseDependencyClosure :: GenericInstallPlan ipkg srcpkg iresult ifailure
-> [UnitId]
-> [GenericPlanPackage ipkg srcpkg iresult ifailure]
reverseDependencyClosure plan =
map (planPkgOf plan)
. concatMap Tree.flatten
. Graph.dfs (planGraphRev plan)
. map (planVertexOf plan)
topologicalOrder :: GenericInstallPlan ipkg srcpkg iresult ifailure
-> [GenericPlanPackage ipkg srcpkg iresult ifailure]
topologicalOrder plan =
map (planPkgOf plan)
. Graph.topSort
$ planGraph plan
reverseTopologicalOrder :: GenericInstallPlan ipkg srcpkg iresult ifailure
-> [GenericPlanPackage ipkg srcpkg iresult ifailure]
reverseTopologicalOrder plan =
map (planPkgOf plan)
. Graph.topSort
$ planGraphRev plan
| headprogrammingczar/cabal | cabal-install/Distribution/Client/InstallPlan.hs | bsd-3-clause | 34,195 | 0 | 18 | 8,441 | 6,111 | 3,238 | 2,873 | 506 | 7 |
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Client.Get
-- Copyright : (c) Andrea Vezzosi 2008
-- Duncan Coutts 2011
-- John Millikin 2012
-- License : BSD-like
--
-- Maintainer : [email protected]
-- Stability : provisional
-- Portability : portable
--
-- The 'cabal get' command.
-----------------------------------------------------------------------------
module Distribution.Client.Get (
get
) where
import Distribution.Package
( PackageId, packageId, packageName )
import Distribution.Simple.Setup
( Flag(..), fromFlag, fromFlagOrDefault )
import Distribution.Simple.Utils
( notice, die, info, writeFileAtomic )
import Distribution.Verbosity
( Verbosity )
import Distribution.Text(display)
import qualified Distribution.PackageDescription as PD
import Distribution.Client.Setup
( GlobalFlags(..), GetFlags(..) )
import Distribution.Client.Types
import Distribution.Client.Targets
import Distribution.Client.Dependency
import Distribution.Client.FetchUtils
import qualified Distribution.Client.Tar as Tar (extractTarGzFile)
import Distribution.Client.IndexUtils as IndexUtils
( getSourcePackages )
import Distribution.Client.Compat.Process
( readProcessWithExitCode )
import Distribution.Compat.Exception
( catchIO )
import Control.Exception
( finally )
import Control.Monad
( filterM, forM_, unless, when )
import Data.List
( sortBy )
import qualified Data.Map
import Data.Maybe
( listToMaybe, mapMaybe )
import Data.Monoid
( mempty )
import Data.Ord
( comparing )
import System.Directory
( createDirectoryIfMissing, doesDirectoryExist, doesFileExist
, getCurrentDirectory, setCurrentDirectory
)
import System.Exit
( ExitCode(..) )
import System.FilePath
( (</>), (<.>), addTrailingPathSeparator )
import System.Process
( rawSystem )
-- | Entry point for the 'cabal get' command.
get :: Verbosity
-> [Repo]
-> GlobalFlags
-> GetFlags
-> [UserTarget]
-> IO ()
get verbosity _ _ _ [] =
notice verbosity "No packages requested. Nothing to do."
get verbosity repos globalFlags getFlags userTargets = do
let useFork = case (getSourceRepository getFlags) of
NoFlag -> False
_ -> True
unless useFork $
mapM_ checkTarget userTargets
sourcePkgDb <- getSourcePackages verbosity repos
pkgSpecifiers <- resolveUserTargets verbosity
(fromFlag $ globalWorldFile globalFlags)
(packageIndex sourcePkgDb)
userTargets
pkgs <- either (die . unlines . map show) return $
resolveWithoutDependencies
(resolverParams sourcePkgDb pkgSpecifiers)
unless (null prefix) $
createDirectoryIfMissing True prefix
if useFork
then fork pkgs
else unpack pkgs
where
resolverParams sourcePkgDb pkgSpecifiers =
--TODO: add command-line constraint and preference args for unpack
standardInstallPolicy mempty sourcePkgDb pkgSpecifiers
prefix = fromFlagOrDefault "" (getDestDir getFlags)
fork :: [SourcePackage] -> IO ()
fork pkgs = do
let kind = fromFlag . getSourceRepository $ getFlags
branchers <- findUsableBranchers
mapM_ (forkPackage verbosity branchers prefix kind) pkgs
unpack :: [SourcePackage] -> IO ()
unpack pkgs = do
forM_ pkgs $ \pkg -> do
location <- fetchPackage verbosity (packageSource pkg)
let pkgid = packageId pkg
descOverride | usePristine = Nothing
| otherwise = packageDescrOverride pkg
case location of
LocalTarballPackage tarballPath ->
unpackPackage verbosity prefix pkgid descOverride tarballPath
RemoteTarballPackage _tarballURL tarballPath ->
unpackPackage verbosity prefix pkgid descOverride tarballPath
RepoTarballPackage _repo _pkgid tarballPath ->
unpackPackage verbosity prefix pkgid descOverride tarballPath
LocalUnpackedPackage _ ->
error "Distribution.Client.Get.unpack: the impossible happened."
where
usePristine = fromFlagOrDefault False (getPristine getFlags)
checkTarget :: UserTarget -> IO ()
checkTarget target = case target of
UserTargetLocalDir dir -> die (notTarball dir)
UserTargetLocalCabalFile file -> die (notTarball file)
_ -> return ()
where
notTarball t =
"The 'get' command is for tarball packages. "
++ "The target '" ++ t ++ "' is not a tarball."
-- ------------------------------------------------------------
-- * Unpacking the source tarball
-- ------------------------------------------------------------
unpackPackage :: Verbosity -> FilePath -> PackageId
-> PackageDescriptionOverride
-> FilePath -> IO ()
unpackPackage verbosity prefix pkgid descOverride pkgPath = do
let pkgdirname = display pkgid
pkgdir = prefix </> pkgdirname
pkgdir' = addTrailingPathSeparator pkgdir
existsDir <- doesDirectoryExist pkgdir
when existsDir $ die $
"The directory \"" ++ pkgdir' ++ "\" already exists, not unpacking."
existsFile <- doesFileExist pkgdir
when existsFile $ die $
"A file \"" ++ pkgdir ++ "\" is in the way, not unpacking."
notice verbosity $ "Unpacking to " ++ pkgdir'
Tar.extractTarGzFile prefix pkgdirname pkgPath
case descOverride of
Nothing -> return ()
Just pkgtxt -> do
let descFilePath = pkgdir </> display (packageName pkgid) <.> "cabal"
info verbosity $
"Updating " ++ descFilePath
++ " with the latest revision from the index."
writeFileAtomic descFilePath pkgtxt
-- ------------------------------------------------------------
-- * Forking the source repository
-- ------------------------------------------------------------
data BranchCmd = BranchCmd (Verbosity -> FilePath -> IO ExitCode)
data Brancher = Brancher
{ brancherBinary :: String
, brancherBuildCmd :: PD.SourceRepo -> Maybe BranchCmd
}
-- | The set of all supported branch drivers.
allBranchers :: [(PD.RepoType, Brancher)]
allBranchers =
[ (PD.Bazaar, branchBzr)
, (PD.Darcs, branchDarcs)
, (PD.Git, branchGit)
, (PD.Mercurial, branchHg)
, (PD.SVN, branchSvn)
]
-- | Find which usable branch drivers (selected from 'allBranchers') are
-- available and usable on the local machine.
--
-- Each driver's main command is run with @--help@, and if the child process
-- exits successfully, that brancher is considered usable.
findUsableBranchers :: IO (Data.Map.Map PD.RepoType Brancher)
findUsableBranchers = do
let usable (_, brancher) = flip catchIO (const (return False)) $ do
let cmd = brancherBinary brancher
(exitCode, _, _) <- readProcessWithExitCode cmd ["--help"] ""
return (exitCode == ExitSuccess)
pairs <- filterM usable allBranchers
return (Data.Map.fromList pairs)
-- | Fork a single package from a remote source repository to the local
-- file system.
forkPackage :: Verbosity
-> Data.Map.Map PD.RepoType Brancher
-- ^ Branchers supported by the local machine.
-> FilePath
-- ^ The directory in which new branches or repositories will
-- be created.
-> (Maybe PD.RepoKind)
-- ^ Which repo to choose.
-> SourcePackage
-- ^ The package to fork.
-> IO ()
forkPackage verbosity branchers prefix kind src = do
let desc = PD.packageDescription (packageDescription src)
pkgid = display (packageId src)
pkgname = display (packageName src)
destdir = prefix </> pkgname
destDirExists <- doesDirectoryExist destdir
when destDirExists $ do
die ("The directory " ++ show destdir ++ " already exists, not forking.")
destFileExists <- doesFileExist destdir
when destFileExists $ do
die ("A file " ++ show destdir ++ " is in the way, not forking.")
let repos = PD.sourceRepos desc
case findBranchCmd branchers repos kind of
Just (BranchCmd io) -> do
exitCode <- io verbosity destdir
case exitCode of
ExitSuccess -> return ()
ExitFailure _ -> die ("Couldn't fork package " ++ pkgid)
Nothing -> case repos of
[] -> die ("Package " ++ pkgid
++ " does not have any source repositories.")
_ -> die ("Package " ++ pkgid
++ " does not have any usable source repositories.")
-- | Given a set of possible branchers, and a set of possible source
-- repositories, find a repository that is both 1) likely to be specific to
-- this source version and 2) is supported by the local machine.
findBranchCmd :: Data.Map.Map PD.RepoType Brancher -> [PD.SourceRepo]
-> (Maybe PD.RepoKind) -> Maybe BranchCmd
findBranchCmd branchers allRepos maybeKind = cmd where
-- Sort repositories by kind, from This to Head to Unknown. Repositories
-- with equivalent kinds are selected based on the order they appear in
-- the Cabal description file.
repos' = sortBy (comparing thisFirst) allRepos
thisFirst r = case PD.repoKind r of
PD.RepoThis -> 0 :: Int
PD.RepoHead -> case PD.repoTag r of
-- If the type is 'head' but the author specified a tag, they
-- probably meant to create a 'this' repository but screwed up.
Just _ -> 0
Nothing -> 1
PD.RepoKindUnknown _ -> 2
-- If the user has specified the repo kind, filter out the repositories
-- she's not interested in.
repos = maybe repos' (\k -> filter ((==) k . PD.repoKind) repos') maybeKind
repoBranchCmd repo = do
t <- PD.repoType repo
brancher <- Data.Map.lookup t branchers
brancherBuildCmd brancher repo
cmd = listToMaybe (mapMaybe repoBranchCmd repos)
-- | Branch driver for Bazaar.
branchBzr :: Brancher
branchBzr = Brancher "bzr" $ \repo -> do
src <- PD.repoLocation repo
let args dst = case PD.repoTag repo of
Just tag -> ["branch", src, dst, "-r", "tag:" ++ tag]
Nothing -> ["branch", src, dst]
return $ BranchCmd $ \verbosity dst -> do
notice verbosity ("bzr: branch " ++ show src)
rawSystem "bzr" (args dst)
-- | Branch driver for Darcs.
branchDarcs :: Brancher
branchDarcs = Brancher "darcs" $ \repo -> do
src <- PD.repoLocation repo
let args dst = case PD.repoTag repo of
Just tag -> ["get", src, dst, "-t", tag]
Nothing -> ["get", src, dst]
return $ BranchCmd $ \verbosity dst -> do
notice verbosity ("darcs: get " ++ show src)
rawSystem "darcs" (args dst)
-- | Branch driver for Git.
branchGit :: Brancher
branchGit = Brancher "git" $ \repo -> do
src <- PD.repoLocation repo
let branchArgs = case PD.repoBranch repo of
Just b -> ["--branch", b]
Nothing -> []
let postClone dst = case PD.repoTag repo of
Just t -> do
cwd <- getCurrentDirectory
setCurrentDirectory dst
finally
(rawSystem "git" (["checkout", t] ++ branchArgs))
(setCurrentDirectory cwd)
Nothing -> return ExitSuccess
return $ BranchCmd $ \verbosity dst -> do
notice verbosity ("git: clone " ++ show src)
code <- rawSystem "git" (["clone", src, dst] ++ branchArgs)
case code of
ExitFailure _ -> return code
ExitSuccess -> postClone dst
-- | Branch driver for Mercurial.
branchHg :: Brancher
branchHg = Brancher "hg" $ \repo -> do
src <- PD.repoLocation repo
let branchArgs = case PD.repoBranch repo of
Just b -> ["--branch", b]
Nothing -> []
let tagArgs = case PD.repoTag repo of
Just t -> ["--rev", t]
Nothing -> []
let args dst = ["clone", src, dst] ++ branchArgs ++ tagArgs
return $ BranchCmd $ \verbosity dst -> do
notice verbosity ("hg: clone " ++ show src)
rawSystem "hg" (args dst)
-- | Branch driver for Subversion.
branchSvn :: Brancher
branchSvn = Brancher "svn" $ \repo -> do
src <- PD.repoLocation repo
let args dst = ["checkout", src, dst]
return $ BranchCmd $ \verbosity dst -> do
notice verbosity ("svn: checkout " ++ show src)
rawSystem "svn" (args dst)
| plumlife/cabal | cabal-install/Distribution/Client/Get.hs | bsd-3-clause | 12,693 | 0 | 22 | 3,408 | 2,975 | 1,520 | 1,455 | 252 | 6 |
module Kalium.Nucleus.Vector.BindClean where
import Kalium.Prelude
import Kalium.Util
import Kalium.Nucleus.Vector.Program
import Kalium.Nucleus.Vector.Recmap
import Kalium.Nucleus.Vector.Attempt
bindClean :: Endo' Program
bindClean = over recmapped bindCleanExpression
bindCleanExpression :: Endo' Expression
bindCleanExpression = \case
Follow p x a | Just e <- asum $ map (subst Follow tainting x a) (patClean p) -> e
Into p x a | Just e <- asum $ map (subst Into id x a) (patClean p) -> e
Follow (PTuple PWildCard p) (AppOp2 OpFmap (AppOp1 OpPair _) x) a -> Follow p x a
e -> e
subst h t x a (p, c) = t propagate c x <&> \x' -> h p x' a
type Con = forall a . Endo' (a,a)
patClean :: Pattern -> Pairs Pattern (EndoKleisli' Maybe Expression)
patClean p@PWildCard = return (p, \_ -> return LitUnit)
patClean (PTuple PWildCard p) = return (p, Just . AppOp1 OpSnd)
patClean (PTuple p PWildCard) = return (p, Just . AppOp1 OpFst)
patClean (PTuple p1 p2) = fstClean ++ sndClean ++ swapClean where
fstClean = do
(p, c) <- patClean p1
let cln (AppOp2 OpPair e1 e2) = AppOp2 OpPair <$> c e1 <*> pure e2
cln _ = Nothing
return (PTuple p p2, cln)
sndClean = do
(p, c) <- patClean p2
let cln (AppOp2 OpPair e1 e2) = AppOp2 OpPair <$> pure e1 <*> c e2
cln _ = Nothing
return (PTuple p1 p, cln)
swapClean = do
let cln (AppOp1 OpSwap e) = pure e
cln _ = Nothing
return (PTuple p2 p1, cln)
patClean _ = []
| rscprof/kalium | src/Kalium/Nucleus/Vector/BindClean.hs | bsd-3-clause | 1,540 | 0 | 15 | 402 | 666 | 333 | 333 | -1 | -1 |
module Lambda.Type
( module Lambda.Data
, module Lambda.Position
, toTree
)
where
import Lambda.Data
import Lambda.IO
import Lambda.Tree
import Lambda.Position
| Erdwolf/autotool-bonn | src/Lambda/Type.hs | gpl-2.0 | 168 | 0 | 5 | 28 | 43 | 27 | 16 | 8 | 0 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.RDS.DeleteDBInstance
-- Copyright : (c) 2013-2014 Brendan Hay <[email protected]>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | The DeleteDBInstance action deletes a previously provisioned DB instance. A
-- successful response from the web service indicates the request was received
-- correctly. When you delete a DB instance, all automated backups for that
-- instance are deleted and cannot be recovered. Manual DB snapshots of the DB
-- instance to be deleted are not deleted.
--
-- If a final DB snapshot is requested the status of the RDS instance will be
-- "deleting" until the DB snapshot is created. The API action 'DescribeDBInstance'
-- is used to monitor the status of this operation. The action cannot be
-- canceled or reverted once submitted.
--
-- <http://docs.aws.amazon.com/AmazonRDS/latest/APIReference/API_DeleteDBInstance.html>
module Network.AWS.RDS.DeleteDBInstance
(
-- * Request
DeleteDBInstance
-- ** Request constructor
, deleteDBInstance
-- ** Request lenses
, ddbiDBInstanceIdentifier
, ddbiFinalDBSnapshotIdentifier
, ddbiSkipFinalSnapshot
-- * Response
, DeleteDBInstanceResponse
-- ** Response constructor
, deleteDBInstanceResponse
-- ** Response lenses
, ddbirDBInstance
) where
import Network.AWS.Prelude
import Network.AWS.Request.Query
import Network.AWS.RDS.Types
import qualified GHC.Exts
data DeleteDBInstance = DeleteDBInstance
{ _ddbiDBInstanceIdentifier :: Text
, _ddbiFinalDBSnapshotIdentifier :: Maybe Text
, _ddbiSkipFinalSnapshot :: Maybe Bool
} deriving (Eq, Ord, Read, Show)
-- | 'DeleteDBInstance' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'ddbiDBInstanceIdentifier' @::@ 'Text'
--
-- * 'ddbiFinalDBSnapshotIdentifier' @::@ 'Maybe' 'Text'
--
-- * 'ddbiSkipFinalSnapshot' @::@ 'Maybe' 'Bool'
--
deleteDBInstance :: Text -- ^ 'ddbiDBInstanceIdentifier'
-> DeleteDBInstance
deleteDBInstance p1 = DeleteDBInstance
{ _ddbiDBInstanceIdentifier = p1
, _ddbiSkipFinalSnapshot = Nothing
, _ddbiFinalDBSnapshotIdentifier = Nothing
}
-- | The DB instance identifier for the DB instance to be deleted. This parameter
-- isn't case sensitive.
--
-- Constraints:
--
-- Must contain from 1 to 63 alphanumeric characters or hyphens First
-- character must be a letter Cannot end with a hyphen or contain two
-- consecutive hyphens
ddbiDBInstanceIdentifier :: Lens' DeleteDBInstance Text
ddbiDBInstanceIdentifier =
lens _ddbiDBInstanceIdentifier
(\s a -> s { _ddbiDBInstanceIdentifier = a })
-- | The DBSnapshotIdentifier of the new DBSnapshot created when
-- SkipFinalSnapshot is set to 'false'.
--
-- Specifying this parameter and also setting the SkipFinalShapshot parameter
-- to true results in an error. Constraints:
--
-- Must be 1 to 255 alphanumeric characters First character must be a letter Cannot end with a hyphen or contain two consecutive hyphens
-- Cannot be specified when deleting a Read Replica.
ddbiFinalDBSnapshotIdentifier :: Lens' DeleteDBInstance (Maybe Text)
ddbiFinalDBSnapshotIdentifier =
lens _ddbiFinalDBSnapshotIdentifier
(\s a -> s { _ddbiFinalDBSnapshotIdentifier = a })
-- | Determines whether a final DB snapshot is created before the DB instance is
-- deleted. If 'true' is specified, no DBSnapshot is created. If 'false' is
-- specified, a DB snapshot is created before the DB instance is deleted.
--
-- Specify 'true' when deleting a Read Replica.
--
-- The FinalDBSnapshotIdentifier parameter must be specified if
-- SkipFinalSnapshot is 'false'. Default: 'false'
ddbiSkipFinalSnapshot :: Lens' DeleteDBInstance (Maybe Bool)
ddbiSkipFinalSnapshot =
lens _ddbiSkipFinalSnapshot (\s a -> s { _ddbiSkipFinalSnapshot = a })
newtype DeleteDBInstanceResponse = DeleteDBInstanceResponse
{ _ddbirDBInstance :: Maybe DBInstance
} deriving (Eq, Read, Show)
-- | 'DeleteDBInstanceResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'ddbirDBInstance' @::@ 'Maybe' 'DBInstance'
--
deleteDBInstanceResponse :: DeleteDBInstanceResponse
deleteDBInstanceResponse = DeleteDBInstanceResponse
{ _ddbirDBInstance = Nothing
}
ddbirDBInstance :: Lens' DeleteDBInstanceResponse (Maybe DBInstance)
ddbirDBInstance = lens _ddbirDBInstance (\s a -> s { _ddbirDBInstance = a })
instance ToPath DeleteDBInstance where
toPath = const "/"
instance ToQuery DeleteDBInstance where
toQuery DeleteDBInstance{..} = mconcat
[ "DBInstanceIdentifier" =? _ddbiDBInstanceIdentifier
, "FinalDBSnapshotIdentifier" =? _ddbiFinalDBSnapshotIdentifier
, "SkipFinalSnapshot" =? _ddbiSkipFinalSnapshot
]
instance ToHeaders DeleteDBInstance
instance AWSRequest DeleteDBInstance where
type Sv DeleteDBInstance = RDS
type Rs DeleteDBInstance = DeleteDBInstanceResponse
request = post "DeleteDBInstance"
response = xmlResponse
instance FromXML DeleteDBInstanceResponse where
parseXML = withElement "DeleteDBInstanceResult" $ \x -> DeleteDBInstanceResponse
<$> x .@? "DBInstance"
| romanb/amazonka | amazonka-rds/gen/Network/AWS/RDS/DeleteDBInstance.hs | mpl-2.0 | 6,075 | 0 | 9 | 1,191 | 589 | 367 | 222 | 70 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.ElastiCache.DescribeReplicationGroups
-- Copyright : (c) 2013-2014 Brendan Hay <[email protected]>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | The /DescribeReplicationGroups/ action returns information about a particular
-- replication group. If no identifier is specified, /DescribeReplicationGroups/
-- returns information about all replication groups.
--
-- <http://docs.aws.amazon.com/AmazonElastiCache/latest/APIReference/API_DescribeReplicationGroups.html>
module Network.AWS.ElastiCache.DescribeReplicationGroups
(
-- * Request
DescribeReplicationGroups
-- ** Request constructor
, describeReplicationGroups
-- ** Request lenses
, drg1Marker
, drg1MaxRecords
, drg1ReplicationGroupId
-- * Response
, DescribeReplicationGroupsResponse
-- ** Response constructor
, describeReplicationGroupsResponse
-- ** Response lenses
, drgrMarker
, drgrReplicationGroups
) where
import Network.AWS.Prelude
import Network.AWS.Request.Query
import Network.AWS.ElastiCache.Types
import qualified GHC.Exts
data DescribeReplicationGroups = DescribeReplicationGroups
{ _drg1Marker :: Maybe Text
, _drg1MaxRecords :: Maybe Int
, _drg1ReplicationGroupId :: Maybe Text
} deriving (Eq, Ord, Read, Show)
-- | 'DescribeReplicationGroups' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'drg1Marker' @::@ 'Maybe' 'Text'
--
-- * 'drg1MaxRecords' @::@ 'Maybe' 'Int'
--
-- * 'drg1ReplicationGroupId' @::@ 'Maybe' 'Text'
--
describeReplicationGroups :: DescribeReplicationGroups
describeReplicationGroups = DescribeReplicationGroups
{ _drg1ReplicationGroupId = Nothing
, _drg1MaxRecords = Nothing
, _drg1Marker = Nothing
}
-- | An optional marker returned from a prior request. Use this marker for
-- pagination of results from this action. If this parameter is specified, the
-- response includes only records beyond the marker, up to the value specified
-- by /MaxRecords/.
drg1Marker :: Lens' DescribeReplicationGroups (Maybe Text)
drg1Marker = lens _drg1Marker (\s a -> s { _drg1Marker = a })
-- | The maximum number of records to include in the response. If more records
-- exist than the specified 'MaxRecords' value, a marker is included in the
-- response so that the remaining results can be retrieved.
--
-- Default: 100
--
-- Constraints: minimum 20; maximum 100.
drg1MaxRecords :: Lens' DescribeReplicationGroups (Maybe Int)
drg1MaxRecords = lens _drg1MaxRecords (\s a -> s { _drg1MaxRecords = a })
-- | The identifier for the replication group to be described. This parameter is
-- not case sensitive.
--
-- If you do not specify this parameter, information about all replication
-- groups is returned.
drg1ReplicationGroupId :: Lens' DescribeReplicationGroups (Maybe Text)
drg1ReplicationGroupId =
lens _drg1ReplicationGroupId (\s a -> s { _drg1ReplicationGroupId = a })
data DescribeReplicationGroupsResponse = DescribeReplicationGroupsResponse
{ _drgrMarker :: Maybe Text
, _drgrReplicationGroups :: List "member" ReplicationGroup
} deriving (Eq, Read, Show)
-- | 'DescribeReplicationGroupsResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'drgrMarker' @::@ 'Maybe' 'Text'
--
-- * 'drgrReplicationGroups' @::@ ['ReplicationGroup']
--
describeReplicationGroupsResponse :: DescribeReplicationGroupsResponse
describeReplicationGroupsResponse = DescribeReplicationGroupsResponse
{ _drgrMarker = Nothing
, _drgrReplicationGroups = mempty
}
-- | Provides an identifier to allow retrieval of paginated results.
drgrMarker :: Lens' DescribeReplicationGroupsResponse (Maybe Text)
drgrMarker = lens _drgrMarker (\s a -> s { _drgrMarker = a })
-- | A list of replication groups. Each item in the list contains detailed
-- information about one replication group.
drgrReplicationGroups :: Lens' DescribeReplicationGroupsResponse [ReplicationGroup]
drgrReplicationGroups =
lens _drgrReplicationGroups (\s a -> s { _drgrReplicationGroups = a })
. _List
instance ToPath DescribeReplicationGroups where
toPath = const "/"
instance ToQuery DescribeReplicationGroups where
toQuery DescribeReplicationGroups{..} = mconcat
[ "Marker" =? _drg1Marker
, "MaxRecords" =? _drg1MaxRecords
, "ReplicationGroupId" =? _drg1ReplicationGroupId
]
instance ToHeaders DescribeReplicationGroups
instance AWSRequest DescribeReplicationGroups where
type Sv DescribeReplicationGroups = ElastiCache
type Rs DescribeReplicationGroups = DescribeReplicationGroupsResponse
request = post "DescribeReplicationGroups"
response = xmlResponse
instance FromXML DescribeReplicationGroupsResponse where
parseXML = withElement "DescribeReplicationGroupsResult" $ \x -> DescribeReplicationGroupsResponse
<$> x .@? "Marker"
<*> x .@? "ReplicationGroups" .!@ mempty
instance AWSPager DescribeReplicationGroups where
page rq rs
| stop (rs ^. drgrMarker) = Nothing
| otherwise = (\x -> rq & drg1Marker ?~ x)
<$> (rs ^. drgrMarker)
| romanb/amazonka | amazonka-elasticache/gen/Network/AWS/ElastiCache/DescribeReplicationGroups.hs | mpl-2.0 | 6,107 | 0 | 12 | 1,217 | 729 | 435 | 294 | 78 | 1 |
-- | A gallery of instruments (found in Csound catalog).
module Color where
import Csound.Base
bass (amp, cps) = sig amp * once env * osc (sig cps)
where env = eexps [1, 0.00001]
pluckSynth (amp, cps1, cps2) = 0.5 * sig amp * once env * pluck 1 (sig cps1) cps2 def 3
where env = eexps [1, 0.004]
marimbaSynth :: (D, D) -> Sig
marimbaSynth (amp, cps) = a6
where
bias = 0.11
i2 = log cps / 10 - bias
k1 = (0.1 * ) $ once $ lins [0.00001, 30, 1, 50, 0.5, 100, 0.00001]
-- k1 = expseg [0.0001, 0.03, amp * 0.7, idur - 0.03, 0.001]
-- * linseg [1, 0.03, 1, idur - 0.03, 3]
k10 = linseg [2.25, 0.03, 3, idur - 0.03, 2]
a1 = gbuzz k1 (sig cps) k10 0 35 (sines3 [(1, 1, 90)])
a2 = reson' a1 500 50
a3 = reson' a2 150 100
a4 = reson' a3 3500 150
a5 = reson' a4 3500 150
a6 = balance a5 a1
reson' a b c = reson a b c `withD` 1
phasing (amp, cps) = aout
where
rise = 1
dec = 0.5
env = linen (sig amp) rise idur dec
osc' tab k ph = oscBy tab (sig $ cps * k) `withD` ph
osc1 = osc' sine
osc2 = osc' $ sines [1, 0, 0.9, 0, 0.8, 0, 0.7, 0, 0.6, 0, 0.5, 0, 0.4, 0, 0.3, 0, 0.2, 0, 0.1]
asum = env * mean
[ osc1 1 0
, osc2 1.008 0.02
, osc1 0.992 0.04
, osc2 2 0.06
, osc2 1 0.08
, osc1 1 0.01 ]
kosc1 = 0.5 * once sine
kosc2 = 0.5 * once sine `withD` 0.4
kosc3 = 1.0 * once sine `withD` 0.8
afilt = sum
[ butbp asum kosc1 1000
, butbp asum kosc2 300
, butbp asum kosc3 20 ]
aout = mean [afilt, asum]
blurp amp = do
cps <- acps
return $ 0.1 * sig amp * osc cps
where
dec = linseg [11, idur * 0.75, 11, idur * 0.25, 0]
kgate = kr $ oscil 1 dec (elins [1, 0, 0])
anoise = noise 11000 0.99
acps = fmap (flip samphold kgate) anoise
wind (amp, bandRise, bandDec, freqRise, freqDec, pan, winds) =
fmap fromRnd $ rand (sig $ amp / 400)
where
valu1 = 100
valu2 = 50
winde = 1 - winds
ramp a b = linseg [a, idur, b]
fromRnd a = (sig pan * aout, (1 - sig pan) * aout )
where
a2 = butbp a (ramp freqRise freqDec) (ramp bandRise bandDec)
a3 = butbp a2 (ramp (freqRise - valu1) (freqDec + valu2))
(ramp (bandRise + valu1) (bandDec - valu2))
aout = (a2 + a3) * linseg [0, idur * winds, 1, idur * winde, 0]
noiz (amp, cps) = fmap a2 k2
where
k1 = linseg [1, 0.05, 100, 0.2, 100, 2, 1, idur, 1]
k2 = fmap ( `withD` 1) $ rand 500
buzz' kamp kcps = buzz kamp (sig $ kcps * cps) k1 sine
a1 = mean $ zipWith buzz' [0.3, 1, 1] [1, 0.5, 0.501]
a2 k = 0.5 * a1 * sig amp * osc k
noiseGliss (amp, cps) = fmap ares anoise
where
ramp = linseg [0, idur * 0.8, amp, idur * 0.2, 0]
env1 = linen (sig amp) 0 idur 10
anoise = randi ramp env1
ares a = reson (a * osc (sig cps)) 100 100 `withD` 2
ivory (amp, cps, vibRate, glisDur, cpsCoeff) = sig amp * mean
-- vibrato env amplitude env freq bias phase vibrato coeff wave
[ alg (linseg [0, idur, 5]) (lincone 0 0.7 1 0.3 0) 0 0 1 sine
, alg (lincone 0 0.6 6 0.4 0) (lincone 0 0.9 1 0.1 0) 0.009 0.2 0.9 (sines [10, 9 .. 1])
, alg (lincone 9 0.7 1 0.3 1) (linenIdur 0.5 0.333) 0.007 0.3 1.2 (sines [10, 0, 9, 0, 8, 0, 7, 0, 6, 0, 5])
, alg (expcone 1 0.4 3 0.6 0.02)
(expcone 0.0001 0.8 1 0.2 0.0001) 0.005 0.5 0.97 (sines [10, 10, 9, 0, 0, 0, 3, 2, 0, 0, 1])
, alg (expcone 1 0.4 3 0.6 0.02)
(expdur [0.001, 0.5, 1, 0.1, 0.6, 0.2, 0.97, 0.2, 0.001])
0.003 0.8 0.99 (sines [10, 0, 0, 0, 5, 0, 0, 0, 0, 0, 3])
, alg (expcone 4 0.91 1 0.09 1)
(expdur [0.001, 0.6, 1, 0.2, 0.8, 0.1, 0.98, 0.1, 0.001])
0.001 1.3 1.4 (sines [10, 0, 0, 0, 0, 3, 1])
]
where
alg :: Sig -> Sig -> D -> D -> D -> Tab -> Sig
alg vibrEnv ampEnv cpsBias phsBias vibrCoeff wave =
ampEnv * (oscBy wave ((sig (cps + cpsBias) + vibr) * glis) `withD` phsBias)
where glis = expseg [1, glisDur, 1, idur - glisDur, cpsCoeff]
vibr = vibrEnv * osc (sig $ vibRate * vibrCoeff)
cone a x1 b x2 c = [a, x1 * idur, b, x2 * idur, c]
lincone a x1 b x2 c = linseg $ cone a x1 b x2 c
expcone a x1 b x2 c = expseg $ cone a x1 b x2 c
linenIdur a b = linen 1 (a * idur) idur (b * idur)
-- snow flakes
blue (amp, cps, lfoCps, harmNum, sweepRate) = fmap aout k1
where
k1 = randi 1 50
k2 = lindur [0, 0.5, 1, 0.5, 0]
k3 = lindur [0.005, 0.71, 0.015, 0.29, 0.01]
k4 = k2 * (kr $ osc (sig lfoCps) `withD` 0.2)
k5 = k4 + 2
ksweep = lindur [harmNum, sweepRate, 1, 1 - sweepRate, 1]
kenv = expdur [0.001, 0.01, amp, 0.99, 0.001]
aout k = gbuzz kenv (sig cps + k3) k5 ksweep k (sines3 [(1, 1, 90)])
i2 t0 dt amp cps lfoCps harmNum sweepRate =
t0 +| (dt *| temp (amp, cps, lfoCps, harmNum, sweepRate))
blueSco = sco blue $ har
[ i2 0 4 0.5 440 23 10 0.72
, i2 0 4 0.5 330 20 6 0.66
]
-- 4pok
black (amp, cps, filterSweepStart, filterSweepEnd, bandWidth) =
fmap aout $ rand 1
where
k1 = expdur [filterSweepStart, 1, filterSweepEnd]
a1 noise = reson noise k1 (k1 / sig bandWidth) `withD` 1
k3 = expdur [0.001, 0.001, amp, 0.999, 0.001]
a2 = k3 * osc (sig cps + 0.6 * (osc 11.3 `withD` 0.1))
aout noise = 0.5 * (a1 noise + a2)
i4 t0 dt amp cps filt0 filt1 bw =
t0 +| (dt *| temp (amp, cps, filt0, filt1, bw))
blackSco = str 1.5 $ sco black $ har
[ i4 0 1 0.7 220 6000 30 10
, i4 0 1 0.7 330 8000 20 6
]
| isomorphism/csound-expression | examples/Color.hs | bsd-3-clause | 6,349 | 0 | 17 | 2,529 | 2,732 | 1,492 | 1,240 | 117 | 1 |
{-# LANGUAGE CPP #-}
{-# OPTIONS_GHC -fno-warn-orphans
-fno-warn-incomplete-patterns
-fno-warn-deprecations
-fno-warn-unused-binds #-} --FIXME
module UnitTests.Distribution.Version (versionTests) where
import Distribution.Version
import Distribution.Text
import Text.PrettyPrint as Disp (text, render, parens, hcat
,punctuate, int, char, (<>), (<+>))
import Test.Tasty
import Test.Tasty.QuickCheck
import qualified Test.Laws as Laws
#if !MIN_VERSION_QuickCheck(2,9,0)
import Test.QuickCheck.Utils
#endif
import Control.Monad (liftM, liftM2)
import Data.Maybe (isJust, fromJust)
import Data.List (sort, sortBy, nub)
import Data.Ord (comparing)
versionTests :: [TestTree]
versionTests =
zipWith (\n p -> testProperty ("Range Property " ++ show n) p) [1::Int ..]
-- properties to validate the test framework
[ property prop_nonNull
, property prop_gen_intervals1
, property prop_gen_intervals2
--, property prop_equivalentVersionRange --FIXME: runs out of test cases
, property prop_intermediateVersion
-- the basic syntactic version range functions
, property prop_anyVersion
, property prop_noVersion
, property prop_thisVersion
, property prop_notThisVersion
, property prop_laterVersion
, property prop_orLaterVersion
, property prop_earlierVersion
, property prop_orEarlierVersion
, property prop_unionVersionRanges
, property prop_intersectVersionRanges
, property prop_differenceVersionRanges
, property prop_invertVersionRange
, property prop_withinVersion
, property prop_foldVersionRange
, property prop_foldVersionRange'
-- the semantic query functions
--, property prop_isAnyVersion1 --FIXME: runs out of test cases
--, property prop_isAnyVersion2 --FIXME: runs out of test cases
--, property prop_isNoVersion --FIXME: runs out of test cases
--, property prop_isSpecificVersion1 --FIXME: runs out of test cases
--, property prop_isSpecificVersion2 --FIXME: runs out of test cases
, property prop_simplifyVersionRange1
, property prop_simplifyVersionRange1'
--, property prop_simplifyVersionRange2 --FIXME: runs out of test cases
--, property prop_simplifyVersionRange2' --FIXME: runs out of test cases
--, property prop_simplifyVersionRange2'' --FIXME: actually wrong
-- converting between version ranges and version intervals
, property prop_to_intervals
--, property prop_to_intervals_canonical --FIXME: runs out of test cases
--, property prop_to_intervals_canonical' --FIXME: runs out of test cases
, property prop_from_intervals
, property prop_to_from_intervals
, property prop_from_to_intervals
, property prop_from_to_intervals'
-- union and intersection of version intervals
, property prop_unionVersionIntervals
, property prop_unionVersionIntervals_idempotent
, property prop_unionVersionIntervals_commutative
, property prop_unionVersionIntervals_associative
, property prop_intersectVersionIntervals
, property prop_intersectVersionIntervals_idempotent
, property prop_intersectVersionIntervals_commutative
, property prop_intersectVersionIntervals_associative
, property prop_union_intersect_distributive
, property prop_intersect_union_distributive
-- inversion of version intervals
, property prop_invertVersionIntervals
, property prop_invertVersionIntervalsTwice
]
-- parseTests :: [TestTree]
-- parseTests =
-- zipWith (\n p -> testProperty ("Parse Property " ++ show n) p) [1::Int ..]
-- -- parsing and pretty printing
-- [ -- property prop_parse_disp1 --FIXME: actually wrong
-- -- These are also wrong, see
-- -- https://github.com/haskell/cabal/issues/3037#issuecomment-177671011
-- -- property prop_parse_disp2
-- -- , property prop_parse_disp3
-- -- , property prop_parse_disp4
-- -- , property prop_parse_disp5
-- ]
#if !MIN_VERSION_QuickCheck(2,9,0)
instance Arbitrary Version where
arbitrary = do
branch <- smallListOf1 $
frequency [(3, return 0)
,(3, return 1)
,(2, return 2)
,(1, return 3)]
return (Version branch []) -- deliberate []
where
smallListOf1 = adjustSize (\n -> min 5 (n `div` 3)) . listOf1
shrink (Version branch []) =
[ Version branch' [] | branch' <- shrink branch, not (null branch') ]
shrink (Version branch _tags) =
[ Version branch [] ]
#endif
instance Arbitrary VersionRange where
arbitrary = sized verRangeExp
where
verRangeExp n = frequency $
[ (2, return anyVersion)
, (1, liftM thisVersion arbitrary)
, (1, liftM laterVersion arbitrary)
, (1, liftM orLaterVersion arbitrary)
, (1, liftM orLaterVersion' arbitrary)
, (1, liftM earlierVersion arbitrary)
, (1, liftM orEarlierVersion arbitrary)
, (1, liftM orEarlierVersion' arbitrary)
, (1, liftM withinVersion arbitrary)
, (2, liftM VersionRangeParens arbitrary)
] ++ if n == 0 then [] else
[ (2, liftM2 unionVersionRanges verRangeExp2 verRangeExp2)
, (2, liftM2 intersectVersionRanges verRangeExp2 verRangeExp2)
]
where
verRangeExp2 = verRangeExp (n `div` 2)
orLaterVersion' v =
unionVersionRanges (LaterVersion v) (ThisVersion v)
orEarlierVersion' v =
unionVersionRanges (EarlierVersion v) (ThisVersion v)
---------------------------
-- VersionRange properties
--
prop_nonNull :: Version -> Bool
prop_nonNull = not . null . versionBranch
prop_anyVersion :: Version -> Bool
prop_anyVersion v' =
withinRange v' anyVersion == True
prop_noVersion :: Version -> Bool
prop_noVersion v' =
withinRange v' noVersion == False
prop_thisVersion :: Version -> Version -> Bool
prop_thisVersion v v' =
withinRange v' (thisVersion v)
== (v' == v)
prop_notThisVersion :: Version -> Version -> Bool
prop_notThisVersion v v' =
withinRange v' (notThisVersion v)
== (v' /= v)
prop_laterVersion :: Version -> Version -> Bool
prop_laterVersion v v' =
withinRange v' (laterVersion v)
== (v' > v)
prop_orLaterVersion :: Version -> Version -> Bool
prop_orLaterVersion v v' =
withinRange v' (orLaterVersion v)
== (v' >= v)
prop_earlierVersion :: Version -> Version -> Bool
prop_earlierVersion v v' =
withinRange v' (earlierVersion v)
== (v' < v)
prop_orEarlierVersion :: Version -> Version -> Bool
prop_orEarlierVersion v v' =
withinRange v' (orEarlierVersion v)
== (v' <= v)
prop_unionVersionRanges :: VersionRange -> VersionRange -> Version -> Bool
prop_unionVersionRanges vr1 vr2 v' =
withinRange v' (unionVersionRanges vr1 vr2)
== (withinRange v' vr1 || withinRange v' vr2)
prop_intersectVersionRanges :: VersionRange -> VersionRange -> Version -> Bool
prop_intersectVersionRanges vr1 vr2 v' =
withinRange v' (intersectVersionRanges vr1 vr2)
== (withinRange v' vr1 && withinRange v' vr2)
prop_differenceVersionRanges :: VersionRange -> VersionRange -> Version -> Bool
prop_differenceVersionRanges vr1 vr2 v' =
withinRange v' (differenceVersionRanges vr1 vr2)
== (withinRange v' vr1 && not (withinRange v' vr2))
prop_invertVersionRange :: VersionRange -> Version -> Bool
prop_invertVersionRange vr v' =
withinRange v' (invertVersionRange vr)
== not (withinRange v' vr)
prop_withinVersion :: Version -> Version -> Bool
prop_withinVersion v v' =
withinRange v' (withinVersion v)
== (v' >= v && v' < upper v)
where
upper (Version lower t) = Version (init lower ++ [last lower + 1]) t
prop_foldVersionRange :: VersionRange -> Bool
prop_foldVersionRange range =
expandWildcard range
== foldVersionRange anyVersion thisVersion
laterVersion earlierVersion
unionVersionRanges intersectVersionRanges
range
where
expandWildcard (WildcardVersion v) =
intersectVersionRanges (orLaterVersion v) (earlierVersion (upper v))
where
upper (Version lower t) = Version (init lower ++ [last lower + 1]) t
expandWildcard (UnionVersionRanges v1 v2) =
UnionVersionRanges (expandWildcard v1) (expandWildcard v2)
expandWildcard (IntersectVersionRanges v1 v2) =
IntersectVersionRanges (expandWildcard v1) (expandWildcard v2)
expandWildcard (VersionRangeParens v) = expandWildcard v
expandWildcard v = v
prop_foldVersionRange' :: VersionRange -> Bool
prop_foldVersionRange' range =
canonicalise range
== foldVersionRange' anyVersion thisVersion
laterVersion earlierVersion
orLaterVersion orEarlierVersion
(\v _ -> withinVersion v)
unionVersionRanges intersectVersionRanges id
range
where
canonicalise (UnionVersionRanges (LaterVersion v)
(ThisVersion v')) | v == v'
= UnionVersionRanges (ThisVersion v')
(LaterVersion v)
canonicalise (UnionVersionRanges (EarlierVersion v)
(ThisVersion v')) | v == v'
= UnionVersionRanges (ThisVersion v')
(EarlierVersion v)
canonicalise (UnionVersionRanges v1 v2) =
UnionVersionRanges (canonicalise v1) (canonicalise v2)
canonicalise (IntersectVersionRanges v1 v2) =
IntersectVersionRanges (canonicalise v1) (canonicalise v2)
canonicalise (VersionRangeParens v) = canonicalise v
canonicalise v = v
prop_isAnyVersion1 :: VersionRange -> Version -> Property
prop_isAnyVersion1 range version =
isAnyVersion range ==> withinRange version range
prop_isAnyVersion2 :: VersionRange -> Property
prop_isAnyVersion2 range =
isAnyVersion range ==>
foldVersionRange True (\_ -> False) (\_ -> False) (\_ -> False)
(\_ _ -> False) (\_ _ -> False)
(simplifyVersionRange range)
prop_isNoVersion :: VersionRange -> Version -> Property
prop_isNoVersion range version =
isNoVersion range ==> not (withinRange version range)
prop_isSpecificVersion1 :: VersionRange -> NonEmptyList Version -> Property
prop_isSpecificVersion1 range (NonEmpty versions) =
isJust version && not (null versions') ==>
allEqual (fromJust version : versions')
where
version = isSpecificVersion range
versions' = filter (`withinRange` range) versions
allEqual xs = and (zipWith (==) xs (tail xs))
prop_isSpecificVersion2 :: VersionRange -> Property
prop_isSpecificVersion2 range =
isJust version ==>
foldVersionRange Nothing Just (\_ -> Nothing) (\_ -> Nothing)
(\_ _ -> Nothing) (\_ _ -> Nothing)
(simplifyVersionRange range)
== version
where
version = isSpecificVersion range
-- | 'simplifyVersionRange' is a semantic identity on 'VersionRange'.
--
prop_simplifyVersionRange1 :: VersionRange -> Version -> Bool
prop_simplifyVersionRange1 range version =
withinRange version range == withinRange version (simplifyVersionRange range)
prop_simplifyVersionRange1' :: VersionRange -> Bool
prop_simplifyVersionRange1' range =
range `equivalentVersionRange` (simplifyVersionRange range)
-- | 'simplifyVersionRange' produces a canonical form for ranges with
-- equivalent semantics.
--
prop_simplifyVersionRange2 :: VersionRange -> VersionRange -> Version -> Property
prop_simplifyVersionRange2 r r' v =
r /= r' && simplifyVersionRange r == simplifyVersionRange r' ==>
withinRange v r == withinRange v r'
prop_simplifyVersionRange2' :: VersionRange -> VersionRange -> Property
prop_simplifyVersionRange2' r r' =
r /= r' && simplifyVersionRange r == simplifyVersionRange r' ==>
r `equivalentVersionRange` r'
--FIXME: see equivalentVersionRange for details
prop_simplifyVersionRange2'' :: VersionRange -> VersionRange -> Property
prop_simplifyVersionRange2'' r r' =
r /= r' && r `equivalentVersionRange` r' ==>
simplifyVersionRange r == simplifyVersionRange r'
|| isNoVersion r
|| isNoVersion r'
--------------------
-- VersionIntervals
--
-- | Generating VersionIntervals
--
-- This is a tad tricky as VersionIntervals is an abstract type, so we first
-- make a local type for generating the internal representation. Then we check
-- that this lets us construct valid 'VersionIntervals'.
--
newtype VersionIntervals' = VersionIntervals' [VersionInterval]
deriving (Eq, Show)
instance Arbitrary VersionIntervals' where
arbitrary = do
ubound <- arbitrary
bounds <- arbitrary
let intervals = mergeTouching
. map fixEmpty
. replaceUpper ubound
. pairs
. sortBy (comparing fst)
$ bounds
return (VersionIntervals' intervals)
where
pairs ((l, lb):(u, ub):bs) = (LowerBound l lb, UpperBound u ub)
: pairs bs
pairs _ = []
replaceUpper NoUpperBound [(l,_)] = [(l, NoUpperBound)]
replaceUpper NoUpperBound (i:is) = i : replaceUpper NoUpperBound is
replaceUpper _ is = is
-- merge adjacent intervals that touch
mergeTouching (i1@(l,u):i2@(l',u'):is)
| doesNotTouch u l' = i1 : mergeTouching (i2:is)
| otherwise = mergeTouching ((l,u'):is)
mergeTouching is = is
doesNotTouch :: UpperBound -> LowerBound -> Bool
doesNotTouch NoUpperBound _ = False
doesNotTouch (UpperBound u ub) (LowerBound l lb) =
u < l
|| (u == l && ub == ExclusiveBound && lb == ExclusiveBound)
fixEmpty (LowerBound l _, UpperBound u _)
| l == u = (LowerBound l InclusiveBound, UpperBound u InclusiveBound)
fixEmpty i = i
shrink (VersionIntervals' intervals) =
[ VersionIntervals' intervals' | intervals' <- shrink intervals ]
instance Arbitrary Bound where
arbitrary = elements [ExclusiveBound, InclusiveBound]
instance Arbitrary LowerBound where
arbitrary = liftM2 LowerBound arbitrary arbitrary
instance Arbitrary UpperBound where
arbitrary = oneof [return NoUpperBound
,liftM2 UpperBound arbitrary arbitrary]
-- | Check that our VersionIntervals' arbitrary instance generates intervals
-- that satisfies the invariant.
--
prop_gen_intervals1 :: VersionIntervals' -> Bool
prop_gen_intervals1 (VersionIntervals' intervals) =
isJust (mkVersionIntervals intervals)
instance Arbitrary VersionIntervals where
arbitrary = do
VersionIntervals' intervals <- arbitrary
case mkVersionIntervals intervals of
Just xs -> return xs
-- | Check that constructing our intervals type and converting it to a
-- 'VersionRange' and then into the true intervals type gives us back
-- the exact same sequence of intervals. This tells us that our arbitrary
-- instance for 'VersionIntervals'' is ok.
--
prop_gen_intervals2 :: VersionIntervals' -> Bool
prop_gen_intervals2 (VersionIntervals' intervals') =
asVersionIntervals (fromVersionIntervals intervals) == intervals'
where
Just intervals = mkVersionIntervals intervals'
-- | Check that 'VersionIntervals' models 'VersionRange' via
-- 'toVersionIntervals'.
--
prop_to_intervals :: VersionRange -> Version -> Bool
prop_to_intervals range version =
withinRange version range == withinIntervals version intervals
where
intervals = toVersionIntervals range
-- | Check that semantic equality on 'VersionRange's is the same as converting
-- to 'VersionIntervals' and doing syntactic equality.
--
prop_to_intervals_canonical :: VersionRange -> VersionRange -> Property
prop_to_intervals_canonical r r' =
r /= r' && r `equivalentVersionRange` r' ==>
toVersionIntervals r == toVersionIntervals r'
prop_to_intervals_canonical' :: VersionRange -> VersionRange -> Property
prop_to_intervals_canonical' r r' =
r /= r' && toVersionIntervals r == toVersionIntervals r' ==>
r `equivalentVersionRange` r'
-- | Check that 'VersionIntervals' models 'VersionRange' via
-- 'fromVersionIntervals'.
--
prop_from_intervals :: VersionIntervals -> Version -> Bool
prop_from_intervals intervals version =
withinRange version range == withinIntervals version intervals
where
range = fromVersionIntervals intervals
-- | @'toVersionIntervals' . 'fromVersionIntervals'@ is an exact identity on
-- 'VersionIntervals'.
--
prop_to_from_intervals :: VersionIntervals -> Bool
prop_to_from_intervals intervals =
toVersionIntervals (fromVersionIntervals intervals) == intervals
-- | @'fromVersionIntervals' . 'toVersionIntervals'@ is a semantic identity on
-- 'VersionRange', though not necessarily a syntactic identity.
--
prop_from_to_intervals :: VersionRange -> Bool
prop_from_to_intervals range =
range' `equivalentVersionRange` range
where
range' = fromVersionIntervals (toVersionIntervals range)
-- | Equivalent of 'prop_from_to_intervals'
--
prop_from_to_intervals' :: VersionRange -> Version -> Bool
prop_from_to_intervals' range version =
withinRange version range' == withinRange version range
where
range' = fromVersionIntervals (toVersionIntervals range)
-- | The semantics of 'unionVersionIntervals' is (||).
--
prop_unionVersionIntervals :: VersionIntervals -> VersionIntervals
-> Version -> Bool
prop_unionVersionIntervals is1 is2 v =
withinIntervals v (unionVersionIntervals is1 is2)
== (withinIntervals v is1 || withinIntervals v is2)
-- | 'unionVersionIntervals' is idempotent
--
prop_unionVersionIntervals_idempotent :: VersionIntervals -> Bool
prop_unionVersionIntervals_idempotent =
Laws.idempotent_binary unionVersionIntervals
-- | 'unionVersionIntervals' is commutative
--
prop_unionVersionIntervals_commutative :: VersionIntervals
-> VersionIntervals -> Bool
prop_unionVersionIntervals_commutative =
Laws.commutative unionVersionIntervals
-- | 'unionVersionIntervals' is associative
--
prop_unionVersionIntervals_associative :: VersionIntervals
-> VersionIntervals
-> VersionIntervals -> Bool
prop_unionVersionIntervals_associative =
Laws.associative unionVersionIntervals
-- | The semantics of 'intersectVersionIntervals' is (&&).
--
prop_intersectVersionIntervals :: VersionIntervals -> VersionIntervals
-> Version -> Bool
prop_intersectVersionIntervals is1 is2 v =
withinIntervals v (intersectVersionIntervals is1 is2)
== (withinIntervals v is1 && withinIntervals v is2)
-- | 'intersectVersionIntervals' is idempotent
--
prop_intersectVersionIntervals_idempotent :: VersionIntervals -> Bool
prop_intersectVersionIntervals_idempotent =
Laws.idempotent_binary intersectVersionIntervals
-- | 'intersectVersionIntervals' is commutative
--
prop_intersectVersionIntervals_commutative :: VersionIntervals
-> VersionIntervals -> Bool
prop_intersectVersionIntervals_commutative =
Laws.commutative intersectVersionIntervals
-- | 'intersectVersionIntervals' is associative
--
prop_intersectVersionIntervals_associative :: VersionIntervals
-> VersionIntervals
-> VersionIntervals -> Bool
prop_intersectVersionIntervals_associative =
Laws.associative intersectVersionIntervals
-- | 'unionVersionIntervals' distributes over 'intersectVersionIntervals'
--
prop_union_intersect_distributive :: Property
prop_union_intersect_distributive =
Laws.distributive_left unionVersionIntervals intersectVersionIntervals
.&. Laws.distributive_right unionVersionIntervals intersectVersionIntervals
-- | 'intersectVersionIntervals' distributes over 'unionVersionIntervals'
--
prop_intersect_union_distributive :: Property
prop_intersect_union_distributive =
Laws.distributive_left intersectVersionIntervals unionVersionIntervals
.&. Laws.distributive_right intersectVersionIntervals unionVersionIntervals
-- | The semantics of 'invertVersionIntervals' is 'not'.
--
prop_invertVersionIntervals :: VersionIntervals
-> Version -> Bool
prop_invertVersionIntervals vi v =
withinIntervals v (invertVersionIntervals vi)
== not (withinIntervals v vi)
-- | Double application of 'invertVersionIntervals' is the identity function
prop_invertVersionIntervalsTwice :: VersionIntervals -> Bool
prop_invertVersionIntervalsTwice vi =
invertVersionIntervals (invertVersionIntervals vi) == vi
--------------------------------
-- equivalentVersionRange helper
prop_equivalentVersionRange :: VersionRange -> VersionRange
-> Version -> Property
prop_equivalentVersionRange range range' version =
equivalentVersionRange range range' && range /= range' ==>
withinRange version range == withinRange version range'
--FIXME: this is wrong. consider version ranges "<=1" and "<1.0"
-- this algorithm cannot distinguish them because there is no version
-- that is included by one that is excluded by the other.
-- Alternatively we must reconsider the semantics of '<' and '<='
-- in version ranges / version intervals. Perhaps the canonical
-- representation should use just < v and interpret "<= v" as "< v.0".
equivalentVersionRange :: VersionRange -> VersionRange -> Bool
equivalentVersionRange vr1 vr2 =
let allVersionsUsed = nub (sort (versionsUsed vr1 ++ versionsUsed vr2))
minPoint = Version [0] []
maxPoint | null allVersionsUsed = minPoint
| otherwise = case maximum allVersionsUsed of
Version vs _ -> Version (vs ++ [1]) []
probeVersions = minPoint : maxPoint
: intermediateVersions allVersionsUsed
in all (\v -> withinRange v vr1 == withinRange v vr2) probeVersions
where
versionsUsed = foldVersionRange [] (\x->[x]) (\x->[x]) (\x->[x]) (++) (++)
intermediateVersions (v1:v2:vs) = v1 : intermediateVersion v1 v2
: intermediateVersions (v2:vs)
intermediateVersions vs = vs
intermediateVersion :: Version -> Version -> Version
intermediateVersion v1 v2 | v1 >= v2 = error "intermediateVersion: v1 >= v2"
intermediateVersion (Version v1 _) (Version v2 _) =
Version (intermediateList v1 v2) []
where
intermediateList :: [Int] -> [Int] -> [Int]
intermediateList [] (_:_) = [0]
intermediateList (x:xs) (y:ys)
| x < y = x : xs ++ [0]
| otherwise = x : intermediateList xs ys
prop_intermediateVersion :: Version -> Version -> Property
prop_intermediateVersion v1 v2 =
(v1 /= v2) && not (adjacentVersions v1 v2) ==>
if v1 < v2
then let v = intermediateVersion v1 v2
in (v1 < v && v < v2)
else let v = intermediateVersion v2 v1
in v1 > v && v > v2
adjacentVersions :: Version -> Version -> Bool
adjacentVersions (Version v1 _) (Version v2 _) = v1 ++ [0] == v2
|| v2 ++ [0] == v1
--------------------------------
-- Parsing and pretty printing
--
prop_parse_disp1 :: VersionRange -> Bool
prop_parse_disp1 vr =
fmap stripParens (simpleParse (display vr)) == Just (canonicalise vr)
where
canonicalise = swizzle . swap
swizzle (UnionVersionRanges (UnionVersionRanges v1 v2) v3)
| not (isOrLaterVersion v1 v2) && not (isOrEarlierVersion v1 v2)
= swizzle (UnionVersionRanges v1 (UnionVersionRanges v2 v3))
swizzle (IntersectVersionRanges (IntersectVersionRanges v1 v2) v3)
= swizzle (IntersectVersionRanges v1 (IntersectVersionRanges v2 v3))
swizzle (UnionVersionRanges v1 v2) =
UnionVersionRanges (swizzle v1) (swizzle v2)
swizzle (IntersectVersionRanges v1 v2) =
IntersectVersionRanges (swizzle v1) (swizzle v2)
swizzle (VersionRangeParens v) = swizzle v
swizzle v = v
isOrLaterVersion (ThisVersion v) (LaterVersion v') = v == v'
isOrLaterVersion _ _ = False
isOrEarlierVersion (ThisVersion v) (EarlierVersion v') = v == v'
isOrEarlierVersion _ _ = False
swap =
foldVersionRange' anyVersion thisVersion
laterVersion earlierVersion
orLaterVersion orEarlierVersion
(\v _ -> withinVersion v)
unionVersionRanges intersectVersionRanges id
stripParens :: VersionRange -> VersionRange
stripParens (VersionRangeParens v) = stripParens v
stripParens (UnionVersionRanges v1 v2) =
UnionVersionRanges (stripParens v1) (stripParens v2)
stripParens (IntersectVersionRanges v1 v2) =
IntersectVersionRanges (stripParens v1) (stripParens v2)
stripParens v = v
prop_parse_disp2 :: VersionRange -> Property
prop_parse_disp2 vr =
let b = fmap (display :: VersionRange -> String) (simpleParse (display vr))
a = Just (display vr)
in
counterexample ("Expected: " ++ show a) $
counterexample ("But got: " ++ show b) $
b == a
prop_parse_disp3 :: VersionRange -> Property
prop_parse_disp3 vr =
let a = Just (display vr)
b = fmap displayRaw (simpleParse (display vr))
in
counterexample ("Expected: " ++ show a) $
counterexample ("But got: " ++ show b) $
b == a
prop_parse_disp4 :: VersionRange -> Property
prop_parse_disp4 vr =
let a = Just vr
b = (simpleParse (display vr))
in
counterexample ("Expected: " ++ show a) $
counterexample ("But got: " ++ show b) $
b == a
prop_parse_disp5 :: VersionRange -> Property
prop_parse_disp5 vr =
let a = Just vr
b = simpleParse (displayRaw vr)
in
counterexample ("Expected: " ++ show a) $
counterexample ("But got: " ++ show b) $
b == a
displayRaw :: VersionRange -> String
displayRaw =
Disp.render
. foldVersionRange' -- precedence:
-- All the same as the usual pretty printer, except for the parens
( Disp.text "-any")
(\v -> Disp.text "==" <> disp v)
(\v -> Disp.char '>' <> disp v)
(\v -> Disp.char '<' <> disp v)
(\v -> Disp.text ">=" <> disp v)
(\v -> Disp.text "<=" <> disp v)
(\v _ -> Disp.text "==" <> dispWild v)
(\r1 r2 -> r1 <+> Disp.text "||" <+> r2)
(\r1 r2 -> r1 <+> Disp.text "&&" <+> r2)
(\r -> Disp.parens r) -- parens
where
dispWild (Version b _) =
Disp.hcat (Disp.punctuate (Disp.char '.') (map Disp.int b))
<> Disp.text ".*"
| tolysz/prepare-ghcjs | spec-lts8/cabal/Cabal/tests/UnitTests/Distribution/Version.hs | bsd-3-clause | 26,648 | 0 | 16 | 6,013 | 6,094 | 3,151 | 2,943 | -1 | -1 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
-- |
module Stack.Types.Package where
import Control.DeepSeq
import Control.Exception hiding (try,catch)
import Control.Monad.Catch
import Control.Monad.IO.Class
import Control.Monad.Logger (MonadLogger)
import Control.Monad.Reader
import Data.Binary
import Data.Binary.VersionTagged
import qualified Data.ByteString as S
import Data.Data
import Data.Function
import Data.List
import qualified Data.Map as M
import Data.Map.Strict (Map)
import Data.Maybe
import Data.Monoid
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Text (Text)
import qualified Data.Text as T
import Data.Text.Encoding (encodeUtf8, decodeUtf8)
import Distribution.InstalledPackageInfo (PError)
import Distribution.ModuleName (ModuleName)
import Distribution.Package hiding (Package,PackageName,packageName,packageVersion,PackageIdentifier)
import Distribution.PackageDescription (TestSuiteInterface)
import Distribution.System (Platform (..))
import Distribution.Text (display)
import GHC.Generics (Generic)
import Path as FL
import Prelude
import Stack.Types.BuildPlan (GitSHA1)
import Stack.Types.Compiler
import Stack.Types.Config
import Stack.Types.FlagName
import Stack.Types.GhcPkgId
import Stack.Types.PackageIdentifier
import Stack.Types.PackageName
import Stack.Types.Version
-- | All exceptions thrown by the library.
data PackageException
= PackageInvalidCabalFile (Maybe (Path Abs File)) PError
| PackageNoCabalFileFound (Path Abs Dir)
| PackageMultipleCabalFilesFound (Path Abs Dir) [Path Abs File]
| MismatchedCabalName (Path Abs File) PackageName
deriving Typeable
instance Exception PackageException
instance Show PackageException where
show (PackageInvalidCabalFile mfile err) =
"Unable to parse cabal file" ++
(case mfile of
Nothing -> ""
Just file -> ' ' : toFilePath file) ++
": " ++
show err
show (PackageNoCabalFileFound dir) =
"No .cabal file found in directory " ++
toFilePath dir
show (PackageMultipleCabalFilesFound dir files) =
"Multiple .cabal files found in directory " ++
toFilePath dir ++
": " ++
intercalate ", " (map (toFilePath . filename) files)
show (MismatchedCabalName fp name) = concat
[ "cabal file path "
, toFilePath fp
, " does not match the package name it defines.\n"
, "Please rename the file to: "
, packageNameString name
, ".cabal\n"
, "For more information, see: https://github.com/commercialhaskell/stack/issues/317"
]
-- | Some package info.
data Package =
Package {packageName :: !PackageName -- ^ Name of the package.
,packageVersion :: !Version -- ^ Version of the package
,packageFiles :: !GetPackageFiles -- ^ Get all files of the package.
,packageDeps :: !(Map PackageName VersionRange) -- ^ Packages that the package depends on.
,packageTools :: ![Dependency] -- ^ A build tool name.
,packageAllDeps :: !(Set PackageName) -- ^ Original dependencies (not sieved).
,packageGhcOptions :: ![Text] -- ^ Ghc options used on package.
,packageFlags :: !(Map FlagName Bool) -- ^ Flags used on package.
,packageDefaultFlags :: !(Map FlagName Bool) -- ^ Defaults for unspecified flags.
,packageHasLibrary :: !Bool -- ^ does the package have a buildable library stanza?
,packageTests :: !(Map Text TestSuiteInterface) -- ^ names and interfaces of test suites
,packageBenchmarks :: !(Set Text) -- ^ names of benchmarks
,packageExes :: !(Set Text) -- ^ names of executables
,packageOpts :: !GetPackageOpts -- ^ Args to pass to GHC.
,packageHasExposedModules :: !Bool -- ^ Does the package have exposed modules?
,packageSimpleType :: !Bool -- ^ Does the package of build-type: Simple
}
deriving (Show,Typeable)
packageIdentifier :: Package -> PackageIdentifier
packageIdentifier pkg =
PackageIdentifier (packageName pkg) (packageVersion pkg)
packageDefinedFlags :: Package -> Set FlagName
packageDefinedFlags = M.keysSet . packageDefaultFlags
-- | Files that the package depends on, relative to package directory.
-- Argument is the location of the .cabal file
newtype GetPackageOpts = GetPackageOpts
{ getPackageOpts :: forall env m. (MonadIO m,HasEnvConfig env, HasPlatform env, MonadThrow m, MonadReader env m, MonadLogger m, MonadCatch m)
=> SourceMap
-> InstalledMap
-> [PackageName]
-> [PackageName]
-> Path Abs File
-> m (Map NamedComponent (Set ModuleName)
,Map NamedComponent (Set DotCabalPath)
,Map NamedComponent BuildInfoOpts)
}
instance Show GetPackageOpts where
show _ = "<GetPackageOpts>"
-- | GHC options based on cabal information and ghc-options.
data BuildInfoOpts = BuildInfoOpts
{ bioOpts :: [String]
, bioOneWordOpts :: [String]
, bioPackageFlags :: [String]
-- ^ These options can safely have 'nubOrd' applied to them, as
-- there are no multi-word options (see
-- https://github.com/commercialhaskell/stack/issues/1255)
, bioCabalMacros :: Maybe (Path Abs File)
} deriving Show
-- | Files to get for a cabal package.
data CabalFileType
= AllFiles
| Modules
-- | Files that the package depends on, relative to package directory.
-- Argument is the location of the .cabal file
newtype GetPackageFiles = GetPackageFiles
{ getPackageFiles :: forall m env. (MonadIO m, MonadLogger m, MonadThrow m, MonadCatch m, MonadReader env m, HasPlatform env, HasEnvConfig env)
=> Path Abs File
-> m (Map NamedComponent (Set ModuleName)
,Map NamedComponent (Set DotCabalPath)
,Set (Path Abs File)
,[PackageWarning])
}
instance Show GetPackageFiles where
show _ = "<GetPackageFiles>"
-- | Warning generated when reading a package
data PackageWarning
= UnlistedModulesWarning (Path Abs File) (Maybe String) [ModuleName]
-- ^ Modules found that are not listed in cabal file
| MissingModulesWarning (Path Abs File) (Maybe String) [ModuleName]
-- ^ Modules not found in file system, which are listed in cabal file
instance Show PackageWarning where
show (UnlistedModulesWarning cabalfp component [unlistedModule]) =
concat
[ "module not listed in "
, toFilePath (filename cabalfp)
, case component of
Nothing -> " for library"
Just c -> " for '" ++ c ++ "'"
, " component (add to other-modules): "
, display unlistedModule]
show (UnlistedModulesWarning cabalfp component unlistedModules) =
concat
[ "modules not listed in "
, toFilePath (filename cabalfp)
, case component of
Nothing -> " for library"
Just c -> " for '" ++ c ++ "'"
, " component (add to other-modules):\n "
, intercalate "\n " (map display unlistedModules)]
show (MissingModulesWarning cabalfp component [missingModule]) =
concat
[ "module listed in "
, toFilePath (filename cabalfp)
, case component of
Nothing -> " for library"
Just c -> " for '" ++ c ++ "'"
, " component not found in filesystem: "
, display missingModule]
show (MissingModulesWarning cabalfp component missingModules) =
concat
[ "modules listed in "
, toFilePath (filename cabalfp)
, case component of
Nothing -> " for library"
Just c -> " for '" ++ c ++ "'"
, " component not found in filesystem:\n "
, intercalate "\n " (map display missingModules)]
-- | Package build configuration
data PackageConfig =
PackageConfig {packageConfigEnableTests :: !Bool -- ^ Are tests enabled?
,packageConfigEnableBenchmarks :: !Bool -- ^ Are benchmarks enabled?
,packageConfigFlags :: !(Map FlagName Bool) -- ^ Configured flags.
,packageConfigGhcOptions :: ![Text] -- ^ Configured ghc options.
,packageConfigCompilerVersion :: !CompilerVersion -- ^ GHC version
,packageConfigPlatform :: !Platform -- ^ host platform
}
deriving (Show,Typeable)
-- | Compares the package name.
instance Ord Package where
compare = on compare packageName
-- | Compares the package name.
instance Eq Package where
(==) = on (==) packageName
type SourceMap = Map PackageName PackageSource
-- | Where the package's source is located: local directory or package index
data PackageSource
= PSLocal LocalPackage
| PSUpstream Version InstallLocation (Map FlagName Bool) [Text] (Maybe GitSHA1)
-- ^ Upstream packages could be installed in either local or snapshot
-- databases; this is what 'InstallLocation' specifies.
deriving Show
instance PackageInstallInfo PackageSource where
piiVersion (PSLocal lp) = packageVersion $ lpPackage lp
piiVersion (PSUpstream v _ _ _ _) = v
piiLocation (PSLocal _) = Local
piiLocation (PSUpstream _ loc _ _ _) = loc
-- | Datatype which tells how which version of a package to install and where
-- to install it into
class PackageInstallInfo a where
piiVersion :: a -> Version
piiLocation :: a -> InstallLocation
-- | Information on a locally available package of source code
data LocalPackage = LocalPackage
{ lpPackage :: !Package
-- ^ The @Package@ info itself, after resolution with package flags,
-- with tests and benchmarks disabled
, lpComponents :: !(Set NamedComponent)
-- ^ Components to build, not including the library component.
, lpUnbuildable :: !(Set NamedComponent)
-- ^ Components explicitly requested for build, that are marked
-- "buildable: false".
, lpWanted :: !Bool
-- ^ Whether this package is wanted as a target.
, lpTestDeps :: !(Map PackageName VersionRange)
-- ^ Used for determining if we can use --enable-tests in a normal build.
, lpBenchDeps :: !(Map PackageName VersionRange)
-- ^ Used for determining if we can use --enable-benchmarks in a normal
-- build.
, lpTestBench :: !(Maybe Package)
-- ^ This stores the 'Package' with tests and benchmarks enabled, if
-- either is asked for by the user.
, lpDir :: !(Path Abs Dir)
-- ^ Directory of the package.
, lpCabalFile :: !(Path Abs File)
-- ^ The .cabal file
, lpForceDirty :: !Bool
, lpDirtyFiles :: !(Maybe (Set FilePath))
-- ^ Nothing == not dirty, Just == dirty. Note that the Set may be empty if
-- we forced the build to treat packages as dirty. Also, the Set may not
-- include all modified files.
, lpNewBuildCache :: !(Map FilePath FileCacheInfo)
-- ^ current state of the files
, lpFiles :: !(Set (Path Abs File))
-- ^ all files used by this package
}
deriving Show
-- | A single, fully resolved component of a package
data NamedComponent
= CLib
| CExe !Text
| CTest !Text
| CBench !Text
deriving (Show, Eq, Ord)
renderComponent :: NamedComponent -> S.ByteString
renderComponent CLib = "lib"
renderComponent (CExe x) = "exe:" <> encodeUtf8 x
renderComponent (CTest x) = "test:" <> encodeUtf8 x
renderComponent (CBench x) = "bench:" <> encodeUtf8 x
renderPkgComponents :: [(PackageName, NamedComponent)] -> Text
renderPkgComponents = T.intercalate " " . map renderPkgComponent
renderPkgComponent :: (PackageName, NamedComponent) -> Text
renderPkgComponent (pkg, comp) = packageNameText pkg <> ":" <> decodeUtf8 (renderComponent comp)
exeComponents :: Set NamedComponent -> Set Text
exeComponents = Set.fromList . mapMaybe mExeName . Set.toList
where
mExeName (CExe name) = Just name
mExeName _ = Nothing
testComponents :: Set NamedComponent -> Set Text
testComponents = Set.fromList . mapMaybe mTestName . Set.toList
where
mTestName (CTest name) = Just name
mTestName _ = Nothing
benchComponents :: Set NamedComponent -> Set Text
benchComponents = Set.fromList . mapMaybe mBenchName . Set.toList
where
mBenchName (CBench name) = Just name
mBenchName _ = Nothing
isCLib :: NamedComponent -> Bool
isCLib CLib{} = True
isCLib _ = False
isCExe :: NamedComponent -> Bool
isCExe CExe{} = True
isCExe _ = False
isCTest :: NamedComponent -> Bool
isCTest CTest{} = True
isCTest _ = False
isCBench :: NamedComponent -> Bool
isCBench CBench{} = True
isCBench _ = False
-- | A location to install a package into, either snapshot or local
data InstallLocation = Snap | Local
deriving (Show, Eq)
instance Monoid InstallLocation where
mempty = Snap
mappend Local _ = Local
mappend _ Local = Local
mappend Snap Snap = Snap
data InstalledPackageLocation = InstalledTo InstallLocation | ExtraGlobal
deriving (Show, Eq)
data FileCacheInfo = FileCacheInfo
{ fciModTime :: !ModTime
, fciSize :: !Word64
, fciHash :: !S.ByteString
}
deriving (Generic, Show)
instance Binary FileCacheInfo
instance HasStructuralInfo FileCacheInfo
instance NFData FileCacheInfo
-- | Used for storage and comparison.
newtype ModTime = ModTime (Integer,Rational)
deriving (Ord,Show,Generic,Eq,NFData,Binary)
instance HasStructuralInfo ModTime
instance HasSemanticVersion ModTime
-- | A descriptor from a .cabal file indicating one of the following:
--
-- exposed-modules: Foo
-- other-modules: Foo
-- or
-- main-is: Foo.hs
--
data DotCabalDescriptor
= DotCabalModule !ModuleName
| DotCabalMain !FilePath
| DotCabalFile !FilePath
| DotCabalCFile !FilePath
deriving (Eq,Ord,Show)
-- | Maybe get the module name from the .cabal descriptor.
dotCabalModule :: DotCabalDescriptor -> Maybe ModuleName
dotCabalModule (DotCabalModule m) = Just m
dotCabalModule _ = Nothing
-- | Maybe get the main name from the .cabal descriptor.
dotCabalMain :: DotCabalDescriptor -> Maybe FilePath
dotCabalMain (DotCabalMain m) = Just m
dotCabalMain _ = Nothing
-- | A path resolved from the .cabal file, which is either main-is or
-- an exposed/internal/referenced module.
data DotCabalPath
= DotCabalModulePath !(Path Abs File)
| DotCabalMainPath !(Path Abs File)
| DotCabalFilePath !(Path Abs File)
| DotCabalCFilePath !(Path Abs File)
deriving (Eq,Ord,Show)
-- | Get the module path.
dotCabalModulePath :: DotCabalPath -> Maybe (Path Abs File)
dotCabalModulePath (DotCabalModulePath fp) = Just fp
dotCabalModulePath _ = Nothing
-- | Get the main path.
dotCabalMainPath :: DotCabalPath -> Maybe (Path Abs File)
dotCabalMainPath (DotCabalMainPath fp) = Just fp
dotCabalMainPath _ = Nothing
-- | Get the c file path.
dotCabalCFilePath :: DotCabalPath -> Maybe (Path Abs File)
dotCabalCFilePath (DotCabalCFilePath fp) = Just fp
dotCabalCFilePath _ = Nothing
-- | Get the path.
dotCabalGetPath :: DotCabalPath -> Path Abs File
dotCabalGetPath dcp =
case dcp of
DotCabalModulePath fp -> fp
DotCabalMainPath fp -> fp
DotCabalFilePath fp -> fp
DotCabalCFilePath fp -> fp
type InstalledMap = Map PackageName (InstallLocation, Installed)
data Installed = Library PackageIdentifier GhcPkgId | Executable PackageIdentifier
deriving (Show, Eq, Ord)
installedPackageIdentifier :: Installed -> PackageIdentifier
installedPackageIdentifier (Library pid _) = pid
installedPackageIdentifier (Executable pid) = pid
-- | Get the installed Version.
installedVersion :: Installed -> Version
installedVersion = packageIdentifierVersion . installedPackageIdentifier
| phadej/stack | src/Stack/Types/Package.hs | bsd-3-clause | 16,693 | 0 | 18 | 4,431 | 3,347 | 1,823 | 1,524 | 408 | 4 |
{-# LANGUAGE TypeFamilies #-}
module ShouldCompile where
import Data.Kind (Type)
class Cls a where
type Fam a :: Type
type Fam a = Maybe a
instance Cls Int where
-- Overriding default
type Fam Int = Bool
nott :: (Fam a ~ Bool) => a -> Fam a -> Fam a
nott _proxy False = True
nott _proxy True = False
foo :: Bool -> Bool
foo = nott (undefined :: Int)
| sdiehl/ghc | testsuite/tests/typecheck/should_compile/tc252.hs | bsd-3-clause | 372 | 0 | 8 | 94 | 137 | 74 | 63 | -1 | -1 |
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="ja-JP">
<title>Regular Expression Tester</title>
<maps>
<homeID>regextester</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/regextester/src/main/javahelp/help_ja_JP/helpset_ja_JP.hs | apache-2.0 | 978 | 77 | 66 | 157 | 409 | 207 | 202 | -1 | -1 |
module D5 where
{-Rename top level identifier 'sumSquares' to 'sum'.
This refactoring affects module `D5', 'B5' , 'C5' and 'A5' -}
data Tree a = Leaf a | Branch (Tree a) (Tree a)
fringe :: Tree a -> [a]
fringe (Leaf x ) = [x]
fringe (Branch left right) = fringe left ++ fringe right
class SameOrNot a where
isSame :: a -> a -> Bool
isNotSame :: a -> a -> Bool
instance SameOrNot Int where
isSame a b = a == b
isNotSame a b = a /= b
sumSquares (x:xs) = sq x + sumSquares xs
where sq x = x ^pow
pow = 2
sumSquares [] = 0
| kmate/HaRe | old/testing/renaming/D5.hs | bsd-3-clause | 561 | 0 | 8 | 154 | 217 | 112 | 105 | 15 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE ViewPatterns #-}
module Stack.Types.Compiler where
import Control.DeepSeq
import Control.DeepSeq.Generics (genericRnf)
import Data.Aeson
import Data.Binary (Binary)
import Data.Monoid ((<>))
import qualified Data.Text as T
import GHC.Generics (Generic)
import Stack.Types.Version
-- | Variety of compiler to use.
data WhichCompiler
= Ghc
| Ghcjs
deriving (Show, Eq, Ord)
-- | Specifies a compiler and its version number(s).
--
-- Note that despite having this datatype, stack isn't in a hurry to
-- support compilers other than GHC.
--
-- NOTE: updating this will change its binary serialization. The
-- version number in the 'BinarySchema' instance for 'MiniBuildPlan'
-- should be updated.
data CompilerVersion
= GhcVersion {-# UNPACK #-} !Version
| GhcjsVersion
{-# UNPACK #-} !Version -- ^ GHCJS version
{-# UNPACK #-} !Version -- ^ GHC version
deriving (Generic, Show, Eq, Ord)
instance Binary CompilerVersion
instance NFData CompilerVersion where
rnf = genericRnf
instance ToJSON CompilerVersion where
toJSON = toJSON . compilerVersionName
instance FromJSON CompilerVersion where
parseJSON (String t) = maybe (fail "Failed to parse compiler version") return (parseCompilerVersion t)
parseJSON _ = fail "Invalid CompilerVersion, must be String"
parseCompilerVersion :: T.Text -> Maybe CompilerVersion
parseCompilerVersion t
| Just t' <- T.stripPrefix "ghc-" t
, Just v <- parseVersionFromString $ T.unpack t'
= Just (GhcVersion v)
| Just t' <- T.stripPrefix "ghcjs-" t
, [tghcjs, tghc] <- T.splitOn "_ghc-" t'
, Just vghcjs <- parseVersionFromString $ T.unpack tghcjs
, Just vghc <- parseVersionFromString $ T.unpack tghc
= Just (GhcjsVersion vghcjs vghc)
| otherwise
= Nothing
compilerVersionName :: CompilerVersion -> T.Text
compilerVersionName (GhcVersion vghc) =
"ghc-" <> versionText vghc
compilerVersionName (GhcjsVersion vghcjs vghc) =
"ghcjs-" <> versionText vghcjs <> "_ghc-" <> versionText vghc
whichCompiler :: CompilerVersion -> WhichCompiler
whichCompiler GhcVersion {} = Ghc
whichCompiler GhcjsVersion {} = Ghcjs
isWantedCompiler :: VersionCheck -> CompilerVersion -> CompilerVersion -> Bool
isWantedCompiler check (GhcVersion wanted) (GhcVersion actual) =
checkVersion check wanted actual
isWantedCompiler check (GhcjsVersion wanted wantedGhc) (GhcjsVersion actual actualGhc) =
checkVersion check wanted actual && checkVersion check wantedGhc actualGhc
isWantedCompiler _ _ _ = False
compilerExeName :: WhichCompiler -> String
compilerExeName Ghc = "ghc"
compilerExeName Ghcjs = "ghcjs"
haddockExeName :: WhichCompiler -> String
haddockExeName Ghc = "haddock"
haddockExeName Ghcjs = "haddock-ghcjs"
| Denommus/stack | src/Stack/Types/Compiler.hs | bsd-3-clause | 2,902 | 0 | 11 | 567 | 673 | 349 | 324 | 62 | 1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TemplateHaskell #-}
module T14931_Bug where
import Prelude (Int, IO, Bool(..), Num(..), Monad(..), not, print)
import qualified Language.Haskell.TH.Syntax as TH
import T14931_State
wat :: IO ()
wat = print $(let playGame [] = do
(_, score) <- get
return score
playGame (x:xs) = do
(on, score) <- get
case x of
'a' | on -> put (on, score + 1)
'b' | on -> put (on, score - 1)
'c' -> put (not on, score)
_ -> put (on, score)
playGame xs
startState :: (Bool, Int)
startState = (False, 0)
in TH.lift (evalState (playGame "abcaaacbbcabbab") startState) )
| sdiehl/ghc | testsuite/tests/profiling/should_compile/T14931_Bug.hs | bsd-3-clause | 901 | 0 | 20 | 407 | 279 | 152 | 127 | 21 | 5 |
{-# LANGUAGE DataKinds, TypeOperators, KindSignatures, TypeFamilies,
ConstraintKinds, FlexibleContexts #-}
{-# OPTIONS_GHC -fplugin T11525_Plugin #-}
module T11525 where
import GHC.TypeLits
import Data.Proxy
truncateB :: KnownNat a => Proxy (a + b) -> Proxy a
truncateB Proxy = Proxy
class Bus t where
type AddrBits t :: Nat
data MasterOut b = MasterOut
{ adr :: Proxy (AddrBits b)
}
type WiderAddress b b' k = ( KnownNat (AddrBits b)
, AddrBits b' ~ (AddrBits b + k)
)
narrowAddress' :: (WiderAddress b b' k)
=> MasterOut b'
-> MasterOut b
narrowAddress' m = MasterOut { adr = truncateB (adr m) }
| ezyang/ghc | testsuite/tests/typecheck/should_compile/T11525.hs | bsd-3-clause | 711 | 0 | 11 | 213 | 188 | 102 | 86 | 18 | 1 |
module Model where
import Prelude
import Yesod
import Yesod.Markdown
import qualified Data.ByteString as BS
import Data.Text (Text)
import Data.Time (UTCTime)
import Data.Map
import Database.Persist.Quasi
import Database.Persist.MongoDB hiding (master)
import Language.Haskell.TH.Syntax
import Data.Typeable (Typeable)
-- You can define all of your database entities in the entities file.
-- You can find more information on persistent and how to declare entities
-- at:
-- http://www.yesodweb.com/book/persistent/
let mongoSettings = (mkPersistSettings (ConT ''MongoContext))
{ mpsGeneric = False
}
in share [mkPersist mongoSettings, mkMigrate "migrateAll"]
$(persistFileWith lowerCaseSettings "config/models")
| klarh/barch | Model.hs | mit | 767 | 0 | 14 | 138 | 149 | 88 | 61 | -1 | -1 |
module Ho.Library(
LibDesc(..),
readDescFile,
collectLibraries,
libModMap,
libHash,
libMgHash,
libProvides,
libName,
libBaseName,
libHoLib,
preprocess,
listLibraries
) where
import Control.Monad
import Data.Char
import Data.List
import Data.Maybe
import Data.Monoid
import Data.Version
import Data.Yaml.Syck
import System.Directory
import Text.Printf
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as LBS
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified System.FilePath as FP
import Ho.Binary
import Ho.ReadSource
import Ho.Type
import Name.Name(Module)
import Options
import PackedString(PackedString,packString,unpackPS)
import Util.Gen
import Util.YAML
import qualified FlagDump as FD
import qualified FlagOpts as FO
import qualified Support.MD5 as MD5
libModMap = hoModuleMap . libHoLib
libHash = hohHash . libHoHeader
libMgHash mg lib = MD5.md5String $ show (libHash lib,mg)
libProvides mg lib = [ m | (m,mg') <- Map.toList (libModMap lib), mg == mg']
libName lib = let HoHeader { hohName = ~(Right (name,vers)) } = libHoHeader lib in unpackPS name ++ "-" ++ showVersion vers
libVersion lib = let HoHeader { hohName = ~(Right (_name,vers)) } = libHoHeader lib in vers
libBaseName lib = let HoHeader { hohName = ~(Right (name,_vers)) } = libHoHeader lib in name
libModules l = let lib = libHoLib l in ([ m | (m,_) <- Map.toList (hoModuleMap lib)],Map.toList (hoReexports lib))
libVersionCompare l1 l2 = compare (libVersion l1) (libVersion l2)
--------------------------------
-- finding and listing libraries
--------------------------------
instance ToNode Module where
toNode m = toNode $ show m
instance ToNode HoHash where
toNode m = toNode $ show m
instance ToNode PackedString where
toNode m = toNode $ unpackPS m
listLibraries :: IO ()
listLibraries = do
(_,byhashes) <- fetchAllLibraries
let libs = Map.toList byhashes
if not verbose then putStr $ showYAML (sort $ map (libName . snd) libs) else do
let f (h,l) = (show h,[
("Name",toNode (libName l)),
("BaseName",toNode (libBaseName l)),
("Version",toNode (showVersion $ libVersion l)),
("FilePath",toNode (libFileName l)),
("LibDeps",toNode [ h | (_,h) <- hohLibDeps (libHoHeader l)]),
("Exported-Modules",toNode $ mod ++ fsts rmod)
]) where
(mod,rmod) = libModules l
putStr $ showYAML (map f libs)
-- Collect all libraries and return those which are explicitly and implicitly imported.
--
-- The basic process is:
-- - Find all libraries and create two indexes, a map of named libraries to
-- the newest version of them, and a map of library hashes to the libraries
-- themselves.
--
-- - For all the libraries listed on the command line, find the newest
-- version of each of them, flag these as the explicitly imported libraries.
--
-- - recursively find the dependencies by the hash's listed in the library deps. if the names
-- match a library already loaded, ensure the hash matches up. flag these libraries as 'implicit' unless
-- already flaged 'explicit'
--
-- - perform sanity checks on final lists of implicit and explicit libraries.
--
-- Library Checks needed:
-- - We have found versions of all libraries listed on the command line
-- - We have all dependencies of all libraries and the hash matches the proper library name
-- - no libraries directly export the same modules, (but re-exporting the same module is fine)
-- - conflicting versions of any particular library are not required due to dependencies
fetchAllLibraries :: IO (Map.Map PackedString [Library],Map.Map HoHash Library)
fetchAllLibraries = ans where
ans = do
(bynames',byhashes') <- unzip `fmap` concatMapM f (optHlPath options)
let bynames = Map.map (reverse . sortBy libVersionCompare) $ Map.unionsWith (++) bynames'
byhashes = Map.unions byhashes'
return (bynames,byhashes)
f fp = do
fs <- flip iocatch (\_ -> return [] ) $ getDirectoryContents fp
forM fs $ \e -> case reverse e of
('l':'h':'.':r) -> flip iocatch (\_ -> return mempty) $ do
lib <- readHlFile (fp ++ "/" ++ e)
return (Map.singleton (libBaseName lib) [lib], Map.singleton (libHash lib) lib)
_ -> return mempty
splitOn' :: (a -> Bool) -> [a] -> [[a]]
splitOn' f xs = split xs
where split xs = case break f xs of
(chunk,[]) -> [chunk]
(chunk,_:rest) -> chunk : split rest
splitVersion :: String -> (String,Data.Version.Version)
splitVersion s = ans where
ans = case reverse (splitOn' ('-' ==) s) of
(vrs:bs@(_:_)) | Just vrs <- runReadP parseVersion vrs -> (intercalate "-" (reverse bs),vrs)
_ -> (s,Data.Version.Version [] [])
collectLibraries :: [String] -> IO ([Library],[Library])
collectLibraries libs = ans where
ans = do
(bynames,byhashes) <- fetchAllLibraries
let f (pn,vrs) = lname pn vrs `mplus` lhash pn vrs where
lname pn vrs = do
xs <- Map.lookup (packString pn) bynames
(x:_) <- return $ filter isGood xs
return x
isGood lib = versionBranch vrs `isPrefixOf` versionBranch (libVersion lib)
lhash pn vrs = do
[] <- return $ versionBranch vrs
Map.lookup pn byhashes'
byhashes' = Map.fromList [ (show x,y) | (x,y) <- Map.toList byhashes]
let es' = [ (x,f $ splitVersion x) | x <- libs ]
es = [ l | (_,Just l) <- es' ]
bad = [ n | (n,Nothing) <- es' ]
unless (null bad) $ do
putErrLn "Libraries not found:"
forM_ bad $ \b -> putErrLn (" " ++ b)
exitFailure
checkForModuleConficts es
let f lmap _ [] = return lmap
f lmap lset ((ei,l):ls)
| libHash l `Set.member` lset = f lmap lset ls
| otherwise = case Map.lookup (libBaseName l) lmap of
Nothing -> f (Map.insert (libBaseName l) (ei,l) lmap) (Set.insert (libHash l) lset) (ls ++ newdeps)
Just (ei',l') | libHash l == libHash l' -> f (Map.insert (libBaseName l) (ei || ei',l) lmap) lset ls
Just (_,l') -> putErrDie $ printf "Conflicting versions of library '%s' are required. [%s]\n" (libName l) (show (libHash l,libHash l'))
where newdeps = [ (False,fromMaybe (error $ printf "Dependency '%s' with hash '%s' needed by '%s' was not found" (unpackPS p) (show h) (libName l)) (Map.lookup h byhashes)) | let HoHeader { hohLibDeps = ldeps } = libHoHeader l , (p,h) <- ldeps ]
finalmap <- f Map.empty Set.empty [ (True,l) | l <- es ]
checkForModuleConficts [ l | (_,l) <- Map.elems finalmap ]
when verbose $ forM_ (Map.toList finalmap) $ \ (n,(e,l)) ->
printf "-- Base: %s Exported: %s Hash: %s Name: %s\n" (unpackPS n) (show e) (show $ libHash l) (libName l)
return ([ l | (True,l) <- Map.elems finalmap ],[ l | (False,l) <- Map.elems finalmap ])
checkForModuleConficts ms = do
let mbad = Map.toList $ Map.filter (\c -> case c of [_] -> False; _ -> True) $ Map.fromListWith (++) [ (m,[l]) | l <- ms, m <- fst $ libModules l]
forM_ mbad $ \ (m,l) -> putErrLn $ printf "Module '%s' is exported by multiple libraries: %s" (show m) (show $ map libName l)
unless (null mbad) $ putErrDie "There were conflicting modules!"
parseLibraryDescription :: Monad m => String -> m [(String,String)]
parseLibraryDescription fs = g [] (lines (f [] fs)) where
--f rs ('\n':s:xs) | isSpace s = f rs (dropWhile isSpace xs)
f rs ('-':'-':xs) = f rs (dropWhile (/= '\n') xs)
f rs ('{':'-':xs) = eatCom rs xs
f rs (x:xs) = f (x:rs) xs
f rs [] = reverse rs
eatCom rs ('\n':xs) = eatCom ('\n':rs) xs
eatCom rs ('-':'}':xs) = f rs xs
eatCom rs (_:xs) = eatCom rs xs
eatCom rs [] = f rs []
g rs (s:ss) | all isSpace s = g rs ss
g rs (s:s':ss) | all isSpace s' = g rs (s:ss)
g rs (s:(h:cl):ss) | isSpace h = g rs ((s ++ h:cl):ss)
g rs (r:ss) | (':':bd') <- bd = g ((map toLower $ condenseWhitespace nm,condenseWhitespace bd'):rs) ss
| otherwise = fail $ "could not find ':' marker: " ++ show (rs,r:ss) where
(nm,bd) = break (== ':') r
g rs [] = return rs
condenseWhitespace xs = reverse $ dropWhile isSpace (reverse (dropWhile isSpace (cw xs))) where
cw (x:y:zs) | isSpace x && isSpace y = cw (' ':zs)
cw (x:xs) = x:cw xs
cw [] = []
procCabal :: [(String,String)] -> LibDesc
procCabal xs = f xs mempty mempty where
f [] dlm dsm = LibDesc (combineAliases dlm) dsm
f ((map toLower -> x,y):rs) dlm dsm | x `Set.member` list_fields = f rs (Map.insert x (spit y) dlm) dsm
| otherwise = f rs dlm (Map.insert x y dsm)
spit = words . map (\c -> if c == ',' then ' ' else c)
procYaml :: YamlNode -> LibDesc
procYaml MkNode { n_elem = EMap ms } = f ms mempty mempty where
f [] dlm dsm = LibDesc (combineAliases dlm) dsm
f ((n_elem -> EStr (map toLower . unpackBuf -> x),y):rs) dlm dsm = if x `Set.member` list_fields then dlist y else dsing y where
dlist (n_elem -> EStr y) = f rs (Map.insert x [unpackBuf y] dlm) dsm
dlist (n_elem -> ESeq ss) = f rs (Map.insert x [ unpackBuf y | (n_elem -> EStr y) <- ss ] dlm) dsm
dlist _ = f rs dlm dsm
dsing (n_elem -> EStr y) = f rs dlm (Map.insert x (unpackBuf y) dsm)
dsing _ = f rs dlm dsm
f (_:xs) dlm dsm = f xs dlm dsm
procYaml _ = LibDesc mempty mempty
list_fields = Set.fromList $ [
"exposed-modules",
"include-dirs",
"extensions",
"options",
"c-sources",
"include-sources",
"build-depends"
] ++ map fst alias_fields
++ map snd alias_fields
alias_fields = [
-- ("other-modules","hidden-modules"),
("exported-modules","exposed-modules"),
("hs-source-dir","hs-source-dirs")
]
combineAliases mp = f alias_fields mp where
f [] mp = mp
f ((x,y):rs) mp = case Map.lookup x mp of
Nothing -> f rs mp
Just ys -> f rs $ Map.delete x $ Map.insertWith (++) y ys mp
data LibDesc = LibDesc (Map.Map String [String]) (Map.Map String String)
readDescFile :: FilePath -> IO LibDesc
readDescFile fp = do
wdump FD.Progress $ putErrLn $ "Reading: " ++ show fp
let doYaml opt = do
lbs <- LBS.readFile fp
dt <- preprocess opt fp lbs
desc <- iocatch (parseYamlBytes $ BS.concat (LBS.toChunks dt))
(\e -> putErrDie $ "Error parsing desc file '" ++ fp ++ "'\n" ++ show e)
when verbose2 $ do
yaml <- emitYaml desc
putStrLn yaml
return $ procYaml desc
doCabal = do
fc <- readFile fp
case parseLibraryDescription fc of
Left err -> fail $ "Error reading library description file: " ++ show fp ++ " " ++ err
Right ps -> return $ procCabal ps
case FP.splitExtension fp of
(_,".cabal") -> doCabal
(_,".yaml") -> doYaml options
(FP.takeExtension -> ".yaml",".m4") -> doYaml options { optFOptsSet = FO.M4 `Set.insert` optFOptsSet options }
_ -> putErrDie $ "Do not recoginize description file type: " ++ fp
| m-alvarez/jhc | src/Ho/Library.hs | mit | 11,496 | 0 | 22 | 3,102 | 4,342 | 2,231 | 2,111 | -1 | -1 |
{- | This module defines a collection of combinators for looping over
nonterminals and metavariables, as well as for assembling output
for Coq. -}
module CoqLNOutputCombinators where
import Control.Monad.State
import Text.Printf ( printf )
import AST
import ASTAnalysis
import ComputationMonad
import CoqLNOutputCommon
import MyLibrary ( sepStrings )
{- ----------------------------------------------------------------------- -}
{- * Generating text for lemmas -}
{- Flag for Coq's sorts. -}
data Sort = Prop | Set
instance Show Sort where
show Prop = "Prop"
show Set = "Set"
{- Flag indicating what sort of @Resolve@ hint to generate. -}
data ResolveHint = NoResolve | Resolve | Immediate
{- Flag indicating what sort of @Rewrite@ hint to generate. -}
data RewriteHint = NoRewrite | Rewrite
{- Flag indicating whether to generate @hide@ directives for @coqdoc@. -}
data DocHide = NoHide | Hide
{- Basic combinator for generating the text of a lemma declaration. -}
lemmaText :: ResolveHint -- Resolve hint?
-> RewriteHint -- Rewrite hint?
-> DocHide -- Hide documentation?
-> [String] -- Hint databases.
-> String -- Name of the lemma
-> String -- Statment of the lemma
-> String -- Proof of the lemma
-> M String
lemmaText resolve rewrite hide dbs name stmt proof =
do { (flags, _) <- get
; return $ printf "%s\
\Lemma %s :\n\
\%s.\n\
\%s\
\%s%s%s%s"
(case hide of
NoHide -> ""
Hide -> "(* begin hide *)\n\n")
name
stmt
(if CoqAdmitted `elem` flags
then "Proof. Admitted.\n\n"
else printf "Proof.\n\
\%s\n\
\Qed.\n\
\\n"
proof)
(case resolve of
NoResolve -> ""
Resolve -> printf "Hint Resolve %s : %s.\n" name (sepStrings " " dbs)
Immediate -> printf "Hint Immediate %s : %s.\n" name (sepStrings " " dbs))
(case rewrite of
NoRewrite -> ""
Rewrite -> printf "Hint Rewrite %s using solve [auto] : %s.\n" name (sepStrings " " dbs))
(case (resolve, rewrite) of
(NoResolve, NoRewrite) -> ""
_ -> "\n")
(case hide of
NoHide -> ""
Hide -> "(* end hide *)\n\n")
}
{- Basic combinator for generating the text of a lemma declaration. -}
lemmaText2 :: ResolveHint -- Resolve hint?
-> RewriteHint -- Rewrite hint?
-> DocHide -- Hide documentation?
-> [String] -- Hint databases.
-> [[String]] -- Names for the parts.
-> [[(String, String)]] -- Statments and proofs for the parts.
-> M String
lemmaText2 resolve rewrite hide dbs names gens =
do { strs <- mapM (\(name, (stmt, pf)) ->
lemmaText resolve rewrite hide dbs name stmt pf)
(zip (concat names) (concat gens))
; return $ concat strs
}
{- Combinator used for generating the text of a lemma proved by mutual
induction/recursion. -}
mutualLemmaText :: ResolveHint -- Resolve hint?
-> RewriteHint -- Rewrite hint?
-> DocHide -- Hide documentation?
-> [String] -- Hint databases.
-> Sort -- Sort
-> [String] -- Names for the parts.
-> [String] -- Statments for the parts.
-> String -- Proof of the lemma.
-> M String
mutualLemmaText resolve rewrite hide dbs sort names stmts proof =
do { let mut_name = sepStrings "_" names ++ "_mutual"
mut_stmts = combine sort $ map wrap stmts
cproof = printf "pose proof %s as H; intuition eauto." mut_name
; lemma <- lemmaText NoResolve NoRewrite Hide dbs mut_name mut_stmts proof
; corollaries <- mapM (\(name, stmt) ->
lemmaText resolve rewrite hide dbs name stmt cproof)
(zip names stmts)
; return $ lemma ++ concat corollaries
}
where
combine Set = sepStrings " *\n"
combine Prop = sepStrings " /\\\n"
wrap str = printf "(%s)" str
{- Combinator used for generating the text of a lemma proved by mutual
induction/recursion. -}
mutualLemmaText2 :: ResolveHint -- Resolve hint?
-> RewriteHint -- Rewrite hint?
-> DocHide -- Hide documentation?
-> [String] -- Hint databases.
-> Sort -- Sort
-> [[String]] -- Names for the parts.
-> [[String]] -- Statments for the parts.
-> [String] -- Proof of the lemma.
-> M String
mutualLemmaText2 resolve rewrite hide dbs sort names stmts proof =
do { strs <- mapM (\(name, stmt, pf) ->
mutualLemmaText resolve rewrite hide dbs sort name stmt pf)
(zip3 names stmts proof)
; return $ concat strs
}
{- Combinator used to generate the application of the mutual
induction/recursion principle. -}
mutPfStart :: Sort
-> [Name] -- Names of types.
-> String
mutPfStart s ns = f (case s of { Prop -> mutIndName ; Set -> mutRecName })
where
f g = printf "%s %s;\n" applyMutInd (g ns)
{- ----------------------------------------------------------------------- -}
{- * Looping patterns -}
{- Combinator used to loop over a set of @nt1s@. -}
processNt1 :: ASTAnalysis
-> [NtRoot]
-> (ASTAnalysis -> NtRoot -> M a)
-> M [a]
processNt1 aa nt1s f = mapM (local . f aa) nt1s
{- Combinator used to loop over @(nt1, nt2, mv2)@ triples. -}
processNt1Nt2Mv2 :: ASTAnalysis
-> [NtRoot]
-> (ASTAnalysis -> NtRoot -> NtRoot -> MvRoot -> M a)
-> M [[a]]
processNt1Nt2Mv2 aa nt1s f =
sequence $
do { nt2 <- filter (canBindOver aa (head nt1s)) (ntRoots aa)
; mv2 <- mvsOfNt aa nt2
; return $ sequence $ do { nt1 <- nt1s
; return (local $ f aa nt1 nt2 mv2)
}
}
{- Combinator used to loop over @(nt1, nt2, mv2, nt2', mv2')@ tuples. -}
processNt1Nt2Mv2' :: ASTAnalysis
-> [NtRoot]
-> (ASTAnalysis -> NtRoot -> NtRoot -> MvRoot -> NtRoot -> MvRoot -> M a)
-> M [[a]]
processNt1Nt2Mv2' aa nt1s f =
sequence $
do { nt2 <- filter (canBindOver aa (head nt1s)) (ntRoots aa)
; mv2 <- mvsOfNt aa nt2
; nt2' <- filter (canBindOver aa (head nt1s)) (ntRoots aa)
; mv2' <- mvsOfNt aa nt2'
; return $ sequence $ do { nt1 <- nt1s
; return (local $ f aa nt1 nt2 mv2 nt2' mv2')
}
}
| plclub/lngen | src/CoqLNOutputCombinators.hs | mit | 7,130 | 0 | 15 | 2,619 | 1,493 | 800 | 693 | 127 | 8 |
-- Copyright © 2013 Bart Massey
-- [This program is licensed under the "MIT License"]
-- Please see the file COPYING in the source
-- distribution of this software for license terms.
-- Select columns and/or rows from a CSV file
import Data.List (intersect)
import System.Console.ParseArgs
import System.IO
import Text.Parsec
import Text.Parsec.String (Parser)
import Text.SSV
parseNumber :: Parser Int
parseNumber = fmap read (many1 digit)
parseRange :: Parser [Int]
parseRange = do
maybeStart <- optionMaybe parseNumber
let start = case maybeStart of
Nothing -> 1
Just n -> n
_ <- char '-'
maybeEnd <- optionMaybe parseNumber
case maybeEnd of
Nothing -> return [start - 1 ..]
Just end -> return [start - 1 .. end - 1]
parseRangeSpec :: Parser [Int]
parseRangeSpec = try parseRange <|> fmap ((:[]) . subtract 1) parseNumber
merge :: [Int] -> [Int] -> [Int]
merge xs [] = xs
merge [] ys = ys
merge xl@(x : xs) yl@(y : ys)
| x <= y = x : merge xs yl
| otherwise = y : merge xl ys
parseSpec :: Parser [Int]
parseSpec = do
ranges <- sepBy1 parseRangeSpec (char ',')
return $ foldr1 merge ranges
readSpec :: String -> String -> [Int]
readSpec spec input =
case " \t\n" `intersect` input of
"" ->
case parse parseSpec spec input of
Left err -> error $ show err
Right val -> val
_ -> error $ "whitespace not allowed in " ++ spec
data ArgIndex = ArgCols | ArgRows | ArgSource deriving (Eq, Ord, Show)
argd :: [Arg ArgIndex]
argd = [
Arg {
argIndex = ArgCols,
argAbbr = Just 'c',
argName = Just "cols",
argData = argDataOptional "column-spec" ArgtypeString,
argDesc = "Expression describing columns to select." },
Arg {
argIndex = ArgRows,
argAbbr = Just 'r',
argName = Just "rows",
argData = argDataOptional "row-spec" ArgtypeString,
argDesc = "Expression describing rows to select." },
Arg {
argIndex = ArgSource,
argAbbr = Nothing,
argName = Nothing,
argData = argDataOptional "csv-file" ArgtypeString,
argDesc = "CSV file to process." } ]
select :: Int -> [Int] -> [a] -> [a]
select _ [] _ = []
select _ _ [] = []
select i (j : js) (s : ss) =
case compare i j of
GT -> select i js (s : ss)
EQ -> s : select (i + 1) js ss
LT -> select (i + 1) (j : js) ss
main :: IO ()
main = do
argv <- parseArgsIO ArgsComplete argd
let colspec = case getArg argv ArgCols of
Nothing -> [0..]
Just cs -> readSpec "column-spec" cs
let rowspec = case getArg argv ArgRows of
Nothing -> [0..]
Just rs -> readSpec "row-spec" rs
h <- getArgStdio argv ArgSource ReadMode
text <- hGetContents h
let csv = readCSV text
let rows = select 0 rowspec csv
let fields = map (select 0 colspec) rows
hPutCSV stdout fields
| BartMassey/csv-cut | csv-cut.hs | mit | 2,802 | 0 | 13 | 695 | 1,022 | 526 | 496 | 83 | 3 |
module PWMModelAux where
import qualified Data.Map.Strict as M
import qualified Data.Text as T
import MlgscTypes
-- some functions useful for building clade models from alignents
-- Converts a residue probability (estimated by its relative frequency) to a
-- rounded, scaled, logarithm.
probToScore :: Double -> Double -> Int
probToScore scale prob = round (scale * (logBase 10 prob))
-- Takes a Column (a vertical slice through an alignment, IOW the residues of
-- each sequence at a given single position) and returns a map of absolute
-- frequency (i.e., counts) of each residue.
colToCountsMap :: Column -> M.Map Residue Int
colToCountsMap col = M.fromListWith (+) [(res, 1) | res <- (T.unpack col)]
-- Computes a residue -> counts map for a column, weighted by sequence weight,
-- e.g. if a sequence has 'A' at that position, and the sequence's weight is 2,
-- then for that sequence 'A' is added twice to the total count of 'A'.
weightedColToCountsMap :: [Int] -> Column -> M.Map Residue Int
weightedColToCountsMap weights col =
M.fromListWith (+) $ zip (T.unpack col) weights
-- Scales the absolute frequency into a relative frequency, by dividing the
-- (possibly weighted) counts by the (posibly weighted) number of sequences
countsMapToRelFreqMap :: Double -> M.Map Residue Int -> M.Map Residue Double
countsMapToRelFreqMap size = fmap (\n -> (fromIntegral n) / size)
-- Transforms a Residue -> Relative frequency map into a Residue -> Score map,
-- where the score is a rounded, scaled logarithm of the relative frequency.
freqMapToScoreMap :: Double -> M.Map Residue Double -> M.Map Residue Int
freqMapToScoreMap scale = fmap $ probToScore scale
| tjunier/mlgsc | src/PWMModelAux.hs | mit | 1,676 | 0 | 11 | 284 | 291 | 160 | 131 | 15 | 1 |
module Spear.Render.StaticModel
(
-- * Data types
StaticModelResource
, StaticModelRenderer
-- * Construction and destruction
, staticModelResource
, staticModelRenderer
-- * Manipulation
, box
, modelRes
-- * Rendering
, bind
, render
-- * Collision
, mkColsFromStatic
)
where
import Spear.Assets.Model
import Spear.Game
import Spear.GL
import Spear.Math.AABB
import Spear.Math.Collision
import Spear.Math.Matrix4 (Matrix4)
import Spear.Math.Vector
import Spear.Render.Material
import Spear.Render.Model
import Spear.Render.Program
import qualified Data.Vector as V
import Unsafe.Coerce (unsafeCoerce)
data StaticModelResource = StaticModelResource
{ vao :: VAO
, nVertices :: Int
, material :: Material
, texture :: Texture
, boxes :: V.Vector Box
, rkey :: Resource
}
instance Eq StaticModelResource where
m1 == m2 = vao m1 == vao m2
instance Ord StaticModelResource where
m1 < m2 = vao m1 < vao m2
instance ResourceClass StaticModelResource where
getResource = rkey
data StaticModelRenderer = StaticModelRenderer { model :: StaticModelResource }
instance Eq StaticModelRenderer where
m1 == m2 = model m1 == model m2
instance Ord StaticModelRenderer where
m1 < m2 = model m1 < model m2
-- | Create a model resource from the given model.
staticModelResource :: StaticProgramChannels
-> Material
-> Texture
-> Model
-> Game s StaticModelResource
staticModelResource (StaticProgramChannels vertChan normChan texChan) material texture model = do
RenderModel elements _ numVertices <- gameIO . renderModelFromModel $ model
elementBuf <- newBuffer
vao <- newVAO
boxes <- gameIO $ modelBoxes model
gameIO $ do
let elemSize = 32
elemSize' = fromIntegral elemSize
n = numVertices
bindVAO vao
bindBuffer ArrayBuffer elementBuf
bufferData' ArrayBuffer (fromIntegral $ elemSize*n) elements StaticDraw
attribVAOPointer vertChan 3 gl_FLOAT False elemSize' 0
attribVAOPointer normChan 3 gl_FLOAT False elemSize' 12
attribVAOPointer texChan 2 gl_FLOAT False elemSize' 24
enableVAOAttrib vertChan
enableVAOAttrib normChan
enableVAOAttrib texChan
rkey <- register $ do
putStrLn "Releasing static model resource"
clean vao
clean elementBuf
return $ StaticModelResource
vao (unsafeCoerce numVertices) material texture boxes rkey
-- | Create a renderer from the given model resource.
staticModelRenderer :: StaticModelResource -> StaticModelRenderer
staticModelRenderer = StaticModelRenderer
-- | Get the model's ith bounding box.
box :: Int -> StaticModelResource -> Box
box i model = boxes model V.! i
-- | Get the renderer's model resource.
modelRes :: StaticModelRenderer -> StaticModelResource
modelRes = model
-- | Bind the given renderer to prepare it for rendering.
bind :: StaticProgramUniforms -> StaticModelRenderer -> IO ()
bind (StaticProgramUniforms kaLoc kdLoc ksLoc shiLoc texLoc _ _ _) (StaticModelRenderer model) =
let (Material _ ka kd ks shi) = material model
in do
bindVAO . vao $ model
bindTexture $ texture model
activeTexture $= gl_TEXTURE0
glUniform1i texLoc 0
-- | Render the given renderer.
render :: StaticProgramUniforms -> StaticModelRenderer -> IO ()
render uniforms (StaticModelRenderer model) =
let (Material _ ka kd ks shi) = material model
in do
uniform (kaLoc uniforms) ka
uniform (kdLoc uniforms) kd
uniform (ksLoc uniforms) ks
glUniform1f (shiLoc uniforms) $ unsafeCoerce shi
drawArrays gl_TRIANGLES 0 $ nVertices model
-- | Compute AABB collisioners in view space from the given model.
mkColsFromStatic
:: Matrix4 -- ^ Modelview matrix
-> StaticModelResource
-> [Collisioner2]
mkColsFromStatic modelview modelRes = mkCols modelview (box 0 modelRes)
| jeannekamikaze/Spear | Spear/Render/StaticModel.hs | mit | 4,210 | 0 | 13 | 1,141 | 968 | 485 | 483 | 98 | 1 |
{-# LANGUAGE OverloadedStrings #-}
import Control.Applicative
import Data.Aeson
import Data.Attoparsec.Number
import Data.Char
import qualified Data.HashMap.Strict as HMS
import Data.Maybe
import qualified Data.Text as DT
import qualified Data.Vector as Vec
-- import Debug.Trace
import System.IO
import Util.Json
data CharPart = CharPart
{ cpCodePoint :: !Int
, _cpVariantNum :: !Int
}
deriving (Show)
fromInt :: Value -> Int
fromInt (Number (I x)) = fromIntegral x
fromInt (String x) = read $ DT.unpack x
fromInt x = error $ "fromNumber: " ++ show x
fromArr :: Value -> Array
fromArr (Array x) = x
fromArr x = error $ "fromArr: " ++ show x
fromObj :: Value -> Object
fromObj (Object x) = x
fromObj x = error $ "fromObj: " ++ show x
grabInfo :: HMS.HashMap DT.Text Value -> Maybe (CharPart, [CharPart])
grabInfo j =
fmap (flip (,) . catMaybes . map (grabPart . fromObj) . Vec.toList .
fromArr . fromJust $ HMS.lookup "parts" j) $ grabPart j
grabPart :: HMS.HashMap DT.Text Value -> Maybe CharPart
grabPart j =
killVar $
case fromInt <$> HMS.lookup "uni" j of
Just i ->
Just . CharPart i . maybe 0 fromInt $ HMS.lookup "variant" j
_ -> Nothing
where
killVar x@(Just (CharPart _ 0)) = x
killVar _ = Nothing
showLine :: (CharPart, [CharPart]) -> String
showLine (cp, cps) = showCp cp : map showCp cps
showCp :: CharPart -> Char
showCp = chr . cpCodePoint
main :: IO ()
main = do
ls <- catMaybes . map (grabInfo . parseJson) <$> hReadLines stdin
mapM_ putStrLn $ map showLine ls
| dancor/melang | src/ProcHanziJson.hs | mit | 1,557 | 0 | 15 | 337 | 597 | 309 | 288 | 50 | 3 |
module Main
( main
) where
import Data.Foldable (maximum)
import Data.Ix (inRange)
import qualified Data.Map.Strict as M
import Linear (V2 (..), _x, _y)
import Relude.Extra.Lens ((^.))
import qualified Relude.Unsafe as U
data Seat = Empty | Occupied deriving stock Eq
type Point = V2 Int
input :: IO (Map Point Seat)
input = do
raw <- fmap toString . lines <$> readFileText "input.txt"
pure $ fromList
[ (V2 x y, s)
| (x, line) <- zip [0 ..] raw
, (y, c ) <- zip [0 ..] line
, s <- [ Empty | c == 'L' ]
]
fixed :: Eq a => (a -> a) -> a -> a
fixed f x = let y = f x in if x == y then x else fixed f y
count :: Map Point Seat -> Int
count = M.foldr' ((+) . bool 0 1 . (== Occupied)) 0
neighbors :: [Point]
neighbors = [ V2 x y | x <- [-1 .. 1], y <- bool [-1, 1] [-1 .. 1] (x /= 0) ]
rule :: Int -> (Point -> [Seat]) -> Point -> Seat -> Seat
rule n see xy p | p == Occupied && n <= ox xy = Empty
| p == Empty && notElem Occupied (see xy) = Occupied
| otherwise = p
where ox = length . filter (== Occupied) . see
step1 :: Map Point Seat -> Map Point Seat
step1 l = M.mapWithKey (rule 4 adj) l
where adj xy = mapMaybe ((l M.!?) . (+ xy)) neighbors
part1 :: Map Point Seat -> Int
part1 = count . fixed step1
step2 :: Map Point Seat -> Map Point Seat
step2 l = M.mapWithKey (rule 5 see) l
where
see xy = mapMaybe ((l M.!?) <=< from xy) neighbors
from xy n = find (`M.member` l) . takeWhile aSeat . U.tail $ iterate (+ n) xy
aSeat = inRange (V2 0 0, V2 maxX maxY)
maxX = maximum . fmap (^. _x) $ M.keys l
maxY = maximum . fmap (^. _y) $ M.keys l
part2 :: Map Point Seat -> Int
part2 = count . fixed step2
main :: IO ()
main = (bitraverse_ print print . (part1 &&& part2)) =<< input
| genos/online_problems | advent_of_code_2020/day11/Main.hs | mit | 1,887 | 0 | 14 | 586 | 906 | 481 | 425 | -1 | -1 |
module BACnet.Prim
(
CharacterString(..),
OctetString(..),
BitString,
bitStringUnusedBits,
bitStringBytes,
bitStringLength,
bitString,
bitStringEmpty,
testBit,
Enumerated(..),
Date(..),
Time(..),
ObjectIdentifier(..),
objectIdentifier,
getObjectType,
getInstanceNumber,
Any(..)
) where
import Data.Word (Word8, Word16, Word32, Word)
import Data.Int (Int32)
import Data.Bits (shiftR, shiftL, (.&.))
import Control.Applicative ((<$>), (<*>))
import qualified Data.Bits as B
newtype CharacterString = CharacterString { characterStringValue :: String }
deriving (Eq, Show)
newtype OctetString = OctetString { octetStringBytes :: [Word8] }
deriving (Eq, Show)
data BitString = BitString { bitStringUnusedBits :: Word8, bitStringBytes :: [Word8] }
deriving (Eq, Show)
bitStringEmpty :: BitString
bitStringEmpty = BitString 0 []
bitString :: Word8 -> [Word8] -> Maybe BitString
bitString n [] = if (n /= 0) then Nothing else Just bitStringEmpty
bitString n bs@(_:_) = if (n >= 8) then Nothing else Just $ BitString n bs
bitStringLength :: BitString -> Int
bitStringLength bs = 1 + length (bitStringBytes bs)
-- | The function @testBit b n@ returns true if the nth bit is set. Counting
-- starts at 0 at the left most bit of the left most byte of 'getBytes'
testBit :: BitString -> Word -> Bool
testBit (BitString unusedBits bs) = testBit' unusedBits bs
testBit' :: Word8 -> [Word8] -> Word -> Bool
testBit' _ [] _ = error "empty list of bytes"
testBit' u [b] n | n > fromIntegral (7 - u) = error "index out of bounds"
| otherwise = B.testBit b (fromIntegral $ 7 - n)
testBit' u (b:bs) n | n > 7 = testBit' u bs (n - 8)
| otherwise = B.testBit b (fromIntegral $ 7 - n)
newtype Enumerated = Enumerated { getEnumValue :: Word } deriving (Eq, Show)
data Date = Date
{
getYear :: Word8,
getMonth :: Word8,
getDayOfMonth :: Word8,
getDayOfWeek :: Word8
} deriving (Show, Eq)
data Time = Time
{
getHour :: Word8,
getMinute :: Word8,
getSecond :: Word8,
getHundredth :: Word8
} deriving (Show, Eq)
newtype ObjectIdentifier = ObjectIdentifier { objectIdentifierValue :: Word32 }
deriving (Show, Eq)
objectIdentifier :: Word16 -> Word32 -> Maybe ObjectIdentifier
objectIdentifier ot inum = ObjectIdentifier <$> rawValue
where rawValue = (+) <$> inum' <*> ot'
inum'
| inum > 0x3FFFFF = Nothing
| otherwise = Just inum
ot'
| ot > 0x3FF = Nothing
| otherwise = Just $ shiftL (fromIntegral ot) 22
getObjectType :: ObjectIdentifier -> Word16
getObjectType = fromIntegral . (.&. 0x3F) . flip shiftR 22 . objectIdentifierValue
getInstanceNumber :: ObjectIdentifier -> Word32
getInstanceNumber = (.&. 0x003FFFFF) . objectIdentifierValue
data Any =
NullAP
| BooleanAP Bool
| UnsignedAP Word32
| SignedAP Int32
| RealAP Float
| DoubleAP Double
| OctetStringAP [Word8]
| CharacterStringAP String
| BitStringAP BitString
| EnumeratedAP Enumerated
| DateAP Date
| TimeAP Time
| ObjectIdentifierAP ObjectIdentifier deriving (Eq, Show)
| michaelgwelch/bacnet | src/BACnet/Prim.hs | mit | 3,186 | 0 | 11 | 730 | 980 | 557 | 423 | 87 | 3 |
{- Catalan Numbers in Haskell, with some help from
- http://rosettacode.org/wiki/Catalan_numbers#Haskell
-}
import Test.QuickCheck (quickCheck)
-- helpers
binom :: Integer -> Integer -> Integer
binom n k = product [k + 1 .. n] `div` product [1 .. n - k]
factorial :: Integer -> Integer
factorial = product . enumFromTo 2
pairs :: [a] -> [(a, a)]
pairs xs = [ (x, y) | x <- xs, y <- xs ]
-- Catalan definitions
cat0 :: [Integer]
cat0 = map (\n -> product [n + 2 .. 2 * n] `div` product [2 .. n]) [0 ..]
cat1 :: [Integer]
cat1 = 1 : map c [1 ..]
where c n = sum $ zipWith (*) (reverse (take n cat1)) cat1
cat2 :: [Integer]
cat2 = scanl (\c n -> c * 2 * (2 * n - 1) `div` (n + 1)) 1 [1 ..]
cat3 :: [Integer]
cat3 = map c [0 ..]
where
c n | n <= 0 = 1
| otherwise = binom (2 * n) n - binom (2 * n) (n + 1)
cat4 :: [Integer]
cat4 = map c [0 ..]
where c n = sum (map (\k -> binom n k ^ 2) [0 .. n]) `div` (n + 1)
cat5 :: [Integer]
cat5 = map (\n -> binom (2 * n) n `div` (n + 1)) [0 ..]
cat6 :: [Integer]
cat6 = map c [0 ..]
where c n = factorial (2 * n) `div` (factorial (n + 1) * factorial n)
-- Check that these look the same
prop_equal :: Int -> Bool
prop_equal n = all p $ pairs cats
where
cats = [cat0, cat1, cat2, cat3, cat4, cat5, cat6]
p (xs, ys) = xs !! n' == ys !! n'
n' = n `mod` 1000
main :: IO ()
main = quickCheck prop_equal
| genos/Programming | workbench/catalan.hs | mit | 1,373 | 0 | 14 | 347 | 734 | 408 | 326 | 33 | 1 |
-- Inverses Module
--
-- This stores all the fundamental things for manipulating matrices
-- This includes things like determinants and inverse matrices
--
-- Jacob Buete 2014
module Inverses (
det_two, -- :: Matrix -> Float
determinant, -- :: Matrix -> Float
cofactor_matrix, -- :: Matrix -> Matrix
adjoint_matrix, -- :: Matrix -> Matrix
inverse_matrix, -- :: Matrix -> Matrix
) where
import Matrices
import Algebra
remove_at :: Int -> [a] -> [a]
remove_at k list = case list of
[] -> error "List not that long"
x:xs
| k == 1 -> xs
| otherwise -> x:remove_at (k-1) xs
find_cofactor :: Int -> Int -> Matrix -> Matrix
find_cofactor n m matrix = map (remove_at m) (remove_at n matrix)
det_two :: Matrix -> Float
det_two matrix = (head top)*(last bottom) - (head bottom)*(last top)
where
top = head matrix
bottom = last matrix
element_at :: Int -> Row -> Float
element_at k row = case row of
[] -> error "Nope"
x:xs
| k == 1 -> x
| otherwise -> element_at (k-1) xs
determinant :: Matrix -> Float
determinant matrix
| length matrix == 2 = det_two matrix
| is_singleton matrix = head (head matrix)
| otherwise = find_det (length matrix) matrix
where
det_element :: Int -> Matrix -> Float
det_element m matrix
| m`mod`2 == 0 = (-element_at m (head matrix)) * determinant (find_cofactor 1 m matrix)
| otherwise = (element_at m (head matrix)) * determinant (find_cofactor 1 m matrix)
find_det :: Int -> Matrix -> Float
find_det m matrix
| m == 0 = 0
| otherwise = (det_element m matrix) + find_det (m-1) matrix
cofactor_matrix :: Matrix -> Matrix
cofactor_matrix matrix = cofactor_aux (length matrix) (length (head matrix))
where
cofactor_row :: Int -> Int -> Row
cofactor_row n m
| m == 0 = []
| (m+n) `mod` 2 == 1 = cofactor_row n (m-1) ++ [-determinant (find_cofactor n m matrix)]
| otherwise = cofactor_row n (m-1) ++ [determinant (find_cofactor n m matrix)]
cofactor_aux :: Int -> Int -> Matrix
cofactor_aux n m
| n == 0 = []
| otherwise = cofactor_aux (n-1) m ++ [cofactor_row n m]
adjoint_matrix :: Matrix -> Matrix
adjoint_matrix matrix = transpose_matrix (cofactor_matrix matrix)
inverse_matrix :: Matrix -> Matrix
inverse_matrix matrix
| is_singleton matrix = [[(1/head (head matrix))]]
| otherwise = scale_matrix (1/(determinant matrix)) (adjoint_matrix matrix)
| JBuete/Haskell-Matrices | Inverses.hs | mit | 3,171 | 2 | 13 | 1,294 | 938 | 471 | 467 | 56 | 2 |
module Feature.BinaryJwtSecretSpec where
-- {{{ Imports
import Network.Wai (Application)
import Network.HTTP.Types
import Test.Hspec
import Test.Hspec.Wai
import Protolude
import SpecHelper
-- }}}
spec :: SpecWith ((), Application)
spec = describe "server started with binary JWT secret" $
-- this test will stop working 9999999999s after the UNIX EPOCH
it "succeeds with jwt token encoded with a binary secret" $ do
let auth = authHeaderJWT "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjk5OTk5OTk5OTksInJvbGUiOiJwb3N0Z3Jlc3RfdGVzdF9hdXRob3IiLCJpZCI6Impkb2UifQ.Dpss-QoLYjec5OTsOaAc3FNVsSjA89wACoV-0ra3ClA"
request methodGet "/authors_only" [auth] ""
`shouldRespondWith` 200
| steve-chavez/postgrest | test/Feature/BinaryJwtSecretSpec.hs | mit | 699 | 0 | 11 | 94 | 110 | 62 | 48 | 13 | 1 |
-- ----------------------------------------------------------------------------
{- |
Module : Holumbus.Data.Crunch
Copyright : Copyright (C) 2008 Timo B. Huebel
License : MIT
Maintainer : Timo B. Huebel ([email protected])
Stability : experimental
Portability: portable
Version : 0.1
This module provides compression for streams of 32-bit words. Because of
some internal restriction in GHC, which makes all fixed integer size equal
in terms of bit-width, the algorithm tries to crunch as much numbers as
possible into a single 64-bit word.
Based on the Simple9 encoding scheme from this article:
* Vo N. Anh, Alstair Moffat,
\"/Inverted Index Compression Using Word-Aligned Binary Codes/\",
Information Retrieval, 8 (1), 2005, pages 151-166
-}
-- ----------------------------------------------------------------------------
{-# OPTIONS -fno-warn-type-defaults #-}
module Holumbus.Data.Crunch
(
-- * Compression
crunch8
, crunch16
, crunch32
, crunch64
-- * Decompression
, decrunch8
, decrunch16
, decrunch32
, decrunch64
)
where
import Data.Bits
import Data.Word
data Width = W01 | W02 | W03 | W04 | W05 | W06 | W07 | W08 | W10 | W12 | W15 | W20 | W30 | W60
deriving (Show, Eq, Enum)
-- | Increase performance by avoiding the calculation of maximum values.
value :: Width -> Word64
value W01 = (2 ^ 1) - 1
value W02 = (2 ^ 2) - 1
value W03 = (2 ^ 3) - 1
value W04 = (2 ^ 4) - 1
value W05 = (2 ^ 5) - 1
value W06 = (2 ^ 6) - 1
value W07 = (2 ^ 7) - 1
value W08 = (2 ^ 8) - 1
value W10 = (2 ^ 10) - 1
value W12 = (2 ^ 12) - 1
value W15 = (2 ^ 15) - 1
value W20 = (2 ^ 20) - 1
value W30 = (2 ^ 30) - 1
value W60 = (2 ^ 60) - 1
-- | Increase performance by avoiding the calculation of counts.
count :: Width -> Int
count W01 = 60
count W02 = 30
count W03 = 20
count W04 = 15
count W05 = 12
count W06 = 10
count W07 = 8
count W08 = 7
count W10 = 6
count W12 = 5
count W15 = 4
count W20 = 3
count W30 = 2
count W60 = 1
width :: Width -> Int
width W01 = 1
width W02 = 2
width W03 = 3
width W04 = 4
width W05 = 5
width W06 = 6
width W07 = 7
width W08 = 8
width W10 = 10
width W12 = 12
width W15 = 15
width W20 = 20
width W30 = 30
width W60 = 60
-- | Crunch some values by encoding several values into one 'Word64'. The values may not exceed
-- the upper limit of @(2 ^ 60) - 1@. This precondition is not checked! The compression works
-- best on small values, therefore a difference encoding (like the one in
-- "Holumbus.Data.DiffList") prior to compression pays off well.
crunch64 :: [Word64] -> [Word64]
crunch64 [] = []
crunch64 s = crunch' s (count W01) W01 []
-- | Crunch a non empty list. This precondition is not checked!
crunch' :: [Word64] -> Int -> Width -> [Word64] -> [Word64]
crunch' [] 0 m r = [encode m r]
crunch' [] _ m r = crunch' r (count (succ m)) (succ m) []
crunch' s 0 m r = (encode m r):(crunch' s (count W01) W01 [])
crunch' s@(x:xs) n m r = if x <= value m then crunch' xs (n - 1) m (r ++ [x])
else crunch' (r ++ s) (count (succ m)) (succ m) []
-- | Encode some numbers with a given width. The number of elements in the list may not exceed
-- the amount of numbers allowed for this width and the numbers in the list may not exceed the
-- upper bound for this width. These preconditions are not checked!
encode :: Width -> [Word64] -> Word64
encode w [] = rotateR (fromIntegral (fromEnum w)) (64 - (width w * count w))
encode w (x:xs) = rotateR (encode w xs .|. fromIntegral x) (width w)
-- | Decrunch a list of crunched values. No checking for properly encoded values is done, weird
-- results have to be expected if calling this function on a list of arbitrary values.
decrunch64 :: [Word64] -> [Word64]
decrunch64 [] = []
decrunch64 (x:xs) = (decode (width w) (count w) (value w) (rotateL x (width w))) ++ (decrunch64 xs)
where
w = toEnum $ fromIntegral (x .&. 15) -- Extract the 4 selector bits.
-- Decode some numbers with a given width.
decode :: Int -> Int -> Word64 -> Word64 -> [Word64]
decode _ 0 _ _ = []
decode w n m x = (x .&. m):(decode w (n - 1) m (rotateL x w))
-- | Crunching 'Word8' values, defined in terms of 'crunch64'.
crunch8 :: [Word8] -> [Word64]
crunch8 = crunch64 . (map fromIntegral)
-- | Crunching 'Word16' values, defined in terms of 'crunch64'.
crunch16 :: [Word16] -> [Word64]
crunch16 = crunch64 . (map fromIntegral)
-- | Crunching 'Word32' values, defined in terms of 'crunch64'.
crunch32 :: [Word32] -> [Word64]
crunch32 = crunch64 . (map fromIntegral)
-- | Decrunching to 'Word8' values, defined in terms of 'decrunch64'.
decrunch8 :: [Word64] -> [Word8]
decrunch8 = (map fromIntegral) . decrunch64
-- | Decrunching to 'Word16' values, defined in terms of 'decrunch64'.
decrunch16 :: [Word64] -> [Word16]
decrunch16 = (map fromIntegral) . decrunch64
-- | Decrunching to 'Word32' values, defined in terms of 'decrunch64'.
decrunch32 :: [Word64] -> [Word32]
decrunch32 = (map fromIntegral) . decrunch64
| ichistmeinname/holumbus | src/Holumbus/Data/Crunch.hs | mit | 5,072 | 0 | 11 | 1,148 | 1,442 | 778 | 664 | 91 | 2 |
{-# LANGUAGE ApplicativeDo #-}
{-# LANGUAGE RecordWildCards #-}
{-|
Module : CLI
Description : CLI options
Stability : experimental
Portability : POSIX
Work with CLI options.
-}
module CLI
( optionsParser
, makeSureOptionsAreValid
) where
import Options.Applicative.Simple
import Data.Monoid ( (<>) )
import Control.Monad ( when )
import Control.Monad.Extra ( unlessM )
import System.Directory ( doesDirectoryExist )
import System.Exit ( die )
-- | Type that represents CLI options, we use it just for 'Parser'.
data Options = Options
{ commonFood :: FilePath -- ^ Path to directory with .csv-files with common localized lists of food.
, port :: Int -- ^ Port that server will listen.
}
-- | Parser parses actual CLI-arguments into a value of 'Option' type.
optionsParser :: Parser Options
optionsParser = do
commonFood <- strOption $
long "food"
<> short 'f'
<> metavar "PATH_TO_CSV_DIR"
<> showDefault
<> value "./food/common" -- Option's default value.
<> help "Path to a directory containing .csv-files with common lists of food"
port <- option auto $
long "port"
<> short 'p'
<> metavar "PORT"
<> showDefault
<> value 3000 -- Option's default value.
<> help "Port that server will listen"
-- 'commonFood' and 'port' fields are already here, so thanks to 'RecordWildCards'. ;-)
return Options{..}
{-|
Just checks if options are valid, exit with error otherwise.
Note that we have a tuple as a final result, not an 'Options' type,
because we don't want unnecessary dependencies outside this module.
-}
makeSureOptionsAreValid :: (Options, ()) -> IO (FilePath, Int)
makeSureOptionsAreValid (Options {..}, ()) =
makeSurePortIsValid
>> makeSureCSVExists
>> return (commonFood, port)
where
-- | Checks if specified value is valid registered port,
-- please see https://en.wikipedia.org/wiki/Registered_port for details.
makeSurePortIsValid :: IO ()
makeSurePortIsValid =
when (port < minPort || port > maxPort) reportAboutWrongPort
where
minPort = 1024 -- There's no reasons to run this service on a privileged port. ;-)
maxPort = 49151
reportAboutWrongPort = die $
"Please specify valid registered port, integer from "
<> show minPort <> " to " <> show maxPort <> "."
makeSureCSVExists :: IO ()
makeSureCSVExists =
unlessM (doesDirectoryExist commonFood) reportAboutCSVMissing
where
reportAboutCSVMissing = die $
"No such directory '"
<> commonFood
<> "', you can specify path to a directory with .csv-file via '--food' option."
| denisshevchenko/breadu.info | src/app/CLI.hs | mit | 3,005 | 0 | 14 | 947 | 415 | 225 | 190 | 51 | 1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE ExistentialQuantification #-}
module IHaskell.Display.Widgets.Types where
-- | This module houses all the type-trickery needed to make widgets happen.
--
-- All widgets have a corresponding 'WidgetType', and some fields/attributes/properties as defined
-- by the 'WidgetFields' type-family.
--
-- Each widget field corresponds to a concrete haskell type, as given by the 'FieldType'
-- type-family.
--
-- Vinyl records are used to wrap together widget fields into a single 'WidgetState'.
--
-- Singletons are used as a way to represent the promoted types of kind Field. For example:
--
-- @
-- SViewName :: SField ViewName
-- @
--
-- This allows the user to pass the type 'ViewName' without using Data.Proxy. In essence, a
-- singleton is the only inhabitant (other than bottom) of a promoted type. Single element set/type
-- == singleton.
--
-- It also allows the record to wrap values of properties with information about their Field type. A
-- vinyl record is represented as @Rec f ts@, which means that a record is a list of @f x@, where
-- @x@ is a type present in the type-level list @ts@. Thus a 'WidgetState' is essentially a list of
-- field properties wrapped together with the corresponding promoted Field type. See ('=::') for
-- more.
--
-- The properties function can be used to view all the @Field@s associated with a widget object.
--
-- Attributes are represented by the @Attr@ data type, which holds the value of a field, along with
-- the actual @Field@ object and a function to verify validity of changes to the value.
--
-- The IPython widgets expect state updates of the form {"property": value}, where an empty string
-- for numeric values is ignored by the frontend and the default value is used instead. Some numbers
-- need to be sent as numbers (represented by @Integer@), whereas some need to be sent as Strings
-- (@StrInt@).
--
-- Child widgets are expected to be sent as strings of the form "IPY_MODEL_<uuid>", where @<uuid>@
-- represents the uuid of the widget's comm.
--
-- To know more about the IPython messaging specification (as implemented in this package) take a
-- look at the supplied MsgSpec.md.
--
-- Widgets are not able to do console input, the reason for that can also be found in the messaging
-- specification
import Control.Monad (unless, join, when, void, mapM_)
import Control.Applicative ((<$>))
import qualified Control.Exception as Ex
import GHC.IO.Exception
import System.IO.Error
import System.Posix.IO
import Data.Aeson
import Data.Aeson.Types (Pair)
import Data.IORef (IORef, readIORef, modifyIORef)
import Data.Text (Text, pack)
import Data.Vinyl (Rec(..), (<+>), recordToList, reifyConstraint, rmap, Dict(..))
import Data.Vinyl.Functor (Compose(..), Const(..))
import Data.Vinyl.Lens (rget, rput, type (∈))
import Data.Vinyl.TypeLevel (RecAll)
import Data.Singletons.Prelude ((:++))
import Data.Singletons.TH
import IHaskell.Eval.Widgets (widgetSendUpdate)
import IHaskell.Display (Base64, IHaskellWidget(..))
import IHaskell.IPython.Message.UUID
import IHaskell.Display.Widgets.Singletons (Field, SField(..))
import qualified IHaskell.Display.Widgets.Singletons as S
import IHaskell.Display.Widgets.Common
-- Classes from IPython's widget hierarchy. Defined as such to reduce code duplication.
type WidgetClass = '[S.ViewModule, S.ViewName, S.MsgThrottle, S.Version,
S.DisplayHandler]
type DOMWidgetClass = WidgetClass :++ '[S.Visible, S.CSS, S.DOMClasses, S.Width, S.Height, S.Padding,
S.Margin, S.Color, S.BackgroundColor, S.BorderColor, S.BorderWidth,
S.BorderRadius, S.BorderStyle, S.FontStyle, S.FontWeight,
S.FontSize, S.FontFamily]
type StringClass = DOMWidgetClass :++ '[S.StringValue, S.Disabled, S.Description, S.Placeholder]
type BoolClass = DOMWidgetClass :++ '[S.BoolValue, S.Disabled, S.Description, S.ChangeHandler]
type SelectionClass = DOMWidgetClass :++ '[S.Options, S.SelectedValue, S.SelectedLabel, S.Disabled,
S.Description, S.SelectionHandler]
type MultipleSelectionClass = DOMWidgetClass :++ '[S.Options, S.SelectedLabels, S.SelectedValues, S.Disabled,
S.Description, S.SelectionHandler]
type IntClass = DOMWidgetClass :++ '[S.IntValue, S.Disabled, S.Description, S.ChangeHandler]
type BoundedIntClass = IntClass :++ '[S.StepInt, S.MinInt, S.MaxInt]
type IntRangeClass = IntClass :++ '[S.IntPairValue, S.LowerInt, S.UpperInt]
type BoundedIntRangeClass = IntRangeClass :++ '[S.StepInt, S.MinInt, S.MaxInt]
type FloatClass = DOMWidgetClass :++ '[S.FloatValue, S.Disabled, S.Description, S.ChangeHandler]
type BoundedFloatClass = FloatClass :++ '[S.StepFloat, S.MinFloat, S.MaxFloat]
type FloatRangeClass = FloatClass :++ '[S.FloatPairValue, S.LowerFloat, S.UpperFloat]
type BoundedFloatRangeClass = FloatRangeClass :++ '[S.StepFloat, S.MinFloat, S.MaxFloat]
type BoxClass = DOMWidgetClass :++ '[S.Children, S.OverflowX, S.OverflowY, S.BoxStyle]
type SelectionContainerClass = BoxClass :++ '[S.Titles, S.SelectedIndex, S.ChangeHandler]
-- Types associated with Fields.
type family FieldType (f :: Field) :: * where
FieldType S.ViewModule = Text
FieldType S.ViewName = Text
FieldType S.MsgThrottle = Integer
FieldType S.Version = Integer
FieldType S.DisplayHandler = IO ()
FieldType S.Visible = Bool
FieldType S.CSS = [(Text, Text, Text)]
FieldType S.DOMClasses = [Text]
FieldType S.Width = StrInt
FieldType S.Height = StrInt
FieldType S.Padding = StrInt
FieldType S.Margin = StrInt
FieldType S.Color = Text
FieldType S.BackgroundColor = Text
FieldType S.BorderColor = Text
FieldType S.BorderWidth = StrInt
FieldType S.BorderRadius = StrInt
FieldType S.BorderStyle = BorderStyleValue
FieldType S.FontStyle = FontStyleValue
FieldType S.FontWeight = FontWeightValue
FieldType S.FontSize = StrInt
FieldType S.FontFamily = Text
FieldType S.Description = Text
FieldType S.ClickHandler = IO ()
FieldType S.SubmitHandler = IO ()
FieldType S.Disabled = Bool
FieldType S.StringValue = Text
FieldType S.Placeholder = Text
FieldType S.Tooltip = Text
FieldType S.Icon = Text
FieldType S.ButtonStyle = ButtonStyleValue
FieldType S.B64Value = Base64
FieldType S.ImageFormat = ImageFormatValue
FieldType S.BoolValue = Bool
FieldType S.Options = SelectionOptions
FieldType S.SelectedLabel = Text
FieldType S.SelectedValue = Text
FieldType S.SelectionHandler = IO ()
FieldType S.Tooltips = [Text]
FieldType S.Icons = [Text]
FieldType S.SelectedLabels = [Text]
FieldType S.SelectedValues = [Text]
FieldType S.IntValue = Integer
FieldType S.StepInt = Integer
FieldType S.MinInt = Integer
FieldType S.MaxInt = Integer
FieldType S.LowerInt = Integer
FieldType S.UpperInt = Integer
FieldType S.IntPairValue = (Integer, Integer)
FieldType S.Orientation = OrientationValue
FieldType S.ShowRange = Bool
FieldType S.ReadOut = Bool
FieldType S.SliderColor = Text
FieldType S.BarStyle = BarStyleValue
FieldType S.FloatValue = Double
FieldType S.StepFloat = Double
FieldType S.MinFloat = Double
FieldType S.MaxFloat = Double
FieldType S.LowerFloat = Double
FieldType S.UpperFloat = Double
FieldType S.FloatPairValue = (Double, Double)
FieldType S.ChangeHandler = IO ()
FieldType S.Children = [ChildWidget]
FieldType S.OverflowX = OverflowValue
FieldType S.OverflowY = OverflowValue
FieldType S.BoxStyle = BoxStyleValue
FieldType S.Flex = Int
FieldType S.Pack = LocationValue
FieldType S.Align = LocationValue
FieldType S.Titles = [Text]
FieldType S.SelectedIndex = Integer
-- | Can be used to put different widgets in a list. Useful for dealing with children widgets.
data ChildWidget = forall w. RecAll Attr (WidgetFields w) ToPairs => ChildWidget (IPythonWidget w)
instance ToJSON ChildWidget where
toJSON (ChildWidget x) = toJSON . pack $ "IPY_MODEL_" ++ uuidToString (uuid x)
-- Will use a custom class rather than a newtype wrapper with an orphan instance. The main issue is
-- the need of a Bounded instance for Float / Double.
class CustomBounded a where
lowerBound :: a
upperBound :: a
-- Set according to what IPython widgets use
instance CustomBounded StrInt where
upperBound = 10 ^ 16 - 1
lowerBound = -(10 ^ 16 - 1)
instance CustomBounded Integer where
lowerBound = -(10 ^ 16 - 1)
upperBound = 10 ^ 16 - 1
instance CustomBounded Double where
lowerBound = -(10 ** 16 - 1)
upperBound = 10 ** 16 - 1
-- Different types of widgets. Every widget in IPython has a corresponding WidgetType
data WidgetType = ButtonType
| ImageType
| OutputType
| HTMLType
| LatexType
| TextType
| TextAreaType
| CheckBoxType
| ToggleButtonType
| DropdownType
| RadioButtonsType
| SelectType
| ToggleButtonsType
| SelectMultipleType
| IntTextType
| BoundedIntTextType
| IntSliderType
| IntProgressType
| IntRangeSliderType
| FloatTextType
| BoundedFloatTextType
| FloatSliderType
| FloatProgressType
| FloatRangeSliderType
| BoxType
| FlexBoxType
| AccordionType
| TabType
-- Fields associated with a widget
type family WidgetFields (w :: WidgetType) :: [Field] where
WidgetFields ButtonType =
DOMWidgetClass :++
'[S.Description, S.Tooltip, S.Disabled, S.Icon, S.ButtonStyle,
S.ClickHandler]
WidgetFields ImageType =
DOMWidgetClass :++ '[S.ImageFormat, S.B64Value]
WidgetFields OutputType = DOMWidgetClass
WidgetFields HTMLType = StringClass
WidgetFields LatexType = StringClass
WidgetFields TextType =
StringClass :++ '[S.SubmitHandler, S.ChangeHandler]
WidgetFields TextAreaType = StringClass :++ '[S.ChangeHandler]
WidgetFields CheckBoxType = BoolClass
WidgetFields ToggleButtonType =
BoolClass :++ '[S.Tooltip, S.Icon, S.ButtonStyle]
WidgetFields DropdownType = SelectionClass :++ '[S.ButtonStyle]
WidgetFields RadioButtonsType = SelectionClass
WidgetFields SelectType = SelectionClass
WidgetFields ToggleButtonsType =
SelectionClass :++ '[S.Tooltips, S.Icons, S.ButtonStyle]
WidgetFields SelectMultipleType = MultipleSelectionClass
WidgetFields IntTextType = IntClass
WidgetFields BoundedIntTextType = BoundedIntClass
WidgetFields IntSliderType =
BoundedIntClass :++
'[S.Orientation, S.ShowRange, S.ReadOut, S.SliderColor]
WidgetFields IntProgressType = BoundedIntClass :++ '[S.BarStyle]
WidgetFields IntRangeSliderType =
BoundedIntRangeClass :++
'[S.Orientation, S.ShowRange, S.ReadOut, S.SliderColor]
WidgetFields FloatTextType = FloatClass
WidgetFields BoundedFloatTextType = BoundedFloatClass
WidgetFields FloatSliderType =
BoundedFloatClass :++
'[S.Orientation, S.ShowRange, S.ReadOut, S.SliderColor]
WidgetFields FloatProgressType =
BoundedFloatClass :++ '[S.BarStyle]
WidgetFields FloatRangeSliderType =
BoundedFloatRangeClass :++
'[S.Orientation, S.ShowRange, S.ReadOut, S.SliderColor]
WidgetFields BoxType = BoxClass
WidgetFields FlexBoxType =
BoxClass :++ '[S.Orientation, S.Flex, S.Pack, S.Align]
WidgetFields AccordionType = SelectionContainerClass
WidgetFields TabType = SelectionContainerClass
-- Wrapper around a field's value. A dummy value is sent as an empty string to the frontend.
data AttrVal a = Dummy a
| Real a
unwrap :: AttrVal a -> a
unwrap (Dummy x) = x
unwrap (Real x) = x
-- Wrapper around a field.
data Attr (f :: Field) =
Attr
{ _value :: AttrVal (FieldType f)
, _verify :: FieldType f -> IO (FieldType f)
, _field :: Field
}
instance ToJSON (FieldType f) => ToJSON (Attr f) where
toJSON attr =
case _value attr of
Dummy _ -> ""
Real x -> toJSON x
-- Types that can be converted to Aeson Pairs.
class ToPairs a where
toPairs :: a -> [Pair]
-- Attributes that aren't synced with the frontend give [] on toPairs
instance ToPairs (Attr S.ViewModule) where
toPairs x = ["_view_module" .= toJSON x]
instance ToPairs (Attr S.ViewName) where
toPairs x = ["_view_name" .= toJSON x]
instance ToPairs (Attr S.MsgThrottle) where
toPairs x = ["msg_throttle" .= toJSON x]
instance ToPairs (Attr S.Version) where
toPairs x = ["version" .= toJSON x]
instance ToPairs (Attr S.DisplayHandler) where
toPairs _ = [] -- Not sent to the frontend
instance ToPairs (Attr S.Visible) where
toPairs x = ["visible" .= toJSON x]
instance ToPairs (Attr S.CSS) where
toPairs x = ["_css" .= toJSON x]
instance ToPairs (Attr S.DOMClasses) where
toPairs x = ["_dom_classes" .= toJSON x]
instance ToPairs (Attr S.Width) where
toPairs x = ["width" .= toJSON x]
instance ToPairs (Attr S.Height) where
toPairs x = ["height" .= toJSON x]
instance ToPairs (Attr S.Padding) where
toPairs x = ["padding" .= toJSON x]
instance ToPairs (Attr S.Margin) where
toPairs x = ["margin" .= toJSON x]
instance ToPairs (Attr S.Color) where
toPairs x = ["color" .= toJSON x]
instance ToPairs (Attr S.BackgroundColor) where
toPairs x = ["background_color" .= toJSON x]
instance ToPairs (Attr S.BorderColor) where
toPairs x = ["border_color" .= toJSON x]
instance ToPairs (Attr S.BorderWidth) where
toPairs x = ["border_width" .= toJSON x]
instance ToPairs (Attr S.BorderRadius) where
toPairs x = ["border_radius" .= toJSON x]
instance ToPairs (Attr S.BorderStyle) where
toPairs x = ["border_style" .= toJSON x]
instance ToPairs (Attr S.FontStyle) where
toPairs x = ["font_style" .= toJSON x]
instance ToPairs (Attr S.FontWeight) where
toPairs x = ["font_weight" .= toJSON x]
instance ToPairs (Attr S.FontSize) where
toPairs x = ["font_size" .= toJSON x]
instance ToPairs (Attr S.FontFamily) where
toPairs x = ["font_family" .= toJSON x]
instance ToPairs (Attr S.Description) where
toPairs x = ["description" .= toJSON x]
instance ToPairs (Attr S.ClickHandler) where
toPairs _ = [] -- Not sent to the frontend
instance ToPairs (Attr S.SubmitHandler) where
toPairs _ = [] -- Not sent to the frontend
instance ToPairs (Attr S.Disabled) where
toPairs x = ["disabled" .= toJSON x]
instance ToPairs (Attr S.StringValue) where
toPairs x = ["value" .= toJSON x]
instance ToPairs (Attr S.Placeholder) where
toPairs x = ["placeholder" .= toJSON x]
instance ToPairs (Attr S.Tooltip) where
toPairs x = ["tooltip" .= toJSON x]
instance ToPairs (Attr S.Icon) where
toPairs x = ["icon" .= toJSON x]
instance ToPairs (Attr S.ButtonStyle) where
toPairs x = ["button_style" .= toJSON x]
instance ToPairs (Attr S.B64Value) where
toPairs x = ["_b64value" .= toJSON x]
instance ToPairs (Attr S.ImageFormat) where
toPairs x = ["format" .= toJSON x]
instance ToPairs (Attr S.BoolValue) where
toPairs x = ["value" .= toJSON x]
instance ToPairs (Attr S.SelectedLabel) where
toPairs x = ["selected_label" .= toJSON x]
instance ToPairs (Attr S.SelectedValue) where
toPairs x = ["value" .= toJSON x]
instance ToPairs (Attr S.Options) where
toPairs x =
case _value x of
Dummy _ -> labels ("" :: Text)
Real (OptionLabels xs) -> labels xs
Real (OptionDict xps) -> labels $ map fst xps
where
labels xs = ["_options_labels" .= xs]
instance ToPairs (Attr S.SelectionHandler) where
toPairs _ = [] -- Not sent to the frontend
instance ToPairs (Attr S.Tooltips) where
toPairs x = ["tooltips" .= toJSON x]
instance ToPairs (Attr S.Icons) where
toPairs x = ["icons" .= toJSON x]
instance ToPairs (Attr S.SelectedLabels) where
toPairs x = ["selected_labels" .= toJSON x]
instance ToPairs (Attr S.SelectedValues) where
toPairs x = ["values" .= toJSON x]
instance ToPairs (Attr S.IntValue) where
toPairs x = ["value" .= toJSON x]
instance ToPairs (Attr S.StepInt) where
toPairs x = ["step" .= toJSON x]
instance ToPairs (Attr S.MinInt) where
toPairs x = ["min" .= toJSON x]
instance ToPairs (Attr S.MaxInt) where
toPairs x = ["max" .= toJSON x]
instance ToPairs (Attr S.IntPairValue) where
toPairs x = ["value" .= toJSON x]
instance ToPairs (Attr S.LowerInt) where
toPairs x = ["min" .= toJSON x]
instance ToPairs (Attr S.UpperInt) where
toPairs x = ["max" .= toJSON x]
instance ToPairs (Attr S.FloatValue) where
toPairs x = ["value" .= toJSON x]
instance ToPairs (Attr S.StepFloat) where
toPairs x = ["step" .= toJSON x]
instance ToPairs (Attr S.MinFloat) where
toPairs x = ["min" .= toJSON x]
instance ToPairs (Attr S.MaxFloat) where
toPairs x = ["max" .= toJSON x]
instance ToPairs (Attr S.FloatPairValue) where
toPairs x = ["value" .= toJSON x]
instance ToPairs (Attr S.LowerFloat) where
toPairs x = ["min" .= toJSON x]
instance ToPairs (Attr S.UpperFloat) where
toPairs x = ["max" .= toJSON x]
instance ToPairs (Attr S.Orientation) where
toPairs x = ["orientation" .= toJSON x]
instance ToPairs (Attr S.ShowRange) where
toPairs x = ["_range" .= toJSON x]
instance ToPairs (Attr S.ReadOut) where
toPairs x = ["readout" .= toJSON x]
instance ToPairs (Attr S.SliderColor) where
toPairs x = ["slider_color" .= toJSON x]
instance ToPairs (Attr S.BarStyle) where
toPairs x = ["bar_style" .= toJSON x]
instance ToPairs (Attr S.ChangeHandler) where
toPairs _ = [] -- Not sent to the frontend
instance ToPairs (Attr S.Children) where
toPairs x = ["children" .= toJSON x]
instance ToPairs (Attr S.OverflowX) where
toPairs x = ["overflow_x" .= toJSON x]
instance ToPairs (Attr S.OverflowY) where
toPairs x = ["overflow_y" .= toJSON x]
instance ToPairs (Attr S.BoxStyle) where
toPairs x = ["box_style" .= toJSON x]
instance ToPairs (Attr S.Flex) where
toPairs x = ["flex" .= toJSON x]
instance ToPairs (Attr S.Pack) where
toPairs x = ["pack" .= toJSON x]
instance ToPairs (Attr S.Align) where
toPairs x = ["align" .= toJSON x]
instance ToPairs (Attr S.Titles) where
toPairs x = ["_titles" .= toJSON x]
instance ToPairs (Attr S.SelectedIndex) where
toPairs x = ["selected_index" .= toJSON x]
-- | Store the value for a field, as an object parametrized by the Field. No verification is done
-- for these values.
(=::) :: SingI f => Sing f -> FieldType f -> Attr f
s =:: x = Attr { _value = Real x, _verify = return, _field = reflect s }
-- | If the number is in the range, return it. Otherwise raise the appropriate (over/under)flow
-- exception.
rangeCheck :: (Num a, Ord a) => (a, a) -> a -> IO a
rangeCheck (l, u) x
| l <= x && x <= u = return x
| l > x = Ex.throw Ex.Underflow
| u < x = Ex.throw Ex.Overflow
| otherwise = error "The impossible happened in IHaskell.Display.Widgets.Types.rangeCheck"
-- | Store a numeric value, with verification mechanism for its range.
ranged :: (SingI f, Num (FieldType f), Ord (FieldType f))
=> Sing f -> (FieldType f, FieldType f) -> AttrVal (FieldType f) -> Attr f
ranged s range x = Attr x (rangeCheck range) (reflect s)
-- | Store a numeric value, with the invariant that it stays non-negative. The value set is set as a
-- dummy value if it's equal to zero.
(=:+) :: (SingI f, Num (FieldType f), CustomBounded (FieldType f), Ord (FieldType f))
=> Sing f -> FieldType f -> Attr f
s =:+ val = Attr
((if val == 0
then Dummy
else Real)
val)
(rangeCheck (0, upperBound))
(reflect s)
-- | Get a field from a singleton Adapted from: http://stackoverflow.com/a/28033250/2388535
reflect :: forall (f :: Field). (SingI f, SingKind ('KProxy :: KProxy Field)) => Sing f -> Field
reflect = fromSing
-- | A record representing an object of the Widget class from IPython
defaultWidget :: FieldType S.ViewName -> Rec Attr WidgetClass
defaultWidget viewName = (ViewModule =:: "")
:& (ViewName =:: viewName)
:& (MsgThrottle =:+ 3)
:& (Version =:: 0)
:& (DisplayHandler =:: return ())
:& RNil
-- | A record representing an object of the DOMWidget class from IPython
defaultDOMWidget :: FieldType S.ViewName -> Rec Attr DOMWidgetClass
defaultDOMWidget viewName = defaultWidget viewName <+> domAttrs
where
domAttrs = (Visible =:: True)
:& (CSS =:: [])
:& (DOMClasses =:: [])
:& (Width =:+ 0)
:& (Height =:+ 0)
:& (Padding =:+ 0)
:& (Margin =:+ 0)
:& (Color =:: "")
:& (BackgroundColor =:: "")
:& (BorderColor =:: "")
:& (BorderWidth =:+ 0)
:& (BorderRadius =:+ 0)
:& (BorderStyle =:: DefaultBorder)
:& (FontStyle =:: DefaultFont)
:& (FontWeight =:: DefaultWeight)
:& (FontSize =:+ 0)
:& (FontFamily =:: "")
:& RNil
-- | A record representing a widget of the _String class from IPython
defaultStringWidget :: FieldType S.ViewName -> Rec Attr StringClass
defaultStringWidget viewName = defaultDOMWidget viewName <+> strAttrs
where
strAttrs = (StringValue =:: "")
:& (Disabled =:: False)
:& (Description =:: "")
:& (Placeholder =:: "")
:& RNil
-- | A record representing a widget of the _Bool class from IPython
defaultBoolWidget :: FieldType S.ViewName -> Rec Attr BoolClass
defaultBoolWidget viewName = defaultDOMWidget viewName <+> boolAttrs
where
boolAttrs = (BoolValue =:: False)
:& (Disabled =:: False)
:& (Description =:: "")
:& (ChangeHandler =:: return ())
:& RNil
-- | A record representing a widget of the _Selection class from IPython
defaultSelectionWidget :: FieldType S.ViewName -> Rec Attr SelectionClass
defaultSelectionWidget viewName = defaultDOMWidget viewName <+> selectionAttrs
where
selectionAttrs = (Options =:: OptionLabels [])
:& (SelectedValue =:: "")
:& (SelectedLabel =:: "")
:& (Disabled =:: False)
:& (Description =:: "")
:& (SelectionHandler =:: return ())
:& RNil
-- | A record representing a widget of the _MultipleSelection class from IPython
defaultMultipleSelectionWidget :: FieldType S.ViewName -> Rec Attr MultipleSelectionClass
defaultMultipleSelectionWidget viewName = defaultDOMWidget viewName <+> mulSelAttrs
where
mulSelAttrs = (Options =:: OptionLabels [])
:& (SelectedLabels =:: [])
:& (SelectedValues =:: [])
:& (Disabled =:: False)
:& (Description =:: "")
:& (SelectionHandler =:: return ())
:& RNil
-- | A record representing a widget of the _Int class from IPython
defaultIntWidget :: FieldType S.ViewName -> Rec Attr IntClass
defaultIntWidget viewName = defaultDOMWidget viewName <+> intAttrs
where
intAttrs = (IntValue =:: 0)
:& (Disabled =:: False)
:& (Description =:: "")
:& (ChangeHandler =:: return ())
:& RNil
-- | A record representing a widget of the _BoundedInt class from IPython
defaultBoundedIntWidget :: FieldType S.ViewName -> Rec Attr BoundedIntClass
defaultBoundedIntWidget viewName = defaultIntWidget viewName <+> boundedIntAttrs
where
boundedIntAttrs = (StepInt =:: 1)
:& (MinInt =:: 0)
:& (MaxInt =:: 100)
:& RNil
-- | A record representing a widget of the _BoundedInt class from IPython
defaultIntRangeWidget :: FieldType S.ViewName -> Rec Attr IntRangeClass
defaultIntRangeWidget viewName = defaultIntWidget viewName <+> rangeAttrs
where
rangeAttrs = (IntPairValue =:: (25, 75))
:& (LowerInt =:: 0)
:& (UpperInt =:: 100)
:& RNil
-- | A record representing a widget of the _BoundedIntRange class from IPython
defaultBoundedIntRangeWidget :: FieldType S.ViewName -> Rec Attr BoundedIntRangeClass
defaultBoundedIntRangeWidget viewName = defaultIntRangeWidget viewName <+> boundedIntRangeAttrs
where
boundedIntRangeAttrs = (StepInt =:+ 1)
:& (MinInt =:: 0)
:& (MaxInt =:: 100)
:& RNil
-- | A record representing a widget of the _Float class from IPython
defaultFloatWidget :: FieldType S.ViewName -> Rec Attr FloatClass
defaultFloatWidget viewName = defaultDOMWidget viewName <+> intAttrs
where
intAttrs = (FloatValue =:: 0)
:& (Disabled =:: False)
:& (Description =:: "")
:& (ChangeHandler =:: return ())
:& RNil
-- | A record representing a widget of the _BoundedFloat class from IPython
defaultBoundedFloatWidget :: FieldType S.ViewName -> Rec Attr BoundedFloatClass
defaultBoundedFloatWidget viewName = defaultFloatWidget viewName <+> boundedFloatAttrs
where
boundedFloatAttrs = (StepFloat =:+ 1)
:& (MinFloat =:: 0)
:& (MaxFloat =:: 100)
:& RNil
-- | A record representing a widget of the _BoundedFloat class from IPython
defaultFloatRangeWidget :: FieldType S.ViewName -> Rec Attr FloatRangeClass
defaultFloatRangeWidget viewName = defaultFloatWidget viewName <+> rangeAttrs
where
rangeAttrs = (FloatPairValue =:: (25, 75))
:& (LowerFloat =:: 0)
:& (UpperFloat =:: 100)
:& RNil
-- | A record representing a widget of the _BoundedFloatRange class from IPython
defaultBoundedFloatRangeWidget :: FieldType S.ViewName -> Rec Attr BoundedFloatRangeClass
defaultBoundedFloatRangeWidget viewName = defaultFloatRangeWidget viewName <+> boundedFloatRangeAttrs
where
boundedFloatRangeAttrs = (StepFloat =:+ 1)
:& (MinFloat =:: 0)
:& (MaxFloat =:: 100)
:& RNil
-- | A record representing a widget of the _Box class from IPython
defaultBoxWidget :: FieldType S.ViewName -> Rec Attr BoxClass
defaultBoxWidget viewName = defaultDOMWidget viewName <+> boxAttrs
where
boxAttrs = (Children =:: [])
:& (OverflowX =:: DefaultOverflow)
:& (OverflowY =:: DefaultOverflow)
:& (BoxStyle =:: DefaultBox)
:& RNil
-- | A record representing a widget of the _SelectionContainer class from IPython
defaultSelectionContainerWidget :: FieldType S.ViewName -> Rec Attr SelectionContainerClass
defaultSelectionContainerWidget viewName = defaultBoxWidget viewName <+> selAttrs
where
selAttrs = (Titles =:: [])
:& (SelectedIndex =:: 0)
:& (ChangeHandler =:: return ())
:& RNil
newtype WidgetState w = WidgetState { _getState :: Rec Attr (WidgetFields w) }
-- All records with ToPair instances for their Attrs will automatically have a toJSON instance now.
instance RecAll Attr (WidgetFields w) ToPairs => ToJSON (WidgetState w) where
toJSON record =
object
. concat
. recordToList
. rmap (\(Compose (Dict x)) -> Const $ toPairs x) $ reifyConstraint (Proxy :: Proxy ToPairs) $ _getState
record
data IPythonWidget (w :: WidgetType) =
IPythonWidget
{ uuid :: UUID
, state :: IORef (WidgetState w)
}
-- | Change the value for a field, and notify the frontend about it.
setField :: (f ∈ WidgetFields w, IHaskellWidget (IPythonWidget w), ToPairs (Attr f))
=> IPythonWidget w -> SField f -> FieldType f -> IO ()
setField widget sfield fval = do
!newattr <- setField' widget sfield fval
let pairs = toPairs newattr
unless (null pairs) $ widgetSendUpdate widget (object pairs)
-- | Change the value of a field, without notifying the frontend. For internal use.
setField' :: (f ∈ WidgetFields w, IHaskellWidget (IPythonWidget w))
=> IPythonWidget w -> SField f -> FieldType f -> IO (Attr f)
setField' widget sfield val = do
attr <- getAttr widget sfield
newval <- _verify attr val
let newattr = attr { _value = Real newval }
modifyIORef (state widget) (WidgetState . rput newattr . _getState)
return newattr
-- | Pluck an attribute from a record
getAttr :: (f ∈ WidgetFields w) => IPythonWidget w -> SField f -> IO (Attr f)
getAttr widget sfield = rget sfield <$> _getState <$> readIORef (state widget)
-- | Get the value of a field.
getField :: (f ∈ WidgetFields w) => IPythonWidget w -> SField f -> IO (FieldType f)
getField widget sfield = unwrap . _value <$> getAttr widget sfield
-- | Useful with toJSON and OverloadedStrings
str :: String -> String
str = id
properties :: IPythonWidget w -> IO ()
properties widget = do
st <- readIORef $ state widget
let convert :: Attr f -> Const Field f
convert attr = Const { getConst = _field attr }
mapM_ print $ recordToList . rmap convert . _getState $ st
-- Helper function for widget to enforce their inability to fetch console input
noStdin :: IO a -> IO ()
noStdin action =
let handler :: IOException -> IO ()
handler e = when (ioeGetErrorType e == InvalidArgument)
(error "Widgets cannot do console input, sorry :)")
in Ex.handle handler $ do
nullFd <- openFd "/dev/null" WriteOnly Nothing defaultFileFlags
oldStdin <- dup stdInput
void $ dupTo nullFd stdInput
closeFd nullFd
void action
void $ dupTo oldStdin stdInput
-- Trigger events
triggerEvent :: (FieldType f ~ IO (), f ∈ WidgetFields w) => SField f -> IPythonWidget w -> IO ()
triggerEvent sfield w = noStdin . join $ getField w sfield
triggerChange :: (S.ChangeHandler ∈ WidgetFields w) => IPythonWidget w -> IO ()
triggerChange = triggerEvent ChangeHandler
triggerClick :: (S.ClickHandler ∈ WidgetFields w) => IPythonWidget w -> IO ()
triggerClick = triggerEvent ClickHandler
triggerSelection :: (S.SelectionHandler ∈ WidgetFields w) => IPythonWidget w -> IO ()
triggerSelection = triggerEvent SelectionHandler
triggerSubmit :: (S.SubmitHandler ∈ WidgetFields w) => IPythonWidget w -> IO ()
triggerSubmit = triggerEvent SubmitHandler
triggerDisplay :: (S.DisplayHandler ∈ WidgetFields w) => IPythonWidget w -> IO ()
triggerDisplay = triggerEvent DisplayHandler
| wyager/IHaskell | ihaskell-display/ihaskell-widgets/src/IHaskell/Display/Widgets/Types.hs | mit | 32,398 | 1 | 26 | 8,400 | 8,388 | 4,406 | 3,982 | -1 | -1 |
{-# LANGUAGE OverloadedStrings, ScopedTypeVariables #-}
-----------------------------------------------------------------------------
-- | This module is where all the routes and handlers are defined for your
-- site. The 'app' function is the initializer that combines everything
-- together and is exported by this module.
module Site
( app
) where
------------------------------------------------------------------------------
import Control.Concurrent
import Control.Applicative
import Control.Monad.Except
import Control.Error.Safe (tryJust)
import Control.Lens hiding ((.=))
import Data.Aeson hiding (json)
import Data.Bifunctor (first)
import Data.ByteString (ByteString)
import qualified Data.Map as M
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.Text.Read as T
import Data.Time (UTCTime)
import Snap.Core
import Snap.Snaplet
import qualified Snap.Snaplet.SqliteJwt as J
import Snap.Snaplet.SqliteSimple
import Snap.Util.FileServe
import qualified Web.JWT as JWT
------------------------------------------------------------------------------
import Application
import qualified Db
import Util
type H = Handler App App
data LoginParams = LoginParams {
lpLogin :: T.Text
, lpPass :: T.Text
}
instance FromJSON LoginParams where
parseJSON (Object v) = LoginParams <$>
v .: "login" <*>
v .: "pass"
parseJSON _ = mzero
data PostTodoParams = PostTodoParams {
ptId :: Maybe Int
, ptSavedOn :: Maybe UTCTime
, ptCompleted :: Bool
, ptText :: T.Text
}
instance FromJSON PostTodoParams where
parseJSON (Object v) = PostTodoParams <$> optional (v.: "id") <*> optional (v .: "savedOn") <*> v .: "completed" <*> v .: "text"
parseJSON _ = mzero
instance ToJSON Db.Todo where
toJSON c = object [ "id" .= Db.todoId c
, "savedOn" .= Db.todoSavedOn c
, "completed" .= Db.todoCompleted c
, "text" .= Db.todoText c]
maybeWhen :: Monad m => Maybe a -> (a -> m ()) -> m ()
maybeWhen Nothing _ = return ()
maybeWhen (Just a) f = f a
handleRestTodos :: H ()
handleRestTodos = (method GET listTodos) <|> (method POST saveTodo)
where
listTodos :: H ()
listTodos = replyJson query
where
query (J.User uid _) = do
withTop db $ Db.listTodos (Db.UserId uid)
saveTodo = do
ps <- reqJSON
replyJson (query ps)
where
query ps (J.User uid _) =
-- If the input todo id is Nothing, create a new todo. Otherwise update
-- an existing one.
case ptId ps of
Nothing -> do
withTop db $ Db.newTodo (Db.UserId uid) (ptText ps)
Just tid -> do
let newTodo = Db.Todo tid (ptSavedOn ps) (ptCompleted ps) (ptText ps)
withTop db $ Db.saveTodo (Db.UserId uid) newTodo
replyJson :: ToJSON a => (J.User -> Handler App J.SqliteJwt a) -> H ()
replyJson action = do
res <- with jwt $ J.requireAuth action
writeJSON res
handleLoginError :: J.AuthFailure -> H ()
handleLoginError err =
case err of
J.DuplicateLogin -> failLogin dupeError
J.UnknownUser -> failLogin failedPassOrUserError
J.WrongPassword -> failLogin failedPassOrUserError
where
dupeError = "Duplicate login"
failedPassOrUserError = "Unknown user or wrong password"
failLogin :: T.Text -> H ()
failLogin err = do
jsonResponse
modifyResponse $ setResponseStatus 401 "bad login"
writeJSON $ object [ "error" .= err]
loginOK :: J.User -> H ()
loginOK user = do
jwt <- with jwt $ J.jwtFromUser user
writeJSON $ object [ "token" .= jwt ]
handleNewUser :: H ()
handleNewUser = method POST newUser
where
newUser = runHttpErrorExceptT $ do
login <- lift reqJSON
userOrErr <- lift $ with jwt $ J.createUser (lpLogin login) (lpPass login)
return (either handleLoginError loginOK userOrErr)
handleLogin :: H ()
handleLogin = method POST go
where
go = runHttpErrorExceptT $ do
login <- lift reqJSON
userOrErr <- lift $ with jwt $ J.loginUser (lpLogin login) (lpPass login)
return (either handleLoginError loginOK userOrErr)
-- | The application's routes.
routes :: [(ByteString, Handler App App ())]
routes = [
("/api/login/new", handleNewUser)
, ("/api/login", handleLogin)
, ("/api/todo", handleRestTodos)
, ("/static", serveDirectory "static")
, ("/", serveFile "static/index.html")
]
-- | The application initializer.
app :: SnapletInit App App
app = makeSnaplet "app" "An snaplet example application." Nothing $ do
addRoutes routes
-- Initialize auth that's backed by an sqlite database
d <- nestSnaplet "db" db sqliteInit
-- Initialize auth that's backed by an sqlite database
jwt <- nestSnaplet "jwt" jwt (J.sqliteJwtInit d)
-- Grab the DB connection pool from the sqlite snaplet and call
-- into the Model to create all the DB tables if necessary.
let c = sqliteConn $ d ^# snapletValue
liftIO $ withMVar c $ \conn -> Db.createTables conn
return $ App d jwt
| marksauter/reactd3 | server/Site.hs | mit | 5,420 | 0 | 19 | 1,491 | 1,437 | 743 | 694 | -1 | -1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.