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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# LANGUAGE OverloadedStrings, CPP #-}
module Text.Inject (
inject
#ifdef TEST
, Element (..)
, pBraces
#endif
) where
import Prelude hiding (takeWhile)
import Control.Applicative
import Data.Text (Text)
import qualified Data.Text as T
import Data.Attoparsec.Text
import Util
type Template = [Element]
data Element = Plain Text | Braces Text
deriving (Eq, Show)
inject :: Text -> IO Text
inject = fmap T.concat . mapM f . parseTemplate
where
f :: Element -> IO Text
f element = case element of
Plain text -> return text
Braces cmd -> system (T.unpack cmd)
parseTemplate :: Text -> Template
parseTemplate = either parseError id . parseOnly (pTemplate <* endOfInput)
where
parseError = (error . unwords) [
"Parsing failed."
, "This should never happen"
, "Please report a bug!"
]
pTemplate :: Parser Template
pTemplate = many (pBraces <|> (Plain <$> pText))
pText :: Parser Text
pText = T.cons <$> anyChar <*> takeWhile (/= '{')
pBraces :: Parser Element
pBraces = Braces . T.init <$> ("{{" *> scan 0 f <* "}")
where
f 0 '}' = Just 1
f 1 '}' = Nothing
f _ _ = Just (0 :: Int)
| beni55/inject | src/Text/Inject.hs | mit | 1,207 | 0 | 13 | 320 | 392 | 213 | 179 | 33 | 3 |
{-# LANGUAGE DeriveDataTypeable #-}
{- |
Module : ./CspCASL/SignCSP.hs
Description : CspCASL signatures
Copyright : (c) Markus Roggenbach and Till Mossakowski and Uni Bremen 2004
License : GPLv2 or higher, see LICENSE.txt
Maintainer : M.Roggenbach@swansea.ac.uk
Stability : provisional
Portability : portable
signatures for CSP-CASL
-}
module CspCASL.SignCSP
( addProcNameToProcNameMap
, ccSig2CASLSign
, ccSig2CspSign
, ChanNameMap
, closeCspCommAlpha
, CspCASLSign
, CspCASLSen
, CspSen (..)
, CspSign (..)
, cspSignUnion
, diffCspSig
, emptyCspCASLSign
, emptyCspSign
, FQProcVarList
, getUniqueProfileInProcNameMap
, isCspCASLSubSig
, isCspSubSign
, isNameInProcNameMap
, isProcessEq
, ProcNameMap
, ProcVarList
, ProcVarMap
, reduceProcProfile
, commType2Sort
, relatedSorts
, relatedProcs
, unionCspCASLSign
) where
import CASL.AS_Basic_CASL
import CASL.Overload
import CASL.Sign
import CASL.ToDoc
import CspCASL.AS_CspCASL_Process
import CspCASL.AS_CspCASL ()
import CspCASL.CspCASL_Keywords
import qualified CspCASL.LocalTop as LocalTop
import CspCASL.Print_CspCASL ()
import Common.AnnoState
import Common.Doc
import Common.DocUtils
import Common.Id
import Common.Result
import Common.Lib.Rel (Rel, predecessors, member)
import qualified Common.Lib.MapSet as MapSet
import Common.Utils (keepMins)
import qualified Data.Map as Map
import qualified Data.Set as Set
import Data.Data
import Data.List
import Data.Ord
type ChanNameMap = MapSet.MapSet CHANNEL_NAME SORT
type ProcNameMap = MapSet.MapSet PROCESS_NAME ProcProfile
type ProcVarMap = Map.Map SIMPLE_ID SORT
type ProcVarList = [(SIMPLE_ID, SORT)]
-- | Add a process name and its profile to a process name map. exist.
addProcNameToProcNameMap :: PROCESS_NAME -> ProcProfile -> ProcNameMap
-> ProcNameMap
addProcNameToProcNameMap = MapSet.insert
-- | Test if a simple process name with a profile is in the process name map.
isNameInProcNameMap :: PROCESS_NAME -> ProcProfile -> ProcNameMap -> Bool
isNameInProcNameMap = MapSet.member
{- | Given a simple process name and a required number of parameters, find a
unqiue profile with that many parameters if possible. If this is not possible
(i.e., name does not exist, or no profile with the required number of
arguments or not unique profile for the required number of arguments), then
the functions returns a failed result with a helpful error message. failure. -}
getUniqueProfileInProcNameMap :: PROCESS_NAME -> Int -> ProcNameMap ->
Result ProcProfile
getUniqueProfileInProcNameMap name numParams pm =
let profiles = MapSet.lookup name pm
isMatch (ProcProfile argSorts _) =
length argSorts == numParams
matchedProfiles = Set.filter isMatch profiles
in case Set.toList matchedProfiles of
[] -> mkError ("Process name not in signature with "
++ show numParams ++ " parameters:") name
[p] -> return p
_ -> mkError ("Process name not unique in signature with "
++ show numParams ++ " parameters:") name
-- Close a communication alphabet under CASL subsort
closeCspCommAlpha :: Rel SORT -> CommAlpha -> CommAlpha
closeCspCommAlpha sr =
Set.unions . Set.toList . Set.map (closeOneCspComm sr)
-- Close one CommType under CASL subsort
closeOneCspComm :: Rel SORT -> CommType -> CommAlpha
closeOneCspComm sr x = let
mkTypedChan c s = CommTypeChan $ TypedChanName c s
subsorts s' = Set.insert s' $ predecessors sr s'
in case x of
CommTypeSort s ->
Set.map CommTypeSort (subsorts s)
CommTypeChan (TypedChanName c s) ->
Set.map CommTypeSort (subsorts s)
`Set.union` Set.map (mkTypedChan c) (subsorts s)
{- | Remove the implicit sorts from the proc name map under a sub-sort
relation. Assumes all the proc profile's comms are in the sub sort relation and
simply makes the comms contain only the minimal super sorts under the sub-sort
relation. -}
reduceProcNamesInSig :: Rel SORT -> CspSign -> CspSign
reduceProcNamesInSig sr cspSig =
cspSig { procSet = reduceProcNameMap sr $ procSet cspSig }
{- | Remove the implicit sorts from a proc name map under a sub-sort
relation. Assumes all the proc profile's comms are in the sub sort relation and
simply makes the comms contain only the minimal super sorts under the sub-sort
relation. -}
reduceProcNameMap :: Rel SORT -> ProcNameMap -> ProcNameMap
reduceProcNameMap sr =
MapSet.map (reduceProcProfile sr)
{- | Remove the implicit sorts from a profile under a sub-sort relation. Assumes
all the proc profile's comms are in the sub sort relation and simply makes the
comms contain only the minimal super sorts under the sub-sort relation. -}
reduceProcProfile :: Rel SORT -> ProcProfile -> ProcProfile
reduceProcProfile sr (ProcProfile argSorts comms) =
ProcProfile argSorts (reduceCspCommAlpha sr comms)
{- | Remove the implicit sorts from a CommAlpha under a sub-sort
relation. Assumes all the proc profile's comms are in the sub sort relation and
simply makes the comms contain only the minimal super sorts under the sub-sort
relation. -}
reduceCspCommAlpha :: Rel SORT -> CommAlpha -> CommAlpha
reduceCspCommAlpha sr =
Set.fromList .
concatMap (keepMins $ cmpCommType sr) . groupBy sameChan . Set.toList
cmpCommType :: Rel SORT -> CommType -> CommType -> Bool
cmpCommType rel t1 t2 = let
s1 = commType2Sort t1
s2 = commType2Sort t2
in s1 == s2 || member s2 s1 rel
commType2Sort :: CommType -> SORT
commType2Sort c = case c of
CommTypeSort s -> s
CommTypeChan (TypedChanName _ s) -> s
sameChan :: CommType -> CommType -> Bool
sameChan t1 t2 = case (t1, t2) of
(CommTypeSort _, CommTypeSort _) -> True
(CommTypeChan (TypedChanName c1 _), CommTypeChan (TypedChanName c2 _))
-> c1 == c2
_ -> False
-- | CSP process signature.
data CspSign = CspSign
{ chans :: ChanNameMap
, procSet :: ProcNameMap
} deriving (Show, Eq, Ord, Typeable, Data)
-- | plain union
cspSignUnion :: CspSign -> CspSign -> CspSign
cspSignUnion sign1 sign2 = emptyCspSign
{ chans = chans sign1 `MapSet.union` chans sign2
, procSet = procSet sign1 `MapSet.union` procSet sign2 }
{- | A CspCASL signature is a CASL signature with a CSP process
signature in the extendedInfo part. -}
type CspCASLSign = Sign CspSen CspSign
ccSig2CASLSign :: CspCASLSign -> CASLSign
ccSig2CASLSign sigma = sigma { extendedInfo = (), sentences = [] }
-- | Projection from CspCASL signature to Csp signature
ccSig2CspSign :: CspCASLSign -> CspSign
ccSig2CspSign = extendedInfo
-- | Empty CspCASL signature.
emptyCspCASLSign :: CspCASLSign
emptyCspCASLSign = emptySign emptyCspSign
-- | Empty CSP process signature.
emptyCspSign :: CspSign
emptyCspSign = CspSign
{ chans = MapSet.empty
, procSet = MapSet.empty }
-- | Compute union of two CSP CASL signatures.
unionCspCASLSign :: CspCASLSign -> CspCASLSign -> Result CspCASLSign
unionCspCASLSign s1 s2 = do
-- Compute the unioned data signature ignoring the csp signatures
let newDataSig = addSig (\ _ _ -> emptyCspSign) s1 s2
-- Check that the new data signature has local top elements
rel = sortRel newDataSig
diags' = LocalTop.checkLocalTops rel
-- Compute the unioned csp signature with respect to the new data signature
newCspSign = unionCspSign rel (extendedInfo s1) (extendedInfo s2)
{- Only error will be added if there are any probelms. If there are no
problems no errors will be added and hets will continue as normal. -}
appendDiags diags'
-- put both the new data signature and the csp signature back together
return $ newDataSig {extendedInfo = newCspSign}
{- | Compute union of two CSP signatures assuming the new already computed data
signature. -}
unionCspSign :: Rel SORT -> CspSign -> CspSign -> CspSign
unionCspSign sr a b = reduceProcNamesInSig sr $ cspSignUnion a b
-- | Compute difference of two CSP process signatures.
diffCspSig :: CspSign -> CspSign -> CspSign
diffCspSig a b = emptyCspSign
{ chans = MapSet.difference (chans a) $ chans b
, procSet = MapSet.difference (procSet a) $ procSet b
}
-- | Is one CspCASL Signature a sub signature of another
isCspCASLSubSig :: CspCASLSign -> CspCASLSign -> Bool
isCspCASLSubSig =
-- Normal casl subsignature and our extended csp part
isSubSig isCspSubSign
{- Also the sorts and sub-sort rels should be equal. If they are not then we
cannot just add the processes in as their profiles need to be donward closed
under the new sort-rels, but we do not check this here. -}
{- | Is one Csp Signature a sub signature of another assuming the same data
signature for now. -}
isCspSubSign :: CspSign -> CspSign -> Bool
isCspSubSign a b =
MapSet.isSubmapOf (chans a) (chans b) &&
-- Check for each profile that the set of names are included.
MapSet.isSubmapOf (procSet a) (procSet b)
-- | Pretty printing for CspCASL signatures
instance Pretty CspSign where
pretty = printCspSign
printCspSign :: CspSign -> Doc
printCspSign sigma =
case mapSetToList $ chans sigma of
[] -> empty
s -> keyword (channelS ++ appendS s) <+> printChanList s
$+$ case mapSetToList $ procSet sigma of
[] -> empty
ps -> keyword processS <+> printProcList ps
-- | Pretty printing for channels
printChanList :: [(CHANNEL_NAME, SORT)] -> Doc
printChanList l = let
gl = groupBy (\ (_, s1) (_, s2) -> s1 == s2) $ sortBy (comparing snd) l
printChan cl = case cl of
[] -> empty -- should not happen
(_, s) : _ -> fsep [ppWithCommas (map fst cl), colon <+> pretty s]
in sepBySemis $ map printChan gl
-- | Pretty printing for processes
printProcList :: [(PROCESS_NAME, ProcProfile)] -> Doc
printProcList = sepBySemis . map
(\ (procName, procProfile) -> pretty procName <+> pretty procProfile)
-- * overload relations: We do not have one of these yet in theory
relatedSorts :: CspCASLSign -> SORT -> SORT -> Bool
relatedSorts sig s1 s2 = haveCommonSupersorts True sig s1 s2
|| haveCommonSupersorts False sig s1 s2
relatedCommTypes :: CspCASLSign -> CommType -> CommType -> Bool
relatedCommTypes sig ct1 ct2 = case (ct1, ct2) of
(CommTypeSort s1, CommTypeSort s2) -> relatedSorts sig s1 s2
(CommTypeChan (TypedChanName c1 s1), CommTypeChan (TypedChanName c2 s2))
-> c1 == c2 && relatedSorts sig s1 s2
_ -> False
relatedCommAlpha :: CspCASLSign -> CommAlpha -> CommAlpha -> Bool
relatedCommAlpha sig al1 al2 = Set.null al1 || Set.null al2 ||
any (\ a -> any (relatedCommTypes sig a) $ Set.toList al1) (Set.toList al2)
relatedProcs :: CspCASLSign -> ProcProfile -> ProcProfile -> Bool
relatedProcs sig (ProcProfile l1 al1) (ProcProfile l2 al2) =
length l1 == length l2 &&
and (zipWith (relatedSorts sig) l1 l2)
&& relatedCommAlpha sig al1 al2
-- * Sentences
{- | FQProcVarList should only contain fully qualified CASL variables which are
TERMs i.e. constructed via the TERM constructor Qual_var. -}
type FQProcVarList = [TERM ()]
{- | A CspCASl senetence is either a CASL formula or a Procsses equation. A
process equation has on the LHS a process name, a list of parameters which
are qualified variables (which are terms), a constituent( or is it permitted
?) communication alphabet and finally on the RHS a fully qualified process. -}
data CspSen = ProcessEq FQ_PROCESS_NAME FQProcVarList CommAlpha PROCESS
deriving (Show, Eq, Ord, Typeable, Data)
type CspCASLSen = FORMULA CspSen
instance GetRange CspSen
instance Pretty CspSen where
pretty (ProcessEq pn varList _commAlpha proc) =
let varDoc = if null varList
then empty
else parens $ ppWithCommas varList
in fsep [pretty pn, varDoc, equals <+> pretty proc]
instance FormExtension CspSen where
prefixExt (ProcessEq pn _ _ _) = case pn of
PROCESS_NAME _ -> (keyword processS <+>)
FQ_PROCESS_NAME {} -> id
instance TermExtension CspSen
instance TermParser CspSen
isProcessEq :: CspCASLSen -> Bool
isProcessEq f = case f of
ExtFORMULA _ -> True
_ -> False
| spechub/Hets | CspCASL/SignCSP.hs | gpl-2.0 | 12,031 | 0 | 16 | 2,350 | 2,588 | 1,361 | 1,227 | 212 | 3 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.RDS.DescribeOrderableDBInstanceOptions
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Returns a list of orderable DB instance options for the specified
-- engine.
--
-- /See:/ <http://docs.aws.amazon.com/AmazonRDS/latest/APIReference/API_DescribeOrderableDBInstanceOptions.html AWS API Reference> for DescribeOrderableDBInstanceOptions.
--
-- This operation returns paginated results.
module Network.AWS.RDS.DescribeOrderableDBInstanceOptions
(
-- * Creating a Request
describeOrderableDBInstanceOptions
, DescribeOrderableDBInstanceOptions
-- * Request Lenses
, dodioEngineVersion
, dodioFilters
, dodioDBInstanceClass
, dodioLicenseModel
, dodioMarker
, dodioMaxRecords
, dodioVPC
, dodioEngine
-- * Destructuring the Response
, describeOrderableDBInstanceOptionsResponse
, DescribeOrderableDBInstanceOptionsResponse
-- * Response Lenses
, dodiorsOrderableDBInstanceOptions
, dodiorsMarker
, dodiorsResponseStatus
) where
import Network.AWS.Pager
import Network.AWS.Prelude
import Network.AWS.RDS.Types
import Network.AWS.RDS.Types.Product
import Network.AWS.Request
import Network.AWS.Response
-- |
--
-- /See:/ 'describeOrderableDBInstanceOptions' smart constructor.
data DescribeOrderableDBInstanceOptions = DescribeOrderableDBInstanceOptions'
{ _dodioEngineVersion :: !(Maybe Text)
, _dodioFilters :: !(Maybe [Filter])
, _dodioDBInstanceClass :: !(Maybe Text)
, _dodioLicenseModel :: !(Maybe Text)
, _dodioMarker :: !(Maybe Text)
, _dodioMaxRecords :: !(Maybe Int)
, _dodioVPC :: !(Maybe Bool)
, _dodioEngine :: !Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'DescribeOrderableDBInstanceOptions' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'dodioEngineVersion'
--
-- * 'dodioFilters'
--
-- * 'dodioDBInstanceClass'
--
-- * 'dodioLicenseModel'
--
-- * 'dodioMarker'
--
-- * 'dodioMaxRecords'
--
-- * 'dodioVPC'
--
-- * 'dodioEngine'
describeOrderableDBInstanceOptions
:: Text -- ^ 'dodioEngine'
-> DescribeOrderableDBInstanceOptions
describeOrderableDBInstanceOptions pEngine_ =
DescribeOrderableDBInstanceOptions'
{ _dodioEngineVersion = Nothing
, _dodioFilters = Nothing
, _dodioDBInstanceClass = Nothing
, _dodioLicenseModel = Nothing
, _dodioMarker = Nothing
, _dodioMaxRecords = Nothing
, _dodioVPC = Nothing
, _dodioEngine = pEngine_
}
-- | The engine version filter value. Specify this parameter to show only the
-- available offerings matching the specified engine version.
dodioEngineVersion :: Lens' DescribeOrderableDBInstanceOptions (Maybe Text)
dodioEngineVersion = lens _dodioEngineVersion (\ s a -> s{_dodioEngineVersion = a});
-- | This parameter is not currently supported.
dodioFilters :: Lens' DescribeOrderableDBInstanceOptions [Filter]
dodioFilters = lens _dodioFilters (\ s a -> s{_dodioFilters = a}) . _Default . _Coerce;
-- | The DB instance class filter value. Specify this parameter to show only
-- the available offerings matching the specified DB instance class.
dodioDBInstanceClass :: Lens' DescribeOrderableDBInstanceOptions (Maybe Text)
dodioDBInstanceClass = lens _dodioDBInstanceClass (\ s a -> s{_dodioDBInstanceClass = a});
-- | The license model filter value. Specify this parameter to show only the
-- available offerings matching the specified license model.
dodioLicenseModel :: Lens' DescribeOrderableDBInstanceOptions (Maybe Text)
dodioLicenseModel = lens _dodioLicenseModel (\ s a -> s{_dodioLicenseModel = a});
-- | An optional pagination token provided by a previous
-- DescribeOrderableDBInstanceOptions request. If this parameter is
-- specified, the response includes only records beyond the marker, up to
-- the value specified by 'MaxRecords' .
dodioMarker :: Lens' DescribeOrderableDBInstanceOptions (Maybe Text)
dodioMarker = lens _dodioMarker (\ s a -> s{_dodioMarker = a});
-- | The maximum number of records to include in the response. If more
-- records exist than the specified 'MaxRecords' value, a pagination token
-- called a marker is included in the response so that the remaining
-- results can be retrieved.
--
-- Default: 100
--
-- Constraints: Minimum 20, maximum 100.
dodioMaxRecords :: Lens' DescribeOrderableDBInstanceOptions (Maybe Int)
dodioMaxRecords = lens _dodioMaxRecords (\ s a -> s{_dodioMaxRecords = a});
-- | The VPC filter value. Specify this parameter to show only the available
-- VPC or non-VPC offerings.
dodioVPC :: Lens' DescribeOrderableDBInstanceOptions (Maybe Bool)
dodioVPC = lens _dodioVPC (\ s a -> s{_dodioVPC = a});
-- | The name of the engine to retrieve DB instance options for.
dodioEngine :: Lens' DescribeOrderableDBInstanceOptions Text
dodioEngine = lens _dodioEngine (\ s a -> s{_dodioEngine = a});
instance AWSPager DescribeOrderableDBInstanceOptions
where
page rq rs
| stop (rs ^. dodiorsMarker) = Nothing
| stop (rs ^. dodiorsOrderableDBInstanceOptions) =
Nothing
| otherwise =
Just $ rq & dodioMarker .~ rs ^. dodiorsMarker
instance AWSRequest
DescribeOrderableDBInstanceOptions where
type Rs DescribeOrderableDBInstanceOptions =
DescribeOrderableDBInstanceOptionsResponse
request = postQuery rDS
response
= receiveXMLWrapper
"DescribeOrderableDBInstanceOptionsResult"
(\ s h x ->
DescribeOrderableDBInstanceOptionsResponse' <$>
(x .@? "OrderableDBInstanceOptions" .!@ mempty >>=
may (parseXMLList "OrderableDBInstanceOption"))
<*> (x .@? "Marker")
<*> (pure (fromEnum s)))
instance ToHeaders DescribeOrderableDBInstanceOptions
where
toHeaders = const mempty
instance ToPath DescribeOrderableDBInstanceOptions
where
toPath = const "/"
instance ToQuery DescribeOrderableDBInstanceOptions
where
toQuery DescribeOrderableDBInstanceOptions'{..}
= mconcat
["Action" =:
("DescribeOrderableDBInstanceOptions" :: ByteString),
"Version" =: ("2014-10-31" :: ByteString),
"EngineVersion" =: _dodioEngineVersion,
"Filters" =:
toQuery (toQueryList "Filter" <$> _dodioFilters),
"DBInstanceClass" =: _dodioDBInstanceClass,
"LicenseModel" =: _dodioLicenseModel,
"Marker" =: _dodioMarker,
"MaxRecords" =: _dodioMaxRecords, "Vpc" =: _dodioVPC,
"Engine" =: _dodioEngine]
-- | Contains the result of a successful invocation of the
-- DescribeOrderableDBInstanceOptions action.
--
-- /See:/ 'describeOrderableDBInstanceOptionsResponse' smart constructor.
data DescribeOrderableDBInstanceOptionsResponse = DescribeOrderableDBInstanceOptionsResponse'
{ _dodiorsOrderableDBInstanceOptions :: !(Maybe [OrderableDBInstanceOption])
, _dodiorsMarker :: !(Maybe Text)
, _dodiorsResponseStatus :: !Int
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'DescribeOrderableDBInstanceOptionsResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'dodiorsOrderableDBInstanceOptions'
--
-- * 'dodiorsMarker'
--
-- * 'dodiorsResponseStatus'
describeOrderableDBInstanceOptionsResponse
:: Int -- ^ 'dodiorsResponseStatus'
-> DescribeOrderableDBInstanceOptionsResponse
describeOrderableDBInstanceOptionsResponse pResponseStatus_ =
DescribeOrderableDBInstanceOptionsResponse'
{ _dodiorsOrderableDBInstanceOptions = Nothing
, _dodiorsMarker = Nothing
, _dodiorsResponseStatus = pResponseStatus_
}
-- | An OrderableDBInstanceOption structure containing information about
-- orderable options for the DB instance.
dodiorsOrderableDBInstanceOptions :: Lens' DescribeOrderableDBInstanceOptionsResponse [OrderableDBInstanceOption]
dodiorsOrderableDBInstanceOptions = lens _dodiorsOrderableDBInstanceOptions (\ s a -> s{_dodiorsOrderableDBInstanceOptions = a}) . _Default . _Coerce;
-- | An optional pagination token provided by a previous
-- OrderableDBInstanceOptions request. If this parameter is specified, the
-- response includes only records beyond the marker, up to the value
-- specified by 'MaxRecords' .
dodiorsMarker :: Lens' DescribeOrderableDBInstanceOptionsResponse (Maybe Text)
dodiorsMarker = lens _dodiorsMarker (\ s a -> s{_dodiorsMarker = a});
-- | The response status code.
dodiorsResponseStatus :: Lens' DescribeOrderableDBInstanceOptionsResponse Int
dodiorsResponseStatus = lens _dodiorsResponseStatus (\ s a -> s{_dodiorsResponseStatus = a});
| fmapfmapfmap/amazonka | amazonka-rds/gen/Network/AWS/RDS/DescribeOrderableDBInstanceOptions.hs | mpl-2.0 | 9,625 | 0 | 16 | 1,919 | 1,325 | 781 | 544 | 150 | 1 |
-- |
-- Module : $Header$
-- Copyright : (c) 2013-2014 Galois, Inc.
-- License : BSD3
-- Maintainer : cryptol@galois.com
-- Stability : provisional
-- Portability : portable
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Main where
import OptParser
import REPL.Command (loadCmd,loadPrelude)
import REPL.Haskeline
import REPL.Monad (REPL,setREPLTitle,io)
import REPL.Logo
import qualified REPL.Monad as REPL
import Paths_cryptol (version)
import Cryptol.Version (commitHash, commitBranch, commitDirty)
import Data.Version (showVersion)
import Cryptol.Utils.PP(pp)
import Data.Monoid (mconcat)
import System.Environment (getArgs,getProgName)
import System.Exit (exitFailure)
import System.Console.GetOpt
(OptDescr(..),ArgOrder(..),ArgDescr(..),getOpt,usageInfo)
data Options = Options
{ optLoad :: [FilePath]
, optVersion :: Bool
, optHelp :: Bool
, optBatch :: Maybe FilePath
} deriving (Show)
defaultOptions :: Options
defaultOptions = Options
{ optLoad = []
, optVersion = False
, optHelp = False
, optBatch = Nothing
}
options :: [OptDescr (OptParser Options)]
options =
[ Option "b" ["batch"] (ReqArg setBatchScript "FILE")
"run the script provided and exit"
, Option "v" ["version"] (NoArg setVersion)
"display version number"
, Option "h" ["help"] (NoArg setHelp)
"display this message"
]
-- | Set a single file to be loaded. This should be extended in the future, if
-- we ever plan to allow multiple files to be loaded at the same time.
addFile :: String -> OptParser Options
addFile path = modify $ \ opts -> opts { optLoad = [ path ] }
-- | Set a batch script to be run.
setBatchScript :: String -> OptParser Options
setBatchScript path = modify $ \ opts -> opts { optBatch = Just path }
-- | Signal that version should be displayed.
setVersion :: OptParser Options
setVersion = modify $ \ opts -> opts { optVersion = True }
-- | Signal that help should be displayed.
setHelp :: OptParser Options
setHelp = modify $ \ opts -> opts { optHelp = True }
-- | Parse arguments.
parseArgs :: [String] -> Either [String] Options
parseArgs args = case getOpt (ReturnInOrder addFile) options args of
(ps,[],[]) -> runOptParser defaultOptions (mconcat ps)
(_,_,errs) -> Left errs
displayVersion :: IO ()
displayVersion = do
let ver = showVersion version
putStrLn ("Cryptol " ++ ver)
putStrLn ("Git commit " ++ commitHash)
putStrLn (" branch " ++ commitBranch ++ dirtyLab)
where
dirtyLab | commitDirty = " (non-committed files present during build)"
| otherwise = ""
displayHelp :: [String] -> IO ()
displayHelp errs = do
prog <- getProgName
let banner = "Usage: " ++ prog ++ " [OPTIONS]"
putStrLn (usageInfo (concat (errs ++ [banner])) options)
main :: IO ()
main = do
args <- getArgs
case parseArgs args of
Left errs -> do
displayHelp errs
exitFailure
Right opts
| optHelp opts -> displayHelp []
| optVersion opts -> displayVersion
| otherwise -> repl (optBatch opts) (setupREPL opts)
setupREPL :: Options -> REPL ()
setupREPL opts = do
displayLogo True
setREPLTitle
case optLoad opts of
[] -> loadPrelude `REPL.catch` \x -> io $ print $ pp x
[l] -> loadCmd l `REPL.catch` \x -> io $ print $ pp x
_ -> io $ putStrLn "Only one file may be loaded at the command line."
| TomMD/cryptol | cryptol/Main.hs | bsd-3-clause | 3,407 | 0 | 14 | 741 | 989 | 535 | 454 | 81 | 3 |
{-# LANGUAGE TypeFamilies, DataKinds, UndecidableInstances #-}
module T6018failclosed7 where
type family FClosed a b c = (result :: *) | result -> a b c where
FClosed Int Char Bool = Bool
FClosed Char Bool Int = Int
FClosed Bool Int Char = Int
| acowley/ghc | testsuite/tests/typecheck/should_fail/T6018failclosed7.hs | bsd-3-clause | 261 | 0 | 6 | 61 | 66 | 41 | 25 | 6 | 0 |
{-# LANGUAGE OverloadedStrings, RankNTypes #-}
-- | It should be noted that most of the code snippets below depend on the
-- OverloadedStrings language pragma.
--
-- The functions in this module allow an arbitrary monad to be embedded
-- in Scotty's monad transformer stack in order that Scotty be combined
-- with other DSLs.
--
-- Scotty is set up by default for development mode. For production servers,
-- you will likely want to modify 'settings' and the 'defaultHandler'. See
-- the comments on each of these functions for more information.
module Web.Scotty.Trans
( -- * scotty-to-WAI
scottyT, scottyAppT, scottyOptsT, scottySocketT, Options(..)
-- * Defining Middleware and Routes
--
-- | 'Middleware' and routes are run in the order in which they
-- are defined. All middleware is run first, followed by the first
-- route that matches. If no route matches, a 404 response is given.
, middleware, get, post, put, delete, patch, options, addroute, matchAny, notFound
-- ** Route Patterns
, capture, regex, function, literal
-- ** Accessing the Request, Captures, and Query Parameters
, request, header, headers, body, bodyReader, param, params, jsonData, files
-- ** Modifying the Response and Redirecting
, status, addHeader, setHeader, redirect
-- ** Setting Response Body
--
-- | Note: only one of these should be present in any given route
-- definition, as they completely replace the current 'Response' body.
, text, html, file, json, stream, raw
-- ** Exceptions
, raise, rescue, next, defaultHandler, ScottyError(..)
-- * Parsing Parameters
, Param, Parsable(..), readEither
-- * Types
, RoutePattern, File
-- * Monad Transformers
, ScottyT, ActionT
) where
import Blaze.ByteString.Builder (fromByteString)
import Control.Monad (when)
import Control.Monad.State (execState, modify)
import Control.Monad.IO.Class
import Data.Default.Class (def)
import Network (Socket)
import Network.HTTP.Types (status404, status500)
import Network.Wai
import Network.Wai.Handler.Warp (Port, runSettings, runSettingsSocket, setPort, getPort)
import Web.Scotty.Action
import Web.Scotty.Route
import Web.Scotty.Internal.Types hiding (Application, Middleware)
import Web.Scotty.Util (socketDescription)
import qualified Web.Scotty.Internal.Types as Scotty
-- | Run a scotty application using the warp server.
-- NB: scotty p === scottyT p id
scottyT :: (Monad m, MonadIO n)
=> Port
-> (m Response -> IO Response) -- ^ Run monad 'm' into 'IO', called at each action.
-> ScottyT e m ()
-> n ()
scottyT p = scottyOptsT $ def { settings = setPort p (settings def) }
-- | Run a scotty application using the warp server, passing extra options.
-- NB: scottyOpts opts === scottyOptsT opts id
scottyOptsT :: (Monad m, MonadIO n)
=> Options
-> (m Response -> IO Response) -- ^ Run monad 'm' into 'IO', called at each action.
-> ScottyT e m ()
-> n ()
scottyOptsT opts runActionToIO s = do
when (verbose opts > 0) $
liftIO $ putStrLn $ "Setting phasers to stun... (port " ++ show (getPort (settings opts)) ++ ") (ctrl-c to quit)"
liftIO . runSettings (settings opts) =<< scottyAppT runActionToIO s
-- | Run a scotty application using the warp server, passing extra options, and
-- listening on the provided socket.
-- NB: scottySocket opts sock === scottySocketT opts sock id
scottySocketT :: (Monad m, MonadIO n)
=> Options
-> Socket
-> (m Response -> IO Response)
-> ScottyT e m ()
-> n ()
scottySocketT opts sock runActionToIO s = do
when (verbose opts > 0) $ do
d <- liftIO $ socketDescription sock
liftIO $ putStrLn $ "Setting phasers to stun... (" ++ d ++ ") (ctrl-c to quit)"
liftIO . runSettingsSocket (settings opts) sock =<< scottyAppT runActionToIO s
-- | Turn a scotty application into a WAI 'Application', which can be
-- run with any WAI handler.
-- NB: scottyApp === scottyAppT id
scottyAppT :: (Monad m, Monad n)
=> (m Response -> IO Response) -- ^ Run monad 'm' into 'IO', called at each action.
-> ScottyT e m ()
-> n Application
scottyAppT runActionToIO defs = do
let s = execState (runS defs) def
let rapp req callback = runActionToIO (foldl (flip ($)) notFoundApp (routes s) req) >>= callback
return $ foldl (flip ($)) rapp (middlewares s)
notFoundApp :: Monad m => Scotty.Application m
notFoundApp _ = return $ responseBuilder status404 [("Content-Type","text/html")]
$ fromByteString "<h1>404: File Not Found!</h1>"
-- | Global handler for uncaught exceptions.
--
-- Uncaught exceptions normally become 500 responses.
-- You can use this to selectively override that behavior.
--
-- Note: IO exceptions are lifted into 'ScottyError's by 'stringError'.
-- This has security implications, so you probably want to provide your
-- own defaultHandler in production which does not send out the error
-- strings as 500 responses.
defaultHandler :: (ScottyError e, Monad m) => (e -> ActionT e m ()) -> ScottyT e m ()
defaultHandler f = ScottyT $ modify $ addHandler $ Just (\e -> status status500 >> f e)
-- | Use given middleware. Middleware is nested such that the first declared
-- is the outermost middleware (it has first dibs on the request and last action
-- on the response). Every middleware is run on each request.
middleware :: Middleware -> ScottyT e m ()
middleware = ScottyT . modify . addMiddleware
| bitemyapp/scotty | Web/Scotty/Trans.hs | bsd-3-clause | 5,631 | 0 | 15 | 1,258 | 1,100 | 621 | 479 | 68 | 1 |
{-# OPTIONS_GHC -Wall #-}
module Canonicalize.Variable where
import qualified Data.Either as Either
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified AST.Helpers as Help
import qualified AST.Module as Module
import qualified AST.Type as Type
import qualified AST.Variable as Var
import qualified Reporting.Annotation as A
import qualified Reporting.Error.Canonicalize as Error
import qualified Reporting.Region as R
import qualified Canonicalize.Environment as Env
import qualified Canonicalize.Result as Result
import Elm.Utils ((|>))
variable :: R.Region -> Env.Environment -> String -> Result.ResultErr Var.Canonical
variable region env var =
case toVarName var of
Right (name, varName)
| Module.nameIsNative name ->
Result.var (Var.Canonical (Var.Module name) varName)
_ ->
case Set.toList `fmap` Map.lookup var (Env._values env) of
Just [v] ->
Result.var v
Just vs ->
preferLocals region env "variable" vs var
Nothing ->
notFound region "variable" (Map.keys (Env._values env)) var
tvar
:: R.Region
-> Env.Environment
-> String
-> Result.ResultErr
(Either
Var.Canonical
(Var.Canonical, [String], Type.Canonical)
)
tvar region env var =
case adts ++ aliases of
[] -> notFound region "type" (Map.keys (Env._adts env) ++ Map.keys (Env._aliases env)) var
[v] -> Result.var' extract v
vs -> preferLocals' region env extract "type" vs var
where
adts =
map Left (maybe [] Set.toList (Map.lookup var (Env._adts env)))
aliases =
map Right (maybe [] Set.toList (Map.lookup var (Env._aliases env)))
extract value =
case value of
Left v -> v
Right (v,_,_) -> v
pvar
:: R.Region
-> Env.Environment
-> String
-> Int
-> Result.ResultErr Var.Canonical
pvar region env var actualArgs =
case Set.toList `fmap` Map.lookup var (Env._patterns env) of
Just [value] ->
foundArgCheck value
Just values ->
preferLocals' region env fst "pattern" values var
`Result.andThen` foundArgCheck
Nothing ->
notFound region "pattern" (Map.keys (Env._patterns env)) var
where
foundArgCheck (name, expectedArgs) =
if actualArgs == expectedArgs
then Result.var name
else Result.err (A.A region (Error.argMismatch name expectedArgs actualArgs))
-- FOUND
preferLocals
:: R.Region
-> Env.Environment
-> String
-> [Var.Canonical]
-> String
-> Result.ResultErr Var.Canonical
preferLocals region env =
preferLocals' region env id
preferLocals'
:: R.Region
-> Env.Environment
-> (a -> Var.Canonical)
-> String
-> [a]
-> String
-> Result.ResultErr a
preferLocals' region env extract kind possibilities var =
case filter (isLocal . extract) possibilities of
[] ->
ambiguous possibilities
[v] ->
Result.var' extract v
locals ->
ambiguous locals
where
isLocal :: Var.Canonical -> Bool
isLocal (Var.Canonical home _) =
case home of
Var.Local -> True
Var.BuiltIn -> False
Var.Module name ->
name == Env._home env
ambiguous possibleVars =
Result.err (A.A region (Error.variable kind var Error.Ambiguous vars))
where
vars = map (Var.toString . extract) possibleVars
-- NOT FOUND HELPERS
type VarName =
Either String (Module.Name, String)
toVarName :: String -> VarName
toVarName var =
case Help.splitDots var of
[x] -> Left x
xs -> Right (init xs, last xs)
noQualifier :: VarName -> String
noQualifier name =
case name of
Left x -> x
Right (_, x) -> x
qualifiedToString :: (Module.Name, String) -> String
qualifiedToString (modul, name) =
Module.nameToString (modul ++ [name])
isOp :: VarName -> Bool
isOp name =
Help.isOp (noQualifier name)
-- NOT FOUND
notFound :: R.Region -> String -> [String] -> String -> Result.ResultErr a
notFound region kind possibilities var =
let name =
toVarName var
possibleNames =
map toVarName possibilities
(problem, suggestions) =
case name of
Left _ ->
exposedProblem name possibleNames
Right (modul, varName) ->
qualifiedProblem modul varName (Either.rights possibleNames)
in
Result.err (A.A region (Error.variable kind var problem suggestions))
exposedProblem :: VarName -> [VarName] -> (Error.VarProblem, [String])
exposedProblem name possibleNames =
let (exposed, qualified) =
possibleNames
|> filter (\n -> isOp name == isOp n)
|> Error.nearbyNames noQualifier name
|> Either.partitionEithers
in
( Error.ExposedUnknown
, exposed ++ map qualifiedToString qualified
)
qualifiedProblem
:: Module.Name
-> String
-> [(Module.Name, String)]
-> (Error.VarProblem, [String])
qualifiedProblem moduleName name allQualified =
let availableModules =
Set.fromList (map fst allQualified)
moduleNameString =
Module.nameToString moduleName
in
case Set.member moduleName availableModules of
True ->
( Error.QualifiedUnknown moduleNameString name
, allQualified
|> filter ((==) moduleName . fst)
|> map snd
|> Error.nearbyNames id name
)
False ->
( Error.UnknownQualifier moduleNameString name
, Set.toList availableModules
|> map Module.nameToString
|> Error.nearbyNames id moduleNameString
) | JoeyEremondi/elm-summer-opt | src/Canonicalize/Variable.hs | bsd-3-clause | 5,839 | 0 | 17 | 1,704 | 1,783 | 925 | 858 | 166 | 5 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
---------------------------------------------------------
-- |
-- Module : Network.Wai.Middleware.Jsonp
-- Copyright : Michael Snoyman
-- License : BSD3
--
-- Maintainer : Michael Snoyman <michael@snoyman.com>
-- Stability : Unstable
-- Portability : portable
--
-- Automatic wrapping of JSON responses to convert into JSONP.
--
---------------------------------------------------------
module Network.Wai.Middleware.Jsonp (jsonp) where
import Network.Wai
import Network.Wai.Internal
import Data.ByteString (ByteString)
import qualified Data.ByteString.Char8 as B8
import Blaze.ByteString.Builder (Builder, copyByteString)
import Blaze.ByteString.Builder.Char8 (fromChar)
import Data.Monoid (mappend)
import Control.Monad (join)
import Data.Maybe (fromMaybe)
import qualified Data.ByteString as S
import Data.CaseInsensitive (CI)
import Network.HTTP.Types (Status)
-- | Wrap json responses in a jsonp callback.
--
-- Basically, if the user requested a \"text\/javascript\" and supplied a
-- \"callback\" GET parameter, ask the application for an
-- \"application/json\" response, then convert that into a JSONP response,
-- having a content type of \"text\/javascript\" and calling the specified
-- callback function.
jsonp :: Middleware
jsonp app env sendResponse = do
let accept = fromMaybe B8.empty $ lookup "Accept" $ requestHeaders env
let callback :: Maybe B8.ByteString
callback =
if B8.pack "text/javascript" `B8.isInfixOf` accept
then join $ lookup "callback" $ queryString env
else Nothing
let env' =
case callback of
Nothing -> env
Just _ -> env
{ requestHeaders = changeVal "Accept"
"application/json"
$ requestHeaders env
}
app env' $ \res ->
case callback of
Nothing -> sendResponse res
Just c -> go c res
where
go c r@(ResponseBuilder s hs b) =
sendResponse $ case checkJSON hs of
Nothing -> r
Just hs' -> responseBuilder s hs' $
copyByteString c
`mappend` fromChar '('
`mappend` b
`mappend` fromChar ')'
go c r =
case checkJSON hs of
Just hs' -> addCallback c s hs' wb
Nothing -> sendResponse r
where
(s, hs, wb) = responseToStream r
checkJSON hs =
case lookup "Content-Type" hs of
Just x
| B8.pack "application/json" `S.isPrefixOf` x ->
Just $ fixHeaders hs
_ -> Nothing
fixHeaders = changeVal "Content-Type" "text/javascript"
addCallback cb s hs wb =
wb $ \body -> sendResponse $ responseStream s hs $ \sendChunk flush -> do
sendChunk $ copyByteString cb `mappend` fromChar '('
body sendChunk flush
sendChunk $ fromChar ')'
changeVal :: Eq a
=> a
-> ByteString
-> [(a, ByteString)]
-> [(a, ByteString)]
changeVal key val old = (key, val)
: filter (\(k, _) -> k /= key) old
| beni55/wai | wai-extra/Network/Wai/Middleware/Jsonp.hs | mit | 3,301 | 0 | 16 | 1,032 | 725 | 389 | 336 | 66 | 8 |
{-# LANGUAGE Safe #-}
-----------------------------------------------------------------------------
-- |
-- Module : Control.Monad.ST.Strict
-- Copyright : (c) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : libraries@haskell.org
-- Stability : provisional
-- Portability : non-portable (requires universal quantification for runST)
--
-- The strict ST monad (re-export of "Control.Monad.ST")
--
-----------------------------------------------------------------------------
module Control.Monad.ST.Strict (
module Control.Monad.ST
) where
import Control.Monad.ST
| rahulmutt/ghcvm | libraries/base/Control/Monad/ST/Strict.hs | bsd-3-clause | 659 | 0 | 5 | 99 | 37 | 30 | 7 | 4 | 0 |
module E1 where
data BTree a
= Empty | T a (BTree a) (BTree a) deriving Show
buildtree :: Ord a => [a] -> BTree a
buildtree [] = Empty
buildtree ((x : xs)) = insert x (buildtree xs)
insert :: Ord a => a -> (BTree a) -> BTree a
insert val Empty = T val Empty Empty
insert val (t@(T tval left right))
| val > tval = T tval left (insert val right)
| otherwise = t
main :: BTree Int
main = buildtree [3, 1, 2]
| kmate/HaRe | old/testing/asPatterns/E1AST.hs | bsd-3-clause | 431 | 0 | 9 | 115 | 228 | 117 | 111 | 13 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Elm.Compiler.Type
( Type(..)
, toString
) where
import Control.Applicative ((<$>), (<*>))
import Control.Arrow (second)
import Data.Aeson ((.:))
import qualified Data.Aeson as Json
import qualified Data.Aeson.Types as Json
import qualified Data.ByteString.Lazy.Char8 as BS
import qualified Data.Text as Text
import Text.PrettyPrint as P
import qualified AST.Helpers as Help
import qualified AST.Type as Type
import qualified AST.Variable as Var
import qualified Parse.Helpers as Parse
import qualified Parse.Type as Type
import qualified Reporting.Annotation as A
data Type
= Lambda Type Type
| Var String
| Type String
| App Type [Type]
| Record [(String, Type)] (Maybe Type)
-- TO STRING
data Context = None | ADT | Function
toString :: Type -> String
toString tipe =
P.render (toDoc None tipe)
toDoc :: Context -> Type -> P.Doc
toDoc context tipe =
case tipe of
Lambda _ _ ->
let t:ts =
map (toDoc Function) (collectLambdas tipe)
lambda =
P.sep [ t, P.sep (map (P.text "->" <+>) ts) ]
in
case context of
None -> lambda
_ -> P.parens lambda
Var name ->
P.text name
Type name ->
P.text (if name == "_Tuple0" then "()" else name)
App (Type name) args
| Help.isTuple name ->
P.sep
[ P.cat (zipWith (<+>) (P.lparen : repeat P.comma) (map (toDoc None) args))
, P.rparen
]
| otherwise ->
let adt = P.hang (P.text name) 2 (P.sep $ map (toDoc ADT) args)
in
case (context, args) of
(ADT, _ : _) -> P.parens adt
_ -> adt
App _ _ ->
error $
"Somehow ended up with an unexpected type, please post a minimal example that\n"
++ "reproduces this error to <https://github.com/elm-lang/elm-compiler/issues>"
Record _ _ ->
case flattenRecord tipe of
([], Nothing) ->
P.text "{}"
(fields, Nothing) ->
P.sep
[ P.cat (zipWith (<+>) (P.lbrace : repeat P.comma) (map prettyField fields))
, P.rbrace
]
(fields, Just x) ->
P.hang
(P.lbrace <+> P.text x <+> P.text "|")
4
(P.sep
[ P.sep (P.punctuate P.comma (map prettyField fields))
, P.rbrace
]
)
where
prettyField (field, tipe) =
P.text field <+> P.text ":" <+> toDoc None tipe
collectLambdas :: Type -> [Type]
collectLambdas tipe =
case tipe of
Lambda arg body -> arg : collectLambdas body
_ -> [tipe]
flattenRecord :: Type -> ( [(String, Type)], Maybe String )
flattenRecord tipe =
case tipe of
Var x -> ([], Just x)
Record fields Nothing -> (fields, Nothing)
Record fields (Just ext) ->
let (fields',ext') = flattenRecord ext
in
(fields' ++ fields, ext')
_ -> error "Trying to flatten ill-formed record."
-- JSON for TYPE
instance Json.ToJSON Type where
toJSON tipe =
Json.String (Text.unwords (Text.words (Text.pack (toString tipe))))
instance Json.FromJSON Type where
parseJSON value =
let
failure _ =
fail $
"Trying to decode a type string, but could not handle this value:\n"
++ BS.unpack (Json.encode value)
in
case value of
Json.String text ->
either failure (return . fromRawType)
(Parse.iParse Type.expr (Text.unpack text))
Json.Object obj ->
fromObject obj
_ ->
failure ()
fromObject :: Json.Object -> Json.Parser Type
fromObject obj =
do tag <- obj .: "tag"
case (tag :: String) of
"lambda" ->
Lambda <$> obj .: "in" <*> obj .: "out"
"var" ->
Var <$> obj .: "name"
"type" ->
Type <$> obj .: "name"
"app" ->
App <$> obj .: "func" <*> obj .: "args"
"record" ->
Record <$> obj .: "fields" <*> obj .: "extension"
_ ->
fail $ "Error when decoding type with tag: " ++ tag
fromRawType :: Type.Raw -> Type
fromRawType (A.A _ astType) =
case astType of
Type.RLambda t1 t2 ->
Lambda (fromRawType t1) (fromRawType t2)
Type.RVar x ->
Var x
Type.RType var ->
Type (Var.toString var)
Type.RApp t ts ->
App (fromRawType t) (map fromRawType ts)
Type.RRecord fields ext ->
Record (map (second fromRawType) fields) (fmap fromRawType ext)
| pairyo/elm-compiler | src/Elm/Compiler/Type.hs | bsd-3-clause | 4,835 | 0 | 19 | 1,747 | 1,540 | 803 | 737 | 135 | 11 |
{-# LANGUAGE TypeFamilies #-}
module Tc265 where
data T a = MkT (F a)
type family F a where
F (T a) = a
F (T Int) = Bool
| ezyang/ghc | testsuite/tests/typecheck/should_compile/tc265.hs | bsd-3-clause | 127 | 0 | 8 | 35 | 56 | 32 | 24 | 6 | 0 |
{-# LANGUAGE Safe #-}
{-# LANGUAGE NoImplicitPrelude #-}
module ImpSafe01 ( MyWord ) where
-- While Data.Word is safe it imports trustworthy
-- modules in base, hence base needs to be trusted.
-- Note: Worthwhile giving out better error messages for cases
-- like this if I can.
import Data.Word
type MyWord = Word
| ghc-android/ghc | testsuite/tests/safeHaskell/check/pkg01/ImpSafe01.hs | bsd-3-clause | 318 | 0 | 4 | 57 | 26 | 19 | 7 | 5 | 0 |
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE MagicHash, NoImplicitPrelude, UnboxedTuples, UnliftedFFITypes #-}
module GHC.Debug ( debugLn, debugErrLn ) where
import GHC.Prim
import GHC.Types
import GHC.Tuple ()
debugLn :: [Char] -> IO ()
debugLn xs = IO (\s0 ->
case mkMBA s0 xs of
(# s1, mba #) ->
case c_debugLn mba of
IO f -> f s1)
debugErrLn :: [Char] -> IO ()
debugErrLn xs = IO (\s0 ->
case mkMBA s0 xs of
(# s1, mba #) ->
case c_debugErrLn mba of
IO f -> f s1)
foreign import ccall unsafe "debugLn"
c_debugLn :: MutableByteArray# RealWorld -> IO ()
foreign import ccall unsafe "debugErrLn"
c_debugErrLn :: MutableByteArray# RealWorld -> IO ()
mkMBA :: State# RealWorld -> [Char] ->
(# State# RealWorld, MutableByteArray# RealWorld #)
mkMBA s0 xs = -- Start with 1 so that we have space to put in a \0 at
-- the end
case len 1# xs of
l ->
case newByteArray# l s0 of
(# s1, mba #) ->
case write mba 0# xs s1 of
s2 -> (# s2, mba #)
where len l [] = l
len l (_ : xs') = len (l +# 1#) xs'
write mba offset [] s = writeCharArray# mba offset '\0'# s
write mba offset (C# x : xs') s
= case writeCharArray# mba offset x s of
s' ->
write mba (offset +# 1#) xs' s'
| urbanslug/ghc | libraries/ghc-prim/GHC/Debug.hs | bsd-3-clause | 1,554 | 0 | 14 | 625 | 464 | 236 | 228 | 38 | 3 |
{-# LANGUAGE BangPatterns, DeriveDataTypeable, FlexibleInstances, MultiParamTypeClasses #-}
module MachineLearning.Protobufs.TrainingStatus (TrainingStatus(..)) where
import Prelude ((+), (/), (.))
import qualified Prelude as Prelude'
import qualified Data.Typeable as Prelude'
import qualified Data.Data as Prelude'
import qualified Text.ProtocolBuffers.Header as P'
data TrainingStatus = UNCLAIMED
| PROCESSING
| FINISHED
deriving (Prelude'.Read, Prelude'.Show, Prelude'.Eq, Prelude'.Ord, Prelude'.Typeable, Prelude'.Data)
instance P'.Mergeable TrainingStatus
instance Prelude'.Bounded TrainingStatus where
minBound = UNCLAIMED
maxBound = FINISHED
instance P'.Default TrainingStatus where
defaultValue = UNCLAIMED
toMaybe'Enum :: Prelude'.Int -> P'.Maybe TrainingStatus
toMaybe'Enum 1 = Prelude'.Just UNCLAIMED
toMaybe'Enum 2 = Prelude'.Just PROCESSING
toMaybe'Enum 3 = Prelude'.Just FINISHED
toMaybe'Enum _ = Prelude'.Nothing
instance Prelude'.Enum TrainingStatus where
fromEnum UNCLAIMED = 1
fromEnum PROCESSING = 2
fromEnum FINISHED = 3
toEnum
= P'.fromMaybe (Prelude'.error "hprotoc generated code: toEnum failure for type MachineLearning.Protobufs.TrainingStatus") .
toMaybe'Enum
succ UNCLAIMED = PROCESSING
succ PROCESSING = FINISHED
succ _ = Prelude'.error "hprotoc generated code: succ failure for type MachineLearning.Protobufs.TrainingStatus"
pred PROCESSING = UNCLAIMED
pred FINISHED = PROCESSING
pred _ = Prelude'.error "hprotoc generated code: pred failure for type MachineLearning.Protobufs.TrainingStatus"
instance P'.Wire TrainingStatus where
wireSize ft' enum = P'.wireSize ft' (Prelude'.fromEnum enum)
wirePut ft' enum = P'.wirePut ft' (Prelude'.fromEnum enum)
wireGet 14 = P'.wireGetEnum toMaybe'Enum
wireGet ft' = P'.wireGetErr ft'
wireGetPacked 14 = P'.wireGetPackedEnum toMaybe'Enum
wireGetPacked ft' = P'.wireGetErr ft'
instance P'.GPB TrainingStatus
instance P'.MessageAPI msg' (msg' -> TrainingStatus) TrainingStatus where
getVal m' f' = f' m'
instance P'.ReflectEnum TrainingStatus where
reflectEnum = [(1, "UNCLAIMED", UNCLAIMED), (2, "PROCESSING", PROCESSING), (3, "FINISHED", FINISHED)]
reflectEnumInfo _
= P'.EnumInfo (P'.makePNF (P'.pack ".protobufs.TrainingStatus") ["MachineLearning"] ["Protobufs"] "TrainingStatus")
["MachineLearning", "Protobufs", "TrainingStatus.hs"]
[(1, "UNCLAIMED"), (2, "PROCESSING"), (3, "FINISHED")] | ajtulloch/haskell-ml | MachineLearning/Protobufs/TrainingStatus.hs | mit | 2,508 | 0 | 11 | 404 | 630 | 342 | 288 | 51 | 1 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE ScopedTypeVariables #-}
-- | A module for decoding an elm-package.json structure.
module Data.ElmPackage where
import ClassyPrelude
import Data.Aeson
import Data.PersistSemVer ()
import Data.Range
import Data.SemVer (Version)
import Network.URI
data ElmPackage = ElmPackage
{ elmPackageVersion :: Version
, elmPackageSummary :: Text
, elmPackageRepository :: Text
, elmPackageLicense :: Text
, elmPackageSourceDirectories :: [Text]
, elmPackageModules :: [Text]
, elmPackageNativeModules :: Bool
, elmPackageDependencies :: Map Text (Range Version)
-- Not all pacakges specify this ... perhaps it wasn't
-- required at one point?
, elmPackageElmVersion :: Maybe (Range Version)
} deriving (Eq, Show)
instance FromJSON ElmPackage where
parseJSON =
withObject "Elm Package" $ \v -> do
elmPackageVersion <- v .: "version"
elmPackageSummary <- v .: "summary"
elmPackageRepository <- v .: "repository"
elmPackageLicense <- v .: "license"
elmPackageModules <- v .: "exposed-modules"
elmPackageDependencies <- v .: "dependencies"
elmPackageElmVersion <- v .:? "elm-version"
elmPackageSourceDirectories <- v .: "source-directories"
elmPackageNativeModules <- v .:? "native-modules" .!= False
pure ElmPackage {..}
elmPackageLibraryName :: ElmPackage -> Maybe Text
elmPackageLibraryName = gitUrlToLibraryName . elmPackageRepository
libraryNameToGitUrl :: Text -> Text
libraryNameToGitUrl libraryName = "https://github.com/" <> libraryName <> ".git"
gitUrlToLibraryName :: Text -> Maybe Text
gitUrlToLibraryName gitUrl = do
uri <- parseAbsoluteURI $ unpack gitUrl
stripSuffix ".git" (pack $ uriPath uri) >>= stripPrefix "/"
| rgrempel/frelm.org | src/Data/ElmPackage.hs | mit | 1,993 | 0 | 12 | 421 | 395 | 211 | 184 | 45 | 1 |
module Main where
is_palindrome :: Int -> Bool
is_palindrome n = reverse (show n) == show n
max_product_palindrome :: [(Int, Int)] -> Int -> Int
max_product_palindrome [] high = high
max_product_palindrome (x:xs) high
| is_palindrome canidate &&
canidate > high = max_product_palindrome xs canidate
| otherwise = max_product_palindrome xs high
where
canidate = fst x * snd x
main =
do
print(max_product_palindrome [(x, y) | x <- [100..999], y <- [x..999]] 0)
| tijko/Project-Euler | haskell_1-10/Euler_4.hs | mit | 518 | 0 | 13 | 131 | 195 | 99 | 96 | 13 | 1 |
module Y2017.M05.D23.Exercise where
import Data.Map (Map)
import Data.Set (Set)
-- below imports available via 1HaskellADay git repository
import Y2017.M05.D22.Exercise
{--
So I wished to analyze terror attack, in which country and for which intent.
Wikidata is all over the map in this, having categories that are not unified
by any class, and calling the same thing many different things: 'terror(ist)
attack' is not a category, but 'suicide bomber' is, which has nothing to do
with some of the recent modi of terrorists: using everyday tools or vehicles
to inflict death, dismemberment, and destruction.
Even 'death' is not a wikidata category, but 'homicide' is, but not all
terrorist deaths are considered homicides, as they may be considered 'collateral
damage' to the intended attack.
And, as the media are quick to say 'do not label this as terrorism' giving
reasons that 'the driver was intoxicated,' when the driver tested 0.0 on a
Blood-Alcohol test (BAC/Blood-Alcohol Content), the data become muddled by
punditry.
All this is a suffix to the terrorist attack in Manchester, England, and, here,
a prefix to say that data science and data analytics is not straightforward
when the topics being analyzed are devisive, such as: poverty statistics, crime
by race, wages by gender, or terrorism.
So, wikidata: some topics are well-categorized and populated, some are scatter-
shot or woefully under- or mis-represented (example: do a SPARQL query to
get the populations of cities in the US State of Alaska: you get less than 10
results as of 2017-05-01, but there are over 144 cities on the wikipedia page
"List of Cities and their populations in Alaska").
What data sources do you use in your data analytics? There is the opendata.gov
project headed up by Princeton, I believe, but I am not familiar with that
interface and every query I've submitted to that system has returned in a
'no result' or 'page not found'-error. That's discouraging. Do you have good
data sources I can poll?
Today's Haskell problem. Back to languages.
Given the list of languages (including their language-roots and number of
speakers) extracted from wikidata yesterday, compute:
1. the number of roots for the answer-set
2. The number of roots YOUR language has (list them)
3. The number of languages each root has
4. The root that has the most languages. What are they?
--}
type Root = String
languageRoots :: [Language] -> Set Root
languageRoots langs = undefined
languageRootsOf :: [Language] -> String -> [Root]
languageRootsOf langs myLang = undefined
languageTree :: [Language] -> Map Root [Language]
languageTree langs = undefined
languageTrunk :: Map Root [Language] -> (Root, [Language])
languageTrunk langTree = undefined
| geophf/1HaskellADay | exercises/HAD/Y2017/M05/D23/Exercise.hs | mit | 2,742 | 0 | 7 | 458 | 157 | 91 | 66 | 13 | 1 |
{-# OPTIONS -Wall #-}
{-# LANGUAGE NamedFieldPuns #-}
import Helpers.Parse
import Text.Parsec
data Command = Forward Int | Down Int | Up Int
deriving (Show)
data Position = Position {horizontal :: Int, depth :: Int, aim :: Int}
deriving (Show)
main :: IO ()
main = do
commands <- parseInput
let Position {horizontal, depth} = foldl move initialPosition commands
let answer = horizontal * depth
print answer
initialPosition :: Position
initialPosition = Position {horizontal = 0, depth = 0, aim = 0}
move :: Position -> Command -> Position
move position (Forward n) =
position
{ horizontal = horizontal position + n,
depth = depth position + aim position * n
}
move position (Up n) = position {aim = aim position - n}
move position (Down n) = position {aim = aim position + n}
parseInput :: IO [Command]
parseInput = parseLinesIO $ do
constructor <-
try (string "forward" >> pure Forward)
<|> try (string "down" >> pure Down)
<|> try (string "up" >> pure Up)
_ <- many1 space
amount <- read <$> many1 digit
return $ constructor amount
| SamirTalwar/advent-of-code | 2021/AOC_02_2.hs | mit | 1,093 | 11 | 14 | 240 | 426 | 212 | 214 | 32 | 1 |
-- | Utilities for pretty printing.
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE UnicodeSyntax #-}
module Apia.Utils.PrettyPrint
( module Text.PrettyPrint.HughesPJ
, cquotes
, Pretty(pretty)
, prettyShow
, scquotes
, spaces
, sspaces
) where
------------------------------------------------------------------------------
import Apia.Prelude
import Text.PrettyPrint.HughesPJ
------------------------------------------------------------------------------
-- Auxiliary functions
-- | Wrap a document in curly quotes (‘...’).
cquotes ∷ Doc → Doc
cquotes d = char '‘' <> d <> char '’'
-- | Wrap a document in spaces.
spaces ∷ Doc → Doc
spaces d = space <> d <> space
-- | Wrap a string in ‘...’.
scquotes ∷ String → Doc
scquotes = cquotes . text
-- | Wrap a string in spaces.
sspaces ∷ String → Doc
sspaces = spaces . text
-- | Use instead of 'show' when printing to world.
prettyShow :: Pretty a ⇒ a → String
prettyShow = render . pretty
------------------------------------------------------------------------------
-- | Pretty print type class.
class Pretty a where
pretty ∷ a → Doc
instance Pretty Doc where
pretty = id
instance Pretty String where
pretty = text
| asr/apia | src/Apia/Utils/PrettyPrint.hs | mit | 1,243 | 0 | 7 | 214 | 223 | 130 | 93 | 31 | 1 |
module Zwerg.Data.UUIDMap
( UUIDMap
, getMinimumUUIDs
, toUUIDSet
) where
import Zwerg.Prelude
import Zwerg.Data.UUIDSet (UUIDSet)
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IM
import Data.Maybe (fromJust)
newtype UUIDMap a = MkUUIDMap (IntMap a)
deriving stock (Functor, Generic)
deriving anyclass Binary
instance ZDefault (UUIDMap a) where
zDefault = MkUUIDMap IM.empty
instance ZEmptiable (UUIDMap a) where
zIsNull (MkUUIDMap m) = IM.null m
zSize (MkUUIDMap m) = IM.size m
instance ZMapContainer UUIDMap UUID where
zModifyAt f uuid (MkUUIDMap m) = MkUUIDMap $ IM.adjust f (unwrap uuid) m
zElems (MkUUIDMap m) = IM.elems m
instance ZIncompleteMapContainer UUIDMap UUID where
zLookup uuid (MkUUIDMap m) = IM.lookup (unwrap uuid) m
zInsert uuid val (MkUUIDMap m) = MkUUIDMap $ IM.insert (unwrap uuid) val m
zRemoveAt uuid (MkUUIDMap m) = MkUUIDMap $ IM.delete (unwrap uuid) m
zContains uuid (MkUUIDMap m) = IM.member (unwrap uuid) m
zKeys (MkUUIDMap m) = (catMaybes . map wrap) $ IM.keys m
instance ZFilterable (UUIDMap a) (UUID, a) where
zFilter f (MkUUIDMap m) = MkUUIDMap $ IM.filterWithKey (\x -> curry f (fromJust $ wrap x)) m
zFilterM f (MkUUIDMap m) = (MkUUIDMap . IM.fromAscList)
<$> (filterM (\(x,a) -> f (unsafeWrap x, a)) $ IM.toAscList m)
getMinimumUUIDs :: (Ord a, Bounded a) => UUIDMap a -> (a, [UUID])
getMinimumUUIDs (MkUUIDMap um) =
let (amin, ids) = IM.foldrWithKey f (minBound, []) um
in (amin, ) $ map unsafeWrap ids
where
f uuid x (_, []) = (x, [uuid])
f uuid x (xmin, uuids) =
if | x == xmin -> (x, uuid : uuids)
| x < xmin -> (x, [uuid])
| otherwise -> (xmin, uuids)
{-# INLINABLE toUUIDSet #-}
toUUIDSet :: UUIDMap a -> UUIDSet
toUUIDSet m = unsafeWrap $ zKeys m
| zmeadows/zwerg | lib/Zwerg/Data/UUIDMap.hs | mit | 1,873 | 0 | 14 | 432 | 787 | 413 | 374 | -1 | -1 |
module Cenary.EvmAPI.OpcodeM where
import Cenary.EvmAPI.Instruction
import Cenary.EvmAPI.Program
import Cenary.Codegen.Evm
import Cenary.Codegen.CodegenState
import Control.Lens
-- | Class of monads that can run opcodes
class Monad m => OpcodeM m where
op :: Instruction -> m ()
instance OpcodeM Evm where
op instr = do
let (_, cost) = toOpcode instr
pc += cost
program %= (addInstr instr)
| yigitozkavci/ivy | src/Cenary/EvmAPI/OpcodeM.hs | mit | 410 | 0 | 11 | 76 | 122 | 65 | 57 | 13 | 0 |
module Hablog.Data.Entry
( updateHtml
) where
import Hablog.Data.Persist
import Hablog.Data.Markup
import Text.Pandoc
updateHtml :: Entry -> Entry
updateHtml entry =
let html = convertToHtml (entryMarkupEngine entry) (entryMarkup entry)
in entry { entryHtml = html }
| garrettpauls/Hablog | src/Hablog/Data/Entry.hs | mit | 275 | 0 | 11 | 43 | 82 | 46 | 36 | 9 | 1 |
primes :: [Int]
primes = sieve $ [2..]
sieve :: [Int] -> [Int]
sieve (p:s) = p:sieve [n | n <- s, n `mod` p /= 0]
reverseInt :: Int -> Int
reverseInt = read . reverse . show
mirp :: [Int]
mirp = filter (\p -> let r = reverseInt p in r `elem` primes) primes
main = print $ take 2 mirp
| kdungs/coursework-functional-programming | 06/mirp.hs | mit | 289 | 1 | 12 | 69 | 184 | 93 | 91 | 9 | 1 |
{-# OPTIONS_GHC -Wall #-}
module GenExercises where
import Test.QuickCheck
data Fool =
Fulse
| Frue
deriving (Eq, Show)
-- Ex1:
-- Equal probabilities for each.
equalProbability :: Gen Fool
equalProbability = do
oneof [return Fulse, return Frue]
-- Ex2:
-- 2/3s chance of Fulse, 1/3 chance of Frue.
unEqualProbability :: Gen Fool
unEqualProbability = do
oneof [return Fulse, return Fulse, return Frue]
unEqualProbability2 :: Gen Fool
unEqualProbability2 = do
frequency [(2, return Fulse), (1, return Frue)]
| NickAger/LearningHaskell | HaskellProgrammingFromFirstPrinciples/Chapter14.hsproj/GenExercises.hs | mit | 536 | 0 | 10 | 105 | 146 | 79 | 67 | 16 | 1 |
{-| Unittest runner for ganeti-htools.
-}
{-
Copyright (C) 2009, 2011, 2012, 2013 Google Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
-}
module Main(main) where
import Data.Monoid (mappend)
import Test.Framework
import System.Environment (getArgs)
import System.Log.Logger
import Test.AutoConf
import Test.Ganeti.TestImports ()
import Test.Ganeti.Attoparsec
import Test.Ganeti.BasicTypes
import Test.Ganeti.Common
import Test.Ganeti.Constants
import Test.Ganeti.Confd.Utils
import Test.Ganeti.Confd.Types
import Test.Ganeti.Daemon
import Test.Ganeti.Errors
import Test.Ganeti.HTools.Backend.Simu
import Test.Ganeti.HTools.Backend.Text
import Test.Ganeti.HTools.CLI
import Test.Ganeti.HTools.Cluster
import Test.Ganeti.HTools.Container
import Test.Ganeti.HTools.Graph
import Test.Ganeti.HTools.Instance
import Test.Ganeti.HTools.Loader
import Test.Ganeti.HTools.Node
import Test.Ganeti.HTools.PeerMap
import Test.Ganeti.HTools.Types
import Test.Ganeti.Hypervisor.Xen.XmParser
import Test.Ganeti.JSON
import Test.Ganeti.Jobs
import Test.Ganeti.JQueue
import Test.Ganeti.JQScheduler
import Test.Ganeti.Kvmd
import Test.Ganeti.Locking.Allocation
import Test.Ganeti.Locking.Locks
import Test.Ganeti.Locking.Waiting
import Test.Ganeti.Luxi
import Test.Ganeti.Network
import Test.Ganeti.Objects
import Test.Ganeti.Objects.BitArray
import Test.Ganeti.OpCodes
import Test.Ganeti.Query.Aliases
import Test.Ganeti.Query.Filter
import Test.Ganeti.Query.Instance
import Test.Ganeti.Query.Language
import Test.Ganeti.Query.Network
import Test.Ganeti.Query.Query
import Test.Ganeti.Rpc
import Test.Ganeti.Runtime
import Test.Ganeti.Ssconf
import Test.Ganeti.Storage.Diskstats.Parser
import Test.Ganeti.Storage.Drbd.Parser
import Test.Ganeti.Storage.Drbd.Types
import Test.Ganeti.Storage.Lvm.LVParser
import Test.Ganeti.THH
import Test.Ganeti.THH.Types
import Test.Ganeti.Types
import Test.Ganeti.Utils
import Test.Ganeti.Utils.MultiMap
import Test.Ganeti.Utils.Statistics
import Test.Ganeti.WConfd.TempRes
-- | Our default test options, overring the built-in test-framework
-- ones (but not the supplied command line parameters).
defOpts :: TestOptions
defOpts = TestOptions
{ topt_seed = Nothing
, topt_maximum_generated_tests = Just 500
, topt_maximum_unsuitable_generated_tests = Just 5000
, topt_maximum_test_size = Nothing
, topt_maximum_test_depth = Nothing
, topt_timeout = Nothing
}
-- | All our defined tests.
allTests :: [Test]
allTests =
[ testAutoConf
, testBasicTypes
, testAttoparsec
, testCommon
, testConstants
, testConfd_Types
, testConfd_Utils
, testDaemon
, testBlock_Diskstats_Parser
, testBlock_Drbd_Parser
, testBlock_Drbd_Types
, testErrors
, testHTools_Backend_Simu
, testHTools_Backend_Text
, testHTools_CLI
, testHTools_Cluster
, testHTools_Container
, testHTools_Graph
, testHTools_Instance
, testHTools_Loader
, testHTools_Node
, testHTools_PeerMap
, testHTools_Types
, testHypervisor_Xen_XmParser
, testJSON
, testJobs
, testJQueue
, testJQScheduler
, testKvmd
, testLocking_Allocation
, testLocking_Locks
, testLocking_Waiting
, testLuxi
, testNetwork
, testObjects
, testObjects_BitArray
, testOpCodes
, testQuery_Aliases
, testQuery_Filter
, testQuery_Instance
, testQuery_Language
, testQuery_Network
, testQuery_Query
, testRpc
, testRuntime
, testSsconf
, testStorage_Lvm_LVParser
, testTHH
, testTHH_Types
, testTypes
, testUtils
, testUtils_MultiMap
, testUtils_Statistics
, testWConfd_TempRes
]
-- | Main function. Note we don't use defaultMain since we want to
-- control explicitly our test sizes (and override the default).
main :: IO ()
main = do
ropts <- getArgs >>= interpretArgsOrExit
let opts = maybe defOpts (defOpts `mappend`) $ ropt_test_options ropts
-- silence the logging system, so that tests can execute I/O actions
-- which create logs without polluting stderr
-- FIXME: improve this by allowing tests to use logging if needed
updateGlobalLogger rootLoggerName (setLevel EMERGENCY)
defaultMainWithOpts allTests (ropts { ropt_test_options = Just opts })
| ribag/ganeti-experiments | test/hs/htest.hs | gpl-2.0 | 4,920 | 0 | 12 | 802 | 739 | 488 | 251 | 130 | 1 |
test_easy = assertEqual (solve 100) 13
| NorfairKing/project-euler | 035/haskell/Test.hs | gpl-2.0 | 39 | 0 | 7 | 6 | 17 | 8 | 9 | 1 | 1 |
-- Does not typecheck
s :: (a -> b -> c) -> (a -> b) -> a -> c
s a b c = a c (b c)
k :: a -> b -> a
k = const
i :: a -> a
i = id
u :: (((a -> b -> c) -> (a -> b) -> a -> c) -> (d -> e -> d) -> f) -> ((a -> b -> c) -> (a -> b) -> a -> c) -> (d -> e -> d) -> f
u f = f s k
a = u(u(u(u)))(u(u))
-- a = u(u(u(u(u))))(u(u(u(u(u))))(u(u(u(u)))(u(u(u(u(u))))))(u(u(u(u(u))))(u(u(u(u)))(u(u(u(u)))))(u(u))))(u(u(u(u(u))))(u(u(u(u(u))))(u(u(u(u)))(u(u(u(u(u))))))(u(u(u(u(u))))(u(u(u(u)))(u(u(u(u)))))(u(u(u(u(u))))(u(u(u(u)))(u(u(u(u(u))))(u(u(u(u(u))))(u(u(u(u)))(u(u(u(u(u))))))(u(u(u(u(u))))(u(u(u(u)))(u(u(u(u)))))(u(u))))(u(u(u(u(u))))(u(u(u(u(u))))(u(u(u(u)))(u(u(u(u(u))))))(u(u(u(u(u))))(u(u(u(u)))(u(u(u(u)))))(u(u(u(u(u))))(u(u(u(u)))(u(u(u(u(u))))(u(u(u(u(u))))(u(u(u(u)))(u(u(u(u(u))))))(u(u(u(u(u))))(u(u(u(u)))(u(u(u(u)))))(u(u))))(u(u(u(u(u))))(u(u(u(u(u))))(u(u(u(u)))(u(u(u(u(u))))))(u(u(u(u(u))))(u(u(u(u)))(u(u(u(u)))))(u(u(u(u(u))))(u(u(u(u)))(u(u(u(u)))(u(u))))(u(u)))))(u(u(u(u)))(u(u))))))(u(u)))))(u(u(u(u)))(u(u))))))(u(u)))))(u(u(u(u)))(u(u))))
main = print $ a succ '\n'
| KenetJervet/mapensee | haskell/theorem-proving/SKI/Iota_a.hs | gpl-3.0 | 1,096 | 2 | 13 | 117 | 299 | 148 | 151 | 10 | 1 |
{-# LANGUAGE DeriveDataTypeable, TemplateHaskell, TypeFamilies, OverloadedStrings #-}
module Life.DB.Books
( Author(..)
, Book(..)
, Books(..)
)
where
import Data.Text
import Data.Set (Set)
import Data.Data (Data,Typeable)
import Control.Applicative ((<$>))
import Control.Monad.Reader (ask)
import Control.Monad.State (get, put)
import Data.DateTime
import Data.Acid (Query, Update, makeAcidic)
import Data.SafeCopy (base, deriveSafeCopy)
import Life.DB.Tag
data Author = Author
{ authorName :: Text
} deriving (Ord, Eq, Read, Show, Data, Typeable)
$(deriveSafeCopy 0 'base ''Author)
data Book = Book
{ bookTitle :: Text
, bookAuthor :: Author
, bookTags :: Set Tag
, bookPages :: Int
} deriving (Eq, Ord, Read, Show, Data, Typeable)
$(deriveSafeCopy 0 'base ''Book)
getBookTitle :: Query Book Text
getBookTitle = bookTitle <$> ask
getBookAuthor :: Query Book Author
getBookAuthor = bookAuthor <$> ask
getBookPages :: Query Book Int
getBookPages = bookPages <$> ask
$(makeAcidic ''Book ['getBookTitle, 'getBookAuthor, 'getBookPages])
data Books = Books
{ booksRead :: [(Book, Maybe DateTime)]
} deriving (Ord, Eq, Read, Show, Data, Typeable)
$(deriveSafeCopy 0 'base ''Books)
getBooksRead :: Query Books [(Book,Maybe DateTime)]
getBooksRead = booksRead <$> ask
-- | Add a new read book
addReadBook :: Book -> Maybe DateTime -> Update Books ()
addReadBook book finishTime = do
books <- get
let rdBooks = booksRead books
put (books { booksRead = (book,finishTime):rdBooks })
$(makeAcidic ''Books ['addReadBook, 'getBooksRead])
| hsyl20/life | src/Life/DB/Books.hs | gpl-3.0 | 1,592 | 0 | 12 | 276 | 562 | 315 | 247 | 45 | 1 |
import Distribution.Simple (defaultMainWithHooks)
import Distribution.Simple.UUAGC (uuagcLibUserHook)
import UU.UUAGC (uuagc)
main :: IO ()
main = defaultMainWithHooks (uuagcLibUserHook uuagc)
| toothbrush/diaspec | Setup.hs | gpl-3.0 | 194 | 1 | 7 | 19 | 59 | 31 | 28 | 5 | 1 |
{-# LANGUAGE CPP #-}
module DirectCodegen where
{-
The standard mode for hsc2hs: generates a C file which is
compiled and run; the output of that program is the .hs file.
-}
import Data.Char ( isAlphaNum, toUpper )
import Control.Monad ( when, forM_ )
import System.Exit ( ExitCode(..), exitWith )
import System.FilePath ( normalise )
import C
import Common
import Flags
import HSCParser
import UtilsCodegen
outputDirect :: Config -> FilePath -> FilePath -> FilePath -> String -> [Token] -> IO ()
outputDirect config outName outDir outBase name toks = do
let beVerbose = cVerbose config
flags = cFlags config
cProgName = outDir++outBase++"_hsc_make.c"
oProgName = outDir++outBase++"_hsc_make.o"
progName = outDir++outBase++"_hsc_make"
#if defined(mingw32_HOST_OS) || defined(__CYGWIN32__)
-- This is a real hack, but the quoting mechanism used for calling the C preprocesseor
-- via GHC has changed a few times, so this seems to be the only way... :-P * * *
++ ".exe"
#endif
outHFile = outBase++"_hsc.h"
outHName = outDir++outHFile
outCName = outDir++outBase++"_hsc.c"
let execProgName
| null outDir = normalise ("./" ++ progName)
| otherwise = progName
let specials = [(pos, key, arg) | Special pos key arg <- toks]
let needsC = any (\(_, key, _) -> key == "def") specials
needsH = needsC
possiblyRemove = if cKeepFiles config
then flip const
else finallyRemove
let includeGuard = map fixChar outHName
where
fixChar c | isAlphaNum c = toUpper c
| otherwise = '_'
when (cCrossSafe config) $
forM_ specials (\ (SourcePos file line,key,_) ->
when (not $ key `elem` ["const","offset","size","peek","poke","ptr",
"type","enum","error","warning","include","define","undef",
"if","ifdef","ifndef", "elif","else","endif"]) $
die (file ++ ":" ++ show line ++ " directive \"" ++ key ++ "\" is not safe for cross-compilation"))
writeBinaryFile cProgName $
outTemplateHeaderCProg (cTemplate config)++
concatMap outFlagHeaderCProg flags++
concatMap outHeaderCProg specials++
"\nint main (int argc, char *argv [])\n{\n"++
outHeaderHs flags (if needsH then Just outHName else Nothing) specials++
outHsLine (SourcePos name 0)++
concatMap outTokenHs toks++
" return 0;\n}\n"
when (cNoCompile config) $ exitWith ExitSuccess
rawSystemL ("compiling " ++ cProgName) beVerbose (cCompiler config)
( ["-c"]
++ [cProgName]
++ ["-o", oProgName]
++ [f | CompFlag f <- flags]
)
possiblyRemove cProgName $
withUtilsObject config outDir outBase $ \oUtilsName -> do
rawSystemL ("linking " ++ oProgName) beVerbose (cLinker config)
( [oProgName, oUtilsName]
++ ["-o", progName]
++ [f | LinkFlag f <- flags]
)
possiblyRemove oProgName $ do
rawSystemWithStdOutL ("running " ++ execProgName) beVerbose execProgName [] outName
possiblyRemove progName $ do
when needsH $ writeBinaryFile outHName $
"#ifndef "++includeGuard++"\n" ++
"#define "++includeGuard++"\n" ++
"#include <HsFFI.h>\n" ++
"#if __NHC__\n" ++
"#undef HsChar\n" ++
"#define HsChar int\n" ++
"#endif\n" ++
concatMap outFlagH flags++
concatMap outTokenH specials++
"#endif\n"
when needsC $ writeBinaryFile outCName $
"#include \""++outHFile++"\"\n"++
concatMap outTokenC specials
-- NB. outHFile not outHName; works better when processed
-- by gcc or mkdependC.
| jwiegley/ghc-release | utils/hsc2hs/DirectCodegen.hs | gpl-3.0 | 4,016 | 6 | 29 | 1,275 | 966 | 505 | 461 | 77 | 3 |
module Test.Language.FIRRTL.Syntax.Expr where
import Control.Unification.IntVar (evalIntBindingT)
import Control.Monad.Trans.Except (runExceptT)
import Data.Functor.Identity (runIdentity)
import Test.Tasty.HUnit
import Language.FIRRTL.Annotations
import Language.FIRRTL.Recursion
import Language.FIRRTL.Syntax
import Language.FIRRTL.Types
import Language.FIRRTL.Unification
nat :: Int -> ExprF a
nat = Lit . Nat
uint :: Int -> ExprF a
uint = Lit . UInt
sint :: Int -> ExprF a
sint = Lit . SInt
constExpr :: ExprF TypedExpr -> Maybe Type -> TypedExpr
constExpr e mt = annotate mt e
field :: Orientation -> Ident -> Type -> Field Type
field = Field
exBundle :: Type
exBundle = Fix $ Bundle [ field Direct "a" (Fix $ Ground $ Signed (Just 3))
, field Direct "b" (Fix $ Ground $ Unsigned Nothing)
, field Flipped "c" (Fix $ Ground $ Unsigned (Just 1))
]
subFieldExpr :: ExprF TypedExpr -> Ident -> TypedExpr
subFieldExpr b id = annotate Nothing b
env = singleton "bundle" (poly exBundle)
ref :: TypedExpr
ref = annotate Nothing (Ref "bundle")
unifyBundle = testCase "unify bundle type" $
either
(assertFailure . show)
(\p -> assertBool "unify bundle type" True)
(runIdentity
$ evalIntBindingT
$ runExceptT
$ typecheck env
$ annotate Nothing (SubField ref "a") )
literal = testCase "unify single literal value" $
either
(assertFailure . show)
(\p -> assertBool "typecheck completed" True)
(runIdentity
$ evalIntBindingT
$ runExceptT
$ typecheck env
$ constExpr (sint 5) (Just (Fix $ Ground $ Signed (Just 4))))
| quivade/screwdriver | test/Test/Language/FIRRTL/Syntax/Expr.hs | gpl-3.0 | 1,672 | 0 | 16 | 394 | 542 | 286 | 256 | 47 | 1 |
{-# LANGUAGE ViewPatterns,DeriveFunctor,ScopedTypeVariables #-}
-- | Translating from the Simple language to the First-Order language
module HipSpec.Lang.SimpleToFO where
import qualified HipSpec.Lang.Simple as S
import HipSpec.Lang.Simple hiding (App)
import HipSpec.Lang.FunctionalFO as FO
import HipSpec.Id
stfFun :: S.Function Id -> FO.Function Id
stfFun (S.Function f (Forall tvs ty) as b) =
FO.Function f tvs (zip as arg_tys) res_ty (stfBody b)
where
peel 0 t = ([],t)
peel n (ArrTy ta t) = let (tas,r) = peel (n - 1) t in (ta:tas,r)
peel _ _ = error "SimpleToFO.peel: not an arrow type!"
(arg_tys,res_ty) = peel (length as) ty
stfBody :: S.Body Id -> FO.Body Id
stfBody b0 = case b0 of
S.Case e alts -> FO.Case (stfExpr e) [ (stfPat p,stfBody b) | (p,b) <- alts ]
S.Body e -> FO.Body (stfExpr e)
stfPat :: S.Pattern Id -> FO.Pattern Id
stfPat p = case p of
S.Default -> FO.Default
S.ConPat c _ty ts as -> FO.ConPat c ts as
S.LitPat x -> FO.LitPat x
stfExpr :: S.Expr Id -> FO.Expr Id
stfExpr e0 = case e0 of
S.Lcl f _ty -> Fun f [] []
S.Gbl f _ty tys -> Ptr f tys
S.Lit x -> FO.Lit x
S.App e1 e2 -> case S.exprType e1 of
ArrTy t1 t2 -> App t1 t2 (stfExpr e1) (stfExpr e2)
_ -> error "SimpleToFO.stfExpr: argument not an arrow type!"
| danr/hipspec | src/HipSpec/Lang/SimpleToFO.hs | gpl-3.0 | 1,395 | 0 | 13 | 379 | 578 | 290 | 288 | 30 | 5 |
module Database.Design.Ampersand.Prototype.Generate
(generateGenerics
, generateDBstructQueries, generateAllDefPopQueries
)
where
import Database.Design.Ampersand
import Database.Design.Ampersand.Core.AbstractSyntaxTree
import Prelude hiding (writeFile,readFile,getContents,exp)
import Data.Function
import Data.List
import Data.Maybe
import Database.Design.Ampersand.FSpec.SQL
import Database.Design.Ampersand.FSpec.FSpecAux
import Database.Design.Ampersand.Prototype.ProtoUtil
import Database.Design.Ampersand.Basics (fatal)
import Database.Design.Ampersand.Prototype.PHP (getTableName, signalTableSpec)
import Database.Design.Ampersand.ECA2SQL.PrettyPrinterSQL (eca2PrettySQL)
-- Generate Generics.php
generateGenerics :: FSpec -> IO ()
generateGenerics fSpec =
do { let filecontent = genPhp "Generate.hs" "Generics.php" genericsPhpContent
-- ; verboseLn (getOpts fSpec) filecontent
; writePrototypeFile fSpec "Generics.php" filecontent
}
where
genericsPhpContent :: [String]
genericsPhpContent =
intercalate [""] $ map ($fSpec)
[ generateConstants
, generateTableInfos
, generateConjuncts
, generateECASQL
, generateRoles
, generateViews
, generateInterfaces
]
generateConstants :: FSpec -> [String]
generateConstants fSpec =
[ "$isDev = "++showPhpBool (development opts)++";"
]
where opts = getOpts fSpec
generateDBstructQueries :: FSpec -> [String]
generateDBstructQueries fSpec = theSQLstatements
where
theSQLstatements :: [String]
theSQLstatements =
createTableStatements ++
[ "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE"
]
createTableStatements :: [String]
createTableStatements =
map concat
[ [ "CREATE TABLE "++ show "__SessionTimeout__"
, " ( "++show "SESSION"++" VARCHAR(255) UNIQUE NOT NULL"
, " , "++show "lastAccess"++" BIGINT NOT NULL"
, " ) ENGINE=InnoDB DEFAULT CHARACTER SET UTF8 COLLATE UTF8_BIN"
]
, [ "CREATE TABLE "++ show "__History__"
, " ( "++show "Seconds"++" VARCHAR(255) DEFAULT NULL"
, " , "++show "Date"++" VARCHAR(255) DEFAULT NULL"
, " ) ENGINE=InnoDB DEFAULT CHARACTER SET UTF8 COLLATE UTF8_BIN"
]
, [ "INSERT INTO "++show "__History__"++" ("++show "Seconds"++","++show "Date"++")"
, " VALUES (UNIX_TIMESTAMP(NOW(6)), NOW(6))"
]
, [ "CREATE TABLE "++ show "__all_signals__"
, " ( "++show "conjId"++" VARCHAR(255) NOT NULL"
, " , "++show "src"++" VARCHAR(255) NOT NULL"
, " , "++show "tgt"++" VARCHAR(255) NOT NULL"
, " ) ENGINE=InnoDB DEFAULT CHARACTER SET UTF8 COLLATE UTF8_BIN"
]
] ++
( concatMap tableSpec2Queries [(plug2TableSpec p) | InternalPlug p <- plugInfos fSpec])
where
tableSpec2Queries :: TableSpecNew -> [String]
tableSpec2Queries ts =
-- [ "DROP TABLE "++show (tsName ts)] ++
[ concat $
( tsCmnt ts ++
["CREATE TABLE "++show (tsName ts)]
++ (map (uncurry (++))
(zip (" ( ": repeat " , " )
( map fld2sql (tsflds ts)
++ tsKey ts
)
)
)
++ [" , "++show "ts_insertupdate"++" TIMESTAMP ON UPDATE CURRENT_TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP"]
++ [" ) ENGINE=InnoDB DEFAULT CHARACTER SET UTF8 COLLATE UTF8_BIN"]
)
]
fld2sql :: SqlAttribute -> String
fld2sql = attributeSpec2Str . fld2AttributeSpec
data TableSpecNew
= TableSpec { tsCmnt :: [String]
, tsName :: String
, tsflds :: [SqlAttribute]
, tsKey :: [String]
, tsEngn :: String
}
data AttributeSpecNew
= AttributeSpec { fsname :: String
, fstype :: String
, fsauto :: Bool
}
fld2AttributeSpec ::SqlAttribute -> AttributeSpecNew
fld2AttributeSpec att
= AttributeSpec { fsname = name att
, fstype = showSQL (attType att)
, fsauto = fldauto att
}
attributeSpec2Str :: AttributeSpecNew -> String
attributeSpec2Str fs = intercalate " "
[ show (fsname fs)
, fstype fs
, if fsauto fs then " AUTO_INCREMENT" else " DEFAULT NULL"
]
plug2TableSpec :: PlugSQL -> TableSpecNew
plug2TableSpec plug
= TableSpec
{ tsCmnt = commentBlockSQL (["Plug "++name plug,"","attributes:"]++map (\x->showADL (attExpr x)++" "++(show.properties.attExpr) x) (plugAttributes plug))
, tsName = name plug
, tsflds = plugAttributes plug
, tsKey = case (plug, (head.plugAttributes) plug) of
(BinSQL{}, _) -> []
(_, primFld) ->
case attUse primFld of
TableKey isPrim _ -> [ (if isPrim then "PRIMARY " else "")
++ "KEY ("++(show . attName) primFld++")"
]
ForeignKey c -> fatal 195 ("ForeignKey "++name c++"not expected here!")
PlainAttr -> []
, tsEngn = "InnoDB DEFAULT CHARACTER SET UTF8 COLLATE UTF8_BIN"
}
commentBlockSQL :: [String] -> [String]
commentBlockSQL xs =
map (\cmmnt -> "/* "++cmmnt++" */") $ hbar ++ xs ++ hbar
where hbar = [replicate (maximum . map length $ xs) '-']
generateAllDefPopQueries :: FSpec -> [String]
generateAllDefPopQueries fSpec = theSQLstatements
where
theSQLstatements
= fillSignalTable (initialConjunctSignals fSpec) ++
populateTablesWithPops
fillSignalTable :: [(Conjunct, [AAtomPair])] -> [String]
fillSignalTable [] = []
fillSignalTable conjSignals
= [concat $
[ "INSERT INTO "++show (getTableName signalTableSpec)
, " ("++intercalate ", " (map show ["conjId","src","tgt"])++")"
] ++ lines
( "VALUES " ++ intercalate "\n , "
[ "(" ++intercalate ", " (map showAsValue [rc_id conj, showValPHP (apLeft p), showValPHP (apRight p)])++ ")"
| (conj, viols) <- conjSignals
, p <- viols
]
)
]
populateTablesWithPops :: [String]
populateTablesWithPops =
concatMap populatePlug [p | InternalPlug p <- plugInfos fSpec]
where
populatePlug :: PlugSQL -> [String]
populatePlug plug
= case tableContents fSpec plug of
[] -> []
tblRecords
-> [concat $
[ "INSERT INTO "++show (name plug)
, " ("++intercalate ", " (map (show . attName) (plugAttributes plug))++") "
] ++ lines
( "VALUES " ++ intercalate "\n , "
[ "(" ++valuechain md++ ")" | md<-tblRecords]
)
]
where
valuechain record
= intercalate ", "
[case att of
Nothing -> "NULL"
Just val -> showValPHP val
| att <- record ]
generateTableInfos :: FSpec -> [String]
generateTableInfos fSpec =
[ "$allRelations ="
, " array" ] ++
addToLastLine ";"
(indent 4 (blockParenthesize "(" ")" ","
[ [showPhpStr (showHSName decl)++" => array ( 'name' => "++showPhpStr (name decl)
++ ", 'srcConcept' => "++showPhpStr (name (source decl))
++ ", 'tgtConcept' => "++showPhpStr (name (target decl))
++ ", 'table' => "++showPhpStr (name table)
++ ", 'srcCol' => "++showPhpStr (attName srcCol)
++ ", 'tgtCol' => "++showPhpStr (attName tgtCol)
++ ", 'affectedInvConjunctIds' => array ("++ intercalate ", " (map (showPhpStr . rc_id) affInvConjs) ++")"
++ ", 'affectedSigConjunctIds' => array ("++ intercalate ", " (map (showPhpStr . rc_id) affSigConjs) ++")"
++ ")"]
| decl@Sgn{} <- allDecls fSpec -- SJ 13 nov 2013: changed to generate all relations instead of just the ones used.
, let (table,srcCol,tgtCol) = getDeclarationTableInfo fSpec decl
, let affConjs = case lookup decl $ allConjsPerDecl fSpec of
Nothing -> []
Just conjs -> conjs
affInvConjs = filterFrontEndInvConjuncts affConjs
affSigConjs = filterFrontEndSigConjuncts affConjs
])) ++
[ ""
, "$allConcepts = array"
] ++
addToLastLine ";"
(indent 2 $
blockParenthesize "(" ")" ","
[ [ (showPhpStr.name) c++" => array"] ++
(indent 2 $
[ "( 'concept' => "++ (showPhpStr.name) c
, ", 'affectedInvConjunctIds' => array ("++ intercalate ", " (map (showPhpStr . rc_id) affInvConjs) ++")"
, ", 'affectedSigConjunctIds' => array ("++ intercalate ", " (map (showPhpStr . rc_id) affSigConjs) ++")"
, ", 'conceptTables' => array" ] ++
(indent 3
(blockParenthesize "(" ")" ","
[ [ "array ( 'table' => "++(showPhpStr.name) table ++
", 'cols' => array ("++ intercalate ", " (map (showPhpStr . attName) conceptAttributes) ++")" ++
" )"
]
-- get the concept tables (pairs of table and column names) for the concept and its generalizations and group them per table name
| (table,conceptAttributes) <- groupOnTable . concatMap (lookupCpt fSpec) $ c : largerConcepts (vgens fSpec) c
])) ++
[ ", 'type' => '"++(show . cptTType fSpec) c++"'" ]++
[ ", 'specializations' => array ("++intercalate ", " (map (showPhpStr . name)(smallerConcepts (vgens fSpec) c))++")"]++
[ ", 'defaultViewId' => "++(showPhpStr . vdlbl $ dfltV)
| Just dfltV <- [getDefaultViewForConcept fSpec c]
]++
[ ")" ]
)
| c <- concs fSpec
, let
affConjs = nub [ conj
| Just conjs<-[lookup c (allConjsPerConcept fSpec)]
, conj<-conjs
]
affInvConjs = filterFrontEndInvConjuncts affConjs
affSigConjs = filterFrontEndSigConjuncts affConjs
]
) ++
[ ""
, "$tableColumnInfo ="
, " array"
] ++
addToLastLine ";"
(indent 4
(blockParenthesize "(" ")" ","
[ [ (showPhpStr.name) plug++" =>"
, " array"
] ++
indent 4
(blockParenthesize "(" ")" ","
[ [ (showPhpStr.attName) attribute++ " => array ( 'concept' => "++(showPhpStr.name.target.attExpr) attribute++
", 'unique' => " ++(showPhpBool.attUniq) attribute++
", 'null' => " ++ (showPhpBool.attNull) attribute++
")"
]
| attribute <- plugAttributes plug]
)
| InternalPlug plug <- plugInfos fSpec
]
) )
where groupOnTable :: [(PlugSQL,SqlAttribute)] -> [(PlugSQL,[SqlAttribute])]
groupOnTable tablesAttributes = [(t,fs) | (t:_, fs) <- map unzip . groupBy ((==) `on` fst) $ sortBy (\(x,_) (y,_) -> name x `compare` name y) tablesAttributes ]
generateConjuncts :: FSpec -> [String]
generateConjuncts fSpec =
[ "$allConjuncts ="
, " array"
] ++
addToLastLine ";"
(indent 4
(blockParenthesize "(" ")" ","
[ [ showPhpStr (rc_id conj) ++ " => /* conj = " ++ showADL rExpr ++ " */"
, " array ( 'signalRuleNames' => array ("++ intercalate ", " signalRuleNames ++")"
, " , 'invariantRuleNames' => array ("++ intercalate ", " invRuleNames ++")"
-- the name of the rules that gave rise to this conjunct
] ++
( if verboseP (getOpts fSpec)
then [" // Normalization steps:"]
++[" // "++ls | ls<-(showPrf showADL . cfProof (getOpts fSpec)) violExpr]
++[" // "]
else [] ) ++
( if development (getOpts fSpec)
then [ " // Conjunct Ampersand: "++escapePhpStr (showADL rExpr) ] ++
[ " // Normalized complement (== violationsSQL): " ] ++
(lines ( " // "++(showHS (getOpts fSpec) "\n // ") violationsExpr))
else [] ) ++
[ " , 'violationsSQL' => "++ showPhpStr (prettySQLQuery fSpec 36 violationsExpr)
, " )"
]
| conj<-vconjs fSpec
, let rExpr=rc_conjunct conj
, let signalRuleNames = [ showPhpStr $ name r | r <- rc_orgRules conj, isFrontEndSignal r ]
, let invRuleNames = [ showPhpStr $ name r | r <- rc_orgRules conj, isFrontEndInvariant r ]
, let violExpr = notCpl rExpr
, let violationsExpr = conjNF (getOpts fSpec) violExpr
]
) )
generateECASQL :: FSpec -> [String]
generateECASQL fSpec@FSpec{vEcas=vEcas} =
[ "$allECASQLFuns ="
, " array"
] ++
addToLastLine ";"
(indent 4
(blockParenthesize "(" ")" "," $ map pure
[ (showPhpStr (show $ ecaNum eca)) ++ " => '" ++ show (eca2PrettySQL fSpec eca) ++ "'" | eca <- vEcas ]
) )
-- Because the signal/invariant condition appears both in generateConjuncts and generateInterface, we use
-- two abstractions to guarantee the same implementation.
isFrontEndInvariant :: Rule -> Bool
isFrontEndInvariant r = not (isSignal r) && not (ruleIsInvariantUniOrInj r)
isFrontEndSignal :: Rule -> Bool
isFrontEndSignal r = isSignal r
-- NOTE that results from filterFrontEndInvConjuncts and filterFrontEndSigConjuncts may overlap (conjunct appearing in both invariants and signals)
-- and that because of extra condition in isFrontEndInvariant (not (ruleIsInvariantUniOrInj r)), some parameter conjuncts may not be returned
-- as either inv or sig conjuncts (i.e. conjuncts that appear only in uni or inj rules)
filterFrontEndInvConjuncts :: [Conjunct] -> [Conjunct]
filterFrontEndInvConjuncts conjs = filter (\c -> any isFrontEndInvariant $ rc_orgRules c) conjs
filterFrontEndSigConjuncts :: [Conjunct] -> [Conjunct]
filterFrontEndSigConjuncts conjs = filter (\c -> any isFrontEndSignal $ rc_orgRules c) conjs
generateRoles :: FSpec -> [String]
generateRoles fSpec =
concatMap showRoles [False,True]
where showRoles isService =
[ if isService then "$allServices =" else "$allRoles ="
, " array"
] ++
addToLastLine ";"
(indent 4
(blockParenthesize "(" ")" ","
[ [ "array ( 'id' => "++show i
, " , 'name' => "++showPhpStr (name role)
, " , 'ruleNames' => array ("++ intercalate ", " ((map (showPhpStr . name . snd) . filter (maintainedByRole role) . fRoleRuls) fSpec) ++")"
, " , 'interfaces' => array ("++ intercalate ", " (map (showPhpStr . name) ((roleInterfaces fSpec) role)) ++")"
, " )" ]
| (i,role) <- zip [1::Int ..] (filter serviceOrRole $ fRoles fSpec) ]
) )
where
serviceOrRole Role{} = not isService
serviceOrRole Service{} = isService
maintainedByRole role (role',_) = role == role'
generateViews :: FSpec -> [String]
generateViews fSpec =
[ "//$allViews is sorted from spec to gen such that the first match for a concept will be the most specific (e.g. see DatabaseUtils.getView())."
, "$allViews ="
, " array"
] ++
addToLastLine ";"
(indent 4
(blockParenthesize "(" ")" ","
[ [ " array ( 'label' => "++showPhpStr label
, " , 'concept' => "++showPhpStr (name cpt)
, " , 'isDefault' => "++showPhpBool isDefault
, " , 'segments' =>" -- a labeled list of sql queries for the view expressions
, " array"
] ++
indent 14 (blockParenthesize "(" ")" "," (map genViewSeg viewSegs)) ++
[ " )" ]
| Vd _ label cpt isDefault _ viewSegs <- [ v | c<-conceptsFromSpecificToGeneric, v <- vviews fSpec, vdcpt v==c ] --sort from spec to gen
]
) )
where genViewSeg (ViewText i str) = [ "array ( 'segmentType' => 'Text'"
, " , 'label' => " ++ lab i
, " , 'Text' => " ++ showPhpStr str
, " )" ]
genViewSeg (ViewHtml i str) = [ "array ( 'segmentType' => 'Html'"
, " , 'label' => " ++ lab i
, " , 'Html' => " ++ showPhpStr str
, " )" ]
genViewSeg (ViewExp _ objDef) = [ "array ( 'segmentType' => 'Exp'"
, " , 'label' => " ++ showPhpStr (objnm objDef) ++ " // view exp: " ++ escapePhpStr (showADL $ objctx objDef) -- note: unlabeled exps are labeled by (index + 1)
, " , 'expSQL' =>"
, " " ++ showPhpStr (prettySQLQuery fSpec 33 (objctx objDef))
, " )"
]
conceptsFromSpecificToGeneric = concatMap reverse (kernels fSpec)
lab i = showPhpStr ("seg_"++show i)
generateInterfaces :: FSpec -> [String]
generateInterfaces fSpec =
[ "$allInterfaceObjects ="
, " array"
] ++
addToLastLine ";"
(indent 4
(blockParenthesize "(" ")" ","
(map (generateInterface fSpec) (interfaceS fSpec ++ interfaceG fSpec))
) )
generateInterface :: FSpec -> Interface -> [String]
generateInterface fSpec interface =
let roleStr = case ifcRoles interface of [] -> " for all roles"
rolez -> " for role"++ (if length rolez == 1 then "" else "s") ++" " ++ intercalate ", " (map name (ifcRoles interface))
arrayKey = escapeIdentifier $ name interface
in ["// Top-level interface " ++ name interface ++ roleStr ++ ":"
, showPhpStr arrayKey ++ " => "
] ++
indent 2 (genInterfaceObjects fSpec (ifcParams interface) (Just $ topLevelFields) 1 (ifcObj interface))
where topLevelFields = -- for the top-level interface object we add the following fields (saves us from adding an extra interface node to the php data structure)
[ " , 'interfaceRoles' => array (" ++ intercalate ", " (map (showPhpStr.name) $ ifcRoles interface) ++")"
, " , 'invConjunctIds' => array ("++intercalate ", " (map (showPhpStr . rc_id) $ invConjuncts) ++")"
, " , 'sigConjunctIds' => array ("++intercalate ", " (map (showPhpStr . rc_id) $ sigConjuncts) ++")"
, " , 'editableConcepts' => array ("++ intercalate ", " (map (showPhpStr . name) ((editableConcepts fSpec) interface)) ++")"
]
invConjuncts = [ c | c <- ifcControls interface, any isFrontEndInvariant $ rc_orgRules c ] -- NOTE: these two
sigConjuncts = [ c | c <- ifcControls interface, any isFrontEndSignal $ rc_orgRules c ] -- may overlap
genInterfaceObjects :: FSpec -> [Declaration] -> Maybe [String] -> Int -> ObjectDef -> [String]
genInterfaceObjects fSpec editableRels mTopLevelFields depth object =
[ "array ( 'name' => "++ showPhpStr (name object)
, " , 'id' => " ++ show (escapeIdentifier $ name object) -- only for new front-end
, " , 'label' => " ++ showPhpStr (name object) -- only for new front-end
]
++ maybe [] (\viewId -> [" , 'viewId' => " ++ showPhpStr viewId]) mViewId
++ (if verboseP (getOpts fSpec) -- previously, this included the condition objctx object /= normalizedInterfaceExp
then [" // Normalization steps:"]
++ [" // "++ls | ls<-(showPrf showADL.cfProof (getOpts fSpec).objctx) object] -- let's hope that none of the names in the relation contains a newline
++ [" //"]
else []
)
++ [" // Normalized interface expression (== expressionSQL): "++escapePhpStr (showADL normalizedInterfaceExp) ]
++ [" // normalizedInterfaceExp = " ++ show normalizedInterfaceExp | development (getOpts fSpec) ]
-- escape for the pathological case that one of the names in the relation contains a newline
++ fromMaybe [] mTopLevelFields -- declare extra fields if this is a top level interface object
++ case mEditableDecl of
Just (decl, isFlipped) ->
[ " , 'relation' => "++showPhpStr (showHSName decl) ++ " // this interface represents a declared relation"
, " , 'relationIsEditable' => "++ showPhpBool (decl `elem` editableRels)
, " , 'relationIsFlipped' => "++showPhpBool isFlipped ] ++
if isFlipped
then [ " , 'min' => "++ if isSur decl then "'One'" else "'Zero'"
, " , 'max' => "++ if isInj decl then "'One'" else "'Many'" ]
else [ " , 'min' => "++ if isTot decl then "'One'" else "'Zero'"
, " , 'max' => "++ if isUni decl then "'One'" else "'Many'" ]
Nothing ->
[ " , 'relation' => '' // this interface expression does not represent a declared relation"
, " , 'relationIsFlipped' => ''"
]
++ [ " , 'srcConcept' => "++showPhpStr (name srcConcept) -- NOTE: these are src and tgt of the expression, not necessarily the relation (if there is one),
, " , 'tgtConcept' => "++showPhpStr (name tgtConcept) -- which may be flipped.
, " , 'crudC' => "++ (showPhpMaybeBool . crudC . objcrud $ object)
, " , 'crudR' => "++ (showPhpMaybeBool . crudR . objcrud $ object)
, " , 'crudU' => "++ (showPhpMaybeBool . crudU . objcrud $ object)
, " , 'crudD' => "++ (showPhpMaybeBool . crudD . objcrud $ object)
, " , 'exprIsUni' => " ++ showPhpBool (isUni normalizedInterfaceExp) -- We could encode these by creating min/max also for non-editable,
, " , 'exprIsTot' => " ++ showPhpBool (isTot normalizedInterfaceExp) -- but this is more in line with the new front-end templates.
, " , 'exprIsProp' => " ++ showPhpBool (isProp normalizedInterfaceExp)
, " , 'exprIsIdent' => " ++ showPhpBool (isIdent normalizedInterfaceExp)
, " , 'expressionSQL' => " ++ showPhpStr (prettySQLQuery fSpec (22+14*depth) normalizedInterfaceExp)
]
++ generateMSubInterface fSpec editableRels depth (objmsub object)
++ [ " )"
]
where mViewId = case objmView object of
Just vId -> Just vId
Nothing -> case getDefaultViewForConcept fSpec tgtConcept of
Just Vd{vdlbl=vId} -> Just vId
Nothing -> Nothing
normalizedInterfaceExp = conjNF (getOpts fSpec) $ objctx object
(srcConcept, tgtConcept, mEditableDecl) =
case getExpressionRelation normalizedInterfaceExp of
Just (src, decl, tgt, isFlipped) ->
(src, tgt, Just (decl, isFlipped))
Nothing -> (source normalizedInterfaceExp, target normalizedInterfaceExp, Nothing) -- fall back to typechecker type
generateMSubInterface :: FSpec -> [Declaration] -> Int -> Maybe SubInterface -> [String]
generateMSubInterface fSpec editableRels depth subIntf =
case subIntf of
Nothing -> [ " // No subinterfaces" ]
Just (InterfaceRef isLink nm _)
-> [ " // InterfaceRef"
-- , " , 'refSubInterface' => " ++ showPhpStr nm
, " , 'refSubInterfaceId' => " ++ showPhpStr (escapeIdentifier nm) -- only for new front-end
, " , 'isLinkTo' => "++ show isLink
]
Just (Box _ cl objects)
-> [ " // Box" ++ (maybe "" (\c -> "<"++c++">") cl)
, " , 'boxSubInterfaces' =>"
, " array"
] ++
indent 12
(blockParenthesize "(" ")" ","
(map (genInterfaceObjects fSpec editableRels Nothing (depth + 1)) objects))
-- utils
-- generatorModule is the Haskell module responsible for generation, makes it easy to track the origin of the php code
genPhp :: String -> String -> [String] -> String
genPhp generatorModule moduleName contentLines = unlines $
[ "<?php"
, "// module "++moduleName++" generated by "++generatorModule
, "// "++ampersandVersionStr
] ++ replicate 2 "" ++ contentLines ++
[ "?>"
]
showAsValue :: String -> String
showAsValue str = "'"++f str++"'"
where f :: String -> String
f str'=
case str' of
[] -> []
('\'':cs) -> "\\\'"++ f cs --This is required to ensure that the result of showValue will be a proper singlequoted string.
(c:cs) -> c : f cs
| 4ZP6Capstone2015/ampersand | src/Database/Design/Ampersand/Prototype/Generate.hs | gpl-3.0 | 26,097 | 0 | 38 | 9,113 | 6,047 | 3,169 | 2,878 | 429 | 11 |
-- grid is a game written in Haskell
-- Copyright (C) 2018 karamellpelle@hotmail.com
--
-- This file is part of grid.
--
-- grid is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- grid is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with grid. If not, see <http://www.gnu.org/licenses/>.
--
module Game.Run.Output.Fancy.Screen
(
outputScreenBegin,
outputScreenBegin',
outputScreenMain,
outputScreenMain',
outputScreenEnd,
outputScreenEnd',
outputScreenLevelMode,
outputScreenPuzzleMode,
outputScreenMemoryMode,
outputScreenForeign,
outputScreenKonami,
outputScreenAtFace',
outputScreenAtFace''',
outputScreenAToB,
) where
import MyPrelude
import Game
import Game.Font
import Game.Data.Color
import Game.Grid
import Game.Grid.Output
import Game.Grid.Output.Fancy.ShadeGeneral
import Game.Run
import Game.Run.Iteration.State
import Game.Run.Output.Fancy.ShadeCube
import Game.Run.Output.Fancy.CornerData
import Game.LevelPuzzle.LevelPuzzleWorld.OutputState
import OpenGL
import OpenGL.Helpers
--------------------------------------------------------------------------------
-- Begin
outputScreenBegin :: GameData -> RunWorld -> IO ()
outputScreenBegin griddata run = do
return ()
outputScreenBegin' :: GameData -> Mat4 -> Mat4 -> Mat4 -> s -> RunWorld -> b -> IO ()
outputScreenBegin' gamedata proj2D proj3D modv3D = \s run b -> do
-- 3D --
let modv = modv3D
projmodv = proj3D `mappend` modv
normal = modv
-- space box
let sh = griddataShadeSpace $ gamedataGridData gamedata
colormap = griddataColorMap $ gamedataGridData gamedata
ix0 = ostateColorIx0 $ levelpuzzleOutputState $ runLevelPuzzleWorld run
ix1 = ostateColorIx1 $ levelpuzzleOutputState $ runLevelPuzzleWorld run
alpha = ostateAlpha $ levelpuzzleOutputState $ runLevelPuzzleWorld run
tweak = sceneTweak $ runScene run
--shadeSpaceColor sh tweak 1.0 modv $ smoothColor (colormapAt colormap ix0)
-- (colormapAt colormap ix1) alpha
shadeSpace sh tweak 1.0 modv
-- cube
let sh = rundataShadeCube $ gamedataRunData gamedata
shadeCube sh 1.0 projmodv normal 0.0 run
-- face names
drawFaceNamesBegin gamedata projmodv run
-- message path
let sh = griddataShadePath $ gamedataGridData gamedata
shadePathBegin sh 1.0 projmodv
shadePathRadius sh valueRunPathRadius
shadePathColor sh valueRunPathColor
shadePathDrawPath0 sh (gridPath $ runGrid run)
shadePathEnd sh
--------------------------------------------------------------------------------
-- Main
outputScreenMain :: GameData -> RunWorld -> IO ()
outputScreenMain gamedata run =
return ()
outputScreenMain' :: GameData -> Mat4 -> Mat4 -> Mat4 -> s -> RunWorld -> b -> IO ()
outputScreenMain' gamedata proj2D proj3D modv3D = \s run b -> do
-- 3D --
let modv = modv3D
projmodv = proj3D `mappend` modv
normal = modv
-- space box
let sh = griddataShadeSpace $ gamedataGridData gamedata
colormap = griddataColorMap $ gamedataGridData gamedata
ix0 = ostateColorIx0 $ levelpuzzleOutputState $ runLevelPuzzleWorld run
ix1 = ostateColorIx1 $ levelpuzzleOutputState $ runLevelPuzzleWorld run
alpha = ostateAlpha $ levelpuzzleOutputState $ runLevelPuzzleWorld run
tweak = sceneTweak $ runScene run
--shadeSpaceColor sh tweak 1.0 modv $ smoothColor (colormapAt colormap ix0)
-- (colormapAt colormap ix1) alpha
shadeSpace sh tweak 1.0 modv
-- cube
let sh = rundataShadeCube $ gamedataRunData gamedata
beta = 1.0 -- grayscale
shadeCube sh 1.0 projmodv modv beta run
-- face names
drawFaceNames gamedata 1.0 projmodv
-- message path
let sh = griddataShadePath $ gamedataGridData gamedata
shadePathBegin sh 1.0 projmodv
shadePathRadius sh valueRunPathRadius
shadePathColor sh valueRunPathColor
shadePathDrawPath0 sh (gridPath $ runGrid run)
shadePathEnd sh
--------------------------------------------------------------------------------
-- End
outputScreenEnd :: GameData -> RunWorld -> IO ()
outputScreenEnd gamedata run =
return ()
outputScreenEnd' :: GameData -> Mat4 -> Mat4 -> Mat4 ->
s -> RunWorld -> b -> IO ()
outputScreenEnd' gamedata proj modv normal s run b = do
return ()
--------------------------------------------------------------------------------
-- Faces
outputScreenLevelMode :: GameData -> RunWorld -> IO ()
outputScreenLevelMode gamedata run = do
return ()
outputScreenPuzzleMode :: GameData -> RunWorld -> IO ()
outputScreenPuzzleMode gamedata run = do
return ()
outputScreenMemoryMode :: GameData -> RunWorld -> IO ()
outputScreenMemoryMode gamedata run = do
return ()
outputScreenForeign :: GameData -> RunWorld -> IO ()
outputScreenForeign griddata run = do
return ()
outputScreenKonami :: GameData -> RunWorld -> IO ()
outputScreenKonami griddata run = do
return ()
--------------------------------------------------------------------------------
-- AtFace
outputScreenAtFace' :: GameData -> Mat4 -> Mat4 -> Mat4 ->
AtFaceState -> RunWorld -> b -> IO ()
outputScreenAtFace' gamedata proj2D proj3D modv3D s run b = do
-- 3D --
let modv = modv3D
projmodv = proj3D `mappend` modv
normal = modv
-- space box
let sh = griddataShadeSpace $ gamedataGridData gamedata
colormap = griddataColorMap $ gamedataGridData gamedata
ix0 = ostateColorIx0 $ levelpuzzleOutputState $ runLevelPuzzleWorld run
ix1 = ostateColorIx1 $ levelpuzzleOutputState $ runLevelPuzzleWorld run
alpha = ostateAlpha $ levelpuzzleOutputState $ runLevelPuzzleWorld run
tweak = sceneTweak $ runScene run
--shadeSpaceColor sh tweak 1.0 modv $ smoothColor (colormapAt colormap ix0)
-- (colormapAt colormap ix1) alpha
shadeSpace sh tweak 1.0 modv
-- cube
let sh = rundataShadeCube $ gamedataRunData gamedata
a = cameraViewAlpha $ runCamera run
beta = 1.0 - a * a
shadeCube sh 1.0 projmodv modv beta run
-- face names
let alpha = cameraViewAlpha $ runCamera run
drawFaceNames gamedata (1.0 - alpha) projmodv
-- message path
let sh = griddataShadePath $ gamedataGridData gamedata
shadePathBegin sh 1.0 projmodv
shadePathRadius sh valueRunPathRadius
shadePathColor sh valueRunPathColor
shadePathDrawPath0 sh (gridPath $ runGrid run)
shadePathEnd sh
-- escape corners
--drawAtFaceCorners gamedata alpha projmodv s run
outputScreenAtFace''' :: GameData -> Mat4 -> Mat4 -> Mat4 ->
AtFaceState -> RunWorld -> b -> IO ()
outputScreenAtFace''' gamedata proj2D proj3D modv3D = \s run b -> do
-- 3D --
let modv = modv3D
projmodv = proj3D `mappend` modv
normal = modv
-- space box
let sh = griddataShadeSpace $ gamedataGridData gamedata
colormap = griddataColorMap $ gamedataGridData gamedata
ix0 = ostateColorIx0 $ levelpuzzleOutputState $ runLevelPuzzleWorld run
ix1 = ostateColorIx1 $ levelpuzzleOutputState $ runLevelPuzzleWorld run
alpha = ostateAlpha $ levelpuzzleOutputState $ runLevelPuzzleWorld run
tweak = sceneTweak $ runScene run
--shadeSpaceColor sh tweak 1.0 modv $ smoothColor (colormapAt colormap ix0)
-- (colormapAt colormap ix1) alpha
shadeSpace sh tweak 1.0 modv
-- cube
let sh = rundataShadeCube $ gamedataRunData gamedata
a = cameraViewAlpha $ runCamera run
beta = a * a
shadeCube sh 1.0 projmodv modv beta run
-- face names
let alpha = cameraViewAlpha $ runCamera run
drawFaceNames gamedata alpha projmodv
-- message path
let sh = griddataShadePath $ gamedataGridData gamedata
shadePathBegin sh 1.0 projmodv
shadePathRadius sh valueRunPathRadius
shadePathColor sh valueRunPathColor
shadePathDrawPath0 sh (gridPath $ runGrid run)
shadePathEnd sh
-- escape corners
--drawAtFaceCorners gamedata (1.0 - alpha) projmodv s run
-- | iterationMain' withouth face names
outputScreenAToB :: GameData -> Mat4 -> Mat4 -> Mat4 -> s -> RunWorld -> b -> IO ()
outputScreenAToB gamedata proj2D proj3D modv3D s run b = do
-- 3D --
let modv = modv3D
projmodv = proj3D `mappend` modv
normal = modv
-- space box
let sh = griddataShadeSpace $ gamedataGridData gamedata
colormap = griddataColorMap $ gamedataGridData gamedata
ix0 = ostateColorIx0 $ levelpuzzleOutputState $ runLevelPuzzleWorld run
ix1 = ostateColorIx1 $ levelpuzzleOutputState $ runLevelPuzzleWorld run
alpha = ostateAlpha $ levelpuzzleOutputState $ runLevelPuzzleWorld run
tweak = sceneTweak $ runScene run
--shadeSpaceColor sh tweak 1.0 modv $ smoothColor (colormapAt colormap ix0)
-- (colormapAt colormap ix1) alpha
shadeSpace sh tweak 1.0 modv
-- cube
let sh = rundataShadeCube $ gamedataRunData gamedata
shadeCube sh 1.0 projmodv modv 0.0 run
-- message path
let sh = griddataShadePath $ gamedataGridData gamedata
shadePathBegin sh 1.0 projmodv
shadePathRadius sh valueRunPathRadius
shadePathColor sh valueRunPathColor
shadePathDrawPath0 sh (gridPath $ runGrid run)
shadePathEnd sh
--------------------------------------------------------------------------------
--
drawFaceNames :: GameData -> Float -> Mat4 -> IO ()
drawFaceNames gamedata alpha projmodv = do
let fsh = gamedataFontShade gamedata
ffd = gamedataFontData gamedata
r = valueRunCubeRadius
fontShade fsh alpha projmodv
fontDrawDefault fsh ffd valueRunCubeFontSize valueRunCubeFontColor
fontSetPlane3D fsh 0 0 1 0 1 0
fontDraw3DCentered fsh ffd (-r) 0 0 "LevelMode"
fontSetPlane3D fsh 1 0 0 0 1 0
fontDraw3DCentered fsh ffd 0 0 (r) "GameCenter"
fontSetPlane3D fsh 0 0 (-1) 0 1 0
fontDraw3DCentered fsh ffd (r) 0 0 "PuzzleMode"
fontSetPlane3D fsh (-1) 0 0 0 1 0
fontDraw3DCentered fsh ffd 0 0 (-r) "MemoryMode"
drawFaceNamesBegin :: GameData -> Mat4 -> RunWorld -> IO ()
drawFaceNamesBegin gamedata projmodv run = do
let fsh = gamedataFontShade gamedata
ffd = gamedataFontData gamedata
r = valueRunCubeRadius
fadeNames = fade fadeNamesTicksInv 0.0 (worldTick run)
fontShade fsh fadeNames projmodv
fontDrawDefault fsh ffd valueRunCubeFontSize valueRunCubeFontColor
fontSetPlane3D fsh 0 0 1 0 1 0
fontDraw3DCentered fsh ffd (-r) 0 0 "LevelMode"
fontSetPlane3D fsh 0 0 (-1) 0 1 0
fontDraw3DCentered fsh ffd (r) 0 0 "PuzzleMode"
fontSetPlane3D fsh (-1) 0 0 0 1 0
fontDraw3DCentered fsh ffd 0 0 (-r) "MemoryMode"
where
fadeNamesTicks = 10.0
fadeNamesTicksInv = 1.0 / fadeNamesTicks
{-
drawAtFaceCorners :: GameData -> Float -> Mat4 -> AtFaceState -> RunWorld -> IO ()
drawAtFaceCorners gamedata alpha projmodv s run = do
let Shape wth hth = sceneShape $ runScene run
wth' = valueRunCubeRadius * wth
hth' = valueRunCubeRadius * hth
r = valueRunCubeRadius * 1.001
case atfacestateFace s of
FaceLevelMode ->
cornersDraw3D gamedata alpha projmodv
(-r) (-hth') (-wth')
(hth * valueSceneCornerSize) 0.0 0.0 (2.0 * wth')
(wth * valueSceneCornerSize) 0.0 (2.0 * hth') 0.0
FacePuzzleMode ->
cornersDraw3D gamedata alpha projmodv
(r) (-hth') (wth')
(hth * valueSceneCornerSize) 0.0 0.0 (-2.0 * wth')
(wth * valueSceneCornerSize) 0.0 (2.0 * hth') 0.0
FaceMemoryMode ->
cornersDraw3D gamedata alpha projmodv
(wth') (-hth') (-r)
(hth * valueSceneCornerSize) ((-2.0) * wth') 0.0 0.0
(wth * valueSceneCornerSize) 0.0 (2.0 * hth') 0.0
_ ->
return ()
where
cornersDraw3D :: GameData -> Float -> Mat4 ->
Float -> Float -> Float ->
Float -> Float -> Float -> Float ->
Float -> Float -> Float -> Float -> IO ()
cornersDraw3D gamedata alpha projmodv
p0 p1 p2
sizeX x0 x1 x2
sizeY y0 y1 y2 = do
let sh = griddataShadeGeneral $ gamedataGridData gamedata
cornerdata = rundataCornerData $ gamedataRunData gamedata
shadeGeneral sh 1.0 projmodv
glActiveTexture gl_TEXTURE0
glBindTexture gl_TEXTURE_2D $ cornerdataTex cornerdata
-- populate pos
cornerdataWrite3D cornerdata p0 p1 p2 sizeX x0 x1 x2 sizeY y0 y1 y2
-- draw
glBindVertexArrayOES $ cornerdataVAO3D cornerdata
glDrawArrays gl_TRIANGLE_STRIP 0 24
-}
--------------------------------------------------------------------------------
-- helpers
fade :: Float -> Tick -> Tick -> Float
fade scale t0 t1 =
min 1.0 $ scale * rTF (t1 - t0)
| karamellpelle/grid | source/Game/Run/Output/Fancy/Screen.hs | gpl-3.0 | 14,035 | 0 | 13 | 3,788 | 2,631 | 1,311 | 1,320 | 205 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.StorageTransfer.TransferOperations.Cancel
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Cancels a transfer. Use the transferOperations.get method to check if
-- the cancellation succeeded or if the operation completed despite the
-- \`cancel\` request. When you cancel an operation, the currently running
-- transfer is interrupted. For recurring transfer jobs, the next instance
-- of the transfer job will still run. For example, if your job is
-- configured to run every day at 1pm and you cancel Monday\'s operation at
-- 1:05pm, Monday\'s transfer will stop. However, a transfer job will still
-- be attempted on Tuesday. This applies only to currently running
-- operations. If an operation is not currently running, \`cancel\` does
-- nothing. *Caution:* Canceling a transfer job can leave your data in an
-- unknown state. We recommend that you restore the state at both the
-- destination and the source after the \`cancel\` request completes so
-- that your data is in a consistent state. When you cancel a job, the next
-- job computes a delta of files and may repair any inconsistent state. For
-- instance, if you run a job every day, and today\'s job found 10 new
-- files and transferred five files before you canceled the job,
-- tomorrow\'s transfer operation will compute a new delta with the five
-- files that were not copied today plus any new files discovered tomorrow.
--
-- /See:/ <https://cloud.google.com/storage-transfer/docs Storage Transfer API Reference> for @storagetransfer.transferOperations.cancel@.
module Network.Google.Resource.StorageTransfer.TransferOperations.Cancel
(
-- * REST Resource
TransferOperationsCancelResource
-- * Creating a Request
, transferOperationsCancel
, TransferOperationsCancel
-- * Request Lenses
, tocXgafv
, tocUploadProtocol
, tocAccessToken
, tocUploadType
, tocPayload
, tocName
, tocCallback
) where
import Network.Google.Prelude
import Network.Google.StorageTransfer.Types
-- | A resource alias for @storagetransfer.transferOperations.cancel@ method which the
-- 'TransferOperationsCancel' request conforms to.
type TransferOperationsCancelResource =
"v1" :>
CaptureMode "name" "cancel" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] CancelOperationRequest :>
Post '[JSON] Empty
-- | Cancels a transfer. Use the transferOperations.get method to check if
-- the cancellation succeeded or if the operation completed despite the
-- \`cancel\` request. When you cancel an operation, the currently running
-- transfer is interrupted. For recurring transfer jobs, the next instance
-- of the transfer job will still run. For example, if your job is
-- configured to run every day at 1pm and you cancel Monday\'s operation at
-- 1:05pm, Monday\'s transfer will stop. However, a transfer job will still
-- be attempted on Tuesday. This applies only to currently running
-- operations. If an operation is not currently running, \`cancel\` does
-- nothing. *Caution:* Canceling a transfer job can leave your data in an
-- unknown state. We recommend that you restore the state at both the
-- destination and the source after the \`cancel\` request completes so
-- that your data is in a consistent state. When you cancel a job, the next
-- job computes a delta of files and may repair any inconsistent state. For
-- instance, if you run a job every day, and today\'s job found 10 new
-- files and transferred five files before you canceled the job,
-- tomorrow\'s transfer operation will compute a new delta with the five
-- files that were not copied today plus any new files discovered tomorrow.
--
-- /See:/ 'transferOperationsCancel' smart constructor.
data TransferOperationsCancel =
TransferOperationsCancel'
{ _tocXgafv :: !(Maybe Xgafv)
, _tocUploadProtocol :: !(Maybe Text)
, _tocAccessToken :: !(Maybe Text)
, _tocUploadType :: !(Maybe Text)
, _tocPayload :: !CancelOperationRequest
, _tocName :: !Text
, _tocCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'TransferOperationsCancel' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'tocXgafv'
--
-- * 'tocUploadProtocol'
--
-- * 'tocAccessToken'
--
-- * 'tocUploadType'
--
-- * 'tocPayload'
--
-- * 'tocName'
--
-- * 'tocCallback'
transferOperationsCancel
:: CancelOperationRequest -- ^ 'tocPayload'
-> Text -- ^ 'tocName'
-> TransferOperationsCancel
transferOperationsCancel pTocPayload_ pTocName_ =
TransferOperationsCancel'
{ _tocXgafv = Nothing
, _tocUploadProtocol = Nothing
, _tocAccessToken = Nothing
, _tocUploadType = Nothing
, _tocPayload = pTocPayload_
, _tocName = pTocName_
, _tocCallback = Nothing
}
-- | V1 error format.
tocXgafv :: Lens' TransferOperationsCancel (Maybe Xgafv)
tocXgafv = lens _tocXgafv (\ s a -> s{_tocXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
tocUploadProtocol :: Lens' TransferOperationsCancel (Maybe Text)
tocUploadProtocol
= lens _tocUploadProtocol
(\ s a -> s{_tocUploadProtocol = a})
-- | OAuth access token.
tocAccessToken :: Lens' TransferOperationsCancel (Maybe Text)
tocAccessToken
= lens _tocAccessToken
(\ s a -> s{_tocAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
tocUploadType :: Lens' TransferOperationsCancel (Maybe Text)
tocUploadType
= lens _tocUploadType
(\ s a -> s{_tocUploadType = a})
-- | Multipart request metadata.
tocPayload :: Lens' TransferOperationsCancel CancelOperationRequest
tocPayload
= lens _tocPayload (\ s a -> s{_tocPayload = a})
-- | The name of the operation resource to be cancelled.
tocName :: Lens' TransferOperationsCancel Text
tocName = lens _tocName (\ s a -> s{_tocName = a})
-- | JSONP
tocCallback :: Lens' TransferOperationsCancel (Maybe Text)
tocCallback
= lens _tocCallback (\ s a -> s{_tocCallback = a})
instance GoogleRequest TransferOperationsCancel where
type Rs TransferOperationsCancel = Empty
type Scopes TransferOperationsCancel =
'["https://www.googleapis.com/auth/cloud-platform"]
requestClient TransferOperationsCancel'{..}
= go _tocName _tocXgafv _tocUploadProtocol
_tocAccessToken
_tocUploadType
_tocCallback
(Just AltJSON)
_tocPayload
storageTransferService
where go
= buildClient
(Proxy :: Proxy TransferOperationsCancelResource)
mempty
| brendanhay/gogol | gogol-storage-transfer/gen/Network/Google/Resource/StorageTransfer/TransferOperations/Cancel.hs | mpl-2.0 | 7,665 | 0 | 16 | 1,585 | 810 | 486 | 324 | 112 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleContexts #-}
module Main where
import ConfigParse
import SnapshotDatabase
import TMSnapshot
import Control.Monad.Except
import Database.SQLite.Simple
import Data.Either.Utils (forceEither) -- provided by MissingH
import Data.Semigroup ((<>))
import Options.Applicative
import System.Exit (ExitCode (ExitSuccess, ExitFailure), exitWith)
data RequestedSnapshots = RequestedSnapshots
{ yearly :: Bool
, monthly :: Bool
, weekly :: Bool
, daily :: Bool
, hourly :: Bool
, quater_hourly :: Bool
} deriving (Show)
-- TODO better way to compare TMSnapshots and Database snapshots metadata
reqToTypes :: RequestedSnapshots -> [SnapshotTimeline]
reqToTypes req
| yearly req = Yearly : (reqToTypes req { yearly = False })
| monthly req = Monthly : (reqToTypes req { monthly = False })
| weekly req = Weekly : (reqToTypes req { weekly = False })
| daily req = Daily : (reqToTypes req { daily = False })
| hourly req = Hourly : (reqToTypes req { hourly = False })
| quater_hourly req = QuaterHourly : (reqToTypes req { quater_hourly = False })
| otherwise = []
-- TODO use submcommands, so you can have other commands for explictly
-- pruning, listing, purging, etc.
cliParser :: Parser RequestedSnapshots
cliParser = RequestedSnapshots
<$> switch
( long "yearly"
<> help "This snapshot is a yearly snapshot")
<*> switch
( long "monthly"
<> help "This snapshot is a monthly snapshot")
<*> switch
( long "weekly"
<> help "This snapshot is a weekly snapshot")
<*> switch
( long "daily"
<> help "This snapshot is a daily snapshot")
<*> switch
( long "hourly"
<> help "This snapshot is a hourly snapshot")
<*> switch
( long "quater-hourly"
<> help "This snapshot is a quater_hourly snapshot")
handleCli :: (MonadError String m, MonadIO m) => [SnapshotTimeline] -> m ()
handleCli [] = throwError "Specify at least one snapshot type (see --help)"
handleCli timelines = do
-- Get our config file options about how many snapshots to keep
cp <- liftIO $ getConfigParser "apfs-auto-snapshot.cfg"
let timelineLimits = forceEither $ getTimelineConfig cp
-- Open the database connection with foreign key support
conn <- liftIO $ open "apfs-auto-snapshot.db"
liftIO $ execute_ conn "PRAGMA foreign_keys = ON"
-- Remove any snapshots from the database that don't exist in time machine
-- any more (deleted outside of this program).
-- TODO should maybe add logging if this finds a missing snapshot
expectedSnaps <- liftIO $ getStoredSnapshots conn
tmSnaps <- listTMSnapshots
let tmSnapIds = map tmId tmSnaps
let missingSnaps = filter (\s -> (snapshotName s) `notElem` tmSnapIds) expectedSnaps
liftIO $ mapM_ (deleteStoredSnapshot conn) missingSnaps
-- Create our new snapshot
tmSnap <- createTMSnapshot
storedSnap <- liftIO $ storeSnapshot conn tmSnap
liftIO $ storeTimelines conn storedSnap timelines
-- Slide the timeline windows
liftIO $ deleteTimelines conn Yearly (yearlyLimit timelineLimits)
liftIO $ deleteTimelines conn Monthly (monthlyLimit timelineLimits)
liftIO $ deleteTimelines conn Weekly (weeklyLimit timelineLimits)
liftIO $ deleteTimelines conn Daily (dailyLimit timelineLimits)
liftIO $ deleteTimelines conn Hourly (hourlyLimit timelineLimits)
liftIO $ deleteTimelines conn QuaterHourly (quaterHourlyLimit timelineLimits)
-- Delete any backups that are now outside of the timeline window
toDeleteFromDb <- liftIO $ snapshotsWithoutTimelines conn
let toDeleteTmIds = map snapshotName toDeleteFromDb
let toDeleteFromTM = filter (\s -> (tmId s) `elem` toDeleteTmIds) tmSnaps
mapM_ deleteTMSnapshot toDeleteFromTM
liftIO $ mapM_ (deleteStoredSnapshot conn) toDeleteFromDb
printAndExit :: String -> IO ()
printAndExit errMsg = do
putStrLn $ "Error: " ++ errMsg
exitWith $ ExitFailure 1
main :: IO ()
main = do
let opts = info (cliParser <**> helper)
( fullDesc
<> progDesc "Create a new snapshot in the given timelines"
<> header "apfs-auto-snapshot - Automaticaaly craete and delete APFS snapshots")
req <- execParser opts
let snapshotTypes = reqToTypes req
result <- runExceptT $ handleCli snapshotTypes
case result of
Right _ -> return ()
Left err -> printAndExit err
| vimalloc/apfs-auto-snapshot | src/Main.hs | agpl-3.0 | 4,593 | 0 | 15 | 1,089 | 1,087 | 539 | 548 | 91 | 2 |
{-# LANGUAGE TypeOperators, ScopedTypeVariables
, FlexibleContexts, TypeFamilies
#-}
{-# OPTIONS_GHC -Wall #-}
----------------------------------------------------------------------
-- |
-- Module : Shady.CompileImage
-- Copyright : (c) Conal Elliott 2009
-- License : AGPLv3
--
-- Maintainer : conal@conal.net
-- Stability : experimental
--
-- Compile a parameterized image
----------------------------------------------------------------------
module Shady.CompileImage (ImageB, imageBProg,imSurfB, eyePos) where
import Data.Derivative (powVal)
import qualified TypeUnary.Vec as V
import Shady.Language.Type (R1,R2)
import Shady.Language.Exp ((:=>),pureE)
import Shady.Color -- (white,HasColor(..))
import Shady.Image (Image)
import Shady.CompileE (GLSL)
import Shady.ParamSurf (xyPlane)
import Shady.Lighting (intrinsic,view1)
import Shady.CompileSurface (EyePosE,SurfB,surfBProg)
import Shady.Misc (EyePos)
-- Built on top of RunSurface
-- | 2D animation
type ImageB c = R1 :=> Image c
eyePos :: EyePos
eyePos = (0, 0.75, 2.5) -- tweak
eyePosE :: EyePosE
eyePosE = pureE (V.vec3 ex ey ez) where (ex,ey,ez) = eyePos
imSurfB :: HasColor c => ImageB c -> SurfB
imSurfB imb t = (intrinsic, view1, xyPlane , toColor . imb (powVal t))
-- | GLSL program for an 'ImageB'.
imageBProg :: HasColor c => ImageB c -> GLSL R1 R2
imageBProg = surfBProg eyePosE . imSurfB
| conal/shady-graphics | src/Shady/CompileImage.hs | agpl-3.0 | 1,409 | 0 | 9 | 225 | 325 | 196 | 129 | 24 | 1 |
-- | Tools for efficient serialization of Scientific.
module ScifiTools where
import Data.Scientific
import Data.List
import Data.Function
-- |Serialization function which uses always the shortest form of
-- given scientific number. If two formats have equal length, then we
-- use the most readable format (i.e. normal decimal number)
compactShow :: Scientific -> String
compactShow x = minimumBy (compare `on` length) (normal:compact:integer)
where (ds,exp) = toDecimalDigits x
tidyExp = exp - length ds
fixSign (x:xs) = (x:map abs xs)
normal = formatScientific Fixed Nothing x
compact = concatMap show (fixSign ds) ++ "E" ++ show tidyExp
integer = if fromInteger (floor x) == x then [show (floor x)] else []
| koodilehto/kryptoradio | data_sources/exchange/ScifiTools.hs | agpl-3.0 | 757 | 0 | 11 | 156 | 200 | 108 | 92 | 12 | 2 |
module Problem059 where
import Data.Bits
import Data.Char
import Data.List
main = do
t <- readFile "problem-059.txt"
let cs = read ("[" ++ t ++ "]") :: [Int]
let key = findKey cs
print $ map chr key
print $ map chr $ decrypt cs key
print $ sum $ decrypt cs key
findKey cs = snd $ foldl1' min [(d, key) | a <- ['a' .. 'z'], b <- ['a' .. 'z'], c <- ['a' .. 'z'],
let key = map ord [a, b, c],
let cs' = decrypt cs key,
let d = distance freq (stat cs')]
-- http://en.wikipedia.org/wiki/Letter_frequency
freq = [ ('a', 0.08167)
, ('b', 0.01492)
, ('c', 0.02782)
, ('d', 0.04253)
, ('e', 0.13000)
, ('f', 0.02228)
, ('g', 0.02015)
, ('h', 0.06094)
, ('i', 0.06966)
, ('j', 0.00153)
, ('k', 0.00772)
, ('l', 0.04025)
, ('m', 0.02406)
, ('n', 0.06749)
, ('o', 0.07507)
, ('p', 0.01929)
, ('q', 0.00095)
, ('r', 0.05987)
, ('s', 0.06327)
, ('t', 0.09056)
, ('u', 0.02758)
, ('v', 0.00978)
, ('w', 0.02360)
, ('x', 0.00150)
, ('y', 0.01974)
, ('z', 0.00074)
]
distance = distance' 0.0
where distance' n [] _ = n
distance' n _ [] = n
distance' n (a:as) (b:bs)
| fst a < fst b = distance' n as (b:bs)
| fst a > fst b = distance' n (a:as) bs
| otherwise = distance' (n + (snd a - snd b) ^ 2) as bs
stat cs = map (\g -> (head g, fromIntegral (length g) / fromIntegral n)) $ group cs'
where cs' = sort $ map (toLower . chr) cs
n = length cs'
decrypt cs ks = zipWith xor cs (cycle ks)
| vasily-kartashov/playground | euler/problem-059.hs | apache-2.0 | 1,772 | 0 | 14 | 682 | 762 | 419 | 343 | 52 | 3 |
import Data.List (findIndices, permutations, sort, splitAt, tails)
import Data.Ratio (Ratio, (%))
import Data.Set (Set)
import qualified Data.Set as Set
import Helpers.CoinsInARow (minimaxDifference)
type Permutation = [Int]
-- descents :: Permutation -> Int
-- descents (a':a:as)
-- | a' > a = descents (a:as) + 1
-- | otherwise = descents (a:as)
-- descents _ = 0
average :: (Integral a) => [a] -> Rational
average l = fromIntegral (sum l) % fromIntegral (length l)
mDescents :: Int -> Permutation -> Int
mDescents m x = length $ filter (uncurry (>)) $ x `zip` drop m x
-- Number of m-tuples (x_{i} > x_{i + 1} > ... > x_{i + m})
m'Descents :: Int -> Permutation -> Int
m'Descents m x = length $ filter startsWithM'Descent $ take (length x - m + 1) $ tails x where
startsWithM'Descent p = all (uncurry (>)) $ take (m - 1) $ p `zip` tail p
fixedPoints :: Permutation -> Int
fixedPoints p = length $ filter (uncurry (==)) $ [1..] `zip` p
numberOfCycles :: Permutation -> Int
numberOfCycles = length . cycleSizes
numberOfKCycles :: Int -> Permutation -> Int
numberOfKCycles k p = length $ filter (==k) $ cycleSizes p
largestCycle :: Permutation -> Int
largestCycle = maximum . cycleSizes
shortestCycle :: Permutation -> Int
shortestCycle = minimum . cycleSizes
cycleStructure :: Permutation -> String
cycleStructure p = "(" ++ recurse 1 (Set.fromList [1..length p]) where
recurse x unseen
| null unseen = ")"
| x `Set.member` unseen = show x ++ recurse (p !! (x - 1)) (Set.delete x unseen)
| otherwise = ")(" ++ recurse (minimum unseen) unseen
lengthOfFirstCycle :: Permutation -> Int
lengthOfFirstCycle p = recurse 1 (head p) where
recurse c 1 = c
recurse c p' = recurse (c + 1) (p !! (p' - 1))
cycleSizes :: Permutation -> [Int]
cycleSizes p = sort $ recurse 1 0 [] $ Set.fromList [1..length p] where
recurse x c sizes unseen
| null unseen = c : sizes
| x `Set.member` unseen = recurse (p !! (x - 1)) (c + 1) sizes (Set.delete x unseen)
| otherwise = recurse (minimum unseen) 0 (c : sizes) unseen
inversionNumber :: Permutation -> Int
inversionNumber = recurse 0 where
recurse c [] = c
recurse c (p:ps) = recurse (c + contribution) ps where
contribution = length $ filter (<p) ps
majorIndex :: Permutation -> Int
majorIndex = recurse 1 0 where
recurse i c (p:p':ps) = recurse (i + 1) (if p > p' then c + i else c) (p':ps)
recurse i c _ = c
longestIncreasingSubsequence :: Permutation -> Int
longestIncreasingSubsequence = recurse [] where
recurse l [] = length l
recurse l ps'@(p:ps)
| all (<p) l = recurse (p:l) ps
| otherwise = recurse (replaceFirst (>p) p l) ps
longestDecreasingSubsequence :: Permutation -> Int
longestDecreasingSubsequence = recurse [] where
recurse l [] = length l
recurse l ps'@(p:ps)
| all (>p) l = recurse (p:l) ps
| otherwise = recurse (replaceFirst (<p) p l) ps
-- This fails if there is no element matching the predicate.
replaceFirst :: Show a => (a -> Bool) -> a -> [a] -> [a]
replaceFirst f a as = replaceAt (head $ findIndices f as) a as where
replaceAt i a as = let (before,after) = splitAt i as in before ++ (a: tail after)
firstStatistic f n = average $ map head $ filter f $ permutations [1..n]
firstLetterKMDescents k m = firstStatistic ((==k) . mDescents m) -- X
firstLetterKFixedPoints k = firstStatistic ((==k) . fixedPoints) -- Table IV
firstLetterKCycles k = firstStatistic ((==k) . numberOfCycles) -- X
firstLetterKCycles' k = firstStatistic ((==1) . numberOfKCycles k) -- Table III
firstLetterKCycles'' k = firstStatistic ((==k) . numberOfKCycles 4)
-- firstLetterTwoCycles k = firstStatistic ((==[k, n-k]) . cycleSizes) -- Table III
firstLetterLargestCycle k = firstStatistic ((==k) . largestCycle) -- Table VI
firstLetterLargestCycle' k = firstStatistic ((<=k) . largestCycle)
firstLetterShortestCycle k = firstStatistic ((==k) . shortestCycle) -- Table I
firstLetterShortestCycle' k = firstStatistic ((>=k) . shortestCycle) -- Table II
firstLetterInversion k = firstStatistic ((==k) . inversionNumber) -- Table V
firstLetterMajorIndex k = firstStatistic ((==k) . majorIndex)
-- firstStatistic ((==9) . minimaxDifference) 9
-- 5377 % 896
-- map (\i -> firstStatistic ((==i) . minimaxDifference) 8) [0,2..16]
-- [1345 % 448,4021 % 1024,39423 % 8720, ..., 9 % 2]
-- map (\i -> firstStatistic ((==i) . minimaxDifference) 7) [-8, -6..4]
-- [5 % 2,3 % 1,663 % 196,325 % 88,2045 % 552,1285 % 304,1187 % 256]
-- map (\i -> firstStatistic ((==i) . minimaxDifference) 6) [1,3..9]
-- [349 % 120,219 % 62,719 % 192,81 % 22,7 % 2]
--map (\i -> firstStatistic ((==i) . minimaxDifference) 5) [-3,-1..5]
-- [2 % 1,21 % 8,131 % 44,17 % 5,27 % 8]
-- map (\i -> firstStatistic ((==i) . minimaxDifference) 4) [0,2,4]
-- [7 % 4,11 % 4,5 % 2]
--VI | Expected value of the first letter of a permutation of S_n that contains an
--VI | (n-k) cycle:
--VI | 0 1 2 3 4
--VI | 1: 1 % 1 . . . .
--VI | 2: 2 % 1 1 / 1 . . .
--VI | 3: 5 % 2 2 % 1 1 / 1 . .
--VI | 4: 3 % 1 5 % 2 7 / 3 1 / 1 .
--VI | 5: 7 % 2 3 % 1 3 % 1 13 / 5 1 / 1
--VI | 6: 4 % 1 7 % 2 7 % 2 17 / 5 3 / 1
--VI | 7: 9 % 2 4 % 1 4 % 1 4 % 1 53 / 14
--VI | 8: 5 % 1 9 % 2 9 % 2 9 % 2 31 / 7
--VI | 9: 11 % 2 5 % 1 5 % 1 5 % 1 5 % 1
--VI | 10: 6 % 1 11 % 2 11 % 2
--I | Table I
--I | Expected value of the first letter of a permutation of S_n that consists of a
--I | floor(n/2) cycle AND ceil(n/2) cycle (n >= 2):
--I | [1/1, 7/4, 3/1, 7/2, 4/1, 9/2, 5/1, 11/2]
--II | Table II
--II | Expected value of the first letter of a permutation of S_n whose shortest permutation is >= k:
--II | 1 2 3 4 5
--II | 1: 1 % 1 . . . .
--II | 2: 3 % 2 2 % 1 . . .
--II | 3: 2 % 1 5 % 2 5 % 2 . .
--II | 4: 5 % 2 3 % 1 3 % 1 3 % 1 .
--II | *: 3 % 1 7 % 2 7 % 2 7 % 2 * / *
--II | 6: 7 % 2 4 % 1 4 % 1 4 % 1 * / *
--II | *: 4 % 1 9 % 2 9 % 2 9 % 2 ** / **
--II | 8: 9 % 2 5 % 1 5 % 1 5 % 1 ** / *
--II | 9: 5 % 1 * % * * % * * % * * % *
-- n-2 cycles: 5 % 2, 29 % 11, 19 % 7, 47 % 17, 14 % 5, 65 % 23, 37 % 13]
--III | Table III
--III | One 2-cycle (n >= 2): 2/1, 2/1, 2/1, 3/1, 18/5, 4/1, 130/29, 5/1, 1282/233
--III | ? 2 ? 3 ? 4 ? 5 ?
--III | One 3-cycle (n >= 3): 5/2, 5/2, 3/1, 13/4, 4/1, 9/2, 131/26, 11/2
--III | ? 2.5, 3, ? 4, 4.5, ? , 5.5
--III | One 4-cycle (n >= 4): 3/1, 3/1, 7/2, 4/1, 13/3, 5/1, 11/2
--III | ? 3 3.5 4 ? 5 5.5
-- All 1-cycles and 2-cycles: 2/1, 2/1, 7/3, 13/5, 3/1, 37/11, 413/109, 1219/291, 975/211
--IV | Table IV
--IV | Conjecture: the expected value of the first letter of a permutation of [n]
--IV | with k fixed points is (n - k + 2)/2
--IV | 2 3 4 5 6
--IV | 3: 8 % 3 . . . .
--IV | 4: 5 % 2 10 % 3 . . .
--IV | 5: 27 % 10 3 % 1 4 % 1 . .
--IV | 6: 21 % 8 28 % 9 7 % 2 14 % 3 .
--IV | 7: 208 % 75 10 % 3 32 % 9 4 % 1 16 % 3
--IV | 8: 27 % 10 13 % 4 15 % 4 4 % 1 9 % 2
--IV | 9: 105 % 37 10 % 3 55 % 14 25 % 6 40 % 9
--IV | 10: 11 % 4 66 % 19 77 % 20 22 % 5 55 % 12
--IV | 11: 240 % 83 222 % 65 51 % 13
--V | Table V
--V | Notice that the numerator of the i-th term is related to the denominator of
--V | the (i+1)-th term
--V | *Main> map (firstLetterInversion 1) [2..8]
--V | [2/1, 3/2, 4/3, 5/4, 6/5, 7/6, 8/7]
--V | * *
--V | *Main> map (firstLetterInversion 2) [3..10]
--V | [5/2, 9/5, 14/9, 10/7, 27/20, 35/27, 44/35, 27/22]
--V | ________ ____________
--V | _________ ____________
--V | * *
--V | *Main> map (firstLetterInversion 3) [4..10] -- A005286
--V | [5/2, 29/15, 49/29, 76/49, 111/76, 155/111, ^CInterrupted.
--V | ____________
--V | ____________
--V | _____________
--V | *Main> map (firstLetterInversion 4) [5..10]
--V | [49/20, 2/1, 87/49, 95/58, 88/57, 59/40] -- A005287
--V |
--V | *Main> map (firstLetterInversion 5) [6..10] -- A005288
--V | [169/71, 343/169, 628/343, 267/157, 1717/1068]
--V | _______________
--V | _________________
| peterokagey/haskellOEIS | src/Sandbox/Sami/PermutationStatistics.hs | apache-2.0 | 8,823 | 0 | 13 | 2,798 | 1,719 | 942 | 777 | 75 | 3 |
{-# LANGUAGE RankNTypes #-}
module Hircine.Monad (
-- * Types
Hircine,
-- * Operations
receive,
send,
buffer,
fork,
-- * Running the bot
runHircine
) where
import Control.Monad
import Control.Monad.Trans.Reader
import Data.IORef
import qualified SlaveThread
import Hircine.Core
import Hircine.Command
import Hircine.Stream
type Hircine = ReaderT Stream IO
-- | Receive a single IRC message from the server.
receive :: Hircine Message
receive = ReaderT streamReceive
-- | Send an IRC command to the server.
send :: IsCommand c => c -> Hircine ()
send c = ReaderT $ \s -> streamSend s [toCommand c]
-- | Buffer up the inner 'send' calls, so that all the commands are sent
-- in one go.
buffer :: Hircine a -> Hircine a
buffer h = ReaderT $ \s -> do
buf <- newIORef []
r <- runReaderT h s {
streamSend = \cs ->
atomicModifyIORef' buf $ \css ->
css `seq` (cs : css, ())
}
-- Poison the IORef, so that no-one can touch it any more
css <- atomicModifyIORef buf $ \css -> (error "messages already sent", css)
let cs = concat $ reverse css
-- Perform the reversal *before* calling hsSend
-- This minimizes the time spent in hsSend's critical section
cs `seq` streamSend s cs
return r
-- | Run the inner action in a separate thread.
--
-- See the "SlaveThread" documentation for tips and caveats.
fork :: Hircine () -> Hircine ()
fork h = ReaderT $ void . SlaveThread.fork . runReaderT h
runHircine :: Hircine a -> Stream -> IO a
runHircine = runReaderT
| lfairy/hircine | Hircine/Monad.hs | apache-2.0 | 1,583 | 0 | 18 | 397 | 383 | 206 | 177 | 35 | 1 |
-- Copyright 2020 Google LLC
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
{-# LANGUAGE OverloadedStrings #-}
-- | Code to make sure every version-specific third-party Haskell package in
-- Google3 has a properly configured version-agnostic package.
--
-- TODO(georgevdd): Merge this and cabal2build into a single third-party
-- code maintenance tool.
module Google.Google3.Tools.Cabal2Build.VersionAgnosticThirdParty
( createOrUpdateWrapperPackage
) where
import Data.Maybe
import Data.Text (Text)
import qualified Data.Text as Text
import System.FilePath ((</>))
import System.Process (readProcess)
import qualified Google.Google3.Name as Google3
import qualified Google.Google3.Package as Google3
import qualified Google.Google3.Buildifier as Buildifier
import qualified Google.Google3.VCSClient as VCSClient
blazeQuery :: Google3.PackageName -> IO Text
blazeQuery package =
Text.pack <$> readProcess "blaze" [
"query", "--noshow_loading_progress", "--noannounce_rc",
"attr(tags, 'haskell-exposed', " ++ targets ++ ")",
"--output=label_kind"] ""
where
targets = show (Google3.Label package $ Google3.TargetName "all")
ruleKinds :: Google3.PackageName -> IO [(Google3.Label, Google3.RuleClass)]
ruleKinds = fmap parse . blazeQuery
where parse = mapMaybe (collect . Text.words) . Text.lines
collect [kind, "rule", label] = Just (Google3.parseLabel label, kind)
collect _ = Nothing
unversionedPackageName :: Google3.PackageName -> Google3.PackageName
unversionedPackageName (Google3.PackageName package) =
Google3.PackageName (init package)
haskellBinary, haskellLibrary, filegroup, shBinary :: Text
haskellBinary = "haskell_binary"
haskellLibrary = "haskell_library"
filegroup = "filegroup"
shBinary = "sh_binary"
wrapperRule :: Google3.Label -> Google3.RuleClass -> Maybe Google3.Rule
wrapperRule label@(Google3.Label _ target) kind
| kind == haskellBinary
= Just (rule shBinary)
{ Google3.ruleSrcs = [Google3.LabelSource label] }
| kind == haskellLibrary
= Just (rule haskellLibrary)
{ Google3.ruleDeps = [Google3.Labelled label] }
| kind == filegroup
= Just (rule filegroup)
{ Google3.ruleSrcs = [Google3.LabelSource label] }
| otherwise = Nothing
where
rule ruleClass = Google3.Rule {
Google3.ruleClass = ruleClass,
Google3.ruleName = target,
Google3.ruleSrcs = [],
Google3.ruleDeps = [],
Google3.ruleOtherAttrs = []
}
wrapperPackage
:: Google3.PackageName
-> [Google3.License]
-> [(Google3.Label, Google3.RuleClass)]
-> Google3.Package
wrapperPackage packageName licenses rulesAndKinds =
Google3.Package
(unversionedPackageName packageName)
"" -- preamble
(Google3.PackageAttributes [Google3.parseLabel "//visibility:public"])
licenses
"" -- packageLicenseFile
rules
[]
where
rules = mapMaybe (uncurry wrapperRule) rulesAndKinds'
-- Don't forward the autogenerated "Paths_foo" library.
rulesAndKinds' = filter (not . isPathsLibrary . fst) rulesAndKinds
isPathsLibrary (Google3.Label _ (Google3.TargetName n))
= "Paths_" `Text.isPrefixOf` n
makeWrapperPackage
:: Google3.PackageName
-> [Google3.License]
-> IO Google3.Package
makeWrapperPackage latestVersion licenses
= wrapperPackage latestVersion licenses <$> ruleKinds latestVersion
writeBuildFile :: Google3.Package -> FilePath -> IO ()
writeBuildFile pkg bfile = do
writeFile bfile (show . Google3.pPrint . Google3.packageSyntax $ pkg)
Buildifier.call [bfile]
createOrUpdateWrapperPackage
:: VCSClient.VCSClient
-> Google3.PackageName
-> [Google3.License]
-> IO ()
createOrUpdateWrapperPackage vcs package licenses = do
wrapper <- makeWrapperPackage package licenses
let wrapperBuildFile =
Google3.google3absolutePath
(VCSClient.g3Dir vcs)
(Google3.packageName wrapper)
</> "BUILD"
VCSClient.withOpenFile vcs wrapperBuildFile $
writeBuildFile wrapper wrapperBuildFile
| google/cabal2bazel | src/Google/Google3/Tools/Cabal2Build/VersionAgnosticThirdParty.hs | apache-2.0 | 4,623 | 0 | 14 | 886 | 997 | 543 | 454 | 92 | 2 |
-- Copyright 2019 Google LLC
--
-- Use of this source code is governed by a BSD-style
-- license that can be found in the LICENSE file or at
-- https://developers.google.com/open-source/licenses/bsd
{-# LANGUAGE CPP #-}
{-# LANGUAGE OverloadedStrings #-}
module GHC.SourceGen.Syntax.Internal where
import GHC.Hs
( HsDecl
, HsExpr(..)
, HsLit
, HsModule
, HsType(..)
, HsBind
, HsTyVarBndr
, HsOverLit
, HsValBinds
, HsMatchContext
, IE
, LHsExpr
, LHsQTyVars
, Match
, MatchGroup
, GRHS
, GRHSs
, Stmt
, ConDecl
, LHsSigType
, ImportDecl
, LHsSigWcType
, LHsWcType
, TyFamInstDecl
#if !MIN_VERSION_ghc(8,8,0)
, LHsRecField
, LHsRecUpdField
#endif
#if MIN_VERSION_ghc(9,0,0)
, HsPatSigType
#endif
#if MIN_VERSION_ghc(9,2,0)
, HsConDeclH98Details
#else
, HsConDeclDetails
#endif
)
import GHC.Hs.Binds (Sig, HsLocalBinds)
#if MIN_VERSION_ghc(8,6,0)
import GHC.Hs.Decls (DerivStrategy)
#else
import BasicTypes (DerivStrategy)
#endif
import GHC.Hs.Decls (HsDerivingClause)
import GHC.Hs.Pat
#if MIN_VERSION_ghc(9,0,0)
import GHC.Types.SrcLoc (SrcSpan, Located, GenLocated(..), mkGeneralSrcSpan)
#else
import RdrName (RdrName)
import SrcLoc (SrcSpan, Located, GenLocated(..), mkGeneralSrcSpan)
#endif
#if MIN_VERSION_ghc(9,2,0)
import GHC.Parser.Annotation
( SrcSpanAnn'(..)
, AnnSortKey(..)
, EpAnn(..)
, EpAnnComments
, emptyComments
)
#endif
#if MIN_VERSION_ghc(9,0,0)
import GHC.Types.Basic (PromotionFlag(..))
#elif MIN_VERSION_ghc(8,8,0)
import BasicTypes (PromotionFlag(..))
#else
import GHC.Hs.Type (Promoted(..))
#endif
#if MIN_VERSION_ghc(8,10,0)
import qualified GHC.Hs as GHC
#elif MIN_VERSION_ghc(8,6,0)
import qualified GHC.Hs.Extension as GHC
#else
import qualified HsExtension as GHC
import qualified PlaceHolder as GHC
#endif
#if MIN_VERSION_ghc(9,0,0)
import GHC.Types.Var (Specificity)
#endif
import GHC.Hs.Extension (GhcPs)
#if MIN_VERSION_ghc(8,10,0)
type NoExtField = GHC.NoExtField
#elif MIN_VERSION_ghc(8,6,0)
type NoExtField = GHC.NoExt
#endif
#if MIN_VERSION_ghc(8,10,0)
noExt :: (NoExtField -> a) -> a
noExt = ($ GHC.NoExtField)
#elif MIN_VERSION_ghc(8,6,0)
noExt :: (NoExtField -> a) -> a
noExt = ($ GHC.NoExt)
#else
noExt :: a -> a
noExt = id
#endif
#if MIN_VERSION_ghc(8,6,0)
noExtOrPlaceHolder :: (NoExtField -> a) -> a
noExtOrPlaceHolder = noExt
#else
noExtOrPlaceHolder :: (GHC.PlaceHolder -> a) -> a
noExtOrPlaceHolder = withPlaceHolder
#endif
#if MIN_VERSION_ghc(9,2,0)
withEpAnnNotUsed :: (EpAnn ann -> a) -> a
withEpAnnNotUsed = ($ EpAnnNotUsed)
#elif MIN_VERSION_ghc(8,6,0)
withEpAnnNotUsed :: (NoExtField -> a) -> a
withEpAnnNotUsed = noExt
#else
withEpAnnNotUsed :: a -> a
withEpAnnNotUsed = id
#endif
#if MIN_VERSION_ghc(9,2,0)
withNoAnnSortKey :: (AnnSortKey -> a) -> a
withNoAnnSortKey = ($ NoAnnSortKey)
#elif MIN_VERSION_ghc(8,6,0)
withNoAnnSortKey :: (NoExtField -> a) -> a
withNoAnnSortKey = noExt
#else
withNoAnnSortKey :: a -> a
withNoAnnSortKey = id
#endif
#if MIN_VERSION_ghc(9,2,0)
withEmptyEpAnnComments :: (EpAnnComments -> a) -> a
withEmptyEpAnnComments = ($ emptyComments)
#elif MIN_VERSION_ghc(8,6,0)
withEmptyEpAnnComments :: (NoExtField -> a) -> a
withEmptyEpAnnComments = noExt
#else
withEmptyEpAnnComments :: a -> a
withEmptyEpAnnComments = id
#endif
#if MIN_VERSION_ghc(8,6,0)
withPlaceHolder :: a -> a
withPlaceHolder = id
#else
withPlaceHolder :: (GHC.PlaceHolder -> a) -> a
withPlaceHolder = ($ GHC.PlaceHolder)
#endif
#if MIN_VERSION_ghc(8,6,0)
withPlaceHolders :: a -> a
withPlaceHolders = id
#else
withPlaceHolders :: ([GHC.PlaceHolder] -> a) -> a
withPlaceHolders = ($ [])
#endif
builtSpan :: SrcSpan
builtSpan = mkGeneralSrcSpan "<ghc-source-gen>"
builtLoc :: e -> Located e
builtLoc = L builtSpan
#if MIN_VERSION_ghc(9,2,0)
type SrcSpanAnn ann = GHC.SrcSpanAnn' (EpAnn ann)
#else
type SrcSpanAnn ann = SrcSpan
#endif
mkLocated :: a -> GenLocated (SrcSpanAnn ann) a
mkLocated = L (toAnn builtSpan)
where
#if MIN_VERSION_ghc(9,2,0)
toAnn = SrcSpanAnn EpAnnNotUsed
#else
toAnn = id
#endif
-- In GHC-8.8.* (but not >=8.10 or <=8.6), source locations for Pat aren't
-- stored in each node, and LPat is a synonym for Pat.
builtPat :: Pat' -> LPat'
#if MIN_VERSION_ghc(9,2,0)
builtPat = mkLocated
#elif MIN_VERSION_ghc(8,8,0) && !MIN_VERSION_ghc(8,10,0)
builtPat = id
#else
builtPat = builtLoc
#endif
#if MIN_VERSION_ghc(8,8,0)
promoted, notPromoted :: PromotionFlag
promoted = IsPromoted
notPromoted = NotPromoted
#else
promoted, notPromoted :: Promoted
promoted = Promoted
notPromoted = NotPromoted
#endif
-- TODO: these Haddock cross-references don't link to the actual
-- definition, only to the module they come from. I think it's
-- because the classes aren't in scope here.
-- | A Haskell type, as it is represented after the parsing step.
--
-- Instances:
--
-- * 'GHC.SourceGen.Overloaded.BVar'
-- * 'GHC.SourceGen.Overloaded.Var'
-- * 'GHC.SourceGen.Overloaded.Par'
-- * 'GHC.SourceGen.Overloaded.App'
-- * 'GHC.SourceGen.Overloaded.HasTuple'
type HsType' = HsType GhcPs
-- | A Haskell pattern, as it is represented after the parsing step.
--
-- Instances:
--
-- * 'GHC.SourceGen.Overloaded.BVar'
-- * 'GHC.SourceGen.Overloaded.Par'
-- * 'GHC.SourceGen.Overloaded.HasTuple'
-- * 'GHC.SourceGen.Overloaded.HasList'
-- * 'GHC.SourceGen.Lit.HasLit'
type Pat' = Pat GhcPs
-- | A Haskell expression, as it is represented after the parsing step.
--
-- Instances:
--
-- * 'GHC.SourceGen.Overloaded.BVar'
-- * 'GHC.SourceGen.Overloaded.Var'
-- * 'GHC.SourceGen.Overloaded.Par'
-- * 'GHC.SourceGen.Overloaded.App'
-- * 'GHC.SourceGen.Overloaded.HasTuple'
-- * 'GHC.SourceGen.Overloaded.HasList'
-- * 'GHC.SourceGen.Lit.HasLit'
type HsExpr' = HsExpr GhcPs
type LHsExpr' = LHsExpr GhcPs
-- | A Haskell declaration, as it is represented after the parsing step.
--
-- Instances:
--
-- * 'GHC.SourceGen.Binds.HasValBind'
-- * 'GHC.SourceGen.Binds.HasPatBind'
type HsDecl' = HsDecl GhcPs
-- | An imported or exported entity, as it is represented after the parsing step.
--
-- Instances:
--
-- * 'GHC.SourceGen.Overloaded.BVar'
-- * 'GHC.SourceGen.Overloaded.Var'
type IE' = IE GhcPs
-- | A type variable binding, as it is represented after the parsing step.
--
-- Construct with either 'GHC.SourceGen.Overloaded.bVar' (for regular type
-- variables) or `GHC.SourceGen.Type.kindedVar` (for kind signatures).
--
-- Instances:
--
-- * 'GHC.SourceGen.Overloaded.BVar'
#if MIN_VERSION_ghc(9,0,0)
type HsTyVarBndr' = HsTyVarBndr () GhcPs
type HsTyVarBndrS' = HsTyVarBndr Specificity GhcPs
#else
type HsTyVarBndr' = HsTyVarBndr GhcPs
type HsTyVarBndrS' = HsTyVarBndr GhcPs
#endif
type HsLit' = HsLit GhcPs
#if MIN_VERSION_ghc(9,0,0)
type HsModule' = HsModule
#else
type HsModule' = HsModule GhcPs
#endif
type HsBind' = HsBind GhcPs
type HsLocalBinds' = HsLocalBinds GhcPs
type HsValBinds' = HsValBinds GhcPs
type Sig' = Sig GhcPs
#if MIN_VERSION_ghc(9,0,0)
type HsMatchContext' = HsMatchContext GhcPs
#else
type HsMatchContext' = HsMatchContext RdrName
#endif
type Match' = Match GhcPs
type MatchGroup' = MatchGroup GhcPs
type GRHS' = GRHS GhcPs
type GRHSs' = GRHSs GhcPs
type Stmt' = Stmt GhcPs LHsExpr'
type HsOverLit' = HsOverLit GhcPs
type LHsQTyVars' = LHsQTyVars GhcPs
type ConDecl' = ConDecl GhcPs
#if MIN_VERSION_ghc(9,2,0)
type HsConDeclDetails' = HsConDeclH98Details GhcPs
#else
type HsConDeclDetails' = HsConDeclDetails GhcPs
#endif
type LHsSigType' = LHsSigType GhcPs
type ImportDecl' = ImportDecl GhcPs
type LHsSigWcType' = LHsSigWcType GhcPs
type LHsWcType' = LHsWcType GhcPs
type HsDerivingClause' = HsDerivingClause GhcPs
type LHsRecField' arg = LHsRecField GhcPs arg
type LHsRecUpdField' = LHsRecUpdField GhcPs
type LPat' = LPat GhcPs
type TyFamInstDecl' = TyFamInstDecl GhcPs
#if MIN_VERSION_ghc(8,6,0)
type DerivStrategy' = DerivStrategy GhcPs
#else
type DerivStrategy' = DerivStrategy
#endif
#if MIN_VERSION_ghc(9,0,0)
type HsPatSigType' = HsPatSigType GhcPs
#else
type HsPatSigType' = LHsSigWcType'
#endif
#if MIN_VERSION_ghc(9,2,0)
type LIdP = GHC.LIdP GHC.GhcPs
#else
type LIdP = Located (GHC.IdP GHC.GhcPs)
#endif
| google/ghc-source-gen | src/GHC/SourceGen/Syntax/Internal.hs | bsd-3-clause | 8,174 | 0 | 8 | 1,229 | 1,018 | 660 | 358 | 104 | 1 |
module LLVM.Assembler (
module LLVM.Assembler.Grammar
) where
import LLVM.Assembler.Grammar
| jfischoff/llvm-quasi | src/LLVM/Assembler.hs | bsd-3-clause | 96 | 0 | 5 | 13 | 21 | 14 | 7 | 3 | 0 |
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.Raw.EXT.TextureLODBias
-- Copyright : (c) Sven Panne 2015
-- License : BSD3
--
-- Maintainer : Sven Panne <svenpanne@gmail.com>
-- Stability : stable
-- Portability : portable
--
-- The <https://www.opengl.org/registry/specs/EXT/texture_lod_bias.txt EXT_texture_lod_bias> extension.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.Raw.EXT.TextureLODBias (
-- * Enums
gl_MAX_TEXTURE_LOD_BIAS_EXT,
gl_TEXTURE_FILTER_CONTROL_EXT,
gl_TEXTURE_LOD_BIAS_EXT
) where
import Graphics.Rendering.OpenGL.Raw.Tokens
| phaazon/OpenGLRaw | src/Graphics/Rendering/OpenGL/Raw/EXT/TextureLODBias.hs | bsd-3-clause | 726 | 0 | 4 | 84 | 43 | 35 | 8 | 5 | 0 |
module Main where
import Control.Concurrent.STM
import Data.IntMap
import Yesod
import Dispatch ()
import Foundation
main :: IO ()
main = do
tstore <- atomically $ newTVar empty
tident <- atomically $ newTVar 0
warpEnv $ App tident tstore
| Kwarrtz/flash | Main.hs | bsd-3-clause | 257 | 0 | 9 | 56 | 82 | 43 | 39 | 11 | 1 |
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE OverloadedStrings #-}
module TypeChecker where
import qualified Data.Map as Map
import qualified Data.Sequence as Seq
import Control.Monad.State
import AST
import Atom
import I18n
type Context = Map.Map VariableName ClassName
type Checker a = State ( Seq.Seq Error ) a
typeCheck :: NameTable -> Seq.Seq Error
typeCheck nameTable = evalState ( checkNameTable >> get ) Seq.empty
where
checkNameTable :: Checker ()
checkNameTable = mapM_ checkClass ( Map.toList nameTable )
isSubtype :: ClassName -> ClassName -> Bool
isSubtype child parent
| parent == child = True
| "Object" == child = False
| otherwise = isSubtype ( parentClassName $ nameTable Map.! child ) parent
-- TODO: Convert those to Map.
fields :: ClassName -> Properties
fields ( ClassName "Object" ) = Map.empty
fields name = let foundClass = nameTable Map.! name
in classProperties foundClass `Map.union`
fields ( parentClassName foundClass )
methods :: ClassName -> Methods
methods ( ClassName "Object" ) = Map.empty
methods name = let foundClass = nameTable Map.! name
in classMethods foundClass `Map.union`
methods ( parentClassName foundClass )
findMethod :: MethodName -> ClassName -> Checker ( Maybe Method )
findMethod name subType = nothing
( name `Map.lookup` methods subType )
( addError ( UndefinedMethod subType ) name )
findClass :: ClassName -> Checker ( Maybe Class )
findClass name = nothing
( name `Map.lookup` nameTable )
( addError UnknownType name )
checkClass :: ( ClassName, Class ) -> Checker ()
checkClass ( className, curClass )
= mapM_ checkMethod ( Map.toList ( classMethods curClass ) )
where
thisContext = Map.singleton "this" className
checkMethod :: ( MethodName, Method ) -> Checker ()
checkMethod ( mName, method ) = do
void $ onJust
( checkWithContext context ( mBody method ) )
$ \ returnType -> do
unless ( returnType `isSubtype` retType method ) $
addError ( InvalidMethodReturnType mName ( retType method ) ) returnType
return Nothing
void $ onJust
( return ( parentMethod ( parentClassName curClass ) ) )
$ \ parMethod -> do
unless
( retType parMethod == retType method &&
argsOrder parMethod == argsOrder method )
( addError ( InvalidSignature className ) mName )
return Nothing
-- TODO Validate overrides.
where
context :: Context
context = thisContext `Map.union` args method
parentMethod :: ClassName -> Maybe Method
parentMethod "Object" = Nothing
parentMethod parClassName = mplus
( mName `Map.lookup` classMethods parClass )
( parentMethod ( parentClassName parClass ) )
where
parClass = nameTable Map.! parClassName
checkWithContext :: Context -> Expression -> Checker ( Maybe ClassName )
checkWithContext context = check
where
check :: Expression -> Checker ( Maybe ClassName )
check ( Variable name ) = nothing ( Map.lookup name context )
( addError VariableHasNoType name )
check ( AttributeAccess expr attrName ) =
check expr `onJust` \ subType ->
( attrName `Map.lookup` fields subType ) `nothing`
addError ( AccessingUknownAttr subType ) attrName
check ( MethodInvocation expr name invocArgs ) =
lift2M
( check expr `onJust` findMethod name )
( allJust <$> mapM check invocArgs )
validSubexprs
where
validSubexprs :: Method -> [ ClassName ] -> Checker ClassName
validSubexprs foundMethod argsTypes = do
if gotCount == expectedCount
then
forM_ ( zip argsTypes ( Map.toList ( args foundMethod ) ) )
$ \ ( inputType, ( argName, argType ) ) ->
unless ( inputType `isSubtype` argType ) $
addError ( MethodArgsInvalidType
name argName argType ) inputType
else
addError ( InvalidNumberOfArgs name expectedCount ) gotCount
return ( retType foundMethod )
where
gotCount = length argsTypes
expectedCount = Map.size ( args foundMethod )
check ( Object constrType args ) = do
foundClass <- findClass constrType
void $ lift2M
( return foundClass )
( allJust <$> mapM check args )
validSubexprs
return ( const constrType <$> foundClass )
where
validSubexprs :: Class -> [ ClassName ] -> Checker ()
validSubexprs ( Class _ _ _ Constructor{..} ) argsTypes =
if gotCount == expectedCount
then
forM_ ( zip argsTypes ( Map.toList constructorArgs ) )
$ \ ( inputType, ( argName, argType ) ) ->
unless ( inputType `isSubtype` argType ) $
addError ( ConstructorArgsInvalidType
constrType argName argType ) inputType
else
addError
( ConstructorInvalidNumberOfArgs constrType expectedCount )
gotCount
where
gotCount = length argsTypes
expectedCount = Map.size constructorArgs
check ( Coercion castType subExpr ) = do
foundClass <- findClass castType
void $ lift2M
( return foundClass )
( check subExpr )
validSubexprs
return ( const castType <$> foundClass )
where
validSubexprs _ castFromType =
unless ( castFromType `isSubtype` castType )
( addError ( InvalidTypeCasting castFromType ) castType )
lift2M :: Monad m
=> m ( Maybe a )
-> m ( Maybe b )
-> ( a -> b -> m c )
-> m ( Maybe c )
lift2M a b f = do
x1 <- a
x2 <- b
onJust ( return $ (,) <$> x1 <*> x2 ) ( fmap Just . uncurry f )
allJust :: [ Maybe a ] -> Maybe [ a ]
allJust = allJustStep []
where
-- TODO: Optimize.
allJustStep acc [] = Just acc
allJustStep acc ( Just v : xs ) = allJustStep ( acc ++ [ v ] ) xs
allJustStep _ ( Nothing : _ ) = Nothing
onJust :: Monad m => m ( Maybe a ) -> ( a -> m ( Maybe b ) ) -> m ( Maybe b )
onJust extr f = do
val <- extr
case val of
Just a -> f a
Nothing -> return Nothing
nothing :: Monad m => Maybe a -> m b -> m ( Maybe a )
nothing Nothing f = f >> return Nothing
nothing v _ = return v
addError :: ( a -> TypeCheckError ) -> a -> Checker ()
addError constr arg
= modify ( Seq.|> Error "" 0 0 Fatal ( TypeCheckError ( constr arg ) ) )
| triplepointfive/Youtan | examples/FJ/TypeChecker.hs | bsd-3-clause | 7,099 | 0 | 21 | 2,479 | 2,019 | 1,016 | 1,003 | 148 | 10 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE DataKinds #-}
-- ^
-- All handlers
module Handlers.Main (app) where
import Api.Documentation
import Api.Main
import Control.Monad.Reader
import qualified Handlers.Lono as LO
import qualified Handlers.Xandar as XA
import Network.HTTP.Types.Status (ok200)
import Network.Wai (responseLBS)
import Servant
import Servant.Utils.Enter ((:~>)(NT), Enter, Entered, enter)
import Types.Common
-- ^
-- Create the main application containing all API endpoints
app :: ApiConfig -> ApiConfig -> Application
app xaConf loConf = serve mainApiProxyWithDocs (server :<|> Tagged serveDocs)
where
server :: Server MainApi
server = server' XA.handlers xaConf :<|> server' LO.handlers loConf
server' ::
(Enter (Entered Handler Api ret) Api Handler ret)
=> Entered Handler Api ret
-> ApiConfig
-> ret
server' hs cfg = enter (toHandler cfg) hs
toHandler :: ApiConfig -> Api :~> Handler
toHandler conf = NT (`runReaderT` conf)
serveDocs _ respond = respond $ responseLBS ok200 [docsType] markdownDocs
docsType = ("Content-Type", "text/markdown") | gabesoft/kapi | src/Handlers/Main.hs | bsd-3-clause | 1,197 | 0 | 10 | 215 | 309 | 178 | 131 | 29 | 1 |
{-# LANGUAGE FlexibleContexts, TypeSynonymInstances, FlexibleInstances, MultiParamTypeClasses #-}
module AbstractInterpreter.Assignment where
{-
Assignments {Name --> AbstractSet, Path} + stuff that can be done with it
-}
import Prelude hiding (subtract)
import TypeSystem
import Utils.Utils
import Utils.ToString
import Utils.Unification
import AbstractInterpreter.AbstractSet
import AbstractInterpreter.ASSubtract as As
import Data.List
import Data.Map (Map, (!), keys, intersection)
import qualified Data.Map as M
import qualified Data.Set as S
import Data.Set (Set)
import Data.Maybe
import Lens.Micro hiding ((&))
import Lens.Micro.TH
import Control.Arrow ((&&&))
import Control.Monad
type Assignments = VariableAssignmentsA AbstractSet
mergeAssgnss :: Syntax -> [Assignments] -> [Assignments]
mergeAssgnss _ []
= [M.empty]
mergeAssgnss syntax (a:as)
= do tail <- mergeAssgnss syntax as
mergeAssgns syntax a tail
mergeAssgns :: Syntax -> Assignments -> Assignments -> [Assignments]
mergeAssgns syntax assgs0 assgs1
= do let commonAssgns = assgs0 `intersection` assgs1 & keys
mergedAssgns <- commonAssgns |> ((!) assgs0 &&& (!) assgs1)
& filter (uncurry (/=))
|> uncurry (mergeAssgn syntax)
& allRight & either (const []) (:[])
let mergedAssgns' = zip commonAssgns mergedAssgns
let assgs' = M.union (M.fromList mergedAssgns') $ M.union assgs0 assgs1
return assgs'
mergeAssgn :: Syntax -> (AbstractSet, Maybe [Int]) -> (AbstractSet, Maybe [Int]) -> Either String (AbstractSet, Maybe [Int])
mergeAssgn syntax (a, pathA) (b, pathB)
| pathA /= pathB = Left "Context paths don't match"
| otherwise
= inMsg ("While trying to unify "++toParsable a++" and "++toParsable b) $
do
substitution <- unifySub (smallestOf syntax) a b
return (substitute substitution a, pathA)
-- we add a special rule for unification, that these variables *can* be matched with each other, despite having a different symbol
smallestOf :: Syntax -> AbstractSet -> AbstractSet -> Maybe AbstractSet
smallestOf syntax a b
| alwaysIsA' syntax a b = Just a
| alwaysIsA' syntax b a = Just b
| otherwise = Nothing
evalExpr f assgns e
= inMsg ("While abstractly evaluating the expression "++toParsable e) $ _evalExpr f assgns e
_evalExpr :: Map Name TypeName -> Assignments -> Expression -> Either String AbstractSet
_evalExpr _ assgns (MParseTree (MLiteral _ mi token))
= return $ ConcreteLiteral (fst mi) token
_evalExpr _ assgns (MParseTree (MInt _ mi i))
= return $ ConcreteLiteral (fst mi) (show i)
_evalExpr _ assgns (MParseTree seq@(PtSeq _ mi _))
= return $ ConcreteLiteral (fst mi) (show seq)
_evalExpr _ assgns (MVar _ n)
= checkExists n assgns ("Unknown variable: "++show n) |> fst
_evalExpr f _ (MCall defType n builtin _)
= do tp <- if builtin then return defType
else checkExists n f $ "AbstractInterpreter.Data: _evalExpr: function not found: "++ n
return $ EveryPossible tp " (Function call - ID not retrievable)" tp
_evalExpr f assgns (MSeq (gen, i) exprs)
| i < 0 = error $ "AbstractInterpreter/Assignemnt: evalExpr: invalid bnf-choice: "++show i
| otherwise
= exprs |+> _evalExpr f assgns |> AsSeq gen i
_evalExpr f assgns (MAscription t e)
= do e' <- _evalExpr f assgns e
unless (typeOf e' == t) $ Left $ "Ascription of "++toParsable e++" as "++t ++ " failed"
return e'
_evalExpr f assgns (MEvalContext _ nm hole)
= do (ctx, Just path) <- checkExists nm assgns $ "Unknwown variable"++show nm
hole' <- _evalExpr f assgns hole
return $ replaceAS ctx path hole'
| pietervdvn/ALGT | src/AbstractInterpreter/Assignment.hs | bsd-3-clause | 3,564 | 154 | 16 | 643 | 1,220 | 668 | 552 | 76 | 2 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Forum.Internal.Types where
import Bookkeeper (Book, Book', Identity, Sorted, sorted)
import qualified Data.ByteString as BS
import Data.Proxy (Proxy (..))
import Data.Reflection (Reifies (..))
import qualified Data.Text as T
import qualified Database.HsSqlPpp.Catalog as Sql
import qualified Database.HsSqlPpp.Types as Sql
import GHC.Generics (Generic)
import GHC.TypeLits
import GHC.Word (Word16)
import Hasql.Query (Query)
import Hasql.Class (Decodable, Encodable)
import Hasql.Pool (Pool)
{-import Hasql.Session (Session)-}
newtype PrimaryKey (tbl :: Symbol) val = PrimaryKey val
deriving (Eq, Show, Read, Generic, Ord)
instance Encodable val => Encodable (PrimaryKey tbl val)
instance Decodable val => Decodable (PrimaryKey tbl val)
newtype ForeignKey (tbl :: Symbol) val = ForeignKey val
deriving (Eq, Show, Read, Generic, Ord)
instance Encodable val => Encodable (ForeignKey tbl val)
instance Decodable val => Decodable (ForeignKey tbl val)
data DB = DB
{ dbCatalog :: Sql.Catalog
, dbSettings :: DBSettings
, dbConnectionPool :: Pool
}
data DBSettings = DBSettings
{ dbName :: BS.ByteString
, dbHost :: BS.ByteString
, dbPort :: Word16
, dbUser :: BS.ByteString
, dbPassword :: BS.ByteString
}
defaultDBSettings :: DBSettings
defaultDBSettings = DBSettings
{ dbName = "postgres"
, dbHost = "localhost"
, dbPort = 5432
, dbUser = "postgres"
, dbPassword = "postgres"
}
defaultTestDBSettings :: DBSettings
defaultTestDBSettings = DBSettings
{ dbName = "test"
, dbHost = "localhost"
, dbPort = 5432
, dbUser = "test"
, dbPassword = "test"
}
-- * SQL types represented as Haskell types
data Scalar (s :: Symbol)
instance KnownSymbol s => Reifies (Scalar s) Sql.Type where
reflect _ = Sql.ScalarType (T.pack $ symbolVal (Proxy :: Proxy s))
-- * SQL
newtype SQL a = SQL { runSQL' :: Query () [Book a] }
makeSQL :: Sorted as => Query () [Book' Identity as] -> SQL as
makeSQL q = SQL (fmap sorted <$> q)
| turingjump/forum | src/Forum/Internal/Types.hs | bsd-3-clause | 2,333 | 0 | 11 | 670 | 628 | 366 | 262 | -1 | -1 |
{-# LANGUAGE InstanceSigs #-} -- Because i love it
{-# LANGUAGE ScopedTypeVariables #-}
{-| Non-polymorphic semi-isomorphisms.
-}
module Sky.Isomorphism.Simple
( SemiIsomorphism
, packSemiIsomorphism
, unpackSemiIsomorphism
, toSemiIsomorphism
, applySemiIsomorphism
, unapplySemiIsomorphism
, revertSemiIsomorphism
, convertSemiIsomorphism
, iso
, apply
, unapply
, convert
, MumuIso
) where
import Prelude hiding (id, (.))
import Control.Category -- yay
import Data.Tuple (swap)
import Control.Monad ((<=<))
-- Note: Isomorphisms should be instances of Category.
----------------------------------------------------------------------------------------------------
class SemiIsomorphism i where
packSemiIsomorphism :: Monad m => (a -> m b, b -> m a) -> i m a b
unpackSemiIsomorphism :: Monad m => i m a b -> (a -> m b, b -> m a)
-- Derived
toSemiIsomorphism :: Monad m => (a -> m b) -> (b -> m a) -> i m a b
toSemiIsomorphism amb bma = packSemiIsomorphism (amb, bma)
applySemiIsomorphism :: Monad m => i m a b -> a -> m b
applySemiIsomorphism = fst . unpackSemiIsomorphism
unapplySemiIsomorphism :: Monad m => i m a b -> b -> m a
unapplySemiIsomorphism = snd . unpackSemiIsomorphism
revertSemiIsomorphism :: Monad m => i m a b -> i m b a
revertSemiIsomorphism = packSemiIsomorphism . swap . unpackSemiIsomorphism
convertSemiIsomorphism :: (Monad m, SemiIsomorphism j) => j m a b -> i m a b
convertSemiIsomorphism = packSemiIsomorphism . unpackSemiIsomorphism
----------------------------------------------------------------------------------------------------
-- Operators and stuff
iso :: forall i m a b. (SemiIsomorphism i, Monad m) => (a -> m b) -> (b -> m a) -> i m a b
iso = toSemiIsomorphism
apply :: forall i m a b. (SemiIsomorphism i, Monad m) => i m a b -> a -> m b
apply = applySemiIsomorphism
unapply :: forall i m a b. (SemiIsomorphism i, Monad m) => i m a b -> b -> m a
unapply = unapplySemiIsomorphism
convert :: forall i j m a b. (SemiIsomorphism i, Monad m, SemiIsomorphism j) => i m a b -> j m a b
convert = convertSemiIsomorphism
----------------------------------------------------------------------------------------------------
-- Simple semi-isomorphism
newtype MumuIso m a b = MumuIso { _rawMumuIso :: (a -> m b, b -> m a) }
instance Monad m => Category (MumuIso m) where
id = MumuIso (return, return)
(MumuIso (applyF, unapplyF)) . (MumuIso (applyG, unapplyG)) =
MumuIso ((applyF <=< applyG), (unapplyG <=< unapplyF))
instance SemiIsomorphism MumuIso where
packSemiIsomorphism = MumuIso
unpackSemiIsomorphism = _rawMumuIso
----------------------------------------------------------------------------------------------------
-- Ignore this!
class IsoFunctor f where
isomap :: forall i m a b x. (SemiIsomorphism i, Monad m) => i m a b -> f m x a -> f m x b
instance IsoFunctor MumuIso where
isomap :: forall i m a b x. (SemiIsomorphism i, Monad m) => i m a b -> MumuIso m x a -> MumuIso m x b
isomap isoA isoB = (convert isoA) . isoB where
| xicesky/sky-haskell-playground | src/Sky/Isomorphism/Simple.hs | bsd-3-clause | 3,161 | 0 | 12 | 662 | 961 | 523 | 438 | 55 | 1 |
-----------------------------------------------------------------------------
-- |
-- Copyright : (C) 2015 Dimitri Sabadie
-- License : BSD3
--
-- Maintainer : Dimitri Sabadie <dimitri.sabadie@gmail.com>
-- Stability : experimental
-- Portability : portable
--
-- Make a better world with a colored-one! This module exports a very
-- straight-forward type, 'Color', which is a 4-float vector.
--
-- > For now, any vector-related function/type uses "linear"’s vectors.
----------------------------------------------------------------------------
module Quaazar.Scene.Color (
-- * Color
Color(unColor)
, color
, colorR
, colorG
, colorB
-- * Coder-colors
, white
, black
, red
, green
, blue
, yellow
, magenta
, cyan
-- * Bright coder-colors
, brightRed
, brightGreen
, brightBlue
, brightYellow
, brightMagenta
, brightCyan
) where
import Control.Lens
import Data.Aeson
import Data.Aeson.Types ( typeMismatch )
import Foreign.Storable ( Storable )
import Linear.V3
import Quaazar.Render.GL.Shader ( Uniformable(..) )
-- |A color is a 3-float vector. The four channels are:
--
-- - *red*
-- - *green*
-- - *blue*
newtype Color = Color { unColor :: V3 Float } deriving (Floating,Fractional,Eq,Num,Ord,Show,Storable)
instance FromJSON Color where
parseJSON v = do
a' <- parseJSON v
case a' of
[r,g,b] -> return (color r g b)
_ -> typeMismatch "color" v
instance Uniformable Color where
sendUniform l = sendUniform l . unColor
color :: Float -> Float -> Float -> Color
color r g b = Color (V3 r g b)
colorR :: Color -> Float
colorR (Color c) = c^._x
colorG :: Color -> Float
colorG (Color c) = c^._y
colorB :: Color -> Float
colorB (Color c) = c^._z
white :: Color
white = color 1 1 1
black :: Color
black = color 0 0 0
red :: Color
red = color 1 0 0
brightRed :: Color
brightRed = color 1 0.5 0.5
green :: Color
green = color 0 1 0
brightGreen :: Color
brightGreen = color 0.5 1 0.5
blue :: Color
blue = color 0 0 1
brightBlue :: Color
brightBlue = color 0.5 0.5 1
yellow :: Color
yellow = color 1 1 0
brightYellow :: Color
brightYellow = color 1 1 0.5
magenta :: Color
magenta = color 1 0 1
brightMagenta :: Color
brightMagenta = color 1 0.5 1
cyan :: Color
cyan = color 0 1 1
brightCyan :: Color
brightCyan = color 0.5 1 1
| phaazon/quaazar | src/Quaazar/Scene/Color.hs | bsd-3-clause | 2,350 | 0 | 13 | 508 | 647 | 363 | 284 | 73 | 1 |
module TiFreeNames(module TiFreeNames,FreeNames(..)) where
import FreeNames
import HsIdent
import Maybe(mapMaybe)
freeTypeNames x = mapMaybe freeTypeName . freeNames $ x
freeValueNames x = mapMaybe freeValueName . freeNames $ x
freeVars x = filter isHsVar . freeValueNames $ x
freeTyvars x = filter isHsVar . freeTypeNames $ x
freeTypeName (n,ClassOrTypeNames) = Just n
freeTypeName (n,_) = Nothing
freeValueName (n,ValueNames) = Just n
freeValueName (n,_) = Nothing
-- Get the type parameters from the lhs of a type/newtype/data/class decl:
typeParams tp = [v|HsVar v<-freeTyvars tp] -- Hmm. Order?
| forste/haReFork | tools/base/TI/TiFreeNames.hs | bsd-3-clause | 605 | 2 | 8 | 90 | 183 | 101 | 82 | 13 | 1 |
{-# LANGUAGE CPP, DeriveDataTypeable, MultiParamTypeClasses, FlexibleInstances, TypeFamilies, Rank2Types, ScopedTypeVariables #-}
-- |
-- Module : Data.Vector.Storable
-- Copyright : (c) Roman Leshchinskiy 2009-2010
-- License : BSD-style
--
-- Maintainer : Roman Leshchinskiy <rl@cse.unsw.edu.au>
-- Stability : experimental
-- Portability : non-portable
--
-- 'Storable'-based vectors.
--
module Data.Vector.Storable (
-- * Storable vectors
Vector, MVector(..), Storable,
-- * Accessors
-- ** Length information
length, null,
-- ** Indexing
(!), (!?), head, last,
unsafeIndex, unsafeHead, unsafeLast,
-- ** Monadic indexing
indexM, headM, lastM,
unsafeIndexM, unsafeHeadM, unsafeLastM,
-- ** Extracting subvectors (slicing)
slice, init, tail, take, drop, splitAt,
unsafeSlice, unsafeInit, unsafeTail, unsafeTake, unsafeDrop,
-- * Construction
-- ** Initialisation
empty, singleton, replicate, generate, iterateN,
-- ** Monadic initialisation
replicateM, generateM, create,
-- ** Unfolding
unfoldr, unfoldrN,
constructN, constructrN,
-- ** Enumeration
enumFromN, enumFromStepN, enumFromTo, enumFromThenTo,
-- ** Concatenation
cons, snoc, (++), concat,
-- ** Restricting memory usage
force,
-- * Modifying vectors
-- ** Bulk updates
(//), update_,
unsafeUpd, unsafeUpdate_,
-- ** Accumulations
accum, accumulate_,
unsafeAccum, unsafeAccumulate_,
-- ** Permutations
reverse, backpermute, unsafeBackpermute,
-- ** Safe destructive updates
modify,
-- * Elementwise operations
-- ** Mapping
map, imap, concatMap,
-- ** Monadic mapping
mapM, mapM_, forM, forM_,
-- ** Zipping
zipWith, zipWith3, zipWith4, zipWith5, zipWith6,
izipWith, izipWith3, izipWith4, izipWith5, izipWith6,
-- ** Monadic zipping
zipWithM, zipWithM_,
-- * Working with predicates
-- ** Filtering
filter, ifilter, filterM,
takeWhile, dropWhile,
-- ** Partitioning
partition, unstablePartition, span, break,
-- ** Searching
elem, notElem, find, findIndex, findIndices, elemIndex, elemIndices,
-- * Folding
foldl, foldl1, foldl', foldl1', foldr, foldr1, foldr', foldr1',
ifoldl, ifoldl', ifoldr, ifoldr',
-- ** Specialised folds
all, any, and, or,
sum, product,
maximum, maximumBy, minimum, minimumBy,
minIndex, minIndexBy, maxIndex, maxIndexBy,
-- ** Monadic folds
foldM, foldM', fold1M, fold1M',
foldM_, foldM'_, fold1M_, fold1M'_,
-- * Prefix sums (scans)
prescanl, prescanl',
postscanl, postscanl',
scanl, scanl', scanl1, scanl1',
prescanr, prescanr',
postscanr, postscanr',
scanr, scanr', scanr1, scanr1',
-- * Conversions
-- ** Lists
toList, fromList, fromListN,
-- ** Other vector types
G.convert, unsafeCast,
-- ** Mutable vectors
freeze, thaw, copy, unsafeFreeze, unsafeThaw, unsafeCopy,
-- * Raw pointers
unsafeFromForeignPtr, unsafeFromForeignPtr0,
unsafeToForeignPtr, unsafeToForeignPtr0,
unsafeWith
) where
import qualified Data.Vector.Generic as G
import Data.Vector.Storable.Mutable ( MVector(..) )
import Data.Vector.Storable.Internal
import qualified Data.Vector.Fusion.Bundle as Bundle
import Foreign.Storable
import Foreign.ForeignPtr
import Foreign.Ptr
import Foreign.Marshal.Array ( advancePtr, copyArray )
import Control.DeepSeq ( NFData )
import Control.Monad.ST ( ST )
import Control.Monad.Primitive
import Prelude hiding ( length, null,
replicate, (++), concat,
head, last,
init, tail, take, drop, splitAt, reverse,
map, concatMap,
zipWith, zipWith3, zip, zip3, unzip, unzip3,
filter, takeWhile, dropWhile, span, break,
elem, notElem,
foldl, foldl1, foldr, foldr1,
all, any, and, or, sum, product, minimum, maximum,
scanl, scanl1, scanr, scanr1,
enumFromTo, enumFromThenTo,
mapM, mapM_ )
import qualified Prelude
import Data.Typeable ( Typeable )
import Data.Data ( Data(..) )
import Text.Read ( Read(..), readListPrecDefault )
import Data.Monoid ( Monoid(..) )
#include "vector.h"
-- | 'Storable'-based vectors
data Vector a = Vector {-# UNPACK #-} !Int
{-# UNPACK #-} !(ForeignPtr a)
deriving ( Typeable )
instance NFData (Vector a)
instance (Show a, Storable a) => Show (Vector a) where
showsPrec = G.showsPrec
instance (Read a, Storable a) => Read (Vector a) where
readPrec = G.readPrec
readListPrec = readListPrecDefault
instance (Data a, Storable a) => Data (Vector a) where
gfoldl = G.gfoldl
toConstr _ = error "toConstr"
gunfold _ _ = error "gunfold"
dataTypeOf _ = G.mkType "Data.Vector.Storable.Vector"
dataCast1 = G.dataCast
type instance G.Mutable Vector = MVector
instance Storable a => G.Vector Vector a where
{-# INLINE basicUnsafeFreeze #-}
basicUnsafeFreeze (MVector n fp) = return $ Vector n fp
{-# INLINE basicUnsafeThaw #-}
basicUnsafeThaw (Vector n fp) = return $ MVector n fp
{-# INLINE basicLength #-}
basicLength (Vector n _) = n
{-# INLINE basicUnsafeSlice #-}
basicUnsafeSlice i n (Vector _ fp) = Vector n (updPtr (`advancePtr` i) fp)
{-# INLINE basicUnsafeIndexM #-}
basicUnsafeIndexM (Vector _ fp) i = return
. unsafeInlineIO
$ withForeignPtr fp $ \p ->
peekElemOff p i
{-# INLINE basicUnsafeCopy #-}
basicUnsafeCopy (MVector n fp) (Vector _ fq)
= unsafePrimToPrim
$ withForeignPtr fp $ \p ->
withForeignPtr fq $ \q ->
copyArray p q n
{-# INLINE elemseq #-}
elemseq _ = seq
-- See http://trac.haskell.org/vector/ticket/12
instance (Storable a, Eq a) => Eq (Vector a) where
{-# INLINE (==) #-}
xs == ys = Bundle.eq (G.stream xs) (G.stream ys)
{-# INLINE (/=) #-}
xs /= ys = not (Bundle.eq (G.stream xs) (G.stream ys))
-- See http://trac.haskell.org/vector/ticket/12
instance (Storable a, Ord a) => Ord (Vector a) where
{-# INLINE compare #-}
compare xs ys = Bundle.cmp (G.stream xs) (G.stream ys)
{-# INLINE (<) #-}
xs < ys = Bundle.cmp (G.stream xs) (G.stream ys) == LT
{-# INLINE (<=) #-}
xs <= ys = Bundle.cmp (G.stream xs) (G.stream ys) /= GT
{-# INLINE (>) #-}
xs > ys = Bundle.cmp (G.stream xs) (G.stream ys) == GT
{-# INLINE (>=) #-}
xs >= ys = Bundle.cmp (G.stream xs) (G.stream ys) /= LT
instance Storable a => Monoid (Vector a) where
{-# INLINE mempty #-}
mempty = empty
{-# INLINE mappend #-}
mappend = (++)
{-# INLINE mconcat #-}
mconcat = concat
-- Length
-- ------
-- | /O(1)/ Yield the length of the vector.
length :: Storable a => Vector a -> Int
{-# INLINE length #-}
length = G.length
-- | /O(1)/ Test whether a vector if empty
null :: Storable a => Vector a -> Bool
{-# INLINE null #-}
null = G.null
-- Indexing
-- --------
-- | O(1) Indexing
(!) :: Storable a => Vector a -> Int -> a
{-# INLINE (!) #-}
(!) = (G.!)
-- | O(1) Safe indexing
(!?) :: Storable a => Vector a -> Int -> Maybe a
{-# INLINE (!?) #-}
(!?) = (G.!?)
-- | /O(1)/ First element
head :: Storable a => Vector a -> a
{-# INLINE head #-}
head = G.head
-- | /O(1)/ Last element
last :: Storable a => Vector a -> a
{-# INLINE last #-}
last = G.last
-- | /O(1)/ Unsafe indexing without bounds checking
unsafeIndex :: Storable a => Vector a -> Int -> a
{-# INLINE unsafeIndex #-}
unsafeIndex = G.unsafeIndex
-- | /O(1)/ First element without checking if the vector is empty
unsafeHead :: Storable a => Vector a -> a
{-# INLINE unsafeHead #-}
unsafeHead = G.unsafeHead
-- | /O(1)/ Last element without checking if the vector is empty
unsafeLast :: Storable a => Vector a -> a
{-# INLINE unsafeLast #-}
unsafeLast = G.unsafeLast
-- Monadic indexing
-- ----------------
-- | /O(1)/ Indexing in a monad.
--
-- The monad allows operations to be strict in the vector when necessary.
-- Suppose vector copying is implemented like this:
--
-- > copy mv v = ... write mv i (v ! i) ...
--
-- For lazy vectors, @v ! i@ would not be evaluated which means that @mv@
-- would unnecessarily retain a reference to @v@ in each element written.
--
-- With 'indexM', copying can be implemented like this instead:
--
-- > copy mv v = ... do
-- > x <- indexM v i
-- > write mv i x
--
-- Here, no references to @v@ are retained because indexing (but /not/ the
-- elements) is evaluated eagerly.
--
indexM :: (Storable a, Monad m) => Vector a -> Int -> m a
{-# INLINE indexM #-}
indexM = G.indexM
-- | /O(1)/ First element of a vector in a monad. See 'indexM' for an
-- explanation of why this is useful.
headM :: (Storable a, Monad m) => Vector a -> m a
{-# INLINE headM #-}
headM = G.headM
-- | /O(1)/ Last element of a vector in a monad. See 'indexM' for an
-- explanation of why this is useful.
lastM :: (Storable a, Monad m) => Vector a -> m a
{-# INLINE lastM #-}
lastM = G.lastM
-- | /O(1)/ Indexing in a monad without bounds checks. See 'indexM' for an
-- explanation of why this is useful.
unsafeIndexM :: (Storable a, Monad m) => Vector a -> Int -> m a
{-# INLINE unsafeIndexM #-}
unsafeIndexM = G.unsafeIndexM
-- | /O(1)/ First element in a monad without checking for empty vectors.
-- See 'indexM' for an explanation of why this is useful.
unsafeHeadM :: (Storable a, Monad m) => Vector a -> m a
{-# INLINE unsafeHeadM #-}
unsafeHeadM = G.unsafeHeadM
-- | /O(1)/ Last element in a monad without checking for empty vectors.
-- See 'indexM' for an explanation of why this is useful.
unsafeLastM :: (Storable a, Monad m) => Vector a -> m a
{-# INLINE unsafeLastM #-}
unsafeLastM = G.unsafeLastM
-- Extracting subvectors (slicing)
-- -------------------------------
-- | /O(1)/ Yield a slice of the vector without copying it. The vector must
-- contain at least @i+n@ elements.
slice :: Storable a
=> Int -- ^ @i@ starting index
-> Int -- ^ @n@ length
-> Vector a
-> Vector a
{-# INLINE slice #-}
slice = G.slice
-- | /O(1)/ Yield all but the last element without copying. The vector may not
-- be empty.
init :: Storable a => Vector a -> Vector a
{-# INLINE init #-}
init = G.init
-- | /O(1)/ Yield all but the first element without copying. The vector may not
-- be empty.
tail :: Storable a => Vector a -> Vector a
{-# INLINE tail #-}
tail = G.tail
-- | /O(1)/ Yield at the first @n@ elements without copying. The vector may
-- contain less than @n@ elements in which case it is returned unchanged.
take :: Storable a => Int -> Vector a -> Vector a
{-# INLINE take #-}
take = G.take
-- | /O(1)/ Yield all but the first @n@ elements without copying. The vector may
-- contain less than @n@ elements in which case an empty vector is returned.
drop :: Storable a => Int -> Vector a -> Vector a
{-# INLINE drop #-}
drop = G.drop
-- | /O(1)/ Yield the first @n@ elements paired with the remainder without copying.
--
-- Note that @'splitAt' n v@ is equivalent to @('take' n v, 'drop' n v)@
-- but slightly more efficient.
{-# INLINE splitAt #-}
splitAt :: Storable a => Int -> Vector a -> (Vector a, Vector a)
splitAt = G.splitAt
-- | /O(1)/ Yield a slice of the vector without copying. The vector must
-- contain at least @i+n@ elements but this is not checked.
unsafeSlice :: Storable a => Int -- ^ @i@ starting index
-> Int -- ^ @n@ length
-> Vector a
-> Vector a
{-# INLINE unsafeSlice #-}
unsafeSlice = G.unsafeSlice
-- | /O(1)/ Yield all but the last element without copying. The vector may not
-- be empty but this is not checked.
unsafeInit :: Storable a => Vector a -> Vector a
{-# INLINE unsafeInit #-}
unsafeInit = G.unsafeInit
-- | /O(1)/ Yield all but the first element without copying. The vector may not
-- be empty but this is not checked.
unsafeTail :: Storable a => Vector a -> Vector a
{-# INLINE unsafeTail #-}
unsafeTail = G.unsafeTail
-- | /O(1)/ Yield the first @n@ elements without copying. The vector must
-- contain at least @n@ elements but this is not checked.
unsafeTake :: Storable a => Int -> Vector a -> Vector a
{-# INLINE unsafeTake #-}
unsafeTake = G.unsafeTake
-- | /O(1)/ Yield all but the first @n@ elements without copying. The vector
-- must contain at least @n@ elements but this is not checked.
unsafeDrop :: Storable a => Int -> Vector a -> Vector a
{-# INLINE unsafeDrop #-}
unsafeDrop = G.unsafeDrop
-- Initialisation
-- --------------
-- | /O(1)/ Empty vector
empty :: Storable a => Vector a
{-# INLINE empty #-}
empty = G.empty
-- | /O(1)/ Vector with exactly one element
singleton :: Storable a => a -> Vector a
{-# INLINE singleton #-}
singleton = G.singleton
-- | /O(n)/ Vector of the given length with the same value in each position
replicate :: Storable a => Int -> a -> Vector a
{-# INLINE replicate #-}
replicate = G.replicate
-- | /O(n)/ Construct a vector of the given length by applying the function to
-- each index
generate :: Storable a => Int -> (Int -> a) -> Vector a
{-# INLINE generate #-}
generate = G.generate
-- | /O(n)/ Apply function n times to value. Zeroth element is original value.
iterateN :: Storable a => Int -> (a -> a) -> a -> Vector a
{-# INLINE iterateN #-}
iterateN = G.iterateN
-- Unfolding
-- ---------
-- | /O(n)/ Construct a vector by repeatedly applying the generator function
-- to a seed. The generator function yields 'Just' the next element and the
-- new seed or 'Nothing' if there are no more elements.
--
-- > unfoldr (\n -> if n == 0 then Nothing else Just (n,n-1)) 10
-- > = <10,9,8,7,6,5,4,3,2,1>
unfoldr :: Storable a => (b -> Maybe (a, b)) -> b -> Vector a
{-# INLINE unfoldr #-}
unfoldr = G.unfoldr
-- | /O(n)/ Construct a vector with at most @n@ by repeatedly applying the
-- generator function to the a seed. The generator function yields 'Just' the
-- next element and the new seed or 'Nothing' if there are no more elements.
--
-- > unfoldrN 3 (\n -> Just (n,n-1)) 10 = <10,9,8>
unfoldrN :: Storable a => Int -> (b -> Maybe (a, b)) -> b -> Vector a
{-# INLINE unfoldrN #-}
unfoldrN = G.unfoldrN
-- | /O(n)/ Construct a vector with @n@ elements by repeatedly applying the
-- generator function to the already constructed part of the vector.
--
-- > constructN 3 f = let a = f <> ; b = f <a> ; c = f <a,b> in f <a,b,c>
--
constructN :: Storable a => Int -> (Vector a -> a) -> Vector a
{-# INLINE constructN #-}
constructN = G.constructN
-- | /O(n)/ Construct a vector with @n@ elements from right to left by
-- repeatedly applying the generator function to the already constructed part
-- of the vector.
--
-- > constructrN 3 f = let a = f <> ; b = f<a> ; c = f <b,a> in f <c,b,a>
--
constructrN :: Storable a => Int -> (Vector a -> a) -> Vector a
{-# INLINE constructrN #-}
constructrN = G.constructrN
-- Enumeration
-- -----------
-- | /O(n)/ Yield a vector of the given length containing the values @x@, @x+1@
-- etc. This operation is usually more efficient than 'enumFromTo'.
--
-- > enumFromN 5 3 = <5,6,7>
enumFromN :: (Storable a, Num a) => a -> Int -> Vector a
{-# INLINE enumFromN #-}
enumFromN = G.enumFromN
-- | /O(n)/ Yield a vector of the given length containing the values @x@, @x+y@,
-- @x+y+y@ etc. This operations is usually more efficient than 'enumFromThenTo'.
--
-- > enumFromStepN 1 0.1 5 = <1,1.1,1.2,1.3,1.4>
enumFromStepN :: (Storable a, Num a) => a -> a -> Int -> Vector a
{-# INLINE enumFromStepN #-}
enumFromStepN = G.enumFromStepN
-- | /O(n)/ Enumerate values from @x@ to @y@.
--
-- /WARNING:/ This operation can be very inefficient. If at all possible, use
-- 'enumFromN' instead.
enumFromTo :: (Storable a, Enum a) => a -> a -> Vector a
{-# INLINE enumFromTo #-}
enumFromTo = G.enumFromTo
-- | /O(n)/ Enumerate values from @x@ to @y@ with a specific step @z@.
--
-- /WARNING:/ This operation can be very inefficient. If at all possible, use
-- 'enumFromStepN' instead.
enumFromThenTo :: (Storable a, Enum a) => a -> a -> a -> Vector a
{-# INLINE enumFromThenTo #-}
enumFromThenTo = G.enumFromThenTo
-- Concatenation
-- -------------
-- | /O(n)/ Prepend an element
cons :: Storable a => a -> Vector a -> Vector a
{-# INLINE cons #-}
cons = G.cons
-- | /O(n)/ Append an element
snoc :: Storable a => Vector a -> a -> Vector a
{-# INLINE snoc #-}
snoc = G.snoc
infixr 5 ++
-- | /O(m+n)/ Concatenate two vectors
(++) :: Storable a => Vector a -> Vector a -> Vector a
{-# INLINE (++) #-}
(++) = (G.++)
-- | /O(n)/ Concatenate all vectors in the list
concat :: Storable a => [Vector a] -> Vector a
{-# INLINE concat #-}
concat = G.concat
-- Monadic initialisation
-- ----------------------
-- | /O(n)/ Execute the monadic action the given number of times and store the
-- results in a vector.
replicateM :: (Monad m, Storable a) => Int -> m a -> m (Vector a)
{-# INLINE replicateM #-}
replicateM = G.replicateM
-- | /O(n)/ Construct a vector of the given length by applying the monadic
-- action to each index
generateM :: (Monad m, Storable a) => Int -> (Int -> m a) -> m (Vector a)
{-# INLINE generateM #-}
generateM = G.generateM
-- | Execute the monadic action and freeze the resulting vector.
--
-- @
-- create (do { v \<- new 2; write v 0 \'a\'; write v 1 \'b\'; return v }) = \<'a','b'\>
-- @
create :: Storable a => (forall s. ST s (MVector s a)) -> Vector a
{-# INLINE create #-}
-- NOTE: eta-expanded due to http://hackage.haskell.org/trac/ghc/ticket/4120
create p = G.create p
-- Restricting memory usage
-- ------------------------
-- | /O(n)/ Yield the argument but force it not to retain any extra memory,
-- possibly by copying it.
--
-- This is especially useful when dealing with slices. For example:
--
-- > force (slice 0 2 <huge vector>)
--
-- Here, the slice retains a reference to the huge vector. Forcing it creates
-- a copy of just the elements that belong to the slice and allows the huge
-- vector to be garbage collected.
force :: Storable a => Vector a -> Vector a
{-# INLINE force #-}
force = G.force
-- Bulk updates
-- ------------
-- | /O(m+n)/ For each pair @(i,a)@ from the list, replace the vector
-- element at position @i@ by @a@.
--
-- > <5,9,2,7> // [(2,1),(0,3),(2,8)] = <3,9,8,7>
--
(//) :: Storable a => Vector a -- ^ initial vector (of length @m@)
-> [(Int, a)] -- ^ list of index/value pairs (of length @n@)
-> Vector a
{-# INLINE (//) #-}
(//) = (G.//)
-- | /O(m+min(n1,n2))/ For each index @i@ from the index vector and the
-- corresponding value @a@ from the value vector, replace the element of the
-- initial vector at position @i@ by @a@.
--
-- > update_ <5,9,2,7> <2,0,2> <1,3,8> = <3,9,8,7>
--
update_ :: Storable a
=> Vector a -- ^ initial vector (of length @m@)
-> Vector Int -- ^ index vector (of length @n1@)
-> Vector a -- ^ value vector (of length @n2@)
-> Vector a
{-# INLINE update_ #-}
update_ = G.update_
-- | Same as ('//') but without bounds checking.
unsafeUpd :: Storable a => Vector a -> [(Int, a)] -> Vector a
{-# INLINE unsafeUpd #-}
unsafeUpd = G.unsafeUpd
-- | Same as 'update_' but without bounds checking.
unsafeUpdate_ :: Storable a => Vector a -> Vector Int -> Vector a -> Vector a
{-# INLINE unsafeUpdate_ #-}
unsafeUpdate_ = G.unsafeUpdate_
-- Accumulations
-- -------------
-- | /O(m+n)/ For each pair @(i,b)@ from the list, replace the vector element
-- @a@ at position @i@ by @f a b@.
--
-- > accum (+) <5,9,2> [(2,4),(1,6),(0,3),(1,7)] = <5+3, 9+6+7, 2+4>
accum :: Storable a
=> (a -> b -> a) -- ^ accumulating function @f@
-> Vector a -- ^ initial vector (of length @m@)
-> [(Int,b)] -- ^ list of index/value pairs (of length @n@)
-> Vector a
{-# INLINE accum #-}
accum = G.accum
-- | /O(m+min(n1,n2))/ For each index @i@ from the index vector and the
-- corresponding value @b@ from the the value vector,
-- replace the element of the initial vector at
-- position @i@ by @f a b@.
--
-- > accumulate_ (+) <5,9,2> <2,1,0,1> <4,6,3,7> = <5+3, 9+6+7, 2+4>
--
accumulate_ :: (Storable a, Storable b)
=> (a -> b -> a) -- ^ accumulating function @f@
-> Vector a -- ^ initial vector (of length @m@)
-> Vector Int -- ^ index vector (of length @n1@)
-> Vector b -- ^ value vector (of length @n2@)
-> Vector a
{-# INLINE accumulate_ #-}
accumulate_ = G.accumulate_
-- | Same as 'accum' but without bounds checking.
unsafeAccum :: Storable a => (a -> b -> a) -> Vector a -> [(Int,b)] -> Vector a
{-# INLINE unsafeAccum #-}
unsafeAccum = G.unsafeAccum
-- | Same as 'accumulate_' but without bounds checking.
unsafeAccumulate_ :: (Storable a, Storable b) =>
(a -> b -> a) -> Vector a -> Vector Int -> Vector b -> Vector a
{-# INLINE unsafeAccumulate_ #-}
unsafeAccumulate_ = G.unsafeAccumulate_
-- Permutations
-- ------------
-- | /O(n)/ Reverse a vector
reverse :: Storable a => Vector a -> Vector a
{-# INLINE reverse #-}
reverse = G.reverse
-- | /O(n)/ Yield the vector obtained by replacing each element @i@ of the
-- index vector by @xs'!'i@. This is equivalent to @'map' (xs'!') is@ but is
-- often much more efficient.
--
-- > backpermute <a,b,c,d> <0,3,2,3,1,0> = <a,d,c,d,b,a>
backpermute :: Storable a => Vector a -> Vector Int -> Vector a
{-# INLINE backpermute #-}
backpermute = G.backpermute
-- | Same as 'backpermute' but without bounds checking.
unsafeBackpermute :: Storable a => Vector a -> Vector Int -> Vector a
{-# INLINE unsafeBackpermute #-}
unsafeBackpermute = G.unsafeBackpermute
-- Safe destructive updates
-- ------------------------
-- | Apply a destructive operation to a vector. The operation will be
-- performed in place if it is safe to do so and will modify a copy of the
-- vector otherwise.
--
-- @
-- modify (\\v -> write v 0 \'x\') ('replicate' 3 \'a\') = \<\'x\',\'a\',\'a\'\>
-- @
modify :: Storable a => (forall s. MVector s a -> ST s ()) -> Vector a -> Vector a
{-# INLINE modify #-}
modify p = G.modify p
-- Mapping
-- -------
-- | /O(n)/ Map a function over a vector
map :: (Storable a, Storable b) => (a -> b) -> Vector a -> Vector b
{-# INLINE map #-}
map = G.map
-- | /O(n)/ Apply a function to every element of a vector and its index
imap :: (Storable a, Storable b) => (Int -> a -> b) -> Vector a -> Vector b
{-# INLINE imap #-}
imap = G.imap
-- | Map a function over a vector and concatenate the results.
concatMap :: (Storable a, Storable b) => (a -> Vector b) -> Vector a -> Vector b
{-# INLINE concatMap #-}
concatMap = G.concatMap
-- Monadic mapping
-- ---------------
-- | /O(n)/ Apply the monadic action to all elements of the vector, yielding a
-- vector of results
mapM :: (Monad m, Storable a, Storable b) => (a -> m b) -> Vector a -> m (Vector b)
{-# INLINE mapM #-}
mapM = G.mapM
-- | /O(n)/ Apply the monadic action to all elements of a vector and ignore the
-- results
mapM_ :: (Monad m, Storable a) => (a -> m b) -> Vector a -> m ()
{-# INLINE mapM_ #-}
mapM_ = G.mapM_
-- | /O(n)/ Apply the monadic action to all elements of the vector, yielding a
-- vector of results. Equvalent to @flip 'mapM'@.
forM :: (Monad m, Storable a, Storable b) => Vector a -> (a -> m b) -> m (Vector b)
{-# INLINE forM #-}
forM = G.forM
-- | /O(n)/ Apply the monadic action to all elements of a vector and ignore the
-- results. Equivalent to @flip 'mapM_'@.
forM_ :: (Monad m, Storable a) => Vector a -> (a -> m b) -> m ()
{-# INLINE forM_ #-}
forM_ = G.forM_
-- Zipping
-- -------
-- | /O(min(m,n))/ Zip two vectors with the given function.
zipWith :: (Storable a, Storable b, Storable c)
=> (a -> b -> c) -> Vector a -> Vector b -> Vector c
{-# INLINE zipWith #-}
zipWith = G.zipWith
-- | Zip three vectors with the given function.
zipWith3 :: (Storable a, Storable b, Storable c, Storable d)
=> (a -> b -> c -> d) -> Vector a -> Vector b -> Vector c -> Vector d
{-# INLINE zipWith3 #-}
zipWith3 = G.zipWith3
zipWith4 :: (Storable a, Storable b, Storable c, Storable d, Storable e)
=> (a -> b -> c -> d -> e)
-> Vector a -> Vector b -> Vector c -> Vector d -> Vector e
{-# INLINE zipWith4 #-}
zipWith4 = G.zipWith4
zipWith5 :: (Storable a, Storable b, Storable c, Storable d, Storable e,
Storable f)
=> (a -> b -> c -> d -> e -> f)
-> Vector a -> Vector b -> Vector c -> Vector d -> Vector e
-> Vector f
{-# INLINE zipWith5 #-}
zipWith5 = G.zipWith5
zipWith6 :: (Storable a, Storable b, Storable c, Storable d, Storable e,
Storable f, Storable g)
=> (a -> b -> c -> d -> e -> f -> g)
-> Vector a -> Vector b -> Vector c -> Vector d -> Vector e
-> Vector f -> Vector g
{-# INLINE zipWith6 #-}
zipWith6 = G.zipWith6
-- | /O(min(m,n))/ Zip two vectors with a function that also takes the
-- elements' indices.
izipWith :: (Storable a, Storable b, Storable c)
=> (Int -> a -> b -> c) -> Vector a -> Vector b -> Vector c
{-# INLINE izipWith #-}
izipWith = G.izipWith
-- | Zip three vectors and their indices with the given function.
izipWith3 :: (Storable a, Storable b, Storable c, Storable d)
=> (Int -> a -> b -> c -> d)
-> Vector a -> Vector b -> Vector c -> Vector d
{-# INLINE izipWith3 #-}
izipWith3 = G.izipWith3
izipWith4 :: (Storable a, Storable b, Storable c, Storable d, Storable e)
=> (Int -> a -> b -> c -> d -> e)
-> Vector a -> Vector b -> Vector c -> Vector d -> Vector e
{-# INLINE izipWith4 #-}
izipWith4 = G.izipWith4
izipWith5 :: (Storable a, Storable b, Storable c, Storable d, Storable e,
Storable f)
=> (Int -> a -> b -> c -> d -> e -> f)
-> Vector a -> Vector b -> Vector c -> Vector d -> Vector e
-> Vector f
{-# INLINE izipWith5 #-}
izipWith5 = G.izipWith5
izipWith6 :: (Storable a, Storable b, Storable c, Storable d, Storable e,
Storable f, Storable g)
=> (Int -> a -> b -> c -> d -> e -> f -> g)
-> Vector a -> Vector b -> Vector c -> Vector d -> Vector e
-> Vector f -> Vector g
{-# INLINE izipWith6 #-}
izipWith6 = G.izipWith6
-- Monadic zipping
-- ---------------
-- | /O(min(m,n))/ Zip the two vectors with the monadic action and yield a
-- vector of results
zipWithM :: (Monad m, Storable a, Storable b, Storable c)
=> (a -> b -> m c) -> Vector a -> Vector b -> m (Vector c)
{-# INLINE zipWithM #-}
zipWithM = G.zipWithM
-- | /O(min(m,n))/ Zip the two vectors with the monadic action and ignore the
-- results
zipWithM_ :: (Monad m, Storable a, Storable b)
=> (a -> b -> m c) -> Vector a -> Vector b -> m ()
{-# INLINE zipWithM_ #-}
zipWithM_ = G.zipWithM_
-- Filtering
-- ---------
-- | /O(n)/ Drop elements that do not satisfy the predicate
filter :: Storable a => (a -> Bool) -> Vector a -> Vector a
{-# INLINE filter #-}
filter = G.filter
-- | /O(n)/ Drop elements that do not satisfy the predicate which is applied to
-- values and their indices
ifilter :: Storable a => (Int -> a -> Bool) -> Vector a -> Vector a
{-# INLINE ifilter #-}
ifilter = G.ifilter
-- | /O(n)/ Drop elements that do not satisfy the monadic predicate
filterM :: (Monad m, Storable a) => (a -> m Bool) -> Vector a -> m (Vector a)
{-# INLINE filterM #-}
filterM = G.filterM
-- | /O(n)/ Yield the longest prefix of elements satisfying the predicate
-- without copying.
takeWhile :: Storable a => (a -> Bool) -> Vector a -> Vector a
{-# INLINE takeWhile #-}
takeWhile = G.takeWhile
-- | /O(n)/ Drop the longest prefix of elements that satisfy the predicate
-- without copying.
dropWhile :: Storable a => (a -> Bool) -> Vector a -> Vector a
{-# INLINE dropWhile #-}
dropWhile = G.dropWhile
-- Parititioning
-- -------------
-- | /O(n)/ Split the vector in two parts, the first one containing those
-- elements that satisfy the predicate and the second one those that don't. The
-- relative order of the elements is preserved at the cost of a sometimes
-- reduced performance compared to 'unstablePartition'.
partition :: Storable a => (a -> Bool) -> Vector a -> (Vector a, Vector a)
{-# INLINE partition #-}
partition = G.partition
-- | /O(n)/ Split the vector in two parts, the first one containing those
-- elements that satisfy the predicate and the second one those that don't.
-- The order of the elements is not preserved but the operation is often
-- faster than 'partition'.
unstablePartition :: Storable a => (a -> Bool) -> Vector a -> (Vector a, Vector a)
{-# INLINE unstablePartition #-}
unstablePartition = G.unstablePartition
-- | /O(n)/ Split the vector into the longest prefix of elements that satisfy
-- the predicate and the rest without copying.
span :: Storable a => (a -> Bool) -> Vector a -> (Vector a, Vector a)
{-# INLINE span #-}
span = G.span
-- | /O(n)/ Split the vector into the longest prefix of elements that do not
-- satisfy the predicate and the rest without copying.
break :: Storable a => (a -> Bool) -> Vector a -> (Vector a, Vector a)
{-# INLINE break #-}
break = G.break
-- Searching
-- ---------
infix 4 `elem`
-- | /O(n)/ Check if the vector contains an element
elem :: (Storable a, Eq a) => a -> Vector a -> Bool
{-# INLINE elem #-}
elem = G.elem
infix 4 `notElem`
-- | /O(n)/ Check if the vector does not contain an element (inverse of 'elem')
notElem :: (Storable a, Eq a) => a -> Vector a -> Bool
{-# INLINE notElem #-}
notElem = G.notElem
-- | /O(n)/ Yield 'Just' the first element matching the predicate or 'Nothing'
-- if no such element exists.
find :: Storable a => (a -> Bool) -> Vector a -> Maybe a
{-# INLINE find #-}
find = G.find
-- | /O(n)/ Yield 'Just' the index of the first element matching the predicate
-- or 'Nothing' if no such element exists.
findIndex :: Storable a => (a -> Bool) -> Vector a -> Maybe Int
{-# INLINE findIndex #-}
findIndex = G.findIndex
-- | /O(n)/ Yield the indices of elements satisfying the predicate in ascending
-- order.
findIndices :: Storable a => (a -> Bool) -> Vector a -> Vector Int
{-# INLINE findIndices #-}
findIndices = G.findIndices
-- | /O(n)/ Yield 'Just' the index of the first occurence of the given element or
-- 'Nothing' if the vector does not contain the element. This is a specialised
-- version of 'findIndex'.
elemIndex :: (Storable a, Eq a) => a -> Vector a -> Maybe Int
{-# INLINE elemIndex #-}
elemIndex = G.elemIndex
-- | /O(n)/ Yield the indices of all occurences of the given element in
-- ascending order. This is a specialised version of 'findIndices'.
elemIndices :: (Storable a, Eq a) => a -> Vector a -> Vector Int
{-# INLINE elemIndices #-}
elemIndices = G.elemIndices
-- Folding
-- -------
-- | /O(n)/ Left fold
foldl :: Storable b => (a -> b -> a) -> a -> Vector b -> a
{-# INLINE foldl #-}
foldl = G.foldl
-- | /O(n)/ Left fold on non-empty vectors
foldl1 :: Storable a => (a -> a -> a) -> Vector a -> a
{-# INLINE foldl1 #-}
foldl1 = G.foldl1
-- | /O(n)/ Left fold with strict accumulator
foldl' :: Storable b => (a -> b -> a) -> a -> Vector b -> a
{-# INLINE foldl' #-}
foldl' = G.foldl'
-- | /O(n)/ Left fold on non-empty vectors with strict accumulator
foldl1' :: Storable a => (a -> a -> a) -> Vector a -> a
{-# INLINE foldl1' #-}
foldl1' = G.foldl1'
-- | /O(n)/ Right fold
foldr :: Storable a => (a -> b -> b) -> b -> Vector a -> b
{-# INLINE foldr #-}
foldr = G.foldr
-- | /O(n)/ Right fold on non-empty vectors
foldr1 :: Storable a => (a -> a -> a) -> Vector a -> a
{-# INLINE foldr1 #-}
foldr1 = G.foldr1
-- | /O(n)/ Right fold with a strict accumulator
foldr' :: Storable a => (a -> b -> b) -> b -> Vector a -> b
{-# INLINE foldr' #-}
foldr' = G.foldr'
-- | /O(n)/ Right fold on non-empty vectors with strict accumulator
foldr1' :: Storable a => (a -> a -> a) -> Vector a -> a
{-# INLINE foldr1' #-}
foldr1' = G.foldr1'
-- | /O(n)/ Left fold (function applied to each element and its index)
ifoldl :: Storable b => (a -> Int -> b -> a) -> a -> Vector b -> a
{-# INLINE ifoldl #-}
ifoldl = G.ifoldl
-- | /O(n)/ Left fold with strict accumulator (function applied to each element
-- and its index)
ifoldl' :: Storable b => (a -> Int -> b -> a) -> a -> Vector b -> a
{-# INLINE ifoldl' #-}
ifoldl' = G.ifoldl'
-- | /O(n)/ Right fold (function applied to each element and its index)
ifoldr :: Storable a => (Int -> a -> b -> b) -> b -> Vector a -> b
{-# INLINE ifoldr #-}
ifoldr = G.ifoldr
-- | /O(n)/ Right fold with strict accumulator (function applied to each
-- element and its index)
ifoldr' :: Storable a => (Int -> a -> b -> b) -> b -> Vector a -> b
{-# INLINE ifoldr' #-}
ifoldr' = G.ifoldr'
-- Specialised folds
-- -----------------
-- | /O(n)/ Check if all elements satisfy the predicate.
all :: Storable a => (a -> Bool) -> Vector a -> Bool
{-# INLINE all #-}
all = G.all
-- | /O(n)/ Check if any element satisfies the predicate.
any :: Storable a => (a -> Bool) -> Vector a -> Bool
{-# INLINE any #-}
any = G.any
-- | /O(n)/ Check if all elements are 'True'
and :: Vector Bool -> Bool
{-# INLINE and #-}
and = G.and
-- | /O(n)/ Check if any element is 'True'
or :: Vector Bool -> Bool
{-# INLINE or #-}
or = G.or
-- | /O(n)/ Compute the sum of the elements
sum :: (Storable a, Num a) => Vector a -> a
{-# INLINE sum #-}
sum = G.sum
-- | /O(n)/ Compute the produce of the elements
product :: (Storable a, Num a) => Vector a -> a
{-# INLINE product #-}
product = G.product
-- | /O(n)/ Yield the maximum element of the vector. The vector may not be
-- empty.
maximum :: (Storable a, Ord a) => Vector a -> a
{-# INLINE maximum #-}
maximum = G.maximum
-- | /O(n)/ Yield the maximum element of the vector according to the given
-- comparison function. The vector may not be empty.
maximumBy :: Storable a => (a -> a -> Ordering) -> Vector a -> a
{-# INLINE maximumBy #-}
maximumBy = G.maximumBy
-- | /O(n)/ Yield the minimum element of the vector. The vector may not be
-- empty.
minimum :: (Storable a, Ord a) => Vector a -> a
{-# INLINE minimum #-}
minimum = G.minimum
-- | /O(n)/ Yield the minimum element of the vector according to the given
-- comparison function. The vector may not be empty.
minimumBy :: Storable a => (a -> a -> Ordering) -> Vector a -> a
{-# INLINE minimumBy #-}
minimumBy = G.minimumBy
-- | /O(n)/ Yield the index of the maximum element of the vector. The vector
-- may not be empty.
maxIndex :: (Storable a, Ord a) => Vector a -> Int
{-# INLINE maxIndex #-}
maxIndex = G.maxIndex
-- | /O(n)/ Yield the index of the maximum element of the vector according to
-- the given comparison function. The vector may not be empty.
maxIndexBy :: Storable a => (a -> a -> Ordering) -> Vector a -> Int
{-# INLINE maxIndexBy #-}
maxIndexBy = G.maxIndexBy
-- | /O(n)/ Yield the index of the minimum element of the vector. The vector
-- may not be empty.
minIndex :: (Storable a, Ord a) => Vector a -> Int
{-# INLINE minIndex #-}
minIndex = G.minIndex
-- | /O(n)/ Yield the index of the minimum element of the vector according to
-- the given comparison function. The vector may not be empty.
minIndexBy :: Storable a => (a -> a -> Ordering) -> Vector a -> Int
{-# INLINE minIndexBy #-}
minIndexBy = G.minIndexBy
-- Monadic folds
-- -------------
-- | /O(n)/ Monadic fold
foldM :: (Monad m, Storable b) => (a -> b -> m a) -> a -> Vector b -> m a
{-# INLINE foldM #-}
foldM = G.foldM
-- | /O(n)/ Monadic fold over non-empty vectors
fold1M :: (Monad m, Storable a) => (a -> a -> m a) -> Vector a -> m a
{-# INLINE fold1M #-}
fold1M = G.fold1M
-- | /O(n)/ Monadic fold with strict accumulator
foldM' :: (Monad m, Storable b) => (a -> b -> m a) -> a -> Vector b -> m a
{-# INLINE foldM' #-}
foldM' = G.foldM'
-- | /O(n)/ Monadic fold over non-empty vectors with strict accumulator
fold1M' :: (Monad m, Storable a) => (a -> a -> m a) -> Vector a -> m a
{-# INLINE fold1M' #-}
fold1M' = G.fold1M'
-- | /O(n)/ Monadic fold that discards the result
foldM_ :: (Monad m, Storable b) => (a -> b -> m a) -> a -> Vector b -> m ()
{-# INLINE foldM_ #-}
foldM_ = G.foldM_
-- | /O(n)/ Monadic fold over non-empty vectors that discards the result
fold1M_ :: (Monad m, Storable a) => (a -> a -> m a) -> Vector a -> m ()
{-# INLINE fold1M_ #-}
fold1M_ = G.fold1M_
-- | /O(n)/ Monadic fold with strict accumulator that discards the result
foldM'_ :: (Monad m, Storable b) => (a -> b -> m a) -> a -> Vector b -> m ()
{-# INLINE foldM'_ #-}
foldM'_ = G.foldM'_
-- | /O(n)/ Monadic fold over non-empty vectors with strict accumulator
-- that discards the result
fold1M'_ :: (Monad m, Storable a) => (a -> a -> m a) -> Vector a -> m ()
{-# INLINE fold1M'_ #-}
fold1M'_ = G.fold1M'_
-- Prefix sums (scans)
-- -------------------
-- | /O(n)/ Prescan
--
-- @
-- prescanl f z = 'init' . 'scanl' f z
-- @
--
-- Example: @prescanl (+) 0 \<1,2,3,4\> = \<0,1,3,6\>@
--
prescanl :: (Storable a, Storable b) => (a -> b -> a) -> a -> Vector b -> Vector a
{-# INLINE prescanl #-}
prescanl = G.prescanl
-- | /O(n)/ Prescan with strict accumulator
prescanl' :: (Storable a, Storable b) => (a -> b -> a) -> a -> Vector b -> Vector a
{-# INLINE prescanl' #-}
prescanl' = G.prescanl'
-- | /O(n)/ Scan
--
-- @
-- postscanl f z = 'tail' . 'scanl' f z
-- @
--
-- Example: @postscanl (+) 0 \<1,2,3,4\> = \<1,3,6,10\>@
--
postscanl :: (Storable a, Storable b) => (a -> b -> a) -> a -> Vector b -> Vector a
{-# INLINE postscanl #-}
postscanl = G.postscanl
-- | /O(n)/ Scan with strict accumulator
postscanl' :: (Storable a, Storable b) => (a -> b -> a) -> a -> Vector b -> Vector a
{-# INLINE postscanl' #-}
postscanl' = G.postscanl'
-- | /O(n)/ Haskell-style scan
--
-- > scanl f z <x1,...,xn> = <y1,...,y(n+1)>
-- > where y1 = z
-- > yi = f y(i-1) x(i-1)
--
-- Example: @scanl (+) 0 \<1,2,3,4\> = \<0,1,3,6,10\>@
--
scanl :: (Storable a, Storable b) => (a -> b -> a) -> a -> Vector b -> Vector a
{-# INLINE scanl #-}
scanl = G.scanl
-- | /O(n)/ Haskell-style scan with strict accumulator
scanl' :: (Storable a, Storable b) => (a -> b -> a) -> a -> Vector b -> Vector a
{-# INLINE scanl' #-}
scanl' = G.scanl'
-- | /O(n)/ Scan over a non-empty vector
--
-- > scanl f <x1,...,xn> = <y1,...,yn>
-- > where y1 = x1
-- > yi = f y(i-1) xi
--
scanl1 :: Storable a => (a -> a -> a) -> Vector a -> Vector a
{-# INLINE scanl1 #-}
scanl1 = G.scanl1
-- | /O(n)/ Scan over a non-empty vector with a strict accumulator
scanl1' :: Storable a => (a -> a -> a) -> Vector a -> Vector a
{-# INLINE scanl1' #-}
scanl1' = G.scanl1'
-- | /O(n)/ Right-to-left prescan
--
-- @
-- prescanr f z = 'reverse' . 'prescanl' (flip f) z . 'reverse'
-- @
--
prescanr :: (Storable a, Storable b) => (a -> b -> b) -> b -> Vector a -> Vector b
{-# INLINE prescanr #-}
prescanr = G.prescanr
-- | /O(n)/ Right-to-left prescan with strict accumulator
prescanr' :: (Storable a, Storable b) => (a -> b -> b) -> b -> Vector a -> Vector b
{-# INLINE prescanr' #-}
prescanr' = G.prescanr'
-- | /O(n)/ Right-to-left scan
postscanr :: (Storable a, Storable b) => (a -> b -> b) -> b -> Vector a -> Vector b
{-# INLINE postscanr #-}
postscanr = G.postscanr
-- | /O(n)/ Right-to-left scan with strict accumulator
postscanr' :: (Storable a, Storable b) => (a -> b -> b) -> b -> Vector a -> Vector b
{-# INLINE postscanr' #-}
postscanr' = G.postscanr'
-- | /O(n)/ Right-to-left Haskell-style scan
scanr :: (Storable a, Storable b) => (a -> b -> b) -> b -> Vector a -> Vector b
{-# INLINE scanr #-}
scanr = G.scanr
-- | /O(n)/ Right-to-left Haskell-style scan with strict accumulator
scanr' :: (Storable a, Storable b) => (a -> b -> b) -> b -> Vector a -> Vector b
{-# INLINE scanr' #-}
scanr' = G.scanr'
-- | /O(n)/ Right-to-left scan over a non-empty vector
scanr1 :: Storable a => (a -> a -> a) -> Vector a -> Vector a
{-# INLINE scanr1 #-}
scanr1 = G.scanr1
-- | /O(n)/ Right-to-left scan over a non-empty vector with a strict
-- accumulator
scanr1' :: Storable a => (a -> a -> a) -> Vector a -> Vector a
{-# INLINE scanr1' #-}
scanr1' = G.scanr1'
-- Conversions - Lists
-- ------------------------
-- | /O(n)/ Convert a vector to a list
toList :: Storable a => Vector a -> [a]
{-# INLINE toList #-}
toList = G.toList
-- | /O(n)/ Convert a list to a vector
fromList :: Storable a => [a] -> Vector a
{-# INLINE fromList #-}
fromList = G.fromList
-- | /O(n)/ Convert the first @n@ elements of a list to a vector
--
-- @
-- fromListN n xs = 'fromList' ('take' n xs)
-- @
fromListN :: Storable a => Int -> [a] -> Vector a
{-# INLINE fromListN #-}
fromListN = G.fromListN
-- Conversions - Unsafe casts
-- --------------------------
-- | /O(1)/ Unsafely cast a vector from one element type to another.
-- The operation just changes the type of the underlying pointer and does not
-- modify the elements.
--
-- The resulting vector contains as many elements as can fit into the
-- underlying memory block.
--
unsafeCast :: forall a b. (Storable a, Storable b) => Vector a -> Vector b
{-# INLINE unsafeCast #-}
unsafeCast (Vector n fp)
= Vector ((n * sizeOf (undefined :: a)) `div` sizeOf (undefined :: b))
(castForeignPtr fp)
-- Conversions - Mutable vectors
-- -----------------------------
-- | /O(1)/ Unsafe convert a mutable vector to an immutable one without
-- copying. The mutable vector may not be used after this operation.
unsafeFreeze
:: (Storable a, PrimMonad m) => MVector (PrimState m) a -> m (Vector a)
{-# INLINE unsafeFreeze #-}
unsafeFreeze = G.unsafeFreeze
-- | /O(1)/ Unsafely convert an immutable vector to a mutable one without
-- copying. The immutable vector may not be used after this operation.
unsafeThaw
:: (Storable a, PrimMonad m) => Vector a -> m (MVector (PrimState m) a)
{-# INLINE unsafeThaw #-}
unsafeThaw = G.unsafeThaw
-- | /O(n)/ Yield a mutable copy of the immutable vector.
thaw :: (Storable a, PrimMonad m) => Vector a -> m (MVector (PrimState m) a)
{-# INLINE thaw #-}
thaw = G.thaw
-- | /O(n)/ Yield an immutable copy of the mutable vector.
freeze :: (Storable a, PrimMonad m) => MVector (PrimState m) a -> m (Vector a)
{-# INLINE freeze #-}
freeze = G.freeze
-- | /O(n)/ Copy an immutable vector into a mutable one. The two vectors must
-- have the same length. This is not checked.
unsafeCopy
:: (Storable a, PrimMonad m) => MVector (PrimState m) a -> Vector a -> m ()
{-# INLINE unsafeCopy #-}
unsafeCopy = G.unsafeCopy
-- | /O(n)/ Copy an immutable vector into a mutable one. The two vectors must
-- have the same length.
copy :: (Storable a, PrimMonad m) => MVector (PrimState m) a -> Vector a -> m ()
{-# INLINE copy #-}
copy = G.copy
-- Conversions - Raw pointers
-- --------------------------
-- | /O(1)/ Create a vector from a 'ForeignPtr' with an offset and a length.
--
-- The data may not be modified through the 'ForeignPtr' afterwards.
--
-- If your offset is 0 it is more efficient to use 'unsafeFromForeignPtr0'.
unsafeFromForeignPtr :: Storable a
=> ForeignPtr a -- ^ pointer
-> Int -- ^ offset
-> Int -- ^ length
-> Vector a
{-# INLINE unsafeFromForeignPtr #-}
unsafeFromForeignPtr fp i n = unsafeFromForeignPtr0 fp' n
where
fp' = updPtr (`advancePtr` i) fp
{-# RULES
"unsafeFromForeignPtr fp 0 n -> unsafeFromForeignPtr0 fp n " forall fp n.
unsafeFromForeignPtr fp 0 n = unsafeFromForeignPtr0 fp n
#-}
-- | /O(1)/ Create a vector from a 'ForeignPtr' and a length.
--
-- It is assumed the pointer points directly to the data (no offset).
-- Use `unsafeFromForeignPtr` if you need to specify an offset.
--
-- The data may not be modified through the 'ForeignPtr' afterwards.
unsafeFromForeignPtr0 :: Storable a
=> ForeignPtr a -- ^ pointer
-> Int -- ^ length
-> Vector a
{-# INLINE unsafeFromForeignPtr0 #-}
unsafeFromForeignPtr0 fp n = Vector n fp
-- | /O(1)/ Yield the underlying 'ForeignPtr' together with the offset to the
-- data and its length. The data may not be modified through the 'ForeignPtr'.
unsafeToForeignPtr :: Storable a => Vector a -> (ForeignPtr a, Int, Int)
{-# INLINE unsafeToForeignPtr #-}
unsafeToForeignPtr (Vector n fp) = (fp, 0, n)
-- | /O(1)/ Yield the underlying 'ForeignPtr' together with its length.
--
-- You can assume the pointer points directly to the data (no offset).
--
-- The data may not be modified through the 'ForeignPtr'.
unsafeToForeignPtr0 :: Storable a => Vector a -> (ForeignPtr a, Int)
{-# INLINE unsafeToForeignPtr0 #-}
unsafeToForeignPtr0 (Vector n fp) = (fp, n)
-- | Pass a pointer to the vector's data to the IO action. The data may not be
-- modified through the 'Ptr.
unsafeWith :: Storable a => Vector a -> (Ptr a -> IO b) -> IO b
{-# INLINE unsafeWith #-}
unsafeWith (Vector n fp) = withForeignPtr fp
| hvr/vector | Data/Vector/Storable.hs | bsd-3-clause | 44,874 | 0 | 14 | 9,844 | 9,906 | 5,487 | 4,419 | -1 | -1 |
module Common where
import Codec.Picture
import Codec.Picture.Metadata (Metadatas)
import Codec.Picture.Types
--
-- Image Processing
--
{-|
>>> fmap (clamp 2 5) [0, 3, 7]
[2,3,5]
-}
clamp :: Ord a => a -> a -> a -> a
clamp l h = min h . max l
getImageSize :: Image a -> (Int, Int)
getImageSize dimg = (imageWidth dimg, imageHeight dimg)
--
-- Logging
--
dumpTitle :: String -> IO ()
dumpTitle name = putStrLn $ "== " ++ name ++ " =="
dump :: Show a => String -> a -> IO ()
dump name val = putStrLn $ name ++ ": " ++ show val
dumpImageInfo :: String -> DynamicImage -> Metadatas -> IO ()
dumpImageInfo title dimg md = do
dumpTitle title
let (w, h) = dynamicMap getImageSize dimg
dump "width" w
dump "height" h
dump "image type" (showImageType dimg)
dump "metadata" md
showImageType :: DynamicImage -> String
showImageType = f where
f (ImageY8 _) = "Y8"
f (ImageY16 _) = "Y16"
f (ImageYF _) = "YF"
f (ImageYA8 _) = "YA8"
f (ImageYA16 _) = "YA16"
f (ImageRGB8 _) = "RGB8"
f (ImageRGB16 _) = "RGB16"
f (ImageRGBF _) = "RGBF"
f (ImageRGBA8 _) = "RGBA8"
f (ImageRGBA16 _) = "RGBA16"
f (ImageYCbCr8 _) = "YCbCr8"
f (ImageCMYK8 _) = "CMYK8"
f (ImageCMYK16 _) = "CMYK16"
| notae/haskell-exercise | graphics/Common.hs | bsd-3-clause | 1,210 | 0 | 10 | 268 | 496 | 250 | 246 | 35 | 13 |
module Parser
( readExpr,
readExprList,
symbol,
parseString,
parseAtom,
parseHash,
parseNumber,
parseExpr,
parseParens,
parseQuoted,
) where
import Control.Monad.Except
import Data.Char
import LispVal
import Numeric (readDec, readHex, readInt,
readOct)
import Text.ParserCombinators.Parsec hiding (spaces)
symbol :: Parser Char
symbol = oneOf "!#$%&|*+-/:<=>?@^_~"
parseString :: Parser LispVal
parseString = do
_ <- char '"'
x <- many character
_ <- char '"'
return $ String $ concat x
escape :: Parser String
escape = do
x <- char '\\'
y <- oneOf "\\\"0nrvtbf"
return [x, y]
nonEscape :: Parser Char
nonEscape = noneOf "\\\""
character :: Parser String
character = fmap return nonEscape <|> escape
parseAtom :: Parser LispVal
parseAtom = do
x <- letter <|> symbol
xs <- many (letter <|> digit <|> symbol)
return $ Atom $ x:xs
parseHash :: Parser LispVal
parseHash = do
_ <- char '#'
parseBool <|> parseChar <|> parseBase
parseBool :: Parser LispVal
parseBool = do
v <- oneOf "tf"
return $ Bool $ case v of
't' -> True
'f' -> False
parseChar :: Parser LispVal
parseChar = do
a <- char '\\'
b <- try (string "newline" <|> string "space") <|> parseSingleChar
return $ Character $ case b of
"space" -> ' '
"newline" -> '\n'
_ -> head b
parseBase :: Parser LispVal
parseBase = parseBaseD <|> parseBaseH <|> parseBaseO <|> parseBaseB
parseBaseD :: Parser LispVal
parseBaseD = char 'd' >> many1 digit >>= toLispNumber . readDec
parseBaseH :: Parser LispVal
parseBaseH = char 'h' >> many1 (digit <|> oneOf "abcdef") >>= toLispNumber . readHex
parseBaseO :: Parser LispVal
parseBaseO = char 'o' >> many1 (oneOf "01234567") >>= toLispNumber . readOct
parseBaseB :: Parser LispVal
parseBaseB = char 'b' >> many1 (oneOf "01") >>= toLispNumber . readBin
readBin :: ReadS Integer
readBin = readInt 2 (`elem` "01") digitToInt
toLispNumber :: [(Integer, String)] -> Parser LispVal
toLispNumber a = return $ Number . toInteger . fst . head $ a
parseSingleChar :: Parser String
parseSingleChar = do
x <- anyChar
_ <- try $ lookAhead $ oneOf " ()"
return [x];
parseNumber :: Parser LispVal
parseNumber = Number . read <$> many1 digit
parseExpr :: Parser LispVal
parseExpr = parseNumber
<|> parseString
<|> parseHash
<|> parseAtom
<|> parseQuoted
<|> parseParens
parseParens :: Parser LispVal
parseParens = do
_ <- char '('
x <- parseExpr `sepEndBy` spaces
mayb <- optionMaybe (char '.' >> spaces >> parseExpr)
_ <- char ')'
return $ case mayb of
Nothing -> List x
Just y -> DottedList x y
parseQuoted :: Parser LispVal
parseQuoted = do
_ <- char '\''
x <- parseExpr
return $ List [Atom "quote", x]
spaces :: Parser ()
spaces = skipMany1 space
readOrThrow :: Parser a -> String -> ThrowsError a
readOrThrow parser input = case parse parser "lisp" input of
Left err -> throwError $ Parser err
Right val -> return val
readExpr :: String -> ThrowsError LispVal
readExpr = readOrThrow parseExpr
readExprList :: String -> ThrowsError [LispVal]
readExprList = readOrThrow (parseExpr `endBy` spaces)
| mhcurylo/scheme-haskell-tutorial | src/Parser.hs | bsd-3-clause | 3,455 | 0 | 12 | 970 | 1,108 | 551 | 557 | 109 | 3 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
module Data.Json.Final.Tokenize.Internal
( IsChar(..)
, JsonToken(..)
, AFP.Parser(..)
, parseJsonToken
) where
import Control.Applicative
import Control.Monad
import qualified Data.Attoparsec.Combinator as AC
import qualified Data.Attoparsec.ByteString as ABS
import qualified Data.Attoparsec.ByteString.Char8 as BC
import Data.Attoparsec.Final.IsChar
import Data.Attoparsec.Final.Parser as AFP
import qualified Data.Attoparsec.Internal as I
import qualified Data.Attoparsec.Types as T
import Data.Bits
import Data.ByteString (ByteString)
import qualified Data.ByteString.Internal as BI
import Data.Char
import Data.Json.Token
import Data.MonoTraversable
import Data.String
import Data.Word8
isHexDigitChar :: Char -> Bool
isHexDigitChar c =
'0' <= c && c <= '9' ||
'a' <= c && c <= 'z' ||
'A' <= c && c <= 'Z'
hexDigitNumeric :: AFP.Parser t => T.Parser t Int
hexDigitNumeric = do
c <- satisfyChar (\c -> '0' <= c && c <= '9')
return $ ord c - ord '0'
hexDigitAlphaLower :: AFP.Parser t => T.Parser t Int
hexDigitAlphaLower = do
c <- satisfyChar (\c -> 'a' <= c && c <= 'z')
return $ ord c - ord 'a' + 10
hexDigitAlphaUpper :: AFP.Parser t => T.Parser t Int
hexDigitAlphaUpper = do
c <- satisfyChar (\c -> 'A' <= c && c <= 'Z')
return $ ord c - ord 'A' + 10
hexDigit :: AFP.Parser t => T.Parser t Int
hexDigit = hexDigitNumeric <|> hexDigitAlphaLower <|> hexDigitAlphaUpper
parseJsonTokenString :: (JsonTokenLike j, AFP.Parser t, Alternative (T.Parser t), IsString t) => T.Parser t j
parseJsonTokenString = do
string "\""
value <- many (verbatimChar <|> escapedChar <|> escapedCode)
string "\""
return $ jsonTokenString value
where
verbatimChar = satisfyChar (BC.notInClass "\"\\") <?> "invalid string character"
escapedChar = string "\\" >> BC.choice (zipWith escapee chars replacements)
escapedCode = do
string "\\u"
a <- hexDigit
b <- hexDigit
c <- hexDigit
d <- hexDigit
return $ chr $ a `shift` 24 .|. b `shift` 16 .|. c `shift` 8 .|. d
escapee c r = try $ char '\\' >> char c >> return r
chars = [ 'b', 'n', 'f', 'r', 't', '\\', '\'', '/']
replacements = ['\b', '\n', '\f', '\r', '\t', '\\', '\'', '/']
parseJsonTokenBraceL :: (JsonTokenLike j, AFP.Parser t, IsString t) => T.Parser t j
parseJsonTokenBraceL = string "{" >> return jsonTokenBraceL
parseJsonTokenBraceR :: (JsonTokenLike j, AFP.Parser t, IsString t) => T.Parser t j
parseJsonTokenBraceR = string "}" >> return jsonTokenBraceR
parseJsonTokenBracketL :: (JsonTokenLike j, AFP.Parser t, IsString t) => T.Parser t j
parseJsonTokenBracketL = string "[" >> return jsonTokenBracketL
parseJsonTokenBracketR :: (JsonTokenLike j, AFP.Parser t, IsString t) => T.Parser t j
parseJsonTokenBracketR = string "]" >> return jsonTokenBracketR
parseJsonTokenComma :: (JsonTokenLike j, AFP.Parser t, IsString t) => T.Parser t j
parseJsonTokenComma = string "," >> return jsonTokenComma
parseJsonTokenColon :: (JsonTokenLike j, AFP.Parser t, IsString t) => T.Parser t j
parseJsonTokenColon = string ":" >> return jsonTokenColon
parseJsonTokenWhitespace :: (JsonTokenLike j, AFP.Parser t, IsString t) => T.Parser t j
parseJsonTokenWhitespace = do
AC.many1' $ BC.choice [string " ", string "\t", string "\n", string "\r"]
return $ jsonTokenWhitespace
parseJsonTokenNull :: (JsonTokenLike j, AFP.Parser t, IsString t) => T.Parser t j
parseJsonTokenNull = string "null" >> return jsonTokenNull
parseJsonTokenBoolean :: (JsonTokenLike j, AFP.Parser t, IsString t) => T.Parser t j
parseJsonTokenBoolean = true <|> false
where
true = string "true" >> return (jsonTokenBoolean True)
false = string "false" >> return (jsonTokenBoolean False)
parseJsonTokenDouble :: (JsonTokenLike j, AFP.Parser t, IsString t) => T.Parser t j
parseJsonTokenDouble = liftM jsonTokenNumber rational
parseJsonToken :: (JsonTokenLike j, AFP.Parser t, IsString t) => T.Parser t j
parseJsonToken =
parseJsonTokenString <|>
parseJsonTokenBraceL <|>
parseJsonTokenBraceR <|>
parseJsonTokenBracketL <|>
parseJsonTokenBracketR <|>
parseJsonTokenComma <|>
parseJsonTokenColon <|>
parseJsonTokenWhitespace <|>
parseJsonTokenNull <|>
parseJsonTokenBoolean <|>
parseJsonTokenDouble
| haskell-works/data-json-tokenize | src/Data/Json/Final/Tokenize/Internal.hs | bsd-3-clause | 4,564 | 0 | 16 | 987 | 1,446 | 758 | 688 | 98 | 1 |
{-# LANGUAGE GADTs, TypeFamilies, DataKinds, ImplicitParams, StandaloneDeriving, DeriveGeneric #-}
{-|
A stab at an extensible exceptions system, used internally. To be displaced eventually by whatever "composable effects" library becomes the de facto standard in the Haskell community.
-}
module DeepBanana.Exception (
-- * Extensible variants of exception datatypes
Coproduct(..)
, Variant(..)
, throwVariant
, catchVariant
-- * Stack traces
, WithStack
, withStack
-- * Managing exception monads
, unsafeRunExcept
, embedExcept
, runExceptTAs
-- * Specific handlers
, attemptGCThenRetryOn
) where
import DeepBanana.Prelude
import Data.Typeable
import GHC.SrcLoc
import GHC.Stack
import System.Mem
-- | Coproduct of datatypes, indexed by a type-level lists of these datatypes.
-- For instance, @'Coproduct' '[a,b]@ is equivalent to @'Either' a b@.
data Coproduct (l :: [*]) where
Left' :: a -> Coproduct (a ': l)
Right' :: Coproduct l -> Coproduct (a ': l)
instance {-# OVERLAPPING #-} (NFData a) => NFData (Coproduct '[a]) where
rnf (Left' x) = rnf x
instance (NFData a, NFData (Coproduct b)) => NFData (Coproduct (a ': b)) where
rnf (Left' a) = rnf a
rnf (Right' cpb) = rnf cpb
-- | Type class to deal with variant datatypes in a generic fashion.
class Variant t e where
setVariant :: e -> t
getVariant :: t -> Maybe e
instance Variant a a where
setVariant = id
getVariant = Just
instance (Variant (Coproduct b) e) => Variant (Coproduct (a ': b)) e where
setVariant e = Right' $ setVariant e
getVariant (Left' _) = Nothing
getVariant (Right' b) = getVariant b
instance {-# OVERLAPPING #-} Variant (Coproduct (a ': b)) a where
setVariant a = Left' a
getVariant (Left' a) = Just a
getVariant (Right' _) = Nothing
instance {-# OVERLAPPING #-} (Show a) => Show (Coproduct '[a]) where
show (Left' a) = show a
instance (Show a, Show (Coproduct b)) => Show (Coproduct (a ': b)) where
show (Left' a) = show a
show (Right' b) = show b
deriving instance (Typeable a) => Typeable (Coproduct '[a])
deriving instance (Typeable a, Typeable (Coproduct b)) => Typeable (Coproduct (a ': b))
deriving instance Typeable '[]
deriving instance (Typeable a, Typeable b) => Typeable (a ': b)
instance (Show a, Typeable a) => Exception (Coproduct '[a])
instance (Show a, Show (Coproduct b), Typeable a, Typeable b, Typeable (Coproduct b))
=> Exception (Coproduct (a ': b))
-- | Throwing an exception when the error datatype is a variant including that datatype.
throwVariant :: (MonadError t m, Variant t e) => e -> m a
throwVariant = throwError . setVariant
-- | Catching one possible exception type out of a variant.
catchVariant :: forall m t e a
. (MonadError t m, Variant t e)
=> m a -> (e -> m a) -> m a
catchVariant action handler =
let handler' t = case getVariant t :: Maybe e of
Nothing -> throwError t
Just e -> handler e
in catchError action handler'
-- | Simple wrapper adding a call stack to an arbitrary exception.
data WithStack e = WithStack {
exception :: e
, callStack :: String
} deriving (Eq, Typeable, Generic)
instance (NFData e) => NFData (WithStack e)
instance (Show e) => Show (WithStack e) where
show wse = show (exception wse) ++ "\n" ++ callStack wse
instance (Eq e, Show e, Typeable e) => Exception (WithStack e)
withStack :: (?loc :: CallStack) => e -> WithStack e
withStack exception = WithStack exception (showCallStack ?loc)
instance (Variant t e) => Variant (WithStack t) e where
setVariant = withStack . setVariant
getVariant = getVariant . exception
-- | Gets the @'Right'@ part of a computation, throwing an imprecise exception
-- in case of @'Left'@.
unsafeRunExcept :: (Exception e) => Either e a -> a
unsafeRunExcept (Left err) = throw err
unsafeRunExcept (Right out) = out
-- | Embeds an @'Either'@ value into an arbitrary error monad.
embedExcept :: (MonadError e m) => Either e a -> m a
embedExcept ea = do
case ea of
Left err -> throwError err
Right res -> return res
-- | Synonym for @'ExceptT'@ specifying the exception type via a @'Proxy'@. Useful to
-- disambiguate types for the compiler.
runExceptTAs :: Proxy t -> ExceptT t m a -> m (Either t a)
runExceptTAs _ action = runExceptT action
-- | Runs a computation, and in case of a specific exception being raised performs
-- garbage collection before attempting the computation again. This is useful when
-- allocating a lot of memory quickly on the GPU, as the garbage collector may not have
-- enough time to run by itself. Throws back the same exception if the second run fails
-- anyway. This is used anytime an allocation is performed on a GPU device, most notably
-- @'DeepBanana.Tensor.Mutable.emptyTensor'@ and other tensor creation functions.
attemptGCThenRetryOn :: forall m t e a
. (MonadIO m, MonadError t m, Variant t e)
=> Proxy e -> m a -> m a
attemptGCThenRetryOn _ action = do
let handler e = do
liftIO $ performGC
action
action `catchVariant` (handler :: e -> m a)
| alexisVallet/deep-banana | src/DeepBanana/Exception.hs | bsd-3-clause | 5,097 | 0 | 12 | 1,069 | 1,490 | 779 | 711 | -1 | -1 |
module Data.Number.IReal.Auxiliary where
import GHC.Float
infix 1 `atDecimals`
-- Auxiliary functions and constants --------------------------------------------
-- | Base 2 logarithm of argument, rounded downwards.
lg2 :: Integer -> Int
lg2 = GHC.Float.integerLogBase 2
-- | Converts precisions from decimal to binary.
dec2bits :: Int -> Int
dec2bits d = ceiling (fromIntegral d * logBase 2 10 :: Double)
-- | Operator allowing function expecting binary precision to be applied to decimal ditto.
atDecimals :: (Int -> a) -> Int -> a
atDecimals f = f . dec2bits
| sydow/ireal | Data/Number/IReal/Auxiliary.hs | bsd-3-clause | 571 | 0 | 8 | 96 | 114 | 65 | 49 | 9 | 1 |
{-# LANGUAGE ScopedTypeVariables #-}
module Yesod.Helpers.Handler where
-- {{{1 imports
import ClassyPrelude.Yesod hiding (runFakeHandler, requestHeaders)
import Yesod.Core.Types (HandlerT(..), handlerRequest)
import qualified Control.Monad.Trans.Reader as R
import qualified Data.ByteString.Char8 as B8
import qualified Data.Text as T
import qualified Data.Text.Encoding as TE
#if MIN_VERSION_yesod_core(1,4,0)
import Yesod.Core.Unsafe (runFakeHandler)
#else
import Yesod.Core (runFakeHandler)
#endif
import qualified Data.Map.Strict as Map
import Control.Monad.Trans.Maybe
import Network.Wai (requestHeaders, rawQueryString, requestMethod)
import Text.Blaze (Markup)
import Data.List (findIndex)
import Data.Aeson.Types (Pair)
import Yesod.Helpers.Form2
import Yesod.Helpers.Form (jsonOrHtmlOutputForm')
import Yesod.Helpers.Utils (nullToNothing, encodeUtf8Rfc5987)
import Yesod.Helpers.Pager
import Yesod.Helpers.JSend (provideRepJsendAndJsonp, JSendMsg(JSendSuccess))
-- }}}1
-- | Tell browser never cache this response
-- See: http://stackoverflow.com/questions/49547/how-to-control-web-page-caching-across-all-browsers/2068407
neverCache :: MonadHandler m => m ()
neverCache = do
addHeader "Cache-Control" "no-cache, no-store, must-revalidate"
addHeader "Pragma" "no-cache"
addHeader "Expires" "0"
setLastModified :: UTCTime -> HandlerT site IO ()
setLastModified = addHeader "Last-Modified" . formatRFC1123
asAttachment :: MonadHandler m => Maybe Text -> m ()
asAttachment Nothing = addHeader "Content-Disposition" "attachment"
asAttachment (Just fn) = addHeader "Content-Disposition" $ "attachment; filename*=" <> decodeUtf8 (encodeUtf8Rfc5987 fn)
{-# DEPRECATED isXHR "use acceptsJson instead" #-}
isXHR :: (MonadHandler m) => m Bool
isXHR = do
req <- waiRequest
let req_with = lookup "X-Request-With" $ requestHeaders req
return $ maybe False (== "XMLHTTPRequest") req_with
-- | Works like aceeptsJson, but for jsonp: check for javascript
-- Code stolen from: Yesod.Core.Json
acceptsJavascript :: MonadHandler m => m Bool
acceptsJavascript = (maybe False ((== "application/javascript") . B8.takeWhile (/= ';'))
. listToMaybe
. reqAccept)
`liftM` getRequest
-- | Check accepts for json or jsonp
acceptsJsonOrJsonp :: MonadHandler m => m Bool
acceptsJsonOrJsonp = liftM2 (||) acceptsJson acceptsJavascript
clientOriginalIp :: MonadHandler m => m (Maybe ByteString)
clientOriginalIp = do
req <- waiRequest
let headers = requestHeaders req
let first_ip_in_header hn = do
h <- lookup hn headers
listToMaybe $ filter (not . null) . map (encodeUtf8 . T.strip) $ T.splitOn "," $ decodeUtf8 h
-- Normally, only x-forwarded-for may contain multiple IPs.
-- But 'http-reverse-proxy' may make x-real-ip to contain multiple ip (possibly a bug).
-- So we always prepare for multiple IPs.
let f1 = first_ip_in_header "X-Real-IP"
f2 = first_ip_in_header "X-Forwarded-For"
f3 = first_ip_in_header "Remote-Addr"
return $ f1 <|> f2 <|> f3
getCurrentUrl :: MonadHandler m => m Text
getCurrentUrl = do
req <- waiRequest
current_route <- getCurrentRoute >>= maybe (error "getCurrentRoute failed") return
url_render <- getUrlRender
return $ url_render current_route <> TE.decodeUtf8 (rawQueryString req)
getCurrentUrlExtraQS :: MonadHandler m => Text -> m Text
getCurrentUrlExtraQS qs = do
req <- waiRequest
current_route <- getCurrentRoute >>= maybe (error "getCurrentRoute failed") return
url_render <- getUrlRender
return $ url_render current_route <> add_qs (TE.decodeUtf8 (rawQueryString req))
where
add_qs x = if T.null x
then qs
else x <> "&" <> qs
-- | form function type synonym
type MkForm site m a = Markup -> MForm (HandlerT site m) (FormResult a, WidgetT site IO ())
type MkEMForm site m a = Markup -> EMForm (HandlerT site m) (FormResult a, WidgetT site IO ())
type FormHandlerT site m a = R.ReaderT (WidgetT site IO (), Enctype) (HandlerT site m) a
type GenFormData site = (WidgetT site IO (), Enctype)
type EFormHandlerT site m a = R.ReaderT (GenFormData site, FieldErrors site) (HandlerT site m) a
handleGetPostEMFormTc :: (Yesod site, RenderMessage site FormMessage)
=> MkEMForm site IO a
-> (Maybe e -> EFormHandlerT site IO Html)
-> ((Maybe e -> HandlerT site IO TypedContent) -> a -> HandlerT site IO TypedContent)
-> HandlerT site IO TypedContent
-- {{{1
handleGetPostEMFormTc form show_form handle_form_data = do
handleGetPostEMForm form show_form' handle_form_data
where
show_form' = jsonOrHtmlOutputFormEX [] . show_form
-- }}}1
handleGetPostEMForm :: (Yesod site, RenderMessage site FormMessage)
=> MkEMForm site IO a
-> (Maybe e -> EFormHandlerT site IO c)
-> ((Maybe e -> HandlerT site IO c) -> a -> HandlerT site IO c)
-> HandlerT site IO c
-- {{{1
handleGetPostEMForm form show_form handle_form_data = do
req_method <- requestMethod <$> waiRequest
case req_method of
"GET" -> do
generateEMFormPost form >>= runReaderT ((show_form Nothing))
"POST" -> do
(((result, formWidget), formEnctype), form_errs) <- runEMFormPost form
let showf merr = do
flip runReaderT ((formWidget, formEnctype), form_errs) $ do
show_form merr
case result of
FormMissing -> showf Nothing
FormFailure _ -> showf Nothing
FormSuccess form_data -> handle_form_data showf form_data
_ -> sendResponseStatus methodNotAllowed405 (asText "Method Not Allowed!")
-- }}}1
handleGetPostEMFormNoTokenTc :: (Yesod site, RenderMessage site FormMessage)
=> MkEMForm site IO a
-> (Maybe Text -> EFormHandlerT site IO Html)
-> ((Maybe Text -> HandlerT site IO TypedContent) -> a -> HandlerT site IO TypedContent)
-> HandlerT site IO TypedContent
-- {{{1
handleGetPostEMFormNoTokenTc form show_form handle_form_data = do
handleGetPostEMFormNoToken form show_form' handle_form_data
where
show_form' = jsonOrHtmlOutputFormEX [] . show_form
-- }}}1
handleGetPostEMFormNoToken :: (Yesod site, RenderMessage site FormMessage)
=> MkEMForm site IO a
-> (Maybe Text -> EFormHandlerT site IO c)
-> ((Maybe Text -> HandlerT site IO c) -> a -> HandlerT site IO c)
-> HandlerT site IO c
-- {{{1
handleGetPostEMFormNoToken form show_form handle_form_data = do
req_method <- requestMethod <$> waiRequest
case req_method of
"GET" -> do
generateEMFormPost form >>= runReaderT ((show_form Nothing))
"POST" -> do
(((result, formWidget), formEnctype), form_errs) <- runEMFormPostNoToken form
let showf merr = do
m_add_err <- liftM (fromMaybe mempty) $ forM merr $ \err -> do
return $ overallFieldError err
flip runReaderT ((formWidget, formEnctype), form_errs <> m_add_err) $ do
show_form merr
case result of
FormMissing -> showf Nothing
FormFailure _ -> showf Nothing
FormSuccess form_data -> handle_form_data showf form_data
_ -> sendResponseStatus methodNotAllowed405 (asText "Method Not Allowed!")
-- }}}1
-- | Handler a GET form
-- If form failed/missing, abort processing and output empty widget (except the form widget)
handleGetEMForm :: (ToTypedContent b, MonadHandler m, w ~ WidgetT site IO ())
=> (Html -> EMForm m (FormResult a, w))
-- ^ 'MkEMForm a', the form function
-> ((w, Enctype) -> FieldErrors (HandlerSite m) -> Maybe Text -> Maybe w -> m b)
-- ^ a function to make some output.
-- Maybe Text param: an error message
-- first 'w': form widget
-- second 'w': extra content. If form failed/missing, this is mempty, otherwise, it is the output of function in next param.
-> (a -> m w)
-- ^ use the form result
-> m b
-- {{{1
handleGetEMForm form show_widget f = do
(((form_result, form_widget), form_enc), form_errs) <- runEMFormGet form
let show_empty_form_page m_err = do
show_widget (form_widget, form_enc) form_errs m_err Nothing
case form_result of
FormMissing -> show_empty_form_page Nothing >>= sendResponse
FormFailure errs -> show_empty_form_page (Just $ intercalate "," errs) >>= sendResponse
FormSuccess result -> do
f result >>= show_widget (form_widget, form_enc) mempty Nothing . Just
-- }}}1
-- ^
-- Typical Usage:
--
-- xxxForm :: Form XXX
-- xxxForm extra = undefined
--
-- showXXXPage :: FormHandlerT App IO Html
-- showXXXPage = do
-- (formWidget, formEnctype) <- R.ask
-- lift $ defaultLayout $ do
-- $(widgetFile "xxx")
--
-- getXXXR :: Handler TypedContent
-- getXXXR = do
-- generateFormPostHandlerJH xxxForm showXXXPage
--
-- postAddJournalInfoR :: Handler TypedContent
-- postAddJournalInfoR = do
-- runFormPostHandlerJH xxxForm showXXXPage $
-- (\result -> undefined) :: (XXX -> Handler (Either [msg] TypedContent))
generateFormPostHandler ::
( Monad m, MonadThrow m, MonadBaseControl IO m, MonadIO m
, RenderMessage site FormMessage
) =>
MkForm site m r
-> FormHandlerT site m a
-> HandlerT site m a
generateFormPostHandler form_func fh = do
generateFormPost form_func >>= R.runReaderT fh
generateEMFormPostHandler ::
( Monad m, MonadThrow m, MonadBaseControl IO m, MonadIO m
, RenderMessage site FormMessage
) =>
MkEMForm site m r
-> EFormHandlerT site m a
-> HandlerT site m a
generateEMFormPostHandler form_func fh = do
generateEMFormPost form_func >>= R.runReaderT fh
generateFormPostHandlerJH ::
( Yesod site, RenderMessage site FormMessage
, MonadIO m, MonadThrow m, MonadBaseControl IO m
) =>
MkForm site m r
-> ([Text] -> FormHandlerT site m Html)
-> HandlerT site m TypedContent
generateFormPostHandlerJH form_func show_page = do
generateFormPostHandler form_func $ do
jsonOrHtmlOutputFormX show_page []
generateEMFormPostHandlerJH ::
( Yesod site, RenderMessage site FormMessage
, MonadIO m, MonadThrow m, MonadBaseControl IO m
) =>
MkEMForm site m r
-> (EFormHandlerT site m Html)
-> HandlerT site m TypedContent
generateEMFormPostHandlerJH form_func show_page = do
generateEMFormPostHandler form_func $ do
jsonOrHtmlOutputFormEX [] show_page
runFormPostHandler ::
( Monad m, MonadThrow m, MonadBaseControl IO m, MonadIO m
, RenderMessage site FormMessage
) =>
MkForm site m r
-> (FormResult r -> FormHandlerT site m a)
-> HandlerT site m a
runFormPostHandler form_func fh = do
((result, formWidget), formEnctype) <- runFormPost form_func
R.runReaderT (fh result) (formWidget, formEnctype)
runFormPostHandlerJH ::
(RenderMessage site FormMessage, RenderMessage site msg, Yesod site
, MonadIO m, MonadBaseControl IO m, MonadThrow m
) =>
MkForm site m r -- ^ form function
-> ([Text] -> FormHandlerT site m Html)
-- ^ show html page function
-> (r -> HandlerT site m (Either [msg] TypedContent))
-- ^ function to handler success form result
-> HandlerT site m TypedContent
runFormPostHandlerJH form_func show_page h_ok = do
runFormPostHandler form_func $
jsonOrHtmlOutputFormHandleResult show_page h_ok
jsonOrHtmlOutputFormX :: (Yesod site, MonadIO m, MonadThrow m, MonadBaseControl IO m) =>
([Text] -> FormHandlerT site m Html)
-> [Text]
-> FormHandlerT site m TypedContent
jsonOrHtmlOutputFormX show_form errs = do
(formWidget, formEnctype) <- R.ask
let show_form' = R.runReaderT (show_form errs) (formWidget, formEnctype)
lift $ jsonOrHtmlOutputForm' show_form' formWidget [ "form_errors" .= errs ]
-- | response with html content or json content
-- the JSON format is in "JSend" format, like this:
-- { "status": "success"
-- , "data": { "form":
-- { "body": /* form html code */
-- , "errors": { "field1", "error message1" }
-- }
-- }
-- }
jsonOrHtmlOutputFormEX :: (Yesod site, MonadIO m, MonadThrow m, MonadBaseControl IO m)
=> [Pair]
-> EFormHandlerT site m Html
-- ^ provide HTML content
-> EFormHandlerT site m TypedContent
jsonOrHtmlOutputFormEX extra_js_fields show_form = do
r@((formWidget, _formEnctype), field_errs) <- R.ask
lift $ do
render_msg <- getMessageRender
selectRep $ do
provideRep $ R.runReaderT show_form r
provideRepJsendAndJsonp $ do
form_body <- widgetToBodyHtml formWidget
return $ jsendFormData render_msg (Just form_body) field_errs extra_js_fields
jsonOrHtmlOutputFormHandleResult ::
(Yesod site, RenderMessage site msg
, MonadIO m, MonadThrow m, MonadBaseControl IO m
) =>
([Text] -> FormHandlerT site m Html)
-> (r -> HandlerT site m (Either [msg] TypedContent))
-> FormResult r
-> FormHandlerT site m TypedContent
jsonOrHtmlOutputFormHandleResult show_page f result = do
let showf errs = jsonOrHtmlOutputFormX show_page errs
showf' msgs = lift getMessageRender >>= showf . flip map msgs
case result of
FormMissing -> showf ([] :: [Text])
FormFailure errs -> showf errs
FormSuccess x -> (lift $ f x) >>= either showf' return
-- | 如果是普通页面输出,则,调用 setMessageI 并重定向至指定的 route
-- 如果是 JSON 输出,则按操作成功的方式输出文字信息
jsonOrRedirect ::
forall site message url.
(RenderMessage site message, RedirectUrl site url) =>
message -> url -> HandlerT site IO TypedContent
jsonOrRedirect msg route = do
selectRep $ do
provideRepJsendAndJsonp $ do
msgRender <- getMessageRender
let tmsg = msgRender msg
turl <- toTextUrl route
let dat = object $ [( "url" .= turl ), ( "msg" .= tmsg )]
return $ JSendSuccess dat
provideRep $ html
where
html :: HandlerT site IO Html
html = do
setMessageI $ msg
redirect route
matchMimeType :: ContentType -> ContentType -> Bool
matchMimeType expected actual =
(mainType == "*" || mainType0 == "*" || mainType == mainType0)
&& (subType == "*" || subType0 == "*" || subType == subType0)
where
(mainType, subType) = contentTypeTypes actual
(mainType0, subType0) = contentTypeTypes expected
lookupReqAccept :: MonadHandler m => [(ContentType -> Bool, a)] -> m (Maybe a)
lookupReqAccept lst = do
fmap reqAccept getRequest >>= return . tryAccepts
where
tryAccepts cts = listToMaybe $ map snd $
sortBy (comparing $ fst) $ catMaybes $
flip map lst $
\(f, x) ->
fmap (, x) $ findIndex f cts
-- | runFormGet needs a special parameter "_hasdata",
-- if it does not exist, runFormGet consider no form data input at all.
-- Use this function to workaround this.
-- XXX: getHelper auto add _hasdata to the form.
-- It'd better to add to params by yourself if submit by AJAX.
withHasDataGetParam :: HandlerT site m a -> HandlerT site m a
withHasDataGetParam f = withAlteredYesodRequest add_has_data_req f
where
getKey = "_hasdata" -- 这个值 Yesod 没有 export 出来
add_has_data_req req =
req { reqGetParams = add_has_data $ reqGetParams req }
add_has_data ps = maybe ((getKey, "") : ps) (const ps) $
lookup getKey ps
-- | modify YesodRequest before executing inner Handler code
withAlteredYesodRequest ::
(YesodRequest -> YesodRequest)
-> HandlerT site m a -> HandlerT site m a
withAlteredYesodRequest change f = HandlerT $ unHandlerT f . modify_hd
where
modify_hd hd = hd { handlerRequest = change $ handlerRequest hd }
-- | like FormResult, but used when you want to manually validate get/post params
data ParamResult a = ParamError [(Text, Text)]
| ParamSuccess a
deriving (Eq, Show)
instance Functor ParamResult where
fmap _ (ParamError errs) = ParamError errs
fmap f (ParamSuccess x) = ParamSuccess (f x)
instance Applicative ParamResult where
pure = ParamSuccess
(ParamError errs) <*> (ParamError errs2) = ParamError (errs ++ errs2)
(ParamError errs) <*> (ParamSuccess _) = ParamError errs
(ParamSuccess _) <*> (ParamError errs) = ParamError errs
(ParamSuccess f) <*> (ParamSuccess x) = ParamSuccess $ f x
instance Monad ParamResult where
return = pure
(ParamError errs) >>= _ = ParamError errs
(ParamSuccess x) >>= f = f x
fail msg = ParamError [("", T.pack msg)]
httpErrorRetryWithValidParams ::
(IsString s, Semigroup s, ToTypedContent s, MonadHandler m) =>
s -> m a
httpErrorRetryWithValidParams msg = do
sendResponseStatus (mkStatus 449 "Retry With") $
"Retry with valid parameters: " <> msg
httpErrorWhenParamError :: MonadHandler m => ParamResult a -> m a
httpErrorWhenParamError (ParamSuccess x) = return x
httpErrorWhenParamError (ParamError errs) =
httpErrorRetryWithValidParams msg
where
msg = T.intercalate ", " $
flip map errs $ \(param_name, err_msg) ->
if T.null err_msg
then param_name
else param_name <> "(" <> err_msg <> ")"
mkParamErrorNoMsg :: Text -> ParamResult a
mkParamErrorNoMsg p = ParamError [ (p, "") ]
reqGetParamE :: MonadHandler m => Text -> m (ParamResult Text)
reqGetParamE p = fmap (maybe (mkParamErrorNoMsg p) ParamSuccess) $ lookupGetParam p
reqGetParamE' :: MonadHandler m => Text -> m (ParamResult Text)
reqGetParamE' p = reqGetParamE p >>= return . nonEmptyParam p
reqPostParamE :: MonadHandler m => Text -> m (ParamResult Text)
reqPostParamE p = fmap (maybe (mkParamErrorNoMsg p) ParamSuccess) $ lookupPostParam p
reqPostParamE' :: MonadHandler m => Text -> m (ParamResult Text)
reqPostParamE' p = reqPostParamE p >>= return . nonEmptyParam p
nonEmptyParam :: Text -> ParamResult Text -> ParamResult Text
nonEmptyParam pn pr = do
x <- pr
if T.null x
then ParamError [(pn, "must not be empty")]
else ParamSuccess x
paramErrorFromEither :: Text -> Either Text a -> ParamResult a
paramErrorFromEither pn (Left err) = ParamError [(pn, err)]
paramErrorFromEither _ (Right x) = ParamSuccess x
validateParam :: Text -> (a -> Either Text b) -> ParamResult a -> ParamResult b
validateParam pn f pr = do
pr >>= paramErrorFromEither pn . f
-- | 用于保持某些 get/post 变量,以便在 redirect 和 提交表单时可以传送給下一个服务器地址
retainHttpParams :: MonadHandler m => [Text] -> m [(Text, Text)]
retainHttpParams param_names = do
fmap catMaybes $ mapM f param_names
where
f n = runMaybeT $ do
val <- MaybeT (lookupPostParam n) <|> MaybeT (lookupGetParam n)
return (n, val)
reqPathPieceParamPostGet :: (PathPiece a, MonadHandler m) =>
Text
-> m a
reqPathPieceParamPostGet pname =
optPathPieceParamPostGet pname >>= maybe (invalidArgs [pname]) return
optPathPieceParamPostGet :: (PathPiece a, MonadHandler m) =>
Text
-> m (Maybe a)
optPathPieceParamPostGet pname =
(fmap (join . fmap fromPathPiece) $ runMaybeT $
(MaybeT $ join . fmap nullToNothing <$> lookupPostParam pname)
<|> (MaybeT $ join . fmap nullToNothing <$> lookupGetParam pname))
getUrlRenderParamsIO :: Yesod site => site -> IO (Route site -> [(Text, Text)] -> Text)
getUrlRenderParamsIO foundation = do
runFakeHandler Map.empty
(error "logger required in getUrlRenderParamsIO")
foundation getUrlRenderParams
>>= either (error "getUrlRenderParams shoud never fail") return
getUrlRenderIO :: Yesod site => site -> IO (Route site -> Text)
getUrlRenderIO foundation = do
runFakeHandler Map.empty
(error "logger required in getUrlRenderIO")
foundation getUrlRender
>>= either (error "getUrlRender shoud never fail") return
widgetToBodyHtml :: (Yesod site, MonadIO m, MonadThrow m, MonadBaseControl IO m)
=> WidgetT site IO ()
-> HandlerT site m Html
widgetToBodyHtml widget = liftHandlerT $ do
widgetToPageContent widget
>>= withUrlRenderer . pageBody
-- | 目前来说,大多数时候情况都不需要 i18n
-- 这个函数包装了 languages:
-- 仅在必要时才真正调用 languages,其它时候只返回固定的语言
defaultLangs :: MonadHandler m
=> Lang
-> m [Lang]
defaultLangs def_lang = do
b <- fromMaybe (0 :: Int) <$> optPathPieceParamPostGet "_i18n"
if b > 0
then languages
else return [ def_lang ]
defaultZhCnLangs :: MonadHandler m
=> m [Lang]
defaultZhCnLangs = defaultLangs "zh-CN"
type PagedPage site a = Maybe Text
-> PagedResult
-> a
-> Int
-> EFormHandlerT site IO Html
handlerPagedPageWithForm :: (NumPerPage so, Yesod site, RenderMessage site FormMessage)
=> so
-> MkEMForm site IO so
-> (so -> Int -> Int -> HandlerT site IO ((a, Value), Int))
-> PagedPage site a
-> HandlerT site IO TypedContent
-- {{{1
handlerPagedPageWithForm def_so form get_data show_html = do
(((result, formWidget), formEnctype), form_errs) <- runEMFormGet form
let so = case result of
FormSuccess x -> x
_ -> def_so
let npp = numPerPage so
pn_param = "p"
let pager_settings = PagerSettings npp pn_param
pn <- pagerGetCurrentPageNumGet pager_settings
((result_list, json), total_num) <- get_data so npp pn
paged <- runPager pager_settings pn total_num
let showf merr results = do
m_add_err <- liftM (fromMaybe mempty) $ forM merr $ \err -> do
return $ overallFieldError err
flip runReaderT ((formWidget, formEnctype), form_errs <> m_add_err) $ do
show_html merr paged results total_num
selectRep $ do
provideRep $ do
showf Nothing result_list
provideRepJsendAndJsonp $ do
return $ JSendSuccess json
-- }}}1
-- vim: set foldmethod=marker:
| yoo-e/yesod-helpers | Yesod/Helpers/Handler.hs | bsd-3-clause | 23,540 | 0 | 23 | 6,419 | 6,114 | 3,079 | 3,035 | -1 | -1 |
module Config where
import Data.Text
data Config
= Config
{ configUsername :: Text
, configHostname :: Text
, configTeam :: Text
, configPort :: Int
, configPassword :: Text
}
| dagit/mattermost-api | examples/Config.hs | bsd-3-clause | 200 | 0 | 8 | 54 | 48 | 31 | 17 | 9 | 0 |
-- | A parser for the Xtract command-language. (The string input is
-- tokenised internally by the lexer 'lexXtract'.)
-- See <http://www.haskell.org/HaXml/Xtract.html> for the grammar that
-- is accepted.
-- Because the original Xtract grammar was left-recursive, we have
-- transformed it into a non-left-recursive form.
module Text.XML.HaXml.Xtract.Parse (parseXtract,xtract) where
import Text.ParserCombinators.Poly hiding (bracket)
import Text.XML.HaXml.Xtract.Lex
import Text.XML.HaXml.Xtract.Combinators
import Text.XML.HaXml.Combinators
import List(isPrefixOf)
-- | To convert an Xtract query into an ordinary HaXml combinator expression.
xtract :: String -> CFilter i
xtract query = dfilter (parseXtract query)
-- | The cool thing is that the Xtract command parser directly builds
-- a higher-order 'DFilter' (see "Text.XML.HaXml.Xtract.Combinators")
-- which can be applied to an XML document without further ado.
-- (@parseXtract@ halts the program if a parse error is found.)
parseXtract :: String -> DFilter i
parseXtract = either error id . parseXtract'
-- | @parseXtract'@ returns error messages through the Either type.
parseXtract' :: String -> Either String (DFilter i)
parseXtract' = fst . runParser xql . lexXtract
xql = aquery (local keep)
---- Auxiliary Parsing Functions ----
type XParser a = Parser (Either String (Posn,TokenT)) a
string :: XParser String
string = P (\inp -> case inp of
(Left err: _) -> (Left (False,err), inp)
(Right (p,TokString n):ts) -> (Right n, ts)
ts -> (Left (False,"expected a string"), ts) )
number :: XParser Integer
number = P (\inp -> case inp of
(Left err: _) -> (Left (False,err), inp)
(Right (p,TokNum n):ts) -> (Right n, ts)
ts -> (Left (False,"expected a number"), ts) )
symbol :: String -> XParser ()
symbol s = P (\inp -> case inp of
(Left err: _) -> (Left (False,err), inp)
(Right (p, Symbol n):ts) | n==s -> (Right (), ts)
ts -> (Left (False,"expected symbol "++s), ts) )
quote = oneOf [ symbol "'", symbol "\"" ]
pam fs x = [ f x | f <- fs ]
{--- original Xtract grammar ----
query = string tagname
| string * tagname prefix
| * string tagname suffix
| * any element
| - chardata
| ( query )
| query / query parent/child relationship
| query // query deep inside
| query + query union of queries
| query [predicate]
| query [positions]
predicate = quattr has attribute
| quattr op ' string ' attribute has value
| quattr op " string " attribute has value
| quattr op quattr attribute value comparison (lexical)
| quattr nop integer attribute has value (numerical)
| quattr nop quattr attribute value comparison (numerical)
| ( predicate ) bracketting
| predicate & predicate logical and
| predicate | predicate logical or
| ~ predicate logical not
attribute = @ string has attribute
| query / @ string child has attribute
| - has textual content
| query / - child has textual content
quattr = query
| attribute
op = = equal to
| != not equal to
| < less than
| <= less than or equal to
| > greater than
| >= greater than or equal to
nop = .=. equal to
| .!=. not equal to
| .<. less than
| .<=. less than or equal to
| .>. greater than
| .>=. greater than or equal to
positions = position {, positions} multiple positions
| position - position ranges
position = integer numbering is from 0 upwards
| $ last
---- transformed grammar (removing left recursion)
aquery = ./ tquery -- current context
| tquery -- also current context
| / tquery -- root context
| // tquery -- deep context from root
tquery = ( tquery ) xquery
| tag xquery
| - -- fixes original grammar ("-/*" is incorrect)
tag = string *
| string
| * string
| *
xquery = / tquery
| // tquery
| / @ string -- new: print attribute value
| + tquery
| [ tpredicate ] xquery
| [ positions ] xquery
| lambda
tpredicate = vpredicate upredicate
upredicate = & tpredicate
| | tpredicate
| lambda
vpredicate = ( tpredicate )
| ~ tpredicate
| tattribute
tattribute = aquery uattribute
| @ string vattribute
uattribute = / @ string vattribute
| vattribute
vattribute = op wattribute
| op ' string '
| nop wattribute
| nop integer
| lambda
wattribute = @ string
| aquery / @ string
| aquery
positions = simplepos commapos
simplepos = integer range
| $
range = - integer
| - $
| lambda
commapos = , simplepos commapos
| lambda
op = =
| !=
| <
| <=
| >
| >=
nop = .=.
| .!=.
| .<.
| .<=.
| .>.
| .>=.
-}
bracket :: XParser a -> XParser a
bracket p =
do symbol "("
x <- p
symbol ")"
return x
---- Xtract parsers ----
-- aquery takes a localisation filter, but if the query string starts
-- from the root, we ignore the local context
aquery :: DFilter i -> XParser (DFilter i)
aquery localise = oneOf
[ do symbol "//"
tquery [oglobo deep]
, do symbol "/"
tquery [oglobo id]
, do symbol "./"
tquery [(localise //>>)]
, do tquery [(localise //>>)]
]
tquery :: [DFilter i->DFilter i] -> XParser (DFilter i)
tquery [] = tquery [id]
tquery (qf:cxt) = oneOf
[ do q <- bracket (tquery (qf:qf:cxt))
xquery cxt q
, do q <- xtag
xquery cxt (qf q)
, do symbol "-"
return (qf (local txt))
]
xtag :: XParser (DFilter i)
xtag = oneOf
[ do s <- string
symbol "*"
return (local (tagWith (s `isPrefixOf`)))
, do s <- string
return (local (tag s))
, do symbol "*"
s <- string
return (local (tagWith (((reverse s) `isPrefixOf`) . reverse)))
, do symbol "*"
return (local elm)
]
xquery :: [DFilter i->DFilter i] -> DFilter i -> XParser (DFilter i)
xquery cxt q1 = oneOf
[ do symbol "/"
( do symbol "@"
attr <- string
return (oiffindo attr (\s->local (literal s)) ononeo `ooo` q1)
`onFail`
tquery ((q1 //>>):cxt) )
, do symbol "//"
tquery ((\q2-> (oloco deep) q2 `ooo` local children `ooo` q1):cxt)
, do symbol "+"
q2 <- tquery cxt
return (ocato [q1,q2])
, do symbol "["
is <- iindex -- now extended to multiple indexes
symbol "]"
xquery cxt (\xml-> concat . pam is . q1 xml)
, do symbol "["
p <- tpredicate
symbol "]"
xquery cxt (q1 `owitho` p)
, return q1
]
tpredicate :: XParser (DFilter i)
tpredicate =
do p <- vpredicate
f <- upredicate
return (f p)
upredicate :: XParser (DFilter i->DFilter i)
upredicate = oneOf
[ do symbol "&"
p2 <- tpredicate
return (`ooo` p2)
, do symbol "|"
p2 <- tpredicate
return (||>|| p2)
, return id
]
vpredicate :: XParser (DFilter i)
vpredicate = oneOf
[ do bracket tpredicate
, do symbol "~"
p <- tpredicate
return (local keep `owithouto` p)
, do tattribute
]
tattribute :: XParser (DFilter i)
tattribute = oneOf
[ do q <- aquery (local keep)
uattribute q
, do symbol "@"
s <- string
vattribute (local keep, local (attr s), oiffindo s)
]
uattribute :: DFilter i -> XParser (DFilter i)
uattribute q = oneOf
[ do symbol "/"
symbol "@"
s <- string
vattribute (q, local (attr s), oiffindo s)
, do vattribute (q, local keep, oifTxto)
]
vattribute :: (DFilter i, DFilter i, (String->DFilter i)->DFilter i->DFilter i)
-> XParser (DFilter i)
vattribute (q,a,iffn) = oneOf
[ do cmp <- op
quote
s2 <- string
quote
return ((iffn (\s1->if cmp s1 s2 then okeepo else ononeo) ononeo)
`ooo` q)
, do cmp <- op
(q2,iffn2) <- wattribute
return ((iffn (\s1-> iffn2 (\s2-> if cmp s1 s2 then okeepo else ononeo)
ononeo)
ononeo) `ooo` q)
, do cmp <- nop
n <- number
return ((iffn (\s->if cmp (read s) n then okeepo else ononeo) ononeo)
`ooo` q)
, do cmp <- nop
(q2,iffn2) <- wattribute
return ((iffn (\s1-> iffn2 (\s2-> if cmp (read s1) (read s2) then okeepo
else ononeo)
ononeo)
ononeo) `ooo` q)
, do return ((a `ooo` q))
]
wattribute :: XParser (DFilter i, (String->DFilter i)->DFilter i->DFilter i)
wattribute = oneOf
[ do symbol "@"
s <- string
return (okeepo, oiffindo s)
, do q <- aquery okeepo
symbol "/"
symbol "@"
s <- string
return (q, oiffindo s)
, do q <- aquery okeepo
return (q, oifTxto)
]
iindex :: XParser [[a]->[a]]
iindex =
do i <- simpleindex
is <- idxcomma
return (i:is)
simpleindex :: XParser ([a]->[a])
simpleindex = oneOf
[ do n <- number
r <- rrange n
return r
, do symbol "$"
return (keep . last)
]
rrange, numberdollar :: Integer -> XParser ([a]->[a])
rrange n1 = oneOf
[ do symbol "-"
numberdollar n1
, return (keep.(!!(fromInteger n1)))
]
numberdollar n1 = oneOf
[ do n2 <- number
return (take (fromInteger (1+n2-n1)) . drop (fromInteger n1))
, do symbol "$"
return (drop (fromInteger n1))
]
idxcomma :: XParser [[a]->[a]]
idxcomma = oneOf
[ do symbol ","
r <- simpleindex
rs <- idxcomma
return (r:rs)
, return []
]
op :: XParser (String->String->Bool)
op = oneOf
[ do symbol "="; return (==)
, do symbol "!="; return (/=)
, do symbol "<"; return (<)
, do symbol "<="; return (<=)
, do symbol ">"; return (>)
, do symbol ">="; return (>=)
]
nop :: XParser (Integer->Integer->Bool)
nop = oneOf
[ do symbol ".=."; return (==)
, do symbol ".!=."; return (/=)
, do symbol ".<."; return (<)
, do symbol ".<=."; return (<=)
, do symbol ".>."; return (>)
, do symbol ".>=."; return (>=)
]
| FranklinChen/hugs98-plus-Sep2006 | packages/HaXml/src/Text/XML/HaXml/Xtract/Parse.hs | bsd-3-clause | 11,554 | 1 | 22 | 4,425 | 3,019 | 1,518 | 1,501 | -1 | -1 |
-- Copyright (c) 2010, Diego Souza
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions are met:
--
-- * Redistributions of source code must retain the above copyright notice,
-- this list of conditions and the following disclaimer.
-- * Redistributions in binary form must reproduce the above copyright notice,
-- this list of conditions and the following disclaimer in the documentation
-- and/or other materials provided with the distribution.
-- * Neither the name of the <ORGANIZATION> nor the names of its contributors
-- may be used to endorse or promote products derived from this software
-- without specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
-- ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-- WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
-- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
-- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
-- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
-- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
-- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
module Yql.Core.LocalFunctions.Exec
( function
) where
import Yql.Core.Types
import System.Process
import Yql.Core.LocalFunction
import Control.Exception as C
import Control.Concurrent
import Control.Monad
import System.Directory
import System.IO
import System.Exit
exec :: String -> [String] -> String -> IO String
exec bin argv input = do { proceed <- binaryOk
; if (proceed)
then runExec
else return $ "error: could not find/execute file ["++ bin ++"]"
}
where binaryOk = do { found <- doesFileExist bin
; if (found)
then getPermissions bin >>= return . executable
else return False
}
runExec = do { (Just inh,Just outh,_,pid) <- createProcess (proc bin argv) { std_in = CreatePipe
, std_out = CreatePipe
, std_err = Inherit
}
; output <- hGetContents outh
; outMVar <- newEmptyMVar
; forkIO $ C.evaluate (length output) >> putMVar outMVar ()
; when (not (null input)) $ do { hPutStr inh input
; hFlush inh
}
; hClose inh
; takeMVar outMVar
; hClose outh
; ex <- waitForProcess pid
; case ex
of ExitSuccess -> return output
ExitFailure errno -> return ("error running program ["++ bin ++"]. exit " ++ show errno)
}
function :: Exec
function = TransformM doc runExec
where doc _ = unlines [ "Invoke an arbitrary function from the filesystem."
, "The program should be able to read input from stdin and write output to stdout. Only stdout is collected for further processing while stderr is printed as-is."
, "Examples:"
, " SELECT * FROM social.profile WHERE guid=me | .exec(file=\"/bin/foobar\");"
, " SELECT * FROM social.profile WHERE guid=me | .exec(file=\"/bin/foobar\", argv='[\"foobar\", \"foo bar\"]');"
, ""
, "N.B.: The reason argv parameter is cumbersome is because it uses read function, which requires valid haskell syntax. In other words, you need to put brackets and use double quotes to every parameter."
]
runExec argv input = case (lookup "file" argv)
of Just (TxtValue bin) -> let computation = exec bin arguments input
handler = \(SomeException e) -> return (show e)
in C.catch computation handler
Just _ -> return $ "error: missing file argument"
_ -> return $ "error: missing file argument"
where arguments = case (lookup "argv" argv)
of Just (TxtValue raw) -> case (reads raw)
of [(arglist,"")] -> arglist
_ -> []
Just _ -> []
Nothing -> []
| dgvncsz0f/iyql | src/main/haskell/Yql/Core/LocalFunctions/Exec.hs | gpl-3.0 | 5,430 | 0 | 17 | 2,237 | 682 | 367 | 315 | 56 | 6 |
-- Copyright (c) 2010, Diego Souza
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions are met:
--
-- * Redistributions of source code must retain the above copyright notice,
-- this list of conditions and the following disclaimer.
-- * Redistributions in binary form must reproduce the above copyright notice,
-- this list of conditions and the following disclaimer in the documentation
-- and/or other materials provided with the distribution.
-- * Neither the name of the <ORGANIZATION> nor the names of its contributors
-- may be used to endorse or promote products derived from this software
-- without specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
-- ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-- WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
-- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
-- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
-- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
-- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
-- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-- | Lexical analysis of yql statements
module Yql.Core.Lexer
( -- * Types
TokenT(..)
, Token(..)
-- * Lexical Analysis
, scan
, accept
-- * Other
, keywords
) where
import Text.ParserCombinators.Parsec
import Data.Char
-- | Tokens emitted by the lexer.
data TokenT = TkKey String -- ^ Keywords (e.g.: SELECT, DESC, OR, *)
| TkStr String -- ^ Quoted String (e.g.: 'foobar', "foobar")
| TkNum String -- ^ Numeric (e.g.: 1, 1.2, .09999)
| TkSym String -- ^ Any Symbol (e.g.: tables, colum names, etc.)
| TkEOF
deriving (Show,Eq)
-- | Relates a TokenT with the position in the stream, so that it can
-- feed the parser.
newtype Token = Token { unToken :: (SourcePos,TokenT) }
deriving (Show,Eq)
-- | Performs the lexical analysis of a string and returns the tokens
-- found.
scan :: GenParser Char st [Token]
scan = do skipMany space
t <- readToken
skipMany space
fmap (t:) (scan <|> (eof >> fmap (:[]) (mkToken TkEOF)))
where readToken = quoted <|> symbol
-- | Parses a token created by the lexer so that you can use to
-- perform syntactic analysis.
accept :: (TokenT -> Maybe a) -> GenParser Token st a
accept p = token (show.snd.unToken) (fst.unToken) (p.snd.unToken)
mkToken :: TokenT -> GenParser Char st Token
mkToken t = do p <- getPosition
return (Token (p,t))
symbol :: GenParser Char st Token
symbol = (fmap TkKey (try $ string ">=")
<|> fmap TkKey (try $ string "<=")
<|> fmap TkKey (try $ string "!=")
<|> fmap (TkKey.(:[])) (oneOf single)
<|> fmap mksym (many1 (satisfy sym))) >>= mkToken
where single = ",;()=><|"
sym c = (c `notElem` single) && not (isSpace c)
quoted :: GenParser Char st Token
quoted = do s <- oneOf "'\""
content <- loop s
mkToken (TkStr content)
where loop s = do c <- anyChar
case c
of '\\' -> (char s >> fmap (s:) (loop s))
<|> fmap (c:) (loop s)
x | s==x -> return []
| otherwise -> fmap (x:) (loop s)
keywords :: [String]
keywords = [ "SELECT"
, "UPDATE"
, "INSERT"
, "DELETE"
, "DESC"
, "USE"
, "AS"
, "SHOW"
, "TABLES"
, "OR"
, "AND"
, "IN"
, "ME"
, "FROM"
, "WHERE"
, "SET"
, "VALUES"
, "INTO"
, "MATCHES"
, "NULL"
, "NOT"
, "LIKE"
, "IS"
, "*"
, "OFFSET"
, "LIMIT"
]
mksym :: String -> TokenT
mksym sym | uSym `elem` keywords = TkKey uSym
| tkNum sym = TkNum sym
| otherwise = TkSym sym
where uSym = map toUpper sym
tkNum (x:xs) | x=='.' = not (null xs) && all isDigit xs
| otherwise = isDigit x && tkNum xs
tkNum [] = True
| rasata/iyql | src/main/haskell/Yql/Core/Lexer.hs | gpl-3.0 | 4,795 | 1 | 17 | 1,580 | 916 | 500 | 416 | 81 | 2 |
{-# 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.EC2.CancelConversionTask
-- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com>
-- 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 <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Cancels an active conversion task. The task can be the import of an instance
-- or volume. The action removes all artifacts of the conversion, including a
-- partially uploaded volume or instance. If the conversion is complete or is in
-- the process of transferring the final disk image, the command fails and
-- returns an exception.
--
-- For more information, see <http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/UploadingYourInstancesandVolumes.html Using the Command Line Tools to Import YourVirtual Machine to Amazon EC2> in the /Amazon Elastic Compute Cloud User Guidefor Linux/.
--
-- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-CancelConversionTask.html>
module Network.AWS.EC2.CancelConversionTask
(
-- * Request
CancelConversionTask
-- ** Request constructor
, cancelConversionTask
-- ** Request lenses
, cctConversionTaskId
, cctDryRun
, cctReasonMessage
-- * Response
, CancelConversionTaskResponse
-- ** Response constructor
, cancelConversionTaskResponse
) where
import Network.AWS.Prelude
import Network.AWS.Request.Query
import Network.AWS.EC2.Types
import qualified GHC.Exts
data CancelConversionTask = CancelConversionTask
{ _cctConversionTaskId :: Text
, _cctDryRun :: Maybe Bool
, _cctReasonMessage :: Maybe Text
} deriving (Eq, Ord, Read, Show)
-- | 'CancelConversionTask' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'cctConversionTaskId' @::@ 'Text'
--
-- * 'cctDryRun' @::@ 'Maybe' 'Bool'
--
-- * 'cctReasonMessage' @::@ 'Maybe' 'Text'
--
cancelConversionTask :: Text -- ^ 'cctConversionTaskId'
-> CancelConversionTask
cancelConversionTask p1 = CancelConversionTask
{ _cctConversionTaskId = p1
, _cctDryRun = Nothing
, _cctReasonMessage = Nothing
}
-- | The ID of the conversion task.
cctConversionTaskId :: Lens' CancelConversionTask Text
cctConversionTaskId =
lens _cctConversionTaskId (\s a -> s { _cctConversionTaskId = a })
cctDryRun :: Lens' CancelConversionTask (Maybe Bool)
cctDryRun = lens _cctDryRun (\s a -> s { _cctDryRun = a })
cctReasonMessage :: Lens' CancelConversionTask (Maybe Text)
cctReasonMessage = lens _cctReasonMessage (\s a -> s { _cctReasonMessage = a })
data CancelConversionTaskResponse = CancelConversionTaskResponse
deriving (Eq, Ord, Read, Show, Generic)
-- | 'CancelConversionTaskResponse' constructor.
cancelConversionTaskResponse :: CancelConversionTaskResponse
cancelConversionTaskResponse = CancelConversionTaskResponse
instance ToPath CancelConversionTask where
toPath = const "/"
instance ToQuery CancelConversionTask where
toQuery CancelConversionTask{..} = mconcat
[ "ConversionTaskId" =? _cctConversionTaskId
, "DryRun" =? _cctDryRun
, "ReasonMessage" =? _cctReasonMessage
]
instance ToHeaders CancelConversionTask
instance AWSRequest CancelConversionTask where
type Sv CancelConversionTask = EC2
type Rs CancelConversionTask = CancelConversionTaskResponse
request = post "CancelConversionTask"
response = nullResponse CancelConversionTaskResponse
| kim/amazonka | amazonka-ec2/gen/Network/AWS/EC2/CancelConversionTask.hs | mpl-2.0 | 4,257 | 0 | 9 | 872 | 471 | 286 | 185 | 58 | 1 |
module Graphics.ImageMagick.MagickCore.Gem
( convertHSBToRGB
, convertHSLToRGB
, convertHWBToRGB
, convertRGBToHSB
, convertRGBToHSL
, convertRGBToHWB
) where
import Foreign.Ptr (Ptr)
import Foreign.Storable (Storable, peek)
import Foreign.Marshal.Alloc (alloca)
import Control.Monad.IO.Class
import Control.Monad.Trans.Resource
import Graphics.ImageMagick.MagickCore.Types
import qualified Graphics.ImageMagick.MagickCore.FFI.Gem as F
with3 :: (Storable a, Storable b, Storable c) =>
(Ptr a -> Ptr b -> Ptr c -> IO ())
-> IO (a, b, c)
with3 f = alloca (\x -> alloca (\y -> alloca (\z -> do
f x y z
x' <- peek x
y' <- peek y
z' <- peek z
return (x',y',z')
)))
map3 :: (a -> b) -> (a, a, a) -> (b, b, b)
map3 f (a,b,c) = (f a, f b, f c)
convertHSBToRGB :: MonadResource m => Double -> Double -> Double -> m (Quantum, Quantum, Quantum)
convertHSBToRGB d1 d2 d3 = liftIO $ with3 (F.convertHSBToRGB (realToFrac d1) (realToFrac d2) (realToFrac d3))
convertHSLToRGB :: MonadResource m => Double -> Double -> Double -> m (Quantum, Quantum, Quantum)
convertHSLToRGB d1 d2 d3 = liftIO $ with3 (F.convertHSLToRGB (realToFrac d1) (realToFrac d2) (realToFrac d3))
convertHWBToRGB :: MonadResource m => Double -> Double -> Double -> m (Quantum, Quantum, Quantum)
convertHWBToRGB d1 d2 d3 = liftIO $ with3 (F.convertHWBToRGB (realToFrac d1) (realToFrac d2) (realToFrac d3))
convertRGBToHSB :: MonadResource m => Quantum -> Quantum -> Quantum -> m (Double, Double, Double)
convertRGBToHSB q1 q2 q3 = (liftIO $ with3 (F.convertRGBToHSB q1 q2 q3)) >>= return . (map3 realToFrac)
convertRGBToHSL :: MonadResource m => Quantum -> Quantum -> Quantum -> m (Double, Double, Double)
convertRGBToHSL q1 q2 q3 = liftIO $ with3 (F.convertRGBToHSL q1 q2 q3) >>= return . (map3 realToFrac)
convertRGBToHWB :: MonadResource m => Quantum -> Quantum -> Quantum -> m (Double, Double, Double)
convertRGBToHWB q1 q2 q3 = liftIO $ with3 (F.convertRGBToHSB q1 q2 q3) >>= return . (map3 realToFrac)
| flowbox-public/imagemagick | Graphics/ImageMagick/MagickCore/Gem.hs | apache-2.0 | 2,114 | 0 | 17 | 455 | 837 | 443 | 394 | 37 | 1 |
module Examples.PathCount
( pcExamples
) where
import Utils
import Algebra.Matrix
import Algebra.Semiring
import Policy.PathCount
pcExamples :: Int -> Matrix PathCount
pcExamples 0 = M (toArray 5 [ zero, PC 1, zero, zero, zero
, PC 1, zero, PC 1, PC 1, PC 1
, zero, PC 1, zero, PC 1, PC 1
, zero, PC 1, PC 1, zero, zero
, zero, PC 1, PC 1, zero, zero])
pcExamples 1 = M (toArray 5 [ zero, PC 1, PC 1, zero, PC 1
, zero, zero, PC 1, PC 1, zero
, zero, zero, zero, PC 1, PC 1
, zero, zero, zero, zero, PC 1
, zero, zero, zero, zero, zero])
pcExamples 2 = M (toArray 5 [ zero, PC 1, PC 1, zero, PC 1
, zero, zero, PC 1, PC 1, zero
, zero, zero, zero, zero, PC 1
, zero, zero, zero, zero, PC 1
, zero, zero, zero, zero, zero])
pcExamples _ = error "Undefined example of PathCount"
| sdynerow/Semirings-Library | haskell/Examples/PathCount.hs | apache-2.0 | 1,139 | 0 | 9 | 525 | 415 | 233 | 182 | 23 | 1 |
{-# OPTIONS_GHC -fglasgow-exts #-}
-----------------------------------------------------------------------------
-- |
-- Module : Control.Comonad
-- Copyright : (C) 2008 Edward Kmett
-- (C) 2004 Dave Menendez
-- License : BSD-style (see the file LICENSE)
--
-- Maintainer : Edward Kmett <ekmett@gmail.com>
-- Stability : experimental
-- Portability : portable
--
-- This module declares the 'Comonad' class
----------------------------------------------------------------------------
module Control.Comonad
( module Control.Functor.Pointed
, Comonad(..)
, liftW
, (=>>)
, (.>>)
, liftCtx
, mapW
, parallelW
, unfoldW
, sequenceW
) where
import Data.Monoid
import Control.Monad.Identity
import Control.Functor.Pointed
infixl 1 =>>, .>>
{-|
There are two ways to define a comonad:
I. Provide definitions for 'fmap', 'extract', and 'duplicate'
satisfying these laws:
> extract . duplicate == id
> fmap extract . duplicate == id
> duplicate . duplicate == fmap duplicate . duplicate
II. Provide definitions for 'extract' and 'extend'
satisfying these laws:
> extend extract == id
> extract . extend f == f
> extend f . extend g == extend (f . extend g)
('fmap' cannot be defaulted, but a comonad which defines
'extend' may simply set 'fmap' equal to 'liftW'.)
A comonad providing definitions for 'extend' /and/ 'duplicate',
must also satisfy these laws:
> extend f == fmap f . duplicate
> duplicate == extend id
> fmap f == extend (f . duplicate)
(The first two are the defaults for 'extend' and 'duplicate',
and the third is the definition of 'liftW'.)
-}
-- class Functor w => Extendable w where
-- duplicate :: w a -> w (w a)
-- extend :: (w a -> b) -> w a -> w b
-- extend f = fmap f . duplicate
-- duplicate = extend id
-- class (Copointed w, Extendable w) => Comonad w
-- instance (Copointed w, Extendable w) => Comonad w
class Copointed w => Comonad w where
duplicate :: w a -> w (w a)
extend :: (w a -> b) -> w a -> w b
extend f = fmap f . duplicate
duplicate = extend id
liftW :: Comonad w => (a -> b) -> w a -> w b
liftW f = extend (f . extract)
-- | 'extend' with the arguments swapped. Dual to '>>=' for monads.
(=>>) :: Comonad w => w a -> (w a -> b) -> w b
(=>>) = flip extend
-- | Injects a value into the comonad.
(.>>) :: Comonad w => w a -> b -> w b
w .>> b = extend (\_ -> b) w
-- | Transform a function into a comonadic action
liftCtx :: Comonad w => (a -> b) -> w a -> b
liftCtx f = extract . fmap f
mapW :: Comonad w => (w a -> b) -> w [a] -> [b]
mapW f w | null (extract w) = []
| otherwise = f (fmap head w) : mapW f (fmap tail w)
parallelW :: Comonad w => w [a] -> [w a]
parallelW w | null (extract w) = []
| otherwise = fmap head w : parallelW (fmap tail w)
unfoldW :: Comonad w => (w b -> (a,b)) -> w b -> [a]
unfoldW f w = fst (f w) : unfoldW f (w =>> snd . f)
-- | Converts a list of comonadic functions into a single function
-- returning a list of values
sequenceW :: Comonad w => [w a -> b] -> w a -> [b]
sequenceW [] _ = []
sequenceW (f:fs) w = f w : sequenceW fs w
instance Comonad Identity where
extend f x = Identity (f x)
duplicate = Identity
instance Comonad ((,)e) where
duplicate ~(e,a) = (e,(e,a))
-- the anonymous exponent comonad
instance Monoid m => Copointed ((->)m) where
extract f = f mempty
instance Monoid m => Comonad ((->)m) where
duplicate f m = f . mappend m
| urska19/MFP---Samodejno-racunanje-dvosmernih-preslikav | Control/Comonad.hs | apache-2.0 | 3,525 | 4 | 10 | 857 | 889 | 466 | 423 | 49 | 1 |
--------------------------------------------------------------------------------
-- | Get a user's last listened track on last.fm
{-# LANGUAGE OverloadedStrings #-}
module NumberSix.Handlers.LastFm
( handler
) where
--------------------------------------------------------------------------------
import Control.Applicative ((<$>))
import Control.Monad.Trans (liftIO)
import Data.Text (Text)
import Text.XmlHtml
import Text.XmlHtml.Cursor
--------------------------------------------------------------------------------
import NumberSix.Bang
import NumberSix.Irc
import NumberSix.Message
import NumberSix.Util.BitLy
import NumberSix.Util.Error
import NumberSix.Util.Http
--------------------------------------------------------------------------------
lastFm :: Text -> IO Text
lastFm query = do
result <- httpScrape Xml url id $ \cursor -> do
artist <- nodeText . current <$> findRec (byTagName "artist") cursor
title <- nodeText . current <$> findRec (byTagName "name") cursor
link <- nodeText . current <$> findRec (byTagName "url") cursor
return (artist, title, link)
case result of
Just (artist, title, link) -> textAndUrl
(query <> " listened to: " <> title <> " by " <> artist) link
_ -> randomError
where
url = "http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user="
<> urlEncode query <> "&api_key=87b8b81da496639cb5a295d78e5f8f4d"
--------------------------------------------------------------------------------
handler :: UninitializedHandler
handler = makeBangHandler "LastFm" ["!lastfm"] $ liftIO . lastFm
| itkovian/number-six | src/NumberSix/Handlers/LastFm.hs | bsd-3-clause | 1,788 | 0 | 16 | 407 | 331 | 180 | 151 | 29 | 2 |
module Paper.Graph(graphLog, graphCreate) where
import Data.List
import qualified Data.Map as Map
import Data.Ord
import System.Time
import System.Process.Extra
import Graphics.Google.Chart
graphLog :: FilePath -> [(String,Int)] -> IO ()
graphLog dest xs = do
t <- getClockTime
t <- toCalendarTime t
appendFile dest $ unlines [show (t,a,b) | (a,b) <- xs]
-- load the data
graphLoad :: FilePath -> [String] -> IO [(Date,String,Int)]
graphLoad src files = do
src <- readFile src
res <- return [(date a,b,c) | s <- lines src, not $ null s, let (a,b,c) = read s, b `elem` files]
return $ sortBy (comparing fst3) res
fst3 (x,_,_) = x
-- year, month (1 based), day (1 based)
type Date = (Int,Int,Int)
date :: CalendarTime -> Date
date t = (ctYear t, fromEnum (ctMonth t) + 1, ctDay t)
incDate :: Date -> Date
incDate (a,12,31) = (a+1,1,1)
incDate (a, b,31) = (a,b+1,1)
incDate (a, b, c) = (a,b,c+1)
totalCounts :: [FilePath] -> [(Date,FilePath,Int)] -> [(Date,Int)]
totalCounts _ [] = [((2000,1,1),0)]
totalCounts files xs = f (Map.fromList (zip files $ repeat 0)) xs steps
where
steps = iterate incDate $ fst3 (head xs)
f now xxs@((a,b,c):xs) (s:ss)
| a > s = dump s now : f now xxs ss
| otherwise = f (Map.insert b c now) xs (s:ss)
f now [] (s:ss) = [dump s now]
dump s mp = (s, sum $ Map.elems mp)
graphCreate :: FilePath -> FilePath -> [String] -> IO ()
graphCreate src dest files = do
xs <- graphLoad src files
let url = graphUrl $ totalCounts files xs
system $ "wget \"" ++ url ++ "\" -O \"" ++ dest ++ "\""
return ()
-- a list of date/count pairs
-- all the dates must be in order
graphUrl :: [(Date,Int)] -> String
graphUrl dat = chartURL $
setSize 400 300 $
setTitle "Word Count" $
setAxisTypes [AxisBottom,AxisLeft] $
setAxisLabels [xAxis, yAxis] $
setData (encodeDataSimple [map scale allY]) $
newLineChart
where
-- calculate the bounding box
minX = let (a,b,_) = fst (head dat) in (a,b,1)
maxX = let (a,b,_) = fst (last dat) in incDate (a,b,31)
allY = if length dat == 1 then replicate 2 $ snd $ head dat else map snd dat
minY = (minimum allY `div` 1000) * 1000
maxY = (maximum allY `div` 1000) * 1000 + 1000
-- calculate the axis
yAxis = map show [minY, minY+1000 .. maxY]
xAxis = map g $ takeWhile (<= maxX) $ iterate f minX
where
f (a,b,c) = incDate (a,b,31)
g (a,b,c) = take 3 (show (toEnum (b-1) :: Month)) ++ " " ++ show (a `mod` 100)
-- scaling (new range is 0 <= x <= 61)
scale y = (61 * (y - minY)) `div` (maxY - minY)
| saep/neil | src/Paper/Graph.hs | bsd-3-clause | 2,741 | 0 | 17 | 761 | 1,308 | 703 | 605 | 58 | 2 |
-----------------------------------------------------------------------------
--
-- Stg to C-- code generation
--
-- (c) The University of Glasgow 2004-2006
--
-----------------------------------------------------------------------------
{-# 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 StgCmm ( codeGen ) where
#define FAST_STRING_NOT_NEEDED
#include "HsVersions.h"
import StgCmmProf
import StgCmmMonad
import StgCmmEnv
import StgCmmBind
import StgCmmCon
import StgCmmLayout
import StgCmmUtils
import StgCmmClosure
import StgCmmHpc
import StgCmmTicky
import Cmm
import CLabel
import StgSyn
import DynFlags
import HscTypes
import CostCentre
import Id
import IdInfo
import Type
import DataCon
import Name
import TyCon
import Module
import ErrUtils
import Outputable
codeGen :: DynFlags
-> Module
-> [TyCon]
-> CollectedCCs -- (Local/global) cost-centres needing declaring/registering.
-> [(StgBinding,[(Id,[Id])])] -- Bindings to convert, with SRTs
-> HpcInfo
-> IO [CmmGroup] -- Output
codeGen dflags this_mod data_tycons
cost_centre_info stg_binds hpc_info
= do { showPass dflags "New CodeGen"
-- Why?
-- ; mapM_ (\x -> seq x (return ())) data_tycons
; code_stuff <- initC dflags this_mod $ do
{ cmm_binds <- mapM (getCmm . cgTopBinding dflags) stg_binds
; cmm_tycons <- mapM cgTyCon data_tycons
; cmm_init <- getCmm (mkModuleInit cost_centre_info
this_mod hpc_info)
; return (cmm_init : cmm_binds ++ cmm_tycons)
}
-- Put datatype_stuff after code_stuff, because the
-- datatype closure table (for enumeration types) to
-- (say) PrelBase_True_closure, which is defined in
-- code_stuff
-- N.B. returning '[Cmm]' and not 'Cmm' here makes it
-- possible for object splitting to split up the
-- pieces later.
-- Note [codegen-split-init] the cmm_init block must
-- come FIRST. This is because when -split-objs is on
-- we need to combine this block with its
-- initialisation routines; see Note
-- [pipeline-split-init].
; return code_stuff }
---------------------------------------------------------------
-- Top-level bindings
---------------------------------------------------------------
{- 'cgTopBinding' is only used for top-level bindings, since they need
to be allocated statically (not in the heap) and need to be labelled.
No unboxed bindings can happen at top level.
In the code below, the static bindings are accumulated in the
@MkCgState@, and transferred into the ``statics'' slot by @forkStatics@.
This is so that we can write the top level processing in a compositional
style, with the increasing static environment being plumbed as a state
variable. -}
cgTopBinding :: DynFlags -> (StgBinding,[(Id,[Id])]) -> FCode ()
cgTopBinding dflags (StgNonRec id rhs, _srts)
= do { id' <- maybeExternaliseId dflags id
; info <- cgTopRhs id' rhs
; addBindC (cg_id info) info -- Add the *un-externalised* Id to the envt,
-- so we find it when we look up occurrences
}
cgTopBinding dflags (StgRec pairs, _srts)
= do { let (bndrs, rhss) = unzip pairs
; bndrs' <- mapFCs (maybeExternaliseId dflags) bndrs
; let pairs' = zip bndrs' rhss
; fixC_(\ new_binds -> do
{ addBindsC new_binds
; mapFCs ( \ (b,e) -> cgTopRhs b e ) pairs' })
; return () }
-- Urgh! I tried moving the forkStatics call from the rhss of cgTopRhs
-- to enclose the listFCs in cgTopBinding, but that tickled the
-- statics "error" call in initC. I DON'T UNDERSTAND WHY!
cgTopRhs :: Id -> StgRhs -> FCode CgIdInfo
-- The Id is passed along for setting up a binding...
-- It's already been externalised if necessary
cgTopRhs bndr (StgRhsCon _cc con args)
= forkStatics (cgTopRhsCon bndr con args)
cgTopRhs bndr (StgRhsClosure cc bi fvs upd_flag srt args body)
= ASSERT(null fvs) -- There should be no free variables
setSRTLabel (mkSRTLabel (idName bndr) (idCafInfo bndr)) $
forkStatics (cgTopRhsClosure bndr cc bi upd_flag srt args body)
---------------------------------------------------------------
-- Module initialisation code
---------------------------------------------------------------
{- The module initialisation code looks like this, roughly:
FN(__stginit_Foo) {
JMP_(__stginit_Foo_1_p)
}
FN(__stginit_Foo_1_p) {
...
}
We have one version of the init code with a module version and the
'way' attached to it. The version number helps to catch cases
where modules are not compiled in dependency order before being
linked: if a module has been compiled since any modules which depend on
it, then the latter modules will refer to a different version in their
init blocks and a link error will ensue.
The 'way' suffix helps to catch cases where modules compiled in different
ways are linked together (eg. profiled and non-profiled).
We provide a plain, unadorned, version of the module init code
which just jumps to the version with the label and way attached. The
reason for this is that when using foreign exports, the caller of
startupHaskell() must supply the name of the init function for the "top"
module in the program, and we don't want to require that this name
has the version and way info appended to it.
We initialise the module tree by keeping a work-stack,
* pointed to by Sp
* that grows downward
* Sp points to the last occupied slot
-}
mkModuleInit
:: CollectedCCs -- cost centre info
-> Module
-> HpcInfo
-> FCode ()
mkModuleInit cost_centre_info this_mod hpc_info
= do { initHpc this_mod hpc_info
; initCostCentres cost_centre_info
-- For backwards compatibility: user code may refer to this
-- label for calling hs_add_root().
; emitDecl (CmmData Data (Statics (mkPlainModuleInitLabel this_mod) []))
}
---------------------------------------------------------------
-- Generating static stuff for algebraic data types
---------------------------------------------------------------
{- [These comments are rather out of date]
Macro Kind of constructor
CONST_INFO_TABLE@ Zero arity (no info -- compiler uses static closure)
CHARLIKE_INFO_TABLE Charlike (no info -- compiler indexes fixed array)
INTLIKE_INFO_TABLE Intlike; the one macro generates both info tbls
SPEC_INFO_TABLE SPECish, and bigger than or equal to MIN_UPD_SIZE
GEN_INFO_TABLE GENish (hence bigger than or equal to MIN_UPD_SIZE@)
Possible info tables for constructor con:
* _con_info:
Used for dynamically let(rec)-bound occurrences of
the constructor, and for updates. For constructors
which are int-like, char-like or nullary, when GC occurs,
the closure tries to get rid of itself.
* _static_info:
Static occurrences of the constructor macro: STATIC_INFO_TABLE.
For zero-arity constructors, \tr{con}, we NO LONGER generate a static closure;
it's place is taken by the top level defn of the constructor.
For charlike and intlike closures there is a fixed array of static
closures predeclared.
-}
cgTyCon :: TyCon -> FCode CmmGroup -- All constructors merged together
cgTyCon tycon
= do { constrs <- mapM (getCmm . cgDataCon) (tyConDataCons tycon)
-- Generate a table of static closures for an enumeration type
-- Put the table after the data constructor decls, because the
-- datatype closure table (for enumeration types)
-- to (say) PrelBase_$wTrue_closure, which is defined in code_stuff
-- Note that the closure pointers are tagged.
-- N.B. comment says to put table after constructor decls, but
-- code puts it before --- NR 16 Aug 2007
; extra <- cgEnumerationTyCon tycon
; return (concat (extra ++ constrs))
}
cgEnumerationTyCon :: TyCon -> FCode [CmmGroup]
cgEnumerationTyCon tycon
| isEnumerationTyCon tycon
= do { tbl <- getCmm $
emitRODataLits (mkLocalClosureTableLabel (tyConName tycon) NoCafRefs)
[ CmmLabelOff (mkLocalClosureLabel (dataConName con) NoCafRefs)
(tagForCon con)
| con <- tyConDataCons tycon]
; return [tbl] }
| otherwise
= return []
cgDataCon :: DataCon -> FCode ()
-- Generate the entry code, info tables, and (for niladic constructor)
-- the static closure, for a constructor.
cgDataCon data_con
= do { let
(tot_wds, -- #ptr_wds + #nonptr_wds
ptr_wds, -- #ptr_wds
arg_things) = mkVirtConstrOffsets arg_reps
nonptr_wds = tot_wds - ptr_wds
sta_info_tbl = mkDataConInfoTable data_con True ptr_wds nonptr_wds
dyn_info_tbl = mkDataConInfoTable data_con False ptr_wds nonptr_wds
emit_info info_tbl ticky_code
= emitClosureAndInfoTable info_tbl NativeDirectCall []
$ mk_code ticky_code
mk_code ticky_code
= -- NB: We don't set CC when entering data (WDP 94/06)
do { _ <- ticky_code
; ldvEnter (CmmReg nodeReg)
; tickyReturnOldCon (length arg_things)
; emitReturn [cmmOffsetB (CmmReg nodeReg)
(tagForCon data_con)] }
-- The case continuation code expects a tagged pointer
arg_reps :: [(PrimRep, Type)]
arg_reps = [(typePrimRep ty, ty) | ty <- dataConRepArgTys data_con]
-- Dynamic closure code for non-nullary constructors only
; whenC (not (isNullaryRepDataCon data_con))
(emit_info dyn_info_tbl tickyEnterDynCon)
-- Dynamic-Closure first, to reduce forward references
; emit_info sta_info_tbl tickyEnterStaticCon }
---------------------------------------------------------------
-- Stuff to support splitting
---------------------------------------------------------------
-- If we're splitting the object, we need to externalise all the
-- top-level names (and then make sure we only use the externalised
-- one in any C label we use which refers to this name).
maybeExternaliseId :: DynFlags -> Id -> FCode Id
maybeExternaliseId dflags id
| dopt Opt_SplitObjs dflags, -- Externalise the name for -split-objs
isInternalName name = do { mod <- getModuleName
; returnFC (setIdName id (externalise mod)) }
| otherwise = returnFC id
where
externalise mod = mkExternalName uniq mod new_occ loc
name = idName id
uniq = nameUnique name
new_occ = mkLocalOcc uniq (nameOccName name)
loc = nameSrcSpan name
-- We want to conjure up a name that can't clash with any
-- existing name. So we generate
-- Mod_$L243foo
-- where 243 is the unique.
| mcmaniac/ghc | compiler/codeGen/StgCmm.hs | bsd-3-clause | 11,092 | 78 | 16 | 2,546 | 1,466 | 798 | 668 | 124 | 1 |
{-# language MultiParamTypeClasses #-}
{-# language TemplateHaskell #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module OpenCV.Core.Types.Size
( Size
, IsSize(..)
, Size2i, Size2f, Size2d
) where
import "base" Data.Int ( Int32 )
import "base" Foreign.C.Types
import qualified "inline-c" Language.C.Inline as C
import qualified "inline-c-cpp" Language.C.Inline.Cpp as C ( using )
import "this" OpenCV.Internal.C.Inline ( openCvCtx )
import "this" OpenCV.Internal.C.Types
import "this" OpenCV.Internal.Core.Types.Size
import "this" OpenCV.Internal.Core.Types.Size.TH
--------------------------------------------------------------------------------
C.context openCvCtx
C.include "opencv2/core.hpp"
C.using "namespace cv"
mkSizeType "Size2i" ''Int32 "int32_t"
mkSizeType "Size2f" ''CFloat "float"
mkSizeType "Size2d" ''CDouble "double"
| lukexi/haskell-opencv | src/OpenCV/Core/Types/Size.hs | bsd-3-clause | 859 | 0 | 6 | 113 | 177 | 110 | 67 | -1 | -1 |
module Control.CP.FD.Solvers where
import qualified Control.CP.PriorityQueue as PriorityQueue
import qualified Data.Sequence
import Control.CP.ComposableTransformers
import Control.CP.SearchTree
import Control.CP.FD.FD
-- import Control.CP.FD.OvertonFD.Sugar
-- import Control.CP.FD.OvertonFD.OvertonFD
-- import Control.CP.FD.Gecode.CodegenSolver
--------------------------------------------------------------------------------
-- FORCE SOLVERS
--------------------------------------------------------------------------------
-- as_overtonfd :: Tree (FDWrapper OvertonFD) a -> Tree OvertonFD a
-- as_overtonfd = unwrap
--
-- as_gecode_codegen :: Tree (FDWrapper CodegenSolver) a -> Tree CodegenSolver a
-- as_gecode_codegen = unwrap
--
-- as_gen_gecode_codegen :: (FDExpr CodegenSolver -> Tree (FDWrapper CodegenSolver) a) -> (FDExpr CodegenSolver -> Tree CodegenSolver a)
-- as_gen_gecode_codegen f = (\x -> unwrap $ f x)
--
------------------------------------------------------------------------------
-- SEARCH STRATEGIES
------------------------------------------------------------------------------
dfs = []
bfs = Data.Sequence.empty
pfs :: Ord a => PriorityQueue.PriorityQueue a (a,b,c)
pfs = PriorityQueue.empty
nb :: Int -> CNodeBoundedST s a
nb = CNBST
db :: Int -> CDepthBoundedST s a
db = CDBST
bb :: NewBound s -> CBranchBoundST s a
bb = CBBST
sb :: Int -> CSolutionBoundST s a
sb = CSBST
fs :: CFirstSolutionST s a
fs = CFSST
it :: CIdentityCST s a
it = CIST
ra :: Int -> CRandomST s a
ra = CRST
ld :: Int -> CLimitedDiscrepancyST s a
ld = CLDST
| neothemachine/monadiccp | src/Control/CP/FD/Solvers.hs | bsd-3-clause | 1,572 | 0 | 7 | 201 | 257 | 153 | 104 | 26 | 1 |
{-|
/WARNING: This module represents the old version of the HLint API./
/It will be deleted in favour of "Language.Haskell.HLint3" in the next major version./
This module provides a library interface to HLint, strongly modelled on the command line interface.
-}
module Language.Haskell.HLint(module HLint) where
import HLint
| mpickering/hlint | src/Language/Haskell/HLint.hs | bsd-3-clause | 328 | 0 | 4 | 50 | 17 | 12 | 5 | 2 | 0 |
<?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="hr-HR">
<title>AdvFuzzer Add-On</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | thc202/zap-extensions | addOns/fuzz/src/main/javahelp/org/zaproxy/zap/extension/fuzz/resources/help_hr_HR/helpset_hr_HR.hs | apache-2.0 | 961 | 82 | 53 | 156 | 394 | 208 | 186 | -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="de-DE">
<title>DOM XSS Active Scan Rule | ZAP Extension</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | thc202/zap-extensions | addOns/domxss/src/main/javahelp/org/zaproxy/zap/extension/domxss/resources/help_de_DE/helpset_de_DE.hs | apache-2.0 | 985 | 83 | 52 | 162 | 402 | 212 | 190 | -1 | -1 |
module TupleIn1 where
f :: (a,b) -> a
f x@(b_1, b_2) = fst x
f x = fst x | SAdams601/HaRe | old/testing/introPattern/TupleIn1_TokOut.hs | bsd-3-clause | 74 | 0 | 7 | 20 | 50 | 28 | 22 | 4 | 1 |
{-# LANGUAGE FlexibleContexts, UndecidableInstances #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE EmptyDataDecls #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Database.Persist.Zookeeper.Store (
deleteRecursive
, BackendKey(..)
)where
import Database.Persist
import qualified Database.Persist.Sql as Sql
import qualified Database.Zookeeper as Z
import Data.Monoid
import qualified Data.Text as T
import Database.Persist.Zookeeper.Config
import Database.Persist.Zookeeper.Internal
import Database.Persist.Zookeeper.ZooUtil
import Control.Monad
import Control.Monad.Reader
import qualified Data.Aeson as A
import qualified Data.Aeson.Types as A
import Web.PathPieces (PathPiece (..))
-- | ToPathPiece is used to convert a key to/from text
instance PathPiece (BackendKey Z.Zookeeper) where
toPathPiece key = "z" <> (unZooKey key)
fromPathPiece keyText =
case T.uncons keyText of
Just ('z', prefixed) -> Just $ ZooKey prefixed
_ -> mzero
instance Sql.PersistFieldSql (BackendKey Z.Zookeeper) where
sqlType _ = Sql.SqlOther "doesn't make much sense for Zookeeper"
instance A.ToJSON (BackendKey Z.Zookeeper) where
toJSON (ZooKey key) = A.toJSON $ "z" <> key
instance A.FromJSON (BackendKey Z.Zookeeper) where
parseJSON v = A.modifyFailure ("Persistent: error loading Zookeeper conf: " ++) $
flip (A.withText "ZooKey") v $ \t ->
case T.uncons t of
Just ('z', prefixed) -> return $ ZooKey prefixed
_ -> (fail "Invalid json for zookey")
deleteRecursive :: (Monad m, MonadIO m) => String -> Action m ()
deleteRecursive dir = execZookeeper $ \zk -> zDeleteRecursive zk dir
instance PersistStore Z.Zookeeper where
newtype BackendKey Z.Zookeeper = ZooKey { unZooKey :: T.Text }
deriving (Show, Read, Eq, Ord, PersistField)
insert val = do
mUniqVal <- val2uniqkey val
case mUniqVal of
Just uniqVal -> do
let key = (uniqkey2key uniqVal)
execZookeeper $ \zk -> do
let dir = entity2path val
r <- zCreate zk dir (keyToTxt key) (Just (entity2bin val)) []
case r of
Right _ -> return $ Right $ key
-- Left Z.NodeExistsError -> return $ Right $ Nothing
Left v -> return $ Left v
Nothing -> do
let dir = entity2path val
str <- execZookeeper $ \zk -> do
zCreate zk dir "" (Just (entity2bin val)) [Z.Sequence]
return $ txtToKey str
insertKey key val = do
_ <- execZookeeper $ \zk -> do
let dir = entity2path val
zCreate zk dir (keyToTxt key) (Just (entity2bin val)) []
return ()
repsert key val = do
_ <- execZookeeper $ \zk -> do
let dir = entity2path val
zRepSert zk dir (keyToTxt key) (Just (entity2bin val))
return ()
replace key val = do
execZookeeper $ \zk -> do
let dir = entity2path val
_ <- zReplace zk dir (keyToTxt key) (Just (entity2bin val))
return $ Right ()
return ()
delete key = do
execZookeeper $ \zk -> do
let dir = key2path key
_ <- zDelete zk dir (keyToTxt key) Nothing
return $ Right ()
return ()
get key = do
r <- execZookeeper $ \zk -> do
let dir = key2path key
val <- zGet zk dir (keyToTxt key)
return $ Right val
case r of
(Left Z.NoNodeError) ->
return Nothing
(Left v) ->
fail $ show v
(Right (Just str,_sta)) -> do
return (bin2entity str)
(Right (Nothing,_stat)) -> do
fail $ "data is nothing"
update key valList = do
va <- get key
case va of
Nothing -> return ()
Just v ->
case updateEntity v valList of
Right v' ->
replace key v'
Left v' -> error $ show v'
| nakaji-dayo/persistent | persistent-zookeeper/Database/Persist/Zookeeper/Store.hs | mit | 3,995 | 0 | 22 | 1,153 | 1,287 | 641 | 646 | 105 | 1 |
{-# LANGUAGE MagicHash #-}
-----------------------------------------------------------------------------
--
-- GHCi Interactive debugging commands
--
-- Pepe Iborra (supported by Google SoC) 2006
--
-- ToDo: lots of violation of layering here. This module should
-- decide whether it is above the GHC API (import GHC and nothing
-- else) or below it.
--
-----------------------------------------------------------------------------
module Debugger (pprintClosureCommand, showTerm, pprTypeAndContents) where
import Linker
import RtClosureInspect
import GhcMonad
import HscTypes
import Id
import Name
import Var hiding ( varName )
import VarSet
import UniqSupply
import Type
import Kind
import GHC
import Outputable
import PprTyThing
import MonadUtils
import DynFlags
import Exception
import Control.Monad
import Data.List
import Data.Maybe
import Data.IORef
import GHC.Exts
-------------------------------------
-- | The :print & friends commands
-------------------------------------
pprintClosureCommand :: GhcMonad m => Bool -> Bool -> String -> m ()
pprintClosureCommand bindThings force str = do
tythings <- (catMaybes . concat) `liftM`
mapM (\w -> GHC.parseName w >>=
mapM GHC.lookupName)
(words str)
let ids = [id | AnId id <- tythings]
-- Obtain the terms and the recovered type information
(subst, terms) <- mapAccumLM go emptyTvSubst ids
-- Apply the substitutions obtained after recovering the types
modifySession $ \hsc_env ->
hsc_env{hsc_IC = substInteractiveContext (hsc_IC hsc_env) subst}
-- Finally, print the Terms
unqual <- GHC.getPrintUnqual
docterms <- mapM showTerm terms
dflags <- getDynFlags
liftIO $ (printOutputForUser dflags unqual . vcat)
(zipWith (\id docterm -> ppr id <+> char '=' <+> docterm)
ids
docterms)
where
-- Do the obtainTerm--bindSuspensions-computeSubstitution dance
go :: GhcMonad m => TvSubst -> Id -> m (TvSubst, Term)
go subst id = do
let id' = id `setIdType` substTy subst (idType id)
term_ <- GHC.obtainTermFromId maxBound force id'
term <- tidyTermTyVars term_
term' <- if bindThings &&
False == isUnliftedTypeKind (termType term)
then bindSuspensions term
else return term
-- Before leaving, we compare the type obtained to see if it's more specific
-- Then, we extract a substitution,
-- mapping the old tyvars to the reconstructed types.
let reconstructed_type = termType term
hsc_env <- getSession
case (improveRTTIType hsc_env (idType id) (reconstructed_type)) of
Nothing -> return (subst, term')
Just subst' -> do { traceOptIf Opt_D_dump_rtti
(fsep $ [text "RTTI Improvement for", ppr id,
text "is the substitution:" , ppr subst'])
; return (subst `unionTvSubst` subst', term')}
tidyTermTyVars :: GhcMonad m => Term -> m Term
tidyTermTyVars t =
withSession $ \hsc_env -> do
let env_tvs = tyThingsTyVars $ ic_tythings $ hsc_IC hsc_env
my_tvs = termTyVars t
tvs = env_tvs `minusVarSet` my_tvs
tyvarOccName = nameOccName . tyVarName
tidyEnv = (initTidyOccEnv (map tyvarOccName (varSetElems tvs))
, env_tvs `intersectVarSet` my_tvs)
return$ mapTermType (snd . tidyOpenType tidyEnv) t
-- | Give names, and bind in the interactive environment, to all the suspensions
-- included (inductively) in a term
bindSuspensions :: GhcMonad m => Term -> m Term
bindSuspensions t = do
hsc_env <- getSession
inScope <- GHC.getBindings
let ictxt = hsc_IC hsc_env
prefix = "_t"
alreadyUsedNames = map (occNameString . nameOccName . getName) inScope
availNames = map ((prefix++) . show) [(1::Int)..] \\ alreadyUsedNames
availNames_var <- liftIO $ newIORef availNames
(t', stuff) <- liftIO $ foldTerm (nameSuspensionsAndGetInfos availNames_var) t
let (names, tys, hvals) = unzip3 stuff
let ids = [ mkVanillaGlobal name ty
| (name,ty) <- zip names tys]
new_ic = extendInteractiveContext ictxt (map AnId ids)
liftIO $ extendLinkEnv (zip names hvals)
modifySession $ \_ -> hsc_env {hsc_IC = new_ic }
return t'
where
-- Processing suspensions. Give names and recopilate info
nameSuspensionsAndGetInfos :: IORef [String] ->
TermFold (IO (Term, [(Name,Type,HValue)]))
nameSuspensionsAndGetInfos freeNames = TermFold
{
fSuspension = doSuspension freeNames
, fTerm = \ty dc v tt -> do
tt' <- sequence tt
let (terms,names) = unzip tt'
return (Term ty dc v terms, concat names)
, fPrim = \ty n ->return (Prim ty n,[])
, fNewtypeWrap =
\ty dc t -> do
(term, names) <- t
return (NewtypeWrap ty dc term, names)
, fRefWrap = \ty t -> do
(term, names) <- t
return (RefWrap ty term, names)
}
doSuspension freeNames ct ty hval _name = do
name <- atomicModifyIORef freeNames (\x->(tail x, head x))
n <- newGrimName name
return (Suspension ct ty hval (Just n), [(n,ty,hval)])
-- A custom Term printer to enable the use of Show instances
showTerm :: GhcMonad m => Term -> m SDoc
showTerm term = do
dflags <- GHC.getSessionDynFlags
if gopt Opt_PrintEvldWithShow dflags
then cPprTerm (liftM2 (++) (\_y->[cPprShowable]) cPprTermBase) term
else cPprTerm cPprTermBase term
where
cPprShowable prec t@Term{ty=ty, val=val} =
if not (isFullyEvaluatedTerm t)
then return Nothing
else do
hsc_env <- getSession
dflags <- GHC.getSessionDynFlags
do
(new_env, bname) <- bindToFreshName hsc_env ty "showme"
setSession new_env
-- XXX: this tries to disable logging of errors
-- does this still do what it is intended to do
-- with the changed error handling and logging?
let noop_log _ _ _ _ _ = return ()
expr = "show " ++ showPpr dflags bname
_ <- GHC.setSessionDynFlags dflags{log_action=noop_log}
txt_ <- withExtendedLinkEnv [(bname, val)]
(GHC.compileExpr expr)
let myprec = 10 -- application precedence. TODO Infix constructors
let txt = unsafeCoerce# txt_
if not (null txt) then
return $ Just $ cparen (prec >= myprec && needsParens txt)
(text txt)
else return Nothing
`gfinally` do
setSession hsc_env
GHC.setSessionDynFlags dflags
cPprShowable prec NewtypeWrap{ty=new_ty,wrapped_term=t} =
cPprShowable prec t{ty=new_ty}
cPprShowable _ _ = return Nothing
needsParens ('"':_) = False -- some simple heuristics to see whether parens
-- are redundant in an arbitrary Show output
needsParens ('(':_) = False
needsParens txt = ' ' `elem` txt
bindToFreshName hsc_env ty userName = do
name <- newGrimName userName
let id = AnId $ mkVanillaGlobal name ty
new_ic = extendInteractiveContext (hsc_IC hsc_env) [id]
return (hsc_env {hsc_IC = new_ic }, name)
-- Create new uniques and give them sequentially numbered names
newGrimName :: MonadIO m => String -> m Name
newGrimName userName = do
us <- liftIO $ mkSplitUniqSupply 'b'
let unique = uniqFromSupply us
occname = mkOccName varName userName
name = mkInternalName unique occname noSrcSpan
return name
pprTypeAndContents :: GhcMonad m => Id -> m SDoc
pprTypeAndContents id = do
dflags <- GHC.getSessionDynFlags
let pcontents = gopt Opt_PrintBindContents dflags
pprdId = (PprTyThing.pprTyThing . AnId) id
if pcontents
then do
let depthBound = 100
-- If the value is an exception, make sure we catch it and
-- show the exception, rather than propagating the exception out.
e_term <- gtry $ GHC.obtainTermFromId depthBound False id
docs_term <- case e_term of
Right term -> showTerm term
Left exn -> return (text "*** Exception:" <+>
text (show (exn :: SomeException)))
return $ pprdId <+> equals <+> docs_term
else return pprdId
--------------------------------------------------------------
-- Utils
traceOptIf :: GhcMonad m => DumpFlag -> SDoc -> m ()
traceOptIf flag doc = do
dflags <- GHC.getSessionDynFlags
when (dopt flag dflags) $ liftIO $ printInfoForUser dflags alwaysQualify doc
| holzensp/ghc | compiler/ghci/Debugger.hs | bsd-3-clause | 9,305 | 0 | 20 | 2,975 | 2,290 | 1,169 | 1,121 | 171 | 8 |
{-# LANGUAGE TypeFamilies, ConstraintKinds #-}
module Foo where
import GHC.Exts
f :: F [a] => a -> Bool
f x = x == x
type family F a :: Constraint
type instance F [a] = (Show a, (Show a, (Show a, (Show a, (Show a,
Show a, (Show a, (Show a, (Show a, (Show a, Eq a)))))))))
| olsner/ghc | testsuite/tests/polykinds/T12885.hs | bsd-3-clause | 300 | 0 | 14 | 85 | 153 | 86 | 67 | -1 | -1 |
{-# LANGUAGE TemplateHaskell, GeneralizedNewtypeDeriving #-}
module AStarSearchTest where
import AStarSearch
import Data.Hashable (Hashable)
import Data.List (foldl')
import Data.Maybe (fromJust, fromMaybe)
import Data.Sequence ((|>))
import Test.QuickCheck
import Test.QuickCheck.All
import qualified Data.HashMap.Strict as Map
import qualified Data.Sequence as Seq
-- We use A* search to find the shortest path (path with least number of moves) of a knight
-- from a start square to a goal square on a chess board.
newtype Square = Square (Int, Int) deriving (Eq, Hashable, Show)
type Path = [Square]
-- Finds the next squares a knight can move to from a given square
nextKnightPos (Square (x, y)) =
map Square . filter isValidMove . map (\(dx, dy) -> (x + dx, y + dy)) $ moves
where
moves = [(1,2), (1,-2), (-1,2), (-1,-2), (2,1), (2,-1), (-2,1), (-2,-1)]
isValidMove (x, y) = and [x > 0, x < 9, y > 0, y < 9]
-- Creates the heuristic function given a goal square. The heuristic used is half of the max of
-- the distance between x coordinates and the distance between y coordinates.
mkHeuristic (Square (gx, gy)) (Square (x, y)) = max (abs (x-gx)) (abs (y-gy)) `div` 2
-- Finds the shortest path of the knight, returns empty path if the goal is invalid
knightsShortestPath :: Square -> Square -> Path
knightsShortestPath initSq goalSq =
snd . fromMaybe (0, [])
$ astarSearch initSq (== goalSq) (flip zip (repeat 1) . nextKnightPos) (mkHeuristic goalSq)
-- Finds the shortest path using breadth first search. Used for checking if the path returned by
-- A* search is indeed shortest.
bfs :: Square -> Square -> Path
bfs startSq goalSq =
bfs' goalSq (Map.singleton startSq noSuchSq) (Seq.singleton startSq)
where
noSuchSq = Square (-1, -1)
bfs' goalSq tracks open = let
(first, rest) = Seq.splitAt 1 open
currentSq = Seq.index first 0
in if currentSq == goalSq
then consPath currentSq
else let
nextSqs = filter (not . flip Map.member tracks) . nextKnightPos $ currentSq
tracks' = foldl' (\t s -> Map.insert s currentSq t) tracks nextSqs
in bfs' goalSq tracks' (foldl (|>) rest nextSqs)
where
consPath square =
if Map.member square tracks
then consPath (fromJust . Map.lookup square $ tracks) ++ [square]
else []
-- Setup to generate arbitrary squares for testing
instance Arbitrary Square where
arbitrary = do
x <- choose (1, 8)
y <- choose (1, 8)
return $ Square (x, y)
-- Properties to test
prop_path_starts_with_start_square startSq goalSq =
head (knightsShortestPath startSq goalSq) == startSq
prop_path_ends_with_goal_square startSq goalSq =
last (knightsShortestPath startSq goalSq) == goalSq
prop_path_consists_of_valid_knights_moves startSq goalSq =
let path = knightsShortestPath startSq goalSq
in all isValidKnightsMove $ zip path (tail path)
where
isValidKnightsMove (sqFrom, sqTo) = sqTo `elem` nextKnightPos sqFrom
prop_no_path_for_invalid_goal startSq =
knightsShortestPath startSq (Square (-1, -1)) == []
prop_path_is_shortest startSq goalSq =
length (knightsShortestPath startSq goalSq) == length (bfs startSq goalSq)
-- Tests all the properties 1000 times each
testAllProps = $forAllProperties $ quickCheckWithResult (stdArgs {maxSuccess = 1000})
-- main function runs the tests. Type `runhaskell AStarSearch_test.hs` on command line to run the tests.
main = testAllProps >> return ()
| warreee/Algorithm-Implementations | A_Star_Search/Haskell/abhin4v/AStarSearch_test.hs | mit | 3,494 | 0 | 20 | 697 | 1,050 | 572 | 478 | 58 | 3 |
module PutJSON where
import Data.List (intercalate)
import SimpleJSON
renderJValue :: JValue -> String
renderJValue (JString s) = show s
renderJValue (JNumber n) = show n
renderJValue (JBool True) = "true"
renderJValue (JBool False) = "false"
renderJValue JNull = "null"
renderJValue (JObject o) = "{" ++ pairs o ++ "}" where
pairs [] = ""
pairs ps = intercalate ", " (map renderPair ps)
renderPair (k, v) = show k ++ ": " ++ renderJValue v
renderJValue (JArray a) = "[" ++ values a ++ "]" where
values [] = ""
values vs = intercalate ", " (map renderJValue vs)
putJValue :: JValue -> IO ()
putJValue v = putStrLn (renderJValue v)
| pauldoo/scratch | RealWorldHaskell/ch05/PutJSON.hs | isc | 678 | 0 | 9 | 158 | 271 | 135 | 136 | 18 | 3 |
{-# LANGUAGE QuasiQuotes #-}
import Text.Printf
import Text.RawString.QQ
import Text.Trifecta
import Control.Applicative
import Data.List
type Year = Integer
type Month = Integer
type Day = Integer
newtype Date = Date (Year,Month,Day)
newtype Time = Time Integer
data Activity = Activity Time String
data OneDay = OneDay Date [Activity]
newtype Log = Log [OneDay]
parseComment :: Parser ()
parseComment = char '-' >> char '-' >> skipMany (notChar '\n') <* char '\n'
parseDate :: Parser Date
parseDate = do
_ <- string "# "
year <- natural
_ <- char '-'
mon <- natural
_ <- char '-'
day <- natural
return $ Date (year,mon,day)
parseTime :: Parser Time
parseTime = do
h <- count 2 digit
_ <- char ':'
m <- count 2 digit
let h' = read h
m' = read m
if h' > 23 then fail "hour out of range" else
if m' > 59 then fail "minute out of range" else
return $ Time $ (h'*60) + m'
stop :: Parser a
stop = unexpected "stop"
skipEOL :: Parser ()
skipEOL = skipMany (oneOf "\n")
skipComments :: Parser ()
skipComments =
skipMany (do _ <- try (char '-' >> char '-')
skipMany (noneOf "\n")
skipEOL)
parseActivity' :: Parser Activity
parseActivity' = do
t <- parseTime
_ <- char ' '
act <- some (noneOf "\n")
return $ Activity t act
parseActivity :: Parser Activity
parseActivity = do
t <- parseTime
_ <- char ' '
act <- some (noneOf "\n") <?> "act"
skipEOL
-- notFollowedBy (skipComments <|> skipEOL) <?> "foo"
return $ Activity t act
skipWhitespace :: Parser ()
--skipWhitespace = skipMany (char ' ' <|> char '\n')
skipWhitespace = skipMany (oneOf " \n")
parseLines :: Parser [String]
parseLines = many $ many (noneOf "\n") <* char '\n'
parseOneDay :: Parser OneDay
parseOneDay = do
skipWhitespace <?> "whitespace"
skipComments <?> "comments"
d <- parseDate <* skipComments <?> "date"
as <- many parseActivity <?> "activities"
return $ OneDay d as
parseLog :: Parser Log
parseLog = Log <$> many parseOneDay
instance Show Date where
show (Date (y,m,d)) =
printf "# %04d-%02d-%02d\n" y m d
instance Show OneDay where
show (OneDay date activities) =
show date ++ "\n" ++ concatMap show activities
instance Show Activity where
show (Activity ts note) =
show ts ++ " " ++ note ++ "\n"
instance Show Time where
show (Time minute) = printf "%02d:%02d" h m
where (h,m) = divMod minute 60
instance Show Log where
show (Log xs) = concatMap ((++ "\n") . show) xs
sampleLog :: String
sampleLog = [r|
-- wheee a comment
# 2025-02-05
08:00 Breakfast
09:00 Sanitizing moisture collector
11:00 Exercising in high-grav gym
12:00 Lunch
13:00 Programming
17:00 Commuting home in rover
17:30 R&R
19:00 Dinner
21:00 Shower
21:15 Read
22:00 Sleep
# 2025-02-07 -- dates not nececessarily sequential
08:00 Breakfast -- should I try skippin bfast?
09:00 Bumped head, passed out
13:36 Wake up, headache
13:37 Go to medbay
13:40 Patch self up
13:45 Commute home for rest
14:15 Read
21:00 Dinner
21:15 Read
22:00 Sleep
a|]
sampleData :: Result Log
sampleData = parseString parseLog mempty sampleLog
-- won't work because parser discards comments
parseLogTest s = case parseString parseLog mempty s of
Failure _ -> False
Success l -> show l == s
com :: Parser Char
com = char '-' >> char '-' >> many (notChar '\n') >> char '\n'
com1 = try com <|> anyChar
com2 = many com1
comment :: Parser Char
comment = do
char '-'
char '-'
many (notChar '\n')
char '\n'
item :: Parser Char
item = try comment <|> anyChar
mySatisfy :: (Char -> Bool) -> Parser Char
mySatisfy f = do
c <- item
if f c then return c else fail "mySatisfy"
myChar :: Char -> Parser Char
myChar c = mySatisfy (== c)
| JustinUnger/haskell-book | ch24/ch24-log-parser.hs | mit | 3,832 | 3 | 13 | 929 | 1,214 | 598 | 616 | 109 | 3 |
module Data.Breadcrumbs.Caterpillar where
data Buffer a = Buffer !Int !Int [a] [a]
empty :: Int -> Buffer a
push :: a -> Buffer a -> Buffer a
bufferToList :: Buffer a -> [a]
empty n = Buffer n n [] []
push a (Buffer n 0 new _) = Buffer n (n - 1) [a] new
push a (Buffer n m new old) = Buffer n (m - 1) (a : new) old
bufferToList (Buffer _ 0 new _) = new
bufferToList (Buffer n _ new old) = take n (new ++ old)
len (Buffer _ _ new old) = length new + length old
| Lysxia/breadcrumbs | Data/Breadcrumbs/Caterpillar.hs | mit | 466 | 0 | 7 | 111 | 266 | 135 | 131 | 15 | 1 |
module Main where
-- only pythagorean triplet that a + b + c == 1000
triplet :: [(Float, Float)] -> Float
triple [] = 0
triplet (pair:xs)
| (fst pair) + (snd pair) + z == 1000 = (fst pair) * (snd pair) * z
| otherwise = triplet xs
where
z = sqrt((fst pair)^2 + (snd pair)^2)
main =
print(triplet [ (x, y) | x <- [1..1000], y <- [x+1..1000] ])
| tijko/Project-Euler | haskell_1-10/Euler_9.hs | mit | 369 | 0 | 13 | 98 | 200 | 105 | 95 | 9 | 1 |
import Data.Map (Map)
import qualified Data.Map as Map
-- fe for feedback
-- st for state
-- ac for action
-- qval for value of q
inf=1e9
learningRate=0.1
discountFactor=0.1
q= Map.empty
getQ::st->ac->qval
getQ state action=q Map.! (state,action)
greater::(Ord a)=>a->a->a
greater x y = if x>y then x else y
getMaxActionVal::(Ord qval)=> st-> [ac]->qval
getMaxActionVal newState actions=let x=map (getQ newState) actions
in foldl greater -inf x
--giveFeedback::fe->st->[ac]->st->ac->Bool
--giveFeedback feedback newState actions lastState lastAction=
-- let maxim=getMaxActionVal newState actions
-- lastQ=q Map.! (lastState,lastAction)
-- newQ=lastQ+learningRate*(feedback + discountFactor* maxim - lastQ)
-- Map.insert (lastState,lastAction) newQ q
-- in True
giveFeedback::fe->st->[ac]->st->ac->qval
giveFeedback feedback newState actions lastState lastAction=newQ
where maxim=getMaxActionVal newState actions
lastQ=q Map.! (lastState,lastAction)
newQ=lastQ+learningRate*(feedback + discountFactor* maxim - lastQ)
res=Map.insert (lastState,lastAction) newQ q
checkZero::st->[ac]->ac
checkZero state [] = -1
checkZero state (action:rest) = if q Map.! (state,action) ==0 then action
else checkZero state rest
findAction::st->[ac]->qval->ac
findAction state [] val=-1
findAction state (action:rest) val=if q Map.! action == val then action
else findAction state rest val
getAction::st->[ac]->ac
getAction state actions=if x \= -1 then x else y
where x=checkZero state actions
z=map (getQ state) actions
yval=foldl greater -inf z
y=findAction state actions yval
| arnabgho/RLearnHaskell | tests/QLearnRef.hs | mit | 1,636 | 6 | 11 | 264 | 588 | 312 | 276 | -1 | -1 |
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TemplateHaskell #-}
module Text.Shakespeare.HamletSpec (spec) where
import HamletTestTypes (ARecord(..))
import Test.HUnit hiding (Test)
import Test.Hspec hiding (Arg)
import Prelude hiding (reverse)
import Text.Hamlet
import Text.Hamlet.RT
import Data.List (intercalate)
import qualified Data.Text.Lazy as T
import qualified Data.List
import qualified Data.List as L
import Data.Text (Text, pack, unpack)
import Data.Monoid (mappend)
import qualified Data.Set as Set
import qualified Text.Blaze.Html.Renderer.Text
import Text.Blaze.Html (toHtml)
import Text.Blaze.Internal (preEscapedString)
import Text.Blaze
spec = do
describe "hamlet" $ do
it "empty" caseEmpty
it "static" caseStatic
it "tag" caseTag
it "var" caseVar
it "var chain " caseVarChain
it "url" caseUrl
it "url chain " caseUrlChain
it "embed" caseEmbed
it "embed chain " caseEmbedChain
it "if" caseIf
it "if chain " caseIfChain
it "else" caseElse
it "else chain " caseElseChain
it "elseif" caseElseIf
it "elseif chain " caseElseIfChain
it "list" caseList
it "list chain" caseListChain
it "with" caseWith
it "with multi" caseWithMulti
it "with chain" caseWithChain
it "with comma string" caseWithCommaString
it "with multi scope" caseWithMultiBindingScope
it "script not empty" caseScriptNotEmpty
it "meta empty" caseMetaEmpty
it "input empty" caseInputEmpty
it "multiple classes" caseMultiClass
it "attrib order" caseAttribOrder
it "nothing" caseNothing
it "nothing chain " caseNothingChain
it "just" caseJust
it "just chain " caseJustChain
it "constructor" caseConstructor
it "url + params" caseUrlParams
it "escape" caseEscape
it "empty statement list" caseEmptyStatementList
it "attribute conditionals" caseAttribCond
it "non-ascii" caseNonAscii
it "maybe function" caseMaybeFunction
it "trailing dollar sign" caseTrailingDollarSign
it "non leading percent sign" caseNonLeadingPercent
it "quoted attributes" caseQuotedAttribs
it "spaced derefs" caseSpacedDerefs
it "attrib vars" caseAttribVars
it "strings and html" caseStringsAndHtml
it "nesting" caseNesting
it "trailing space" caseTrailingSpace
it "currency symbols" caseCurrency
it "external" caseExternal
it "parens" caseParens
it "hamlet literals" caseHamletLiterals
it "hamlet' and xhamlet'" caseHamlet'
it "hamlet tuple" caseTuple
it "complex pattern" caseComplex
it "record pattern" caseRecord
it "record wildcard pattern #1" caseRecordWildCard
it "record wildcard pattern #2" caseRecordWildCard1
it "comments" $ do
-- FIXME reconsider Hamlet comment syntax?
helper "" [hamlet|$# this is a comment
$# another comment
$#a third one|]
it "ignores a blank line" $ do
helper "<p>foo</p>\n" [hamlet|
<p>
foo
|]
it "angle bracket syntax" $
helper "<p class=\"foo\" height=\"100\"><span id=\"bar\" width=\"50\">HELLO</span></p>"
[hamlet|
$newline never
<p.foo height="100">
<span #bar width=50>HELLO
|]
it "hamlet module names" $ do
let foo = "foo"
helper "oof oof 3.14 -5"
[hamlet|
$newline never
#{Data.List.reverse foo} #
#{L.reverse foo} #
#{show 3.14} #{show -5}|]
it "single dollar at and caret" $ do
helper "$@^" [hamlet|\$@^|]
helper "#{@{^{" [hamlet|#\{@\{^\{|]
it "dollar operator" $ do
let val = (1, (2, 3))
helper "2" [hamlet|#{ show $ fst $ snd val }|]
helper "2" [hamlet|#{ show $ fst $ snd $ val}|]
it "in a row" $ do
helper "1" [hamlet|#{ show $ const 1 2 }|]
it "embedded slash" $ do
helper "///" [hamlet|///|]
{- compile-time error
it "tag with slash" $ do
helper "" [hamlet|
<p>
Text
</p>
|]
-}
it "string literals" $ do
helper "string" [hamlet|#{"string"}|]
helper "string" [hamlet|#{id "string"}|]
helper "gnirts" [hamlet|#{L.reverse $ id "string"}|]
helper "str"ing" [hamlet|#{"str\"ing"}|]
helper "str<ing" [hamlet|#{"str<ing"}|]
it "interpolated operators" $ do
helper "3" [hamlet|#{show $ (+) 1 2}|]
helper "6" [hamlet|#{show $ sum $ (:) 1 ((:) 2 $ return 3)}|]
it "HTML comments" $ do
helper "<p>1</p><p>2 not ignored</p>" [hamlet|
$newline never
<p>1
<!-- ignored comment -->
<p>
2
<!-- ignored --> not ignored<!-- ignored -->
|]
it "Keeps SSI includes" $
helper "<!--# SSI -->" [hamlet|<!--# SSI -->|]
it "nested maybes" $ do
let muser = Just "User" :: Maybe String
mprof = Nothing :: Maybe Int
m3 = Nothing :: Maybe String
helper "justnothing" [hamlet|
$maybe user <- muser
$maybe profile <- mprof
First two are Just
$maybe desc <- m3
\ and left us a description:
<p>#{desc}
$nothing
and has left us no description.
$nothing
justnothing
$nothing
<h1>No such Person exists.
|]
it "maybe with qualified constructor" $ do
helper "5" [hamlet|
$maybe HamletTestTypes.ARecord x y <- Just $ ARecord 5 True
\#{x}
|]
it "record with qualified constructor" $ do
helper "5" [hamlet|
$maybe HamletTestTypes.ARecord {..} <- Just $ ARecord 5 True
\#{field1}
|]
it "conditional class" $ do
helper "<p class=\"current\"></p>\n"
[hamlet|<p :False:.ignored :True:.current>|]
helper "<p class=\"1 3 2 4\"></p>\n"
[hamlet|<p :True:.1 :True:class=2 :False:.a :False:class=b .3 class=4>|]
helper "<p class=\"foo bar baz\"></p>\n"
[hamlet|<p class=foo class=bar class=baz>|]
it "forall on Foldable" $ do
let set = Set.fromList [1..5 :: Int]
helper "12345" [hamlet|
$forall x <- set
#{x}
|]
it "non-poly HTML" $ do
helperHtml "<h1>HELLO WORLD</h1>\n" [shamlet|
<h1>HELLO WORLD
|]
helperHtml "<h1>HELLO WORLD</h1>\n" $(shamletFile "test/hamlets/nonpolyhtml.hamlet")
helper "<h1>HELLO WORLD</h1>\n" $(hamletFileReload "test/hamlets/nonpolyhtml.hamlet")
it "non-poly Hamlet" $ do
let embed = [hamlet|<p>EMBEDDED|]
helper "<h1>url</h1>\n<p>EMBEDDED</p>\n" [hamlet|
<h1>@{Home}
^{embed}
|]
helper "<h1>url</h1>\n" $(hamletFile "test/hamlets/nonpolyhamlet.hamlet")
helper "<h1>url</h1>\n" $(hamletFileReload "test/hamlets/nonpolyhamlet.hamlet")
it "non-poly IHamlet" $ do
let embed = [ihamlet|<p>EMBEDDED|]
ihelper "<h1>Adios</h1>\n<p>EMBEDDED</p>\n" [ihamlet|
<h1>_{Goodbye}
^{embed}
|]
ihelper "<h1>Hola</h1>\n" $(ihamletFile "test/hamlets/nonpolyihamlet.hamlet")
ihelper "<h1>Hola</h1>\n" $(ihamletFileReload "test/hamlets/nonpolyihamlet.hamlet")
it "pattern-match tuples: forall" $ do
let people = [("Michael", 26), ("Miriam", 25)]
helper "<dl><dt>Michael</dt><dd>26</dd><dt>Miriam</dt><dd>25</dd></dl>" [hamlet|
$newline never
<dl>
$forall (name, age) <- people
<dt>#{name}
<dd>#{show age}
|]
it "pattern-match tuples: maybe" $ do
let people = Just ("Michael", 26)
helper "<dl><dt>Michael</dt><dd>26</dd></dl>" [hamlet|
$newline never
<dl>
$maybe (name, age) <- people
<dt>#{name}
<dd>#{show age}
|]
it "pattern-match tuples: with" $ do
let people = ("Michael", 26)
helper "<dl><dt>Michael</dt><dd>26</dd></dl>" [hamlet|
$newline never
<dl>
$with (name, age) <- people
<dt>#{name}
<dd>#{show age}
|]
it "list syntax for interpolation" $ do
helper "<ul><li>1</li><li>2</li><li>3</li></ul>" [hamlet|
$newline never
<ul>
$forall num <- [1, 2, 3]
<li>#{show num}
|]
it "infix operators" $
helper "5" [hamlet|#{show $ (4 + 5) - (2 + 2)}|]
it "infix operators with parens" $
helper "5" [hamlet|#{show ((+) 1 1 + 3)}|]
it "doctypes" $ helper "<!DOCTYPE html>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n" [hamlet|
$newline never
$doctype 5
$doctype strict
|]
it "case on Maybe" $
let nothing = Nothing
justTrue = Just True
in helper "<br><br><br><br>" [hamlet|
$newline never
$case nothing
$of Just val
$of Nothing
<br>
$case justTrue
$of Just val
$if val
<br>
$of Nothing
$case (Just $ not False)
$of Nothing
$of Just val
$if val
<br>
$case Nothing
$of Just val
$of _
<br>
|]
it "case on Url" $
let url1 = Home
url2 = Sub SubUrl
in helper "<br>\n<br>\n" [hamlet|
$newline always
$case url1
$of Home
<br>
$of _
$case url2
$of Sub sub
$case sub
$of SubUrl
<br>
$of Home
|]
it "pattern-match constructors: forall" $ do
let people = [Pair "Michael" 26, Pair "Miriam" 25]
helper "<dl><dt>Michael</dt><dd>26</dd><dt>Miriam</dt><dd>25</dd></dl>" [hamlet|
$newline text
<dl>
$forall Pair name age <- people
<dt>#{name}
<dd>#{show age}
|]
it "pattern-match constructors: maybe" $ do
let people = Just $ Pair "Michael" 26
helper "<dl><dt>Michael</dt><dd>26</dd></dl>" [hamlet|
$newline text
<dl>
$maybe Pair name age <- people
<dt>#{name}
<dd>#{show age}
|]
it "pattern-match constructors: with" $ do
let people = Pair "Michael" 26
helper "<dl><dt>Michael</dt><dd>26</dd></dl>" [hamlet|
$newline text
<dl>
$with Pair name age <- people
<dt>#{name}
<dd>#{show age}
|]
it "multiline tags" $ helper
"<foo bar=\"baz\" bin=\"bin\">content</foo>\n" [hamlet|
<foo bar=baz
bin=bin>content
|]
it "*{...} attributes" $
let attrs = [("bar", "baz"), ("bin", "<>\"&")] in helper
"<foo bar=\"baz\" bin=\"<>"&\">content</foo>\n" [hamlet|
<foo *{attrs}>content
|]
it "blank attr values" $ helper
"<foo bar=\"\" baz bin=\"\"></foo>\n"
[hamlet|<foo bar="" baz bin=>|]
it "greater than in attr" $ helper
"<button data-bind=\"enable: someFunction() > 5\">hello</button>\n"
[hamlet|<button data-bind="enable: someFunction() > 5">hello|]
it "normal doctype" $ helper
"<!DOCTYPE html>\n"
[hamlet|<!DOCTYPE html>|]
it "newline style" $ helper
"<p>foo</p>\n<pre>bar\nbaz\nbin</pre>\n"
[hamlet|
$newline always
<p>foo
<pre>
bar
baz
bin
|]
it "avoid newlines" $ helper
"<p>foo</p><pre>barbazbin</pre>"
[hamlet|
$newline always
<p>foo#
<pre>#
bar#
baz#
bin#
|]
it "manual linebreaks" $ helper
"<p>foo</p><pre>bar\nbaz\nbin</pre>"
[hamlet|
$newline never
<p>foo
<pre>
bar
\
baz
\
bin
|]
it "indented newline" $ helper
"<p>foo</p><pre>bar\nbaz\nbin</pre>"
[hamlet|
$newline never
<p>foo
<pre>
bar
\
baz
\
bin
|]
it "case underscore" $
let num = 3
in helper "<p>Many</p>\n" [hamlet|
$case num
$of 1
<p>1
$of 2
<p>2
$of _
<p>Many
|]
it "optional and missing classes" $
helper "<i>foo</i>\n" [hamlet|<i :False:.not-present>foo|]
it "multiple optional and missing classes" $
helper "<i>foo</i>\n" [hamlet|<i :False:.not-present :False:.also-not-here>foo|]
it "optional and present classes" $
helper "<i class=\"present\">foo</i>\n" [hamlet|<i :False:.not-present :True:.present>foo|]
it "punctuation operators #115" $
helper "foo"
[hamlet|
$if True && True
foo
$else
bar
|]
it "list syntax" $
helper "123"
[hamlet|
$forall x <- []
ignored
$forall x <- [1, 2, 3]
#{show x}
|]
it "list in attribute" $
let myShow :: [Int] -> String
myShow = show
in helper "<a href=\"[]\">foo</a>\n<a href=\"[1,2]\">bar</a>\n"
[hamlet|
<a href=#{myShow []}>foo
<a href=#{myShow [1, 2]}>bar
|]
it "AngularJS attribute values #122" $
helper "<li ng-repeat=\"addr in msgForm.new.split(/\\\\s/)\">{{addr}}</li>\n"
[hamlet|<li ng-repeat="addr in msgForm.new.split(/\\s/)">{{addr}}|]
it "runtime Hamlet with caret interpolation" $ do
let toInclude render = render (5, [("hello", "world")])
let renderer x y = pack $ show (x :: Int, y :: [(Text, Text)])
template1 = "@?{url}"
template2 = "foo^{toInclude}bar"
toInclude <- parseHamletRT defaultHamletSettings template1
hamletRT <- parseHamletRT defaultHamletSettings template2
res <- renderHamletRT hamletRT
[ (["toInclude"], HDTemplate toInclude)
, (["url"], HDUrlParams 5 [(pack "hello", pack "world")])
] renderer
helperHtml "foo(5,[(\"hello\",\"world\")])bar" res
data Pair = Pair String Int
data Url = Home | Sub SubUrl
data SubUrl = SubUrl
render :: Url -> [(Text, Text)] -> Text
render Home qs = pack "url" `mappend` showParams qs
render (Sub SubUrl) qs = pack "suburl" `mappend` showParams qs
showParams :: [(Text, Text)] -> Text
showParams [] = pack ""
showParams z =
pack $ '?' : intercalate "&" (map go z)
where
go (x, y) = go' x ++ '=' : go' y
go' = concatMap encodeUrlChar . unpack
-- | Taken straight from web-encodings; reimplemented here to avoid extra
-- dependencies.
encodeUrlChar :: Char -> String
encodeUrlChar c
-- List of unreserved characters per RFC 3986
-- Gleaned from http://en.wikipedia.org/wiki/Percent-encoding
| 'A' <= c && c <= 'Z' = [c]
| 'a' <= c && c <= 'z' = [c]
| '0' <= c && c <= '9' = [c]
encodeUrlChar c@'-' = [c]
encodeUrlChar c@'_' = [c]
encodeUrlChar c@'.' = [c]
encodeUrlChar c@'~' = [c]
encodeUrlChar ' ' = "+"
encodeUrlChar y =
let (a, c) = fromEnum y `divMod` 16
b = a `mod` 16
showHex' x
| x < 10 = toEnum $ x + (fromEnum '0')
| x < 16 = toEnum $ x - 10 + (fromEnum 'A')
| otherwise = error $ "Invalid argument to showHex: " ++ show x
in ['%', showHex' b, showHex' c]
data Arg url = Arg
{ getArg :: Arg url
, var :: Html
, url :: Url
, embed :: HtmlUrl url
, true :: Bool
, false :: Bool
, list :: [Arg url]
, nothing :: Maybe String
, just :: Maybe String
, urlParams :: (Url, [(Text, Text)])
}
theArg :: Arg url
theArg = Arg
{ getArg = theArg
, var = toHtml "<var>"
, url = Home
, embed = [hamlet|embed|]
, true = True
, false = False
, list = [theArg, theArg, theArg]
, nothing = Nothing
, just = Just "just"
, urlParams = (Home, [(pack "foo", pack "bar"), (pack "foo1", pack "bar1")])
}
helperHtml :: String -> Html -> Assertion
helperHtml res h = do
let x = Text.Blaze.Html.Renderer.Text.renderHtml h
T.pack res @=? x
helper :: String -> HtmlUrl Url -> Assertion
helper res h = do
let x = Text.Blaze.Html.Renderer.Text.renderHtml $ h render
T.pack res @=? x
caseEmpty :: Assertion
caseEmpty = helper "" [hamlet||]
caseStatic :: Assertion
caseStatic = helper "some static content" [hamlet|some static content|]
caseTag :: Assertion
caseTag = do
helper "<p class=\"foo\"><div id=\"bar\">baz</div></p>" [hamlet|
$newline text
<p .foo>
<#bar>baz
|]
helper "<p class=\"foo.bar\"><div id=\"bar\">baz</div></p>" [hamlet|
$newline text
<p class=foo.bar>
<#bar>baz
|]
caseVar :: Assertion
caseVar = do
helper "<var>" [hamlet|#{var theArg}|]
caseVarChain :: Assertion
caseVarChain = do
helper "<var>" [hamlet|#{var (getArg (getArg (getArg theArg)))}|]
caseUrl :: Assertion
caseUrl = do
helper (unpack $ render Home []) [hamlet|@{url theArg}|]
caseUrlChain :: Assertion
caseUrlChain = do
helper (unpack $ render Home []) [hamlet|@{url (getArg (getArg (getArg theArg)))}|]
caseEmbed :: Assertion
caseEmbed = do
helper "embed" [hamlet|^{embed theArg}|]
helper "embed" $(hamletFileReload "test/hamlets/embed.hamlet")
ihelper "embed" $(ihamletFileReload "test/hamlets/embed.hamlet")
caseEmbedChain :: Assertion
caseEmbedChain = do
helper "embed" [hamlet|^{embed (getArg (getArg (getArg theArg)))}|]
caseIf :: Assertion
caseIf = do
helper "if" [hamlet|
$if true theArg
if
|]
caseIfChain :: Assertion
caseIfChain = do
helper "if" [hamlet|
$if true (getArg (getArg (getArg theArg)))
if
|]
caseElse :: Assertion
caseElse = helper "else" [hamlet|
$if false theArg
if
$else
else
|]
caseElseChain :: Assertion
caseElseChain = helper "else" [hamlet|
$if false (getArg (getArg (getArg theArg)))
if
$else
else
|]
caseElseIf :: Assertion
caseElseIf = helper "elseif" [hamlet|
$if false theArg
if
$elseif true theArg
elseif
$else
else
|]
caseElseIfChain :: Assertion
caseElseIfChain = helper "elseif" [hamlet|
$if false(getArg(getArg(getArg theArg)))
if
$elseif true(getArg(getArg(getArg theArg)))
elseif
$else
else
|]
caseList :: Assertion
caseList = do
helper "xxx" [hamlet|
$forall _x <- (list theArg)
x
|]
caseListChain :: Assertion
caseListChain = do
helper "urlurlurl" [hamlet|
$forall x <- list(getArg(getArg(getArg(getArg(getArg (theArg))))))
@{url x}
|]
caseWith :: Assertion
caseWith = do
helper "it's embedded" [hamlet|
$with n <- embed theArg
it's ^{n}ded
|]
caseWithMulti :: Assertion
caseWithMulti = do
helper "it's embedded" [hamlet|
$with n <- embed theArg, m <- true theArg
$if m
it's ^{n}ded
|]
caseWithChain :: Assertion
caseWithChain = do
helper "it's true" [hamlet|
$with n <- true(getArg(getArg(getArg(getArg theArg))))
$if n
it's true
|]
-- in multi-with binding, make sure that a comma in a string doesn't confuse the parser.
caseWithCommaString :: Assertion
caseWithCommaString = do
helper "it's , something" [hamlet|
$with n <- " , something"
it's #{n}
|]
caseWithMultiBindingScope :: Assertion
caseWithMultiBindingScope = do
helper "it's , something" [hamlet|
$with n <- " , something", y <- n
it's #{y}
|]
caseScriptNotEmpty :: Assertion
caseScriptNotEmpty = helper "<script></script>\n" [hamlet|<script>|]
caseMetaEmpty :: Assertion
caseMetaEmpty = do
helper "<meta>\n" [hamlet|<meta>|]
helper "<meta/>\n" [xhamlet|<meta>|]
caseInputEmpty :: Assertion
caseInputEmpty = do
helper "<input>\n" [hamlet|<input>|]
helper "<input/>\n" [xhamlet|<input>|]
caseMultiClass :: Assertion
caseMultiClass = helper "<div class=\"foo bar\"></div>\n" [hamlet|<.foo.bar>|]
caseAttribOrder :: Assertion
caseAttribOrder =
helper "<meta 1 2 3>\n" [hamlet|<meta 1 2 3>|]
caseNothing :: Assertion
caseNothing = do
helper "" [hamlet|
$maybe _n <- nothing theArg
nothing
|]
helper "nothing" [hamlet|
$maybe _n <- nothing theArg
something
$nothing
nothing
|]
caseNothingChain :: Assertion
caseNothingChain = helper "" [hamlet|
$maybe n <- nothing(getArg(getArg(getArg theArg)))
nothing #{n}
|]
caseJust :: Assertion
caseJust = helper "it's just" [hamlet|
$maybe n <- just theArg
it's #{n}
|]
caseJustChain :: Assertion
caseJustChain = helper "it's just" [hamlet|
$maybe n <- just(getArg(getArg(getArg theArg)))
it's #{n}
|]
caseConstructor :: Assertion
caseConstructor = do
helper "url" [hamlet|@{Home}|]
helper "suburl" [hamlet|@{Sub SubUrl}|]
let text = "<raw text>"
helper "<raw text>" [hamlet|#{preEscapedString text}|]
caseUrlParams :: Assertion
caseUrlParams = do
helper "url?foo=bar&foo1=bar1" [hamlet|@?{urlParams theArg}|]
caseEscape :: Assertion
caseEscape = do
helper "#this is raw\n " [hamlet|
$newline never
\#this is raw
\
\
|]
helper "$@^" [hamlet|\$@^|]
caseEmptyStatementList :: Assertion
caseEmptyStatementList = do
helper "" [hamlet|$if True|]
helper "" [hamlet|$maybe _x <- Nothing|]
let emptyList = []
helper "" [hamlet|$forall _x <- emptyList|]
caseAttribCond :: Assertion
caseAttribCond = do
helper "<select></select>\n" [hamlet|<select :False:selected>|]
helper "<select selected></select>\n" [hamlet|<select :True:selected>|]
helper "<meta var=\"foo:bar\">\n" [hamlet|<meta var=foo:bar>|]
helper "<select selected></select>\n"
[hamlet|<select :true theArg:selected>|]
helper "<select></select>\n" [hamlet|<select :False:selected>|]
helper "<select selected></select>\n" [hamlet|<select :True:selected>|]
helper "<meta var=\"foo:bar\">\n" [hamlet|<meta var=foo:bar>|]
helper "<select selected></select>\n"
[hamlet|<select :true theArg:selected>|]
caseNonAscii :: Assertion
caseNonAscii = do
helper "עִבְרִי" [hamlet|עִבְרִי|]
caseMaybeFunction :: Assertion
caseMaybeFunction = do
helper "url?foo=bar&foo1=bar1" [hamlet|
$maybe x <- Just urlParams
@?{x theArg}
|]
caseTrailingDollarSign :: Assertion
caseTrailingDollarSign =
helper "trailing space \ndollar sign #" [hamlet|
$newline never
trailing space #
\
dollar sign #\
|]
caseNonLeadingPercent :: Assertion
caseNonLeadingPercent =
helper "<span style=\"height:100%\">foo</span>" [hamlet|
$newline never
<span style=height:100%>foo
|]
caseQuotedAttribs :: Assertion
caseQuotedAttribs =
helper "<input type=\"submit\" value=\"Submit response\">" [hamlet|
$newline never
<input type=submit value="Submit response">
|]
caseSpacedDerefs :: Assertion
caseSpacedDerefs = do
helper "<var>" [hamlet|#{var theArg}|]
helper "<div class=\"<var>\"></div>\n" [hamlet|<.#{var theArg}>|]
caseAttribVars :: Assertion
caseAttribVars = do
helper "<div id=\"<var>\"></div>\n" [hamlet|<##{var theArg}>|]
helper "<div class=\"<var>\"></div>\n" [hamlet|<.#{var theArg}>|]
helper "<div f=\"<var>\"></div>\n" [hamlet|< f=#{var theArg}>|]
helper "<div id=\"<var>\"></div>\n" [hamlet|<##{var theArg}>|]
helper "<div class=\"<var>\"></div>\n" [hamlet|<.#{var theArg}>|]
helper "<div f=\"<var>\"></div>\n" [hamlet|< f=#{var theArg}>|]
caseStringsAndHtml :: Assertion
caseStringsAndHtml = do
let str = "<string>"
let html = preEscapedString "<html>"
helper "<string> <html>" [hamlet|#{str} #{html}|]
caseNesting :: Assertion
caseNesting = do
helper
"<table><tbody><tr><td>1</td></tr><tr><td>2</td></tr></tbody></table>"
[hamlet|
$newline never
<table>
<tbody>
$forall user <- users
<tr>
<td>#{user}
|]
helper
(concat
[ "<select id=\"foo\" name=\"foo\"><option selected></option>"
, "<option value=\"true\">Yes</option>"
, "<option value=\"false\">No</option>"
, "</select>"
])
[hamlet|
$newline never
<select #"#{name}" name=#{name}>
<option :isBoolBlank val:selected>
<option value=true :isBoolTrue val:selected>Yes
<option value=false :isBoolFalse val:selected>No
|]
where
users = ["1", "2"]
name = "foo"
val = 5 :: Int
isBoolBlank _ = True
isBoolTrue _ = False
isBoolFalse _ = False
caseTrailingSpace :: Assertion
caseTrailingSpace =
helper "" [hamlet| |]
caseCurrency :: Assertion
caseCurrency =
helper foo [hamlet|#{foo}|]
where
foo = "eg: 5, $6, €7.01, £75"
caseExternal :: Assertion
caseExternal = do
helper "foo\n<br>\n" $(hamletFile "test/hamlets/external.hamlet")
helper "foo\n<br/>\n" $(xhamletFile "test/hamlets/external.hamlet")
helper "foo\n<br>\n" $(hamletFileReload "test/hamlets/external.hamlet")
where
foo = "foo"
caseParens :: Assertion
caseParens = do
let plus = (++)
x = "x"
y = "y"
helper "xy" [hamlet|#{(plus x) y}|]
helper "xxy" [hamlet|#{plus (plus x x) y}|]
let alist = ["1", "2", "3"]
helper "123" [hamlet|
$forall x <- (id id id id alist)
#{x}
|]
caseHamletLiterals :: Assertion
caseHamletLiterals = do
helper "123" [hamlet|#{show 123}|]
helper "123.456" [hamlet|#{show 123.456}|]
helper "-123" [hamlet|#{show -123}|]
helper "-123.456" [hamlet|#{show -123.456}|]
helper' :: String -> Html -> Assertion
helper' res h = T.pack res @=? Text.Blaze.Html.Renderer.Text.renderHtml h
caseHamlet' :: Assertion
caseHamlet' = do
helper' "foo" [shamlet|foo|]
helper' "foo" [xshamlet|foo|]
helper "<br>\n" $ const $ [shamlet|<br>|]
helper "<br/>\n" $ const $ [xshamlet|<br>|]
-- new with generalized stuff
helper' "foo" [shamlet|foo|]
helper' "foo" [xshamlet|foo|]
helper "<br>\n" $ const $ [shamlet|<br>|]
helper "<br/>\n" $ const $ [xshamlet|<br>|]
instance Show Url where
show _ = "FIXME remove this instance show Url"
caseDiffBindNames :: Assertion
caseDiffBindNames = do
let list = words "1 2 3"
-- FIXME helper "123123" $(hamletFileReload "test/hamlets/external-debug3.hamlet")
error "test has been disabled"
caseTrailingSpaces :: Assertion
caseTrailingSpaces = helper "" [hamlet|
$if True
$elseif False
$else
$maybe x <- Nothing
$nothing
$forall x <- empty
|]
where
empty = []
caseTuple :: Assertion
caseTuple = do
helper "(1,1)" [hamlet| #{("1","1")}|]
helper "foo" [hamlet|
$with (a,b) <- ("foo","bar")
#{a}
|]
helper "url" [hamlet|
$with (a,b) <- (Home,Home)
@{a}
|]
helper "url" [hamlet|
$with p <- (Home,[])
@?{p}
|]
caseComplex :: Assertion
caseComplex = do
let z :: ((Int,Int),Maybe Int,(),Bool,[[Int]])
z = ((1,2),Just 3,(),True,[[4],[5,6]])
helper "1 2 3 4 5 61 2 3 4 5 6" [hamlet|
$with ((a,b),Just c, () ,True,d@[[e],[f,g]]) <- z
$forall h <- d
#{a} #{b} #{c} #{e} #{f} #{g}
|]
caseRecord :: Assertion
caseRecord = do
let z = ARecord 10 True
helper "10" [hamlet|
$with ARecord { field1, field2 = True } <- z
#{field1}
|]
caseRecordWildCard :: Assertion
caseRecordWildCard = do
let z = ARecord 10 True
helper "10 True" [hamlet|
$with ARecord {..} <- z
#{field1} #{field2}
|]
caseRecordWildCard1 :: Assertion
caseRecordWildCard1 = do
let z = ARecord 10 True
helper "10" [hamlet|
$with ARecord {field2 = True, ..} <- z
#{field1}
|]
caseCaseRecord :: Assertion
caseCaseRecord = do
let z = ARecord 10 True
helper "10\nTrue" [hamlet|
$case z
$of ARecord { field1, field2 = x }
#{field1}
#{x}
|]
data Msg = Hello | Goodbye
ihelper :: String -> HtmlUrlI18n Msg Url -> Assertion
ihelper res h = do
let x = Text.Blaze.Html.Renderer.Text.renderHtml $ h showMsg render
T.pack res @=? x
where
showMsg Hello = preEscapedString "Hola"
showMsg Goodbye = preEscapedString "Adios"
instance (ToMarkup a, ToMarkup b) => ToMarkup (a,b) where
toMarkup (a,b) = do
toMarkup "("
toMarkup a
toMarkup ","
toMarkup b
toMarkup ")"
| myShoggoth/shakespeare | test/Text/Shakespeare/HamletSpec.hs | mit | 27,155 | 0 | 20 | 6,561 | 5,575 | 2,985 | 2,590 | 558 | 2 |
module ProductionTest
where
import Test.HUnit
import TestUtils
import Curve
import Production
import Cost
-- Pindyck, Rubinfeld, 2003: Chaptel 7, assignment 2.
test72 =
let prodfunc = CobbDouglas 100 1 1
q = 1000
r = 120
w = 30
costfunc = (0, prodfunc)
c = cost costfunc r w q
(k, l) = factors prodfunc r w q
q' = production prodfunc k l
in do
assertBool ("Capital: " ++ show k) (closeEnough k (sqrt 2.5) 0.001)
assertBool ("Labor: " ++ show l) (closeEnough l ((sqrt 2.5) * 4) 0.001)
assertBool ("Cost: " ++ show c) (closeEnough c 379.20 1)
assertBool ("Production: " ++ show q') (closeEnough q 1000 0.001)
test73 =
let p = CobbDouglas 1 1 2
r = 10
w = 15
(k, l) = factors p r w 1000
in do
assertBool ("Capital/Labor ratio: " ++ show (k / l)) (closeEnough (k / l) 0.75 0.001)
test83 =
let fc = 100
mc = [LinearFunction 2 0]
pf = CobbDouglas (sqrt 2) 0.25 0.25
cf = (fc, pf)
r = 1
w = 1
mcf = marginalCosts cf r w
p = 60
q = productionQuantity mcf p
q' = productionQuantity mc p
c = totalCosts cf r w q
q2 = productionQuantity mcf 0
q3 = productionQuantity mcf 1
in do
assertBool ("Production (Linear): " ++ show q) (closeEnough q 30 0.0001)
assertBool ("Production (Cobb-Douglas): " ++ show q') (closeEnough q' 30 0.0001)
assertBool ("Costs: " ++ show c) (closeEnough c 1000 0.0001)
assertBool ("Production at price 0: " ++ show q2) (closeEnough q2 0 0.0001)
assertBool ("Production at price 1: " ++ show q3) (closeEnough q3 0.5 0.0001)
test86 =
let mc = [LinearFunction 2 3]
p = 9
q = productionQuantity mc p
in do
assertBool ("Production: " ++ show q) (closeEnough q 3 0.0001)
| anttisalonen/economics | src/ProductionTest.hs | mit | 1,831 | 0 | 15 | 554 | 691 | 348 | 343 | 53 | 1 |
module SetupGLFW where
import qualified Graphics.UI.GLFW as GLFW
import Control.Monad
setupGLFW :: String -> Int -> Int -> IO GLFW.Window
setupGLFW windowName desiredW desiredH = do
_ <- GLFW.init
GLFW.windowHint $ GLFW.WindowHint'ClientAPI GLFW.ClientAPI'OpenGL
GLFW.windowHint $ GLFW.WindowHint'OpenGLForwardCompat True
GLFW.windowHint $ GLFW.WindowHint'OpenGLProfile GLFW.OpenGLProfile'Core
GLFW.windowHint $ GLFW.WindowHint'ContextVersionMajor 3
GLFW.windowHint $ GLFW.WindowHint'ContextVersionMinor 2
Just win <- GLFW.createWindow desiredW desiredH windowName Nothing Nothing
-- Compensate for retina framebuffers on Mac
(frameW, frameH) <- GLFW.getFramebufferSize win
when (frameW > desiredW && frameH > desiredH) $
GLFW.setWindowSize win (desiredW `div` 2) (desiredH `div` 2)
GLFW.makeContextCurrent (Just win)
GLFW.swapInterval 0
return win | lukexi/oculus-mini | test/SetupGLFW.hs | mit | 930 | 0 | 12 | 175 | 257 | 125 | 132 | 18 | 1 |
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE FlexibleContexts #-}
module Text.Greek.Script.Syllable where
import qualified Control.Lens as Lens
import qualified Data.Maybe as Maybe
import qualified Text.Greek.Phonology.Consonant as Consonant
import qualified Text.Greek.Script.Abstract as Abstract
import qualified Text.Greek.Script.Mark as Mark
import qualified Text.Greek.Script.Place as Place
import qualified Text.Greek.Script.Punctuation as Punctuation
import qualified Text.Greek.Script.Word as Word
data StartVocalic v
= StartVocalicSingle v
| StartVocalicDiaeresis v
| StartVocalicIota v
| StartVocalicDiphthong v v
deriving (Eq, Ord, Show)
instance Functor StartVocalic where
fmap f (StartVocalicSingle v) = StartVocalicSingle (f v)
fmap f (StartVocalicDiaeresis v) = StartVocalicDiaeresis (f v)
fmap f (StartVocalicIota v) = StartVocalicIota (f v)
fmap f (StartVocalicDiphthong v1 v2) = StartVocalicDiphthong (f v1) (f v2)
type Start m = Either (StartVocalic (Abstract.Vowel, m)) (Abstract.Consonant, m)
makeStartVocalic :: [(Abstract.VowelConsonant, Mark.Group Maybe)] -> [Start (Mark.Group Maybe)]
makeStartVocalic = foldr go []
where
go (Right a, c) xs = Right (a, c) : xs
go (Left a, c@(_, _, Just Mark.SyllabicIotaSubscript)) xs = Left (StartVocalicIota (a, c)) : xs
go (Left a, c@(_, _, Just Mark.SyllabicDiaeresis)) xs = Left (StartVocalicDiaeresis (a, c)) : xs
go (Left a, c@(_, _, Nothing)) [] = Left (StartVocalicSingle (a, c)) : []
go (Left a, c@(_, _, Nothing)) (Left (StartVocalicSingle v@(vw, _)) : xs) | isCombiner vw = Left (StartVocalicDiphthong (a, c) v) : xs
go (Left a, c) xs = Left (StartVocalicSingle (a, c)) : xs
isCombiner Abstract.V_ι = True
isCombiner Abstract.V_υ = True
isCombiner _ = False
data Diphthong = D_αι | D_αυ | D_ει | D_ευ | D_ηυ | D_οι | D_ου | D_υι deriving (Eq, Ord, Show)
data ImproperDiphthong = I_α | I_η | I_ω deriving (Eq, Ord, Show)
data Vocalic m
= VocalicSingle Abstract.Vowel m
| VocalicIota ImproperDiphthong m
| VocalicDiphthong Diphthong m
deriving (Eq, Ord, Show)
getVocalicMark :: Vocalic m -> m
getVocalicMark (VocalicSingle _ m) = m
getVocalicMark (VocalicIota _ m) = m
getVocalicMark (VocalicDiphthong _ m) = m
type Vocalic' = Vocalic ()
instance Functor Vocalic where
fmap f (VocalicSingle v m) = VocalicSingle v (f m)
fmap f (VocalicIota v m) = VocalicIota v (f m)
fmap f (VocalicDiphthong v m) = VocalicDiphthong v (f m)
vocalicMarkLens :: forall a b f. Functor f => (a -> f b) -> Vocalic a -> f (Vocalic b)
vocalicMarkLens f (VocalicSingle v m) = (\m' -> VocalicSingle v m') <$> f m
vocalicMarkLens f (VocalicIota v m) = (\m' -> VocalicIota v m') <$> f m
vocalicMarkLens f (VocalicDiphthong v m) = (\m' -> VocalicDiphthong v m') <$> f m
type VocalicEither mv c = Either (Vocalic mv) c
type VocalicConsonant mv mc = VocalicEither mv (Abstract.Consonant, mc)
clusterConsonants :: [VocalicEither mv c] -> [VocalicEither mv [c]]
clusterConsonants = foldr go []
where
go (Left v) xs = Left v : xs
go (Right c) (Right cs : xs) = Right (c : cs) : xs
go (Right c) xs = Right [c] : xs
newtype Count = Count Int deriving (Eq, Ord, Show, Num)
newtype VocalicSingleCount = VocalicSingleCount Int deriving (Eq, Ord, Show, Num)
newtype ImproperDiphthongCount = ImproperDiphthongCount Int deriving (Eq, Ord, Show, Num)
newtype DiphthongCount = DiphthongCount Int deriving (Eq, Ord, Show, Num)
tagConsonantPositions :: [Either v c] -> [Either v (c, Place.Place3)]
tagConsonantPositions [] = []
tagConsonantPositions [x] = pure . Lens.over Lens._Right (flip (,) Place.initialFinal) $ x
tagConsonantPositions (x : xs) = (Lens.over Lens._Right (flip (,) Place.initial) x) : (reverse . tagReverseMedialFinal . reverse $ xs)
tagReverseMedialFinal :: [Either v c] -> [Either v (c, Place.Place3)]
tagReverseMedialFinal [] = []
tagReverseMedialFinal (x : xs) = (Lens.over Lens._Right (flip (,) Place.final) x) : (Lens.over (traverse . Lens._Right) (flip (,) Place.medial) xs)
getSyllableCount :: VocalicConsonant a b -> Count
getSyllableCount (Left _) = 1
getSyllableCount (Right _) = 0
getVocalicSingleCount :: VocalicConsonant a b -> VocalicSingleCount
getVocalicSingleCount (Left (VocalicSingle _ _)) = 1
getVocalicSingleCount _ = 0
getImproperDiphthongCount :: VocalicConsonant a b -> ImproperDiphthongCount
getImproperDiphthongCount (Left (VocalicIota _ _)) = 1
getImproperDiphthongCount _ = 0
getDiphthongCount :: VocalicConsonant a b -> DiphthongCount
getDiphthongCount (Left (VocalicDiphthong _ _)) = 1
getDiphthongCount _ = 0
getSyllableMark :: Syllable m a -> m
getSyllableMark (Syllable _ v _) = getVocalicMark v
validateVocalicConsonant :: Start (Mark.Group Maybe) -> Maybe (VocalicConsonant (Mark.AccentBreathing Maybe) (Maybe Mark.Breathing))
validateVocalicConsonant x = Lens._Left validateStartVocalic x >>= Lens._Right validateConsonantBreathing
validateStartVocalic :: StartVocalic (Abstract.Vowel, Mark.Group Maybe) -> Maybe (Vocalic (Mark.AccentBreathing Maybe))
validateStartVocalic (StartVocalicSingle (v, (a, b, Nothing))) =
Just $ VocalicSingle v (a, b)
validateStartVocalic (StartVocalicDiaeresis (v, (a, b, Just Mark.SyllabicDiaeresis))) =
Just $ VocalicSingle v (a, b)
validateStartVocalic (StartVocalicIota (v, (a, b, Just Mark.SyllabicIotaSubscript))) =
VocalicIota <$> vowelToImproperDiphthong v <*> pure (a, b)
validateStartVocalic (StartVocalicDiphthong (v1, (Nothing, Nothing, Nothing)) (v2, (a, b, Nothing))) =
VocalicDiphthong <$> vowelPairToDiphthong v1 v2 <*> pure (a, b)
validateStartVocalic _ =
Nothing
vowelToImproperDiphthong :: Abstract.Vowel -> Maybe ImproperDiphthong
vowelToImproperDiphthong Abstract.V_α = Just I_α
vowelToImproperDiphthong Abstract.V_η = Just I_η
vowelToImproperDiphthong Abstract.V_ω = Just I_ω
vowelToImproperDiphthong _ = Nothing
vowelPairToDiphthong :: Abstract.Vowel -> Abstract.Vowel -> Maybe Diphthong
vowelPairToDiphthong Abstract.V_α Abstract.V_ι = Just D_αι
vowelPairToDiphthong Abstract.V_α Abstract.V_υ = Just D_αυ
vowelPairToDiphthong Abstract.V_ε Abstract.V_ι = Just D_ει
vowelPairToDiphthong Abstract.V_ε Abstract.V_υ = Just D_ευ
vowelPairToDiphthong Abstract.V_η Abstract.V_υ = Just D_ηυ
vowelPairToDiphthong Abstract.V_ο Abstract.V_ι = Just D_οι
vowelPairToDiphthong Abstract.V_ο Abstract.V_υ = Just D_ου
vowelPairToDiphthong Abstract.V_υ Abstract.V_ι = Just D_υι
vowelPairToDiphthong _ _ = Nothing
validateConsonantBreathing :: (Abstract.Consonant, Mark.Group Maybe) -> Maybe (Abstract.Consonant, Maybe Mark.Breathing)
validateConsonantBreathing (x, (Nothing, b, Nothing)) = Just (x, b)
validateConsonantBreathing _ = Nothing
vocalicToSingle :: Vocalic m -> [Abstract.Vowel]
vocalicToSingle (VocalicSingle v _) = [v]
vocalicToSingle _ = []
vocalicToImproperDiphthong :: Vocalic m -> [ImproperDiphthong]
vocalicToImproperDiphthong (VocalicIota d _) = [d]
vocalicToImproperDiphthong _ = []
vocalicToDiphthong :: Vocalic m -> [Diphthong]
vocalicToDiphthong (VocalicDiphthong d _) = [d]
vocalicToDiphthong _ = []
data Syllable m c = Syllable
{ syllableInitialConsonants :: c
, syllableVocalic :: Vocalic m
, syllableFinalConsonants :: c
} deriving (Eq, Ord, Show)
syllableMarkLens :: forall m m' c f. Functor f => (m -> f m') -> Syllable m c -> f (Syllable m' c)
syllableMarkLens f (Syllable cl v cr) = (\m' -> Syllable cl (fmap (const m') v) cr) <$> f (getVocalicMark v)
type SyllableListOrConsonants m c = Either [Syllable m c] c
type SyllableOrConsonants m c = Either (Syllable m c) c
unifySyllableConsonant :: SyllableListOrConsonants m c -> [SyllableOrConsonants m c]
unifySyllableConsonant (Left ss) = fmap Left ss
unifySyllableConsonant (Right cs) = pure (Right cs)
mapSyllableMark :: (m -> m2) -> Syllable m c -> Syllable m2 c
mapSyllableMark f (Syllable c1 m c2) = Syllable c1 (fmap f m) c2
splitMedial :: ([c] -> ([c], [c])) -> [Syllable m [c]] -> Maybe [Syllable m [c]]
splitMedial split = foldr go (Just [])
where
go (Syllable _ _ (_:_)) (Just (Syllable [] _ _ : _)) = Nothing
go (Syllable cl1 v1 []) (Just (Syllable cl2 v2 cr2 : xs)) | (l, r) <- split cl2 = Just (Syllable cl1 v1 l : Syllable r v2 cr2 : xs)
go x (Just xs) = Just (x : xs)
go _ Nothing = Nothing
makeSyllableMedialNext :: [VocalicEither m [c]] -> Maybe (SyllableListOrConsonants m [c])
makeSyllableMedialNext = tryFinish . foldr go (Just ([], []))
where
go (Left v) (Just (cs, ss)) = Just ([], Syllable [] v cs : ss)
go (Right csl) (Just ([], Syllable [] v csr : ss)) = Just ([], Syllable csl v csr : ss)
go (Right csr) (Just ([], [])) = Just (csr, [])
go _ _ = Nothing
tryFinish (Just ([], ss)) = Just . Left $ ss
tryFinish (Just (cs@(_:_), [])) = Just . Right $ cs
tryFinish _ = Nothing
getCrasis :: SyllableListOrConsonants (Mark.AccentBreathing Maybe) [c] -> Word.Crasis
getCrasis (Left ((Syllable (_:_) v _) : _))
| (_, Just Mark.BreathingSmooth) <- getVocalicMark v = Word.HasCrasis
getCrasis _ = Word.NoCrasis
processBreathing :: SyllableListOrConsonants (Mark.AccentBreathing Maybe) [Consonant.PlusRoughRho]
-> Maybe (SyllableListOrConsonants (Maybe Mark.Accent) [Consonant.PlusRoughRhoRoughBreathing])
processBreathing (Right r) = Just . Right . fmap Consonant.promotePlusRoughRho $ r
processBreathing (Left ss) = go ss >>= (pure . Left)
where
go ((Syllable [] v cr) : ss')
| (_, Just Mark.BreathingRough) <- getVocalicMark v
= (:) <$> pure (Syllable [Consonant.RB_Rough] (dropBreathing v) (promote cr)) <*> validateAllNoBreathing ss'
go ((Syllable cl v cr) : ss')
| smoothOrNone v
= (:) <$> promoteC (Syllable cl (dropBreathing v) cr) <*> validateAllNoBreathing ss'
go _ = Nothing
promote = fmap Consonant.promotePlusRoughRho
promoteC :: Syllable a [Consonant.PlusRoughRho]
-> Maybe (Syllable a [Consonant.PlusRoughRhoRoughBreathing])
promoteC (Syllable cl v cr) = Just (Syllable (promote cl) v (promote cr))
dropBreathing = fmap fst
smoothOrNone v | (_, Just Mark.BreathingSmooth) <- getVocalicMark v = True
smoothOrNone v | (_, Nothing) <- getVocalicMark v = True
smoothOrNone _ = False
validateAllNoBreathing :: [Syllable (Mark.AccentBreathing Maybe) [Consonant.PlusRoughRho]]
-> Maybe ([Syllable (Maybe Mark.Accent) [Consonant.PlusRoughRhoRoughBreathing]])
validateAllNoBreathing = traverse validateNoBreathing
validateNoBreathing :: Syllable (Mark.AccentBreathing Maybe) [Consonant.PlusRoughRho]
-> Maybe (Syllable (Maybe Mark.Accent) [Consonant.PlusRoughRhoRoughBreathing])
validateNoBreathing (Syllable cl v cr) | (_, Nothing) <- getVocalicMark v = promoteC $ (Syllable cl (dropBreathing v) cr)
validateNoBreathing _ = Nothing
processGrave :: Punctuation.EndOfSentence -> Mark.Accent -> Maybe Mark.AcuteCircumflex
processGrave Punctuation.IsEndOfSentence = Mark.accentNotGrave
processGrave _ = Just . Mark.convertGraveToAcute
newtype ReverseIndex = ReverseIndex { getReverseIndex :: Int } deriving (Eq, Show, Ord)
applyReverseIndex :: [a] -> [(Int, a)]
applyReverseIndex = reverse . zip [0..] . reverse
getAccents :: SyllableListOrConsonants (Maybe Mark.AcuteCircumflex) c -> [Mark.AcuteCircumflex]
getAccents = Lens.toListOf (Lens._Left . traverse . syllableMarkLens . Lens._Just)
getAccentCount :: SyllableListOrConsonants (Maybe Mark.AcuteCircumflex) c -> Int
getAccentCount = length . getAccents
isDoubleAccentWithFinalAcute :: SyllableListOrConsonants (Maybe Mark.AcuteCircumflex) c -> Bool
isDoubleAccentWithFinalAcute s = length accents == 2 && (checkLast . reverse $ accents)
where
accents = getAccents s
checkLast (Mark.Acute : _) = True
checkLast _ = False
getTopLevelSyllableCount :: SyllableListOrConsonants (Maybe Mark.AcuteCircumflex) c -> Int
getTopLevelSyllableCount = length . Lens.toListOf (Lens._Left . traverse)
dropFinalAcute :: SyllableListOrConsonants (Maybe Mark.AcuteCircumflex) c
-> SyllableListOrConsonants (Maybe Mark.AcuteCircumflex) c
dropFinalAcute = Lens.over Lens._Left dropLastAcute
where
dropLastAcute :: [Syllable (Maybe Mark.AcuteCircumflex) c] -> [Syllable (Maybe Mark.AcuteCircumflex) c]
dropLastAcute = reverse . dropFirstAcute . reverse
dropFirstAcute :: [Syllable (Maybe Mark.AcuteCircumflex) c] -> [Syllable (Maybe Mark.AcuteCircumflex) c]
dropFirstAcute (x : xs) = Lens.over syllableMarkLens acuteToNothing x : xs
dropFirstAcute [] = []
acuteToNothing :: Maybe Mark.AcuteCircumflex -> Maybe Mark.AcuteCircumflex
acuteToNothing (Just Mark.Acute) = Nothing
acuteToNothing x = x
trackEncliticAccent :: [Word.Word Word.WithEnclitic (SyllableListOrConsonants (Maybe Mark.AcuteCircumflex) c)]
-> [Word.Word Word.WithEnclitic (SyllableListOrConsonants (Maybe Mark.AcuteCircumflex) c)]
trackEncliticAccent (w : ws)
| Word.NoAccentUncertainEnclitic <- Lens.view (Word.info . Word.encliticLens) w
= Lens.set (Word.info . Word.encliticLens) Word.UnaccentedAfterDoubleIsEnclitic w : ws
trackEncliticAccent (w : ws)
| Word.AccentedUnlikelyEnclitic <- Lens.view (Word.info . Word.encliticLens) w
= Lens.set (Word.info . Word.encliticLens) Word.SandwichDoubleEncliticIsEnclitic w : trackEncliticAccent ws
trackEncliticAccent ws = ws
markInitialEnclitic :: [Word.Word Word.Sentence (SyllableListOrConsonants (Maybe Mark.AcuteCircumflex) c)]
-> [Word.Word Word.WithEnclitic (SyllableListOrConsonants (Maybe Mark.AcuteCircumflex) c)]
markInitialEnclitic = foldr go []
where
go w ys
| s <- Word.getSurface w
, isDoubleAccentWithFinalAcute s
= Word.Word (Word.addInitialEnclitic Word.DoubleAccentNotEnclitic (Word.getInfo w)) (dropFinalAcute s)
: trackEncliticAccent ys
go w ys
| getTopLevelSyllableCount (Word.getSurface w) == 0
= Lens.over Word.info (Word.addInitialEnclitic Word.NoSyllableNotEnclitic) w : ys
go w ys
| getTopLevelSyllableCount (Word.getSurface w) > 2 || getAccents (Word.getSurface w) == [Mark.Circumflex]
= Lens.over Word.info (Word.addInitialEnclitic Word.AccentedNotEnclitic) w : ys
go w ys
| getTopLevelSyllableCount (Word.getSurface w) <= 2 && getAccents (Word.getSurface w) == [Mark.Acute]
= Lens.over Word.info (Word.addInitialEnclitic Word.AccentedUnlikelyEnclitic) w : ys
go w ys
| getWordAccent (Word.getSurface w) == Just Word.AccentNone
= Lens.over Word.info (Word.addInitialEnclitic Word.NoAccentUncertainEnclitic) w : ys
go w ys
= Lens.over Word.info (Word.addInitialEnclitic Word.OtherUncertainEnclitic) w : ys
getWordAccent :: SyllableListOrConsonants (Maybe Mark.AcuteCircumflex) c
-> Maybe Word.Accent
getWordAccent (Right _) = Just Word.AccentNone
getWordAccent (Left ss) = go . reverse . fmap getSyllableMark $ ss
where
go :: [Maybe Mark.AcuteCircumflex] -> Maybe Word.Accent
go (Just Mark.Acute : xs) | allEmptyAccents xs = Just Word.AccentAcuteUltima
go (Just Mark.Circumflex : xs) | allEmptyAccents xs = Just Word.AccentCircumflexUltima
go (Nothing : Just Mark.Acute : xs) | allEmptyAccents xs = Just Word.AccentAcutePenult
go (Nothing : Just Mark.Circumflex : xs) | allEmptyAccents xs = Just Word.AccentCircumflexPenult
go (Nothing : Nothing : Just Mark.Acute : xs) | allEmptyAccents xs = Just Word.AccentAcuteAntepenult
go xs | allEmptyAccents xs = Just Word.AccentNone
go _ = Nothing
allEmptyAccents :: [Maybe Mark.AcuteCircumflex] -> Bool
allEmptyAccents = all Maybe.isNothing
| scott-fleischman/greek-grammar | haskell/greek-grammar/src/Text/Greek/Script/Syllable.hs | mit | 15,630 | 0 | 16 | 2,531 | 5,996 | 3,081 | 2,915 | 260 | 8 |
import Data.List
import Data.Ord (comparing)
lsort :: [[a]] -> [[a]]
lsort = sortBy (comparing length)
lfsort :: [[a]] -> [[a]]
lfsort xs = concat groups
where groups = lsort . groupBy (\xs ys -> length xs == length ys) $ lsort xs
main :: IO ()
main = do
let value = lfsort ["abc", "de", "fgh", "de", "ijkl", "mn", "o"]
print value
| zeyuanxy/haskell-playground | ninety-nine-haskell-problems/vol3/28B.hs | mit | 351 | 0 | 11 | 81 | 179 | 96 | 83 | 11 | 1 |
{-# LANGUAGE BangPatterns #-}
-- The code in this file was crafted by Claude Heiland-Allen
-- For more details see: http://code.mathr.co.uk/word-histogram
-- | Split a UTF-8 ByteString into chunks.
module Utf8Chunk (utf8Chunk) where
import Data.Bits ((.&.))
import Data.Word (Word8)
import qualified Data.ByteString as B -- bytestring
import qualified Data.Text as T -- text
import qualified Data.Text.Encoding as T -- text
-- | Split a strict ByteString containing UTF-8 into chunks, each no smaller
-- than the desired size.
utf8Chunk
:: (Char -> Bool) -- ^ which characters are allowable break points
-> Int -- ^ desired chunk size in bytes
-> B.ByteString -- ^ must be valid UTF-8
-> [B.ByteString] -- ^ valid UTF-8 chunks split at allowable points
utf8Chunk canBreak approxChunkBytes = go
where
go utf8Input
| B.null utf8Input = []
| otherwise =
let -- skip the target number of bytes
post = B.drop approxChunkBytes utf8Input
-- ensure multi-byte characters are synchronized
(cont, rest) = B.span isUtf8ContinuationByte post
-- ensure it is safe to break (eg: not in hte middle of a word)
block = breakLengthUtf8 canBreak rest
-- find the true chunk length taking the above into account
chunkBytes = approxChunkBytes + B.length cont + block
-- split the input without copying
(prefix, suffix) = B.splitAt chunkBytes utf8Input
-- decode the chunk and continue with the remainder
in prefix : go suffix
isUtf8ContinuationByte :: Word8 -> Bool
-- https://en.wikipedia.org/wiki/UTF-8#Description
isUtf8ContinuationByte w = w .&. 0xC0 == 0x80
breakLengthUtf8 :: (Char -> Bool) -> B.ByteString -> Int
-- keep getting text until it's safe to break
-- return the number of bytes consumed
breakLengthUtf8 canBreak = go 0
where
go !count s = case fromUtf8 s of
Nothing -> count
Just (t, bytes)
| canBreak (T.last t) -> count
| otherwise -> go (count + bytes) (B.drop bytes s)
fromUtf8 :: B.ByteString -> Maybe (T.Text, Int)
-- feed in a byte at a time until some text can be decoded or there are no more
fromUtf8
= go 0 (T.Some T.empty B.empty T.streamDecodeUtf8)
. map B.singleton . B.unpack
where
go !count (T.Some t _ next) bs
| T.null t = case bs of
[] -> Nothing
(b:rest) -> go (count + 1) (next b) rest
| otherwise = Just (t, count)
| apauley/parallel-frequency | src/Utf8Chunk.hs | mit | 2,559 | 0 | 16 | 699 | 556 | 297 | 259 | 41 | 2 |
module Utils (collapseParts, collapseString) where
import Types
import Numeric
collapseParts :: [BracedStringParts] -> String
collapseParts parts = go parts []
where go ((BareString s):_parts) accum =
go _parts (accum ++ s)
go ((QuotedCharCode c):_parts) accum =
go _parts (accum ++ c)
go ((QuotedHex h):_parts) accum =
go _parts (accum ++ "0x" ++ (showHex h ""))
go ((QuotedOctal o):_parts) accum =
go _parts (accum ++ "0o" ++ (showOct o ""))
go ((QuotedChar c):_parts) accum =
go _parts (accum ++ c)
go ((NestedBrace ps):_parts) accum =
go _parts ("{" ++ (go ps accum) ++ "}")
go [] accum = accum
collapseString :: UnbrokenOrBraced -> String
collapseString (UnbrokenString s) = s
collapseString (BracedString []) = ""
collapseString (BracedString parts) = collapseParts parts
| deech/fltkhs | src/Fluid/Utils.hs | mit | 890 | 0 | 12 | 231 | 361 | 187 | 174 | 22 | 7 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
module Test.SerialSpec (main, spec) where
import Control.Applicative
import Data.Aeson
import GHC.Generics
import Control.Monad.IO.Class
import Test.Hspec
import qualified Data.Binary as B
import qualified Data.Serialize as C
import Test.QuickCheck.Monadic
import Test.QuickCheck
import Test.Serial ( runAesonSerializationTest
, runBinarySerializationTest
, runCerealSerializationTest
, TestError (..) )
import Filesystem
data TestSerialData = TestSerialData {
anExampleStringField :: String,
anExampleIntField :: Int,
anExampleListTupleField :: (Int,Int)
}
deriving (Generic,Eq)
testAesonSerialFilePath = "serialfiles/aesontest.json"
testBinarySerialFilePath = "serialfiles/binarytest.serial"
testCerealSerialFilePath = "serialfiles/cerealtest.serial"
instance ToJSON TestSerialData where
instance FromJSON TestSerialData where
instance B.Binary TestSerialData where
instance C.Serialize TestSerialData where
generateTestSerialData :: [Int] -> [String] -> [(Int, Int)] -> [TestSerialData]
generateTestSerialData integers strings integerTuples = TestSerialData <$> strings <*> integers <*> integerTuples
quickCheckAesonSerializeIsIsoMorphic integers strings integerTuples = do
let testData = generateTestSerialData integers strings integerTuples
eTestData <- liftIO $ runAesonSerializationTest testData testAesonSerialFilePath
case eTestData of
(Left NoFileFound) -> do
eTestNowThatFileIsMade <- liftIO $ runAesonSerializationTest testData testAesonSerialFilePath
liftIO $ removeFile "serialfiles/aesontest.json"
assert (eTestNowThatFileIsMade == (Right testData))
_ -> assert (False == True)
quickCheckBinarySerializeIsIsoMorphic integers strings integerTuples = do
let testData = generateTestSerialData integers strings integerTuples
eTestData <- liftIO $ runBinarySerializationTest testData testBinarySerialFilePath
case eTestData of
(Left NoFileFound) -> do
eTestNowThatFileIsMade <- liftIO $ runBinarySerializationTest testData testBinarySerialFilePath
liftIO $ removeFile "serialfiles/binarytest.serial"
assert (eTestNowThatFileIsMade == (Right testData))
_ -> assert (False == True)
quickCheckCerealSerializeIsIsoMorphic integers strings integerTuples = do
let testData = generateTestSerialData integers strings integerTuples
eTestData <- liftIO $ runCerealSerializationTest testData testCerealSerialFilePath
case eTestData of
(Left NoFileFound) -> do
eTestNowThatFileIsMade <- liftIO $ runCerealSerializationTest testData testCerealSerialFilePath
liftIO $ removeFile "serialfiles/cerealtest.serial"
assert (eTestNowThatFileIsMade == (Right testData))
_ -> assert (False == True)
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "someFunction" $ do
it "should serialize and deserialize correctly " $ property $ (\s i t -> monadicIO $ quickCheckAesonSerializeIsIsoMorphic s i t)
testData = generateTestSerialData [0] [""] [(0,0)]
| smurphy8/serial-test-generators | test/Test/SerialSpec.hs | mit | 3,299 | 0 | 16 | 688 | 724 | 375 | 349 | 65 | 2 |
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE helpset
PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 1.0//EN"
"http://java.sun.com/products/javahelp/helpset_1_0.dtd">
<helpset version="1.0">
<!-- title -->
<title>Hilfe zum AVL-Modul</title>
<!-- maps -->
<maps>
<homeID>avl</homeID>
<mapref location="map.jhm"/>
</maps>
<!-- presentations -->
<presentation default=true>
<name>main window</name>
<size width="920" height="450" />
<location x="150" y="150" />
<image>mainicon</image>
<toolbar>
<helpaction>javax.help.BackAction</helpaction>
<helpaction>javax.help.ForwardAction</helpaction>
<helpaction>javax.help.ReloadAction</helpaction>
<helpaction>javax.help.SeparatorAction</helpaction>
<helpaction image="Startseite">javax.help.HomeAction</helpaction>
<helpaction>javax.help.SeparatorAction</helpaction>
<helpaction>javax.help.PrintAction</helpaction>
<helpaction>javax.help.PrintSetupAction</helpaction>
</toolbar>
</presentation>
<!-- views -->
<view mergetype="javax.help.UniteAppendMerge">
<name>TOC</name>
<label>Inhaltsverzeichnis</label>
<type>javax.help.TOCView</type>
<data>avlTOC.xml</data>
</view>
<view mergetype="javax.help.SortMerge">
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>avlIndex.xml</data>
</view>
<view xml:lang="de">
<name>Search</name>
<label>Suche</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
</helpset> | jurkov/j-algo-mod | res/module/avl/help/jhelp/avl_help.hs | gpl-2.0 | 1,617 | 124 | 90 | 217 | 647 | 323 | 324 | -1 | -1 |
{-# OPTIONS_GHC -Wall -fwarn-tabs -Werror #-}
-------------------------------------------------------------------------------
-- |
-- Module : Error
-- Copyright : Copyright (c) 2014 Michael R. Shannon
-- License : GPLv2 or Later
-- Maintainer : mrshannon.aerospace@gmail.com
-- Stability : unstable
-- Portability : portable
--
-- Error handling and reporting module.
-------------------------------------------------------------------------------
module Error
( printOpenGLErrors
) where
import System.IO
import qualified Graphics.UI.GLUT as GLUT
-- Print OpenGL errors.
printOpenGLErrors :: IO ()
printOpenGLErrors = GLUT.get GLUT.errors >>= mapM_ (hPrint stderr)
| mrshannon/trees | src/Error.hs | gpl-2.0 | 697 | 0 | 8 | 107 | 71 | 46 | 25 | 7 | 1 |
module PureRunner
(
runSDPure
) where
import FRP.Yampa
import SIR
runSDPure :: Double
-> Double
-> Double
-> Double
-> Double
-> Time
-> DTime
-> [SIRStep]
runSDPure populationSize infectedCount contactRate infectivity illnessDuration t dt
= embed (sir populationSize infectedCount contactRate infectivity illnessDuration) ((), steps)
where
steps = replicate (floor $ t / dt) (dt, Nothing) | thalerjonathan/phd | coding/papers/sdhaskell/src/PureRunner.hs | gpl-3.0 | 482 | 0 | 12 | 148 | 129 | 70 | 59 | 16 | 1 |
module SugarScape.Simulation
( SimulationState (..)
, SimStepOut
, AgentObservable
, initSimulation
, initSimulationOpt
, initSimulationRng
, initSimulationSeed
, simulationStep
, simStepSF
, mkSimState
, simulateUntil
, sugarScapeTimeDelta
) where
import Data.Maybe
import System.Random
import Control.Monad.Random
import Control.Monad.Reader
import Control.Monad.State.Strict
import FRP.BearRiver
import SugarScape.AgentMonad
import SugarScape.Environment
import SugarScape.Model
import SugarScape.Init
import SugarScape.Random
type AgentObservable o = (AgentId, o)
type SimStepOut = (Time, SugEnvironment, [AgentObservable SugAgentObservable])
-- NOTE: strictness on those fields, otherwise space-leak
-- (memory consumption increases throughout run-time and execution gets slower and slower)
data SimulationState g = SimulationState
{ simSf :: SF (SugAgentMonadT g) () [AgentObservable SugAgentObservable]
, simAbsState :: !ABSState
, simEnv :: !SugEnvironment
, simRng :: !g
, simSteps :: !Int
}
-- sugarscape is stepped with a time-delta of 1.0
sugarScapeTimeDelta :: DTime
sugarScapeTimeDelta = 1.0
initSimulation :: SugarScapeParams
-> IO (SimulationState StdGen, SugEnvironment)
initSimulation params = do
g0 <- newStdGen
return $ initSimulationRng g0 params
initSimulationOpt :: Maybe Int
-> SugarScapeParams
-> IO (SimulationState StdGen, SugEnvironment)
initSimulationOpt Nothing params = initSimulation params
initSimulationOpt (Just seed) params = return $ initSimulationSeed seed params
initSimulationSeed :: Int
-> SugarScapeParams
-> (SimulationState StdGen, SugEnvironment)
initSimulationSeed seed = initSimulationRng g0
where
g0 = mkStdGen seed
initSimulationRng :: RandomGen g
=> g
-> SugarScapeParams
-> (SimulationState g, SugEnvironment)
initSimulationRng g0 params = (initSimState, initEnv)
where
-- split
(gSim, shuffleRng) = split g0
-- initial agents and environment data
((initAs, initEnv), gSim') = runRand (createSugarScape params) gSim
-- initial simulation state
(initAis, initSfs) = unzip initAs
-- initial simulation state
initSimState = mkSimState
(simStepSF initAis initSfs (sugEnvironment params) shuffleRng)
(mkAbsState $ maximum initAis) initEnv gSim' 0
simulateUntil :: RandomGen g
=> Time
-> SimulationState g
-> [SimStepOut]
simulateUntil tMax ss0 = simulateUntilAux ss0 []
where
simulateUntilAux :: SimulationState g
-> [SimStepOut]
-> [SimStepOut]
simulateUntilAux ss acc
| t < tMax = simulateUntilAux ss' acc'
| otherwise = reverse acc'
where
(ss', so@(t, _, _)) = simulationStep ss
acc' = so : acc
simulationStep :: SimulationState g
-> (SimulationState g, SimStepOut)
simulationStep ss = (ss', (t, env', out))
where
sf = simSf ss
absState = simAbsState ss
env = simEnv ss
g = simRng ss
steps = simSteps ss
sfReader = unMSF sf ()
sfAbsState = runReaderT sfReader sugarScapeTimeDelta
sfEnvState = runStateT sfAbsState absState
sfRand = runStateT sfEnvState env
((((out, sf'), absState'), env'), g') = runRand sfRand g
t = absTime absState
absState'' = absState' { absTime = t + sugarScapeTimeDelta }
ss' = mkSimState sf' absState'' env' g' (steps + 1)
simStepSF :: RandomGen g
=> [AgentId]
-> [SugAgent g]
-> SugAgent g
-> g
-> SF (SugAgentMonadT g) () [AgentObservable SugAgentObservable]
simStepSF ais0 sfs0 envSf0 shuffleRng = MSF $ \_ -> do
let (sfsAis, shuffleRng') = fisherYatesShuffle shuffleRng (zip sfs0 ais0)
(sfs, ais) = unzip sfsAis
ret <- mapM (`unMSF` ()) sfs
-- NOTE: run environment separately after all agents
(_, envSf') <- unMSF envSf0 ()
let adefs = concatMap (\(ao, _) -> aoCreate ao) ret
newSfs = map adBeh adefs
newAis = map adId adefs
obs = foldr (\((ao, _), aid) acc ->
if isObservable ao
then (aid, fromJust $ aoObservable ao) : acc
else acc) [] (zip ret ais)
(sfs', ais') = foldr (\((ao, sf), aid) acc@(accSf, accAid) ->
if isDead ao
then acc
else (sf : accSf, aid : accAid)) ([], []) (zip ret ais)
ct = simStepSF (newAis ++ ais') (newSfs ++ sfs') envSf' shuffleRng'
return (obs, ct)
mkSimState :: SF (SugAgentMonadT g) () [AgentObservable SugAgentObservable]
-> ABSState
-> SugEnvironment
-> g
-> Int
-> SimulationState g
mkSimState sf absState env g steps = SimulationState
{ simSf = sf
, simAbsState = absState
, simEnv = env
, simRng = g
, simSteps = steps
} | thalerjonathan/phd | public/towards/SugarScape/experimental/chapter2/src/SugarScape/Simulation.hs | gpl-3.0 | 5,120 | 0 | 19 | 1,495 | 1,405 | 762 | 643 | 133 | 3 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.IAM.Projects.ServiceAccounts.Update
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Updates a ServiceAccount. Currently, only the following fields are
-- updatable: \`display_name\` . The \`etag\` is mandatory.
--
-- /See:/ <https://cloud.google.com/iam/ Google Identity and Access Management (IAM) API Reference> for @iam.projects.serviceAccounts.update@.
module Network.Google.Resource.IAM.Projects.ServiceAccounts.Update
(
-- * REST Resource
ProjectsServiceAccountsUpdateResource
-- * Creating a Request
, projectsServiceAccountsUpdate
, ProjectsServiceAccountsUpdate
-- * Request Lenses
, psauXgafv
, psauUploadProtocol
, psauPp
, psauAccessToken
, psauUploadType
, psauPayload
, psauBearerToken
, psauName
, psauCallback
) where
import Network.Google.IAM.Types
import Network.Google.Prelude
-- | A resource alias for @iam.projects.serviceAccounts.update@ method which the
-- 'ProjectsServiceAccountsUpdate' request conforms to.
type ProjectsServiceAccountsUpdateResource =
"v1" :>
Capture "name" Text :>
QueryParam "$.xgafv" Text :>
QueryParam "upload_protocol" Text :>
QueryParam "pp" Bool :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "bearer_token" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] ServiceAccount :>
Put '[JSON] ServiceAccount
-- | Updates a ServiceAccount. Currently, only the following fields are
-- updatable: \`display_name\` . The \`etag\` is mandatory.
--
-- /See:/ 'projectsServiceAccountsUpdate' smart constructor.
data ProjectsServiceAccountsUpdate = ProjectsServiceAccountsUpdate'
{ _psauXgafv :: !(Maybe Text)
, _psauUploadProtocol :: !(Maybe Text)
, _psauPp :: !Bool
, _psauAccessToken :: !(Maybe Text)
, _psauUploadType :: !(Maybe Text)
, _psauPayload :: !ServiceAccount
, _psauBearerToken :: !(Maybe Text)
, _psauName :: !Text
, _psauCallback :: !(Maybe Text)
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'ProjectsServiceAccountsUpdate' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'psauXgafv'
--
-- * 'psauUploadProtocol'
--
-- * 'psauPp'
--
-- * 'psauAccessToken'
--
-- * 'psauUploadType'
--
-- * 'psauPayload'
--
-- * 'psauBearerToken'
--
-- * 'psauName'
--
-- * 'psauCallback'
projectsServiceAccountsUpdate
:: ServiceAccount -- ^ 'psauPayload'
-> Text -- ^ 'psauName'
-> ProjectsServiceAccountsUpdate
projectsServiceAccountsUpdate pPsauPayload_ pPsauName_ =
ProjectsServiceAccountsUpdate'
{ _psauXgafv = Nothing
, _psauUploadProtocol = Nothing
, _psauPp = True
, _psauAccessToken = Nothing
, _psauUploadType = Nothing
, _psauPayload = pPsauPayload_
, _psauBearerToken = Nothing
, _psauName = pPsauName_
, _psauCallback = Nothing
}
-- | V1 error format.
psauXgafv :: Lens' ProjectsServiceAccountsUpdate (Maybe Text)
psauXgafv
= lens _psauXgafv (\ s a -> s{_psauXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
psauUploadProtocol :: Lens' ProjectsServiceAccountsUpdate (Maybe Text)
psauUploadProtocol
= lens _psauUploadProtocol
(\ s a -> s{_psauUploadProtocol = a})
-- | Pretty-print response.
psauPp :: Lens' ProjectsServiceAccountsUpdate Bool
psauPp = lens _psauPp (\ s a -> s{_psauPp = a})
-- | OAuth access token.
psauAccessToken :: Lens' ProjectsServiceAccountsUpdate (Maybe Text)
psauAccessToken
= lens _psauAccessToken
(\ s a -> s{_psauAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
psauUploadType :: Lens' ProjectsServiceAccountsUpdate (Maybe Text)
psauUploadType
= lens _psauUploadType
(\ s a -> s{_psauUploadType = a})
-- | Multipart request metadata.
psauPayload :: Lens' ProjectsServiceAccountsUpdate ServiceAccount
psauPayload
= lens _psauPayload (\ s a -> s{_psauPayload = a})
-- | OAuth bearer token.
psauBearerToken :: Lens' ProjectsServiceAccountsUpdate (Maybe Text)
psauBearerToken
= lens _psauBearerToken
(\ s a -> s{_psauBearerToken = a})
-- | The resource name of the service account in the following format:
-- \`projects\/{project}\/serviceAccounts\/{account}\`. Requests using
-- \`-\` as a wildcard for the project will infer the project from the
-- \`account\` and the \`account\` value can be the \`email\` address or
-- the \`unique_id\` of the service account. In responses the resource name
-- will always be in the format
-- \`projects\/{project}\/serviceAccounts\/{email}\`.
psauName :: Lens' ProjectsServiceAccountsUpdate Text
psauName = lens _psauName (\ s a -> s{_psauName = a})
-- | JSONP
psauCallback :: Lens' ProjectsServiceAccountsUpdate (Maybe Text)
psauCallback
= lens _psauCallback (\ s a -> s{_psauCallback = a})
instance GoogleRequest ProjectsServiceAccountsUpdate
where
type Rs ProjectsServiceAccountsUpdate =
ServiceAccount
type Scopes ProjectsServiceAccountsUpdate =
'["https://www.googleapis.com/auth/cloud-platform"]
requestClient ProjectsServiceAccountsUpdate'{..}
= go _psauName _psauXgafv _psauUploadProtocol
(Just _psauPp)
_psauAccessToken
_psauUploadType
_psauBearerToken
_psauCallback
(Just AltJSON)
_psauPayload
iAMService
where go
= buildClient
(Proxy ::
Proxy ProjectsServiceAccountsUpdateResource)
mempty
| rueshyna/gogol | gogol-iam/gen/Network/Google/Resource/IAM/Projects/ServiceAccounts/Update.hs | mpl-2.0 | 6,612 | 0 | 18 | 1,540 | 937 | 547 | 390 | 134 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.