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
maybe Tips for using this guide CodeWorld editor -> can link back to CodeWorld editor program = drawingOf(wheel) wheel = text("I Love Pandas!") wheel = solidRectangle(8,4) wheel = circle(5) --5 is radius --multiple program = drawingOf(design) design = solidRectangle(4, 0.4) & solidCircle(1.2) & circle(2) -- renders the last one on top? -- make sure shapes don't overlap. I figured out my first object -- was smaller than the second so my first wa completely covered -- by second -- gallery of things people have made with CodeWorld? -- the tree was super cool! -- overlap program = drawingOf(overlap) overlap = colored(square, translucent(blue)) & colored(disk, translucent(green)) square = solidRectangle(5,5) disk = solidCircle(3) -- translated program = drawingOf(forest) forest = translated(tree, -5, 5) & translated(tree, 0, 0) & translated(tree, 5, -5) tree = colored(leaves, green) & colored(trunk, brown) leaves = sector(0, 180, 4) trunk = solidRectangle(1, 4) -- rotation rotated(square, 45) -- scale -- scale (var to pass through, x, y) -- circle(4) is an expression -- colored(text("Help"), red) is also an expression -- rectangle(1, 4) & circle(2) is an expression -- leaves & trunk is an expression -- rectangle is a function. It needs a width and a height and makes a picture -- light is a function. It needs a color, and makes another color -- that's the same name, but lighter -- drawingOf is a function. It needs a picture, and makes a program to -- draw that picture -- scaled is a function. It needs a picture and two scaling factors -- and makes a modified picture -- name it all in one program = drawingOf(diamond) diamond = rotated(rectangle(2, 2),45) -- or program = drawingOf(rotated(rectangle(2, 2), 45)) -- functions -- light is a function that needs a color and makes another Color -- it has the type Color -> Color -- circle is a function that needs a number (the radius) and makes -- a picture. It has the type Number -> Picture -- Rectangle is a function that needs two numbers, and makes a -- Picture. It has the type (Number, Number) -> Picture -- translated is a function that needs a picture and two numbers -- (x and y distance) and makes a new picture. It has the type -- (Picture, Number, Number) -> Picture
kammitama5/kammitama5.github.io
images/play_img/notes.hs
mit
2,382
1
10
514
432
252
180
-1
-1
-- What's up next? -- http://www.codewars.com/kata/542ebbdb494db239f8000046 module LazyNext where next :: Eq a => a -> [a] -> Maybe a next _ [] = Nothing next item [x] = Nothing next item (x:xs) = if x == item then Just(head xs) else next item xs
gafiatulin/codewars
src/8 kyu/LazyNext.hs
mit
249
0
8
47
100
53
47
5
2
module SuperUserSpark.Constants where import Import keywordCard :: String keywordCard = "card" keywordSpark :: String keywordSpark = "spark" keywordFile :: String keywordFile = "file" keywordInto :: String keywordInto = "into" keywordOutof :: String keywordOutof = "outof" keywordKindOverride :: String keywordKindOverride = "kind" keywordLink :: String keywordLink = "link" keywordCopy :: String keywordCopy = "copy" keywordAlternatives :: String keywordAlternatives = "alternatives" linkKindSymbol :: String linkKindSymbol = "l->" copyKindSymbol :: String copyKindSymbol = "c->" unspecifiedKindSymbol :: String unspecifiedKindSymbol = "->" bracesChars :: [Char] bracesChars = ['{', '}'] linespaceChars :: [Char] linespaceChars = [' ', '\t'] endOfLineChars :: [Char] endOfLineChars = ['\n', '\r'] whitespaceChars :: [Char] whitespaceChars = linespaceChars ++ endOfLineChars lineDelimiter :: String lineDelimiter = ";" branchDelimiter :: String branchDelimiter = ":" quotesChar :: Char quotesChar = '"' lineCommentStr :: String lineCommentStr = "#" blockCommentStrs :: (String, String) blockCommentStrs = ("[[", "]]") sparkExtension :: String sparkExtension = "sus"
NorfairKing/super-user-spark
src/SuperUserSpark/Constants.hs
mit
1,189
0
5
168
275
168
107
46
1
{-# htermination enumFromThenTo :: () -> () -> () -> [()] #-}
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/full_haskell/Prelude_enumFromThenTo_2.hs
mit
62
0
2
12
3
2
1
1
0
module Control.Monad.Classes.Except where import qualified Control.Monad.Trans.Except as Exc import qualified Control.Monad.Trans.Maybe as Mb import qualified Control.Exception as E import Control.Monad import Control.Monad.Trans.Class import GHC.Prim (Proxy#, proxy#) import Control.Monad.Classes.Core import Control.Monad.Classes.Effects import Data.Peano (Peano (..)) type instance CanDo IO (EffExcept e) = True type instance CanDo (Exc.ExceptT e m) eff = ExceptCanDo e eff type instance CanDo (Mb.MaybeT m) eff = ExceptCanDo () eff type family ExceptCanDo e eff where ExceptCanDo e (EffExcept e) = True ExceptCanDo e eff = False class Monad m => MonadExceptN (n :: Peano) e m where throwN :: Proxy# n -> (e -> m a) instance Monad m => MonadExceptN Zero e (Exc.ExceptT e m) where throwN _ = Exc.throwE instance E.Exception e => MonadExceptN Zero e IO where throwN _ = E.throwIO instance Monad m => MonadExceptN Zero () (Mb.MaybeT m) where throwN _ _ = mzero instance (MonadTrans t, Monad (t m), MonadExceptN n e m, Monad m) => MonadExceptN (Succ n) e (t m) where throwN _ = lift . throwN (proxy# :: Proxy# n) -- | The @'MonadExcept' e m@ constraint asserts that @m@ is a monad stack -- that supports throwing exceptions of type @e@ type MonadExcept e m = MonadExceptN (Find (EffExcept e) m) e m -- | Throw an exception throw :: forall a e m . MonadExcept e m => e -> m a throw = throwN (proxy# :: Proxy# (Find (EffExcept e) m)) runExcept :: Exc.ExceptT e m a -> m (Either e a) runExcept = Exc.runExceptT runMaybe :: Mb.MaybeT m a -> m (Maybe a) runMaybe = Mb.runMaybeT
strake/monad-classes.hs
Control/Monad/Classes/Except.hs
mit
1,605
0
11
296
596
324
272
-1
-1
-- | A utility module containing data definitions common to the rest of the -- code. This file is forbidden from having dependencies on any other part -- of the codebase, except for other libraries (such as -- Graphics.Rendering.OpenGL.Monad and its cousins). -- -- In all cases, the dependency graph should be acyclic. module Util.Defs where import Prelewd -- | The (x, y) coordinates of a point on the screen, measured from the bottom, -- left corner. type Coord = (Int, Int) -- | If you were to draw an axis-aligned bounding box around an object, -- Dimensions would represent the (x, y) lengths of the sides. type Dimensions = (Int, Int)
bfops/Chess
src/Util/Defs.hs
mit
661
0
5
131
43
32
11
4
0
-- Lists alphabet = ['a'..'z'] -- This breaks out to the full alphabet -- lists are lazy by default, so this pulls only the first 20 first20Mults x = take 20 [0,x..] -- cycle creates a cycle between elements, generating a repeating sequence -- repeat just repeats the same value over and over first20MultsComp x = firstN x 20 firstN x n = [i * x | i <- [1..n]] cartesianProduct x y = [(a,b)|a <- [1..x], b <- [1..y]] -- zip only creates pairs as long as there is a matching index in both lists zipped = zip [1..10] ['a'..'i'] rightTriangleWithPerim n = [(a,b,c) | c <- [1..n], b <- [1..c], a <- [1..b], -- such that (a^2)+(b^2) == (c^2), a < b && b < c, a + b + c == n]
ChrisCoffey/haskell_sandbox
c_1/first_func.hs
mit
746
10
10
211
279
153
126
12
1
module Mck.AST where newtype VarId = VarId String newtype TypeId = TypeId String newtype Agent = Agent String newtype ProtocolId = ProtocolId String newtype Label = Label String newtype Constant = Const String data JointProtocol = JointProtocol Environment [Protocol] data Environment = Env [TypeDec] [VarDec] [Definition] (Maybe EnvInitCond) [EnvAgentDec] (Maybe TransitionBlock) [EnvFairness] [EnvSpec] data TypeDec = TypeDec TypeId VarType data Definition = Def Var Expr data EnvAgentDec = EnvAgentDec Agent ProtocolId [Var] data EnvInitCond = InitDec InitFromDec TransitionBlock data EnvFairness = Fairness BoolTransitionExpr data InitFromDec = Uniform | AllInit data TransitionBlock = Block [TransitionStmt] data TransitionStmt = TBlockStmt TransitionBlock | TIfClause TransitionClause [TransitionClause] (Maybe TransitionStmt) | TIfBool BoolTransitionExpr TransitionStmt TransitionStmt | TSkip | TAssign VarId Expr | TRandom [Var] BoolExpr data TransitionClause = TC BoolTransitionExpr TransitionStmt data Protocol = Protocol ProtocolId EnvVarParams LocalVars [Definition] ProtocolBlock data EnvVarParams = EV [VarDec] data LocalVars = LV [VarDec] (Maybe LocalVarInitCond) data LocalVarInitCond = LVAllInit | LVExpr Expr | LVInitDec InitFromDec TransitionBlock data ProtocolBlock = PBlock [LabelledStmt] data LabelledStmt = LS ProtocolStmt (Maybe Label) data ProtocolStmt = PBlockStmt ProtocolBlock | PIfClause Clause [Clause] (Maybe LabelledStmt) | PDo Clause [Clause] (Maybe LabelledStmt) (Maybe LabelledStmt) | PIfBool BoolExpr LabelledStmt LabelledStmt | PWhile BoolExpr LabelledStmt | PSkip | PAssign VarId Expr | PRandom [Var] BoolExpr | PAction Action [ActionAssignment] data Clause = Clause BoolExpr LabelledStmt data Action = AConstant Constant | AWrite Var Expr | ARead VarId Var data ActionAssignment = AAssign Var Expr data BoolTransitionExpr = BTEVarPrime VarPrime | BTEConstant Constant | BTEObject LocalObject | BTEIn Var VarType | BTEAEq ArithExpr ArithExpr | BTEANeq ArithExpr ArithExpr | BTEEEq EnumExpr EnumExpr | BTEENeq EnumExpr EnumExpr | BTEARel RelOp ArithExpr ArithExpr | BTEERel RelOp EnumExpr EnumExpr | BTEBOp BoolOp BoolTransitionExpr BoolTransitionExpr | BTENeg BoolTransitionExpr | BTEParen BoolTransitionExpr data Expr = BExpr BoolExpr | AExpr ArithExpr | EExpr EnumExpr data BoolExpr = BEVarPrime VarPrime | BEConstant Constant | BEIn Var VarType | BEAEq ArithExpr ArithExpr | BEANeq ArithExpr ArithExpr | BEEEq EnumExpr EnumExpr | BEENeq EnumExpr EnumExpr | BEARel RelOp ArithExpr ArithExpr | BEERel RelOp EnumExpr EnumExpr | BEBOp BoolOp BoolTransitionExpr BoolTransitionExpr | BENeg BoolTransitionExpr | BEParen BoolTransitionExpr data ArithExpr = AEVarPrime VarPrime | AEInt Integer | AEOp ArithOp ArithExpr ArithExpr | AEParen ArithExpr data EnumExpr = EEVarPrime VarPrime | EEConstant Constant | EEPrev EnumExpr | EENext EnumExpr | EEParen EnumExpr data VarType = EnumType [Constant] | RangeType Integer Integer data VarDec = VarDec VarId Type data Type = Observable RawType | Plain RawType data RawType = RawType TypeId | Array TypeId Integer data Var = Var VarId | ArraySelf VarId | ArrayAccess VarId Integer data VarPrime = Primed Var | UnPrimed Var data LocalObject = LocalObject Constant Constant data BoolOp = And | Or | Implies | Equiv | Xor data ArithOp = Plus | Minus data RelOp = Lt | Lte | Gt | Gte data EnvSpec = Obs
thinkmoore/influence-checker
src/Mck/AST.hs
mit
4,237
0
8
1,335
923
529
394
90
0
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE StrictData #-} {-# LANGUAGE TupleSections #-} -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-fsx-filesystem-windowsconfiguration.html module Stratosphere.ResourceProperties.FSxFileSystemWindowsConfiguration where import Stratosphere.ResourceImports -- | Full data type definition for FSxFileSystemWindowsConfiguration. See -- 'fSxFileSystemWindowsConfiguration' for a more convenient constructor. data FSxFileSystemWindowsConfiguration = FSxFileSystemWindowsConfiguration { _fSxFileSystemWindowsConfigurationActiveDirectoryId :: Maybe (Val Text) , _fSxFileSystemWindowsConfigurationAutomaticBackupRetentionDays :: Maybe (Val Integer) , _fSxFileSystemWindowsConfigurationCopyTagsToBackups :: Maybe (Val Bool) , _fSxFileSystemWindowsConfigurationDailyAutomaticBackupStartTime :: Maybe (Val Text) , _fSxFileSystemWindowsConfigurationThroughputCapacity :: Maybe (Val Integer) , _fSxFileSystemWindowsConfigurationWeeklyMaintenanceStartTime :: Maybe (Val Text) } deriving (Show, Eq) instance ToJSON FSxFileSystemWindowsConfiguration where toJSON FSxFileSystemWindowsConfiguration{..} = object $ catMaybes [ fmap (("ActiveDirectoryId",) . toJSON) _fSxFileSystemWindowsConfigurationActiveDirectoryId , fmap (("AutomaticBackupRetentionDays",) . toJSON) _fSxFileSystemWindowsConfigurationAutomaticBackupRetentionDays , fmap (("CopyTagsToBackups",) . toJSON) _fSxFileSystemWindowsConfigurationCopyTagsToBackups , fmap (("DailyAutomaticBackupStartTime",) . toJSON) _fSxFileSystemWindowsConfigurationDailyAutomaticBackupStartTime , fmap (("ThroughputCapacity",) . toJSON) _fSxFileSystemWindowsConfigurationThroughputCapacity , fmap (("WeeklyMaintenanceStartTime",) . toJSON) _fSxFileSystemWindowsConfigurationWeeklyMaintenanceStartTime ] -- | Constructor for 'FSxFileSystemWindowsConfiguration' containing required -- fields as arguments. fSxFileSystemWindowsConfiguration :: FSxFileSystemWindowsConfiguration fSxFileSystemWindowsConfiguration = FSxFileSystemWindowsConfiguration { _fSxFileSystemWindowsConfigurationActiveDirectoryId = Nothing , _fSxFileSystemWindowsConfigurationAutomaticBackupRetentionDays = Nothing , _fSxFileSystemWindowsConfigurationCopyTagsToBackups = Nothing , _fSxFileSystemWindowsConfigurationDailyAutomaticBackupStartTime = Nothing , _fSxFileSystemWindowsConfigurationThroughputCapacity = Nothing , _fSxFileSystemWindowsConfigurationWeeklyMaintenanceStartTime = Nothing } -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-fsx-filesystem-windowsconfiguration.html#cfn-fsx-filesystem-windowsconfiguration-activedirectoryid fsfswcActiveDirectoryId :: Lens' FSxFileSystemWindowsConfiguration (Maybe (Val Text)) fsfswcActiveDirectoryId = lens _fSxFileSystemWindowsConfigurationActiveDirectoryId (\s a -> s { _fSxFileSystemWindowsConfigurationActiveDirectoryId = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-fsx-filesystem-windowsconfiguration.html#cfn-fsx-filesystem-windowsconfiguration-automaticbackupretentiondays fsfswcAutomaticBackupRetentionDays :: Lens' FSxFileSystemWindowsConfiguration (Maybe (Val Integer)) fsfswcAutomaticBackupRetentionDays = lens _fSxFileSystemWindowsConfigurationAutomaticBackupRetentionDays (\s a -> s { _fSxFileSystemWindowsConfigurationAutomaticBackupRetentionDays = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-fsx-filesystem-windowsconfiguration.html#cfn-fsx-filesystem-windowsconfiguration-copytagstobackups fsfswcCopyTagsToBackups :: Lens' FSxFileSystemWindowsConfiguration (Maybe (Val Bool)) fsfswcCopyTagsToBackups = lens _fSxFileSystemWindowsConfigurationCopyTagsToBackups (\s a -> s { _fSxFileSystemWindowsConfigurationCopyTagsToBackups = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-fsx-filesystem-windowsconfiguration.html#cfn-fsx-filesystem-windowsconfiguration-dailyautomaticbackupstarttime fsfswcDailyAutomaticBackupStartTime :: Lens' FSxFileSystemWindowsConfiguration (Maybe (Val Text)) fsfswcDailyAutomaticBackupStartTime = lens _fSxFileSystemWindowsConfigurationDailyAutomaticBackupStartTime (\s a -> s { _fSxFileSystemWindowsConfigurationDailyAutomaticBackupStartTime = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-fsx-filesystem-windowsconfiguration.html#cfn-fsx-filesystem-windowsconfiguration-throughputcapacity fsfswcThroughputCapacity :: Lens' FSxFileSystemWindowsConfiguration (Maybe (Val Integer)) fsfswcThroughputCapacity = lens _fSxFileSystemWindowsConfigurationThroughputCapacity (\s a -> s { _fSxFileSystemWindowsConfigurationThroughputCapacity = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-fsx-filesystem-windowsconfiguration.html#cfn-fsx-filesystem-windowsconfiguration-weeklymaintenancestarttime fsfswcWeeklyMaintenanceStartTime :: Lens' FSxFileSystemWindowsConfiguration (Maybe (Val Text)) fsfswcWeeklyMaintenanceStartTime = lens _fSxFileSystemWindowsConfigurationWeeklyMaintenanceStartTime (\s a -> s { _fSxFileSystemWindowsConfigurationWeeklyMaintenanceStartTime = a })
frontrowed/stratosphere
library-gen/Stratosphere/ResourceProperties/FSxFileSystemWindowsConfiguration.hs
mit
5,291
0
12
397
628
355
273
47
1
module Graphics.Render.Light( module L , enlightNormal , enlightNormal' , enlightSimple ) where import Prelude as P hiding ((<*)) import Graphics.Light as L import Graphics.GPipe import Data.Vec as Vec import Math.Vector -- | Transforms color with alpha-as-intensity to GPU color liftVec4Color :: Vec4 Float -> Vec3 (Fragment Float) liftVec4Color vcpu = Vec.take n3 vRGBA `smult` Vec.get n3 vRGBA where vRGBA :: Vec4 (Fragment Float) vRGBA = toGPU vcpu v `smult` s = Vec.map (*s) v enlightSimple :: -- | Diffuse texture Texture2D RGBAFormat -- | Ambient color, alpha is entensity -> Vec4 Float -- | Additional color modifier, the fourth component is intensity -> Vec4 Float -- | Fragment uv pos -> Vec2 (Fragment Float) -- | Resulting color -> Color RGBAFormat (Fragment Float) enlightSimple tex ambientColor colorMod uv = RGBA fragColor fragColorA where (RGBA diffuseColor diffuseColorA) = sample (Sampler Point Wrap) tex uv ambient = liftVec4Color ambientColor modifier = liftVec4Color colorMod itensity = ambient + 1 fragColor :: Vec3 (Fragment Float) fragColor = (diffuseColor + modifier) * itensity fragColorA = diffuseColorA -- | Performs dynamic lighting of fragments with given set of lights enlightNormal :: Vec2 Int -- ^ Resolution of screen -- | Diffuse texture -> Texture2D RGBAFormat -- | Normal texture -> Texture2D RGBAFormat -- | Ambient color, alpha is entensity -> Vec4 Float -- | Additional color modifier, the fourth component is intensity -> Vec4 Float -- | Lights that are used to enlight -> [Light Float] -- | Inverse of VP matrix -> Mat44 Float -- | Fragment uv pos -> Vec2 (Fragment Float) -- | Resulting color -> Color RGBAFormat (Fragment Float) enlightNormal size tex ntex ambientColor colorMod lightsCPU vpInverse uv = enlightNormal' size tex ntex ambientColor colorMod lightsCPU vpInverse uv uv -- | More general function than enlightNormal, accepts different uvs for diffuse and normal textures enlightNormal' :: Vec2 Int -- ^ Resolution of screen -- | Diffuse texture -> Texture2D RGBAFormat -- | Normal texture -> Texture2D RGBAFormat -- | Ambient color, alpha is entensity -> Vec4 Float -- | Additional color modifier, the fourth component is intensity -> Vec4 Float -- | Lights that are used to enlight -> [Light Float] -- | Inverse of VP matrix -> Mat44 Float -- | Fragment uv pos for diffuse texture -> Vec2 (Fragment Float) -- | Fragment uv pos for normal texture -> Vec2 (Fragment Float) -- | Resulting color -> Color RGBAFormat (Fragment Float) enlightNormal' size tex ntex ambientColor colorMod lightsCPU vpInverse uvDiff uvNorm = P.foldl combineLights (RGBA 0 0) $ enlightLight <$> lightsCPU where v `smult` s = Vec.map (*s) v combineLights (RGBA accRGB accAlpha) (RGBA lightRGB lightAlpha) = RGBA (accRGB + lightRGB)--(accRGB `smult` (1 - accAlpha) + lightRGB `smult` lightAlpha) (accAlpha + (1 - accAlpha)*lightAlpha) enlightLight lightCPU = RGBA fragColor fragColorA where (RGBA diffuseColor diffuseColorA) = sample (Sampler Point Wrap) tex uvDiff (RGBA normalMap _) = sample (Sampler Point Wrap) ntex uvNorm (xSize :. ySize :. ()) = toGPU $ Vec.map fromIntegral size light :: Light (Fragment Float) light = toGPU lightCPU lightPos = lightPosition light lColorRGB = lightColor light power = lightPower light powerLoss = lightPowerLoss light (fx:.fy:.fz:.fw:.()) = toGPU vpInverse `multmv` ( (fragX/xSize * 2 - 1):. (fragY/ySize * 2 - 1):. (fragDepth * 2 - 1) :. 1:.()) fragmentPos :: Vec3 (Fragment Float) fragmentPos = ((fx/fw) :. (fy/fw) :. (fz/fw) :. ()) lightDir = case light of (DirectionalLight d _ _) -> d _ -> lightPos - fragmentPos dist = Vec.norm lightDir n = Vec.normalize $ normalMap `smult` 2.0 - 1 l = Vec.normalize lightDir diffuse :: Vec3 (Fragment Float) diffuse = (lColorRGB `smult` power) `smult` maxB (Vec.dot n l) 0.0 ambient = liftVec4Color ambientColor modifier = liftVec4Color colorMod attenuation = case light of (ConeLight _ coneDir conAngle _ _ _) -> let da = (negate l) `angleBetweenVecs` coneDir distAtten = 1.0 / (attentation powerLoss dist * (conAngle/2*pi)) in ifB (da <* conAngle) distAtten -- Soft border, the formula is based on sigmoid function (let x = da - conAngle p = 0.99 k = 100 in distAtten / (1 + exp (k*x + log ( (1-p)/p ))) ) _ -> 1.0 / (attentation powerLoss dist) itensity = ambient + diffuse `smult` attenuation finalColor = (diffuseColor + modifier) * itensity fragColor :: Vec3 (Fragment Float) fragColor = finalColor fragColorA = diffuseColorA
NCrashed/sinister
src/client/Graphics/Render/Light.hs
mit
5,009
6
22
1,281
1,384
728
656
98
3
{-# OPTIONS -Wall #-} import Data.Functor import qualified Data.List as List import qualified Data.Maybe as Maybe import qualified Data.Set as Set import Data.Text (Text) import Helpers.Grid (Grid, (!), (//)) import qualified Helpers.Grid as Grid import Helpers.Parse import Helpers.Point (Point (..)) import Text.Parsec data SeaCucumber = FacingEast | FacingSouth deriving (Eq) instance Show SeaCucumber where show FacingEast = "> " show FacingSouth = "v " type SeaFloor = Grid (Maybe SeaCucumber) main :: IO () main = do seaFloor <- Grid.fromList <$> parseLinesIO parser let steps = iterate step seaFloor let answer = Maybe.fromJust (List.elemIndex True (zipWith (==) steps (tail steps))) + 1 print answer step :: SeaFloor -> SeaFloor step = stepSouth . stepEast stepEast :: SeaFloor -> SeaFloor stepEast = stepInDirection nextPoint FacingEast where nextPoint (Point _ minX, Point _ maxX) (Point y x) = Point y (inc minX maxX x) stepSouth :: SeaFloor -> SeaFloor stepSouth = stepInDirection nextPoint FacingSouth where nextPoint (Point minY _, Point maxY _) (Point y x) = Point (inc minY maxY y) x stepInDirection :: ((Point, Point) -> Point -> Point) -> SeaCucumber -> SeaFloor -> SeaFloor stepInDirection updatePoint toMove seaFloor = let bounds = Grid.bounds seaFloor points = Grid.allPointsList seaFloor values = zip points $ map (seaFloor !) points available = Set.fromList $ map fst $ filter (Maybe.isNothing . snd) values candidates = filter ((== Just toMove) . snd) values canMove = filter (\(_, new, _) -> new `Set.member` available) $ map (\(point, seaCucumber) -> (point, updatePoint bounds point, seaCucumber)) candidates updates = map (\(old, _, _) -> (old, Nothing)) canMove ++ map (\(_, new, seaCucumber) -> (new, seaCucumber)) canMove in seaFloor // updates inc :: Int -> Int -> Int -> Int inc lowest highest value = (value + 1) `mod` (highest - lowest + 1) + lowest parser :: Parsec Text () [Maybe SeaCucumber] parser = many1 seaCucumber where seaCucumber = try (char '>' $> Just FacingEast) <|> try (char 'v' $> Just FacingSouth) <|> (char '.' $> Nothing)
SamirTalwar/advent-of-code
2021/AOC_25.hs
mit
2,200
1
17
453
842
451
391
-1
-1
{-# LANGUAGE ForeignFunctionInterface, EmptyDataDecls, OverloadedStrings, DeriveGeneric, DeriveDataTypeable #-} {- JQuery bindings, loosely based on fay-jquery -} module JavaScript.JQuery ( JQuery(..) , Event(..) , EventType , Selector , Method(..) , AjaxSettings(..) , AjaxResult(..) , ajax , HandlerSettings(..) , addClass , animate , getAttr , setAttr , hasClass , getHtml , setHtml , getProp , setProp , removeAttr , removeClass , removeProp , getVal , setVal , getText , setText , holdReady , selectElement , selectObject , select , selectEmpty , selectWithContext , getCss , setCss , getHeight , setHeight , getWidth , setWidth , getInnerHeight , getOuterHeight , getInnerWidth , getOuterWidth , getScrollLeft , setScrollLeft , getScrollTop , setScrollTop , click , dblclick , focusin , focusout , hover , mousedown , mouseenter , mouseleave , mousemove , mouseup , on , one , triggerHandler , delegateTarget , isDefaultPrevented , isImmediatePropagationStopped , isPropagationStopped , namespace , pageX , pageY , preventDefault , stopPropagation , stopImmediatePropagation , target , timeStamp , eventType , which , blur , change , onFocus , focus , onSelect , keydown , keyup , keypress , after , afterJQuery , afterElem , append , appendJQuery , appendElem , appendTo , appendToJQuery , appendToElem , before , beforeJQuery , beforeElem , CloneType(..) , clone , detach , detachSelector , empty , insertAfter , insertAfterJQuery , insertAfterElem , insertBefore , insertBeforeJQuery , insertBeforeElem , prepend , prependJQuery , prependElem , prependTo , prependToJQuery , prependToElem , remove , removeSelector , replaceAll , replaceAllJQuery , replaceAllElem , replaceWith , replaceWithJQuery , replaceWithElem , unwrap , wrap , wrapJQuery , wrapElem , wrapAll , wrapAllJQuery , wrapAllElem , wrapInner , wrapInnerJQuery , wrapInnerElem , addSelector , addElement , addHtml , add , andSelf , children , childrenMatching , closestSelector , closest , closestElement , contents , end , eq , filter , filterElement , filterJQuery , find , findJQuery , findElement , first , has , hasElement , is , isJQuery , isElement , last , next , nextSelector , nextAll , nextAllSelector , nextUntil , nextUntilElement , not , notElement , notJQuery , offsetParent , parent , parentSelector , parents , parentsSelector , parentsUntil , parentsUntilElement , prev , prevSelector , prevAll , prevAllSelector , prevUntil , prevUntilElement , siblings , siblingsSelector , slice , sliceFromTo , stop ) where import Prelude hiding (filter, not, empty, last) import GHCJS.Marshal import GHCJS.Foreign (toJSBool, jsNull, jsFalse, jsTrue) import GHCJS.Types import GHCJS.DOM.Types ( ToJSString(..), FromJSString(..), toJSString, fromJSString , Element(..), IsElement(..), toElement, unElement) import qualified GHCJS.Foreign as F import qualified GHCJS.Foreign.Callback as F import GHCJS.Nullable import qualified JavaScript.Object as F import JavaScript.JQuery.Internal import Control.Applicative hiding (empty) import Control.Concurrent import Control.Concurrent.MVar import Control.Monad import Data.Default import Data.Maybe import Data.Text (Text) import Data.Typeable import Data.Coerce import System.IO (fixIO) type EventType = Text type Selector = Text data Method = GET | POST | PUT | DELETE deriving (Eq, Ord, Enum, Show) data AjaxSettings = AjaxSettings { asContentType :: Text , asCache :: Bool , asIfModified :: Bool , asMethod :: Method } deriving (Ord, Eq, Show, Typeable) data AjaxResult = AjaxResult { arStatus :: Int , arData :: Maybe Text } deriving (Ord, Eq, Show, Typeable) instance Default AjaxSettings where def = AjaxSettings "application/x-www-form-urlencoded; charset=UTF-8" True False GET instance ToJSRef AjaxSettings where toJSRef (AjaxSettings ct cache ifMod method) = do o <- F.create let (.=) :: Text -> JSRef -> IO () p .= v = F.setProp p v o "method" .= toJSString method "ifModified" .= toJSBool ifMod "cache" .= toJSBool cache "contentType" .= toJSString ct "dataType" .= ("text" :: JSString) return o instance ToJSString Method instance ToJSRef Method where toJSRef m = (toJSRef :: JSString -> JSRef) $ case m of GET -> "GET" POST -> "POST" PUT -> "PUT" DELETE -> "DELETE" ajax :: Text -> [(Text,Text)] -> AjaxSettings -> IO AjaxResult ajax url d s = do o <- F.create forM_ d (\(k,v) -> F.setProp k (toJSString v) o) os <- toJSRef s F.setProp ("data"::Text) o os arr <- jq_ajax (toJSString url) os dat <- F.getProp ("data"::Text) arr let d = if isNull dat then Nothing else Just (fromJSString dat) status <- fromMaybe 0 <$> (fromJSRef =<< F.getProp ("status"::Text) arr) return (AjaxResult status d) data HandlerSettings = HandlerSettings { hsPreventDefault :: Bool , hsStopPropagation :: Bool , hsStopImmediatePropagation :: Bool , hsSynchronous :: Bool , hsDescendantFilter :: Maybe Selector , hsHandlerData :: Maybe JSRef } convertHandlerSettings :: HandlerSettings -> (Bool, Bool, Bool, JSString, JSRef) convertHandlerSettings (HandlerSettings pd sp sip _ ds hd) = (pd, sp, sip, maybe jsNull toJSString ds, fromMaybe jsNull hd) instance Default HandlerSettings where def = HandlerSettings False False False True Nothing Nothing addClass :: Text -> JQuery -> IO JQuery addClass c = jq_addClass (toJSString c) animate :: F.Object -> F.Object -> JQuery -> IO JQuery animate = jq_animate getAttr :: Text -> JQuery -> IO Text getAttr a jq = fromJSString <$> jq_getAttr (toJSString a) jq setAttr :: Text -> Text -> JQuery -> IO JQuery setAttr a v = jq_setAttr (toJSString a) (toJSString v) hasClass :: Text -> JQuery -> IO Bool hasClass c jq = jq_hasClass (toJSString c) jq getHtml :: JQuery -> IO Text getHtml jq = fromJSString <$> jq_getHtml jq setHtml :: Text -> JQuery -> IO JQuery setHtml t = jq_setHtml (toJSString t) getProp :: Text -> JQuery -> IO Text getProp p jq = fromJSString <$> jq_getProp (toJSString p) jq -- fixme value can be Boolean or Number setProp :: Text -> Text -> JQuery -> IO JQuery setProp p v = jq_setProp (toJSString p) (toJSString v) removeAttr :: Text -> JQuery -> IO JQuery removeAttr a = jq_removeAttr (toJSString a) removeClass :: Text -> JQuery -> IO JQuery removeClass c = jq_removeClass (toJSString c) removeProp :: Text -> JQuery -> IO JQuery removeProp p = jq_removeProp (toJSString p) -- toggleClass :: Text -> JQuery -> IO JQuery -- toggleClass c = jq_toggleClass (toJSString c) getVal :: JQuery -> IO Text getVal jq = fromJSString <$> jq_getVal jq setVal :: Text -> JQuery -> IO JQuery setVal v = jq_setVal (toJSString v) getText :: JQuery -> IO Text getText jq = fromJSString <$> jq_getText jq setText :: Text -> JQuery -> IO JQuery setText t = jq_setText (toJSString t) holdReady :: Bool -> IO () holdReady b = jq_holdReady b selectElement :: IsElement e => e -> IO JQuery selectElement e = jq_selectElement (unElement (toElement e)) selectObject :: F.Object -> IO JQuery selectObject a = jq_selectObject (coerce a) select :: Text -> IO JQuery select q = jq_select (toJSString q) selectEmpty :: IO JQuery selectEmpty = jq_selectEmpty -- :: Text -> Either JQuery F.Object -> IO JQuery ? selectWithContext :: Text -> F.Object -> IO JQuery selectWithContext t o = jq_selectWithContext (toJSString t) (coerce o) getCss :: Text -> JQuery -> IO Text getCss t jq = fromJSString <$> jq_getCss (toJSString t) jq setCss :: Text -> Text -> JQuery -> IO JQuery setCss k v = jq_setCss (toJSString k) (toJSString v) getHeight :: JQuery -> IO Double getHeight = jq_getHeight setHeight :: Double -> JQuery -> IO JQuery setHeight = jq_setHeight getWidth :: JQuery -> IO Double getWidth = jq_getWidth setWidth :: Double -> JQuery -> IO JQuery setWidth = jq_setWidth getInnerHeight :: JQuery -> IO Double getInnerHeight = jq_getInnerHeight getInnerWidth :: JQuery -> IO Double getInnerWidth = jq_getInnerWidth getOuterHeight :: Bool -- ^ include margin? -> JQuery -> IO Double getOuterHeight b = jq_getOuterHeight b getOuterWidth :: Bool -- ^ include margin? -> JQuery -> IO Double getOuterWidth b = jq_getOuterWidth b getScrollLeft :: JQuery -> IO Double getScrollLeft = jq_getScrollLeft setScrollLeft :: Double -> JQuery -> IO JQuery setScrollLeft = jq_setScrollLeft getScrollTop :: JQuery -> IO Double getScrollTop = jq_getScrollTop setScrollTop :: Double -> JQuery -> IO JQuery setScrollTop = jq_setScrollTop click :: (Event -> IO ()) -> HandlerSettings -> JQuery -> IO (IO ()) click a = on a "click" dblclick :: (Event -> IO ()) -> HandlerSettings -> JQuery -> IO (IO ()) dblclick a = on a "dblclick" focusin :: (Event -> IO ()) -> HandlerSettings -> JQuery -> IO (IO ()) focusin a = on a "focusin" focusout :: (Event -> IO ()) -> HandlerSettings -> JQuery -> IO (IO ()) focusout a = on a "focusout" hover :: (Event -> IO ()) -> HandlerSettings -> JQuery -> IO (IO ()) hover a = on a "hover" mousedown :: (Event -> IO ()) -> HandlerSettings -> JQuery -> IO (IO ()) mousedown a = on a "mousedown" mouseenter :: (Event -> IO ()) -> HandlerSettings -> JQuery -> IO (IO ()) mouseenter a = on a "mouseenter" mouseleave :: (Event -> IO ()) -> HandlerSettings -> JQuery -> IO (IO ()) mouseleave a = on a "mouseleave" mousemove :: (Event -> IO ()) -> HandlerSettings -> JQuery -> IO (IO ()) mousemove a = on a "mousemove" mouseout :: (Event -> IO ()) -> HandlerSettings -> JQuery -> IO (IO ()) mouseout a = on a "mouseout" mouseover :: (Event -> IO ()) -> HandlerSettings -> JQuery -> IO (IO ()) mouseover a = on a "mouseover" mouseup :: (Event -> IO ()) -> HandlerSettings -> JQuery -> IO (IO ()) mouseup a = on a "mouseup" {- | Register an event handler. Use the returned IO action to remove the handler. Note that the handler will stay in memory until the returned IO action is executed, even if the DOM nodes are removed. -} on :: (Event -> IO ()) -> EventType -> HandlerSettings -> JQuery -> IO (IO ()) on a et hs jq = do cb <- if hsSynchronous hs then F.syncCallback1 F.ContinueAsync a else F.asyncCallback1 a jq_on cb et' ds hd sp sip pd jq return (jq_off cb et' ds jq >> F.releaseCallback cb) where et' = toJSString et (pd, sp, sip, ds, hd) = convertHandlerSettings hs one :: (Event -> IO ()) -> EventType -> HandlerSettings -> JQuery -> IO (IO ()) one a et hs jq = do cb <- fixIO $ \cb -> let a' = \e -> F.releaseCallback cb >> a e in if hsSynchronous hs then F.syncCallback1 F.ContinueAsync a else F.asyncCallback1 a jq_one cb et' ds hd sp sip pd jq return (jq_off cb et' ds jq >> F.releaseCallback cb) where et' = toJSString et (pd, sp, sip, ds, hd) = convertHandlerSettings hs trigger :: EventType -> JQuery -> IO () trigger et jq = jq_trigger (toJSString et) jq triggerHandler :: EventType -> JQuery -> IO () triggerHandler et jq = jq_triggerHandler (toJSString et) jq delegateTarget :: Event -> IO Element delegateTarget ev = Element <$> jq_delegateTarget ev isDefaultPrevented :: Event -> IO Bool isDefaultPrevented e = jq_isDefaultPrevented e isImmediatePropagationStopped :: Event -> IO Bool isImmediatePropagationStopped e = jq_isImmediatePropagationStopped e isPropagationStopped :: Event -> IO Bool isPropagationStopped e = jq_isPropagationStopped e namespace :: Event -> IO Text namespace e = fromJSString <$> jq_namespace e pageX :: Event -> IO Double pageX = jq_pageX pageY :: Event -> IO Double pageY = jq_pageY preventDefault :: Event -> IO () preventDefault = jq_preventDefault stopPropagation :: Event -> IO () stopPropagation = jq_stopPropagation stopImmediatePropagation :: Event -> IO () stopImmediatePropagation = jq_stopImmediatePropagation target :: Event -> IO Element target ev = Element <$> jq_target ev timeStamp :: Event -> IO Double timeStamp = jq_timeStamp eventType :: Event -> IO Text eventType e = fromJSString <$> jq_eventType e which :: Event -> IO Int which = jq_eventWhich blur :: (Event -> IO ()) -> HandlerSettings -> JQuery -> IO (IO ()) blur a = on a "blur" change :: (Event -> IO ()) -> HandlerSettings -> JQuery -> IO (IO ()) change a = on a "change" onFocus :: (Event -> IO ()) -> HandlerSettings -> JQuery -> IO (IO ()) onFocus a = on a "focus" focus :: JQuery -> IO JQuery focus = jq_focus onSelect :: (Event -> IO ()) -> HandlerSettings -> JQuery -> IO (IO ()) onSelect a = on a "select" submit :: (Event -> IO ()) -> HandlerSettings -> JQuery -> IO (IO ()) submit a = on a "submit" keydown :: (Event -> IO ()) -> HandlerSettings -> JQuery -> IO (IO ()) keydown a = on a "keydown" keyup :: (Event -> IO ()) -> HandlerSettings -> JQuery -> IO (IO ()) keyup a = on a "keyup" keypress :: (Event -> IO ()) -> HandlerSettings -> JQuery -> IO (IO ()) keypress a = on a "keypress" after :: Text -> JQuery -> IO JQuery after h jq = jq_after (coerce $ toJSString h) jq afterJQuery :: JQuery -> JQuery -> IO JQuery afterJQuery j jq = jq_after (coerce j) jq afterElem :: IsElement e => e -> JQuery -> IO JQuery afterElem e jq = jq_after (coerce . unElement $ toElement e) jq append :: Text -> JQuery -> IO JQuery append h jq = jq_append (coerce $ toJSString h) jq appendJQuery :: JQuery -> JQuery -> IO JQuery appendJQuery j jq = jq_append (coerce j) jq appendElem :: IsElement e => e -> JQuery -> IO JQuery appendElem e jq = jq_append (coerce . unElement $ toElement e) jq appendTo :: Text -> JQuery -> IO JQuery appendTo h jq = jq_appendTo (coerce $ toJSString h) jq appendToJQuery :: JQuery -> JQuery -> IO JQuery appendToJQuery j jq = jq_appendTo (coerce j) jq appendToElem :: IsElement e => e -> JQuery -> IO JQuery appendToElem e jq = jq_appendTo (coerce . unElement $ toElement e) jq before :: Text -> JQuery -> IO JQuery before h jq = jq_before (coerce $ toJSString h) jq beforeJQuery :: JQuery -> JQuery -> IO JQuery beforeJQuery j jq = jq_before (coerce j) jq beforeElem :: IsElement e => e -> JQuery -> IO JQuery beforeElem e jq = jq_before (coerce . unElement $ toElement e) jq data CloneType = WithoutDataAndEvents | WithDataAndEvents | DeepWithDataAndEvents clone :: CloneType -> JQuery -> IO JQuery clone WithoutDataAndEvents = jq_clone False False clone WithDataAndEvents = jq_clone True False clone DeepWithDataAndEvents = jq_clone True True detach :: JQuery -> IO JQuery detach = jq_detach jsNull detachSelector :: Selector -> JQuery -> IO JQuery detachSelector s = jq_detach (toJSString s) empty :: JQuery -> IO JQuery empty = jq_empty insertAfter :: Text -> JQuery -> IO JQuery insertAfter h jq = jq_insertAfter (coerce $ toJSString h) jq insertAfterJQuery :: JQuery -> JQuery -> IO JQuery insertAfterJQuery j jq = jq_insertAfter (coerce j) jq insertAfterElem :: IsElement e => e -> JQuery -> IO JQuery insertAfterElem e jq = jq_insertAfter (coerce . unElement $ toElement e) jq insertBefore :: Text -> JQuery -> IO JQuery insertBefore h jq = jq_insertBefore (coerce $ toJSString h) jq insertBeforeJQuery :: JQuery -> JQuery -> IO JQuery insertBeforeJQuery j jq = jq_insertBefore (coerce j) jq insertBeforeElem :: IsElement e => e -> JQuery -> IO JQuery insertBeforeElem e jq = jq_insertBefore (coerce . unElement $ toElement e) jq prepend :: Text -> JQuery -> IO JQuery prepend h jq = jq_prepend (coerce $ toJSString h) jq prependJQuery :: JQuery -> JQuery -> IO JQuery prependJQuery j jq = jq_prepend (coerce j) jq prependElem :: IsElement e => e -> JQuery -> IO JQuery prependElem e jq = jq_prepend (coerce . unElement $ toElement e) jq prependTo :: Text -> JQuery -> IO JQuery prependTo h jq = jq_prependTo (coerce $ toJSString h) jq prependToJQuery :: JQuery -> JQuery -> IO JQuery prependToJQuery j jq = jq_prependTo (coerce j) jq prependToElem :: IsElement e => e -> JQuery -> IO JQuery prependToElem e jq = jq_prependTo (coerce . unElement $ toElement e) jq remove :: JQuery -> IO JQuery remove = jq_remove jsNull removeSelector :: Selector -> JQuery -> IO JQuery removeSelector s = jq_remove (toJSString s) replaceAll :: Text -> JQuery -> IO JQuery replaceAll h jq = jq_replaceAll (coerce $ toJSString h) jq replaceAllJQuery :: JQuery -> JQuery -> IO JQuery replaceAllJQuery j jq = jq_replaceAll (coerce j) jq replaceAllElem :: IsElement e => e -> JQuery -> IO JQuery replaceAllElem e jq = jq_replaceAll (coerce . unElement $ toElement e) jq replaceWith :: Text -> JQuery -> IO JQuery replaceWith h jq = jq_replaceWith (coerce $ toJSString h) jq replaceWithJQuery :: JQuery -> JQuery -> IO JQuery replaceWithJQuery j jq = jq_replaceWith (coerce j) jq replaceWithElem :: IsElement e => e -> JQuery -> IO JQuery replaceWithElem e jq = jq_replaceWith (coerce . unElement $ toElement e) jq unwrap :: JQuery -> IO JQuery unwrap = jq_unwrap wrap :: Text -> JQuery -> IO JQuery wrap h jq = jq_wrap (coerce $ toJSString h) jq wrapJQuery :: JQuery -> JQuery -> IO JQuery wrapJQuery j jq = jq_wrap (coerce j) jq wrapElem :: IsElement e => e -> JQuery -> IO JQuery wrapElem e jq = jq_wrap (coerce . unElement $ toElement e) jq wrapAll :: Text -> JQuery -> IO JQuery wrapAll h jq = jq_wrapAll (coerce $ toJSString h) jq wrapAllJQuery :: JQuery -> JQuery -> IO JQuery wrapAllJQuery j jq = jq_wrapAll (coerce j) jq wrapAllElem :: IsElement e => e -> JQuery -> IO JQuery wrapAllElem e jq = jq_wrapAll (coerce . unElement $ toElement e) jq wrapInner :: Text -> JQuery -> IO JQuery wrapInner h jq = jq_wrapInner (coerce $ toJSString h) jq wrapInnerJQuery :: JQuery -> JQuery -> IO JQuery wrapInnerJQuery j jq = jq_wrapInner (coerce j) jq wrapInnerElem :: IsElement e => e -> JQuery -> IO JQuery wrapInnerElem e jq = jq_wrapInner (coerce . unElement $ toElement e) jq addSelector :: Selector -> JQuery -> IO JQuery addSelector s jq = jq_add (coerce $ toJSString s) jq addElement :: IsElement e => e -> JQuery -> IO JQuery addElement e jq = jq_add (coerce . unElement $ toElement e) jq addHtml :: Text -> JQuery -> IO JQuery addHtml h jq = jq_add (coerce $ toJSString h) jq add :: JQuery -> JQuery -> IO JQuery add j jq = jq_add (coerce j) jq -- addSelectorWithContext :: Selector -> JQuery -> JQuery -> IO JQuery -- addSelectorWithContext = undefined andSelf :: JQuery -> IO JQuery andSelf = jq_andSelf children :: JQuery -> IO JQuery children = jq_children jsNull childrenMatching :: Selector -> JQuery -> IO JQuery childrenMatching s = jq_children (toJSString s) closestSelector :: Selector -> JQuery -> IO JQuery closestSelector s jq = jq_closest (coerce $ toJSString s) jq -- closestWithContext :: Selector -> Selector -> JQuery -> IO JQuery -- closestWithContext = undefined closest :: JQuery -> JQuery -> IO JQuery closest j jq = jq_closest (coerce j) jq closestElement :: IsElement e => e -> JQuery -> IO JQuery closestElement e jq = jq_closest (coerce . unElement $ toElement e) jq contents :: JQuery -> IO JQuery contents = jq_contents -- This just isn't cool[' Can']'t we all just use map? -- each :: (Double -> Element -> Fay Bool) -> JQuery -> Fay JQuery -- each = ffi "%2['each'](%1)" end :: JQuery -> IO JQuery end = jq_end eq :: Int -> JQuery -> IO JQuery eq = jq_eq filter :: Selector -> JQuery -> IO JQuery filter s = jq_filter (coerce $ toJSString s) filterElement :: IsElement e => e -> JQuery -> IO JQuery filterElement e = jq_filter (coerce . unElement $ toElement e) filterJQuery :: JQuery -> JQuery -> IO JQuery filterJQuery j = jq_filter (coerce j) find :: Selector -> JQuery -> IO JQuery find s = jq_find (coerce $ toJSString s) findJQuery :: JQuery -> JQuery -> IO JQuery findJQuery j = jq_find (coerce j) findElement :: IsElement e => e -> JQuery -> IO JQuery findElement e = jq_find (coerce . unElement $ toElement e) first :: JQuery -> IO JQuery first = jq_first has :: Selector -> JQuery -> IO JQuery has s = jq_has (coerce $ toJSString s) hasElement :: IsElement e => e -> JQuery -> IO JQuery hasElement e = jq_has (coerce . unElement $ toElement e) is :: Selector -> JQuery -> IO Bool is s = jq_is (coerce $ toJSString s) isJQuery :: JQuery -> JQuery -> IO Bool isJQuery j = jq_is (coerce j) isElement :: IsElement e => e -> JQuery -> IO Bool isElement e = jq_is (coerce . unElement $ toElement e) last :: JQuery -> IO JQuery last = jq_last next :: JQuery -> IO JQuery next = jq_next jsNull nextSelector :: Selector -> JQuery -> IO JQuery nextSelector s = jq_next (toJSString s) nextAll :: JQuery -> IO JQuery nextAll = jq_nextAll jsNull nextAllSelector :: Selector -> JQuery -> IO JQuery nextAllSelector s = jq_nextAll (toJSString s) nextUntil :: Selector -> Maybe Selector -> JQuery -> IO JQuery nextUntil s mf = jq_nextUntil (coerce $ toJSString s) (maybe jsNull toJSString mf) nextUntilElement :: IsElement e => e -> Maybe Selector -> JQuery -> IO JQuery nextUntilElement e mf = jq_nextUntil (coerce . unElement $ toElement e) (maybe jsNull toJSString mf) not :: Selector -> JQuery -> IO JQuery not s = jq_not (coerce $ toJSString s) notElement :: IsElement e => e -> JQuery -> IO JQuery notElement e = jq_not (coerce . unElement $ toElement e) -- notElements :: [Element] -> JQuery -> IO JQuery -- notElements = jq_notElements notJQuery :: JQuery -> JQuery -> IO JQuery notJQuery j = jq_not (coerce j) offsetParent :: JQuery -> IO JQuery offsetParent = jq_offsetParent parent :: JQuery -> IO JQuery parent = jq_parent jsNull parentSelector :: String -> JQuery -> IO JQuery parentSelector s = jq_parent (toJSString s) parents :: JQuery -> IO JQuery parents = jq_parents jsNull parentsSelector :: Selector -> JQuery -> IO JQuery parentsSelector s = jq_parents (toJSString s) parentsUntil :: Selector -> Maybe Selector -> JQuery -> IO JQuery parentsUntil s mf = jq_parentsUntil (coerce $ toJSString s) (maybe jsNull (coerce . toJSString) mf) parentsUntilElement :: IsElement e => e -> Maybe Selector -> JQuery -> IO JQuery parentsUntilElement e mf = jq_parentsUntil (coerce . unElement $ toElement e) (maybe jsNull (coerce . toJSString) mf) prev :: JQuery -> IO JQuery prev = jq_prev jsNull prevSelector :: Selector -> JQuery -> IO JQuery prevSelector s = jq_prev (toJSString s) prevAll :: JQuery -> IO JQuery prevAll = jq_prevAll jsNull prevAllSelector :: String -> JQuery -> IO JQuery prevAllSelector s = jq_prevAll (toJSString s) prevUntil :: Selector -> Maybe Selector -> JQuery -> IO JQuery prevUntil s mf = jq_prevUntil (coerce $ toJSString s) (maybe jsNull toJSString mf) prevUntilElement :: IsElement e => e -> Maybe Selector -> JQuery -> IO JQuery prevUntilElement e mf = jq_prevUntil (coerce . unElement $ toElement e) (maybe jsNull toJSString mf) siblings :: JQuery -> IO JQuery siblings = jq_siblings (maybeToNullable Nothing) siblingsSelector :: Selector -> JQuery -> IO JQuery siblingsSelector s = jq_siblings (maybeToNullable (Just (toJSString s))) slice :: Int -> JQuery -> IO JQuery slice = jq_slice sliceFromTo :: Int -> Int -> JQuery -> IO JQuery sliceFromTo = jq_sliceFromTo stop :: Bool -> JQuery -> IO JQuery stop = jq_stop
mgsloan/ghcjs-jquery
JavaScript/JQuery.hs
mit
28,244
0
17
9,560
8,229
4,201
4,028
628
2
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies #-} module Web.Authenticate.SQRL.Client.Types where import Web.Authenticate.SQRL.Types import Data.ByteString (ByteString) import Data.Text (Text) import Control.Exception (SomeException) import Data.Maybe (fromMaybe) import qualified Crypto.Ed25519.Exceptions as ED25519 type FullRealm = Text type Password = Text newtype PublicLockKey = PublicLockKey { publicLockKey :: ByteString } newtype RescueCode = RescueCode { rescueCode :: Text } --newtype PrivateIdentityKey = PrivateIdentityKey { privateIdentityKey :: ByteString } newtype PrivateMasterKey = PrivateMasterKey { privateMasterKey :: ByteString } deriving (Show, Eq) newtype PrivateUnlockKey = PrivateUnlockKey { privateUnlockKey :: ByteString } deriving (Show, Eq) newtype PrivateLockKey = PrivateLockKey { privateLockKey :: ByteString } deriving (Show, Eq) class (PublicKey pub, DomainKey priv, Signature sig) => KeyPair priv pub sig | priv -> pub sig where -- | Generates a public key from a 'DomainKey'. generatePublic :: priv -> pub generatePublic = mkPublicKey . ED25519.exportPublic . ED25519.generatePublic . fromMaybe (error "KeyPair.generatePublic: importPrivate returned Nothing.") . ED25519.importPrivate . domainKey signData :: priv -> pub -> ByteString -> sig signData priv' pub' bs = let ED25519.Sig sig = ED25519.sign bs priv pub priv = fromMaybe (error "KeyPair.signData: importPrivate returned Nothing.") $ ED25519.importPrivate $ domainKey priv' pub = fromMaybe (error "KeyPair.signData: importPublic returned Nothing.") $ ED25519.importPublic $ publicKey pub' in mkSignature sig instance KeyPair DomainIdentityKey IdentityKey IdentitySignature class PrivateKey k where privateKey :: k -> ByteString mkPrivateKey :: ByteString -> k instance PrivateKey PrivateMasterKey where privateKey = privateMasterKey mkPrivateKey = PrivateMasterKey instance PrivateKey PrivateUnlockKey where privateKey = privateUnlockKey mkPrivateKey = PrivateUnlockKey instance PrivateKey PrivateLockKey where privateKey = privateLockKey mkPrivateKey = PrivateLockKey newtype DomainLockKey = DomainLockKey { domainLockKey :: ByteString } deriving (Show, Eq) newtype DomainIdentityKey = DomainIdentityKey { domainIdentityKey :: ByteString } deriving (Show, Eq) class DomainKey k where domainKey :: k -> ByteString mkDomainKey :: ByteString -> k instance DomainKey DomainLockKey where domainKey = domainLockKey mkDomainKey = DomainLockKey instance DomainKey DomainIdentityKey where domainKey = domainIdentityKey mkDomainKey = DomainIdentityKey data ClientErr = ClientErrNone | ClientErrLoginAborted | ClientErrAskAborted | ClientErrAssocAborted | ClientErrNoProfile | ClientErrWrongPassword | ClientErrSecureStorage String | ClientErrDecryptionFailed String | ClientErrThrown SomeException | ClientErrOther String deriving (Show)
TimLuq/sqrl-auth-client-hs
src/Web/Authenticate/SQRL/Client/Types.hs
mit
2,990
0
15
486
632
360
272
60
0
module TriggerSpec (spec) where import Helper import Trigger normalize :: String -> [String] normalize = normalizeErrors . normalizeTiming . normalizeSeed . lines . stripAnsiColors where normalizeTiming :: [String] -> [String] normalizeTiming = mkNormalize "Finished in " normalizeSeed :: [String] -> [String] normalizeSeed = mkNormalize "Randomized with seed " mkNormalize :: String -> [String] -> [String] mkNormalize message = map f where f line | message `isPrefixOf` line = message ++ "..." | otherwise = line normalizeErrors :: [String] -> [String] normalizeErrors xs = case xs of y : ys | "Spec.hs:" `isPrefixOf` y -> "Spec.hs:..." : normalizeErrors (removeErrorDetails ys) y : ys -> y : normalizeErrors ys [] -> [] removeErrorDetails :: [String] -> [String] removeErrorDetails xs = case xs of (_ : _ : ' ' : '|' : _) : ys -> removeErrorDetails ys _ -> xs stripAnsiColors xs = case xs of '\ESC' : '[' : ';' : ys | 'm' : zs <- dropWhile isNumber ys -> stripAnsiColors zs '\ESC' : '[' : ys | 'm' : zs <- dropWhile isNumber ys -> stripAnsiColors zs y : ys -> y : stripAnsiColors ys [] -> [] spec :: Spec spec = do describe "reloadedSuccessfully" $ do context "with GHC < 8.2.1" $ do it "detects success" $ do reloadedSuccessfully "Ok, modules loaded: Spec." `shouldBe` True context "with GHC >= 8.2.1" $ do context "with a single module" $ do it "detects success" $ do reloadedSuccessfully "Ok, 1 module loaded." `shouldBe` True context "with multiple modules" $ do it "detects success" $ do reloadedSuccessfully "Ok, 5 modules loaded." `shouldBe` True context "with GHC >= 8.2.2" $ do context "with a single module" $ do it "detects success" $ do reloadedSuccessfully "Ok, one module loaded." `shouldBe` True context "with multiple modules" $ do it "detects success" $ do reloadedSuccessfully "Ok, four modules loaded." `shouldBe` True describe "triggerAll" $ around_ withSomeSpec $ do it "runs all specs" $ do withSession ["Spec.hs", "--no-color"] $ \session -> do writeFile "Spec.hs" failingSpec (False, xs) <- silence (trigger session >> triggerAll session) normalize xs `shouldBe` [ modulesLoaded Ok ["Spec"] , "" , "foo" , "bar FAILED [1]" , "" , "Failures:" , "" , " Spec.hs:9:3: " , " 1) bar" , "" , " To rerun use: --match \"/bar/\"" , "" , "Randomized with seed ..." , "" , "Finished in ..." , "2 examples, 1 failure" , "Summary {summaryExamples = 2, summaryFailures = 1}" ] describe "trigger" $ around_ withSomeSpec $ do it "reloads and runs specs" $ do withSession ["Spec.hs", "--no-color"] $ \session -> do result <- silence (trigger session >> trigger session) fmap normalize result `shouldBe` (True, [ modulesLoaded Ok ["Spec"] , "" , "foo" , "bar" , "" , "Finished in ..." , "2 examples, 0 failures" , "Summary {summaryExamples = 2, summaryFailures = 0}" ]) context "with a module that does not compile" $ do it "stops after reloading" $ do withSession ["Spec.hs"] $ \session -> do writeFile "Spec.hs" (passingSpec ++ "foo = bar") (False, xs) <- silence (trigger session >> trigger session) normalize xs `shouldBe` [ "[1 of 1] Compiling Spec ( Spec.hs, interpreted )" , "" , "Spec.hs:..." , modulesLoaded Failed [] ] context "with a failing spec" $ do it "indicates failure" $ do withSession ["Spec.hs"] $ \session -> do writeFile "Spec.hs" failingSpec (False, xs) <- silence (trigger session) xs `shouldContain` modulesLoaded Ok ["Spec"] xs `shouldContain` "2 examples, 1 failure" it "only reruns failing specs" $ do withSession ["Spec.hs", "--no-color"] $ \session -> do writeFile "Spec.hs" failingSpec (False, xs) <- silence (trigger session >> trigger session) normalize xs `shouldBe` [ modulesLoaded Ok ["Spec"] , "" , "bar FAILED [1]" , "" , "Failures:" , "" , " Spec.hs:9:3: " , " 1) bar" , "" , " To rerun use: --match \"/bar/\"" , "" , "Randomized with seed ..." , "" , "Finished in ..." , "1 example, 1 failure" , "Summary {summaryExamples = 1, summaryFailures = 1}" ] context "after a failing spec passes" $ do it "runs all specs" $ do withSession ["Spec.hs", "--no-color"] $ \session -> do writeFile "Spec.hs" failingSpec _ <- silence (trigger session) writeFile "Spec.hs" passingSpec (True, xs) <- silence (trigger session) normalize xs `shouldBe` [ "[1 of 1] Compiling Spec ( Spec.hs, interpreted )" , modulesLoaded Ok ["Spec"] , "" , "bar" , "" , "Finished in ..." , "1 example, 0 failures" , "Summary {summaryExamples = 1, summaryFailures = 0}" , "" , "foo" , "bar" , "" , "Finished in ..." , "2 examples, 0 failures" , "Summary {summaryExamples = 2, summaryFailures = 0}" ] context "with a module that does not expose a spec" $ do it "only reloads" $ do withSession ["Spec.hs"] $ \session -> do writeFile "Spec.hs" "module Foo where" silence (trigger session >> trigger session) `shouldReturn` (True, modulesLoaded Ok ["Foo"] ++ "\n") context "with an hspec-meta spec" $ do it "reloads and runs spec" $ do withSession ["Spec.hs", "--no-color"] $ \session -> do writeFile "Spec.hs" passingMetaSpec result <- silence (trigger session >> trigger session) fmap normalize result `shouldBe` (True, [ modulesLoaded Ok ["Spec"] , "" , "foo" , "bar" , "" , "Finished in ..." , "2 examples, 0 failures" , "Summary {summaryExamples = 2, summaryFailures = 0}" ])
hspec/sensei
test/TriggerSpec.hs
mit
6,731
0
26
2,410
1,632
816
816
164
7
module Bonlang.Runtime.Bool ( or' , and' , negate' ) where import Bonlang.Lang import qualified Bonlang.Lang.Bool as B import qualified Data.Map as M import Prelude hiding (negate) booleanOp :: PrimFunc -> BonlangValue booleanOp f = BonlangClosure { cParams = ["b0", "b1"] , cEnv = M.empty , cBody = BonlangPrimFunc f } or', and' :: BonlangValue or' = booleanOp B.or and' = booleanOp B.and negate' :: BonlangValue negate' = BonlangClosure { cParams = ["b0"] , cEnv = M.empty , cBody = BonlangPrimFunc B.negate }
charlydagos/bonlang
src/Bonlang/Runtime/Bool.hs
mit
753
0
8
323
164
101
63
19
1
module Files.Utils where import qualified Control.Exception as E import qualified System.IO as I import System.FilePath ( splitDirectories, joinPath, (</>) ) import Data.Default import Data.Time.Clock.POSIX import Data.Time import Files.Data import System.Posix.Files import System.Posix.Types import System.Directory import Control.Monad import Data.Time.Format import qualified System.Posix.Files as SPF stringOfTime :: POSIXTime -> String stringOfTime time = formatTime defaultTimeLocale "%Y-%m-%d" (posixSecondsToUTCTime time) makeTime :: EpochTime -> String makeTime = show . posixSecondsToUTCTime . realToFrac ----------- -- PATHS -- ----------- curDirPath :: FilePath -> FilePath curDirPath = last . splitDirectories upDirPath :: FilePath -> FilePath upDirPath = joinPath . init . splitDirectories -- |A `maybe` flavor using the `Default` class. maybeD :: (Default b) => (a -> b) -> Maybe a -> b maybeD = maybe def -- |Gets the contente variable. Returns Nothing if the constructor is of `Unknown`. getFreeVar :: File a -> Maybe a getFreeVar (Directory _ d) = Just d getFreeVar (RegularFile _ d) = Just d getFreeVar _ = Nothing -- |Apply a function on the content variable. If there is no content variable -- for the given constructor the value from the `Default` class is used. fromFreeVar :: (Default d) => (a -> d) -> File a -> d fromFreeVar f df = maybeD f $ getFreeVar df -- |Pack the modification time into a string. packModTime :: File FileInfo -> String packModTime = fromFreeVar $ show . posixSecondsToUTCTime . realToFrac . time -- |Pack the permissions into a string, similar to what "ls -l" does. packPermissions :: File FileInfo -> String packPermissions dt = fromFreeVar (pStr . mode) dt where pStr ffm = typeModeStr ++ ownerModeStr ++ groupModeStr ++ otherModeStr where typeModeStr = case dt of Directory {} -> "d" RegularFile {} -> "-" ownerModeStr = hasFmStr SPF.ownerReadMode "r" ++ hasFmStr SPF.ownerWriteMode "w" ++ hasFmStr SPF.ownerExecuteMode "x" groupModeStr = hasFmStr SPF.groupReadMode "r" ++ hasFmStr SPF.groupWriteMode "w" ++ hasFmStr SPF.groupExecuteMode "x" otherModeStr = hasFmStr SPF.otherReadMode "r" ++ hasFmStr SPF.otherWriteMode "w" ++ hasFmStr SPF.otherExecuteMode "x" hasFmStr fm str | hasFM fm = str | otherwise = "-" hasFM fm = ffm `SPF.intersectFileModes` fm == fm
DronovIlya/filemanager-hs
src/Files/Utils.hs
gpl-2.0
2,759
0
12
789
621
332
289
59
2
-- Copyright 2013 Metamocracy LLC -- Written by Jim Snow ([email protected]) -- -- This is code related to the Polink rest API and data import/export -- for various tools. -- -- In particular, this file defines the Aeson instances that allow us to dump -- the reputation system graph in a format that Pariah understands, the Aeson -- instance for entities (needed for D3 interface Daniel is working on), and -- code to generate graphviz source. {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE FlexibleInstances #-} module PolinkAPI where import qualified Data.Text as T import qualified Data.Map as M import qualified Data.Set as S import qualified Data.List as L import Control.Lens hiding ((.=)) import Data.Aeson import Data.Time.Calendar (Day, toGregorian) import PolinkState mapMaybe f [] = [] mapMaybe f (x:xs) = case f x of Nothing -> mapMaybe f xs Just res -> res : mapMaybe f xs mToL Nothing = [] mToL (Just x) = [x] mLtoL Nothing = [] mLtoL (Just xs) = xs mStoL Nothing = [] mStoL (Just xs) = S.toList xs deMaybe :: [Maybe a] -> [a] deMaybe [] = [] deMaybe (Just x:xs) = x : deMaybe xs deMaybe (Nothing:xs) = deMaybe xs resolveEids gs eids = mapMaybe f eids where f eid = gs ^. entities . at eid resolveEidsFst :: GraphState -> [(Eid, a)] -> [(Entity, a)] resolveEidsFst gs eids = mapMaybe f eids where f (eid,x) = case gs ^. entities . at eid of Nothing -> Nothing Just e -> Just (e,x) resolveUids gs uids = mapMaybe f uids where f uid = gs ^. users . at uid resolveLids gs lids = mapMaybe f lids where f lid = gs ^. links . at lid getAllLinks :: GraphState -> Eid -> [Link] getAllLinks gs eid = let src = mStoL $ gs ^. linksBySrc . at eid dst = mStoL $ gs ^. linksByDst . at eid in mapMaybe (\lid -> gs ^. links . at lid) (src++dst) overlap :: Maybe (Day, Day) -> Maybe (Day, Bool) -> Maybe (Day, Bool) -> Bool overlap Nothing _ _ = True overlap (Just (astart, aend)) mastart maend = timeOverlap (Just astart) (Just aend) (fmap fst mastart) (fmap fst maend) -- Get all the links of a particular type. getLinks :: GraphState -> Eid -> LinkType -> Maybe (Day, Day) -> Bool -> [(Eid, Link)] getLinks gs eid lt mrange rev = case gs ^. (if rev then linksBySrc else linksByDst) . at eid of Nothing -> [] Just lids -> mapMaybe f (S.toList lids) where f lid = case gs ^. links . at lid of Nothing -> Nothing Just link -> if (link ^. ltype) == lt && overlap mrange (Just $ link ^. ldate) (link ^. lend) then Just ((link ^. (if rev then ldst else lsrc)), link) else Nothing -- Select just the Lids from a list of Ids. {- filterLids :: [Id] -> [Lid] filterLids [] = [] filterLids ((L lid):xs) = lid : (filterLids xs) filterLids (_:xs) = filterLids xs -} -- Get all the direct links associated with an issue. getIssueLinks :: GraphState -> Iid -> Maybe (Day, Day) -> [Link] getIssueLinks gs iid mrange = case gs ^. issues ^. at iid of Nothing -> [] Just issue -> mapMaybe f $ S.toList $ issue ^. itagged where f (L lid) = do link <- gs ^. links . at lid if overlap mrange (Just $ link ^. ldate) (link ^. lend) then return link else Nothing f _ = Nothing -- Find all directly reachable suborganizations of an organization. subOrgs :: GraphState -> Eid -> Maybe (Day, Day) -> [(Eid, Link)] subOrgs gs eid mrange = getLinks gs eid (PL $ PLType $ fromEnum SubOrg) mrange False superOrgs :: GraphState -> Eid -> Maybe (Day, Day) -> [(Eid, Link)] superOrgs gs eid mrange = getLinks gs eid (PL $ PLType $ fromEnum SubOrg) mrange True -- Find all members of an org. members :: GraphState -> Eid -> Maybe (Day, Day) -> [(Eid, Link)] members gs eid mrange = getLinks gs eid (PL $ PLType $ fromEnum Member) mrange False isMember :: GraphState -> Eid -> Maybe (Day, Day) -> [(Eid, Link)] isMember gs eid mrange = getLinks gs eid (PL $ PLType $ fromEnum Member) mrange True -- Find all holders of an office. offHolders :: GraphState -> Eid -> Maybe (Day, Day) -> [(Eid, Link)] offHolders gs eid mrange = getLinks gs eid (PL $ PLType $ fromEnum HoldsOffice) mrange False officesHeld :: GraphState -> Eid -> Maybe (Day, Day) -> [(Eid, Link)] officesHeld gs eid mrange = getLinks gs eid (PL $ PLType $ fromEnum HoldsOffice) mrange True -- All suborgs reachable from an org. reachableSubOrgs :: GraphState -> Eid -> Maybe (Day, Day) -> S.Set Eid reachableSubOrgs gs eid mrange = go (S.singleton eid) S.empty where go unvisited visited = if unvisited == S.empty then visited else let (e,unvs) = S.deleteFindMin unvisited in if S.member e visited then go unvs visited else let new = L.filter (\x -> not $ S.member x visited) (map fst $ subOrgs gs e mrange) in go (S.union unvs (S.fromList new)) (S.insert e visited) -- All superorgs reachable from an org. reachableSuperOrgs :: GraphState -> [Eid] -> Maybe (Day, Day) -> (S.Set Eid, S.Set Link) reachableSuperOrgs gs eids mrange = go (S.fromList eids) S.empty S.empty where go unvisited visited links = if unvisited == S.empty then (visited, links) else let (e,unvs) = S.deleteFindMin unvisited in if (S.member e visited) then go unvs visited links else let new = superOrgs gs e mrange in go (S.union unvs (S.fromList (L.filter (\x -> not $ S.member x visited) (map fst new)))) (S.insert e visited) (S.union links (S.fromList (map snd new))) -- If an organization has more members than this, we just show membership count. maxmembers = 20 -- Returns, for each entity, its sub-organizations, members, and office holders. orgchart :: GraphState -> Eid -> Maybe (Day, Day) -> [(Entity, [(Entity, Link)], Either Int [(Entity,Link)], [(Entity, Link)])] orgchart gs eid mrange = mapMaybe f (S.toList $ reachableSubOrgs gs eid mrange) where f eid2 = case gs ^. entities . at eid2 of Nothing -> Nothing Just e -> Just (e, resolveEidsFst gs (subOrgs gs eid2 mrange), mems eid2, resolveEidsFst gs (offHolders gs eid2 mrange)) -- Some groups have a lot of members; we can't show them all. mems :: Eid -> Either Int [(Entity, Link)] mems eid2 = let ms = members gs eid2 mrange mcount = length ms in if mcount > maxmembers then Left mcount else Right $ resolveEidsFst gs ms baseUrl = if production then "http://polink.org" else"http://localhost:3001" eurl (Eid id) = baseUrl ++ "/e/" ++ (show id) linkurl (Lid id) = baseUrl ++ "/l/" ++ (show id) mapRight :: (b -> c) -> Either a [b] -> [c] mapRight f (Right xs) = map f xs mapRight f (Left _) = [] mapLeft :: (a -> c) -> Either a b -> c -> c mapLeft f (Right _ ) def = def mapLeft f (Left x) def = f x entitygv :: Entity -> String entitygv e = " " ++ (show (e^. ecname)) ++ (case e ^. etype of Person _ -> " [shape=plaintext fontsize=8 URL=\"" Organization _ -> " [shape=box fontsize=9 URL=\"") ++ (eurl (_eid e)) ++ "\" target=\"_top\"]\n" -- Some link types make better visual sense if they're reversed. lswap l src dst = case (l ^. ltype) of PL plt -> case toEnum $ unPLType plt of HoldsOffice -> rev SubOrg -> rev Member -> rev _ -> fwd NL _ -> fwd where fwd = (src, dst) rev = (dst, src) linkgv :: GraphState -> Link -> String linkgv gs l = case (do s <- gs ^. entities ^. at (l ^. lsrc) d <- gs ^. entities ^. at (l ^. ldst) return (s,d)) of Nothing -> "" Just (src', dst') -> let (src, dst) = lswap l src' dst' color = case (l ^. ltype) of NL _ -> "red" PL plt -> case toEnum $ unPLType plt of HoldsOffice -> "navy" SubOrg -> "blue4" Member -> "lightseagreen" _ -> "green" in " " ++ (show $ src ^. ecname) ++ " -> " ++ (show $ dst ^. ecname) ++ " [color=" ++ color ++ " URL=\"" ++ (linkurl (l ^. lid)) ++ "\" target=\"_top\"]\n" -- Produce graphviz source for an orgchart rooted at a particular eid. -- Note: originally, I set "aspect=1.5", but that causes all kinds of -- corruption inside graphviz. -- See http://www.graphviz.org/mantisbt/view.php?id=2364 orgchartgv :: GraphState -> Eid -> Maybe (Day, Day) -> String orgchartgv gs eid mrange = case gs ^. entities . at eid of Nothing -> error "no root" Just root -> let oc = orgchart gs eid mrange -- Use intermediate Map to eliminate duplicates. allOrgs :: [Entity] allOrgs = M.elems $ M.fromList $ map eidtuple $ (concatMap (\(_,suborgs,_,_) -> (map fst suborgs)) oc) allPeople :: [Entity] allPeople = M.elems $ M.fromList $ map eidtuple $ (concatMap (\(_,_,members,_) -> (mapRight fst members)) oc) allOffs :: [Entity] allOffs = M.elems $ M.fromList $ map eidtuple $ (concatMap (\(_,_,_,offs) -> (map fst offs)) oc) allTrunc :: [(Entity, Int)] allTrunc = concatMap (\(parent, _, members, _) -> mapLeft (\count -> [(parent,count)]) members []) oc in "digraph {\n graph [bgcolor=\"transparent\"]\n" ++ (entitygv root) ++ (concatMap entitygv allOrgs) ++ (concatMap entitygv (allOffs ++ allPeople)) ++ (concatMap truncf allTrunc) ++ (concatMap linkf oc) ++ "}\n" where orglinkf src link dst = " " ++ src ++ " -> " ++ (show (dst ^. ecname)) ++ " [color=blue4 URL=\"" ++ (linkurl (_lid link)) ++ "\" target=\"_top\"]\n" memlinkf src link dst = " " ++ src ++ " -> " ++ (show (dst ^. ecname)) ++ " [color=lightseagreen URL=\"" ++ (linkurl (_lid link)) ++ "\" target=\"_top\"]\n" offlinkf src link dst = " " ++ src ++ " -> " ++ (show (dst ^. ecname)) ++ " [color=navy URL=\"" ++ (linkurl (_lid link)) ++ "\" target=\"_top\"]\n" linkf (ent, suborgs, members, offs) = let srcname = show (ent ^. ecname) in (concatMap (\(dst, link) -> orglinkf srcname link dst) suborgs) ++ (concatMap (\(dst, link) -> memlinkf srcname link dst) (mapRight id members)) ++ (concatMap (\(dst, link) -> offlinkf srcname link dst) offs) ++ (mapLeft (\count -> trunclinkf ent count) members "") truncf (parent, count) = " \"" ++ (T.unpack (parent ^. ecname)) ++ "-members\" [label=\"" ++ (show count) ++ " members\" fontsize=8 shape=plaintext]\n" trunclinkf parent count = " " ++ (show (parent ^. ecname)) ++ " -> \"" ++ (T.unpack (parent ^. ecname)) ++ "-members\" [color=green]\n" eidtuple ent = (_eid ent, ent) -- Generate a graph from all the links associated with a given issues. unique xs = S.toList (S.fromList xs) issuegv :: GraphState -> Iid -> Maybe (Day, Day) -> String issuegv gs iid mrange = "digraph {\n graph [bgcolor=\"transparent\"]\n" ++ (concatMap entitygv ents) ++ (concatMap (linkgv gs) links) ++ "}\n" where directlinks = getIssueLinks gs iid mrange directeids = concatMap (\l-> [l ^. lsrc, l ^. ldst]) directlinks indirectlinks = allParentLinks gs directeids mrange links = unique ((reverse indirectlinks) ++ directlinks) ents = resolveEids gs (unique $ concatMap (\l-> [l ^. lsrc, l ^. ldst]) links) allParentLinks :: GraphState -> [Eid] -> Maybe (Day, Day) -> [Link] allParentLinks gs eids mrange = let members :: [(Eid, Link)] members = concatMap (\eid -> isMember gs eid Nothing) eids membereids = map fst members memberlids = map snd members offices :: [(Eid, Link)] offices = concatMap (\eid -> officesHeld gs eid Nothing) eids officeeids = map fst offices officelids = map snd offices supers :: (S.Set Eid, S.Set Link) supers = reachableSuperOrgs gs (eids ++ membereids ++ officeeids) mrange supereids = S.toList $ fst supers superlids = S.toList $ snd supers in memberlids ++ officelids ++ superlids msquish :: Maybe (S.Set a) -> [a] msquish Nothing = [] msquish (Just xs) = S.toList xs -- For each entity, returns fwd pos, fwd neg, -- things it's a member or suborg of, and users that like/dislike it. -- We have to look at reverse links, because some are bi-directional. elinks :: GraphState -> [(Entity, [(Entity, PosLinkType)], [(Entity, NegLinkType)], [Entity], [Entity], [User], [User])] elinks gs = map f (M.elems (gs ^. entities)) where f ent = let eid = _eid ent (fwdpos, fwdneg) = sortLinks $ msquish $ gs ^. linksBySrc . at eid (revpos, revneg) = bidirLinks $ msquish $ gs ^. linksByDst . at eid likes = resolveUids gs $ msquish $ gs ^. like . at (E eid) dislikes = resolveUids gs $ msquish $ gs ^. dislike . at (E eid) in (ent, fwdpos++revpos, fwdneg++revneg, [], [], likes, dislikes) -- Get the list of positive and negative fwd links. sortLinks lids = slgo [] [] lids slgo pos neg [] = (resolveEidsFst gs pos, resolveEidsFst gs neg) slgo pos neg (l:ls) = case gs ^. links . at l of Nothing -> slgo pos neg ls Just link -> case link ^. ltype of PL pl -> slgo (((link ^. ldst), toEnum $ unPLType pl) : pos) neg ls NL nl -> slgo pos (((link ^. ldst), toEnum $ unNLType nl) : neg) ls -- Get the list of positive and negative backlinks that are bidirectional. bidirLinks lids = bdgo [] [] lids bdgo pos neg [] = (resolveEidsFst gs pos, resolveEidsFst gs neg) bdgo pos neg (l:ls) = case gs ^. links . at l of Nothing -> bdgo pos neg ls Just link -> case link ^. ltype of PL pl -> let plt = toEnum $ unPLType pl in if isBiDirPL plt then bdgo (((link ^. lsrc), plt) : pos) neg ls else bdgo pos neg ls NL nl -> let nlt = toEnum $ unNLType nl in if isBiDirNL nlt then bdgo pos (((link ^. lsrc), nlt) : neg) ls else bdgo pos neg ls -- Given an Entity, generate a meaningful name for the reputation system. genENameVerbose :: GraphState -> Entity -> T.Text genENameVerbose gs e = et `T.append` "-" `T.append` (T.pack $ show $ e ^. eid) `T.append` "-" `T.append` (e ^. ecname) where et = case e ^. etype of Person _ -> "person" Organization _ -> "org" genEName :: GraphState -> Entity -> T.Text genEName gs e = let (Eid id) = e ^. eid in "e" `T.append` (T.pack (show id)) -- Given a User, generate a group named after that user. genUGNameVerbose :: GraphState -> T.Text -> User -> T.Text genUGNameVerbose gs prefix u = prefix `T.append` (T.pack $ show $ u ^. uid) `T.append` "-" `T.append` (u ^. name) genUGName :: GraphState -> T.Text -> User -> T.Text genUGName gs prefix u = let (Uid id) = u ^. uid in prefix `T.append` ("u" `T.append` (T.pack $ show id)) instance ToJSON Uid where toJSON (Uid uid) = toJSON uid -- Not a complete representation of the entire state; -- this is just for the reputation system. instance ToJSON GraphState where toJSON gs = let es = map f (elinks gs) f (ent, friends, foes, memberof, suborgof, likes, dislikes) = object [ "user" .= genEName gs ent , "friends" .= map (genEName gs . fst) friends , "foes" .= map (genEName gs . fst) foes , "groups" .= ((map (genUGName gs "likedby-") likes) ++ (map (genUGName gs "dislikedby-") dislikes)) ] groups = (map (genUGName gs "likedby-") $ M.elems (gs ^. users)) ++ (map (genUGName gs "dislikedby-") $ M.elems (gs ^. users)) in object ["users" .= toJSON es, "groups" .= groups] etypeString :: Entity -> T.Text etypeString ent = case ent ^. etype of Person _ -> "person" Organization _ -> "organization" instance ToJSON (Day, Bool) where toJSON (day, approx) = let (y,m,d) = toGregorian day in if approx then object ["year" .= y] else object ["month" .= m, "day" .= d, "year" .= y] isPos (PL _) = True isPos (NL _) = False instance ToJSON (GraphState, Link) where toJSON (gs, l) = object [ "lid" .= (idToInt $ L (l ^. lid)) , "src" .= (idToInt $ E (l ^. lsrc)) , "dst" .= (idToInt $ E (l ^. ldst)) , "linktype" .= showLT lt , "linkdesc" .= lToText lt , "pos" .= isPos lt , "bidir" .= isBiDir lt ] where lt = l ^. ltype instance ToJSON (GraphState, Entity) where toJSON (gs,e) = object ([ "eid" .= (idToInt $ E (e ^. eid)) , "etype" .= etypeString e , "ename" .= (e ^. ecname) , "links" .= zip (L.repeat gs) ls ] ++ (deMaybe [ fmap (\wp -> "wp" .= unUrl wp) (e ^. ewp) , fmap (\hp -> "homepage" .= unUrl hp) (e ^. ehp) , fmap (\tw -> "twt" .= unUrl tw) (e ^. etwt) , fmap (\b -> "birth" .= b) (e ^. ebirth) , fmap (\d -> "death" .= d) (e ^. edeath) ])) where ls = getAllLinks gs (e ^. eid)
jimsnow/polink
PolinkAPI.hs
gpl-2.0
17,786
0
24
5,290
6,419
3,363
3,056
-1
-1
module Muttells ( checkAlias , getHeaders , getBody ) where import Text.Parsec import Data.Maybe (maybeToList) import Data.List (intercalate, isInfixOf) type Parser t s = Parsec t s ------------------------ -- Mutt email parsers -- ------------------------ getHeaders :: String -> [String] getHeaders = takeWhile (/= []) . lines -- Will eventually accounts for headers that span multiple lines -- joinMultiLineHeaders [] = [] -- joinMultiLineHeaders (x:xs) -- | " " `isPrefixOf` head xs = (x ++ head xs) : (tail xs) -- | "\t" `isPrefixOf` head xs = (x ++ head xs) : (tail xs) -- | otherwise = x : joinMultiLineHeaders xs getBody :: String -> String getBody = unlines . dropWhile (/= []) . lines ------------------------ -- Mutt alias parsers -- ------------------------ stopWords :: [String] stopWords = [ "notification", "notifications", "do-not-reply", "no-reply", "noreply", "donotreply" ] checkAlias :: String -> String checkAlias input = case parse validLine "" input of Left _ -> '#':input Right _ -> if any (`isInfixOf` input) stopWords then '#':input else input -- NB: if you don't want to use stopwords, use "Right _ -> input" instead where validLine = try comment <|> try groupAlias <|> validAlias preAlias, validAlias, comment, groupAlias :: Parser String st String preAlias = string "alias " >> manyTill anyChar space comment = string "#" >> many (noneOf "\n") groupAlias = do _ <- preAlias >> nickname >> nicknameSep _ <- sepBy nickname nicknameSep return "valid group alias" where nickname = many (noneOf " ,\n") nicknameSep = skipMany (char ' ') >> char ',' >> skipMany (char ' ') validAlias = do _ <- preAlias >> manyTill (noneOf "<>\n") (try ( angEmail <|> emailAddress )) notFollowedBy anyToken <?> "end of input" return "valid single alias" --------------------------- -- Email address parsers -- --------------------------- -- Using modified old emailAddress parser from Pandoc -- https://github.com/jgm/pandoc/blob/a71641a2a04c1d324163e16299f1e9821a26c9f9/src/Text/Pandoc/Parsing.hs angEmail :: Parser String st String angEmail = do _ <- char '<' >> emailAddress >> char '>' return "bracketed email address" emailChar :: Parser String st Char emailChar = alphaNum <|> oneOf "!\"#$%&'*+-/0123456789=?^_{|}~" domain :: Parser String st String domain = do x <- subdomain xs <- many (try $ char '.' >> subdomain) return $ intercalate "." (x:xs) subdomain :: Parser String st String subdomain = many1 (emailChar <|> char '@') emailWord :: Parser String st String emailWord = many1 emailChar -- ignores possibility of quoted strings emailAddress :: Parser String st String emailAddress = try $ do firstLetter <- alphaNum firstDot <- optionMaybe (char '.') x <- emailWord xs <- many (try $ char '.' >> emailWord) let addr = (firstLetter : maybeToList firstDot) ++ intercalate "." (x:xs) _ <- char '@' dom <- domain let full = addr ++ '@':dom return full
wcaleb/muttells
Muttells.hs
gpl-2.0
3,024
0
14
601
796
411
385
59
3
module Api where import Rest.Api import qualified Api.Tiddler as Tiddler import ApiTypes (GitRestApi) api :: Api GitRestApi api = [(mkVersion 0 0 1, Some1 gitRest)] gitRest :: Router GitRestApi GitRestApi gitRest = root -/ tiddler where tiddler = route Tiddler.resource
bitraten/gitrest
src/Api.hs
gpl-3.0
305
0
8
75
88
50
38
10
1
{-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE FlexibleContexts #-} module System.UtilsBox.Optparse where import Prelude hiding (getLine, putStrLn, putStr) import qualified Control.Monad.Free as F import qualified Options.Applicative as OA import qualified System.Exit as SE import System.UtilsBoxSpec.CoreTypes ((:<:)) import System.UtilsBoxSpec.Teletype (TeletypeAPI, putStr) import System.UtilsBoxSpec.Environment import System.UtilsBoxSpec.Exit (ExitAPI, exitWith) handleParserFree :: (TeletypeAPI :<: f) => String -> OA.ParserResult a -> F.Free f (Either (String, SE.ExitCode) a) handleParserFree _ (OA.Success a) = return . Right $ a handleParserFree programName (OA.Failure failure) = return (Left (msg, exit)) where (msg, exit) = OA.renderFailure failure programName handleParserFree _ (OA.CompletionInvoked _) = return (Left ("We currently do not support tab completions :(.", SE.ExitFailure 2)) execParserFree :: (TeletypeAPI :<: f, EnvironmentAPI :<: f) => String -> OA.ParserInfo a -> F.Free f (Either (String, SE.ExitCode) a) execParserFree programName info = do programArgs <- getArgs let result = OA.execParserPure OA.defaultPrefs info programArgs handleParserFree programName result execParserFreeExit :: (TeletypeAPI :<: f, EnvironmentAPI :<: f, ExitAPI :<: f) => String -> OA.ParserInfo a -> F.Free f a execParserFreeExit programName info = execParserFree programName info >>= exitOnErr where exitOnErr (Left (errMsg, exitCode)) = do putStr errMsg exitWith exitCode exitOnErr (Right x) = return x
changlinli/utilsbox
System/UtilsBox/Optparse.hs
gpl-3.0
1,633
0
12
283
494
265
229
28
2
{-# LANGUAGE RecordWildCards #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE Arrows #-} -- ./dist/build/TaxIds2Text/TaxIds2Text -t /home/mescalin/egg/current/Projects/Haskell/TaxonomyTools/RF00169_accessionnumbers.tax -r Phylum -i /scratch/egg/taxdmpnew/ > out.csv module Main where import System.Console.CmdArgs import Data.Either.Unwrap import qualified Data.Text.Lazy as TL import Biobase.Taxonomy import Data.Maybe import Text.Read data Options = Options { taxDumpDirectoryPath :: String, taxonomicRank :: String, taxNodeListFilePath :: String } deriving (Show,Data,Typeable) options :: Options options = Options { taxDumpDirectoryPath = def &= name "i" &= help "Path to input NCBI taxonomy dump files directory", taxonomicRank = "Class" &= name "r" &= help "Requested taxonomic rank - default Class", taxNodeListFilePath = def &= name "t" &= help "Path to input taxonomy id list without header" } &= summary "TaxIds2Text - List of taxonomy ids is converted in a short text summary for each node." &= help "Florian Eggenhofer - 2015" &= verbosity main :: IO () main = do Options{..} <- cmdArgs options graphOutput <- readNamedTaxonomy taxDumpDirectoryPath let currentRank = readMaybeRank taxonomicRank if isNothing currentRank then putStrLn "Please provide a valid taxonomic Rank (e.g. Class)." else do if isLeft graphOutput then print ("Could not parse provided taxonomy dump files" ++ show (fromLeft graphOutput)) else do if null taxNodeListFilePath then do putStrLn "Provide a path to input taxonomy id list or to RNAlienResult CSV." else do -- input taxid path present taxidtable <- readFile taxNodeListFilePath let taxidtableentries = map (\l -> read l :: Int) (lines taxidtable) let graph = fromRight graphOutput let maybeParentNodes = map (\taxidtableentry -> getParentbyRank taxidtableentry graph (Just Phylum)) taxidtableentries let parentNodeStrings = map (\maybeParentNode -> maybe "not found,not found" (\(_,n) -> printSimpleNode n) maybeParentNode) maybeParentNodes let outputCSV = map (\(txid,parentNodeString) -> (show txid) ++ "," ++ parentNodeString) (zip taxidtableentries parentNodeStrings) mapM_ putStrLn outputCSV printSimpleNode :: SimpleTaxon -> String printSimpleNode snode = show (simpleRank snode) ++ "," ++ TL.unpack (simpleScientificName snode) readMaybeRank :: String -> Maybe Rank readMaybeRank inputString = readMaybe inputString
eggzilla/TaxonomyTools
Biobase/TaxIds2Text.hs
gpl-3.0
2,626
0
25
566
563
288
275
47
4
module HMail.Brick.Init ( mkInitialState , initView ) where import HMail.Types import Control.Concurrent.Chan mkInitialState :: Chan Command -> Verbosity -> HMailState mkInitialState chan verbosity = HMailState mempty [] chan verbosity initView :: View initView = IsMailBoxesView (MailBoxesView Nothing)
xaverdh/hmail
HMail/Brick/Init.hs
gpl-3.0
311
0
7
44
82
45
37
10
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.CloudFront.ListInvalidations -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- List invalidation batches. -- -- /See:/ <http://docs.aws.amazon.com/AmazonCloudFront/latest/APIReference/ListInvalidations.html AWS API Reference> for ListInvalidations. module Network.AWS.CloudFront.ListInvalidations ( -- * Creating a Request listInvalidations , ListInvalidations -- * Request Lenses , liMarker , liMaxItems , liDistributionId -- * Destructuring the Response , listInvalidationsResponse , ListInvalidationsResponse -- * Response Lenses , lirsResponseStatus , lirsInvalidationList ) where import Network.AWS.CloudFront.Types import Network.AWS.CloudFront.Types.Product import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response -- | The request to list invalidations. -- -- /See:/ 'listInvalidations' smart constructor. data ListInvalidations = ListInvalidations' { _liMarker :: !(Maybe Text) , _liMaxItems :: !(Maybe Text) , _liDistributionId :: !Text } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'ListInvalidations' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'liMarker' -- -- * 'liMaxItems' -- -- * 'liDistributionId' listInvalidations :: Text -- ^ 'liDistributionId' -> ListInvalidations listInvalidations pDistributionId_ = ListInvalidations' { _liMarker = Nothing , _liMaxItems = Nothing , _liDistributionId = pDistributionId_ } -- | Use this parameter when paginating results to indicate where to begin in -- your list of invalidation batches. Because the results are returned in -- decreasing order from most recent to oldest, the most recent results are -- on the first page, the second page will contain earlier results, and so -- on. To get the next page of results, set the Marker to the value of the -- NextMarker from the current page\'s response. This value is the same as -- the ID of the last invalidation batch on that page. liMarker :: Lens' ListInvalidations (Maybe Text) liMarker = lens _liMarker (\ s a -> s{_liMarker = a}); -- | The maximum number of invalidation batches you want in the response -- body. liMaxItems :: Lens' ListInvalidations (Maybe Text) liMaxItems = lens _liMaxItems (\ s a -> s{_liMaxItems = a}); -- | The distribution\'s id. liDistributionId :: Lens' ListInvalidations Text liDistributionId = lens _liDistributionId (\ s a -> s{_liDistributionId = a}); instance AWSRequest ListInvalidations where type Rs ListInvalidations = ListInvalidationsResponse request = get cloudFront response = receiveXML (\ s h x -> ListInvalidationsResponse' <$> (pure (fromEnum s)) <*> (parseXML x)) instance ToHeaders ListInvalidations where toHeaders = const mempty instance ToPath ListInvalidations where toPath ListInvalidations'{..} = mconcat ["/2015-04-17/distribution/", toBS _liDistributionId, "/invalidation"] instance ToQuery ListInvalidations where toQuery ListInvalidations'{..} = mconcat ["Marker" =: _liMarker, "MaxItems" =: _liMaxItems] -- | The returned result of the corresponding request. -- -- /See:/ 'listInvalidationsResponse' smart constructor. data ListInvalidationsResponse = ListInvalidationsResponse' { _lirsResponseStatus :: !Int , _lirsInvalidationList :: !InvalidationList } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'ListInvalidationsResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lirsResponseStatus' -- -- * 'lirsInvalidationList' listInvalidationsResponse :: Int -- ^ 'lirsResponseStatus' -> InvalidationList -- ^ 'lirsInvalidationList' -> ListInvalidationsResponse listInvalidationsResponse pResponseStatus_ pInvalidationList_ = ListInvalidationsResponse' { _lirsResponseStatus = pResponseStatus_ , _lirsInvalidationList = pInvalidationList_ } -- | The response status code. lirsResponseStatus :: Lens' ListInvalidationsResponse Int lirsResponseStatus = lens _lirsResponseStatus (\ s a -> s{_lirsResponseStatus = a}); -- | Information about invalidation batches. lirsInvalidationList :: Lens' ListInvalidationsResponse InvalidationList lirsInvalidationList = lens _lirsInvalidationList (\ s a -> s{_lirsInvalidationList = a});
fmapfmapfmap/amazonka
amazonka-cloudfront/gen/Network/AWS/CloudFront/ListInvalidations.hs
mpl-2.0
5,245
0
14
1,042
694
416
278
88
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.Autoscaler.Zones.List -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- -- | -- -- /See:/ <http://developers.google.com/compute/docs/autoscaler Google Compute Engine Autoscaler API Reference> for @autoscaler.zones.list@. module Network.Google.Resource.Autoscaler.Zones.List ( -- * REST Resource ZonesListResource -- * Creating a Request , zonesList , ZonesList -- * Request Lenses , zlProject , zlFilter , zlPageToken , zlMaxResults ) where import Network.Google.Autoscaler.Types import Network.Google.Prelude -- | A resource alias for @autoscaler.zones.list@ method which the -- 'ZonesList' request conforms to. type ZonesListResource = "autoscaler" :> "v1beta2" :> "zones" :> QueryParam "project" Text :> QueryParam "filter" Text :> QueryParam "pageToken" Text :> QueryParam "maxResults" (Textual Word32) :> QueryParam "alt" AltJSON :> Get '[JSON] ZoneList -- | -- -- /See:/ 'zonesList' smart constructor. data ZonesList = ZonesList' { _zlProject :: !(Maybe Text) , _zlFilter :: !(Maybe Text) , _zlPageToken :: !(Maybe Text) , _zlMaxResults :: !(Textual Word32) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ZonesList' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'zlProject' -- -- * 'zlFilter' -- -- * 'zlPageToken' -- -- * 'zlMaxResults' zonesList :: ZonesList zonesList = ZonesList' { _zlProject = Nothing , _zlFilter = Nothing , _zlPageToken = Nothing , _zlMaxResults = 500 } zlProject :: Lens' ZonesList (Maybe Text) zlProject = lens _zlProject (\ s a -> s{_zlProject = a}) zlFilter :: Lens' ZonesList (Maybe Text) zlFilter = lens _zlFilter (\ s a -> s{_zlFilter = a}) zlPageToken :: Lens' ZonesList (Maybe Text) zlPageToken = lens _zlPageToken (\ s a -> s{_zlPageToken = a}) zlMaxResults :: Lens' ZonesList Word32 zlMaxResults = lens _zlMaxResults (\ s a -> s{_zlMaxResults = a}) . _Coerce instance GoogleRequest ZonesList where type Rs ZonesList = ZoneList type Scopes ZonesList = '["https://www.googleapis.com/auth/compute", "https://www.googleapis.com/auth/compute.readonly"] requestClient ZonesList'{..} = go _zlProject _zlFilter _zlPageToken (Just _zlMaxResults) (Just AltJSON) autoscalerService where go = buildClient (Proxy :: Proxy ZonesListResource) mempty
rueshyna/gogol
gogol-autoscaler/gen/Network/Google/Resource/Autoscaler/Zones/List.hs
mpl-2.0
3,381
0
15
847
555
324
231
79
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.Compute.HTTPSHealthChecks.Update -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Updates a HttpsHealthCheck resource in the specified project using the -- data included in the request. -- -- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.httpsHealthChecks.update@. module Network.Google.Resource.Compute.HTTPSHealthChecks.Update ( -- * REST Resource HTTPSHealthChecksUpdateResource -- * Creating a Request , httpsHealthChecksUpdate , HTTPSHealthChecksUpdate -- * Request Lenses , hhcuRequestId , hhcuProject , hhcuPayload , hhcuHTTPSHealthCheck ) where import Network.Google.Compute.Types import Network.Google.Prelude -- | A resource alias for @compute.httpsHealthChecks.update@ method which the -- 'HTTPSHealthChecksUpdate' request conforms to. type HTTPSHealthChecksUpdateResource = "compute" :> "v1" :> "projects" :> Capture "project" Text :> "global" :> "httpsHealthChecks" :> Capture "httpsHealthCheck" Text :> QueryParam "requestId" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] HTTPSHealthCheck :> Put '[JSON] Operation -- | Updates a HttpsHealthCheck resource in the specified project using the -- data included in the request. -- -- /See:/ 'httpsHealthChecksUpdate' smart constructor. data HTTPSHealthChecksUpdate = HTTPSHealthChecksUpdate' { _hhcuRequestId :: !(Maybe Text) , _hhcuProject :: !Text , _hhcuPayload :: !HTTPSHealthCheck , _hhcuHTTPSHealthCheck :: !Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'HTTPSHealthChecksUpdate' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'hhcuRequestId' -- -- * 'hhcuProject' -- -- * 'hhcuPayload' -- -- * 'hhcuHTTPSHealthCheck' httpsHealthChecksUpdate :: Text -- ^ 'hhcuProject' -> HTTPSHealthCheck -- ^ 'hhcuPayload' -> Text -- ^ 'hhcuHTTPSHealthCheck' -> HTTPSHealthChecksUpdate httpsHealthChecksUpdate pHhcuProject_ pHhcuPayload_ pHhcuHTTPSHealthCheck_ = HTTPSHealthChecksUpdate' { _hhcuRequestId = Nothing , _hhcuProject = pHhcuProject_ , _hhcuPayload = pHhcuPayload_ , _hhcuHTTPSHealthCheck = pHhcuHTTPSHealthCheck_ } -- | An optional request ID to identify requests. Specify a unique request ID -- so that if you must retry your request, the server will know to ignore -- the request if it has already been completed. For example, consider a -- situation where you make an initial request and the request times out. -- If you make the request again with the same request ID, the server can -- check if original operation with the same request ID was received, and -- if so, will ignore the second request. This prevents clients from -- accidentally creating duplicate commitments. The request ID must be a -- valid UUID with the exception that zero UUID is not supported -- (00000000-0000-0000-0000-000000000000). hhcuRequestId :: Lens' HTTPSHealthChecksUpdate (Maybe Text) hhcuRequestId = lens _hhcuRequestId (\ s a -> s{_hhcuRequestId = a}) -- | Project ID for this request. hhcuProject :: Lens' HTTPSHealthChecksUpdate Text hhcuProject = lens _hhcuProject (\ s a -> s{_hhcuProject = a}) -- | Multipart request metadata. hhcuPayload :: Lens' HTTPSHealthChecksUpdate HTTPSHealthCheck hhcuPayload = lens _hhcuPayload (\ s a -> s{_hhcuPayload = a}) -- | Name of the HttpsHealthCheck resource to update. hhcuHTTPSHealthCheck :: Lens' HTTPSHealthChecksUpdate Text hhcuHTTPSHealthCheck = lens _hhcuHTTPSHealthCheck (\ s a -> s{_hhcuHTTPSHealthCheck = a}) instance GoogleRequest HTTPSHealthChecksUpdate where type Rs HTTPSHealthChecksUpdate = Operation type Scopes HTTPSHealthChecksUpdate = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/compute"] requestClient HTTPSHealthChecksUpdate'{..} = go _hhcuProject _hhcuHTTPSHealthCheck _hhcuRequestId (Just AltJSON) _hhcuPayload computeService where go = buildClient (Proxy :: Proxy HTTPSHealthChecksUpdateResource) mempty
brendanhay/gogol
gogol-compute/gen/Network/Google/Resource/Compute/HTTPSHealthChecks/Update.hs
mpl-2.0
5,149
0
17
1,134
559
335
224
90
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.Monitoring.Types.Product -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- module Network.Google.Monitoring.Types.Product where import Network.Google.Monitoring.Types.Sum import Network.Google.Prelude -- | An object that describes the schema of a MonitoredResource object using -- a type name and a set of labels. For example, the monitored resource -- descriptor for Google Compute Engine VM instances has a type of -- \"gce_instance\" and specifies the use of the labels \"instance_id\" and -- \"zone\" to identify particular VM instances.Different APIs can support -- different monitored resource types. APIs generally provide a list method -- that returns the monitored resource descriptors used by the API. -- -- /See:/ 'monitoredResourceDescriptor' smart constructor. data MonitoredResourceDescriptor = MonitoredResourceDescriptor' { _mrdName :: !(Maybe Text) , _mrdDisplayName :: !(Maybe Text) , _mrdLabels :: !(Maybe [LabelDescriptor]) , _mrdType :: !(Maybe Text) , _mrdDescription :: !(Maybe Text) , _mrdLaunchStage :: !(Maybe MonitoredResourceDescriptorLaunchStage) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'MonitoredResourceDescriptor' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'mrdName' -- -- * 'mrdDisplayName' -- -- * 'mrdLabels' -- -- * 'mrdType' -- -- * 'mrdDescription' -- -- * 'mrdLaunchStage' monitoredResourceDescriptor :: MonitoredResourceDescriptor monitoredResourceDescriptor = MonitoredResourceDescriptor' { _mrdName = Nothing , _mrdDisplayName = Nothing , _mrdLabels = Nothing , _mrdType = Nothing , _mrdDescription = Nothing , _mrdLaunchStage = Nothing } -- | Optional. The resource name of the monitored resource descriptor: -- \"projects\/{project_id}\/monitoredResourceDescriptors\/{type}\" where -- {type} is the value of the type field in this object and {project_id} is -- a project ID that provides API-specific context for accessing the type. -- APIs that do not use project information can use the resource name -- format \"monitoredResourceDescriptors\/{type}\". mrdName :: Lens' MonitoredResourceDescriptor (Maybe Text) mrdName = lens _mrdName (\ s a -> s{_mrdName = a}) -- | Optional. A concise name for the monitored resource type that might be -- displayed in user interfaces. It should be a Title Cased Noun Phrase, -- without any article or other determiners. For example, \"Google Cloud -- SQL Database\". mrdDisplayName :: Lens' MonitoredResourceDescriptor (Maybe Text) mrdDisplayName = lens _mrdDisplayName (\ s a -> s{_mrdDisplayName = a}) -- | Required. A set of labels used to describe instances of this monitored -- resource type. For example, an individual Google Cloud SQL database is -- identified by values for the labels \"database_id\" and \"zone\". mrdLabels :: Lens' MonitoredResourceDescriptor [LabelDescriptor] mrdLabels = lens _mrdLabels (\ s a -> s{_mrdLabels = a}) . _Default . _Coerce -- | Required. The monitored resource type. For example, the type -- \"cloudsql_database\" represents databases in Google Cloud SQL. mrdType :: Lens' MonitoredResourceDescriptor (Maybe Text) mrdType = lens _mrdType (\ s a -> s{_mrdType = a}) -- | Optional. A detailed description of the monitored resource type that -- might be used in documentation. mrdDescription :: Lens' MonitoredResourceDescriptor (Maybe Text) mrdDescription = lens _mrdDescription (\ s a -> s{_mrdDescription = a}) -- | Optional. The launch stage of the monitored resource definition. mrdLaunchStage :: Lens' MonitoredResourceDescriptor (Maybe MonitoredResourceDescriptorLaunchStage) mrdLaunchStage = lens _mrdLaunchStage (\ s a -> s{_mrdLaunchStage = a}) instance FromJSON MonitoredResourceDescriptor where parseJSON = withObject "MonitoredResourceDescriptor" (\ o -> MonitoredResourceDescriptor' <$> (o .:? "name") <*> (o .:? "displayName") <*> (o .:? "labels" .!= mempty) <*> (o .:? "type") <*> (o .:? "description") <*> (o .:? "launchStage")) instance ToJSON MonitoredResourceDescriptor where toJSON MonitoredResourceDescriptor'{..} = object (catMaybes [("name" .=) <$> _mrdName, ("displayName" .=) <$> _mrdDisplayName, ("labels" .=) <$> _mrdLabels, ("type" .=) <$> _mrdType, ("description" .=) <$> _mrdDescription, ("launchStage" .=) <$> _mrdLaunchStage]) -- | An SLI measuring performance on a well-known service type. Performance -- will be computed on the basis of pre-defined metrics. The type of the -- service_resource determines the metrics to use and the -- service_resource.labels and metric_labels are used to construct a -- monitoring filter to filter that metric down to just the data relevant -- to this service. -- -- /See:/ 'basicSli' smart constructor. data BasicSli = BasicSli' { _bsLocation :: !(Maybe [Text]) , _bsLatency :: !(Maybe LatencyCriteria) , _bsAvailability :: !(Maybe AvailabilityCriteria) , _bsMethod :: !(Maybe [Text]) , _bsVersion :: !(Maybe [Text]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'BasicSli' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'bsLocation' -- -- * 'bsLatency' -- -- * 'bsAvailability' -- -- * 'bsMethod' -- -- * 'bsVersion' basicSli :: BasicSli basicSli = BasicSli' { _bsLocation = Nothing , _bsLatency = Nothing , _bsAvailability = Nothing , _bsMethod = Nothing , _bsVersion = Nothing } -- | OPTIONAL: The set of locations to which this SLI is relevant. Telemetry -- from other locations will not be used to calculate performance for this -- SLI. If omitted, this SLI applies to all locations in which the Service -- has activity. For service types that don\'t support breaking down by -- location, setting this field will result in an error. bsLocation :: Lens' BasicSli [Text] bsLocation = lens _bsLocation (\ s a -> s{_bsLocation = a}) . _Default . _Coerce -- | Good service is defined to be the count of requests made to this service -- that are fast enough with respect to latency.threshold. bsLatency :: Lens' BasicSli (Maybe LatencyCriteria) bsLatency = lens _bsLatency (\ s a -> s{_bsLatency = a}) -- | Good service is defined to be the count of requests made to this service -- that return successfully. bsAvailability :: Lens' BasicSli (Maybe AvailabilityCriteria) bsAvailability = lens _bsAvailability (\ s a -> s{_bsAvailability = a}) -- | OPTIONAL: The set of RPCs to which this SLI is relevant. Telemetry from -- other methods will not be used to calculate performance for this SLI. If -- omitted, this SLI applies to all the Service\'s methods. For service -- types that don\'t support breaking down by method, setting this field -- will result in an error. bsMethod :: Lens' BasicSli [Text] bsMethod = lens _bsMethod (\ s a -> s{_bsMethod = a}) . _Default . _Coerce -- | OPTIONAL: The set of API versions to which this SLI is relevant. -- Telemetry from other API versions will not be used to calculate -- performance for this SLI. If omitted, this SLI applies to all API -- versions. For service types that don\'t support breaking down by -- version, setting this field will result in an error. bsVersion :: Lens' BasicSli [Text] bsVersion = lens _bsVersion (\ s a -> s{_bsVersion = a}) . _Default . _Coerce instance FromJSON BasicSli where parseJSON = withObject "BasicSli" (\ o -> BasicSli' <$> (o .:? "location" .!= mempty) <*> (o .:? "latency") <*> (o .:? "availability") <*> (o .:? "method" .!= mempty) <*> (o .:? "version" .!= mempty)) instance ToJSON BasicSli where toJSON BasicSli'{..} = object (catMaybes [("location" .=) <$> _bsLocation, ("latency" .=) <$> _bsLatency, ("availability" .=) <$> _bsAvailability, ("method" .=) <$> _bsMethod, ("version" .=) <$> _bsVersion]) -- | 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]) -- | A Service-Level Objective (SLO) describes a level of desired good -- service. It consists of a service-level indicator (SLI), a performance -- goal, and a period over which the objective is to be evaluated against -- that goal. The SLO can use SLIs defined in a number of different -- manners. Typical SLOs might include \"99% of requests in each rolling -- week have latency below 200 milliseconds\" or \"99.5% of requests in -- each calendar month return successfully.\" -- -- /See:/ 'serviceLevelObjective' smart constructor. data ServiceLevelObjective = ServiceLevelObjective' { _sloUserLabels :: !(Maybe ServiceLevelObjectiveUserLabels) , _sloName :: !(Maybe Text) , _sloCalendarPeriod :: !(Maybe ServiceLevelObjectiveCalendarPeriod) , _sloServiceLevelIndicator :: !(Maybe ServiceLevelIndicator) , _sloGoal :: !(Maybe (Textual Double)) , _sloDisplayName :: !(Maybe Text) , _sloRollingPeriod :: !(Maybe GDuration) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ServiceLevelObjective' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'sloUserLabels' -- -- * 'sloName' -- -- * 'sloCalendarPeriod' -- -- * 'sloServiceLevelIndicator' -- -- * 'sloGoal' -- -- * 'sloDisplayName' -- -- * 'sloRollingPeriod' serviceLevelObjective :: ServiceLevelObjective serviceLevelObjective = ServiceLevelObjective' { _sloUserLabels = Nothing , _sloName = Nothing , _sloCalendarPeriod = Nothing , _sloServiceLevelIndicator = Nothing , _sloGoal = Nothing , _sloDisplayName = Nothing , _sloRollingPeriod = Nothing } -- | Labels which have been used to annotate the service-level objective. -- Label keys must start with a letter. Label keys and values may contain -- lowercase letters, numbers, underscores, and dashes. Label keys and -- values have a maximum length of 63 characters, and must be less than 128 -- bytes in size. Up to 64 label entries may be stored. For labels which do -- not have a semantic value, the empty string may be supplied for the -- label value. sloUserLabels :: Lens' ServiceLevelObjective (Maybe ServiceLevelObjectiveUserLabels) sloUserLabels = lens _sloUserLabels (\ s a -> s{_sloUserLabels = a}) -- | Resource name for this ServiceLevelObjective. The format is: -- projects\/[PROJECT_ID_OR_NUMBER]\/services\/[SERVICE_ID]\/serviceLevelObjectives\/[SLO_NAME] sloName :: Lens' ServiceLevelObjective (Maybe Text) sloName = lens _sloName (\ s a -> s{_sloName = a}) -- | A calendar period, semantically \"since the start of the current \". At -- this time, only DAY, WEEK, FORTNIGHT, and MONTH are supported. sloCalendarPeriod :: Lens' ServiceLevelObjective (Maybe ServiceLevelObjectiveCalendarPeriod) sloCalendarPeriod = lens _sloCalendarPeriod (\ s a -> s{_sloCalendarPeriod = a}) -- | The definition of good service, used to measure and calculate the -- quality of the Service\'s performance with respect to a single aspect of -- service quality. sloServiceLevelIndicator :: Lens' ServiceLevelObjective (Maybe ServiceLevelIndicator) sloServiceLevelIndicator = lens _sloServiceLevelIndicator (\ s a -> s{_sloServiceLevelIndicator = a}) -- | The fraction of service that must be good in order for this objective to -- be met. 0 \< goal \<= 0.999. sloGoal :: Lens' ServiceLevelObjective (Maybe Double) sloGoal = lens _sloGoal (\ s a -> s{_sloGoal = a}) . mapping _Coerce -- | Name used for UI elements listing this SLO. sloDisplayName :: Lens' ServiceLevelObjective (Maybe Text) sloDisplayName = lens _sloDisplayName (\ s a -> s{_sloDisplayName = a}) -- | A rolling time period, semantically \"in the past \". Must be an integer -- multiple of 1 day no larger than 30 days. sloRollingPeriod :: Lens' ServiceLevelObjective (Maybe Scientific) sloRollingPeriod = lens _sloRollingPeriod (\ s a -> s{_sloRollingPeriod = a}) . mapping _GDuration instance FromJSON ServiceLevelObjective where parseJSON = withObject "ServiceLevelObjective" (\ o -> ServiceLevelObjective' <$> (o .:? "userLabels") <*> (o .:? "name") <*> (o .:? "calendarPeriod") <*> (o .:? "serviceLevelIndicator") <*> (o .:? "goal") <*> (o .:? "displayName") <*> (o .:? "rollingPeriod")) instance ToJSON ServiceLevelObjective where toJSON ServiceLevelObjective'{..} = object (catMaybes [("userLabels" .=) <$> _sloUserLabels, ("name" .=) <$> _sloName, ("calendarPeriod" .=) <$> _sloCalendarPeriod, ("serviceLevelIndicator" .=) <$> _sloServiceLevelIndicator, ("goal" .=) <$> _sloGoal, ("displayName" .=) <$> _sloDisplayName, ("rollingPeriod" .=) <$> _sloRollingPeriod]) -- | The ListNotificationChannels response. -- -- /See:/ 'listNotificationChannelsResponse' smart constructor. data ListNotificationChannelsResponse = ListNotificationChannelsResponse' { _lncrNextPageToken :: !(Maybe Text) , _lncrNotificationChannels :: !(Maybe [NotificationChannel]) , _lncrTotalSize :: !(Maybe (Textual Int32)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ListNotificationChannelsResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lncrNextPageToken' -- -- * 'lncrNotificationChannels' -- -- * 'lncrTotalSize' listNotificationChannelsResponse :: ListNotificationChannelsResponse listNotificationChannelsResponse = ListNotificationChannelsResponse' { _lncrNextPageToken = Nothing , _lncrNotificationChannels = Nothing , _lncrTotalSize = Nothing } -- | If not empty, indicates that there may be more results that match the -- request. Use the value in the page_token field in a subsequent request -- to fetch the next set of results. If empty, all results have been -- returned. lncrNextPageToken :: Lens' ListNotificationChannelsResponse (Maybe Text) lncrNextPageToken = lens _lncrNextPageToken (\ s a -> s{_lncrNextPageToken = a}) -- | The notification channels defined for the specified project. lncrNotificationChannels :: Lens' ListNotificationChannelsResponse [NotificationChannel] lncrNotificationChannels = lens _lncrNotificationChannels (\ s a -> s{_lncrNotificationChannels = a}) . _Default . _Coerce -- | The total number of notification channels in all pages. This number is -- only an estimate, and may change in subsequent pages. -- https:\/\/aip.dev\/158 lncrTotalSize :: Lens' ListNotificationChannelsResponse (Maybe Int32) lncrTotalSize = lens _lncrTotalSize (\ s a -> s{_lncrTotalSize = a}) . mapping _Coerce instance FromJSON ListNotificationChannelsResponse where parseJSON = withObject "ListNotificationChannelsResponse" (\ o -> ListNotificationChannelsResponse' <$> (o .:? "nextPageToken") <*> (o .:? "notificationChannels" .!= mempty) <*> (o .:? "totalSize")) instance ToJSON ListNotificationChannelsResponse where toJSON ListNotificationChannelsResponse'{..} = object (catMaybes [("nextPageToken" .=) <$> _lncrNextPageToken, ("notificationChannels" .=) <$> _lncrNotificationChannels, ("totalSize" .=) <$> _lncrTotalSize]) -- | The ListTimeSeries response. -- -- /See:/ 'listTimeSeriesResponse' smart constructor. data ListTimeSeriesResponse = ListTimeSeriesResponse' { _ltsrNextPageToken :: !(Maybe Text) , _ltsrExecutionErrors :: !(Maybe [Status]) , _ltsrUnit :: !(Maybe Text) , _ltsrTimeSeries :: !(Maybe [TimeSeries]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ListTimeSeriesResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ltsrNextPageToken' -- -- * 'ltsrExecutionErrors' -- -- * 'ltsrUnit' -- -- * 'ltsrTimeSeries' listTimeSeriesResponse :: ListTimeSeriesResponse listTimeSeriesResponse = ListTimeSeriesResponse' { _ltsrNextPageToken = Nothing , _ltsrExecutionErrors = Nothing , _ltsrUnit = Nothing , _ltsrTimeSeries = Nothing } -- | If there are more results than have been returned, then this field is -- set to a non-empty value. To see the additional results, use that value -- as page_token in the next call to this method. ltsrNextPageToken :: Lens' ListTimeSeriesResponse (Maybe Text) ltsrNextPageToken = lens _ltsrNextPageToken (\ s a -> s{_ltsrNextPageToken = a}) -- | Query execution errors that may have caused the time series data -- returned to be incomplete. ltsrExecutionErrors :: Lens' ListTimeSeriesResponse [Status] ltsrExecutionErrors = lens _ltsrExecutionErrors (\ s a -> s{_ltsrExecutionErrors = a}) . _Default . _Coerce -- | The unit in which all time_series point values are reported. unit -- follows the UCUM format for units as seen in -- https:\/\/unitsofmeasure.org\/ucum.html. If different time_series have -- different units (for example, because they come from different metric -- types, or a unit is absent), then unit will be \"{not_a_unit}\". ltsrUnit :: Lens' ListTimeSeriesResponse (Maybe Text) ltsrUnit = lens _ltsrUnit (\ s a -> s{_ltsrUnit = a}) -- | One or more time series that match the filter included in the request. ltsrTimeSeries :: Lens' ListTimeSeriesResponse [TimeSeries] ltsrTimeSeries = lens _ltsrTimeSeries (\ s a -> s{_ltsrTimeSeries = a}) . _Default . _Coerce instance FromJSON ListTimeSeriesResponse where parseJSON = withObject "ListTimeSeriesResponse" (\ o -> ListTimeSeriesResponse' <$> (o .:? "nextPageToken") <*> (o .:? "executionErrors" .!= mempty) <*> (o .:? "unit") <*> (o .:? "timeSeries" .!= mempty)) instance ToJSON ListTimeSeriesResponse where toJSON ListTimeSeriesResponse'{..} = object (catMaybes [("nextPageToken" .=) <$> _ltsrNextPageToken, ("executionErrors" .=) <$> _ltsrExecutionErrors, ("unit" .=) <$> _ltsrUnit, ("timeSeries" .=) <$> _ltsrTimeSeries]) -- | The GetNotificationChannelVerificationCode request. -- -- /See:/ 'getNotificationChannelVerificationCodeResponse' smart constructor. data GetNotificationChannelVerificationCodeResponse = GetNotificationChannelVerificationCodeResponse' { _gncvcrCode :: !(Maybe Text) , _gncvcrExpireTime :: !(Maybe DateTime') } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GetNotificationChannelVerificationCodeResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gncvcrCode' -- -- * 'gncvcrExpireTime' getNotificationChannelVerificationCodeResponse :: GetNotificationChannelVerificationCodeResponse getNotificationChannelVerificationCodeResponse = GetNotificationChannelVerificationCodeResponse' {_gncvcrCode = Nothing, _gncvcrExpireTime = Nothing} -- | The verification code, which may be used to verify other channels that -- have an equivalent identity (i.e. other channels of the same type with -- the same fingerprint such as other email channels with the same email -- address or other sms channels with the same number). gncvcrCode :: Lens' GetNotificationChannelVerificationCodeResponse (Maybe Text) gncvcrCode = lens _gncvcrCode (\ s a -> s{_gncvcrCode = a}) -- | The expiration time associated with the code that was returned. If an -- expiration was provided in the request, this is the minimum of the -- requested expiration in the request and the max permitted expiration. gncvcrExpireTime :: Lens' GetNotificationChannelVerificationCodeResponse (Maybe UTCTime) gncvcrExpireTime = lens _gncvcrExpireTime (\ s a -> s{_gncvcrExpireTime = a}) . mapping _DateTime instance FromJSON GetNotificationChannelVerificationCodeResponse where parseJSON = withObject "GetNotificationChannelVerificationCodeResponse" (\ o -> GetNotificationChannelVerificationCodeResponse' <$> (o .:? "code") <*> (o .:? "expireTime")) instance ToJSON GetNotificationChannelVerificationCodeResponse where toJSON GetNotificationChannelVerificationCodeResponse'{..} = object (catMaybes [("code" .=) <$> _gncvcrCode, ("expireTime" .=) <$> _gncvcrExpireTime]) -- | Configuration for how to query telemetry on a Service. -- -- /See:/ 'telemetry' smart constructor. newtype Telemetry = Telemetry' { _tResourceName :: Maybe Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Telemetry' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'tResourceName' telemetry :: Telemetry telemetry = Telemetry' {_tResourceName = Nothing} -- | The full name of the resource that defines this service. Formatted as -- described in https:\/\/cloud.google.com\/apis\/design\/resource_names. tResourceName :: Lens' Telemetry (Maybe Text) tResourceName = lens _tResourceName (\ s a -> s{_tResourceName = a}) instance FromJSON Telemetry where parseJSON = withObject "Telemetry" (\ o -> Telemetry' <$> (o .:? "resourceName")) instance ToJSON Telemetry where toJSON Telemetry'{..} = object (catMaybes [("resourceName" .=) <$> _tResourceName]) -- | A condition type that allows alert policies to be defined using -- Monitoring Query Language (https:\/\/cloud.google.com\/monitoring\/mql). -- -- /See:/ 'monitoringQueryLanguageCondition' smart constructor. data MonitoringQueryLanguageCondition = MonitoringQueryLanguageCondition' { _mqlcQuery :: !(Maybe Text) , _mqlcTrigger :: !(Maybe Trigger) , _mqlcDuration :: !(Maybe GDuration) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'MonitoringQueryLanguageCondition' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'mqlcQuery' -- -- * 'mqlcTrigger' -- -- * 'mqlcDuration' monitoringQueryLanguageCondition :: MonitoringQueryLanguageCondition monitoringQueryLanguageCondition = MonitoringQueryLanguageCondition' {_mqlcQuery = Nothing, _mqlcTrigger = Nothing, _mqlcDuration = Nothing} -- | Monitoring Query Language (https:\/\/cloud.google.com\/monitoring\/mql) -- query that outputs a boolean stream. mqlcQuery :: Lens' MonitoringQueryLanguageCondition (Maybe Text) mqlcQuery = lens _mqlcQuery (\ s a -> s{_mqlcQuery = a}) -- | The number\/percent of time series for which the comparison must hold in -- order for the condition to trigger. If unspecified, then the condition -- will trigger if the comparison is true for any of the time series that -- have been identified by filter and aggregations, or by the ratio, if -- denominator_filter and denominator_aggregations are specified. mqlcTrigger :: Lens' MonitoringQueryLanguageCondition (Maybe Trigger) mqlcTrigger = lens _mqlcTrigger (\ s a -> s{_mqlcTrigger = a}) -- | The amount of time that a time series must violate the threshold to be -- considered failing. Currently, only values that are a multiple of a -- minute--e.g., 0, 60, 120, or 300 seconds--are supported. If an invalid -- value is given, an error will be returned. When choosing a duration, it -- is useful to keep in mind the frequency of the underlying time series -- data (which may also be affected by any alignments specified in the -- aggregations field); a good duration is long enough so that a single -- outlier does not generate spurious alerts, but short enough that -- unhealthy states are detected and alerted on quickly. mqlcDuration :: Lens' MonitoringQueryLanguageCondition (Maybe Scientific) mqlcDuration = lens _mqlcDuration (\ s a -> s{_mqlcDuration = a}) . mapping _GDuration instance FromJSON MonitoringQueryLanguageCondition where parseJSON = withObject "MonitoringQueryLanguageCondition" (\ o -> MonitoringQueryLanguageCondition' <$> (o .:? "query") <*> (o .:? "trigger") <*> (o .:? "duration")) instance ToJSON MonitoringQueryLanguageCondition where toJSON MonitoringQueryLanguageCondition'{..} = object (catMaybes [("query" .=) <$> _mqlcQuery, ("trigger" .=) <$> _mqlcTrigger, ("duration" .=) <$> _mqlcDuration]) -- | The ListServices response. -- -- /See:/ 'listServicesResponse' smart constructor. data ListServicesResponse = ListServicesResponse' { _lsrNextPageToken :: !(Maybe Text) , _lsrServices :: !(Maybe [Service]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ListServicesResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lsrNextPageToken' -- -- * 'lsrServices' listServicesResponse :: ListServicesResponse listServicesResponse = ListServicesResponse' {_lsrNextPageToken = Nothing, _lsrServices = Nothing} -- | If there are more results than have been returned, then this field is -- set to a non-empty value. To see the additional results, use that value -- as page_token in the next call to this method. lsrNextPageToken :: Lens' ListServicesResponse (Maybe Text) lsrNextPageToken = lens _lsrNextPageToken (\ s a -> s{_lsrNextPageToken = a}) -- | The Services matching the specified filter. lsrServices :: Lens' ListServicesResponse [Service] lsrServices = lens _lsrServices (\ s a -> s{_lsrServices = a}) . _Default . _Coerce instance FromJSON ListServicesResponse where parseJSON = withObject "ListServicesResponse" (\ o -> ListServicesResponse' <$> (o .:? "nextPageToken") <*> (o .:? "services" .!= mempty)) instance ToJSON ListServicesResponse where toJSON ListServicesResponse'{..} = object (catMaybes [("nextPageToken" .=) <$> _lsrNextPageToken, ("services" .=) <$> _lsrServices]) -- | The ListNotificationChannelDescriptors response. -- -- /See:/ 'listNotificationChannelDescriptorsResponse' smart constructor. data ListNotificationChannelDescriptorsResponse = ListNotificationChannelDescriptorsResponse' { _lncdrNextPageToken :: !(Maybe Text) , _lncdrChannelDescriptors :: !(Maybe [NotificationChannelDescriptor]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ListNotificationChannelDescriptorsResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lncdrNextPageToken' -- -- * 'lncdrChannelDescriptors' listNotificationChannelDescriptorsResponse :: ListNotificationChannelDescriptorsResponse listNotificationChannelDescriptorsResponse = ListNotificationChannelDescriptorsResponse' {_lncdrNextPageToken = Nothing, _lncdrChannelDescriptors = Nothing} -- | If not empty, indicates that there may be more results that match the -- request. Use the value in the page_token field in a subsequent request -- to fetch the next set of results. If empty, all results have been -- returned. lncdrNextPageToken :: Lens' ListNotificationChannelDescriptorsResponse (Maybe Text) lncdrNextPageToken = lens _lncdrNextPageToken (\ s a -> s{_lncdrNextPageToken = a}) -- | The monitored resource descriptors supported for the specified project, -- optionally filtered. lncdrChannelDescriptors :: Lens' ListNotificationChannelDescriptorsResponse [NotificationChannelDescriptor] lncdrChannelDescriptors = lens _lncdrChannelDescriptors (\ s a -> s{_lncdrChannelDescriptors = a}) . _Default . _Coerce instance FromJSON ListNotificationChannelDescriptorsResponse where parseJSON = withObject "ListNotificationChannelDescriptorsResponse" (\ o -> ListNotificationChannelDescriptorsResponse' <$> (o .:? "nextPageToken") <*> (o .:? "channelDescriptors" .!= mempty)) instance ToJSON ListNotificationChannelDescriptorsResponse where toJSON ListNotificationChannelDescriptorsResponse'{..} = object (catMaybes [("nextPageToken" .=) <$> _lncdrNextPageToken, ("channelDescriptors" .=) <$> _lncdrChannelDescriptors]) -- | A TimeSeriesRatio specifies two TimeSeries to use for computing the -- good_service \/ total_service ratio. The specified TimeSeries must have -- ValueType = DOUBLE or ValueType = INT64 and must have MetricKind = DELTA -- or MetricKind = CUMULATIVE. The TimeSeriesRatio must specify exactly two -- of good, bad, and total, and the relationship good_service + bad_service -- = total_service will be assumed. -- -- /See:/ 'timeSeriesRatio' smart constructor. data TimeSeriesRatio = TimeSeriesRatio' { _tsrTotalServiceFilter :: !(Maybe Text) , _tsrGoodServiceFilter :: !(Maybe Text) , _tsrBadServiceFilter :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'TimeSeriesRatio' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'tsrTotalServiceFilter' -- -- * 'tsrGoodServiceFilter' -- -- * 'tsrBadServiceFilter' timeSeriesRatio :: TimeSeriesRatio timeSeriesRatio = TimeSeriesRatio' { _tsrTotalServiceFilter = Nothing , _tsrGoodServiceFilter = Nothing , _tsrBadServiceFilter = Nothing } -- | A monitoring filter -- (https:\/\/cloud.google.com\/monitoring\/api\/v3\/filters) specifying a -- TimeSeries quantifying total demanded service. Must have ValueType = -- DOUBLE or ValueType = INT64 and must have MetricKind = DELTA or -- MetricKind = CUMULATIVE. tsrTotalServiceFilter :: Lens' TimeSeriesRatio (Maybe Text) tsrTotalServiceFilter = lens _tsrTotalServiceFilter (\ s a -> s{_tsrTotalServiceFilter = a}) -- | A monitoring filter -- (https:\/\/cloud.google.com\/monitoring\/api\/v3\/filters) specifying a -- TimeSeries quantifying good service provided. Must have ValueType = -- DOUBLE or ValueType = INT64 and must have MetricKind = DELTA or -- MetricKind = CUMULATIVE. tsrGoodServiceFilter :: Lens' TimeSeriesRatio (Maybe Text) tsrGoodServiceFilter = lens _tsrGoodServiceFilter (\ s a -> s{_tsrGoodServiceFilter = a}) -- | A monitoring filter -- (https:\/\/cloud.google.com\/monitoring\/api\/v3\/filters) specifying a -- TimeSeries quantifying bad service, either demanded service that was not -- provided or demanded service that was of inadequate quality. Must have -- ValueType = DOUBLE or ValueType = INT64 and must have MetricKind = DELTA -- or MetricKind = CUMULATIVE. tsrBadServiceFilter :: Lens' TimeSeriesRatio (Maybe Text) tsrBadServiceFilter = lens _tsrBadServiceFilter (\ s a -> s{_tsrBadServiceFilter = a}) instance FromJSON TimeSeriesRatio where parseJSON = withObject "TimeSeriesRatio" (\ o -> TimeSeriesRatio' <$> (o .:? "totalServiceFilter") <*> (o .:? "goodServiceFilter") <*> (o .:? "badServiceFilter")) instance ToJSON TimeSeriesRatio where toJSON TimeSeriesRatio'{..} = object (catMaybes [("totalServiceFilter" .=) <$> _tsrTotalServiceFilter, ("goodServiceFilter" .=) <$> _tsrGoodServiceFilter, ("badServiceFilter" .=) <$> _tsrBadServiceFilter]) -- | Defines a metric type and its schema. Once a metric descriptor is -- created, deleting or altering it stops data collection and makes the -- metric type\'s existing data unusable. -- -- /See:/ 'metricDescriptor' smart constructor. data MetricDescriptor = MetricDescriptor' { _mdMonitoredResourceTypes :: !(Maybe [Text]) , _mdMetricKind :: !(Maybe MetricDescriptorMetricKind) , _mdName :: !(Maybe Text) , _mdMetadata :: !(Maybe MetricDescriptorMetadata) , _mdDisplayName :: !(Maybe Text) , _mdLabels :: !(Maybe [LabelDescriptor]) , _mdType :: !(Maybe Text) , _mdValueType :: !(Maybe MetricDescriptorValueType) , _mdDescription :: !(Maybe Text) , _mdUnit :: !(Maybe Text) , _mdLaunchStage :: !(Maybe MetricDescriptorLaunchStage) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'MetricDescriptor' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'mdMonitoredResourceTypes' -- -- * 'mdMetricKind' -- -- * 'mdName' -- -- * 'mdMetadata' -- -- * 'mdDisplayName' -- -- * 'mdLabels' -- -- * 'mdType' -- -- * 'mdValueType' -- -- * 'mdDescription' -- -- * 'mdUnit' -- -- * 'mdLaunchStage' metricDescriptor :: MetricDescriptor metricDescriptor = MetricDescriptor' { _mdMonitoredResourceTypes = Nothing , _mdMetricKind = Nothing , _mdName = Nothing , _mdMetadata = Nothing , _mdDisplayName = Nothing , _mdLabels = Nothing , _mdType = Nothing , _mdValueType = Nothing , _mdDescription = Nothing , _mdUnit = Nothing , _mdLaunchStage = Nothing } -- | Read-only. If present, then a time series, which is identified partially -- by a metric type and a MonitoredResourceDescriptor, that is associated -- with this metric type can only be associated with one of the monitored -- resource types listed here. mdMonitoredResourceTypes :: Lens' MetricDescriptor [Text] mdMonitoredResourceTypes = lens _mdMonitoredResourceTypes (\ s a -> s{_mdMonitoredResourceTypes = a}) . _Default . _Coerce -- | Whether the metric records instantaneous values, changes to a value, -- etc. Some combinations of metric_kind and value_type might not be -- supported. mdMetricKind :: Lens' MetricDescriptor (Maybe MetricDescriptorMetricKind) mdMetricKind = lens _mdMetricKind (\ s a -> s{_mdMetricKind = a}) -- | The resource name of the metric descriptor. mdName :: Lens' MetricDescriptor (Maybe Text) mdName = lens _mdName (\ s a -> s{_mdName = a}) -- | Optional. Metadata which can be used to guide usage of the metric. mdMetadata :: Lens' MetricDescriptor (Maybe MetricDescriptorMetadata) mdMetadata = lens _mdMetadata (\ s a -> s{_mdMetadata = a}) -- | A concise name for the metric, which can be displayed in user -- interfaces. Use sentence case without an ending period, for example -- \"Request count\". This field is optional but it is recommended to be -- set for any metrics associated with user-visible concepts, such as -- Quota. mdDisplayName :: Lens' MetricDescriptor (Maybe Text) mdDisplayName = lens _mdDisplayName (\ s a -> s{_mdDisplayName = a}) -- | The set of labels that can be used to describe a specific instance of -- this metric type. For example, the -- appengine.googleapis.com\/http\/server\/response_latencies metric type -- has a label for the HTTP response code, response_code, so you can look -- at latencies for successful responses or just for responses that failed. mdLabels :: Lens' MetricDescriptor [LabelDescriptor] mdLabels = lens _mdLabels (\ s a -> s{_mdLabels = a}) . _Default . _Coerce -- | The metric type, including its DNS name prefix. The type is not -- URL-encoded. All user-defined metric types have the DNS name -- custom.googleapis.com or external.googleapis.com. Metric types should -- use a natural hierarchical grouping. For example: -- \"custom.googleapis.com\/invoice\/paid\/amount\" -- \"external.googleapis.com\/prometheus\/up\" -- \"appengine.googleapis.com\/http\/server\/response_latencies\" mdType :: Lens' MetricDescriptor (Maybe Text) mdType = lens _mdType (\ s a -> s{_mdType = a}) -- | Whether the measurement is an integer, a floating-point number, etc. -- Some combinations of metric_kind and value_type might not be supported. mdValueType :: Lens' MetricDescriptor (Maybe MetricDescriptorValueType) mdValueType = lens _mdValueType (\ s a -> s{_mdValueType = a}) -- | A detailed description of the metric, which can be used in -- documentation. mdDescription :: Lens' MetricDescriptor (Maybe Text) mdDescription = lens _mdDescription (\ s a -> s{_mdDescription = a}) -- | The units in which the metric value is reported. It is only applicable -- if the value_type is INT64, DOUBLE, or DISTRIBUTION. The unit defines -- the representation of the stored metric values.Different systems might -- scale the values to be more easily displayed (so a value of 0.02kBy -- might be displayed as 20By, and a value of 3523kBy might be displayed as -- 3.5MBy). However, if the unit is kBy, then the value of the metric is -- always in thousands of bytes, no matter how it might be displayed.If you -- want a custom metric to record the exact number of CPU-seconds used by a -- job, you can create an INT64 CUMULATIVE metric whose unit is s{CPU} (or -- equivalently 1s{CPU} or just s). If the job uses 12,005 CPU-seconds, -- then the value is written as 12005.Alternatively, if you want a custom -- metric to record data in a more granular way, you can create a DOUBLE -- CUMULATIVE metric whose unit is ks{CPU}, and then write the value 12.005 -- (which is 12005\/1000), or use Kis{CPU} and write 11.723 (which is -- 12005\/1024).The supported units are a subset of The Unified Code for -- Units of Measure (https:\/\/unitsofmeasure.org\/ucum.html) -- standard:Basic units (UNIT) bit bit By byte s second min minute h hour d -- day 1 dimensionlessPrefixes (PREFIX) k kilo (10^3) M mega (10^6) G giga -- (10^9) T tera (10^12) P peta (10^15) E exa (10^18) Z zetta (10^21) Y -- yotta (10^24) m milli (10^-3) u micro (10^-6) n nano (10^-9) p pico -- (10^-12) f femto (10^-15) a atto (10^-18) z zepto (10^-21) y yocto -- (10^-24) Ki kibi (2^10) Mi mebi (2^20) Gi gibi (2^30) Ti tebi (2^40) Pi -- pebi (2^50)GrammarThe grammar also includes these connectors: \/ -- division or ratio (as an infix operator). For examples, kBy\/{email} or -- MiBy\/10ms (although you should almost never have \/s in a metric unit; -- rates should always be computed at query time from the underlying -- cumulative or delta value). . multiplication or composition (as an infix -- operator). For examples, GBy.d or k{watt}.h.The grammar for a unit is as -- follows: Expression = Component { \".\" Component } { \"\/\" Component } -- ; Component = ( [ PREFIX ] UNIT | \"%\" ) [ Annotation ] | Annotation | -- \"1\" ; Annotation = \"{\" NAME \"}\" ; Notes: Annotation is just a -- comment if it follows a UNIT. If the annotation is used alone, then the -- unit is equivalent to 1. For examples, {request}\/s == 1\/s, -- By{transmitted}\/s == By\/s. NAME is a sequence of non-blank printable -- ASCII characters not containing { or }. 1 represents a unitary -- dimensionless unit -- (https:\/\/en.wikipedia.org\/wiki\/Dimensionless_quantity) of 1, such as -- in 1\/s. It is typically used when none of the basic units are -- appropriate. For example, \"new users per day\" can be represented as -- 1\/d or {new-users}\/d (and a metric value 5 would mean \"5 new users). -- Alternatively, \"thousands of page views per day\" would be represented -- as 1000\/d or k1\/d or k{page_views}\/d (and a metric value of 5.3 would -- mean \"5300 page views per day\"). % represents dimensionless value of -- 1\/100, and annotates values giving a percentage (so the metric values -- are typically in the range of 0..100, and a metric value 3 means \"3 -- percent\"). 10^2.% indicates a metric contains a ratio, typically in the -- range 0..1, that will be multiplied by 100 and displayed as a percentage -- (so a metric value 0.03 means \"3 percent\"). mdUnit :: Lens' MetricDescriptor (Maybe Text) mdUnit = lens _mdUnit (\ s a -> s{_mdUnit = a}) -- | Optional. The launch stage of the metric definition. mdLaunchStage :: Lens' MetricDescriptor (Maybe MetricDescriptorLaunchStage) mdLaunchStage = lens _mdLaunchStage (\ s a -> s{_mdLaunchStage = a}) instance FromJSON MetricDescriptor where parseJSON = withObject "MetricDescriptor" (\ o -> MetricDescriptor' <$> (o .:? "monitoredResourceTypes" .!= mempty) <*> (o .:? "metricKind") <*> (o .:? "name") <*> (o .:? "metadata") <*> (o .:? "displayName") <*> (o .:? "labels" .!= mempty) <*> (o .:? "type") <*> (o .:? "valueType") <*> (o .:? "description") <*> (o .:? "unit") <*> (o .:? "launchStage")) instance ToJSON MetricDescriptor where toJSON MetricDescriptor'{..} = object (catMaybes [("monitoredResourceTypes" .=) <$> _mdMonitoredResourceTypes, ("metricKind" .=) <$> _mdMetricKind, ("name" .=) <$> _mdName, ("metadata" .=) <$> _mdMetadata, ("displayName" .=) <$> _mdDisplayName, ("labels" .=) <$> _mdLabels, ("type" .=) <$> _mdType, ("valueType" .=) <$> _mdValueType, ("description" .=) <$> _mdDescription, ("unit" .=) <$> _mdUnit, ("launchStage" .=) <$> _mdLaunchStage]) -- | Range of numerical values within min and max. If the open range \"\< -- range.max\" is desired, set range.min = -infinity. If the open range -- \">= range.min\" is desired, set range.max = infinity. -- -- /See:/ 'googleMonitoringV3Range' smart constructor. data GoogleMonitoringV3Range = GoogleMonitoringV3Range' { _gmvrMax :: !(Maybe (Textual Double)) , _gmvrMin :: !(Maybe (Textual Double)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GoogleMonitoringV3Range' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gmvrMax' -- -- * 'gmvrMin' googleMonitoringV3Range :: GoogleMonitoringV3Range googleMonitoringV3Range = GoogleMonitoringV3Range' {_gmvrMax = Nothing, _gmvrMin = Nothing} -- | Range maximum. gmvrMax :: Lens' GoogleMonitoringV3Range (Maybe Double) gmvrMax = lens _gmvrMax (\ s a -> s{_gmvrMax = a}) . mapping _Coerce -- | Range minimum. gmvrMin :: Lens' GoogleMonitoringV3Range (Maybe Double) gmvrMin = lens _gmvrMin (\ s a -> s{_gmvrMin = a}) . mapping _Coerce instance FromJSON GoogleMonitoringV3Range where parseJSON = withObject "GoogleMonitoringV3Range" (\ o -> GoogleMonitoringV3Range' <$> (o .:? "max") <*> (o .:? "min")) instance ToJSON GoogleMonitoringV3Range where toJSON GoogleMonitoringV3Range'{..} = object (catMaybes [("max" .=) <$> _gmvrMax, ("min" .=) <$> _gmvrMin]) -- | The description of a dynamic collection of monitored resources. Each -- group has a filter that is matched against monitored resources and their -- associated metadata. If a group\'s filter matches an available monitored -- resource, then that resource is a member of that group. Groups can -- contain any number of monitored resources, and each monitored resource -- can be a member of any number of groups.Groups can be nested in -- parent-child hierarchies. The parentName field identifies an optional -- parent for each group. If a group has a parent, then the only monitored -- resources available to be matched by the group\'s filter are the -- resources contained in the parent group. In other words, a group -- contains the monitored resources that match its filter and the filters -- of all the group\'s ancestors. A group without a parent can contain any -- monitored resource.For example, consider an infrastructure running a set -- of instances with two user-defined tags: \"environment\" and \"role\". A -- parent group has a filter, environment=\"production\". A child of that -- parent group has a filter, role=\"transcoder\". The parent group -- contains all instances in the production environment, regardless of -- their roles. The child group contains instances that have the transcoder -- role and are in the production environment.The monitored resources -- contained in a group can change at any moment, depending on what -- resources exist and what filters are associated with the group and its -- ancestors. -- -- /See:/ 'group'' smart constructor. data Group = Group' { _gName :: !(Maybe Text) , _gDisplayName :: !(Maybe Text) , _gFilter :: !(Maybe Text) , _gIsCluster :: !(Maybe Bool) , _gParentName :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Group' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gName' -- -- * 'gDisplayName' -- -- * 'gFilter' -- -- * 'gIsCluster' -- -- * 'gParentName' group' :: Group group' = Group' { _gName = Nothing , _gDisplayName = Nothing , _gFilter = Nothing , _gIsCluster = Nothing , _gParentName = Nothing } -- | Output only. The name of this group. The format is: -- projects\/[PROJECT_ID_OR_NUMBER]\/groups\/[GROUP_ID] When creating a -- group, this field is ignored and a new name is created consisting of the -- project specified in the call to CreateGroup and a unique [GROUP_ID] -- that is generated automatically. gName :: Lens' Group (Maybe Text) gName = lens _gName (\ s a -> s{_gName = a}) -- | A user-assigned name for this group, used only for display purposes. gDisplayName :: Lens' Group (Maybe Text) gDisplayName = lens _gDisplayName (\ s a -> s{_gDisplayName = a}) -- | The filter used to determine which monitored resources belong to this -- group. gFilter :: Lens' Group (Maybe Text) gFilter = lens _gFilter (\ s a -> s{_gFilter = a}) -- | If true, the members of this group are considered to be a cluster. The -- system can perform additional analysis on groups that are clusters. gIsCluster :: Lens' Group (Maybe Bool) gIsCluster = lens _gIsCluster (\ s a -> s{_gIsCluster = a}) -- | The name of the group\'s parent, if it has one. The format is: -- projects\/[PROJECT_ID_OR_NUMBER]\/groups\/[GROUP_ID] For groups with no -- parent, parent_name is the empty string, \"\". gParentName :: Lens' Group (Maybe Text) gParentName = lens _gParentName (\ s a -> s{_gParentName = a}) instance FromJSON Group where parseJSON = withObject "Group" (\ o -> Group' <$> (o .:? "name") <*> (o .:? "displayName") <*> (o .:? "filter") <*> (o .:? "isCluster") <*> (o .:? "parentName")) instance ToJSON Group where toJSON Group'{..} = object (catMaybes [("name" .=) <$> _gName, ("displayName" .=) <$> _gDisplayName, ("filter" .=) <$> _gFilter, ("isCluster" .=) <$> _gIsCluster, ("parentName" .=) <$> _gParentName]) -- | A single strongly-typed value. -- -- /See:/ 'typedValue' smart constructor. data TypedValue = TypedValue' { _tvBoolValue :: !(Maybe Bool) , _tvDoubleValue :: !(Maybe (Textual Double)) , _tvStringValue :: !(Maybe Text) , _tvDistributionValue :: !(Maybe Distribution) , _tvInt64Value :: !(Maybe (Textual Int64)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'TypedValue' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'tvBoolValue' -- -- * 'tvDoubleValue' -- -- * 'tvStringValue' -- -- * 'tvDistributionValue' -- -- * 'tvInt64Value' typedValue :: TypedValue typedValue = TypedValue' { _tvBoolValue = Nothing , _tvDoubleValue = Nothing , _tvStringValue = Nothing , _tvDistributionValue = Nothing , _tvInt64Value = Nothing } -- | A Boolean value: true or false. tvBoolValue :: Lens' TypedValue (Maybe Bool) tvBoolValue = lens _tvBoolValue (\ s a -> s{_tvBoolValue = a}) -- | A 64-bit double-precision floating-point number. Its magnitude is -- approximately Β±10Β±300 and it has 16 significant digits of precision. tvDoubleValue :: Lens' TypedValue (Maybe Double) tvDoubleValue = lens _tvDoubleValue (\ s a -> s{_tvDoubleValue = a}) . mapping _Coerce -- | A variable-length string value. tvStringValue :: Lens' TypedValue (Maybe Text) tvStringValue = lens _tvStringValue (\ s a -> s{_tvStringValue = a}) -- | A distribution value. tvDistributionValue :: Lens' TypedValue (Maybe Distribution) tvDistributionValue = lens _tvDistributionValue (\ s a -> s{_tvDistributionValue = a}) -- | A 64-bit integer. Its range is approximately Β±9.2x1018. tvInt64Value :: Lens' TypedValue (Maybe Int64) tvInt64Value = lens _tvInt64Value (\ s a -> s{_tvInt64Value = a}) . mapping _Coerce instance FromJSON TypedValue where parseJSON = withObject "TypedValue" (\ o -> TypedValue' <$> (o .:? "boolValue") <*> (o .:? "doubleValue") <*> (o .:? "stringValue") <*> (o .:? "distributionValue") <*> (o .:? "int64Value")) instance ToJSON TypedValue where toJSON TypedValue'{..} = object (catMaybes [("boolValue" .=) <$> _tvBoolValue, ("doubleValue" .=) <$> _tvDoubleValue, ("stringValue" .=) <$> _tvStringValue, ("distributionValue" .=) <$> _tvDistributionValue, ("int64Value" .=) <$> _tvInt64Value]) -- | Required. Values for all of the labels listed in the associated -- monitored resource descriptor. For example, Compute Engine VM instances -- use the labels \"project_id\", \"instance_id\", and \"zone\". -- -- /See:/ 'monitoredResourceLabels' smart constructor. newtype MonitoredResourceLabels = MonitoredResourceLabels' { _mrlAddtional :: HashMap Text Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'MonitoredResourceLabels' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'mrlAddtional' monitoredResourceLabels :: HashMap Text Text -- ^ 'mrlAddtional' -> MonitoredResourceLabels monitoredResourceLabels pMrlAddtional_ = MonitoredResourceLabels' {_mrlAddtional = _Coerce # pMrlAddtional_} mrlAddtional :: Lens' MonitoredResourceLabels (HashMap Text Text) mrlAddtional = lens _mrlAddtional (\ s a -> s{_mrlAddtional = a}) . _Coerce instance FromJSON MonitoredResourceLabels where parseJSON = withObject "MonitoredResourceLabels" (\ o -> MonitoredResourceLabels' <$> (parseJSONObject o)) instance ToJSON MonitoredResourceLabels where toJSON = toJSON . _mrlAddtional -- | Auxiliary metadata for a MonitoredResource object. MonitoredResource -- objects contain the minimum set of information to uniquely identify a -- monitored resource instance. There is some other useful auxiliary -- metadata. Monitoring and Logging use an ingestion pipeline to extract -- metadata for cloud resources of all types, and store the metadata in -- this message. -- -- /See:/ 'monitoredResourceMetadata' smart constructor. data MonitoredResourceMetadata = MonitoredResourceMetadata' { _mrmUserLabels :: !(Maybe MonitoredResourceMetadataUserLabels) , _mrmSystemLabels :: !(Maybe MonitoredResourceMetadataSystemLabels) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'MonitoredResourceMetadata' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'mrmUserLabels' -- -- * 'mrmSystemLabels' monitoredResourceMetadata :: MonitoredResourceMetadata monitoredResourceMetadata = MonitoredResourceMetadata' {_mrmUserLabels = Nothing, _mrmSystemLabels = Nothing} -- | Output only. A map of user-defined metadata labels. mrmUserLabels :: Lens' MonitoredResourceMetadata (Maybe MonitoredResourceMetadataUserLabels) mrmUserLabels = lens _mrmUserLabels (\ s a -> s{_mrmUserLabels = a}) -- | Output only. Values for predefined system metadata labels. System labels -- are a kind of metadata extracted by Google, including \"machine_image\", -- \"vpc\", \"subnet_id\", \"security_group\", \"name\", etc. System label -- values can be only strings, Boolean values, or a list of strings. For -- example: { \"name\": \"my-test-instance\", \"security_group\": [\"a\", -- \"b\", \"c\"], \"spot_instance\": false } mrmSystemLabels :: Lens' MonitoredResourceMetadata (Maybe MonitoredResourceMetadataSystemLabels) mrmSystemLabels = lens _mrmSystemLabels (\ s a -> s{_mrmSystemLabels = a}) instance FromJSON MonitoredResourceMetadata where parseJSON = withObject "MonitoredResourceMetadata" (\ o -> MonitoredResourceMetadata' <$> (o .:? "userLabels") <*> (o .:? "systemLabels")) instance ToJSON MonitoredResourceMetadata where toJSON MonitoredResourceMetadata'{..} = object (catMaybes [("userLabels" .=) <$> _mrmUserLabels, ("systemLabels" .=) <$> _mrmSystemLabels]) -- | User-supplied key\/value data that does not need to conform to the -- corresponding NotificationChannelDescriptor\'s schema, unlike the labels -- field. This field is intended to be used for organizing and identifying -- the NotificationChannel objects.The field can contain up to 64 entries. -- Each key and value is limited to 63 Unicode characters or 128 bytes, -- whichever is smaller. Labels and values can contain only lowercase -- letters, numerals, underscores, and dashes. Keys must begin with a -- letter. -- -- /See:/ 'notificationChannelUserLabels' smart constructor. newtype NotificationChannelUserLabels = NotificationChannelUserLabels' { _nculAddtional :: HashMap Text Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'NotificationChannelUserLabels' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'nculAddtional' notificationChannelUserLabels :: HashMap Text Text -- ^ 'nculAddtional' -> NotificationChannelUserLabels notificationChannelUserLabels pNculAddtional_ = NotificationChannelUserLabels' {_nculAddtional = _Coerce # pNculAddtional_} nculAddtional :: Lens' NotificationChannelUserLabels (HashMap Text Text) nculAddtional = lens _nculAddtional (\ s a -> s{_nculAddtional = a}) . _Coerce instance FromJSON NotificationChannelUserLabels where parseJSON = withObject "NotificationChannelUserLabels" (\ o -> NotificationChannelUserLabels' <$> (parseJSONObject o)) instance ToJSON NotificationChannelUserLabels where toJSON = toJSON . _nculAddtional -- | SourceContext represents information about the source of a protobuf -- element, like the file in which it is defined. -- -- /See:/ 'sourceContext' smart constructor. newtype SourceContext = SourceContext' { _scFileName :: Maybe Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'SourceContext' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'scFileName' sourceContext :: SourceContext sourceContext = SourceContext' {_scFileName = Nothing} -- | The path-qualified name of the .proto file that contained the associated -- protobuf element. For example: -- \"google\/protobuf\/source_context.proto\". scFileName :: Lens' SourceContext (Maybe Text) scFileName = lens _scFileName (\ s a -> s{_scFileName = a}) instance FromJSON SourceContext where parseJSON = withObject "SourceContext" (\ o -> SourceContext' <$> (o .:? "fileName")) instance ToJSON SourceContext where toJSON SourceContext'{..} = object (catMaybes [("fileName" .=) <$> _scFileName]) -- | The authentication parameters to provide to the specified resource or -- URL that requires a username and password. Currently, only Basic HTTP -- authentication (https:\/\/tools.ietf.org\/html\/rfc7617) is supported in -- Uptime checks. -- -- /See:/ 'basicAuthentication' smart constructor. data BasicAuthentication = BasicAuthentication' { _baUsername :: !(Maybe Text) , _baPassword :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'BasicAuthentication' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'baUsername' -- -- * 'baPassword' basicAuthentication :: BasicAuthentication basicAuthentication = BasicAuthentication' {_baUsername = Nothing, _baPassword = Nothing} -- | The username to use when authenticating with the HTTP server. baUsername :: Lens' BasicAuthentication (Maybe Text) baUsername = lens _baUsername (\ s a -> s{_baUsername = a}) -- | The password to use when authenticating with the HTTP server. baPassword :: Lens' BasicAuthentication (Maybe Text) baPassword = lens _baPassword (\ s a -> s{_baPassword = a}) instance FromJSON BasicAuthentication where parseJSON = withObject "BasicAuthentication" (\ o -> BasicAuthentication' <$> (o .:? "username") <*> (o .:? "password")) instance ToJSON BasicAuthentication where toJSON BasicAuthentication'{..} = object (catMaybes [("username" .=) <$> _baUsername, ("password" .=) <$> _baPassword]) -- | Distribution contains summary statistics for a population of values. It -- optionally contains a histogram representing the distribution of those -- values across a set of buckets.The summary statistics are the count, -- mean, sum of the squared deviation from the mean, the minimum, and the -- maximum of the set of population of values. The histogram is based on a -- sequence of buckets and gives a count of values that fall into each -- bucket. The boundaries of the buckets are given either explicitly or by -- formulas for buckets of fixed or exponentially increasing -- widths.Although it is not forbidden, it is generally a bad idea to -- include non-finite values (infinities or NaNs) in the population of -- values, as this will render the mean and sum_of_squared_deviation fields -- meaningless. -- -- /See:/ 'distribution' smart constructor. data Distribution = Distribution' { _dSumOfSquaredDeviation :: !(Maybe (Textual Double)) , _dMean :: !(Maybe (Textual Double)) , _dCount :: !(Maybe (Textual Int64)) , _dBucketCounts :: !(Maybe [Textual Int64]) , _dExemplars :: !(Maybe [Exemplar]) , _dRange :: !(Maybe Range) , _dBucketOptions :: !(Maybe BucketOptions) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Distribution' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dSumOfSquaredDeviation' -- -- * 'dMean' -- -- * 'dCount' -- -- * 'dBucketCounts' -- -- * 'dExemplars' -- -- * 'dRange' -- -- * 'dBucketOptions' distribution :: Distribution distribution = Distribution' { _dSumOfSquaredDeviation = Nothing , _dMean = Nothing , _dCount = Nothing , _dBucketCounts = Nothing , _dExemplars = Nothing , _dRange = Nothing , _dBucketOptions = Nothing } -- | The sum of squared deviations from the mean of the values in the -- population. For values x_i this is: Sum[i=1..n]((x_i - mean)^2) Knuth, -- \"The Art of Computer Programming\", Vol. 2, page 232, 3rd edition -- describes Welford\'s method for accumulating this sum in one pass.If -- count is zero then this field must be zero. dSumOfSquaredDeviation :: Lens' Distribution (Maybe Double) dSumOfSquaredDeviation = lens _dSumOfSquaredDeviation (\ s a -> s{_dSumOfSquaredDeviation = a}) . mapping _Coerce -- | The arithmetic mean of the values in the population. If count is zero -- then this field must be zero. dMean :: Lens' Distribution (Maybe Double) dMean = lens _dMean (\ s a -> s{_dMean = a}) . mapping _Coerce -- | The number of values in the population. Must be non-negative. This value -- must equal the sum of the values in bucket_counts if a histogram is -- provided. dCount :: Lens' Distribution (Maybe Int64) dCount = lens _dCount (\ s a -> s{_dCount = a}) . mapping _Coerce -- | Required in the Cloud Monitoring API v3. The values for each bucket -- specified in bucket_options. The sum of the values in bucketCounts must -- equal the value in the count field of the Distribution object. The order -- of the bucket counts follows the numbering schemes described for the -- three bucket types. The underflow bucket has number 0; the finite -- buckets, if any, have numbers 1 through N-2; and the overflow bucket has -- number N-1. The size of bucket_counts must not be greater than N. If the -- size is less than N, then the remaining buckets are assigned values of -- zero. dBucketCounts :: Lens' Distribution [Int64] dBucketCounts = lens _dBucketCounts (\ s a -> s{_dBucketCounts = a}) . _Default . _Coerce -- | Must be in increasing order of value field. dExemplars :: Lens' Distribution [Exemplar] dExemplars = lens _dExemplars (\ s a -> s{_dExemplars = a}) . _Default . _Coerce -- | If specified, contains the range of the population values. The field -- must not be present if the count is zero. This field is presently -- ignored by the Cloud Monitoring API v3. dRange :: Lens' Distribution (Maybe Range) dRange = lens _dRange (\ s a -> s{_dRange = a}) -- | Required in the Cloud Monitoring API v3. Defines the histogram bucket -- boundaries. dBucketOptions :: Lens' Distribution (Maybe BucketOptions) dBucketOptions = lens _dBucketOptions (\ s a -> s{_dBucketOptions = a}) instance FromJSON Distribution where parseJSON = withObject "Distribution" (\ o -> Distribution' <$> (o .:? "sumOfSquaredDeviation") <*> (o .:? "mean") <*> (o .:? "count") <*> (o .:? "bucketCounts" .!= mempty) <*> (o .:? "exemplars" .!= mempty) <*> (o .:? "range") <*> (o .:? "bucketOptions")) instance ToJSON Distribution where toJSON Distribution'{..} = object (catMaybes [("sumOfSquaredDeviation" .=) <$> _dSumOfSquaredDeviation, ("mean" .=) <$> _dMean, ("count" .=) <$> _dCount, ("bucketCounts" .=) <$> _dBucketCounts, ("exemplars" .=) <$> _dExemplars, ("range" .=) <$> _dRange, ("bucketOptions" .=) <$> _dBucketOptions]) -- | A single field of a message type. -- -- /See:/ 'field' smart constructor. data Field = Field' { _fKind :: !(Maybe FieldKind) , _fOneofIndex :: !(Maybe (Textual Int32)) , _fName :: !(Maybe Text) , _fJSONName :: !(Maybe Text) , _fCardinality :: !(Maybe FieldCardinality) , _fOptions :: !(Maybe [Option]) , _fPacked :: !(Maybe Bool) , _fDefaultValue :: !(Maybe Text) , _fNumber :: !(Maybe (Textual Int32)) , _fTypeURL :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Field' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'fKind' -- -- * 'fOneofIndex' -- -- * 'fName' -- -- * 'fJSONName' -- -- * 'fCardinality' -- -- * 'fOptions' -- -- * 'fPacked' -- -- * 'fDefaultValue' -- -- * 'fNumber' -- -- * 'fTypeURL' field :: Field field = Field' { _fKind = Nothing , _fOneofIndex = Nothing , _fName = Nothing , _fJSONName = Nothing , _fCardinality = Nothing , _fOptions = Nothing , _fPacked = Nothing , _fDefaultValue = Nothing , _fNumber = Nothing , _fTypeURL = Nothing } -- | The field type. fKind :: Lens' Field (Maybe FieldKind) fKind = lens _fKind (\ s a -> s{_fKind = a}) -- | The index of the field type in Type.oneofs, for message or enumeration -- types. The first type has index 1; zero means the type is not in the -- list. fOneofIndex :: Lens' Field (Maybe Int32) fOneofIndex = lens _fOneofIndex (\ s a -> s{_fOneofIndex = a}) . mapping _Coerce -- | The field name. fName :: Lens' Field (Maybe Text) fName = lens _fName (\ s a -> s{_fName = a}) -- | The field JSON name. fJSONName :: Lens' Field (Maybe Text) fJSONName = lens _fJSONName (\ s a -> s{_fJSONName = a}) -- | The field cardinality. fCardinality :: Lens' Field (Maybe FieldCardinality) fCardinality = lens _fCardinality (\ s a -> s{_fCardinality = a}) -- | The protocol buffer options. fOptions :: Lens' Field [Option] fOptions = lens _fOptions (\ s a -> s{_fOptions = a}) . _Default . _Coerce -- | Whether to use alternative packed wire representation. fPacked :: Lens' Field (Maybe Bool) fPacked = lens _fPacked (\ s a -> s{_fPacked = a}) -- | The string value of the default value of this field. Proto2 syntax only. fDefaultValue :: Lens' Field (Maybe Text) fDefaultValue = lens _fDefaultValue (\ s a -> s{_fDefaultValue = a}) -- | The field number. fNumber :: Lens' Field (Maybe Int32) fNumber = lens _fNumber (\ s a -> s{_fNumber = a}) . mapping _Coerce -- | The field type URL, without the scheme, for message or enumeration -- types. Example: \"type.googleapis.com\/google.protobuf.Timestamp\". fTypeURL :: Lens' Field (Maybe Text) fTypeURL = lens _fTypeURL (\ s a -> s{_fTypeURL = a}) instance FromJSON Field where parseJSON = withObject "Field" (\ o -> Field' <$> (o .:? "kind") <*> (o .:? "oneofIndex") <*> (o .:? "name") <*> (o .:? "jsonName") <*> (o .:? "cardinality") <*> (o .:? "options" .!= mempty) <*> (o .:? "packed") <*> (o .:? "defaultValue") <*> (o .:? "number") <*> (o .:? "typeUrl")) instance ToJSON Field where toJSON Field'{..} = object (catMaybes [("kind" .=) <$> _fKind, ("oneofIndex" .=) <$> _fOneofIndex, ("name" .=) <$> _fName, ("jsonName" .=) <$> _fJSONName, ("cardinality" .=) <$> _fCardinality, ("options" .=) <$> _fOptions, ("packed" .=) <$> _fPacked, ("defaultValue" .=) <$> _fDefaultValue, ("number" .=) <$> _fNumber, ("typeUrl" .=) <$> _fTypeURL]) -- -- /See:/ 'exemplarAttachmentsItem' smart constructor. newtype ExemplarAttachmentsItem = ExemplarAttachmentsItem' { _eaiAddtional :: HashMap Text JSONValue } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ExemplarAttachmentsItem' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'eaiAddtional' exemplarAttachmentsItem :: HashMap Text JSONValue -- ^ 'eaiAddtional' -> ExemplarAttachmentsItem exemplarAttachmentsItem pEaiAddtional_ = ExemplarAttachmentsItem' {_eaiAddtional = _Coerce # pEaiAddtional_} -- | Properties of the object. Contains field \'type with type URL. eaiAddtional :: Lens' ExemplarAttachmentsItem (HashMap Text JSONValue) eaiAddtional = lens _eaiAddtional (\ s a -> s{_eaiAddtional = a}) . _Coerce instance FromJSON ExemplarAttachmentsItem where parseJSON = withObject "ExemplarAttachmentsItem" (\ o -> ExemplarAttachmentsItem' <$> (parseJSONObject o)) instance ToJSON ExemplarAttachmentsItem where toJSON = toJSON . _eaiAddtional -- | A Service is a discrete, autonomous, and network-accessible unit, -- designed to solve an individual concern (Wikipedia -- (https:\/\/en.wikipedia.org\/wiki\/Service-orientation)). In Cloud -- Monitoring, a Service acts as the root resource under which operational -- aspects of the service are accessible. -- -- /See:/ 'service' smart constructor. data Service = Service' { _sTelemetry :: !(Maybe Telemetry) , _sCustom :: !(Maybe Custom) , _sUserLabels :: !(Maybe ServiceUserLabels) , _sIstioCanonicalService :: !(Maybe IstioCanonicalService) , _sName :: !(Maybe Text) , _sAppEngine :: !(Maybe AppEngine) , _sClusterIstio :: !(Maybe ClusterIstio) , _sDisplayName :: !(Maybe Text) , _sMeshIstio :: !(Maybe MeshIstio) , _sCloudEndpoints :: !(Maybe CloudEndpoints) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Service' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'sTelemetry' -- -- * 'sCustom' -- -- * 'sUserLabels' -- -- * 'sIstioCanonicalService' -- -- * 'sName' -- -- * 'sAppEngine' -- -- * 'sClusterIstio' -- -- * 'sDisplayName' -- -- * 'sMeshIstio' -- -- * 'sCloudEndpoints' service :: Service service = Service' { _sTelemetry = Nothing , _sCustom = Nothing , _sUserLabels = Nothing , _sIstioCanonicalService = Nothing , _sName = Nothing , _sAppEngine = Nothing , _sClusterIstio = Nothing , _sDisplayName = Nothing , _sMeshIstio = Nothing , _sCloudEndpoints = Nothing } -- | Configuration for how to query telemetry on a Service. sTelemetry :: Lens' Service (Maybe Telemetry) sTelemetry = lens _sTelemetry (\ s a -> s{_sTelemetry = a}) -- | Custom service type. sCustom :: Lens' Service (Maybe Custom) sCustom = lens _sCustom (\ s a -> s{_sCustom = a}) -- | Labels which have been used to annotate the service. Label keys must -- start with a letter. Label keys and values may contain lowercase -- letters, numbers, underscores, and dashes. Label keys and values have a -- maximum length of 63 characters, and must be less than 128 bytes in -- size. Up to 64 label entries may be stored. For labels which do not have -- a semantic value, the empty string may be supplied for the label value. sUserLabels :: Lens' Service (Maybe ServiceUserLabels) sUserLabels = lens _sUserLabels (\ s a -> s{_sUserLabels = a}) -- | Type used for canonical services scoped to an Istio mesh. Metrics for -- Istio are documented here -- (https:\/\/istio.io\/latest\/docs\/reference\/config\/metrics\/) sIstioCanonicalService :: Lens' Service (Maybe IstioCanonicalService) sIstioCanonicalService = lens _sIstioCanonicalService (\ s a -> s{_sIstioCanonicalService = a}) -- | Resource name for this Service. The format is: -- projects\/[PROJECT_ID_OR_NUMBER]\/services\/[SERVICE_ID] sName :: Lens' Service (Maybe Text) sName = lens _sName (\ s a -> s{_sName = a}) -- | Type used for App Engine services. sAppEngine :: Lens' Service (Maybe AppEngine) sAppEngine = lens _sAppEngine (\ s a -> s{_sAppEngine = a}) -- | Type used for Istio services that live in a Kubernetes cluster. sClusterIstio :: Lens' Service (Maybe ClusterIstio) sClusterIstio = lens _sClusterIstio (\ s a -> s{_sClusterIstio = a}) -- | Name used for UI elements listing this Service. sDisplayName :: Lens' Service (Maybe Text) sDisplayName = lens _sDisplayName (\ s a -> s{_sDisplayName = a}) -- | Type used for Istio services scoped to an Istio mesh. sMeshIstio :: Lens' Service (Maybe MeshIstio) sMeshIstio = lens _sMeshIstio (\ s a -> s{_sMeshIstio = a}) -- | Type used for Cloud Endpoints services. sCloudEndpoints :: Lens' Service (Maybe CloudEndpoints) sCloudEndpoints = lens _sCloudEndpoints (\ s a -> s{_sCloudEndpoints = a}) instance FromJSON Service where parseJSON = withObject "Service" (\ o -> Service' <$> (o .:? "telemetry") <*> (o .:? "custom") <*> (o .:? "userLabels") <*> (o .:? "istioCanonicalService") <*> (o .:? "name") <*> (o .:? "appEngine") <*> (o .:? "clusterIstio") <*> (o .:? "displayName") <*> (o .:? "meshIstio") <*> (o .:? "cloudEndpoints")) instance ToJSON Service where toJSON Service'{..} = object (catMaybes [("telemetry" .=) <$> _sTelemetry, ("custom" .=) <$> _sCustom, ("userLabels" .=) <$> _sUserLabels, ("istioCanonicalService" .=) <$> _sIstioCanonicalService, ("name" .=) <$> _sName, ("appEngine" .=) <$> _sAppEngine, ("clusterIstio" .=) <$> _sClusterIstio, ("displayName" .=) <$> _sDisplayName, ("meshIstio" .=) <$> _sMeshIstio, ("cloudEndpoints" .=) <$> _sCloudEndpoints]) -- | The QueryTimeSeries request. -- -- /See:/ 'queryTimeSeriesRequest' smart constructor. data QueryTimeSeriesRequest = QueryTimeSeriesRequest' { _qtsrQuery :: !(Maybe Text) , _qtsrPageToken :: !(Maybe Text) , _qtsrPageSize :: !(Maybe (Textual Int32)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'QueryTimeSeriesRequest' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'qtsrQuery' -- -- * 'qtsrPageToken' -- -- * 'qtsrPageSize' queryTimeSeriesRequest :: QueryTimeSeriesRequest queryTimeSeriesRequest = QueryTimeSeriesRequest' {_qtsrQuery = Nothing, _qtsrPageToken = Nothing, _qtsrPageSize = Nothing} -- | Required. The query in the Monitoring Query Language -- (https:\/\/cloud.google.com\/monitoring\/mql\/reference) format. The -- default time zone is in UTC. qtsrQuery :: Lens' QueryTimeSeriesRequest (Maybe Text) qtsrQuery = lens _qtsrQuery (\ s a -> s{_qtsrQuery = a}) -- | If this field is not empty then it must contain the nextPageToken value -- returned by a previous call to this method. Using this field causes the -- method to return additional results from the previous method call. qtsrPageToken :: Lens' QueryTimeSeriesRequest (Maybe Text) qtsrPageToken = lens _qtsrPageToken (\ s a -> s{_qtsrPageToken = a}) -- | A positive number that is the maximum number of time_series_data to -- return. qtsrPageSize :: Lens' QueryTimeSeriesRequest (Maybe Int32) qtsrPageSize = lens _qtsrPageSize (\ s a -> s{_qtsrPageSize = a}) . mapping _Coerce instance FromJSON QueryTimeSeriesRequest where parseJSON = withObject "QueryTimeSeriesRequest" (\ o -> QueryTimeSeriesRequest' <$> (o .:? "query") <*> (o .:? "pageToken") <*> (o .:? "pageSize")) instance ToJSON QueryTimeSeriesRequest where toJSON QueryTimeSeriesRequest'{..} = object (catMaybes [("query" .=) <$> _qtsrQuery, ("pageToken" .=) <$> _qtsrPageToken, ("pageSize" .=) <$> _qtsrPageSize]) -- | A description of a notification channel. The descriptor includes the -- properties of the channel and the set of labels or fields that must be -- specified to configure channels of a given type. -- -- /See:/ 'notificationChannelDescriptor' smart constructor. data NotificationChannelDescriptor = NotificationChannelDescriptor' { _ncdName :: !(Maybe Text) , _ncdDisplayName :: !(Maybe Text) , _ncdLabels :: !(Maybe [LabelDescriptor]) , _ncdType :: !(Maybe Text) , _ncdDescription :: !(Maybe Text) , _ncdLaunchStage :: !(Maybe NotificationChannelDescriptorLaunchStage) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'NotificationChannelDescriptor' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ncdName' -- -- * 'ncdDisplayName' -- -- * 'ncdLabels' -- -- * 'ncdType' -- -- * 'ncdDescription' -- -- * 'ncdLaunchStage' notificationChannelDescriptor :: NotificationChannelDescriptor notificationChannelDescriptor = NotificationChannelDescriptor' { _ncdName = Nothing , _ncdDisplayName = Nothing , _ncdLabels = Nothing , _ncdType = Nothing , _ncdDescription = Nothing , _ncdLaunchStage = Nothing } -- | The full REST resource name for this descriptor. The format is: -- projects\/[PROJECT_ID_OR_NUMBER]\/notificationChannelDescriptors\/[TYPE] -- In the above, [TYPE] is the value of the type field. ncdName :: Lens' NotificationChannelDescriptor (Maybe Text) ncdName = lens _ncdName (\ s a -> s{_ncdName = a}) -- | A human-readable name for the notification channel type. This form of -- the name is suitable for a user interface. ncdDisplayName :: Lens' NotificationChannelDescriptor (Maybe Text) ncdDisplayName = lens _ncdDisplayName (\ s a -> s{_ncdDisplayName = a}) -- | The set of labels that must be defined to identify a particular channel -- of the corresponding type. Each label includes a description for how -- that field should be populated. ncdLabels :: Lens' NotificationChannelDescriptor [LabelDescriptor] ncdLabels = lens _ncdLabels (\ s a -> s{_ncdLabels = a}) . _Default . _Coerce -- | The type of notification channel, such as \"email\" and \"sms\". To view -- the full list of channels, see Channel descriptors -- (https:\/\/cloud.google.com\/monitoring\/alerts\/using-channels-api#ncd). -- Notification channel types are globally unique. ncdType :: Lens' NotificationChannelDescriptor (Maybe Text) ncdType = lens _ncdType (\ s a -> s{_ncdType = a}) -- | A human-readable description of the notification channel type. The -- description may include a description of the properties of the channel -- and pointers to external documentation. ncdDescription :: Lens' NotificationChannelDescriptor (Maybe Text) ncdDescription = lens _ncdDescription (\ s a -> s{_ncdDescription = a}) -- | The product launch stage for channels of this type. ncdLaunchStage :: Lens' NotificationChannelDescriptor (Maybe NotificationChannelDescriptorLaunchStage) ncdLaunchStage = lens _ncdLaunchStage (\ s a -> s{_ncdLaunchStage = a}) instance FromJSON NotificationChannelDescriptor where parseJSON = withObject "NotificationChannelDescriptor" (\ o -> NotificationChannelDescriptor' <$> (o .:? "name") <*> (o .:? "displayName") <*> (o .:? "labels" .!= mempty) <*> (o .:? "type") <*> (o .:? "description") <*> (o .:? "launchStage")) instance ToJSON NotificationChannelDescriptor where toJSON NotificationChannelDescriptor'{..} = object (catMaybes [("name" .=) <$> _ncdName, ("displayName" .=) <$> _ncdDisplayName, ("labels" .=) <$> _ncdLabels, ("type" .=) <$> _ncdType, ("description" .=) <$> _ncdDescription, ("launchStage" .=) <$> _ncdLaunchStage]) -- | A label value. -- -- /See:/ 'labelValue' smart constructor. data LabelValue = LabelValue' { _lvBoolValue :: !(Maybe Bool) , _lvStringValue :: !(Maybe Text) , _lvInt64Value :: !(Maybe (Textual Int64)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'LabelValue' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lvBoolValue' -- -- * 'lvStringValue' -- -- * 'lvInt64Value' labelValue :: LabelValue labelValue = LabelValue' {_lvBoolValue = Nothing, _lvStringValue = Nothing, _lvInt64Value = Nothing} -- | A bool label value. lvBoolValue :: Lens' LabelValue (Maybe Bool) lvBoolValue = lens _lvBoolValue (\ s a -> s{_lvBoolValue = a}) -- | A string label value. lvStringValue :: Lens' LabelValue (Maybe Text) lvStringValue = lens _lvStringValue (\ s a -> s{_lvStringValue = a}) -- | An int64 label value. lvInt64Value :: Lens' LabelValue (Maybe Int64) lvInt64Value = lens _lvInt64Value (\ s a -> s{_lvInt64Value = a}) . mapping _Coerce instance FromJSON LabelValue where parseJSON = withObject "LabelValue" (\ o -> LabelValue' <$> (o .:? "boolValue") <*> (o .:? "stringValue") <*> (o .:? "int64Value")) instance ToJSON LabelValue where toJSON LabelValue'{..} = object (catMaybes [("boolValue" .=) <$> _lvBoolValue, ("stringValue" .=) <$> _lvStringValue, ("int64Value" .=) <$> _lvInt64Value]) -- | 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 -- | The ListGroups response. -- -- /See:/ 'listGroupsResponse' smart constructor. data ListGroupsResponse = ListGroupsResponse' { _lgrNextPageToken :: !(Maybe Text) , _lgrGroup :: !(Maybe [Group]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ListGroupsResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lgrNextPageToken' -- -- * 'lgrGroup' listGroupsResponse :: ListGroupsResponse listGroupsResponse = ListGroupsResponse' {_lgrNextPageToken = Nothing, _lgrGroup = Nothing} -- | If there are more results than have been returned, then this field is -- set to a non-empty value. To see the additional results, use that value -- as page_token in the next call to this method. lgrNextPageToken :: Lens' ListGroupsResponse (Maybe Text) lgrNextPageToken = lens _lgrNextPageToken (\ s a -> s{_lgrNextPageToken = a}) -- | The groups that match the specified filters. lgrGroup :: Lens' ListGroupsResponse [Group] lgrGroup = lens _lgrGroup (\ s a -> s{_lgrGroup = a}) . _Default . _Coerce instance FromJSON ListGroupsResponse where parseJSON = withObject "ListGroupsResponse" (\ o -> ListGroupsResponse' <$> (o .:? "nextPageToken") <*> (o .:? "group" .!= mempty)) instance ToJSON ListGroupsResponse where toJSON ListGroupsResponse'{..} = object (catMaybes [("nextPageToken" .=) <$> _lgrNextPageToken, ("group" .=) <$> _lgrGroup]) -- | The ListMetricDescriptors response. -- -- /See:/ 'listMetricDescriptorsResponse' smart constructor. data ListMetricDescriptorsResponse = ListMetricDescriptorsResponse' { _lmdrMetricDescriptors :: !(Maybe [MetricDescriptor]) , _lmdrNextPageToken :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ListMetricDescriptorsResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lmdrMetricDescriptors' -- -- * 'lmdrNextPageToken' listMetricDescriptorsResponse :: ListMetricDescriptorsResponse listMetricDescriptorsResponse = ListMetricDescriptorsResponse' {_lmdrMetricDescriptors = Nothing, _lmdrNextPageToken = Nothing} -- | The metric descriptors that are available to the project and that match -- the value of filter, if present. lmdrMetricDescriptors :: Lens' ListMetricDescriptorsResponse [MetricDescriptor] lmdrMetricDescriptors = lens _lmdrMetricDescriptors (\ s a -> s{_lmdrMetricDescriptors = a}) . _Default . _Coerce -- | If there are more results than have been returned, then this field is -- set to a non-empty value. To see the additional results, use that value -- as page_token in the next call to this method. lmdrNextPageToken :: Lens' ListMetricDescriptorsResponse (Maybe Text) lmdrNextPageToken = lens _lmdrNextPageToken (\ s a -> s{_lmdrNextPageToken = a}) instance FromJSON ListMetricDescriptorsResponse where parseJSON = withObject "ListMetricDescriptorsResponse" (\ o -> ListMetricDescriptorsResponse' <$> (o .:? "metricDescriptors" .!= mempty) <*> (o .:? "nextPageToken")) instance ToJSON ListMetricDescriptorsResponse where toJSON ListMetricDescriptorsResponse'{..} = object (catMaybes [("metricDescriptors" .=) <$> _lmdrMetricDescriptors, ("nextPageToken" .=) <$> _lmdrNextPageToken]) -- | A WindowsBasedSli defines good_service as the count of time windows for -- which the provided service was of good quality. Criteria for determining -- if service was good are embedded in the window_criterion. -- -- /See:/ 'windowsBasedSli' smart constructor. data WindowsBasedSli = WindowsBasedSli' { _wbsMetricSumInRange :: !(Maybe MetricRange) , _wbsWindowPeriod :: !(Maybe GDuration) , _wbsGoodTotalRatioThreshold :: !(Maybe PerformanceThreshold) , _wbsGoodBadMetricFilter :: !(Maybe Text) , _wbsMetricMeanInRange :: !(Maybe MetricRange) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'WindowsBasedSli' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'wbsMetricSumInRange' -- -- * 'wbsWindowPeriod' -- -- * 'wbsGoodTotalRatioThreshold' -- -- * 'wbsGoodBadMetricFilter' -- -- * 'wbsMetricMeanInRange' windowsBasedSli :: WindowsBasedSli windowsBasedSli = WindowsBasedSli' { _wbsMetricSumInRange = Nothing , _wbsWindowPeriod = Nothing , _wbsGoodTotalRatioThreshold = Nothing , _wbsGoodBadMetricFilter = Nothing , _wbsMetricMeanInRange = Nothing } -- | A window is good if the metric\'s value is in a good range, summed -- across returned streams. wbsMetricSumInRange :: Lens' WindowsBasedSli (Maybe MetricRange) wbsMetricSumInRange = lens _wbsMetricSumInRange (\ s a -> s{_wbsMetricSumInRange = a}) -- | Duration over which window quality is evaluated. Must be an integer -- fraction of a day and at least 60s. wbsWindowPeriod :: Lens' WindowsBasedSli (Maybe Scientific) wbsWindowPeriod = lens _wbsWindowPeriod (\ s a -> s{_wbsWindowPeriod = a}) . mapping _GDuration -- | A window is good if its performance is high enough. wbsGoodTotalRatioThreshold :: Lens' WindowsBasedSli (Maybe PerformanceThreshold) wbsGoodTotalRatioThreshold = lens _wbsGoodTotalRatioThreshold (\ s a -> s{_wbsGoodTotalRatioThreshold = a}) -- | A monitoring filter -- (https:\/\/cloud.google.com\/monitoring\/api\/v3\/filters) specifying a -- TimeSeries with ValueType = BOOL. The window is good if any true values -- appear in the window. wbsGoodBadMetricFilter :: Lens' WindowsBasedSli (Maybe Text) wbsGoodBadMetricFilter = lens _wbsGoodBadMetricFilter (\ s a -> s{_wbsGoodBadMetricFilter = a}) -- | A window is good if the metric\'s value is in a good range, averaged -- across returned streams. wbsMetricMeanInRange :: Lens' WindowsBasedSli (Maybe MetricRange) wbsMetricMeanInRange = lens _wbsMetricMeanInRange (\ s a -> s{_wbsMetricMeanInRange = a}) instance FromJSON WindowsBasedSli where parseJSON = withObject "WindowsBasedSli" (\ o -> WindowsBasedSli' <$> (o .:? "metricSumInRange") <*> (o .:? "windowPeriod") <*> (o .:? "goodTotalRatioThreshold") <*> (o .:? "goodBadMetricFilter") <*> (o .:? "metricMeanInRange")) instance ToJSON WindowsBasedSli where toJSON WindowsBasedSli'{..} = object (catMaybes [("metricSumInRange" .=) <$> _wbsMetricSumInRange, ("windowPeriod" .=) <$> _wbsWindowPeriod, ("goodTotalRatioThreshold" .=) <$> _wbsGoodTotalRatioThreshold, ("goodBadMetricFilter" .=) <$> _wbsGoodBadMetricFilter, ("metricMeanInRange" .=) <$> _wbsMetricMeanInRange]) -- | Detailed information about an error category. -- -- /See:/ 'error'' smart constructor. data Error' = Error'' { _eStatus :: !(Maybe Status) , _ePointCount :: !(Maybe (Textual Int32)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Error' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'eStatus' -- -- * 'ePointCount' error' :: Error' error' = Error'' {_eStatus = Nothing, _ePointCount = Nothing} -- | The status of the requested write operation. eStatus :: Lens' Error' (Maybe Status) eStatus = lens _eStatus (\ s a -> s{_eStatus = a}) -- | The number of points that couldn\'t be written because of status. ePointCount :: Lens' Error' (Maybe Int32) ePointCount = lens _ePointCount (\ s a -> s{_ePointCount = a}) . mapping _Coerce instance FromJSON Error' where parseJSON = withObject "Error" (\ o -> Error'' <$> (o .:? "status") <*> (o .:? "pointCount")) instance ToJSON Error' where toJSON Error''{..} = object (catMaybes [("status" .=) <$> _eStatus, ("pointCount" .=) <$> _ePointCount]) -- | The VerifyNotificationChannel request. -- -- /See:/ 'verifyNotificationChannelRequest' smart constructor. newtype VerifyNotificationChannelRequest = VerifyNotificationChannelRequest' { _vncrCode :: Maybe Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'VerifyNotificationChannelRequest' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'vncrCode' verifyNotificationChannelRequest :: VerifyNotificationChannelRequest verifyNotificationChannelRequest = VerifyNotificationChannelRequest' {_vncrCode = Nothing} -- | Required. The verification code that was delivered to the channel as a -- result of invoking the SendNotificationChannelVerificationCode API -- method or that was retrieved from a verified channel via -- GetNotificationChannelVerificationCode. For example, one might have -- \"G-123456\" or \"TKNZGhhd2EyN3I1MnRnMjRv\" (in general, one is only -- guaranteed that the code is valid UTF-8; one should not make any -- assumptions regarding the structure or format of the code). vncrCode :: Lens' VerifyNotificationChannelRequest (Maybe Text) vncrCode = lens _vncrCode (\ s a -> s{_vncrCode = a}) instance FromJSON VerifyNotificationChannelRequest where parseJSON = withObject "VerifyNotificationChannelRequest" (\ o -> VerifyNotificationChannelRequest' <$> (o .:? "code")) instance ToJSON VerifyNotificationChannelRequest where toJSON VerifyNotificationChannelRequest'{..} = object (catMaybes [("code" .=) <$> _vncrCode]) -- | The option\'s value packed in an Any message. If the value is a -- primitive, the corresponding wrapper type defined in -- google\/protobuf\/wrappers.proto should be used. If the value is an -- enum, it should be stored as an int32 value using the -- google.protobuf.Int32Value type. -- -- /See:/ 'optionValue' smart constructor. newtype OptionValue = OptionValue' { _ovAddtional :: HashMap Text JSONValue } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'OptionValue' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ovAddtional' optionValue :: HashMap Text JSONValue -- ^ 'ovAddtional' -> OptionValue optionValue pOvAddtional_ = OptionValue' {_ovAddtional = _Coerce # pOvAddtional_} -- | Properties of the object. Contains field \'type with type URL. ovAddtional :: Lens' OptionValue (HashMap Text JSONValue) ovAddtional = lens _ovAddtional (\ s a -> s{_ovAddtional = a}) . _Coerce instance FromJSON OptionValue where parseJSON = withObject "OptionValue" (\ o -> OptionValue' <$> (parseJSONObject o)) instance ToJSON OptionValue where toJSON = toJSON . _ovAddtional -- | A DistributionCut defines a TimeSeries and thresholds used for measuring -- good service and total service. The TimeSeries must have ValueType = -- DISTRIBUTION and MetricKind = DELTA or MetricKind = CUMULATIVE. The -- computed good_service will be the estimated count of values in the -- Distribution that fall within the specified min and max. -- -- /See:/ 'distributionCut' smart constructor. data DistributionCut = DistributionCut' { _dcRange :: !(Maybe GoogleMonitoringV3Range) , _dcDistributionFilter :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'DistributionCut' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dcRange' -- -- * 'dcDistributionFilter' distributionCut :: DistributionCut distributionCut = DistributionCut' {_dcRange = Nothing, _dcDistributionFilter = Nothing} -- | Range of values considered \"good.\" For a one-sided range, set one -- bound to an infinite value. dcRange :: Lens' DistributionCut (Maybe GoogleMonitoringV3Range) dcRange = lens _dcRange (\ s a -> s{_dcRange = a}) -- | A monitoring filter -- (https:\/\/cloud.google.com\/monitoring\/api\/v3\/filters) specifying a -- TimeSeries aggregating values. Must have ValueType = DISTRIBUTION and -- MetricKind = DELTA or MetricKind = CUMULATIVE. dcDistributionFilter :: Lens' DistributionCut (Maybe Text) dcDistributionFilter = lens _dcDistributionFilter (\ s a -> s{_dcDistributionFilter = a}) instance FromJSON DistributionCut where parseJSON = withObject "DistributionCut" (\ o -> DistributionCut' <$> (o .:? "range") <*> (o .:? "distributionFilter")) instance ToJSON DistributionCut where toJSON DistributionCut'{..} = object (catMaybes [("range" .=) <$> _dcRange, ("distributionFilter" .=) <$> _dcDistributionFilter]) -- | A MetricRange is used when each window is good when the value x of a -- single TimeSeries satisfies range.min \<= x \<= range.max. The provided -- TimeSeries must have ValueType = INT64 or ValueType = DOUBLE and -- MetricKind = GAUGE. -- -- /See:/ 'metricRange' smart constructor. data MetricRange = MetricRange' { _mrRange :: !(Maybe GoogleMonitoringV3Range) , _mrTimeSeries :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'MetricRange' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'mrRange' -- -- * 'mrTimeSeries' metricRange :: MetricRange metricRange = MetricRange' {_mrRange = Nothing, _mrTimeSeries = Nothing} -- | Range of values considered \"good.\" For a one-sided range, set one -- bound to an infinite value. mrRange :: Lens' MetricRange (Maybe GoogleMonitoringV3Range) mrRange = lens _mrRange (\ s a -> s{_mrRange = a}) -- | A monitoring filter -- (https:\/\/cloud.google.com\/monitoring\/api\/v3\/filters) specifying -- the TimeSeries to use for evaluating window quality. mrTimeSeries :: Lens' MetricRange (Maybe Text) mrTimeSeries = lens _mrTimeSeries (\ s a -> s{_mrTimeSeries = a}) instance FromJSON MetricRange where parseJSON = withObject "MetricRange" (\ o -> MetricRange' <$> (o .:? "range") <*> (o .:? "timeSeries")) instance ToJSON MetricRange where toJSON MetricRange'{..} = object (catMaybes [("range" .=) <$> _mrRange, ("timeSeries" .=) <$> _mrTimeSeries]) -- | Configuration fields that define the channel and its behavior. The -- permissible and required labels are specified in the -- NotificationChannelDescriptor.labels of the -- NotificationChannelDescriptor corresponding to the type field. -- -- /See:/ 'notificationChannelLabels' smart constructor. newtype NotificationChannelLabels = NotificationChannelLabels' { _nclAddtional :: HashMap Text Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'NotificationChannelLabels' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'nclAddtional' notificationChannelLabels :: HashMap Text Text -- ^ 'nclAddtional' -> NotificationChannelLabels notificationChannelLabels pNclAddtional_ = NotificationChannelLabels' {_nclAddtional = _Coerce # pNclAddtional_} nclAddtional :: Lens' NotificationChannelLabels (HashMap Text Text) nclAddtional = lens _nclAddtional (\ s a -> s{_nclAddtional = a}) . _Coerce instance FromJSON NotificationChannelLabels where parseJSON = withObject "NotificationChannelLabels" (\ o -> NotificationChannelLabels' <$> (parseJSONObject o)) instance ToJSON NotificationChannelLabels where toJSON = toJSON . _nclAddtional -- | The CreateTimeSeries request. -- -- /See:/ 'createTimeSeriesRequest' smart constructor. newtype CreateTimeSeriesRequest = CreateTimeSeriesRequest' { _ctsrTimeSeries :: Maybe [TimeSeries] } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'CreateTimeSeriesRequest' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ctsrTimeSeries' createTimeSeriesRequest :: CreateTimeSeriesRequest createTimeSeriesRequest = CreateTimeSeriesRequest' {_ctsrTimeSeries = Nothing} -- | Required. The new data to be added to a list of time series. Adds at -- most one data point to each of several time series. The new data point -- must be more recent than any other point in its time series. Each -- TimeSeries value must fully specify a unique time series by supplying -- all label values for the metric and the monitored resource.The maximum -- number of TimeSeries objects per Create request is 200. ctsrTimeSeries :: Lens' CreateTimeSeriesRequest [TimeSeries] ctsrTimeSeries = lens _ctsrTimeSeries (\ s a -> s{_ctsrTimeSeries = a}) . _Default . _Coerce instance FromJSON CreateTimeSeriesRequest where parseJSON = withObject "CreateTimeSeriesRequest" (\ o -> CreateTimeSeriesRequest' <$> (o .:? "timeSeries" .!= mempty)) instance ToJSON CreateTimeSeriesRequest where toJSON CreateTimeSeriesRequest'{..} = object (catMaybes [("timeSeries" .=) <$> _ctsrTimeSeries]) -- | Custom view of service telemetry. Currently a place-holder pending final -- design. -- -- /See:/ 'custom' smart constructor. data Custom = Custom' deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Custom' with the minimum fields required to make a request. -- custom :: Custom custom = Custom' instance FromJSON Custom where parseJSON = withObject "Custom" (\ o -> pure Custom') instance ToJSON Custom where toJSON = const emptyObject -- | Map from label to its value, for all labels dropped in any aggregation. -- -- /See:/ 'droppedLabelsLabel' smart constructor. newtype DroppedLabelsLabel = DroppedLabelsLabel' { _dllAddtional :: HashMap Text Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'DroppedLabelsLabel' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dllAddtional' droppedLabelsLabel :: HashMap Text Text -- ^ 'dllAddtional' -> DroppedLabelsLabel droppedLabelsLabel pDllAddtional_ = DroppedLabelsLabel' {_dllAddtional = _Coerce # pDllAddtional_} dllAddtional :: Lens' DroppedLabelsLabel (HashMap Text Text) dllAddtional = lens _dllAddtional (\ s a -> s{_dllAddtional = a}) . _Coerce instance FromJSON DroppedLabelsLabel where parseJSON = withObject "DroppedLabelsLabel" (\ o -> DroppedLabelsLabel' <$> (parseJSONObject o)) instance ToJSON DroppedLabelsLabel where toJSON = toJSON . _dllAddtional -- | A condition type that compares a collection of time series against a -- threshold. -- -- /See:/ 'metricThreshold' smart constructor. data MetricThreshold = MetricThreshold' { _mtThresholdValue :: !(Maybe (Textual Double)) , _mtAggregations :: !(Maybe [Aggregation]) , _mtDenominatorAggregations :: !(Maybe [Aggregation]) , _mtComparison :: !(Maybe MetricThresholdComparison) , _mtDenominatorFilter :: !(Maybe Text) , _mtFilter :: !(Maybe Text) , _mtTrigger :: !(Maybe Trigger) , _mtDuration :: !(Maybe GDuration) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'MetricThreshold' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'mtThresholdValue' -- -- * 'mtAggregations' -- -- * 'mtDenominatorAggregations' -- -- * 'mtComparison' -- -- * 'mtDenominatorFilter' -- -- * 'mtFilter' -- -- * 'mtTrigger' -- -- * 'mtDuration' metricThreshold :: MetricThreshold metricThreshold = MetricThreshold' { _mtThresholdValue = Nothing , _mtAggregations = Nothing , _mtDenominatorAggregations = Nothing , _mtComparison = Nothing , _mtDenominatorFilter = Nothing , _mtFilter = Nothing , _mtTrigger = Nothing , _mtDuration = Nothing } -- | A value against which to compare the time series. mtThresholdValue :: Lens' MetricThreshold (Maybe Double) mtThresholdValue = lens _mtThresholdValue (\ s a -> s{_mtThresholdValue = a}) . mapping _Coerce -- | Specifies the alignment of data points in individual time series as well -- as how to combine the retrieved time series together (such as when -- aggregating multiple streams on each resource to a single stream for -- each resource or when aggregating streams across all members of a group -- of resrouces). Multiple aggregations are applied in the order -- specified.This field is similar to the one in the ListTimeSeries request -- (https:\/\/cloud.google.com\/monitoring\/api\/ref_v3\/rest\/v3\/projects.timeSeries\/list). -- It is advisable to use the ListTimeSeries method when debugging this -- field. mtAggregations :: Lens' MetricThreshold [Aggregation] mtAggregations = lens _mtAggregations (\ s a -> s{_mtAggregations = a}) . _Default . _Coerce -- | Specifies the alignment of data points in individual time series -- selected by denominatorFilter as well as how to combine the retrieved -- time series together (such as when aggregating multiple streams on each -- resource to a single stream for each resource or when aggregating -- streams across all members of a group of resources).When computing -- ratios, the aggregations and denominator_aggregations fields must use -- the same alignment period and produce time series that have the same -- periodicity and labels. mtDenominatorAggregations :: Lens' MetricThreshold [Aggregation] mtDenominatorAggregations = lens _mtDenominatorAggregations (\ s a -> s{_mtDenominatorAggregations = a}) . _Default . _Coerce -- | The comparison to apply between the time series (indicated by filter and -- aggregation) and the threshold (indicated by threshold_value). The -- comparison is applied on each time series, with the time series on the -- left-hand side and the threshold on the right-hand side.Only -- COMPARISON_LT and COMPARISON_GT are supported currently. mtComparison :: Lens' MetricThreshold (Maybe MetricThresholdComparison) mtComparison = lens _mtComparison (\ s a -> s{_mtComparison = a}) -- | A filter (https:\/\/cloud.google.com\/monitoring\/api\/v3\/filters) that -- identifies a time series that should be used as the denominator of a -- ratio that will be compared with the threshold. If a denominator_filter -- is specified, the time series specified by the filter field will be used -- as the numerator.The filter must specify the metric type and optionally -- may contain restrictions on resource type, resource labels, and metric -- labels. This field may not exceed 2048 Unicode characters in length. mtDenominatorFilter :: Lens' MetricThreshold (Maybe Text) mtDenominatorFilter = lens _mtDenominatorFilter (\ s a -> s{_mtDenominatorFilter = a}) -- | Required. A filter -- (https:\/\/cloud.google.com\/monitoring\/api\/v3\/filters) that -- identifies which time series should be compared with the threshold.The -- filter is similar to the one that is specified in the ListTimeSeries -- request -- (https:\/\/cloud.google.com\/monitoring\/api\/ref_v3\/rest\/v3\/projects.timeSeries\/list) -- (that call is useful to verify the time series that will be retrieved \/ -- processed). The filter must specify the metric type and the resource -- type. Optionally, it can specify resource labels and metric labels. This -- field must not exceed 2048 Unicode characters in length. mtFilter :: Lens' MetricThreshold (Maybe Text) mtFilter = lens _mtFilter (\ s a -> s{_mtFilter = a}) -- | The number\/percent of time series for which the comparison must hold in -- order for the condition to trigger. If unspecified, then the condition -- will trigger if the comparison is true for any of the time series that -- have been identified by filter and aggregations, or by the ratio, if -- denominator_filter and denominator_aggregations are specified. mtTrigger :: Lens' MetricThreshold (Maybe Trigger) mtTrigger = lens _mtTrigger (\ s a -> s{_mtTrigger = a}) -- | The amount of time that a time series must violate the threshold to be -- considered failing. Currently, only values that are a multiple of a -- minute--e.g., 0, 60, 120, or 300 seconds--are supported. If an invalid -- value is given, an error will be returned. When choosing a duration, it -- is useful to keep in mind the frequency of the underlying time series -- data (which may also be affected by any alignments specified in the -- aggregations field); a good duration is long enough so that a single -- outlier does not generate spurious alerts, but short enough that -- unhealthy states are detected and alerted on quickly. mtDuration :: Lens' MetricThreshold (Maybe Scientific) mtDuration = lens _mtDuration (\ s a -> s{_mtDuration = a}) . mapping _GDuration instance FromJSON MetricThreshold where parseJSON = withObject "MetricThreshold" (\ o -> MetricThreshold' <$> (o .:? "thresholdValue") <*> (o .:? "aggregations" .!= mempty) <*> (o .:? "denominatorAggregations" .!= mempty) <*> (o .:? "comparison") <*> (o .:? "denominatorFilter") <*> (o .:? "filter") <*> (o .:? "trigger") <*> (o .:? "duration")) instance ToJSON MetricThreshold where toJSON MetricThreshold'{..} = object (catMaybes [("thresholdValue" .=) <$> _mtThresholdValue, ("aggregations" .=) <$> _mtAggregations, ("denominatorAggregations" .=) <$> _mtDenominatorAggregations, ("comparison" .=) <$> _mtComparison, ("denominatorFilter" .=) <$> _mtDenominatorFilter, ("filter" .=) <$> _mtFilter, ("trigger" .=) <$> _mtTrigger, ("duration" .=) <$> _mtDuration]) -- | The context of a span. This is attached to an Exemplar in Distribution -- values during aggregation.It contains the name of a span with format: -- projects\/[PROJECT_ID_OR_NUMBER]\/traces\/[TRACE_ID]\/spans\/[SPAN_ID] -- -- /See:/ 'spanContext' smart constructor. newtype SpanContext = SpanContext' { _scSpanName :: Maybe Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'SpanContext' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'scSpanName' spanContext :: SpanContext spanContext = SpanContext' {_scSpanName = Nothing} -- | The resource name of the span. The format is: -- projects\/[PROJECT_ID_OR_NUMBER]\/traces\/[TRACE_ID]\/spans\/[SPAN_ID] -- [TRACE_ID] is a unique identifier for a trace within a project; it is a -- 32-character hexadecimal encoding of a 16-byte array.[SPAN_ID] is a -- unique identifier for a span within a trace; it is a 16-character -- hexadecimal encoding of an 8-byte array. scSpanName :: Lens' SpanContext (Maybe Text) scSpanName = lens _scSpanName (\ s a -> s{_scSpanName = a}) instance FromJSON SpanContext where parseJSON = withObject "SpanContext" (\ o -> SpanContext' <$> (o .:? "spanName")) instance ToJSON SpanContext where toJSON SpanContext'{..} = object (catMaybes [("spanName" .=) <$> _scSpanName]) -- -- /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 -- | Summary of the result of a failed request to write data to a time -- series. -- -- /See:/ 'createTimeSeriesSummary' smart constructor. data CreateTimeSeriesSummary = CreateTimeSeriesSummary' { _ctssTotalPointCount :: !(Maybe (Textual Int32)) , _ctssSuccessPointCount :: !(Maybe (Textual Int32)) , _ctssErrors :: !(Maybe [Error']) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'CreateTimeSeriesSummary' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ctssTotalPointCount' -- -- * 'ctssSuccessPointCount' -- -- * 'ctssErrors' createTimeSeriesSummary :: CreateTimeSeriesSummary createTimeSeriesSummary = CreateTimeSeriesSummary' { _ctssTotalPointCount = Nothing , _ctssSuccessPointCount = Nothing , _ctssErrors = Nothing } -- | The number of points in the request. ctssTotalPointCount :: Lens' CreateTimeSeriesSummary (Maybe Int32) ctssTotalPointCount = lens _ctssTotalPointCount (\ s a -> s{_ctssTotalPointCount = a}) . mapping _Coerce -- | The number of points that were successfully written. ctssSuccessPointCount :: Lens' CreateTimeSeriesSummary (Maybe Int32) ctssSuccessPointCount = lens _ctssSuccessPointCount (\ s a -> s{_ctssSuccessPointCount = a}) . mapping _Coerce -- | The number of points that failed to be written. Order is not guaranteed. ctssErrors :: Lens' CreateTimeSeriesSummary [Error'] ctssErrors = lens _ctssErrors (\ s a -> s{_ctssErrors = a}) . _Default . _Coerce instance FromJSON CreateTimeSeriesSummary where parseJSON = withObject "CreateTimeSeriesSummary" (\ o -> CreateTimeSeriesSummary' <$> (o .:? "totalPointCount") <*> (o .:? "successPointCount") <*> (o .:? "errors" .!= mempty)) instance ToJSON CreateTimeSeriesSummary where toJSON CreateTimeSeriesSummary'{..} = object (catMaybes [("totalPointCount" .=) <$> _ctssTotalPointCount, ("successPointCount" .=) <$> _ctssSuccessPointCount, ("errors" .=) <$> _ctssErrors]) -- | Output only. A map of user-defined metadata labels. -- -- /See:/ 'monitoredResourceMetadataUserLabels' smart constructor. newtype MonitoredResourceMetadataUserLabels = MonitoredResourceMetadataUserLabels' { _mrmulAddtional :: HashMap Text Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'MonitoredResourceMetadataUserLabels' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'mrmulAddtional' monitoredResourceMetadataUserLabels :: HashMap Text Text -- ^ 'mrmulAddtional' -> MonitoredResourceMetadataUserLabels monitoredResourceMetadataUserLabels pMrmulAddtional_ = MonitoredResourceMetadataUserLabels' {_mrmulAddtional = _Coerce # pMrmulAddtional_} mrmulAddtional :: Lens' MonitoredResourceMetadataUserLabels (HashMap Text Text) mrmulAddtional = lens _mrmulAddtional (\ s a -> s{_mrmulAddtional = a}) . _Coerce instance FromJSON MonitoredResourceMetadataUserLabels where parseJSON = withObject "MonitoredResourceMetadataUserLabels" (\ o -> MonitoredResourceMetadataUserLabels' <$> (parseJSONObject o)) instance ToJSON MonitoredResourceMetadataUserLabels where toJSON = toJSON . _mrmulAddtional -- | An internal checker allows Uptime checks to run on private\/internal GCP -- resources. -- -- /See:/ 'internalChecker' smart constructor. data InternalChecker = InternalChecker' { _icState :: !(Maybe InternalCheckerState) , _icNetwork :: !(Maybe Text) , _icName :: !(Maybe Text) , _icPeerProjectId :: !(Maybe Text) , _icGcpZone :: !(Maybe Text) , _icDisplayName :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'InternalChecker' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'icState' -- -- * 'icNetwork' -- -- * 'icName' -- -- * 'icPeerProjectId' -- -- * 'icGcpZone' -- -- * 'icDisplayName' internalChecker :: InternalChecker internalChecker = InternalChecker' { _icState = Nothing , _icNetwork = Nothing , _icName = Nothing , _icPeerProjectId = Nothing , _icGcpZone = Nothing , _icDisplayName = Nothing } -- | The current operational state of the internal checker. icState :: Lens' InternalChecker (Maybe InternalCheckerState) icState = lens _icState (\ s a -> s{_icState = a}) -- | The GCP VPC network (https:\/\/cloud.google.com\/vpc\/docs\/vpc) where -- the internal resource lives (ex: \"default\"). icNetwork :: Lens' InternalChecker (Maybe Text) icNetwork = lens _icNetwork (\ s a -> s{_icNetwork = a}) -- | A unique resource name for this InternalChecker. The format is: -- projects\/[PROJECT_ID_OR_NUMBER]\/internalCheckers\/[INTERNAL_CHECKER_ID] -- [PROJECT_ID_OR_NUMBER] is the Stackdriver Workspace project for the -- Uptime check config associated with the internal checker. icName :: Lens' InternalChecker (Maybe Text) icName = lens _icName (\ s a -> s{_icName = a}) -- | The GCP project ID where the internal checker lives. Not necessary the -- same as the Workspace project. icPeerProjectId :: Lens' InternalChecker (Maybe Text) icPeerProjectId = lens _icPeerProjectId (\ s a -> s{_icPeerProjectId = a}) -- | The GCP zone the Uptime check should egress from. Only respected for -- internal Uptime checks, where internal_network is specified. icGcpZone :: Lens' InternalChecker (Maybe Text) icGcpZone = lens _icGcpZone (\ s a -> s{_icGcpZone = a}) -- | The checker\'s human-readable name. The display name should be unique -- within a Stackdriver Workspace in order to make it easier to identify; -- however, uniqueness is not enforced. icDisplayName :: Lens' InternalChecker (Maybe Text) icDisplayName = lens _icDisplayName (\ s a -> s{_icDisplayName = a}) instance FromJSON InternalChecker where parseJSON = withObject "InternalChecker" (\ o -> InternalChecker' <$> (o .:? "state") <*> (o .:? "network") <*> (o .:? "name") <*> (o .:? "peerProjectId") <*> (o .:? "gcpZone") <*> (o .:? "displayName")) instance ToJSON InternalChecker where toJSON InternalChecker'{..} = object (catMaybes [("state" .=) <$> _icState, ("network" .=) <$> _icNetwork, ("name" .=) <$> _icName, ("peerProjectId" .=) <$> _icPeerProjectId, ("gcpZone" .=) <$> _icGcpZone, ("displayName" .=) <$> _icDisplayName]) -- | A NotificationChannel is a medium through which an alert is delivered -- when a policy violation is detected. Examples of channels include email, -- SMS, and third-party messaging applications. Fields containing sensitive -- information like authentication tokens or contact info are only -- partially populated on retrieval. -- -- /See:/ 'notificationChannel' smart constructor. data NotificationChannel = NotificationChannel' { _ncMutationRecords :: !(Maybe [MutationRecord]) , _ncEnabled :: !(Maybe Bool) , _ncCreationRecord :: !(Maybe MutationRecord) , _ncUserLabels :: !(Maybe NotificationChannelUserLabels) , _ncName :: !(Maybe Text) , _ncDisplayName :: !(Maybe Text) , _ncVerificationStatus :: !(Maybe NotificationChannelVerificationStatus) , _ncLabels :: !(Maybe NotificationChannelLabels) , _ncType :: !(Maybe Text) , _ncDescription :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'NotificationChannel' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ncMutationRecords' -- -- * 'ncEnabled' -- -- * 'ncCreationRecord' -- -- * 'ncUserLabels' -- -- * 'ncName' -- -- * 'ncDisplayName' -- -- * 'ncVerificationStatus' -- -- * 'ncLabels' -- -- * 'ncType' -- -- * 'ncDescription' notificationChannel :: NotificationChannel notificationChannel = NotificationChannel' { _ncMutationRecords = Nothing , _ncEnabled = Nothing , _ncCreationRecord = Nothing , _ncUserLabels = Nothing , _ncName = Nothing , _ncDisplayName = Nothing , _ncVerificationStatus = Nothing , _ncLabels = Nothing , _ncType = Nothing , _ncDescription = Nothing } -- | Records of the modification of this channel. ncMutationRecords :: Lens' NotificationChannel [MutationRecord] ncMutationRecords = lens _ncMutationRecords (\ s a -> s{_ncMutationRecords = a}) . _Default . _Coerce -- | Whether notifications are forwarded to the described channel. This makes -- it possible to disable delivery of notifications to a particular channel -- without removing the channel from all alerting policies that reference -- the channel. This is a more convenient approach when the change is -- temporary and you want to receive notifications from the same set of -- alerting policies on the channel at some point in the future. ncEnabled :: Lens' NotificationChannel (Maybe Bool) ncEnabled = lens _ncEnabled (\ s a -> s{_ncEnabled = a}) -- | Record of the creation of this channel. ncCreationRecord :: Lens' NotificationChannel (Maybe MutationRecord) ncCreationRecord = lens _ncCreationRecord (\ s a -> s{_ncCreationRecord = a}) -- | User-supplied key\/value data that does not need to conform to the -- corresponding NotificationChannelDescriptor\'s schema, unlike the labels -- field. This field is intended to be used for organizing and identifying -- the NotificationChannel objects.The field can contain up to 64 entries. -- Each key and value is limited to 63 Unicode characters or 128 bytes, -- whichever is smaller. Labels and values can contain only lowercase -- letters, numerals, underscores, and dashes. Keys must begin with a -- letter. ncUserLabels :: Lens' NotificationChannel (Maybe NotificationChannelUserLabels) ncUserLabels = lens _ncUserLabels (\ s a -> s{_ncUserLabels = a}) -- | The full REST resource name for this channel. The format is: -- projects\/[PROJECT_ID_OR_NUMBER]\/notificationChannels\/[CHANNEL_ID] The -- [CHANNEL_ID] is automatically assigned by the server on creation. ncName :: Lens' NotificationChannel (Maybe Text) ncName = lens _ncName (\ s a -> s{_ncName = a}) -- | An optional human-readable name for this notification channel. It is -- recommended that you specify a non-empty and unique name in order to -- make it easier to identify the channels in your project, though this is -- not enforced. The display name is limited to 512 Unicode characters. ncDisplayName :: Lens' NotificationChannel (Maybe Text) ncDisplayName = lens _ncDisplayName (\ s a -> s{_ncDisplayName = a}) -- | Indicates whether this channel has been verified or not. On a -- ListNotificationChannels or GetNotificationChannel operation, this field -- is expected to be populated.If the value is UNVERIFIED, then it -- indicates that the channel is non-functioning (it both requires -- verification and lacks verification); otherwise, it is assumed that the -- channel works.If the channel is neither VERIFIED nor UNVERIFIED, it -- implies that the channel is of a type that does not require verification -- or that this specific channel has been exempted from verification -- because it was created prior to verification being required for channels -- of this type.This field cannot be modified using a standard -- UpdateNotificationChannel operation. To change the value of this field, -- you must call VerifyNotificationChannel. ncVerificationStatus :: Lens' NotificationChannel (Maybe NotificationChannelVerificationStatus) ncVerificationStatus = lens _ncVerificationStatus (\ s a -> s{_ncVerificationStatus = a}) -- | Configuration fields that define the channel and its behavior. The -- permissible and required labels are specified in the -- NotificationChannelDescriptor.labels of the -- NotificationChannelDescriptor corresponding to the type field. ncLabels :: Lens' NotificationChannel (Maybe NotificationChannelLabels) ncLabels = lens _ncLabels (\ s a -> s{_ncLabels = a}) -- | The type of the notification channel. This field matches the value of -- the NotificationChannelDescriptor.type field. ncType :: Lens' NotificationChannel (Maybe Text) ncType = lens _ncType (\ s a -> s{_ncType = a}) -- | An optional human-readable description of this notification channel. -- This description may provide additional details, beyond the display -- name, for the channel. This may not exceed 1024 Unicode characters. ncDescription :: Lens' NotificationChannel (Maybe Text) ncDescription = lens _ncDescription (\ s a -> s{_ncDescription = a}) instance FromJSON NotificationChannel where parseJSON = withObject "NotificationChannel" (\ o -> NotificationChannel' <$> (o .:? "mutationRecords" .!= mempty) <*> (o .:? "enabled") <*> (o .:? "creationRecord") <*> (o .:? "userLabels") <*> (o .:? "name") <*> (o .:? "displayName") <*> (o .:? "verificationStatus") <*> (o .:? "labels") <*> (o .:? "type") <*> (o .:? "description")) instance ToJSON NotificationChannel where toJSON NotificationChannel'{..} = object (catMaybes [("mutationRecords" .=) <$> _ncMutationRecords, ("enabled" .=) <$> _ncEnabled, ("creationRecord" .=) <$> _ncCreationRecord, ("userLabels" .=) <$> _ncUserLabels, ("name" .=) <$> _ncName, ("displayName" .=) <$> _ncDisplayName, ("verificationStatus" .=) <$> _ncVerificationStatus, ("labels" .=) <$> _ncLabels, ("type" .=) <$> _ncType, ("description" .=) <$> _ncDescription]) -- | The ListServiceLevelObjectives response. -- -- /See:/ 'listServiceLevelObjectivesResponse' smart constructor. data ListServiceLevelObjectivesResponse = ListServiceLevelObjectivesResponse' { _lslorNextPageToken :: !(Maybe Text) , _lslorServiceLevelObjectives :: !(Maybe [ServiceLevelObjective]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ListServiceLevelObjectivesResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lslorNextPageToken' -- -- * 'lslorServiceLevelObjectives' listServiceLevelObjectivesResponse :: ListServiceLevelObjectivesResponse listServiceLevelObjectivesResponse = ListServiceLevelObjectivesResponse' {_lslorNextPageToken = Nothing, _lslorServiceLevelObjectives = Nothing} -- | If there are more results than have been returned, then this field is -- set to a non-empty value. To see the additional results, use that value -- as page_token in the next call to this method. lslorNextPageToken :: Lens' ListServiceLevelObjectivesResponse (Maybe Text) lslorNextPageToken = lens _lslorNextPageToken (\ s a -> s{_lslorNextPageToken = a}) -- | The ServiceLevelObjectives matching the specified filter. lslorServiceLevelObjectives :: Lens' ListServiceLevelObjectivesResponse [ServiceLevelObjective] lslorServiceLevelObjectives = lens _lslorServiceLevelObjectives (\ s a -> s{_lslorServiceLevelObjectives = a}) . _Default . _Coerce instance FromJSON ListServiceLevelObjectivesResponse where parseJSON = withObject "ListServiceLevelObjectivesResponse" (\ o -> ListServiceLevelObjectivesResponse' <$> (o .:? "nextPageToken") <*> (o .:? "serviceLevelObjectives" .!= mempty)) instance ToJSON ListServiceLevelObjectivesResponse where toJSON ListServiceLevelObjectivesResponse'{..} = object (catMaybes [("nextPageToken" .=) <$> _lslorNextPageToken, ("serviceLevelObjectives" .=) <$> _lslorServiceLevelObjectives]) -- | The ListMonitoredResourceDescriptors response. -- -- /See:/ 'listMonitoredResourceDescriptorsResponse' smart constructor. data ListMonitoredResourceDescriptorsResponse = ListMonitoredResourceDescriptorsResponse' { _lmrdrNextPageToken :: !(Maybe Text) , _lmrdrResourceDescriptors :: !(Maybe [MonitoredResourceDescriptor]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ListMonitoredResourceDescriptorsResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lmrdrNextPageToken' -- -- * 'lmrdrResourceDescriptors' listMonitoredResourceDescriptorsResponse :: ListMonitoredResourceDescriptorsResponse listMonitoredResourceDescriptorsResponse = ListMonitoredResourceDescriptorsResponse' {_lmrdrNextPageToken = Nothing, _lmrdrResourceDescriptors = Nothing} -- | If there are more results than have been returned, then this field is -- set to a non-empty value. To see the additional results, use that value -- as page_token in the next call to this method. lmrdrNextPageToken :: Lens' ListMonitoredResourceDescriptorsResponse (Maybe Text) lmrdrNextPageToken = lens _lmrdrNextPageToken (\ s a -> s{_lmrdrNextPageToken = a}) -- | The monitored resource descriptors that are available to this project -- and that match filter, if present. lmrdrResourceDescriptors :: Lens' ListMonitoredResourceDescriptorsResponse [MonitoredResourceDescriptor] lmrdrResourceDescriptors = lens _lmrdrResourceDescriptors (\ s a -> s{_lmrdrResourceDescriptors = a}) . _Default . _Coerce instance FromJSON ListMonitoredResourceDescriptorsResponse where parseJSON = withObject "ListMonitoredResourceDescriptorsResponse" (\ o -> ListMonitoredResourceDescriptorsResponse' <$> (o .:? "nextPageToken") <*> (o .:? "resourceDescriptors" .!= mempty)) instance ToJSON ListMonitoredResourceDescriptorsResponse where toJSON ListMonitoredResourceDescriptorsResponse'{..} = object (catMaybes [("nextPageToken" .=) <$> _lmrdrNextPageToken, ("resourceDescriptors" .=) <$> _lmrdrResourceDescriptors]) -- | Specifies a set of buckets with arbitrary widths.There are size(bounds) -- + 1 (= N) buckets. Bucket i has the following boundaries:Upper bound (0 -- \<= i \< N-1): boundsi Lower bound (1 \<= i \< N); boundsi - 1The bounds -- field must contain at least one element. If bounds has only one element, -- then there are no finite buckets, and that single element is the common -- boundary of the overflow and underflow buckets. -- -- /See:/ 'explicit' smart constructor. newtype Explicit = Explicit' { _eBounds :: Maybe [Textual Double] } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Explicit' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'eBounds' explicit :: Explicit explicit = Explicit' {_eBounds = Nothing} -- | The values must be monotonically increasing. eBounds :: Lens' Explicit [Double] eBounds = lens _eBounds (\ s a -> s{_eBounds = a}) . _Default . _Coerce instance FromJSON Explicit where parseJSON = withObject "Explicit" (\ o -> Explicit' <$> (o .:? "bounds" .!= mempty)) instance ToJSON Explicit where toJSON Explicit'{..} = object (catMaybes [("bounds" .=) <$> _eBounds]) -- | The set of label values that uniquely identify this metric. All labels -- listed in the MetricDescriptor must be assigned values. -- -- /See:/ 'metricLabels' smart constructor. newtype MetricLabels = MetricLabels' { _mlAddtional :: HashMap Text Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'MetricLabels' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'mlAddtional' metricLabels :: HashMap Text Text -- ^ 'mlAddtional' -> MetricLabels metricLabels pMlAddtional_ = MetricLabels' {_mlAddtional = _Coerce # pMlAddtional_} mlAddtional :: Lens' MetricLabels (HashMap Text Text) mlAddtional = lens _mlAddtional (\ s a -> s{_mlAddtional = a}) . _Coerce instance FromJSON MetricLabels where parseJSON = withObject "MetricLabels" (\ o -> MetricLabels' <$> (parseJSONObject o)) instance ToJSON MetricLabels where toJSON = toJSON . _mlAddtional -- | The measurement metadata. Example: \"process_id\" -> 12345 -- -- /See:/ 'collectdPayloadMetadata' smart constructor. newtype CollectdPayloadMetadata = CollectdPayloadMetadata' { _cpmAddtional :: HashMap Text TypedValue } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'CollectdPayloadMetadata' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'cpmAddtional' collectdPayloadMetadata :: HashMap Text TypedValue -- ^ 'cpmAddtional' -> CollectdPayloadMetadata collectdPayloadMetadata pCpmAddtional_ = CollectdPayloadMetadata' {_cpmAddtional = _Coerce # pCpmAddtional_} cpmAddtional :: Lens' CollectdPayloadMetadata (HashMap Text TypedValue) cpmAddtional = lens _cpmAddtional (\ s a -> s{_cpmAddtional = a}) . _Coerce instance FromJSON CollectdPayloadMetadata where parseJSON = withObject "CollectdPayloadMetadata" (\ o -> CollectdPayloadMetadata' <$> (parseJSONObject o)) instance ToJSON CollectdPayloadMetadata where toJSON = toJSON . _cpmAddtional -- | A single data point from a collectd-based plugin. -- -- /See:/ 'collectdValue' smart constructor. data CollectdValue = CollectdValue' { _cvDataSourceName :: !(Maybe Text) , _cvDataSourceType :: !(Maybe CollectdValueDataSourceType) , _cvValue :: !(Maybe TypedValue) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'CollectdValue' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'cvDataSourceName' -- -- * 'cvDataSourceType' -- -- * 'cvValue' collectdValue :: CollectdValue collectdValue = CollectdValue' { _cvDataSourceName = Nothing , _cvDataSourceType = Nothing , _cvValue = Nothing } -- | The data source for the collectd value. For example, there are two data -- sources for network measurements: \"rx\" and \"tx\". cvDataSourceName :: Lens' CollectdValue (Maybe Text) cvDataSourceName = lens _cvDataSourceName (\ s a -> s{_cvDataSourceName = a}) -- | The type of measurement. cvDataSourceType :: Lens' CollectdValue (Maybe CollectdValueDataSourceType) cvDataSourceType = lens _cvDataSourceType (\ s a -> s{_cvDataSourceType = a}) -- | The measurement value. cvValue :: Lens' CollectdValue (Maybe TypedValue) cvValue = lens _cvValue (\ s a -> s{_cvValue = a}) instance FromJSON CollectdValue where parseJSON = withObject "CollectdValue" (\ o -> CollectdValue' <$> (o .:? "dataSourceName") <*> (o .:? "dataSourceType") <*> (o .:? "value")) instance ToJSON CollectdValue where toJSON CollectdValue'{..} = object (catMaybes [("dataSourceName" .=) <$> _cvDataSourceName, ("dataSourceType" .=) <$> _cvDataSourceType, ("value" .=) <$> _cvValue]) -- | The CreateCollectdTimeSeries request. -- -- /See:/ 'createCollectdTimeSeriesRequest' smart constructor. data CreateCollectdTimeSeriesRequest = CreateCollectdTimeSeriesRequest' { _cctsrCollectdPayloads :: !(Maybe [CollectdPayload]) , _cctsrResource :: !(Maybe MonitoredResource) , _cctsrCollectdVersion :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'CreateCollectdTimeSeriesRequest' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'cctsrCollectdPayloads' -- -- * 'cctsrResource' -- -- * 'cctsrCollectdVersion' createCollectdTimeSeriesRequest :: CreateCollectdTimeSeriesRequest createCollectdTimeSeriesRequest = CreateCollectdTimeSeriesRequest' { _cctsrCollectdPayloads = Nothing , _cctsrResource = Nothing , _cctsrCollectdVersion = Nothing } -- | The collectd payloads representing the time series data. You must not -- include more than a single point for each time series, so no two -- payloads can have the same values for all of the fields plugin, -- plugin_instance, type, and type_instance. cctsrCollectdPayloads :: Lens' CreateCollectdTimeSeriesRequest [CollectdPayload] cctsrCollectdPayloads = lens _cctsrCollectdPayloads (\ s a -> s{_cctsrCollectdPayloads = a}) . _Default . _Coerce -- | The monitored resource associated with the time series. cctsrResource :: Lens' CreateCollectdTimeSeriesRequest (Maybe MonitoredResource) cctsrResource = lens _cctsrResource (\ s a -> s{_cctsrResource = a}) -- | The version of collectd that collected the data. Example: -- \"5.3.0-192.el6\". cctsrCollectdVersion :: Lens' CreateCollectdTimeSeriesRequest (Maybe Text) cctsrCollectdVersion = lens _cctsrCollectdVersion (\ s a -> s{_cctsrCollectdVersion = a}) instance FromJSON CreateCollectdTimeSeriesRequest where parseJSON = withObject "CreateCollectdTimeSeriesRequest" (\ o -> CreateCollectdTimeSeriesRequest' <$> (o .:? "collectdPayloads" .!= mempty) <*> (o .:? "resource") <*> (o .:? "collectdVersion")) instance ToJSON CreateCollectdTimeSeriesRequest where toJSON CreateCollectdTimeSeriesRequest'{..} = object (catMaybes [("collectdPayloads" .=) <$> _cctsrCollectdPayloads, ("resource" .=) <$> _cctsrResource, ("collectdVersion" .=) <$> _cctsrCollectdVersion]) -- | A point\'s value columns and time interval. Each point has one or more -- point values corresponding to the entries in point_descriptors field in -- the TimeSeriesDescriptor associated with this object. -- -- /See:/ 'pointData' smart constructor. data PointData = PointData' { _pdValues :: !(Maybe [TypedValue]) , _pdTimeInterval :: !(Maybe TimeInterval) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'PointData' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pdValues' -- -- * 'pdTimeInterval' pointData :: PointData pointData = PointData' {_pdValues = Nothing, _pdTimeInterval = Nothing} -- | The values that make up the point. pdValues :: Lens' PointData [TypedValue] pdValues = lens _pdValues (\ s a -> s{_pdValues = a}) . _Default . _Coerce -- | The time interval associated with the point. pdTimeInterval :: Lens' PointData (Maybe TimeInterval) pdTimeInterval = lens _pdTimeInterval (\ s a -> s{_pdTimeInterval = a}) instance FromJSON PointData where parseJSON = withObject "PointData" (\ o -> PointData' <$> (o .:? "values" .!= mempty) <*> (o .:? "timeInterval")) instance ToJSON PointData where toJSON PointData'{..} = object (catMaybes [("values" .=) <$> _pdValues, ("timeInterval" .=) <$> _pdTimeInterval]) -- | Describes how to combine multiple time series to provide a different -- view of the data. Aggregation of time series is done in two steps. -- First, each time series in the set is aligned to the same time interval -- boundaries, then the set of time series is optionally reduced in -- number.Alignment consists of applying the per_series_aligner operation -- to each time series after its data has been divided into regular -- alignment_period time intervals. This process takes all of the data -- points in an alignment period, applies a mathematical transformation -- such as averaging, minimum, maximum, delta, etc., and converts them into -- a single data point per period.Reduction is when the aligned and -- transformed time series can optionally be combined, reducing the number -- of time series through similar mathematical transformations. Reduction -- involves applying a cross_series_reducer to all the time series, -- optionally sorting the time series into subsets with group_by_fields, -- and applying the reducer to each subset.The raw time series data can -- contain a huge amount of information from multiple sources. Alignment -- and reduction transforms this mass of data into a more manageable and -- representative collection of data, for example \"the 95% latency across -- the average of all tasks in a cluster\". This representative data can be -- more easily graphed and comprehended, and the individual time series -- data is still available for later drilldown. For more details, see -- Filtering and aggregation -- (https:\/\/cloud.google.com\/monitoring\/api\/v3\/aggregation). -- -- /See:/ 'aggregation' smart constructor. data Aggregation = Aggregation' { _aPerSeriesAligner :: !(Maybe AggregationPerSeriesAligner) , _aCrossSeriesReducer :: !(Maybe AggregationCrossSeriesReducer) , _aAlignmentPeriod :: !(Maybe GDuration) , _aGroupByFields :: !(Maybe [Text]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Aggregation' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'aPerSeriesAligner' -- -- * 'aCrossSeriesReducer' -- -- * 'aAlignmentPeriod' -- -- * 'aGroupByFields' aggregation :: Aggregation aggregation = Aggregation' { _aPerSeriesAligner = Nothing , _aCrossSeriesReducer = Nothing , _aAlignmentPeriod = Nothing , _aGroupByFields = Nothing } -- | An Aligner describes how to bring the data points in a single time -- series into temporal alignment. Except for ALIGN_NONE, all alignments -- cause all the data points in an alignment_period to be mathematically -- grouped together, resulting in a single data point for each -- alignment_period with end timestamp at the end of the period.Not all -- alignment operations may be applied to all time series. The valid -- choices depend on the metric_kind and value_type of the original time -- series. Alignment can change the metric_kind or the value_type of the -- time series.Time series data must be aligned in order to perform -- cross-time series reduction. If cross_series_reducer is specified, then -- per_series_aligner must be specified and not equal to ALIGN_NONE and -- alignment_period must be specified; otherwise, an error is returned. aPerSeriesAligner :: Lens' Aggregation (Maybe AggregationPerSeriesAligner) aPerSeriesAligner = lens _aPerSeriesAligner (\ s a -> s{_aPerSeriesAligner = a}) -- | The reduction operation to be used to combine time series into a single -- time series, where the value of each data point in the resulting series -- is a function of all the already aligned values in the input time -- series.Not all reducer operations can be applied to all time series. The -- valid choices depend on the metric_kind and the value_type of the -- original time series. Reduction can yield a time series with a different -- metric_kind or value_type than the input time series.Time series data -- must first be aligned (see per_series_aligner) in order to perform -- cross-time series reduction. If cross_series_reducer is specified, then -- per_series_aligner must be specified, and must not be ALIGN_NONE. An -- alignment_period must also be specified; otherwise, an error is -- returned. aCrossSeriesReducer :: Lens' Aggregation (Maybe AggregationCrossSeriesReducer) aCrossSeriesReducer = lens _aCrossSeriesReducer (\ s a -> s{_aCrossSeriesReducer = a}) -- | The alignment_period specifies a time interval, in seconds, that is used -- to divide the data in all the time series into consistent blocks of -- time. This will be done before the per-series aligner can be applied to -- the data.The value must be at least 60 seconds. If a per-series aligner -- other than ALIGN_NONE is specified, this field is required or an error -- is returned. If no per-series aligner is specified, or the aligner -- ALIGN_NONE is specified, then this field is ignored.The maximum value of -- the alignment_period is 104 weeks (2 years) for charts, and 90,000 -- seconds (25 hours) for alerting policies. aAlignmentPeriod :: Lens' Aggregation (Maybe Scientific) aAlignmentPeriod = lens _aAlignmentPeriod (\ s a -> s{_aAlignmentPeriod = a}) . mapping _GDuration -- | The set of fields to preserve when cross_series_reducer is specified. -- The group_by_fields determine how the time series are partitioned into -- subsets prior to applying the aggregation operation. Each subset -- contains time series that have the same value for each of the grouping -- fields. Each individual time series is a member of exactly one subset. -- The cross_series_reducer is applied to each subset of time series. It is -- not possible to reduce across different resource types, so this field -- implicitly contains resource.type. Fields not specified in -- group_by_fields are aggregated away. If group_by_fields is not specified -- and all the time series have the same resource type, then the time -- series are aggregated into a single output time series. If -- cross_series_reducer is not defined, this field is ignored. aGroupByFields :: Lens' Aggregation [Text] aGroupByFields = lens _aGroupByFields (\ s a -> s{_aGroupByFields = a}) . _Default . _Coerce instance FromJSON Aggregation where parseJSON = withObject "Aggregation" (\ o -> Aggregation' <$> (o .:? "perSeriesAligner") <*> (o .:? "crossSeriesReducer") <*> (o .:? "alignmentPeriod") <*> (o .:? "groupByFields" .!= mempty)) instance ToJSON Aggregation where toJSON Aggregation'{..} = object (catMaybes [("perSeriesAligner" .=) <$> _aPerSeriesAligner, ("crossSeriesReducer" .=) <$> _aCrossSeriesReducer, ("alignmentPeriod" .=) <$> _aAlignmentPeriod, ("groupByFields" .=) <$> _aGroupByFields]) -- | This message configures which resources and services to monitor for -- availability. -- -- /See:/ 'uptimeCheckConfig' smart constructor. data UptimeCheckConfig = UptimeCheckConfig' { _uccInternalCheckers :: !(Maybe [InternalChecker]) , _uccPeriod :: !(Maybe GDuration) , _uccContentMatchers :: !(Maybe [ContentMatcher]) , _uccName :: !(Maybe Text) , _uccMonitoredResource :: !(Maybe MonitoredResource) , _uccSelectedRegions :: !(Maybe [UptimeCheckConfigSelectedRegionsItem]) , _uccIsInternal :: !(Maybe Bool) , _uccDisplayName :: !(Maybe Text) , _uccResourceGroup :: !(Maybe ResourceGroup) , _uccTimeout :: !(Maybe GDuration) , _uccHTTPCheck :: !(Maybe HTTPCheck) , _uccTCPCheck :: !(Maybe TCPCheck) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'UptimeCheckConfig' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'uccInternalCheckers' -- -- * 'uccPeriod' -- -- * 'uccContentMatchers' -- -- * 'uccName' -- -- * 'uccMonitoredResource' -- -- * 'uccSelectedRegions' -- -- * 'uccIsInternal' -- -- * 'uccDisplayName' -- -- * 'uccResourceGroup' -- -- * 'uccTimeout' -- -- * 'uccHTTPCheck' -- -- * 'uccTCPCheck' uptimeCheckConfig :: UptimeCheckConfig uptimeCheckConfig = UptimeCheckConfig' { _uccInternalCheckers = Nothing , _uccPeriod = Nothing , _uccContentMatchers = Nothing , _uccName = Nothing , _uccMonitoredResource = Nothing , _uccSelectedRegions = Nothing , _uccIsInternal = Nothing , _uccDisplayName = Nothing , _uccResourceGroup = Nothing , _uccTimeout = Nothing , _uccHTTPCheck = Nothing , _uccTCPCheck = Nothing } -- | The internal checkers that this check will egress from. If is_internal -- is true and this list is empty, the check will egress from all the -- InternalCheckers configured for the project that owns this -- UptimeCheckConfig. uccInternalCheckers :: Lens' UptimeCheckConfig [InternalChecker] uccInternalCheckers = lens _uccInternalCheckers (\ s a -> s{_uccInternalCheckers = a}) . _Default . _Coerce -- | How often, in seconds, the Uptime check is performed. Currently, the -- only supported values are 60s (1 minute), 300s (5 minutes), 600s (10 -- minutes), and 900s (15 minutes). Optional, defaults to 60s. uccPeriod :: Lens' UptimeCheckConfig (Maybe Scientific) uccPeriod = lens _uccPeriod (\ s a -> s{_uccPeriod = a}) . mapping _GDuration -- | The content that is expected to appear in the data returned by the -- target server against which the check is run. Currently, only the first -- entry in the content_matchers list is supported, and additional entries -- will be ignored. This field is optional and should only be specified if -- a content match is required as part of the\/ Uptime check. uccContentMatchers :: Lens' UptimeCheckConfig [ContentMatcher] uccContentMatchers = lens _uccContentMatchers (\ s a -> s{_uccContentMatchers = a}) . _Default . _Coerce -- | A unique resource name for this Uptime check configuration. The format -- is: -- projects\/[PROJECT_ID_OR_NUMBER]\/uptimeCheckConfigs\/[UPTIME_CHECK_ID] -- [PROJECT_ID_OR_NUMBER] is the Workspace host project associated with the -- Uptime check.This field should be omitted when creating the Uptime check -- configuration; on create, the resource name is assigned by the server -- and included in the response. uccName :: Lens' UptimeCheckConfig (Maybe Text) uccName = lens _uccName (\ s a -> s{_uccName = a}) -- | The monitored resource -- (https:\/\/cloud.google.com\/monitoring\/api\/resources) associated with -- the configuration. The following monitored resource types are valid for -- this field: uptime_url, gce_instance, gae_app, aws_ec2_instance, -- aws_elb_load_balancer uccMonitoredResource :: Lens' UptimeCheckConfig (Maybe MonitoredResource) uccMonitoredResource = lens _uccMonitoredResource (\ s a -> s{_uccMonitoredResource = a}) -- | The list of regions from which the check will be run. Some regions -- contain one location, and others contain more than one. If this field is -- specified, enough regions must be provided to include a minimum of 3 -- locations. Not specifying this field will result in Uptime checks -- running from all available regions. uccSelectedRegions :: Lens' UptimeCheckConfig [UptimeCheckConfigSelectedRegionsItem] uccSelectedRegions = lens _uccSelectedRegions (\ s a -> s{_uccSelectedRegions = a}) . _Default . _Coerce -- | If this is true, then checks are made only from the -- \'internal_checkers\'. If it is false, then checks are made only from -- the \'selected_regions\'. It is an error to provide \'selected_regions\' -- when is_internal is true, or to provide \'internal_checkers\' when -- is_internal is false. uccIsInternal :: Lens' UptimeCheckConfig (Maybe Bool) uccIsInternal = lens _uccIsInternal (\ s a -> s{_uccIsInternal = a}) -- | A human-friendly name for the Uptime check configuration. The display -- name should be unique within a Stackdriver Workspace in order to make it -- easier to identify; however, uniqueness is not enforced. Required. uccDisplayName :: Lens' UptimeCheckConfig (Maybe Text) uccDisplayName = lens _uccDisplayName (\ s a -> s{_uccDisplayName = a}) -- | The group resource associated with the configuration. uccResourceGroup :: Lens' UptimeCheckConfig (Maybe ResourceGroup) uccResourceGroup = lens _uccResourceGroup (\ s a -> s{_uccResourceGroup = a}) -- | The maximum amount of time to wait for the request to complete (must be -- between 1 and 60 seconds). Required. uccTimeout :: Lens' UptimeCheckConfig (Maybe Scientific) uccTimeout = lens _uccTimeout (\ s a -> s{_uccTimeout = a}) . mapping _GDuration -- | Contains information needed to make an HTTP or HTTPS check. uccHTTPCheck :: Lens' UptimeCheckConfig (Maybe HTTPCheck) uccHTTPCheck = lens _uccHTTPCheck (\ s a -> s{_uccHTTPCheck = a}) -- | Contains information needed to make a TCP check. uccTCPCheck :: Lens' UptimeCheckConfig (Maybe TCPCheck) uccTCPCheck = lens _uccTCPCheck (\ s a -> s{_uccTCPCheck = a}) instance FromJSON UptimeCheckConfig where parseJSON = withObject "UptimeCheckConfig" (\ o -> UptimeCheckConfig' <$> (o .:? "internalCheckers" .!= mempty) <*> (o .:? "period") <*> (o .:? "contentMatchers" .!= mempty) <*> (o .:? "name") <*> (o .:? "monitoredResource") <*> (o .:? "selectedRegions" .!= mempty) <*> (o .:? "isInternal") <*> (o .:? "displayName") <*> (o .:? "resourceGroup") <*> (o .:? "timeout") <*> (o .:? "httpCheck") <*> (o .:? "tcpCheck")) instance ToJSON UptimeCheckConfig where toJSON UptimeCheckConfig'{..} = object (catMaybes [("internalCheckers" .=) <$> _uccInternalCheckers, ("period" .=) <$> _uccPeriod, ("contentMatchers" .=) <$> _uccContentMatchers, ("name" .=) <$> _uccName, ("monitoredResource" .=) <$> _uccMonitoredResource, ("selectedRegions" .=) <$> _uccSelectedRegions, ("isInternal" .=) <$> _uccIsInternal, ("displayName" .=) <$> _uccDisplayName, ("resourceGroup" .=) <$> _uccResourceGroup, ("timeout" .=) <$> _uccTimeout, ("httpCheck" .=) <$> _uccHTTPCheck, ("tcpCheck" .=) <$> _uccTCPCheck]) -- | A single data point in a time series. -- -- /See:/ 'point' smart constructor. data Point = Point' { _pValue :: !(Maybe TypedValue) , _pInterval :: !(Maybe TimeInterval) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Point' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pValue' -- -- * 'pInterval' point :: Point point = Point' {_pValue = Nothing, _pInterval = Nothing} -- | The value of the data point. pValue :: Lens' Point (Maybe TypedValue) pValue = lens _pValue (\ s a -> s{_pValue = a}) -- | The time interval to which the data point applies. For GAUGE metrics, -- the start time is optional, but if it is supplied, it must equal the end -- time. For DELTA metrics, the start and end time should specify a -- non-zero interval, with subsequent points specifying contiguous and -- non-overlapping intervals. For CUMULATIVE metrics, the start and end -- time should specify a non-zero interval, with subsequent points -- specifying the same start time and increasing end times, until an event -- resets the cumulative value to zero and sets a new start time for the -- following points. pInterval :: Lens' Point (Maybe TimeInterval) pInterval = lens _pInterval (\ s a -> s{_pInterval = a}) instance FromJSON Point where parseJSON = withObject "Point" (\ o -> Point' <$> (o .:? "value") <*> (o .:? "interval")) instance ToJSON Point where toJSON Point'{..} = object (catMaybes [("value" .=) <$> _pValue, ("interval" .=) <$> _pInterval]) -- | A collection of data points sent from a collectd-based plugin. See the -- collectd documentation for more information. -- -- /See:/ 'collectdPayload' smart constructor. data CollectdPayload = CollectdPayload' { _cpStartTime :: !(Maybe DateTime') , _cpPluginInstance :: !(Maybe Text) , _cpValues :: !(Maybe [CollectdValue]) , _cpTypeInstance :: !(Maybe Text) , _cpEndTime :: !(Maybe DateTime') , _cpMetadata :: !(Maybe CollectdPayloadMetadata) , _cpType :: !(Maybe Text) , _cpPlugin :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'CollectdPayload' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'cpStartTime' -- -- * 'cpPluginInstance' -- -- * 'cpValues' -- -- * 'cpTypeInstance' -- -- * 'cpEndTime' -- -- * 'cpMetadata' -- -- * 'cpType' -- -- * 'cpPlugin' collectdPayload :: CollectdPayload collectdPayload = CollectdPayload' { _cpStartTime = Nothing , _cpPluginInstance = Nothing , _cpValues = Nothing , _cpTypeInstance = Nothing , _cpEndTime = Nothing , _cpMetadata = Nothing , _cpType = Nothing , _cpPlugin = Nothing } -- | The start time of the interval. cpStartTime :: Lens' CollectdPayload (Maybe UTCTime) cpStartTime = lens _cpStartTime (\ s a -> s{_cpStartTime = a}) . mapping _DateTime -- | The instance name of the plugin Example: \"hdcl\". cpPluginInstance :: Lens' CollectdPayload (Maybe Text) cpPluginInstance = lens _cpPluginInstance (\ s a -> s{_cpPluginInstance = a}) -- | The measured values during this time interval. Each value must have a -- different data_source_name. cpValues :: Lens' CollectdPayload [CollectdValue] cpValues = lens _cpValues (\ s a -> s{_cpValues = a}) . _Default . _Coerce -- | The measurement type instance. Example: \"used\". cpTypeInstance :: Lens' CollectdPayload (Maybe Text) cpTypeInstance = lens _cpTypeInstance (\ s a -> s{_cpTypeInstance = a}) -- | The end time of the interval. cpEndTime :: Lens' CollectdPayload (Maybe UTCTime) cpEndTime = lens _cpEndTime (\ s a -> s{_cpEndTime = a}) . mapping _DateTime -- | The measurement metadata. Example: \"process_id\" -> 12345 cpMetadata :: Lens' CollectdPayload (Maybe CollectdPayloadMetadata) cpMetadata = lens _cpMetadata (\ s a -> s{_cpMetadata = a}) -- | The measurement type. Example: \"memory\". cpType :: Lens' CollectdPayload (Maybe Text) cpType = lens _cpType (\ s a -> s{_cpType = a}) -- | The name of the plugin. Example: \"disk\". cpPlugin :: Lens' CollectdPayload (Maybe Text) cpPlugin = lens _cpPlugin (\ s a -> s{_cpPlugin = a}) instance FromJSON CollectdPayload where parseJSON = withObject "CollectdPayload" (\ o -> CollectdPayload' <$> (o .:? "startTime") <*> (o .:? "pluginInstance") <*> (o .:? "values" .!= mempty) <*> (o .:? "typeInstance") <*> (o .:? "endTime") <*> (o .:? "metadata") <*> (o .:? "type") <*> (o .:? "plugin")) instance ToJSON CollectdPayload where toJSON CollectdPayload'{..} = object (catMaybes [("startTime" .=) <$> _cpStartTime, ("pluginInstance" .=) <$> _cpPluginInstance, ("values" .=) <$> _cpValues, ("typeInstance" .=) <$> _cpTypeInstance, ("endTime" .=) <$> _cpEndTime, ("metadata" .=) <$> _cpMetadata, ("type" .=) <$> _cpType, ("plugin" .=) <$> _cpPlugin]) -- | Describes a change made to a configuration. -- -- /See:/ 'mutationRecord' smart constructor. data MutationRecord = MutationRecord' { _mrMutatedBy :: !(Maybe Text) , _mrMutateTime :: !(Maybe DateTime') } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'MutationRecord' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'mrMutatedBy' -- -- * 'mrMutateTime' mutationRecord :: MutationRecord mutationRecord = MutationRecord' {_mrMutatedBy = Nothing, _mrMutateTime = Nothing} -- | The email address of the user making the change. mrMutatedBy :: Lens' MutationRecord (Maybe Text) mrMutatedBy = lens _mrMutatedBy (\ s a -> s{_mrMutatedBy = a}) -- | When the change occurred. mrMutateTime :: Lens' MutationRecord (Maybe UTCTime) mrMutateTime = lens _mrMutateTime (\ s a -> s{_mrMutateTime = a}) . mapping _DateTime instance FromJSON MutationRecord where parseJSON = withObject "MutationRecord" (\ o -> MutationRecord' <$> (o .:? "mutatedBy") <*> (o .:? "mutateTime")) instance ToJSON MutationRecord where toJSON MutationRecord'{..} = object (catMaybes [("mutatedBy" .=) <$> _mrMutatedBy, ("mutateTime" .=) <$> _mrMutateTime]) -- | A specific metric, identified by specifying values for all of the labels -- of a MetricDescriptor. -- -- /See:/ 'metric' smart constructor. data Metric = Metric' { _mLabels :: !(Maybe MetricLabels) , _mType :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Metric' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'mLabels' -- -- * 'mType' metric :: Metric metric = Metric' {_mLabels = Nothing, _mType = Nothing} -- | The set of label values that uniquely identify this metric. All labels -- listed in the MetricDescriptor must be assigned values. mLabels :: Lens' Metric (Maybe MetricLabels) mLabels = lens _mLabels (\ s a -> s{_mLabels = a}) -- | An existing metric type, see google.api.MetricDescriptor. For example, -- custom.googleapis.com\/invoice\/paid\/amount. mType :: Lens' Metric (Maybe Text) mType = lens _mType (\ s a -> s{_mType = a}) instance FromJSON Metric where parseJSON = withObject "Metric" (\ o -> Metric' <$> (o .:? "labels") <*> (o .:? "type")) instance ToJSON Metric where toJSON Metric'{..} = object (catMaybes [("labels" .=) <$> _mLabels, ("type" .=) <$> _mType]) -- | Describes the error status for payloads that were not written. -- -- /See:/ 'collectdPayloadError' smart constructor. data CollectdPayloadError = CollectdPayloadError' { _cpeError :: !(Maybe Status) , _cpeValueErrors :: !(Maybe [CollectdValueError]) , _cpeIndex :: !(Maybe (Textual Int32)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'CollectdPayloadError' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'cpeError' -- -- * 'cpeValueErrors' -- -- * 'cpeIndex' collectdPayloadError :: CollectdPayloadError collectdPayloadError = CollectdPayloadError' {_cpeError = Nothing, _cpeValueErrors = Nothing, _cpeIndex = Nothing} -- | Records the error status for the payload. If this field is present, the -- partial errors for nested values won\'t be populated. cpeError :: Lens' CollectdPayloadError (Maybe Status) cpeError = lens _cpeError (\ s a -> s{_cpeError = a}) -- | Records the error status for values that were not written due to an -- error.Failed payloads for which nothing is written will not include -- partial value errors. cpeValueErrors :: Lens' CollectdPayloadError [CollectdValueError] cpeValueErrors = lens _cpeValueErrors (\ s a -> s{_cpeValueErrors = a}) . _Default . _Coerce -- | The zero-based index in -- CreateCollectdTimeSeriesRequest.collectd_payloads. cpeIndex :: Lens' CollectdPayloadError (Maybe Int32) cpeIndex = lens _cpeIndex (\ s a -> s{_cpeIndex = a}) . mapping _Coerce instance FromJSON CollectdPayloadError where parseJSON = withObject "CollectdPayloadError" (\ o -> CollectdPayloadError' <$> (o .:? "error") <*> (o .:? "valueErrors" .!= mempty) <*> (o .:? "index")) instance ToJSON CollectdPayloadError where toJSON CollectdPayloadError'{..} = object (catMaybes [("error" .=) <$> _cpeError, ("valueErrors" .=) <$> _cpeValueErrors, ("index" .=) <$> _cpeIndex]) -- | The SendNotificationChannelVerificationCode request. -- -- /See:/ 'sendNotificationChannelVerificationCodeRequest' smart constructor. data SendNotificationChannelVerificationCodeRequest = SendNotificationChannelVerificationCodeRequest' deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'SendNotificationChannelVerificationCodeRequest' with the minimum fields required to make a request. -- sendNotificationChannelVerificationCodeRequest :: SendNotificationChannelVerificationCodeRequest sendNotificationChannelVerificationCodeRequest = SendNotificationChannelVerificationCodeRequest' instance FromJSON SendNotificationChannelVerificationCodeRequest where parseJSON = withObject "SendNotificationChannelVerificationCodeRequest" (\ o -> pure SendNotificationChannelVerificationCodeRequest') instance ToJSON SendNotificationChannelVerificationCodeRequest where toJSON = const emptyObject -- | Specifies an exponential sequence of buckets that have a width that is -- proportional to the value of the lower bound. Each bucket represents a -- constant relative uncertainty on a specific value in the bucket.There -- are num_finite_buckets + 2 (= N) buckets. Bucket i has the following -- boundaries:Upper bound (0 \<= i \< N-1): scale * (growth_factor ^ i). -- Lower bound (1 \<= i \< N): scale * (growth_factor ^ (i - 1)). -- -- /See:/ 'exponential' smart constructor. data Exponential = Exponential' { _eGrowthFactor :: !(Maybe (Textual Double)) , _eScale :: !(Maybe (Textual Double)) , _eNumFiniteBuckets :: !(Maybe (Textual Int32)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Exponential' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'eGrowthFactor' -- -- * 'eScale' -- -- * 'eNumFiniteBuckets' exponential :: Exponential exponential = Exponential' {_eGrowthFactor = Nothing, _eScale = Nothing, _eNumFiniteBuckets = Nothing} -- | Must be greater than 1. eGrowthFactor :: Lens' Exponential (Maybe Double) eGrowthFactor = lens _eGrowthFactor (\ s a -> s{_eGrowthFactor = a}) . mapping _Coerce -- | Must be greater than 0. eScale :: Lens' Exponential (Maybe Double) eScale = lens _eScale (\ s a -> s{_eScale = a}) . mapping _Coerce -- | Must be greater than 0. eNumFiniteBuckets :: Lens' Exponential (Maybe Int32) eNumFiniteBuckets = lens _eNumFiniteBuckets (\ s a -> s{_eNumFiniteBuckets = a}) . mapping _Coerce instance FromJSON Exponential where parseJSON = withObject "Exponential" (\ o -> Exponential' <$> (o .:? "growthFactor") <*> (o .:? "scale") <*> (o .:? "numFiniteBuckets")) instance ToJSON Exponential where toJSON Exponential'{..} = object (catMaybes [("growthFactor" .=) <$> _eGrowthFactor, ("scale" .=) <$> _eScale, ("numFiniteBuckets" .=) <$> _eNumFiniteBuckets]) -- | A PerformanceThreshold is used when each window is good when that window -- has a sufficiently high performance. -- -- /See:/ 'performanceThreshold' smart constructor. data PerformanceThreshold = PerformanceThreshold' { _ptBasicSliPerformance :: !(Maybe BasicSli) , _ptPerformance :: !(Maybe RequestBasedSli) , _ptThreshold :: !(Maybe (Textual Double)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'PerformanceThreshold' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ptBasicSliPerformance' -- -- * 'ptPerformance' -- -- * 'ptThreshold' performanceThreshold :: PerformanceThreshold performanceThreshold = PerformanceThreshold' { _ptBasicSliPerformance = Nothing , _ptPerformance = Nothing , _ptThreshold = Nothing } -- | BasicSli to evaluate to judge window quality. ptBasicSliPerformance :: Lens' PerformanceThreshold (Maybe BasicSli) ptBasicSliPerformance = lens _ptBasicSliPerformance (\ s a -> s{_ptBasicSliPerformance = a}) -- | RequestBasedSli to evaluate to judge window quality. ptPerformance :: Lens' PerformanceThreshold (Maybe RequestBasedSli) ptPerformance = lens _ptPerformance (\ s a -> s{_ptPerformance = a}) -- | If window performance >= threshold, the window is counted as good. ptThreshold :: Lens' PerformanceThreshold (Maybe Double) ptThreshold = lens _ptThreshold (\ s a -> s{_ptThreshold = a}) . mapping _Coerce instance FromJSON PerformanceThreshold where parseJSON = withObject "PerformanceThreshold" (\ o -> PerformanceThreshold' <$> (o .:? "basicSliPerformance") <*> (o .:? "performance") <*> (o .:? "threshold")) instance ToJSON PerformanceThreshold where toJSON PerformanceThreshold'{..} = object (catMaybes [("basicSliPerformance" .=) <$> _ptBasicSliPerformance, ("performance" .=) <$> _ptPerformance, ("threshold" .=) <$> _ptThreshold]) -- | A condition type that checks whether a log message in the scoping -- project (https:\/\/cloud.google.com\/monitoring\/api\/v3#project_name) -- satisfies the given filter. Logs from other projects in the metrics -- scope are not evaluated. -- -- /See:/ 'logMatch' smart constructor. data LogMatch = LogMatch' { _lmLabelExtractors :: !(Maybe LogMatchLabelExtractors) , _lmFilter :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'LogMatch' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lmLabelExtractors' -- -- * 'lmFilter' logMatch :: LogMatch logMatch = LogMatch' {_lmLabelExtractors = Nothing, _lmFilter = Nothing} -- | Optional. A map from a label key to an extractor expression, which is -- used to extract the value for this label key. Each entry in this map is -- a specification for how data should be extracted from log entries that -- match filter. Each combination of extracted values is treated as a -- separate rule for the purposes of triggering notifications. Label keys -- and corresponding values can be used in notifications generated by this -- condition.Please see the documentation on logs-based metric -- valueExtractors for syntax and examples. lmLabelExtractors :: Lens' LogMatch (Maybe LogMatchLabelExtractors) lmLabelExtractors = lens _lmLabelExtractors (\ s a -> s{_lmLabelExtractors = a}) -- | Required. A logs-based filter. See Advanced Logs Queries for how this -- filter should be constructed. lmFilter :: Lens' LogMatch (Maybe Text) lmFilter = lens _lmFilter (\ s a -> s{_lmFilter = a}) instance FromJSON LogMatch where parseJSON = withObject "LogMatch" (\ o -> LogMatch' <$> (o .:? "labelExtractors") <*> (o .:? "filter")) instance ToJSON LogMatch where toJSON LogMatch'{..} = object (catMaybes [("labelExtractors" .=) <$> _lmLabelExtractors, ("filter" .=) <$> _lmFilter]) -- | The range of the population values. -- -- /See:/ 'range' smart constructor. data Range = Range' { _rMax :: !(Maybe (Textual Double)) , _rMin :: !(Maybe (Textual Double)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Range' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'rMax' -- -- * 'rMin' range :: Range range = Range' {_rMax = Nothing, _rMin = Nothing} -- | The maximum of the population values. rMax :: Lens' Range (Maybe Double) rMax = lens _rMax (\ s a -> s{_rMax = a}) . mapping _Coerce -- | The minimum of the population values. rMin :: Lens' Range (Maybe Double) rMin = lens _rMin (\ s a -> s{_rMin = a}) . mapping _Coerce instance FromJSON Range where parseJSON = withObject "Range" (\ o -> Range' <$> (o .:? "max") <*> (o .:? "min")) instance ToJSON Range where toJSON Range'{..} = object (catMaybes [("max" .=) <$> _rMax, ("min" .=) <$> _rMin]) -- | Canonical service scoped to an Istio mesh. Anthos clusters running ASM -- >= 1.6.8 will have their services ingested as this type. -- -- /See:/ 'istioCanonicalService' smart constructor. data IstioCanonicalService = IstioCanonicalService' { _icsCanonicalService :: !(Maybe Text) , _icsMeshUid :: !(Maybe Text) , _icsCanonicalServiceNamespace :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'IstioCanonicalService' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'icsCanonicalService' -- -- * 'icsMeshUid' -- -- * 'icsCanonicalServiceNamespace' istioCanonicalService :: IstioCanonicalService istioCanonicalService = IstioCanonicalService' { _icsCanonicalService = Nothing , _icsMeshUid = Nothing , _icsCanonicalServiceNamespace = Nothing } -- | The name of the canonical service underlying this service. Corresponds -- to the destination_canonical_service_name metric label in label in Istio -- metrics (https:\/\/cloud.google.com\/monitoring\/api\/metrics_istio). icsCanonicalService :: Lens' IstioCanonicalService (Maybe Text) icsCanonicalService = lens _icsCanonicalService (\ s a -> s{_icsCanonicalService = a}) -- | Identifier for the Istio mesh in which this canonical service is -- defined. Corresponds to the mesh_uid metric label in Istio metrics -- (https:\/\/cloud.google.com\/monitoring\/api\/metrics_istio). icsMeshUid :: Lens' IstioCanonicalService (Maybe Text) icsMeshUid = lens _icsMeshUid (\ s a -> s{_icsMeshUid = a}) -- | The namespace of the canonical service underlying this service. -- Corresponds to the destination_canonical_service_namespace metric label -- in Istio metrics -- (https:\/\/cloud.google.com\/monitoring\/api\/metrics_istio). icsCanonicalServiceNamespace :: Lens' IstioCanonicalService (Maybe Text) icsCanonicalServiceNamespace = lens _icsCanonicalServiceNamespace (\ s a -> s{_icsCanonicalServiceNamespace = a}) instance FromJSON IstioCanonicalService where parseJSON = withObject "IstioCanonicalService" (\ o -> IstioCanonicalService' <$> (o .:? "canonicalService") <*> (o .:? "meshUid") <*> (o .:? "canonicalServiceNamespace")) instance ToJSON IstioCanonicalService where toJSON IstioCanonicalService'{..} = object (catMaybes [("canonicalService" .=) <$> _icsCanonicalService, ("meshUid" .=) <$> _icsMeshUid, ("canonicalServiceNamespace" .=) <$> _icsCanonicalServiceNamespace]) -- | App Engine service. Learn more at https:\/\/cloud.google.com\/appengine. -- -- /See:/ 'appEngine' smart constructor. newtype AppEngine = AppEngine' { _aeModuleId :: Maybe Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'AppEngine' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'aeModuleId' appEngine :: AppEngine appEngine = AppEngine' {_aeModuleId = Nothing} -- | The ID of the App Engine module underlying this service. Corresponds to -- the module_id resource label in the gae_app monitored resource: -- https:\/\/cloud.google.com\/monitoring\/api\/resources#tag_gae_app aeModuleId :: Lens' AppEngine (Maybe Text) aeModuleId = lens _aeModuleId (\ s a -> s{_aeModuleId = a}) instance FromJSON AppEngine where parseJSON = withObject "AppEngine" (\ o -> AppEngine' <$> (o .:? "moduleId")) instance ToJSON AppEngine where toJSON AppEngine'{..} = object (catMaybes [("moduleId" .=) <$> _aeModuleId]) -- | The QueryTimeSeries response. -- -- /See:/ 'queryTimeSeriesResponse' smart constructor. data QueryTimeSeriesResponse = QueryTimeSeriesResponse' { _qtsrNextPageToken :: !(Maybe Text) , _qtsrPartialErrors :: !(Maybe [Status]) , _qtsrTimeSeriesDescriptor :: !(Maybe TimeSeriesDescriptor) , _qtsrTimeSeriesData :: !(Maybe [TimeSeriesData]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'QueryTimeSeriesResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'qtsrNextPageToken' -- -- * 'qtsrPartialErrors' -- -- * 'qtsrTimeSeriesDescriptor' -- -- * 'qtsrTimeSeriesData' queryTimeSeriesResponse :: QueryTimeSeriesResponse queryTimeSeriesResponse = QueryTimeSeriesResponse' { _qtsrNextPageToken = Nothing , _qtsrPartialErrors = Nothing , _qtsrTimeSeriesDescriptor = Nothing , _qtsrTimeSeriesData = Nothing } -- | If there are more results than have been returned, then this field is -- set to a non-empty value. To see the additional results, use that value -- as page_token in the next call to this method. qtsrNextPageToken :: Lens' QueryTimeSeriesResponse (Maybe Text) qtsrNextPageToken = lens _qtsrNextPageToken (\ s a -> s{_qtsrNextPageToken = a}) -- | Query execution errors that may have caused the time series data -- returned to be incomplete. The available data will be available in the -- response. qtsrPartialErrors :: Lens' QueryTimeSeriesResponse [Status] qtsrPartialErrors = lens _qtsrPartialErrors (\ s a -> s{_qtsrPartialErrors = a}) . _Default . _Coerce -- | The descriptor for the time series data. qtsrTimeSeriesDescriptor :: Lens' QueryTimeSeriesResponse (Maybe TimeSeriesDescriptor) qtsrTimeSeriesDescriptor = lens _qtsrTimeSeriesDescriptor (\ s a -> s{_qtsrTimeSeriesDescriptor = a}) -- | The time series data. qtsrTimeSeriesData :: Lens' QueryTimeSeriesResponse [TimeSeriesData] qtsrTimeSeriesData = lens _qtsrTimeSeriesData (\ s a -> s{_qtsrTimeSeriesData = a}) . _Default . _Coerce instance FromJSON QueryTimeSeriesResponse where parseJSON = withObject "QueryTimeSeriesResponse" (\ o -> QueryTimeSeriesResponse' <$> (o .:? "nextPageToken") <*> (o .:? "partialErrors" .!= mempty) <*> (o .:? "timeSeriesDescriptor") <*> (o .:? "timeSeriesData" .!= mempty)) instance ToJSON QueryTimeSeriesResponse where toJSON QueryTimeSeriesResponse'{..} = object (catMaybes [("nextPageToken" .=) <$> _qtsrNextPageToken, ("partialErrors" .=) <$> _qtsrPartialErrors, ("timeSeriesDescriptor" .=) <$> _qtsrTimeSeriesDescriptor, ("timeSeriesData" .=) <$> _qtsrTimeSeriesData]) -- | An object representing a resource that can be used for monitoring, -- logging, billing, or other purposes. Examples include virtual machine -- instances, databases, and storage devices such as disks. The type field -- identifies a MonitoredResourceDescriptor object that describes the -- resource\'s schema. Information in the labels field identifies the -- actual resource and its attributes according to the schema. For example, -- a particular Compute Engine VM instance could be represented by the -- following object, because the MonitoredResourceDescriptor for -- \"gce_instance\" has labels \"instance_id\" and \"zone\": { \"type\": -- \"gce_instance\", \"labels\": { \"instance_id\": \"12345678901234\", -- \"zone\": \"us-central1-a\" }} -- -- /See:/ 'monitoredResource' smart constructor. data MonitoredResource = MonitoredResource' { _mrLabels :: !(Maybe MonitoredResourceLabels) , _mrType :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'MonitoredResource' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'mrLabels' -- -- * 'mrType' monitoredResource :: MonitoredResource monitoredResource = MonitoredResource' {_mrLabels = Nothing, _mrType = Nothing} -- | Required. Values for all of the labels listed in the associated -- monitored resource descriptor. For example, Compute Engine VM instances -- use the labels \"project_id\", \"instance_id\", and \"zone\". mrLabels :: Lens' MonitoredResource (Maybe MonitoredResourceLabels) mrLabels = lens _mrLabels (\ s a -> s{_mrLabels = a}) -- | Required. The monitored resource type. This field must match the type -- field of a MonitoredResourceDescriptor object. For example, the type of -- a Compute Engine VM instance is gce_instance. For a list of types, see -- Monitoring resource types -- (https:\/\/cloud.google.com\/monitoring\/api\/resources) and Logging -- resource types -- (https:\/\/cloud.google.com\/logging\/docs\/api\/v2\/resource-list). mrType :: Lens' MonitoredResource (Maybe Text) mrType = lens _mrType (\ s a -> s{_mrType = a}) instance FromJSON MonitoredResource where parseJSON = withObject "MonitoredResource" (\ o -> MonitoredResource' <$> (o .:? "labels") <*> (o .:? "type")) instance ToJSON MonitoredResource where toJSON MonitoredResource'{..} = object (catMaybes [("labels" .=) <$> _mrLabels, ("type" .=) <$> _mrType]) -- | Contains the region, location, and list of IP addresses where checkers -- in the location run from. -- -- /See:/ 'uptimeCheckIP' smart constructor. data UptimeCheckIP = UptimeCheckIP' { _uciIPAddress :: !(Maybe Text) , _uciLocation :: !(Maybe Text) , _uciRegion :: !(Maybe UptimeCheckIPRegion) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'UptimeCheckIP' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'uciIPAddress' -- -- * 'uciLocation' -- -- * 'uciRegion' uptimeCheckIP :: UptimeCheckIP uptimeCheckIP = UptimeCheckIP' {_uciIPAddress = Nothing, _uciLocation = Nothing, _uciRegion = Nothing} -- | The IP address from which the Uptime check originates. This is a fully -- specified IP address (not an IP address range). Most IP addresses, as of -- this publication, are in IPv4 format; however, one should not rely on -- the IP addresses being in IPv4 format indefinitely, and should support -- interpreting this field in either IPv4 or IPv6 format. uciIPAddress :: Lens' UptimeCheckIP (Maybe Text) uciIPAddress = lens _uciIPAddress (\ s a -> s{_uciIPAddress = a}) -- | A more specific location within the region that typically encodes a -- particular city\/town\/metro (and its containing state\/province or -- country) within the broader umbrella region category. uciLocation :: Lens' UptimeCheckIP (Maybe Text) uciLocation = lens _uciLocation (\ s a -> s{_uciLocation = a}) -- | A broad region category in which the IP address is located. uciRegion :: Lens' UptimeCheckIP (Maybe UptimeCheckIPRegion) uciRegion = lens _uciRegion (\ s a -> s{_uciRegion = a}) instance FromJSON UptimeCheckIP where parseJSON = withObject "UptimeCheckIP" (\ o -> UptimeCheckIP' <$> (o .:? "ipAddress") <*> (o .:? "location") <*> (o .:? "region")) instance ToJSON UptimeCheckIP where toJSON UptimeCheckIP'{..} = object (catMaybes [("ipAddress" .=) <$> _uciIPAddress, ("location" .=) <$> _uciLocation, ("region" .=) <$> _uciRegion]) -- | Istio service scoped to a single Kubernetes cluster. Learn more at -- https:\/\/istio.io. Clusters running OSS Istio will have their services -- ingested as this type. -- -- /See:/ 'clusterIstio' smart constructor. data ClusterIstio = ClusterIstio' { _ciLocation :: !(Maybe Text) , _ciServiceNamespace :: !(Maybe Text) , _ciServiceName :: !(Maybe Text) , _ciClusterName :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ClusterIstio' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ciLocation' -- -- * 'ciServiceNamespace' -- -- * 'ciServiceName' -- -- * 'ciClusterName' clusterIstio :: ClusterIstio clusterIstio = ClusterIstio' { _ciLocation = Nothing , _ciServiceNamespace = Nothing , _ciServiceName = Nothing , _ciClusterName = Nothing } -- | The location of the Kubernetes cluster in which this Istio service is -- defined. Corresponds to the location resource label in k8s_cluster -- resources. ciLocation :: Lens' ClusterIstio (Maybe Text) ciLocation = lens _ciLocation (\ s a -> s{_ciLocation = a}) -- | The namespace of the Istio service underlying this service. Corresponds -- to the destination_service_namespace metric label in Istio metrics. ciServiceNamespace :: Lens' ClusterIstio (Maybe Text) ciServiceNamespace = lens _ciServiceNamespace (\ s a -> s{_ciServiceNamespace = a}) -- | The name of the Istio service underlying this service. Corresponds to -- the destination_service_name metric label in Istio metrics. ciServiceName :: Lens' ClusterIstio (Maybe Text) ciServiceName = lens _ciServiceName (\ s a -> s{_ciServiceName = a}) -- | The name of the Kubernetes cluster in which this Istio service is -- defined. Corresponds to the cluster_name resource label in k8s_cluster -- resources. ciClusterName :: Lens' ClusterIstio (Maybe Text) ciClusterName = lens _ciClusterName (\ s a -> s{_ciClusterName = a}) instance FromJSON ClusterIstio where parseJSON = withObject "ClusterIstio" (\ o -> ClusterIstio' <$> (o .:? "location") <*> (o .:? "serviceNamespace") <*> (o .:? "serviceName") <*> (o .:? "clusterName")) instance ToJSON ClusterIstio where toJSON ClusterIstio'{..} = object (catMaybes [("location" .=) <$> _ciLocation, ("serviceNamespace" .=) <$> _ciServiceNamespace, ("serviceName" .=) <$> _ciServiceName, ("clusterName" .=) <$> _ciClusterName]) -- | User-supplied key\/value data to be used for organizing and identifying -- the AlertPolicy objects.The field can contain up to 64 entries. Each key -- and value is limited to 63 Unicode characters or 128 bytes, whichever is -- smaller. Labels and values can contain only lowercase letters, numerals, -- underscores, and dashes. Keys must begin with a letter. -- -- /See:/ 'alertPolicyUserLabels' smart constructor. newtype AlertPolicyUserLabels = AlertPolicyUserLabels' { _apulAddtional :: HashMap Text Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'AlertPolicyUserLabels' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'apulAddtional' alertPolicyUserLabels :: HashMap Text Text -- ^ 'apulAddtional' -> AlertPolicyUserLabels alertPolicyUserLabels pApulAddtional_ = AlertPolicyUserLabels' {_apulAddtional = _Coerce # pApulAddtional_} apulAddtional :: Lens' AlertPolicyUserLabels (HashMap Text Text) apulAddtional = lens _apulAddtional (\ s a -> s{_apulAddtional = a}) . _Coerce instance FromJSON AlertPolicyUserLabels where parseJSON = withObject "AlertPolicyUserLabels" (\ o -> AlertPolicyUserLabels' <$> (parseJSONObject o)) instance ToJSON AlertPolicyUserLabels where toJSON = toJSON . _apulAddtional -- | A content string and a MIME type that describes the content string\'s -- format. -- -- /See:/ 'documentation' smart constructor. data Documentation = Documentation' { _dContent :: !(Maybe Text) , _dMimeType :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Documentation' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dContent' -- -- * 'dMimeType' documentation :: Documentation documentation = Documentation' {_dContent = Nothing, _dMimeType = Nothing} -- | The text of the documentation, interpreted according to mime_type. The -- content may not exceed 8,192 Unicode characters and may not exceed more -- than 10,240 bytes when encoded in UTF-8 format, whichever is smaller. dContent :: Lens' Documentation (Maybe Text) dContent = lens _dContent (\ s a -> s{_dContent = a}) -- | The format of the content field. Presently, only the value -- \"text\/markdown\" is supported. See Markdown -- (https:\/\/en.wikipedia.org\/wiki\/Markdown) for more information. dMimeType :: Lens' Documentation (Maybe Text) dMimeType = lens _dMimeType (\ s a -> s{_dMimeType = a}) instance FromJSON Documentation where parseJSON = withObject "Documentation" (\ o -> Documentation' <$> (o .:? "content") <*> (o .:? "mimeType")) instance ToJSON Documentation where toJSON Documentation'{..} = object (catMaybes [("content" .=) <$> _dContent, ("mimeType" .=) <$> _dMimeType]) -- | Optional. A map from a label key to an extractor expression, which is -- used to extract the value for this label key. Each entry in this map is -- a specification for how data should be extracted from log entries that -- match filter. Each combination of extracted values is treated as a -- separate rule for the purposes of triggering notifications. Label keys -- and corresponding values can be used in notifications generated by this -- condition.Please see the documentation on logs-based metric -- valueExtractors for syntax and examples. -- -- /See:/ 'logMatchLabelExtractors' smart constructor. newtype LogMatchLabelExtractors = LogMatchLabelExtractors' { _lmleAddtional :: HashMap Text Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'LogMatchLabelExtractors' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lmleAddtional' logMatchLabelExtractors :: HashMap Text Text -- ^ 'lmleAddtional' -> LogMatchLabelExtractors logMatchLabelExtractors pLmleAddtional_ = LogMatchLabelExtractors' {_lmleAddtional = _Coerce # pLmleAddtional_} lmleAddtional :: Lens' LogMatchLabelExtractors (HashMap Text Text) lmleAddtional = lens _lmleAddtional (\ s a -> s{_lmleAddtional = a}) . _Coerce instance FromJSON LogMatchLabelExtractors where parseJSON = withObject "LogMatchLabelExtractors" (\ o -> LogMatchLabelExtractors' <$> (parseJSONObject o)) instance ToJSON LogMatchLabelExtractors where toJSON = toJSON . _lmleAddtional -- | Future parameters for the availability SLI. -- -- /See:/ 'availabilityCriteria' smart constructor. data AvailabilityCriteria = AvailabilityCriteria' deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'AvailabilityCriteria' with the minimum fields required to make a request. -- availabilityCriteria :: AvailabilityCriteria availabilityCriteria = AvailabilityCriteria' instance FromJSON AvailabilityCriteria where parseJSON = withObject "AvailabilityCriteria" (\ o -> pure AvailabilityCriteria') instance ToJSON AvailabilityCriteria where toJSON = const emptyObject -- | Exemplars are example points that may be used to annotate aggregated -- distribution values. They are metadata that gives information about a -- particular value added to a Distribution bucket, such as a trace ID that -- was active when a value was added. They may contain further information, -- such as a example values and timestamps, origin, etc. -- -- /See:/ 'exemplar' smart constructor. data Exemplar = Exemplar' { _eAttachments :: !(Maybe [ExemplarAttachmentsItem]) , _eValue :: !(Maybe (Textual Double)) , _eTimestamp :: !(Maybe DateTime') } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Exemplar' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'eAttachments' -- -- * 'eValue' -- -- * 'eTimestamp' exemplar :: Exemplar exemplar = Exemplar' {_eAttachments = Nothing, _eValue = Nothing, _eTimestamp = Nothing} -- | Contextual information about the example value. Examples are:Trace: -- type.googleapis.com\/google.monitoring.v3.SpanContextLiteral string: -- type.googleapis.com\/google.protobuf.StringValueLabels dropped during -- aggregation: -- type.googleapis.com\/google.monitoring.v3.DroppedLabelsThere may be only -- a single attachment of any given message type in a single exemplar, and -- this is enforced by the system. eAttachments :: Lens' Exemplar [ExemplarAttachmentsItem] eAttachments = lens _eAttachments (\ s a -> s{_eAttachments = a}) . _Default . _Coerce -- | Value of the exemplar point. This value determines to which bucket the -- exemplar belongs. eValue :: Lens' Exemplar (Maybe Double) eValue = lens _eValue (\ s a -> s{_eValue = a}) . mapping _Coerce -- | The observation (sampling) time of the above value. eTimestamp :: Lens' Exemplar (Maybe UTCTime) eTimestamp = lens _eTimestamp (\ s a -> s{_eTimestamp = a}) . mapping _DateTime instance FromJSON Exemplar where parseJSON = withObject "Exemplar" (\ o -> Exemplar' <$> (o .:? "attachments" .!= mempty) <*> (o .:? "value") <*> (o .:? "timestamp")) instance ToJSON Exemplar where toJSON Exemplar'{..} = object (catMaybes [("attachments" .=) <$> _eAttachments, ("value" .=) <$> _eValue, ("timestamp" .=) <$> _eTimestamp]) -- | Control over the rate of notifications sent to this alert policy\'s -- notification channels. -- -- /See:/ 'notificationRateLimit' smart constructor. newtype NotificationRateLimit = NotificationRateLimit' { _nrlPeriod :: Maybe GDuration } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'NotificationRateLimit' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'nrlPeriod' notificationRateLimit :: NotificationRateLimit notificationRateLimit = NotificationRateLimit' {_nrlPeriod = Nothing} -- | Not more than one notification per period. nrlPeriod :: Lens' NotificationRateLimit (Maybe Scientific) nrlPeriod = lens _nrlPeriod (\ s a -> s{_nrlPeriod = a}) . mapping _GDuration instance FromJSON NotificationRateLimit where parseJSON = withObject "NotificationRateLimit" (\ o -> NotificationRateLimit' <$> (o .:? "period")) instance ToJSON NotificationRateLimit where toJSON NotificationRateLimit'{..} = object (catMaybes [("period" .=) <$> _nrlPeriod]) -- | Additional annotations that can be used to guide the usage of a metric. -- -- /See:/ 'metricDescriptorMetadata' smart constructor. data MetricDescriptorMetadata = MetricDescriptorMetadata' { _mdmSamplePeriod :: !(Maybe GDuration) , _mdmIngestDelay :: !(Maybe GDuration) , _mdmLaunchStage :: !(Maybe MetricDescriptorMetadataLaunchStage) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'MetricDescriptorMetadata' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'mdmSamplePeriod' -- -- * 'mdmIngestDelay' -- -- * 'mdmLaunchStage' metricDescriptorMetadata :: MetricDescriptorMetadata metricDescriptorMetadata = MetricDescriptorMetadata' { _mdmSamplePeriod = Nothing , _mdmIngestDelay = Nothing , _mdmLaunchStage = Nothing } -- | The sampling period of metric data points. For metrics which are written -- periodically, consecutive data points are stored at this time interval, -- excluding data loss due to errors. Metrics with a higher granularity -- have a smaller sampling period. mdmSamplePeriod :: Lens' MetricDescriptorMetadata (Maybe Scientific) mdmSamplePeriod = lens _mdmSamplePeriod (\ s a -> s{_mdmSamplePeriod = a}) . mapping _GDuration -- | The delay of data points caused by ingestion. Data points older than -- this age are guaranteed to be ingested and available to be read, -- excluding data loss due to errors. mdmIngestDelay :: Lens' MetricDescriptorMetadata (Maybe Scientific) mdmIngestDelay = lens _mdmIngestDelay (\ s a -> s{_mdmIngestDelay = a}) . mapping _GDuration -- | Deprecated. Must use the MetricDescriptor.launch_stage instead. mdmLaunchStage :: Lens' MetricDescriptorMetadata (Maybe MetricDescriptorMetadataLaunchStage) mdmLaunchStage = lens _mdmLaunchStage (\ s a -> s{_mdmLaunchStage = a}) instance FromJSON MetricDescriptorMetadata where parseJSON = withObject "MetricDescriptorMetadata" (\ o -> MetricDescriptorMetadata' <$> (o .:? "samplePeriod") <*> (o .:? "ingestDelay") <*> (o .:? "launchStage")) instance ToJSON MetricDescriptorMetadata where toJSON MetricDescriptorMetadata'{..} = object (catMaybes [("samplePeriod" .=) <$> _mdmSamplePeriod, ("ingestDelay" .=) <$> _mdmIngestDelay, ("launchStage" .=) <$> _mdmLaunchStage]) -- | A Service-Level Indicator (SLI) describes the \"performance\" of a -- service. For some services, the SLI is well-defined. In such cases, the -- SLI can be described easily by referencing the well-known SLI and -- providing the needed parameters. Alternatively, a \"custom\" SLI can be -- defined with a query to the underlying metric store. An SLI is defined -- to be good_service \/ total_service over any queried time interval. The -- value of performance always falls into the range 0 \<= performance \<= -- 1. A custom SLI describes how to compute this ratio, whether this is by -- dividing values from a pair of time series, cutting a Distribution into -- good and bad counts, or counting time windows in which the service -- complies with a criterion. For separation of concerns, a single -- Service-Level Indicator measures performance for only one aspect of -- service quality, such as fraction of successful queries or fast-enough -- queries. -- -- /See:/ 'serviceLevelIndicator' smart constructor. data ServiceLevelIndicator = ServiceLevelIndicator' { _sliBasicSli :: !(Maybe BasicSli) , _sliRequestBased :: !(Maybe RequestBasedSli) , _sliWindowsBased :: !(Maybe WindowsBasedSli) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ServiceLevelIndicator' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'sliBasicSli' -- -- * 'sliRequestBased' -- -- * 'sliWindowsBased' serviceLevelIndicator :: ServiceLevelIndicator serviceLevelIndicator = ServiceLevelIndicator' { _sliBasicSli = Nothing , _sliRequestBased = Nothing , _sliWindowsBased = Nothing } -- | Basic SLI on a well-known service type. sliBasicSli :: Lens' ServiceLevelIndicator (Maybe BasicSli) sliBasicSli = lens _sliBasicSli (\ s a -> s{_sliBasicSli = a}) -- | Request-based SLIs sliRequestBased :: Lens' ServiceLevelIndicator (Maybe RequestBasedSli) sliRequestBased = lens _sliRequestBased (\ s a -> s{_sliRequestBased = a}) -- | Windows-based SLIs sliWindowsBased :: Lens' ServiceLevelIndicator (Maybe WindowsBasedSli) sliWindowsBased = lens _sliWindowsBased (\ s a -> s{_sliWindowsBased = a}) instance FromJSON ServiceLevelIndicator where parseJSON = withObject "ServiceLevelIndicator" (\ o -> ServiceLevelIndicator' <$> (o .:? "basicSli") <*> (o .:? "requestBased") <*> (o .:? "windowsBased")) instance ToJSON ServiceLevelIndicator where toJSON ServiceLevelIndicator'{..} = object (catMaybes [("basicSli" .=) <$> _sliBasicSli, ("requestBased" .=) <$> _sliRequestBased, ("windowsBased" .=) <$> _sliWindowsBased]) -- | A closed time interval. It extends from the start time to the end time, -- and includes both: [startTime, endTime]. Valid time intervals depend on -- the MetricKind -- (https:\/\/cloud.google.com\/monitoring\/api\/ref_v3\/rest\/v3\/projects.metricDescriptors#MetricKind) -- of the metric value. The end time must not be earlier than the start -- time. When writing data points, the start time must not be more than 25 -- hours in the past and the end time must not be more than five minutes in -- the future. For GAUGE metrics, the startTime value is technically -- optional; if no value is specified, the start time defaults to the value -- of the end time, and the interval represents a single point in time. If -- both start and end times are specified, they must be identical. Such an -- interval is valid only for GAUGE metrics, which are point-in-time -- measurements. The end time of a new interval must be at least a -- millisecond after the end time of the previous interval. For DELTA -- metrics, the start time and end time must specify a non-zero interval, -- with subsequent points specifying contiguous and non-overlapping -- intervals. For DELTA metrics, the start time of the next interval must -- be at least a millisecond after the end time of the previous interval. -- For CUMULATIVE metrics, the start time and end time must specify a a -- non-zero interval, with subsequent points specifying the same start time -- and increasing end times, until an event resets the cumulative value to -- zero and sets a new start time for the following points. The new start -- time must be at least a millisecond after the end time of the previous -- interval. The start time of a new interval must be at least a -- millisecond after the end time of the previous interval because -- intervals are closed. If the start time of a new interval is the same as -- the end time of the previous interval, then data written at the new -- start time could overwrite data written at the previous end time. -- -- /See:/ 'timeInterval' smart constructor. data TimeInterval = TimeInterval' { _tiStartTime :: !(Maybe DateTime') , _tiEndTime :: !(Maybe DateTime') } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'TimeInterval' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'tiStartTime' -- -- * 'tiEndTime' timeInterval :: TimeInterval timeInterval = TimeInterval' {_tiStartTime = Nothing, _tiEndTime = Nothing} -- | Optional. The beginning of the time interval. The default value for the -- start time is the end time. The start time must not be later than the -- end time. tiStartTime :: Lens' TimeInterval (Maybe UTCTime) tiStartTime = lens _tiStartTime (\ s a -> s{_tiStartTime = a}) . mapping _DateTime -- | Required. The end of the time interval. tiEndTime :: Lens' TimeInterval (Maybe UTCTime) tiEndTime = lens _tiEndTime (\ s a -> s{_tiEndTime = a}) . mapping _DateTime instance FromJSON TimeInterval where parseJSON = withObject "TimeInterval" (\ o -> TimeInterval' <$> (o .:? "startTime") <*> (o .:? "endTime")) instance ToJSON TimeInterval where toJSON TimeInterval'{..} = object (catMaybes [("startTime" .=) <$> _tiStartTime, ("endTime" .=) <$> _tiEndTime]) -- | The list of headers to send as part of the Uptime check request. If two -- headers have the same key and different values, they should be entered -- as a single header, with the value being a comma-separated list of all -- the desired values as described at -- https:\/\/www.w3.org\/Protocols\/rfc2616\/rfc2616.txt (page 31). -- Entering two separate headers with the same key in a Create call will -- cause the first to be overwritten by the second. The maximum number of -- headers allowed is 100. -- -- /See:/ 'hTTPCheckHeaders' smart constructor. newtype HTTPCheckHeaders = HTTPCheckHeaders' { _httpchAddtional :: HashMap Text Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'HTTPCheckHeaders' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'httpchAddtional' hTTPCheckHeaders :: HashMap Text Text -- ^ 'httpchAddtional' -> HTTPCheckHeaders hTTPCheckHeaders pHttpchAddtional_ = HTTPCheckHeaders' {_httpchAddtional = _Coerce # pHttpchAddtional_} httpchAddtional :: Lens' HTTPCheckHeaders (HashMap Text Text) httpchAddtional = lens _httpchAddtional (\ s a -> s{_httpchAddtional = a}) . _Coerce instance FromJSON HTTPCheckHeaders where parseJSON = withObject "HTTPCheckHeaders" (\ o -> HTTPCheckHeaders' <$> (parseJSONObject o)) instance ToJSON HTTPCheckHeaders where toJSON = toJSON . _httpchAddtional -- | Output only. Values for predefined system metadata labels. System labels -- are a kind of metadata extracted by Google, including \"machine_image\", -- \"vpc\", \"subnet_id\", \"security_group\", \"name\", etc. System label -- values can be only strings, Boolean values, or a list of strings. For -- example: { \"name\": \"my-test-instance\", \"security_group\": [\"a\", -- \"b\", \"c\"], \"spot_instance\": false } -- -- /See:/ 'monitoredResourceMetadataSystemLabels' smart constructor. newtype MonitoredResourceMetadataSystemLabels = MonitoredResourceMetadataSystemLabels' { _mrmslAddtional :: HashMap Text JSONValue } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'MonitoredResourceMetadataSystemLabels' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'mrmslAddtional' monitoredResourceMetadataSystemLabels :: HashMap Text JSONValue -- ^ 'mrmslAddtional' -> MonitoredResourceMetadataSystemLabels monitoredResourceMetadataSystemLabels pMrmslAddtional_ = MonitoredResourceMetadataSystemLabels' {_mrmslAddtional = _Coerce # pMrmslAddtional_} -- | Properties of the object. mrmslAddtional :: Lens' MonitoredResourceMetadataSystemLabels (HashMap Text JSONValue) mrmslAddtional = lens _mrmslAddtional (\ s a -> s{_mrmslAddtional = a}) . _Coerce instance FromJSON MonitoredResourceMetadataSystemLabels where parseJSON = withObject "MonitoredResourceMetadataSystemLabels" (\ o -> MonitoredResourceMetadataSystemLabels' <$> (parseJSONObject o)) instance ToJSON MonitoredResourceMetadataSystemLabels where toJSON = toJSON . _mrmslAddtional -- | Optional. Used to perform content matching. This allows matching based -- on substrings and regular expressions, together with their negations. -- Only the first 4 MB of an HTTP or HTTPS check\'s response (and the first -- 1 MB of a TCP check\'s response) are examined for purposes of content -- matching. -- -- /See:/ 'contentMatcher' smart constructor. data ContentMatcher = ContentMatcher' { _cmMatcher :: !(Maybe ContentMatcherMatcher) , _cmContent :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ContentMatcher' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'cmMatcher' -- -- * 'cmContent' contentMatcher :: ContentMatcher contentMatcher = ContentMatcher' {_cmMatcher = Nothing, _cmContent = Nothing} -- | The type of content matcher that will be applied to the server output, -- compared to the content string when the check is run. cmMatcher :: Lens' ContentMatcher (Maybe ContentMatcherMatcher) cmMatcher = lens _cmMatcher (\ s a -> s{_cmMatcher = a}) -- | String or regex content to match. Maximum 1024 bytes. An empty content -- string indicates no content matching is to be performed. cmContent :: Lens' ContentMatcher (Maybe Text) cmContent = lens _cmContent (\ s a -> s{_cmContent = a}) instance FromJSON ContentMatcher where parseJSON = withObject "ContentMatcher" (\ o -> ContentMatcher' <$> (o .:? "matcher") <*> (o .:? "content")) instance ToJSON ContentMatcher where toJSON ContentMatcher'{..} = object (catMaybes [("matcher" .=) <$> _cmMatcher, ("content" .=) <$> _cmContent]) -- | The ListGroupMembers response. -- -- /See:/ 'listGroupMembersResponse' smart constructor. data ListGroupMembersResponse = ListGroupMembersResponse' { _lgmrNextPageToken :: !(Maybe Text) , _lgmrMembers :: !(Maybe [MonitoredResource]) , _lgmrTotalSize :: !(Maybe (Textual Int32)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ListGroupMembersResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lgmrNextPageToken' -- -- * 'lgmrMembers' -- -- * 'lgmrTotalSize' listGroupMembersResponse :: ListGroupMembersResponse listGroupMembersResponse = ListGroupMembersResponse' { _lgmrNextPageToken = Nothing , _lgmrMembers = Nothing , _lgmrTotalSize = Nothing } -- | If there are more results than have been returned, then this field is -- set to a non-empty value. To see the additional results, use that value -- as page_token in the next call to this method. lgmrNextPageToken :: Lens' ListGroupMembersResponse (Maybe Text) lgmrNextPageToken = lens _lgmrNextPageToken (\ s a -> s{_lgmrNextPageToken = a}) -- | A set of monitored resources in the group. lgmrMembers :: Lens' ListGroupMembersResponse [MonitoredResource] lgmrMembers = lens _lgmrMembers (\ s a -> s{_lgmrMembers = a}) . _Default . _Coerce -- | The total number of elements matching this request. lgmrTotalSize :: Lens' ListGroupMembersResponse (Maybe Int32) lgmrTotalSize = lens _lgmrTotalSize (\ s a -> s{_lgmrTotalSize = a}) . mapping _Coerce instance FromJSON ListGroupMembersResponse where parseJSON = withObject "ListGroupMembersResponse" (\ o -> ListGroupMembersResponse' <$> (o .:? "nextPageToken") <*> (o .:? "members" .!= mempty) <*> (o .:? "totalSize")) instance ToJSON ListGroupMembersResponse where toJSON ListGroupMembersResponse'{..} = object (catMaybes [("nextPageToken" .=) <$> _lgmrNextPageToken, ("members" .=) <$> _lgmrMembers, ("totalSize" .=) <$> _lgmrTotalSize]) -- | Control over how the notification channels in notification_channels are -- notified when this alert fires. -- -- /See:/ 'alertStrategy' smart constructor. newtype AlertStrategy = AlertStrategy' { _asNotificationRateLimit :: Maybe NotificationRateLimit } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'AlertStrategy' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'asNotificationRateLimit' alertStrategy :: AlertStrategy alertStrategy = AlertStrategy' {_asNotificationRateLimit = Nothing} -- | Required for alert policies with a LogMatch condition.This limit is not -- implemented for alert policies that are not log-based. asNotificationRateLimit :: Lens' AlertStrategy (Maybe NotificationRateLimit) asNotificationRateLimit = lens _asNotificationRateLimit (\ s a -> s{_asNotificationRateLimit = a}) instance FromJSON AlertStrategy where parseJSON = withObject "AlertStrategy" (\ o -> AlertStrategy' <$> (o .:? "notificationRateLimit")) instance ToJSON AlertStrategy where toJSON AlertStrategy'{..} = object (catMaybes [("notificationRateLimit" .=) <$> _asNotificationRateLimit]) -- | A description of a label. -- -- /See:/ 'labelDescriptor' smart constructor. data LabelDescriptor = LabelDescriptor' { _ldKey :: !(Maybe Text) , _ldValueType :: !(Maybe LabelDescriptorValueType) , _ldDescription :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'LabelDescriptor' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ldKey' -- -- * 'ldValueType' -- -- * 'ldDescription' labelDescriptor :: LabelDescriptor labelDescriptor = LabelDescriptor' {_ldKey = Nothing, _ldValueType = Nothing, _ldDescription = Nothing} -- | The key for this label. The key must meet the following criteria: Does -- not exceed 100 characters. Matches the following regular expression: -- [a-zA-Z][a-zA-Z0-9_]* The first character must be an upper- or -- lower-case letter. The remaining characters must be letters, digits, or -- underscores. ldKey :: Lens' LabelDescriptor (Maybe Text) ldKey = lens _ldKey (\ s a -> s{_ldKey = a}) -- | The type of data that can be assigned to the label. ldValueType :: Lens' LabelDescriptor (Maybe LabelDescriptorValueType) ldValueType = lens _ldValueType (\ s a -> s{_ldValueType = a}) -- | A human-readable description for the label. ldDescription :: Lens' LabelDescriptor (Maybe Text) ldDescription = lens _ldDescription (\ s a -> s{_ldDescription = a}) instance FromJSON LabelDescriptor where parseJSON = withObject "LabelDescriptor" (\ o -> LabelDescriptor' <$> (o .:? "key") <*> (o .:? "valueType") <*> (o .:? "description")) instance ToJSON LabelDescriptor where toJSON LabelDescriptor'{..} = object (catMaybes [("key" .=) <$> _ldKey, ("valueType" .=) <$> _ldValueType, ("description" .=) <$> _ldDescription]) -- | Specifies a linear sequence of buckets that all have the same width -- (except overflow and underflow). Each bucket represents a constant -- absolute uncertainty on the specific value in the bucket.There are -- num_finite_buckets + 2 (= N) buckets. Bucket i has the following -- boundaries:Upper bound (0 \<= i \< N-1): offset + (width * i). Lower -- bound (1 \<= i \< N): offset + (width * (i - 1)). -- -- /See:/ 'linear' smart constructor. data Linear = Linear' { _lOffSet :: !(Maybe (Textual Double)) , _lWidth :: !(Maybe (Textual Double)) , _lNumFiniteBuckets :: !(Maybe (Textual Int32)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Linear' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lOffSet' -- -- * 'lWidth' -- -- * 'lNumFiniteBuckets' linear :: Linear linear = Linear' {_lOffSet = Nothing, _lWidth = Nothing, _lNumFiniteBuckets = Nothing} -- | Lower bound of the first bucket. lOffSet :: Lens' Linear (Maybe Double) lOffSet = lens _lOffSet (\ s a -> s{_lOffSet = a}) . mapping _Coerce -- | Must be greater than 0. lWidth :: Lens' Linear (Maybe Double) lWidth = lens _lWidth (\ s a -> s{_lWidth = a}) . mapping _Coerce -- | Must be greater than 0. lNumFiniteBuckets :: Lens' Linear (Maybe Int32) lNumFiniteBuckets = lens _lNumFiniteBuckets (\ s a -> s{_lNumFiniteBuckets = a}) . mapping _Coerce instance FromJSON Linear where parseJSON = withObject "Linear" (\ o -> Linear' <$> (o .:? "offset") <*> (o .:? "width") <*> (o .:? "numFiniteBuckets")) instance ToJSON Linear where toJSON Linear'{..} = object (catMaybes [("offset" .=) <$> _lOffSet, ("width" .=) <$> _lWidth, ("numFiniteBuckets" .=) <$> _lNumFiniteBuckets]) -- | The protocol for the ListUptimeCheckIps response. -- -- /See:/ 'listUptimeCheckIPsResponse' smart constructor. data ListUptimeCheckIPsResponse = ListUptimeCheckIPsResponse' { _lucirNextPageToken :: !(Maybe Text) , _lucirUptimeCheckIPs :: !(Maybe [UptimeCheckIP]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ListUptimeCheckIPsResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lucirNextPageToken' -- -- * 'lucirUptimeCheckIPs' listUptimeCheckIPsResponse :: ListUptimeCheckIPsResponse listUptimeCheckIPsResponse = ListUptimeCheckIPsResponse' {_lucirNextPageToken = Nothing, _lucirUptimeCheckIPs = Nothing} -- | This field represents the pagination token to retrieve the next page of -- results. If the value is empty, it means no further results for the -- request. To retrieve the next page of results, the value of the -- next_page_token is passed to the subsequent List method call (in the -- request message\'s page_token field). NOTE: this field is not yet -- implemented lucirNextPageToken :: Lens' ListUptimeCheckIPsResponse (Maybe Text) lucirNextPageToken = lens _lucirNextPageToken (\ s a -> s{_lucirNextPageToken = a}) -- | The returned list of IP addresses (including region and location) that -- the checkers run from. lucirUptimeCheckIPs :: Lens' ListUptimeCheckIPsResponse [UptimeCheckIP] lucirUptimeCheckIPs = lens _lucirUptimeCheckIPs (\ s a -> s{_lucirUptimeCheckIPs = a}) . _Default . _Coerce instance FromJSON ListUptimeCheckIPsResponse where parseJSON = withObject "ListUptimeCheckIPsResponse" (\ o -> ListUptimeCheckIPsResponse' <$> (o .:? "nextPageToken") <*> (o .:? "uptimeCheckIps" .!= mempty)) instance ToJSON ListUptimeCheckIPsResponse where toJSON ListUptimeCheckIPsResponse'{..} = object (catMaybes [("nextPageToken" .=) <$> _lucirNextPageToken, ("uptimeCheckIps" .=) <$> _lucirUptimeCheckIPs]) -- | The GetNotificationChannelVerificationCode request. -- -- /See:/ 'getNotificationChannelVerificationCodeRequest' smart constructor. newtype GetNotificationChannelVerificationCodeRequest = GetNotificationChannelVerificationCodeRequest' { _gExpireTime :: Maybe DateTime' } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'GetNotificationChannelVerificationCodeRequest' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'gExpireTime' getNotificationChannelVerificationCodeRequest :: GetNotificationChannelVerificationCodeRequest getNotificationChannelVerificationCodeRequest = GetNotificationChannelVerificationCodeRequest' {_gExpireTime = Nothing} -- | The desired expiration time. If specified, the API will guarantee that -- the returned code will not be valid after the specified timestamp; -- however, the API cannot guarantee that the returned code will be valid -- for at least as long as the requested time (the API puts an upper bound -- on the amount of time for which a code may be valid). If omitted, a -- default expiration will be used, which may be less than the max -- permissible expiration (so specifying an expiration may extend the -- code\'s lifetime over omitting an expiration, even though the API does -- impose an upper limit on the maximum expiration that is permitted). gExpireTime :: Lens' GetNotificationChannelVerificationCodeRequest (Maybe UTCTime) gExpireTime = lens _gExpireTime (\ s a -> s{_gExpireTime = a}) . mapping _DateTime instance FromJSON GetNotificationChannelVerificationCodeRequest where parseJSON = withObject "GetNotificationChannelVerificationCodeRequest" (\ o -> GetNotificationChannelVerificationCodeRequest' <$> (o .:? "expireTime")) instance ToJSON GetNotificationChannelVerificationCodeRequest where toJSON GetNotificationChannelVerificationCodeRequest'{..} = object (catMaybes [("expireTime" .=) <$> _gExpireTime]) -- | The resource submessage for group checks. It can be used instead of a -- monitored resource, when multiple resources are being monitored. -- -- /See:/ 'resourceGroup' smart constructor. data ResourceGroup = ResourceGroup' { _rgResourceType :: !(Maybe ResourceGroupResourceType) , _rgGroupId :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ResourceGroup' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'rgResourceType' -- -- * 'rgGroupId' resourceGroup :: ResourceGroup resourceGroup = ResourceGroup' {_rgResourceType = Nothing, _rgGroupId = Nothing} -- | The resource type of the group members. rgResourceType :: Lens' ResourceGroup (Maybe ResourceGroupResourceType) rgResourceType = lens _rgResourceType (\ s a -> s{_rgResourceType = a}) -- | The group of resources being monitored. Should be only the [GROUP_ID], -- and not the full-path -- projects\/[PROJECT_ID_OR_NUMBER]\/groups\/[GROUP_ID]. rgGroupId :: Lens' ResourceGroup (Maybe Text) rgGroupId = lens _rgGroupId (\ s a -> s{_rgGroupId = a}) instance FromJSON ResourceGroup where parseJSON = withObject "ResourceGroup" (\ o -> ResourceGroup' <$> (o .:? "resourceType") <*> (o .:? "groupId")) instance ToJSON ResourceGroup where toJSON ResourceGroup'{..} = object (catMaybes [("resourceType" .=) <$> _rgResourceType, ("groupId" .=) <$> _rgGroupId]) -- | A set of (label, value) pairs that were removed from a Distribution time -- series during aggregation and then added as an attachment to a -- Distribution.Exemplar.The full label set for the exemplars is -- constructed by using the dropped pairs in combination with the label -- values that remain on the aggregated Distribution time series. The -- constructed full label set can be used to identify the specific entity, -- such as the instance or job, which might be contributing to a long-tail. -- However, with dropped labels, the storage requirements are reduced -- because only the aggregated distribution values for a large group of -- time series are stored.Note that there are no guarantees on ordering of -- the labels from exemplar-to-exemplar and from -- distribution-to-distribution in the same stream, and there may be -- duplicates. It is up to clients to resolve any ambiguities. -- -- /See:/ 'droppedLabels' smart constructor. newtype DroppedLabels = DroppedLabels' { _dlLabel :: Maybe DroppedLabelsLabel } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'DroppedLabels' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dlLabel' droppedLabels :: DroppedLabels droppedLabels = DroppedLabels' {_dlLabel = Nothing} -- | Map from label to its value, for all labels dropped in any aggregation. dlLabel :: Lens' DroppedLabels (Maybe DroppedLabelsLabel) dlLabel = lens _dlLabel (\ s a -> s{_dlLabel = a}) instance FromJSON DroppedLabels where parseJSON = withObject "DroppedLabels" (\ o -> DroppedLabels' <$> (o .:? "label")) instance ToJSON DroppedLabels where toJSON DroppedLabels'{..} = object (catMaybes [("label" .=) <$> _dlLabel]) -- | A descriptor for the labels and points in a time series. -- -- /See:/ 'timeSeriesDescriptor' smart constructor. data TimeSeriesDescriptor = TimeSeriesDescriptor' { _tsdPointDescriptors :: !(Maybe [ValueDescriptor]) , _tsdLabelDescriptors :: !(Maybe [LabelDescriptor]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'TimeSeriesDescriptor' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'tsdPointDescriptors' -- -- * 'tsdLabelDescriptors' timeSeriesDescriptor :: TimeSeriesDescriptor timeSeriesDescriptor = TimeSeriesDescriptor' {_tsdPointDescriptors = Nothing, _tsdLabelDescriptors = Nothing} -- | Descriptors for the point data value columns. tsdPointDescriptors :: Lens' TimeSeriesDescriptor [ValueDescriptor] tsdPointDescriptors = lens _tsdPointDescriptors (\ s a -> s{_tsdPointDescriptors = a}) . _Default . _Coerce -- | Descriptors for the labels. tsdLabelDescriptors :: Lens' TimeSeriesDescriptor [LabelDescriptor] tsdLabelDescriptors = lens _tsdLabelDescriptors (\ s a -> s{_tsdLabelDescriptors = a}) . _Default . _Coerce instance FromJSON TimeSeriesDescriptor where parseJSON = withObject "TimeSeriesDescriptor" (\ o -> TimeSeriesDescriptor' <$> (o .:? "pointDescriptors" .!= mempty) <*> (o .:? "labelDescriptors" .!= mempty)) instance ToJSON TimeSeriesDescriptor where toJSON TimeSeriesDescriptor'{..} = object (catMaybes [("pointDescriptors" .=) <$> _tsdPointDescriptors, ("labelDescriptors" .=) <$> _tsdLabelDescriptors]) -- | Specifies how many time series must fail a predicate to trigger a -- condition. If not specified, then a {count: 1} trigger is used. -- -- /See:/ 'trigger' smart constructor. data Trigger = Trigger' { _tPercent :: !(Maybe (Textual Double)) , _tCount :: !(Maybe (Textual Int32)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Trigger' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'tPercent' -- -- * 'tCount' trigger :: Trigger trigger = Trigger' {_tPercent = Nothing, _tCount = Nothing} -- | The percentage of time series that must fail the predicate for the -- condition to be triggered. tPercent :: Lens' Trigger (Maybe Double) tPercent = lens _tPercent (\ s a -> s{_tPercent = a}) . mapping _Coerce -- | The absolute number of time series that must fail the predicate for the -- condition to be triggered. tCount :: Lens' Trigger (Maybe Int32) tCount = lens _tCount (\ s a -> s{_tCount = a}) . mapping _Coerce instance FromJSON Trigger where parseJSON = withObject "Trigger" (\ o -> Trigger' <$> (o .:? "percent") <*> (o .:? "count")) instance ToJSON Trigger where toJSON Trigger'{..} = object (catMaybes [("percent" .=) <$> _tPercent, ("count" .=) <$> _tCount]) -- | Labels which have been used to annotate the service-level objective. -- Label keys must start with a letter. Label keys and values may contain -- lowercase letters, numbers, underscores, and dashes. Label keys and -- values have a maximum length of 63 characters, and must be less than 128 -- bytes in size. Up to 64 label entries may be stored. For labels which do -- not have a semantic value, the empty string may be supplied for the -- label value. -- -- /See:/ 'serviceLevelObjectiveUserLabels' smart constructor. newtype ServiceLevelObjectiveUserLabels = ServiceLevelObjectiveUserLabels' { _sloulAddtional :: HashMap Text Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ServiceLevelObjectiveUserLabels' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'sloulAddtional' serviceLevelObjectiveUserLabels :: HashMap Text Text -- ^ 'sloulAddtional' -> ServiceLevelObjectiveUserLabels serviceLevelObjectiveUserLabels pSloulAddtional_ = ServiceLevelObjectiveUserLabels' {_sloulAddtional = _Coerce # pSloulAddtional_} sloulAddtional :: Lens' ServiceLevelObjectiveUserLabels (HashMap Text Text) sloulAddtional = lens _sloulAddtional (\ s a -> s{_sloulAddtional = a}) . _Coerce instance FromJSON ServiceLevelObjectiveUserLabels where parseJSON = withObject "ServiceLevelObjectiveUserLabels" (\ o -> ServiceLevelObjectiveUserLabels' <$> (parseJSONObject o)) instance ToJSON ServiceLevelObjectiveUserLabels where toJSON = toJSON . _sloulAddtional -- | A descriptor for the value columns in a data point. -- -- /See:/ 'valueDescriptor' smart constructor. data ValueDescriptor = ValueDescriptor' { _vdMetricKind :: !(Maybe ValueDescriptorMetricKind) , _vdKey :: !(Maybe Text) , _vdValueType :: !(Maybe ValueDescriptorValueType) , _vdUnit :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ValueDescriptor' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'vdMetricKind' -- -- * 'vdKey' -- -- * 'vdValueType' -- -- * 'vdUnit' valueDescriptor :: ValueDescriptor valueDescriptor = ValueDescriptor' { _vdMetricKind = Nothing , _vdKey = Nothing , _vdValueType = Nothing , _vdUnit = Nothing } -- | The value stream kind. vdMetricKind :: Lens' ValueDescriptor (Maybe ValueDescriptorMetricKind) vdMetricKind = lens _vdMetricKind (\ s a -> s{_vdMetricKind = a}) -- | The value key. vdKey :: Lens' ValueDescriptor (Maybe Text) vdKey = lens _vdKey (\ s a -> s{_vdKey = a}) -- | The value type. vdValueType :: Lens' ValueDescriptor (Maybe ValueDescriptorValueType) vdValueType = lens _vdValueType (\ s a -> s{_vdValueType = a}) -- | The unit in which time_series point values are reported. unit follows -- the UCUM format for units as seen in -- https:\/\/unitsofmeasure.org\/ucum.html. unit is only valid if -- value_type is INTEGER, DOUBLE, DISTRIBUTION. vdUnit :: Lens' ValueDescriptor (Maybe Text) vdUnit = lens _vdUnit (\ s a -> s{_vdUnit = a}) instance FromJSON ValueDescriptor where parseJSON = withObject "ValueDescriptor" (\ o -> ValueDescriptor' <$> (o .:? "metricKind") <*> (o .:? "key") <*> (o .:? "valueType") <*> (o .:? "unit")) instance ToJSON ValueDescriptor where toJSON ValueDescriptor'{..} = object (catMaybes [("metricKind" .=) <$> _vdMetricKind, ("key" .=) <$> _vdKey, ("valueType" .=) <$> _vdValueType, ("unit" .=) <$> _vdUnit]) -- | A protocol buffer message type. -- -- /See:/ 'type'' smart constructor. data Type = Type' { _tSourceContext :: !(Maybe SourceContext) , _tOneofs :: !(Maybe [Text]) , _tName :: !(Maybe Text) , _tOptions :: !(Maybe [Option]) , _tFields :: !(Maybe [Field]) , _tSyntax :: !(Maybe TypeSyntax) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Type' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'tSourceContext' -- -- * 'tOneofs' -- -- * 'tName' -- -- * 'tOptions' -- -- * 'tFields' -- -- * 'tSyntax' type' :: Type type' = Type' { _tSourceContext = Nothing , _tOneofs = Nothing , _tName = Nothing , _tOptions = Nothing , _tFields = Nothing , _tSyntax = Nothing } -- | The source context. tSourceContext :: Lens' Type (Maybe SourceContext) tSourceContext = lens _tSourceContext (\ s a -> s{_tSourceContext = a}) -- | The list of types appearing in oneof definitions in this type. tOneofs :: Lens' Type [Text] tOneofs = lens _tOneofs (\ s a -> s{_tOneofs = a}) . _Default . _Coerce -- | The fully qualified message name. tName :: Lens' Type (Maybe Text) tName = lens _tName (\ s a -> s{_tName = a}) -- | The protocol buffer options. tOptions :: Lens' Type [Option] tOptions = lens _tOptions (\ s a -> s{_tOptions = a}) . _Default . _Coerce -- | The list of fields. tFields :: Lens' Type [Field] tFields = lens _tFields (\ s a -> s{_tFields = a}) . _Default . _Coerce -- | The source syntax. tSyntax :: Lens' Type (Maybe TypeSyntax) tSyntax = lens _tSyntax (\ s a -> s{_tSyntax = a}) instance FromJSON Type where parseJSON = withObject "Type" (\ o -> Type' <$> (o .:? "sourceContext") <*> (o .:? "oneofs" .!= mempty) <*> (o .:? "name") <*> (o .:? "options" .!= mempty) <*> (o .:? "fields" .!= mempty) <*> (o .:? "syntax")) instance ToJSON Type where toJSON Type'{..} = object (catMaybes [("sourceContext" .=) <$> _tSourceContext, ("oneofs" .=) <$> _tOneofs, ("name" .=) <$> _tName, ("options" .=) <$> _tOptions, ("fields" .=) <$> _tFields, ("syntax" .=) <$> _tSyntax]) -- | Contains metadata for longrunning operation for the edit Metrics Scope -- endpoints. -- -- /See:/ 'operationMetadata' smart constructor. data OperationMetadata = OperationMetadata' { _omState :: !(Maybe OperationMetadataState) , _omUpdateTime :: !(Maybe DateTime') , _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: -- -- * 'omState' -- -- * 'omUpdateTime' -- -- * 'omCreateTime' operationMetadata :: OperationMetadata operationMetadata = OperationMetadata' {_omState = Nothing, _omUpdateTime = Nothing, _omCreateTime = Nothing} -- | Current state of the batch operation. omState :: Lens' OperationMetadata (Maybe OperationMetadataState) omState = lens _omState (\ s a -> s{_omState = a}) -- | The time when the operation result was last updated. omUpdateTime :: Lens' OperationMetadata (Maybe UTCTime) omUpdateTime = lens _omUpdateTime (\ s a -> s{_omUpdateTime = a}) . mapping _DateTime -- | The time when the batch request was received. 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 .:? "state") <*> (o .:? "updateTime") <*> (o .:? "createTime")) instance ToJSON OperationMetadata where toJSON OperationMetadata'{..} = object (catMaybes [("state" .=) <$> _omState, ("updateTime" .=) <$> _omUpdateTime, ("createTime" .=) <$> _omCreateTime]) -- | The CreateCollectdTimeSeries response. -- -- /See:/ 'createCollectdTimeSeriesResponse' smart constructor. data CreateCollectdTimeSeriesResponse = CreateCollectdTimeSeriesResponse' { _cctsrSummary :: !(Maybe CreateTimeSeriesSummary) , _cctsrPayloadErrors :: !(Maybe [CollectdPayloadError]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'CreateCollectdTimeSeriesResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'cctsrSummary' -- -- * 'cctsrPayloadErrors' createCollectdTimeSeriesResponse :: CreateCollectdTimeSeriesResponse createCollectdTimeSeriesResponse = CreateCollectdTimeSeriesResponse' {_cctsrSummary = Nothing, _cctsrPayloadErrors = Nothing} -- | Aggregate statistics from writing the payloads. This field is omitted if -- all points were successfully written, so that the response is empty. -- This is for backwards compatibility with clients that log errors on any -- non-empty response. cctsrSummary :: Lens' CreateCollectdTimeSeriesResponse (Maybe CreateTimeSeriesSummary) cctsrSummary = lens _cctsrSummary (\ s a -> s{_cctsrSummary = a}) -- | Records the error status for points that were not written due to an -- error in the request.Failed requests for which nothing is written will -- return an error response instead. Requests where data points were -- rejected by the backend will set summary instead. cctsrPayloadErrors :: Lens' CreateCollectdTimeSeriesResponse [CollectdPayloadError] cctsrPayloadErrors = lens _cctsrPayloadErrors (\ s a -> s{_cctsrPayloadErrors = a}) . _Default . _Coerce instance FromJSON CreateCollectdTimeSeriesResponse where parseJSON = withObject "CreateCollectdTimeSeriesResponse" (\ o -> CreateCollectdTimeSeriesResponse' <$> (o .:? "summary") <*> (o .:? "payloadErrors" .!= mempty)) instance ToJSON CreateCollectdTimeSeriesResponse where toJSON CreateCollectdTimeSeriesResponse'{..} = object (catMaybes [("summary" .=) <$> _cctsrSummary, ("payloadErrors" .=) <$> _cctsrPayloadErrors]) -- | Parameters for a latency threshold SLI. -- -- /See:/ 'latencyCriteria' smart constructor. newtype LatencyCriteria = LatencyCriteria' { _lcThreshold :: Maybe GDuration } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'LatencyCriteria' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lcThreshold' latencyCriteria :: LatencyCriteria latencyCriteria = LatencyCriteria' {_lcThreshold = Nothing} -- | Good service is defined to be the count of requests made to this service -- that return in no more than threshold. lcThreshold :: Lens' LatencyCriteria (Maybe Scientific) lcThreshold = lens _lcThreshold (\ s a -> s{_lcThreshold = a}) . mapping _GDuration instance FromJSON LatencyCriteria where parseJSON = withObject "LatencyCriteria" (\ o -> LatencyCriteria' <$> (o .:? "threshold")) instance ToJSON LatencyCriteria where toJSON LatencyCriteria'{..} = object (catMaybes [("threshold" .=) <$> _lcThreshold]) -- | Istio service scoped to an Istio mesh. Anthos clusters running ASM \< -- 1.6.8 will have their services ingested as this type. -- -- /See:/ 'meshIstio' smart constructor. data MeshIstio = MeshIstio' { _miMeshUid :: !(Maybe Text) , _miServiceNamespace :: !(Maybe Text) , _miServiceName :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'MeshIstio' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'miMeshUid' -- -- * 'miServiceNamespace' -- -- * 'miServiceName' meshIstio :: MeshIstio meshIstio = MeshIstio' { _miMeshUid = Nothing , _miServiceNamespace = Nothing , _miServiceName = Nothing } -- | Identifier for the mesh in which this Istio service is defined. -- Corresponds to the mesh_uid metric label in Istio metrics. miMeshUid :: Lens' MeshIstio (Maybe Text) miMeshUid = lens _miMeshUid (\ s a -> s{_miMeshUid = a}) -- | The namespace of the Istio service underlying this service. Corresponds -- to the destination_service_namespace metric label in Istio metrics. miServiceNamespace :: Lens' MeshIstio (Maybe Text) miServiceNamespace = lens _miServiceNamespace (\ s a -> s{_miServiceNamespace = a}) -- | The name of the Istio service underlying this service. Corresponds to -- the destination_service_name metric label in Istio metrics. miServiceName :: Lens' MeshIstio (Maybe Text) miServiceName = lens _miServiceName (\ s a -> s{_miServiceName = a}) instance FromJSON MeshIstio where parseJSON = withObject "MeshIstio" (\ o -> MeshIstio' <$> (o .:? "meshUid") <*> (o .:? "serviceNamespace") <*> (o .:? "serviceName")) instance ToJSON MeshIstio where toJSON MeshIstio'{..} = object (catMaybes [("meshUid" .=) <$> _miMeshUid, ("serviceNamespace" .=) <$> _miServiceNamespace, ("serviceName" .=) <$> _miServiceName]) -- | A protocol buffer option, which can be attached to a message, field, -- enumeration, etc. -- -- /See:/ 'option' smart constructor. data Option = Option' { _oValue :: !(Maybe OptionValue) , _oName :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Option' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'oValue' -- -- * 'oName' option :: Option option = Option' {_oValue = Nothing, _oName = Nothing} -- | The option\'s value packed in an Any message. If the value is a -- primitive, the corresponding wrapper type defined in -- google\/protobuf\/wrappers.proto should be used. If the value is an -- enum, it should be stored as an int32 value using the -- google.protobuf.Int32Value type. oValue :: Lens' Option (Maybe OptionValue) oValue = lens _oValue (\ s a -> s{_oValue = a}) -- | The option\'s name. For protobuf built-in options (options defined in -- descriptor.proto), this is the short name. For example, \"map_entry\". -- For custom options, it should be the fully-qualified name. For example, -- \"google.api.http\". oName :: Lens' Option (Maybe Text) oName = lens _oName (\ s a -> s{_oName = a}) instance FromJSON Option where parseJSON = withObject "Option" (\ o -> Option' <$> (o .:? "value") <*> (o .:? "name")) instance ToJSON Option where toJSON Option'{..} = object (catMaybes [("value" .=) <$> _oValue, ("name" .=) <$> _oName]) -- | A condition is a true\/false test that determines when an alerting -- policy should open an incident. If a condition evaluates to true, it -- signifies that something is wrong. -- -- /See:/ 'condition' smart constructor. data Condition = Condition' { _cConditionAbsent :: !(Maybe MetricAbsence) , _cConditionThreshold :: !(Maybe MetricThreshold) , _cName :: !(Maybe Text) , _cConditionMonitoringQueryLanguage :: !(Maybe MonitoringQueryLanguageCondition) , _cConditionMatchedLog :: !(Maybe LogMatch) , _cDisplayName :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Condition' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'cConditionAbsent' -- -- * 'cConditionThreshold' -- -- * 'cName' -- -- * 'cConditionMonitoringQueryLanguage' -- -- * 'cConditionMatchedLog' -- -- * 'cDisplayName' condition :: Condition condition = Condition' { _cConditionAbsent = Nothing , _cConditionThreshold = Nothing , _cName = Nothing , _cConditionMonitoringQueryLanguage = Nothing , _cConditionMatchedLog = Nothing , _cDisplayName = Nothing } -- | A condition that checks that a time series continues to receive new data -- points. cConditionAbsent :: Lens' Condition (Maybe MetricAbsence) cConditionAbsent = lens _cConditionAbsent (\ s a -> s{_cConditionAbsent = a}) -- | A condition that compares a time series against a threshold. cConditionThreshold :: Lens' Condition (Maybe MetricThreshold) cConditionThreshold = lens _cConditionThreshold (\ s a -> s{_cConditionThreshold = a}) -- | Required if the condition exists. The unique resource name for this -- condition. Its format is: -- projects\/[PROJECT_ID_OR_NUMBER]\/alertPolicies\/[POLICY_ID]\/conditions\/[CONDITION_ID] -- [CONDITION_ID] is assigned by Stackdriver Monitoring when the condition -- is created as part of a new or updated alerting policy.When calling the -- alertPolicies.create method, do not include the name field in the -- conditions of the requested alerting policy. Stackdriver Monitoring -- creates the condition identifiers and includes them in the new -- policy.When calling the alertPolicies.update method to update a policy, -- including a condition name causes the existing condition to be updated. -- Conditions without names are added to the updated policy. Existing -- conditions are deleted if they are not updated.Best practice is to -- preserve [CONDITION_ID] if you make only small changes, such as those to -- condition thresholds, durations, or trigger values. Otherwise, treat the -- change as a new condition and let the existing condition be deleted. cName :: Lens' Condition (Maybe Text) cName = lens _cName (\ s a -> s{_cName = a}) -- | A condition that uses the Monitoring Query Language to define alerts. cConditionMonitoringQueryLanguage :: Lens' Condition (Maybe MonitoringQueryLanguageCondition) cConditionMonitoringQueryLanguage = lens _cConditionMonitoringQueryLanguage (\ s a -> s{_cConditionMonitoringQueryLanguage = a}) -- | A condition that checks for log messages matching given constraints. If -- set, no other conditions can be present. cConditionMatchedLog :: Lens' Condition (Maybe LogMatch) cConditionMatchedLog = lens _cConditionMatchedLog (\ s a -> s{_cConditionMatchedLog = a}) -- | A short name or phrase used to identify the condition in dashboards, -- notifications, and incidents. To avoid confusion, don\'t use the same -- display name for multiple conditions in the same policy. cDisplayName :: Lens' Condition (Maybe Text) cDisplayName = lens _cDisplayName (\ s a -> s{_cDisplayName = a}) instance FromJSON Condition where parseJSON = withObject "Condition" (\ o -> Condition' <$> (o .:? "conditionAbsent") <*> (o .:? "conditionThreshold") <*> (o .:? "name") <*> (o .:? "conditionMonitoringQueryLanguage") <*> (o .:? "conditionMatchedLog") <*> (o .:? "displayName")) instance ToJSON Condition where toJSON Condition'{..} = object (catMaybes [("conditionAbsent" .=) <$> _cConditionAbsent, ("conditionThreshold" .=) <$> _cConditionThreshold, ("name" .=) <$> _cName, ("conditionMonitoringQueryLanguage" .=) <$> _cConditionMonitoringQueryLanguage, ("conditionMatchedLog" .=) <$> _cConditionMatchedLog, ("displayName" .=) <$> _cDisplayName]) -- | Represents the values of a time series associated with a -- TimeSeriesDescriptor. -- -- /See:/ 'timeSeriesData' smart constructor. data TimeSeriesData = TimeSeriesData' { _tsdPointData :: !(Maybe [PointData]) , _tsdLabelValues :: !(Maybe [LabelValue]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'TimeSeriesData' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'tsdPointData' -- -- * 'tsdLabelValues' timeSeriesData :: TimeSeriesData timeSeriesData = TimeSeriesData' {_tsdPointData = Nothing, _tsdLabelValues = Nothing} -- | The points in the time series. tsdPointData :: Lens' TimeSeriesData [PointData] tsdPointData = lens _tsdPointData (\ s a -> s{_tsdPointData = a}) . _Default . _Coerce -- | The values of the labels in the time series identifier, given in the -- same order as the label_descriptors field of the TimeSeriesDescriptor -- associated with this object. Each value must have a value of the type -- given in the corresponding entry of label_descriptors. tsdLabelValues :: Lens' TimeSeriesData [LabelValue] tsdLabelValues = lens _tsdLabelValues (\ s a -> s{_tsdLabelValues = a}) . _Default . _Coerce instance FromJSON TimeSeriesData where parseJSON = withObject "TimeSeriesData" (\ o -> TimeSeriesData' <$> (o .:? "pointData" .!= mempty) <*> (o .:? "labelValues" .!= mempty)) instance ToJSON TimeSeriesData where toJSON TimeSeriesData'{..} = object (catMaybes [("pointData" .=) <$> _tsdPointData, ("labelValues" .=) <$> _tsdLabelValues]) -- | BucketOptions describes the bucket boundaries used to create a histogram -- for the distribution. The buckets can be in a linear sequence, an -- exponential sequence, or each bucket can be specified explicitly. -- BucketOptions does not include the number of values in each bucket.A -- bucket has an inclusive lower bound and exclusive upper bound for the -- values that are counted for that bucket. The upper bound of a bucket -- must be strictly greater than the lower bound. The sequence of N buckets -- for a distribution consists of an underflow bucket (number 0), zero or -- more finite buckets (number 1 through N - 2) and an overflow bucket -- (number N - 1). The buckets are contiguous: the lower bound of bucket i -- (i > 0) is the same as the upper bound of bucket i - 1. The buckets span -- the whole range of finite values: lower bound of the underflow bucket is -- -infinity and the upper bound of the overflow bucket is +infinity. The -- finite buckets are so-called because both bounds are finite. -- -- /See:/ 'bucketOptions' smart constructor. data BucketOptions = BucketOptions' { _boExponentialBuckets :: !(Maybe Exponential) , _boLinearBuckets :: !(Maybe Linear) , _boExplicitBuckets :: !(Maybe Explicit) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'BucketOptions' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'boExponentialBuckets' -- -- * 'boLinearBuckets' -- -- * 'boExplicitBuckets' bucketOptions :: BucketOptions bucketOptions = BucketOptions' { _boExponentialBuckets = Nothing , _boLinearBuckets = Nothing , _boExplicitBuckets = Nothing } -- | The exponential buckets. boExponentialBuckets :: Lens' BucketOptions (Maybe Exponential) boExponentialBuckets = lens _boExponentialBuckets (\ s a -> s{_boExponentialBuckets = a}) -- | The linear bucket. boLinearBuckets :: Lens' BucketOptions (Maybe Linear) boLinearBuckets = lens _boLinearBuckets (\ s a -> s{_boLinearBuckets = a}) -- | The explicit buckets. boExplicitBuckets :: Lens' BucketOptions (Maybe Explicit) boExplicitBuckets = lens _boExplicitBuckets (\ s a -> s{_boExplicitBuckets = a}) instance FromJSON BucketOptions where parseJSON = withObject "BucketOptions" (\ o -> BucketOptions' <$> (o .:? "exponentialBuckets") <*> (o .:? "linearBuckets") <*> (o .:? "explicitBuckets")) instance ToJSON BucketOptions where toJSON BucketOptions'{..} = object (catMaybes [("exponentialBuckets" .=) <$> _boExponentialBuckets, ("linearBuckets" .=) <$> _boLinearBuckets, ("explicitBuckets" .=) <$> _boExplicitBuckets]) -- | The protocol for the ListUptimeCheckConfigs response. -- -- /See:/ 'listUptimeCheckConfigsResponse' smart constructor. data ListUptimeCheckConfigsResponse = ListUptimeCheckConfigsResponse' { _luccrUptimeCheckConfigs :: !(Maybe [UptimeCheckConfig]) , _luccrNextPageToken :: !(Maybe Text) , _luccrTotalSize :: !(Maybe (Textual Int32)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ListUptimeCheckConfigsResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'luccrUptimeCheckConfigs' -- -- * 'luccrNextPageToken' -- -- * 'luccrTotalSize' listUptimeCheckConfigsResponse :: ListUptimeCheckConfigsResponse listUptimeCheckConfigsResponse = ListUptimeCheckConfigsResponse' { _luccrUptimeCheckConfigs = Nothing , _luccrNextPageToken = Nothing , _luccrTotalSize = Nothing } -- | The returned Uptime check configurations. luccrUptimeCheckConfigs :: Lens' ListUptimeCheckConfigsResponse [UptimeCheckConfig] luccrUptimeCheckConfigs = lens _luccrUptimeCheckConfigs (\ s a -> s{_luccrUptimeCheckConfigs = a}) . _Default . _Coerce -- | This field represents the pagination token to retrieve the next page of -- results. If the value is empty, it means no further results for the -- request. To retrieve the next page of results, the value of the -- next_page_token is passed to the subsequent List method call (in the -- request message\'s page_token field). luccrNextPageToken :: Lens' ListUptimeCheckConfigsResponse (Maybe Text) luccrNextPageToken = lens _luccrNextPageToken (\ s a -> s{_luccrNextPageToken = a}) -- | The total number of Uptime check configurations for the project, -- irrespective of any pagination. luccrTotalSize :: Lens' ListUptimeCheckConfigsResponse (Maybe Int32) luccrTotalSize = lens _luccrTotalSize (\ s a -> s{_luccrTotalSize = a}) . mapping _Coerce instance FromJSON ListUptimeCheckConfigsResponse where parseJSON = withObject "ListUptimeCheckConfigsResponse" (\ o -> ListUptimeCheckConfigsResponse' <$> (o .:? "uptimeCheckConfigs" .!= mempty) <*> (o .:? "nextPageToken") <*> (o .:? "totalSize")) instance ToJSON ListUptimeCheckConfigsResponse where toJSON ListUptimeCheckConfigsResponse'{..} = object (catMaybes [("uptimeCheckConfigs" .=) <$> _luccrUptimeCheckConfigs, ("nextPageToken" .=) <$> _luccrNextPageToken, ("totalSize" .=) <$> _luccrTotalSize]) -- | Information involved in an HTTP\/HTTPS Uptime check request. -- -- /See:/ 'hTTPCheck' smart constructor. data HTTPCheck = HTTPCheck' { _httpcUseSSL :: !(Maybe Bool) , _httpcPath :: !(Maybe Text) , _httpcBody :: !(Maybe Bytes) , _httpcMaskHeaders :: !(Maybe Bool) , _httpcHeaders :: !(Maybe HTTPCheckHeaders) , _httpcValidateSSL :: !(Maybe Bool) , _httpcRequestMethod :: !(Maybe HTTPCheckRequestMethod) , _httpcAuthInfo :: !(Maybe BasicAuthentication) , _httpcContentType :: !(Maybe HTTPCheckContentType) , _httpcPort :: !(Maybe (Textual Int32)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'HTTPCheck' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'httpcUseSSL' -- -- * 'httpcPath' -- -- * 'httpcBody' -- -- * 'httpcMaskHeaders' -- -- * 'httpcHeaders' -- -- * 'httpcValidateSSL' -- -- * 'httpcRequestMethod' -- -- * 'httpcAuthInfo' -- -- * 'httpcContentType' -- -- * 'httpcPort' hTTPCheck :: HTTPCheck hTTPCheck = HTTPCheck' { _httpcUseSSL = Nothing , _httpcPath = Nothing , _httpcBody = Nothing , _httpcMaskHeaders = Nothing , _httpcHeaders = Nothing , _httpcValidateSSL = Nothing , _httpcRequestMethod = Nothing , _httpcAuthInfo = Nothing , _httpcContentType = Nothing , _httpcPort = Nothing } -- | If true, use HTTPS instead of HTTP to run the check. httpcUseSSL :: Lens' HTTPCheck (Maybe Bool) httpcUseSSL = lens _httpcUseSSL (\ s a -> s{_httpcUseSSL = a}) -- | Optional (defaults to \"\/\"). The path to the page against which to run -- the check. Will be combined with the host (specified within the -- monitored_resource) and port to construct the full URL. If the provided -- path does not begin with \"\/\", a \"\/\" will be prepended -- automatically. httpcPath :: Lens' HTTPCheck (Maybe Text) httpcPath = lens _httpcPath (\ s a -> s{_httpcPath = a}) -- | The request body associated with the HTTP POST request. If content_type -- is URL_ENCODED, the body passed in must be URL-encoded. Users can -- provide a Content-Length header via the headers field or the API will do -- so. If the request_method is GET and body is not empty, the API will -- return an error. The maximum byte size is 1 megabyte. Note: As with all -- bytes fields, JSON representations are base64 encoded. e.g.: \"foo=bar\" -- in URL-encoded form is \"foo%3Dbar\" and in base64 encoding is -- \"Zm9vJTI1M0RiYXI=\". httpcBody :: Lens' HTTPCheck (Maybe ByteString) httpcBody = lens _httpcBody (\ s a -> s{_httpcBody = a}) . mapping _Bytes -- | Boolean specifying whether to encrypt the header information. Encryption -- should be specified for any headers related to authentication that you -- do not wish to be seen when retrieving the configuration. The server -- will be responsible for encrypting the headers. On Get\/List calls, if -- mask_headers is set to true then the headers will be obscured with -- ******. httpcMaskHeaders :: Lens' HTTPCheck (Maybe Bool) httpcMaskHeaders = lens _httpcMaskHeaders (\ s a -> s{_httpcMaskHeaders = a}) -- | The list of headers to send as part of the Uptime check request. If two -- headers have the same key and different values, they should be entered -- as a single header, with the value being a comma-separated list of all -- the desired values as described at -- https:\/\/www.w3.org\/Protocols\/rfc2616\/rfc2616.txt (page 31). -- Entering two separate headers with the same key in a Create call will -- cause the first to be overwritten by the second. The maximum number of -- headers allowed is 100. httpcHeaders :: Lens' HTTPCheck (Maybe HTTPCheckHeaders) httpcHeaders = lens _httpcHeaders (\ s a -> s{_httpcHeaders = a}) -- | Boolean specifying whether to include SSL certificate validation as a -- part of the Uptime check. Only applies to checks where -- monitored_resource is set to uptime_url. If use_ssl is false, setting -- validate_ssl to true has no effect. httpcValidateSSL :: Lens' HTTPCheck (Maybe Bool) httpcValidateSSL = lens _httpcValidateSSL (\ s a -> s{_httpcValidateSSL = a}) -- | The HTTP request method to use for the check. If set to -- METHOD_UNSPECIFIED then request_method defaults to GET. httpcRequestMethod :: Lens' HTTPCheck (Maybe HTTPCheckRequestMethod) httpcRequestMethod = lens _httpcRequestMethod (\ s a -> s{_httpcRequestMethod = a}) -- | The authentication information. Optional when creating an HTTP check; -- defaults to empty. httpcAuthInfo :: Lens' HTTPCheck (Maybe BasicAuthentication) httpcAuthInfo = lens _httpcAuthInfo (\ s a -> s{_httpcAuthInfo = a}) -- | The content type header to use for the check. The following -- configurations result in errors: 1. Content type is specified in both -- the headers field and the content_type field. 2. Request method is GET -- and content_type is not TYPE_UNSPECIFIED 3. Request method is POST and -- content_type is TYPE_UNSPECIFIED. 4. Request method is POST and a -- \"Content-Type\" header is provided via headers field. The content_type -- field should be used instead. httpcContentType :: Lens' HTTPCheck (Maybe HTTPCheckContentType) httpcContentType = lens _httpcContentType (\ s a -> s{_httpcContentType = a}) -- | Optional (defaults to 80 when use_ssl is false, and 443 when use_ssl is -- true). The TCP port on the HTTP server against which to run the check. -- Will be combined with host (specified within the monitored_resource) and -- path to construct the full URL. httpcPort :: Lens' HTTPCheck (Maybe Int32) httpcPort = lens _httpcPort (\ s a -> s{_httpcPort = a}) . mapping _Coerce instance FromJSON HTTPCheck where parseJSON = withObject "HTTPCheck" (\ o -> HTTPCheck' <$> (o .:? "useSsl") <*> (o .:? "path") <*> (o .:? "body") <*> (o .:? "maskHeaders") <*> (o .:? "headers") <*> (o .:? "validateSsl") <*> (o .:? "requestMethod") <*> (o .:? "authInfo") <*> (o .:? "contentType") <*> (o .:? "port")) instance ToJSON HTTPCheck where toJSON HTTPCheck'{..} = object (catMaybes [("useSsl" .=) <$> _httpcUseSSL, ("path" .=) <$> _httpcPath, ("body" .=) <$> _httpcBody, ("maskHeaders" .=) <$> _httpcMaskHeaders, ("headers" .=) <$> _httpcHeaders, ("validateSsl" .=) <$> _httpcValidateSSL, ("requestMethod" .=) <$> _httpcRequestMethod, ("authInfo" .=) <$> _httpcAuthInfo, ("contentType" .=) <$> _httpcContentType, ("port" .=) <$> _httpcPort]) -- | A collection of data points that describes the time-varying values of a -- metric. A time series is identified by a combination of a -- fully-specified monitored resource and a fully-specified metric. This -- type is used for both listing and creating time series. -- -- /See:/ 'timeSeries' smart constructor. data TimeSeries = TimeSeries' { _tsPoints :: !(Maybe [Point]) , _tsMetricKind :: !(Maybe TimeSeriesMetricKind) , _tsMetric :: !(Maybe Metric) , _tsResource :: !(Maybe MonitoredResource) , _tsMetadata :: !(Maybe MonitoredResourceMetadata) , _tsValueType :: !(Maybe TimeSeriesValueType) , _tsUnit :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'TimeSeries' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'tsPoints' -- -- * 'tsMetricKind' -- -- * 'tsMetric' -- -- * 'tsResource' -- -- * 'tsMetadata' -- -- * 'tsValueType' -- -- * 'tsUnit' timeSeries :: TimeSeries timeSeries = TimeSeries' { _tsPoints = Nothing , _tsMetricKind = Nothing , _tsMetric = Nothing , _tsResource = Nothing , _tsMetadata = Nothing , _tsValueType = Nothing , _tsUnit = Nothing } -- | The data points of this time series. When listing time series, points -- are returned in reverse time order.When creating a time series, this -- field must contain exactly one point and the point\'s type must be the -- same as the value type of the associated metric. If the associated -- metric\'s descriptor must be auto-created, then the value type of the -- descriptor is determined by the point\'s type, which must be BOOL, -- INT64, DOUBLE, or DISTRIBUTION. tsPoints :: Lens' TimeSeries [Point] tsPoints = lens _tsPoints (\ s a -> s{_tsPoints = a}) . _Default . _Coerce -- | The metric kind of the time series. When listing time series, this -- metric kind might be different from the metric kind of the associated -- metric if this time series is an alignment or reduction of other time -- series.When creating a time series, this field is optional. If present, -- it must be the same as the metric kind of the associated metric. If the -- associated metric\'s descriptor must be auto-created, then this field -- specifies the metric kind of the new descriptor and must be either GAUGE -- (the default) or CUMULATIVE. tsMetricKind :: Lens' TimeSeries (Maybe TimeSeriesMetricKind) tsMetricKind = lens _tsMetricKind (\ s a -> s{_tsMetricKind = a}) -- | The associated metric. A fully-specified metric used to identify the -- time series. tsMetric :: Lens' TimeSeries (Maybe Metric) tsMetric = lens _tsMetric (\ s a -> s{_tsMetric = a}) -- | The associated monitored resource. Custom metrics can use only certain -- monitored resource types in their time series data. For more -- information, see Monitored resources for custom metrics -- (https:\/\/cloud.google.com\/monitoring\/custom-metrics\/creating-metrics#custom-metric-resources). tsResource :: Lens' TimeSeries (Maybe MonitoredResource) tsResource = lens _tsResource (\ s a -> s{_tsResource = a}) -- | Output only. The associated monitored resource metadata. When reading a -- time series, this field will include metadata labels that are explicitly -- named in the reduction. When creating a time series, this field is -- ignored. tsMetadata :: Lens' TimeSeries (Maybe MonitoredResourceMetadata) tsMetadata = lens _tsMetadata (\ s a -> s{_tsMetadata = a}) -- | The value type of the time series. When listing time series, this value -- type might be different from the value type of the associated metric if -- this time series is an alignment or reduction of other time series.When -- creating a time series, this field is optional. If present, it must be -- the same as the type of the data in the points field. tsValueType :: Lens' TimeSeries (Maybe TimeSeriesValueType) tsValueType = lens _tsValueType (\ s a -> s{_tsValueType = a}) -- | The units in which the metric value is reported. It is only applicable -- if the value_type is INT64, DOUBLE, or DISTRIBUTION. The unit defines -- the representation of the stored metric values. tsUnit :: Lens' TimeSeries (Maybe Text) tsUnit = lens _tsUnit (\ s a -> s{_tsUnit = a}) instance FromJSON TimeSeries where parseJSON = withObject "TimeSeries" (\ o -> TimeSeries' <$> (o .:? "points" .!= mempty) <*> (o .:? "metricKind") <*> (o .:? "metric") <*> (o .:? "resource") <*> (o .:? "metadata") <*> (o .:? "valueType") <*> (o .:? "unit")) instance ToJSON TimeSeries where toJSON TimeSeries'{..} = object (catMaybes [("points" .=) <$> _tsPoints, ("metricKind" .=) <$> _tsMetricKind, ("metric" .=) <$> _tsMetric, ("resource" .=) <$> _tsResource, ("metadata" .=) <$> _tsMetadata, ("valueType" .=) <$> _tsValueType, ("unit" .=) <$> _tsUnit]) -- | A description of the conditions under which some aspect of your system -- is considered to be \"unhealthy\" and the ways to notify people or -- services about this state. For an overview of alert policies, see -- Introduction to Alerting -- (https:\/\/cloud.google.com\/monitoring\/alerts\/). -- -- /See:/ 'alertPolicy' smart constructor. data AlertPolicy = AlertPolicy' { _apEnabled :: !(Maybe Bool) , _apNotificationChannels :: !(Maybe [Text]) , _apMutationRecord :: !(Maybe MutationRecord) , _apCreationRecord :: !(Maybe MutationRecord) , _apUserLabels :: !(Maybe AlertPolicyUserLabels) , _apName :: !(Maybe Text) , _apDocumentation :: !(Maybe Documentation) , _apValidity :: !(Maybe Status) , _apDisplayName :: !(Maybe Text) , _apAlertStrategy :: !(Maybe AlertStrategy) , _apConditions :: !(Maybe [Condition]) , _apCombiner :: !(Maybe AlertPolicyCombiner) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'AlertPolicy' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'apEnabled' -- -- * 'apNotificationChannels' -- -- * 'apMutationRecord' -- -- * 'apCreationRecord' -- -- * 'apUserLabels' -- -- * 'apName' -- -- * 'apDocumentation' -- -- * 'apValidity' -- -- * 'apDisplayName' -- -- * 'apAlertStrategy' -- -- * 'apConditions' -- -- * 'apCombiner' alertPolicy :: AlertPolicy alertPolicy = AlertPolicy' { _apEnabled = Nothing , _apNotificationChannels = Nothing , _apMutationRecord = Nothing , _apCreationRecord = Nothing , _apUserLabels = Nothing , _apName = Nothing , _apDocumentation = Nothing , _apValidity = Nothing , _apDisplayName = Nothing , _apAlertStrategy = Nothing , _apConditions = Nothing , _apCombiner = Nothing } -- | Whether or not the policy is enabled. On write, the default -- interpretation if unset is that the policy is enabled. On read, clients -- should not make any assumption about the state if it has not been -- populated. The field should always be populated on List and Get -- operations, unless a field projection has been specified that strips it -- out. apEnabled :: Lens' AlertPolicy (Maybe Bool) apEnabled = lens _apEnabled (\ s a -> s{_apEnabled = a}) -- | Identifies the notification channels to which notifications should be -- sent when incidents are opened or closed or when new violations occur on -- an already opened incident. Each element of this array corresponds to -- the name field in each of the NotificationChannel objects that are -- returned from the ListNotificationChannels method. The format of the -- entries in this field is: -- projects\/[PROJECT_ID_OR_NUMBER]\/notificationChannels\/[CHANNEL_ID] apNotificationChannels :: Lens' AlertPolicy [Text] apNotificationChannels = lens _apNotificationChannels (\ s a -> s{_apNotificationChannels = a}) . _Default . _Coerce -- | A read-only record of the most recent change to the alerting policy. If -- provided in a call to create or update, this field will be ignored. apMutationRecord :: Lens' AlertPolicy (Maybe MutationRecord) apMutationRecord = lens _apMutationRecord (\ s a -> s{_apMutationRecord = a}) -- | A read-only record of the creation of the alerting policy. If provided -- in a call to create or update, this field will be ignored. apCreationRecord :: Lens' AlertPolicy (Maybe MutationRecord) apCreationRecord = lens _apCreationRecord (\ s a -> s{_apCreationRecord = a}) -- | User-supplied key\/value data to be used for organizing and identifying -- the AlertPolicy objects.The field can contain up to 64 entries. Each key -- and value is limited to 63 Unicode characters or 128 bytes, whichever is -- smaller. Labels and values can contain only lowercase letters, numerals, -- underscores, and dashes. Keys must begin with a letter. apUserLabels :: Lens' AlertPolicy (Maybe AlertPolicyUserLabels) apUserLabels = lens _apUserLabels (\ s a -> s{_apUserLabels = a}) -- | Required if the policy exists. The resource name for this policy. The -- format is: -- projects\/[PROJECT_ID_OR_NUMBER]\/alertPolicies\/[ALERT_POLICY_ID] -- [ALERT_POLICY_ID] is assigned by Stackdriver Monitoring when the policy -- is created. When calling the alertPolicies.create method, do not include -- the name field in the alerting policy passed as part of the request. apName :: Lens' AlertPolicy (Maybe Text) apName = lens _apName (\ s a -> s{_apName = a}) -- | Documentation that is included with notifications and incidents related -- to this policy. Best practice is for the documentation to include -- information to help responders understand, mitigate, escalate, and -- correct the underlying problems detected by the alerting policy. -- Notification channels that have limited capacity might not show this -- documentation. apDocumentation :: Lens' AlertPolicy (Maybe Documentation) apDocumentation = lens _apDocumentation (\ s a -> s{_apDocumentation = a}) -- | Read-only description of how the alert policy is invalid. OK if the -- alert policy is valid. If not OK, the alert policy will not generate -- incidents. apValidity :: Lens' AlertPolicy (Maybe Status) apValidity = lens _apValidity (\ s a -> s{_apValidity = a}) -- | A short name or phrase used to identify the policy in dashboards, -- notifications, and incidents. To avoid confusion, don\'t use the same -- display name for multiple policies in the same project. The name is -- limited to 512 Unicode characters. apDisplayName :: Lens' AlertPolicy (Maybe Text) apDisplayName = lens _apDisplayName (\ s a -> s{_apDisplayName = a}) -- | Control over how this alert policy\'s notification channels are -- notified. apAlertStrategy :: Lens' AlertPolicy (Maybe AlertStrategy) apAlertStrategy = lens _apAlertStrategy (\ s a -> s{_apAlertStrategy = a}) -- | A list of conditions for the policy. The conditions are combined by AND -- or OR according to the combiner field. If the combined conditions -- evaluate to true, then an incident is created. A policy can have from -- one to six conditions. If condition_time_series_query_language is -- present, it must be the only condition. apConditions :: Lens' AlertPolicy [Condition] apConditions = lens _apConditions (\ s a -> s{_apConditions = a}) . _Default . _Coerce -- | How to combine the results of multiple conditions to determine if an -- incident should be opened. If condition_time_series_query_language is -- present, this must be COMBINE_UNSPECIFIED. apCombiner :: Lens' AlertPolicy (Maybe AlertPolicyCombiner) apCombiner = lens _apCombiner (\ s a -> s{_apCombiner = a}) instance FromJSON AlertPolicy where parseJSON = withObject "AlertPolicy" (\ o -> AlertPolicy' <$> (o .:? "enabled") <*> (o .:? "notificationChannels" .!= mempty) <*> (o .:? "mutationRecord") <*> (o .:? "creationRecord") <*> (o .:? "userLabels") <*> (o .:? "name") <*> (o .:? "documentation") <*> (o .:? "validity") <*> (o .:? "displayName") <*> (o .:? "alertStrategy") <*> (o .:? "conditions" .!= mempty) <*> (o .:? "combiner")) instance ToJSON AlertPolicy where toJSON AlertPolicy'{..} = object (catMaybes [("enabled" .=) <$> _apEnabled, ("notificationChannels" .=) <$> _apNotificationChannels, ("mutationRecord" .=) <$> _apMutationRecord, ("creationRecord" .=) <$> _apCreationRecord, ("userLabels" .=) <$> _apUserLabels, ("name" .=) <$> _apName, ("documentation" .=) <$> _apDocumentation, ("validity" .=) <$> _apValidity, ("displayName" .=) <$> _apDisplayName, ("alertStrategy" .=) <$> _apAlertStrategy, ("conditions" .=) <$> _apConditions, ("combiner" .=) <$> _apCombiner]) -- | Service Level Indicators for which atomic units of service are counted -- directly. -- -- /See:/ 'requestBasedSli' smart constructor. data RequestBasedSli = RequestBasedSli' { _rbsGoodTotalRatio :: !(Maybe TimeSeriesRatio) , _rbsDistributionCut :: !(Maybe DistributionCut) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'RequestBasedSli' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'rbsGoodTotalRatio' -- -- * 'rbsDistributionCut' requestBasedSli :: RequestBasedSli requestBasedSli = RequestBasedSli' {_rbsGoodTotalRatio = Nothing, _rbsDistributionCut = Nothing} -- | good_total_ratio is used when the ratio of good_service to total_service -- is computed from two TimeSeries. rbsGoodTotalRatio :: Lens' RequestBasedSli (Maybe TimeSeriesRatio) rbsGoodTotalRatio = lens _rbsGoodTotalRatio (\ s a -> s{_rbsGoodTotalRatio = a}) -- | distribution_cut is used when good_service is a count of values -- aggregated in a Distribution that fall into a good range. The -- total_service is the total count of all values aggregated in the -- Distribution. rbsDistributionCut :: Lens' RequestBasedSli (Maybe DistributionCut) rbsDistributionCut = lens _rbsDistributionCut (\ s a -> s{_rbsDistributionCut = a}) instance FromJSON RequestBasedSli where parseJSON = withObject "RequestBasedSli" (\ o -> RequestBasedSli' <$> (o .:? "goodTotalRatio") <*> (o .:? "distributionCut")) instance ToJSON RequestBasedSli where toJSON RequestBasedSli'{..} = object (catMaybes [("goodTotalRatio" .=) <$> _rbsGoodTotalRatio, ("distributionCut" .=) <$> _rbsDistributionCut]) -- | Cloud Endpoints service. Learn more at -- https:\/\/cloud.google.com\/endpoints. -- -- /See:/ 'cloudEndpoints' smart constructor. newtype CloudEndpoints = CloudEndpoints' { _ceService :: Maybe Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'CloudEndpoints' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ceService' cloudEndpoints :: CloudEndpoints cloudEndpoints = CloudEndpoints' {_ceService = Nothing} -- | The name of the Cloud Endpoints service underlying this service. -- Corresponds to the service resource label in the api monitored resource: -- https:\/\/cloud.google.com\/monitoring\/api\/resources#tag_api ceService :: Lens' CloudEndpoints (Maybe Text) ceService = lens _ceService (\ s a -> s{_ceService = a}) instance FromJSON CloudEndpoints where parseJSON = withObject "CloudEndpoints" (\ o -> CloudEndpoints' <$> (o .:? "service")) instance ToJSON CloudEndpoints where toJSON CloudEndpoints'{..} = object (catMaybes [("service" .=) <$> _ceService]) -- | The protocol for the ListAlertPolicies response. -- -- /See:/ 'listAlertPoliciesResponse' smart constructor. data ListAlertPoliciesResponse = ListAlertPoliciesResponse' { _laprNextPageToken :: !(Maybe Text) , _laprTotalSize :: !(Maybe (Textual Int32)) , _laprAlertPolicies :: !(Maybe [AlertPolicy]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ListAlertPoliciesResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'laprNextPageToken' -- -- * 'laprTotalSize' -- -- * 'laprAlertPolicies' listAlertPoliciesResponse :: ListAlertPoliciesResponse listAlertPoliciesResponse = ListAlertPoliciesResponse' { _laprNextPageToken = Nothing , _laprTotalSize = Nothing , _laprAlertPolicies = Nothing } -- | If there might be more results than were returned, then this field is -- set to a non-empty value. To see the additional results, use that value -- as page_token in the next call to this method. laprNextPageToken :: Lens' ListAlertPoliciesResponse (Maybe Text) laprNextPageToken = lens _laprNextPageToken (\ s a -> s{_laprNextPageToken = a}) -- | The total number of alert policies in all pages. This number is only an -- estimate, and may change in subsequent pages. https:\/\/aip.dev\/158 laprTotalSize :: Lens' ListAlertPoliciesResponse (Maybe Int32) laprTotalSize = lens _laprTotalSize (\ s a -> s{_laprTotalSize = a}) . mapping _Coerce -- | The returned alert policies. laprAlertPolicies :: Lens' ListAlertPoliciesResponse [AlertPolicy] laprAlertPolicies = lens _laprAlertPolicies (\ s a -> s{_laprAlertPolicies = a}) . _Default . _Coerce instance FromJSON ListAlertPoliciesResponse where parseJSON = withObject "ListAlertPoliciesResponse" (\ o -> ListAlertPoliciesResponse' <$> (o .:? "nextPageToken") <*> (o .:? "totalSize") <*> (o .:? "alertPolicies" .!= mempty)) instance ToJSON ListAlertPoliciesResponse where toJSON ListAlertPoliciesResponse'{..} = object (catMaybes [("nextPageToken" .=) <$> _laprNextPageToken, ("totalSize" .=) <$> _laprTotalSize, ("alertPolicies" .=) <$> _laprAlertPolicies]) -- | Information required for a TCP Uptime check request. -- -- /See:/ 'tcpCheck' smart constructor. newtype TCPCheck = TCPCheck' { _tcPort :: Maybe (Textual Int32) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'TCPCheck' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'tcPort' tcpCheck :: TCPCheck tcpCheck = TCPCheck' {_tcPort = Nothing} -- | The TCP port on the server against which to run the check. Will be -- combined with host (specified within the monitored_resource) to -- construct the full URL. Required. tcPort :: Lens' TCPCheck (Maybe Int32) tcPort = lens _tcPort (\ s a -> s{_tcPort = a}) . mapping _Coerce instance FromJSON TCPCheck where parseJSON = withObject "TCPCheck" (\ o -> TCPCheck' <$> (o .:? "port")) instance ToJSON TCPCheck where toJSON TCPCheck'{..} = object (catMaybes [("port" .=) <$> _tcPort]) -- | Labels which have been used to annotate the service. Label keys must -- start with a letter. Label keys and values may contain lowercase -- letters, numbers, underscores, and dashes. Label keys and values have a -- maximum length of 63 characters, and must be less than 128 bytes in -- size. Up to 64 label entries may be stored. For labels which do not have -- a semantic value, the empty string may be supplied for the label value. -- -- /See:/ 'serviceUserLabels' smart constructor. newtype ServiceUserLabels = ServiceUserLabels' { _sulAddtional :: HashMap Text Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ServiceUserLabels' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'sulAddtional' serviceUserLabels :: HashMap Text Text -- ^ 'sulAddtional' -> ServiceUserLabels serviceUserLabels pSulAddtional_ = ServiceUserLabels' {_sulAddtional = _Coerce # pSulAddtional_} sulAddtional :: Lens' ServiceUserLabels (HashMap Text Text) sulAddtional = lens _sulAddtional (\ s a -> s{_sulAddtional = a}) . _Coerce instance FromJSON ServiceUserLabels where parseJSON = withObject "ServiceUserLabels" (\ o -> ServiceUserLabels' <$> (parseJSONObject o)) instance ToJSON ServiceUserLabels where toJSON = toJSON . _sulAddtional -- | A condition type that checks that monitored resources are reporting -- data. The configuration defines a metric and a set of monitored -- resources. The predicate is considered in violation when a time series -- for the specified metric of a monitored resource does not include any -- data in the specified duration. -- -- /See:/ 'metricAbsence' smart constructor. data MetricAbsence = MetricAbsence' { _maAggregations :: !(Maybe [Aggregation]) , _maFilter :: !(Maybe Text) , _maTrigger :: !(Maybe Trigger) , _maDuration :: !(Maybe GDuration) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'MetricAbsence' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'maAggregations' -- -- * 'maFilter' -- -- * 'maTrigger' -- -- * 'maDuration' metricAbsence :: MetricAbsence metricAbsence = MetricAbsence' { _maAggregations = Nothing , _maFilter = Nothing , _maTrigger = Nothing , _maDuration = Nothing } -- | Specifies the alignment of data points in individual time series as well -- as how to combine the retrieved time series together (such as when -- aggregating multiple streams on each resource to a single stream for -- each resource or when aggregating streams across all members of a group -- of resrouces). Multiple aggregations are applied in the order -- specified.This field is similar to the one in the ListTimeSeries request -- (https:\/\/cloud.google.com\/monitoring\/api\/ref_v3\/rest\/v3\/projects.timeSeries\/list). -- It is advisable to use the ListTimeSeries method when debugging this -- field. maAggregations :: Lens' MetricAbsence [Aggregation] maAggregations = lens _maAggregations (\ s a -> s{_maAggregations = a}) . _Default . _Coerce -- | Required. A filter -- (https:\/\/cloud.google.com\/monitoring\/api\/v3\/filters) that -- identifies which time series should be compared with the threshold.The -- filter is similar to the one that is specified in the ListTimeSeries -- request -- (https:\/\/cloud.google.com\/monitoring\/api\/ref_v3\/rest\/v3\/projects.timeSeries\/list) -- (that call is useful to verify the time series that will be retrieved \/ -- processed). The filter must specify the metric type and the resource -- type. Optionally, it can specify resource labels and metric labels. This -- field must not exceed 2048 Unicode characters in length. maFilter :: Lens' MetricAbsence (Maybe Text) maFilter = lens _maFilter (\ s a -> s{_maFilter = a}) -- | The number\/percent of time series for which the comparison must hold in -- order for the condition to trigger. If unspecified, then the condition -- will trigger if the comparison is true for any of the time series that -- have been identified by filter and aggregations. maTrigger :: Lens' MetricAbsence (Maybe Trigger) maTrigger = lens _maTrigger (\ s a -> s{_maTrigger = a}) -- | The amount of time that a time series must fail to report new data to be -- considered failing. The minimum value of this field is 120 seconds. -- Larger values that are a multiple of a minute--for example, 240 or 300 -- seconds--are supported. If an invalid value is given, an error will be -- returned. The Duration.nanos field is ignored. maDuration :: Lens' MetricAbsence (Maybe Scientific) maDuration = lens _maDuration (\ s a -> s{_maDuration = a}) . mapping _GDuration instance FromJSON MetricAbsence where parseJSON = withObject "MetricAbsence" (\ o -> MetricAbsence' <$> (o .:? "aggregations" .!= mempty) <*> (o .:? "filter") <*> (o .:? "trigger") <*> (o .:? "duration")) instance ToJSON MetricAbsence where toJSON MetricAbsence'{..} = object (catMaybes [("aggregations" .=) <$> _maAggregations, ("filter" .=) <$> _maFilter, ("trigger" .=) <$> _maTrigger, ("duration" .=) <$> _maDuration]) -- | Describes the error status for values that were not written. -- -- /See:/ 'collectdValueError' smart constructor. data CollectdValueError = CollectdValueError' { _cveError :: !(Maybe Status) , _cveIndex :: !(Maybe (Textual Int32)) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'CollectdValueError' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'cveError' -- -- * 'cveIndex' collectdValueError :: CollectdValueError collectdValueError = CollectdValueError' {_cveError = Nothing, _cveIndex = Nothing} -- | Records the error status for the value. cveError :: Lens' CollectdValueError (Maybe Status) cveError = lens _cveError (\ s a -> s{_cveError = a}) -- | The zero-based index in CollectdPayload.values within the parent -- CreateCollectdTimeSeriesRequest.collectd_payloads. cveIndex :: Lens' CollectdValueError (Maybe Int32) cveIndex = lens _cveIndex (\ s a -> s{_cveIndex = a}) . mapping _Coerce instance FromJSON CollectdValueError where parseJSON = withObject "CollectdValueError" (\ o -> CollectdValueError' <$> (o .:? "error") <*> (o .:? "index")) instance ToJSON CollectdValueError where toJSON CollectdValueError'{..} = object (catMaybes [("error" .=) <$> _cveError, ("index" .=) <$> _cveIndex])
brendanhay/gogol
gogol-monitoring/gen/Network/Google/Monitoring/Types/Product.hs
mpl-2.0
295,157
0
23
66,697
45,928
26,639
19,289
5,043
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.Analytics.Management.RemarketingAudience.Get -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Gets a remarketing audience to which the user has access. -- -- /See:/ <https://developers.google.com/analytics/ Google Analytics API Reference> for @analytics.management.remarketingAudience.get@. module Network.Google.Resource.Analytics.Management.RemarketingAudience.Get ( -- * REST Resource ManagementRemarketingAudienceGetResource -- * Creating a Request , managementRemarketingAudienceGet , ManagementRemarketingAudienceGet -- * Request Lenses , mragWebPropertyId , mragAccountId , mragRemarketingAudienceId ) where import Network.Google.Analytics.Types import Network.Google.Prelude -- | A resource alias for @analytics.management.remarketingAudience.get@ method which the -- 'ManagementRemarketingAudienceGet' request conforms to. type ManagementRemarketingAudienceGetResource = "analytics" :> "v3" :> "management" :> "accounts" :> Capture "accountId" Text :> "webproperties" :> Capture "webPropertyId" Text :> "remarketingAudiences" :> Capture "remarketingAudienceId" Text :> QueryParam "alt" AltJSON :> Get '[JSON] RemarketingAudience -- | Gets a remarketing audience to which the user has access. -- -- /See:/ 'managementRemarketingAudienceGet' smart constructor. data ManagementRemarketingAudienceGet = ManagementRemarketingAudienceGet' { _mragWebPropertyId :: !Text , _mragAccountId :: !Text , _mragRemarketingAudienceId :: !Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ManagementRemarketingAudienceGet' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'mragWebPropertyId' -- -- * 'mragAccountId' -- -- * 'mragRemarketingAudienceId' managementRemarketingAudienceGet :: Text -- ^ 'mragWebPropertyId' -> Text -- ^ 'mragAccountId' -> Text -- ^ 'mragRemarketingAudienceId' -> ManagementRemarketingAudienceGet managementRemarketingAudienceGet pMragWebPropertyId_ pMragAccountId_ pMragRemarketingAudienceId_ = ManagementRemarketingAudienceGet' { _mragWebPropertyId = pMragWebPropertyId_ , _mragAccountId = pMragAccountId_ , _mragRemarketingAudienceId = pMragRemarketingAudienceId_ } -- | The web property ID of the remarketing audience to retrieve. mragWebPropertyId :: Lens' ManagementRemarketingAudienceGet Text mragWebPropertyId = lens _mragWebPropertyId (\ s a -> s{_mragWebPropertyId = a}) -- | The account ID of the remarketing audience to retrieve. mragAccountId :: Lens' ManagementRemarketingAudienceGet Text mragAccountId = lens _mragAccountId (\ s a -> s{_mragAccountId = a}) -- | The ID of the remarketing audience to retrieve. mragRemarketingAudienceId :: Lens' ManagementRemarketingAudienceGet Text mragRemarketingAudienceId = lens _mragRemarketingAudienceId (\ s a -> s{_mragRemarketingAudienceId = a}) instance GoogleRequest ManagementRemarketingAudienceGet where type Rs ManagementRemarketingAudienceGet = RemarketingAudience type Scopes ManagementRemarketingAudienceGet = '["https://www.googleapis.com/auth/analytics.edit", "https://www.googleapis.com/auth/analytics.readonly"] requestClient ManagementRemarketingAudienceGet'{..} = go _mragAccountId _mragWebPropertyId _mragRemarketingAudienceId (Just AltJSON) analyticsService where go = buildClient (Proxy :: Proxy ManagementRemarketingAudienceGetResource) mempty
brendanhay/gogol
gogol-analytics/gen/Network/Google/Resource/Analytics/Management/RemarketingAudience/Get.hs
mpl-2.0
4,583
0
17
1,014
468
279
189
85
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.URLShortener.URL.Insert -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Creates a new short URL. -- -- /See:/ <https://developers.google.com/url-shortener/v1/getting_started URL Shortener API Reference> for @urlshortener.url.insert@. module Network.Google.Resource.URLShortener.URL.Insert ( -- * REST Resource URLInsertResource -- * Creating a Request , urlInsert , URLInsert -- * Request Lenses , uiPayload ) where import Network.Google.Prelude import Network.Google.URLShortener.Types -- | A resource alias for @urlshortener.url.insert@ method which the -- 'URLInsert' request conforms to. type URLInsertResource = "urlshortener" :> "v1" :> "url" :> QueryParam "alt" AltJSON :> ReqBody '[JSON] URL :> Post '[JSON] URL -- | Creates a new short URL. -- -- /See:/ 'urlInsert' smart constructor. newtype URLInsert = URLInsert' { _uiPayload :: URL } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'URLInsert' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'uiPayload' urlInsert :: URL -- ^ 'uiPayload' -> URLInsert urlInsert pUiPayload_ = URLInsert' {_uiPayload = pUiPayload_} -- | Multipart request metadata. uiPayload :: Lens' URLInsert URL uiPayload = lens _uiPayload (\ s a -> s{_uiPayload = a}) instance GoogleRequest URLInsert where type Rs URLInsert = URL type Scopes URLInsert = '["https://www.googleapis.com/auth/urlshortener"] requestClient URLInsert'{..} = go (Just AltJSON) _uiPayload uRLShortenerService where go = buildClient (Proxy :: Proxy URLInsertResource) mempty
brendanhay/gogol
gogol-urlshortener/gen/Network/Google/Resource/URLShortener/URL/Insert.hs
mpl-2.0
2,499
0
12
562
304
187
117
46
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.Environments.Patch -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Updates a GTM Environment. This method supports patch semantics. -- -- /See:/ <https://developers.google.com/tag-manager/api/v1/ Tag Manager API Reference> for @tagmanager.accounts.containers.environments.patch@. module Network.Google.Resource.TagManager.Accounts.Containers.Environments.Patch ( -- * REST Resource AccountsContainersEnvironmentsPatchResource -- * Creating a Request , accountsContainersEnvironmentsPatch , AccountsContainersEnvironmentsPatch -- * Request Lenses , acepContainerId , acepFingerprint , acepPayload , acepAccountId , acepEnvironmentId ) where import Network.Google.Prelude import Network.Google.TagManager.Types -- | A resource alias for @tagmanager.accounts.containers.environments.patch@ method which the -- 'AccountsContainersEnvironmentsPatch' request conforms to. type AccountsContainersEnvironmentsPatchResource = "tagmanager" :> "v1" :> "accounts" :> Capture "accountId" Text :> "containers" :> Capture "containerId" Text :> "environments" :> Capture "environmentId" Text :> QueryParam "fingerprint" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] Environment :> Patch '[JSON] Environment -- | Updates a GTM Environment. This method supports patch semantics. -- -- /See:/ 'accountsContainersEnvironmentsPatch' smart constructor. data AccountsContainersEnvironmentsPatch = AccountsContainersEnvironmentsPatch' { _acepContainerId :: !Text , _acepFingerprint :: !(Maybe Text) , _acepPayload :: !Environment , _acepAccountId :: !Text , _acepEnvironmentId :: !Text } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'AccountsContainersEnvironmentsPatch' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'acepContainerId' -- -- * 'acepFingerprint' -- -- * 'acepPayload' -- -- * 'acepAccountId' -- -- * 'acepEnvironmentId' accountsContainersEnvironmentsPatch :: Text -- ^ 'acepContainerId' -> Environment -- ^ 'acepPayload' -> Text -- ^ 'acepAccountId' -> Text -- ^ 'acepEnvironmentId' -> AccountsContainersEnvironmentsPatch accountsContainersEnvironmentsPatch pAcepContainerId_ pAcepPayload_ pAcepAccountId_ pAcepEnvironmentId_ = AccountsContainersEnvironmentsPatch' { _acepContainerId = pAcepContainerId_ , _acepFingerprint = Nothing , _acepPayload = pAcepPayload_ , _acepAccountId = pAcepAccountId_ , _acepEnvironmentId = pAcepEnvironmentId_ } -- | The GTM Container ID. acepContainerId :: Lens' AccountsContainersEnvironmentsPatch Text acepContainerId = lens _acepContainerId (\ s a -> s{_acepContainerId = a}) -- | When provided, this fingerprint must match the fingerprint of the -- environment in storage. acepFingerprint :: Lens' AccountsContainersEnvironmentsPatch (Maybe Text) acepFingerprint = lens _acepFingerprint (\ s a -> s{_acepFingerprint = a}) -- | Multipart request metadata. acepPayload :: Lens' AccountsContainersEnvironmentsPatch Environment acepPayload = lens _acepPayload (\ s a -> s{_acepPayload = a}) -- | The GTM Account ID. acepAccountId :: Lens' AccountsContainersEnvironmentsPatch Text acepAccountId = lens _acepAccountId (\ s a -> s{_acepAccountId = a}) -- | The GTM Environment ID. acepEnvironmentId :: Lens' AccountsContainersEnvironmentsPatch Text acepEnvironmentId = lens _acepEnvironmentId (\ s a -> s{_acepEnvironmentId = a}) instance GoogleRequest AccountsContainersEnvironmentsPatch where type Rs AccountsContainersEnvironmentsPatch = Environment type Scopes AccountsContainersEnvironmentsPatch = '["https://www.googleapis.com/auth/tagmanager.edit.containers"] requestClient AccountsContainersEnvironmentsPatch'{..} = go _acepAccountId _acepContainerId _acepEnvironmentId _acepFingerprint (Just AltJSON) _acepPayload tagManagerService where go = buildClient (Proxy :: Proxy AccountsContainersEnvironmentsPatchResource) mempty
rueshyna/gogol
gogol-tagmanager/gen/Network/Google/Resource/TagManager/Accounts/Containers/Environments/Patch.hs
mpl-2.0
5,241
0
18
1,198
623
368
255
105
1
#!/usr/bin/env stack -- stack --resolver lts-8.12 script {-# OPTIONS_GHC -fno-warn-missing-signatures #-} {-# OPTIONS_GHC -fno-warn-type-defaults #-} {-# LANGUAGE OverloadedStrings #-} module E6ReadUtf8WriteUtf16 where import qualified Data.ByteString as B import Data.Text.Encoding as TE e6 = main main :: IO () main = do let nameIn = "E6ReadUtf8WriteUtf16.hs" let nameOut = "/tmp/JUNK/E6ReadUtf8WriteUtf16" contents <- B.readFile nameIn let utf8In = TE.decodeUtf8 contents let utf16Out = TE.encodeUtf16LE utf8In B.writeFile nameOut utf16Out
haroldcarr/learn-haskell-coq-ml-etc
haskell/course/2017-05-snoyman-applied-haskell-at-lambdaconf/E6ReadUtf8WriteUtf16.hs
unlicense
586
0
11
109
113
60
53
15
1
-- vim: ts=2 sw=2 et : {-# LANGUAGE RankNTypes #-} {- | "Text.ParserCombinators.ReadP" instance of 'Parsing'. -} module Parsing.ReadP where import Parsing import qualified Text.ParserCombinators.ReadP as ReadP import Text.ParserCombinators.ReadP ( readP_to_S ) import Data.Char as Ch (isDigit, isSpace) -- | make 'ReadP.ReadP' an instance of 'Parsing'. instance Parsing ReadP.ReadP where try = id (<?>) = const skipMany = ReadP.skipMany skipSome = ReadP.skipMany1 unexpected = const ReadP.pfail eof = ReadP.eof notFollowedBy p = ((Just <$> p) ReadP.<++ pure Nothing) >>= maybe (pure ()) (unexpected . show) satisfy = ReadP.satisfy char = ReadP.char notChar c = ReadP.satisfy (/= c) anyChar = ReadP.get string = ReadP.string digit = ReadP.satisfy Ch.isDigit space = ReadP.satisfy Ch.isSpace many1 = ReadP.many1 manyTill = ReadP.manyTill option = ReadP.option noneOf cs = ReadP.satisfy (`notElem` cs) endOfLine = newline <|> crlf <?> "new-line" -- | parse a line feed character newline :: Parser Char newline = char '\n' <?> "lf new-line" -- | parse the seqence cr, lf, and return a line feed character crlf :: Parser Char crlf = char '\r' *> char '\n' <?> "crlf new-line" -- | run a 'Parser' computation using 'ReadP'. -- -- @parse p filename s@ runs parser @p@ on the string @s@, -- obtained from source @filePath@. -- The @filePath@ is not used at all, and may be the empty -- string, or even @undefined@. Returns either an error message, a 'String' ('Left') or a -- value of type @a@ ('Right'). parse :: Parser a -> String -> String -> Either String a parse p filename s = case readP_to_S p s of [] -> Left "couldn't parse" [(res, rest)] -> Right res parses -> Left "ambiguous parse"
phlummox/ghci-history-parser
src/Parsing/ReadP.hs
unlicense
1,912
0
10
501
414
230
184
37
3
{-# LANGUAGE TemplateHaskell #-} module Language.SillyStack.Instructions where import Control.Lens import Control.Monad.State data Thing = TInt Integer | TInstruction Instruction deriving (Eq, Ord, Show) data Instruction = PUSH Thing | POP | ADD deriving (Eq, Ord, Show) data SillyState = SillyState { _stack :: [Thing] --, _programCounter :: Integer } deriving (Eq, Ord, Show) makeLenses ''SillyState emptyState :: SillyState emptyState = SillyState [] type SillyVMT a = StateT SillyState IO a push :: Thing -> SillyVMT () push t = do s <- use stack stack .= t : s pop :: SillyVMT Thing pop = do s <- use stack stack .= init s return . last $ s add :: SillyVMT () add = do TInt x1 <- pop TInt x2 <- pop s <- use stack stack .= (TInt (x1 + x2)) : s
relrod/sillystack
src/Language/SillyStack/Instructions.hs
bsd-2-clause
858
0
12
245
305
157
148
33
1
cd ../books cd ../src runghc Converter.hs\ --title "Numeric Haskell: A Vector Tutorial" \ --language "en-us" \ --author "hackage" \ --toc "http://www.haskell.org/haskellwiki/Numeric_Haskell:_A_Vector_Tutorial" \ --folder "../books"
thlorenz/WebToInk
scripts/make-numerichaskellvectortutorial.hs
bsd-2-clause
254
0
6
46
31
16
15
-1
-1
module Analysis.Types.SortsTests where import Test.QuickCheck import Control.Applicative import Analysis.Types.Sorts import Control.Applicative() maxComplexity = 5 allSorts = foldl mkSorts [Ann,Eff] [1..(maxComplexity + 1)] where mkSorts s _ = s ++ concatMap (\x -> map (Arr x) s) s instance Arbitrary Sort where arbitrary = (!!) allSorts <$> choose (0,maxComplexity) shrink x = case x of Eff -> [] Ann -> [] Arr a b -> merge a b where merge a b = [Eff,Ann,a,b] ++ [Arr x y | (x,y) <- shrink (a,b)]
netogallo/polyvariant
test/Analysis/Types/SortsTests.hs
bsd-3-clause
548
0
13
131
240
131
109
16
1
import Data.Char (chr, ord) import Common.Utils (if') import Common.Numbers.Primes (testPrime) type Mask = [Int] substitute :: Mask -> Int -> Int substitute mask d = read (map (\x -> chr (x + ord '0')) (map (\x -> if' (x == -1) d x) mask)) goMask :: Int -> Int -> Int -> Mask -> Int goMask top dep free mask = if dep == 0 then if' (free == 3) (compute mask) maxBound else minimum $ map (\x -> goMask top (dep - 1) (free' x) (mask ++ [x])) can where free' x = free + (if' (x == -1) 1 0) can | top == dep = -1 : [1 .. 9] | dep == 1 = [1, 3, 7, 9] | otherwise = [-1 .. 9] compute :: Mask -> Int compute mask = if' (total == 8) (head primes) maxBound where can = if' (head mask == -1) [1 .. 9] [0 .. 9] converted = map (substitute mask) can primes = filter testPrime converted total = length primes main = print $ goMask 6 6 0 [] -- consider all valid masks, we can get some key observations: -- 0. the answer is 6-digit long; -- 1. the last digit must be 1,3,7,9; -- 2. there should be exactly 3 free digits, otherwise, there will be at least 3 generated numbers divisable by 3.
foreverbell/project-euler-solutions
src/51.hs
bsd-3-clause
1,159
0
15
311
482
258
224
21
2
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_HADDOCK show-extensions #-} {-| Module : $Header$ Copyright : (c) 2016 Deakin Software & Technology Innovation Lab License : BSD3 Maintainer : Rhys Adams <[email protected]> Stability : unstable Portability : portable Persistence for job states and yet-to-be-run 'ScheduleCommand's. -} module Eclogues.Persist ( -- * 'Action' Action, Context -- ** Running , withPersistDir, atomically -- * View , allIntents, allEntities, allContainers -- * Mutate , insert, updateStage, casStage, updateSatis, updateSpec, delete , scheduleIntent, deleteIntent , insertBox, sealBox, deleteBox , insertFile, deleteFilesAttachedTo , insertContainer, deleteContainer ) where import Eclogues.Prelude import Eclogues.Persist.Stage1 () import Eclogues.Scheduling.Command (ScheduleCommand) import qualified Eclogues.Job as Job import Control.Monad.Base (MonadBase, liftBase) import Control.Monad.Logger (LoggingT, runStderrLoggingT) import Control.Monad.Reader (ReaderT) import qualified Data.HashMap.Strict as HM import Database.Persist.TH (mkPersist, sqlSettings, mkMigrate, share, persistLowerCase) import Database.Persist ((==.), (=.)) import qualified Database.Persist as P import qualified Database.Persist.Sql as PSql import Database.Persist.Sqlite (withSqlitePool) import Path (toFilePath) -- Table definitions. share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase| Job name Job.Name spec Job.Spec stage Job.Stage satis Job.Satisfiability uuid UUID UniqueName name Box name Job.Name stage Job.Sealed UniqueBoxName name File name Job.FileId uuid UUID entityName Job.Name UniqueEntityFile name entityName UniqueFileUUID uuid ScheduleIntent command ScheduleCommand UniqueCommand command Container name Job.ContainerId uuid UUID UniqueContainerName name UniqueContainerUUID uuid |] -- Hide away the implementation details. -- | All 'Action's run in a Context. newtype Context = Context PSql.ConnectionPool -- | An interaction with the persistence backend. newtype Action r = Action (ReaderT PSql.SqlBackend IO r) deriving (Functor, Applicative, Monad) instance Show (Action ()) where show _ = "Action" -- | You can join up Actions by running them sequentially. instance Semigroup (Action ()) where (<>) = (*>) instance Monoid (Action ()) where mempty = pure () mappend = (<>) -- | Run some action that might persist things inside the given directory. -- Logs to stderr. withPersistDir :: Path Abs Dir -> (Context -> LoggingT IO a) -> IO a withPersistDir path f = runStderrLoggingT $ withSqlitePool ("WAL=off " <> path' <> "/eclogues.db3") 1 act where act pool = do PSql.runSqlPool (PSql.runMigration migrateAll) pool f (Context pool) path' = fromString $ toFilePath path -- | Apply some Action in a transaction. atomically :: (MonadBase IO m) => Context -> Action r -> m r atomically (Context pool) (Action a) = liftBase $ PSql.runSqlPool a pool -- | Does not insert files. insert :: Job.Status -> Action () insert status = Action $ P.insert_ job where job = Job { jobName = status ^. Job.name , jobSpec = status ^. Job.spec , jobStage = status ^. Job.stage , jobSatis = status ^. Job.satis , jobUuid = status ^. Job.uuid } insertBox :: Job.BoxStatus -> Action () insertBox status = Action . P.insert_ $ Box (status ^. Job.name) (status ^. Job.sealed) insertContainer :: Job.ContainerId -> UUID -> Action () insertContainer n = Action . P.insert_ . Container n insertFile :: Job.Name -> Job.FileId -> UUID -> Action () insertFile jn fn u = Action . P.insert_ $ File fn u jn updateStage :: Job.Name -> Job.Stage -> Action () updateStage name st = Action $ P.updateWhere [JobName ==. name] [JobStage =. st] casStage :: Job.Name -> Job.Stage -> Job.Stage -> Action () casStage name st st' = Action $ P.updateWhere [JobName ==. name, JobStage ==. st] [JobStage =. st'] updateSatis :: Job.Name -> Job.Satisfiability -> Action () updateSatis name st = Action $ P.updateWhere [JobName ==. name] [JobSatis =. st] updateSpec :: Job.Name -> Job.Spec -> Action () updateSpec name st = Action $ P.updateWhere [JobName ==. name] [JobSpec =. st] sealBox :: Job.Name -> Action () sealBox name = Action $ P.updateWhere [BoxName ==. name] [BoxStage =. Job.Sealed] delete :: Job.Name -> Action () delete = Action . P.deleteBy . UniqueName deleteBox :: Job.Name -> Action () deleteBox = Action . P.deleteBy . UniqueBoxName deleteContainer :: Job.ContainerId -> Action () deleteContainer = Action . P.deleteBy . UniqueContainerName deleteFilesAttachedTo :: Job.Name -> Action () deleteFilesAttachedTo name = Action $ P.deleteWhere [FileEntityName ==. name] scheduleIntent :: ScheduleCommand -> Action () scheduleIntent = Action . P.insert_ . ScheduleIntent deleteIntent :: ScheduleCommand -> Action () deleteIntent = Action . P.deleteBy . UniqueCommand getAll :: (PSql.SqlBackend ~ PSql.PersistEntityBackend a, PSql.PersistEntity a) => (a -> b) -> Action [b] getAll f = Action $ fmap (f . P.entityVal) <$> P.selectList [] [] allIntents :: Action [ScheduleCommand] allIntents = getAll scheduleIntentCommand allEntities :: Action [Job.AnyStatus] allEntities = do fs <- HM.fromListWith (++) <$> getAll toPair js <- getAll toMkStatus bs <- getAll toMkBoxStatus pure $ toStatus fs <$> js ++ bs where toMkStatus (Job n spec st satis uuid) = (n, Job.AJob . Job.mkStatus spec st satis uuid) toMkBoxStatus (Box n sealed) = (n, Job.ABox . Job.mkBoxStatus n sealed) toPair (File n u jn) = (jn, [(n, u)]) toStatus m (n, mk) = mk . maybe mempty HM.fromList $ HM.lookup n m allContainers :: Action [(Job.ContainerId, UUID)] allContainers = getAll (\(Container n u) -> (n, u))
rimmington/eclogues
eclogues-impl/app/api/Eclogues/Persist.hs
bsd-3-clause
6,281
0
12
1,223
1,713
929
784
104
1
{-# LANGUAGE PostfixOperators #-} {-# OPTIONS_HADDOCK prune #-} ---------------------------------------------------------------------------- -- | -- Module : ForSyDe.Atom.ExB -- Copyright : (c) George Ungureanu, 2015-2017 -- License : BSD-style (see the file LICENSE) -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : portable -- -- This module exports the core entities of the extended behavior -- layer: interfaces for atoms and common patterns of atoms. It does -- /NOT/ export any implementation or instantiation of any specific -- behavior extension type. For an overview about atoms, layers and -- patterns, please refer to the "ForSyDe.Atom" module documentation. -- -- __IMPORTANT!!!__ -- see the <ForSyDe-Atom.html#naming_conv naming convention> rules -- on how to interpret, use and develop your own constructors. ---------------------------------------------------------------------------- module ForSyDe.Atom.ExB ( -- * Atoms ExB (..), -- * Patterns res11, res12, res13, res14, res21, res22, res23, res24, res31, res32, res33, res34, res41, res42, res43, res44, res51, res52, res53, res54, res61, res62, res63, res64, res71, res72, res73, res74, res81, res82, res83, res84, filter, filter', degen, ignore11, ignore12, ignore13, ignore14, ignore21, ignore22, ignore23, ignore24, ignore31, ignore32, ignore33, ignore34, ignore41, ignore42, ignore43, ignore44 ) where import Prelude hiding (filter) import ForSyDe.Atom.Utility.Tuple infixl 4 /.\, /*\, /&\, /!\ -- | Class which defines the atoms for the extended behavior layer. -- -- As its name suggests, this layer is extending the behavior of the -- wrapped entity/function by expanding its domains set with symbols -- having clearly defined semantics (e.g. special events with known -- responses). -- -- The types associated with this layer can simply be describes as: -- -- <<fig/eqs-exb-types.png>> -- -- where \(\alpha\) is a base type and \(b\) is the type extension, -- i.e. a set of symbols with clearly defined semantics. -- -- Extended behavior atoms are functions of these types, defined as -- interfaces in the 'ExB' type class. class Functor b => ExB b where -- | Extends a value (from a layer below) with a set of symbols with -- known semantics, as described by a type instantiating this class. extend :: a -> b a -- | Basic functor operator. Lifts a function (from a layer below) -- into the domain of the extended behavior layer. -- -- <<fig/eqs-exb-atom-func.png>> (/.\) :: (a -> a') -> b a -> b a' -- | Applicative operator. Defines a resolution between two extended -- behavior symbols. -- -- <<fig/eqs-exb-atom-app.png>> (/*\) :: b (a -> a') -> b a -> b a' -- | Predicate operator. Generates a defined behavior based on an -- extended Boolean predicate. -- -- <<fig/eqs-exb-atom-phi.png>> (/&\) :: b Bool -> b a -> b a -- | Degenerate operator. Degenerates a behavior-extended value into -- a non-extended one (from a layer below), based on a kernel -- value. Used also to throw exceptions. -- -- <<fig/eqs-exb-atom-deg.png>> (/!\) :: a -> b a -> a -- | -- <<fig/eqs-exb-pattern-resolution.png>> -- -- The @res@ behavior pattern lifts a function on values to the -- extended behavior domain, and applies a resolution between two -- extended behavior symbols. -- -- Constructors: @res[1-8][1-4]@. res22 :: ExB b => (a1 -> a2 -> (a1', a2')) -- ^ function on values -> b a1 -- ^ first input -> b a2 -- ^ second input -> (b a1', b a2') -- ^ tupled output res11 f b1 = (f /.\ b1) res21 f b1 b2 = (f /.\ b1 /*\ b2) res31 f b1 b2 b3 = (f /.\ b1 /*\ b2 /*\ b3) res41 f b1 b2 b3 b4 = (f /.\ b1 /*\ b2 /*\ b3 /*\ b4) res51 f b1 b2 b3 b4 b5 = (f /.\ b1 /*\ b2 /*\ b3 /*\ b4 /*\ b5) res61 f b1 b2 b3 b4 b5 b6 = (f /.\ b1 /*\ b2 /*\ b3 /*\ b4 /*\ b5 /*\ b6) res71 f b1 b2 b3 b4 b5 b6 b7 = (f /.\ b1 /*\ b2 /*\ b3 /*\ b4 /*\ b5 /*\ b6 /*\ b7) res81 f b1 b2 b3 b4 b5 b6 b7 b8 = (f /.\ b1 /*\ b2 /*\ b3 /*\ b4 /*\ b5 /*\ b6 /*\ b7 /*\ b8) res12 f b1 = (f /.\ b1 |<) res22 f b1 b2 = (f /.\ b1 /*\ b2 |<) res32 f b1 b2 b3 = (f /.\ b1 /*\ b2 /*\ b3 |<) res42 f b1 b2 b3 b4 = (f /.\ b1 /*\ b2 /*\ b3 /*\ b4 |<) res52 f b1 b2 b3 b4 b5 = (f /.\ b1 /*\ b2 /*\ b3 /*\ b4 /*\ b5 |<) res62 f b1 b2 b3 b4 b5 b6 = (f /.\ b1 /*\ b2 /*\ b3 /*\ b4 /*\ b5 /*\ b6 |<) res72 f b1 b2 b3 b4 b5 b6 b7 = (f /.\ b1 /*\ b2 /*\ b3 /*\ b4 /*\ b5 /*\ b6 /*\ b7 |<) res82 f b1 b2 b3 b4 b5 b6 b7 b8 = (f /.\ b1 /*\ b2 /*\ b3 /*\ b4 /*\ b5 /*\ b6 /*\ b5 /*\ b8 |<) res13 f b1 = (f /.\ b1 |<<) res23 f b1 b2 = (f /.\ b1 /*\ b2 |<<) res33 f b1 b2 b3 = (f /.\ b1 /*\ b2 /*\ b3 |<<) res43 f b1 b2 b3 b4 = (f /.\ b1 /*\ b2 /*\ b3 /*\ b4 |<<) res53 f b1 b2 b3 b4 b5 = (f /.\ b1 /*\ b2 /*\ b3 /*\ b4 /*\ b5 |<<) res63 f b1 b2 b3 b4 b5 b6 = (f /.\ b1 /*\ b2 /*\ b3 /*\ b4 /*\ b5 /*\ b6 |<<) res73 f b1 b2 b3 b4 b5 b6 b7 = (f /.\ b1 /*\ b2 /*\ b3 /*\ b4 /*\ b5 /*\ b6 /*\ b7 |<<) res83 f b1 b2 b3 b4 b5 b6 b7 b8 = (f /.\ b1 /*\ b2 /*\ b3 /*\ b4 /*\ b5 /*\ b6 /*\ b5 /*\ b8 |<<) res14 f b1 = (f /.\ b1 |<<<) res24 f b1 b2 = (f /.\ b1 /*\ b2 |<<<) res34 f b1 b2 b3 = (f /.\ b1 /*\ b2 /*\ b3 |<<<) res44 f b1 b2 b3 b4 = (f /.\ b1 /*\ b2 /*\ b3 /*\ b4 |<<<) res54 f b1 b2 b3 b4 b5 = (f /.\ b1 /*\ b2 /*\ b3 /*\ b4 /*\ b5 |<<<) res64 f b1 b2 b3 b4 b5 b6 = (f /.\ b1 /*\ b2 /*\ b3 /*\ b4 /*\ b5 /*\ b6 |<<<) res74 f b1 b2 b3 b4 b5 b6 b7 = (f /.\ b1 /*\ b2 /*\ b3 /*\ b4 /*\ b5 /*\ b6 /*\ b7 |<<<) res84 f b1 b2 b3 b4 b5 b6 b7 b8 = (f /.\ b1 /*\ b2 /*\ b3 /*\ b4 /*\ b5 /*\ b6 /*\ b7 /*\ b8 |<<<) -- | Prefix name for the prefix operator '/&\'. filter p = (/&\) p -- | Same as 'filter' but takes base (non-extended) values as -- input arguments. filter' p a = (/&\) (extend p) (extend a) -- | Prefix name for the degenerate operator '/!\'. degen a = (/!\) a -- | -- <<fig/eqs-exb-pattern-ignore.png>> -- -- The @ignoreXY@ pattern takes a function of @Y + X@ arguments, @Y@ -- basic inputs followed by @X@ behavior-extended inputs. The function -- is first lifted and applied on the @X@ behavior-extended arguments, -- and the result is then degenerated using the @Y@ non-extended -- arguments as fallback. The effect is similar to "ignoring" a the -- result of a function evaluation if \(\in b\). -- -- The main application of this pattern is as extended behavior -- wrapper for stateful processes which do not "understand" extended -- behavior semantics, i.e. it simply propagates the current state -- \((\in \alpha)\) if the inputs belongs to the set of extended -- values \((\in b)\). -- -- Constructors: @ignore[1-4][1-4]@. ignore22 :: ExB b => (a1 -> a2 -> a1' -> a2' -> (a1, a2)) -- ^ function of @Y + X@ arguments -> a1 -> a2 -> b a1' -> b a2' -> (a1, a2) ignore11 f a1 b1 = degen a1 $ res11 (f a1) b1 ignore21 f a1 b1 b2 = degen a1 $ res21 (f a1) b1 b2 ignore31 f a1 b1 b2 b3 = degen a1 $ res31 (f a1) b1 b2 b3 ignore41 f a1 b1 b2 b3 b4 = degen a1 $ res41 (f a1) b1 b2 b3 b4 ignore12 f a1 a2 b1 = degen (a1, a2) $ res11 (f a1 a2) b1 ignore22 f a1 a2 b1 b2 = degen (a1, a2) $ res21 (f a1 a2) b1 b2 ignore32 f a1 a2 b1 b2 b3 = degen (a1, a2) $ res31 (f a1 a2) b1 b2 b3 ignore42 f a1 a2 b1 b2 b3 b4 = degen (a1, a2) $ res41 (f a1 a2) b1 b2 b3 b4 ignore13 f a1 a2 a3 b1 = degen (a1, a2, a3) $ res11 (f a1 a2 a3) b1 ignore23 f a1 a2 a3 b1 b2 = degen (a1, a2, a3) $ res21 (f a1 a2 a3) b1 b2 ignore33 f a1 a2 a3 b1 b2 b3 = degen (a1, a2, a3) $ res31 (f a1 a2 a3) b1 b2 b3 ignore43 f a1 a2 a3 b1 b2 b3 b4 = degen (a1, a2, a3) $ res41 (f a1 a2 a3) b1 b2 b3 b4 ignore14 f a1 a2 a3 a4 b1 = degen (a1, a2, a3, a4) $ res11 (f a1 a2 a3 a4) b1 ignore24 f a1 a2 a3 a4 b1 b2 = degen (a1, a2, a3, a4) $ res21 (f a1 a2 a3 a4) b1 b2 ignore34 f a1 a2 a3 a4 b1 b2 b3 = degen (a1, a2, a3, a4) $ res31 (f a1 a2 a3 a4) b1 b2 b3 ignore44 f a1 a2 a3 a4 b1 b2 b3 b4 = degen (a1, a2, a3, a4) $ res41 (f a1 a2 a3 a4) b1 b2 b3 b4
forsyde/forsyde-atom
src/ForSyDe/Atom/ExB.hs
bsd-3-clause
8,397
0
13
2,291
2,624
1,427
1,197
-1
-1
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DefaultSignatures #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FunctionalDependencies #-} module Language.Granule.Syntax.FirstParameter where import GHC.Generics class FirstParameter a e | a -> e where getFirstParameter :: a -> e setFirstParameter :: e -> a -> a default getFirstParameter :: (Generic a, GFirstParameter (Rep a) e) => a -> e getFirstParameter a = getFirstParameter' . from $ a default setFirstParameter :: (Generic a, GFirstParameter (Rep a) e) => e -> a -> a setFirstParameter e a = to . setFirstParameter' e . from $ a class GFirstParameter f e where getFirstParameter' :: f a -> e setFirstParameter' :: e -> f a -> f a instance {-# OVERLAPPING #-} GFirstParameter (K1 i e) e where getFirstParameter' (K1 a) = a setFirstParameter' e (K1 _) = K1 e instance {-# OVERLAPPABLE #-} GFirstParameter (K1 i a) e where getFirstParameter' _ = undefined setFirstParameter' _ _ = undefined instance GFirstParameter a e => GFirstParameter (M1 i c a) e where getFirstParameter' (M1 a) = getFirstParameter' a setFirstParameter' e (M1 a) = M1 $ setFirstParameter' e a instance (GFirstParameter a e, GFirstParameter b e) => GFirstParameter (a :+: b) e where getFirstParameter' (L1 a) = getFirstParameter' a getFirstParameter' (R1 a) = getFirstParameter' a setFirstParameter' e (L1 a) = L1 $ setFirstParameter' e a setFirstParameter' e (R1 a) = R1 $ setFirstParameter' e a instance GFirstParameter a e => GFirstParameter (a :*: b) e where getFirstParameter' (a :*: _) = getFirstParameter' a setFirstParameter' e (a :*: b) = (setFirstParameter' e a :*: b) instance (GFirstParameter U1 String) where getFirstParameter' _ = "" setFirstParameter' _ e = e
dorchard/gram_lang
frontend/src/Language/Granule/Syntax/FirstParameter.hs
bsd-3-clause
1,825
1
11
334
600
305
295
-1
-1
{-# LANGUAGE CPP #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DoAndIfThenElse #-} {-# LANGUAGE ScopedTypeVariables #-} import Common import Database.PostgreSQL.Simple.Copy import Database.PostgreSQL.Simple.FromField (FromField) import Database.PostgreSQL.Simple.HStore import Database.PostgreSQL.Simple.Internal (breakOnSingleQuestionMark) import Database.PostgreSQL.Simple.Types(Query(..),Values(..), PGArray(..)) import qualified Database.PostgreSQL.Simple.Transaction as ST import Control.Applicative import Control.Exception as E import Control.Monad import Data.Char import Data.List (concat, sort) import Data.IORef import Data.Monoid ((<>)) import Data.String (fromString) import Data.Typeable import GHC.Generics (Generic) import Data.Aeson import Data.ByteString (ByteString) import qualified Data.ByteString as B import qualified Data.ByteString.Lazy.Char8 as BL import Data.CaseInsensitive (CI) import qualified Data.CaseInsensitive as CI import Data.Map (Map) import qualified Data.Map as Map import Data.Text(Text) import qualified Data.Text.Encoding as T import qualified Data.Vector as V import System.FilePath import System.Timeout(timeout) import Data.Time(getCurrentTime, diffUTCTime) import Test.Tasty import Test.Tasty.Golden import Notify import Serializable import Time tests :: TestEnv -> TestTree tests env = testGroup "tests" $ map ($ env) [ testBytea , testCase "ExecuteMany" . testExecuteMany , testCase "Fold" . testFold , testCase "Notify" . testNotify , testCase "Serializable" . testSerializable , testCase "Time" . testTime , testCase "Array" . testArray , testCase "Array of nullables" . testNullableArray , testCase "HStore" . testHStore , testCase "citext" . testCIText , testCase "JSON" . testJSON , testCase "Question mark escape" . testQM , testCase "Savepoint" . testSavepoint , testCase "Unicode" . testUnicode , testCase "Values" . testValues , testCase "Copy" . testCopy , testCopyFailures , testCase "Double" . testDouble , testCase "1-ary generic" . testGeneric1 , testCase "2-ary generic" . testGeneric2 , testCase "3-ary generic" . testGeneric3 , testCase "Timeout" . testTimeout ] testBytea :: TestEnv -> TestTree testBytea TestEnv{..} = testGroup "Bytea" [ testStr "empty" [] , testStr "\"hello\"" $ map (fromIntegral . fromEnum) ("hello" :: String) , testStr "ascending" [0..255] , testStr "descending" [255,254..0] , testStr "ascending, doubled up" $ doubleUp [0..255] , testStr "descending, doubled up" $ doubleUp [255,254..0] ] where testStr label bytes = testCase label $ do let bs = B.pack bytes [Only h] <- query conn "SELECT md5(?::bytea)" [Binary bs] assertBool "Haskell -> SQL conversion altered the string" $ md5 bs == h [Only (Binary r)] <- query conn "SELECT ?::bytea" [Binary bs] assertBool "SQL -> Haskell conversion altered the string" $ bs == r doubleUp = concatMap (\x -> [x, x]) testExecuteMany :: TestEnv -> Assertion testExecuteMany TestEnv{..} = do execute_ conn "CREATE TEMPORARY TABLE tmp_executeMany (i INT, t TEXT, b BYTEA)" let rows :: [(Int, String, Binary ByteString)] rows = [ (1, "hello", Binary "bye") , (2, "world", Binary "\0\r\t\n") , (3, "?", Binary "") ] count <- executeMany conn "INSERT INTO tmp_executeMany VALUES (?, ?, ?)" rows count @?= fromIntegral (length rows) rows' <- query_ conn "SELECT * FROM tmp_executeMany" rows' @?= rows return () testFold :: TestEnv -> Assertion testFold TestEnv{..} = do xs <- fold_ conn "SELECT generate_series(1,10000)" [] $ \xs (Only x) -> return (x:xs) reverse xs @?= ([1..10000] :: [Int]) ref <- newIORef [] forEach conn "SELECT * FROM generate_series(1,?) a, generate_series(1,?) b" (100 :: Int, 50 :: Int) $ \(a :: Int, b :: Int) -> do xs <- readIORef ref writeIORef ref $! (a,b):xs xs <- readIORef ref reverse xs @?= [(a,b) | a <- [1..100], b <- [1..50]] -- Make sure fold propagates our exception. ref <- newIORef [] True <- expectError (== TestException) $ forEach_ conn "SELECT generate_series(1,10)" $ \(Only a) -> if a == 5 then do -- Cause a SQL error to trip up CLOSE. True <- expectError isSyntaxError $ execute_ conn "asdf" True <- expectError ST.isFailedTransactionError $ (query_ conn "SELECT 1" :: IO [(Only Int)]) throwIO TestException else do xs <- readIORef ref writeIORef ref $! (a :: Int) : xs xs <- readIORef ref reverse xs @?= [1..4] withTransaction conn $ replicateM_ 2 $ do xs <- fold_ conn "VALUES (1), (2), (3), (4), (5)" [] $ \xs (Only x) -> return (x:xs) reverse xs @?= ([1..5] :: [Int]) ref <- newIORef [] forEach_ conn "SELECT generate_series(1,101)" $ \(Only a) -> forEach_ conn "SELECT generate_series(1,55)" $ \(Only b) -> do xs <- readIORef ref writeIORef ref $! (a :: Int, b :: Int) : xs xs <- readIORef ref reverse xs @?= [(a,b) | a <- [1..101], b <- [1..55]] xs <- fold_ conn "SELECT 1 WHERE FALSE" [] $ \xs (Only x) -> return (x:xs) xs @?= ([] :: [Int]) -- TODO: add more complete tests, e.g.: -- -- * Fold in a transaction -- -- * Fold in a transaction after a previous fold has been performed -- -- * Nested fold return () queryFailure :: forall a. (FromField a, Typeable a, Show a) => Connection -> Query -> a -> Assertion queryFailure conn q resultType = do x :: Either SomeException [Only a] <- E.try $ query_ conn q case x of Left _ -> return () Right val -> assertFailure ("Did not fail as expected: " ++ show q ++ " :: " ++ show (typeOf resultType) ++ " -> " ++ show val) testArray :: TestEnv -> Assertion testArray TestEnv{..} = do xs <- query_ conn "SELECT '{1,2,3,4}'::_int4" xs @?= [Only (V.fromList [1,2,3,4 :: Int])] xs <- query_ conn "SELECT '{{1,2},{3,4}}'::_int4" xs @?= [Only (V.fromList [V.fromList [1,2], V.fromList [3,4 :: Int]])] queryFailure conn "SELECT '{1,2,3,4}'::_int4" (undefined :: V.Vector Bool) queryFailure conn "SELECT '{{1,2},{3,4}}'::_int4" (undefined :: V.Vector Int) testNullableArray :: TestEnv -> Assertion testNullableArray TestEnv{..} = do xs <- query_ conn "SELECT '{sometext, \"NULL\"}'::_text" xs @?= [Only (V.fromList ["sometext", "NULL" :: Text])] xs <- query_ conn "SELECT '{sometext, NULL}'::_text" xs @?= [Only (V.fromList [Just "sometext", Nothing :: Maybe Text])] queryFailure conn "SELECT '{sometext, NULL}'::_text" (undefined :: V.Vector Text) testHStore :: TestEnv -> Assertion testHStore TestEnv{..} = do execute_ conn "CREATE EXTENSION IF NOT EXISTS hstore" roundTrip [] roundTrip [("foo","bar"),("bar","baz"),("baz","hello")] roundTrip [("fo\"o","bar"),("b\\ar","baz"),("baz","\"value\\with\"escapes")] where roundTrip :: [(Text,Text)] -> Assertion roundTrip xs = do let m = Only (HStoreMap (Map.fromList xs)) m' <- query conn "SELECT ?::hstore" m [m] @?= m' testCIText :: TestEnv -> Assertion testCIText TestEnv{..} = do execute_ conn "CREATE EXTENSION IF NOT EXISTS citext" roundTrip (CI.mk "") roundTrip (CI.mk "UPPERCASE") roundTrip (CI.mk "lowercase") where roundTrip :: (CI Text) -> Assertion roundTrip cit = do let toPostgres = Only cit fromPostgres <- query conn "SELECT ?::citext" toPostgres [toPostgres] @?= fromPostgres testJSON :: TestEnv -> Assertion testJSON TestEnv{..} = do roundTrip (Map.fromList [] :: Map Text Text) roundTrip (Map.fromList [("foo","bar"),("bar","baz"),("baz","hello")] :: Map Text Text) roundTrip (Map.fromList [("fo\"o","bar"),("b\\ar","baz"),("baz","\"value\\with\"escapes")] :: Map Text Text) roundTrip (V.fromList [1,2,3,4,5::Int]) roundTrip ("foo" :: Text) roundTrip (42 :: Int) where roundTrip :: ToJSON a => a -> Assertion roundTrip a = do let js = Only (toJSON a) js' <- query conn "SELECT ?::json" js [js] @?= js' testQM :: TestEnv -> Assertion testQM TestEnv{..} = do -- Just test on a single string let testQuery' b = "testing for ?" <> b <> " and making sure " testQueryDoubleQM = testQuery' "?" testQueryRest = "? is substituted" testQuery = fromString $ testQueryDoubleQM <> testQueryRest -- expect the entire first part with double QMs replaced with literal '?' expected = (fromString $ testQuery' "", fromString testQueryRest) tried = breakOnSingleQuestionMark testQuery errMsg = concat [ "Failed to break on single question mark exclusively:\n" , "expected: ", show expected , "result: ", show tried ] assertBool errMsg $ tried == expected -- Let's also test the question mark operators in action -- ? -> Does the string exist as a top-level key within the JSON value? positiveQuery "SELECT ?::jsonb ?? ?" (testObj, "foo" :: Text) negativeQuery "SELECT ?::jsonb ?? ?" (testObj, "baz" :: Text) negativeQuery "SELECT ?::jsonb ?? ?" (toJSON numArray, "1" :: Text) -- ?| -> Do any of these array strings exist as top-level keys? positiveQuery "SELECT ?::jsonb ??| ?" (testObj, PGArray ["nope","bar","6" :: Text]) negativeQuery "SELECT ?::jsonb ??| ?" (testObj, PGArray ["nope","6" :: Text]) negativeQuery "SELECT ?::jsonb ??| ?" (toJSON numArray, PGArray ["1","2","6" :: Text]) -- ?& -> Do all of these array strings exist as top-level keys? positiveQuery "SELECT ?::jsonb ??& ?" (testObj, PGArray ["foo","bar","quux" :: Text]) positiveQuery "SELECT ?::jsonb ??& ?" (testObj, PGArray ["foo","bar" :: Text]) negativeQuery "SELECT ?::jsonb ??& ?" (testObj, PGArray ["foo","bar","baz" :: Text]) negativeQuery "SELECT ?::jsonb ??& ?" (toJSON numArray, PGArray ["1","2","3","4","5" :: Text]) -- Format error for 2 question marks, not 4 True <- expectError (isFormatError 2) $ (query conn "SELECT ?::jsonb ?? ?" $ Only testObj :: IO [Only Bool]) return () where positiveQuery :: ToRow a => Query -> a -> Assertion positiveQuery = boolQuery True negativeQuery :: ToRow a => Query -> a -> Assertion negativeQuery = boolQuery False numArray :: [Int] numArray = [1,2,3,4,5] boolQuery :: ToRow a => Bool -> Query -> a -> Assertion boolQuery b t x = do a <- query conn t x [Only b] @?= a testObj = toJSON (Map.fromList [("foo",toJSON (1 :: Int)) ,("bar",String "baz") ,("quux",toJSON [1 :: Int,2,3,4,5])] :: Map Text Value ) testSavepoint :: TestEnv -> Assertion testSavepoint TestEnv{..} = do True <- expectError ST.isNoActiveTransactionError $ withSavepoint conn $ return () let getRows :: IO [Int] getRows = map fromOnly <$> query_ conn "SELECT a FROM tmp_savepoint ORDER BY a" withTransaction conn $ do execute_ conn "CREATE TEMPORARY TABLE tmp_savepoint (a INT UNIQUE)" execute_ conn "INSERT INTO tmp_savepoint VALUES (1)" [1] <- getRows withSavepoint conn $ do execute_ conn "INSERT INTO tmp_savepoint VALUES (2)" [1,2] <- getRows return () [1,2] <- getRows withSavepoint conn $ do execute_ conn "INSERT INTO tmp_savepoint VALUES (3)" [1,2,3] <- getRows True <- expectError isUniqueViolation $ execute_ conn "INSERT INTO tmp_savepoint VALUES (2)" True <- expectError ST.isFailedTransactionError getRows -- Body returning successfully after handling error, -- but 'withSavepoint' will roll back without complaining. return () -- Rolling back clears the error condition. [1,2] <- getRows -- 'withSavepoint' will roll back after an exception, even if the -- exception wasn't SQL-related. True <- expectError (== TestException) $ withSavepoint conn $ do execute_ conn "INSERT INTO tmp_savepoint VALUES (3)" [1,2,3] <- getRows throwIO TestException [1,2] <- getRows -- Nested savepoint can be rolled back while the -- outer effects are retained. withSavepoint conn $ do execute_ conn "INSERT INTO tmp_savepoint VALUES (3)" True <- expectError isUniqueViolation $ withSavepoint conn $ do execute_ conn "INSERT INTO tmp_savepoint VALUES (4)" [1,2,3,4] <- getRows execute_ conn "INSERT INTO tmp_savepoint VALUES (4)" [1,2,3] <- getRows return () [1,2,3] <- getRows return () -- Transaction committed successfully, even though there were errors -- (but we rolled them back). [1,2,3] <- getRows return () testUnicode :: TestEnv -> Assertion testUnicode TestEnv{..} = do let q = Query . T.encodeUtf8 -- Handle encoding ourselves to ensure -- the table gets created correctly. let messages = map Only ["ΠΏΡ€ΠΈΠ²Π΅Ρ‚","ΠΌΠΈΡ€"] :: [Only Text] execute_ conn (q "CREATE TEMPORARY TABLE ру́сский (сообщСниС TEXT)") executeMany conn "INSERT INTO ру́сский (сообщСниС) VALUES (?)" messages messages' <- query_ conn "SELECT сообщСниС FROM ру́сский" sort messages @?= sort messages' testValues :: TestEnv -> Assertion testValues TestEnv{..} = do execute_ conn "CREATE TEMPORARY TABLE values_test (x int, y text)" test (Values ["int4","text"] []) test (Values ["int4","text"] [(1,"hello")]) test (Values ["int4","text"] [(1,"hello"),(2,"world")]) test (Values ["int4","text"] [(1,"hello"),(2,"world"),(3,"goodbye")]) test (Values [] [(1,"hello")]) test (Values [] [(1,"hello"),(2,"world")]) test (Values [] [(1,"hello"),(2,"world"),(3,"goodbye")]) where test :: Values (Int, Text) -> Assertion test table@(Values _ vals) = do execute conn "INSERT INTO values_test ?" (Only table) vals' <- query_ conn "DELETE FROM values_test RETURNING *" sort vals @?= sort vals' testCopy :: TestEnv -> Assertion testCopy TestEnv{..} = do execute_ conn "CREATE TEMPORARY TABLE copy_test (x int, y text)" copy_ conn "COPY copy_test FROM STDIN (FORMAT CSV)" mapM_ (putCopyData conn) copyRows putCopyEnd conn copy_ conn "COPY copy_test FROM STDIN (FORMAT CSV)" mapM_ (putCopyData conn) abortRows putCopyError conn "aborted" -- Hmm, does postgres always produce \n as an end-of-line here, or -- are there cases where it will use a \r\n as well? copy_ conn "COPY copy_test TO STDOUT (FORMAT CSV)" rows <- loop [] sort rows @?= sort copyRows -- Now, let's just verify that the connection state is back to ready, -- so that we can issue more queries: [Only (x::Int)] <- query_ conn "SELECT 2 + 2" x @?= 4 where copyRows = ["1,foo\n" ,"2,bar\n"] abortRows = ["3,baz\n"] loop rows = do mrow <- getCopyData conn case mrow of CopyOutDone _ -> return rows CopyOutRow row -> loop (row:rows) testCopyFailures :: TestEnv -> TestTree testCopyFailures env = testGroup "Copy failures" $ map ($ env) [ testCopyUniqueConstraintError , testCopyMalformedError ] goldenTest :: TestName -> IO BL.ByteString -> TestTree goldenTest testName = goldenVsString testName (resultsDir </> fileName<.>"expected") where resultsDir = "test" </> "results" fileName = map normalize testName normalize c | not (isAlpha c) = '-' | otherwise = c -- | Test that we provide a sensible error message on failure testCopyUniqueConstraintError :: TestEnv -> TestTree testCopyUniqueConstraintError TestEnv{..} = goldenTest "unique constraint violation" $ handle (\(SomeException exc) -> return $ BL.pack $ show exc) $ do execute_ conn "CREATE TEMPORARY TABLE copy_unique_constraint_error_test (x int PRIMARY KEY, y text)" copy_ conn "COPY copy_unique_constraint_error_test FROM STDIN (FORMAT CSV)" mapM_ (putCopyData conn) copyRows _n <- putCopyEnd conn return BL.empty where copyRows = ["1,foo\n" ,"2,bar\n" ,"1,baz\n"] testCopyMalformedError :: TestEnv -> TestTree testCopyMalformedError TestEnv{..} = goldenTest "malformed input" $ handle (\(SomeException exc) -> return $ BL.pack $ show exc) $ do execute_ conn "CREATE TEMPORARY TABLE copy_malformed_input_error_test (x int PRIMARY KEY, y text)" copy_ conn "COPY copy_unique_constraint_error_test FROM STDIN (FORMAT CSV)" mapM_ (putCopyData conn) copyRows _n <- putCopyEnd conn return BL.empty where copyRows = ["1,foo\n" ,"2,bar\n" ,"z,baz\n"] testTimeout :: TestEnv -> Assertion testTimeout TestEnv{..} = withConn $ \c -> do start_t <- getCurrentTime res <- timeout 200000 $ do withTransaction c $ do query_ c "SELECT pg_sleep(1)" :: IO [Only ()] end_t <- getCurrentTime assertBool "Timeout did not occur" (res == Nothing) #if !defined(mingw32_HOST_OS) -- At the moment, you cannot timely abandon queries with async exceptions on -- Windows. let d = end_t `diffUTCTime` start_t assertBool "Timeout didn't work in a timely fashion" (0.1 < d && d < 0.6) #endif testDouble :: TestEnv -> Assertion testDouble TestEnv{..} = do [Only (x :: Double)] <- query_ conn "SELECT 'NaN'::float8" assertBool "expected NaN" (isNaN x) [Only (x :: Double)] <- query_ conn "SELECT 'Infinity'::float8" x @?= (1 / 0) [Only (x :: Double)] <- query_ conn "SELECT '-Infinity'::float8" x @?= (-1 / 0) testGeneric1 :: TestEnv -> Assertion testGeneric1 TestEnv{..} = do roundTrip conn (Gen1 123) where roundTrip conn x0 = do r <- query conn "SELECT ?::int" (x0 :: Gen1) r @?= [x0] testGeneric2 :: TestEnv -> Assertion testGeneric2 TestEnv{..} = do roundTrip conn (Gen2 123 "asdf") where roundTrip conn x0 = do r <- query conn "SELECT ?::int, ?::text" x0 r @?= [x0] testGeneric3 :: TestEnv -> Assertion testGeneric3 TestEnv{..} = do roundTrip conn (Gen3 123 "asdf" True) where roundTrip conn x0 = do r <- query conn "SELECT ?::int, ?::text, ?::bool" x0 r @?= [x0] data Gen1 = Gen1 Int deriving (Show,Eq,Generic) instance FromRow Gen1 instance ToRow Gen1 data Gen2 = Gen2 Int Text deriving (Show,Eq,Generic) instance FromRow Gen2 instance ToRow Gen2 data Gen3 = Gen3 Int Text Bool deriving (Show,Eq,Generic) instance FromRow Gen3 instance ToRow Gen3 data TestException = TestException deriving (Eq, Show, Typeable) instance Exception TestException expectError :: Exception e => (e -> Bool) -> IO a -> IO Bool expectError p io = (io >> return False) `E.catch` \ex -> if p ex then return True else throwIO ex isUniqueViolation :: SqlError -> Bool isUniqueViolation SqlError{..} = sqlState == "23505" isSyntaxError :: SqlError -> Bool isSyntaxError SqlError{..} = sqlState == "42601" isFormatError :: Int -> FormatError -> Bool isFormatError i FormatError{..} | null fmtMessage = False | otherwise = fmtMessage == concat [ show i , " single '?' characters, but " , show (length fmtParams) , " parameters" ] ------------------------------------------------------------------------ -- | Action for connecting to the database that will be used for testing. -- -- Note that some tests, such as Notify, use multiple connections, and assume -- that 'testConnect' connects to the same database every time it is called. testConnect :: IO Connection testConnect = connectPostgreSQL "" withTestEnv :: (TestEnv -> IO a) -> IO a withTestEnv cb = withConn $ \conn -> cb TestEnv { conn = conn , withConn = withConn } where withConn = bracket testConnect close main :: IO () main = withTestEnv $ defaultMain . tests
tomjaguarpaw/postgresql-simple
test/Main.hs
bsd-3-clause
21,271
0
19
5,860
6,036
3,078
2,958
-1
-1
{-# LANGUAGE Rank2Types #-} {-| 'Snap.Extension.ConnectionPool' exports the 'MonadConnectionPool' interface which allows you to use HDBC connections in your application. These connections are pooled and only created once. The interface's only operation is 'withConnection'. 'Snap.Extension.ConnectionPool.ConnectionPool' contains the only implementation of this interface and can be used to turn your application's monad into a 'MonadConnectionPool'. -} module Snap.Extension.ConnectionPool ( MonadConnectionPool(..) , IsConnectionPoolState(..)) where import Control.Monad.Trans import Database.HDBC import Snap.Types ------------------------------------------------------------------------------ -- | The 'MonadConnectionPool' type class. Minimal complete definition: -- 'withConnection'. class MonadIO m => MonadConnectionPool m where -- | Given an action, wait for an available connection from the pool and -- execute the action. Return the result. withConnection :: (forall c. IConnection c => c -> IO a) -> m a ------------------------------------------------------------------------------ class IsConnectionPoolState a where withConnectionFromPool :: MonadIO m => (forall c. IConnection c => c -> IO b) -> a -> m b
duairc/snap-extensions
src/Snap/Extension/ConnectionPool.hs
bsd-3-clause
1,280
0
13
205
151
84
67
11
0
module Data.Iteratee.List.IO ( defaultBufferSize , enumHandleSize , enumHandle , enumFileSize , enumFile ) where ------------------------------------------------------------------------ -- Imports ------------------------------------------------------------------------ import Data.Iteratee.Base import Data.Iteratee.Exception import Data.Iteratee.IO (defaultBufferSize, enumHandleWithSize) import Data.Monoid (Monoid (..)) import Control.Exception import Control.Monad import Control.Monad.CatchIO (MonadCatchIO (..)) import qualified Control.Monad.CatchIO as CIO import Control.Monad.IO.Class import Foreign.C import Foreign.Ptr import Foreign.Storable import Foreign.Marshal.Alloc import Foreign.Marshal.Array import System.IO ------------------------------------------------------------------------ -- IO Enumerators ------------------------------------------------------------------------ enumHandleSize :: (Storable a) => Int -> Handle -> Enumerator [a] IO b enumHandleSize = enumHandleWithSize peekArray {-# INLINE enumHandleSize #-} {-# RULES "enumHandleSize/String" enumHandleSize = enumHandleSizeString #-} enumHandleSizeString :: Int -> Handle -> Enumerator String IO a enumHandleSizeString = enumHandleWithSize (flip (curry peekCAStringLen)) {-# INLINE enumHandleSizeString #-} enumHandle :: (Storable a) => Handle -> Enumerator [a] IO b enumHandle = enumHandleSize defaultBufferSize {-# INLINE enumHandle #-} enumFileSize :: (Storable a) => Int -> FilePath -> Enumerator [a] IO b enumFileSize size file iter = bracket (openFile file ReadMode) (hClose) (\hand -> enumHandleSize size hand iter) {-# INLINE enumFileSize #-} enumFile :: (Storable a) => FilePath -> Enumerator [a] IO b enumFile = enumFileSize defaultBufferSize {-# INLINE enumFile #-}
tanimoto/iteratee
src/Data/Iteratee/List/IO.hs
bsd-3-clause
1,781
0
9
202
379
222
157
40
1
{-# LANGUAGE RecordWildCards #-} {-# LANGUAGE ViewPatterns #-} {-# OPTIONS_GHC -fno-warn-name-shadowing #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} {-# LANGUAGE TupleSections #-} module Ivory.ModelCheck.Ivory2CVC4 -- ( modelCheckMod ) where import Prelude () import Prelude.Compat hiding (exp) import Control.Monad (forM, forM_, void, when) import Data.List (nub) import qualified Data.Map as M import Data.Maybe import qualified Ivory.Language.Array as I import qualified Ivory.Language.Cast as I import qualified Ivory.Language.Syntax as I import Ivory.Opts.BitShift (bitShiftFold) import Ivory.Opts.ConstFold (constFold) import Ivory.Opts.DivZero (divZeroFold) import Ivory.Opts.Index (ixFold) import Ivory.Opts.Overflow (overflowFold) import Ivory.ModelCheck.CVC4 import Ivory.ModelCheck.Monad -- XXX testing -- import Debug.Trace -------------------------------------------------------------------------------- modelCheckProc :: [I.Module] -> I.Proc -> ModelCheck () modelCheckProc mods p = do forM_ mods $ \m -> do mapM_ toStruct (getVisible $ I.modStructs m) mapM_ addStruct (getVisible $ I.modStructs m) mapM_ addImport (I.modImports m) mapM_ (addProc Defined) (getVisible $ I.modProcs m) mapM_ toArea (getVisible $ I.modAreas m) modelCheckProc' . overflowFold . divZeroFold . bitShiftFold . ixFold . constFold $ p where getVisible ps = I.public ps ++ I.private ps addImport e = addProc Imported I.Proc { I.procSym = I.importSym e , I.procRetTy = err "addImport" "tried to use return type" , I.procArgs = I.importArgs e , I.procBody = [] , I.procRequires = I.importRequires e , I.procEnsures = I.importEnsures e } -------------------------------------------------------------------------------- toArea :: I.Area -> ModelCheck () toArea I.Area { I.areaSym = sym , I.areaType = ty , I.areaInit = init } = void $ addEnvVar ty sym -------------------------------------------------------------------------------- modelCheckProc' :: I.Proc -> ModelCheck () modelCheckProc' I.Proc { I.procSym = sym , I.procRetTy = ret , I.procArgs = args , I.procBody = body , I.procRequires = requires , I.procEnsures = ensures } = do mapM_ toParam args mapM_ toRequire requires mapM_ (toBody ensures) body -------------------------------------------------------------------------------- toParam :: I.Typed I.Var -> ModelCheck () toParam (I.Typed t val) = do v <- addEnvVar t (toVar val) assertBoundedVar t (var v) -------------------------------------------------------------------------------- toRequire :: I.Require -> ModelCheck () toRequire (I.Require cond) = do e <- toAssertion id cond addInvariant e -------------------------------------------------------------------------------- toEnsure :: I.Ensure -> ModelCheck Expr toEnsure (I.Ensure cond) = toAssertion id cond -------------------------------------------------------------------------------- toAssertion :: (I.Expr -> I.Expr) -> I.Cond -> ModelCheck Expr toAssertion trans cond = case cond of I.CondBool exp -> toExpr I.TyBool (trans exp) I.CondDeref t exp var c -> do e <- toExpr t exp toAssertion (subst [(var, exp)] . trans) c -------------------------------------------------------------------------------- -- | Symbolically execute statements, carrying the return requirements forward -- to each location that there is a return statement. toBody :: [I.Ensure] -> I.Stmt -> ModelCheck () toBody ens stmt = case stmt of I.IfTE exp blk0 blk1 -> toIfTE ens exp blk0 blk1 I.Assume exp -> addInvariant =<< toExpr I.TyBool exp I.Assert exp -> addQuery =<< toExpr I.TyBool exp I.CompilerAssert exp -> addQuery =<< toExpr I.TyBool exp I.Return (I.Typed t e) -> snapshotRefs >> toReturn ens t e I.ReturnVoid -> snapshotRefs >> return () I.Deref t v ref -> toDeref t v ref I.Store t ptr exp -> toStore t ptr exp I.RefCopy t ptr exp -> toStore t ptr exp -- XXX is this correct? I.Assign t v exp -> toAssign t v exp I.Call t retV nm args -> toCall t retV nm args I.Local t v inits -> toLocal t v inits I.AllocRef t ref name -> toAlloc t ref name I.Loop m v exp inc blk -> toLoop ens m v exp inc blk I.Comment (I.SourcePos src) -> setSrcLoc src I.Comment _ -> return () I.Break -> err "toBody" (show stmt) I.Forever _ -> err "toBody" (show stmt) -- TODO: Need to interpret the zero initializer here I.RefZero t ptr -> err "refZero" (show stmt) toReturn :: [I.Ensure] -> I.Type -> I.Expr -> ModelCheck () toReturn ens t exp = do e <- toExpr t exp v <- addEnvVar t "retval" addInvariant (var v .== e) queryEnsures ens t exp toDeref :: I.Type -> I.Var -> I.Expr -> ModelCheck () toDeref t v ref = do v' <- addEnvVar t (toVar v) e <- toExpr t ref assertBoundedVar t (var v') addInvariant (var v' .== e) toAlloc :: I.Type -> I.Var -> I.Name -> ModelCheck () toAlloc t ref name = do v' <- addEnvVar t (toVar ref) n' <- lookupVar (toName name) addInvariant (var v' .== var n') toStore :: I.Type -> I.Expr -> I.Expr -> ModelCheck () toStore t e@(I.ExpIndex{}) exp = toSelectStore t e exp toStore t e@(I.ExpLabel{}) exp = toSelectStore t e exp toStore t ptr exp = do v' <- updateEnvRef t ptr e <- toExpr t exp addInvariant (var v' .== e) toSelectStore :: I.Type -> I.Expr -> I.Expr -> ModelCheck () toSelectStore t f exp = do f' <- toExpr t f v <- toStoreRef t f e <- toExpr t exp addInvariant (var v .== store f' e) toLocal :: I.Type -> I.Var -> I.Init -> ModelCheck () toLocal t v inits = do v' <- addEnvVar t (toVar v) is <- toInit t inits addInvariant (var v' .== is) toInit :: I.Type -> I.Init -> ModelCheck Expr toInit ty init = case init of I.InitZero -> case ty of I.TyArr _ _ -> fmap var $ incReservedVar =<< toType ty I.TyStruct _-> fmap var $ incReservedVar =<< toType ty I.TyBool -> return false _ -> return $ intLit 0 I.InitExpr t exp -> toExpr t exp I.InitArray is _ -> do let (I.TyArr k t) = ty tv <- fmap var $ incReservedVar =<< toType ty forM_ (zip [0..] is) $ \ (ix,i) -> do e <- toInit t i addInvariant (index (intLit ix) tv .== e) return tv I.InitStruct fs -> do tv <- fmap var $ incReservedVar =<< toType ty let (I.TyStruct s) = ty forM_ fs $ \ (f, i) -> do structs <- getStructs case M.lookup s structs >>= lookupField f of Just t -> do e <- toInit t i addInvariant (field (var f) tv .== e) Nothing -> error $ "I don't know how to initialize field " ++ f ++ " of struct " ++ s return tv where lookupField f (I.Struct _ tfs) = listToMaybe [ t | I.Typed t f' <- tfs, f == f' ] lookupField f (I.Abstract _ _) = Nothing toAssign :: I.Type -> I.Var -> I.Expr -> ModelCheck () toAssign t v exp = do e <- toExpr t exp v' <- addEnvVar t (toVar v) addInvariant (var v' .== e) toCall :: I.Type -> Maybe I.Var -> I.Name -> [I.Typed I.Expr] -> ModelCheck () toCall t retV nm args = do (d, p) <- lookupProc $ toName nm case d of Imported -> toCallContract t retV p args Defined -> do inline <- askInline if inline then toCallInline t retV p args else toCallContract t retV p args toCallInline :: I.Type -> Maybe I.Var -> I.Proc -> [I.Typed I.Expr] -> ModelCheck () toCallInline t retV (I.Proc {..}) args = do argEnv <- forM (zip procArgs args) $ \ (formal, actual) -> do e <- toExpr (I.tType actual) (I.tValue actual) v <- addEnvVar (I.tType formal) (toVar $ I.tValue formal) addInvariant (var v .== e) return (toVar (I.tValue formal), e) withLocalReturnRefs $ do mapM_ (toBody []) procBody snapshotRefs -- incase of implicit retVoid rs <- getReturnRefs forM_ (M.toList rs) $ \ ((t, r), bvs) -> do -- XXX: can we rely on Refs always being passed as a Var? case lookup r argEnv of Just (Var x) -> do r' <- addEnvVar t x -- x may point to any number of values upon returning from a call addInvariant $ foldr1 (.&&) [b .=> (var r' .== var v) | (b,v) <- bvs] _ -> return () case retV of Nothing -> return () Just v -> do r <- addEnvVar t (toVar v) rv <- lookupVar (toVar I.retval) addInvariant (var r .== var rv) toCallContract :: I.Type -> Maybe I.Var -> I.Proc -> [I.Typed I.Expr] -> ModelCheck () toCallContract t retV pc args = do let su = [ (v, e) | (I.Typed _ v, I.Typed _ e) <- zip (I.procArgs pc) args] checkRequires su $ I.procRequires pc case retV of Nothing -> return () Just v -> do r <- addEnvVar t (toVar v) assumeEnsures ((I.retval, I.ExpVar $ I.VarName r) : su) (I.procEnsures pc) return () where checkRequires su reqs = forM_ reqs $ \ (I.Require c) -> addQuery =<< toAssertion (subst su) c assumeEnsures su ens = forM_ ens $ \ (I.Ensure c) -> addInvariant =<< toAssertion (subst su) c -- XXX Abstraction (to implement): If there is load/stores in the block, the we -- don't care how many times it iterates. It's pure. toLoop :: [I.Ensure] -> Integer -> I.Var -> I.Expr -> I.LoopIncr -> [I.Stmt] -> ModelCheck () toLoop ens maxIx v start end blk = mapM_ go ixs where go :: Integer -> ModelCheck () go ix = do v' <- addEnvVar t (toVar v) addInvariant (var v' .== intLit ix) mapM_ (toBody ens) blk t = I.ixRep loopData = loopIterations maxIx start end ixs | loopOp loopData == Incr = takeWhile (<= endVal loopData) $ iterate (+ 1) (startVal loopData) | otherwise -- loopOp loopData == Decr = takeWhile (>= endVal loopData) $ iterate (flip (-) 1) (startVal loopData) toIfTE :: [I.Ensure] -> I.Expr -> [I.Stmt] -> [I.Stmt] -> ModelCheck () toIfTE ens cond blk0 blk1 = do b <- toExpr I.TyBool cond trs <- runBranch b blk0 frs <- runBranch (not' b) blk1 forM_ (M.toList (M.unionWith (++) trs frs)) $ \ ((t, r), nub -> vs) -> do when (length vs == 2) $ do r' <- addEnvVar t r let [tv,fv] = vs addInvariant $ (b .=> (var r' .== var tv)) .&& (not' b .=> (var r' .== var fv)) where runBranch b blk = withLocalRefs $ inBranch b $ do mapM_ (toBody ens) blk -- Body under the invariant symRefs <$> getState -------------------------------------------------------------------------------- toExpr :: I.Type -> I.Expr -> ModelCheck Expr toExpr t exp = case exp of I.ExpSym s -> return (var s) I.ExpVar v -> var <$> lookupVar (toVar v) I.ExpLit lit -> case lit of I.LitInteger i -> return $ intLit i I.LitFloat r -> return $ realLit $ realToFrac r I.LitDouble r -> return $ realLit r I.LitBool b -> return $ if b then T else F I.LitChar _ -> fmap var $ incReservedVar =<< toType t I.LitNull -> fmap var $ incReservedVar =<< toType t I.LitString _ -> fmap var $ incReservedVar =<< toType t I.ExpLabel t' e f -> do e' <- toExpr t' e return $ field (var f) e' I.ExpIndex ta a ti i -> do a' <- toExpr ta a i' <- toExpr ti i return $ index i' a' I.ExpToIx e i -> toExpr t e I.ExpSafeCast t' e -> do e' <- toExpr t' e assertBoundedVar t e' return e' I.ExpOp op args -> toExprOp t op args I.ExpAddrOfGlobal s -> var <$> lookupVar s I.ExpMaxMin True -> return $ intLit $ fromJust $ I.toMaxSize t I.ExpMaxMin False -> return $ intLit $ fromJust $ I.toMinSize t I.ExpSizeOf _ty -> error "Ivory.ModelCheck.Ivory2CVC4.toExpr: FIXME: handle sizeof expressions" I.ExpExtern _ -> error "Ivory.ModelCheck.Ivory2CVC4.toExpr: can't handle external symbols" -------------------------------------------------------------------------------- toExprOp :: I.Type -> I.ExpOp -> [I.Expr] -> ModelCheck Expr toExprOp t op args = case op of I.ExpEq t' -> go t' (mkEq t') I.ExpNeq t' -> toExpr t (I.ExpOp I.ExpNot [I.ExpOp (I.ExpEq t') args]) I.ExpCond -> toExpCond t arg0 arg1 arg2 I.ExpLt orEq t' -> case orEq of True -> go t' (.<=) False -> go t' (.<) I.ExpGt orEq t' -> case orEq of True -> go t' (.>=) False -> go t' (.>) I.ExpNot -> not' <$> toExpr I.TyBool arg0 I.ExpAnd -> go t (.&&) I.ExpOr -> go t (.||) I.ExpMod -> toMod t arg0 arg1 I.ExpAdd -> go t (.+) I.ExpSub -> go t (.-) I.ExpMul -> toMul t arg0 arg1 I.ExpDiv -> toDiv t arg0 arg1 I.ExpNegate -> let neg = I.ExpOp I.ExpSub [litOp t 0, arg0] in toExpr t neg I.ExpAbs -> do v <- fmap var $ incReservedVar =<< toType t addInvariant (v .>= intLit 0) return v _ -> fmap var $ incReservedVar =<< toType t where arg0 = args !! 0 arg1 = args !! 1 arg2 = args !! 2 mkEq I.TyBool = (.<=>) mkEq _ = (.==) go t' op = do e0 <- toExpr t' arg0 e1 <- toExpr t' arg1 return (e0 `op` e1) toExpCond :: I.Type -> I.Expr -> I.Expr -> I.Expr -> ModelCheck Expr toExpCond t b x y = do v <- incReservedVar =<< toType t b' <- toExpr I.TyBool b x' <- toExpr t x y' <- toExpr t y let v' = var v addInvariant ((b' .=> (v' .== x')) .&& (not' b' .=> (v' .== y'))) return v' -- Abstraction: a % b (C semantics) implies -- -- ( ((a => 0) && (a % b => 0) && (a % b < b) && (a % b <= a)) -- || ((a < 0) && (a % b <= 0) && (a % b > b) && (a % b => a))) -- -- make a fresh variable v == a % b -- and assert the above for v then returning it. toMod :: I.Type -> I.Expr -> I.Expr -> ModelCheck Expr toMod t e0 e1 = do v <- incReservedVar =<< toType t let v' = var v a <- toExpr t e0 case e1 of I.ExpLit (I.LitInteger i) -> addInvariant (v' .== (a .% i)) _ -> do b <- toExpr t e1 addInvariant (v' .== call modAbs [a, b] .&& modExp v' a b) return v' toMul :: I.Type -> I.Expr -> I.Expr -> ModelCheck Expr toMul t e0 e1 = do v <- incReservedVar =<< toType t a <- toExpr t e0 b <- toExpr t e1 let v' = var v addInvariant (v' .== call mulAbs [a, b] .&& mulExp v' a b) return v' toDiv :: I.Type -> I.Expr -> I.Expr -> ModelCheck Expr toDiv t e0 e1 = do v <- incReservedVar =<< toType t a <- toExpr t e0 b <- toExpr t e1 let v' = var v addInvariant (v' .== call divAbs [a, b] .&& divExp v' a b) return v' -------------------------------------------------------------------------------- -- Helpers toName :: I.Name -> Var toName name = case name of I.NameSym s -> s I.NameVar v -> toVar v toVar :: I.Var -> Var toVar v = case v of I.VarName n -> n I.VarInternal n -> n I.VarLitName n -> n baseType :: I.Type -> Bool baseType t = case t of I.TyBool -> True (I.TyWord _) -> True (I.TyInt _) -> True I.TyFloat -> True I.TyDouble -> True _ -> False -- Abstraction: collapse references. toType :: I.Type -> ModelCheck Type toType t = case t of I.TyVoid -> return Void (I.TyWord _) -> return Integer (I.TyInt _) -> return Integer (I.TyIndex n) -> return Integer I.TyBool -> return Bool I.TyChar -> return Char I.TyFloat -> return Real I.TyDouble -> return Real I.TyProc _ _ -> return Opaque -- I.TyProc t' ts -> err "toType" "<< proc >>" I.TyRef t' -> toType t' I.TyConstRef t' -> toType t' I.TyPtr t' -> toType t' I.TyConstPtr t' -> toType t' I.TyArr i t' -> Array <$> toType t' I.TyCArray t' -> Array <$> toType t' I.TyOpaque -> return Opaque I.TyStruct name -> return $ Struct name updateEnvRef :: I.Type -> I.Expr -> ModelCheck Var updateEnvRef t ref = case ref of I.ExpVar v -> addEnvVar t (toVar v) I.ExpAddrOfGlobal v -> addEnvVar t v _ -> err "updateEnvRef" (show ref) toStoreRef :: I.Type -> I.Expr -> ModelCheck Var toStoreRef t ref = case ref of I.ExpIndex t' e _ _ -> toStoreRef t' e I.ExpLabel t' e _ -> toStoreRef t' e I.ExpVar v -> updateEnvRef t ref I.ExpAddrOfGlobal v -> updateEnvRef t ref _ -> err "toStoreRef" (show ref) data LoopOp = Incr | Decr deriving (Show, Read, Eq) data Loop = Loop { startVal :: Integer , endVal :: Integer , loopOp :: LoopOp } deriving (Show, Read, Eq) -- Compute the number of iterations in a loop. Assume the constant folder has -- run. loopIterations :: Integer -> I.Expr -> I.LoopIncr -> Loop loopIterations maxIx start end = case end of I.IncrTo e -> Loop { startVal = getLit 0 start , endVal = getLit maxIx e , loopOp = Incr } I.DecrTo e -> Loop { startVal = getLit maxIx start , endVal = getLit 0 e , loopOp = Decr } where getLit d e = case e of I.ExpLit l -> case l of I.LitInteger i -> i _ -> err "loopIterations.ExpLit" (show e) _ -> d -------------------------------------------------------------------------------- -- Language construction helpers binOp :: I.ExpOp -> I.Expr -> I.Expr -> I.Expr binOp op e0 e1 = I.ExpOp op [e0, e1] -- orOp, andOp :: I.Expr -> I.Expr -> I.Expr -- orOp = binOp I.ExpOr -- andOp = binOp I.ExpAnd -- leOp, leqOp, geOp, geqOp :: I.Type -> I.Expr -> I.Expr -> I.Expr -- leOp t = binOp (I.ExpLt False t) -- leqOp t = binOp (I.ExpLt True t) -- geOp t = binOp (I.ExpGt False t) -- geqOp t = binOp (I.ExpGt True t) -- negOp :: I.Expr -> I.Expr -- negOp e = I.ExpOp I.ExpNot [e] -- addOp :: I.Expr -> I.Expr -> I.Expr -- addOp e0 e1 = binOp I.ExpAdd e0 e1 -- subOp :: I.Expr -> I.Expr -> I.Expr -- subOp e0 e1 = binOp I.ExpSub e0 e1 -- incrOp :: I.Type -> I.Expr -> I.Expr -- incrOp t e = addOp e (litOp t 1) -- decrOp :: I.Type -> I.Expr -> I.Expr -- decrOp t e = subOp e (litOp t 1) litOp :: I.Type -> Integer -> I.Expr litOp t n = I.ExpLit e where e = case t of I.TyWord _ -> I.LitInteger n I.TyInt _ -> I.LitInteger n I.TyFloat -> I.LitFloat (fromIntegral n) I.TyDouble -> I.LitDouble (fromIntegral n) _ -> err "litOp" (show t) varOp :: Var -> I.Expr varOp = I.ExpVar . I.VarName -------------------------------------------------------------------------------- addEnvVar :: I.Type -> Var -> ModelCheck Var addEnvVar t v = do t' <- toType t v' <- declUpdateEnv t' v updateStRef t v v' return v' where isRef = case t of I.TyRef _ -> True _ -> False -- Call the appropriate cvc4lib functions. assertBoundedVar :: I.Type -> Expr -> ModelCheck () assertBoundedVar t e = getBounds t where getBounds t' = case t' of I.TyWord w -> case w of I.Word8 -> c word8 I.Word16 -> c word16 I.Word32 -> c word32 I.Word64 -> c word64 I.TyInt i -> case i of I.Int8 -> c int8 I.Int16 -> c int16 I.Int32 -> c int32 I.Int64 -> c int64 I.TyIndex n -> addInvariant $ (intLit 0 .<= e) .&& (e .<= (intLit n .- intLit 1)) _ -> return () c f = addInvariant (call f [e]) subst :: [(I.Var, I.Expr)] -> I.Expr -> I.Expr subst su = loop where loop e = case e of I.ExpSym{} -> e I.ExpVar v -> case lookup v su of Nothing -> e Just e' -> e' I.ExpLit{} -> e I.ExpOp op args -> I.ExpOp op (map loop args) I.ExpLabel t e0 s -> I.ExpLabel t (loop e0) s I.ExpIndex t e0 t1 e1 -> I.ExpIndex t (loop e0) t1 (loop e1) I.ExpSafeCast t e0 -> I.ExpSafeCast t (loop e0) I.ExpToIx e0 maxSz -> I.ExpToIx (loop e0) maxSz I.ExpAddrOfGlobal{} -> e I.ExpMaxMin{} -> e I.ExpSizeOf{} -> e I.ExpExtern{} -> e queryEnsures :: [I.Ensure] -> I.Type -> I.Expr -> ModelCheck () queryEnsures ens t retE = forM_ ens $ \e -> addQuery =<< toEnsure e toStruct :: I.Struct -> ModelCheck () toStruct (I.Abstract name _) = addType name [] toStruct (I.Struct name fields) = do fs <- forM fields $ \ (I.Typed t f) -> (f,) <$> toType t addType name fs err :: String -> String -> a err f msg = error $ "in ivory-model-check. Unexpected: " ++ msg ++ " in function " ++ f --------------------------------------------------------------------------------
GaloisInc/ivory
ivory-model-check/src/Ivory/ModelCheck/Ivory2CVC4.hs
bsd-3-clause
21,486
0
25
6,463
7,776
3,774
4,002
489
20
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-} -- FIXME module B.Shake.Core.Rule.Internal ( ShakeValue , Rule(..) , RuleKey(..) , RuleExecutor(..) ) where import Control.Applicative import Control.Monad (join, void) import Data.Maybe (maybeToList) import qualified Control.Exception as Ex import B.Question import B.Shake.Classes import B.Shake.Core.Action.Internal (Action(..)) import qualified B.Rule as B type ShakeValue a = (Show a, Typeable a, Eq a, Hashable a, Binary a, NFData a) class (ShakeValue key, ShakeValue value) => Rule key value where storedValue :: key -> IO (Maybe value) -- | What Shake calls 'Rule' we call 'Question'. 'RuleKey' -- wraps a Shake 'Rule's key so it can be an instance of -- 'Question'. newtype RuleKey key value = RuleKey key deriving (Show, Typeable, Eq, Hashable, Binary, NFData) data NoValue = NoValue deriving (Show, Typeable) instance Ex.Exception NoValue instance (Rule key value) => Question (RuleKey key value) where type Answer (RuleKey key value) = value type AnswerMonad (RuleKey key value) = IO answer (RuleKey key) = fmap join . Ex.try $ do mValue <- storedValue key return $ maybe (Left (Ex.toException NoValue)) Right mValue -- | Shake does not have a class or type corresponding to -- b's 'Rule'. Instead, it uses 'key -> Maybe (Action -- value)' inline. newtype RuleExecutor key value = RuleExecutor (key -> Maybe (Action value)) deriving (Typeable) instance (Rule key value) => B.Rule (RuleKey key value) (RuleExecutor key value) where queryRule (RuleKey key) (RuleExecutor f) = maybeToList $ (void . toBuildRule) <$> f key
strager/b-shake
B/Shake/Core/Rule/Internal.hs
bsd-3-clause
1,833
0
15
320
510
288
222
41
0
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. An additional grant -- of patent rights can be found in the PATENTS file in the same directory. {-# LANGUAGE GADTs #-} {-# LANGUAGE OverloadedStrings #-} module Duckling.Ordinal.IT.Rules ( rules ) where import qualified Data.Text as Text import Prelude import Data.String import Duckling.Dimensions.Types import Duckling.Numeral.Helpers (parseInt) import Duckling.Ordinal.Helpers import Duckling.Regex.Types import Duckling.Types ruleOrdinalsPrimo :: Rule ruleOrdinalsPrimo = Rule { name = "ordinals (primo..10)" , pattern = [ regex "((prim|second|terz|quart|quint|sest|settim|ottav|non|decim)(o|a|i|e))" ] , prod = \tokens -> case tokens of (Token RegexMatch (GroupMatch (match:_)):_) -> case Text.toLower match of "primi" -> Just $ ordinal 1 "prima" -> Just $ ordinal 1 "primo" -> Just $ ordinal 1 "prime" -> Just $ ordinal 1 "seconda" -> Just $ ordinal 2 "secondi" -> Just $ ordinal 2 "seconde" -> Just $ ordinal 2 "secondo" -> Just $ ordinal 2 "terze" -> Just $ ordinal 3 "terzi" -> Just $ ordinal 3 "terzo" -> Just $ ordinal 3 "terza" -> Just $ ordinal 3 "quarte" -> Just $ ordinal 4 "quarto" -> Just $ ordinal 4 "quarta" -> Just $ ordinal 4 "quarti" -> Just $ ordinal 4 "quinto" -> Just $ ordinal 5 "quinta" -> Just $ ordinal 5 "quinti" -> Just $ ordinal 5 "quinte" -> Just $ ordinal 5 "sesti" -> Just $ ordinal 6 "seste" -> Just $ ordinal 6 "sesta" -> Just $ ordinal 6 "sesto" -> Just $ ordinal 6 "settimi" -> Just $ ordinal 7 "settima" -> Just $ ordinal 7 "settimo" -> Just $ ordinal 7 "settime" -> Just $ ordinal 7 "ottavo" -> Just $ ordinal 8 "ottava" -> Just $ ordinal 8 "ottavi" -> Just $ ordinal 8 "ottave" -> Just $ ordinal 8 "none" -> Just $ ordinal 9 "noni" -> Just $ ordinal 9 "nona" -> Just $ ordinal 9 "nono" -> Just $ ordinal 9 "decimo" -> Just $ ordinal 10 "decima" -> Just $ ordinal 10 "decime" -> Just $ ordinal 10 "decimi" -> Just $ ordinal 10 _ -> Nothing _ -> Nothing } ruleOrdinalDigits :: Rule ruleOrdinalDigits = Rule { name = "ordinal (digits)" , pattern = [ regex "0*(\\d+) ?(\x00aa|\x00b0|\x00b0)" ] , prod = \tokens -> case tokens of (Token RegexMatch (GroupMatch (match:_)):_) -> ordinal <$> parseInt match _ -> Nothing } rules :: [Rule] rules = [ ruleOrdinalDigits , ruleOrdinalsPrimo ]
rfranek/duckling
Duckling/Ordinal/IT/Rules.hs
bsd-3-clause
2,827
0
17
819
796
404
392
73
42
module ProjectEuler.Problem011 (solution011) where import Util takeWhilePN :: Int -> (a -> Bool) -> [a] -> [a] takeWhilePN _ _ [] = [] takeWhilePN n p (x:xs) | p x = x : takeWhilePN n p xs | otherwise = take n (x:xs) triangles :: [Int] triangles = 1 : map pairSum (zip triangles [2..]) firstWithN n = first (zip triangles (takeWhilePN 1 (\xs -> length xs <= n) (map factors triangles))))
ThermalSpan/haskell-euler
src/ProjectEuler/Problem011.hs
bsd-3-clause
421
1
13
105
207
107
100
-1
-1
{-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE DeriveDataTypeable #-} module Example.Engine where import Data.DEVS import Data.Binary import Data.Typeable (Typeable) import Data.Set (Set) import qualified Data.Set as Set import qualified Prelude as P import Numeric.Units.Dimensional.Prelude import Numeric.NumType (Zero, Pos3, Neg1) data Engine = Engine deriving (Typeable, Ord, Eq, Show) instance PDEVS Engine where type Y Engine = Int type X Engine = Int instance AtomicModel Engine instance ProcessorModel Simulator Engine pm_engine = procModel Engine ref_engine = selfRef Engine
alios/lambda-devs
Example/Example/Engine.hs
bsd-3-clause
634
0
6
95
160
94
66
20
1
{-# LANGUAGE CPP #-} {-# LANGUAGE MagicHash #-} {-# LANGUAGE UnboxedTuples #-} {-# LANGUAGE ForeignFunctionInterface #-} -- | -- Module : Data.Binary.Serialise.CBOR.ByteOrder -- Copyright : (c) Duncan Coutts 2015 -- License : BSD3-style (see LICENSE.txt) -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Lorem ipsum... -- module Data.Binary.Serialise.CBOR.ByteOrder where #include "MachDeps.h" #if __GLASHOW_HASKELL >= 710 #define HAVE_BYTESWAP_PRIMOPS #endif #if i386_HOST_ARCH || x86_64_HOST_ARCH #define MEM_UNALIGNED_OPS #endif #if WORD_SIZE_IN_BITS == 64 #define ARCH_64bit #elif WORD_SIZE_IN_BITS == 32 #else #error expected WORD_SIZE_IN_BITS to be 32 or 64 #endif import GHC.Exts import GHC.Word import Foreign.C.Types import Foreign.Ptr import GHC.ForeignPtr #if !defined(HAVE_BYTESWAP_PRIMOPS) || !defined(MEM_UNALIGNED_OPS) import Data.Bits ((.|.), shiftL) #endif #if !defined(ARCH_64bit) import GHC.IntWord64 (wordToWord64#) #endif import Data.ByteString (ByteString) import qualified Data.ByteString.Internal as BS {-# INLINE grabWord8 #-} grabWord8 :: Ptr () -> Word grabWord8 (Ptr ip#) = W# (indexWord8OffAddr# ip# 0#) #if defined(HAVE_BYTESWAP_PRIMOPS) && \ defined(MEM_UNALIGNED_OPS) && \ !defined(WORDS_BIGENDIAN) {-# INLINE grabWord16 #-} grabWord16 :: Ptr () -> Word grabWord16 (Ptr ip#) = W# (byteSwap16# (indexWord16OffAddr# ip# 0#)) {-# INLINE grabWord32 #-} grabWord32 :: Ptr () -> Word grabWord32 (Ptr ip#) = W# (byteSwap32# (indexWord32OffAddr# ip# 0#)) {-# INLINE grabWord64 #-} grabWord64 :: Ptr () -> Word64 grabWord64 (Ptr ip#) = W64# (byteSwap64# (indexWord64OffAddr# ip# 0#)) #elif defined(MEM_UNALIGNED_OPS) && \ defined(WORDS_BIGENDIAN) {-# INLINE grabWord16 #-} grabWord16 :: Ptr () -> Word grabWord16 (Ptr ip#) = W# (indexWord16OffAddr# ip# 0#) {-# INLINE grabWord32 #-} grabWord32 :: Ptr () -> Word grabWord32 (Ptr ip#) = W# (indexWord32OffAddr# ip# 0#) {-# INLINE grabWord64 #-} grabWord64 :: Ptr () -> Word64 grabWord64 (Ptr ip#) = W64# (indexWord64OffAddr# ip# 0#) #else -- fallback version: {-# INLINE grabWord16 #-} grabWord16 :: Ptr () -> Word grabWord16 (Ptr ip#) = case indexWord8OffAddr# ip# 0# of w0# -> case indexWord8OffAddr# ip# 1# of w1# -> W# w0# `shiftL` 8 .|. W# w1# {-# INLINE grabWord32 #-} grabWord32 :: Ptr () -> Word grabWord32 (Ptr ip#) = case indexWord8OffAddr# ip# 0# of w0# -> case indexWord8OffAddr# ip# 1# of w1# -> case indexWord8OffAddr# ip# 2# of w2# -> case indexWord8OffAddr# ip# 3# of w3# -> W# w0# `shiftL` 24 .|. W# w1# `shiftL` 16 .|. W# w2# `shiftL` 8 .|. W# w3# {-# INLINE grabWord64 #-} grabWord64 :: Ptr () -> Word64 grabWord64 (Ptr ip#) = case indexWord8OffAddr# ip# 0# of w0# -> case indexWord8OffAddr# ip# 1# of w1# -> case indexWord8OffAddr# ip# 2# of w2# -> case indexWord8OffAddr# ip# 3# of w3# -> case indexWord8OffAddr# ip# 4# of w4# -> case indexWord8OffAddr# ip# 5# of w5# -> case indexWord8OffAddr# ip# 6# of w6# -> case indexWord8OffAddr# ip# 7# of w7# -> w w0# `shiftL` 56 .|. w w1# `shiftL` 48 .|. w w2# `shiftL` 40 .|. w w3# `shiftL` 32 .|. w w4# `shiftL` 24 .|. w w5# `shiftL` 16 .|. w w6# `shiftL` 8 .|. w w7# where #ifdef ARCH_64bit w w# = W64# w# #else w w# = W64# (wordToWord64# w#) #endif #endif {-# INLINE withBsPtr #-} withBsPtr :: (Ptr b -> a) -> ByteString -> a withBsPtr f (BS.PS (ForeignPtr addr# _fpc) off _len) = f (Ptr addr# `plusPtr` off) {-# INLINE unsafeHead #-} unsafeHead :: ByteString -> Word8 unsafeHead (BS.PS (ForeignPtr addr# _fpc) (I# off#) _len) = W8# (indexWord8OffAddr# addr# off#) -- -- Half floats -- {-# INLINE wordToFloat16 #-} wordToFloat16 :: Word -> Float wordToFloat16 = halfToFloat . fromIntegral {-# INLINE floatToWord16 #-} floatToWord16 :: Float -> Word16 floatToWord16 = fromIntegral . floatToHalf foreign import ccall unsafe "hs_binary_halfToFloat" halfToFloat :: CUShort -> Float foreign import ccall unsafe "hs_binary_floatToHalf" floatToHalf :: Float -> CUShort -- -- Casting words to floats -- -- We have to go via a word rather than reading directly from memory because of -- endian issues. A little endian machine cannot read a big-endian float direct -- from memory, so we read a word, bswap it and then convert to float. -- Currently there are no primops for casting word <-> float, see -- https://ghc.haskell.org/trac/ghc/ticket/4092 -- In this implementation, we're avoiding doing the extra indirection (and -- closure allocation) of the runSTRep stuff, but we have to be very careful -- here, we cannot allow the "constsant" newByteArray# 8# realWorld# to be -- floated out and shared and aliased across multiple concurrent calls. So we -- do manual worker/wrapper with the worker not being inlined. {-# INLINE wordToFloat32 #-} wordToFloat32 :: Word -> Float wordToFloat32 (W# w#) = F# (wordToFloat32# w#) {-# NOINLINE wordToFloat32# #-} wordToFloat32# :: Word# -> Float# wordToFloat32# w# = case newByteArray# 4# realWorld# of (# s', mba# #) -> case writeWord32Array# mba# 0# w# s' of s'' -> case readFloatArray# mba# 0# s'' of (# _, f# #) -> f# {-# INLINE wordToFloat64 #-} wordToFloat64 :: Word64 -> Double wordToFloat64 (W64# w#) = D# (wordToFloat64# w#) {-# NOINLINE wordToFloat64# #-} #ifdef ARCH_64bit wordToFloat64# :: Word# -> Double# #else wordToFloat64# :: Word64# -> Double# #endif wordToFloat64# w# = case newByteArray# 8# realWorld# of (# s', mba# #) -> case writeWord64Array# mba# 0# w# s' of s'' -> case readDoubleArray# mba# 0# s'' of (# _, f# #) -> f# -- Alternative impl that goes via the FFI {- {-# INLINE wordToFloat32 #-} wordToFloat32 :: Word -> Float wordToFloat32 = toFloat {-# INLINE wordToFloat64 #-} wordToFloat64 :: Word64 -> Double wordToFloat64 = toFloat {-# INLINE toFloat #-} toFloat :: (Storable word, Storable float) => word -> float toFloat w = unsafeDupablePerformIO $ alloca $ \buf -> do poke (castPtr buf) w peek buf -}
thoughtpolice/binary-serialise-cbor
Data/Binary/Serialise/CBOR/ByteOrder.hs
bsd-3-clause
6,724
0
14
1,748
734
416
318
-1
-1
module PasswordGenerator (newPasswordBox) where import Graphics.UI.Gtk import Crypto.Threefish.Random import Data.IORef import System.IO.Unsafe import Graphics.Rendering.Pango.Font import Himitsu.PasswordUtils import PasswordDialogs (passwordBox) {-# NOINLINE prng #-} prng :: IORef SkeinGen prng = unsafePerformIO $ newSkeinGen >>= newIORef -- | Returns a HBox containing everything needed to add or modify an account, -- along with references to entry boxes containing the account's service -- name, account name and password respectively. newPasswordBox :: Dialog -> IO (HBox, Entry, Entry, Entry) newPasswordBox dlg = do box <- hBoxNew False 10 (pass, passframe, passent) <- generatorBox dlg (account, serviceent, userent) <- accountBox passframe dlg containerAdd box account containerAdd box pass return (box, serviceent, userent, passent) -- | Returns a VBox containing inputs for entering account details, an entry -- box which will contain a service name, and an entry box which will contain -- an account name for that service. accountBox :: Frame -> Dialog -> IO (VBox, Entry, Entry) accountBox passframe dlg = do vbox <- vBoxNew False 10 containerSetBorderWidth vbox 5 accountframe <- frameNew frameSetLabel accountframe "Account Details" accountbox <- vBoxNew False 5 containerSetBorderWidth accountbox 5 containerAdd accountframe accountbox containerAdd vbox accountframe -- Service name servicelabel <- labelNew (Just "Name of service/website") serviceent <- entryNew _ <- serviceent `on` entryActivate $ dialogResponse dlg ResponseAccept servicelblalign <- alignmentNew 0 0 0 0 containerAdd servicelblalign servicelabel containerAdd accountbox servicelblalign containerAdd accountbox serviceent -- Username for service userlabel <- labelNew (Just "Your username") userent <- entryNew _ <- userent `on` entryActivate $ dialogResponse dlg ResponseAccept userlblalign <- alignmentNew 0 0 0 0 containerAdd userlblalign userlabel containerAdd accountbox userlblalign containerAdd accountbox userent containerAdd vbox passframe set vbox [boxChildPacking passframe := PackNatural, boxChildPacking accountframe := PackNatural] return (vbox, serviceent, userent) -- | Returns a framed box containing settings for password generation, a framed -- box containing a password entry field with a "generate" button, and the -- password entry field itself. generatorBox :: Dialog -> IO (Frame, Frame, Entry) generatorBox dlg = do frame <- frameNew containerSetBorderWidth frame 5 frameSetLabel frame "Generator Settings" box <- vBoxNew False 10 containerSetBorderWidth box 5 containerAdd frame box -- What chars should go in the password? includeframe <- frameNew frameSetLabel includeframe "Password Characters" includebox <- vBoxNew False 5 containerSetBorderWidth includebox 5 lower <- checkButtonNewWithLabel "Include lowercase letters" upper <- checkButtonNewWithLabel "Include uppercase letters" numbers <- checkButtonNewWithLabel "Include numbers" special <- checkButtonNewWithLabel "Include symbols" mapM_ (flip toggleButtonSetActive True) [lower, upper, numbers, special] mapM_ (containerAdd includebox) [lower, upper, numbers, special] containerAdd includeframe includebox containerAdd box includeframe -- How long should it be? lenframe <- frameNew frameSetLabel lenframe "Password Length" numcharsbox <- hBoxNew False 5 containerSetBorderWidth numcharsbox 5 numchars <- spinButtonNewWithRange 4 100 1 spinButtonSetValue numchars 20 containerAdd numcharsbox numchars numcharslbl <- labelNew (Just "characters") containerAdd numcharsbox numcharslbl containerAdd lenframe numcharsbox set numcharsbox [boxChildPacking numcharslbl := PackNatural, boxChildPacking numchars := PackNatural] containerAdd box lenframe -- What does it look like? passframe <- frameNew frameSetLabel passframe "Your Password" passbox <- vBoxNew False 5 containerSetBorderWidth passbox 5 containerAdd passframe passbox -- Text box containing password. passent <- passwordBox dlg fd <- fontDescriptionNew fontDescriptionSetFamily fd "monospace" widgetModifyFont passent (Just fd) entrySetWidthChars passent 30 entrySetVisibility passent False containerAdd passbox passent -- Show the password? visible <- checkButtonNewWithLabel "Show password" containerAdd passbox visible _ <- visible `on` toggled $ do toggleButtonGetActive visible >>= entrySetVisibility passent -- Asessing password strength strbox <- hBoxNew False 5 containerSetBorderWidth strbox 5 ratinglbl <- labelNew (Just "Password strength:") containerAdd strbox ratinglbl rating <- labelNew (Just "N/A") containerAdd strbox rating set strbox [boxChildPacking ratinglbl := PackNatural, boxChildPacking rating := PackNatural] containerAdd passbox strbox -- Set up password ratings let fillPW = fillNewPassword rating passent numchars lower upper numbers special fillPR = entryGetText passent >>= fillPasswordRating rating mapM_ (\x -> x `on` buttonActivated $ fillPW) [lower,upper,numbers,special] _ <- onValueSpinned numchars fillPW widgetGrabFocus passent _ <- passent `on` editableChanged $ fillPR btn <- buttonNewWithLabel "Generate" _ <- btn `on` buttonActivated $ do fillNewPassword rating passent numchars lower upper numbers special containerAdd passbox btn set box [boxChildPacking includeframe := PackNatural, boxChildPacking lenframe := PackNatural] return (frame, passframe, passent) where fillNewPassword r ent chars bLower bUpper bNum bSym = do lower <- toggleButtonGetActive bLower upper <- toggleButtonGetActive bUpper num <- toggleButtonGetActive bNum sym <- toggleButtonGetActive bSym len <- spinButtonGetValue chars let ps = specify (floor len) lower upper num sym pass <- atomicModifyIORef' prng (generate ps) entrySetText ent pass fillPasswordRating r pass fillPasswordRating r pass = do let strength = judge $ analyze pass labelSetText r (show strength)
valderman/himitsu
src/PasswordGenerator.hs
bsd-3-clause
6,212
0
14
1,130
1,533
708
825
131
1
{-# LANGUAGE DeriveDataTypeable , NoImplicitPrelude , PackageImports , UnicodeSyntax #-} module Data.LList ( LList , fromList , toList , cons , (++) , head , safeHead , last , safeLast , tail , safeTail , init , null , length , map , reverse , intersperse , intercalate , concat , take , drop , splitAt ) where -------------------------------------------------------------------------------- -- Imports -------------------------------------------------------------------------------- import qualified "base" Data.List as L ( head, last, init, length , reverse, intersperse , foldr, foldl, foldr1, foldl1, map , genericTake, genericDrop ) import "base" Control.Applicative ( Applicative, pure, (<*>) , Alternative, empty, (<|>) ) import "base" Control.Monad ( Monad, return, (>>=), (>>), fail, ap ) import "base" Data.Bool ( Bool(False, True), otherwise ) import "base" Data.Eq ( Eq, (==), (/=) ) import "base" Data.Foldable ( Foldable, foldr, foldl, foldr1, foldl1 ) import "base" Data.Function ( ($) ) import "base" Data.Functor ( Functor, fmap ) import "base" Data.Maybe ( Maybe(Nothing, Just) ) import "base" Data.Monoid ( Monoid, mempty, mappend ) import "base" Data.Ord ( Ord, compare, (<), min, max ) import "base" Data.Typeable ( Typeable ) import "base" Prelude ( Num, (+), (-), fromIntegral, error ) import "base" Text.Show ( Show ) import "base-unicode-symbols" Data.Eq.Unicode ( (≑), (β‰’) ) import "base-unicode-symbols" Data.Function.Unicode ( (∘) ) import "base-unicode-symbols" Prelude.Unicode ( β„€, (β‹…) ) import "deepseq" Control.DeepSeq ( NFData, rnf ) -------------------------------------------------------------------------------- -- LList, a list with a known length -------------------------------------------------------------------------------- data LList Ξ± = LList !β„€ [Ξ±] deriving (Show, Typeable) -------------------------------------------------------------------------------- -- Basic list functions -------------------------------------------------------------------------------- fromList ∷ [Ξ±] β†’ LList Ξ± fromList xs = LList (fromIntegral $ L.length xs) xs {-# INLINE fromList #-} toList ∷ LList Ξ± β†’ [Ξ±] toList (LList _ xs) = xs {-# INLINE toList #-} cons ∷ Ξ± β†’ LList Ξ± β†’ LList Ξ± cons x (LList n xs) = LList (n + 1) (x : xs) (++) ∷ LList Ξ± β†’ LList Ξ± β†’ LList Ξ± (++) = mappend {-# INLINE (++) #-} head ∷ LList Ξ± β†’ Ξ± head = L.head ∘ toList {-# INLINE head #-} safeHead ∷ LList Ξ± β†’ Maybe Ξ± safeHead l | null l = Nothing | otherwise = Just (head l) last ∷ LList Ξ± β†’ Ξ± last = L.last ∘ toList {-# INLINE last #-} safeLast ∷ LList Ξ± β†’ Maybe Ξ± safeLast l | null l = Nothing | otherwise = Just (last l) tail ∷ LList Ξ± β†’ LList Ξ± tail (LList n (_:xs)) = LList (n - 1) xs tail _ = error "Data.LList.tail: empty list" safeTail ∷ LList Ξ± β†’ Maybe (LList Ξ±) safeTail l | null l = Nothing | otherwise = Just $ tail l init ∷ LList Ξ± β†’ LList Ξ± init (LList n xs) = LList (n - 1) (L.init xs) null ∷ LList Ξ± β†’ Bool null (LList n _) = n ≑ 0 {-# INLINE null #-} length ∷ LList Ξ± β†’ β„€ length (LList n _) = n {-# INLINE length #-} map ∷ (Ξ± β†’ Ξ²) β†’ LList Ξ± β†’ LList Ξ² map f (LList n xs) = LList n (L.map f xs) {-# INLINE map #-} reverse ∷ LList Ξ± β†’ LList Ξ± reverse (LList n xs) = LList n (L.reverse xs) {-# INLINE reverse #-} intersperse ∷ Ξ± β†’ LList Ξ± β†’ LList Ξ± intersperse e (LList n xs) = LList (if n < 2 then n else 2β‹…n - 1) (L.intersperse e xs) intercalate ∷ LList Ξ± β†’ LList (LList Ξ±) β†’ LList Ξ± intercalate xs xss = concat (intersperse xs xss) {-# INLINE intercalate #-} concat ∷ LList (LList Ξ±) β†’ LList Ξ± concat = foldr mappend mempty {-# INLINE concat #-} take ∷ β„€ β†’ LList Ξ± β†’ LList Ξ± take i (LList n xs) = LList (min i n) (L.genericTake i xs) drop ∷ β„€ β†’ LList Ξ± β†’ LList Ξ± drop i (LList n xs) = LList (max 0 (n-i)) (L.genericDrop i xs) splitAt ∷ β„€ β†’ LList Ξ± β†’ (LList Ξ±, LList Ξ±) splitAt n l = (take n l, drop n l) {-# INLINE splitAt #-} -------------------------------------------------------------------------------- -- Instances -------------------------------------------------------------------------------- instance (NFData Ξ±) β‡’ NFData (LList Ξ±) where rnf (LList _ xs) = rnf xs -- Note that the length is already evaluated -- since it has a strictness flag. instance Foldable LList where foldr f z = L.foldr f z ∘ toList foldl f z = L.foldl f z ∘ toList foldr1 f = L.foldr1 f ∘ toList foldl1 f = L.foldl1 f ∘ toList instance (Eq Ξ±) β‡’ Eq (LList Ξ±) where (LList nx xs) == (LList ny ys) | nx β‰’ ny = False | otherwise = xs ≑ ys (LList nx xs) /= (LList ny ys) | nx β‰’ ny = True | otherwise = xs β‰’ ys instance (Ord Ξ±) β‡’ Ord (LList Ξ±) where compare (LList _ xs) (LList _ ys) = compare xs ys instance Monoid (LList Ξ±) where mempty = fromList [] mappend (LList nx xs) (LList ny ys) = LList (nx + ny) (xs `mappend` ys) instance Functor LList where fmap = map instance Applicative LList where pure = return (<*>) = ap instance Alternative LList where empty = mempty (<|>) = mappend instance Monad LList where m >>= k = foldr (mappend ∘ k) mempty m m >> k = foldr (mappend ∘ (\_ β†’ k)) mempty m return = fromList ∘ (: []) fail _ = mempty
roelvandijk/length-list
src/Data/LList.hs
bsd-3-clause
5,867
0
10
1,517
1,985
1,080
905
144
2
module Abs where main = (abs 3, abs (-4), absFloat 4.0, absFloat (-.2.0))
roberth/uu-helium
test/correct/Abs.hs
gpl-3.0
75
0
8
14
42
24
18
2
1
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="si-LK"> <title>TLS Debug | ZAP Extension</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
veggiespam/zap-extensions
addOns/tlsdebug/src/main/javahelp/org/zaproxy/zap/extension/tlsdebug/resources/help_si_LK/helpset_si_LK.hs
apache-2.0
971
80
66
160
415
210
205
-1
-1
module TimeMaster (timeMaster) where import ServerMonad import Control.Concurrent.MVar import Data.Time.LocalTime import System.Posix.Env timeMaster :: TimeMasterVar -> IO () timeMaster tmvar = do (timezone, mv) <- takeMVar tmvar lt <- getLocalTimeInTimezone timezone putMVar mv lt timeMaster tmvar getLocalTimeInTimezone :: String -> IO LocalTime getLocalTimeInTimezone tz = do setEnv "TZ" tz True tzset t <- getZonedTime return $ zonedTimeToLocalTime t foreign import ccall "time.h tzset" tzset :: IO ()
haskell/ghc-builder
server/TimeMaster.hs
bsd-3-clause
625
0
8
186
159
79
80
17
1
{-# LANGUAGE CPP #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE UndecidableInstances #-} #ifndef MIN_VERSION_mtl #define MIN_VERSION_mtl(x,y,z) 0 #endif ----------------------------------------------------------------------------- -- | -- Module : Data.Machine.Plan -- Copyright : (C) 2012 Edward Kmett, RΓΊnar Bjarnason -- License : BSD-style (see the file LICENSE) -- -- Maintainer : Edward Kmett <[email protected]> -- Stability : provisional -- Portability : Rank-N Types, MPTCs -- ---------------------------------------------------------------------------- module Data.Machine.Plan ( -- * Plans Plan , runPlan , PlanT(..) , yield , maybeYield , await , stop , awaits , exhaust ) where import Control.Applicative import Control.Category import Control.Monad (MonadPlus(..)) import Control.Monad.Trans.Class import Control.Monad.IO.Class import Control.Monad.State.Class import Control.Monad.Reader.Class import Control.Monad.Error.Class import Control.Monad.Writer.Class import Data.Functor.Identity import Prelude hiding ((.),id) ------------------------------------------------------------------------------- -- Plans ------------------------------------------------------------------------------- -- | You can 'construct' a 'Plan' (or 'PlanT'), turning it into a -- 'Data.Machine.Type.Machine' (or 'Data.Machine.Type.MachineT'). -- newtype PlanT k o m a = PlanT { runPlanT :: forall r. (a -> m r) -> -- Done a (o -> m r -> m r) -> -- Yield o (Plan k o a) (forall z. (z -> m r) -> k z -> m r -> m r) -> -- forall z. Await (z -> Plan k o a) (k z) (Plan k o a) m r -> -- Fail m r } -- | A @'Plan' k o a@ is a specification for a pure 'Machine', that reads inputs selected by @k@ -- with types based on @i@, writes values of type @o@, and has intermediate results of type @a@. -- -- A @'Plan' k o a@ can be used as a @'PlanT' k o m a@ for any @'Monad' m@. -- -- It is perhaps easier to think of 'Plan' in its un-cps'ed form, which would -- look like: -- -- @ -- data 'Plan' k o a -- = Done a -- | Yield o (Plan k o a) -- | forall z. Await (z -> Plan k o a) (k z) (Plan k o a) -- | Fail -- @ type Plan k o a = forall m. PlanT k o m a -- | Deconstruct a 'Plan' without reference to a 'Monad'. runPlan :: PlanT k o Identity a -> (a -> r) -> (o -> r -> r) -> (forall z. (z -> r) -> k z -> r -> r) -> r -> r runPlan m kp ke kr kf = runIdentity $ runPlanT m (Identity . kp) (\o (Identity r) -> Identity (ke o r)) (\f k (Identity r) -> Identity (kr (runIdentity . f) k r)) (Identity kf) {-# INLINE runPlan #-} instance Functor (PlanT k o m) where fmap f (PlanT m) = PlanT $ \k -> m (k . f) {-# INLINE fmap #-} instance Applicative (PlanT k o m) where pure a = PlanT (\kp _ _ _ -> kp a) {-# INLINE pure #-} m <*> n = PlanT $ \kp ke kr kf -> runPlanT m (\f -> runPlanT n (\a -> kp (f a)) ke kr kf) ke kr kf {-# INLINE (<*>) #-} m *> n = PlanT $ \kp ke kr kf -> runPlanT m (\_ -> runPlanT n kp ke kr kf) ke kr kf {-# INLINE (*>) #-} m <* n = PlanT $ \kp ke kr kf -> runPlanT m (\a -> runPlanT n (\_ -> kp a) ke kr kf) ke kr kf {-# INLINE (<*) #-} instance Alternative (PlanT k o m) where empty = PlanT $ \_ _ _ kf -> kf {-# INLINE empty #-} PlanT m <|> PlanT n = PlanT $ \kp ke kr kf -> m kp ke kr (n kp ke kr kf) {-# INLINE (<|>) #-} instance Monad (PlanT k o m) where return = pure {-# INLINE return #-} PlanT m >>= f = PlanT (\kp ke kr kf -> m (\a -> runPlanT (f a) kp ke kr kf) ke kr kf) (>>) = (*>) {-# INLINE (>>) #-} fail _ = PlanT (\_ _ _ kf -> kf) {-# INLINE (>>=) #-} instance MonadPlus (PlanT k o m) where mzero = empty {-# INLINE mzero #-} mplus = (<|>) {-# INLINE mplus #-} instance MonadTrans (PlanT k o) where lift m = PlanT (\kp _ _ _ -> m >>= kp) {-# INLINE lift #-} instance MonadIO m => MonadIO (PlanT k o m) where liftIO m = PlanT (\kp _ _ _ -> liftIO m >>= kp) {-# INLINE liftIO #-} instance MonadState s m => MonadState s (PlanT k o m) where get = lift get {-# INLINE get #-} put = lift . put {-# INLINE put #-} #if MIN_VERSION_mtl(2,1,0) state f = PlanT $ \kp _ _ _ -> state f >>= kp {-# INLINE state #-} #endif instance MonadReader e m => MonadReader e (PlanT k o m) where ask = lift ask #if MIN_VERSION_mtl(2,1,0) reader = lift . reader #endif local f m = PlanT $ \kp ke kr kf -> local f (runPlanT m kp ke kr kf) instance MonadWriter w m => MonadWriter w (PlanT k o m) where #if MIN_VERSION_mtl(2,1,0) writer = lift . writer #endif tell = lift . tell listen m = PlanT $ \kp ke kr kf -> runPlanT m ((kp =<<) . listen . return) ke kr kf pass m = PlanT $ \kp ke kr kf -> runPlanT m ((kp =<<) . pass . return) ke kr kf instance MonadError e m => MonadError e (PlanT k o m) where throwError = lift . throwError catchError m k = PlanT $ \kp ke kr kf -> runPlanT m kp ke kr kf `catchError` \e -> runPlanT (k e) kp ke kr kf -- | Output a result. yield :: o -> Plan k o () yield o = PlanT (\kp ke _ _ -> ke o (kp ())) -- | Like yield, except stops if there is no value to yield. maybeYield :: Maybe o -> Plan k o () maybeYield = maybe stop yield -- | Wait for input. -- -- @'await' = 'awaits' 'id'@ await :: Category k => Plan (k i) o i await = PlanT (\kp _ kr kf -> kr kp id kf) -- | Wait for a particular input. -- -- @ -- awaits 'L' :: 'Plan' ('T' a b) o a -- awaits 'R' :: 'Plan' ('T' a b) o b -- awaits 'id' :: 'Plan' ('Data.Machine.Is.Is' i) o i -- @ awaits :: k i -> Plan k o i awaits h = PlanT $ \kp _ kr -> kr kp h -- | @'stop' = 'empty'@ stop :: Plan k o a stop = empty -- | Run a monadic action repeatedly yielding its results, until it returns Nothing. exhaust :: Monad m => m (Maybe a) -> PlanT k a m () exhaust f = do (lift f >>= maybeYield); exhaust f
bitemyapp/machines
src/Data/Machine/Plan.hs
bsd-3-clause
6,013
0
16
1,517
1,854
1,009
845
110
1
{-# LANGUAGE RecordWildCards #-} module GHCJS.DOM.JSFFI.PositionError ( module Generated , PositionErrorCode(..) , PositionException(..) , throwPositionException ) where import Control.Exception (Exception, throwIO) import Control.Monad.IO.Class (MonadIO(..)) import GHCJS.DOM.JSFFI.Generated.PositionError as Generated data PositionErrorCode = PositionPermissionDenied | PositionUnavailable | PositionTimeout deriving (Show, Eq, Enum) data PositionException = PositionException { positionErrorCode :: PositionErrorCode, positionErrorMessage :: String } deriving (Show, Eq) instance Exception PositionException throwPositionException :: MonadIO m => PositionError -> m a throwPositionException error = do positionErrorCode <- (toEnum . subtract 1 . fromIntegral) <$> getCode error positionErrorMessage <- getMessage error liftIO $ throwIO (PositionException{..})
plow-technologies/ghcjs-dom
src/GHCJS/DOM/JSFFI/PositionError.hs
mit
913
0
12
140
221
127
94
19
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Module : Network.AWS.IAM.DeleteUser -- Copyright : (c) 2013-2014 Brendan Hay <[email protected]> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <[email protected]> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | Deletes the specified user. The user must not belong to any groups, have any -- keys or signing certificates, or have any attached policies. -- -- <http://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteUser.html> module Network.AWS.IAM.DeleteUser ( -- * Request DeleteUser -- ** Request constructor , deleteUser -- ** Request lenses , duUserName -- * Response , DeleteUserResponse -- ** Response constructor , deleteUserResponse ) where import Network.AWS.Prelude import Network.AWS.Request.Query import Network.AWS.IAM.Types import qualified GHC.Exts newtype DeleteUser = DeleteUser { _duUserName :: Text } deriving (Eq, Ord, Read, Show, Monoid, IsString) -- | 'DeleteUser' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'duUserName' @::@ 'Text' -- deleteUser :: Text -- ^ 'duUserName' -> DeleteUser deleteUser p1 = DeleteUser { _duUserName = p1 } -- | The name of the user to delete. duUserName :: Lens' DeleteUser Text duUserName = lens _duUserName (\s a -> s { _duUserName = a }) data DeleteUserResponse = DeleteUserResponse deriving (Eq, Ord, Read, Show, Generic) -- | 'DeleteUserResponse' constructor. deleteUserResponse :: DeleteUserResponse deleteUserResponse = DeleteUserResponse instance ToPath DeleteUser where toPath = const "/" instance ToQuery DeleteUser where toQuery DeleteUser{..} = mconcat [ "UserName" =? _duUserName ] instance ToHeaders DeleteUser instance AWSRequest DeleteUser where type Sv DeleteUser = IAM type Rs DeleteUser = DeleteUserResponse request = post "DeleteUser" response = nullResponse DeleteUserResponse
romanb/amazonka
amazonka-iam/gen/Network/AWS/IAM/DeleteUser.hs
mpl-2.0
2,750
0
9
636
330
203
127
45
1
module X (foo) where foo = 10
itchyny/vim-haskell-indent
test/module/export.out.hs
mit
30
0
4
7
14
9
5
2
1
{-# OPTIONS_JHC -fno-prelude -fm4 #-} module Jhc.Inst.Read() where import Prelude.Text import Jhc.Basics import Jhc.Float import Prelude.Float import Jhc.Num import Numeric(showSigned, showInt, readSigned, readDec, showFloat, readFloat, lexDigits) -- Reading at the Integer type avoids -- possible difficulty with minInt m4_define(READINST,{{ instance Read $1 where readsPrec p r = [(fromInteger i, t) | (i,t) <- readsPrec p r] }}) READINST(Int8) READINST(Int16) READINST(Int32) READINST(Int64) READINST(IntMax) READINST(IntPtr) m4_define(READWORD,{{ instance Read $1 where readsPrec _ r = readDec r }}) READWORD(Word) READWORD(Word8) READWORD(Word16) READWORD(Word32) READWORD(Word64) READWORD(WordMax) READWORD(WordPtr) instance Read () where readsPrec p = readParen False (\r -> [((),t) | ("(",s) <- lex r, (")",t) <- lex s ] ) instance Read Double where readsPrec p = readSigned readDouble instance Read Float where readsPrec p s = [ (doubleToFloat x,y) | (x,y) <- readSigned readDouble s]
m-alvarez/jhc
lib/jhc/Jhc/Inst/Read.hs
mit
1,136
6
13
273
400
226
174
-1
-1
module Layout.Default where default (Float,Integer,Double) foo = 5
RefactoringTools/HaRe
test/testdata/Layout/Default.hs
bsd-3-clause
70
0
4
11
23
15
8
3
1
{-# LANGUAGE Safe #-} ----------------------------------------------------------------------------- -- | -- Module : Data.STRef.Lazy -- Copyright : (c) The University of Glasgow 2001 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : non-portable (uses Control.Monad.ST.Lazy) -- -- Mutable references in the lazy ST monad. -- ----------------------------------------------------------------------------- module Data.STRef.Lazy ( -- * STRefs ST.STRef, -- abstract newSTRef, readSTRef, writeSTRef, modifySTRef ) where import Control.Monad.ST.Lazy.Safe import qualified Data.STRef as ST import Prelude newSTRef :: a -> ST s (ST.STRef s a) readSTRef :: ST.STRef s a -> ST s a writeSTRef :: ST.STRef s a -> a -> ST s () modifySTRef :: ST.STRef s a -> (a -> a) -> ST s () newSTRef = strictToLazyST . ST.newSTRef readSTRef = strictToLazyST . ST.readSTRef writeSTRef r a = strictToLazyST (ST.writeSTRef r a) modifySTRef r f = strictToLazyST (ST.modifySTRef r f)
frantisekfarka/ghc-dsi
libraries/base/Data/STRef/Lazy.hs
bsd-3-clause
1,152
0
9
248
235
133
102
18
1
import qualified Data.Map as M main :: IO () main = interact parseExpensesFile parseExpensesFile :: String -> String parseExpensesFile f = show $ calcRatePerDay $ sanityCheck $ map words $ lines f calcRatePerDay :: [(String, Double, String)] -> Double calcRatePerDay xl = (sum $ map (\(_, v) -> v) dayRateList) / (fromIntegral $ length dayRateList) where dayRateMap = foldl (\a (d, v, _) -> M.insertWith (+) d v a) M.empty xl dayRateList = M.toList dayRateMap {-- -- 1. check if element is a list |x| == 0 or 3 -- 2. convert 1st element to string, 2nd to double, 3rd to string --} sanityCheck :: [[String]] -> [(String, Double, String)] sanityCheck [] = [] sanityCheck xl = map parseElem $ filter (\x -> length x > 0) xl where parseElem e = if length e == 3 then (head e, read (head $ drop 1 e) :: Double, head $ drop 2 e) else error "Bad element."
fredmorcos/attic
projects/pet/archive/pet_expenses_haskell_tmp_1/Main.hs
isc
988
1
11
296
336
180
156
17
2
-- | This module contains functions that act on factions. module Game.Cosanostra.Faction ( factionMembers , effectsFaction , winners ) where import Game.Cosanostra.Effect import Game.Cosanostra.Lenses import Game.Cosanostra.Types import Control.Lens import Data.Maybe import qualified Data.Set as S -- | Get all members of a action. factionMembers :: Players -> Turn -> Phase -> Faction -> S.Set Player factionMembers players turn phase faction = S.fromList $ filter (\player -> player ^. to (playerFaction players turn phase) == faction) (playerKeys players) effectsFaction :: [Effect] -> Faction effectsFaction = (^?! to effectsRecruited . effectType . effectTypeRecruitedFaction) -- | Get the faction for a player. -- -- Note this function is non-total, that is, will cause an error if the player -- does not have a faction. playerFaction :: Players -> Turn -> Phase -> Player -> Faction playerFaction players turn phase player = player ^?! to (playerEffects players player turn phase) . to effectsRecruited . effectType . effectTypeRecruitedFaction factionsPrimaryWinners :: Players -> Turn -> Phase -> Factions -> S.Set Faction factionsPrimaryWinners players turn phase factions = S.fromList [faction | player <- playerKeys players , isNothing (player ^. to (playerEffects players player turn phase) . to effectsCauseOfDeath) , let faction = player ^. to (playerFaction players turn phase) , factions ^?! ix faction . factionTraitsIsPrimary ] winners :: Players -> Turn -> Phase -> Factions -> Maybe [Player] winners players turn phase factions | S.size winningFactions > 1 = Nothing | otherwise = Just [player | player <- playerKeys players , let recruit = player ^?! to (playerEffects players player turn phase) . to effectsRecruited . effectType , let faction = recruit ^?! effectTypeRecruitedFaction , let factionTraits = factions ^?! ix faction , not (factionTraits ^. factionTraitsIsPrimary) || faction `S.member` winningFactions , checkConstraint players player turn phase (recruit ^?! effectTypeAgenda) ] where winningFactions = factionsPrimaryWinners players turn phase factions
rfw/cosanostra
src/Game/Cosanostra/Faction.hs
mit
2,675
0
17
885
601
309
292
-1
-1
{- Copyright (C) 2015 Braden Walters This file is licensed under the MIT Expat License. See LICENSE.txt. -} {-# LANGUAGE QuasiQuotes #-} module Output.CPP (outputCpp) where import Data.List (intersperse, sortBy) import FollowTable import Rules import StartEndTable import StateTable import Text.RawString.QQ outputCpp :: FilePath -> [Rule] -> IO () outputCpp baseName rules = do outputHeader (baseName ++ ".hpp") rules outputSource (baseName ++ ".cpp") (baseName ++ ".hpp") rules outputSource :: FilePath -> FilePath -> [Rule] -> IO () outputSource fileName headerPath rules = let include = includeHeader headerPath tokenDefinitions = defineTokens [name | (Token name _) <- rules] transTables = rulesToCpp rules 1 tokenRulesList = rulesList "tokens" [x | x@(Token _ _) <- rules] ignoreRulesList = rulesList "ignores" [x | x@(Ignore _) <- rules] in writeFile fileName (include ++ sourceClasses ++ tokenDefinitions ++ transTables ++ tokenRulesList ++ ignoreRulesList ++ lexicalAnalyserCpp) outputHeader :: FilePath -> [Rule] -> IO () outputHeader fileName rules = let tokenNames = [name | (Token name _) <- rules] in writeFile fileName $ lexicalAnalyserHpp tokenNames includeHeader :: FilePath -> String includeHeader headerPath = [r| #include <cstdio> #include <stdexcept> #include "|] ++ headerPath ++ [r|" |] sourceClasses :: String sourceClasses = [r| const int END = -1; struct CharOrRange { bool end; bool is_range; char c1, c2; CharOrRange() : end(true) { } CharOrRange(char c1) : end(false), is_range(false), c1(c1) { } CharOrRange(char c1, char c2) : end(false), is_range(true), c1(c1), c2(c2) { } }; enum TransitionType { NONE, CHARACTER, CHARCLASS, ANYCHAR, }; struct StateTransition { TransitionType type; char character; CharOrRange* charclass; int goto_state; StateTransition(char c, int goto_state) : type(CHARACTER), character(c), charclass(0), goto_state(goto_state) { } StateTransition(CharOrRange* c, int goto_state) : type(CHARCLASS), character(0), charclass(c), goto_state(goto_state) { } StateTransition(int goto_state) : type(ANYCHAR), goto_state(goto_state) { } StateTransition() : type(NONE) { } }; struct Rule { bool end; Token token; StateTransition* transition_table; int num_transitions; int* accepting_states; Rule(StateTransition* transition_table, int num_transitions, int* accepting_states) : end(false), transition_table(transition_table), num_transitions(num_transitions), accepting_states(accepting_states) { } Rule(Token token, StateTransition* transition_table, int num_transitions, int* accepting_states) : end(false), token(token), transition_table(transition_table), num_transitions(num_transitions), accepting_states(accepting_states) { } Rule() : end(true) { } }; |] defineTokens :: [Name] -> String defineTokens rules = let defineToken name num = [r|Token |] ++ name ++ [r| = |] ++ show num ++ [r|;|] in concat (intersperse "\n" $ zipWith defineToken rules [1..]) rulesToCpp :: [Rule] -> Integer -> String rulesToCpp ((Class name charsAndRanges):rest) i = [r| CharOrRange charclass_|] ++ name ++ [r|[] = {|] ++ concat (intersperse ", " (map charOrRangeToCpp charsAndRanges)) ++ [r|, CharOrRange()}; |] ++ rulesToCpp rest i rulesToCpp ((Token name regex):rest) i = let seTable = buildStartEndTable regex followTable = buildFollowTable seTable stateTable = buildStateTable (head $ seTableEntries seTable) followTable in transitionTable name stateTable ++ acceptingStates name stateTable ++ rulesToCpp rest i rulesToCpp ((Ignore regex):rest) i = let seTable = buildStartEndTable regex followTable = buildFollowTable seTable stateTable = buildStateTable (head $ seTableEntries seTable) followTable in transitionTable (show i) stateTable ++ acceptingStates (show i) stateTable ++ rulesToCpp rest (i + 1) rulesToCpp [] _ = [] charOrRangeToCpp :: CharacterOrRange -> String charOrRangeToCpp (Character c) = [r|CharOrRange('|] ++ [c] ++ [r|')|] charOrRangeToCpp (Range c1 c2) = [r|CharOrRange('|] ++ [c1] ++ [r|', '|] ++ [c2] ++ [r|')|] transitionTable :: Name -> StateTable -> String transitionTable name stateTable = let rowLength = maxStateTransitions stateTable getTransitions (StateTableEntry _ _ transitions) = transitions transRows = map transAnyLast (map getTransitions $ stateTableEntries stateTable) in [r| StateTransition trans_|] ++ name ++ [r|[][|] ++ show rowLength ++ [r|] = { { |] ++ concat (intersperse "}, {" $ map (transitionRow rowLength) transRows) ++ [r| } }; int num_trans_|] ++ name ++ [r| = |] ++ show rowLength ++ [r|; |] transAnyLast :: [StateTransition] -> [StateTransition] transAnyLast transitions = let anyLast (RxAnyChar _) (RxAnyChar _) = EQ anyLast (RxAnyChar _) _ = GT anyLast _ (RxAnyChar _) = LT anyLast _ _ = EQ anyLastTransition (StateTransition rx1 _) (StateTransition rx2 _) = anyLast rx1 rx2 in sortBy anyLastTransition transitions transitionRow :: Integer -> [StateTransition] -> String transitionRow rowLength ((StateTransition (RxChar c _) num):rest) = [r| StateTransition('|] ++ toEscapeSequence c ++ [r|', |] ++ show num ++ [r|), |] ++ transitionRow (rowLength - 1) rest transitionRow rowLength ((StateTransition (RxClass name _) num):rest) = [r| StateTransition(charclass_|] ++ name ++ [r|, |] ++ show num ++ [r|), |] ++ transitionRow (rowLength - 1) rest transitionRow rowLength ((StateTransition (RxAnyChar _) num):rest) = [r| StateTransition(|] ++ show num ++ [r|), |] ++ transitionRow (rowLength - 1) rest transitionRow rowLength (item:rest) = transitionRow (rowLength - 1) rest transitionRow rowLength [] | rowLength > 0 = [r|StateTransition(),|] ++ transitionRow (rowLength - 1) [] | otherwise = [] acceptingStates :: Name -> StateTable -> String acceptingStates name stateTable = let accepting = filter isAcceptingState $ stateTableEntries stateTable toStateNum (StateTableEntry num _ _) = show num in [r|int accepting_|] ++ name ++ [r|[] = {|] ++ concat (intersperse ", " (map toStateNum accepting)) ++ [r|, END}; |] rulesList :: Name -> [Rule] -> String rulesList name rules = let toRule (Token name _) _ = [r|Rule(|] ++ name ++ [r|, &trans_|] ++ name ++ [r|[0][0], num_trans_|] ++ name ++ [r|, accepting_|] ++ name ++ [r|)|] toRule (Ignore _) id = [r|Rule(&trans_|] ++ show id ++ [r|[0][0], num_trans_|] ++ show id ++ [r|, accepting_|] ++ show id ++ [r|)|] toRule _ _ = "" ruleStrings = filter (not . null) $ zipWith toRule rules [1..] in [r| Rule rules_|] ++ name ++ [r|[] = { |] ++ concat (intersperse ", " ruleStrings) ++ [r|, Rule() }; |] lexicalAnalyserCpp :: String lexicalAnalyserCpp = [r| bool isAccepting(int accepting[], int current_state) { for (int i = 0; accepting[i] != END; ++i) { if (accepting[i] == current_state) return true; } return false; } enum DFAMatchResult { MATCHED, FAILED, REACHED_EOF, }; DFAMatchResult dfaMatch(Rule& rule, istream& input, string& lexeme) { streampos start_pos = input.tellg(); int current_state = 0; char current_char = (char) input.get(); string found_chars; bool made_transition = true; while (made_transition && current_char != EOF) { made_transition = false; for (int i = 0; i < rule.num_transitions && !made_transition; ++i) { StateTransition& cur_transition = rule.transition_table[(current_state * rule.num_transitions) + i]; switch (cur_transition.type) { case CHARACTER: { if (current_char == cur_transition.character) { current_state = cur_transition.goto_state; made_transition = true; } break; } case CHARCLASS: { bool success = false; for (int j = 0; !cur_transition.charclass[j].end; ++j) { CharOrRange& cur_char_or_range = cur_transition.charclass[j]; if (cur_char_or_range.is_range) { if (current_char >= cur_char_or_range.c1 && current_char <= cur_char_or_range.c2) success = true; } else { if (current_char == cur_char_or_range.c1) success = true; } } if (success) { current_state = cur_transition.goto_state; made_transition = true; } break; } case ANYCHAR: { current_state = cur_transition.goto_state; made_transition = true; break; } case NONE: break; } } if (made_transition) found_chars += current_char; current_char = (char) input.get(); } input.seekg(start_pos, input.beg); if (isAccepting(rule.accepting_states, current_state)) { lexeme = found_chars; return MATCHED; } else if (current_char == EOF) return REACHED_EOF; else { return FAILED; } } LexicalAnalyzer::LexicalAnalyzer(istream& input) : input(input) {} void LexicalAnalyzer::start() { input.seekg(0, input.beg); } bool LexicalAnalyzer::next(Token& t, string& lexeme) { string current_lexeme; bool reached_eof = false; do { lexeme = ""; for (int i = 0; !rules_ignores[i].end; ++i) { switch (dfaMatch(rules_ignores[i], input, current_lexeme)) { case MATCHED: if (current_lexeme.length() > lexeme.length()) lexeme = current_lexeme; break; case FAILED: break; case REACHED_EOF: reached_eof = true; } current_lexeme = ""; } if (lexeme.length() > 0) input.seekg(streamoff(lexeme.length()), input.cur); else if (reached_eof) return false; reached_eof = false; } while (lexeme.length() > 0); for (int i = 0; !rules_tokens[i].end; ++i) { switch (dfaMatch(rules_tokens[i], input, current_lexeme)) { case MATCHED: if (current_lexeme.length() > lexeme.length()) { t = rules_tokens[i].token; lexeme = current_lexeme; } case FAILED: break; case REACHED_EOF: reached_eof = true; } } if (lexeme.length() > 0) { input.seekg(streamoff(lexeme.length()), input.cur); return true; } else { if (reached_eof) return false; throw invalid_argument("Could not match a token in stream."); } } |] lexicalAnalyserHpp :: [Name] -> String lexicalAnalyserHpp tokenNames = let declareToken name = [r|extern Token |] ++ name ++ [r|;|] in [r| #ifndef LEXICAL_ANALYZER_HPP #define LEXICAL_ANALYZER_HPP #include <iostream> using namespace std; typedef int Token; |] ++ concat (intersperse "\n" $ map declareToken tokenNames) ++ [r| class LexicalAnalyzer { public: LexicalAnalyzer(istream& input = cin); void start(); bool next(Token& t, string& lexeme); private: istream& input; }; #endif |] maxStateTransitions :: StateTable -> Integer maxStateTransitions stateTable = let getTransitions (StateTableEntry _ _ transitions) = transitions transLists = map getTransitions $ stateTableEntries stateTable in maximum $ map (fromIntegral . length) transLists
meoblast001/lexical-analyser-generator
src/Output/CPP.hs
mit
11,472
0
18
2,697
2,061
1,128
933
123
4
{-# LANGUAGE TupleSections, OverloadedStrings #-} module Handler.Home where import Import import App.Pieces import App.UTCTimeP import Data.Text as T -- This is a handler function for the GET request method on the HomeR -- resource pattern. All of your resource patterns are defined in -- config/routes -- -- The majority of the code you will write in Yesod lives in these handler -- functions. You can spread them across multiple files if you are so -- inclined, or create a single monolithic file. getHomeR :: Handler Html getHomeR = do (formWidget, formEnctype) <- generateFormPost sampleForm let submission = Nothing :: Maybe (FileInfo, Text) handlerName = "getHomeR" :: Text defaultLayout $ do aDomId <- newIdent setTitleI MsgMainPageTitle $(widgetFile "homepage") postHomeR :: Handler Html postHomeR = do ((result, formWidget), formEnctype) <- runFormPost sampleForm let handlerName = "postHomeR" :: Text submission = case result of FormSuccess res -> Just res _ -> Nothing defaultLayout $ do aDomId <- newIdent setTitle "Welcome To Yesod!" $(widgetFile "homepage") sampleForm :: Form (FileInfo, Text) sampleForm = renderDivs $ (,) <$> fileAFormReq "Choose a file" <*> areq textField "What's on the file?" Nothing
TimeAttack/time-attack-server
Handler/Home.hs
mit
1,346
0
13
310
270
141
129
30
2
{-# LANGUAGE Arrows #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE TemplateHaskell #-} module Db.PlaceCategory ( PlaceCategory'(PlaceCategory) , NewPlaceCategory , PlaceCategory , placeCategoryQuery , getPlaceCategory , insertPlaceCategory , placeCategoryId , placeCategoryName ) where import BasePrelude hiding (optional) import Control.Lens import Data.Profunctor.Product.TH (makeAdaptorAndInstance) import Data.Text (Text) import Opaleye import Db.Internal data PlaceCategory' a b = PlaceCategory { _placeCategoryId :: a , _placeCategoryName :: b } deriving (Eq,Show) makeLenses ''PlaceCategory' type PlaceCategory = PlaceCategory' Int Text type PlaceCategoryColumn = PlaceCategory' (Column PGInt4) (Column PGText) makeAdaptorAndInstance "pPlaceCategory" ''PlaceCategory' type NewPlaceCategory = PlaceCategory' (Maybe Int) Text type NewPlaceCategoryColumn = PlaceCategory' (Maybe (Column PGInt4)) (Column PGText) placeCategoryTable :: Table NewPlaceCategoryColumn PlaceCategoryColumn placeCategoryTable = Table "place_category" $ pPlaceCategory PlaceCategory { _placeCategoryId = optional "id" , _placeCategoryName = required "name" } placeCategoryQuery :: Query PlaceCategoryColumn placeCategoryQuery = queryTable placeCategoryTable insertPlaceCategory :: CanDb c e m => NewPlaceCategory -> m Int insertPlaceCategory = liftInsertReturningFirst placeCategoryTable (view placeCategoryId) . packNew getPlaceCategory :: CanDb c e m => Int -> m (Maybe PlaceCategory) getPlaceCategory i = liftQueryFirst $ proc () -> do p <- placeCategoryQuery -< () restrict -< p^.placeCategoryId .== pgInt4 i returnA -< p packNew :: NewPlaceCategory -> NewPlaceCategoryColumn packNew = pPlaceCategory PlaceCategory { _placeCategoryId = fmap pgInt4 , _placeCategoryName = pgStrictText }
benkolera/talk-stacking-your-monads
code-classy/src/Db/PlaceCategory.hs
mit
2,004
1
11
338
444
240
204
52
1
module Parse ( totalCents, purchaseDate, maybeToEither ) where import Text.Read as R import Data.List as DL import Data.Char (isDigit) import Data.Time.Calendar import Data.Time.Format as DF import Data.Time.Clock totalCents :: String -> Either String Int totalCents "" = Left "empty input" totalCents s = case elemIndex ',' s of Nothing -> Left "Input contained no ','" Just p -> do let (integer_s, fractional_s) = splitAt p s let euros = digits integer_s let cents = digits $ if take 3 fractional_s == ",--" then "00" else fractional_s let unsigned = (+) <$> fmap (* 100) euros <*> cents if head s == '-' then negate <$> unsigned else unsigned -- todo: Figure out why an Either in parseTimeM will throw instead of filling in the left. purchaseDate :: String -> Either String Day purchaseDate s = do let utcTime = DF.parseTimeM True DF.defaultTimeLocale "%e %b, %Y" s :: Maybe Day maybeToEither ("Unable to parse '" ++ s ++ "' as date" ) utcTime digits :: String -> Either String Int digits "" = Left "Empty input" digits s = annotateLeft ("For input '" ++ s ++ "': ") (R.readEither (filter isDigit s) :: Either String Int) -- Prepends a string to the Left value of an Either String _ annotateLeft :: String -> Either String a -> Either String a annotateLeft _ (Right a) = Right a annotateLeft s (Left v) = Left(s ++ v) maybeToEither :: l -> Maybe a -> Either l a maybeToEither _ (Just a) = Right a maybeToEither l Nothing = Left l
fsvehla/steam-analytics
src/Parse.hs
mit
1,544
3
18
368
501
253
248
36
4
module Main ( main ) where -- doctest import qualified Test.DocTest as DocTest main :: IO () main = DocTest.doctest [ "-isrc" , "src/AParser.hs" ]
mauriciofierrom/cis194-homework
homework10/test/examples/Main.hs
mit
170
0
6
48
44
27
17
8
1
{-# LANGUAGE DuplicateRecordFields #-} {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE OverloadedLabels #-} module Examples.Rpc.CalculatorClient (main) where import qualified Capnp.New as C import Capnp.Rpc (ConnConfig(..), fromClient, handleConn, socketTransport) import Control.Monad (when) import Data.Function ((&)) import Data.Functor ((<&>)) import qualified Data.Vector as V import Network.Simple.TCP (connect) import Capnp.Gen.Calculator.New main :: IO () main = connect "localhost" "4000" $ \(sock, _addr) -> handleConn (socketTransport sock C.defaultLimit) C.def { debugMode = True , withBootstrap = Just $ \_sup client -> do let calc :: C.Client Calculator calc = fromClient client value <- calc & C.callP #evaluate C.def { expression = Expression $ Expression'literal 123 } <&> C.pipe #value >>= C.callR #read C.def >>= C.waitPipeline >>= C.evalLimitT C.defaultLimit . C.parseField #value assertEq value 123 let getOp op = calc & C.callP #getOperator C.def { op } <&> C.pipe #func >>= C.asClient add <- getOp Operator'add subtract <- getOp Operator'subtract value <- calc & C.callP #evaluate C.def { expression = Expression $ Expression'call Expression'call' { function = subtract , params = V.fromList [ Expression $ Expression'call Expression'call' { function = add , params = V.fromList [ Expression $ Expression'literal 123 , Expression $ Expression'literal 45 ] } , Expression $ Expression'literal 67 ] } } <&> C.pipe #value >>= C.callR #read C.def >>= C.waitPipeline >>= C.evalLimitT C.defaultLimit . C.parseField #value assertEq value 101 putStrLn "PASS" } assertEq :: (Show a, Eq a) => a -> a -> IO () assertEq got want = when (got /= want) $ error $ "Got " ++ show got ++ " but wanted " ++ show want
zenhack/haskell-capnp
examples/lib/Examples/Rpc/CalculatorClient.hs
mit
2,681
0
37
1,220
615
320
295
55
1
module Tree.Lists where import Tree.Types import Tree.BTree import Tree.Balanced (insert) -- IN-order traversal. -- 1. traverse left. 2. visit root. 3. traverse right. inOrdList :: BTree a -> [a] inOrdList = foldTree (\v lRes rRes -> lRes ++ v : rRes) [] -- POST-order traversal. -- 1. traverse left. 2. traverse right. 3. visit root. postOrdList :: BTree a -> [a] postOrdList = foldTree (\v lRes rRes -> rRes ++ v : lRes) [] -- PRE-order traversal. -- 1. visit root. 2. traverse left. 3. traverse right. -- Not ordered. aka 'flatten' preOrdList :: BTree a -> [a] preOrdList = foldTree (\v lRes rRes -> v : lRes ++ rRes) [] -- From >>pre<< OrdList, that is. fromPreList :: Ord a => [a] -> BTree a fromPreList [] = Empty fromPreList (x:xs) = Node x (fromPreList lefts) (fromPreList rights) where lefts = takeWhile (<= x) xs rights = dropWhile (<= x) xs -- This list doesn't need to be in any particular order at all. -- Creates a balanced tree. -- -- Not too efficient; with each folded-over `a`, -- it starts at the root of the tree and moves down to insert. fromList :: Ord a => [a] -> BTree a fromList = foldl (flip insert) Empty
marklar/elm-fun
BTree/Tree/Lists.hs
mit
1,169
0
9
245
314
173
141
18
1
{-# LANGUAGE TypeFamilies #-} {-# LANGUAGE DataKinds, ConstraintKinds, PolyKinds #-} {-# LANGUAGE FlexibleInstances, FlexibleContexts, UndecidableInstances #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeOperators #-} module GrammarGen where import Generics.SOP import Random class Gen a where gen :: MonadDiscrete w m => m a instance (SListI l, All Gen l) => Gen (NP I l) where gen = case (sList :: SList l) of SNil -> return Nil SCons -> (:*) <$> (I <$> gen) <*> gen instance {-# OVERLAPPABLE #-} (Generic a, All2 Gen (Code a)) => Gen a where gen = uniform sums >>= fmap (to . SOP) sums :: forall w l m. (MonadDiscrete w m, All2 Gen l) => [m (NS (NP I) l)] sums = case (sList :: SList l) of SNil -> [] SCons -> (Z <$> gen) : map (fmap S) sums
vladfi1/hs-misc
GrammarGen.hs
mit
780
0
12
163
285
153
132
20
2
module Util where import qualified System.Random.MWC as MWC import Data.ByteVector (fromByteVector) import System.IO.Temp (withSystemTempFile) import Data.ByteString.Lazy.Internal (defaultChunkSize) import System.IO (hClose) import Conduit import Control.Monad.Catch (MonadMask) import Data.Time (getCurrentTime, diffUTCTime) withRandomFile :: (MonadIO m, MonadMask m) => (FilePath -> m a) -> m a withRandomFile f = withSystemTempFile "random-file.bin" $ \fp h -> do liftIO $ do gen <- MWC.createSystemRandom replicateMC (4000000 `div` defaultChunkSize) (MWC.uniformVector gen defaultChunkSize) $$ mapC fromByteVector =$ sinkHandle h hClose h f fp timed :: MonadIO m => m a -> m a timed f = do start <- liftIO $ do start <- getCurrentTime putStrLn $ "Start: " ++ show start return start res <- f liftIO $ do end <- getCurrentTime putStrLn $ "End : " ++ show end print $ diffUTCTime end start return res
snoyberg/bytevector
bench/Util.hs
mit
1,050
0
17
278
332
167
165
32
1
{-# LANGUAGE GeneralizedNewtypeDeriving #-} module Graphics.Tracy.Color ( -- * Colors Color (..) , from256 , Alpha , blending -- * Literals , white , gray , black , red , green , blue , cyan , magenta , yellow -- * Modifiers , Modifier , bright , dark ) where import Data.Default import Data.Monoid import Graphics.Tracy.V3 newtype Color = Color { clr :: V3 } deriving (Show, Read, Num) instance Default Color where def = gray -- | Mix two colors. instance Monoid Color where mempty = gray mappend (Color a) (Color b) = Color (avg a b) type Alpha = Double -- | Linear interpolation. blending :: Alpha -> Color -> Color -> Color blending alpha (Color a) (Color b) = Color ((alpha .* a) + ((1 - alpha) .* b)) {-# INLINE blending #-} -- | Build color from an RGB components. from256 :: Double -> Double -> Double -> Color from256 x y z = Color (V3 (x / 255) (y / 255) (z / 255)) white, gray, black :: Color white = from256 255 255 255 gray = from256 128 128 128 black = from256 0 0 0 red, green, blue :: Color red = from256 255 0 0 green = from256 0 255 0 blue = from256 0 0 255 cyan, magenta, yellow :: Color cyan = from256 0 255 255 magenta = from256 255 0 255 yellow = from256 0 255 255 type Modifier a = a -> a bright :: Modifier Color bright = (white <>) dark :: Modifier Color dark = (black <>)
pxqr/tracy
src/Graphics/Tracy/Color.hs
mit
1,504
0
11
467
493
283
210
52
1
{-# LANGUAGE ScopedTypeVariables #-} module CodeGen where import Prelude import Data.List import qualified Data.Map as HashMap import qualified LLIR import LLIR hiding (blockName) import Text.Printf data CGContext = CGContext { -- label, constant string constStrs :: HashMap.Map String String, nextConstStrId :: Int, -- global arrays with sizes globalArrays :: [(String, Int)] } deriving(Eq, Show); newCGContext :: CGContext newCGContext = CGContext (HashMap.empty) 0 [] getConstStrId :: FxContext -> String -> (FxContext, String) getConstStrId fcx str = let gcx = global fcx strs = constStrs gcx in case HashMap.lookup str strs of Just name -> (fcx, name) Nothing -> let next = (nextConstStrId gcx) id = ".const_str" ++ (show next) gcx2 = gcx{ constStrs= HashMap.insert str id strs, nextConstStrId = next + 1 } in (fcx{global=gcx2}, id) addGlobals (CGContext constStrs nextConstStrId globalArrays) globals = -- only collects sizes of global arrays so the beginning of main function can set the lengths. let arrays = filter (\(_, (_, size)) -> case size of Just _ -> True Nothing -> False) (HashMap.toList globals) l = map (\(name, (_, Just size)) -> (".global_" ++ name, size)) arrays in CGContext constStrs nextConstStrId l data InstLoc = Register String | Memory String Int | Immediate Int deriving(Eq, Show); data FxContext = FxContext { name :: String, global :: CGContext, function :: LLIR.VFunction, blockName :: String, -- variables maps registers to a label/reg + offset variables :: HashMap.Map String InstLoc, offset :: Int, instrs :: [String], errors :: [String] } deriving(Eq, Show); newFxContext :: String -> CGContext -> LLIR.VFunction -> FxContext newFxContext name global func = FxContext name global func "entry" HashMap.empty 0 [] [] updateOffsetBy :: FxContext -> Int -> FxContext updateOffsetBy fcx size = fcx{offset=(offset fcx) + size} updateOffset :: FxContext -> FxContext updateOffset fcx = updateOffsetBy fcx 8 locStr :: InstLoc -> String locStr (Memory place offset) = (show offset) ++ "(" ++ place ++ ")" locStr (Register place) = place locStr (Immediate place) = "$" ++ (show place) getVar :: FxContext -> String -> InstLoc getVar fxc var = hml (variables fxc) var "getVar" lookupVariable :: FxContext -> String -> String lookupVariable fxc var = let table = (variables fxc) in case head var of '$' -> var _ -> locStr $ hml table var "lookupVariable" setVariableLoc :: FxContext -> String -> InstLoc -> FxContext setVariableLoc fcx var loc = fcx{variables=HashMap.alter update var (variables fcx)} where update _ = Just loc getHeader :: String getHeader = ".section .text\n" ++ ".globl main\n" -- args: [(Name, size)] getPreCall :: [(String, Int)] -> String getPreCall args = let argRegs = ["%rdi", "%rsi", "%rdx", "%rcx", "%r8", "%r9"] remainingArgs = drop (length argRegs) args argsInRegisters = (foldl (\acc (arg, reg) -> acc ++ " movq " ++ (fst arg) ++ ", " ++ reg ++ "\n") "" (zip args argRegs)) pushedArgs = (foldl (\acc arg -> acc ++ " pushq " ++ (fst arg) ++ "\n") "" (reverse remainingArgs)) in " #precall\n" ++ pusha ++ argsInRegisters ++ pushedArgs ++ " #/precall\n" getPostCall :: Int -> String getPostCall numArguments = " #postcall\n" ++ (intercalate "" $ replicate (numArguments - 6) " pop %rax\n") ++ popa ++ " #/postcall\n" getProlog :: FxContext -> Int -> Int -> String getProlog cx argsLength localsSize = let argRegs = ["%rdi", "%rsi", "%rdx", "%rcx", "%r8", "%r9"] argz = ( argRegs ++ (map (\i -> (show $ (i - (length argRegs) + 1) * 8) ++ "(%rbp)") (drop 6 [1..argsLength]) ) ) in " #prolog\n" ++ " push %rbp\n" ++ " movq %rsp, %rbp\n" ++ " subq $" ++ (show localsSize) ++ ", %rsp\n" ++ -- put register arguments to stack ( arrayToLine $ concat $ map (\(x, y) -> let fm = x to = getRef cx $ ArgRef (y-1) (name cx) in if fm == to then [] else move x to ) $ zip argz [1..argsLength] ) ++ " #/prolog\n" getEpilog :: String getEpilog = " \n" ++ " #epilog\n" ++ " movq %rbp, %rsp\n" ++ " pop %rbp\n" ++ " ret\n" ++ " #/epilog\n" genGlobals :: HashMap.Map String (VType, Maybe Int) -> String genGlobals globals = ".bss\n" ++ (intercalate "" $ map genGlobal $ HashMap.toList globals) ++ "\n" genGlobal :: (String, (VType, Maybe Int)) -> String genGlobal (name, (_, Nothing)) = ".global_" ++ name ++ ":\n .zero 8\n" -- Need to adjust for arrays genGlobal (name, (_, Just size)) = -- an extra 8-byte word for storing the length ".global_" ++ name ++ ":\n .zero " ++ show (8 * (1 + size)) ++ "\n" genCallouts :: HashMap.Map String String -> String genCallouts callouts = "" -- Not sure how to declare global strings closestMultipleOf16 num = ((num + 15) `div` 16) * 16 localSize instr = case instr of VStore _ _ _ -> 0 VArrayStore _ _ _ _ -> 0 VReturn _ _ -> 0 VCondBranch _ _ _ _ -> 0 VUncondBranch _ _ -> 0 VUnreachable _ -> 0 VAllocation _ _ (Just x) -> (x + 1) * 8 VAllocation _ _ Nothing -> 8 _ -> 8 calculateLocalsSize instrs = foldl (+) 0 (map localSize instrs) genFunction :: CGContext -> LLIR.VFunction -> (CGContext, String) genFunction cx f = let argsLength = length $ LLIR.arguments f instrs = concat $ map (\x -> snd $ getBlockInstrs f $ hml (LLIR.blocks f) x "getblocks" ) (LLIR.blockOrder f) nzInst = (filter (\x -> 0 /= (localSize x)) instrs) localsSize = (8*argsLength) + (calculateLocalsSize nzInst) ncx0 = foldl (\cx (idx, arg) -> let sz = 8 in if idx <= 6 then updateOffsetBy ( setVariableLoc cx (LLIR.functionName f ++ "@" ++ show (idx - 1)) (Memory "%rbp" $ ( -((offset cx) + sz) ) ) ) sz else setVariableLoc cx (LLIR.functionName f ++ "@" ++ show (idx - 1)) (Memory "%rbp" $ ( (idx - 6) + 2 ) * 6 ) ) (newFxContext (LLIR.functionName f) cx f) (zip [1..argsLength] $ LLIR.arguments f) ncx1 = foldl (\cx arg -> let sz = localSize arg in updateOffsetBy ( setVariableLoc cx (LLIR.getName arg) (Memory "%rbp" $ ( -((offset cx) + sz) ) ) ) sz ) ncx0 nzInst (ncx2, blocksStr) = foldl (\(cx, s) name -> let block = hml (LLIR.blocks f) name "getFunc-Block" (ncx, str) = genBlock cx{blockName=name} block name f in (ncx, s ++ str)) (ncx1, "") $ LLIR.blockOrder f prolog = getProlog ncx2 argsLength (closestMultipleOf16 localsSize) strRes = "\n" ++ LLIR.functionName f ++ ":\n" ++ prolog ++ blocksStr ++ getEpilog in --if (LLIR.getName f) /= "sum" then (global ncx2, strRes) --else --error ( printf "localsSize:%s\n\nncx0:%s\n\nncx1:%s\n\nncx2:%s\n\n%s" (show localsSize) (show ncx0) (show ncx1) (show ncx2) (show (map (\y -> getRef ncx2 $ ArgRef (y-1) (name ncx2) ) [1..argsLength] ) ) ) getBlockInstrs :: LLIR.VFunction -> LLIR.VBlock -> (Bool,[LLIR.VInstruction]) getBlockInstrs f block = let instructions :: [String] = LLIR.blockInstructions block term = last instructions termI = instCastU f $ InstRef term instructions2 :: [String] = case termI of VCondBranch _ _ _ _ -> filter (\x -> case do inst <- instCast f $ InstRef x _ <- case inst of VBinOp _ op _ _ -> if elem op ["<","<=",">",">=","u<","u<=","u>","u>=","==","!="] then Just True else Nothing _ -> Nothing uses <- return $ getUses inst f _ <- if 1 == length uses then Just True else Nothing if ( getName $ getUseInstr2 f (uses !! 0) ) == term then Just True else Nothing of Just _ -> False _ -> True ) instructions _ -> instructions instrs = map (\x -> instCastU f $ InstRef x) instructions2 in ( (length instructions)/=(length instructions2), instrs ) makeOneReg :: String -> String -> String -> (String,String,[String]) makeOneReg a b c = if (isMemoryS a) && (isMemoryS b) then (c,b,move a c) else (a,b,[]) swapBinop :: String -> String swapBinop a | a == "==" = "==" | a == "!=" = "!=" | a == ">" = "<" | a == ">=" = "<=" | a == "<" = ">" | a == "<=" = ">=" | a == "u>" = "u<" | a == "u>=" = "<u=" | a == "u<" = "u>" | a == "u<=" = "u>=" genBlock :: FxContext -> LLIR.VBlock -> String -> LLIR.VFunction -> (FxContext, String) genBlock cx block name f = let instructions = LLIR.blockInstructions block term = last instructions (fastTerm, instructions2) = getBlockInstrs f block instructions3 = if fastTerm then take ((length instructions2)-1) instructions2 else instructions2 (ncx, s) = foldl (\(cx, acc) instruction -> let (ncx, str) = genInstruction cx instruction in (ncx, acc ++ ( "# " ++ (show instruction) ++ "\n" ) ++ str)) (cx, "") instructions3 blockName = LLIR.blockFunctionName block ++ "_" ++ LLIR.blockName block setupGlobals = if blockName /= "main_entry" then "" else genSetupGlobals (global cx) fastEnd = if not fastTerm then "" else let termI = instCastU f $ InstRef term (_,cond,tB, fB) = case termI of VCondBranch a c t f -> (a, c, t, f) _ -> error "badcond" cmpI = instCastU f $ cond (_,op0,a1,a2) = case cmpI of VBinOp a b c d -> (a,b,c,d) _ -> error "badbin" r1 :: String = getRef cx a1 r2 :: String = getRef cx a2 phis = (LLIR.getPHIs (function cx) tB) ++ (LLIR.getPHIs (function cx) fB) cors = concat $ map (\(VPHINode pname hm) -> let var = locStr $ getVar cx pname str :: String = CodeGen.blockName cx val = getRef cx (hml hm str "genBlock") in move val var ) phis (x1,x2,mvs) = makeOneReg r1 r2 "%rax" (y1,y2,op) = if isImmediateS x1 then (x2, x1, swapBinop op0) else (x1, x2, op0) mp = HashMap.fromList [("==","je"),("!=","jne"),("u<","jb"),("u<=","jbe"),("u>","ja"),("u>","jae"),("<","jl"),("<=","jle"),(">","jg"),(">=","jge")] insts = ["# " ++ (show cmpI), "# "++ (show termI), printf "cmpq %s, %s" y2 y1, printf "%s %s_%s" (hml mp op "reverse cmp") (CodeGen.name cx) tB, printf "jmp %s_%s" (CodeGen.name cx) fB] in arrayToLine $ cors ++ mvs ++ insts in (ncx, blockName ++ ":\n" ++ setupGlobals ++ s ++ fastEnd) genSetupGlobals cx = concat $ map (\(name, size) -> arrayToLine $ move ("$" ++ (show size)) name ) $ globalArrays cx arrayToLine :: [String] -> String arrayToLine ar = concat $ map (\x -> " " ++ x ++ "\n") ar genUOp :: String -> String -> String genUOp op reg = case op of "-" -> printf "negq %s" reg "!" -> printf "xorq $1, %s" reg isMemory :: InstLoc -> Bool isMemory (Memory _ _ ) = True isMemory _ = False isMemoryS :: String -> Bool isMemoryS s = ( (last s) == ')' ) || ( (take (length ".global") s) == ".global" ) isRegisterS :: String -> Bool isRegisterS s = (head s) == '%' isImmediateS :: String -> Bool isImmediateS s = (head s) == '$' move :: String -> String -> [String] move loc1 loc2 = if loc1 == loc2 then [] else if (isMemoryS loc1) && (isMemoryS loc2) then [printf "movq %s, %s" loc1 "%rax", printf "movq %s, %s" "%rax" loc2 ] else [printf "movq %s, %s" loc1 loc2] makeReg :: String -> String -> (String,[String]) makeReg reg tmp = if isRegisterS reg then (reg, []) else (tmp, move reg tmp) genInstruction cx (VAllocation result tp size) = let s = case size of Just i -> i Nothing -> 0 -- reserve first 8-byte number to store the length of the array var = getVar cx result -- in case of an array, skip first byte stackOffset = case var of Memory loc off -> off _ -> error "badd var for allocation" destination = (show stackOffset) ++ "(%rbp)" ncx :: FxContext = case size of -- if array, store location of its length lookup at the head Just i -> let cx2 = setVariableLoc cx (result) (Memory "%rbp" $ stackOffset + 8) cx3 = setVariableLoc cx2 (result ++ "@len" ) (Memory "%rbp" $ stackOffset) in cx3 Nothing -> cx ncx2 = ncx zeroingCode = case size of Just sz -> " # bzero\n" ++ " cld\n" ++ " leaq " ++ (locStr $ getVar ncx2 result ) ++ ", %rdi\n" ++ " movq $" ++ (show sz) ++ ", %rcx\n" ++ " movq $0, %rax\n" ++ " rep stosq\n" ++ " # /bzero\n" Nothing -> "" in (ncx2, (if s > 0 then arrayToLine ( move ("$" ++ (show s)) destination ) else "") ++ zeroingCode ) genInstruction cx (VUnOp result op val) = let loc = getRef cx val var = getVar cx result vloc = locStr var oploc = case var of Register _ -> vloc _ -> "%rax" insts = move loc oploc ++ [ genUOp op oploc ] ++ move oploc vloc in (cx, arrayToLine insts) genInstruction cx (VPHINode _ _) = (cx, "") genInstruction cx (VBinOp result op val1 val2) = let loc1 = getRef cx val1 loc2 = getRef cx val2 var = getVar cx result vloc = locStr var oploc = case var of Register _ -> vloc _ -> "%rax" cp = move oploc vloc in (cx, ( if ((op == "/") || (op == "%")) then -- in A/B require A in rax, rdx empty let (nreg, inst0) = if isImmediateS loc2 then makeReg loc2 "%rbx" else (loc2,[]) (instA, out) :: ([String], String) = genOpB op loc1 nreg in (arrayToLine ( inst0 ++ instA ++ (move out vloc) ) ) else (arrayToLine $ move loc1 oploc) ++ ( arrayToLine $ genOp op loc2 oploc ) ++ ( arrayToLine cp ) ) ) genInstruction cx (VMethodCall name isCallout fname args) = -- push arguments let (ncx, nargs) = foldl (\(cx, acc) arg -> let (ncx, narg) = genArg cx arg in (ncx, acc ++ [narg])) (cx, []) args precall = getPreCall nargs cleanRax = " movq $0, %rax\n" postcall = getPostCall $ length args destination = locStr $ getVar cx name (ncx2, exitMessage) = if fname == "exit" && isCallout then genExitMessage cx (args !! 0) else (ncx, "") in (ncx2, exitMessage ++ precall ++ cleanRax ++ " callq " ++ fname ++ "\n movq %rax, " ++ destination ++ "\n" ++ postcall) genInstruction cx (VStore _ val var) = let loc1 = getRef cx val loc2 = getRef cx var in (cx, arrayToLine $ move loc1 loc2) genInstruction cx (VLookup result val) = let loc = getRef cx val destination = locStr $ getVar cx result in (cx, arrayToLine $ move loc destination) genInstruction cx (VArrayStore _ val arrayRef idxRef) = let arr = case arrayRef of InstRef s -> lookupVariable cx s GlobalRef s -> ".global_" ++ s _ -> "bad array store " ++ (show arrayRef) isGlobal = case arrayRef of GlobalRef _ -> True _ -> False idx = getRef cx idxRef loc = getRef cx val in (cx, " leaq " ++ arr ++ ", %rax\n" ++ " movq " ++ idx ++ ", %rbx\n" ++ (if isGlobal then " addq $1, %rbx\n" else "") ++ " leaq (%rax, %rbx, 8), %rbx\n" ++ " movq " ++ loc ++ ", %rax\n" ++ " movq %rax, (%rbx)\n") genInstruction cx (VArrayLookup result arrayRef idxRef) = let arr = case arrayRef of InstRef s -> lookupVariable cx s GlobalRef s -> ".global_" ++ s _ -> "bad array lookup " ++ (show arrayRef) isGlobal = case arrayRef of GlobalRef _ -> True _ -> False idx = getRef cx idxRef destination = locStr $ getVar cx result in (cx, " leaq " ++ arr ++ ", %rax\n" ++ " movq " ++ idx ++ ", %rbx\n" ++ (if isGlobal then " addq $1, %rbx\n" else "") ++ " movq (%rax, %rbx, 8), %rbx\n" ++ " movq %rbx, " ++ destination ++ "\n") genInstruction cx (VArrayLen result ref) = let access = case ref of InstRef s -> lookupVariable cx (s ++ "@len") GlobalRef s -> ".global_" ++ s _ -> "bad VArrayLen of " ++ (show ref) destination = locStr $ getVar cx result in (cx, " movq " ++ access ++ ", %rax\n" ++ " movq %rax, " ++ destination ++ "\n") genInstruction cx (VReturn _ maybeRef) = case maybeRef of Just ref -> (cx, " movq " ++ (snd (genAccess cx ref)) ++ ", %rax\n" ++ " movq %rbp, %rsp\n pop %rbp\n ret\n" ) Nothing -> if name cx == "main" then (cx, " movq %rbp, %rsp\n xorq %rax, %rax\n pop %rbp\n ret\n" ) else (cx, " movq %rbp, %rsp\n pop %rbp\n ret\n" ) -- TODO MOVE CMP / etc genInstruction cx (VCondBranch result cond true false) = let loc :: String = getRef cx cond phis = (LLIR.getPHIs (function cx) true) ++ (LLIR.getPHIs (function cx) false) cors = concat $ map (\(VPHINode pname hm) -> let var = locStr $ getVar cx pname val = getRef cx (hml hm (blockName cx) "condBr" ) in move val var ) phis (reg, inst1) :: (String, [String]) = makeReg loc "%rax" insts = inst1 ++ [printf "testq %s, %s" reg reg, printf "jnz %s_%s" (name cx) true, printf "jz %s_%s" (name cx) false] in ( cx, arrayToLine $ cors ++ insts ) genInstruction cx (VUnreachable _) = (cx, " # unreachable instruction\n") genInstruction cx (VUncondBranch result dest) = let phis = LLIR.getPHIs (function cx) dest cors :: [String] = concat $ map (\(VPHINode pname hm) -> let var = locStr $ getVar cx pname val = getRef cx (hml hm (blockName cx) "uncondBr") in move val var ) phis in (cx, arrayToLine $ cors ++ [printf "jmp %s_%s" (name cx) dest ]) genExitMessage :: FxContext -> ValueRef -> (FxContext, String) genExitMessage cx val = (ncx, " xorq %rax, %rax\n movq $" ++ message ++ ", %rdi\n" ++ " call printf\n") where (ncx, message) = case val of LLIR.ConstInt (-1) -> getConstStrId cx ("\"*** RUNTIME ERROR ***: Array out of Bounds access in method \\\"" ++ name cx ++ "\\\"\\n\"") LLIR.ConstInt (-2) -> getConstStrId cx ("\"*** RUNTIME ERROR ***: Method \\\"" ++ name cx ++ "\\\" didn't return\\n\"") quadRegToByteReg :: String -> String quadRegToByteReg a | a == "%rax" = "%al" | a == "%rbx" = "%bl" | a == "%rcx" = "%cl" | a == "%rdx" = "%dl" | a == "%r8" = "%r8b" | a == "%r9" = "%r9b" | a == "%r10" = "%r10b" | a == "%r11" = "%r11b" | a == "%r12" = "%r12b" | a == "%r13" = "%r13b" | a == "%r14" = "%r14b" | a == "%r15" = "%r15b" | a == "%rsp" = "%spl" | a == "%rbp" = "%bpl" | a == "%rsi" = "%sil" | a == "%rsd" = "%dil" quadRegToWordReg :: String -> String quadRegToWordReg a | a == "%rax" = "%eax" | a == "%rbx" = "%ebx" | a == "%rcx" = "%ecx" | a == "%rdx" = "%edx" | a == "%r8" = "%r8b" | a == "%r9" = "%r9b" | a == "%r10" = "%r10d" | a == "%r11" = "%r11d" | a == "%r12" = "%r12d" | a == "%r13" = "%r13d" | a == "%r14" = "%r14d" | a == "%r15" = "%r15d" | a == "%rsp" = "%esp" | a == "%rbp" = "%ebp" | a == "%rsi" = "%esi" | a == "%rsd" = "%ed" zero :: String -> String zero reg = printf "xorl %s, %s" reg -- arg2 must be register, arg1 may be memory -- OP -> arg1 -> arg2 / output -> insts genOp :: String -> String -> String -> [String] -- out is RHS and must be reg/mem, loc is LHS could be immediate/etc genOp "+" loc out = [printf "addq %s, %s" loc out] genOp "-" loc out = [printf "subq %s, %s" loc out] genOp "*" loc out = [printf "imulq %s, %s" loc out] genOp "==" loc out = [printf "cmpq %s, %s" loc out, printf "sete %s" $ quadRegToByteReg out, printf "movzx %s, %s" (quadRegToByteReg out) (quadRegToWordReg out)] genOp "!=" loc out = [printf "cmpq %s, %s" loc out, printf "setne %s" $ quadRegToByteReg out, printf "movzx %s, %s" (quadRegToByteReg out) (quadRegToWordReg out)] genOp "<" loc out = [printf "cmpq %s, %s" loc out, printf "setl %s" $ quadRegToByteReg out, printf "movzx %s, %s" (quadRegToByteReg out) (quadRegToWordReg out)] genOp "<=" loc out = [printf "cmpq %s, %s" loc out, printf "setle %s" $ quadRegToByteReg out, printf "movzx %s, %s" (quadRegToByteReg out) (quadRegToWordReg out)] genOp ">" loc out = [printf "cmpq %s, %s" loc out, printf "setg %s" $ quadRegToByteReg out, printf "movzx %s, %s" (quadRegToByteReg out) (quadRegToWordReg out)] genOp ">=" loc out = [printf "cmpq %s, %s" loc out, printf "setge %s" $ quadRegToByteReg out, printf "movzx %s, %s" (quadRegToByteReg out) (quadRegToWordReg out)] genOp "u<" loc out = [printf "cmpq %s, %s" loc out, printf "setb %s" $ quadRegToByteReg out, printf "movzx %s, %s" (quadRegToByteReg out) (quadRegToWordReg out)] genOp "u<=" loc out = [printf "cmpq %s, %s" loc out, printf "setbe %s" $ quadRegToByteReg out, printf "movzx %s, %s" (quadRegToByteReg out) (quadRegToWordReg out)] genOp "u>" loc out = [printf "cmpq %s, %s" loc out, printf "seta %s" $ quadRegToByteReg out, printf "movzx %s, %s" (quadRegToByteReg out) (quadRegToWordReg out)] genOp "u>=" loc out = [printf "cmpq %s, %s" loc out, printf "setae %s" $ quadRegToByteReg out, printf "movzx %s, %s" (quadRegToByteReg out) (quadRegToWordReg out)] genOp "|" loc out = [printf "orq %s, %s" loc out] -- ++ ", %rax\n cmp %rax, $0\n movq $0, %rax\n setnz %al\n" genOp "&" loc out = [printf "andq %s, %s" loc out]-- ++ ", %rax\n cmp %rax, $0\n movq $0, %rax\n setnz %al\n" -- requires RAX, RDX, and divisor -- In A/B %rax must contain A, arg2 contains B -- returns instructions, output -- op arg2 genOpB :: String -> String -> String -> ([String], String) genOpB "/" arg1 arg2 = ((move arg1 "%rax") ++ ["cqto", printf "idivq %s" arg2], "%rax") genOpB "%" arg1 arg2 = ((move arg1 "%rax") ++ ["cqto", printf "idivq %s" arg2], "%rdx") genArg :: FxContext -> ValueRef -> (FxContext, (String, Int)) genArg cx x = let (ncx, asm) = genAccess cx x in (ncx, (asm, 8)) getRef :: FxContext -> ValueRef -> String getRef cx (InstRef ref) = lookupVariable cx ref getRef cx (ConstInt i) = "$" ++ (show i) getRef cx (ConstString s) = let (ncx, id) = getConstStrId cx s in "$" ++ id getRef cx (ConstBool b) = "$" ++ (if b then "1" else "0") getRef cx (ArgRef i funcName) = if i < 6 then lookupVariable cx $ funcName ++ "@" ++ (show i) else (show $ 16 + 8 * (i - 6)) ++ "(%rbp)" getRef cx (GlobalRef name) = ".global_" ++ name genAccess :: FxContext -> ValueRef -> (FxContext, String) genAccess cx (InstRef ref) = (cx, lookupVariable cx ref) genAccess cx (FunctionRef i) = (cx, "$" ++ i) genAccess cx (ConstInt i) = (cx, "$" ++ (show i)) genAccess cx (ConstString s) = let (ncx, id) = getConstStrId cx s in (ncx, "$" ++ id) genAccess cx (ConstBool b) = (cx, "$" ++ (if b then "1" else "0")) genAccess cx (ArgRef i funcName) = (cx, if i < 6 then lookupVariable cx $ funcName ++ "@" ++ (show i) else (show $ 16 + 8 * (i - 6)) ++ "(%rbp)") genAccess cx (GlobalRef name) = (cx, ".global_" ++ name) genConstants cx = ".section .rodata\n" ++ HashMap.foldWithKey (\cnst label str-> str ++ "\n" ++ label ++ ":\n .string " ++ cnst) "" (constStrs cx) gen :: LLIR.PModule -> String gen mod = let globals = LLIR.globals mod callouts = LLIR.callouts mod fxs = HashMap.elems $ LLIR.functions mod cx = newCGContext cx2 = addGlobals cx globals (cx3, fns) = foldl (\(cx, asm) fn -> let (ncx, str) = genFunction cx fn in (ncx, asm ++ str)) (cx2, "") fxs in (genGlobals globals) ++ getHeader ++ (genCallouts callouts) ++ fns ++ "\n\n" ++ (genConstants cx3) ++ "\n" pusha = " push %rax\n" ++ " push %rbx\n" ++ " push %rcx\n" ++ " push %rdx\n" ++ " push %rsi\n" ++ " push %rdi\n" ++ " push %r8\n" ++ " push %r9\n" ++ " push %r10\n" ++ " push %r11\n" ++ " push %r12\n" ++ " push %r13\n" ++ " push %r14\n" ++ " push %r15\n" popa = " pop %r15\n" ++ " pop %r14\n" ++ " pop %r13\n" ++ " pop %r12\n" ++ " pop %r11\n" ++ " pop %r10\n" ++ " pop %r9\n" ++ " pop %r8\n" ++ " pop %rdi\n" ++ " pop %rsi\n" ++ " pop %rdx\n" ++ " pop %rcx\n" ++ " pop %rbx\n" ++ " pop %rax\n"
Slava/6.035-decaf-compiler
src/CodeGen.hs
mit
25,071
6
25
7,231
8,959
4,647
4,312
552
23
{-# LANGUAGE DeriveGeneric, OverloadedStrings #-} module Pitch.Players.Network where import Control.Applicative import Control.Concurrent import Control.Monad import Control.Monad.Writer import Data.Aeson (ToJSON, toJSON, FromJSON, fromJSON, encode, decode, Value (..), object, (.:), (.=), parseJSON, (.:?)) import Data.ByteString.Lazy.Char8 (pack) import qualified Data.Text as T import GHC.Generics import Pitch.Game import Pitch.Card import Pitch.Network import Pitch.Network.JSON import System.Random data NetworkConfig = NetworkConfig {readChannel :: Chan String ,writeChannel :: Chan (Status, GameState) ,state :: MVar (Writer [String] (GameState, ActionRequired, Int)) ,authentication :: MVar (Bool, String) ,thread :: ThreadId } data ActionRequired = Wait | BidAction | PlayAction deriving (Show, Generic) instance ToJSON ActionRequired where toJSON action = String . T.pack $ case action of Wait -> "Wait" BidAction -> "Bid" PlayAction -> "Play" instance FromJSON ActionRequired where parseJSON (String v) = case T.unpack v of "Wait" -> return Wait "Bid" -> return BidAction "Play" -> return PlayAction _ -> mzero parseJSON _ = mzero data NetStatus = NetStatus {messages :: [String], gamestate :: (GameState, ActionRequired, Int)} deriving (Show, Generic) instance ToJSON NetStatus instance FromJSON NetStatus data Status = Success String | Failure String instance ToJSON Status where toJSON (Success m) = object ["code" .= toJSON (20 :: Int), "message" .= toJSON m] toJSON (Failure m) = object ["code" .= toJSON (50 :: Int), "message" .= toJSON m] instance FromJSON Status where parseJSON (Object v) = mkStatus <$> v .: "code" <*> v .: "message" parseJSON _ = mzero mkStatus :: Int -> String -> Status mkStatus 20 = Success mkStatus 50 = Failure mkNetworkConfig :: StdGen -> IO (NetworkConfig, StdGen) mkNetworkConfig g = do rchannel <- newChan wchannel <- newChan state <- newEmptyMVar authentication <- newMVar (False, token) threadId <- forkIO $ runServer (rchannel, wchannel, state, authentication) return (NetworkConfig {readChannel = rchannel ,writeChannel = wchannel ,state = state ,thread = threadId ,authentication = authentication } ,g' ) where (token, g') = iterate (\(xs, g) -> let (x, g') = randomR ('A', 'Z') g in (x:xs, g')) ([], g) !! 20 setAction :: MVar (Writer [String] (GameState, ActionRequired, Int)) -> ActionRequired -> IO () setAction mvar ar = modifyMVar_ mvar $ \w -> return (do (a, _, c) <- w return (a, ar, c)) setGameState :: MVar (Writer [String] (GameState, ActionRequired, Int)) -> GameState -> IO () setGameState mvar gs = modifyMVar_ mvar $ \w -> return (do (_, b, c) <- w return (gs, b, c)) putMessage :: MVar (Writer [String] a) -> String -> IO () putMessage mvar message = modifyMVar_ mvar $ \w -> return (do v <- w tell [message] return v) updateMVAR :: Monoid a => MVar (Writer a b) -> b -> IO () updateMVAR mvar v = do mw <- tryTakeMVar mvar case mw of Nothing -> putMVar mvar (writer (v, mempty)) Just x -> putMVar mvar (do x return v) mkNetworkPlayerFromConfig :: NetworkConfig -> String -> Player mkNetworkPlayerFromConfig netc@NetworkConfig {readChannel=rchannel ,writeChannel=wchannel ,state=state ,authentication=authentication ,thread=threadId } name = player where player = defaultPlayer { initGameState = \pid gs -> updateMVAR state (gs, Wait, pid) , mkBid = \pid gs -> do setAction state BidAction setGameState state gs string <- readChan rchannel let maybeBid = decode (pack string) :: Maybe (Int, Maybe Suit) bid <- case maybeBid of Just x -> return x Nothing -> do writeChan wchannel (Failure "Parser error", gs) (mkBid player) pid gs validatedBid <- case validateBid pid gs bid of Nothing -> return bid Just errorMessage -> do writeChan wchannel (Failure errorMessage, gs) (mkBid player) pid gs writeChan wchannel (Success "Bid accepted", gs) setAction state Wait return validatedBid , mkPlay = \pid gs -> do setAction state PlayAction setGameState state gs string <- readChan rchannel let maybeCard = decode (pack string) :: Maybe Card card <- case maybeCard of Just x -> return x Nothing -> do writeChan wchannel (Failure "Parser error", gs) (mkPlay player) pid gs validatedCard <- case validateCard pid gs card of Nothing -> return card Just errorMessage -> do writeChan wchannel (Failure errorMessage, gs) (mkPlay player) pid gs writeChan wchannel (Success "Card accepted", gs) setAction state Wait return validatedCard , -- postBidHook :: (p, Int) -> Bid -> GameState -> IO () postBidHook = \pid Bid {amount=amount,bidSuit=suit,bidderIdx=bidderIdx} gs@(Game scores players rounds hand) -> do let bidMessage = case amount of 0 -> players !! bidderIdx ++ " passed" x -> players !! bidderIdx ++ " bid " ++ show x putMessage state bidMessage setGameState state gs , -- postPlayHook :: (p, Int) -> Play -> GameState -> [Card] -> IO () postPlayHook = \pid Play {card=card,playerIdx=playerIdx} gs@(Game scores players rounds hand) -> do let playMessage = players !! playerIdx ++ " played " ++ show card putMessage state playMessage setGameState state gs , acknowledgeTrump = \pid Bid {amount=amount,bidSuit=Just suit,bidderIdx=bidderIdx} _ -> putMessage state $ "Trump is " ++ show suit , name = name } mkNetworkPlayer :: StdGen -> String -> IO (Player, StdGen) mkNetworkPlayer g name = do (conf, g) <- mkNetworkConfig g let p = mkNetworkPlayerFromConfig conf name return (p, g)
benweitzman/Pitch
src/Pitch/Players/Network.hs
mit
8,028
0
20
3,504
2,093
1,086
1,007
141
6
{-# LANGUAGE FlexibleInstances #-} module Model where import ClassyPrelude.Yesod import Database.Persist.Quasi import ModelTypes import Yesod.Auth.HashDB (HashDBUser(..)) -- You can define all of your database entities in the entities file. -- You can find more information on persistent and how to declare entities -- at: -- http://www.yesodweb.com/book/persistent/ share [mkPersist sqlSettings, mkMigrate "migrateAll"] $(persistFileWith lowerCaseSettings "config/models") instance HashDBUser User where userPasswordHash = userPassword setPasswordHash h p = p { userPassword = Just h }
ahushh/Monaba
monaba/src/Model.hs
mit
603
0
8
88
101
58
43
-1
-1
-- Multiples of Ten in a Sequence Which Values Climb Up -- http://www.codewars.com/kata/561d54055e399e2f62000045/ module Codewars.Kata.ClimbUp where import Control.Arrow ((&&&)) findMult10SF :: Int -> Integer findMult10SF = uncurry (+) . ((*3) . (2^) &&& (*9) . (6^)) . (+ (-3)) . (*4)
gafiatulin/codewars
src/Beta/ClimbUp.hs
mit
289
0
12
44
96
61
35
-1
-1
{- Model of explosion of buried curved charge. Proposed by L. M. Kotlyar in 1970's Makes possible the calculations of blast edges given set parameters. Explosion is modelled as potential flow of ideal liquid. Encoded by Saphronov Mark a. k. a. hijarian 2011.09 Public Domain -} module Model.Functions ( dzdu, dzdu', coeffCalculationHelper ) where import Data.Complex import Data.Complex.Integrate -- We need theta-functions here, -- see http://mathworld.wolfram.com/JacobiThetaFunctions.html import Numeric.Functions.Theta -- We import the data type named "ModelParams" from there import Model.Params type AuxiliaryDomainComplexValue = Complex Double type OriginDomainComplexValue = Complex Double ----------------------------------------------------------------------- -- DZDU FUNCTIONS BEGIN ----------------------------------------------------------------------- -- dz/du -- That is, differential of the mapping from auxiliary domain U to origin domain Z dzdu :: ModelParams -> AuxiliaryDomainComplexValue -> OriginDomainComplexValue dzdu p u = dwdu p u * exp (chi p u) -- dz/du -- Provided here for testing and comparing purposes -- It's a mathematically simplified equivalent of original `dzdu` dzdu' :: ModelParams -> AuxiliaryDomainComplexValue -> OriginDomainComplexValue dzdu' p u = (dzdu_simple p u) * (exp $ f_corr p u) -- Calculates simplified version of the area. It needs correcting function f_corr dzdu_simple :: ModelParams -> Complex Double -> Complex Double dzdu_simple p u = nval' * eval' * divident' / divisor'' where nval' = (mfunc p) * ((toComplex.negate) $ (phi_0 p) / pi / (v_0 p)) eval' = exp ( 0 :+ ((1 - alpha p) * pi)) divident' = t1m4t p u * t1p4t p u * t2m4t p u * t2p4t p u divisor'' = (t1m4 p u * t4m4 p u) ** ((1 - alpha p) :+ 0) * (t1p4 p u * t4p4 p u) ** ((1 + alpha p) :+ 0) ----------------------------------------------------------------------- -- DZDU FUNCTIONS END ----------------------------------------------------------------------- -------------------------------------------------------------------------------- -- Helper which will be passed to the method which renews coefficients -- It's a function which uses `chi` method, so, we cannot really use this helper -- right in the module which needs it. coeffCalculationHelper :: ModelParams -> Double -> Double coeffCalculationHelper param e = curvature param (t e) where t e = imagPart $ chi param (0 :+ e) -- Curvature. -- Parametrized by the length of the curve, so, has a single argument -- which is a point at the curve. -- Returns the curvature at this point -- TODO: Maybe should convert this function to Complex valued? curvature :: ModelParams -> Double -> Double curvature param x = ((1 - epssin) ** (3/2)) / p where epssin = (epsilon * (sin x)) ^ 2 -- Here we see with our own eyes that RAD_B MUST BE GREATER THAN RAD_A! epsilon = ( sqrt ( b'*b' - a'*a' ) ) / b' p = (a'*a') / (b'*b') a' = rad_a param b' = rad_b param -------------------------------------------------------------------------------- ----------------------------------------------------------------------- -- CORE FUNCTIONS BEGIN ----------------------------------------------------------------------- -- The mapping between points in auxillary -- domain `u` and source domain `z` is defined as: -- dzdu param u = ((dwdu param u)) * exp ( negate $ chi param u ) -- and `chi` is `chi_0 - f_corr` -- So, we need to provide functions dwdu, chi_0 and f_corr -- Derivative of the complex potential dwdu dwdu :: ModelParams -> Complex Double -> Complex Double dwdu p u = npar * (mfunc p) * divident / divisor where npar = toComplex.negate $ phi_0' / pi divident = (t1m4t p u) * (t1p4t p u) * (t2m4t p u) * (t2p4t p u) divisor = (t1m4 p u) * (t1p4 p u) * (t4m4 p u) * (t4p4 p u) phi_0' = phi_0 p -- Small helper for dwdu function mfunc :: ModelParams -> Complex Double mfunc param = (* 2) . (** 2) . (/ divisor) $ divident where divisor = (t2z param) * (t3z param) * (t4z param) divident = (** 2) . abs $ t14p4t param -- Zhukovsky function chi chi :: ModelParams -> Complex Double -> Complex Double chi param u = (chi_0 param u) - (f_corr param u) -- Zhukovsky function chi_0 for simplified problem chi_0 :: ModelParams -> Complex Double -> Complex Double chi_0 p u = (+ cpar).(* (toComplex g)).log $ divident / divisor where cpar = toImaginary $ (pi * (g - 1)) g = alpha p divident = (t1p4 p u) * (t4p4 p u) divisor = (t1m4 p u) * (t4m4 p u) -- Correcting function f(u) -- For it to work, in the ModelParams object there should be already calculated values -- of the coefficients `cN` in field `cn` f_corr :: ModelParams -> Complex Double -> Complex Double f_corr p u = const_part + (foldl (+) c0 (f_arg u clist)) where const_part = ((4 * (1 - (gamma/2)) * negate(1/tau') ) :+ 0) * u gamma = alpha p c0 = 0 :+ 0 -- :) f_arg u clist = map (\ (n, cn) -> ((cn * (1 - rho n)) :+ 0) * exp' n) clist clist = zip [1..(n_cn p)] (c_n p) exp' n = exp $ (4 * u - pi * (fromInteger n)) / (tau' :+ 0) rho n = exp $ (negate (2 * pi * fromInteger n)) / tau' tau' = tau p ----------------------------------------------------------------------- -- CORE FUNCTIONS END ----------------------------------------------------------------------- ----------------------------------------------------------------------- -- HELPER FUNCTIONS BEGIN ----------------------------------------------------------------------- -- Semantically converting to complex toComplex :: (RealFloat a) => a -> Complex a toComplex = (:+ 0) -- Semantically converting to pure imaginary number -- Equals to multiplying the real number by i toImaginary :: (RealFloat a) => a -> Complex a toImaginary = ((:+) 0) -- We will use theta-functions with parameters from object -- typed ModelParams, so let's write a helper so we will be able -- to write just thetaN' <p> <u> theta1' param = theta1 (n_theta param) (qpar (tau param)) theta2' param = theta2 (n_theta param) (qpar (tau param)) theta3' param = theta3 (n_theta param) (qpar (tau param)) theta4' param = theta4 (n_theta param) (qpar (tau param)) --pi4 :: (RealFloat a) => a pi4 = pi / 4 --pi4t :: ModelParams -> Complex Double pi4t p = toImaginary . (* pi4) $ (tau p) -- This is a set of helper functions to quickly calculate -- some often encountered theta function invocations t1m4t, t1p4t, t1m4, t1p4 :: ModelParams -> Complex Double -> Complex Double t1m4t p u = theta1' p (u - ( pi4t p )) t1p4t p u = theta1' p (u + ( pi4t p )) t1m4 p u = theta1' p (u - (toComplex pi4)) t1p4 p u = theta1' p (u + (toComplex pi4)) t1z :: ModelParams -> Complex Double t1z p = theta1' p (0 :+ 0) t14p4t :: ModelParams -> Complex Double t14p4t p = theta1' p ((toComplex pi4) + ( pi4t p )) t2m4t, t2p4t, t2m4, t2p4 :: ModelParams -> Complex Double -> Complex Double t2m4t p u = theta2' p (u - ( pi4t p )) t2p4t p u = theta2' p (u + ( pi4t p )) t2m4 p u = theta2' p (u - (toComplex pi4)) t2p4 p u = theta2' p (u + (toComplex pi4)) t2z :: ModelParams -> Complex Double t2z p = theta2' p (0 :+ 0) t3m4t, t3p4t, t3m4, t3p4 :: ModelParams -> Complex Double -> Complex Double t3m4t p u = theta3' p (u - ( pi4t p )) t3p4t p u = theta3' p (u + ( pi4t p )) t3m4 p u = theta3' p (u - (toComplex pi4)) t3p4 p u = theta3' p (u + (toComplex pi4)) t3z :: ModelParams -> Complex Double t3z p = theta3' p (0 :+ 0) t4m4t, t4p4t, t4m4, t4p4 :: ModelParams -> Complex Double -> Complex Double t4m4t p u = theta4' p (u - ( pi4t p )) t4p4t p u = theta4' p (u + ( pi4t p )) t4m4 p u = theta4' p (u - (toComplex pi4)) t4p4 p u = theta4' p (u + (toComplex pi4)) t4z :: ModelParams -> Complex Double t4z p = theta4' p (0 :+ 0) ----------------------------------------------------------------------- -- HELPER FUNCTIONS END -----------------------------------------------------------------------
hijarian/AFCALC
program/src/Model/Functions.hs
cc0-1.0
8,074
1
17
1,672
2,351
1,249
1,102
98
1
{-# LANGUAGE TemplateHaskell, DeriveDataTypeable #-} module Lambda.Backward_Join.Solution where import Lambda.Type import Autolib.ToDoc import Autolib.Reader import Data.Typeable data Type = Make { start :: Lambda , left_steps :: [ Int ] , right_steps :: [ Int ] } deriving ( Typeable, Eq, Ord ) $(derives [makeReader, makeToDoc] [''Type]) example :: Type example = Make { start = read "(x -> x x)( x -> x x)" , left_steps = [0] , right_steps = [1] } -- local variables: -- mode: haskell -- end;
Erdwolf/autotool-bonn
src/Lambda/Backward_Join/Solution.hs
gpl-2.0
581
0
9
167
141
86
55
17
1
module Text.Pandoc.CrossRef.Util.CustomLabels (customLabel) where import Text.Pandoc.Definition import Text.Pandoc.CrossRef.Util.Meta import Control.Monad import Data.List import Text.Numeral.Roman customLabel :: Meta -> String -> Int -> Maybe String customLabel meta ref i | refLabel <- takeWhile (/=':') ref , Just cl <- lookupMeta (refLabel++"Labels") meta = mkLabel i cl | otherwise = Nothing mkLabel :: Int -> MetaValue -> Maybe String mkLabel i lt | toString lt == Just "arabic" = Nothing | toString lt == Just "roman" = Just $ toRoman i | Just (startWith:_) <- join $ stripPrefix "alpha " `fmap` toString lt = Just [[startWith..] !! (i-1)] | Just val <- join $ toString `fmap` getList (i-1) lt = Just val | otherwise = error $ "Unknown numeration type: " ++ show lt
infotroph/pandoc-crossref
lib/Text/Pandoc/CrossRef/Util/CustomLabels.hs
gpl-2.0
802
0
12
151
320
161
159
23
1
module Main ( main ) where import Test.Framework (defaultMain, testGroup, Test) import Test.Framework.Providers.HUnit import Test.Framework.Providers.QuickCheck2 (testProperty) -- import Test.QuickCheck import Test.HUnit hiding (Test) import Handy.List main :: IO () main = defaultMain tests tests :: [Test] tests = [ testGroup "Handy.List" [ testGroup "ordElem" [ testCaseSimple "Contains first" test_ordElem_1 , testCaseSimple "Contains middle" test_ordElem_2 , testCaseSimple "Contains last" test_ordElem_3 , testCaseSimple "Does not contain before" test_ordElem_4 , testCaseSimple "Does not contain middle" test_ordElem_5 , testCaseSimple "Does not contain after" test_ordElem_6 , testCaseSimple "Contains infinite" test_ordElem_7 , testCaseSimple "Does not contain infinite" test_ordElem_8 ] , testGroup "breakAll" [ testProperty "Relation to filter" prop_breakAll_1 , testProperty "Lengths" prop_breakAll_2 , testCaseSimple "Lazyness" test_breakAll_1 ] ] , testGroup "Trivial" [ testCase "test" test_trivial_1 , testProperty "prop" prop_trivial_1 ] ] testCaseSimple :: AssertionPredicable t => String -> t -> Test testCaseSimple msg b = testCase msg (b @? msg) test_trivial_1 :: Assertion test_trivial_1 = () @?= () prop_trivial_1 :: () -> Bool prop_trivial_1 x = x == x holedFiniteList :: [Int] holedFiniteList = [100,102..200] test_ordElem_1 :: Bool test_ordElem_1 = 100 `ordElem` holedFiniteList test_ordElem_2 :: Bool test_ordElem_2 = 150 `ordElem` holedFiniteList test_ordElem_3 :: Bool test_ordElem_3 = 200 `ordElem` holedFiniteList test_ordElem_4 :: Bool test_ordElem_4 = not $ 1 `ordElem` holedFiniteList test_ordElem_5 :: Bool test_ordElem_5 = not $ 151 `ordElem` holedFiniteList test_ordElem_6 :: Bool test_ordElem_6 = not $ 300 `ordElem` holedFiniteList holedInfiniteList :: [Integer] holedInfiniteList = [1,3..] test_ordElem_7 :: Bool test_ordElem_7 = 1001 `ordElem` holedInfiniteList test_ordElem_8 :: Bool test_ordElem_8 = not $ 1000 `ordElem` holedInfiniteList prop_breakAll_1 :: [Int] -> [Int] -> Bool prop_breakAll_1 l s = concat (breakAll p s) == filter (not . p) s where p = flip elem l prop_breakAll_2 :: [Int] -> [Int] -> Bool prop_breakAll_2 l s = length (breakAll p s) == length (filter p s) + 1 where p = flip elem l test_breakAll_1 :: Bool test_breakAll_1 = head (head (breakAll (const False) holedInfiniteList)) == head holedInfiniteList
xkollar/handy-haskell
handy/test/HandyTest.hs
gpl-3.0
2,616
0
12
562
674
372
302
61
1
module Main where import Data.Char (toLower) import Data.Set (Set, fromList, member) import GameState import System.IO (IOMode (ReadMode), hGetContents, openFile) import System.Random (getStdGen, randomR) getWordsLst :: IO [String] getWordsLst = do handle <- openFile "words" ReadMode contents <- hGetContents handle return $ words contents getRandomWord :: [String] -> IO String getRandomWord words = do gen <- getStdGen let (i, _) = randomR (0, (length words) - 1) gen in return $ words !! i main = do words <- getWordsLst word <- getRandomWord words -- putStrLn $ "word is: " ++ word makeGameStep (GameState (map toLower word) $ fromList "")
dasdy/Hangman
src/Main.hs
gpl-3.0
736
0
15
190
244
127
117
20
1
{-# LANGUAGE OverloadedStrings #-} module Sets.Controller where import Control.Monad.Trans.Either (runEitherT) import qualified Data.Text as T import Network.Wai (Response) import Web.Fn import Ctxt import Kiss import Sets.View import Upload import Users.Model userUploadHandler :: User -> Ctxt -> File -> IO (Maybe Response) userUploadHandler user ctxt (File name _ filePath') = do output <- runEitherT $ processSet (userUsername user) (T.unpack name, filePath') renderKissSet ctxt output userSetHandler :: User -> Ctxt -> T.Text -> IO (Maybe Response) userSetHandler user ctxt setName = do let userDir = staticUserDir (userUsername user) let staticDir = staticSetDir userDir (T.unpack setName) output <- (fmap . fmap) ((,) staticDir) (runEitherT $ createCels staticDir) -- The previous line is a bit weird. -- the result of runEitherT is an `IO (Either Text [KissCel])`. -- `renderKissSet` wants an `Either Text (FilePath, [KissCel])` -- The `(,)` lets us turn two things into a tuple. -- `(fmap . fmap)` let's us map into two layers of functions -- first the -- IO functor, then then Either functor. This makes the Right side of -- the Either a tuple! Whew. renderKissSet ctxt output renderKissSet :: Ctxt -> Either T.Text (FilePath, [KissCel]) -> IO (Maybe Response) renderKissSet ctxt eOutputError = case eOutputError of Right (staticDir, cels) -> renderWith ctxt ["users", "kiss-set"] $ setSplices staticDir cels Left e -> errText e
huggablemonad/smooch
app/src/Sets/Controller.hs
gpl-3.0
1,636
0
13
412
382
200
182
28
2
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Content.Accounts.AuthInfo -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Returns information about the authenticated user. -- -- /See:/ <https://developers.google.com/shopping-content Content API for Shopping Reference> for @content.accounts.authinfo@. module Network.Google.Resource.Content.Accounts.AuthInfo ( -- * REST Resource AccountsAuthInfoResource -- * Creating a Request , accountsAuthInfo , AccountsAuthInfo ) where import Network.Google.Prelude import Network.Google.ShoppingContent.Types -- | A resource alias for @content.accounts.authinfo@ method which the -- 'AccountsAuthInfo' request conforms to. type AccountsAuthInfoResource = "content" :> "v2" :> "accounts" :> "authinfo" :> QueryParam "alt" AltJSON :> Get '[JSON] AccountsAuthInfoResponse -- | Returns information about the authenticated user. -- -- /See:/ 'accountsAuthInfo' smart constructor. data AccountsAuthInfo = AccountsAuthInfo' deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'AccountsAuthInfo' with the minimum fields required to make a request. -- accountsAuthInfo :: AccountsAuthInfo accountsAuthInfo = AccountsAuthInfo' instance GoogleRequest AccountsAuthInfo where type Rs AccountsAuthInfo = AccountsAuthInfoResponse type Scopes AccountsAuthInfo = '["https://www.googleapis.com/auth/content"] requestClient AccountsAuthInfo'{} = go (Just AltJSON) shoppingContentService where go = buildClient (Proxy :: Proxy AccountsAuthInfoResource) mempty
rueshyna/gogol
gogol-shopping-content/gen/Network/Google/Resource/Content/Accounts/AuthInfo.hs
mpl-2.0
2,393
0
12
536
222
138
84
42
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.CloudErrorReporting.Projects.DeleteEvents -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Deletes all error events of a given project. -- -- /See:/ <https://cloud.google.com/error-reporting/ Error Reporting API Reference> for @clouderrorreporting.projects.deleteEvents@. module Network.Google.Resource.CloudErrorReporting.Projects.DeleteEvents ( -- * REST Resource ProjectsDeleteEventsResource -- * Creating a Request , projectsDeleteEvents , ProjectsDeleteEvents -- * Request Lenses , pdeXgafv , pdeUploadProtocol , pdeAccessToken , pdeUploadType , pdeProjectName , pdeCallback ) where import Network.Google.CloudErrorReporting.Types import Network.Google.Prelude -- | A resource alias for @clouderrorreporting.projects.deleteEvents@ method which the -- 'ProjectsDeleteEvents' request conforms to. type ProjectsDeleteEventsResource = "v1beta1" :> Capture "projectName" Text :> "events" :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Delete '[JSON] DeleteEventsResponse -- | Deletes all error events of a given project. -- -- /See:/ 'projectsDeleteEvents' smart constructor. data ProjectsDeleteEvents = ProjectsDeleteEvents' { _pdeXgafv :: !(Maybe Xgafv) , _pdeUploadProtocol :: !(Maybe Text) , _pdeAccessToken :: !(Maybe Text) , _pdeUploadType :: !(Maybe Text) , _pdeProjectName :: !Text , _pdeCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ProjectsDeleteEvents' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pdeXgafv' -- -- * 'pdeUploadProtocol' -- -- * 'pdeAccessToken' -- -- * 'pdeUploadType' -- -- * 'pdeProjectName' -- -- * 'pdeCallback' projectsDeleteEvents :: Text -- ^ 'pdeProjectName' -> ProjectsDeleteEvents projectsDeleteEvents pPdeProjectName_ = ProjectsDeleteEvents' { _pdeXgafv = Nothing , _pdeUploadProtocol = Nothing , _pdeAccessToken = Nothing , _pdeUploadType = Nothing , _pdeProjectName = pPdeProjectName_ , _pdeCallback = Nothing } -- | V1 error format. pdeXgafv :: Lens' ProjectsDeleteEvents (Maybe Xgafv) pdeXgafv = lens _pdeXgafv (\ s a -> s{_pdeXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). pdeUploadProtocol :: Lens' ProjectsDeleteEvents (Maybe Text) pdeUploadProtocol = lens _pdeUploadProtocol (\ s a -> s{_pdeUploadProtocol = a}) -- | OAuth access token. pdeAccessToken :: Lens' ProjectsDeleteEvents (Maybe Text) pdeAccessToken = lens _pdeAccessToken (\ s a -> s{_pdeAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). pdeUploadType :: Lens' ProjectsDeleteEvents (Maybe Text) pdeUploadType = lens _pdeUploadType (\ s a -> s{_pdeUploadType = a}) -- | Required. The resource name of the Google Cloud Platform project. -- Written as \`projects\/{projectID}\`, where \`{projectID}\` is the -- [Google Cloud Platform project -- ID](https:\/\/support.google.com\/cloud\/answer\/6158840). Example: -- \`projects\/my-project-123\`. pdeProjectName :: Lens' ProjectsDeleteEvents Text pdeProjectName = lens _pdeProjectName (\ s a -> s{_pdeProjectName = a}) -- | JSONP pdeCallback :: Lens' ProjectsDeleteEvents (Maybe Text) pdeCallback = lens _pdeCallback (\ s a -> s{_pdeCallback = a}) instance GoogleRequest ProjectsDeleteEvents where type Rs ProjectsDeleteEvents = DeleteEventsResponse type Scopes ProjectsDeleteEvents = '["https://www.googleapis.com/auth/cloud-platform"] requestClient ProjectsDeleteEvents'{..} = go _pdeProjectName _pdeXgafv _pdeUploadProtocol _pdeAccessToken _pdeUploadType _pdeCallback (Just AltJSON) cloudErrorReportingService where go = buildClient (Proxy :: Proxy ProjectsDeleteEventsResource) mempty
brendanhay/gogol
gogol-clouderrorreporting/gen/Network/Google/Resource/CloudErrorReporting/Projects/DeleteEvents.hs
mpl-2.0
5,001
0
16
1,104
702
411
291
104
1
module Ch5Exercises where -- multiple choice: -- 1 -> c -- 2. a -- 3. b -- 4. c func1a = (* 9) 6 func1b = head [(0,"doge"),(1,"kitteh")] func1c = head [(0 :: Integer, "doge"),(1,"kitteh")] func1d = if False then True else False func1e = length [1,2,3,4,5] func1f = (length [1,2,3,4]) > (length "TACOCAT")
thewoolleyman/haskellbook
05/09/maor/ch5Exercises.hs
unlicense
310
0
8
59
145
90
55
7
2
{-# LANGUAGE PolyKinds #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE DefaultSignatures #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE BangPatterns #-} {-# LANGUAGE MultiParamTypeClasses #-} -- The generic implementation for the protocol that converts to -- and from SQL cells. -- Going through JSON is not recommended because of precision loss -- for the numbers, and other issues related to numbers. module Spark.Core.Internal.RowGenerics( ToSQL, valueToCell, ) where import GHC.Generics import qualified Data.Vector as V import Data.Text(pack, Text) import Spark.Core.Internal.RowStructures import Spark.Core.Internal.Utilities -- We need to differentiate between the list built for the -- constructor and an inner object. data CurrentBuffer = ConsData ![Cell] | BuiltCell !Cell deriving (Show) _cellOrError :: CurrentBuffer -> Cell _cellOrError (BuiltCell cell) = cell _cellOrError x = let msg = "Expected built cell, received " ++ show x in failure (pack msg) -- All the types that can be converted to a SQL value. class ToSQL a where _valueToCell :: a -> Cell default _valueToCell :: (Generic a, GToSQL (Rep a)) => a -> Cell _valueToCell !x = _g2cell (from x) valueToCell :: (ToSQL a) => a -> Cell valueToCell = _valueToCell -- class FromSQL a where -- _cellToValue :: Cell -> Try a instance ToSQL a => ToSQL (Maybe a) where _valueToCell (Just x) = _valueToCell x _valueToCell Nothing = Empty instance (ToSQL a, ToSQL b) => ToSQL (a, b) where _valueToCell (x, y) = RowArray (V.fromList [valueToCell x, valueToCell y]) instance ToSQL Int where _valueToCell = IntElement instance ToSQL Double where _valueToCell = DoubleElement instance ToSQL Text where _valueToCell = StringElement class GToSQL r where _g2buffer :: r a -> CurrentBuffer _g2cell :: r a -> Cell _g2cell = _cellOrError . _g2buffer instance GToSQL U1 where _g2buffer U1 = failure $ pack "GToSQL UI called" -- | Constants, additional parameters and recursion of kind * instance (GToSQL a, GToSQL b) => GToSQL (a :*: b) where _g2buffer (a :*: b) = case (_g2buffer a, _g2buffer b) of (ConsData l1, ConsData l2) -> ConsData (l1 ++ l2) (y1, y2) -> failure $ pack $ "GToSQL (a :*: b): Expected buffers, received " ++ show y1 ++ " and " ++ show y2 instance (GToSQL a, GToSQL b) => GToSQL (a :+: b) where _g2buffer (L1 x) = _g2buffer x _g2buffer (R1 x) = let !y = _g2buffer x in y -- -- | Sums: encode choice between constructors -- instance (GToSQL a) => GToSQL (M1 i c a) where -- _g2cell !(M1 x) = let !y = _g2cell x in -- trace ("GToSQL M1: y = " ++ show y) y instance (GToSQL a) => GToSQL (M1 C c a) where _g2buffer (M1 x) = let !y = _g2buffer x in y instance (GToSQL a) => GToSQL (M1 S c a) where _g2buffer (M1 x) = let !y = ConsData [_g2cell x] in y instance (GToSQL a) => GToSQL (M1 D c a) where _g2buffer (M1 x) = case _g2buffer x of ConsData cs -> BuiltCell $ RowArray (V.fromList cs) BuiltCell cell -> BuiltCell cell -- | Products: encode multiple arguments to constructors instance (ToSQL a) => GToSQL (K1 i a) where _g2buffer (K1 x) = let !y = _valueToCell x in BuiltCell y
krapsh/kraps-haskell
src/Spark/Core/Internal/RowGenerics.hs
apache-2.0
3,263
0
13
647
938
488
450
69
1
{-# LANGUAGE TypeFamilies, OverloadedLists, FlexibleInstances, FunctionalDependencies, ViewPatterns, MultiParamTypeClasses, UnicodeSyntax, GeneralizedNewtypeDeriving #-} module Fuzzy.Bool where import Prelude.Unicode import Control.Applicative import Data.Monoid import GHC.Exts class Adjunct f u | f β†’ u where forget ∷ f β†’ u construct ∷ u β†’ f newtype PolygonicNumber = Poly { unPoly ∷ [Double] } instance Show PolygonicNumber where show (forget β†’ [a,b,c]) = "Poly $ " <> show a <> " ← " <> show b <> " β†’ " <> show c instance Adjunct PolygonicNumber [Double] where forget (Poly xs) = xs construct = Poly instance IsList PolygonicNumber where type Item PolygonicNumber = Double fromList = Poly toList (Poly xs) = xs instance Eq PolygonicNumber where (==) (forget β†’ [al,bl,cl]) (forget β†’ [ar, br, cr]) | ar ≑ al ∧ br ≑ ar ∧ cr ≑ cl = True | otherwise = False instance Ord PolygonicNumber where (<=) (forget β†’ [al, bl, cl]) (forget β†’ [ar, br, cr]) | bl ≑ br ∧ cl ≀ cr ∧ al ≀ ar = True | otherwise = False class PolyNumbers Ξ² where ΞΌ ∷ Ξ² β†’ Double β†’ Double spreadleft ∷ Ξ² β†’ Double spreadright :: Ξ² β†’ Double instance PolyNumbers PolygonicNumber where ΞΌ Ξ²@(forget β†’ [a,b,c]) x | a ≀ x ∧ x ≀ b = (x - a) / spreadleft Ξ² | b ≀ x ∧ x ≀ c = (c - x) / spreadright Ξ² | otherwise = 0 spreadleft (forget β†’ [a,b,c]) = b - a spreadright (forget β†’ [a,b,c]) = c - b instance Fractional PolygonicNumber where fromRational a = Poly $ let b = fromRational a in [b,b,b] (/) (forget β†’ xs) (forget β†’ ys) = construct $ zipWith (/) xs ys member ∷ PolyNumbers a β‡’ a β†’ Double β†’ Double member = ΞΌ -- | These types of fuzzy logics are all monoidal in nature class FuzzyLogic Ξ± where -- | Laws -- -- for Ο„-norm ∷ Ξ± β†’ Ξ± β†’ Ξ± -- with tunit ∷ Ξ± -- Ξ± βŠ• Ξ² = Ξ² βŠ• Ξ± -- Ξ± βŠ• Ξ² ≀ Ξ³ βŠ• Ξ΄ if Ξ± ≀ Ξ³ and Ξ² ≀ Ξ΄ -- Ξ± βŠ• (Ξ² βŠ• Ξ³) = (Ξ± βŠ• Ξ²) βŠ• Ξ³ -- tunit βŠ• Ξ± = Ξ± -- Ξ± βŠ• tunit = Ξ± tnorm :: Ξ± -> Ξ± -> Ξ± tunit ∷ Ξ± -- | Forget the algebraic structure instance Num PolygonicNumber where -- Creates a spike with exactly spread 0 fromInteger x = construct $ fromInteger <$> [x,x,x] (forget β†’ xs) + (forget β†’ ys) = construct $ zipWith (+) xs ys (forget β†’ xs) * (forget β†’ ys) = construct $ zipWith (*) xs ys abs (forget β†’ xs) = construct $ abs <$> xs negate (forget β†’ xs) = construct $ reverse $ negate <$> xs signum (forget β†’ xs) = construct $ signum <$> xs fib ∷ (Eq a, Fractional a, Num a) β‡’ a β†’ a fib a | a ≑ 0 = 0 fib n = fib (n - 1) + fib (n - 2)
edgarklerks/document-indexer
Fuzzy/Bool.hs
bsd-2-clause
2,977
0
13
907
998
537
461
55
1
{-# LANGUAGE RankNTypes #-} module Graphics.GL.Low.Framebuffer ( -- | By default, rendering commands output graphics to the default framebuffer. -- This includes the color buffer, the depth buffer, and the stencil buffer. It -- is possible to render to a texture instead. This is important for many -- techniques. Rendering to a texture (either color, depth, or depth/stencil) -- is accomplished by using a framebuffer object (FBO). -- -- The following ritual sets up an FBO with a blank 256x256 color texture for -- off-screen rendering: -- -- @ -- do -- fbo <- newFBO -- tex <- newEmptyTexture2D 256 256 :: IO (Tex2D RGB) -- bindFramebuffer fbo -- attachTex2D tex -- bindFramebuffer DefaultFramebuffer -- return (fbo, tex) -- @ -- -- After binding an FBO to the framebuffer binding target, rendering commands -- will output to its color attachment and possible depth/stencil attachment -- if present. An FBO must have a color attachment before rendering. If only -- the depth results are needed, then you can attach a color RBO instead of -- a texture to the color attachment point. newFBO, bindFramebuffer, deleteFBO, attachTex2D, attachCubeMap, attachRBO, newRBO, deleteRBO, FBO, DefaultFramebuffer(..), RBO -- * Example -- $example ) where import Foreign.Ptr import Foreign.Marshal import Foreign.Storable import Control.Monad.IO.Class import Data.Default import Graphics.GL import Graphics.GL.Low.Internal.Types import Graphics.GL.Low.Classes import Graphics.GL.Low.Common import Graphics.GL.Low.Cube import Graphics.GL.Low.Texture -- | The default framebuffer. data DefaultFramebuffer = DefaultFramebuffer deriving Show instance Default DefaultFramebuffer where def = DefaultFramebuffer instance Framebuffer DefaultFramebuffer where framebufferName _ = 0 -- | Binds an FBO or the default framebuffer to the framebuffer binding target. -- Replaces the framebuffer already bound there. bindFramebuffer :: (MonadIO m, Framebuffer a) => a -> m () bindFramebuffer x = glBindFramebuffer GL_FRAMEBUFFER (framebufferName x) -- | Create a new framebuffer object. Before the framebuffer can be used for -- rendering it must have a color image attachment. newFBO :: (MonadIO m) => m FBO newFBO = liftIO . fmap FBO $ alloca (\ptr -> glGenFramebuffers 1 ptr >> peek ptr) -- | Delete an FBO. deleteFBO :: (MonadIO m) => FBO -> m () deleteFBO (FBO n) = liftIO $ withArray [n] (\ptr -> glDeleteFramebuffers 1 ptr) -- | Attach a 2D texture to the FBO currently bound to the -- framebuffer binding target. attachTex2D :: (MonadIO m, Attachable a) => Tex2D a -> m () attachTex2D tex = glFramebufferTexture2D GL_FRAMEBUFFER (attachPoint tex) GL_TEXTURE_2D (glObjectName tex) 0 -- | Attach one of the sides of a cubemap texture to the FBO currently bound -- to the framebuffer binding target. attachCubeMap :: (MonadIO m, Attachable a) => CubeMap a -> Side -> m () attachCubeMap cm side = glFramebufferTexture2D GL_FRAMEBUFFER (attachPoint cm) (side cubeSideCodes) (glObjectName cm) 0 -- | Attach an RBO to the FBO currently bound to the framebuffer binding -- target. attachRBO :: (MonadIO m, Attachable a) => RBO a -> m () attachRBO rbo = glFramebufferRenderbuffer GL_FRAMEBUFFER (attachPoint rbo) GL_RENDERBUFFER (unRBO rbo) -- | Create a new renderbuffer with the specified dimensions. newRBO :: (MonadIO m, InternalFormat a) => Int -> Int -> m (RBO a) newRBO w h = do n <- liftIO $ alloca (\ptr -> glGenRenderbuffers 1 ptr >> peek ptr) rbo <- return (RBO n) glBindRenderbuffer GL_RENDERBUFFER n glRenderbufferStorage GL_RENDERBUFFER (internalFormat rbo) (fromIntegral w) (fromIntegral h) return rbo -- | Delete an RBO. deleteRBO :: (MonadIO m) => RBO a -> m () deleteRBO (RBO n) = liftIO $ withArray [n] (\ptr -> glDeleteRenderbuffers 1 ptr) -- $example -- -- <<framebuffer.gif Animated screenshot showing post-processing effect>> -- -- This example program renders an animating object to an off-screen -- framebuffer. The resulting texture is then shown on a full-screen quad -- with an effect. -- -- @ -- module Main where -- -- import Control.Monad.Loops (whileM_) -- import Data.Functor ((\<$\>)) -- import qualified Data.Vector.Storable as V -- import Data.Maybe (fromJust) -- import Data.Default -- import Data.Word -- -- import qualified Graphics.UI.GLFW as GLFW -- import Linear -- import Graphics.GL.Low -- -- main = do -- GLFW.init -- GLFW.windowHint (GLFW.WindowHint'ContextVersionMajor 3) -- GLFW.windowHint (GLFW.WindowHint'ContextVersionMinor 2) -- GLFW.windowHint (GLFW.WindowHint'OpenGLForwardCompat True) -- GLFW.windowHint (GLFW.WindowHint'OpenGLProfile GLFW.OpenGLProfile'Core) -- mwin <- GLFW.createWindow 640 480 \"Framebuffer\" Nothing Nothing -- case mwin of -- Nothing -> putStrLn "createWindow failed" -- Just win -> do -- GLFW.makeContextCurrent (Just win) -- GLFW.swapInterval 1 -- (vao1, vao2, prog1, prog2, fbo, texture) <- setup -- whileM_ (not <$> GLFW.windowShouldClose win) $ do -- GLFW.pollEvents -- t <- (realToFrac . fromJust) \<$\> GLFW.getTime -- draw vao1 vao2 prog1 prog2 fbo texture t -- GLFW.swapBuffers win -- -- setup = do -- -- primary subject -- vao1 <- newVAO -- bindVAO vao1 -- let blob = V.fromList -- [ -0.5, -0.5, 0, 0 -- , 0, 0.5, 0, 1 -- , 0.5, -0.5, 1, 1] :: V.Vector Float -- vbo <- newVBO blob StaticDraw -- bindVBO vbo -- vsource <- readFile "framebuffer.vert" -- fsource1 <- readFile "framebuffer1.frag" -- prog1 <- newProgram vsource fsource1 -- useProgram prog1 -- setVertexLayout -- [ Attrib "position" 2 GLFloat -- , Attrib "texcoord" 2 GLFloat ] -- -- -- full-screen quad to show the post-processed scene -- vao2 <- newVAO -- bindVAO vao2 -- let blob = V.fromList -- [ -1, -1, 0, 0 -- , -1, 1, 0, 1 -- , 1, -1, 1, 0 -- , 1, 1, 1, 1] :: V.Vector Float -- vbo <- newVBO blob StaticDraw -- bindVBO vbo -- indices <- newElementArray (V.fromList [0,1,2,3,2,1] :: V.Vector Word8) StaticDraw -- bindElementArray indices -- fsource2 <- readFile "framebuffer2.frag" -- prog2 <- newProgram vsource fsource2 -- useProgram prog2 -- setVertexLayout -- [ Attrib "position" 2 GLFloat -- , Attrib "texcoord" 2 GLFloat ] -- -- -- create an FBO to render the primary scene on -- fbo <- newFBO -- bindFramebuffer fbo -- texture <- newEmptyTexture2D 640 480 :: IO (Tex2D RGB) -- bindTexture2D texture -- setTex2DFiltering Linear -- attachTex2D texture -- return (vao1, vao2, prog1, prog2, fbo, texture) -- -- draw :: VAO -> VAO -> Program -> Program -> FBO -> Tex2D RGB -> Float -> IO () -- draw vao1 vao2 prog1 prog2 fbo texture t = do -- -- render primary scene to fbo -- bindVAO vao1 -- bindFramebuffer fbo -- useProgram prog1 -- clearColorBuffer (0,0,0) -- setUniform1f "time" [t] -- drawTriangles 3 -- -- -- render results to quad on main screen -- bindVAO vao2 -- bindFramebuffer DefaultFramebuffer -- useProgram prog2 -- bindTexture2D texture -- clearColorBuffer (0,0,0) -- setUniform1f "time" [t] -- drawIndexedTriangles 6 UByteIndices -- @ -- -- The vertex shader for this program is -- -- @ -- #version 150 -- in vec2 position; -- in vec2 texcoord; -- out vec2 Texcoord; -- void main() -- { -- gl_Position = vec4(position, 0.0, 1.0); -- Texcoord = texcoord; -- } -- @ -- -- The two fragment shaders, one for the object, one for the effect, are -- -- @ -- #version 150 -- uniform float time; -- in vec2 Texcoord; -- out vec4 outColor; -- void main() -- { -- float t = time; -- outColor = vec4( -- fract(Texcoord.x*5) < 0.5 ? sin(t*0.145) : cos(t*0.567), -- fract(Texcoord.y*5) < 0.5 ? cos(t*0.534) : sin(t*0.321), -- 0.0, 1.0 -- ); -- } -- @ -- -- @ -- #version 150 -- uniform float time; -- uniform sampler2D tex; -- in vec2 Texcoord; -- out vec4 outColor; -- -- void main() -- { -- float d = pow(10,(abs(cos(time))+1.5)); -- outColor c = texture(tex, floor(Texcoord*d)/d); -- } -- @
sgraf812/lowgl
Graphics/GL/Low/Framebuffer.hs
bsd-2-clause
8,157
0
13
1,664
918
573
345
67
1
module Data.CRF.Chain2.Tiers.DP ( table , flexible2 , flexible3 ) where import qualified Data.Array as A import Data.Array ((!)) import Data.Ix (range) table :: A.Ix i => (i, i) -> ((i -> e) -> i -> e) -> A.Array i e table bounds f = table' where table' = A.listArray bounds $ map (f (table' !)) $ range bounds down1 :: A.Ix i => (i, i) -> (i -> e) -> i -> e down1 bounds f = (!) down' where down' = A.listArray bounds $ map f $ range bounds down2 :: (A.Ix i, A.Ix j) => (j, j) -> (j -> (i, i)) -> (j -> i -> e) -> j -> i -> e down2 bounds1 bounds2 f = (!) down' where down' = A.listArray bounds1 [ down1 (bounds2 i) (f i) | i <- range bounds1 ] flexible2 :: (A.Ix i, A.Ix j) => (j, j) -> (j -> (i, i)) -> ((j -> i -> e) -> j -> i -> e) -> j -> i -> e flexible2 bounds1 bounds2 f = (!) flex where flex = A.listArray bounds1 [ down1 (bounds2 i) (f (flex !) i) | i <- range bounds1 ] flexible3 :: (A.Ix j, A.Ix i, A.Ix k) => (k, k) -> (k -> (j, j)) -> (k -> j -> (i, i)) -> ((k -> j -> i -> e) -> k -> j -> i -> e) -> k -> j -> i -> e flexible3 bounds1 bounds2 bounds3 f = (!) flex where flex = A.listArray bounds1 [ down2 (bounds2 i) (bounds3 i) (f (flex !) i) | i <- range bounds1 ]
kawu/crf-chain2-tiers
src/Data/CRF/Chain2/Tiers/DP.hs
bsd-2-clause
1,339
0
15
430
730
393
337
36
1
{-| Module : Database.Relational.FieldType Description : Definition of FieldType and friends. Copyright : (c) Alexander Vieth, 2015 Licence : BSD3 Maintainer : [email protected] Stability : experimental Portability : non-portable (GHC only) -} {-# LANGUAGE AutoDeriveTypeable #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE TypeOperators #-} module Database.Relational.FieldType ( WriteOrRead(..) , FieldType , FieldTypes , FieldTypeWrite , FieldTypeRead ) where import GHC.TypeLits (Symbol) import Database.Relational.Schema import Database.Relational.Column import Database.Relational.Default data WriteOrRead where WRITE :: WriteOrRead READ :: WriteOrRead -- | The *field type* is distinct from the *column* type, and they coincide -- precisely when that column cannot be null. Thus, the field type depends -- upon the column *and* the schema in which it lives. -- We have two notions of *field type*: write field type, and read field -- type. The former is the type which must be given when writing data to -- this field, and the latter is the type which will be obtained when -- reading. They differ when the relevant column has a default, in which case -- Default may be given. type family FieldType (wor :: WriteOrRead) schema (column :: (Symbol, *)) :: * where FieldType READ schema column = FieldTypeRead column (IsNullable column schema) FieldType WRITE schema column = FieldTypeWrite column (IsNullable column schema) (IsDefault column schema) type family FieldTypes (wor :: WriteOrRead) schema (columns :: [(Symbol, *)]) :: [*] where FieldTypes wor schema '[] = '[] FieldTypes wor schema (c ': cs) = FieldType wor schema c ': FieldTypes wor schema cs type family FieldTypeRead (column :: (Symbol, *)) isNullable :: * where FieldTypeRead column True = Maybe (ColumnType column) FieldTypeRead column False = ColumnType column type family FieldTypeWrite (column :: (Symbol, *)) isNullable isDefault :: * where FieldTypeWrite column nullable True = Default (FieldTypeRead column nullable) FieldTypeWrite column nullable False = FieldTypeRead column nullable
avieth/Relational
Database/Relational/FieldType.hs
bsd-3-clause
2,284
0
8
422
392
234
158
32
0
{-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE OverloadedLists #-} {-# LANGUAGE TemplateHaskell #-} -- | This module contains operations related to symbolic stack. module Toy.X86.SymStack ( regSymStack , atSymStack , SymStackSpace , SymStackHolder , runSymStackHolder , symStackSize , allocSymStackOp , popSymStackOp , peekSymStackOp , occupiedRegs , accountHardMem ) where import Control.Lens (ix, makeLenses, (%=), (<-=), (<<+=)) import Control.Monad.Fix import Control.Monad.State (StateT, runStateT) import Control.Monad.Writer (MonadWriter) import Data.Default (Default (..)) import qualified Data.Vector as V import Universum import Toy.X86.Data (Operand (..)) regSymStack :: V.Vector Operand regSymStack = Reg <$> ["ecx", "ebx", "esi", "edi"] atSymStack :: Int -> Operand atSymStack k = case regSymStack ^? ix k of Just x -> x Nothing -> Stack (k - V.length regSymStack) data SymStackState = SymStackState { _symSize :: Int , _symMaxSize :: Int } makeLenses ''SymStackState instance Default SymStackState where def = SymStackState 0 0 newtype SymStackHolder m a = SymStackHolder (StateT SymStackState m a) deriving (Functor, Applicative, Monad, MonadWriter __, MonadFix) -- | How much space sym stack requires on real stack. newtype SymStackSpace = SymStackSpace Int deriving (Show, Eq, Ord, Enum, Num, Real, Integral) runSymStackHolder :: Monad m => SymStackHolder m a -> m ((SymStackSpace, Int), a) runSymStackHolder (SymStackHolder a) = do (res, SymStackState k totalSize) <- runStateT a def let space = max 0 $ totalSize - V.length regSymStack return ((SymStackSpace space, k), res) updateSymMaxSize :: Monad m => Int -> SymStackHolder m () updateSymMaxSize k = SymStackHolder $ symMaxSize %= max k symStackSize :: Monad m => SymStackHolder m Int symStackSize = SymStackHolder $ use symSize allocSymStackOp :: Monad m => SymStackHolder m Operand allocSymStackOp = do pos <- SymStackHolder $ symSize <<+= 1 updateSymMaxSize (pos + 1) return $ atSymStack pos popSymStackOp :: Monad m => SymStackHolder m Operand popSymStackOp = SymStackHolder $ (symSize <-= 1) <&> atSymStack peekSymStackOp :: Monad m => SymStackHolder m Operand peekSymStackOp = SymStackHolder $ use symSize <&> atSymStack . pred occupiedRegs :: Monad m => SymStackHolder m [Operand] occupiedRegs = symStackSize <&> flip take (V.toList regSymStack) -- | @HardMem@s occupy same space as sym stack accountHardMem :: Monad m => Int -> SymStackHolder m () accountHardMem = updateSymMaxSize . (+ V.length regSymStack) -- TODO: dirty hack
Martoon-00/toy-compiler
src/Toy/X86/SymStack.hs
bsd-3-clause
2,788
0
12
630
775
419
356
-1
-1
{-# LANGUAGE TemplateHaskell #-} module Test.ScopeLookup where import Language.Haskell.TH import NotCPP.ScopeLookup scopeLookupTest = $(do Just t <- scopeLookup' "True" return t)
bmillwood/notcpp
Test/ScopeLookup.hs
bsd-3-clause
186
0
10
28
46
24
22
7
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE PatternGuards #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} ----------------------------------------------------------------------------- -- | -- Module : Control.Distributed.Process.Registry -- Copyright : (c) Tim Watson 2012 - 2013 -- License : BSD3 (see the file LICENSE) -- -- Maintainer : Tim Watson <[email protected]> -- Stability : experimental -- Portability : non-portable (requires concurrency) -- -- The module provides an extended process registry, offering slightly altered -- semantics to the built in @register@ and @unregister@ primitives and a richer -- set of features: -- -- * Associate (unique) keys with a process /or/ (unique key per-process) values -- * Use any 'Keyable' algebraic data type as keys -- * Query for process with matching keys / values / properties -- * Atomically /give away/ names -- * Forceibly re-allocate names to/from a third party -- -- [Subscribing To Registry Events] -- -- It is possible to monitor a registry for changes and be informed whenever -- changes take place. All subscriptions are /key based/, which means that -- you can subscribe to name or property changes for any process, so that any -- property changes matching the key you've subscribed to will trigger a -- notification (i.e., regardless of the process to which the property belongs). -- -- The different types of event are defined by the 'KeyUpdateEvent' type. -- -- Processes subscribe to registry events using @monitorName@ or its counterpart -- @monitorProperty@. If the operation succeeds, this will evaluate to an -- opaque /reference/ that can be used when subsequently handling incoming -- notifications, which will be delivered to the subscriber's mailbox as -- @RegistryKeyMonitorNotification keyIdentity opaqueRef event@, where @event@ -- has the type 'KeyUpdateEvent'. -- -- Subscribers can filter the types of event they receive by using the lower -- level @monitor@ function (defined in /this/ module - not the one defined -- in distributed-process' @Primitives@) and passing a list of filtering -- 'KeyUpdateEventMask'. Without these filters in place, a monitor event will -- be fired for /every/ pertinent change. -- ----------------------------------------------------------------------------- module Control.Distributed.Process.Registry ( -- * Registry Keys KeyType(..) , Key(..) , Keyable -- * Defining / Starting A Registry , Registry(..) , start , run -- * Registration / Unregistration , addName , addProperty , registerName , registerValue , giveAwayName , RegisterKeyReply(..) , unregisterName , UnregisterKeyReply(..) -- * Queries / Lookups , lookupName , lookupProperty , registeredNames , foldNames , SearchHandle() , member , queryNames , findByProperty , findByPropertyValue -- * Monitoring / Waiting , monitor , monitorName , monitorProp , unmonitor , await , awaitTimeout , AwaitResult(..) , KeyUpdateEventMask(..) , KeyUpdateEvent(..) , RegKeyMonitorRef , RegistryKeyMonitorNotification(RegistryKeyMonitorNotification) ) where {- DESIGN NOTES This registry is a single process, parameterised by the types of key and property value it can manage. It is, of course, possible to start multiple registries and inter-connect them via registration, with one another. The /Service/ API is intended to be a declarative layer in which you define the managed processes that make up your services, and each /Service Component/ is registered and supervised appropriately for you, with the correct restart strategies and start order calculated and so on. The registry is not only a service locator, but provides the /wait for these dependencies to start first/ bit of the puzzle. At some point, we'd like to offer a shared memory based registry, created on behalf of a particular subsystem (i.e., some service or service group) and passed implicitly using a reader monad or some such. This would allow multiple processes to interact with the registry using STM (or perhaps a simple RWLock) and could facilitate reduced contention. Even for the singleton-process based registry (i.e., this one) we /might/ also be better off separating the monitoring (or at least the notifications) from the registration/mapping parts into separate processes. -} import Control.Distributed.Process hiding (call, monitor, unmonitor, mask) import qualified Control.Distributed.Process.UnsafePrimitives as Unsafe (send) import qualified Control.Distributed.Process as P (monitor) import Control.Distributed.Process.Serializable import Control.Distributed.Process.Extras hiding (monitor, wrapMessage) import qualified Control.Distributed.Process.Extras as PL ( monitor ) import Control.Distributed.Process.ManagedProcess ( call , cast , handleInfo , reply , continue , input , defaultProcess , prioritised , InitResult(..) , ProcessAction , ProcessReply , ProcessDefinition(..) , PrioritisedProcessDefinition(..) , DispatchPriority , CallRef ) import qualified Control.Distributed.Process.ManagedProcess as MP ( pserve ) import Control.Distributed.Process.ManagedProcess.Server ( handleCallIf , handleCallFrom , handleCallFromIf , handleCast ) import Control.Distributed.Process.ManagedProcess.Server.Priority ( prioritiseInfo_ , setPriority ) import Control.Distributed.Process.ManagedProcess.Server.Restricted ( RestrictedProcess , Result , getState ) import qualified Control.Distributed.Process.ManagedProcess.Server.Restricted as Restricted ( handleCall , reply ) import Control.Distributed.Process.Extras.Time import Control.Monad (forM_, void) import Data.Accessor ( Accessor , accessor , (^:) , (^=) , (^.) ) import Data.Binary import Data.Foldable (Foldable) import qualified Data.Foldable as Foldable import Data.Maybe (fromJust, isJust) import Data.Hashable import Data.HashMap.Strict (HashMap) import qualified Data.HashMap.Strict as Map import Control.Distributed.Process.Extras.Internal.Containers.MultiMap (MultiMap) import qualified Control.Distributed.Process.Extras.Internal.Containers.MultiMap as MultiMap import Data.HashSet (HashSet) import qualified Data.HashSet as Set import Data.Typeable (Typeable) import GHC.Generics -------------------------------------------------------------------------------- -- Types -- -------------------------------------------------------------------------------- -- | Describes how a key will be used - for storing names or properties. data KeyType = KeyTypeAlias -- ^ the key will refer to a name (i.e., named process) | KeyTypeProperty -- ^ the key will refer to a (per-process) property deriving (Typeable, Generic, Show, Eq) instance Binary KeyType where instance Hashable KeyType where -- | A registered key. Keys can be mapped to names or (process-local) properties -- in the registry. The 'keyIdentity' holds the key's value (e.g., a string or -- similar simple data type, which must provide a 'Keyable' instance), whilst -- the 'keyType' and 'keyScope' describe the key's intended use and ownership. data Key a = Key { keyIdentity :: !a , keyType :: !KeyType , keyScope :: !(Maybe ProcessId) } deriving (Typeable, Generic, Show, Eq) instance (Serializable a) => Binary (Key a) where instance (Hashable a) => Hashable (Key a) where -- | The 'Keyable' class describes types that can be used as registry keys. -- The constraints ensure that the key can be stored and compared appropriately. class (Show a, Eq a, Hashable a, Serializable a) => Keyable a instance (Show a, Eq a, Hashable a, Serializable a) => Keyable a -- | A phantom type, used to parameterise registry startup -- with the required key and value types. data Registry k v = Registry { registryPid :: ProcessId } deriving (Typeable, Generic, Show, Eq) instance (Keyable k, Serializable v) => Binary (Registry k v) where instance Resolvable (Registry k v) where resolve = return . Just . registryPid instance Linkable (Registry k v) where linkTo = link . registryPid -- Internal/Private Request/Response Types data LookupKeyReq k = LookupKeyReq !(Key k) deriving (Typeable, Generic) instance (Serializable k) => Binary (LookupKeyReq k) where data LookupPropReq k = PropReq (Key k) deriving (Typeable, Generic) instance (Serializable k) => Binary (LookupPropReq k) where data LookupPropReply = PropFound !Message | PropNotFound deriving (Typeable, Generic) instance Binary LookupPropReply where data InvalidPropertyType = InvalidPropertyType deriving (Typeable, Generic, Show, Eq) instance Binary InvalidPropertyType where data RegNamesReq = RegNamesReq !ProcessId deriving (Typeable, Generic) instance Binary RegNamesReq where data UnregisterKeyReq k = UnregisterKeyReq !(Key k) deriving (Typeable, Generic) instance (Serializable k) => Binary (UnregisterKeyReq k) where -- | The result of an un-registration attempt. data UnregisterKeyReply = UnregisterOk -- ^ The given key was successfully unregistered | UnregisterInvalidKey -- ^ The given key was invalid and could not be unregistered | UnregisterKeyNotFound -- ^ The given key was not found (i.e., was not registered) deriving (Typeable, Generic, Eq, Show) instance Binary UnregisterKeyReply where -- Types used in (setting up and interacting with) key monitors -- | Used to describe a subset of monitoring events to listen for. data KeyUpdateEventMask = OnKeyRegistered -- ^ receive an event when a key is registered | OnKeyUnregistered -- ^ receive an event when a key is unregistered | OnKeyOwnershipChange -- ^ receive an event when a key's owner changes | OnKeyLeaseExpiry -- ^ receive an event when a key's lease expires deriving (Typeable, Generic, Eq, Show) instance Binary KeyUpdateEventMask where instance Hashable KeyUpdateEventMask where -- | An opaque reference used for matching monitoring events. See -- 'RegistryKeyMonitorNotification' for more details. newtype RegKeyMonitorRef = RegKeyMonitorRef { unRef :: (ProcessId, Integer) } deriving (Typeable, Generic, Eq, Show) instance Binary RegKeyMonitorRef where instance Hashable RegKeyMonitorRef where instance Resolvable RegKeyMonitorRef where resolve = return . Just . fst . unRef -- | Provides information about a key monitoring event. data KeyUpdateEvent = KeyRegistered { owner :: !ProcessId } | KeyUnregistered | KeyLeaseExpired | KeyOwnerDied { diedReason :: !DiedReason } | KeyOwnerChanged { previousOwner :: !ProcessId , newOwner :: !ProcessId } deriving (Typeable, Generic, Eq, Show) instance Binary KeyUpdateEvent where -- | This message is delivered to processes which are monioring a -- registry key. The opaque monitor reference will match (i.e., be equal -- to) the reference returned from the @monitor@ function, which the -- 'KeyUpdateEvent' describes the change that took place. data RegistryKeyMonitorNotification k = RegistryKeyMonitorNotification !k !RegKeyMonitorRef !KeyUpdateEvent !ProcessId deriving (Typeable, Generic) instance (Keyable k) => Binary (RegistryKeyMonitorNotification k) where deriving instance (Keyable k) => Eq (RegistryKeyMonitorNotification k) deriving instance (Keyable k) => Show (RegistryKeyMonitorNotification k) data RegisterKeyReq k = RegisterKeyReq !(Key k) deriving (Typeable, Generic) instance (Serializable k) => Binary (RegisterKeyReq k) where -- | The (return) value of an attempted registration. data RegisterKeyReply = RegisteredOk -- ^ The given key was registered successfully | AlreadyRegistered -- ^ The key was already registered deriving (Typeable, Generic, Eq, Show) instance Binary RegisterKeyReply where -- | A cast message used to atomically give a name/key away to another process. data GiveAwayName k = GiveAwayName !ProcessId !(Key k) deriving (Typeable, Generic) instance (Keyable k) => Binary (GiveAwayName k) where deriving instance (Keyable k) => Eq (GiveAwayName k) deriving instance (Keyable k) => Show (GiveAwayName k) data MonitorReq k = MonitorReq !(Key k) !(Maybe [KeyUpdateEventMask]) deriving (Typeable, Generic) instance (Keyable k) => Binary (MonitorReq k) where data UnmonitorReq = UnmonitorReq !RegKeyMonitorRef deriving (Typeable, Generic) instance Binary UnmonitorReq where -- | The result of an @await@ operation. data AwaitResult k = RegisteredName !ProcessId !k -- ^ The name was registered | ServerUnreachable !DiedReason -- ^ The server was unreachable (or died) | AwaitTimeout -- ^ The operation timed out deriving (Typeable, Generic, Eq, Show) instance (Keyable k) => Binary (AwaitResult k) where -- Server state -- On the server, a monitor reference consists of the actual -- RegKeyMonitorRef which we can 'sendTo' /and/ the which -- the client matches on, plus an optional list of event masks data KMRef = KMRef { ref :: !RegKeyMonitorRef , mask :: !(Maybe [KeyUpdateEventMask]) -- use Nothing to monitor every event } deriving (Typeable, Generic, Show) instance Hashable KMRef where -- instance Binary KMRef where instance Eq KMRef where (KMRef a _) == (KMRef b _) = a == b data State k v = State { _names :: !(HashMap k ProcessId) , _properties :: !(HashMap (ProcessId, k) v) , _monitors :: !(MultiMap k KMRef) , _registeredPids :: !(HashSet ProcessId) , _listeningPids :: !(HashSet ProcessId) , _monitorIdCount :: !Integer } deriving (Typeable, Generic) -- Types used in \direct/ queries -- TODO: enforce QueryDirect's usage over only local channels data QueryDirect = QueryDirectNames | QueryDirectProperties | QueryDirectValues deriving (Typeable, Generic) instance Binary QueryDirect where -- NB: SHashMap is basically a shim, allowing us to copy a -- pointer to our HashMap directly to the querying process' -- mailbox with no serialisation or even deepseq evaluation -- required. We disallow remote queries (i.e., from other nodes) -- and thus the Binary instance below is never used (though it's -- required by the type system) and will in fact generate errors if -- you attempt to use it at runtime. data SHashMap k v = SHashMap [(k, v)] (HashMap k v) deriving (Typeable, Generic) instance (Keyable k, Serializable v) => Binary (SHashMap k v) where put = error "AttemptedToUseBinaryShim" get = error "AttemptedToUseBinaryShim" {- a real instance could look something like this: put (SHashMap _ hmap) = put (toList hmap) get = do hm <- get :: Get [(k, v)] return $ SHashMap [] (fromList hm) -} newtype SearchHandle k v = RS { getRS :: HashMap k v } deriving (Typeable) instance (Keyable k) => Functor (SearchHandle k) where fmap f (RS m) = RS $ Map.map f m instance (Keyable k) => Foldable (SearchHandle k) where foldr f acc = Foldable.foldr f acc . getRS -- TODO: add Functor and Traversable instances -------------------------------------------------------------------------------- -- Starting / Running A Registry -- -------------------------------------------------------------------------------- start :: forall k v. (Keyable k, Serializable v) => Process (Registry k v) start = return . Registry =<< spawnLocal (run (undefined :: Registry k v)) run :: forall k v. (Keyable k, Serializable v) => Registry k v -> Process () run _ = MP.pserve () (const $ return $ InitOk initState Infinity) serverDefinition where initState = State { _names = Map.empty , _properties = Map.empty , _monitors = MultiMap.empty , _registeredPids = Set.empty , _listeningPids = Set.empty , _monitorIdCount = (1 :: Integer) } :: State k v -------------------------------------------------------------------------------- -- Client Facing API -- -------------------------------------------------------------------------------- -- -- | Sends a message to the process, or processes, corresponding to @key@. -- -- If Key belongs to a unique object (name or aggregated counter), this -- -- function will send a message to the corresponding process, or fail if there -- -- is no such process. If Key is for a non-unique object type (counter or -- -- property), Msg will be send to all processes that have such an object. -- -- -- dispatch svr ky msg = undefined -- -- TODO: do a local-lookup and then sendTo the target -- | Associate the calling process with the given (unique) key. addName :: forall k v. (Keyable k) => Registry k v -> k -> Process RegisterKeyReply addName s n = getSelfPid >>= registerName s n -- | Atomically transfer a (registered) name to another process. Has no effect -- if the name does is not registered to the calling process! -- giveAwayName :: forall k v . (Keyable k) => Registry k v -> k -> ProcessId -> Process () giveAwayName s n p = do us <- getSelfPid cast s $ GiveAwayName p $ Key n KeyTypeAlias (Just us) -- | Associate the given (non-unique) property with the current process. -- If the property already exists, it will be overwritten with the new value. addProperty :: (Keyable k, Serializable v) => Registry k v -> k -> v -> Process RegisterKeyReply addProperty s k v = do call s $ (RegisterKeyReq (Key k KeyTypeProperty $ Nothing), v) -- | Register the item at the given address. registerName :: forall k v . (Keyable k) => Registry k v -> k -> ProcessId -> Process RegisterKeyReply registerName s n p = do call s $ RegisterKeyReq (Key n KeyTypeAlias $ Just p) -- | Register an item at the given address and associate it with a value. -- If the property already exists, it will be overwritten with the new value. registerValue :: (Resolvable b, Keyable k, Serializable v) => Registry k v -> b -> k -> v -> Process RegisterKeyReply registerValue s t n v = do Just p <- resolve t call s $ (RegisterKeyReq (Key n KeyTypeProperty $ Just p), v) -- | Un-register a (unique) name for the calling process. unregisterName :: forall k v . (Keyable k) => Registry k v -> k -> Process UnregisterKeyReply unregisterName s n = do self <- getSelfPid call s $ UnregisterKeyReq (Key n KeyTypeAlias $ Just self) -- | Lookup the process identified by the supplied key. Evaluates to -- @Nothing@ if the key is not registered. lookupName :: forall k v . (Keyable k) => Registry k v -> k -> Process (Maybe ProcessId) lookupName s n = call s $ LookupKeyReq (Key n KeyTypeAlias Nothing) -- | Lookup the value of a named property for the calling process. Evaluates to -- @Nothing@ if the property (key) is not registered. If the assignment to a -- value of type @v@ does not correspond to the type of properties stored by -- the registry, the calling process will exit with the reason set to -- @InvalidPropertyType@. lookupProperty :: (Keyable k, Serializable v) => Registry k v -> k -> Process (Maybe v) lookupProperty s n = do us <- getSelfPid res <- call s $ PropReq (Key n KeyTypeProperty (Just us)) case res of PropNotFound -> return Nothing PropFound msg -> do val <- unwrapMessage msg if (isJust val) then return val else die InvalidPropertyType -- | Obtain a list of all registered keys. registeredNames :: forall k v . (Keyable k) => Registry k v -> ProcessId -> Process [k] registeredNames s p = call s $ RegNamesReq p -- | Monitor changes to the supplied name. -- monitorName :: forall k v. (Keyable k) => Registry k v -> k -> Process RegKeyMonitorRef monitorName svr name = do let key' = Key { keyIdentity = name , keyScope = Nothing , keyType = KeyTypeAlias } monitor svr key' Nothing -- | Monitor changes to the supplied (property) key. -- monitorProp :: forall k v. (Keyable k) => Registry k v -> k -> ProcessId -> Process RegKeyMonitorRef monitorProp svr key pid = do let key' = Key { keyIdentity = key , keyScope = Just pid , keyType = KeyTypeProperty } monitor svr key' Nothing -- | Low level monitor operation. For the given key, set up a monitor -- filtered by any 'KeyUpdateEventMask' entries that are supplied. monitor :: forall k v. (Keyable k) => Registry k v -> Key k -> Maybe [KeyUpdateEventMask] -> Process RegKeyMonitorRef monitor svr key' mask' = call svr $ MonitorReq key' mask' -- | Remove a previously set monitor. -- unmonitor :: forall k v. (Keyable k) => Registry k v -> RegKeyMonitorRef -> Process () unmonitor s = call s . UnmonitorReq -- | Await registration of a given key. This function will subsequently -- block the evaluating process until the key is registered and a registration -- event is dispatched to the caller's mailbox. -- await :: forall k v. (Keyable k) => Registry k v -> k -> Process (AwaitResult k) await a k = awaitTimeout a Infinity k -- | Await registration of a given key, but give up and return @AwaitTimeout@ -- if registration does not take place within the specified time period (@delay@). awaitTimeout :: forall k v. (Keyable k) => Registry k v -> Delay -> k -> Process (AwaitResult k) awaitTimeout a d k = do p <- forceResolve a Just mRef <- PL.monitor p kRef <- monitor a (Key k KeyTypeAlias Nothing) (Just [OnKeyRegistered]) let matches' = matches mRef kRef k let recv = case d of Infinity -> receiveWait matches' >>= return . Just Delay t -> receiveTimeout (asTimeout t) matches' NoDelay -> receiveTimeout 0 matches' recv >>= return . maybe AwaitTimeout id where forceResolve addr = do mPid <- resolve addr case mPid of Nothing -> die "InvalidAddressable" Just p -> return p matches mr kr k' = [ matchIf (\(RegistryKeyMonitorNotification mk' kRef' ev' _) -> (matchEv ev' && kRef' == kr && mk' == k')) (\(RegistryKeyMonitorNotification _ _ (KeyRegistered pid) _) -> return $ RegisteredName pid k') , matchIf (\(ProcessMonitorNotification mRef' _ _) -> mRef' == mr) (\(ProcessMonitorNotification _ _ dr) -> return $ ServerUnreachable dr) ] matchEv ev' = case ev' of KeyRegistered _ -> True _ -> False -- Local (non-serialised) shared data access. See note [sharing] below. findByProperty :: forall k v. (Keyable k) => Registry k v -> k -> Process [ProcessId] findByProperty r key = do let pid = registryPid r self <- getSelfPid withMonitor pid $ do cast r $ (self, QueryDirectProperties) answer <- receiveWait [ match (\(SHashMap _ m :: SHashMap ProcessId [k]) -> return $ Just m) , matchIf (\(ProcessMonitorNotification _ p _) -> p == pid) (\_ -> return Nothing) , matchAny (\_ -> return Nothing) ] case answer of Nothing -> die "DisconnectedFromServer" Just m -> return $ Map.foldlWithKey' matchKey [] m where matchKey ps p ks | key `elem` ks = p:ps | otherwise = ps findByPropertyValue :: (Keyable k, Serializable v, Eq v) => Registry k v -> k -> v -> Process [ProcessId] findByPropertyValue r key val = do let pid = registryPid r self <- getSelfPid withMonitor pid $ do cast r $ (self, QueryDirectValues) answer <- receiveWait [ match (\(SHashMap _ m :: SHashMap ProcessId [(k, v)]) -> return $ Just m) , matchIf (\(ProcessMonitorNotification _ p _) -> p == pid) (\_ -> return Nothing) , matchAny (\_ -> return Nothing) -- TODO: logging? ] case answer of Nothing -> die "DisconnectedFromServer" Just m -> return $ Map.foldlWithKey' matchKey [] m where matchKey ps p ks | (key, val) `elem` ks = p:ps | otherwise = ps -- TODO: move to UnsafePrimitives over a passed {Send|Receive}Port here, and -- avoid interfering with the caller's mailbox. -- | Monadic left fold over all registered names/keys. The fold takes place -- in the evaluating process. foldNames :: forall b k v . Keyable k => Registry k v -> b -> (b -> (k, ProcessId) -> Process b) -> Process b foldNames pid acc fn = do self <- getSelfPid -- TODO: monitor @pid@ and die if necessary!!! cast pid $ (self, QueryDirectNames) -- Although we incur the cost of scanning our mailbox here (which we could -- avoid by spawning an intermediary perhaps), the message is delivered to -- us without any copying or serialisation overheads. SHashMap _ m <- expect :: Process (SHashMap k ProcessId) Foldable.foldlM fn acc (Map.toList m) -- | Evaluate a query on a 'SearchHandle', in the calling process. queryNames :: forall b k v . Keyable k => Registry k v -> (SearchHandle k ProcessId -> Process b) -> Process b queryNames pid fn = do self <- getSelfPid cast pid $ (self, QueryDirectNames) SHashMap _ m <- expect :: Process (SHashMap k ProcessId) fn (RS m) -- | Tests whether or not the supplied key is registered, evaluated in the -- calling process. member :: (Keyable k, Serializable v) => k -> SearchHandle k v -> Bool member k = Map.member k . getRS -- note [sharing]: -- We use the base library's UnsafePrimitives for these fold/query operations, -- to pass a pointer to our internal HashMaps for read-only operations. There -- is a potential cost to the caller, if their mailbox is full - we should move -- to use unsafe channel's for this at some point. -- -------------------------------------------------------------------------------- -- Server Process -- -------------------------------------------------------------------------------- serverDefinition :: forall k v. (Keyable k, Serializable v) => PrioritisedProcessDefinition (State k v) serverDefinition = prioritised processDefinition regPriorities where regPriorities :: [DispatchPriority (State k v)] regPriorities = [ prioritiseInfo_ (\(ProcessMonitorNotification _ _ _) -> setPriority 100) ] processDefinition :: forall k v. (Keyable k, Serializable v) => ProcessDefinition (State k v) processDefinition = defaultProcess { apiHandlers = [ handleCallIf (input ((\(RegisterKeyReq (Key{..} :: Key k)) -> keyType == KeyTypeAlias && (isJust keyScope)))) handleRegisterName , handleCallIf (input ((\((RegisterKeyReq (Key{..} :: Key k)), _ :: v) -> keyType == KeyTypeProperty && (isJust keyScope)))) handleRegisterProperty , handleCallFromIf (input ((\((RegisterKeyReq (Key{..} :: Key k)), _ :: v) -> keyType == KeyTypeProperty && (not $ isJust keyScope)))) handleRegisterPropertyCR , handleCast handleGiveAwayName , handleCallIf (input ((\(LookupKeyReq (Key{..} :: Key k)) -> keyType == KeyTypeAlias))) (\state (LookupKeyReq key') -> reply (findName key' state) state) , handleCallIf (input ((\(PropReq (Key{..} :: Key k)) -> keyType == KeyTypeProperty && (isJust keyScope)))) handleLookupProperty , handleCallIf (input ((\(UnregisterKeyReq (Key{..} :: Key k)) -> keyType == KeyTypeAlias && (isJust keyScope)))) handleUnregisterName , handleCallFrom handleMonitorReq , handleCallFrom handleUnmonitorReq , Restricted.handleCall handleRegNamesLookup , handleCast handleQuery ] , infoHandlers = [handleInfo handleMonitorSignal] } :: ProcessDefinition (State k v) handleQuery :: forall k v. (Keyable k, Serializable v) => State k v -> (ProcessId, QueryDirect) -> Process (ProcessAction (State k v)) handleQuery st@State{..} (pid, qd) = do case qd of QueryDirectNames -> Unsafe.send pid shmNames QueryDirectProperties -> Unsafe.send pid shmProps QueryDirectValues -> Unsafe.send pid shmVals continue st where shmNames = SHashMap [] $ st ^. names shmProps = SHashMap [] xfmProps shmVals = SHashMap [] xfmVals -- since we currently have to fold over our properties in order -- answer remote queries, the sharing we do here seems a bit pointless, -- however we'll be moving to a shared memory based registry soon xfmProps = Map.foldlWithKey' convProps Map.empty (st ^. properties) xfmVals = Map.foldlWithKey' convVals Map.empty (st ^. properties) convProps m (p, k) _ = case Map.lookup p m of Nothing -> Map.insert p [k] m Just ks -> Map.insert p (k:ks) m convVals m (p, k) v = case Map.lookup p m of Nothing -> Map.insert p [(k, v)] m Just ks -> Map.insert p ((k, v):ks) m handleRegisterName :: forall k v. (Keyable k, Serializable v) => State k v -> RegisterKeyReq k -> Process (ProcessReply RegisterKeyReply (State k v)) handleRegisterName state (RegisterKeyReq Key{..}) = do let found = Map.lookup keyIdentity (state ^. names) case found of Nothing -> do let pid = fromJust keyScope let refs = state ^. registeredPids refs' <- ensureMonitored pid refs notifySubscribers keyIdentity state (KeyRegistered pid) reply RegisteredOk $ ( (names ^: Map.insert keyIdentity pid) . (registeredPids ^= refs') $ state) Just pid -> if (pid == (fromJust keyScope)) then reply RegisteredOk state else reply AlreadyRegistered state handleRegisterPropertyCR :: forall k v. (Keyable k, Serializable v) => State k v -> CallRef (RegisterKeyReply) -> (RegisterKeyReq k, v) -> Process (ProcessReply RegisterKeyReply (State k v)) handleRegisterPropertyCR st cr req = do pid <- resolve cr doRegisterProperty (fromJust pid) st req handleRegisterProperty :: forall k v. (Keyable k, Serializable v) => State k v -> (RegisterKeyReq k, v) -> Process (ProcessReply RegisterKeyReply (State k v)) handleRegisterProperty state req@((RegisterKeyReq Key{..}), _) = do doRegisterProperty (fromJust keyScope) state req doRegisterProperty :: forall k v. (Keyable k, Serializable v) => ProcessId -> State k v -> (RegisterKeyReq k, v) -> Process (ProcessReply RegisterKeyReply (State k v)) doRegisterProperty scope state ((RegisterKeyReq Key{..}), v) = do void $ P.monitor scope notifySubscribers keyIdentity state (KeyRegistered scope) reply RegisteredOk $ ( (properties ^: Map.insert (scope, keyIdentity) v) $ state ) handleLookupProperty :: forall k v. (Keyable k, Serializable v) => State k v -> LookupPropReq k -> Process (ProcessReply LookupPropReply (State k v)) handleLookupProperty state (PropReq Key{..}) = do let entry = Map.lookup (fromJust keyScope, keyIdentity) (state ^. properties) case entry of Nothing -> reply PropNotFound state Just p -> reply (PropFound (wrapMessage p)) state handleUnregisterName :: forall k v. (Keyable k, Serializable v) => State k v -> UnregisterKeyReq k -> Process (ProcessReply UnregisterKeyReply (State k v)) handleUnregisterName state (UnregisterKeyReq Key{..}) = do let entry = Map.lookup keyIdentity (state ^. names) case entry of Nothing -> reply UnregisterKeyNotFound state Just pid -> case (pid /= (fromJust keyScope)) of True -> reply UnregisterInvalidKey state False -> do notifySubscribers keyIdentity state KeyUnregistered let state' = ( (names ^: Map.delete keyIdentity) . (monitors ^: MultiMap.filterWithKey (\k' _ -> k' /= keyIdentity)) $ state) reply UnregisterOk $ state' handleGiveAwayName :: forall k v. (Keyable k, Serializable v) => State k v -> GiveAwayName k -> Process (ProcessAction (State k v)) handleGiveAwayName state (GiveAwayName newPid Key{..}) = do maybe (continue state) giveAway $ Map.lookup keyIdentity (state ^. names) where giveAway pid = do let scope = fromJust keyScope case (pid == scope) of False -> continue state True -> do let state' = ((names ^: Map.insert keyIdentity newPid) $ state) notifySubscribers keyIdentity state (KeyOwnerChanged pid newPid) continue state' handleMonitorReq :: forall k v. (Keyable k, Serializable v) => State k v -> CallRef RegKeyMonitorRef -> MonitorReq k -> Process (ProcessReply RegKeyMonitorRef (State k v)) handleMonitorReq state cRef (MonitorReq Key{..} mask') = do let mRefId = (state ^. monitorIdCount) + 1 Just caller <- resolve cRef let mRef = RegKeyMonitorRef (caller, mRefId) let kmRef = KMRef mRef mask' let refs = state ^. listeningPids refs' <- ensureMonitored caller refs fireEventForPreRegisteredKey state keyIdentity keyScope kmRef reply mRef $ ( (monitors ^: MultiMap.insert keyIdentity kmRef) . (listeningPids ^= refs') . (monitorIdCount ^= mRefId) $ state ) where fireEventForPreRegisteredKey st kId kScope KMRef{..} = do let evMask = maybe [] id mask case (keyType, elem OnKeyRegistered evMask) of (KeyTypeAlias, True) -> do let found = Map.lookup kId (st ^. names) fireEvent found kId ref (KeyTypeProperty, _) -> do self <- getSelfPid let scope = maybe self id kScope let found = Map.lookup (scope, kId) (st ^. properties) case found of Nothing -> return () -- TODO: logging or some such!? Just _ -> fireEvent (Just scope) kId ref _ -> return () fireEvent fnd kId' ref' = do case fnd of Nothing -> return () Just p -> do us <- getSelfPid sendTo ref' $ (RegistryKeyMonitorNotification kId' ref' (KeyRegistered p) us) handleUnmonitorReq :: forall k v. (Keyable k, Serializable v) => State k v -> CallRef () -> UnmonitorReq -> Process (ProcessReply () (State k v)) handleUnmonitorReq state _cRef (UnmonitorReq ref') = do let pid = fst $ unRef ref' reply () $ ( (monitors ^: MultiMap.filter ((/= ref') . ref)) . (listeningPids ^: Set.delete pid) $ state ) handleRegNamesLookup :: forall k v. (Keyable k, Serializable v) => RegNamesReq -> RestrictedProcess (State k v) (Result [k]) handleRegNamesLookup (RegNamesReq p) = do state <- getState Restricted.reply $ Map.foldlWithKey' (acc p) [] (state ^. names) where acc pid ns n pid' | pid == pid' = (n:ns) | otherwise = ns handleMonitorSignal :: forall k v. (Keyable k, Serializable v) => State k v -> ProcessMonitorNotification -> Process (ProcessAction (State k v)) handleMonitorSignal state@State{..} (ProcessMonitorNotification _ pid diedReason) = do let state' = removeActiveSubscriptions pid state (deadNames, deadProps) <- notifyListeners state' pid diedReason continue $ ( (names ^= Map.difference _names deadNames) . (properties ^= Map.difference _properties deadProps) $ state) where removeActiveSubscriptions p s = let subscriptions = (state ^. listeningPids) in case (Set.member p subscriptions) of False -> s True -> ( (listeningPids ^: Set.delete p) -- delete any monitors this (now dead) process held . (monitors ^: MultiMap.filter ((/= p) . fst . unRef . ref)) $ s) notifyListeners :: State k v -> ProcessId -> DiedReason -> Process (HashMap k ProcessId, HashMap (ProcessId, k) v) notifyListeners st pid' dr = do let diedNames = Map.filter (== pid') (st ^. names) let diedProps = Map.filterWithKey (\(p, _) _ -> p == pid') (st ^. properties) let nameSubs = MultiMap.filterWithKey (\k _ -> Map.member k diedNames) (st ^. monitors) let propSubs = MultiMap.filterWithKey (\k _ -> Map.member (pid', k) diedProps) (st ^. monitors) forM_ (MultiMap.toList nameSubs) $ \(kIdent, KMRef{..}) -> do let kEvDied = KeyOwnerDied { diedReason = dr } let mRef = RegistryKeyMonitorNotification kIdent ref us <- getSelfPid case mask of Nothing -> sendTo ref (mRef kEvDied us) Just mask' -> do case (elem OnKeyOwnershipChange mask') of True -> sendTo ref (mRef kEvDied us) False -> do if (elem OnKeyUnregistered mask') then sendTo ref (mRef KeyUnregistered us) else return () forM_ (MultiMap.toList propSubs) (notifyPropSubscribers dr) return (diedNames, diedProps) notifyPropSubscribers dr' (kIdent, KMRef{..}) = do let died = maybe False (elem OnKeyOwnershipChange) mask let event = case died of True -> KeyOwnerDied { diedReason = dr' } False -> KeyUnregistered getSelfPid >>= sendTo ref . RegistryKeyMonitorNotification kIdent ref event ensureMonitored :: ProcessId -> HashSet ProcessId -> Process (HashSet ProcessId) ensureMonitored pid refs = do case (Set.member pid refs) of True -> return refs False -> P.monitor pid >> return (Set.insert pid refs) notifySubscribers :: forall k v. (Keyable k, Serializable v) => k -> State k v -> KeyUpdateEvent -> Process () notifySubscribers k st ev = do let subscribers = MultiMap.filterWithKey (\k' _ -> k' == k) (st ^. monitors) forM_ (MultiMap.toList subscribers) $ \(_, KMRef{..}) -> do if (maybe True (elem (maskFor ev)) mask) then getSelfPid >>= sendTo ref . RegistryKeyMonitorNotification k ref ev else {- (liftIO $ putStrLn "no mask") >> -} return () -------------------------------------------------------------------------------- -- Utilities / Accessors -- -------------------------------------------------------------------------------- maskFor :: KeyUpdateEvent -> KeyUpdateEventMask maskFor (KeyRegistered _) = OnKeyRegistered maskFor KeyUnregistered = OnKeyUnregistered maskFor (KeyOwnerDied _) = OnKeyOwnershipChange maskFor (KeyOwnerChanged _ _) = OnKeyOwnershipChange maskFor KeyLeaseExpired = OnKeyLeaseExpiry findName :: forall k v. (Keyable k, Serializable v) => Key k -> State k v -> Maybe ProcessId findName Key{..} state = Map.lookup keyIdentity (state ^. names) names :: forall k v. Accessor (State k v) (HashMap k ProcessId) names = accessor _names (\n' st -> st { _names = n' }) properties :: forall k v. Accessor (State k v) (HashMap (ProcessId, k) v) properties = accessor _properties (\ps st -> st { _properties = ps }) monitors :: forall k v. Accessor (State k v) (MultiMap k KMRef) monitors = accessor _monitors (\ms st -> st { _monitors = ms }) registeredPids :: forall k v. Accessor (State k v) (HashSet ProcessId) registeredPids = accessor _registeredPids (\mp st -> st { _registeredPids = mp }) listeningPids :: forall k v. Accessor (State k v) (HashSet ProcessId) listeningPids = accessor _listeningPids (\lp st -> st { _listeningPids = lp }) monitorIdCount :: forall k v. Accessor (State k v) Integer monitorIdCount = accessor _monitorIdCount (\i st -> st { _monitorIdCount = i })
haskell-distributed/distributed-process-registry
src/Control/Distributed/Process/Registry.hs
bsd-3-clause
41,815
66
26
10,991
9,833
5,212
4,621
-1
-1
module Diag.Util.Encoding where import Data.Char import Data.Word import Data.Bits import Numeric import Data.List import qualified Data.ByteString.Char8 as B import qualified Data.ByteString as S int2Word8 x = fromIntegral x :: Word8 word8ToInt x = fromIntegral x :: Int encodeInt :: (Integral a, Bits a) => a -> Int -> [Word8] encodeInt n width = [int2Word8 $ 0xFF .&. (n `shiftR` s) | s <- reverse $ take width [0,8..]] encodeLength :: Int -> [Word8] encodeLength len = [0xFF .&. int2Word8 (len `shiftR` 24) ,0xFF .&. int2Word8 (len `shiftR` 16) ,0xFF .&. int2Word8 (len `shiftR` 8) ,0xFF .&. int2Word8 (len `shiftR` 0)] string2hex :: String -> Word8 string2hex = fst . head . readHex string2hex16 :: String -> Word16 string2hex16 = fst . head . readHex showAsHex :: Word8 -> String showAsHex = ((++) "0x") . (flip showHex "") showAsHexOneString :: [Word8] -> String showAsHexOneString bs = "0x" ++ (concatMap showMin2Chars bs) showMin2Chars :: Word8 -> String showMin2Chars n = let x = flip showHex "" n len = length x in replicate (2 - len) '0' ++ x showAsHexString :: [Word8] -> String showAsHexString bs = '[':(intercalate "," $ map (showAsHex) bs) ++ "]" showAsBin :: Word8 -> String showAsBin = flip showBin "" where showBin = showIntAtBase 2 intToDigit showBinString :: B.ByteString -> String showBinString xs = showAsHexNumbers $ S.unpack xs showAsHexNumbers :: [Word8] -> String showAsHexNumbers xs = concat $ intersperse "," $ map (showAsHex . int2Word8) xs nothingIf :: Bool -> Maybe Int nothingIf True = Nothing nothingIf False = Just 0 convert :: String -> Char convert = chr . fst . head . readHex toWord :: (Enum a) => a -> Word8 toWord = int2Word8 . fromEnum
marcmo/hsDiagnosis
src/Diag/Util/Encoding.hs
bsd-3-clause
1,777
4
11
380
617
343
274
48
1
{-# LANGUAGE TemplateHaskell, QuasiQuotes #-} module Language.C.CPPPP.Transforms.Chs (mkChs, mkObjChs) where import Language.C.CPPPP.Transforms.CTypes import qualified Language.C.Syntax as C import Language.C.Quote.C import Data.Loc (SrcLoc) import Data.List import Language.Haskell.TH hiding (varP) import System.IO mkChs = (initHs, mkChs', closeHs) mkObjChs = (initHs', mkObjChs', closeHs) mkChs' :: Handle -> String -> [C.Id] -> SrcLoc -> IO (Handle, C.Initializer) mkChs' h ex vars loc = (fcall ex vars :: IO (FCall CLang)) >>= emit h loc mkObjChs' :: Handle -> String -> [C.Id] -> SrcLoc -> IO (Handle, C.Initializer) mkObjChs' h ex vars loc = (fcall ex vars :: IO (FCall ObjCLang)) >>= emit h loc initHs = do h <- openFile "HSAux.hs" WriteMode hPutStrLn h "module HSAux where\n" return h initHs' = do h <- openFile "HSAuxObjC.hs" WriteMode hPutStrLn h "module HSAuxObjC where\n" return h closeHs = hClose -- | Return the C expression and use IO to generate the auxiliary Haskell -- | The auxiliary Haskell will use the FFI -- It should also have a unique counter for generated function names (instead of Data.Unique). -- | Write out the aux Haskell and return the C Expression to substitute emit :: (FormatString a) => Handle -> SrcLoc -> FCall a -> IO (Handle, C.Initializer) emit h loc (FCall fname ffi_name args) = do let carg_list = map snd args cexpr = C.FnCall (C.Var (C.Id ffi_name loc) loc) (map (flip C.Var loc) carg_list) loc hs_expr <- runQ $ mkHsExpr ffi_name fname args hPutStrLn h $ pprint hs_expr return (h, [cinit|$cexpr|]) -- args: [(CType CInt,Id "x" ),(CType CInt,Id "y" )] mkHsExpr :: FormatString a => String -> String -> [(Arg a, C.Id)] -> Q [Dec] mkHsExpr ffi_name fname args = do names <- mapM newName $ replicate (length args) "x" let types = applyT $ map (mkName . mkType . fst) args mar = map (mkMarshalling . fst) args body = NormalB $ applyN (zip mar (reverse names)) (mkName fname) for = ForeignD $ ExportF CCall ffi_name (mkName ffi_name) types decl = FunD (mkName ffi_name) [Clause (map VarP names) body []] return [for, decl] applyN :: [(Exp, Name)] -> Name -> Exp applyN [] fname = VarE fname applyN [(m, x)] fname = AppE (VarE fname) (AppE m (VarE x)) applyN ((m, x):xs) fname = AppE (applyN xs fname) (AppE m (VarE x)) applyT :: [Name] -> Type -- applyT [] = boom applyT [x] = ConT x applyT (x:xs) = AppT (AppT ArrowT (ConT x)) (applyT xs)
mxswd/cpppp
Language/C/CPPPP/Transforms/Chs.hs
bsd-3-clause
2,463
0
15
483
940
492
448
47
1
{-# OPTIONS -Wall #-} {-| Module : Esge.Base Description : Highlevel basic esge module. Copyright : (c) Simon Goller, 2015 License : BSD Maintainer : [email protected] Basic required functions in order create a game. They are higher level and let you for example move Individuals. Many features are introduced by this module * Error handling * Individual and Room interaction * State * Player handling * Provide basic 'EC.Action's -} module Esge.Base ( -- * Type definitions Error (RoomNotFoundError, ExitNotFoundError), State (stPlayer, stVersion, stName), -- * Error functions printError, -- * Individual/Room interaction individualsInRoomId, individualsInRoom, roomsOfIndividualId, roomOfIndividualId, roomOfIndividual, beam, move, -- * State functions nullState, state, -- * Player specific functions player, currRoom, -- * Actions -- ** Long term actions infinityAction, condInfinityAction, condDropableAction, condSingleAction, delayedAction, -- ** Game state actions moveRoomAction, showRoomAction, showIndAction, showStateAction, showStorageAction ) where import qualified Esge.Core as EC import qualified Esge.Room as ER import qualified Esge.Individual as EI import Data.Maybe (catMaybes) -- | Thrown in case of something goes wrong data Error = RoomNotFoundError String | ExitNotFoundError String deriving (Show, Read, Eq) -- | Return all individuals from the given room id. -- Result is Nothing if room is not found. individualsInRoomId :: String -> EC.Ingame -> Maybe [EI.Individual] individualsInRoomId key ingame = do room <- ER.getRoomMaybe ingame key let inds = ER.individual room :: [String] let storages = catMaybes $ map (flip EC.storageGet $ ingame) inds :: [EC.Storage] let maybeInds = map EC.fromStorage storages :: [Maybe EI.Individual] return $ catMaybes maybeInds -- | Return all individuals from the given room individualsInRoom :: ER.Room -> EC.Ingame -> Maybe [EI.Individual] individualsInRoom room ingame = individualsInRoomId (ER.key room) ingame -- | Room which contains the given Individual id. -- Returns nullRoom if not found roomOfIndividualId :: String -> EC.Ingame -> ER.Room roomOfIndividualId key ingame = let rooms = roomsOfIndividualId key ingame in if null rooms then ER.nullRoom else head rooms -- | Return all rooms, where the individual is located. -- -- This should only be one or nothing otherwise there is most likely an issue -- in the story setup. Normally, 'roomOfIndividualId' or 'roomOfIndividual' -- should be used. The purpose of this function is as helper for the -- plausability check. roomsOfIndividualId :: String -> EC.Ingame -> [ER.Room] roomsOfIndividualId key ingame = let rooms = ER.allRooms ingame :: [ER.Room] in filter (\x -> elem key $ ER.individual x) rooms -- | Room which contains the given Individual roomOfIndividual :: EI.Individual -> EC.Ingame -> ER.Room roomOfIndividual ind ingame = roomOfIndividualId (EI.key ind) ingame -- | Place Individual in other room beam :: EI.Individual -> String -> EC.Action (Either Error ()) beam ind roomId = do ingame <- EC.getIngame let indKey = EI.key ind fromRoom = roomOfIndividual ind ingame case ER.getRoomMaybe ingame roomId of Nothing -> return $ Left $ RoomNotFoundError roomId Just room -> do let room' = ER.addIndividualId indKey room fromRoom' = ER.removeIndividualId indKey fromRoom EC.storageInsertA fromRoom' EC.storageInsertA room' return $ Right () -- | Move individual through an exit to another room move :: EI.Individual -> String -> EC.Action (Either Error ()) move ind exitRoom = do ingame <- EC.getIngame let fromRoom = roomOfIndividual ind ingame if exitRoom `elem` (map fst $ ER.exits fromRoom) then beam ind (maybe "" id $ lookup exitRoom $ ER.exits fromRoom) else return $ Left $ ExitNotFoundError exitRoom -- | Important state values data State = State { stPlayer :: String, stVersion :: String, stName :: String } deriving (Eq, Read, Show) -- | State to use in case of an error nullState :: State nullState = State "" "" "" -- | State can be stored in 'EC.Ingame' instance EC.Storageable State where toStorage st = EC.Storage "state" "esgeState" [ ("player", stPlayer st), ("version", stVersion st), ("name", stName st) ] fromStorage (EC.Storage _ t metas) = if t /= "esgeState" then Nothing else do ply <- lookup "player" metas version <- lookup "version" metas name <- lookup "name" metas return State { stPlayer = ply, stVersion = version, stName = name } -- | Get state from 'EC.Ingame' state :: EC.Ingame -> State state ingame = maybe nullState id $ do storage <- EC.storageGet "state" ingame st <- EC.fromStorage storage return st -- | Get player from 'EC.Ingame' player :: EC.Ingame -> EI.Individual player ingame = let playerId = stPlayer $ state ingame in EI.getIndividualNull ingame playerId -- | Get room where player is located currRoom :: EC.Ingame -> ER.Room currRoom ingame = roomOfIndividual (player ingame) ingame -- | Print 'Error' to 'EC.Ingame' output response printError :: Error -> EC.Action () printError err = EC.setIngameResponseA "output" ( case err of RoomNotFoundError str -> "Room not found: '" ++ str ++ "'" ExitNotFoundError str -> "Exit not found: " ++ str ++ "'" ) -- | Move player in 'Room' of behind exit. moveRoomAction :: String -> EC.Action () moveRoomAction exitName = do ingame <- EC.getIngame res <- move (player ingame) exitName case res of Left err -> printError err Right () -> return () -- | Display room showRoomAction :: EC.Action () showRoomAction = do ingame <- EC.getIngame let room = currRoom ingame roomText = ER.title room ++ "\n" ++ ER.desc room ++ "\n" ++ "Exits: " ++ (unwords $ ER.exitNames room) EC.setIngameResponseA "output" roomText -- | Show individual showIndAction :: EI.Individual -> EC.Action () showIndAction ind = EC.setIngameResponseA "output" indText where indText = EI.name ind -- | Show state for debugging showStateAction :: EC.Action () showStateAction = do ingame <- EC.getIngame let stateText = show $ state ingame EC.setIngameResponseA "output" stateText -- | Show the whole 'Storage' showStorageAction :: EC.Action () showStorageAction = do ingame <- EC.getIngame let stateText = show $ EC.storage ingame EC.setIngameResponseA "output" stateText -- | Run given action and re register infinityAction :: EC.Action () -> EC.Action () infinityAction act = do let self = infinityAction act EC.replaceIngame $ EC.scheduleAction self act -- | Run given action only if condition is true condInfinityAction :: (EC.Ingame -> Bool) -> EC.Action () -> EC.Action () condInfinityAction condFn act = do let self = condInfinityAction condFn act EC.replaceIngame $ EC.scheduleAction self ingame <- EC.getIngame if condFn ingame then act else return () -- | Run given action as long as condition is true, then remove it condDropableAction :: (EC.Ingame -> Bool) -> EC.Action () -> EC.Action () condDropableAction condFn act = do let self = condDropableAction condFn act ingame <- EC.getIngame if condFn ingame then do EC.replaceIngame $ EC.scheduleAction self act else return () -- | Do nothing until the condition becomes true, then run 'Action' once -- and remove. condSingleAction :: (EC.Ingame -> Bool) -> EC.Action () -> EC.Action () condSingleAction condFn act = do let self = condSingleAction condFn act ingame <- EC.getIngame if condFn ingame then act else EC.replaceIngame $ EC.scheduleAction self -- | Wait n times and then run the action delayedAction :: Int -> EC.Action () -> EC.Action () delayedAction n act = do let self = delayedAction (n - 1) act if n <= 0 then act else EC.replaceIngame $ EC.scheduleAction self
neosam/esge
src/Esge/Base.hs
bsd-3-clause
8,528
0
16
2,160
2,077
1,053
1,024
178
2
module TestData where import Data.IntMap as IMap import Data.Set as Set data Codegen = C | JS deriving (Show, Eq, Ord) type Index = Int data CompatCodegen = ANY | C_CG | NODE_CG | NONE -- A TestFamily groups tests that share the same theme data TestFamily = TestFamily { -- A shorter lowcase name to use in filenames id :: String, -- A proper name for the test family that will be displayed name :: String, -- A map of test metadata: -- - The key is the index (>=1 && <1000) -- - The value is the set of compatible code generators, -- or Nothing if the test doesn't depend on a code generator tests :: IntMap (Maybe (Set Codegen)) } deriving (Show) toCodegenSet :: CompatCodegen -> Maybe (Set Codegen) toCodegenSet compatCodegen = fmap Set.fromList mList where mList = case compatCodegen of ANY -> Just [ C, JS ] C_CG -> Just [ C ] NODE_CG -> Just [ JS ] NONE -> Nothing testFamilies :: [TestFamily] testFamilies = fmap instantiate testFamiliesData where instantiate (id, name, testsData) = TestFamily id name tests where tests = IMap.fromList (fmap makeSetCodegen testsData) makeSetCodegen (index, codegens) = (index, toCodegenSet codegens) testFamiliesForCodegen :: Codegen -> [TestFamily] testFamiliesForCodegen codegen = fmap (\testFamily -> testFamily {tests = IMap.filter f (tests testFamily)}) testFamilies where f mCodegens = case mCodegens of Just codegens -> Set.member codegen codegens Nothing -> True -- The data to instanciate testFamilies -- The first column is the id -- The second column is the proper name (the prefix of the subfolders) -- The third column is the data for each test testFamiliesData :: [(String, String, [(Index, CompatCodegen)])] testFamiliesData = [ ("base", "Base", [ ( 1, C_CG )]), ("basic", "Basic", [ ( 1, ANY ), ( 2, ANY ), ( 3, ANY ), ( 4, ANY ), ( 5, ANY ), ( 6, ANY ), ( 7, C_CG ), ( 8, ANY ), ( 9, ANY ), ( 10, ANY ), ( 11, C_CG ), ( 12, ANY ), ( 13, ANY ), ( 14, ANY ), ( 15, ANY ), ( 16, ANY ), ( 17, ANY ), ( 18, ANY ), ( 19, ANY ), ( 20, ANY ), ( 21, C_CG )]), ("bignum", "Bignum", [ ( 1, ANY ), ( 2, ANY )]), ("bounded", "Bounded", [ ( 1, ANY )]), ("buffer", "Buffer", [ ( 1, C_CG )]), ("corecords", "Corecords", [ ( 1, ANY ), ( 2, ANY )]), ("delab", "De-elaboration", [ ( 1, ANY )]), ("directives", "Directives", [ ( 1, ANY ), ( 2, ANY )]), ("disambig", "Disambiguation", [ ( 2, ANY )]), ("docs", "Documentation", [ ( 1, ANY ), ( 2, ANY ), ( 3, ANY ), ( 4, ANY ), ( 5, ANY ), ( 6, ANY )]), ("dsl", "DSL", [ ( 1, ANY ), ( 2, C_CG ), ( 3, ANY ), ( 4, ANY )]), ("effects", "Effects", [ ( 1, C_CG ), ( 2, C_CG ), ( 3, ANY ), ( 4, ANY ), ( 5, ANY )]), ("error", "Errors", [ ( 1, ANY ), ( 2, ANY ), ( 3, ANY ), ( 4, ANY ), ( 5, ANY ), ( 6, ANY ), ( 7, ANY ), ( 8, ANY ), ( 9, ANY )]), ("ffi", "FFI", [ ( 1, ANY ) , ( 2, ANY ) , ( 3, ANY ) , ( 4, ANY ) , ( 5, ANY ) , ( 6, C_CG ) , ( 7, C_CG ) , ( 8, C_CG ) , ( 9, C_CG ) , ( 10, NODE_CG ) , ( 11, NODE_CG ) ]), ("folding", "Folding", [ ( 1, ANY )]), ("idrisdoc", "Idris documentation", [ ( 1, ANY ), ( 2, ANY ), ( 3, ANY ), ( 4, ANY ), ( 5, ANY ), ( 6, ANY ), ( 7, ANY ), ( 8, ANY ), ( 9, ANY )]), ("interactive", "Interactive editing", [ ( 1, ANY ), ( 2, ANY ), ( 3, ANY ), ( 4, ANY ), ( 5, ANY ), ( 6, ANY ), ( 7, ANY ), ( 8, ANY ), ( 9, ANY ), ( 10, ANY ), ( 11, ANY ), ( 12, ANY ), ( 13, ANY ), ( 14, C_CG ), ( 15, ANY ), ( 16, ANY ), -- FIXME: Re-enable interactive017 once it works with and without node. -- FIXME: See https://github.com/idris-lang/Idris-dev/pull/4046#issuecomment-326910042 -- ( 17, ANY ), ( 18, ANY )]), ("interfaces", "Interfaces", [ ( 1, ANY ), ( 2, ANY ), ( 3, ANY ), ( 4, ANY ), -- ( 5, ANY ), ( 6, ANY ), ( 7, ANY ), ( 8, ANY )]), ("interpret", "Interpret", [ ( 1, ANY ), ( 2, ANY )]), ("io", "IO monad", [ ( 1, C_CG ), ( 2, ANY ), ( 3, C_CG )]), ("layout", "Layout", [ ( 1, ANY )]), ("literate", "Literate programming", [ ( 1, ANY )]), ("meta", "Meta-programming", [ ( 1, ANY ), ( 2, ANY ), ( 3, ANY ), ( 4, ANY )]), ("pkg", "Packages", [ ( 1, ANY ), ( 2, ANY ), ( 3, ANY ), ( 4, ANY ), ( 5, ANY ), ( 6, ANY ), ( 7, ANY ), ( 8, ANY )]), ("prelude", "Prelude", [ ( 1, ANY )]), ("primitives", "Primitive types", [ ( 1, ANY ), ( 2, ANY ), ( 3, ANY ), ( 5, C_CG ), ( 6, C_CG )]), ("proof", "Theorem proving", [ ( 1, ANY ), ( 2, ANY ), ( 3, ANY ), ( 4, ANY ), ( 5, ANY ), ( 6, ANY ), ( 7, ANY ), ( 8, ANY ), ( 9, ANY ), ( 10, ANY ), ( 11, ANY )]), ("proofsearch", "Proof search", [ ( 1, ANY ), ( 2, ANY ), ( 3, ANY )]), ("pruviloj", "Pruviloj", [ ( 1, ANY )]), ("quasiquote", "Quasiquotations", [ ( 1, ANY ), ( 2, ANY ), ( 3, ANY ), ( 4, ANY ), ( 5, ANY ), ( 6, ANY )]), ("records", "Records", [ ( 1, ANY ), ( 2, ANY ), ( 3, ANY ), ( 4, ANY ), ( 5, ANY )]), ("reg", "Regressions", [ ( 1, ANY ), ( 2, ANY ), ( 4, ANY ), ( 5, ANY ), ( 13, ANY ), ( 16, ANY ), ( 17, ANY ), ( 20, ANY ), ( 24, ANY ), ( 25, ANY ), ( 27, ANY ), ( 29, C_CG ), ( 31, ANY ), ( 32, ANY ), ( 39, ANY ), ( 40, ANY ), ( 41, ANY ), ( 42, ANY ), ( 45, ANY ), ( 48, ANY ), ( 52, C_CG ), ( 67, ANY ), ( 75, ANY ), ( 76, ANY ), ( 77, ANY )]), ("regression", "Regression", [ ( 1 , ANY ), ( 2 , ANY ), ( 3 , ANY )]), ("sourceLocation", "Source location", [ ( 1 , ANY )]), ("sugar", "Syntactic sugar", [ ( 1, ANY ), ( 2, ANY ), ( 3, ANY ), ( 4, C_CG ), ( 5, ANY )]), ("syntax", "Syntax extensions", [ ( 1, ANY ), ( 2, ANY )]), ("tactics", "Tactics", [ ( 1, ANY )]), ("totality", "Totality checking", [ ( 1, ANY ), ( 2, ANY ), ( 3, ANY ), ( 4, ANY ), ( 5, ANY ), ( 6, ANY ), ( 7, ANY ), ( 8, ANY ), ( 9, ANY ), ( 10, ANY ), ( 11, ANY ), ( 12, ANY ), ( 13, ANY ), ( 14, ANY ), ( 15, ANY ), ( 16, ANY ), ( 17, ANY ), ( 18, ANY ), ( 19, ANY ), ( 20, ANY ), ( 21, ANY ), ( 22, ANY ), ( 23, ANY )]), ("tutorial", "Tutorial examples", [ ( 1, ANY ), ( 2, ANY ), ( 3, ANY ), ( 4, ANY ), ( 5, ANY ), ( 6, ANY ), ( 7, C_CG )]), ("unique", "Uniqueness types", [ ( 1, ANY ), ( 4, ANY )]), ("universes", "Universes", [ ( 1, ANY ), ( 2, ANY )]), ("views", "Views", [ ( 1, ANY ), ( 2, ANY ), ( 3, C_CG )])]
uuhan/Idris-dev
test/TestData.hs
bsd-3-clause
8,201
0
13
3,588
2,964
1,934
1,030
300
4
module HLearn.Data.UnsafeVector ( setptsize ) where import Control.DeepSeq import Control.Monad import Data.IORef import Debug.Trace import qualified Data.Foldable as F import Data.Primitive import Data.Primitive.MachDeps import qualified Data.Vector.Generic as VG import qualified Data.Vector.Generic.Mutable as VGM import qualified Data.Vector.Unboxed as VU import qualified Data.Vector.Unboxed.Mutable as VUM import System.IO.Unsafe import qualified Data.Strict.Maybe as Strict import Data.Csv import Unsafe.Coerce import Data.Hashable import Data.Primitive.ByteArray import GHC.Prim import GHC.Int import GHC.Types import SubHask hiding (Functor(..), Applicative(..), Monad(..), Then(..), fail, return, liftM, forM_) -- import SubHask.Compatibility.Vector.HistogramMetrics import SubHask.Compatibility.Vector.Lebesgue ------------------------------------------------------------------------------- -- unsafe globals {-# NOINLINE ptsizeIO #-} ptsizeIO = unsafeDupablePerformIO $ newIORef (16::Int) {-# NOINLINE ptalignIO #-} ptalignIO = unsafeDupablePerformIO $ newIORef (16::Int) {-# NOINLINE ptsize #-} ptsize = unsafeDupablePerformIO $ readIORef ptsizeIO {-# NOINLINE ptalign #-} ptalign = unsafeDupablePerformIO $ readIORef ptalignIO setptsize :: Int -> IO () setptsize len = do writeIORef ptsizeIO len writeIORef ptalignIO (4::Int) ------------------------------------------------------------------------------- -- l2 vector ops instance VUM.Unbox elem => VUM.Unbox (L2 VU.Vector elem) data instance VUM.MVector s (L2 VU.Vector elem) = UnsafeMVector { elemsizeM :: {-#UNPACK#-} !Int , elemsizerealM :: {-#UNPACK#-} !Int , lenM :: {-#UNPACK#-} !Int , vecM :: !(VUM.MVector s elem) } instance ( VG.Vector VU.Vector elem , VGM.MVector VUM.MVector elem ) => VGM.MVector VUM.MVector (L2 VU.Vector elem) where {-# INLINABLE basicLength #-} basicLength uv = lenM uv {-# INLINABLE basicUnsafeSlice #-} basicUnsafeSlice i lenM' uv = UnsafeMVector { elemsizeM = elemsizeM uv , elemsizerealM = elemsizerealM uv , lenM = lenM' , vecM = VGM.basicUnsafeSlice (i*elemsizerealM uv) (lenM'*elemsizerealM uv) $ vecM uv } {-# INLINABLE basicOverlaps #-} basicOverlaps uv1 uv2 = VGM.basicOverlaps (vecM uv1) (vecM uv2) {-# INLINABLE basicUnsafeNew #-} basicUnsafeNew lenM' = do let elemsizeM'=ptsize -- let elemsizerealM'=20 let elemsizerealM'=ptalign*(ptsize `div` ptalign) +if ptsize `mod` ptalign == 0 then 0 else ptalign -- trace ("elemsizeM' = "++show elemsizeM') $ return () -- trace ("elemsizerealM' = "++show elemsizerealM') $ return () vecM' <- VGM.basicUnsafeNew (lenM'*elemsizerealM') return $ UnsafeMVector { elemsizeM=elemsizeM' , elemsizerealM=elemsizerealM' , lenM=lenM' , vecM=vecM' } {-# INLINABLE basicUnsafeRead #-} basicUnsafeRead uv i = liftM L2 $ VG.freeze $ VGM.unsafeSlice (i*elemsizerealM uv) (elemsizeM uv) (vecM uv) {-# INLINABLE basicUnsafeWrite #-} -- FIXME: this is probably better, but it causes GHC to panic -- basicUnsafeWrite uv loc v = go 0 -- where -- go i = if i <= elemsizerealM uv -- then do -- VGM.unsafeWrite (vecM uv) (start+i) $ v `VG.unsafeIndex` i -- go (i+1) -- else return () -- start = loc*elemsizerealM uv basicUnsafeWrite uv loc v = forM_ [0..elemsizeM uv-1] $ \i -> do let x = v `VG.unsafeIndex` i VGM.unsafeWrite (vecM uv) (start+i) x where start = loc*elemsizerealM uv {-# INLINABLE basicUnsafeCopy #-} basicUnsafeCopy v1 v2 = VGM.basicUnsafeCopy (vecM v1) (vecM v2) {-# INLINABLE basicUnsafeMove #-} basicUnsafeMove v1 v2 = VGM.basicUnsafeMove (vecM v1) (vecM v2) -- {-# INLINABLE basicSet #-} -- basicSet v x = VGM.basicSet (vecM v) x ------------------------------------------------------------------------------- -- immutable vector data instance VU.Vector (L2 VU.Vector elem) = UnsafeVector { elemsize :: {-# UNPACK #-} !Int , elemsizereal :: {-# UNPACK #-} !Int , len :: {-# UNPACK #-} !Int , vec :: !(L2 VU.Vector elem) } instance ( VG.Vector VU.Vector elem , VGM.MVector VUM.MVector elem ) => VG.Vector VU.Vector (L2 VU.Vector elem) where {-# INLINABLE basicUnsafeFreeze #-} basicUnsafeFreeze uv = do vec' <- VG.basicUnsafeFreeze (vecM uv) return $ UnsafeVector { elemsize = elemsizeM uv , elemsizereal = elemsizerealM uv , len = lenM uv , vec = L2 vec' } {-# INLINABLE basicUnsafeThaw #-} basicUnsafeThaw uv = do vecM' <- VG.basicUnsafeThaw (unL2 $ vec uv) return $ UnsafeMVector { elemsizeM = elemsize uv , elemsizerealM = elemsizereal uv , lenM = len uv , vecM = vecM' } {-# INLINABLE basicLength #-} basicLength uv = len uv {-# INLINABLE basicUnsafeSlice #-} basicUnsafeSlice i len' uv = uv { len = len' , vec = VG.basicUnsafeSlice (i*elemsizereal uv) (len'*elemsizereal uv) (vec uv) } {-# INLINABLE basicUnsafeIndexM #-} basicUnsafeIndexM uv i = return $ VG.basicUnsafeSlice (i*elemsizereal uv) (elemsize uv) (vec uv) -- {-# INLINABLE basicUnsafeCopy #-} -- basicUnsafeCopy mv v = VG.basicUnsafeCopy (vecM mv) (vec v) ------------------------------------------------------------------------------- -- Labeled' instance (VUM.Unbox x, VUM.Unbox y) => VUM.Unbox (Labeled' x y) newtype instance VUM.MVector s (Labeled' x y) = UMV_Labeled' (VUM.MVector s (x,y)) instance ( VUM.Unbox x , VUM.Unbox y ) => VGM.MVector VUM.MVector (Labeled' x y) where {-# INLINABLE basicLength #-} {-# INLINABLE basicUnsafeSlice #-} {-# INLINABLE basicOverlaps #-} {-# INLINABLE basicUnsafeNew #-} {-# INLINABLE basicUnsafeRead #-} {-# INLINABLE basicUnsafeWrite #-} {-# INLINABLE basicUnsafeCopy #-} {-# INLINABLE basicUnsafeMove #-} {-# INLINABLE basicSet #-} basicLength (UMV_Labeled' v) = VGM.basicLength v basicUnsafeSlice i len (UMV_Labeled' v) = UMV_Labeled' $ VGM.basicUnsafeSlice i len v basicOverlaps (UMV_Labeled' v1) (UMV_Labeled' v2) = VGM.basicOverlaps v1 v2 basicUnsafeNew len = liftM UMV_Labeled' $ VGM.basicUnsafeNew len basicUnsafeRead (UMV_Labeled' v) i = do (!x,!y) <- VGM.basicUnsafeRead v i return $ Labeled' x y basicUnsafeWrite (UMV_Labeled' v) i (Labeled' x y) = VGM.basicUnsafeWrite v i (x,y) basicUnsafeCopy (UMV_Labeled' v1) (UMV_Labeled' v2) = VGM.basicUnsafeCopy v1 v2 basicUnsafeMove (UMV_Labeled' v1) (UMV_Labeled' v2) = VGM.basicUnsafeMove v1 v2 basicSet (UMV_Labeled' v1) (Labeled' x y) = VGM.basicSet v1 (x,y) newtype instance VU.Vector (Labeled' x y) = UV_Labeled' (VU.Vector (x,y)) instance ( VUM.Unbox x , VUM.Unbox y ) => VG.Vector VU.Vector (Labeled' x y) where {-# INLINABLE basicUnsafeFreeze #-} {-# INLINABLE basicUnsafeThaw #-} {-# INLINABLE basicLength #-} {-# INLINABLE basicUnsafeSlice #-} {-# INLINABLE basicUnsafeIndexM #-} basicUnsafeFreeze (UMV_Labeled' v) = liftM UV_Labeled' $ VG.basicUnsafeFreeze v basicUnsafeThaw (UV_Labeled' v) = liftM UMV_Labeled' $ VG.basicUnsafeThaw v basicLength (UV_Labeled' v) = VG.basicLength v basicUnsafeSlice i len (UV_Labeled' v) = UV_Labeled' $ VG.basicUnsafeSlice i len v basicUnsafeIndexM (UV_Labeled' v) i = do (!x,!y) <- VG.basicUnsafeIndexM v i return $ Labeled' x y
iamkingmaker/HLearn
src/HLearn/Data/UnsafeVector.hs
bsd-3-clause
7,912
26
16
1,953
1,897
1,029
868
-1
-1
{-# LANGUAGE QuasiQuotes #-} module Test0 () where import LiquidHaskell [lq| thing :: Int -> x:Int |] thing = undefined
spinda/liquidhaskell
benchmarks/gsoc15/neg/test5.hs
bsd-3-clause
124
0
4
24
23
16
7
5
1
{-# LANGUAGE DoRec, GeneralizedNewtypeDeriving #-} module Language.Brainfuck.CompileToIA32 (compile) where import qualified Language.Brainfuck.Syntax as BF import Language.IA32.Syntax import Control.Monad.RWS newtype Compiler a = Compiler { runCompiler :: RWS () [Directive] Label a } deriving (Monad, MonadFix) compile :: [BF.Stmt] -> Program compile program = Program $ snd $ execRWS (runCompiler (compileMain program)) () (Label 0) label :: Compiler Label label = Compiler $ do lbl <- get tell [LabelDef lbl] modify succ return lbl tellOp :: [Op] -> Compiler () tellOp = Compiler . tell . map Op (ptr, dat) = (Reg reg, Deref reg) where reg = EBP compileMain program = do tellOp [Mov ptr (Macro "BUF")] mapM_ compileStep $ group program tellOp [Mov (Reg EAX) (Imm 1), Mov (Reg EBX) (Imm 0), Int80] group = foldr f [] where f x (y@(x', n):ys) | x β‰ˆ x' = (x', n+1):ys | otherwise = (x, 1):y:ys f x [] = [(x, 1)] BF.IncPtr β‰ˆ BF.IncPtr = True BF.DecPtr β‰ˆ BF.DecPtr = True BF.IncData β‰ˆ BF.IncData = True BF.DecData β‰ˆ BF.DecData = True _ β‰ˆ _ = False arith 1 arg = Inc arg arith (-1) arg = Dec arg arith n arg | n > 0 = Add arg (Imm $ fromInteger n) | n < 0 = Sub arg (Imm $ fromInteger (abs n)) compileStep (BF.IncPtr, n) = tellOp [arith n ptr] compileStep (BF.DecPtr, n) = tellOp [arith (-n) ptr] compileStep (BF.IncData, n) = tellOp [arith n dat] compileStep (BF.DecData, n) = tellOp [arith (-n) dat] compileStep (BF.Output, 1) = tellOp [Mov (Reg EDX) (Imm 1), Mov (Reg ECX) (Target ptr), Mov (Reg EBX) (Imm 1), Mov (Reg EAX) (Imm 4), Int80] compileStep (BF.While prog, 1) = do rec l <- label tellOp [Cmp (Target dat) (Imm 0), JmpZero l'] mapM_ compileStep $ group prog tellOp [Jmp l] l' <- label return ()
gergoerdi/brainfuck
language-brainfuck/src/Language/Brainfuck/CompileToIA32.hs
bsd-3-clause
2,123
0
13
710
932
470
462
55
6
{-# OPTIONS -XDeriveDataTypeable -XCPP #-} module ShopCart ( shopCart) where import Data.Typeable import qualified Data.Vector as V import Text.Blaze.Html5 as El import Text.Blaze.Html5.Attributes as At hiding (step) import Data.Monoid import Data.String import Data.Typeable -- #define ALONE -- to execute it alone, uncomment this #ifdef ALONE import MFlow.Wai.Blaze.Html.All main= runNavigation "" $ transientNav grid #else import MFlow.Wai.Blaze.Html.All hiding(retry, page) import Menu #endif data ShopOptions= IPhone | IPod | IPad deriving (Bounded, Enum, Show,Read , Typeable) newtype Cart= Cart (V.Vector Int) deriving Typeable emptyCart= Cart $ V.fromList [0,0,0] shopCart= shopCart1 shopCart1 = do -- setHeader stdheader -- setTimeouts 200 $ 60*60 prod <- step . page $ do Cart cart <- getSessionData `onNothing` return emptyCart moreexplain ++> (table ! At.style (attr "border:1;width:20%;margin-left:auto;margin-right:auto") <<< caption << "choose an item" ++> thead << tr << ( th << b << "item" <> th << b << "times chosen") ++> (tbody <<< tr ! rowspan (attr "2") << td << linkHome ++> (tr <<< td <<< wlink IPhone (b << "iphone") <++ tdc << ( b << show ( cart V.! 0)) <|> tr <<< td <<< wlink IPod (b << "ipod") <++ tdc << ( b << show ( cart V.! 1)) <|> tr <<< td <<< wlink IPad (b << "ipad") <++ tdc << ( b << show ( cart V.! 2))) <++ tr << td << linkHome )) let i = fromEnum prod Cart cart <- getSessionData `onNothing` return emptyCart setSessionData . Cart $ cart V.// [(i, cart V.! i + 1 )] shopCart1 where tdc= td ! At.style (attr "text-align:center") linkHome= a ! href (attr $ "/" ++ noScript) << b << "home" attr= fromString moreexplain= do p $ El.span <<( "A persistent flow (uses step). The process is killed after the timeout set by setTimeouts "++ "but it is restarted automatically. Event If you restart the whole server, it remember the shopping cart "++ " The shopping cart is not logged, just the products bought returned by step are logged. The shopping cart "++ " is rebuild from the events (that is an example of event sourcing."++ " .Defines a table with links that return ints and a link to the menu, that abandon this flow. "++ " .The cart state is not stored, Only the history of events is saved. The cart is recreated by running the history of events.") p << "The second parameter of \"setTimeout\" is the time during which the cart is recorded"
agocorona/MFlow
Demos/ShopCart.hs
bsd-3-clause
2,856
0
35
881
656
351
305
49
1