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 MultiParamTypeClasses #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} module FsMain where import System.Fuse (fuseMain, defaultExceptionHandler) import Adb (ifAdbPresent) import Fs import qualified System.Environment as Env import Control.Monad (join, void) import System.Console.GetOpt import System.FilePath ((</>)) import System.Directory (getCurrentDirectory) import Data.Maybe (isJust) import Data.List (find) import Prelude hiding (log) main :: IO () main = do args <- Env.getArgs currentDir <- getCurrentDirectory case getOpt Permute options args of (opts, left, []) -> do if Help `elem` opts then printHelp else case createLogFunc currentDir opts of Right logFunc -> Env.withArgs left $ void $ ifAdbPresent $ fuseMain (adbFSOps logFunc) defaultExceptionHandler Left error -> ioError $ userError error (_, _, errors) -> ioError (userError $ concat errors) help :: String help = usageInfo "Usage: fuse_adb_fs [OPTION...] mountpoint" options printHelp :: IO () printHelp = putStrLn help data LogLevel = LogSilent | LogFailsOnly | LogFull deriving (Show, Eq) data Option = LogLevel (Maybe LogLevel) | LoggingFile String | Help deriving (Show, Eq) options :: [OptDescr Option] options = [ Option ['l'] ["loglevel"] (ReqArg toLogLevel "MODE") "silent, fails, full" , Option ['f'] ["logfile"] (ReqArg LoggingFile "FILE") "write log to FILE" , Option ['h'] ["help"] (NoArg Help) "show help" ] where toLogLevel "silent" = ok LogSilent toLogLevel "fails" = ok LogFailsOnly toLogLevel "full" = ok LogFull toLogLevel _ = LogLevel Nothing ok = LogLevel . Just createLogFunc :: FilePath -> [Option] -> Either String LogFunction createLogFunc currentDir options | Nothing <- logLevel , Nothing <- logFile = noLogging | Just _ <- logLevel , Nothing <- logFile = Left "if log level specified, log file should be specified too" | Nothing <- logLevel , Just file <- logFile = logFull file | Just level <- logLevel , Just file <- logFile = case level of Just LogSilent -> noLogging Just LogFailsOnly -> logFails file Just LogFull -> logFull file Nothing -> logFull file where toLogLevel (LogLevel l) = Just l toLogLevel _ = Nothing toLogFile (LoggingFile f) = Just f toLogFile _ = Nothing logLevel = fnd toLogLevel logFile = fnd toLogFile noLogging = Right $ const $ const $ return () logFull = doLog $ either Just Just logFails = doLog $ either Just $ const Nothing doLog :: (Either String String -> Maybe String) -> String -> Either String LogFunction doLog filter file = Right $ \resultMsg -> \logged -> case filter resultMsg of Just msg -> appendFile targetPath $ concat logged ++ "\n" ++ msg ++ "\n------------------" _ -> return () where targetPath = currentDir </> file fnd f = join $ find isJust $ map f options
7ocb/fuse_adb_fs
lib/FsMain.hs
gpl-3.0
3,440
0
20
1,088
957
490
467
85
7
module GraphBuilder where {-# LANGUAGE NoMonomorphismRestriction #-} import Diagrams.Prelude import Diagrams.Backend.SVG.CmdLine import Domain {- generate a path diagram -} pathToGraph :: Domain.Path -> QDiagram SVG V2 Double Any pathToGraph p = let points = pathToPoints p nodes = atPoints points $ map node [1..] nodesPaired = cnv $ [1..length points] ++ [1] in foldr (\(x,y) z -> connect x y z ) nodes nodesPaired {- from a path generate a list of points -} pathToPoints :: Domain.Path -> [Point V2 Double] pathToPoints p = map (\y -> p2(coordinatesToDouble(fst y))) p {- Convert coordinate to double due to type checking errors -} coordinatesToDouble :: Domain.Coordinate -> (Double, Double) coordinatesToDouble (x,y) = ((fromIntegral x)/5, (fromIntegral y)/5) node :: Int -> Diagram B node n = (text (show n) # fontSizeL 0.2 # fc white <> circle 0.2 # fc green) # named (toName n) cnv :: [a] -> [(a, a)] cnv [] = [] cnv (_:[]) = [] cnv (k:v:t) = (k, v) : cnv (v:t)
benkio/VRP
src/GraphBuilder.hs
gpl-3.0
1,009
0
13
203
415
220
195
-1
-1
{-# LANGUAGE PackageImports #-} module HEP.Automation.MadGraph.Dataset.Set20110302v1 where import HEP.Automation.MadGraph.Model import HEP.Automation.MadGraph.Machine import HEP.Automation.MadGraph.UserCut import HEP.Automation.MadGraph.Cluster import HEP.Automation.MadGraph.SetupType my_ssetup :: ScriptSetup my_ssetup = SS { scriptbase = "/Users/iankim/mac/workspace/ttbar/mc_script/" , mg5base = "/Users/iankim/mac/montecarlo/MG_ME_V4.4.44/MadGraph5_v0_6_1/" , workbase = "/Users/iankim/mac/workspace/ttbar/mc/" } ucut :: UserCut ucut = UserCut { uc_metcut = 15.0 , uc_etacutlep = 1.2 , uc_etcutlep = 18.0 , uc_etacutjet = 2.5 , uc_etcutjet = 15.0 } processTTBar0or1jet :: [Char] processTTBar0or1jet = "\ngenerate P P > t t~ QED=99 @1 \nadd process P P > t t~ J QED=99 @2 \n" psetup_wp_ttbar01j :: ProcessSetup psetup_wp_ttbar01j = PS { mversion = MadGraph4 , model = Wp , process = processTTBar0or1jet , processBrief = "ttbar01j" , workname = "302Wp1J" } rsetupGen :: Param -> MatchType -> Int -> RunSetup rsetupGen p matchtype num = RS { param = p , numevent = 100000 , machine = TeVatron , rgrun = Fixed , rgscale = 200.0 , match = matchtype , cut = case matchtype of NoMatch -> NoCut MLM -> DefCut , pythia = case matchtype of NoMatch -> NoPYTHIA MLM -> RunPYTHIA , usercut = UserCutDef ucut , pgs = RunPGS , setnum = num } my_csetup :: ClusterSetup my_csetup = CS { cluster = Parallel 3 } wpparamset :: [Param] wpparamset = [ WpParam 400.0 2.55 ] psetuplist :: [ProcessSetup] psetuplist = [ psetup_wp_ttbar01j ] sets :: [Int] sets = [1 .. 50 ] wptasklist :: [WorkSetup] wptasklist = [ WS my_ssetup (psetup_wp_ttbar01j) (rsetupGen p MLM num) my_csetup | p <- wpparamset , num <- sets ] totaltasklist :: [WorkSetup] totaltasklist = wptasklist
wavewave/madgraph-auto-dataset
src/HEP/Automation/MadGraph/Dataset/Set20110302v1.hs
gpl-3.0
1,959
0
9
468
448
274
174
60
3
import S.Type import S.Size import S.Model import qualified S.ModelIO import S.ToDoc import S.Reduce (isnormal) import qualified S.Reduce import S.Table import qualified S.TableHead as TH import qualified S.Normal import qualified S.Head import S.Verify import S.Back import L.Type ( froms ) import qualified L.Reduce import qualified L.Eval import qualified L.Eval.Pure import qualified L.Eval.Monadic as M import qualified L.Eval.Generic as G import qualified L.Convert import qualified L.Pure import Control.Monad ( forM_, when, guard ) import Data.List ( inits, tails, nub) import qualified Data.Map as M import qualified Data.Set as S import Control.Concurrent.STM import Data.Maybe (isNothing, isJust, maybeToList) import System.IO main = do find_normal_monster_for [b,d] -- find_divergent_for [b,d] -- write_cl_table_for [ d,b ] 6 500 -- this does not seem to halt: -- write_beta_table 10 1000 -- this terminates (38 states): -- write_cl_table 6 200 -- find_max_size $ 10^1 -- S.Model.write_full_black_table -- compare_cl_beta_normal -- find_max_left -- find_max_order -- L.Convert.find_convertible_normalforms -- L.Pure.find_pure -- write_beta_table -- let second = 10^6 ; minute = 60 * second -- L.Eval.find_monster_to $ 15 * minute -- S.Normal.find_monster -- S.Reduce.find_maxpipe -- L.Reduce.find_deep_vars -- L.Reduce.find_weak_strong -- print_multi_origins -- local S.Table.trans -- local_head TH.trans -- write_head_table -- check_head_normalization -- find_head_monster -- check_forward_closed_head TH.trans -- equiv_examples compare_cl_beta_normal = forM_ ( concat $ S.Type.normalforms ) $ \ t -> do let d = 500 b = M.eval d t c = S.Normal.normal d $ unspine [ t, var 1, var 2, var 3] if (isJust b == isJust c) then do putStr "." ; hFlush stdout else printf (t, isJust b, isJust c) find_max_left = do let work top (t:ts) = case M.eval 500 t of Just e -> do let (h,m) = G.eval G.max_left_depth t when (m > top) $ do print (t, e, m) -- print $ last $ L.Reduce.imo $ froms t -- putStrLn $ take 10 $ show $ last $ L.Reduce.imo $ froms t hFlush stdout work (max top m) ts Nothing -> work top ts work 0 $ concat S.Type.normalforms find_max_order = do let work top (t:ts) = case M.eval 500 t of Just e -> do let (h,m) = G.eval G.max_lambda_depth t when (m >= top) $ do print (t, e, (h,m)) -- print $ last $ L.Reduce.imo $ froms t -- putStrLn $ take 10 $ show $ last $ L.Reduce.imo $ froms t hFlush stdout work (max top m) ts Nothing -> work top ts work 0 $ concat S.Type.normalforms find_max_size mu = do let work top (t:ts) = do ms <- L.Eval.Pure.eval_musec mu t case ms of Just s -> do when (s >= top) $ do print (t, size t, s) hFlush stdout work (max top s) ts Nothing -> work top ts -- work 0 $ concat S.Type.normalforms work 0 $ concat S.Type.terms print_multi_origins = forM_ multi_origins $ \ (t,os) -> do print (t, toDoc os) equiv_examples = do let handle m (t:ts) = do let v = TH.value t case M.lookup v m of Nothing -> return () Just others -> print (v, toDoc $ t : others) handle (M.insertWith (++) v [t] m) ts handle M.empty $ filter isnormal $ concat terms check_normalization = do forM_ (concat terms) $ \ t -> do let v = value t n = S.Normal.normal 100 t if isNothing v == isNothing n then putStr "." else error $ show $ toDoc (t,v,n) hFlush stdout check_head_normalization = do forM_ (concat terms) $ \ t -> do let v = TH.normalizing t n = null $ drop 100 $ S.Head.plain t if v == n then if v then putStr "." else putStr "!" else error $ show $ toDoc (t,v,n) hFlush stdout find_divergent_for bs = do div <- atomically $ newTVar $ S.empty forM_ (concat $ terms_for bs) $ \ t -> do s <- atomically $ readTVar div when ( not $ or $ for (subterms t) $ \ u -> S.member u s || case u of App {fun=D,arg=App{fun=App{fun=B},arg=D}} -> True ; _ -> False ) $ do case S.Normal.normal (10 ^ 2) t of Nothing -> do atomically $ modifyTVar div $ S.insert t -- printf t Just n -> do printf t return () for = flip map find_normal_monster = do top <- atomically $ newTVar 0 forM_ (concat $ terms) $ \ t -> when (S.Table.normalizing t) $ do let n = S.Normal.normalform t up <- atomically $ do s <- readTVar top let up = size n > s when up $ writeTVar top $ size n return up when up $ printf (size t, size n, t) find_normal_monster_for bs = do top <- atomically $ newTVar 0 forM_ (concat $ terms_for bs) $ \ t -> case S.Normal.normal (10 ^ 2) t of Nothing -> return () Just n -> do up <- atomically $ do s <- readTVar top let up = size n > s when up $ writeTVar top $ size n return up when up $ printf (size t, size n, t) find_head_monster = do top <- atomically $ newTVar 0 forM_ (concat terms) $ \ t -> when (TH.normalizing t) $ do let ts = S.Head.plain t up <- atomically $ do s <- readTVar top let up = length ts > s when up $ writeTVar top $ length ts return up when up $ printf (size t, length ts, size $ last ts, t) write_cl_table = write_cl_table_for [s] write_cl_table_for bs dep len = do m0 <- model_for bs dep len m1 <- build_full_for bs m0 print $ toDoc $ base m1 print $ toDoc $ S.Model.trans m1 print $ toDoc $ S.Model.accept m1 write_head_table = do m0 <- model0 8 200 m1 <- build_head m0 print $ toDoc $ base m1 print $ toDoc $ S.Model.trans m1 print $ toDoc $ S.Model.accept m1 write_beta_table depth mu = do m0 <- S.ModelIO.model0 depth mu m1 <- S.ModelIO.build_beta_full m0 print $ toDoc $ S.ModelIO.base m1 print $ toDoc $ S.ModelIO.trans m1 print $ toDoc $ S.ModelIO.accept m1 ---------------------------------------------------- highdees n k = do yield <- inserts k d $ replicate n b t <- termsfrom yield return t looksnormalizing n = isJust . S.Normal.normal n -- replace exactly k elements of ys by x inserts :: Int -> a -> [a] -> [[a]] inserts 0 x ys = return ys inserts k x ys = do guard $ k <= length ys (pre, this : post) <- splits ys post' <- inserts (k-1) x post return $ pre ++ x : post' termsfrom :: [T] -> [T] termsfrom [leaf] = return leaf termsfrom yield = do (pre, post) <- splits yield guard $ not $ null pre guard $ not $ null post l <- termsfrom pre ; r <- termsfrom post return $ app l r splits xs = zip (inits xs) (tails xs) -- | ground term over base, attach variables [1..k], -- enumerate all pure subterms that are reachable reachable_subterms_for bs k = nub $ do n <- [1 .. ] t <- terms_for bs !! n let s = unspine $ t : map var [ 1 .. k ] n <- maybeToList $ S.Normal.normal 100 s u <- subterms n guard $ bfree u return u bfree u = and $ for (subterms u) $ \ s -> s /= b
jwaldmann/s
Main.hs
gpl-3.0
7,967
0
28
2,750
2,753
1,361
1,392
189
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.SecurityCenter.Organizations.Sources.Patch -- 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 source. -- -- /See:/ <https://console.cloud.google.com/apis/api/securitycenter.googleapis.com/overview Security Command Center API Reference> for @securitycenter.organizations.sources.patch@. module Network.Google.Resource.SecurityCenter.Organizations.Sources.Patch ( -- * REST Resource OrganizationsSourcesPatchResource -- * Creating a Request , organizationsSourcesPatch , OrganizationsSourcesPatch -- * Request Lenses , ospXgafv , ospUploadProtocol , ospUpdateMask , ospAccessToken , ospUploadType , ospPayload , ospName , ospCallback ) where import Network.Google.Prelude import Network.Google.SecurityCenter.Types -- | A resource alias for @securitycenter.organizations.sources.patch@ method which the -- 'OrganizationsSourcesPatch' request conforms to. type OrganizationsSourcesPatchResource = "v1p1beta1" :> Capture "name" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "updateMask" GFieldMask :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] Source :> Patch '[JSON] Source -- | Updates a source. -- -- /See:/ 'organizationsSourcesPatch' smart constructor. data OrganizationsSourcesPatch = OrganizationsSourcesPatch' { _ospXgafv :: !(Maybe Xgafv) , _ospUploadProtocol :: !(Maybe Text) , _ospUpdateMask :: !(Maybe GFieldMask) , _ospAccessToken :: !(Maybe Text) , _ospUploadType :: !(Maybe Text) , _ospPayload :: !Source , _ospName :: !Text , _ospCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'OrganizationsSourcesPatch' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ospXgafv' -- -- * 'ospUploadProtocol' -- -- * 'ospUpdateMask' -- -- * 'ospAccessToken' -- -- * 'ospUploadType' -- -- * 'ospPayload' -- -- * 'ospName' -- -- * 'ospCallback' organizationsSourcesPatch :: Source -- ^ 'ospPayload' -> Text -- ^ 'ospName' -> OrganizationsSourcesPatch organizationsSourcesPatch pOspPayload_ pOspName_ = OrganizationsSourcesPatch' { _ospXgafv = Nothing , _ospUploadProtocol = Nothing , _ospUpdateMask = Nothing , _ospAccessToken = Nothing , _ospUploadType = Nothing , _ospPayload = pOspPayload_ , _ospName = pOspName_ , _ospCallback = Nothing } -- | V1 error format. ospXgafv :: Lens' OrganizationsSourcesPatch (Maybe Xgafv) ospXgafv = lens _ospXgafv (\ s a -> s{_ospXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). ospUploadProtocol :: Lens' OrganizationsSourcesPatch (Maybe Text) ospUploadProtocol = lens _ospUploadProtocol (\ s a -> s{_ospUploadProtocol = a}) -- | The FieldMask to use when updating the source resource. If empty all -- mutable fields will be updated. ospUpdateMask :: Lens' OrganizationsSourcesPatch (Maybe GFieldMask) ospUpdateMask = lens _ospUpdateMask (\ s a -> s{_ospUpdateMask = a}) -- | OAuth access token. ospAccessToken :: Lens' OrganizationsSourcesPatch (Maybe Text) ospAccessToken = lens _ospAccessToken (\ s a -> s{_ospAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). ospUploadType :: Lens' OrganizationsSourcesPatch (Maybe Text) ospUploadType = lens _ospUploadType (\ s a -> s{_ospUploadType = a}) -- | Multipart request metadata. ospPayload :: Lens' OrganizationsSourcesPatch Source ospPayload = lens _ospPayload (\ s a -> s{_ospPayload = a}) -- | The relative resource name of this source. See: -- https:\/\/cloud.google.com\/apis\/design\/resource_names#relative_resource_name -- Example: \"organizations\/{organization_id}\/sources\/{source_id}\" ospName :: Lens' OrganizationsSourcesPatch Text ospName = lens _ospName (\ s a -> s{_ospName = a}) -- | JSONP ospCallback :: Lens' OrganizationsSourcesPatch (Maybe Text) ospCallback = lens _ospCallback (\ s a -> s{_ospCallback = a}) instance GoogleRequest OrganizationsSourcesPatch where type Rs OrganizationsSourcesPatch = Source type Scopes OrganizationsSourcesPatch = '["https://www.googleapis.com/auth/cloud-platform"] requestClient OrganizationsSourcesPatch'{..} = go _ospName _ospXgafv _ospUploadProtocol _ospUpdateMask _ospAccessToken _ospUploadType _ospCallback (Just AltJSON) _ospPayload securityCenterService where go = buildClient (Proxy :: Proxy OrganizationsSourcesPatchResource) mempty
brendanhay/gogol
gogol-securitycenter/gen/Network/Google/Resource/SecurityCenter/Organizations/Sources/Patch.hs
mpl-2.0
5,694
0
17
1,250
858
500
358
122
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE ViewPatterns #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Module : Network.AWS.CodeDeploy.Types -- 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. module Network.AWS.CodeDeploy.Types ( -- * Service CodeDeploy -- ** Error , JSONError -- * GenericRevisionInfo , GenericRevisionInfo , genericRevisionInfo , griDeploymentGroups , griDescription , griFirstUsedTime , griLastUsedTime , griRegisterTime -- * ApplicationInfo , ApplicationInfo , applicationInfo , aiApplicationId , aiApplicationName , aiCreateTime , aiLinkedToGitHub -- * BundleType , BundleType (..) -- * TimeRange , TimeRange , timeRange , trEnd , trStart -- * DeploymentCreator , DeploymentCreator (..) -- * InstanceSummary , InstanceSummary , instanceSummary , isDeploymentId , isInstanceId , isLastUpdatedAt , isLifecycleEvents , isStatus -- * AutoScalingGroup , AutoScalingGroup , autoScalingGroup , asgHook , asgName -- * DeploymentGroupInfo , DeploymentGroupInfo , deploymentGroupInfo , dgiApplicationName , dgiAutoScalingGroups , dgiDeploymentConfigName , dgiDeploymentGroupId , dgiDeploymentGroupName , dgiEc2TagFilters , dgiServiceRoleArn , dgiTargetRevision -- * ApplicationRevisionSortBy , ApplicationRevisionSortBy (..) -- * MinimumHealthyHosts , MinimumHealthyHosts , minimumHealthyHosts , mhhType , mhhValue -- * ListStateFilterAction , ListStateFilterAction (..) -- * LifecycleErrorCode , LifecycleErrorCode (..) -- * RevisionLocation , RevisionLocation , revisionLocation , rlGitHubLocation , rlRevisionType , rlS3Location -- * LifecycleEventStatus , LifecycleEventStatus (..) -- * EC2TagFilter , EC2TagFilter , ec2TagFilter , ectfKey , ectfType , ectfValue -- * Diagnostics , Diagnostics , diagnostics , dErrorCode , dLogTail , dMessage , dScriptName -- * StopStatus , StopStatus (..) -- * ErrorInformation , ErrorInformation , errorInformation , eiCode , eiMessage -- * SortOrder , SortOrder (..) -- * DeploymentInfo , DeploymentInfo , deploymentInfo , diApplicationName , diCompleteTime , diCreateTime , diCreator , diDeploymentConfigName , diDeploymentGroupName , diDeploymentId , diDeploymentOverview , diDescription , diErrorInformation , diIgnoreApplicationStopFailures , diRevision , diStartTime , diStatus -- * LifecycleEvent , LifecycleEvent , lifecycleEvent , leDiagnostics , leEndTime , leLifecycleEventName , leStartTime , leStatus -- * DeploymentOverview , DeploymentOverview , deploymentOverview , doFailed , doInProgress , doPending , doSkipped , doSucceeded -- * ErrorCode , ErrorCode (..) -- * DeploymentConfigInfo , DeploymentConfigInfo , deploymentConfigInfo , dciCreateTime , dciDeploymentConfigId , dciDeploymentConfigName , dciMinimumHealthyHosts -- * InstanceStatus , InstanceStatus (..) -- * DeploymentStatus , DeploymentStatus (..) -- * S3Location , S3Location , s3Location , slBucket , slBundleType , slETag , slKey , slVersion -- * MinimumHealthyHostsType , MinimumHealthyHostsType (..) -- * GitHubLocation , GitHubLocation , gitHubLocation , ghlCommitId , ghlRepository -- * RevisionLocationType , RevisionLocationType (..) -- * EC2TagFilterType , EC2TagFilterType (..) ) where import Network.AWS.Prelude import Network.AWS.Signing import qualified GHC.Exts -- | Version @2014-10-06@ of the Amazon CodeDeploy service. data CodeDeploy instance AWSService CodeDeploy where type Sg CodeDeploy = V4 type Er CodeDeploy = JSONError service = service' where service' :: Service CodeDeploy service' = Service { _svcAbbrev = "CodeDeploy" , _svcPrefix = "codedeploy" , _svcVersion = "2014-10-06" , _svcTargetPrefix = Just "CodeDeploy_20141006" , _svcJSONVersion = Just "1.1" , _svcHandle = handle , _svcRetry = retry } handle :: Status -> Maybe (LazyByteString -> ServiceError JSONError) handle = jsonError statusSuccess service' retry :: Retry CodeDeploy retry = Exponential { _retryBase = 0.05 , _retryGrowth = 2 , _retryAttempts = 5 , _retryCheck = check } check :: Status -> JSONError -> Bool check (statusCode -> s) (awsErrorCode -> e) | s == 500 = True -- General Server Error | s == 509 = True -- Limit Exceeded | s == 503 = True -- Service Unavailable | otherwise = False data GenericRevisionInfo = GenericRevisionInfo { _griDeploymentGroups :: List "deploymentGroups" Text , _griDescription :: Maybe Text , _griFirstUsedTime :: Maybe POSIX , _griLastUsedTime :: Maybe POSIX , _griRegisterTime :: Maybe POSIX } deriving (Eq, Ord, Read, Show) -- | 'GenericRevisionInfo' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'griDeploymentGroups' @::@ ['Text'] -- -- * 'griDescription' @::@ 'Maybe' 'Text' -- -- * 'griFirstUsedTime' @::@ 'Maybe' 'UTCTime' -- -- * 'griLastUsedTime' @::@ 'Maybe' 'UTCTime' -- -- * 'griRegisterTime' @::@ 'Maybe' 'UTCTime' -- genericRevisionInfo :: GenericRevisionInfo genericRevisionInfo = GenericRevisionInfo { _griDescription = Nothing , _griDeploymentGroups = mempty , _griFirstUsedTime = Nothing , _griLastUsedTime = Nothing , _griRegisterTime = Nothing } -- | A list of deployment groups that use this revision. griDeploymentGroups :: Lens' GenericRevisionInfo [Text] griDeploymentGroups = lens _griDeploymentGroups (\s a -> s { _griDeploymentGroups = a }) . _List -- | A comment about the revision. griDescription :: Lens' GenericRevisionInfo (Maybe Text) griDescription = lens _griDescription (\s a -> s { _griDescription = a }) -- | When the revision was first used by AWS CodeDeploy. griFirstUsedTime :: Lens' GenericRevisionInfo (Maybe UTCTime) griFirstUsedTime = lens _griFirstUsedTime (\s a -> s { _griFirstUsedTime = a }) . mapping _Time -- | When the revision was last used by AWS CodeDeploy. griLastUsedTime :: Lens' GenericRevisionInfo (Maybe UTCTime) griLastUsedTime = lens _griLastUsedTime (\s a -> s { _griLastUsedTime = a }) . mapping _Time -- | When the revision was registered with AWS CodeDeploy. griRegisterTime :: Lens' GenericRevisionInfo (Maybe UTCTime) griRegisterTime = lens _griRegisterTime (\s a -> s { _griRegisterTime = a }) . mapping _Time instance FromJSON GenericRevisionInfo where parseJSON = withObject "GenericRevisionInfo" $ \o -> GenericRevisionInfo <$> o .:? "deploymentGroups" .!= mempty <*> o .:? "description" <*> o .:? "firstUsedTime" <*> o .:? "lastUsedTime" <*> o .:? "registerTime" instance ToJSON GenericRevisionInfo where toJSON GenericRevisionInfo{..} = object [ "description" .= _griDescription , "deploymentGroups" .= _griDeploymentGroups , "firstUsedTime" .= _griFirstUsedTime , "lastUsedTime" .= _griLastUsedTime , "registerTime" .= _griRegisterTime ] data ApplicationInfo = ApplicationInfo { _aiApplicationId :: Maybe Text , _aiApplicationName :: Maybe Text , _aiCreateTime :: Maybe POSIX , _aiLinkedToGitHub :: Maybe Bool } deriving (Eq, Ord, Read, Show) -- | 'ApplicationInfo' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'aiApplicationId' @::@ 'Maybe' 'Text' -- -- * 'aiApplicationName' @::@ 'Maybe' 'Text' -- -- * 'aiCreateTime' @::@ 'Maybe' 'UTCTime' -- -- * 'aiLinkedToGitHub' @::@ 'Maybe' 'Bool' -- applicationInfo :: ApplicationInfo applicationInfo = ApplicationInfo { _aiApplicationId = Nothing , _aiApplicationName = Nothing , _aiCreateTime = Nothing , _aiLinkedToGitHub = Nothing } -- | The application ID. aiApplicationId :: Lens' ApplicationInfo (Maybe Text) aiApplicationId = lens _aiApplicationId (\s a -> s { _aiApplicationId = a }) -- | The application name. aiApplicationName :: Lens' ApplicationInfo (Maybe Text) aiApplicationName = lens _aiApplicationName (\s a -> s { _aiApplicationName = a }) -- | The time that the application was created. aiCreateTime :: Lens' ApplicationInfo (Maybe UTCTime) aiCreateTime = lens _aiCreateTime (\s a -> s { _aiCreateTime = a }) . mapping _Time -- | True if the user has authenticated with GitHub for the specified application; -- otherwise, false. aiLinkedToGitHub :: Lens' ApplicationInfo (Maybe Bool) aiLinkedToGitHub = lens _aiLinkedToGitHub (\s a -> s { _aiLinkedToGitHub = a }) instance FromJSON ApplicationInfo where parseJSON = withObject "ApplicationInfo" $ \o -> ApplicationInfo <$> o .:? "applicationId" <*> o .:? "applicationName" <*> o .:? "createTime" <*> o .:? "linkedToGitHub" instance ToJSON ApplicationInfo where toJSON ApplicationInfo{..} = object [ "applicationId" .= _aiApplicationId , "applicationName" .= _aiApplicationName , "createTime" .= _aiCreateTime , "linkedToGitHub" .= _aiLinkedToGitHub ] data BundleType = Tar -- ^ tar | Tgz -- ^ tgz | Zip -- ^ zip deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable BundleType instance FromText BundleType where parser = takeLowerText >>= \case "tar" -> pure Tar "tgz" -> pure Tgz "zip" -> pure Zip e -> fail $ "Failure parsing BundleType from " ++ show e instance ToText BundleType where toText = \case Tar -> "tar" Tgz -> "tgz" Zip -> "zip" instance ToByteString BundleType instance ToHeader BundleType instance ToQuery BundleType instance FromJSON BundleType where parseJSON = parseJSONText "BundleType" instance ToJSON BundleType where toJSON = toJSONText data TimeRange = TimeRange { _trEnd :: Maybe POSIX , _trStart :: Maybe POSIX } deriving (Eq, Ord, Read, Show) -- | 'TimeRange' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'trEnd' @::@ 'Maybe' 'UTCTime' -- -- * 'trStart' @::@ 'Maybe' 'UTCTime' -- timeRange :: TimeRange timeRange = TimeRange { _trStart = Nothing , _trEnd = Nothing } -- | The time range's end time. -- -- Specify null to leave the time range's end time open-ended. trEnd :: Lens' TimeRange (Maybe UTCTime) trEnd = lens _trEnd (\s a -> s { _trEnd = a }) . mapping _Time -- | The time range's start time. -- -- Specify null to leave the time range's start time open-ended. trStart :: Lens' TimeRange (Maybe UTCTime) trStart = lens _trStart (\s a -> s { _trStart = a }) . mapping _Time instance FromJSON TimeRange where parseJSON = withObject "TimeRange" $ \o -> TimeRange <$> o .:? "end" <*> o .:? "start" instance ToJSON TimeRange where toJSON TimeRange{..} = object [ "start" .= _trStart , "end" .= _trEnd ] data DeploymentCreator = Autoscaling -- ^ autoscaling | User -- ^ user deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable DeploymentCreator instance FromText DeploymentCreator where parser = takeLowerText >>= \case "autoscaling" -> pure Autoscaling "user" -> pure User e -> fail $ "Failure parsing DeploymentCreator from " ++ show e instance ToText DeploymentCreator where toText = \case Autoscaling -> "autoscaling" User -> "user" instance ToByteString DeploymentCreator instance ToHeader DeploymentCreator instance ToQuery DeploymentCreator instance FromJSON DeploymentCreator where parseJSON = parseJSONText "DeploymentCreator" instance ToJSON DeploymentCreator where toJSON = toJSONText data InstanceSummary = InstanceSummary { _isDeploymentId :: Maybe Text , _isInstanceId :: Maybe Text , _isLastUpdatedAt :: Maybe POSIX , _isLifecycleEvents :: List "lifecycleEvents" LifecycleEvent , _isStatus :: Maybe InstanceStatus } deriving (Eq, Read, Show) -- | 'InstanceSummary' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'isDeploymentId' @::@ 'Maybe' 'Text' -- -- * 'isInstanceId' @::@ 'Maybe' 'Text' -- -- * 'isLastUpdatedAt' @::@ 'Maybe' 'UTCTime' -- -- * 'isLifecycleEvents' @::@ ['LifecycleEvent'] -- -- * 'isStatus' @::@ 'Maybe' 'InstanceStatus' -- instanceSummary :: InstanceSummary instanceSummary = InstanceSummary { _isDeploymentId = Nothing , _isInstanceId = Nothing , _isStatus = Nothing , _isLastUpdatedAt = Nothing , _isLifecycleEvents = mempty } -- | The deployment ID. isDeploymentId :: Lens' InstanceSummary (Maybe Text) isDeploymentId = lens _isDeploymentId (\s a -> s { _isDeploymentId = a }) -- | The instance ID. isInstanceId :: Lens' InstanceSummary (Maybe Text) isInstanceId = lens _isInstanceId (\s a -> s { _isInstanceId = a }) -- | A timestamp indicating when the instance information was last updated. isLastUpdatedAt :: Lens' InstanceSummary (Maybe UTCTime) isLastUpdatedAt = lens _isLastUpdatedAt (\s a -> s { _isLastUpdatedAt = a }) . mapping _Time -- | A list of lifecycle events for this instance. isLifecycleEvents :: Lens' InstanceSummary [LifecycleEvent] isLifecycleEvents = lens _isLifecycleEvents (\s a -> s { _isLifecycleEvents = a }) . _List -- | The deployment status for this instance: -- -- Pending: The deployment is pending for this instance. In Progress: The -- deployment is in progress for this instance. Succeeded: The deployment has -- succeeded for this instance. Failed: The deployment has failed for this -- instance. Skipped: The deployment has been skipped for this instance. Unknown: The deployment status is unknown for this instance. -- isStatus :: Lens' InstanceSummary (Maybe InstanceStatus) isStatus = lens _isStatus (\s a -> s { _isStatus = a }) instance FromJSON InstanceSummary where parseJSON = withObject "InstanceSummary" $ \o -> InstanceSummary <$> o .:? "deploymentId" <*> o .:? "instanceId" <*> o .:? "lastUpdatedAt" <*> o .:? "lifecycleEvents" .!= mempty <*> o .:? "status" instance ToJSON InstanceSummary where toJSON InstanceSummary{..} = object [ "deploymentId" .= _isDeploymentId , "instanceId" .= _isInstanceId , "status" .= _isStatus , "lastUpdatedAt" .= _isLastUpdatedAt , "lifecycleEvents" .= _isLifecycleEvents ] data AutoScalingGroup = AutoScalingGroup { _asgHook :: Maybe Text , _asgName :: Maybe Text } deriving (Eq, Ord, Read, Show) -- | 'AutoScalingGroup' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'asgHook' @::@ 'Maybe' 'Text' -- -- * 'asgName' @::@ 'Maybe' 'Text' -- autoScalingGroup :: AutoScalingGroup autoScalingGroup = AutoScalingGroup { _asgName = Nothing , _asgHook = Nothing } -- | An Auto Scaling lifecycle event hook name. asgHook :: Lens' AutoScalingGroup (Maybe Text) asgHook = lens _asgHook (\s a -> s { _asgHook = a }) -- | The Auto Scaling group name. asgName :: Lens' AutoScalingGroup (Maybe Text) asgName = lens _asgName (\s a -> s { _asgName = a }) instance FromJSON AutoScalingGroup where parseJSON = withObject "AutoScalingGroup" $ \o -> AutoScalingGroup <$> o .:? "hook" <*> o .:? "name" instance ToJSON AutoScalingGroup where toJSON AutoScalingGroup{..} = object [ "name" .= _asgName , "hook" .= _asgHook ] data DeploymentGroupInfo = DeploymentGroupInfo { _dgiApplicationName :: Maybe Text , _dgiAutoScalingGroups :: List "autoScalingGroups" AutoScalingGroup , _dgiDeploymentConfigName :: Maybe Text , _dgiDeploymentGroupId :: Maybe Text , _dgiDeploymentGroupName :: Maybe Text , _dgiEc2TagFilters :: List "ec2TagFilters" EC2TagFilter , _dgiServiceRoleArn :: Maybe Text , _dgiTargetRevision :: Maybe RevisionLocation } deriving (Eq, Read, Show) -- | 'DeploymentGroupInfo' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'dgiApplicationName' @::@ 'Maybe' 'Text' -- -- * 'dgiAutoScalingGroups' @::@ ['AutoScalingGroup'] -- -- * 'dgiDeploymentConfigName' @::@ 'Maybe' 'Text' -- -- * 'dgiDeploymentGroupId' @::@ 'Maybe' 'Text' -- -- * 'dgiDeploymentGroupName' @::@ 'Maybe' 'Text' -- -- * 'dgiEc2TagFilters' @::@ ['EC2TagFilter'] -- -- * 'dgiServiceRoleArn' @::@ 'Maybe' 'Text' -- -- * 'dgiTargetRevision' @::@ 'Maybe' 'RevisionLocation' -- deploymentGroupInfo :: DeploymentGroupInfo deploymentGroupInfo = DeploymentGroupInfo { _dgiApplicationName = Nothing , _dgiDeploymentGroupId = Nothing , _dgiDeploymentGroupName = Nothing , _dgiDeploymentConfigName = Nothing , _dgiEc2TagFilters = mempty , _dgiAutoScalingGroups = mempty , _dgiServiceRoleArn = Nothing , _dgiTargetRevision = Nothing } -- | The application name. dgiApplicationName :: Lens' DeploymentGroupInfo (Maybe Text) dgiApplicationName = lens _dgiApplicationName (\s a -> s { _dgiApplicationName = a }) -- | A list of associated Auto Scaling groups. dgiAutoScalingGroups :: Lens' DeploymentGroupInfo [AutoScalingGroup] dgiAutoScalingGroups = lens _dgiAutoScalingGroups (\s a -> s { _dgiAutoScalingGroups = a }) . _List -- | The deployment configuration name. dgiDeploymentConfigName :: Lens' DeploymentGroupInfo (Maybe Text) dgiDeploymentConfigName = lens _dgiDeploymentConfigName (\s a -> s { _dgiDeploymentConfigName = a }) -- | The deployment group ID. dgiDeploymentGroupId :: Lens' DeploymentGroupInfo (Maybe Text) dgiDeploymentGroupId = lens _dgiDeploymentGroupId (\s a -> s { _dgiDeploymentGroupId = a }) -- | The deployment group name. dgiDeploymentGroupName :: Lens' DeploymentGroupInfo (Maybe Text) dgiDeploymentGroupName = lens _dgiDeploymentGroupName (\s a -> s { _dgiDeploymentGroupName = a }) -- | The Amazon EC2 tags to filter on. dgiEc2TagFilters :: Lens' DeploymentGroupInfo [EC2TagFilter] dgiEc2TagFilters = lens _dgiEc2TagFilters (\s a -> s { _dgiEc2TagFilters = a }) . _List -- | A service role ARN. dgiServiceRoleArn :: Lens' DeploymentGroupInfo (Maybe Text) dgiServiceRoleArn = lens _dgiServiceRoleArn (\s a -> s { _dgiServiceRoleArn = a }) -- | Information about the deployment group's target revision, including the -- revision's type and its location. dgiTargetRevision :: Lens' DeploymentGroupInfo (Maybe RevisionLocation) dgiTargetRevision = lens _dgiTargetRevision (\s a -> s { _dgiTargetRevision = a }) instance FromJSON DeploymentGroupInfo where parseJSON = withObject "DeploymentGroupInfo" $ \o -> DeploymentGroupInfo <$> o .:? "applicationName" <*> o .:? "autoScalingGroups" .!= mempty <*> o .:? "deploymentConfigName" <*> o .:? "deploymentGroupId" <*> o .:? "deploymentGroupName" <*> o .:? "ec2TagFilters" .!= mempty <*> o .:? "serviceRoleArn" <*> o .:? "targetRevision" instance ToJSON DeploymentGroupInfo where toJSON DeploymentGroupInfo{..} = object [ "applicationName" .= _dgiApplicationName , "deploymentGroupId" .= _dgiDeploymentGroupId , "deploymentGroupName" .= _dgiDeploymentGroupName , "deploymentConfigName" .= _dgiDeploymentConfigName , "ec2TagFilters" .= _dgiEc2TagFilters , "autoScalingGroups" .= _dgiAutoScalingGroups , "serviceRoleArn" .= _dgiServiceRoleArn , "targetRevision" .= _dgiTargetRevision ] data ApplicationRevisionSortBy = FirstUsedTime -- ^ firstUsedTime | LastUsedTime -- ^ lastUsedTime | RegisterTime -- ^ registerTime deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable ApplicationRevisionSortBy instance FromText ApplicationRevisionSortBy where parser = takeLowerText >>= \case "firstusedtime" -> pure FirstUsedTime "lastusedtime" -> pure LastUsedTime "registertime" -> pure RegisterTime e -> fail $ "Failure parsing ApplicationRevisionSortBy from " ++ show e instance ToText ApplicationRevisionSortBy where toText = \case FirstUsedTime -> "firstUsedTime" LastUsedTime -> "lastUsedTime" RegisterTime -> "registerTime" instance ToByteString ApplicationRevisionSortBy instance ToHeader ApplicationRevisionSortBy instance ToQuery ApplicationRevisionSortBy instance FromJSON ApplicationRevisionSortBy where parseJSON = parseJSONText "ApplicationRevisionSortBy" instance ToJSON ApplicationRevisionSortBy where toJSON = toJSONText data MinimumHealthyHosts = MinimumHealthyHosts { _mhhType :: Maybe MinimumHealthyHostsType , _mhhValue :: Maybe Int } deriving (Eq, Read, Show) -- | 'MinimumHealthyHosts' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'mhhType' @::@ 'Maybe' 'MinimumHealthyHostsType' -- -- * 'mhhValue' @::@ 'Maybe' 'Int' -- minimumHealthyHosts :: MinimumHealthyHosts minimumHealthyHosts = MinimumHealthyHosts { _mhhValue = Nothing , _mhhType = Nothing } -- | The minimum healthy instances type: -- -- HOST_COUNT: The minimum number of healthy instances, as an absolute value. FLEET_PERCENT: The minimum number of healthy instances, as a percentage of the total number of instances in the deployment. -- For example, for 9 Amazon EC2 instances, if a HOST_COUNT of 6 is specified, -- deploy to up to 3 instances at a time. The deployment succeeds if 6 or more -- instances are successfully deployed to; otherwise, the deployment fails. If a -- FLEET_PERCENT of 40 is specified, deploy to up to 5 instances at a time. The -- deployment succeeds if 4 or more instances are successfully deployed to; -- otherwise, the deployment fails. -- -- In a call to the get deployment configuration operation, -- CodeDeployDefault.OneAtATime will return a minimum healthy instances type of -- MOST_CONCURRENCY and a value of 1. This means a deployment to only one Amazon -- EC2 instance at a time. (You cannot set the type to MOST_CONCURRENCY, only to -- HOST_COUNT or FLEET_PERCENT.) mhhType :: Lens' MinimumHealthyHosts (Maybe MinimumHealthyHostsType) mhhType = lens _mhhType (\s a -> s { _mhhType = a }) -- | The minimum healthy instances value. mhhValue :: Lens' MinimumHealthyHosts (Maybe Int) mhhValue = lens _mhhValue (\s a -> s { _mhhValue = a }) instance FromJSON MinimumHealthyHosts where parseJSON = withObject "MinimumHealthyHosts" $ \o -> MinimumHealthyHosts <$> o .:? "type" <*> o .:? "value" instance ToJSON MinimumHealthyHosts where toJSON MinimumHealthyHosts{..} = object [ "value" .= _mhhValue , "type" .= _mhhType ] data ListStateFilterAction = Exclude -- ^ exclude | Ignore -- ^ ignore | Include -- ^ include deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable ListStateFilterAction instance FromText ListStateFilterAction where parser = takeLowerText >>= \case "exclude" -> pure Exclude "ignore" -> pure Ignore "include" -> pure Include e -> fail $ "Failure parsing ListStateFilterAction from " ++ show e instance ToText ListStateFilterAction where toText = \case Exclude -> "exclude" Ignore -> "ignore" Include -> "include" instance ToByteString ListStateFilterAction instance ToHeader ListStateFilterAction instance ToQuery ListStateFilterAction instance FromJSON ListStateFilterAction where parseJSON = parseJSONText "ListStateFilterAction" instance ToJSON ListStateFilterAction where toJSON = toJSONText data LifecycleErrorCode = ScriptFailed -- ^ ScriptFailed | ScriptMissing -- ^ ScriptMissing | ScriptNotExecutable -- ^ ScriptNotExecutable | ScriptTimedOut -- ^ ScriptTimedOut | Success -- ^ Success | UnknownError -- ^ UnknownError deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable LifecycleErrorCode instance FromText LifecycleErrorCode where parser = takeLowerText >>= \case "scriptfailed" -> pure ScriptFailed "scriptmissing" -> pure ScriptMissing "scriptnotexecutable" -> pure ScriptNotExecutable "scripttimedout" -> pure ScriptTimedOut "success" -> pure Success "unknownerror" -> pure UnknownError e -> fail $ "Failure parsing LifecycleErrorCode from " ++ show e instance ToText LifecycleErrorCode where toText = \case ScriptFailed -> "ScriptFailed" ScriptMissing -> "ScriptMissing" ScriptNotExecutable -> "ScriptNotExecutable" ScriptTimedOut -> "ScriptTimedOut" Success -> "Success" UnknownError -> "UnknownError" instance ToByteString LifecycleErrorCode instance ToHeader LifecycleErrorCode instance ToQuery LifecycleErrorCode instance FromJSON LifecycleErrorCode where parseJSON = parseJSONText "LifecycleErrorCode" instance ToJSON LifecycleErrorCode where toJSON = toJSONText data RevisionLocation = RevisionLocation { _rlGitHubLocation :: Maybe GitHubLocation , _rlRevisionType :: Maybe RevisionLocationType , _rlS3Location :: Maybe S3Location } deriving (Eq, Read, Show) -- | 'RevisionLocation' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'rlGitHubLocation' @::@ 'Maybe' 'GitHubLocation' -- -- * 'rlRevisionType' @::@ 'Maybe' 'RevisionLocationType' -- -- * 'rlS3Location' @::@ 'Maybe' 'S3Location' -- revisionLocation :: RevisionLocation revisionLocation = RevisionLocation { _rlRevisionType = Nothing , _rlS3Location = Nothing , _rlGitHubLocation = Nothing } rlGitHubLocation :: Lens' RevisionLocation (Maybe GitHubLocation) rlGitHubLocation = lens _rlGitHubLocation (\s a -> s { _rlGitHubLocation = a }) -- | The application revision's type: -- -- S3: An application revision stored in Amazon S3. GitHub: An application -- revision stored in GitHub. rlRevisionType :: Lens' RevisionLocation (Maybe RevisionLocationType) rlRevisionType = lens _rlRevisionType (\s a -> s { _rlRevisionType = a }) rlS3Location :: Lens' RevisionLocation (Maybe S3Location) rlS3Location = lens _rlS3Location (\s a -> s { _rlS3Location = a }) instance FromJSON RevisionLocation where parseJSON = withObject "RevisionLocation" $ \o -> RevisionLocation <$> o .:? "gitHubLocation" <*> o .:? "revisionType" <*> o .:? "s3Location" instance ToJSON RevisionLocation where toJSON RevisionLocation{..} = object [ "revisionType" .= _rlRevisionType , "s3Location" .= _rlS3Location , "gitHubLocation" .= _rlGitHubLocation ] data LifecycleEventStatus = Failed -- ^ Failed | InProgress -- ^ InProgress | Pending -- ^ Pending | Skipped -- ^ Skipped | Succeeded -- ^ Succeeded | Unknown -- ^ Unknown deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable LifecycleEventStatus instance FromText LifecycleEventStatus where parser = takeLowerText >>= \case "failed" -> pure Failed "inprogress" -> pure InProgress "pending" -> pure Pending "skipped" -> pure Skipped "succeeded" -> pure Succeeded "unknown" -> pure Unknown e -> fail $ "Failure parsing LifecycleEventStatus from " ++ show e instance ToText LifecycleEventStatus where toText = \case Failed -> "Failed" InProgress -> "InProgress" Pending -> "Pending" Skipped -> "Skipped" Succeeded -> "Succeeded" Unknown -> "Unknown" instance ToByteString LifecycleEventStatus instance ToHeader LifecycleEventStatus instance ToQuery LifecycleEventStatus instance FromJSON LifecycleEventStatus where parseJSON = parseJSONText "LifecycleEventStatus" instance ToJSON LifecycleEventStatus where toJSON = toJSONText data EC2TagFilter = EC2TagFilter { _ectfKey :: Maybe Text , _ectfType :: Maybe EC2TagFilterType , _ectfValue :: Maybe Text } deriving (Eq, Read, Show) -- | 'EC2TagFilter' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'ectfKey' @::@ 'Maybe' 'Text' -- -- * 'ectfType' @::@ 'Maybe' 'EC2TagFilterType' -- -- * 'ectfValue' @::@ 'Maybe' 'Text' -- ec2TagFilter :: EC2TagFilter ec2TagFilter = EC2TagFilter { _ectfKey = Nothing , _ectfValue = Nothing , _ectfType = Nothing } -- | The Amazon EC2 tag filter key. ectfKey :: Lens' EC2TagFilter (Maybe Text) ectfKey = lens _ectfKey (\s a -> s { _ectfKey = a }) -- | The Amazon EC2 tag filter type: -- -- KEY_ONLY: Key only. VALUE_ONLY: Value only. KEY_AND_VALUE: Key and value. ectfType :: Lens' EC2TagFilter (Maybe EC2TagFilterType) ectfType = lens _ectfType (\s a -> s { _ectfType = a }) -- | The Amazon EC2 tag filter value. ectfValue :: Lens' EC2TagFilter (Maybe Text) ectfValue = lens _ectfValue (\s a -> s { _ectfValue = a }) instance FromJSON EC2TagFilter where parseJSON = withObject "EC2TagFilter" $ \o -> EC2TagFilter <$> o .:? "Key" <*> o .:? "Type" <*> o .:? "Value" instance ToJSON EC2TagFilter where toJSON EC2TagFilter{..} = object [ "Key" .= _ectfKey , "Value" .= _ectfValue , "Type" .= _ectfType ] data Diagnostics = Diagnostics { _dErrorCode :: Maybe LifecycleErrorCode , _dLogTail :: Maybe Text , _dMessage :: Maybe Text , _dScriptName :: Maybe Text } deriving (Eq, Read, Show) -- | 'Diagnostics' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'dErrorCode' @::@ 'Maybe' 'LifecycleErrorCode' -- -- * 'dLogTail' @::@ 'Maybe' 'Text' -- -- * 'dMessage' @::@ 'Maybe' 'Text' -- -- * 'dScriptName' @::@ 'Maybe' 'Text' -- diagnostics :: Diagnostics diagnostics = Diagnostics { _dErrorCode = Nothing , _dScriptName = Nothing , _dMessage = Nothing , _dLogTail = Nothing } -- | The associated error code: -- -- Success: The specified script ran. ScriptMissing: The specified script was -- not found in the specified location. ScriptNotExecutable: The specified -- script is not a recognized executable file type. ScriptTimedOut: The -- specified script did not finish running in the specified time period. ScriptFailed: The specified script failed to run as expected. -- UnknownError: The specified script did not run for an unknown reason. dErrorCode :: Lens' Diagnostics (Maybe LifecycleErrorCode) dErrorCode = lens _dErrorCode (\s a -> s { _dErrorCode = a }) -- | The last portion of the associated diagnostic log. dLogTail :: Lens' Diagnostics (Maybe Text) dLogTail = lens _dLogTail (\s a -> s { _dLogTail = a }) -- | The message associated with the error. dMessage :: Lens' Diagnostics (Maybe Text) dMessage = lens _dMessage (\s a -> s { _dMessage = a }) -- | The name of the script. dScriptName :: Lens' Diagnostics (Maybe Text) dScriptName = lens _dScriptName (\s a -> s { _dScriptName = a }) instance FromJSON Diagnostics where parseJSON = withObject "Diagnostics" $ \o -> Diagnostics <$> o .:? "errorCode" <*> o .:? "logTail" <*> o .:? "message" <*> o .:? "scriptName" instance ToJSON Diagnostics where toJSON Diagnostics{..} = object [ "errorCode" .= _dErrorCode , "scriptName" .= _dScriptName , "message" .= _dMessage , "logTail" .= _dLogTail ] data StopStatus = SSPending -- ^ Pending | SSSucceeded -- ^ Succeeded deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable StopStatus instance FromText StopStatus where parser = takeLowerText >>= \case "pending" -> pure SSPending "succeeded" -> pure SSSucceeded e -> fail $ "Failure parsing StopStatus from " ++ show e instance ToText StopStatus where toText = \case SSPending -> "Pending" SSSucceeded -> "Succeeded" instance ToByteString StopStatus instance ToHeader StopStatus instance ToQuery StopStatus instance FromJSON StopStatus where parseJSON = parseJSONText "StopStatus" instance ToJSON StopStatus where toJSON = toJSONText data ErrorInformation = ErrorInformation { _eiCode :: Maybe ErrorCode , _eiMessage :: Maybe Text } deriving (Eq, Read, Show) -- | 'ErrorInformation' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'eiCode' @::@ 'Maybe' 'ErrorCode' -- -- * 'eiMessage' @::@ 'Maybe' 'Text' -- errorInformation :: ErrorInformation errorInformation = ErrorInformation { _eiCode = Nothing , _eiMessage = Nothing } -- | The error code: -- -- APPLICATION_MISSING: The application was missing. Note that this error code -- will most likely be raised if the application is deleted after the deployment -- is created but before it starts. DEPLOYMENT_GROUP_MISSING: The deployment -- group was missing. Note that this error code will most likely be raised if -- the deployment group is deleted after the deployment is created but before it -- starts. REVISION_MISSING: The revision ID was missing. Note that this error -- code will most likely be raised if the revision is deleted after the -- deployment is created but before it starts. IAM_ROLE_MISSING: The service -- role cannot be accessed. IAM_ROLE_PERMISSIONS: The service role does not have -- the correct permissions. OVER_MAX_INSTANCES: The maximum number of instances -- was exceeded. NO_INSTANCES: No instances were specified, or no instances can -- be found. TIMEOUT: The deployment has timed out. HEALTH_CONSTRAINTS_INVALID: -- The revision can never successfully deploy under the instance health -- constraints as specified. HEALTH_CONSTRAINTS: The deployment failed on too -- many instances to be able to successfully deploy under the specified instance -- health constraints. INTERNAL_ERROR: There was an internal error. eiCode :: Lens' ErrorInformation (Maybe ErrorCode) eiCode = lens _eiCode (\s a -> s { _eiCode = a }) -- | An accompanying error message. eiMessage :: Lens' ErrorInformation (Maybe Text) eiMessage = lens _eiMessage (\s a -> s { _eiMessage = a }) instance FromJSON ErrorInformation where parseJSON = withObject "ErrorInformation" $ \o -> ErrorInformation <$> o .:? "code" <*> o .:? "message" instance ToJSON ErrorInformation where toJSON ErrorInformation{..} = object [ "code" .= _eiCode , "message" .= _eiMessage ] data SortOrder = Ascending -- ^ ascending | Descending -- ^ descending deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable SortOrder instance FromText SortOrder where parser = takeLowerText >>= \case "ascending" -> pure Ascending "descending" -> pure Descending e -> fail $ "Failure parsing SortOrder from " ++ show e instance ToText SortOrder where toText = \case Ascending -> "ascending" Descending -> "descending" instance ToByteString SortOrder instance ToHeader SortOrder instance ToQuery SortOrder instance FromJSON SortOrder where parseJSON = parseJSONText "SortOrder" instance ToJSON SortOrder where toJSON = toJSONText data DeploymentInfo = DeploymentInfo { _diApplicationName :: Maybe Text , _diCompleteTime :: Maybe POSIX , _diCreateTime :: Maybe POSIX , _diCreator :: Maybe DeploymentCreator , _diDeploymentConfigName :: Maybe Text , _diDeploymentGroupName :: Maybe Text , _diDeploymentId :: Maybe Text , _diDeploymentOverview :: Maybe DeploymentOverview , _diDescription :: Maybe Text , _diErrorInformation :: Maybe ErrorInformation , _diIgnoreApplicationStopFailures :: Maybe Bool , _diRevision :: Maybe RevisionLocation , _diStartTime :: Maybe POSIX , _diStatus :: Maybe DeploymentStatus } deriving (Eq, Read, Show) -- | 'DeploymentInfo' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'diApplicationName' @::@ 'Maybe' 'Text' -- -- * 'diCompleteTime' @::@ 'Maybe' 'UTCTime' -- -- * 'diCreateTime' @::@ 'Maybe' 'UTCTime' -- -- * 'diCreator' @::@ 'Maybe' 'DeploymentCreator' -- -- * 'diDeploymentConfigName' @::@ 'Maybe' 'Text' -- -- * 'diDeploymentGroupName' @::@ 'Maybe' 'Text' -- -- * 'diDeploymentId' @::@ 'Maybe' 'Text' -- -- * 'diDeploymentOverview' @::@ 'Maybe' 'DeploymentOverview' -- -- * 'diDescription' @::@ 'Maybe' 'Text' -- -- * 'diErrorInformation' @::@ 'Maybe' 'ErrorInformation' -- -- * 'diIgnoreApplicationStopFailures' @::@ 'Maybe' 'Bool' -- -- * 'diRevision' @::@ 'Maybe' 'RevisionLocation' -- -- * 'diStartTime' @::@ 'Maybe' 'UTCTime' -- -- * 'diStatus' @::@ 'Maybe' 'DeploymentStatus' -- deploymentInfo :: DeploymentInfo deploymentInfo = DeploymentInfo { _diApplicationName = Nothing , _diDeploymentGroupName = Nothing , _diDeploymentConfigName = Nothing , _diDeploymentId = Nothing , _diRevision = Nothing , _diStatus = Nothing , _diErrorInformation = Nothing , _diCreateTime = Nothing , _diStartTime = Nothing , _diCompleteTime = Nothing , _diDeploymentOverview = Nothing , _diDescription = Nothing , _diCreator = Nothing , _diIgnoreApplicationStopFailures = Nothing } -- | The application name. diApplicationName :: Lens' DeploymentInfo (Maybe Text) diApplicationName = lens _diApplicationName (\s a -> s { _diApplicationName = a }) -- | A timestamp indicating when the deployment was completed. diCompleteTime :: Lens' DeploymentInfo (Maybe UTCTime) diCompleteTime = lens _diCompleteTime (\s a -> s { _diCompleteTime = a }) . mapping _Time -- | A timestamp indicating when the deployment was created. diCreateTime :: Lens' DeploymentInfo (Maybe UTCTime) diCreateTime = lens _diCreateTime (\s a -> s { _diCreateTime = a }) . mapping _Time -- | How the deployment was created: -- -- user: A user created the deployment. autoscaling: Auto Scaling created the -- deployment. diCreator :: Lens' DeploymentInfo (Maybe DeploymentCreator) diCreator = lens _diCreator (\s a -> s { _diCreator = a }) -- | The deployment configuration name. diDeploymentConfigName :: Lens' DeploymentInfo (Maybe Text) diDeploymentConfigName = lens _diDeploymentConfigName (\s a -> s { _diDeploymentConfigName = a }) -- | The deployment group name. diDeploymentGroupName :: Lens' DeploymentInfo (Maybe Text) diDeploymentGroupName = lens _diDeploymentGroupName (\s a -> s { _diDeploymentGroupName = a }) -- | The deployment ID. diDeploymentId :: Lens' DeploymentInfo (Maybe Text) diDeploymentId = lens _diDeploymentId (\s a -> s { _diDeploymentId = a }) -- | A summary of the deployment status of the instances in the deployment. diDeploymentOverview :: Lens' DeploymentInfo (Maybe DeploymentOverview) diDeploymentOverview = lens _diDeploymentOverview (\s a -> s { _diDeploymentOverview = a }) -- | A comment about the deployment. diDescription :: Lens' DeploymentInfo (Maybe Text) diDescription = lens _diDescription (\s a -> s { _diDescription = a }) -- | Information about any error associated with this deployment. diErrorInformation :: Lens' DeploymentInfo (Maybe ErrorInformation) diErrorInformation = lens _diErrorInformation (\s a -> s { _diErrorInformation = a }) -- | If true, then if the deployment causes the ApplicationStop deployment -- lifecycle event to fail to a specific instance, the deployment will not be -- considered to have failed to that instance at that point and will continue on -- to the BeforeInstall deployment lifecycle event. -- -- If false or not specified, then if the deployment causes the ApplicationStop -- deployment lifecycle event to fail to a specific instance, the deployment -- will stop to that instance, and the deployment to that instance will be -- considered to have failed. diIgnoreApplicationStopFailures :: Lens' DeploymentInfo (Maybe Bool) diIgnoreApplicationStopFailures = lens _diIgnoreApplicationStopFailures (\s a -> s { _diIgnoreApplicationStopFailures = a }) -- | Information about the location of application artifacts that are stored and -- the service to retrieve them from. diRevision :: Lens' DeploymentInfo (Maybe RevisionLocation) diRevision = lens _diRevision (\s a -> s { _diRevision = a }) -- | A timestamp indicating when the deployment began deploying to the deployment -- group. -- -- Note that in some cases, the reported value of the start time may be later -- than the complete time. This is due to differences in the clock settings of -- various back-end servers that participate in the overall deployment process. diStartTime :: Lens' DeploymentInfo (Maybe UTCTime) diStartTime = lens _diStartTime (\s a -> s { _diStartTime = a }) . mapping _Time -- | The current state of the deployment as a whole. diStatus :: Lens' DeploymentInfo (Maybe DeploymentStatus) diStatus = lens _diStatus (\s a -> s { _diStatus = a }) instance FromJSON DeploymentInfo where parseJSON = withObject "DeploymentInfo" $ \o -> DeploymentInfo <$> o .:? "applicationName" <*> o .:? "completeTime" <*> o .:? "createTime" <*> o .:? "creator" <*> o .:? "deploymentConfigName" <*> o .:? "deploymentGroupName" <*> o .:? "deploymentId" <*> o .:? "deploymentOverview" <*> o .:? "description" <*> o .:? "errorInformation" <*> o .:? "ignoreApplicationStopFailures" <*> o .:? "revision" <*> o .:? "startTime" <*> o .:? "status" instance ToJSON DeploymentInfo where toJSON DeploymentInfo{..} = object [ "applicationName" .= _diApplicationName , "deploymentGroupName" .= _diDeploymentGroupName , "deploymentConfigName" .= _diDeploymentConfigName , "deploymentId" .= _diDeploymentId , "revision" .= _diRevision , "status" .= _diStatus , "errorInformation" .= _diErrorInformation , "createTime" .= _diCreateTime , "startTime" .= _diStartTime , "completeTime" .= _diCompleteTime , "deploymentOverview" .= _diDeploymentOverview , "description" .= _diDescription , "creator" .= _diCreator , "ignoreApplicationStopFailures" .= _diIgnoreApplicationStopFailures ] data LifecycleEvent = LifecycleEvent { _leDiagnostics :: Maybe Diagnostics , _leEndTime :: Maybe POSIX , _leLifecycleEventName :: Maybe Text , _leStartTime :: Maybe POSIX , _leStatus :: Maybe LifecycleEventStatus } deriving (Eq, Read, Show) -- | 'LifecycleEvent' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'leDiagnostics' @::@ 'Maybe' 'Diagnostics' -- -- * 'leEndTime' @::@ 'Maybe' 'UTCTime' -- -- * 'leLifecycleEventName' @::@ 'Maybe' 'Text' -- -- * 'leStartTime' @::@ 'Maybe' 'UTCTime' -- -- * 'leStatus' @::@ 'Maybe' 'LifecycleEventStatus' -- lifecycleEvent :: LifecycleEvent lifecycleEvent = LifecycleEvent { _leLifecycleEventName = Nothing , _leDiagnostics = Nothing , _leStartTime = Nothing , _leEndTime = Nothing , _leStatus = Nothing } -- | Diagnostic information about the deployment lifecycle event. leDiagnostics :: Lens' LifecycleEvent (Maybe Diagnostics) leDiagnostics = lens _leDiagnostics (\s a -> s { _leDiagnostics = a }) -- | A timestamp indicating when the deployment lifecycle event ended. leEndTime :: Lens' LifecycleEvent (Maybe UTCTime) leEndTime = lens _leEndTime (\s a -> s { _leEndTime = a }) . mapping _Time -- | The deployment lifecycle event name, such as ApplicationStop, BeforeInstall, -- AfterInstall, ApplicationStart, or ValidateService. leLifecycleEventName :: Lens' LifecycleEvent (Maybe Text) leLifecycleEventName = lens _leLifecycleEventName (\s a -> s { _leLifecycleEventName = a }) -- | A timestamp indicating when the deployment lifecycle event started. leStartTime :: Lens' LifecycleEvent (Maybe UTCTime) leStartTime = lens _leStartTime (\s a -> s { _leStartTime = a }) . mapping _Time -- | The deployment lifecycle event status: -- -- Pending: The deployment lifecycle event is pending. InProgress: The -- deployment lifecycle event is in progress. Succeeded: The deployment -- lifecycle event has succeeded. Failed: The deployment lifecycle event has -- failed. Skipped: The deployment lifecycle event has been skipped. Unknown: -- The deployment lifecycle event is unknown. leStatus :: Lens' LifecycleEvent (Maybe LifecycleEventStatus) leStatus = lens _leStatus (\s a -> s { _leStatus = a }) instance FromJSON LifecycleEvent where parseJSON = withObject "LifecycleEvent" $ \o -> LifecycleEvent <$> o .:? "diagnostics" <*> o .:? "endTime" <*> o .:? "lifecycleEventName" <*> o .:? "startTime" <*> o .:? "status" instance ToJSON LifecycleEvent where toJSON LifecycleEvent{..} = object [ "lifecycleEventName" .= _leLifecycleEventName , "diagnostics" .= _leDiagnostics , "startTime" .= _leStartTime , "endTime" .= _leEndTime , "status" .= _leStatus ] data DeploymentOverview = DeploymentOverview { _doFailed :: Maybe Integer , _doInProgress :: Maybe Integer , _doPending :: Maybe Integer , _doSkipped :: Maybe Integer , _doSucceeded :: Maybe Integer } deriving (Eq, Ord, Read, Show) -- | 'DeploymentOverview' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'doFailed' @::@ 'Maybe' 'Integer' -- -- * 'doInProgress' @::@ 'Maybe' 'Integer' -- -- * 'doPending' @::@ 'Maybe' 'Integer' -- -- * 'doSkipped' @::@ 'Maybe' 'Integer' -- -- * 'doSucceeded' @::@ 'Maybe' 'Integer' -- deploymentOverview :: DeploymentOverview deploymentOverview = DeploymentOverview { _doPending = Nothing , _doInProgress = Nothing , _doSucceeded = Nothing , _doFailed = Nothing , _doSkipped = Nothing } -- | The number of instances that have failed in the deployment. doFailed :: Lens' DeploymentOverview (Maybe Integer) doFailed = lens _doFailed (\s a -> s { _doFailed = a }) -- | The number of instances that are in progress in the deployment. doInProgress :: Lens' DeploymentOverview (Maybe Integer) doInProgress = lens _doInProgress (\s a -> s { _doInProgress = a }) -- | The number of instances that are pending in the deployment. doPending :: Lens' DeploymentOverview (Maybe Integer) doPending = lens _doPending (\s a -> s { _doPending = a }) -- | The number of instances that have been skipped in the deployment. doSkipped :: Lens' DeploymentOverview (Maybe Integer) doSkipped = lens _doSkipped (\s a -> s { _doSkipped = a }) -- | The number of instances that have succeeded in the deployment. doSucceeded :: Lens' DeploymentOverview (Maybe Integer) doSucceeded = lens _doSucceeded (\s a -> s { _doSucceeded = a }) instance FromJSON DeploymentOverview where parseJSON = withObject "DeploymentOverview" $ \o -> DeploymentOverview <$> o .:? "Failed" <*> o .:? "InProgress" <*> o .:? "Pending" <*> o .:? "Skipped" <*> o .:? "Succeeded" instance ToJSON DeploymentOverview where toJSON DeploymentOverview{..} = object [ "Pending" .= _doPending , "InProgress" .= _doInProgress , "Succeeded" .= _doSucceeded , "Failed" .= _doFailed , "Skipped" .= _doSkipped ] data ErrorCode = ApplicationMissing -- ^ APPLICATION_MISSING | DeploymentGroupMissing -- ^ DEPLOYMENT_GROUP_MISSING | HealthConstraints -- ^ HEALTH_CONSTRAINTS | HealthConstraintsInvalid -- ^ HEALTH_CONSTRAINTS_INVALID | IamRoleMissing -- ^ IAM_ROLE_MISSING | IamRolePermissions -- ^ IAM_ROLE_PERMISSIONS | InternalError -- ^ INTERNAL_ERROR | NoInstances -- ^ NO_INSTANCES | OverMaxInstances -- ^ OVER_MAX_INSTANCES | RevisionMissing -- ^ REVISION_MISSING | Timeout -- ^ TIMEOUT deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable ErrorCode instance FromText ErrorCode where parser = takeLowerText >>= \case "application_missing" -> pure ApplicationMissing "deployment_group_missing" -> pure DeploymentGroupMissing "health_constraints" -> pure HealthConstraints "health_constraints_invalid" -> pure HealthConstraintsInvalid "iam_role_missing" -> pure IamRoleMissing "iam_role_permissions" -> pure IamRolePermissions "internal_error" -> pure InternalError "no_instances" -> pure NoInstances "over_max_instances" -> pure OverMaxInstances "revision_missing" -> pure RevisionMissing "timeout" -> pure Timeout e -> fail $ "Failure parsing ErrorCode from " ++ show e instance ToText ErrorCode where toText = \case ApplicationMissing -> "APPLICATION_MISSING" DeploymentGroupMissing -> "DEPLOYMENT_GROUP_MISSING" HealthConstraints -> "HEALTH_CONSTRAINTS" HealthConstraintsInvalid -> "HEALTH_CONSTRAINTS_INVALID" IamRoleMissing -> "IAM_ROLE_MISSING" IamRolePermissions -> "IAM_ROLE_PERMISSIONS" InternalError -> "INTERNAL_ERROR" NoInstances -> "NO_INSTANCES" OverMaxInstances -> "OVER_MAX_INSTANCES" RevisionMissing -> "REVISION_MISSING" Timeout -> "TIMEOUT" instance ToByteString ErrorCode instance ToHeader ErrorCode instance ToQuery ErrorCode instance FromJSON ErrorCode where parseJSON = parseJSONText "ErrorCode" instance ToJSON ErrorCode where toJSON = toJSONText data DeploymentConfigInfo = DeploymentConfigInfo { _dciCreateTime :: Maybe POSIX , _dciDeploymentConfigId :: Maybe Text , _dciDeploymentConfigName :: Maybe Text , _dciMinimumHealthyHosts :: Maybe MinimumHealthyHosts } deriving (Eq, Read, Show) -- | 'DeploymentConfigInfo' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'dciCreateTime' @::@ 'Maybe' 'UTCTime' -- -- * 'dciDeploymentConfigId' @::@ 'Maybe' 'Text' -- -- * 'dciDeploymentConfigName' @::@ 'Maybe' 'Text' -- -- * 'dciMinimumHealthyHosts' @::@ 'Maybe' 'MinimumHealthyHosts' -- deploymentConfigInfo :: DeploymentConfigInfo deploymentConfigInfo = DeploymentConfigInfo { _dciDeploymentConfigId = Nothing , _dciDeploymentConfigName = Nothing , _dciMinimumHealthyHosts = Nothing , _dciCreateTime = Nothing } -- | The time that the deployment configuration was created. dciCreateTime :: Lens' DeploymentConfigInfo (Maybe UTCTime) dciCreateTime = lens _dciCreateTime (\s a -> s { _dciCreateTime = a }) . mapping _Time -- | The deployment configuration ID. dciDeploymentConfigId :: Lens' DeploymentConfigInfo (Maybe Text) dciDeploymentConfigId = lens _dciDeploymentConfigId (\s a -> s { _dciDeploymentConfigId = a }) -- | The deployment configuration name. dciDeploymentConfigName :: Lens' DeploymentConfigInfo (Maybe Text) dciDeploymentConfigName = lens _dciDeploymentConfigName (\s a -> s { _dciDeploymentConfigName = a }) -- | Information about the number or percentage of minimum healthy instances. dciMinimumHealthyHosts :: Lens' DeploymentConfigInfo (Maybe MinimumHealthyHosts) dciMinimumHealthyHosts = lens _dciMinimumHealthyHosts (\s a -> s { _dciMinimumHealthyHosts = a }) instance FromJSON DeploymentConfigInfo where parseJSON = withObject "DeploymentConfigInfo" $ \o -> DeploymentConfigInfo <$> o .:? "createTime" <*> o .:? "deploymentConfigId" <*> o .:? "deploymentConfigName" <*> o .:? "minimumHealthyHosts" instance ToJSON DeploymentConfigInfo where toJSON DeploymentConfigInfo{..} = object [ "deploymentConfigId" .= _dciDeploymentConfigId , "deploymentConfigName" .= _dciDeploymentConfigName , "minimumHealthyHosts" .= _dciMinimumHealthyHosts , "createTime" .= _dciCreateTime ] data InstanceStatus = ISFailed -- ^ Failed | ISInProgress -- ^ InProgress | ISPending -- ^ Pending | ISSkipped -- ^ Skipped | ISSucceeded -- ^ Succeeded | ISUnknown -- ^ Unknown deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable InstanceStatus instance FromText InstanceStatus where parser = takeLowerText >>= \case "failed" -> pure ISFailed "inprogress" -> pure ISInProgress "pending" -> pure ISPending "skipped" -> pure ISSkipped "succeeded" -> pure ISSucceeded "unknown" -> pure ISUnknown e -> fail $ "Failure parsing InstanceStatus from " ++ show e instance ToText InstanceStatus where toText = \case ISFailed -> "Failed" ISInProgress -> "InProgress" ISPending -> "Pending" ISSkipped -> "Skipped" ISSucceeded -> "Succeeded" ISUnknown -> "Unknown" instance ToByteString InstanceStatus instance ToHeader InstanceStatus instance ToQuery InstanceStatus instance FromJSON InstanceStatus where parseJSON = parseJSONText "InstanceStatus" instance ToJSON InstanceStatus where toJSON = toJSONText data DeploymentStatus = DSCreated -- ^ Created | DSFailed -- ^ Failed | DSInProgress -- ^ InProgress | DSQueued -- ^ Queued | DSStopped -- ^ Stopped | DSSucceeded -- ^ Succeeded deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable DeploymentStatus instance FromText DeploymentStatus where parser = takeLowerText >>= \case "created" -> pure DSCreated "failed" -> pure DSFailed "inprogress" -> pure DSInProgress "queued" -> pure DSQueued "stopped" -> pure DSStopped "succeeded" -> pure DSSucceeded e -> fail $ "Failure parsing DeploymentStatus from " ++ show e instance ToText DeploymentStatus where toText = \case DSCreated -> "Created" DSFailed -> "Failed" DSInProgress -> "InProgress" DSQueued -> "Queued" DSStopped -> "Stopped" DSSucceeded -> "Succeeded" instance ToByteString DeploymentStatus instance ToHeader DeploymentStatus instance ToQuery DeploymentStatus instance FromJSON DeploymentStatus where parseJSON = parseJSONText "DeploymentStatus" instance ToJSON DeploymentStatus where toJSON = toJSONText data S3Location = S3Location { _slBucket :: Maybe Text , _slBundleType :: Maybe BundleType , _slETag :: Maybe Text , _slKey :: Maybe Text , _slVersion :: Maybe Text } deriving (Eq, Read, Show) -- | 'S3Location' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'slBucket' @::@ 'Maybe' 'Text' -- -- * 'slBundleType' @::@ 'Maybe' 'BundleType' -- -- * 'slETag' @::@ 'Maybe' 'Text' -- -- * 'slKey' @::@ 'Maybe' 'Text' -- -- * 'slVersion' @::@ 'Maybe' 'Text' -- s3Location :: S3Location s3Location = S3Location { _slBucket = Nothing , _slKey = Nothing , _slBundleType = Nothing , _slVersion = Nothing , _slETag = Nothing } -- | The name of the Amazon S3 bucket where the application revision is stored. slBucket :: Lens' S3Location (Maybe Text) slBucket = lens _slBucket (\s a -> s { _slBucket = a }) -- | The file type of the application revision. Must be one of the following: -- -- tar: A tar archive file. tgz: A compressed tar archive file. zip: A zip -- archive file. slBundleType :: Lens' S3Location (Maybe BundleType) slBundleType = lens _slBundleType (\s a -> s { _slBundleType = a }) -- | The ETag of the Amazon S3 object that represents the bundled artifacts for -- the application revision. -- -- If the ETag is not specified as an input parameter, ETag validation of the -- object will be skipped. slETag :: Lens' S3Location (Maybe Text) slETag = lens _slETag (\s a -> s { _slETag = a }) -- | The name of the Amazon S3 object that represents the bundled artifacts for -- the application revision. slKey :: Lens' S3Location (Maybe Text) slKey = lens _slKey (\s a -> s { _slKey = a }) -- | A specific version of the Amazon S3 object that represents the bundled -- artifacts for the application revision. -- -- If the version is not specified, the system will use the most recent version -- by default. slVersion :: Lens' S3Location (Maybe Text) slVersion = lens _slVersion (\s a -> s { _slVersion = a }) instance FromJSON S3Location where parseJSON = withObject "S3Location" $ \o -> S3Location <$> o .:? "bucket" <*> o .:? "bundleType" <*> o .:? "eTag" <*> o .:? "key" <*> o .:? "version" instance ToJSON S3Location where toJSON S3Location{..} = object [ "bucket" .= _slBucket , "key" .= _slKey , "bundleType" .= _slBundleType , "version" .= _slVersion , "eTag" .= _slETag ] data MinimumHealthyHostsType = FleetPercent -- ^ FLEET_PERCENT | HostCount -- ^ HOST_COUNT deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable MinimumHealthyHostsType instance FromText MinimumHealthyHostsType where parser = takeLowerText >>= \case "fleet_percent" -> pure FleetPercent "host_count" -> pure HostCount e -> fail $ "Failure parsing MinimumHealthyHostsType from " ++ show e instance ToText MinimumHealthyHostsType where toText = \case FleetPercent -> "FLEET_PERCENT" HostCount -> "HOST_COUNT" instance ToByteString MinimumHealthyHostsType instance ToHeader MinimumHealthyHostsType instance ToQuery MinimumHealthyHostsType instance FromJSON MinimumHealthyHostsType where parseJSON = parseJSONText "MinimumHealthyHostsType" instance ToJSON MinimumHealthyHostsType where toJSON = toJSONText data GitHubLocation = GitHubLocation { _ghlCommitId :: Maybe Text , _ghlRepository :: Maybe Text } deriving (Eq, Ord, Read, Show) -- | 'GitHubLocation' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'ghlCommitId' @::@ 'Maybe' 'Text' -- -- * 'ghlRepository' @::@ 'Maybe' 'Text' -- gitHubLocation :: GitHubLocation gitHubLocation = GitHubLocation { _ghlRepository = Nothing , _ghlCommitId = Nothing } -- | The SHA1 commit ID of the GitHub commit that references the that represents -- the bundled artifacts for the application revision. ghlCommitId :: Lens' GitHubLocation (Maybe Text) ghlCommitId = lens _ghlCommitId (\s a -> s { _ghlCommitId = a }) -- | The GitHub account and repository pair that stores a reference to the commit -- that represents the bundled artifacts for the application revision. -- -- Specified as account/repository. ghlRepository :: Lens' GitHubLocation (Maybe Text) ghlRepository = lens _ghlRepository (\s a -> s { _ghlRepository = a }) instance FromJSON GitHubLocation where parseJSON = withObject "GitHubLocation" $ \o -> GitHubLocation <$> o .:? "commitId" <*> o .:? "repository" instance ToJSON GitHubLocation where toJSON GitHubLocation{..} = object [ "repository" .= _ghlRepository , "commitId" .= _ghlCommitId ] data RevisionLocationType = GitHub -- ^ GitHub | S3 -- ^ S3 deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable RevisionLocationType instance FromText RevisionLocationType where parser = takeLowerText >>= \case "github" -> pure GitHub "s3" -> pure S3 e -> fail $ "Failure parsing RevisionLocationType from " ++ show e instance ToText RevisionLocationType where toText = \case GitHub -> "GitHub" S3 -> "S3" instance ToByteString RevisionLocationType instance ToHeader RevisionLocationType instance ToQuery RevisionLocationType instance FromJSON RevisionLocationType where parseJSON = parseJSONText "RevisionLocationType" instance ToJSON RevisionLocationType where toJSON = toJSONText data EC2TagFilterType = KeyAndValue -- ^ KEY_AND_VALUE | KeyOnly -- ^ KEY_ONLY | ValueOnly -- ^ VALUE_ONLY deriving (Eq, Ord, Read, Show, Generic, Enum) instance Hashable EC2TagFilterType instance FromText EC2TagFilterType where parser = takeLowerText >>= \case "key_and_value" -> pure KeyAndValue "key_only" -> pure KeyOnly "value_only" -> pure ValueOnly e -> fail $ "Failure parsing EC2TagFilterType from " ++ show e instance ToText EC2TagFilterType where toText = \case KeyAndValue -> "KEY_AND_VALUE" KeyOnly -> "KEY_ONLY" ValueOnly -> "VALUE_ONLY" instance ToByteString EC2TagFilterType instance ToHeader EC2TagFilterType instance ToQuery EC2TagFilterType instance FromJSON EC2TagFilterType where parseJSON = parseJSONText "EC2TagFilterType" instance ToJSON EC2TagFilterType where toJSON = toJSONText
dysinger/amazonka
amazonka-codedeploy/gen/Network/AWS/CodeDeploy/Types.hs
mpl-2.0
63,944
0
35
15,493
11,339
6,336
5,003
-1
-1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Books.MyConfig.RequestAccess -- 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) -- -- Request concurrent and download access restrictions. -- -- /See:/ <https://code.google.com/apis/books/docs/v1/getting_started.html Books API Reference> for @books.myconfig.requestAccess@. module Network.Google.Resource.Books.MyConfig.RequestAccess ( -- * REST Resource MyConfigRequestAccessResource -- * Creating a Request , myConfigRequestAccess , MyConfigRequestAccess -- * Request Lenses , mcraXgafv , mcraCpksver , mcraUploadProtocol , mcraLocale , mcraAccessToken , mcraLicenseTypes , mcraUploadType , mcraVolumeId , mcraSource , mcraCallback , mcraNonce ) where import Network.Google.Books.Types import Network.Google.Prelude -- | A resource alias for @books.myconfig.requestAccess@ method which the -- 'MyConfigRequestAccess' request conforms to. type MyConfigRequestAccessResource = "books" :> "v1" :> "myconfig" :> "requestAccess" :> QueryParam "cpksver" Text :> QueryParam "nonce" Text :> QueryParam "source" Text :> QueryParam "volumeId" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "locale" Text :> QueryParam "access_token" Text :> QueryParam "licenseTypes" MyConfigRequestAccessLicenseTypes :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Post '[JSON] RequestAccessData -- | Request concurrent and download access restrictions. -- -- /See:/ 'myConfigRequestAccess' smart constructor. data MyConfigRequestAccess = MyConfigRequestAccess' { _mcraXgafv :: !(Maybe Xgafv) , _mcraCpksver :: !Text , _mcraUploadProtocol :: !(Maybe Text) , _mcraLocale :: !(Maybe Text) , _mcraAccessToken :: !(Maybe Text) , _mcraLicenseTypes :: !(Maybe MyConfigRequestAccessLicenseTypes) , _mcraUploadType :: !(Maybe Text) , _mcraVolumeId :: !Text , _mcraSource :: !Text , _mcraCallback :: !(Maybe Text) , _mcraNonce :: !Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'MyConfigRequestAccess' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'mcraXgafv' -- -- * 'mcraCpksver' -- -- * 'mcraUploadProtocol' -- -- * 'mcraLocale' -- -- * 'mcraAccessToken' -- -- * 'mcraLicenseTypes' -- -- * 'mcraUploadType' -- -- * 'mcraVolumeId' -- -- * 'mcraSource' -- -- * 'mcraCallback' -- -- * 'mcraNonce' myConfigRequestAccess :: Text -- ^ 'mcraCpksver' -> Text -- ^ 'mcraVolumeId' -> Text -- ^ 'mcraSource' -> Text -- ^ 'mcraNonce' -> MyConfigRequestAccess myConfigRequestAccess pMcraCpksver_ pMcraVolumeId_ pMcraSource_ pMcraNonce_ = MyConfigRequestAccess' { _mcraXgafv = Nothing , _mcraCpksver = pMcraCpksver_ , _mcraUploadProtocol = Nothing , _mcraLocale = Nothing , _mcraAccessToken = Nothing , _mcraLicenseTypes = Nothing , _mcraUploadType = Nothing , _mcraVolumeId = pMcraVolumeId_ , _mcraSource = pMcraSource_ , _mcraCallback = Nothing , _mcraNonce = pMcraNonce_ } -- | V1 error format. mcraXgafv :: Lens' MyConfigRequestAccess (Maybe Xgafv) mcraXgafv = lens _mcraXgafv (\ s a -> s{_mcraXgafv = a}) -- | The device\/version ID from which to request the restrictions. mcraCpksver :: Lens' MyConfigRequestAccess Text mcraCpksver = lens _mcraCpksver (\ s a -> s{_mcraCpksver = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). mcraUploadProtocol :: Lens' MyConfigRequestAccess (Maybe Text) mcraUploadProtocol = lens _mcraUploadProtocol (\ s a -> s{_mcraUploadProtocol = a}) -- | ISO-639-1, ISO-3166-1 codes for message localization, i.e. en_US. mcraLocale :: Lens' MyConfigRequestAccess (Maybe Text) mcraLocale = lens _mcraLocale (\ s a -> s{_mcraLocale = a}) -- | OAuth access token. mcraAccessToken :: Lens' MyConfigRequestAccess (Maybe Text) mcraAccessToken = lens _mcraAccessToken (\ s a -> s{_mcraAccessToken = a}) -- | The type of access license to request. If not specified, the default is -- BOTH. mcraLicenseTypes :: Lens' MyConfigRequestAccess (Maybe MyConfigRequestAccessLicenseTypes) mcraLicenseTypes = lens _mcraLicenseTypes (\ s a -> s{_mcraLicenseTypes = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). mcraUploadType :: Lens' MyConfigRequestAccess (Maybe Text) mcraUploadType = lens _mcraUploadType (\ s a -> s{_mcraUploadType = a}) -- | The volume to request concurrent\/download restrictions for. mcraVolumeId :: Lens' MyConfigRequestAccess Text mcraVolumeId = lens _mcraVolumeId (\ s a -> s{_mcraVolumeId = a}) -- | String to identify the originator of this request. mcraSource :: Lens' MyConfigRequestAccess Text mcraSource = lens _mcraSource (\ s a -> s{_mcraSource = a}) -- | JSONP mcraCallback :: Lens' MyConfigRequestAccess (Maybe Text) mcraCallback = lens _mcraCallback (\ s a -> s{_mcraCallback = a}) -- | The client nonce value. mcraNonce :: Lens' MyConfigRequestAccess Text mcraNonce = lens _mcraNonce (\ s a -> s{_mcraNonce = a}) instance GoogleRequest MyConfigRequestAccess where type Rs MyConfigRequestAccess = RequestAccessData type Scopes MyConfigRequestAccess = '["https://www.googleapis.com/auth/books"] requestClient MyConfigRequestAccess'{..} = go (Just _mcraCpksver) (Just _mcraNonce) (Just _mcraSource) (Just _mcraVolumeId) _mcraXgafv _mcraUploadProtocol _mcraLocale _mcraAccessToken _mcraLicenseTypes _mcraUploadType _mcraCallback (Just AltJSON) booksService where go = buildClient (Proxy :: Proxy MyConfigRequestAccessResource) mempty
brendanhay/gogol
gogol-books/gen/Network/Google/Resource/Books/MyConfig/RequestAccess.hs
mpl-2.0
7,032
0
23
1,789
1,116
643
473
163
1
{-# LANGUAGE OverloadedStrings #-} module View.Template ( htmlHeader , htmlFooter , htmlTemplate , htmlSocialMedia ) where import Control.Monad (void, when, forM_) import qualified Data.ByteString.Builder as BSB import Data.Monoid ((<>)) import qualified Data.Text as T import Data.Version (showVersion) import qualified Text.Blaze.Html5 as H import qualified Text.Blaze.Html5.Attributes as HA import Network.HTTP.Types (methodGet) import qualified Network.Wai as Wai import Paths_databrary (version) import Ops import Has (view) import Model.Identity import Action.Types import Action.Route import Controller.Paths import View.Html import {-# SOURCE #-} Controller.Angular import {-# SOURCE #-} Controller.Root import {-# SOURCE #-} Controller.Login import {-# SOURCE #-} Controller.Party import {-# SOURCE #-} Controller.Web htmlHeader :: Maybe BSB.Builder -> JSOpt -> H.Html htmlHeader canon hasjs = do forM_ canon $ \c -> H.link H.! HA.rel "canonical" H.! HA.href (builderValue c) H.link H.! HA.rel "shortcut icon" H.! HA.href (builderValue $ actionURL Nothing webFile (Just $ staticPath ["icons", "favicon.png"]) []) H.link H.! HA.rel "start" H.! actionLink viewRoot HTML hasjs -- forM_ ["news", "about", "access", "community"] $ \l -> H.link forM_ ["about", "support"] $ \l -> H.link H.! HA.rel l H.! HA.href ("//databrary.org/" <> l <> ".html") htmlAddress :: H.Html htmlAddress = H.p H.! HA.class_ "footer-address" $ do H.strong $ void "Databrary" H.br void "4 Washington Place, Room 409 | New York, NY 10003" H.br void "212.998.5800" htmlCopyrightTermsPrivacy :: H.Html htmlCopyrightTermsPrivacy = H.p H.! HA.class_ "footer-copyright" $ do void "Copyright © 2014-2021" void " | " H.a H.! HA.href "https://databrary.org/about/policies/terms.html" $ "Terms of Use" void " | " H.a H.! HA.href "https://databrary.org/about/policies/privacy.html" $ "Privacy Policy" H.br htmlSocialMedia :: H.Html htmlSocialMedia = H.p H.! HA.class_ "footer-social-media" $ do let sm n l a = H.a H.! HA.href l H.! HA.target "_blank" H.! HA.class_ "img" $ H.img H.! HA.id n H.! HA.src ("/web/images/social/16px/" <> n <> ".png") H.! HA.alt a void "Find us on " sm "twitter" "https://twitter.com/databrary" "Twitter" void " " sm "facebook" "https://www.facebook.com/databrary" "Facebook" void " " sm "linkedin" "https://www.linkedin.com/company/databrary-project" "LinkedIn" void " " -- sm "google-plus" "https://plus.google.com/u/1/111083162045777800330/posts" "Google+" -- void " " sm "github" "https://github.com/databrary/" "GitHub" htmlFooter :: H.Html htmlFooter = H.footer H.! HA.id "site-footer" H.! HA.class_ "site-footer" $ H.div H.! HA.class_ "wrap" $ H.div H.! HA.class_ "row" $ do H.div H.! HA.class_ "site-footer-social-address" $ do -- htmlAddress htmlCopyrightTermsPrivacy htmlSocialMedia H.ul H.! HA.class_ "site-footer-grants" $ do H.li $ H.a H.! HA.href "http://www.nyu.edu" $ H.img H.! HA.src "/web/images/grants/nyu-small.jpg" H.! HA.class_ "nyu" H.! HA.alt "funder NYU logo" H.li $ H.a H.! HA.href "http://www.psu.edu" $ H.img H.! HA.src "/web/images/grants/pennstate.png" H.! HA.class_ "psu" H.! HA.alt "funder Penn State logo" H.li $ H.a H.! HA.href "http://www.nsf.gov/awardsearch/showAward?AWD_ID=1238599&HistoricalAwards=false" $ do H.img H.! HA.src "/web/images/grants/nsf.png" H.! HA.class_ "nsf" H.! HA.alt "funder NSF logo" " BCS-1238599" H.li $ H.a H.! HA.href "https://www.nsf.gov/awardsearch/showAward?AWD_ID=2032713&HistoricalAwards=false" $ do H.img H.! HA.src "/web/images/grants/nsf.png" H.! HA.class_ "nsf" H.! HA.alt "funder NSF logo" " OAC-2032713" H.li $ H.a H.! HA.href "http://projectreporter.nih.gov/project_info_description.cfm?aid=8531595&icde=15908155&ddparam=&ddvalue=&ddsub=&cr=1&csb=default&cs=ASC" $ do H.img H.! HA.src "/web/images/grants/nih.png" H.! HA.class_ "nih" H.! HA.alt "funder NICHD logo" " U01-HD-076595" H.li $ H.a H.! HA.href "https://www.srcd.org/" $ H.img H.! HA.src "/web/images/grants/srcd.png" H.! HA.class_ "srcd" H.! HA.alt "funder SRCD logo" H.li $ H.a H.! HA.href "https://sloan.org/" $ H.img H.! HA.src "/web/images/grants/sloan.png" H.! HA.class_ "sloan" H.! HA.alt "funder Sloan logo" H.li $ H.a H.! HA.href "https://www.legofoundation.com" $ H.img H.! HA.src "/web/images/grants/lego.png" H.! HA.class_ "lego" H.! HA.alt "funder Lego logo" H.div H.! HA.class_ "site-footer-legal col" $ H.p $ do void "Each dataset on Databrary represents an individual work owned by the party who contributed it. Use of Databrary is subject to the " H.a H.! HA.href "https://databrary.org/about/policies/terms.html" H.! HA.target "_blank" $ "Terms & Conditions of Use" void " and the " H.a H.! HA.href "https://databrary.org/about/agreement/agreement.html" H.! HA.target "_blank" $ "Databrary Access Agreement." -- H.string $ showVersion version -- "]" htmlTemplate :: RequestContext -> Maybe T.Text -> (JSOpt -> H.Html) -> H.Html htmlTemplate req title body = H.docTypeHtml $ do H.head $ do htmlHeader canon hasjs H.link H.! HA.rel "stylesheet" H.! actionLink webFile (Just $ StaticPath "all.min.css") ([] :: Query) H.title $ do mapM_ (\t -> H.toHtml t >> " || ") title "Databrary" H.body H.! H.customAttribute "vocab" "http://schema.org" $ do H.section H.! HA.id "toolbar" H.! HA.class_ "toolbar" $ H.div H.! HA.class_ "wrap toolbar-main" $ H.div H.! HA.class_ "row" $ H.nav H.! HA.class_ "toolbar-nav no-angular cf" $ do H.ul H.! HA.class_ "inline-block flat cf" $ do H.li $ H.a H.! actionLink viewRoot HTML hasjs $ "Databrary" -- forM_ ["news", "about", "access", "community"] $ \l -> forM_ ["about", "support"] $ \l -> H.li $ H.a H.! HA.href (H.stringValue $ "//databrary.org/" ++ l ++ ".html") $ H.string l H.ul H.! HA.class_ "toolbar-user inline-block flat cf" $ extractFromIdentifiedSessOrDefault (H.li $ H.a H.! actionLink viewLogin () hasjs $ "Login") (\_ -> do H.li $ H.a H.! actionLink viewParty (HTML, TargetProfile) hasjs $ "Your Dashboard" H.li $ actionForm postLogout HTML hasjs $ H.button H.! HA.class_ "mini" H.! HA.type_ "submit" $ "Logout") $ requestIdentity req H.section H.! HA.id "main" H.! HA.class_ "main" $ H.div H.! HA.class_ "wrap" $ H.div H.! HA.class_ "row" $ do when (hasjs /= JSEnabled) $ forM_ canon $ \c -> H.div $ do H.preEscapedString "Our site works best with modern browsers (Firefox, Chrome, Safari &ge;6, IE &ge;10, and others). \ \You are viewing the simple version of our site: some functionality may not be available. \ \Try switching to the " H.a H.! HA.href (builderValue c) $ "modern version" " to see if it will work on your browser." mapM_ (H.h1 . H.toHtml) title H.! HA.class_ "view-title" r <- body hasjs htmlFooter return r where -- FIXME: I don't think these lines do what they think they do. (hasjs, nojs) = jsURL JSDefault (view req) canon = (Wai.requestMethod (view req) == methodGet && hasjs == JSDefault) `unlessUse` nojs
databrary/databrary
src/View/Template.hs
agpl-3.0
8,250
0
26
2,348
2,262
1,092
1,170
179
1
-- -- Copyright (c) 2012 Citrix Systems, Inc. -- -- This library is free software; you can redistribute it and/or -- modify it under the terms of the GNU Lesser General Public -- License as published by the Free Software Foundation; either -- version 2.1 of the License, or (at your option) any later version. -- -- This library 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 -- Lesser General Public License for more details. -- -- You should have received a copy of the GNU Lesser General Public -- License along with this library; if not, write to the Free Software -- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA -- module Rpc.Domain where import Control.Applicative import Control.Monad.Trans import Control.Concurrent import Data.Map (Map) import qualified Data.Map as M import Rpc.Monad import Rpc.Log import Rpc.Dispatch import qualified Rpc.DBusArgo as A import qualified Control.Exception as E -- rpc on another domain's bus -- this even allows funky things like exporting service on another domain bus but with processing in dom0 rpcWithDomain :: MonadRpc e m => Int -> m a -> m a rpcWithDomain domain f = rpcGetContext >>= \context -> liftIO (rpcCacheDomainBus domain context) >>= \client' -> rpcLocalContext (\c -> c{ client = client' } ) f rpcCacheDomainBus :: Int -> RpcContext -> IO Dispatcher rpcCacheDomainBus domid context = modifyMVar (domUClients context) $ \clients -> case M.lookup domid clients of Nothing -> connected clients =<< rpcTryConnectDomainBus domid 120 Just b -> return (clients, b) where connected clients Nothing = do warn $ "giving up on accessing domain's " ++ show domid ++ " system bus." ioError . userError $ "exceeded maximum attempt count trying to connect to domain's system bus" connected clients (Just b) = return (M.insert domid b clients, b) rpcTryConnectDomainBus :: Int -> Int -> IO (Maybe Dispatcher) rpcTryConnectDomainBus domid 0 = return Nothing rpcTryConnectDomainBus domid timeout = ( Just <$> get ) `E.catch` retry where get = A.domainSystemBus domid >>= connectBus >>= return . fst retry :: E.SomeException -> IO (Maybe Dispatcher) retry e = do warn $ "domain's " ++ show domid ++ " sytem bus is unresponsive: " ++ show e ++ ", retrying.." threadDelay (10^6) rpcTryConnectDomainBus domid (timeout-1)
OpenXT/xclibs
xch-rpc/Rpc/Domain.hs
lgpl-2.1
2,565
0
13
527
513
274
239
36
3
{-# LANGUAGE PackageImports #-} {-# LANGUAGE PatternSynonyms #-} {-# LANGUAGE NoImplicitPrelude #-} {- Copyright 2020 The CodeWorld Authors. All rights reserved. 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. -} module Internal.Exports ( -- * Entry points Program, drawingOf, animationOf, activityOf, debugActivityOf, groupActivityOf, -- * Pictures Picture, codeWorldLogo, circle, solidCircle, thickCircle, rectangle, solidRectangle, thickRectangle, pictures, (&), coordinatePlane, blank, colored, coloured, translated, scaled, dilated, rotated, reflected, clipped, polyline, thickPolyline, polygon, thickPolygon, solidPolygon, curve, thickCurve, closedCurve, thickClosedCurve, solidClosedCurve, arc, sector, thickArc, lettering, styledLettering, Font (..), TextStyle (..), -- * Colors Color, Colour, pattern RGBA, pattern RGB, pattern HSL, black, white, red, green, blue, yellow, orange, brown, pink, purple, gray, grey, mixed, light, dark, bright, dull, translucent, assortedColors, lighter, darker, brighter, duller, -- * Points and vectors Point, translatedPoint, rotatedPoint, reflectedPoint, scaledPoint, dilatedPoint, Vector, vectorLength, vectorDirection, vectorSum, vectorDifference, scaledVector, rotatedVector, dotProduct, -- * Events Event (..), -- * Debugging traced, ) where import Internal.CodeWorld import Internal.Color import Internal.Event import Internal.Num import Internal.Picture import Internal.Prelude import Internal.Text import "base" Prelude (IO)
google/codeworld
codeworld-base/src/Internal/Exports.hs
apache-2.0
2,352
0
5
643
344
231
113
100
0
{- Primitive.hs - Primitive shapes. - - Timothy A. Chagnon - CS 636 - Spring 2009 -} module Primitive where import Math import Ray import Material data Primitive = Sphere RealT Vec3f -- Sphere defined by radius, center | Plane Vec3f Vec3f Vec3f -- Plane defined by 3 points deriving (Show, Eq) -- Sphere centered at the origin sphere :: RealT -> Primitive sphere r = Sphere r zeroVec3f -- Intersect a ray with primitives intersectP :: Ray -> Material -> Primitive -> [Intersection] intersectP (Ray o d) mat (Sphere r ctr) = let b = 2 * (d `dot` (o-ctr)) in let c = (magSq (o-ctr)) - r*r in let discrim = b*b - 4*c in let normal t = (1/r) `svMul` ((o-ctr) + (t `svMul` d)) in if discrim < 0 then [] else let t0 = (-b - (sqrt discrim))/2 in let t1 = (-b + (sqrt discrim))/2 in if t0 < 0 then if t1 < 0 then [] else [(Inx t1 (normal t1) mat)] else [(Inx t0 (normal t0) mat), (Inx t1 (normal t1) mat)] intersectP (Ray r d) mat (Plane a b c) = let amb = a-b in let amc = a-c in let amr = a-r in let mtxA = colMat3f amb amc d in let detA = detMat3f mtxA in let beta = (detMat3f (colMat3f amr amc d)) / detA in let gamma = (detMat3f (colMat3f amb amr d)) / detA in let alpha = 1 - beta - gamma in let t = (detMat3f (colMat3f amb amc amr)) / detA in let normal = norm (amb `cross` amc) in if t > 0 then [Inx t normal mat] else [] -- Transform Primitives transformP :: Mat4f -> Primitive -> Primitive transformP t (Sphere r c) = let r' = r * (t!|0!.0) in let c' = transformPt t c in Sphere r' c' transformP t (Plane a b c) = let a' = transformPt t a in let b' = transformPt t b in let c' = transformPt t c in Plane a' b' c'
tchagnon/cs636-raytracer
a5/Primitive.hs
apache-2.0
2,060
0
29
790
832
424
408
48
5
{-# LANGUAGE CPP #-} {-# LANGUAGE TemplateHaskell #-} #include "settings.h" -- | Settings are centralized, as much as possible, into this file. This -- includes database connection settings, static file locations, etc. -- In addition, you can configure a number of different aspects of Yesod -- by overriding methods in the Yesod typeclass. That instance is -- declared in the Foundation.hs file. module Settings ( hamletFile , cassiusFile , juliusFile , widgetFile , connStr , ConnectionPool , withConnectionPool , runConnectionPool , approot , staticroot , staticdir , previewImage , bugImage , spinnerImage ) where import qualified Text.Hamlet as H import qualified Text.Cassius as H import qualified Text.Julius as H import Language.Haskell.TH.Syntax import Database.Persist.Sqlite import Yesod (MonadInvertIO, addWidget, addCassius, addJulius) import Data.Monoid (mempty) import System.Directory (doesFileExist) -- | The base URL for your application. This will usually be different for -- development and production. Yesod automatically constructs URLs for you, -- so this value must be accurate to create valid links. approot :: String #ifdef PRODUCTION approot = "http://funkyfotoapp.com" #else approot = "http://localhost:3000" #endif -- | The location of static files on your system. This is a file system -- path. The default value works properly with your scaffolded site. staticdir :: FilePath staticdir = "static" -- | The base URL for your static files. As you can see by the default -- value, this can simply be "static" appended to your application root. -- A powerful optimization can be serving static files from a separate -- domain name. This allows you to use a web server optimized for static -- files, more easily set expires and cache values, and avoid possibly -- costly transference of cookies on static files. For more information, -- please see: -- http://code.google.com/speed/page-speed/docs/request.html#ServeFromCookielessDomain -- -- If you change the resource pattern for StaticR in Foundation.hs, you will -- have to make a corresponding change here. -- -- To see how this value is used, see urlRenderOverride in Foundation.hs staticroot :: String staticroot = approot ++ "/static" -- Location of image files to use for effect preivews. -- previewImage :: FilePath previewImage = "original.jpg" bugImage :: FilePath bugImage = "bug.jpg" spinnerImage :: FilePath spinnerImage = "spinner.gif" -- | The database connection string. The meaning of this string is backend- -- specific. connStr :: String #ifdef PRODUCTION connStr = "production.db3" #else connStr = "debug.db3" #endif -- | Your application will keep a connection pool and take connections from -- there as necessary instead of continually creating new connections. This -- value gives the maximum number of connections to be open at a given time. -- If your application requests a connection when all connections are in -- use, that request will fail. Try to choose a number that will work well -- with the system resources available to you while providing enough -- connections for your expected load. -- -- Also, connections are returned to the pool as quickly as possible by -- Yesod to avoid resource exhaustion. A connection is only considered in -- use while within a call to runDB. connectionCount :: Int connectionCount = 10 -- The rest of this file contains settings which rarely need changing by a -- user. -- The following three functions are used for calling HTML, CSS and -- Javascript templates from your Haskell code. During development, -- the "Debug" versions of these functions are used so that changes to -- the templates are immediately reflected in an already running -- application. When making a production compile, the non-debug version -- is used for increased performance. -- -- You can see an example of how to call these functions in Handler/Root.hs -- -- Note: due to polymorphic Hamlet templates, hamletFileDebug is no longer -- used; to get the same auto-loading effect, it is recommended that you -- use the devel server. toHamletFile, toCassiusFile, toJuliusFile :: String -> FilePath toHamletFile x = "hamlet/" ++ x ++ ".hamlet" toCassiusFile x = "cassius/" ++ x ++ ".cassius" toJuliusFile x = "julius/" ++ x ++ ".julius" hamletFile :: FilePath -> Q Exp hamletFile = H.hamletFile . toHamletFile cassiusFile :: FilePath -> Q Exp #ifdef PRODUCTION cassiusFile = H.cassiusFile . toCassiusFile #else cassiusFile = H.cassiusFileDebug . toCassiusFile #endif juliusFile :: FilePath -> Q Exp #ifdef PRODUCTION juliusFile = H.juliusFile . toJuliusFile #else juliusFile = H.juliusFileDebug . toJuliusFile #endif widgetFile :: FilePath -> Q Exp widgetFile x = do let h = unlessExists toHamletFile hamletFile let c = unlessExists toCassiusFile cassiusFile let j = unlessExists toJuliusFile juliusFile [|addWidget $h >> addCassius $c >> addJulius $j|] where unlessExists tofn f = do e <- qRunIO $ doesFileExist $ tofn x if e then f x else [|mempty|] -- The next two functions are for allocating a connection pool and running -- database actions using a pool, respectively. It is used internally -- by the scaffolded application, and therefore you will rarely need to use -- them yourself. withConnectionPool :: MonadInvertIO m => (ConnectionPool -> m a) -> m a withConnectionPool = withSqlitePool connStr connectionCount runConnectionPool :: MonadInvertIO m => SqlPersist m a -> ConnectionPool -> m a runConnectionPool = runSqlPool
sseefried/funky-foto
Settings.hs
bsd-2-clause
5,570
0
11
964
594
363
231
64
2
-- | Provides functionality of rendering the application model. module Renderer ( Descriptor , initialize , terminate , render ) where import Foreign.Marshal.Array import Foreign.Ptr import Foreign.Storable import Graphics.Rendering.OpenGL import System.IO import qualified LoadShaders as LS -- | Checks OpenGL errors, and Writes to stderr when errors occur. checkError :: String -- ^ a function name that called this -> IO () checkError functionName = get errors >>= mapM_ reportError where reportError (Error category message) = do hPutStrLn stderr $ (show category) ++ " in " ++ functionName ++ ": " ++ message -- | Converts an offset value to the Ptr value. bufferOffset :: Integral a => a -- ^ an offset value -> Ptr b -- ^ the Ptr value bufferOffset = plusPtr nullPtr . fromIntegral -- | The byte size of a memory area that is converted from a list. arrayByteSize :: (Storable a) => [a] -- ^ a list -> Int arrayByteSize ls = (sizeOf (head ls)) * (length ls) -- | Represents a set of OpenGL objects for rendering information. data Descriptor = Descriptor BufferObject VertexArrayObject BufferObject Program ArrayIndex NumArrayIndices -- | Initializes a buffer object. initializeBuffer :: (Storable a) => BufferTarget -> [a] -> IO BufferObject initializeBuffer t array = do buffer <- genObjectName bindBuffer t $= Just buffer withArray array $ \ptr -> do bufferData t $= (fromIntegral $ arrayByteSize array, ptr, StaticDraw) bindBuffer ElementArrayBuffer $= Nothing return buffer -- | Initializes OpenGL objects. initialize :: IO Descriptor initialize = do -- meshes let vertices = -- vertex attribute format : x, y, z, r, g, b, a [ (-0.90), (-0.90), 0.0, 1.0, 0.0, 0.0, 1.0 , 0.90, (-0.90), 0.0, 0.0, 1.0, 0.0, 1.0 , 0.90, 0.90, 0.0, 1.0, 1.0, 1.0, 1.0 , (-0.90), 0.90, 0.0, 0.0, 0.0, 1.0, 1.0 ] :: [GLfloat] numPositionElements = 3 numColorElements = 4 offsetPosition = 0 offsetColor = offsetPosition + numPositionElements sizeElement = sizeOf (head vertices) sizeVertex = fromIntegral (sizeElement * (numPositionElements + numColorElements)) let indices = [ 0, 1, 2 , 2, 3, 0 ] :: [GLushort] vertexBuffer <- initializeBuffer ArrayBuffer vertices attributes <- genObjectName bindVertexArrayObject $= Just attributes bindBuffer ArrayBuffer $= Just vertexBuffer let vPosition = AttribLocation 0 vColor = AttribLocation 1 vertexAttribPointer vPosition $= (ToFloat, VertexArrayDescriptor (fromIntegral numPositionElements) Float sizeVertex (bufferOffset (offsetPosition * sizeElement))) vertexAttribPointer vColor $= (ToFloat, VertexArrayDescriptor (fromIntegral numColorElements) Float sizeVertex (bufferOffset (offsetColor * sizeElement))) vertexAttribArray vPosition $= Enabled vertexAttribArray vColor $= Enabled bindBuffer ArrayBuffer $= Nothing bindVertexArrayObject $= Nothing indexBuffer <- initializeBuffer ElementArrayBuffer indices program <- LS.loadShaders [ LS.ShaderInfo VertexShader (LS.FileSource "rectangle.vert") , LS.ShaderInfo FragmentShader (LS.FileSource "rectangle.frag") ] currentProgram $= Just program checkError "initialize" return $ Descriptor vertexBuffer attributes indexBuffer program 0 (fromIntegral $ length indices) -- | Terminates OpenGL objects. terminate :: Descriptor -> IO () terminate (Descriptor vertexBuffer attributes indexBuffer program _ _) = do currentProgram $= Nothing shaders <- get $ attachedShaders program mapM_ releaseShader shaders deleteObjectName program deleteObjectName indexBuffer deleteObjectName attributes deleteObjectName vertexBuffer checkError "terminate" where releaseShader shader = do detachShader program shader deleteObjectName shader -- | Renders the application model with a descriptor. render :: Descriptor -- ^ a descriptor -> IO () render (Descriptor _ attributes indexBuffer _ rectangleOffset rectangleNumIndices) = do clear [ ColorBuffer ] bindVertexArrayObject $= Just attributes bindBuffer ElementArrayBuffer $= Just indexBuffer drawElements Triangles rectangleNumIndices UnsignedShort (bufferOffset rectangleOffset) bindBuffer ElementArrayBuffer $= Nothing bindVertexArrayObject $= Nothing flush checkError "render"
fujiyan/toriaezuzakki
haskell/opengl/rectangle/Renderer.hs
bsd-2-clause
4,665
0
15
1,123
1,118
565
553
105
1
{-# LANGUAGE OverloadedStrings #-} -- | This module contains convertions from LDAP types to ASN.1. -- -- Various hacks are employed because "asn1-encoding" only encodes to DER, but -- LDAP demands BER-encoding. So, when a definition looks suspiciously different -- from the spec in the comment, that's why. I hope all that will be fixed -- eventually. module Ldap.Asn1.ToAsn1 ( ToAsn1(toAsn1) ) where import Data.ASN1.Types (ASN1, ASN1Class, ASN1Tag, ASN1ConstructionType) import qualified Data.ASN1.Types as Asn1 import Data.ByteString (ByteString) import Data.Foldable (fold, foldMap) import Data.List.NonEmpty (NonEmpty) import Data.Maybe (maybe) import Data.Monoid (Endo(Endo), (<>), mempty) import qualified Data.Text.Encoding as Text import Prelude (Integer, (.), fromIntegral) import Ldap.Asn1.Type -- | Convert a LDAP type to ASN.1. -- -- When it's relevant, instances include the part of RFC describing the encoding. class ToAsn1 a where toAsn1 :: a -> Endo [ASN1] {- | @ LDAPMessage ::= SEQUENCE { messageID MessageID, protocolOp CHOICE { bindRequest BindRequest, bindResponse BindResponse, unbindRequest UnbindRequest, searchRequest SearchRequest, searchResEntry SearchResultEntry, searchResDone SearchResultDone, searchResRef SearchResultReference, addRequest AddRequest, addResponse AddResponse, ... }, controls [0] Controls OPTIONAL } @ -} instance ToAsn1 op => ToAsn1 (LdapMessage op) where toAsn1 (LdapMessage i op mc) = sequence (toAsn1 i <> toAsn1 op <> maybe mempty (context 0 . toAsn1) mc) {- | @ MessageID ::= INTEGER (0 .. maxInt) @ -} instance ToAsn1 Id where toAsn1 (Id i) = single (Asn1.IntVal (fromIntegral i)) {- | @ LDAPString ::= OCTET STRING -- UTF-8 encoded @ -} instance ToAsn1 LdapString where toAsn1 (LdapString s) = single (Asn1.OctetString (Text.encodeUtf8 s)) {- | @ LDAPOID ::= OCTET STRING -- Constrained to \<numericoid\> @ -} instance ToAsn1 LdapOid where toAsn1 (LdapOid s) = single (Asn1.OctetString (Text.encodeUtf8 s)) {- | @ LDAPDN ::= LDAPString -- Constrained to \<distinguishedName\> @ -} instance ToAsn1 LdapDn where toAsn1 (LdapDn s) = toAsn1 s {- | @ RelativeLDAPDN ::= LDAPString -- Constrained to \<name-component\> @ -} instance ToAsn1 RelativeLdapDn where toAsn1 (RelativeLdapDn s) = toAsn1 s {- | @ AttributeDescription ::= LDAPString @ -} instance ToAsn1 AttributeDescription where toAsn1 (AttributeDescription s) = toAsn1 s {- | @ AttributeValue ::= OCTET STRING @ -} instance ToAsn1 AttributeValue where toAsn1 (AttributeValue s) = single (Asn1.OctetString s) {- | @ AttributeValueAssertion ::= SEQUENCE { attributeDesc AttributeDescription, assertionValue AssertionValue } @ -} instance ToAsn1 AttributeValueAssertion where toAsn1 (AttributeValueAssertion d v) = toAsn1 d <> toAsn1 v {- | @ AssertionValue ::= OCTET STRING @ -} instance ToAsn1 AssertionValue where toAsn1 (AssertionValue s) = single (Asn1.OctetString s) {- | @ PartialAttribute ::= SEQUENCE { type AttributeDescription, vals SET OF value AttributeValue } @ -} instance ToAsn1 PartialAttribute where toAsn1 (PartialAttribute d xs) = sequence (toAsn1 d <> set (toAsn1 xs)) {- | @ Attribute ::= PartialAttribute(WITH COMPONENTS { ..., vals (SIZE(1..MAX))}) @ -} instance ToAsn1 Attribute where toAsn1 (Attribute d xs) = sequence (toAsn1 d <> set (toAsn1 xs)) {- | @ MatchingRuleId ::= LDAPString @ -} instance ToAsn1 MatchingRuleId where toAsn1 (MatchingRuleId s) = toAsn1 s {- | @ Controls ::= SEQUENCE OF control Control @ -} instance ToAsn1 Controls where toAsn1 (Controls cs) = sequence (toAsn1 cs) {- | @ Control ::= SEQUENCE { controlType LDAPOID, criticality BOOLEAN DEFAULT FALSE, controlValue OCTET STRING OPTIONAL } @ -} instance ToAsn1 Control where toAsn1 (Control t c v) = sequence (fold [ toAsn1 t , single (Asn1.Boolean c) , maybe mempty (single . Asn1.OctetString) v ]) {- | @ BindRequest ::= [APPLICATION 0] SEQUENCE { version INTEGER (1 .. 127), name LDAPDN, authentication AuthenticationChoice } @ @ UnbindRequest ::= [APPLICATION 2] NULL @ @ SearchRequest ::= [APPLICATION 3] SEQUENCE { baseObject LDAPDN, scope ENUMERATED { baseObject (0), singleLevel (1), wholeSubtree (2), ... }, derefAliases ENUMERATED { neverDerefAliases (0), derefInSearching (1), derefFindingBaseObj (2), derefAlways (3) }, sizeLimit INTEGER (0 .. maxInt), timeLimit INTEGER (0 .. maxInt), typesOnly BOOLEAN, filter Filter, attributes AttributeSelection } @ @ ModifyRequest ::= [APPLICATION 6] SEQUENCE { object LDAPDN, changes SEQUENCE OF change SEQUENCE { operation ENUMERATED { add (0), delete (1), replace (2), ... }, modification PartialAttribute } } @ @ AddRequest ::= [APPLICATION 8] SEQUENCE { entry LDAPDN, attributes AttributeList } @ @ DelRequest ::= [APPLICATION 10] LDAPDN @ @ ModifyDNRequest ::= [APPLICATION 12] SEQUENCE { entry LDAPDN, newrdn RelativeLDAPDN, deleteoldrdn BOOLEAN, newSuperior [0] LDAPDN OPTIONAL } @ @ CompareRequest ::= [APPLICATION 14] SEQUENCE { entry LDAPDN, ava AttributeValueAssertion } @ @ ExtendedRequest ::= [APPLICATION 23] SEQUENCE { requestName [0] LDAPOID, requestValue [1] OCTET STRING OPTIONAL } @ -} instance ToAsn1 ProtocolClientOp where toAsn1 (BindRequest v n a) = application 0 (single (Asn1.IntVal (fromIntegral v)) <> toAsn1 n <> toAsn1 a) toAsn1 UnbindRequest = other Asn1.Application 2 mempty toAsn1 (SearchRequest bo s da sl tl to f a) = application 3 (fold [ toAsn1 bo , enum s' , enum da' , single (Asn1.IntVal (fromIntegral sl)) , single (Asn1.IntVal (fromIntegral tl)) , single (Asn1.Boolean to) , toAsn1 f , toAsn1 a ]) where s' = case s of BaseObject -> 0 SingleLevel -> 1 WholeSubtree -> 2 da' = case da of NeverDerefAliases -> 0 DerefInSearching -> 1 DerefFindingBaseObject -> 2 DerefAlways -> 3 toAsn1 (ModifyRequest dn xs) = application 6 (fold [ toAsn1 dn , sequence (foldMap (\(op, pa) -> sequence (enum (case op of Add -> 0 Delete -> 1 Replace -> 2) <> toAsn1 pa)) xs) ]) toAsn1 (AddRequest dn as) = application 8 (toAsn1 dn <> toAsn1 as) toAsn1 (DeleteRequest (LdapDn (LdapString dn))) = other Asn1.Application 10 (Text.encodeUtf8 dn) toAsn1 (ModifyDnRequest dn rdn del new) = application 12 (fold [ toAsn1 dn , toAsn1 rdn , single (Asn1.Boolean del) , maybe mempty (\(LdapDn (LdapString dn')) -> other Asn1.Context 0 (Text.encodeUtf8 dn')) new ]) toAsn1 (CompareRequest dn av) = application 14 (toAsn1 dn <> sequence (toAsn1 av)) toAsn1 (ExtendedRequest (LdapOid oid) mv) = application 23 (fold [ other Asn1.Context 0 (Text.encodeUtf8 oid) , maybe mempty (other Asn1.Context 1) mv ]) {- | @ AuthenticationChoice ::= CHOICE { simple [0] OCTET STRING, sasl [3] SaslCredentials, ... } SaslCredentials ::= SEQUENCE { mechanism LDAPString, credentials OCTET STRING OPTIONAL } @ -} instance ToAsn1 AuthenticationChoice where toAsn1 (Simple s) = other Asn1.Context 0 s toAsn1 (Sasl External c) = context 3 (fold [ toAsn1 (LdapString "EXTERNAL") , maybe mempty (toAsn1 . LdapString) c ]) {- | @ AttributeSelection ::= SEQUENCE OF selector LDAPString @ -} instance ToAsn1 AttributeSelection where toAsn1 (AttributeSelection as) = sequence (toAsn1 as) {- | @ Filter ::= CHOICE { and [0] SET SIZE (1..MAX) OF filter Filter, or [1] SET SIZE (1..MAX) OF filter Filter, not [2] Filter, equalityMatch [3] AttributeValueAssertion, substrings [4] SubstringFilter, greaterOrEqual [5] AttributeValueAssertion, lessOrEqual [6] AttributeValueAssertion, present [7] AttributeDescription, approxMatch [8] AttributeValueAssertion, extensibleMatch [9] MatchingRuleAssertion, ... } @ -} instance ToAsn1 Filter where toAsn1 f = case f of And xs -> context 0 (toAsn1 xs) Or xs -> context 1 (toAsn1 xs) Not x -> context 2 (toAsn1 x) EqualityMatch x -> context 3 (toAsn1 x) Substrings x -> context 4 (toAsn1 x) GreaterOrEqual x -> context 5 (toAsn1 x) LessOrEqual x -> context 6 (toAsn1 x) Present (AttributeDescription (LdapString x)) -> other Asn1.Context 7 (Text.encodeUtf8 x) ApproxMatch x -> context 8 (toAsn1 x) ExtensibleMatch x -> context 9 (toAsn1 x) {- | @ SubstringFilter ::= SEQUENCE { type AttributeDescription, substrings SEQUENCE SIZE (1..MAX) OF substring CHOICE { initial [0] AssertionValue, -- can occur at most once any [1] AssertionValue, final [2] AssertionValue } -- can occur at most once } @ -} instance ToAsn1 SubstringFilter where toAsn1 (SubstringFilter ad ss) = toAsn1 ad <> sequence (foldMap (\s -> case s of Initial (AssertionValue v) -> other Asn1.Context 0 v Any (AssertionValue v) -> other Asn1.Context 1 v Final (AssertionValue v) -> other Asn1.Context 2 v) ss) {- | @ MatchingRuleAssertion ::= SEQUENCE { matchingRule [1] MatchingRuleId OPTIONAL, type [2] AttributeDescription OPTIONAL, matchValue [3] AssertionValue, dnAttributes [4] BOOLEAN DEFAULT FALSE } @ -} instance ToAsn1 MatchingRuleAssertion where toAsn1 (MatchingRuleAssertion mmr mad (AssertionValue av) _) = fold [ maybe mempty f mmr , maybe mempty g mad , other Asn1.Context 3 av ] where f (MatchingRuleId (LdapString x)) = other Asn1.Context 1 (Text.encodeUtf8 x) g (AttributeDescription (LdapString x)) = other Asn1.Context 2 (Text.encodeUtf8 x) {- | @ AttributeList ::= SEQUENCE OF attribute Attribute @ -} instance ToAsn1 AttributeList where toAsn1 (AttributeList xs) = sequence (toAsn1 xs) instance ToAsn1 a => ToAsn1 [a] where toAsn1 = foldMap toAsn1 instance ToAsn1 a => ToAsn1 (NonEmpty a) where toAsn1 = foldMap toAsn1 sequence :: Endo [ASN1] -> Endo [ASN1] sequence = construction Asn1.Sequence set :: Endo [ASN1] -> Endo [ASN1] set = construction Asn1.Set application :: ASN1Tag -> Endo [ASN1] -> Endo [ASN1] application = construction . Asn1.Container Asn1.Application context :: ASN1Tag -> Endo [ASN1] -> Endo [ASN1] context = construction . Asn1.Container Asn1.Context construction :: ASN1ConstructionType -> Endo [ASN1] -> Endo [ASN1] construction t x = single (Asn1.Start t) <> x <> single (Asn1.End t) other :: ASN1Class -> ASN1Tag -> ByteString -> Endo [ASN1] other c t = single . Asn1.Other c t enum :: Integer -> Endo [ASN1] enum = single . Asn1.Enumerated single :: a -> Endo [a] single x = Endo (x :)
supki/ldap-client
src/Ldap/Asn1/ToAsn1.hs
bsd-2-clause
11,863
0
22
3,385
2,477
1,252
1,225
158
1
module HSNTP.Util.Daemon (daemonize, childLives) where import System.Posix daemonize :: IO () -> IO () -> IO ProcessID daemonize hup comp = forkProcess cont where cont = do createSession installHandler lostConnection (Catch hup) Nothing comp childLives :: ProcessID -> IO Bool childLives pid = do sleep 1 ms <- getProcessStatus False False pid return $ maybe True (const False) ms
creswick/hsntp
HSNTP/Util/Daemon.hs
bsd-3-clause
413
8
10
91
149
73
76
11
1
-- -fno-warn-deprecations for use of Map.foldWithKey {-# OPTIONS_GHC -fno-warn-deprecations #-} ----------------------------------------------------------------------------- -- | -- Module : Distribution.PackageDescription.Configuration -- Copyright : Thomas Schilling, 2007 -- License : BSD3 -- -- Maintainer : cabal-devel@haskell.org -- Portability : portable -- -- This is about the cabal configurations feature. It exports -- 'finalizePackageDescription' and 'flattenPackageDescription' which are -- functions for converting 'GenericPackageDescription's down to -- 'PackageDescription's. It has code for working with the tree of conditions -- and resolving or flattening conditions. module Distribution.PackageDescription.Configuration ( finalizePackageDescription, flattenPackageDescription, -- Utils parseCondition, freeVars, mapCondTree, mapTreeData, mapTreeConds, mapTreeConstrs, ) where import Distribution.Package import Distribution.PackageDescription import Distribution.PackageDescription.Utils import Distribution.Version import Distribution.Compiler import Distribution.System import Distribution.Simple.Utils import Distribution.Text import Distribution.Compat.ReadP as ReadP hiding ( char ) import qualified Distribution.Compat.ReadP as ReadP ( char ) import Distribution.Compat.Semigroup as Semi import Control.Arrow (first) import Data.Char ( isAlphaNum ) import Data.Maybe ( mapMaybe, maybeToList ) import Data.Map ( Map, fromListWith, toList ) import qualified Data.Map as Map ------------------------------------------------------------------------------ -- | Simplify the condition and return its free variables. simplifyCondition :: Condition c -> (c -> Either d Bool) -- ^ (partial) variable assignment -> (Condition d, [d]) simplifyCondition cond i = fv . walk $ cond where walk cnd = case cnd of Var v -> either Var Lit (i v) Lit b -> Lit b CNot c -> case walk c of Lit True -> Lit False Lit False -> Lit True c' -> CNot c' COr c d -> case (walk c, walk d) of (Lit False, d') -> d' (Lit True, _) -> Lit True (c', Lit False) -> c' (_, Lit True) -> Lit True (c',d') -> COr c' d' CAnd c d -> case (walk c, walk d) of (Lit False, _) -> Lit False (Lit True, d') -> d' (_, Lit False) -> Lit False (c', Lit True) -> c' (c',d') -> CAnd c' d' -- gather free vars fv c = (c, fv' c) fv' c = case c of Var v -> [v] Lit _ -> [] CNot c' -> fv' c' COr c1 c2 -> fv' c1 ++ fv' c2 CAnd c1 c2 -> fv' c1 ++ fv' c2 -- | Simplify a configuration condition using the OS and arch names. Returns -- the names of all the flags occurring in the condition. simplifyWithSysParams :: OS -> Arch -> CompilerInfo -> Condition ConfVar -> (Condition FlagName, [FlagName]) simplifyWithSysParams os arch cinfo cond = (cond', flags) where (cond', flags) = simplifyCondition cond interp interp (OS os') = Right $ os' == os interp (Arch arch') = Right $ arch' == arch interp (Impl comp vr) | matchImpl (compilerInfoId cinfo) = Right True | otherwise = case compilerInfoCompat cinfo of -- fixme: treat Nothing as unknown, rather than empty list once we -- support partial resolution of system parameters Nothing -> Right False Just compat -> Right (any matchImpl compat) where matchImpl (CompilerId c v) = comp == c && v `withinRange` vr interp (Flag f) = Left f -- TODO: Add instances and check -- -- prop_sC_idempotent cond a o = cond' == cond'' -- where -- cond' = simplifyCondition cond a o -- cond'' = simplifyCondition cond' a o -- -- prop_sC_noLits cond a o = isLit res || not (hasLits res) -- where -- res = simplifyCondition cond a o -- hasLits (Lit _) = True -- hasLits (CNot c) = hasLits c -- hasLits (COr l r) = hasLits l || hasLits r -- hasLits (CAnd l r) = hasLits l || hasLits r -- hasLits _ = False -- -- | Parse a configuration condition from a string. parseCondition :: ReadP r (Condition ConfVar) parseCondition = condOr where condOr = sepBy1 condAnd (oper "||") >>= return . foldl1 COr condAnd = sepBy1 cond (oper "&&")>>= return . foldl1 CAnd cond = sp >> (boolLiteral +++ inparens condOr +++ notCond +++ osCond +++ archCond +++ flagCond +++ implCond ) inparens = between (ReadP.char '(' >> sp) (sp >> ReadP.char ')' >> sp) notCond = ReadP.char '!' >> sp >> cond >>= return . CNot osCond = string "os" >> sp >> inparens osIdent >>= return . Var archCond = string "arch" >> sp >> inparens archIdent >>= return . Var flagCond = string "flag" >> sp >> inparens flagIdent >>= return . Var implCond = string "impl" >> sp >> inparens implIdent >>= return . Var boolLiteral = fmap Lit parse archIdent = fmap Arch parse osIdent = fmap OS parse flagIdent = fmap (Flag . FlagName . lowercase) (munch1 isIdentChar) isIdentChar c = isAlphaNum c || c == '_' || c == '-' oper s = sp >> string s >> sp sp = skipSpaces implIdent = do i <- parse vr <- sp >> option anyVersion parse return $ Impl i vr ------------------------------------------------------------------------------ mapCondTree :: (a -> b) -> (c -> d) -> (Condition v -> Condition w) -> CondTree v c a -> CondTree w d b mapCondTree fa fc fcnd (CondNode a c ifs) = CondNode (fa a) (fc c) (map g ifs) where g (cnd, t, me) = (fcnd cnd, mapCondTree fa fc fcnd t, fmap (mapCondTree fa fc fcnd) me) mapTreeConstrs :: (c -> d) -> CondTree v c a -> CondTree v d a mapTreeConstrs f = mapCondTree id f id mapTreeConds :: (Condition v -> Condition w) -> CondTree v c a -> CondTree w c a mapTreeConds f = mapCondTree id id f mapTreeData :: (a -> b) -> CondTree v c a -> CondTree v c b mapTreeData f = mapCondTree f id id -- | Result of dependency test. Isomorphic to @Maybe d@ but renamed for -- clarity. data DepTestRslt d = DepOk | MissingDeps d instance Semigroup d => Monoid (DepTestRslt d) where mempty = DepOk mappend = (Semi.<>) instance Semigroup d => Semigroup (DepTestRslt d) where DepOk <> x = x x <> DepOk = x (MissingDeps d) <> (MissingDeps d') = MissingDeps (d <> d') -- | Try to find a flag assignment that satisfies the constraints of all trees. -- -- Returns either the missing dependencies, or a tuple containing the -- resulting data, the associated dependencies, and the chosen flag -- assignments. -- -- In case of failure, the _smallest_ number of of missing dependencies is -- returned. [TODO: Could also be specified with a function argument.] -- -- TODO: The current algorithm is rather naive. A better approach would be to: -- -- * Rule out possible paths, by taking a look at the associated dependencies. -- -- * Infer the required values for the conditions of these paths, and -- calculate the required domains for the variables used in these -- conditions. Then picking a flag assignment would be linear (I guess). -- -- This would require some sort of SAT solving, though, thus it's not -- implemented unless we really need it. -- resolveWithFlags :: [(FlagName,[Bool])] -- ^ Domain for each flag name, will be tested in order. -> OS -- ^ OS as returned by Distribution.System.buildOS -> Arch -- ^ Arch as returned by Distribution.System.buildArch -> CompilerInfo -- ^ Compiler information -> [Dependency] -- ^ Additional constraints -> [CondTree ConfVar [Dependency] PDTagged] -> ([Dependency] -> DepTestRslt [Dependency]) -- ^ Dependency test function. -> Either [Dependency] (TargetSet PDTagged, FlagAssignment) -- ^ Either the missing dependencies (error case), or a pair of -- (set of build targets with dependencies, chosen flag assignments) resolveWithFlags dom os arch impl constrs trees checkDeps = try dom [] where extraConstrs = toDepMap constrs -- simplify trees by (partially) evaluating all conditions and converting -- dependencies to dependency maps. simplifiedTrees :: [CondTree FlagName DependencyMap PDTagged] simplifiedTrees = map ( mapTreeConstrs toDepMap -- convert to maps . mapTreeConds (fst . simplifyWithSysParams os arch impl)) trees -- @try@ recursively tries all possible flag assignments in the domain and -- either succeeds or returns the shortest list of missing dependencies. try :: [(FlagName, [Bool])] -> [(FlagName, Bool)] -> Either [Dependency] (TargetSet PDTagged, FlagAssignment) try [] flags = let targetSet = TargetSet $ flip map simplifiedTrees $ -- apply additional constraints to all dependencies first (`constrainBy` extraConstrs) . simplifyCondTree (env flags) deps = overallDependencies targetSet in case checkDeps (fromDepMap deps) of DepOk -> Right (targetSet, flags) MissingDeps mds -> Left mds try ((n, vals):rest) flags = tryAll $ map (\v -> try rest ((n, v):flags)) vals tryAll :: [Either [a] b] -> Either [a] b tryAll = foldr mp mz -- special version of `mplus' for our local purposes mp :: Either [a] b -> Either [a] b -> Either [a] b mp (Left xs) (Left ys) = xs `seq` ys `seq` Left (findShortest xs ys) mp (Left _) m@(Right _) = m mp m@(Right _) _ = m -- `mzero' mz :: Either [a] b mz = Left [] env :: FlagAssignment -> FlagName -> Either FlagName Bool env flags flag = (maybe (Left flag) Right . lookup flag) flags -- we pick the shortest list of missing dependencies findShortest :: [a] -> [a] -> [a] findShortest [] xs = xs -- [] is too short findShortest xs [] = xs findShortest [x] _ = [x] -- single elem is optimum findShortest _ [x] = [x] findShortest xs ys = if lazyLengthCmp xs ys then xs else ys -- lazy variant of @\xs ys -> length xs <= length ys@ lazyLengthCmp :: [a] -> [a] -> Bool lazyLengthCmp [] _ = True lazyLengthCmp _ [] = False lazyLengthCmp (_:xs) (_:ys) = lazyLengthCmp xs ys -- | A map of dependencies. Newtyped since the default monoid instance is not -- appropriate. The monoid instance uses 'intersectVersionRanges'. newtype DependencyMap = DependencyMap { unDependencyMap :: Map PackageName VersionRange } deriving (Show, Read) instance Monoid DependencyMap where mempty = DependencyMap Map.empty mappend = (Semi.<>) instance Semigroup DependencyMap where (DependencyMap a) <> (DependencyMap b) = DependencyMap (Map.unionWith intersectVersionRanges a b) toDepMap :: [Dependency] -> DependencyMap toDepMap ds = DependencyMap $ fromListWith intersectVersionRanges [ (p,vr) | Dependency p vr <- ds ] fromDepMap :: DependencyMap -> [Dependency] fromDepMap m = [ Dependency p vr | (p,vr) <- toList (unDependencyMap m) ] simplifyCondTree :: (Monoid a, Monoid d) => (v -> Either v Bool) -> CondTree v d a -> (d, a) simplifyCondTree env (CondNode a d ifs) = mconcat $ (d, a) : mapMaybe simplifyIf ifs where simplifyIf (cnd, t, me) = case simplifyCondition cnd env of (Lit True, _) -> Just $ simplifyCondTree env t (Lit False, _) -> fmap (simplifyCondTree env) me _ -> error $ "Environment not defined for all free vars" -- | Flatten a CondTree. This will resolve the CondTree by taking all -- possible paths into account. Note that since branches represent exclusive -- choices this may not result in a \"sane\" result. ignoreConditions :: (Monoid a, Monoid c) => CondTree v c a -> (a, c) ignoreConditions (CondNode a c ifs) = (a, c) `mappend` mconcat (concatMap f ifs) where f (_, t, me) = ignoreConditions t : maybeToList (fmap ignoreConditions me) freeVars :: CondTree ConfVar c a -> [FlagName] freeVars t = [ f | Flag f <- freeVars' t ] where freeVars' (CondNode _ _ ifs) = concatMap compfv ifs compfv (c, ct, mct) = condfv c ++ freeVars' ct ++ maybe [] freeVars' mct condfv c = case c of Var v -> [v] Lit _ -> [] CNot c' -> condfv c' COr c1 c2 -> condfv c1 ++ condfv c2 CAnd c1 c2 -> condfv c1 ++ condfv c2 ------------------------------------------------------------------------------ -- | A set of targets with their package dependencies newtype TargetSet a = TargetSet [(DependencyMap, a)] -- | Combine the target-specific dependencies in a TargetSet to give the -- dependencies for the package as a whole. overallDependencies :: TargetSet PDTagged -> DependencyMap overallDependencies (TargetSet targets) = mconcat depss where (depss, _) = unzip $ filter (removeDisabledSections . snd) targets removeDisabledSections :: PDTagged -> Bool removeDisabledSections (Lib l) = buildable (libBuildInfo l) removeDisabledSections (Exe _ e) = buildable (buildInfo e) removeDisabledSections (Test _ t) = testEnabled t && buildable (testBuildInfo t) removeDisabledSections (Bench _ b) = benchmarkEnabled b && buildable (benchmarkBuildInfo b) removeDisabledSections PDNull = True -- Apply extra constraints to a dependency map. -- Combines dependencies where the result will only contain keys from the left -- (first) map. If a key also exists in the right map, both constraints will -- be intersected. constrainBy :: DependencyMap -- ^ Input map -> DependencyMap -- ^ Extra constraints -> DependencyMap constrainBy left extra = DependencyMap $ Map.foldWithKey tightenConstraint (unDependencyMap left) (unDependencyMap extra) where tightenConstraint n c l = case Map.lookup n l of Nothing -> l Just vr -> Map.insert n (intersectVersionRanges vr c) l -- | Collect up the targets in a TargetSet of tagged targets, storing the -- dependencies as we go. flattenTaggedTargets :: TargetSet PDTagged -> (Maybe Library, [(String, Executable)], [(String, TestSuite)] , [(String, Benchmark)]) flattenTaggedTargets (TargetSet targets) = foldr untag (Nothing, [], [], []) targets where untag (_, Lib _) (Just _, _, _, _) = userBug "Only one library expected" untag (deps, Lib l) (Nothing, exes, tests, bms) = (Just l', exes, tests, bms) where l' = l { libBuildInfo = (libBuildInfo l) { targetBuildDepends = fromDepMap deps } } untag (deps, Exe n e) (mlib, exes, tests, bms) | any ((== n) . fst) exes = userBug $ "There exist several exes with the same name: '" ++ n ++ "'" | any ((== n) . fst) tests = userBug $ "There exists a test with the same name as an exe: '" ++ n ++ "'" | any ((== n) . fst) bms = userBug $ "There exists a benchmark with the same name as an exe: '" ++ n ++ "'" | otherwise = (mlib, (n, e'):exes, tests, bms) where e' = e { buildInfo = (buildInfo e) { targetBuildDepends = fromDepMap deps } } untag (deps, Test n t) (mlib, exes, tests, bms) | any ((== n) . fst) tests = userBug $ "There exist several tests with the same name: '" ++ n ++ "'" | any ((== n) . fst) exes = userBug $ "There exists an exe with the same name as the test: '" ++ n ++ "'" | any ((== n) . fst) bms = userBug $ "There exists a benchmark with the same name as the test: '" ++ n ++ "'" | otherwise = (mlib, exes, (n, t'):tests, bms) where t' = t { testBuildInfo = (testBuildInfo t) { targetBuildDepends = fromDepMap deps } } untag (deps, Bench n b) (mlib, exes, tests, bms) | any ((== n) . fst) bms = userBug $ "There exist several benchmarks with the same name: '" ++ n ++ "'" | any ((== n) . fst) exes = userBug $ "There exists an exe with the same name as the benchmark: '" ++ n ++ "'" | any ((== n) . fst) tests = userBug $ "There exists a test with the same name as the benchmark: '" ++ n ++ "'" | otherwise = (mlib, exes, tests, (n, b'):bms) where b' = b { benchmarkBuildInfo = (benchmarkBuildInfo b) { targetBuildDepends = fromDepMap deps } } untag (_, PDNull) x = x -- actually this should not happen, but let's be liberal ------------------------------------------------------------------------------ -- Convert GenericPackageDescription to PackageDescription -- data PDTagged = Lib Library | Exe String Executable | Test String TestSuite | Bench String Benchmark | PDNull deriving Show instance Monoid PDTagged where mempty = PDNull mappend = (Semi.<>) instance Semigroup PDTagged where PDNull <> x = x x <> PDNull = x Lib l <> Lib l' = Lib (l <> l') Exe n e <> Exe n' e' | n == n' = Exe n (e <> e') Test n t <> Test n' t' | n == n' = Test n (t <> t') Bench n b <> Bench n' b' | n == n' = Bench n (b <> b') _ <> _ = cabalBug "Cannot combine incompatible tags" -- | Create a package description with all configurations resolved. -- -- This function takes a `GenericPackageDescription` and several environment -- parameters and tries to generate `PackageDescription` by finding a flag -- assignment that result in satisfiable dependencies. -- -- It takes as inputs a not necessarily complete specifications of flags -- assignments, an optional package index as well as platform parameters. If -- some flags are not assigned explicitly, this function will try to pick an -- assignment that causes this function to succeed. The package index is -- optional since on some platforms we cannot determine which packages have -- been installed before. When no package index is supplied, every dependency -- is assumed to be satisfiable, therefore all not explicitly assigned flags -- will get their default values. -- -- This function will fail if it cannot find a flag assignment that leads to -- satisfiable dependencies. (It will not try alternative assignments for -- explicitly specified flags.) In case of failure it will return a /minimum/ -- number of dependencies that could not be satisfied. On success, it will -- return the package description and the full flag assignment chosen. -- finalizePackageDescription :: FlagAssignment -- ^ Explicitly specified flag assignments -> (Dependency -> Bool) -- ^ Is a given dependency satisfiable from the set of -- available packages? If this is unknown then use -- True. -> Platform -- ^ The 'Arch' and 'OS' -> CompilerInfo -- ^ Compiler information -> [Dependency] -- ^ Additional constraints -> GenericPackageDescription -> Either [Dependency] (PackageDescription, FlagAssignment) -- ^ Either missing dependencies or the resolved package -- description along with the flag assignments chosen. finalizePackageDescription userflags satisfyDep (Platform arch os) impl constraints (GenericPackageDescription pkg flags mlib0 exes0 tests0 bms0) = case resolveFlags of Right ((mlib, exes', tests', bms'), targetSet, flagVals) -> Right ( pkg { library = mlib , executables = exes' , testSuites = tests' , benchmarks = bms' , buildDepends = fromDepMap (overallDependencies targetSet) } , flagVals ) Left missing -> Left missing where -- Combine lib, exes, and tests into one list of @CondTree@s with tagged data condTrees = maybeToList (fmap (mapTreeData Lib) mlib0 ) ++ map (\(name,tree) -> mapTreeData (Exe name) tree) exes0 ++ map (\(name,tree) -> mapTreeData (Test name) tree) tests0 ++ map (\(name,tree) -> mapTreeData (Bench name) tree) bms0 resolveFlags = case resolveWithFlags flagChoices os arch impl constraints condTrees check of Right (targetSet, fs) -> let (mlib, exes, tests, bms) = flattenTaggedTargets targetSet in Right ( (fmap libFillInDefaults mlib, map (\(n,e) -> (exeFillInDefaults e) { exeName = n }) exes, map (\(n,t) -> (testFillInDefaults t) { testName = n }) tests, map (\(n,b) -> (benchFillInDefaults b) { benchmarkName = n }) bms), targetSet, fs) Left missing -> Left missing flagChoices = map (\(MkFlag n _ d manual) -> (n, d2c manual n d)) flags d2c manual n b = case lookup n userflags of Just val -> [val] Nothing | manual -> [b] | otherwise -> [b, not b] --flagDefaults = map (\(n,x:_) -> (n,x)) flagChoices check ds = let missingDeps = filter (not . satisfyDep) ds in if null missingDeps then DepOk else MissingDeps missingDeps {- let tst_p = (CondNode [1::Int] [Distribution.Package.Dependency "a" AnyVersion] []) let tst_p2 = (CondNode [1::Int] [Distribution.Package.Dependency "a" (EarlierVersion (Version [1,0] [])), Distribution.Package.Dependency "a" (LaterVersion (Version [2,0] []))] []) let p_index = Distribution.Simple.PackageIndex.fromList [Distribution.Package.PackageIdentifier "a" (Version [0,5] []), Distribution.Package.PackageIdentifier "a" (Version [2,5] [])] let look = not . null . Distribution.Simple.PackageIndex.lookupDependency p_index let looks ds = mconcat $ map (\d -> if look d then DepOk else MissingDeps [d]) ds resolveWithFlags [] Distribution.System.Linux Distribution.System.I386 (Distribution.Compiler.GHC,Version [6,8,2] []) [tst_p] looks ===> Right ... resolveWithFlags [] Distribution.System.Linux Distribution.System.I386 (Distribution.Compiler.GHC,Version [6,8,2] []) [tst_p2] looks ===> Left ... -} -- | Flatten a generic package description by ignoring all conditions and just -- join the field descriptors into on package description. Note, however, -- that this may lead to inconsistent field values, since all values are -- joined into one field, which may not be possible in the original package -- description, due to the use of exclusive choices (if ... else ...). -- -- TODO: One particularly tricky case is defaulting. In the original package -- description, e.g., the source directory might either be the default or a -- certain, explicitly set path. Since defaults are filled in only after the -- package has been resolved and when no explicit value has been set, the -- default path will be missing from the package description returned by this -- function. flattenPackageDescription :: GenericPackageDescription -> PackageDescription flattenPackageDescription (GenericPackageDescription pkg _ mlib0 exes0 tests0 bms0) = pkg { library = mlib , executables = reverse exes , testSuites = reverse tests , benchmarks = reverse bms , buildDepends = ldeps ++ reverse edeps ++ reverse tdeps ++ reverse bdeps } where (mlib, ldeps) = case mlib0 of Just lib -> let (l,ds) = ignoreConditions lib in (Just (libFillInDefaults l), ds) Nothing -> (Nothing, []) (exes, edeps) = foldr flattenExe ([],[]) exes0 (tests, tdeps) = foldr flattenTst ([],[]) tests0 (bms, bdeps) = foldr flattenBm ([],[]) bms0 flattenExe (n, t) (es, ds) = let (e, ds') = ignoreConditions t in ( (exeFillInDefaults $ e { exeName = n }) : es, ds' ++ ds ) flattenTst (n, t) (es, ds) = let (e, ds') = ignoreConditions t in ( (testFillInDefaults $ e { testName = n }) : es, ds' ++ ds ) flattenBm (n, t) (es, ds) = let (e, ds') = ignoreConditions t in ( (benchFillInDefaults $ e { benchmarkName = n }) : es, ds' ++ ds ) -- This is in fact rather a hack. The original version just overrode the -- default values, however, when adding conditions we had to switch to a -- modifier-based approach. There, nothing is ever overwritten, but only -- joined together. -- -- This is the cleanest way i could think of, that doesn't require -- changing all field parsing functions to return modifiers instead. libFillInDefaults :: Library -> Library libFillInDefaults lib@(Library { libBuildInfo = bi }) = lib { libBuildInfo = biFillInDefaults bi } exeFillInDefaults :: Executable -> Executable exeFillInDefaults exe@(Executable { buildInfo = bi }) = exe { buildInfo = biFillInDefaults bi } testFillInDefaults :: TestSuite -> TestSuite testFillInDefaults tst@(TestSuite { testBuildInfo = bi }) = tst { testBuildInfo = biFillInDefaults bi } benchFillInDefaults :: Benchmark -> Benchmark benchFillInDefaults bm@(Benchmark { benchmarkBuildInfo = bi }) = bm { benchmarkBuildInfo = biFillInDefaults bi } biFillInDefaults :: BuildInfo -> BuildInfo biFillInDefaults bi = if null (hsSourceDirs bi) then bi { hsSourceDirs = [currentDir] } else bi
edsko/cabal
Cabal/src/Distribution/PackageDescription/Configuration.hs
bsd-3-clause
25,834
0
20
6,936
6,219
3,320
2,899
363
19
{-# LANGUAGE BangPatterns, MultiParamTypeClasses, FunctionalDependencies, FlexibleContexts #-} ----------------------------------------------------------------------------- -- | -- Module : Data.Permute.MPermute -- Copyright : Copyright (c) , Patrick Perry <patperry@stanford.edu> -- License : BSD3 -- Maintainer : Patrick Perry <patperry@stanford.edu> -- Stability : experimental -- -- An overloaded interface to mutable permutations. For permutation types which -- can be used with this interface, see "Data.Permute.IO" and "Data.Permute.ST". -- module Data.Permute.MPermute ( -- * Class of mutable permutation types MPermute, -- * Constructing mutable permutations newPermute, newPermute_, newListPermute, newSwapsPermute, newCyclesPermute, newCopyPermute, copyPermute, setIdentity, -- * Accessing permutation elements getElem, setElem, getIndexOf, swapElems, -- * Permutation properties getSize, getElems, setElems, isValid, getIsEven, getPeriod, -- * Permutation functions getInverse, copyInverse, setNext, setPrev, -- * Applying permutations getSwaps, getInvSwaps, getCycleFrom, getCycles, -- * Sorting getSort, getSortBy, getOrder, getOrderBy, getRank, getRankBy, -- * Converstions between mutable and immutable permutations freeze, unsafeFreeze, thaw, unsafeThaw, -- * Unsafe operations unsafeNewListPermute, unsafeNewSwapsPermute, unsafeNewCyclesPermute, unsafeGetElem, unsafeSetElem, unsafeSwapElems, ) where import Control.Monad import Control.Monad.ST import Data.Function( on ) import qualified Data.List as List import System.IO.Unsafe( unsafeInterleaveIO ) import Data.Permute.Base import Data.Permute.IOBase --------------------------------- MPermute -------------------------------- -- | Class for representing a mutable permutation. The type is parameterized -- over the type of the monad, @m@, in which the mutable permutation will be -- manipulated. class (Monad m) => MPermute p m | p -> m, m -> p where -- | Get the size of a permutation. getSize :: p -> m Int -- | Create a new permutation initialized to be the identity. newPermute :: Int -> m p -- | Allocate a new permutation but do not initialize it. newPermute_ :: Int -> m p unsafeGetElem :: p -> Int -> m Int unsafeSetElem :: p -> Int -> Int -> m () unsafeSwapElems :: p -> Int -> Int -> m () -- | Get a lazy list of the permutation elements. The laziness makes this -- function slightly dangerous if you are modifying the permutation. getElems :: p -> m [Int] -- | Set all the values of a permutation from a list of elements. setElems :: p -> [Int] -> m () unsafeFreeze :: p -> m Permute unsafeThaw :: Permute -> m p unsafeInterleaveM :: m a -> m a -- | Construct a permutation from a list of elements. -- @newListPermute n is@ creates a permutation of size @n@ with -- the @i@th element equal to @is !! i@. For the permutation to be valid, -- the list @is@ must have length @n@ and contain the indices @0..(n-1)@ -- exactly once each. newListPermute :: (MPermute p m) => Int -> [Int] -> m p newListPermute n is = do p <- unsafeNewListPermute n is valid <- isValid p when (not valid) $ fail "invalid permutation" return p {-# INLINE newListPermute #-} unsafeNewListPermute :: (MPermute p m) => Int -> [Int] -> m p unsafeNewListPermute n is = do p <- newPermute_ n setElems p is return p {-# INLINE unsafeNewListPermute #-} -- | Construct a permutation from a list of swaps. -- @newSwapsPermute n ss@ creates a permutation of size @n@ given a -- sequence of swaps. -- If @ss@ is @[(i0,j0), (i1,j1), ..., (ik,jk)]@, the -- sequence of swaps is -- @i0 \<-> j0@, then -- @i1 \<-> j1@, and so on until -- @ik \<-> jk@. newSwapsPermute :: (MPermute p m) => Int -> [(Int,Int)] -> m p newSwapsPermute = newSwapsPermuteHelp swapElems {-# INLINE newSwapsPermute #-} unsafeNewSwapsPermute :: (MPermute p m) => Int -> [(Int,Int)] -> m p unsafeNewSwapsPermute = newSwapsPermuteHelp unsafeSwapElems {-# INLINE unsafeNewSwapsPermute #-} newSwapsPermuteHelp :: (MPermute p m) => (p -> Int -> Int -> m ()) -> Int -> [(Int,Int)] -> m p newSwapsPermuteHelp swap n ss = do p <- newPermute n mapM_ (uncurry $ swap p) ss return p {-# INLINE newSwapsPermuteHelp #-} -- | Construct a permutation from a list of disjoint cycles. -- @newCyclesPermute n cs@ creates a permutation of size @n@ which is the -- composition of the cycles @cs@. newCyclesPermute :: (MPermute p m) => Int -> [[Int]] -> m p newCyclesPermute n cs = newSwapsPermute n $ concatMap cycleToSwaps cs {-# INLINE newCyclesPermute #-} unsafeNewCyclesPermute :: (MPermute p m) => Int -> [[Int]] -> m p unsafeNewCyclesPermute n cs = unsafeNewSwapsPermute n $ concatMap cycleToSwaps cs {-# INLINE unsafeNewCyclesPermute #-} cycleToSwaps :: [Int] -> [(Int, Int)] cycleToSwaps [] = error "Empty cycle" cycleToSwaps (i:is) = [(i,j) | j <- reverse is] {-# INLINE cycleToSwaps #-} -- | Construct a new permutation by copying another. newCopyPermute :: (MPermute p m) => p -> m p newCopyPermute p = do n <- getSize p p' <- newPermute_ n copyPermute p' p return p' {-# INLINE newCopyPermute #-} -- | @copyPermute dst src@ copies the elements of the permutation @src@ -- into the permutation @dst@. The two permutations must have the same -- size. copyPermute :: (MPermute p m) => p -> p -> m () copyPermute dst src = getElems src >>= setElems dst {-# INLINE copyPermute #-} -- | Set a permutation to the identity. setIdentity :: (MPermute p m) => p -> m () setIdentity p = do n <- getSize p setElems p [0 .. n-1] {-# INLINE setIdentity #-} -- | @getElem p i@ gets the value of the @i@th element of the permutation -- @p@. The index @i@ must be in the range @0..(n-1)@, where @n@ is the -- size of the permutation. getElem :: (MPermute p m) => p -> Int -> m Int getElem p i = do n <- getSize p when (i < 0 || i >= n) $ fail "getElem: invalid index" unsafeGetElem p i {-# INLINE getElem #-} -- | @getIndexOf p x@ returns @i@ sutch that @getElem p i@ equals @x@. This -- is a linear-time operation. getIndexOf :: (MPermute p m) => p -> Int -> m Int getIndexOf p x = let go !i (y:ys) | y == x = i | otherwise = go (i+1) ys go _ _ = error "getIndexOf: invalid element" in liftM (go 0) $ getElems p {-# INLINE getIndexOf #-} -- | @setElem p i x@ sets the value of the @i@th element of the permutation -- @p@. The index @i@ must be in the range @0..(n-1)@, where @n@ is the -- size of the permutation. setElem :: (MPermute p m) => p -> Int -> Int -> m () setElem p i x = do n <- getSize p when (i < 0 || i >= n) $ fail "getElem: invalid index" unsafeSetElem p i x {-# INLINE setElem #-} -- | @swapElems p i j@ exchanges the @i@th and @j@th elements of the -- permutation @p@. swapElems :: (MPermute p m) => p -> Int -> Int -> m () swapElems p i j = do n <- getSize p when (i < 0 || i >= n || j < 0 || j >= n) $ fail "swapElems: invalid index" unsafeSwapElems p i j {-# INLINE swapElems #-} -- | Returns whether or not the permutation is valid. For it to be valid, -- the numbers @0,...,(n-1)@ must all appear exactly once in the stored -- values @p[0],...,p[n-1]@. isValid :: (MPermute p m) => p -> m Bool isValid p = do n <- getSize p valid <- liftM and $ validIndices n return $! valid where j `existsIn` i = do seen <- liftM (take i) $ getElems p return $ (any (==j)) seen isValidIndex n i = do i' <- unsafeGetElem p i valid <- return $ i' >= 0 && i' < n unique <- liftM not (i' `existsIn` i) return $ valid && unique validIndices n = validIndicesHelp n 0 validIndicesHelp n i | i == n = return [] | otherwise = unsafeInterleaveM $ do a <- isValidIndex n i as <- validIndicesHelp n (i+1) return (a:as) {-# INLINE isValid #-} -- | Compute the inverse of a permutation. getInverse :: (MPermute p m) => p -> m p getInverse p = do n <- getSize p q <- newPermute_ n copyInverse q p return $! q {-# INLINE getInverse #-} -- | Set one permutation to be the inverse of another. -- @copyInverse inv p@ computes the inverse of @p@ and stores it in @inv@. -- The two permutations must have the same size. copyInverse :: (MPermute p m) => p -> p -> m () copyInverse dst src = do n <- getSize src n' <- getSize dst when (n /= n') $ fail "permutation size mismatch" forM_ [0 .. n-1] $ \i -> do i' <- unsafeGetElem src i unsafeSetElem dst i' i {-# INLINE copyInverse #-} -- | Advance a permutation to the next permutation in lexicogrphic order and -- return @True@. If no further permutaitons are available, return @False@ and -- leave the permutation unmodified. Starting with the idendity permutation -- and repeatedly calling @setNext@ will iterate through all permutations of a -- given size. setNext :: (MPermute p m) => p -> m Bool setNext = setNextBy compare {-# INLINE setNext #-} -- | Step backwards to the previous permutation in lexicographic order and -- return @True@. If there is no previous permutation, return @False@ and -- leave the permutation unmodified. setPrev :: (MPermute p m) => p -> m Bool setPrev = setNextBy (flip compare) {-# INLINE setPrev #-} setNextBy :: (MPermute p m) => (Int -> Int -> Ordering) -> p -> m Bool setNextBy cmp p = do n <- getSize p if n > 1 then do findLastAscent (n-2) >>= maybe (return False) (\i -> do i' <- unsafeGetElem p i i1' <- unsafeGetElem p (i+1) (k,k') <- findSmallestLargerThan n i' (i+2) (i+1) i1' -- swap i and k unsafeSetElem p i k' unsafeSetElem p k i' reverseElems (i+1) (n-1) return True ) else return False where i `lt` j = cmp i j == LT i `gt` j = cmp i j == GT findLastAscent i = do ascent <- isAscent i if ascent then return (Just i) else recurse where recurse = if i /= 0 then findLastAscent (i-1) else return Nothing findSmallestLargerThan n i' j k k' | j < n = do j' <- unsafeGetElem p j if j' `gt` i' && j' `lt` k' then findSmallestLargerThan n i' (j+1) j j' else findSmallestLargerThan n i' (j+1) k k' | otherwise = return (k,k') isAscent i = liftM2 lt (unsafeGetElem p i) (unsafeGetElem p (i+1)) reverseElems i j | i >= j = return () | otherwise = do unsafeSwapElems p i j reverseElems (i+1) (j-1) {-# INLINE setNextBy #-} -- | Get a lazy list of swaps equivalent to the permutation. A result of -- @[ (i0,j0), (i1,j1), ..., (ik,jk) ]@ means swap @i0 \<-> j0@, -- then @i1 \<-> j1@, and so on until @ik \<-> jk@. The laziness makes this -- function slightly dangerous if you are modifying the permutation. getSwaps :: (MPermute p m) => p -> m [(Int,Int)] getSwaps = getSwapsHelp overlapping_pairs where overlapping_pairs [] = [] overlapping_pairs [_] = [] overlapping_pairs (x:xs@(y:_)) = (x,y) : overlapping_pairs xs {-# INLINE getSwaps #-} -- | Get a lazy list of swaps equivalent to the inverse of a permutation. getInvSwaps :: (MPermute p m) => p -> m [(Int,Int)] getInvSwaps = getSwapsHelp pairs_withstart where pairs_withstart [] = error "Empty cycle" pairs_withstart (x:xs) = [(x,y) | y <- xs] {-# INLINE getInvSwaps #-} getSwapsHelp :: (MPermute p m) => ([Int] -> [(Int, Int)]) -> p -> m [(Int,Int)] getSwapsHelp swapgen p = do liftM (concatMap swapgen) $ getCycles p {-# INLINE getSwapsHelp #-} -- | @getCycleFrom p i@ gets the list of elements reachable from @i@ -- by repeated application of @p@. getCycleFrom :: (MPermute p m) => p -> Int -> m [Int] getCycleFrom p i = liftM (i:) $ go i where go j = unsafeInterleaveM $ do next <- unsafeGetElem p j if next == i then return [] else liftM (next:) $ go next {-# INLINE getCycleFrom #-} -- | @getCycles p@ returns the list of disjoin cycles in @p@. getCycles :: (MPermute p m) => p -> m [[Int]] getCycles p = do n <- getSize p go n 0 where go n i | i == n = return [] | otherwise = unsafeInterleaveM $ do least <- isLeast i i if least then do c <- getCycleFrom p i liftM (c:) $ go n (i+1) else go n (i+1) isLeast i j = do k <- unsafeGetElem p j case compare i k of LT -> isLeast i k EQ -> return True GT -> return False {-# INLINE getCycles #-} -- | Whether or not the permutation is made from an even number of swaps getIsEven :: (MPermute p m) => p -> m Bool getIsEven p = do liftM (even . length) $ getSwaps p -- | @getPeriod p@ - The first power of @p@ that is the identity permutation getPeriod :: (MPermute p m) => p -> m Integer getPeriod p = do cycles <- getCycles p let lengths = map List.genericLength cycles return $ List.foldl' lcm 1 lengths -- | Convert a mutable permutation to an immutable one. freeze :: (MPermute p m) => p -> m Permute freeze p = unsafeFreeze =<< newCopyPermute p {-# INLINE freeze #-} -- | Convert an immutable permutation to a mutable one. thaw :: (MPermute p m) => Permute -> m p thaw p = newCopyPermute =<< unsafeThaw p {-# INLINE thaw #-} -- | @getSort n xs@ sorts the first @n@ elements of @xs@ and returns a -- permutation which transforms @xs@ into sorted order. The results are -- undefined if @n@ is greater than the length of @xs@. This is a special -- case of 'getSortBy'. getSort :: (Ord a, MPermute p m) => Int -> [a] -> m ([a], p) getSort = getSortBy compare {-# INLINE getSort #-} getSortBy :: (MPermute p m) => (a -> a -> Ordering) -> Int -> [a] -> m ([a], p) getSortBy cmp n xs = let ys = take n xs (is,ys') = (unzip . List.sortBy (cmp `on` snd) . zip [0..]) ys in liftM ((,) ys') $ unsafeNewListPermute n is {-# INLINE getSortBy #-} -- | @getOrder n xs@ returns a permutation which rearranges the first @n@ -- elements of @xs@ into ascending order. The results are undefined if @n@ is -- greater than the length of @xs@. This is a special case of 'getOrderBy'. getOrder :: (Ord a, MPermute p m) => Int -> [a] -> m p getOrder = getOrderBy compare {-# INLINE getOrder #-} getOrderBy :: (MPermute p m) => (a -> a -> Ordering) -> Int -> [a] -> m p getOrderBy cmp n xs = liftM snd $ getSortBy cmp n xs {-# INLINE getOrderBy #-} -- | @getRank n xs@ eturns a permutation, the inverse of which rearranges the -- first @n@ elements of @xs@ into ascending order. The returned permutation, -- @p@, has the property that @p[i]@ is the rank of the @i@th element of @xs@. -- The results are undefined if @n@ is greater than the length of @xs@. -- This is a special case of 'getRankBy'. getRank :: (Ord a, MPermute p m) => Int -> [a] -> m p getRank = getRankBy compare {-# INLINE getRank #-} getRankBy :: (MPermute p m) => (a -> a -> Ordering) -> Int -> [a] -> m p getRankBy cmp n xs = do p <- getOrderBy cmp n xs getInverse p {-# INLINE getRankBy #-} --------------------------------- Instances --------------------------------- instance MPermute (STPermute s) (ST s) where getSize = getSizeSTPermute {-# INLINE getSize #-} newPermute = newSTPermute {-# INLINE newPermute #-} newPermute_ = newSTPermute_ {-# INLINE newPermute_ #-} unsafeGetElem = unsafeGetElemSTPermute {-# INLINE unsafeGetElem #-} unsafeSetElem = unsafeSetElemSTPermute {-# INLINE unsafeSetElem #-} unsafeSwapElems = unsafeSwapElemsSTPermute {-# INLINE unsafeSwapElems #-} getElems = getElemsSTPermute {-# INLINE getElems #-} setElems = setElemsSTPermute {-# INLINE setElems #-} unsafeFreeze = unsafeFreezeSTPermute {-# INLINE unsafeFreeze #-} unsafeThaw = unsafeThawSTPermute {-# INLINE unsafeThaw #-} unsafeInterleaveM = unsafeInterleaveST {-# INLINE unsafeInterleaveM #-} instance MPermute IOPermute IO where getSize = getSizeIOPermute {-# INLINE getSize #-} newPermute = newIOPermute {-# INLINE newPermute #-} newPermute_ = newIOPermute_ {-# INLINE newPermute_ #-} unsafeGetElem = unsafeGetElemIOPermute {-# INLINE unsafeGetElem #-} unsafeSetElem = unsafeSetElemIOPermute {-# INLINE unsafeSetElem #-} unsafeSwapElems = unsafeSwapElemsIOPermute {-# INLINE unsafeSwapElems #-} getElems = getElemsIOPermute {-# INLINE getElems #-} setElems = setElemsIOPermute {-# INLINE setElems #-} unsafeFreeze = unsafeFreezeIOPermute {-# INLINE unsafeFreeze #-} unsafeThaw = unsafeThawIOPermute {-# INLINE unsafeThaw #-} unsafeInterleaveM = unsafeInterleaveIO {-# INLINE unsafeInterleaveM #-}
patperry/permutation
lib/Data/Permute/MPermute.hs
bsd-3-clause
17,466
0
19
4,604
4,181
2,189
1,992
350
5
{-# LANGUAGE AllowAmbiguousTypes #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE PatternSynonyms #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-} -- | Interface for GraphQL API. -- -- __Note__: This module is highly subject to change. We're still figuring -- where to draw the lines and what to expose. module GraphQL ( -- * Running queries interpretQuery , interpretAnonymousQuery , Response(..) -- * Preparing queries then running them , makeSchema , compileQuery , executeQuery , QueryError , Schema , VariableValues , Value ) where import Protolude import Data.Attoparsec.Text (parseOnly, endOfInput) import Data.List.NonEmpty (NonEmpty(..)) import qualified Data.List.NonEmpty as NonEmpty import GraphQL.API (HasObjectDefinition(..), Object, SchemaError(..)) import GraphQL.Internal.Execution ( VariableValues , ExecutionError , substituteVariables ) import qualified GraphQL.Internal.Execution as Execution import qualified GraphQL.Internal.Syntax.AST as AST import qualified GraphQL.Internal.Syntax.Parser as Parser import GraphQL.Internal.Validation ( QueryDocument , SelectionSetByType , ValidationErrors , validate , getSelectionSet , VariableValue ) import GraphQL.Internal.Output ( GraphQLError(..) , Response(..) , singleError ) import GraphQL.Internal.Schema (Schema) import qualified GraphQL.Internal.Schema as Schema import GraphQL.Resolver ( HasResolver(..) , OperationResolverConstraint , Result(..) , resolveOperation ) import GraphQL.Value (Name, Value) -- | Errors that can happen while processing a query document. data QueryError -- | Failed to parse. = ParseError Text -- | Parsed, but failed validation. -- -- See <https://facebook.github.io/graphql/#sec-Validation> for more -- details. | ValidationError ValidationErrors -- | Validated, but failed during execution. | ExecutionError ExecutionError -- | Error in the schema. | SchemaError SchemaError -- | Got a value that wasn't an object. | NonObjectResult Value deriving (Eq, Show) instance GraphQLError QueryError where formatError (ParseError e) = "Couldn't parse query document: " <> e formatError (ValidationError es) = "Validation errors:\n" <> mconcat [" " <> formatError e <> "\n" | e <- NonEmpty.toList es] formatError (ExecutionError e) = "Execution error: " <> show e formatError (SchemaError e) = "Schema error: " <> formatError e formatError (NonObjectResult v) = "Query returned a value that is not an object: " <> show v -- | Execute a GraphQL query. executeQuery :: forall api m fields typeName interfaces. ( Object typeName interfaces fields ~ api , OperationResolverConstraint m fields typeName interfaces ) => Handler m api -- ^ Handler for the query. This links the query to the code you've written to handle it. -> QueryDocument VariableValue -- ^ A validated query document. Build one with 'compileQuery'. -> Maybe Name -- ^ An optional name. If 'Nothing', then executes the only operation in the query. If @Just "something"@, executes the query named @"something". -> VariableValues -- ^ Values for variables defined in the query document. A map of 'Variable' to 'Value'. -> m Response -- ^ The outcome of running the query. executeQuery handler document name variables = case getOperation document name variables of Left e -> pure (ExecutionFailure (singleError e)) Right operation -> toResult <$> resolveOperation @m @fields @typeName @interfaces handler operation where toResult (Result errors object) = case NonEmpty.nonEmpty errors of Nothing -> Success object Just errs -> PartialSuccess object (map toError errs) -- | Create a GraphQL schema. makeSchema :: forall api. HasObjectDefinition api => Either QueryError Schema makeSchema = first SchemaError (Schema.makeSchema <$> getDefinition @api) -- | Interpet a GraphQL query. -- -- Compiles then executes a GraphQL query. interpretQuery :: forall api m fields typeName interfaces. ( Object typeName interfaces fields ~ api , OperationResolverConstraint m fields typeName interfaces ) => Handler m api -- ^ Handler for the query. This links the query to the code you've written to handle it. -> Text -- ^ The text of a query document. Will be parsed and then executed. -> Maybe Name -- ^ An optional name for the operation within document to run. If 'Nothing', execute the only operation in the document. If @Just "something"@, execute the query or mutation named @"something"@. -> VariableValues -- ^ Values for variables defined in the query document. A map of 'Variable' to 'Value'. -> m Response -- ^ The outcome of running the query. interpretQuery handler query name variables = case makeSchema @api >>= flip compileQuery query of Left err -> pure (PreExecutionFailure (toError err :| [])) Right document -> executeQuery @api @m handler document name variables -- | Interpret an anonymous GraphQL query. -- -- Anonymous queries have no name and take no variables. interpretAnonymousQuery :: forall api m fields typeName interfaces. ( Object typeName interfaces fields ~ api , OperationResolverConstraint m fields typeName interfaces ) => Handler m api -- ^ Handler for the anonymous query. -> Text -- ^ The text of the anonymous query. Should defined only a single, unnamed query operation. -> m Response -- ^ The result of running the query. interpretAnonymousQuery handler query = interpretQuery @api @m handler query Nothing mempty -- | Turn some text into a valid query document. compileQuery :: Schema -> Text -> Either QueryError (QueryDocument VariableValue) compileQuery schema query = do parsed <- first ParseError (parseQuery query) first ValidationError (validate schema parsed) -- | Parse a query document. parseQuery :: Text -> Either Text AST.QueryDocument parseQuery query = first toS (parseOnly (Parser.queryDocument <* endOfInput) query) -- | Get an operation from a query document ready to be processed. getOperation :: QueryDocument VariableValue -> Maybe Name -> VariableValues -> Either QueryError (SelectionSetByType Value) getOperation document name vars = first ExecutionError $ do op <- Execution.getOperation document name resolved <- substituteVariables op vars pure (getSelectionSet resolved)
jml/graphql-api
src/GraphQL.hs
bsd-3-clause
6,404
0
13
1,153
1,196
659
537
-1
-1
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE UndecidableInstances #-} module EFA.Utility.List where vhead :: String -> [a] -> a vhead _ (x:_) = x vhead caller _ = error $ "vhead, " ++ caller ++ ": empty list" vlast :: String -> [a] -> a vlast _ xs@(_:_) = last xs vlast caller _ = error $ "vlast, " ++ caller ++ ": empty list" -- | Example -- -- >>> takeUntil (>5) [1..10] -- [1,2,3,4,5,6] takeUntil :: (a -> Bool) -> [a] -> [a] takeUntil p = go where go (x:xs) = x : if not (p x) then go xs else [] go [] = []
energyflowanalysis/efa-2.1
src/EFA/Utility/List.hs
bsd-3-clause
531
0
11
124
218
119
99
13
3
{-| Copyright : (c) Dave Laing, 2017 License : BSD3 Maintainer : dave.laing.80@gmail.com Stability : experimental Portability : non-portable -} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE PolyKinds #-} module Rules.Kind.Infer.Offline ( UnifyT , IKOffline ) where import Control.Monad (unless) import Data.Foldable (toList) import Data.List (tails) import Data.Proxy (Proxy(..)) import Bound (Bound) import Control.Monad.Error.Lens (throwing) import Control.Monad.Except (MonadError) import Control.Monad.Writer (MonadWriter(..), WriterT, execWriterT, runWriterT) import Data.List.NonEmpty (NonEmpty(..)) import qualified Data.List.NonEmpty as N import qualified Data.Map as M import Data.Bitransversable import Data.Functor.Rec import Ast.Kind import Ast.Type import Ast.Error.Common import Context.Type.Error import Rules.Unification import Rules.Kind.Infer.Common type UnifyT ki a = WriterT [UConstraint (Kind ki) a] mkInferKind' :: (UnificationContext e m (Kind ki) a, MonadError e m) => (Type ki ty a -> UnifyT ki a m (Kind ki a)) -> ([UConstraint (Kind ki) a] -> m (M.Map a (Kind ki a))) -> Type ki ty a -> m (Kind ki a) mkInferKind' go unifyFn x = do (ty, cs) <- runWriterT $ go x s <- unifyFn cs return $ mapSubst _KiVar s ty data IKOffline mkCheck' :: MkInferKindConstraint e w s r m ki ty a IKOffline => Proxy (MonadProxy e w s r m) -> (Type ki ty a -> UnifyT ki a m (Kind ki a)) -> ([UConstraint (Kind ki) a] -> m (M.Map a (Kind ki a))) -> Type ki ty a -> Kind ki a -> m () mkCheck' m inferFn unifyFn x y = do cs <- execWriterT $ (mkCheckKind m (Proxy :: Proxy ki) (Proxy :: Proxy ty) (Proxy :: Proxy a) (Proxy :: Proxy IKOffline) inferFn) x y _ <- unifyFn cs return () instance MkInferKind IKOffline where type MkInferKindConstraint e w s r m ki ty a IKOffline = ( MonadError e m , AsUnknownKindError e , AsOccursError e (Kind ki) a , AsUnificationMismatch e (Kind ki) a , AsUnificationExpectedEq e (Kind ki) a , AsUnboundTypeVariable e a , Ord a , OrdRec ki , OrdRec (ty ki) , Bound ki , Bitransversable ki , Bound (ty ki) , Bitransversable (ty ki) ) type InferKindMonad m ki a IKOffline = UnifyT ki a m type MkInferKindErrorList ki ty a IKOffline = '[ ErrOccursError (Kind ki) a , ErrUnificationMismatch (Kind ki) a , ErrUnificationExpectedEq (Kind ki) a , ErrUnificationExpectedEq (Type ki ty) a , ErrUnboundTypeVariable a ] type MkInferKindWarningList ki ty a IKOffline = '[] mkCheckKind m ki ty a i = mkCheckKind' i (expectKind m ki ty a i) expectKind _ _ _ _ _ (ExpectedKind ki1) (ActualKind ki2) = unless (ki1 == ki2) $ tell [UCEq ki1 ki2] expectKindEq _ _ _ _ _ ki1 ki2 = unless (ki1 == ki2) $ tell [UCEq ki1 ki2] expectKindAllEq _ _ _ _ _ n@(ki :| kis) = do unless (all (== ki) kis) $ let xss = tails . N.toList $ n f [] = [] f (x : xs) = fmap (UCEq x) xs ws = xss >>= f in tell ws return ki prepareInferKind pm pki pty pa pi kri = let u = mkUnify _KiVar id . kriUnifyRules $ kri i = mkInferKind . kriInferRules $ kri convertKind k = case toList k of [] -> return k (x : _) -> throwing _UnboundTypeVariable x i' = (>>= convertKind) . mkInferKind' i u c = mkCheck' pm i u in InferKindOutput i' c
dalaing/type-systems
src/Rules/Kind/Infer/Offline.hs
bsd-3-clause
3,672
0
15
967
1,361
709
652
-1
-1
{-# LANGUAGE ExistentialQuantification #-} module Data.IORef.ReadWrite ( ReadWriteIORef , toReadWriteIORef ) where import Data.Bifunctor (first) import Data.IORef (IORef) import Data.IORef.Class data ReadWriteIORef a = forall b. ReadWriteIORef (IORef b) (a -> b) (b -> a) toReadWriteIORef :: IORef a -> ReadWriteIORef a toReadWriteIORef ref = ReadWriteIORef ref id id instance IORefRead ReadWriteIORef where readIORef (ReadWriteIORef ref _ g) = g <$> readIORef ref {-# INLINE readIORef #-} instance IORefWrite ReadWriteIORef where writeIORef (ReadWriteIORef ref f _) a = writeIORef ref (f a) {-# INLINE writeIORef #-} atomicWriteIORef (ReadWriteIORef ref f _) a = atomicWriteIORef ref (f a) {-# INLINE atomicWriteIORef #-} instance IORefReadWrite ReadWriteIORef where modifyIORef (ReadWriteIORef ref f g) h = modifyIORef ref (f . h . g) {-# INLINE modifyIORef #-} modifyIORef' (ReadWriteIORef ref f g) h = modifyIORef' ref (f . h . g) {-# INLINE modifyIORef' #-} atomicModifyIORef (ReadWriteIORef ref f g) h = atomicModifyIORef ref $ first f . h . g {-# INLINE atomicModifyIORef #-} atomicModifyIORef' (ReadWriteIORef ref f g) h = atomicModifyIORef' ref $ first f . h . g {-# INLINE atomicModifyIORef' #-}
osa1/privileged-concurrency
Data/IORef/ReadWrite.hs
bsd-3-clause
1,251
0
9
226
377
196
181
27
1
module Main where main :: IO () main = print $ length ('a', 'b')
stepcut/safe-length
example/BrokenTuple.hs
bsd-3-clause
66
0
7
15
32
18
14
3
1
module Main where import Control.Lens import Numeric.Lens (binary, negated, adding) import Test.Tasty (TestTree, defaultMain, testGroup) import Test.Tasty.ExpectedFailure (allowFail) import Test.DumbCheck -- (TestTree, defaultMain, testGroup) import qualified Test.Tasty.Lens.Iso as Iso import qualified Test.Tasty.Lens.Lens as Lens import qualified Test.Tasty.Lens.Prism as Prism main :: IO () main = defaultMain $ testGroup "Lens tests" [ tupleTests , maybeTests , numTests ] tupleTests :: TestTree tupleTests = testGroup "Tuples" [ testGroup "_1" [ testGroup "Lens' (Char,Char) Char" [ Lens.test (_1 :: Lens' (Char,Char) Char) ] , testGroup "Lens' (Int,Char) Int" [ Lens.test (_1 :: Lens' (Int,Char) Int) ] ] , testGroup "_2" [ testGroup "Lens' (Char,Char,Char) Char" [ Lens.test (_2 :: Lens' (Char,Char,Char) Char) ] ] ] maybeTests :: TestTree maybeTests = testGroup "Maybe" [ testGroup "_Nothing" [ testGroup "Prism' (Maybe Char) ()" [ Prism.test (_Nothing :: Prism' (Maybe Char) ()) ] , testGroup "Prism' (Maybe Int) ()" [ Prism.test (_Nothing :: Prism' (Maybe Int) ()) ] ] , testGroup "_Just" [ testGroup "Prism' (Maybe Char) Char" [ Prism.test (_Just :: Prism' (Maybe Char) Char) ] , testGroup "Prism' (Maybe Int) Int" [ Prism.test (_Just :: Prism' (Maybe Int) Int) ] ] ] type AlphaNumString = [AlphaNum] numTests :: TestTree numTests = testGroup "Numeric" [ testGroup "negated" [ testGroup "Iso' Int Int" [ Iso.test (negated :: Iso' Int Int) ] , testGroup "Iso' Float Float" [ Iso.test (negated :: Iso' Float Float) ] ] , testGroup "binary" [ testGroup "Prism'' String Int" [ allowFail $ Prism.test (_AlphaNumString . (binary :: Prism' String Int)) ] , testGroup "Prism'' String Integer" [ Prism.test (binary :: Prism' String Integer) ] ] , testGroup "adding" [ testGroup "Iso' Int Int" [ Iso.test (adding 2 :: Iso' Int Int) ] , testGroup "Iso' Integer Integer" [ Iso.test (adding 3 :: Iso' Integer Integer) ] ] ] where _AlphaNumString :: Iso' AlphaNumString String _AlphaNumString = iso (fmap unAlphaNum) (fmap AlphaNum)
jdnavarro/tasty-lens
tests/tasty.hs
bsd-3-clause
2,255
0
16
533
682
372
310
57
1
{-# LANGUAGE BangPatterns #-} -- need a fast way to represent a sudo puzzle -- use vector reference: https://wiki.haskell.org/Numeric_Haskell:_A_Vector_Tutorial -- * End users should use Data.Vector.Unboxed for most cases -- * If you need to store more complex structures, use Data.Vector -- * If you need to pass to C, use Data.Vector.Storable import qualified Data.Vector as V import System.Environment -- import Data.ByteString.Lazy.Char8 as BL import Data.List (partition, intersect, nub) data Cell = Unique Int | Choice [Int] deriving (Eq) newtype Puzzle = Puzzle (V.Vector (V.Vector Cell)) -- for this simple solution, I should just use Array. and make Cell = Int is enough instance Show Cell where show (Unique n) = show n show (Choice _) = "0" instance Show Puzzle where show puz = unlines . map (concatMap show) . puzzleToList $ puz listToPuzzle :: [[Int]] -> Puzzle listToPuzzle xs = Puzzle . V.fromList . map change $ xs where change = V.fromList . map parse parse 0 = Choice [1..9] parse n = Unique n puzzleToList :: Puzzle -> [[Cell]] puzzleToList (Puzzle puz) = V.toList . (V.map V.toList) $ puz index :: Int -> Int -> Puzzle -> Cell index i j (Puzzle puz) = (puz V.! i) V.! j indexCol i puz = [index i j puz | j <- [0..8]] indexRow j puz = [index i j puz | i <- [0..8]] indexTri i puz = [index x y puz | x <- sets !! i' , y <- sets !! j'] where (i', j') = divMod i 3 sets = [[0,1,2],[3,4,5],[6,7,8]] isLegal :: Puzzle -> Bool isLegal puz = all legal [indexCol i puz | i <- [0..8]] && all legal [indexRow i puz | i <- [0..8]] && all legal [indexTri i puz | i <- [0..8]] where legal :: [Cell] -> Bool legal xs = let (uni, choices) = partition par xs par (Unique _) = True par _ = False uni' = map (\(Unique x) -> x) uni choices' = concatMap (\(Choice ys) -> ys) choices in length uni == length (nub uni) -- rest check not used for solution 1 && null (intersect uni' choices') isFinish :: Puzzle -> Bool isFinish (Puzzle puz) = V.all id . V.map (V.all par) $ puz where par (Unique _) = True par _ = False update :: Puzzle -> ((Int, Int), Cell) -> Puzzle update (Puzzle puz) ((m, n), x) = Puzzle (puz V.// [(m, inner)]) where inner = puz V.! m inner' = inner V.// [(n, x)] solution :: Puzzle -> Maybe Puzzle solution puz = walk puz 0 where walk puz 81 = if isFinish puz then Just puz else Nothing walk puz num = let (m, n) = divMod num 9 cell = index m n puz isUnique = case cell of Unique _ -> True _ -> False in if isUnique then walk puz (num+1) else go puz m n 1 go _ _ _ 10 = Nothing go puz m n x = let out = update puz ((m, n), Unique x) in if isLegal out then case walk out (m*9+n+1) of Just puz' -> Just puz' Nothing -> go puz m n (x+1) else go puz m n (x+1) parseString :: String -> [[Int]] parseString = map (map (read . (:[]))) . lines -- main :: IO () main = do content <- readFile "data" let puz = listToPuzzle $ parseString content print $ solution puz -- Why these function alawys give answer to sudoku problem? -- because it is actually traverse all possible combination for the problem. -- a brute algorithm, which take a lot of time
niexshao/Exercises
src/Euler96-Sudoku/sudoku1.hs
bsd-3-clause
3,446
0
15
985
1,313
690
623
72
8
{-# LANGUAGE CPP #-} ----------------------------------------------------------------------------- -- | -- Module : Xmobar.Plugins.Monitors -- Copyright : (c) 2010, 2011, 2012, 2013 Jose Antonio Ortega Ruiz -- (c) 2007-10 Andrea Rossato -- License : BSD-style (see LICENSE) -- -- Maintainer : Jose A. Ortega Ruiz <jao@gnu.org> -- Stability : unstable -- Portability : unportable -- -- The system monitor plugin for Xmobar. -- ----------------------------------------------------------------------------- module Plugins.Monitors where import Plugins import Plugins.Monitors.Common (runM, runMD) import Plugins.Monitors.Weather import Plugins.Monitors.Net import Plugins.Monitors.Mem import Plugins.Monitors.Swap import Plugins.Monitors.Cpu import Plugins.Monitors.MultiCpu import Plugins.Monitors.Batt import Plugins.Monitors.Bright import Plugins.Monitors.Thermal import Plugins.Monitors.ThermalZone import Plugins.Monitors.CpuFreq import Plugins.Monitors.CoreTemp import Plugins.Monitors.Disk import Plugins.Monitors.Top import Plugins.Monitors.Uptime #ifdef IWLIB import Plugins.Monitors.Wireless #endif #ifdef LIBMPD import Plugins.Monitors.MPD import Plugins.Monitors.Common (runMBD) #endif #ifdef ALSA import Plugins.Monitors.Volume #endif #ifdef MPRIS import Plugins.Monitors.Mpris #endif data Monitors = Weather Station Args Rate | Network Interface Args Rate | DynNetwork Args Rate | BatteryP Args Args Rate | BatteryN Args Args Rate Alias | Battery Args Rate | DiskU DiskSpec Args Rate | DiskIO DiskSpec Args Rate | Thermal Zone Args Rate | ThermalZone ZoneNo Args Rate | Memory Args Rate | Swap Args Rate | Cpu Args Rate | MultiCpu Args Rate | Brightness Args Rate | CpuFreq Args Rate | CoreTemp Args Rate | TopProc Args Rate | TopMem Args Rate | Uptime Args Rate #ifdef IWLIB | Wireless Interface Args Rate #endif #ifdef LIBMPD | MPD Args Rate | AutoMPD Args #endif #ifdef ALSA | Volume String String Args Rate #endif #ifdef MPRIS | Mpris1 String Args Rate | Mpris2 String Args Rate #endif deriving (Show,Read,Eq) type Args = [String] type Program = String type Alias = String type Station = String type Zone = String type ZoneNo = Int type Interface = String type Rate = Int type DiskSpec = [(String, String)] instance Exec Monitors where alias (Weather s _ _) = s alias (Network i _ _) = i alias (DynNetwork _ _) = "dynnetwork" alias (Thermal z _ _) = z alias (ThermalZone z _ _) = "thermal" ++ show z alias (Memory _ _) = "memory" alias (Swap _ _) = "swap" alias (Cpu _ _) = "cpu" alias (MultiCpu _ _) = "multicpu" alias (Battery _ _) = "battery" alias (BatteryP _ _ _)= "battery" alias (BatteryN _ _ _ a)= a alias (Brightness _ _) = "bright" alias (CpuFreq _ _) = "cpufreq" alias (TopProc _ _) = "top" alias (TopMem _ _) = "topmem" alias (CoreTemp _ _) = "coretemp" alias (DiskU _ _ _) = "disku" alias (DiskIO _ _ _) = "diskio" alias (Uptime _ _) = "uptime" #ifdef IWLIB alias (Wireless i _ _) = i ++ "wi" #endif #ifdef LIBMPD alias (MPD _ _) = "mpd" alias (AutoMPD _) = "autompd" #endif #ifdef ALSA alias (Volume m c _ _) = m ++ ":" ++ c #endif #ifdef MPRIS alias (Mpris1 _ _ _) = "mpris1" alias (Mpris2 _ _ _) = "mpris2" #endif start (Network i a r) = startNet i a r start (DynNetwork a r) = startDynNet a r start (Cpu a r) = startCpu a r start (MultiCpu a r) = startMultiCpu a r start (TopProc a r) = startTop a r start (TopMem a r) = runM a topMemConfig runTopMem r start (Weather s a r) = runMD (a ++ [s]) weatherConfig runWeather r weatherReady start (Thermal z a r) = runM (a ++ [z]) thermalConfig runThermal r start (ThermalZone z a r) = runM (a ++ [show z]) thermalZoneConfig runThermalZone r start (Memory a r) = runM a memConfig runMem r start (Swap a r) = runM a swapConfig runSwap r start (Battery a r) = runM a battConfig runBatt r start (BatteryP s a r) = runM a battConfig (runBatt' s) r start (BatteryN s a r _) = runM a battConfig (runBatt' s) r start (Brightness a r) = runM a brightConfig runBright r start (CpuFreq a r) = runM a cpuFreqConfig runCpuFreq r start (CoreTemp a r) = runM a coreTempConfig runCoreTemp r start (DiskU s a r) = runM a diskUConfig (runDiskU s) r start (DiskIO s a r) = startDiskIO s a r start (Uptime a r) = runM a uptimeConfig runUptime r #ifdef IWLIB start (Wireless i a r) = runM (a ++ [i]) wirelessConfig runWireless r #endif #ifdef LIBMPD start (MPD a r) = runMD a mpdConfig runMPD r mpdReady start (AutoMPD a) = runMBD a mpdConfig runMPD mpdWait mpdReady #endif #ifdef ALSA start (Volume m c a r) = runM a volumeConfig (runVolume m c) r #endif #ifdef MPRIS start (Mpris1 s a r) = runM a mprisConfig (runMPRIS1 s) r start (Mpris2 s a r) = runM a mprisConfig (runMPRIS2 s) r #endif
apoikos/pkg-xmobar
src/Plugins/Monitors.hs
bsd-3-clause
5,554
0
10
1,686
1,700
912
788
91
0
{-# LANGUAGE RecordWildCards #-} module Helper ( emptyEnv , newUserAct , midnight , stubRunner , stubCommand , addUser , createEnv , createUser , createPost , stubUsers , secAfterMidnight , usersEnv , newSysAct ) where import Types import qualified Data.Map.Lazy as Map (insert, empty, fromList) import Data.Time.Calendar (fromGregorian) import Data.Time.Clock import Env emptyEnv :: Env emptyEnv = createEnv (Map.empty, Map.empty, midnight) usersEnv :: Env usersEnv = createEnv (Map.empty, stubUsers, secAfterMidnight 250) newSysAct :: String -> UTCTime -> Action newSysAct xs t = SystemAct { sysAct = xs, sysTime = t } newUserAct :: String -> String -> String -> UTCTime -> Action newUserAct n act args t = UserAct { userName = n , action = act , args = args , time = t } createEnv :: (Commands, Users, UTCTime) -> Env createEnv (c, u, t) = Env { cmds = c , users = u , eTime = t } midnight :: UTCTime midnight = UTCTime (fromGregorian 2017 1 1) 0 stubRunner :: ActionRunner stubRunner a = return "" stubCommand :: Command stubCommand = Cmd { cmd = "stub", runner = stubRunner, desc = "a stub command"} addUser :: User -> Env -> Env addUser u@User{..} e@Env{..} = e { users = Map.insert name u users} createUser :: (String, [Post], [String]) -> User createUser (n, ps, fs) = User { name = n , posts = ps , followings = fs } createPost :: (String, String, UTCTime) -> Post createPost (u, m, d) = Post { user = u , msg = m , date = d } stubUsers :: Users stubUsers = Map.fromList $ zip ["foo", "bob", "alice"] users where users = map createUser [ ("foo", fooPosts, ["bob", "alice"]) , ("bob", bobPosts, ["alice"]) , ("alice", alicePosts, ["foo"]) ] fooPosts :: [Post] fooPosts = map createPost [ ("foo", "ruuun", secAfterMidnight 200) , ("foo", "goooo", secAfterMidnight 210) , ("foo", "get to the choppaaa!", secAfterMidnight 220) ] bobPosts :: [Post] bobPosts = map createPost [ ("bob", "hello!", secAfterMidnight 10) , ("bob", "I'm batman", secAfterMidnight 20) , ("bob", "you ok bro?", secAfterMidnight 215) ] alicePosts :: [Post] alicePosts = map createPost [ ("alice", "I like dogs", midnight) ] secAfterMidnight :: Integer -> UTCTime secAfterMidnight = UTCTime (fromGregorian 2017 1 1) . secondsToDiffTime
lpalma/hamerkop
test/Helper.hs
bsd-3-clause
2,747
0
10
904
817
486
331
71
1
-- | Collection of types (@Proc_*@ types and others), and -- some functions on these types as well. module Graphics.Web.Processing.Core.Types ( -- * Processing Script ProcScript (..) , emptyScript -- ** Script rendering , renderScript , renderFile -- ** Processing Code , ProcCode -- * Contexts , Preamble (..) , Setup (..) , Draw (..) , MouseClicked (..) , MouseReleased (..) , KeyPressed (..) -- * @Proc_*@ types , ProcType -- ** Bool , Proc_Bool, true, false , fromBool , pnot, (#||), (#&&) -- ** Int , Proc_Int , fromInt , intToFloat -- ** Float , Proc_Float , fromFloat , pfloor , pround -- ** Char , Proc_Char , fromChar -- ** Text , Proc_Text , fromStText , (+.+) , Proc_Show (..) -- ** Image , Proc_Image -- * Processing classes , Proc_Eq (..) , Proc_Ord (..) -- * Conditional values , if_ ) where import Graphics.Web.Processing.Core.Primal import Text.PrettyPrint.Mainland import Data.Text.Lazy (Text) import qualified Data.Text.Lazy.IO as T charsPerLine :: Int charsPerLine = 80 -- | Render a script as a lazy 'Text'. renderScript :: ProcScript -> Text renderScript = prettyLazyText charsPerLine . ppr -- | Render a script using 'renderScript' and -- write it directly in a file. renderFile :: FilePath -> ProcScript -> IO () renderFile fp = T.writeFile fp . renderScript -- | Conditional value. For example: -- -- > if_ (x #> 3) "X is greater than 3." -- > "X is less than or equal to 3." -- if_ :: ProcType a => Proc_Bool -> a -> a -> a if_ = proc_cond
Daniel-Diaz/processing
Graphics/Web/Processing/Core/Types.hs
bsd-3-clause
1,582
0
8
373
318
213
105
45
1
module MakeTerm where import BruijnTerm import Value import Name val :: Value -> LamTerm () () n val = Val () var :: String -> LamTerm () () Name var = Var () . fromString double :: Double -> LamTerm () () n double = Val () . Prim . MyDouble true :: LamTerm () () n true = Val () $ Prim $ MyBool True false :: LamTerm () () n false = Val () $ Prim $ MyBool False bvar :: Int -> BruijnTerm () () bvar = Var () . Bound lambda :: String -> LamTerm () () n -> LamTerm () () n lambda = Lambda () . fromString appl :: LamTerm ()() n -> LamTerm () () n -> LamTerm () () n appl = Appl mkLet :: [(String, LamTerm () () n)] -> LamTerm () () n -> LamTerm () () n mkLet tupleDef = Let () (map (uncurry (Def (). Name )) tupleDef) def :: String -> t -> Def () t def = Def () . Name
kwibus/myLang
tests/MakeTerm.hs
bsd-3-clause
779
0
13
186
451
226
225
24
1
module Main where import GHC.IO.Handle import System.Console.GetOpt import System.Environment import System.Exit import System.IO import Data.Aeson import Sampler import Control.Monad ( replicateM ) import qualified Data.ByteString.Lazy.Char8 as B data Flag = OutputFile String -- ^ output file location | LowerBound String -- ^ structure size lower bound | UpperBound String -- ^ structure size upper bound | Samples String -- ^ number of samples | Help -- ^ whether to print usage help text deriving (Show,Eq) options :: [OptDescr Flag] options = [ Option "o" ["output"] (ReqArg OutputFile "FILE") "Output file. If not given, STDOUT is used instead." , Option "l" ["lower-bound"] (ReqArg LowerBound "N") "Lower bound for the structure size. Default: 10." , Option "u" ["upper-bound"] (ReqArg UpperBound "N") "Upper bound for the structure size. Default: 50." , Option "s" ["samples"] (ReqArg Samples "N") "Number of structures to sample. Default: 1." , Option "h" ["help"] (NoArg Help) "Prints this help message." ] outputF :: [Flag] -> Maybe String outputF (OutputFile f : _ ) = Just f outputF (_ : fs) = outputF fs outputF [] = Nothing lowerBound :: [Flag] -> Int lowerBound (LowerBound n : _ ) = (read n) lowerBound (_ : opts) = lowerBound opts lowerBound [] = 10 upperBound :: [Flag] -> Int upperBound (UpperBound n : _ ) = read n upperBound (_ : opts) = upperBound opts upperBound [] = 50 samples :: [Flag] -> Int samples (Samples n : _ ) = read n samples (_ : opts) = samples opts samples [] = 1 fail' s = do hPutStrLn stderr s exitWith (ExitFailure 1) align :: String -> String -> String align s t = s ++ t ++ replicate (80 - length s - length t) ' ' version :: String version = "v2.0" signature :: String signature = "Boltzmann Brain " ++ version versionHeader :: String versionHeader = signature ++ " (c) 2017-2021." logoHeader :: String logoHeader = align s versionHeader where s = " `/:/::- ` ././:.` " buildTimeHeader :: String buildTimeHeader = align s "Sampler" where s = " .- `..- " artLogo :: String artLogo = unlines [ " .-- " , " .-` ./:`` ` " , " .:.-` `.-` ..--:/ .+- ``....:::. " , " ``.:`-:-::` --..:--//:+/-````:-`.```.-` `//::///---`" , " ``::-:` //+:. `. `...`-::.++//++/:----:-:.-:/-`/oo+::/-" , " /o. .:::/-.-:` ` -://:::/:// .::`.-..::/:- " , " `` ``````.-:` `.`...-/`. `- ``.` `.:/:` -:. " , " ...+-/-:--::-:` -::/-/:-`.-.`..:::/+:. `+` " , " `:-.-::::--::.```:/+:-:` ./+/:-+:. :-`.` --. " , " `` .`.:-``.////-``../++:/::-:/--::::-+/:. -+- " , "..`..-...:```````-:::`.`.///:-.` ``-.-``.:. ` `/.:/:` `-` " , "`:////::/+-/+/.`:/o++/:::++-:-.-- . ` `.+/. ` " , " ` :/:``--.:- .--/+++-::-:-: ` .:. " , " -::+:./:://+:--.-:://-``/+-` .` " , " -/`.- -/o+/o+/+//+++//o+. " , " ` `:/+/s+-...```.://-- " , logoHeader , buildTimeHeader ] usage = do putStrLn artLogo putStr (usageInfo "Usage:" options) exitWith (ExitFailure 1) -- | Parses the CLI arguments into the command string -- and some additional (optional) flags. parse :: [String] -> IO [Flag] parse argv = case getOpt Permute options argv of (opts, _, []) | Help `elem` opts -> usage | otherwise -> return opts (_, _, errs) -> fail' $ concat errs -- | Sets up stdout and stdin IO handles. handleIO :: [Flag] -> IO () handleIO opts = do case outputF opts of Just file -> do h <- openFile file WriteMode hDuplicateTo h stdout -- h becomes the new stdout Nothing -> return () main :: IO () main = do opts <- getArgs >>= parse handleIO opts -- set up IO handles. let lb = lowerBound opts let ub = upperBound opts let n = samples opts xs <- replicateM n (SAMPLE_COMMAND lb ub) B.putStrLn $ encode xs
maciej-bendkowski/boltzmann-brain
scripts/sampler-template/app/Main.hs
bsd-3-clause
4,877
0
13
1,915
1,028
539
489
113
2
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE ScopedTypeVariables #-} -- | Simple program to proxy a SFTP session. I.e. a SFTP client will spawn us -- through SSH instead of a real sftp executable. It won't see any difference -- as we are fully transparent, but we can se what the protocol looks like. module Main (main) where import Control.Applicative ((<$>), (<*), (<*>)) import Control.Concurrent (forkIO) import Control.Concurrent.MVar (newEmptyMVar, putMVar, takeMVar, MVar) import Control.Exception (finally) import Control.Monad (when) import Control.Monad.Trans.Class import Control.Monad.Trans.Writer import qualified Data.Attoparsec.ByteString as AB (take) import Data.Attoparsec.ByteString hiding (parse, take) import Data.Bits (unsafeShiftL, (.&.), Bits) import Data.ByteString (ByteString) import qualified Data.ByteString.Base16 as Base16 import qualified Data.ByteString.Char8 as BC import Data.List (partition) import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.Encoding as T (decodeUtf8) import Data.Word (Word8, Word32, Word64) import System.Environment (getArgs) import System.IO (hClose, hFlush, hPutStrLn, hSetBuffering, stdin, stderr, stdout, BufferMode(..)) import System.IO.Streams (InputStream, OutputStream) import qualified System.IO.Streams as S import qualified System.IO.Streams.Attoparsec as S import qualified System.Process as P import Network.SFTP.Messages debug :: String -> IO () debug s = hPutStrLn stderr ("### " ++ s) >> hFlush stderr ---------------------------------------------------------------------- -- Main loop: -- We connect our stdin, stdout, and stderr to the real sftp process -- and feed at the same time our parser. ---------------------------------------------------------------------- main :: IO () main = do hSetBuffering stdin NoBuffering hSetBuffering stdout NoBuffering hSetBuffering stderr NoBuffering args <- getArgs (sftpInp, sftpOut, sftpErr, _) <- runInteractiveProcess "/usr/lib/openssh/sftp-server-original" args Nothing Nothing (is, is') <- splitIS S.stdin (is2, is2') <- splitIS sftpOut inThread <- forkIO $ S.connect is' sftpInp errThread <- forkIO $ S.connect sftpErr S.stderr _ <- forkIO $ S.connect is2' S.stdout -- S.withFileAsOutput "/home/sftp/debug.txt" $ \observe -> do mvar <- newEmptyMVar _ <- forkIO $ do ps <- execWriterT (protocol is) putMVar mvar ps ps <- execWriterT (protocol is2) ps' <- takeMVar mvar S.withFileAsOutput "/home/sftp/debug.txt" $ \os -> do S.write (Just . BC.pack $ "Arguments: " ++ show args ++ "\n") os mapM_ (\(s, p) -> S.write (Just . BC.pack $ s ++ display p ++ "\n") os) $ merge ps' ps return () -- takeMVar inThread -- takeMVar errThread merge [] ys = map ("<<< ",) ys merge (x:xs) ys = (">>> ", x) : ("<<< ", y') : merge xs ys' where (y', ys') = case partition ((== packetId x) . packetId) ys of (y:ys1, ys2) -> (y, ys1 ++ ys2) (_, ys2) -> (Unknown (RequestId 0) "Missing response.", ys2) waitableForkIO :: IO () -> IO (MVar ()) waitableForkIO io = do mvar <- newEmptyMVar _ <- forkIO (io `finally` putMVar mvar ()) return mvar -- | Similar to S.runInteractiveProcess but set the different (wrapped) -- Handles to NoBuffering. runInteractiveProcess :: FilePath -> [String] -> Maybe FilePath -> Maybe [(String, String)] -> IO (OutputStream ByteString, InputStream ByteString, InputStream ByteString, P.ProcessHandle) runInteractiveProcess cmd args wd env = do (hin, hout, herr, ph) <- P.runInteractiveProcess cmd args wd env hSetBuffering hin NoBuffering hSetBuffering hout NoBuffering hSetBuffering herr NoBuffering sIn <- S.handleToOutputStream hin >>= S.atEndOfOutput (hClose hin) >>= S.lockingOutputStream sOut <- S.handleToInputStream hout >>= S.atEndOfInput (hClose hout) >>= S.lockingInputStream sErr <- S.handleToInputStream herr >>= S.atEndOfInput (hClose herr) >>= S.lockingInputStream return (sIn, sOut, sErr, ph) splitIS :: InputStream a -> IO (InputStream a, InputStream a) splitIS is = do mvar <- newEmptyMVar is0 <- S.makeInputStream (S.read is >>= \m -> putMVar mvar m >> return m) is1 <- S.makeInputStream (takeMVar mvar) return (is0, is1) display :: Packet -> String display p = short p ++ (let d = description p in if null d then "" else " " ++ d)
noteed/sftp-streams
bin/sftp-mitm.hs
bsd-3-clause
4,471
0
21
823
1,376
737
639
94
2
{-# LANGUAGE MonadComprehensions #-} -- | A big-endian binary PATRICIA trie with fixed-size ints as keys. module BinaryTrie where import Prelude hiding (lookup) import Data.Bits import Data.Monoid import Text.Printf -- | A PATRICIA trie that inspects an @Int@ key bit by bit. data Trie a = Empty | Leaf !Int a -- ^ Each leaf stores the whole key along with the value -- for that key. | Branch !Int !Int (Trie a) (Trie a) deriving (Eq, Ord) -- ^ Each branch stores a prefix and a control bit for -- the bit it branched on—an @Int@ with just that bit -- set. instance Show a => Show (Trie a) where show Empty = "Empty" show (Leaf k v) = printf "Leaf %d %s" k (show v) show (Branch prefix control l r) = printf "(Branch %b %b %s %s)" prefix control (show l) (show r) width :: Int width = finiteBitSize (0 :: Int) -- | Returns the key masked to every bit before (ie more significant) -- than the control bit. getPrefix :: Int -> Int -> Int getPrefix key control = key .&. complement ((control `shiftL` 1) - 1) -- | A smart consructor for branches of the tree tha avoids creating -- unnecessary nodes and puts children in the correct order. branch :: Int -> Int -> Trie a -> Trie a -> Trie a branch _ _ Empty Empty = Empty branch _ _ Empty (Leaf k v) = Leaf k v branch _ _ (Leaf k v) Empty = Leaf k v branch prefix control l r = Branch prefix control l r -- TODO: Replace with efficient version with 7.10 countLeadingZeros :: Int -> Int countLeadingZeros n = (width - 1) - go (width - 1) where go i | i < 0 = i | testBit n i = i | otherwise = go (i - 1) highestBitSet :: Int -> Int highestBitSet n = bit $ width - countLeadingZeros n - 1 -- | Branches on whether the bit of the key at the given control bit -- is 0 (left) or 1 (right). checkBit :: Int -> Int -> a -> a -> a checkBit k control left right = if k .&. control == 0 then left else right -- | We look a value up by branching based on bits. If we ever hit a -- leaf node, we check whether our whole key matches. If we ever hit -- an empty node, we know the key is not in the trie. lookup :: Int -> Trie a -> Maybe a lookup _ Empty = Nothing lookup k (Leaf k' v) = [v | k == k'] lookup k (Branch prefix control l r) | getPrefix k control /= prefix = Nothing | otherwise = lookup k (checkBit k control l r) -- | Combines two trees with two different prefixes. combine :: Int -> Trie a -> Int -> Trie a -> Trie a combine pl l pr r = checkBit pl control (branch prefix control l r) (branch prefix control r l) where control = highestBitSet (pl `xor` pr) prefix = getPrefix pl control insert :: Monoid a => Int -> a -> Trie a -> Trie a insert k v Empty = Leaf k v insert k v (Leaf k' v') | k == k' = Leaf k (v <> v') | otherwise = combine k (Leaf k v) k' (Leaf k' v') insert k v trie@(Branch prefix control l r) | getPrefix k control == prefix = checkBit k control (branch prefix control (insert k v l) r) (branch prefix control l (insert k v r)) | otherwise = combine k (Leaf k v) prefix trie fromList :: Monoid a => [(Int, a)] -> Trie a fromList = foldr (\ (k, v) t -> insert k v t) Empty keys :: Trie a -> [Int] keys Empty = [] keys (Leaf k _) = [k] keys (Branch _ _ l r) = keys l ++ keys r merge :: Monoid a => Trie a -> Trie a -> Trie a merge Empty t = t merge t Empty = t merge (Leaf k v) t = insert k v t merge t (Leaf k v) = insert k v t merge t₁@(Branch p₁ c₁ l₁ r₁) t₂@(Branch p₂ c₂ l₂ r₂) | p₁ == p₂ && c₁ == c₂ = branch p₁ c₁ (merge l₁ l₂) (merge r₁ r₂) | c₁ > c₂ && getPrefix p₂ c₁ == p₁ = checkBit p₂ c₁ (branch p₁ c₁ (merge l₁ t₂) r₁) (branch p₁ c₁ l₁ (merge r₁ t₂)) | c₂ > c₁ && getPrefix p₁ c₂ == p₂ = checkBit p₁ c₂ (branch p₂ c₂ (merge t₁ l₂) r₂) (branch p₂ c₂ l₂ (merge t₁ r₂)) | otherwise = combine p₁ t₁ p₂ t₂ delete :: Int -> Trie a -> Trie a delete k Empty = Empty delete k (Leaf k' v) | k == k' = Empty | otherwise = Leaf k' v delete k trie@(Branch prefix control l r) | getPrefix k control == prefix = checkBit k control (branch prefix control (delete k l) r) (branch prefix control l (delete k r)) | otherwise = trie intersect :: Monoid a => Trie a -> Trie a -> Trie a intersect Empty _ = Empty intersect _ Empty = Empty intersect (Leaf k v) (Leaf k' v') | k == k' = Leaf k (v <> v') | otherwise = Empty intersect leaf@(Leaf k v) (Branch prefix control l r) | getPrefix k control == prefix = checkBit k control (intersect leaf l) (intersect leaf r) | otherwise = Empty intersect (Branch prefix control l r) leaf@(Leaf k v) | getPrefix k control == prefix = checkBit k control (intersect l leaf) (intersect r leaf) | otherwise = Empty intersect left@(Branch p₁ c₁ l₁ r₁) right@(Branch p₂ c₂ l₂ r₂) | c₁ == c₂ && p₁ == p₂ = branch p₁ c₁ (intersect l₁ l₂) (intersect r₁ r₂) | c₁ > c₂ && getPrefix p₂ c₁ == p₁ = checkBit p₂ c₁ (intersect l₁ right) (intersect r₁ right) | c₁ < c₂ && getPrefix p₁ c₂ == p₂ = checkBit p₁ c₂ (intersect left l₂) (intersect right r₂) | otherwise = Empty -- Utility functions b :: Int -> IO () b i = printf "%b\n" i
silky/different-tries
src/BinaryTrie.hs
bsd-3-clause
5,963
188
10
1,922
2,347
1,158
1,189
108
2
module B1.Data.Technicals.StockData ( StockData , StockDataStatus(..) , StockPriceData(..) , newStockData , createStockPriceData , getStockDataStatus , getStockPriceData , getErrorMessage , handleStockData ) where import Control.Concurrent import Control.Concurrent.MVar import Data.Either import Data.Maybe import Data.Time.Calendar import Data.Time.Clock import Data.Time.LocalTime import System.IO import B1.Control.TaskManager import B1.Data.Price import B1.Data.Price.Google import B1.Data.Symbol import B1.Data.Technicals.MovingAverage import B1.Data.Technicals.Stochastic -- TODO: Rename to StockDataFactory data StockData = StockData Symbol (MVar (Either StockPriceData String)) -- TODO: Rename to StockData data StockPriceData = StockPriceData { prices :: [Price] , stochastics :: [Stochastic] , weeklyPrices :: [Price] , weeklyStochastics :: [Stochastic] , movingAverage25 :: [MovingAverage] , movingAverage50 :: [MovingAverage] , movingAverage200 :: [MovingAverage] , numDailyElements :: Int , numWeeklyElements :: Int } data StockDataStatus = Loading | Data | ErrorMessage deriving (Eq) newStockData :: TaskManager -> Symbol -> IO StockData newStockData taskManager symbol = do priceDataMVar <- newEmptyMVar addTask taskManager $ do startDate <- getStartDate endDate <- getEndDate pricesOrError <- getGooglePrices startDate endDate symbol putMVar priceDataMVar $ either (Left . createStockPriceData) Right pricesOrError return $ StockData symbol priceDataMVar getStartDate :: IO LocalTime getStartDate = do endDate <- getEndDate let startDay = (addGregorianYearsClip (-2) . localDay) endDate return endDate { localDay = startDay , localTimeOfDay = midnight } getEndDate :: IO LocalTime getEndDate = do timeZone <- getCurrentTimeZone time <- getCurrentTime let localTime = utcToLocalTime timeZone time return $ localTime { localTimeOfDay = midnight } createStockPriceData :: [Price] -> StockPriceData createStockPriceData prices = StockPriceData { prices = prices , stochastics = stochastics , weeklyPrices = weeklyPrices , weeklyStochastics = weeklyStochastics , movingAverage25 = movingAverage25 , movingAverage50 = movingAverage50 , movingAverage200 = movingAverage200 , numDailyElements = numDailyElements , numWeeklyElements = numWeeklyElements } where stochasticsFunction = getStochastics 10 3 stochastics = stochasticsFunction prices movingAverage25 = getMovingAverage 25 prices movingAverage50 = getMovingAverage 50 prices movingAverage200 = getMovingAverage 200 prices weeklyPrices = getWeeklyPrices prices weeklyStochastics = stochasticsFunction weeklyPrices maxDailyElements = minimum [ length prices , length stochastics ] weeksInYear = 52 maxWeeklyElements = minimum [ length weeklyPrices , length weeklyStochastics , weeksInYear ] earliestStartTime = (startTime . last . take maxWeeklyElements ) weeklyPrices numDailyElements = (length . takeWhile ((>= earliestStartTime) . startTime) . take maxDailyElements ) prices numWeeklyElements = (length . takeWhile ((>= earliestStartTime) . startTime) . take maxWeeklyElements ) weeklyPrices getStockDataStatus :: StockData -> IO StockDataStatus getStockDataStatus = handleStockData (ignore Data) (ignore ErrorMessage) Loading getStockPriceData :: StockData -> IO (Maybe StockPriceData) getStockPriceData = handleStockData (return . Just) (ignore Nothing) Nothing getErrorMessage :: StockData -> IO (Maybe String) getErrorMessage = handleStockData (ignore Nothing) (return . Just) Nothing handleStockData :: (StockPriceData -> IO a) -> (String -> IO a) -> a -> StockData -> IO a handleStockData priceFunction errorFunction noValue (StockData _ contentsVar) = do maybeContents <- tryTakeMVar contentsVar case maybeContents of Just contents -> do tryPutMVar contentsVar contents either priceFunction errorFunction contents _ -> return noValue ignore :: a -> b -> IO a ignore value _ = return value
btmura/b1
src/B1/Data/Technicals/StockData.hs
bsd-3-clause
4,249
0
15
858
1,043
563
480
117
2
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE FlexibleInstances #-} -- | The commented code summarizes what will be auto-generated below module Main where import Control.Lens -- import Test.QuickCheck (quickCheck) data Bar a b c = Bar { _baz :: (a, b) } makeLenses ''Bar -- baz :: Lens (Bar a b c) (Bar a' b' c) (a,b) (a',b') data Quux a b = Quux { _quaffle :: Int, _quartz :: Double } makeLenses ''Quux -- quaffle :: Lens (Quux a b) (Quux a' b') Int Int -- quartz :: Lens (Quux a b) (Quux a' b') Double Double data Quark a = Qualified { _gaffer :: a } | Unqualified { _gaffer :: a, _tape :: a } makeLenses ''Quark -- gaffer :: Simple Lens (Quark a) a -- tape :: Simple Traversal (Quark a) a data Hadron a b = Science { _a1 :: a, _a2 :: a, _b :: b } makeLenses ''Hadron -- a1 :: Simple Lens (Hadron a b) a -- a2 :: Simple Lens (Hadron a b) a -- b :: Lens (Hadron a b) (Hadron a b') b b' data Perambulation a b = Mountains { _terrain :: a, _altitude :: b } | Beaches { _terrain :: a, _dunes :: a } makeLenses ''Perambulation -- terrain :: Simple Lens (Perambulation a b) a -- altitude :: Traversal (Perambulation a b) (Parambulation a b') b b' -- dunes :: Simple Traversal (Perambulation a b) a makeLensesFor [("_terrain", "allTerrain"), ("_dunes", "allTerrain")] ''Perambulation -- allTerrain :: Traversal (Perambulation a b) (Perambulation a' b) a a' data LensCrafted a = Still { _still :: a } | Works { _still :: a } makeLenses ''LensCrafted -- still :: Lens (LensCrafted a) (LensCrafted b) a b data Danger a = Zone { _highway :: a } | Twilight makeLensesWith (partialLenses .~ True $ buildTraversals .~ False $ lensRules) ''Danger -- highway :: Lens (Danger a) (Danger a') a a' data Task a = Task { taskOutput :: a -> IO () , taskState :: a , taskStop :: IO () } makeLensesFor [("taskOutput", "outputLens"), ("taskState", "stateLens"), ("taskStop", "stopLens")] ''Task data Mono a = Mono { _monoFoo :: a, _monoBar :: Int } makeClassy ''Mono -- class HasMono t where -- mono :: Simple Lens t Mono -- instance HasMono Mono where -- mono = id -- monoFoo :: HasMono t => Simple Lens t Int -- monoBar :: HasMono t => Simple Lens t Int data Nucleosis = Nucleosis { _nuclear :: Mono Int } makeClassy ''Nucleosis -- class HasNucleosis t where -- nucleosis :: Simple Lens t Nucleosis -- instance HasNucleosis Nucleosis -- nuclear :: HasNucleosis t => Simple Lens t Mono instance HasMono Nucleosis Int where mono = nuclear -- Dodek's example data Foo = Foo { _fooX, _fooY :: Int } makeClassy ''Foo main :: IO () main = putStrLn "test/templates.hs: ok"
np/lens
tests/templates.hs
bsd-3-clause
2,743
0
11
573
534
319
215
42
1
module Idris.DeepSeq(module Idris.DeepSeq, module Idris.Core.DeepSeq) where import Idris.Core.DeepSeq import Idris.Core.TT import Idris.AbsSyntaxTree import Control.DeepSeq -- All generated by 'derive' instance NFData Forceability where rnf Conditional = () rnf Unconditional = () instance NFData IntTy where rnf (ITFixed x1) = rnf x1 `seq` () rnf ITNative = () rnf ITBig = () rnf ITChar = () rnf (ITVec x1 x2) = rnf x1 `seq` rnf x2 `seq` () instance NFData NativeTy where rnf IT8 = () rnf IT16 = () rnf IT32 = () rnf IT64 = () instance NFData ArithTy where rnf (ATInt x1) = rnf x1 `seq` () rnf ATFloat = () instance NFData SizeChange where rnf Smaller = () rnf Same = () rnf Bigger = () rnf Unknown = () instance NFData CGInfo where rnf (CGInfo x1 x2 x3 x4 x5) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` rnf x5 `seq` () instance NFData Fixity where rnf (Infixl x1) = rnf x1 `seq` () rnf (Infixr x1) = rnf x1 `seq` () rnf (InfixN x1) = rnf x1 `seq` () rnf (PrefixN x1) = rnf x1 `seq` () instance NFData FixDecl where rnf (Fix x1 x2) = rnf x1 `seq` rnf x2 `seq` () instance NFData Static where rnf Static = () rnf Dynamic = () instance NFData ArgOpt where rnf _ = () instance NFData Plicity where rnf (Imp x1 x2 x3 x4) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` () rnf (Exp x1 x2 x3 x4) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` () rnf (Constraint x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` () rnf (TacImp x1 x2 x3 x4) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` () instance NFData FnOpt where rnf Inlinable = () rnf TotalFn = () rnf PartialFn = () rnf Coinductive = () rnf AssertTotal = () rnf Dictionary = () rnf Implicit = () rnf (CExport x1) = rnf x1 `seq` () rnf Reflection = () rnf (Specialise x1) = rnf x1 `seq` () instance NFData DataOpt where rnf Codata = () rnf DefaultEliminator = () instance (NFData t) => NFData (PDecl' t) where rnf (PFix x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` () rnf (PTy x1 x2 x3 x4 x5 x6) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` rnf x5 `seq` rnf x6 `seq` () rnf (PPostulate x1 x2 x3 x4 x5 x6) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` rnf x5 `seq` rnf x6 `seq` () rnf (PClauses x1 x2 x3 x4) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` () rnf (PCAF x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` () rnf (PData x1 x2 x3 x4 x5) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` rnf x5 `seq` () rnf (PParams x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` () rnf (PNamespace x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf (PRecord x1 x2 x3 x4 x5 x6 x7 x8) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` rnf x5 `seq` rnf x6 `seq` rnf x7 `seq` rnf x8 `seq` () rnf (PClass x1 x2 x3 x4 x5 x6 x7) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` rnf x5 `seq` rnf x6 `seq` rnf x7 `seq` () rnf (PInstance x1 x2 x3 x4 x5 x6 x7 x8) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` rnf x5 `seq` rnf x6 `seq` rnf x7 `seq` rnf x8 `seq` () rnf (PDSL x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf (PSyntax x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf (PMutual x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf (PDirective x1) = () rnf (PProvider x1 x2 x3 x4 x5) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` rnf x5 `seq` () rnf (PTransform x1 x2 x3 x4) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` () instance (NFData t) => NFData (PClause' t) where rnf (PClause x1 x2 x3 x4 x5 x6) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` rnf x5 `seq` rnf x6 `seq` () rnf (PWith x1 x2 x3 x4 x5 x6) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` rnf x5 `seq` rnf x6 `seq` () rnf (PClauseR x1 x2 x3 x4) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` () rnf (PWithR x1 x2 x3 x4) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` () instance (NFData t) => NFData (PData' t) where rnf (PDatadecl x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` () rnf (PLaterdecl x1 x2) = rnf x1 `seq` rnf x2 `seq` () instance NFData PTerm where rnf (PQuote x1) = rnf x1 `seq` () rnf (PRef x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf (PInferRef x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf (PPatvar x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf (PLam x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` () rnf (PPi x1 x2 x3 x4) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` () rnf (PLet x1 x2 x3 x4) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` () rnf (PTyped x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf (PApp x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` () rnf (PAppBind x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` () rnf (PMatchApp x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf (PCase x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` () rnf (PTrue x1) = rnf x1 `seq` () rnf (PFalse x1) = rnf x1 `seq` () rnf (PRefl x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf (PResolveTC x1) = rnf x1 `seq` () rnf (PEq x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` () rnf (PRewrite x1 x2 x3 x4) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` () rnf (PPair x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` () rnf (PDPair x1 x2 x3 x4) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` () rnf (PAlternative x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf (PHidden x1) = rnf x1 `seq` () rnf PType = () rnf (PGoal x1 x2 x3 x4) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` () rnf (PConstant x1) = x1 `seq` () rnf Placeholder = () rnf (PDoBlock x1) = rnf x1 `seq` () rnf (PIdiom x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf (PReturn x1) = rnf x1 `seq` () rnf (PMetavar x1) = rnf x1 `seq` () rnf (PProof x1) = rnf x1 `seq` () rnf (PTactics x1) = rnf x1 `seq` () rnf (PElabError x1) = rnf x1 `seq` () rnf PImpossible = () rnf (PCoerced x1) = rnf x1 `seq` () rnf (PUnifyLog x1) = rnf x1 `seq` () rnf (PNoImplicits x1) = rnf x1 `seq` () instance (NFData t) => NFData (PTactic' t) where rnf (Intro x1) = rnf x1 `seq` () rnf Intros = () rnf (Focus x1) = rnf x1 `seq` () rnf (Refine x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf (Rewrite x1) = rnf x1 `seq` () rnf (Induction x1) = rnf x1 `seq` () rnf (Equiv x1) = rnf x1 `seq` () rnf (MatchRefine x1) = rnf x1 `seq` () rnf (LetTac x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf (LetTacTy x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` () rnf (Exact x1) = rnf x1 `seq` () rnf Compute = () rnf Trivial = () rnf (ProofSearch x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` () rnf Solve = () rnf Attack = () rnf ProofState = () rnf ProofTerm = () rnf Undo = () rnf (Try x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf (TSeq x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf (ApplyTactic x1) = rnf x1 `seq` () rnf (Reflect x1) = rnf x1 `seq` () rnf (Fill x1) = rnf x1 `seq` () rnf (GoalType x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf Qed = () rnf Abandon = () instance (NFData t) => NFData (PDo' t) where rnf (DoExp x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf (DoBind x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` () rnf (DoBindP x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` () rnf (DoLet x1 x2 x3 x4) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` () rnf (DoLetP x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` () instance (NFData t) => NFData (PArg' t) where rnf (PImp x1 x2 x3 x4 x5 x6) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` rnf x5 `seq` rnf x6 `seq` () rnf (PExp x1 x2 x3 x4) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` () rnf (PConstraint x1 x2 x3 x4) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` () rnf (PTacImplicit x1 x2 x3 x4 x5 x6) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` rnf x5 `seq` rnf x6 `seq` () instance NFData ClassInfo where rnf (CI x1 x2 x3 x4 x5 x6) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` rnf x5 `seq` rnf x6 `seq` () instance NFData OptInfo where rnf (Optimise x1 x2 x3 x4) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` () instance NFData TypeInfo where rnf (TI x1 x2 x3 x4) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` () instance (NFData t) => NFData (DSL' t) where rnf (DSL x1 x2 x3 x4 x5 x6 x7 x8 x9) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` rnf x5 `seq` rnf x6 `seq` rnf x7 `seq` rnf x8 `seq` rnf x9 `seq` () instance NFData SynContext where rnf PatternSyntax = () rnf TermSyntax = () rnf AnySyntax = () instance NFData Syntax where rnf (Rule x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` () instance NFData SSymbol where rnf (Keyword x1) = rnf x1 `seq` () rnf (Symbol x1) = rnf x1 `seq` () rnf (Binding x1) = rnf x1 `seq` () rnf (Expr x1) = rnf x1 `seq` () rnf (SimpleExpr x1) = rnf x1 `seq` () instance NFData Using where rnf (UImplicit x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf (UConstraint x1 x2) = rnf x1 `seq` rnf x2 `seq` () instance NFData SyntaxInfo where rnf (Syn x1 x2 x3 x4 x5 x6 x7 x8) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` rnf x5 `seq` rnf x6 `seq` rnf x7 `seq` rnf x8 `seq` ()
ctford/Idris-Elba-dev
src/Idris/DeepSeq.hs
bsd-3-clause
10,810
0
15
3,971
5,664
2,993
2,671
247
0
{-| Implementation of the Ganeti Confd client functionality. -} {- Copyright (C) 2012 Google Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -} module Ganeti.Confd.Client ( getConfdClient , query ) where import Control.Concurrent import Control.Monad import Data.List import qualified Network.Socket as S import System.Posix.Time import qualified Text.JSON as J import Ganeti.BasicTypes import Ganeti.Confd.Types import Ganeti.Confd.Utils import qualified Ganeti.Constants as C import Ganeti.Hash import Ganeti.Ssconf -- | Builds a properly initialized ConfdClient getConfdClient :: IO ConfdClient getConfdClient = S.withSocketsDo $ do hmac <- getClusterHmac candList <- getMasterCandidatesIps Nothing peerList <- case candList of (Ok p) -> return p (Bad msg) -> fail msg return . ConfdClient hmac peerList $ fromIntegral C.defaultConfdPort -- | Sends a query to all the Confd servers the client is connected to. -- Returns the most up-to-date result according to the serial number, -- chosen between those received before the timeout. query :: ConfdClient -> ConfdRequestType -> ConfdQuery -> IO (Maybe ConfdReply) query client crType cQuery = do semaphore <- newMVar () answer <- newMVar Nothing let dest = [(host, serverPort client) | host <- peers client] hmac = hmacKey client jobs = map (queryOneServer semaphore answer crType cQuery hmac) dest watchdog reqAnswers = do threadDelay $ 1000000 * C.confdClientExpireTimeout _ <- swapMVar reqAnswers 0 putMVar semaphore () waitForResult reqAnswers = do _ <- takeMVar semaphore l <- takeMVar reqAnswers unless (l == 0) $ do putMVar reqAnswers $ l - 1 waitForResult reqAnswers reqAnswers <- newMVar . min C.confdDefaultReqCoverage $ length dest workers <- mapM forkIO jobs watcher <- forkIO $ watchdog reqAnswers waitForResult reqAnswers mapM_ killThread $ watcher:workers takeMVar answer -- | Updates the reply to the query. As per the Confd design document, -- only the reply with the highest serial number is kept. updateConfdReply :: ConfdReply -> Maybe ConfdReply -> Maybe ConfdReply updateConfdReply newValue Nothing = Just newValue updateConfdReply newValue (Just currentValue) = Just $ if confdReplyStatus newValue == ReplyStatusOk && (confdReplyStatus currentValue /= ReplyStatusOk || confdReplySerial newValue > confdReplySerial currentValue) then newValue else currentValue -- | Send a query to a single server, waits for the result and stores it -- in a shared variable. Then, sends a signal on another shared variable -- acting as a semaphore. -- This function is meant to be used as one of multiple threads querying -- multiple servers in parallel. queryOneServer :: MVar () -- ^ The semaphore that will be signalled -> MVar (Maybe ConfdReply) -- ^ The shared variable for the result -> ConfdRequestType -- ^ The type of the query to be sent -> ConfdQuery -- ^ The content of the query -> HashKey -- ^ The hmac key to sign the message -> (String, S.PortNumber) -- ^ The address and port of the server -> IO () queryOneServer semaphore answer crType cQuery hmac (host, port) = do request <- newConfdRequest crType cQuery timestamp <- fmap show epochTime let signedMsg = signMessage hmac timestamp (J.encodeStrict request) completeMsg = C.confdMagicFourcc ++ J.encodeStrict signedMsg s <- S.socket S.AF_INET S.Datagram S.defaultProtocol hostAddr <- S.inet_addr host _ <- S.sendTo s completeMsg $ S.SockAddrInet port hostAddr replyMsg <- S.recv s C.maxUdpDataSize parsedReply <- if C.confdMagicFourcc `isPrefixOf` replyMsg then return . parseReply hmac (drop 4 replyMsg) $ confdRqRsalt request else fail "Invalid magic code!" reply <- case parsedReply of Ok (_, r) -> return r Bad msg -> fail msg modifyMVar_ answer $! return . updateConfdReply reply putMVar semaphore ()
sarahn/ganeti
src/Ganeti/Confd/Client.hs
gpl-2.0
4,684
0
17
984
943
464
479
83
3
{-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.CloudFormation -- 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) -- -- AWS CloudFormation -- -- AWS CloudFormation enables you to create and manage AWS infrastructure -- deployments predictably and repeatedly. AWS CloudFormation helps you -- leverage AWS products such as Amazon EC2, EBS, Amazon SNS, ELB, and Auto -- Scaling to build highly-reliable, highly scalable, cost effective -- applications without worrying about creating and configuring the -- underlying AWS infrastructure. -- -- With AWS CloudFormation, you declare all of your resources and -- dependencies in a template file. The template defines a collection of -- resources as a single unit called a stack. AWS CloudFormation creates -- and deletes all member resources of the stack together and manages all -- dependencies between the resources for you. -- -- For more information about this product, go to the -- <http://aws.amazon.com/cloudformation/ CloudFormation Product Page>. -- -- Amazon CloudFormation makes use of other AWS products. If you need -- additional technical information about a specific AWS product, you can -- find the product\'s technical documentation at -- <http://aws.amazon.com/documentation/>. -- -- /See:/ <http://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/Welcome.html AWS API Reference> module Network.AWS.CloudFormation ( -- * Service Configuration cloudFormation -- * Errors -- $errors -- ** InsufficientCapabilitiesException , _InsufficientCapabilitiesException -- ** AlreadyExistsException , _AlreadyExistsException -- ** LimitExceededException , _LimitExceededException -- * Waiters -- $waiters -- * Operations -- $operations -- ** DeleteStack , module Network.AWS.CloudFormation.DeleteStack -- ** UpdateStack , module Network.AWS.CloudFormation.UpdateStack -- ** GetTemplateSummary , module Network.AWS.CloudFormation.GetTemplateSummary -- ** ListStackResources (Paginated) , module Network.AWS.CloudFormation.ListStackResources -- ** GetStackPolicy , module Network.AWS.CloudFormation.GetStackPolicy -- ** DescribeStacks (Paginated) , module Network.AWS.CloudFormation.DescribeStacks -- ** ValidateTemplate , module Network.AWS.CloudFormation.ValidateTemplate -- ** CancelUpdateStack , module Network.AWS.CloudFormation.CancelUpdateStack -- ** DescribeStackEvents (Paginated) , module Network.AWS.CloudFormation.DescribeStackEvents -- ** SignalResource , module Network.AWS.CloudFormation.SignalResource -- ** SetStackPolicy , module Network.AWS.CloudFormation.SetStackPolicy -- ** ListStacks (Paginated) , module Network.AWS.CloudFormation.ListStacks -- ** DescribeStackResources , module Network.AWS.CloudFormation.DescribeStackResources -- ** CreateStack , module Network.AWS.CloudFormation.CreateStack -- ** EstimateTemplateCost , module Network.AWS.CloudFormation.EstimateTemplateCost -- ** GetTemplate , module Network.AWS.CloudFormation.GetTemplate -- ** DescribeStackResource , module Network.AWS.CloudFormation.DescribeStackResource -- * Types -- ** Capability , Capability (..) -- ** OnFailure , OnFailure (..) -- ** ResourceSignalStatus , ResourceSignalStatus (..) -- ** ResourceStatus , ResourceStatus (..) -- ** StackStatus , StackStatus (..) -- ** Output , Output , output , oOutputValue , oOutputKey , oDescription -- ** Parameter , Parameter , parameter , pParameterValue , pParameterKey , pUsePreviousValue -- ** ParameterConstraints , ParameterConstraints , parameterConstraints , pcAllowedValues -- ** ParameterDeclaration , ParameterDeclaration , parameterDeclaration , pdParameterKey , pdParameterType , pdParameterConstraints , pdDefaultValue , pdNoEcho , pdDescription -- ** Stack , Stack , stack , sDisableRollback , sLastUpdatedTime , sNotificationARNs , sStackStatusReason , sOutputs , sParameters , sStackId , sDescription , sCapabilities , sTags , sTimeoutInMinutes , sStackName , sCreationTime , sStackStatus -- ** StackEvent , StackEvent , stackEvent , seLogicalResourceId , sePhysicalResourceId , seResourceType , seResourceStatusReason , seResourceProperties , seResourceStatus , seStackId , seEventId , seStackName , seTimestamp -- ** StackResource , StackResource , stackResource , srPhysicalResourceId , srResourceStatusReason , srStackId , srDescription , srStackName , srLogicalResourceId , srResourceType , srTimestamp , srResourceStatus -- ** StackResourceDetail , StackResourceDetail , stackResourceDetail , srdPhysicalResourceId , srdResourceStatusReason , srdMetadata , srdStackId , srdDescription , srdStackName , srdLogicalResourceId , srdResourceType , srdLastUpdatedTimestamp , srdResourceStatus -- ** StackResourceSummary , StackResourceSummary , stackResourceSummary , srsPhysicalResourceId , srsResourceStatusReason , srsLogicalResourceId , srsResourceType , srsLastUpdatedTimestamp , srsResourceStatus -- ** StackSummary , StackSummary , stackSummary , ssLastUpdatedTime , ssStackStatusReason , ssTemplateDescription , ssDeletionTime , ssStackId , ssStackName , ssCreationTime , ssStackStatus -- ** Tag , Tag , tag , tagValue , tagKey -- ** TemplateParameter , TemplateParameter , templateParameter , tpParameterKey , tpDefaultValue , tpNoEcho , tpDescription ) where import Network.AWS.CloudFormation.CancelUpdateStack import Network.AWS.CloudFormation.CreateStack import Network.AWS.CloudFormation.DeleteStack import Network.AWS.CloudFormation.DescribeStackEvents import Network.AWS.CloudFormation.DescribeStackResource import Network.AWS.CloudFormation.DescribeStackResources import Network.AWS.CloudFormation.DescribeStacks import Network.AWS.CloudFormation.EstimateTemplateCost import Network.AWS.CloudFormation.GetStackPolicy import Network.AWS.CloudFormation.GetTemplate import Network.AWS.CloudFormation.GetTemplateSummary import Network.AWS.CloudFormation.ListStackResources import Network.AWS.CloudFormation.ListStacks import Network.AWS.CloudFormation.SetStackPolicy import Network.AWS.CloudFormation.SignalResource import Network.AWS.CloudFormation.Types import Network.AWS.CloudFormation.UpdateStack import Network.AWS.CloudFormation.ValidateTemplate import Network.AWS.CloudFormation.Waiters {- $errors Error matchers are designed for use with the functions provided by <http://hackage.haskell.org/package/lens/docs/Control-Exception-Lens.html Control.Exception.Lens>. This allows catching (and rethrowing) service specific errors returned by 'CloudFormation'. -} {- $operations Some AWS operations return results that are incomplete and require subsequent requests in order to obtain the entire result set. The process of sending subsequent requests to continue where a previous request left off is called pagination. For example, the 'ListObjects' operation of Amazon S3 returns up to 1000 objects at a time, and you must send subsequent requests with the appropriate Marker in order to retrieve the next page of results. Operations that have an 'AWSPager' instance can transparently perform subsequent requests, correctly setting Markers and other request facets to iterate through the entire result set of a truncated API operation. Operations which support this have an additional note in the documentation. Many operations have the ability to filter results on the server side. See the individual operation parameters for details. -} {- $waiters Waiters poll by repeatedly sending a request until some remote success condition configured by the 'Wait' specification is fulfilled. The 'Wait' specification determines how many attempts should be made, in addition to delay and retry strategies. -}
fmapfmapfmap/amazonka
amazonka-cloudformation/gen/Network/AWS/CloudFormation.hs
mpl-2.0
8,796
0
5
1,832
708
519
189
149
0
{-# LANGUAGE BangPatterns #-} {-# OPTIONS_GHC -Wall #-} module Main where import Control.Concurrent import Control.Exception as Ex import Control.Monad import Data.IORef import System.Posix.CircularBuffer import System.Environment -- read Int's from the supplied buffer as fast as possible, and print the -- number read after 10 seconds main :: IO () main = do args <- getArgs counter <- newIORef (0::Int) case args of [nm,szStr] -> do let sz = read szStr Ex.bracket ((openBuffer nm nm sz 0o600 :: IO (ReadBuffer Int))) (removeBuffer) $ \rb -> do tid <- forkIO $ forever $ do xs <- getAvailable rb if (null xs) then yield else writeIORef counter $ last xs -- x <- getBuffer WaitYield rb -- writeIORef counter x threadDelay $ 10*1000000 killThread tid print =<< readIORef counter _ -> error "usage: reader NAME SZ"
smunix/shared-buffer
benchmarks/Reader.hs
bsd-3-clause
989
0
22
308
249
128
121
24
3
{-| Implementation of the RAPI client interface. -} {- Copyright (C) 2009, 2010, 2011, 2012, 2013 Google Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} {-# LANGUAGE BangPatterns, CPP #-} module Ganeti.HTools.Backend.Rapi ( loadData , parseData ) where import Control.Exception import Data.List (isPrefixOf) import Data.Maybe (fromMaybe) import Network.Curl import Network.Curl.Types () import Control.Monad import Text.JSON (JSObject, fromJSObject, decodeStrict) import Text.JSON.Types (JSValue(..)) import Text.Printf (printf) import System.FilePath import Ganeti.BasicTypes import Ganeti.HTools.Loader import Ganeti.HTools.Types import Ganeti.JSON import qualified Ganeti.HTools.Group as Group import qualified Ganeti.HTools.Node as Node import qualified Ganeti.HTools.Instance as Instance import qualified Ganeti.Constants as C {-# ANN module "HLint: ignore Eta reduce" #-} -- | File method prefix. filePrefix :: String filePrefix = "file://" -- | Read an URL via curl and return the body if successful. getUrl :: (Monad m) => String -> IO (m String) -- | Connection timeout (when using non-file methods). connTimeout :: Long connTimeout = 15 -- | The default timeout for queries (when using non-file methods). queryTimeout :: Long queryTimeout = 60 -- | The curl options we use. curlOpts :: [CurlOption] curlOpts = [ CurlSSLVerifyPeer False , CurlSSLVerifyHost 0 , CurlTimeout queryTimeout , CurlConnectTimeout connTimeout ] getUrl url = do (code, !body) <- curlGetString url curlOpts return (case code of CurlOK -> return body _ -> fail $ printf "Curl error for '%s', error %s" url (show code)) -- | Helper to convert I/O errors in 'Bad' values. ioErrToResult :: IO a -> IO (Result a) ioErrToResult ioaction = Control.Exception.catch (liftM Ok ioaction) (\e -> return . Bad . show $ (e::IOException)) -- | Append the default port if not passed in. formatHost :: String -> String formatHost master = if ':' `elem` master then master else "https://" ++ master ++ ":" ++ show C.defaultRapiPort -- | Parse a instance list in JSON format. getInstances :: NameAssoc -> String -> Result [(String, Instance.Instance)] getInstances ktn body = loadJSArray "Parsing instance data" body >>= mapM (parseInstance ktn . fromJSObject) -- | Parse a node list in JSON format. getNodes :: NameAssoc -> String -> Result [(String, Node.Node)] getNodes ktg body = loadJSArray "Parsing node data" body >>= mapM (parseNode ktg . fromJSObject) -- | Parse a group list in JSON format. getGroups :: String -> Result [(String, Group.Group)] getGroups body = loadJSArray "Parsing group data" body >>= mapM (parseGroup . fromJSObject) -- | Construct an instance from a JSON object. parseInstance :: NameAssoc -> JSRecord -> Result (String, Instance.Instance) parseInstance ktn a = do name <- tryFromObj "Parsing new instance" a "name" let owner_name = "Instance '" ++ name ++ "', error while parsing data" let extract s x = tryFromObj owner_name x s disk <- extract "disk_usage" a dsizes <- extract "disk.sizes" a dspindles <- tryArrayMaybeFromObj owner_name a "disk.spindles" beparams <- liftM fromJSObject (extract "beparams" a) omem <- extract "oper_ram" a mem <- case omem of JSRational _ _ -> annotateResult owner_name (fromJVal omem) _ -> extract "memory" beparams `mplus` extract "maxmem" beparams vcpus <- extract "vcpus" beparams pnode <- extract "pnode" a >>= lookupNode ktn name snodes <- extract "snodes" a snode <- case snodes of [] -> return Node.noSecondary x:_ -> readEitherString x >>= lookupNode ktn name running <- extract "status" a tags <- extract "tags" a auto_balance <- extract "auto_balance" beparams dt <- extract "disk_template" a su <- extract "spindle_use" beparams -- Not forthcoming by default. forthcoming <- extract "forthcoming" a `orElse` Ok False let disks = zipWith Instance.Disk dsizes dspindles let inst = Instance.create name mem disk disks vcpus running tags auto_balance pnode snode dt su [] forthcoming return (name, inst) -- | Construct a node from a JSON object. parseNode :: NameAssoc -> JSRecord -> Result (String, Node.Node) parseNode ktg a = do name <- tryFromObj "Parsing new node" a "name" let desc = "Node '" ++ name ++ "', error while parsing data" extract key = tryFromObj desc a key extractDef def key = fromObjWithDefault a key def offline <- extract "offline" drained <- extract "drained" vm_cap <- annotateResult desc $ maybeFromObj a "vm_capable" let vm_cap' = fromMaybe True vm_cap ndparams <- extract "ndparams" >>= asJSObject excl_stor <- tryFromObj desc (fromJSObject ndparams) "exclusive_storage" guuid <- annotateResult desc $ maybeFromObj a "group.uuid" guuid' <- lookupGroup ktg name (fromMaybe defaultGroupID guuid) let live = not offline && vm_cap' lvextract def = eitherLive live def . extract lvextractDef def = eitherLive live def . extractDef def sptotal <- if excl_stor then lvextract 0 "sptotal" else tryFromObj desc (fromJSObject ndparams) "spindle_count" spfree <- lvextractDef 0 "spfree" mtotal <- lvextract 0.0 "mtotal" mnode <- lvextract 0 "mnode" mfree <- lvextract 0 "mfree" dtotal <- lvextractDef 0.0 "dtotal" dfree <- lvextractDef 0 "dfree" ctotal <- lvextract 0.0 "ctotal" cnos <- lvextract 0 "cnos" tags <- extract "tags" let node = flip Node.setNodeTags tags $ Node.create name mtotal mnode mfree dtotal dfree ctotal cnos (not live || drained) sptotal spfree guuid' excl_stor return (name, node) -- | Construct a group from a JSON object. parseGroup :: JSRecord -> Result (String, Group.Group) parseGroup a = do name <- tryFromObj "Parsing new group" a "name" let extract s = tryFromObj ("Group '" ++ name ++ "'") a s uuid <- extract "uuid" apol <- extract "alloc_policy" ipol <- extract "ipolicy" tags <- extract "tags" -- TODO: parse networks to which this group is connected return (uuid, Group.create name uuid apol [] ipol tags) -- | Parse cluster data from the info resource. parseCluster :: JSObject JSValue -> Result ([String], IPolicy, String) parseCluster obj = do let obj' = fromJSObject obj extract s = tryFromObj "Parsing cluster data" obj' s master <- extract "master" tags <- extract "tags" ipolicy <- extract "ipolicy" return (tags, ipolicy, master) -- | Loads the raw cluster data from an URL. readDataHttp :: String -- ^ Cluster or URL to use as source -> IO (Result String, Result String, Result String, Result String) readDataHttp master = do let url = formatHost master group_body <- getUrl $ printf "%s/2/groups?bulk=1" url node_body <- getUrl $ printf "%s/2/nodes?bulk=1" url inst_body <- getUrl $ printf "%s/2/instances?bulk=1" url info_body <- getUrl $ printf "%s/2/info" url return (group_body, node_body, inst_body, info_body) -- | Loads the raw cluster data from the filesystem. readDataFile:: String -- ^ Path to the directory containing the files -> IO (Result String, Result String, Result String, Result String) readDataFile path = do group_body <- ioErrToResult . readFile $ path </> "groups.json" node_body <- ioErrToResult . readFile $ path </> "nodes.json" inst_body <- ioErrToResult . readFile $ path </> "instances.json" info_body <- ioErrToResult . readFile $ path </> "info.json" return (group_body, node_body, inst_body, info_body) -- | Loads data via either 'readDataFile' or 'readDataHttp'. readData :: String -- ^ URL to use as source -> IO (Result String, Result String, Result String, Result String) readData url = if filePrefix `isPrefixOf` url then readDataFile (drop (length filePrefix) url) else readDataHttp url -- | Builds the cluster data from the raw Rapi content. parseData :: (Result String, Result String, Result String, Result String) -> Result ClusterData parseData (group_body, node_body, inst_body, info_body) = do group_data <- group_body >>= getGroups let (group_names, group_idx) = assignIndices group_data node_data <- node_body >>= getNodes group_names let (node_names, node_idx) = assignIndices node_data inst_data <- inst_body >>= getInstances node_names let (_, inst_idx) = assignIndices inst_data (tags, ipolicy, master) <- info_body >>= (fromJResult "Parsing cluster info" . decodeStrict) >>= parseCluster node_idx' <- setMaster node_names node_idx master return (ClusterData group_idx node_idx' inst_idx tags ipolicy) -- | Top level function for data loading. loadData :: String -- ^ Cluster or URL to use as source -> IO (Result ClusterData) loadData = fmap parseData . readData
apyrgio/ganeti
src/Ganeti/HTools/Backend/Rapi.hs
bsd-2-clause
10,150
0
15
2,059
2,440
1,209
1,231
184
3
----------------------------------------------------------------------------- -- -- Machine-specific parts of the register allocator -- -- (c) The University of Glasgow 1996-2004 -- ----------------------------------------------------------------------------- {-# 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://ghc.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#TabsvsSpaces -- for details module PPC.RegInfo ( JumpDest( DestBlockId ), getJumpDestBlockId, canShortcut, shortcutJump, shortcutStatics ) where #include "nativeGen/NCG.h" #include "HsVersions.h" import PPC.Instr import BlockId import Cmm import CLabel import Unique data JumpDest = DestBlockId BlockId getJumpDestBlockId :: JumpDest -> Maybe BlockId getJumpDestBlockId (DestBlockId bid) = Just bid canShortcut :: Instr -> Maybe JumpDest canShortcut _ = Nothing shortcutJump :: (BlockId -> Maybe JumpDest) -> Instr -> Instr shortcutJump _ other = other -- Here because it knows about JumpDest shortcutStatics :: (BlockId -> Maybe JumpDest) -> CmmStatics -> CmmStatics shortcutStatics fn (Statics lbl statics) = Statics lbl $ map (shortcutStatic fn) statics -- we need to get the jump tables, so apply the mapping to the entries -- of a CmmData too. shortcutLabel :: (BlockId -> Maybe JumpDest) -> CLabel -> CLabel shortcutLabel fn lab | Just uq <- maybeAsmTemp lab = shortBlockId fn (mkBlockId uq) | otherwise = lab shortcutStatic :: (BlockId -> Maybe JumpDest) -> CmmStatic -> CmmStatic shortcutStatic fn (CmmStaticLit (CmmLabel lab)) = CmmStaticLit (CmmLabel (shortcutLabel fn lab)) shortcutStatic fn (CmmStaticLit (CmmLabelDiffOff lbl1 lbl2 off)) = CmmStaticLit (CmmLabelDiffOff (shortcutLabel fn lbl1) lbl2 off) -- slightly dodgy, we're ignoring the second label, but this -- works with the way we use CmmLabelDiffOff for jump tables now. shortcutStatic _ other_static = other_static shortBlockId :: (BlockId -> Maybe JumpDest) -> BlockId -> CLabel shortBlockId fn blockid = case fn blockid of Nothing -> mkAsmTempLabel uq Just (DestBlockId blockid') -> shortBlockId fn blockid' where uq = getUnique blockid
lukexi/ghc-7.8-arm64
compiler/nativeGen/PPC/RegInfo.hs
bsd-3-clause
2,380
12
10
422
493
259
234
44
2
{-# Language PatternGuards #-} module Blub ( blub , foo , bar ) where import Ugah.Foo ( a , b ) import Control.Applicative import Ugah.Blub f :: Int -> Int f = (+ 3) g :: Int -> Int g = where
jystic/hsimport
tests/inputFiles/ModuleTest28.hs
bsd-3-clause
240
0
5
90
71
44
27
-1
-1
-- FrontEnd.Tc.Type should be imported instead of this. module FrontEnd.Representation( Type(..), Tyvar(..), tyvar, Tycon(..), fn, Pred(..), Qual(..), Class, tForAll, tExists, MetaVarType(..), prettyPrintType, fromTAp, fromTArrow, tassocToAp, MetaVar(..), tTTuple, tTTuple', tList, tArrow, tAp )where import Control.Monad.Identity import Data.IORef import Data.Binary import Doc.DocLike import Doc.PPrint import FrontEnd.Tc.Kind import Name.Names import Name.VConsts import Support.CanType import Support.Unparse import Util.VarName -- Types data MetaVarType = Tau | Rho | Sigma deriving(Eq,Ord) {-! derive: Binary !-} data Type = TVar { typeVar :: !Tyvar } | TCon { typeCon :: !Tycon } | TAp Type Type | TArrow Type Type | TForAll { typeArgs :: [Tyvar], typeBody :: (Qual Type) } | TExists { typeArgs :: [Tyvar], typeBody :: (Qual Type) } | TMetaVar { metaVar :: MetaVar } | TAssoc { typeCon :: !Tycon, typeClassArgs :: [Type], typeExtraArgs :: [Type] } deriving(Ord,Show) {-! derive: Binary !-} -- | metavars are used in type checking data MetaVar = MetaVar { metaUniq :: {-# UNPACK #-} !Int, metaKind :: Kind, metaRef :: {-# UNPACK #-} !(IORef (Maybe Type)), metaType :: !MetaVarType } {-! derive: Binary !-} instance Eq MetaVar where a == b = metaUniq a == metaUniq b instance Ord MetaVar where compare a b = compare (metaUniq a) (metaUniq b) instance TypeNames Type where tBool = TCon (Tycon tc_Bool kindStar) tString = TAp tList tChar tChar = TCon (Tycon tc_Char kindStar) tUnit = TCon (Tycon tc_Unit kindStar) tCharzh = TCon (Tycon tc_Char_ kindHash) instance Ord (IORef a) instance Binary (IORef a) where put = error "Binary.put: not impl." get = error "Binary.get: not impl." tList :: Type tList = TCon (Tycon tc_List (Kfun kindStar kindStar)) -- | The @(->)@ type constructor. Invariant: @tArrow@ shall not be fully applied. To this end, see 'tAp'. tArrow :: Type tArrow = TCon (Tycon tc_Arrow (kindArg `Kfun` (kindFunRet `Kfun` kindStar))) -- | Type application, enforcing the invariant that there be no fully-applied 'tArrow's tAp :: Type -> Type -> Type tAp (TAp c@TCon{} a) b | c == tArrow = TArrow a b tAp a b = TAp a b instance Eq Type where (TVar a) == (TVar b) = a == b (TMetaVar a) == (TMetaVar b) = a == b (TCon a) == (TCon b) = a == b (TAp a' a) == (TAp b' b) = a' == b' && b == a (TArrow a' a) == (TArrow b' b) = a' == b' && b == a _ == _ = False tassocToAp TAssoc { typeCon = con, typeClassArgs = cas, typeExtraArgs = eas } = foldl tAp (TCon con) (cas ++ eas) tassocToAp _ = error "Representation.tassocToAp: bad." -- Unquantified type variables data Tyvar = Tyvar { tyvarName :: {-# UNPACK #-} !Name, tyvarKind :: Kind } {- derive: Binary -} instance Show Tyvar where showsPrec _ Tyvar { tyvarName = hn, tyvarKind = k } = shows hn . ("::" ++) . shows k tForAll [] ([] :=> t) = t tForAll vs (ps :=> TForAll vs' (ps' :=> t)) = tForAll (vs ++ vs') ((ps ++ ps') :=> t) tForAll x y = TForAll x y tExists [] ([] :=> t) = t tExists vs (ps :=> TExists vs' (ps' :=> t)) = tExists (vs ++ vs') ((ps ++ ps') :=> t) tExists x y = TExists x y tyvar n k = Tyvar n k instance Eq Tyvar where Tyvar { tyvarName = x } == Tyvar { tyvarName = y } = x == y Tyvar { tyvarName = x } /= Tyvar { tyvarName = y } = x /= y instance Ord Tyvar where compare (Tyvar { tyvarName = x }) (Tyvar { tyvarName = y }) = compare x y (Tyvar { tyvarName = x }) <= (Tyvar { tyvarName = y }) = x <= y (Tyvar { tyvarName = x }) >= (Tyvar { tyvarName = y }) = x >= y (Tyvar { tyvarName = x }) < (Tyvar { tyvarName = y }) = x < y (Tyvar { tyvarName = x }) > (Tyvar { tyvarName = y }) = x > y -- Type constructors data Tycon = Tycon { tyconName :: Name, tyconKind :: Kind } deriving(Eq, Show,Ord) {-! derive: Binary !-} instance ToTuple Tycon where --toTuple n = Tycon (nameTuple TypeConstructor n) (foldr Kfun kindStar $ replicate n kindStar) toTuple n = Tycon (name_TupleConstructor typeLevel n) (foldr Kfun kindStar $ replicate n kindStar) instance ToTuple Type where toTuple n = TCon $ toTuple n instance DocLike d => PPrint d Tycon where pprint (Tycon i _) = pprint i infixr 4 `fn` fn :: Type -> Type -> Type a `fn` b = TArrow a b -------------------------------------------------------------------------------- -- Predicates data Pred = IsIn Class Type | IsEq Type Type deriving(Show, Eq,Ord) {-! derive: Binary !-} -- Qualified entities data Qual t = [Pred] :=> t deriving(Show, Eq,Ord) {-! derive: Binary !-} instance (DocLike d,PPrint d t) => PPrint d (Qual t) where pprint ([] :=> r) = pprint r pprint ([x] :=> r) = pprint x <+> text "=>" <+> pprint r pprint (xs :=> r) = tupled (map pprint xs) <+> text "=>" <+> pprint r instance DocLike d => PPrint d Tyvar where pprint tv = tshow (tyvarName tv) instance Binary Tyvar where put (Tyvar aa ab) = do put aa put ab get = do aa <- get ab <- get return (Tyvar aa ab) instance DocLike d => PPrint d Module where pprint s = tshow s withNewNames ts action = subVarName $ do ts' <- mapM newTyvarName ts action ts' newTyvarName t = case tyvarKind t of x@(KBase Star) -> newLookupName (map (:[]) ['a' ..]) x t y@(KBase Star `Kfun` KBase Star) -> newLookupName (map (('f':) . show) [0 :: Int ..]) y t z@(KBase KUTuple) -> newLookupName (map (('u':) . show) [0 :: Int ..]) z t z@(KBase KQuest) -> newLookupName (map (('q':) . show) [0 :: Int ..]) z t z@(KBase KQuestQuest) -> newLookupName (map (('q':) . ('q':) . show) [0 :: Int ..]) z t z -> newLookupName (map (('t':) . show) [0 :: Int ..]) z t prettyPrintType :: DocLike d => Type -> d prettyPrintType = pprint instance DocLike d => PPrint d Type where pprintAssoc _ n t = prettyPrintTypePrec n t prettyPrintTypePrec :: DocLike d => Int -> Type -> d prettyPrintTypePrec n t = unparse $ zup (runIdentity (runVarNameT (f t))) where zup = if n >= 10 then pop empty else id arr = bop (R,0) (space <> text "->" <> space) app = bop (L,100) (text " ") fp (IsIn cn t) = do t' <- f t return (atom (text $ show cn) `app` t') fp (IsEq t1 t2) = do t1' <- f t1 t2' <- f t2 return (atom (parens $ unparse t1' <+> text "=" <+> unparse t2')) f (TForAll [] ([] :=> t)) = f t f (TForAll vs (ps :=> t)) = do withNewNames vs $ \ts' -> do t' <- f t ps' <- mapM fp ps return $ case ps' of [] -> fixitize (N,-3) $ pop (text "forall" <+> hsep (map text ts') <+> text ". ") (atomize t') [p] -> fixitize (N,-3) $ pop (text "forall" <+> hsep (map text ts') <+> text "." <+> unparse p <+> text "=> ") (atomize t') ps -> fixitize (N,-3) $ pop (text "forall" <+> hsep (map text ts') <+> text "." <+> tupled (map unparse ps) <+> text "=> ") (atomize t') f (TExists [] ([] :=> t)) = f t f (TExists vs (ps :=> t)) = do withNewNames vs $ \ts' -> do t' <- f t ps' <- mapM fp ps return $ case ps' of [] -> fixitize (N,-3) $ pop (text "exists" <+> hsep (map text ts') <+> text ". ") (atomize t') [p] -> fixitize (N,-3) $ pop (text "exists" <+> hsep (map text ts') <+> text "." <+> unparse p <+> text "=> ") (atomize t') ps -> fixitize (N,-3) $ pop (text "exists" <+> hsep (map text ts') <+> text "." <+> tupled (map unparse ps) <+> text "=> ") (atomize t') f (TCon tycon) = return $ atom (pprint tycon) f (TVar tyvar) = do vo <- maybeLookupName tyvar case vo of Just c -> return $ atom $ text c Nothing -> return $ atom $ tshow (tyvarName tyvar) f (TAp (TCon (Tycon n _)) x) | n == tc_List = do x <- f x return $ atom (char '[' <> unparse x <> char ']') f TAssoc { typeCon = con, typeClassArgs = cas, typeExtraArgs = eas } = do let x = atom (pprint con) xs <- mapM f (cas ++ eas) return $ foldl app x xs f ta@(TAp {}) | (TCon (Tycon c _),xs) <- fromTAp ta, Just _ <- fromTupname c = do xs <- mapM f xs return $ atom (tupled (map unparse xs)) f (TAp t1 t2) = do t1 <- f t1 t2 <- f t2 return $ t1 `app` t2 f (TArrow t1 t2) = do t1 <- f t1 t2 <- f t2 return $ t1 `arr` t2 f (TMetaVar mv) = return $ atom $ pprint mv --f tv = return $ atom $ parens $ text ("FrontEnd.Tc.Type.pp: " ++ show tv) instance DocLike d => PPrint d MetaVarType where pprint t = case t of Tau -> char 't' Rho -> char 'r' Sigma -> char 's' instance DocLike d => PPrint d Pred where pprint (IsIn c t) = tshow c <+> pprintParen t pprint (IsEq t1 t2) = parens $ prettyPrintType t1 <+> text "=" <+> prettyPrintType t2 instance DocLike d => PPrint d MetaVar where pprint MetaVar { metaUniq = u, metaKind = k, metaType = t } | KBase Star <- k = pprint t <> tshow u | otherwise = parens $ pprint t <> tshow u <> text " :: " <> pprint k instance Show MetaVarType where show mv = pprint mv instance Show MetaVar where show mv = pprint mv fromTAp t = f t [] where f (TArrow a b) rs = f (TAp (TAp tArrow a) b) rs f (TAp a b) rs = f a (b:rs) f t rs = (t,rs) fromTArrow t = f t [] where f (TArrow a b) rs = f b (a:rs) f t rs = (reverse rs,t) instance CanType MetaVar where type TypeOf MetaVar = Kind getType mv = metaKind mv instance CanType Tycon where type TypeOf Tycon = Kind getType (Tycon _ k) = k instance CanType Tyvar where type TypeOf Tyvar = Kind getType = tyvarKind instance CanType Type where type TypeOf Type = Kind getType (TCon tc) = getType tc getType (TVar u) = getType u getType typ@(TAp t _) = case (getType t) of (Kfun _ k) -> k x -> error $ "Representation.getType: kind error in: " ++ (show typ) getType (TArrow _l _r) = kindStar getType (TForAll _ (_ :=> t)) = getType t getType (TExists _ (_ :=> t)) = getType t getType (TMetaVar mv) = getType mv getType ta@TAssoc {} = getType (tassocToAp ta) tTTuple [] = tUnit tTTuple [_] = error "tTTuple" tTTuple ts = foldl TAp (toTuple (length ts)) ts tTTuple' ts = foldl TAp (TCon $ Tycon (name_UnboxedTupleConstructor typeLevel n) (foldr Kfun kindUTuple $ replicate n kindStar)) ts where n = length ts
hvr/jhc
src/FrontEnd/Representation.hs
mit
10,748
0
26
3,080
4,645
2,367
2,278
-1
-1
{-# LANGUAGE BangPatterns, CPP #-} module RegAlloc.Graph.TrivColorable ( trivColorable, ) where #include "HsVersions.h" import RegClass import Reg import GraphBase import UniqFM import FastTypes import Platform import Panic -- trivColorable --------------------------------------------------------------- -- trivColorable function for the graph coloring allocator -- -- This gets hammered by scanGraph during register allocation, -- so needs to be fairly efficient. -- -- NOTE: This only works for arcitectures with just RcInteger and RcDouble -- (which are disjoint) ie. x86, x86_64 and ppc -- -- The number of allocatable regs is hard coded in here so we can do -- a fast comparison in trivColorable. -- -- It's ok if these numbers are _less_ than the actual number of free -- regs, but they can't be more or the register conflict -- graph won't color. -- -- If the graph doesn't color then the allocator will panic, but it won't -- generate bad object code or anything nasty like that. -- -- There is an allocatableRegsInClass :: RegClass -> Int, but doing -- the unboxing is too slow for us here. -- TODO: Is that still true? Could we use allocatableRegsInClass -- without losing performance now? -- -- Look at includes/stg/MachRegs.h to get the numbers. -- -- Disjoint registers ---------------------------------------------------------- -- -- The definition has been unfolded into individual cases for speed. -- Each architecture has a different register setup, so we use a -- different regSqueeze function for each. -- accSqueeze :: FastInt -> FastInt -> (reg -> FastInt) -> UniqFM reg -> FastInt accSqueeze count maxCount squeeze ufm = acc count (eltsUFM ufm) where acc count [] = count acc count _ | count >=# maxCount = count acc count (r:rs) = acc (count +# squeeze r) rs {- Note [accSqueeze] ~~~~~~~~~~~~~~~~~~~~ BL 2007/09 Doing a nice fold over the UniqSet makes trivColorable use 32% of total compile time and 42% of total alloc when compiling SHA1.hs from darcs. Therefore the UniqFM is made non-abstract and we use custom fold. MS 2010/04 When converting UniqFM to use Data.IntMap, the fold cannot use UniqFM internal representation any more. But it is imperative that the assSqueeze stops the folding if the count gets greater or equal to maxCount. We thus convert UniqFM to a (lazy) list, do the fold and stops if necessary, which was the most efficient variant tried. Benchmark compiling 10-times SHA1.hs follows. (original = previous implementation, folding = fold of the whole UFM, lazyFold = the current implementation, hackFold = using internal representation of Data.IntMap) original folding hackFold lazyFold -O -fasm (used everywhere) 31.509s 30.387s 30.791s 30.603s 100.00% 96.44% 97.72% 97.12% -fregs-graph 67.938s 74.875s 62.673s 64.679s 100.00% 110.21% 92.25% 95.20% -fregs-iterative 89.761s 143.913s 81.075s 86.912s 100.00% 160.33% 90.32% 96.83% -fnew-codegen 38.225s 37.142s 37.551s 37.119s 100.00% 97.17% 98.24% 97.11% -fnew-codegen -fregs-graph 91.786s 91.51s 87.368s 86.88s 100.00% 99.70% 95.19% 94.65% -fnew-codegen -fregs-iterative 206.72s 343.632s 194.694s 208.677s 100.00% 166.23% 94.18% 100.95% -} trivColorable :: Platform -> (RegClass -> VirtualReg -> FastInt) -> (RegClass -> RealReg -> FastInt) -> Triv VirtualReg RegClass RealReg trivColorable platform virtualRegSqueeze realRegSqueeze RcInteger conflicts exclusions | let !cALLOCATABLE_REGS_INTEGER = iUnbox (case platformArch platform of ArchX86 -> 3 ArchX86_64 -> 5 ArchPPC -> 16 ArchSPARC -> 14 ArchPPC_64 -> panic "trivColorable ArchPPC_64" ArchARM _ _ _ -> panic "trivColorable ArchARM" ArchARM64 -> panic "trivColorable ArchARM64" ArchAlpha -> panic "trivColorable ArchAlpha" ArchMipseb -> panic "trivColorable ArchMipseb" ArchMipsel -> panic "trivColorable ArchMipsel" ArchJavaScript-> panic "trivColorable ArchJavaScript" ArchUnknown -> panic "trivColorable ArchUnknown") , count2 <- accSqueeze (_ILIT(0)) cALLOCATABLE_REGS_INTEGER (virtualRegSqueeze RcInteger) conflicts , count3 <- accSqueeze count2 cALLOCATABLE_REGS_INTEGER (realRegSqueeze RcInteger) exclusions = count3 <# cALLOCATABLE_REGS_INTEGER trivColorable platform virtualRegSqueeze realRegSqueeze RcFloat conflicts exclusions | let !cALLOCATABLE_REGS_FLOAT = iUnbox (case platformArch platform of ArchX86 -> 0 ArchX86_64 -> 0 ArchPPC -> 0 ArchSPARC -> 22 ArchPPC_64 -> panic "trivColorable ArchPPC_64" ArchARM _ _ _ -> panic "trivColorable ArchARM" ArchARM64 -> panic "trivColorable ArchARM64" ArchAlpha -> panic "trivColorable ArchAlpha" ArchMipseb -> panic "trivColorable ArchMipseb" ArchMipsel -> panic "trivColorable ArchMipsel" ArchJavaScript-> panic "trivColorable ArchJavaScript" ArchUnknown -> panic "trivColorable ArchUnknown") , count2 <- accSqueeze (_ILIT(0)) cALLOCATABLE_REGS_FLOAT (virtualRegSqueeze RcFloat) conflicts , count3 <- accSqueeze count2 cALLOCATABLE_REGS_FLOAT (realRegSqueeze RcFloat) exclusions = count3 <# cALLOCATABLE_REGS_FLOAT trivColorable platform virtualRegSqueeze realRegSqueeze RcDouble conflicts exclusions | let !cALLOCATABLE_REGS_DOUBLE = iUnbox (case platformArch platform of ArchX86 -> 6 ArchX86_64 -> 0 ArchPPC -> 26 ArchSPARC -> 11 ArchPPC_64 -> panic "trivColorable ArchPPC_64" ArchARM _ _ _ -> panic "trivColorable ArchARM" ArchARM64 -> panic "trivColorable ArchARM64" ArchAlpha -> panic "trivColorable ArchAlpha" ArchMipseb -> panic "trivColorable ArchMipseb" ArchMipsel -> panic "trivColorable ArchMipsel" ArchJavaScript-> panic "trivColorable ArchJavaScript" ArchUnknown -> panic "trivColorable ArchUnknown") , count2 <- accSqueeze (_ILIT(0)) cALLOCATABLE_REGS_DOUBLE (virtualRegSqueeze RcDouble) conflicts , count3 <- accSqueeze count2 cALLOCATABLE_REGS_DOUBLE (realRegSqueeze RcDouble) exclusions = count3 <# cALLOCATABLE_REGS_DOUBLE trivColorable platform virtualRegSqueeze realRegSqueeze RcDoubleSSE conflicts exclusions | let !cALLOCATABLE_REGS_SSE = iUnbox (case platformArch platform of ArchX86 -> 8 ArchX86_64 -> 10 ArchPPC -> 0 ArchSPARC -> 0 ArchPPC_64 -> panic "trivColorable ArchPPC_64" ArchARM _ _ _ -> panic "trivColorable ArchARM" ArchARM64 -> panic "trivColorable ArchARM64" ArchAlpha -> panic "trivColorable ArchAlpha" ArchMipseb -> panic "trivColorable ArchMipseb" ArchMipsel -> panic "trivColorable ArchMipsel" ArchJavaScript-> panic "trivColorable ArchJavaScript" ArchUnknown -> panic "trivColorable ArchUnknown") , count2 <- accSqueeze (_ILIT(0)) cALLOCATABLE_REGS_SSE (virtualRegSqueeze RcDoubleSSE) conflicts , count3 <- accSqueeze count2 cALLOCATABLE_REGS_SSE (realRegSqueeze RcDoubleSSE) exclusions = count3 <# cALLOCATABLE_REGS_SSE -- Specification Code ---------------------------------------------------------- -- -- The trivColorable function for each particular architecture should -- implement the following function, but faster. -- {- trivColorable :: RegClass -> UniqSet Reg -> UniqSet Reg -> Bool trivColorable classN conflicts exclusions = let acc :: Reg -> (Int, Int) -> (Int, Int) acc r (cd, cf) = case regClass r of RcInteger -> (cd+1, cf) RcFloat -> (cd, cf+1) _ -> panic "Regs.trivColorable: reg class not handled" tmp = foldUniqSet acc (0, 0) conflicts (countInt, countFloat) = foldUniqSet acc tmp exclusions squeese = worst countInt classN RcInteger + worst countFloat classN RcFloat in squeese < allocatableRegsInClass classN -- | Worst case displacement -- node N of classN has n neighbors of class C. -- -- We currently only have RcInteger and RcDouble, which don't conflict at all. -- This is a bit boring compared to what's in RegArchX86. -- worst :: Int -> RegClass -> RegClass -> Int worst n classN classC = case classN of RcInteger -> case classC of RcInteger -> min n (allocatableRegsInClass RcInteger) RcFloat -> 0 RcDouble -> case classC of RcFloat -> min n (allocatableRegsInClass RcFloat) RcInteger -> 0 -- allocatableRegs is allMachRegNos with the fixed-use regs removed. -- i.e., these are the regs for which we are prepared to allow the -- register allocator to attempt to map VRegs to. allocatableRegs :: [RegNo] allocatableRegs = let isFree i = isFastTrue (freeReg i) in filter isFree allMachRegNos -- | The number of regs in each class. -- We go via top level CAFs to ensure that we're not recomputing -- the length of these lists each time the fn is called. allocatableRegsInClass :: RegClass -> Int allocatableRegsInClass cls = case cls of RcInteger -> allocatableRegsInteger RcFloat -> allocatableRegsDouble allocatableRegsInteger :: Int allocatableRegsInteger = length $ filter (\r -> regClass r == RcInteger) $ map RealReg allocatableRegs allocatableRegsFloat :: Int allocatableRegsFloat = length $ filter (\r -> regClass r == RcFloat $ map RealReg allocatableRegs -}
christiaanb/ghc
compiler/nativeGen/RegAlloc/Graph/TrivColorable.hs
bsd-3-clause
12,047
0
16
4,587
1,071
532
539
113
45
{-# LANGUAGE TypeFamilies, FlexibleInstances, FlexibleContexts, UndecidableInstances, MultiParamTypeClasses, FunctionalDependencies #-} {-# OPTIONS_GHC -fno-warn-redundant-constraints #-} module T10139 where import Data.Monoid import Data.Kind import Data.Coerce class Monoid v => Measured v a | a -> v where _measure :: v -> a data FingerTree v a = Dummy v a singleton :: Measured v a => a -> FingerTree v a singleton = undefined class DOps a where plus :: a -> D a -> a type family D a :: Type type instance D (FingerTree (Size Int, v) (Sized a)) = [Diff (Normal a)] type family Normal a :: Type data Diff a = Add Int a newtype Sized a = Sized a newtype Size a = Size a -- This works: {- instance (Measured (Size Int, v) (Sized a), Coercible (Normal a) (Sized a)) => DOps (FingerTree (Size Int, v) (Sized a)) where plus = foldr (\(Add index val) seq -> singleton ((coerce) val)) -} -- This hangs: instance (Measured (Size Int, v) (Sized a), Coercible (Normal a) (Sized a)) => DOps (FingerTree (Size Int, v) (Sized a)) where plus = foldr (flip f) where f _seq x = case x of Add _index val -> singleton ((coerce) val)
sdiehl/ghc
testsuite/tests/indexed-types/should_compile/T10139.hs
bsd-3-clause
1,165
0
14
245
346
189
157
-1
-1
{-# OPTIONS_GHC -fcontext-stack=1000 #-} {-# LANGUAGE FlexibleContexts, FlexibleInstances, FunctionalDependencies, MultiParamTypeClasses, OverlappingInstances, TypeSynonymInstances, TypeOperators, UndecidableInstances, TypeFamilies #-} module T5321Fun where -- As the below code demonstrates, the same issues demonstrated with -- Functional Dependencies also appear with Type Families, although less --horribly, as their code-path seems more optimized in the current -- constraint solver: -- Our running example, for simplicity's sake, is a type-level map of a -- single function. For reference, here is the code for a simple -- value-level map of a single function. -- > vfoo = id -- > mapfoo (x : xs) = vfoo x : mapfoo xs -- > mapfoo [] = [] -- Because Haskell is a lazy language, this runs in O(n) time and constant stack. -- We now lift map to the type level, to operate over HLists. -- First, the basic HList types infixr 3 :* data x :* xs = x :* xs deriving Show data HNil = HNil deriving Show -- Next, a large boring HList -- Adds ten cells addData x = i :* i :* d :* d :* s :* i :* i :* d :* d :* s :* x where i = 1 :: Int d = 1 :: Double s = "" -- Has 70 cells. sampleData = addData $ addData $ addData $ addData $ addData $ addData $ addData $ HNil class TFoo x where type TFooFun x tfoo :: x -> TFooFun x tfoo = undefined instance TFoo Int where type TFooFun Int = Double instance TFoo Double where type TFooFun Double = Int instance TFoo String where type TFooFun String = String class THMapFoo1 as where type THMapFoo1Res as thMapFoo1 :: as -> THMapFoo1Res as instance (TFoo a, THMapFoo1 as) => THMapFoo1 (a :* as) where type THMapFoo1Res (a :* as) = TFooFun a :* THMapFoo1Res as thMapFoo1 (x :* xs) = tfoo x :* thMapFoo1 xs instance THMapFoo1 HNil where type THMapFoo1Res HNil = HNil thMapFoo1 _ = HNil -- The following, when enabled, takes ~3.5s. This demonstrates that slowdown occurs with type families as well. testTHMapFoo1 = thMapFoo1 sampleData class THMapFoo2 acc as where type THMapFoo2Res acc as thMapFoo2 :: acc -> as -> THMapFoo2Res acc as instance (TFoo a, THMapFoo2 (TFooFun a :* acc) as) => THMapFoo2 acc (a :* as) where type THMapFoo2Res acc (a :* as) = THMapFoo2Res (TFooFun a :* acc) as thMapFoo2 acc (x :* xs) = thMapFoo2 (tfoo x :* acc) xs instance THMapFoo2 acc HNil where type THMapFoo2Res acc HNil = acc thMapFoo2 acc _ = acc -- The following, when enabled, takes ~0.6s. This demonstrates that the -- tail recursive transform fixes the slowdown with type families just as -- with fundeps. testTHMapFoo2 = thMapFoo2 HNil sampleData class THMapFoo3 acc as where type THMapFoo3Res acc as thMapFoo3 :: acc -> as -> THMapFoo3Res acc as instance (THMapFoo3 (TFooFun a :* acc) as, TFoo a) => THMapFoo3 acc (a :* as) where type THMapFoo3Res acc (a :* as) = THMapFoo3Res (TFooFun a :* acc) as thMapFoo3 acc (x :* xs) = thMapFoo3 (tfoo x :* acc) xs instance THMapFoo3 acc HNil where type THMapFoo3Res acc HNil = acc thMapFoo3 acc _ = acc -- The following, when enabled, also takes ~0.6s. This demonstrates that, -- unlike the fundep case, the order of type class constraints does not, -- in this instance, affect the performance of type families. testTHMapFoo3 = thMapFoo3 HNil sampleData
frantisekfarka/ghc-dsi
testsuite/tests/perf/compiler/T5321Fun.hs
bsd-3-clause
3,485
0
14
841
752
406
346
58
1
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE NoImplicitPrelude #-} ----------------------------------------------------------------------------- -- | -- Module : Foreign.ForeignPtr.Safe -- Copyright : (c) The University of Glasgow 2001 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : ffi@haskell.org -- Stability : provisional -- Portability : portable -- -- The 'ForeignPtr' type and operations. This module is part of the -- Foreign Function Interface (FFI) and will usually be imported via -- the "Foreign" module. -- -- Safe API Only. -- ----------------------------------------------------------------------------- module Foreign.ForeignPtr.Safe ( -- * Finalised data pointers ForeignPtr , FinalizerPtr , FinalizerEnvPtr -- ** Basic operations , newForeignPtr , newForeignPtr_ , addForeignPtrFinalizer , newForeignPtrEnv , addForeignPtrFinalizerEnv , withForeignPtr , finalizeForeignPtr -- ** Low-level operations , touchForeignPtr , castForeignPtr -- ** Allocating managed memory , mallocForeignPtr , mallocForeignPtrBytes , mallocForeignPtrArray , mallocForeignPtrArray0 ) where import Foreign.ForeignPtr.Imp
ryantm/ghc
libraries/base/Foreign/ForeignPtr/Safe.hs
bsd-3-clause
1,340
0
4
331
86
65
21
20
0
{-# LANGUAGE TypeFamilies #-} module Hadrian.Oracles.ArgsHash ( TrackArgument, trackAllArguments, trackArgsHash, argsHashOracle ) where import Control.Monad import Development.Shake import Development.Shake.Classes import Hadrian.Expression hiding (inputs, outputs) import Hadrian.Target -- | 'TrackArgument' is used to specify the arguments that should be tracked by -- the @ArgsHash@ oracle. The safest option is to track all arguments, but some -- arguments, such as @-jN@, do not change the build results, hence there is no -- need to initiate unnecessary rebuild if they are added to or removed from a -- command line. If all arguments should be tracked, use 'trackAllArguments'. type TrackArgument c b = Target c b -> String -> Bool -- | Returns 'True' for all targets and arguments, hence can be used a safe -- default for 'argsHashOracle'. trackAllArguments :: TrackArgument c b trackAllArguments _ _ = True -- | Given a 'Target' this 'Action' determines the corresponding argument list -- and computes its hash. The resulting value is tracked in a Shake oracle, -- hence initiating rebuilds when the hash changes (a hash change indicates -- changes in the build command for the given target). -- Note: for efficiency we replace the list of input files with its hash to -- avoid storing long lists of source files passed to some builders (e.g. ar) -- in the Shake database. This optimisation is normally harmless, because -- argument list constructors are assumed not to examine target sources, but -- only append them to argument lists where appropriate. trackArgsHash :: (ShakeValue c, ShakeValue b) => Target c b -> Action () trackArgsHash t = do let hashedInputs = [ show $ hash (inputs t) ] hashedTarget = target (context t) (builder t) hashedInputs (outputs t) void (askOracle $ ArgsHash hashedTarget :: Action Int) newtype ArgsHash c b = ArgsHash (Target c b) deriving (Binary, Eq, Hashable, NFData, Show, Typeable) type instance RuleResult (ArgsHash c b) = Int -- | This oracle stores per-target argument list hashes in the Shake database, -- allowing the user to track them between builds using 'trackArgsHash' queries. argsHashOracle :: (ShakeValue c, ShakeValue b) => TrackArgument c b -> Args c b -> Rules () argsHashOracle trackArgument args = void $ addOracle $ \(ArgsHash target) -> do argList <- interpret target args let trackedArgList = filter (trackArgument target) argList return $ hash trackedArgList
snowleopard/shaking-up-ghc
src/Hadrian/Oracles/ArgsHash.hs
bsd-3-clause
2,494
0
14
448
414
225
189
25
1
module NegativeIn1 where f x y = x + y
kmate/HaRe
old/testing/introCase/NegativeIn1_TokOut.hs
bsd-3-clause
42
0
5
13
18
10
8
2
1
{-# LANGUAGE GeneralizedNewtypeDeriving #-} module Graphics.UI.Bottle.Widgets.Spacer ( make , makeWidget , makeHorizontal, makeVertical , makeHorizontalWidget , makeHorizLine , empty ) where import Control.Monad (void) import Data.Monoid (mempty) import Data.Vector.Vector2 (Vector2(..)) import Graphics.UI.Bottle.View (View) import Graphics.UI.Bottle.Widget (Widget) import qualified Graphics.DrawingCombinators as Draw import qualified Graphics.UI.Bottle.Animation as Anim import qualified Graphics.UI.Bottle.Widget as Widget widget :: View -> Widget f widget = uncurry Widget.liftView make :: Anim.Size -> View make size = (size, mempty) makeWidget :: Widget.Size -> Widget f makeWidget = widget . make makeHorizontal :: Anim.R -> View makeHorizontal width = make $ Vector2 width 0 makeVertical :: Anim.R -> View makeVertical height = make $ Vector2 0 height makeHorizontalWidget :: Widget.R -> Widget f makeHorizontalWidget = widget . makeHorizontal horizLineFrame :: Anim.AnimId -> Widget.Size -> Anim.Frame horizLineFrame animId size@(Vector2 w h) = Anim.simpleFrameDownscale animId size . void $ Draw.line (0, h/2) (w, h/2) makeHorizLine :: Anim.AnimId -> Widget.Size -> Widget f makeHorizLine animId size = Widget.liftView size $ horizLineFrame animId size empty :: Widget f empty = makeWidget 0
sinelaw/lamdu
bottlelib/Graphics/UI/Bottle/Widgets/Spacer.hs
gpl-3.0
1,330
0
8
195
411
232
179
35
1
{-# OPTIONS_GHC -fno-warn-redundant-constraints #-} {-# LANGUAGE FlexibleInstances, TypeSynonymInstances, UndecidableInstances #-} module Tc173a where class FormValue value where isFormValue :: value -> () isFormValue _ = () class FormTextField value instance FormTextField String instance {-# OVERLAPPABLE #-} FormTextField value => FormTextFieldIO value class FormTextFieldIO value instance FormTextFieldIO value => FormValue value instance {-# OVERLAPPING #-} FormTextFieldIO value => FormTextFieldIO (Maybe value)
christiaanb/ghc
testsuite/tests/typecheck/should_compile/Tc173a.hs
bsd-3-clause
533
0
8
75
107
52
55
-1
-1
module Shaker.GhcInterface ( -- * GHC Compile management initializeGhc ,ghcCompile ,getListNeededPackages ,installedPackageIdString ,fillModuleDataTest ,addLibraryToDynFlags ,searchInstalledPackageId ) where import Distribution.InstalledPackageInfo import Distribution.Simple.PackageIndex import Control.Arrow import Control.Monad.Reader(lift, asks ) import Data.List import Data.Monoid import Data.Maybe import Digraph import Distribution.Package (InstalledPackageId(..)) import DynFlags import GHC hiding (parseModule, HsModule) import GHC.Paths import HscTypes import Linker import Name (nameOccName) import OccName (occNameString) import Outputable import Packages (lookupModuleInAllPackages, PackageConfig) import qualified Data.Map as M import Shaker.Io import Shaker.Type import Shaker.ModuleData import Shaker.CommonUtil import Var (varName) type ImportToPackages = [ ( String, [PackageConfig] ) ] -- | Get the list of unresolved import and -- unexposed yet needed packages getListNeededPackages :: Shaker IO [String] getListNeededPackages = do cpIn <- fmap head (asks shakerCompileInputs) (PackageData map_import_modules list_project_modules) <- lift mapImportToModules import_to_packages <- lift $ runGhc (Just libdir) $ do initializeGhc cpIn dyn_flags <- getSessionDynFlags return $ map ( \ imp -> (imp , lookupModuleInAllPackages dyn_flags . mkModuleName $ imp) ) >>> map ( second (map fst) ) $ (M.keys map_import_modules \\ list_project_modules) return $ getPackagesToExpose import_to_packages getPackagesToExpose :: ImportToPackages -> [String] getPackagesToExpose = map snd >>> filter (not . null) >>> filter (all (not . exposed) ) >>> map head >>> nubBy (\a b -> getPackage a == getPackage b ) >>> filter (not . exposed) >>> map getPackage where getPackage = installedPackageId >>> installedPackageIdString installedPackageIdString :: InstalledPackageId -> String installedPackageIdString (InstalledPackageId v) = v initializeGhc :: GhcMonad m => CompileInput -> m () initializeGhc cpIn@(CompileInput _ _ procFlags strflags targetFiles) = do modifySession (\h -> h {hsc_HPT = emptyHomePackageTable} ) dflags <- getSessionDynFlags (newFlags,_,_) <- parseDynamicFlags dflags (map noLoc strflags) let chgdFlags = configureDynFlagsWithCompileInput cpIn newFlags _ <- setSessionDynFlags $ procFlags chgdFlags target <- mapM (`guessTarget` Nothing) targetFiles setTargets target -- | Configure and load targets of compilation. -- It is possible to exploit the compilation result after this step. ghcCompile :: GhcMonad m => CompileInput -> m SuccessFlag ghcCompile cpIn = do initializeGhc cpIn dflags <- getSessionDynFlags liftIO $ unload dflags [] load LoadAllTargets -- | Change the dynflags with information from the CompileInput like importPaths -- and .o and .hi fileListenInfoDirectory configureDynFlagsWithCompileInput :: CompileInput -> DynFlags -> DynFlags configureDynFlagsWithCompileInput cpIn dflags = dflags{ importPaths = sourceDirs ,objectDir = Just compileTarget ,hiDir = Just compileTarget } where compileTarget = compileInputBuildDirectory cpIn sourceDirs = compileInputSourceDirs cpIn -- * Test discovering fillModuleDataTest :: [ModuleData] -> Shaker IO [[ModuleData]] fillModuleDataTest = separateEqual >>> mapM fillModuleDataTest' fillModuleDataTest' :: [ModuleData] -> Shaker IO [ModuleData] fillModuleDataTest' modDatas = do cpIn <- fmap mconcat (asks shakerCompileInputs) let newCpIn = cpIn { compileInputTargetFiles = map moduleDataFileName modDatas } ghcModuleDatas <- lift $ runGhc (Just libdir) $ do _ <- ghcCompile newCpIn mss <- depanal [] False let sort_mss = flattenSCCs $ topSortModuleGraph True mss Nothing mapM convertModSummaryToModuleData sort_mss mergeMdatas >>> filter (\a -> moduleDataName a /= "") >>> removeNonTestModules >>> return $ (modDatas ++ ghcModuleDatas) mergeMdatas :: [ModuleData] -> [ModuleData] mergeMdatas lstMdatas = map (\mdata -> filter (==mdata) >>> mconcat $ lstMdatas) uniqueMdata where uniqueMdata = nub lstMdatas -- | Collect module name and tests name for the given module convertModSummaryToModuleData :: (GhcMonad m) => ModSummary -> m ModuleData convertModSummaryToModuleData modSum = do mayModuleInfo <- getModuleInfo $ ms_mod modSum let assertions = getHunitAssertions mayModuleInfo let testCases = getHunitTestCase mayModuleInfo return GhcModuleData { ghcModuleDataName = modName ,ghcModuleDataAssertions = assertions ,ghcModuleDataTestCase = testCases } where modName = (moduleNameString . moduleName . ms_mod) modSum getHunitAssertions :: Maybe ModuleInfo -> [String] getHunitAssertions = getFunctionTypeWithPredicate (== "Test.HUnit.Lang.Assertion") getHunitTestCase :: Maybe ModuleInfo -> [String] getHunitTestCase = getFunctionTypeWithPredicate (== "Test.HUnit.Base.Test") getFunctionTypeWithPredicate :: (String -> Bool) -> Maybe ModuleInfo -> [String] getFunctionTypeWithPredicate _ Nothing = [] getFunctionTypeWithPredicate predicat (Just modInfo) = getIdExportedList >>> map ((showPpr . idType) &&& getFunctionNameFromId ) >>> filter (predicat . fst) >>> map snd $ modInfo getFunctionNameFromId :: Id -> String getFunctionNameFromId = occNameString . nameOccName . varName getIdExportedList :: ModuleInfo -> [Id] getIdExportedList modInfo = modInfoTyThings >>> mapMaybe tyThingToId >>> filter (\a -> varName a `elem` lstExportedNames) $ modInfo where lstExportedNames = modInfoExports modInfo tyThingToId :: TyThing -> Maybe Id tyThingToId (AnId tyId) = Just tyId tyThingToId _ = Nothing addLibraryToDynFlags :: [String] -> DynFlags -> DynFlags addLibraryToDynFlags listInstalledPkgId dflags = dflags { packageFlags = nub $ map ExposePackageId listInstalledPkgId ++ oldPackageFlags } where oldPackageFlags = packageFlags dflags searchInstalledPackageId :: String -> Shaker IO (Maybe String) searchInstalledPackageId pkgName = do pkgIndex <- asks shakerPackageIndex let srchRes = searchByName pkgIndex pkgName return $ processSearchResult srchRes where processSearchResult None = Nothing processSearchResult (Unambiguous a) = Just $ installedPackageId >>> installedPackageIdString $ last a processSearchResult (Ambiguous (a:_)) = Just $ installedPackageId >>> installedPackageIdString $ last a processSearchResult _ = Nothing
bonnefoa/Shaker
src/Shaker/GhcInterface.hs
isc
6,547
0
20
1,091
1,685
872
813
142
4
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE TypeFamilies #-} -- | This module defines a collection of simplification rules, as per -- "Futhark.Optimise.Simplifier.Rule". They are used in the -- simplifier. module Futhark.Optimise.Simplifier.Rules ( standardRules ) where import Control.Applicative import Control.Monad import Data.Either import Data.Foldable (all) import Data.List hiding (all) import Data.Maybe import Data.Monoid import qualified Data.Map.Strict as M import qualified Data.Set as S import qualified Futhark.Analysis.SymbolTable as ST import qualified Futhark.Analysis.UsageTable as UT import Futhark.Analysis.DataDependencies import Futhark.Optimise.Simplifier.ClosedForm import Futhark.Optimise.Simplifier.Rule import Futhark.Optimise.Simplifier.RuleM import qualified Futhark.Analysis.AlgSimplify as AS import qualified Futhark.Analysis.ScalExp as SE import Futhark.Analysis.PrimExp.Convert import Futhark.Representation.AST import Futhark.Representation.AST.Attributes.Aliases import Futhark.Construct import Futhark.Transform.Substitute import Futhark.Util import Prelude hiding (all) topDownRules :: (MonadBinder m, Aliased (Lore m)) => TopDownRules m topDownRules = [ hoistLoopInvariantMergeVariables , simplifyClosedFormLoop , simplifKnownIterationLoop , simplifyLoopVariables , simplifyRearrange , simplifyRotate , letRule simplifyBinOp , letRule simplifyCmpOp , letRule simplifyUnOp , letRule simplifyConvOp , letRule simplifyAssert , letRule copyScratchToScratch , constantFoldPrimFun , simplifyIndexIntoReshape , removeEmptySplits , removeSingletonSplits , evaluateBranch , simplifyBoolBranch , hoistBranchInvariant , simplifyScalExp , letRule simplifyIdentityReshape , letRule simplifyReshapeReshape , letRule simplifyReshapeScratch , letRule simplifyReshapeReplicate , letRule improveReshape , removeScratchValue , simplifyFallbackBranch , removeIdentityInPlace , removeFullInPlace , simplifyBranchResultComparison , simplifyReplicate , arrayLitToReplicate ] bottomUpRules :: MonadBinder m => BottomUpRules m bottomUpRules = [ removeRedundantMergeVariables , removeDeadBranchResult , simplifyIndex , simplifyConcat ] asInt32PrimExp :: PrimExp v -> PrimExp v asInt32PrimExp pe | IntType it <- primExpType pe, it /= Int32 = ConvOpExp (SExt it Int32) pe | otherwise = pe -- | A set of standard simplification rules. These assume pure -- functional semantics, and so probably should not be applied after -- memory block merging. standardRules :: (MonadBinder m, Aliased (Lore m)) => RuleBook m standardRules = RuleBook topDownRules bottomUpRules -- This next one is tricky - it's easy enough to determine that some -- loop result is not used after the loop, but here, we must also make -- sure that it does not affect any other values. -- -- I do not claim that the current implementation of this rule is -- perfect, but it should suffice for many cases, and should never -- generate wrong code. removeRedundantMergeVariables :: MonadBinder m => BottomUpRule m removeRedundantMergeVariables (_, used) (Let pat _ (DoLoop ctx val form body)) | not $ all (usedAfterLoop . fst) val, null ctx = -- FIXME: things get tricky if we can remove all vals -- but some ctxs are still used. We take the easy way -- out for now. let (ctx_es, val_es) = splitAt (length ctx) $ bodyResult body necessaryForReturned = findNecessaryForReturned usedAfterLoopOrInForm (zip (map fst $ ctx++val) $ ctx_es++val_es) (dataDependencies body) resIsNecessary ((v,_), _) = usedAfterLoop v || paramName v `S.member` necessaryForReturned || referencedInPat v || referencedInForm v (keep_ctx, discard_ctx) = partition resIsNecessary $ zip ctx ctx_es (keep_valpart, discard_valpart) = partition (resIsNecessary . snd) $ zip (patternValueElements pat) $ zip val val_es (keep_valpatelems, keep_val) = unzip keep_valpart (_discard_valpatelems, discard_val) = unzip discard_valpart (ctx', ctx_es') = unzip keep_ctx (val', val_es') = unzip keep_val body' = body { bodyResult = ctx_es' ++ val_es' } free_in_keeps = freeIn keep_valpatelems stillUsedContext pat_elem = patElemName pat_elem `S.member` (free_in_keeps <> freeIn (filter (/=pat_elem) $ patternContextElements pat)) pat' = pat { patternValueElements = keep_valpatelems , patternContextElements = filter stillUsedContext $ patternContextElements pat } in if ctx' ++ val' == ctx ++ val then cannotSimplify else do -- We can't just remove the bindings in 'discard', since the loop -- body may still use their names in (now-dead) expressions. -- Hence, we add them inside the loop, fully aware that dead-code -- removal will eventually get rid of them. Some care is -- necessary to handle unique bindings. body'' <- insertStmsM $ do mapM_ (uncurry letBindNames') $ dummyStms discard_ctx mapM_ (uncurry letBindNames') $ dummyStms discard_val return body' letBind_ pat' $ DoLoop ctx' val' form body'' where pat_used = map (`UT.used` used) $ patternValueNames pat used_vals = map fst $ filter snd $ zip (map (paramName . fst) val) pat_used usedAfterLoop = flip elem used_vals . paramName usedAfterLoopOrInForm p = usedAfterLoop p || paramName p `S.member` freeIn form patAnnotNames = freeIn $ map fst $ ctx++val referencedInPat = (`S.member` patAnnotNames) . paramName referencedInForm = (`S.member` freeIn form) . paramName dummyStms = map dummyStm dummyStm ((p,e), _) | unique (paramDeclType p), Var v <- e = ([paramName p], BasicOp $ Copy v) | otherwise = ([paramName p], BasicOp $ SubExp e) removeRedundantMergeVariables _ _ = cannotSimplify findNecessaryForReturned :: (Param attr -> Bool) -> [(Param attr, SubExp)] -> M.Map VName Names -> Names findNecessaryForReturned usedAfterLoop merge_and_res allDependencies = iterateNecessary mempty where iterateNecessary prev_necessary | necessary == prev_necessary = necessary | otherwise = iterateNecessary necessary where necessary = mconcat $ map dependencies returnedResultSubExps usedAfterLoopOrNecessary param = usedAfterLoop param || paramName param `S.member` prev_necessary returnedResultSubExps = map snd $ filter (usedAfterLoopOrNecessary . fst) merge_and_res dependencies (Constant _) = S.empty dependencies (Var v) = M.findWithDefault (S.singleton v) v allDependencies -- We may change the type of the loop if we hoist out a shape -- annotation, in which case we also need to tweak the bound pattern. hoistLoopInvariantMergeVariables :: forall m.MonadBinder m => TopDownRule m hoistLoopInvariantMergeVariables _ (Let pat _ (DoLoop ctx val form loopbody)) = -- Figure out which of the elements of loopresult are -- loop-invariant, and hoist them out. case foldr checkInvariance ([], explpat, [], []) $ zip merge res of ([], _, _, _) -> -- Nothing is invariant. cannotSimplify (invariant, explpat', merge', res') -> do -- We have moved something invariant out of the loop. let loopbody' = loopbody { bodyResult = res' } invariantShape :: (a, VName) -> Bool invariantShape (_, shapemerge) = shapemerge `elem` map (paramName . fst) merge' (implpat',implinvariant) = partition invariantShape implpat implinvariant' = [ (patElemIdent p, Var v) | (p,v) <- implinvariant ] implpat'' = map fst implpat' explpat'' = map fst explpat' (ctx', val') = splitAt (length implpat') merge' forM_ (invariant ++ implinvariant') $ \(v1,v2) -> letBindNames'_ [identName v1] $ BasicOp $ SubExp v2 letBind_ (Pattern implpat'' explpat'') $ DoLoop ctx' val' form loopbody' where merge = ctx ++ val res = bodyResult loopbody implpat = zip (patternContextElements pat) $ map paramName $ loopResultContext (map fst ctx) (map fst val) explpat = zip (patternValueElements pat) $ map (paramName . fst) val namesOfMergeParams = S.fromList $ map (paramName . fst) $ ctx++val removeFromResult (mergeParam,mergeInit) explpat' = case partition ((==paramName mergeParam) . snd) explpat' of ([(patelem,_)], rest) -> (Just (patElemIdent patelem, mergeInit), rest) (_, _) -> (Nothing, explpat') checkInvariance ((mergeParam,mergeInit), resExp) (invariant, explpat', merge', resExps) | not (unique (paramDeclType mergeParam)) || arrayRank (paramDeclType mergeParam) == 1, isInvariant resExp = let (bnd, explpat'') = removeFromResult (mergeParam,mergeInit) explpat' in (maybe id (:) bnd $ (paramIdent mergeParam, mergeInit) : invariant, explpat'', merge', resExps) where -- A non-unique merge variable is invariant if the corresponding -- subexp in the result is EITHER: -- -- (0) a variable of the same name as the parameter, where -- all existential parameters are already known to be -- invariant isInvariant (Var v2) | paramName mergeParam == v2 = allExistentialInvariant (S.fromList $ map (identName . fst) invariant) mergeParam -- (1) or identical to the initial value of the parameter. isInvariant _ = mergeInit == resExp checkInvariance ((mergeParam,mergeInit), resExp) (invariant, explpat', merge', resExps) = (invariant, explpat', (mergeParam,mergeInit):merge', resExp:resExps) allExistentialInvariant namesOfInvariant mergeParam = all (invariantOrNotMergeParam namesOfInvariant) (paramName mergeParam `S.delete` freeIn mergeParam) invariantOrNotMergeParam namesOfInvariant name = not (name `S.member` namesOfMergeParams) || name `S.member` namesOfInvariant hoistLoopInvariantMergeVariables _ _ = cannotSimplify -- | A function that, given a variable name, returns its definition. type VarLookup lore = VName -> Maybe (Exp lore, Certificates) -- | A function that, given a subexpression, returns its type. type TypeLookup = SubExp -> Maybe Type type LetTopDownRule lore u = VarLookup lore -> TypeLookup -> BasicOp lore -> Maybe (BasicOp lore, Certificates) letRule :: MonadBinder m => LetTopDownRule (Lore m) u -> TopDownRule m letRule rule vtable (Let pat aux (BasicOp op)) = do (op', cs) <- liftMaybe $ rule defOf seType op certifying (cs <> stmAuxCerts aux) $ letBind_ pat $ BasicOp op' where defOf = (`ST.lookupExp` vtable) seType (Var v) = ST.lookupType v vtable seType (Constant v) = Just $ Prim $ primValueType v letRule _ _ _ = cannotSimplify simplifyClosedFormLoop :: MonadBinder m => TopDownRule m simplifyClosedFormLoop _ (Let pat _ (DoLoop [] val (ForLoop i _ bound []) body)) = loopClosedForm pat val (S.singleton i) bound body simplifyClosedFormLoop _ _ = cannotSimplify simplifyLoopVariables :: (MonadBinder m, Aliased (Lore m)) => TopDownRule m simplifyLoopVariables vtable (Let pat _ (DoLoop ctx val form@(ForLoop i it num_iters loop_vars) body)) | simplifiable <- map checkIfSimplifiable loop_vars, not $ all isNothing simplifiable = do -- Check if the simplifications throw away more information than -- we are comfortable with at this stage. (maybe_loop_vars, body_prefix_stms) <- localScope (scopeOf form) $ unzip <$> zipWithM onLoopVar loop_vars simplifiable if maybe_loop_vars == map Just loop_vars then cannotSimplify else do body' <- insertStmsM $ do mapM_ addStm $ concat body_prefix_stms resultBodyM =<< bodyBind body letBind_ pat $ DoLoop ctx val (ForLoop i it num_iters $ catMaybes maybe_loop_vars) body' where seType (Var v) | v == i = Just $ Prim $ IntType it | otherwise = ST.lookupType v vtable seType (Constant v) = Just $ Prim $ primValueType v consumed_in_body = consumedInBody body vtable' = ST.fromScope (scopeOf form) <> vtable checkIfSimplifiable (p,arr) = simplifyIndexing vtable' seType arr (DimFix (Var i) : fullSlice (paramType p) []) $ paramName p `S.member` consumed_in_body -- We only want this simplification it the result does not refer -- to 'i' at all, or does not contain accesses. onLoopVar (p,arr) Nothing = return (Just (p,arr), mempty) onLoopVar (p,arr) (Just m) = do (x,x_stms) <- collectStms m case x of IndexResult cs arr' slice | all (not . (i `S.member`) . freeInStm) x_stms, DimFix (Var j) : slice' <- slice, j == i, not $ i `S.member` freeIn slice -> do mapM_ addStm x_stms w <- arraySize 0 <$> lookupType arr' for_in_partial <- certifying cs $ letExp "for_in_partial" $ BasicOp $ Index arr' $ DimSlice (intConst Int32 0) w (intConst Int32 1) : slice' return (Just (p, for_in_partial), mempty) SubExpResult cs se | all (safeExp . stmExp) x_stms -> do x_stms' <- collectStms_ $ certifying cs $ do mapM_ addStm x_stms letBindNames'_ [paramName p] $ BasicOp $ SubExp se return (Nothing, x_stms') _ -> return (Just (p,arr), mempty) simplifyLoopVariables _ _ = cannotSimplify simplifKnownIterationLoop :: MonadBinder m => TopDownRule m simplifKnownIterationLoop _ (Let pat _ (DoLoop ctx val (ForLoop i it (Constant iters) loop_vars) body)) | zeroIsh iters = do let bindResult p r = letBindNames' [patElemName p] $ BasicOp $ SubExp r zipWithM_ bindResult (patternContextElements pat) (map snd ctx) zipWithM_ bindResult (patternValueElements pat) (map snd val) | oneIsh iters = do forM_ (ctx++val) $ \(mergevar, mergeinit) -> letBindNames' [paramName mergevar] $ BasicOp $ SubExp mergeinit letBindNames'_ [i] $ BasicOp $ SubExp $ intConst it 0 forM_ loop_vars $ \(p,arr) -> letBindNames'_ [paramName p] $ BasicOp $ Index arr $ DimFix (intConst Int32 0) : fullSlice (paramType p) [] (loop_body_ctx, loop_body_val) <- splitAt (length ctx) <$> (mapM asVar =<< bodyBind body) let subst = M.fromList $ zip (map (paramName . fst) ctx) loop_body_ctx ctx_params = substituteNames subst $ map fst ctx val_params = substituteNames subst $ map fst val res_context = loopResultContext ctx_params val_params forM_ (zip (patternContextElements pat) res_context) $ \(pat_elem, p) -> letBind_ (Pattern [] [pat_elem]) $ BasicOp $ SubExp $ Var $ paramName p forM_ (zip (patternValueElements pat) loop_body_val) $ \(pat_elem, v) -> letBind_ (Pattern [] [pat_elem]) $ BasicOp $ SubExp $ Var v where asVar (Var v) = return v asVar (Constant v) = letExp "named" $ BasicOp $ SubExp $ Constant v simplifKnownIterationLoop _ _ = cannotSimplify simplifyRearrange :: MonadBinder m => TopDownRule m -- Handle identity permutation. simplifyRearrange _ (Let pat _ (BasicOp (Rearrange perm v))) | sort perm == perm = letBind_ pat $ BasicOp $ SubExp $ Var v simplifyRearrange vtable (Let pat (StmAux cs _) (BasicOp (Rearrange perm v))) | Just (BasicOp (Rearrange perm2 e), v_cs) <- ST.lookupExp v vtable = -- Rearranging a rearranging: compose the permutations. certifying (cs<>v_cs) $ letBind_ pat $ BasicOp $ Rearrange (perm `rearrangeCompose` perm2) e simplifyRearrange vtable (Let pat (StmAux cs _) (BasicOp (Rearrange perm v))) | Just (BasicOp (Rotate offsets v2), v_cs) <- ST.lookupExp v vtable, Just (BasicOp (Rearrange perm3 v3), v2_cs) <- ST.lookupExp v2 vtable = do let offsets' = rearrangeShape (rearrangeInverse perm3) offsets rearrange_rotate <- letExp "rearrange_rotate" $ BasicOp $ Rotate offsets' v3 certifying (cs<>v_cs<>v2_cs) $ letBind_ pat $ BasicOp $ Rearrange (perm `rearrangeCompose` perm3) rearrange_rotate simplifyRearrange vtable (Let pat (StmAux cs1 _) (BasicOp (Rearrange perm1 v1))) | Just (to_drop, to_take, cs2, 0, v2) <- isDropTake v1 vtable, Just (BasicOp (Rearrange perm3 v3), v2_cs) <- ST.lookupExp v2 vtable, dim1:_ <- perm1, perm1 == rearrangeInverse perm3 = do to_drop' <- letSubExp "drop" =<< toExp (asInt32PrimExp to_drop) to_take' <- letSubExp "take" =<< toExp (asInt32PrimExp to_take) [_, v] <- certifying (cs2<>cs1) $ letTupExp' "simplify_rearrange" $ BasicOp $ Split dim1 [to_drop', to_take'] v3 certifying v2_cs $ letBind_ pat $ BasicOp $ SubExp v -- Rearranging a replicate where the outer dimension is left untouched. simplifyRearrange vtable (Let pat (StmAux cs _) (BasicOp (Rearrange perm v1))) | Just (BasicOp (Replicate dims (Var v2)), v1_cs) <- ST.lookupExp v1 vtable, num_dims <- shapeRank dims, (rep_perm, rest_perm) <- splitAt num_dims perm, not $ null rest_perm, rep_perm == [0..length rep_perm-1] = certifying (cs<>v1_cs) $ do v <- letSubExp "rearrange_replicate" $ BasicOp $ Rearrange (map (subtract num_dims) rest_perm) v2 letBind_ pat $ BasicOp $ Replicate dims v simplifyRearrange _ _ = cannotSimplify isDropTake :: VName -> ST.SymbolTable lore -> Maybe (PrimExp VName, PrimExp VName, Certificates, Int, VName) isDropTake v vtable = do Let pat (StmAux cs _) (BasicOp (Split dim splits v')) <- ST.entryStm =<< ST.lookup v vtable i <- elemIndex v $ patternValueNames pat return (offs $ take i splits, offs $ take 1 $ drop i splits, cs, dim, v') where offs = sum . map (primExpFromSubExp int32) simplifyRotate :: MonadBinder m => TopDownRule m -- A zero-rotation is identity. simplifyRotate _ (Let pat _ (BasicOp (Rotate offsets v))) | all isCt0 offsets = letBind_ pat $ BasicOp $ SubExp $ Var v simplifyRotate vtable (Let pat (StmAux cs _) (BasicOp (Rotate offsets v))) | Just (BasicOp (Rearrange perm v2), v_cs) <- ST.lookupExp v vtable, Just (BasicOp (Rotate offsets2 v3), v2_cs) <- ST.lookupExp v2 vtable = do let offsets2' = rearrangeShape (rearrangeInverse perm) offsets2 addOffsets x y = letSubExp "summed_offset" $ BasicOp $ BinOp (Add Int32) x y offsets' <- zipWithM addOffsets offsets offsets2' rotate_rearrange <- certifying cs $ letExp "rotate_rearrange" $ BasicOp $ Rearrange perm v3 certifying (v_cs <> v2_cs) $ letBind_ pat $ BasicOp $ Rotate offsets' rotate_rearrange simplifyRotate _ _ = cannotSimplify simplifyReplicate :: MonadBinder m => TopDownRule m simplifyReplicate _ (Let pat _ (BasicOp (Replicate (Shape []) se@Constant{}))) = letBind_ pat $ BasicOp $ SubExp se simplifyReplicate _ (Let pat _ (BasicOp (Replicate (Shape []) (Var v)))) = do v_t <- lookupType v letBind_ pat $ BasicOp $ if primType v_t then SubExp $ Var v else Copy v simplifyReplicate vtable (Let pat _ (BasicOp (Replicate shape (Var v)))) | Just (BasicOp (Replicate shape2 se), cs) <- ST.lookupExp v vtable = certifying cs $ letBind_ pat $ BasicOp $ Replicate (shape<>shape2) se simplifyReplicate _ _ = cannotSimplify -- | Turn array literals with identical elements into replicates. arrayLitToReplicate :: MonadBinder m => TopDownRule m arrayLitToReplicate _ (Let pat _ (BasicOp (ArrayLit (se:ses) _))) | all (==se) ses = let n = constant (genericLength ses + 1 :: Int32) in letBind_ pat $ BasicOp $ Replicate (Shape [n]) se arrayLitToReplicate _ _ = cannotSimplify simplifyCmpOp :: LetTopDownRule lore u simplifyCmpOp _ _ (CmpOp cmp e1 e2) | e1 == e2 = constRes $ BoolValue $ case cmp of CmpEq{} -> True CmpSlt{} -> False CmpUlt{} -> False CmpSle{} -> True CmpUle{} -> True FCmpLt{} -> False FCmpLe{} -> True simplifyCmpOp _ _ (CmpOp cmp (Constant v1) (Constant v2)) = constRes =<< BoolValue <$> doCmpOp cmp v1 v2 simplifyCmpOp _ _ _ = Nothing simplifyBinOp :: LetTopDownRule lore u simplifyBinOp _ _ (BinOp op (Constant v1) (Constant v2)) | Just res <- doBinOp op v1 v2 = constRes res simplifyBinOp _ _ (BinOp Add{} e1 e2) | isCt0 e1 = subExpRes e2 | isCt0 e2 = subExpRes e1 simplifyBinOp _ _ (BinOp FAdd{} e1 e2) | isCt0 e1 = subExpRes e2 | isCt0 e2 = subExpRes e1 simplifyBinOp _ _ (BinOp Sub{} e1 e2) | isCt0 e2 = subExpRes e1 simplifyBinOp _ _ (BinOp FSub{} e1 e2) | isCt0 e2 = subExpRes e1 simplifyBinOp _ _ (BinOp Mul{} e1 e2) | isCt0 e1 = subExpRes e1 | isCt0 e2 = subExpRes e2 | isCt1 e1 = subExpRes e2 | isCt1 e2 = subExpRes e1 simplifyBinOp _ _ (BinOp FMul{} e1 e2) | isCt0 e1 = subExpRes e1 | isCt0 e2 = subExpRes e2 | isCt1 e1 = subExpRes e2 | isCt1 e2 = subExpRes e1 simplifyBinOp look _ (BinOp (SMod t) e1 e2) | isCt1 e2 = constRes $ IntValue $ intValue t (0 :: Int) | e1 == e2 = constRes $ IntValue $ intValue t (0 :: Int) | Var v1 <- e1, Just (BasicOp (BinOp SMod{} _ e4), v1_cs) <- look v1, e4 == e2 = Just (SubExp e1, v1_cs) simplifyBinOp _ _ (BinOp SDiv{} e1 e2) | isCt0 e1 = subExpRes e1 | isCt1 e2 = subExpRes e1 | isCt0 e2 = Nothing simplifyBinOp _ _ (BinOp FDiv{} e1 e2) | isCt0 e1 = subExpRes e1 | isCt1 e2 = subExpRes e1 | isCt0 e2 = Nothing simplifyBinOp _ _ (BinOp (SRem t) e1 e2) | isCt1 e2 = constRes $ IntValue $ intValue t (0 :: Int) | e1 == e2 = constRes $ IntValue $ intValue t (1 :: Int) simplifyBinOp _ _ (BinOp SQuot{} e1 e2) | isCt1 e2 = subExpRes e1 | isCt0 e2 = Nothing simplifyBinOp _ _ (BinOp (FPow t) e1 e2) | isCt0 e2 = subExpRes $ floatConst t 1 | isCt0 e1 || isCt1 e1 || isCt1 e2 = subExpRes e1 simplifyBinOp _ _ (BinOp (Shl t) e1 e2) | isCt0 e2 = subExpRes e1 | isCt0 e1 = subExpRes $ intConst t 0 simplifyBinOp _ _ (BinOp AShr{} e1 e2) | isCt0 e2 = subExpRes e1 simplifyBinOp _ _ (BinOp (And t) e1 e2) | isCt0 e1 = subExpRes $ intConst t 0 | isCt0 e2 = subExpRes $ intConst t 0 | e1 == e2 = subExpRes e1 simplifyBinOp _ _ (BinOp Or{} e1 e2) | isCt0 e1 = subExpRes e2 | isCt0 e2 = subExpRes e1 | e1 == e2 = subExpRes e1 simplifyBinOp _ _ (BinOp (Xor t) e1 e2) | isCt0 e1 = subExpRes e2 | isCt0 e2 = subExpRes e1 | e1 == e2 = subExpRes $ intConst t 0 simplifyBinOp defOf _ (BinOp LogAnd e1 e2) | isCt0 e1 = constRes $ BoolValue False | isCt0 e2 = constRes $ BoolValue False | isCt1 e1 = subExpRes e2 | isCt1 e2 = subExpRes e1 | Var v <- e1, Just (BasicOp (UnOp Not e1'), v_cs) <- defOf v, e1' == e2 = Just (SubExp $ Constant $ BoolValue False, v_cs) | Var v <- e2, Just (BasicOp (UnOp Not e2'), v_cs) <- defOf v, e2' == e1 = Just (SubExp $ Constant $ BoolValue False, v_cs) simplifyBinOp defOf _ (BinOp LogOr e1 e2) | isCt0 e1 = subExpRes e2 | isCt0 e2 = subExpRes e1 | isCt1 e1 = constRes $ BoolValue True | isCt1 e2 = constRes $ BoolValue True | Var v <- e1, Just (BasicOp (UnOp Not e1'), v_cs) <- defOf v, e1' == e2 = Just (SubExp $ Constant $ BoolValue True, v_cs) | Var v <- e2, Just (BasicOp (UnOp Not e2'), v_cs) <- defOf v, e2' == e1 = Just (SubExp $ Constant $ BoolValue True, v_cs) simplifyBinOp defOf _ (BinOp (SMax it) e1 e2) | e1 == e2 = subExpRes e1 | Var v1 <- e1, Just (BasicOp (BinOp (SMax _) e1_1 e1_2), v1_cs) <- defOf v1, e1_1 == e2 = Just (BinOp (SMax it) e1_2 e2, v1_cs) | Var v1 <- e1, Just (BasicOp (BinOp (SMax _) e1_1 e1_2), v1_cs) <- defOf v1, e1_2 == e2 = Just (BinOp (SMax it) e1_1 e2, v1_cs) | Var v2 <- e2, Just (BasicOp (BinOp (SMax _) e2_1 e2_2), v2_cs) <- defOf v2, e2_1 == e1 = Just (BinOp (SMax it) e2_2 e1, v2_cs) | Var v2 <- e2, Just (BasicOp (BinOp (SMax _) e2_1 e2_2), v2_cs) <- defOf v2, e2_2 == e1 = Just (BinOp (SMax it) e2_1 e1, v2_cs) simplifyBinOp _ _ _ = Nothing constRes :: PrimValue -> Maybe (BasicOp lore, Certificates) constRes = Just . (,mempty) . SubExp . Constant subExpRes :: SubExp -> Maybe (BasicOp lore, Certificates) subExpRes = Just . (,mempty) . SubExp simplifyUnOp :: LetTopDownRule lore u simplifyUnOp _ _ (UnOp op (Constant v)) = constRes =<< doUnOp op v simplifyUnOp defOf _ (UnOp Not (Var v)) | Just (BasicOp (UnOp Not v2), v_cs) <- defOf v = Just (SubExp v2, v_cs) simplifyUnOp _ _ _ = Nothing simplifyConvOp :: LetTopDownRule lore u simplifyConvOp _ _ (ConvOp op (Constant v)) = constRes =<< doConvOp op v simplifyConvOp _ _ (ConvOp op se) | (from, to) <- convOpType op, from == to = subExpRes se simplifyConvOp lookupVar _ (ConvOp (SExt t2 t1) (Var v)) | Just (BasicOp (ConvOp (SExt t3 _) se), v_cs) <- lookupVar v, t2 >= t3 = Just (ConvOp (SExt t3 t1) se, v_cs) simplifyConvOp lookupVar _ (ConvOp (ZExt t2 t1) (Var v)) | Just (BasicOp (ConvOp (ZExt t3 _) se), v_cs) <- lookupVar v, t2 >= t3 = Just (ConvOp (ZExt t3 t1) se, v_cs) simplifyConvOp lookupVar _ (ConvOp (SIToFP t2 t1) (Var v)) | Just (BasicOp (ConvOp (SExt t3 _) se), v_cs) <- lookupVar v, t2 >= t3 = Just (ConvOp (SIToFP t3 t1) se, v_cs) simplifyConvOp lookupVar _ (ConvOp (UIToFP t2 t1) (Var v)) | Just (BasicOp (ConvOp (ZExt t3 _) se), v_cs) <- lookupVar v, t2 >= t3 = Just (ConvOp (UIToFP t3 t1) se, v_cs) simplifyConvOp lookupVar _ (ConvOp (FPConv t2 t1) (Var v)) | Just (BasicOp (ConvOp (FPConv t3 _) se), v_cs) <- lookupVar v, t2 >= t3 = Just (ConvOp (FPConv t3 t1) se, v_cs) simplifyConvOp _ _ _ = Nothing -- If expression is true then just replace assertion. simplifyAssert :: LetTopDownRule lore u simplifyAssert _ _ (Assert (Constant (BoolValue True)) _ _) = constRes Checked simplifyAssert _ _ _ = Nothing constantFoldPrimFun :: MonadBinder m => TopDownRule m constantFoldPrimFun _ (Let pat (StmAux cs _) (Apply fname args _ _)) | Just args' <- mapM (isConst . fst) args, Just (_, _, fun) <- M.lookup (nameToString fname) primFuns, Just result <- fun args' = certifying cs $ letBind_ pat $ BasicOp $ SubExp $ Constant result where isConst (Constant v) = Just v isConst _ = Nothing constantFoldPrimFun _ _ = cannotSimplify simplifyIndex :: MonadBinder m => BottomUpRule m simplifyIndex (vtable, used) (Let pat@(Pattern [] [pe]) (StmAux cs _) (BasicOp (Index idd inds))) | Just m <- simplifyIndexing vtable seType idd inds consumed = do res <- m case res of SubExpResult cs' se -> certifying (cs<>cs') $ letBindNames'_ (patternNames pat) $ BasicOp $ SubExp se IndexResult extra_cs idd' inds' -> certifying (cs<>extra_cs) $ letBindNames'_ (patternNames pat) $ BasicOp $ Index idd' inds' where consumed = patElemName pe `UT.isConsumed` used seType (Var v) = ST.lookupType v vtable seType (Constant v) = Just $ Prim $ primValueType v simplifyIndex _ _ = cannotSimplify data IndexResult = IndexResult Certificates VName (Slice SubExp) | SubExpResult Certificates SubExp simplifyIndexing :: MonadBinder m => ST.SymbolTable (Lore m) -> TypeLookup -> VName -> Slice SubExp -> Bool -> Maybe (m IndexResult) simplifyIndexing vtable seType idd inds consuming = case defOf idd of _ | Just t <- seType (Var idd), inds == fullSlice t [] -> Just $ pure $ SubExpResult mempty $ Var idd | Just inds' <- sliceIndices inds, Just (e, cs) <- ST.index idd inds' vtable -> Just $ SubExpResult cs <$> (letSubExp "index_primexp" =<< toExp e) Nothing -> Nothing Just (SubExp (Var v), cs) -> Just $ pure $ IndexResult cs v inds Just (Iota _ x s to_it, cs) | [DimFix ii] <- inds, Just (Prim (IntType from_it)) <- seType ii -> Just $ fmap (SubExpResult cs) $ letSubExp "index_iota" <=< toExp $ ConvOpExp (SExt from_it to_it) (primExpFromSubExp (IntType from_it) ii) * primExpFromSubExp (IntType to_it) s + primExpFromSubExp (IntType to_it) x | [DimSlice i_offset i_n i_stride] <- inds -> Just $ do i_offset' <- asIntS to_it i_offset i_stride' <- asIntS to_it i_stride i_offset'' <- letSubExp "iota_offset" $ BasicOp $ BinOp (Add Int32) x i_offset' i_stride'' <- letSubExp "iota_offset" $ BasicOp $ BinOp (Mul Int32) s i_stride' fmap (SubExpResult cs) $ letSubExp "slice_iota" $ BasicOp $ Iota i_n i_offset'' i_stride'' to_it Just (Rotate offsets a, cs) -> Just $ do dims <- arrayDims <$> lookupType a let adjustI i o d = do i_p_o <- letSubExp "i_p_o" $ BasicOp $ BinOp (Add Int32) i o letSubExp "rot_i" (BasicOp $ BinOp (SMod Int32) i_p_o d) adjust (DimFix i, o, d) = DimFix <$> adjustI i o d adjust (DimSlice i n s, o, d) = DimSlice <$> adjustI i o d <*> pure n <*> pure s IndexResult cs a <$> mapM adjust (zip3 inds offsets dims) Just (Index aa ais, cs) -> Just $ fmap (IndexResult cs aa) $ do let adjust (DimFix j:js') is' = (DimFix j:) <$> adjust js' is' adjust (DimSlice j _ s:js') (DimFix i:is') = do i_t_s <- letSubExp "j_t_s" $ BasicOp $ BinOp (Mul Int32) i s j_p_i_t_s <- letSubExp "j_p_i_t_s" $ BasicOp $ BinOp (Add Int32) j i_t_s (DimFix j_p_i_t_s:) <$> adjust js' is' adjust (DimSlice j _ s0:js') (DimSlice i n s1:is') = do s0_t_i <- letSubExp "s0_t_i" $ BasicOp $ BinOp (Mul Int32) s0 i j_p_s0_t_i <- letSubExp "j_p_s0_t_i" $ BasicOp $ BinOp (Add Int32) j s0_t_i (DimSlice j_p_s0_t_i n s1:) <$> adjust js' is' adjust _ _ = return [] adjust ais inds Just (Replicate (Shape [_]) (Var vv), cs) | [DimFix{}] <- inds, not consuming -> Just $ pure $ SubExpResult cs $ Var vv | DimFix{}:is' <- inds, not consuming -> Just $ pure $ IndexResult cs vv is' Just (Replicate (Shape [_]) val@(Constant _), cs) | [DimFix{}] <- inds, not consuming -> Just $ pure $ SubExpResult cs val Just (Replicate (Shape ds) v, cs) | (ds_inds, rest_inds) <- splitAt (length ds) inds, (ds', ds_inds') <- unzip $ mapMaybe index ds_inds, ds' /= ds -> Just $ do arr <- letExp "smaller_replicate" $ BasicOp $ Replicate (Shape ds') v return $ IndexResult cs arr $ ds_inds' ++ rest_inds where index DimFix{} = Nothing index (DimSlice _ n s) = Just (n, DimSlice (constant (0::Int32)) n s) Just (Rearrange perm src, cs) | rearrangeReach perm <= length (takeWhile isIndex inds) -> let inds' = rearrangeShape (rearrangeInverse perm) inds in Just $ pure $ IndexResult cs src inds' where isIndex DimFix{} = True isIndex _ = False Just (Copy src, cs) | Just dims <- arrayDims <$> seType (Var src), length inds == length dims, not consuming -> Just $ pure $ IndexResult cs src inds Just (Reshape newshape src, cs) | Just newdims <- shapeCoercion newshape, Just olddims <- arrayDims <$> seType (Var src), changed_dims <- zipWith (/=) newdims olddims, not $ or $ drop (length inds) changed_dims -> Just $ pure $ IndexResult cs src inds | Just newdims <- shapeCoercion newshape, Just olddims <- arrayDims <$> seType (Var src), length newshape == length inds, length olddims == length newdims -> Just $ pure $ IndexResult cs src inds Just (Reshape [_] v2, cs) | Just [_] <- arrayDims <$> seType (Var v2) -> Just $ pure $ IndexResult cs v2 inds Just (Concat d x xs _, cs) | Just (ibef, DimFix i, iaft) <- focusNth d inds -> Just $ do Prim res_t <- stripArray (length inds) <$> lookupType x x_len <- arraySize d <$> lookupType x xs_lens <- mapM (fmap (arraySize d) . lookupType) xs let add n m = do added <- letSubExp "index_concat_add" $ BasicOp $ BinOp (Add Int32) n m return (added, n) (_, starts) <- mapAccumLM add x_len xs_lens let xs_and_starts = reverse $ zip xs starts let mkBranch [] = letSubExp "index_concat" $ BasicOp $ Index x $ ibef ++ DimFix i : iaft mkBranch ((x', start):xs_and_starts') = do cmp <- letSubExp "index_concat_cmp" $ BasicOp $ CmpOp (CmpSle Int32) start i (thisres, thisbnds) <- collectStms $ do i' <- letSubExp "index_concat_i" $ BasicOp $ BinOp (Sub Int32) i start letSubExp "index_concat" $ BasicOp $ Index x' $ ibef ++ DimFix i' : iaft thisbody <- mkBodyM thisbnds [thisres] (altres, altbnds) <- collectStms $ mkBranch xs_and_starts' altbody <- mkBodyM altbnds [altres] letSubExp "index_concat_branch" $ If cmp thisbody altbody $ IfAttr [primBodyType res_t] IfNormal SubExpResult cs <$> mkBranch xs_and_starts Just (ArrayLit ses _, cs) | DimFix (Constant (IntValue (Int32Value i))) : inds' <- inds, Just se <- maybeNth i ses -> case inds' of [] -> Just $ pure $ SubExpResult cs se _ | Var v2 <- se -> Just $ pure $ IndexResult cs v2 inds' _ -> Nothing -- Indexing single-element arrays. We know the index must be 0. _ | Just t <- seType $ Var idd, isCt1 $ arraySize 0 t, DimFix i : inds' <- inds, not $ isCt0 i -> Just $ pure $ IndexResult mempty idd $ DimFix (constant (0::Int32)) : inds' _ -> case ST.entryStm =<< ST.lookup idd vtable of Just (Let split_pat (StmAux cs2 _) (BasicOp (Split 0 ns idd2))) | DimFix first_index : rest_indices <- inds -> Just $ do -- Figure out the extra offset that we should add to the first index. let plus = eBinOp (Add Int32) esum [] = return $ BasicOp $ SubExp $ constant (0 :: Int32) esum (x:xs) = foldl plus x xs patElem_and_offset <- zip (patternValueElements split_pat) <$> mapM esum (inits $ map eSubExp ns) case find ((==idd) . patElemName . fst) patElem_and_offset of Nothing -> fail "simplifyIndexing: could not find pattern element." Just (_, offset_e) -> do offset <- letSubExp "offset" offset_e offset_index <- letSubExp "offset_index" $ BasicOp $ BinOp (Add Int32) first_index offset return $ IndexResult cs2 idd2 $ DimFix offset_index:rest_indices _ -> Nothing where defOf v = do (BasicOp op, def_cs) <- ST.lookupExp v vtable return (op, def_cs) simplifyIndexIntoReshape :: MonadBinder m => TopDownRule m simplifyIndexIntoReshape vtable (Let pat (StmAux cs _) (BasicOp (Index idd slice))) | Just inds <- sliceIndices slice, Just (BasicOp (Reshape newshape idd2), idd_cs) <- ST.lookupExp idd vtable, length newshape == length inds = case shapeCoercion newshape of Just _ -> certifying (cs<>idd_cs) $ letBind_ pat $ BasicOp $ Index idd2 slice Nothing -> do -- Linearise indices and map to old index space. oldshape <- arrayDims <$> lookupType idd2 let new_inds = reshapeIndex (map (primExpFromSubExp int32) oldshape) (map (primExpFromSubExp int32) $ newDims newshape) (map (primExpFromSubExp int32) inds) new_inds' <- mapM (letSubExp "new_index" <=< toExp . asInt32PrimExp) new_inds certifying (cs<>idd_cs) $ letBind_ pat $ BasicOp $ Index idd2 $ map DimFix new_inds' simplifyIndexIntoReshape _ _ = cannotSimplify removeEmptySplits :: MonadBinder m => TopDownRule m removeEmptySplits _ (Let pat (StmAux cs _) (BasicOp (Split i ns arr))) | (pointless,sane) <- partition (isCt0 . snd) $ zip (patternValueElements pat) ns, not (null pointless) = do rt <- rowType <$> lookupType arr certifying cs $ letBind_ (Pattern [] $ map fst sane) $ BasicOp $ Split i (map snd sane) arr forM_ pointless $ \(patElem,_) -> letBindNames' [patElemName patElem] $ BasicOp $ ArrayLit [] rt removeEmptySplits _ _ = cannotSimplify removeSingletonSplits :: MonadBinder m => TopDownRule m removeSingletonSplits _ (Let pat _ (BasicOp (Split i [n] arr))) = do size <- arraySize i <$> lookupType arr if size == n then letBind_ pat $ BasicOp $ SubExp $ Var arr else cannotSimplify removeSingletonSplits _ _ = cannotSimplify simplifyConcat :: MonadBinder m => BottomUpRule m -- concat@1(transpose(x),transpose(y)) == transpose(concat@0(x,y)) simplifyConcat (vtable, _) (Let pat _ (BasicOp (Concat i x xs new_d))) | Just r <- arrayRank <$> ST.lookupType x vtable, let perm = [i] ++ [0..i-1] ++ [i+1..r-1], Just (x',x_cs) <- transposedBy perm x, Just (xs',xs_cs) <- unzip <$> mapM (transposedBy perm) xs = do concat_rearrange <- certifying (x_cs<>mconcat xs_cs) $ letExp "concat_rearrange" $ BasicOp $ Concat 0 x' xs' new_d letBind_ pat $ BasicOp $ Rearrange perm concat_rearrange where transposedBy perm1 v = case ST.lookupExp v vtable of Just (BasicOp (Rearrange perm2 v'), vcs) | perm1 == perm2 -> Just (v', vcs) _ -> Nothing -- concat of a split array is identity. simplifyConcat (vtable, used) (Let pat (StmAux cs _) (BasicOp (Concat i x xs new_d))) | Just (Let split_pat (StmAux split_cs _) (BasicOp (Split split_i _ split_arr))) <- ST.lookupStm x vtable, i == split_i, x:xs == patternNames split_pat = do split_arr_t <- lookupType split_arr let reshape = map DimCoercion $ arrayDims $ setDimSize i split_arr_t new_d split_arr' <- certifying (cs<>split_cs) $ letExp "concat_reshape" $ BasicOp $ Reshape reshape split_arr if any (`UT.isConsumed` used) $ patternNames pat then letBind_ pat $ BasicOp $ Copy split_arr' else letBind_ pat $ BasicOp $ SubExp $ Var split_arr' simplifyConcat _ _ = cannotSimplify evaluateBranch :: MonadBinder m => TopDownRule m evaluateBranch _ (Let pat _ (If e1 tb fb (IfAttr t ifsort))) | Just branch <- checkBranch, ifsort /= IfFallback || isCt1 e1 = do let ses = bodyResult branch mapM_ addStm $ bodyStms branch ctx <- subExpShapeContext (bodyTypeValues t) ses let ses' = ctx ++ ses sequence_ [ letBind (Pattern [] [p]) $ BasicOp $ SubExp se | (p,se) <- zip (patternElements pat) ses'] where checkBranch | isCt1 e1 = Just tb | isCt0 e1 = Just fb | otherwise = Nothing evaluateBranch _ _ = cannotSimplify -- IMPROVE: This rule can be generalised to work in more cases, -- especially when the branches have bindings, or return more than one -- value. simplifyBoolBranch :: MonadBinder m => TopDownRule m -- if c then True else v == c || v simplifyBoolBranch _ (Let pat _ (If cond (Body _ [] [Constant (BoolValue True)]) (Body _ [] [se]) (IfAttr ts _))) | [Prim Bool] <- bodyTypeValues ts = letBind_ pat $ BasicOp $ BinOp LogOr cond se -- When seType(x)==bool, if c then x else y == (c && x) || (!c && y) simplifyBoolBranch _ (Let pat _ (If cond tb fb (IfAttr ts _))) | Body _ tstms [tres] <- tb, Body _ fstms [fres] <- fb, all (safeExp . stmExp) $ tstms ++ fstms, all (==Prim Bool) $ bodyTypeValues ts = do mapM_ addStm tstms mapM_ addStm fstms e <- eBinOp LogOr (pure $ BasicOp $ BinOp LogAnd cond tres) (eBinOp LogAnd (pure $ BasicOp $ UnOp Not cond) (pure $ BasicOp $ SubExp fres)) letBind_ pat e simplifyBoolBranch _ _ = cannotSimplify simplifyFallbackBranch :: MonadBinder m => TopDownRule m simplifyFallbackBranch _ (Let pat _ (If _ tbranch _ (IfAttr _ IfFallback))) | null $ patternContextNames pat, all (safeExp . stmExp) $ bodyStms tbranch = do let ses = bodyResult tbranch mapM_ addStm $ bodyStms tbranch sequence_ [ letBind (Pattern [] [p]) $ BasicOp $ SubExp se | (p,se) <- zip (patternElements pat) ses] simplifyFallbackBranch _ _ = cannotSimplify -- | Move out results of a conditional expression whose computation is -- either invariant to the branches (only done for results in the -- context), or the same in both branches. hoistBranchInvariant :: MonadBinder m => TopDownRule m hoistBranchInvariant _ (Let pat _ (If cond tb fb (IfAttr ret ifsort))) = do let tses = bodyResult tb fses = bodyResult fb (hoistings, (pes, ts, res)) <- fmap (fmap unzip3 . partitionEithers) $ mapM branchInvariant $ zip3 (patternElements pat) (map Left [0..num_ctx-1] ++ map Right ret) (zip tses fses) let ctx_fixes = catMaybes hoistings (tses', fses') = unzip res tb' = tb { bodyResult = tses' } fb' = fb { bodyResult = fses' } ret' = foldr (uncurry fixExt) (rights ts) ctx_fixes (ctx_pes, val_pes) = splitFromEnd (length ret') pes if not $ null hoistings -- Was something hoisted? then do -- We may have to add some reshapes if we made the type -- less existential. tb'' <- reshapeBodyResults tb' $ map extTypeOf ret' fb'' <- reshapeBodyResults fb' $ map extTypeOf ret' letBind_ (Pattern ctx_pes val_pes) $ If cond tb'' fb'' (IfAttr ret' ifsort) else cannotSimplify where num_ctx = length $ patternContextElements pat bound_in_branches = S.fromList $ concatMap (patternNames . stmPattern) $ bodyStms tb ++ bodyStms fb mem_sizes = freeIn $ filter (isMem . patElemType) $ patternElements pat invariant Constant{} = True invariant (Var v) = not $ v `S.member` bound_in_branches isMem Mem{} = True isMem _ = False sizeOfMem v = v `S.member` mem_sizes branchInvariant (pe, t, (tse, fse)) -- Do both branches return the same value? | tse == fse = do letBind_ (Pattern [] [pe]) $ BasicOp $ SubExp tse hoisted pe t -- Do both branches return values that are free in the -- branch, and are we not the only pattern element? The -- latter is to avoid infinite application of this rule. | invariant tse, invariant fse, patternSize pat > 1, Prim _ <- patElemType pe, not $ sizeOfMem $ patElemName pe = do bt <- expTypesFromPattern $ Pattern [] [pe] letBind_ (Pattern [] [pe]) =<< (If cond <$> resultBodyM [tse] <*> resultBodyM [fse] <*> pure (IfAttr bt ifsort)) hoisted pe t | otherwise = return $ Right (pe, t, (tse,fse)) hoisted pe (Left i) = return $ Left $ Just (i, Var $ patElemName pe) hoisted _ Right{} = return $ Left Nothing reshapeBodyResults body rets = insertStmsM $ do ses <- bodyBind body let (ctx_ses, val_ses) = splitFromEnd (length rets) ses resultBodyM . (ctx_ses++) =<< zipWithM reshapeResult val_ses rets reshapeResult (Var v) (t@Array{}) = do v_t <- lookupType v let newshape = arrayDims $ removeExistentials t v_t if newshape /= arrayDims v_t then letSubExp "branch_ctx_reshaped" $ shapeCoerce newshape v else return $ Var v reshapeResult se _ = return se hoistBranchInvariant _ _ = cannotSimplify simplifyScalExp :: MonadBinder m => TopDownRule m simplifyScalExp vtable (Let pat _ e) = do res <- SE.toScalExp (`ST.lookupScalExp` vtable) e case res of -- If the sufficient condition is 'True', then it statically succeeds. Just se | not $ isConstant se, Just ses <- lth0s se, all ((<size_bound) . SE.scalExpSize) ses, Right True <- and <$> mapM truish ses -> letBind_ pat $ BasicOp $ SubExp $ Constant $ BoolValue True | isNothing $ valOrVar se, SE.scalExpSize se < size_bound, Just se' <- valOrVar $ AS.simplify se ranges -> letBind_ pat $ BasicOp $ SubExp se' _ -> cannotSimplify where ranges = ST.rangesRep vtable size_bound = 30 -- don't touch scalexps bigger than this. lth0s se@(SE.RelExp SE.LTH0 _) = Just [se] lth0s (SE.RelExp SE.LEQ0 x) = Just [SE.RelExp SE.LTH0 $ x - 1] lth0s (SE.SLogAnd x y) = (++) <$> lth0s x <*> lth0s y lth0s _ = Nothing isConstant SE.Val{} = True isConstant _ = False valOrVar (SE.Val v) = Just $ Constant v valOrVar (SE.Id v _) = Just $ Var v valOrVar _ = Nothing truish se = (SE.Val (BoolValue True)==) . mkDisj <$> AS.mkSuffConds se ranges mkDisj [] = SE.Val $ BoolValue False mkDisj (x:xs) = foldl SE.SLogOr (mkConj x) $ map mkConj xs mkConj [] = SE.Val $ BoolValue True mkConj (x:xs) = foldl SE.SLogAnd x xs simplifyIdentityReshape :: LetTopDownRule lore u simplifyIdentityReshape _ seType (Reshape newshape v) | Just t <- seType $ Var v, newDims newshape == arrayDims t = -- No-op reshape. subExpRes $ Var v simplifyIdentityReshape _ _ _ = Nothing simplifyReshapeReshape :: LetTopDownRule lore u simplifyReshapeReshape defOf _ (Reshape newshape v) | Just (BasicOp (Reshape oldshape v2), v_cs) <- defOf v = Just (Reshape (fuseReshape oldshape newshape) v2, v_cs) simplifyReshapeReshape _ _ _ = Nothing simplifyReshapeScratch :: LetTopDownRule lore u simplifyReshapeScratch defOf _ (Reshape newshape v) | Just (BasicOp (Scratch bt _), v_cs) <- defOf v = Just (Scratch bt $ newDims newshape, v_cs) simplifyReshapeScratch _ _ _ = Nothing simplifyReshapeReplicate :: LetTopDownRule lore u simplifyReshapeReplicate defOf seType (Reshape newshape v) | Just (BasicOp (Replicate _ se), v_cs) <- defOf v, Just oldshape <- arrayShape <$> seType se, shapeDims oldshape `isSuffixOf` newDims newshape = let new = take (length newshape - shapeRank oldshape) $ newDims newshape in Just (Replicate (Shape new) se, v_cs) simplifyReshapeReplicate _ _ _ = Nothing improveReshape :: LetTopDownRule lore u improveReshape _ seType (Reshape newshape v) | Just t <- seType $ Var v, newshape' <- informReshape (arrayDims t) newshape, newshape' /= newshape = Just (Reshape newshape' v, mempty) improveReshape _ _ _ = Nothing -- | If we are copying a scratch array (possibly indirectly), just turn it into a scratch by -- itself. copyScratchToScratch :: LetTopDownRule lore u copyScratchToScratch defOf seType (Copy src) = do t <- seType $ Var src if isActuallyScratch src then Just (Scratch (elemType t) (arrayDims t), mempty) else Nothing where isActuallyScratch v = case asBasicOp . fst =<< defOf v of Just Scratch{} -> True Just (Rearrange _ v') -> isActuallyScratch v' Just (Reshape _ v') -> isActuallyScratch v' _ -> False copyScratchToScratch _ _ _ = Nothing removeIdentityInPlace :: MonadBinder m => TopDownRule m removeIdentityInPlace vtable (Let (Pattern [] [d]) _ e) | BindInPlace dest destis <- patElemBindage d, arrayFrom e dest destis = letBind_ (Pattern [] [d { patElemBindage = BindVar}]) $ BasicOp $ SubExp $ Var dest where arrayFrom (BasicOp (Copy v)) dest destis | Just (e',_) <- ST.lookupExp v vtable = arrayFrom e' dest destis arrayFrom (BasicOp (Index src srcis)) dest destis = src == dest && destis == srcis arrayFrom _ _ _ = False removeIdentityInPlace _ _ = cannotSimplify -- | Turn in-place updates that replace an entire array into just -- array literals. removeFullInPlace :: MonadBinder m => TopDownRule m removeFullInPlace vtable (Let (Pattern [] [d]) _ e) | BindInPlace dest is <- patElemBindage d, Just dest_t <- ST.lookupType dest vtable, isFullSlice (arrayShape dest_t) is = do in_place_val <- letSubExp "in_place_val" e letBind_ (Pattern [] [d { patElemBindage = BindVar}]) $ BasicOp $ ArrayLit [in_place_val] $ rowType dest_t removeFullInPlace _ _ = cannotSimplify removeScratchValue :: MonadBinder m => TopDownRule m removeScratchValue _ (Let (Pattern [] [PatElem v (BindInPlace src _) _]) _ (BasicOp Scratch{})) = letBindNames'_ [v] $ BasicOp $ SubExp $ Var src removeScratchValue _ _ = cannotSimplify -- | Remove the return values of a branch, that are not actually used -- after a branch. Standard dead code removal can remove the branch -- if *none* of the return values are used, but this rule is more -- precise. removeDeadBranchResult :: MonadBinder m => BottomUpRule m removeDeadBranchResult (_, used) (Let pat _ (If e1 tb fb (IfAttr rettype ifsort))) | -- Only if there is no existential context... patternSize pat == length rettype, -- Figure out which of the names in 'pat' are used... patused <- map (`UT.used` used) $ patternNames pat, -- If they are not all used, then this rule applies. not (and patused) = -- Remove the parts of the branch-results that correspond to dead -- return value bindings. Note that this leaves dead code in the -- branch bodies, but that will be removed later. let tses = bodyResult tb fses = bodyResult fb pick :: [a] -> [a] pick = map snd . filter fst . zip patused tb' = tb { bodyResult = pick tses } fb' = fb { bodyResult = pick fses } pat' = pick $ patternElements pat rettype' = pick rettype in letBind_ (Pattern [] pat') $ If e1 tb' fb' $ IfAttr rettype' ifsort removeDeadBranchResult _ _ = cannotSimplify -- | If we are comparing X against the result of a branch of the form -- @if P then Y else Z@ then replace comparison with '(P && X == Y) || -- (!P && X == Z'). This may allow us to get rid of a branch, and the -- extra comparisons may be constant-folded out. Question: maybe we -- should have some more checks to ensure that we only do this if that -- is actually the case, such as if we will obtain at least one -- constant-to-constant comparison? simplifyBranchResultComparison :: MonadBinder m => TopDownRule m simplifyBranchResultComparison vtable (Let pat _ (BasicOp (CmpOp (CmpEq t) se1 se2))) | Just m <- simplifyWith se1 se2 = m | Just m <- simplifyWith se2 se1 = m where simplifyWith (Var v) x | Just bnd <- ST.entryStm =<< ST.lookup v vtable, If p tbranch fbranch _ <- stmExp bnd, Just (y, z) <- returns v (stmPattern bnd) tbranch fbranch, S.null $ freeIn y `S.intersection` boundInBody tbranch, S.null $ freeIn z `S.intersection` boundInBody fbranch = Just $ do eq_x_y <- letSubExp "eq_x_y" $ BasicOp $ CmpOp (CmpEq t) x y eq_x_z <- letSubExp "eq_x_z" $ BasicOp $ CmpOp (CmpEq t) x z p_and_eq_x_y <- letSubExp "p_and_eq_x_y" $ BasicOp $ BinOp LogAnd p eq_x_y not_p <- letSubExp "not_p" $ BasicOp $ UnOp Not p not_p_and_eq_x_z <- letSubExp "p_and_eq_x_y" $ BasicOp $ BinOp LogAnd not_p eq_x_z letBind_ pat $ BasicOp $ BinOp LogOr p_and_eq_x_y not_p_and_eq_x_z simplifyWith _ _ = Nothing returns v ifpat tbranch fbranch = fmap snd $ find ((==v) . patElemName . fst) $ zip (patternValueElements ifpat) $ zip (bodyResult tbranch) (bodyResult fbranch) simplifyBranchResultComparison _ _ = cannotSimplify -- Some helper functions isCt1 :: SubExp -> Bool isCt1 (Constant v) = oneIsh v isCt1 _ = False isCt0 :: SubExp -> Bool isCt0 (Constant v) = zeroIsh v isCt0 _ = False
ihc/futhark
src/Futhark/Optimise/Simplifier/Rules.hs
isc
53,885
0
26
15,149
18,598
9,037
9,561
-1
-1
{-# LANGUAGE GADTs #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE CPP #-} module Text.Regex.Applicative.Types where import Control.Applicative import Control.Monad ((<=<)) import Data.Filtrable (Filtrable (..)) import Data.Functor.Identity (Identity (..)) import Data.String #if !MIN_VERSION_base(4,11,0) import Data.Semigroup #endif newtype ThreadId = ThreadId Int -- | A thread either is a result or corresponds to a symbol in the regular -- expression, which is expected by that thread. data Thread s r = Thread { threadId_ :: ThreadId , _threadCont :: s -> [Thread s r] } | Accept r -- | Returns thread identifier. This will be 'Just' for ordinary threads and -- 'Nothing' for results. threadId :: Thread s r -> Maybe ThreadId threadId Thread { threadId_ = i } = Just i threadId _ = Nothing data Greediness = Greedy | NonGreedy deriving (Show, Read, Eq, Ord, Enum) -- | Type of regular expressions that recognize symbols of type @s@ and -- produce a result of type @a@. -- -- Regular expressions can be built using 'Functor', 'Applicative', -- 'Alternative', and 'Filtrable' instances in the following natural way: -- -- * @f@ '<$>' @ra@ matches iff @ra@ matches, and its return value is the result -- of applying @f@ to the return value of @ra@. -- -- * 'pure' @x@ matches the empty string (i.e. it does not consume any symbols), -- and its return value is @x@ -- -- * @rf@ '<*>' @ra@ matches a string iff it is a concatenation of two -- strings: one matched by @rf@ and the other matched by @ra@. The return value -- is @f a@, where @f@ and @a@ are the return values of @rf@ and @ra@ -- respectively. -- -- * @ra@ '<|>' @rb@ matches a string which is accepted by either @ra@ or @rb@. -- It is left-biased, so if both can match, the result of @ra@ is used. -- -- * 'empty' is a regular expression which does not match any string. -- -- * 'many' @ra@ matches concatenation of zero or more strings matched by @ra@ -- and returns the list of @ra@'s return values on those strings. -- -- * 'some' @ra@ matches concatenation of one or more strings matched by @ra@ -- and returns the list of @ra@'s return values on those strings. -- -- * 'catMaybes' @ram@ matches iff @ram@ matches and produces 'Just _'. -- -- * @ra@ '<>' @rb@ matches @ra@ followed by @rb@. The return value is @a <> b@, -- where @a@ and @b@ are the return values of @ra@ and @rb@ respectively. -- (See <https://github.com/feuerbach/regex-applicative/issues/37#issue-499781703> -- for an example usage.) -- -- * 'mempty' matches the empty string (i.e. it does not consume any symbols), -- and its return value is the 'mempty' value of type @a@. data RE s a where Eps :: RE s () Symbol :: ThreadId -> (s -> Maybe a) -> RE s a Alt :: RE s a -> RE s a -> RE s a App :: RE s (a -> b) -> RE s a -> RE s b Fmap :: (a -> b) -> RE s a -> RE s b CatMaybes :: RE s (Maybe a) -> RE s a Fail :: RE s a Rep :: Greediness -- repetition may be greedy or not -> (b -> a -> b) -- folding function (like in foldl) -> b -- the value for zero matches, and also the initial value -- for the folding function -> RE s a -> RE s b Void :: RE s a -> RE s () -- | Traverse each (reflexive, transitive) subexpression of a 'RE', depth-first and post-order. traversePostorder :: forall s a m . Monad m => (forall a . RE s a -> m (RE s a)) -> RE s a -> m (RE s a) traversePostorder f = go where go :: forall a . RE s a -> m (RE s a) go = f <=< \ case Eps -> pure Eps Symbol i p -> pure (Symbol i p) Alt a b -> Alt <$> go a <*> go b App a b -> App <$> go a <*> go b Fmap g a -> Fmap g <$> go a CatMaybes a -> CatMaybes <$> go a Fail -> pure Fail Rep greed g b a -> Rep greed g b <$> go a Void a -> Void <$> go a -- | Fold each (reflexive, transitive) subexpression of a 'RE', depth-first and post-order. foldMapPostorder :: Monoid b => (forall a . RE s a -> b) -> RE s a -> b foldMapPostorder f = fst . traversePostorder ((,) <$> f <*> id) -- | Map each (reflexive, transitive) subexpression of a 'RE'. mapRE :: (forall a . RE s a -> RE s a) -> RE s a -> RE s a mapRE f = runIdentity . traversePostorder (Identity . f) instance Functor (RE s) where fmap f x = Fmap f x f <$ x = pure f <* x instance Applicative (RE s) where pure x = const x <$> Eps a1 <*> a2 = App a1 a2 a *> b = pure (const id) <*> Void a <*> b a <* b = pure const <*> a <*> Void b instance Alternative (RE s) where a1 <|> a2 = Alt a1 a2 empty = Fail many a = reverse <$> Rep Greedy (flip (:)) [] a some a = (:) <$> a <*> many a -- | @since 0.3.4 instance Filtrable (RE s) where catMaybes = CatMaybes instance (char ~ Char, string ~ String) => IsString (RE char string) where fromString = string -- | @since 0.3.4 instance Semigroup a => Semigroup (RE s a) where x <> y = (<>) <$> x <*> y -- | @since 0.3.4 instance Monoid a => Monoid (RE s a) where mempty = pure mempty -- | Match and return the given sequence of symbols. -- -- Note that there is an 'IsString' instance for regular expression, so -- if you enable the @OverloadedStrings@ language extension, you can write -- @string \"foo\"@ simply as @\"foo\"@. -- -- Example: -- -- >{-# LANGUAGE OverloadedStrings #-} -- >import Text.Regex.Applicative -- > -- >number = "one" *> pure 1 <|> "two" *> pure 2 -- > -- >main = print $ "two" =~ number string :: Eq a => [a] -> RE a [a] string = traverse sym -- | Match and return a single symbol which satisfies the predicate psym :: (s -> Bool) -> RE s s psym p = msym (\s -> if p s then Just s else Nothing) -- | Like 'psym', but allows to return a computed value instead of the -- original symbol msym :: (s -> Maybe a) -> RE s a msym p = Symbol (error "Not numbered symbol") p -- | Match and return the given symbol sym :: Eq s => s -> RE s s sym s = psym (s ==)
feuerbach/regex-applicative
Text/Regex/Applicative/Types.hs
mit
6,009
0
13
1,471
1,471
776
695
-1
-1
module Rocketfuel.Grid ( generateRandomGrid, afterMove, applySwap, getFallingTiles, hasMoves ) where import Data.Array import Data.List import Data.List.Split (chunksOf) import Data.Maybe import Data.Natural import Control.Monad.Writer import Control.Monad.Random import Rocketfuel.Types -- These lines allow us to run random and randomR on an enum getRandomR' :: (MonadRandom m, Enum a, Bounded a) => (a,a) -> m a getRandomR' (a, b) = uniform [a..b] generateRandomCell :: (MonadRandom r) => r Cell generateRandomCell = getRandomR'(Fuel, Navigate) generateRandomLine :: (MonadRandom r) => r Line generateRandomLine = replicateM 8 (liftM Just generateRandomCell) generateRandomGrid :: (MonadRandom r) => r GameGrid generateRandomGrid = replicateM 8 generateRandomLine emptyAndLogIfAboveThree :: Line -> Writer [Effect] Line emptyAndLogIfAboveThree line | length line' >= 3 = let effect = [Effect (head line') (length line')] in tell effect >> mapM (\_ -> return Nothing) line | otherwise = return line where line' = catMaybes line emptyRepeted :: Line -> Writer [Effect] Line emptyRepeted l = do groups <- return . group $ l result <- mapM emptyAndLogIfAboveThree groups return . concat $ result -- | Basic utility to get a clockwise 90° rotation on the grid, -- useful to handle columns as if they were lines. -- -- >>> rotateGrid [[Just Fuel,Just Repair,Just Trade],[Just Fuel,Just Shoot,Just Navigate],[Just Fuel,Just Trade,Just Trade]] -- [[Just Fuel,Just Fuel,Just Fuel],[Just Repair,Just Shoot,Just Trade],[Just Trade,Just Navigate,Just Trade]] rotateGrid :: Grid a -> Grid a rotateGrid = transpose -- | Basic utility to get a 90° counterclockwise 90° rotation on the grid. -- >>> rotateGrid [[Just Fuel,Just Fuel,Just Fuel],[Just Repair,Just Shoot,Just Trade],[Just Trade,Just Navigate,Nothing]] -- [[Just Fuel,Just Repair,Just Trade],[Just Fuel,Just Shoot,Just Navigate],[Just Fuel,Just Trade,Nothing]] unrotateGrid :: Grid a -> Grid a unrotateGrid = transpose . transpose . transpose -- | The main matching function that will look for matches in lines and columns, -- and log each matches. emptyGrid :: GameGrid -> Writer [Effect] GameGrid emptyGrid g = emptyLines g >>= emptyColumns where emptyLines :: GameGrid -> Writer [Effect] GameGrid emptyLines = mapM emptyRepeted emptyColumns :: GameGrid -> Writer [Effect] GameGrid emptyColumns g' = do let rotated = rotateGrid g' columnsEmptied <- emptyLines rotated return $ unrotateGrid columnsEmptied -- |Find the index of the LAST element of a list -- matching a predicate. -- >>> findLastIndex (==2) [2,2,2,2] -- Just (Natural 3) -- >>> findLastIndex (==2) [] -- Nothing -- >>> findLastIndex (==2) [1,3,5] -- Nothing -- >>> findLastIndex (=='z') "zoning zoning" -- Just (Natural 7) findLastIndex :: (a -> Bool) -> [a] -> Maybe Natural findLastIndex p xs = fmap reverseIndex (findIndex p . reverse $ xs) where maxIndex = length xs - 1 reverseIndex :: Int -> Natural reverseIndex = natural . fromIntegral . (-) maxIndex getFallingTiles :: GameGrid -> Moves getFallingTiles = map gravityColumn . rotateGrid where gravityColumn :: Line -> Maybe Natural gravityColumn = findLastIndex isNothing -- >>> gravity [[Just Fuel,Just Fuel,Just Repair,Just Shoot],[Nothing,Nothing,Nothing,Nothing],[Just Fuel,Nothing,Just Trade,Nothing]] -- [[Nothing,Nothing,Nothing,Nothing],[Just Fuel,Nothing,Just Repair,Nothing],[Just Fuel,Just Fuel,Just Trade,Just Shoot]] gravity :: GameGrid -> GameGrid gravity = tail . unrotateGrid . map gravityColumn . rotateGrid where gravityColumn :: Line -> Line gravityColumn = until filledAtBottom falling filledAtBottom :: Line -> Bool filledAtBottom = anyNull . break isNothing falling :: Line -> Line falling (x:Nothing:ys) = Nothing:falling (x:ys) falling (x:y:ys) = x:falling (y:ys) falling ys = ys anyNull (f, s) = null f || null s -- |Used before calling gravity. prependGrid :: (MonadRandom r) => GameGrid -> r GameGrid prependGrid ls = do newLine <- generateRandomLine return $ newLine:ls containsEmptyCells :: GameGrid -> Bool -- |Check if a grill contains any empty cell. -- >>> containsEmptyCells [[Just Fuel, Just Fuel], [Nothing, Just Shoot]] -- True -- >>> containsEmptyCells [[Just Fuel, Just Fuel], [Just Shoot, Just Shoot]] -- False containsEmptyCells = any isNothing . concat -- | Call gravity till there is no empty cell left in the grid gravityLoop :: (MonadRandom r) => GameGrid -> r GameGrid gravityLoop g | containsEmptyCells g = liftM gravity (prependGrid g) >>= gravityLoop | otherwise = return g -- | After a given move, we must : -- - Check for matchs. -- - If matches were made, apply gravity and loop. -- - If no matches were made, return the grid and the effects. afterMove :: (MonadRandom r) => GameGrid -> r (GameGrid, [Effect]) afterMove = afterMove' [] where afterMove' :: (MonadRandom r) => [Effect] -> GameGrid -> r (GameGrid, [Effect]) afterMove' eff g = case runWriter (emptyGrid g) of (g', []) -> return (g', eff) (g', e) -> do afterGravity <- gravityLoop g' afterMove' (eff ++ e) afterGravity -- | Applying a swap means : -- 1°) Transform the grid into a single array to allow for easier -- manipulation -- 2°) Swap the position in the single array -- 3°) Transform the array back into a list -- applySwap :: Swap -> GameGrid -> GameGrid applySwap (Swap p1 p2) g = rebuild . elems $ toArray // [(oneIdx, twoValue), (twoIdx, oneValue)] where toArray :: Array Integer Cell toArray = listArray (0, 63) . concatMap catMaybes $ g idx2Dto1D :: Position -> Integer idx2Dto1D (x, y) = y*8 + x oneIdx = idx2Dto1D p1 twoIdx = idx2Dto1D p2 oneValue = toArray ! oneIdx twoValue = toArray ! twoIdx rebuild = map (map Just) . chunksOf 8 -- |Given a list of moves, check if there is any current move. -- This simply means checking that the list of Moves (one per column in the grid) -- is only made out of Nothing. -- -- >>> hasMoves [Nothing, Nothing, Nothing] -- False -- >>> hasMoves [Nothing, Nothing, Just 3] -- True hasMoves :: Moves -> Bool hasMoves = any (isJust)
Raveline/Rocketfuel
src/Rocketfuel/Grid.hs
mit
6,579
0
14
1,523
1,430
762
668
94
3
{-# LANGUAGE PatternGuards #-} module Tarefa3_2017li1g180 where import LI11718 import Tarefa2_2017li1g180 import Test.QuickCheck.Gen import Data.List import Data.Maybe import Safe testesT3 :: [(Tabuleiro,Tempo,Carro)] testesT3 = unitTests randomizeCarro :: Tabuleiro -> Double -> Carro -> Gen Carro randomizeCarro tab delta c = do suchThat genC (validaCarro tab) where (x,y) = posicao c genC = do dx <- choose (0,delta) dy <- choose (0,delta) let x' = x + dx let y' = y + dy return c { posicao = (x',y') } ranksT3 :: [(Tabuleiro,Tempo,Carro)] ranksT3 = unitTests -- Nuno/Hugo's simpler version -- ranksT3Nuno :: [(Tabuleiro,Tempo,Carro)] -- ranksT3Nuno = [(tab1,5,carro1)] -- where -- tab1 = [[Peca Lava altLava, Peca Lava altLava, Peca Lava altLava, Peca Lava altLava, Peca Lava altLava] -- ,[Peca Lava altLava, Peca (Curva Norte) 2,Peca Recta 2,Peca (Curva Este) 2, Peca Lava altLava] -- ,[Peca Lava altLava, Peca Recta 2,Peca Lava altLava,Peca Recta 2, Peca Lava altLava] -- ,[Peca Lava altLava, Peca (Curva Oeste) 2,Peca Recta 2,Peca (Curva Sul) 2, Peca Lava altLava] -- ,[Peca Lava altLava, Peca Lava altLava, Peca Lava altLava, Peca Lava altLava, Peca Lava altLava] -- ] -- carro1 = Carro (3,3) 30 (2,1.5) solutionsT3 :: [((Tabuleiro,Tempo,Carro),Maybe Carro)] solutionsT3 = zip ranksT3 (map aux ranksT3) where aux x@(tab,tempo,carro) = movimenta tab tempo carro compareT3Solutions :: Double -> Maybe Carro -> Maybe Carro -> Double compareT3Solutions distance Nothing Nothing = 100 compareT3Solutions distance Nothing (Just y) = 0 compareT3Solutions distance (Just x) Nothing = 0 compareT3Solutions distance (Just x) (Just y) = (pos+dir+vel) / 3 where pos = if distance == 0 then 100 else (1 - dist (posicao x) (posicao y) / distance) * 100 dir = (1 - (normAngulo (abs (direcao x - direcao y))) / 360) * 100 vel = if distance == 0 then 100 else (1 - dist (velocidade x) (velocidade y) / distance) * 100 normAngulo x = if x >= 360 then normAngulo (x - 360) else x genTempo :: Gen Tempo genTempo = choose (0,30) validaCarro :: Tabuleiro -> Carro -> Bool validaCarro tab carro = validaPonto (posicao carro) tab && (not $ derrete tab (posicao carro)) derrete :: Tabuleiro -> Ponto -> Bool derrete t p = derrete' tp a where (i,j) = ponto2Pos p a = denorm p (i,j) Peca tp _ = (atNote "derrete" (atNote "derrete" t j) i) derrete' :: Tipo -> Ponto -> Bool derrete' Lava _ = True -- hpacheco: mudei para incluir parede derrete' (Curva Norte) (x,y) = x < (1-y) derrete' (Curva Este) (x,y) = x > y derrete' (Curva Sul) (x,y) = x > (1-y) derrete' (Curva Oeste) (x,y) = x < y derrete' _ _ = False movimenta :: Tabuleiro -> Tempo -> Carro -> Maybe Carro movimenta m t c = case (colideLocal m v (a,b) i) of Nothing -> Nothing Just (p',v') -> Just $ c { posicao = p', velocidade = v' } where a = posicao c v = velocidade c b = a .+. (t .*. v) i = ponto2Pos a bounce :: (Double,Double) -> (Double,Double) -> (Double,Double) bounce (d,a1) (1,a2) = componentsToArrow $ (arrowToComponents (d,a1)) .+. (-x,-y) where dp = 2 * (arrowToComponents (d,a1) .$. arrowToComponents (1,a2)) (x,y) = dp .*. (arrowToComponents (1,a2)) colideLocal :: Tabuleiro -> Velocidade -> (Ponto,Ponto) -> Posicao -> Maybe (Ponto,Velocidade) colideLocal e v ab ij = case colideLocalAcc [] e v ab ij of (l,Just v) -> Just (last l,v) (_,Nothing) -> Nothing colideLocalAcc :: [Ponto] -> Tabuleiro -> Velocidade -> (Ponto,Ponto) -> Posicao -> ([Ponto],Maybe Velocidade) colideLocalAcc ps m v (a,b) (i,j) | morto = (ps++[a,b],Nothing) | colideInterno = colideLocalAcc (ps++[a]) m iVel iPos (i,j) -- se houverem colisões internas (diagonais), da prioridade e volta a aplicar novo vector | dentroPeca (a,b) (i,j) g = (ps++[a,b],Just v) -- caso contrario, se estiver dentro da peça pode parar | colideExterno = colideLocalAcc (ps++[a]) m eVel ePos (i,j) -- se passar para fora da peça mas houver parede, colide na parede e volta a aplicar novo vector | otherwise = colideLocalAcc (ps++[a]) m v (aPos,b) ij' -- se passar para fora da peça mas não houver parede, chama na peça seguinte where (_,g) = componentsToArrow (b.-.a) morto = (isJust int && isNothing (fromJust int)) || (colideExterno && not (fromJust $ temParede m (i,j) (fromJust ext))) int = colisaoInterna (atNote "colideLocalAcc" (atNote "colideLocalAcc" m j) i) (i,j) (a,b) colideInterno = isJust int && isJust (fromJust int) && colisaoRelevante (a,b) (fromJust (fromJust int)) (iPos,iVel) = inv v (a,b) (fromJust int) ext = atravessaOnde (i,j) (a,b) colideExterno = isJust ext && (isJust . temParede m (i,j)) (fromJust ext) (ePos,eVel) = inv v (a,b) (Just (norm (fst (fromJust ext)) (i,j),snd (fromJust ext))) (aPos,aVel) = (norm (fst (fromJust ext)) (i,j), snd (fromJust ext)) ij' = atravessa aVel (i,j) norm (x,y) (i,j) = (x+toEnum i,y+toEnum j) denorm (x,y) (i,j) = (x-toEnum i,y-toEnum j) -- dada uma velocidade e um deslocamento, inverte ambos dada uma colisão inv :: Velocidade -> (Ponto,Ponto) -> Maybe (Ponto,Double) -> ((Ponto,Ponto),Velocidade) inv v ab Nothing = (ab,v) inv v ab (Just (c,g)) = ((c,d),arrowToComponents (vd,v')) where (_,d,v') = inverte ab c g (vd,_) = componentsToArrow v inverte :: (Ponto,Ponto) -> Ponto -> Double -> (Ponto,Ponto,Double) inverte (a,b) c g = (c,d,v') where (z,v') = bounce (componentsToArrow (b .-. c)) (1,g) d = c .+. arrowToComponents (z,v') -- dada uma peça e um segmento (relativo à peça), detecta colisoes e devolve angulo da normal -- colisões internas apenas acontecem em diagonais e no maximo uma colisaoInterna :: Peca -> Posicao -> (Ponto,Ponto) -> Maybe (Maybe (Ponto,Double)) colisaoInterna (Peca (Curva d) al) ij (a,b) | d == Norte || d == Sul = f (intersecta ab ((1,0),(0,1))) (135 + dlt) | otherwise = f (intersecta ab ((0,0),(1,1))) (45 + dlt) where f :: Maybe Ponto -> Double -> Maybe (Maybe (Ponto,Double)) f Nothing _ = Nothing f (Just a) b | al < altLava = Just $ Just (norm a ij,b) | otherwise = Just Nothing dlt = if d == Norte || d == Este then 180 else 0 ab = (denorm a ij, denorm b ij) colisaoInterna _ _ _ = Nothing -- se o movimento mantem-se dentro da peça dentroPeca :: (Ponto,Ponto) -> Posicao -> Double -> Bool dentroPeca (a,b) (i,j) g = belongs b where belongs (x,y) = (x == toEnum i+1 || floor x == i) && (floor y == j || y == toEnum j+1) -- dado um segmento (relativo à peça), calcula pontos de interceção e angulos das normais -- entre 0 e 2 no caso extremo (segmento que começa em cima da linha e atravessa outra) atravessaOnde :: Posicao -> (Ponto,Ponto) -> Maybe (Ponto, Double) atravessaOnde ij (x,y) | null rel = Nothing | length rel == 1 = Just (head rel) | otherwise = Just (last rel) --error $ "Duas travessias: "++(show rel) where rel = filter (colisaoRelevante (x,y)) $ normalize $ zip is [0,270,90,180] is = [intersecta xy ((i,i),(toEnum j,toEnum $ (j+1)`mod`2)) | i <- [0,1], j <- [0,1]] normalize = catMaybes . map (\(a,b) -> if (isJust a) then Just (fromJust a,b) else Nothing) xy = (denorm x ij, denorm y ij) -- para uma peça e uma aresta, testa se vai haver colisão temParede :: Tabuleiro -> Posicao -> (Ponto,Double) -> Maybe Bool temParede m (i,j) c | t == Lava = Just (a1 < altLava) | snd c == 270 && (t == Curva Sul || t == Curva Oeste) = Just (a1 < altLava) | snd c == 180 && (t == Curva Norte || t == Curva Oeste) = Just (a1 < altLava) | snd c == 90 && (t == Curva Norte || t == Curva Este) = Just (a1 < altLava) | snd c == 0 && (t == Curva Sul || t == Curva Este) = Just (a1 < altLava) | middle && mwall t0 (fst c) && aa > aa' = Just True | middle && mfall t0 (fst c) && aa < aa' = Just False | a2 > a1 = Just True | a2 < a1 = Just False | otherwise = Nothing where (i',j') = atravessa (snd c) (i,j) Peca t aa = atNote "temParede" (atNote "temParede" m j') i' Peca t0 aa' = atNote "temParede" (atNote "temParede" m j) i isR (Rampa _) = True isR _ = False (a1,a2) = normAlturas (atNote "temParede" (atNote "temParede" m j) i) (atNote "temParede" (atNote "temParede" m j') i') middle = case t of (Rampa x) -> t0 == (Rampa (toEnum (((fromEnum x) + 2) `mod` 4))) && (abs $ aa-aa') == 1 otherwise -> False mwall (Rampa Oeste) (x,y) = x >= 0.5 mwall (Rampa Este) (x,y) = x <= 0.5 mwall (Rampa Norte) (x,y) = y >= 0.5 mwall (Rampa Sul) (x,y) = y <= 0.5 mfall r p = not $ mwall r p normAlturas :: Peca -> Peca -> (Altura,Altura) normAlturas (Peca (Rampa _) a1) p@(Peca _ a2) | a2 > a1 = normAlturas (Peca Recta (a1+1)) p | otherwise = normAlturas (Peca Recta a1) p normAlturas p@(Peca _ a1) (Peca (Rampa _) a2) | a2 < a1 = normAlturas p (Peca Recta (a2+1)) | otherwise = normAlturas p (Peca Recta a2) normAlturas (Peca _ a1) (Peca _ a2) = (a1,a2) -- dado o angulo de travessia, da a nova posiçao atravessa :: Double -> Posicao -> Posicao atravessa 270 (i,j) = (i,j-1) atravessa 90 (i,j) = (i,j+1) atravessa 0 (i,j) = (i-1,j) atravessa 180 (i,j) = (i+1,j) -- dado o deslocamento e o ponto de colisão com o angulo da normal, testa de é relevante -- é relevante se a diferença de angulos > 90º colisaoRelevante :: (Ponto,Ponto) -> (Ponto,Double) -> Bool colisaoRelevante ((a1,a2),(b1,b2)) ((x,y),a) = diff > 90 && diff < 270 where (_,a') = componentsToArrow (b1-a1,b2-a2) diff = f (a-a') f x | x < 0 = f (x+360) | x > 360 = f (x-360) | otherwise = x -- geometry -- copiado do Gloss para Double intersecta :: (Ponto,Ponto) -> (Ponto,Ponto) -> Maybe Ponto intersecta (p1,p2) (p3,p4) | Just p0 <- intersectaL p1 p2 p3 p4 , t12 <- closestPontoOnL p1 p2 p0 , t23 <- closestPontoOnL p3 p4 p0 , t12 >= 0 && t12 <= 1 , t23 >= 0 && t23 <= 1 = Just p0 | otherwise = Nothing -- copiado do Gloss para Double intersectaL :: Ponto -> Ponto -> Ponto -> Ponto -> Maybe Ponto intersectaL (x1, y1) (x2, y2) (x3, y3) (x4, y4) = let dx12 = x1 - x2 dx34 = x3 - x4 dy12 = y1 - y2 dy34 = y3 - y4 den = dx12 * dy34 - dy12 * dx34 in if den == 0 then Nothing else let det12 = x1*y2 - y1*x2 det34 = x3*y4 - y3*x4 numx = det12 * dx34 - dx12 * det34 numy = det12 * dy34 - dy12 * det34 in Just (numx / den, numy / den) -- copiado do Gloss para Double closestPontoOnL :: Ponto -> Ponto -> Ponto -> Double closestPontoOnL p1 p2 p3 = (p3 .-. p1) .$. (p2 .-. p1) / (p2 .-. p1) .$. (p2 .-. p1) (.*.) :: Double -> (Double,Double) -> (Double,Double) (.*.) x (a,b) = ((x*a),(x*b)) (.+.) :: (Double,Double) -> (Double,Double) -> (Double,Double) (.+.) (x,y) (a,b) = ((x+a),(y+b)) (.-.) :: (Double,Double) -> (Double,Double) -> (Double,Double) (.-.) (x,y) (a,b) = ((x-a),(y-b)) -- the dot product between two (Double,Double)s (.$.) :: (Double,Double) -> (Double,Double) -> Double (.$.) (d1,a1) (d2,a2) = (x1*x2) + (y1*y2) where (x1,y1) = (d1,a1) (x2,y2) = (d2,a2) radians th = th * (pi/180) degrees th = th * (180/pi) arrowToComponents :: (Double,Double) -> Ponto arrowToComponents (v,th) = (getX v th,getY v th) where getX v th = v * cos (radians (th)) getY v th = v * sin (radians (-th)) componentsToArrow :: Ponto -> (Double,Double) componentsToArrow (x,0) | x >= 0 = (x,0) componentsToArrow (x,0) | x < 0 = (abs x,180) componentsToArrow (0,y) | y >= 0 = (y,-90) componentsToArrow (0,y) | y < 0 = (abs y,90) componentsToArrow (x,y) = (hyp,dir angle) where dir o = case (x >= 0, y >= 0) of (True,True) -> -o (True,False) -> o (False,False) -> 180 - o (False,True) -> 180 + o hyp = sqrt ((abs x)^2 + (abs y)^2) angle = degrees $ atan (abs y / abs x) dist :: Ponto -> Ponto -> Double dist (x1,y1) (x2,y2) = sqrt ((x2-x1)^2+(y2-y1)^2) -------------- testeMapa = [[Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0 ,Peca Lava 0,Peca Lava 0,Peca Lava 0] ,[Peca Lava 0,Peca (Curva Norte) 0,Peca (Rampa Este) 0,Peca Recta 1,Peca (Rampa Oeste) 0,Peca Recta 0,Peca Recta 0,Peca (Rampa Oeste) (-1),Peca Recta (-1) ,Peca (Rampa Este) (-1),Peca (Rampa Este) 0,Peca (Rampa Oeste) 0,Peca (Rampa Oeste) (-1),Peca (Curva Este) (-1),Peca Lava 0] ,[Peca Lava 0,Peca (Curva Oeste) 0,Peca (Rampa Este) 0,Peca (Rampa Oeste) 0,Peca (Rampa Este) 0,Peca Recta 1,Peca (Rampa Oeste) 0,Peca (Rampa Oeste) (-1) ,Peca Recta (-1),Peca (Rampa Oeste) (-2),Peca (Rampa Oeste) (-3),Peca (Rampa Este) (-3),Peca (Rampa Este) (-2),Peca (Curva Sul) (-1),Peca Lava 0] ,[Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0 ,Peca Lava 0,Peca Lava 0,Peca Lava 0]] -- 00011110000009999001100999 -- ..//>>[]<<[][]<<[]>>>><<<<\\.. -- ..\\>><<>>[]<<<<[]<<<<>>>>//.. -- 00011001111009999887788999 testeCurvas = [[Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0] ,[Peca Lava 0,Peca (Curva Norte) 0,Peca (Rampa Oeste) (-1),Peca (Curva Este) (-1),Peca Lava 0,Peca (Curva Norte) 0,Peca (Curva Este) 0 ,Peca Lava 0,Peca (Curva Norte) 1,Peca (Curva Este) 1,Peca Lava 0] ,[Peca Lava 0,Peca (Rampa Sul) 0,Peca Lava 0,Peca (Curva Oeste) (-1),Peca (Rampa Este) (-1),Peca (Curva Sul) 0,Peca (Curva Oeste) 0 ,Peca (Rampa Este) 0,Peca (Curva Sul) 1,Peca Recta 1,Peca Lava 0] ,[Peca Lava 0,Peca (Curva Oeste) 1,Peca (Rampa Oeste) 0,Peca Recta 0,Peca (Rampa Oeste) (-1),Peca Recta (-1),Peca (Rampa Este) (-1) ,Peca (Rampa Este) 0,Peca Recta 1,Peca (Curva Sul) 1,Peca Lava 0] ,[Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0,Peca Lava 0]] -- ..//<<\\..//\\..//\\.. -- ..\/..\\>>//\\>>//[].. -- ..\\<<[]<<[]>>>>[]//.. unitTests :: [(Tabuleiro,Tempo,Carro)] unitTests = [ --- apenas um passo recursivo -- rectas: passa percurso (testeMapa , 1.2, Carro (5.5,1.5) 0 (0.9,0.1)) -- rectas: cai adjacente , (testeMapa , 1.2, Carro (5.5,2.5) 0 (0.1,-0.9)) -- rectas: passa adjacente , (testeMapa , 1.2, Carro (8.5,1.5) 0 (0.1,0.9)) -- rectas: choca adjacente , (testeMapa , 1.2, Carro (5.5,1.5) 0 (0.1,0.9)) -- rectas: cai lava , (testeMapa , 1.2, Carro (3.5,1.5) 0 (0.1,-0.9)) -- rectas: passa lava (mesma altura) , (testeMapa , 1.2, Carro (5.5,1.5) 0 (0.1,-0.9)) -- rectas: choca lava , (testeMapa , 1.2, Carro (8.5,1.5) 0 (0.1,-0.9)) -- curva: choca lava , (testeMapa , 1.2, Carro (13.4,1.5) 0 (0.3,-0.1)) -- curva: cai lava (mesma altura) , (testeMapa , 1.2, Carro (1.6,1.5) 0 (-0.3,-0.1)) -- recta->curva: cai , (testeCurvas , 1.2, Carro (8.5,3.5) 0 (0.1,-0.9)) -- recta->curva: lava , (testeCurvas , 1.2, Carro (5.5,3.5) 0 (0.1,-0.9)) -- recta->curva: choca , (testeCurvas , 1.2, Carro (3.5,3.5) 0 (0.1,-0.9)) --- dois+ passos recursivos -- rectas: passa percurso 2 , (testeMapa , 1.2, Carro (3.6,1.5) 0 (-1.6,0.1)) -- rectas: passa percurso 3 , (testeMapa , 1.2, Carro (4.6,1.5) 0 (-2.6,0.1)) -- curvas: cai lava (mesma altura) 3 , (testeMapa , 1.2, Carro (3.6,1.5) 0 (-2.6,0.1)) -- rectas: adjacente + cai lava (mesma altura) 10 , (testeMapa , 5.5, Carro (12.5,1.2) 0 (-2.1,0.1)) -- rectas: adjacente + choca lava 2 , (testeMapa , 1.2, Carro (8.5,1.5) 0 (0.1,1.9)) -- rectas: choca lava + adjacente 2 , (testeMapa , 1.2, Carro (8.5,2.5) 0 (0.1,1.9)) -- rectas: choca lava + adjacente + choca lava 3 , (testeMapa , 1.2, Carro (8.5,2.5) 0 (0.1,2.3)) -- rectas: choca lava + adjacente + choca lava + adjacente 4 , (testeMapa , 1.2, Carro (8.5,2.5) 0 (0.1,3.3)) -- rectas: choca adjacente + cai lava (mesma altura) 2 , (testeMapa , 1.2, Carro (5.5,1.5) 0 (0.1,1.9)) -- curvas: adjacente + choca lava 3 , (testeMapa , 1.2, Carro (11.6,1.5) 0 (2.1,0.1)) -- curva: adjacente + cai lava 2 , (testeMapa , 1.2, Carro (1.6,2.5) 0 (-0.1,-1.1)) -- curva: choca lava 2 , (testeMapa , 1.2, Carro (12.5,1.5) 0 (2.8,-0.1)) -- curva: cai 2 (passa a lava) -- @nmm nao percebo a particularidade deste teste! , (testeMapa , 1.2, Carro (1.6,2.5) 0 (-0.3,-0.1)) ----- PLANO NOVO (cai se queda >= 1, choca se degrau >= 1, passa se diff. entre 1 e -1) -- rampas: cai , (testeMapa , 1.2, Carro (10.5,1.5) 0 (-0.1,0.9)) -- rampas: choca , (testeMapa , 1.2, Carro (10.5,2.5) 0 (0.1,-0.9)) -- rampas: passa (igual) , (testeMapa , 1.2, Carro (2.5,1.5) 0 (0.1,0.9)) -- rampas x2: passa (um pouco maior) , (testeMapa , 1.2, Carro (4.5,1.5) 0 (0.1,0.9)) -- rampas x2: passa (um pouco menor) , (testeMapa , 1.2, Carro (4.5,1.5) 0 (-0.1,0.9)) ---- casos difíceis (sobe/desce Bom Jesus)! -- rampas: choca (tricky) , (testeMapa , 1.2, Carro (9.5,2.5) 0 (0.1,-0.9)) -- rampas: não choca (tricky) , (testeMapa , 1.2, Carro (9.5,2.5) 0 (-0.1,-0.9)) -- rampas: passa (tricky) , (testeMapa , 1.2, Carro (9.5,1.5) 0 (0.1,0.9)) -- rampas: não passa (tricky) , (testeMapa , 1.2, Carro (9.5,1.5) 0 (-0.1,0.9)) -- rampas: choca rés-vés (tricky x2) , (testeMapa , 1.2, Carro (9.5,2.5) 0 (0,-0.9)) -- rampas: choca lava , (testeMapa , 1.2, Carro (9.5,2.5) 0 (0.1,0.9)) -- rampas: cai lava , (testeMapa , 1.2, Carro (9.5,1.5) 0 (0.1,-0.9)) ------ ----- PLANO ANTIGO (cai se altura maior, choca se menor, passa se igual) -- -- rampas: cai -- , (testeMapa , 1.2, Carro (6.5,2.5) 0 (0.1,-0.9)) -- oracle: (6.6,1.4), got Noth -- -- rampas: passa -- , (testeMapa , 1.2, Carro (2.5,1.5) 0 (0.1,0.9)) -- -- rampas: choca -- , (testeMapa , 1.2, Carro (3.5,2.5) 0 (0.1,-0.9)) -- oracle: (_.1.5), got (_,2.6) -- -- rampas x2: choca -- , (testeMapa , 1.2, Carro (4.5,1.5) 0 (0.1,0.9)) -- oracle (_.2.5), got (_,1.4) -- -- rampas x2: cai -- , (testeMapa , 1.2, Carro (4.5,1.5) 0 (-0.1,0.9)) -- oracle (4.4,2.6), got Noth -- -- rampas x2: bónus - passa? -- , (testeMapa , 1.2, Carro (4.5,1.5) 0 (0,0.9)) ------------- ]
hpacheco/HAAP
examples/plab/svn/2017li1g180/src/Tarefa3_2017li1g180.hs
mit
19,467
0
22
5,159
8,208
4,494
3,714
269
6
newtype Stack a = Stk [a] deriving(Show) -- The follwing Functions are supposed declared in the exams' question (just to make it work) -- Start top/pop/push/empty top :: Stack a -> a top (Stk []) = error "Stack is empty, can't call top function on it!" top (Stk (x:_)) = x pop :: Stack a -> Stack a pop (Stk []) = error "Stack is empty, can't call pop function on it!" pop (Stk (x:xs)) = Stk xs push :: a -> Stack a -> Stack a push x (Stk xs) = Stk (x:xs) empty :: Stack a -> Bool empty (Stk []) = True empty _ = False -- End top/pop/push/empty -- 1) cvider cvider :: Stack a -> [a] cvider s | empty s = [] | otherwise = (top s):(cvider (pop s)) -- 2) vider vider :: Stack a -> (a -> Bool) -> [a] -> ([a], Stack a) vider (Stk []) _ _ = ([], (Stk [])) vider s p ys | p $ top s = (ys,pop s) | otherwise = let (k,l) = vider (pop s) p ys in ((top s):k, l) -- 3) transform -- Algo: http://csis.pace.edu/~wolf/CS122/infix-postfix.htm (the last part; summary) prio :: Char -> Int prio '+' = 1 prio '*' = 2 prio '(' = 0 isOperand :: Char -> Bool isOperand x | x == '+' || x == '*' || x == '(' || x == ')' = False | otherwise = True transform :: [Char] -> [Char] transform xs = tr' xs (Stk []) tr' :: [Char] -> Stack Char -> [Char] tr' [] s = cvider s tr' (x:xs) s@(Stk []) | isOperand x = x:(tr' xs s) | otherwise = tr' xs (push x s) tr' (x:xs) s | isOperand x = x:(tr' xs s) | x == ')' = let (ys,t) = vider s (== '(') [] in ys ++ (tr' xs t) | x == '(' = tr' xs (push '(' s) | (prio x) > (prio ts) = tr' xs (push x s) | otherwise = ts:(tr' (x:xs) (pop s)) where ts = top s -- 4) pe2st (postfix expression to a syntaxic tree) data AS = E | Node Char AS AS pe2st :: [Char] -> AS pe2st = pe2st' . (foldl (flip push) (Stk [])) pe2st' :: Stack Char -> AS pe2st' s | isOperand ts = Node ts E E | otherwise = let (fstST, sndST, _) = squeeze (pop s) in Node ts fstST sndST where ts = top s squeeze :: Stack Char -> (AS, AS, Stack Char) -- Left Squeezed, Right Squeezed, The rest after the squeezing is DONE! // Fuck this function in particular squeeze s | isOperand ts && isOperand tss = (Node ts E E, Node tss E E, pss) | isOperand ts = (Node ts E E, pe2st' ps, Stk []) | otherwise = (Node ts sqzFst sqzSnd, pe2st' sqzRest, Stk []) where ts = top s tss = top ps ps = pop s -- no ts pss = pop ps -- no ts && no tss (sqzFst, sqzSnd, sqzRest) = squeeze ps -- Debugging the correctness of the tree instance Show AS where show E = "E" show (Node c s t) = "(" ++ [c] ++ " " ++ show s ++ ", " ++ show t ++ ")" -- Tests: -- Test 1) cvider (Stk [1..5]) => [1,2,3,4,5] -- Test 2) vider (Stk [1,3,5,4,8,7,10,9]) even [] => ([1,3,5], Stack [8,7,10,9]) -- Test 3) transform "a*(b+c)+d*f" => "abc+*df*+" -- Test 4) pe2st (transform "a*(b+c)+d*f") => Should give u the correct tree xZ
NMouad21/HaskellSamples
HaskellFinalExV.hs
mit
3,112
0
14
959
1,310
659
651
57
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DefaultSignatures #-} module Solar.Utility.NoCache where import Data.Typeable import Data.Generics as D import GHC.Generics as G import Data.Monoid -- | The "No Cache" data type, use 'kvNoCache' to provide a typed 'Nothing' data KVNoCache n r c = KVNoCache deriving (Show, Read, Typeable, Eq, Ord, Data, G.Generic) -- | Gives a typed 'Nothing' of 'KVNoCache' kvNoCache :: (Maybe (KVNoCache n r c)) kvNoCache = Nothing instance Monoid (KVNoCache n r c) where mempty = KVNoCache mappend a _ = a
Cordite-Studios/solar
solar-shared/Solar/Utility/NoCache.hs
mit
589
0
8
105
138
81
57
15
1
module HistogramTest where import Control.Concurrent.Async import Data.Metrics.Histogram.Internal import Data.Metrics.Snapshot import Data.Metrics.Types import System.Random.MWC import System.Posix.Time import Test.QuickCheck histogramTests :: [Test] histogramTests = [ testUniformSampleMin , testUniformSampleMax , testUniformSampleMean , testUniformSampleMeanThreaded , testUniformSample2000 -- , testUniformSample2000Threaded , testUniformSampleSnapshot , testUniformSampleSnapshotThreaded , testExponentialSampleMin , testExponentialSampleMax , testExponentialSampleMean , testExponentialSampleMeanThreaded , testExponentialSample2000 --, testExponentialSample2000Threaded , testExponentialSampleSnapshot , testExponentialSampleSnapshotThreaded -- , testExponentialSampleLongIdle ] withUniform :: (Histogram IO -> IO a) -> IO a withUniform f = do seed <- withSystemRandom (asGenIO save) h <- uniformHistogram seed f h withExponential :: (Histogram IO -> IO a) -> IO a withExponential f = do seed <- withSystemRandom (asGenIO save) t <- epochTime h <- exponentiallyDecayingHistogram t seed f h uniformTest :: Assertable a => String -> (Histogram IO -> IO a) -> Test uniformTest d f = d ~: test $ assert $ withUniform f exponentialTest :: Assertable a => String -> (Histogram IO -> IO a) -> Test exponentialTest d f = d ~: test $ assert $ withExponential f testUniformSampleMin :: Test testUniformSampleMin = uniformTest "uniform min value" $ \h -> do update h 5 update h 10 x <- minVal h assertEqual "min" 5 x testUniformSampleMax :: Test testUniformSampleMax = uniformTest "uniform max value" $ \h -> do update h 5 update h 10 x <- maxVal h assertEqual "max" 10 x testUniformSampleMean :: Test testUniformSampleMean = uniformTest "uniform mean value" $ \h -> do update h 5 update h 10 x <- mean h assertEqual "mean" 7.5 x testUniformSampleMeanThreaded :: Test testUniformSampleMeanThreaded = uniformTest "async uniform mean value" $ \h -> do let task = update h 5 >> update h 10 asyncs <- sequence $ replicate 10 (async $ task) mapM_ wait asyncs x <- mean h assert $ x == 7.5 testUniformSample2000 :: Test testUniformSample2000 = uniformTest "uniform sample 2000" $ \h -> do mapM_ (update h $) [0..1999] x <- maxVal h assert $ x == 1999 --testUniformSample2000Threaded :: Test --testUniformSample2000Threaded ="" ~: test $ do -- x <- with testUniformSampleSnapshot :: Test testUniformSampleSnapshot = uniformTest "uniform snapshot" $ \h -> do mapM_ (update h $) [0..99] s <- snapshot h assert $ median s == 49.5 testUniformSampleSnapshotThreaded :: Test testUniformSampleSnapshotThreaded = uniformTest "async uniform snapshot" $ \h -> do let task = mapM_ (update h $) [0..99] asyncs <- sequence $ replicate 10 (async $ task) mapM_ wait asyncs s <- snapshot h assertEqual "median" 49.5 $ median s testExponentialSampleMin :: Test testExponentialSampleMin = exponentialTest "minVal" $ \h -> do update h 5 update h 10 x <- minVal h assertEqual "min" 5 x testExponentialSampleMax :: Test testExponentialSampleMax = exponentialTest "maxVal" $ \h -> do update h 5 update h 10 x <- maxVal h assertEqual "max" 10 x testExponentialSampleMean :: Test testExponentialSampleMean = exponentialTest "mean" $ \h -> do update h 5 update h 10 x <- mean h assertEqual "mean" 7.5 x testExponentialSampleMeanThreaded :: Test testExponentialSampleMeanThreaded = exponentialTest "mean threaded" $ \h -> do let task = update h 5 >> update h 10 asyncs <- sequence $ replicate 10 (async $ task) mapM_ wait asyncs x <- mean h assertEqual "mean" 7.5 x testExponentialSample2000 :: Test testExponentialSample2000 = exponentialTest "sample 2000" $ \h -> do mapM_ (update h $) [0..1999] x <- maxVal h assertEqual "max" 1999 x --testExponentialSample2000Threaded :: Test --testExponentialSample2000Threaded = exponentialTest "async sample 2000" $ \h -> do -- x <- with testExponentialSampleSnapshot :: Test testExponentialSampleSnapshot = exponentialTest "snapshot" $ \h -> do mapM_ (update h $) [0..99] s <- snapshot h assertEqual "median" 49.5 $ median s testExponentialSampleSnapshotThreaded :: Test testExponentialSampleSnapshotThreaded = exponentialTest "async snapshot" $ \h -> do let task = mapM_ (update h $) [0..99] asyncs <- sequence $ replicate 10 (async $ task) mapM_ wait asyncs s <- snapshot h assertEqual "median" 49.5 $ median s --testExponentialSampleLongIdle :: Test --testExponentialSampleLongIdle ="" ~: test $ do -- x <- with
graydon/metrics
tests/HistogramTest.hs
mit
4,609
0
14
830
1,375
665
710
123
1
{-# LANGUAGE TypeOperators, OverloadedStrings, FlexibleContexts, ScopedTypeVariables #-} module Wf.Control.Eff.Run.Session ( runSession , getRequestSessionId , genSessionId ) where import Control.Eff (Eff, (:>), Member, freeMap, handleRelay) import Control.Eff.Reader.Strict (Reader, ask) import Wf.Control.Eff.Session (Session(..)) import Control.Monad (when) import qualified Data.ByteString as B (ByteString, append) import qualified Data.ByteString.Char8 as B (pack) import qualified Data.List as L (lookup) import qualified Data.HashMap.Strict as HM (lookup, insert) import qualified Blaze.ByteString.Builder as Blaze (toByteString) import qualified Network.Wai as Wai (Request, requestHeaders, isSecure) import qualified Web.Cookie as Cookie (parseCookies, renderSetCookie, def, setCookieName, setCookieValue, setCookieExpires, setCookieSecure, setCookieHttpOnly, setCookieDomain, setCookiePath) import Wf.Session.Types (SessionState(..), SessionData(..), SessionSettings(..), SetCookieSettings(..), SessionHandler(..), defaultSessionState) import qualified Wf.Application.Time as T (Time, formatTime, addSeconds) import Wf.Application.Random (randomByteString) runSession :: Member (Reader Wai.Request) r => SessionHandler (Eff r) -> SessionSettings -> T.Time -> Eff (Session :> r) a -> Eff r a runSession handler sessionSettings current eff = do requestSessionId <- fmap (getRequestSessionId sname) ask s <- loadSession requestSessionId (r, s') <- loop s eff when (s' /= s) $ saveSession s' return r where sname = sessionName sessionSettings scSettings = sessionSetCookieSettings sessionSettings loop s = freeMap (\a -> return (a, s)) $ \u -> handleRelay u (loop s) (handle s) newSession = sessionHandlerNew handler sessionSettings current loadSession = sessionHandlerLoad handler current saveSession = sessionHandlerSave handler current sessionDestroy = sessionHandlerDestroy handler handle s (SessionGet decode k c) = do let m = HM.lookup k . sessionValue . sessionData $ s loop s . c $ decode =<< m handle s (SessionPut encode k v c) = do s' <- if sessionId s == "" then newSession else return s loop (f s') c where f ses @ (SessionState _ d @ (SessionData m _ _) _) = ses { sessionData = d { sessionValue = HM.insert k (encode v) m } } handle s (SessionTtl ttl' c) = loop (f s) c where expire = T.addSeconds current ttl' f ses @ (SessionState _ d _) = ses { sessionData = d { sessionExpireDate = expire } } handle s (SessionDestroy c) = do when (sid /= "") (sessionDestroy sid) loop defaultSessionState c where sid = sessionId s handle s (GetSessionId c) = loop s . c . sessionId $ s handle s (RenderSetCookie c) = do requestIsSecure <- fmap Wai.isSecure ask loop s . c $ ("Set-Cookie", Blaze.toByteString . Cookie.renderSetCookie $ setCookie requestIsSecure) where sid = sessionId s expires = if addExpires scSettings then Just . sessionExpireDate . sessionData $ s else Nothing setCookie requestIsSecure = Cookie.def { Cookie.setCookieName = sname , Cookie.setCookieValue = sid , Cookie.setCookieExpires = expires , Cookie.setCookieSecure = requestIsSecure && addSecureIfHttps scSettings , Cookie.setCookieHttpOnly = isHttpOnly scSettings , Cookie.setCookieDomain = cookieDomain scSettings , Cookie.setCookiePath = cookiePath scSettings } getRequestSessionId :: B.ByteString -> Wai.Request -> Maybe B.ByteString getRequestSessionId name = (L.lookup name =<<) . fmap Cookie.parseCookies . L.lookup "Cookie" . Wai.requestHeaders genSessionId :: B.ByteString -> T.Time -> Int -> IO B.ByteString genSessionId sname t len = do let dateStr = B.pack $ T.formatTime ":%Y%m%d:" t randomStr <- randomByteString len return $ sname `B.append` dateStr `B.append` randomStr
bigsleep/Wf
wf-session/src/Wf/Control/Eff/Run/Session.hs
mit
4,197
3
16
1,022
1,266
685
581
80
8
main :: IO () main = error "undefined"
mlitchard/cosmos
executable/old.hs
mit
40
0
6
9
19
9
10
2
1
{-# LANGUAGE OverloadedStrings #-} module Bce.BlockChainSerialization where import Bce.Hash import Bce.Crypto import qualified Bce.BlockChain as BlockChain import Bce.BlockChainHash import qualified Data.Binary as Bin import GHC.Generics (Generic) import qualified Data.Binary.Get as BinGet import qualified Data.Aeson as Aeson import qualified Data.Text as Text import qualified Data.Text.Encoding as TextEncoding import qualified Data.ByteString as BS import qualified Data.ByteString.Base16 as B16 instance Bin.Binary Hash instance Bin.Binary PubKey instance Bin.Binary PrivKey instance Bin.Binary KeyPair instance Bin.Binary BlockChain.TxOutputRef instance Bin.Binary BlockChain.TxOutput instance Bin.Binary BlockChain.TxInput instance Bin.Binary BlockChain.Transaction instance Bin.Binary BlockChain.BlockHeader instance Bin.Binary BlockChain.Block instance Aeson.ToJSON BS.ByteString where toJSON bs = Aeson.toJSON (TextEncoding.decodeUtf8 $ B16.encode bs) instance Aeson.FromJSON BS.ByteString where parseJSON (Aeson.String txt) = return $ fst $ B16.decode $ TextEncoding.encodeUtf8 txt instance Aeson.FromJSON Hash instance Aeson.FromJSON PubKey instance Aeson.FromJSON PrivKey instance Aeson.FromJSON BlockChain.TxOutputRef instance Aeson.FromJSON BlockChain.TxOutput instance Aeson.FromJSON BlockChain.TxInput instance Aeson.FromJSON BlockChain.Transaction instance Aeson.FromJSON BlockChain.BlockHeader instance Aeson.FromJSON BlockChain.Block instance Aeson.ToJSON Hash instance Aeson.ToJSON PubKey instance Aeson.ToJSON PrivKey instance Aeson.ToJSON BlockChain.TxOutputRef instance Aeson.ToJSON BlockChain.TxOutput instance Aeson.ToJSON BlockChain.TxInput instance Aeson.ToJSON BlockChain.Transaction instance Aeson.ToJSON BlockChain.BlockHeader instance Aeson.ToJSON BlockChain.Block
dehun/bce
src/Bce/BlockChainSerialization.hs
mit
2,013
0
10
383
473
243
230
46
0
{-# LANGUAGE PackageImports #-} {-# OPTIONS_GHC -fno-warn-dodgy-exports -fno-warn-unused-imports #-} -- | Reexports "Data.Word.Compat" -- from a globally unique namespace. module Data.Word.Compat.Repl.Batteries ( module Data.Word.Compat ) where import "this" Data.Word.Compat
haskell-compat/base-compat
base-compat-batteries/src/Data/Word/Compat/Repl/Batteries.hs
mit
278
0
5
31
29
22
7
5
0
module Streamer.HTTPClient where import Streamer.Util (maybeRead) import Network.URI (parseURI) import Network.Stream (Result) import Network.HTTP.Headers ( replaceHeader , HeaderName(HdrIfNoneMatch, HdrETag) , findHeader ) import qualified Network.HTTP.Base as HB import qualified Network.HTTP as H import qualified Data.ByteString.Lazy as L import qualified Data.ByteString as B import qualified Data.ByteString.Char8 as C httpGetFrameBytes :: String -> IO (Maybe L.ByteString) httpGetFrameBytes url = do -- putStrLn $ "Executing request for URL: " ++ url rsp <- H.simpleHTTP $ simpleLazyRequest url isValid <- validateFrameResponse rsp if isValid == True then H.getResponseBody rsp >>= (\rsBody -> return $ Just rsBody) else putStrLn ("Invalid response for " ++ (show url)) >> return Nothing validateFrameResponse :: Result (H.Response L.ByteString) -> IO Bool validateFrameResponse rsp = do responseCode <- H.getResponseCode rsp if responseCode == (2,0,0) then return True else return False simpleLazyRequest :: String -- ^URL to fetch -> H.Request L.ByteString -- ^The constructed request simpleLazyRequest urlString = case parseURI urlString of Nothing -> error ("simpleLazyRequest: Not a valid URL - " ++ urlString) Just u -> H.mkRequest H.GET u constructFrameURL :: String -> Int -> Int -> String constructFrameURL pIp pPort seqNr = "http://" ++ pIp ++ ":" ++ (show pPort) ++ "/" ++ (show seqNr) ++ ".frame" constructCounterURL :: String -> Int -> String constructCounterURL pIp pPort = "http://" ++ pIp ++ ":" ++ (show pPort) ++ "/counter" httpGetCounter :: String -> B.ByteString -> IO (Maybe (Int, B.ByteString)) httpGetCounter url etg = do maybeResp <- H.simpleHTTP req case maybeResp of Left _ -> return Nothing Right resp -> do let etagValue = getETagFromResponse resp isValid <- validateCounterReponse resp if isValid == True then (assembleResult (maybeRead $ HB.rspBody resp) etagValue) else return Nothing where req = replaceHeader HdrIfNoneMatch (C.unpack etg) $ H.getRequest url assembleResult mCounter etagVal = case mCounter of Just counterVal -> return $ Just (counterVal, etagVal) Nothing -> return $ Nothing getETagFromResponse :: H.Response String -> B.ByteString getETagFromResponse response = case etagValue of Just a -> C.pack a Nothing -> B.empty where etagValue = findHeader HdrETag response validateCounterReponse :: H.Response String -> IO Bool validateCounterReponse rsp = do let responseCode = HB.rspCode rsp if responseCode == (2,0,0) then return True else if responseCode == (3,0,4) then return False -- still valid, but empty response else do putStrLn $ "Error getting counter. Response code: " ++ (show responseCode) return False
adizere/nifty-tree
src/Streamer/HTTPClient.hs
mit
3,306
0
18
1,019
864
446
418
70
4
{-**************************************************************************** * Hamster Balls * * Purpose: Rendering code for lasers * * Author: David, Harley, Alex, Matt * * Copyright (c) Yale University, 2010 * ****************************************************************************-} module Laser where import Common import FRP.Yampa as Yampa import Vec3d import Graphics.Rendering.OpenGL import Control.Monad import Colors laserRad, laserHeight :: GLdouble laserRad = 0.5 laserHeight = 10 laserRadf, laserHeightf :: Float laserRadf = float laserRad laserHeightf = float laserHeight renderLaser :: Laser -> IO () renderLaser l = do loadIdentity preservingMatrix $ do translate $ vector3 $ laserPos l -- Move to cylinder center let drawDir = Vec3d(0,0,1) dir = Yampa.normalize (laserVel l) rotAxis = drawDir `cross` dir rotAngle = acos(dir .* drawDir) / pi * 180 preservingMatrix $ do when (rotAxis /= zeroVector) $ rotate rotAngle $ vector3 rotAxis materialEmission FrontAndBack $= vecToColor (laserColor l) -- make it Emission so that it's not affected by light materialDiffuse FrontAndBack $= colorf Black let style = QuadricStyle (Just Smooth) NoTextureCoordinates Outside FillStyle renderQuadric style $ Cylinder 0.0 laserRad laserHeight 10 10
harley/hamball
src/Laser.hs
mit
1,589
0
18
499
302
155
147
29
1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE UndecidableInstances #-} {-# OPTIONS_HADDOCK show-extensions #-} -- | -- Module : Yi.Keymap.Emacs.Utils -- License : GPL-2 -- Maintainer : yi-devel@googlegroups.com -- Stability : experimental -- Portability : portable -- -- This module is aimed at being a helper for the Emacs keybindings. -- In particular this should be useful for anyone that has a custom -- keymap derived from or based on the Emacs one. module Yi.Keymap.Emacs.Utils ( UnivArgument , argToInt , askQuitEditor , askSaveEditor , modifiedQuitEditor , withMinibuffer , queryReplaceE , isearchKeymap , cabalConfigureE , cabalBuildE , reloadProjectE , executeExtendedCommandE , evalRegionE , readUniversalArg , scrollDownE , scrollUpE , switchBufferE , killBufferE , insertNextC , findFile , findFileReadOnly , findFileNewTab , promptFile , promptTag , justOneSep , joinLinesE , countWordsRegion ) where import Control.Applicative import Control.Lens hiding (re,act) import Control.Monad import Control.Monad.Base import Data.List ((\\)) import Data.Maybe (fromMaybe) import Data.Monoid import qualified Data.Text as T import System.Directory (doesDirectoryExist) import System.FilePath (takeDirectory, takeFileName, (</>)) import System.FriendlyPath () import Yi.Buffer import Yi.Command (cabalConfigureE, cabalBuildE, reloadProjectE) import Yi.Core (quitEditor) import Yi.Editor import Yi.Eval import Yi.File import Yi.Keymap import Yi.Keymap.Keys import Yi.MiniBuffer import Yi.Misc (promptFile) import Yi.Monad import Yi.Rectangle import Yi.Regex import qualified Yi.Rope as R import Yi.Search import Yi.String import Yi.Tag import Yi.Utils type UnivArgument = Maybe Int ---------------------------- -- | Quits the editor if there are no unmodified buffers -- if there are unmodified buffers then we ask individually for -- each modified buffer whether or not the user wishes to save -- it or not. If we get to the end of this list and there are still -- some modified buffers then we ask again if the user wishes to -- quit, but this is then a simple yes or no. askQuitEditor :: YiM () askQuitEditor = askIndividualSave True =<< getModifiedBuffers askSaveEditor :: YiM () askSaveEditor = askIndividualSave False =<< getModifiedBuffers getModifiedBuffers :: YiM [FBuffer] getModifiedBuffers = filterM deservesSave =<< gets bufferSet -------------------------------------------------- -- Takes in a list of buffers which have been identified -- as modified since their last save. askIndividualSave :: Bool -> [FBuffer] -> YiM () askIndividualSave True [] = modifiedQuitEditor askIndividualSave False [] = return () askIndividualSave hasQuit allBuffers@(firstBuffer : others) = void (withEditor (spawnMinibufferE saveMessage (const askKeymap))) where saveMessage = T.concat [ "do you want to save the buffer: " , bufferName , "? (y/n/", if hasQuit then "q/" else "", "c/!)" ] bufferName = identString firstBuffer askKeymap = choice ([ char 'n' ?>>! noAction , char 'y' ?>>! yesAction , char '!' ?>>! allAction , oneOf [char 'c', ctrl $ char 'g'] >>! closeBufferAndWindowE -- cancel ] ++ [char 'q' ?>>! quitEditor | hasQuit]) yesAction = do fwriteBufferE (bkey firstBuffer) withEditor closeBufferAndWindowE continue noAction = do withEditor closeBufferAndWindowE continue allAction = do mapM_ fwriteBufferE $ fmap bkey allBuffers withEditor closeBufferAndWindowE askIndividualSave hasQuit [] continue = askIndividualSave hasQuit others --------------------------- --------------------------- -- | Quits the editor if there are no unmodified buffers -- if there are then simply confirms with the user that they -- with to quit. modifiedQuitEditor :: YiM () modifiedQuitEditor = do modifiedBuffers <- getModifiedBuffers if null modifiedBuffers then quitEditor else withEditor $ void (spawnMinibufferE modifiedMessage (const askKeymap)) where modifiedMessage = "Modified buffers exist really quit? (y/n)" askKeymap = choice [ char 'n' ?>>! noAction , char 'y' ?>>! quitEditor ] noAction = closeBufferAndWindowE ----------------------------- -- isearch selfSearchKeymap :: Keymap selfSearchKeymap = do Event (KASCII c) [] <- anyEvent write . isearchAddE $ T.singleton c searchKeymap :: Keymap searchKeymap = selfSearchKeymap <|> choice [ -- ("C-g", isearchDelE) -- Only if string is not empty. ctrl (char 'r') ?>>! isearchPrevE , ctrl (char 's') ?>>! isearchNextE , ctrl (char 'w') ?>>! isearchWordE , meta (char 'p') ?>>! isearchHistory 1 , meta (char 'n') ?>>! isearchHistory (-1) , spec KBS ?>>! isearchDelE ] isearchKeymap :: Direction -> Keymap isearchKeymap dir = do write $ isearchInitE dir void $ many searchKeymap choice [ ctrl (char 'g') ?>>! isearchCancelE , oneOf [ctrl (char 'm'), spec KEnter] >>! isearchFinishWithE resetRegexE ] <|| write isearchFinishE ---------------------------- -- query-replace queryReplaceE :: YiM () queryReplaceE = withMinibufferFree "Replace:" $ \replaceWhat -> withMinibufferFree "With:" $ \replaceWith -> do b <- gets currentBuffer win <- use currentWindowA let repStr = R.fromText replaceWith replaceKm = choice [ char 'n' ?>>! qrNext win b re , char '!' ?>>! qrReplaceAll win b re repStr , oneOf [char 'y', char ' '] >>! qrReplaceOne win b re repStr , oneOf [char 'q', ctrl (char 'g')] >>! qrFinish ] -- TODO: Yi.Regex to Text Right re = makeSearchOptsM [] (T.unpack replaceWhat) question = T.unwords [ "Replacing", replaceWhat , "with", replaceWith, " (y,n,q,!):" ] withEditor $ do setRegexE re void $ spawnMinibufferE question (const replaceKm) qrNext win b re executeExtendedCommandE :: YiM () executeExtendedCommandE = withMinibuffer "M-x" scope act where act = execEditorAction . T.unpack scope = const $ map T.pack <$> getAllNamesInScope evalRegionE :: YiM () evalRegionE = do -- FIXME: do something sensible. void $ withCurrentBuffer (getSelectRegionB >>= readRegionB) return () -- * Code for various commands -- This ideally should be put in their own module, -- without a prefix, so M-x ... would be easily implemented -- by looking up that module's contents -- | Insert next character, "raw" insertNextC :: UnivArgument -> KeymapM () insertNextC a = do c <- anyEvent write $ replicateM_ (argToInt a) $ insertB (eventToChar c) -- | Convert the universal argument to a number of repetitions argToInt :: UnivArgument -> Int argToInt = fromMaybe 1 digit :: (Event -> Event) -> KeymapM Char digit f = charOf f '0' '9' -- TODO: replace tt by digit meta tt :: KeymapM Char tt = do Event (KASCII c) _ <- foldr1 (<|>) $ fmap (event . metaCh ) ['0'..'9'] return c -- doing the argument precisely is kind of tedious. -- read: http://www.gnu.org/software/emacs/manual/html_node/Arguments.html -- and: http://www.gnu.org/software/emacs/elisp-manual/html_node/elisp_318.html readUniversalArg :: KeymapM (Maybe Int) readUniversalArg = optional ((ctrlCh 'u' ?>> (read <$> some (digit id) <|> pure 4)) <|> (read <$> some tt)) -- | Finds file and runs specified action on the resulting buffer findFileAndDo :: T.Text -- ^ Prompt -> BufferM a -- ^ Action to run on the resulting buffer -> YiM () findFileAndDo prompt act = promptFile prompt $ \filename -> do printMsg $ "loading " <> filename openingNewFile (T.unpack filename) act -- | Open a file using the minibuffer. We have to set up some stuff to -- allow hints and auto-completion. findFile :: YiM () findFile = findFileAndDo "find file:" $ return () -- | Like 'findFile' but sets the resulting buffer to read-only. findFileReadOnly :: YiM () findFileReadOnly = findFileAndDo "find file (read only):" $ readOnlyA .= True -- | Open a file in a new tab using the minibuffer. findFileNewTab :: YiM () findFileNewTab = promptFile "find file (new tab): " $ \filename -> do withEditor newTabE printMsg $ "loading " <> filename void . editFile $ T.unpack filename scrollDownE :: UnivArgument -> BufferM () scrollDownE a = case a of Nothing -> downScreenB Just n -> scrollB n scrollUpE :: UnivArgument -> BufferM () scrollUpE a = case a of Nothing -> upScreenB Just n -> scrollB (negate n) -- | Prompts the user for a buffer name and switches to the chosen buffer. switchBufferE :: YiM () switchBufferE = promptingForBuffer "switch to buffer:" (withEditor . switchToBufferE) (\o b -> (b \\ o) ++ o) -- | Prompts the user for a buffer name and kills the chosen buffer. -- Prompts about really closing if the buffer is marked as changed -- since last save. killBufferE :: YiM () killBufferE = promptingForBuffer "kill buffer:" k (\o b -> o ++ (b \\ o)) where k :: BufferRef -> YiM () k b = do buf <- withEditor . gets $ findBufferWith b ch <- deservesSave buf let askKeymap = choice [ char 'n' ?>>! closeBufferAndWindowE , char 'y' ?>>! delBuf >> closeBufferAndWindowE , ctrlCh 'g' ?>>! closeBufferAndWindowE ] delBuf = deleteBuffer b question = identString buf <> " changed, close anyway? (y/n)" withEditor $ if ch then void $ spawnMinibufferE question (const askKeymap) else delBuf -- | If on separators (space, tab, unicode seps), reduce multiple -- separators to just a single separator (or however many given -- through 'UniversalArgument'). -- -- If we aren't looking at a separator, insert a single space. This is -- like emacs ‘just-one-space’ but doesn't deal with negative argument -- case but works with other separators than just space. What counts -- as a separator is decided by 'isAnySep' modulo @\n@ character. -- -- Further, it will only reduce a single type of separator at once: if -- we have hard tabs followed by spaces, we are able to reduce one and -- not the other. justOneSep :: UnivArgument -> BufferM () justOneSep u = readB >>= \c -> pointB >>= \point -> case point of Point 0 -> if isSep c then deleteSeparators else insertMult c Point x -> if isSep c then deleteSeparators else readAtB (Point $ x - 1) >>= \d -> -- We weren't looking at separator but there might be one behind us if isSep d then moveB Character Backward >> deleteSeparators else insertMult ' ' -- no separators, insert a space just -- like emacs does where isSep c = c /= '\n' && isAnySep c insertMult c = insertN $ R.replicateChar (maybe 1 (max 1) u) c deleteSeparators = do genMaybeMoveB unitSepThisLine (Backward, InsideBound) Backward moveB Character Forward doIfCharB isSep $ deleteB unitSepThisLine Forward -- | Join this line to previous (or next N if universal) joinLinesE :: UnivArgument -> BufferM () joinLinesE Nothing = return () joinLinesE (Just _) = do moveB VLine Forward moveToSol >> transformB (const " ") Character Backward >> justOneSep Nothing -- | Shortcut to use a default list when a blank list is given. -- Used for default values to emacs queries maybeList :: [a] -> [a] -> [a] maybeList def [] = def maybeList _ ls = ls maybeTag :: Tag -> T.Text -> Tag maybeTag def t = if T.null t then def else Tag t -------------------------------------------------- -- TAGS - See Yi.Tag for more info -- | Prompt the user to give a tag and then jump to that tag promptTag :: YiM () promptTag = do -- default tag is where the buffer is on defaultTag <- withCurrentBuffer $ Tag . R.toText <$> readUnitB unitWord -- if we have tags use them to generate hints tagTable <- withEditor getTags -- Hints are expensive - only lazily generate 10 let hinter = return . take 10 . maybe (fail . T.unpack) hintTags tagTable -- Completions are super-cheap. Go wild let completer = return . maybe id completeTag tagTable p = "Find tag: (default " <> _unTag defaultTag `T.snoc` ')' withMinibufferGen "" hinter p completer (const $ return ()) $ -- if the string is "" use the defaultTag gotoTag . maybeTag defaultTag -- | Opens the file that contains @tag@. Uses the global tag table and prompts -- the user to open one if it does not exist gotoTag :: Tag -> YiM () gotoTag tag = visitTagTable $ \tagTable -> case lookupTag tag tagTable of [] -> printMsg $ "No tags containing " <> _unTag tag (filename, line):_ -> openingNewFile filename $ gotoLn line -- | Call continuation @act@ with the TagTable. Uses the global table -- and prompts the user if it doesn't exist visitTagTable :: (TagTable -> YiM ()) -> YiM () visitTagTable act = do posTagTable <- withEditor getTags -- does the tagtable exist? case posTagTable of Just tagTable -> act tagTable Nothing -> promptFile "Visit tags table: (default tags)" $ \path -> do -- default emacs behavior, append tags let p = T.unpack path filename = maybeList "tags" $ takeFileName p tagTable <- io $ importTagTable $ takeDirectory p </> filename withEditor $ setTags tagTable act tagTable -- TODO: use TextUnit to count things inside region for better experience -- | Counts the number of lines, words and characters inside selected -- region. Coresponds to emacs' @count-words-region@. countWordsRegion :: YiM () countWordsRegion = do (l, w, c) <- withEditor $ do t <- withCurrentBuffer $ getRectangle >>= \(reg, _, _) -> readRegionB reg let nls = R.countNewLines t return (if nls == 0 then 1 else nls, length $ R.words t, R.length t) printMsg $ T.unwords [ "Region has", showT l, p l "line" <> "," , showT w, p w "word" <> ", and" , showT c, p w "character" <> "." ] where p x w = if x == 1 then w else w <> "s"
atsukotakahashi/wi
src/library/Yi/Keymap/Emacs/Utils.hs
gpl-2.0
15,159
0
21
4,022
3,280
1,701
1,579
271
5
module SrcTemplateTree where data ParamConfig valueType = SimpleParam | ParamWithDefaultValue valueType | ParamWithHistroy String deriving(Show) data Param = StrParam String String (ParamConfig String) deriving Show data SrcTemplateGroupOptions = SrcTemplateGroupOptions { stgoDescription :: Maybe String } deriving Show data SrcTemplateGroup = SrcTemplateGroup SrcTemplateGroupOptions [Param] [SrcTemplate] deriving Show data SrcTemplate = SrcTemplate [Stmt] String deriving Show data Expr = StrLit String | BoolLit Bool | IntLit Int | Operator String Expr Expr | UnOperator String Expr | FunctionCall String [Expr] | VarExpr String | DefinedExpr String deriving Show data Stmt = AssignmentStmt String Expr | IfStmt Expr [Stmt] [Stmt] deriving Show
thomkoehler/SrcGen
src/SrcTemplateTree.hs
gpl-2.0
1,069
0
9
418
198
116
82
26
0
-- Exercise 7.7Voting algorithms -- Graham Hutton. “Programming in Haskell” votes :: [String] votes = ["Red", "Blue", "Green", "Blue", "Blue", "Red"] count :: Eq a => a -> [a] -> Int count x = length . filter (== x) rmdups :: Eq a => [a] -> [a] rmdups []= [] rmdups (x:xs) = x : rmdups( filter(/=x) xs) result :: Ord a => [a] -> [(Int,a)] result vs = sort [(count v vs, v) | v <- rmdups vs] winner :: Ord a => [a] -> a winner = snd . last . result -- ALTERNATIVE SOLUTION ballots ::   [[String]] ballots = [["Red", "Green"], ["Blue"], ["Green", "Red", "Blue"], ["Blue", "Green", "Red"], ["Green"]] rmempty :: Eq a => [[a]] -> [[a]] rmempty = filter (/= []) elim :: Eq a => a -> [[a]] -> [[a]] elim x = map (filter (/= x)) rank :: Ord a => [[a]] -> [a] rank = map snd . result . map head winner’ :: Ord a => [[a]] -> a winner’ bs = case rank (rmempty bs) of [c]-> c (c:cs) -> winner’ (elim c bs)
jack793/Haskell-examples
Flipped/votes.hs
gpl-3.0
920
7
9
196
520
289
231
-1
-1
module Curves(Point, Curve, Line(..), point, pointX, pointY, curve, connect, rotate, translate, reflect, bbox, height, width, toList, toSVG, toFile, hilbert) where import Text.Printf data Point = Point (Double, Double) deriving (Show) data Curve = Curve Point [Point] deriving (Eq, Show) data Line = Vertical Double | Horizontal Double deriving (Show) instance Eq Point where Point(x1,y1) == Point(x2,y2) = abs(x1 - x2) < 0.01 && abs(y1 -y2) < 0.01 point :: (Double, Double) -> Point point (x, y) = Point (x, y) pointX :: Point -> Double pointX (Point (x, _)) = x pointY :: Point -> Double pointY (Point (_, y)) = y curve :: Point -> [Point] -> Curve curve = Curve connect :: Curve -> Curve -> Curve connect (Curve p1 cs1) (Curve p2 cs2) = curve p1 (cs1 ++ [p2] ++ cs2) rotate :: Curve -> Double -> Curve rotate (Curve p cs) r = curve (rot p) (map rot cs) where rot rotp = let rad = (r * pi) / 180 xnew = pointX rotp * cos rad - pointY rotp * sin rad ynew = pointX rotp * sin rad + pointY rotp * cos rad in point (xnew, ynew) translate :: Curve -> Point -> Curve translate (Curve p cs) newp = curve (trans p) (map trans cs) where trans tp = let distx = pointX newp - pointX p disty = pointY newp - pointY p in point (pointX tp + distx, pointY tp + disty) reflect :: Curve -> Line -> Curve reflect (Curve p cs) l = curve (ref p) (map ref cs) where ref refp = case l of Vertical d -> point(2*d - pointX refp, pointY refp) Horizontal d -> point(pointX refp, 2*d - pointY refp) bbox :: Curve -> (Point, Point) bbox (Curve p cs) = (point (xmin, ymin), point (xmax, ymax)) where (xmin, ymin) = foldl (\ (m,n) (Point (a,b)) -> (min a m, min b n)) (pointX p, pointY p) (p:cs) (xmax, ymax) = foldl (\ (m,n) (Point (a,b)) -> (max a m, max b n)) (pointX p, pointY p) (p:cs) height :: Curve -> Double height c = pointY p2 - pointY p1 where (p1, p2) = bbox c width :: Curve -> Double width c = pointX p2 - pointX p1 where (p1, p2) = bbox c toList :: Curve -> [Point] toList (Curve c cs) = c:cs svgLines :: [Point] -> String svgLines [] = "" svgLines (_:[]) = "" svgLines (p:ps:pss) = "\t\t<line style=\"stroke-width: 2px; stroke: black; fill:white\"" ++ " x1=\"" ++ printf "%.2f" (pointX p) ++ "\" x2=\"" ++ printf "%.2f" (pointX ps) ++ "\" y1=\"" ++ printf "%.2f" (pointY p) ++ "\" y2=\"" ++ printf "%.2f" (pointY ps) ++ "\"></line>\n" ++ svgLines (ps:pss) toSVG :: Curve -> String toSVG c = let w = printf "%d" ((ceiling $ height c)::Integer) h = printf "%d" ((ceiling $ height c)::Integer) svgStart = "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"" ++ w ++ "px\" height=\"" ++ h ++ "px\" version=\"1.1\">\n\t<g>\n" svgEnd = "\t</g>\n</svg>\n" in svgStart ++ svgLines (toList c) ++ svgEnd toFile :: Curve -> FilePath -> IO () toFile c p = writeFile p (toSVG c) hilbert :: Curve -> Curve hilbert c = c0 `connect` c1 `connect` c2 `connect` c3 where w = width c h = height c p = 6 ch = reflect c $ Vertical 0 c0 = ch `rotate` (-90) `translate` point (w+p+w, h+p+h) c1 = c `translate` point (w+p+w, h) c2 = c c3 = ch `rotate` 90 `translate` point (0, h+p)
Rathcke/uni
ap/advanced programming/assignment0/Curves.hs
gpl-3.0
3,623
0
16
1,159
1,610
850
760
82
2
module MLLabs.Validation ( TrainAndTestSets , ValidationStrategy , kfold ) where import MLLabs.Types type TrainAndTestSets obj lbl = (Dataset obj lbl, Dataset obj lbl) type ValidationStrategy obj lbl = Dataset obj lbl -> [TrainAndTestSets obj lbl] -- kfold 3 [1..6] == [([3,4,5,6],[1,2]),([1,2,5,6],[3,4]),([1,2,3,4],[5,6])] kfold :: Int -> ValidationStrategy obj lbl kfold k dat = parts where n = length dat -- size of the first i parts size :: Int -> Int size i | i < 0 = error "invalid size in kfold" | i > k = error "invalid size in kfold" | i < q = i * (p+1) | True = q * (p+1) + (i - q) * p where (p,q) = n `divMod` k splitsAt :: [Int] -> [a] -> [[a]] splitsAt [] xs = [xs] splitsAt (i:is) xs = let (as, bs) = splitAt i xs in as : splitsAt is bs -- trainᵢ = d[0,sᵢ) ++ d[sᵢ₊₁,n) -- testᵢ = d[sᵢ,sᵢ₊₁) parts = flip map [0..k-1] $ \i -> let [tr1, te, tr2] = splitsAt [size i, size (i+1) - size i] dat in (tr1 ++ tr2, te)
zhenyavinogradov/ml-labs
src/MLLabs/Validation.hs
gpl-3.0
1,100
0
18
339
413
220
193
24
2
{- Author: Michal Parusinski Email: mparusinski@googlemail.com License: GPL 3.0 File: OutputProof.hs Description: outputs a latex file that can be inserted in a latex document -} module OutputProof where import System.IO import System.Cmd(system) import System.Exit import Control.Monad import Signature import Proof import ProofSearch --Generates a pdf from a proof outputProof :: ProofTree -> FilePath -> IO () outputProof proof filename = do writeFile (filename++".tex") "" -- helps create a directory createGenericPDF [proof] $ filename++".tex" let command = "pdflatex -halt-on-error -interaction=nonstopmode "++ filename++".tex > /dev/null" code <- system command if code == ExitSuccess then return () else error "Unable to generate a pdf file" getConcepts (cs,_,_) = cs getRule (_,rule,_) = rule getUsed (_,_,used) = used -- Turns a proof tree into a string which will be incorporated inside a latex tree latexify :: ProofTree -> String latexify (NodeZero step) = "[.{"++concepts++end++"\n]" where concepts = niceConceptLatex (getConcepts step) end = "}\n\t[. { $\\bot$ } ]" latexify (NodeOne step tree) = "[.{"++concepts++"}\n\t"++rest++"\n]" where concepts = niceConceptLatex (getConcepts step) rule = " ("++getRule step++") " -- ++" for $"++(conceptToLatex $ getConceptUsed step)++"$) " rest = latexify tree latexify (NodeTwo step left right) = "[.{"++concepts++"}\n\t"++lrest++"\n\t"++rrest++"\n]" where concepts = niceConceptLatex (getConcepts step) rule = " ("++getRule step++") " -- ++" for $"++(conceptToLatex $ getConceptUsed step)++"$) " lrest = latexify left rrest = latexify right -- Turns a proof into a string representing a tree for latex proofToLatexTree :: ProofTree -> String proofToLatexTree prooftree = "\\Tree\n"++latexify prooftree++"\n" -- Takes a proof alongside a location and turns creates a tex file createGenericPDF :: [ProofTree] -> FilePath -> IO () createGenericPDF proofs file = do putStrLn $ "Opening file "++file output <- openFile file WriteMode hPutStrLn output header mapM_ (hPutStrLn output . proofToLatexTree) proofs hPutStrLn output end putStrLn $ "Closing file "++file hClose output where header = "\\documentclass[10pt, a4paper,landscape]{article}\n"++ "\\usepackage{amsmath}\n"++ "\\usepackage{amssymb}\n"++ "\\usepackage{qtree}\n"++ "\\usepackage{fullpage}\n"++ "\\begin{document}\n"++ "\\begin{center}\n" end = "\\end{center}\n"++"\\end{document}" -- Breaks a list into several list of a certain size breakInPieces _ [] = [] breakInPieces size list = result:breakInPieces size rest where (result,rest) = countTo 0 size list countTo _ _ [] = ([],[]) countTo num size (x:xs) | num >= size = ([],x:xs) | otherwise = (newleft, newright) where (oldleft, oldright) = countTo (num+conceptLength x) size xs newleft = x:oldleft newright = oldright -- Outputs in a nice formated format for latex to improve readability niceConceptLatex :: [Concept] -> String niceConceptLatex cs = concatMap fullFormat (init conceptsList) ++ lastFormat (last conceptsList) where conceptsList = breakInPieces 6 cs fullFormat list = "$"++conceptsToLatex list++",$\\\\" lastFormat list = "$"++conceptsToLatex list++"$" -- Way to mesure how long a concept is so we can break out the proof more neatly -- this estimates how a formula will be in latex conceptLength T = 1 conceptLength (Neg T) = 1 conceptLength (Atom a) = length a conceptLength (Neg concept) = 1+conceptLength concept conceptLength (Or c1 c2) = 1+conceptLength c1+conceptLength c2 conceptLength (And c1 c2) = 1+conceptLength c1+conceptLength c2 conceptLength (Exists rel c) = conceptLength c+length rel+1 conceptLength (Forall rel c) = conceptLength c+length rel+1 -- Turns a concept into a nice string (for latex) conceptToLatex :: Concept -> String conceptToLatex T = "\\top" conceptToLatex (Neg T) = "\\bot" conceptToLatex (Atom a) = a conceptToLatex (Neg (Atom a)) = "\\neg "++a conceptToLatex (Neg concept) = "\\neg ("++conceptToLatex concept++")" conceptToLatex (Or (Atom a) (Atom b)) = a++" \\lor "++b conceptToLatex (Or T (Neg T)) = "\\top \\lor \\bot" conceptToLatex (Or (Neg T) T) = "\\bot \\lor \\top" conceptToLatex (Or T (Atom b)) = "\\top \\lor "++b conceptToLatex (Or (Neg T) (Atom b)) = "\\bot \\lor "++b conceptToLatex (Or (Atom a) T) = a++" \\lor \\top" conceptToLatex (Or (Atom a) (Neg T)) = a++" \\lor \\bot" conceptToLatex (Or (Atom a) rc) = a++" \\lor ("++conceptToLatex rc++")" conceptToLatex (Or T rc) = "\\top \\lor ("++conceptToLatex rc++")" conceptToLatex (Or (Neg T) rc) ="\\bot \\lor ("++conceptToLatex rc++")" conceptToLatex (Or lc (Atom a)) = "("++conceptToLatex lc++") \\lor "++a conceptToLatex (Or lc T) = "("++conceptToLatex lc++") \\lor \\top" conceptToLatex (Or lc (Neg T)) = "("++conceptToLatex lc++") \\lor \\bot" conceptToLatex (Or lc rc) = "("++conceptToLatex lc++") \\lor ("++conceptToLatex rc++")" conceptToLatex (And (Atom a) (Atom b)) = a++" \\land "++b conceptToLatex (And T (Neg T)) = "\\top \\land \\bot" conceptToLatex (And (Neg T) T) = "\\bot \\land \\top" conceptToLatex (And T (Atom b)) = "\\top \\land "++b conceptToLatex (And (Neg T) (Atom b)) = "\\bot \\land "++b conceptToLatex (And (Atom a) T) = a++" \\land \\top" conceptToLatex (And (Atom a) (Neg T)) = a++" \\land \\bot" conceptToLatex (And (Atom a) rc) = a++" \\land ("++conceptToLatex rc++")" conceptToLatex (And T rc) = "\\top \\land ("++conceptToLatex rc++")" conceptToLatex (And (Neg T) rc) = "\\bot \\land ("++conceptToLatex rc++")" conceptToLatex (And lc (Atom a)) = "("++conceptToLatex lc++") \\land "++a conceptToLatex (And lc T) = "("++conceptToLatex lc++") \\land \\top" conceptToLatex (And lc (Neg T)) = "("++conceptToLatex lc++") \\land \\bot" conceptToLatex (And lc rc) = "("++conceptToLatex lc++") \\land ("++conceptToLatex rc++")" conceptToLatex (Exists rel (Atom a)) = "\\exists "++rel++". "++a conceptToLatex (Exists rel T) = "\\exists "++rel++". \\top" conceptToLatex (Exists rel (Neg T)) = "\\exists "++rel++". \\bot" conceptToLatex (Exists rel concept) = "\\exists "++rel++". ("++conceptToLatex concept++")" conceptToLatex (Forall rel (Atom a)) = "\\forall "++rel++". "++a conceptToLatex (Forall rel T) = "\\forall "++rel++". \\top" conceptToLatex (Forall rel (Neg T)) = "\\forall "++rel++". \\bot" conceptToLatex (Forall rel concept) = "\\forall "++rel++". ("++conceptToLatex concept++")" conceptsToLatex :: [Concept] -> String conceptsToLatex [] = "" conceptsToLatex [concept] = conceptToLatex concept conceptsToLatex list = iterator list where iterator [] = "" -- this shoudln't occur iterator [concept] = conceptToLatex concept iterator (c:cs) = conceptToLatex c++","++conceptsToLatex cs
j5b/ps-pc
OutputProof.hs
gpl-3.0
7,299
0
12
1,610
2,355
1,176
1,179
124
3
{-# LANGUAGE CPP #-} module Constants where import Data.String import System.Environment.XDG.BaseDir import System.FilePath import System.Directory import System.IO import System.Process import Control.Concurrent import Control.Exception import Control.Monad #ifdef CABAL_PATH import Paths_apelsin hiding (getDataDir) #endif configName, programName, fullProgramName :: IsString s => s configName = "apelsin" programName = "Apelsin" fullProgramName = "Apelsin Tremulous Browser" inCacheDir, inConfDir :: FilePath -> IO FilePath inCacheDir x = do dir <- getUserCacheDir configName createDirectoryIfMissing True dir return (dir </> x) inConfDir x = do dir <- getUserConfigDir configName createDirectoryIfMissing True dir return (dir </> x) getDataDir :: IO FilePath #ifdef CABAL_PATH getDataDir = dropTrailingPathSeparator `fmap` getDataFileName "" #else getDataDir = getCurrentDirectory #endif trace :: String -> IO () defaultBrowser :: String -> IO CreateProcess #if defined(mingw32_HOST_OS) || defined(__MINGW32__) trace _ = return () defaultBrowser x = do ddir <- getDataDir return (proc "wscript" [ddir </> "open.js", x]) #else trace x = hPutStrLn stderr x >> hFlush stderr #if defined(__APPLE__) || defined(__MACH__) defaultBrowser x = return $ proc "open" [x] #else defaultBrowser x = return $ proc "xdg-open" [x] #endif #endif openInBrowser :: String -> IO () openInBrowser x = handle (\(_ :: IOError) -> return ()) $ do p <- defaultBrowser x (_,_,_,hdl) <- createProcess p {close_fds = True} -- The following hack is needed to avoid ghost processes because of: -- http://hackage.haskell.org/trac/ghc/ticket/2123 forkIO $ void $ waitForProcess hdl return () spacing, spacingHalf, spacingBig, spacingHuge :: Integral i => i spacingHalf = 2 spacing = 4 spacingBig = 8 spacingHuge = 12
Cadynum/Apelsin
src/Constants.hs
gpl-3.0
1,823
12
11
280
456
246
210
-1
-1
import Prelude hiding (putStrLn) import Control.Monad import Control.Monad.Progress import Control.Monad.Writer import Data.List import Data.Text (Text) import qualified Data.Text as Text import Data.Text.IO import Data.Time import Data.Version import qualified Graphics.Forensics.Analysers as Analysers import qualified Graphics.Forensics.Analyser as Analyser import qualified Graphics.Forensics.Image as Image import qualified Graphics.Forensics.Report as Report import System.Console.ANSI import System.Console.CmdArgs.Implicit import System.Environment as Environment import System.IO (stderr) import System.Locale import qualified Data.Set as Set import Graphics.Forensics.Report data RunMode = ModeAnalyse { modeAnalyser :: String , modeFile :: String } | ModeList | ModeInfo { modeAnalyser :: String } deriving (Show, Data, Typeable) main :: IO () main = do pname <- Environment.getProgName m <- cmdArgs_ $ makeModes pname :: IO RunMode case m of ModeAnalyse analyser file -> doAnalysis analyser file ModeList -> listAnalysers ModeInfo analyser -> showAnalyserInfo analyser listAnalysers :: IO () listAnalysers = forM_ Analysers.analysers printAnalyserName where printAnalyserName = putStrLn . Analyser.name showAnalyserInfo :: String -> IO () showAnalyserInfo analyserName = case maybeAnalyser of Nothing -> putErrLn "There is no such analyser installed" Just analyser -> do putStrLn . Text.append "Name: " . Analyser.name $ analyser putStrLn . Text.append "Author: " . Analyser.author $ analyser putStrLn . Text.append "Version: " . Text.pack . showVersion . Analyser.version $ analyser where maybeAnalyser = findAnalyser analyserName findAnalyser :: String -> Maybe (Analyser.Analyser Image.ByteImage) findAnalyser analyserName = find hasRightName Analysers.analysers where foldName = Text.toCaseFold . Text.pack $ analyserName hasRightName = (== foldName) . Text.toCaseFold . Analyser.name doAnalysis :: String -> String -> IO () doAnalysis analyserName fileName = case maybeAnalyser of Nothing -> putErrLn "There is no such analyser installed" Just analyser -> do image <- Image.readImage fileName runAnalysis mempty $ Analyser.analyse analyser image where maybeAnalyser = findAnalyser analyserName runAnalysis :: Report.Report -> Analyser.Analysis () -> IO () runAnalysis currReport analysis = case result of Left (cont, stack) -> do whenLoud $ renderTaskStack stack runAnalysis report cont Right () -> whenLoud $ do hClearFromCursorToScreenEnd stderr saveReport report putErrLn "Done." where (result, newReport) = runWriter . runProgressT $ analysis report = currReport `mappend` newReport saveReport :: Report -> IO () saveReport = mapM_ processReportEntry . Set.toList processReportEntry :: ReportEntry -> IO () processReportEntry (ReportEntry _ message dat) = do putStrLn message saveReportData dat saveReportData :: ReportData -> IO () saveReportData (ReportNothing) = return () saveReportData (ReportImage i) = do timestamp <- getTime Image.writeImage ("output/output-" ++ timestamp ++ ".png") i saveReportData _ = return () getTime :: IO (String) getTime = liftM2 utcToLocalTime getCurrentTimeZone getCurrentTime >>= return . formatTime defaultTimeLocale "%y%m%d-%H%M%S" renderTaskStack :: TaskStack Text -> IO () renderTaskStack stackRev = do hHideCursor stderr when currentIsNew $ do putErrLn . renderNewTask numberOfTasks $ curr hClearFromCursorToScreenEnd stderr forM_ stack $ putErrLn . renderTask hClearFromCursorToScreenEnd stderr replicateM_ numberOfTasks moveUpTwice hShowCursor stderr where curr = head stackRev currentIsNew = taskStep curr == 0 stack = reverse stackRev numberOfTasks = length stack moveUpTwice = hCursorUpLine stderr 2 renderNewTask :: Int -> Task Text -> Text renderNewTask level t = Text.replicate level "-" <> "> " <> taskLabel t renderTask :: Task Text -> Text renderTask t = taskLabel t <> "\n" <> makeProgress t makeProgress :: Task a -> Text makeProgress t = "[" <> bar <> "]" where ratio = (fromIntegral . taskStep $ t) / (fromIntegral . taskTotalSteps $ t) :: Double barElemCount = round . (* 78) $ ratio restElemCount = 78 - barElemCount barElems = Text.replicate barElemCount "=" restElems = Text.replicate restElemCount " " bar = barElems <> restElems putErrLn :: Text -> IO () putErrLn = hPutStrLn stderr makeModes :: String -> Annotate Ann makeModes pname = modes_ [ record (ModeAnalyse "" "") [ modeAnalyser := def += typ "ANALYSER" += argPos 0 , modeFile := def += typ "IMAGE" += argPos 1 ] += help "Analyses an image with the specified analyser" += name "analyse" , record ModeList [] += help "Lists all available analysers" += name "list" , record (ModeInfo "") [ modeAnalyser := def += typ "ANALYSER" += argPos 0 ] += help "Shows information about the specified analyser" += name "info" ] += program pname += summary (pname ++ " v0.1") += verbosity
Purview/purview
src/Graphics/Forensics/Runner/Console.hs
gpl-3.0
5,272
0
16
1,130
1,509
760
749
158
3
module CatanProject where import System.Random import System.Random.Shuffle (shuffle') import Data.List import Data.Maybe import Text.Printf -- Settlers -- a turn has mulitple -- stages, some of which might -- include all players -- so that makes it a little more -- complex than just a simple set of -- moves -- there can be up to 4 players -- data Player -- = Player1 | Player2 | Player3 | Player4 -- deriving(Show) -- A player has: -- A set of buildable tokens (15 roads, 3 settlements, 3 cities) -- A hand of resource cards -- A collection of development cards in hand -- A collection of development cards played -- A turn order -- A number of victory points data Player = Player { id :: Int -- Player number (eg: Player 1, Player 2, etc) , turn :: Int -- Assigned at the beginning of the game , resourcehand :: ResourceHand -- Resources the player has , devcardhand :: DevCardHand -- Unplayed dev cards , activedevcards :: DevCardHand -- dev cards player has used, eg: 3 knights , victorypoints :: Int -- total victory points } deriving (Show,Eq) -- a player's hand of resources is a list of resource cards type ResourceHand = [ResourceCard] -- a players devcard hand is a list of development cards type DevCardHand = [DevCard] -- a resource card has an id Int, and a Resource type type ResourceCard = (Int, Resource) -- a resource card has an id Int and a card type -- types are: -- knight -- victory point -- road building -- monopoly -- year of plenty data DevCardValue = K | VP | RB | M | YOP deriving(Show, Eq) type DevCard = (Int, DevCardValue) -- A move consists a player and each phase -- An initial game also counts as a move data SCMove = MovePlayer SCRollPhase SCResourcesPhase SCTradePhase SCBuildPhase | InitBoard deriving(Show) -- The Roll phase is just an integer -- The result of 2d6 being rolled type SCRollPhase = Int -- The Resource Phase is a list of resources -- added to each player type SCResourcesPhase = [(Player, ResourceSet)] -- The Trade phase is a list of Trades type SCTradePhase = [Trade] -- A trade consists of -- Player1 -- Player2 (or a port or the bank) -- ResourceSet1 (resources going from P1 to P2) -- ResourceSet2 (resources going from P2 to P1) type Trade = (Player, TradeEntity, ResourceSet, ResourceSet) data TradeEntity = TEPlayer Player | SCPort | Bank deriving(Show) -- ResourceSet is number of Grain, Bricks, Sheep, Wood, and Ore type ResourceSet = (Int, Int, Int, Int, Int) type SCBuildPhase = [(Player, Building, ResourceSet)] -- This represents adding a buidling to the board -- Either place a new settlement or a new city at Node ID data Building = NewSettlement Int | NewCity Int deriving(Show) data SCResource = Desert | Land Resource | Water SCPort deriving(Show) data SCPort = Wildcard | PBrick | PGrain | PWood | POre | PSheep deriving(Show) data Resource = Brick | Grain | Wood | Ore | Sheep deriving(Show, Eq) -- tools to build up the initial board initType a | a <= 3 = Land Brick | a <= 7 = Land Grain | a <= 11 = Land Wood | a <= 14 = Land Ore | otherwise = Land Sheep init_typelist = (Desert:[initType x | x <- [1..18]]) -- Note -- this isn't really random, but we could change the seed up shuffle_seed = 10 shuffled_typelist seed = shuffle' init_typelist (length init_typelist) (mkStdGen seed) -- a board consists of: -- a boardID int, -- a list of nodes [SCNode], -- a list of HexTiles that span those nodes, [HexTile], -- a list of road edges that span those nodes, [RoadEdge] type SCBoard = (Int, [SCNode], [HexTile], [RoadEdge]) -- an edge connects nodes on the board -- we have 2 types of edges -- Road Edge -- which has an id, maybe a road, and two connected noddes type RoadEdge = (Int, MaybeSCRoad, Int, Int) -- Land Edge which has an ID -- a number representing its dice -- and a group of connected nodes (as ids) type HexTile = (Int, SCResource, Int, NodeList) -- A nodelist is a tuple of 6 SCNode ids -- starting from top and moving clockwise -- so (Up, UR, DR, Down, DL, UL) type NodeList = (Int, Int, Int, Int, Int, Int) data MaybeSCRoad = NoRoad | ARoad Player deriving(Show) data MaybeSCBuilding = NoBuilding| Settlement Player | City Player deriving(Show) -- An SCNode has an ID and possibly a building type SCNode = (Int, MaybeSCBuilding) emptyboard :: SCBoard emptyboard = (1, [], [], [] ) nodeforid :: Int -> SCBoard -> Maybe SCNode nodeforid id (_, nodes, _, _) = find (\ (nid, _) -> nid == id) nodes hextileforid :: Int -> SCBoard -> Maybe HexTile hextileforid id (_, _, hextiles, _) = find (\ (lid, _, _, _) -> lid == id) hextiles roadedgeforid :: Int -> SCBoard -> Maybe RoadEdge roadedgeforid id (_, _, _, roads) = find (\ (rid, _, _, _) -> rid == id) roads -- hextiletoleft returns the the hextile to the left of a given input hextile -- or none if this is the leftmost -- or none if this is not in hextiletoleft :: HexTile -> SCBoard -> Maybe HexTile hextiletoleft (_, _, _, (_, _, _, _, dl, ul)) (_, _, hextiles, _) = find (\ (_, _, _, (_, ur, dr, _, _, _)) -> ur == ul && dr == dl) hextiles -- hextiletoright returns the the hextile to the right of a given input hextile -- or none if this is the right edge -- or none if this is not in hextiletoright :: HexTile -> SCBoard -> Maybe HexTile hextiletoright (_, _, _, (_, ur, dr, _, _, _)) (_, _, hextiles, _) = find (\ (_, _, _, (_, _, _, _, dl, ul)) -> ur == ul && dr == dl) hextiles -- hextiletoupright returns the hextile up and to the right -- or none if this is at an edge of the board hextiletoupright :: HexTile -> SCBoard -> Maybe HexTile hextiletoupright (_, _, _, (top, ur, _, _, _, _)) (_, _, hextiles, _) = find (\ (_, _, _, (_, _, _, down, dl, _)) -> top == dl && ur == down) hextiles -- hextiletodownleft returns the hextile down and to the left -- or none if this is at an edge of the board hextiletodownleft :: HexTile -> SCBoard -> Maybe HexTile hextiletodownleft (_, _, _, (_, _, _, dn, dl, _)) (_, _, hextiles, _) = find (\ (_, _, _, (top, ur, _, _, _, _)) -> top == dl && ur == dn) hextiles -- hextiletodownright returns the hextile down and to the right -- or none if this is at an edge of the board hextiletodownright :: HexTile -> SCBoard -> Maybe HexTile hextiletodownright (_, _, _, (_, _, dr, down, _, _)) (_, _, hextiles, _) = find (\ (_, _, _, (top, _, _, _, _, ul)) -> down == ul && dr == top) hextiles -- hextiletoupleft returns the hextile down and to the left -- or none if this is at an edge of the board hextiletoupleft :: HexTile -> SCBoard -> Maybe HexTile hextiletoupleft (_, _, _, (top, _, _, _, _, ul)) (_, _, hextiles, _) = find (\ (_, _, _, (_, _, dr, down, _, _)) -> down == ul && dr == top) hextiles -- roadsforrange creates roads for a group of id numbers -- assumption is you pass the start of a range of 6 consecutive ids -- so this is only really useful for the first tile roadedgesforrange nodestart startid = (startid + 5, NoRoad, nodestart + 5, nodestart):([(startid + x, NoRoad, nodestart + x, nodestart + 1 + x)| x <- [0..4]]) -- build board takes a random seed and -- generates a fresh settlers board buildboard :: Int -> SCBoard buildboard seed = boardwithlist (shuffled_typelist seed) starting_tile_numbers starting_directions emptyboard starting_tile_numbers = [5, 2, 6, 3, 8, 10, 9, 12, 11, 4, 8, 10, 9, 4, 5, 6, 3, 11] -- boardwithlist generateds a board from a resource list -- it adds a new hextile and its associated edges and nodes boardwithlist :: [SCResource] -> [Int] -> [Direction] -> SCBoard -> SCBoard boardwithlist [] _ _ board = board boardwithlist _ [] _ board = error "Not enough tile numbers" boardwithlist _ _ [] board = error "Not enough directions" boardwithlist (Desert:rs) tlist (d:ds) board = boardwithlist rs tlist ds (addhextile board Desert 7 d) boardwithlist (r:rs) (x:xs) (d:ds) board = boardwithlist rs xs ds (addhextile board r x d) -- hextiles get added in a spiral data Direction = UR | R | DR | DL | L | UL deriving(Show) -- directions to add starting_directions = [UR, -- the first direction can be anything DL, DL, DR, DR, R, -- This is where an error happens R, UR, UR, UL, UL, L, -- outer ring DL, DL, DR, R, UR, UL, -- inner ring DL] -- center -- find the last hextile added in a board (the one with the highest id) lasthextileadded :: SCBoard -> Maybe HexTile lasthextileadded (_, _, [], _) = Nothing lasthextileadded (_, _, (x:_), _) = Just x addhextile :: SCBoard -> SCResource -> Int -> Direction -> SCBoard addhextile board hextile rollno dir = let prev = lasthextileadded board in case prev of Nothing -> addfirsthextile hextile rollno Just pl -> addnexthextilecheck board hextile rollno pl dir -- addnexthextilecheck checks if the next hextile to add exists, then continues addnexthextilecheck :: SCBoard -> SCResource -> Int -> HexTile -> Direction -> SCBoard addnexthextilecheck board res rollno lasthextile dir = let (_,_,lands,_) = board count = length lands result = addnexthextile board res rollno lasthextile dir chk1 = hextileindirb lasthextile dir board chk2 = hextileindirb lasthextile dir result in case (chk1, chk2) of (Just any, _) -> error (printf "Land already exists: %d lands placed\n %s\n%s\n%s\n" count (show any) (show lasthextile) (show board)) (Nothing, Nothing) -> error (printf "placed in wrong direction, expected %s\n%s" (show dir) (show result)) (Nothing, Just any) -> result -- add first hextile to a brand new board addfirsthextile :: SCResource -> Int -> SCBoard addfirsthextile hextile rollno = (14, [(id, NoBuilding)| id <- [2..7]], [(1, hextile, rollno, (2,3,4,5,6,7))], (roadedgesforrange 2 8)) -- addnexthextile has to do a lot of things -- 1. It needs to place a new hextile on the board -- 2. It needs to look back from the previous tile to find and nodes -- that the hextile should be connected to (we can do this by -- walking around the tile from the previous tile -- 3. It needs to add nodes and roadedges for any nodes -- that are not already there addnexthextile :: SCBoard -> SCResource -> Int -> HexTile -> Direction -> SCBoard addnexthextile (id, nodes, hextiles, roads) hextile rollno prevhextile direction = let existingnodes = getexistingnodeschk prevhextile direction hextiles (newnodes, newnodeset) = add_needed_nodes existingnodes (id + 1) nodesneeded = length newnodes newedges = makeneedededges newnodeset roads (id + 1 + nodesneeded) edgesneeded = length newedges in (id + 1 + nodesneeded + edgesneeded, newnodes ++ nodes, (id, hextile, rollno, newnodeset):hextiles, newedges ++ roads) -- getexistingnodeschk wraps getexisting nodes and errors if there -- aren't at least 2 fields set getexistingnodeschk :: HexTile -> Direction -> [HexTile]-> NodeList getexistingnodeschk ht dir hts = let newnodeset = getexistingnodes ht dir hts (a,b,c,d,e,f) = newnodeset count = length (filter (\ x -> x /= 0) [a,b,c,d,e,f]) chkvals = (\ x y -> if (x == 0 || y == 0) then (error (printf "chk failed %s%s" (show newnodeset) (show dir))) else newnodeset) in case ((count < 2), dir) of (True, _) -> error "there sould be at least 2 nodes" (_, UR) -> chkvals d e (_, R) -> chkvals e f (_, DR) -> chkvals a f (_, DL) -> chkvals a b (_, L) -> chkvals b c (_, UL) -> chkvals c d -- fill in each slot in the nodeset for a hextile with 0 if there -- input direction is the direction we moved in to get to the new node -- is no node for it, or the node's id if there is getexistingnodes :: HexTile -> Direction -> [HexTile]-> NodeList -- first add the ones from the previous edge -- then use a recursive helper to look for more {- I don't actually need to flip this do I? getexistingnodes le dir hextiles = let (sid, _, _, (up, ur, dr, dn, dl, ul)) = le in case dir of UR -> existingnodeshelper le sid (sharednodes le DL) DLhextiles R -> existingnodeshelper le sid (sharednodes le L) L hextiles DR -> existingnodeshelper le sid (sharednodes le UL) UL hextiles DL -> existingnodeshelper le sid (sharednodes le UR) UR hextiles L -> existingnodeshelper le sid (sharednodes le R) R hextiles UL -> existingnodeshelper le sid (sharednodes le DR) DR hextiles -} getexistingnodes le dir hextiles = let (sid,_, _, _) = le in existingnodeshelper le sid (sharednodes le dir) dir hextiles -- fill in a node list with just the nodes facing -- direction (and flip them so it is from the new node's perspective) sharednodes :: HexTile -> Direction -> NodeList sharednodes (_, _, _, (up, ur, dr, dn, dl,ul)) dir = case dir of UR -> (0,0,0,ur,up,0) R -> (0,0,0,0,dr,ur) DR -> (dr,0,0,0,0,dn) DL -> (dl,dn,0,0,0,0) L -> (0,ul,dl,0,0,0) UL -> (0,0,up,ul,0,0) -- takes a current HexTile -- an id (this is the start, so we don't get stuck in an infinite loop -- a direction (this time the direction of the new hextile) -- and returns a nodelist for the new hextile, with 0 for any nodes -- that dont yet exist, and ids for those that do existingnodeshelper :: HexTile -> Int -> NodeList -> Direction -> [HexTile] -> NodeList existingnodeshelper le sid nl dir hextiles = nodeunify (enodescw le sid nl dir hextiles) (enodesccw le sid nl dir hextiles) -- choose non-zero items for each elem in a nodelist nodeunify :: NodeList -> NodeList -> NodeList nodeunify (a1,b1,c1,d1,e1,f1) (a2,b2,c2,d2,e2,f2) = let nz = (\ a b -> if (a /= 0) then a else b) in ((nz a1 a2), (nz b1 b2), (nz c1 c2), (nz d1 d2), (nz e1 e2), (nz f1 f2)) -- cw_move input_dir -- input_dir is a direction facing in towards the centre -- of clockwise ring -- returns (go, in) -- go is the next direction to go in a clockwise ring -- in is the direction facing towards the centre cw_move :: Direction -> (Direction, Direction) cw_move UR = (UL, R) cw_move R = (UR, DR) cw_move DR = (R, DL) cw_move DL = (DR, L) cw_move L = (DL, UL) cw_move UL = (L, UR) -- ccw_move input_dir -- input_dir is a direction facing in towards the centre -- of clockwise ring -- returns (go, in) -- go is the next direction to go in a clockwise ring around the new -- node's locaiton -- in is the direction facing towards the centre from the next position ccw_move :: Direction -> (Direction, Direction) ccw_move UR = (R, UL) ccw_move UL = (UR, L) ccw_move L = (UL, DL) ccw_move DL = (L, DR) ccw_move DR = (DL, R) ccw_move R = (DR, UR) -- search clockwise for points around a space enodescw :: HexTile -> Int -> NodeList -> Direction -> [HexTile] -> NodeList enodescw current sid acc dir hextiles = let (go, indir) = cw_move dir in case (hextileindir current go hextiles) of Nothing -> acc Just le -> let (id, _, _,_) = le in if (sid == id) then acc else (enodescw le sid (nodeunify acc (sharednodes le indir)) indir hextiles) -- search counterclockwise for points around a space enodesccw :: HexTile -> Int -> NodeList -> Direction -> [HexTile] -> NodeList enodesccw current sid acc dir hextiles = let (go, indir) = ccw_move dir in case (hextileindir current go hextiles) of Nothing -> acc Just le -> let (id, _, _,_) = le in if (sid == id) then acc else (enodesccw le sid (nodeunify acc (sharednodes le indir)) indir hextiles) -- get a hextile in a direction hextileindirb:: HexTile -> Direction -> SCBoard -> Maybe HexTile hextileindirb le dir board = case dir of UR -> hextiletoupright le board R -> hextiletoright le board DR -> hextiletodownright le board DL -> hextiletodownleft le board L -> hextiletoleft le board UL -> hextiletoupleft le board hextileindir :: HexTile -> Direction -> [HexTile] -> Maybe HexTile hextileindir le dir hextiles= let fakeboard = (0, [], hextiles, []) in case dir of UR -> hextiletoupright le fakeboard R -> hextiletoright le fakeboard DR -> hextiletodownright le fakeboard DL -> hextiletodownleft le fakeboard L -> hextiletoleft le fakeboard UL -> hextiletoupleft le fakeboard -- given a nodeset, return a list of empty nodes for each -- 0 value, starting with id add_needed_nodes :: NodeList -> Int -> ([SCNode], NodeList) add_needed_nodes nl id = add_needed_nodes_helper [] nl id -- recursive helper add_needed_nodes_helper :: [SCNode] -> NodeList -> Int -> ([SCNode], NodeList) add_needed_nodes_helper acc (up, ur, dr, dn, dl, ul) id | up == 0 = add_needed_nodes_helper ((id, NoBuilding):acc) (id, ur, dr, dn, dl, ul) (id + 1) | ur == 0 = add_needed_nodes_helper ((id, NoBuilding):acc) (up, id, dr, dn, dl, ul) (id + 1) | dr == 0 = add_needed_nodes_helper ((id, NoBuilding):acc) (up, ur, id, dn, dl, ul) (id + 1) | dn == 0 = add_needed_nodes_helper ((id, NoBuilding):acc) (up, ur, dr, id, dl, ul) (id + 1) | dl == 0 = add_needed_nodes_helper ((id, NoBuilding):acc) (up, ur, dr, dn, id, ul) (id + 1) | ul == 0 = add_needed_nodes_helper ((id, NoBuilding):acc) (up, ur, dr, dn, dl, id) (id + 1) | (length acc) > 4 = error "too many nodes" | otherwise = (acc, (up, ur, dr, dn, dl, ul)) -- given a nodeset, create empty RoadEdges for any that don't exist -- starting with id makeneedededges :: NodeList -> [RoadEdge] -> Int -> [RoadEdge] makeneedededges nl roads id = needededgeshelper [] (neededpairs nl) roads id needededgeshelper :: [RoadEdge] -> [(Int, Int)] -> [RoadEdge] -> Int -> [RoadEdge] needededgeshelper acc [] _ _ = acc needededgeshelper acc ((n1, n2):pairs) roads id = case (findroad n1 n2 roads) of Just _ -> needededgeshelper acc pairs roads id Nothing -> needededgeshelper ((id, NoRoad, n1, n2):acc) pairs roads (id + 1) -- find a road connecting 2 points findroad :: Int -> Int -> [RoadEdge] -> Maybe RoadEdge findroad a b roads = find (\ (_, _, x, y) -> (x == a && y == b) || (x == b && y == a)) roads -- List all the pairs of nodes needed from a nodelist neededpairs :: NodeList -> [(Int, Int)] neededpairs (a, b, c, d, e,f) = [(a,b), (b, c), (c,d), (d,e), (e,f), (f,a)] -- validate checks a board to make sure it meets certain criteria data TestResult = OK | Failure [Char] deriving( Show ) validate :: SCBoard -> [TestResult] validate b = [right_number_of_lands b, right_number_of_nodes b, same_number_nodes_as_lands b, right_number_of_outside_nodes b] right_number_of_lands :: SCBoard -> TestResult right_number_of_lands (_, _, lands, _) | (length lands) == 19 = OK | otherwise = Failure (printf "Expected 19 hexes, but there are %d" (length lands)) right_number_of_nodes :: SCBoard -> TestResult right_number_of_nodes (_, nodes, _, _) | (length nodes) == 55 = OK | otherwise = Failure (printf "Expected 55 nodes, but there are %d" (length nodes)) -- checks if there are the same number of unique nodes as there are in the same_number_nodes_as_lands :: SCBoard -> TestResult same_number_nodes_as_lands (_, nodes, lands, _) = let n_nodes = length nodes n_lands = count_unique_nodes_in_lands lands [] in if (n_lands == n_nodes) then OK else Failure (printf "%d nodes, %d unique nodes in HexTiles" n_nodes n_lands) count_unique_nodes_in_lands :: [HexTile] -> [Int]-> Int count_unique_nodes_in_lands [] acc = length acc count_unique_nodes_in_lands (l:ls) acc = let (_,_,_, (a,b,c,d,e,f)) = l in count_unique_nodes_in_lands ls (add_nl_uniques [a,b,c,d,e,f] acc) -- given a list of numbers that may not be unique -- and an accumulator of unique numbers, -- return a list of all unique numbers add_nl_uniques :: [Int] -> [Int] -> [Int] add_nl_uniques lst acc = foldl (\ a e -> if (elem e a) then a else (e:a)) acc lst no_duplicate_roads :: SCBoard -> TestResult no_duplicate_roads (_,_,_,roads) = duproadhelper roads [] duproadhelper :: [RoadEdge] -> [(Int,Int)] -> TestResult duproadhelper [] acc = OK duproadhelper (x:xs) acc = let (_, _, a, b) = x in if ((elem (a, b) acc) || (elem (b,a) acc)) then Failure "Duplicate roads detected" else duproadhelper xs ((a,b):acc) lands_connected_to_node :: SCBoard -> Int -> [HexTile] lands_connected_to_node (_, _, lands, _) id = foldl (landconnectedhelper id) [] lands landconnectedhelper :: Int -> [HexTile] -> HexTile -> [HexTile] landconnectedhelper id acc nxt = let (_, _, _, (a,b,c,d,e,f)) = nxt in if (elem id [a,b,c,d,e,f]) then (nxt:acc) else acc all_lands_connected :: SCBoard -> [[HexTile]] all_lands_connected board = let (_, nodes, _, _) = board in map (\ (id, _) -> (lands_connected_to_node board id)) nodes right_number_of_outside_nodes :: SCBoard -> TestResult right_number_of_outside_nodes board = let (_, nodes, _, _) = board connected = map (\ (id, _) -> (lands_connected_to_node board id)) nodes counts = map length connected just2 = filter (\a -> a == 2 || a == 1) counts total = length just2 in if (total == 30) then OK else (Failure (printf "total %d, expected 30" total)) -- unit tests
tyh0/312-Catan-Project
Main.hs
gpl-3.0
21,167
0
18
4,558
6,455
3,690
2,765
337
8
{-# 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.Jobs.Projects.Tenants.Patch -- 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 specified tenant. -- -- /See:/ <https://cloud.google.com/talent-solution/job-search/docs/ Cloud Talent Solution API Reference> for @jobs.projects.tenants.patch@. module Network.Google.Resource.Jobs.Projects.Tenants.Patch ( -- * REST Resource ProjectsTenantsPatchResource -- * Creating a Request , projectsTenantsPatch , ProjectsTenantsPatch -- * Request Lenses , ptpXgafv , ptpUploadProtocol , ptpUpdateMask , ptpAccessToken , ptpUploadType , ptpPayload , ptpName , ptpCallback ) where import Network.Google.Jobs.Types import Network.Google.Prelude -- | A resource alias for @jobs.projects.tenants.patch@ method which the -- 'ProjectsTenantsPatch' request conforms to. type ProjectsTenantsPatchResource = "v4" :> Capture "name" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "updateMask" GFieldMask :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] Tenant :> Patch '[JSON] Tenant -- | Updates specified tenant. -- -- /See:/ 'projectsTenantsPatch' smart constructor. data ProjectsTenantsPatch = ProjectsTenantsPatch' { _ptpXgafv :: !(Maybe Xgafv) , _ptpUploadProtocol :: !(Maybe Text) , _ptpUpdateMask :: !(Maybe GFieldMask) , _ptpAccessToken :: !(Maybe Text) , _ptpUploadType :: !(Maybe Text) , _ptpPayload :: !Tenant , _ptpName :: !Text , _ptpCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ProjectsTenantsPatch' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ptpXgafv' -- -- * 'ptpUploadProtocol' -- -- * 'ptpUpdateMask' -- -- * 'ptpAccessToken' -- -- * 'ptpUploadType' -- -- * 'ptpPayload' -- -- * 'ptpName' -- -- * 'ptpCallback' projectsTenantsPatch :: Tenant -- ^ 'ptpPayload' -> Text -- ^ 'ptpName' -> ProjectsTenantsPatch projectsTenantsPatch pPtpPayload_ pPtpName_ = ProjectsTenantsPatch' { _ptpXgafv = Nothing , _ptpUploadProtocol = Nothing , _ptpUpdateMask = Nothing , _ptpAccessToken = Nothing , _ptpUploadType = Nothing , _ptpPayload = pPtpPayload_ , _ptpName = pPtpName_ , _ptpCallback = Nothing } -- | V1 error format. ptpXgafv :: Lens' ProjectsTenantsPatch (Maybe Xgafv) ptpXgafv = lens _ptpXgafv (\ s a -> s{_ptpXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). ptpUploadProtocol :: Lens' ProjectsTenantsPatch (Maybe Text) ptpUploadProtocol = lens _ptpUploadProtocol (\ s a -> s{_ptpUploadProtocol = a}) -- | Strongly recommended for the best service experience. If update_mask is -- provided, only the specified fields in tenant are updated. Otherwise all -- the fields are updated. A field mask to specify the tenant fields to be -- updated. Only top level fields of Tenant are supported. ptpUpdateMask :: Lens' ProjectsTenantsPatch (Maybe GFieldMask) ptpUpdateMask = lens _ptpUpdateMask (\ s a -> s{_ptpUpdateMask = a}) -- | OAuth access token. ptpAccessToken :: Lens' ProjectsTenantsPatch (Maybe Text) ptpAccessToken = lens _ptpAccessToken (\ s a -> s{_ptpAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). ptpUploadType :: Lens' ProjectsTenantsPatch (Maybe Text) ptpUploadType = lens _ptpUploadType (\ s a -> s{_ptpUploadType = a}) -- | Multipart request metadata. ptpPayload :: Lens' ProjectsTenantsPatch Tenant ptpPayload = lens _ptpPayload (\ s a -> s{_ptpPayload = a}) -- | Required during tenant update. The resource name for a tenant. This is -- generated by the service when a tenant is created. The format is -- \"projects\/{project_id}\/tenants\/{tenant_id}\", for example, -- \"projects\/foo\/tenants\/bar\". ptpName :: Lens' ProjectsTenantsPatch Text ptpName = lens _ptpName (\ s a -> s{_ptpName = a}) -- | JSONP ptpCallback :: Lens' ProjectsTenantsPatch (Maybe Text) ptpCallback = lens _ptpCallback (\ s a -> s{_ptpCallback = a}) instance GoogleRequest ProjectsTenantsPatch where type Rs ProjectsTenantsPatch = Tenant type Scopes ProjectsTenantsPatch = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/jobs"] requestClient ProjectsTenantsPatch'{..} = go _ptpName _ptpXgafv _ptpUploadProtocol _ptpUpdateMask _ptpAccessToken _ptpUploadType _ptpCallback (Just AltJSON) _ptpPayload jobsService where go = buildClient (Proxy :: Proxy ProjectsTenantsPatchResource) mempty
brendanhay/gogol
gogol-jobs/gen/Network/Google/Resource/Jobs/Projects/Tenants/Patch.hs
mpl-2.0
5,731
0
17
1,304
864
505
359
123
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.ReplicaPool.InstanceGroupManagers.Insert -- 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) -- -- Creates an instance group manager, as well as the instance group and the -- specified number of instances. -- -- /See:/ <https://developers.google.com/compute/docs/instance-groups/manager/v1beta2 Google Compute Engine Instance Group Manager API Reference> for @replicapool.instanceGroupManagers.insert@. module Network.Google.Resource.ReplicaPool.InstanceGroupManagers.Insert ( -- * REST Resource InstanceGroupManagersInsertResource -- * Creating a Request , instanceGroupManagersInsert , InstanceGroupManagersInsert -- * Request Lenses , igmiProject , igmiSize , igmiZone , igmiPayload ) where import Network.Google.Prelude import Network.Google.ReplicaPool.Types -- | A resource alias for @replicapool.instanceGroupManagers.insert@ method which the -- 'InstanceGroupManagersInsert' request conforms to. type InstanceGroupManagersInsertResource = "replicapool" :> "v1beta2" :> "projects" :> Capture "project" Text :> "zones" :> Capture "zone" Text :> "instanceGroupManagers" :> QueryParam "size" (Textual Int32) :> QueryParam "alt" AltJSON :> ReqBody '[JSON] InstanceGroupManager :> Post '[JSON] Operation -- | Creates an instance group manager, as well as the instance group and the -- specified number of instances. -- -- /See:/ 'instanceGroupManagersInsert' smart constructor. data InstanceGroupManagersInsert = InstanceGroupManagersInsert' { _igmiProject :: !Text , _igmiSize :: !(Textual Int32) , _igmiZone :: !Text , _igmiPayload :: !InstanceGroupManager } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'InstanceGroupManagersInsert' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'igmiProject' -- -- * 'igmiSize' -- -- * 'igmiZone' -- -- * 'igmiPayload' instanceGroupManagersInsert :: Text -- ^ 'igmiProject' -> Int32 -- ^ 'igmiSize' -> Text -- ^ 'igmiZone' -> InstanceGroupManager -- ^ 'igmiPayload' -> InstanceGroupManagersInsert instanceGroupManagersInsert pIgmiProject_ pIgmiSize_ pIgmiZone_ pIgmiPayload_ = InstanceGroupManagersInsert' { _igmiProject = pIgmiProject_ , _igmiSize = _Coerce # pIgmiSize_ , _igmiZone = pIgmiZone_ , _igmiPayload = pIgmiPayload_ } -- | The Google Developers Console project name. igmiProject :: Lens' InstanceGroupManagersInsert Text igmiProject = lens _igmiProject (\ s a -> s{_igmiProject = a}) -- | Number of instances that should exist. igmiSize :: Lens' InstanceGroupManagersInsert Int32 igmiSize = lens _igmiSize (\ s a -> s{_igmiSize = a}) . _Coerce -- | The name of the zone in which the instance group manager resides. igmiZone :: Lens' InstanceGroupManagersInsert Text igmiZone = lens _igmiZone (\ s a -> s{_igmiZone = a}) -- | Multipart request metadata. igmiPayload :: Lens' InstanceGroupManagersInsert InstanceGroupManager igmiPayload = lens _igmiPayload (\ s a -> s{_igmiPayload = a}) instance GoogleRequest InstanceGroupManagersInsert where type Rs InstanceGroupManagersInsert = Operation type Scopes InstanceGroupManagersInsert = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/compute"] requestClient InstanceGroupManagersInsert'{..} = go _igmiProject _igmiZone (Just _igmiSize) (Just AltJSON) _igmiPayload replicaPoolService where go = buildClient (Proxy :: Proxy InstanceGroupManagersInsertResource) mempty
rueshyna/gogol
gogol-replicapool/gen/Network/Google/Resource/ReplicaPool/InstanceGroupManagers/Insert.hs
mpl-2.0
4,611
0
17
1,056
571
337
234
87
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.TagManager.Accounts.Containers.Create -- 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) -- -- Creates a Container. -- -- /See:/ <https://developers.google.com/tag-manager Tag Manager API Reference> for @tagmanager.accounts.containers.create@. module Network.Google.Resource.TagManager.Accounts.Containers.Create ( -- * REST Resource AccountsContainersCreateResource -- * Creating a Request , accountsContainersCreate , AccountsContainersCreate -- * Request Lenses , acccParent , acccXgafv , acccUploadProtocol , acccAccessToken , acccUploadType , acccPayload , acccCallback ) where import Network.Google.Prelude import Network.Google.TagManager.Types -- | A resource alias for @tagmanager.accounts.containers.create@ method which the -- 'AccountsContainersCreate' request conforms to. type AccountsContainersCreateResource = "tagmanager" :> "v2" :> Capture "parent" Text :> "containers" :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] Container :> Post '[JSON] Container -- | Creates a Container. -- -- /See:/ 'accountsContainersCreate' smart constructor. data AccountsContainersCreate = AccountsContainersCreate' { _acccParent :: !Text , _acccXgafv :: !(Maybe Xgafv) , _acccUploadProtocol :: !(Maybe Text) , _acccAccessToken :: !(Maybe Text) , _acccUploadType :: !(Maybe Text) , _acccPayload :: !Container , _acccCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'AccountsContainersCreate' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'acccParent' -- -- * 'acccXgafv' -- -- * 'acccUploadProtocol' -- -- * 'acccAccessToken' -- -- * 'acccUploadType' -- -- * 'acccPayload' -- -- * 'acccCallback' accountsContainersCreate :: Text -- ^ 'acccParent' -> Container -- ^ 'acccPayload' -> AccountsContainersCreate accountsContainersCreate pAcccParent_ pAcccPayload_ = AccountsContainersCreate' { _acccParent = pAcccParent_ , _acccXgafv = Nothing , _acccUploadProtocol = Nothing , _acccAccessToken = Nothing , _acccUploadType = Nothing , _acccPayload = pAcccPayload_ , _acccCallback = Nothing } -- | GTM Account\'s API relative path. Example: accounts\/{account_id}. acccParent :: Lens' AccountsContainersCreate Text acccParent = lens _acccParent (\ s a -> s{_acccParent = a}) -- | V1 error format. acccXgafv :: Lens' AccountsContainersCreate (Maybe Xgafv) acccXgafv = lens _acccXgafv (\ s a -> s{_acccXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). acccUploadProtocol :: Lens' AccountsContainersCreate (Maybe Text) acccUploadProtocol = lens _acccUploadProtocol (\ s a -> s{_acccUploadProtocol = a}) -- | OAuth access token. acccAccessToken :: Lens' AccountsContainersCreate (Maybe Text) acccAccessToken = lens _acccAccessToken (\ s a -> s{_acccAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). acccUploadType :: Lens' AccountsContainersCreate (Maybe Text) acccUploadType = lens _acccUploadType (\ s a -> s{_acccUploadType = a}) -- | Multipart request metadata. acccPayload :: Lens' AccountsContainersCreate Container acccPayload = lens _acccPayload (\ s a -> s{_acccPayload = a}) -- | JSONP acccCallback :: Lens' AccountsContainersCreate (Maybe Text) acccCallback = lens _acccCallback (\ s a -> s{_acccCallback = a}) instance GoogleRequest AccountsContainersCreate where type Rs AccountsContainersCreate = Container type Scopes AccountsContainersCreate = '["https://www.googleapis.com/auth/tagmanager.edit.containers"] requestClient AccountsContainersCreate'{..} = go _acccParent _acccXgafv _acccUploadProtocol _acccAccessToken _acccUploadType _acccCallback (Just AltJSON) _acccPayload tagManagerService where go = buildClient (Proxy :: Proxy AccountsContainersCreateResource) mempty
brendanhay/gogol
gogol-tagmanager/gen/Network/Google/Resource/TagManager/Accounts/Containers/Create.hs
mpl-2.0
5,189
0
18
1,175
783
456
327
115
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.ContainerBuilder.Types.Product -- 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) -- module Network.Google.ContainerBuilder.Types.Product where import Network.Google.ContainerBuilder.Types.Sum import Network.Google.Prelude -- | A step in the build pipeline. -- -- /See:/ 'buildStep' smart constructor. data BuildStep = BuildStep' { _bsStatus :: !(Maybe BuildStepStatus) , _bsDir :: !(Maybe Text) , _bsArgs :: !(Maybe [Text]) , _bsEnv :: !(Maybe [Text]) , _bsPullTiming :: !(Maybe TimeSpan) , _bsEntrypoint :: !(Maybe Text) , _bsWaitFor :: !(Maybe [Text]) , _bsName :: !(Maybe Text) , _bsId :: !(Maybe Text) , _bsTiming :: !(Maybe TimeSpan) , _bsSecretEnv :: !(Maybe [Text]) , _bsTimeout :: !(Maybe GDuration) , _bsVolumes :: !(Maybe [Volume]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'BuildStep' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'bsStatus' -- -- * 'bsDir' -- -- * 'bsArgs' -- -- * 'bsEnv' -- -- * 'bsPullTiming' -- -- * 'bsEntrypoint' -- -- * 'bsWaitFor' -- -- * 'bsName' -- -- * 'bsId' -- -- * 'bsTiming' -- -- * 'bsSecretEnv' -- -- * 'bsTimeout' -- -- * 'bsVolumes' buildStep :: BuildStep buildStep = BuildStep' { _bsStatus = Nothing , _bsDir = Nothing , _bsArgs = Nothing , _bsEnv = Nothing , _bsPullTiming = Nothing , _bsEntrypoint = Nothing , _bsWaitFor = Nothing , _bsName = Nothing , _bsId = Nothing , _bsTiming = Nothing , _bsSecretEnv = Nothing , _bsTimeout = Nothing , _bsVolumes = Nothing } -- | Output only. Status of the build step. At this time, build step status -- is only updated on build completion; step status is not updated in -- real-time as the build progresses. bsStatus :: Lens' BuildStep (Maybe BuildStepStatus) bsStatus = lens _bsStatus (\ s a -> s{_bsStatus = a}) -- | Working directory to use when running this step\'s container. If this -- value is a relative path, it is relative to the build\'s working -- directory. If this value is absolute, it may be outside the build\'s -- working directory, in which case the contents of the path may not be -- persisted across build step executions, unless a \`volume\` for that -- path is specified. If the build specifies a \`RepoSource\` with \`dir\` -- and a step with a \`dir\`, which specifies an absolute path, the -- \`RepoSource\` \`dir\` is ignored for the step\'s execution. bsDir :: Lens' BuildStep (Maybe Text) bsDir = lens _bsDir (\ s a -> s{_bsDir = a}) -- | A list of arguments that will be presented to the step when it is -- started. If the image used to run the step\'s container has an -- entrypoint, the \`args\` are used as arguments to that entrypoint. If -- the image does not define an entrypoint, the first element in args is -- used as the entrypoint, and the remainder will be used as arguments. bsArgs :: Lens' BuildStep [Text] bsArgs = lens _bsArgs (\ s a -> s{_bsArgs = a}) . _Default . _Coerce -- | A list of environment variable definitions to be used when running a -- step. The elements are of the form \"KEY=VALUE\" for the environment -- variable \"KEY\" being given the value \"VALUE\". bsEnv :: Lens' BuildStep [Text] bsEnv = lens _bsEnv (\ s a -> s{_bsEnv = a}) . _Default . _Coerce -- | Output only. Stores timing information for pulling this build step\'s -- builder image only. bsPullTiming :: Lens' BuildStep (Maybe TimeSpan) bsPullTiming = lens _bsPullTiming (\ s a -> s{_bsPullTiming = a}) -- | Entrypoint to be used instead of the build step image\'s default -- entrypoint. If unset, the image\'s default entrypoint is used. bsEntrypoint :: Lens' BuildStep (Maybe Text) bsEntrypoint = lens _bsEntrypoint (\ s a -> s{_bsEntrypoint = a}) -- | The ID(s) of the step(s) that this build step depends on. This build -- step will not start until all the build steps in \`wait_for\` have -- completed successfully. If \`wait_for\` is empty, this build step will -- start when all previous build steps in the \`Build.Steps\` list have -- completed successfully. bsWaitFor :: Lens' BuildStep [Text] bsWaitFor = lens _bsWaitFor (\ s a -> s{_bsWaitFor = a}) . _Default . _Coerce -- | Required. The name of the container image that will run this particular -- build step. If the image is available in the host\'s Docker daemon\'s -- cache, it will be run directly. If not, the host will attempt to pull -- the image first, using the builder service account\'s credentials if -- necessary. The Docker daemon\'s cache will already have the latest -- versions of all of the officially supported build steps -- ([https:\/\/github.com\/GoogleCloudPlatform\/cloud-builders](https:\/\/github.com\/GoogleCloudPlatform\/cloud-builders)). -- The Docker daemon will also have cached many of the layers for some -- popular images, like \"ubuntu\", \"debian\", but they will be refreshed -- at the time you attempt to use them. If you built an image in a previous -- build step, it will be stored in the host\'s Docker daemon\'s cache and -- is available to use as the name for a later build step. bsName :: Lens' BuildStep (Maybe Text) bsName = lens _bsName (\ s a -> s{_bsName = a}) -- | Unique identifier for this build step, used in \`wait_for\` to reference -- this build step as a dependency. bsId :: Lens' BuildStep (Maybe Text) bsId = lens _bsId (\ s a -> s{_bsId = a}) -- | Output only. Stores timing information for executing this build step. bsTiming :: Lens' BuildStep (Maybe TimeSpan) bsTiming = lens _bsTiming (\ s a -> s{_bsTiming = a}) -- | A list of environment variables which are encrypted using a Cloud Key -- Management Service crypto key. These values must be specified in the -- build\'s \`Secret\`. bsSecretEnv :: Lens' BuildStep [Text] bsSecretEnv = lens _bsSecretEnv (\ s a -> s{_bsSecretEnv = a}) . _Default . _Coerce -- | Time limit for executing this build step. If not defined, the step has -- no time limit and will be allowed to continue to run until either it -- completes or the build itself times out. bsTimeout :: Lens' BuildStep (Maybe Scientific) bsTimeout = lens _bsTimeout (\ s a -> s{_bsTimeout = a}) . mapping _GDuration -- | List of volumes to mount into the build step. Each volume is created as -- an empty volume prior to execution of the build step. Upon completion of -- the build, volumes and their contents are discarded. Using a named -- volume in only one step is not valid as it is indicative of a build -- request with an incorrect configuration. bsVolumes :: Lens' BuildStep [Volume] bsVolumes = lens _bsVolumes (\ s a -> s{_bsVolumes = a}) . _Default . _Coerce instance FromJSON BuildStep where parseJSON = withObject "BuildStep" (\ o -> BuildStep' <$> (o .:? "status") <*> (o .:? "dir") <*> (o .:? "args" .!= mempty) <*> (o .:? "env" .!= mempty) <*> (o .:? "pullTiming") <*> (o .:? "entrypoint") <*> (o .:? "waitFor" .!= mempty) <*> (o .:? "name") <*> (o .:? "id") <*> (o .:? "timing") <*> (o .:? "secretEnv" .!= mempty) <*> (o .:? "timeout") <*> (o .:? "volumes" .!= mempty)) instance ToJSON BuildStep where toJSON BuildStep'{..} = object (catMaybes [("status" .=) <$> _bsStatus, ("dir" .=) <$> _bsDir, ("args" .=) <$> _bsArgs, ("env" .=) <$> _bsEnv, ("pullTiming" .=) <$> _bsPullTiming, ("entrypoint" .=) <$> _bsEntrypoint, ("waitFor" .=) <$> _bsWaitFor, ("name" .=) <$> _bsName, ("id" .=) <$> _bsId, ("timing" .=) <$> _bsTiming, ("secretEnv" .=) <$> _bsSecretEnv, ("timeout" .=) <$> _bsTimeout, ("volumes" .=) <$> _bsVolumes]) -- | Defines the configuration to be used for creating workers in the pool. -- -- /See:/ 'workerConfig' smart constructor. data WorkerConfig = WorkerConfig' { _wcDiskSizeGb :: !(Maybe (Textual Int64)) , _wcMachineType :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'WorkerConfig' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'wcDiskSizeGb' -- -- * 'wcMachineType' workerConfig :: WorkerConfig workerConfig = WorkerConfig' {_wcDiskSizeGb = Nothing, _wcMachineType = Nothing} -- | Size of the disk attached to the worker, in GB. See [Worker pool config -- file](https:\/\/cloud.google.com\/build\/docs\/private-pools\/worker-pool-config-file-schema). -- Specify a value of up to 1000. If \`0\` is specified, Cloud Build will -- use a standard disk size. wcDiskSizeGb :: Lens' WorkerConfig (Maybe Int64) wcDiskSizeGb = lens _wcDiskSizeGb (\ s a -> s{_wcDiskSizeGb = a}) . mapping _Coerce -- | Machine type of a worker, such as \`e2-medium\`. See [Worker pool config -- file](https:\/\/cloud.google.com\/build\/docs\/private-pools\/worker-pool-config-file-schema). -- If left blank, Cloud Build will use a sensible default. wcMachineType :: Lens' WorkerConfig (Maybe Text) wcMachineType = lens _wcMachineType (\ s a -> s{_wcMachineType = a}) instance FromJSON WorkerConfig where parseJSON = withObject "WorkerConfig" (\ o -> WorkerConfig' <$> (o .:? "diskSizeGb") <*> (o .:? "machineType")) instance ToJSON WorkerConfig where toJSON WorkerConfig'{..} = object (catMaybes [("diskSizeGb" .=) <$> _wcDiskSizeGb, ("machineType" .=) <$> _wcMachineType]) -- | Provenance of the source. Ways to find the original source, or verify -- that some source was used for this build. -- -- /See:/ 'sourceProvenance' smart constructor. data SourceProvenance = SourceProvenance' { _spResolvedRepoSource :: !(Maybe RepoSource) , _spResolvedStorageSourceManifest :: !(Maybe StorageSourceManifest) , _spResolvedStorageSource :: !(Maybe StorageSource) , _spFileHashes :: !(Maybe SourceProvenanceFileHashes) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'SourceProvenance' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'spResolvedRepoSource' -- -- * 'spResolvedStorageSourceManifest' -- -- * 'spResolvedStorageSource' -- -- * 'spFileHashes' sourceProvenance :: SourceProvenance sourceProvenance = SourceProvenance' { _spResolvedRepoSource = Nothing , _spResolvedStorageSourceManifest = Nothing , _spResolvedStorageSource = Nothing , _spFileHashes = Nothing } -- | A copy of the build\'s \`source.repo_source\`, if exists, with any -- revisions resolved. spResolvedRepoSource :: Lens' SourceProvenance (Maybe RepoSource) spResolvedRepoSource = lens _spResolvedRepoSource (\ s a -> s{_spResolvedRepoSource = a}) -- | A copy of the build\'s \`source.storage_source_manifest\`, if exists, -- with any revisions resolved. This feature is in Preview. spResolvedStorageSourceManifest :: Lens' SourceProvenance (Maybe StorageSourceManifest) spResolvedStorageSourceManifest = lens _spResolvedStorageSourceManifest (\ s a -> s{_spResolvedStorageSourceManifest = a}) -- | A copy of the build\'s \`source.storage_source\`, if exists, with any -- generations resolved. spResolvedStorageSource :: Lens' SourceProvenance (Maybe StorageSource) spResolvedStorageSource = lens _spResolvedStorageSource (\ s a -> s{_spResolvedStorageSource = a}) -- | Output only. Hash(es) of the build source, which can be used to verify -- that the original source integrity was maintained in the build. Note -- that \`FileHashes\` will only be populated if \`BuildOptions\` has -- requested a \`SourceProvenanceHash\`. The keys to this map are file -- paths used as build source and the values contain the hash values for -- those files. If the build source came in a single package such as a -- gzipped tarfile (\`.tar.gz\`), the \`FileHash\` will be for the single -- path to that file. spFileHashes :: Lens' SourceProvenance (Maybe SourceProvenanceFileHashes) spFileHashes = lens _spFileHashes (\ s a -> s{_spFileHashes = a}) instance FromJSON SourceProvenance where parseJSON = withObject "SourceProvenance" (\ o -> SourceProvenance' <$> (o .:? "resolvedRepoSource") <*> (o .:? "resolvedStorageSourceManifest") <*> (o .:? "resolvedStorageSource") <*> (o .:? "fileHashes")) instance ToJSON SourceProvenance where toJSON SourceProvenance'{..} = object (catMaybes [("resolvedRepoSource" .=) <$> _spResolvedRepoSource, ("resolvedStorageSourceManifest" .=) <$> _spResolvedStorageSourceManifest, ("resolvedStorageSource" .=) <$> _spResolvedStorageSource, ("fileHashes" .=) <$> _spFileHashes]) -- | Response including listed builds. -- -- /See:/ 'listBuildsResponse' smart constructor. data ListBuildsResponse = ListBuildsResponse' { _lbrNextPageToken :: !(Maybe Text) , _lbrBuilds :: !(Maybe [Build]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ListBuildsResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lbrNextPageToken' -- -- * 'lbrBuilds' listBuildsResponse :: ListBuildsResponse listBuildsResponse = ListBuildsResponse' {_lbrNextPageToken = Nothing, _lbrBuilds = Nothing} -- | Token to receive the next page of results. This will be absent if the -- end of the response list has been reached. lbrNextPageToken :: Lens' ListBuildsResponse (Maybe Text) lbrNextPageToken = lens _lbrNextPageToken (\ s a -> s{_lbrNextPageToken = a}) -- | Builds will be sorted by \`create_time\`, descending. lbrBuilds :: Lens' ListBuildsResponse [Build] lbrBuilds = lens _lbrBuilds (\ s a -> s{_lbrBuilds = a}) . _Default . _Coerce instance FromJSON ListBuildsResponse where parseJSON = withObject "ListBuildsResponse" (\ o -> ListBuildsResponse' <$> (o .:? "nextPageToken") <*> (o .:? "builds" .!= mempty)) instance ToJSON ListBuildsResponse where toJSON ListBuildsResponse'{..} = object (catMaybes [("nextPageToken" .=) <$> _lbrNextPageToken, ("builds" .=) <$> _lbrBuilds]) -- | The \`Status\` type defines a logical error model that is suitable for -- different programming environments, including REST APIs and RPC APIs. It -- is used by [gRPC](https:\/\/github.com\/grpc). Each \`Status\` message -- contains three pieces of data: error code, error message, and error -- details. You can find out more about this error model and how to work -- with it in the [API Design -- Guide](https:\/\/cloud.google.com\/apis\/design\/errors). -- -- /See:/ 'status' smart constructor. data Status = Status' { _sDetails :: !(Maybe [StatusDetailsItem]) , _sCode :: !(Maybe (Textual Int32)) , _sMessage :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Status' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'sDetails' -- -- * 'sCode' -- -- * 'sMessage' status :: Status status = Status' {_sDetails = Nothing, _sCode = Nothing, _sMessage = Nothing} -- | A list of messages that carry the error details. There is a common set -- of message types for APIs to use. sDetails :: Lens' Status [StatusDetailsItem] sDetails = lens _sDetails (\ s a -> s{_sDetails = a}) . _Default . _Coerce -- | The status code, which should be an enum value of google.rpc.Code. sCode :: Lens' Status (Maybe Int32) sCode = lens _sCode (\ s a -> s{_sCode = a}) . mapping _Coerce -- | A developer-facing error message, which should be in English. Any -- user-facing error message should be localized and sent in the -- google.rpc.Status.details field, or localized by the client. sMessage :: Lens' Status (Maybe Text) sMessage = lens _sMessage (\ s a -> s{_sMessage = a}) instance FromJSON Status where parseJSON = withObject "Status" (\ o -> Status' <$> (o .:? "details" .!= mempty) <*> (o .:? "code") <*> (o .:? "message")) instance ToJSON Status where toJSON Status'{..} = object (catMaybes [("details" .=) <$> _sDetails, ("code" .=) <$> _sCode, ("message" .=) <$> _sMessage]) -- | Service-specific metadata associated with the operation. It typically -- contains progress information and common metadata such as create time. -- Some services might not provide such metadata. Any method that returns a -- long-running operation should document the metadata type, if any. -- -- /See:/ 'operationSchema' smart constructor. newtype OperationSchema = OperationSchema' { _osAddtional :: HashMap Text JSONValue } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'OperationSchema' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'osAddtional' operationSchema :: HashMap Text JSONValue -- ^ 'osAddtional' -> OperationSchema operationSchema pOsAddtional_ = OperationSchema' {_osAddtional = _Coerce # pOsAddtional_} -- | Properties of the object. Contains field \'type with type URL. osAddtional :: Lens' OperationSchema (HashMap Text JSONValue) osAddtional = lens _osAddtional (\ s a -> s{_osAddtional = a}) . _Coerce instance FromJSON OperationSchema where parseJSON = withObject "OperationSchema" (\ o -> OperationSchema' <$> (parseJSONObject o)) instance ToJSON OperationSchema where toJSON = toJSON . _osAddtional -- | PullRequestFilter contains filter properties for matching GitHub Pull -- Requests. -- -- /See:/ 'pullRequestFilter' smart constructor. data PullRequestFilter = PullRequestFilter' { _prfCommentControl :: !(Maybe PullRequestFilterCommentControl) , _prfInvertRegex :: !(Maybe Bool) , _prfBranch :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'PullRequestFilter' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'prfCommentControl' -- -- * 'prfInvertRegex' -- -- * 'prfBranch' pullRequestFilter :: PullRequestFilter pullRequestFilter = PullRequestFilter' { _prfCommentControl = Nothing , _prfInvertRegex = Nothing , _prfBranch = Nothing } -- | Configure builds to run whether a repository owner or collaborator need -- to comment \`\/gcbrun\`. prfCommentControl :: Lens' PullRequestFilter (Maybe PullRequestFilterCommentControl) prfCommentControl = lens _prfCommentControl (\ s a -> s{_prfCommentControl = a}) -- | If true, branches that do NOT match the git_ref will trigger a build. prfInvertRegex :: Lens' PullRequestFilter (Maybe Bool) prfInvertRegex = lens _prfInvertRegex (\ s a -> s{_prfInvertRegex = a}) -- | Regex of branches to match. The syntax of the regular expressions -- accepted is the syntax accepted by RE2 and described at -- https:\/\/github.com\/google\/re2\/wiki\/Syntax prfBranch :: Lens' PullRequestFilter (Maybe Text) prfBranch = lens _prfBranch (\ s a -> s{_prfBranch = a}) instance FromJSON PullRequestFilter where parseJSON = withObject "PullRequestFilter" (\ o -> PullRequestFilter' <$> (o .:? "commentControl") <*> (o .:? "invertRegex") <*> (o .:? "branch")) instance ToJSON PullRequestFilter where toJSON PullRequestFilter'{..} = object (catMaybes [("commentControl" .=) <$> _prfCommentControl, ("invertRegex" .=) <$> _prfInvertRegex, ("branch" .=) <$> _prfBranch]) -- | Specifies a build to retry. -- -- /See:/ 'retryBuildRequest' smart constructor. data RetryBuildRequest = RetryBuildRequest' { _rbrName :: !(Maybe Text) , _rbrId :: !(Maybe Text) , _rbrProjectId :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'RetryBuildRequest' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'rbrName' -- -- * 'rbrId' -- -- * 'rbrProjectId' retryBuildRequest :: RetryBuildRequest retryBuildRequest = RetryBuildRequest' {_rbrName = Nothing, _rbrId = Nothing, _rbrProjectId = Nothing} -- | The name of the \`Build\` to retry. Format: -- \`projects\/{project}\/locations\/{location}\/builds\/{build}\` rbrName :: Lens' RetryBuildRequest (Maybe Text) rbrName = lens _rbrName (\ s a -> s{_rbrName = a}) -- | Required. Build ID of the original build. rbrId :: Lens' RetryBuildRequest (Maybe Text) rbrId = lens _rbrId (\ s a -> s{_rbrId = a}) -- | Required. ID of the project. rbrProjectId :: Lens' RetryBuildRequest (Maybe Text) rbrProjectId = lens _rbrProjectId (\ s a -> s{_rbrProjectId = a}) instance FromJSON RetryBuildRequest where parseJSON = withObject "RetryBuildRequest" (\ o -> RetryBuildRequest' <$> (o .:? "name") <*> (o .:? "id") <*> (o .:? "projectId")) instance ToJSON RetryBuildRequest where toJSON RetryBuildRequest'{..} = object (catMaybes [("name" .=) <$> _rbrName, ("id" .=) <$> _rbrId, ("projectId" .=) <$> _rbrProjectId]) -- | Details about how a build should be executed on a \`WorkerPool\`. See -- [running builds in a private -- pool](https:\/\/cloud.google.com\/build\/docs\/private-pools\/run-builds-in-private-pool) -- for more information. -- -- /See:/ 'poolOption' smart constructor. newtype PoolOption = PoolOption' { _poName :: Maybe Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'PoolOption' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'poName' poolOption :: PoolOption poolOption = PoolOption' {_poName = Nothing} -- | The \`WorkerPool\` resource to execute the build on. You must have -- \`cloudbuild.workerpools.use\` on the project hosting the WorkerPool. -- Format -- projects\/{project}\/locations\/{location}\/workerPools\/{workerPoolId} poName :: Lens' PoolOption (Maybe Text) poName = lens _poName (\ s a -> s{_poName = a}) instance FromJSON PoolOption where parseJSON = withObject "PoolOption" (\ o -> PoolOption' <$> (o .:? "name")) instance ToJSON PoolOption where toJSON PoolOption'{..} = object (catMaybes [("name" .=) <$> _poName]) -- -- /See:/ 'hTTPBodyExtensionsItem' smart constructor. newtype HTTPBodyExtensionsItem = HTTPBodyExtensionsItem' { _httpbeiAddtional :: HashMap Text JSONValue } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'HTTPBodyExtensionsItem' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'httpbeiAddtional' hTTPBodyExtensionsItem :: HashMap Text JSONValue -- ^ 'httpbeiAddtional' -> HTTPBodyExtensionsItem hTTPBodyExtensionsItem pHttpbeiAddtional_ = HTTPBodyExtensionsItem' {_httpbeiAddtional = _Coerce # pHttpbeiAddtional_} -- | Properties of the object. Contains field \'type with type URL. httpbeiAddtional :: Lens' HTTPBodyExtensionsItem (HashMap Text JSONValue) httpbeiAddtional = lens _httpbeiAddtional (\ s a -> s{_httpbeiAddtional = a}) . _Coerce instance FromJSON HTTPBodyExtensionsItem where parseJSON = withObject "HTTPBodyExtensionsItem" (\ o -> HTTPBodyExtensionsItem' <$> (parseJSONObject o)) instance ToJSON HTTPBodyExtensionsItem where toJSON = toJSON . _httpbeiAddtional -- | The request message for Operations.CancelOperation. -- -- /See:/ 'cancelOperationRequest' smart constructor. data CancelOperationRequest = CancelOperationRequest' deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'CancelOperationRequest' with the minimum fields required to make a request. -- cancelOperationRequest :: CancelOperationRequest cancelOperationRequest = CancelOperationRequest' instance FromJSON CancelOperationRequest where parseJSON = withObject "CancelOperationRequest" (\ o -> pure CancelOperationRequest') instance ToJSON CancelOperationRequest where toJSON = const emptyObject -- | Container message for hash values. -- -- /See:/ 'hash' smart constructor. data Hash = Hash' { _hValue :: !(Maybe Bytes) , _hType :: !(Maybe HashType) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Hash' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'hValue' -- -- * 'hType' hash :: Hash hash = Hash' {_hValue = Nothing, _hType = Nothing} -- | The hash value. hValue :: Lens' Hash (Maybe ByteString) hValue = lens _hValue (\ s a -> s{_hValue = a}) . mapping _Bytes -- | The type of hash that was performed. hType :: Lens' Hash (Maybe HashType) hType = lens _hType (\ s a -> s{_hType = a}) instance FromJSON Hash where parseJSON = withObject "Hash" (\ o -> Hash' <$> (o .:? "value") <*> (o .:? "type")) instance ToJSON Hash where toJSON Hash'{..} = object (catMaybes [("value" .=) <$> _hValue, ("type" .=) <$> _hType]) -- | Artifacts created by the build pipeline. -- -- /See:/ 'results' smart constructor. data Results = Results' { _rImages :: !(Maybe [BuiltImage]) , _rBuildStepImages :: !(Maybe [Text]) , _rArtifactManifest :: !(Maybe Text) , _rBuildStepOutputs :: !(Maybe [Bytes]) , _rNumArtifacts :: !(Maybe (Textual Int64)) , _rArtifactTiming :: !(Maybe TimeSpan) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Results' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'rImages' -- -- * 'rBuildStepImages' -- -- * 'rArtifactManifest' -- -- * 'rBuildStepOutputs' -- -- * 'rNumArtifacts' -- -- * 'rArtifactTiming' results :: Results results = Results' { _rImages = Nothing , _rBuildStepImages = Nothing , _rArtifactManifest = Nothing , _rBuildStepOutputs = Nothing , _rNumArtifacts = Nothing , _rArtifactTiming = Nothing } -- | Container images that were built as a part of the build. rImages :: Lens' Results [BuiltImage] rImages = lens _rImages (\ s a -> s{_rImages = a}) . _Default . _Coerce -- | List of build step digests, in the order corresponding to build step -- indices. rBuildStepImages :: Lens' Results [Text] rBuildStepImages = lens _rBuildStepImages (\ s a -> s{_rBuildStepImages = a}) . _Default . _Coerce -- | Path to the artifact manifest. Only populated when artifacts are -- uploaded. rArtifactManifest :: Lens' Results (Maybe Text) rArtifactManifest = lens _rArtifactManifest (\ s a -> s{_rArtifactManifest = a}) -- | List of build step outputs, produced by builder images, in the order -- corresponding to build step indices. [Cloud -- Builders](https:\/\/cloud.google.com\/cloud-build\/docs\/cloud-builders) -- can produce this output by writing to \`$BUILDER_OUTPUT\/output\`. Only -- the first 4KB of data is stored. rBuildStepOutputs :: Lens' Results [ByteString] rBuildStepOutputs = lens _rBuildStepOutputs (\ s a -> s{_rBuildStepOutputs = a}) . _Default . _Coerce -- | Number of artifacts uploaded. Only populated when artifacts are -- uploaded. rNumArtifacts :: Lens' Results (Maybe Int64) rNumArtifacts = lens _rNumArtifacts (\ s a -> s{_rNumArtifacts = a}) . mapping _Coerce -- | Time to push all non-container artifacts. rArtifactTiming :: Lens' Results (Maybe TimeSpan) rArtifactTiming = lens _rArtifactTiming (\ s a -> s{_rArtifactTiming = a}) instance FromJSON Results where parseJSON = withObject "Results" (\ o -> Results' <$> (o .:? "images" .!= mempty) <*> (o .:? "buildStepImages" .!= mempty) <*> (o .:? "artifactManifest") <*> (o .:? "buildStepOutputs" .!= mempty) <*> (o .:? "numArtifacts") <*> (o .:? "artifactTiming")) instance ToJSON Results where toJSON Results'{..} = object (catMaybes [("images" .=) <$> _rImages, ("buildStepImages" .=) <$> _rBuildStepImages, ("artifactManifest" .=) <$> _rArtifactManifest, ("buildStepOutputs" .=) <$> _rBuildStepOutputs, ("numArtifacts" .=) <$> _rNumArtifacts, ("artifactTiming" .=) <$> _rArtifactTiming]) -- | Substitutions for Build resource. The keys must match the following -- regular expression: \`^_[A-Z0-9_]+$\`. -- -- /See:/ 'buildTriggerSubstitutions' smart constructor. newtype BuildTriggerSubstitutions = BuildTriggerSubstitutions' { _btsAddtional :: HashMap Text Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'BuildTriggerSubstitutions' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'btsAddtional' buildTriggerSubstitutions :: HashMap Text Text -- ^ 'btsAddtional' -> BuildTriggerSubstitutions buildTriggerSubstitutions pBtsAddtional_ = BuildTriggerSubstitutions' {_btsAddtional = _Coerce # pBtsAddtional_} btsAddtional :: Lens' BuildTriggerSubstitutions (HashMap Text Text) btsAddtional = lens _btsAddtional (\ s a -> s{_btsAddtional = a}) . _Coerce instance FromJSON BuildTriggerSubstitutions where parseJSON = withObject "BuildTriggerSubstitutions" (\ o -> BuildTriggerSubstitutions' <$> (parseJSONObject o)) instance ToJSON BuildTriggerSubstitutions where toJSON = toJSON . _btsAddtional -- | Location of the source in a Google Cloud Source Repository. -- -- /See:/ 'repoSource' smart constructor. data RepoSource = RepoSource' { _rsSubstitutions :: !(Maybe RepoSourceSubstitutions) , _rsInvertRegex :: !(Maybe Bool) , _rsRepoName :: !(Maybe Text) , _rsDir :: !(Maybe Text) , _rsCommitSha :: !(Maybe Text) , _rsBranchName :: !(Maybe Text) , _rsTagName :: !(Maybe Text) , _rsProjectId :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'RepoSource' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'rsSubstitutions' -- -- * 'rsInvertRegex' -- -- * 'rsRepoName' -- -- * 'rsDir' -- -- * 'rsCommitSha' -- -- * 'rsBranchName' -- -- * 'rsTagName' -- -- * 'rsProjectId' repoSource :: RepoSource repoSource = RepoSource' { _rsSubstitutions = Nothing , _rsInvertRegex = Nothing , _rsRepoName = Nothing , _rsDir = Nothing , _rsCommitSha = Nothing , _rsBranchName = Nothing , _rsTagName = Nothing , _rsProjectId = Nothing } -- | Substitutions to use in a triggered build. Should only be used with -- RunBuildTrigger rsSubstitutions :: Lens' RepoSource (Maybe RepoSourceSubstitutions) rsSubstitutions = lens _rsSubstitutions (\ s a -> s{_rsSubstitutions = a}) -- | Only trigger a build if the revision regex does NOT match the revision -- regex. rsInvertRegex :: Lens' RepoSource (Maybe Bool) rsInvertRegex = lens _rsInvertRegex (\ s a -> s{_rsInvertRegex = a}) -- | Name of the Cloud Source Repository. rsRepoName :: Lens' RepoSource (Maybe Text) rsRepoName = lens _rsRepoName (\ s a -> s{_rsRepoName = a}) -- | Directory, relative to the source root, in which to run the build. This -- must be a relative path. If a step\'s \`dir\` is specified and is an -- absolute path, this value is ignored for that step\'s execution. rsDir :: Lens' RepoSource (Maybe Text) rsDir = lens _rsDir (\ s a -> s{_rsDir = a}) -- | Explicit commit SHA to build. rsCommitSha :: Lens' RepoSource (Maybe Text) rsCommitSha = lens _rsCommitSha (\ s a -> s{_rsCommitSha = a}) -- | Regex matching branches to build. The syntax of the regular expressions -- accepted is the syntax accepted by RE2 and described at -- https:\/\/github.com\/google\/re2\/wiki\/Syntax rsBranchName :: Lens' RepoSource (Maybe Text) rsBranchName = lens _rsBranchName (\ s a -> s{_rsBranchName = a}) -- | Regex matching tags to build. The syntax of the regular expressions -- accepted is the syntax accepted by RE2 and described at -- https:\/\/github.com\/google\/re2\/wiki\/Syntax rsTagName :: Lens' RepoSource (Maybe Text) rsTagName = lens _rsTagName (\ s a -> s{_rsTagName = a}) -- | ID of the project that owns the Cloud Source Repository. If omitted, the -- project ID requesting the build is assumed. rsProjectId :: Lens' RepoSource (Maybe Text) rsProjectId = lens _rsProjectId (\ s a -> s{_rsProjectId = a}) instance FromJSON RepoSource where parseJSON = withObject "RepoSource" (\ o -> RepoSource' <$> (o .:? "substitutions") <*> (o .:? "invertRegex") <*> (o .:? "repoName") <*> (o .:? "dir") <*> (o .:? "commitSha") <*> (o .:? "branchName") <*> (o .:? "tagName") <*> (o .:? "projectId")) instance ToJSON RepoSource where toJSON RepoSource'{..} = object (catMaybes [("substitutions" .=) <$> _rsSubstitutions, ("invertRegex" .=) <$> _rsInvertRegex, ("repoName" .=) <$> _rsRepoName, ("dir" .=) <$> _rsDir, ("commitSha" .=) <$> _rsCommitSha, ("branchName" .=) <$> _rsBranchName, ("tagName" .=) <$> _rsTagName, ("projectId" .=) <$> _rsProjectId]) -- | Secrets and secret environment variables. -- -- /See:/ 'secrets' smart constructor. data Secrets = Secrets' { _sInline :: !(Maybe [InlineSecret]) , _sSecretManager :: !(Maybe [SecretManagerSecret]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Secrets' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'sInline' -- -- * 'sSecretManager' secrets :: Secrets secrets = Secrets' {_sInline = Nothing, _sSecretManager = Nothing} -- | Secrets encrypted with KMS key and the associated secret environment -- variable. sInline :: Lens' Secrets [InlineSecret] sInline = lens _sInline (\ s a -> s{_sInline = a}) . _Default . _Coerce -- | Secrets in Secret Manager and associated secret environment variable. sSecretManager :: Lens' Secrets [SecretManagerSecret] sSecretManager = lens _sSecretManager (\ s a -> s{_sSecretManager = a}) . _Default . _Coerce instance FromJSON Secrets where parseJSON = withObject "Secrets" (\ o -> Secrets' <$> (o .:? "inline" .!= mempty) <*> (o .:? "secretManager" .!= mempty)) instance ToJSON Secrets where toJSON Secrets'{..} = object (catMaybes [("inline" .=) <$> _sInline, ("secretManager" .=) <$> _sSecretManager]) -- | This resource represents a long-running operation that is the result of -- a network API call. -- -- /See:/ 'operation' smart constructor. data Operation = Operation' { _oDone :: !(Maybe Bool) , _oError :: !(Maybe Status) , _oResponse :: !(Maybe OperationResponse) , _oName :: !(Maybe Text) , _oMetadata :: !(Maybe OperationSchema) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Operation' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'oDone' -- -- * 'oError' -- -- * 'oResponse' -- -- * 'oName' -- -- * 'oMetadata' operation :: Operation operation = Operation' { _oDone = Nothing , _oError = Nothing , _oResponse = Nothing , _oName = Nothing , _oMetadata = Nothing } -- | If the value is \`false\`, it means the operation is still in progress. -- If \`true\`, the operation is completed, and either \`error\` or -- \`response\` is available. oDone :: Lens' Operation (Maybe Bool) oDone = lens _oDone (\ s a -> s{_oDone = a}) -- | The error result of the operation in case of failure or cancellation. oError :: Lens' Operation (Maybe Status) oError = lens _oError (\ s a -> s{_oError = a}) -- | The normal response of the operation in case of success. If the original -- method returns no data on success, such as \`Delete\`, the response is -- \`google.protobuf.Empty\`. If the original method is standard -- \`Get\`\/\`Create\`\/\`Update\`, the response should be the resource. -- For other methods, the response should have the type \`XxxResponse\`, -- where \`Xxx\` is the original method name. For example, if the original -- method name is \`TakeSnapshot()\`, the inferred response type is -- \`TakeSnapshotResponse\`. oResponse :: Lens' Operation (Maybe OperationResponse) oResponse = lens _oResponse (\ s a -> s{_oResponse = a}) -- | The server-assigned name, which is only unique within the same service -- that originally returns it. If you use the default HTTP mapping, the -- \`name\` should be a resource name ending with -- \`operations\/{unique_id}\`. oName :: Lens' Operation (Maybe Text) oName = lens _oName (\ s a -> s{_oName = a}) -- | Service-specific metadata associated with the operation. It typically -- contains progress information and common metadata such as create time. -- Some services might not provide such metadata. Any method that returns a -- long-running operation should document the metadata type, if any. oMetadata :: Lens' Operation (Maybe OperationSchema) oMetadata = lens _oMetadata (\ s a -> s{_oMetadata = a}) instance FromJSON Operation where parseJSON = withObject "Operation" (\ o -> Operation' <$> (o .:? "done") <*> (o .:? "error") <*> (o .:? "response") <*> (o .:? "name") <*> (o .:? "metadata")) instance ToJSON Operation where toJSON Operation'{..} = object (catMaybes [("done" .=) <$> _oDone, ("error" .=) <$> _oError, ("response" .=) <$> _oResponse, ("name" .=) <$> _oName, ("metadata" .=) <$> _oMetadata]) -- | A generic empty message that you can re-use to avoid defining duplicated -- empty messages in your APIs. A typical example is to use it as the -- request or the response type of an API method. For instance: service Foo -- { rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); } The -- JSON representation for \`Empty\` is empty JSON object \`{}\`. -- -- /See:/ 'empty' smart constructor. data Empty = Empty' deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Empty' with the minimum fields required to make a request. -- empty :: Empty empty = Empty' instance FromJSON Empty where parseJSON = withObject "Empty" (\ o -> pure Empty') instance ToJSON Empty where toJSON = const emptyObject -- | Map of environment variable name to its encrypted value. Secret -- environment variables must be unique across all of a build\'s secrets, -- and must be used by at least one build step. Values can be at most 64 KB -- in size. There can be at most 100 secret values across all of a build\'s -- secrets. -- -- /See:/ 'secretSecretEnv' smart constructor. newtype SecretSecretEnv = SecretSecretEnv' { _sseAddtional :: HashMap Text Bytes } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'SecretSecretEnv' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'sseAddtional' secretSecretEnv :: HashMap Text ByteString -- ^ 'sseAddtional' -> SecretSecretEnv secretSecretEnv pSseAddtional_ = SecretSecretEnv' {_sseAddtional = _Coerce # pSseAddtional_} sseAddtional :: Lens' SecretSecretEnv (HashMap Text ByteString) sseAddtional = lens _sseAddtional (\ s a -> s{_sseAddtional = a}) . _Coerce instance FromJSON SecretSecretEnv where parseJSON = withObject "SecretSecretEnv" (\ o -> SecretSecretEnv' <$> (parseJSONObject o)) instance ToJSON SecretSecretEnv where toJSON = toJSON . _sseAddtional -- | Notification is the container which holds the data that is relevant to -- this particular notification. -- -- /See:/ 'notification' smart constructor. data Notification = Notification' { _nStructDelivery :: !(Maybe NotificationStructDelivery) , _nSmtpDelivery :: !(Maybe SMTPDelivery) , _nHTTPDelivery :: !(Maybe HTTPDelivery) , _nSlackDelivery :: !(Maybe SlackDelivery) , _nFilter :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Notification' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'nStructDelivery' -- -- * 'nSmtpDelivery' -- -- * 'nHTTPDelivery' -- -- * 'nSlackDelivery' -- -- * 'nFilter' notification :: Notification notification = Notification' { _nStructDelivery = Nothing , _nSmtpDelivery = Nothing , _nHTTPDelivery = Nothing , _nSlackDelivery = Nothing , _nFilter = Nothing } -- | Escape hatch for users to supply custom delivery configs. nStructDelivery :: Lens' Notification (Maybe NotificationStructDelivery) nStructDelivery = lens _nStructDelivery (\ s a -> s{_nStructDelivery = a}) -- | Configuration for SMTP (email) delivery. nSmtpDelivery :: Lens' Notification (Maybe SMTPDelivery) nSmtpDelivery = lens _nSmtpDelivery (\ s a -> s{_nSmtpDelivery = a}) -- | Configuration for HTTP delivery. nHTTPDelivery :: Lens' Notification (Maybe HTTPDelivery) nHTTPDelivery = lens _nHTTPDelivery (\ s a -> s{_nHTTPDelivery = a}) -- | Configuration for Slack delivery. nSlackDelivery :: Lens' Notification (Maybe SlackDelivery) nSlackDelivery = lens _nSlackDelivery (\ s a -> s{_nSlackDelivery = a}) -- | The filter string to use for notification filtering. Currently, this is -- assumed to be a CEL program. See -- https:\/\/opensource.google\/projects\/cel for more. nFilter :: Lens' Notification (Maybe Text) nFilter = lens _nFilter (\ s a -> s{_nFilter = a}) instance FromJSON Notification where parseJSON = withObject "Notification" (\ o -> Notification' <$> (o .:? "structDelivery") <*> (o .:? "smtpDelivery") <*> (o .:? "httpDelivery") <*> (o .:? "slackDelivery") <*> (o .:? "filter")) instance ToJSON Notification where toJSON Notification'{..} = object (catMaybes [("structDelivery" .=) <$> _nStructDelivery, ("smtpDelivery" .=) <$> _nSmtpDelivery, ("httpDelivery" .=) <$> _nHTTPDelivery, ("slackDelivery" .=) <$> _nSlackDelivery, ("filter" .=) <$> _nFilter]) -- | Artifacts produced by a build that should be uploaded upon successful -- completion of all build steps. -- -- /See:/ 'artifacts' smart constructor. data Artifacts = Artifacts' { _aImages :: !(Maybe [Text]) , _aObjects :: !(Maybe ArtifactObjects) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Artifacts' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'aImages' -- -- * 'aObjects' artifacts :: Artifacts artifacts = Artifacts' {_aImages = Nothing, _aObjects = Nothing} -- | A list of images to be pushed upon the successful completion of all -- build steps. The images will be pushed using the builder service -- account\'s credentials. The digests of the pushed images will be stored -- in the Build resource\'s results field. If any of the images fail to be -- pushed, the build is marked FAILURE. aImages :: Lens' Artifacts [Text] aImages = lens _aImages (\ s a -> s{_aImages = a}) . _Default . _Coerce -- | A list of objects to be uploaded to Cloud Storage upon successful -- completion of all build steps. Files in the workspace matching specified -- paths globs will be uploaded to the specified Cloud Storage location -- using the builder service account\'s credentials. The location and -- generation of the uploaded objects will be stored in the Build -- resource\'s results field. If any objects fail to be pushed, the build -- is marked FAILURE. aObjects :: Lens' Artifacts (Maybe ArtifactObjects) aObjects = lens _aObjects (\ s a -> s{_aObjects = a}) instance FromJSON Artifacts where parseJSON = withObject "Artifacts" (\ o -> Artifacts' <$> (o .:? "images" .!= mempty) <*> (o .:? "objects")) instance ToJSON Artifacts where toJSON Artifacts'{..} = object (catMaybes [("images" .=) <$> _aImages, ("objects" .=) <$> _aObjects]) -- | Files in the workspace to upload to Cloud Storage upon successful -- completion of all build steps. -- -- /See:/ 'artifactObjects' smart constructor. data ArtifactObjects = ArtifactObjects' { _aoLocation :: !(Maybe Text) , _aoTiming :: !(Maybe TimeSpan) , _aoPaths :: !(Maybe [Text]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ArtifactObjects' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'aoLocation' -- -- * 'aoTiming' -- -- * 'aoPaths' artifactObjects :: ArtifactObjects artifactObjects = ArtifactObjects' {_aoLocation = Nothing, _aoTiming = Nothing, _aoPaths = Nothing} -- | Cloud Storage bucket and optional object path, in the form -- \"gs:\/\/bucket\/path\/to\/somewhere\/\". (see [Bucket Name -- Requirements](https:\/\/cloud.google.com\/storage\/docs\/bucket-naming#requirements)). -- Files in the workspace matching any path pattern will be uploaded to -- Cloud Storage with this location as a prefix. aoLocation :: Lens' ArtifactObjects (Maybe Text) aoLocation = lens _aoLocation (\ s a -> s{_aoLocation = a}) -- | Output only. Stores timing information for pushing all artifact objects. aoTiming :: Lens' ArtifactObjects (Maybe TimeSpan) aoTiming = lens _aoTiming (\ s a -> s{_aoTiming = a}) -- | Path globs used to match files in the build\'s workspace. aoPaths :: Lens' ArtifactObjects [Text] aoPaths = lens _aoPaths (\ s a -> s{_aoPaths = a}) . _Default . _Coerce instance FromJSON ArtifactObjects where parseJSON = withObject "ArtifactObjects" (\ o -> ArtifactObjects' <$> (o .:? "location") <*> (o .:? "timing") <*> (o .:? "paths" .!= mempty)) instance ToJSON ArtifactObjects where toJSON ArtifactObjects'{..} = object (catMaybes [("location" .=) <$> _aoLocation, ("timing" .=) <$> _aoTiming, ("paths" .=) <$> _aoPaths]) -- | GitHubEventsConfig describes the configuration of a trigger that creates -- a build whenever a GitHub event is received. This message is -- experimental. -- -- /See:/ 'gitHubEventsConfig' smart constructor. data GitHubEventsConfig = GitHubEventsConfig' { _ghecOwner :: !(Maybe Text) , _ghecPullRequest :: !(Maybe PullRequestFilter) , _ghecName :: !(Maybe Text) , _ghecPush :: !(Maybe PushFilter) , _ghecInstallationId :: !(Maybe (Textual Int64)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GitHubEventsConfig' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ghecOwner' -- -- * 'ghecPullRequest' -- -- * 'ghecName' -- -- * 'ghecPush' -- -- * 'ghecInstallationId' gitHubEventsConfig :: GitHubEventsConfig gitHubEventsConfig = GitHubEventsConfig' { _ghecOwner = Nothing , _ghecPullRequest = Nothing , _ghecName = Nothing , _ghecPush = Nothing , _ghecInstallationId = Nothing } -- | Owner of the repository. For example: The owner for -- https:\/\/github.com\/googlecloudplatform\/cloud-builders is -- \"googlecloudplatform\". ghecOwner :: Lens' GitHubEventsConfig (Maybe Text) ghecOwner = lens _ghecOwner (\ s a -> s{_ghecOwner = a}) -- | filter to match changes in pull requests. ghecPullRequest :: Lens' GitHubEventsConfig (Maybe PullRequestFilter) ghecPullRequest = lens _ghecPullRequest (\ s a -> s{_ghecPullRequest = a}) -- | Name of the repository. For example: The name for -- https:\/\/github.com\/googlecloudplatform\/cloud-builders is -- \"cloud-builders\". ghecName :: Lens' GitHubEventsConfig (Maybe Text) ghecName = lens _ghecName (\ s a -> s{_ghecName = a}) -- | filter to match changes in refs like branches, tags. ghecPush :: Lens' GitHubEventsConfig (Maybe PushFilter) ghecPush = lens _ghecPush (\ s a -> s{_ghecPush = a}) -- | The installationID that emits the GitHub event. ghecInstallationId :: Lens' GitHubEventsConfig (Maybe Int64) ghecInstallationId = lens _ghecInstallationId (\ s a -> s{_ghecInstallationId = a}) . mapping _Coerce instance FromJSON GitHubEventsConfig where parseJSON = withObject "GitHubEventsConfig" (\ o -> GitHubEventsConfig' <$> (o .:? "owner") <*> (o .:? "pullRequest") <*> (o .:? "name") <*> (o .:? "push") <*> (o .:? "installationId")) instance ToJSON GitHubEventsConfig where toJSON GitHubEventsConfig'{..} = object (catMaybes [("owner" .=) <$> _ghecOwner, ("pullRequest" .=) <$> _ghecPullRequest, ("name" .=) <$> _ghecName, ("push" .=) <$> _ghecPush, ("installationId" .=) <$> _ghecInstallationId]) -- | Response containing existing \`WorkerPools\`. -- -- /See:/ 'listWorkerPoolsResponse' smart constructor. data ListWorkerPoolsResponse = ListWorkerPoolsResponse' { _lwprNextPageToken :: !(Maybe Text) , _lwprWorkerPools :: !(Maybe [WorkerPool]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ListWorkerPoolsResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lwprNextPageToken' -- -- * 'lwprWorkerPools' listWorkerPoolsResponse :: ListWorkerPoolsResponse listWorkerPoolsResponse = ListWorkerPoolsResponse' {_lwprNextPageToken = Nothing, _lwprWorkerPools = Nothing} -- | Continuation token used to page through large result sets. Provide this -- value in a subsequent ListWorkerPoolsRequest to return the next page of -- results. lwprNextPageToken :: Lens' ListWorkerPoolsResponse (Maybe Text) lwprNextPageToken = lens _lwprNextPageToken (\ s a -> s{_lwprNextPageToken = a}) -- | \`WorkerPools\` for the specified project. lwprWorkerPools :: Lens' ListWorkerPoolsResponse [WorkerPool] lwprWorkerPools = lens _lwprWorkerPools (\ s a -> s{_lwprWorkerPools = a}) . _Default . _Coerce instance FromJSON ListWorkerPoolsResponse where parseJSON = withObject "ListWorkerPoolsResponse" (\ o -> ListWorkerPoolsResponse' <$> (o .:? "nextPageToken") <*> (o .:? "workerPools" .!= mempty)) instance ToJSON ListWorkerPoolsResponse where toJSON ListWorkerPoolsResponse'{..} = object (catMaybes [("nextPageToken" .=) <$> _lwprNextPageToken, ("workerPools" .=) <$> _lwprWorkerPools]) -- | Volume describes a Docker container volume which is mounted into build -- steps in order to persist files across build step execution. -- -- /See:/ 'volume' smart constructor. data Volume = Volume' { _vPath :: !(Maybe Text) , _vName :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Volume' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'vPath' -- -- * 'vName' volume :: Volume volume = Volume' {_vPath = Nothing, _vName = Nothing} -- | Path at which to mount the volume. Paths must be absolute and cannot -- conflict with other volume paths on the same build step or with certain -- reserved volume paths. vPath :: Lens' Volume (Maybe Text) vPath = lens _vPath (\ s a -> s{_vPath = a}) -- | Name of the volume to mount. Volume names must be unique per build step -- and must be valid names for Docker volumes. Each named volume must be -- used by at least two build steps. vName :: Lens' Volume (Maybe Text) vName = lens _vName (\ s a -> s{_vName = a}) instance FromJSON Volume where parseJSON = withObject "Volume" (\ o -> Volume' <$> (o .:? "path") <*> (o .:? "name")) instance ToJSON Volume where toJSON Volume'{..} = object (catMaybes [("path" .=) <$> _vPath, ("name" .=) <$> _vName]) -- | NotifierSecretRef contains the reference to a secret stored in the -- corresponding NotifierSpec. -- -- /See:/ 'notifierSecretRef' smart constructor. newtype NotifierSecretRef = NotifierSecretRef' { _nsrSecretRef :: Maybe Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'NotifierSecretRef' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'nsrSecretRef' notifierSecretRef :: NotifierSecretRef notifierSecretRef = NotifierSecretRef' {_nsrSecretRef = Nothing} -- | The value of \`secret_ref\` should be a \`name\` that is registered in a -- \`Secret\` in the \`secrets\` list of the \`Spec\`. nsrSecretRef :: Lens' NotifierSecretRef (Maybe Text) nsrSecretRef = lens _nsrSecretRef (\ s a -> s{_nsrSecretRef = a}) instance FromJSON NotifierSecretRef where parseJSON = withObject "NotifierSecretRef" (\ o -> NotifierSecretRef' <$> (o .:? "secretRef")) instance ToJSON NotifierSecretRef where toJSON NotifierSecretRef'{..} = object (catMaybes [("secretRef" .=) <$> _nsrSecretRef]) -- | ReceiveTriggerWebhookResponse [Experimental] is the response object for -- the ReceiveTriggerWebhook method. -- -- /See:/ 'receiveTriggerWebhookResponse' smart constructor. data ReceiveTriggerWebhookResponse = ReceiveTriggerWebhookResponse' deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ReceiveTriggerWebhookResponse' with the minimum fields required to make a request. -- receiveTriggerWebhookResponse :: ReceiveTriggerWebhookResponse receiveTriggerWebhookResponse = ReceiveTriggerWebhookResponse' instance FromJSON ReceiveTriggerWebhookResponse where parseJSON = withObject "ReceiveTriggerWebhookResponse" (\ o -> pure ReceiveTriggerWebhookResponse') instance ToJSON ReceiveTriggerWebhookResponse where toJSON = const emptyObject -- | Location of the source manifest in Google Cloud Storage. This feature is -- in Preview; see description -- [here](https:\/\/github.com\/GoogleCloudPlatform\/cloud-builders\/tree\/master\/gcs-fetcher). -- -- /See:/ 'storageSourceManifest' smart constructor. data StorageSourceManifest = StorageSourceManifest' { _ssmBucket :: !(Maybe Text) , _ssmObject :: !(Maybe Text) , _ssmGeneration :: !(Maybe (Textual Int64)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'StorageSourceManifest' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ssmBucket' -- -- * 'ssmObject' -- -- * 'ssmGeneration' storageSourceManifest :: StorageSourceManifest storageSourceManifest = StorageSourceManifest' {_ssmBucket = Nothing, _ssmObject = Nothing, _ssmGeneration = Nothing} -- | Google Cloud Storage bucket containing the source manifest (see [Bucket -- Name -- Requirements](https:\/\/cloud.google.com\/storage\/docs\/bucket-naming#requirements)). ssmBucket :: Lens' StorageSourceManifest (Maybe Text) ssmBucket = lens _ssmBucket (\ s a -> s{_ssmBucket = a}) -- | Google Cloud Storage object containing the source manifest. This object -- must be a JSON file. ssmObject :: Lens' StorageSourceManifest (Maybe Text) ssmObject = lens _ssmObject (\ s a -> s{_ssmObject = a}) -- | Google Cloud Storage generation for the object. If the generation is -- omitted, the latest generation will be used. ssmGeneration :: Lens' StorageSourceManifest (Maybe Int64) ssmGeneration = lens _ssmGeneration (\ s a -> s{_ssmGeneration = a}) . mapping _Coerce instance FromJSON StorageSourceManifest where parseJSON = withObject "StorageSourceManifest" (\ o -> StorageSourceManifest' <$> (o .:? "bucket") <*> (o .:? "object") <*> (o .:? "generation")) instance ToJSON StorageSourceManifest where toJSON StorageSourceManifest'{..} = object (catMaybes [("bucket" .=) <$> _ssmBucket, ("object" .=) <$> _ssmObject, ("generation" .=) <$> _ssmGeneration]) -- | Metadata for the \`DeleteWorkerPool\` operation. -- -- /See:/ 'deleteWorkerPoolOperationMetadata' smart constructor. data DeleteWorkerPoolOperationMetadata = DeleteWorkerPoolOperationMetadata' { _dwpomCompleteTime :: !(Maybe DateTime') , _dwpomWorkerPool :: !(Maybe Text) , _dwpomCreateTime :: !(Maybe DateTime') } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'DeleteWorkerPoolOperationMetadata' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dwpomCompleteTime' -- -- * 'dwpomWorkerPool' -- -- * 'dwpomCreateTime' deleteWorkerPoolOperationMetadata :: DeleteWorkerPoolOperationMetadata deleteWorkerPoolOperationMetadata = DeleteWorkerPoolOperationMetadata' { _dwpomCompleteTime = Nothing , _dwpomWorkerPool = Nothing , _dwpomCreateTime = Nothing } -- | Time the operation was completed. dwpomCompleteTime :: Lens' DeleteWorkerPoolOperationMetadata (Maybe UTCTime) dwpomCompleteTime = lens _dwpomCompleteTime (\ s a -> s{_dwpomCompleteTime = a}) . mapping _DateTime -- | The resource name of the \`WorkerPool\` being deleted. Format: -- \`projects\/{project}\/locations\/{location}\/workerPools\/{worker_pool}\`. dwpomWorkerPool :: Lens' DeleteWorkerPoolOperationMetadata (Maybe Text) dwpomWorkerPool = lens _dwpomWorkerPool (\ s a -> s{_dwpomWorkerPool = a}) -- | Time the operation was created. dwpomCreateTime :: Lens' DeleteWorkerPoolOperationMetadata (Maybe UTCTime) dwpomCreateTime = lens _dwpomCreateTime (\ s a -> s{_dwpomCreateTime = a}) . mapping _DateTime instance FromJSON DeleteWorkerPoolOperationMetadata where parseJSON = withObject "DeleteWorkerPoolOperationMetadata" (\ o -> DeleteWorkerPoolOperationMetadata' <$> (o .:? "completeTime") <*> (o .:? "workerPool") <*> (o .:? "createTime")) instance ToJSON DeleteWorkerPoolOperationMetadata where toJSON DeleteWorkerPoolOperationMetadata'{..} = object (catMaybes [("completeTime" .=) <$> _dwpomCompleteTime, ("workerPool" .=) <$> _dwpomWorkerPool, ("createTime" .=) <$> _dwpomCreateTime]) -- | Metadata for the \`UpdateWorkerPool\` operation. -- -- /See:/ 'updateWorkerPoolOperationMetadata' smart constructor. data UpdateWorkerPoolOperationMetadata = UpdateWorkerPoolOperationMetadata' { _uwpomCompleteTime :: !(Maybe DateTime') , _uwpomWorkerPool :: !(Maybe Text) , _uwpomCreateTime :: !(Maybe DateTime') } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'UpdateWorkerPoolOperationMetadata' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'uwpomCompleteTime' -- -- * 'uwpomWorkerPool' -- -- * 'uwpomCreateTime' updateWorkerPoolOperationMetadata :: UpdateWorkerPoolOperationMetadata updateWorkerPoolOperationMetadata = UpdateWorkerPoolOperationMetadata' { _uwpomCompleteTime = Nothing , _uwpomWorkerPool = Nothing , _uwpomCreateTime = Nothing } -- | Time the operation was completed. uwpomCompleteTime :: Lens' UpdateWorkerPoolOperationMetadata (Maybe UTCTime) uwpomCompleteTime = lens _uwpomCompleteTime (\ s a -> s{_uwpomCompleteTime = a}) . mapping _DateTime -- | The resource name of the \`WorkerPool\` being updated. Format: -- \`projects\/{project}\/locations\/{location}\/workerPools\/{worker_pool}\`. uwpomWorkerPool :: Lens' UpdateWorkerPoolOperationMetadata (Maybe Text) uwpomWorkerPool = lens _uwpomWorkerPool (\ s a -> s{_uwpomWorkerPool = a}) -- | Time the operation was created. uwpomCreateTime :: Lens' UpdateWorkerPoolOperationMetadata (Maybe UTCTime) uwpomCreateTime = lens _uwpomCreateTime (\ s a -> s{_uwpomCreateTime = a}) . mapping _DateTime instance FromJSON UpdateWorkerPoolOperationMetadata where parseJSON = withObject "UpdateWorkerPoolOperationMetadata" (\ o -> UpdateWorkerPoolOperationMetadata' <$> (o .:? "completeTime") <*> (o .:? "workerPool") <*> (o .:? "createTime")) instance ToJSON UpdateWorkerPoolOperationMetadata where toJSON UpdateWorkerPoolOperationMetadata'{..} = object (catMaybes [("completeTime" .=) <$> _uwpomCompleteTime, ("workerPool" .=) <$> _uwpomWorkerPool, ("createTime" .=) <$> _uwpomCreateTime]) -- | Pairs a secret environment variable with a SecretVersion in Secret -- Manager. -- -- /See:/ 'secretManagerSecret' smart constructor. data SecretManagerSecret = SecretManagerSecret' { _smsVersionName :: !(Maybe Text) , _smsEnv :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'SecretManagerSecret' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'smsVersionName' -- -- * 'smsEnv' secretManagerSecret :: SecretManagerSecret secretManagerSecret = SecretManagerSecret' {_smsVersionName = Nothing, _smsEnv = Nothing} -- | Resource name of the SecretVersion. In format: -- projects\/*\/secrets\/*\/versions\/* smsVersionName :: Lens' SecretManagerSecret (Maybe Text) smsVersionName = lens _smsVersionName (\ s a -> s{_smsVersionName = a}) -- | Environment variable name to associate with the secret. Secret -- environment variables must be unique across all of a build\'s secrets, -- and must be used by at least one build step. smsEnv :: Lens' SecretManagerSecret (Maybe Text) smsEnv = lens _smsEnv (\ s a -> s{_smsEnv = a}) instance FromJSON SecretManagerSecret where parseJSON = withObject "SecretManagerSecret" (\ o -> SecretManagerSecret' <$> (o .:? "versionName") <*> (o .:? "env")) instance ToJSON SecretManagerSecret where toJSON SecretManagerSecret'{..} = object (catMaybes [("versionName" .=) <$> _smsVersionName, ("env" .=) <$> _smsEnv]) -- -- /See:/ 'statusDetailsItem' smart constructor. newtype StatusDetailsItem = StatusDetailsItem' { _sdiAddtional :: HashMap Text JSONValue } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'StatusDetailsItem' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'sdiAddtional' statusDetailsItem :: HashMap Text JSONValue -- ^ 'sdiAddtional' -> StatusDetailsItem statusDetailsItem pSdiAddtional_ = StatusDetailsItem' {_sdiAddtional = _Coerce # pSdiAddtional_} -- | Properties of the object. Contains field \'type with type URL. sdiAddtional :: Lens' StatusDetailsItem (HashMap Text JSONValue) sdiAddtional = lens _sdiAddtional (\ s a -> s{_sdiAddtional = a}) . _Coerce instance FromJSON StatusDetailsItem where parseJSON = withObject "StatusDetailsItem" (\ o -> StatusDetailsItem' <$> (parseJSONObject o)) instance ToJSON StatusDetailsItem where toJSON = toJSON . _sdiAddtional -- | A build resource in the Cloud Build API. At a high level, a \`Build\` -- describes where to find source code, how to build it (for example, the -- builder image to run on the source), and where to store the built -- artifacts. Fields can include the following variables, which will be -- expanded when the build is created: - $PROJECT_ID: the project ID of the -- build. - $PROJECT_NUMBER: the project number of the build. - $BUILD_ID: -- the autogenerated ID of the build. - $REPO_NAME: the source repository -- name specified by RepoSource. - $BRANCH_NAME: the branch name specified -- by RepoSource. - $TAG_NAME: the tag name specified by RepoSource. - -- $REVISION_ID or $COMMIT_SHA: the commit SHA specified by RepoSource or -- resolved from the specified branch or tag. - $SHORT_SHA: first 7 -- characters of $REVISION_ID or $COMMIT_SHA. -- -- /See:/ 'build' smart constructor. data Build = Build' { _bAvailableSecrets :: !(Maybe Secrets) , _bImages :: !(Maybe [Text]) , _bStatus :: !(Maybe BuildStatus) , _bSourceProvenance :: !(Maybe SourceProvenance) , _bSubstitutions :: !(Maybe BuildSubstitutions) , _bLogURL :: !(Maybe Text) , _bResults :: !(Maybe Results) , _bSecrets :: !(Maybe [Secret]) , _bStartTime :: !(Maybe DateTime') , _bArtifacts :: !(Maybe Artifacts) , _bFailureInfo :: !(Maybe FailureInfo) , _bWarnings :: !(Maybe [Warning]) , _bLogsBucket :: !(Maybe Text) , _bSteps :: !(Maybe [BuildStep]) , _bServiceAccount :: !(Maybe Text) , _bName :: !(Maybe Text) , _bStatusDetail :: !(Maybe Text) , _bSource :: !(Maybe Source) , _bId :: !(Maybe Text) , _bQueueTtl :: !(Maybe GDuration) , _bOptions :: !(Maybe BuildOptions) , _bProjectId :: !(Maybe Text) , _bTiming :: !(Maybe BuildTiming) , _bBuildTriggerId :: !(Maybe Text) , _bTimeout :: !(Maybe GDuration) , _bFinishTime :: !(Maybe DateTime') , _bCreateTime :: !(Maybe DateTime') , _bTags :: !(Maybe [Text]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Build' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'bAvailableSecrets' -- -- * 'bImages' -- -- * 'bStatus' -- -- * 'bSourceProvenance' -- -- * 'bSubstitutions' -- -- * 'bLogURL' -- -- * 'bResults' -- -- * 'bSecrets' -- -- * 'bStartTime' -- -- * 'bArtifacts' -- -- * 'bFailureInfo' -- -- * 'bWarnings' -- -- * 'bLogsBucket' -- -- * 'bSteps' -- -- * 'bServiceAccount' -- -- * 'bName' -- -- * 'bStatusDetail' -- -- * 'bSource' -- -- * 'bId' -- -- * 'bQueueTtl' -- -- * 'bOptions' -- -- * 'bProjectId' -- -- * 'bTiming' -- -- * 'bBuildTriggerId' -- -- * 'bTimeout' -- -- * 'bFinishTime' -- -- * 'bCreateTime' -- -- * 'bTags' build :: Build build = Build' { _bAvailableSecrets = Nothing , _bImages = Nothing , _bStatus = Nothing , _bSourceProvenance = Nothing , _bSubstitutions = Nothing , _bLogURL = Nothing , _bResults = Nothing , _bSecrets = Nothing , _bStartTime = Nothing , _bArtifacts = Nothing , _bFailureInfo = Nothing , _bWarnings = Nothing , _bLogsBucket = Nothing , _bSteps = Nothing , _bServiceAccount = Nothing , _bName = Nothing , _bStatusDetail = Nothing , _bSource = Nothing , _bId = Nothing , _bQueueTtl = Nothing , _bOptions = Nothing , _bProjectId = Nothing , _bTiming = Nothing , _bBuildTriggerId = Nothing , _bTimeout = Nothing , _bFinishTime = Nothing , _bCreateTime = Nothing , _bTags = Nothing } -- | Secrets and secret environment variables. bAvailableSecrets :: Lens' Build (Maybe Secrets) bAvailableSecrets = lens _bAvailableSecrets (\ s a -> s{_bAvailableSecrets = a}) -- | A list of images to be pushed upon the successful completion of all -- build steps. The images are pushed using the builder service account\'s -- credentials. The digests of the pushed images will be stored in the -- \`Build\` resource\'s results field. If any of the images fail to be -- pushed, the build status is marked \`FAILURE\`. bImages :: Lens' Build [Text] bImages = lens _bImages (\ s a -> s{_bImages = a}) . _Default . _Coerce -- | Output only. Status of the build. bStatus :: Lens' Build (Maybe BuildStatus) bStatus = lens _bStatus (\ s a -> s{_bStatus = a}) -- | Output only. A permanent fixed identifier for source. bSourceProvenance :: Lens' Build (Maybe SourceProvenance) bSourceProvenance = lens _bSourceProvenance (\ s a -> s{_bSourceProvenance = a}) -- | Substitutions data for \`Build\` resource. bSubstitutions :: Lens' Build (Maybe BuildSubstitutions) bSubstitutions = lens _bSubstitutions (\ s a -> s{_bSubstitutions = a}) -- | Output only. URL to logs for this build in Google Cloud Console. bLogURL :: Lens' Build (Maybe Text) bLogURL = lens _bLogURL (\ s a -> s{_bLogURL = a}) -- | Output only. Results of the build. bResults :: Lens' Build (Maybe Results) bResults = lens _bResults (\ s a -> s{_bResults = a}) -- | Secrets to decrypt using Cloud Key Management Service. Note: Secret -- Manager is the recommended technique for managing sensitive data with -- Cloud Build. Use \`available_secrets\` to configure builds to access -- secrets from Secret Manager. For instructions, see: -- https:\/\/cloud.google.com\/cloud-build\/docs\/securing-builds\/use-secrets bSecrets :: Lens' Build [Secret] bSecrets = lens _bSecrets (\ s a -> s{_bSecrets = a}) . _Default . _Coerce -- | Output only. Time at which execution of the build was started. bStartTime :: Lens' Build (Maybe UTCTime) bStartTime = lens _bStartTime (\ s a -> s{_bStartTime = a}) . mapping _DateTime -- | Artifacts produced by the build that should be uploaded upon successful -- completion of all build steps. bArtifacts :: Lens' Build (Maybe Artifacts) bArtifacts = lens _bArtifacts (\ s a -> s{_bArtifacts = a}) -- | Output only. Contains information about the build when status=FAILURE. bFailureInfo :: Lens' Build (Maybe FailureInfo) bFailureInfo = lens _bFailureInfo (\ s a -> s{_bFailureInfo = a}) -- | Output only. Non-fatal problems encountered during the execution of the -- build. bWarnings :: Lens' Build [Warning] bWarnings = lens _bWarnings (\ s a -> s{_bWarnings = a}) . _Default . _Coerce -- | Google Cloud Storage bucket where logs should be written (see [Bucket -- Name -- Requirements](https:\/\/cloud.google.com\/storage\/docs\/bucket-naming#requirements)). -- Logs file names will be of the format -- \`${logs_bucket}\/log-${build_id}.txt\`. bLogsBucket :: Lens' Build (Maybe Text) bLogsBucket = lens _bLogsBucket (\ s a -> s{_bLogsBucket = a}) -- | Required. The operations to be performed on the workspace. bSteps :: Lens' Build [BuildStep] bSteps = lens _bSteps (\ s a -> s{_bSteps = a}) . _Default . _Coerce -- | IAM service account whose credentials will be used at build runtime. -- Must be of the format -- \`projects\/{PROJECT_ID}\/serviceAccounts\/{ACCOUNT}\`. ACCOUNT can be -- email address or uniqueId of the service account. bServiceAccount :: Lens' Build (Maybe Text) bServiceAccount = lens _bServiceAccount (\ s a -> s{_bServiceAccount = a}) -- | Output only. The \'Build\' name with format: -- \`projects\/{project}\/locations\/{location}\/builds\/{build}\`, where -- {build} is a unique identifier generated by the service. bName :: Lens' Build (Maybe Text) bName = lens _bName (\ s a -> s{_bName = a}) -- | Output only. Customer-readable message about the current status. bStatusDetail :: Lens' Build (Maybe Text) bStatusDetail = lens _bStatusDetail (\ s a -> s{_bStatusDetail = a}) -- | The location of the source files to build. bSource :: Lens' Build (Maybe Source) bSource = lens _bSource (\ s a -> s{_bSource = a}) -- | Output only. Unique identifier of the build. bId :: Lens' Build (Maybe Text) bId = lens _bId (\ s a -> s{_bId = a}) -- | TTL in queue for this build. If provided and the build is enqueued -- longer than this value, the build will expire and the build status will -- be \`EXPIRED\`. The TTL starts ticking from create_time. bQueueTtl :: Lens' Build (Maybe Scientific) bQueueTtl = lens _bQueueTtl (\ s a -> s{_bQueueTtl = a}) . mapping _GDuration -- | Special options for this build. bOptions :: Lens' Build (Maybe BuildOptions) bOptions = lens _bOptions (\ s a -> s{_bOptions = a}) -- | Output only. ID of the project. bProjectId :: Lens' Build (Maybe Text) bProjectId = lens _bProjectId (\ s a -> s{_bProjectId = a}) -- | Output only. Stores timing information for phases of the build. Valid -- keys are: * BUILD: time to execute all build steps * PUSH: time to push -- all specified images. * FETCHSOURCE: time to fetch source. If the build -- does not specify source or images, these keys will not be included. bTiming :: Lens' Build (Maybe BuildTiming) bTiming = lens _bTiming (\ s a -> s{_bTiming = a}) -- | Output only. The ID of the \`BuildTrigger\` that triggered this build, -- if it was triggered automatically. bBuildTriggerId :: Lens' Build (Maybe Text) bBuildTriggerId = lens _bBuildTriggerId (\ s a -> s{_bBuildTriggerId = a}) -- | Amount of time that this build should be allowed to run, to second -- granularity. If this amount of time elapses, work on the build will -- cease and the build status will be \`TIMEOUT\`. \`timeout\` starts -- ticking from \`startTime\`. Default time is ten minutes. bTimeout :: Lens' Build (Maybe Scientific) bTimeout = lens _bTimeout (\ s a -> s{_bTimeout = a}) . mapping _GDuration -- | Output only. Time at which execution of the build was finished. The -- difference between finish_time and start_time is the duration of the -- build\'s execution. bFinishTime :: Lens' Build (Maybe UTCTime) bFinishTime = lens _bFinishTime (\ s a -> s{_bFinishTime = a}) . mapping _DateTime -- | Output only. Time at which the request to create the build was received. bCreateTime :: Lens' Build (Maybe UTCTime) bCreateTime = lens _bCreateTime (\ s a -> s{_bCreateTime = a}) . mapping _DateTime -- | Tags for annotation of a \`Build\`. These are not docker tags. bTags :: Lens' Build [Text] bTags = lens _bTags (\ s a -> s{_bTags = a}) . _Default . _Coerce instance FromJSON Build where parseJSON = withObject "Build" (\ o -> Build' <$> (o .:? "availableSecrets") <*> (o .:? "images" .!= mempty) <*> (o .:? "status") <*> (o .:? "sourceProvenance") <*> (o .:? "substitutions") <*> (o .:? "logUrl") <*> (o .:? "results") <*> (o .:? "secrets" .!= mempty) <*> (o .:? "startTime") <*> (o .:? "artifacts") <*> (o .:? "failureInfo") <*> (o .:? "warnings" .!= mempty) <*> (o .:? "logsBucket") <*> (o .:? "steps" .!= mempty) <*> (o .:? "serviceAccount") <*> (o .:? "name") <*> (o .:? "statusDetail") <*> (o .:? "source") <*> (o .:? "id") <*> (o .:? "queueTtl") <*> (o .:? "options") <*> (o .:? "projectId") <*> (o .:? "timing") <*> (o .:? "buildTriggerId") <*> (o .:? "timeout") <*> (o .:? "finishTime") <*> (o .:? "createTime") <*> (o .:? "tags" .!= mempty)) instance ToJSON Build where toJSON Build'{..} = object (catMaybes [("availableSecrets" .=) <$> _bAvailableSecrets, ("images" .=) <$> _bImages, ("status" .=) <$> _bStatus, ("sourceProvenance" .=) <$> _bSourceProvenance, ("substitutions" .=) <$> _bSubstitutions, ("logUrl" .=) <$> _bLogURL, ("results" .=) <$> _bResults, ("secrets" .=) <$> _bSecrets, ("startTime" .=) <$> _bStartTime, ("artifacts" .=) <$> _bArtifacts, ("failureInfo" .=) <$> _bFailureInfo, ("warnings" .=) <$> _bWarnings, ("logsBucket" .=) <$> _bLogsBucket, ("steps" .=) <$> _bSteps, ("serviceAccount" .=) <$> _bServiceAccount, ("name" .=) <$> _bName, ("statusDetail" .=) <$> _bStatusDetail, ("source" .=) <$> _bSource, ("id" .=) <$> _bId, ("queueTtl" .=) <$> _bQueueTtl, ("options" .=) <$> _bOptions, ("projectId" .=) <$> _bProjectId, ("timing" .=) <$> _bTiming, ("buildTriggerId" .=) <$> _bBuildTriggerId, ("timeout" .=) <$> _bTimeout, ("finishTime" .=) <$> _bFinishTime, ("createTime" .=) <$> _bCreateTime, ("tags" .=) <$> _bTags]) -- | Map of environment variable name to its encrypted value. Secret -- environment variables must be unique across all of a build\'s secrets, -- and must be used by at least one build step. Values can be at most 64 KB -- in size. There can be at most 100 secret values across all of a build\'s -- secrets. -- -- /See:/ 'inlineSecretEnvMap' smart constructor. newtype InlineSecretEnvMap = InlineSecretEnvMap' { _isemAddtional :: HashMap Text Bytes } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'InlineSecretEnvMap' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'isemAddtional' inlineSecretEnvMap :: HashMap Text ByteString -- ^ 'isemAddtional' -> InlineSecretEnvMap inlineSecretEnvMap pIsemAddtional_ = InlineSecretEnvMap' {_isemAddtional = _Coerce # pIsemAddtional_} isemAddtional :: Lens' InlineSecretEnvMap (HashMap Text ByteString) isemAddtional = lens _isemAddtional (\ s a -> s{_isemAddtional = a}) . _Coerce instance FromJSON InlineSecretEnvMap where parseJSON = withObject "InlineSecretEnvMap" (\ o -> InlineSecretEnvMap' <$> (parseJSONObject o)) instance ToJSON InlineSecretEnvMap where toJSON = toJSON . _isemAddtional -- | A fatal problem encountered during the execution of the build. -- -- /See:/ 'failureInfo' smart constructor. data FailureInfo = FailureInfo' { _fiType :: !(Maybe FailureInfoType) , _fiDetail :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'FailureInfo' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'fiType' -- -- * 'fiDetail' failureInfo :: FailureInfo failureInfo = FailureInfo' {_fiType = Nothing, _fiDetail = Nothing} -- | The name of the failure. fiType :: Lens' FailureInfo (Maybe FailureInfoType) fiType = lens _fiType (\ s a -> s{_fiType = a}) -- | Explains the failure issue in more detail using hard-coded text. fiDetail :: Lens' FailureInfo (Maybe Text) fiDetail = lens _fiDetail (\ s a -> s{_fiDetail = a}) instance FromJSON FailureInfo where parseJSON = withObject "FailureInfo" (\ o -> FailureInfo' <$> (o .:? "type") <*> (o .:? "detail")) instance ToJSON FailureInfo where toJSON FailureInfo'{..} = object (catMaybes [("type" .=) <$> _fiType, ("detail" .=) <$> _fiDetail]) -- | Metadata for the \`CreateWorkerPool\` operation. -- -- /See:/ 'createWorkerPoolOperationMetadata' smart constructor. data CreateWorkerPoolOperationMetadata = CreateWorkerPoolOperationMetadata' { _cwpomCompleteTime :: !(Maybe DateTime') , _cwpomWorkerPool :: !(Maybe Text) , _cwpomCreateTime :: !(Maybe DateTime') } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'CreateWorkerPoolOperationMetadata' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'cwpomCompleteTime' -- -- * 'cwpomWorkerPool' -- -- * 'cwpomCreateTime' createWorkerPoolOperationMetadata :: CreateWorkerPoolOperationMetadata createWorkerPoolOperationMetadata = CreateWorkerPoolOperationMetadata' { _cwpomCompleteTime = Nothing , _cwpomWorkerPool = Nothing , _cwpomCreateTime = Nothing } -- | Time the operation was completed. cwpomCompleteTime :: Lens' CreateWorkerPoolOperationMetadata (Maybe UTCTime) cwpomCompleteTime = lens _cwpomCompleteTime (\ s a -> s{_cwpomCompleteTime = a}) . mapping _DateTime -- | The resource name of the \`WorkerPool\` to create. Format: -- \`projects\/{project}\/locations\/{location}\/workerPools\/{worker_pool}\`. cwpomWorkerPool :: Lens' CreateWorkerPoolOperationMetadata (Maybe Text) cwpomWorkerPool = lens _cwpomWorkerPool (\ s a -> s{_cwpomWorkerPool = a}) -- | Time the operation was created. cwpomCreateTime :: Lens' CreateWorkerPoolOperationMetadata (Maybe UTCTime) cwpomCreateTime = lens _cwpomCreateTime (\ s a -> s{_cwpomCreateTime = a}) . mapping _DateTime instance FromJSON CreateWorkerPoolOperationMetadata where parseJSON = withObject "CreateWorkerPoolOperationMetadata" (\ o -> CreateWorkerPoolOperationMetadata' <$> (o .:? "completeTime") <*> (o .:? "workerPool") <*> (o .:? "createTime")) instance ToJSON CreateWorkerPoolOperationMetadata where toJSON CreateWorkerPoolOperationMetadata'{..} = object (catMaybes [("completeTime" .=) <$> _cwpomCompleteTime, ("workerPool" .=) <$> _cwpomWorkerPool, ("createTime" .=) <$> _cwpomCreateTime]) -- | Output only. Hash(es) of the build source, which can be used to verify -- that the original source integrity was maintained in the build. Note -- that \`FileHashes\` will only be populated if \`BuildOptions\` has -- requested a \`SourceProvenanceHash\`. The keys to this map are file -- paths used as build source and the values contain the hash values for -- those files. If the build source came in a single package such as a -- gzipped tarfile (\`.tar.gz\`), the \`FileHash\` will be for the single -- path to that file. -- -- /See:/ 'sourceProvenanceFileHashes' smart constructor. newtype SourceProvenanceFileHashes = SourceProvenanceFileHashes' { _spfhAddtional :: HashMap Text FileHashes } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'SourceProvenanceFileHashes' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'spfhAddtional' sourceProvenanceFileHashes :: HashMap Text FileHashes -- ^ 'spfhAddtional' -> SourceProvenanceFileHashes sourceProvenanceFileHashes pSpfhAddtional_ = SourceProvenanceFileHashes' {_spfhAddtional = _Coerce # pSpfhAddtional_} spfhAddtional :: Lens' SourceProvenanceFileHashes (HashMap Text FileHashes) spfhAddtional = lens _spfhAddtional (\ s a -> s{_spfhAddtional = a}) . _Coerce instance FromJSON SourceProvenanceFileHashes where parseJSON = withObject "SourceProvenanceFileHashes" (\ o -> SourceProvenanceFileHashes' <$> (parseJSONObject o)) instance ToJSON SourceProvenanceFileHashes where toJSON = toJSON . _spfhAddtional -- | User specified annotations. See -- https:\/\/google.aip.dev\/128#annotations for more details such as -- format and size limitations. -- -- /See:/ 'workerPoolAnnotations' smart constructor. newtype WorkerPoolAnnotations = WorkerPoolAnnotations' { _wpaAddtional :: HashMap Text Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'WorkerPoolAnnotations' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'wpaAddtional' workerPoolAnnotations :: HashMap Text Text -- ^ 'wpaAddtional' -> WorkerPoolAnnotations workerPoolAnnotations pWpaAddtional_ = WorkerPoolAnnotations' {_wpaAddtional = _Coerce # pWpaAddtional_} wpaAddtional :: Lens' WorkerPoolAnnotations (HashMap Text Text) wpaAddtional = lens _wpaAddtional (\ s a -> s{_wpaAddtional = a}) . _Coerce instance FromJSON WorkerPoolAnnotations where parseJSON = withObject "WorkerPoolAnnotations" (\ o -> WorkerPoolAnnotations' <$> (parseJSONObject o)) instance ToJSON WorkerPoolAnnotations where toJSON = toJSON . _wpaAddtional -- | SMTPDelivery is the delivery configuration for an SMTP (email) -- notification. -- -- /See:/ 'sMTPDelivery' smart constructor. data SMTPDelivery = SMTPDelivery' { _smtpdSenderAddress :: !(Maybe Text) , _smtpdFromAddress :: !(Maybe Text) , _smtpdRecipientAddresses :: !(Maybe [Text]) , _smtpdPassword :: !(Maybe NotifierSecretRef) , _smtpdServer :: !(Maybe Text) , _smtpdPort :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'SMTPDelivery' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'smtpdSenderAddress' -- -- * 'smtpdFromAddress' -- -- * 'smtpdRecipientAddresses' -- -- * 'smtpdPassword' -- -- * 'smtpdServer' -- -- * 'smtpdPort' sMTPDelivery :: SMTPDelivery sMTPDelivery = SMTPDelivery' { _smtpdSenderAddress = Nothing , _smtpdFromAddress = Nothing , _smtpdRecipientAddresses = Nothing , _smtpdPassword = Nothing , _smtpdServer = Nothing , _smtpdPort = Nothing } -- | This is the SMTP account\/email that is used to send the message. smtpdSenderAddress :: Lens' SMTPDelivery (Maybe Text) smtpdSenderAddress = lens _smtpdSenderAddress (\ s a -> s{_smtpdSenderAddress = a}) -- | This is the SMTP account\/email that appears in the \`From:\` of the -- email. If empty, it is assumed to be sender. smtpdFromAddress :: Lens' SMTPDelivery (Maybe Text) smtpdFromAddress = lens _smtpdFromAddress (\ s a -> s{_smtpdFromAddress = a}) -- | This is the list of addresses to which we send the email (i.e. in the -- \`To:\` of the email). smtpdRecipientAddresses :: Lens' SMTPDelivery [Text] smtpdRecipientAddresses = lens _smtpdRecipientAddresses (\ s a -> s{_smtpdRecipientAddresses = a}) . _Default . _Coerce -- | The SMTP sender\'s password. smtpdPassword :: Lens' SMTPDelivery (Maybe NotifierSecretRef) smtpdPassword = lens _smtpdPassword (\ s a -> s{_smtpdPassword = a}) -- | The address of the SMTP server. smtpdServer :: Lens' SMTPDelivery (Maybe Text) smtpdServer = lens _smtpdServer (\ s a -> s{_smtpdServer = a}) -- | The SMTP port of the server. smtpdPort :: Lens' SMTPDelivery (Maybe Text) smtpdPort = lens _smtpdPort (\ s a -> s{_smtpdPort = a}) instance FromJSON SMTPDelivery where parseJSON = withObject "SMTPDelivery" (\ o -> SMTPDelivery' <$> (o .:? "senderAddress") <*> (o .:? "fromAddress") <*> (o .:? "recipientAddresses" .!= mempty) <*> (o .:? "password") <*> (o .:? "server") <*> (o .:? "port")) instance ToJSON SMTPDelivery where toJSON SMTPDelivery'{..} = object (catMaybes [("senderAddress" .=) <$> _smtpdSenderAddress, ("fromAddress" .=) <$> _smtpdFromAddress, ("recipientAddresses" .=) <$> _smtpdRecipientAddresses, ("password" .=) <$> _smtpdPassword, ("server" .=) <$> _smtpdServer, ("port" .=) <$> _smtpdPort]) -- | Pairs a set of secret environment variables containing encrypted values -- with the Cloud KMS key to use to decrypt the value. Note: Use -- \`kmsKeyName\` with \`available_secrets\` instead of using -- \`kmsKeyName\` with \`secret\`. For instructions see: -- https:\/\/cloud.google.com\/cloud-build\/docs\/securing-builds\/use-encrypted-credentials. -- -- /See:/ 'secret' smart constructor. data Secret = Secret' { _sKmsKeyName :: !(Maybe Text) , _sSecretEnv :: !(Maybe SecretSecretEnv) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Secret' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'sKmsKeyName' -- -- * 'sSecretEnv' secret :: Secret secret = Secret' {_sKmsKeyName = Nothing, _sSecretEnv = Nothing} -- | Cloud KMS key name to use to decrypt these envs. sKmsKeyName :: Lens' Secret (Maybe Text) sKmsKeyName = lens _sKmsKeyName (\ s a -> s{_sKmsKeyName = a}) -- | Map of environment variable name to its encrypted value. Secret -- environment variables must be unique across all of a build\'s secrets, -- and must be used by at least one build step. Values can be at most 64 KB -- in size. There can be at most 100 secret values across all of a build\'s -- secrets. sSecretEnv :: Lens' Secret (Maybe SecretSecretEnv) sSecretEnv = lens _sSecretEnv (\ s a -> s{_sSecretEnv = a}) instance FromJSON Secret where parseJSON = withObject "Secret" (\ o -> Secret' <$> (o .:? "kmsKeyName") <*> (o .:? "secretEnv")) instance ToJSON Secret where toJSON Secret'{..} = object (catMaybes [("kmsKeyName" .=) <$> _sKmsKeyName, ("secretEnv" .=) <$> _sSecretEnv]) -- | Represents the metadata of the long-running operation. -- -- /See:/ 'googleDevtoolsCloudbuildV2OperationMetadata' smart constructor. data GoogleDevtoolsCloudbuildV2OperationMetadata = GoogleDevtoolsCloudbuildV2OperationMetadata' { _gdcvomAPIVersion :: !(Maybe Text) , _gdcvomRequestedCancellation :: !(Maybe Bool) , _gdcvomStatusMessage :: !(Maybe Text) , _gdcvomEndTime :: !(Maybe DateTime') , _gdcvomVerb :: !(Maybe Text) , _gdcvomTarget :: !(Maybe Text) , _gdcvomCreateTime :: !(Maybe DateTime') } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleDevtoolsCloudbuildV2OperationMetadata' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gdcvomAPIVersion' -- -- * 'gdcvomRequestedCancellation' -- -- * 'gdcvomStatusMessage' -- -- * 'gdcvomEndTime' -- -- * 'gdcvomVerb' -- -- * 'gdcvomTarget' -- -- * 'gdcvomCreateTime' googleDevtoolsCloudbuildV2OperationMetadata :: GoogleDevtoolsCloudbuildV2OperationMetadata googleDevtoolsCloudbuildV2OperationMetadata = GoogleDevtoolsCloudbuildV2OperationMetadata' { _gdcvomAPIVersion = Nothing , _gdcvomRequestedCancellation = Nothing , _gdcvomStatusMessage = Nothing , _gdcvomEndTime = Nothing , _gdcvomVerb = Nothing , _gdcvomTarget = Nothing , _gdcvomCreateTime = Nothing } -- | Output only. API version used to start the operation. gdcvomAPIVersion :: Lens' GoogleDevtoolsCloudbuildV2OperationMetadata (Maybe Text) gdcvomAPIVersion = lens _gdcvomAPIVersion (\ s a -> s{_gdcvomAPIVersion = a}) -- | Output only. Identifies whether the user has requested cancellation of -- the operation. Operations that have successfully been cancelled have -- Operation.error value with a google.rpc.Status.code of 1, corresponding -- to \`Code.CANCELLED\`. gdcvomRequestedCancellation :: Lens' GoogleDevtoolsCloudbuildV2OperationMetadata (Maybe Bool) gdcvomRequestedCancellation = lens _gdcvomRequestedCancellation (\ s a -> s{_gdcvomRequestedCancellation = a}) -- | Output only. Human-readable status of the operation, if any. gdcvomStatusMessage :: Lens' GoogleDevtoolsCloudbuildV2OperationMetadata (Maybe Text) gdcvomStatusMessage = lens _gdcvomStatusMessage (\ s a -> s{_gdcvomStatusMessage = a}) -- | Output only. The time the operation finished running. gdcvomEndTime :: Lens' GoogleDevtoolsCloudbuildV2OperationMetadata (Maybe UTCTime) gdcvomEndTime = lens _gdcvomEndTime (\ s a -> s{_gdcvomEndTime = a}) . mapping _DateTime -- | Output only. Name of the verb executed by the operation. gdcvomVerb :: Lens' GoogleDevtoolsCloudbuildV2OperationMetadata (Maybe Text) gdcvomVerb = lens _gdcvomVerb (\ s a -> s{_gdcvomVerb = a}) -- | Output only. Server-defined resource path for the target of the -- operation. gdcvomTarget :: Lens' GoogleDevtoolsCloudbuildV2OperationMetadata (Maybe Text) gdcvomTarget = lens _gdcvomTarget (\ s a -> s{_gdcvomTarget = a}) -- | Output only. The time the operation was created. gdcvomCreateTime :: Lens' GoogleDevtoolsCloudbuildV2OperationMetadata (Maybe UTCTime) gdcvomCreateTime = lens _gdcvomCreateTime (\ s a -> s{_gdcvomCreateTime = a}) . mapping _DateTime instance FromJSON GoogleDevtoolsCloudbuildV2OperationMetadata where parseJSON = withObject "GoogleDevtoolsCloudbuildV2OperationMetadata" (\ o -> GoogleDevtoolsCloudbuildV2OperationMetadata' <$> (o .:? "apiVersion") <*> (o .:? "requestedCancellation") <*> (o .:? "statusMessage") <*> (o .:? "endTime") <*> (o .:? "verb") <*> (o .:? "target") <*> (o .:? "createTime")) instance ToJSON GoogleDevtoolsCloudbuildV2OperationMetadata where toJSON GoogleDevtoolsCloudbuildV2OperationMetadata'{..} = object (catMaybes [("apiVersion" .=) <$> _gdcvomAPIVersion, ("requestedCancellation" .=) <$> _gdcvomRequestedCancellation, ("statusMessage" .=) <$> _gdcvomStatusMessage, ("endTime" .=) <$> _gdcvomEndTime, ("verb" .=) <$> _gdcvomVerb, ("target" .=) <$> _gdcvomTarget, ("createTime" .=) <$> _gdcvomCreateTime]) -- | Push contains filter properties for matching GitHub git pushes. -- -- /See:/ 'pushFilter' smart constructor. data PushFilter = PushFilter' { _pfInvertRegex :: !(Maybe Bool) , _pfTag :: !(Maybe Text) , _pfBranch :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'PushFilter' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pfInvertRegex' -- -- * 'pfTag' -- -- * 'pfBranch' pushFilter :: PushFilter pushFilter = PushFilter' {_pfInvertRegex = Nothing, _pfTag = Nothing, _pfBranch = Nothing} -- | When true, only trigger a build if the revision regex does NOT match the -- git_ref regex. pfInvertRegex :: Lens' PushFilter (Maybe Bool) pfInvertRegex = lens _pfInvertRegex (\ s a -> s{_pfInvertRegex = a}) -- | Regexes matching tags to build. The syntax of the regular expressions -- accepted is the syntax accepted by RE2 and described at -- https:\/\/github.com\/google\/re2\/wiki\/Syntax pfTag :: Lens' PushFilter (Maybe Text) pfTag = lens _pfTag (\ s a -> s{_pfTag = a}) -- | Regexes matching branches to build. The syntax of the regular -- expressions accepted is the syntax accepted by RE2 and described at -- https:\/\/github.com\/google\/re2\/wiki\/Syntax pfBranch :: Lens' PushFilter (Maybe Text) pfBranch = lens _pfBranch (\ s a -> s{_pfBranch = a}) instance FromJSON PushFilter where parseJSON = withObject "PushFilter" (\ o -> PushFilter' <$> (o .:? "invertRegex") <*> (o .:? "tag") <*> (o .:? "branch")) instance ToJSON PushFilter where toJSON PushFilter'{..} = object (catMaybes [("invertRegex" .=) <$> _pfInvertRegex, ("tag" .=) <$> _pfTag, ("branch" .=) <$> _pfBranch]) -- | Request to cancel an ongoing build. -- -- /See:/ 'cancelBuildRequest' smart constructor. data CancelBuildRequest = CancelBuildRequest' { _cbrName :: !(Maybe Text) , _cbrId :: !(Maybe Text) , _cbrProjectId :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'CancelBuildRequest' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'cbrName' -- -- * 'cbrId' -- -- * 'cbrProjectId' cancelBuildRequest :: CancelBuildRequest cancelBuildRequest = CancelBuildRequest' {_cbrName = Nothing, _cbrId = Nothing, _cbrProjectId = Nothing} -- | The name of the \`Build\` to cancel. Format: -- \`projects\/{project}\/locations\/{location}\/builds\/{build}\` cbrName :: Lens' CancelBuildRequest (Maybe Text) cbrName = lens _cbrName (\ s a -> s{_cbrName = a}) -- | Required. ID of the build. cbrId :: Lens' CancelBuildRequest (Maybe Text) cbrId = lens _cbrId (\ s a -> s{_cbrId = a}) -- | Required. ID of the project. cbrProjectId :: Lens' CancelBuildRequest (Maybe Text) cbrProjectId = lens _cbrProjectId (\ s a -> s{_cbrProjectId = a}) instance FromJSON CancelBuildRequest where parseJSON = withObject "CancelBuildRequest" (\ o -> CancelBuildRequest' <$> (o .:? "name") <*> (o .:? "id") <*> (o .:? "projectId")) instance ToJSON CancelBuildRequest where toJSON CancelBuildRequest'{..} = object (catMaybes [("name" .=) <$> _cbrName, ("id" .=) <$> _cbrId, ("projectId" .=) <$> _cbrProjectId]) -- | PubsubConfig describes the configuration of a trigger that creates a -- build whenever a Pub\/Sub message is published. -- -- /See:/ 'pubsubConfig' smart constructor. data PubsubConfig = PubsubConfig' { _pcState :: !(Maybe PubsubConfigState) , _pcTopic :: !(Maybe Text) , _pcServiceAccountEmail :: !(Maybe Text) , _pcSubscription :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'PubsubConfig' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pcState' -- -- * 'pcTopic' -- -- * 'pcServiceAccountEmail' -- -- * 'pcSubscription' pubsubConfig :: PubsubConfig pubsubConfig = PubsubConfig' { _pcState = Nothing , _pcTopic = Nothing , _pcServiceAccountEmail = Nothing , _pcSubscription = Nothing } -- | Potential issues with the underlying Pub\/Sub subscription -- configuration. Only populated on get requests. pcState :: Lens' PubsubConfig (Maybe PubsubConfigState) pcState = lens _pcState (\ s a -> s{_pcState = a}) -- | The name of the topic from which this subscription is receiving -- messages. Format is \`projects\/{project}\/topics\/{topic}\`. pcTopic :: Lens' PubsubConfig (Maybe Text) pcTopic = lens _pcTopic (\ s a -> s{_pcTopic = a}) -- | Service account that will make the push request. pcServiceAccountEmail :: Lens' PubsubConfig (Maybe Text) pcServiceAccountEmail = lens _pcServiceAccountEmail (\ s a -> s{_pcServiceAccountEmail = a}) -- | Output only. Name of the subscription. Format is -- \`projects\/{project}\/subscriptions\/{subscription}\`. pcSubscription :: Lens' PubsubConfig (Maybe Text) pcSubscription = lens _pcSubscription (\ s a -> s{_pcSubscription = a}) instance FromJSON PubsubConfig where parseJSON = withObject "PubsubConfig" (\ o -> PubsubConfig' <$> (o .:? "state") <*> (o .:? "topic") <*> (o .:? "serviceAccountEmail") <*> (o .:? "subscription")) instance ToJSON PubsubConfig where toJSON PubsubConfig'{..} = object (catMaybes [("state" .=) <$> _pcState, ("topic" .=) <$> _pcTopic, ("serviceAccountEmail" .=) <$> _pcServiceAccountEmail, ("subscription" .=) <$> _pcSubscription]) -- | Start and end times for a build execution phase. -- -- /See:/ 'timeSpan' smart constructor. data TimeSpan = TimeSpan' { _tsStartTime :: !(Maybe DateTime') , _tsEndTime :: !(Maybe DateTime') } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'TimeSpan' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'tsStartTime' -- -- * 'tsEndTime' timeSpan :: TimeSpan timeSpan = TimeSpan' {_tsStartTime = Nothing, _tsEndTime = Nothing} -- | Start of time span. tsStartTime :: Lens' TimeSpan (Maybe UTCTime) tsStartTime = lens _tsStartTime (\ s a -> s{_tsStartTime = a}) . mapping _DateTime -- | End of time span. tsEndTime :: Lens' TimeSpan (Maybe UTCTime) tsEndTime = lens _tsEndTime (\ s a -> s{_tsEndTime = a}) . mapping _DateTime instance FromJSON TimeSpan where parseJSON = withObject "TimeSpan" (\ o -> TimeSpan' <$> (o .:? "startTime") <*> (o .:? "endTime")) instance ToJSON TimeSpan where toJSON TimeSpan'{..} = object (catMaybes [("startTime" .=) <$> _tsStartTime, ("endTime" .=) <$> _tsEndTime]) -- | Defines the network configuration for the pool. -- -- /See:/ 'networkConfig' smart constructor. data NetworkConfig = NetworkConfig' { _ncPeeredNetwork :: !(Maybe Text) , _ncEgressOption :: !(Maybe NetworkConfigEgressOption) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'NetworkConfig' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ncPeeredNetwork' -- -- * 'ncEgressOption' networkConfig :: NetworkConfig networkConfig = NetworkConfig' {_ncPeeredNetwork = Nothing, _ncEgressOption = Nothing} -- | Required. Immutable. The network definition that the workers are peered -- to. If this section is left empty, the workers will be peered to -- \`WorkerPool.project_id\` on the service producer network. Must be in -- the format \`projects\/{project}\/global\/networks\/{network}\`, where -- \`{project}\` is a project number, such as \`12345\`, and \`{network}\` -- is the name of a VPC network in the project. See [Understanding network -- configuration -- options](https:\/\/cloud.google.com\/build\/docs\/private-pools\/set-up-private-pool-environment) ncPeeredNetwork :: Lens' NetworkConfig (Maybe Text) ncPeeredNetwork = lens _ncPeeredNetwork (\ s a -> s{_ncPeeredNetwork = a}) -- | Option to configure network egress for the workers. ncEgressOption :: Lens' NetworkConfig (Maybe NetworkConfigEgressOption) ncEgressOption = lens _ncEgressOption (\ s a -> s{_ncEgressOption = a}) instance FromJSON NetworkConfig where parseJSON = withObject "NetworkConfig" (\ o -> NetworkConfig' <$> (o .:? "peeredNetwork") <*> (o .:? "egressOption")) instance ToJSON NetworkConfig where toJSON NetworkConfig'{..} = object (catMaybes [("peeredNetwork" .=) <$> _ncPeeredNetwork, ("egressOption" .=) <$> _ncEgressOption]) -- | Location of the source in an archive file in Google Cloud Storage. -- -- /See:/ 'storageSource' smart constructor. data StorageSource = StorageSource' { _ssBucket :: !(Maybe Text) , _ssObject :: !(Maybe Text) , _ssGeneration :: !(Maybe (Textual Int64)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'StorageSource' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ssBucket' -- -- * 'ssObject' -- -- * 'ssGeneration' storageSource :: StorageSource storageSource = StorageSource' {_ssBucket = Nothing, _ssObject = Nothing, _ssGeneration = Nothing} -- | Google Cloud Storage bucket containing the source (see [Bucket Name -- Requirements](https:\/\/cloud.google.com\/storage\/docs\/bucket-naming#requirements)). ssBucket :: Lens' StorageSource (Maybe Text) ssBucket = lens _ssBucket (\ s a -> s{_ssBucket = a}) -- | Google Cloud Storage object containing the source. This object must be a -- zipped (\`.zip\`) or gzipped archive file (\`.tar.gz\`) containing -- source to build. ssObject :: Lens' StorageSource (Maybe Text) ssObject = lens _ssObject (\ s a -> s{_ssObject = a}) -- | Google Cloud Storage generation for the object. If the generation is -- omitted, the latest generation will be used. ssGeneration :: Lens' StorageSource (Maybe Int64) ssGeneration = lens _ssGeneration (\ s a -> s{_ssGeneration = a}) . mapping _Coerce instance FromJSON StorageSource where parseJSON = withObject "StorageSource" (\ o -> StorageSource' <$> (o .:? "bucket") <*> (o .:? "object") <*> (o .:? "generation")) instance ToJSON StorageSource where toJSON StorageSource'{..} = object (catMaybes [("bucket" .=) <$> _ssBucket, ("object" .=) <$> _ssObject, ("generation" .=) <$> _ssGeneration]) -- | Configuration for a V1 \`PrivatePool\`. -- -- /See:/ 'privatePoolV1Config' smart constructor. data PrivatePoolV1Config = PrivatePoolV1Config' { _ppvcWorkerConfig :: !(Maybe WorkerConfig) , _ppvcNetworkConfig :: !(Maybe NetworkConfig) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'PrivatePoolV1Config' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ppvcWorkerConfig' -- -- * 'ppvcNetworkConfig' privatePoolV1Config :: PrivatePoolV1Config privatePoolV1Config = PrivatePoolV1Config' {_ppvcWorkerConfig = Nothing, _ppvcNetworkConfig = Nothing} -- | Machine configuration for the workers in the pool. ppvcWorkerConfig :: Lens' PrivatePoolV1Config (Maybe WorkerConfig) ppvcWorkerConfig = lens _ppvcWorkerConfig (\ s a -> s{_ppvcWorkerConfig = a}) -- | Network configuration for the pool. ppvcNetworkConfig :: Lens' PrivatePoolV1Config (Maybe NetworkConfig) ppvcNetworkConfig = lens _ppvcNetworkConfig (\ s a -> s{_ppvcNetworkConfig = a}) instance FromJSON PrivatePoolV1Config where parseJSON = withObject "PrivatePoolV1Config" (\ o -> PrivatePoolV1Config' <$> (o .:? "workerConfig") <*> (o .:? "networkConfig")) instance ToJSON PrivatePoolV1Config where toJSON PrivatePoolV1Config'{..} = object (catMaybes [("workerConfig" .=) <$> _ppvcWorkerConfig, ("networkConfig" .=) <$> _ppvcNetworkConfig]) -- | HTTPDelivery is the delivery configuration for an HTTP notification. -- -- /See:/ 'hTTPDelivery' smart constructor. newtype HTTPDelivery = HTTPDelivery' { _httpdURI :: Maybe Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'HTTPDelivery' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'httpdURI' hTTPDelivery :: HTTPDelivery hTTPDelivery = HTTPDelivery' {_httpdURI = Nothing} -- | The URI to which JSON-containing HTTP POST requests should be sent. httpdURI :: Lens' HTTPDelivery (Maybe Text) httpdURI = lens _httpdURI (\ s a -> s{_httpdURI = a}) instance FromJSON HTTPDelivery where parseJSON = withObject "HTTPDelivery" (\ o -> HTTPDelivery' <$> (o .:? "uri")) instance ToJSON HTTPDelivery where toJSON HTTPDelivery'{..} = object (catMaybes [("uri" .=) <$> _httpdURI]) -- | Response containing existing \`BuildTriggers\`. -- -- /See:/ 'listBuildTriggersResponse' smart constructor. data ListBuildTriggersResponse = ListBuildTriggersResponse' { _lbtrNextPageToken :: !(Maybe Text) , _lbtrTriggers :: !(Maybe [BuildTrigger]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ListBuildTriggersResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lbtrNextPageToken' -- -- * 'lbtrTriggers' listBuildTriggersResponse :: ListBuildTriggersResponse listBuildTriggersResponse = ListBuildTriggersResponse' {_lbtrNextPageToken = Nothing, _lbtrTriggers = Nothing} -- | Token to receive the next page of results. lbtrNextPageToken :: Lens' ListBuildTriggersResponse (Maybe Text) lbtrNextPageToken = lens _lbtrNextPageToken (\ s a -> s{_lbtrNextPageToken = a}) -- | \`BuildTriggers\` for the project, sorted by \`create_time\` descending. lbtrTriggers :: Lens' ListBuildTriggersResponse [BuildTrigger] lbtrTriggers = lens _lbtrTriggers (\ s a -> s{_lbtrTriggers = a}) . _Default . _Coerce instance FromJSON ListBuildTriggersResponse where parseJSON = withObject "ListBuildTriggersResponse" (\ o -> ListBuildTriggersResponse' <$> (o .:? "nextPageToken") <*> (o .:? "triggers" .!= mempty)) instance ToJSON ListBuildTriggersResponse where toJSON ListBuildTriggersResponse'{..} = object (catMaybes [("nextPageToken" .=) <$> _lbtrNextPageToken, ("triggers" .=) <$> _lbtrTriggers]) -- | Pairs a set of secret environment variables mapped to encrypted values -- with the Cloud KMS key to use to decrypt the value. -- -- /See:/ 'inlineSecret' smart constructor. data InlineSecret = InlineSecret' { _isEnvMap :: !(Maybe InlineSecretEnvMap) , _isKmsKeyName :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'InlineSecret' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'isEnvMap' -- -- * 'isKmsKeyName' inlineSecret :: InlineSecret inlineSecret = InlineSecret' {_isEnvMap = Nothing, _isKmsKeyName = Nothing} -- | Map of environment variable name to its encrypted value. Secret -- environment variables must be unique across all of a build\'s secrets, -- and must be used by at least one build step. Values can be at most 64 KB -- in size. There can be at most 100 secret values across all of a build\'s -- secrets. isEnvMap :: Lens' InlineSecret (Maybe InlineSecretEnvMap) isEnvMap = lens _isEnvMap (\ s a -> s{_isEnvMap = a}) -- | Resource name of Cloud KMS crypto key to decrypt the encrypted value. In -- format: projects\/*\/locations\/*\/keyRings\/*\/cryptoKeys\/* isKmsKeyName :: Lens' InlineSecret (Maybe Text) isKmsKeyName = lens _isKmsKeyName (\ s a -> s{_isKmsKeyName = a}) instance FromJSON InlineSecret where parseJSON = withObject "InlineSecret" (\ o -> InlineSecret' <$> (o .:? "envMap") <*> (o .:? "kmsKeyName")) instance ToJSON InlineSecret where toJSON InlineSecret'{..} = object (catMaybes [("envMap" .=) <$> _isEnvMap, ("kmsKeyName" .=) <$> _isKmsKeyName]) -- | An artifact that was uploaded during a build. This is a single record in -- the artifact manifest JSON file. -- -- /See:/ 'artifactResult' smart constructor. data ArtifactResult = ArtifactResult' { _arFileHash :: !(Maybe [FileHashes]) , _arLocation :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ArtifactResult' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'arFileHash' -- -- * 'arLocation' artifactResult :: ArtifactResult artifactResult = ArtifactResult' {_arFileHash = Nothing, _arLocation = Nothing} -- | The file hash of the artifact. arFileHash :: Lens' ArtifactResult [FileHashes] arFileHash = lens _arFileHash (\ s a -> s{_arFileHash = a}) . _Default . _Coerce -- | The path of an artifact in a Google Cloud Storage bucket, with the -- generation number. For example, -- \`gs:\/\/mybucket\/path\/to\/output.jar#generation\`. arLocation :: Lens' ArtifactResult (Maybe Text) arLocation = lens _arLocation (\ s a -> s{_arLocation = a}) instance FromJSON ArtifactResult where parseJSON = withObject "ArtifactResult" (\ o -> ArtifactResult' <$> (o .:? "fileHash" .!= mempty) <*> (o .:? "location")) instance ToJSON ArtifactResult where toJSON ArtifactResult'{..} = object (catMaybes [("fileHash" .=) <$> _arFileHash, ("location" .=) <$> _arLocation]) -- | GitRepoSource describes a repo and ref of a code repository. -- -- /See:/ 'gitRepoSource' smart constructor. data GitRepoSource = GitRepoSource' { _grsRepoType :: !(Maybe GitRepoSourceRepoType) , _grsURI :: !(Maybe Text) , _grsRef :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GitRepoSource' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'grsRepoType' -- -- * 'grsURI' -- -- * 'grsRef' gitRepoSource :: GitRepoSource gitRepoSource = GitRepoSource' {_grsRepoType = Nothing, _grsURI = Nothing, _grsRef = Nothing} -- | See RepoType below. grsRepoType :: Lens' GitRepoSource (Maybe GitRepoSourceRepoType) grsRepoType = lens _grsRepoType (\ s a -> s{_grsRepoType = a}) -- | The URI of the repo (required). grsURI :: Lens' GitRepoSource (Maybe Text) grsURI = lens _grsURI (\ s a -> s{_grsURI = a}) -- | The branch or tag to use. Must start with \"refs\/\" (required). grsRef :: Lens' GitRepoSource (Maybe Text) grsRef = lens _grsRef (\ s a -> s{_grsRef = a}) instance FromJSON GitRepoSource where parseJSON = withObject "GitRepoSource" (\ o -> GitRepoSource' <$> (o .:? "repoType") <*> (o .:? "uri") <*> (o .:? "ref")) instance ToJSON GitRepoSource where toJSON GitRepoSource'{..} = object (catMaybes [("repoType" .=) <$> _grsRepoType, ("uri" .=) <$> _grsURI, ("ref" .=) <$> _grsRef]) -- | Container message for hashes of byte content of files, used in -- SourceProvenance messages to verify integrity of source input to the -- build. -- -- /See:/ 'fileHashes' smart constructor. newtype FileHashes = FileHashes' { _fhFileHash :: Maybe [Hash] } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'FileHashes' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'fhFileHash' fileHashes :: FileHashes fileHashes = FileHashes' {_fhFileHash = Nothing} -- | Collection of file hashes. fhFileHash :: Lens' FileHashes [Hash] fhFileHash = lens _fhFileHash (\ s a -> s{_fhFileHash = a}) . _Default . _Coerce instance FromJSON FileHashes where parseJSON = withObject "FileHashes" (\ o -> FileHashes' <$> (o .:? "fileHash" .!= mempty)) instance ToJSON FileHashes where toJSON FileHashes'{..} = object (catMaybes [("fileHash" .=) <$> _fhFileHash]) -- | A non-fatal problem encountered during the execution of the build. -- -- /See:/ 'warning' smart constructor. data Warning = Warning' { _wPriority :: !(Maybe WarningPriority) , _wText :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Warning' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'wPriority' -- -- * 'wText' warning :: Warning warning = Warning' {_wPriority = Nothing, _wText = Nothing} -- | The priority for this warning. wPriority :: Lens' Warning (Maybe WarningPriority) wPriority = lens _wPriority (\ s a -> s{_wPriority = a}) -- | Explanation of the warning generated. wText :: Lens' Warning (Maybe Text) wText = lens _wText (\ s a -> s{_wText = a}) instance FromJSON Warning where parseJSON = withObject "Warning" (\ o -> Warning' <$> (o .:? "priority") <*> (o .:? "text")) instance ToJSON Warning where toJSON Warning'{..} = object (catMaybes [("priority" .=) <$> _wPriority, ("text" .=) <$> _wText]) -- | Configuration for a \`WorkerPool\`. Cloud Build owns and maintains a -- pool of workers for general use and have no access to a project\'s -- private network. By default, builds submitted to Cloud Build will use a -- worker from this pool. If your build needs access to resources on a -- private network, create and use a \`WorkerPool\` to run your builds. -- Private \`WorkerPool\`s give your builds access to any single VPC -- network that you administer, including any on-prem resources connected -- to that VPC network. For an overview of private pools, see [Private -- pools -- overview](https:\/\/cloud.google.com\/build\/docs\/private-pools\/private-pools-overview). -- -- /See:/ 'workerPool' smart constructor. data WorkerPool = WorkerPool' { _wpAnnotations :: !(Maybe WorkerPoolAnnotations) , _wpEtag :: !(Maybe Text) , _wpState :: !(Maybe WorkerPoolState) , _wpUid :: !(Maybe Text) , _wpUpdateTime :: !(Maybe DateTime') , _wpDeleteTime :: !(Maybe DateTime') , _wpPrivatePoolV1Config :: !(Maybe PrivatePoolV1Config) , _wpName :: !(Maybe Text) , _wpDisplayName :: !(Maybe Text) , _wpCreateTime :: !(Maybe DateTime') } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'WorkerPool' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'wpAnnotations' -- -- * 'wpEtag' -- -- * 'wpState' -- -- * 'wpUid' -- -- * 'wpUpdateTime' -- -- * 'wpDeleteTime' -- -- * 'wpPrivatePoolV1Config' -- -- * 'wpName' -- -- * 'wpDisplayName' -- -- * 'wpCreateTime' workerPool :: WorkerPool workerPool = WorkerPool' { _wpAnnotations = Nothing , _wpEtag = Nothing , _wpState = Nothing , _wpUid = Nothing , _wpUpdateTime = Nothing , _wpDeleteTime = Nothing , _wpPrivatePoolV1Config = Nothing , _wpName = Nothing , _wpDisplayName = Nothing , _wpCreateTime = Nothing } -- | User specified annotations. See -- https:\/\/google.aip.dev\/128#annotations for more details such as -- format and size limitations. wpAnnotations :: Lens' WorkerPool (Maybe WorkerPoolAnnotations) wpAnnotations = lens _wpAnnotations (\ s a -> s{_wpAnnotations = a}) -- | Output only. Checksum computed by the server. May be sent on update and -- delete requests to ensure that the client has an up-to-date value before -- proceeding. wpEtag :: Lens' WorkerPool (Maybe Text) wpEtag = lens _wpEtag (\ s a -> s{_wpEtag = a}) -- | Output only. \`WorkerPool\` state. wpState :: Lens' WorkerPool (Maybe WorkerPoolState) wpState = lens _wpState (\ s a -> s{_wpState = a}) -- | Output only. A unique identifier for the \`WorkerPool\`. wpUid :: Lens' WorkerPool (Maybe Text) wpUid = lens _wpUid (\ s a -> s{_wpUid = a}) -- | Output only. Time at which the request to update the \`WorkerPool\` was -- received. wpUpdateTime :: Lens' WorkerPool (Maybe UTCTime) wpUpdateTime = lens _wpUpdateTime (\ s a -> s{_wpUpdateTime = a}) . mapping _DateTime -- | Output only. Time at which the request to delete the \`WorkerPool\` was -- received. wpDeleteTime :: Lens' WorkerPool (Maybe UTCTime) wpDeleteTime = lens _wpDeleteTime (\ s a -> s{_wpDeleteTime = a}) . mapping _DateTime -- | Private Pool using a v1 configuration. wpPrivatePoolV1Config :: Lens' WorkerPool (Maybe PrivatePoolV1Config) wpPrivatePoolV1Config = lens _wpPrivatePoolV1Config (\ s a -> s{_wpPrivatePoolV1Config = a}) -- | Output only. The resource name of the \`WorkerPool\`, with format -- \`projects\/{project}\/locations\/{location}\/workerPools\/{worker_pool}\`. -- The value of \`{worker_pool}\` is provided by \`worker_pool_id\` in -- \`CreateWorkerPool\` request and the value of \`{location}\` is -- determined by the endpoint accessed. wpName :: Lens' WorkerPool (Maybe Text) wpName = lens _wpName (\ s a -> s{_wpName = a}) -- | A user-specified, human-readable name for the \`WorkerPool\`. If -- provided, this value must be 1-63 characters. wpDisplayName :: Lens' WorkerPool (Maybe Text) wpDisplayName = lens _wpDisplayName (\ s a -> s{_wpDisplayName = a}) -- | Output only. Time at which the request to create the \`WorkerPool\` was -- received. wpCreateTime :: Lens' WorkerPool (Maybe UTCTime) wpCreateTime = lens _wpCreateTime (\ s a -> s{_wpCreateTime = a}) . mapping _DateTime instance FromJSON WorkerPool where parseJSON = withObject "WorkerPool" (\ o -> WorkerPool' <$> (o .:? "annotations") <*> (o .:? "etag") <*> (o .:? "state") <*> (o .:? "uid") <*> (o .:? "updateTime") <*> (o .:? "deleteTime") <*> (o .:? "privatePoolV1Config") <*> (o .:? "name") <*> (o .:? "displayName") <*> (o .:? "createTime")) instance ToJSON WorkerPool where toJSON WorkerPool'{..} = object (catMaybes [("annotations" .=) <$> _wpAnnotations, ("etag" .=) <$> _wpEtag, ("state" .=) <$> _wpState, ("uid" .=) <$> _wpUid, ("updateTime" .=) <$> _wpUpdateTime, ("deleteTime" .=) <$> _wpDeleteTime, ("privatePoolV1Config" .=) <$> _wpPrivatePoolV1Config, ("name" .=) <$> _wpName, ("displayName" .=) <$> _wpDisplayName, ("createTime" .=) <$> _wpCreateTime]) -- | Substitutions data for \`Build\` resource. -- -- /See:/ 'buildSubstitutions' smart constructor. newtype BuildSubstitutions = BuildSubstitutions' { _bsAddtional :: HashMap Text Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'BuildSubstitutions' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'bsAddtional' buildSubstitutions :: HashMap Text Text -- ^ 'bsAddtional' -> BuildSubstitutions buildSubstitutions pBsAddtional_ = BuildSubstitutions' {_bsAddtional = _Coerce # pBsAddtional_} bsAddtional :: Lens' BuildSubstitutions (HashMap Text Text) bsAddtional = lens _bsAddtional (\ s a -> s{_bsAddtional = a}) . _Coerce instance FromJSON BuildSubstitutions where parseJSON = withObject "BuildSubstitutions" (\ o -> BuildSubstitutions' <$> (parseJSONObject o)) instance ToJSON BuildSubstitutions where toJSON = toJSON . _bsAddtional -- | SlackDelivery is the delivery configuration for delivering Slack -- messages via webhooks. See Slack webhook documentation at: -- https:\/\/api.slack.com\/messaging\/webhooks. -- -- /See:/ 'slackDelivery' smart constructor. newtype SlackDelivery = SlackDelivery' { _sdWebhookURI :: Maybe NotifierSecretRef } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'SlackDelivery' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'sdWebhookURI' slackDelivery :: SlackDelivery slackDelivery = SlackDelivery' {_sdWebhookURI = Nothing} -- | The secret reference for the Slack webhook URI for sending messages to a -- channel. sdWebhookURI :: Lens' SlackDelivery (Maybe NotifierSecretRef) sdWebhookURI = lens _sdWebhookURI (\ s a -> s{_sdWebhookURI = a}) instance FromJSON SlackDelivery where parseJSON = withObject "SlackDelivery" (\ o -> SlackDelivery' <$> (o .:? "webhookUri")) instance ToJSON SlackDelivery where toJSON SlackDelivery'{..} = object (catMaybes [("webhookUri" .=) <$> _sdWebhookURI]) -- | NotifierSecret is the container that maps a secret name (reference) to -- its Google Cloud Secret Manager resource path. -- -- /See:/ 'notifierSecret' smart constructor. data NotifierSecret = NotifierSecret' { _nsValue :: !(Maybe Text) , _nsName :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'NotifierSecret' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'nsValue' -- -- * 'nsName' notifierSecret :: NotifierSecret notifierSecret = NotifierSecret' {_nsValue = Nothing, _nsName = Nothing} -- | Value is interpreted to be a resource path for fetching the actual -- (versioned) secret data for this secret. For example, this would be a -- Google Cloud Secret Manager secret version resource path like: -- \"projects\/my-project\/secrets\/my-secret\/versions\/latest\". nsValue :: Lens' NotifierSecret (Maybe Text) nsValue = lens _nsValue (\ s a -> s{_nsValue = a}) -- | Name is the local name of the secret, such as the verbatim string -- \"my-smtp-password\". nsName :: Lens' NotifierSecret (Maybe Text) nsName = lens _nsName (\ s a -> s{_nsName = a}) instance FromJSON NotifierSecret where parseJSON = withObject "NotifierSecret" (\ o -> NotifierSecret' <$> (o .:? "value") <*> (o .:? "name")) instance ToJSON NotifierSecret where toJSON NotifierSecret'{..} = object (catMaybes [("value" .=) <$> _nsValue, ("name" .=) <$> _nsName]) -- | Location of the source in a supported storage service. -- -- /See:/ 'source' smart constructor. data Source = Source' { _sRepoSource :: !(Maybe RepoSource) , _sStorageSourceManifest :: !(Maybe StorageSourceManifest) , _sStorageSource :: !(Maybe StorageSource) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Source' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'sRepoSource' -- -- * 'sStorageSourceManifest' -- -- * 'sStorageSource' source :: Source source = Source' { _sRepoSource = Nothing , _sStorageSourceManifest = Nothing , _sStorageSource = Nothing } -- | If provided, get the source from this location in a Cloud Source -- Repository. sRepoSource :: Lens' Source (Maybe RepoSource) sRepoSource = lens _sRepoSource (\ s a -> s{_sRepoSource = a}) -- | If provided, get the source from this manifest in Google Cloud Storage. -- This feature is in Preview; see description -- [here](https:\/\/github.com\/GoogleCloudPlatform\/cloud-builders\/tree\/master\/gcs-fetcher). sStorageSourceManifest :: Lens' Source (Maybe StorageSourceManifest) sStorageSourceManifest = lens _sStorageSourceManifest (\ s a -> s{_sStorageSourceManifest = a}) -- | If provided, get the source from this location in Google Cloud Storage. sStorageSource :: Lens' Source (Maybe StorageSource) sStorageSource = lens _sStorageSource (\ s a -> s{_sStorageSource = a}) instance FromJSON Source where parseJSON = withObject "Source" (\ o -> Source' <$> (o .:? "repoSource") <*> (o .:? "storageSourceManifest") <*> (o .:? "storageSource")) instance ToJSON Source where toJSON Source'{..} = object (catMaybes [("repoSource" .=) <$> _sRepoSource, ("storageSourceManifest" .=) <$> _sStorageSourceManifest, ("storageSource" .=) <$> _sStorageSource]) -- | Message that represents an arbitrary HTTP body. It should only be used -- for payload formats that can\'t be represented as JSON, such as raw -- binary or an HTML page. This message can be used both in streaming and -- non-streaming API methods in the request as well as the response. It can -- be used as a top-level request field, which is convenient if one wants -- to extract parameters from either the URL or HTTP template into the -- request fields and also want access to the raw HTTP body. Example: -- message GetResourceRequest { \/\/ A unique request id. string request_id -- = 1; \/\/ The raw HTTP body is bound to this field. google.api.HttpBody -- http_body = 2; } service ResourceService { rpc -- GetResource(GetResourceRequest) returns (google.api.HttpBody); rpc -- UpdateResource(google.api.HttpBody) returns (google.protobuf.Empty); } -- Example with streaming methods: service CaldavService { rpc -- GetCalendar(stream google.api.HttpBody) returns (stream -- google.api.HttpBody); rpc UpdateCalendar(stream google.api.HttpBody) -- returns (stream google.api.HttpBody); } Use of this type only changes -- how the request and response bodies are handled, all other features will -- continue to work unchanged. -- -- /See:/ 'hTTPBody' smart constructor. data HTTPBody = HTTPBody' { _httpbExtensions :: !(Maybe [HTTPBodyExtensionsItem]) , _httpbData :: !(Maybe Bytes) , _httpbContentType :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'HTTPBody' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'httpbExtensions' -- -- * 'httpbData' -- -- * 'httpbContentType' hTTPBody :: HTTPBody hTTPBody = HTTPBody' { _httpbExtensions = Nothing , _httpbData = Nothing , _httpbContentType = Nothing } -- | Application specific response metadata. Must be set in the first -- response for streaming APIs. httpbExtensions :: Lens' HTTPBody [HTTPBodyExtensionsItem] httpbExtensions = lens _httpbExtensions (\ s a -> s{_httpbExtensions = a}) . _Default . _Coerce -- | The HTTP request\/response body as raw binary. httpbData :: Lens' HTTPBody (Maybe ByteString) httpbData = lens _httpbData (\ s a -> s{_httpbData = a}) . mapping _Bytes -- | The HTTP Content-Type header value specifying the content type of the -- body. httpbContentType :: Lens' HTTPBody (Maybe Text) httpbContentType = lens _httpbContentType (\ s a -> s{_httpbContentType = a}) instance FromJSON HTTPBody where parseJSON = withObject "HTTPBody" (\ o -> HTTPBody' <$> (o .:? "extensions" .!= mempty) <*> (o .:? "data") <*> (o .:? "contentType")) instance ToJSON HTTPBody where toJSON HTTPBody'{..} = object (catMaybes [("extensions" .=) <$> _httpbExtensions, ("data" .=) <$> _httpbData, ("contentType" .=) <$> _httpbContentType]) -- | Represents the metadata of the long-running operation. -- -- /See:/ 'operationMetadata' smart constructor. data OperationMetadata = OperationMetadata' { _omAPIVersion :: !(Maybe Text) , _omEndTime :: !(Maybe DateTime') , _omStatusDetail :: !(Maybe Text) , _omVerb :: !(Maybe Text) , _omCancelRequested :: !(Maybe Bool) , _omTarget :: !(Maybe Text) , _omCreateTime :: !(Maybe DateTime') } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'OperationMetadata' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'omAPIVersion' -- -- * 'omEndTime' -- -- * 'omStatusDetail' -- -- * 'omVerb' -- -- * 'omCancelRequested' -- -- * 'omTarget' -- -- * 'omCreateTime' operationMetadata :: OperationMetadata operationMetadata = OperationMetadata' { _omAPIVersion = Nothing , _omEndTime = Nothing , _omStatusDetail = Nothing , _omVerb = Nothing , _omCancelRequested = Nothing , _omTarget = Nothing , _omCreateTime = Nothing } -- | Output only. API version used to start the operation. omAPIVersion :: Lens' OperationMetadata (Maybe Text) omAPIVersion = lens _omAPIVersion (\ s a -> s{_omAPIVersion = a}) -- | Output only. The time the operation finished running. omEndTime :: Lens' OperationMetadata (Maybe UTCTime) omEndTime = lens _omEndTime (\ s a -> s{_omEndTime = a}) . mapping _DateTime -- | Output only. Human-readable status of the operation, if any. omStatusDetail :: Lens' OperationMetadata (Maybe Text) omStatusDetail = lens _omStatusDetail (\ s a -> s{_omStatusDetail = a}) -- | Output only. Name of the verb executed by the operation. omVerb :: Lens' OperationMetadata (Maybe Text) omVerb = lens _omVerb (\ s a -> s{_omVerb = a}) -- | Output only. Identifies whether the user has requested cancellation of -- the operation. Operations that have successfully been cancelled have -- Operation.error value with a google.rpc.Status.code of 1, corresponding -- to \`Code.CANCELLED\`. omCancelRequested :: Lens' OperationMetadata (Maybe Bool) omCancelRequested = lens _omCancelRequested (\ s a -> s{_omCancelRequested = a}) -- | Output only. Server-defined resource path for the target of the -- operation. omTarget :: Lens' OperationMetadata (Maybe Text) omTarget = lens _omTarget (\ s a -> s{_omTarget = a}) -- | Output only. The time the operation was created. omCreateTime :: Lens' OperationMetadata (Maybe UTCTime) omCreateTime = lens _omCreateTime (\ s a -> s{_omCreateTime = a}) . mapping _DateTime instance FromJSON OperationMetadata where parseJSON = withObject "OperationMetadata" (\ o -> OperationMetadata' <$> (o .:? "apiVersion") <*> (o .:? "endTime") <*> (o .:? "statusDetail") <*> (o .:? "verb") <*> (o .:? "cancelRequested") <*> (o .:? "target") <*> (o .:? "createTime")) instance ToJSON OperationMetadata where toJSON OperationMetadata'{..} = object (catMaybes [("apiVersion" .=) <$> _omAPIVersion, ("endTime" .=) <$> _omEndTime, ("statusDetail" .=) <$> _omStatusDetail, ("verb" .=) <$> _omVerb, ("cancelRequested" .=) <$> _omCancelRequested, ("target" .=) <$> _omTarget, ("createTime" .=) <$> _omCreateTime]) -- | Output only. Stores timing information for phases of the build. Valid -- keys are: * BUILD: time to execute all build steps * PUSH: time to push -- all specified images. * FETCHSOURCE: time to fetch source. If the build -- does not specify source or images, these keys will not be included. -- -- /See:/ 'buildTiming' smart constructor. newtype BuildTiming = BuildTiming' { _btAddtional :: HashMap Text TimeSpan } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'BuildTiming' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'btAddtional' buildTiming :: HashMap Text TimeSpan -- ^ 'btAddtional' -> BuildTiming buildTiming pBtAddtional_ = BuildTiming' {_btAddtional = _Coerce # pBtAddtional_} btAddtional :: Lens' BuildTiming (HashMap Text TimeSpan) btAddtional = lens _btAddtional (\ s a -> s{_btAddtional = a}) . _Coerce instance FromJSON BuildTiming where parseJSON = withObject "BuildTiming" (\ o -> BuildTiming' <$> (parseJSONObject o)) instance ToJSON BuildTiming where toJSON = toJSON . _btAddtional -- | NotifierConfig is the top-level configuration message. -- -- /See:/ 'notifierConfig' smart constructor. data NotifierConfig = NotifierConfig' { _ncAPIVersion :: !(Maybe Text) , _ncKind :: !(Maybe Text) , _ncSpec :: !(Maybe NotifierSpec) , _ncMetadata :: !(Maybe NotifierMetadata) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'NotifierConfig' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ncAPIVersion' -- -- * 'ncKind' -- -- * 'ncSpec' -- -- * 'ncMetadata' notifierConfig :: NotifierConfig notifierConfig = NotifierConfig' { _ncAPIVersion = Nothing , _ncKind = Nothing , _ncSpec = Nothing , _ncMetadata = Nothing } -- | The API version of this configuration format. ncAPIVersion :: Lens' NotifierConfig (Maybe Text) ncAPIVersion = lens _ncAPIVersion (\ s a -> s{_ncAPIVersion = a}) -- | The type of notifier to use (e.g. SMTPNotifier). ncKind :: Lens' NotifierConfig (Maybe Text) ncKind = lens _ncKind (\ s a -> s{_ncKind = a}) -- | The actual configuration for this notifier. ncSpec :: Lens' NotifierConfig (Maybe NotifierSpec) ncSpec = lens _ncSpec (\ s a -> s{_ncSpec = a}) -- | Metadata for referring to\/handling\/deploying this notifier. ncMetadata :: Lens' NotifierConfig (Maybe NotifierMetadata) ncMetadata = lens _ncMetadata (\ s a -> s{_ncMetadata = a}) instance FromJSON NotifierConfig where parseJSON = withObject "NotifierConfig" (\ o -> NotifierConfig' <$> (o .:? "apiVersion") <*> (o .:? "kind") <*> (o .:? "spec") <*> (o .:? "metadata")) instance ToJSON NotifierConfig where toJSON NotifierConfig'{..} = object (catMaybes [("apiVersion" .=) <$> _ncAPIVersion, ("kind" .=) <$> _ncKind, ("spec" .=) <$> _ncSpec, ("metadata" .=) <$> _ncMetadata]) -- | Metadata for build operations. -- -- /See:/ 'buildOperationMetadata' smart constructor. newtype BuildOperationMetadata = BuildOperationMetadata' { _bomBuild :: Maybe Build } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'BuildOperationMetadata' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'bomBuild' buildOperationMetadata :: BuildOperationMetadata buildOperationMetadata = BuildOperationMetadata' {_bomBuild = Nothing} -- | The build that the operation is tracking. bomBuild :: Lens' BuildOperationMetadata (Maybe Build) bomBuild = lens _bomBuild (\ s a -> s{_bomBuild = a}) instance FromJSON BuildOperationMetadata where parseJSON = withObject "BuildOperationMetadata" (\ o -> BuildOperationMetadata' <$> (o .:? "build")) instance ToJSON BuildOperationMetadata where toJSON BuildOperationMetadata'{..} = object (catMaybes [("build" .=) <$> _bomBuild]) -- | Optional arguments to enable specific features of builds. -- -- /See:/ 'buildOptions' smart constructor. data BuildOptions = BuildOptions' { _boDiskSizeGb :: !(Maybe (Textual Int64)) , _boEnv :: !(Maybe [Text]) , _boPool :: !(Maybe PoolOption) , _boSubstitutionOption :: !(Maybe BuildOptionsSubstitutionOption) , _boRequestedVerifyOption :: !(Maybe BuildOptionsRequestedVerifyOption) , _boWorkerPool :: !(Maybe Text) , _boMachineType :: !(Maybe BuildOptionsMachineType) , _boSecretEnv :: !(Maybe [Text]) , _boVolumes :: !(Maybe [Volume]) , _boLogStreamingOption :: !(Maybe BuildOptionsLogStreamingOption) , _boLogging :: !(Maybe BuildOptionsLogging) , _boSourceProvenanceHash :: !(Maybe [BuildOptionsSourceProvenanceHashItem]) , _boDynamicSubstitutions :: !(Maybe Bool) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'BuildOptions' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'boDiskSizeGb' -- -- * 'boEnv' -- -- * 'boPool' -- -- * 'boSubstitutionOption' -- -- * 'boRequestedVerifyOption' -- -- * 'boWorkerPool' -- -- * 'boMachineType' -- -- * 'boSecretEnv' -- -- * 'boVolumes' -- -- * 'boLogStreamingOption' -- -- * 'boLogging' -- -- * 'boSourceProvenanceHash' -- -- * 'boDynamicSubstitutions' buildOptions :: BuildOptions buildOptions = BuildOptions' { _boDiskSizeGb = Nothing , _boEnv = Nothing , _boPool = Nothing , _boSubstitutionOption = Nothing , _boRequestedVerifyOption = Nothing , _boWorkerPool = Nothing , _boMachineType = Nothing , _boSecretEnv = Nothing , _boVolumes = Nothing , _boLogStreamingOption = Nothing , _boLogging = Nothing , _boSourceProvenanceHash = Nothing , _boDynamicSubstitutions = Nothing } -- | Requested disk size for the VM that runs the build. Note that this is -- *NOT* \"disk free\"; some of the space will be used by the operating -- system and build utilities. Also note that this is the minimum disk size -- that will be allocated for the build -- the build may run with a larger -- disk than requested. At present, the maximum disk size is 1000GB; builds -- that request more than the maximum are rejected with an error. boDiskSizeGb :: Lens' BuildOptions (Maybe Int64) boDiskSizeGb = lens _boDiskSizeGb (\ s a -> s{_boDiskSizeGb = a}) . mapping _Coerce -- | A list of global environment variable definitions that will exist for -- all build steps in this build. If a variable is defined in both globally -- and in a build step, the variable will use the build step value. The -- elements are of the form \"KEY=VALUE\" for the environment variable -- \"KEY\" being given the value \"VALUE\". boEnv :: Lens' BuildOptions [Text] boEnv = lens _boEnv (\ s a -> s{_boEnv = a}) . _Default . _Coerce -- | Optional. Specification for execution on a \`WorkerPool\`. See [running -- builds in a private -- pool](https:\/\/cloud.google.com\/build\/docs\/private-pools\/run-builds-in-private-pool) -- for more information. boPool :: Lens' BuildOptions (Maybe PoolOption) boPool = lens _boPool (\ s a -> s{_boPool = a}) -- | Option to specify behavior when there is an error in the substitution -- checks. NOTE: this is always set to ALLOW_LOOSE for triggered builds and -- cannot be overridden in the build configuration file. boSubstitutionOption :: Lens' BuildOptions (Maybe BuildOptionsSubstitutionOption) boSubstitutionOption = lens _boSubstitutionOption (\ s a -> s{_boSubstitutionOption = a}) -- | Requested verifiability options. boRequestedVerifyOption :: Lens' BuildOptions (Maybe BuildOptionsRequestedVerifyOption) boRequestedVerifyOption = lens _boRequestedVerifyOption (\ s a -> s{_boRequestedVerifyOption = a}) -- | This field deprecated; please use \`pool.name\` instead. boWorkerPool :: Lens' BuildOptions (Maybe Text) boWorkerPool = lens _boWorkerPool (\ s a -> s{_boWorkerPool = a}) -- | Compute Engine machine type on which to run the build. boMachineType :: Lens' BuildOptions (Maybe BuildOptionsMachineType) boMachineType = lens _boMachineType (\ s a -> s{_boMachineType = a}) -- | A list of global environment variables, which are encrypted using a -- Cloud Key Management Service crypto key. These values must be specified -- in the build\'s \`Secret\`. These variables will be available to all -- build steps in this build. boSecretEnv :: Lens' BuildOptions [Text] boSecretEnv = lens _boSecretEnv (\ s a -> s{_boSecretEnv = a}) . _Default . _Coerce -- | Global list of volumes to mount for ALL build steps Each volume is -- created as an empty volume prior to starting the build process. Upon -- completion of the build, volumes and their contents are discarded. -- Global volume names and paths cannot conflict with the volumes defined a -- build step. Using a global volume in a build with only one step is not -- valid as it is indicative of a build request with an incorrect -- configuration. boVolumes :: Lens' BuildOptions [Volume] boVolumes = lens _boVolumes (\ s a -> s{_boVolumes = a}) . _Default . _Coerce -- | Option to define build log streaming behavior to Google Cloud Storage. boLogStreamingOption :: Lens' BuildOptions (Maybe BuildOptionsLogStreamingOption) boLogStreamingOption = lens _boLogStreamingOption (\ s a -> s{_boLogStreamingOption = a}) -- | Option to specify the logging mode, which determines if and where build -- logs are stored. boLogging :: Lens' BuildOptions (Maybe BuildOptionsLogging) boLogging = lens _boLogging (\ s a -> s{_boLogging = a}) -- | Requested hash for SourceProvenance. boSourceProvenanceHash :: Lens' BuildOptions [BuildOptionsSourceProvenanceHashItem] boSourceProvenanceHash = lens _boSourceProvenanceHash (\ s a -> s{_boSourceProvenanceHash = a}) . _Default . _Coerce -- | Option to specify whether or not to apply bash style string operations -- to the substitutions. NOTE: this is always enabled for triggered builds -- and cannot be overridden in the build configuration file. boDynamicSubstitutions :: Lens' BuildOptions (Maybe Bool) boDynamicSubstitutions = lens _boDynamicSubstitutions (\ s a -> s{_boDynamicSubstitutions = a}) instance FromJSON BuildOptions where parseJSON = withObject "BuildOptions" (\ o -> BuildOptions' <$> (o .:? "diskSizeGb") <*> (o .:? "env" .!= mempty) <*> (o .:? "pool") <*> (o .:? "substitutionOption") <*> (o .:? "requestedVerifyOption") <*> (o .:? "workerPool") <*> (o .:? "machineType") <*> (o .:? "secretEnv" .!= mempty) <*> (o .:? "volumes" .!= mempty) <*> (o .:? "logStreamingOption") <*> (o .:? "logging") <*> (o .:? "sourceProvenanceHash" .!= mempty) <*> (o .:? "dynamicSubstitutions")) instance ToJSON BuildOptions where toJSON BuildOptions'{..} = object (catMaybes [("diskSizeGb" .=) <$> _boDiskSizeGb, ("env" .=) <$> _boEnv, ("pool" .=) <$> _boPool, ("substitutionOption" .=) <$> _boSubstitutionOption, ("requestedVerifyOption" .=) <$> _boRequestedVerifyOption, ("workerPool" .=) <$> _boWorkerPool, ("machineType" .=) <$> _boMachineType, ("secretEnv" .=) <$> _boSecretEnv, ("volumes" .=) <$> _boVolumes, ("logStreamingOption" .=) <$> _boLogStreamingOption, ("logging" .=) <$> _boLogging, ("sourceProvenanceHash" .=) <$> _boSourceProvenanceHash, ("dynamicSubstitutions" .=) <$> _boDynamicSubstitutions]) -- | Escape hatch for users to supply custom delivery configs. -- -- /See:/ 'notificationStructDelivery' smart constructor. newtype NotificationStructDelivery = NotificationStructDelivery' { _nsdAddtional :: HashMap Text JSONValue } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'NotificationStructDelivery' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'nsdAddtional' notificationStructDelivery :: HashMap Text JSONValue -- ^ 'nsdAddtional' -> NotificationStructDelivery notificationStructDelivery pNsdAddtional_ = NotificationStructDelivery' {_nsdAddtional = _Coerce # pNsdAddtional_} -- | Properties of the object. nsdAddtional :: Lens' NotificationStructDelivery (HashMap Text JSONValue) nsdAddtional = lens _nsdAddtional (\ s a -> s{_nsdAddtional = a}) . _Coerce instance FromJSON NotificationStructDelivery where parseJSON = withObject "NotificationStructDelivery" (\ o -> NotificationStructDelivery' <$> (parseJSONObject o)) instance ToJSON NotificationStructDelivery where toJSON = toJSON . _nsdAddtional -- | The normal response of the operation in case of success. If the original -- method returns no data on success, such as \`Delete\`, the response is -- \`google.protobuf.Empty\`. If the original method is standard -- \`Get\`\/\`Create\`\/\`Update\`, the response should be the resource. -- For other methods, the response should have the type \`XxxResponse\`, -- where \`Xxx\` is the original method name. For example, if the original -- method name is \`TakeSnapshot()\`, the inferred response type is -- \`TakeSnapshotResponse\`. -- -- /See:/ 'operationResponse' smart constructor. newtype OperationResponse = OperationResponse' { _orAddtional :: HashMap Text JSONValue } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'OperationResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'orAddtional' operationResponse :: HashMap Text JSONValue -- ^ 'orAddtional' -> OperationResponse operationResponse pOrAddtional_ = OperationResponse' {_orAddtional = _Coerce # pOrAddtional_} -- | Properties of the object. Contains field \'type with type URL. orAddtional :: Lens' OperationResponse (HashMap Text JSONValue) orAddtional = lens _orAddtional (\ s a -> s{_orAddtional = a}) . _Coerce instance FromJSON OperationResponse where parseJSON = withObject "OperationResponse" (\ o -> OperationResponse' <$> (parseJSONObject o)) instance ToJSON OperationResponse where toJSON = toJSON . _orAddtional -- | Specifies a build trigger to run and the source to use. -- -- /See:/ 'runBuildTriggerRequest' smart constructor. data RunBuildTriggerRequest = RunBuildTriggerRequest' { _rbtrTriggerId :: !(Maybe Text) , _rbtrSource :: !(Maybe RepoSource) , _rbtrProjectId :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'RunBuildTriggerRequest' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'rbtrTriggerId' -- -- * 'rbtrSource' -- -- * 'rbtrProjectId' runBuildTriggerRequest :: RunBuildTriggerRequest runBuildTriggerRequest = RunBuildTriggerRequest' {_rbtrTriggerId = Nothing, _rbtrSource = Nothing, _rbtrProjectId = Nothing} -- | Required. ID of the trigger. rbtrTriggerId :: Lens' RunBuildTriggerRequest (Maybe Text) rbtrTriggerId = lens _rbtrTriggerId (\ s a -> s{_rbtrTriggerId = a}) -- | Source to build against this trigger. rbtrSource :: Lens' RunBuildTriggerRequest (Maybe RepoSource) rbtrSource = lens _rbtrSource (\ s a -> s{_rbtrSource = a}) -- | Required. ID of the project. rbtrProjectId :: Lens' RunBuildTriggerRequest (Maybe Text) rbtrProjectId = lens _rbtrProjectId (\ s a -> s{_rbtrProjectId = a}) instance FromJSON RunBuildTriggerRequest where parseJSON = withObject "RunBuildTriggerRequest" (\ o -> RunBuildTriggerRequest' <$> (o .:? "triggerId") <*> (o .:? "source") <*> (o .:? "projectId")) instance ToJSON RunBuildTriggerRequest where toJSON RunBuildTriggerRequest'{..} = object (catMaybes [("triggerId" .=) <$> _rbtrTriggerId, ("source" .=) <$> _rbtrSource, ("projectId" .=) <$> _rbtrProjectId]) -- | Configuration for an automated build in response to source repository -- changes. -- -- /See:/ 'buildTrigger' smart constructor. data BuildTrigger = BuildTrigger' { _btSubstitutions :: !(Maybe BuildTriggerSubstitutions) , _btResourceName :: !(Maybe Text) , _btIncludedFiles :: !(Maybe [Text]) , _btSourceToBuild :: !(Maybe GitRepoSource) , _btDisabled :: !(Maybe Bool) , _btTriggerTemplate :: !(Maybe RepoSource) , _btBuild :: !(Maybe Build) , _btIgnoredFiles :: !(Maybe [Text]) , _btPubsubConfig :: !(Maybe PubsubConfig) , _btName :: !(Maybe Text) , _btId :: !(Maybe Text) , _btGithub :: !(Maybe GitHubEventsConfig) , _btFilter :: !(Maybe Text) , _btAutodetect :: !(Maybe Bool) , _btDescription :: !(Maybe Text) , _btFilename :: !(Maybe Text) , _btCreateTime :: !(Maybe DateTime') , _btWebhookConfig :: !(Maybe WebhookConfig) , _btTags :: !(Maybe [Text]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'BuildTrigger' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'btSubstitutions' -- -- * 'btResourceName' -- -- * 'btIncludedFiles' -- -- * 'btSourceToBuild' -- -- * 'btDisabled' -- -- * 'btTriggerTemplate' -- -- * 'btBuild' -- -- * 'btIgnoredFiles' -- -- * 'btPubsubConfig' -- -- * 'btName' -- -- * 'btId' -- -- * 'btGithub' -- -- * 'btFilter' -- -- * 'btAutodetect' -- -- * 'btDescription' -- -- * 'btFilename' -- -- * 'btCreateTime' -- -- * 'btWebhookConfig' -- -- * 'btTags' buildTrigger :: BuildTrigger buildTrigger = BuildTrigger' { _btSubstitutions = Nothing , _btResourceName = Nothing , _btIncludedFiles = Nothing , _btSourceToBuild = Nothing , _btDisabled = Nothing , _btTriggerTemplate = Nothing , _btBuild = Nothing , _btIgnoredFiles = Nothing , _btPubsubConfig = Nothing , _btName = Nothing , _btId = Nothing , _btGithub = Nothing , _btFilter = Nothing , _btAutodetect = Nothing , _btDescription = Nothing , _btFilename = Nothing , _btCreateTime = Nothing , _btWebhookConfig = Nothing , _btTags = Nothing } -- | Substitutions for Build resource. The keys must match the following -- regular expression: \`^_[A-Z0-9_]+$\`. btSubstitutions :: Lens' BuildTrigger (Maybe BuildTriggerSubstitutions) btSubstitutions = lens _btSubstitutions (\ s a -> s{_btSubstitutions = a}) -- | The \`Trigger\` name with format: -- \`projects\/{project}\/locations\/{location}\/triggers\/{trigger}\`, -- where {trigger} is a unique identifier generated by the service. btResourceName :: Lens' BuildTrigger (Maybe Text) btResourceName = lens _btResourceName (\ s a -> s{_btResourceName = a}) -- | If any of the files altered in the commit pass the ignored_files filter -- and included_files is empty, then as far as this filter is concerned, we -- should trigger the build. If any of the files altered in the commit pass -- the ignored_files filter and included_files is not empty, then we make -- sure that at least one of those files matches a included_files glob. If -- not, then we do not trigger a build. btIncludedFiles :: Lens' BuildTrigger [Text] btIncludedFiles = lens _btIncludedFiles (\ s a -> s{_btIncludedFiles = a}) . _Default . _Coerce -- | The repo and ref of the repository from which to build. This field is -- used only for those triggers that do not respond to SCM events. Triggers -- that respond to such events build source at whatever commit caused the -- event. This field is currently only used by Webhook, Pub\/Sub, Manual, -- and Cron triggers. btSourceToBuild :: Lens' BuildTrigger (Maybe GitRepoSource) btSourceToBuild = lens _btSourceToBuild (\ s a -> s{_btSourceToBuild = a}) -- | If true, the trigger will never automatically execute a build. btDisabled :: Lens' BuildTrigger (Maybe Bool) btDisabled = lens _btDisabled (\ s a -> s{_btDisabled = a}) -- | Template describing the types of source changes to trigger a build. -- Branch and tag names in trigger templates are interpreted as regular -- expressions. Any branch or tag change that matches that regular -- expression will trigger a build. Mutually exclusive with \`github\`. btTriggerTemplate :: Lens' BuildTrigger (Maybe RepoSource) btTriggerTemplate = lens _btTriggerTemplate (\ s a -> s{_btTriggerTemplate = a}) -- | Contents of the build template. btBuild :: Lens' BuildTrigger (Maybe Build) btBuild = lens _btBuild (\ s a -> s{_btBuild = a}) -- | ignored_files and included_files are file glob matches using -- https:\/\/golang.org\/pkg\/path\/filepath\/#Match extended with support -- for \"**\". If ignored_files and changed files are both empty, then they -- are not used to determine whether or not to trigger a build. If -- ignored_files is not empty, then we ignore any files that match any of -- the ignored_file globs. If the change has no files that are outside of -- the ignored_files globs, then we do not trigger a build. btIgnoredFiles :: Lens' BuildTrigger [Text] btIgnoredFiles = lens _btIgnoredFiles (\ s a -> s{_btIgnoredFiles = a}) . _Default . _Coerce -- | PubsubConfig describes the configuration of a trigger that creates a -- build whenever a Pub\/Sub message is published. btPubsubConfig :: Lens' BuildTrigger (Maybe PubsubConfig) btPubsubConfig = lens _btPubsubConfig (\ s a -> s{_btPubsubConfig = a}) -- | User-assigned name of the trigger. Must be unique within the project. -- Trigger names must meet the following requirements: + They must contain -- only alphanumeric characters and dashes. + They can be 1-64 characters -- long. + They must begin and end with an alphanumeric character. btName :: Lens' BuildTrigger (Maybe Text) btName = lens _btName (\ s a -> s{_btName = a}) -- | Output only. Unique identifier of the trigger. btId :: Lens' BuildTrigger (Maybe Text) btId = lens _btId (\ s a -> s{_btId = a}) -- | GitHubEventsConfig describes the configuration of a trigger that creates -- a build whenever a GitHub event is received. Mutually exclusive with -- \`trigger_template\`. btGithub :: Lens' BuildTrigger (Maybe GitHubEventsConfig) btGithub = lens _btGithub (\ s a -> s{_btGithub = a}) -- | Optional. A Common Expression Language string. btFilter :: Lens' BuildTrigger (Maybe Text) btFilter = lens _btFilter (\ s a -> s{_btFilter = a}) -- | Autodetect build configuration. The following precedence is used (case -- insensitive): 1. cloudbuild.yaml 2. cloudbuild.yml 3. cloudbuild.json 4. -- Dockerfile Currently only available for GitHub App Triggers. btAutodetect :: Lens' BuildTrigger (Maybe Bool) btAutodetect = lens _btAutodetect (\ s a -> s{_btAutodetect = a}) -- | Human-readable description of this trigger. btDescription :: Lens' BuildTrigger (Maybe Text) btDescription = lens _btDescription (\ s a -> s{_btDescription = a}) -- | Path, from the source root, to the build configuration file (i.e. -- cloudbuild.yaml). btFilename :: Lens' BuildTrigger (Maybe Text) btFilename = lens _btFilename (\ s a -> s{_btFilename = a}) -- | Output only. Time when the trigger was created. btCreateTime :: Lens' BuildTrigger (Maybe UTCTime) btCreateTime = lens _btCreateTime (\ s a -> s{_btCreateTime = a}) . mapping _DateTime -- | WebhookConfig describes the configuration of a trigger that creates a -- build whenever a webhook is sent to a trigger\'s webhook URL. btWebhookConfig :: Lens' BuildTrigger (Maybe WebhookConfig) btWebhookConfig = lens _btWebhookConfig (\ s a -> s{_btWebhookConfig = a}) -- | Tags for annotation of a \`BuildTrigger\` btTags :: Lens' BuildTrigger [Text] btTags = lens _btTags (\ s a -> s{_btTags = a}) . _Default . _Coerce instance FromJSON BuildTrigger where parseJSON = withObject "BuildTrigger" (\ o -> BuildTrigger' <$> (o .:? "substitutions") <*> (o .:? "resourceName") <*> (o .:? "includedFiles" .!= mempty) <*> (o .:? "sourceToBuild") <*> (o .:? "disabled") <*> (o .:? "triggerTemplate") <*> (o .:? "build") <*> (o .:? "ignoredFiles" .!= mempty) <*> (o .:? "pubsubConfig") <*> (o .:? "name") <*> (o .:? "id") <*> (o .:? "github") <*> (o .:? "filter") <*> (o .:? "autodetect") <*> (o .:? "description") <*> (o .:? "filename") <*> (o .:? "createTime") <*> (o .:? "webhookConfig") <*> (o .:? "tags" .!= mempty)) instance ToJSON BuildTrigger where toJSON BuildTrigger'{..} = object (catMaybes [("substitutions" .=) <$> _btSubstitutions, ("resourceName" .=) <$> _btResourceName, ("includedFiles" .=) <$> _btIncludedFiles, ("sourceToBuild" .=) <$> _btSourceToBuild, ("disabled" .=) <$> _btDisabled, ("triggerTemplate" .=) <$> _btTriggerTemplate, ("build" .=) <$> _btBuild, ("ignoredFiles" .=) <$> _btIgnoredFiles, ("pubsubConfig" .=) <$> _btPubsubConfig, ("name" .=) <$> _btName, ("id" .=) <$> _btId, ("github" .=) <$> _btGithub, ("filter" .=) <$> _btFilter, ("autodetect" .=) <$> _btAutodetect, ("description" .=) <$> _btDescription, ("filename" .=) <$> _btFilename, ("createTime" .=) <$> _btCreateTime, ("webhookConfig" .=) <$> _btWebhookConfig, ("tags" .=) <$> _btTags]) -- | NotifierMetadata contains the data which can be used to reference or -- describe this notifier. -- -- /See:/ 'notifierMetadata' smart constructor. data NotifierMetadata = NotifierMetadata' { _nmNotifier :: !(Maybe Text) , _nmName :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'NotifierMetadata' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'nmNotifier' -- -- * 'nmName' notifierMetadata :: NotifierMetadata notifierMetadata = NotifierMetadata' {_nmNotifier = Nothing, _nmName = Nothing} -- | The string representing the name and version of notifier to deploy. -- Expected to be of the form of \"\/:\". For example: -- \"gcr.io\/my-project\/notifiers\/smtp:1.2.34\". nmNotifier :: Lens' NotifierMetadata (Maybe Text) nmNotifier = lens _nmNotifier (\ s a -> s{_nmNotifier = a}) -- | The human-readable and user-given name for the notifier. For example: -- \"repo-merge-email-notifier\". nmName :: Lens' NotifierMetadata (Maybe Text) nmName = lens _nmName (\ s a -> s{_nmName = a}) instance FromJSON NotifierMetadata where parseJSON = withObject "NotifierMetadata" (\ o -> NotifierMetadata' <$> (o .:? "notifier") <*> (o .:? "name")) instance ToJSON NotifierMetadata where toJSON NotifierMetadata'{..} = object (catMaybes [("notifier" .=) <$> _nmNotifier, ("name" .=) <$> _nmName]) -- | NotifierSpec is the configuration container for notifications. -- -- /See:/ 'notifierSpec' smart constructor. data NotifierSpec = NotifierSpec' { _nsSecrets :: !(Maybe [NotifierSecret]) , _nsNotification :: !(Maybe Notification) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'NotifierSpec' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'nsSecrets' -- -- * 'nsNotification' notifierSpec :: NotifierSpec notifierSpec = NotifierSpec' {_nsSecrets = Nothing, _nsNotification = Nothing} -- | Configurations for secret resources used by this particular notifier. nsSecrets :: Lens' NotifierSpec [NotifierSecret] nsSecrets = lens _nsSecrets (\ s a -> s{_nsSecrets = a}) . _Default . _Coerce -- | The configuration of this particular notifier. nsNotification :: Lens' NotifierSpec (Maybe Notification) nsNotification = lens _nsNotification (\ s a -> s{_nsNotification = a}) instance FromJSON NotifierSpec where parseJSON = withObject "NotifierSpec" (\ o -> NotifierSpec' <$> (o .:? "secrets" .!= mempty) <*> (o .:? "notification")) instance ToJSON NotifierSpec where toJSON NotifierSpec'{..} = object (catMaybes [("secrets" .=) <$> _nsSecrets, ("notification" .=) <$> _nsNotification]) -- | An image built by the pipeline. -- -- /See:/ 'builtImage' smart constructor. data BuiltImage = BuiltImage' { _biPushTiming :: !(Maybe TimeSpan) , _biName :: !(Maybe Text) , _biDigest :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'BuiltImage' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'biPushTiming' -- -- * 'biName' -- -- * 'biDigest' builtImage :: BuiltImage builtImage = BuiltImage' {_biPushTiming = Nothing, _biName = Nothing, _biDigest = Nothing} -- | Output only. Stores timing information for pushing the specified image. biPushTiming :: Lens' BuiltImage (Maybe TimeSpan) biPushTiming = lens _biPushTiming (\ s a -> s{_biPushTiming = a}) -- | Name used to push the container image to Google Container Registry, as -- presented to \`docker push\`. biName :: Lens' BuiltImage (Maybe Text) biName = lens _biName (\ s a -> s{_biName = a}) -- | Docker Registry 2.0 digest. biDigest :: Lens' BuiltImage (Maybe Text) biDigest = lens _biDigest (\ s a -> s{_biDigest = a}) instance FromJSON BuiltImage where parseJSON = withObject "BuiltImage" (\ o -> BuiltImage' <$> (o .:? "pushTiming") <*> (o .:? "name") <*> (o .:? "digest")) instance ToJSON BuiltImage where toJSON BuiltImage'{..} = object (catMaybes [("pushTiming" .=) <$> _biPushTiming, ("name" .=) <$> _biName, ("digest" .=) <$> _biDigest]) -- | Substitutions to use in a triggered build. Should only be used with -- RunBuildTrigger -- -- /See:/ 'repoSourceSubstitutions' smart constructor. newtype RepoSourceSubstitutions = RepoSourceSubstitutions' { _rssAddtional :: HashMap Text Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'RepoSourceSubstitutions' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'rssAddtional' repoSourceSubstitutions :: HashMap Text Text -- ^ 'rssAddtional' -> RepoSourceSubstitutions repoSourceSubstitutions pRssAddtional_ = RepoSourceSubstitutions' {_rssAddtional = _Coerce # pRssAddtional_} rssAddtional :: Lens' RepoSourceSubstitutions (HashMap Text Text) rssAddtional = lens _rssAddtional (\ s a -> s{_rssAddtional = a}) . _Coerce instance FromJSON RepoSourceSubstitutions where parseJSON = withObject "RepoSourceSubstitutions" (\ o -> RepoSourceSubstitutions' <$> (parseJSONObject o)) instance ToJSON RepoSourceSubstitutions where toJSON = toJSON . _rssAddtional -- | WebhookConfig describes the configuration of a trigger that creates a -- build whenever a webhook is sent to a trigger\'s webhook URL. -- -- /See:/ 'webhookConfig' smart constructor. data WebhookConfig = WebhookConfig' { _wcState :: !(Maybe WebhookConfigState) , _wcSecret :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'WebhookConfig' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'wcState' -- -- * 'wcSecret' webhookConfig :: WebhookConfig webhookConfig = WebhookConfig' {_wcState = Nothing, _wcSecret = Nothing} -- | Potential issues with the underlying Pub\/Sub subscription -- configuration. Only populated on get requests. wcState :: Lens' WebhookConfig (Maybe WebhookConfigState) wcState = lens _wcState (\ s a -> s{_wcState = a}) -- | Required. Resource name for the secret required as a URL parameter. wcSecret :: Lens' WebhookConfig (Maybe Text) wcSecret = lens _wcSecret (\ s a -> s{_wcSecret = a}) instance FromJSON WebhookConfig where parseJSON = withObject "WebhookConfig" (\ o -> WebhookConfig' <$> (o .:? "state") <*> (o .:? "secret")) instance ToJSON WebhookConfig where toJSON WebhookConfig'{..} = object (catMaybes [("state" .=) <$> _wcState, ("secret" .=) <$> _wcSecret])
brendanhay/gogol
gogol-containerbuilder/gen/Network/Google/ContainerBuilder/Types/Product.hs
mpl-2.0
173,022
0
38
40,921
31,197
18,007
13,190
3,333
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} module Main where import Data.Maybe (fromJust) import qualified Data.Text as T (unpack) import Data.GI.Base.ManagedPtr (unsafeCastTo) import Data.GI.Base.GError (gerrorMessage, GError(..)) import Control.Exception (catch) import qualified GI.Gtk as Gtk (main, init) import GI.Gtk (widgetShowAll, mainQuit, onWidgetDestroy, onButtonClicked, Button(..), Window(..), builderGetObject, builderAddFromFile, builderNew) main = (do Gtk.init Nothing -- Create the builder, and load the UI file builder <- builderNew builderAddFromFile builder "simple.ui" -- Retrieve some objects from the UI window <- builderGetObject builder "window1" >>= unsafeCastTo Window . fromJust button <- builderGetObject builder "button1" >>= unsafeCastTo Button . fromJust -- Basic user interation onButtonClicked button $ putStrLn "button pressed!" onWidgetDestroy window mainQuit -- Display the window widgetShowAll window Gtk.main) `catch` (\(e::GError) -> gerrorMessage e >>= putStrLn . T.unpack)
haskell-gi/gi-gtk-examples
gtkbuilder/GtkBuilderTest.hs
lgpl-2.1
1,119
0
12
199
275
155
120
23
1
{-# LANGUAGE QuasiQuotes #-} module ParseAndPrintSpec where ------------------------------------------------------------------------------ import HC.ParseAndPrint ------------------------------------------------------------------------------ import Language.LBNF.Compiletime import Test.Hspec ------------------------------------------------------------------------------ spec :: Spec spec = do parseST printST deBruijnST parseST :: Spec parseST = describe "parseST" $ do -------------------------------------------------- tpGType "a" (Ok (GTFree (Ident "a"))) tpGITerm "ann x :: a" (Ok (GAnn (GInf (GVar (Ident "x"))) (GTFree (Ident "a")))) -------------------------------------------------- tpGType "a -> b" (Ok (GFun (GTFree (Ident "a")) (GTFree (Ident "b")))) tpGITerm "ann \\x -> x :: a -> a" (Ok (GAnn (GLam (Ident "x") [] (GInf (GVar (Ident "x")))) (GFun (GTFree (Ident "a")) (GTFree (Ident "a"))))) -------------------------------------------------- tpGType "a -> b -> c" (Ok (GFun (GTFree (Ident "a")) (GFun (GTFree (Ident "b")) (GTFree (Ident "c"))))) -------------------------------------------------- tpGCTerm "x" (Ok (GInf (GVar (Ident "x")))) tpGITerm "x" (Ok (GVar (Ident "x"))) -------------------------------------------------- tpGCTerm "\\x -> x" (Ok (GLam (Ident "x") [] (GInf (GVar (Ident "x"))))) tpGStm "let x = ann \\x -> x :: a" (Ok (GLet (Ident "x") (GAnn (GLam (Ident "x") [] (GInf (GVar (Ident "x")))) (GTFree (Ident "a"))))) tpGStm "let x = ann \\x -> x :: a -> a" (Ok (GLet (Ident "x") (GAnn (GLam (Ident "x") [] (GInf (GVar (Ident "x")))) (GFun (GTFree (Ident "a")) (GTFree (Ident "a")))))) tpGStm "let x = ann \\x x -> x :: a -> a -> a" (Ok (GLet (Ident "x") (GAnn (GLam (Ident "x") [Ident "x"] (GInf (GVar (Ident "x")))) (GFun (GTFree (Ident "a")) (GFun (GTFree (Ident "a")) (GTFree (Ident "a"))))))) -------------------------------------------------- tpGCTerm "\\x y -> (x y)" (Ok (GLam (Ident "x") [Ident "y"] (GInf (GAp (GVar (Ident "x")) (GInf (GVar (Ident "y"))))))) tpGCTerm "\\x y z-> (x y)" (Ok (GLam (Ident "x") [Ident "y",Ident "z"] (GInf (GAp (GVar (Ident "x")) (GInf (GVar (Ident "y"))))))) -------------------------------------------------- tpGCTerm "(x x)" (Ok (GInf (GAp (GVar (Ident "x")) (GInf (GVar (Ident "x")))))) tpGITerm "(x x)" (Ok (GAp (GVar (Ident "x")) (GInf (GVar (Ident "x"))))) tpGStm "(x z)" (Ok (GEval (GAp (GVar (Ident "x")) (GInf (GVar (Ident "z")))))) -------------------------------------------------- tpGStm "((x y) z)" (Ok (GEval (GAp (GAp (GVar (Ident "x")) (GInf (GVar (Ident "y")))) (GInf (GVar (Ident "z")))))) ------------------------------------------------------------------------------ printST :: Spec printST = describe "printST" $ do it "print \\x y z -> ((z y) x)" $ printTree [gCTerm|\x y z -> ((z y) x)|] `shouldBe` "\\ x y z -> ((z y)x)" it "print let x = ann \\x x -> x :: a -> a -> a" $ printTree [gStm|let x = ann \x x -> x :: a -> a -> a|] `shouldBe` "let x = ann \\ x x -> x :: a -> a -> a" ------------------------------------------------------------------------------ deBruijnST :: Spec deBruijnST = describe "deBruijnST" $ tdbC "\\x y z-> (((z y) x) g)" (Lam (Lam (Lam (Inf (((Bound 0 :@: Inf (Bound 1)) :@: Inf (Bound 2)) :@: Inf (Free (Global "g"))))))) ------------------------------------------------------------------------------ tpGStm :: String -> ParseMonad GStm -> Spec tpGStm x expect = it ("pGStm " ++ x) $ pGStm (myLexer x) `shouldBe` expect tpGITerm :: String -> ParseMonad GITerm -> Spec tpGITerm x expect = it ("pGITerm " ++ x) $ pGITerm (myLexer x) `shouldBe` expect tpGCTerm :: String -> ParseMonad GCTerm -> Spec tpGCTerm x expect = it ("pGCTerm " ++ x) $ pGCTerm (myLexer x) `shouldBe` expect tpGType :: String -> ParseMonad GType -> Spec tpGType x expect = it ("pGType " ++ x) $ pGType (myLexer x) `shouldBe` expect tdbC :: String -> CTerm -> Spec tdbC x expect = it x $ case pGCTerm (myLexer x) of Ok ok -> deBruijnC [] ok `shouldBe` expect bad -> show bad `shouldBe` "WRONG"
haroldcarr/learn-haskell-coq-ml-etc
haskell/topic/parsing/bnfc-meta-examples/test/ParseAndPrintSpec.hs
unlicense
4,662
0
23
1,262
1,659
828
831
92
2
{-# OPTIONS_GHC -fno-warn-orphans #-} module Hecate.Orphans () where import Data.Text.Arbitrary () import Test.QuickCheck (Arbitrary (..)) import Hecate.Data (Description (..), Identity (..), Metadata (..), Plaintext (..)) instance Arbitrary Description where arbitrary = Description <$> arbitrary shrink (Description xs) = Description <$> shrink xs instance Arbitrary Identity where arbitrary = Identity <$> arbitrary shrink (Identity xs) = Identity <$> shrink xs instance Arbitrary Plaintext where arbitrary = Plaintext <$> arbitrary shrink (Plaintext xs) = Plaintext <$> shrink xs instance Arbitrary Metadata where arbitrary = Metadata <$> arbitrary shrink (Metadata xs) = Metadata <$> shrink xs
henrytill/hecate
tests/Hecate/Orphans.hs
apache-2.0
813
0
8
207
220
122
98
17
0
-- How many polynomials of degree k in Z_n[x] that are 0 under every evaluation map? -- coefficientList generates polynomials of degree k. coefficientList :: Int -> Int -> [[Int]] coefficientList n k = recurse k $ map (:[]) [1..n-1] where recurse 0 ls = ls recurse c ls = recurse (c - 1) [a : as | a <- [0..n-1], as <- ls] coefficientList' :: Int -> Int -> [[Int]] coefficientList' n k = recurse k [[1]] where recurse 0 ls = ls recurse c ls = recurse (c - 1) [a : as | a <- [0, 1], as <- ls] nonzeroZeroes n k = filter (`nonzeroZero` n) $ coefficientList n k nonzeroZeroes' n k = filter (`nonzeroZero` n) $ coefficientList' n k nonzeroZero coeffs n = all ((==0) . (`mod` n) . evaluate coeffs) [0..n] -- evaluate [1,2,3] 10 = 1 + 2*10 + 3*100 = 321 evaluate coeffs k = recurse 0 1 coeffs where recurse s _ [] = s recurse s x (c:cs) = recurse (s + c*x) (x*k) cs -- Table read by rows: T(n,k) gives the number of degree k polynomials with -- coefficients in Z/nZ that evaluate to 0 for all values in Z/nZ, with n > 1, k > 0 -- 2: 0, 1, 2, 4, 8, 16, 32, ... -- 3: 0, 0, 2, 6, 18, 54, 162, ... -- 4: 0, 1, 2, 12, 48, 192, 768, ... -- 5: 0, 0, 0, 0, 4, 20, 100, ... -- 6: 0, 1, 10, 60, 360, 2160, 12960, ... -- 7: 0, 0, 0, 0, 0, 0, 6, ... -- Table read by rows: T(n,k) gives the number of degree k polynomials with -- coefficients in {0,1} that evaluate to 0 (mod n) for all values in Z/nZ, with n > 1, k > 0. -- 2: 0,1,2,4,8,16,32, ... -- 3: 0,0,0,0,1,2,6,15,30,66,121,242,... (https://oeis.org/draft/A329479) -- 4: 0,0,0,0,1,2,6,10,20,32,64,120,256,512,1056,2080,4160,8192,16384,32640,65536,131072,... -- 5: 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,4,8,40,... -- 6: 0,0,0,0,0,1,3,12,24,60,101,202,312,573,903,1785,3248 -- 7: 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,^CInterrupted. -- 8: 0,0,0,0,0,0,0,0,0,1,4,20,50,150,300,700,... -- Idea, count up to scaling. So 2x + 1 and x + 2 are the same (mod 3) -- Complication: Are 2x and 0 the same (mod 6), via multiplication by 3? -- Idea, 0-1 polynomials with exactly n 1s. -- 2: 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16 -- 3: 0,0,0,0,1,1,3,3,6,6,10,10,15,15,21,21,28,28,36 -- 4: 0,0,0,0,1,2,6,10,19,28,44,60,85,110,146,182,231 -- 5: 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,5 -- 6: 0,0,0,0,0,1,3,12,24,60,101,201,306,531,756,1197 -- 7: 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,^CInterrupted. -- Idea, some minimality condition on polynomials. For example, for n = 2, -- don't count x^3 + x^2 = x(x^2 + x) since x^2 + x works. -- Idea, polynomials that are bijections under the evaluation map.
peterokagey/haskellOEIS
src/Sandbox/NonzeroZeroPolynomials.hs
apache-2.0
2,579
0
12
494
435
245
190
14
2
{-# LANGUAGE PatternSynonyms #-} {- Copyright 2020 The CodeWorld Authors. All rights reserved. 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. -} module CodeWorld ( -- * Entry points drawingOf, animationOf, activityOf, debugActivityOf, groupActivityOf, unsafeGroupActivityOf, -- * Pictures Picture, TextStyle (..), Font (..), blank, polyline, thickPolyline, polygon, thickPolygon, solidPolygon, curve, thickCurve, closedCurve, thickClosedCurve, solidClosedCurve, rectangle, solidRectangle, thickRectangle, circle, solidCircle, thickCircle, arc, sector, thickArc, lettering, styledLettering, colored, coloured, translated, scaled, dilated, rotated, reflected, clipped, pictures, (<>), (&), coordinatePlane, codeWorldLogo, Point, translatedPoint, rotatedPoint, reflectedPoint, scaledPoint, dilatedPoint, Vector, vectorLength, vectorDirection, vectorSum, vectorDifference, scaledVector, rotatedVector, dotProduct, -- * Colors Color (..), Colour, pattern RGB, pattern HSL, black, white, red, green, blue, yellow, orange, brown, pink, purple, gray, grey, mixed, lighter, light, darker, dark, brighter, bright, duller, dull, translucent, assortedColors, hue, saturation, luminosity, alpha, -- * Events Event (..), -- * Debugging trace, ) where import CodeWorld.Color import CodeWorld.EntryPoints import CodeWorld.Event import CodeWorld.Picture
google/codeworld
codeworld-api/src/CodeWorld.hs
apache-2.0
2,225
0
5
635
331
224
107
98
0
{- Ray.hs - Ray type - - Timothy A. Chagnon - CS 636 - Spring 2009 -} module Ray where import Math import Material data Ray = Ray Vec3f Vec3f deriving Show -- t Normal Material data Intersection = Inx RealT Vec3f Material deriving (Show, Eq) instance Ord Intersection where compare (Inx t0 _ _) (Inx t1 _ _) = compare t0 t1 intxLessThan :: Intersection -> RealT -> Bool intxLessThan (Inx t0 _ _) t1 = t0 < t1
tchagnon/cs636-raytracer
a5/Ray.hs
apache-2.0
456
0
8
127
130
70
60
11
1
{-# LANGUAGE DeriveGeneric, DeriveFunctor, DeriveFoldable #-} {- © Utrecht University (Department of Information and Computing Sciences) -} module Domain.Scenarios.Globals where import GHC.Generics import Data.Binary import qualified Data.Map as M import Data.Maybe import qualified Domain.Scenarios.DomainData as DD type ID = String type Name = String data StatementInfo = StatementInfo { statType :: StatementType , statCharacterIdref :: Maybe ID , statText :: StatementText , statPropertyValues :: PropertyValues } deriving (Show, Eq, Read, Generic) instance Binary StatementInfo type StatementType = String type StatementText = String type PropertyValues = Charactered (Assocs DD.Value) data Charactered a = Charactered { characteredIndependent :: a , characteredPerCharacter :: M.Map String a } deriving (Show, Eq, Read, Functor, Foldable, Generic) instance Binary a => Binary (Charactered a) data Assocs a = Assocs [(String, a)] deriving (Show, Read, Eq, Generic) instance Binary a => Binary (Assocs a) -------------------------------------------------------------------------------------------------------------------------- data Definitions = Definitions { definitionsCharacters :: [CharacterDefinition] , definitionsProperties :: ([Definition ()], TypeMap) , definitionsParameters :: (Usered [Definition ()], TypeMap) } deriving (Show, Read, Generic) instance Binary Definitions data CharacterDefinition = CharacterDefinition { characterDefinitionId :: ID , characterDefinitionName :: Maybe Name } deriving (Show, Read, Generic) instance Binary CharacterDefinition type TypeMap = M.Map ID DD.Type data Usered a = Usered { useredUserDefined :: a , useredFixed :: a } deriving (Show, Read, Functor, Foldable, Generic) instance Binary a => Binary (Usered a) data Definition a = Definition { definitionId :: ID , definitionName :: Name , definitionDescription :: Maybe String , definitionType :: DD.Type , definitionDefault :: Maybe DD.Value , definitionContent :: a } deriving (Show, Read, Generic) instance Binary a => Binary (Definition a) type ParameterState = Usered (Charactered ParameterMap) type ParameterMap = M.Map ID DD.Value -- | Retrieves the value of a parameter from the given state getParameterValue :: ParameterState -> ID -> Maybe ID -> DD.Value getParameterValue paramState idref mCharacterIdref = case mCharacterIdref of Just characterIdref -> M.findWithDefault unknownParameter idref $ M.findWithDefault unknownCharacter characterIdref $ M.union (characteredPerCharacter (useredUserDefined paramState)) (characteredPerCharacter (useredFixed paramState)) where unknownCharacter = error ("Reference to unknown character " ++ characterIdref) Nothing -> M.findWithDefault unknownParameter idref $ M.union (characteredIndependent (useredUserDefined paramState)) (characteredIndependent (useredFixed paramState)) where unknownParameter = error ("Reference to unknown parameter " ++ idref) -- Functions for dealing with the Nothing case of a Maybe value produced by the -- implementation of fail in the Monad instance of Maybe. -- Useful for handling failure of findAttribute and findChild (from Ideas.Text.XML.Interface). errorOnFail :: String -> Maybe a -> a errorOnFail errorMsg = fromMaybe (error errorMsg) emptyOnFail :: Maybe [a] -> [a] emptyOnFail = fromMaybe [] -- | Applies a function to the first element of a list, if there is one applyToFirst :: (a -> a) -> [a] -> [a] applyToFirst _ [] = [] applyToFirst f (x:xs) = f x : xs
UURAGE/ScenarioReasoner
src/Domain/Scenarios/Globals.hs
apache-2.0
3,785
0
13
785
921
502
419
73
2
module HelperSequences.A116416Spec (main, spec) where import Test.Hspec import HelperSequences.A116416 (a116416) main :: IO () main = hspec spec spec :: Spec spec = describe "A116416" $ it "correctly computes the first 20 elements" $ take 20 (map a116416 [0..]) `shouldBe` expectedValue where expectedValue = [0,1,1,3,1,4,5,11,1,5,3,7,7,19,13,25,1,6,7,17]
peterokagey/haskellOEIS
test/HelperSequences/A116416Spec.hs
apache-2.0
370
0
10
59
160
95
65
10
1
{-# LANGUAGE TypeFamilies, FlexibleInstances, FlexibleContexts, DeriveDataTypeable, StandaloneDeriving #-} ----------------------------------------------------------------------------- -- | -- Module : HEP.Automation.MadGraph.Model.AxiGluon -- Copyright : (c) 2011, 2012 Ian-Woo Kim -- -- License : BSD3 -- Maintainer : Ian-Woo Kim <ianwookim@gmail.com> -- Stability : experimental -- Portability : GHC -- -- Axigluon model -- ----------------------------------------------------------------------------- module HEP.Automation.MadGraph.Model.AxiGluon where import Control.Monad.Identity import Data.Typeable import Data.Data import Text.Parsec import Text.Printf import Text.StringTemplate import Text.StringTemplate.Helpers -- from hep-platform import HEP.Automation.MadGraph.Model -- | data AxiGluon = AxiGluon deriving (Show, Typeable, Data) instance Model AxiGluon where data ModelParam AxiGluon = AxiGluonParam { massAxiG :: Double, gVq :: Double , gVt :: Double , gAq :: Double , gAt :: Double } deriving Show briefShow AxiGluon = "Axi" madgraphVersion _ = MadGraph4 modelName AxiGluon = "Axigluon_AV_MG" modelFromString str = case str of "Axigluon_AV_MG" -> Just AxiGluon _ -> Nothing paramCard4Model AxiGluon = "param_card_axigluon.dat" paramCardSetup tpath AxiGluon (AxiGluonParam m gvq gvt gaq gat) = do templates <- directoryGroup tpath return $ ( renderTemplateGroup templates [ ("maxi" , (printf "%.4e" m :: String)) , ("gvq" , (printf "%.4e" gvq :: String)) , ("gvt" , (printf "%.4e" gvt :: String)) , ("gaq" , (printf "%.4e" gaq :: String)) , ("gat" , (printf "%.4e" gat :: String)) , ("waxi", (printf "%.4e" (gammaAxigluon 0.118 m gvq gvt gaq gat) :: String)) ] (paramCard4Model AxiGluon) ) ++ "\n\n\n" briefParamShow (AxiGluonParam m gvq gvt gaq gat) = "M"++show m++"Vq"++show gvq ++ "Vt"++show gvt ++ "Aq" ++ show gaq ++ "At" ++ show gat interpreteParam str = let r = parse axigluonparse "" str in case r of Right param -> param Left err -> error (show err) axigluonparse :: ParsecT String () Identity (ModelParam AxiGluon) axigluonparse = do char 'M' massstr <- many1 ( oneOf "+-0123456789." ) string "Vq" gvqstr <- many1 ( oneOf "+-0123456789." ) string "Vt" gvtstr <- many1 ( oneOf "+-0123456789." ) string "Aq" gaqstr <- many1 ( oneOf "+-0123456789." ) string "At" gatstr <- many1 ( oneOf "+-0123456789." ) return (AxiGluonParam (read massstr) (read gvqstr) (read gvtstr) (read gaqstr) (read gatstr)) gammaAxigluon :: Double -> Double -> Double -> Double -> Double -> Double -> Double gammaAxigluon alphas mass gvq gvt gaq gat = alphas / 3.0 * mass * (gvt^(2 :: Int) + gat^(2 :: Int) + 2.0 * ( gvq^(2 :: Int) + gaq^(2 :: Int) ) ) axiGluonTr :: TypeRep axiGluonTr = mkTyConApp (mkTyCon "HEP.Automation.MadGraph.Model.AxiGluon.AxiGluon") [] instance Typeable (ModelParam AxiGluon) where typeOf _ = mkTyConApp modelParamTc [axiGluonTr] deriving instance Data (ModelParam AxiGluon)
wavewave/madgraph-auto-model
src/HEP/Automation/MadGraph/Model/AxiGluon.hs
bsd-2-clause
3,581
0
17
1,090
908
477
431
68
1
{-# LANGUAGE CPP #-} {-# LANGUAGE OverloadedStrings #-} -- | -- -- OAuth2 plugin for http://spotify.com -- module Yesod.Auth.OAuth2.Spotify ( oauth2Spotify , module Yesod.Auth.OAuth2 ) where #if __GLASGOW_HASKELL__ < 710 import Control.Applicative ((<$>), (<*>), pure) #endif import Control.Monad (mzero) import Data.Aeson import Data.ByteString (ByteString) import Data.Maybe import Data.Text (Text) import Data.Text.Encoding (encodeUtf8) import Yesod.Auth import Yesod.Auth.OAuth2 import qualified Data.ByteString as B import qualified Data.Text as T data SpotifyUserImage = SpotifyUserImage { spotifyUserImageHeight :: Maybe Int , spotifyUserImageWidth :: Maybe Int , spotifyUserImageUrl :: Text } instance FromJSON SpotifyUserImage where parseJSON (Object v) = SpotifyUserImage <$> v .: "height" <*> v .: "width" <*> v .: "url" parseJSON _ = mzero data SpotifyUser = SpotifyUser { spotifyUserId :: Text , spotifyUserHref :: Text , spotifyUserUri :: Text , spotifyUserDisplayName :: Maybe Text , spotifyUserProduct :: Maybe Text , spotifyUserCountry :: Maybe Text , spotifyUserEmail :: Maybe Text , spotifyUserImages :: Maybe [SpotifyUserImage] } instance FromJSON SpotifyUser where parseJSON (Object v) = SpotifyUser <$> v .: "id" <*> v .: "href" <*> v .: "uri" <*> v .:? "display_name" <*> v .:? "product" <*> v .:? "country" <*> v .:? "email" <*> v .:? "images" parseJSON _ = mzero oauth2Spotify :: YesodAuth m => Text -- ^ Client ID -> Text -- ^ Client Secret -> [ByteString] -- ^ Scopes -> AuthPlugin m oauth2Spotify clientId clientSecret scope = authOAuth2 "spotify" OAuth2 { oauthClientId = encodeUtf8 clientId , oauthClientSecret = encodeUtf8 clientSecret , oauthOAuthorizeEndpoint = B.append "https://accounts.spotify.com/authorize?scope=" (B.intercalate "%20" scope) , oauthAccessTokenEndpoint = "https://accounts.spotify.com/api/token" , oauthCallback = Nothing } $ fromProfileURL "spotify" "https://api.spotify.com/v1/me" toCreds toCreds :: SpotifyUser -> Creds m toCreds user = Creds { credsPlugin = "spotify" , credsIdent = spotifyUserId user , credsExtra = mapMaybe getExtra extrasTemplate } where userImage :: Maybe SpotifyUserImage userImage = spotifyUserImages user >>= listToMaybe userImagePart :: (SpotifyUserImage -> Maybe a) -> Maybe a userImagePart getter = userImage >>= getter extrasTemplate = [ ("href", Just $ spotifyUserHref user) , ("uri", Just $ spotifyUserUri user) , ("display_name", spotifyUserDisplayName user) , ("product", spotifyUserProduct user) , ("country", spotifyUserCountry user) , ("email", spotifyUserEmail user) , ("image_url", spotifyUserImageUrl <$> userImage) , ("image_height", T.pack . show <$> userImagePart spotifyUserImageHeight) , ("image_width", T.pack . show <$> userImagePart spotifyUserImageWidth) ] getExtra :: (Text, Maybe Text) -> Maybe (Text, Text) getExtra (key, val) = fmap ((,) key) val
jasonzoladz/yesod-auth-oauth2
Yesod/Auth/OAuth2/Spotify.hs
bsd-2-clause
3,386
0
21
912
799
450
349
79
1
{-# LANGUAGE TypeOperators #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE Rank2Types #-} module Orbits.Units ( au , solarMass , simLength , simTime , simMass , simVelocity , simEnergy , gravitationalConstant , simGravitationalConstant , day , year , inUnit , fromUnit ) where import Prelude () import Numeric.Units.Dimensional.Prelude import Numeric.Units.Dimensional.NonSI (year) import Numeric.Units.Dimensional.UnitNames (atom) import Control.Lens ((^.), Iso', iso, from) -- | An Iso, for moving between a physical quantity and a raw number, -- representing that physical quantity in some units inUnit :: Fractional a => Unit m d a -> Iso' (Quantity d a) a inUnit u = iso (/~ u) (*~ u) fromUnit :: Fractional a => Unit m d a -> Iso' a (Quantity d a) fromUnit u = from $ inUnit u -- | Astronomical unit. -- Approximate distance between Earth and Sol au :: Floating a => Unit 'NonMetric DLength a au = mkUnitR (atom "au" "au" "astronomical unit") 1.49597870700e+11 meter -- | Mass of Sol. solarMass :: Floating a => Unit 'NonMetric DMass a solarMass = mkUnitR (atom "mS" "mS" "solar mass") 1.98855e+30 (kilo gram) -- | Unit of length used for the simulation simLength :: Floating a => Unit 'NonMetric DLength a simLength = au -- | Unit of time used for the simulation simTime :: Floating a => Unit 'NonMetric DTime a simTime = day -- | Unit of mass used for the simulation simMass :: Floating a => Unit 'NonMetric DMass a simMass = solarMass -- | Unit of velocity used for the simulation simVelocity :: Floating a => Unit 'NonMetric DVelocity a simVelocity = simLength / simTime -- | Unit of energy used for the simulation simEnergy :: Floating a => Unit 'NonMetric DEnergy a simEnergy = simMass * simLength * simLength / (simTime * simTime) -- | Newton's Gravitational Constant. gravitationalConstant :: Floating a => Quantity (DVolume / (DMass * DTime * DTime)) a gravitationalConstant = 6.67408e-11 *~ ((cubic meter) / (kilo gram * second * second)) -- | Gravitational Constant, expressed in simulation units simGravitationalConstant :: Floating a => a simGravitationalConstant = gravitationalConstant ^. (inUnit ((cubic simLength) / (simMass * simTime * simTime)))
bjoeris/orbits-haskell-tensorflow
src/Orbits/Units.hs
bsd-3-clause
2,214
0
12
402
596
324
272
44
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} module IOStreams where import Control.Exception import Data.ByteString (ByteString) import Data.Char (isSpace) import qualified Data.Text as Text import System.IO.Streams (InputStream, OutputStream) import qualified System.IO.Streams as Streams run :: FilePath -> IO () run fname = do i <- Streams.withFileAsInput fname countWhiteSpace print i countWhiteSpace :: InputStream ByteString -> IO Int countWhiteSpace is = Streams.decodeUtf8 is >>= Streams.map (Text.length . Text.filter isSpace) >>= Streams.fold (+) 0
fujimura/functional-stream-processing-meetup-sample
src/IOStreams.hs
bsd-3-clause
696
0
11
182
168
92
76
17
1
module PackageTests.BuildCompilerFlags.BuildTypeCustom.Suite ( test ) where import PackageTests.BuildCompilerFlags.Util import qualified PackageTests.PackageTester as PT import System.FilePath ((</>)) import Test.Framework (Test, testGroup) import Test.Framework.Providers.HUnit (testCase) dir :: FilePath dir = "PackageTests" </> "BuildCompilerFlags" </> "BuildTypeCustom" test :: PT.TestsPaths -> Test test paths' = testGroup "BuildTypeCustom" [ testGroup "'cabal configure'" [ testCase "Add default setup compiler options to newly generated ~/.cabal/config" $ withTestDir $ \ paths -> do _ <- configure paths [] assertLineInFile "-- build-compiler-path:" (PT.configPath paths) assertLineInFile "-- build-hc-pkg-path:" (PT.configPath paths) , testCase "Pass setup compiler options from ~/.cabal/config to 'Setup.hs'" $ withTestDir $ \ paths -> do copyTestScriptsToTempDir paths writeFile (PT.configPath paths) (cabalConfigBuildCompiler paths) res <- configure paths [] PT.assertConfigureSucceeded res let configureOutput = PT.outputText res assertLineInString (testBuildCompOpt paths) configureOutput assertLineInString (testBuildHcPkgOpt paths) configureOutput assertTestCompilerLogFile paths assertTestHcPkgLogFile paths , testCase "Pass command line setup compiler options to 'Setup.hs'" $ withTestDir $ \ paths -> do copyTestScriptsToTempDir paths let opts = [testBuildCompOpt paths, testBuildHcPkgOpt paths] res <- configure paths opts PT.assertConfigureSucceeded res let configureOutput = PT.outputText res assertLineInString (testBuildCompOpt paths) configureOutput assertLineInString (testBuildHcPkgOpt paths) configureOutput assertTestCompilerLogFile paths assertTestHcPkgLogFile paths ] , testGroup "'cabal install'" [ testCase "Pass setup compiler options from ~/.cabal/config to 'Setup.hs'" $ withTestDir $ \ paths -> do copyTestScriptsToTempDir paths writeFile (PT.configPath paths) (cabalConfigBuildCompiler paths) res <- install paths [] PT.assertInstallSucceeded res let installOutput = PT.outputText res assertLineInString (testBuildCompOpt paths) installOutput assertLineInString (testBuildHcPkgOpt paths) installOutput assertTestCompilerLogFile paths assertTestHcPkgLogFile paths , testCase "Use the '--with-build-*' command line options" $ withTestDir $ \ paths -> do copyTestScriptsToTempDir paths let opts = [testBuildCompOpt paths, testBuildHcPkgOpt paths] res <- install paths opts PT.assertInstallSucceeded res let installOutput = PT.outputText res assertLineInString (testBuildCompOpt paths) installOutput assertLineInString (testBuildHcPkgOpt paths) installOutput assertTestCompilerLogFile paths assertTestHcPkgLogFile paths ] ] where configure p = PT.cabal_configure p dir install p = PT.cabal_install p dir withTestDir = PT.withTempBuildDir dir paths'
plumlife/cabal
cabal-install/tests/PackageTests/BuildCompilerFlags/BuildTypeCustom/Suite.hs
bsd-3-clause
3,269
0
17
785
717
334
383
73
1
{-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} -- -- RegTypes.hs --- ADC register types -- -- Copyright (C) 2015, Galois, Inc. -- All Rights Reserved. -- module Ivory.BSP.STM32.Peripheral.ADC.RegTypes where import Ivory.Language [ivory| bitdata ADCResolution :: Bits 2 = adc_12bit as 0 | adc_10bit as 1 | adc_8bit as 2 | adc_6bit as 3 |]
GaloisInc/ivory-tower-stm32
ivory-bsp-stm32/src/Ivory/BSP/STM32/Peripheral/ADC/RegTypes.hs
bsd-3-clause
444
0
4
86
32
26
6
7
0
module Fibon.Run.Config ( Fibon.ConfigMonad.append , Fibon.ConfigMonad.setTimeout , Fibon.ConfigMonad.done , Fibon.ConfigMonad.collectExtraStatsFrom , Fibon.ConfigMonad.noExtraStats , Fibon.ConfigMonad.useGhcDir , Fibon.ConfigMonad.useGhcInPlaceDir , Fibon.ConfigMonad.getEnv , Fibon.ConfigMonad.useRunScript , Fibon.Timeout.Timeout(..) , Fibon.ConfigMonad.FlagParameter(..) , Fibon.ConfigMonad.Configuration , Fibon.ConfigMonad.ConfigState(..) , Fibon.Benchmarks.FibonGroup(..) , Fibon.Benchmarks.FibonBenchmark(..) , Fibon.Benchmarks.allBenchmarks , Fibon.InputSize.InputSize(..) , RunConfig(..) , TuneSetting(..) , TuneSelection(..) , BenchmarkRunSelection(..) , BenchmarkConfigSelection(..) , ConfigBuilder , ConfigId , mkConfig ) where import Fibon.Benchmarks import Fibon.BenchmarkInstance import Fibon.InputSize import Fibon.ConfigMonad import Fibon.Timeout data RunConfig = RunConfig { configId :: ConfigId , sizeList :: [InputSize] , tuneList :: [TuneSetting] , runList :: [BenchmarkRunSelection] , iterations :: Int , configBuilder :: ConfigBuilder } type ConfigId = String type ConfigBuilder = TuneSelection -> BenchmarkConfigSelection -> ConfigMonad data TuneSetting = Base | Peak deriving(Eq, Read, Show, Ord, Enum) data TuneSelection = ConfigTune TuneSetting | ConfigTuneDefault deriving(Show, Eq, Ord) data BenchmarkRunSelection = RunGroup FibonGroup | RunSingle FibonBenchmark deriving(Show, Eq, Ord) data BenchmarkConfigSelection = ConfigBenchGroup FibonGroup | ConfigBench FibonBenchmark | ConfigBenchDefault deriving(Show, Eq, Ord) mkConfig :: RunConfig -> FibonBenchmark -> InputSize -> TuneSetting -> [(String, String)] -> Configuration mkConfig rc bm size tune env = runWithInitialFlags benchFlags env configM where configM = mapM_ (uncurry builder) [ (ConfigTuneDefault, ConfigBenchDefault) , (ConfigTune tune , ConfigBenchDefault) , (ConfigTuneDefault, ConfigBenchGroup group) , (ConfigTune tune , ConfigBenchGroup group) , (ConfigTuneDefault, ConfigBench bm) , (ConfigTune tune , ConfigBench bm) ] builder = configBuilder rc group = benchGroup bm benchFlags = flagConfig $ benchInstance bm size
dmpots/fibon
tools/fibon-run/Fibon/Run/Config.hs
bsd-3-clause
2,420
0
11
525
579
349
230
74
1
{-# LANGUAGE Safe, TypeFamilies #-} module Data.Logic.Pair ( Pair, -- *Construction pair, pair', -- *Deconstruction left, right, -- *Utilities swap ) where import Control.Monad.Predicate import Data.Logic.Atom import Data.Logic.Term import Data.Logic.Var import Control.Applicative ((<$>), (<*>)) -- |A pair of terms. data Pair a b s = Pair (Var a s) (Var b s) instance (Term a, Term b) => Term (Pair a b) where type Collapse (Pair a b) = (Collapse a, Collapse b) collapse (Pair x y) = (,) <$> collapse x <*> collapse y unify (Pair x y) (Pair x' y') = do unify x x' unify y y' occurs v (Pair x y) = (||) <$> occurs v x <*> occurs v y -- |Constructs a pair of terms. pair :: (Term a, Term b) => Var a s -> Var b s -> Var (Pair a b) s pair x y = bind (Pair x y) -- |Constructs a pair of atoms. pair' :: (Eq a, Eq b) => a -> b -> Var (Pair (Atom a) (Atom b)) s pair' x y = pair (atom x) (atom y) -- |@left x p@ instantiates its arguments such that @p@ is @(x, _)@. left :: (Term a, Term b) => Var a s -> Var (Pair a b) s -> Predicate s () left x p = do y <- auto p `is` pair x y -- |@right x p@ instantiates its arguments such that @p@ is @(_, x)@. right :: (Term a, Term b) => Var b s -> Var (Pair a b) s -> Predicate s () right y p = do x <- auto p `is` pair x y -- |@swap p q@ instantiates its arguments such that @p@ is @(x, y)@, and @q@ is @(y, x)@. swap :: (Term a, Term b) => Var (Pair a b) s -> Var (Pair b a) s -> Predicate s () swap x y = do (l, r) <- auto2 x `is` pair l r y `is` pair r l
YellPika/tlogic
src/Data/Logic/Pair.hs
bsd-3-clause
1,601
0
12
437
713
371
342
36
1
{-# LANGUAGE GADTs, DisambiguateRecordFields #-} {-# OPTIONS_GHC -fno-warn-warnings-deprecations #-} module CmmProcPoint ( ProcPointSet, Status(..) , callProcPoints, minimalProcPointSet , splitAtProcPoints, procPointAnalysis , attachContInfoTables ) where import Prelude hiding (last, unzip, succ, zip) import BlockId import CLabel import Cmm import PprCmm () import CmmUtils import CmmInfo import Data.List (sortBy) import Maybes import Control.Monad import Outputable import Platform import UniqSupply import Hoopl import qualified Data.Map as Map -- Compute a minimal set of proc points for a control-flow graph. -- Determine a protocol for each proc point (which live variables will -- be passed as arguments and which will be on the stack). {- A proc point is a basic block that, after CPS transformation, will start a new function. The entry block of the original function is a proc point, as is the continuation of each function call. A third kind of proc point arises if we want to avoid copying code. Suppose we have code like the following: f() { if (...) { ..1..; call foo(); ..2..} else { ..3..; call bar(); ..4..} x = y + z; return x; } The statement 'x = y + z' can be reached from two different proc points: the continuations of foo() and bar(). We would prefer not to put a copy in each continuation; instead we would like 'x = y + z' to be the start of a new procedure to which the continuations can jump: f_cps () { if (...) { ..1..; push k_foo; jump foo_cps(); } else { ..3..; push k_bar; jump bar_cps(); } } k_foo() { ..2..; jump k_join(y, z); } k_bar() { ..4..; jump k_join(y, z); } k_join(y, z) { x = y + z; return x; } You might think then that a criterion to make a node a proc point is that it is directly reached by two distinct proc points. (Note [Direct reachability].) But this criterion is a bit too simple; for example, 'return x' is also reached by two proc points, yet there is no point in pulling it out of k_join. A good criterion would be to say that a node should be made a proc point if it is reached by a set of proc points that is different than its immediate dominator. NR believes this criterion can be shown to produce a minimum set of proc points, and given a dominator tree, the proc points can be chosen in time linear in the number of blocks. Lacking a dominator analysis, however, we turn instead to an iterative solution, starting with no proc points and adding them according to these rules: 1. The entry block is a proc point. 2. The continuation of a call is a proc point. 3. A node is a proc point if it is directly reached by more proc points than one of its predecessors. Because we don't understand the problem very well, we apply rule 3 at most once per iteration, then recompute the reachability information. (See Note [No simple dataflow].) The choice of the new proc point is arbitrary, and I don't know if the choice affects the final solution, so I don't know if the number of proc points chosen is the minimum---but the set will be minimal. -} type ProcPointSet = BlockSet data Status = ReachedBy ProcPointSet -- set of proc points that directly reach the block | ProcPoint -- this block is itself a proc point instance Outputable Status where ppr (ReachedBy ps) | setNull ps = text "<not-reached>" | otherwise = text "reached by" <+> (hsep $ punctuate comma $ map ppr $ setElems ps) ppr ProcPoint = text "<procpt>" -------------------------------------------------- -- Proc point analysis procPointAnalysis :: ProcPointSet -> CmmGraph -> UniqSM (BlockEnv Status) -- Once you know what the proc-points are, figure out -- what proc-points each block is reachable from procPointAnalysis procPoints g = -- pprTrace "procPointAnalysis" (ppr procPoints) $ dataflowAnalFwdBlocks g initProcPoints $ analFwd lattice forward where initProcPoints = [(id, ProcPoint) | id <- setElems procPoints] -- transfer equations forward :: FwdTransfer CmmNode Status forward = mkFTransfer3 first middle last where first :: CmmNode C O -> Status -> Status first (CmmEntry id) ProcPoint = ReachedBy $ setSingleton id first _ x = x middle _ x = x last :: CmmNode O C -> Status -> FactBase Status last l x = mkFactBase lattice $ map (\id -> (id, x)) (successors l) lattice :: DataflowLattice Status lattice = DataflowLattice "direct proc-point reachability" unreached add_to where unreached = ReachedBy setEmpty add_to _ (OldFact ProcPoint) _ = (NoChange, ProcPoint) add_to _ _ (NewFact ProcPoint) = (SomeChange, ProcPoint) -- because of previous case add_to _ (OldFact (ReachedBy p)) (NewFact (ReachedBy p')) | setSize union > setSize p = (SomeChange, ReachedBy union) | otherwise = (NoChange, ReachedBy p) where union = setUnion p' p ---------------------------------------------------------------------- -- It is worth distinguishing two sets of proc points: those that are -- induced by calls in the original graph and those that are -- introduced because they're reachable from multiple proc points. -- -- Extract the set of Continuation BlockIds, see Note [Continuation BlockIds]. callProcPoints :: CmmGraph -> ProcPointSet callProcPoints g = foldGraphBlocks add (setSingleton (g_entry g)) g where add :: CmmBlock -> BlockSet -> BlockSet add b set = case lastNode b of CmmCall {cml_cont = Just k} -> setInsert k set CmmForeignCall {succ=k} -> setInsert k set _ -> set minimalProcPointSet :: Platform -> ProcPointSet -> CmmGraph -> UniqSM ProcPointSet -- Given the set of successors of calls (which must be proc-points) -- figure out the minimal set of necessary proc-points minimalProcPointSet platform callProcPoints g = extendPPSet platform g (postorderDfs g) callProcPoints extendPPSet :: Platform -> CmmGraph -> [CmmBlock] -> ProcPointSet -> UniqSM ProcPointSet extendPPSet platform g blocks procPoints = do env <- procPointAnalysis procPoints g -- pprTrace "extensPPSet" (ppr env) $ return () let add block pps = let id = entryLabel block in case mapLookup id env of Just ProcPoint -> setInsert id pps _ -> pps procPoints' = foldGraphBlocks add setEmpty g newPoints = mapMaybe ppSuccessor blocks newPoint = listToMaybe newPoints ppSuccessor b = let nreached id = case mapLookup id env `orElse` pprPanic "no ppt" (ppr id <+> ppr b) of ProcPoint -> 1 ReachedBy ps -> setSize ps block_procpoints = nreached (entryLabel b) -- | Looking for a successor of b that is reached by -- more proc points than b and is not already a proc -- point. If found, it can become a proc point. newId succ_id = not (setMember succ_id procPoints') && nreached succ_id > block_procpoints in listToMaybe $ filter newId $ successors b {- case newPoints of [] -> return procPoints' pps -> extendPPSet g blocks (foldl extendBlockSet procPoints' pps) -} case newPoint of Just id -> if setMember id procPoints' then panic "added old proc pt" else extendPPSet platform g blocks (setInsert id procPoints') Nothing -> return procPoints' -- At this point, we have found a set of procpoints, each of which should be -- the entry point of a procedure. -- Now, we create the procedure for each proc point, -- which requires that we: -- 1. build a map from proc points to the blocks reachable from the proc point -- 2. turn each branch to a proc point into a jump -- 3. turn calls and returns into jumps -- 4. build info tables for the procedures -- and update the info table for -- the SRTs in the entry procedure as well. -- Input invariant: A block should only be reachable from a single ProcPoint. -- ToDo: use the _ret naming convention that the old code generator -- used. -- EZY splitAtProcPoints :: CLabel -> ProcPointSet-> ProcPointSet -> BlockEnv Status -> CmmDecl -> UniqSM [CmmDecl] splitAtProcPoints entry_label callPPs procPoints procMap (CmmProc (TopInfo {info_tbls = info_tbls}) top_l g@(CmmGraph {g_entry=entry})) = do -- Build a map from procpoints to the blocks they reach let addBlock b graphEnv = case mapLookup bid procMap of Just ProcPoint -> add graphEnv bid bid b Just (ReachedBy set) -> case setElems set of [] -> graphEnv [id] -> add graphEnv id bid b _ -> panic "Each block should be reachable from only one ProcPoint" Nothing -> graphEnv where bid = entryLabel b add graphEnv procId bid b = mapInsert procId graph' graphEnv where graph = mapLookup procId graphEnv `orElse` mapEmpty graph' = mapInsert bid b graph graphEnv <- return $ foldGraphBlocks addBlock emptyBlockMap g -- Build a map from proc point BlockId to pairs of: -- * Labels for their new procedures -- * Labels for the info tables of their new procedures (only if -- the proc point is a callPP) -- Due to common blockification, we may overestimate the set of procpoints. let add_label map pp = Map.insert pp lbls map where lbls | pp == entry = (entry_label, Just (toInfoLbl entry_label)) | otherwise = (blockLbl pp, guard (setMember pp callPPs) >> Just (infoTblLbl pp)) procLabels = foldl add_label Map.empty (filter (flip mapMember (toBlockMap g)) (setElems procPoints)) -- In each new graph, add blocks jumping off to the new procedures, -- and replace branches to procpoints with branches to the jump-off blocks let add_jump_block (env, bs) (pp, l) = do bid <- liftM mkBlockId getUniqueM let b = blockJoin (CmmEntry bid) emptyBlock jump jump = CmmCall (CmmLit (CmmLabel l)) Nothing [{-XXX-}] 0 0 0 -- XXX: No regs are live at the call return (mapInsert pp bid env, b : bs) add_jumps newGraphEnv (ppId, blockEnv) = do let needed_jumps = -- find which procpoints we currently branch to mapFold add_if_branch_to_pp [] blockEnv add_if_branch_to_pp :: CmmBlock -> [(BlockId, CLabel)] -> [(BlockId, CLabel)] add_if_branch_to_pp block rst = case lastNode block of CmmBranch id -> add_if_pp id rst CmmCondBranch _ ti fi -> add_if_pp ti (add_if_pp fi rst) CmmSwitch _ tbl -> foldr add_if_pp rst (catMaybes tbl) _ -> rst add_if_pp id rst = case Map.lookup id procLabels of Just (lbl, mb_info_lbl) -> (id, mb_info_lbl `orElse` lbl) : rst Nothing -> rst (jumpEnv, jumpBlocks) <- foldM add_jump_block (mapEmpty, []) needed_jumps -- update the entry block let b = expectJust "block in env" $ mapLookup ppId blockEnv blockEnv' = mapInsert ppId b blockEnv -- replace branches to procpoints with branches to jumps blockEnv'' = toBlockMap $ replaceBranches jumpEnv $ ofBlockMap ppId blockEnv' -- add the jump blocks to the graph blockEnv''' = foldl (flip insertBlock) blockEnv'' jumpBlocks let g' = ofBlockMap ppId blockEnv''' -- pprTrace "g' pre jumps" (ppr g') $ do return (mapInsert ppId g' newGraphEnv) graphEnv <- foldM add_jumps emptyBlockMap $ mapToList graphEnv let to_proc (bid, g) = case expectJust "pp label" $ Map.lookup bid procLabels of (lbl, Just info_lbl) | bid == entry -> CmmProc (TopInfo {info_tbls=info_tbls, stack_info=stack_info}) top_l (replacePPIds g) | otherwise -> CmmProc (TopInfo {info_tbls = mapSingleton (g_entry g) (mkEmptyContInfoTable info_lbl), stack_info=stack_info}) lbl (replacePPIds g) (lbl, Nothing) -> CmmProc (TopInfo {info_tbls = mapEmpty, stack_info=stack_info}) lbl (replacePPIds g) where stack_info = StackInfo 0 Nothing -- panic "No StackInfo" -- cannot use panic, this is printed by -ddump-cmmz -- References to procpoint IDs can now be replaced with the -- infotable's label replacePPIds g = {-# SCC "replacePPIds" #-} mapGraphNodes (id, mapExp repl, mapExp repl) g where repl e@(CmmLit (CmmBlock bid)) = case Map.lookup bid procLabels of Just (_, Just info_lbl) -> CmmLit (CmmLabel info_lbl) _ -> e repl e = e -- The C back end expects to see return continuations before the -- call sites. Here, we sort them in reverse order -- it gets -- reversed later. let (_, block_order) = foldl add_block_num (0::Int, emptyBlockMap) (postorderDfs g) add_block_num (i, map) block = (i+1, mapInsert (entryLabel block) i map) sort_fn (bid, _) (bid', _) = compare (expectJust "block_order" $ mapLookup bid block_order) (expectJust "block_order" $ mapLookup bid' block_order) procs <- return $ map to_proc $ sortBy sort_fn $ mapToList graphEnv return -- pprTrace "procLabels" (ppr procLabels) -- pprTrace "splitting graphs" (ppr procs) procs splitAtProcPoints _ _ _ _ t@(CmmData _ _) = return [t] -- Only called from CmmProcPoint.splitAtProcPoints. NB. does a -- recursive lookup, see comment below. replaceBranches :: BlockEnv BlockId -> CmmGraph -> CmmGraph replaceBranches env cmmg = {-# SCC "replaceBranches" #-} ofBlockMap (g_entry cmmg) $ mapMap f $ toBlockMap cmmg where f block = replaceLastNode block $ last (lastNode block) last :: CmmNode O C -> CmmNode O C last (CmmBranch id) = CmmBranch (lookup id) last (CmmCondBranch e ti fi) = CmmCondBranch e (lookup ti) (lookup fi) last (CmmSwitch e tbl) = CmmSwitch e (map (fmap lookup) tbl) last l@(CmmCall {}) = l last l@(CmmForeignCall {}) = l lookup id = fmap lookup (mapLookup id env) `orElse` id -- XXX: this is a recursive lookup, it follows chains -- until the lookup returns Nothing, at which point we -- return the last BlockId -- -------------------------------------------------------------- -- Not splitting proc points: add info tables for continuations attachContInfoTables :: ProcPointSet -> CmmDecl -> CmmDecl attachContInfoTables call_proc_points (CmmProc top_info top_l g) = CmmProc top_info{info_tbls = info_tbls'} top_l g where info_tbls' = mapUnion (info_tbls top_info) $ mapFromList [ (l, mkEmptyContInfoTable (infoTblLbl l)) | l <- setElems call_proc_points , l /= g_entry g ] attachContInfoTables _ other_decl = other_decl ---------------------------------------------------------------- {- Note [Direct reachability] Block B is directly reachable from proc point P iff control can flow from P to B without passing through an intervening proc point. -} ---------------------------------------------------------------- {- Note [No simple dataflow] Sadly, it seems impossible to compute the proc points using a single dataflow pass. One might attempt to use this simple lattice: data Location = Unknown | InProc BlockId -- node is in procedure headed by the named proc point | ProcPoint -- node is itself a proc point At a join, a node in two different blocks becomes a proc point. The difficulty is that the change of information during iterative computation may promote a node prematurely. Here's a program that illustrates the difficulty: f () { entry: .... L1: if (...) { ... } else { ... } L2: if (...) { g(); goto L1; } return x + y; } The only proc-point needed (besides the entry) is L1. But in an iterative analysis, consider what happens to L2. On the first pass through, it rises from Unknown to 'InProc entry', but when L1 is promoted to a proc point (because it's the successor of g()), L1's successors will be promoted to 'InProc L1'. The problem hits when the new fact 'InProc L1' flows into L2 which is already bound to 'InProc entry'. The join operation makes it a proc point when in fact it needn't be, because its immediate dominator L1 is already a proc point and there are no other proc points that directly reach L2. -} {- Note [Separate Adams optimization] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ It may be worthwhile to attempt the Adams optimization by rewriting the graph before the assignment of proc-point protocols. Here are a couple of rules: g() returns to k; g() returns to L; k: CopyIn c ress; goto L: ... ==> ... L: // no CopyIn node here L: CopyIn c ress; And when c == c' and ress == ress', this also: g() returns to k; g() returns to L; k: CopyIn c ress; goto L: ... ==> ... L: CopyIn c' ress' L: CopyIn c' ress' ; In both cases the goal is to eliminate k. -}
nomeata/ghc
compiler/cmm/CmmProcPoint.hs
bsd-3-clause
18,571
0
20
5,709
2,935
1,506
1,429
191
12
{-# LANGUAGE ExistentialQuantification #-} -- |Defines the network API required for a Tor implementation to run. module Tor.NetworkStack( TorNetworkStack(..) , SomeNetworkStack(..) , toBackend , recvAll , recvLine ) where import qualified Data.ByteString as S import qualified Data.ByteString.Lazy as L import Data.Word import Network.TLS import Tor.DataFormat.TorAddress -- |A network stack, but with the type variables hidden. data SomeNetworkStack = forall lsock sock . HasBackend sock => MkNS (TorNetworkStack lsock sock) -- |The type of a Tor-compatible network stack. The first type variable is the -- type of a listener socket, the second the type of a standard connection -- socket. data TorNetworkStack lsock sock = TorNetworkStack { connect :: String -> Word16 -> IO (Maybe sock) -- |Lookup the given hostname and return any IP6 (Left) or IP4 (Right) -- addresses associated with it. , getAddress :: String -> IO [TorAddress] , listen :: Word16 -> IO lsock , accept :: lsock -> IO (sock, TorAddress) , recv :: sock -> Int -> IO S.ByteString , write :: sock -> L.ByteString -> IO () , flush :: sock -> IO () , close :: sock -> IO () , lclose :: lsock -> IO () } -- |Receive a line of ASCII text from a socket. recvLine :: TorNetworkStack ls s -> s -> IO L.ByteString recvLine ns s = go [] where go acc = do next <- recv ns s 1 case S.uncons next of Nothing -> return (L.pack (reverse acc)) Just (10, _) -> return (L.pack (reverse acc)) Just (f, _) -> go (f:acc) -- |Receive all the input from the socket as a lazy ByteString; this may cause -- the system to block upon some ByteString operations to fetch more data. recvAll :: TorNetworkStack ls s -> s -> IO L.ByteString recvAll ns s = go [] where go acc = do next <- recv ns s 4096 if S.null next then return (L.fromChunks (reverse acc)) else go (next:acc) -- |Convert a Tor-compatible network stack to a TLS-compatible Backend -- structure. toBackend :: TorNetworkStack ls s -> s -> Backend toBackend ns s = Backend { backendFlush = flush ns s , backendClose = close ns s , backendRecv = recv ns s , backendSend = write ns s . L.fromStrict }
GaloisInc/haskell-tor
src/Tor/NetworkStack.hs
bsd-3-clause
2,487
0
16
758
613
330
283
45
3
-- |Standardizes the language specification of submitted tests. module CS173.NormalizeSubmissions ( standardizeLang ) where -- |Removes leading whitespace and PLT Scheme comments from the string. pltWs :: String -> String pltWs [] = [] pltWs (';':rest) = pltWs $ pltWsLine rest pltWs ('#':'|':rest) = pltWs $ pltWsBlock rest -- TODO: s-exp whitespace pltWs ('#':';':rest) = pltWs $ pltWsSexp rest pltWs (ch:rest) | ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n' = pltWs rest | otherwise = ch:rest pltWsLine ('\r':'\n':rest) = rest pltWsLine ('\n':rest) = rest pltWsLine ('\r':rest) = rest pltWsLine (_:rest) = pltWsLine rest pltWsLine [] = [] pltWsBlock ('|':'#':rest) = rest pltWsBlock ('#':'|':rest) = pltWsBlock $ pltWsBlock rest pltWsBlock (_:rest) = pltWsBlock rest pltWsBlock [] = [] -- this is a syntax error standardizeLang :: String -- ^'#lang' name -> String -- ^submission text -> String -- ^submission in the given '#lang' standardizeLang langName submission = let sub = pltWs submission in case sub of '#':'l':'a':'n':'g':_ -> submission '#':'r':'e':'a':'d':'e':'r':_ -> submission otherwise -> "#lang " ++ langName ++ "\n" ++ submission
jesboat/173tourney
server-src/CS173/NormalizeSubmissions.hs
bsd-3-clause
1,224
0
16
248
421
216
205
27
3
{-# OPTIONS_GHC -fno-warn-incomplete-patterns #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE ScopedTypeVariables #-} {-| Module : Numeric.AERN.IVP.Examples.Hybrid.Simple Description : simple examples of hybrid system IVPs Copyright : (c) Michal Konecny License : BSD3 Maintainer : mikkonecny@gmail.com Stability : experimental Portability : portable Simple examples of hybrid system IVPs. -} module Numeric.AERN.IVP.Examples.Hybrid.Simple where import Numeric.AERN.IVP.Specification.Hybrid import Numeric.AERN.RmToRn.Domain import Numeric.AERN.RmToRn.New import Numeric.AERN.RmToRn.Evaluation import qualified Numeric.AERN.RealArithmetic.RefinementOrderRounding as ArithInOut import Numeric.AERN.RealArithmetic.RefinementOrderRounding (dblToReal) import Numeric.AERN.RealArithmetic.RefinementOrderRounding.Operators --import qualified Numeric.AERN.RealArithmetic.NumericOrderRounding as ArithUpDn import Numeric.AERN.RealArithmetic.ExactOps import qualified Numeric.AERN.RefinementOrder as RefOrd import Numeric.AERN.RefinementOrder.Operators import qualified Numeric.AERN.NumericOrder as NumOrd import Numeric.AERN.NumericOrder.Operators import Numeric.AERN.Basics.Consistency import qualified Data.Map as Map import Debug.Trace _ = trace -- stop the unused warning ivpByNameMap :: (Var f ~ String, HasConstFns f, CanEvaluate f, RefOrd.RoundedLattice f, Neg f, ArithInOut.RoundedAbs f, ArithInOut.RoundedSubtr f, ArithInOut.RoundedMultiply f, ArithInOut.RoundedPowerToNonnegInt f, ArithInOut.RoundedDivide f, ArithInOut.RoundedMixedAdd f Double, ArithInOut.RoundedMixedMultiply f Double, ArithInOut.RoundedMixedDivide f Double, ArithInOut.RoundedReal (Domain f), HasConsistency (Domain f), RefOrd.IntervalLike (Domain f), ArithInOut.RoundedSquareRoot (Domain f), Show f, Show (Domain f) ) => f -> Map.Map String (HybridIVP f) ivpByNameMap sampleFn = Map.fromList [ -- ("expDec-resetOnce", ivpExpDecay_resetTHalf sampleFn), -- ("expDec-resetOn34", ivpExpDecay_resetOn34 sampleFn), -- ("springMass-resetOnce", ivpSpringMass_resetTHalf sampleFn), -- ("springMass-resetOn34", ivpSpringMass_resetOn34 sampleFn), ("pendulumDampened", ivpDampenedPendulum sampleFn), ("bouncingBall", ivpBouncingBall sampleFn), ("bouncingBallEnergy", ivpBouncingBallEnergy sampleFn), ("bouncingBallFloorRise", ivpBouncingBallFloorRise sampleFn), ("bouncingBallFloorRiseEnergy", ivpBouncingBallFloorRiseEnergy sampleFn), ("bouncingBallFloorDropEnergy", ivpBouncingBallFloorDropEnergy sampleFn), ("bouncingBallRiseFall", ivpBouncingBallRiseFall sampleFn), ("bouncingBallEnergyRiseFall", ivpBouncingBallRiseFallEnergy sampleFn), ("bouncingBallDrag", ivpBouncingBallDrag sampleFn), ("bouncingBallDragEnergy", ivpBouncingBallDragEnergy sampleFn), ("bouncingBallDragPosNeg", ivpBouncingBallDragPosNeg sampleFn), ("bouncingBallDragPosNegEnergy", ivpBouncingBallDragPosNegEnergy sampleFn), ("bouncingBallDragNewtonianGravityEnergy", ivpBouncingBallDragNewtonianGravityEnergy sampleFn), ("bouncingBallDragPosNegNewtonianGravityEnergy", ivpBouncingBallDragPosNegNewtonGravityEnergy sampleFn), ("bouncingBallNewtonianGravityEnergy", ivpBouncingBallNewtonianGravityEnergy sampleFn), ("bouncingBallCubicDrag", ivpBouncingBallCubicDrag sampleFn), ("bouncingBallCubicDragEnergy", ivpBouncingBallCubicDragEnergy sampleFn), ("bouncingBallCircle", ivpBouncingBallCircle sampleFn), ("2BeadColumnEnergy", ivp2BeadColumnEnergy sampleFn), ("2BeadColumnEnergyVDiff", ivp2BeadColumnEnergyVDiff sampleFn), -- , -- ("bouncingBallVibr-graze", ivpBouncingBallVibr_AtTime 2 sampleFn), -- -- TODO: define "bouncingBallVibrEnergy-graze" -- ("bouncingBallDrop", ivpBouncingBallDrop_AtTime 3 2 0 5 sampleFn), -- ("bouncingBallEnergyDrop", ivpBouncingBallEnergyDrop_AtTime 3 2 0 5 sampleFn), -- ("twoBouncingBallsDrop", ivpTwoBouncingBallsDrop_AtTime 30 20 25 10 45 sampleFn), -- ("twoBouncingBallsEnergyDrop", ivpTwoBouncingBallsEnergyDrop_AtTime 30 20 25 10 45 sampleFn), -- -- TODO: fix breakage at time 20 -- ("bouncingSpring-4", ivpBouncingSpring_AtTime 4 sampleFn), ("twoTanks", ivpTwoTanks 0 sampleFn), ("twoTanksR", ivpTwoTanks 0.5 sampleFn), ("twoTanksSum", ivpTwoTanksSum 0 sampleFn), ("twoTanksSumR", ivpTwoTanksSum 0.5 sampleFn) ] ivpByName :: (Var f ~ String, HasConstFns f, CanEvaluate f, RefOrd.RoundedLattice f, Neg f, ArithInOut.RoundedAbs f, ArithInOut.RoundedSubtr f, ArithInOut.RoundedMultiply f, ArithInOut.RoundedPowerToNonnegInt f, ArithInOut.RoundedDivide f, ArithInOut.RoundedMixedAdd f Double, ArithInOut.RoundedMixedMultiply f Double, ArithInOut.RoundedMixedDivide f Double, ArithInOut.RoundedReal (Domain f), HasConsistency (Domain f), RefOrd.IntervalLike (Domain f), ArithInOut.RoundedSquareRoot (Domain f), Show f, Show (Domain f) ) => String {-^ IVP name - see source code for the list -} -> Double {-^ end time -} -> f {-^ sample function of the type to be used in simulation -} -> Maybe (HybridIVP f) ivpByName name endTimeDbl sampleFn = do ivp <- Map.lookup name $ ivpByNameMap sampleFn return $ ivp { hybivp_tEnd = z <+>| endTimeDbl } where z = zero sampleDom sampleDom = getSampleDomValue sampleFn ivpByNameReportError :: (Var f ~ String, HasConstFns f, CanEvaluate f, RefOrd.RoundedLattice f, Neg f, ArithInOut.RoundedAbs f, ArithInOut.RoundedSubtr f, ArithInOut.RoundedMultiply f, ArithInOut.RoundedPowerToNonnegInt f, ArithInOut.RoundedDivide f, ArithInOut.RoundedMixedAdd f Double, ArithInOut.RoundedMixedMultiply f Double, ArithInOut.RoundedMixedDivide f Double, ArithInOut.RoundedReal (Domain f), HasConsistency (Domain f), RefOrd.IntervalLike (Domain f), ArithInOut.RoundedSquareRoot (Domain f), Show f, Show (Domain f) ) => String -> Double -> f -> HybridIVP f ivpByNameReportError ivpName endTimeDbl samplePoly = case ivpByName ivpName endTimeDbl samplePoly of Just ivp -> ivp _ -> error $ "unknown ivp: " ++ ivpName ++ "\n known ivps:\n" ++ unlines (map (" " ++) (ivpNames samplePoly)) ivpNames :: (Var f ~ String, HasConstFns f, CanEvaluate f, RefOrd.RoundedLattice f, Neg f, ArithInOut.RoundedAbs f, ArithInOut.RoundedSubtr f, ArithInOut.RoundedMultiply f, ArithInOut.RoundedPowerToNonnegInt f, ArithInOut.RoundedDivide f, ArithInOut.RoundedMixedAdd f Double, ArithInOut.RoundedMixedMultiply f Double, ArithInOut.RoundedMixedDivide f Double, ArithInOut.RoundedReal (Domain f), HasConsistency (Domain f), RefOrd.IntervalLike (Domain f), ArithInOut.RoundedSquareRoot (Domain f), Show f, Show (Domain f) ) => f -> [String] ivpNames sampleFn = Map.keys $ ivpByNameMap sampleFn --ivpExpDecay_resetTHalf :: -- (Var f ~ String, -- HasConstFns f, -- Neg f, -- ArithInOut.RoundedSubtr f, -- ArithInOut.RoundedReal (Domain f), -- Show (Domain f) -- ) -- => -- f -> HybridIVP f --ivpExpDecay_resetTHalf (sampleFn :: f) = -- ivp -- where ---- system :: HybridSystem f -- system = -- HybridSystem -- { -- hybsys_componentNames = ["x","time"], -- hybsys_modeFields = Map.fromList [(modeBefore, odeBefore), (modeAfter, odeAfter)], -- hybsys_modeInvariants = Map.fromList [(modeBefore, id), (modeAfter, id)], -- hybsys_eventModeSwitchesAndResetFunctions = -- Map.fromList [(eventReset, (modeAfter, resetReset))], -- hybsys_eventSpecification = eventSpecMap -- } -- modeBefore = HybSysMode "before" -- modeAfter = HybSysMode "after" -- odeBefore, odeAfter :: [f] -> [f] -- odeBefore [x,time] = [neg x, newConstFnFromSample time (toD 1)] -- odeAfter = odeBefore -- eventReset = HybSysEventKind "reset" -- resetReset :: [f] -> [f] -- resetReset [x,time] = [newConstFnFromSample x initValue, time] -- eventSpecMap (HybSysMode "after") = Map.empty -- reset only once! -- eventSpecMap _ = -- Map.singleton eventReset $ -- ([True,True], timeDip, const (Just True), timeReset) -- where -- timeDip [_, t] = tEventP <-> t -- where -- tEventP = newConstFnFromSample t $ (one sampleDom) <*>| tEventDbl -- timeReset [x,t] = [x,zP] -- where -- zP = zero t -- tEventDbl = 0.5 :: Double -- tEvent = (zero sampleDom) <+>| tEventDbl -- -- ivp :: HybridIVP f -- ivp = -- HybridIVP -- { -- hybivp_description = description, -- hybivp_system = system, -- hybivp_tVar = "t", -- hybivp_tStart = toD 0, -- hybivp_tEnd = toD 1, -- hybivp_initialStateEnclosure = -- Map.singleton modeBefore [initValue, tStart], -- hybivp_maybeExactStateAtTEnd = Just $ -- Map.singleton modeAfter [xEnd, tEnd <-> tEvent] -- } -- description = -- "v = -x; if t = " ++ show tEventDbl ++ " then x := " ++ show initValue -- ++ "; x(" ++ show tStart ++ ") = " ++ show initValue -- initValue = (one sampleDom) :: Domain f -- tStart = hybivp_tStart ivp -- tEnd = hybivp_tEnd ivp -- xEnd = (one sampleDom) <*>| (exp (-tEndDbl+tEventDbl) :: Double) -- tEndDbl :: Double -- (Just tEndDbl) = ArithUpDn.convertUpEff (ArithUpDn.convertDefaultEffort tEnd (0::Double)) 0 tEnd -- toD = dblToReal sampleDom -- sampleDom = getSampleDomValue sampleFn -- --ivpExpDecay_resetOn34 :: -- (Var f ~ String, -- HasConstFns f, -- Neg f, -- ArithInOut.RoundedSubtr f, -- ArithInOut.RoundedReal (Domain f), -- Show (Domain f) -- ) -- => -- f -> HybridIVP f --ivpExpDecay_resetOn34 (sampleFn :: f) = -- ivp -- where -- system = -- HybridSystem -- { -- hybsys_componentNames = ["x"], -- hybsys_modeFields = Map.fromList [(modeNormal, odeNormal)], -- hybsys_modeInvariants = Map.fromList [(modeNormal, id)], -- hybsys_eventModeSwitchesAndResetFunctions = -- Map.fromList [(eventReset, (modeNormal, resetReset))], -- hybsys_eventSpecification = eventSpecMap -- } -- modeNormal = HybSysMode "normal" -- odeNormal :: [f] -> [f] -- odeNormal [x] = [neg x] -- eventReset = HybSysEventKind "reset" -- resetReset :: [f] -> [f] -- resetReset [x] = [newConstFnFromSample x initValue] -- eventSpecMap _mode = -- Map.singleton eventReset $ -- ([True], xDip, const (Just True), id) -- where -- xDip [x] = x <-> xEventFn -- where -- xEventFn = newConstFnFromSample x $ (toD 1) <*>| xEventDbl -- -- xEventDbl = 0.75 :: Double -- -- ivp :: HybridIVP f -- ivp = -- HybridIVP -- { -- hybivp_description = description, -- hybivp_system = system, -- hybivp_tVar = "t", -- hybivp_tStart = toD 0, -- hybivp_tEnd = toD 1, -- hybivp_initialStateEnclosure = -- Map.singleton modeNormal [initValue], -- hybivp_maybeExactStateAtTEnd = Just $ -- Map.singleton modeNormal [xEnd] -- } -- description = -- "v = -x; if x <= " ++ show xEventDbl ++ " then x := " ++ show initValue -- ++ "; x(" ++ show tStart ++ ") = " ++ show initValue -- initValue = (toD 1) :: Domain f -- tStart = hybivp_tStart ivp -- tEnd = hybivp_tEnd ivp ---- tVar = hybivp_tVar ivp -- xEnd = (toD 1) <*>| (exp (-tEndDbl-3*(log xEventDbl)) :: Double) -- tEndDbl :: Double -- (Just tEndDbl) = ArithUpDn.convertUpEff (ArithUpDn.convertDefaultEffort tEnd (0::Double)) 0 tEnd -- toD = dblToReal sampleDom -- sampleDom = getSampleDomValue sampleFn -- -- --ivpSpringMass_resetTHalf :: -- (Var f ~ String, -- HasConstFns f, -- Neg f, -- ArithInOut.RoundedSubtr f, -- ArithInOut.RoundedReal (Domain f), -- Show (Domain f) -- ) -- => -- f -> HybridIVP f --ivpSpringMass_resetTHalf (sampleFn :: f) = -- ivp -- where -- system = -- HybridSystem -- { -- hybsys_componentNames = ["x","v","time"], -- hybsys_modeFields = Map.fromList [(modeBefore, odeBefore), (modeAfter, odeAfter)], -- hybsys_modeInvariants = Map.fromList [(modeBefore, id), (modeAfter, id)], -- hybsys_eventModeSwitchesAndResetFunctions = -- Map.fromList [(eventReset, (modeAfter, resetReset))], -- hybsys_eventSpecification = eventSpecMap -- } -- modeBefore = HybSysMode "before" -- modeAfter = HybSysMode "after" -- odeBefore, odeAfter :: [f] -> [f] -- odeBefore [x,v,time] = [v, neg x, newConstFnFromSample time (toD 1)] -- odeAfter = odeBefore -- eventReset = HybSysEventKind "reset" -- resetReset :: [f] -> [f] -- resetReset [x,_v,time] = map (newConstFnFromSample x) initValues ++ [time] -- eventSpecMap (HybSysMode "after") = Map.empty -- reset only once! -- eventSpecMap _ = -- Map.singleton eventReset $ -- ([True,True,True], timeDip, const (Just True), timeReset) -- where -- timeDip [_, _, t] = tEventP <-> t -- where -- tEventP = newConstFnFromSample t $ (toD 1) <*>| tEventDbl -- timeReset [x,v,t] = [x,v,zP] -- where -- zP = zero t -- tEventDbl = 0.5 :: Double -- tEvent = ((zero sampleDom) :: Domain f) <+>| tEventDbl -- -- ivp :: HybridIVP f -- ivp = -- HybridIVP -- { -- hybivp_description = description, -- hybivp_system = system, -- hybivp_tVar = "t", -- hybivp_tStart = toD 0, -- hybivp_tEnd = toD 1, -- hybivp_initialStateEnclosure = -- Map.singleton modeBefore (initValues ++ [tStart]), -- hybivp_maybeExactStateAtTEnd = Just $ -- Map.singleton modeAfter [xEnd, xDerEnd, tEnd <-> tEvent] -- } -- description = -- "x'' = -x; if t = " ++ show tEventDbl ++ " then [x,v] := " ++ show initValues -- ++ "; x(" ++ show tStart ++ ") = " ++ show initX -- ++ ", v(" ++ show tStart ++ ") = " ++ show initX' -- initValues@[initX, initX'] = [toD 1,toD 0] :: [Domain f] -- tStart = hybivp_tStart ivp -- tEnd = hybivp_tEnd ivp -- xEnd = (toD 1) <*>| (cos (tEndDbl - tEventDbl) :: Double) -- xDerEnd = (toD $ -1) <*>| (sin (tEndDbl - tEventDbl) :: Double) -- tEndDbl :: Double -- (Just tEndDbl) = ArithUpDn.convertUpEff (ArithUpDn.convertDefaultEffort tEnd (0::Double)) 0 tEnd -- toD = dblToReal sampleDom -- sampleDom = getSampleDomValue sampleFn -- -- --ivpSpringMass_resetOn34 :: -- (Var f ~ String, -- HasConstFns f, -- Neg f, -- ArithInOut.RoundedSubtr f, -- ArithInOut.RoundedReal (Domain f), -- Show (Domain f) -- ) -- => -- f -> HybridIVP f --ivpSpringMass_resetOn34 (sampleFn :: f) = -- ivp -- where -- system = -- HybridSystem -- { -- hybsys_componentNames = ["x","v"], -- hybsys_modeFields = Map.fromList [(modeNormal, odeNormal)], -- hybsys_modeInvariants = Map.fromList [(modeNormal, id)], -- hybsys_eventModeSwitchesAndResetFunctions = -- Map.fromList [(eventReset, (modeNormal, resetReset))], -- hybsys_eventSpecification = eventSpecMap -- } -- modeNormal = HybSysMode "normal" -- odeNormal :: [f] -> [f] -- odeNormal [x,v] = [v, neg x] -- eventReset = HybSysEventKind "reset" -- resetReset :: [f] -> [f] -- resetReset [x,_v] = map (newConstFnFromSample x) initValues -- eventSpecMap _mode = -- Map.singleton eventReset $ -- ([True, True], xDip, const (Just True), id) -- where -- xDip [x,_v] = x <-> xEventFn -- where -- xEventFn = newConstFnFromSample x $ (toD 1) <*>| xEventDbl -- xEventDbl = 0.75 :: Double -- tEventDbl = acos xEventDbl -- 0.72273424781341... -- -- ivp :: HybridIVP f -- ivp = -- HybridIVP -- { -- hybivp_description = description, -- hybivp_system = system, -- hybivp_tVar = "t", -- hybivp_tStart = toD 0, -- hybivp_tEnd = toD 1, -- hybivp_initialStateEnclosure = -- Map.singleton modeNormal (initValues ++ [tStart]), -- hybivp_maybeExactStateAtTEnd = Just $ -- Map.singleton modeNormal [xEnd, xDerEnd, tEnd] -- } -- description = -- "x'' = -x; if x <= " ++ show xEventDbl ++ " then [x,v] := " ++ show initValues -- ++ "; x(" ++ show tStart ++ ") = " ++ show initX -- ++ ", v(" ++ show tStart ++ ") = " ++ show initX' -- initValues@[initX, initX'] = [one sampleDom,zero sampleDom] :: [Domain f] -- tStart = hybivp_tStart ivp -- tEnd = hybivp_tEnd ivp ---- tVar = hybivp_tVar ivp -- xEnd = (one sampleDom) <*>| (cos (tEndDbl - tEventDbl) :: Double) -- xDerEnd = (toD $ -1) <*>| (sin (tEndDbl - tEventDbl) :: Double) -- tEndDbl :: Double -- (Just tEndDbl) = ArithUpDn.convertUpEff (ArithUpDn.convertDefaultEffort tEnd (0::Double)) 0 tEnd -- toD = dblToReal sampleDom -- sampleDom = getSampleDomValue sampleFn ivpDampenedPendulum :: (Var f ~ String, HasConstFns f, Neg f, ArithInOut.RoundedSubtr f, ArithInOut.RoundedMixedMultiply f Double, ArithInOut.RoundedReal (Domain f), HasConsistency (Domain f), RefOrd.IntervalLike (Domain f), Show (Domain f) ) => f -> HybridIVP f ivpDampenedPendulum (sampleFn :: f) = ivp where system = HybridSystem { hybsys_componentNames = ["x","v"], hybsys_modeFields = Map.fromList [(modeMove, odeMove)], hybsys_modeInvariants = Map.fromList [(modeMove, invariantMove)], hybsys_eventSpecification = eventSpecMap } modeMove = HybSysMode "move" odeMove :: [f] -> [f] odeMove [x,v] = [v, ((-0.5 :: Double) |<*> v) <-> x] -- invariantMove = id invariantMove [x,v] = Just [x,v] eventSpecMap _mode = Map.empty ivp :: HybridIVP f ivp = HybridIVP { hybivp_description = description, hybivp_system = system, hybivp_tVar = "t", hybivp_tStart = toD 0, hybivp_tEnd = toD 1, hybivp_initialStateEnclosure = Map.singleton modeMove initValues, hybivp_maybeExactStateAtTEnd = Nothing } description = "x''=-1.5x'-x" ++ "; x(" ++ show tStart ++ ") = " ++ show initX ++ ", v(" ++ show tStart ++ ") = " ++ show initV initValues@[initX, initV] = [toD 1, toD 0] :: [Domain f] tStart = hybivp_tStart ivp -- z = toD 0 toD = dblToReal sampleDom sampleDom = getSampleDomValue sampleFn ivpBouncingBall :: (Var f ~ String, HasConstFns f, Neg f, ArithInOut.RoundedSubtr f, ArithInOut.RoundedMixedMultiply f Double, ArithInOut.RoundedReal (Domain f), HasConsistency (Domain f), RefOrd.IntervalLike (Domain f), Show (Domain f) ) => f -> HybridIVP f ivpBouncingBall (sampleFn :: f) = ivp where system = HybridSystem { hybsys_componentNames = ["x","v"], hybsys_modeFields = Map.fromList [(modeMove, odeMove)], hybsys_modeInvariants = Map.fromList [(modeMove, invariantMove)], hybsys_eventSpecification = eventSpecMap } modeMove = HybSysMode "move" odeMove :: [f] -> [f] odeMove [x,v] = [v, newConstFnFromSample x (toD $ -10)] -- invariantMove = id invariantMove [x,v] = do xNN <- makeNonneg x return [xNN,v] eventSpecMap _mode = Map.singleton eventBounce $ (modeMove, resetBounce, [True, True], pruneBounce) eventBounce = HybSysEventKind "bounce" pruneBounce _ [x,v] = do vNP <- makeNonpos v _ <- isect z x return [z, vNP] where -- z = toD 0 resetBounce [x,v] = [x, (-0.5 :: Double) |<*> v] -- [newConstFnFromSample v 0, (0 :: Double) |<*> v] ivp :: HybridIVP f ivp = HybridIVP { hybivp_description = description, hybivp_system = system, hybivp_tVar = "t", hybivp_tStart = toD 0, hybivp_tEnd = toD 1, hybivp_initialStateEnclosure = Map.singleton modeMove initValues, hybivp_maybeExactStateAtTEnd = Nothing } description = "BB" -- "if x = 0 && v <= 0 then post(v) = -0.5*pre(v) else x'' = -10" ++ "; x(" ++ show tStart ++ ") = " ++ show initX ++ ", v(" ++ show tStart ++ ") = " ++ show initX' initValues@[initX, initX'] = [toD 5, toD 0] :: [Domain f] tStart = hybivp_tStart ivp z = toD 0 toD = dblToReal sampleDom sampleDom = getSampleDomValue sampleFn ivpBouncingBallEnergy :: (Var f ~ String, HasConstFns f, Neg f, ArithInOut.RoundedSubtr f, ArithInOut.RoundedMixedMultiply f Double, ArithInOut.RoundedReal (Domain f), RefOrd.IntervalLike (Domain f), HasConsistency (Domain f), ArithInOut.RoundedSquareRoot (Domain f), Show (Domain f) ) => f -> HybridIVP f ivpBouncingBallEnergy (sampleFn :: f) = ivp where energyWith x v = -- z </\> (v <*> v <+> (toD 20) <*> x) -- added zero so that after reset the interval refines the original (model-level hack!) system = HybridSystem { hybsys_componentNames = ["x","v","r"], hybsys_modeFields = Map.fromList [(modeMove, odeMove)], hybsys_modeInvariants = Map.fromList [(modeMove, invariantMove)], hybsys_eventSpecification = eventSpecMap } modeMove = HybSysMode "move" odeMove :: [f] -> [f] odeMove [x,v,r] = [v, newConstFnFromSample x (toD $ -10), newConstFnFromSample r (toD 0)] invariantMove [x,v,r] = do -- x >= 0: xNN <- makeNonneg x -- r >= 0: rNN <- makeNonneg r -- |v| = sqrt(r - 2gx): vSqr1 <- makeNonneg $ rNN <-> ((toD 20) <*> xNN) let absV = ArithInOut.sqrtOut vSqr1 vNew <- isect v ((neg absV) </\> absV) -- x = (r - (v)^2) / 2g: vSqr2 <- makeNonneg $ v <*> v let x2 = (rNN <-> vSqr2) </> (toD 20) xNew <- isect xNN x2 return [xNew, vNew, rNN] eventBounce = HybSysEventKind "bc" pruneBounce _ [x,v,r] = do _ <- isect z x vNP <- makeNonpos v return $ [z,vNP,r] resetBounce [x,v,r] = [x, (-0.5 :: Double) |<*> v, (toDInterval 0 0.25) <*> r ] -- deliberately lose precision to facilitate quicker event tree convergence (HACK!) eventSpecMap _mode = Map.singleton eventBounce $ (modeMove, resetBounce, [True, True, True], pruneBounce) ivp :: HybridIVP f ivp = HybridIVP { hybivp_description = description, hybivp_system = system, hybivp_tVar = "t", hybivp_tStart = z, hybivp_tEnd = z, hybivp_initialStateEnclosure = Map.singleton modeMove initValues, hybivp_maybeExactStateAtTEnd = Nothing } description = "BB+" -- "" ++ "if x = 0 && v <= 0 then post(v) = -v/2, post(r) = r/4 else x''= -10, r' = 0, r = v^2+20x, x >= 0, r >= 0)" ++ "; x(" ++ show tStart ++ ") = " ++ show initX ++ ", v(" ++ show tStart ++ ") = " ++ show initX' ++ ", r(" ++ show tStart ++ ") ∊ " ++ show initR initValues@[initX, initX', initR] = [toD 5, toD 0, energyWith initX initX'] :: [Domain f] tStart = hybivp_tStart ivp z = toD 0 toD = dblToReal sampleDom toDInterval l r = (toD l) </\> (toD r) sampleDom = getSampleDomValue sampleFn ivpBouncingBallRiseFall :: (Var f ~ String, HasConstFns f, Neg f, ArithInOut.RoundedSubtr f, ArithInOut.RoundedMixedMultiply f Double, ArithInOut.RoundedReal (Domain f), HasConsistency (Domain f), RefOrd.IntervalLike (Domain f), Show (Domain f) ) => f -> HybridIVP f ivpBouncingBallRiseFall (sampleFn :: f) = ivp where system = HybridSystem { hybsys_componentNames = ["x","v"], hybsys_modeFields = Map.fromList [(modeRise, odeMove), (modeFall, odeMove)], hybsys_modeInvariants = Map.fromList [(modeRise, invariantRise), (modeFall, invariantFall)], hybsys_eventSpecification = eventSpecMap } modeRise = HybSysMode "rise" modeFall = HybSysMode "fall" odeMove :: [f] -> [f] odeMove [x,v] = [v, newConstFnFromSample x (toD $ -10)] invariantRise [x,v] = do xNN <- makeNonneg x vNN <- makeNonneg v return [xNN,vNN] invariantFall [x,v] = do xNN <- makeNonneg x vNP <- makeNonpos v return [xNN,vNP] eventSpecMap mode | mode == modeRise = Map.singleton eventPeak $ (modeFall, resetPeak, [True, True], prunePeak) | mode == modeFall = Map.singleton eventBounce $ (modeRise, resetBounce, [True, True], pruneBounce) eventBounce = HybSysEventKind "bounce" pruneBounce _ [x,v] = do vNP <- makeNonpos v _ <- isect z x return [z, vNP] where -- z = toD 0 resetBounce [x,v] = [x, (-0.5 :: Double) |<*> v] -- [newConstFnFromSample v 0, (0 :: Double) |<*> v] eventPeak = HybSysEventKind "peak" prunePeak _ [x,v] = do _ <- isect z v return [x, z] resetPeak [x,v] = [x,v] ivp :: HybridIVP f ivp = HybridIVP { hybivp_description = description, hybivp_system = system, hybivp_tVar = "t", hybivp_tStart = toD 0, hybivp_tEnd = toD 1, hybivp_initialStateEnclosure = Map.singleton modeFall initValues, hybivp_maybeExactStateAtTEnd = Nothing } description = "BB-M" -- "if x = 0 && v <= 0 then post(v) = -0.5*pre(v) else x'' = -10" ++ "; x(" ++ show tStart ++ ") = " ++ show initX ++ ", v(" ++ show tStart ++ ") = " ++ show initX' initValues@[initX, initX'] = [toD 5, toD 0] :: [Domain f] tStart = hybivp_tStart ivp z = toD 0 toD = dblToReal sampleDom sampleDom = getSampleDomValue sampleFn ivpBouncingBallRiseFallEnergy :: (Var f ~ String, HasConstFns f, Neg f, ArithInOut.RoundedSubtr f, ArithInOut.RoundedMixedMultiply f Double, ArithInOut.RoundedReal (Domain f), RefOrd.IntervalLike (Domain f), HasConsistency (Domain f), ArithInOut.RoundedSquareRoot (Domain f), Show (Domain f) ) => f -> HybridIVP f ivpBouncingBallRiseFallEnergy (sampleFn :: f) = ivp where energyWith x v = (v <*> v <+> (toD 20) <*> x) -- added zero so that after reset the interval refines the original (model-level hack!) system = HybridSystem { hybsys_componentNames = ["x","v","r"], hybsys_modeFields = Map.fromList [(modeRise, odeMove), (modeFall, odeMove)], hybsys_modeInvariants = Map.fromList [(modeRise, invariantRise), (modeFall, invariantFall)], hybsys_eventSpecification = eventSpecMap } modeRise = HybSysMode "rise" modeFall = HybSysMode "fall" odeMove :: [f] -> [f] odeMove [x,v,r] = [v, newConstFnFromSample x (toD $ -10), newConstFnFromSample r (toD 0)] invariantRise [x,v,r] = do -- x >= 0: xNN <- makeNonneg x -- r >= 0: rNN <- makeNonneg r -- v >= 0: -- vNN <- makeNonneg v -- v = sqrt(r - 2gx): vSqr1 <- makeNonneg $ rNN <-> ((toD 20) <*> xNN) let v1 = ArithInOut.sqrtOut vSqr1 vNew <- isect v v1 -- x = (r - (v)^2) / 2g: vSqr2 <- makeNonneg $ v <*> v let x2 = (rNN <-> vSqr2) </> (toD 20) xNew <- isect xNN x2 return [xNew, vNew, rNN] invariantFall [x,v,r] = do -- x >= 0: xNN <- makeNonneg x -- r >= 0: rNN <- makeNonneg r -- v <= 0: -- vNP <- makeNonpos v -- v = sqrt(r - 2gx): vSqr1 <- makeNonneg $ rNN <-> ((toD 20) <*> xNN) let v1 = neg $ ArithInOut.sqrtOut vSqr1 vNew <- isect v v1 -- x = (r - (v)^2) / 2g: vSqr2 <- makeNonneg $ v <*> v let x2 = (rNN <-> vSqr2) </> (toD 20) xNew <- isect xNN x2 return [xNew, vNew, rNN] eventBounce = HybSysEventKind "bc" pruneBounce _ [x,v,r] = do _ <- isect z x vNP <- makeNonpos v return $ [z,vNP,r] resetBounce [x,v,r] = [x, (-0.5 :: Double) |<*> v, (toDInterval 0 0.25) <*> r] eventPeak = HybSysEventKind "pk" prunePeak _ [x,v,r] = do _ <- isect z v return [x, z, r] resetPeak [x,v,r] = [x,v,r] eventSpecMap mode | mode == modeFall = Map.singleton eventBounce (modeRise, resetBounce, [True, True, True], pruneBounce) | mode == modeRise = Map.singleton eventPeak (modeFall, resetPeak, [False, True, False], prunePeak) ivp :: HybridIVP f ivp = HybridIVP { hybivp_description = description, hybivp_system = system, hybivp_tVar = "t", hybivp_tStart = z, hybivp_tEnd = z, hybivp_initialStateEnclosure = Map.singleton modeFall initValues, hybivp_maybeExactStateAtTEnd = Nothing } description = "BB-M" -- "" ++ "if x = 0 && v <= 0 then post(v) = -v/2, post(r) = r/4 else x''= -10, r' = 0, r = v^2+20x, x >= 0, r >= 0)" ++ "; x(" ++ show tStart ++ ") = " ++ show initX ++ ", v(" ++ show tStart ++ ") = " ++ show initX' ++ ", r(" ++ show tStart ++ ") ∊ " ++ show initR initValues@[initX, initX', initR] = [toD 5, toD 0, energyWith initX initX'] :: [Domain f] tStart = hybivp_tStart ivp z = toD 0 toD = dblToReal sampleDom toDInterval l r = (toD l) </\> (toD r) sampleDom = getSampleDomValue sampleFn ivpBouncingBallFloorRise :: (Var f ~ String, HasConstFns f, Neg f, ArithInOut.RoundedSubtr f, ArithInOut.RoundedMixedMultiply f Double, ArithInOut.RoundedReal (Domain f), HasConsistency (Domain f), RefOrd.IntervalLike (Domain f), Show (Domain f) ) => f -> HybridIVP f ivpBouncingBallFloorRise (sampleFn :: f) = ivp where system = HybridSystem { hybsys_componentNames = ["x","xv","y","yv"], hybsys_modeFields = Map.fromList [(modeMove, odeMove)], hybsys_modeInvariants = Map.fromList [(modeMove, invariantMove)], hybsys_eventSpecification = eventSpecMap } modeMove = HybSysMode "move" odeMove :: [f] -> [f] odeMove [x,xv,y,yv] = [xv, newConstFnFromSample x (toD $ -10), yv, newConstFnFromSample y (toD $ 1)] -- invariantMove = id invariantMove [x,xv,y,yv] = do xMyNN <- makeNonneg $ x <-> y return [xMyNN <+> y,xv,y,yv] eventSpecMap _mode = Map.singleton eventBounce $ (modeMove, resetBounce, [True, True, True, True], pruneBounce) eventBounce = HybSysEventKind "bounce" pruneBounce _ [x,xv,y,yv] = do vDiffNP <- makeNonpos $ xv <-> yv _ <- isect x y return [y, vDiffNP <+> yv, y, yv] resetBounce [x,xv,y,yv] = [x, yv <+> (-0.5 :: Double) |<*> (xv <-> yv), y, yv] ivp :: HybridIVP f ivp = HybridIVP { hybivp_description = description, hybivp_system = system, hybivp_tVar = "t", hybivp_tStart = toD 0, hybivp_tEnd = toD 1, hybivp_initialStateEnclosure = Map.singleton modeMove initValues, hybivp_maybeExactStateAtTEnd = Nothing } description = "BB-R" -- "if x = y && x' <= y' then post(x') = y'-0.5*(x'-y') else x'' = -10, y'' = 1" ++ "; x(" ++ show tStart ++ ") = " ++ show initX ++ ", x'(" ++ show tStart ++ ") = " ++ show initXV ++ "; y(" ++ show tStart ++ ") = " ++ show initY ++ ", y'(" ++ show tStart ++ ") = " ++ show initYV initValues@[initX, initXV, initY, initYV] = [toD 5, toD 0, toD 0, toD 0] :: [Domain f] tStart = hybivp_tStart ivp -- z = toD 0 toD = dblToReal sampleDom sampleDom = getSampleDomValue sampleFn ivpBouncingBallFloorRiseEnergy :: (Var f ~ String, HasConstFns f, Neg f, ArithInOut.RoundedSubtr f, ArithInOut.RoundedMultiply f, ArithInOut.RoundedMixedMultiply f Double, ArithInOut.RoundedReal (Domain f), ArithInOut.RoundedSquareRoot (Domain f), HasConsistency (Domain f), RefOrd.IntervalLike (Domain f), Show (Domain f) ) => f -> HybridIVP f ivpBouncingBallFloorRiseEnergy (sampleFn :: f) = ivp where system = HybridSystem { hybsys_componentNames = ["x","xv","y","yv","yvv", "r"], hybsys_modeFields = Map.fromList [(modeMove, odeMove)], hybsys_modeInvariants = Map.fromList [(modeMove, invariantMove)], hybsys_eventSpecification = eventSpecMap } initValues@[initX, initXV, initY, initYV, _initYVV, initR] = [toD 5, toD 0, toD 0, toD 1, toD 0, toD 101] -- linear rise -- toD 0, toD 1, toD floorRiseAccelD, toD $ 101] -- quadratic -- toD 3.5, toD 0, toD 6, toD 30] -- cubic hill -- r = 2g(x-y) + (x'-y')^2 modeMove = HybSysMode "move" odeMove :: [f] -> [f] odeMove [x,xv,_y,yv,yvv,r] = [xv, newConstFnFromSample x (toD $ -10), yv, yvv, newConstFnFromSample yvv (toD $ 0), -- linear/quadratic (y''' = 0) -- newConstFnFromSample y (toD $ -6), -- cubic hill -- r' = 2(x'-y')(g+x''-y'') newConstFnFromSample r (toD $ 0) -- linear -- (-2 * floorRiseAccelD) |<*> (xv <-> yv) -- quadratic -- (-2 :: Double) |<*> ((xv <-> yv) <*> yvv) -- cubic ] -- invariantMove = id -- floorRiseAccelD = 1 :: Double -- floorRiseAccelD = -0.375 :: Double -- floorRiseAccelD = -2 :: Double -- floorRiseThirdD = -11 :: Double invariantMove [x,xv,y,yv,yvv,r] = do -- x >= y: xMyNN <- makeNonneg $ x <-> y let xFromY = xMyNN <+> y -- r = 2g(x-y) + (x'-y')^2 -- r >= 0: rNN <- makeNonneg r -- x-y = (r - (x'-y')^2) / 2g: let xvMyv = xv <-> yv xvMyvSqr2 <- makeNonneg $ xvMyv <*> xvMyv let xFromXV = (rNN <-> xvMyvSqr2) </> (toD 20) <+> y xNew <- isect xFromY xFromXV -- |x'-y'| = sqrt(r - 2g(x-y)): xvMyvSqr <- makeNonneg $ rNN <-> ((toD 20) <*> xMyNN) let xvMyvAbs = ArithInOut.sqrtOut xvMyvSqr xvNew <- isect xv ((neg xvMyvAbs </\> xvMyvAbs) <+> yv) return [xNew,xvNew,y,yv,yvv,rNN] eventSpecMap _mode = Map.singleton eventBounce $ -- (modeMove, resetBounce, [True, True, False, False, False, True], pruneBounce) (modeMove, resetBounce, [True, True, True, True, True, True], pruneBounce) eventBounce = HybSysEventKind "bounce" pruneBounce _ [x,xv,y,yv,yvv,r] = do vDiffNP <- makeNonpos $ xv <-> yv _ <- isect x y return [y, vDiffNP <+> yv, y, yv,yvv,r] resetBounce [x,xv,y,yv,yvv,r] = [x, yv <+> (-0.5 :: Double) |<*> (xv <-> yv), -- x' := y' - (x' - y')/2 y, yv, yvv, (toDInterval 0 0.25) <*> r] -- r := r/4 ivp :: HybridIVP f ivp = HybridIVP { hybivp_description = description, hybivp_system = system, hybivp_tVar = "t", hybivp_tStart = toD 0, hybivp_tEnd = toD 1, hybivp_initialStateEnclosure = Map.singleton modeMove initValues, hybivp_maybeExactStateAtTEnd = Nothing } description = "BB-R+" ++ "; x(" ++ show tStart ++ ") = " ++ show initX ++ ", x'(" ++ show tStart ++ ") = " ++ show initXV ++ "; y(" ++ show tStart ++ ") = " ++ show initY ++ ", y'(" ++ show tStart ++ ") = " ++ show initYV ++ ", r(" ++ show tStart ++ ") = " ++ show initR tStart = hybivp_tStart ivp -- z = toD 0 toD = dblToReal sampleDom toDInterval l r = (toD l) </\> (toD r) sampleDom = getSampleDomValue sampleFn ivpBouncingBallFloorDropEnergy :: (Var f ~ String, HasConstFns f, Neg f, ArithInOut.RoundedSubtr f, ArithInOut.RoundedMultiply f, ArithInOut.RoundedMixedMultiply f Double, ArithInOut.RoundedReal (Domain f), ArithInOut.RoundedSquareRoot (Domain f), HasConsistency (Domain f), RefOrd.IntervalLike (Domain f), Show (Domain f) ) => f -> HybridIVP f ivpBouncingBallFloorDropEnergy (sampleFn :: f) = ivp where system = HybridSystem { hybsys_componentNames = ["x","xv","y","tm","r"], hybsys_modeFields = Map.fromList [(modeMove1, odeMove), (modeMove2, odeMove)], hybsys_modeInvariants = Map.fromList [(modeMove1, invariantMove1), (modeMove2, invariantMove2)], hybsys_eventSpecification = eventSpecMap } initValues = [initX, initXV, initY, initTM, initR] initX = toD 6 initXV = toD 0 initY = toD 1 initTM = toD 0 initR = toD 100 -- r = 2g(x-y) + (x'-y')^2 tDrop = 3.03125 yDrop = 0 modeMove1 = HybSysMode "move1" modeMove2 = HybSysMode "move2" odeMove :: [f] -> [f] odeMove [x,xv,_y,_t,r] = [xv, newConstFnFromSample x (toD $ -10), newConstFnFromSample x (toD $ 0), -- y' newConstFnFromSample x (toD $ 1), -- tm' -- r' = 2(x'-y')(g+x''-y'') newConstFnFromSample r (toD $ 0) -- r' ] invariantMove1 orig@[_x,_xv,_y,tm,_r] = do _ <- isect (tStart </\> (toD tDrop)) tm invariantMove orig invariantMove2 = invariantMove invariantMove [x,xv,y,tm,r] = do let yv = zero y -- x >= y: xMyNN <- makeNonneg $ x <-> y let xFromY = xMyNN <+> y -- r = 2g(x-y) + (x'-y')^2 -- r >= 0: rNN <- makeNonneg r -- x-y = (r - (x'-y')^2) / 2g: let xvMyv = xv <-> yv xvMyvSqr2 <- makeNonneg $ xvMyv <*> xvMyv let xFromXV = (rNN <-> xvMyvSqr2) </> (toD 20) <+> y xNew <- isect xFromY xFromXV -- |x'-y'| = sqrt(r - 2g(x-y)): xvMyvSqr <- makeNonneg $ rNN <-> ((toD 20) <*> xMyNN) let xvMyvAbs = ArithInOut.sqrtOut xvMyvSqr xvNew <- isect xv ((neg xvMyvAbs </\> xvMyvAbs) <+> yv) return [xNew,xvNew,y,tm,rNN] eventSpecMap mode | mode == modeMove1 = Map.fromList $ [ (eventBounce1, (modeMove1, resetBounce, -- [True, True, True, True, True], [True, True, False, False, True], pruneBounce)) , (eventDrop, (modeMove2, resetDrop, [True, True, True, True, True], pruneDrop)) ] | mode == modeMove2 = Map.fromList $ [ (eventBounce2, (modeMove2, resetBounce, [True, True, False, False, True], -- [True, True, True, True, True], pruneBounce)) ] | otherwise = error "internal error: eventSpecMap" eventBounce1 = HybSysEventKind "bounce1" eventBounce2 = HybSysEventKind "bounce2" pruneBounce _ [x,xv,y,tm,r] = do let yv = zero y vDiffNP <- makeNonpos $ xv <-> yv _ <- isect x y return [y, vDiffNP <+> yv, y, tm, r] pruneBounce _ _ = error "internal error: pruneBounce" resetBounce [x,xv,y,tm,r] = let yv = zero y in [x, yv <+> (-0.5 :: Double) |<*> (xv <-> yv), -- x' := y' - (x' - y')/2 y, tm, (toDInterval 0 0.25) <*> r] -- r := r/4 resetBounce _ = error "internal error: resetBounce" eventDrop = HybSysEventKind "drop" pruneDrop _ orig@[_x,_xv,_y,tm,_r] = do _ <- isect tm (toD tDrop) return orig pruneDrop _ _ = error "internal error: pruneDrop" resetDrop [x,xv,y,tm,r] = [x, xv, toD yDrop, tm, ((toD 20) <*> (y <-> (toD yDrop))) <+> r] -- -- r = 2g(x-y) + (x'-y')^2 resetDrop _ = error "internal error: resetDrop" ivp :: HybridIVP f ivp = HybridIVP { hybivp_description = description, hybivp_system = system, hybivp_tVar = "t", hybivp_tStart = toD 0, hybivp_tEnd = toD 1, hybivp_initialStateEnclosure = Map.singleton modeMove1 initValues, hybivp_maybeExactStateAtTEnd = Nothing } description = "BB-R+" ++ "; x(" ++ show tStart ++ ") = " ++ show initX ++ ", x'(" ++ show tStart ++ ") = " ++ show initXV ++ "; y(" ++ show tStart ++ ") = " ++ show initY ++ ", t(" ++ show tStart ++ ") = " ++ show initTM ++ ", r(" ++ show tStart ++ ") = " ++ show initR tStart = hybivp_tStart ivp -- z = toD 0 toD = dblToReal sampleDom toDInterval l r = (toD l) </\> (toD r) sampleDom = getSampleDomValue sampleFn ivpBouncingBallDrag :: (Var f ~ String, HasConstFns f, Neg f, ArithInOut.RoundedSubtr f, ArithInOut.RoundedAbs f, ArithInOut.RoundedMultiply f, ArithInOut.RoundedMixedMultiply f Double, ArithInOut.RoundedReal (Domain f), HasConsistency (Domain f), RefOrd.IntervalLike (Domain f), Show (Domain f) ) => f -> HybridIVP f ivpBouncingBallDrag (sampleFn :: f) = ivp where system = HybridSystem { hybsys_componentNames = ["x","v"], hybsys_modeFields = Map.fromList [(modeMove, odeMove)], hybsys_modeInvariants = Map.fromList [(modeMove, invariantMove)], hybsys_eventSpecification = eventSpecMap } modeMove = HybSysMode "move" odeMove :: [f] -> [f] odeMove [x,v] = [v, newConstFnFromSample x (toD $ -10) <-> ((ArithInOut.absOut v) <*> v <*>| (0.1 :: Double))] -- invariantMove = id invariantMove [x,v] = do xNN <- makeNonneg x return [xNN,v] eventSpecMap _mode = Map.singleton eventBounce $ (modeMove, resetBounce, [True, True], pruneBounce) eventBounce = HybSysEventKind "bounce" pruneBounce _ [x,v] = do vNP <- makeNonpos v _ <- isect z x return [z, vNP] where z = toD 0 resetBounce [x,v] = [x, (-0.5 :: Double) |<*> v] -- [newConstFnFromSample v 0, (0 :: Double) |<*> v] ivp :: HybridIVP f ivp = HybridIVP { hybivp_description = description, hybivp_system = system, hybivp_tVar = "t", hybivp_tStart = toD 0, hybivp_tEnd = toD 1, hybivp_initialStateEnclosure = Map.singleton modeMove initValues, hybivp_maybeExactStateAtTEnd = Nothing } description = "BB-D" -- "if x = 0 && v <= 0 then post(v) = -0.5*pre(v) else x'' = -10" ++ "; x(" ++ show tStart ++ ") = " ++ show initX ++ ", v(" ++ show tStart ++ ") = " ++ show initX' initValues@[initX, initX'] = [toD 5, toD 0] :: [Domain f] tStart = hybivp_tStart ivp -- z = toD 0 toD = dblToReal sampleDom sampleDom = getSampleDomValue sampleFn ivpBouncingBallDragPosNeg :: (Var f ~ String, HasConstFns f, Neg f, ArithInOut.RoundedSubtr f, ArithInOut.RoundedMultiply f, ArithInOut.RoundedMixedMultiply f Double, ArithInOut.RoundedReal (Domain f), HasConsistency (Domain f), RefOrd.IntervalLike (Domain f), Show (Domain f) ) => f -> HybridIVP f ivpBouncingBallDragPosNeg (sampleFn :: f) = ivp where system = HybridSystem { hybsys_componentNames = ["x","v"], hybsys_modeFields = Map.fromList [(modeRise, odeRise), (modeFall, odeFall)], hybsys_modeInvariants = Map.fromList [(modeRise, invariantRise), (modeFall, invariantFall)], hybsys_eventSpecification = eventSpecMap } modeRise = HybSysMode "rise" modeFall = HybSysMode "fall" odeRise :: [f] -> [f] odeRise [x,v] = [v, newConstFnFromSample x (toD $ -10) <-> (v <*> v <*>| (0.1 :: Double))] odeFall :: [f] -> [f] odeFall [x,v] = [v, newConstFnFromSample x (toD $ -10) <+> (v <*> v <*>| (0.1 :: Double))] invariantRise [x,v] = do xNN <- makeNonneg x vNN <- makeNonneg v return [xNN,vNN] invariantFall [x,v] = do xNN <- makeNonneg x vNP <- makeNonpos v return [xNN,vNP] eventSpecMap mode | mode == modeRise = Map.singleton eventPeak $ (modeFall, resetPeak, [True, True], prunePeak) | mode == modeFall = Map.singleton eventBounce $ (modeRise, resetBounce, [True, True], pruneBounce) eventBounce = HybSysEventKind "bounce" pruneBounce _ [x,v] = do vNP <- makeNonpos v _ <- isect z x return [z, vNP] resetBounce [x,v] = [x, (-0.5 :: Double) |<*> v] -- [newConstFnFromSample v 0, (0 :: Double) |<*> v] eventPeak = HybSysEventKind "peak" prunePeak _ [x,v] = do _ <- isect z v return [x, z] resetPeak [x,v] = [x,v] ivp :: HybridIVP f ivp = HybridIVP { hybivp_description = description, hybivp_system = system, hybivp_tVar = "t", hybivp_tStart = toD 0, hybivp_tEnd = toD 1, hybivp_initialStateEnclosure = Map.singleton modeFall initValues, hybivp_maybeExactStateAtTEnd = Nothing } description = "BB-D2" -- "if x = 0 && v <= 0 then post(v) = -0.5*pre(v) else x'' = -10" ++ "; x(" ++ show tStart ++ ") = " ++ show initX ++ ", v(" ++ show tStart ++ ") = " ++ show initX' initValues@[initX, initX'] = [toD 5, toD 0] :: [Domain f] tStart = hybivp_tStart ivp z = toD 0 toD = dblToReal sampleDom sampleDom = getSampleDomValue sampleFn {- Minimal system spec: x' = v v' = -10 - 0.1*v*|v| Extended with energy: r = v^2 + 20x r' = 2v*(-10 - 0.1*v*|v|) + 20v = -0.2 * |v|^3 -} ivpBouncingBallDragEnergy :: (Var f ~ String, HasConstFns f, Neg f, ArithInOut.RoundedSubtr f, ArithInOut.RoundedAbs f, ArithInOut.RoundedMultiply f, ArithInOut.RoundedMixedMultiply f Double, ArithInOut.RoundedReal (Domain f), RefOrd.IntervalLike (Domain f), HasConsistency (Domain f), ArithInOut.RoundedSquareRoot (Domain f), Show (Domain f) ) => f -> HybridIVP f ivpBouncingBallDragEnergy (sampleFn :: f) = ivp where energyWith x v = -- z </\> (v <*> v <+> (toD 20) <*> x) -- added zero so that after reset the interval refines the original (model-level hack!) system = HybridSystem { hybsys_componentNames = ["x","v","r"], hybsys_modeFields = Map.fromList [(modeMove, odeMove)], hybsys_modeInvariants = Map.fromList [(modeMove, invariantMove)], hybsys_eventSpecification = eventSpecMap } modeMove = HybSysMode "move" odeMove :: [f] -> [f] -- odeMove [x,v,r] = [v, newConstFnFromSample x (toD $ -10), newConstFnFromSample r (toD 0)] odeMove [x,v,_r] = [v, newConstFnFromSample x (toD $ -10) <-> ((ArithInOut.absOut v) <*> v <*>| (0.1 :: Double)), ((ArithInOut.absOut v) <*> v <*> v <*>| (-0.2 :: Double))] invariantMove [x,v,r] = do -- x >= 0: xNN <- makeNonneg x -- r >= 0: rNN <- makeNonneg r -- |v| = sqrt(r - 2gx): vSqr1 <- makeNonneg $ rNN <-> ((toD 20) <*> xNN) let absV = ArithInOut.sqrtOut vSqr1 vNew <- isect v ((neg absV) </\> absV) -- x = (r - (v)^2) / 2g: vSqr2 <- makeNonneg $ v <*> v let x2 = (rNN <-> vSqr2) </> (toD 20) xNew <- isect xNN x2 return [xNew, vNew, rNN] eventBounce = HybSysEventKind "bc" pruneBounce _ [x,v,r] = do _ <- isect z x vNP <- makeNonpos v return $ [z,vNP,r] resetBounce [x,v,r] = [x, (-0.5 :: Double) |<*> v, (toDInterval 0 0.25) <*> r ] -- deliberately lose precision to facilitate quicker event tree convergence (HACK!) eventSpecMap _mode = Map.singleton eventBounce $ (modeMove, resetBounce, [True, True, True], pruneBounce) ivp :: HybridIVP f ivp = HybridIVP { hybivp_description = description, hybivp_system = system, hybivp_tVar = "t", hybivp_tStart = z, hybivp_tEnd = z, hybivp_initialStateEnclosure = Map.singleton modeMove initValues, hybivp_maybeExactStateAtTEnd = Nothing } description = "BB-D+" -- "" ++ "if x = 0 && v <= 0 then post(v) = -v/2, post(r) = r/4 else x''= -10, r' = 0, r = v^2+20x, x >= 0, r >= 0)" ++ "; x(" ++ show tStart ++ ") = " ++ show initX ++ ", v(" ++ show tStart ++ ") = " ++ show initX' ++ ", r(" ++ show tStart ++ ") ∊ " ++ show initR initValues@[initX, initX', initR] = [toD 5, toD 0, energyWith initX initX'] :: [Domain f] tStart = hybivp_tStart ivp z = toD 0 toD = dblToReal sampleDom toDInterval l r = (toD l) </\> (toD r) sampleDom = getSampleDomValue sampleFn ivpBouncingBallDragPosNegEnergy :: (Var f ~ String, HasConstFns f, Neg f, ArithInOut.RoundedSubtr f, ArithInOut.RoundedMultiply f, ArithInOut.RoundedMixedMultiply f Double, ArithInOut.RoundedReal (Domain f), RefOrd.IntervalLike (Domain f), HasConsistency (Domain f), ArithInOut.RoundedSquareRoot (Domain f), Show (Domain f) ) => f -> HybridIVP f ivpBouncingBallDragPosNegEnergy (sampleFn :: f) = ivp where energyWith x v = z </\> (v <*> v <+> (toD 20) <*> x) system = HybridSystem { hybsys_componentNames = ["x","v","r"], hybsys_modeFields = Map.fromList [(modeRise, odeRise), (modeFall, odeFall)], hybsys_modeInvariants = Map.fromList [(modeRise, invariantRise), (modeFall, invariantFall)], hybsys_eventSpecification = eventSpecMap } modeRise = HybSysMode "rise" modeFall = HybSysMode "fall" odeRise :: [f] -> [f] odeRise [x,v,_r] = [v, newConstFnFromSample x (toD $ -10) <-> (v <*> v <*>| (0.1 :: Double)), (v <*> v <*> v <*>| (-0.2 :: Double))] odeFall :: [f] -> [f] odeFall [x,v,_r] = [v, newConstFnFromSample x (toD $ -10) <+> (v <*> v <*>| (0.1 :: Double)), (v <*> v <*> v <*>| (0.2 :: Double))] invariantRise = invariantMove False invariantFall = invariantMove True invariantMove vIsNeg [x,v,r] = do -- x >= 0: xNN <- makeNonneg x -- r >= 0: rNN <- makeNonneg r -- v >= 0: vNN <- case vIsNeg of False -> makeNonneg v True -> makeNonpos v -- v = sqrt(r - 2gx): vSqr1 <- makeNonneg $ rNN <-> ((toD 20) <*> xNN) let v1 = (if vIsNeg then neg else id) $ ArithInOut.sqrtOut vSqr1 vNew <- isect vNN v1 -- x = (r - (v)^2) / 2g: vSqr2 <- makeNonneg $ vNew <*> vNew let x2 = (rNN <-> vSqr2) </> (toD 20) xNew <- isect xNN x2 return [xNew, vNew, rNN] eventBounce = HybSysEventKind "bc" pruneBounce _ [x,v,r] = do _ <- isect z x vNP <- makeNonpos v return $ [z,vNP,r] resetBounce [x,v,r] = [x, (-0.5 :: Double) |<*> v, (0.25 :: Double) |<*> r] eventPeak = HybSysEventKind "pk" prunePeak _ [x,v,r] = do _ <- isect z v return [x, z, r] resetPeak [x,v,r] = [x,v,r] eventSpecMap mode | mode == modeFall = Map.singleton eventBounce (modeRise, resetBounce, [True, True, True], pruneBounce) | mode == modeRise = Map.singleton eventPeak (modeFall, resetPeak, [False, True, False], prunePeak) ivp :: HybridIVP f ivp = HybridIVP { hybivp_description = description, hybivp_system = system, hybivp_tVar = "t", hybivp_tStart = z, hybivp_tEnd = z, hybivp_initialStateEnclosure = Map.singleton modeFall initValues, hybivp_maybeExactStateAtTEnd = Nothing } description = "BB-D2+" -- "" ++ "if x = 0 && v <= 0 then post(v) = -v/2, post(r) = r/4 else x''= -10, r' = 0, r = v^2+20x, x >= 0, r >= 0)" ++ "; x(" ++ show tStart ++ ") = " ++ show initX ++ ", v(" ++ show tStart ++ ") = " ++ show initX' ++ ", r(" ++ show tStart ++ ") ∊ " ++ show initR initValues@[initX, initX', initR] = [toD 5, toD 0, energyWith initX initX'] :: [Domain f] tStart = hybivp_tStart ivp z = toD 0 toD = dblToReal sampleDom sampleDom = getSampleDomValue sampleFn {- Minimal system spec: x' = v v' = -5000/(20+x)^2 - 0.1*v*|v| Extended with energy: r = v^2 + 500 - 10000/(20+x) r' = 2v*(-5000/(20+x)^2 - 0.1*v*|v|) + 10000*v/(20+x)^2 = -10000*v/(20+x)^2 - 0.2*|v|^3 + 10000*v/(20+x)^2 = - 0.2*|v|^3 -} ivpBouncingBallDragNewtonianGravityEnergy :: (Var f ~ String, HasConstFns f, Neg f, CanEvaluate f, ArithInOut.RoundedSubtr f, ArithInOut.RoundedAbs f, ArithInOut.RoundedMultiply f, ArithInOut.RoundedPowerToNonnegInt f, ArithInOut.RoundedDivide f, ArithInOut.RoundedMixedAdd f Double, ArithInOut.RoundedMixedMultiply f Double, ArithInOut.RoundedReal (Domain f), RefOrd.IntervalLike (Domain f), HasConsistency (Domain f), ArithInOut.RoundedSquareRoot (Domain f), Show f, Show (Domain f) ) => f -> HybridIVP f ivpBouncingBallDragNewtonianGravityEnergy (sampleFn :: f) = ivp where energyWith x v = z </\> (v <*> v <+> (toD 500) <+> (toD (-10000)) </> ((toD 20) <+> x)) -- r = v^2 + 500 - 10000/(20+x) -- r' = 2v(-5000/(20+x)^2) + 10000 v/(20+x)^2 = 0 system = HybridSystem { hybsys_componentNames = ["x","v","r"], hybsys_modeFields = Map.fromList [(modeMove, odeMove)], hybsys_modeInvariants = Map.fromList [(modeMove, invariantMove)], hybsys_eventSpecification = eventSpecMap } modeMove = HybSysMode "move" odeMove :: [f] -> [f] odeMove [x,v,_r] = [v, (newConstFnFromSample x (toD $ -5000) </> (((20 :: Double) |<+> x) <^> 2)) <-> ((ArithInOut.absOut v) <*> v <*>| (0.1 :: Double)), ((ArithInOut.absOut v) <*> v <*> v <*>| (-0.2 :: Double))] invariantMove [x,v,r] = do -- x >= 0: xNN <- makeNonneg x -- r >= 0: rNN <- makeNonneg r -- r = v^2 + 500 - 10000/(20+x) ---> -- v = sqrt(r - 500 + 10000/(20+x)): vSqr1 <- makeNonneg $ rNN <+> (toD (-500)) <+> ((toD 10000) </> ((toD 20) <+> xNN)) let v1 = ArithInOut.sqrtOut vSqr1 vNew <- case (v >=? z) of Just True -> isect v v1 Just False -> isect v (neg v1) _ -> isect v (neg v1 </\> v1) -- r = v^2 + 500 - 10000/(20+x) ---> -- r - v^2 - 500 = -10000/(20+x) ---> -- 20 + x = -10000/(r - v^2 - 500) ---> -- x = -20 +10000/(v^2 + 500 - r) vSqr2 <- makeNonneg $ vNew <*> vNew let x2 = (toD (-20)) <+> ((toD 10000) </> (vSqr2 <-> rNN <+> (toD 500))) xNew <- isect xNN x2 return [xNew, vNew, rNN] eventBounce = HybSysEventKind "bc" pruneBounce _ [x,v,r] = do _ <- isect z x vNP <- makeNonpos v return $ [z,vNP,r] resetBounce [x,v,r] = [x, (-0.5 :: Double) |<*> v, (0.25 :: Double) |<*> r] eventSpecMap _mode = Map.singleton eventBounce (modeMove, resetBounce, [True, True, True], pruneBounce) ivp :: HybridIVP f ivp = HybridIVP { hybivp_description = description, hybivp_system = system, hybivp_tVar = "t", hybivp_tStart = z, hybivp_tEnd = z, hybivp_initialStateEnclosure = Map.singleton modeMove initValues, hybivp_maybeExactStateAtTEnd = Nothing } description = "BB-DG+" -- "" ++ "if x = 0 && v <= 0 then post(v) = -v/2, post(r) = r/4 else x''= -10, r' = 0, r = v^2+20x, x >= 0, r >= 0)" ++ "; x(" ++ show tStart ++ ") = " ++ show initX ++ ", v(" ++ show tStart ++ ") = " ++ show initX' ++ ", r(" ++ show tStart ++ ") ∊ " ++ show initR initValues@[initX, initX', initR] = [toD 5, toD 0, energyWith initX initX'] :: [Domain f] tStart = hybivp_tStart ivp z = toD 0 toD = dblToReal sampleDom sampleDom = getSampleDomValue sampleFn ivpBouncingBallDragPosNegNewtonGravityEnergy :: (Var f ~ String, HasConstFns f, Neg f, CanEvaluate f, ArithInOut.RoundedSubtr f, ArithInOut.RoundedMultiply f, ArithInOut.RoundedPowerToNonnegInt f, ArithInOut.RoundedDivide f, ArithInOut.RoundedMixedAdd f Double, ArithInOut.RoundedMixedMultiply f Double, ArithInOut.RoundedReal (Domain f), RefOrd.IntervalLike (Domain f), HasConsistency (Domain f), ArithInOut.RoundedSquareRoot (Domain f), Show f, Show (Domain f) ) => f -> HybridIVP f ivpBouncingBallDragPosNegNewtonGravityEnergy (sampleFn :: f) = ivp where energyWith x v = z </\> (v <*> v <+> (toD 500) <+> (toD (-10000)) </> ((toD 20) <+> x)) system = HybridSystem { hybsys_componentNames = ["x","v","r"], hybsys_modeFields = Map.fromList [(modeRise, odeRise), (modeFall, odeFall)], hybsys_modeInvariants = Map.fromList [(modeRise, invariantRise), (modeFall, invariantFall)], hybsys_eventSpecification = eventSpecMap } modeRise = HybSysMode "rise" modeFall = HybSysMode "fall" odeRise :: [f] -> [f] odeRise [x,v,_r] = [v, (newConstFnFromSample x (toD $ -5000) </> (((20 :: Double) |<+> x) <^> 2)) <-> (v <*> v <*>| (0.1 :: Double)), (v <*> v <*> v <*>| (-0.2 :: Double))] odeFall :: [f] -> [f] odeFall [x,v,_r] = [v, (newConstFnFromSample x (toD $ -5000) </> (((20 :: Double) |<+> x) <^> 2)) <+> (v <*> v <*>| (0.1 :: Double)), (v <*> v <*> v <*>| (0.2 :: Double))] invariantRise = invariantMove False invariantFall = invariantMove True invariantMove vIsNeg [x,v,r] = do -- v >= 0: vNN <- case vIsNeg of False -> makeNonneg v True -> makeNonpos v -- x >= 0: xNN <- makeNonneg x -- r >= 0: rNN <- makeNonneg r -- r = v^2 + 500 - 10000/(20+x) ---> -- v = sqrt(r - 500 + 10000/(20+x)): vSqr1 <- makeNonneg $ rNN <+> (toD (-500)) <+> ((toD 10000) </> ((toD 20) <+> xNN)) let v1 = ArithInOut.sqrtOut vSqr1 vNew <- case vIsNeg of False -> isect vNN v1 True -> isect vNN (neg v1) -- r = v^2 + 500 - 10000/(20+x) ---> -- r - v^2 - 500 = -10000/(20+x) ---> -- 20 + x = -10000/(r - v^2 - 500) ---> -- x = -20 +10000/(v^2 + 500 - r) vSqr2 <- makeNonneg $ vNew <*> vNew let x2 = (toD (-20)) <+> ((toD 10000) </> (vSqr2 <-> rNN <+> (toD 500))) xNew <- isect xNN x2 return [xNew, vNew, rNN] eventBounce = HybSysEventKind "bc" pruneBounce _ [x,v,r] = do _ <- isect z x vNP <- makeNonpos v return $ [z,vNP,r] resetBounce [x,v,r] = [x, (-0.5 :: Double) |<*> v, (0.25 :: Double) |<*> r] eventPeak = HybSysEventKind "pk" prunePeak _ [x,v,r] = do _ <- isect z v return [x, z, r] resetPeak [x,v,r] = [x,v,r] eventSpecMap mode | mode == modeFall = Map.singleton eventBounce (modeRise, resetBounce, [True, True, True], pruneBounce) | mode == modeRise = Map.singleton eventPeak (modeFall, resetPeak, [False, True, False], prunePeak) ivp :: HybridIVP f ivp = HybridIVP { hybivp_description = description, hybivp_system = system, hybivp_tVar = "t", hybivp_tStart = z, hybivp_tEnd = z, hybivp_initialStateEnclosure = Map.singleton modeFall initValues, hybivp_maybeExactStateAtTEnd = Nothing } description = "BB-D2G+" -- "" ++ "if x = 0 && v <= 0 then post(v) = -v/2, post(r) = r/4 else x''= -10, r' = 0, r = v^2+20x, x >= 0, r >= 0)" ++ "; x(" ++ show tStart ++ ") = " ++ show initX ++ ", v(" ++ show tStart ++ ") = " ++ show initX' ++ ", r(" ++ show tStart ++ ") ∊ " ++ show initR initValues@[initX, initX', initR] = [toD 5, toD 0, energyWith initX initX'] :: [Domain f] tStart = hybivp_tStart ivp z = toD 0 toD = dblToReal sampleDom sampleDom = getSampleDomValue sampleFn {- Minimal system spec: x' = v v' = -5000/(20+x)^2 if Extended with energy: r = v^2 + 500 - 10000/(20+x) r' = 0 -} ivpBouncingBallNewtonianGravityEnergy :: (Var f ~ String, HasConstFns f, Neg f, CanEvaluate f, ArithInOut.RoundedSubtr f, ArithInOut.RoundedMultiply f, ArithInOut.RoundedPowerToNonnegInt f, ArithInOut.RoundedDivide f, ArithInOut.RoundedMixedAdd f Double, ArithInOut.RoundedMixedMultiply f Double, ArithInOut.RoundedReal (Domain f), RefOrd.IntervalLike (Domain f), HasConsistency (Domain f), ArithInOut.RoundedSquareRoot (Domain f), Show f, Show (Domain f) ) => f -> HybridIVP f ivpBouncingBallNewtonianGravityEnergy (sampleFn :: f) = ivp where energyWith x v = z </\> (v <*> v <+> (toD 500) <+> (toD (-10000)) </> ((toD 20) <+> x)) -- r = v^2 + 500 - 10000/(20+x) -- r' = 2v(-5000/(20+x)^2) + 10000 v/(20+x)^2 = 0 system = HybridSystem { hybsys_componentNames = ["x","v","r"], hybsys_modeFields = Map.fromList [(modeMove, odeMove)], hybsys_modeInvariants = Map.fromList [(modeMove, invariantMove)], hybsys_eventSpecification = eventSpecMap } modeMove = HybSysMode "move" odeMove :: [f] -> [f] odeMove [x,v,r] = -- trace ( -- "odeMove:" -- ++ "\n Dom(x) = " ++ (show (toAscList $ getDomainBox x)) -- ++ "\n x = " ++ (show x) -- ++ "\n Ran(x) <- " ++ (show (getRangeOut x)) -- ++ "\n v = " ++ (show v) -- ++ "\n Ran(v) <- " ++ (show (getRangeOut v)) ---- ++ "\n Ran(r) <- " ++ (show r) -- (getRangeOut r)) -- ) $ [v, newConstFnFromSample x (toD $ -5000) </> (((20 :: Double) |<+> x) <^> 2), newConstFnFromSample r (toD 0)] invariantMove [x,v,r] = do -- x >= 0: xNN <- makeNonneg x -- r >= 0: rNN <- makeNonneg r -- r = v^2 + 500 - 10000/(20+x) ---> -- v = sqrt(r - 500 + 10000/(20+x)): vSqr1 <- makeNonneg $ rNN <+> (toD (-500)) <+> ((toD 10000) </> ((toD 20) <+> xNN)) let v1 = ArithInOut.sqrtOut vSqr1 vNew <- case (v >=? z) of Just True -> isect v v1 Just False -> isect v (neg v1) _ -> isect v (neg v1 </\> v1) -- r = v^2 + 500 - 10000/(20+x) ---> -- r - v^2 - 500 = -10000/(20+x) ---> -- 20 + x = -10000/(r - v^2 - 500) ---> -- x = -20 +10000/(v^2 + 500 - r) vSqr2 <- makeNonneg $ vNew <*> vNew let x2 = (toD (-20)) <+> ((toD 10000) </> (vSqr2 <-> rNN <+> (toD 500))) xNew <- isect xNN x2 return [xNew, vNew, rNN] eventBounce = HybSysEventKind "bc" pruneBounce _ [x,v,r] = do _ <- isect z x vNP <- makeNonpos v return $ [z,vNP,r] resetBounce [x,v,r] = [x, (-0.5 :: Double) |<*> v, (0.25 :: Double) |<*> r] eventSpecMap _mode = Map.singleton eventBounce (modeMove, resetBounce, [True, True, True], pruneBounce) ivp :: HybridIVP f ivp = HybridIVP { hybivp_description = description, hybivp_system = system, hybivp_tVar = "t", hybivp_tStart = z, hybivp_tEnd = z, hybivp_initialStateEnclosure = Map.singleton modeMove initValues, hybivp_maybeExactStateAtTEnd = Nothing } description = "BB-G+" -- "" ++ "if x = 0 && v <= 0 then post(v) = -v/2, post(r) = r/4 else x''= -10, r' = 0, r = v^2+20x, x >= 0, r >= 0)" ++ "; x(" ++ show tStart ++ ") = " ++ show initX ++ ", v(" ++ show tStart ++ ") = " ++ show initX' ++ ", r(" ++ show tStart ++ ") ∊ " ++ show initR initValues@[initX, initX', initR] = [toD 5, toD 0, energyWith initX initX'] :: [Domain f] tStart = hybivp_tStart ivp z = toD 0 toD = dblToReal sampleDom sampleDom = getSampleDomValue sampleFn ivpBouncingBallCubicDrag :: (Var f ~ String, HasConstFns f, Neg f, ArithInOut.RoundedSubtr f, ArithInOut.RoundedMultiply f, ArithInOut.RoundedMixedMultiply f Double, ArithInOut.RoundedMixedDivide f Double, ArithInOut.RoundedReal (Domain f), HasConsistency (Domain f), RefOrd.IntervalLike (Domain f), Show (Domain f) ) => f -> HybridIVP f ivpBouncingBallCubicDrag (sampleFn :: f) = ivp where system = HybridSystem { hybsys_componentNames = ["x","v"], hybsys_modeFields = Map.fromList [(modeMove, odeMove)], hybsys_modeInvariants = Map.fromList [(modeMove, invariantMove)], hybsys_eventSpecification = eventSpecMap } modeMove = HybSysMode "move" odeMove :: [f] -> [f] odeMove [x,v] = [ v, newConstFnFromSample x (toD $ -10) <-> (v <*> v <*> v) </>| (1000 :: Double) ] -- invariantMove = id invariantMove [x,v] = do xNN <- makeNonneg x return [xNN,v] eventSpecMap _mode = Map.singleton eventBounce $ (modeMove, resetBounce, [True, True], pruneBounce) eventBounce = HybSysEventKind "bounce" pruneBounce _ [x,v] = do vNP <- makeNonpos v _ <- isect z x return [z, vNP] resetBounce [x,v] = [x, (-0.5 :: Double) |<*> v] -- [newConstFnFromSample v 0, (0 :: Double) |<*> v] ivp :: HybridIVP f ivp = HybridIVP { hybivp_description = description, hybivp_system = system, hybivp_tVar = "t", hybivp_tStart = toD 0, hybivp_tEnd = toD 1, hybivp_initialStateEnclosure = Map.singleton modeMove initValues, hybivp_maybeExactStateAtTEnd = Nothing } description = "BB" -- "if x = 0 && v <= 0 then post(v) = -0.5*pre(v) else x'' = -10" ++ "; x(" ++ show tStart ++ ") = " ++ show initX ++ ", v(" ++ show tStart ++ ") = " ++ show initX' initValues@[initX, initX'] = [toD 5, toD 0] :: [Domain f] tStart = hybivp_tStart ivp z = toD 0 toD = dblToReal sampleDom sampleDom = getSampleDomValue sampleFn ivpBouncingBallCubicDragEnergy :: (Var f ~ String, HasConstFns f, Neg f, ArithInOut.RoundedSubtr f, ArithInOut.RoundedMultiply f, ArithInOut.RoundedMixedMultiply f Double, ArithInOut.RoundedMixedDivide f Double, ArithInOut.RoundedReal (Domain f), RefOrd.IntervalLike (Domain f), HasConsistency (Domain f), ArithInOut.RoundedSquareRoot (Domain f), Show (Domain f) ) => f -> HybridIVP f ivpBouncingBallCubicDragEnergy (sampleFn :: f) = ivp where energyWith x v = -- z </\> (v <*> v <+> (toD 20) <*> x) -- added zero so that after reset the interval refines the original (model-level hack!) system = HybridSystem { hybsys_componentNames = ["x","v","r"], hybsys_modeFields = Map.fromList [(modeMove, odeMove)], hybsys_modeInvariants = Map.fromList [(modeMove, invariantMove)], hybsys_eventSpecification = eventSpecMap } modeMove = HybSysMode "move" odeMove :: [f] -> [f] odeMove [x,v,_r] = [ v, newConstFnFromSample x (toD $ -10) <-> (v <*> v <*> v) </>| (1000 :: Double), (v <*> v <*> v <*> v) </>| (-500 :: Double) ] invariantMove [x,v,r] = do -- x >= 0: xNN <- makeNonneg x -- r >= 0: rNN <- makeNonneg r -- |v| = sqrt(r - 2gx): vSqr1 <- makeNonneg $ rNN <-> ((toD 20) <*> xNN) let absV = ArithInOut.sqrtOut vSqr1 vNew <- isect v ((neg absV) </\> absV) -- x = (r - (v)^2) / 2g: vSqr2 <- makeNonneg $ v <*> v let x2 = (rNN <-> vSqr2) </> (toD 20) xNew <- isect xNN x2 return [xNew, vNew, rNN] eventBounce = HybSysEventKind "bc" pruneBounce _ [x,v,r] = do _ <- isect z x vNP <- makeNonpos v return $ [z,vNP,r] resetBounce [x,v,r] = [x, (-0.5 :: Double) |<*> v, (toDInterval 0 0.25) <*> r ] -- deliberately lose precision to facilitate quicker event tree convergence (HACK!) eventSpecMap _mode = Map.singleton eventBounce $ (modeMove, resetBounce, [True, True, True], pruneBounce) ivp :: HybridIVP f ivp = HybridIVP { hybivp_description = description, hybivp_system = system, hybivp_tVar = "t", hybivp_tStart = z, hybivp_tEnd = z, hybivp_initialStateEnclosure = Map.singleton modeMove initValues, hybivp_maybeExactStateAtTEnd = Nothing } description = "EBBCD" -- "" ++ "if x = 0 && v <= 0 then post(v) = -v/2, post(r) = r/4 else x''= -10, r' = 0, r = v^2+20x, x >= 0, r >= 0)" ++ "; x(" ++ show tStart ++ ") = " ++ show initX ++ ", v(" ++ show tStart ++ ") = " ++ show initX' ++ ", r(" ++ show tStart ++ ") ∊ " ++ show initR initValues@[initX, initX', initR] = [toD 5, toD 0, energyWith initX initX'] :: [Domain f] tStart = hybivp_tStart ivp z = toD 0 toD = dblToReal sampleDom toDInterval l r = (toD l) </\> (toD r) sampleDom = getSampleDomValue sampleFn {-| A bouncing ball on a circle, Example 1 from paper: http://www.bipedalrobotics.com/uploads/8/0/6/8/8068963/lyapunov_zeno_2012.pdf -} ivpBouncingBallCircle :: (Var f ~ String, HasConstFns f, Neg f, ArithInOut.RoundedSubtr f, ArithInOut.RoundedMixedMultiply f Double, ArithInOut.RoundedReal (Domain f), RefOrd.IntervalLike (Domain f), HasConsistency (Domain f), ArithInOut.RoundedSquareRoot (Domain f), Show (Domain f) ) => f -> HybridIVP f ivpBouncingBallCircle (sampleFn :: f) = ivp where g = toD gD; gD = 1 e = toD eD; eD = 0.5 initX1 = toD 0.15 -- initX1 = toD 0.191 -- Zeno -- initX1 = toD 0.192 -- non-Zeno -- initX1 = toD 0.2 -- initX1 = toD 0.21 -- 4 bounces, OK with locate prec 21 -- initX1 = toD 0.22 -- 4 bounces, OK with locate prec 18 -- initX1 = toD 0.25 -- 3 bounces, OK with locate prec 16 initX2 = toD 1.2 initV1 = toD 0 initV2 = toD 0 initD = (initX1<*>initX1) <+> (initX2<*>initX2) initS = toD 0 initR = neg g <*> initX2 system = HybridSystem { hybsys_componentNames = ["x1","x2","v1","v2","d","s","r"], hybsys_modeFields = Map.fromList [(modeMove, odeMove)], hybsys_modeInvariants = Map.fromList [(modeMove, invariantMove)], hybsys_eventSpecification = eventSpecMap } modeMove = HybSysMode "move" odeMove :: [f] -> [f] odeMove [x1,x2,v1,v2,_d,s,r] = [v1, v2, newConstFnFromSample x1 (toD 0), newConstFnFromSample x2 (neg g), (2 :: Double) ArithInOut.|<*> s, r, (-3 * gD) ArithInOut.|<*> v2 ] odeMove _ = error "odeMove: internal error" invariantMove [x1,x2,v1,v2,d,s,r] = do -- d >= 1: dM1NN <- makeNonneg (d <-> c1) -- d = x1^2 + x2^2 x1New <- case (x1 >? z) of Just True -> isect x1 $ ArithInOut.sqrtOut (NumOrd.maxOut z $ dM1NN <+> c1 <-> (x2<^>2)) _ -> return x1 x2New <- case (x2 >? z) of Just True -> isect x2 $ ArithInOut.sqrtOut (NumOrd.maxOut z $ dM1NN <+> c1 <-> (x1<^>2)) _ -> return x2 dNew <- isect (dM1NN <+> c1) ((x1<^>2) <+> (x2<^>2)) -- s = x1*v1 + x2*v2 -- r = v1^2 + v2^2 - x2*g return [x1New,x2New,v1,v2,dNew,s,r] invariantMove _ = error "invariantMove: internal error" eventBounce = HybSysEventKind "bc" pruneBounce _ [x1,x2,v1,v2,d,s,r] = do _ <- isect z (d <-> c1) x1New <- isect x1 $ ArithInOut.sqrtOut (NumOrd.maxOut z $ c1 <-> (x2<^>2)) x2New <- isect x2 $ ArithInOut.sqrtOut (NumOrd.maxOut z $ c1 <-> (x1<^>2)) sNP <- makeNonpos s return $ [x1New,x2New,v1,v2,c1,sNP,r] pruneBounce _ _ = error "pruneBounce: internal error" resetBounce [x1,x2,v1,v2,d,s,r] = [x1, x2, v1 <-> c <*> x1, v2 <-> c <*> x2, d, (neg e) <*> s, r <-> (s<^>2)<*>(c1 <-> e<^>2) ] where c = (c1 <+> e) <*> s resetBounce _ = error "resetBounce: internal error" eventSpecMap _mode = Map.singleton eventBounce $ (modeMove, resetBounce, [True, True, True, True, True, True, True], pruneBounce) ivp :: HybridIVP f ivp = HybridIVP { hybivp_description = description, hybivp_system = system, hybivp_tVar = "t", hybivp_tStart = z, hybivp_tEnd = z, hybivp_initialStateEnclosure = Map.singleton modeMove initValues, hybivp_maybeExactStateAtTEnd = Nothing } description = "BB-O" -- "" ++ "if x = 0 && v <= 0 then post(v) = -v/2, post(r) = r/4 else x''= -10, r' = 0, r = v^2+20x, x >= 0, r >= 0)" ++ "; x1(" ++ show tStart ++ ") = " ++ show initX1 ++ "; x2(" ++ show tStart ++ ") = " ++ show initX2 ++ ", v1(" ++ show tStart ++ ") = " ++ show initV1 ++ ", v2(" ++ show tStart ++ ") = " ++ show initV2 ++ ", d(" ++ show tStart ++ ") = " ++ show initD ++ ", s(" ++ show tStart ++ ") = " ++ show initS ++ ", r(" ++ show tStart ++ ") = " ++ show initR initValues = [initX1, initX2, initV1, initV2, initD, initS, initR] tStart = hybivp_tStart ivp z = toD 0 c1 = toD 1 toD = dblToReal sampleDom -- toDInterval l r = (toD l) </\> (toD r) sampleDom = getSampleDomValue sampleFn --ivpBouncingBallVibr_AtTime :: -- (Var f ~ String, -- HasConstFns f, -- Neg f, -- ArithInOut.RoundedSubtr f, -- ArithInOut.RoundedMixedMultiply f Double, -- ArithInOut.RoundedReal (Domain f), -- RefOrd.IntervalLike (Domain f), -- Show (Domain f) -- ) -- => -- Double -> -- f -> -- HybridIVP f --ivpBouncingBallVibr_AtTime tEndDbl (sampleFn :: f) = -- ivp -- where -- system = -- HybridSystem -- { -- hybsys_componentNames = ["x","v","y","w"], -- hybsys_modeFields = Map.fromList [(modeMove, odeMove)], -- hybsys_modeInvariants = Map.fromList [(modeMove, invariantMove)], -- hybsys_eventModeSwitchesAndResetFunctions = -- Map.fromList [(eventBounce, (modeMove, resetBounce))], -- hybsys_eventSpecification = eventSpecMap -- } -- modeMove = HybSysMode "move" -- odeMove :: [f] -> [f] -- odeMove [x,v,y,w] = -- [v, newConstFnFromSample x (toD $ -0.81056947), -- 8/pi^2 -- w, (1::Double) |<*> (neg y)] ---- invariantMove = id -- invariantMove [x,v,y,w] = [y <+> (makeNonneg (x <-> y)),v,y,w] -- eventBounce = HybSysEventKind "bounce" -- pruneBounce [_x,v,y,w] = [y, w <-> (makeNonneg (w <-> v)),y,w] -- resetBounce :: [f] -> [f] -- resetBounce [x,v,y,w] = -- [x, w <+> ((-0.5 :: Double) |<*> (v <-> w)), y, w] ---- [newConstFnFromSample v 0, (0 :: Double) |<*> v] -- eventSpecMap _mode = -- Map.singleton eventBounce $ -- ([True, True, False, False], xDip, vNegative, pruneBounce) -- where -- xDip [x,_v,y,_w] = x <-> y -- vNegative [_x,v,_y,w] = (v <-> w <? z) -- -- ivp :: HybridIVP f -- ivp = -- HybridIVP -- { -- hybivp_description = description, -- hybivp_system = system, -- hybivp_tVar = "t", -- hybivp_tStart = z, -- hybivp_tEnd = tEnd, -- hybivp_initialStateEnclosure = -- Map.singleton modeMove initValues, -- hybivp_maybeExactStateAtTEnd = Nothing -- } -- description = -- "if x = y && v <= w then post(v) = w -0.5*(pre(v)-prec(w)) else x'' = -10, y'' = -y" -- ++ "; x(" ++ show tStart ++ ") = " ++ show initX -- ++ ", v(" ++ show tStart ++ ") = " ++ show initV -- ++ "; y(" ++ show tStart ++ ") = " ++ show initY -- ++ ", w(" ++ show tStart ++ ") = " ++ show initW -- initValues@[initX, initV, initY, initW] = (map toD [0,1.2732395,0,1]) :: [Domain f] ---- initValues@[initX, initX'] = [0,0] :: [Domain f] -- tStart = hybivp_tStart ivp -- tEnd = toD tEndDbl -- z = toD 0 -- toD = dblToReal sampleDom -- sampleDom = getSampleDomValue sampleFn -- -- --ivpBouncingBallDrop_AtTime :: -- (Var f ~ String, -- HasConstFns f, -- Neg f, -- ArithInOut.RoundedSubtr f, -- ArithInOut.RoundedMixedMultiply f Double, -- ArithInOut.RoundedMixedAdd f Double, -- ArithInOut.RoundedReal (Domain f), -- RefOrd.IntervalLike (Domain f), -- Show (Domain f) -- ) -- => -- Double -> -- Double -> -- Double -> -- Double -> -- f -> -- HybridIVP f --ivpBouncingBallDrop_AtTime groundInitDbl tDropDbl groundDropDbl tEndDbl (sampleFn :: f) = -- ivp -- where -- system = -- HybridSystem -- { -- hybsys_componentNames = ["x","v","y","tt"], -- hybsys_modeFields = Map.fromList [(modeMove1, odeMove), (modeMove2, odeMove)], -- hybsys_modeInvariants = Map.fromList [(modeMove1, invariantMove), (modeMove2, invariantMove)], -- hybsys_eventModeSwitchesAndResetFunctions = -- Map.fromList -- [ -- (eventBounce1, (modeMove1, resetBounce)), -- (eventBounce2, (modeMove2, resetBounce)), -- (eventDrop, (modeMove2, resetDrop)) -- ], -- hybsys_eventSpecification = eventSpecMap -- } -- modeMove1 = HybSysMode "move1" -- modeMove2 = HybSysMode "move2" -- odeMove :: [f] -> [f] -- odeMove [x,v,_y,_tt] = -- [v, newConstFnFromSample x (toD $ -10), -- newConstFnFromSample x (toD 0), -- newConstFnFromSample x (toD 1)] ---- invariantMove = id -- invariantMove [x,v,y,tt] = [y <+> (makeNonneg (x<->y)),v,y,tt] -- eventBounce1 = HybSysEventKind "bounce1" -- eventBounce2 = HybSysEventKind "bounce2" -- pruneBounce [_x,v,y,tt] = [y, neg (makeNonneg (neg v)),y,tt] -- resetBounce :: [f] -> [f] -- resetBounce [x,v,y,tt] = -- [x, ((-0.5 :: Double) |<*> v), y, tt] -- eventDrop = HybSysEventKind "drop" -- pruneDrop [x,v,y,_tt] = [x,v,y,tDrop] -- resetDrop :: [f] -> [f] -- resetDrop [x,v,y,tt] = -- [x, v, newConstFnFromSample y groundDrop, tt] -- eventSpecMap mode -- | mode == modeMove1 = -- (eventsBounce eventBounce1) `Map.union` eventsDrop -- | mode == modeMove2 = -- eventsBounce eventBounce2 -- where -- eventsDrop = -- Map.singleton eventDrop $ -- ([False, False, True, False], tDip, const (Just True), pruneDrop) -- where -- tDip [_x,_v,_y,tt] = tDropP <-> tt -- where -- tDropP = newConstFnFromSample tt tDrop -- eventsBounce eventBounce = -- Map.singleton eventBounce $ -- ([True, True, False, False], xDip, vNegative, pruneBounce) -- where -- xDip [x,_v,y,_tt] = x <-> y -- vNegative [_x,v,_y,_tt] = (v <? z) -- -- ivp :: HybridIVP f -- ivp = -- HybridIVP -- { -- hybivp_description = description, -- hybivp_system = system, -- hybivp_tVar = "t", -- hybivp_tStart = toD 0, -- hybivp_tEnd = tEnd, -- hybivp_initialStateEnclosure = -- Map.singleton modeMove1 initValues, -- hybivp_maybeExactStateAtTEnd = Nothing -- } -- description = -- "if t = " ++ show tDrop ++ " then post(y) = " ++ show groundDrop -- ++ "else (if x = y && v <= 0 then post(v) = -0.5*(pre(v)) else x'' = -10, y' = 0)" -- ++ "; x(" ++ show tStart ++ ") = " ++ show initX -- ++ ", v(" ++ show tStart ++ ") = " ++ show initV -- ++ "; y(" ++ show tStart ++ ") = " ++ show initY -- initValues@[initX, initV, initY, _initTT] = (map toD [5,0,groundInitDbl,0]) :: [Domain f] ---- initValues@[initX, initX'] = [0,0] :: [Domain f] -- tStart = hybivp_tStart ivp -- [_groundInit, tDrop, groundDrop, tEnd] = map toD [groundInitDbl, tDropDbl, groundDropDbl, tEndDbl] -- z = toD 0 -- toD = dblToReal sampleDom -- sampleDom = getSampleDomValue sampleFn -- --ivpBouncingBallEnergyDrop_AtTime :: -- (Var f ~ String, -- HasConstFns f, -- RefOrd.RoundedLattice f, -- Neg f, -- ArithInOut.RoundedSubtr f, -- ArithInOut.RoundedMixedAdd f Double, -- ArithInOut.RoundedMixedMultiply f Double, -- ArithInOut.RoundedMixedDivide f Double, -- ArithInOut.RoundedReal (Domain f), -- RefOrd.IntervalLike (Domain f), -- ArithInOut.RoundedSquareRoot (Domain f), -- Show (Domain f) -- ) -- => -- Double -> -- Double -> -- Double -> -- Double -> -- f -> -- HybridIVP f --ivpBouncingBallEnergyDrop_AtTime groundInitDbl tDropDbl groundDropDbl tEndDbl (sampleFn :: f) = -- ivp -- where -- energyWith x v = z </\> (v <*> v <+> (toD 20) <*> x) -- system = -- HybridSystem -- { -- hybsys_componentNames = ["x","v","r","y","tt"], -- hybsys_modeFields = Map.fromList [(modeMove1, odeMove), (modeMove2, odeMove)], -- hybsys_modeInvariants = Map.fromList [(modeMove1, invariantMove), (modeMove2, invariantMove)], -- hybsys_eventModeSwitchesAndResetFunctions = -- Map.fromList -- [ -- (eventBounce1, (modeMove1, resetBounce)), -- (eventBounce2, (modeMove2, resetBounce)), -- (eventDrop, (modeMove2, resetDrop)) -- ], -- hybsys_eventSpecification = eventSpecMap -- } -- modeMove1 = HybSysMode "move1" -- modeMove2 = HybSysMode "move2" -- odeMove :: [f] -> [f] -- odeMove [x,v,r,y,tt] = -- [v, -- newConstFnFromSample x (toD $ -10), -- newConstFnFromSample r (toD 0), -- newConstFnFromSample y (toD 0), -- newConstFnFromSample tt (toD 1)] ---- invariantMove = id -- invariantMove [x,v,r,y,tt] = -- [xNN <\/> x2, -- v <\/> ((neg absV) </\> absV), -- rNN, -- y, tt] -- {- making use of the energy conservation law: -- (v)^2 + 2gx = r -- -- which implies -- |v| = sqrt(r - 2gx) -- x = (r - (v)^2) / 2g -- -} -- where -- rNN = makeNonneg r -- xNN = y <+> (makeNonneg (x <-> y)) -- absV = sqrtOut $ makeNonneg $ rNN <-> ((toD 20) <*> xNN) -- x2 = (rNN <-> (makeNonneg $ v <*> v)) </> (toD 20) -- eventBounce1 = HybSysEventKind "bounce1" -- eventBounce2 = HybSysEventKind "bounce2" -- pruneBounce [_x,v,r,y,tt] = [y, neg (makeNonneg (neg v)),r,y,tt] -- resetBounce :: [f] -> [f] -- resetBounce [x,v,r,y,tt] = -- [x, -- ((-0.5 :: Double) |<*> v), -- y2g <+> ((r <-> y2g) </>| (4 :: Double)), -- Kinetic energy is scaled by 1/4 -- y, tt] -- where -- y2g = (20 :: Double) |<*> y -- potential energy -- eventDrop = HybSysEventKind "drop" -- pruneDrop [x,v,r,y,_tt] = [x,v,r,y,tDrop] -- resetDrop :: [f] -> [f] -- resetDrop [x,v,r,y,tt] = -- [x, v, -- zP </\> r, -- include 0 to create a refinement fixed point (hack?) -- newConstFnFromSample y groundDrop, -- tt] -- where -- zP = newConstFnFromSample r z -- eventSpecMap mode -- | mode == modeMove1 = -- eventsBounce eventBounce1 `Map.union` eventsDrop -- | mode == modeMove2 = -- eventsBounce eventBounce2 -- where -- eventsDrop = -- Map.singleton eventDrop $ -- ([False, False, True, True, False], tDip, const (Just True), pruneDrop) -- where -- tDip [_x,_v,_r, _y,tt] = tDropP <-> tt -- where -- tDropP = newConstFnFromSample tt tDrop -- eventsBounce eventBounce = -- Map.singleton eventBounce $ -- ([True, True, True, False, False], xDip, vNegative, pruneBounce) -- where -- xDip [x,_v,_r,y,_tt] = x <-> y -- vNegative [_x,v,_r,_y,_tt] = (v <? z) -- -- ivp :: HybridIVP f -- ivp = -- HybridIVP -- { -- hybivp_description = description, -- hybivp_system = system, -- hybivp_tVar = "t", -- hybivp_tStart = z, -- hybivp_tEnd = tEnd, -- hybivp_initialStateEnclosure = -- Map.singleton modeMove1 initValues, -- hybivp_maybeExactStateAtTEnd = Nothing -- } -- description = -- "if t = " ++ show tDrop ++ " then post(y) = " ++ show groundDrop -- ++ "else (if x = y && v <= 0 then post(v) = -0.5*(pre(v)) else x'' = -10, y' = 0)" -- ++ "; x(" ++ show tStart ++ ") = " ++ show initX -- ++ ", v(" ++ show tStart ++ ") = " ++ show initV -- ++ ", r(" ++ show tStart ++ ") ∊ " ++ show initR -- ++ "; y(" ++ show tStart ++ ") = " ++ show initY -- initValues@[initX, initV, initR, initY, _initTT] = -- [toD 5,toD 0, -- energyWith initX initV, -- groundInit, -- toD 0] :: [Domain f] ---- initValues@[initX, initX'] = [0,0] :: [Domain f] -- tStart = hybivp_tStart ivp -- [groundInit, tDrop, groundDrop, tEnd] = map toD [groundInitDbl, tDropDbl, groundDropDbl, tEndDbl] -- z = toD 0 -- toD = dblToReal sampleDom -- sampleDom = getSampleDomValue sampleFn -- --ivpTwoBouncingBallsDrop_AtTime :: -- (Var f ~ String, -- HasConstFns f, -- Neg f, -- ArithInOut.RoundedSubtr f, -- ArithInOut.RoundedMixedMultiply f Double, -- ArithInOut.RoundedMixedAdd f Double, -- ArithInOut.RoundedReal (Domain f), -- RefOrd.IntervalLike (Domain f), -- Show (Domain f) -- ) -- => -- Double -> -- Double -> -- Double -> -- Double -> -- Double -> -- f -> -- HybridIVP f --ivpTwoBouncingBallsDrop_AtTime -- groundInitDbl tDrop1Dbl tDrop2PreDbl groundDropDbl tEndDbl (sampleFn :: f) = -- ivp -- where -- g = 9.81 :: Double -- c = 0.8 :: Double -- tDrop2Dbl = tDrop2PreDbl + 1 -- system = -- HybridSystem -- { -- hybsys_componentNames = ["x1","v1","y1","x2","v2","y2","tt"], -- hybsys_modeFields = Map.fromList [(modeMove, odeMove)], -- hybsys_modeInvariants = Map.fromList [(modeMove, invariantMove)], -- hybsys_eventModeSwitchesAndResetFunctions = -- Map.fromList -- [ -- (eventBounce1, (modeMove, resetBounce1)) -- , -- (eventDrop1, (modeMove, resetDrop1)) -- , -- (eventBounce2, (modeMove, resetBounce2)) -- , -- (eventDrop2, (modeMove, resetDrop2)) -- ], -- hybsys_eventSpecification = eventSpecMap -- } -- modeMove = HybSysMode "move" -- odeMove :: [f] -> [f] -- odeMove [x1,v1,y1,x2,v2,y2,tt] = -- [v1, -- newConstFnFromSample x1 (toD (-g)), -- newConstFnFromSample y1 (toD 0), -- v2, -- newConstFnFromSample x2 (toD (-g)), -- newConstFnFromSample y2 (toD 0), -- newConstFnFromSample tt (toD 1)] ---- invariantMove = id -- invariantMove [x1,v1,y1,x2,v2,y2,tt] = -- [y1 <+> (makeNonneg (x1 <-> y1)),v1,y1, -- y2 <+> (makeNonneg (x2 <-> y2)),v2,y2, -- tt] -- eventBounce1 = HybSysEventKind "bounce1" -- eventBounce2 = HybSysEventKind "bounce2" -- pruneBounce1 [_x1,v1,y1,x2,v2,y2,tt] = -- [y1, neg (makeNonneg (neg v1)),y1, -- x2,v2,y2, -- tt] -- pruneBounce2 [x1,v1,y1,_x2,v2,y2,tt] = -- [x1,v1,y1, -- y2, neg (makeNonneg (neg v2)),y2, -- tt] -- resetBounce1 :: [f] -> [f] -- resetBounce1 [x1,v1,y1,x2,v2,y2,tt] = -- [x1, ((-c) |<*> v1), y1, -- x2,v2,y2, -- tt] -- resetBounce2 [x1,v1,y1,x2,v2,y2,tt] = -- [x1,v1,y1, -- x2, ((-c) |<*> v2), y2, -- tt] -- eventDrop1 = HybSysEventKind "drop1" -- eventDrop2 = HybSysEventKind "drop2" -- pruneDrop1 [x1,v1,y1,x2,v2,y2,_tt] = [x1,v1,y1,x2,v2,y2,tDrop1] -- pruneDrop2 [x1,v1,y1,x2,v2,y2,_tt] = [x1,v1,y1,x2,v2,y2,tDrop2] -- resetDrop1 :: [f] -> [f] -- resetDrop1 [x1,v1,y1,x2,v2,y2,tt] = -- [x1, v1, newConstFnFromSample y1 groundDrop, -- x2,v2,y2, -- tt <+>| (1 :: Double)] -- jump tt to avoid another drop event (hack!!) -- resetDrop2 [x1,v1,y1,x2,v2,y2,tt] = -- [x1,v1,y1, -- x2, v2, newConstFnFromSample y2 groundDrop, -- tt <+>| (1 :: Double)] -- jump tt to avoid another drop event (hack!!) -- eventSpecMap _mode = -- Map.unions [eventsBounce1, eventsDrop1, eventsBounce2, eventsDrop2] -- where -- eventsDrop1 = -- Map.singleton eventDrop1 -- ([False, False, True, False, False, False, True], tDip1, tNearDrop1, pruneDrop1) -- where -- tDip1 [_x1,_v1,_y1,_x2,_v2,_y2,tt] = tDrop1P <-> tt -- where -- tDrop1P = newConstFnFromSample tt tDrop1 -- tNearDrop1 [_x1,_v1,_y1,_x2,_v2,_y2,tt] = tt <? (tDrop1 <+> (toD 0.5)) -- eventsDrop2 = -- Map.singleton eventDrop2 -- ([False, False, False, False, False, True, True], tDip2, tNearDrop2, pruneDrop2) -- where -- tDip2 [_x1,_v1,_y1,_x2,_v2,_y2,tt] = tDrop2P <-> tt -- where -- tDrop2P = newConstFnFromSample tt tDrop2 -- tNearDrop2 [_x1,_v1,_y1,_x2,_v2,_y2,tt] = tt <? (tDrop2 <+> (toD 0.5)) -- eventsBounce1 = -- Map.singleton eventBounce1 $ -- ([True, True, False, False, False, False, False], -- x1Dip, v1Negative, pruneBounce1) -- where -- x1Dip [x1,_v1,y1,_x2,_v2,_y2,_tt] = x1 <-> y1 -- v1Negative [_x1,v1,_y1,_x2,_v2,_y2,_tt] = (v1 <? z) -- eventsBounce2 = -- Map.singleton eventBounce2 $ -- ([False, False, False, True, True, False, False], -- x2Dip, v2Negative, pruneBounce2) -- where -- x2Dip [_x1,_v1,_y1,x2,_v2,y2,_tt] = x2 <-> y2 -- v2Negative [_x1,_v1,_y1,_x2,v2,_y2,_tt] = (v2 <? z) -- -- ivp :: HybridIVP f -- ivp = -- HybridIVP -- { -- hybivp_description = description, -- hybivp_system = system, -- hybivp_tVar = "t", -- hybivp_tStart = z, -- hybivp_tEnd = tEnd, -- hybivp_initialStateEnclosure = -- Map.singleton modeMove initValues, -- hybivp_maybeExactStateAtTEnd = Nothing -- } -- description = -- "if t = " ++ show tDrop1 ++ " then post(y1) = " ++ show groundDrop -- ++ "else (if x1 = y1 && v1 <= 0 then post(v1) = -0.5*(pre(v1)) else x1'' = -10, y1' = 0)" -- ++ "if t = " ++ show tDrop2 ++ " then post(y2) = " ++ show groundDrop -- ++ "else (if x2 = y2 && v2 <= 0 then post(v2) = -0.5*(pre(v2)) else x2'' = -10, y2' = 0)" -- ++ "; x1(" ++ show tStart ++ ") = " ++ show initX1 -- ++ ", v1(" ++ show tStart ++ ") = " ++ show initV1 -- ++ "; y1(" ++ show tStart ++ ") = " ++ show initY1 -- ++ "; x2(" ++ show tStart ++ ") = " ++ show initX2 -- ++ ", v2(" ++ show tStart ++ ") = " ++ show initV2 -- ++ "; y2(" ++ show tStart ++ ") = " ++ show initY2 -- initValues@[initX1, initV1, initY1, initX2, initV2, initY2, _initTT] = -- [toD 30,toD 14,groundInit, -- toD 30,toD 25,groundInit, -- z] :: [Domain f] -- tStart = hybivp_tStart ivp -- [groundInit, tDrop1, tDrop2, groundDrop, tEnd] = map toD [groundInitDbl, tDrop1Dbl, tDrop2Dbl, groundDropDbl, tEndDbl] -- z = toD 0 -- toD = dblToReal sampleDom -- sampleDom = getSampleDomValue sampleFn -- -- --ivpTwoBouncingBallsEnergyDrop_AtTime :: -- (Var f ~ String, -- HasConstFns f, -- RefOrd.RoundedLattice f, -- Neg f, -- ArithInOut.RoundedSubtr f, -- ArithInOut.RoundedMixedAdd f Double, -- ArithInOut.RoundedMixedMultiply f Double, -- ArithInOut.RoundedMixedDivide f Double, -- ArithInOut.RoundedReal (Domain f), -- RefOrd.IntervalLike (Domain f), -- ArithInOut.RoundedSquareRoot (Domain f), -- Show (Domain f) -- ) -- => -- Double -> -- Double -> -- Double -> -- Double -> -- Double -> -- f -> -- HybridIVP f --ivpTwoBouncingBallsEnergyDrop_AtTime -- groundInitDbl tDrop1Dbl tDrop2PreDbl groundDropDbl tEndDbl (sampleFn :: f) = -- ivp -- where -- tDrop2Dbl = tDrop2PreDbl + 1 -- g = 9.81 :: Double -- c = 0.8 :: Double -- energyWith x v = z </\> (v <*> v <+> (toD 20) <*> x) -- system = -- HybridSystem -- { -- hybsys_componentNames = ["x1","v1","r1","y1","x2","v2","r2","y2","tt"], -- hybsys_modeFields = Map.fromList [(modeMove, odeMove)], -- hybsys_modeInvariants = Map.fromList [(modeMove, invariantMove)], -- hybsys_eventModeSwitchesAndResetFunctions = -- Map.fromList -- [ -- (eventBounce1, (modeMove, resetBounce1)), -- (eventDrop1, (modeMove, resetDrop1)) -- , -- (eventBounce2, (modeMove, resetBounce2)), -- (eventDrop2, (modeMove, resetDrop2)) -- ], -- hybsys_eventSpecification = eventSpecMap -- } -- modeMove = HybSysMode "move" -- odeMove :: [f] -> [f] -- odeMove [x1,v1,r1,y1,x2,v2,r2,y2,tt] = -- [v1, -- newConstFnFromSample x1 (toD (-g)), -- newConstFnFromSample r1 (toD 0), -- newConstFnFromSample y1 (toD 0), -- v2, -- newConstFnFromSample x2 (toD (-g)), -- newConstFnFromSample r2 (toD 0), -- newConstFnFromSample y2 (toD 0), -- newConstFnFromSample tt (toD 1)] ---- invariantMove = id -- invariantMove [x1,v1,r1,y1,x2,v2,r2,y2,tt] = -- [x1NN <\/> x1E, -- v1 <\/> ((neg absV1) </\> absV1), -- r1NN, -- y1, -- x2NN <\/> x2E, -- v2 <\/> ((neg absV2) </\> absV2), -- r2NN, -- y2, -- tt] -- {- making use of the energy conservation law: -- (v)^2 + 2gx = r -- -- which implies -- |v| = sqrt(r - 2gx) -- x = (r - (v)^2) / 2g -- -} -- where -- r1NN = makeNonneg r1 -- x1NN = y1 <+> (makeNonneg (x1 <-> y1)) -- absV1 = sqrtOut $ makeNonneg $ r1NN <-> ((2*g) |<*> x1NN) -- x1E = (r1NN <-> (makeNonneg $ v1 <*> v1)) </>| (2*g) -- r2NN = makeNonneg r2 -- x2NN = y2 <+> (makeNonneg (x2 <-> y2)) -- absV2 = sqrtOut $ makeNonneg $ r2NN <-> ((2*g) |<*> x2NN) -- x2E = (r2NN <-> (makeNonneg $ v2 <*> v2)) </>| (2*g) -- eventBounce1 = HybSysEventKind "bounce1" -- eventBounce2 = HybSysEventKind "bounce2" -- pruneBounce1 [_x1,v1,r1,y1,x2,v2,r2,y2,tt] = -- [y1, neg (makeNonneg (neg v1)),r1,y1, -- x2,v2,r2,y2, -- tt] -- pruneBounce2 [x1,v1,r1,y1,_x2,v2,r2,y2,tt] = -- [x1,v1,r1,y1, -- y2, neg (makeNonneg (neg v2)),r2,y2, -- tt] -- resetBounce1 :: [f] -> [f] -- resetBounce1 [x1,v1,r1,y1,x2,v2,r2,y2,tt] = -- [x1, -- ((-c) |<*> v1), -- yyg1 <+> ((c*c) |<*> (r1 <-> yyg1)), -- Kinetic energy is scaled by c^2 -- y1, -- x2,v2,r2,y2, -- tt] -- where -- yyg1 = (2*g) |<*> y1 -- resetBounce2 [x1,v1,r1,y1,x2,v2,r2,y2,tt] = -- [x1,v1,r1,y1, -- x2, -- ((-c) |<*> v2), -- yyg2 <+> ((c*c) |<*> (r2 <-> yyg2)), -- Kinetic energy is scaled by c^2 -- y2, -- tt] -- where -- yyg2 = (2*g) |<*> y2 -- eventDrop1 = HybSysEventKind "drop1" -- eventDrop2 = HybSysEventKind "drop2" -- pruneDrop1 [x1,v1,r1,y1,x2,v2,r2,y2,_tt] = -- [x1,v1,r1,y1,x2,v2,r2,y2,tDrop1] -- pruneDrop2 [x1,v1,r1,y1,x2,v2,r2,y2,_tt] = -- [x1,v1,r1,y1,x2,v2,r2,y2,tDrop2] -- resetDrop1 :: [f] -> [f] -- resetDrop1 [x1,v1,r1,y1,x2,v2,r2,y2,tt] = -- [x1, v1, -- zP </\> r1, -- include 0 to create a refinement fixed point (hack!!) -- newConstFnFromSample y1 groundDrop, -- x2,v2,r2,y2, -- tt <+>| (1 :: Double)] -- move clock to avoid another drop event (hack!!) -- where -- zP = newConstFnFromSample tt z -- resetDrop2 [x1,v1,r1,y1,x2,v2,r2,y2,tt] = -- [x1,v1,r1,y1, -- x2, v2, -- zP </\> r2, -- include 0 to create a refinement fixed point (hack!!) -- newConstFnFromSample y2 groundDrop, -- tt <+>| (1 :: Double)] -- move clock to avoid another drop event (hack!!) -- where -- zP = newConstFnFromSample tt z -- eventSpecMap _mode = -- Map.unions [eventsBounce1, eventsDrop1, eventsBounce2, eventsDrop2] -- where -- eventsDrop1 = -- Map.singleton eventDrop1 -- ([False, False, True, True, False, False, False, False, True], tDip1, tNearDrop1, pruneDrop1) -- where -- tDip1 [_x1,_v1,_r1,_y1,_x2,_v2,_r2,_y2,tt] = tDrop1P <-> tt -- where -- tDrop1P = newConstFnFromSample tt tDrop1 -- tNearDrop1 [_x1,_v1,_r1,_y1,_x2,_v2,_r2,_y2,tt] = tt <? (tDrop1 <+> (toD 0.5)) -- eventsDrop2 = -- Map.singleton eventDrop2 -- ([False, False, False, False, False, False, True, True, True], tDip2, tNearDrop2, pruneDrop2) -- where -- tDip2 [_x1,_v1,_r1,_y1,_x2,_v2,_r2,_y2,tt] = tDrop2P <-> tt -- where -- tDrop2P = newConstFnFromSample tt tDrop2 -- tNearDrop2 [_x1,_v1,_r1,_y1,_x2,_v2,_r2,_y2,tt] = tt <? (tDrop2 <+> (toD 0.5)) -- eventsBounce1 = -- Map.singleton eventBounce1 $ -- ([True, True, True, False, False, False, False, False, False], -- x1Dip, v1Negative, pruneBounce1) -- where -- x1Dip [x1,_v1,_r1,y1,_x2,_v2,_r2,_y2,_tt] = x1 <-> y1 -- v1Negative [_x1,v1,_r1,_y1,_x2,_v2,_r2,_y2,_tt] = (v1 <? z) -- eventsBounce2 = -- Map.singleton eventBounce2 $ -- ([False, False, False, False, True, True, True, False, False], -- x2Dip, v2Negative, pruneBounce2) -- where -- x2Dip [_x1,_v1,_r1,_y1,x2,_v2,_r2,y2,_tt] = x2 <-> y2 -- v2Negative [_x1,_v1,_r1,_y1,_x2,v2,_r2,_y2,_tt] = (v2 <? z) -- -- ivp :: HybridIVP f -- ivp = -- HybridIVP -- { -- hybivp_description = description, -- hybivp_system = system, -- hybivp_tVar = "t", -- hybivp_tStart = z, -- hybivp_tEnd = tEnd, -- hybivp_initialStateEnclosure = -- Map.singleton modeMove initValues, -- hybivp_maybeExactStateAtTEnd = Nothing -- } -- description = -- "if t = " ++ show tDrop1 ++ " then post(y1) = " ++ show groundDrop -- ++ "else (if x1 = y1 && v1 <= 0 then post(v1) = -" ++ show c ++ "*(pre(v1)) else x1'' = -" ++ show g ++ ", y1' = 0)" -- ++ "if t = " ++ show tDrop2 ++ " then post(y2) = " ++ show groundDrop -- ++ "else (if x2 = y2 && v2 <= 0 then post(v2) = -" ++ show c ++ "*(pre(v2)) else x2'' = -" ++ show g ++ ", y2' = 0)" -- ++ "; x1(" ++ show tStart ++ ") = " ++ show initX1 -- ++ ", v1(" ++ show tStart ++ ") = " ++ show initV1 -- ++ ", r1(" ++ show tStart ++ ") ∊ " ++ show initR1 -- ++ "; y1(" ++ show tStart ++ ") = " ++ show initY1 -- ++ "; x2(" ++ show tStart ++ ") = " ++ show initX2 -- ++ ", v2(" ++ show tStart ++ ") = " ++ show initV2 -- ++ ", r2(" ++ show tStart ++ ") ∊ " ++ show initR2 -- ++ "; y2(" ++ show tStart ++ ") = " ++ show initY2 -- initValues@[initX1, initV1, initR1, initY1, initX2, initV2, initR2, initY2, _initTT] = -- [toD 30,toD 14,energyWith initX1 initV1,groundInit, -- toD 30,toD 25,energyWith initX2 initV2,groundInit, -- z] :: [Domain f] ---- initValues@[initX, initX'] = [0,0] :: [Domain f] -- tStart = hybivp_tStart ivp -- [groundInit, tDrop1, tDrop2, groundDrop, tEnd] = -- map toD [groundInitDbl, tDrop1Dbl, tDrop2Dbl, groundDropDbl, tEndDbl] -- z = toD 0 -- toD = dblToReal sampleDom -- sampleDom = getSampleDomValue sampleFn -- --ivpBouncingSpring_AtTime :: -- (Var f ~ String, -- HasConstFns f, -- ArithInOut.RoundedMixedAdd f Double, -- ArithInOut.RoundedMixedMultiply f Double, -- ArithInOut.RoundedReal (Domain f), -- RefOrd.IntervalLike (Domain f), -- Show (Domain f) -- ) -- => -- Double -> -- f -> -- HybridIVP f --ivpBouncingSpring_AtTime tEndDbl (sampleFn :: f) = -- ivp -- where -- system = -- HybridSystem -- { -- hybsys_componentNames = ["x","v"], -- hybsys_modeFields = Map.fromList [(modeMove, odeMove)], -- hybsys_modeInvariants = Map.fromList [(modeMove, invariantMove)], -- hybsys_eventModeSwitchesAndResetFunctions = -- Map.fromList [(eventBounce, (modeMove, resetBounce))], -- hybsys_eventSpecification = eventSpecMap -- } -- modeMove = HybSysMode "move" -- odeMove :: [f] -> [f] -- odeMove [x,v] = [v, (-1 :: Double) |<*> x] -- invariantMove [x,v] = [(toD 1) <+> (makeNonneg (x <-> (toD 1))), v] -- eventBounce = HybSysEventKind "bounce" -- pruneBounce [_x,v] = [toD 1, neg $ makeNonneg $ neg v] -- resetBounce :: [f] -> [f] -- resetBounce [x,v] = -- [x, (-0.5 :: Double) |<*> v] ---- [newConstFnFromSample v 0, (0 :: Double) |<*> v] -- eventSpecMap _mode = -- Map.singleton eventBounce $ -- ([True, True], xDip, vNegative, pruneBounce) -- where -- xDip [x,_v] = x <+>| (-1 :: Double) -- vNegative [_x,v] = (v <? z) -- -- ivp :: HybridIVP f -- ivp = -- HybridIVP -- { -- hybivp_description = description, -- hybivp_system = system, -- hybivp_tVar = "t", -- hybivp_tStart = z, -- hybivp_tEnd = tEnd, -- hybivp_initialStateEnclosure = -- Map.singleton modeMove initValues, -- hybivp_maybeExactStateAtTEnd = Nothing -- } -- description = -- "if x = 1 && v <= 0 then post(v) = -0.5*pre(v) else x'' = -10x" -- ++ "; x(" ++ show tStart ++ ") = " ++ show initX -- ++ ", v(" ++ show tStart ++ ") = " ++ show initX' -- initValues@[initX, initX'] = [toD 1,toD 1] :: [Domain f] -- tStart = hybivp_tStart ivp -- z = toD 0 -- tEnd = toD tEndDbl -- toD = dblToReal sampleDom -- sampleDom = getSampleDomValue sampleFn -- --ivpTwoTanks_AfterZeno :: -- (Var f ~ String, -- HasConstFns f, -- ArithInOut.RoundedReal (Domain f), -- RefOrd.IntervalLike (Domain f), -- Show (Domain f) -- ) -- => -- Double -> -- f -> -- HybridIVP f --ivpTwoTanks_AfterZeno tEndMinusTZenoDbl (sampleFn :: f) = -- ivp -- where -- v1 = toD 2 -- v2 = toD 3 -- w = toD 4 -- tZenoDbl = 2 -- tEndDbl = tEndMinusTZenoDbl + tZenoDbl -- system = -- HybridSystem -- { -- hybsys_componentNames = ["x1","x2"], -- hybsys_modeFields = Map.fromList [(modeFill1, odeFill1), (modeFill2, odeFill2)], -- hybsys_modeInvariants = Map.fromList [(modeFill1, invariant), (modeFill2, invariant)], -- hybsys_eventModeSwitchesAndResetFunctions = -- Map.fromList [(event1To2, (modeFill2, id)), (event2To1, (modeFill1, id))], -- hybsys_eventSpecification = eventSpecMap -- } -- modeFill1 = HybSysMode "fill1" -- modeFill2 = HybSysMode "fill2" -- odeFill1 :: [f] -> [f] -- odeFill1 [_x1,_x2] = [newConstFnFromSample _x1 (w <-> v1), newConstFnFromSample _x1 (neg v2)] -- odeFill2 :: [f] -> [f] -- odeFill2 [_x1,_x2] = [newConstFnFromSample _x1 (neg v1), newConstFnFromSample _x1 (w <-> v2)] -- invariant [x1,x2] = [makeNonneg x1, makeNonneg x2] -- event1To2 = HybSysEventKind "1To2" -- event2To1 = HybSysEventKind "2To1" -- prune1To2 [x1,_x2] = [x1, toD 0] -- prune2To1 [_x1,x2] = [toD 0, x2] -- -- eventSpecMap (HybSysMode "fill1") = -- Map.singleton event1To2 $ -- ([True, True], x2Dip, const (Just True), prune1To2) -- where -- x2Dip [_x1,x2] = x2 -- eventSpecMap (HybSysMode "fill2") = -- Map.singleton event2To1 $ -- ([True, True], x1Dip, const (Just True), prune2To1) -- where -- x1Dip [x1,_x2] = x1 -- -- ivp :: HybridIVP f -- ivp = -- HybridIVP -- { -- hybivp_description = description, -- hybivp_system = system, -- hybivp_tVar = "t", -- hybivp_tStart = z, -- hybivp_tEnd = tEnd, -- hybivp_initialStateEnclosure = -- Map.singleton modeFill1 initValues, -- hybivp_maybeExactStateAtTEnd = Just $ -- Map.fromList -- [ -- (modeFill1, [toD 0,toD 0]), -- (modeFill2, [toD 0,toD 0]) -- ] -- } -- description = -- "" -- ++ "if fill1 then (if x2 = 0 then fill2 else x1' = 4-2, x2' = -3)" -- ++ "\n if fill2 then (if x1 = 0 then fill1 else x1' = -2, x2' = 4-3)" -- ++ "\n ; x1(" ++ show tStart ++ ") = " ++ show initX1 -- ++ ", x2(" ++ show tStart ++ ") = " ++ show initX2 -- initValues@[initX1, initX2] = [toD 1,toD 1] :: [Domain f] -- tStart = hybivp_tStart ivp -- z = toD 0 -- tEnd = toD tEndDbl -- toD = dblToReal sampleDom -- sampleDom = getSampleDomValue sampleFn ivpTwoTanks :: (Var f ~ String, HasConstFns f, ArithInOut.RoundedReal (Domain f), RefOrd.IntervalLike (Domain f), HasConsistency (Domain f), Show (Domain f) ) => Double {-^ minimum level that triggers switch (>= 0) -} -> f -> HybridIVP f ivpTwoTanks rD (sampleFn :: f) = ivp where v1 = toD 2 v2 = toD 3 w = toD 4 r = toD rD system = HybridSystem { hybsys_componentNames = ["x1","x2"], hybsys_modeFields = Map.fromList [(modeFill1, odeFill1), (modeFill2, odeFill2) ], hybsys_modeInvariants = Map.fromList [(modeFill1, invariant), (modeFill2, invariant) ], hybsys_eventSpecification = eventSpecMap } modeFill1 = HybSysMode "fill1" modeFill2 = HybSysMode "fill2" odeFill1 :: [f] -> [f] odeFill1 [_x1,_x2] = [newConstFnFromSample _x1 (w <-> v1), newConstFnFromSample _x1 (neg v2) ] odeFill2 :: [f] -> [f] odeFill2 [_x1,_x2] = [newConstFnFromSample _x1 (neg v1), newConstFnFromSample _x1 (w <-> v2) ] invariant [x1,x2] = do let x1Limit = NumOrd.minOut x2 r let x2Limit = NumOrd.minOut x1 r -- x1MlimNN <- makeNonneg (x1 <-> x1Limit) let x1AboveLim = x1MlimNN <+> x1Limit x2MlimNN <- makeNonneg (x2 <-> x2Limit) let x2AboveLim = x2MlimNN <+> x2Limit -- x1New <- isect x1AboveLim x1 x2New <- isect x2AboveLim x2 return [x1New, x2New] eventSpecMap mode | mode == modeFill1 = Map.singleton event1To2 $ (modeFill2, id, [True, True], prune1To2) | mode == modeFill2 = Map.singleton event2To1 $ (modeFill1, id, [True, True], prune2To1) event1To2 = HybSysEventKind "1To2" event2To1 = HybSysEventKind "2To1" prune1To2 _ [x1,x2] = do _ <- isect x2 r return [x1, r] prune2To1 _ [x1,x2] = do _ <- isect x1 r return [r, x2] ivp :: HybridIVP f ivp = HybridIVP { hybivp_description = description, hybivp_system = system, hybivp_tVar = "t", hybivp_tStart = z, hybivp_tEnd = z, -- will be overridden hybivp_initialStateEnclosure = Map.singleton modeFill1 initValues, hybivp_maybeExactStateAtTEnd = Nothing } description = "" ++ "2T-S" ++ "\n ; x1(" ++ show tStart ++ ") = " ++ show initX1 ++ ", x2(" ++ show tStart ++ ") = " ++ show initX2 initValues@[initX1, initX2] = [toD 1,toD 1] :: [Domain f] tStart = hybivp_tStart ivp z = toD 0 toD = dblToReal sampleDom sampleDom = getSampleDomValue sampleFn ivpTwoTanksSum :: (Var f ~ String, HasConstFns f, ArithInOut.RoundedReal (Domain f), RefOrd.IntervalLike (Domain f), HasConsistency (Domain f), Show (Domain f) ) => Double {-^ minimum level that triggers switch (>= 0) -} -> f -> HybridIVP f ivpTwoTanksSum rD (sampleFn :: f) = ivp where v1 = toD 2 v2 = toD 3 w = toD 4 r = toD rD system = HybridSystem { hybsys_componentNames = ["x1","x2","x12"], hybsys_modeFields = Map.fromList [(modeFill1, odeFill1), (modeFill2, odeFill2) ], hybsys_modeInvariants = Map.fromList [(modeFill1, invariant), (modeFill2, invariant) ], hybsys_eventSpecification = eventSpecMap } modeFill1 = HybSysMode "fill1" modeFill2 = HybSysMode "fill2" odeFill1 :: [f] -> [f] odeFill1 [_x1,_x2,_x12] = [newConstFnFromSample _x1 (w <-> v1), newConstFnFromSample _x1 (neg v2), newConstFnFromSample _x1 (w <-> v1 <-> v2) ] odeFill2 :: [f] -> [f] odeFill2 [_x1,_x2,_x12] = [newConstFnFromSample _x1 (neg v1), newConstFnFromSample _x1 (w <-> v2), newConstFnFromSample _x1 (w <-> v1 <-> v2) ] invariant [x1,x2,x12] = do let x1Limit = NumOrd.minOut x2 r let x2Limit = NumOrd.minOut x1 r -- x1MlimNN <- makeNonneg (x1 <-> x1Limit) let x1AboveLim = x1MlimNN <+> x1Limit x2MlimNN <- makeNonneg (x2 <-> x2Limit) let x2AboveLim = x2MlimNN <+> x2Limit x12NN <- makeNonneg x12 -- $ NumOrd.maxOut (zero x12) x12 -- x12mx2 <- makeNonneg $ x12NN <-> x2AboveLim x1New <- isect x1AboveLim x12mx2 x12mx1 <- makeNonneg $ x12NN <-> x1AboveLim x2New <- isect x2AboveLim x12mx1 -- let x1px2 = x1AboveLim <+> x2AboveLim x12New <- isect x12NN x1px2 return [x1New, x2New, x12New] eventSpecMap mode | mode == modeFill1 = Map.singleton event1To2 $ (modeFill2, id, [True, True, True], prune1To2) | mode == modeFill2 = Map.singleton event2To1 $ (modeFill1, id, [True, True, True], prune2To1) event1To2 = HybSysEventKind "1To2" event2To1 = HybSysEventKind "2To1" prune1To2 _ [x1,x2, x12] = do _ <- isect x2 r return [x1, r, x12] prune2To1 _ [x1,x2, x12] = do _ <- isect x1 r return [r, x2, x12] ivp :: HybridIVP f ivp = HybridIVP { hybivp_description = description, hybivp_system = system, hybivp_tVar = "t", hybivp_tStart = z, hybivp_tEnd = z, -- will be overridden hybivp_initialStateEnclosure = Map.singleton modeFill1 initValues, hybivp_maybeExactStateAtTEnd = Nothing -- Just $ -- HybridSystemUncertainState -- { -- hybstate_modes = Set.fromList [modeFlow], -- hybstate_values = [0, 0, 0] -- } } description = "" ++ "2T-S" ++ "\n ; x1(" ++ show tStart ++ ") = " ++ show initX1 ++ ", x2(" ++ show tStart ++ ") = " ++ show initX2 ++ ", x12(" ++ show tStart ++ ") = " ++ show initX12 initValues@[initX1, initX2, initX12] = [toD 1,toD 1,toD 2] :: [Domain f] tStart = hybivp_tStart ivp z = toD 0 toD = dblToReal sampleDom sampleDom = getSampleDomValue sampleFn ivp2BeadColumnEnergy :: (Var f ~ String, HasConstFns f, Neg f, ArithInOut.RoundedSubtr f, ArithInOut.RoundedMixedMultiply f Double, ArithInOut.RoundedReal (Domain f), RefOrd.IntervalLike (Domain f), HasConsistency (Domain f), ArithInOut.RoundedSquareRoot (Domain f), Show (Domain f) ) => f -> HybridIVP f ivp2BeadColumnEnergy (sampleFn :: f) = ivp where energyWith x v = (v <*> v <+> (toD 20) <*> x) system = HybridSystem { hybsys_componentNames = ["x1","v1","r1", "x2","v2","r2"], hybsys_modeFields = Map.fromList [(modeMove, odeMove)], hybsys_modeInvariants = Map.fromList [(modeMove, invariantMove)], hybsys_eventSpecification = eventSpecMap } modeMove = HybSysMode "move" odeMove :: [f] -> [f] odeMove vars = odeMoveAux vars1 ++ odeMoveAux vars2 where (vars1, vars2) = splitAt 3 vars odeMoveAux [x,v,r] = [v, newConstFnFromSample x (toD $ -10), newConstFnFromSample r (toD 0)] odeMoveAux _ = error "internal error in odeMoveAux" invariantMove vars = do [x1,v1,r1] <- invariantMoveAux vars1 -- x1 <= x2: x2Mx1NN <- makeNonneg $ x2 <-> x1 x1New <- isect x1 (x2 <-> x2Mx1NN) x2New <- isect x2 (x2Mx1NN <+> x1) let vars2 = [x2New, v2, r2] res2 <- invariantMoveAux vars2 return $ [x1New,v1,r1] ++ res2 where (vars1, [x2,v2,r2]) = splitAt 3 vars invariantMoveAux [x,v,r] = do -- x >= 0: xNN <- makeNonneg x -- r >= 0: rNN <- makeNonneg r -- |v| = sqrt(r - 2gx): vSqr1 <- makeNonneg $ rNN <-> ((toD 20) <*> xNN) let absV = ArithInOut.sqrtOut vSqr1 vNew <- isect v ((neg absV) </\> absV) -- x = (r - (v)^2) / 2g: vSqr2 <- makeNonneg $ v <*> v let x2 = (rNN <-> vSqr2) </> (toD 20) xNew <- isect xNN x2 return [xNew, vNew, rNN] eventSpecMap _mode = Map.fromList $ [ (eventBounce1, (modeMove, resetBounce1, -- [True, True, True, True, True, True], [True, True, True, False, False, False], pruneBounce1)) , (eventBounce2, (modeMove, resetBounce2, [True, True, True, True, True, True], pruneBounce2)) ] eventBounce1 = HybSysEventKind "bc1" pruneBounce1 _ [x1,v1,r1,x2,v2,r2] = do _ <- isect z x1 v1NP <- makeNonpos v1 return $ [z,v1NP,r1,x2,v2,r2] pruneBounce1 _ _ = error "internal error in pruneBounce1" resetBounce1 [x1,v1,r1,x2,v2,r2] = [x1, (-0.5 :: Double) |<*> v1, (toDInterval 0 0.25) <*> r1, x2, v2, r2 ] resetBounce1 _ = error "internal error in resetBounce1" eventBounce2 = HybSysEventKind "bc2" pruneBounce2 _ [x1,v1,r1,x2,v2,r2] = do xNew <- isect x1 x2 v2Mv1NP <- makeNonpos $ v2 <-> v1 v1New <- isect v1 $ v2 <-> v2Mv1NP v2New <- isect v2 $ v2Mv1NP <+> v1 return $ [xNew,v1New,r1,xNew,v2New,r2] pruneBounce2 _ _ = error "internal error in pruneBounce2" resetBounce2 [x1,v1,r1,x2,v2,r2] = [x1, v2 <+> vDiffRest, -- v1+ := v2 + c(v1-v2) r2 <+> vDiffRest <*> (vDiffRest <+> ((2 :: Int) |<*> v2)), -- r1+ = (v1+)^2 + 20x -- = (v2 + c(v1-v2))^2 + 20x -- = v2^2 + 20x + 2*v2*c*(v1-v2) + (c(v1-v2))^2 -- = r2 + 2*v2*c*(v1-v2) + (c(v1-v2))^2 -- = r2 + c(v1-v2)*(c(v1-v2)+2*v2) x2, v1 <-> vDiffRest, -- v2+ := v1 - c(v1-v2) r1 <+> vDiffRest <*> (vDiffRest <-> ((2 :: Int) |<*> v1)) -- r2+ = (v2+)^2 + 20x -- = (v1 - c(v1-v2))^2 + 20x -- = v1^2 + 20x - 2*v1*c*(v1-v2) + (c(v1-v2))^2 -- = r1 - 2*v1*c*(v1-v2) + (c(v1-v2))^2 -- = r1 + c(v1-v2)*(c(v1-v2)-2*v1) ] where vDiff = (v1 <-> v2) vDiffRest = restCoeff |<*> vDiff restCoeff = 0.25 :: Double -- has to be > 0 and < 0.5 resetBounce2 _ = error "internal error in resetBounce2" ivp :: HybridIVP f ivp = HybridIVP { hybivp_description = description, hybivp_system = system, hybivp_tVar = "t", hybivp_tStart = z, hybivp_tEnd = z, hybivp_initialStateEnclosure = Map.singleton modeMove initValues, hybivp_maybeExactStateAtTEnd = Nothing } description = "2BC+" ++ "; x1(" ++ show tStart ++ ") = " ++ show initX1 ++ ", v1(" ++ show tStart ++ ") = " ++ show initX1' ++ ", r1(" ++ show tStart ++ ") ∊ " ++ show initR1 tStart = hybivp_tStart ivp initValues = [initX1, initX1', initR1, initX2, initX2', initR2] initX1 = toD 2 initX1' = toD 0 initR1 = energyWith initX1 initX1' initX2 = toD 4 initX2' = toD 0 initR2 = energyWith initX2 initX2' z = toD 0 toD = dblToReal sampleDom toDInterval l r = (toD l) </\> (toD r) sampleDom = getSampleDomValue sampleFn ivp2BeadColumnEnergyVDiff :: (Var f ~ String, HasConstFns f, Neg f, ArithInOut.RoundedSubtr f, ArithInOut.RoundedMixedMultiply f Double, ArithInOut.RoundedReal (Domain f), RefOrd.IntervalLike (Domain f), HasConsistency (Domain f), ArithInOut.RoundedSquareRoot (Domain f), Show (Domain f) ) => f -> HybridIVP f ivp2BeadColumnEnergyVDiff (sampleFn :: f) = ivp where energyWith x v = (v <*> v <+> (toD 20) <*> x) system = HybridSystem { hybsys_componentNames = ["x1","v1","r1", "x2","v2","r2","v1Mv2"], hybsys_modeFields = Map.fromList [(modeMove, odeMove)], hybsys_modeInvariants = Map.fromList [(modeMove, invariantMove)], hybsys_eventSpecification = eventSpecMap } modeMove = HybSysMode "move" odeMove :: [f] -> [f] odeMove vars = odeMoveAux vars1 ++ odeMoveAux vars2 ++ [newConstFnFromSample v1Mv2 (toD 0)] where (vars2, [v1Mv2]) = splitAt 3 vars2vDiff (vars1, vars2vDiff) = splitAt 3 vars odeMoveAux [x,v,r] = [v, newConstFnFromSample x (toD $ -10), newConstFnFromSample r (toD 0)] odeMoveAux _ = error "internal error in odeMoveAux" invariantMove vars = do [x1,v1,r1] <- invariantMoveAux vars1 -- x1 <= x2: x2Mx1NN <- makeNonneg $ x2 <-> x1 x1New <- isect x1 (x2 <-> x2Mx1NN) x2New <- isect x2 (x2Mx1NN <+> x1) -- v2 = v1 - v1Mv2: v2New <- isect v2 (v1 <-> v1Mv2) v1Mv2New <- isect v1Mv2 $ v1 <-> v2New let vars2 = [x2New, v2New, r2] res2@[_, v2New2, _] <- invariantMoveAux vars2 -- v1 = v1Mv2 + v2: v1New <- isect v1 (v1Mv2New <+> v2New2) v1Mv2New2 <- isect v1Mv2New $ v1New <-> v2New2 return $ [x1New,v1New,r1] ++ res2 ++ [v1Mv2New2] where (vars1, [x2,v2,r2,v1Mv2]) = splitAt 3 vars invariantMoveAux [x,v,r] = do -- x >= 0: xNN <- makeNonneg x -- r >= 0: rNN <- makeNonneg r -- |v| = sqrt(r - 2gx): vSqr1 <- makeNonneg $ rNN <-> ((toD 20) <*> xNN) let absV = ArithInOut.sqrtOut vSqr1 vNew <- isect v ((neg absV) </\> absV) -- x = (r - (v)^2) / 2g: vSqr2 <- makeNonneg $ v <*> v let x2 = (rNN <-> vSqr2) </> (toD 20) xNew <- isect xNN x2 return [xNew, vNew, rNN] eventSpecMap _mode = Map.fromList $ [ (eventBounce1, (modeMove, resetBounce1, -- [True, True, True, True, True, True, True], [True, True, True, False, False, False, True], pruneBounce1)) , (eventBounce2, (modeMove, resetBounce2, [True, True, True, True, True, True, True], pruneBounce2)) ] eventBounce1 = HybSysEventKind "bc1" pruneBounce1 _ [x1,v1,r1,x2,v2,r2,v1Mv2] = do _ <- isect z x1 v1NP <- makeNonpos v1 return $ [z,v1NP,r1,x2,v2,r2,v1Mv2] pruneBounce1 _ _ = error "internal error in pruneBounce1" resetBounce1 [x1,v1,r1,x2,v2,r2,v1Mv2] = [x1, (-0.5 :: Double) |<*> v1, (toDInterval 0 0.25) <*> r1, x2, v2, r2, v1Mv2 <+> ((-1.5 :: Double) |<*> v1) ] resetBounce1 _ = error "internal error in resetBounce1" eventBounce2 = HybSysEventKind "bc2" pruneBounce2 _ [x1,v1,r1,x2,v2,r2,v1Mv2] = do xNew <- isect x1 x2 -- v1 >= v2 v1Mv2New <- isect v1Mv2 (v1 <-> v2) v1Mv2NN <- makeNonneg $ v1Mv2New v1New <- isect v1 $ v1Mv2NN <+> v2 v2New <- isect v2 $ v1 <-> v1Mv2NN return $ [xNew,v1New,r1,xNew,v2New,r2,v1Mv2NN] pruneBounce2 _ _ = error "internal error in pruneBounce2" resetBounce2 [x1,v1,r1,x2,v2,r2,v1Mv2] = [x1, v2 <+> vDiffRest, -- v1+ := v2 + c(v1-v2) r2 <+> vDiffRest <*> (vDiffRest <+> ((2 :: Int) |<*> v2)), -- r1+ = (v1+)^2 + 20x -- = (v2 + c(v1-v2))^2 + 20x -- = v2^2 + 20x + 2*v2*c*(v1-v2) + (c(v1-v2))^2 -- = r2 + 2*v2*c*(v1-v2) + (c(v1-v2))^2 -- = r2 + c(v1-v2)*(c(v1-v2)+2*v2) x2, v1 <-> vDiffRest, -- v2+ := v1 - c(v1-v2) r1 <+> vDiffRest <*> (vDiffRest <-> ((2 :: Int) |<*> v1)), -- r2+ = (v2+)^2 + 20x -- = (v1 - c(v1-v2))^2 + 20x -- = v1^2 + 20x - 2*v1*c*(v1-v2) + (c(v1-v2))^2 -- = r1 - 2*v1*c*(v1-v2) + (c(v1-v2))^2 -- = r1 + c(v1-v2)*(c(v1-v2)-2*v1) (2*restCoeff - 1) |<*> v1Mv2 ] where vDiff = v1Mv2 vDiffRest = restCoeff |<*> vDiff restCoeff = 0.25 :: Double -- has to be > 0 and < 0.5 resetBounce2 _ = error "internal error in resetBounce2" ivp :: HybridIVP f ivp = HybridIVP { hybivp_description = description, hybivp_system = system, hybivp_tVar = "t", hybivp_tStart = z, hybivp_tEnd = z, hybivp_initialStateEnclosure = Map.singleton modeMove initValues, hybivp_maybeExactStateAtTEnd = Nothing } description = "2BC+" ++ "; x1(" ++ show tStart ++ ") = " ++ show initX1 ++ ", v1(" ++ show tStart ++ ") = " ++ show initX1' ++ ", r1(" ++ show tStart ++ ") ∊ " ++ show initR1 tStart = hybivp_tStart ivp initValues = [initX1, initX1', initR1, initX2, initX2', initR2, initV1MV2] initX1 = toD 2 initX1' = toD 0 initR1 = energyWith initX1 initX1' initX2 = toD 4 initX2' = toD 0 initR2 = energyWith initX2 initX2' initV1MV2 = initX1' <-> initX2' z = toD 0 toD = dblToReal sampleDom toDInterval l r = (toD l) </\> (toD r) sampleDom = getSampleDomValue sampleFn makeNonneg :: (HasZero d, NumOrd.PartialComparison d, RefOrd.IntervalLike d, Show d) => d -> Maybe d makeNonneg r | rangeContainsZero = Just $ RefOrd.fromEndpointsOut (z, rR) | alreadyNonneg = Just $ r | otherwise = Nothing where alreadyNonneg = (z <=? rL) == Just True rangeContainsZero = ((rL <=? z) == Just True) && ((z <=? rR) == Just True) z = zero r (rL, rR) = RefOrd.getEndpointsOut r makeNonpos :: (HasZero d, Neg d, NumOrd.PartialComparison d, RefOrd.IntervalLike d, Show d) => d -> Maybe d makeNonpos r = do rN <- makeNonneg $ neg r return $ neg rN isect :: (RefOrd.RoundedLattice d, HasConsistency d) => d -> d -> Maybe d isect x1 x2 = case isConsistentEff (consistencyDefaultEffort x1) meet of Just False -> Nothing _ -> Just meet where meet = x1 <\/> x2
michalkonecny/aern
aern-ivp/src/Numeric/AERN/IVP/Examples/Hybrid/Simple.hs
bsd-3-clause
130,512
0
34
43,167
25,693
14,334
11,359
-1
-1
import Language.KansasLava.Trace import Language.KansasLava.VCD import Control.Applicative import System.Environment vcdDiff :: Trace -> Trace -> String vcdDiff (Trace c1 i1 o1 p1) (Trace _ i2 o2 p2) = toVCD t where t = Trace c1 (mergeMaps i1 i2) (mergeMaps o1 o2) (mergeMaps p1 p2) mergeMaps m1 m2 = [ ("trace1_" ++ k,v) | (k,v) <- m1 ] ++ [ ("trace2_" ++ k,v) | (k,v) <- m2 ] main :: IO () main = do args <- getArgs if length args < 3 then do pname <- getProgName putStrLn "Need two ascii dumps and a signature to build diff." putStrLn $ "USAGE: " ++ pname ++ " X.shallow X.deep X.sig" else do let leftfile = args !! 0 rightfile = args !! 1 sigfile = args !! 2 shallow <- lines <$> readFile leftfile deep <- lines <$> readFile rightfile sig <- read <$> readFile sigfile let t1 = readTBF shallow sig t2 = readTBF deep sig writeFile "diff.vcd" $ vcdDiff t1 t2
andygill/kansas-lava
tests/Diff.hs
bsd-3-clause
1,140
0
13
441
361
181
180
26
2
{-# LANGUAGE OverloadedStrings #-} ----------------------------------------------------------------------------- -- | -- Module : Hasmin.Types.BgSize -- Copyright : (c) 2017 Cristian Adrián Ontivero -- License : BSD3 -- Stability : experimental -- Portability : non-portable -- ----------------------------------------------------------------------------- module Hasmin.Types.BgSize ( BgSize(..) , Auto(..) ) where import Control.Monad.Reader (Reader) import Data.Monoid ((<>)) import Data.Text.Lazy.Builder (singleton) import Hasmin.Class import Hasmin.Config import Hasmin.Types.PercentageLength -- | The CSS @auto@ keyword. data Auto = Auto deriving (Eq, Show) instance ToText Auto where toBuilder Auto = "auto" -- | CSS <https://drafts.csswg.org/css-backgrounds-3/#typedef-bg-size \<bg-size\>> -- data type, used by the @background-size@ and @background@ properties. data BgSize = Cover | Contain | BgSize1 (Either PercentageLength Auto) | BgSize2 (Either PercentageLength Auto) (Either PercentageLength Auto) deriving Show instance Eq BgSize where BgSize1 x1 == BgSize1 x2 = x1 `bgsizeArgEq` x2 BgSize2 x1 y == BgSize1 x2 = x1 `bgsizeArgEq` x2 && y == Right Auto x@BgSize1{} == y@BgSize2{} = y == x BgSize2 x1 y1 == BgSize2 x2 y2 = x1 `bgsizeArgEq` x2 && y1 `bgsizeArgEq` y2 Cover == Cover = True Contain == Contain = True _ == _ = False bgsizeArgEq :: Either PercentageLength Auto -> Either PercentageLength Auto -> Bool bgsizeArgEq (Left x) (Left y) = isZero x && isZero y || x == y bgsizeArgEq x y = x == y instance ToText BgSize where toBuilder Cover = "cover" toBuilder Contain = "contain" toBuilder (BgSize1 x) = toBuilder x toBuilder (BgSize2 x y) = toBuilder x <> singleton ' ' <> toBuilder y -- | Minifying a @\<bg-size\>@ value entails, apart from minifying the -- individual values, removing any @auto@ value in the second position (if -- present). instance Minifiable BgSize where minify (BgSize1 x) = BgSize1 <$> minifyBgSizeArg x minify (BgSize2 x y) = do nx <- minifyBgSizeArg x ny <- minifyBgSizeArg y let b = BgSize2 nx ny pure $ if True {- shouldMinifyBgSize conf -} then minifyBgSize b else b where minifyBgSize (BgSize2 l (Right Auto)) = BgSize1 l minifyBgSize z = z minify x = pure x minifyBgSizeArg :: Either PercentageLength Auto -> Reader Config (Either PercentageLength Auto) minifyBgSizeArg (Left a) = Left <$> minifyPL a minifyBgSizeArg (Right Auto) = pure $ Right Auto
contivero/hasmin
src/Hasmin/Types/BgSize.hs
bsd-3-clause
2,662
0
12
617
703
364
339
51
1
module Prototype where
plow-technologies/template-service
src/Prototype.hs
bsd-3-clause
24
0
2
4
4
3
1
1
0
-- | module VK.App.AppSettings where import VK.API appId :: Integer appId = 5082615 appScope :: [AuthPermissions] appScope = [Audio, Status]
eryx67/vk-api-example
src/VK/App/AppSettings.hs
bsd-3-clause
155
0
5
34
42
27
15
6
1