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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|
module Folgerhs.Animate (animation) where
import System.Exit
import Data.Function (on)
import Data.Maybe
import Data.Array
import Data.List
import Data.Maybe (fromMaybe)
import Graphics.Gloss as G
import Graphics.Gloss.Data.Vector
import Graphics.Gloss.Interface.IO.Game
import Graphics.Gloss.Interface.Environment
import Folgerhs.Stage as S
import Folgerhs.Parse (parse)
type Palette = (Character -> Color)
data State = Paused | Resumed
deriving (Eq, Show)
type Play = (State, (Array Int StageEvent), Int, Palette)
takeA :: (Ix i, Eq e) => Int -> (Array i e) -> [e]
takeA i a = take i $ elems a
colors :: [Color]
colors = cycle [ red, green, blue, yellow, magenta, rose, violet, azure,
aquamarine, chartreuse, orange ]
selectColor :: [Character] -> Palette
selectColor chs ch = fromMaybe (greyN 0.5) $ lookup ch (zip chs colors)
newPlay :: Line -> [StageEvent] -> Play
newPlay l ses = ( Paused
, (listArray (1, length ses) ses)
, (fromMaybe 1 (elemIndex (Milestone l) ses))
, (selectColor $ characters ses)
)
boxW :: Float
boxW = 140
boxH :: Float
boxH = 40
speak :: Picture -> Picture
speak p = pictures [color (greyN 0.85) (rectangleSolid (boxW+10) (boxH+10)), p]
arrow :: Picture
arrow = color white $ pictures [ G.line [o, t1]
, G.line [o, t2]
, G.line [o, t3]
]
where o = (0, boxH/4)
t1 = mulSV (boxH/(-4)) (0,1)
a = mulSV (boxH/6) (0,1)
t2 = rotateV (pi/4) a
t3 = rotateV (-(pi/4)) a
above :: Picture -> Picture
above = translate 0 (boxH*3/4)
enter :: Picture -> Picture
enter p = pictures [p, color (withAlpha 0.6 black) (rectangleSolid boxW boxH), above (rotate 180 arrow)]
exit :: Picture -> Picture
exit p = pictures [p, color (withAlpha 0.6 black) (rectangleSolid boxW boxH), above arrow]
charPic :: Character -> Bool -> Color -> Picture
charPic ch sp c = let box = color c $ rectangleSolid boxW boxH
name = translate (-60) (-4) $ scale 0.1 0.1 $ text ch
pic = pictures [box, name]
in if sp then speak pic else pic
transArc :: Float -> Float -> Picture -> Picture
transArc d a p = let (x, y) = mulSV d $ unitVectorAtAngle a
in translate x y p
optPos :: Float -> Float -> Int -> (Float, Float)
optPos a s i = let i' = fromIntegral i
in (max a (s*i' / (2*pi)), 2*pi / i')
charPics :: Play -> [Picture]
charPics p@(_,ses,i,cf) = let sp = accumSpeaker (takeA i ses)
chs = accumStage (takeA i ses)
charPic' ch = charPic ch (ch == sp) (cf ch)
in case ses ! i of
(Entrance chs') -> map charPic' (chs \\ chs') ++ map (enter . charPic') chs'
(Exit chs') -> map charPic' (chs \\ chs') ++ map (exit . charPic') chs'
_ -> map charPic' chs
curLine :: Play -> Line
curLine (_, ses, i, _) = let past = [ ses ! i' | i' <- [i, i-1 .. fst (bounds ses)] ]
in fromMaybe "0" $ listToMaybe $ mapMaybe maybeLine past
lineRatio :: Play -> Float
lineRatio p@(_, ses, _, _) = let ls = S.lines (elems ses)
i = fromMaybe 0 $ elemIndex (curLine p) ls
in on (/) fromIntegral i (length ls)
clock :: Play -> Picture
clock p = let d = translate (-60) (-10) $ scale 0.3 0.3 $ color white $ text $ curLine p
a = color (greyN 0.2) $ rotate (-90) $ scale 1 (-1) $ thickArc 0 (lineRatio p * 360) 75 5
in pictures [d, a]
playPic :: (Int, Int) -> Play -> IO Picture
playPic (w, h) p = let (d, a) = optPos 200 175 $ length $ charPics p
pics = clock p : [ transArc d (i*a) pic | (i, pic) <- zip [0..] (charPics p) ]
in return $ scale ratio ratio $ pictures pics
where
ratio = fromIntegral (min w h) / 800
playEvent :: Event -> Play -> IO Play
playEvent (EventKey (SpecialKey KeyEsc) Down _ _) _ = exitSuccess
playEvent (EventKey (SpecialKey KeySpace) Down _ _) (Paused, ses, i, cf) = return (Resumed, ses, i, cf)
playEvent (EventKey (SpecialKey KeySpace) Down _ _) (Resumed, ses, i, cf) = return (Paused, ses, i, cf)
playEvent (EventKey (SpecialKey KeyLeft) Down _ _) (p, ses, i, cf) = return (p, ses, max (fst $ bounds ses) (i-50), cf)
playEvent (EventKey (SpecialKey KeyRight) Down _ _) (p, ses, i, cf) = return (p, ses, min (snd $ bounds ses) (i+50), cf)
playEvent _ p = return p
playStep :: Float -> Play -> IO Play
playStep t (Resumed, ses, i, cf) = let n = (Resumed, ses, (i+1), cf)
in case ses ! (i+1) of
Speech _ -> playStep t n
_ -> return n
playStep _ p = return p
replicateChanges :: Int -> [StageEvent] -> [StageEvent]
replicateChanges i [] = []
replicateChanges i (se:ses) = let r = replicateChanges i ses
in case se of
Entrance _ -> replicate i se ++ r
Exit _ -> replicate i se ++ r
_ -> se : r
animation :: FilePath -> Int -> Bool -> Line -> IO ()
animation f lps wu sl = let dis = FullScreen
bg = greyN 0.05
scf = if wu then hasName else const True
np = newPlay sl . replicateChanges 10 . selectCharacters scf . parse
in do res <- getScreenSize
source <- readFile f
playIO dis bg lps (np source) (playPic res) playEvent playStep
|
SU-LOSP/folgerhs
|
app/Folgerhs/Animate.hs
|
gpl-3.0
| 6,030
| 0
| 15
| 2,209
| 2,455
| 1,294
| 1,161
| 113
| 3
|
module Application.Game.Engine where
import Application.Game.Logic (eventHandler)
import Middleware.FreeGame.Environment (runEnvironment, EnvironmentInfo(..))
import View.Logic (runGameStep)
import View.View (drawState)
ticksPerSecond = 10
runEngine state = runEnvironment ticksPerSecond info
where info = EnvironmentInfo drawState runGameStep eventHandler state
|
EPashkin/gamenumber-freegame
|
src/Application/Game/Engine.hs
|
gpl-3.0
| 370
| 0
| 7
| 40
| 90
| 53
| 37
| 8
| 1
|
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE StandaloneDeriving #-}
module Tic.ImageCoord where
import Control.Lens(makeLenses)
import ClassyPrelude
data ImageCoord a = ImageCoord {
_imx :: a
, _imy :: a
} deriving(Functor)
deriving instance Eq a => Eq (ImageCoord a)
deriving instance Show a => Show (ImageCoord a)
$(makeLenses ''ImageCoord)
|
pmiddend/tic
|
lib/Tic/ImageCoord.hs
|
gpl-3.0
| 387
| 0
| 8
| 64
| 105
| 58
| 47
| 13
| 0
|
{-# LANGUAGE OverloadedStrings #-}
module Lamdu.GUI.ExpressionEdit.LambdaEdit
( make
) where
import qualified Control.Lens as Lens
import Control.Lens.Operators
import Control.MonadA (MonadA)
import qualified Graphics.UI.Bottle.Widget as Widget
import qualified Lamdu.GUI.ExpressionEdit.BinderEdit as BinderEdit
import Lamdu.GUI.ExpressionGui (ExpressionGui)
import qualified Lamdu.GUI.ExpressionGui as ExpressionGui
import Lamdu.GUI.ExpressionGui.Monad (ExprGuiM)
import qualified Lamdu.GUI.ExpressionGui.Monad as ExprGuiM
import qualified Lamdu.GUI.ExpressionGui.Types as ExprGuiT
import qualified Lamdu.GUI.WidgetIds as WidgetIds
import Lamdu.Sugar.Names.Types (Name(..))
import qualified Lamdu.Sugar.Types as Sugar
make ::
MonadA m =>
ExpressionGui.ParentPrecedence ->
Sugar.Binder (Name m) m (ExprGuiT.SugarExpr m) ->
Sugar.Payload m ExprGuiT.Payload ->
ExprGuiM m (ExpressionGui m)
make parentPrecedence binder pl =
ExpressionGui.stdWrapParenify plNoType parentPrecedence
(ExpressionGui.MyPrecedence (ExpressionGui.Precedence 20 0)) $ \myId ->
ExprGuiM.assignCursor myId bodyId $
do
BinderEdit.Parts mParamsEdit bodyEdit eventMap <-
BinderEdit.makeParts showParamType binder bodyId myId
let animId = Widget.toAnimId myId
labelEdits <-
case params of
Sugar.NullParam{} -> return []
_ -> ExpressionGui.grammarLabel "β" animId <&> (:[])
(mParamsEdit ^.. Lens._Just) ++ labelEdits ++ [bodyEdit]
& ExpressionGui.hboxSpaced
<&> ExpressionGui.egWidget %~ Widget.weakerEvents eventMap
where
params = binder ^. Sugar.bParams
body = binder ^. Sugar.bBody
-- We show the param type instead of the lambda type
showParamType = pl ^. Sugar.plData . ExprGuiT.plShowAnnotation
plNoType =
pl
& Sugar.plData . ExprGuiT.plShowAnnotation
.~ ExprGuiT.DoNotShowAnnotation
bodyId = WidgetIds.fromExprPayload $ body ^. Sugar.rPayload
|
rvion/lamdu
|
Lamdu/GUI/ExpressionEdit/LambdaEdit.hs
|
gpl-3.0
| 2,106
| 0
| 17
| 484
| 490
| 276
| 214
| -1
| -1
|
module Hinance.User.Data (
addtagged, canmerge, canxfer, patched,
planfrom, planto, planned, slices, tagged
) where
import Hinance.User.Tag
import Hinance.User.Type
import Hinance.Bank.Type
import Hinance.Shop.Type
import Hinance.Currency
blue = "#337AB7"
cyan = "#5BC0DE"
green = "#5CB85C"
grey = "#777"
red = "#D9534F"
white = "#FFF"
yellow = "#F0AD4E"
addtagged _ = [] :: [Tag]
canxfer _ _ = False
canmerge _ _ = False
slices = [
Slice {sname="Expenses", stags=[TagExpense], scategs=[
SliceCateg {scname="Tax", scbg=green, scfg=white,
sctags=[TagTax]},
SliceCateg {scname="Shipping", scbg=blue, scfg=white,
sctags=[TagShipping]},
SliceCateg {scname="Other", scbg=red, scfg=white,
sctags=[TagOther]}]},
Slice {sname="Income", stags=[TagIncome], scategs=[
SliceCateg {scname="Discounts", scbg=blue,scfg=white,sctags=[TagDiscount]},
SliceCateg {scname="Other", scbg=red, scfg=white, sctags=[TagOther]}]},
Slice {sname="Assets", stags=[TagAsset], scategs=[
SliceCateg {scname="Other", scbg=red, scfg=white,
sctags=[TagOther]}]},
Slice {sname="All", stags=[], scategs=[
SliceCateg {scname="Assets", scbg=green, scfg=white, sctags=[TagAsset]},
SliceCateg {scname="Income", scbg=blue, scfg=white, sctags=[TagIncome]},
SliceCateg {scname="Expenses",scbg=red,scfg=white,sctags=[TagExpense]}]}]
instance Taggable (Bank, BankAcc, BankTrans) where
tagged _ t
| t==TagAsset = True
| t==TagOther = True
| otherwise = False
instance Taggable (Shop, ShopOrder, String) where
tagged (_, _, l) t
| t==TagExpense = l=="shipping" || l=="tax"
| t==TagIncome = l=="discount"
| t==TagDiscount = l=="discount"
| t==TagShipping = l=="shipping"
| t==TagTax = l=="tax"
| otherwise = False
instance Taggable (Shop, ShopOrder, ShopPayment) where
tagged _ t
| t==TagAsset = True
| t==TagOther = True
| otherwise = False
instance Taggable (Shop, ShopOrder, ShopItem) where
tagged _ t
| t==TagExpense = True
| t==TagOther = True
| otherwise = False
instance Patchable Shop where
patched = id
instance Patchable Bank where
patched = id
planfrom = 0
planto = 0
planned = []
|
hinance/hinance
|
src/default/user_data.hs
|
gpl-3.0
| 2,213
| 0
| 11
| 413
| 887
| 520
| 367
| 66
| 1
|
module Language.Mulang.Generator (
boundDeclarations,
boundDeclarators,
declarators,
declarations,
declarationsOf,
declaredIdentifiers,
mainDeclaredIdentifiers,
equationBodies,
expressions,
referencedIdentifiers,
identifierReferences,
transitiveReferencedIdentifiers,
equationsExpressions,
statementsExpressions,
equationsExpandedExpressions,
Generator,
Declarator,
Expression(..)) where
import Language.Mulang.Ast
import Language.Mulang.Ast.Visitor
import Language.Mulang.Identifier
import Data.Maybe (mapMaybe)
import Data.List (nub)
type Generator a = Expression -> [a]
type Declarator = (Identifier, Expression)
-- | Returns all the declarations their identifiers -
-- | classes, methods, functions, records, local and global variables, and so on
-- |
-- | For example, in 'f x = g x where x = y', it returns '(f, f x = ...)' and '(x, x = y)'
declarators :: Generator Declarator
declarators (Sequence es) = concatMap declarators es
declarators e@(Attribute n _) = [(n, e)]
declarators e@(Class n _ b) = (n, e) : declarators b
declarators e@(Clause n _ es) = (n, e) : concatMap declarators es
declarators e@(Enumeration n _) = [(n, e)]
declarators e@(Interface n _ b) = (n, e) : declarators b
declarators e@(EntryPoint n b) = (n, e) : declarators b
declarators e@(Subroutine n b) = (n, e) : concatMap declarators (equationsExpressions b)
declarators e@(Object n b) = (n, e) : declarators b
declarators e@(Clause n _ _) = [(n, e)]
declarators e@(Record n) = [(n, e)]
declarators e@(TypeAlias n _) = [(n, e)]
declarators e@(TypeSignature n _) = [(n, e)]
declarators e@(LValue n _) = [(n, e)]
declarators (Other _ (Just e)) = declarators e
declarators _ = []
declarations :: Generator Expression
declarations = map snd . declarators
-- | Returns all declarations bound to the given identifier predicate
-- |
boundDeclarations :: IdentifierPredicate -> Generator Expression
boundDeclarations f = map snd . boundDeclarators f
-- | Returns all declarators bound to the given identifier predicate
-- |
boundDeclarators :: IdentifierPredicate -> Generator Declarator
boundDeclarators f = filter (f.fst) . declarators
-- | Returns the given expression and all its subexpressions
-- For example: in 'f x = x + 1', it returns 'f x = x + 1', 'x + 1', 'x' and '1'
expressions :: Generator Expression
expressions expr = expr : concatMap expressions (subExpressions expr)
where
subExpressions :: Generator Expression
--
subExpressions (Assert _ _) = [] -- FIXME
subExpressions (For stmts a) = statementsExpressions stmts ++ [a]
subExpressions (ForLoop i c p s) = [i, c, p, s]
subExpressions (Lambda _ e) = [e]
subExpressions (Match e eqs) = e : equationsExpressions eqs
subExpressions (Rule _ _ es) = es
subExpressions (Send e1 e2 es) = e1 : e2 : es
subExpressions (Switch e1 list e2) = e1 : concatMap (\(x,y) -> [x,y]) list ++ [e2]
subExpressions (Try t cs f) = t : map snd cs ++ [f]
--
subExpressions (ExpressionAndExpressionsList e es _) = e : es
subExpressions (SingleEquationsList eqs _) = equationsExpressions eqs
subExpressions (SingleExpression e _) = [e]
subExpressions (SingleExpressionsList es _) = es
subExpressions (SinglePatternsList _ _) = []
subExpressions (Terminal) = []
subExpressions (ThreeExpressions e1 e2 e3 _) = [e1, e2, e3]
subExpressions (TwoExpressions e1 e2 _) = [e1, e2]
-- | Returns all the referenced identifiers
-- For example, in 'f (x + 1)', it returns 'f' and 'x'
referencedIdentifiers :: Generator Identifier
referencedIdentifiers = nub . identifierReferences
identifierReferences :: Generator Identifier
identifierReferences = mapMaybe extractReference . expressions
-- | Returns all the identifiers transitively referenced by the given one
-- |
transitiveReferencedIdentifiers :: Identifier -> Generator Identifier
transitiveReferencedIdentifiers identifier code = expand (concatMap referencedIdentifiers . (`declarationsOf` code)) identifier
where
expand :: Eq a => (a-> [a]) -> a -> [a]
expand f x = expand' [] f [x]
expand' _ _ [] = []
expand' ps f (x:xs) | elem x ps = expand' ps f xs
| otherwise = [x] ++ expand' (x:ps) f (xs ++ f x)
-- | Returns all the declared identifiers
-- For example, in 'f x = g x where x = y', it returns 'f' and 'x'
declaredIdentifiers :: Generator Identifier
declaredIdentifiers = map fst . declarators
mainDeclaredIdentifiers :: Generator Identifier
mainDeclaredIdentifiers (Sequence _) = []
mainDeclaredIdentifiers expression = take 1 . declaredIdentifiers $ expression
-- | Returns all the body equations of functions, procedures and methods
equationBodies :: Generator EquationBody
equationBodies = concatMap bodiesOf . declarations
where
bodiesOf :: Generator EquationBody
bodiesOf (Subroutine _ equations) = equationBodies equations
bodiesOf _ = []
equationBodies = map (\(Equation _ body) -> body)
equationsExpandedExpressions :: [Equation] -> [Expression]
equationsExpandedExpressions = concatMap expand . equationsExpressions
where
expand (Sequence xs) = xs
expand other = [other]
declarationsOf :: Identifier -> Generator Expression
declarationsOf b = boundDeclarations (named b)
extractReference :: Expression -> Maybe Identifier
extractReference (Reference n) = Just n
extractReference (FieldReference _ n) = Just n
extractReference (Exist n _) = Just n
extractReference _ = Nothing
equationsExpressions :: [Equation] -> [Expression]
equationsExpressions = concatMap (\(Equation _ body) -> bodyExpressions body)
where
bodyExpressions (UnguardedBody e) = [e]
bodyExpressions (GuardedBody b) = b >>= \(es1, es2) -> [es1, es2]
statementsExpressions :: [Statement] -> [Expression]
statementsExpressions = map expression
where
expression (Generator _ e) = e
expression (Guard e) = e
|
mumuki/mulang
|
src/Language/Mulang/Generator.hs
|
gpl-3.0
| 6,368
| 0
| 12
| 1,550
| 1,836
| 983
| 853
| 110
| 17
|
{-# LANGUAGE BangPatterns, MultiParamTypeClasses, OverloadedStrings, TemplateHaskell, TypeFamilies, TypeOperators #-}
{- |
Module : Milkman.Context
License : GPL-3
Stability : experimental
Portability : unknown
Basic algorithms and utilities for formal contexts
-}
module Milkman.Context ( Concept
, Context ()
, Cross
, attributes
, augment
, clarify
, complement
, concepts
, crosses
, extent
, incidence
, intent
, mkContext
, objectAttributeConcepts
, objectConcept
, objects
, productContext
, reduce
, showAugmented
, showIncidence
, tightCrosses
) where
import Control.Applicative ((<$>))
import Control.Monad (when)
import Data.List ( (\\)
, intersect
, nub
, transpose
)
import Data.List.Split (chunksOf)
import Data.Text ( Text
, intercalate
)
import Data.Array.Repa ( Array
, computeUnboxedS
, fromListUnboxed
, toList
, U
)
import qualified Data.Array.Repa as R
import Data.Array.Repa.Index ( Z (Z)
, (:.) ((:.))
, DIM2
)
import Data.Array.Repa.Shape (listOfShape)
import Data.Map.Strict ( (!)
, assocs
, fromList
, keys
)
import qualified Data.Set as S
import Data.Vector.Unboxed.Base ()
import Data.Vector.Unboxed.Deriving (derivingUnbox)
import Milkman.Context.Context ( Attribute ( Attribute
, unAttribute
)
, Context (Context)
, Object ( Object
, unObject
)
, Names
, incident
)
-- |Construct a formal context, performing sanity checks
mkContext :: Monad m
=> [Text] -- ^ object names
-> [Text] -- ^ attribute names
-> [[Bool]] -- ^ incidence relation, in row-major order
-> m Context
mkContext objs atts rows = do
let nr = length rows
nc = nub $ map length rows
when (no == 0) $ fail "No objects."
when (na == 0) $ fail "No attributes."
when (no /= nr) $ fail "Number of objects does not match number of rows."
when (length nc /= 1) $ fail "Non-uniform number of columns."
when (any (na/=) nc) $ fail "Number of attributes does not match number of columns."
return $! Context g m i
where no = length objs
na = length atts
g = fromList $ zip [0..] objs
m = fromList $ zip [0..] atts
i = fromListUnboxed (Z :. no :. na :: DIM2) $ concat rows
-- |Objects of a formal context
objects :: Context -> [(Object, Text)]
objects (Context g _ _) = assocs g
-- |Attributes of a formal context
attributes :: Context -> [(Attribute, Text)]
attributes (Context _ m _) = assocs m
-- |Incidence relation of a formal context
incidence :: Context -> [Bool]
incidence (Context _ _ i) = toList i
-- |Compute the intent of an object, i.e. the set of all its
-- attributes
intent :: Context -> Object -> [Attribute]
intent c obj = intent' c [obj]
-- |Compute the intent of a set of objects, i.e. the set of all
-- attributes that belong to all the objects
intent' :: Context -> [Object] -> [Attribute]
intent' (Context _ m i) objs = [ att
| att <- keys m
, all (\obj -> incident i obj att) objs
]
-- |Compute the extent of an attribute, i.e. the set of all objects
-- having it
extent :: Context -> Attribute -> [Object]
extent c att = extent' c [att]
-- |Compute the extent of a set of attributes, i.e. the set of all
-- objects that have all the attributes
extent' :: Context -> [Attribute] -> [Object]
extent' (Context g _ i) atts = [ obj
| obj <- keys g
, all (incident i obj) atts
]
-- |Compute the complementary context, complementing the incidence
-- relation
complement :: Context -> Context
complement (Context g m i) = Context g m i'
where i' = computeUnboxedS $ R.map not i
-- |Aggregate names
clarify' :: (Enum a, Ord a, Num a)
=> (Int -> a) -- ^ object/attribute wrapper constructor
-> Names a -- ^ un-aggregated name map
-> [(Int, [Int])] -- ^ indices to be aggregated as another index
-> (Names a, [Int]) -- ^ aggregated names and removed indices
clarify' c n is = let ub = length is - 1
ps = [ (i, j)
| (i, ii) <- is
, (j, ij) <- is
, ii == ij
, i <= j
]
es = [ (i, map snd $ filter ((i==) . fst) ps)
| i <- [0..ub]
, i `notElem` [ j'
| (i', j') <- ps
, i' < i
]
]
e' = [ (i, intercalate "/" [ n ! c j
| j <- js
])
| (i, js) <- es
]
rs = [0..ub] \\ map fst e'
in (fromList $ zip [0..] $ map snd e', rs)
-- |Clarify a given context
clarify :: Context -> Context
clarify c@(Context g m i) =
let no = length $ keys g
na = length $ keys m
(g', ro) = clarify' Object g
[ (j, unAttribute <$> intent c (Object j))
| j <- [0..(no - 1)]
]
(m', ra) = clarify' Attribute m
[ (j, unObject <$> extent c (Attribute j))
| j <- [0..(na - 1)]
]
in Context g' m'
$! fromListUnboxed (Z :. length (keys g')
:. length (keys m')
:: DIM2)
[ e
| (j, e) <- zip [0..] $ toList i
, (j `div` na) `notElem` ro
, (j `mod` na) `notElem` ra
]
-- |Values for augmented contexts
data Arrows = UpArrow -- ^ upward arrow
| DownArrow -- ^ downward arrow
| UpDownArrow -- ^ double arrow
| Cross -- ^ cross
| Empty -- ^ nothing
deriving ( Enum
, Eq
, Ord
, Read
, Show
)
derivingUnbox "Arrows"
[t|Arrows -> Int|]
[|fromEnum|]
[|toEnum|]
-- |Incidence relation of an augmented context
type AugmentedIncidence = Array U DIM2 Arrows
-- |Augmented context
data AugmentedContext = AugmentedContext (Names Object)
(Names Attribute)
AugmentedIncidence
deriving (Show)
-- |Check whether a given object/attribute pair is incident in the
-- upward arrow relation
isUpArrow :: Context -> Object -> Attribute -> Bool
isUpArrow c@(Context _ _ i) g m
| incident i g m = False
| otherwise = let [na, _] = listOfShape $ R.extent i
in all (incident i g) [ n
| n <- Attribute <$> [0..(na - 1)]
, let m' = S.fromList $ extent c m
n' = S.fromList $ extent c n
in m' `S.isProperSubsetOf` n'
]
-- |Check whether a given object/attribute pair is incident in the
-- downward arrow relation
isDownArrow :: Context -> Object -> Attribute -> Bool
isDownArrow c@(Context _ _ i) g m
| incident i g m = False
| otherwise = let [_, no] = listOfShape $ R.extent i
in all (\o -> incident i o m) [ h
| h <- Object <$> [0..(no - 1)]
, let g' = S.fromList $ intent c g
h' = S.fromList $ intent c h
in g' `S.isProperSubsetOf` h'
]
-- |Augment a context by extending it with the arrow relations
augment :: Context -> AugmentedContext
augment c@(Context g m i) = AugmentedContext g m i'
where no = length $ keys g
na = length $ keys m
sh = Z :. no :. na :: DIM2
is = [ (Object j, Attribute k)
| j <- [0..(no - 1)]
, k <- [0..(na - 1)]
]
i' = fromListUnboxed sh $ zipWith aug is $ toList i
aug _ True = Cross
aug (j, k) False
| isUpArrow c j k && isDownArrow c j k = UpDownArrow
| isUpArrow c j k = UpArrow
| isDownArrow c j k = DownArrow
| otherwise = Empty
-- |Diminish an augmented context, dropping the arrows
diminish :: AugmentedContext -> Context
diminish (AugmentedContext g m i) = Context g m i'
where i' = computeUnboxedS $ R.map (==Cross) i
-- |Reduce (and clarify) a given formal context
reduce :: Context -> Context
reduce c = let AugmentedContext g m i = augment . clarify $ c
[na, no] = listOfShape $ R.extent i
rs = chunksOf no $ toList i
ro = filt rs
ra = filt $ transpose rs
g' = fromList $ zip [0..] [ g ! j
| j <- keys g
, j `notElem` ro
]
m' = fromList $ zip [0..] [ m ! j
| j <- keys m
, j `notElem` ra
]
i' = fromListUnboxed (Z :. length (keys g')
:. length (keys m')
:: DIM2)
[ e
| (j, e) <- zip [0..] $ toList i
, (j `div` na) `notElem` (unObject <$> ro)
, (j `mod` na) `notElem` (unAttribute <$> ra)
]
in diminish $! AugmentedContext g' m' i'
where filt l = map fst $ filter (notElem UpDownArrow . snd) $ zip [0..] l
-- |Cross in a formal context
type Cross = (Object, Attribute)
-- |formal concept
type Concept = ([Object], [Attribute])
-- |Compute the object concept induced by an object
objectConcept :: Context -> Object -> Concept
objectConcept c g = (g'', g')
where g' = intent c g
g'' = extent' c g'
-- |Compute the attribute concept induced by an attribute
attributeConcept :: Context -> Attribute -> Concept
attributeConcept c m = (m', m'')
where m' = extent c m
m'' = intent' c m'
-- |Compute the set of concepts that are both object concepts and
-- attribute concepts
objectAttributeConcepts :: Context -> [Concept]
objectAttributeConcepts c@(Context g m _) = ocs `intersect` acs
where ocs = map (objectConcept c) $ keys g
acs = map (attributeConcept c) $ keys m
-- |Compute the tight crosses (the double arrows of the complementary
-- context) of a given formal context
tightCrosses :: Context -> Context
tightCrosses c@(Context g m _) = Context g m i'
where (AugmentedContext _ _ i) = augment . complement $ c
i' = computeUnboxedS . R.map (==UpDownArrow) $ i
-- |Pretty-print the incidence relation of an augmented context
showAugmented :: AugmentedContext -> String
showAugmented (AugmentedContext g m i) = unlines [ concatMap (showI o)
$ unAttribute <$> keys m
| o <- unObject <$> keys g
]
where showI o a = case i R.! (Z :. o :. a :: DIM2) of
UpArrow -> "β"
DownArrow -> "β"
UpDownArrow -> "β€’"
Cross -> "β"
Empty -> "β
"
-- |Pretty-print the incidence relation of a formal context
showIncidence :: Context -> String
showIncidence (Context g m i) = unlines [ concatMap (showI o) $ keys m
| o <- keys g
]
where showI o a
| incident i o a = "β"
| otherwise = "β
"
-- |Compute the concepts of a formal context
concepts :: Context -> [Concept]
concepts c@(Context g m _) = go (keys m) [keys g]
where go (a:as) !exts = go as $ nub $ exts ++ [ let a' = extent c a
in e `intersect` a'
| e <- exts
]
go [] exts = map conceptify exts
where conceptify ext = (ext, intent' c ext)
-- |Compute the context product of two contexts
productContext :: Monad m => Context -> Context -> m Context
productContext gf@(Context _ _ igf) fm@(Context _ _ ifm) = do
let (objs, g) = unzip . objects $ gf
f = fst <$> attributes gf
f' = fst <$> objects fm
(attrs, m) = unzip . attributes $ fm
nf = length f
when ((unAttribute <$> f) /= (unObject <$> f')) $ fail "Factors differ."
let i = [ [ any (\factor -> incident igf obj (Attribute factor)
&& incident ifm (Object factor) attr)
[0 .. nf - 1]
| attr <- attrs
]
| obj <- objs
]
mkContext g m i
-- |Compute the indexes of all the crosses of a given context
crosses :: Context -> [(Object, Attribute)]
crosses (Context g m i) = [ (o, a)
| o <- keys g
, a <- keys m
, incident i o a
]
|
mmarx/milkman
|
src/Milkman/Context.hs
|
gpl-3.0
| 14,777
| 0
| 18
| 6,731
| 3,837
| 2,059
| 1,778
| 273
| 5
|
module RayMarch.Run where
import Data.Maybe
import Control.Monad.Trans.State
import Codec.Picture hiding (Pixel)
import RayMarch.Types
import RayMarch.March
import RayMarch.Quaternion
import Debug.Trace (trace)
runMarcher :: Config -> World s -> IO ()
runMarcher cfg wld = savePngImage (fileName cfg) $ ImageRGB8 img where
world = wld {viewPoint = position $ view cfg}
w = width cfg
h = w * ratio (view cfg)
rt = 0.5*h/w
img = flip ((flip generateImage) (floor w)) (floor h) $ \x y ->let
px = (fromIntegral x/w-0.5,-(fromIntegral y/w-rt))
Color (r,g,b) = fst $ runState (getColor cfg px) $ world
toP8 t = fromIntegral $ max 0 $ min 255 $ floor $ t*256
in PixelRGB8 (toP8 r) (toP8 g) (toP8 b)
getColor :: Config -> Pixel -> March s Color
getColor cfg px@(x,y) = do
w <- get
let vw = view cfg
l = lens vw
p = position vw
v = norm $ flip apply (l px) $ direction vw
cu <- (if abs x < 0.001 then trace (show (100-(y*4/3+0.5)*100) ++ "%") else id) $ advance Nothing p v
return $ effector w p cfg px cu
|
phi16/RayMarch
|
RayMarch/Run.hs
|
gpl-3.0
| 1,060
| 0
| 21
| 246
| 539
| 275
| 264
| 28
| 2
|
{-# 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.Analytics.Types.Product
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
module Network.Google.Analytics.Types.Product where
import Network.Google.Analytics.Types.Sum
import Network.Google.Prelude
-- | JSON template for a user deletion request resource.
--
-- /See:/ 'userDeletionRequest' smart constructor.
data UserDeletionRequest =
UserDeletionRequest'
{ _udrWebPropertyId :: !(Maybe Text)
, _udrKind :: !Text
, _udrPropertyId :: !(Maybe Text)
, _udrId :: !(Maybe UserDeletionRequestId)
, _udrFirebaseProjectId :: !(Maybe Text)
, _udrDeletionRequestTime :: !(Maybe DateTime')
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'UserDeletionRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'udrWebPropertyId'
--
-- * 'udrKind'
--
-- * 'udrPropertyId'
--
-- * 'udrId'
--
-- * 'udrFirebaseProjectId'
--
-- * 'udrDeletionRequestTime'
userDeletionRequest
:: UserDeletionRequest
userDeletionRequest =
UserDeletionRequest'
{ _udrWebPropertyId = Nothing
, _udrKind = "analytics#userDeletionRequest"
, _udrPropertyId = Nothing
, _udrId = Nothing
, _udrFirebaseProjectId = Nothing
, _udrDeletionRequestTime = Nothing
}
-- | Web property ID of the form UA-XXXXX-YY.
udrWebPropertyId :: Lens' UserDeletionRequest (Maybe Text)
udrWebPropertyId
= lens _udrWebPropertyId
(\ s a -> s{_udrWebPropertyId = a})
-- | Value is \"analytics#userDeletionRequest\".
udrKind :: Lens' UserDeletionRequest Text
udrKind = lens _udrKind (\ s a -> s{_udrKind = a})
-- | Property ID
udrPropertyId :: Lens' UserDeletionRequest (Maybe Text)
udrPropertyId
= lens _udrPropertyId
(\ s a -> s{_udrPropertyId = a})
-- | User ID.
udrId :: Lens' UserDeletionRequest (Maybe UserDeletionRequestId)
udrId = lens _udrId (\ s a -> s{_udrId = a})
-- | Firebase Project Id
udrFirebaseProjectId :: Lens' UserDeletionRequest (Maybe Text)
udrFirebaseProjectId
= lens _udrFirebaseProjectId
(\ s a -> s{_udrFirebaseProjectId = a})
-- | This marks the point in time for which all user data before should be
-- deleted
udrDeletionRequestTime :: Lens' UserDeletionRequest (Maybe UTCTime)
udrDeletionRequestTime
= lens _udrDeletionRequestTime
(\ s a -> s{_udrDeletionRequestTime = a})
. mapping _DateTime
instance FromJSON UserDeletionRequest where
parseJSON
= withObject "UserDeletionRequest"
(\ o ->
UserDeletionRequest' <$>
(o .:? "webPropertyId") <*>
(o .:? "kind" .!= "analytics#userDeletionRequest")
<*> (o .:? "propertyId")
<*> (o .:? "id")
<*> (o .:? "firebaseProjectId")
<*> (o .:? "deletionRequestTime"))
instance ToJSON UserDeletionRequest where
toJSON UserDeletionRequest'{..}
= object
(catMaybes
[("webPropertyId" .=) <$> _udrWebPropertyId,
Just ("kind" .= _udrKind),
("propertyId" .=) <$> _udrPropertyId,
("id" .=) <$> _udrId,
("firebaseProjectId" .=) <$> _udrFirebaseProjectId,
("deletionRequestTime" .=) <$>
_udrDeletionRequestTime])
-- | An unsampled report collection lists Analytics unsampled reports to
-- which the user has access. Each view (profile) can have a set of
-- unsampled reports. Each resource in the unsampled report collection
-- corresponds to a single Analytics unsampled report.
--
-- /See:/ 'unSampledReports' smart constructor.
data UnSampledReports =
UnSampledReports'
{ _usrNextLink :: !(Maybe Text)
, _usrItemsPerPage :: !(Maybe (Textual Int32))
, _usrKind :: !Text
, _usrUsername :: !(Maybe Text)
, _usrItems :: !(Maybe [UnSampledReport])
, _usrTotalResults :: !(Maybe (Textual Int32))
, _usrStartIndex :: !(Maybe (Textual Int32))
, _usrPreviousLink :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'UnSampledReports' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'usrNextLink'
--
-- * 'usrItemsPerPage'
--
-- * 'usrKind'
--
-- * 'usrUsername'
--
-- * 'usrItems'
--
-- * 'usrTotalResults'
--
-- * 'usrStartIndex'
--
-- * 'usrPreviousLink'
unSampledReports
:: UnSampledReports
unSampledReports =
UnSampledReports'
{ _usrNextLink = Nothing
, _usrItemsPerPage = Nothing
, _usrKind = "analytics#unsampledReports"
, _usrUsername = Nothing
, _usrItems = Nothing
, _usrTotalResults = Nothing
, _usrStartIndex = Nothing
, _usrPreviousLink = Nothing
}
-- | Link to next page for this unsampled report collection.
usrNextLink :: Lens' UnSampledReports (Maybe Text)
usrNextLink
= lens _usrNextLink (\ s a -> s{_usrNextLink = a})
-- | The maximum number of resources the response can contain, regardless of
-- the actual number of resources returned. Its value ranges from 1 to 1000
-- with a value of 1000 by default, or otherwise specified by the
-- max-results query parameter.
usrItemsPerPage :: Lens' UnSampledReports (Maybe Int32)
usrItemsPerPage
= lens _usrItemsPerPage
(\ s a -> s{_usrItemsPerPage = a})
. mapping _Coerce
-- | Collection type.
usrKind :: Lens' UnSampledReports Text
usrKind = lens _usrKind (\ s a -> s{_usrKind = a})
-- | Email ID of the authenticated user
usrUsername :: Lens' UnSampledReports (Maybe Text)
usrUsername
= lens _usrUsername (\ s a -> s{_usrUsername = a})
-- | A list of unsampled reports.
usrItems :: Lens' UnSampledReports [UnSampledReport]
usrItems
= lens _usrItems (\ s a -> s{_usrItems = a}) .
_Default
. _Coerce
-- | The total number of results for the query, regardless of the number of
-- resources in the result.
usrTotalResults :: Lens' UnSampledReports (Maybe Int32)
usrTotalResults
= lens _usrTotalResults
(\ s a -> s{_usrTotalResults = a})
. mapping _Coerce
-- | The starting index of the resources, which is 1 by default or otherwise
-- specified by the start-index query parameter.
usrStartIndex :: Lens' UnSampledReports (Maybe Int32)
usrStartIndex
= lens _usrStartIndex
(\ s a -> s{_usrStartIndex = a})
. mapping _Coerce
-- | Link to previous page for this unsampled report collection.
usrPreviousLink :: Lens' UnSampledReports (Maybe Text)
usrPreviousLink
= lens _usrPreviousLink
(\ s a -> s{_usrPreviousLink = a})
instance FromJSON UnSampledReports where
parseJSON
= withObject "UnSampledReports"
(\ o ->
UnSampledReports' <$>
(o .:? "nextLink") <*> (o .:? "itemsPerPage") <*>
(o .:? "kind" .!= "analytics#unsampledReports")
<*> (o .:? "username")
<*> (o .:? "items" .!= mempty)
<*> (o .:? "totalResults")
<*> (o .:? "startIndex")
<*> (o .:? "previousLink"))
instance ToJSON UnSampledReports where
toJSON UnSampledReports'{..}
= object
(catMaybes
[("nextLink" .=) <$> _usrNextLink,
("itemsPerPage" .=) <$> _usrItemsPerPage,
Just ("kind" .= _usrKind),
("username" .=) <$> _usrUsername,
("items" .=) <$> _usrItems,
("totalResults" .=) <$> _usrTotalResults,
("startIndex" .=) <$> _usrStartIndex,
("previousLink" .=) <$> _usrPreviousLink])
--
-- /See:/ 'goalURLDestinationDetailsStepsItem' smart constructor.
data GoalURLDestinationDetailsStepsItem =
GoalURLDestinationDetailsStepsItem'
{ _guddsiURL :: !(Maybe Text)
, _guddsiName :: !(Maybe Text)
, _guddsiNumber :: !(Maybe (Textual Int32))
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'GoalURLDestinationDetailsStepsItem' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'guddsiURL'
--
-- * 'guddsiName'
--
-- * 'guddsiNumber'
goalURLDestinationDetailsStepsItem
:: GoalURLDestinationDetailsStepsItem
goalURLDestinationDetailsStepsItem =
GoalURLDestinationDetailsStepsItem'
{_guddsiURL = Nothing, _guddsiName = Nothing, _guddsiNumber = Nothing}
-- | URL for this step.
guddsiURL :: Lens' GoalURLDestinationDetailsStepsItem (Maybe Text)
guddsiURL
= lens _guddsiURL (\ s a -> s{_guddsiURL = a})
-- | Step name.
guddsiName :: Lens' GoalURLDestinationDetailsStepsItem (Maybe Text)
guddsiName
= lens _guddsiName (\ s a -> s{_guddsiName = a})
-- | Step number.
guddsiNumber :: Lens' GoalURLDestinationDetailsStepsItem (Maybe Int32)
guddsiNumber
= lens _guddsiNumber (\ s a -> s{_guddsiNumber = a})
. mapping _Coerce
instance FromJSON GoalURLDestinationDetailsStepsItem
where
parseJSON
= withObject "GoalURLDestinationDetailsStepsItem"
(\ o ->
GoalURLDestinationDetailsStepsItem' <$>
(o .:? "url") <*> (o .:? "name") <*>
(o .:? "number"))
instance ToJSON GoalURLDestinationDetailsStepsItem
where
toJSON GoalURLDestinationDetailsStepsItem'{..}
= object
(catMaybes
[("url" .=) <$> _guddsiURL,
("name" .=) <$> _guddsiName,
("number" .=) <$> _guddsiNumber])
-- | Analytics data request query parameters.
--
-- /See:/ 'gaDataQuery' smart constructor.
data GaDataQuery =
GaDataQuery'
{ _gdqMetrics :: !(Maybe [Text])
, _gdqSamplingLevel :: !(Maybe Text)
, _gdqFilters :: !(Maybe Text)
, _gdqIds :: !(Maybe Text)
, _gdqEndDate :: !(Maybe Text)
, _gdqSort :: !(Maybe [Text])
, _gdqDimensions :: !(Maybe Text)
, _gdqStartIndex :: !(Maybe (Textual Int32))
, _gdqMaxResults :: !(Maybe (Textual Int32))
, _gdqSegment :: !(Maybe Text)
, _gdqStartDate :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'GaDataQuery' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gdqMetrics'
--
-- * 'gdqSamplingLevel'
--
-- * 'gdqFilters'
--
-- * 'gdqIds'
--
-- * 'gdqEndDate'
--
-- * 'gdqSort'
--
-- * 'gdqDimensions'
--
-- * 'gdqStartIndex'
--
-- * 'gdqMaxResults'
--
-- * 'gdqSegment'
--
-- * 'gdqStartDate'
gaDataQuery
:: GaDataQuery
gaDataQuery =
GaDataQuery'
{ _gdqMetrics = Nothing
, _gdqSamplingLevel = Nothing
, _gdqFilters = Nothing
, _gdqIds = Nothing
, _gdqEndDate = Nothing
, _gdqSort = Nothing
, _gdqDimensions = Nothing
, _gdqStartIndex = Nothing
, _gdqMaxResults = Nothing
, _gdqSegment = Nothing
, _gdqStartDate = Nothing
}
-- | List of analytics metrics.
gdqMetrics :: Lens' GaDataQuery [Text]
gdqMetrics
= lens _gdqMetrics (\ s a -> s{_gdqMetrics = a}) .
_Default
. _Coerce
-- | Desired sampling level
gdqSamplingLevel :: Lens' GaDataQuery (Maybe Text)
gdqSamplingLevel
= lens _gdqSamplingLevel
(\ s a -> s{_gdqSamplingLevel = a})
-- | Comma-separated list of dimension or metric filters.
gdqFilters :: Lens' GaDataQuery (Maybe Text)
gdqFilters
= lens _gdqFilters (\ s a -> s{_gdqFilters = a})
-- | Unique table ID.
gdqIds :: Lens' GaDataQuery (Maybe Text)
gdqIds = lens _gdqIds (\ s a -> s{_gdqIds = a})
-- | End date.
gdqEndDate :: Lens' GaDataQuery (Maybe Text)
gdqEndDate
= lens _gdqEndDate (\ s a -> s{_gdqEndDate = a})
-- | List of dimensions or metrics based on which Analytics data is sorted.
gdqSort :: Lens' GaDataQuery [Text]
gdqSort
= lens _gdqSort (\ s a -> s{_gdqSort = a}) . _Default
. _Coerce
-- | List of analytics dimensions.
gdqDimensions :: Lens' GaDataQuery (Maybe Text)
gdqDimensions
= lens _gdqDimensions
(\ s a -> s{_gdqDimensions = a})
-- | Start index.
gdqStartIndex :: Lens' GaDataQuery (Maybe Int32)
gdqStartIndex
= lens _gdqStartIndex
(\ s a -> s{_gdqStartIndex = a})
. mapping _Coerce
-- | Maximum results per page.
gdqMaxResults :: Lens' GaDataQuery (Maybe Int32)
gdqMaxResults
= lens _gdqMaxResults
(\ s a -> s{_gdqMaxResults = a})
. mapping _Coerce
-- | Analytics advanced segment.
gdqSegment :: Lens' GaDataQuery (Maybe Text)
gdqSegment
= lens _gdqSegment (\ s a -> s{_gdqSegment = a})
-- | Start date.
gdqStartDate :: Lens' GaDataQuery (Maybe Text)
gdqStartDate
= lens _gdqStartDate (\ s a -> s{_gdqStartDate = a})
instance FromJSON GaDataQuery where
parseJSON
= withObject "GaDataQuery"
(\ o ->
GaDataQuery' <$>
(o .:? "metrics" .!= mempty) <*>
(o .:? "samplingLevel")
<*> (o .:? "filters")
<*> (o .:? "ids")
<*> (o .:? "end-date")
<*> (o .:? "sort" .!= mempty)
<*> (o .:? "dimensions")
<*> (o .:? "start-index")
<*> (o .:? "max-results")
<*> (o .:? "segment")
<*> (o .:? "start-date"))
instance ToJSON GaDataQuery where
toJSON GaDataQuery'{..}
= object
(catMaybes
[("metrics" .=) <$> _gdqMetrics,
("samplingLevel" .=) <$> _gdqSamplingLevel,
("filters" .=) <$> _gdqFilters,
("ids" .=) <$> _gdqIds,
("end-date" .=) <$> _gdqEndDate,
("sort" .=) <$> _gdqSort,
("dimensions" .=) <$> _gdqDimensions,
("start-index" .=) <$> _gdqStartIndex,
("max-results" .=) <$> _gdqMaxResults,
("segment" .=) <$> _gdqSegment,
("start-date" .=) <$> _gdqStartDate])
-- | A remarketing audience collection lists Analytics remarketing audiences
-- to which the user has access. Each resource in the collection
-- corresponds to a single Analytics remarketing audience.
--
-- /See:/ 'remarketingAudiences' smart constructor.
data RemarketingAudiences =
RemarketingAudiences'
{ _raNextLink :: !(Maybe Text)
, _raItemsPerPage :: !(Maybe (Textual Int32))
, _raKind :: !Text
, _raUsername :: !(Maybe Text)
, _raItems :: !(Maybe [RemarketingAudience])
, _raTotalResults :: !(Maybe (Textual Int32))
, _raStartIndex :: !(Maybe (Textual Int32))
, _raPreviousLink :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'RemarketingAudiences' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'raNextLink'
--
-- * 'raItemsPerPage'
--
-- * 'raKind'
--
-- * 'raUsername'
--
-- * 'raItems'
--
-- * 'raTotalResults'
--
-- * 'raStartIndex'
--
-- * 'raPreviousLink'
remarketingAudiences
:: RemarketingAudiences
remarketingAudiences =
RemarketingAudiences'
{ _raNextLink = Nothing
, _raItemsPerPage = Nothing
, _raKind = "analytics#remarketingAudiences"
, _raUsername = Nothing
, _raItems = Nothing
, _raTotalResults = Nothing
, _raStartIndex = Nothing
, _raPreviousLink = Nothing
}
-- | Link to next page for this remarketing audience collection.
raNextLink :: Lens' RemarketingAudiences (Maybe Text)
raNextLink
= lens _raNextLink (\ s a -> s{_raNextLink = a})
-- | The maximum number of resources the response can contain, regardless of
-- the actual number of resources returned. Its value ranges from 1 to 1000
-- with a value of 1000 by default, or otherwise specified by the
-- max-results query parameter.
raItemsPerPage :: Lens' RemarketingAudiences (Maybe Int32)
raItemsPerPage
= lens _raItemsPerPage
(\ s a -> s{_raItemsPerPage = a})
. mapping _Coerce
-- | Collection type.
raKind :: Lens' RemarketingAudiences Text
raKind = lens _raKind (\ s a -> s{_raKind = a})
-- | Email ID of the authenticated user
raUsername :: Lens' RemarketingAudiences (Maybe Text)
raUsername
= lens _raUsername (\ s a -> s{_raUsername = a})
-- | A list of remarketing audiences.
raItems :: Lens' RemarketingAudiences [RemarketingAudience]
raItems
= lens _raItems (\ s a -> s{_raItems = a}) . _Default
. _Coerce
-- | The total number of results for the query, regardless of the number of
-- results in the response.
raTotalResults :: Lens' RemarketingAudiences (Maybe Int32)
raTotalResults
= lens _raTotalResults
(\ s a -> s{_raTotalResults = a})
. mapping _Coerce
-- | The starting index of the resources, which is 1 by default or otherwise
-- specified by the start-index query parameter.
raStartIndex :: Lens' RemarketingAudiences (Maybe Int32)
raStartIndex
= lens _raStartIndex (\ s a -> s{_raStartIndex = a})
. mapping _Coerce
-- | Link to previous page for this view (profile) collection.
raPreviousLink :: Lens' RemarketingAudiences (Maybe Text)
raPreviousLink
= lens _raPreviousLink
(\ s a -> s{_raPreviousLink = a})
instance FromJSON RemarketingAudiences where
parseJSON
= withObject "RemarketingAudiences"
(\ o ->
RemarketingAudiences' <$>
(o .:? "nextLink") <*> (o .:? "itemsPerPage") <*>
(o .:? "kind" .!= "analytics#remarketingAudiences")
<*> (o .:? "username")
<*> (o .:? "items" .!= mempty)
<*> (o .:? "totalResults")
<*> (o .:? "startIndex")
<*> (o .:? "previousLink"))
instance ToJSON RemarketingAudiences where
toJSON RemarketingAudiences'{..}
= object
(catMaybes
[("nextLink" .=) <$> _raNextLink,
("itemsPerPage" .=) <$> _raItemsPerPage,
Just ("kind" .= _raKind),
("username" .=) <$> _raUsername,
("items" .=) <$> _raItems,
("totalResults" .=) <$> _raTotalResults,
("startIndex" .=) <$> _raStartIndex,
("previousLink" .=) <$> _raPreviousLink])
--
-- /See:/ 'gaDataDataTableRowsItem' smart constructor.
newtype GaDataDataTableRowsItem =
GaDataDataTableRowsItem'
{ _gddtriC :: Maybe [GaDataDataTableRowsItemCItem]
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'GaDataDataTableRowsItem' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gddtriC'
gaDataDataTableRowsItem
:: GaDataDataTableRowsItem
gaDataDataTableRowsItem = GaDataDataTableRowsItem' {_gddtriC = Nothing}
gddtriC :: Lens' GaDataDataTableRowsItem [GaDataDataTableRowsItemCItem]
gddtriC
= lens _gddtriC (\ s a -> s{_gddtriC = a}) . _Default
. _Coerce
instance FromJSON GaDataDataTableRowsItem where
parseJSON
= withObject "GaDataDataTableRowsItem"
(\ o ->
GaDataDataTableRowsItem' <$> (o .:? "c" .!= mempty))
instance ToJSON GaDataDataTableRowsItem where
toJSON GaDataDataTableRowsItem'{..}
= object (catMaybes [("c" .=) <$> _gddtriC])
-- | JSON template for Analytics unsampled report resource.
--
-- /See:/ 'unSampledReport' smart constructor.
data UnSampledReport =
UnSampledReport'
{ _uDownloadType :: !(Maybe Text)
, _uStatus :: !(Maybe Text)
, _uMetrics :: !(Maybe Text)
, _uDriveDownloadDetails :: !(Maybe UnSampledReportDriveDownloadDetails)
, _uWebPropertyId :: !(Maybe Text)
, _uKind :: !Text
, _uCreated :: !(Maybe DateTime')
, _uFilters :: !(Maybe Text)
, _uProFileId :: !(Maybe Text)
, _uEndDate :: !(Maybe Text)
, _uSelfLink :: !(Maybe Text)
, _uAccountId :: !(Maybe Text)
, _uId :: !(Maybe Text)
, _uUpdated :: !(Maybe DateTime')
, _uTitle :: !(Maybe Text)
, _uDimensions :: !(Maybe Text)
, _uSegment :: !(Maybe Text)
, _uCloudStorageDownloadDetails :: !(Maybe UnSampledReportCloudStorageDownloadDetails)
, _uStartDate :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'UnSampledReport' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'uDownloadType'
--
-- * 'uStatus'
--
-- * 'uMetrics'
--
-- * 'uDriveDownloadDetails'
--
-- * 'uWebPropertyId'
--
-- * 'uKind'
--
-- * 'uCreated'
--
-- * 'uFilters'
--
-- * 'uProFileId'
--
-- * 'uEndDate'
--
-- * 'uSelfLink'
--
-- * 'uAccountId'
--
-- * 'uId'
--
-- * 'uUpdated'
--
-- * 'uTitle'
--
-- * 'uDimensions'
--
-- * 'uSegment'
--
-- * 'uCloudStorageDownloadDetails'
--
-- * 'uStartDate'
unSampledReport
:: UnSampledReport
unSampledReport =
UnSampledReport'
{ _uDownloadType = Nothing
, _uStatus = Nothing
, _uMetrics = Nothing
, _uDriveDownloadDetails = Nothing
, _uWebPropertyId = Nothing
, _uKind = "analytics#unsampledReport"
, _uCreated = Nothing
, _uFilters = Nothing
, _uProFileId = Nothing
, _uEndDate = Nothing
, _uSelfLink = Nothing
, _uAccountId = Nothing
, _uId = Nothing
, _uUpdated = Nothing
, _uTitle = Nothing
, _uDimensions = Nothing
, _uSegment = Nothing
, _uCloudStorageDownloadDetails = Nothing
, _uStartDate = Nothing
}
-- | The type of download you need to use for the report data file. Possible
-- values include \`GOOGLE_DRIVE\` and \`GOOGLE_CLOUD_STORAGE\`. If the
-- value is \`GOOGLE_DRIVE\`, see the \`driveDownloadDetails\` field. If
-- the value is \`GOOGLE_CLOUD_STORAGE\`, see the
-- \`cloudStorageDownloadDetails\` field.
uDownloadType :: Lens' UnSampledReport (Maybe Text)
uDownloadType
= lens _uDownloadType
(\ s a -> s{_uDownloadType = a})
-- | Status of this unsampled report. Possible values are PENDING, COMPLETED,
-- or FAILED.
uStatus :: Lens' UnSampledReport (Maybe Text)
uStatus = lens _uStatus (\ s a -> s{_uStatus = a})
-- | The metrics for the unsampled report.
uMetrics :: Lens' UnSampledReport (Maybe Text)
uMetrics = lens _uMetrics (\ s a -> s{_uMetrics = a})
-- | Download details for a file stored in Google Drive.
uDriveDownloadDetails :: Lens' UnSampledReport (Maybe UnSampledReportDriveDownloadDetails)
uDriveDownloadDetails
= lens _uDriveDownloadDetails
(\ s a -> s{_uDriveDownloadDetails = a})
-- | Web property ID to which this unsampled report belongs. The web property
-- ID is of the form UA-XXXXX-YY.
uWebPropertyId :: Lens' UnSampledReport (Maybe Text)
uWebPropertyId
= lens _uWebPropertyId
(\ s a -> s{_uWebPropertyId = a})
-- | Resource type for an Analytics unsampled report.
uKind :: Lens' UnSampledReport Text
uKind = lens _uKind (\ s a -> s{_uKind = a})
-- | Time this unsampled report was created.
uCreated :: Lens' UnSampledReport (Maybe UTCTime)
uCreated
= lens _uCreated (\ s a -> s{_uCreated = a}) .
mapping _DateTime
-- | The filters for the unsampled report.
uFilters :: Lens' UnSampledReport (Maybe Text)
uFilters = lens _uFilters (\ s a -> s{_uFilters = a})
-- | View (Profile) ID to which this unsampled report belongs.
uProFileId :: Lens' UnSampledReport (Maybe Text)
uProFileId
= lens _uProFileId (\ s a -> s{_uProFileId = a})
-- | The end date for the unsampled report.
uEndDate :: Lens' UnSampledReport (Maybe Text)
uEndDate = lens _uEndDate (\ s a -> s{_uEndDate = a})
-- | Link for this unsampled report.
uSelfLink :: Lens' UnSampledReport (Maybe Text)
uSelfLink
= lens _uSelfLink (\ s a -> s{_uSelfLink = a})
-- | Account ID to which this unsampled report belongs.
uAccountId :: Lens' UnSampledReport (Maybe Text)
uAccountId
= lens _uAccountId (\ s a -> s{_uAccountId = a})
-- | Unsampled report ID.
uId :: Lens' UnSampledReport (Maybe Text)
uId = lens _uId (\ s a -> s{_uId = a})
-- | Time this unsampled report was last modified.
uUpdated :: Lens' UnSampledReport (Maybe UTCTime)
uUpdated
= lens _uUpdated (\ s a -> s{_uUpdated = a}) .
mapping _DateTime
-- | Title of the unsampled report.
uTitle :: Lens' UnSampledReport (Maybe Text)
uTitle = lens _uTitle (\ s a -> s{_uTitle = a})
-- | The dimensions for the unsampled report.
uDimensions :: Lens' UnSampledReport (Maybe Text)
uDimensions
= lens _uDimensions (\ s a -> s{_uDimensions = a})
-- | The segment for the unsampled report.
uSegment :: Lens' UnSampledReport (Maybe Text)
uSegment = lens _uSegment (\ s a -> s{_uSegment = a})
-- | Download details for a file stored in Google Cloud Storage.
uCloudStorageDownloadDetails :: Lens' UnSampledReport (Maybe UnSampledReportCloudStorageDownloadDetails)
uCloudStorageDownloadDetails
= lens _uCloudStorageDownloadDetails
(\ s a -> s{_uCloudStorageDownloadDetails = a})
-- | The start date for the unsampled report.
uStartDate :: Lens' UnSampledReport (Maybe Text)
uStartDate
= lens _uStartDate (\ s a -> s{_uStartDate = a})
instance FromJSON UnSampledReport where
parseJSON
= withObject "UnSampledReport"
(\ o ->
UnSampledReport' <$>
(o .:? "downloadType") <*> (o .:? "status") <*>
(o .:? "metrics")
<*> (o .:? "driveDownloadDetails")
<*> (o .:? "webPropertyId")
<*> (o .:? "kind" .!= "analytics#unsampledReport")
<*> (o .:? "created")
<*> (o .:? "filters")
<*> (o .:? "profileId")
<*> (o .:? "end-date")
<*> (o .:? "selfLink")
<*> (o .:? "accountId")
<*> (o .:? "id")
<*> (o .:? "updated")
<*> (o .:? "title")
<*> (o .:? "dimensions")
<*> (o .:? "segment")
<*> (o .:? "cloudStorageDownloadDetails")
<*> (o .:? "start-date"))
instance ToJSON UnSampledReport where
toJSON UnSampledReport'{..}
= object
(catMaybes
[("downloadType" .=) <$> _uDownloadType,
("status" .=) <$> _uStatus,
("metrics" .=) <$> _uMetrics,
("driveDownloadDetails" .=) <$>
_uDriveDownloadDetails,
("webPropertyId" .=) <$> _uWebPropertyId,
Just ("kind" .= _uKind),
("created" .=) <$> _uCreated,
("filters" .=) <$> _uFilters,
("profileId" .=) <$> _uProFileId,
("end-date" .=) <$> _uEndDate,
("selfLink" .=) <$> _uSelfLink,
("accountId" .=) <$> _uAccountId, ("id" .=) <$> _uId,
("updated" .=) <$> _uUpdated,
("title" .=) <$> _uTitle,
("dimensions" .=) <$> _uDimensions,
("segment" .=) <$> _uSegment,
("cloudStorageDownloadDetails" .=) <$>
_uCloudStorageDownloadDetails,
("start-date" .=) <$> _uStartDate])
--
-- /See:/ 'mcfDataColumnHeadersItem' smart constructor.
data McfDataColumnHeadersItem =
McfDataColumnHeadersItem'
{ _mdchiColumnType :: !(Maybe Text)
, _mdchiName :: !(Maybe Text)
, _mdchiDataType :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'McfDataColumnHeadersItem' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'mdchiColumnType'
--
-- * 'mdchiName'
--
-- * 'mdchiDataType'
mcfDataColumnHeadersItem
:: McfDataColumnHeadersItem
mcfDataColumnHeadersItem =
McfDataColumnHeadersItem'
{_mdchiColumnType = Nothing, _mdchiName = Nothing, _mdchiDataType = Nothing}
-- | Column Type. Either DIMENSION or METRIC.
mdchiColumnType :: Lens' McfDataColumnHeadersItem (Maybe Text)
mdchiColumnType
= lens _mdchiColumnType
(\ s a -> s{_mdchiColumnType = a})
-- | Column name.
mdchiName :: Lens' McfDataColumnHeadersItem (Maybe Text)
mdchiName
= lens _mdchiName (\ s a -> s{_mdchiName = a})
-- | Data type. Dimension and metric values data types such as INTEGER,
-- DOUBLE, CURRENCY, MCF_SEQUENCE etc.
mdchiDataType :: Lens' McfDataColumnHeadersItem (Maybe Text)
mdchiDataType
= lens _mdchiDataType
(\ s a -> s{_mdchiDataType = a})
instance FromJSON McfDataColumnHeadersItem where
parseJSON
= withObject "McfDataColumnHeadersItem"
(\ o ->
McfDataColumnHeadersItem' <$>
(o .:? "columnType") <*> (o .:? "name") <*>
(o .:? "dataType"))
instance ToJSON McfDataColumnHeadersItem where
toJSON McfDataColumnHeadersItem'{..}
= object
(catMaybes
[("columnType" .=) <$> _mdchiColumnType,
("name" .=) <$> _mdchiName,
("dataType" .=) <$> _mdchiDataType])
-- | Total values for the requested metrics over all the results, not just
-- the results returned in this response. The order of the metric totals is
-- same as the metric order specified in the request.
--
-- /See:/ 'gaDataTotalsForAllResults' smart constructor.
newtype GaDataTotalsForAllResults =
GaDataTotalsForAllResults'
{ _gdtfarAddtional :: HashMap Text Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'GaDataTotalsForAllResults' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gdtfarAddtional'
gaDataTotalsForAllResults
:: HashMap Text Text -- ^ 'gdtfarAddtional'
-> GaDataTotalsForAllResults
gaDataTotalsForAllResults pGdtfarAddtional_ =
GaDataTotalsForAllResults' {_gdtfarAddtional = _Coerce # pGdtfarAddtional_}
-- | Key-value pair for the total value of a metric. Key is the metric name
-- and the value is the total value for that metric.
gdtfarAddtional :: Lens' GaDataTotalsForAllResults (HashMap Text Text)
gdtfarAddtional
= lens _gdtfarAddtional
(\ s a -> s{_gdtfarAddtional = a})
. _Coerce
instance FromJSON GaDataTotalsForAllResults where
parseJSON
= withObject "GaDataTotalsForAllResults"
(\ o ->
GaDataTotalsForAllResults' <$> (parseJSONObject o))
instance ToJSON GaDataTotalsForAllResults where
toJSON = toJSON . _gdtfarAddtional
-- | Parent link for this view (profile). Points to the web property to which
-- this view (profile) belongs.
--
-- /See:/ 'proFileParentLink' smart constructor.
data ProFileParentLink =
ProFileParentLink'
{ _pfplHref :: !(Maybe Text)
, _pfplType :: !Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProFileParentLink' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pfplHref'
--
-- * 'pfplType'
proFileParentLink
:: ProFileParentLink
proFileParentLink =
ProFileParentLink' {_pfplHref = Nothing, _pfplType = "analytics#webproperty"}
-- | Link to the web property to which this view (profile) belongs.
pfplHref :: Lens' ProFileParentLink (Maybe Text)
pfplHref = lens _pfplHref (\ s a -> s{_pfplHref = a})
-- | Value is \"analytics#webproperty\".
pfplType :: Lens' ProFileParentLink Text
pfplType = lens _pfplType (\ s a -> s{_pfplType = a})
instance FromJSON ProFileParentLink where
parseJSON
= withObject "ProFileParentLink"
(\ o ->
ProFileParentLink' <$>
(o .:? "href") <*>
(o .:? "type" .!= "analytics#webproperty"))
instance ToJSON ProFileParentLink where
toJSON ProFileParentLink'{..}
= object
(catMaybes
[("href" .=) <$> _pfplHref,
Just ("type" .= _pfplType)])
-- | JSON template for an Analytics remarketing audience.
--
-- /See:/ 'remarketingAudience' smart constructor.
data RemarketingAudience =
RemarketingAudience'
{ _rWebPropertyId :: !(Maybe Text)
, _rKind :: !Text
, _rCreated :: !(Maybe DateTime')
, _rLinkedAdAccounts :: !(Maybe [LinkedForeignAccount])
, _rAudienceDefinition :: !(Maybe RemarketingAudienceAudienceDefinition)
, _rAudienceType :: !(Maybe Text)
, _rAccountId :: !(Maybe Text)
, _rName :: !(Maybe Text)
, _rStateBasedAudienceDefinition :: !(Maybe RemarketingAudienceStateBasedAudienceDefinition)
, _rLinkedViews :: !(Maybe [Text])
, _rInternalWebPropertyId :: !(Maybe Text)
, _rId :: !(Maybe Text)
, _rUpdated :: !(Maybe DateTime')
, _rDescription :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'RemarketingAudience' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'rWebPropertyId'
--
-- * 'rKind'
--
-- * 'rCreated'
--
-- * 'rLinkedAdAccounts'
--
-- * 'rAudienceDefinition'
--
-- * 'rAudienceType'
--
-- * 'rAccountId'
--
-- * 'rName'
--
-- * 'rStateBasedAudienceDefinition'
--
-- * 'rLinkedViews'
--
-- * 'rInternalWebPropertyId'
--
-- * 'rId'
--
-- * 'rUpdated'
--
-- * 'rDescription'
remarketingAudience
:: RemarketingAudience
remarketingAudience =
RemarketingAudience'
{ _rWebPropertyId = Nothing
, _rKind = "analytics#remarketingAudience"
, _rCreated = Nothing
, _rLinkedAdAccounts = Nothing
, _rAudienceDefinition = Nothing
, _rAudienceType = Nothing
, _rAccountId = Nothing
, _rName = Nothing
, _rStateBasedAudienceDefinition = Nothing
, _rLinkedViews = Nothing
, _rInternalWebPropertyId = Nothing
, _rId = Nothing
, _rUpdated = Nothing
, _rDescription = Nothing
}
-- | Web property ID of the form UA-XXXXX-YY to which this remarketing
-- audience belongs.
rWebPropertyId :: Lens' RemarketingAudience (Maybe Text)
rWebPropertyId
= lens _rWebPropertyId
(\ s a -> s{_rWebPropertyId = a})
-- | Collection type.
rKind :: Lens' RemarketingAudience Text
rKind = lens _rKind (\ s a -> s{_rKind = a})
-- | Time this remarketing audience was created.
rCreated :: Lens' RemarketingAudience (Maybe UTCTime)
rCreated
= lens _rCreated (\ s a -> s{_rCreated = a}) .
mapping _DateTime
-- | The linked ad accounts associated with this remarketing audience. A
-- remarketing audience can have only one linkedAdAccount currently.
rLinkedAdAccounts :: Lens' RemarketingAudience [LinkedForeignAccount]
rLinkedAdAccounts
= lens _rLinkedAdAccounts
(\ s a -> s{_rLinkedAdAccounts = a})
. _Default
. _Coerce
-- | The simple audience definition that will cause a user to be added to an
-- audience.
rAudienceDefinition :: Lens' RemarketingAudience (Maybe RemarketingAudienceAudienceDefinition)
rAudienceDefinition
= lens _rAudienceDefinition
(\ s a -> s{_rAudienceDefinition = a})
-- | The type of audience, either SIMPLE or STATE_BASED.
rAudienceType :: Lens' RemarketingAudience (Maybe Text)
rAudienceType
= lens _rAudienceType
(\ s a -> s{_rAudienceType = a})
-- | Account ID to which this remarketing audience belongs.
rAccountId :: Lens' RemarketingAudience (Maybe Text)
rAccountId
= lens _rAccountId (\ s a -> s{_rAccountId = a})
-- | The name of this remarketing audience.
rName :: Lens' RemarketingAudience (Maybe Text)
rName = lens _rName (\ s a -> s{_rName = a})
-- | A state based audience definition that will cause a user to be added or
-- removed from an audience.
rStateBasedAudienceDefinition :: Lens' RemarketingAudience (Maybe RemarketingAudienceStateBasedAudienceDefinition)
rStateBasedAudienceDefinition
= lens _rStateBasedAudienceDefinition
(\ s a -> s{_rStateBasedAudienceDefinition = a})
-- | The views (profiles) that this remarketing audience is linked to.
rLinkedViews :: Lens' RemarketingAudience [Text]
rLinkedViews
= lens _rLinkedViews (\ s a -> s{_rLinkedViews = a})
. _Default
. _Coerce
-- | Internal ID for the web property to which this remarketing audience
-- belongs.
rInternalWebPropertyId :: Lens' RemarketingAudience (Maybe Text)
rInternalWebPropertyId
= lens _rInternalWebPropertyId
(\ s a -> s{_rInternalWebPropertyId = a})
-- | Remarketing Audience ID.
rId :: Lens' RemarketingAudience (Maybe Text)
rId = lens _rId (\ s a -> s{_rId = a})
-- | Time this remarketing audience was last modified.
rUpdated :: Lens' RemarketingAudience (Maybe UTCTime)
rUpdated
= lens _rUpdated (\ s a -> s{_rUpdated = a}) .
mapping _DateTime
-- | The description of this remarketing audience.
rDescription :: Lens' RemarketingAudience (Maybe Text)
rDescription
= lens _rDescription (\ s a -> s{_rDescription = a})
instance FromJSON RemarketingAudience where
parseJSON
= withObject "RemarketingAudience"
(\ o ->
RemarketingAudience' <$>
(o .:? "webPropertyId") <*>
(o .:? "kind" .!= "analytics#remarketingAudience")
<*> (o .:? "created")
<*> (o .:? "linkedAdAccounts" .!= mempty)
<*> (o .:? "audienceDefinition")
<*> (o .:? "audienceType")
<*> (o .:? "accountId")
<*> (o .:? "name")
<*> (o .:? "stateBasedAudienceDefinition")
<*> (o .:? "linkedViews" .!= mempty)
<*> (o .:? "internalWebPropertyId")
<*> (o .:? "id")
<*> (o .:? "updated")
<*> (o .:? "description"))
instance ToJSON RemarketingAudience where
toJSON RemarketingAudience'{..}
= object
(catMaybes
[("webPropertyId" .=) <$> _rWebPropertyId,
Just ("kind" .= _rKind),
("created" .=) <$> _rCreated,
("linkedAdAccounts" .=) <$> _rLinkedAdAccounts,
("audienceDefinition" .=) <$> _rAudienceDefinition,
("audienceType" .=) <$> _rAudienceType,
("accountId" .=) <$> _rAccountId,
("name" .=) <$> _rName,
("stateBasedAudienceDefinition" .=) <$>
_rStateBasedAudienceDefinition,
("linkedViews" .=) <$> _rLinkedViews,
("internalWebPropertyId" .=) <$>
_rInternalWebPropertyId,
("id" .=) <$> _rId, ("updated" .=) <$> _rUpdated,
("description" .=) <$> _rDescription])
--
-- /See:/ 'gaDataDataTableRowsItemCItem' smart constructor.
newtype GaDataDataTableRowsItemCItem =
GaDataDataTableRowsItemCItem'
{ _gddtriciV :: Maybe Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'GaDataDataTableRowsItemCItem' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gddtriciV'
gaDataDataTableRowsItemCItem
:: GaDataDataTableRowsItemCItem
gaDataDataTableRowsItemCItem =
GaDataDataTableRowsItemCItem' {_gddtriciV = Nothing}
gddtriciV :: Lens' GaDataDataTableRowsItemCItem (Maybe Text)
gddtriciV
= lens _gddtriciV (\ s a -> s{_gddtriciV = a})
instance FromJSON GaDataDataTableRowsItemCItem where
parseJSON
= withObject "GaDataDataTableRowsItemCItem"
(\ o ->
GaDataDataTableRowsItemCItem' <$> (o .:? "v"))
instance ToJSON GaDataDataTableRowsItemCItem where
toJSON GaDataDataTableRowsItemCItem'{..}
= object (catMaybes [("v" .=) <$> _gddtriciV])
-- | Permissions the user has for this entity.
--
-- /See:/ 'entityUserLinkPermissions' smart constructor.
data EntityUserLinkPermissions =
EntityUserLinkPermissions'
{ _eulpLocal :: !(Maybe [Text])
, _eulpEffective :: !(Maybe [Text])
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'EntityUserLinkPermissions' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'eulpLocal'
--
-- * 'eulpEffective'
entityUserLinkPermissions
:: EntityUserLinkPermissions
entityUserLinkPermissions =
EntityUserLinkPermissions' {_eulpLocal = Nothing, _eulpEffective = Nothing}
-- | Permissions that a user has been assigned at this very level. Does not
-- include any implied or inherited permissions. Local permissions are
-- modifiable.
eulpLocal :: Lens' EntityUserLinkPermissions [Text]
eulpLocal
= lens _eulpLocal (\ s a -> s{_eulpLocal = a}) .
_Default
. _Coerce
-- | Effective permissions represent all the permissions that a user has for
-- this entity. These include any implied permissions (e.g., EDIT implies
-- VIEW) or inherited permissions from the parent entity. Effective
-- permissions are read-only.
eulpEffective :: Lens' EntityUserLinkPermissions [Text]
eulpEffective
= lens _eulpEffective
(\ s a -> s{_eulpEffective = a})
. _Default
. _Coerce
instance FromJSON EntityUserLinkPermissions where
parseJSON
= withObject "EntityUserLinkPermissions"
(\ o ->
EntityUserLinkPermissions' <$>
(o .:? "local" .!= mempty) <*>
(o .:? "effective" .!= mempty))
instance ToJSON EntityUserLinkPermissions where
toJSON EntityUserLinkPermissions'{..}
= object
(catMaybes
[("local" .=) <$> _eulpLocal,
("effective" .=) <$> _eulpEffective])
-- | Information for the view (profile), for which the real time data was
-- requested.
--
-- /See:/ 'realtimeDataProFileInfo' smart constructor.
data RealtimeDataProFileInfo =
RealtimeDataProFileInfo'
{ _rdpfiWebPropertyId :: !(Maybe Text)
, _rdpfiProFileId :: !(Maybe Text)
, _rdpfiProFileName :: !(Maybe Text)
, _rdpfiAccountId :: !(Maybe Text)
, _rdpfiInternalWebPropertyId :: !(Maybe Text)
, _rdpfiTableId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'RealtimeDataProFileInfo' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'rdpfiWebPropertyId'
--
-- * 'rdpfiProFileId'
--
-- * 'rdpfiProFileName'
--
-- * 'rdpfiAccountId'
--
-- * 'rdpfiInternalWebPropertyId'
--
-- * 'rdpfiTableId'
realtimeDataProFileInfo
:: RealtimeDataProFileInfo
realtimeDataProFileInfo =
RealtimeDataProFileInfo'
{ _rdpfiWebPropertyId = Nothing
, _rdpfiProFileId = Nothing
, _rdpfiProFileName = Nothing
, _rdpfiAccountId = Nothing
, _rdpfiInternalWebPropertyId = Nothing
, _rdpfiTableId = Nothing
}
-- | Web Property ID to which this view (profile) belongs.
rdpfiWebPropertyId :: Lens' RealtimeDataProFileInfo (Maybe Text)
rdpfiWebPropertyId
= lens _rdpfiWebPropertyId
(\ s a -> s{_rdpfiWebPropertyId = a})
-- | View (Profile) ID.
rdpfiProFileId :: Lens' RealtimeDataProFileInfo (Maybe Text)
rdpfiProFileId
= lens _rdpfiProFileId
(\ s a -> s{_rdpfiProFileId = a})
-- | View (Profile) name.
rdpfiProFileName :: Lens' RealtimeDataProFileInfo (Maybe Text)
rdpfiProFileName
= lens _rdpfiProFileName
(\ s a -> s{_rdpfiProFileName = a})
-- | Account ID to which this view (profile) belongs.
rdpfiAccountId :: Lens' RealtimeDataProFileInfo (Maybe Text)
rdpfiAccountId
= lens _rdpfiAccountId
(\ s a -> s{_rdpfiAccountId = a})
-- | Internal ID for the web property to which this view (profile) belongs.
rdpfiInternalWebPropertyId :: Lens' RealtimeDataProFileInfo (Maybe Text)
rdpfiInternalWebPropertyId
= lens _rdpfiInternalWebPropertyId
(\ s a -> s{_rdpfiInternalWebPropertyId = a})
-- | Table ID for view (profile).
rdpfiTableId :: Lens' RealtimeDataProFileInfo (Maybe Text)
rdpfiTableId
= lens _rdpfiTableId (\ s a -> s{_rdpfiTableId = a})
instance FromJSON RealtimeDataProFileInfo where
parseJSON
= withObject "RealtimeDataProFileInfo"
(\ o ->
RealtimeDataProFileInfo' <$>
(o .:? "webPropertyId") <*> (o .:? "profileId") <*>
(o .:? "profileName")
<*> (o .:? "accountId")
<*> (o .:? "internalWebPropertyId")
<*> (o .:? "tableId"))
instance ToJSON RealtimeDataProFileInfo where
toJSON RealtimeDataProFileInfo'{..}
= object
(catMaybes
[("webPropertyId" .=) <$> _rdpfiWebPropertyId,
("profileId" .=) <$> _rdpfiProFileId,
("profileName" .=) <$> _rdpfiProFileName,
("accountId" .=) <$> _rdpfiAccountId,
("internalWebPropertyId" .=) <$>
_rdpfiInternalWebPropertyId,
("tableId" .=) <$> _rdpfiTableId])
--
-- /See:/ 'mcfDataRowsItemItemConversionPathValueItem' smart constructor.
data McfDataRowsItemItemConversionPathValueItem =
McfDataRowsItemItemConversionPathValueItem'
{ _mdriicpviInteractionType :: !(Maybe Text)
, _mdriicpviNodeValue :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'McfDataRowsItemItemConversionPathValueItem' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'mdriicpviInteractionType'
--
-- * 'mdriicpviNodeValue'
mcfDataRowsItemItemConversionPathValueItem
:: McfDataRowsItemItemConversionPathValueItem
mcfDataRowsItemItemConversionPathValueItem =
McfDataRowsItemItemConversionPathValueItem'
{_mdriicpviInteractionType = Nothing, _mdriicpviNodeValue = Nothing}
-- | Type of an interaction on conversion path. Such as CLICK, IMPRESSION
-- etc.
mdriicpviInteractionType :: Lens' McfDataRowsItemItemConversionPathValueItem (Maybe Text)
mdriicpviInteractionType
= lens _mdriicpviInteractionType
(\ s a -> s{_mdriicpviInteractionType = a})
-- | Node value of an interaction on conversion path. Such as source, medium
-- etc.
mdriicpviNodeValue :: Lens' McfDataRowsItemItemConversionPathValueItem (Maybe Text)
mdriicpviNodeValue
= lens _mdriicpviNodeValue
(\ s a -> s{_mdriicpviNodeValue = a})
instance FromJSON
McfDataRowsItemItemConversionPathValueItem
where
parseJSON
= withObject
"McfDataRowsItemItemConversionPathValueItem"
(\ o ->
McfDataRowsItemItemConversionPathValueItem' <$>
(o .:? "interactionType") <*> (o .:? "nodeValue"))
instance ToJSON
McfDataRowsItemItemConversionPathValueItem
where
toJSON
McfDataRowsItemItemConversionPathValueItem'{..}
= object
(catMaybes
[("interactionType" .=) <$>
_mdriicpviInteractionType,
("nodeValue" .=) <$> _mdriicpviNodeValue])
-- | JSON template for an Analytics filter expression.
--
-- /See:/ 'filterExpression' smart constructor.
data FilterExpression =
FilterExpression'
{ _feFieldIndex :: !(Maybe (Textual Int32))
, _feField :: !(Maybe Text)
, _feKind :: !Text
, _feMatchType :: !(Maybe Text)
, _feCaseSensitive :: !(Maybe Bool)
, _feExpressionValue :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'FilterExpression' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'feFieldIndex'
--
-- * 'feField'
--
-- * 'feKind'
--
-- * 'feMatchType'
--
-- * 'feCaseSensitive'
--
-- * 'feExpressionValue'
filterExpression
:: FilterExpression
filterExpression =
FilterExpression'
{ _feFieldIndex = Nothing
, _feField = Nothing
, _feKind = "analytics#filterExpression"
, _feMatchType = Nothing
, _feCaseSensitive = Nothing
, _feExpressionValue = Nothing
}
-- | The Index of the custom dimension. Set only if the field is a is
-- CUSTOM_DIMENSION.
feFieldIndex :: Lens' FilterExpression (Maybe Int32)
feFieldIndex
= lens _feFieldIndex (\ s a -> s{_feFieldIndex = a})
. mapping _Coerce
-- | Field to filter. Possible values: - Content and Traffic -
-- PAGE_REQUEST_URI, - PAGE_HOSTNAME, - PAGE_TITLE, - REFERRAL, -
-- COST_DATA_URI (Campaign target URL), - HIT_TYPE, - INTERNAL_SEARCH_TERM,
-- - INTERNAL_SEARCH_TYPE, - SOURCE_PROPERTY_TRACKING_ID, - Campaign or
-- AdGroup - CAMPAIGN_SOURCE, - CAMPAIGN_MEDIUM, - CAMPAIGN_NAME, -
-- CAMPAIGN_AD_GROUP, - CAMPAIGN_TERM, - CAMPAIGN_CONTENT, - CAMPAIGN_CODE,
-- - CAMPAIGN_REFERRAL_PATH, - E-Commerce - TRANSACTION_COUNTRY, -
-- TRANSACTION_REGION, - TRANSACTION_CITY, - TRANSACTION_AFFILIATION (Store
-- or order location), - ITEM_NAME, - ITEM_CODE, - ITEM_VARIATION, -
-- TRANSACTION_ID, - TRANSACTION_CURRENCY_CODE, - PRODUCT_ACTION_TYPE, -
-- Audience\/Users - BROWSER, - BROWSER_VERSION, - BROWSER_SIZE, -
-- PLATFORM, - PLATFORM_VERSION, - LANGUAGE, - SCREEN_RESOLUTION, -
-- SCREEN_COLORS, - JAVA_ENABLED (Boolean Field), - FLASH_VERSION, -
-- GEO_SPEED (Connection speed), - VISITOR_TYPE, - GEO_ORGANIZATION (ISP
-- organization), - GEO_DOMAIN, - GEO_IP_ADDRESS, - GEO_IP_VERSION, -
-- Location - GEO_COUNTRY, - GEO_REGION, - GEO_CITY, - Event -
-- EVENT_CATEGORY, - EVENT_ACTION, - EVENT_LABEL, - Other - CUSTOM_FIELD_1,
-- - CUSTOM_FIELD_2, - USER_DEFINED_VALUE, - Application - APP_ID, -
-- APP_INSTALLER_ID, - APP_NAME, - APP_VERSION, - SCREEN, - IS_APP (Boolean
-- Field), - IS_FATAL_EXCEPTION (Boolean Field), - EXCEPTION_DESCRIPTION, -
-- Mobile device - IS_MOBILE (Boolean Field, Deprecated. Use
-- DEVICE_CATEGORY=mobile), - IS_TABLET (Boolean Field, Deprecated. Use
-- DEVICE_CATEGORY=tablet), - DEVICE_CATEGORY, - MOBILE_HAS_QWERTY_KEYBOARD
-- (Boolean Field), - MOBILE_HAS_NFC_SUPPORT (Boolean Field), -
-- MOBILE_HAS_CELLULAR_RADIO (Boolean Field), - MOBILE_HAS_WIFI_SUPPORT
-- (Boolean Field), - MOBILE_BRAND_NAME, - MOBILE_MODEL_NAME, -
-- MOBILE_MARKETING_NAME, - MOBILE_POINTING_METHOD, - Social -
-- SOCIAL_NETWORK, - SOCIAL_ACTION, - SOCIAL_ACTION_TARGET, - Custom
-- dimension - CUSTOM_DIMENSION (See accompanying field index),
feField :: Lens' FilterExpression (Maybe Text)
feField = lens _feField (\ s a -> s{_feField = a})
-- | Kind value for filter expression
feKind :: Lens' FilterExpression Text
feKind = lens _feKind (\ s a -> s{_feKind = a})
-- | Match type for this filter. Possible values are BEGINS_WITH, EQUAL,
-- ENDS_WITH, CONTAINS, or MATCHES. GEO_DOMAIN, GEO_IP_ADDRESS,
-- PAGE_REQUEST_URI, or PAGE_HOSTNAME filters can use any match type; all
-- other filters must use MATCHES.
feMatchType :: Lens' FilterExpression (Maybe Text)
feMatchType
= lens _feMatchType (\ s a -> s{_feMatchType = a})
-- | Determines if the filter is case sensitive.
feCaseSensitive :: Lens' FilterExpression (Maybe Bool)
feCaseSensitive
= lens _feCaseSensitive
(\ s a -> s{_feCaseSensitive = a})
-- | Filter expression value
feExpressionValue :: Lens' FilterExpression (Maybe Text)
feExpressionValue
= lens _feExpressionValue
(\ s a -> s{_feExpressionValue = a})
instance FromJSON FilterExpression where
parseJSON
= withObject "FilterExpression"
(\ o ->
FilterExpression' <$>
(o .:? "fieldIndex") <*> (o .:? "field") <*>
(o .:? "kind" .!= "analytics#filterExpression")
<*> (o .:? "matchType")
<*> (o .:? "caseSensitive")
<*> (o .:? "expressionValue"))
instance ToJSON FilterExpression where
toJSON FilterExpression'{..}
= object
(catMaybes
[("fieldIndex" .=) <$> _feFieldIndex,
("field" .=) <$> _feField, Just ("kind" .= _feKind),
("matchType" .=) <$> _feMatchType,
("caseSensitive" .=) <$> _feCaseSensitive,
("expressionValue" .=) <$> _feExpressionValue])
-- | JSON template for a linked view (profile).
--
-- /See:/ 'proFileRef' smart constructor.
data ProFileRef =
ProFileRef'
{ _pfrWebPropertyId :: !(Maybe Text)
, _pfrKind :: !Text
, _pfrHref :: !(Maybe Text)
, _pfrAccountId :: !(Maybe Text)
, _pfrName :: !(Maybe Text)
, _pfrInternalWebPropertyId :: !(Maybe Text)
, _pfrId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProFileRef' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pfrWebPropertyId'
--
-- * 'pfrKind'
--
-- * 'pfrHref'
--
-- * 'pfrAccountId'
--
-- * 'pfrName'
--
-- * 'pfrInternalWebPropertyId'
--
-- * 'pfrId'
proFileRef
:: ProFileRef
proFileRef =
ProFileRef'
{ _pfrWebPropertyId = Nothing
, _pfrKind = "analytics#profileRef"
, _pfrHref = Nothing
, _pfrAccountId = Nothing
, _pfrName = Nothing
, _pfrInternalWebPropertyId = Nothing
, _pfrId = Nothing
}
-- | Web property ID of the form UA-XXXXX-YY to which this view (profile)
-- belongs.
pfrWebPropertyId :: Lens' ProFileRef (Maybe Text)
pfrWebPropertyId
= lens _pfrWebPropertyId
(\ s a -> s{_pfrWebPropertyId = a})
-- | Analytics view (profile) reference.
pfrKind :: Lens' ProFileRef Text
pfrKind = lens _pfrKind (\ s a -> s{_pfrKind = a})
-- | Link for this view (profile).
pfrHref :: Lens' ProFileRef (Maybe Text)
pfrHref = lens _pfrHref (\ s a -> s{_pfrHref = a})
-- | Account ID to which this view (profile) belongs.
pfrAccountId :: Lens' ProFileRef (Maybe Text)
pfrAccountId
= lens _pfrAccountId (\ s a -> s{_pfrAccountId = a})
-- | Name of this view (profile).
pfrName :: Lens' ProFileRef (Maybe Text)
pfrName = lens _pfrName (\ s a -> s{_pfrName = a})
-- | Internal ID for the web property to which this view (profile) belongs.
pfrInternalWebPropertyId :: Lens' ProFileRef (Maybe Text)
pfrInternalWebPropertyId
= lens _pfrInternalWebPropertyId
(\ s a -> s{_pfrInternalWebPropertyId = a})
-- | View (Profile) ID.
pfrId :: Lens' ProFileRef (Maybe Text)
pfrId = lens _pfrId (\ s a -> s{_pfrId = a})
instance FromJSON ProFileRef where
parseJSON
= withObject "ProFileRef"
(\ o ->
ProFileRef' <$>
(o .:? "webPropertyId") <*>
(o .:? "kind" .!= "analytics#profileRef")
<*> (o .:? "href")
<*> (o .:? "accountId")
<*> (o .:? "name")
<*> (o .:? "internalWebPropertyId")
<*> (o .:? "id"))
instance ToJSON ProFileRef where
toJSON ProFileRef'{..}
= object
(catMaybes
[("webPropertyId" .=) <$> _pfrWebPropertyId,
Just ("kind" .= _pfrKind), ("href" .=) <$> _pfrHref,
("accountId" .=) <$> _pfrAccountId,
("name" .=) <$> _pfrName,
("internalWebPropertyId" .=) <$>
_pfrInternalWebPropertyId,
("id" .=) <$> _pfrId])
-- | An account collection provides a list of Analytics accounts to which a
-- user has access. The account collection is the entry point to all
-- management information. Each resource in the collection corresponds to a
-- single Analytics account.
--
-- /See:/ 'accounts' smart constructor.
data Accounts =
Accounts'
{ _aNextLink :: !(Maybe Text)
, _aItemsPerPage :: !(Maybe (Textual Int32))
, _aKind :: !Text
, _aUsername :: !(Maybe Text)
, _aItems :: !(Maybe [Account])
, _aTotalResults :: !(Maybe (Textual Int32))
, _aStartIndex :: !(Maybe (Textual Int32))
, _aPreviousLink :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Accounts' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'aNextLink'
--
-- * 'aItemsPerPage'
--
-- * 'aKind'
--
-- * 'aUsername'
--
-- * 'aItems'
--
-- * 'aTotalResults'
--
-- * 'aStartIndex'
--
-- * 'aPreviousLink'
accounts
:: Accounts
accounts =
Accounts'
{ _aNextLink = Nothing
, _aItemsPerPage = Nothing
, _aKind = "analytics#accounts"
, _aUsername = Nothing
, _aItems = Nothing
, _aTotalResults = Nothing
, _aStartIndex = Nothing
, _aPreviousLink = Nothing
}
-- | Next link for this account collection.
aNextLink :: Lens' Accounts (Maybe Text)
aNextLink
= lens _aNextLink (\ s a -> s{_aNextLink = a})
-- | The maximum number of entries the response can contain, regardless of
-- the actual number of entries returned. Its value ranges from 1 to 1000
-- with a value of 1000 by default, or otherwise specified by the
-- max-results query parameter.
aItemsPerPage :: Lens' Accounts (Maybe Int32)
aItemsPerPage
= lens _aItemsPerPage
(\ s a -> s{_aItemsPerPage = a})
. mapping _Coerce
-- | Collection type.
aKind :: Lens' Accounts Text
aKind = lens _aKind (\ s a -> s{_aKind = a})
-- | Email ID of the authenticated user
aUsername :: Lens' Accounts (Maybe Text)
aUsername
= lens _aUsername (\ s a -> s{_aUsername = a})
-- | A list of accounts.
aItems :: Lens' Accounts [Account]
aItems
= lens _aItems (\ s a -> s{_aItems = a}) . _Default .
_Coerce
-- | The total number of results for the query, regardless of the number of
-- results in the response.
aTotalResults :: Lens' Accounts (Maybe Int32)
aTotalResults
= lens _aTotalResults
(\ s a -> s{_aTotalResults = a})
. mapping _Coerce
-- | The starting index of the entries, which is 1 by default or otherwise
-- specified by the start-index query parameter.
aStartIndex :: Lens' Accounts (Maybe Int32)
aStartIndex
= lens _aStartIndex (\ s a -> s{_aStartIndex = a}) .
mapping _Coerce
-- | Previous link for this account collection.
aPreviousLink :: Lens' Accounts (Maybe Text)
aPreviousLink
= lens _aPreviousLink
(\ s a -> s{_aPreviousLink = a})
instance FromJSON Accounts where
parseJSON
= withObject "Accounts"
(\ o ->
Accounts' <$>
(o .:? "nextLink") <*> (o .:? "itemsPerPage") <*>
(o .:? "kind" .!= "analytics#accounts")
<*> (o .:? "username")
<*> (o .:? "items" .!= mempty)
<*> (o .:? "totalResults")
<*> (o .:? "startIndex")
<*> (o .:? "previousLink"))
instance ToJSON Accounts where
toJSON Accounts'{..}
= object
(catMaybes
[("nextLink" .=) <$> _aNextLink,
("itemsPerPage" .=) <$> _aItemsPerPage,
Just ("kind" .= _aKind),
("username" .=) <$> _aUsername,
("items" .=) <$> _aItems,
("totalResults" .=) <$> _aTotalResults,
("startIndex" .=) <$> _aStartIndex,
("previousLink" .=) <$> _aPreviousLink])
-- | An experiment collection lists Analytics experiments to which the user
-- has access. Each view (profile) can have a set of experiments. Each
-- resource in the Experiment collection corresponds to a single Analytics
-- experiment.
--
-- /See:/ 'experiments' smart constructor.
data Experiments =
Experiments'
{ _eNextLink :: !(Maybe Text)
, _eItemsPerPage :: !(Maybe (Textual Int32))
, _eKind :: !Text
, _eUsername :: !(Maybe Text)
, _eItems :: !(Maybe [Experiment])
, _eTotalResults :: !(Maybe (Textual Int32))
, _eStartIndex :: !(Maybe (Textual Int32))
, _ePreviousLink :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Experiments' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'eNextLink'
--
-- * 'eItemsPerPage'
--
-- * 'eKind'
--
-- * 'eUsername'
--
-- * 'eItems'
--
-- * 'eTotalResults'
--
-- * 'eStartIndex'
--
-- * 'ePreviousLink'
experiments
:: Experiments
experiments =
Experiments'
{ _eNextLink = Nothing
, _eItemsPerPage = Nothing
, _eKind = "analytics#experiments"
, _eUsername = Nothing
, _eItems = Nothing
, _eTotalResults = Nothing
, _eStartIndex = Nothing
, _ePreviousLink = Nothing
}
-- | Link to next page for this experiment collection.
eNextLink :: Lens' Experiments (Maybe Text)
eNextLink
= lens _eNextLink (\ s a -> s{_eNextLink = a})
-- | The maximum number of resources the response can contain, regardless of
-- the actual number of resources returned. Its value ranges from 1 to 1000
-- with a value of 1000 by default, or otherwise specified by the
-- max-results query parameter.
eItemsPerPage :: Lens' Experiments (Maybe Int32)
eItemsPerPage
= lens _eItemsPerPage
(\ s a -> s{_eItemsPerPage = a})
. mapping _Coerce
-- | Collection type.
eKind :: Lens' Experiments Text
eKind = lens _eKind (\ s a -> s{_eKind = a})
-- | Email ID of the authenticated user
eUsername :: Lens' Experiments (Maybe Text)
eUsername
= lens _eUsername (\ s a -> s{_eUsername = a})
-- | A list of experiments.
eItems :: Lens' Experiments [Experiment]
eItems
= lens _eItems (\ s a -> s{_eItems = a}) . _Default .
_Coerce
-- | The total number of results for the query, regardless of the number of
-- resources in the result.
eTotalResults :: Lens' Experiments (Maybe Int32)
eTotalResults
= lens _eTotalResults
(\ s a -> s{_eTotalResults = a})
. mapping _Coerce
-- | The starting index of the resources, which is 1 by default or otherwise
-- specified by the start-index query parameter.
eStartIndex :: Lens' Experiments (Maybe Int32)
eStartIndex
= lens _eStartIndex (\ s a -> s{_eStartIndex = a}) .
mapping _Coerce
-- | Link to previous page for this experiment collection.
ePreviousLink :: Lens' Experiments (Maybe Text)
ePreviousLink
= lens _ePreviousLink
(\ s a -> s{_ePreviousLink = a})
instance FromJSON Experiments where
parseJSON
= withObject "Experiments"
(\ o ->
Experiments' <$>
(o .:? "nextLink") <*> (o .:? "itemsPerPage") <*>
(o .:? "kind" .!= "analytics#experiments")
<*> (o .:? "username")
<*> (o .:? "items" .!= mempty)
<*> (o .:? "totalResults")
<*> (o .:? "startIndex")
<*> (o .:? "previousLink"))
instance ToJSON Experiments where
toJSON Experiments'{..}
= object
(catMaybes
[("nextLink" .=) <$> _eNextLink,
("itemsPerPage" .=) <$> _eItemsPerPage,
Just ("kind" .= _eKind),
("username" .=) <$> _eUsername,
("items" .=) <$> _eItems,
("totalResults" .=) <$> _eTotalResults,
("startIndex" .=) <$> _eStartIndex,
("previousLink" .=) <$> _ePreviousLink])
-- | Parent link for an experiment. Points to the view (profile) to which
-- this experiment belongs.
--
-- /See:/ 'experimentParentLink' smart constructor.
data ExperimentParentLink =
ExperimentParentLink'
{ _eplHref :: !(Maybe Text)
, _eplType :: !Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ExperimentParentLink' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'eplHref'
--
-- * 'eplType'
experimentParentLink
:: ExperimentParentLink
experimentParentLink =
ExperimentParentLink' {_eplHref = Nothing, _eplType = "analytics#profile"}
-- | Link to the view (profile) to which this experiment belongs. This field
-- is read-only.
eplHref :: Lens' ExperimentParentLink (Maybe Text)
eplHref = lens _eplHref (\ s a -> s{_eplHref = a})
-- | Value is \"analytics#profile\". This field is read-only.
eplType :: Lens' ExperimentParentLink Text
eplType = lens _eplType (\ s a -> s{_eplType = a})
instance FromJSON ExperimentParentLink where
parseJSON
= withObject "ExperimentParentLink"
(\ o ->
ExperimentParentLink' <$>
(o .:? "href") <*>
(o .:? "type" .!= "analytics#profile"))
instance ToJSON ExperimentParentLink where
toJSON ExperimentParentLink'{..}
= object
(catMaybes
[("href" .=) <$> _eplHref,
Just ("type" .= _eplType)])
-- | Download details for a file stored in Google Drive.
--
-- /See:/ 'unSampledReportDriveDownloadDetails' smart constructor.
newtype UnSampledReportDriveDownloadDetails =
UnSampledReportDriveDownloadDetails'
{ _usrdddDocumentId :: Maybe Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'UnSampledReportDriveDownloadDetails' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'usrdddDocumentId'
unSampledReportDriveDownloadDetails
:: UnSampledReportDriveDownloadDetails
unSampledReportDriveDownloadDetails =
UnSampledReportDriveDownloadDetails' {_usrdddDocumentId = Nothing}
-- | Id of the document\/file containing the report data.
usrdddDocumentId :: Lens' UnSampledReportDriveDownloadDetails (Maybe Text)
usrdddDocumentId
= lens _usrdddDocumentId
(\ s a -> s{_usrdddDocumentId = a})
instance FromJSON UnSampledReportDriveDownloadDetails
where
parseJSON
= withObject "UnSampledReportDriveDownloadDetails"
(\ o ->
UnSampledReportDriveDownloadDetails' <$>
(o .:? "documentId"))
instance ToJSON UnSampledReportDriveDownloadDetails
where
toJSON UnSampledReportDriveDownloadDetails'{..}
= object
(catMaybes [("documentId" .=) <$> _usrdddDocumentId])
-- | Information for the view (profile), for which the Analytics data was
-- requested.
--
-- /See:/ 'mcfDataProFileInfo' smart constructor.
data McfDataProFileInfo =
McfDataProFileInfo'
{ _mdpfiWebPropertyId :: !(Maybe Text)
, _mdpfiProFileId :: !(Maybe Text)
, _mdpfiProFileName :: !(Maybe Text)
, _mdpfiAccountId :: !(Maybe Text)
, _mdpfiInternalWebPropertyId :: !(Maybe Text)
, _mdpfiTableId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'McfDataProFileInfo' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'mdpfiWebPropertyId'
--
-- * 'mdpfiProFileId'
--
-- * 'mdpfiProFileName'
--
-- * 'mdpfiAccountId'
--
-- * 'mdpfiInternalWebPropertyId'
--
-- * 'mdpfiTableId'
mcfDataProFileInfo
:: McfDataProFileInfo
mcfDataProFileInfo =
McfDataProFileInfo'
{ _mdpfiWebPropertyId = Nothing
, _mdpfiProFileId = Nothing
, _mdpfiProFileName = Nothing
, _mdpfiAccountId = Nothing
, _mdpfiInternalWebPropertyId = Nothing
, _mdpfiTableId = Nothing
}
-- | Web Property ID to which this view (profile) belongs.
mdpfiWebPropertyId :: Lens' McfDataProFileInfo (Maybe Text)
mdpfiWebPropertyId
= lens _mdpfiWebPropertyId
(\ s a -> s{_mdpfiWebPropertyId = a})
-- | View (Profile) ID.
mdpfiProFileId :: Lens' McfDataProFileInfo (Maybe Text)
mdpfiProFileId
= lens _mdpfiProFileId
(\ s a -> s{_mdpfiProFileId = a})
-- | View (Profile) name.
mdpfiProFileName :: Lens' McfDataProFileInfo (Maybe Text)
mdpfiProFileName
= lens _mdpfiProFileName
(\ s a -> s{_mdpfiProFileName = a})
-- | Account ID to which this view (profile) belongs.
mdpfiAccountId :: Lens' McfDataProFileInfo (Maybe Text)
mdpfiAccountId
= lens _mdpfiAccountId
(\ s a -> s{_mdpfiAccountId = a})
-- | Internal ID for the web property to which this view (profile) belongs.
mdpfiInternalWebPropertyId :: Lens' McfDataProFileInfo (Maybe Text)
mdpfiInternalWebPropertyId
= lens _mdpfiInternalWebPropertyId
(\ s a -> s{_mdpfiInternalWebPropertyId = a})
-- | Table ID for view (profile).
mdpfiTableId :: Lens' McfDataProFileInfo (Maybe Text)
mdpfiTableId
= lens _mdpfiTableId (\ s a -> s{_mdpfiTableId = a})
instance FromJSON McfDataProFileInfo where
parseJSON
= withObject "McfDataProFileInfo"
(\ o ->
McfDataProFileInfo' <$>
(o .:? "webPropertyId") <*> (o .:? "profileId") <*>
(o .:? "profileName")
<*> (o .:? "accountId")
<*> (o .:? "internalWebPropertyId")
<*> (o .:? "tableId"))
instance ToJSON McfDataProFileInfo where
toJSON McfDataProFileInfo'{..}
= object
(catMaybes
[("webPropertyId" .=) <$> _mdpfiWebPropertyId,
("profileId" .=) <$> _mdpfiProFileId,
("profileName" .=) <$> _mdpfiProFileName,
("accountId" .=) <$> _mdpfiAccountId,
("internalWebPropertyId" .=) <$>
_mdpfiInternalWebPropertyId,
("tableId" .=) <$> _mdpfiTableId])
-- | Lists Analytics custom data sources to which the user has access. Each
-- resource in the collection corresponds to a single Analytics custom data
-- source.
--
-- /See:/ 'customDataSources' smart constructor.
data CustomDataSources =
CustomDataSources'
{ _cdsNextLink :: !(Maybe Text)
, _cdsItemsPerPage :: !(Maybe (Textual Int32))
, _cdsKind :: !Text
, _cdsUsername :: !(Maybe Text)
, _cdsItems :: !(Maybe [CustomDataSource])
, _cdsTotalResults :: !(Maybe (Textual Int32))
, _cdsStartIndex :: !(Maybe (Textual Int32))
, _cdsPreviousLink :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'CustomDataSources' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cdsNextLink'
--
-- * 'cdsItemsPerPage'
--
-- * 'cdsKind'
--
-- * 'cdsUsername'
--
-- * 'cdsItems'
--
-- * 'cdsTotalResults'
--
-- * 'cdsStartIndex'
--
-- * 'cdsPreviousLink'
customDataSources
:: CustomDataSources
customDataSources =
CustomDataSources'
{ _cdsNextLink = Nothing
, _cdsItemsPerPage = Nothing
, _cdsKind = "analytics#customDataSources"
, _cdsUsername = Nothing
, _cdsItems = Nothing
, _cdsTotalResults = Nothing
, _cdsStartIndex = Nothing
, _cdsPreviousLink = Nothing
}
-- | Link to next page for this custom data source collection.
cdsNextLink :: Lens' CustomDataSources (Maybe Text)
cdsNextLink
= lens _cdsNextLink (\ s a -> s{_cdsNextLink = a})
-- | The maximum number of resources the response can contain, regardless of
-- the actual number of resources returned. Its value ranges from 1 to 1000
-- with a value of 1000 by default, or otherwise specified by the
-- max-results query parameter.
cdsItemsPerPage :: Lens' CustomDataSources (Maybe Int32)
cdsItemsPerPage
= lens _cdsItemsPerPage
(\ s a -> s{_cdsItemsPerPage = a})
. mapping _Coerce
-- | Collection type.
cdsKind :: Lens' CustomDataSources Text
cdsKind = lens _cdsKind (\ s a -> s{_cdsKind = a})
-- | Email ID of the authenticated user
cdsUsername :: Lens' CustomDataSources (Maybe Text)
cdsUsername
= lens _cdsUsername (\ s a -> s{_cdsUsername = a})
-- | Collection of custom data sources.
cdsItems :: Lens' CustomDataSources [CustomDataSource]
cdsItems
= lens _cdsItems (\ s a -> s{_cdsItems = a}) .
_Default
. _Coerce
-- | The total number of results for the query, regardless of the number of
-- results in the response.
cdsTotalResults :: Lens' CustomDataSources (Maybe Int32)
cdsTotalResults
= lens _cdsTotalResults
(\ s a -> s{_cdsTotalResults = a})
. mapping _Coerce
-- | The starting index of the resources, which is 1 by default or otherwise
-- specified by the start-index query parameter.
cdsStartIndex :: Lens' CustomDataSources (Maybe Int32)
cdsStartIndex
= lens _cdsStartIndex
(\ s a -> s{_cdsStartIndex = a})
. mapping _Coerce
-- | Link to previous page for this custom data source collection.
cdsPreviousLink :: Lens' CustomDataSources (Maybe Text)
cdsPreviousLink
= lens _cdsPreviousLink
(\ s a -> s{_cdsPreviousLink = a})
instance FromJSON CustomDataSources where
parseJSON
= withObject "CustomDataSources"
(\ o ->
CustomDataSources' <$>
(o .:? "nextLink") <*> (o .:? "itemsPerPage") <*>
(o .:? "kind" .!= "analytics#customDataSources")
<*> (o .:? "username")
<*> (o .:? "items" .!= mempty)
<*> (o .:? "totalResults")
<*> (o .:? "startIndex")
<*> (o .:? "previousLink"))
instance ToJSON CustomDataSources where
toJSON CustomDataSources'{..}
= object
(catMaybes
[("nextLink" .=) <$> _cdsNextLink,
("itemsPerPage" .=) <$> _cdsItemsPerPage,
Just ("kind" .= _cdsKind),
("username" .=) <$> _cdsUsername,
("items" .=) <$> _cdsItems,
("totalResults" .=) <$> _cdsTotalResults,
("startIndex" .=) <$> _cdsStartIndex,
("previousLink" .=) <$> _cdsPreviousLink])
-- | Child link for this web property. Points to the list of views (profiles)
-- for this web property.
--
-- /See:/ 'webPropertyChildLink' smart constructor.
data WebPropertyChildLink =
WebPropertyChildLink'
{ _wpclHref :: !(Maybe Text)
, _wpclType :: !Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'WebPropertyChildLink' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'wpclHref'
--
-- * 'wpclType'
webPropertyChildLink
:: WebPropertyChildLink
webPropertyChildLink =
WebPropertyChildLink' {_wpclHref = Nothing, _wpclType = "analytics#profiles"}
-- | Link to the list of views (profiles) for this web property.
wpclHref :: Lens' WebPropertyChildLink (Maybe Text)
wpclHref = lens _wpclHref (\ s a -> s{_wpclHref = a})
-- | Type of the parent link. Its value is \"analytics#profiles\".
wpclType :: Lens' WebPropertyChildLink Text
wpclType = lens _wpclType (\ s a -> s{_wpclType = a})
instance FromJSON WebPropertyChildLink where
parseJSON
= withObject "WebPropertyChildLink"
(\ o ->
WebPropertyChildLink' <$>
(o .:? "href") <*>
(o .:? "type" .!= "analytics#profiles"))
instance ToJSON WebPropertyChildLink where
toJSON WebPropertyChildLink'{..}
= object
(catMaybes
[("href" .=) <$> _wpclHref,
Just ("type" .= _wpclType)])
-- | JSON template for a hash Client Id response resource.
--
-- /See:/ 'hashClientIdResponse' smart constructor.
data HashClientIdResponse =
HashClientIdResponse'
{ _hcirClientId :: !(Maybe Text)
, _hcirWebPropertyId :: !(Maybe Text)
, _hcirKind :: !Text
, _hcirHashedClientId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'HashClientIdResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'hcirClientId'
--
-- * 'hcirWebPropertyId'
--
-- * 'hcirKind'
--
-- * 'hcirHashedClientId'
hashClientIdResponse
:: HashClientIdResponse
hashClientIdResponse =
HashClientIdResponse'
{ _hcirClientId = Nothing
, _hcirWebPropertyId = Nothing
, _hcirKind = "analytics#hashClientIdResponse"
, _hcirHashedClientId = Nothing
}
hcirClientId :: Lens' HashClientIdResponse (Maybe Text)
hcirClientId
= lens _hcirClientId (\ s a -> s{_hcirClientId = a})
hcirWebPropertyId :: Lens' HashClientIdResponse (Maybe Text)
hcirWebPropertyId
= lens _hcirWebPropertyId
(\ s a -> s{_hcirWebPropertyId = a})
hcirKind :: Lens' HashClientIdResponse Text
hcirKind = lens _hcirKind (\ s a -> s{_hcirKind = a})
hcirHashedClientId :: Lens' HashClientIdResponse (Maybe Text)
hcirHashedClientId
= lens _hcirHashedClientId
(\ s a -> s{_hcirHashedClientId = a})
instance FromJSON HashClientIdResponse where
parseJSON
= withObject "HashClientIdResponse"
(\ o ->
HashClientIdResponse' <$>
(o .:? "clientId") <*> (o .:? "webPropertyId") <*>
(o .:? "kind" .!= "analytics#hashClientIdResponse")
<*> (o .:? "hashedClientId"))
instance ToJSON HashClientIdResponse where
toJSON HashClientIdResponse'{..}
= object
(catMaybes
[("clientId" .=) <$> _hcirClientId,
("webPropertyId" .=) <$> _hcirWebPropertyId,
Just ("kind" .= _hcirKind),
("hashedClientId" .=) <$> _hcirHashedClientId])
-- | Multi-Channel Funnels data for a given view (profile).
--
-- /See:/ 'mcfData' smart constructor.
data McfData =
McfData'
{ _mdNextLink :: !(Maybe Text)
, _mdSampleSpace :: !(Maybe (Textual Int64))
, _mdItemsPerPage :: !(Maybe (Textual Int32))
, _mdProFileInfo :: !(Maybe McfDataProFileInfo)
, _mdKind :: !Text
, _mdSampleSize :: !(Maybe (Textual Int64))
, _mdRows :: !(Maybe [[McfDataRowsItemItem]])
, _mdSelfLink :: !(Maybe Text)
, _mdQuery :: !(Maybe McfDataQuery)
, _mdColumnHeaders :: !(Maybe [McfDataColumnHeadersItem])
, _mdId :: !(Maybe Text)
, _mdTotalResults :: !(Maybe (Textual Int32))
, _mdContainsSampledData :: !(Maybe Bool)
, _mdTotalsForAllResults :: !(Maybe McfDataTotalsForAllResults)
, _mdPreviousLink :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'McfData' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'mdNextLink'
--
-- * 'mdSampleSpace'
--
-- * 'mdItemsPerPage'
--
-- * 'mdProFileInfo'
--
-- * 'mdKind'
--
-- * 'mdSampleSize'
--
-- * 'mdRows'
--
-- * 'mdSelfLink'
--
-- * 'mdQuery'
--
-- * 'mdColumnHeaders'
--
-- * 'mdId'
--
-- * 'mdTotalResults'
--
-- * 'mdContainsSampledData'
--
-- * 'mdTotalsForAllResults'
--
-- * 'mdPreviousLink'
mcfData
:: McfData
mcfData =
McfData'
{ _mdNextLink = Nothing
, _mdSampleSpace = Nothing
, _mdItemsPerPage = Nothing
, _mdProFileInfo = Nothing
, _mdKind = "analytics#mcfData"
, _mdSampleSize = Nothing
, _mdRows = Nothing
, _mdSelfLink = Nothing
, _mdQuery = Nothing
, _mdColumnHeaders = Nothing
, _mdId = Nothing
, _mdTotalResults = Nothing
, _mdContainsSampledData = Nothing
, _mdTotalsForAllResults = Nothing
, _mdPreviousLink = Nothing
}
-- | Link to next page for this Analytics data query.
mdNextLink :: Lens' McfData (Maybe Text)
mdNextLink
= lens _mdNextLink (\ s a -> s{_mdNextLink = a})
-- | Total size of the sample space from which the samples were selected.
mdSampleSpace :: Lens' McfData (Maybe Int64)
mdSampleSpace
= lens _mdSampleSpace
(\ s a -> s{_mdSampleSpace = a})
. mapping _Coerce
-- | The maximum number of rows the response can contain, regardless of the
-- actual number of rows returned. Its value ranges from 1 to 10,000 with a
-- value of 1000 by default, or otherwise specified by the max-results
-- query parameter.
mdItemsPerPage :: Lens' McfData (Maybe Int32)
mdItemsPerPage
= lens _mdItemsPerPage
(\ s a -> s{_mdItemsPerPage = a})
. mapping _Coerce
-- | Information for the view (profile), for which the Analytics data was
-- requested.
mdProFileInfo :: Lens' McfData (Maybe McfDataProFileInfo)
mdProFileInfo
= lens _mdProFileInfo
(\ s a -> s{_mdProFileInfo = a})
-- | Resource type.
mdKind :: Lens' McfData Text
mdKind = lens _mdKind (\ s a -> s{_mdKind = a})
-- | The number of samples used to calculate the result.
mdSampleSize :: Lens' McfData (Maybe Int64)
mdSampleSize
= lens _mdSampleSize (\ s a -> s{_mdSampleSize = a})
. mapping _Coerce
-- | Analytics data rows, where each row contains a list of dimension values
-- followed by the metric values. The order of dimensions and metrics is
-- same as specified in the request.
mdRows :: Lens' McfData [[McfDataRowsItemItem]]
mdRows
= lens _mdRows (\ s a -> s{_mdRows = a}) . _Default .
_Coerce
-- | Link to this page.
mdSelfLink :: Lens' McfData (Maybe Text)
mdSelfLink
= lens _mdSelfLink (\ s a -> s{_mdSelfLink = a})
-- | Analytics data request query parameters.
mdQuery :: Lens' McfData (Maybe McfDataQuery)
mdQuery = lens _mdQuery (\ s a -> s{_mdQuery = a})
-- | Column headers that list dimension names followed by the metric names.
-- The order of dimensions and metrics is same as specified in the request.
mdColumnHeaders :: Lens' McfData [McfDataColumnHeadersItem]
mdColumnHeaders
= lens _mdColumnHeaders
(\ s a -> s{_mdColumnHeaders = a})
. _Default
. _Coerce
-- | Unique ID for this data response.
mdId :: Lens' McfData (Maybe Text)
mdId = lens _mdId (\ s a -> s{_mdId = a})
-- | The total number of rows for the query, regardless of the number of rows
-- in the response.
mdTotalResults :: Lens' McfData (Maybe Int32)
mdTotalResults
= lens _mdTotalResults
(\ s a -> s{_mdTotalResults = a})
. mapping _Coerce
-- | Determines if the Analytics data contains sampled data.
mdContainsSampledData :: Lens' McfData (Maybe Bool)
mdContainsSampledData
= lens _mdContainsSampledData
(\ s a -> s{_mdContainsSampledData = a})
-- | Total values for the requested metrics over all the results, not just
-- the results returned in this response. The order of the metric totals is
-- same as the metric order specified in the request.
mdTotalsForAllResults :: Lens' McfData (Maybe McfDataTotalsForAllResults)
mdTotalsForAllResults
= lens _mdTotalsForAllResults
(\ s a -> s{_mdTotalsForAllResults = a})
-- | Link to previous page for this Analytics data query.
mdPreviousLink :: Lens' McfData (Maybe Text)
mdPreviousLink
= lens _mdPreviousLink
(\ s a -> s{_mdPreviousLink = a})
instance FromJSON McfData where
parseJSON
= withObject "McfData"
(\ o ->
McfData' <$>
(o .:? "nextLink") <*> (o .:? "sampleSpace") <*>
(o .:? "itemsPerPage")
<*> (o .:? "profileInfo")
<*> (o .:? "kind" .!= "analytics#mcfData")
<*> (o .:? "sampleSize")
<*> (o .:? "rows" .!= mempty)
<*> (o .:? "selfLink")
<*> (o .:? "query")
<*> (o .:? "columnHeaders" .!= mempty)
<*> (o .:? "id")
<*> (o .:? "totalResults")
<*> (o .:? "containsSampledData")
<*> (o .:? "totalsForAllResults")
<*> (o .:? "previousLink"))
instance ToJSON McfData where
toJSON McfData'{..}
= object
(catMaybes
[("nextLink" .=) <$> _mdNextLink,
("sampleSpace" .=) <$> _mdSampleSpace,
("itemsPerPage" .=) <$> _mdItemsPerPage,
("profileInfo" .=) <$> _mdProFileInfo,
Just ("kind" .= _mdKind),
("sampleSize" .=) <$> _mdSampleSize,
("rows" .=) <$> _mdRows,
("selfLink" .=) <$> _mdSelfLink,
("query" .=) <$> _mdQuery,
("columnHeaders" .=) <$> _mdColumnHeaders,
("id" .=) <$> _mdId,
("totalResults" .=) <$> _mdTotalResults,
("containsSampledData" .=) <$>
_mdContainsSampledData,
("totalsForAllResults" .=) <$>
_mdTotalsForAllResults,
("previousLink" .=) <$> _mdPreviousLink])
-- | JSON template for a user reference.
--
-- /See:/ 'userRef' smart constructor.
data UserRef =
UserRef'
{ _urEmail :: !(Maybe Text)
, _urKind :: !Text
, _urId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'UserRef' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'urEmail'
--
-- * 'urKind'
--
-- * 'urId'
userRef
:: UserRef
userRef =
UserRef' {_urEmail = Nothing, _urKind = "analytics#userRef", _urId = Nothing}
-- | Email ID of this user.
urEmail :: Lens' UserRef (Maybe Text)
urEmail = lens _urEmail (\ s a -> s{_urEmail = a})
urKind :: Lens' UserRef Text
urKind = lens _urKind (\ s a -> s{_urKind = a})
-- | User ID.
urId :: Lens' UserRef (Maybe Text)
urId = lens _urId (\ s a -> s{_urId = a})
instance FromJSON UserRef where
parseJSON
= withObject "UserRef"
(\ o ->
UserRef' <$>
(o .:? "email") <*>
(o .:? "kind" .!= "analytics#userRef")
<*> (o .:? "id"))
instance ToJSON UserRef where
toJSON UserRef'{..}
= object
(catMaybes
[("email" .=) <$> _urEmail, Just ("kind" .= _urKind),
("id" .=) <$> _urId])
-- | Details for the goal of the type VISIT_NUM_PAGES.
--
-- /See:/ 'goalVisitNumPagesDetails' smart constructor.
data GoalVisitNumPagesDetails =
GoalVisitNumPagesDetails'
{ _gvnpdComparisonValue :: !(Maybe (Textual Int64))
, _gvnpdComparisonType :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'GoalVisitNumPagesDetails' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gvnpdComparisonValue'
--
-- * 'gvnpdComparisonType'
goalVisitNumPagesDetails
:: GoalVisitNumPagesDetails
goalVisitNumPagesDetails =
GoalVisitNumPagesDetails'
{_gvnpdComparisonValue = Nothing, _gvnpdComparisonType = Nothing}
-- | Value used for this comparison.
gvnpdComparisonValue :: Lens' GoalVisitNumPagesDetails (Maybe Int64)
gvnpdComparisonValue
= lens _gvnpdComparisonValue
(\ s a -> s{_gvnpdComparisonValue = a})
. mapping _Coerce
-- | Type of comparison. Possible values are LESS_THAN, GREATER_THAN, or
-- EQUAL.
gvnpdComparisonType :: Lens' GoalVisitNumPagesDetails (Maybe Text)
gvnpdComparisonType
= lens _gvnpdComparisonType
(\ s a -> s{_gvnpdComparisonType = a})
instance FromJSON GoalVisitNumPagesDetails where
parseJSON
= withObject "GoalVisitNumPagesDetails"
(\ o ->
GoalVisitNumPagesDetails' <$>
(o .:? "comparisonValue") <*>
(o .:? "comparisonType"))
instance ToJSON GoalVisitNumPagesDetails where
toJSON GoalVisitNumPagesDetails'{..}
= object
(catMaybes
[("comparisonValue" .=) <$> _gvnpdComparisonValue,
("comparisonType" .=) <$> _gvnpdComparisonType])
--
-- /See:/ 'realtimeDataColumnHeadersItem' smart constructor.
data RealtimeDataColumnHeadersItem =
RealtimeDataColumnHeadersItem'
{ _rdchiColumnType :: !(Maybe Text)
, _rdchiName :: !(Maybe Text)
, _rdchiDataType :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'RealtimeDataColumnHeadersItem' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'rdchiColumnType'
--
-- * 'rdchiName'
--
-- * 'rdchiDataType'
realtimeDataColumnHeadersItem
:: RealtimeDataColumnHeadersItem
realtimeDataColumnHeadersItem =
RealtimeDataColumnHeadersItem'
{_rdchiColumnType = Nothing, _rdchiName = Nothing, _rdchiDataType = Nothing}
-- | Column Type. Either DIMENSION or METRIC.
rdchiColumnType :: Lens' RealtimeDataColumnHeadersItem (Maybe Text)
rdchiColumnType
= lens _rdchiColumnType
(\ s a -> s{_rdchiColumnType = a})
-- | Column name.
rdchiName :: Lens' RealtimeDataColumnHeadersItem (Maybe Text)
rdchiName
= lens _rdchiName (\ s a -> s{_rdchiName = a})
-- | Data type. Dimension column headers have only STRING as the data type.
-- Metric column headers have data types for metric values such as INTEGER,
-- DOUBLE, CURRENCY etc.
rdchiDataType :: Lens' RealtimeDataColumnHeadersItem (Maybe Text)
rdchiDataType
= lens _rdchiDataType
(\ s a -> s{_rdchiDataType = a})
instance FromJSON RealtimeDataColumnHeadersItem where
parseJSON
= withObject "RealtimeDataColumnHeadersItem"
(\ o ->
RealtimeDataColumnHeadersItem' <$>
(o .:? "columnType") <*> (o .:? "name") <*>
(o .:? "dataType"))
instance ToJSON RealtimeDataColumnHeadersItem where
toJSON RealtimeDataColumnHeadersItem'{..}
= object
(catMaybes
[("columnType" .=) <$> _rdchiColumnType,
("name" .=) <$> _rdchiName,
("dataType" .=) <$> _rdchiDataType])
-- | JSON template for a linked account.
--
-- /See:/ 'accountRef' smart constructor.
data AccountRef =
AccountRef'
{ _arKind :: !Text
, _arHref :: !(Maybe Text)
, _arName :: !(Maybe Text)
, _arId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'AccountRef' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'arKind'
--
-- * 'arHref'
--
-- * 'arName'
--
-- * 'arId'
accountRef
:: AccountRef
accountRef =
AccountRef'
{ _arKind = "analytics#accountRef"
, _arHref = Nothing
, _arName = Nothing
, _arId = Nothing
}
-- | Analytics account reference.
arKind :: Lens' AccountRef Text
arKind = lens _arKind (\ s a -> s{_arKind = a})
-- | Link for this account.
arHref :: Lens' AccountRef (Maybe Text)
arHref = lens _arHref (\ s a -> s{_arHref = a})
-- | Account name.
arName :: Lens' AccountRef (Maybe Text)
arName = lens _arName (\ s a -> s{_arName = a})
-- | Account ID.
arId :: Lens' AccountRef (Maybe Text)
arId = lens _arId (\ s a -> s{_arId = a})
instance FromJSON AccountRef where
parseJSON
= withObject "AccountRef"
(\ o ->
AccountRef' <$>
(o .:? "kind" .!= "analytics#accountRef") <*>
(o .:? "href")
<*> (o .:? "name")
<*> (o .:? "id"))
instance ToJSON AccountRef where
toJSON AccountRef'{..}
= object
(catMaybes
[Just ("kind" .= _arKind), ("href" .=) <$> _arHref,
("name" .=) <$> _arName, ("id" .=) <$> _arId])
-- | An entity Google Ads link collection provides a list of GA-Google Ads
-- links Each resource in this collection corresponds to a single link.
--
-- /See:/ 'entityAdWordsLinks' smart constructor.
data EntityAdWordsLinks =
EntityAdWordsLinks'
{ _eawlNextLink :: !(Maybe Text)
, _eawlItemsPerPage :: !(Maybe (Textual Int32))
, _eawlKind :: !Text
, _eawlItems :: !(Maybe [EntityAdWordsLink])
, _eawlTotalResults :: !(Maybe (Textual Int32))
, _eawlStartIndex :: !(Maybe (Textual Int32))
, _eawlPreviousLink :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'EntityAdWordsLinks' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'eawlNextLink'
--
-- * 'eawlItemsPerPage'
--
-- * 'eawlKind'
--
-- * 'eawlItems'
--
-- * 'eawlTotalResults'
--
-- * 'eawlStartIndex'
--
-- * 'eawlPreviousLink'
entityAdWordsLinks
:: EntityAdWordsLinks
entityAdWordsLinks =
EntityAdWordsLinks'
{ _eawlNextLink = Nothing
, _eawlItemsPerPage = Nothing
, _eawlKind = "analytics#entityAdWordsLinks"
, _eawlItems = Nothing
, _eawlTotalResults = Nothing
, _eawlStartIndex = Nothing
, _eawlPreviousLink = Nothing
}
-- | Next link for this Google Ads link collection.
eawlNextLink :: Lens' EntityAdWordsLinks (Maybe Text)
eawlNextLink
= lens _eawlNextLink (\ s a -> s{_eawlNextLink = a})
-- | The maximum number of entries the response can contain, regardless of
-- the actual number of entries returned. Its value ranges from 1 to 1000
-- with a value of 1000 by default, or otherwise specified by the
-- max-results query parameter.
eawlItemsPerPage :: Lens' EntityAdWordsLinks (Maybe Int32)
eawlItemsPerPage
= lens _eawlItemsPerPage
(\ s a -> s{_eawlItemsPerPage = a})
. mapping _Coerce
-- | Collection type.
eawlKind :: Lens' EntityAdWordsLinks Text
eawlKind = lens _eawlKind (\ s a -> s{_eawlKind = a})
-- | A list of entity Google Ads links.
eawlItems :: Lens' EntityAdWordsLinks [EntityAdWordsLink]
eawlItems
= lens _eawlItems (\ s a -> s{_eawlItems = a}) .
_Default
. _Coerce
-- | The total number of results for the query, regardless of the number of
-- results in the response.
eawlTotalResults :: Lens' EntityAdWordsLinks (Maybe Int32)
eawlTotalResults
= lens _eawlTotalResults
(\ s a -> s{_eawlTotalResults = a})
. mapping _Coerce
-- | The starting index of the entries, which is 1 by default or otherwise
-- specified by the start-index query parameter.
eawlStartIndex :: Lens' EntityAdWordsLinks (Maybe Int32)
eawlStartIndex
= lens _eawlStartIndex
(\ s a -> s{_eawlStartIndex = a})
. mapping _Coerce
-- | Previous link for this Google Ads link collection.
eawlPreviousLink :: Lens' EntityAdWordsLinks (Maybe Text)
eawlPreviousLink
= lens _eawlPreviousLink
(\ s a -> s{_eawlPreviousLink = a})
instance FromJSON EntityAdWordsLinks where
parseJSON
= withObject "EntityAdWordsLinks"
(\ o ->
EntityAdWordsLinks' <$>
(o .:? "nextLink") <*> (o .:? "itemsPerPage") <*>
(o .:? "kind" .!= "analytics#entityAdWordsLinks")
<*> (o .:? "items" .!= mempty)
<*> (o .:? "totalResults")
<*> (o .:? "startIndex")
<*> (o .:? "previousLink"))
instance ToJSON EntityAdWordsLinks where
toJSON EntityAdWordsLinks'{..}
= object
(catMaybes
[("nextLink" .=) <$> _eawlNextLink,
("itemsPerPage" .=) <$> _eawlItemsPerPage,
Just ("kind" .= _eawlKind),
("items" .=) <$> _eawlItems,
("totalResults" .=) <$> _eawlTotalResults,
("startIndex" .=) <$> _eawlStartIndex,
("previousLink" .=) <$> _eawlPreviousLink])
-- | A view (profile) collection lists Analytics views (profiles) to which
-- the user has access. Each resource in the collection corresponds to a
-- single Analytics view (profile).
--
-- /See:/ 'proFiles' smart constructor.
data ProFiles =
ProFiles'
{ _pfNextLink :: !(Maybe Text)
, _pfItemsPerPage :: !(Maybe (Textual Int32))
, _pfKind :: !Text
, _pfUsername :: !(Maybe Text)
, _pfItems :: !(Maybe [ProFile])
, _pfTotalResults :: !(Maybe (Textual Int32))
, _pfStartIndex :: !(Maybe (Textual Int32))
, _pfPreviousLink :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProFiles' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pfNextLink'
--
-- * 'pfItemsPerPage'
--
-- * 'pfKind'
--
-- * 'pfUsername'
--
-- * 'pfItems'
--
-- * 'pfTotalResults'
--
-- * 'pfStartIndex'
--
-- * 'pfPreviousLink'
proFiles
:: ProFiles
proFiles =
ProFiles'
{ _pfNextLink = Nothing
, _pfItemsPerPage = Nothing
, _pfKind = "analytics#profiles"
, _pfUsername = Nothing
, _pfItems = Nothing
, _pfTotalResults = Nothing
, _pfStartIndex = Nothing
, _pfPreviousLink = Nothing
}
-- | Link to next page for this view (profile) collection.
pfNextLink :: Lens' ProFiles (Maybe Text)
pfNextLink
= lens _pfNextLink (\ s a -> s{_pfNextLink = a})
-- | The maximum number of resources the response can contain, regardless of
-- the actual number of resources returned. Its value ranges from 1 to 1000
-- with a value of 1000 by default, or otherwise specified by the
-- max-results query parameter.
pfItemsPerPage :: Lens' ProFiles (Maybe Int32)
pfItemsPerPage
= lens _pfItemsPerPage
(\ s a -> s{_pfItemsPerPage = a})
. mapping _Coerce
-- | Collection type.
pfKind :: Lens' ProFiles Text
pfKind = lens _pfKind (\ s a -> s{_pfKind = a})
-- | Email ID of the authenticated user
pfUsername :: Lens' ProFiles (Maybe Text)
pfUsername
= lens _pfUsername (\ s a -> s{_pfUsername = a})
-- | A list of views (profiles).
pfItems :: Lens' ProFiles [ProFile]
pfItems
= lens _pfItems (\ s a -> s{_pfItems = a}) . _Default
. _Coerce
-- | The total number of results for the query, regardless of the number of
-- results in the response.
pfTotalResults :: Lens' ProFiles (Maybe Int32)
pfTotalResults
= lens _pfTotalResults
(\ s a -> s{_pfTotalResults = a})
. mapping _Coerce
-- | The starting index of the resources, which is 1 by default or otherwise
-- specified by the start-index query parameter.
pfStartIndex :: Lens' ProFiles (Maybe Int32)
pfStartIndex
= lens _pfStartIndex (\ s a -> s{_pfStartIndex = a})
. mapping _Coerce
-- | Link to previous page for this view (profile) collection.
pfPreviousLink :: Lens' ProFiles (Maybe Text)
pfPreviousLink
= lens _pfPreviousLink
(\ s a -> s{_pfPreviousLink = a})
instance FromJSON ProFiles where
parseJSON
= withObject "ProFiles"
(\ o ->
ProFiles' <$>
(o .:? "nextLink") <*> (o .:? "itemsPerPage") <*>
(o .:? "kind" .!= "analytics#profiles")
<*> (o .:? "username")
<*> (o .:? "items" .!= mempty)
<*> (o .:? "totalResults")
<*> (o .:? "startIndex")
<*> (o .:? "previousLink"))
instance ToJSON ProFiles where
toJSON ProFiles'{..}
= object
(catMaybes
[("nextLink" .=) <$> _pfNextLink,
("itemsPerPage" .=) <$> _pfItemsPerPage,
Just ("kind" .= _pfKind),
("username" .=) <$> _pfUsername,
("items" .=) <$> _pfItems,
("totalResults" .=) <$> _pfTotalResults,
("startIndex" .=) <$> _pfStartIndex,
("previousLink" .=) <$> _pfPreviousLink])
-- | Request template for the delete upload data request.
--
-- /See:/ 'analyticsDataimportDeleteUploadDataRequest' smart constructor.
newtype AnalyticsDataimportDeleteUploadDataRequest =
AnalyticsDataimportDeleteUploadDataRequest'
{ _addudrCustomDataImportUids :: Maybe [Text]
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'AnalyticsDataimportDeleteUploadDataRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'addudrCustomDataImportUids'
analyticsDataimportDeleteUploadDataRequest
:: AnalyticsDataimportDeleteUploadDataRequest
analyticsDataimportDeleteUploadDataRequest =
AnalyticsDataimportDeleteUploadDataRequest'
{_addudrCustomDataImportUids = Nothing}
-- | A list of upload UIDs.
addudrCustomDataImportUids :: Lens' AnalyticsDataimportDeleteUploadDataRequest [Text]
addudrCustomDataImportUids
= lens _addudrCustomDataImportUids
(\ s a -> s{_addudrCustomDataImportUids = a})
. _Default
. _Coerce
instance FromJSON
AnalyticsDataimportDeleteUploadDataRequest
where
parseJSON
= withObject
"AnalyticsDataimportDeleteUploadDataRequest"
(\ o ->
AnalyticsDataimportDeleteUploadDataRequest' <$>
(o .:? "customDataImportUids" .!= mempty))
instance ToJSON
AnalyticsDataimportDeleteUploadDataRequest
where
toJSON
AnalyticsDataimportDeleteUploadDataRequest'{..}
= object
(catMaybes
[("customDataImportUids" .=) <$>
_addudrCustomDataImportUids])
-- | JSON template for Analytics Entity Google Ads Link.
--
-- /See:/ 'entityAdWordsLink' smart constructor.
data EntityAdWordsLink =
EntityAdWordsLink'
{ _entAdWordsAccounts :: !(Maybe [AdWordsAccount])
, _entProFileIds :: !(Maybe [Text])
, _entKind :: !Text
, _entSelfLink :: !(Maybe Text)
, _entName :: !(Maybe Text)
, _entId :: !(Maybe Text)
, _entEntity :: !(Maybe EntityAdWordsLinkEntity)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'EntityAdWordsLink' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'entAdWordsAccounts'
--
-- * 'entProFileIds'
--
-- * 'entKind'
--
-- * 'entSelfLink'
--
-- * 'entName'
--
-- * 'entId'
--
-- * 'entEntity'
entityAdWordsLink
:: EntityAdWordsLink
entityAdWordsLink =
EntityAdWordsLink'
{ _entAdWordsAccounts = Nothing
, _entProFileIds = Nothing
, _entKind = "analytics#entityAdWordsLink"
, _entSelfLink = Nothing
, _entName = Nothing
, _entId = Nothing
, _entEntity = Nothing
}
-- | A list of Google Ads client accounts. These cannot be MCC accounts. This
-- field is required when creating a Google Ads link. It cannot be empty.
entAdWordsAccounts :: Lens' EntityAdWordsLink [AdWordsAccount]
entAdWordsAccounts
= lens _entAdWordsAccounts
(\ s a -> s{_entAdWordsAccounts = a})
. _Default
. _Coerce
-- | IDs of linked Views (Profiles) represented as strings.
entProFileIds :: Lens' EntityAdWordsLink [Text]
entProFileIds
= lens _entProFileIds
(\ s a -> s{_entProFileIds = a})
. _Default
. _Coerce
-- | Resource type for entity Google Ads link.
entKind :: Lens' EntityAdWordsLink Text
entKind = lens _entKind (\ s a -> s{_entKind = a})
-- | URL link for this Google Analytics - Google Ads link.
entSelfLink :: Lens' EntityAdWordsLink (Maybe Text)
entSelfLink
= lens _entSelfLink (\ s a -> s{_entSelfLink = a})
-- | Name of the link. This field is required when creating a Google Ads
-- link.
entName :: Lens' EntityAdWordsLink (Maybe Text)
entName = lens _entName (\ s a -> s{_entName = a})
-- | Entity Google Ads link ID
entId :: Lens' EntityAdWordsLink (Maybe Text)
entId = lens _entId (\ s a -> s{_entId = a})
-- | Web property being linked.
entEntity :: Lens' EntityAdWordsLink (Maybe EntityAdWordsLinkEntity)
entEntity
= lens _entEntity (\ s a -> s{_entEntity = a})
instance FromJSON EntityAdWordsLink where
parseJSON
= withObject "EntityAdWordsLink"
(\ o ->
EntityAdWordsLink' <$>
(o .:? "adWordsAccounts" .!= mempty) <*>
(o .:? "profileIds" .!= mempty)
<*> (o .:? "kind" .!= "analytics#entityAdWordsLink")
<*> (o .:? "selfLink")
<*> (o .:? "name")
<*> (o .:? "id")
<*> (o .:? "entity"))
instance ToJSON EntityAdWordsLink where
toJSON EntityAdWordsLink'{..}
= object
(catMaybes
[("adWordsAccounts" .=) <$> _entAdWordsAccounts,
("profileIds" .=) <$> _entProFileIds,
Just ("kind" .= _entKind),
("selfLink" .=) <$> _entSelfLink,
("name" .=) <$> _entName, ("id" .=) <$> _entId,
("entity" .=) <$> _entEntity])
-- | Details for the filter of the type SEARCH_AND_REPLACE.
--
-- /See:/ 'filterSearchAndReplaceDetails' smart constructor.
data FilterSearchAndReplaceDetails =
FilterSearchAndReplaceDetails'
{ _fsardFieldIndex :: !(Maybe (Textual Int32))
, _fsardField :: !(Maybe Text)
, _fsardSearchString :: !(Maybe Text)
, _fsardReplaceString :: !(Maybe Text)
, _fsardCaseSensitive :: !(Maybe Bool)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'FilterSearchAndReplaceDetails' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'fsardFieldIndex'
--
-- * 'fsardField'
--
-- * 'fsardSearchString'
--
-- * 'fsardReplaceString'
--
-- * 'fsardCaseSensitive'
filterSearchAndReplaceDetails
:: FilterSearchAndReplaceDetails
filterSearchAndReplaceDetails =
FilterSearchAndReplaceDetails'
{ _fsardFieldIndex = Nothing
, _fsardField = Nothing
, _fsardSearchString = Nothing
, _fsardReplaceString = Nothing
, _fsardCaseSensitive = Nothing
}
-- | The Index of the custom dimension. Required if field is a
-- CUSTOM_DIMENSION.
fsardFieldIndex :: Lens' FilterSearchAndReplaceDetails (Maybe Int32)
fsardFieldIndex
= lens _fsardFieldIndex
(\ s a -> s{_fsardFieldIndex = a})
. mapping _Coerce
-- | Field to use in the filter.
fsardField :: Lens' FilterSearchAndReplaceDetails (Maybe Text)
fsardField
= lens _fsardField (\ s a -> s{_fsardField = a})
-- | Term to search.
fsardSearchString :: Lens' FilterSearchAndReplaceDetails (Maybe Text)
fsardSearchString
= lens _fsardSearchString
(\ s a -> s{_fsardSearchString = a})
-- | Term to replace the search term with.
fsardReplaceString :: Lens' FilterSearchAndReplaceDetails (Maybe Text)
fsardReplaceString
= lens _fsardReplaceString
(\ s a -> s{_fsardReplaceString = a})
-- | Determines if the filter is case sensitive.
fsardCaseSensitive :: Lens' FilterSearchAndReplaceDetails (Maybe Bool)
fsardCaseSensitive
= lens _fsardCaseSensitive
(\ s a -> s{_fsardCaseSensitive = a})
instance FromJSON FilterSearchAndReplaceDetails where
parseJSON
= withObject "FilterSearchAndReplaceDetails"
(\ o ->
FilterSearchAndReplaceDetails' <$>
(o .:? "fieldIndex") <*> (o .:? "field") <*>
(o .:? "searchString")
<*> (o .:? "replaceString")
<*> (o .:? "caseSensitive"))
instance ToJSON FilterSearchAndReplaceDetails where
toJSON FilterSearchAndReplaceDetails'{..}
= object
(catMaybes
[("fieldIndex" .=) <$> _fsardFieldIndex,
("field" .=) <$> _fsardField,
("searchString" .=) <$> _fsardSearchString,
("replaceString" .=) <$> _fsardReplaceString,
("caseSensitive" .=) <$> _fsardCaseSensitive])
-- | Permissions the user has for this view (profile).
--
-- /See:/ 'proFilePermissions' smart constructor.
newtype ProFilePermissions =
ProFilePermissions'
{ _pfpEffective :: Maybe [Text]
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProFilePermissions' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pfpEffective'
proFilePermissions
:: ProFilePermissions
proFilePermissions = ProFilePermissions' {_pfpEffective = Nothing}
-- | All the permissions that the user has for this view (profile). These
-- include any implied permissions (e.g., EDIT implies VIEW) or inherited
-- permissions from the parent web property.
pfpEffective :: Lens' ProFilePermissions [Text]
pfpEffective
= lens _pfpEffective (\ s a -> s{_pfpEffective = a})
. _Default
. _Coerce
instance FromJSON ProFilePermissions where
parseJSON
= withObject "ProFilePermissions"
(\ o ->
ProFilePermissions' <$>
(o .:? "effective" .!= mempty))
instance ToJSON ProFilePermissions where
toJSON ProFilePermissions'{..}
= object
(catMaybes [("effective" .=) <$> _pfpEffective])
-- | JSON template for an Analytics view (profile).
--
-- /See:/ 'proFile' smart constructor.
data ProFile =
ProFile'
{ _pParentLink :: !(Maybe ProFileParentLink)
, _pECommerceTracking :: !(Maybe Bool)
, _pSiteSearchCategoryParameters :: !(Maybe Text)
, _pWebPropertyId :: !(Maybe Text)
, _pChildLink :: !(Maybe ProFileChildLink)
, _pSiteSearchQueryParameters :: !(Maybe Text)
, _pKind :: !Text
, _pDefaultPage :: !(Maybe Text)
, _pCreated :: !(Maybe DateTime')
, _pSelfLink :: !(Maybe Text)
, _pAccountId :: !(Maybe Text)
, _pBotFilteringEnabled :: !(Maybe Bool)
, _pName :: !(Maybe Text)
, _pCurrency :: !(Maybe Text)
, _pStarred :: !(Maybe Bool)
, _pInternalWebPropertyId :: !(Maybe Text)
, _pId :: !(Maybe Text)
, _pUpdated :: !(Maybe DateTime')
, _pPermissions :: !(Maybe ProFilePermissions)
, _pWebsiteURL :: !(Maybe Text)
, _pType :: !(Maybe Text)
, _pStripSiteSearchCategoryParameters :: !(Maybe Bool)
, _pTimezone :: !(Maybe Text)
, _pExcludeQueryParameters :: !(Maybe Text)
, _pEnhancedECommerceTracking :: !(Maybe Bool)
, _pStripSiteSearchQueryParameters :: !(Maybe Bool)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProFile' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pParentLink'
--
-- * 'pECommerceTracking'
--
-- * 'pSiteSearchCategoryParameters'
--
-- * 'pWebPropertyId'
--
-- * 'pChildLink'
--
-- * 'pSiteSearchQueryParameters'
--
-- * 'pKind'
--
-- * 'pDefaultPage'
--
-- * 'pCreated'
--
-- * 'pSelfLink'
--
-- * 'pAccountId'
--
-- * 'pBotFilteringEnabled'
--
-- * 'pName'
--
-- * 'pCurrency'
--
-- * 'pStarred'
--
-- * 'pInternalWebPropertyId'
--
-- * 'pId'
--
-- * 'pUpdated'
--
-- * 'pPermissions'
--
-- * 'pWebsiteURL'
--
-- * 'pType'
--
-- * 'pStripSiteSearchCategoryParameters'
--
-- * 'pTimezone'
--
-- * 'pExcludeQueryParameters'
--
-- * 'pEnhancedECommerceTracking'
--
-- * 'pStripSiteSearchQueryParameters'
proFile
:: ProFile
proFile =
ProFile'
{ _pParentLink = Nothing
, _pECommerceTracking = Nothing
, _pSiteSearchCategoryParameters = Nothing
, _pWebPropertyId = Nothing
, _pChildLink = Nothing
, _pSiteSearchQueryParameters = Nothing
, _pKind = "analytics#profile"
, _pDefaultPage = Nothing
, _pCreated = Nothing
, _pSelfLink = Nothing
, _pAccountId = Nothing
, _pBotFilteringEnabled = Nothing
, _pName = Nothing
, _pCurrency = Nothing
, _pStarred = Nothing
, _pInternalWebPropertyId = Nothing
, _pId = Nothing
, _pUpdated = Nothing
, _pPermissions = Nothing
, _pWebsiteURL = Nothing
, _pType = Nothing
, _pStripSiteSearchCategoryParameters = Nothing
, _pTimezone = Nothing
, _pExcludeQueryParameters = Nothing
, _pEnhancedECommerceTracking = Nothing
, _pStripSiteSearchQueryParameters = Nothing
}
-- | Parent link for this view (profile). Points to the web property to which
-- this view (profile) belongs.
pParentLink :: Lens' ProFile (Maybe ProFileParentLink)
pParentLink
= lens _pParentLink (\ s a -> s{_pParentLink = a})
-- | Indicates whether ecommerce tracking is enabled for this view (profile).
pECommerceTracking :: Lens' ProFile (Maybe Bool)
pECommerceTracking
= lens _pECommerceTracking
(\ s a -> s{_pECommerceTracking = a})
-- | Site search category parameters for this view (profile).
pSiteSearchCategoryParameters :: Lens' ProFile (Maybe Text)
pSiteSearchCategoryParameters
= lens _pSiteSearchCategoryParameters
(\ s a -> s{_pSiteSearchCategoryParameters = a})
-- | Web property ID of the form UA-XXXXX-YY to which this view (profile)
-- belongs.
pWebPropertyId :: Lens' ProFile (Maybe Text)
pWebPropertyId
= lens _pWebPropertyId
(\ s a -> s{_pWebPropertyId = a})
-- | Child link for this view (profile). Points to the list of goals for this
-- view (profile).
pChildLink :: Lens' ProFile (Maybe ProFileChildLink)
pChildLink
= lens _pChildLink (\ s a -> s{_pChildLink = a})
-- | The site search query parameters for this view (profile).
pSiteSearchQueryParameters :: Lens' ProFile (Maybe Text)
pSiteSearchQueryParameters
= lens _pSiteSearchQueryParameters
(\ s a -> s{_pSiteSearchQueryParameters = a})
-- | Resource type for Analytics view (profile).
pKind :: Lens' ProFile Text
pKind = lens _pKind (\ s a -> s{_pKind = a})
-- | Default page for this view (profile).
pDefaultPage :: Lens' ProFile (Maybe Text)
pDefaultPage
= lens _pDefaultPage (\ s a -> s{_pDefaultPage = a})
-- | Time this view (profile) was created.
pCreated :: Lens' ProFile (Maybe UTCTime)
pCreated
= lens _pCreated (\ s a -> s{_pCreated = a}) .
mapping _DateTime
-- | Link for this view (profile).
pSelfLink :: Lens' ProFile (Maybe Text)
pSelfLink
= lens _pSelfLink (\ s a -> s{_pSelfLink = a})
-- | Account ID to which this view (profile) belongs.
pAccountId :: Lens' ProFile (Maybe Text)
pAccountId
= lens _pAccountId (\ s a -> s{_pAccountId = a})
-- | Indicates whether bot filtering is enabled for this view (profile).
pBotFilteringEnabled :: Lens' ProFile (Maybe Bool)
pBotFilteringEnabled
= lens _pBotFilteringEnabled
(\ s a -> s{_pBotFilteringEnabled = a})
-- | Name of this view (profile).
pName :: Lens' ProFile (Maybe Text)
pName = lens _pName (\ s a -> s{_pName = a})
-- | The currency type associated with this view (profile), defaults to USD.
-- The supported values are: USD, JPY, EUR, GBP, AUD, KRW, BRL, CNY, DKK,
-- RUB, SEK, NOK, PLN, TRY, TWD, HKD, THB, IDR, ARS, MXN, VND, PHP, INR,
-- CHF, CAD, CZK, NZD, HUF, BGN, LTL, ZAR, UAH, AED, BOB, CLP, COP, EGP,
-- HRK, ILS, MAD, MYR, PEN, PKR, RON, RSD, SAR, SGD, VEF, LVL
pCurrency :: Lens' ProFile (Maybe Text)
pCurrency
= lens _pCurrency (\ s a -> s{_pCurrency = a})
-- | Indicates whether this view (profile) is starred or not.
pStarred :: Lens' ProFile (Maybe Bool)
pStarred = lens _pStarred (\ s a -> s{_pStarred = a})
-- | Internal ID for the web property to which this view (profile) belongs.
pInternalWebPropertyId :: Lens' ProFile (Maybe Text)
pInternalWebPropertyId
= lens _pInternalWebPropertyId
(\ s a -> s{_pInternalWebPropertyId = a})
-- | View (Profile) ID.
pId :: Lens' ProFile (Maybe Text)
pId = lens _pId (\ s a -> s{_pId = a})
-- | Time this view (profile) was last modified.
pUpdated :: Lens' ProFile (Maybe UTCTime)
pUpdated
= lens _pUpdated (\ s a -> s{_pUpdated = a}) .
mapping _DateTime
-- | Permissions the user has for this view (profile).
pPermissions :: Lens' ProFile (Maybe ProFilePermissions)
pPermissions
= lens _pPermissions (\ s a -> s{_pPermissions = a})
-- | Website URL for this view (profile).
pWebsiteURL :: Lens' ProFile (Maybe Text)
pWebsiteURL
= lens _pWebsiteURL (\ s a -> s{_pWebsiteURL = a})
-- | View (Profile) type. Supported types: WEB or APP.
pType :: Lens' ProFile (Maybe Text)
pType = lens _pType (\ s a -> s{_pType = a})
-- | Whether or not Analytics will strip search category parameters from the
-- URLs in your reports.
pStripSiteSearchCategoryParameters :: Lens' ProFile (Maybe Bool)
pStripSiteSearchCategoryParameters
= lens _pStripSiteSearchCategoryParameters
(\ s a -> s{_pStripSiteSearchCategoryParameters = a})
-- | Time zone for which this view (profile) has been configured. Time zones
-- are identified by strings from the TZ database.
pTimezone :: Lens' ProFile (Maybe Text)
pTimezone
= lens _pTimezone (\ s a -> s{_pTimezone = a})
-- | The query parameters that are excluded from this view (profile).
pExcludeQueryParameters :: Lens' ProFile (Maybe Text)
pExcludeQueryParameters
= lens _pExcludeQueryParameters
(\ s a -> s{_pExcludeQueryParameters = a})
-- | Indicates whether enhanced ecommerce tracking is enabled for this view
-- (profile). This property can only be enabled if ecommerce tracking is
-- enabled.
pEnhancedECommerceTracking :: Lens' ProFile (Maybe Bool)
pEnhancedECommerceTracking
= lens _pEnhancedECommerceTracking
(\ s a -> s{_pEnhancedECommerceTracking = a})
-- | Whether or not Analytics will strip search query parameters from the
-- URLs in your reports.
pStripSiteSearchQueryParameters :: Lens' ProFile (Maybe Bool)
pStripSiteSearchQueryParameters
= lens _pStripSiteSearchQueryParameters
(\ s a -> s{_pStripSiteSearchQueryParameters = a})
instance FromJSON ProFile where
parseJSON
= withObject "ProFile"
(\ o ->
ProFile' <$>
(o .:? "parentLink") <*> (o .:? "eCommerceTracking")
<*> (o .:? "siteSearchCategoryParameters")
<*> (o .:? "webPropertyId")
<*> (o .:? "childLink")
<*> (o .:? "siteSearchQueryParameters")
<*> (o .:? "kind" .!= "analytics#profile")
<*> (o .:? "defaultPage")
<*> (o .:? "created")
<*> (o .:? "selfLink")
<*> (o .:? "accountId")
<*> (o .:? "botFilteringEnabled")
<*> (o .:? "name")
<*> (o .:? "currency")
<*> (o .:? "starred")
<*> (o .:? "internalWebPropertyId")
<*> (o .:? "id")
<*> (o .:? "updated")
<*> (o .:? "permissions")
<*> (o .:? "websiteUrl")
<*> (o .:? "type")
<*> (o .:? "stripSiteSearchCategoryParameters")
<*> (o .:? "timezone")
<*> (o .:? "excludeQueryParameters")
<*> (o .:? "enhancedECommerceTracking")
<*> (o .:? "stripSiteSearchQueryParameters"))
instance ToJSON ProFile where
toJSON ProFile'{..}
= object
(catMaybes
[("parentLink" .=) <$> _pParentLink,
("eCommerceTracking" .=) <$> _pECommerceTracking,
("siteSearchCategoryParameters" .=) <$>
_pSiteSearchCategoryParameters,
("webPropertyId" .=) <$> _pWebPropertyId,
("childLink" .=) <$> _pChildLink,
("siteSearchQueryParameters" .=) <$>
_pSiteSearchQueryParameters,
Just ("kind" .= _pKind),
("defaultPage" .=) <$> _pDefaultPage,
("created" .=) <$> _pCreated,
("selfLink" .=) <$> _pSelfLink,
("accountId" .=) <$> _pAccountId,
("botFilteringEnabled" .=) <$> _pBotFilteringEnabled,
("name" .=) <$> _pName,
("currency" .=) <$> _pCurrency,
("starred" .=) <$> _pStarred,
("internalWebPropertyId" .=) <$>
_pInternalWebPropertyId,
("id" .=) <$> _pId, ("updated" .=) <$> _pUpdated,
("permissions" .=) <$> _pPermissions,
("websiteUrl" .=) <$> _pWebsiteURL,
("type" .=) <$> _pType,
("stripSiteSearchCategoryParameters" .=) <$>
_pStripSiteSearchCategoryParameters,
("timezone" .=) <$> _pTimezone,
("excludeQueryParameters" .=) <$>
_pExcludeQueryParameters,
("enhancedECommerceTracking" .=) <$>
_pEnhancedECommerceTracking,
("stripSiteSearchQueryParameters" .=) <$>
_pStripSiteSearchQueryParameters])
-- | An AccountSummary collection lists a summary of accounts, properties and
-- views (profiles) to which the user has access. Each resource in the
-- collection corresponds to a single AccountSummary.
--
-- /See:/ 'accountSummaries' smart constructor.
data AccountSummaries =
AccountSummaries'
{ _asNextLink :: !(Maybe Text)
, _asItemsPerPage :: !(Maybe (Textual Int32))
, _asKind :: !Text
, _asUsername :: !(Maybe Text)
, _asItems :: !(Maybe [AccountSummary])
, _asTotalResults :: !(Maybe (Textual Int32))
, _asStartIndex :: !(Maybe (Textual Int32))
, _asPreviousLink :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'AccountSummaries' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'asNextLink'
--
-- * 'asItemsPerPage'
--
-- * 'asKind'
--
-- * 'asUsername'
--
-- * 'asItems'
--
-- * 'asTotalResults'
--
-- * 'asStartIndex'
--
-- * 'asPreviousLink'
accountSummaries
:: AccountSummaries
accountSummaries =
AccountSummaries'
{ _asNextLink = Nothing
, _asItemsPerPage = Nothing
, _asKind = "analytics#accountSummaries"
, _asUsername = Nothing
, _asItems = Nothing
, _asTotalResults = Nothing
, _asStartIndex = Nothing
, _asPreviousLink = Nothing
}
-- | Link to next page for this AccountSummary collection.
asNextLink :: Lens' AccountSummaries (Maybe Text)
asNextLink
= lens _asNextLink (\ s a -> s{_asNextLink = a})
-- | The maximum number of resources the response can contain, regardless of
-- the actual number of resources returned. Its value ranges from 1 to 1000
-- with a value of 1000 by default, or otherwise specified by the
-- max-results query parameter.
asItemsPerPage :: Lens' AccountSummaries (Maybe Int32)
asItemsPerPage
= lens _asItemsPerPage
(\ s a -> s{_asItemsPerPage = a})
. mapping _Coerce
-- | Collection type.
asKind :: Lens' AccountSummaries Text
asKind = lens _asKind (\ s a -> s{_asKind = a})
-- | Email ID of the authenticated user
asUsername :: Lens' AccountSummaries (Maybe Text)
asUsername
= lens _asUsername (\ s a -> s{_asUsername = a})
-- | A list of AccountSummaries.
asItems :: Lens' AccountSummaries [AccountSummary]
asItems
= lens _asItems (\ s a -> s{_asItems = a}) . _Default
. _Coerce
-- | The total number of results for the query, regardless of the number of
-- results in the response.
asTotalResults :: Lens' AccountSummaries (Maybe Int32)
asTotalResults
= lens _asTotalResults
(\ s a -> s{_asTotalResults = a})
. mapping _Coerce
-- | The starting index of the resources, which is 1 by default or otherwise
-- specified by the start-index query parameter.
asStartIndex :: Lens' AccountSummaries (Maybe Int32)
asStartIndex
= lens _asStartIndex (\ s a -> s{_asStartIndex = a})
. mapping _Coerce
-- | Link to previous page for this AccountSummary collection.
asPreviousLink :: Lens' AccountSummaries (Maybe Text)
asPreviousLink
= lens _asPreviousLink
(\ s a -> s{_asPreviousLink = a})
instance FromJSON AccountSummaries where
parseJSON
= withObject "AccountSummaries"
(\ o ->
AccountSummaries' <$>
(o .:? "nextLink") <*> (o .:? "itemsPerPage") <*>
(o .:? "kind" .!= "analytics#accountSummaries")
<*> (o .:? "username")
<*> (o .:? "items" .!= mempty)
<*> (o .:? "totalResults")
<*> (o .:? "startIndex")
<*> (o .:? "previousLink"))
instance ToJSON AccountSummaries where
toJSON AccountSummaries'{..}
= object
(catMaybes
[("nextLink" .=) <$> _asNextLink,
("itemsPerPage" .=) <$> _asItemsPerPage,
Just ("kind" .= _asKind),
("username" .=) <$> _asUsername,
("items" .=) <$> _asItems,
("totalResults" .=) <$> _asTotalResults,
("startIndex" .=) <$> _asStartIndex,
("previousLink" .=) <$> _asPreviousLink])
-- | Details for the goal of the type EVENT.
--
-- /See:/ 'goalEventDetails' smart constructor.
data GoalEventDetails =
GoalEventDetails'
{ _gedUseEventValue :: !(Maybe Bool)
, _gedEventConditions :: !(Maybe [GoalEventDetailsEventConditionsItem])
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'GoalEventDetails' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gedUseEventValue'
--
-- * 'gedEventConditions'
goalEventDetails
:: GoalEventDetails
goalEventDetails =
GoalEventDetails' {_gedUseEventValue = Nothing, _gedEventConditions = Nothing}
-- | Determines if the event value should be used as the value for this goal.
gedUseEventValue :: Lens' GoalEventDetails (Maybe Bool)
gedUseEventValue
= lens _gedUseEventValue
(\ s a -> s{_gedUseEventValue = a})
-- | List of event conditions.
gedEventConditions :: Lens' GoalEventDetails [GoalEventDetailsEventConditionsItem]
gedEventConditions
= lens _gedEventConditions
(\ s a -> s{_gedEventConditions = a})
. _Default
. _Coerce
instance FromJSON GoalEventDetails where
parseJSON
= withObject "GoalEventDetails"
(\ o ->
GoalEventDetails' <$>
(o .:? "useEventValue") <*>
(o .:? "eventConditions" .!= mempty))
instance ToJSON GoalEventDetails where
toJSON GoalEventDetails'{..}
= object
(catMaybes
[("useEventValue" .=) <$> _gedUseEventValue,
("eventConditions" .=) <$> _gedEventConditions])
-- | JSON template for an Analytics WebPropertySummary. WebPropertySummary
-- returns basic information (i.e., summary) for a web property.
--
-- /See:/ 'webPropertySummary' smart constructor.
data WebPropertySummary =
WebPropertySummary'
{ _wpsKind :: !Text
, _wpsProFiles :: !(Maybe [ProFileSummary])
, _wpsName :: !(Maybe Text)
, _wpsStarred :: !(Maybe Bool)
, _wpsInternalWebPropertyId :: !(Maybe Text)
, _wpsId :: !(Maybe Text)
, _wpsWebsiteURL :: !(Maybe Text)
, _wpsLevel :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'WebPropertySummary' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'wpsKind'
--
-- * 'wpsProFiles'
--
-- * 'wpsName'
--
-- * 'wpsStarred'
--
-- * 'wpsInternalWebPropertyId'
--
-- * 'wpsId'
--
-- * 'wpsWebsiteURL'
--
-- * 'wpsLevel'
webPropertySummary
:: WebPropertySummary
webPropertySummary =
WebPropertySummary'
{ _wpsKind = "analytics#webPropertySummary"
, _wpsProFiles = Nothing
, _wpsName = Nothing
, _wpsStarred = Nothing
, _wpsInternalWebPropertyId = Nothing
, _wpsId = Nothing
, _wpsWebsiteURL = Nothing
, _wpsLevel = Nothing
}
-- | Resource type for Analytics WebPropertySummary.
wpsKind :: Lens' WebPropertySummary Text
wpsKind = lens _wpsKind (\ s a -> s{_wpsKind = a})
-- | List of profiles under this web property.
wpsProFiles :: Lens' WebPropertySummary [ProFileSummary]
wpsProFiles
= lens _wpsProFiles (\ s a -> s{_wpsProFiles = a}) .
_Default
. _Coerce
-- | Web property name.
wpsName :: Lens' WebPropertySummary (Maybe Text)
wpsName = lens _wpsName (\ s a -> s{_wpsName = a})
-- | Indicates whether this web property is starred or not.
wpsStarred :: Lens' WebPropertySummary (Maybe Bool)
wpsStarred
= lens _wpsStarred (\ s a -> s{_wpsStarred = a})
-- | Internal ID for this web property.
wpsInternalWebPropertyId :: Lens' WebPropertySummary (Maybe Text)
wpsInternalWebPropertyId
= lens _wpsInternalWebPropertyId
(\ s a -> s{_wpsInternalWebPropertyId = a})
-- | Web property ID of the form UA-XXXXX-YY.
wpsId :: Lens' WebPropertySummary (Maybe Text)
wpsId = lens _wpsId (\ s a -> s{_wpsId = a})
-- | Website url for this web property.
wpsWebsiteURL :: Lens' WebPropertySummary (Maybe Text)
wpsWebsiteURL
= lens _wpsWebsiteURL
(\ s a -> s{_wpsWebsiteURL = a})
-- | Level for this web property. Possible values are STANDARD or PREMIUM.
wpsLevel :: Lens' WebPropertySummary (Maybe Text)
wpsLevel = lens _wpsLevel (\ s a -> s{_wpsLevel = a})
instance FromJSON WebPropertySummary where
parseJSON
= withObject "WebPropertySummary"
(\ o ->
WebPropertySummary' <$>
(o .:? "kind" .!= "analytics#webPropertySummary") <*>
(o .:? "profiles" .!= mempty)
<*> (o .:? "name")
<*> (o .:? "starred")
<*> (o .:? "internalWebPropertyId")
<*> (o .:? "id")
<*> (o .:? "websiteUrl")
<*> (o .:? "level"))
instance ToJSON WebPropertySummary where
toJSON WebPropertySummary'{..}
= object
(catMaybes
[Just ("kind" .= _wpsKind),
("profiles" .=) <$> _wpsProFiles,
("name" .=) <$> _wpsName,
("starred" .=) <$> _wpsStarred,
("internalWebPropertyId" .=) <$>
_wpsInternalWebPropertyId,
("id" .=) <$> _wpsId,
("websiteUrl" .=) <$> _wpsWebsiteURL,
("level" .=) <$> _wpsLevel])
-- | A filter collection lists filters created by users in an Analytics
-- account. Each resource in the collection corresponds to a filter.
--
-- /See:/ 'filters' smart constructor.
data Filters =
Filters'
{ _fNextLink :: !(Maybe Text)
, _fItemsPerPage :: !(Maybe (Textual Int32))
, _fKind :: !Text
, _fUsername :: !(Maybe Text)
, _fItems :: !(Maybe [Filter])
, _fTotalResults :: !(Maybe (Textual Int32))
, _fStartIndex :: !(Maybe (Textual Int32))
, _fPreviousLink :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Filters' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'fNextLink'
--
-- * 'fItemsPerPage'
--
-- * 'fKind'
--
-- * 'fUsername'
--
-- * 'fItems'
--
-- * 'fTotalResults'
--
-- * 'fStartIndex'
--
-- * 'fPreviousLink'
filters
:: Filters
filters =
Filters'
{ _fNextLink = Nothing
, _fItemsPerPage = Nothing
, _fKind = "analytics#filters"
, _fUsername = Nothing
, _fItems = Nothing
, _fTotalResults = Nothing
, _fStartIndex = Nothing
, _fPreviousLink = Nothing
}
-- | Link to next page for this filter collection.
fNextLink :: Lens' Filters (Maybe Text)
fNextLink
= lens _fNextLink (\ s a -> s{_fNextLink = a})
-- | The maximum number of resources the response can contain, regardless of
-- the actual number of resources returned. Its value ranges from 1 to
-- 1,000 with a value of 1000 by default, or otherwise specified by the
-- max-results query parameter.
fItemsPerPage :: Lens' Filters (Maybe Int32)
fItemsPerPage
= lens _fItemsPerPage
(\ s a -> s{_fItemsPerPage = a})
. mapping _Coerce
-- | Collection type.
fKind :: Lens' Filters Text
fKind = lens _fKind (\ s a -> s{_fKind = a})
-- | Email ID of the authenticated user
fUsername :: Lens' Filters (Maybe Text)
fUsername
= lens _fUsername (\ s a -> s{_fUsername = a})
-- | A list of filters.
fItems :: Lens' Filters [Filter]
fItems
= lens _fItems (\ s a -> s{_fItems = a}) . _Default .
_Coerce
-- | The total number of results for the query, regardless of the number of
-- results in the response.
fTotalResults :: Lens' Filters (Maybe Int32)
fTotalResults
= lens _fTotalResults
(\ s a -> s{_fTotalResults = a})
. mapping _Coerce
-- | The starting index of the resources, which is 1 by default or otherwise
-- specified by the start-index query parameter.
fStartIndex :: Lens' Filters (Maybe Int32)
fStartIndex
= lens _fStartIndex (\ s a -> s{_fStartIndex = a}) .
mapping _Coerce
-- | Link to previous page for this filter collection.
fPreviousLink :: Lens' Filters (Maybe Text)
fPreviousLink
= lens _fPreviousLink
(\ s a -> s{_fPreviousLink = a})
instance FromJSON Filters where
parseJSON
= withObject "Filters"
(\ o ->
Filters' <$>
(o .:? "nextLink") <*> (o .:? "itemsPerPage") <*>
(o .:? "kind" .!= "analytics#filters")
<*> (o .:? "username")
<*> (o .:? "items" .!= mempty)
<*> (o .:? "totalResults")
<*> (o .:? "startIndex")
<*> (o .:? "previousLink"))
instance ToJSON Filters where
toJSON Filters'{..}
= object
(catMaybes
[("nextLink" .=) <$> _fNextLink,
("itemsPerPage" .=) <$> _fItemsPerPage,
Just ("kind" .= _fKind),
("username" .=) <$> _fUsername,
("items" .=) <$> _fItems,
("totalResults" .=) <$> _fTotalResults,
("startIndex" .=) <$> _fStartIndex,
("previousLink" .=) <$> _fPreviousLink])
-- | Analytics data for a given view (profile).
--
-- /See:/ 'gaData' smart constructor.
data GaData =
GaData'
{ _gdNextLink :: !(Maybe Text)
, _gdSampleSpace :: !(Maybe (Textual Int64))
, _gdItemsPerPage :: !(Maybe (Textual Int32))
, _gdProFileInfo :: !(Maybe GaDataProFileInfo)
, _gdKind :: !Text
, _gdSampleSize :: !(Maybe (Textual Int64))
, _gdRows :: !(Maybe [[Text]])
, _gdSelfLink :: !(Maybe Text)
, _gdQuery :: !(Maybe GaDataQuery)
, _gdColumnHeaders :: !(Maybe [GaDataColumnHeadersItem])
, _gdId :: !(Maybe Text)
, _gdTotalResults :: !(Maybe (Textual Int32))
, _gdDataLastRefreshed :: !(Maybe (Textual Int64))
, _gdDataTable :: !(Maybe GaDataDataTable)
, _gdContainsSampledData :: !(Maybe Bool)
, _gdTotalsForAllResults :: !(Maybe GaDataTotalsForAllResults)
, _gdPreviousLink :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'GaData' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gdNextLink'
--
-- * 'gdSampleSpace'
--
-- * 'gdItemsPerPage'
--
-- * 'gdProFileInfo'
--
-- * 'gdKind'
--
-- * 'gdSampleSize'
--
-- * 'gdRows'
--
-- * 'gdSelfLink'
--
-- * 'gdQuery'
--
-- * 'gdColumnHeaders'
--
-- * 'gdId'
--
-- * 'gdTotalResults'
--
-- * 'gdDataLastRefreshed'
--
-- * 'gdDataTable'
--
-- * 'gdContainsSampledData'
--
-- * 'gdTotalsForAllResults'
--
-- * 'gdPreviousLink'
gaData
:: GaData
gaData =
GaData'
{ _gdNextLink = Nothing
, _gdSampleSpace = Nothing
, _gdItemsPerPage = Nothing
, _gdProFileInfo = Nothing
, _gdKind = "analytics#gaData"
, _gdSampleSize = Nothing
, _gdRows = Nothing
, _gdSelfLink = Nothing
, _gdQuery = Nothing
, _gdColumnHeaders = Nothing
, _gdId = Nothing
, _gdTotalResults = Nothing
, _gdDataLastRefreshed = Nothing
, _gdDataTable = Nothing
, _gdContainsSampledData = Nothing
, _gdTotalsForAllResults = Nothing
, _gdPreviousLink = Nothing
}
-- | Link to next page for this Analytics data query.
gdNextLink :: Lens' GaData (Maybe Text)
gdNextLink
= lens _gdNextLink (\ s a -> s{_gdNextLink = a})
-- | Total size of the sample space from which the samples were selected.
gdSampleSpace :: Lens' GaData (Maybe Int64)
gdSampleSpace
= lens _gdSampleSpace
(\ s a -> s{_gdSampleSpace = a})
. mapping _Coerce
-- | The maximum number of rows the response can contain, regardless of the
-- actual number of rows returned. Its value ranges from 1 to 10,000 with a
-- value of 1000 by default, or otherwise specified by the max-results
-- query parameter.
gdItemsPerPage :: Lens' GaData (Maybe Int32)
gdItemsPerPage
= lens _gdItemsPerPage
(\ s a -> s{_gdItemsPerPage = a})
. mapping _Coerce
-- | Information for the view (profile), for which the Analytics data was
-- requested.
gdProFileInfo :: Lens' GaData (Maybe GaDataProFileInfo)
gdProFileInfo
= lens _gdProFileInfo
(\ s a -> s{_gdProFileInfo = a})
-- | Resource type.
gdKind :: Lens' GaData Text
gdKind = lens _gdKind (\ s a -> s{_gdKind = a})
-- | The number of samples used to calculate the result.
gdSampleSize :: Lens' GaData (Maybe Int64)
gdSampleSize
= lens _gdSampleSize (\ s a -> s{_gdSampleSize = a})
. mapping _Coerce
-- | Analytics data rows, where each row contains a list of dimension values
-- followed by the metric values. The order of dimensions and metrics is
-- same as specified in the request.
gdRows :: Lens' GaData [[Text]]
gdRows
= lens _gdRows (\ s a -> s{_gdRows = a}) . _Default .
_Coerce
-- | Link to this page.
gdSelfLink :: Lens' GaData (Maybe Text)
gdSelfLink
= lens _gdSelfLink (\ s a -> s{_gdSelfLink = a})
-- | Analytics data request query parameters.
gdQuery :: Lens' GaData (Maybe GaDataQuery)
gdQuery = lens _gdQuery (\ s a -> s{_gdQuery = a})
-- | Column headers that list dimension names followed by the metric names.
-- The order of dimensions and metrics is same as specified in the request.
gdColumnHeaders :: Lens' GaData [GaDataColumnHeadersItem]
gdColumnHeaders
= lens _gdColumnHeaders
(\ s a -> s{_gdColumnHeaders = a})
. _Default
. _Coerce
-- | Unique ID for this data response.
gdId :: Lens' GaData (Maybe Text)
gdId = lens _gdId (\ s a -> s{_gdId = a})
-- | The total number of rows for the query, regardless of the number of rows
-- in the response.
gdTotalResults :: Lens' GaData (Maybe Int32)
gdTotalResults
= lens _gdTotalResults
(\ s a -> s{_gdTotalResults = a})
. mapping _Coerce
-- | The last refreshed time in seconds for Analytics data.
gdDataLastRefreshed :: Lens' GaData (Maybe Int64)
gdDataLastRefreshed
= lens _gdDataLastRefreshed
(\ s a -> s{_gdDataLastRefreshed = a})
. mapping _Coerce
gdDataTable :: Lens' GaData (Maybe GaDataDataTable)
gdDataTable
= lens _gdDataTable (\ s a -> s{_gdDataTable = a})
-- | Determines if Analytics data contains samples.
gdContainsSampledData :: Lens' GaData (Maybe Bool)
gdContainsSampledData
= lens _gdContainsSampledData
(\ s a -> s{_gdContainsSampledData = a})
-- | Total values for the requested metrics over all the results, not just
-- the results returned in this response. The order of the metric totals is
-- same as the metric order specified in the request.
gdTotalsForAllResults :: Lens' GaData (Maybe GaDataTotalsForAllResults)
gdTotalsForAllResults
= lens _gdTotalsForAllResults
(\ s a -> s{_gdTotalsForAllResults = a})
-- | Link to previous page for this Analytics data query.
gdPreviousLink :: Lens' GaData (Maybe Text)
gdPreviousLink
= lens _gdPreviousLink
(\ s a -> s{_gdPreviousLink = a})
instance FromJSON GaData where
parseJSON
= withObject "GaData"
(\ o ->
GaData' <$>
(o .:? "nextLink") <*> (o .:? "sampleSpace") <*>
(o .:? "itemsPerPage")
<*> (o .:? "profileInfo")
<*> (o .:? "kind" .!= "analytics#gaData")
<*> (o .:? "sampleSize")
<*> (o .:? "rows" .!= mempty)
<*> (o .:? "selfLink")
<*> (o .:? "query")
<*> (o .:? "columnHeaders" .!= mempty)
<*> (o .:? "id")
<*> (o .:? "totalResults")
<*> (o .:? "dataLastRefreshed")
<*> (o .:? "dataTable")
<*> (o .:? "containsSampledData")
<*> (o .:? "totalsForAllResults")
<*> (o .:? "previousLink"))
instance ToJSON GaData where
toJSON GaData'{..}
= object
(catMaybes
[("nextLink" .=) <$> _gdNextLink,
("sampleSpace" .=) <$> _gdSampleSpace,
("itemsPerPage" .=) <$> _gdItemsPerPage,
("profileInfo" .=) <$> _gdProFileInfo,
Just ("kind" .= _gdKind),
("sampleSize" .=) <$> _gdSampleSize,
("rows" .=) <$> _gdRows,
("selfLink" .=) <$> _gdSelfLink,
("query" .=) <$> _gdQuery,
("columnHeaders" .=) <$> _gdColumnHeaders,
("id" .=) <$> _gdId,
("totalResults" .=) <$> _gdTotalResults,
("dataLastRefreshed" .=) <$> _gdDataLastRefreshed,
("dataTable" .=) <$> _gdDataTable,
("containsSampledData" .=) <$>
_gdContainsSampledData,
("totalsForAllResults" .=) <$>
_gdTotalsForAllResults,
("previousLink" .=) <$> _gdPreviousLink])
-- | Total values for the requested metrics over all the results, not just
-- the results returned in this response. The order of the metric totals is
-- same as the metric order specified in the request.
--
-- /See:/ 'realtimeDataTotalsForAllResults' smart constructor.
newtype RealtimeDataTotalsForAllResults =
RealtimeDataTotalsForAllResults'
{ _rdtfarAddtional :: HashMap Text Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'RealtimeDataTotalsForAllResults' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'rdtfarAddtional'
realtimeDataTotalsForAllResults
:: HashMap Text Text -- ^ 'rdtfarAddtional'
-> RealtimeDataTotalsForAllResults
realtimeDataTotalsForAllResults pRdtfarAddtional_ =
RealtimeDataTotalsForAllResults'
{_rdtfarAddtional = _Coerce # pRdtfarAddtional_}
-- | Key-value pair for the total value of a metric. Key is the metric name
-- and the value is the total value for that metric.
rdtfarAddtional :: Lens' RealtimeDataTotalsForAllResults (HashMap Text Text)
rdtfarAddtional
= lens _rdtfarAddtional
(\ s a -> s{_rdtfarAddtional = a})
. _Coerce
instance FromJSON RealtimeDataTotalsForAllResults
where
parseJSON
= withObject "RealtimeDataTotalsForAllResults"
(\ o ->
RealtimeDataTotalsForAllResults' <$>
(parseJSONObject o))
instance ToJSON RealtimeDataTotalsForAllResults where
toJSON = toJSON . _rdtfarAddtional
-- | JSON template for an Analytics custom data source.
--
-- /See:/ 'customDataSource' smart constructor.
data CustomDataSource =
CustomDataSource'
{ _cParentLink :: !(Maybe CustomDataSourceParentLink)
, _cWebPropertyId :: !(Maybe Text)
, _cChildLink :: !(Maybe CustomDataSourceChildLink)
, _cKind :: !Text
, _cCreated :: !(Maybe DateTime')
, _cUploadType :: !(Maybe Text)
, _cSchema :: !(Maybe [Text])
, _cImportBehavior :: !(Maybe Text)
, _cSelfLink :: !(Maybe Text)
, _cAccountId :: !(Maybe Text)
, _cName :: !(Maybe Text)
, _cId :: !(Maybe Text)
, _cUpdated :: !(Maybe DateTime')
, _cType :: !(Maybe Text)
, _cDescription :: !(Maybe Text)
, _cProFilesLinked :: !(Maybe [Text])
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'CustomDataSource' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cParentLink'
--
-- * 'cWebPropertyId'
--
-- * 'cChildLink'
--
-- * 'cKind'
--
-- * 'cCreated'
--
-- * 'cUploadType'
--
-- * 'cSchema'
--
-- * 'cImportBehavior'
--
-- * 'cSelfLink'
--
-- * 'cAccountId'
--
-- * 'cName'
--
-- * 'cId'
--
-- * 'cUpdated'
--
-- * 'cType'
--
-- * 'cDescription'
--
-- * 'cProFilesLinked'
customDataSource
:: CustomDataSource
customDataSource =
CustomDataSource'
{ _cParentLink = Nothing
, _cWebPropertyId = Nothing
, _cChildLink = Nothing
, _cKind = "analytics#customDataSource"
, _cCreated = Nothing
, _cUploadType = Nothing
, _cSchema = Nothing
, _cImportBehavior = Nothing
, _cSelfLink = Nothing
, _cAccountId = Nothing
, _cName = Nothing
, _cId = Nothing
, _cUpdated = Nothing
, _cType = Nothing
, _cDescription = Nothing
, _cProFilesLinked = Nothing
}
-- | Parent link for this custom data source. Points to the web property to
-- which this custom data source belongs.
cParentLink :: Lens' CustomDataSource (Maybe CustomDataSourceParentLink)
cParentLink
= lens _cParentLink (\ s a -> s{_cParentLink = a})
-- | Web property ID of the form UA-XXXXX-YY to which this custom data source
-- belongs.
cWebPropertyId :: Lens' CustomDataSource (Maybe Text)
cWebPropertyId
= lens _cWebPropertyId
(\ s a -> s{_cWebPropertyId = a})
cChildLink :: Lens' CustomDataSource (Maybe CustomDataSourceChildLink)
cChildLink
= lens _cChildLink (\ s a -> s{_cChildLink = a})
-- | Resource type for Analytics custom data source.
cKind :: Lens' CustomDataSource Text
cKind = lens _cKind (\ s a -> s{_cKind = a})
-- | Time this custom data source was created.
cCreated :: Lens' CustomDataSource (Maybe UTCTime)
cCreated
= lens _cCreated (\ s a -> s{_cCreated = a}) .
mapping _DateTime
-- | Upload type of the custom data source.
cUploadType :: Lens' CustomDataSource (Maybe Text)
cUploadType
= lens _cUploadType (\ s a -> s{_cUploadType = a})
-- | Collection of schema headers of the custom data source.
cSchema :: Lens' CustomDataSource [Text]
cSchema
= lens _cSchema (\ s a -> s{_cSchema = a}) . _Default
. _Coerce
cImportBehavior :: Lens' CustomDataSource (Maybe Text)
cImportBehavior
= lens _cImportBehavior
(\ s a -> s{_cImportBehavior = a})
-- | Link for this Analytics custom data source.
cSelfLink :: Lens' CustomDataSource (Maybe Text)
cSelfLink
= lens _cSelfLink (\ s a -> s{_cSelfLink = a})
-- | Account ID to which this custom data source belongs.
cAccountId :: Lens' CustomDataSource (Maybe Text)
cAccountId
= lens _cAccountId (\ s a -> s{_cAccountId = a})
-- | Name of this custom data source.
cName :: Lens' CustomDataSource (Maybe Text)
cName = lens _cName (\ s a -> s{_cName = a})
-- | Custom data source ID.
cId :: Lens' CustomDataSource (Maybe Text)
cId = lens _cId (\ s a -> s{_cId = a})
-- | Time this custom data source was last modified.
cUpdated :: Lens' CustomDataSource (Maybe UTCTime)
cUpdated
= lens _cUpdated (\ s a -> s{_cUpdated = a}) .
mapping _DateTime
-- | Type of the custom data source.
cType :: Lens' CustomDataSource (Maybe Text)
cType = lens _cType (\ s a -> s{_cType = a})
-- | Description of custom data source.
cDescription :: Lens' CustomDataSource (Maybe Text)
cDescription
= lens _cDescription (\ s a -> s{_cDescription = a})
-- | IDs of views (profiles) linked to the custom data source.
cProFilesLinked :: Lens' CustomDataSource [Text]
cProFilesLinked
= lens _cProFilesLinked
(\ s a -> s{_cProFilesLinked = a})
. _Default
. _Coerce
instance FromJSON CustomDataSource where
parseJSON
= withObject "CustomDataSource"
(\ o ->
CustomDataSource' <$>
(o .:? "parentLink") <*> (o .:? "webPropertyId") <*>
(o .:? "childLink")
<*> (o .:? "kind" .!= "analytics#customDataSource")
<*> (o .:? "created")
<*> (o .:? "uploadType")
<*> (o .:? "schema" .!= mempty)
<*> (o .:? "importBehavior")
<*> (o .:? "selfLink")
<*> (o .:? "accountId")
<*> (o .:? "name")
<*> (o .:? "id")
<*> (o .:? "updated")
<*> (o .:? "type")
<*> (o .:? "description")
<*> (o .:? "profilesLinked" .!= mempty))
instance ToJSON CustomDataSource where
toJSON CustomDataSource'{..}
= object
(catMaybes
[("parentLink" .=) <$> _cParentLink,
("webPropertyId" .=) <$> _cWebPropertyId,
("childLink" .=) <$> _cChildLink,
Just ("kind" .= _cKind),
("created" .=) <$> _cCreated,
("uploadType" .=) <$> _cUploadType,
("schema" .=) <$> _cSchema,
("importBehavior" .=) <$> _cImportBehavior,
("selfLink" .=) <$> _cSelfLink,
("accountId" .=) <$> _cAccountId,
("name" .=) <$> _cName, ("id" .=) <$> _cId,
("updated" .=) <$> _cUpdated, ("type" .=) <$> _cType,
("description" .=) <$> _cDescription,
("profilesLinked" .=) <$> _cProFilesLinked])
-- | JSON template for an Analytics account tree requests. The account tree
-- request is used in the provisioning api to create an account, property,
-- and view (profile). It contains the basic information required to make
-- these fields.
--
-- /See:/ 'accountTreeRequest' smart constructor.
data AccountTreeRequest =
AccountTreeRequest'
{ _atrWebPropertyName :: !(Maybe Text)
, _atrKind :: !Text
, _atrAccountName :: !(Maybe Text)
, _atrProFileName :: !(Maybe Text)
, _atrWebsiteURL :: !(Maybe Text)
, _atrTimezone :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'AccountTreeRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'atrWebPropertyName'
--
-- * 'atrKind'
--
-- * 'atrAccountName'
--
-- * 'atrProFileName'
--
-- * 'atrWebsiteURL'
--
-- * 'atrTimezone'
accountTreeRequest
:: AccountTreeRequest
accountTreeRequest =
AccountTreeRequest'
{ _atrWebPropertyName = Nothing
, _atrKind = "analytics#accountTreeRequest"
, _atrAccountName = Nothing
, _atrProFileName = Nothing
, _atrWebsiteURL = Nothing
, _atrTimezone = Nothing
}
atrWebPropertyName :: Lens' AccountTreeRequest (Maybe Text)
atrWebPropertyName
= lens _atrWebPropertyName
(\ s a -> s{_atrWebPropertyName = a})
-- | Resource type for account ticket.
atrKind :: Lens' AccountTreeRequest Text
atrKind = lens _atrKind (\ s a -> s{_atrKind = a})
atrAccountName :: Lens' AccountTreeRequest (Maybe Text)
atrAccountName
= lens _atrAccountName
(\ s a -> s{_atrAccountName = a})
atrProFileName :: Lens' AccountTreeRequest (Maybe Text)
atrProFileName
= lens _atrProFileName
(\ s a -> s{_atrProFileName = a})
atrWebsiteURL :: Lens' AccountTreeRequest (Maybe Text)
atrWebsiteURL
= lens _atrWebsiteURL
(\ s a -> s{_atrWebsiteURL = a})
atrTimezone :: Lens' AccountTreeRequest (Maybe Text)
atrTimezone
= lens _atrTimezone (\ s a -> s{_atrTimezone = a})
instance FromJSON AccountTreeRequest where
parseJSON
= withObject "AccountTreeRequest"
(\ o ->
AccountTreeRequest' <$>
(o .:? "webpropertyName") <*>
(o .:? "kind" .!= "analytics#accountTreeRequest")
<*> (o .:? "accountName")
<*> (o .:? "profileName")
<*> (o .:? "websiteUrl")
<*> (o .:? "timezone"))
instance ToJSON AccountTreeRequest where
toJSON AccountTreeRequest'{..}
= object
(catMaybes
[("webpropertyName" .=) <$> _atrWebPropertyName,
Just ("kind" .= _atrKind),
("accountName" .=) <$> _atrAccountName,
("profileName" .=) <$> _atrProFileName,
("websiteUrl" .=) <$> _atrWebsiteURL,
("timezone" .=) <$> _atrTimezone])
-- | JSON template for a web property reference.
--
-- /See:/ 'webPropertyRef' smart constructor.
data WebPropertyRef =
WebPropertyRef'
{ _wprKind :: !Text
, _wprHref :: !(Maybe Text)
, _wprAccountId :: !(Maybe Text)
, _wprName :: !(Maybe Text)
, _wprInternalWebPropertyId :: !(Maybe Text)
, _wprId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'WebPropertyRef' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'wprKind'
--
-- * 'wprHref'
--
-- * 'wprAccountId'
--
-- * 'wprName'
--
-- * 'wprInternalWebPropertyId'
--
-- * 'wprId'
webPropertyRef
:: WebPropertyRef
webPropertyRef =
WebPropertyRef'
{ _wprKind = "analytics#webPropertyRef"
, _wprHref = Nothing
, _wprAccountId = Nothing
, _wprName = Nothing
, _wprInternalWebPropertyId = Nothing
, _wprId = Nothing
}
-- | Analytics web property reference.
wprKind :: Lens' WebPropertyRef Text
wprKind = lens _wprKind (\ s a -> s{_wprKind = a})
-- | Link for this web property.
wprHref :: Lens' WebPropertyRef (Maybe Text)
wprHref = lens _wprHref (\ s a -> s{_wprHref = a})
-- | Account ID to which this web property belongs.
wprAccountId :: Lens' WebPropertyRef (Maybe Text)
wprAccountId
= lens _wprAccountId (\ s a -> s{_wprAccountId = a})
-- | Name of this web property.
wprName :: Lens' WebPropertyRef (Maybe Text)
wprName = lens _wprName (\ s a -> s{_wprName = a})
-- | Internal ID for this web property.
wprInternalWebPropertyId :: Lens' WebPropertyRef (Maybe Text)
wprInternalWebPropertyId
= lens _wprInternalWebPropertyId
(\ s a -> s{_wprInternalWebPropertyId = a})
-- | Web property ID of the form UA-XXXXX-YY.
wprId :: Lens' WebPropertyRef (Maybe Text)
wprId = lens _wprId (\ s a -> s{_wprId = a})
instance FromJSON WebPropertyRef where
parseJSON
= withObject "WebPropertyRef"
(\ o ->
WebPropertyRef' <$>
(o .:? "kind" .!= "analytics#webPropertyRef") <*>
(o .:? "href")
<*> (o .:? "accountId")
<*> (o .:? "name")
<*> (o .:? "internalWebPropertyId")
<*> (o .:? "id"))
instance ToJSON WebPropertyRef where
toJSON WebPropertyRef'{..}
= object
(catMaybes
[Just ("kind" .= _wprKind), ("href" .=) <$> _wprHref,
("accountId" .=) <$> _wprAccountId,
("name" .=) <$> _wprName,
("internalWebPropertyId" .=) <$>
_wprInternalWebPropertyId,
("id" .=) <$> _wprId])
-- | JSON template for an Analytics Remarketing Audience Foreign Link.
--
-- /See:/ 'linkedForeignAccount' smart constructor.
data LinkedForeignAccount =
LinkedForeignAccount'
{ _lfaStatus :: !(Maybe Text)
, _lfaWebPropertyId :: !(Maybe Text)
, _lfaKind :: !Text
, _lfaEligibleForSearch :: !(Maybe Bool)
, _lfaAccountId :: !(Maybe Text)
, _lfaRemarketingAudienceId :: !(Maybe Text)
, _lfaLinkedAccountId :: !(Maybe Text)
, _lfaInternalWebPropertyId :: !(Maybe Text)
, _lfaId :: !(Maybe Text)
, _lfaType :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'LinkedForeignAccount' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lfaStatus'
--
-- * 'lfaWebPropertyId'
--
-- * 'lfaKind'
--
-- * 'lfaEligibleForSearch'
--
-- * 'lfaAccountId'
--
-- * 'lfaRemarketingAudienceId'
--
-- * 'lfaLinkedAccountId'
--
-- * 'lfaInternalWebPropertyId'
--
-- * 'lfaId'
--
-- * 'lfaType'
linkedForeignAccount
:: LinkedForeignAccount
linkedForeignAccount =
LinkedForeignAccount'
{ _lfaStatus = Nothing
, _lfaWebPropertyId = Nothing
, _lfaKind = "analytics#linkedForeignAccount"
, _lfaEligibleForSearch = Nothing
, _lfaAccountId = Nothing
, _lfaRemarketingAudienceId = Nothing
, _lfaLinkedAccountId = Nothing
, _lfaInternalWebPropertyId = Nothing
, _lfaId = Nothing
, _lfaType = Nothing
}
-- | The status of this foreign account link.
lfaStatus :: Lens' LinkedForeignAccount (Maybe Text)
lfaStatus
= lens _lfaStatus (\ s a -> s{_lfaStatus = a})
-- | Web property ID of the form UA-XXXXX-YY to which this linked foreign
-- account belongs.
lfaWebPropertyId :: Lens' LinkedForeignAccount (Maybe Text)
lfaWebPropertyId
= lens _lfaWebPropertyId
(\ s a -> s{_lfaWebPropertyId = a})
-- | Resource type for linked foreign account.
lfaKind :: Lens' LinkedForeignAccount Text
lfaKind = lens _lfaKind (\ s a -> s{_lfaKind = a})
-- | Boolean indicating whether this is eligible for search.
lfaEligibleForSearch :: Lens' LinkedForeignAccount (Maybe Bool)
lfaEligibleForSearch
= lens _lfaEligibleForSearch
(\ s a -> s{_lfaEligibleForSearch = a})
-- | Account ID to which this linked foreign account belongs.
lfaAccountId :: Lens' LinkedForeignAccount (Maybe Text)
lfaAccountId
= lens _lfaAccountId (\ s a -> s{_lfaAccountId = a})
-- | Remarketing audience ID to which this linked foreign account belongs.
lfaRemarketingAudienceId :: Lens' LinkedForeignAccount (Maybe Text)
lfaRemarketingAudienceId
= lens _lfaRemarketingAudienceId
(\ s a -> s{_lfaRemarketingAudienceId = a})
-- | The foreign account ID. For example the an Google Ads
-- \`linkedAccountId\` has the following format XXX-XXX-XXXX.
lfaLinkedAccountId :: Lens' LinkedForeignAccount (Maybe Text)
lfaLinkedAccountId
= lens _lfaLinkedAccountId
(\ s a -> s{_lfaLinkedAccountId = a})
-- | Internal ID for the web property to which this linked foreign account
-- belongs.
lfaInternalWebPropertyId :: Lens' LinkedForeignAccount (Maybe Text)
lfaInternalWebPropertyId
= lens _lfaInternalWebPropertyId
(\ s a -> s{_lfaInternalWebPropertyId = a})
-- | Entity ad account link ID.
lfaId :: Lens' LinkedForeignAccount (Maybe Text)
lfaId = lens _lfaId (\ s a -> s{_lfaId = a})
-- | The type of the foreign account. For example, \`ADWORDS_LINKS\`,
-- \`DBM_LINKS\`, \`MCC_LINKS\` or \`OPTIMIZE\`.
lfaType :: Lens' LinkedForeignAccount (Maybe Text)
lfaType = lens _lfaType (\ s a -> s{_lfaType = a})
instance FromJSON LinkedForeignAccount where
parseJSON
= withObject "LinkedForeignAccount"
(\ o ->
LinkedForeignAccount' <$>
(o .:? "status") <*> (o .:? "webPropertyId") <*>
(o .:? "kind" .!= "analytics#linkedForeignAccount")
<*> (o .:? "eligibleForSearch")
<*> (o .:? "accountId")
<*> (o .:? "remarketingAudienceId")
<*> (o .:? "linkedAccountId")
<*> (o .:? "internalWebPropertyId")
<*> (o .:? "id")
<*> (o .:? "type"))
instance ToJSON LinkedForeignAccount where
toJSON LinkedForeignAccount'{..}
= object
(catMaybes
[("status" .=) <$> _lfaStatus,
("webPropertyId" .=) <$> _lfaWebPropertyId,
Just ("kind" .= _lfaKind),
("eligibleForSearch" .=) <$> _lfaEligibleForSearch,
("accountId" .=) <$> _lfaAccountId,
("remarketingAudienceId" .=) <$>
_lfaRemarketingAudienceId,
("linkedAccountId" .=) <$> _lfaLinkedAccountId,
("internalWebPropertyId" .=) <$>
_lfaInternalWebPropertyId,
("id" .=) <$> _lfaId, ("type" .=) <$> _lfaType])
-- | A goal collection lists Analytics goals to which the user has access.
-- Each view (profile) can have a set of goals. Each resource in the Goal
-- collection corresponds to a single Analytics goal.
--
-- /See:/ 'goals' smart constructor.
data Goals =
Goals'
{ _gNextLink :: !(Maybe Text)
, _gItemsPerPage :: !(Maybe (Textual Int32))
, _gKind :: !Text
, _gUsername :: !(Maybe Text)
, _gItems :: !(Maybe [Goal])
, _gTotalResults :: !(Maybe (Textual Int32))
, _gStartIndex :: !(Maybe (Textual Int32))
, _gPreviousLink :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Goals' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gNextLink'
--
-- * 'gItemsPerPage'
--
-- * 'gKind'
--
-- * 'gUsername'
--
-- * 'gItems'
--
-- * 'gTotalResults'
--
-- * 'gStartIndex'
--
-- * 'gPreviousLink'
goals
:: Goals
goals =
Goals'
{ _gNextLink = Nothing
, _gItemsPerPage = Nothing
, _gKind = "analytics#goals"
, _gUsername = Nothing
, _gItems = Nothing
, _gTotalResults = Nothing
, _gStartIndex = Nothing
, _gPreviousLink = Nothing
}
-- | Link to next page for this goal collection.
gNextLink :: Lens' Goals (Maybe Text)
gNextLink
= lens _gNextLink (\ s a -> s{_gNextLink = a})
-- | The maximum number of resources the response can contain, regardless of
-- the actual number of resources returned. Its value ranges from 1 to 1000
-- with a value of 1000 by default, or otherwise specified by the
-- max-results query parameter.
gItemsPerPage :: Lens' Goals (Maybe Int32)
gItemsPerPage
= lens _gItemsPerPage
(\ s a -> s{_gItemsPerPage = a})
. mapping _Coerce
-- | Collection type.
gKind :: Lens' Goals Text
gKind = lens _gKind (\ s a -> s{_gKind = a})
-- | Email ID of the authenticated user
gUsername :: Lens' Goals (Maybe Text)
gUsername
= lens _gUsername (\ s a -> s{_gUsername = a})
-- | A list of goals.
gItems :: Lens' Goals [Goal]
gItems
= lens _gItems (\ s a -> s{_gItems = a}) . _Default .
_Coerce
-- | The total number of results for the query, regardless of the number of
-- resources in the result.
gTotalResults :: Lens' Goals (Maybe Int32)
gTotalResults
= lens _gTotalResults
(\ s a -> s{_gTotalResults = a})
. mapping _Coerce
-- | The starting index of the resources, which is 1 by default or otherwise
-- specified by the start-index query parameter.
gStartIndex :: Lens' Goals (Maybe Int32)
gStartIndex
= lens _gStartIndex (\ s a -> s{_gStartIndex = a}) .
mapping _Coerce
-- | Link to previous page for this goal collection.
gPreviousLink :: Lens' Goals (Maybe Text)
gPreviousLink
= lens _gPreviousLink
(\ s a -> s{_gPreviousLink = a})
instance FromJSON Goals where
parseJSON
= withObject "Goals"
(\ o ->
Goals' <$>
(o .:? "nextLink") <*> (o .:? "itemsPerPage") <*>
(o .:? "kind" .!= "analytics#goals")
<*> (o .:? "username")
<*> (o .:? "items" .!= mempty)
<*> (o .:? "totalResults")
<*> (o .:? "startIndex")
<*> (o .:? "previousLink"))
instance ToJSON Goals where
toJSON Goals'{..}
= object
(catMaybes
[("nextLink" .=) <$> _gNextLink,
("itemsPerPage" .=) <$> _gItemsPerPage,
Just ("kind" .= _gKind),
("username" .=) <$> _gUsername,
("items" .=) <$> _gItems,
("totalResults" .=) <$> _gTotalResults,
("startIndex" .=) <$> _gStartIndex,
("previousLink" .=) <$> _gPreviousLink])
-- | A union object representing a dimension or metric value. Only one of
-- \"primitiveValue\" or \"conversionPathValue\" attribute will be
-- populated.
--
-- /See:/ 'mcfDataRowsItemItem' smart constructor.
data McfDataRowsItemItem =
McfDataRowsItemItem'
{ _mdriiPrimitiveValue :: !(Maybe Text)
, _mdriiConversionPathValue :: !(Maybe [McfDataRowsItemItemConversionPathValueItem])
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'McfDataRowsItemItem' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'mdriiPrimitiveValue'
--
-- * 'mdriiConversionPathValue'
mcfDataRowsItemItem
:: McfDataRowsItemItem
mcfDataRowsItemItem =
McfDataRowsItemItem'
{_mdriiPrimitiveValue = Nothing, _mdriiConversionPathValue = Nothing}
-- | A primitive dimension value. A primitive metric value.
mdriiPrimitiveValue :: Lens' McfDataRowsItemItem (Maybe Text)
mdriiPrimitiveValue
= lens _mdriiPrimitiveValue
(\ s a -> s{_mdriiPrimitiveValue = a})
-- | A conversion path dimension value, containing a list of interactions
-- with their attributes.
mdriiConversionPathValue :: Lens' McfDataRowsItemItem [McfDataRowsItemItemConversionPathValueItem]
mdriiConversionPathValue
= lens _mdriiConversionPathValue
(\ s a -> s{_mdriiConversionPathValue = a})
. _Default
. _Coerce
instance FromJSON McfDataRowsItemItem where
parseJSON
= withObject "McfDataRowsItemItem"
(\ o ->
McfDataRowsItemItem' <$>
(o .:? "primitiveValue") <*>
(o .:? "conversionPathValue" .!= mempty))
instance ToJSON McfDataRowsItemItem where
toJSON McfDataRowsItemItem'{..}
= object
(catMaybes
[("primitiveValue" .=) <$> _mdriiPrimitiveValue,
("conversionPathValue" .=) <$>
_mdriiConversionPathValue])
-- | Permissions the user has for this account.
--
-- /See:/ 'accountPermissions' smart constructor.
newtype AccountPermissions =
AccountPermissions'
{ _apEffective :: Maybe [Text]
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'AccountPermissions' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'apEffective'
accountPermissions
:: AccountPermissions
accountPermissions = AccountPermissions' {_apEffective = Nothing}
-- | All the permissions that the user has for this account. These include
-- any implied permissions (e.g., EDIT implies VIEW).
apEffective :: Lens' AccountPermissions [Text]
apEffective
= lens _apEffective (\ s a -> s{_apEffective = a}) .
_Default
. _Coerce
instance FromJSON AccountPermissions where
parseJSON
= withObject "AccountPermissions"
(\ o ->
AccountPermissions' <$>
(o .:? "effective" .!= mempty))
instance ToJSON AccountPermissions where
toJSON AccountPermissions'{..}
= object
(catMaybes [("effective" .=) <$> _apEffective])
-- | Entity for this link. It can be an account, a web property, or a view
-- (profile).
--
-- /See:/ 'entityUserLinkEntity' smart constructor.
data EntityUserLinkEntity =
EntityUserLinkEntity'
{ _euleProFileRef :: !(Maybe ProFileRef)
, _euleAccountRef :: !(Maybe AccountRef)
, _euleWebPropertyRef :: !(Maybe WebPropertyRef)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'EntityUserLinkEntity' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'euleProFileRef'
--
-- * 'euleAccountRef'
--
-- * 'euleWebPropertyRef'
entityUserLinkEntity
:: EntityUserLinkEntity
entityUserLinkEntity =
EntityUserLinkEntity'
{ _euleProFileRef = Nothing
, _euleAccountRef = Nothing
, _euleWebPropertyRef = Nothing
}
-- | View (Profile) for this link.
euleProFileRef :: Lens' EntityUserLinkEntity (Maybe ProFileRef)
euleProFileRef
= lens _euleProFileRef
(\ s a -> s{_euleProFileRef = a})
-- | Account for this link.
euleAccountRef :: Lens' EntityUserLinkEntity (Maybe AccountRef)
euleAccountRef
= lens _euleAccountRef
(\ s a -> s{_euleAccountRef = a})
-- | Web property for this link.
euleWebPropertyRef :: Lens' EntityUserLinkEntity (Maybe WebPropertyRef)
euleWebPropertyRef
= lens _euleWebPropertyRef
(\ s a -> s{_euleWebPropertyRef = a})
instance FromJSON EntityUserLinkEntity where
parseJSON
= withObject "EntityUserLinkEntity"
(\ o ->
EntityUserLinkEntity' <$>
(o .:? "profileRef") <*> (o .:? "accountRef") <*>
(o .:? "webPropertyRef"))
instance ToJSON EntityUserLinkEntity where
toJSON EntityUserLinkEntity'{..}
= object
(catMaybes
[("profileRef" .=) <$> _euleProFileRef,
("accountRef" .=) <$> _euleAccountRef,
("webPropertyRef" .=) <$> _euleWebPropertyRef])
-- | JSON template for Analytics account entry.
--
-- /See:/ 'account' smart constructor.
data Account =
Account'
{ _accChildLink :: !(Maybe AccountChildLink)
, _accKind :: !Text
, _accCreated :: !(Maybe DateTime')
, _accSelfLink :: !(Maybe Text)
, _accName :: !(Maybe Text)
, _accStarred :: !(Maybe Bool)
, _accId :: !(Maybe Text)
, _accUpdated :: !(Maybe DateTime')
, _accPermissions :: !(Maybe AccountPermissions)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Account' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'accChildLink'
--
-- * 'accKind'
--
-- * 'accCreated'
--
-- * 'accSelfLink'
--
-- * 'accName'
--
-- * 'accStarred'
--
-- * 'accId'
--
-- * 'accUpdated'
--
-- * 'accPermissions'
account
:: Account
account =
Account'
{ _accChildLink = Nothing
, _accKind = "analytics#account"
, _accCreated = Nothing
, _accSelfLink = Nothing
, _accName = Nothing
, _accStarred = Nothing
, _accId = Nothing
, _accUpdated = Nothing
, _accPermissions = Nothing
}
-- | Child link for an account entry. Points to the list of web properties
-- for this account.
accChildLink :: Lens' Account (Maybe AccountChildLink)
accChildLink
= lens _accChildLink (\ s a -> s{_accChildLink = a})
-- | Resource type for Analytics account.
accKind :: Lens' Account Text
accKind = lens _accKind (\ s a -> s{_accKind = a})
-- | Time the account was created.
accCreated :: Lens' Account (Maybe UTCTime)
accCreated
= lens _accCreated (\ s a -> s{_accCreated = a}) .
mapping _DateTime
-- | Link for this account.
accSelfLink :: Lens' Account (Maybe Text)
accSelfLink
= lens _accSelfLink (\ s a -> s{_accSelfLink = a})
-- | Account name.
accName :: Lens' Account (Maybe Text)
accName = lens _accName (\ s a -> s{_accName = a})
-- | Indicates whether this account is starred or not.
accStarred :: Lens' Account (Maybe Bool)
accStarred
= lens _accStarred (\ s a -> s{_accStarred = a})
-- | Account ID.
accId :: Lens' Account (Maybe Text)
accId = lens _accId (\ s a -> s{_accId = a})
-- | Time the account was last modified.
accUpdated :: Lens' Account (Maybe UTCTime)
accUpdated
= lens _accUpdated (\ s a -> s{_accUpdated = a}) .
mapping _DateTime
-- | Permissions the user has for this account.
accPermissions :: Lens' Account (Maybe AccountPermissions)
accPermissions
= lens _accPermissions
(\ s a -> s{_accPermissions = a})
instance FromJSON Account where
parseJSON
= withObject "Account"
(\ o ->
Account' <$>
(o .:? "childLink") <*>
(o .:? "kind" .!= "analytics#account")
<*> (o .:? "created")
<*> (o .:? "selfLink")
<*> (o .:? "name")
<*> (o .:? "starred")
<*> (o .:? "id")
<*> (o .:? "updated")
<*> (o .:? "permissions"))
instance ToJSON Account where
toJSON Account'{..}
= object
(catMaybes
[("childLink" .=) <$> _accChildLink,
Just ("kind" .= _accKind),
("created" .=) <$> _accCreated,
("selfLink" .=) <$> _accSelfLink,
("name" .=) <$> _accName,
("starred" .=) <$> _accStarred, ("id" .=) <$> _accId,
("updated" .=) <$> _accUpdated,
("permissions" .=) <$> _accPermissions])
-- | JSON template for Analytics experiment resource.
--
-- /See:/ 'experiment' smart constructor.
data Experiment =
Experiment'
{ _expParentLink :: !(Maybe ExperimentParentLink)
, _expEqualWeighting :: !(Maybe Bool)
, _expStatus :: !(Maybe Text)
, _expWebPropertyId :: !(Maybe Text)
, _expStartTime :: !(Maybe DateTime')
, _expSnippet :: !(Maybe Text)
, _expKind :: !Text
, _expCreated :: !(Maybe DateTime')
, _expReasonExperimentEnded :: !(Maybe Text)
, _expTrafficCoverage :: !(Maybe (Textual Double))
, _expEditableInGaUi :: !(Maybe Bool)
, _expMinimumExperimentLengthInDays :: !(Maybe (Textual Int32))
, _expProFileId :: !(Maybe Text)
, _expOptimizationType :: !(Maybe Text)
, _expSelfLink :: !(Maybe Text)
, _expAccountId :: !(Maybe Text)
, _expName :: !(Maybe Text)
, _expWinnerFound :: !(Maybe Bool)
, _expEndTime :: !(Maybe DateTime')
, _expVariations :: !(Maybe [ExperimentVariationsItem])
, _expInternalWebPropertyId :: !(Maybe Text)
, _expId :: !(Maybe Text)
, _expUpdated :: !(Maybe DateTime')
, _expRewriteVariationURLsAsOriginal :: !(Maybe Bool)
, _expObjectiveMetric :: !(Maybe Text)
, _expWinnerConfidenceLevel :: !(Maybe (Textual Double))
, _expServingFramework :: !(Maybe Text)
, _expDescription :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Experiment' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'expParentLink'
--
-- * 'expEqualWeighting'
--
-- * 'expStatus'
--
-- * 'expWebPropertyId'
--
-- * 'expStartTime'
--
-- * 'expSnippet'
--
-- * 'expKind'
--
-- * 'expCreated'
--
-- * 'expReasonExperimentEnded'
--
-- * 'expTrafficCoverage'
--
-- * 'expEditableInGaUi'
--
-- * 'expMinimumExperimentLengthInDays'
--
-- * 'expProFileId'
--
-- * 'expOptimizationType'
--
-- * 'expSelfLink'
--
-- * 'expAccountId'
--
-- * 'expName'
--
-- * 'expWinnerFound'
--
-- * 'expEndTime'
--
-- * 'expVariations'
--
-- * 'expInternalWebPropertyId'
--
-- * 'expId'
--
-- * 'expUpdated'
--
-- * 'expRewriteVariationURLsAsOriginal'
--
-- * 'expObjectiveMetric'
--
-- * 'expWinnerConfidenceLevel'
--
-- * 'expServingFramework'
--
-- * 'expDescription'
experiment
:: Experiment
experiment =
Experiment'
{ _expParentLink = Nothing
, _expEqualWeighting = Nothing
, _expStatus = Nothing
, _expWebPropertyId = Nothing
, _expStartTime = Nothing
, _expSnippet = Nothing
, _expKind = "analytics#experiment"
, _expCreated = Nothing
, _expReasonExperimentEnded = Nothing
, _expTrafficCoverage = Nothing
, _expEditableInGaUi = Nothing
, _expMinimumExperimentLengthInDays = Nothing
, _expProFileId = Nothing
, _expOptimizationType = Nothing
, _expSelfLink = Nothing
, _expAccountId = Nothing
, _expName = Nothing
, _expWinnerFound = Nothing
, _expEndTime = Nothing
, _expVariations = Nothing
, _expInternalWebPropertyId = Nothing
, _expId = Nothing
, _expUpdated = Nothing
, _expRewriteVariationURLsAsOriginal = Nothing
, _expObjectiveMetric = Nothing
, _expWinnerConfidenceLevel = Nothing
, _expServingFramework = Nothing
, _expDescription = Nothing
}
-- | Parent link for an experiment. Points to the view (profile) to which
-- this experiment belongs.
expParentLink :: Lens' Experiment (Maybe ExperimentParentLink)
expParentLink
= lens _expParentLink
(\ s a -> s{_expParentLink = a})
-- | Boolean specifying whether to distribute traffic evenly across all
-- variations. If the value is False, content experiments follows the
-- default behavior of adjusting traffic dynamically based on variation
-- performance. Optional -- defaults to False. This field may not be
-- changed for an experiment whose status is ENDED.
expEqualWeighting :: Lens' Experiment (Maybe Bool)
expEqualWeighting
= lens _expEqualWeighting
(\ s a -> s{_expEqualWeighting = a})
-- | Experiment status. Possible values: \"DRAFT\", \"READY_TO_RUN\",
-- \"RUNNING\", \"ENDED\". Experiments can be created in the \"DRAFT\",
-- \"READY_TO_RUN\" or \"RUNNING\" state. This field is required when
-- creating an experiment.
expStatus :: Lens' Experiment (Maybe Text)
expStatus
= lens _expStatus (\ s a -> s{_expStatus = a})
-- | Web property ID to which this experiment belongs. The web property ID is
-- of the form UA-XXXXX-YY. This field is read-only.
expWebPropertyId :: Lens' Experiment (Maybe Text)
expWebPropertyId
= lens _expWebPropertyId
(\ s a -> s{_expWebPropertyId = a})
-- | The starting time of the experiment (the time the status changed from
-- READY_TO_RUN to RUNNING). This field is present only if the experiment
-- has started. This field is read-only.
expStartTime :: Lens' Experiment (Maybe UTCTime)
expStartTime
= lens _expStartTime (\ s a -> s{_expStartTime = a})
. mapping _DateTime
-- | The snippet of code to include on the control page(s). This field is
-- read-only.
expSnippet :: Lens' Experiment (Maybe Text)
expSnippet
= lens _expSnippet (\ s a -> s{_expSnippet = a})
-- | Resource type for an Analytics experiment. This field is read-only.
expKind :: Lens' Experiment Text
expKind = lens _expKind (\ s a -> s{_expKind = a})
-- | Time the experiment was created. This field is read-only.
expCreated :: Lens' Experiment (Maybe UTCTime)
expCreated
= lens _expCreated (\ s a -> s{_expCreated = a}) .
mapping _DateTime
-- | Why the experiment ended. Possible values: \"STOPPED_BY_USER\",
-- \"WINNER_FOUND\", \"EXPERIMENT_EXPIRED\", \"ENDED_WITH_NO_WINNER\",
-- \"GOAL_OBJECTIVE_CHANGED\". \"ENDED_WITH_NO_WINNER\" means that the
-- experiment didn\'t expire but no winner was projected to be found. If
-- the experiment status is changed via the API to ENDED this field is set
-- to STOPPED_BY_USER. This field is read-only.
expReasonExperimentEnded :: Lens' Experiment (Maybe Text)
expReasonExperimentEnded
= lens _expReasonExperimentEnded
(\ s a -> s{_expReasonExperimentEnded = a})
-- | A floating-point number in (0, 1]. Specifies the fraction of the traffic
-- that participates in the experiment. Can be changed for a running
-- experiment. This field may not be changed for an experiments whose
-- status is ENDED.
expTrafficCoverage :: Lens' Experiment (Maybe Double)
expTrafficCoverage
= lens _expTrafficCoverage
(\ s a -> s{_expTrafficCoverage = a})
. mapping _Coerce
-- | If true, the end user will be able to edit the experiment via the Google
-- Analytics user interface.
expEditableInGaUi :: Lens' Experiment (Maybe Bool)
expEditableInGaUi
= lens _expEditableInGaUi
(\ s a -> s{_expEditableInGaUi = a})
-- | An integer number in [3, 90]. Specifies the minimum length of the
-- experiment. Can be changed for a running experiment. This field may not
-- be changed for an experiments whose status is ENDED.
expMinimumExperimentLengthInDays :: Lens' Experiment (Maybe Int32)
expMinimumExperimentLengthInDays
= lens _expMinimumExperimentLengthInDays
(\ s a -> s{_expMinimumExperimentLengthInDays = a})
. mapping _Coerce
-- | View (Profile) ID to which this experiment belongs. This field is
-- read-only.
expProFileId :: Lens' Experiment (Maybe Text)
expProFileId
= lens _expProFileId (\ s a -> s{_expProFileId = a})
-- | Whether the objectiveMetric should be minimized or maximized. Possible
-- values: \"MAXIMUM\", \"MINIMUM\". Optional--defaults to \"MAXIMUM\".
-- Cannot be specified without objectiveMetric. Cannot be modified when
-- status is \"RUNNING\" or \"ENDED\".
expOptimizationType :: Lens' Experiment (Maybe Text)
expOptimizationType
= lens _expOptimizationType
(\ s a -> s{_expOptimizationType = a})
-- | Link for this experiment. This field is read-only.
expSelfLink :: Lens' Experiment (Maybe Text)
expSelfLink
= lens _expSelfLink (\ s a -> s{_expSelfLink = a})
-- | Account ID to which this experiment belongs. This field is read-only.
expAccountId :: Lens' Experiment (Maybe Text)
expAccountId
= lens _expAccountId (\ s a -> s{_expAccountId = a})
-- | Experiment name. This field may not be changed for an experiment whose
-- status is ENDED. This field is required when creating an experiment.
expName :: Lens' Experiment (Maybe Text)
expName = lens _expName (\ s a -> s{_expName = a})
-- | Boolean specifying whether a winner has been found for this experiment.
-- This field is read-only.
expWinnerFound :: Lens' Experiment (Maybe Bool)
expWinnerFound
= lens _expWinnerFound
(\ s a -> s{_expWinnerFound = a})
-- | The ending time of the experiment (the time the status changed from
-- RUNNING to ENDED). This field is present only if the experiment has
-- ended. This field is read-only.
expEndTime :: Lens' Experiment (Maybe UTCTime)
expEndTime
= lens _expEndTime (\ s a -> s{_expEndTime = a}) .
mapping _DateTime
-- | Array of variations. The first variation in the array is the original.
-- The number of variations may not change once an experiment is in the
-- RUNNING state. At least two variations are required before status can be
-- set to RUNNING.
expVariations :: Lens' Experiment [ExperimentVariationsItem]
expVariations
= lens _expVariations
(\ s a -> s{_expVariations = a})
. _Default
. _Coerce
-- | Internal ID for the web property to which this experiment belongs. This
-- field is read-only.
expInternalWebPropertyId :: Lens' Experiment (Maybe Text)
expInternalWebPropertyId
= lens _expInternalWebPropertyId
(\ s a -> s{_expInternalWebPropertyId = a})
-- | Experiment ID. Required for patch and update. Disallowed for create.
expId :: Lens' Experiment (Maybe Text)
expId = lens _expId (\ s a -> s{_expId = a})
-- | Time the experiment was last modified. This field is read-only.
expUpdated :: Lens' Experiment (Maybe UTCTime)
expUpdated
= lens _expUpdated (\ s a -> s{_expUpdated = a}) .
mapping _DateTime
-- | Boolean specifying whether variations URLS are rewritten to match those
-- of the original. This field may not be changed for an experiments whose
-- status is ENDED.
expRewriteVariationURLsAsOriginal :: Lens' Experiment (Maybe Bool)
expRewriteVariationURLsAsOriginal
= lens _expRewriteVariationURLsAsOriginal
(\ s a -> s{_expRewriteVariationURLsAsOriginal = a})
-- | The metric that the experiment is optimizing. Valid values:
-- \"ga:goal(n)Completions\", \"ga:adsenseAdsClicks\",
-- \"ga:adsenseAdsViewed\", \"ga:adsenseRevenue\", \"ga:bounces\",
-- \"ga:pageviews\", \"ga:sessionDuration\", \"ga:transactions\",
-- \"ga:transactionRevenue\". This field is required if status is
-- \"RUNNING\" and servingFramework is one of \"REDIRECT\" or \"API\".
expObjectiveMetric :: Lens' Experiment (Maybe Text)
expObjectiveMetric
= lens _expObjectiveMetric
(\ s a -> s{_expObjectiveMetric = a})
-- | A floating-point number in (0, 1). Specifies the necessary confidence
-- level to choose a winner. This field may not be changed for an
-- experiments whose status is ENDED.
expWinnerConfidenceLevel :: Lens' Experiment (Maybe Double)
expWinnerConfidenceLevel
= lens _expWinnerConfidenceLevel
(\ s a -> s{_expWinnerConfidenceLevel = a})
. mapping _Coerce
-- | The framework used to serve the experiment variations and evaluate the
-- results. One of: - REDIRECT: Google Analytics redirects traffic to
-- different variation pages, reports the chosen variation and evaluates
-- the results. - API: Google Analytics chooses and reports the variation
-- to serve and evaluates the results; the caller is responsible for
-- serving the selected variation. - EXTERNAL: The variations will be
-- served externally and the chosen variation reported to Google Analytics.
-- The caller is responsible for serving the selected variation and
-- evaluating the results.
expServingFramework :: Lens' Experiment (Maybe Text)
expServingFramework
= lens _expServingFramework
(\ s a -> s{_expServingFramework = a})
-- | Notes about this experiment.
expDescription :: Lens' Experiment (Maybe Text)
expDescription
= lens _expDescription
(\ s a -> s{_expDescription = a})
instance FromJSON Experiment where
parseJSON
= withObject "Experiment"
(\ o ->
Experiment' <$>
(o .:? "parentLink") <*> (o .:? "equalWeighting") <*>
(o .:? "status")
<*> (o .:? "webPropertyId")
<*> (o .:? "startTime")
<*> (o .:? "snippet")
<*> (o .:? "kind" .!= "analytics#experiment")
<*> (o .:? "created")
<*> (o .:? "reasonExperimentEnded")
<*> (o .:? "trafficCoverage")
<*> (o .:? "editableInGaUi")
<*> (o .:? "minimumExperimentLengthInDays")
<*> (o .:? "profileId")
<*> (o .:? "optimizationType")
<*> (o .:? "selfLink")
<*> (o .:? "accountId")
<*> (o .:? "name")
<*> (o .:? "winnerFound")
<*> (o .:? "endTime")
<*> (o .:? "variations" .!= mempty)
<*> (o .:? "internalWebPropertyId")
<*> (o .:? "id")
<*> (o .:? "updated")
<*> (o .:? "rewriteVariationUrlsAsOriginal")
<*> (o .:? "objectiveMetric")
<*> (o .:? "winnerConfidenceLevel")
<*> (o .:? "servingFramework")
<*> (o .:? "description"))
instance ToJSON Experiment where
toJSON Experiment'{..}
= object
(catMaybes
[("parentLink" .=) <$> _expParentLink,
("equalWeighting" .=) <$> _expEqualWeighting,
("status" .=) <$> _expStatus,
("webPropertyId" .=) <$> _expWebPropertyId,
("startTime" .=) <$> _expStartTime,
("snippet" .=) <$> _expSnippet,
Just ("kind" .= _expKind),
("created" .=) <$> _expCreated,
("reasonExperimentEnded" .=) <$>
_expReasonExperimentEnded,
("trafficCoverage" .=) <$> _expTrafficCoverage,
("editableInGaUi" .=) <$> _expEditableInGaUi,
("minimumExperimentLengthInDays" .=) <$>
_expMinimumExperimentLengthInDays,
("profileId" .=) <$> _expProFileId,
("optimizationType" .=) <$> _expOptimizationType,
("selfLink" .=) <$> _expSelfLink,
("accountId" .=) <$> _expAccountId,
("name" .=) <$> _expName,
("winnerFound" .=) <$> _expWinnerFound,
("endTime" .=) <$> _expEndTime,
("variations" .=) <$> _expVariations,
("internalWebPropertyId" .=) <$>
_expInternalWebPropertyId,
("id" .=) <$> _expId, ("updated" .=) <$> _expUpdated,
("rewriteVariationUrlsAsOriginal" .=) <$>
_expRewriteVariationURLsAsOriginal,
("objectiveMetric" .=) <$> _expObjectiveMetric,
("winnerConfidenceLevel" .=) <$>
_expWinnerConfidenceLevel,
("servingFramework" .=) <$> _expServingFramework,
("description" .=) <$> _expDescription])
-- | An entity user link collection provides a list of Analytics ACL links
-- Each resource in this collection corresponds to a single link.
--
-- /See:/ 'entityUserLinks' smart constructor.
data EntityUserLinks =
EntityUserLinks'
{ _eulNextLink :: !(Maybe Text)
, _eulItemsPerPage :: !(Maybe (Textual Int32))
, _eulKind :: !Text
, _eulItems :: !(Maybe [EntityUserLink])
, _eulTotalResults :: !(Maybe (Textual Int32))
, _eulStartIndex :: !(Maybe (Textual Int32))
, _eulPreviousLink :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'EntityUserLinks' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'eulNextLink'
--
-- * 'eulItemsPerPage'
--
-- * 'eulKind'
--
-- * 'eulItems'
--
-- * 'eulTotalResults'
--
-- * 'eulStartIndex'
--
-- * 'eulPreviousLink'
entityUserLinks
:: EntityUserLinks
entityUserLinks =
EntityUserLinks'
{ _eulNextLink = Nothing
, _eulItemsPerPage = Nothing
, _eulKind = "analytics#entityUserLinks"
, _eulItems = Nothing
, _eulTotalResults = Nothing
, _eulStartIndex = Nothing
, _eulPreviousLink = Nothing
}
-- | Next link for this account collection.
eulNextLink :: Lens' EntityUserLinks (Maybe Text)
eulNextLink
= lens _eulNextLink (\ s a -> s{_eulNextLink = a})
-- | The maximum number of entries the response can contain, regardless of
-- the actual number of entries returned. Its value ranges from 1 to 1000
-- with a value of 1000 by default, or otherwise specified by the
-- max-results query parameter.
eulItemsPerPage :: Lens' EntityUserLinks (Maybe Int32)
eulItemsPerPage
= lens _eulItemsPerPage
(\ s a -> s{_eulItemsPerPage = a})
. mapping _Coerce
-- | Collection type.
eulKind :: Lens' EntityUserLinks Text
eulKind = lens _eulKind (\ s a -> s{_eulKind = a})
-- | A list of entity user links.
eulItems :: Lens' EntityUserLinks [EntityUserLink]
eulItems
= lens _eulItems (\ s a -> s{_eulItems = a}) .
_Default
. _Coerce
-- | The total number of results for the query, regardless of the number of
-- results in the response.
eulTotalResults :: Lens' EntityUserLinks (Maybe Int32)
eulTotalResults
= lens _eulTotalResults
(\ s a -> s{_eulTotalResults = a})
. mapping _Coerce
-- | The starting index of the entries, which is 1 by default or otherwise
-- specified by the start-index query parameter.
eulStartIndex :: Lens' EntityUserLinks (Maybe Int32)
eulStartIndex
= lens _eulStartIndex
(\ s a -> s{_eulStartIndex = a})
. mapping _Coerce
-- | Previous link for this account collection.
eulPreviousLink :: Lens' EntityUserLinks (Maybe Text)
eulPreviousLink
= lens _eulPreviousLink
(\ s a -> s{_eulPreviousLink = a})
instance FromJSON EntityUserLinks where
parseJSON
= withObject "EntityUserLinks"
(\ o ->
EntityUserLinks' <$>
(o .:? "nextLink") <*> (o .:? "itemsPerPage") <*>
(o .:? "kind" .!= "analytics#entityUserLinks")
<*> (o .:? "items" .!= mempty)
<*> (o .:? "totalResults")
<*> (o .:? "startIndex")
<*> (o .:? "previousLink"))
instance ToJSON EntityUserLinks where
toJSON EntityUserLinks'{..}
= object
(catMaybes
[("nextLink" .=) <$> _eulNextLink,
("itemsPerPage" .=) <$> _eulItemsPerPage,
Just ("kind" .= _eulKind),
("items" .=) <$> _eulItems,
("totalResults" .=) <$> _eulTotalResults,
("startIndex" .=) <$> _eulStartIndex,
("previousLink" .=) <$> _eulPreviousLink])
-- | JSON template for an Google Ads account.
--
-- /See:/ 'adWordsAccount' smart constructor.
data AdWordsAccount =
AdWordsAccount'
{ _awaAutoTaggingEnabled :: !(Maybe Bool)
, _awaKind :: !Text
, _awaCustomerId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'AdWordsAccount' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'awaAutoTaggingEnabled'
--
-- * 'awaKind'
--
-- * 'awaCustomerId'
adWordsAccount
:: AdWordsAccount
adWordsAccount =
AdWordsAccount'
{ _awaAutoTaggingEnabled = Nothing
, _awaKind = "analytics#adWordsAccount"
, _awaCustomerId = Nothing
}
-- | True if auto-tagging is enabled on the Google Ads account. Read-only
-- after the insert operation.
awaAutoTaggingEnabled :: Lens' AdWordsAccount (Maybe Bool)
awaAutoTaggingEnabled
= lens _awaAutoTaggingEnabled
(\ s a -> s{_awaAutoTaggingEnabled = a})
-- | Resource type for Google Ads account.
awaKind :: Lens' AdWordsAccount Text
awaKind = lens _awaKind (\ s a -> s{_awaKind = a})
-- | Customer ID. This field is required when creating a Google Ads link.
awaCustomerId :: Lens' AdWordsAccount (Maybe Text)
awaCustomerId
= lens _awaCustomerId
(\ s a -> s{_awaCustomerId = a})
instance FromJSON AdWordsAccount where
parseJSON
= withObject "AdWordsAccount"
(\ o ->
AdWordsAccount' <$>
(o .:? "autoTaggingEnabled") <*>
(o .:? "kind" .!= "analytics#adWordsAccount")
<*> (o .:? "customerId"))
instance ToJSON AdWordsAccount where
toJSON AdWordsAccount'{..}
= object
(catMaybes
[("autoTaggingEnabled" .=) <$>
_awaAutoTaggingEnabled,
Just ("kind" .= _awaKind),
("customerId" .=) <$> _awaCustomerId])
-- | JSON template for a profile filter link.
--
-- /See:/ 'filterRef' smart constructor.
data FilterRef =
FilterRef'
{ _frKind :: !Text
, _frHref :: !(Maybe Text)
, _frAccountId :: !(Maybe Text)
, _frName :: !(Maybe Text)
, _frId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'FilterRef' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'frKind'
--
-- * 'frHref'
--
-- * 'frAccountId'
--
-- * 'frName'
--
-- * 'frId'
filterRef
:: FilterRef
filterRef =
FilterRef'
{ _frKind = "analytics#filterRef"
, _frHref = Nothing
, _frAccountId = Nothing
, _frName = Nothing
, _frId = Nothing
}
-- | Kind value for filter reference.
frKind :: Lens' FilterRef Text
frKind = lens _frKind (\ s a -> s{_frKind = a})
-- | Link for this filter.
frHref :: Lens' FilterRef (Maybe Text)
frHref = lens _frHref (\ s a -> s{_frHref = a})
-- | Account ID to which this filter belongs.
frAccountId :: Lens' FilterRef (Maybe Text)
frAccountId
= lens _frAccountId (\ s a -> s{_frAccountId = a})
-- | Name of this filter.
frName :: Lens' FilterRef (Maybe Text)
frName = lens _frName (\ s a -> s{_frName = a})
-- | Filter ID.
frId :: Lens' FilterRef (Maybe Text)
frId = lens _frId (\ s a -> s{_frId = a})
instance FromJSON FilterRef where
parseJSON
= withObject "FilterRef"
(\ o ->
FilterRef' <$>
(o .:? "kind" .!= "analytics#filterRef") <*>
(o .:? "href")
<*> (o .:? "accountId")
<*> (o .:? "name")
<*> (o .:? "id"))
instance ToJSON FilterRef where
toJSON FilterRef'{..}
= object
(catMaybes
[Just ("kind" .= _frKind), ("href" .=) <$> _frHref,
("accountId" .=) <$> _frAccountId,
("name" .=) <$> _frName, ("id" .=) <$> _frId])
-- | Details for the goal of the type VISIT_TIME_ON_SITE.
--
-- /See:/ 'goalVisitTimeOnSiteDetails' smart constructor.
data GoalVisitTimeOnSiteDetails =
GoalVisitTimeOnSiteDetails'
{ _gvtosdComparisonValue :: !(Maybe (Textual Int64))
, _gvtosdComparisonType :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'GoalVisitTimeOnSiteDetails' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gvtosdComparisonValue'
--
-- * 'gvtosdComparisonType'
goalVisitTimeOnSiteDetails
:: GoalVisitTimeOnSiteDetails
goalVisitTimeOnSiteDetails =
GoalVisitTimeOnSiteDetails'
{_gvtosdComparisonValue = Nothing, _gvtosdComparisonType = Nothing}
-- | Value used for this comparison.
gvtosdComparisonValue :: Lens' GoalVisitTimeOnSiteDetails (Maybe Int64)
gvtosdComparisonValue
= lens _gvtosdComparisonValue
(\ s a -> s{_gvtosdComparisonValue = a})
. mapping _Coerce
-- | Type of comparison. Possible values are LESS_THAN or GREATER_THAN.
gvtosdComparisonType :: Lens' GoalVisitTimeOnSiteDetails (Maybe Text)
gvtosdComparisonType
= lens _gvtosdComparisonType
(\ s a -> s{_gvtosdComparisonType = a})
instance FromJSON GoalVisitTimeOnSiteDetails where
parseJSON
= withObject "GoalVisitTimeOnSiteDetails"
(\ o ->
GoalVisitTimeOnSiteDetails' <$>
(o .:? "comparisonValue") <*>
(o .:? "comparisonType"))
instance ToJSON GoalVisitTimeOnSiteDetails where
toJSON GoalVisitTimeOnSiteDetails'{..}
= object
(catMaybes
[("comparisonValue" .=) <$> _gvtosdComparisonValue,
("comparisonType" .=) <$> _gvtosdComparisonType])
-- | A web property collection lists Analytics web properties to which the
-- user has access. Each resource in the collection corresponds to a single
-- Analytics web property.
--
-- /See:/ 'webProperties' smart constructor.
data WebProperties =
WebProperties'
{ _wpNextLink :: !(Maybe Text)
, _wpItemsPerPage :: !(Maybe (Textual Int32))
, _wpKind :: !Text
, _wpUsername :: !(Maybe Text)
, _wpItems :: !(Maybe [WebProperty])
, _wpTotalResults :: !(Maybe (Textual Int32))
, _wpStartIndex :: !(Maybe (Textual Int32))
, _wpPreviousLink :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'WebProperties' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'wpNextLink'
--
-- * 'wpItemsPerPage'
--
-- * 'wpKind'
--
-- * 'wpUsername'
--
-- * 'wpItems'
--
-- * 'wpTotalResults'
--
-- * 'wpStartIndex'
--
-- * 'wpPreviousLink'
webProperties
:: WebProperties
webProperties =
WebProperties'
{ _wpNextLink = Nothing
, _wpItemsPerPage = Nothing
, _wpKind = "analytics#webproperties"
, _wpUsername = Nothing
, _wpItems = Nothing
, _wpTotalResults = Nothing
, _wpStartIndex = Nothing
, _wpPreviousLink = Nothing
}
-- | Link to next page for this web property collection.
wpNextLink :: Lens' WebProperties (Maybe Text)
wpNextLink
= lens _wpNextLink (\ s a -> s{_wpNextLink = a})
-- | The maximum number of resources the response can contain, regardless of
-- the actual number of resources returned. Its value ranges from 1 to 1000
-- with a value of 1000 by default, or otherwise specified by the
-- max-results query parameter.
wpItemsPerPage :: Lens' WebProperties (Maybe Int32)
wpItemsPerPage
= lens _wpItemsPerPage
(\ s a -> s{_wpItemsPerPage = a})
. mapping _Coerce
-- | Collection type.
wpKind :: Lens' WebProperties Text
wpKind = lens _wpKind (\ s a -> s{_wpKind = a})
-- | Email ID of the authenticated user
wpUsername :: Lens' WebProperties (Maybe Text)
wpUsername
= lens _wpUsername (\ s a -> s{_wpUsername = a})
-- | A list of web properties.
wpItems :: Lens' WebProperties [WebProperty]
wpItems
= lens _wpItems (\ s a -> s{_wpItems = a}) . _Default
. _Coerce
-- | The total number of results for the query, regardless of the number of
-- results in the response.
wpTotalResults :: Lens' WebProperties (Maybe Int32)
wpTotalResults
= lens _wpTotalResults
(\ s a -> s{_wpTotalResults = a})
. mapping _Coerce
-- | The starting index of the resources, which is 1 by default or otherwise
-- specified by the start-index query parameter.
wpStartIndex :: Lens' WebProperties (Maybe Int32)
wpStartIndex
= lens _wpStartIndex (\ s a -> s{_wpStartIndex = a})
. mapping _Coerce
-- | Link to previous page for this web property collection.
wpPreviousLink :: Lens' WebProperties (Maybe Text)
wpPreviousLink
= lens _wpPreviousLink
(\ s a -> s{_wpPreviousLink = a})
instance FromJSON WebProperties where
parseJSON
= withObject "WebProperties"
(\ o ->
WebProperties' <$>
(o .:? "nextLink") <*> (o .:? "itemsPerPage") <*>
(o .:? "kind" .!= "analytics#webproperties")
<*> (o .:? "username")
<*> (o .:? "items" .!= mempty)
<*> (o .:? "totalResults")
<*> (o .:? "startIndex")
<*> (o .:? "previousLink"))
instance ToJSON WebProperties where
toJSON WebProperties'{..}
= object
(catMaybes
[("nextLink" .=) <$> _wpNextLink,
("itemsPerPage" .=) <$> _wpItemsPerPage,
Just ("kind" .= _wpKind),
("username" .=) <$> _wpUsername,
("items" .=) <$> _wpItems,
("totalResults" .=) <$> _wpTotalResults,
("startIndex" .=) <$> _wpStartIndex,
("previousLink" .=) <$> _wpPreviousLink])
-- | A custom metric collection lists Analytics custom metrics to which the
-- user has access. Each resource in the collection corresponds to a single
-- Analytics custom metric.
--
-- /See:/ 'customMetrics' smart constructor.
data CustomMetrics =
CustomMetrics'
{ _cmNextLink :: !(Maybe Text)
, _cmItemsPerPage :: !(Maybe (Textual Int32))
, _cmKind :: !Text
, _cmUsername :: !(Maybe Text)
, _cmItems :: !(Maybe [CustomMetric])
, _cmTotalResults :: !(Maybe (Textual Int32))
, _cmStartIndex :: !(Maybe (Textual Int32))
, _cmPreviousLink :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'CustomMetrics' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cmNextLink'
--
-- * 'cmItemsPerPage'
--
-- * 'cmKind'
--
-- * 'cmUsername'
--
-- * 'cmItems'
--
-- * 'cmTotalResults'
--
-- * 'cmStartIndex'
--
-- * 'cmPreviousLink'
customMetrics
:: CustomMetrics
customMetrics =
CustomMetrics'
{ _cmNextLink = Nothing
, _cmItemsPerPage = Nothing
, _cmKind = "analytics#customMetrics"
, _cmUsername = Nothing
, _cmItems = Nothing
, _cmTotalResults = Nothing
, _cmStartIndex = Nothing
, _cmPreviousLink = Nothing
}
-- | Link to next page for this custom metric collection.
cmNextLink :: Lens' CustomMetrics (Maybe Text)
cmNextLink
= lens _cmNextLink (\ s a -> s{_cmNextLink = a})
-- | The maximum number of resources the response can contain, regardless of
-- the actual number of resources returned. Its value ranges from 1 to 1000
-- with a value of 1000 by default, or otherwise specified by the
-- max-results query parameter.
cmItemsPerPage :: Lens' CustomMetrics (Maybe Int32)
cmItemsPerPage
= lens _cmItemsPerPage
(\ s a -> s{_cmItemsPerPage = a})
. mapping _Coerce
-- | Collection type.
cmKind :: Lens' CustomMetrics Text
cmKind = lens _cmKind (\ s a -> s{_cmKind = a})
-- | Email ID of the authenticated user
cmUsername :: Lens' CustomMetrics (Maybe Text)
cmUsername
= lens _cmUsername (\ s a -> s{_cmUsername = a})
-- | Collection of custom metrics.
cmItems :: Lens' CustomMetrics [CustomMetric]
cmItems
= lens _cmItems (\ s a -> s{_cmItems = a}) . _Default
. _Coerce
-- | The total number of results for the query, regardless of the number of
-- results in the response.
cmTotalResults :: Lens' CustomMetrics (Maybe Int32)
cmTotalResults
= lens _cmTotalResults
(\ s a -> s{_cmTotalResults = a})
. mapping _Coerce
-- | The starting index of the resources, which is 1 by default or otherwise
-- specified by the start-index query parameter.
cmStartIndex :: Lens' CustomMetrics (Maybe Int32)
cmStartIndex
= lens _cmStartIndex (\ s a -> s{_cmStartIndex = a})
. mapping _Coerce
-- | Link to previous page for this custom metric collection.
cmPreviousLink :: Lens' CustomMetrics (Maybe Text)
cmPreviousLink
= lens _cmPreviousLink
(\ s a -> s{_cmPreviousLink = a})
instance FromJSON CustomMetrics where
parseJSON
= withObject "CustomMetrics"
(\ o ->
CustomMetrics' <$>
(o .:? "nextLink") <*> (o .:? "itemsPerPage") <*>
(o .:? "kind" .!= "analytics#customMetrics")
<*> (o .:? "username")
<*> (o .:? "items" .!= mempty)
<*> (o .:? "totalResults")
<*> (o .:? "startIndex")
<*> (o .:? "previousLink"))
instance ToJSON CustomMetrics where
toJSON CustomMetrics'{..}
= object
(catMaybes
[("nextLink" .=) <$> _cmNextLink,
("itemsPerPage" .=) <$> _cmItemsPerPage,
Just ("kind" .= _cmKind),
("username" .=) <$> _cmUsername,
("items" .=) <$> _cmItems,
("totalResults" .=) <$> _cmTotalResults,
("startIndex" .=) <$> _cmStartIndex,
("previousLink" .=) <$> _cmPreviousLink])
-- | Details for the filter of the type ADVANCED.
--
-- /See:/ 'filterAdvancedDetails' smart constructor.
data FilterAdvancedDetails =
FilterAdvancedDetails'
{ _fadExtractA :: !(Maybe Text)
, _fadFieldARequired :: !(Maybe Bool)
, _fadFieldA :: !(Maybe Text)
, _fadFieldBIndex :: !(Maybe (Textual Int32))
, _fadOutputToField :: !(Maybe Text)
, _fadOutputConstructor :: !(Maybe Text)
, _fadExtractB :: !(Maybe Text)
, _fadFieldAIndex :: !(Maybe (Textual Int32))
, _fadCaseSensitive :: !(Maybe Bool)
, _fadOutputToFieldIndex :: !(Maybe (Textual Int32))
, _fadFieldB :: !(Maybe Text)
, _fadFieldBRequired :: !(Maybe Bool)
, _fadOverrideOutputField :: !(Maybe Bool)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'FilterAdvancedDetails' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'fadExtractA'
--
-- * 'fadFieldARequired'
--
-- * 'fadFieldA'
--
-- * 'fadFieldBIndex'
--
-- * 'fadOutputToField'
--
-- * 'fadOutputConstructor'
--
-- * 'fadExtractB'
--
-- * 'fadFieldAIndex'
--
-- * 'fadCaseSensitive'
--
-- * 'fadOutputToFieldIndex'
--
-- * 'fadFieldB'
--
-- * 'fadFieldBRequired'
--
-- * 'fadOverrideOutputField'
filterAdvancedDetails
:: FilterAdvancedDetails
filterAdvancedDetails =
FilterAdvancedDetails'
{ _fadExtractA = Nothing
, _fadFieldARequired = Nothing
, _fadFieldA = Nothing
, _fadFieldBIndex = Nothing
, _fadOutputToField = Nothing
, _fadOutputConstructor = Nothing
, _fadExtractB = Nothing
, _fadFieldAIndex = Nothing
, _fadCaseSensitive = Nothing
, _fadOutputToFieldIndex = Nothing
, _fadFieldB = Nothing
, _fadFieldBRequired = Nothing
, _fadOverrideOutputField = Nothing
}
-- | Expression to extract from field A.
fadExtractA :: Lens' FilterAdvancedDetails (Maybe Text)
fadExtractA
= lens _fadExtractA (\ s a -> s{_fadExtractA = a})
-- | Indicates if field A is required to match.
fadFieldARequired :: Lens' FilterAdvancedDetails (Maybe Bool)
fadFieldARequired
= lens _fadFieldARequired
(\ s a -> s{_fadFieldARequired = a})
-- | Field A.
fadFieldA :: Lens' FilterAdvancedDetails (Maybe Text)
fadFieldA
= lens _fadFieldA (\ s a -> s{_fadFieldA = a})
-- | The Index of the custom dimension. Required if field is a
-- CUSTOM_DIMENSION.
fadFieldBIndex :: Lens' FilterAdvancedDetails (Maybe Int32)
fadFieldBIndex
= lens _fadFieldBIndex
(\ s a -> s{_fadFieldBIndex = a})
. mapping _Coerce
-- | Output field.
fadOutputToField :: Lens' FilterAdvancedDetails (Maybe Text)
fadOutputToField
= lens _fadOutputToField
(\ s a -> s{_fadOutputToField = a})
-- | Expression used to construct the output value.
fadOutputConstructor :: Lens' FilterAdvancedDetails (Maybe Text)
fadOutputConstructor
= lens _fadOutputConstructor
(\ s a -> s{_fadOutputConstructor = a})
-- | Expression to extract from field B.
fadExtractB :: Lens' FilterAdvancedDetails (Maybe Text)
fadExtractB
= lens _fadExtractB (\ s a -> s{_fadExtractB = a})
-- | The Index of the custom dimension. Required if field is a
-- CUSTOM_DIMENSION.
fadFieldAIndex :: Lens' FilterAdvancedDetails (Maybe Int32)
fadFieldAIndex
= lens _fadFieldAIndex
(\ s a -> s{_fadFieldAIndex = a})
. mapping _Coerce
-- | Indicates if the filter expressions are case sensitive.
fadCaseSensitive :: Lens' FilterAdvancedDetails (Maybe Bool)
fadCaseSensitive
= lens _fadCaseSensitive
(\ s a -> s{_fadCaseSensitive = a})
-- | The Index of the custom dimension. Required if field is a
-- CUSTOM_DIMENSION.
fadOutputToFieldIndex :: Lens' FilterAdvancedDetails (Maybe Int32)
fadOutputToFieldIndex
= lens _fadOutputToFieldIndex
(\ s a -> s{_fadOutputToFieldIndex = a})
. mapping _Coerce
-- | Field B.
fadFieldB :: Lens' FilterAdvancedDetails (Maybe Text)
fadFieldB
= lens _fadFieldB (\ s a -> s{_fadFieldB = a})
-- | Indicates if field B is required to match.
fadFieldBRequired :: Lens' FilterAdvancedDetails (Maybe Bool)
fadFieldBRequired
= lens _fadFieldBRequired
(\ s a -> s{_fadFieldBRequired = a})
-- | Indicates if the existing value of the output field, if any, should be
-- overridden by the output expression.
fadOverrideOutputField :: Lens' FilterAdvancedDetails (Maybe Bool)
fadOverrideOutputField
= lens _fadOverrideOutputField
(\ s a -> s{_fadOverrideOutputField = a})
instance FromJSON FilterAdvancedDetails where
parseJSON
= withObject "FilterAdvancedDetails"
(\ o ->
FilterAdvancedDetails' <$>
(o .:? "extractA") <*> (o .:? "fieldARequired") <*>
(o .:? "fieldA")
<*> (o .:? "fieldBIndex")
<*> (o .:? "outputToField")
<*> (o .:? "outputConstructor")
<*> (o .:? "extractB")
<*> (o .:? "fieldAIndex")
<*> (o .:? "caseSensitive")
<*> (o .:? "outputToFieldIndex")
<*> (o .:? "fieldB")
<*> (o .:? "fieldBRequired")
<*> (o .:? "overrideOutputField"))
instance ToJSON FilterAdvancedDetails where
toJSON FilterAdvancedDetails'{..}
= object
(catMaybes
[("extractA" .=) <$> _fadExtractA,
("fieldARequired" .=) <$> _fadFieldARequired,
("fieldA" .=) <$> _fadFieldA,
("fieldBIndex" .=) <$> _fadFieldBIndex,
("outputToField" .=) <$> _fadOutputToField,
("outputConstructor" .=) <$> _fadOutputConstructor,
("extractB" .=) <$> _fadExtractB,
("fieldAIndex" .=) <$> _fadFieldAIndex,
("caseSensitive" .=) <$> _fadCaseSensitive,
("outputToFieldIndex" .=) <$> _fadOutputToFieldIndex,
("fieldB" .=) <$> _fadFieldB,
("fieldBRequired" .=) <$> _fadFieldBRequired,
("overrideOutputField" .=) <$>
_fadOverrideOutputField])
-- | JSON template for an Analytics account tree response. The account tree
-- response is used in the provisioning api to return the result of
-- creating an account, property, and view (profile).
--
-- /See:/ 'accountTreeResponse' smart constructor.
data AccountTreeResponse =
AccountTreeResponse'
{ _atrtKind :: !Text
, _atrtProFile :: !(Maybe ProFile)
, _atrtAccount :: !(Maybe Account)
, _atrtWebProperty :: !(Maybe WebProperty)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'AccountTreeResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'atrtKind'
--
-- * 'atrtProFile'
--
-- * 'atrtAccount'
--
-- * 'atrtWebProperty'
accountTreeResponse
:: AccountTreeResponse
accountTreeResponse =
AccountTreeResponse'
{ _atrtKind = "analytics#accountTreeResponse"
, _atrtProFile = Nothing
, _atrtAccount = Nothing
, _atrtWebProperty = Nothing
}
-- | Resource type for account ticket.
atrtKind :: Lens' AccountTreeResponse Text
atrtKind = lens _atrtKind (\ s a -> s{_atrtKind = a})
-- | View (Profile) for the account.
atrtProFile :: Lens' AccountTreeResponse (Maybe ProFile)
atrtProFile
= lens _atrtProFile (\ s a -> s{_atrtProFile = a})
-- | The account created.
atrtAccount :: Lens' AccountTreeResponse (Maybe Account)
atrtAccount
= lens _atrtAccount (\ s a -> s{_atrtAccount = a})
-- | Web property for the account.
atrtWebProperty :: Lens' AccountTreeResponse (Maybe WebProperty)
atrtWebProperty
= lens _atrtWebProperty
(\ s a -> s{_atrtWebProperty = a})
instance FromJSON AccountTreeResponse where
parseJSON
= withObject "AccountTreeResponse"
(\ o ->
AccountTreeResponse' <$>
(o .:? "kind" .!= "analytics#accountTreeResponse")
<*> (o .:? "profile")
<*> (o .:? "account")
<*> (o .:? "webproperty"))
instance ToJSON AccountTreeResponse where
toJSON AccountTreeResponse'{..}
= object
(catMaybes
[Just ("kind" .= _atrtKind),
("profile" .=) <$> _atrtProFile,
("account" .=) <$> _atrtAccount,
("webproperty" .=) <$> _atrtWebProperty])
-- | Details for the filter of the type UPPER.
--
-- /See:/ 'filterUppercaseDetails' smart constructor.
data FilterUppercaseDetails =
FilterUppercaseDetails'
{ _fudFieldIndex :: !(Maybe (Textual Int32))
, _fudField :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'FilterUppercaseDetails' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'fudFieldIndex'
--
-- * 'fudField'
filterUppercaseDetails
:: FilterUppercaseDetails
filterUppercaseDetails =
FilterUppercaseDetails' {_fudFieldIndex = Nothing, _fudField = Nothing}
-- | The Index of the custom dimension. Required if field is a
-- CUSTOM_DIMENSION.
fudFieldIndex :: Lens' FilterUppercaseDetails (Maybe Int32)
fudFieldIndex
= lens _fudFieldIndex
(\ s a -> s{_fudFieldIndex = a})
. mapping _Coerce
-- | Field to use in the filter.
fudField :: Lens' FilterUppercaseDetails (Maybe Text)
fudField = lens _fudField (\ s a -> s{_fudField = a})
instance FromJSON FilterUppercaseDetails where
parseJSON
= withObject "FilterUppercaseDetails"
(\ o ->
FilterUppercaseDetails' <$>
(o .:? "fieldIndex") <*> (o .:? "field"))
instance ToJSON FilterUppercaseDetails where
toJSON FilterUppercaseDetails'{..}
= object
(catMaybes
[("fieldIndex" .=) <$> _fudFieldIndex,
("field" .=) <$> _fudField])
--
-- /See:/ 'customDataSourceChildLink' smart constructor.
data CustomDataSourceChildLink =
CustomDataSourceChildLink'
{ _cdsclHref :: !(Maybe Text)
, _cdsclType :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'CustomDataSourceChildLink' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cdsclHref'
--
-- * 'cdsclType'
customDataSourceChildLink
:: CustomDataSourceChildLink
customDataSourceChildLink =
CustomDataSourceChildLink' {_cdsclHref = Nothing, _cdsclType = Nothing}
-- | Link to the list of daily uploads for this custom data source. Link to
-- the list of uploads for this custom data source.
cdsclHref :: Lens' CustomDataSourceChildLink (Maybe Text)
cdsclHref
= lens _cdsclHref (\ s a -> s{_cdsclHref = a})
-- | Value is \"analytics#dailyUploads\". Value is \"analytics#uploads\".
cdsclType :: Lens' CustomDataSourceChildLink (Maybe Text)
cdsclType
= lens _cdsclType (\ s a -> s{_cdsclType = a})
instance FromJSON CustomDataSourceChildLink where
parseJSON
= withObject "CustomDataSourceChildLink"
(\ o ->
CustomDataSourceChildLink' <$>
(o .:? "href") <*> (o .:? "type"))
instance ToJSON CustomDataSourceChildLink where
toJSON CustomDataSourceChildLink'{..}
= object
(catMaybes
[("href" .=) <$> _cdsclHref,
("type" .=) <$> _cdsclType])
-- | JSON template for an Analytics Remarketing Include Conditions.
--
-- /See:/ 'includeConditions' smart constructor.
data IncludeConditions =
IncludeConditions'
{ _icKind :: !Text
, _icDaysToLookBack :: !(Maybe (Textual Int32))
, _icMembershipDurationDays :: !(Maybe (Textual Int32))
, _icSegment :: !(Maybe Text)
, _icIsSmartList :: !(Maybe Bool)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'IncludeConditions' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'icKind'
--
-- * 'icDaysToLookBack'
--
-- * 'icMembershipDurationDays'
--
-- * 'icSegment'
--
-- * 'icIsSmartList'
includeConditions
:: IncludeConditions
includeConditions =
IncludeConditions'
{ _icKind = "analytics#includeConditions"
, _icDaysToLookBack = Nothing
, _icMembershipDurationDays = Nothing
, _icSegment = Nothing
, _icIsSmartList = Nothing
}
-- | Resource type for include conditions.
icKind :: Lens' IncludeConditions Text
icKind = lens _icKind (\ s a -> s{_icKind = a})
-- | The look-back window lets you specify a time frame for evaluating the
-- behavior that qualifies users for your audience. For example, if your
-- filters include users from Central Asia, and Transactions Greater than
-- 2, and you set the look-back window to 14 days, then any user from
-- Central Asia whose cumulative transactions exceed 2 during the last 14
-- days is added to the audience.
icDaysToLookBack :: Lens' IncludeConditions (Maybe Int32)
icDaysToLookBack
= lens _icDaysToLookBack
(\ s a -> s{_icDaysToLookBack = a})
. mapping _Coerce
-- | Number of days (in the range 1 to 540) a user remains in the audience.
icMembershipDurationDays :: Lens' IncludeConditions (Maybe Int32)
icMembershipDurationDays
= lens _icMembershipDurationDays
(\ s a -> s{_icMembershipDurationDays = a})
. mapping _Coerce
-- | The segment condition that will cause a user to be added to an audience.
icSegment :: Lens' IncludeConditions (Maybe Text)
icSegment
= lens _icSegment (\ s a -> s{_icSegment = a})
-- | Boolean indicating whether this segment is a smart list.
-- https:\/\/support.google.com\/analytics\/answer\/4628577
icIsSmartList :: Lens' IncludeConditions (Maybe Bool)
icIsSmartList
= lens _icIsSmartList
(\ s a -> s{_icIsSmartList = a})
instance FromJSON IncludeConditions where
parseJSON
= withObject "IncludeConditions"
(\ o ->
IncludeConditions' <$>
(o .:? "kind" .!= "analytics#includeConditions") <*>
(o .:? "daysToLookBack")
<*> (o .:? "membershipDurationDays")
<*> (o .:? "segment")
<*> (o .:? "isSmartList"))
instance ToJSON IncludeConditions where
toJSON IncludeConditions'{..}
= object
(catMaybes
[Just ("kind" .= _icKind),
("daysToLookBack" .=) <$> _icDaysToLookBack,
("membershipDurationDays" .=) <$>
_icMembershipDurationDays,
("segment" .=) <$> _icSegment,
("isSmartList" .=) <$> _icIsSmartList])
-- | Parent link for this filter. Points to the account to which this filter
-- belongs.
--
-- /See:/ 'filterParentLink' smart constructor.
data FilterParentLink =
FilterParentLink'
{ _fplHref :: !(Maybe Text)
, _fplType :: !Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'FilterParentLink' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'fplHref'
--
-- * 'fplType'
filterParentLink
:: FilterParentLink
filterParentLink =
FilterParentLink' {_fplHref = Nothing, _fplType = "analytics#account"}
-- | Link to the account to which this filter belongs.
fplHref :: Lens' FilterParentLink (Maybe Text)
fplHref = lens _fplHref (\ s a -> s{_fplHref = a})
-- | Value is \"analytics#account\".
fplType :: Lens' FilterParentLink Text
fplType = lens _fplType (\ s a -> s{_fplType = a})
instance FromJSON FilterParentLink where
parseJSON
= withObject "FilterParentLink"
(\ o ->
FilterParentLink' <$>
(o .:? "href") <*>
(o .:? "type" .!= "analytics#account"))
instance ToJSON FilterParentLink where
toJSON FilterParentLink'{..}
= object
(catMaybes
[("href" .=) <$> _fplHref,
Just ("type" .= _fplType)])
-- | JSON template for a hash Client Id request resource.
--
-- /See:/ 'hashClientIdRequest' smart constructor.
data HashClientIdRequest =
HashClientIdRequest'
{ _hClientId :: !(Maybe Text)
, _hWebPropertyId :: !(Maybe Text)
, _hKind :: !Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'HashClientIdRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'hClientId'
--
-- * 'hWebPropertyId'
--
-- * 'hKind'
hashClientIdRequest
:: HashClientIdRequest
hashClientIdRequest =
HashClientIdRequest'
{ _hClientId = Nothing
, _hWebPropertyId = Nothing
, _hKind = "analytics#hashClientIdRequest"
}
hClientId :: Lens' HashClientIdRequest (Maybe Text)
hClientId
= lens _hClientId (\ s a -> s{_hClientId = a})
hWebPropertyId :: Lens' HashClientIdRequest (Maybe Text)
hWebPropertyId
= lens _hWebPropertyId
(\ s a -> s{_hWebPropertyId = a})
hKind :: Lens' HashClientIdRequest Text
hKind = lens _hKind (\ s a -> s{_hKind = a})
instance FromJSON HashClientIdRequest where
parseJSON
= withObject "HashClientIdRequest"
(\ o ->
HashClientIdRequest' <$>
(o .:? "clientId") <*> (o .:? "webPropertyId") <*>
(o .:? "kind" .!= "analytics#hashClientIdRequest"))
instance ToJSON HashClientIdRequest where
toJSON HashClientIdRequest'{..}
= object
(catMaybes
[("clientId" .=) <$> _hClientId,
("webPropertyId" .=) <$> _hWebPropertyId,
Just ("kind" .= _hKind)])
-- | Real time data for a given view (profile).
--
-- /See:/ 'realtimeData' smart constructor.
data RealtimeData =
RealtimeData'
{ _rdProFileInfo :: !(Maybe RealtimeDataProFileInfo)
, _rdKind :: !Text
, _rdRows :: !(Maybe [[Text]])
, _rdSelfLink :: !(Maybe Text)
, _rdQuery :: !(Maybe RealtimeDataQuery)
, _rdColumnHeaders :: !(Maybe [RealtimeDataColumnHeadersItem])
, _rdId :: !(Maybe Text)
, _rdTotalResults :: !(Maybe (Textual Int32))
, _rdTotalsForAllResults :: !(Maybe RealtimeDataTotalsForAllResults)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'RealtimeData' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'rdProFileInfo'
--
-- * 'rdKind'
--
-- * 'rdRows'
--
-- * 'rdSelfLink'
--
-- * 'rdQuery'
--
-- * 'rdColumnHeaders'
--
-- * 'rdId'
--
-- * 'rdTotalResults'
--
-- * 'rdTotalsForAllResults'
realtimeData
:: RealtimeData
realtimeData =
RealtimeData'
{ _rdProFileInfo = Nothing
, _rdKind = "analytics#realtimeData"
, _rdRows = Nothing
, _rdSelfLink = Nothing
, _rdQuery = Nothing
, _rdColumnHeaders = Nothing
, _rdId = Nothing
, _rdTotalResults = Nothing
, _rdTotalsForAllResults = Nothing
}
-- | Information for the view (profile), for which the real time data was
-- requested.
rdProFileInfo :: Lens' RealtimeData (Maybe RealtimeDataProFileInfo)
rdProFileInfo
= lens _rdProFileInfo
(\ s a -> s{_rdProFileInfo = a})
-- | Resource type.
rdKind :: Lens' RealtimeData Text
rdKind = lens _rdKind (\ s a -> s{_rdKind = a})
-- | Real time data rows, where each row contains a list of dimension values
-- followed by the metric values. The order of dimensions and metrics is
-- same as specified in the request.
rdRows :: Lens' RealtimeData [[Text]]
rdRows
= lens _rdRows (\ s a -> s{_rdRows = a}) . _Default .
_Coerce
-- | Link to this page.
rdSelfLink :: Lens' RealtimeData (Maybe Text)
rdSelfLink
= lens _rdSelfLink (\ s a -> s{_rdSelfLink = a})
-- | Real time data request query parameters.
rdQuery :: Lens' RealtimeData (Maybe RealtimeDataQuery)
rdQuery = lens _rdQuery (\ s a -> s{_rdQuery = a})
-- | Column headers that list dimension names followed by the metric names.
-- The order of dimensions and metrics is same as specified in the request.
rdColumnHeaders :: Lens' RealtimeData [RealtimeDataColumnHeadersItem]
rdColumnHeaders
= lens _rdColumnHeaders
(\ s a -> s{_rdColumnHeaders = a})
. _Default
. _Coerce
-- | Unique ID for this data response.
rdId :: Lens' RealtimeData (Maybe Text)
rdId = lens _rdId (\ s a -> s{_rdId = a})
-- | The total number of rows for the query, regardless of the number of rows
-- in the response.
rdTotalResults :: Lens' RealtimeData (Maybe Int32)
rdTotalResults
= lens _rdTotalResults
(\ s a -> s{_rdTotalResults = a})
. mapping _Coerce
-- | Total values for the requested metrics over all the results, not just
-- the results returned in this response. The order of the metric totals is
-- same as the metric order specified in the request.
rdTotalsForAllResults :: Lens' RealtimeData (Maybe RealtimeDataTotalsForAllResults)
rdTotalsForAllResults
= lens _rdTotalsForAllResults
(\ s a -> s{_rdTotalsForAllResults = a})
instance FromJSON RealtimeData where
parseJSON
= withObject "RealtimeData"
(\ o ->
RealtimeData' <$>
(o .:? "profileInfo") <*>
(o .:? "kind" .!= "analytics#realtimeData")
<*> (o .:? "rows" .!= mempty)
<*> (o .:? "selfLink")
<*> (o .:? "query")
<*> (o .:? "columnHeaders" .!= mempty)
<*> (o .:? "id")
<*> (o .:? "totalResults")
<*> (o .:? "totalsForAllResults"))
instance ToJSON RealtimeData where
toJSON RealtimeData'{..}
= object
(catMaybes
[("profileInfo" .=) <$> _rdProFileInfo,
Just ("kind" .= _rdKind), ("rows" .=) <$> _rdRows,
("selfLink" .=) <$> _rdSelfLink,
("query" .=) <$> _rdQuery,
("columnHeaders" .=) <$> _rdColumnHeaders,
("id" .=) <$> _rdId,
("totalResults" .=) <$> _rdTotalResults,
("totalsForAllResults" .=) <$>
_rdTotalsForAllResults])
-- | JSON template for Analytics Custom Metric.
--
-- /See:/ 'customMetric' smart constructor.
data CustomMetric =
CustomMetric'
{ _cusParentLink :: !(Maybe CustomMetricParentLink)
, _cusWebPropertyId :: !(Maybe Text)
, _cusKind :: !Text
, _cusMaxValue :: !(Maybe Text)
, _cusCreated :: !(Maybe DateTime')
, _cusMinValue :: !(Maybe Text)
, _cusActive :: !(Maybe Bool)
, _cusSelfLink :: !(Maybe Text)
, _cusAccountId :: !(Maybe Text)
, _cusName :: !(Maybe Text)
, _cusScope :: !(Maybe Text)
, _cusId :: !(Maybe Text)
, _cusUpdated :: !(Maybe DateTime')
, _cusType :: !(Maybe Text)
, _cusIndex :: !(Maybe (Textual Int32))
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'CustomMetric' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cusParentLink'
--
-- * 'cusWebPropertyId'
--
-- * 'cusKind'
--
-- * 'cusMaxValue'
--
-- * 'cusCreated'
--
-- * 'cusMinValue'
--
-- * 'cusActive'
--
-- * 'cusSelfLink'
--
-- * 'cusAccountId'
--
-- * 'cusName'
--
-- * 'cusScope'
--
-- * 'cusId'
--
-- * 'cusUpdated'
--
-- * 'cusType'
--
-- * 'cusIndex'
customMetric
:: CustomMetric
customMetric =
CustomMetric'
{ _cusParentLink = Nothing
, _cusWebPropertyId = Nothing
, _cusKind = "analytics#customMetric"
, _cusMaxValue = Nothing
, _cusCreated = Nothing
, _cusMinValue = Nothing
, _cusActive = Nothing
, _cusSelfLink = Nothing
, _cusAccountId = Nothing
, _cusName = Nothing
, _cusScope = Nothing
, _cusId = Nothing
, _cusUpdated = Nothing
, _cusType = Nothing
, _cusIndex = Nothing
}
-- | Parent link for the custom metric. Points to the property to which the
-- custom metric belongs.
cusParentLink :: Lens' CustomMetric (Maybe CustomMetricParentLink)
cusParentLink
= lens _cusParentLink
(\ s a -> s{_cusParentLink = a})
-- | Property ID.
cusWebPropertyId :: Lens' CustomMetric (Maybe Text)
cusWebPropertyId
= lens _cusWebPropertyId
(\ s a -> s{_cusWebPropertyId = a})
-- | Kind value for a custom metric. Set to \"analytics#customMetric\". It is
-- a read-only field.
cusKind :: Lens' CustomMetric Text
cusKind = lens _cusKind (\ s a -> s{_cusKind = a})
-- | Max value of custom metric.
cusMaxValue :: Lens' CustomMetric (Maybe Text)
cusMaxValue
= lens _cusMaxValue (\ s a -> s{_cusMaxValue = a})
-- | Time the custom metric was created.
cusCreated :: Lens' CustomMetric (Maybe UTCTime)
cusCreated
= lens _cusCreated (\ s a -> s{_cusCreated = a}) .
mapping _DateTime
-- | Min value of custom metric.
cusMinValue :: Lens' CustomMetric (Maybe Text)
cusMinValue
= lens _cusMinValue (\ s a -> s{_cusMinValue = a})
-- | Boolean indicating whether the custom metric is active.
cusActive :: Lens' CustomMetric (Maybe Bool)
cusActive
= lens _cusActive (\ s a -> s{_cusActive = a})
-- | Link for the custom metric
cusSelfLink :: Lens' CustomMetric (Maybe Text)
cusSelfLink
= lens _cusSelfLink (\ s a -> s{_cusSelfLink = a})
-- | Account ID.
cusAccountId :: Lens' CustomMetric (Maybe Text)
cusAccountId
= lens _cusAccountId (\ s a -> s{_cusAccountId = a})
-- | Name of the custom metric.
cusName :: Lens' CustomMetric (Maybe Text)
cusName = lens _cusName (\ s a -> s{_cusName = a})
-- | Scope of the custom metric: HIT or PRODUCT.
cusScope :: Lens' CustomMetric (Maybe Text)
cusScope = lens _cusScope (\ s a -> s{_cusScope = a})
-- | Custom metric ID.
cusId :: Lens' CustomMetric (Maybe Text)
cusId = lens _cusId (\ s a -> s{_cusId = a})
-- | Time the custom metric was last modified.
cusUpdated :: Lens' CustomMetric (Maybe UTCTime)
cusUpdated
= lens _cusUpdated (\ s a -> s{_cusUpdated = a}) .
mapping _DateTime
-- | Data type of custom metric.
cusType :: Lens' CustomMetric (Maybe Text)
cusType = lens _cusType (\ s a -> s{_cusType = a})
-- | Index of the custom metric.
cusIndex :: Lens' CustomMetric (Maybe Int32)
cusIndex
= lens _cusIndex (\ s a -> s{_cusIndex = a}) .
mapping _Coerce
instance FromJSON CustomMetric where
parseJSON
= withObject "CustomMetric"
(\ o ->
CustomMetric' <$>
(o .:? "parentLink") <*> (o .:? "webPropertyId") <*>
(o .:? "kind" .!= "analytics#customMetric")
<*> (o .:? "max_value")
<*> (o .:? "created")
<*> (o .:? "min_value")
<*> (o .:? "active")
<*> (o .:? "selfLink")
<*> (o .:? "accountId")
<*> (o .:? "name")
<*> (o .:? "scope")
<*> (o .:? "id")
<*> (o .:? "updated")
<*> (o .:? "type")
<*> (o .:? "index"))
instance ToJSON CustomMetric where
toJSON CustomMetric'{..}
= object
(catMaybes
[("parentLink" .=) <$> _cusParentLink,
("webPropertyId" .=) <$> _cusWebPropertyId,
Just ("kind" .= _cusKind),
("max_value" .=) <$> _cusMaxValue,
("created" .=) <$> _cusCreated,
("min_value" .=) <$> _cusMinValue,
("active" .=) <$> _cusActive,
("selfLink" .=) <$> _cusSelfLink,
("accountId" .=) <$> _cusAccountId,
("name" .=) <$> _cusName, ("scope" .=) <$> _cusScope,
("id" .=) <$> _cusId, ("updated" .=) <$> _cusUpdated,
("type" .=) <$> _cusType,
("index" .=) <$> _cusIndex])
-- | JSON template for an Analytics ProfileSummary. ProfileSummary returns
-- basic information (i.e., summary) for a profile.
--
-- /See:/ 'proFileSummary' smart constructor.
data ProFileSummary =
ProFileSummary'
{ _pfsKind :: !Text
, _pfsName :: !(Maybe Text)
, _pfsStarred :: !(Maybe Bool)
, _pfsId :: !(Maybe Text)
, _pfsType :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProFileSummary' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pfsKind'
--
-- * 'pfsName'
--
-- * 'pfsStarred'
--
-- * 'pfsId'
--
-- * 'pfsType'
proFileSummary
:: ProFileSummary
proFileSummary =
ProFileSummary'
{ _pfsKind = "analytics#profileSummary"
, _pfsName = Nothing
, _pfsStarred = Nothing
, _pfsId = Nothing
, _pfsType = Nothing
}
-- | Resource type for Analytics ProfileSummary.
pfsKind :: Lens' ProFileSummary Text
pfsKind = lens _pfsKind (\ s a -> s{_pfsKind = a})
-- | View (profile) name.
pfsName :: Lens' ProFileSummary (Maybe Text)
pfsName = lens _pfsName (\ s a -> s{_pfsName = a})
-- | Indicates whether this view (profile) is starred or not.
pfsStarred :: Lens' ProFileSummary (Maybe Bool)
pfsStarred
= lens _pfsStarred (\ s a -> s{_pfsStarred = a})
-- | View (profile) ID.
pfsId :: Lens' ProFileSummary (Maybe Text)
pfsId = lens _pfsId (\ s a -> s{_pfsId = a})
-- | View (Profile) type. Supported types: WEB or APP.
pfsType :: Lens' ProFileSummary (Maybe Text)
pfsType = lens _pfsType (\ s a -> s{_pfsType = a})
instance FromJSON ProFileSummary where
parseJSON
= withObject "ProFileSummary"
(\ o ->
ProFileSummary' <$>
(o .:? "kind" .!= "analytics#profileSummary") <*>
(o .:? "name")
<*> (o .:? "starred")
<*> (o .:? "id")
<*> (o .:? "type"))
instance ToJSON ProFileSummary where
toJSON ProFileSummary'{..}
= object
(catMaybes
[Just ("kind" .= _pfsKind), ("name" .=) <$> _pfsName,
("starred" .=) <$> _pfsStarred, ("id" .=) <$> _pfsId,
("type" .=) <$> _pfsType])
-- | Parent link for the custom dimension. Points to the property to which
-- the custom dimension belongs.
--
-- /See:/ 'customDimensionParentLink' smart constructor.
data CustomDimensionParentLink =
CustomDimensionParentLink'
{ _cdplHref :: !(Maybe Text)
, _cdplType :: !Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'CustomDimensionParentLink' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cdplHref'
--
-- * 'cdplType'
customDimensionParentLink
:: CustomDimensionParentLink
customDimensionParentLink =
CustomDimensionParentLink'
{_cdplHref = Nothing, _cdplType = "analytics#webproperty"}
-- | Link to the property to which the custom dimension belongs.
cdplHref :: Lens' CustomDimensionParentLink (Maybe Text)
cdplHref = lens _cdplHref (\ s a -> s{_cdplHref = a})
-- | Type of the parent link. Set to \"analytics#webproperty\".
cdplType :: Lens' CustomDimensionParentLink Text
cdplType = lens _cdplType (\ s a -> s{_cdplType = a})
instance FromJSON CustomDimensionParentLink where
parseJSON
= withObject "CustomDimensionParentLink"
(\ o ->
CustomDimensionParentLink' <$>
(o .:? "href") <*>
(o .:? "type" .!= "analytics#webproperty"))
instance ToJSON CustomDimensionParentLink where
toJSON CustomDimensionParentLink'{..}
= object
(catMaybes
[("href" .=) <$> _cdplHref,
Just ("type" .= _cdplType)])
-- | JSON template for an Analytics web property.
--
-- /See:/ 'webProperty' smart constructor.
data WebProperty =
WebProperty'
{ _wParentLink :: !(Maybe WebPropertyParentLink)
, _wChildLink :: !(Maybe WebPropertyChildLink)
, _wDefaultProFileId :: !(Maybe (Textual Int64))
, _wKind :: !Text
, _wCreated :: !(Maybe DateTime')
, _wDataRetentionTtl :: !(Maybe Text)
, _wDataRetentionResetOnNewActivity :: !(Maybe Bool)
, _wSelfLink :: !(Maybe Text)
, _wAccountId :: !(Maybe Text)
, _wName :: !(Maybe Text)
, _wStarred :: !(Maybe Bool)
, _wInternalWebPropertyId :: !(Maybe Text)
, _wId :: !(Maybe Text)
, _wUpdated :: !(Maybe DateTime')
, _wProFileCount :: !(Maybe (Textual Int32))
, _wPermissions :: !(Maybe WebPropertyPermissions)
, _wWebsiteURL :: !(Maybe Text)
, _wIndustryVertical :: !(Maybe Text)
, _wLevel :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'WebProperty' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'wParentLink'
--
-- * 'wChildLink'
--
-- * 'wDefaultProFileId'
--
-- * 'wKind'
--
-- * 'wCreated'
--
-- * 'wDataRetentionTtl'
--
-- * 'wDataRetentionResetOnNewActivity'
--
-- * 'wSelfLink'
--
-- * 'wAccountId'
--
-- * 'wName'
--
-- * 'wStarred'
--
-- * 'wInternalWebPropertyId'
--
-- * 'wId'
--
-- * 'wUpdated'
--
-- * 'wProFileCount'
--
-- * 'wPermissions'
--
-- * 'wWebsiteURL'
--
-- * 'wIndustryVertical'
--
-- * 'wLevel'
webProperty
:: WebProperty
webProperty =
WebProperty'
{ _wParentLink = Nothing
, _wChildLink = Nothing
, _wDefaultProFileId = Nothing
, _wKind = "analytics#webproperty"
, _wCreated = Nothing
, _wDataRetentionTtl = Nothing
, _wDataRetentionResetOnNewActivity = Nothing
, _wSelfLink = Nothing
, _wAccountId = Nothing
, _wName = Nothing
, _wStarred = Nothing
, _wInternalWebPropertyId = Nothing
, _wId = Nothing
, _wUpdated = Nothing
, _wProFileCount = Nothing
, _wPermissions = Nothing
, _wWebsiteURL = Nothing
, _wIndustryVertical = Nothing
, _wLevel = Nothing
}
-- | Parent link for this web property. Points to the account to which this
-- web property belongs.
wParentLink :: Lens' WebProperty (Maybe WebPropertyParentLink)
wParentLink
= lens _wParentLink (\ s a -> s{_wParentLink = a})
-- | Child link for this web property. Points to the list of views (profiles)
-- for this web property.
wChildLink :: Lens' WebProperty (Maybe WebPropertyChildLink)
wChildLink
= lens _wChildLink (\ s a -> s{_wChildLink = a})
-- | Default view (profile) ID.
wDefaultProFileId :: Lens' WebProperty (Maybe Int64)
wDefaultProFileId
= lens _wDefaultProFileId
(\ s a -> s{_wDefaultProFileId = a})
. mapping _Coerce
-- | Resource type for Analytics WebProperty.
wKind :: Lens' WebProperty Text
wKind = lens _wKind (\ s a -> s{_wKind = a})
-- | Time this web property was created.
wCreated :: Lens' WebProperty (Maybe UTCTime)
wCreated
= lens _wCreated (\ s a -> s{_wCreated = a}) .
mapping _DateTime
-- | The length of time for which user and event data is retained. This
-- property cannot be set on insert.
wDataRetentionTtl :: Lens' WebProperty (Maybe Text)
wDataRetentionTtl
= lens _wDataRetentionTtl
(\ s a -> s{_wDataRetentionTtl = a})
-- | Set to true to reset the retention period of the user identifier with
-- each new event from that user (thus setting the expiration date to
-- current time plus retention period). Set to false to delete data
-- associated with the user identifier automatically after the rentention
-- period. This property cannot be set on insert.
wDataRetentionResetOnNewActivity :: Lens' WebProperty (Maybe Bool)
wDataRetentionResetOnNewActivity
= lens _wDataRetentionResetOnNewActivity
(\ s a -> s{_wDataRetentionResetOnNewActivity = a})
-- | Link for this web property.
wSelfLink :: Lens' WebProperty (Maybe Text)
wSelfLink
= lens _wSelfLink (\ s a -> s{_wSelfLink = a})
-- | Account ID to which this web property belongs.
wAccountId :: Lens' WebProperty (Maybe Text)
wAccountId
= lens _wAccountId (\ s a -> s{_wAccountId = a})
-- | Name of this web property.
wName :: Lens' WebProperty (Maybe Text)
wName = lens _wName (\ s a -> s{_wName = a})
-- | Indicates whether this web property is starred or not.
wStarred :: Lens' WebProperty (Maybe Bool)
wStarred = lens _wStarred (\ s a -> s{_wStarred = a})
-- | Internal ID for this web property.
wInternalWebPropertyId :: Lens' WebProperty (Maybe Text)
wInternalWebPropertyId
= lens _wInternalWebPropertyId
(\ s a -> s{_wInternalWebPropertyId = a})
-- | Web property ID of the form UA-XXXXX-YY.
wId :: Lens' WebProperty (Maybe Text)
wId = lens _wId (\ s a -> s{_wId = a})
-- | Time this web property was last modified.
wUpdated :: Lens' WebProperty (Maybe UTCTime)
wUpdated
= lens _wUpdated (\ s a -> s{_wUpdated = a}) .
mapping _DateTime
-- | View (Profile) count for this web property.
wProFileCount :: Lens' WebProperty (Maybe Int32)
wProFileCount
= lens _wProFileCount
(\ s a -> s{_wProFileCount = a})
. mapping _Coerce
-- | Permissions the user has for this web property.
wPermissions :: Lens' WebProperty (Maybe WebPropertyPermissions)
wPermissions
= lens _wPermissions (\ s a -> s{_wPermissions = a})
-- | Website url for this web property.
wWebsiteURL :: Lens' WebProperty (Maybe Text)
wWebsiteURL
= lens _wWebsiteURL (\ s a -> s{_wWebsiteURL = a})
-- | The industry vertical\/category selected for this web property.
wIndustryVertical :: Lens' WebProperty (Maybe Text)
wIndustryVertical
= lens _wIndustryVertical
(\ s a -> s{_wIndustryVertical = a})
-- | Level for this web property. Possible values are STANDARD or PREMIUM.
wLevel :: Lens' WebProperty (Maybe Text)
wLevel = lens _wLevel (\ s a -> s{_wLevel = a})
instance FromJSON WebProperty where
parseJSON
= withObject "WebProperty"
(\ o ->
WebProperty' <$>
(o .:? "parentLink") <*> (o .:? "childLink") <*>
(o .:? "defaultProfileId")
<*> (o .:? "kind" .!= "analytics#webproperty")
<*> (o .:? "created")
<*> (o .:? "dataRetentionTtl")
<*> (o .:? "dataRetentionResetOnNewActivity")
<*> (o .:? "selfLink")
<*> (o .:? "accountId")
<*> (o .:? "name")
<*> (o .:? "starred")
<*> (o .:? "internalWebPropertyId")
<*> (o .:? "id")
<*> (o .:? "updated")
<*> (o .:? "profileCount")
<*> (o .:? "permissions")
<*> (o .:? "websiteUrl")
<*> (o .:? "industryVertical")
<*> (o .:? "level"))
instance ToJSON WebProperty where
toJSON WebProperty'{..}
= object
(catMaybes
[("parentLink" .=) <$> _wParentLink,
("childLink" .=) <$> _wChildLink,
("defaultProfileId" .=) <$> _wDefaultProFileId,
Just ("kind" .= _wKind),
("created" .=) <$> _wCreated,
("dataRetentionTtl" .=) <$> _wDataRetentionTtl,
("dataRetentionResetOnNewActivity" .=) <$>
_wDataRetentionResetOnNewActivity,
("selfLink" .=) <$> _wSelfLink,
("accountId" .=) <$> _wAccountId,
("name" .=) <$> _wName, ("starred" .=) <$> _wStarred,
("internalWebPropertyId" .=) <$>
_wInternalWebPropertyId,
("id" .=) <$> _wId, ("updated" .=) <$> _wUpdated,
("profileCount" .=) <$> _wProFileCount,
("permissions" .=) <$> _wPermissions,
("websiteUrl" .=) <$> _wWebsiteURL,
("industryVertical" .=) <$> _wIndustryVertical,
("level" .=) <$> _wLevel])
-- | Permissions the user has for this web property.
--
-- /See:/ 'webPropertyPermissions' smart constructor.
newtype WebPropertyPermissions =
WebPropertyPermissions'
{ _wppEffective :: Maybe [Text]
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'WebPropertyPermissions' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'wppEffective'
webPropertyPermissions
:: WebPropertyPermissions
webPropertyPermissions = WebPropertyPermissions' {_wppEffective = Nothing}
-- | All the permissions that the user has for this web property. These
-- include any implied permissions (e.g., EDIT implies VIEW) or inherited
-- permissions from the parent account.
wppEffective :: Lens' WebPropertyPermissions [Text]
wppEffective
= lens _wppEffective (\ s a -> s{_wppEffective = a})
. _Default
. _Coerce
instance FromJSON WebPropertyPermissions where
parseJSON
= withObject "WebPropertyPermissions"
(\ o ->
WebPropertyPermissions' <$>
(o .:? "effective" .!= mempty))
instance ToJSON WebPropertyPermissions where
toJSON WebPropertyPermissions'{..}
= object
(catMaybes [("effective" .=) <$> _wppEffective])
-- | JSON template for an Analytics Entity-User Link. Returns permissions
-- that a user has for an entity.
--
-- /See:/ 'entityUserLink' smart constructor.
data EntityUserLink =
EntityUserLink'
{ _euluKind :: !Text
, _euluUserRef :: !(Maybe UserRef)
, _euluSelfLink :: !(Maybe Text)
, _euluId :: !(Maybe Text)
, _euluPermissions :: !(Maybe EntityUserLinkPermissions)
, _euluEntity :: !(Maybe EntityUserLinkEntity)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'EntityUserLink' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'euluKind'
--
-- * 'euluUserRef'
--
-- * 'euluSelfLink'
--
-- * 'euluId'
--
-- * 'euluPermissions'
--
-- * 'euluEntity'
entityUserLink
:: EntityUserLink
entityUserLink =
EntityUserLink'
{ _euluKind = "analytics#entityUserLink"
, _euluUserRef = Nothing
, _euluSelfLink = Nothing
, _euluId = Nothing
, _euluPermissions = Nothing
, _euluEntity = Nothing
}
-- | Resource type for entity user link.
euluKind :: Lens' EntityUserLink Text
euluKind = lens _euluKind (\ s a -> s{_euluKind = a})
-- | User reference.
euluUserRef :: Lens' EntityUserLink (Maybe UserRef)
euluUserRef
= lens _euluUserRef (\ s a -> s{_euluUserRef = a})
-- | Self link for this resource.
euluSelfLink :: Lens' EntityUserLink (Maybe Text)
euluSelfLink
= lens _euluSelfLink (\ s a -> s{_euluSelfLink = a})
-- | Entity user link ID
euluId :: Lens' EntityUserLink (Maybe Text)
euluId = lens _euluId (\ s a -> s{_euluId = a})
-- | Permissions the user has for this entity.
euluPermissions :: Lens' EntityUserLink (Maybe EntityUserLinkPermissions)
euluPermissions
= lens _euluPermissions
(\ s a -> s{_euluPermissions = a})
-- | Entity for this link. It can be an account, a web property, or a view
-- (profile).
euluEntity :: Lens' EntityUserLink (Maybe EntityUserLinkEntity)
euluEntity
= lens _euluEntity (\ s a -> s{_euluEntity = a})
instance FromJSON EntityUserLink where
parseJSON
= withObject "EntityUserLink"
(\ o ->
EntityUserLink' <$>
(o .:? "kind" .!= "analytics#entityUserLink") <*>
(o .:? "userRef")
<*> (o .:? "selfLink")
<*> (o .:? "id")
<*> (o .:? "permissions")
<*> (o .:? "entity"))
instance ToJSON EntityUserLink where
toJSON EntityUserLink'{..}
= object
(catMaybes
[Just ("kind" .= _euluKind),
("userRef" .=) <$> _euluUserRef,
("selfLink" .=) <$> _euluSelfLink,
("id" .=) <$> _euluId,
("permissions" .=) <$> _euluPermissions,
("entity" .=) <$> _euluEntity])
-- | Parent link for this custom data source. Points to the web property to
-- which this custom data source belongs.
--
-- /See:/ 'customDataSourceParentLink' smart constructor.
data CustomDataSourceParentLink =
CustomDataSourceParentLink'
{ _cdsplHref :: !(Maybe Text)
, _cdsplType :: !Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'CustomDataSourceParentLink' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cdsplHref'
--
-- * 'cdsplType'
customDataSourceParentLink
:: CustomDataSourceParentLink
customDataSourceParentLink =
CustomDataSourceParentLink'
{_cdsplHref = Nothing, _cdsplType = "analytics#webproperty"}
-- | Link to the web property to which this custom data source belongs.
cdsplHref :: Lens' CustomDataSourceParentLink (Maybe Text)
cdsplHref
= lens _cdsplHref (\ s a -> s{_cdsplHref = a})
-- | Value is \"analytics#webproperty\".
cdsplType :: Lens' CustomDataSourceParentLink Text
cdsplType
= lens _cdsplType (\ s a -> s{_cdsplType = a})
instance FromJSON CustomDataSourceParentLink where
parseJSON
= withObject "CustomDataSourceParentLink"
(\ o ->
CustomDataSourceParentLink' <$>
(o .:? "href") <*>
(o .:? "type" .!= "analytics#webproperty"))
instance ToJSON CustomDataSourceParentLink where
toJSON CustomDataSourceParentLink'{..}
= object
(catMaybes
[("href" .=) <$> _cdsplHref,
Just ("type" .= _cdsplType)])
--
-- /See:/ 'goalEventDetailsEventConditionsItem' smart constructor.
data GoalEventDetailsEventConditionsItem =
GoalEventDetailsEventConditionsItem'
{ _gedeciMatchType :: !(Maybe Text)
, _gedeciExpression :: !(Maybe Text)
, _gedeciComparisonValue :: !(Maybe (Textual Int64))
, _gedeciType :: !(Maybe Text)
, _gedeciComparisonType :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'GoalEventDetailsEventConditionsItem' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gedeciMatchType'
--
-- * 'gedeciExpression'
--
-- * 'gedeciComparisonValue'
--
-- * 'gedeciType'
--
-- * 'gedeciComparisonType'
goalEventDetailsEventConditionsItem
:: GoalEventDetailsEventConditionsItem
goalEventDetailsEventConditionsItem =
GoalEventDetailsEventConditionsItem'
{ _gedeciMatchType = Nothing
, _gedeciExpression = Nothing
, _gedeciComparisonValue = Nothing
, _gedeciType = Nothing
, _gedeciComparisonType = Nothing
}
-- | Type of the match to be performed. Possible values are REGEXP,
-- BEGINS_WITH, or EXACT.
gedeciMatchType :: Lens' GoalEventDetailsEventConditionsItem (Maybe Text)
gedeciMatchType
= lens _gedeciMatchType
(\ s a -> s{_gedeciMatchType = a})
-- | Expression used for this match.
gedeciExpression :: Lens' GoalEventDetailsEventConditionsItem (Maybe Text)
gedeciExpression
= lens _gedeciExpression
(\ s a -> s{_gedeciExpression = a})
-- | Value used for this comparison.
gedeciComparisonValue :: Lens' GoalEventDetailsEventConditionsItem (Maybe Int64)
gedeciComparisonValue
= lens _gedeciComparisonValue
(\ s a -> s{_gedeciComparisonValue = a})
. mapping _Coerce
-- | Type of this event condition. Possible values are CATEGORY, ACTION,
-- LABEL, or VALUE.
gedeciType :: Lens' GoalEventDetailsEventConditionsItem (Maybe Text)
gedeciType
= lens _gedeciType (\ s a -> s{_gedeciType = a})
-- | Type of comparison. Possible values are LESS_THAN, GREATER_THAN or
-- EQUAL.
gedeciComparisonType :: Lens' GoalEventDetailsEventConditionsItem (Maybe Text)
gedeciComparisonType
= lens _gedeciComparisonType
(\ s a -> s{_gedeciComparisonType = a})
instance FromJSON GoalEventDetailsEventConditionsItem
where
parseJSON
= withObject "GoalEventDetailsEventConditionsItem"
(\ o ->
GoalEventDetailsEventConditionsItem' <$>
(o .:? "matchType") <*> (o .:? "expression") <*>
(o .:? "comparisonValue")
<*> (o .:? "type")
<*> (o .:? "comparisonType"))
instance ToJSON GoalEventDetailsEventConditionsItem
where
toJSON GoalEventDetailsEventConditionsItem'{..}
= object
(catMaybes
[("matchType" .=) <$> _gedeciMatchType,
("expression" .=) <$> _gedeciExpression,
("comparisonValue" .=) <$> _gedeciComparisonValue,
("type" .=) <$> _gedeciType,
("comparisonType" .=) <$> _gedeciComparisonType])
-- | Analytics data request query parameters.
--
-- /See:/ 'mcfDataQuery' smart constructor.
data McfDataQuery =
McfDataQuery'
{ _mdqMetrics :: !(Maybe [Text])
, _mdqSamplingLevel :: !(Maybe Text)
, _mdqFilters :: !(Maybe Text)
, _mdqIds :: !(Maybe Text)
, _mdqEndDate :: !(Maybe Text)
, _mdqSort :: !(Maybe [Text])
, _mdqDimensions :: !(Maybe Text)
, _mdqStartIndex :: !(Maybe (Textual Int32))
, _mdqMaxResults :: !(Maybe (Textual Int32))
, _mdqSegment :: !(Maybe Text)
, _mdqStartDate :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'McfDataQuery' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'mdqMetrics'
--
-- * 'mdqSamplingLevel'
--
-- * 'mdqFilters'
--
-- * 'mdqIds'
--
-- * 'mdqEndDate'
--
-- * 'mdqSort'
--
-- * 'mdqDimensions'
--
-- * 'mdqStartIndex'
--
-- * 'mdqMaxResults'
--
-- * 'mdqSegment'
--
-- * 'mdqStartDate'
mcfDataQuery
:: McfDataQuery
mcfDataQuery =
McfDataQuery'
{ _mdqMetrics = Nothing
, _mdqSamplingLevel = Nothing
, _mdqFilters = Nothing
, _mdqIds = Nothing
, _mdqEndDate = Nothing
, _mdqSort = Nothing
, _mdqDimensions = Nothing
, _mdqStartIndex = Nothing
, _mdqMaxResults = Nothing
, _mdqSegment = Nothing
, _mdqStartDate = Nothing
}
-- | List of analytics metrics.
mdqMetrics :: Lens' McfDataQuery [Text]
mdqMetrics
= lens _mdqMetrics (\ s a -> s{_mdqMetrics = a}) .
_Default
. _Coerce
-- | Desired sampling level
mdqSamplingLevel :: Lens' McfDataQuery (Maybe Text)
mdqSamplingLevel
= lens _mdqSamplingLevel
(\ s a -> s{_mdqSamplingLevel = a})
-- | Comma-separated list of dimension or metric filters.
mdqFilters :: Lens' McfDataQuery (Maybe Text)
mdqFilters
= lens _mdqFilters (\ s a -> s{_mdqFilters = a})
-- | Unique table ID.
mdqIds :: Lens' McfDataQuery (Maybe Text)
mdqIds = lens _mdqIds (\ s a -> s{_mdqIds = a})
-- | End date.
mdqEndDate :: Lens' McfDataQuery (Maybe Text)
mdqEndDate
= lens _mdqEndDate (\ s a -> s{_mdqEndDate = a})
-- | List of dimensions or metrics based on which Analytics data is sorted.
mdqSort :: Lens' McfDataQuery [Text]
mdqSort
= lens _mdqSort (\ s a -> s{_mdqSort = a}) . _Default
. _Coerce
-- | List of analytics dimensions.
mdqDimensions :: Lens' McfDataQuery (Maybe Text)
mdqDimensions
= lens _mdqDimensions
(\ s a -> s{_mdqDimensions = a})
-- | Start index.
mdqStartIndex :: Lens' McfDataQuery (Maybe Int32)
mdqStartIndex
= lens _mdqStartIndex
(\ s a -> s{_mdqStartIndex = a})
. mapping _Coerce
-- | Maximum results per page.
mdqMaxResults :: Lens' McfDataQuery (Maybe Int32)
mdqMaxResults
= lens _mdqMaxResults
(\ s a -> s{_mdqMaxResults = a})
. mapping _Coerce
-- | Analytics advanced segment.
mdqSegment :: Lens' McfDataQuery (Maybe Text)
mdqSegment
= lens _mdqSegment (\ s a -> s{_mdqSegment = a})
-- | Start date.
mdqStartDate :: Lens' McfDataQuery (Maybe Text)
mdqStartDate
= lens _mdqStartDate (\ s a -> s{_mdqStartDate = a})
instance FromJSON McfDataQuery where
parseJSON
= withObject "McfDataQuery"
(\ o ->
McfDataQuery' <$>
(o .:? "metrics" .!= mempty) <*>
(o .:? "samplingLevel")
<*> (o .:? "filters")
<*> (o .:? "ids")
<*> (o .:? "end-date")
<*> (o .:? "sort" .!= mempty)
<*> (o .:? "dimensions")
<*> (o .:? "start-index")
<*> (o .:? "max-results")
<*> (o .:? "segment")
<*> (o .:? "start-date"))
instance ToJSON McfDataQuery where
toJSON McfDataQuery'{..}
= object
(catMaybes
[("metrics" .=) <$> _mdqMetrics,
("samplingLevel" .=) <$> _mdqSamplingLevel,
("filters" .=) <$> _mdqFilters,
("ids" .=) <$> _mdqIds,
("end-date" .=) <$> _mdqEndDate,
("sort" .=) <$> _mdqSort,
("dimensions" .=) <$> _mdqDimensions,
("start-index" .=) <$> _mdqStartIndex,
("max-results" .=) <$> _mdqMaxResults,
("segment" .=) <$> _mdqSegment,
("start-date" .=) <$> _mdqStartDate])
-- | JSON template for Analytics goal resource.
--
-- /See:/ 'goal' smart constructor.
data Goal =
Goal'
{ _goaParentLink :: !(Maybe GoalParentLink)
, _goaWebPropertyId :: !(Maybe Text)
, _goaKind :: !Text
, _goaCreated :: !(Maybe DateTime')
, _goaValue :: !(Maybe (Textual Double))
, _goaProFileId :: !(Maybe Text)
, _goaEventDetails :: !(Maybe GoalEventDetails)
, _goaActive :: !(Maybe Bool)
, _goaSelfLink :: !(Maybe Text)
, _goaVisitTimeOnSiteDetails :: !(Maybe GoalVisitTimeOnSiteDetails)
, _goaAccountId :: !(Maybe Text)
, _goaName :: !(Maybe Text)
, _goaInternalWebPropertyId :: !(Maybe Text)
, _goaId :: !(Maybe Text)
, _goaURLDestinationDetails :: !(Maybe GoalURLDestinationDetails)
, _goaVisitNumPagesDetails :: !(Maybe GoalVisitNumPagesDetails)
, _goaUpdated :: !(Maybe DateTime')
, _goaType :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Goal' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'goaParentLink'
--
-- * 'goaWebPropertyId'
--
-- * 'goaKind'
--
-- * 'goaCreated'
--
-- * 'goaValue'
--
-- * 'goaProFileId'
--
-- * 'goaEventDetails'
--
-- * 'goaActive'
--
-- * 'goaSelfLink'
--
-- * 'goaVisitTimeOnSiteDetails'
--
-- * 'goaAccountId'
--
-- * 'goaName'
--
-- * 'goaInternalWebPropertyId'
--
-- * 'goaId'
--
-- * 'goaURLDestinationDetails'
--
-- * 'goaVisitNumPagesDetails'
--
-- * 'goaUpdated'
--
-- * 'goaType'
goal
:: Goal
goal =
Goal'
{ _goaParentLink = Nothing
, _goaWebPropertyId = Nothing
, _goaKind = "analytics#goal"
, _goaCreated = Nothing
, _goaValue = Nothing
, _goaProFileId = Nothing
, _goaEventDetails = Nothing
, _goaActive = Nothing
, _goaSelfLink = Nothing
, _goaVisitTimeOnSiteDetails = Nothing
, _goaAccountId = Nothing
, _goaName = Nothing
, _goaInternalWebPropertyId = Nothing
, _goaId = Nothing
, _goaURLDestinationDetails = Nothing
, _goaVisitNumPagesDetails = Nothing
, _goaUpdated = Nothing
, _goaType = Nothing
}
-- | Parent link for a goal. Points to the view (profile) to which this goal
-- belongs.
goaParentLink :: Lens' Goal (Maybe GoalParentLink)
goaParentLink
= lens _goaParentLink
(\ s a -> s{_goaParentLink = a})
-- | Web property ID to which this goal belongs. The web property ID is of
-- the form UA-XXXXX-YY.
goaWebPropertyId :: Lens' Goal (Maybe Text)
goaWebPropertyId
= lens _goaWebPropertyId
(\ s a -> s{_goaWebPropertyId = a})
-- | Resource type for an Analytics goal.
goaKind :: Lens' Goal Text
goaKind = lens _goaKind (\ s a -> s{_goaKind = a})
-- | Time this goal was created.
goaCreated :: Lens' Goal (Maybe UTCTime)
goaCreated
= lens _goaCreated (\ s a -> s{_goaCreated = a}) .
mapping _DateTime
-- | Goal value.
goaValue :: Lens' Goal (Maybe Double)
goaValue
= lens _goaValue (\ s a -> s{_goaValue = a}) .
mapping _Coerce
-- | View (Profile) ID to which this goal belongs.
goaProFileId :: Lens' Goal (Maybe Text)
goaProFileId
= lens _goaProFileId (\ s a -> s{_goaProFileId = a})
-- | Details for the goal of the type EVENT.
goaEventDetails :: Lens' Goal (Maybe GoalEventDetails)
goaEventDetails
= lens _goaEventDetails
(\ s a -> s{_goaEventDetails = a})
-- | Determines whether this goal is active.
goaActive :: Lens' Goal (Maybe Bool)
goaActive
= lens _goaActive (\ s a -> s{_goaActive = a})
-- | Link for this goal.
goaSelfLink :: Lens' Goal (Maybe Text)
goaSelfLink
= lens _goaSelfLink (\ s a -> s{_goaSelfLink = a})
-- | Details for the goal of the type VISIT_TIME_ON_SITE.
goaVisitTimeOnSiteDetails :: Lens' Goal (Maybe GoalVisitTimeOnSiteDetails)
goaVisitTimeOnSiteDetails
= lens _goaVisitTimeOnSiteDetails
(\ s a -> s{_goaVisitTimeOnSiteDetails = a})
-- | Account ID to which this goal belongs.
goaAccountId :: Lens' Goal (Maybe Text)
goaAccountId
= lens _goaAccountId (\ s a -> s{_goaAccountId = a})
-- | Goal name.
goaName :: Lens' Goal (Maybe Text)
goaName = lens _goaName (\ s a -> s{_goaName = a})
-- | Internal ID for the web property to which this goal belongs.
goaInternalWebPropertyId :: Lens' Goal (Maybe Text)
goaInternalWebPropertyId
= lens _goaInternalWebPropertyId
(\ s a -> s{_goaInternalWebPropertyId = a})
-- | Goal ID.
goaId :: Lens' Goal (Maybe Text)
goaId = lens _goaId (\ s a -> s{_goaId = a})
-- | Details for the goal of the type URL_DESTINATION.
goaURLDestinationDetails :: Lens' Goal (Maybe GoalURLDestinationDetails)
goaURLDestinationDetails
= lens _goaURLDestinationDetails
(\ s a -> s{_goaURLDestinationDetails = a})
-- | Details for the goal of the type VISIT_NUM_PAGES.
goaVisitNumPagesDetails :: Lens' Goal (Maybe GoalVisitNumPagesDetails)
goaVisitNumPagesDetails
= lens _goaVisitNumPagesDetails
(\ s a -> s{_goaVisitNumPagesDetails = a})
-- | Time this goal was last modified.
goaUpdated :: Lens' Goal (Maybe UTCTime)
goaUpdated
= lens _goaUpdated (\ s a -> s{_goaUpdated = a}) .
mapping _DateTime
-- | Goal type. Possible values are URL_DESTINATION, VISIT_TIME_ON_SITE,
-- VISIT_NUM_PAGES, AND EVENT.
goaType :: Lens' Goal (Maybe Text)
goaType = lens _goaType (\ s a -> s{_goaType = a})
instance FromJSON Goal where
parseJSON
= withObject "Goal"
(\ o ->
Goal' <$>
(o .:? "parentLink") <*> (o .:? "webPropertyId") <*>
(o .:? "kind" .!= "analytics#goal")
<*> (o .:? "created")
<*> (o .:? "value")
<*> (o .:? "profileId")
<*> (o .:? "eventDetails")
<*> (o .:? "active")
<*> (o .:? "selfLink")
<*> (o .:? "visitTimeOnSiteDetails")
<*> (o .:? "accountId")
<*> (o .:? "name")
<*> (o .:? "internalWebPropertyId")
<*> (o .:? "id")
<*> (o .:? "urlDestinationDetails")
<*> (o .:? "visitNumPagesDetails")
<*> (o .:? "updated")
<*> (o .:? "type"))
instance ToJSON Goal where
toJSON Goal'{..}
= object
(catMaybes
[("parentLink" .=) <$> _goaParentLink,
("webPropertyId" .=) <$> _goaWebPropertyId,
Just ("kind" .= _goaKind),
("created" .=) <$> _goaCreated,
("value" .=) <$> _goaValue,
("profileId" .=) <$> _goaProFileId,
("eventDetails" .=) <$> _goaEventDetails,
("active" .=) <$> _goaActive,
("selfLink" .=) <$> _goaSelfLink,
("visitTimeOnSiteDetails" .=) <$>
_goaVisitTimeOnSiteDetails,
("accountId" .=) <$> _goaAccountId,
("name" .=) <$> _goaName,
("internalWebPropertyId" .=) <$>
_goaInternalWebPropertyId,
("id" .=) <$> _goaId,
("urlDestinationDetails" .=) <$>
_goaURLDestinationDetails,
("visitNumPagesDetails" .=) <$>
_goaVisitNumPagesDetails,
("updated" .=) <$> _goaUpdated,
("type" .=) <$> _goaType])
-- | JSON template for an Analytics account ticket. The account ticket
-- consists of the ticket ID and the basic information for the account,
-- property and profile.
--
-- /See:/ 'accountTicket' smart constructor.
data AccountTicket =
AccountTicket'
{ _atRedirectURI :: !(Maybe Text)
, _atKind :: !Text
, _atProFile :: !(Maybe ProFile)
, _atAccount :: !(Maybe Account)
, _atWebProperty :: !(Maybe WebProperty)
, _atId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'AccountTicket' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'atRedirectURI'
--
-- * 'atKind'
--
-- * 'atProFile'
--
-- * 'atAccount'
--
-- * 'atWebProperty'
--
-- * 'atId'
accountTicket
:: AccountTicket
accountTicket =
AccountTicket'
{ _atRedirectURI = Nothing
, _atKind = "analytics#accountTicket"
, _atProFile = Nothing
, _atAccount = Nothing
, _atWebProperty = Nothing
, _atId = Nothing
}
-- | Redirect URI where the user will be sent after accepting Terms of
-- Service. Must be configured in APIs console as a callback URL.
atRedirectURI :: Lens' AccountTicket (Maybe Text)
atRedirectURI
= lens _atRedirectURI
(\ s a -> s{_atRedirectURI = a})
-- | Resource type for account ticket.
atKind :: Lens' AccountTicket Text
atKind = lens _atKind (\ s a -> s{_atKind = a})
-- | View (Profile) for the account.
atProFile :: Lens' AccountTicket (Maybe ProFile)
atProFile
= lens _atProFile (\ s a -> s{_atProFile = a})
-- | Account for this ticket.
atAccount :: Lens' AccountTicket (Maybe Account)
atAccount
= lens _atAccount (\ s a -> s{_atAccount = a})
-- | Web property for the account.
atWebProperty :: Lens' AccountTicket (Maybe WebProperty)
atWebProperty
= lens _atWebProperty
(\ s a -> s{_atWebProperty = a})
-- | Account ticket ID used to access the account ticket.
atId :: Lens' AccountTicket (Maybe Text)
atId = lens _atId (\ s a -> s{_atId = a})
instance FromJSON AccountTicket where
parseJSON
= withObject "AccountTicket"
(\ o ->
AccountTicket' <$>
(o .:? "redirectUri") <*>
(o .:? "kind" .!= "analytics#accountTicket")
<*> (o .:? "profile")
<*> (o .:? "account")
<*> (o .:? "webproperty")
<*> (o .:? "id"))
instance ToJSON AccountTicket where
toJSON AccountTicket'{..}
= object
(catMaybes
[("redirectUri" .=) <$> _atRedirectURI,
Just ("kind" .= _atKind),
("profile" .=) <$> _atProFile,
("account" .=) <$> _atAccount,
("webproperty" .=) <$> _atWebProperty,
("id" .=) <$> _atId])
-- | JSON template for an Analytics AccountSummary. An AccountSummary is a
-- lightweight tree comprised of properties\/profiles.
--
-- /See:/ 'accountSummary' smart constructor.
data AccountSummary =
AccountSummary'
{ _assKind :: !Text
, _assWebProperties :: !(Maybe [WebPropertySummary])
, _assName :: !(Maybe Text)
, _assStarred :: !(Maybe Bool)
, _assId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'AccountSummary' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'assKind'
--
-- * 'assWebProperties'
--
-- * 'assName'
--
-- * 'assStarred'
--
-- * 'assId'
accountSummary
:: AccountSummary
accountSummary =
AccountSummary'
{ _assKind = "analytics#accountSummary"
, _assWebProperties = Nothing
, _assName = Nothing
, _assStarred = Nothing
, _assId = Nothing
}
-- | Resource type for Analytics AccountSummary.
assKind :: Lens' AccountSummary Text
assKind = lens _assKind (\ s a -> s{_assKind = a})
-- | List of web properties under this account.
assWebProperties :: Lens' AccountSummary [WebPropertySummary]
assWebProperties
= lens _assWebProperties
(\ s a -> s{_assWebProperties = a})
. _Default
. _Coerce
-- | Account name.
assName :: Lens' AccountSummary (Maybe Text)
assName = lens _assName (\ s a -> s{_assName = a})
-- | Indicates whether this account is starred or not.
assStarred :: Lens' AccountSummary (Maybe Bool)
assStarred
= lens _assStarred (\ s a -> s{_assStarred = a})
-- | Account ID.
assId :: Lens' AccountSummary (Maybe Text)
assId = lens _assId (\ s a -> s{_assId = a})
instance FromJSON AccountSummary where
parseJSON
= withObject "AccountSummary"
(\ o ->
AccountSummary' <$>
(o .:? "kind" .!= "analytics#accountSummary") <*>
(o .:? "webProperties" .!= mempty)
<*> (o .:? "name")
<*> (o .:? "starred")
<*> (o .:? "id"))
instance ToJSON AccountSummary where
toJSON AccountSummary'{..}
= object
(catMaybes
[Just ("kind" .= _assKind),
("webProperties" .=) <$> _assWebProperties,
("name" .=) <$> _assName,
("starred" .=) <$> _assStarred,
("id" .=) <$> _assId])
-- | Real time data request query parameters.
--
-- /See:/ 'realtimeDataQuery' smart constructor.
data RealtimeDataQuery =
RealtimeDataQuery'
{ _rdqMetrics :: !(Maybe [Text])
, _rdqFilters :: !(Maybe Text)
, _rdqIds :: !(Maybe Text)
, _rdqSort :: !(Maybe [Text])
, _rdqDimensions :: !(Maybe Text)
, _rdqMaxResults :: !(Maybe (Textual Int32))
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'RealtimeDataQuery' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'rdqMetrics'
--
-- * 'rdqFilters'
--
-- * 'rdqIds'
--
-- * 'rdqSort'
--
-- * 'rdqDimensions'
--
-- * 'rdqMaxResults'
realtimeDataQuery
:: RealtimeDataQuery
realtimeDataQuery =
RealtimeDataQuery'
{ _rdqMetrics = Nothing
, _rdqFilters = Nothing
, _rdqIds = Nothing
, _rdqSort = Nothing
, _rdqDimensions = Nothing
, _rdqMaxResults = Nothing
}
-- | List of real time metrics.
rdqMetrics :: Lens' RealtimeDataQuery [Text]
rdqMetrics
= lens _rdqMetrics (\ s a -> s{_rdqMetrics = a}) .
_Default
. _Coerce
-- | Comma-separated list of dimension or metric filters.
rdqFilters :: Lens' RealtimeDataQuery (Maybe Text)
rdqFilters
= lens _rdqFilters (\ s a -> s{_rdqFilters = a})
-- | Unique table ID.
rdqIds :: Lens' RealtimeDataQuery (Maybe Text)
rdqIds = lens _rdqIds (\ s a -> s{_rdqIds = a})
-- | List of dimensions or metrics based on which real time data is sorted.
rdqSort :: Lens' RealtimeDataQuery [Text]
rdqSort
= lens _rdqSort (\ s a -> s{_rdqSort = a}) . _Default
. _Coerce
-- | List of real time dimensions.
rdqDimensions :: Lens' RealtimeDataQuery (Maybe Text)
rdqDimensions
= lens _rdqDimensions
(\ s a -> s{_rdqDimensions = a})
-- | Maximum results per page.
rdqMaxResults :: Lens' RealtimeDataQuery (Maybe Int32)
rdqMaxResults
= lens _rdqMaxResults
(\ s a -> s{_rdqMaxResults = a})
. mapping _Coerce
instance FromJSON RealtimeDataQuery where
parseJSON
= withObject "RealtimeDataQuery"
(\ o ->
RealtimeDataQuery' <$>
(o .:? "metrics" .!= mempty) <*> (o .:? "filters")
<*> (o .:? "ids")
<*> (o .:? "sort" .!= mempty)
<*> (o .:? "dimensions")
<*> (o .:? "max-results"))
instance ToJSON RealtimeDataQuery where
toJSON RealtimeDataQuery'{..}
= object
(catMaybes
[("metrics" .=) <$> _rdqMetrics,
("filters" .=) <$> _rdqFilters,
("ids" .=) <$> _rdqIds, ("sort" .=) <$> _rdqSort,
("dimensions" .=) <$> _rdqDimensions,
("max-results" .=) <$> _rdqMaxResults])
-- | Lists columns (dimensions and metrics) for a particular report type.
--
-- /See:/ 'columns' smart constructor.
data Columns =
Columns'
{ _colEtag :: !(Maybe Text)
, _colKind :: !Text
, _colItems :: !(Maybe [Column])
, _colTotalResults :: !(Maybe (Textual Int32))
, _colAttributeNames :: !(Maybe [Text])
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Columns' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'colEtag'
--
-- * 'colKind'
--
-- * 'colItems'
--
-- * 'colTotalResults'
--
-- * 'colAttributeNames'
columns
:: Columns
columns =
Columns'
{ _colEtag = Nothing
, _colKind = "analytics#columns"
, _colItems = Nothing
, _colTotalResults = Nothing
, _colAttributeNames = Nothing
}
-- | Etag of collection. This etag can be compared with the last response
-- etag to check if response has changed.
colEtag :: Lens' Columns (Maybe Text)
colEtag = lens _colEtag (\ s a -> s{_colEtag = a})
-- | Collection type.
colKind :: Lens' Columns Text
colKind = lens _colKind (\ s a -> s{_colKind = a})
-- | List of columns for a report type.
colItems :: Lens' Columns [Column]
colItems
= lens _colItems (\ s a -> s{_colItems = a}) .
_Default
. _Coerce
-- | Total number of columns returned in the response.
colTotalResults :: Lens' Columns (Maybe Int32)
colTotalResults
= lens _colTotalResults
(\ s a -> s{_colTotalResults = a})
. mapping _Coerce
-- | List of attributes names returned by columns.
colAttributeNames :: Lens' Columns [Text]
colAttributeNames
= lens _colAttributeNames
(\ s a -> s{_colAttributeNames = a})
. _Default
. _Coerce
instance FromJSON Columns where
parseJSON
= withObject "Columns"
(\ o ->
Columns' <$>
(o .:? "etag") <*>
(o .:? "kind" .!= "analytics#columns")
<*> (o .:? "items" .!= mempty)
<*> (o .:? "totalResults")
<*> (o .:? "attributeNames" .!= mempty))
instance ToJSON Columns where
toJSON Columns'{..}
= object
(catMaybes
[("etag" .=) <$> _colEtag, Just ("kind" .= _colKind),
("items" .=) <$> _colItems,
("totalResults" .=) <$> _colTotalResults,
("attributeNames" .=) <$> _colAttributeNames])
-- | Details for the filter of the type LOWER.
--
-- /See:/ 'filterLowercaseDetails' smart constructor.
data FilterLowercaseDetails =
FilterLowercaseDetails'
{ _fldFieldIndex :: !(Maybe (Textual Int32))
, _fldField :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'FilterLowercaseDetails' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'fldFieldIndex'
--
-- * 'fldField'
filterLowercaseDetails
:: FilterLowercaseDetails
filterLowercaseDetails =
FilterLowercaseDetails' {_fldFieldIndex = Nothing, _fldField = Nothing}
-- | The Index of the custom dimension. Required if field is a
-- CUSTOM_DIMENSION.
fldFieldIndex :: Lens' FilterLowercaseDetails (Maybe Int32)
fldFieldIndex
= lens _fldFieldIndex
(\ s a -> s{_fldFieldIndex = a})
. mapping _Coerce
-- | Field to use in the filter.
fldField :: Lens' FilterLowercaseDetails (Maybe Text)
fldField = lens _fldField (\ s a -> s{_fldField = a})
instance FromJSON FilterLowercaseDetails where
parseJSON
= withObject "FilterLowercaseDetails"
(\ o ->
FilterLowercaseDetails' <$>
(o .:? "fieldIndex") <*> (o .:? "field"))
instance ToJSON FilterLowercaseDetails where
toJSON FilterLowercaseDetails'{..}
= object
(catMaybes
[("fieldIndex" .=) <$> _fldFieldIndex,
("field" .=) <$> _fldField])
-- | JSON template for an Analytics account filter.
--
-- /See:/ 'filter'' smart constructor.
data Filter =
Filter'
{ _filParentLink :: !(Maybe FilterParentLink)
, _filAdvancedDetails :: !(Maybe FilterAdvancedDetails)
, _filUppercaseDetails :: !(Maybe FilterUppercaseDetails)
, _filLowercaseDetails :: !(Maybe FilterLowercaseDetails)
, _filKind :: !Text
, _filCreated :: !(Maybe DateTime')
, _filIncludeDetails :: !(Maybe FilterExpression)
, _filExcludeDetails :: !(Maybe FilterExpression)
, _filSelfLink :: !(Maybe Text)
, _filAccountId :: !(Maybe Text)
, _filName :: !(Maybe Text)
, _filId :: !(Maybe Text)
, _filUpdated :: !(Maybe DateTime')
, _filType :: !(Maybe Text)
, _filSearchAndReplaceDetails :: !(Maybe FilterSearchAndReplaceDetails)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Filter' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'filParentLink'
--
-- * 'filAdvancedDetails'
--
-- * 'filUppercaseDetails'
--
-- * 'filLowercaseDetails'
--
-- * 'filKind'
--
-- * 'filCreated'
--
-- * 'filIncludeDetails'
--
-- * 'filExcludeDetails'
--
-- * 'filSelfLink'
--
-- * 'filAccountId'
--
-- * 'filName'
--
-- * 'filId'
--
-- * 'filUpdated'
--
-- * 'filType'
--
-- * 'filSearchAndReplaceDetails'
filter'
:: Filter
filter' =
Filter'
{ _filParentLink = Nothing
, _filAdvancedDetails = Nothing
, _filUppercaseDetails = Nothing
, _filLowercaseDetails = Nothing
, _filKind = "analytics#filter"
, _filCreated = Nothing
, _filIncludeDetails = Nothing
, _filExcludeDetails = Nothing
, _filSelfLink = Nothing
, _filAccountId = Nothing
, _filName = Nothing
, _filId = Nothing
, _filUpdated = Nothing
, _filType = Nothing
, _filSearchAndReplaceDetails = Nothing
}
-- | Parent link for this filter. Points to the account to which this filter
-- belongs.
filParentLink :: Lens' Filter (Maybe FilterParentLink)
filParentLink
= lens _filParentLink
(\ s a -> s{_filParentLink = a})
-- | Details for the filter of the type ADVANCED.
filAdvancedDetails :: Lens' Filter (Maybe FilterAdvancedDetails)
filAdvancedDetails
= lens _filAdvancedDetails
(\ s a -> s{_filAdvancedDetails = a})
-- | Details for the filter of the type UPPER.
filUppercaseDetails :: Lens' Filter (Maybe FilterUppercaseDetails)
filUppercaseDetails
= lens _filUppercaseDetails
(\ s a -> s{_filUppercaseDetails = a})
-- | Details for the filter of the type LOWER.
filLowercaseDetails :: Lens' Filter (Maybe FilterLowercaseDetails)
filLowercaseDetails
= lens _filLowercaseDetails
(\ s a -> s{_filLowercaseDetails = a})
-- | Resource type for Analytics filter.
filKind :: Lens' Filter Text
filKind = lens _filKind (\ s a -> s{_filKind = a})
-- | Time this filter was created.
filCreated :: Lens' Filter (Maybe UTCTime)
filCreated
= lens _filCreated (\ s a -> s{_filCreated = a}) .
mapping _DateTime
-- | Details for the filter of the type INCLUDE.
filIncludeDetails :: Lens' Filter (Maybe FilterExpression)
filIncludeDetails
= lens _filIncludeDetails
(\ s a -> s{_filIncludeDetails = a})
-- | Details for the filter of the type EXCLUDE.
filExcludeDetails :: Lens' Filter (Maybe FilterExpression)
filExcludeDetails
= lens _filExcludeDetails
(\ s a -> s{_filExcludeDetails = a})
-- | Link for this filter.
filSelfLink :: Lens' Filter (Maybe Text)
filSelfLink
= lens _filSelfLink (\ s a -> s{_filSelfLink = a})
-- | Account ID to which this filter belongs.
filAccountId :: Lens' Filter (Maybe Text)
filAccountId
= lens _filAccountId (\ s a -> s{_filAccountId = a})
-- | Name of this filter.
filName :: Lens' Filter (Maybe Text)
filName = lens _filName (\ s a -> s{_filName = a})
-- | Filter ID.
filId :: Lens' Filter (Maybe Text)
filId = lens _filId (\ s a -> s{_filId = a})
-- | Time this filter was last modified.
filUpdated :: Lens' Filter (Maybe UTCTime)
filUpdated
= lens _filUpdated (\ s a -> s{_filUpdated = a}) .
mapping _DateTime
-- | Type of this filter. Possible values are INCLUDE, EXCLUDE, LOWERCASE,
-- UPPERCASE, SEARCH_AND_REPLACE and ADVANCED.
filType :: Lens' Filter (Maybe Text)
filType = lens _filType (\ s a -> s{_filType = a})
-- | Details for the filter of the type SEARCH_AND_REPLACE.
filSearchAndReplaceDetails :: Lens' Filter (Maybe FilterSearchAndReplaceDetails)
filSearchAndReplaceDetails
= lens _filSearchAndReplaceDetails
(\ s a -> s{_filSearchAndReplaceDetails = a})
instance FromJSON Filter where
parseJSON
= withObject "Filter"
(\ o ->
Filter' <$>
(o .:? "parentLink") <*> (o .:? "advancedDetails")
<*> (o .:? "uppercaseDetails")
<*> (o .:? "lowercaseDetails")
<*> (o .:? "kind" .!= "analytics#filter")
<*> (o .:? "created")
<*> (o .:? "includeDetails")
<*> (o .:? "excludeDetails")
<*> (o .:? "selfLink")
<*> (o .:? "accountId")
<*> (o .:? "name")
<*> (o .:? "id")
<*> (o .:? "updated")
<*> (o .:? "type")
<*> (o .:? "searchAndReplaceDetails"))
instance ToJSON Filter where
toJSON Filter'{..}
= object
(catMaybes
[("parentLink" .=) <$> _filParentLink,
("advancedDetails" .=) <$> _filAdvancedDetails,
("uppercaseDetails" .=) <$> _filUppercaseDetails,
("lowercaseDetails" .=) <$> _filLowercaseDetails,
Just ("kind" .= _filKind),
("created" .=) <$> _filCreated,
("includeDetails" .=) <$> _filIncludeDetails,
("excludeDetails" .=) <$> _filExcludeDetails,
("selfLink" .=) <$> _filSelfLink,
("accountId" .=) <$> _filAccountId,
("name" .=) <$> _filName, ("id" .=) <$> _filId,
("updated" .=) <$> _filUpdated,
("type" .=) <$> _filType,
("searchAndReplaceDetails" .=) <$>
_filSearchAndReplaceDetails])
-- | Upload collection lists Analytics uploads to which the user has access.
-- Each custom data source can have a set of uploads. Each resource in the
-- upload collection corresponds to a single Analytics data upload.
--
-- /See:/ 'uploads' smart constructor.
data Uploads =
Uploads'
{ _uplNextLink :: !(Maybe Text)
, _uplItemsPerPage :: !(Maybe (Textual Int32))
, _uplKind :: !Text
, _uplItems :: !(Maybe [Upload])
, _uplTotalResults :: !(Maybe (Textual Int32))
, _uplStartIndex :: !(Maybe (Textual Int32))
, _uplPreviousLink :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Uploads' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'uplNextLink'
--
-- * 'uplItemsPerPage'
--
-- * 'uplKind'
--
-- * 'uplItems'
--
-- * 'uplTotalResults'
--
-- * 'uplStartIndex'
--
-- * 'uplPreviousLink'
uploads
:: Uploads
uploads =
Uploads'
{ _uplNextLink = Nothing
, _uplItemsPerPage = Nothing
, _uplKind = "analytics#uploads"
, _uplItems = Nothing
, _uplTotalResults = Nothing
, _uplStartIndex = Nothing
, _uplPreviousLink = Nothing
}
-- | Link to next page for this upload collection.
uplNextLink :: Lens' Uploads (Maybe Text)
uplNextLink
= lens _uplNextLink (\ s a -> s{_uplNextLink = a})
-- | The maximum number of resources the response can contain, regardless of
-- the actual number of resources returned. Its value ranges from 1 to 1000
-- with a value of 1000 by default, or otherwise specified by the
-- max-results query parameter.
uplItemsPerPage :: Lens' Uploads (Maybe Int32)
uplItemsPerPage
= lens _uplItemsPerPage
(\ s a -> s{_uplItemsPerPage = a})
. mapping _Coerce
-- | Collection type.
uplKind :: Lens' Uploads Text
uplKind = lens _uplKind (\ s a -> s{_uplKind = a})
-- | A list of uploads.
uplItems :: Lens' Uploads [Upload]
uplItems
= lens _uplItems (\ s a -> s{_uplItems = a}) .
_Default
. _Coerce
-- | The total number of results for the query, regardless of the number of
-- resources in the result.
uplTotalResults :: Lens' Uploads (Maybe Int32)
uplTotalResults
= lens _uplTotalResults
(\ s a -> s{_uplTotalResults = a})
. mapping _Coerce
-- | The starting index of the resources, which is 1 by default or otherwise
-- specified by the start-index query parameter.
uplStartIndex :: Lens' Uploads (Maybe Int32)
uplStartIndex
= lens _uplStartIndex
(\ s a -> s{_uplStartIndex = a})
. mapping _Coerce
-- | Link to previous page for this upload collection.
uplPreviousLink :: Lens' Uploads (Maybe Text)
uplPreviousLink
= lens _uplPreviousLink
(\ s a -> s{_uplPreviousLink = a})
instance FromJSON Uploads where
parseJSON
= withObject "Uploads"
(\ o ->
Uploads' <$>
(o .:? "nextLink") <*> (o .:? "itemsPerPage") <*>
(o .:? "kind" .!= "analytics#uploads")
<*> (o .:? "items" .!= mempty)
<*> (o .:? "totalResults")
<*> (o .:? "startIndex")
<*> (o .:? "previousLink"))
instance ToJSON Uploads where
toJSON Uploads'{..}
= object
(catMaybes
[("nextLink" .=) <$> _uplNextLink,
("itemsPerPage" .=) <$> _uplItemsPerPage,
Just ("kind" .= _uplKind),
("items" .=) <$> _uplItems,
("totalResults" .=) <$> _uplTotalResults,
("startIndex" .=) <$> _uplStartIndex,
("previousLink" .=) <$> _uplPreviousLink])
-- | A custom dimension collection lists Analytics custom dimensions to which
-- the user has access. Each resource in the collection corresponds to a
-- single Analytics custom dimension.
--
-- /See:/ 'customDimensions' smart constructor.
data CustomDimensions =
CustomDimensions'
{ _cdNextLink :: !(Maybe Text)
, _cdItemsPerPage :: !(Maybe (Textual Int32))
, _cdKind :: !Text
, _cdUsername :: !(Maybe Text)
, _cdItems :: !(Maybe [CustomDimension])
, _cdTotalResults :: !(Maybe (Textual Int32))
, _cdStartIndex :: !(Maybe (Textual Int32))
, _cdPreviousLink :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'CustomDimensions' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cdNextLink'
--
-- * 'cdItemsPerPage'
--
-- * 'cdKind'
--
-- * 'cdUsername'
--
-- * 'cdItems'
--
-- * 'cdTotalResults'
--
-- * 'cdStartIndex'
--
-- * 'cdPreviousLink'
customDimensions
:: CustomDimensions
customDimensions =
CustomDimensions'
{ _cdNextLink = Nothing
, _cdItemsPerPage = Nothing
, _cdKind = "analytics#customDimensions"
, _cdUsername = Nothing
, _cdItems = Nothing
, _cdTotalResults = Nothing
, _cdStartIndex = Nothing
, _cdPreviousLink = Nothing
}
-- | Link to next page for this custom dimension collection.
cdNextLink :: Lens' CustomDimensions (Maybe Text)
cdNextLink
= lens _cdNextLink (\ s a -> s{_cdNextLink = a})
-- | The maximum number of resources the response can contain, regardless of
-- the actual number of resources returned. Its value ranges from 1 to 1000
-- with a value of 1000 by default, or otherwise specified by the
-- max-results query parameter.
cdItemsPerPage :: Lens' CustomDimensions (Maybe Int32)
cdItemsPerPage
= lens _cdItemsPerPage
(\ s a -> s{_cdItemsPerPage = a})
. mapping _Coerce
-- | Collection type.
cdKind :: Lens' CustomDimensions Text
cdKind = lens _cdKind (\ s a -> s{_cdKind = a})
-- | Email ID of the authenticated user
cdUsername :: Lens' CustomDimensions (Maybe Text)
cdUsername
= lens _cdUsername (\ s a -> s{_cdUsername = a})
-- | Collection of custom dimensions.
cdItems :: Lens' CustomDimensions [CustomDimension]
cdItems
= lens _cdItems (\ s a -> s{_cdItems = a}) . _Default
. _Coerce
-- | The total number of results for the query, regardless of the number of
-- results in the response.
cdTotalResults :: Lens' CustomDimensions (Maybe Int32)
cdTotalResults
= lens _cdTotalResults
(\ s a -> s{_cdTotalResults = a})
. mapping _Coerce
-- | The starting index of the resources, which is 1 by default or otherwise
-- specified by the start-index query parameter.
cdStartIndex :: Lens' CustomDimensions (Maybe Int32)
cdStartIndex
= lens _cdStartIndex (\ s a -> s{_cdStartIndex = a})
. mapping _Coerce
-- | Link to previous page for this custom dimension collection.
cdPreviousLink :: Lens' CustomDimensions (Maybe Text)
cdPreviousLink
= lens _cdPreviousLink
(\ s a -> s{_cdPreviousLink = a})
instance FromJSON CustomDimensions where
parseJSON
= withObject "CustomDimensions"
(\ o ->
CustomDimensions' <$>
(o .:? "nextLink") <*> (o .:? "itemsPerPage") <*>
(o .:? "kind" .!= "analytics#customDimensions")
<*> (o .:? "username")
<*> (o .:? "items" .!= mempty)
<*> (o .:? "totalResults")
<*> (o .:? "startIndex")
<*> (o .:? "previousLink"))
instance ToJSON CustomDimensions where
toJSON CustomDimensions'{..}
= object
(catMaybes
[("nextLink" .=) <$> _cdNextLink,
("itemsPerPage" .=) <$> _cdItemsPerPage,
Just ("kind" .= _cdKind),
("username" .=) <$> _cdUsername,
("items" .=) <$> _cdItems,
("totalResults" .=) <$> _cdTotalResults,
("startIndex" .=) <$> _cdStartIndex,
("previousLink" .=) <$> _cdPreviousLink])
-- | An segment collection lists Analytics segments that the user has access
-- to. Each resource in the collection corresponds to a single Analytics
-- segment.
--
-- /See:/ 'segments' smart constructor.
data Segments =
Segments'
{ _sNextLink :: !(Maybe Text)
, _sItemsPerPage :: !(Maybe (Textual Int32))
, _sKind :: !Text
, _sUsername :: !(Maybe Text)
, _sItems :: !(Maybe [Segment])
, _sTotalResults :: !(Maybe (Textual Int32))
, _sStartIndex :: !(Maybe (Textual Int32))
, _sPreviousLink :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Segments' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'sNextLink'
--
-- * 'sItemsPerPage'
--
-- * 'sKind'
--
-- * 'sUsername'
--
-- * 'sItems'
--
-- * 'sTotalResults'
--
-- * 'sStartIndex'
--
-- * 'sPreviousLink'
segments
:: Segments
segments =
Segments'
{ _sNextLink = Nothing
, _sItemsPerPage = Nothing
, _sKind = "analytics#segments"
, _sUsername = Nothing
, _sItems = Nothing
, _sTotalResults = Nothing
, _sStartIndex = Nothing
, _sPreviousLink = Nothing
}
-- | Link to next page for this segment collection.
sNextLink :: Lens' Segments (Maybe Text)
sNextLink
= lens _sNextLink (\ s a -> s{_sNextLink = a})
-- | The maximum number of resources the response can contain, regardless of
-- the actual number of resources returned. Its value ranges from 1 to 1000
-- with a value of 1000 by default, or otherwise specified by the
-- max-results query parameter.
sItemsPerPage :: Lens' Segments (Maybe Int32)
sItemsPerPage
= lens _sItemsPerPage
(\ s a -> s{_sItemsPerPage = a})
. mapping _Coerce
-- | Collection type for segments.
sKind :: Lens' Segments Text
sKind = lens _sKind (\ s a -> s{_sKind = a})
-- | Email ID of the authenticated user
sUsername :: Lens' Segments (Maybe Text)
sUsername
= lens _sUsername (\ s a -> s{_sUsername = a})
-- | A list of segments.
sItems :: Lens' Segments [Segment]
sItems
= lens _sItems (\ s a -> s{_sItems = a}) . _Default .
_Coerce
-- | The total number of results for the query, regardless of the number of
-- results in the response.
sTotalResults :: Lens' Segments (Maybe Int32)
sTotalResults
= lens _sTotalResults
(\ s a -> s{_sTotalResults = a})
. mapping _Coerce
-- | The starting index of the resources, which is 1 by default or otherwise
-- specified by the start-index query parameter.
sStartIndex :: Lens' Segments (Maybe Int32)
sStartIndex
= lens _sStartIndex (\ s a -> s{_sStartIndex = a}) .
mapping _Coerce
-- | Link to previous page for this segment collection.
sPreviousLink :: Lens' Segments (Maybe Text)
sPreviousLink
= lens _sPreviousLink
(\ s a -> s{_sPreviousLink = a})
instance FromJSON Segments where
parseJSON
= withObject "Segments"
(\ o ->
Segments' <$>
(o .:? "nextLink") <*> (o .:? "itemsPerPage") <*>
(o .:? "kind" .!= "analytics#segments")
<*> (o .:? "username")
<*> (o .:? "items" .!= mempty)
<*> (o .:? "totalResults")
<*> (o .:? "startIndex")
<*> (o .:? "previousLink"))
instance ToJSON Segments where
toJSON Segments'{..}
= object
(catMaybes
[("nextLink" .=) <$> _sNextLink,
("itemsPerPage" .=) <$> _sItemsPerPage,
Just ("kind" .= _sKind),
("username" .=) <$> _sUsername,
("items" .=) <$> _sItems,
("totalResults" .=) <$> _sTotalResults,
("startIndex" .=) <$> _sStartIndex,
("previousLink" .=) <$> _sPreviousLink])
--
-- /See:/ 'gaDataDataTable' smart constructor.
data GaDataDataTable =
GaDataDataTable'
{ _gddtCols :: !(Maybe [GaDataDataTableColsItem])
, _gddtRows :: !(Maybe [GaDataDataTableRowsItem])
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'GaDataDataTable' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gddtCols'
--
-- * 'gddtRows'
gaDataDataTable
:: GaDataDataTable
gaDataDataTable = GaDataDataTable' {_gddtCols = Nothing, _gddtRows = Nothing}
gddtCols :: Lens' GaDataDataTable [GaDataDataTableColsItem]
gddtCols
= lens _gddtCols (\ s a -> s{_gddtCols = a}) .
_Default
. _Coerce
gddtRows :: Lens' GaDataDataTable [GaDataDataTableRowsItem]
gddtRows
= lens _gddtRows (\ s a -> s{_gddtRows = a}) .
_Default
. _Coerce
instance FromJSON GaDataDataTable where
parseJSON
= withObject "GaDataDataTable"
(\ o ->
GaDataDataTable' <$>
(o .:? "cols" .!= mempty) <*>
(o .:? "rows" .!= mempty))
instance ToJSON GaDataDataTable where
toJSON GaDataDataTable'{..}
= object
(catMaybes
[("cols" .=) <$> _gddtCols,
("rows" .=) <$> _gddtRows])
-- | Web property being linked.
--
-- /See:/ 'entityAdWordsLinkEntity' smart constructor.
newtype EntityAdWordsLinkEntity =
EntityAdWordsLinkEntity'
{ _eawleWebPropertyRef :: Maybe WebPropertyRef
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'EntityAdWordsLinkEntity' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'eawleWebPropertyRef'
entityAdWordsLinkEntity
:: EntityAdWordsLinkEntity
entityAdWordsLinkEntity =
EntityAdWordsLinkEntity' {_eawleWebPropertyRef = Nothing}
eawleWebPropertyRef :: Lens' EntityAdWordsLinkEntity (Maybe WebPropertyRef)
eawleWebPropertyRef
= lens _eawleWebPropertyRef
(\ s a -> s{_eawleWebPropertyRef = a})
instance FromJSON EntityAdWordsLinkEntity where
parseJSON
= withObject "EntityAdWordsLinkEntity"
(\ o ->
EntityAdWordsLinkEntity' <$>
(o .:? "webPropertyRef"))
instance ToJSON EntityAdWordsLinkEntity where
toJSON EntityAdWordsLinkEntity'{..}
= object
(catMaybes
[("webPropertyRef" .=) <$> _eawleWebPropertyRef])
-- | A state based audience definition that will cause a user to be added or
-- removed from an audience.
--
-- /See:/ 'remarketingAudienceStateBasedAudienceDefinition' smart constructor.
data RemarketingAudienceStateBasedAudienceDefinition =
RemarketingAudienceStateBasedAudienceDefinition'
{ _rasbadExcludeConditions :: !(Maybe RemarketingAudienceStateBasedAudienceDefinitionExcludeConditions)
, _rasbadIncludeConditions :: !(Maybe IncludeConditions)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'RemarketingAudienceStateBasedAudienceDefinition' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'rasbadExcludeConditions'
--
-- * 'rasbadIncludeConditions'
remarketingAudienceStateBasedAudienceDefinition
:: RemarketingAudienceStateBasedAudienceDefinition
remarketingAudienceStateBasedAudienceDefinition =
RemarketingAudienceStateBasedAudienceDefinition'
{_rasbadExcludeConditions = Nothing, _rasbadIncludeConditions = Nothing}
-- | Defines the conditions to exclude users from the audience.
rasbadExcludeConditions :: Lens' RemarketingAudienceStateBasedAudienceDefinition (Maybe RemarketingAudienceStateBasedAudienceDefinitionExcludeConditions)
rasbadExcludeConditions
= lens _rasbadExcludeConditions
(\ s a -> s{_rasbadExcludeConditions = a})
-- | Defines the conditions to include users to the audience.
rasbadIncludeConditions :: Lens' RemarketingAudienceStateBasedAudienceDefinition (Maybe IncludeConditions)
rasbadIncludeConditions
= lens _rasbadIncludeConditions
(\ s a -> s{_rasbadIncludeConditions = a})
instance FromJSON
RemarketingAudienceStateBasedAudienceDefinition
where
parseJSON
= withObject
"RemarketingAudienceStateBasedAudienceDefinition"
(\ o ->
RemarketingAudienceStateBasedAudienceDefinition' <$>
(o .:? "excludeConditions") <*>
(o .:? "includeConditions"))
instance ToJSON
RemarketingAudienceStateBasedAudienceDefinition
where
toJSON
RemarketingAudienceStateBasedAudienceDefinition'{..}
= object
(catMaybes
[("excludeConditions" .=) <$>
_rasbadExcludeConditions,
("includeConditions" .=) <$>
_rasbadIncludeConditions])
-- | Details for the goal of the type URL_DESTINATION.
--
-- /See:/ 'goalURLDestinationDetails' smart constructor.
data GoalURLDestinationDetails =
GoalURLDestinationDetails'
{ _guddURL :: !(Maybe Text)
, _guddMatchType :: !(Maybe Text)
, _guddSteps :: !(Maybe [GoalURLDestinationDetailsStepsItem])
, _guddCaseSensitive :: !(Maybe Bool)
, _guddFirstStepRequired :: !(Maybe Bool)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'GoalURLDestinationDetails' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'guddURL'
--
-- * 'guddMatchType'
--
-- * 'guddSteps'
--
-- * 'guddCaseSensitive'
--
-- * 'guddFirstStepRequired'
goalURLDestinationDetails
:: GoalURLDestinationDetails
goalURLDestinationDetails =
GoalURLDestinationDetails'
{ _guddURL = Nothing
, _guddMatchType = Nothing
, _guddSteps = Nothing
, _guddCaseSensitive = Nothing
, _guddFirstStepRequired = Nothing
}
-- | URL for this goal.
guddURL :: Lens' GoalURLDestinationDetails (Maybe Text)
guddURL = lens _guddURL (\ s a -> s{_guddURL = a})
-- | Match type for the goal URL. Possible values are HEAD, EXACT, or REGEX.
guddMatchType :: Lens' GoalURLDestinationDetails (Maybe Text)
guddMatchType
= lens _guddMatchType
(\ s a -> s{_guddMatchType = a})
-- | List of steps configured for this goal funnel.
guddSteps :: Lens' GoalURLDestinationDetails [GoalURLDestinationDetailsStepsItem]
guddSteps
= lens _guddSteps (\ s a -> s{_guddSteps = a}) .
_Default
. _Coerce
-- | Determines if the goal URL must exactly match the capitalization of
-- visited URLs.
guddCaseSensitive :: Lens' GoalURLDestinationDetails (Maybe Bool)
guddCaseSensitive
= lens _guddCaseSensitive
(\ s a -> s{_guddCaseSensitive = a})
-- | Determines if the first step in this goal is required.
guddFirstStepRequired :: Lens' GoalURLDestinationDetails (Maybe Bool)
guddFirstStepRequired
= lens _guddFirstStepRequired
(\ s a -> s{_guddFirstStepRequired = a})
instance FromJSON GoalURLDestinationDetails where
parseJSON
= withObject "GoalURLDestinationDetails"
(\ o ->
GoalURLDestinationDetails' <$>
(o .:? "url") <*> (o .:? "matchType") <*>
(o .:? "steps" .!= mempty)
<*> (o .:? "caseSensitive")
<*> (o .:? "firstStepRequired"))
instance ToJSON GoalURLDestinationDetails where
toJSON GoalURLDestinationDetails'{..}
= object
(catMaybes
[("url" .=) <$> _guddURL,
("matchType" .=) <$> _guddMatchType,
("steps" .=) <$> _guddSteps,
("caseSensitive" .=) <$> _guddCaseSensitive,
("firstStepRequired" .=) <$> _guddFirstStepRequired])
-- | A profile filter link collection lists profile filter links between
-- profiles and filters. Each resource in the collection corresponds to a
-- profile filter link.
--
-- /See:/ 'proFileFilterLinks' smart constructor.
data ProFileFilterLinks =
ProFileFilterLinks'
{ _pfflNextLink :: !(Maybe Text)
, _pfflItemsPerPage :: !(Maybe (Textual Int32))
, _pfflKind :: !Text
, _pfflUsername :: !(Maybe Text)
, _pfflItems :: !(Maybe [ProFileFilterLink])
, _pfflTotalResults :: !(Maybe (Textual Int32))
, _pfflStartIndex :: !(Maybe (Textual Int32))
, _pfflPreviousLink :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProFileFilterLinks' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pfflNextLink'
--
-- * 'pfflItemsPerPage'
--
-- * 'pfflKind'
--
-- * 'pfflUsername'
--
-- * 'pfflItems'
--
-- * 'pfflTotalResults'
--
-- * 'pfflStartIndex'
--
-- * 'pfflPreviousLink'
proFileFilterLinks
:: ProFileFilterLinks
proFileFilterLinks =
ProFileFilterLinks'
{ _pfflNextLink = Nothing
, _pfflItemsPerPage = Nothing
, _pfflKind = "analytics#profileFilterLinks"
, _pfflUsername = Nothing
, _pfflItems = Nothing
, _pfflTotalResults = Nothing
, _pfflStartIndex = Nothing
, _pfflPreviousLink = Nothing
}
-- | Link to next page for this profile filter link collection.
pfflNextLink :: Lens' ProFileFilterLinks (Maybe Text)
pfflNextLink
= lens _pfflNextLink (\ s a -> s{_pfflNextLink = a})
-- | The maximum number of resources the response can contain, regardless of
-- the actual number of resources returned. Its value ranges from 1 to
-- 1,000 with a value of 1000 by default, or otherwise specified by the
-- max-results query parameter.
pfflItemsPerPage :: Lens' ProFileFilterLinks (Maybe Int32)
pfflItemsPerPage
= lens _pfflItemsPerPage
(\ s a -> s{_pfflItemsPerPage = a})
. mapping _Coerce
-- | Collection type.
pfflKind :: Lens' ProFileFilterLinks Text
pfflKind = lens _pfflKind (\ s a -> s{_pfflKind = a})
-- | Email ID of the authenticated user
pfflUsername :: Lens' ProFileFilterLinks (Maybe Text)
pfflUsername
= lens _pfflUsername (\ s a -> s{_pfflUsername = a})
-- | A list of profile filter links.
pfflItems :: Lens' ProFileFilterLinks [ProFileFilterLink]
pfflItems
= lens _pfflItems (\ s a -> s{_pfflItems = a}) .
_Default
. _Coerce
-- | The total number of results for the query, regardless of the number of
-- results in the response.
pfflTotalResults :: Lens' ProFileFilterLinks (Maybe Int32)
pfflTotalResults
= lens _pfflTotalResults
(\ s a -> s{_pfflTotalResults = a})
. mapping _Coerce
-- | The starting index of the resources, which is 1 by default or otherwise
-- specified by the start-index query parameter.
pfflStartIndex :: Lens' ProFileFilterLinks (Maybe Int32)
pfflStartIndex
= lens _pfflStartIndex
(\ s a -> s{_pfflStartIndex = a})
. mapping _Coerce
-- | Link to previous page for this profile filter link collection.
pfflPreviousLink :: Lens' ProFileFilterLinks (Maybe Text)
pfflPreviousLink
= lens _pfflPreviousLink
(\ s a -> s{_pfflPreviousLink = a})
instance FromJSON ProFileFilterLinks where
parseJSON
= withObject "ProFileFilterLinks"
(\ o ->
ProFileFilterLinks' <$>
(o .:? "nextLink") <*> (o .:? "itemsPerPage") <*>
(o .:? "kind" .!= "analytics#profileFilterLinks")
<*> (o .:? "username")
<*> (o .:? "items" .!= mempty)
<*> (o .:? "totalResults")
<*> (o .:? "startIndex")
<*> (o .:? "previousLink"))
instance ToJSON ProFileFilterLinks where
toJSON ProFileFilterLinks'{..}
= object
(catMaybes
[("nextLink" .=) <$> _pfflNextLink,
("itemsPerPage" .=) <$> _pfflItemsPerPage,
Just ("kind" .= _pfflKind),
("username" .=) <$> _pfflUsername,
("items" .=) <$> _pfflItems,
("totalResults" .=) <$> _pfflTotalResults,
("startIndex" .=) <$> _pfflStartIndex,
("previousLink" .=) <$> _pfflPreviousLink])
-- | Parent link for this web property. Points to the account to which this
-- web property belongs.
--
-- /See:/ 'webPropertyParentLink' smart constructor.
data WebPropertyParentLink =
WebPropertyParentLink'
{ _wpplHref :: !(Maybe Text)
, _wpplType :: !Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'WebPropertyParentLink' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'wpplHref'
--
-- * 'wpplType'
webPropertyParentLink
:: WebPropertyParentLink
webPropertyParentLink =
WebPropertyParentLink' {_wpplHref = Nothing, _wpplType = "analytics#account"}
-- | Link to the account for this web property.
wpplHref :: Lens' WebPropertyParentLink (Maybe Text)
wpplHref = lens _wpplHref (\ s a -> s{_wpplHref = a})
-- | Type of the parent link. Its value is \"analytics#account\".
wpplType :: Lens' WebPropertyParentLink Text
wpplType = lens _wpplType (\ s a -> s{_wpplType = a})
instance FromJSON WebPropertyParentLink where
parseJSON
= withObject "WebPropertyParentLink"
(\ o ->
WebPropertyParentLink' <$>
(o .:? "href") <*>
(o .:? "type" .!= "analytics#account"))
instance ToJSON WebPropertyParentLink where
toJSON WebPropertyParentLink'{..}
= object
(catMaybes
[("href" .=) <$> _wpplHref,
Just ("type" .= _wpplType)])
-- | Information for the view (profile), for which the Analytics data was
-- requested.
--
-- /See:/ 'gaDataProFileInfo' smart constructor.
data GaDataProFileInfo =
GaDataProFileInfo'
{ _gdpfiWebPropertyId :: !(Maybe Text)
, _gdpfiProFileId :: !(Maybe Text)
, _gdpfiProFileName :: !(Maybe Text)
, _gdpfiAccountId :: !(Maybe Text)
, _gdpfiInternalWebPropertyId :: !(Maybe Text)
, _gdpfiTableId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'GaDataProFileInfo' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gdpfiWebPropertyId'
--
-- * 'gdpfiProFileId'
--
-- * 'gdpfiProFileName'
--
-- * 'gdpfiAccountId'
--
-- * 'gdpfiInternalWebPropertyId'
--
-- * 'gdpfiTableId'
gaDataProFileInfo
:: GaDataProFileInfo
gaDataProFileInfo =
GaDataProFileInfo'
{ _gdpfiWebPropertyId = Nothing
, _gdpfiProFileId = Nothing
, _gdpfiProFileName = Nothing
, _gdpfiAccountId = Nothing
, _gdpfiInternalWebPropertyId = Nothing
, _gdpfiTableId = Nothing
}
-- | Web Property ID to which this view (profile) belongs.
gdpfiWebPropertyId :: Lens' GaDataProFileInfo (Maybe Text)
gdpfiWebPropertyId
= lens _gdpfiWebPropertyId
(\ s a -> s{_gdpfiWebPropertyId = a})
-- | View (Profile) ID.
gdpfiProFileId :: Lens' GaDataProFileInfo (Maybe Text)
gdpfiProFileId
= lens _gdpfiProFileId
(\ s a -> s{_gdpfiProFileId = a})
-- | View (Profile) name.
gdpfiProFileName :: Lens' GaDataProFileInfo (Maybe Text)
gdpfiProFileName
= lens _gdpfiProFileName
(\ s a -> s{_gdpfiProFileName = a})
-- | Account ID to which this view (profile) belongs.
gdpfiAccountId :: Lens' GaDataProFileInfo (Maybe Text)
gdpfiAccountId
= lens _gdpfiAccountId
(\ s a -> s{_gdpfiAccountId = a})
-- | Internal ID for the web property to which this view (profile) belongs.
gdpfiInternalWebPropertyId :: Lens' GaDataProFileInfo (Maybe Text)
gdpfiInternalWebPropertyId
= lens _gdpfiInternalWebPropertyId
(\ s a -> s{_gdpfiInternalWebPropertyId = a})
-- | Table ID for view (profile).
gdpfiTableId :: Lens' GaDataProFileInfo (Maybe Text)
gdpfiTableId
= lens _gdpfiTableId (\ s a -> s{_gdpfiTableId = a})
instance FromJSON GaDataProFileInfo where
parseJSON
= withObject "GaDataProFileInfo"
(\ o ->
GaDataProFileInfo' <$>
(o .:? "webPropertyId") <*> (o .:? "profileId") <*>
(o .:? "profileName")
<*> (o .:? "accountId")
<*> (o .:? "internalWebPropertyId")
<*> (o .:? "tableId"))
instance ToJSON GaDataProFileInfo where
toJSON GaDataProFileInfo'{..}
= object
(catMaybes
[("webPropertyId" .=) <$> _gdpfiWebPropertyId,
("profileId" .=) <$> _gdpfiProFileId,
("profileName" .=) <$> _gdpfiProFileName,
("accountId" .=) <$> _gdpfiAccountId,
("internalWebPropertyId" .=) <$>
_gdpfiInternalWebPropertyId,
("tableId" .=) <$> _gdpfiTableId])
-- | Metadata returned for an upload operation.
--
-- /See:/ 'upload' smart constructor.
data Upload =
Upload'
{ _uuStatus :: !(Maybe Text)
, _uuKind :: !Text
, _uuCustomDataSourceId :: !(Maybe Text)
, _uuUploadTime :: !(Maybe DateTime')
, _uuAccountId :: !(Maybe (Textual Int64))
, _uuId :: !(Maybe Text)
, _uuErrors :: !(Maybe [Text])
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Upload' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'uuStatus'
--
-- * 'uuKind'
--
-- * 'uuCustomDataSourceId'
--
-- * 'uuUploadTime'
--
-- * 'uuAccountId'
--
-- * 'uuId'
--
-- * 'uuErrors'
upload
:: Upload
upload =
Upload'
{ _uuStatus = Nothing
, _uuKind = "analytics#upload"
, _uuCustomDataSourceId = Nothing
, _uuUploadTime = Nothing
, _uuAccountId = Nothing
, _uuId = Nothing
, _uuErrors = Nothing
}
-- | Upload status. Possible values: PENDING, COMPLETED, FAILED, DELETING,
-- DELETED.
uuStatus :: Lens' Upload (Maybe Text)
uuStatus = lens _uuStatus (\ s a -> s{_uuStatus = a})
-- | Resource type for Analytics upload.
uuKind :: Lens' Upload Text
uuKind = lens _uuKind (\ s a -> s{_uuKind = a})
-- | Custom data source Id to which this data import belongs.
uuCustomDataSourceId :: Lens' Upload (Maybe Text)
uuCustomDataSourceId
= lens _uuCustomDataSourceId
(\ s a -> s{_uuCustomDataSourceId = a})
-- | Time this file is uploaded.
uuUploadTime :: Lens' Upload (Maybe UTCTime)
uuUploadTime
= lens _uuUploadTime (\ s a -> s{_uuUploadTime = a})
. mapping _DateTime
-- | Account Id to which this upload belongs.
uuAccountId :: Lens' Upload (Maybe Int64)
uuAccountId
= lens _uuAccountId (\ s a -> s{_uuAccountId = a}) .
mapping _Coerce
-- | A unique ID for this upload.
uuId :: Lens' Upload (Maybe Text)
uuId = lens _uuId (\ s a -> s{_uuId = a})
-- | Data import errors collection.
uuErrors :: Lens' Upload [Text]
uuErrors
= lens _uuErrors (\ s a -> s{_uuErrors = a}) .
_Default
. _Coerce
instance FromJSON Upload where
parseJSON
= withObject "Upload"
(\ o ->
Upload' <$>
(o .:? "status") <*>
(o .:? "kind" .!= "analytics#upload")
<*> (o .:? "customDataSourceId")
<*> (o .:? "uploadTime")
<*> (o .:? "accountId")
<*> (o .:? "id")
<*> (o .:? "errors" .!= mempty))
instance ToJSON Upload where
toJSON Upload'{..}
= object
(catMaybes
[("status" .=) <$> _uuStatus,
Just ("kind" .= _uuKind),
("customDataSourceId" .=) <$> _uuCustomDataSourceId,
("uploadTime" .=) <$> _uuUploadTime,
("accountId" .=) <$> _uuAccountId,
("id" .=) <$> _uuId, ("errors" .=) <$> _uuErrors])
-- | JSON template for Analytics Custom Dimension.
--
-- /See:/ 'customDimension' smart constructor.
data CustomDimension =
CustomDimension'
{ _cddParentLink :: !(Maybe CustomDimensionParentLink)
, _cddWebPropertyId :: !(Maybe Text)
, _cddKind :: !Text
, _cddCreated :: !(Maybe DateTime')
, _cddActive :: !(Maybe Bool)
, _cddSelfLink :: !(Maybe Text)
, _cddAccountId :: !(Maybe Text)
, _cddName :: !(Maybe Text)
, _cddScope :: !(Maybe Text)
, _cddId :: !(Maybe Text)
, _cddUpdated :: !(Maybe DateTime')
, _cddIndex :: !(Maybe (Textual Int32))
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'CustomDimension' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cddParentLink'
--
-- * 'cddWebPropertyId'
--
-- * 'cddKind'
--
-- * 'cddCreated'
--
-- * 'cddActive'
--
-- * 'cddSelfLink'
--
-- * 'cddAccountId'
--
-- * 'cddName'
--
-- * 'cddScope'
--
-- * 'cddId'
--
-- * 'cddUpdated'
--
-- * 'cddIndex'
customDimension
:: CustomDimension
customDimension =
CustomDimension'
{ _cddParentLink = Nothing
, _cddWebPropertyId = Nothing
, _cddKind = "analytics#customDimension"
, _cddCreated = Nothing
, _cddActive = Nothing
, _cddSelfLink = Nothing
, _cddAccountId = Nothing
, _cddName = Nothing
, _cddScope = Nothing
, _cddId = Nothing
, _cddUpdated = Nothing
, _cddIndex = Nothing
}
-- | Parent link for the custom dimension. Points to the property to which
-- the custom dimension belongs.
cddParentLink :: Lens' CustomDimension (Maybe CustomDimensionParentLink)
cddParentLink
= lens _cddParentLink
(\ s a -> s{_cddParentLink = a})
-- | Property ID.
cddWebPropertyId :: Lens' CustomDimension (Maybe Text)
cddWebPropertyId
= lens _cddWebPropertyId
(\ s a -> s{_cddWebPropertyId = a})
-- | Kind value for a custom dimension. Set to \"analytics#customDimension\".
-- It is a read-only field.
cddKind :: Lens' CustomDimension Text
cddKind = lens _cddKind (\ s a -> s{_cddKind = a})
-- | Time the custom dimension was created.
cddCreated :: Lens' CustomDimension (Maybe UTCTime)
cddCreated
= lens _cddCreated (\ s a -> s{_cddCreated = a}) .
mapping _DateTime
-- | Boolean indicating whether the custom dimension is active.
cddActive :: Lens' CustomDimension (Maybe Bool)
cddActive
= lens _cddActive (\ s a -> s{_cddActive = a})
-- | Link for the custom dimension
cddSelfLink :: Lens' CustomDimension (Maybe Text)
cddSelfLink
= lens _cddSelfLink (\ s a -> s{_cddSelfLink = a})
-- | Account ID.
cddAccountId :: Lens' CustomDimension (Maybe Text)
cddAccountId
= lens _cddAccountId (\ s a -> s{_cddAccountId = a})
-- | Name of the custom dimension.
cddName :: Lens' CustomDimension (Maybe Text)
cddName = lens _cddName (\ s a -> s{_cddName = a})
-- | Scope of the custom dimension: HIT, SESSION, USER or PRODUCT.
cddScope :: Lens' CustomDimension (Maybe Text)
cddScope = lens _cddScope (\ s a -> s{_cddScope = a})
-- | Custom dimension ID.
cddId :: Lens' CustomDimension (Maybe Text)
cddId = lens _cddId (\ s a -> s{_cddId = a})
-- | Time the custom dimension was last modified.
cddUpdated :: Lens' CustomDimension (Maybe UTCTime)
cddUpdated
= lens _cddUpdated (\ s a -> s{_cddUpdated = a}) .
mapping _DateTime
-- | Index of the custom dimension.
cddIndex :: Lens' CustomDimension (Maybe Int32)
cddIndex
= lens _cddIndex (\ s a -> s{_cddIndex = a}) .
mapping _Coerce
instance FromJSON CustomDimension where
parseJSON
= withObject "CustomDimension"
(\ o ->
CustomDimension' <$>
(o .:? "parentLink") <*> (o .:? "webPropertyId") <*>
(o .:? "kind" .!= "analytics#customDimension")
<*> (o .:? "created")
<*> (o .:? "active")
<*> (o .:? "selfLink")
<*> (o .:? "accountId")
<*> (o .:? "name")
<*> (o .:? "scope")
<*> (o .:? "id")
<*> (o .:? "updated")
<*> (o .:? "index"))
instance ToJSON CustomDimension where
toJSON CustomDimension'{..}
= object
(catMaybes
[("parentLink" .=) <$> _cddParentLink,
("webPropertyId" .=) <$> _cddWebPropertyId,
Just ("kind" .= _cddKind),
("created" .=) <$> _cddCreated,
("active" .=) <$> _cddActive,
("selfLink" .=) <$> _cddSelfLink,
("accountId" .=) <$> _cddAccountId,
("name" .=) <$> _cddName, ("scope" .=) <$> _cddScope,
("id" .=) <$> _cddId, ("updated" .=) <$> _cddUpdated,
("index" .=) <$> _cddIndex])
-- | JSON template for an Analytics segment.
--
-- /See:/ 'segment' smart constructor.
data Segment =
Segment'
{ _segDefinition :: !(Maybe Text)
, _segKind :: !Text
, _segCreated :: !(Maybe DateTime')
, _segSelfLink :: !(Maybe Text)
, _segName :: !(Maybe Text)
, _segId :: !(Maybe Text)
, _segUpdated :: !(Maybe DateTime')
, _segType :: !(Maybe Text)
, _segSegmentId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Segment' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'segDefinition'
--
-- * 'segKind'
--
-- * 'segCreated'
--
-- * 'segSelfLink'
--
-- * 'segName'
--
-- * 'segId'
--
-- * 'segUpdated'
--
-- * 'segType'
--
-- * 'segSegmentId'
segment
:: Segment
segment =
Segment'
{ _segDefinition = Nothing
, _segKind = "analytics#segment"
, _segCreated = Nothing
, _segSelfLink = Nothing
, _segName = Nothing
, _segId = Nothing
, _segUpdated = Nothing
, _segType = Nothing
, _segSegmentId = Nothing
}
-- | Segment definition.
segDefinition :: Lens' Segment (Maybe Text)
segDefinition
= lens _segDefinition
(\ s a -> s{_segDefinition = a})
-- | Resource type for Analytics segment.
segKind :: Lens' Segment Text
segKind = lens _segKind (\ s a -> s{_segKind = a})
-- | Time the segment was created.
segCreated :: Lens' Segment (Maybe UTCTime)
segCreated
= lens _segCreated (\ s a -> s{_segCreated = a}) .
mapping _DateTime
-- | Link for this segment.
segSelfLink :: Lens' Segment (Maybe Text)
segSelfLink
= lens _segSelfLink (\ s a -> s{_segSelfLink = a})
-- | Segment name.
segName :: Lens' Segment (Maybe Text)
segName = lens _segName (\ s a -> s{_segName = a})
-- | Segment ID.
segId :: Lens' Segment (Maybe Text)
segId = lens _segId (\ s a -> s{_segId = a})
-- | Time the segment was last modified.
segUpdated :: Lens' Segment (Maybe UTCTime)
segUpdated
= lens _segUpdated (\ s a -> s{_segUpdated = a}) .
mapping _DateTime
-- | Type for a segment. Possible values are \"BUILT_IN\" or \"CUSTOM\".
segType :: Lens' Segment (Maybe Text)
segType = lens _segType (\ s a -> s{_segType = a})
-- | Segment ID. Can be used with the \'segment\' parameter in Core Reporting
-- API.
segSegmentId :: Lens' Segment (Maybe Text)
segSegmentId
= lens _segSegmentId (\ s a -> s{_segSegmentId = a})
instance FromJSON Segment where
parseJSON
= withObject "Segment"
(\ o ->
Segment' <$>
(o .:? "definition") <*>
(o .:? "kind" .!= "analytics#segment")
<*> (o .:? "created")
<*> (o .:? "selfLink")
<*> (o .:? "name")
<*> (o .:? "id")
<*> (o .:? "updated")
<*> (o .:? "type")
<*> (o .:? "segmentId"))
instance ToJSON Segment where
toJSON Segment'{..}
= object
(catMaybes
[("definition" .=) <$> _segDefinition,
Just ("kind" .= _segKind),
("created" .=) <$> _segCreated,
("selfLink" .=) <$> _segSelfLink,
("name" .=) <$> _segName, ("id" .=) <$> _segId,
("updated" .=) <$> _segUpdated,
("type" .=) <$> _segType,
("segmentId" .=) <$> _segSegmentId])
-- | Child link for an account entry. Points to the list of web properties
-- for this account.
--
-- /See:/ 'accountChildLink' smart constructor.
data AccountChildLink =
AccountChildLink'
{ _aclHref :: !(Maybe Text)
, _aclType :: !Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'AccountChildLink' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'aclHref'
--
-- * 'aclType'
accountChildLink
:: AccountChildLink
accountChildLink =
AccountChildLink' {_aclHref = Nothing, _aclType = "analytics#webproperties"}
-- | Link to the list of web properties for this account.
aclHref :: Lens' AccountChildLink (Maybe Text)
aclHref = lens _aclHref (\ s a -> s{_aclHref = a})
-- | Type of the child link. Its value is \"analytics#webproperties\".
aclType :: Lens' AccountChildLink Text
aclType = lens _aclType (\ s a -> s{_aclType = a})
instance FromJSON AccountChildLink where
parseJSON
= withObject "AccountChildLink"
(\ o ->
AccountChildLink' <$>
(o .:? "href") <*>
(o .:? "type" .!= "analytics#webproperties"))
instance ToJSON AccountChildLink where
toJSON AccountChildLink'{..}
= object
(catMaybes
[("href" .=) <$> _aclHref,
Just ("type" .= _aclType)])
-- | JSON template for an Analytics profile filter link.
--
-- /See:/ 'proFileFilterLink' smart constructor.
data ProFileFilterLink =
ProFileFilterLink'
{ _proProFileRef :: !(Maybe ProFileRef)
, _proKind :: !Text
, _proFilterRef :: !(Maybe FilterRef)
, _proSelfLink :: !(Maybe Text)
, _proId :: !(Maybe Text)
, _proRank :: !(Maybe (Textual Int32))
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProFileFilterLink' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'proProFileRef'
--
-- * 'proKind'
--
-- * 'proFilterRef'
--
-- * 'proSelfLink'
--
-- * 'proId'
--
-- * 'proRank'
proFileFilterLink
:: ProFileFilterLink
proFileFilterLink =
ProFileFilterLink'
{ _proProFileRef = Nothing
, _proKind = "analytics#profileFilterLink"
, _proFilterRef = Nothing
, _proSelfLink = Nothing
, _proId = Nothing
, _proRank = Nothing
}
-- | View (Profile) for this link.
proProFileRef :: Lens' ProFileFilterLink (Maybe ProFileRef)
proProFileRef
= lens _proProFileRef
(\ s a -> s{_proProFileRef = a})
-- | Resource type for Analytics filter.
proKind :: Lens' ProFileFilterLink Text
proKind = lens _proKind (\ s a -> s{_proKind = a})
-- | Filter for this link.
proFilterRef :: Lens' ProFileFilterLink (Maybe FilterRef)
proFilterRef
= lens _proFilterRef (\ s a -> s{_proFilterRef = a})
-- | Link for this profile filter link.
proSelfLink :: Lens' ProFileFilterLink (Maybe Text)
proSelfLink
= lens _proSelfLink (\ s a -> s{_proSelfLink = a})
-- | Profile filter link ID.
proId :: Lens' ProFileFilterLink (Maybe Text)
proId = lens _proId (\ s a -> s{_proId = a})
-- | The rank of this profile filter link relative to the other filters
-- linked to the same profile. For readonly (i.e., list and get)
-- operations, the rank always starts at 1. For write (i.e., create,
-- update, or delete) operations, you may specify a value between 0 and 255
-- inclusively, [0, 255]. In order to insert a link at the end of the list,
-- either don\'t specify a rank or set a rank to a number greater than the
-- largest rank in the list. In order to insert a link to the beginning of
-- the list specify a rank that is less than or equal to 1. The new link
-- will move all existing filters with the same or lower rank down the
-- list. After the link is inserted\/updated\/deleted all profile filter
-- links will be renumbered starting at 1.
proRank :: Lens' ProFileFilterLink (Maybe Int32)
proRank
= lens _proRank (\ s a -> s{_proRank = a}) .
mapping _Coerce
instance FromJSON ProFileFilterLink where
parseJSON
= withObject "ProFileFilterLink"
(\ o ->
ProFileFilterLink' <$>
(o .:? "profileRef") <*>
(o .:? "kind" .!= "analytics#profileFilterLink")
<*> (o .:? "filterRef")
<*> (o .:? "selfLink")
<*> (o .:? "id")
<*> (o .:? "rank"))
instance ToJSON ProFileFilterLink where
toJSON ProFileFilterLink'{..}
= object
(catMaybes
[("profileRef" .=) <$> _proProFileRef,
Just ("kind" .= _proKind),
("filterRef" .=) <$> _proFilterRef,
("selfLink" .=) <$> _proSelfLink,
("id" .=) <$> _proId, ("rank" .=) <$> _proRank])
-- | Parent link for the custom metric. Points to the property to which the
-- custom metric belongs.
--
-- /See:/ 'customMetricParentLink' smart constructor.
data CustomMetricParentLink =
CustomMetricParentLink'
{ _cmplHref :: !(Maybe Text)
, _cmplType :: !Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'CustomMetricParentLink' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cmplHref'
--
-- * 'cmplType'
customMetricParentLink
:: CustomMetricParentLink
customMetricParentLink =
CustomMetricParentLink'
{_cmplHref = Nothing, _cmplType = "analytics#webproperty"}
-- | Link to the property to which the custom metric belongs.
cmplHref :: Lens' CustomMetricParentLink (Maybe Text)
cmplHref = lens _cmplHref (\ s a -> s{_cmplHref = a})
-- | Type of the parent link. Set to \"analytics#webproperty\".
cmplType :: Lens' CustomMetricParentLink Text
cmplType = lens _cmplType (\ s a -> s{_cmplType = a})
instance FromJSON CustomMetricParentLink where
parseJSON
= withObject "CustomMetricParentLink"
(\ o ->
CustomMetricParentLink' <$>
(o .:? "href") <*>
(o .:? "type" .!= "analytics#webproperty"))
instance ToJSON CustomMetricParentLink where
toJSON CustomMetricParentLink'{..}
= object
(catMaybes
[("href" .=) <$> _cmplHref,
Just ("type" .= _cmplType)])
-- | JSON template for a metadata column.
--
-- /See:/ 'column' smart constructor.
data Column =
Column'
{ _ccKind :: !Text
, _ccAttributes :: !(Maybe ColumnAttributes)
, _ccId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Column' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ccKind'
--
-- * 'ccAttributes'
--
-- * 'ccId'
column
:: Column
column =
Column'
{_ccKind = "analytics#column", _ccAttributes = Nothing, _ccId = Nothing}
-- | Resource type for Analytics column.
ccKind :: Lens' Column Text
ccKind = lens _ccKind (\ s a -> s{_ccKind = a})
-- | Map of attribute name and value for this column.
ccAttributes :: Lens' Column (Maybe ColumnAttributes)
ccAttributes
= lens _ccAttributes (\ s a -> s{_ccAttributes = a})
-- | Column id.
ccId :: Lens' Column (Maybe Text)
ccId = lens _ccId (\ s a -> s{_ccId = a})
instance FromJSON Column where
parseJSON
= withObject "Column"
(\ o ->
Column' <$>
(o .:? "kind" .!= "analytics#column") <*>
(o .:? "attributes")
<*> (o .:? "id"))
instance ToJSON Column where
toJSON Column'{..}
= object
(catMaybes
[Just ("kind" .= _ccKind),
("attributes" .=) <$> _ccAttributes,
("id" .=) <$> _ccId])
-- | The simple audience definition that will cause a user to be added to an
-- audience.
--
-- /See:/ 'remarketingAudienceAudienceDefinition' smart constructor.
newtype RemarketingAudienceAudienceDefinition =
RemarketingAudienceAudienceDefinition'
{ _raadIncludeConditions :: Maybe IncludeConditions
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'RemarketingAudienceAudienceDefinition' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'raadIncludeConditions'
remarketingAudienceAudienceDefinition
:: RemarketingAudienceAudienceDefinition
remarketingAudienceAudienceDefinition =
RemarketingAudienceAudienceDefinition' {_raadIncludeConditions = Nothing}
-- | Defines the conditions to include users to the audience.
raadIncludeConditions :: Lens' RemarketingAudienceAudienceDefinition (Maybe IncludeConditions)
raadIncludeConditions
= lens _raadIncludeConditions
(\ s a -> s{_raadIncludeConditions = a})
instance FromJSON
RemarketingAudienceAudienceDefinition
where
parseJSON
= withObject "RemarketingAudienceAudienceDefinition"
(\ o ->
RemarketingAudienceAudienceDefinition' <$>
(o .:? "includeConditions"))
instance ToJSON RemarketingAudienceAudienceDefinition
where
toJSON RemarketingAudienceAudienceDefinition'{..}
= object
(catMaybes
[("includeConditions" .=) <$>
_raadIncludeConditions])
--
-- /See:/ 'gaDataDataTableColsItem' smart constructor.
data GaDataDataTableColsItem =
GaDataDataTableColsItem'
{ _gddtciId :: !(Maybe Text)
, _gddtciType :: !(Maybe Text)
, _gddtciLabel :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'GaDataDataTableColsItem' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gddtciId'
--
-- * 'gddtciType'
--
-- * 'gddtciLabel'
gaDataDataTableColsItem
:: GaDataDataTableColsItem
gaDataDataTableColsItem =
GaDataDataTableColsItem'
{_gddtciId = Nothing, _gddtciType = Nothing, _gddtciLabel = Nothing}
gddtciId :: Lens' GaDataDataTableColsItem (Maybe Text)
gddtciId = lens _gddtciId (\ s a -> s{_gddtciId = a})
gddtciType :: Lens' GaDataDataTableColsItem (Maybe Text)
gddtciType
= lens _gddtciType (\ s a -> s{_gddtciType = a})
gddtciLabel :: Lens' GaDataDataTableColsItem (Maybe Text)
gddtciLabel
= lens _gddtciLabel (\ s a -> s{_gddtciLabel = a})
instance FromJSON GaDataDataTableColsItem where
parseJSON
= withObject "GaDataDataTableColsItem"
(\ o ->
GaDataDataTableColsItem' <$>
(o .:? "id") <*> (o .:? "type") <*> (o .:? "label"))
instance ToJSON GaDataDataTableColsItem where
toJSON GaDataDataTableColsItem'{..}
= object
(catMaybes
[("id" .=) <$> _gddtciId,
("type" .=) <$> _gddtciType,
("label" .=) <$> _gddtciLabel])
--
-- /See:/ 'experimentVariationsItem' smart constructor.
data ExperimentVariationsItem =
ExperimentVariationsItem'
{ _eviStatus :: !(Maybe Text)
, _eviWeight :: !(Maybe (Textual Double))
, _eviURL :: !(Maybe Text)
, _eviWon :: !(Maybe Bool)
, _eviName :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ExperimentVariationsItem' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'eviStatus'
--
-- * 'eviWeight'
--
-- * 'eviURL'
--
-- * 'eviWon'
--
-- * 'eviName'
experimentVariationsItem
:: ExperimentVariationsItem
experimentVariationsItem =
ExperimentVariationsItem'
{ _eviStatus = Nothing
, _eviWeight = Nothing
, _eviURL = Nothing
, _eviWon = Nothing
, _eviName = Nothing
}
-- | Status of the variation. Possible values: \"ACTIVE\", \"INACTIVE\".
-- INACTIVE variations are not served. This field may not be changed for an
-- experiment whose status is ENDED.
eviStatus :: Lens' ExperimentVariationsItem (Maybe Text)
eviStatus
= lens _eviStatus (\ s a -> s{_eviStatus = a})
-- | Weight that this variation should receive. Only present if the
-- experiment is running. This field is read-only.
eviWeight :: Lens' ExperimentVariationsItem (Maybe Double)
eviWeight
= lens _eviWeight (\ s a -> s{_eviWeight = a}) .
mapping _Coerce
-- | The URL of the variation. This field may not be changed for an
-- experiment whose status is RUNNING or ENDED.
eviURL :: Lens' ExperimentVariationsItem (Maybe Text)
eviURL = lens _eviURL (\ s a -> s{_eviURL = a})
-- | True if the experiment has ended and this variation performed
-- (statistically) significantly better than the original. This field is
-- read-only.
eviWon :: Lens' ExperimentVariationsItem (Maybe Bool)
eviWon = lens _eviWon (\ s a -> s{_eviWon = a})
-- | The name of the variation. This field is required when creating an
-- experiment. This field may not be changed for an experiment whose status
-- is ENDED.
eviName :: Lens' ExperimentVariationsItem (Maybe Text)
eviName = lens _eviName (\ s a -> s{_eviName = a})
instance FromJSON ExperimentVariationsItem where
parseJSON
= withObject "ExperimentVariationsItem"
(\ o ->
ExperimentVariationsItem' <$>
(o .:? "status") <*> (o .:? "weight") <*>
(o .:? "url")
<*> (o .:? "won")
<*> (o .:? "name"))
instance ToJSON ExperimentVariationsItem where
toJSON ExperimentVariationsItem'{..}
= object
(catMaybes
[("status" .=) <$> _eviStatus,
("weight" .=) <$> _eviWeight, ("url" .=) <$> _eviURL,
("won" .=) <$> _eviWon, ("name" .=) <$> _eviName])
-- | Defines the conditions to exclude users from the audience.
--
-- /See:/ 'remarketingAudienceStateBasedAudienceDefinitionExcludeConditions' smart constructor.
data RemarketingAudienceStateBasedAudienceDefinitionExcludeConditions =
RemarketingAudienceStateBasedAudienceDefinitionExcludeConditions'
{ _rasbadecExclusionDuration :: !(Maybe Text)
, _rasbadecSegment :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'RemarketingAudienceStateBasedAudienceDefinitionExcludeConditions' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'rasbadecExclusionDuration'
--
-- * 'rasbadecSegment'
remarketingAudienceStateBasedAudienceDefinitionExcludeConditions
:: RemarketingAudienceStateBasedAudienceDefinitionExcludeConditions
remarketingAudienceStateBasedAudienceDefinitionExcludeConditions =
RemarketingAudienceStateBasedAudienceDefinitionExcludeConditions'
{_rasbadecExclusionDuration = Nothing, _rasbadecSegment = Nothing}
-- | Whether to make the exclusion TEMPORARY or PERMANENT.
rasbadecExclusionDuration :: Lens' RemarketingAudienceStateBasedAudienceDefinitionExcludeConditions (Maybe Text)
rasbadecExclusionDuration
= lens _rasbadecExclusionDuration
(\ s a -> s{_rasbadecExclusionDuration = a})
-- | The segment condition that will cause a user to be removed from an
-- audience.
rasbadecSegment :: Lens' RemarketingAudienceStateBasedAudienceDefinitionExcludeConditions (Maybe Text)
rasbadecSegment
= lens _rasbadecSegment
(\ s a -> s{_rasbadecSegment = a})
instance FromJSON
RemarketingAudienceStateBasedAudienceDefinitionExcludeConditions
where
parseJSON
= withObject
"RemarketingAudienceStateBasedAudienceDefinitionExcludeConditions"
(\ o ->
RemarketingAudienceStateBasedAudienceDefinitionExcludeConditions'
<$>
(o .:? "exclusionDuration") <*> (o .:? "segment"))
instance ToJSON
RemarketingAudienceStateBasedAudienceDefinitionExcludeConditions
where
toJSON
RemarketingAudienceStateBasedAudienceDefinitionExcludeConditions'{..}
= object
(catMaybes
[("exclusionDuration" .=) <$>
_rasbadecExclusionDuration,
("segment" .=) <$> _rasbadecSegment])
-- | Total values for the requested metrics over all the results, not just
-- the results returned in this response. The order of the metric totals is
-- same as the metric order specified in the request.
--
-- /See:/ 'mcfDataTotalsForAllResults' smart constructor.
newtype McfDataTotalsForAllResults =
McfDataTotalsForAllResults'
{ _mdtfarAddtional :: HashMap Text Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'McfDataTotalsForAllResults' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'mdtfarAddtional'
mcfDataTotalsForAllResults
:: HashMap Text Text -- ^ 'mdtfarAddtional'
-> McfDataTotalsForAllResults
mcfDataTotalsForAllResults pMdtfarAddtional_ =
McfDataTotalsForAllResults' {_mdtfarAddtional = _Coerce # pMdtfarAddtional_}
-- | Key-value pair for the total value of a metric. Key is the metric name
-- and the value is the total value for that metric.
mdtfarAddtional :: Lens' McfDataTotalsForAllResults (HashMap Text Text)
mdtfarAddtional
= lens _mdtfarAddtional
(\ s a -> s{_mdtfarAddtional = a})
. _Coerce
instance FromJSON McfDataTotalsForAllResults where
parseJSON
= withObject "McfDataTotalsForAllResults"
(\ o ->
McfDataTotalsForAllResults' <$> (parseJSONObject o))
instance ToJSON McfDataTotalsForAllResults where
toJSON = toJSON . _mdtfarAddtional
-- | User ID.
--
-- /See:/ 'userDeletionRequestId' smart constructor.
data UserDeletionRequestId =
UserDeletionRequestId'
{ _udriUserId :: !(Maybe Text)
, _udriType :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'UserDeletionRequestId' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'udriUserId'
--
-- * 'udriType'
userDeletionRequestId
:: UserDeletionRequestId
userDeletionRequestId =
UserDeletionRequestId' {_udriUserId = Nothing, _udriType = Nothing}
-- | The User\'s id
udriUserId :: Lens' UserDeletionRequestId (Maybe Text)
udriUserId
= lens _udriUserId (\ s a -> s{_udriUserId = a})
-- | Type of user
udriType :: Lens' UserDeletionRequestId (Maybe Text)
udriType = lens _udriType (\ s a -> s{_udriType = a})
instance FromJSON UserDeletionRequestId where
parseJSON
= withObject "UserDeletionRequestId"
(\ o ->
UserDeletionRequestId' <$>
(o .:? "userId") <*> (o .:? "type"))
instance ToJSON UserDeletionRequestId where
toJSON UserDeletionRequestId'{..}
= object
(catMaybes
[("userId" .=) <$> _udriUserId,
("type" .=) <$> _udriType])
-- | Download details for a file stored in Google Cloud Storage.
--
-- /See:/ 'unSampledReportCloudStorageDownloadDetails' smart constructor.
data UnSampledReportCloudStorageDownloadDetails =
UnSampledReportCloudStorageDownloadDetails'
{ _usrcsddObjectId :: !(Maybe Text)
, _usrcsddBucketId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'UnSampledReportCloudStorageDownloadDetails' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'usrcsddObjectId'
--
-- * 'usrcsddBucketId'
unSampledReportCloudStorageDownloadDetails
:: UnSampledReportCloudStorageDownloadDetails
unSampledReportCloudStorageDownloadDetails =
UnSampledReportCloudStorageDownloadDetails'
{_usrcsddObjectId = Nothing, _usrcsddBucketId = Nothing}
-- | Id of the file object containing the report data.
usrcsddObjectId :: Lens' UnSampledReportCloudStorageDownloadDetails (Maybe Text)
usrcsddObjectId
= lens _usrcsddObjectId
(\ s a -> s{_usrcsddObjectId = a})
-- | Id of the bucket the file object is stored in.
usrcsddBucketId :: Lens' UnSampledReportCloudStorageDownloadDetails (Maybe Text)
usrcsddBucketId
= lens _usrcsddBucketId
(\ s a -> s{_usrcsddBucketId = a})
instance FromJSON
UnSampledReportCloudStorageDownloadDetails
where
parseJSON
= withObject
"UnSampledReportCloudStorageDownloadDetails"
(\ o ->
UnSampledReportCloudStorageDownloadDetails' <$>
(o .:? "objectId") <*> (o .:? "bucketId"))
instance ToJSON
UnSampledReportCloudStorageDownloadDetails
where
toJSON
UnSampledReportCloudStorageDownloadDetails'{..}
= object
(catMaybes
[("objectId" .=) <$> _usrcsddObjectId,
("bucketId" .=) <$> _usrcsddBucketId])
-- | Child link for this view (profile). Points to the list of goals for this
-- view (profile).
--
-- /See:/ 'proFileChildLink' smart constructor.
data ProFileChildLink =
ProFileChildLink'
{ _pfclHref :: !(Maybe Text)
, _pfclType :: !Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProFileChildLink' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pfclHref'
--
-- * 'pfclType'
proFileChildLink
:: ProFileChildLink
proFileChildLink =
ProFileChildLink' {_pfclHref = Nothing, _pfclType = "analytics#goals"}
-- | Link to the list of goals for this view (profile).
pfclHref :: Lens' ProFileChildLink (Maybe Text)
pfclHref = lens _pfclHref (\ s a -> s{_pfclHref = a})
-- | Value is \"analytics#goals\".
pfclType :: Lens' ProFileChildLink Text
pfclType = lens _pfclType (\ s a -> s{_pfclType = a})
instance FromJSON ProFileChildLink where
parseJSON
= withObject "ProFileChildLink"
(\ o ->
ProFileChildLink' <$>
(o .:? "href") <*>
(o .:? "type" .!= "analytics#goals"))
instance ToJSON ProFileChildLink where
toJSON ProFileChildLink'{..}
= object
(catMaybes
[("href" .=) <$> _pfclHref,
Just ("type" .= _pfclType)])
--
-- /See:/ 'gaDataColumnHeadersItem' smart constructor.
data GaDataColumnHeadersItem =
GaDataColumnHeadersItem'
{ _gdchiColumnType :: !(Maybe Text)
, _gdchiName :: !(Maybe Text)
, _gdchiDataType :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'GaDataColumnHeadersItem' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gdchiColumnType'
--
-- * 'gdchiName'
--
-- * 'gdchiDataType'
gaDataColumnHeadersItem
:: GaDataColumnHeadersItem
gaDataColumnHeadersItem =
GaDataColumnHeadersItem'
{_gdchiColumnType = Nothing, _gdchiName = Nothing, _gdchiDataType = Nothing}
-- | Column Type. Either DIMENSION or METRIC.
gdchiColumnType :: Lens' GaDataColumnHeadersItem (Maybe Text)
gdchiColumnType
= lens _gdchiColumnType
(\ s a -> s{_gdchiColumnType = a})
-- | Column name.
gdchiName :: Lens' GaDataColumnHeadersItem (Maybe Text)
gdchiName
= lens _gdchiName (\ s a -> s{_gdchiName = a})
-- | Data type. Dimension column headers have only STRING as the data type.
-- Metric column headers have data types for metric values such as INTEGER,
-- DOUBLE, CURRENCY etc.
gdchiDataType :: Lens' GaDataColumnHeadersItem (Maybe Text)
gdchiDataType
= lens _gdchiDataType
(\ s a -> s{_gdchiDataType = a})
instance FromJSON GaDataColumnHeadersItem where
parseJSON
= withObject "GaDataColumnHeadersItem"
(\ o ->
GaDataColumnHeadersItem' <$>
(o .:? "columnType") <*> (o .:? "name") <*>
(o .:? "dataType"))
instance ToJSON GaDataColumnHeadersItem where
toJSON GaDataColumnHeadersItem'{..}
= object
(catMaybes
[("columnType" .=) <$> _gdchiColumnType,
("name" .=) <$> _gdchiName,
("dataType" .=) <$> _gdchiDataType])
-- | Parent link for a goal. Points to the view (profile) to which this goal
-- belongs.
--
-- /See:/ 'goalParentLink' smart constructor.
data GoalParentLink =
GoalParentLink'
{ _gplHref :: !(Maybe Text)
, _gplType :: !Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'GoalParentLink' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gplHref'
--
-- * 'gplType'
goalParentLink
:: GoalParentLink
goalParentLink =
GoalParentLink' {_gplHref = Nothing, _gplType = "analytics#profile"}
-- | Link to the view (profile) to which this goal belongs.
gplHref :: Lens' GoalParentLink (Maybe Text)
gplHref = lens _gplHref (\ s a -> s{_gplHref = a})
-- | Value is \"analytics#profile\".
gplType :: Lens' GoalParentLink Text
gplType = lens _gplType (\ s a -> s{_gplType = a})
instance FromJSON GoalParentLink where
parseJSON
= withObject "GoalParentLink"
(\ o ->
GoalParentLink' <$>
(o .:? "href") <*>
(o .:? "type" .!= "analytics#profile"))
instance ToJSON GoalParentLink where
toJSON GoalParentLink'{..}
= object
(catMaybes
[("href" .=) <$> _gplHref,
Just ("type" .= _gplType)])
-- | Map of attribute name and value for this column.
--
-- /See:/ 'columnAttributes' smart constructor.
newtype ColumnAttributes =
ColumnAttributes'
{ _caAddtional :: HashMap Text Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ColumnAttributes' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'caAddtional'
columnAttributes
:: HashMap Text Text -- ^ 'caAddtional'
-> ColumnAttributes
columnAttributes pCaAddtional_ =
ColumnAttributes' {_caAddtional = _Coerce # pCaAddtional_}
-- | The name of the attribute.
caAddtional :: Lens' ColumnAttributes (HashMap Text Text)
caAddtional
= lens _caAddtional (\ s a -> s{_caAddtional = a}) .
_Coerce
instance FromJSON ColumnAttributes where
parseJSON
= withObject "ColumnAttributes"
(\ o -> ColumnAttributes' <$> (parseJSONObject o))
instance ToJSON ColumnAttributes where
toJSON = toJSON . _caAddtional
|
brendanhay/gogol
|
gogol-analytics/gen/Network/Google/Analytics/Types/Product.hs
|
mpl-2.0
| 353,479
| 0
| 38
| 90,398
| 72,242
| 41,502
| 30,740
| 7,927
| 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.ServiceNetworking.Services.Projects.Global.Networks.Get
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Service producers use this method to get the configuration of their
-- connection including the import\/export of custom routes and subnetwork
-- routes with public IP.
--
-- /See:/ <https://cloud.google.com/service-infrastructure/docs/service-networking/getting-started Service Networking API Reference> for @servicenetworking.services.projects.global.networks.get@.
module Network.Google.Resource.ServiceNetworking.Services.Projects.Global.Networks.Get
(
-- * REST Resource
ServicesProjectsGlobalNetworksGetResource
-- * Creating a Request
, servicesProjectsGlobalNetworksGet
, ServicesProjectsGlobalNetworksGet
-- * Request Lenses
, spgngXgafv
, spgngUploadProtocol
, spgngAccessToken
, spgngUploadType
, spgngName
, spgngCallback
) where
import Network.Google.Prelude
import Network.Google.ServiceNetworking.Types
-- | A resource alias for @servicenetworking.services.projects.global.networks.get@ method which the
-- 'ServicesProjectsGlobalNetworksGet' request conforms to.
type ServicesProjectsGlobalNetworksGetResource =
"v1" :>
Capture "name" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] ConsumerConfig
-- | Service producers use this method to get the configuration of their
-- connection including the import\/export of custom routes and subnetwork
-- routes with public IP.
--
-- /See:/ 'servicesProjectsGlobalNetworksGet' smart constructor.
data ServicesProjectsGlobalNetworksGet =
ServicesProjectsGlobalNetworksGet'
{ _spgngXgafv :: !(Maybe Xgafv)
, _spgngUploadProtocol :: !(Maybe Text)
, _spgngAccessToken :: !(Maybe Text)
, _spgngUploadType :: !(Maybe Text)
, _spgngName :: !Text
, _spgngCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ServicesProjectsGlobalNetworksGet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'spgngXgafv'
--
-- * 'spgngUploadProtocol'
--
-- * 'spgngAccessToken'
--
-- * 'spgngUploadType'
--
-- * 'spgngName'
--
-- * 'spgngCallback'
servicesProjectsGlobalNetworksGet
:: Text -- ^ 'spgngName'
-> ServicesProjectsGlobalNetworksGet
servicesProjectsGlobalNetworksGet pSpgngName_ =
ServicesProjectsGlobalNetworksGet'
{ _spgngXgafv = Nothing
, _spgngUploadProtocol = Nothing
, _spgngAccessToken = Nothing
, _spgngUploadType = Nothing
, _spgngName = pSpgngName_
, _spgngCallback = Nothing
}
-- | V1 error format.
spgngXgafv :: Lens' ServicesProjectsGlobalNetworksGet (Maybe Xgafv)
spgngXgafv
= lens _spgngXgafv (\ s a -> s{_spgngXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
spgngUploadProtocol :: Lens' ServicesProjectsGlobalNetworksGet (Maybe Text)
spgngUploadProtocol
= lens _spgngUploadProtocol
(\ s a -> s{_spgngUploadProtocol = a})
-- | OAuth access token.
spgngAccessToken :: Lens' ServicesProjectsGlobalNetworksGet (Maybe Text)
spgngAccessToken
= lens _spgngAccessToken
(\ s a -> s{_spgngAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
spgngUploadType :: Lens' ServicesProjectsGlobalNetworksGet (Maybe Text)
spgngUploadType
= lens _spgngUploadType
(\ s a -> s{_spgngUploadType = a})
-- | Required. Name of the consumer config to retrieve in the format:
-- \`services\/{service}\/projects\/{project}\/global\/networks\/{network}\`.
-- {service} is the peering service that is managing connectivity for the
-- service producer\'s organization. For Google services that support this
-- functionality, this value is \`servicenetworking.googleapis.com\`.
-- {project} is a project number e.g. \`12345\` that contains the service
-- consumer\'s VPC network. {network} is the name of the service
-- consumer\'s VPC network.
spgngName :: Lens' ServicesProjectsGlobalNetworksGet Text
spgngName
= lens _spgngName (\ s a -> s{_spgngName = a})
-- | JSONP
spgngCallback :: Lens' ServicesProjectsGlobalNetworksGet (Maybe Text)
spgngCallback
= lens _spgngCallback
(\ s a -> s{_spgngCallback = a})
instance GoogleRequest
ServicesProjectsGlobalNetworksGet
where
type Rs ServicesProjectsGlobalNetworksGet =
ConsumerConfig
type Scopes ServicesProjectsGlobalNetworksGet =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/service.management"]
requestClient ServicesProjectsGlobalNetworksGet'{..}
= go _spgngName _spgngXgafv _spgngUploadProtocol
_spgngAccessToken
_spgngUploadType
_spgngCallback
(Just AltJSON)
serviceNetworkingService
where go
= buildClient
(Proxy ::
Proxy ServicesProjectsGlobalNetworksGetResource)
mempty
|
brendanhay/gogol
|
gogol-servicenetworking/gen/Network/Google/Resource/ServiceNetworking/Services/Projects/Global/Networks/Get.hs
|
mpl-2.0
| 6,014
| 0
| 15
| 1,231
| 711
| 421
| 290
| 108
| 1
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.DoubleClickBidManager.Queries.GetQuery
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Retrieves a stored query.
--
-- /See:/ <https://developers.google.com/bid-manager/ DoubleClick Bid Manager API Reference> for @doubleclickbidmanager.queries.getquery@.
module Network.Google.Resource.DoubleClickBidManager.Queries.GetQuery
(
-- * REST Resource
QueriesGetQueryResource
-- * Creating a Request
, queriesGetQuery
, QueriesGetQuery
-- * Request Lenses
, qgqXgafv
, qgqQueryId
, qgqUploadProtocol
, qgqAccessToken
, qgqUploadType
, qgqCallback
) where
import Network.Google.DoubleClickBids.Types
import Network.Google.Prelude
-- | A resource alias for @doubleclickbidmanager.queries.getquery@ method which the
-- 'QueriesGetQuery' request conforms to.
type QueriesGetQueryResource =
"doubleclickbidmanager" :>
"v1.1" :>
"query" :>
Capture "queryId" (Textual Int64) :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :> Get '[JSON] Query
-- | Retrieves a stored query.
--
-- /See:/ 'queriesGetQuery' smart constructor.
data QueriesGetQuery =
QueriesGetQuery'
{ _qgqXgafv :: !(Maybe Xgafv)
, _qgqQueryId :: !(Textual Int64)
, _qgqUploadProtocol :: !(Maybe Text)
, _qgqAccessToken :: !(Maybe Text)
, _qgqUploadType :: !(Maybe Text)
, _qgqCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'QueriesGetQuery' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'qgqXgafv'
--
-- * 'qgqQueryId'
--
-- * 'qgqUploadProtocol'
--
-- * 'qgqAccessToken'
--
-- * 'qgqUploadType'
--
-- * 'qgqCallback'
queriesGetQuery
:: Int64 -- ^ 'qgqQueryId'
-> QueriesGetQuery
queriesGetQuery pQgqQueryId_ =
QueriesGetQuery'
{ _qgqXgafv = Nothing
, _qgqQueryId = _Coerce # pQgqQueryId_
, _qgqUploadProtocol = Nothing
, _qgqAccessToken = Nothing
, _qgqUploadType = Nothing
, _qgqCallback = Nothing
}
-- | V1 error format.
qgqXgafv :: Lens' QueriesGetQuery (Maybe Xgafv)
qgqXgafv = lens _qgqXgafv (\ s a -> s{_qgqXgafv = a})
-- | Query ID to retrieve.
qgqQueryId :: Lens' QueriesGetQuery Int64
qgqQueryId
= lens _qgqQueryId (\ s a -> s{_qgqQueryId = a}) .
_Coerce
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
qgqUploadProtocol :: Lens' QueriesGetQuery (Maybe Text)
qgqUploadProtocol
= lens _qgqUploadProtocol
(\ s a -> s{_qgqUploadProtocol = a})
-- | OAuth access token.
qgqAccessToken :: Lens' QueriesGetQuery (Maybe Text)
qgqAccessToken
= lens _qgqAccessToken
(\ s a -> s{_qgqAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
qgqUploadType :: Lens' QueriesGetQuery (Maybe Text)
qgqUploadType
= lens _qgqUploadType
(\ s a -> s{_qgqUploadType = a})
-- | JSONP
qgqCallback :: Lens' QueriesGetQuery (Maybe Text)
qgqCallback
= lens _qgqCallback (\ s a -> s{_qgqCallback = a})
instance GoogleRequest QueriesGetQuery where
type Rs QueriesGetQuery = Query
type Scopes QueriesGetQuery =
'["https://www.googleapis.com/auth/doubleclickbidmanager"]
requestClient QueriesGetQuery'{..}
= go _qgqQueryId _qgqXgafv _qgqUploadProtocol
_qgqAccessToken
_qgqUploadType
_qgqCallback
(Just AltJSON)
doubleClickBidsService
where go
= buildClient
(Proxy :: Proxy QueriesGetQueryResource)
mempty
|
brendanhay/gogol
|
gogol-doubleclick-bids/gen/Network/Google/Resource/DoubleClickBidManager/Queries/GetQuery.hs
|
mpl-2.0
| 4,569
| 0
| 17
| 1,081
| 722
| 419
| 303
| 104
| 1
|
module Mean where
mean :: (Integral a, Fractional b) => [a] -> b
mean a = (fromIntegral $ sum a) / (fromIntegral $ length a)
|
ice1000/OI-codes
|
codewars/1-100/thats-mean.hs
|
agpl-3.0
| 126
| 0
| 8
| 26
| 63
| 34
| 29
| 3
| 1
|
{-
Copyright (C) 2009 Andrejs Sisojevs <andrejs.sisojevs@nextmail.ru>
All rights reserved.
For license and copyright information, see the file COPYRIGHT
-}
--------------------------------------------------------------------------
--------------------------------------------------------------------------
-- | This is thought to be imported outside of PCLT package by modules,
-- that use PCLT logics (catalog formation routines and
-- messages generation routines)
--
-- And another briefing on what is PCLT. First is in the top level of
-- Haddock documentation provided for the package.
--
-- _______________
--
-- > export "Text.PCLT.SH__"
--
-- This module provides interfaces to the classes 'ShowAsPCSI' and
-- 'HasStaticRawPCLTs' an all the routines, that usually are used for
-- declaration of their instanitations.
--
-- _______________
--
-- > export "Text.ConstraintedLBS"
--
-- A constrainting (the constraint here is on it's size) wrapper for a
-- lazy 'ByteString' (LBS) - this container is used for messages
-- generated from PCLT templates
--
-- _______________
--
-- > export "Text.PCLT.InitialDefaultCatalog"
--
-- > initDefaultCatalog_3 :: Text.PCLT.Catalog.PCLT_CatalogID -> (StdErr_CLBS, ShowDetalizationLevel, LanguageName) -> (PCLT_Catalog, StdErr_CLBS)
--
-- _______________
--
-- > export "Text.PCLT.Catalog"
--
-- Catalog is a unit with 3 fields: catalog ID, config, and a map by
-- template_IDs of templates, where each template is: minimal SDL required
-- to represent message from this template, and a maps by languages of
-- localized templates.
--
-- _______________
--
-- > export "Text.PCLT.CatalogFromHSRT"
--
-- We want to add to the default catalog some our application specific
-- entries (templates)
--
-- > addFromHSRTToCatalog_2 :: HasStaticRawPCLTs a => a -> PCLT_Catalog -> (StdErr_CLBS, ShowDetalizationLevel, LanguageName) -> (PCLT_Catalog, StdErr_CLBS)
--
-- _______________
--
-- > export "Text.PCLT.CommonTypes"
--
-- Some type aliases, like @'LanguageName' = 'String'@
--
-- _______________
--
-- > export "Text.PCLT.Config"
--
-- Configuration that influences the behaviour of catalog formation routines
-- and messages generation routines.
--
-- _______________
--
-- > export "Text.PCLT.MakeMessage"
--
-- PCSI(template_id + params) + language_name + recepient_SDL + catalog >---(Text.PCLT.MakeMessage)---> message
--
-- _______________
--
-- > export "Text.PCLT.MakeMessage2"
--
-- Some comfort wrappers for "Text.PCLT.MakeMessage"
--
-- _______________
--
-- > export "Text.PCLT.SDL"
--
-- SDL (Show Detalization Level) is a 1-dimensional variable type, built
-- on Int, but extended with additional values:
--
-- @Zero_SDL@ (absolute minimal level) @< One_SDL@ (minimal something) @< SDL Int < InfinitelyBig_SDL@
--
-- With SDL we regulate, how much some Reader (of our generated messages)
-- wishes (is allowed) to see.
--
-- _______________
--
-- > export "Text.PCLT.ShowAsPCSI__"
--
-- Some general instances of 'ShowAsPCSI' class are to be found here
-- (Bool, ShowAsPCSI a => Maybe a, SomeException)
module Text.PCLT (
module Text.PCLT.SH__
, module Text.ConstraintedLBS
, module Text.PCLT.InitialDefaultCatalog
, module Text.PCLT.Catalog
, module Text.PCLT.CatalogFromHSRT
, module Text.PCLT.CommonTypes
, module Text.PCLT.Config
, module Text.PCLT.MakeMessage
, module Text.PCLT.MakeMessage2
, module Text.PCLT.SDL
, module Text.PCLT.ShowAsPCSI__
) where
-- It's a pitty one can't comment with Haddock on imports...
import Text.PCLT.SH__
import Text.ConstraintedLBS
import Text.PCLT.InitialDefaultCatalog
import Text.PCLT.Catalog
import Text.PCLT.CatalogFromHSRT
import Text.PCLT.CommonTypes
import Text.PCLT.Config
import Text.PCLT.MakeMessage
import Text.PCLT.MakeMessage2
import Text.PCLT.SDL
import Text.PCLT.ShowAsPCSI__
|
Andrey-Sisoyev/haskell-PCLT
|
Text/PCLT.hs
|
lgpl-2.1
| 3,999
| 0
| 5
| 710
| 243
| 196
| 47
| 23
| 0
|
-- when (Control.Monad)
-- takes a Bool and an I/O action. If that Bool value is true, it returns the same
-- I/O action that we supplied to it. However, if it's False, it returns the
-- return () action, which doesn't do anything
import Control.Monad
main = do
input <- getLine
when (input == "SWORDFISH") $ do
putStrLn input
-- without when
-- main = do
-- input <- getLine
-- if (input == "SWORDFISH")
-- then putStrLn input
-- else return ()
|
Ketouem/learn-you-a-haskell
|
src/chapter-8-input-and-output/useful-io-fns/when.hs
|
unlicense
| 485
| 1
| 11
| 123
| 55
| 29
| 26
| 5
| 1
|
{-# LANGUAGE BangPatterns #-}
module Main where
import Prelude hiding (concat, filter)
import qualified Data.Alpino.Model as AM
import Data.Alpino.Model.Conduit
import Data.Conduit (Sink, runResourceT, ($=), ($$))
import qualified Data.Conduit.Binary as CB
import qualified Data.Conduit.List as CL
import Data.List (genericLength)
import System.IO (stdin)
import Text.Printf (printf)
statistics :: Monad m => Sink [AM.TrainingInstance] m (Int, Int, Int)
statistics =
CL.fold handleCtx (0, 0, 0)
where
handleCtx (!evts, !ctxs, !maxCtx) ctx =
(evts + ctxLen, succ ctxs, max maxCtx ctxLen)
where
ctxLen =
genericLength ctx
main :: IO ()
main = do
(evts, ctxs, maxCtx) <- runResourceT (CB.sourceHandle stdin $=
CB.lines $= bsToTrainingInstance $= groupByKey $$ statistics)
putStrLn $ printf "Contexts: %d" ctxs
putStrLn $ printf "Max. events: %d" maxCtx
putStrLn $ printf "Avg. events: %.2f" (fromIntegral evts / fromIntegral ctxs :: Double)
|
danieldk/alpino-tools
|
utils/model_statistics_data.hs
|
apache-2.0
| 995
| 0
| 15
| 187
| 325
| 184
| 141
| 25
| 1
|
doubleMe x = x + x
doubleSmallNumber x =
if x > 100
then x
else x*2
lostNumbers = [4,8,15,16,23,42]
|
Kermit95/Playground
|
lang/haskell/haskell_tut4.hs
|
apache-2.0
| 108
| 1
| 6
| 28
| 62
| 34
| 28
| 6
| 2
|
{-# LANGUAGE TemplateHaskell #-}
-- https://ocharles.org.uk/blog/guest-posts/2014-12-22-template-haskell.html
import Th04
import Language.Haskell.TH
primes= $(primeQ 0 2390)
main = do
runQ [d| x= 5|] >>= print
runQ [t| Int |] >>= print
runQ [p|(x,y)|] >>= print
print $ length $ primes
|
egaburov/funstuff
|
Haskell/thsk/th04.hs
|
apache-2.0
| 298
| 1
| 8
| 50
| 91
| 48
| 43
| 9
| 1
|
import Prelude
dropEvery :: [a] -> Int -> [a]
dropEvery [] _ = []
dropEvery xs n = (take (n - 1) xs) ++ dropEvery (drop n xs) n
|
2dor/99-problems-Haskell
|
11-20-lists-continued/problem-16.hs
|
bsd-2-clause
| 129
| 0
| 9
| 30
| 79
| 41
| 38
| 4
| 1
|
{-# LANGUAGE FlexibleContexts, ScopedTypeVariables #-}
-- hexpat, a Haskell wrapper for expat
-- Copyright (C) 2008 Evan Martin <martine@danga.com>
-- Copyright (C) 2009 Stephen Blackheath <http://blacksapphire.com/antispam>
-- | This module provides functions to format a tree
-- structure or SAX stream as UTF-8 encoded XML.
--
-- The formatting functions always outputs only UTF-8, regardless
-- of what encoding is specified in the document's 'Doc.XMLDeclaration'.
-- If you want to output a document in another encoding, then make sure the
-- 'Doc.XMLDeclaration' agrees with the final output encoding, then format the
-- document, and convert from UTF-8 to your desired encoding using some text
-- conversion library.
--
-- The lazy 'L.ByteString' representation of the output in generated with very
-- small chunks, so in some applications you may want to combine them into
-- larger chunks to get better efficiency.
module Text.XML.Expat.Format (
-- * High level
format,
format',
formatG,
formatNode,
formatNode',
formatNodeG,
-- * Format document (for use with Extended.hs)
formatDocument,
formatDocument',
formatDocumentG,
-- * Low level
xmlHeader,
treeToSAX,
documentToSAX,
formatSAX,
formatSAX',
formatSAXG,
-- * Indentation
indent,
indent_
) where
import qualified Text.XML.Expat.Internal.DocumentClass as Doc
import Text.XML.Expat.Internal.NodeClass
import Text.XML.Expat.SAX
import Control.Monad
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as L
import Data.ByteString.Internal (c2w, w2c)
import Data.Char (isSpace)
import Data.List.Class (List(..), ListItem(..), fromList)
import Data.Monoid
import Data.Word
import Data.Text (Text)
import Text.XML.Expat.Tree (UNode)
-- | Format document with <?xml.. header - lazy variant that returns lazy ByteString.
format :: (NodeClass n [], GenericXMLString tag, GenericXMLString text) =>
n [] tag text
-> L.ByteString
format node = L.fromChunks (xmlHeader : formatNodeG node)
{-# SPECIALIZE format :: UNode Text -> L.ByteString #-}
-- | Format document with <?xml.. header - generalized variant that returns a generic
-- list of strict ByteStrings.
formatG :: (NodeClass n c, GenericXMLString tag, GenericXMLString text) =>
n c tag text
-> c B.ByteString
formatG node = cons xmlHeader $ formatNodeG node
-- | Format document with <?xml.. header - strict variant that returns strict ByteString.
format' :: (NodeClass n [], GenericXMLString tag, GenericXMLString text) =>
n [] tag text
-> B.ByteString
format' = B.concat . L.toChunks . format
-- | Format XML node with no header - lazy variant that returns lazy ByteString.
formatNode :: (NodeClass n [], GenericXMLString tag, GenericXMLString text) =>
n [] tag text
-> L.ByteString
formatNode = formatSAX . treeToSAX
-- | Format XML node with no header - strict variant that returns strict ByteString.
formatNode' :: (NodeClass n [], GenericXMLString tag, GenericXMLString text) =>
n [] tag text
-> B.ByteString
formatNode' = B.concat . L.toChunks . formatNode
-- | Format XML node with no header - generalized variant that returns a generic
-- list of strict ByteStrings.
formatNodeG :: (NodeClass n c, GenericXMLString tag, GenericXMLString text) =>
n c tag text
-> c B.ByteString
formatNodeG = formatSAXG . treeToSAX
{-# SPECIALIZE formatNodeG :: UNode Text -> [B.ByteString] #-}
-- | Format an XML document - lazy variant that returns lazy ByteString.
formatDocument :: (Doc.DocumentClass d [], GenericXMLString tag, GenericXMLString text) =>
d [] tag text
-> L.ByteString
formatDocument = formatSAX . documentToSAX
-- | Format an XML document - strict variant that returns strict ByteString.
formatDocument' :: (Doc.DocumentClass d [], GenericXMLString tag, GenericXMLString text) =>
d [] tag text
-> B.ByteString
formatDocument' = B.concat . L.toChunks . formatDocument
-- | Format an XML document - generalized variant that returns a generic
-- list of strict ByteStrings.
formatDocumentG :: (Doc.DocumentClass d c, GenericXMLString tag, GenericXMLString text) =>
d c tag text
-> c B.ByteString
formatDocumentG = formatSAXG . documentToSAX
-- | The standard XML header with UTF-8 encoding.
xmlHeader :: B.ByteString
xmlHeader = B.pack $ map c2w "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
documentToSAX :: forall tag text d c . (GenericXMLString tag, GenericXMLString text,
Monoid text, Doc.DocumentClass d c) =>
d c tag text -> c (SAXEvent tag text)
documentToSAX doc =
(case Doc.getXMLDeclaration doc of
Just (Doc.XMLDeclaration ver mEnc sd) -> fromList [
XMLDeclaration ver mEnc sd, CharacterData (gxFromString "\n")]
Nothing -> mzero) `mplus`
join (fmap (\misc -> fromList [case misc of
Doc.ProcessingInstruction target text -> ProcessingInstruction target text
Doc.Comment text -> Comment text,
CharacterData (gxFromString "\n")]
) (Doc.getTopLevelMiscs doc)) `mplus`
treeToSAX (Doc.getRoot doc)
-- | Flatten a tree structure into SAX events, monadic version.
treeToSAX :: forall tag text n c . (GenericXMLString tag, GenericXMLString text,
Monoid text, NodeClass n c) =>
n c tag text -> c (SAXEvent tag text)
treeToSAX node
| isElement node =
let name = getName node
atts = getAttributes node
children = getChildren node
postpend :: c (SAXEvent tag text) -> c (SAXEvent tag text)
postpend l = joinL $ do
li <- runList l
return $ case li of
Nil -> singleton (EndElement name)
Cons n l' -> cons n (postpend l')
in cons (StartElement name atts) $
postpend (concatL $ fmap treeToSAX children)
| isCData node =
cons StartCData (cons (CharacterData $ getText node) (singleton EndCData))
| isText node =
singleton (CharacterData $ getText node)
| isProcessingInstruction node =
singleton (ProcessingInstruction (getTarget node) (getText node))
| isComment node =
singleton (Comment $ getText node)
| otherwise = mzero
where
singleton = return
concatL = join
{-# SPECIALIZE treeToSAX :: UNode Text -> [(SAXEvent Text Text)] #-}
-- | Format SAX events with no header - lazy variant that returns lazy ByteString.
formatSAX :: (GenericXMLString tag, GenericXMLString text) =>
[SAXEvent tag text]
-> L.ByteString
formatSAX = L.fromChunks . formatSAXG
-- | Format SAX events with no header - strict variant that returns strict ByteString.
formatSAX' :: (GenericXMLString tag, GenericXMLString text) =>
[SAXEvent tag text]
-> B.ByteString
formatSAX' = B.concat . formatSAXG
-- Do start tag and attributes but omit closing >
startTagHelper :: (GenericXMLString tag, GenericXMLString text) =>
tag
-> [(tag, text)]
-> [B.ByteString]
startTagHelper name atts =
B.singleton (c2w '<'):
gxToByteString name:
Prelude.concatMap (
\(aname, avalue) ->
B.singleton (c2w ' '):
gxToByteString aname:
pack "=\"":
escapeText (gxToByteString avalue)++
[B.singleton (c2w '"')]
) atts
-- | Format SAX events with no header - generalized variant that uses generic
-- list.
formatSAXG :: forall c tag text . (List c, GenericXMLString tag,
GenericXMLString text) =>
c (SAXEvent tag text) -- ^ SAX events
-> c B.ByteString
formatSAXG l1 = formatSAXGb l1 False
{-# SPECIALIZE formatSAXG :: [SAXEvent Text Text] -> [B.ByteString] #-}
formatSAXGb :: forall c tag text . (List c, GenericXMLString tag,
GenericXMLString text) =>
c (SAXEvent tag text) -- ^ SAX events
-> Bool -- ^ True if processing CDATA
-> c B.ByteString
formatSAXGb l1 cd = joinL $ do
it1 <- runList l1
return $ formatItem it1
where
formatItem it1 = case it1 of
Nil -> mzero
Cons (XMLDeclaration ver mEnc mSD) l2 ->
return (pack "<?xml version=\"") `mplus`
fromList (escapeText (gxToByteString ver)) `mplus`
return (pack "\"") `mplus`
(
case mEnc of
Nothing -> mzero
Just enc ->
return (pack " encoding=\"") `mplus`
fromList (escapeText (gxToByteString enc)) `mplus`
return (pack "\"")
) `mplus`
(
case mSD of
Nothing -> mzero
Just True -> return (pack " standalone=\"yes\"")
Just False -> return (pack " standalone=\"no\"")
) `mplus`
return (pack ("?>"))
`mplus`
formatSAXGb l2 cd
Cons (StartElement name attrs) l2 ->
fromList (startTagHelper name attrs)
`mplus` (
joinL $ do
it2 <- runList l2
return $ case it2 of
Cons (EndElement _) l3 ->
cons (pack "/>") $
formatSAXGb l3 cd
_ ->
cons (B.singleton (c2w '>')) $
formatItem it2
)
Cons (EndElement name) l2 ->
cons (pack "</") $
cons (gxToByteString name) $
cons (B.singleton (c2w '>')) $
formatSAXGb l2 cd
Cons (CharacterData txt) l2 ->
(if cd then
fromList [gxToByteString txt]
else
fromList (escapeText (gxToByteString txt))
) `mplus` (formatSAXGb l2 cd)
Cons StartCData l2 ->
cons(pack "<![CDATA[") $
formatSAXGb l2 True
Cons EndCData l2 ->
cons(pack "]]>") $
formatSAXGb l2 False
Cons (ProcessingInstruction target txt) l2 ->
cons (pack "<?") $
cons (gxToByteString target) $
cons (pack " ") $
cons (gxToByteString txt) $
cons (pack "?>") $
formatSAXGb l2 cd
Cons (Comment txt) l2 ->
cons (pack "<!--") $
cons (gxToByteString txt) $
cons (pack "-->") $
formatSAXGb l2 cd
Cons (FailDocument _) l2 ->
formatSAXGb l2 cd
{-# SPECIALIZE formatSAXGb :: [SAXEvent Text Text] -> Bool -> [B.ByteString] #-}
pack :: String -> B.ByteString
pack = B.pack . map c2w
isSafeChar :: Word8 -> Bool
isSafeChar c =
(c /= c2w '&')
&& (c /= c2w '<')
&& (c /= c2w '>')
&& (c /= c2w '"')
&& (c /= c2w '\'')
{-# INLINE isSafeChar #-}
escapeText :: B.ByteString -> [B.ByteString]
escapeText str | B.null str = []
escapeText str =
let (good, bad) = B.span isSafeChar str
in if B.null good
then case w2c $ B.head str of
'&' -> pack "&":escapeText rema
'<' -> pack "<":escapeText rema
'>' -> pack ">":escapeText rema
'"' -> pack """:escapeText rema
'\'' -> pack "'":escapeText rema
_ -> error "hexpat: impossible"
else good:escapeText bad
where
rema = B.tail str
-- | Make the output prettier by adding indentation.
indent :: (NodeClass n c, GenericXMLString tag, GenericXMLString text) =>
Int -- ^ Number of indentation spaces per nesting level
-> n c tag text
-> n c tag text
indent = indent_ 0
-- | Make the output prettier by adding indentation, specifying initial indent.
indent_ :: forall n c tag text . (NodeClass n c, GenericXMLString tag, GenericXMLString text) =>
Int -- ^ Initial indent (spaces)
-> Int -- ^ Number of indentation spaces per nesting level
-> n c tag text
-> n c tag text
indent_ cur perLevel elt | isElement elt =
flip modifyChildren elt $ \chs -> joinL $ do
(anyElts, chs') <- anyElements [] chs
-- The new list chs' is the same as the old list chs, but some of its
-- nodes have been loaded into memory. This is to avoid evaluating
-- list elements twice.
if anyElts
then addSpace True chs'
else return chs'
where
addSpace :: Bool -> c (n c tag text) -> ItemM c (c (n c tag text))
addSpace startOfText l = do
ch <- runList l
case ch of
Nil -> return $ singleton (mkText $ gxFromString ('\n':replicate cur ' '))
Cons elt l' | isElement elt -> do
let cur' = cur + perLevel
return $
cons (mkText $ gxFromString ('\n':replicate cur' ' ')) $
cons (indent_ cur' perLevel elt) $
joinL (addSpace True l')
Cons tx l' | isText tx && startOfText ->
case strip (getText tx) of
Nothing -> addSpace True l'
Just t' -> return $
cons (mkText t') $
joinL $ addSpace False l'
Cons n l' ->
return $
cons n $
joinL $ addSpace False l'
-- acc is used to keep the nodes we've scanned into memory.
-- We then construct a new list that looks the same as the old list, but
-- which starts with the nodes in memory, to prevent the list being
-- demanded more than once (in case it's monadic and it's expensive to
-- evaluate).
anyElements :: [n c tag text] -- ^ Accumulator for tags we've looked at.
-> c (n c tag text)
-> ItemM c (Bool, c (n c tag text))
anyElements acc l = do
n <- runList l
case n of
Nil -> return (False, instantiatedList acc mzero)
Cons n l' | isElement n -> return (True, instantiatedList (n:acc) l')
Cons n l' -> anyElements (n:acc) l'
where
instantiatedList :: [n c tag text] -> c (n c tag text) -> c (n c tag text)
instantiatedList acc l' = reverse acc `prepend` l'
prepend :: forall a . [a] -> c a -> c a
prepend xs l = foldr cons l xs
strip t | gxNullString t = Nothing
strip t | isSpace (gxHead t) = strip (gxTail t)
strip t = Just t
singleton = return
indent_ _ _ n = n
|
the-real-blackh/hexpat
|
Text/XML/Expat/Format.hs
|
bsd-3-clause
| 14,996
| 0
| 24
| 4,920
| 3,772
| 1,914
| 1,858
| 296
| 15
|
import Triangle
main :: IO ()
main = print $ filter (\x -> isTriangle x && isPent x) hexas !! 2
|
stulli/projectEuler
|
eu45.hs
|
bsd-3-clause
| 97
| 1
| 11
| 22
| 53
| 25
| 28
| 3
| 1
|
[ BlockComment
[ "/*"
, "*/"
], Space " ", Token "#", Space " ",
BlockComment
[ "/*"
, "*/"
], Space " ", Token "define", Space " ", Token "FOO", Space " ", Token "1020"
, NewLine
]
|
mkovacs/language-c-preproc
|
resources/test-small-2.out.hs
|
bsd-3-clause
| 196
| 0
| 7
| 53
| 85
| 44
| 41
| -1
| -1
|
module Evaluator (
evaluate
) where
import Base
termMap :: (Int -> Int -> Term) -> Term -> Term
termMap onvar t = go 0 t
where
go index (TermVar var) = onvar index var
go index (TermIfThenElse t1 t2 t3) = TermIfThenElse (go index t1) (go index t2) (go index t3)
go index (TermAbs var ty t) = TermAbs var ty (go (index + 1) t)
go index (TermApp t1 t2) = TermApp (go index t1) (go index t2)
go _ TermTrue = TermTrue
go _ TermFalse = TermFalse
-- | Shift up deBruijn indices of all free variables by delta.
termShift :: Term -> Int -> Term
termShift t delta = termMap (\index var -> if var >= index then TermVar (var + delta) else TermVar var) t
-- | Substitute the variable with 0 deBruijn index in term to subterm.
termSubstitute :: Term -> Term -> Term
termSubstitute t subt = termMap (\index var -> if var == index then termShift subt index else TermVar var) t
isValue :: Term -> Bool
isValue TermTrue = True
isValue TermFalse = True
isValue (TermAbs _ _ _) = True
isValue _ = False
-- | One step evaluation, return Nothing if there is no rule applies.
evaluate1 :: Term -> Maybe Term
{- E-IfTrue -}
evaluate1 (TermIfThenElse TermTrue t1 _) = Just t1
{- E-IfFalse -}
evaluate1 (TermIfThenElse TermFalse _ t2) = Just t2
{- E-If -}
evaluate1 (TermIfThenElse t t1 t2) = TermIfThenElse <$> evaluate1 t <*> pure t1 <*> pure t2
{- E-AppAbs -}
evaluate1 (TermApp (TermAbs _ _ t) v)
| isValue v = Just $ termShift (termSubstitute t (termShift v 1)) (-1)
{- E-App2 -}
evaluate1 (TermApp v t)
| isValue v = TermApp v <$> evaluate1 t
{- E-App1 -}
evaluate1 (TermApp t1 t2) = TermApp <$> evaluate1 t1 <*> pure t2
{- E-NoRule -}
evaluate1 _ = Nothing
evaluate :: Term -> Term
evaluate t = case evaluate1 t of
Just t' -> evaluate t'
Nothing -> t
|
foreverbell/unlimited-plt-toys
|
tapl/simplebool/Evaluator.hs
|
bsd-3-clause
| 1,783
| 0
| 11
| 385
| 681
| 341
| 340
| 34
| 6
|
{-# LANGUAGE OverloadedStrings #-}
module Hakyll.Convert.IO where
import qualified Data.ByteString as B
import Data.Maybe (fromJust)
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import Data.Time.Format (defaultTimeLocale, formatTime)
import Hakyll.Convert.Common (DistilledPost (..))
import Hakyll.Convert.OutputFormat (formatPath)
import System.Directory (createDirectoryIfMissing)
import System.FilePath (takeDirectory, takeFileName, (<.>), (</>))
-- | Save a post along with its comments in a format that Hakyll understands.
--
-- Returns the filename of the file that was written.
savePost :: FilePath -> T.Text -> T.Text -> DistilledPost -> IO FilePath
savePost odir oformat ext post = do
createDirectoryIfMissing True (takeDirectory fname)
B.writeFile fname . T.encodeUtf8 $
T.unlines
[ "---",
metadata "title" (formatTitle (dpTitle post)),
metadata "published" (formatDate (dpDate post)),
metadata "categories" (formatTags (dpCategories post)),
metadata "tags" (formatTags (dpTags post)),
"---",
"",
formatBody (dpBody post)
]
return fname
where
metadata k v = k <> ": " <> v
--
fname = odir </> postPath <.> (T.unpack ext)
postPath = T.unpack $ fromJust $ formatPath oformat post
--
formatTitle (Just t) = t
formatTitle Nothing =
"untitled (" <> T.unwords firstFewWords <> "β¦)"
where
firstFewWords = T.splitOn "-" . T.pack $ takeFileName postPath
formatDate = T.pack . formatTime defaultTimeLocale "%FT%TZ" --for hakyll
formatTags = T.intercalate ","
formatBody = id
|
kowey/hakyll-convert
|
src/Hakyll/Convert/IO.hs
|
bsd-3-clause
| 1,649
| 0
| 14
| 345
| 460
| 252
| 208
| 35
| 2
|
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
-- |
module Libtorrent.TorrentInfoSpec where
import Test.Hspec
import Libtorrent.Exceptions
import Libtorrent.TorrentInfo
spec :: Spec
spec = do
describe "Torrent info" $ do
it "read from nonexistent file" $
newTorrentInfo "aaa" `shouldThrow` (\case
TorrentInfoError _ -> True
_ -> False)
it "read from existent file" $
newTorrentInfo "test-data/debian-8.5.0-amd64-CD-1.iso.torrent" >>=
(`shouldSatisfy` const True)
|
eryx67/haskell-libtorrent
|
test/Libtorrent/TorrentInfoSpec.hs
|
bsd-3-clause
| 610
| 0
| 15
| 190
| 109
| 58
| 51
| 16
| 2
|
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE DeriveFoldable #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances #-}
module HSync.Common.FileVersion where
import Data.Aeson.TH
import ClassyPrelude.Yesod
import Control.Lens
import HSync.Common.Types
import Data.Semigroup
import HSync.Common.StorageTree(Measured(..))
import Data.SafeCopy
import HSync.Common.DateTime
import qualified Data.Text as T
import Text.Blaze(ToMarkup(..))
--------------------------------------------------------------------------------
newtype LastModificationTime = LastModificationTime { _unLMT :: Max DateTime }
deriving (Show,Read,Eq,Ord,Semigroup)
makeLenses ''LastModificationTime
instance SafeCopy LastModificationTime where
putCopy (LastModificationTime (Max u)) = contain $ safePut u
getCopy = contain $ LastModificationTime . Max <$> safeGet
instance ToMarkup LastModificationTime where
toMarkup = toMarkup . getMax . _unLMT
instance ToJSON LastModificationTime where
toJSON = toJSON . getMax . _unLMT
instance FromJSON LastModificationTime where
parseJSON = fmap (LastModificationTime . Max) . parseJSON
--------------------------------------------------------------------------------
data FileKind = Directory
| File Signature
| NonExistent
deriving (Show,Read,Eq)
makePrisms ''FileKind
$(deriveSafeCopy 0 'base ''FileKind)
$(deriveJSON defaultOptions ''FileKind)
instance PathPiece FileKind where
toPathPiece Directory = "Directory"
toPathPiece (File s) = "File_" <> toPathPiece s
toPathPiece NonExistent = "NonExistent"
fromPathPiece "Directory" = pure Directory
fromPathPiece "NonExistent" = pure NonExistent
fromPathPiece t = case splitAt 5 t of
("File_",t') -> File <$> fromPathPiece t'
_ -> Nothing
isFile :: FileKind -> Bool
isFile (File _) = True
isFile _ = False
isDirectory :: FileKind -> Bool
isDirectory Directory = True
isDirectory _ = False
exists :: FileKind -> Bool
exists NonExistent = False
exists _ = True
signature :: Traversal' FileKind Signature
signature = _File
--------------------------------------------------------------------------------
-- | Last modified information
data LastModified c = LastModified { _modificationTime :: DateTime
, _modUser :: UserId
, _modClient :: c
}
deriving (Show,Read,Eq,Functor,Foldable,Traversable)
makeLenses ''LastModified
$(deriveSafeCopy 0 'base ''LastModified)
$(deriveJSON defaultOptions ''LastModified)
instance Measured LastModificationTime (LastModified c) where
measure = LastModificationTime . Max . _modificationTime
--------------------------------------------------------------------------------
data FileVersion c = FileVersion { _fileKind :: FileKind
, _lastModified :: LastModified c
, _dataCommitted :: Bool -- ^ Whether or not the data
-- has successfully been
-- written on disk (in case)
-- this is a file
}
deriving (Show,Read,Eq,Functor,Foldable,Traversable)
makeLenses ''FileVersion
$(deriveSafeCopy 0 'base ''FileVersion)
$(deriveJSON defaultOptions ''FileVersion)
instance Measured LastModificationTime (FileVersion c) where
measure = measure . _lastModified
|
noinia/hsync-common
|
src/HSync/Common/FileVersion.hs
|
bsd-3-clause
| 3,744
| 0
| 10
| 1,002
| 783
| 419
| 364
| -1
| -1
|
{-# LANGUAGE QuasiQuotes #-}
import LiquidHaskell
import Data.Set
[lq| measure foo |]
[lq| measure foo1 |]
data F a = F a | E
foo1 :: F a -> Set a
foo1 (F x) = singleton x
foo1 E = empty
foo :: F Int -> Int
foo (F x) = x + 1
foo E = 0
-- bar = F
|
spinda/liquidhaskell
|
tests/gsoc15/unknown/pos/MeasureSets.hs
|
bsd-3-clause
| 266
| 2
| 10
| 82
| 125
| 62
| 63
| 12
| 1
|
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
module Mismi.Kernel.Data (
MismiRegion (..)
, renderMismiRegion
, parseMismiRegion
) where
import P
-- | Mismi's view of available AWS regions.
data MismiRegion =
IrelandRegion -- ^ Europe / eu-west-1
| FrankfurtRegion -- ^ Europe / eu-central-1
| TokyoRegion -- ^ Asia Pacific / ap-northeast-1
| SeoulRegion -- ^ Asia Pacific / ap-northeast-2
| SingaporeRegion -- ^ Asia Pacific / ap-southeast-1
| SydneyRegion -- ^ Asia Pacific / ap-southeast-2
| MumbaiRegion -- ^ Asia Pacific / ap-south-1
| MontrealRegion
| LondonRegion
| BeijingRegion -- ^ China / cn-north-1
| NorthVirginiaRegion -- ^ US / us-east-1
| OhioRegion -- ^ US / us-east-2
| NorthCaliforniaRegion -- ^ US / us-west-1
| OregonRegion -- ^ US / us-west-2
| GovCloudRegion -- ^ AWS GovCloud / us-gov-west-1
| GovCloudFIPSRegion -- ^ AWS GovCloud (FIPS 140-2) S3 Only / fips-us-gov-west-1
| SaoPauloRegion -- ^ South America / sa-east-1
deriving (Eq, Ord, Read, Show, Enum, Bounded)
renderMismiRegion :: MismiRegion -> Text
renderMismiRegion r =
case r of
IrelandRegion ->
"eu-west-1"
FrankfurtRegion ->
"eu-central-1"
TokyoRegion ->
"ap-northeast-1"
SeoulRegion ->
"ap-northeast-2"
SingaporeRegion ->
"ap-southeast-1"
SydneyRegion ->
"ap-southeast-2"
MumbaiRegion ->
"ap-south-1"
BeijingRegion ->
"cn-north-1"
NorthVirginiaRegion ->
"us-east-1"
OhioRegion ->
"us-east-2"
NorthCaliforniaRegion ->
"us-west-1"
OregonRegion ->
"us-west-2"
GovCloudRegion ->
"us-gov-west-1"
GovCloudFIPSRegion ->
"fips-us-gov-west-1"
SaoPauloRegion ->
"sa-east-1"
MontrealRegion ->
"ca-central-1"
LondonRegion ->
"eu-west-2"
parseMismiRegion :: Text -> Maybe MismiRegion
parseMismiRegion t =
case t of
"eu-west-1" ->
Just IrelandRegion
"eu-central-1" ->
Just FrankfurtRegion
"ap-northeast-1" ->
Just TokyoRegion
"ap-northeast-2" ->
Just SeoulRegion
"ap-southeast-1" ->
Just SingaporeRegion
"ap-southeast-2" ->
Just SydneyRegion
"ap-south-1" ->
Just MumbaiRegion
"cn-north-1" ->
Just BeijingRegion
"us-east-1" ->
Just NorthVirginiaRegion
"us-east-2" ->
Just OhioRegion
"us-west-2" ->
Just OregonRegion
"us-west-1" ->
Just NorthCaliforniaRegion
"us-gov-west-1" ->
Just GovCloudRegion
"fips-us-gov-west-1" ->
Just GovCloudFIPSRegion
"sa-east-1" ->
Just SaoPauloRegion
"eu-west-2" ->
Just LondonRegion
"ca-central-1" ->
Just MontrealRegion
_ ->
Nothing
|
ambiata/mismi
|
mismi-kernel/src/Mismi/Kernel/Data.hs
|
bsd-3-clause
| 2,888
| 0
| 8
| 831
| 431
| 230
| 201
| 102
| 18
|
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree.
{-# LANGUAGE OverloadedStrings #-}
module Duckling.Temperature.MN.Corpus
( corpus
) where
import Prelude
import Data.String
import Duckling.Locale
import Duckling.Resolve
import Duckling.Temperature.Types
import Duckling.Testing.Types
corpus :: Corpus
corpus = (testContext {locale = makeLocale MN Nothing}, testOptions, allExamples)
allExamples :: [Example]
allExamples = concat
[ examples (simple Celsius 37)
[ "37Β°C"
]
, examples (simple Fahrenheit 70)
[ "70Β°F"
]
, examples (simple Degree 45)
[ "45Β°"
, "45 Ρ
ΡΠΌ"
]
, examples (simple Degree (-2))
[ "-2Β°"
, "- 2 Ρ
ΡΠΌ"
]
]
|
facebookincubator/duckling
|
Duckling/Temperature/MN/Corpus.hs
|
bsd-3-clause
| 942
| 0
| 11
| 269
| 184
| 109
| 75
| 23
| 1
|
module TTT.Game where
import Data.List
import Data.List.Split
import Data.Maybe
data Piece = X | O
deriving (Eq)
data Position = Position {px :: Int, py :: Int}
deriving (Show, Eq)
type Board = [(Maybe Piece, Position)]
data GameState = GameState {board :: Board, whoseTurn :: Piece}
data Result = Win | Lose | Tie
deriving (Eq)
instance Show Piece where
show p = showPiece (Just p)
instance Show Result where
show r
| r == Win = "You won! :)"
| r == Lose = "You lost! :("
| otherwise = "Tie -.-"
------------------------
-- Display game board --
------------------------
showBoard :: Board -> String
showBoard b = "\nGame board:\n" ++ boardDisplay where
boardDisplay = simpleBoard ++ hack
simpleBoard =
intercalate divider $
map (intercalate "|") $
chunksOf boardDim $
map (\(p,pos) -> " " ++ (showPiece p) ++ " ") b
hack = showDivider boardDim " "
divider = showDivider boardDim "_____"
boardDim = getBoardDim b
showPiece :: Maybe Piece -> String
showPiece p
| p == Just X = "X"
| p == Just O = "O"
| otherwise = "*"
showDivider :: Int -> String -> String
showDivider boardDim spaces = ("\n" ++ divider ++ "\n") where
divider =
intercalate "|" $
replicate boardDim spaces
showPlayerResult :: Piece -> Result -> String
showPlayerResult p r = "Player '" ++ show p ++ "'' " ++ show r
------------------
-- Constructors --
------------------
initBoard :: Int -> Board
initBoard dim = do
xs <- take dim [0..]
ys <- take dim [0..]
return $ (Nothing, Position {px=xs, py=ys})
initGameState :: Board -> Piece -> GameState
initGameState b p =
GameState {board=b, whoseTurn=p}
----------------
-- Game rules --
----------------
opposite :: Piece -> Piece
opposite p
| p == X = O
| p == O = X
whoseTurnNext :: GameState -> Piece
whoseTurnNext s = opposite (whoseTurn s)
isLegalMove :: GameState -> Position -> Piece -> Bool
isLegalMove s nextPos nextPiece = legalPosition && legalMove where
legalPosition = nextPos `elem` posibleMoves
legalMove = nextPiece == (whoseTurn s)
posibleMoves = findPositions b isEmpty
b = (board s)
hasItTied :: GameState -> Bool
hasItTied s = do
let b = (board s)
getBoardSize b == length (findPositions b isFilled)
hasItWon :: GameState -> Position -> Piece -> Bool
hasItWon s (Position x y) p = row || col || diag where
b = (board s)
bDim = getBoardDim b
row = length (filter (\(piece,pos) -> piece == Just p && (py pos) == y) b) == bDim
col = length (filter (\(piece,pos) -> piece == Just p && (px pos) == x) b) == bDim
diag = diag' m || diag' (reverse m) where
diag' xs = all (\(piece,pos) -> piece == Just p) $ diagonal xs
m = matrix bDim b
matrix :: Int -> [a] -> [[a]]
matrix n [] = []
matrix n xs = take n xs : matrix n (drop n xs)
diagonal :: [[a]] -> [a]
diagonal x = zipWith (!!) x [0..]
------------------------
-- Game board queries --
-----------------------
getBoardSize :: Board -> Int
getBoardSize b = length b
getBoardDim :: Board -> Int
getBoardDim b = round ((sqrt :: Double -> Double) (fromIntegral (getBoardSize b)))
indexToPosition :: Board -> Int -> Position
indexToPosition b index = do
let bDim = getBoardDim b
Position {px=(index `div` bDim), py=(index `rem` bDim)}
isEmpty :: (Maybe Piece, Position) -> Bool
isEmpty (p, pos) = isNothing p
isFilled :: (Maybe Piece, Position) -> Bool
isFilled (p, pos) = isNothing p == False
findPositions :: Board -> ((Maybe Piece, Position) -> Bool) -> [Position]
findPositions b satisfiable =
map (\index -> indexToPosition b index) $
findIndices (satisfiable) b
newBoard :: Board -> Position -> Piece -> Board
newBoard b pos p = do
--hack
let (xs,_:ys) = splitAt (fromMaybe 0 (elemIndex (Nothing, pos) b)) b
xs ++ (Just p, pos):ys
getNextState :: GameState -> Position -> Piece -> Maybe GameState
getNextState s nextPos nextPiece = do
if isLegalMove s nextPos nextPiece
then Just GameState {
board = newBoard (board s) nextPos nextPiece,
whoseTurn = whoseTurnNext s }
else Nothing
|
cjw-charleswu/Wizard
|
TicTacToe/src/TTT/Game.hs
|
bsd-3-clause
| 4,098
| 0
| 16
| 914
| 1,620
| 851
| 769
| 107
| 2
|
{-# LANGUAGE OverloadedStrings #-}
module Hack2.Interface.Wai
(
hackAppToWaiApp
) where
import Control.Monad.IO.Class (liftIO)
import Data.ByteString.Char8 (ByteString, pack)
import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString.Lazy.Char8 as Lazy
import qualified Data.CaseInsensitive as CaseInsensitive
import Data.Char (toUpper)
import Data.Default (def, Default)
import Data.Maybe (fromMaybe)
import Hack2
import qualified Network.HTTP.Types as HTTPTypes
import qualified Network.Wai as Wai
import Prelude hiding ((-), (.))
import qualified Safe as Safe
{-
{ requestMethod :: RequestMethod
, scriptName :: ByteString
, pathInfo :: ByteString
, queryString :: ByteString
, serverName :: ByteString
, serverPort :: Int
, httpHeaders :: [(ByteString, ByteString)]
, hackVersion :: (Int, Int, Int)
, hackUrlScheme :: HackUrlScheme
, hackInput :: HackEnumerator
, hackErrors :: HackErrors
, hackHeaders :: [(ByteString, ByteString)]
-}
infixr 0 -
{-# INLINE (-) #-}
(-) :: (a -> b) -> a -> b
f - x = f x
infixl 9 .
{-# INLINE (.) #-}
(.) :: a -> (a -> b) -> b
a . f = f a
requestToEnv :: Wai.Request -> IO Env
requestToEnv request = do
requestBody <- request.Wai.strictRequestBody
let
(serverName:serverPort:_) = request.Wai.remoteHost.show.B.pack.B.split ':' ++ [mempty, mempty]
return -
def
{
requestMethod = request.Wai.requestMethod.show.map toUpper.Safe.readDef GET
, pathInfo = request.Wai.rawPathInfo
, queryString = request.Wai.rawQueryString.B.dropWhile (== '?')
, serverName = serverName
, serverPort = Safe.readMay (show serverPort).fromMaybe 0
, httpHeaders = request.Wai.requestHeaders.map caseInsensitiveHeaderToHeader
, hackUrlScheme = if request.Wai.isSecure then HTTPS else HTTP
, hackHeaders = [("RemoteHost", request.Wai.remoteHost.show.pack)]
, hackInput = Lazy.toStrict requestBody
}
caseInsensitiveHeaderToHeader :: (CaseInsensitive.CI ByteString, ByteString) -> (ByteString, ByteString)
caseInsensitiveHeaderToHeader (x, y) = (x.CaseInsensitive.original, y)
headerToCaseInsensitiveHeader :: (ByteString, ByteString) -> (CaseInsensitive.CI ByteString, ByteString)
headerToCaseInsensitiveHeader (x, y) = (x.CaseInsensitive.mk, y)
statusToStatusHeader :: Int -> HTTPTypes.Status
statusToStatusHeader 200 = HTTPTypes.status200
statusToStatusHeader 201 = HTTPTypes.status201
statusToStatusHeader 206 = HTTPTypes.status206
statusToStatusHeader 301 = HTTPTypes.status301
statusToStatusHeader 302 = HTTPTypes.status302
statusToStatusHeader 303 = HTTPTypes.status303
statusToStatusHeader 304 = HTTPTypes.status304
statusToStatusHeader 400 = HTTPTypes.status400
statusToStatusHeader 401 = HTTPTypes.status401
statusToStatusHeader 403 = HTTPTypes.status403
statusToStatusHeader 404 = HTTPTypes.status404
statusToStatusHeader 405 = HTTPTypes.status405
statusToStatusHeader 412 = HTTPTypes.status412
statusToStatusHeader 416 = HTTPTypes.status416
statusToStatusHeader 500 = HTTPTypes.status500
statusToStatusHeader 501 = HTTPTypes.status501
statusToStatusHeader 502 = HTTPTypes.status502
statusToStatusHeader 503 = HTTPTypes.status503
statusToStatusHeader 504 = HTTPTypes.status504
statusToStatusHeader 505 = HTTPTypes.status505
statusToStatusHeader _ = HTTPTypes.status505
hackAppToWaiApp :: Application -> Wai.Application
hackAppToWaiApp app request respond = do
response <- liftIO - app =<< requestToEnv request
let wai_response = hackResponseToWaiResponse response
respond wai_response
hackResponseToWaiResponse :: Response -> Wai.Response
hackResponseToWaiResponse response =
let s = response.status.statusToStatusHeader
h = response.headers.map headerToCaseInsensitiveHeader
b = Lazy.fromChunks [response.body]
in
Wai.responseLBS s h b
|
nfjinjing/hack2-interface-wai
|
src/Hack2/Interface/Wai.hs
|
bsd-3-clause
| 3,954
| 14
| 15
| 686
| 934
| 519
| 415
| 78
| 2
|
{-# LANGUAGE FlexibleContexts, FlexibleInstances, MultiParamTypeClasses #-}
{-# LANGUAGE TypeFamilies #-}
module Opaleye.Internal.Join where
import qualified Opaleye.Internal.HaskellDB.PrimQuery as HPQ
import qualified Opaleye.Internal.PackMap as PM
import qualified Opaleye.Internal.Tag as T
import qualified Opaleye.Internal.Unpackspec as U
import Opaleye.Internal.Column (Column(Column), Nullable)
import qualified Opaleye.Internal.QueryArr as Q
import qualified Opaleye.Internal.PrimQuery as PQ
import qualified Opaleye.PGTypes as T
import qualified Opaleye.Column as C
import qualified Opaleye.Map as Map
import qualified Opaleye.Internal.TypeFamilies as TF
import qualified Control.Applicative as A
import Data.Profunctor (Profunctor, dimap)
import qualified Data.Profunctor.Product as PP
import qualified Data.Profunctor.Product.Default as D
newtype NullMaker a b = NullMaker (a -> b)
toNullable :: NullMaker a b -> a -> b
toNullable (NullMaker f) = f
instance D.Default NullMaker (Column a) (Column (Nullable a)) where
def = NullMaker C.toNullable
instance D.Default NullMaker (Column (Nullable a)) (Column (Nullable a)) where
def = NullMaker id
joinExplicit :: U.Unpackspec columnsA columnsA
-> U.Unpackspec columnsB columnsB
-> (columnsA -> returnedColumnsA)
-> (columnsB -> returnedColumnsB)
-> PQ.JoinType
-> Q.Query columnsA -> Q.Query columnsB
-> ((columnsA, columnsB) -> Column T.PGBool)
-> Q.Query (returnedColumnsA, returnedColumnsB)
joinExplicit uA uB returnColumnsA returnColumnsB joinType
qA qB cond = Q.simpleQueryArr q where
q ((), startTag) = ((nullableColumnsA, nullableColumnsB), primQueryR, T.next endTag)
where (columnsA, primQueryA, midTag) = Q.runSimpleQueryArr qA ((), startTag)
(columnsB, primQueryB, endTag) = Q.runSimpleQueryArr qB ((), midTag)
(newColumnsA, ljPEsA) =
PM.run (U.runUnpackspec uA (extractLeftJoinFields 1 endTag) columnsA)
(newColumnsB, ljPEsB) =
PM.run (U.runUnpackspec uB (extractLeftJoinFields 2 endTag) columnsB)
nullableColumnsA = returnColumnsA newColumnsA
nullableColumnsB = returnColumnsB newColumnsB
Column cond' = cond (columnsA, columnsB)
primQueryR = PQ.Join joinType cond' ljPEsA ljPEsB primQueryA primQueryB
leftJoinAExplicit :: U.Unpackspec a a
-> NullMaker a nullableA
-> Q.Query a
-> Q.QueryArr (a -> Column T.PGBool) nullableA
leftJoinAExplicit uA nullmaker rq =
Q.QueryArr $ \(p, primQueryL, t1) ->
let (columnsR, primQueryR, t2) = Q.runSimpleQueryArr rq ((), t1)
(newColumnsR, ljPEsR) = PM.run $ U.runUnpackspec uA (extractLeftJoinFields 2 t2) columnsR
renamedNullable = toNullable nullmaker newColumnsR
Column cond = p newColumnsR
in ( renamedNullable
, PQ.Join
PQ.LeftJoin
cond
[]
--- ^ I am reasonably confident that we don't need any
--- column names here. Columns that can become NULL need
--- to be written here so that we can wrap them. If we
--- don't constant columns can avoid becoming NULL.
--- However, these are the left columns and cannot become
--- NULL in a left join, so we are fine.
---
--- Report about the "avoiding NULL" bug:
---
--- https://github.com/tomjaguarpaw/haskell-opaleye/issues/223
ljPEsR
primQueryL
primQueryR
, T.next t2)
extractLeftJoinFields :: Int
-> T.Tag
-> HPQ.PrimExpr
-> PM.PM [(HPQ.Symbol, HPQ.PrimExpr)] HPQ.PrimExpr
extractLeftJoinFields n = PM.extractAttr ("result" ++ show n ++ "_")
-- { Boilerplate instances
instance Functor (NullMaker a) where
fmap f (NullMaker g) = NullMaker (fmap f g)
instance A.Applicative (NullMaker a) where
pure = NullMaker . A.pure
NullMaker f <*> NullMaker x = NullMaker (f A.<*> x)
instance Profunctor NullMaker where
dimap f g (NullMaker h) = NullMaker (dimap f g h)
instance PP.ProductProfunctor NullMaker where
empty = PP.defaultEmpty
(***!) = PP.defaultProfunctorProduct
--
data Nulled
type instance TF.IMap Nulled TF.OT = TF.NullsT
type instance TF.IMap Nulled TF.NullsT = TF.NullsT
-- It's quite unfortunate that we have to write these out by hand
-- until we probably do nullability as a distinction between
--
-- Column (Nullable a)
-- Column (NonNullable a)
type instance Map.Map Nulled (Column (Nullable a)) = Column (Nullable a)
type instance Map.Map Nulled (Column T.PGInt4) = Column (Nullable T.PGInt4)
type instance Map.Map Nulled (Column T.PGInt8) = Column (Nullable T.PGInt8)
type instance Map.Map Nulled (Column T.PGText) = Column (Nullable T.PGText)
type instance Map.Map Nulled (Column T.PGFloat8) = Column (Nullable T.PGFloat8)
type instance Map.Map Nulled (Column T.PGBool) = Column (Nullable T.PGBool)
type instance Map.Map Nulled (Column T.PGUuid) = Column (Nullable T.PGUuid)
type instance Map.Map Nulled (Column T.PGBytea) = Column (Nullable T.PGBytea)
type instance Map.Map Nulled (Column T.PGText) = Column (Nullable T.PGText)
type instance Map.Map Nulled (Column T.PGDate) = Column (Nullable T.PGDate)
type instance Map.Map Nulled (Column T.PGTimestamp) = Column (Nullable T.PGTimestamp)
type instance Map.Map Nulled (Column T.PGTimestamptz) = Column (Nullable T.PGTimestamptz)
type instance Map.Map Nulled (Column T.PGTime) = Column (Nullable T.PGTime)
type instance Map.Map Nulled (Column T.PGCitext) = Column (Nullable T.PGCitext)
type instance Map.Map Nulled (Column T.PGJson) = Column (Nullable T.PGJson)
type instance Map.Map Nulled (Column T.PGJsonb) = Column (Nullable T.PGJsonb)
|
WraithM/haskell-opaleye
|
src/Opaleye/Internal/Join.hs
|
bsd-3-clause
| 5,923
| 0
| 16
| 1,356
| 1,682
| 912
| 770
| -1
| -1
|
import Control.Exception
import Control.Monad
import Test.HUnit
import Board.Vector
import Board.List
import SudokuAbstract
import SimpleSolve
import Square.Simple
import Value.Integer
import Data.Maybe
import Data.Char
import ProjectEuler
import Test.QuickCheck
-- Helper function
boardToMaybeValList :: (SudokuBoard b, SudokuSquare s, SudokuValue v) => b (s v) -> [v]
boardToMaybeValList board = concat $ map (getRow board) [ i | i <-[0..8] ]
-- |Test for solving algorithm - does it work correct?
testSolving :: Test
testSolving = TestCase $ assertEqual "Incorrect solution" vb1 vb2
where
solved = "483921657967345821251876493548132976729564138136798245372689514814253769695417382"
notSolved = "003020600900305001001806400008102900700000008006708200002609500800203009005010300"
readBoard' string = (fromJust $ readBoard string) :: ListBoard (SimpleSquare IntegerValue)
b1 = readBoard' solved
b2 = readBoard' notSolved
vb1 = boardToMaybeValList b1
vb2 = boardToMaybeValList $ fromJust $ solve b2
-- |Test for ProjectEuler algorithm - does it work properly?
testProjectEuler :: Test
testProjectEuler = TestCase $ assertEqual "Wrong answer" (483+483) answer
where
solved = "483921657967345821251876493548132976729564138136798245372689514814253769695417382"
readBoard' string = (fromJust $ readBoard string) :: ListBoard (SimpleSquare IntegerValue)
board = readBoard' solved
answer = projectEuler96 [Just board, Just board]
-- |Test for reader, it should allow creating invalid sudoku (repeating values)
testReader :: Test
testReader = TestCase $ assertEqual "Parsing invalid sudoku" True (isNothing board)
where
wrongInput = "303020600900305001001806400008102900700000008006708200002609500800203009005010300"
board = readBoard wrongInput :: Maybe( ListBoard (SimpleSquare IntegerValue) )
newtype List9 = List9 [Char] deriving (Eq, Show)
instance Arbitrary List9 where
arbitrary = do
list <- shuffle ['1'..'9']
return (List9 list)
-- |Test for ListBoard, check if it returns the right row values
testListRow :: List9 -> Bool
testListRow (List9 list) = all id $ allElements
where
input = list ++ (take 72 $ repeat '0')
board = (fromJust $ readBoard input) :: ListBoard (SimpleSquare IntegerValue)
intList = map digitToInt list
values = map fromInt intList
row = getRow board 0
allElements = map (`elem` row) values
-- |Test for VectorBoard, check if it returns the right row values
testVectorRow :: List9 -> Bool
testVectorRow (List9 list) = all id $ allElements
where
input = list ++ (take 72 $ repeat '0')
board = (fromJust $ readBoard input) :: VectorBoard (SimpleSquare IntegerValue)
intList = map digitToInt list
values = map fromInt intList
row = getRow board 0
allElements = map (`elem` row) values
-- |Test for VectorBoard, check if it returns the right column values
testVectorColumn :: List9 -> Bool
testVectorColumn (List9 list) = all id $ allElements
where
input = concat $ map (:"00000000") list
board = (fromJust $ readBoard input) :: VectorBoard (SimpleSquare IntegerValue)
intList = map digitToInt list
values = map fromInt intList
column = getColumn board 0
allElements = map (`elem` column) values
main = do
putStrLn "QuickCheck"
quickCheckResult testListRow
quickCheckResult testVectorRow
quickCheckResult testVectorColumn
putStrLn "HUnit"
runTestTT $ TestList [testSolving, testProjectEuler, testReader]
|
Solpatium/Haskell-Sudoku
|
test/Spec.hs
|
bsd-3-clause
| 4,270
| 0
| 11
| 1,390
| 897
| 469
| 428
| 70
| 1
|
{- This module provides type-level finite maps.
The implementation is similar to that shown in the paper.
"Embedding effect systems in Haskell" Orchard, Petricek 2014 -}
{-# LANGUAGE TypeOperators, PolyKinds, DataKinds, KindSignatures,
TypeFamilies, UndecidableInstances, MultiParamTypeClasses,
FlexibleInstances, GADTs, FlexibleContexts, ScopedTypeVariables,
ConstraintKinds #-}
{-# LANGUAGE TypeInType #-}
{-# OPTIONS_GHC -Wno-unticked-promoted-constructors #-}
module Data.Type.Map (Mapping(..), Union, Unionable, union, Var(..), Map(..),
Combine, Combinable(..), Cmp,
Nubable, nub,
Lookup, Member, (:\), Split, split,
IsMap, AsMap, asMap,
Submap, submap) where
import GHC.TypeLits hiding (type (*))
import Data.Kind (type (*))
import Data.Type.Bool
import Data.Type.Equality
import Data.Type.Set (Cmp, Proxy(..), Flag(..), Sort, Filter, (:++))
{- Throughout, type variables
'k' ranges over "keys"
'v' ranges over "values"
'kvp' ranges over "key-value-pairs"
'm', 'n' range over "maps" -}
-- Mappings
infixr 4 :->
{-| A key-value pair -}
data Mapping k v = k :-> v
{-| Union of two finite maps -}
type Union m n = Nub (Sort (m :++ n))
{-| Apply 'Combine' to values with matching key (removes duplicate keys) -}
type family Nub t where
Nub '[] = '[]
Nub '[kvp] = '[kvp]
Nub ((k :-> v1) ': (k :-> v2) ': m) = Nub ((k :-> Combine v1 v2) ': m)
Nub (kvp1 ': kvp2 ': s) = kvp1 ': Nub (kvp2 ': s)
{-| Open type family for combining values in a map (that have the same key) -}
type family Combine (a :: v) (b :: v) :: v
{-| Delete elements from a map by key -}
type family (m :: [Mapping k v]) :\ (c :: k) :: [Mapping k v] where
'[] :\ k = '[]
((k :-> v) ': m) :\ k = m :\ k
(kvp ': m) :\ k = kvp ': (m :\ k)
{-| Lookup elements from a map -}
type family Lookup (m :: [Mapping k v]) (c :: k) :: Maybe v where
Lookup '[] k = Nothing
Lookup ((k :-> v) ': m) k = Just v
Lookup (kvp ': m) k = Lookup m k
{-| Membership test -}
type family Member (c :: k) (m :: [Mapping k v]) :: Bool where
Member k '[] = False
Member k ((k :-> v) ': m) = True
Member k (kvp ': m) = Member k m
-----------------------------------------------------------------
-- Value-level map with a type-level representation
{-| Pair a symbol (representing a variable) with a type -}
data Var (k :: Symbol) = Var
instance KnownSymbol k => Show (Var k) where
show = symbolVal
{-| A value-level heterogenously-typed Map (with type-level representation in terms of lists) -}
data Map (n :: [Mapping Symbol *]) where
Empty :: Map '[]
Ext :: Var k -> v -> Map m -> Map ((k :-> v) ': m)
{-| Predicate to check if in normalised map form -}
type IsMap s = (s ~ Nub (Sort s))
{-| At the type level, normalise the list form to the map form -}
type AsMap s = Nub (Sort s)
{-| At the value level, noramlise the list form to the map form -}
asMap :: (Sortable s, Nubable (Sort s)) => Map s -> Map (AsMap s)
asMap x = nub (quicksort x)
instance Show (Map '[]) where
show Empty = "{}"
instance (KnownSymbol k, Show v, Show' (Map s)) => Show (Map ((k :-> v) ': s)) where
show (Ext k v s) = "{" ++ show k ++ " :-> " ++ show v ++ (show' s) ++ "}"
class Show' t where
show' :: t -> String
instance Show' (Map '[]) where
show' Empty = ""
instance (KnownSymbol k, Show v, Show' (Map s)) => Show' (Map ((k :-> v) ': s)) where
show' (Ext k v s) = ", " ++ show k ++ " :-> " ++ show v ++ (show' s)
instance Eq (Map '[]) where
Empty == Empty = True
instance (KnownSymbol k, Eq (Var k), Eq v, Eq (Map s)) => Eq (Map ((k :-> v) ': s)) where
(Ext k v m) == (Ext k' v' m') = k == k' && v == v' && m == m'
{-| Union of two finite maps -}
union :: (Unionable s t) => Map s -> Map t -> Map (Union s t)
union s t = nub (quicksort (append s t))
type Unionable s t = (Nubable (Sort (s :++ t)), Sortable (s :++ t))
append :: Map s -> Map t -> Map (s :++ t)
append Empty x = x
append (Ext k v xs) ys = Ext k v (append xs ys)
type instance Cmp (k :: Symbol) (k' :: Symbol) = CmpSymbol k k'
type instance Cmp (k :-> v) (k' :-> v') = CmpSymbol k k'
{-| Value-level quick sort that respects the type-level ordering -}
class Sortable xs where
quicksort :: Map xs -> Map (Sort xs)
instance Sortable '[] where
quicksort Empty = Empty
instance (Sortable (Filter FMin (k :-> v) xs),
Sortable (Filter FMax (k :-> v) xs), FilterV FMin k v xs, FilterV FMax k v xs) => Sortable ((k :-> v) ': xs) where
quicksort (Ext k v xs) = ((quicksort (less k v xs)) `append` (Ext k v Empty)) `append` (quicksort (more k v xs))
where less = filterV (Proxy::(Proxy FMin))
more = filterV (Proxy::(Proxy FMax))
{- Filter out the elements less-than or greater-than-or-equal to the pivot -}
class FilterV (f::Flag) k v xs where
filterV :: Proxy f -> Var k -> v -> Map xs -> Map (Filter f (k :-> v) xs)
instance FilterV f k v '[] where
filterV _ k v Empty = Empty
instance (Conder ((Cmp x (k :-> v)) == LT), FilterV FMin k v xs) => FilterV FMin k v (x ': xs) where
filterV f@Proxy k v (Ext k' v' xs) = cond (Proxy::(Proxy ((Cmp x (k :-> v)) == LT)))
(Ext k' v' (filterV f k v xs)) (filterV f k v xs)
instance (Conder (((Cmp x (k :-> v)) == GT) || ((Cmp x (k :-> v)) == EQ)), FilterV FMax k v xs) => FilterV FMax k v (x ': xs) where
filterV f@Proxy k v (Ext k' v' xs) = cond (Proxy::(Proxy (((Cmp x (k :-> v)) == GT) || ((Cmp x (k :-> v)) == EQ))))
(Ext k' v' (filterV f k v xs)) (filterV f k v xs)
class Combinable t t' where
combine :: t -> t' -> Combine t t'
class Nubable t where
nub :: Map t -> Map (Nub t)
instance Nubable '[] where
nub Empty = Empty
instance Nubable '[e] where
nub (Ext k v Empty) = Ext k v Empty
instance {-# OVERLAPPABLE #-}
(Nub (e ': f ': s) ~ (e ': Nub (f ': s)),
Nubable (f ': s)) => Nubable (e ': f ': s) where
nub (Ext k v (Ext k' v' s)) = Ext k v (nub (Ext k' v' s))
instance {-# OVERLAPS #-}
(Combinable v v', Nubable ((k :-> Combine v v') ': s)) => Nubable ((k :-> v) ': (k :-> v') ': s) where
nub (Ext k v (Ext k' v' s)) = nub (Ext k (combine v v') s)
class Conder g where
cond :: Proxy g -> Map s -> Map t -> Map (If g s t)
instance Conder True where
cond _ s t = s
instance Conder False where
cond _ s t = t
{-| Splitting a union of maps, given the maps we want to split it into -}
class Split s t st where
-- where st ~ Union s t
split :: Map st -> (Map s, Map t)
instance Split '[] '[] '[] where
split Empty = (Empty, Empty)
instance {-# OVERLAPPABLE #-} Split s t st => Split (x ': s) (x ': t) (x ': st) where
split (Ext k v st) = let (s, t) = split st
in (Ext k v s, Ext k v t)
instance {-# OVERLAPS #-} Split s t st => Split (x ': s) t (x ': st) where
split (Ext k v st) = let (s, t) = split st
in (Ext k v s, t)
instance {-# OVERLAPS #-} (Split s t st) => Split s (x ': t) (x ': st) where
split (Ext k v st) = let (s, t) = split st
in (s, Ext k v t)
{-| Construct a submap 's' from a supermap 't' -}
class Submap s t where
submap :: Map t -> Map s
instance Submap '[] '[] where
submap xs = Empty
instance {-# OVERLAPPABLE #-} Submap s t => Submap s (x ': t) where
submap (Ext _ _ xs) = submap xs
instance {-# OVERLAPS #-} Submap s t => Submap (x ': s) (x ': t) where
submap (Ext k v xs) = Ext k v (submap xs)
|
AaronFriel/eff-experiments
|
src/Data/Type/Map.hs
|
bsd-3-clause
| 7,879
| 2
| 17
| 2,311
| 3,374
| 1,794
| 1,580
| -1
| -1
|
module Main where
import qualified Data.List as Lst
import Language.CCS.Data
import Language.CCS.Parser
import Language.CCS.Printer
import System.Environment(getArgs)
import Text.Parsec
import Test.QuickCheck
import Test.Framework as TF (defaultMain, testGroup, Test)
import Test.Framework.Providers.HUnit
import Test.Framework.Providers.QuickCheck2 (testProperty)
import qualified Data.HashSet as HS
import qualified Data.HashMap.Strict as HM
small :: Gen Char
small = choose ('a','z')
capital :: Gen Char
capital = choose ('A','Z')
digits :: Gen Char
digits = choose ('0','9')
genhspace :: Gen String
genhspace = listOf1 (elements [' ','\t'])
genvspace :: Gen String
genvspace = do
n <- listOf1 (elements ["\n", "\r\n"])
return $ concat n
genspace = oneof [genhspace, genvspace]
gencomma = do
l <- genspace
return $ ',' : l
gensym c = do
l <- genspace
return $ c : l
genCurlyOpen = gensym '{'
genCurlyClose = gensym '}'
genequals = elements [":", "="]
genLib :: Gen CLib
genLib = do
f <- small
rest <- listOf $ oneof [small, capital, digits , elements ['-','.']]
return . CLib $ (f:rest)
genHdr :: Gen CInclude
genHdr = do
f <- small
rest <- listOf $ oneof [small, capital, digits, elements ['-','/','.']]
return . CInclude $ (f:rest)
gParse :: (a -> Bool) -> String -> Parser a -> String -> Gen Bool
gParse eqcheck sourceName parser text = case runParser parser (HS.empty) sourceName text of
Left err -> return False
Right i -> return $ eqcheck i
gptest :: (Show a) => Gen String -> Parsec String u a -> u -> IO ()
gptest g p u = do
txt <- generate g
putStrLn txt
case runParser p u "gptest" txt of
Left err -> print err
Right a -> putStrLn (show a)
libText :: CLib -> Gen String
libText (CLib txt) = return $ "\"" ++ txt ++ "\""
hdrText :: CInclude -> Gen String
hdrText (CInclude str) = return $ "<" ++ str ++ ">"
hdrTexts = combElems hdrText gencomma
combElems2 :: (a -> Gen String) ->[a] -> Gen String
combElems2 _ [] = return ""
combElems2 f (h:rest)= do
t <- f h
rem <- combElems2 f rest
return $ t ++ rem
combElems :: (a -> Gen String) -> Gen String ->[a] -> Gen String
combElems _ _ [] = return ""
combElems f sep (h:rest)= do
t <- f h
s <- genspace
c <- gencomma
case rest of
[] -> return $ t ++ s
_ -> do
rem <- combElems f sep rest
return $ t ++ s ++ c ++ rem
headerSecTxt :: [CInclude] -> Gen String
headerSecTxt incs = do
s1 <- genspace
e <- genequals
ghs <-hdrTexts incs
return $ "headers" ++ s1 ++ e ++ ghs
libSectionText :: CLib -> Gen String
libSectionText lib = do
l <- libText lib
e <- genequals
s1 <- genspace
s2 <- genspace
s3 <- genspace
return $ "library" ++ s1 ++ e ++ s2 ++ l ++ s3
dependencySecTxt :: Gen String
dependencySecTxt = do
s1 <- genspace
e <- genequals
o <- genCurlyOpen
c <- genCurlyClose
libs <- listOf genLib
txt <- combElems libText gencomma libs
return $ "dependencies" ++ e ++ o ++ txt ++ c
asisText :: Gen String
asisText = vectorOf 100 $ suchThat (choose (' ','z')) onlyAllowed
where onlyAllowed c = not $ elem c "{}#$"
verbatimText :: Gen CSVal
verbatimText = do
t <- listOf (choose ('%','~'))
return $ CSVerbatim t
genCId :: Gen String
genCId = do
l <- small
rest <- listOf $ oneof [small, capital, digits , elements ['_']]
return $ l:rest
genTypeName :: Gen String
genTypeName = do
l <- listOf1 genCId
return . Lst.concat $ Lst.intersperse "." l
genHashDef :: Gen CSVal
genHashDef = do
c <- genCId
return $ CHashDef c
genHashChar :: Gen CSVal
genHashChar = return CDblHash
genHashAlign :: Gen CSVal
genHashAlign = do
s <- genCId
c <- genCId
return $ CFieldOffset s c
genSizeof :: Gen CSVal
genSizeof = do
s <- genCId
return $ CSizeOf s
genEpiFrag = oneof [verbatimText, genHashDef, genHashChar, genHashAlign, genSizeof]
prop_validEpilog = do
frags <- listOf genEpiFrag
txt <- combElems2 csVerbToStr frags
gParse (\x -> True) "prop_validEpilog" epilogue txt
prop_parseLib :: Gen Bool
prop_parseLib = do
l <- genLib
txt <- libSectionText l
gParse (== l) "prop_parseLib " libSection txt
prop_parseHeader :: Gen Bool
prop_parseHeader = do
hdrs <- listOf1 genHdr
txt <- headerSecTxt hdrs
gParse (== hdrs) "prop_parseHeader" headers txt
prop_parseDependencySec :: Gen Bool
prop_parseDependencySec = do
txt <- dependencySecTxt
gParse (\x -> True) "prop_parseDependencySec" extraLibs txt
csVerbToStr :: CSVal -> Gen String
csVerbToStr (CSVerbatim str) = return str
csVerbToStr (CHashDef str) = return str
csVerbToStr (CDblHash ) = return "##"
csVerbToStr (CSizeOf s) = do
s1 <- gensym '('
s2 <- gensym ')'
return $ "#$sizeof" ++ s1 ++ s ++ s2
csVerbToStr (CFieldOffset str f) = do
s1 <- gensym '('
s2 <- gensym ')'
junk <- genspace
return $ "#$offset" ++ s1 ++ str ++ junk ++ f ++ s2
enumValToStr :: EnumValue -> Gen String
enumValToStr EmptyEnum = return ""
enumValToStr (FromMacro s) = return $ '#' : s
enumValToStr (EnumSize s) = do {s1 <- gensym '('; s2 <- gensym ')'; return $ "#$sizeof" ++ s1 ++ s ++ s2}
enumValToStr (EnumOffset s f) = do {s1 <- gensym '('; s2 <- gensym ')'; c <- gensym ','; return $ "#$offset" ++ s1 ++ s ++ c ++ f ++ s2}
enumValToStr (EnumText s) = return s
enumValToStr (EnumComplex lst) = do
txts <- mapM enumValToStr lst
return $ "{" ++ concat txts ++ "}"
genEnumVal = oneof [genempty, genmacro, genComplex, gensize, genoffset]
where
genempty = return $ EmptyEnum
genmacro = (genCId >>= return . FromMacro)
gensize = (genCId >>= return . EnumSize )
genasis = (asisText >>= return . EnumText)
genoffset = do
s1 <- genCId
f <- genCId
return $ EnumOffset s1 f
genComplex = do
l <- listOf1 $ oneof [genasis, genmacro]
return $ EnumComplex l
prop_enumVal :: Gen Bool
prop_enumVal = do
ev <- genEnumVal
txt <- enumValToStr ev
gParse (\x -> True) "prop_enumVal" (option EmptyEnum enumValue) txt
tests :: [TF.Test]
tests = [
testGroup "QuickCheck CCS.Parser" [
testProperty "parseLibrary" prop_parseLib,
testProperty "parseHeader" prop_parseHeader,
testProperty "parseDependency" prop_parseDependencySec,
testProperty "parseEpilogue" prop_validEpilog,
testProperty "parseEnumValue" prop_enumVal
]
]
tester p strs = parseTest p (unlines strs)
main = defaultMain tests
|
kapilash/dc
|
src/ccs2c/ccs2cs-lib/tests/Main.hs
|
bsd-3-clause
| 6,641
| 0
| 15
| 1,644
| 2,520
| 1,250
| 1,270
| 200
| 2
|
module ExampleUtil where
import System.Random
import Data.List
import Data.Array.Accelerate as A
-- Takes a size and a seed to produce a list of doubles
randomlist :: Int -> StdGen -> [Double]
randomlist n = Data.List.take n . unfoldr (Just . random)
-- Takes a size and 3 seeds to produce a list of 3 tuples
random3Tuplelist :: Int -> StdGen -> StdGen -> StdGen -> [(Double, Double, Double)]
random3Tuplelist n s1 s2 s3 = Data.List.zip3 xs ys zs
where xs = randomlist n s1
ys = randomlist n s2
zs = randomlist n s3
-- Takes a size and a list of doubles to produce an Accelerate vector
toAccVector :: Int -> [Double] -> Acc (Vector Double)
toAccVector size rs = A.use $ A.fromList (Z :. size) $ rs
-- Takes a size and a list of doubles to produce an Accelerate vector
toAccVector3 :: Int -> [(Double,Double,Double)] -> Acc (Vector (Double,Double,Double))
toAccVector3 size rs = A.use $ A.fromList (Z :. size) $ rs
-- Do nothing
noop size = do
return ()
|
pwoh/examples-hs
|
src/ExampleUtil.hs
|
bsd-3-clause
| 1,046
| 0
| 10
| 266
| 308
| 167
| 141
| 17
| 1
|
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
module Common
( SlackMessage(..)
, MessageAcceptor
, slackPayloadWithChannel
, startMessageAcceptor
, textInMessageAcceptor
) where
import ClassyPrelude
import Data.Aeson
type MessageAcceptor = Text -> Bool
data SlackMessage = SlackMessage
{ channel :: Text
, message :: Text
} deriving (Eq, Show)
instance ToJSON SlackMessage where
toJSON sm = object [
"channel" .= channel sm,
"text" .= message sm ]
slackPayloadWithChannel :: Text -> Text -> Text
slackPayloadWithChannel channel payload =
decodeUtf8 $ toStrict $ encode $ SlackMessage channel payload
startMessageAcceptorGenerator :: Text -> Text -> Bool
startMessageAcceptorGenerator start message =
let messageWords = words message in
case (headMay messageWords) of
Nothing -> False
Just firstWord -> firstWord == start
startMessageAcceptor :: Text -> MessageAcceptor
startMessageAcceptor start =
startMessageAcceptorGenerator start
textInMessageAcceptorGenerator :: Text -> Text -> Bool
textInMessageAcceptorGenerator needle message =
isInfixOf needle (toLower message)
textInMessageAcceptor :: Text -> MessageAcceptor
textInMessageAcceptor needle =
textInMessageAcceptorGenerator needle
|
Koshroy/kokona
|
src/Common.hs
|
bsd-3-clause
| 1,298
| 0
| 10
| 235
| 296
| 157
| 139
| 37
| 2
|
module PackageTests.Tests(tests) where
import PackageTests.PackageTester
import qualified PackageTests.AutogenModules.Package.Check
import qualified PackageTests.AutogenModules.SrcDist.Check
import qualified PackageTests.BenchmarkStanza.Check
import qualified PackageTests.CaretOperator.Check
import qualified PackageTests.TestStanza.Check
import qualified PackageTests.DeterministicAr.Check
import qualified PackageTests.TestSuiteTests.ExeV10.Check
import Distribution.Types.TargetInfo
import Distribution.Types.LocalBuildInfo
import Distribution.Simple.LocalBuildInfo
( absoluteComponentInstallDirs
, InstallDirs(libdir)
, ComponentLocalBuildInfo(componentUnitId), ComponentName(..) )
import Distribution.Simple.InstallDirs ( CopyDest(NoCopyDest) )
import Distribution.Simple.BuildPaths ( mkLibName, mkSharedLibName )
import Distribution.Simple.Compiler ( compilerId )
import Distribution.System (buildOS, OS(Windows))
import Control.Monad
import System.Directory
import Data.Version
import Test.Tasty (mkTimeout, localOption)
tests :: SuiteConfig -> TestTreeM ()
tests config = do
---------------------------------------------------------------------
-- * External tests
-- Test that Cabal parses 'benchmark' sections correctly
tc "BenchmarkStanza" PackageTests.BenchmarkStanza.Check.suite
-- Test that Cabal parses 'test' sections correctly
tc "TestStanza" PackageTests.TestStanza.Check.suite
-- Test that Cabal parses '^>=' operator correctly
tc "CaretOperator" PackageTests.CaretOperator.Check.suite
-- Test that Cabal determinstically generates object archives
tc "DeterministicAr" PackageTests.DeterministicAr.Check.suite
-- Test that cabal shows all the 'autogen-modules' warnings.
tc "AutogenModules/Package" PackageTests.AutogenModules.Package.Check.suite
-- Test that Cabal parses and uses 'autogen-modules' fields correctly
tc "AutogenModules/SrcDist" PackageTests.AutogenModules.SrcDist.Check.suite
---------------------------------------------------------------------
-- * Test suite tests
-- TODO: This shouldn't be necessary, but there seems to be some
-- bug in the way the test is written. Not going to lose sleep
-- over this... but would be nice to fix.
testWhen (hasCabalForGhc config)
. groupTests "TestSuiteTests/ExeV10" $
(PackageTests.TestSuiteTests.ExeV10.Check.tests config)
-- Test if detailed-0.9 builds correctly
testWhen (hasCabalForGhc config)
. tcs "TestSuiteTests/LibV09" "Build" $ cabal_build ["--enable-tests"]
-- Tests for #2489, stdio deadlock
testWhen (hasCabalForGhc config)
. mapTestTrees (localOption (mkTimeout $ 10 ^ (8 :: Int)))
. tcs "TestSuiteTests/LibV09" "Deadlock" $ do
cabal_build ["--enable-tests"]
shouldFail $ cabal "test" []
---------------------------------------------------------------------
-- * Inline tests
-- Test if exitcode-stdio-1.0 benchmark builds correctly
tc "BenchmarkExeV10" $ cabal_build ["--enable-benchmarks"]
-- Test --benchmark-option(s) flags on ./Setup bench
tc "BenchmarkOptions" $ do
cabal_build ["--enable-benchmarks"]
cabal "bench" [ "--benchmark-options=1 2 3" ]
cabal "bench" [ "--benchmark-option=1"
, "--benchmark-option=2"
, "--benchmark-option=3"
]
-- Test --test-option(s) flags on ./Setup test
tc "TestOptions" $ do
cabal_build ["--enable-tests"]
cabal "test" ["--test-options=1 2 3"]
cabal "test" [ "--test-option=1"
, "--test-option=2"
, "--test-option=3"
]
-- Test attempt to have executable depend on internal
-- library, but cabal-version is too old.
tc "BuildDeps/InternalLibrary0" $ do
r <- shouldFail $ cabal' "configure" []
-- Should tell you how to enable the desired behavior
let sb = "library which is defined within the same package."
assertOutputContains sb r
-- Test executable depends on internal library.
tc "BuildDeps/InternalLibrary1" $ cabal_build []
-- Test that internal library is preferred to an installed on
-- with the same name and version
tc "BuildDeps/InternalLibrary2" $ internal_lib_test "internal"
-- Test that internal library is preferred to an installed on
-- with the same name and LATER version
tc "BuildDeps/InternalLibrary3" $ internal_lib_test "internal"
-- Test that an explicit dependency constraint which doesn't
-- match the internal library causes us to use external library
tc "BuildDeps/InternalLibrary4" $ internal_lib_test "installed"
-- Test "old build-dep behavior", where we should get the
-- same package dependencies on all targets if cabal-version
-- is sufficiently old.
tc "BuildDeps/SameDepsAllRound" $ cabal_build []
-- Test "new build-dep behavior", where each target gets
-- separate dependencies. This tests that an executable
-- dep does not leak into the library.
tc "BuildDeps/TargetSpecificDeps1" $ do
cabal "configure" []
r <- shouldFail $ cabal' "build" []
assertRegex "error should be in MyLibrary.hs" "^MyLibrary.hs:" r
assertRegex
"error should be \"Could not find module `Text\\.PrettyPrint\""
"(Could not find module|Failed to load interface for).*Text\\.PrettyPrint" r
-- This is a control on TargetSpecificDeps1; it should
-- succeed.
tc "BuildDeps/TargetSpecificDeps2" $ cabal_build []
-- Test "new build-dep behavior", where each target gets
-- separate dependencies. This tests that an library
-- dep does not leak into the executable.
tc "BuildDeps/TargetSpecificDeps3" $ do
cabal "configure" []
r <- shouldFail $ cabal' "build" []
assertRegex "error should be in lemon.hs" "^lemon.hs:" r
assertRegex
"error should be \"Could not find module `Text\\.PrettyPrint\""
"(Could not find module|Failed to load interface for).*Text\\.PrettyPrint" r
-- Test that Paths module is generated and available for executables.
tc "PathsModule/Executable" $ cabal_build []
-- Test that Paths module is generated and available for libraries.
tc "PathsModule/Library" $ cabal_build []
-- Check that preprocessors (hsc2hs) are run
tc "PreProcess" $ cabal_build ["--enable-tests", "--enable-benchmarks"]
-- Check that preprocessors that generate extra C sources are handled
tc "PreProcessExtraSources" $ cabal_build ["--enable-tests",
"--enable-benchmarks"]
-- Test building a vanilla library/executable which uses Template Haskell
tc "TemplateHaskell/vanilla" $ cabal_build []
-- Test building a profiled library/executable which uses Template Haskell
-- (Cabal has to build the non-profiled version first)
tc "TemplateHaskell/profiling" $ cabal_build ["--enable-library-profiling",
"--enable-profiling"]
-- Test building a dynamic library/executable which uses Template
-- Haskell
testWhen (hasSharedLibraries config) $
tc "TemplateHaskell/dynamic" $ cabal_build ["--enable-shared",
"--enable-executable-dynamic"]
-- Test building an executable whose main() function is defined in a C
-- file
tc "CMain" $ cabal_build []
-- Test build when the library is empty, for #1241
tc "EmptyLib" $
withPackage "empty" $ cabal_build []
-- Test that "./Setup haddock" works correctly
tc "Haddock" $ do
dist_dir <- distDir
let haddocksDir = dist_dir </> "doc" </> "html" </> "Haddock"
cabal "configure" []
cabal "haddock" []
let docFiles
= map (haddocksDir </>)
["CPP.html", "Literate.html", "NoCPP.html", "Simple.html"]
mapM_ (assertFindInFile "For hiding needles.") docFiles
-- Test that Haddock with a newline in synopsis works correctly, #3004
tc "HaddockNewline" $ do
cabal "configure" []
cabal "haddock" []
-- Test that Cabal properly orders GHC flags passed to GHC (when
-- there are multiple ghc-options fields.)
tc "OrderFlags" $ cabal_build []
-- Test that reexported modules build correctly
tc "ReexportedModules" . whenGhcVersion (>= Version [7,9] []) $ do
withPackageDb $ do
withPackage "p" $ cabal_install []
withPackage "q" $ do
cabal_build []
-- Test that Cabal computes different IPIDs when the source changes.
tc "UniqueIPID" . withPackageDb $ do
withPackage "P1" $ cabal "configure" []
withPackage "P2" $ cabal "configure" []
withPackage "P1" $ cabal "build" []
withPackage "P1" $ cabal "build" [] -- rebuild should work
r1 <- withPackage "P1" $ cabal' "register" ["--print-ipid", "--inplace"]
withPackage "P2" $ cabal "build" []
r2 <- withPackage "P2" $ cabal' "register" ["--print-ipid", "--inplace"]
let exIPID s = takeWhile (/= '\n') $
head . filter (isPrefixOf $ "UniqueIPID-0.1-") $ (tails s)
when ((exIPID $ resultOutput r1) == (exIPID $ resultOutput r2)) $
assertFailure $ "cabal has not calculated different Installed " ++
"package ID when source is changed."
-- Test that if two components have the same module name, they do not
-- clobber each other.
testWhen (hasCabalForGhc config) $ -- uses library test suite
tc "DuplicateModuleName" $ do
cabal_build ["--enable-tests"]
r1 <- shouldFail $ cabal' "test" ["foo"]
assertOutputContains "test B" r1
assertOutputContains "test A" r1
r2 <- shouldFail $ cabal' "test" ["foo2"]
assertOutputContains "test C" r2
assertOutputContains "test A" r2
-- Test that if test suite has a name which conflicts with a package
-- which is in the database, we can still use the test case (they
-- should NOT shadow).
testWhen (hasCabalForGhc config)
. tc "TestNameCollision" $ do
withPackageDb $ do
withPackage "parent" $ cabal_install []
withPackage "child" $ do
cabal_build ["--enable-tests"]
cabal "test" []
-- Test that '--allow-newer' works via the 'Setup.hs configure' interface.
tc "AllowNewer" $ do
shouldFail $ cabal "configure" []
cabal "configure" ["--allow-newer"]
shouldFail $ cabal "configure" ["--allow-newer=baz,quux"]
cabal "configure" ["--allow-newer=base", "--allow-newer=baz,quux"]
cabal "configure" ["--allow-newer=bar", "--allow-newer=base,baz"
,"--allow-newer=quux"]
shouldFail $ cabal "configure" ["--enable-tests"]
cabal "configure" ["--enable-tests", "--allow-newer"]
shouldFail $ cabal "configure" ["--enable-benchmarks"]
cabal "configure" ["--enable-benchmarks", "--allow-newer"]
shouldFail $ cabal "configure" ["--enable-benchmarks", "--enable-tests"]
cabal "configure" ["--enable-benchmarks", "--enable-tests"
,"--allow-newer"]
shouldFail $ cabal "configure" ["--allow-newer=Foo:base"]
shouldFail $ cabal "configure" ["--allow-newer=Foo:base"
,"--enable-tests", "--enable-benchmarks"]
cabal "configure" ["--allow-newer=AllowNewer:base"]
cabal "configure" ["--allow-newer=AllowNewer:base"
,"--allow-newer=Foo:base"]
cabal "configure" ["--allow-newer=AllowNewer:base"
,"--allow-newer=Foo:base"
,"--enable-tests", "--enable-benchmarks"]
-- Test that '--allow-older' works via the 'Setup.hs configure' interface.
tc "AllowOlder" $ do
shouldFail $ cabal "configure" []
cabal "configure" ["--allow-older"]
shouldFail $ cabal "configure" ["--allow-older=baz,quux"]
cabal "configure" ["--allow-older=base", "--allow-older=baz,quux"]
cabal "configure" ["--allow-older=bar", "--allow-older=base,baz"
,"--allow-older=quux"]
shouldFail $ cabal "configure" ["--enable-tests"]
cabal "configure" ["--enable-tests", "--allow-older"]
shouldFail $ cabal "configure" ["--enable-benchmarks"]
cabal "configure" ["--enable-benchmarks", "--allow-older"]
shouldFail $ cabal "configure" ["--enable-benchmarks", "--enable-tests"]
cabal "configure" ["--enable-benchmarks", "--enable-tests"
,"--allow-older"]
shouldFail $ cabal "configure" ["--allow-older=Foo:base"]
shouldFail $ cabal "configure" ["--allow-older=Foo:base"
,"--enable-tests", "--enable-benchmarks"]
cabal "configure" ["--allow-older=AllowOlder:base"]
cabal "configure" ["--allow-older=AllowOlder:base"
,"--allow-older=Foo:base"]
cabal "configure" ["--allow-older=AllowOlder:base"
,"--allow-older=Foo:base"
,"--enable-tests", "--enable-benchmarks"]
-- Test that Cabal can choose flags to disable building a component when that
-- component's dependencies are unavailable. The build should succeed without
-- requiring the component's dependencies or imports.
tc "BuildableField" $ do
r <- cabal' "configure" ["-v"]
assertOutputContains "Flags chosen: build-exe=False" r
cabal "build" []
-- TODO: Enable these tests on Windows
unlessWindows $ do
tc "GhcPkgGuess/SameDirectory" $ ghc_pkg_guess "ghc"
tc "GhcPkgGuess/SameDirectoryVersion" $ ghc_pkg_guess "ghc-7.10"
tc "GhcPkgGuess/SameDirectoryGhcVersion" $ ghc_pkg_guess "ghc-7.10"
unlessWindows $ do
tc "GhcPkgGuess/Symlink" $ do
-- We don't want to distribute a tarball with symlinks. See #3190.
withSymlink "bin/ghc"
"tests/PackageTests/GhcPkgGuess/Symlink/ghc" $
ghc_pkg_guess "ghc"
tc "GhcPkgGuess/SymlinkVersion" $ do
withSymlink "bin/ghc-7.10"
"tests/PackageTests/GhcPkgGuess/SymlinkVersion/ghc" $
ghc_pkg_guess "ghc"
tc "GhcPkgGuess/SymlinkGhcVersion" $ do
withSymlink "bin/ghc-7.10"
"tests/PackageTests/GhcPkgGuess/SymlinkGhcVersion/ghc" $
ghc_pkg_guess "ghc"
-- Basic test for internal libraries (in p); package q is to make
-- sure that the internal library correctly is used, not the
-- external library.
tc "InternalLibraries" $ do
withPackageDb $ do
withPackage "q" $ cabal_install []
withPackage "p" $ do
cabal_install []
cabal "clean" []
r <- runInstalledExe' "foo" []
assertOutputContains "I AM THE ONE" r
-- Test to see if --gen-script works.
tcs "InternalLibraries" "gen-script" $ do
withPackageDb $ do
withPackage "p" $ do
cabal_build []
cabal "copy" []
cabal "register" ["--gen-script"]
_ <- if buildOS == Windows
then shell "cmd" ["/C", "register.bat"]
else shell "sh" ["register.sh"]
return ()
-- Make sure we can see p
withPackage "r" $ cabal_install []
-- Test to see if --gen-pkg-config works.
tcs "InternalLibraries" "gen-pkg-config" $ do
withPackageDb $ do
withPackage "p" $ do
cabal_build []
cabal "copy" []
let dir = "pkg-config.bak"
cabal "register" ["--gen-pkg-config=" ++ dir]
-- Infelicity! Does not respect CWD.
pkg_dir <- packageDir
let notHidden = not . isHidden
isHidden name = "." `isPrefixOf` name
confs <- fmap (sort . filter notHidden)
. liftIO $ getDirectoryContents (pkg_dir </> dir)
forM_ confs $ \conf -> ghcPkg "register" [pkg_dir </> dir </> conf]
-- Make sure we can see p
withPackage "r" $ cabal_install []
-- Internal libraries used by a statically linked executable:
-- no libraries should get installed or registered. (Note,
-- this does build shared libraries just to make sure they
-- don't get installed, so this test doesn't work on Windows.)
testWhen (hasSharedLibraries config) $
tcs "InternalLibraries/Executable" "Static" $
multiple_libraries_executable False
-- Internal libraries used by a dynamically linked executable:
-- ONLY the dynamic library should be installed, no registration
testWhen (hasSharedLibraries config) $
tcs "InternalLibraries/Executable" "Dynamic" $
multiple_libraries_executable True
-- Internal library used by public library; it must be installed and
-- registered.
tc "InternalLibraries/Library" $ do
withPackageDb $ do
withPackage "foolib" $ cabal_install []
withPackage "fooexe" $ do
cabal_build []
runExe' "fooexe" []
>>= assertOutputContains "25"
-- Basic test to make sure we can build internal libraries manually.
mtcs "InternalLibraries/Library" "AssumeDepsUpToDate" $ \step -> do
withPackageDb $ do
step "Building foolib"
withPackage "foolib" $ do
cabal "configure" []
let upd = "--assume-deps-up-to-date"
step "foolib: copying global data"
cabal "copy" [upd]
let mk_foolib_internal str = do
step $ "foolib: building foolib-internal (" ++ str ++ ")"
cabal "build" [upd, "foolib-internal"]
cabal "copy" [upd, "foolib-internal"]
cabal "register" [upd, "foolib-internal"]
mk_foolib str = do
step $ "foolib: building foolib (" ++ str ++ ")"
cabal "build" [upd, "foolib"]
cabal "copy" [upd, "foolib"]
cabal "register" [upd, "foolib"]
mk_foolib_internal "run 1"
mk_foolib "run 1"
mk_foolib_internal "run 2"
mk_foolib "run 2"
withPackage "fooexe" $ do
cabal_build []
runExe' "fooexe" [] >>= assertOutputContains "25"
-- Test to ensure that cabal_macros.h are computed per-component.
tc "Macros" $ do
cabal_build []
runExe' "macros-a" []
>>= assertOutputContains "macros-a"
runExe' "macros-b" []
>>= assertOutputContains "macros-b"
-- Test for 'build-type: Configure' example from the Cabal manual.
-- Disabled on Windows since MingW doesn't ship with autoreconf by
-- default.
unlessWindows $ do
tc "Configure" $ do
_ <- shell "autoreconf" ["-i"]
cabal_build []
tc "ConfigureComponent/Exe" $ do
withPackageDb $ do
cabal_install ["goodexe"]
runExe' "goodexe" [] >>= assertOutputContains "OK"
tcs "ConfigureComponent/SubLib" "sublib-explicit" $ do
withPackageDb $ do
cabal_install ["sublib", "--cid", "sublib-0.1-abc"]
cabal_install ["exe", "--dependency", "sublib=sublib-0.1-abc"]
runExe' "exe" [] >>= assertOutputContains "OK"
tcs "ConfigureComponent/SubLib" "sublib" $ do
withPackageDb $ do
cabal_install ["sublib"]
cabal_install ["exe"]
runExe' "exe" [] >>= assertOutputContains "OK"
tcs "ConfigureComponent/Test" "test" $ do
withPackageDb $ do
cabal_install ["test-for-cabal"]
withPackage "testlib" $ cabal_install []
cabal "configure" ["testsuite"]
cabal "build" []
cabal "test" []
-- Test that per-component copy works, when only building library
tc "CopyComponent/Lib" $
withPackageDb $ do
cabal "configure" []
cabal "build" ["lib:p"]
cabal "copy" ["lib:p"]
-- Test that per-component copy works, when only building one executable
tc "CopyComponent/Exe" $
withPackageDb $ do
cabal "configure" []
cabal "build" ["myprog"]
cabal "copy" ["myprog"]
-- Test internal custom preprocessor
tc "CustomPreProcess" $ do
cabal_build []
runExe' "hello-world" []
>>= assertOutputContains "hello from A"
-- Test PATH-munging
tc "BuildToolsPath" $ do
cabal_build []
runExe' "hello-world" []
>>= assertOutputContains "1111"
-- Test that executable recompilation works
-- https://github.com/haskell/cabal/issues/3294
tc "Regression/T3294" $ do
pkg_dir <- packageDir
liftIO $ writeFile (pkg_dir </> "Main.hs") "main = putStrLn \"aaa\""
cabal "configure" []
cabal "build" []
runExe' "T3294" [] >>= assertOutputContains "aaa"
ghcFileModDelay
liftIO $ writeFile (pkg_dir </> "Main.hs") "main = putStrLn \"bbb\""
cabal "build" []
runExe' "T3294" [] >>= assertOutputContains "bbb"
-- Test build --assume-deps-up-to-date
mtc "BuildAssumeDepsUpToDate" $ \step -> do
step "Initial build"
pkg_dir <- packageDir
liftIO $ writeFile (pkg_dir </> "A.hs") "module A where\na = \"a1\""
liftIO $ writeFile (pkg_dir </> "myprog/Main.hs") "import A\nmain = print (a ++ \" b1\")"
cabal "configure" []
cabal "build" ["--assume-deps-up-to-date", "BuildAssumeDepsUpToDate"]
cabal "build" ["--assume-deps-up-to-date", "myprog"]
runExe' "myprog" []
>>= assertOutputContains "a1 b1"
step "Rebuild executable only"
ghcFileModDelay
liftIO $ writeFile (pkg_dir </> "A.hs") "module A where\na = \"a2\""
liftIO $ writeFile (pkg_dir </> "myprog/Main.hs") "import A\nmain = print (a ++ \" b2\")"
cabal "build" ["--assume-deps-up-to-date", "myprog"]
runExe' "myprog" []
>>= assertOutputContains "a1 b2"
-- Test copy --assume-deps-up-to-date
-- NB: This test has a HORRIBLE HORRIBLE hack to ensure that
-- on Windows, we don't try to make a prefix relative package;
-- specifically, we give the package under testing a library
-- so that we don't attempt to make it prefix relative.
mtc "CopyAssumeDepsUpToDate" $ \step -> do
withPackageDb $ do
step "Initial build"
cabal_build []
step "Executable cannot find data file"
pkg_dir <- packageDir
shouldFail (runExe' "myprog" [])
>>= assertOutputContains "does not exist"
prefix_dir <- prefixDir
shouldNotExist $ prefix_dir </> "bin" </> "myprog"
step "Install data file"
liftIO $ writeFile (pkg_dir </> "data") "aaa"
cabal "copy" ["--assume-deps-up-to-date"]
shouldNotExist $ prefix_dir </> "bin" </> "myprog"
runExe' "myprog" []
>>= assertOutputContains "aaa"
step "Install executable"
liftIO $ writeFile (pkg_dir </> "data") "bbb"
cabal "copy" ["--assume-deps-up-to-date", "exe:myprog"]
runInstalledExe' "myprog" []
>>= assertOutputContains "aaa"
-- Test register --assume-deps-up-to-date
mtc "RegisterAssumeDepsUpToDate" $ \step -> do
withPackageDb $ do
-- We'll test this by generating registration files and verifying
-- that they are indeed files (and not directories)
step "Initial build and copy"
cabal_build []
cabal "copy" []
step "Register q"
let q_reg = "pkg-config-q"
cabal "register" ["--assume-deps-up-to-date", "q", "--gen-pkg-config=" ++ q_reg]
pkg_dir <- packageDir
ghcPkg "register" [pkg_dir </> q_reg]
step "Register p"
let main_reg = "pkg-config-p"
cabal "register" ["--assume-deps-up-to-date", "RegisterAssumeDepsUpToDate", "--gen-pkg-config=" ++ main_reg]
ghcPkg "register" [pkg_dir </> main_reg]
where
ghc_pkg_guess bin_name = do
cwd <- packageDir
with_ghc <- getWithGhcPath
r <- withEnv [("WITH_GHC", Just with_ghc)]
. shouldFail $ cabal' "configure" ["-w", cwd </> bin_name]
assertOutputContains "is version 9999999" r
return ()
-- Shared test function for BuildDeps/InternalLibrary* tests.
internal_lib_test expect = withPackageDb $ do
withPackage "to-install" $ cabal_install []
cabal_build []
r <- runExe' "lemon" []
assertEqual
("executable should have linked with the " ++ expect ++ " library")
("foo foo myLibFunc " ++ expect)
(concatOutput (resultOutput r))
assertRegex :: String -> String -> Result -> TestM ()
assertRegex msg regex r = let out = resultOutput r
in assertBool (msg ++ ",\nactual output:\n" ++ out)
(out =~ regex)
multiple_libraries_executable is_dynamic =
withPackageDb $ do
cabal_install $ [ if is_dynamic then "--enable-executable-dynamic"
else "--disable-executable-dynamic"
, "--enable-shared"]
dist_dir <- distDir
lbi <- liftIO $ getPersistBuildConfig dist_dir
let pkg_descr = localPkgDescr lbi
compiler_id = compilerId (compiler lbi)
cname = CSubLibName "foo-internal"
[target] = componentNameTargets' pkg_descr lbi cname
uid = componentUnitId (targetCLBI target)
dir = libdir (absoluteComponentInstallDirs pkg_descr lbi uid
NoCopyDest)
assertBool "interface files should be installed"
=<< liftIO (doesFileExist (dir </> "Foo.hi"))
assertBool "static library should be installed"
=<< liftIO (doesFileExist (dir </> mkLibName uid))
if is_dynamic
then
assertBool "dynamic library MUST be installed"
=<< liftIO (doesFileExist (dir </> mkSharedLibName
compiler_id uid))
else
assertBool "dynamic library should be installed"
=<< liftIO (doesFileExist (dir </> mkSharedLibName
compiler_id uid))
shouldFail $ ghcPkg "describe" ["foo"]
-- clean away the dist directory so that we catch accidental
-- dependence on the inplace files
cabal "clean" []
runInstalledExe' "foo" [] >>= assertOutputContains "46"
tc :: FilePath -> TestM a -> TestTreeM ()
tc name = testTree config name
mtc :: FilePath -> ((String -> TestM ()) -> TestM a) -> TestTreeM ()
mtc name = testTreeSteps config name
tcs :: FilePath -> FilePath -> TestM a -> TestTreeM ()
tcs name sub_name m
= testTreeSub config name sub_name m
mtcs :: FilePath -> FilePath -> ((String -> TestM ()) -> TestM a) -> TestTreeM ()
mtcs name sub_name = testTreeSubSteps config name sub_name
|
sopvop/cabal
|
Cabal/tests/PackageTests/Tests.hs
|
bsd-3-clause
| 26,614
| 86
| 26
| 6,860
| 5,009
| 2,406
| 2,603
| 444
| 4
|
{-# LANGUAGE DeriveDataTypeable #-}
module Main where
import System.Console.CmdArgs
import System.Directory (getHomeDirectory)
import System.FilePath (joinPath, splitPath, (</>))
import GitRunner
import G4Release
data CmdOptions = AboutIrt {
}
| G4Release { gitRepo :: String
, ignoreGitModifications :: Bool
, g4options :: [G4ReleaseOption]
, g4Tree :: String
}
| G4AblaRelease { gitRepo :: String
, ignoreGitModifications :: Bool
, g4options :: [G4ReleaseOption]
, g4Tree :: String
}
deriving (Show, Eq, Data, Typeable)
data SourceConfig = SourceConfig { rootDir :: FilePath }
data SourceTransform = FileTransform { transformFileName :: FilePath
, transformFileContents :: [String]
}
| TreeTransform { transformTreeDirectory :: FilePath
}
deriving (Show, Eq)
tildeExpansion :: FilePath -> IO FilePath
tildeExpansion s = do
homeDir <- getHomeDirectory
return $ case splitPath s of
("~/" : t) -> joinPath $ homeDir : t
_ -> s
g4release :: CmdOptions
g4release = G4Release { gitRepo = def &= help "INCL++ Git repository path"
, ignoreGitModifications = False &= help "Ignore modifications in the Git tree"
, g4Tree = def &= help "Geant4 checkout (main level)"
, g4options = [] &= help "(AllowAssert, NoG4Types, NoLicense, RevisionInfo)"
} &= help "Release INCL++ to Geant4"
g4ablarelease :: CmdOptions
g4ablarelease = G4AblaRelease { gitRepo = def &= help "ABLAXX Git repository path (containing the ablaxx directory)"
, ignoreGitModifications = False &= help "Ignore modifications in the Git tree"
, g4Tree = def &= help "Geant4 checkout (main level)"
, g4options = [] &= help "(AllowAssert, NoG4Types, NoLicense, RevisionInfo)"
} &= help "Release ABLAXX to Geant4"
info :: CmdOptions
info = AboutIrt {} &= help "Help"
mode :: Mode (CmdArgs CmdOptions)
mode = cmdArgsMode $ modes [info,g4release,g4ablarelease] &= help "Make an INCL release" &= program "irt" &= summary "irt v0.5"
abortG4Release :: IO ()
abortG4Release = do
putStrLn "Error! Git tree must not contain uncommitted changes!"
performG4Release :: GitRepo -> FilePath -> [G4ReleaseOption] -> IO ()
performG4Release repo targetDir g4opts = do
let inclDir = gitRepoPath repo
codename = "inclxx"
g4inclxxUtilsModule <- mkModuleDefinition inclDir "utils" codename "utils" []
g4inclxxPhysicsModule <- mkModuleDefinition inclDir "incl_physics" codename "physics" [g4inclxxUtilsModule]
g4inclxxInterfaceModule <- mkModuleDefinition inclDir "interface" codename "interface" [g4inclxxUtilsModule, g4inclxxPhysicsModule]
let g4modules = [g4inclxxUtilsModule, g4inclxxPhysicsModule, g4inclxxInterfaceModule]
releaseG4 repo targetDir g4modules g4opts
performG4AblaRelease :: GitRepo -> FilePath -> [G4ReleaseOption] -> IO ()
performG4AblaRelease repo targetDir g4opts = do
let ablaDir = gitRepoPath repo
codename = "abla"
g4AblaModule <- mkModuleDefinition ablaDir "" codename "abla" []
releaseG4Abla repo targetDir g4AblaModule g4opts
runIrtCommand :: CmdOptions -> IO ()
runIrtCommand (G4Release gitpath ignoregitmodif g4opts g4sourcepath) = do
let expandedGitPathIO = tildeExpansion gitpath
expandedG4SourcePathIO = tildeExpansion g4sourcepath
expandedGitPath <- expandedGitPathIO
expandedG4SourcePath <- expandedG4SourcePathIO
let inclRepository = GitRepo expandedGitPath
targetDir = expandedG4SourcePath </> "source/processes/hadronic/models/inclxx/"
inclDirtyTree <- gitIsDirtyTree inclRepository
inclRev <- buildGitRevisionString inclRepository
putStrLn $ "INCL++ repository path is: " ++ expandedGitPath
putStrLn $ "INCL++ revision is: " ++ inclRev
putStrLn $ "Geant4 path is: " ++ expandedG4SourcePath
putStrLn $ "G4 release options: " ++ (show g4opts)
if inclDirtyTree && (not ignoregitmodif)
then abortG4Release
else performG4Release inclRepository targetDir g4opts
runIrtCommand (G4AblaRelease gitpath ignoregitmodif g4opts g4sourcepath) = do
let expandedGitPathIO = tildeExpansion gitpath
expandedG4SourcePathIO = tildeExpansion g4sourcepath
expandedGitPath <- expandedGitPathIO
expandedG4SourcePath <- expandedG4SourcePathIO
let inclRepository = GitRepo expandedGitPath
targetDir = expandedG4SourcePath </> "source/processes/hadronic/models/abla/"
inclDirtyTree <- gitIsDirtyTree inclRepository
inclRev <- buildGitRevisionString inclRepository
putStrLn $ "ABLAXX repository path is: " ++ expandedGitPath
putStrLn $ "ABLAXX revision is: " ++ inclRev
putStrLn $ "Geant4 path is: " ++ expandedG4SourcePath
putStrLn $ "G4 release options: " ++ (show g4opts)
if inclDirtyTree && (not ignoregitmodif)
then abortG4Release
else performG4AblaRelease inclRepository targetDir g4opts
runIrtCommand AboutIrt = do
putStrLn "About irt"
main :: IO ()
main = do
conf <- cmdArgsRun mode
runIrtCommand conf
|
arekfu/irt
|
src/irt.hs
|
bsd-3-clause
| 5,448
| 1
| 12
| 1,389
| 1,152
| 587
| 565
| 101
| 3
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
-- BSD-3, Ricky Elrod <ricky@elrod.me>
-- BSD-3, Maxwell Swadling <maxwellswadling@gmail.com>
-- TODO:
-- - Dryrun mode
module Network.DigitalOcean (
Authentication (..),
DOResponse (..),
Droplet (..), droplets,
Region (..), regions,
Size (..), sizes,
Image (..), images,
SSH (..), sshKeys,
NewDropletRequest (..), newDroplet,
NewDroplet (..),
Event (..), event,
PackedDroplet (..), packDroplets
) where
import Control.Applicative ((<$>), (<*>))
import Control.Monad (liftM)
import Control.Monad.IO.Class
import Data.Aeson ((.:), decode, FromJSON(..), Value(..))
import qualified Data.ByteString.Lazy.Char8 as BS
import Data.List (intercalate, find)
import Data.Maybe
import Data.Monoid
import Data.Text (Text)
import Network.HTTP.Base (urlEncode)
import Network.HTTP.Conduit
data Authentication = Authentication { clientId :: String, apiKey :: String } deriving (Show)
data Droplet = Droplet {
dropletId :: Integer,
name :: String,
imageId :: Integer,
sizeId :: Integer,
regionId :: Integer,
backupsActive :: Bool,
ipAddress :: String,
privateIpAddress :: Maybe String,
locked :: Bool,
status' :: String,
createdAt :: String
} deriving (Show, Read)
data Region = Region {
rId :: Integer,
rName :: String
} deriving (Show, Read)
data Size = Size {
sId :: Integer,
sName :: String,
sMemory :: Integer,
sCpu :: Integer,
sDisk :: Integer,
sCostHour :: Float,
sCostMonth :: String -- Yeah, it's a string.
} deriving (Show, Read)
data Image = Image {
iImageId :: Integer,
iImageName :: String,
iImageDistribution :: String,
iImageSlug :: Maybe String,
iImagePublic :: Maybe Bool
} deriving (Show, Read)
data SSH = SSH {
sshId :: Integer,
sshName :: String
} deriving (Show, Read)
data NewDropletRequest = NewDropletRequest {
ndName :: String,
ndSizeId :: Integer,
ndImageId :: Integer,
ndRegionId :: Integer,
ndSSHKeys :: [Integer],
ndPrivateNetworking :: Bool,
ndBackups :: Bool
} deriving (Show, Read)
data NewDroplet = NewDroplet {
ndId :: Integer,
ndEventId :: Integer
} deriving (Show, Read)
data Event = Event {
eId :: Integer,
eStatus :: Maybe String,
eDropletId :: Integer,
eEventId :: Integer,
ePercentage :: String
} deriving (Show, Read)
data DOResponse a = DOResponse {
rResponseStatus :: String,
rResponseObjects :: a
} deriving (Show, Read)
type DropletsResponse = DOResponse [Droplet]
type EventResponse = DOResponse Event
type ImagesResponse = DOResponse [Image]
type NewDropletResponse = DOResponse NewDroplet
type RegionsResponse = DOResponse [Region]
type SSHsResponse = DOResponse [SSH]
type SizesResponse = DOResponse [Size]
-- a droplet with objects (joined on id)
data PackedDroplet = PackedDroplet {
pDropletId :: Integer,
pName :: String,
pImage :: Image,
pSize :: Size,
pRegion :: Region,
pBackupsActive :: Bool,
pIpAddress :: String,
pPrivateIPAddress :: Maybe String,
pLocked :: Bool,
pStatus' :: String,
pCreatedAt :: String
} deriving (Show, Read)
-- could do lenses...
packDroplets :: [Size] -> [Region] -> [SSH] -> [Image] -> [Droplet] -> [PackedDroplet]
packDroplets _ _ _ _ [] = []
packDroplets s r k i (Droplet idx n im si re b ip pip l st c : xs) =
PackedDroplet idx n (getImage im i) (getSize si s) (getRegion re r) b ip pip l st c : packDroplets s r k i xs
where
-- safe by construction? :P
getImage i' = fromJust . find (\(Image x _ _ _ _) -> x == i')
getSize i' = fromJust . find (\(Size x _ _ _ _ _ _) -> x == i')
getRegion i' = fromJust . find (\(Region x _) -> x == i')
-- request an array of objects
request :: (FromJSON a, DOResp a) => String -> String -> Authentication -> (MonadIO m) => m (Maybe (DOResponse [a]))
request url' p x = liftM decode $ simpleHttp' $ constructURL ("/" <> url') x p
-- request a single object
requestObject :: (FromJSON a, DOResp a) => String -> String -> Authentication -> (MonadIO m) => m (Maybe (DOResponse a))
requestObject url' p x = liftM decode $ simpleHttp' $ constructURL ("/" <> url') x p
simpleHttp' :: MonadIO m => String -> m BS.ByteString
simpleHttp' url' = liftIO $ withManager $ \man -> do
req <- liftIO $ parseUrl url'
responseBody <$> httpLbs (setConnection req) man
where
setConnection req = req{requestHeaders = ("Connection", "close") : requestHeaders req, responseTimeout = Just 10000000 } -- 10 seconds
class DOResp a where
primaryKey :: a -> Text
instance DOResp a => DOResp [a] where
-- the request / requestObject ensure you can't lookup key on an array
primaryKey _ = primaryKey (undefined :: a)
instance DOResp Droplet where
primaryKey _ = "droplets"
instance DOResp NewDroplet where
primaryKey _ = "droplet"
instance DOResp Region where
primaryKey _ = "regions"
instance DOResp Size where
primaryKey _ = "sizes"
instance DOResp Image where
primaryKey _ = "images"
instance DOResp SSH where
primaryKey _ = "ssh_keys"
instance DOResp Event where
primaryKey _ = "event"
class MkParams a where
mkParams :: a -> String
showB :: Bool -> String
showB True = "true"
showB False = "false"
instance MkParams NewDropletRequest where
mkParams (NewDropletRequest n s i r ssh p b) = concatMap (\(k, v) -> "&" ++ k ++ "=" ++ v) vals
where
vals = [
("name", urlEncode n)
, ("size_id", show s)
, ("image_id", show i)
, ("region_id", show r)
, ("ssh_key_ids", intercalate "," (map show ssh))
, ("private_networking", showB p)
, ("backups_enabled", showB b)
]
instance (DOResp a, FromJSON a) => FromJSON (DOResponse a) where
parseJSON (Object v) =
DOResponse <$>
(v .: "status") <*>
(v .: primaryKey (undefined :: a))
instance FromJSON Droplet where
parseJSON (Object v) =
Droplet <$>
(v .: "id") <*>
(v .: "name") <*>
(v .: "image_id") <*>
(v .: "size_id") <*>
(v .: "region_id") <*>
(v .: "backups_active") <*>
(v .: "ip_address") <*>
(v .: "private_ip_address") <*>
(v .: "locked") <*>
(v .: "status") <*>
(v .: "created_at")
instance FromJSON NewDroplet where
parseJSON (Object v) =
NewDroplet <$>
(v .: "id") <*>
(v .: "event_id")
instance FromJSON Region where
parseJSON (Object v) =
Region <$>
(v .: "id") <*>
(v .: "name")
instance FromJSON Size where
parseJSON (Object v) =
Size <$>
(v .: "id") <*>
(v .: "name") <*>
(v .: "memory") <*>
(v .: "cpu") <*>
(v .: "disk") <*>
(v .: "cost_per_hour") <*>
(v .: "cost_per_month")
instance FromJSON Image where
parseJSON (Object v) =
Image <$>
(v .: "id") <*>
(v .: "name") <*>
(v .: "distribution") <*>
(v .: "slug") <*>
(v .: "public")
instance FromJSON SSH where
parseJSON (Object v) =
SSH <$>
(v .: "id") <*>
(v .: "name")
instance FromJSON Event where
parseJSON (Object v) =
Event <$>
(v .: "id") <*>
(v .: "action_status") <*>
(v .: "droplet_id") <*>
(v .: "event_type_id") <*>
(v .: "percentage")
-- The API url
url :: String
url = "https://api.digitalocean.com"
-- QueryString that contains authentication information (client ID and API key)
authQS :: Authentication -> String
authQS a = "client_id=" ++ urlEncode (clientId a) ++ "&api_key=" ++ urlEncode (apiKey a)
constructURL :: String -> Authentication -> String -> String
constructURL a b p = url ++ a ++ "?" ++ authQS b ++ p
droplets :: Authentication -> (MonadIO m) => m (Maybe DropletsResponse)
droplets = request "droplets" ""
newDroplet :: NewDropletRequest -> Authentication -> (MonadIO m) => m (Maybe NewDropletResponse)
newDroplet r = requestObject "droplets/new" (mkParams r)
regions :: Authentication -> (MonadIO m) => m (Maybe RegionsResponse)
regions = request "regions" ""
sizes :: Authentication -> (MonadIO m) => m (Maybe SizesResponse)
sizes = request "sizes" ""
images :: Authentication -> (MonadIO m) => m (Maybe ImagesResponse)
images = request "images" ""
sshKeys :: Authentication -> (MonadIO m) => m (Maybe SSHsResponse)
sshKeys = request "ssh_keys" ""
event :: Integer -> Authentication -> (MonadIO m) => m (Maybe EventResponse)
event i = requestObject ("events/" ++ show i ++ "/") ""
|
relrod/digitalocean
|
src/Network/DigitalOcean.hs
|
bsd-3-clause
| 8,298
| 0
| 18
| 1,753
| 2,869
| 1,594
| 1,275
| 237
| 1
|
module Shakefiles.Shellcheck (rules) where
import Development.Shake
import Development.Shake.Command
import Development.Shake.FilePath
import Development.Shake.Util
rules shellcheck = do
phony "shellcheck" $ need [ "_build/shellcheck.ok" ]
"_build/shellcheck.ok" %> \out -> do
scriptFiles <- getDirectoryFiles ""
[ "build.sh"
, "tests/run-tests.sh"
, "package/elm-tooling/build.sh"
, "package/elm-tooling/generate.sh"
, "package/linux/build-in-docker.sh"
, "package/linux/build-package.sh"
, "package/mac/build-package.sh"
, "package/nix/build.sh"
, "package/nix/generate_derivation.sh"
, "package/win/build-package.sh"
]
let oks = ["_build" </> f <.> "shellcheck.ok" | f <- scriptFiles]
need oks
writeFile' out (unlines scriptFiles)
"_build//*.shellcheck.ok" %> \out -> do
let script = dropDirectory1 $ dropExtension $ dropExtension out
need [ shellcheck, script ]
cmd_ shellcheck "-s" "bash" script
writeFile' out ""
|
avh4/elm-format
|
Shakefiles/Shellcheck.hs
|
bsd-3-clause
| 1,132
| 0
| 16
| 311
| 224
| 115
| 109
| 27
| 1
|
{-# LANGUAGE OverloadedStrings #-}
module TestOrdECMWithTestSequenceInvalidating (
testWithTestSequenceInvalidating
) where
import Caching.ExpiringCacheMap.OrdECM (newECMForM, lookupECM, CacheSettings(..), consistentDuration, invalidate, invalidateCache, keysCached, keysNotExpired)
import qualified Caching.ExpiringCacheMap.Utils.TestSequence as TestSeq
import TestECMWithTestSequenceCommonInvalidating
import qualified Data.ByteString.Char8 as BS
import System.Exit (exitFailure)
testWithTestSequenceInvalidating = do
(TestSeq.TestSequenceState (_, events', _), return_value) <- TestSeq.runTestSequence test'
(TestSeq.TestSequenceState (_, events'', _), return_value) <- TestSeq.runTestSequence test''
(TestSeq.TestSequenceState (_, events''', _), return_value) <- TestSeq.runTestSequence test'''
(TestSeq.TestSequenceState (_, events'''', _), return_value) <- TestSeq.runTestSequence test''''
(TestSeq.TestSequenceState (_, events''''', _), return_value) <- TestSeq.runTestSequence test'''''
(TestSeq.TestSequenceState (_, events'''''', _), return_value) <- TestSeq.runTestSequence test''''''
if pattern'I (filt events') &&
pattern''I (filt events'') &&
pattern'''I (filt events''') &&
pattern''''I (filt events'''') &&
pattern'''''I (filt events''''') &&
pattern''''''I (filt events'''''')
then do
putStrLn "Passed TestOrdECMWithTestSequenceInvalidating"
-- printOutEvents events' events'' events''' events''''
return ()
else do
printOutFailedPatternI "TestOrdECMWithTestSequenceInvalidating.testWithTestSequenceInvalidating"
(filt events') (filt events'') (filt events''') (filt events'''') (filt events''''') (filt events'''''')
printOutEventsI events' events'' events''' events'''' events''''' events''''''
exitFailure
where
filt = filter someEventsOnlyI . reverse
commonreadnumber =
(\state _id -> do number <- TestSeq.readNumber
return (state, number))
newTestECM valreq timecheck =
newECMForM valreq
(TestSeq.getCurrentTime >>= return)
timecheck
(CacheWithLRUList 6 6 12)
TestSeq.newTestSVar TestSeq.enterTestSVar TestSeq.readTestSVar
test' = do
filecache <- newTestECM
(consistentDuration 100 commonreadnumber) -- Duration between access and expiry time
12000 -- Time check frequency
testLookupsI (lookupECM filecache) (invalidate filecache) (invalidateCache filecache) (keysCached filecache) (keysNotExpired filecache)
test'' = do
filecache <- newTestECM
(consistentDuration 100 commonreadnumber) -- Duration between access and expiry time
1 -- Time check frequency
testLookupsI (lookupECM filecache) (invalidate filecache) (invalidateCache filecache) (keysCached filecache) (keysNotExpired filecache)
test''' = do
filecache <- newTestECM
(consistentDuration 1 commonreadnumber) -- Duration between access and expiry time
12000 -- Time check frequency
testLookupsI (lookupECM filecache) (invalidate filecache) (invalidateCache filecache) (keysCached filecache) (keysNotExpired filecache)
test'''' = do
filecache <- newTestECM
(consistentDuration 1 commonreadnumber) -- Duration between access and expiry time
1 -- Time check frequency
testLookupsI (lookupECM filecache) (invalidate filecache) (invalidateCache filecache) (keysCached filecache) (keysNotExpired filecache)
test''''' = do
filecache <- newTestECM
(consistentDuration 50 commonreadnumber) -- Duration between access and expiry time
12000 -- Time check frequency
testLookupsI (lookupECM filecache) (invalidate filecache) (invalidateCache filecache) (keysCached filecache) (keysNotExpired filecache)
test'''''' = do
filecache <- newTestECM
(consistentDuration 50 commonreadnumber) -- Duration between access and expiry time
1 -- Time check frequency
testLookupsI (lookupECM filecache) (invalidate filecache) (invalidateCache filecache) (keysCached filecache) (keysNotExpired filecache)
|
elblake/expiring-cache-map
|
tests/TestOrdECMWithTestSequenceInvalidating.hs
|
bsd-3-clause
| 4,174
| 0
| 15
| 791
| 974
| 500
| 474
| 69
| 2
|
{-# LANGUAGE ForeignFunctionInterface #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Test.Hspec.Json.GHCJS (
genericToJSValTests,
genericFromJSValTests,
genericAesonToJSVal,
genericJSValToAeson,
genericJSValRoundtrip,
genericAesonRoundtrip,
-- re-export
Proxy(..),
) where
import Control.Arrow
import Control.Exception
import Control.Monad
import qualified Data.Aeson as Aeson
import Data.Aeson as Aeson hiding (encode)
import Data.ByteString.Lazy (ByteString)
import Data.JSString
import Data.Proxy
import Data.String.Conversions
import Data.Typeable
import GHCJS.Marshal as JSVal
import GHCJS.Types
import Test.Hspec
import Test.QuickCheck
-- | Generically create an hspec 'Spec' that tests whether the 'ToJSVal'
-- and the 'ToJSON' instances for the given datatype match.
genericToJSValTests :: forall a .
(Typeable a, Show a, Arbitrary a, ToJSON a, ToJSVal a) =>
Proxy a -> Spec
genericToJSValTests proxy = do
describe ("ToJSVal " ++ show (typeRep proxy)) $ do
it "converts to JSON compatible with aeson" $ do
property $ \ (a :: a) -> do
jsVal <- toJSVal a
jsValAsByteString <- jsonStringify jsVal
Aeson.encode a `shouldBeSameJson` jsValAsByteString
shouldBeSameJson :: ByteString -> ByteString -> IO ()
shouldBeSameJson a b = do
let dec :: ByteString -> Value
dec s = either (\ err -> error ("invalid json: " ++ err ++ "\n" ++ cs s)) id $
eitherDecode s
dec a `shouldBe` dec b
genericFromJSValTests :: forall a .
(Typeable a, Eq a, Show a, Arbitrary a, ToJSON a, FromJSON a, FromJSVal a) =>
Proxy a -> Spec
genericFromJSValTests proxy = do
describe ("FromJSVal " ++ show (typeRep proxy)) $ do
it "converts from JSON compatible with aeson" $ do
property $ \ (a :: a) -> do
let json :: ByteString = Aeson.encode a
expected :: Maybe a = decode json
expected `shouldBe` Just a
jsVal :: JSVal <- jsonParse json
result :: Maybe a <- fromJSVal jsVal
result `shouldBe` expected
-- | Returns tests that make sure that values can be serialized to JSON using
-- `aeson` and then read back into Haskell values using `fromJSVal`.
--
-- This is a common case when transferring values from a server to a client.
genericAesonToJSVal :: forall a .
(Typeable a, Show a, Eq a, Arbitrary a, ToJSON a, FromJSVal a) =>
Proxy a -> Spec
genericAesonToJSVal proxy = do
describe ("JSON encoding of " ++ show (typeRep proxy)) $ do
it "allows to encode values with aeson and decode with FromJSVal" $ do
shouldBeIdentity proxy $
Aeson.encode >>> jsonParse >=> fromJSValIO
-- | Returns tests that make sure that values can be serialized to JSON using
-- `toJSVal` and then read back into Haskell values using `aeson`.
--
-- This is a common case when sending values from a client to a server.
genericJSValToAeson :: forall a .
(Typeable a, Show a, Eq a, Arbitrary a, ToJSVal a, FromJSON a) =>
Proxy a -> Spec
genericJSValToAeson proxy = do
describe ("JSON encoding of " ++ show (typeRep proxy)) $ do
it "allows to encode values with ToJSVal and decode with aeson" $ do
shouldBeIdentity proxy $
toJSVal >=> jsonStringify >=> aesonDecodeIO
genericJSValRoundtrip :: forall a .
(Typeable a, Eq a, Show a, Arbitrary a, ToJSVal a, FromJSVal a) =>
Proxy a -> Spec
genericJSValRoundtrip proxy = do
describe ("JSON encoding of " ++ show (typeRep proxy)) $ do
it "allows to encode values with JSVal and read them back" $ do
shouldBeIdentity proxy $
toJSVal >=> fromJSValIO
genericAesonRoundtrip :: forall a .
(Typeable a, Eq a, Show a, Arbitrary a, ToJSON a, FromJSON a) =>
Proxy a -> Spec
genericAesonRoundtrip proxy = do
describe ("JSON encoding of " ++ show (typeRep proxy)) $ do
it "allows to encode values with aeson and read them back" $ do
shouldBeIdentity proxy $
Aeson.encode >>> aesonDecodeIO
-- * utils
shouldBeIdentity :: (Eq a, Show a, Arbitrary a) =>
Proxy a -> (a -> IO a) -> Property
shouldBeIdentity Proxy function =
property $ \ (a :: a) -> do
function a `shouldReturn` a
fromJSValIO :: forall a . Typeable a => FromJSVal a => JSVal -> IO a
fromJSValIO jsVal = fromJSVal jsVal >>= \ case
Just r -> return r
Nothing -> throwIO $ ErrorCall
("fromJSVal couldn't convert to type " ++ show (typeRep (Proxy :: Proxy a)))
aesonDecodeIO :: FromJSON a => ByteString -> IO a
aesonDecodeIO bs = case eitherDecode bs of
Right a -> return a
Left msg -> throwIO $ ErrorCall
("aeson couldn't parse value: " ++ msg)
-- * ffi json stuff
jsonStringify :: JSVal -> IO ByteString
jsonStringify jsVal = cs <$> unpack <$> json_stringify jsVal
foreign import javascript unsafe
"JSON.stringify($1)"
json_stringify :: JSVal -> IO JSString
jsonParse :: ByteString -> IO JSVal
jsonParse = json_parse . pack . cs
foreign import javascript unsafe
"JSON.parse($1)"
json_parse :: JSString -> IO JSVal
|
plow-technologies/ghcjs-hspec-json
|
src/Test/Hspec/Json/GHCJS.hs
|
bsd-3-clause
| 5,100
| 9
| 22
| 1,184
| 1,424
| 721
| 703
| 109
| 2
|
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances #-}
module DyNet.Expr (
-- * Input operations
input,
input'',
parameter,
lookupParameter,
constParameter,
constLookupParameter,
lookup,
-- lookup,
lookup',
-- constLookup,
constLookup',
zeroes,
-- ones,
-- constant,
randomNormal,
randomBernoulli,
randomUniform,
randomGumbel,
-- * Arithmetic operations
neg,
add,
mul,
div,
sub,
cdiv,
cmult,
colwiseAdd,
affineTransform,
sum,
sumCols,
sumBatches,
sumElems,
momentBatches,
momentElems,
momentDim,
meanElems,
meanBatches,
meanDim,
stdDim,
stdElems,
stdBatches,
average,
sqrt,
abs,
erf,
tanh,
exp,
square,
cube,
log,
lgamma,
elu,
selu,
logistic,
rectify,
softsign,
pow,
max,
dotProduct,
bmin,
bmax,
-- * Probability / loss operations
softmax,
logSoftmax,
logSoftmax',
logsumexp,
pickneglogsoftmax,
pickneglogsoftmax',
hinge,
hinge',
-- sparsemax
-- sparsemaxLoss
squaredDistance,
squaredNorm,
l2Norm,
huberDistance,
binaryLogLoss,
pairwiseRankLoss,
poissonLoss,
l1Distance,
-- * Flow operations
nobackprop,
flipGradient,
reshape,
transpose,
selectRows,
selectCols,
-- pick,
pick',
pickRange,
pickBatchElems,
pickBatchElem,
concatCols,
concat,
concat',
concatToBatch,
maxDim,
minDim,
-- * Noise operations
noise,
dropout,
dropoutBatch,
dropoutDim,
blockDropout,
-- * Convolution operations
filter1dNarrow,
kmaxPooling,
foldRows,
kmhNgram,
conv2d,
conv2d',
maxpooling2d,
-- * Tensor operations
contract3d_1d,
contract3d_1d',
contract3d_1d_1d,
contract3d_1d_1d',
-- * Linear algebra operations
inverse,
logdet,
traceOfProduct,
-- * Normalization operations
layerNorm,
weightNorm,
) where
import Prelude hiding ( tanh, concat, sum, lookup,
exp, sqrt, abs, log, max, div )
import DyNet.Internal.Expr
import DyNet.Internal.Core
import DyNet.Core
class DyNum a b where
-- | @x \`add\` y@ where both x and y are either 'IsExpr' or 'Float'
add :: a -> b -> IO Expression
-- | @x \`mul\` y@ where both x and y are either 'IsExpr' or 'Float'
mul :: a -> b -> IO Expression
-- | @x \`div\` y@ where the case x is 'IsExpr' and y either of 'IsExpr' or 'Float' is valid.
div :: a -> b -> IO Expression
-- | @x \`sub\` y@ where both x and y are either 'IsExpr' or 'Float'
sub :: a -> b -> IO Expression
instance (IsExpr e1, IsExpr e2) => DyNum e1 e2 where
add = op_add
mul = op_mul
div _ _ = error $ "no implementation"
sub x y = x `op_add` (neg y)
instance IsExpr e => DyNum e Float where
add = op_scalar_add
mul = op_scalar_mul
div = op_scalar_div
sub x y = neg (y `op_scalar_sub` x)
instance IsExpr e => DyNum Float e where
add = flip op_scalar_add
mul = flip op_scalar_mul
div _ _ = error $ "no implementation"
sub = op_scalar_sub
|
masashi-y/dynet.hs
|
src/DyNet/Expr.hs
|
bsd-3-clause
| 3,258
| 0
| 9
| 1,005
| 663
| 411
| 252
| 137
| 0
|
{-# LANGUAGE CPP #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FunctionalDependencies #-}
#ifdef TRUSTWORTHY
{-# LANGUAGE Trustworthy #-}
#endif
-----------------------------------------------------------------------------
-- |
-- Module : Control.Lens.Cons
-- Copyright : (C) 2012-14 Edward Kmett
-- License : BSD-style (see the file LICENSE)
-- Maintainer : Edward Kmett <ekmett@gmail.com>
-- Stability : experimental
-- Portability : non-portable
--
-----------------------------------------------------------------------------
module Control.Lens.Cons
(
-- * Cons
Cons(..)
, (<|)
, cons
, uncons
, _head, _tail
-- * Snoc
, Snoc(..)
, (|>)
, snoc
, unsnoc
, _init, _last
) where
import Control.Lens.Equality (simply)
import Control.Lens.Fold
import Control.Lens.Prism
import Control.Lens.Review
import Control.Lens.Tuple
import Control.Lens.Type
import qualified Data.ByteString as StrictB
import qualified Data.ByteString.Lazy as LazyB
import Data.Monoid
import qualified Data.Sequence as Seq
import Data.Sequence hiding ((<|), (|>))
import qualified Data.Text as StrictT
import qualified Data.Text.Lazy as LazyT
import Data.Vector (Vector)
import qualified Data.Vector as Vector
import Data.Vector.Storable (Storable)
import qualified Data.Vector.Storable as Storable
import Data.Vector.Primitive (Prim)
import qualified Data.Vector.Primitive as Prim
import Data.Vector.Unboxed (Unbox)
import qualified Data.Vector.Unboxed as Unbox
import Data.Word
{-# ANN module "HLint: ignore Eta reduce" #-}
-- $setup
-- >>> :set -XNoOverloadedStrings
-- >>> import Control.Lens
-- >>> import Debug.SimpleReflect.Expr
-- >>> import Debug.SimpleReflect.Vars as Vars hiding (f,g)
-- >>> let f :: Expr -> Expr; f = Debug.SimpleReflect.Vars.f
-- >>> let g :: Expr -> Expr; g = Debug.SimpleReflect.Vars.g
infixr 5 <|, `cons`
infixl 5 |>, `snoc`
------------------------------------------------------------------------------
-- Cons
------------------------------------------------------------------------------
-- | This class provides a way to attach or detach elements on the left
-- side of a structure in a flexible manner.
class Cons s t a b | s -> a, t -> b, s b -> t, t a -> s where
-- |
--
-- @
-- '_Cons' :: 'Prism' [a] [b] (a, [a]) (b, [b])
-- '_Cons' :: 'Prism' ('Seq' a) ('Seq' b) (a, 'Seq' a) (b, 'Seq' b)
-- '_Cons' :: 'Prism' ('Vector' a) ('Vector' b) (a, 'Vector' a) (b, 'Vector' b)
-- '_Cons' :: 'Prism'' 'String' ('Char', 'String')
-- '_Cons' :: 'Prism'' 'StrictT.Text' ('Char', 'StrictT.Text')
-- '_Cons' :: 'Prism'' 'StrictB.ByteString' ('Word8', 'StrictB.ByteString')
-- @
_Cons :: Prism s t (a,s) (b,t)
instance Cons [a] [b] a b where
_Cons = prism (uncurry (:)) $ \ aas -> case aas of
(a:as) -> Right (a, as)
[] -> Left []
{-# INLINE _Cons #-}
instance Cons (Seq a) (Seq b) a b where
_Cons = prism (uncurry (Seq.<|)) $ \aas -> case viewl aas of
a :< as -> Right (a, as)
EmptyL -> Left mempty
{-# INLINE _Cons #-}
instance Cons StrictB.ByteString StrictB.ByteString Word8 Word8 where
_Cons = prism' (uncurry StrictB.cons) StrictB.uncons
{-# INLINE _Cons #-}
instance Cons LazyB.ByteString LazyB.ByteString Word8 Word8 where
_Cons = prism' (uncurry LazyB.cons) LazyB.uncons
{-# INLINE _Cons #-}
instance Cons StrictT.Text StrictT.Text Char Char where
_Cons = prism' (uncurry StrictT.cons) StrictT.uncons
{-# INLINE _Cons #-}
instance Cons LazyT.Text LazyT.Text Char Char where
_Cons = prism' (uncurry LazyT.cons) LazyT.uncons
{-# INLINE _Cons #-}
instance Cons (Vector a) (Vector b) a b where
_Cons = prism (uncurry Vector.cons) $ \v ->
if Vector.null v
then Left Vector.empty
else Right (Vector.unsafeHead v, Vector.unsafeTail v)
{-# INLINE _Cons #-}
instance (Prim a, Prim b) => Cons (Prim.Vector a) (Prim.Vector b) a b where
_Cons = prism (uncurry Prim.cons) $ \v ->
if Prim.null v
then Left Prim.empty
else Right (Prim.unsafeHead v, Prim.unsafeTail v)
{-# INLINE _Cons #-}
instance (Storable a, Storable b) => Cons (Storable.Vector a) (Storable.Vector b) a b where
_Cons = prism (uncurry Storable.cons) $ \v ->
if Storable.null v
then Left Storable.empty
else Right (Storable.unsafeHead v, Storable.unsafeTail v)
{-# INLINE _Cons #-}
instance (Unbox a, Unbox b) => Cons (Unbox.Vector a) (Unbox.Vector b) a b where
_Cons = prism (uncurry Unbox.cons) $ \v ->
if Unbox.null v
then Left Unbox.empty
else Right (Unbox.unsafeHead v, Unbox.unsafeTail v)
{-# INLINE _Cons #-}
-- | 'cons' an element onto a container.
--
-- This is an infix alias for 'cons'.
--
-- >>> a <| []
-- [a]
--
-- >>> a <| [b, c]
-- [a,b,c]
--
-- >>> a <| Seq.fromList []
-- fromList [a]
--
-- >>> a <| Seq.fromList [b, c]
-- fromList [a,b,c]
(<|) :: Cons s s a a => a -> s -> s
(<|) = curry (simply review _Cons)
{-# INLINE (<|) #-}
-- | 'cons' an element onto a container.
--
-- >>> cons a []
-- [a]
--
-- >>> cons a [b, c]
-- [a,b,c]
--
-- >>> cons a (Seq.fromList [])
-- fromList [a]
--
-- >>> cons a (Seq.fromList [b, c])
-- fromList [a,b,c]
cons :: Cons s s a a => a -> s -> s
cons = curry (simply review _Cons)
{-# INLINE cons #-}
-- | Attempt to extract the left-most element from a container, and a version of the container without that element.
--
-- >>> uncons []
-- Nothing
--
-- >>> uncons [a, b, c]
-- Just (a,[b,c])
uncons :: Cons s s a a => s -> Maybe (a, s)
uncons = simply preview _Cons
{-# INLINE uncons #-}
-- | A 'Traversal' reading and writing to the 'head' of a /non-empty/ container.
--
-- >>> [a,b,c]^? _head
-- Just a
--
-- >>> [a,b,c] & _head .~ d
-- [d,b,c]
--
-- >>> [a,b,c] & _head %~ f
-- [f a,b,c]
--
-- >>> [] & _head %~ f
-- []
--
-- >>> [1,2,3]^?!_head
-- 1
--
-- >>> []^?_head
-- Nothing
--
-- >>> [1,2]^?_head
-- Just 1
--
-- >>> [] & _head .~ 1
-- []
--
-- >>> [0] & _head .~ 2
-- [2]
--
-- >>> [0,1] & _head .~ 2
-- [2,1]
--
-- This isn't limited to lists.
--
-- For instance you can also 'Data.Traversable.traverse' the head of a 'Seq':
--
-- >>> Seq.fromList [a,b,c,d] & _head %~ f
-- fromList [f a,b,c,d]
--
-- >>> Seq.fromList [] ^? _head
-- Nothing
--
-- >>> Seq.fromList [a,b,c,d] ^? _head
-- Just a
--
-- @
-- '_head' :: 'Traversal'' [a] a
-- '_head' :: 'Traversal'' ('Seq' a) a
-- '_head' :: 'Traversal'' ('Vector' a) a
-- @
_head :: Cons s s a a => Traversal' s a
_head = _Cons._1
{-# INLINE _head #-}
-- | A 'Traversal' reading and writing to the 'tail' of a /non-empty/ container.
--
-- >>> [a,b] & _tail .~ [c,d,e]
-- [a,c,d,e]
--
-- >>> [] & _tail .~ [a,b]
-- []
--
-- >>> [a,b,c,d,e] & _tail.traverse %~ f
-- [a,f b,f c,f d,f e]
--
-- >>> [1,2] & _tail .~ [3,4,5]
-- [1,3,4,5]
--
-- >>> [] & _tail .~ [1,2]
-- []
--
-- >>> [a,b,c]^?_tail
-- Just [b,c]
--
-- >>> [1,2]^?!_tail
-- [2]
--
-- >>> "hello"^._tail
-- "ello"
--
-- >>> ""^._tail
-- ""
--
-- This isn't limited to lists. For instance you can also 'Control.Traversable.traverse' the tail of a 'Seq'.
--
-- >>> Seq.fromList [a,b] & _tail .~ Seq.fromList [c,d,e]
-- fromList [a,c,d,e]
--
-- >>> Seq.fromList [a,b,c] ^? _tail
-- Just (fromList [b,c])
--
-- >>> Seq.fromList [] ^? _tail
-- Nothing
--
-- @
-- '_tail' :: 'Traversal'' [a] [a]
-- '_tail' :: 'Traversal'' ('Seq' a) ('Seq' a)
-- '_tail' :: 'Traversal'' ('Vector' a) ('Vector' a)
-- @
_tail :: Cons s s a a => Traversal' s s
_tail = _Cons._2
{-# INLINE _tail #-}
------------------------------------------------------------------------------
-- Snoc
------------------------------------------------------------------------------
-- | This class provides a way to attach or detach elements on the right
-- side of a structure in a flexible manner.
class Snoc s t a b | s -> a, t -> b, s b -> t, t a -> s where
-- |
--
-- @
-- '_Snoc' :: 'Prism' [a] [b] ([a], a) ([b], b)
-- '_Snoc' :: 'Prism' ('Seq' a) ('Seq' b) ('Seq' a, a) ('Seq' b, b)
-- '_Snoc' :: 'Prism' ('Vector' a) ('Vector' b) ('Vector' a, a) ('Vector' b, b)
-- '_Snoc' :: 'Prism'' 'String' ('String', 'Char')
-- '_Snoc' :: 'Prism'' 'StrictT.Text' ('StrictT.Text', 'Char')
-- '_Snoc' :: 'Prism'' 'StrictB.ByteString' ('StrictB.ByteString', 'Word8')
-- @
_Snoc :: Prism s t (s,a) (t,b)
instance Snoc [a] [b] a b where
_Snoc = prism (\(as,a) -> as Prelude.++ [a]) $ \aas -> if Prelude.null aas
then Left []
else Right (Prelude.init aas, Prelude.last aas)
{-# INLINE _Snoc #-}
instance Snoc (Seq a) (Seq b) a b where
_Snoc = prism (uncurry (Seq.|>)) $ \aas -> case viewr aas of
as :> a -> Right (as, a)
EmptyR -> Left mempty
{-# INLINE _Snoc #-}
instance Snoc (Vector a) (Vector b) a b where
_Snoc = prism (uncurry Vector.snoc) $ \v -> if Vector.null v
then Left Vector.empty
else Right (Vector.unsafeInit v, Vector.unsafeLast v)
{-# INLINE _Snoc #-}
instance (Prim a, Prim b) => Snoc (Prim.Vector a) (Prim.Vector b) a b where
_Snoc = prism (uncurry Prim.snoc) $ \v -> if Prim.null v
then Left Prim.empty
else Right (Prim.unsafeInit v, Prim.unsafeLast v)
{-# INLINE _Snoc #-}
instance (Storable a, Storable b) => Snoc (Storable.Vector a) (Storable.Vector b) a b where
_Snoc = prism (uncurry Storable.snoc) $ \v -> if Storable.null v
then Left Storable.empty
else Right (Storable.unsafeInit v, Storable.unsafeLast v)
{-# INLINE _Snoc #-}
instance (Unbox a, Unbox b) => Snoc (Unbox.Vector a) (Unbox.Vector b) a b where
_Snoc = prism (uncurry Unbox.snoc) $ \v -> if Unbox.null v
then Left Unbox.empty
else Right (Unbox.unsafeInit v, Unbox.unsafeLast v)
{-# INLINE _Snoc #-}
instance Snoc StrictB.ByteString StrictB.ByteString Word8 Word8 where
_Snoc = prism (uncurry StrictB.snoc) $ \v -> if StrictB.null v
then Left StrictB.empty
else Right (StrictB.init v, StrictB.last v)
{-# INLINE _Snoc #-}
instance Snoc LazyB.ByteString LazyB.ByteString Word8 Word8 where
_Snoc = prism (uncurry LazyB.snoc) $ \v -> if LazyB.null v
then Left LazyB.empty
else Right (LazyB.init v, LazyB.last v)
{-# INLINE _Snoc #-}
instance Snoc StrictT.Text StrictT.Text Char Char where
_Snoc = prism (uncurry StrictT.snoc) $ \v -> if StrictT.null v
then Left StrictT.empty
else Right (StrictT.init v, StrictT.last v)
{-# INLINE _Snoc #-}
instance Snoc LazyT.Text LazyT.Text Char Char where
_Snoc = prism (uncurry LazyT.snoc) $ \v -> if LazyT.null v
then Left LazyT.empty
else Right (LazyT.init v, LazyT.last v)
{-# INLINE _Snoc #-}
-- | A 'Traversal' reading and replacing all but the a last element of a /non-empty/ container.
--
-- >>> [a,b,c,d]^?_init
-- Just [a,b,c]
--
-- >>> []^?_init
-- Nothing
--
-- >>> [a,b] & _init .~ [c,d,e]
-- [c,d,e,b]
--
-- >>> [] & _init .~ [a,b]
-- []
--
-- >>> [a,b,c,d] & _init.traverse %~ f
-- [f a,f b,f c,d]
--
-- >>> [1,2,3]^?_init
-- Just [1,2]
--
-- >>> [1,2,3,4]^?!_init
-- [1,2,3]
--
-- >>> "hello"^._init
-- "hell"
--
-- >>> ""^._init
-- ""
--
-- @
-- '_init' :: 'Traversal'' [a] [a]
-- '_init' :: 'Traversal'' ('Seq' a) ('Seq' a)
-- '_init' :: 'Traversal'' ('Vector' a) ('Vector' a)
-- @
_init :: Snoc s s a a => Traversal' s s
_init = _Snoc._1
{-# INLINE _init #-}
-- | A 'Traversal' reading and writing to the last element of a /non-empty/ container.
--
-- >>> [a,b,c]^?!_last
-- c
--
-- >>> []^?_last
-- Nothing
--
-- >>> [a,b,c] & _last %~ f
-- [a,b,f c]
--
-- >>> [1,2]^?_last
-- Just 2
--
-- >>> [] & _last .~ 1
-- []
--
-- >>> [0] & _last .~ 2
-- [2]
--
-- >>> [0,1] & _last .~ 2
-- [0,2]
--
-- This 'Traversal' is not limited to lists, however. We can also work with other containers, such as a 'Vector'.
--
-- >>> Vector.fromList "abcde" ^? _last
-- Just 'e'
--
-- >>> Vector.empty ^? _last
-- Nothing
--
-- >>> Vector.fromList "abcde" & _last .~ 'Q'
-- fromList "abcdQ"
--
-- @
-- '_last' :: 'Traversal'' [a] a
-- '_last' :: 'Traversal'' ('Seq' a) a
-- '_last' :: 'Traversal'' ('Vector' a) a
-- @
_last :: Snoc s s a a => Traversal' s a
_last = _Snoc._2
{-# INLINE _last #-}
-- | 'snoc' an element onto the end of a container.
--
-- This is an infix alias for 'snoc'.
--
-- >>> Seq.fromList [] |> a
-- fromList [a]
--
-- >>> Seq.fromList [b, c] |> a
-- fromList [b,c,a]
--
-- >>> LazyT.pack "hello" |> '!'
-- "hello!"
(|>) :: Snoc s s a a => s -> a -> s
(|>) = curry (simply review _Snoc)
{-# INLINE (|>) #-}
-- | 'snoc' an element onto the end of a container.
--
-- >>> snoc (Seq.fromList []) a
-- fromList [a]
--
-- >>> snoc (Seq.fromList [b, c]) a
-- fromList [b,c,a]
--
-- >>> snoc (LazyT.pack "hello") '!'
-- "hello!"
snoc :: Snoc s s a a => s -> a -> s
snoc = curry (simply review _Snoc)
{-# INLINE snoc #-}
-- | Attempt to extract the right-most element from a container, and a version of the container without that element.
--
-- >>> unsnoc (LazyT.pack "hello!")
-- Just ("hello",'!')
--
-- >>> unsnoc (LazyT.pack "")
-- Nothing
--
-- >>> unsnoc (Seq.fromList [b,c,a])
-- Just (fromList [b,c],a)
--
-- >>> unsnoc (Seq.fromList [])
-- Nothing
unsnoc :: Snoc s s a a => s -> Maybe (s, a)
unsnoc s = simply preview _Snoc s
{-# INLINE unsnoc #-}
|
hvr/lens
|
src/Control/Lens/Cons.hs
|
bsd-3-clause
| 13,202
| 0
| 12
| 2,660
| 2,750
| 1,623
| 1,127
| 172
| 1
|
{-# LANGUAGE PatternGuards #-}
module Ant.Search
( SearchNode (..)
, search
, searchPath
, searchN
)
where
import qualified Data.IntSet as S
import Data.Maybe
import Data.PSQueue ( Binding(..) )
import qualified Data.PSQueue as Q
type Queue m = Q.PSQ SearchNode m
data SearchNode = SearchNode
{ snKey :: Int
, snDistance :: Int
, snPred :: Maybe (SearchNode)
}
instance Show (SearchNode) where
show (SearchNode r d _) = show r ++ " dist: " ++ show d
instance Eq (SearchNode) where
(==) sn sn' = snKey sn == snKey sn'
instance Ord (SearchNode) where
compare sn sn' = snKey sn `compare` snKey sn'
searchPath :: SearchNode -> [Int]
searchPath = (`path` []) where
path (SearchNode r _ Nothing) xs = r : xs
path (SearchNode r _ (Just p)) xs = path p (r : xs)
insertMin :: (Ord m) => SearchNode -> m -> Queue m -> Queue m
insertMin node p = Q.alter alter node where
alter (Just p') = Just (min p p')
alter Nothing = Just p
{-# INLINE insertMin #-}
search :: (Ord m) => (SearchNode -> [SearchNode]) -> (SearchNode -> m) -> Int -> [SearchNode]
search succ metric r = searchN succ metric [r]
searchN :: (Ord m) => (SearchNode -> [SearchNode]) -> (SearchNode -> m) -> [Int] -> [SearchNode]
searchN succ metric rs = search (S.fromList rs) (Q.fromList (map toPriorityNode rs)) where
toPriorityNode r = node :-> metric node
where node = SearchNode r 0 Nothing
search seen queue | Nothing <- view = []
| Just ((node :-> _), queue') <- view = next node seen queue'
where view = Q.minView queue
next node seen queue = node : (search seen' queue')
where
queue' = foldr insert queue successors
seen' = S.insert (snKey node) seen
successors = filter (flip S.notMember seen . snKey) (succ node)
insert node = insertMin node (metric node)
|
Saulzar/Ants
|
Ant/Search.hs
|
bsd-3-clause
| 2,063
| 0
| 14
| 656
| 757
| 401
| 356
| 44
| 2
|
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
---------------------------------------------------------
--
-- Module : Yesod.Handler
-- Copyright : Michael Snoyman
-- License : BSD3
--
-- Maintainer : Michael Snoyman <michael@snoyman.com>
-- Stability : stable
-- Portability : portable
--
-- Define Handler stuff.
--
---------------------------------------------------------
module Yesod.Core.Handler
( -- * Handler monad
HandlerT
, HandlerFor
-- ** Read information from handler
, getYesod
, getsYesod
, getUrlRender
, getUrlRenderParams
, getPostParams
, getCurrentRoute
, getRequest
, waiRequest
, runRequestBody
, rawRequestBody
-- ** Request information
-- *** Request datatype
, RequestBodyContents
, YesodRequest (..)
, FileInfo
, fileName
, fileContentType
, fileSource
, fileSourceByteString
, fileMove
-- *** Convenience functions
, languages
-- *** Lookup parameters
, lookupGetParam
, lookupPostParam
, lookupCookie
, lookupFile
, lookupHeader
-- **** Lookup authentication data
, lookupBasicAuth
, lookupBearerAuth
-- **** Multi-lookup
, lookupGetParams
, lookupPostParams
, lookupCookies
, lookupFiles
, lookupHeaders
-- * Responses
-- ** Pure
, respond
-- ** Streaming
, respondSource
, sendChunk
, sendFlush
, sendChunkBS
, sendChunkLBS
, sendChunkText
, sendChunkLazyText
, sendChunkHtml
-- ** Redirecting
, RedirectUrl (..)
, redirect
, redirectWith
, redirectToPost
, Fragment(..)
-- ** Errors
, notFound
, badMethod
, notAuthenticated
, permissionDenied
, permissionDeniedI
, invalidArgs
, invalidArgsI
-- ** Short-circuit responses
-- $rollbackWarning
, sendFile
, sendFilePart
, sendResponse
, sendResponseStatus
-- ** Type specific response with custom status
, sendStatusJSON
, sendResponseCreated
, sendResponseNoContent
, sendWaiResponse
, sendWaiApplication
, sendRawResponse
, sendRawResponseNoConduit
, notModified
-- * Different representations
-- $representations
, selectRep
, provideRep
, provideRepType
, ProvidedRep
-- * Setting headers
, setCookie
, getExpires
, deleteCookie
, addHeader
, setHeader
, replaceOrAddHeader
, setLanguage
, addContentDispositionFileName
-- ** Content caching and expiration
, cacheSeconds
, neverExpires
, alreadyExpired
, expiresAt
, setEtag
, setWeakEtag
-- * Session
, SessionMap
, lookupSession
, lookupSessionBS
, getSession
, setSession
, setSessionBS
, deleteSession
, clearSession
-- ** Ultimate destination
, setUltDest
, setUltDestCurrent
, setUltDestReferer
, redirectUltDest
, clearUltDest
-- ** Messages
, addMessage
, addMessageI
, getMessages
, setMessage
, setMessageI
, getMessage
-- * Subsites
, SubHandlerFor
, getSubYesod
, getRouteToParent
, getSubCurrentRoute
-- * Helpers for specific content
-- ** Hamlet
, hamletToRepHtml
, giveUrlRenderer
, withUrlRenderer
-- ** Misc
, newIdent
-- * Lifting
, handlerToIO
, forkHandler
-- * i18n
, getMessageRender
-- * Per-request caching
, cached
, cacheGet
, cacheSet
, cachedBy
, cacheByGet
, cacheBySet
-- * AJAX CSRF protection
-- $ajaxCSRFOverview
-- ** Setting CSRF Cookies
, setCsrfCookie
, setCsrfCookieWithCookie
, defaultCsrfCookieName
-- ** Looking up CSRF Headers
, checkCsrfHeaderNamed
, hasValidCsrfHeaderNamed
, defaultCsrfHeaderName
-- ** Looking up CSRF POST Parameters
, hasValidCsrfParamNamed
, checkCsrfParamNamed
, defaultCsrfParamName
-- ** Checking CSRF Headers or POST Parameters
, checkCsrfHeaderOrParam
) where
import Data.Time (UTCTime, addUTCTime,
getCurrentTime)
import Yesod.Core.Internal.Request (langKey, mkFileInfoFile,
mkFileInfoLBS, mkFileInfoSource)
import Control.Applicative ((<|>))
import qualified Data.CaseInsensitive as CI
import Control.Exception (evaluate, SomeException, throwIO)
import Control.Exception (handle)
import Control.Monad (void, liftM, unless)
import qualified Control.Monad.Trans.Writer as Writer
import UnliftIO (MonadIO, liftIO, MonadUnliftIO, withRunInIO)
import qualified Network.HTTP.Types as H
import qualified Network.Wai as W
import Network.Wai.Middleware.HttpAuth
( extractBasicAuth, extractBearerAuth )
import Control.Monad.Trans.Class (lift)
import Data.Aeson (ToJSON(..))
import qualified Data.Text as T
import Data.Text.Encoding (decodeUtf8With, encodeUtf8, decodeUtf8)
import Data.Text.Encoding.Error (lenientDecode)
import qualified Data.Text.Lazy as TL
import Text.Blaze.Html.Renderer.Utf8 (renderHtml)
import Text.Hamlet (Html, HtmlUrl, hamlet)
import qualified Data.ByteString as S
import qualified Data.ByteString.Lazy as L
import qualified Data.Map as Map
import qualified Data.HashMap.Strict as HM
import Data.ByteArray (constEq)
import Control.Arrow ((***))
import qualified Data.ByteString.Char8 as S8
import Data.Monoid (Endo (..))
import Data.Text (Text)
import qualified Network.Wai.Parse as NWP
import Text.Shakespeare.I18N (RenderMessage (..))
import Web.Cookie (SetCookie (..), defaultSetCookie)
import Yesod.Core.Content (ToTypedContent (..), simpleContentType, contentTypeTypes, HasContentType (..), ToContent (..), ToFlushBuilder (..))
import Yesod.Core.Internal.Util (formatRFC1123)
import Text.Blaze.Html (preEscapedToHtml, toHtml)
import qualified Data.IORef as I
import Data.Maybe (listToMaybe, mapMaybe)
import Data.Typeable (Typeable)
import Web.PathPieces (PathPiece(..))
import Yesod.Core.Class.Handler
import Yesod.Core.Types
import Yesod.Routes.Class (Route)
import Data.ByteString.Builder (Builder)
import Data.CaseInsensitive (CI, original)
import qualified Data.Conduit.List as CL
import Control.Monad.Trans.Resource (MonadResource, InternalState, runResourceT, withInternalState, getInternalState, liftResourceT, resourceForkIO)
import qualified System.PosixCompat.Files as PC
import Conduit ((.|), runConduit, sinkLazy)
import Data.Conduit (ConduitT, transPipe, Flush (Flush), yield, Void)
import qualified Yesod.Core.TypeCache as Cache
import qualified Data.Word8 as W8
import qualified Data.Foldable as Fold
import Control.Monad.Logger (MonadLogger, logWarnS)
type HandlerT site (m :: * -> *) = HandlerFor site
{-# DEPRECATED HandlerT "Use HandlerFor directly" #-}
get :: MonadHandler m => m GHState
get = liftHandler $ HandlerFor $ I.readIORef . handlerState
put :: MonadHandler m => GHState -> m ()
put x = liftHandler $ HandlerFor $ flip I.writeIORef x . handlerState
modify :: MonadHandler m => (GHState -> GHState) -> m ()
modify f = liftHandler $ HandlerFor $ flip I.modifyIORef f . handlerState
tell :: MonadHandler m => Endo [Header] -> m ()
tell hs = modify $ \g -> g { ghsHeaders = ghsHeaders g `mappend` hs }
handlerError :: MonadHandler m => HandlerContents -> m a
handlerError = liftIO . throwIO
hcError :: MonadHandler m => ErrorResponse -> m a
hcError = handlerError . HCError
getRequest :: MonadHandler m => m YesodRequest
getRequest = liftHandler $ HandlerFor $ return . handlerRequest
runRequestBody :: MonadHandler m => m RequestBodyContents
runRequestBody = do
HandlerData
{ handlerEnv = RunHandlerEnv {..}
, handlerRequest = req
} <- liftHandler $ HandlerFor return
let len = W.requestBodyLength $ reqWaiRequest req
upload = rheUpload len
x <- get
case ghsRBC x of
Just rbc -> return rbc
Nothing -> do
rr <- waiRequest
internalState <- liftResourceT getInternalState
rbc <- liftIO $ rbHelper upload rr internalState
put x { ghsRBC = Just rbc }
return rbc
rbHelper :: FileUpload -> W.Request -> InternalState -> IO RequestBodyContents
rbHelper upload req internalState =
case upload of
FileUploadMemory s -> rbHelper' s mkFileInfoLBS req
FileUploadDisk s -> rbHelper' (s internalState) mkFileInfoFile req
FileUploadSource s -> rbHelper' s mkFileInfoSource req
rbHelper' :: NWP.BackEnd x
-> (Text -> Text -> x -> FileInfo)
-> W.Request
-> IO ([(Text, Text)], [(Text, FileInfo)])
rbHelper' backend mkFI req =
(map fix1 *** mapMaybe fix2) <$> NWP.parseRequestBody backend req
where
fix1 = go *** go
fix2 (x, NWP.FileInfo a' b c)
| S.null a = Nothing
| otherwise = Just (go x, mkFI (go a) (go b) c)
where
a
| S.length a' < 2 = a'
| S8.head a' == '"' && S8.last a' == '"' = S.tail $ S.init a'
| S8.head a' == '\'' && S8.last a' == '\'' = S.tail $ S.init a'
| otherwise = a'
go = decodeUtf8With lenientDecode
askHandlerEnv :: MonadHandler m => m (RunHandlerEnv (HandlerSite m) (HandlerSite m))
askHandlerEnv = liftHandler $ HandlerFor $ return . handlerEnv
-- | Get the master site application argument.
getYesod :: MonadHandler m => m (HandlerSite m)
getYesod = rheSite <$> askHandlerEnv
-- | Get a specific component of the master site application argument.
-- Analogous to the 'gets' function for operating on 'StateT'.
getsYesod :: MonadHandler m => (HandlerSite m -> a) -> m a
getsYesod f = (f . rheSite) <$> askHandlerEnv
-- | Get the URL rendering function.
getUrlRender :: MonadHandler m => m (Route (HandlerSite m) -> Text)
getUrlRender = do
x <- rheRender <$> askHandlerEnv
return $ flip x []
-- | The URL rendering function with query-string parameters.
getUrlRenderParams
:: MonadHandler m
=> m (Route (HandlerSite m) -> [(Text, Text)] -> Text)
getUrlRenderParams = rheRender <$> askHandlerEnv
-- | Get all the post parameters passed to the handler. To also get
-- the submitted files (if any), you have to use 'runRequestBody'
-- instead of this function.
--
-- @since 1.4.33
getPostParams
:: MonadHandler m
=> m [(Text, Text)]
getPostParams = do
reqBodyContent <- runRequestBody
return $ fst reqBodyContent
-- | Get the route requested by the user. If this is a 404 response- where the
-- user requested an invalid route- this function will return 'Nothing'.
getCurrentRoute :: MonadHandler m => m (Maybe (Route (HandlerSite m)))
getCurrentRoute = rheRoute <$> askHandlerEnv
-- | Returns a function that runs 'HandlerFor' actions inside @IO@.
--
-- Sometimes you want to run an inner 'HandlerFor' action outside
-- the control flow of an HTTP request (on the outer 'HandlerFor'
-- action). For example, you may want to spawn a new thread:
--
-- @
-- getFooR :: Handler RepHtml
-- getFooR = do
-- runInnerHandler <- handlerToIO
-- liftIO $ forkIO $ runInnerHandler $ do
-- /Code here runs inside HandlerFor but on a new thread./
-- /This is the inner HandlerFor./
-- ...
-- /Code here runs inside the request's control flow./
-- /This is the outer HandlerFor./
-- ...
-- @
--
-- Another use case for this function is creating a stream of
-- server-sent events using 'HandlerFor' actions (see
-- @yesod-eventsource@).
--
-- Most of the environment from the outer 'HandlerFor' is preserved
-- on the inner 'HandlerFor', however:
--
-- * The request body is cleared (otherwise it would be very
-- difficult to prevent huge memory leaks).
--
-- * The cache is cleared (see 'cached').
--
-- Changes to the response made inside the inner 'HandlerFor' are
-- ignored (e.g., session variables, cookies, response headers).
-- This allows the inner 'HandlerFor' to outlive the outer
-- 'HandlerFor' (e.g., on the @forkIO@ example above, a response
-- may be sent to the client without killing the new thread).
handlerToIO :: MonadIO m => HandlerFor site (HandlerFor site a -> m a)
handlerToIO =
HandlerFor $ \oldHandlerData -> do
-- Take just the bits we need from oldHandlerData.
let newReq = oldReq { reqWaiRequest = newWaiReq }
where
oldReq = handlerRequest oldHandlerData
oldWaiReq = reqWaiRequest oldReq
newWaiReq = oldWaiReq { W.requestBody = return mempty
, W.requestBodyLength = W.KnownLength 0
}
oldEnv = handlerEnv oldHandlerData
newState <- liftIO $ do
oldState <- I.readIORef (handlerState oldHandlerData)
return $ oldState { ghsRBC = Nothing
, ghsIdent = 1
, ghsCache = mempty
, ghsCacheBy = mempty
, ghsHeaders = mempty }
-- xx From this point onwards, no references to oldHandlerData xx
liftIO $ evaluate (newReq `seq` oldEnv `seq` newState `seq` ())
-- Return HandlerFor running function.
return $ \(HandlerFor f) ->
liftIO $
runResourceT $ withInternalState $ \resState -> do
-- The state IORef needs to be created here, otherwise it
-- will be shared by different invocations of this function.
newStateIORef <- liftIO (I.newIORef newState)
let newHandlerData =
HandlerData
{ handlerRequest = newReq
, handlerEnv = oldEnv
, handlerState = newStateIORef
, handlerResource = resState
}
liftIO (f newHandlerData)
-- | forkIO for a Handler (run an action in the background)
--
-- Uses 'handlerToIO', liftResourceT, and resourceForkIO
-- for correctness and efficiency
--
-- @since 1.2.8
forkHandler :: (SomeException -> HandlerFor site ()) -- ^ error handler
-> HandlerFor site ()
-> HandlerFor site ()
forkHandler onErr handler = do
yesRunner <- handlerToIO
void $ liftResourceT $ resourceForkIO $
liftIO $ handle (yesRunner . onErr) (yesRunner handler)
-- | Redirect to the given route.
-- HTTP status code 303 for HTTP 1.1 clients and 302 for HTTP 1.0
-- This is the appropriate choice for a get-following-post
-- technique, which should be the usual use case.
--
-- If you want direct control of the final status code, or need a different
-- status code, please use 'redirectWith'.
redirect :: (MonadHandler m, RedirectUrl (HandlerSite m) url)
=> url -> m a
redirect url = do
req <- waiRequest
let status =
if W.httpVersion req == H.http11
then H.status303
else H.status302
redirectWith status url
-- | Redirect to the given URL with the specified status code.
redirectWith :: (MonadHandler m, RedirectUrl (HandlerSite m) url)
=> H.Status
-> url
-> m a
redirectWith status url = do
urlText <- toTextUrl url
handlerError $ HCRedirect status urlText
ultDestKey :: Text
ultDestKey = "_ULT"
-- | Sets the ultimate destination variable to the given route.
--
-- An ultimate destination is stored in the user session and can be loaded
-- later by 'redirectUltDest'.
setUltDest :: (MonadHandler m, RedirectUrl (HandlerSite m) url)
=> url
-> m ()
setUltDest url = do
urlText <- toTextUrl url
setSession ultDestKey urlText
-- | Same as 'setUltDest', but uses the current page.
--
-- If this is a 404 handler, there is no current page, and then this call does
-- nothing.
setUltDestCurrent :: MonadHandler m => m ()
setUltDestCurrent = do
route <- getCurrentRoute
case route of
Nothing -> return ()
Just r -> do
gets' <- reqGetParams <$> getRequest
setUltDest (r, gets')
-- | Sets the ultimate destination to the referer request header, if present.
--
-- This function will not overwrite an existing ultdest.
setUltDestReferer :: MonadHandler m => m ()
setUltDestReferer = do
mdest <- lookupSession ultDestKey
maybe
(waiRequest >>= maybe (return ()) setUltDestBS . lookup "referer" . W.requestHeaders)
(const $ return ())
mdest
where
setUltDestBS = setUltDest . T.pack . S8.unpack
-- | Redirect to the ultimate destination in the user's session. Clear the
-- value from the session.
--
-- The ultimate destination is set with 'setUltDest'.
--
-- This function uses 'redirect', and thus will perform a temporary redirect to
-- a GET request.
redirectUltDest :: (RedirectUrl (HandlerSite m) url, MonadHandler m)
=> url -- ^ default destination if nothing in session
-> m a
redirectUltDest defaultDestination = do
mdest <- lookupSession ultDestKey
deleteSession ultDestKey
maybe (redirect defaultDestination) redirect mdest
-- | Remove a previously set ultimate destination. See 'setUltDest'.
clearUltDest :: MonadHandler m => m ()
clearUltDest = deleteSession ultDestKey
msgKey :: Text
msgKey = "_MSG"
-- | Adds a status and message in the user's session.
--
-- See 'getMessages'.
--
-- @since 1.4.20
addMessage :: MonadHandler m
=> Text -- ^ status
-> Html -- ^ message
-> m ()
addMessage status msg = do
val <- lookupSessionBS msgKey
setSessionBS msgKey $ addMsg val
where
addMsg = maybe msg' (S.append msg' . S.cons W8._nul)
msg' = S.append
(encodeUtf8 status)
(W8._nul `S.cons` L.toStrict (renderHtml msg))
-- | Adds a message in the user's session but uses RenderMessage to allow for i18n
--
-- See 'getMessages'.
--
-- @since 1.4.20
addMessageI :: (MonadHandler m, RenderMessage (HandlerSite m) msg)
=> Text -> msg -> m ()
addMessageI status msg = do
mr <- getMessageRender
addMessage status $ toHtml $ mr msg
-- | Gets all messages in the user's session, and then clears the variable.
--
-- See 'addMessage'.
--
-- @since 1.4.20
getMessages :: MonadHandler m => m [(Text, Html)]
getMessages = do
bs <- lookupSessionBS msgKey
let ms = maybe [] enlist bs
deleteSession msgKey
return ms
where
enlist = pairup . S.split W8._nul
pairup [] = []
pairup [_] = []
pairup (s:v:xs) = (decode s, preEscapedToHtml (decode v)) : pairup xs
decode = decodeUtf8With lenientDecode
-- | Calls 'addMessage' with an empty status
setMessage :: MonadHandler m => Html -> m ()
setMessage = addMessage ""
-- | Calls 'addMessageI' with an empty status
setMessageI :: (MonadHandler m, RenderMessage (HandlerSite m) msg)
=> msg -> m ()
setMessageI = addMessageI ""
-- | Gets just the last message in the user's session,
-- discards the rest and the status
getMessage :: MonadHandler m => m (Maybe Html)
getMessage = fmap (fmap snd . listToMaybe) getMessages
-- $rollbackWarning
--
-- Note that since short-circuiting is implemented by using exceptions,
-- using e.g. 'sendStatusJSON' inside a runDB block
-- will result in the database actions getting rolled back:
--
-- @
-- runDB $ do
-- userId <- insert $ User "username" "email@example.com"
-- postId <- insert $ BlogPost "title" "hi there!"
-- /The previous two inserts will be rolled back./
-- sendStatusJSON Status.status200 ()
-- @
-- | Bypass remaining handler code and output the given file.
--
-- For some backends, this is more efficient than reading in the file to
-- memory, since they can optimize file sending via a system call to sendfile.
sendFile :: MonadHandler m => ContentType -> FilePath -> m a
sendFile ct fp = handlerError $ HCSendFile ct fp Nothing
-- | Same as 'sendFile', but only sends part of a file.
sendFilePart :: MonadHandler m
=> ContentType
-> FilePath
-> Integer -- ^ offset
-> Integer -- ^ count
-> m a
sendFilePart ct fp off count = do
fs <- liftIO $ PC.getFileStatus fp
handlerError $ HCSendFile ct fp $ Just W.FilePart
{ W.filePartOffset = off
, W.filePartByteCount = count
, W.filePartFileSize = fromIntegral $ PC.fileSize fs
}
-- | Bypass remaining handler code and output the given content with a 200
-- status code.
sendResponse :: (MonadHandler m, ToTypedContent c) => c -> m a
sendResponse = handlerError . HCContent H.status200 . toTypedContent
-- | Bypass remaining handler code and output the given content with the given
-- status code.
sendResponseStatus :: (MonadHandler m, ToTypedContent c) => H.Status -> c -> m a
sendResponseStatus s = handlerError . HCContent s . toTypedContent
-- | Bypass remaining handler code and output the given JSON with the given
-- status code.
--
-- @since 1.4.18
sendStatusJSON :: (MonadHandler m, ToJSON c) => H.Status -> c -> m a
sendStatusJSON s v = sendResponseStatus s (toEncoding v)
-- | Send a 201 "Created" response with the given route as the Location
-- response header.
sendResponseCreated :: MonadHandler m => Route (HandlerSite m) -> m a
sendResponseCreated url = do
r <- getUrlRender
handlerError $ HCCreated $ r url
-- | Bypass remaining handler code and output no content with a 204 status code.
--
-- @since 1.6.9
sendResponseNoContent :: MonadHandler m => m a
sendResponseNoContent = sendWaiResponse $ W.responseBuilder H.status204 [] mempty
-- | Send a 'W.Response'. Please note: this function is rarely
-- necessary, and will /disregard/ any changes to response headers and session
-- that you have already specified. This function short-circuits. It should be
-- considered only for very specific needs. If you are not sure if you need it,
-- you don't.
sendWaiResponse :: MonadHandler m => W.Response -> m b
sendWaiResponse = handlerError . HCWai
-- | Switch over to handling the current request with a WAI @Application@.
--
-- @since 1.2.17
sendWaiApplication :: MonadHandler m => W.Application -> m b
sendWaiApplication = handlerError . HCWaiApp
-- | Send a raw response without conduit. This is used for cases such as
-- WebSockets. Requires WAI 3.0 or later, and a web server which supports raw
-- responses (e.g., Warp).
--
-- @since 1.2.16
sendRawResponseNoConduit
:: (MonadHandler m, MonadUnliftIO m)
=> (IO S8.ByteString -> (S8.ByteString -> IO ()) -> m ())
-> m a
sendRawResponseNoConduit raw = withRunInIO $ \runInIO ->
liftIO $ throwIO $ HCWai $ flip W.responseRaw fallback
$ \src sink -> void $ runInIO (raw src sink)
where
fallback = W.responseLBS H.status500 [("Content-Type", "text/plain")]
"sendRawResponse: backend does not support raw responses"
-- | Send a raw response. This is used for cases such as WebSockets. Requires
-- WAI 2.1 or later, and a web server which supports raw responses (e.g.,
-- Warp).
--
-- @since 1.2.7
sendRawResponse
:: (MonadHandler m, MonadUnliftIO m)
=> (ConduitT () S8.ByteString IO () -> ConduitT S8.ByteString Void IO () -> m ())
-> m a
sendRawResponse raw = withRunInIO $ \runInIO ->
liftIO $ throwIO $ HCWai $ flip W.responseRaw fallback
$ \src sink -> void $ runInIO $ raw (src' src) (CL.mapM_ sink)
where
fallback = W.responseLBS H.status500 [("Content-Type", "text/plain")]
"sendRawResponse: backend does not support raw responses"
src' src = do
bs <- liftIO src
unless (S.null bs) $ do
yield bs
src' src
-- | Send a 304 not modified response immediately. This is a short-circuiting
-- action.
--
-- @since 1.4.4
notModified :: MonadHandler m => m a
notModified = sendWaiResponse $ W.responseBuilder H.status304 [] mempty
-- | Return a 404 not found page. Also denotes no handler available.
notFound :: MonadHandler m => m a
notFound = hcError NotFound
-- | Return a 405 method not supported page.
badMethod :: MonadHandler m => m a
badMethod = do
w <- waiRequest
hcError $ BadMethod $ W.requestMethod w
-- | Return a 401 status code
notAuthenticated :: MonadHandler m => m a
notAuthenticated = hcError NotAuthenticated
-- | Return a 403 permission denied page.
permissionDenied :: MonadHandler m => Text -> m a
permissionDenied = hcError . PermissionDenied
-- | Return a 403 permission denied page.
permissionDeniedI :: (RenderMessage (HandlerSite m) msg, MonadHandler m)
=> msg
-> m a
permissionDeniedI msg = do
mr <- getMessageRender
permissionDenied $ mr msg
-- | Return a 400 invalid arguments page.
invalidArgs :: MonadHandler m => [Text] -> m a
invalidArgs = hcError . InvalidArgs
-- | Return a 400 invalid arguments page.
invalidArgsI :: (MonadHandler m, RenderMessage (HandlerSite m) msg) => [msg] -> m a
invalidArgsI msg = do
mr <- getMessageRender
invalidArgs $ map mr msg
------- Headers
-- | Set the cookie on the client.
setCookie :: MonadHandler m => SetCookie -> m ()
setCookie sc = do
addHeaderInternal (DeleteCookie name path)
addHeaderInternal (AddCookie sc)
where name = setCookieName sc
path = maybe "/" id (setCookiePath sc)
-- | Helper function for setCookieExpires value
getExpires :: MonadIO m
=> Int -- ^ minutes
-> m UTCTime
getExpires m = do
now <- liftIO getCurrentTime
return $ fromIntegral (m * 60) `addUTCTime` now
-- | Unset the cookie on the client.
--
-- Note: although the value used for key and path is 'Text', you should only
-- use ASCII values to be HTTP compliant.
deleteCookie :: MonadHandler m
=> Text -- ^ key
-> Text -- ^ path
-> m ()
deleteCookie a = addHeaderInternal . DeleteCookie (encodeUtf8 a) . encodeUtf8
-- | Set the language in the user session. Will show up in 'languages' on the
-- next request.
setLanguage :: MonadHandler m => Text -> m ()
setLanguage = setSession langKey
-- | Set attachment file name.
--
-- Allows Unicode characters by encoding to UTF-8.
-- Some modurn browser parse UTF-8 characters with out encoding setting.
-- But, for example IE9 can't parse UTF-8 characters.
-- This function use
-- <https://tools.ietf.org/html/rfc6266 RFC 6266>(<https://tools.ietf.org/html/rfc5987 RFC 5987>)
--
-- @since 1.6.4
addContentDispositionFileName :: MonadHandler m => T.Text -> m ()
addContentDispositionFileName fileName
= addHeader "Content-Disposition" $ rfc6266Utf8FileName fileName
-- | <https://tools.ietf.org/html/rfc6266 RFC 6266> Unicode attachment filename.
--
-- > rfc6266Utf8FileName (Data.Text.pack "β¬")
-- "attachment; filename*=UTF-8''%E2%82%AC"
rfc6266Utf8FileName :: T.Text -> T.Text
rfc6266Utf8FileName fileName = "attachment; filename*=UTF-8''" `mappend` decodeUtf8 (H.urlEncode True (encodeUtf8 fileName))
-- | Set an arbitrary response header.
--
-- Note that, while the data type used here is 'Text', you must provide only
-- ASCII value to be HTTP compliant.
--
-- @since 1.2.0
addHeader :: MonadHandler m => Text -> Text -> m ()
addHeader a = addHeaderInternal . Header (CI.mk $ encodeUtf8 a) . encodeUtf8
-- | Deprecated synonym for addHeader.
setHeader :: MonadHandler m => Text -> Text -> m ()
setHeader = addHeader
{-# DEPRECATED setHeader "Please use addHeader instead" #-}
-- | Replace an existing header with a new value or add a new header
-- if not present.
--
-- Note that, while the data type used here is 'Text', you must provide only
-- ASCII value to be HTTP compliant.
--
-- @since 1.4.36
replaceOrAddHeader :: MonadHandler m => Text -> Text -> m ()
replaceOrAddHeader a b =
modify $ \g -> g {ghsHeaders = replaceHeader (ghsHeaders g)}
where
repHeader = Header (CI.mk $ encodeUtf8 a) (encodeUtf8 b)
sameHeaderName :: Header -> Header -> Bool
sameHeaderName (Header n1 _) (Header n2 _) = n1 == n2
sameHeaderName _ _ = False
replaceIndividualHeader :: [Header] -> [Header]
replaceIndividualHeader [] = [repHeader]
replaceIndividualHeader xs = aux xs []
where
aux [] acc = acc ++ [repHeader]
aux (x:xs') acc =
if sameHeaderName repHeader x
then acc ++
[repHeader] ++
(filter (\header -> not (sameHeaderName header repHeader)) xs')
else aux xs' (acc ++ [x])
replaceHeader :: Endo [Header] -> Endo [Header]
replaceHeader endo =
let allHeaders :: [Header] = appEndo endo []
in Endo (\rest -> replaceIndividualHeader allHeaders ++ rest)
-- | Set the Cache-Control header to indicate this response should be cached
-- for the given number of seconds.
cacheSeconds :: MonadHandler m => Int -> m ()
cacheSeconds i = setHeader "Cache-Control" $ T.concat
[ "max-age="
, T.pack $ show i
, ", public"
]
-- | Set the Expires header to some date in 2037. In other words, this content
-- is never (realistically) expired.
neverExpires :: MonadHandler m => m ()
neverExpires = do
setHeader "Expires" . rheMaxExpires =<< askHandlerEnv
cacheSeconds oneYear
where
oneYear :: Int
oneYear = 60 * 60 * 24 * 365
-- | Set an Expires header in the past, meaning this content should not be
-- cached.
alreadyExpired :: MonadHandler m => m ()
alreadyExpired = setHeader "Expires" "Thu, 01 Jan 1970 05:05:05 GMT"
-- | Set an Expires header to the given date.
expiresAt :: MonadHandler m => UTCTime -> m ()
expiresAt = setHeader "Expires" . formatRFC1123
data Etag
= WeakEtag !S.ByteString
-- ^ Prefixed by W/ and surrounded in quotes. Signifies that contents are
-- semantically identical but make no guarantees about being bytewise identical.
| StrongEtag !S.ByteString
-- ^ Signifies that contents should be byte-for-byte identical if they match
-- the provided ETag
| InvalidEtag !S.ByteString
-- ^ Anything else that ends up in a header that expects an ETag but doesn't
-- properly follow the ETag format specified in RFC 7232, section 2.3
deriving (Show, Eq)
-- | Check the if-none-match header and, if it matches the given value, return
-- a 304 not modified response. Otherwise, set the etag header to the given
-- value.
--
-- Note that it is the responsibility of the caller to ensure that the provided
-- value is a valid etag value, no sanity checking is performed by this
-- function.
--
-- @since 1.4.4
setEtag :: MonadHandler m => Text -> m ()
setEtag etag = do
mmatch <- lookupHeader "if-none-match"
let matches = maybe [] parseMatch mmatch
baseTag = encodeUtf8 etag
strongTag = StrongEtag baseTag
badTag = InvalidEtag baseTag
if any (\tag -> tag == strongTag || tag == badTag) matches
then notModified
else addHeader "etag" $ T.concat ["\"", etag, "\""]
-- | Parse an if-none-match field according to the spec.
parseMatch :: S.ByteString -> [Etag]
parseMatch =
map clean . S.split W8._comma
where
clean = classify . fst . S.spanEnd W8.isSpace . S.dropWhile W8.isSpace
classify bs
| S.length bs >= 2 && S.head bs == W8._quotedbl && S.last bs == W8._quotedbl
= StrongEtag $ S.init $ S.tail bs
| S.length bs >= 4 &&
S.head bs == W8._W &&
S.index bs 1 == W8._slash &&
S.index bs 2 == W8._quotedbl &&
S.last bs == W8._quotedbl
= WeakEtag $ S.init $ S.drop 3 bs
| otherwise = InvalidEtag bs
-- | Check the if-none-match header and, if it matches the given value, return
-- a 304 not modified response. Otherwise, set the etag header to the given
-- value.
--
-- A weak etag is only expected to be semantically identical to the prior content,
-- but doesn't have to be byte-for-byte identical. Therefore it can be useful for
-- dynamically generated content that may be difficult to perform bytewise hashing
-- upon.
--
-- Note that it is the responsibility of the caller to ensure that the provided
-- value is a valid etag value, no sanity checking is performed by this
-- function.
--
-- @since 1.4.37
setWeakEtag :: MonadHandler m => Text -> m ()
setWeakEtag etag = do
mmatch <- lookupHeader "if-none-match"
let matches = maybe [] parseMatch mmatch
if WeakEtag (encodeUtf8 etag) `elem` matches
then notModified
else addHeader "etag" $ T.concat ["W/\"", etag, "\""]
-- | Set a variable in the user's session.
--
-- The session is handled by the clientsession package: it sets an encrypted
-- and hashed cookie on the client. This ensures that all data is secure and
-- not tampered with.
setSession :: MonadHandler m
=> Text -- ^ key
-> Text -- ^ value
-> m ()
setSession k = setSessionBS k . encodeUtf8
-- | Same as 'setSession', but uses binary data for the value.
setSessionBS :: MonadHandler m
=> Text
-> S.ByteString
-> m ()
setSessionBS k = modify . modSession . Map.insert k
-- | Unsets a session variable. See 'setSession'.
deleteSession :: MonadHandler m => Text -> m ()
deleteSession = modify . modSession . Map.delete
-- | Clear all session variables.
--
-- @since: 1.0.1
clearSession :: MonadHandler m => m ()
clearSession = modify $ \x -> x { ghsSession = Map.empty }
modSession :: (SessionMap -> SessionMap) -> GHState -> GHState
modSession f x = x { ghsSession = f $ ghsSession x }
-- | Internal use only, not to be confused with 'setHeader'.
addHeaderInternal :: MonadHandler m => Header -> m ()
addHeaderInternal = tell . Endo . (:)
-- | Some value which can be turned into a URL for redirects.
class RedirectUrl master a where
-- | Converts the value to the URL and a list of query-string parameters.
toTextUrl :: (MonadHandler m, HandlerSite m ~ master) => a -> m Text
instance RedirectUrl master Text where
toTextUrl = return
instance RedirectUrl master String where
toTextUrl = toTextUrl . T.pack
instance RedirectUrl master (Route master) where
toTextUrl url = do
r <- getUrlRender
return $ r url
instance (key ~ Text, val ~ Text) => RedirectUrl master (Route master, [(key, val)]) where
toTextUrl (url, params) = do
r <- getUrlRenderParams
return $ r url params
instance (key ~ Text, val ~ Text) => RedirectUrl master (Route master, Map.Map key val) where
toTextUrl (url, params) = toTextUrl (url, Map.toList params)
-- | Add a fragment identifier to a route to be used when
-- redirecting. For example:
--
-- > redirect (NewsfeedR :#: storyId)
--
-- @since 1.2.9.
data Fragment a b = a :#: b deriving Show
instance (RedirectUrl master a, PathPiece b) => RedirectUrl master (Fragment a b) where
toTextUrl (a :#: b) = (\ua -> T.concat [ua, "#", toPathPiece b]) <$> toTextUrl a
-- | Lookup for session data.
lookupSession :: MonadHandler m => Text -> m (Maybe Text)
lookupSession = (fmap . fmap) (decodeUtf8With lenientDecode) . lookupSessionBS
-- | Lookup for session data in binary format.
lookupSessionBS :: MonadHandler m => Text -> m (Maybe S.ByteString)
lookupSessionBS n = do
m <- fmap ghsSession get
return $ Map.lookup n m
-- | Get all session variables.
getSession :: MonadHandler m => m SessionMap
getSession = fmap ghsSession get
-- | Get a unique identifier.
newIdent :: MonadHandler m => m Text
newIdent = do
x <- get
let i' = ghsIdent x + 1
put x { ghsIdent = i' }
return $ T.pack $ "hident" ++ show i'
-- | Redirect to a POST resource.
--
-- This is not technically a redirect; instead, it returns an HTML page with a
-- POST form, and some Javascript to automatically submit the form. This can be
-- useful when you need to post a plain link somewhere that needs to cause
-- changes on the server.
redirectToPost :: (MonadHandler m, RedirectUrl (HandlerSite m) url)
=> url
-> m a
redirectToPost url = do
urlText <- toTextUrl url
req <- getRequest
withUrlRenderer [hamlet|
$newline never
$doctype 5
<html>
<head>
<title>Redirecting...
<body>
<form id="form" method="post" action=#{urlText}>
$maybe token <- reqToken req
<input type=hidden name=#{defaultCsrfParamName} value=#{token}>
<noscript>
<p>Javascript has been disabled; please click on the button below to be redirected.
<input type="submit" value="Continue">
<script>
window.onload = function() { document.getElementById('form').submit(); };
|] >>= sendResponse
-- | Wraps the 'Content' generated by 'hamletToContent' in a 'RepHtml'.
hamletToRepHtml :: MonadHandler m => HtmlUrl (Route (HandlerSite m)) -> m Html
hamletToRepHtml = withUrlRenderer
{-# DEPRECATED hamletToRepHtml "Use withUrlRenderer instead" #-}
-- | Deprecated synonym for 'withUrlRenderer'.
--
-- @since 1.2.0
giveUrlRenderer :: MonadHandler m
=> ((Route (HandlerSite m) -> [(Text, Text)] -> Text) -> output)
-> m output
giveUrlRenderer = withUrlRenderer
{-# DEPRECATED giveUrlRenderer "Use withUrlRenderer instead" #-}
-- | Provide a URL rendering function to the given function and return the
-- result. Useful for processing Shakespearean templates.
--
-- @since 1.2.20
withUrlRenderer :: MonadHandler m
=> ((Route (HandlerSite m) -> [(Text, Text)] -> Text) -> output)
-> m output
withUrlRenderer f = do
render <- getUrlRenderParams
return $ f render
-- | Get the request\'s 'W.Request' value.
waiRequest :: MonadHandler m => m W.Request
waiRequest = reqWaiRequest <$> getRequest
getMessageRender :: (MonadHandler m, RenderMessage (HandlerSite m) message)
=> m (message -> Text)
getMessageRender = do
env <- askHandlerEnv
l <- languages
return $ renderMessage (rheSite env) l
-- | Use a per-request cache to avoid performing the same action multiple times.
-- Values are stored by their type, the result of typeOf from Typeable.
-- Therefore, you should use different newtype wrappers at each cache site.
--
-- For example, yesod-auth uses an un-exported newtype, CachedMaybeAuth and exports functions that utilize it such as maybeAuth.
-- This means that another module can create its own newtype wrapper to cache the same type from a different action without any cache conflicts.
--
-- See the original announcement: <http://www.yesodweb.com/blog/2013/03/yesod-1-2-cleaner-internals>
--
-- @since 1.2.0
cached :: (MonadHandler m, Typeable a)
=> m a
-> m a
cached action = do
cache <- ghsCache <$> get
eres <- Cache.cached cache action
case eres of
Right res -> return res
Left (newCache, res) -> do
gs <- get
let merged = newCache `HM.union` ghsCache gs
put $ gs { ghsCache = merged }
return res
-- | Retrieves a value from the cache used by 'cached'.
--
-- @since 1.6.10
cacheGet :: (MonadHandler m, Typeable a)
=> m (Maybe a)
cacheGet = do
cache <- ghsCache <$> get
pure $ Cache.cacheGet cache
-- | Sets a value in the cache used by 'cached'.
--
-- @since 1.6.10
cacheSet :: (MonadHandler m, Typeable a)
=> a
-> m ()
cacheSet value = do
gs <- get
let cache = ghsCache gs
newCache = Cache.cacheSet value cache
put $ gs { ghsCache = newCache }
-- | a per-request cache. just like 'cached'.
-- 'cached' can only cache a single value per type.
-- 'cachedBy' stores multiple values per type by usage of a ByteString key
--
-- 'cached' is ideal to cache an action that has only one value of a type, such as the session's current user
-- 'cachedBy' is required if the action has parameters and can return multiple values per type.
-- You can turn those parameters into a ByteString cache key.
-- For example, caching a lookup of a Link by a token where multiple token lookups might be performed.
--
-- @since 1.4.0
cachedBy :: (MonadHandler m, Typeable a) => S.ByteString -> m a -> m a
cachedBy k action = do
cache <- ghsCacheBy <$> get
eres <- Cache.cachedBy cache k action
case eres of
Right res -> return res
Left (newCache, res) -> do
gs <- get
let merged = newCache `HM.union` ghsCacheBy gs
put $ gs { ghsCacheBy = merged }
return res
-- | Retrieves a value from the cache used by 'cachedBy'.
--
-- @since 1.6.10
cacheByGet :: (MonadHandler m, Typeable a)
=> S.ByteString
-> m (Maybe a)
cacheByGet key = do
cache <- ghsCacheBy <$> get
pure $ Cache.cacheByGet key cache
-- | Sets a value in the cache used by 'cachedBy'.
--
-- @since 1.6.10
cacheBySet :: (MonadHandler m, Typeable a)
=> S.ByteString
-> a
-> m ()
cacheBySet key value = do
gs <- get
let cache = ghsCacheBy gs
newCache = Cache.cacheBySet key value cache
put $ gs { ghsCacheBy = newCache }
-- | Get the list of supported languages supplied by the user.
--
-- Languages are determined based on the following (in descending order
-- of preference):
--
-- * The _LANG get parameter.
--
-- * The _LANG user session variable.
--
-- * The _LANG cookie.
--
-- * Accept-Language HTTP header.
--
-- Yesod will seek the first language from the returned list matched with languages supporting by your application. This language will be used to render i18n templates.
-- If a matching language is not found the default language will be used.
--
-- This is handled by parseWaiRequest (not exposed).
--
-- __NOTE__: Before version @1.6.19.0@, this function prioritized the session
-- variable above all other sources.
--
languages :: MonadHandler m => m [Text]
languages = reqLangs <$> getRequest
lookup' :: Eq a => a -> [(a, b)] -> [b]
lookup' a = map snd . filter (\x -> a == fst x)
-- | Lookup a request header.
--
-- @since 1.2.2
lookupHeader :: MonadHandler m => CI S8.ByteString -> m (Maybe S8.ByteString)
lookupHeader = fmap listToMaybe . lookupHeaders
-- | Lookup a request header.
--
-- @since 1.2.2
lookupHeaders :: MonadHandler m => CI S8.ByteString -> m [S8.ByteString]
lookupHeaders key = do
req <- waiRequest
return $ lookup' key $ W.requestHeaders req
-- | Lookup basic authentication data from __Authorization__ header of
-- request. Returns user name and password
--
-- @since 1.4.9
lookupBasicAuth :: (MonadHandler m) => m (Maybe (Text, Text))
lookupBasicAuth = fmap (>>= getBA) (lookupHeader "Authorization")
where
getBA bs = (decodeUtf8With lenientDecode *** decodeUtf8With lenientDecode)
<$> extractBasicAuth bs
-- | Lookup bearer authentication datafrom __Authorization__ header of
-- request. Returns bearer token value
--
-- @since 1.4.9
lookupBearerAuth :: (MonadHandler m) => m (Maybe Text)
lookupBearerAuth = fmap (>>= getBR)
(lookupHeader "Authorization")
where
getBR bs = decodeUtf8With lenientDecode
<$> extractBearerAuth bs
-- | Lookup for GET parameters.
lookupGetParams :: MonadHandler m => Text -> m [Text]
lookupGetParams pn = do
rr <- getRequest
return $ lookup' pn $ reqGetParams rr
-- | Lookup for GET parameters.
lookupGetParam :: MonadHandler m => Text -> m (Maybe Text)
lookupGetParam = fmap listToMaybe . lookupGetParams
-- | Lookup for POST parameters.
lookupPostParams :: (MonadResource m, MonadHandler m) => Text -> m [Text]
lookupPostParams pn = do
(pp, _) <- runRequestBody
return $ lookup' pn pp
lookupPostParam :: (MonadResource m, MonadHandler m)
=> Text
-> m (Maybe Text)
lookupPostParam = fmap listToMaybe . lookupPostParams
-- | Lookup for POSTed files.
lookupFile :: MonadHandler m
=> Text
-> m (Maybe FileInfo)
lookupFile = fmap listToMaybe . lookupFiles
-- | Lookup for POSTed files.
lookupFiles :: MonadHandler m
=> Text
-> m [FileInfo]
lookupFiles pn = do
(_, files) <- runRequestBody
return $ lookup' pn files
-- | Lookup for cookie data.
lookupCookie :: MonadHandler m => Text -> m (Maybe Text)
lookupCookie = fmap listToMaybe . lookupCookies
-- | Lookup for cookie data.
lookupCookies :: MonadHandler m => Text -> m [Text]
lookupCookies pn = do
rr <- getRequest
return $ lookup' pn $ reqCookies rr
-- $representations
--
-- HTTP allows content negotation to determine what /representation/ of data
-- you would like to use. The most common example of this is providing both a
-- user-facing HTML page and an API facing JSON response from the same URL. The
-- means of achieving this is the Accept HTTP header, which provides a list of
-- content types the client will accept, sorted by preference.
--
-- By using 'selectRep' and 'provideRep', you can provide a number of different
-- representations, e.g.:
--
-- > selectRep $ do
-- > provideRep produceHtmlOutput
-- > provideRep produceJsonOutput
--
-- The first provided representation will be used if no matches are found.
-- | Select a representation to send to the client based on the representations
-- provided inside this do-block. Should be used together with 'provideRep'.
--
-- @since 1.2.0
selectRep :: MonadHandler m
=> Writer.Writer (Endo [ProvidedRep m]) ()
-> m TypedContent
selectRep w = do
-- the content types are already sorted by q values
-- which have been stripped
cts <- fmap reqAccept getRequest
case mapMaybe tryAccept cts of
[] ->
case reps of
[] -> sendResponseStatus H.status500 ("No reps provided to selectRep" :: Text)
rep:_ -> returnRep rep
rep:_ -> returnRep rep
where
returnRep (ProvidedRep ct mcontent) = fmap (TypedContent ct) mcontent
reps = appEndo (Writer.execWriter w) []
repMap = Map.unions $ map (\v@(ProvidedRep k _) -> Map.fromList
[ (k, v)
, (noSpace k, v)
, (simpleContentType k, v)
]) reps
-- match on the type for sub-type wildcards.
-- If the accept is text/ * it should match a provided text/html
mainTypeMap = Map.fromList $ reverse $ map
(\v@(ProvidedRep ct _) -> (fst $ contentTypeTypes ct, v)) reps
tryAccept ct =
if subType == "*"
then if mainType == "*"
then listToMaybe reps
else Map.lookup mainType mainTypeMap
else lookupAccept ct
where
(mainType, subType) = contentTypeTypes ct
lookupAccept ct = Map.lookup ct repMap <|>
Map.lookup (noSpace ct) repMap <|>
Map.lookup (simpleContentType ct) repMap
-- Mime types such as "text/html; charset=foo" get converted to
-- "text/html;charset=foo"
noSpace = S8.filter (/= ' ')
-- | Internal representation of a single provided representation.
--
-- @since 1.2.0
data ProvidedRep m = ProvidedRep !ContentType !(m Content)
-- | Provide a single representation to be used, based on the request of the
-- client. Should be used together with 'selectRep'.
--
-- @since 1.2.0
provideRep :: (Monad m, HasContentType a)
=> m a
-> Writer.Writer (Endo [ProvidedRep m]) ()
provideRep handler = provideRepType (getContentType handler) handler
-- | Same as 'provideRep', but instead of determining the content type from the
-- type of the value itself, you provide the content type separately. This can
-- be a convenience instead of creating newtype wrappers for uncommonly used
-- content types.
--
-- > provideRepType "application/x-special-format" "This is the content"
--
-- @since 1.2.0
provideRepType :: (Monad m, ToContent a)
=> ContentType
-> m a
-> Writer.Writer (Endo [ProvidedRep m]) ()
provideRepType ct handler =
Writer.tell $ Endo (ProvidedRep ct (liftM toContent handler):)
-- | Stream in the raw request body without any parsing.
--
-- @since 1.2.0
rawRequestBody :: MonadHandler m => ConduitT i S.ByteString m ()
rawRequestBody = do
req <- lift waiRequest
let loop = do
bs <- liftIO $ W.requestBody req
unless (S.null bs) $ do
yield bs
loop
loop
-- | Stream the data from the file. Since Yesod 1.2, this has been generalized
-- to work in any @MonadResource@.
fileSource :: MonadResource m => FileInfo -> ConduitT () S.ByteString m ()
fileSource = transPipe liftResourceT . fileSourceRaw
-- | Extract a strict `ByteString` body from a `FileInfo`.
--
-- This function will block while reading the file.
--
-- > do
-- > fileByteString <- fileSourceByteString fileInfo
--
-- @since 1.6.5
fileSourceByteString :: MonadResource m => FileInfo -> m S.ByteString
fileSourceByteString fileInfo = runConduit (L.toStrict <$> (fileSource fileInfo .| sinkLazy))
-- | Provide a pure value for the response body.
--
-- > respond ct = return . TypedContent ct . toContent
--
-- @since 1.2.0
respond :: (Monad m, ToContent a) => ContentType -> a -> m TypedContent
respond ct = return . TypedContent ct . toContent
-- | Use a @Source@ for the response body.
--
-- Note that, for ease of use, the underlying monad is a @HandlerFor@. This
-- implies that you can run any @HandlerFor@ action. However, since a streaming
-- response occurs after the response headers have already been sent, some
-- actions make no sense here. For example: short-circuit responses, setting
-- headers, changing status codes, etc.
--
-- @since 1.2.0
respondSource :: ContentType
-> ConduitT () (Flush Builder) (HandlerFor site) ()
-> HandlerFor site TypedContent
respondSource ctype src = HandlerFor $ \hd ->
-- Note that this implementation relies on the fact that the ResourceT
-- environment provided by the server is the same one used in HandlerFor.
-- This is a safe assumption assuming the HandlerFor is run correctly.
return $ TypedContent ctype $ ContentSource
$ transPipe (lift . flip unHandlerFor hd) src
-- | In a streaming response, send a single chunk of data. This function works
-- on most datatypes, such as @ByteString@ and @Html@.
--
-- @since 1.2.0
sendChunk :: Monad m => ToFlushBuilder a => a -> ConduitT i (Flush Builder) m ()
sendChunk = yield . toFlushBuilder
-- | In a streaming response, send a flush command, causing all buffered data
-- to be immediately sent to the client.
--
-- @since 1.2.0
sendFlush :: Monad m => ConduitT i (Flush Builder) m ()
sendFlush = yield Flush
-- | Type-specialized version of 'sendChunk' for strict @ByteString@s.
--
-- @since 1.2.0
sendChunkBS :: Monad m => S.ByteString -> ConduitT i (Flush Builder) m ()
sendChunkBS = sendChunk
-- | Type-specialized version of 'sendChunk' for lazy @ByteString@s.
--
-- @since 1.2.0
sendChunkLBS :: Monad m => L.ByteString -> ConduitT i (Flush Builder) m ()
sendChunkLBS = sendChunk
-- | Type-specialized version of 'sendChunk' for strict @Text@s.
--
-- @since 1.2.0
sendChunkText :: Monad m => T.Text -> ConduitT i (Flush Builder) m ()
sendChunkText = sendChunk
-- | Type-specialized version of 'sendChunk' for lazy @Text@s.
--
-- @since 1.2.0
sendChunkLazyText :: Monad m => TL.Text -> ConduitT i (Flush Builder) m ()
sendChunkLazyText = sendChunk
-- | Type-specialized version of 'sendChunk' for @Html@s.
--
-- @since 1.2.0
sendChunkHtml :: Monad m => Html -> ConduitT i (Flush Builder) m ()
sendChunkHtml = sendChunk
-- $ajaxCSRFOverview
-- When a user has authenticated with your site, all requests made from the browser to your server will include the session information that you use to verify that the user is logged in.
-- Unfortunately, this allows attackers to make unwanted requests on behalf of the user by e.g. submitting an HTTP request to your site when the user visits theirs.
-- This is known as a <https://en.wikipedia.org/wiki/Cross-site_request_forgery Cross Site Request Forgery> (CSRF) attack.
--
-- To combat this attack, you need a way to verify that the request is valid.
-- This is achieved by generating a random string ("token"), storing it in your encrypted session so that the server can look it up (see 'reqToken'), and adding the token to HTTP requests made to your server.
-- When a request comes in, the token in the request is compared to the one from the encrypted session. If they match, you can be sure the request is valid.
--
-- Yesod implements this behavior in two ways:
--
-- (1) The yesod-form package <http://www.yesodweb.com/book/forms#forms_running_forms stores the CSRF token in a hidden field> in the form, then validates it with functions like 'Yesod.Form.Functions.runFormPost'.
--
-- (2) Yesod can store the CSRF token in a cookie which is accessible by Javascript. Requests made by Javascript can lookup this cookie and add it as a header to requests. The server then checks the token in the header against the one in the encrypted session.
--
-- The form-based approach has the advantage of working for users with Javascript disabled, while adding the token to the headers with Javascript allows things like submitting JSON or binary data in AJAX requests. Yesod supports checking for a CSRF token in either the POST parameters of the form ('checkCsrfParamNamed'), the headers ('checkCsrfHeaderNamed'), or both options ('checkCsrfHeaderOrParam').
--
-- The easiest way to check both sources is to add the 'Yesod.Core.defaultCsrfMiddleware' to your Yesod Middleware.
--
-- === Opting-out of CSRF checking for specific routes
--
-- (Note: this code is generic to opting out of any Yesod middleware)
--
-- @
-- 'yesodMiddleware' app = do
-- maybeRoute <- 'getCurrentRoute'
-- let dontCheckCsrf = case maybeRoute of
-- Just HomeR -> True -- Don't check HomeR
-- Nothing -> True -- Don't check for 404s
-- _ -> False -- Check other routes
--
-- 'defaultYesodMiddleware' $ 'defaultCsrfSetCookieMiddleware' $ (if dontCheckCsrf then 'id' else 'defaultCsrfCheckMiddleware') $ app
-- @
--
-- This can also be implemented using the 'csrfCheckMiddleware' function.
-- | The default cookie name for the CSRF token ("XSRF-TOKEN").
--
-- @since 1.4.14
defaultCsrfCookieName :: S8.ByteString
defaultCsrfCookieName = "XSRF-TOKEN"
-- | Sets a cookie with a CSRF token, using 'defaultCsrfCookieName' for the cookie name.
--
-- The cookie's path is set to @/@, making it valid for your whole website.
--
-- @since 1.4.14
setCsrfCookie :: MonadHandler m => m ()
setCsrfCookie = setCsrfCookieWithCookie defaultSetCookie
{ setCookieName = defaultCsrfCookieName
, setCookiePath = Just "/"
}
-- | Takes a 'SetCookie' and overrides its value with a CSRF token, then sets the cookie.
--
-- Make sure to set the 'setCookiePath' to the root path of your application, otherwise you'll generate a new CSRF token for every path of your app. If your app is run from from e.g. www.example.com\/app1, use @app1@. The vast majority of sites will just use @/@.
--
-- @since 1.4.14
setCsrfCookieWithCookie :: MonadHandler m => SetCookie -> m ()
setCsrfCookieWithCookie cookie = do
mCsrfToken <- reqToken <$> getRequest
Fold.forM_ mCsrfToken (\token -> setCookie $ cookie { setCookieValue = encodeUtf8 token })
-- | The default header name for the CSRF token ("X-XSRF-TOKEN").
--
-- @since 1.4.14
defaultCsrfHeaderName :: CI S8.ByteString
defaultCsrfHeaderName = "X-XSRF-TOKEN"
-- | Takes a header name to lookup a CSRF token. If the value doesn't match the token stored in the session,
-- this function throws a 'PermissionDenied' error.
--
-- @since 1.4.14
checkCsrfHeaderNamed :: MonadHandler m => CI S8.ByteString -> m ()
checkCsrfHeaderNamed headerName = do
(valid, mHeader) <- hasValidCsrfHeaderNamed' headerName
unless valid (permissionDenied $ csrfErrorMessage [CSRFHeader (decodeUtf8 $ original headerName) mHeader])
-- | Takes a header name to lookup a CSRF token, and returns whether the value matches the token stored in the session.
--
-- @since 1.4.14
hasValidCsrfHeaderNamed :: MonadHandler m => CI S8.ByteString -> m Bool
hasValidCsrfHeaderNamed headerName = fst <$> hasValidCsrfHeaderNamed' headerName
-- | Like 'hasValidCsrfHeaderNamed', but also returns the header value to be used in error messages.
hasValidCsrfHeaderNamed' :: MonadHandler m => CI S8.ByteString -> m (Bool, Maybe Text)
hasValidCsrfHeaderNamed' headerName = do
mCsrfToken <- reqToken <$> getRequest
mXsrfHeader <- lookupHeader headerName
return $ (validCsrf mCsrfToken mXsrfHeader, decodeUtf8 <$> mXsrfHeader)
-- CSRF Parameter checking
-- | The default parameter name for the CSRF token ("_token")
--
-- @since 1.4.14
defaultCsrfParamName :: Text
defaultCsrfParamName = "_token"
-- | Takes a POST parameter name to lookup a CSRF token. If the value doesn't match the token stored in the session,
-- this function throws a 'PermissionDenied' error.
--
-- @since 1.4.14
checkCsrfParamNamed :: MonadHandler m => Text -> m ()
checkCsrfParamNamed paramName = do
(valid, mParam) <- hasValidCsrfParamNamed' paramName
unless valid (permissionDenied $ csrfErrorMessage [CSRFParam paramName mParam])
-- | Takes a POST parameter name to lookup a CSRF token, and returns whether the value matches the token stored in the session.
--
-- @since 1.4.14
hasValidCsrfParamNamed :: MonadHandler m => Text -> m Bool
hasValidCsrfParamNamed paramName = fst <$> hasValidCsrfParamNamed' paramName
-- | Like 'hasValidCsrfParamNamed', but also returns the param value to be used in error messages.
hasValidCsrfParamNamed' :: MonadHandler m => Text -> m (Bool, Maybe Text)
hasValidCsrfParamNamed' paramName = do
mCsrfToken <- reqToken <$> getRequest
mCsrfParam <- lookupPostParam paramName
return $ (validCsrf mCsrfToken (encodeUtf8 <$> mCsrfParam), mCsrfParam)
-- | Checks that a valid CSRF token is present in either the request headers or POST parameters.
-- If the value doesn't match the token stored in the session, this function throws a 'PermissionDenied' error.
--
-- @since 1.4.14
checkCsrfHeaderOrParam :: (MonadHandler m, MonadLogger m)
=> CI S8.ByteString -- ^ The header name to lookup the CSRF token
-> Text -- ^ The POST parameter name to lookup the CSRF token
-> m ()
checkCsrfHeaderOrParam headerName paramName = do
(validHeader, mHeader) <- hasValidCsrfHeaderNamed' headerName
(validParam, mParam) <- hasValidCsrfParamNamed' paramName
unless (validHeader || validParam) $ do
let errorMessage = csrfErrorMessage $ [CSRFHeader (decodeUtf8 $ original headerName) mHeader, CSRFParam paramName mParam]
$logWarnS "yesod-core" errorMessage
permissionDenied errorMessage
validCsrf :: Maybe Text -> Maybe S.ByteString -> Bool
-- It's important to use constant-time comparison (constEq) in order to avoid timing attacks.
validCsrf (Just token) (Just param) = encodeUtf8 token `constEq` param
validCsrf Nothing _param = True
validCsrf (Just _token) Nothing = False
data CSRFExpectation = CSRFHeader Text (Maybe Text) -- Key/Value
| CSRFParam Text (Maybe Text) -- Key/Value
csrfErrorMessage :: [CSRFExpectation]
-> Text -- ^ Error message
csrfErrorMessage expectedLocations = T.intercalate "\n"
[ "A valid CSRF token wasn't present. Because the request could have been forged, it's been rejected altogether."
, "If you're a developer of this site, these tips will help you debug the issue:"
, "- Read the Yesod.Core.Handler docs of the yesod-core package for details on CSRF protection."
, "- Check that your HTTP client is persisting cookies between requests, like a browser does."
, "- By default, the CSRF token is sent to the client in a cookie named " `mappend` (decodeUtf8 defaultCsrfCookieName) `mappend` "."
, "- The server is looking for the token in the following locations:\n" `mappend` T.intercalate "\n" (map csrfLocation expectedLocations)
]
where csrfLocation expected = case expected of
CSRFHeader k v -> T.intercalate " " [" - An HTTP header named", k, (formatValue v)]
CSRFParam k v -> T.intercalate " " [" - A POST parameter named", k, (formatValue v)]
formatValue :: Maybe Text -> Text
formatValue maybeText = case maybeText of
Nothing -> "(which is not currently set)"
Just t -> T.concat ["(which has the current, incorrect value: '", t, "')"]
getSubYesod :: MonadHandler m => m (SubHandlerSite m)
getSubYesod = liftSubHandler $ SubHandlerFor $ return . rheChild . handlerEnv
getRouteToParent :: MonadHandler m => m (Route (SubHandlerSite m) -> Route (HandlerSite m))
getRouteToParent = liftSubHandler $ SubHandlerFor $ return . rheRouteToMaster . handlerEnv
getSubCurrentRoute :: MonadHandler m => m (Maybe (Route (SubHandlerSite m)))
getSubCurrentRoute = liftSubHandler $ SubHandlerFor $ return . rheRoute . handlerEnv
|
geraldus/yesod
|
yesod-core/src/Yesod/Core/Handler.hs
|
mit
| 61,845
| 0
| 20
| 14,642
| 11,866
| 6,364
| 5,502
| -1
| -1
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
module Qi.CLI.Dispatcher (
updateLambdas
, deployApp
, createCfStack
, updateCfStack
, describeCfStack
, destroyCfStack
, cycleStack
, printLogs
) where
import Control.Lens
import Control.Monad.Freer
import Data.Aeson.Encode.Pretty (encodePretty)
import qualified Data.ByteString.Lazy as LBS
import qualified Data.Map as Map
import Network.AWS.CloudWatchLogs
import Network.AWS.Data.Body (toBody)
import Network.AWS.S3
import Protolude hiding (FilePath, getAll)
import Qi.CLI.Dispatcher.S3 as S3 (clearBuckets)
import Qi.Config.AWS (Config, getAll, getName,
getPhysicalName, namePrefix)
import Qi.Config.AWS (getById)
import Qi.Config.AWS.Lambda (Lambda)
import qualified Qi.Config.AWS.Lambda.Accessors as Lbd
import Qi.Config.AWS.S3 (S3Key (S3Key), s3Object)
import qualified Qi.Config.AWS.S3.Accessors as S3
import qualified Qi.Config.CfTemplate as CF
import Qi.Config.Identifier (LambdaId)
import Qi.Program.CF.Lang
import Qi.Program.Config.Lang (ConfigEff, getConfig)
import Qi.Program.Gen.Lang
import Qi.Program.Lambda.Lang (LambdaEff)
import qualified Qi.Program.Lambda.Lang as Lbd
import Qi.Program.S3.Lang
deployApp
:: Members '[ S3Eff, GenEff, ConfigEff ] effs
=> LBS.ByteString
-> LBS.ByteString
-> Eff effs ()
deployApp template content = do
say "deploying the app..."
config <- getConfig
let appName = config ^. namePrefix
bucketName = BucketName $ appName <> ".app"
say $ "creating bucket '" <> show bucketName <> "'"
amazonka s3 $ createBucket bucketName
say $ "writing lambda executable into bucket '" <> show bucketName <> "'"
amazonka s3 $ putObject bucketName "lambda.zip" (toBody content) & poACL ?~ OPublicReadWrite
pass
createCfStack
:: Members '[ CfEff, GenEff, ConfigEff ] effs
=> LBS.ByteString
-> Eff effs ()
createCfStack template = do
config <- getConfig
let appName = config ^. namePrefix
stackName = StackName appName
say "creating the stack..."
createStack stackName template
say "waiting on the stack to be created..."
waitOnStackStatus stackName SSCreateComplete NoAbsent
say "stack was successfully created"
updateCfStack
:: Members '[ LambdaEff, CfEff, GenEff, ConfigEff ] effs
=> LBS.ByteString
-> Eff effs ()
updateCfStack template = do
config <- getConfig
let appName = config ^. namePrefix
stackName = StackName appName
say "updating the stack..."
updateStack stackName template
say "waiting on the stack to be updated..."
waitOnStackStatus stackName SSUpdateComplete NoAbsent
-- TODO: make lambda updating concurrent with the above stack update?
updateLambdas
say "stack was successfully updated"
updateLambdas
:: Members '[ LambdaEff, GenEff, ConfigEff ] effs
=> Eff effs ()
updateLambdas = do
config <- getConfig
let lbdS3Obj = s3Object (S3.getIdByName config "app") $ S3Key "lambda.zip"
say "updating the lambdas..."
traverse_ ((`Lbd.update` lbdS3Obj) . Lbd.getIdByName config . getName config)
(getAll config :: [ Lambda ])
describeCfStack
:: Members '[ CfEff, GenEff, ConfigEff ] effs
=> Eff effs ()
describeCfStack = do
config <- getConfig
let stackName = StackName $ config ^. namePrefix
stackDict <- describeStacks
maybe (panic $ "stack '" <> show stackName <> "' not found") (say . toS . encodePretty) $ Map.lookup stackName stackDict
destroyCfStack
:: Members '[ LambdaEff, CfEff, S3Eff, GenEff, ConfigEff ] effs
=> Eff effs ()
-> Eff effs ()
destroyCfStack action = do
config <- getConfig
let stackName = StackName $ config ^. namePrefix
say "destroying the stack..."
clearBuckets
deleteStack stackName
action
say "waiting on the stack to be destroyed..."
waitOnStackStatus stackName SSDeleteComplete AbsentOk
say "stack was successfully destroyed"
cycleStack
:: Members '[ LambdaEff, CfEff, S3Eff, GenEff, ConfigEff ] effs
=> LBS.ByteString
-> LBS.ByteString
-> Eff effs ()
cycleStack template content = do
destroyCfStack $ deployApp template content
createCfStack template
say "all done!"
printLogs
:: Members '[ GenEff, ConfigEff ] effs
=> Text
-> Eff effs ()
printLogs lbdName = do
config <- getConfig
let lbdId = Lbd.getIdByName config lbdName
lbd = getById config lbdId :: Lambda
groupName = "/aws/lambda/" <> show (getPhysicalName config lbd)
res <- amazonka cloudWatchLogs $ filterLogEvents groupName
traverse_ say . catMaybes $ (^.fleMessage) <$> res ^. flersEvents
|
ababkin/qmuli
|
library/Qi/CLI/Dispatcher.hs
|
mit
| 4,996
| 0
| 14
| 1,254
| 1,281
| 673
| 608
| 130
| 1
|
module Main (main) where
import System.Environment (getEnv)
import Network.Wai.Middleware.RequestLogger (logStdoutDev)
import Web.Scotty (scotty, middleware)
import Middleware (allowCORS)
import Routes (handleRequest)
import qualified Storage as DB (setup)
main :: IO ()
main = do
DB.setup
port <- read <$> getEnv "PORT"
scotty port $ do
middleware allowCORS
middleware logStdoutDev
handleRequest
|
vyorkin-archive/assignment
|
api/src/Main.hs
|
mit
| 436
| 0
| 10
| 88
| 130
| 71
| 59
| 15
| 1
|
module SynRec where
type A = B
type B = C
type C = D
type D = A
|
roberth/uu-helium
|
test/staticerrors/SynRec.hs
|
gpl-3.0
| 65
| 0
| 4
| 20
| 28
| 19
| 9
| 5
| 0
|
module PointInPolygon where
type Point = (Double, Double)
x p = fst p
y p = snd p
tol = 0.0001
diff p1 p2 = ((x p1) - (x p2), (y p1) - (y p2))
vmod p = sqrt ((x p) * (x p) + (y p) * (y p))
vdot p1 p2 = (x p1) * (x p2) + (y p1) * (y p2)
angle p1 p2 = acos ((vdot p1 p2) / ((vmod p1) * (vmod p2)))
feq x y = abs (x - y) < tol
pointWithinAngle p1 root p2 t = let sp1 = diff p1 root
sp2 = diff p2 root
st = diff t root
in
feq ((angle sp1 st) + (angle st sp2)) (angle sp1 sp2)
pointInTriangle a b c t = (pointWithinAngle a b c t) && (pointWithinAngle b c a t)
pointInPoly :: [Point] -> Point -> Bool
pointInPoly poly point = let root = head poly
l1 = init $ drop 1 poly
l2 = drop 2 poly
in any (\(p1, p2) -> pointInTriangle p1 root p2 point) $ zip l1 l2
|
lisphacker/codewars
|
PointInPolygon_flymake.hs
|
bsd-2-clause
| 981
| 0
| 11
| 414
| 485
| 246
| 239
| 20
| 1
|
{-# OPTIONS -Wall -Werror #-}
module Main where
import Data.Time.Calendar.MonthDay
showCompare :: (Eq a,Show a) => a -> String -> a -> String
showCompare a1 b a2 | a1 == a2 = (show a1) ++ " == " ++ b
showCompare a1 b a2 = "DIFF: " ++ (show a1) ++ " -> " ++ b ++ " -> " ++ (show a2)
main :: IO ()
main = mapM_ (\isLeap -> do
putStrLn (if isLeap then "Leap:" else "Regular:")
mapM_ (\yd -> do
let (m,d) = dayOfYearToMonthAndDay isLeap yd
let yd' = monthAndDayToDayOfYear isLeap m d
let mdtext = (show m) ++ "-" ++ (show d)
putStrLn (showCompare yd mdtext yd')
) [-2..369]
) [False,True]
|
takano-akio/time
|
test/TestMonthDay.hs
|
bsd-3-clause
| 602
| 0
| 21
| 133
| 280
| 143
| 137
| 16
| 2
|
{-# LANGUAGE CPP, DeriveDataTypeable, MultiParamTypeClasses, FlexibleInstances, ScopedTypeVariables #-}
-- |
-- Module : Data.Vector.Storable.Mutable
-- Copyright : (c) Roman Leshchinskiy 2009-2010
-- License : BSD-style
--
-- Maintainer : Roman Leshchinskiy <rl@cse.unsw.edu.au>
-- Stability : experimental
-- Portability : non-portable
--
-- Mutable vectors based on Storable.
--
module Data.Vector.Storable.Mutable(
-- * Mutable vectors of 'Storable' types
MVector(..), IOVector, STVector, Storable,
-- * Accessors
-- ** Length information
length, null,
-- ** Extracting subvectors
slice, init, tail, take, drop, splitAt,
unsafeSlice, unsafeInit, unsafeTail, unsafeTake, unsafeDrop,
-- ** Overlapping
overlaps,
-- * Construction
-- ** Initialisation
new, unsafeNew, replicate, replicateM, clone,
-- ** Growing
grow, unsafeGrow,
-- ** Restricting memory usage
clear,
-- * Accessing individual elements
read, write, modify, swap,
unsafeRead, unsafeWrite, unsafeModify, unsafeSwap,
-- * Modifying vectors
-- ** Filling and copying
set, copy, move, unsafeCopy, unsafeMove,
-- * Unsafe conversions
unsafeCast,
-- * Raw pointers
unsafeFromForeignPtr, unsafeFromForeignPtr0,
unsafeToForeignPtr, unsafeToForeignPtr0,
unsafeWith
) where
import Control.DeepSeq ( NFData(rnf) )
import qualified Data.Vector.Generic.Mutable as G
import Data.Vector.Storable.Internal
import Foreign.Storable
import Foreign.ForeignPtr
#if __GLASGOW_HASKELL__ >= 605
import GHC.ForeignPtr (mallocPlainForeignPtrBytes)
#endif
import Foreign.Ptr
import Foreign.Marshal.Array ( advancePtr, copyArray, moveArray )
import Control.Monad.Primitive
import Data.Primitive.Addr
import Data.Primitive.Types (Prim)
import GHC.Word (Word8, Word16, Word32, Word64)
import GHC.Ptr (Ptr(..))
import Prelude hiding ( length, null, replicate, reverse, map, read,
take, drop, splitAt, init, tail )
import Data.Typeable ( Typeable )
-- Data.Vector.Internal.Check is not needed
#define NOT_VECTOR_MODULE
#include "vector.h"
-- | Mutable 'Storable'-based vectors
data MVector s a = MVector {-# UNPACK #-} !Int
{-# UNPACK #-} !(ForeignPtr a)
deriving ( Typeable )
type IOVector = MVector RealWorld
type STVector s = MVector s
instance NFData (MVector s a) where
rnf (MVector _ _) = ()
instance Storable a => G.MVector MVector a where
{-# INLINE basicLength #-}
basicLength (MVector n _) = n
{-# INLINE basicUnsafeSlice #-}
basicUnsafeSlice j m (MVector _ fp) = MVector m (updPtr (`advancePtr` j) fp)
-- FIXME: this relies on non-portable pointer comparisons
{-# INLINE basicOverlaps #-}
basicOverlaps (MVector m fp) (MVector n fq)
= between p q (q `advancePtr` n) || between q p (p `advancePtr` m)
where
between x y z = x >= y && x < z
p = getPtr fp
q = getPtr fq
{-# INLINE basicUnsafeNew #-}
basicUnsafeNew n
| n < 0 = error $ "Storable.basicUnsafeNew: negative length: " ++ show n
| n > mx = error $ "Storable.basicUnsafeNew: length too large: " ++ show n
| otherwise = unsafePrimToPrim $ do
fp <- mallocVector n
return $ MVector n fp
where
size = sizeOf (undefined :: a)
mx = maxBound `quot` size :: Int
{-# INLINE basicInitialize #-}
basicInitialize = storableZero
{-# INLINE basicUnsafeRead #-}
basicUnsafeRead (MVector _ fp) i
= unsafePrimToPrim
$ withForeignPtr fp (`peekElemOff` i)
{-# INLINE basicUnsafeWrite #-}
basicUnsafeWrite (MVector _ fp) i x
= unsafePrimToPrim
$ withForeignPtr fp $ \p -> pokeElemOff p i x
{-# INLINE basicSet #-}
basicSet = storableSet
{-# INLINE basicUnsafeCopy #-}
basicUnsafeCopy (MVector n fp) (MVector _ fq)
= unsafePrimToPrim
$ withForeignPtr fp $ \p ->
withForeignPtr fq $ \q ->
copyArray p q n
{-# INLINE basicUnsafeMove #-}
basicUnsafeMove (MVector n fp) (MVector _ fq)
= unsafePrimToPrim
$ withForeignPtr fp $ \p ->
withForeignPtr fq $ \q ->
moveArray p q n
storableZero :: forall a m. (Storable a, PrimMonad m) => MVector (PrimState m) a -> m ()
{-# INLINE storableZero #-}
storableZero (MVector n fp) = unsafePrimToPrim . withForeignPtr fp $ \(Ptr p) -> do
let q = Addr p
setAddr q byteSize (0 :: Word8)
where
x :: a
x = undefined
byteSize :: Int
byteSize = n * sizeOf x
storableSet :: (Storable a, PrimMonad m) => MVector (PrimState m) a -> a -> m ()
{-# INLINE storableSet #-}
storableSet (MVector n fp) x
| n == 0 = return ()
| otherwise = unsafePrimToPrim $
case sizeOf x of
1 -> storableSetAsPrim n fp x (undefined :: Word8)
2 -> storableSetAsPrim n fp x (undefined :: Word16)
4 -> storableSetAsPrim n fp x (undefined :: Word32)
8 -> storableSetAsPrim n fp x (undefined :: Word64)
_ -> withForeignPtr fp $ \p -> do
poke p x
let do_set i
| 2*i < n = do
copyArray (p `advancePtr` i) p i
do_set (2*i)
| otherwise = copyArray (p `advancePtr` i) p (n-i)
do_set 1
storableSetAsPrim
:: (Storable a, Prim b) => Int -> ForeignPtr a -> a -> b -> IO ()
{-# INLINE [0] storableSetAsPrim #-}
storableSetAsPrim n fp x y = withForeignPtr fp $ \(Ptr p) -> do
poke (Ptr p) x
let q = Addr p
w <- readOffAddr q 0
setAddr (q `plusAddr` sizeOf x) (n-1) (w `asTypeOf` y)
{-# INLINE mallocVector #-}
mallocVector :: Storable a => Int -> IO (ForeignPtr a)
mallocVector =
#if __GLASGOW_HASKELL__ >= 605
doMalloc undefined
where
doMalloc :: Storable b => b -> Int -> IO (ForeignPtr b)
doMalloc dummy size = mallocPlainForeignPtrBytes (size * sizeOf dummy)
#else
mallocForeignPtrArray
#endif
-- Length information
-- ------------------
-- | Length of the mutable vector.
length :: Storable a => MVector s a -> Int
{-# INLINE length #-}
length = G.length
-- | Check whether the vector is empty
null :: Storable a => MVector s a -> Bool
{-# INLINE null #-}
null = G.null
-- Extracting subvectors
-- ---------------------
-- | Yield a part of the mutable vector without copying it.
slice :: Storable a => Int -> Int -> MVector s a -> MVector s a
{-# INLINE slice #-}
slice = G.slice
take :: Storable a => Int -> MVector s a -> MVector s a
{-# INLINE take #-}
take = G.take
drop :: Storable a => Int -> MVector s a -> MVector s a
{-# INLINE drop #-}
drop = G.drop
splitAt :: Storable a => Int -> MVector s a -> (MVector s a, MVector s a)
{-# INLINE splitAt #-}
splitAt = G.splitAt
init :: Storable a => MVector s a -> MVector s a
{-# INLINE init #-}
init = G.init
tail :: Storable a => MVector s a -> MVector s a
{-# INLINE tail #-}
tail = G.tail
-- | Yield a part of the mutable vector without copying it. No bounds checks
-- are performed.
unsafeSlice :: Storable a
=> Int -- ^ starting index
-> Int -- ^ length of the slice
-> MVector s a
-> MVector s a
{-# INLINE unsafeSlice #-}
unsafeSlice = G.unsafeSlice
unsafeTake :: Storable a => Int -> MVector s a -> MVector s a
{-# INLINE unsafeTake #-}
unsafeTake = G.unsafeTake
unsafeDrop :: Storable a => Int -> MVector s a -> MVector s a
{-# INLINE unsafeDrop #-}
unsafeDrop = G.unsafeDrop
unsafeInit :: Storable a => MVector s a -> MVector s a
{-# INLINE unsafeInit #-}
unsafeInit = G.unsafeInit
unsafeTail :: Storable a => MVector s a -> MVector s a
{-# INLINE unsafeTail #-}
unsafeTail = G.unsafeTail
-- Overlapping
-- -----------
-- | Check whether two vectors overlap.
overlaps :: Storable a => MVector s a -> MVector s a -> Bool
{-# INLINE overlaps #-}
overlaps = G.overlaps
-- Initialisation
-- --------------
-- | Create a mutable vector of the given length.
new :: (PrimMonad m, Storable a) => Int -> m (MVector (PrimState m) a)
{-# INLINE new #-}
new = G.new
-- | Create a mutable vector of the given length. The length is not checked.
unsafeNew :: (PrimMonad m, Storable a) => Int -> m (MVector (PrimState m) a)
{-# INLINE unsafeNew #-}
unsafeNew = G.unsafeNew
-- | Create a mutable vector of the given length (0 if the length is negative)
-- and fill it with an initial value.
replicate :: (PrimMonad m, Storable a) => Int -> a -> m (MVector (PrimState m) a)
{-# INLINE replicate #-}
replicate = G.replicate
-- | Create a mutable vector of the given length (0 if the length is negative)
-- and fill it with values produced by repeatedly executing the monadic action.
replicateM :: (PrimMonad m, Storable a) => Int -> m a -> m (MVector (PrimState m) a)
{-# INLINE replicateM #-}
replicateM = G.replicateM
-- | Create a copy of a mutable vector.
clone :: (PrimMonad m, Storable a)
=> MVector (PrimState m) a -> m (MVector (PrimState m) a)
{-# INLINE clone #-}
clone = G.clone
-- Growing
-- -------
-- | Grow a vector by the given number of elements. The number must be
-- positive.
grow :: (PrimMonad m, Storable a)
=> MVector (PrimState m) a -> Int -> m (MVector (PrimState m) a)
{-# INLINE grow #-}
grow = G.grow
-- | Grow a vector by the given number of elements. The number must be
-- positive but this is not checked.
unsafeGrow :: (PrimMonad m, Storable a)
=> MVector (PrimState m) a -> Int -> m (MVector (PrimState m) a)
{-# INLINE unsafeGrow #-}
unsafeGrow = G.unsafeGrow
-- Restricting memory usage
-- ------------------------
-- | Reset all elements of the vector to some undefined value, clearing all
-- references to external objects. This is usually a noop for unboxed vectors.
clear :: (PrimMonad m, Storable a) => MVector (PrimState m) a -> m ()
{-# INLINE clear #-}
clear = G.clear
-- Accessing individual elements
-- -----------------------------
-- | Yield the element at the given position.
read :: (PrimMonad m, Storable a) => MVector (PrimState m) a -> Int -> m a
{-# INLINE read #-}
read = G.read
-- | Replace the element at the given position.
write
:: (PrimMonad m, Storable a) => MVector (PrimState m) a -> Int -> a -> m ()
{-# INLINE write #-}
write = G.write
-- | Modify the element at the given position.
modify :: (PrimMonad m, Storable a) => MVector (PrimState m) a -> (a -> a) -> Int -> m ()
{-# INLINE modify #-}
modify = G.modify
-- | Swap the elements at the given positions.
swap
:: (PrimMonad m, Storable a) => MVector (PrimState m) a -> Int -> Int -> m ()
{-# INLINE swap #-}
swap = G.swap
-- | Yield the element at the given position. No bounds checks are performed.
unsafeRead :: (PrimMonad m, Storable a) => MVector (PrimState m) a -> Int -> m a
{-# INLINE unsafeRead #-}
unsafeRead = G.unsafeRead
-- | Replace the element at the given position. No bounds checks are performed.
unsafeWrite
:: (PrimMonad m, Storable a) => MVector (PrimState m) a -> Int -> a -> m ()
{-# INLINE unsafeWrite #-}
unsafeWrite = G.unsafeWrite
-- | Modify the element at the given position. No bounds checks are performed.
unsafeModify :: (PrimMonad m, Storable a) => MVector (PrimState m) a -> (a -> a) -> Int -> m ()
{-# INLINE unsafeModify #-}
unsafeModify = G.unsafeModify
-- | Swap the elements at the given positions. No bounds checks are performed.
unsafeSwap
:: (PrimMonad m, Storable a) => MVector (PrimState m) a -> Int -> Int -> m ()
{-# INLINE unsafeSwap #-}
unsafeSwap = G.unsafeSwap
-- Filling and copying
-- -------------------
-- | Set all elements of the vector to the given value.
set :: (PrimMonad m, Storable a) => MVector (PrimState m) a -> a -> m ()
{-# INLINE set #-}
set = G.set
-- | Copy a vector. The two vectors must have the same length and may not
-- overlap.
copy :: (PrimMonad m, Storable a)
=> MVector (PrimState m) a -> MVector (PrimState m) a -> m ()
{-# INLINE copy #-}
copy = G.copy
-- | Copy a vector. The two vectors must have the same length and may not
-- overlap. This is not checked.
unsafeCopy :: (PrimMonad m, Storable a)
=> MVector (PrimState m) a -- ^ target
-> MVector (PrimState m) a -- ^ source
-> m ()
{-# INLINE unsafeCopy #-}
unsafeCopy = G.unsafeCopy
-- | Move the contents of a vector. The two vectors must have the same
-- length.
--
-- If the vectors do not overlap, then this is equivalent to 'copy'.
-- Otherwise, the copying is performed as if the source vector were
-- copied to a temporary vector and then the temporary vector was copied
-- to the target vector.
move :: (PrimMonad m, Storable a)
=> MVector (PrimState m) a -> MVector (PrimState m) a -> m ()
{-# INLINE move #-}
move = G.move
-- | Move the contents of a vector. The two vectors must have the same
-- length, but this is not checked.
--
-- If the vectors do not overlap, then this is equivalent to 'unsafeCopy'.
-- Otherwise, the copying is performed as if the source vector were
-- copied to a temporary vector and then the temporary vector was copied
-- to the target vector.
unsafeMove :: (PrimMonad m, Storable a)
=> MVector (PrimState m) a -- ^ target
-> MVector (PrimState m) a -- ^ source
-> m ()
{-# INLINE unsafeMove #-}
unsafeMove = G.unsafeMove
-- Unsafe conversions
-- ------------------
-- | /O(1)/ Unsafely cast a mutable vector from one element type to another.
-- The operation just changes the type of the underlying pointer and does not
-- modify the elements.
--
-- The resulting vector contains as many elements as can fit into the
-- underlying memory block.
--
unsafeCast :: forall a b s.
(Storable a, Storable b) => MVector s a -> MVector s b
{-# INLINE unsafeCast #-}
unsafeCast (MVector n fp)
= MVector ((n * sizeOf (undefined :: a)) `div` sizeOf (undefined :: b))
(castForeignPtr fp)
-- Raw pointers
-- ------------
-- | Create a mutable vector from a 'ForeignPtr' with an offset and a length.
--
-- Modifying data through the 'ForeignPtr' afterwards is unsafe if the vector
-- could have been frozen before the modification.
--
-- If your offset is 0 it is more efficient to use 'unsafeFromForeignPtr0'.
unsafeFromForeignPtr :: Storable a
=> ForeignPtr a -- ^ pointer
-> Int -- ^ offset
-> Int -- ^ length
-> MVector s a
{-# INLINE_FUSED unsafeFromForeignPtr #-}
unsafeFromForeignPtr fp i n = unsafeFromForeignPtr0 fp' n
where
fp' = updPtr (`advancePtr` i) fp
{-# RULES
"unsafeFromForeignPtr fp 0 n -> unsafeFromForeignPtr0 fp n " forall fp n.
unsafeFromForeignPtr fp 0 n = unsafeFromForeignPtr0 fp n #-}
-- | /O(1)/ Create a mutable vector from a 'ForeignPtr' and a length.
--
-- It is assumed the pointer points directly to the data (no offset).
-- Use `unsafeFromForeignPtr` if you need to specify an offset.
--
-- Modifying data through the 'ForeignPtr' afterwards is unsafe if the vector
-- could have been frozen before the modification.
unsafeFromForeignPtr0 :: Storable a
=> ForeignPtr a -- ^ pointer
-> Int -- ^ length
-> MVector s a
{-# INLINE unsafeFromForeignPtr0 #-}
unsafeFromForeignPtr0 fp n = MVector n fp
-- | Yield the underlying 'ForeignPtr' together with the offset to the data
-- and its length. Modifying the data through the 'ForeignPtr' is
-- unsafe if the vector could have frozen before the modification.
unsafeToForeignPtr :: Storable a => MVector s a -> (ForeignPtr a, Int, Int)
{-# INLINE unsafeToForeignPtr #-}
unsafeToForeignPtr (MVector n fp) = (fp, 0, n)
-- | /O(1)/ Yield the underlying 'ForeignPtr' together with its length.
--
-- You can assume the pointer points directly to the data (no offset).
--
-- Modifying the data through the 'ForeignPtr' is unsafe if the vector could
-- have frozen before the modification.
unsafeToForeignPtr0 :: Storable a => MVector s a -> (ForeignPtr a, Int)
{-# INLINE unsafeToForeignPtr0 #-}
unsafeToForeignPtr0 (MVector n fp) = (fp, n)
-- | Pass a pointer to the vector's data to the IO action. Modifying data
-- through the pointer is unsafe if the vector could have been frozen before
-- the modification.
unsafeWith :: Storable a => IOVector a -> (Ptr a -> IO b) -> IO b
{-# INLINE unsafeWith #-}
unsafeWith (MVector _ fp) = withForeignPtr fp
|
seckcoder/vector
|
Data/Vector/Storable/Mutable.hs
|
bsd-3-clause
| 16,467
| 0
| 22
| 3,905
| 3,857
| 2,092
| 1,765
| 277
| 5
|
module Lambda1 where
zip' = zipWith (\a b -> (a,b))
|
charleso/intellij-haskforce
|
tests/gold/parser/Lambda00001.hs
|
apache-2.0
| 53
| 0
| 8
| 11
| 28
| 17
| 11
| 2
| 1
|
{-# OPTIONS_GHC -Wall #-}
module Canonicalize.Sort (definitions) where
import Control.Monad.State
import Control.Applicative ((<$>),(<*>))
import qualified Data.Graph as Graph
import qualified Data.Map as Map
import qualified Data.Maybe as Maybe
import qualified Data.Set as Set
import AST.Expression.General (Expr'(..), PortImpl(..))
import qualified AST.Expression.Canonical as Canonical
import qualified AST.Pattern as P
import qualified AST.Variable as V
import qualified Reporting.Annotation as A
-- STARTING POINT
definitions :: Canonical.Expr -> Canonical.Expr
definitions expression =
evalState (reorder expression) Set.empty
free :: String -> State (Set.Set String) ()
free x =
modify (Set.insert x)
freeIfLocal :: V.Canonical -> State (Set.Set String) ()
freeIfLocal (V.Canonical home name) =
case home of
V.Local -> free name
V.BuiltIn -> return ()
V.Module _ -> return ()
-- REORDER EXPRESSIONS
reorder :: Canonical.Expr -> State (Set.Set String) Canonical.Expr
reorder (A.A ann expression) =
A.A ann <$>
case expression of
-- Be careful adding and restricting freeVars
Var var ->
do freeIfLocal var
return expression
Lambda pattern body ->
uncurry Lambda <$> bindingReorder (pattern,body)
Binop op leftExpr rightExpr ->
do freeIfLocal op
Binop op <$> reorder leftExpr <*> reorder rightExpr
Case expr cases ->
Case <$> reorder expr <*> mapM bindingReorder cases
Data name exprs ->
do free name
Data name <$> mapM reorder exprs
-- Just pipe the reorder though
Literal _ ->
return expression
Range lowExpr highExpr ->
Range <$> reorder lowExpr <*> reorder highExpr
ExplicitList es ->
ExplicitList <$> mapM reorder es
App func arg ->
App <$> reorder func <*> reorder arg
MultiIf branches ->
MultiIf <$> mapM (\(cond,branch) -> (,) <$> reorder cond <*> reorder branch) branches
Access record field ->
Access <$> reorder record <*> return field
Remove record field ->
Remove <$> reorder record <*> return field
Insert record field expr ->
Insert <$> reorder record <*> return field <*> reorder expr
Modify record fields ->
Modify
<$> reorder record
<*> mapM (\(field,expr) -> (,) field <$> reorder expr) fields
Record fields ->
Record
<$> mapM (\(field,expr) -> (,) field <$> reorder expr) fields
GLShader _ _ _ ->
return expression
Port impl ->
Port <$>
case impl of
In _ _ ->
return impl
Out name expr tipe ->
(\e -> Out name e tipe) <$> reorder expr
Task name expr tipe ->
(\e -> Task name e tipe) <$> reorder expr
-- Actually do some reordering
Let defs body ->
do body' <- reorder body
-- Sort defs into strongly connected components.This
-- allows the programmer to write definitions in whatever
-- order they please, we can still define things in order
-- and generalize polymorphic functions when appropriate.
sccs <- Graph.stronglyConnComp <$> buildDefGraph defs
let defss = map Graph.flattenSCC sccs
-- remove let-bound variables from the context
forM_ defs $ \(Canonical.Definition pattern _ _) -> do
bound pattern
mapM free (ctors pattern)
let (A.A _ let') =
foldr (\ds bod -> A.A ann (Let ds bod)) body' defss
return let'
ctors :: P.CanonicalPattern -> [String]
ctors (A.A _ pattern) =
case pattern of
P.Var _ ->
[]
P.Alias _ p ->
ctors p
P.Record _ ->
[]
P.Anything ->
[]
P.Literal _ ->
[]
P.Data (V.Canonical home name) ps ->
case home of
V.Local -> name : rest
V.BuiltIn -> rest
V.Module _ -> rest
where
rest = concatMap ctors ps
bound :: P.CanonicalPattern -> State (Set.Set String) ()
bound pattern =
let boundVars = P.boundVarSet pattern
in
modify (\freeVars -> Set.difference freeVars boundVars)
bindingReorder
:: (P.CanonicalPattern, Canonical.Expr)
-> State (Set.Set String) (P.CanonicalPattern, Canonical.Expr)
bindingReorder (pattern, expr) =
do expr' <- reorder expr
bound pattern
mapM_ free (ctors pattern)
return (pattern, expr')
-- BUILD DEPENDENCY GRAPH BETWEEN DEFINITIONS
-- This also reorders the all of the sub-expressions in the Def list.
buildDefGraph
:: [Canonical.Def]
-> State (Set.Set String) [(Canonical.Def, Int, [Int])]
buildDefGraph defs =
do pdefsDeps <- mapM reorderAndGetDependencies defs
return $ realDeps (addKey pdefsDeps)
where
addKey :: [(Canonical.Def, [String])] -> [(Canonical.Def, Int, [String])]
addKey =
zipWith (\n (pdef,deps) -> (pdef,n,deps)) [0..]
variableToKey :: (Canonical.Def, Int, [String]) -> [(String, Int)]
variableToKey (Canonical.Definition pattern _ _, key, _) =
[ (var, key) | var <- P.boundVarList pattern ]
variableToKeyMap :: [(Canonical.Def, Int, [String])] -> Map.Map String Int
variableToKeyMap pdefsDeps =
Map.fromList (concatMap variableToKey pdefsDeps)
realDeps :: [(Canonical.Def, Int, [String])] -> [(Canonical.Def, Int, [Int])]
realDeps pdefsDeps =
map convert pdefsDeps
where
varDict = variableToKeyMap pdefsDeps
convert (pdef, key, deps) =
(pdef, key, Maybe.mapMaybe (flip Map.lookup varDict) deps)
reorderAndGetDependencies
:: Canonical.Def
-> State (Set.Set String) (Canonical.Def, [String])
reorderAndGetDependencies (Canonical.Definition pattern expr mType) =
do globalFrees <- get
-- work in a fresh environment
put Set.empty
expr' <- reorder expr
localFrees <- get
-- merge with global frees
modify (Set.union globalFrees)
return (Canonical.Definition pattern expr' mType, Set.toList localFrees)
|
JoeyEremondi/elm-summer-opt
|
src/Canonicalize/Sort.hs
|
bsd-3-clause
| 6,335
| 0
| 19
| 1,910
| 1,958
| 997
| 961
| 148
| 20
|
no = \x -> f x (g x)
|
bitemyapp/apply-refact
|
tests/examples/Default33.hs
|
bsd-3-clause
| 20
| 0
| 8
| 7
| 22
| 11
| 11
| 1
| 1
|
module A5 where
data Data1 b a = C1 a Int Char | C2 Int | C3 b Float
f :: (Data1 b a) -> Int
f (C1 a b c) = b -- errorData "b" "Data.C1" "f"
f (C2 a) = a
f (C3 c3_1 a) = 42
g (C1 (C1 x y z) b c) = y
h :: Data1 b a
h = C2 42
|
kmate/HaRe
|
old/testing/addField/A5_TokOut.hs
|
bsd-3-clause
| 227
| 0
| 9
| 71
| 143
| 76
| 67
| 9
| 1
|
{-# LANGUAGE FlexibleContexts #-}
module OutputM (module IxOutputM, F.HasOutput, outputTree, output, outputs)
where
import IxOutputM hiding (HasOutput(..))
import qualified MT as F
import Tree
outputTree :: F.HasOutput m F.Z o => Tree o -> m ()
output :: F.HasOutput m F.Z o => o -> m ()
outputs :: F.HasOutput m F.Z o => [o] -> m ()
outputTree = F.outputTree F.this
output = F.output F.this
outputs = F.outputs F.this
|
kmate/HaRe
|
old/tools/base/lib/Monads/OutputM.hs
|
bsd-3-clause
| 438
| 0
| 8
| 89
| 176
| 96
| 80
| 11
| 1
|
module PropLexer(module PropLexer{-,LexerFlags(..)-}) where
--import LexerOptions
import HsLexerPass1(lexerPass0,lexerPass0',startPos)
import HsTokens
{-+
This module defines the lexical analyser for the P-logic extension of Haskell.
Differences from the plain Haskell 98 lexical syntax:
- The identifiers "assert" and "property" are reserved.
- The contents of nested comments of the form {-P: ... -} are parsed as
normal code, providing a convenient way to hide assertions and predicate
declarations from standard Haskell impementations.
-}
pLexerPass0 plogic =
if plogic
then propLexerPass0
else lexerPass0
where
propLexerPass0 = propLexerPass0' startPos
propLexerPass0' pos = concatMap plogicTokens . lexerPass0' pos
plogicTokens t@(Varid,ps@(_,s)) =
case s of
"assert" -> [(Reservedid,ps)]
"property" -> [(Reservedid,ps)]
_ -> [t]
plogicTokens t@(NestedComment,ps@(p,'{':'-':'P':':':s)) =
propLexerPass0' p (adjust s)
plogicTokens t = [t]
-- Replace the delimiting "{-P:" and "-}" with the same amount of space
-- to preserve layout.
adjust s = " "++reverse (" "++drop 2 (reverse s))
|
forste/haReFork
|
tools/property/parse2/PropLexer.hs
|
bsd-3-clause
| 1,185
| 4
| 19
| 242
| 245
| 137
| 108
| 18
| 6
|
-----------------------------------------------------------------------------
-- |
-- Module : Text.ParserCombinators.Parsec
-- Copyright : (c) Paolo Martini 2007
-- License : BSD-style (see the LICENSE file)
--
-- Maintainer : derek.a.elkins@gmail.com
-- Stability : provisional
-- Portability : portable
--
-- Parsec compatibility module
--
-----------------------------------------------------------------------------
module Text.ParserCombinators.Parsec
( -- complete modules
module Text.ParserCombinators.Parsec.Prim
, module Text.ParserCombinators.Parsec.Combinator
, module Text.ParserCombinators.Parsec.Char
-- module Text.ParserCombinators.Parsec.Error
, ParseError
, errorPos
-- module Text.ParserCombinators.Parsec.Pos
, SourcePos
, SourceName, Line, Column
, sourceName, sourceLine, sourceColumn
, incSourceLine, incSourceColumn
, setSourceLine, setSourceColumn, setSourceName
) where
import Text.Parsec.String()
import Text.ParserCombinators.Parsec.Prim
import Text.ParserCombinators.Parsec.Combinator
import Text.ParserCombinators.Parsec.Char
import Text.ParserCombinators.Parsec.Error
import Text.ParserCombinators.Parsec.Pos
|
maurer/15-411-Haskell-Base-Code
|
src/Text/ParserCombinators/Parsec.hs
|
bsd-3-clause
| 1,229
| 0
| 5
| 185
| 135
| 99
| 36
| 18
| 0
|
module Tests.Writers.Docx (tests) where
import Text.Pandoc.Options
import Text.Pandoc.Readers.Native
import Text.Pandoc.Definition
import Tests.Helpers
import Test.Framework
import Text.Pandoc.Readers.Docx
import Text.Pandoc.Writers.Docx
import Text.Pandoc.Error
type Options = (WriterOptions, ReaderOptions)
compareOutput :: Options
-> FilePath
-> IO (Pandoc, Pandoc)
compareOutput opts nativeFile = do
nf <- Prelude.readFile nativeFile
df <- writeDocx (fst opts) (handleError $ readNative nf)
let (p, _) = handleError $ readDocx (snd opts) df
return (p, handleError $ readNative nf)
testCompareWithOptsIO :: Options -> String -> FilePath -> IO Test
testCompareWithOptsIO opts name nativeFile = do
(dp, np) <- compareOutput opts nativeFile
return $ test id name (dp, np)
testCompareWithOpts :: Options -> String -> FilePath -> Test
testCompareWithOpts opts name nativeFile =
buildTest $ testCompareWithOptsIO opts name nativeFile
testCompare :: String -> FilePath -> Test
testCompare = testCompareWithOpts def
tests :: [Test]
tests = [ testGroup "inlines"
[ testCompare
"font formatting"
"docx/inline_formatting_writer.native"
, testCompare
"font formatting with character styles"
"docx/char_styles.native"
, testCompare
"hyperlinks"
"docx/links_writer.native"
, testCompare
"inline image"
"docx/image_no_embed_writer.native"
, testCompare
"inline image in links"
"docx/inline_images_writer.native"
, testCompare
"handling unicode input"
"docx/unicode.native"
, testCompare
"literal tabs"
"docx/tabs.native"
, testCompare
"normalizing inlines"
"docx/normalize.native"
, testCompare
"normalizing inlines deep inside blocks"
"docx/deep_normalize.native"
, testCompare
"move trailing spaces outside of formatting"
"docx/trailing_spaces_in_formatting.native"
, testCompare
"inline code (with VerbatimChar style)"
"docx/inline_code.native"
, testCompare
"inline code in subscript and superscript"
"docx/verbatim_subsuper.native"
]
, testGroup "blocks"
[ testCompare
"headers"
"docx/headers.native"
, testCompare
"headers already having auto identifiers"
"docx/already_auto_ident.native"
, testCompare
"numbered headers automatically made into list"
"docx/numbered_header.native"
, testCompare
"i18n blocks (headers and blockquotes)"
"docx/i18n_blocks.native"
-- Continuation does not survive round-trip
, testCompare
"lists"
"docx/lists_writer.native"
, testCompare
"definition lists"
"docx/definition_list.native"
, testCompare
"custom defined lists in styles"
"docx/german_styled_lists.native"
, testCompare
"footnotes and endnotes"
"docx/notes.native"
, testCompare
"blockquotes (parsing indent as blockquote)"
"docx/block_quotes_parse_indent.native"
, testCompare
"hanging indents"
"docx/hanging_indent.native"
-- tables headers do not survive round-trip, should look into that
, testCompare
"tables"
"docx/tables.native"
, testCompare
"tables with lists in cells"
"docx/table_with_list_cell.native"
, testCompare
"code block"
"docx/codeblock.native"
, testCompare
"dropcap paragraphs"
"docx/drop_cap.native"
]
, testGroup "metadata"
[ testCompareWithOpts (def,def{readerStandalone=True})
"metadata fields"
"docx/metadata.native"
, testCompareWithOpts (def,def{readerStandalone=True})
"stop recording metadata with normal text"
"docx/metadata_after_normal.native"
]
]
|
gbataille/pandoc
|
tests/Tests/Writers/Docx.hs
|
gpl-2.0
| 4,350
| 0
| 13
| 1,427
| 621
| 328
| 293
| 115
| 1
|
{-# LANGUAGE UndecidableInstances, FlexibleInstances,
MultiParamTypeClasses, FunctionalDependencies #-}
-- UndecidableInstances now needed because the Coverage Condition fails
-- Hugs failed this functional-dependency test
-- Reported by Iavor Diatchki Feb 05
module ShouldCompile where
data N0
newtype Succ n = Succ n
class Plus a b c | a b -> c
instance Plus N0 n n
instance Plus a b c => Plus (Succ a) b (Succ c)
( # ) :: Plus x y z => x -> y -> z
( # ) = undefined
class BitRep t n | t -> n where
toBits :: t -> n
instance BitRep Bool (Succ N0) where
toBits = error "urk"
instance BitRep (Bool,Bool,Bool) (Succ (Succ (Succ N0))) where
toBits (x,y,z) = toBits x # toBits y # toBits z
-- Hugs complains that it cannot solve the constraint:
-- Plus (Succ N0) (Succ N0) (Succ (Succ N0))
|
spacekitteh/smcghc
|
testsuite/tests/typecheck/should_compile/tc187.hs
|
bsd-3-clause
| 854
| 0
| 11
| 214
| 239
| 130
| 109
| -1
| -1
|
import Data.Array
properDividers' n q
| n < qΒ² = []
| n == qΒ² = [q]
| otherwise = if (n == q * r) then q : r : properDividers' n (q+1)
else properDividers' n (q+1)
where qΒ² = q * q; r = quot n q
properDividers :: Int -> [Int]
properDividers n = 1 : (properDividers' n 2)
isAbundant :: Int -> Bool
isAbundant n = n < (sum . properDividers) n
limit :: Int
limit = 28123
sumOfTwoAbundants' :: [Int] -> Array Int Bool -> Array Int Bool
sumOfTwoAbundants' [] acc = acc
sumOfTwoAbundants' (y:ys) acc
= sumOfTwoAbundants' ys
(acc // [(i, True) | i <- (filter (<=limit) (map (+y) (y:ys)))])
main = do
print (sum [i | (i, n) <- (assocs (sumOfTwoAbundants' abundants initArray)),
n == False])
where abundants = filter isAbundant [1 .. limit-12]
initArray = listArray (1, limit) [False | i <- [1 .. limit]]
|
dpieroux/euler
|
0/0023.hs
|
mit
| 939
| 6
| 16
| 293
| 431
| 228
| 203
| -1
| -1
|
import System.Random (newStdGen, StdGen)
import Graphics.Gloss
import qualified Graphics.Gloss.Interface.IO.Game as G
import Graphics.Gloss.Interface.FRP.Yampa
import FRP.Yampa (Event(..), SF, arr, tag, (>>>))
import Types
import Game
import Rendering
-- | Our game uses up, down, left and right arrows to make the moves, so
-- the first thing we want to do is to parse the Gloss Event into something
-- we are happy to work with (Direction data type)
parseInput :: SF (Event InputEvent) GameInput
parseInput = arr $ \event ->
case event of
Event (G.EventKey (G.SpecialKey G.KeyUp) G.Down _ _) -> event `tag` Types.Up
Event (G.EventKey (G.SpecialKey G.KeyDown) G.Down _ _) -> event `tag` Types.Down
Event (G.EventKey (G.SpecialKey G.KeyLeft) G.Down _ _) -> event `tag` Types.Left
Event (G.EventKey (G.SpecialKey G.KeyRight) G.Down _ _) -> event `tag` Types.Right
_ -> event `tag` None
-- | After parsing the game input and reacting to it we need to draw the
-- current game state which might have been updated
drawGame :: SF GameState Picture
drawGame = arr drawBoard
-- | Our main signal function which is responsible for handling the whole
-- game process, starting from parsing the input, moving to the game logic
-- based on that input and finally drawing the resulting game state to
-- Gloss' Picture
mainSF :: StdGen -> SF (Event InputEvent) Picture
mainSF g = parseInput >>> wholeGame g >>> drawGame
main :: IO ()
main = do
g <- newStdGen
playYampa
(InWindow "2048 game" (410, 500) (200, 200))
white
30
(mainSF g)
|
ksaveljev/yampa-2048
|
src/Main.hs
|
mit
| 1,580
| 0
| 15
| 306
| 421
| 233
| 188
| 28
| 5
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-as-lifecyclehook.html
module Stratosphere.Resources.AutoScalingLifecycleHook where
import Stratosphere.ResourceImports
-- | Full data type definition for AutoScalingLifecycleHook. See
-- 'autoScalingLifecycleHook' for a more convenient constructor.
data AutoScalingLifecycleHook =
AutoScalingLifecycleHook
{ _autoScalingLifecycleHookAutoScalingGroupName :: Val Text
, _autoScalingLifecycleHookDefaultResult :: Maybe (Val Text)
, _autoScalingLifecycleHookHeartbeatTimeout :: Maybe (Val Integer)
, _autoScalingLifecycleHookLifecycleHookName :: Maybe (Val Text)
, _autoScalingLifecycleHookLifecycleTransition :: Val Text
, _autoScalingLifecycleHookNotificationMetadata :: Maybe (Val Text)
, _autoScalingLifecycleHookNotificationTargetARN :: Maybe (Val Text)
, _autoScalingLifecycleHookRoleARN :: Maybe (Val Text)
} deriving (Show, Eq)
instance ToResourceProperties AutoScalingLifecycleHook where
toResourceProperties AutoScalingLifecycleHook{..} =
ResourceProperties
{ resourcePropertiesType = "AWS::AutoScaling::LifecycleHook"
, resourcePropertiesProperties =
hashMapFromList $ catMaybes
[ (Just . ("AutoScalingGroupName",) . toJSON) _autoScalingLifecycleHookAutoScalingGroupName
, fmap (("DefaultResult",) . toJSON) _autoScalingLifecycleHookDefaultResult
, fmap (("HeartbeatTimeout",) . toJSON) _autoScalingLifecycleHookHeartbeatTimeout
, fmap (("LifecycleHookName",) . toJSON) _autoScalingLifecycleHookLifecycleHookName
, (Just . ("LifecycleTransition",) . toJSON) _autoScalingLifecycleHookLifecycleTransition
, fmap (("NotificationMetadata",) . toJSON) _autoScalingLifecycleHookNotificationMetadata
, fmap (("NotificationTargetARN",) . toJSON) _autoScalingLifecycleHookNotificationTargetARN
, fmap (("RoleARN",) . toJSON) _autoScalingLifecycleHookRoleARN
]
}
-- | Constructor for 'AutoScalingLifecycleHook' containing required fields as
-- arguments.
autoScalingLifecycleHook
:: Val Text -- ^ 'aslhAutoScalingGroupName'
-> Val Text -- ^ 'aslhLifecycleTransition'
-> AutoScalingLifecycleHook
autoScalingLifecycleHook autoScalingGroupNamearg lifecycleTransitionarg =
AutoScalingLifecycleHook
{ _autoScalingLifecycleHookAutoScalingGroupName = autoScalingGroupNamearg
, _autoScalingLifecycleHookDefaultResult = Nothing
, _autoScalingLifecycleHookHeartbeatTimeout = Nothing
, _autoScalingLifecycleHookLifecycleHookName = Nothing
, _autoScalingLifecycleHookLifecycleTransition = lifecycleTransitionarg
, _autoScalingLifecycleHookNotificationMetadata = Nothing
, _autoScalingLifecycleHookNotificationTargetARN = Nothing
, _autoScalingLifecycleHookRoleARN = Nothing
}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-as-lifecyclehook.html#cfn-as-lifecyclehook-autoscalinggroupname
aslhAutoScalingGroupName :: Lens' AutoScalingLifecycleHook (Val Text)
aslhAutoScalingGroupName = lens _autoScalingLifecycleHookAutoScalingGroupName (\s a -> s { _autoScalingLifecycleHookAutoScalingGroupName = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-as-lifecyclehook.html#cfn-as-lifecyclehook-defaultresult
aslhDefaultResult :: Lens' AutoScalingLifecycleHook (Maybe (Val Text))
aslhDefaultResult = lens _autoScalingLifecycleHookDefaultResult (\s a -> s { _autoScalingLifecycleHookDefaultResult = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-as-lifecyclehook.html#cfn-as-lifecyclehook-heartbeattimeout
aslhHeartbeatTimeout :: Lens' AutoScalingLifecycleHook (Maybe (Val Integer))
aslhHeartbeatTimeout = lens _autoScalingLifecycleHookHeartbeatTimeout (\s a -> s { _autoScalingLifecycleHookHeartbeatTimeout = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-as-lifecyclehook.html#cfn-autoscaling-lifecyclehook-lifecyclehookname
aslhLifecycleHookName :: Lens' AutoScalingLifecycleHook (Maybe (Val Text))
aslhLifecycleHookName = lens _autoScalingLifecycleHookLifecycleHookName (\s a -> s { _autoScalingLifecycleHookLifecycleHookName = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-as-lifecyclehook.html#cfn-as-lifecyclehook-lifecycletransition
aslhLifecycleTransition :: Lens' AutoScalingLifecycleHook (Val Text)
aslhLifecycleTransition = lens _autoScalingLifecycleHookLifecycleTransition (\s a -> s { _autoScalingLifecycleHookLifecycleTransition = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-as-lifecyclehook.html#cfn-as-lifecyclehook-notificationmetadata
aslhNotificationMetadata :: Lens' AutoScalingLifecycleHook (Maybe (Val Text))
aslhNotificationMetadata = lens _autoScalingLifecycleHookNotificationMetadata (\s a -> s { _autoScalingLifecycleHookNotificationMetadata = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-as-lifecyclehook.html#cfn-as-lifecyclehook-notificationtargetarn
aslhNotificationTargetARN :: Lens' AutoScalingLifecycleHook (Maybe (Val Text))
aslhNotificationTargetARN = lens _autoScalingLifecycleHookNotificationTargetARN (\s a -> s { _autoScalingLifecycleHookNotificationTargetARN = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-as-lifecyclehook.html#cfn-as-lifecyclehook-rolearn
aslhRoleARN :: Lens' AutoScalingLifecycleHook (Maybe (Val Text))
aslhRoleARN = lens _autoScalingLifecycleHookRoleARN (\s a -> s { _autoScalingLifecycleHookRoleARN = a })
|
frontrowed/stratosphere
|
library-gen/Stratosphere/Resources/AutoScalingLifecycleHook.hs
|
mit
| 5,716
| 0
| 15
| 569
| 825
| 466
| 359
| 61
| 1
|
module GHCJS.DOM.FileReaderSync (
) where
|
manyoo/ghcjs-dom
|
ghcjs-dom-webkit/src/GHCJS/DOM/FileReaderSync.hs
|
mit
| 44
| 0
| 3
| 7
| 10
| 7
| 3
| 1
| 0
|
module Codewars.Kata.Sheep where
countSheep :: [Bool] -> Int
countSheep (x:xs) = count + countSheep xs
where count = if x == True then 1 else 0
countSheep [] = 0
|
dzeban/haskell-exercises
|
countSheep.hs
|
mit
| 169
| 0
| 8
| 37
| 70
| 39
| 31
| 5
| 2
|
module ZoomHub.Debug
( spy,
)
where
import qualified Debug.Trace as Trace
spy :: Show a => String -> a -> a
spy tag x = Trace.trace (tag <> ": " <> show x) x
|
zoomhub/zoomhub
|
src/ZoomHub/Debug.hs
|
mit
| 164
| 0
| 8
| 40
| 71
| 39
| 32
| 5
| 1
|
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances #-}
module Plug (
usesDefaultPort,
withScheme,
withCredentials,
withoutCredentials,
withHostname,
withPort,
withTrailingSlash,
withoutTrailingSlash,
at,
with,
with',
without,
withParams,
withoutQuery,
getParam,
getParams,
withFragment,
withoutFragment,
getScheme,
getAuthority,
getHost,
getPath,
getQuery,
getFragment,
show,
(&)
) where
import Data.Char (isAsciiLower, isAsciiUpper, isDigit, toUpper)
import Data.List (intercalate)
import Network.URI (escapeURIString)
equalsIgnoreCase :: String -> String -> Bool
equalsIgnoreCase a b = map toUpper a == map toUpper b
-- let p = Plug { scheme = "http", username = Nothing, password = Nothing, hostname = "example.com", port = 80, path = Nothing, query = Nothing, fragment = Nothing }
-- p `withScheme` "https" `withCredentials` ("john", "pwd") `withPort` 443 `at` "x" `at` "y" `with` ("a", Just "b") `withFragment` "foo"
data Plug = Plug {
scheme :: String,
username :: Maybe String,
password :: Maybe String,
hostname :: String,
port :: Int,
path :: Maybe ([String], Bool),
query :: Maybe [(String, Maybe String)],
fragment :: Maybe String
} deriving (Eq)
-- TODO (steveb): need to fix this; this function is about determinig if the original text had an explicit port or not
isDefaultPort :: String -> Int -> Bool
isDefaultPort scheme' 80 = scheme' `equalsIgnoreCase` "http"
isDefaultPort scheme' 443 = scheme' `equalsIgnoreCase` "https"
isDefaultPort scheme' 21 = scheme' `equalsIgnoreCase` "ftp"
isDefaultPort _ _ = False
usesDefaultPort :: Plug -> Bool
usesDefaultPort plug = isDefaultPort (scheme plug) (port plug)
withScheme :: Plug -> String -> Plug
withScheme plug scheme' = plug { scheme = scheme' }
withCredentials :: Plug -> (String, String) -> Plug
withCredentials plug (username', password') = plug { username = Just username', password = Just password' }
withoutCredentials :: Plug -> Plug
withoutCredentials plug@Plug { username = Nothing, password = Nothing } = plug
withoutCredentials plug = plug { username = Nothing, password = Nothing }
withHostname :: Plug -> String -> Plug
withHostname plug hostname' = plug { hostname = hostname' }
withPort :: Plug -> Int -> Plug
withPort plug port' = plug { port = port' }
withTrailingSlash :: Plug -> Plug
withTrailingSlash plug@Plug { path = Nothing } = plug { path = Just ([], True) }
withTrailingSlash plug@Plug { path = Just (_, True) } = plug
withTrailingSlash plug@Plug { path = Just (segments', False) } = plug { path = Just (segments', True) }
withoutTrailingSlash :: Plug -> Plug
withoutTrailingSlash plug@Plug { path = Nothing } = plug
withoutTrailingSlash plug@Plug { path = Just (segments', True) } = plug { path = Just (segments', False) }
withoutTrailingSlash plug@Plug { path = Just (_, False ) } = plug
at :: Plug -> String -> Plug
at plug@Plug { path = Nothing } segment = plug { path = Just ([ segment ], False)}
at plug@Plug { path = Just (segments', trailingSlash') } segment = plug { path = Just (segments' ++ [ segment ], trailingSlash')}
with :: Plug -> (String, Maybe String) -> Plug
with plug@Plug { query = Nothing } kv = plug { query = Just [ kv ]}
with plug@Plug { query = Just kvs } kv = plug { query = Just (kvs ++ [ kv ])}
with' :: Plug -> (String, String) -> Plug
with' plug@Plug { query = Nothing } (k, v) = plug { query = Just [ (k, Just v) ]}
with' plug@Plug { query = Just kvs } (k, v) = plug { query = Just (kvs ++ [ (k, Just v) ])}
without :: Plug -> String -> Plug
without plug@Plug { query = Nothing } _ = plug
without plug@Plug { query = Just queryParams } key = plug { query = if null queryParams' then Nothing else Just queryParams' }
where matchesKey (key', _) = not (key `equalsIgnoreCase` key')
queryParams' = filter matchesKey queryParams
withParams :: Plug -> [(String, Maybe String)] -> Plug
withParams plug@Plug { query = Nothing } kvs = plug { query = Just kvs }
withParams plug@Plug { query = Just kvs' } kvs = plug { query = Just (kvs' ++ kvs) }
-- TODO
-- withQuery :: Plug -> String -> Plug
withoutQuery :: Plug -> Plug
withoutQuery plug = plug { query = Nothing }
getParam :: Plug -> String -> Maybe (Maybe String)
getParam Plug { query = Nothing } _ = Nothing
getParam plug@Plug { query = Just _ } key = if null matchedParams then Nothing else Just $ head matchedParams
where matchedParams = plug `getParams` key
getParams :: Plug -> String -> [ Maybe String ]
getParams Plug { query = Nothing } _ = [ ]
getParams Plug { query = Just queryParams } key = map selectValue $ filter matchesKey queryParams
where matchesKey (key', _) = key `equalsIgnoreCase` key'
selectValue (_, value) = value
withFragment :: Plug -> String -> Plug
withFragment plug fragment' = plug { fragment = Just fragment' }
withoutFragment :: Plug -> Plug
withoutFragment plug@Plug { fragment = Nothing } = plug
withoutFragment plug = plug { fragment = Nothing }
data EncodingLevel = UserInfo | Segment | Query | Fragment
deriving (Ord, Eq)
isValidUriChar :: EncodingLevel -> Char -> Bool
isValidUriChar l c
| isAsciiLower c || isAsciiUpper c || isDigit c = True
| c `elem` "'()*-._!" = True
| l >= Fragment && c == '#' = True
| l >= Query && (c `elem` "/:-$,;|") = True
| l >= Segment && (c `elem` "@^") = True
| l == UserInfo && (c `elem` "&=") = True
| otherwise = False
encodeUserInfo :: String -> String
encodeUserInfo = escapeURIString (isValidUriChar UserInfo)
encodeSegment :: String -> String
encodeSegment = escapeURIString (isValidUriChar Segment)
encodeQuery :: String -> String
encodeQuery = escapeURIString (isValidUriChar Query)
encodeFragment :: String -> String
encodeFragment = escapeURIString (isValidUriChar Fragment)
getScheme :: Plug -> String
getScheme plug = scheme plug ++ "://"
getUserInfo :: Plug -> String
getUserInfo Plug { username = Nothing, password = Nothing } = ""
getUserInfo Plug { username = Nothing, password = Just password' } = ':' : encodeUserInfo password' ++ "@"
getUserInfo Plug { username = Just username', password = Nothing } = encodeUserInfo username' ++ "@"
getUserInfo Plug { username = Just username', password = Just password' } = encodeUserInfo username' ++ ":" ++ encodeUserInfo password' ++ "@"
getHost :: Plug -> String
getHost plug = hostname plug ++ (if usesDefaultPort plug then "" else ':' : show (port plug) )
getAuthority :: Plug -> String
getAuthority plug = getUserInfo plug ++ getHost plug
getPath :: Plug -> String
getPath Plug { path = Nothing } = ""
getPath Plug { path = Just (segments', True) } = '/' : intercalate "/" (map encodeSegment segments') ++ "/"
getPath Plug { path = Just (segments', False) } = '/' : intercalate "/" (map encodeSegment segments')
getQuery :: Plug -> String
getQuery Plug { query = Nothing } = ""
getQuery Plug { query = Just kvs } = '?' : intercalate "&" (map showQueryKeyValue kvs)
where showQueryKeyValue (k, Nothing) = encodeQuery k
showQueryKeyValue (k, Just v) = encodeQuery k ++ "=" ++ encodeQuery v
getFragment :: Plug -> String
getFragment Plug { fragment = Nothing } = ""
getFragment Plug { fragment = Just fragment' } = '#' : encodeFragment fragment'
instance Show Plug where
show plug = getScheme plug ++ getAuthority plug ++ getPath plug ++ getQuery plug ++ getFragment plug
class PlugAppend a where
(&) :: Plug -> a -> Plug
instance PlugAppend String where
(&) plug segment = plug `at` segment
instance PlugAppend (String, Maybe String) where
(&) plug kv = plug `with` kv
instance PlugAppend (String, String) where
(&) plug (k, v) = plug `with` (k, Just v)
|
bjorg/HPlug
|
plug.hs
|
mit
| 7,821
| 0
| 12
| 1,616
| 2,683
| 1,461
| 1,222
| 155
| 2
|
{-# LANGUAGE TupleSections, OverloadedStrings #-}
module Handler.Home where
import Import
-- 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 (Maybe FileInfo, Text)
handlerName = "getHomeR" :: Text
defaultLayout $ do
aDomId <- newIdent
setTitle "Welcome To Yesod!"
$(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 "Thanks for submitting!"
$(widgetFile "homepage")
sampleForm :: Form (Maybe FileInfo, Text)
sampleForm = renderDivs $ (,)
<$> fileAFormOpt "Choose a file"
<*> areq textField "What's on the file?" Nothing
hasFile :: Maybe (Maybe FileInfo, Text) -> Bool
hasFile Nothing = False
hasFile (Just (Nothing, _)) = False
hasFile (Just (Just _, _)) = True
hasLink :: Maybe (Maybe FileInfo, Text) -> Bool
hasLink Nothing = False
hasLink (Just (Nothing, _)) = True
hasLink (Just (Just _, _)) = False
|
losvedir/style-guidance
|
Handler/Home.hs
|
mit
| 1,591
| 0
| 13
| 358
| 403
| 208
| 195
| 35
| 2
|
{-# LANGUAGE OverloadedStrings #-}
module Test.Hspec.WaiSpec (main, spec) where
import Test.Hspec
import Data.ByteString (ByteString)
import qualified Data.ByteString.Lazy as BL
import Network.HTTP.Types
import Network.Wai
import Test.Hspec.Wai
import Test.Hspec.Wai.Internal (withApplication)
main :: IO ()
main = hspec spec
expectMethod :: Method -> Application
expectMethod method req respond = do
requestMethod req `shouldBe` method
respond $ responseLBS status200 [] ""
expectRequest :: Method -> ByteString -> ByteString -> [Header] -> Application
expectRequest method path body headers req respond = do
requestMethod req `shouldBe` method
rawPathInfo req `shouldBe` path
requestHeaders req `shouldBe` headers
rawBody <- getRequestBodyChunk req
rawBody `shouldBe` body
respond $ responseLBS status200 [] ""
spec :: Spec
spec = do
describe "WaiSession" $ do
it "has a MonadFail instance" $ do
withApplication undefined $ do
23 <- return (42 :: Int)
return ()
`shouldThrow` anyIOException
describe "get" $ with (return $ expectMethod methodGet) $ do
it "sends a get request" $ do
get "/" `shouldRespondWith` 200
describe "post" $ with (return $ expectMethod methodPost) $ do
it "sends a post request" $ do
post "/" "" `shouldRespondWith` 200
describe "put" $ with (return $ expectMethod methodPut) $ do
it "sends a put request" $ do
put "/" "" `shouldRespondWith` 200
describe "options" $ with (return $ expectMethod methodOptions) $ do
it "sends an options request" $ do
options "/" `shouldRespondWith` 200
describe "delete" $ with (return $ expectMethod methodDelete) $ do
it "sends a delete request" $ do
delete "/" `shouldRespondWith` 200
describe "request" $ with (return $ expectRequest methodGet "/foo" body accept) $ do
it "sends method, path, headers, and body" $ do
request methodGet "/foo" accept (BL.fromChunks [body]) `shouldRespondWith` 200
describe "postHtmlForm" $ with (return $ expectRequest methodPost "/foo" "foo=bar" formEncoded) $ do
it "sends a post request with form-encoded params" $ do
postHtmlForm "/foo" [("foo", "bar")] `shouldRespondWith` 200
where
accept = [(hAccept, "application/json")]
body = "{\"foo\": 1}"
formEncoded = [(hContentType, "application/x-www-form-urlencoded")]
|
hspec/hspec-wai
|
test/Test/Hspec/WaiSpec.hs
|
mit
| 2,436
| 0
| 19
| 534
| 741
| 368
| 373
| 55
| 1
|
{-# htermination maximum :: [Int] -> Int #-}
|
ComputationWithBoundedResources/ara-inference
|
doc/tpdb_trs/Haskell/full_haskell/Prelude_maximum_5.hs
|
mit
| 45
| 0
| 2
| 8
| 3
| 2
| 1
| 1
| 0
|
{-# LANGUAGE
OverloadedStrings
, TypeApplications
, LambdaCase
, NoMonomorphismRestriction
#-}
module CommandInstall
( cmdInstall
, updateGrubConf
) where
import Algorithms.NaturalSort
import Control.Exception
import Control.Monad
import Data.List
import Data.Ord
import System.Environment
import System.Exit
import Text.Microstache
import Turtle.Prelude
import Turtle.Shell
import qualified Control.Foldl as Foldl
import qualified Data.Text as T
import qualified Data.Text.Lazy as TL
import qualified Data.Aeson as Aeson
import qualified Data.HashMap.Lazy as HM
import qualified Data.Vector as Vec
import qualified Data.Text.IO as T
import qualified Filesystem.Path.CurrentOS as FP
import Common
cmdInstall :: IO ()
cmdInstall = sh $ do
pushd "/usr/src/linux"
ExitSuccess <- liftIO $ shDive "make" ["install"]
ExitSuccess <- liftIO $ shDive "make" ["modules_install"]
liftIO $ Control.Exception.try @SomeException updateGrubConf >>= \case
Left e -> putStrLn $ "Allowed to fail: " <> displayException e
Right _ -> pure ()
r <- liftIO $ shDive "emerge" ["@module-rebuild"]
case r of
ExitSuccess -> pure ()
ExitFailure ec -> liftIO $
putStrLn $ "Exitcode=" <> show ec <> " (allowed to fail)"
updateGrubConf :: IO ()
updateGrubConf =
determineBootloader >>= getUpdateAction
where
getUpdateAction :: Bootloader -> IO ()
getUpdateAction = \case
Grub1 -> updateGrub1Conf
Grub2 -> updateGrub2Conf
{-
Recognize existing kernels and update grub.conf using a template.
To recognize a valid kernel version,
config-XXX, System.map-XXX, vmlinux-XXX must all exist,
with XXX being exactly the same.
-}
updateGrub1Conf :: IO ()
updateGrub1Conf = do
-- get potential options for vmlinuz-* files.
kernelSets <- fmap (Data.List.sortOn (Down . sortKey)) $ reduce Foldl.list $
ls "/boot/" >>= \fp -> do
let fName = FP.encodeString . FP.filename $ fp
vmlzMagic = "vmlinuz-"
True <- testfile fp
guard $ vmlzMagic `isPrefixOf` fName
-- we say "X.Y.Z-gentoo" is a KernelSet,
-- if all of vmlinuz, System.map and config exists
let kernelSet = T.pack $ drop (T.length vmlzMagic) fName
True <- testfile ("/boot" FP.</> FP.fromText ("System.map-" <> kernelSet))
True <- testfile ("/boot" FP.</> FP.fromText ("config-" <> kernelSet))
pure kernelSet
let context =
Aeson.Object $
HM.singleton
"kernel_version" $
Aeson.Array $
Vec.fromList (toVerObj <$> kernelSets)
toVerObj :: T.Text -> Aeson.Value
toVerObj t = Aeson.Object $ HM.singleton "ver" (Aeson.String t)
tmpl <- getEnv "KERNEL_TOOL_GRUB_CONF_TEMPLATE" >>= compileMustacheFile
let grubConfContent = renderMustache tmpl context
putStrLn "Writing to grub.conf ..."
T.writeFile "/boot/grub/grub.conf" $ TL.toStrict grubConfContent
updateGrub2Conf :: IO ()
updateGrub2Conf = do
(ExitSuccess, _) <-
procStrict "/usr/sbin/grub-mkconfig" ["-o", "/boot/grub/grub.cfg"] ""
pure ()
|
Javran/misc
|
kernel-tool/src/CommandInstall.hs
|
mit
| 3,059
| 0
| 19
| 636
| 772
| 400
| 372
| 76
| 3
|
import System.Environment
import System.Directory
import System.IO
import Data.List
type TaskAction = [String] -> IO ()
dispatch :: [ ( String, TaskAction ) ]
dispatch = [ ("add", add)
, ("view", view)
, ("remove", remove)
]
main = do
(command:args) <- getArgs
let (Just action) = lookup command dispatch
action args
add :: TaskAction
add [fileName, todoItem ] = appendFile fileName (todoItem ++ "\n")
view :: TaskAction
view [fileName] = do
contents <- readFile fileName
let todoTasks = lines contents
numberedTasks = unlines $ zipWith (\n str -> show n ++ " - " ++ str) [0..] todoTasks
putStrLn numberedTasks
remove :: TaskAction
remove [fileName, numberString] = do
handle <- openFile fileName ReadMode
(tempName, tempHandle) <- openTempFile "." "temp"
contents <- hGetContents handle
let number = read numberString
todoTasks = lines contents
newTodoTasks = delete (todoTasks !! number) todoTasks
newContents = unlines newTodoTasks
hPutStr tempHandle newContents
hClose handle
hClose tempHandle
removeFile fileName
renameFile tempName fileName
|
feliposz/learning-stuff
|
haskell/task_original.hs
|
mit
| 1,189
| 0
| 16
| 296
| 384
| 194
| 190
| 35
| 1
|
{-|
Module: Parse
The module to parse lisp expressions.
-}
module Parse (lispParse, obj, objs) where
import Lexer
import Representation
import Text.Parsec.Combinator
import Text.Parsec.Error
import Text.Parsec.Pos
import Text.Parsec.Prim
type Parser = Parsec [LexOut] ()
match :: Token -> Parser ()
match tok = tokenPrim (show . getToken) pos (match' . getToken)
where
match' x = if x == tok then Just () else Nothing
symbol :: Parser String
symbol = tokenPrim (show . getToken) pos (match' . getToken)
where
match' (TSymbol sym) = Just sym
match' _ = Nothing
pos :: (SourcePos -> LexOut -> [LexOut] -> SourcePos)
pos oldPos (LexOut _ line col _) _ = newPos (sourceName oldPos) line col
-- | Parses a string into a series of list objects.
lispParse :: Parser a -> String -> [LexOut] -> Either ParseError a
lispParse p name toks = runParser (p <* eof) () name toks
-- | A parser for one lisp object.
obj :: Parser AST
obj = list <|> quote <|> (fmap SSymbol symbol)
-- | A parser for multiple lisp object.
objs :: Parser [AST]
objs = many1 obj
list :: Parser AST
list = do match TLParen
os <- many obj
match TRParen
return (SList os)
quote :: Parser AST
quote = do match TQuote
l <- obj
return (SList [SSymbol "quote", l])
|
lambda-11235/pure-hlisp
|
src/Parse.hs
|
gpl-2.0
| 1,306
| 0
| 11
| 304
| 456
| 237
| 219
| 32
| 2
|
-- yaht_5_1.hs
module Main
where
{-
Exercise 5.1 Write a program that asks the user for his or her name. If the
name is one of Simon, John or Phil, tell the user that you think Haskell is
a great programming language. If the name is Koen, tell them that you think
debugging Haskell is fun (Koen Classen is one of the people who works on
Haskell debugging); otherwise, tell the user that you donβt know who he or
she is. Write two different versions of this program, one using if
statements, the other using a case statement.
main = do
putStrLn "Please tell me your name:"
name <- getLine
if elem name ["Simon", "John", "Phil"]
then putStrLn "Haskell is a great programming language."
else if name == "Koen"
then putStrLn "debugging Haskell is fun"
else putStrLn "I know who are you."
-}
main = do
putStrLn "Please tell me your name:"
name <- getLine
case name of
"Koen" -> putStrLn "debugging Haskell is fun"
"Simon" -> putStrLn "Haskell is a great programming language."
"John" -> putStrLn "Haskell is a great programming language."
"Phil" -> putStrLn "Haskell is a great programming language."
_ -> putStrLn "I know who are you."
|
dormouse/blog
|
source/haskell/yaht-exercises/yaht_5_1.hs
|
gpl-2.0
| 1,248
| 0
| 10
| 314
| 76
| 36
| 40
| 10
| 5
|
-- C->Haskell Compiler: C builtin information
--
-- Author : Manuel M. T. Chakravarty
-- Created: 12 February 01
--
-- Copyright (c) 2001 Manuel M. T. Chakravarty
--
-- This file is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 2 of the License, or
-- (at your option) any later version.
--
-- This file is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
--- DESCRIPTION ---------------------------------------------------------------
--
-- This module provides information about builtin entities.
--
--- DOCU ----------------------------------------------------------------------
--
-- language: Haskell 98
--
-- Currently, only builtin type names are supported. The only builtin type
-- name is `__builtin_va_list', which is a builtin of GNU C.
--
--- TODO ----------------------------------------------------------------------
--
module C2HS.C.Builtin (
builtinTypeNames
) where
import Language.C.Data.Ident (Ident, builtinIdent)
import C2HS.C.Attrs (CObj(BuiltinCO))
-- | predefined type names
--
builtinTypeNames :: [(Ident, CObj)]
builtinTypeNames = [(builtinIdent "__builtin_va_list", BuiltinCO)]
|
jrockway/c2hs
|
src/C2HS/C/Builtin.hs
|
gpl-2.0
| 1,438
| 0
| 7
| 222
| 105
| 79
| 26
| 6
| 1
|
-- grid is a game written in Haskell
-- Copyright (C) 2018 karamellpelle@hotmail.com
--
-- This file is part of grid.
--
-- grid is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- grid is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with grid. If not, see <http://www.gnu.org/licenses/>.
--
module MEnv.Sound.GLFW
(
) where
import MEnv
|
karamellpelle/grid
|
designer/source/MEnv/Sound/GLFW.hs
|
gpl-3.0
| 802
| 0
| 3
| 151
| 31
| 27
| 4
| 3
| 0
|
import Data.List
-- Project euler problem 2
-- Find the sum of all even-valued fibonacci numbers not exceeding 4 million
main = putStrLn $ show result
where
result = sum [ x | x <- (takeWhile (<=4000000) fibonacci), x `mod` 2 == 0 ]
fibonacci :: [Int]
fibonacci = fibonacci' 0 1
fibonacci' :: Int -> Int -> [Int]
fibonacci' x y = (x+y) : (fibonacci' y (x+y))
|
peri4n/projecteuler
|
haskell/problem2.hs
|
gpl-3.0
| 374
| 0
| 13
| 83
| 137
| 75
| 62
| 7
| 1
|
{-# LANGUAGE GADTs #-}
module AVR.REPL where
import AVR.Decoder (decode, Instruction)
import AVR.Fetch (fetch)
import AVR.Exec (exec)
import AVR.AVRState
import Data.Word (Word16)
import Data.Vector (Vector)
import System.Console.Readline
import System.Exit
import AVR.REPL.Command
import AVR.REPL.Expr
import Control.Monad
import Text.Parsec (parse)
import Text.Printf (printf)
type EvalError = String
fetchDecode :: AVRState -> Instruction
fetchDecode = decode . fetch
-- | Executes one simulation step
-- | The return value is a tuple of the instruction executed, and the next state
step :: AVRState -> AVRState
step = exec =<< fetchDecode
evaluate :: String -> [AVRState] -> (Either EvalError String, [AVRState])
evaluate _ [] = error "Cannot evaluate with empty history, this shouldn't happen."
evaluate line history@(current:past) = case parse parseCommand "repl" line of
Left err -> (Left (show err), history)
Right command -> case command of
Inst -> (Right (showCurrentInst history), history)
Regs -> (Right (prettyPrintRegs current), history)
Print8 expr -> (Right $ show $ eval expr current, history)
Print16 expr -> (Right $ show $ eval expr current, history)
Step n -> let newHistory = (iterate (\h -> step (head h) : h) history) !! n
in (Right (showCurrentInst history), newHistory)
Back n -> if n >= length history
then (Left "Cannot backtrack any further.", [last history])
else let newHistory = drop n history
in (Right (showCurrentInst newHistory), newHistory)
Set8 target val -> let updateState = case target of
TargetReg num -> setReg num =<< eval val
TargetPCL -> setPC =<< (onLow . const . eval val) `ap` getPC
TargetPCH -> setPC =<< (onHigh . const . eval val) `ap` getPC
TargetIO addr -> writeIOReg addr =<< eval val
TargetData eAddr -> \s -> writeDMem (eval eAddr s) (eval val s) s
in (Right "", updateState current : past)
Set16 target val -> let updateState = case target of
TargetPC -> setPC =<< eval val
in (Right "", updateState current : past)
where
showCurrentInst h = printf "\nPC = 0x%04X\n%s\n"
(programCounter (head h))
(show (fetchDecode (head h)))
loop :: [AVRState] -> IO [AVRState]
loop replState = do
line <- readline "> "
case line of
Nothing -> exitSuccess
Just command -> do
let (result, nextReplState) = evaluate command replState
case result of
Left err -> putStrLn $ "Error: " ++ err
Right msg -> addHistory command >> putStrLn msg
return nextReplState
iterateM :: (Monad m) => (a -> m a) -> a -> m a
iterateM = foldr (>=>) return . repeat
repl :: Vector Word16 -> IO()
repl pmem = void $ iterateM loop [initialState pmem]
|
dhrosa/haskell-avr-simulator
|
AVR/REPL.hs
|
gpl-3.0
| 3,214
| 0
| 23
| 1,060
| 1,004
| 513
| 491
| 63
| 14
|
{-# LANGUAGE OverloadedStrings, ScopedTypeVariables #-}
-- | Recognises zip archives and adds their content to the database.
module Handler.Upload.Archive (
ArchiveTree (..), extensions, processArchive, archiveTree, treeToHtml
) where
import Import
import qualified Control.Exception as E
import Control.Monad
import qualified Data.ByteString.Lazy as B
import Data.List (foldl', sortBy)
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.Text as T
import System.FilePath (splitDirectories, hasTrailingPathSeparator)
import qualified Codec.Archive.Zip as Z
import qualified JobsDaemon.Compression as C
import Util.Hmac (Hmac, newHmac)
import Util.Pretty (PrettyFileSize (..), wrappedText)
-- | Represents a hierarchy of files within an archive.
data ArchiveTree = NodeDirectory (M.Map FilePath ArchiveTree)
| NodeFile Hmac Word64
-- | Files extensions which are supported by the zip-archive package.
extensions :: S.Set Text
extensions = S.fromDistinctAscList [".apk", ".jar", ".zip"]
-- | Try to read the content of a zip archive.
processArchive :: FilePath -> Text -> FileId -> Handler Bool
processArchive path ext fileId | not (ext `S.member` extensions) = return False
| otherwise = do
eEntries <- liftIO $ E.try (readArchiveFiles >>= E.evaluate)
case eEntries of
Right entries -> do
app <- getYesod
runDB $ do
update fileId [FileType =. Archive]
-- Appends the files of the archive to the database.
forM_ entries $ \e -> do
let ePath = Z.eRelativePath e
ePathText = T.pack ePath
exists <- getBy $ UniqueArchiveFile fileId ePathText
case exists of
Just _ -> return ()
Nothing -> do
(key, hmac) <- newHmac HmacArchiveFile
let eSize | hasTrailingPathSeparator ePath =
Nothing
| otherwise =
let size = Z.eUncompressedSize e
in Just $ word64 size
insertKey key $ ArchiveFile hmac fileId ePathText
eSize
_ <- liftIO $ C.putFile app fileId []
return True
Left (_ :: E.SomeException) -> return False
where
-- Try to read the archive index of a zip file.
readArchiveFiles =
B.readFile path >>= return . Z.zEntries . Z.toArchive
-- | Transforms the list of files in a hierarchy.
archiveTree :: [ArchiveFile] -> ArchiveTree
archiveTree =
foldl' insertFile emptyDir . map preprocess
where
preprocess (ArchiveFile hmac _ path size) =
(hmac, splitDirectories $ T.unpack path, size)
insertFile (NodeDirectory files) (_, [e], Nothing) =
-- Inserts a directory
let files' = M.insertWith (\_ old -> old) e emptyDir files
in NodeDirectory files'
insertFile (NodeDirectory files) (hmac, [e], Just size) =
-- Inserts a file
let files' = M.insert e (NodeFile hmac size) files
in NodeDirectory files'
insertFile (NodeDirectory files) (hmac, (e:es), size) =
-- Inserts recursively
let exists old = insertFile old (hmac, es, size)
new = insertFile emptyDir (hmac, es, size)
files' = M.insertWith (\_ old -> exists old) e new files
in NodeDirectory files'
insertFile tree _ = tree -- File already in the tree, ignore
emptyDir = NodeDirectory M.empty
-- | Renders the archive tree with HTML tags using the given function to render
-- URLs to download files separately.
treeToHtml :: (Hmac -> Text) -> ArchiveTree -> Html
treeToHtml rdrUrl ~(NodeDirectory tree) = [shamlet|
<ul .last>
^{go $ sortFiles tree}
|]
where
go [] = mempty
go ((name, item):is) = -- Last item of a level
let nodeClass = if null is then "last" else "" :: Text
name' = wrappedText (T.pack name) 30
in case item of
NodeDirectory files -> [shamlet|
<li class=#{nodeClass}>
<span .directory title=#{name}>#{name'}
<ul>
^{go (sortFiles files)}
|]
NodeFile hmac size ->
let url = rdrUrl hmac
in [shamlet|
<li class=#{nodeClass}>
<a .file href=#{url} download=#{name} title=#{name}>
#{name'}
<span .size>#{PrettyFileSize size}
|]
`mappend` go is
-- Extracts and sorts a single level of mapped files. Directories first.
sortFiles = sortBy cmpNodes . M.toList
cmpNodes (_, NodeDirectory {}) (_, NodeFile {}) = LT
cmpNodes (_, NodeFile {}) (_, NodeDirectory {}) = GT
cmpNodes (name1, _) (name2, _) = name1 `compare` name2
|
RaphaelJ/getwebb.org
|
Handler/Upload/Archive.hs
|
gpl-3.0
| 5,129
| 7
| 39
| 1,745
| 1,192
| 642
| 550
| -1
| -1
|
{-# LANGUAGE RankNTypes #-}
-- | Example of using lenses for manipulating a configuration file.
module Config where
import Control.Lens
data Config = Config
{ verbose :: Bool
, authors :: [Author]
, foo :: Foo
} deriving (Show)
data Author = Author
{ name :: String
, age :: Int
} deriving (Show)
newtype Foo = Foo { bar :: String } deriving Show
-- * Lenses for `Config` and `Author`.
verboseL :: Lens' Config Bool
-- Remember that a lens is defined as:
--
-- > Lens' Config Bool = forall f . Functor f => (Bool -> f Bool) -> Config -> f Config
--
verboseL fb cfg = (\b -> cfg { verbose = b } ) <$> fb (verbose cfg)
authorsL :: Lens' Config [Author]
authorsL fxs cfg = (\xs -> cfg { authors = xs }) <$> fxs (authors cfg)
fooL :: Lens' Config Foo
fooL ff cfg = (\f -> cfg { foo = f }) <$> ff (foo cfg)
nameL :: Lens' Author String
nameL fstr a = (\str -> a { name = str }) <$> fstr (name a)
ageL :: Lens' Author Int
ageL fi a = (\i -> a { age = i }) <$> fi (age a)
barL :: Lens' Foo String
barL fstr fo = (\str -> fo { bar = str} ) <$> fstr (bar fo)
-- * Sample configurations.
config0 :: Config
config0 = Config
{ authors = [nicole, another], verbose = False , foo = baz}
where nicole = Author "One" 35
another = Author "Two" 27
baz = Foo "baz"
-- * Playing with lenses
foo0 :: String
foo0 = view (fooL . barL) config0
-- How come we're able to compose lenses?
--
--
-- See this answer: https://stackoverflow.com/a/46010477/2289983
-- We have:
--
-- > (.) :: Lens' Config Foo -> Lens' Foo String -> Lens' Config String
--
-- Expanding we get (ignore the universal quantification for now ...):
--
-- > (.) :: (forall f. Functor f => (Foo -> f Foo) -> Config -> f Config)
-- -> (forall f. Functor f => (String -> f String) -> Foo -> f Foo)
-- -> (forall f. Functor f => (String -> f String) -> Config -> f Config)
--
-- Which coincides with the usual definition of function composition:
--
-- > (.) :: (b -> c) -> (a -> b) -> (a -> c)
-- What is the type of `view`?
--
-- > view :: MonadReader s m => Getting a s a -> m a
-- > MonadReader s m => ((a -> Const a a) -> s -> Const a s) -> m a
--
-- Instantiated for our particular case (`foo0`):
--
-- > view :: MonadReader Config m => ((String -> Const String String) -> Config -> Const String Config) -> m String
--
-- And in this case the monad reader is `m ~ (Config ->) String` or
-- equivalently `m ~ Config -> String`.
authorNames0 :: [String]
-- The implementation below won't typecheck. Traverse will apply the Monoid
-- operator on strings (resulting on a value `String`), whereas we want a list
-- of names! (of type `[String]`)
--
-- > authorNames0 = view (authorsL . traverse . nameL) config0
--
-- How is `traverse` a lens? Remember its type:
--
-- > traverse :: (Applicative f, Traversable t) => (a -> f b) -> t a -> f (t b)
--
-- And compare with
--
-- > Lens s t a b = forall f . Functor f => (a -> f b) -> s -> f t
--
-- So a traverse it is not a `Lens'` but a `Lens (t a) (t b) a b`!
authorNames0 = toListOf (authorsL . traverse . nameL) config0
-- TODO: understand the `toList` and `Traversal` magic:
--
-- > https://hackage.haskell.org/package/lens-tutorial-1.0.3/docs/Control-Lens-Tutorial.html#g:5
authorAges0 :: [Int]
authorAges0 = toListOf (authorsL . traverse . ageL) config0
-- * Parametrizing lenses.
-- | Append a string to the field defined by the given Traversal. Note that we
-- could have used a Lens instead, but with Traversal we can use traversal:
--
-- > appendPorAtras (authorsL . traverse . nameL) config0
--
-- Besides of course:
--
-- > appendPorAtras (fooL . barL) config0
--
appendPorAtras :: forall a . Traversal' a String -> a -> a
appendPorAtras accessor = over accessor (++" por atras")
-- Why does `traverse` works as a Traversal?
--
-- > authorsL :: Functor f => ([Author] -> f [Author]) -> Config -> f Config
-- > authorsL . traverse :: Applicative f => (Author -> f Author) -> Config -> f Config
-- > authorsL . traverse . nameL :: Applicative f => (String -> f String) -> Config -> f Config
--
|
capitanbatata/sandbox
|
pw-lenses/src/Config.hs
|
gpl-3.0
| 4,085
| 0
| 9
| 896
| 644
| 389
| 255
| 39
| 1
|
type Exp a b = Lan ((,) a) I b
|
hmemcpy/milewski-ctfp-pdf
|
src/content/3.11/code/haskell/snippet07.hs
|
gpl-3.0
| 30
| 0
| 8
| 9
| 25
| 14
| 11
| 1
| 0
|
-- Copyright (c) 2015, Sven Thiele <sthiele78@gmail.com>
-- This file is part of hasple.
-- hasple is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
-- hasple is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
-- You should have received a copy of the GNU General Public License
-- along with hasple. If not, see <http://www.gnu.org/licenses/>.
module CDNLSolver (
anssets
) where
import Prelude (($), (+), (-), (++))
import Data.Bool
import Data.Int
import Data.Eq
import Data.Ord
import Text.Show
import ASP
import SPVar
import Assignment (Assignment, initAssignment, unassigned, trueatoms, elem, assign, backtrack)
import SPC
import DLT
import qualified NGS
import UFS
import Data.List (head, map, sort, nub, intersect, (\\), delete, null )
import qualified Data.Vector as Vector
import qualified Data.Vector.Unboxed as UVector
import Data.Maybe
import qualified Data.Map as Map
import Debug.Trace
------------------------------
-- little helper
get_svar :: SPVar -> SymbolTable -> SVar
get_svar l st = get_svar2 l st 0
get_svar2 :: SPVar -> SymbolTable -> Int -> SVar
get_svar2 s st i =
if st Vector.!i == s
then i
else get_svar2 s st (i+1)
transforms :: [CClause] -> SymbolTable -> [NGS.Clause]
transforms cclauses st = map (NGS.fromCClause st) cclauses
-- -----------------------------------------------------------------------------
-- Conflict Driven Nogood Learning - Enumeration
data TSolver = TSolver {
program :: [Rule] -- the program
, is_tight :: Bool
, symboltable :: SymbolTable --
, boocons :: NGS.NogoodStore -- the store of boolean constraints
, decision_level :: Int -- the decision level
, blocked_level :: Int -- the blocked level
, assignment_level :: Int -- the assignment level
, assignment :: Assignment -- an assignment
, dltracker :: DLT -- the decision level tracker
, get_unfounded_set :: [Atom] -- unfounded atoms
, conf :: Bool -- is the state of the solver in conflict
} deriving (Show, Eq)
set_program :: [Rule] -> TSolver -> TSolver
set_program p (TSolver _ t st ngs dl bl al a dlt u c) = (TSolver p t st ngs dl bl al a dlt u c)
set_symboltable st (TSolver p t _ ngs dl bl al a dlt u c) = (TSolver p t st ngs dl bl al a dlt u c)
set_boocons ngs (TSolver p t st _ dl bl al a dlt u c) = (TSolver p t st ngs dl bl al a dlt u c)
set_decision_level dl (TSolver p t st ngs _ bl al a dlt u c) = (TSolver p t st ngs dl bl al a dlt u c)
set_blocked_level bl (TSolver p t st ngs dl _ al a dlt u c) = (TSolver p t st ngs dl bl al a dlt u c)
set_assignment_level al (TSolver p t st ngs dl bl _ a dlt u c) = (TSolver p t st ngs dl bl al a dlt u c)
set_assignment a (TSolver p t st ngs dl bl al _ dlt u c) = (TSolver p t st ngs dl bl al a dlt u c)
set_dltracker dlt (TSolver p t st ngs dl bl al a _ u c) = (TSolver p t st ngs dl bl al a dlt u c)
set_unfounded_set u (TSolver p t st ngs dl bl al a dlt _ c) = (TSolver p t st ngs dl bl al a dlt u c)
set_conf c (TSolver p t st ngs dl bl al a dlt u _) = (TSolver p t st ngs dl bl al a dlt u c)
anssets :: [Rule] -> [[Atom]]
-- create a solver and initiate solving process
anssets prg =
let t = tight prg
cngs = nub (nogoods_of_lp prg)
st = Vector.fromList (get_vars cngs)
png = transforms cngs st
ngs = NGS.new_ngs png []
l = Vector.length st
dl = 1
bl = 1
al = 1
a = initAssignment l
dlt = []
u = []
conf = False
solver = TSolver prg t st ngs dl bl al a dlt u conf
in
-- trace ("Clauses: " Prelude.++ (show png)) $
-- trace ("SymbTab: " Prelude.++ (show st)) $
cdnl_enum solver 0
cdnl_enum :: TSolver -> Int -> [[Atom]]
cdnl_enum solver s =
let
solverp = set_unfounded_set [] solver
solver' = nogood_propagation solverp
in
-- trace ("cdnl: " Prelude.++ (show (assignment solver'))) $
if conf solver'
then -- conflict
if (decision_level solver') == 1
then [] -- no need for conflict handling, no more answer sets
else -- conflict handling
let solver'' = conflict_handling solver' in
cdnl_enum solver'' s
else -- no conflict
let
a' = assignment solver'
al' = assignment_level solver'
dlt = dltracker solver'
selectable = unassigned a'
in
if null selectable
then -- if all atoms then answer set found
if (decision_level solver')==1 || s==1
then [nub (trueatoms a' (symboltable solver'))] -- last answer set
else -- backtrack for remaining answer sets
let dl = decision_level solver'
sigma_d = get_dliteral dlt dl
cal = dl2al dlt dl
dlt' = dlbacktrack dlt dl
a'' = backtrack a' cal
a''' = assign a'' (invert sigma_d) cal -- invert last decision literal
solver'' = set_decision_level (dl-1) $
set_blocked_level (dl-1) $
set_dltracker dlt' $
set_assignment_level (cal+1) $
set_assignment a''' solver'
remaining_as = cdnl_enum solver'' (s-1)
in
(nub (trueatoms a' (symboltable solver'))):remaining_as
else -- select new lit
let dl = decision_level solver'
sigma_d = head selectable
dlt' = (al',dl+1,(T sigma_d)):dlt
a'' = assign a' (T sigma_d) al'
solver'' = set_decision_level (dl+1) $
set_dltracker dlt' $
set_assignment_level (al'+1) $
set_assignment a'' solver'
remaining_as = cdnl_enum solver'' s
in
-- trace ("choose: " Prelude.++ (show sigma_d)) $
remaining_as
conflict_handling :: TSolver -> TSolver
-- should resolve the conflict learn a new maybe clause and backtrack the solver
conflict_handling s =
let a = assignment s
bl = blocked_level s
dl = decision_level s
dlt = dltracker s
in
if bl < dl
then -- learn a new nogood and backtrack
let ngs = boocons s
(ngs', sigma_uip, alx) = conflict_analysis ngs a dlt
in
let -- backtrack
bt_dl = al2dl dlt alx
bt_al = dl2al dlt bt_dl
a' = assign (backtrack a bt_al) (invert sigma_uip) bt_al
dlt' = dlbacktrack dlt bt_dl
in
set_decision_level (bt_dl-1) $
set_dltracker dlt' $
set_assignment_level (bt_al+1) $
set_assignment a' $
set_boocons ngs' $
set_conf False s
else -- backtrack
let
sigma_d = get_dliteral dlt dl
dl' = dl-1
bt_al = dl2al dlt dl'
a' = assign (backtrack a bt_al) (invert sigma_d) bt_al
dlt' = dlbacktrack dlt dl'
in
set_decision_level dl' $
set_blocked_level dl' $
set_dltracker dlt' $
set_assignment_level bt_al $
set_assignment a' $
set_conf False s
conflict_analysis :: NGS.NogoodStore -> Assignment -> DLT -> (NGS.NogoodStore, SignedVar, Int)
conflict_analysis ngs a dlt =
let conflict_nogood = NGS.get_ng ngs
ngs' = NGS.rewind ngs
in
NGS.conflict_resolution ngs' conflict_nogood a dlt
-- Propagation
nogood_propagation :: TSolver -> TSolver
-- propagate nogoods
nogood_propagation s =
let
prg = program s
st = symboltable s
u = get_unfounded_set s
s' = local_propagation s
a = assignment s'
al = assignment_level s'
ngs = boocons s'
in
-- trace ("nogo_prop: " Prelude.++ (show (assignment s'))) $
if conf s'
then s'
else
if is_tight s
then s'
else
case ufs_check prg a st u of -- unfounded set check
[] -> s' -- no unfounded atoms
u' -> let p = get_svar (ALit (head u')) st in -- unfounded atoms
if elem (T p) a
then
let cngs_of_loop = loop_nogoods prg u'
ngs_of_loop = transforms cngs_of_loop st
ngs' = NGS.add_nogoods ngs_of_loop ngs
s'' = set_boocons ngs' s'
in
nogood_propagation s''
else
if elem (F p) a
then
let s'' = set_unfounded_set u' s' in
nogood_propagation s''
else
let a' = assign a (F p) al -- extend assignment
s'' = set_assignment_level (al+1) $
set_assignment a' $
set_unfounded_set u' s'
in
nogood_propagation s''
local_propagation :: TSolver -> TSolver
-- itterate over the nogoods and try to resolve them until nothing new can be infered or a conflict is found
local_propagation s =
if conf s
then s
else
if NGS.can_choose $ boocons s
then
let a = choose_next_ng s
b = resolve a
in
-- trace ("loc_prop: " Prelude.++ (show (assignment b))) $
let
c = local_propagation b
in
c
-- local_propagation $ resolve $ choose_next_ng s
else
-- trace ("loc_prop: " Prelude.++ "no choice") $
let ngs' = NGS.rewind $ boocons s in -- rewind for next use
set_boocons ngs' s
choose_next_ng :: TSolver -> TSolver
choose_next_ng s = set_boocons (NGS.choose $ boocons s) s
resolve :: TSolver -> TSolver
-- resolve the current no good
resolve s =
let al = (assignment_level s)
ng = NGS.get_ng (boocons s)
x = NGS.resolve al ng (assignment s)
in
-- trace ("res: " ++ (show x)) $
case x of
NGS.NIX -> s
NGS.NIXU ng' -> let ngs' = NGS.upgrade (boocons s) ng' in
set_boocons ngs' s
NGS.Res a' -> let ngs' = NGS.rewind (boocons s) in
set_boocons ngs' $ set_assignment_level (al+1) $ set_assignment a' s
NGS.ResU a' ng' -> let ngs' = NGS.up_rew (boocons s) ng' in
set_boocons ngs' $ set_assignment_level (al+1) $ set_assignment a' s
NGS.CONF -> set_conf True s -- set conflict
|
sthiele/hasple
|
CDNLSolver.hs
|
gpl-3.0
| 12,660
| 0
| 24
| 5,447
| 2,898
| 1,510
| 1,388
| 208
| 6
|
{-# 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.AndroidPublisher.Edits.ExpansionFiles.Get
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Fetches the Expansion File configuration for the APK specified.
--
-- /See:/ <https://developers.google.com/android-publisher Google Play Developer API Reference> for @androidpublisher.edits.expansionfiles.get@.
module Network.Google.Resource.AndroidPublisher.Edits.ExpansionFiles.Get
(
-- * REST Resource
EditsExpansionFilesGetResource
-- * Creating a Request
, editsExpansionFilesGet
, EditsExpansionFilesGet
-- * Request Lenses
, eefgPackageName
, eefgAPKVersionCode
, eefgExpansionFileType
, eefgEditId
) where
import Network.Google.AndroidPublisher.Types
import Network.Google.Prelude
-- | A resource alias for @androidpublisher.edits.expansionfiles.get@ method which the
-- 'EditsExpansionFilesGet' request conforms to.
type EditsExpansionFilesGetResource =
"androidpublisher" :>
"v2" :>
"applications" :>
Capture "packageName" Text :>
"edits" :>
Capture "editId" Text :>
"apks" :>
Capture "apkVersionCode" (Textual Int32) :>
"expansionFiles" :>
Capture "expansionFileType"
EditsExpansionFilesGetExpansionFileType
:>
QueryParam "alt" AltJSON :> Get '[JSON] ExpansionFile
-- | Fetches the Expansion File configuration for the APK specified.
--
-- /See:/ 'editsExpansionFilesGet' smart constructor.
data EditsExpansionFilesGet = EditsExpansionFilesGet'
{ _eefgPackageName :: !Text
, _eefgAPKVersionCode :: !(Textual Int32)
, _eefgExpansionFileType :: !EditsExpansionFilesGetExpansionFileType
, _eefgEditId :: !Text
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'EditsExpansionFilesGet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'eefgPackageName'
--
-- * 'eefgAPKVersionCode'
--
-- * 'eefgExpansionFileType'
--
-- * 'eefgEditId'
editsExpansionFilesGet
:: Text -- ^ 'eefgPackageName'
-> Int32 -- ^ 'eefgAPKVersionCode'
-> EditsExpansionFilesGetExpansionFileType -- ^ 'eefgExpansionFileType'
-> Text -- ^ 'eefgEditId'
-> EditsExpansionFilesGet
editsExpansionFilesGet pEefgPackageName_ pEefgAPKVersionCode_ pEefgExpansionFileType_ pEefgEditId_ =
EditsExpansionFilesGet'
{ _eefgPackageName = pEefgPackageName_
, _eefgAPKVersionCode = _Coerce # pEefgAPKVersionCode_
, _eefgExpansionFileType = pEefgExpansionFileType_
, _eefgEditId = pEefgEditId_
}
-- | Unique identifier for the Android app that is being updated; for
-- example, \"com.spiffygame\".
eefgPackageName :: Lens' EditsExpansionFilesGet Text
eefgPackageName
= lens _eefgPackageName
(\ s a -> s{_eefgPackageName = a})
-- | The version code of the APK whose Expansion File configuration is being
-- read or modified.
eefgAPKVersionCode :: Lens' EditsExpansionFilesGet Int32
eefgAPKVersionCode
= lens _eefgAPKVersionCode
(\ s a -> s{_eefgAPKVersionCode = a})
. _Coerce
eefgExpansionFileType :: Lens' EditsExpansionFilesGet EditsExpansionFilesGetExpansionFileType
eefgExpansionFileType
= lens _eefgExpansionFileType
(\ s a -> s{_eefgExpansionFileType = a})
-- | Unique identifier for this edit.
eefgEditId :: Lens' EditsExpansionFilesGet Text
eefgEditId
= lens _eefgEditId (\ s a -> s{_eefgEditId = a})
instance GoogleRequest EditsExpansionFilesGet where
type Rs EditsExpansionFilesGet = ExpansionFile
type Scopes EditsExpansionFilesGet =
'["https://www.googleapis.com/auth/androidpublisher"]
requestClient EditsExpansionFilesGet'{..}
= go _eefgPackageName _eefgEditId _eefgAPKVersionCode
_eefgExpansionFileType
(Just AltJSON)
androidPublisherService
where go
= buildClient
(Proxy :: Proxy EditsExpansionFilesGetResource)
mempty
|
rueshyna/gogol
|
gogol-android-publisher/gen/Network/Google/Resource/AndroidPublisher/Edits/ExpansionFiles/Get.hs
|
mpl-2.0
| 4,859
| 0
| 18
| 1,101
| 561
| 331
| 230
| 92
| 1
|
module Kth where
import Prelude hiding ((!!))
elementAt :: [a] -> Int -> a
elementAt ls 1 = head ls
elementAt ls n = elementAt (tail ls) (n - 1)
|
ice1000/OI-codes
|
codewars/101-200/find-the-kth-element-of-a-list.hs
|
agpl-3.0
| 146
| 0
| 7
| 31
| 72
| 40
| 32
| 5
| 1
|
{-# LANGUAGE BangPatterns,OverloadedStrings #-}
module BSParse
( consumed
, tryGet
, getPred
, getPred1
, wrapWith
, parseLit
, parseMany
, parseMany1
, parseOneOf
, parseNoneOf
, parseStr
, parseLen
, parseBlock
, parseCharPred
, chain
, choose
, pass
, sepBut
, sepBut1
, parseEof
, safeHead
, eatSpaces
, quotes
, brackets
, commaSep
, pjoin
, braceVar
, checkStartsWith
, parseAny
, wordChar
, bchar
, pchar
, parseDecInt
, escapedChar
, escapedCharBString
, should_fail_
, runParser1
, runParser2
, bsParseTests
, reminder
, module Text.Parsec
, module Text.Parsec.ByteString
)where
import qualified Data.ByteString.Char8 as B
-- import qualified Data.ByteString.Unsafe as B
-- import Data.ByteString.Internal (w2c)
import Control.Monad
-- (mplus)
import Data.Ix
import Util
import Test.HUnit
import Text.Parsec
import Text.Parsec.ByteString
-- import Text.ParserCombinators.Parsec.Char
-- import Text.ParserCombinators.Parsec.Combinator
-- import Text.ParserCombinators.Parsec.Prim ((<|>))
-- import Control.Monad
-- import qualified Text.Parsec.Token as P
-- import Text.Parsec.Language (haskellDef)
-- lexer = P.makeTokenParser haskellDef
-- type Parser a = ParserT BString a
-- type Parser a = BString -> Result a
-- type ParseMonad = Either String
-- type Result a = ParseMonad (a, BString)
eatSpaces :: Parser ()
eatSpaces = void (many1 (parseOneOf " \t")) <|> return ()
-- takeWreturn ((), dropSpaces s)
{-# INLINE eatSpaces #-}
-- emit :: a -> Parser a
-- emit = return
-- {-# INLINE emit #-}
consumed :: Parser t -> Parser BString
consumed p = do
s <- getInput
try p <|> fail "consume failed"
r <- getInput
let lendiff = B.length s - B.length r
return $ B.take lendiff s
-- let lendiff = B.length s - B.length r
-- return (B.take lendiff s, r)
{-# INLINE consumed #-}
-- (</>) :: Parser t -> Parser t -> Parser t
-- a </> b = (a v) `mplus` (b v))
-- {-# INLINE (</>) #-}
tryGet fn = try fn <|> return ""
-- chain_ lst = consumed (sequence_ lst)
-- chain :: [Parser BString] -> Parser BString
-- chain lst = (foldr pcons (emit []) lst) `wrapWith` B.concat
chain :: Monoid a => [Parser a] -> Parser a
chain = fmap mconcat . sequence
-- chain =
{-# INLINE chain #-}
choose = choice
-- {-# INLINE choose #-}
pjoin :: (t1 -> t2 -> t3) -> Parser t1 -> Parser t2 -> Parser t3
pjoin op a b = op <$> a <*> b
-- do
-- (w,r) <- a s
-- (w2,r2) <- b r
-- return ((op w w2), r2)
{-# INLINE pjoin #-}
pass = pjoin const
{-# INLINE pass #-}
-- (.>>) = (>>)
-- pjoin (\_ b -> b)
-- {-# INLINE (.>>) #-}
-- pcons :: Parser t -> Parser [t] -> Parser [t]
-- pcons = pjoin (:)
-- {-# INLINE pcons #-}
parseMany :: Parser t -> Parser [t]
parseMany = many
-- try inner <|> emit []
-- where inner = parseMany1 p
parseMany1 :: Parser t -> Parser [t]
parseMany1 = many1
-- p `pcons` (parseMany p)
{-# INLINE parseMany1 #-}
parseLit :: BString -> Parser BString
parseLit w = string (B.unpack w) >> return w
-- if w `B.isPrefixOf` s
-- then return (w, B.unsafeDrop (B.length w) s)
-- else fail $ "didn't match " ++ show w
{-# INLINE parseLit #-}
parseLen :: Int -> Parser BString
parseLen !i = B.pack <$> count i anyChar
-- \s -> if B.length s < i
-- then fail ("can't parse " ++ show i ++ ", not enough")
-- else return $ B.splitAt i s
{-# INLINE parseLen #-}
parseOneOf :: String -> Parser Char
parseOneOf = oneOf
-- parseCharPred (`elem` cl) ("one of " ++ show cl)
parseNoneOf :: String -> String -> Parser Char
parseNoneOf cl desc = noneOf cl <?> desc
-- parseCharPred (`B.notElem` cl) desc
pchar :: Char -> Parser Char
pchar = char -- parseCharPred (== c) (show c)
{-# INLINE pchar #-}
bchar c = B.singleton <$> pchar c
parseAny = anyChar
-- parseCharPred (const True) "any char"
parseCharPred :: (Char -> Bool) -> String -> Parser Char
parseCharPred pred desc= satisfy pred <?> "expected " ++ desc ++ ", got"
-- s <- getInput
-- (do
-- c <- anyChar
-- unless (pred c) $ fail ""
-- return c
-- ) <?> "expected " ++ desc ++ ", got "
-- case B.uncons s of
-- Nothing -> failStr "eof"
-- Just (h,t) -> if pred h then setInput t >> return h
-- else failStr (show h)
-- where failStr what = fail $ "expected " ++ desc ++ ", got " ++ what
{-# INLINE parseCharPred #-}
-- wrapWith fn wr s = fn s >>= \(!w,r) -> return (wr w, r)
wrapWith fn wr = wr <$> fn
{-# INLINE wrapWith #-}
getPred :: (Char -> Bool) -> Parser BString
-- getPred p =
-- <$> many1 p
-- s <- getInput
-- let (w,n) = B.span p s
-- setInput $! n
-- return $! w
getPred p = B.pack <$> many1 (satisfy p)
-- return $ B.pack b
-- return $! (w,n)
-- where (w,n) = B.span p s
-- isPred :: (Char -> Bool) -> Parser Char
-- isPred = satisfy
-- try $ do
-- c <- anyChar
-- unless (p c) (fail $ "got: " ++ [c])
-- return c
-- TODO: slightly inaccuate error messages
getPred1 :: (Char -> Bool) -> String -> Parser BString
getPred1 pred desc = B.pack <$> many1 (satisfy pred) <?> "wanted " ++ desc ++ ", but fail"
-- do
-- i <- getInput
-- getPred pred <?> "wanted " ++ desc ++ ", but fail to get it" ++ show i
-- if B.null w then fail ("wanted " ++ desc ++ ", but fail to get it") else return w
-- where (w,n) = B.span pred s
{-# INLINE getPred1 #-}
parseEof :: Parser ()
parseEof = eof
-- if B.null s
-- then return ((), s)
-- else fail $ "expected eof, got " ++ show (B.take 20 s)
-- sepBy1 :: Parser t -> Parser t2 -> Parser [t]
-- sepBy1 p sep = p `pcons` (parseMany (sep .>> p))
-- sepBy p sep = (p `sepBy1` sep) </> emit []
sepBut1 :: (Stream s m t) => ParsecT s u m a -> ParsecT s u m sep -> ParsecT s u m [a]
sepBut1 p sep = do { x <- p
; try (do{ sep
; xs <- sepBut1 p sep
; return (x:xs)
})
<|> return [x]
}
sepBut :: (Stream s m t) => ParsecT s u m a -> ParsecT s u m sep -> ParsecT s u m [a]
sepBut p sep = sepBut1 p sep <|> return []
commaSep :: Parser t -> Parser [t]
commaSep = (`sepBy` (eatSpaces >> pchar ','))
checkStartsWith :: Char -> Parser ()
checkStartsWith !c = do
h <- lookAhead anyChar
-- h <- safeHead (show c) s
unless (h == c) $ fail $ "expected " ++ show c ++ ", got " ++ show h
{-# INLINE checkStartsWith #-}
safeHead :: String -> Parser Char
safeHead r = lookAhead anyChar <?> ("expected " ++ r ++ ", got eof")
-- if B.null s then fail ("expected " ++ r ++ ", got eof") else return (w2c . B.unsafeHead $ s)
{-# INLINE safeHead #-}
-- between l r p = (l .>> p) `pass` r
-- {-# INLINE between #-}
brackets = between (pchar '[') (try (eatSpaces >> pchar ']'))
quotes = between (pchar '"') (try (pchar '"'))
wordChar :: Char -> Bool
wordChar !c = c /= ' ' && (inRange ('a','z') c || inRange ('A','Z') c || inRange ('0','9') c || c == '_')
braceVar :: Parser BString
braceVar = B.pack <$> between (pchar '{') (try (pchar '}')) (concat <$> inner)
where inner = many $ choose [(:[]) <$> nobraces, escapedChar]
nobraces = noneOf "}\\" -- "not } or \\"
parseStr :: Parser BString
parseStr = B.pack <$> quotes ( concat <$> inside)
where noquotes = noneOf "\"\\"
-- "non-quote chars"
inside = many ((:[]) <$> try noquotes <|> escapedChar)
parseDecInt :: Parser Int
parseDecInt = read <$> ((:) <$> (char '-' <|> return ' ') <*> many1 digit)
-- P.integer lexer
-- case B.readInt s of
-- Just x -> return x
-- Nothing -> fail "expected int"
{-# INLINE parseDecInt #-}
reminder :: Parser BString
reminder = B.pack <$> many anyChar
escapedChar :: Parser [Char]
escapedChar = do
char '\\'
c <- parseAny
return ['\\', c]
escapedCharBString :: Parser BString
escapedCharBString = B.pack <$> escapedChar
parseBlock :: Parser BString
parseBlock = B.pack <$> between (pchar '{') (pchar '}') nest_filling
where inner = choose [(:[]) <$> nobraces, escapedChar, braces]
nest_filling :: Parser String
nest_filling = concat <$> parseMany inner
braces = chain [(:[]) <$> pchar '{', nest_filling, (:[]) <$> pchar '}']
nobraces = noneOf "{}\\" -- <?> "non-brace chars"
{-# INLINE parseBlock #-}
-- parseBlock :: Parser BString
-- parseBlock = B.pack <$> between (pchar '{') (pchar '}') nest_filling
-- where inner = choose [(:[]) <$> nobraces, (:[]) <$> escapedChar, braces]
-- nest_filling :: Parser String
-- nest_filling = concat <$> parseMany inner
-- braces = concat <$> chain [(:[]) <$> pchar '{', nest_filling, (:[]) <$> pchar '}']
-- nobraces = noneOf "{}\\" -- <?> "non-brace chars"
-- {-# INLINE parseBlock #-}
-- # TESTS # --
should_fail_ act _ = let res = case act of
Left _ -> True
Right (_,"") -> False
_ -> True
in TestCase $ assertBool ("should fail " ++ show act) res
runParser1 :: Parser a -> BString -> Either ParseError (a, BString)
runParser1 p = runParser ww () ""
where
ww = do
pr <- p
-- i <- reminder
i <- getInput
return (pr,i)
runParser2 :: Parser a -> BString -> Either ParseError (a, BString)
runParser2 p = runParser ww () ""
where
ww = (,) <$> p <*>reminder
-- i <- getInput
-- return (pr,i)
parseStrTests = "parseStr" ~: TestList [
"Escaped works" ~: ("Oh \\\"yeah\\\" baby.", "") ?=? "\"Oh \\\"yeah\\\" baby.\"",
"Parse Str with leftover" ~: ("Hey there.", " 44") ?=? "\"Hey there.\" 44",
"Parse Str with dolla" ~: ("How about \\$44?", "") ?=? "\"How about \\$44?\"",
"bad parse1" ~: "What's new?" `should_fail` ()
]
where (?=?) res str = Right res ~=? runParser1 parseStr str
should_fail str _ = (runParser1 parseStr str) `should_fail_` ()
braceVarTests = TestList [
"Simple" ~: ("data", "") ?=? "{data}",
"With spaces" ~: (" a b c d ", " ") ?=? "{ a b c d } ",
"With esc" ~: (" \\} yeah! ", " ") ?=? "{ \\} yeah! } ",
"bad parse" ~: "{ oh no" `should_fail` (),
"bad parse" ~: "pancake" `should_fail` ()
]
where (?=?) res str = Right res ~=? runParser1 braceVar str
should_fail str _ = (runParser1 braceVar str) `should_fail_` ()
blockTests = "code block" ~: TestList [
"Fail nested" ~: " { the end" `should_fail` (),
"Pass nested" ~: "{ { }}" `should_be` " { }",
"Pass empty nested" ~: "{ }" `should_be` " ",
"Fail nested" ~: " { { }" `should_fail` (),
"Pass escape" ~: "{ \\{ }" `should_be` " \\{ ",
"Pass escape 2" ~: "{ \\{ \\{ }" `should_be` " \\{ \\{ ",
"Pass escape 3" ~: "{ \\\\}" `should_be` " \\\\",
"Pass escape 4" ~: "{ \\} }" `should_be` " \\} "
,"no braces" ~: "happy" `should_fail` ()
]
where should_be act exp = Right (exp, B.empty) ~=? runParser1 parseBlock act
should_fail act _ = (runParser1 parseBlock act) `should_fail_` ()
bsParseTests = TestList [ blockTests, braceVarTests, parseStrTests ]
-- # ENDTESTS # --
|
tolysz/hiccup
|
BSParse.hs
|
lgpl-2.1
| 11,190
| 0
| 14
| 2,916
| 2,553
| 1,406
| 1,147
| 196
| 3
|
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
module Spark.Core.ColumnSpec where
import Test.Hspec
import Data.List.NonEmpty(NonEmpty( (:|) ))
import Spark.Core.Context
import Spark.Core.Dataset
import Spark.Core.Column
import Spark.Core.Row
import Spark.Core.Functions
import qualified Spark.Core.ColumnFunctions as C
import Spark.Core.SimpleAddSpec(run, xrun)
import Spark.Core.Internal.LocalDataFunctions(iPackTupleObs)
import Spark.Core.Internal.DatasetFunctions(untypedLocalData)
myScaler :: Column ref Double -> Column ref Double
myScaler col =
let cnt = asDouble (C.count col)
m = C.sum col / cnt
centered = col .- m
stdDev = C.sum (centered * centered) / cnt
in centered ./ stdDev
spec :: Spec
spec = do
describe "local data operations" $ do
xrun "broadcastPair_struct" $ do
let ds = dataset [1] :: Dataset Int
let cnt = C.count (asCol ds)
let c = collect (asCol ds .+ cnt)
res <- exec1Def c
res `shouldBe` [2]
run "LocalPack (doubles)" $ do
let x = untypedLocalData (1 :: LocalData Double)
let x2 = iPackTupleObs (x :| [x])
res <- exec1Def x2
res `shouldBe` rowCell [DoubleElement 1, DoubleElement 1]
run "LocalPack" $ do
let x = untypedLocalData (1 :: LocalData Int)
let x2 = iPackTupleObs (x :| [x])
res <- exec1Def x2
res `shouldBe` rowCell [IntElement 1, IntElement 1]
xrun "BroadcastPair" $ do
let x = 1 :: LocalData Int
let ds = dataset [2, 3] :: Dataset Int
let ds2 = broadcastPair ds x
res <- exec1Def (collect (asCol ds2))
res `shouldBe` [(2, 1), (3, 1)]
-- TODO: this combines a lot of elements together.
describe "columns - integration" $ do
xrun "mean" $ do
let ds = dataset [-1, 1] :: Dataset Double
let c = myScaler (asCol ds)
res <- exec1Def (collect c)
res `shouldBe` [-1, 1]
|
tjhunter/karps
|
haskell/test-integration/Spark/Core/ColumnSpec.hs
|
apache-2.0
| 1,919
| 0
| 19
| 457
| 704
| 361
| 343
| 52
| 1
|
{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses #-}
--------------------------------------------------------------------------------
-- This code is generated by util/genC.hs.
--------------------------------------------------------------------------------
module Graphics.UI.GLFW.C where
--------------------------------------------------------------------------------
import Data.Bits ((.&.))
import Data.Char (chr, ord)
import Foreign.C.Types (CDouble, CFloat, CInt, CChar, CUChar, CUInt, CUShort)
import Foreign.Ptr (Ptr)
import Bindings.GLFW
import Graphics.UI.GLFW.Types
--------------------------------------------------------------------------------
class C c h where
fromC :: c -> h
toC :: h -> c
--------------------------------------------------------------------------------
instance C CChar Char where
fromC = chr . fromIntegral
toC = fromIntegral . ord
instance C CInt Char where
fromC = chr . fromIntegral
toC = fromIntegral . ord
instance C CUInt Char where
fromC = chr . fromIntegral
toC = fromIntegral . ord
instance C CDouble Double where
fromC = realToFrac
toC = realToFrac
instance C CInt Int where
fromC = fromIntegral
toC = fromIntegral
instance C CUInt Int where
fromC = fromIntegral
toC = fromIntegral
instance C CUShort Int where
fromC = fromIntegral
toC = fromIntegral
instance C CFloat Double where
fromC = realToFrac
toC = realToFrac
instance C (Ptr C'GLFWmonitor) Monitor where
fromC = Monitor
toC = unMonitor
instance C (Ptr C'GLFWwindow) Window where
fromC = Window
toC = unWindow
instance C CInt ModifierKeys where
fromC v = ModifierKeys
{ modifierKeysShift = (v .&. c'GLFW_MOD_SHIFT) /= 0
, modifierKeysControl = (v .&. c'GLFW_MOD_CONTROL) /= 0
, modifierKeysAlt = (v .&. c'GLFW_MOD_ALT) /= 0
, modifierKeysSuper = (v .&. c'GLFW_MOD_SUPER) /= 0
}
toC = undefined
instance C C'GLFWvidmode VideoMode where
fromC gvm = VideoMode
{ videoModeWidth = fromIntegral $ c'GLFWvidmode'width gvm
, videoModeHeight = fromIntegral $ c'GLFWvidmode'height gvm
, videoModeRedBits = fromIntegral $ c'GLFWvidmode'redBits gvm
, videoModeGreenBits = fromIntegral $ c'GLFWvidmode'greenBits gvm
, videoModeBlueBits = fromIntegral $ c'GLFWvidmode'blueBits gvm
, videoModeRefreshRate = fromIntegral $ c'GLFWvidmode'refreshRate gvm
}
toC = undefined
--------------------------------------------------------------------------------
instance C CInt Bool where
fromC v
| v == c'GL_FALSE = False
| v == c'GL_TRUE = True
| otherwise = error $ "C CInt Bool fromC: " ++ show v
toC False = c'GL_FALSE
toC True = c'GL_TRUE
instance C CInt Error where
fromC v
| v == c'GLFW_NOT_INITIALIZED = Error'NotInitialized
| v == c'GLFW_NO_CURRENT_CONTEXT = Error'NoCurrentContext
| v == c'GLFW_INVALID_ENUM = Error'InvalidEnum
| v == c'GLFW_INVALID_VALUE = Error'InvalidValue
| v == c'GLFW_OUT_OF_MEMORY = Error'OutOfMemory
| v == c'GLFW_API_UNAVAILABLE = Error'ApiUnavailable
| v == c'GLFW_VERSION_UNAVAILABLE = Error'VersionUnavailable
| v == c'GLFW_PLATFORM_ERROR = Error'PlatformError
| v == c'GLFW_FORMAT_UNAVAILABLE = Error'FormatUnavailable
| otherwise = error $ "C CInt Error fromC: " ++ show v
toC Error'NotInitialized = c'GLFW_NOT_INITIALIZED
toC Error'NoCurrentContext = c'GLFW_NO_CURRENT_CONTEXT
toC Error'InvalidEnum = c'GLFW_INVALID_ENUM
toC Error'InvalidValue = c'GLFW_INVALID_VALUE
toC Error'OutOfMemory = c'GLFW_OUT_OF_MEMORY
toC Error'ApiUnavailable = c'GLFW_API_UNAVAILABLE
toC Error'VersionUnavailable = c'GLFW_VERSION_UNAVAILABLE
toC Error'PlatformError = c'GLFW_PLATFORM_ERROR
toC Error'FormatUnavailable = c'GLFW_FORMAT_UNAVAILABLE
instance C CInt MonitorState where
fromC v
| v == c'GL_TRUE = MonitorState'Connected
| v == c'GL_FALSE = MonitorState'Disconnected
| otherwise = error $ "C CInt MonitorState fromC: " ++ show v
toC MonitorState'Connected = c'GL_TRUE
toC MonitorState'Disconnected = c'GL_FALSE
instance C CInt FocusState where
fromC v
| v == c'GL_TRUE = FocusState'Focused
| v == c'GL_FALSE = FocusState'Defocused
| otherwise = error $ "C CInt FocusState fromC: " ++ show v
toC FocusState'Focused = c'GL_TRUE
toC FocusState'Defocused = c'GL_FALSE
instance C CInt IconifyState where
fromC v
| v == c'GL_TRUE = IconifyState'Iconified
| v == c'GL_FALSE = IconifyState'NotIconified
| otherwise = error $ "C CInt IconifyState fromC: " ++ show v
toC IconifyState'Iconified = c'GL_TRUE
toC IconifyState'NotIconified = c'GL_FALSE
instance C CInt ContextRobustness where
fromC v
| v == c'GLFW_NO_ROBUSTNESS = ContextRobustness'NoRobustness
| v == c'GLFW_NO_RESET_NOTIFICATION = ContextRobustness'NoResetNotification
| v == c'GLFW_LOSE_CONTEXT_ON_RESET = ContextRobustness'LoseContextOnReset
| otherwise = error $ "C CInt ContextRobustness fromC: " ++ show v
toC ContextRobustness'NoRobustness = c'GLFW_NO_ROBUSTNESS
toC ContextRobustness'NoResetNotification = c'GLFW_NO_RESET_NOTIFICATION
toC ContextRobustness'LoseContextOnReset = c'GLFW_LOSE_CONTEXT_ON_RESET
instance C CInt OpenGLProfile where
fromC v
| v == c'GLFW_OPENGL_ANY_PROFILE = OpenGLProfile'Any
| v == c'GLFW_OPENGL_COMPAT_PROFILE = OpenGLProfile'Compat
| v == c'GLFW_OPENGL_CORE_PROFILE = OpenGLProfile'Core
| otherwise = error $ "C CInt OpenGLProfile fromC: " ++ show v
toC OpenGLProfile'Any = c'GLFW_OPENGL_ANY_PROFILE
toC OpenGLProfile'Compat = c'GLFW_OPENGL_COMPAT_PROFILE
toC OpenGLProfile'Core = c'GLFW_OPENGL_CORE_PROFILE
instance C CInt ClientAPI where
fromC v
| v == c'GLFW_OPENGL_API = ClientAPI'OpenGL
| v == c'GLFW_OPENGL_ES_API = ClientAPI'OpenGLES
| otherwise = error $ "C CInt ClientAPI fromC: " ++ show v
toC ClientAPI'OpenGL = c'GLFW_OPENGL_API
toC ClientAPI'OpenGLES = c'GLFW_OPENGL_ES_API
instance C CInt Key where
fromC v
| v == c'GLFW_KEY_UNKNOWN = Key'Unknown
| v == c'GLFW_KEY_SPACE = Key'Space
| v == c'GLFW_KEY_APOSTROPHE = Key'Apostrophe
| v == c'GLFW_KEY_COMMA = Key'Comma
| v == c'GLFW_KEY_MINUS = Key'Minus
| v == c'GLFW_KEY_PERIOD = Key'Period
| v == c'GLFW_KEY_SLASH = Key'Slash
| v == c'GLFW_KEY_0 = Key'0
| v == c'GLFW_KEY_1 = Key'1
| v == c'GLFW_KEY_2 = Key'2
| v == c'GLFW_KEY_3 = Key'3
| v == c'GLFW_KEY_4 = Key'4
| v == c'GLFW_KEY_5 = Key'5
| v == c'GLFW_KEY_6 = Key'6
| v == c'GLFW_KEY_7 = Key'7
| v == c'GLFW_KEY_8 = Key'8
| v == c'GLFW_KEY_9 = Key'9
| v == c'GLFW_KEY_SEMICOLON = Key'Semicolon
| v == c'GLFW_KEY_EQUAL = Key'Equal
| v == c'GLFW_KEY_A = Key'A
| v == c'GLFW_KEY_B = Key'B
| v == c'GLFW_KEY_C = Key'C
| v == c'GLFW_KEY_D = Key'D
| v == c'GLFW_KEY_E = Key'E
| v == c'GLFW_KEY_F = Key'F
| v == c'GLFW_KEY_G = Key'G
| v == c'GLFW_KEY_H = Key'H
| v == c'GLFW_KEY_I = Key'I
| v == c'GLFW_KEY_J = Key'J
| v == c'GLFW_KEY_K = Key'K
| v == c'GLFW_KEY_L = Key'L
| v == c'GLFW_KEY_M = Key'M
| v == c'GLFW_KEY_N = Key'N
| v == c'GLFW_KEY_O = Key'O
| v == c'GLFW_KEY_P = Key'P
| v == c'GLFW_KEY_Q = Key'Q
| v == c'GLFW_KEY_R = Key'R
| v == c'GLFW_KEY_S = Key'S
| v == c'GLFW_KEY_T = Key'T
| v == c'GLFW_KEY_U = Key'U
| v == c'GLFW_KEY_V = Key'V
| v == c'GLFW_KEY_W = Key'W
| v == c'GLFW_KEY_X = Key'X
| v == c'GLFW_KEY_Y = Key'Y
| v == c'GLFW_KEY_Z = Key'Z
| v == c'GLFW_KEY_LEFT_BRACKET = Key'LeftBracket
| v == c'GLFW_KEY_BACKSLASH = Key'Backslash
| v == c'GLFW_KEY_RIGHT_BRACKET = Key'RightBracket
| v == c'GLFW_KEY_GRAVE_ACCENT = Key'GraveAccent
| v == c'GLFW_KEY_WORLD_1 = Key'World1
| v == c'GLFW_KEY_WORLD_2 = Key'World2
| v == c'GLFW_KEY_ESCAPE = Key'Escape
| v == c'GLFW_KEY_ENTER = Key'Enter
| v == c'GLFW_KEY_TAB = Key'Tab
| v == c'GLFW_KEY_BACKSPACE = Key'Backspace
| v == c'GLFW_KEY_INSERT = Key'Insert
| v == c'GLFW_KEY_DELETE = Key'Delete
| v == c'GLFW_KEY_RIGHT = Key'Right
| v == c'GLFW_KEY_LEFT = Key'Left
| v == c'GLFW_KEY_DOWN = Key'Down
| v == c'GLFW_KEY_UP = Key'Up
| v == c'GLFW_KEY_PAGE_UP = Key'PageUp
| v == c'GLFW_KEY_PAGE_DOWN = Key'PageDown
| v == c'GLFW_KEY_HOME = Key'Home
| v == c'GLFW_KEY_END = Key'End
| v == c'GLFW_KEY_CAPS_LOCK = Key'CapsLock
| v == c'GLFW_KEY_SCROLL_LOCK = Key'ScrollLock
| v == c'GLFW_KEY_NUM_LOCK = Key'NumLock
| v == c'GLFW_KEY_PRINT_SCREEN = Key'PrintScreen
| v == c'GLFW_KEY_PAUSE = Key'Pause
| v == c'GLFW_KEY_F1 = Key'F1
| v == c'GLFW_KEY_F2 = Key'F2
| v == c'GLFW_KEY_F3 = Key'F3
| v == c'GLFW_KEY_F4 = Key'F4
| v == c'GLFW_KEY_F5 = Key'F5
| v == c'GLFW_KEY_F6 = Key'F6
| v == c'GLFW_KEY_F7 = Key'F7
| v == c'GLFW_KEY_F8 = Key'F8
| v == c'GLFW_KEY_F9 = Key'F9
| v == c'GLFW_KEY_F10 = Key'F10
| v == c'GLFW_KEY_F11 = Key'F11
| v == c'GLFW_KEY_F12 = Key'F12
| v == c'GLFW_KEY_F13 = Key'F13
| v == c'GLFW_KEY_F14 = Key'F14
| v == c'GLFW_KEY_F15 = Key'F15
| v == c'GLFW_KEY_F16 = Key'F16
| v == c'GLFW_KEY_F17 = Key'F17
| v == c'GLFW_KEY_F18 = Key'F18
| v == c'GLFW_KEY_F19 = Key'F19
| v == c'GLFW_KEY_F20 = Key'F20
| v == c'GLFW_KEY_F21 = Key'F21
| v == c'GLFW_KEY_F22 = Key'F22
| v == c'GLFW_KEY_F23 = Key'F23
| v == c'GLFW_KEY_F24 = Key'F24
| v == c'GLFW_KEY_F25 = Key'F25
| v == c'GLFW_KEY_KP_0 = Key'Pad0
| v == c'GLFW_KEY_KP_1 = Key'Pad1
| v == c'GLFW_KEY_KP_2 = Key'Pad2
| v == c'GLFW_KEY_KP_3 = Key'Pad3
| v == c'GLFW_KEY_KP_4 = Key'Pad4
| v == c'GLFW_KEY_KP_5 = Key'Pad5
| v == c'GLFW_KEY_KP_6 = Key'Pad6
| v == c'GLFW_KEY_KP_7 = Key'Pad7
| v == c'GLFW_KEY_KP_8 = Key'Pad8
| v == c'GLFW_KEY_KP_9 = Key'Pad9
| v == c'GLFW_KEY_KP_DECIMAL = Key'PadDecimal
| v == c'GLFW_KEY_KP_DIVIDE = Key'PadDivide
| v == c'GLFW_KEY_KP_MULTIPLY = Key'PadMultiply
| v == c'GLFW_KEY_KP_SUBTRACT = Key'PadSubtract
| v == c'GLFW_KEY_KP_ADD = Key'PadAdd
| v == c'GLFW_KEY_KP_ENTER = Key'PadEnter
| v == c'GLFW_KEY_KP_EQUAL = Key'PadEqual
| v == c'GLFW_KEY_LEFT_SHIFT = Key'LeftShift
| v == c'GLFW_KEY_LEFT_CONTROL = Key'LeftControl
| v == c'GLFW_KEY_LEFT_ALT = Key'LeftAlt
| v == c'GLFW_KEY_LEFT_SUPER = Key'LeftSuper
| v == c'GLFW_KEY_RIGHT_SHIFT = Key'RightShift
| v == c'GLFW_KEY_RIGHT_CONTROL = Key'RightControl
| v == c'GLFW_KEY_RIGHT_ALT = Key'RightAlt
| v == c'GLFW_KEY_RIGHT_SUPER = Key'RightSuper
| v == c'GLFW_KEY_MENU = Key'Menu
| otherwise = error $ "C CInt Key fromC: " ++ show v
toC Key'Unknown = c'GLFW_KEY_UNKNOWN
toC Key'Space = c'GLFW_KEY_SPACE
toC Key'Apostrophe = c'GLFW_KEY_APOSTROPHE
toC Key'Comma = c'GLFW_KEY_COMMA
toC Key'Minus = c'GLFW_KEY_MINUS
toC Key'Period = c'GLFW_KEY_PERIOD
toC Key'Slash = c'GLFW_KEY_SLASH
toC Key'0 = c'GLFW_KEY_0
toC Key'1 = c'GLFW_KEY_1
toC Key'2 = c'GLFW_KEY_2
toC Key'3 = c'GLFW_KEY_3
toC Key'4 = c'GLFW_KEY_4
toC Key'5 = c'GLFW_KEY_5
toC Key'6 = c'GLFW_KEY_6
toC Key'7 = c'GLFW_KEY_7
toC Key'8 = c'GLFW_KEY_8
toC Key'9 = c'GLFW_KEY_9
toC Key'Semicolon = c'GLFW_KEY_SEMICOLON
toC Key'Equal = c'GLFW_KEY_EQUAL
toC Key'A = c'GLFW_KEY_A
toC Key'B = c'GLFW_KEY_B
toC Key'C = c'GLFW_KEY_C
toC Key'D = c'GLFW_KEY_D
toC Key'E = c'GLFW_KEY_E
toC Key'F = c'GLFW_KEY_F
toC Key'G = c'GLFW_KEY_G
toC Key'H = c'GLFW_KEY_H
toC Key'I = c'GLFW_KEY_I
toC Key'J = c'GLFW_KEY_J
toC Key'K = c'GLFW_KEY_K
toC Key'L = c'GLFW_KEY_L
toC Key'M = c'GLFW_KEY_M
toC Key'N = c'GLFW_KEY_N
toC Key'O = c'GLFW_KEY_O
toC Key'P = c'GLFW_KEY_P
toC Key'Q = c'GLFW_KEY_Q
toC Key'R = c'GLFW_KEY_R
toC Key'S = c'GLFW_KEY_S
toC Key'T = c'GLFW_KEY_T
toC Key'U = c'GLFW_KEY_U
toC Key'V = c'GLFW_KEY_V
toC Key'W = c'GLFW_KEY_W
toC Key'X = c'GLFW_KEY_X
toC Key'Y = c'GLFW_KEY_Y
toC Key'Z = c'GLFW_KEY_Z
toC Key'LeftBracket = c'GLFW_KEY_LEFT_BRACKET
toC Key'Backslash = c'GLFW_KEY_BACKSLASH
toC Key'RightBracket = c'GLFW_KEY_RIGHT_BRACKET
toC Key'GraveAccent = c'GLFW_KEY_GRAVE_ACCENT
toC Key'World1 = c'GLFW_KEY_WORLD_1
toC Key'World2 = c'GLFW_KEY_WORLD_2
toC Key'Escape = c'GLFW_KEY_ESCAPE
toC Key'Enter = c'GLFW_KEY_ENTER
toC Key'Tab = c'GLFW_KEY_TAB
toC Key'Backspace = c'GLFW_KEY_BACKSPACE
toC Key'Insert = c'GLFW_KEY_INSERT
toC Key'Delete = c'GLFW_KEY_DELETE
toC Key'Right = c'GLFW_KEY_RIGHT
toC Key'Left = c'GLFW_KEY_LEFT
toC Key'Down = c'GLFW_KEY_DOWN
toC Key'Up = c'GLFW_KEY_UP
toC Key'PageUp = c'GLFW_KEY_PAGE_UP
toC Key'PageDown = c'GLFW_KEY_PAGE_DOWN
toC Key'Home = c'GLFW_KEY_HOME
toC Key'End = c'GLFW_KEY_END
toC Key'CapsLock = c'GLFW_KEY_CAPS_LOCK
toC Key'ScrollLock = c'GLFW_KEY_SCROLL_LOCK
toC Key'NumLock = c'GLFW_KEY_NUM_LOCK
toC Key'PrintScreen = c'GLFW_KEY_PRINT_SCREEN
toC Key'Pause = c'GLFW_KEY_PAUSE
toC Key'F1 = c'GLFW_KEY_F1
toC Key'F2 = c'GLFW_KEY_F2
toC Key'F3 = c'GLFW_KEY_F3
toC Key'F4 = c'GLFW_KEY_F4
toC Key'F5 = c'GLFW_KEY_F5
toC Key'F6 = c'GLFW_KEY_F6
toC Key'F7 = c'GLFW_KEY_F7
toC Key'F8 = c'GLFW_KEY_F8
toC Key'F9 = c'GLFW_KEY_F9
toC Key'F10 = c'GLFW_KEY_F10
toC Key'F11 = c'GLFW_KEY_F11
toC Key'F12 = c'GLFW_KEY_F12
toC Key'F13 = c'GLFW_KEY_F13
toC Key'F14 = c'GLFW_KEY_F14
toC Key'F15 = c'GLFW_KEY_F15
toC Key'F16 = c'GLFW_KEY_F16
toC Key'F17 = c'GLFW_KEY_F17
toC Key'F18 = c'GLFW_KEY_F18
toC Key'F19 = c'GLFW_KEY_F19
toC Key'F20 = c'GLFW_KEY_F20
toC Key'F21 = c'GLFW_KEY_F21
toC Key'F22 = c'GLFW_KEY_F22
toC Key'F23 = c'GLFW_KEY_F23
toC Key'F24 = c'GLFW_KEY_F24
toC Key'F25 = c'GLFW_KEY_F25
toC Key'Pad0 = c'GLFW_KEY_KP_0
toC Key'Pad1 = c'GLFW_KEY_KP_1
toC Key'Pad2 = c'GLFW_KEY_KP_2
toC Key'Pad3 = c'GLFW_KEY_KP_3
toC Key'Pad4 = c'GLFW_KEY_KP_4
toC Key'Pad5 = c'GLFW_KEY_KP_5
toC Key'Pad6 = c'GLFW_KEY_KP_6
toC Key'Pad7 = c'GLFW_KEY_KP_7
toC Key'Pad8 = c'GLFW_KEY_KP_8
toC Key'Pad9 = c'GLFW_KEY_KP_9
toC Key'PadDecimal = c'GLFW_KEY_KP_DECIMAL
toC Key'PadDivide = c'GLFW_KEY_KP_DIVIDE
toC Key'PadMultiply = c'GLFW_KEY_KP_MULTIPLY
toC Key'PadSubtract = c'GLFW_KEY_KP_SUBTRACT
toC Key'PadAdd = c'GLFW_KEY_KP_ADD
toC Key'PadEnter = c'GLFW_KEY_KP_ENTER
toC Key'PadEqual = c'GLFW_KEY_KP_EQUAL
toC Key'LeftShift = c'GLFW_KEY_LEFT_SHIFT
toC Key'LeftControl = c'GLFW_KEY_LEFT_CONTROL
toC Key'LeftAlt = c'GLFW_KEY_LEFT_ALT
toC Key'LeftSuper = c'GLFW_KEY_LEFT_SUPER
toC Key'RightShift = c'GLFW_KEY_RIGHT_SHIFT
toC Key'RightControl = c'GLFW_KEY_RIGHT_CONTROL
toC Key'RightAlt = c'GLFW_KEY_RIGHT_ALT
toC Key'RightSuper = c'GLFW_KEY_RIGHT_SUPER
toC Key'Menu = c'GLFW_KEY_MENU
instance C CInt KeyState where
fromC v
| v == c'GLFW_PRESS = KeyState'Pressed
| v == c'GLFW_RELEASE = KeyState'Released
| v == c'GLFW_REPEAT = KeyState'Repeating
| otherwise = error $ "C CInt KeyState fromC: " ++ show v
toC KeyState'Pressed = c'GLFW_PRESS
toC KeyState'Released = c'GLFW_RELEASE
toC KeyState'Repeating = c'GLFW_REPEAT
instance C CInt Joystick where
fromC v
| v == c'GLFW_JOYSTICK_1 = Joystick'1
| v == c'GLFW_JOYSTICK_2 = Joystick'2
| v == c'GLFW_JOYSTICK_3 = Joystick'3
| v == c'GLFW_JOYSTICK_4 = Joystick'4
| v == c'GLFW_JOYSTICK_5 = Joystick'5
| v == c'GLFW_JOYSTICK_6 = Joystick'6
| v == c'GLFW_JOYSTICK_7 = Joystick'7
| v == c'GLFW_JOYSTICK_8 = Joystick'8
| v == c'GLFW_JOYSTICK_9 = Joystick'9
| v == c'GLFW_JOYSTICK_10 = Joystick'10
| v == c'GLFW_JOYSTICK_11 = Joystick'11
| v == c'GLFW_JOYSTICK_12 = Joystick'12
| v == c'GLFW_JOYSTICK_13 = Joystick'13
| v == c'GLFW_JOYSTICK_14 = Joystick'14
| v == c'GLFW_JOYSTICK_15 = Joystick'15
| v == c'GLFW_JOYSTICK_16 = Joystick'16
| otherwise = error $ "C CInt Joystick fromC: " ++ show v
toC Joystick'1 = c'GLFW_JOYSTICK_1
toC Joystick'2 = c'GLFW_JOYSTICK_2
toC Joystick'3 = c'GLFW_JOYSTICK_3
toC Joystick'4 = c'GLFW_JOYSTICK_4
toC Joystick'5 = c'GLFW_JOYSTICK_5
toC Joystick'6 = c'GLFW_JOYSTICK_6
toC Joystick'7 = c'GLFW_JOYSTICK_7
toC Joystick'8 = c'GLFW_JOYSTICK_8
toC Joystick'9 = c'GLFW_JOYSTICK_9
toC Joystick'10 = c'GLFW_JOYSTICK_10
toC Joystick'11 = c'GLFW_JOYSTICK_11
toC Joystick'12 = c'GLFW_JOYSTICK_12
toC Joystick'13 = c'GLFW_JOYSTICK_13
toC Joystick'14 = c'GLFW_JOYSTICK_14
toC Joystick'15 = c'GLFW_JOYSTICK_15
toC Joystick'16 = c'GLFW_JOYSTICK_16
instance C CUChar JoystickButtonState where
fromC v
| v == c'GLFW_PRESS = JoystickButtonState'Pressed
| v == c'GLFW_RELEASE = JoystickButtonState'Released
| otherwise = error $ "C CUChar JoystickButtonState fromC: " ++ show v
toC JoystickButtonState'Pressed = c'GLFW_PRESS
toC JoystickButtonState'Released = c'GLFW_RELEASE
instance C CInt MouseButton where
fromC v
| v == c'GLFW_MOUSE_BUTTON_1 = MouseButton'1
| v == c'GLFW_MOUSE_BUTTON_2 = MouseButton'2
| v == c'GLFW_MOUSE_BUTTON_3 = MouseButton'3
| v == c'GLFW_MOUSE_BUTTON_4 = MouseButton'4
| v == c'GLFW_MOUSE_BUTTON_5 = MouseButton'5
| v == c'GLFW_MOUSE_BUTTON_6 = MouseButton'6
| v == c'GLFW_MOUSE_BUTTON_7 = MouseButton'7
| v == c'GLFW_MOUSE_BUTTON_8 = MouseButton'8
| otherwise = error $ "C CInt MouseButton fromC: " ++ show v
toC MouseButton'1 = c'GLFW_MOUSE_BUTTON_1
toC MouseButton'2 = c'GLFW_MOUSE_BUTTON_2
toC MouseButton'3 = c'GLFW_MOUSE_BUTTON_3
toC MouseButton'4 = c'GLFW_MOUSE_BUTTON_4
toC MouseButton'5 = c'GLFW_MOUSE_BUTTON_5
toC MouseButton'6 = c'GLFW_MOUSE_BUTTON_6
toC MouseButton'7 = c'GLFW_MOUSE_BUTTON_7
toC MouseButton'8 = c'GLFW_MOUSE_BUTTON_8
instance C CInt MouseButtonState where
fromC v
| v == c'GLFW_PRESS = MouseButtonState'Pressed
| v == c'GLFW_RELEASE = MouseButtonState'Released
| otherwise = error $ "C CInt MouseButtonState fromC: " ++ show v
toC MouseButtonState'Pressed = c'GLFW_PRESS
toC MouseButtonState'Released = c'GLFW_RELEASE
instance C CInt CursorState where
fromC v
| v == c'GL_TRUE = CursorState'InWindow
| v == c'GL_FALSE = CursorState'NotInWindow
| otherwise = error $ "C CInt CursorState fromC: " ++ show v
toC CursorState'InWindow = c'GL_TRUE
toC CursorState'NotInWindow = c'GL_FALSE
instance C CInt CursorInputMode where
fromC v
| v == c'GLFW_CURSOR_NORMAL = CursorInputMode'Normal
| v == c'GLFW_CURSOR_HIDDEN = CursorInputMode'Hidden
| v == c'GLFW_CURSOR_DISABLED = CursorInputMode'Disabled
| otherwise = error $ "C CInt CursorInputMode fromC: " ++ show v
toC CursorInputMode'Normal = c'GLFW_CURSOR_NORMAL
toC CursorInputMode'Hidden = c'GLFW_CURSOR_HIDDEN
toC CursorInputMode'Disabled = c'GLFW_CURSOR_DISABLED
instance C CInt StickyKeysInputMode where
fromC v
| v == c'GL_TRUE = StickyKeysInputMode'Enabled
| v == c'GL_FALSE = StickyKeysInputMode'Disabled
| otherwise = error $ "C CInt StickyKeysInputMode fromC: " ++ show v
toC StickyKeysInputMode'Enabled = c'GL_TRUE
toC StickyKeysInputMode'Disabled = c'GL_FALSE
instance C CInt StickyMouseButtonsInputMode where
fromC v
| v == c'GL_TRUE = StickyMouseButtonsInputMode'Enabled
| v == c'GL_FALSE = StickyMouseButtonsInputMode'Disabled
| otherwise = error $ "C CInt StickyMouseButtonsInputMode fromC: " ++ show v
toC StickyMouseButtonsInputMode'Enabled = c'GL_TRUE
toC StickyMouseButtonsInputMode'Disabled = c'GL_FALSE
--------------------------------------------------------------------------------
-- 3.1 Additions
--------------------------------------------------------------------------------
instance C CInt StandardCursorShape where
fromC v
| v == c'GLFW_ARROW_CURSOR = StandardCursorShape'Arrow
| v == c'GLFW_IBEAM_CURSOR = StandardCursorShape'IBeam
| v == c'GLFW_CROSSHAIR_CURSOR = StandardCursorShape'Crosshair
| v == c'GLFW_HAND_CURSOR = StandardCursorShape'Hand
| v == c'GLFW_HRESIZE_CURSOR = StandardCursorShape'HResize
| v == c'GLFW_VRESIZE_CURSOR = StandardCursorShape'VResize
| otherwise = error $ "C CInt StandardCursorShape fromC: " ++ show v
toC StandardCursorShape'Arrow = c'GLFW_ARROW_CURSOR
toC StandardCursorShape'IBeam = c'GLFW_IBEAM_CURSOR
toC StandardCursorShape'Crosshair = c'GLFW_CROSSHAIR_CURSOR
toC StandardCursorShape'Hand = c'GLFW_HAND_CURSOR
toC StandardCursorShape'HResize = c'GLFW_HRESIZE_CURSOR
toC StandardCursorShape'VResize = c'GLFW_VRESIZE_CURSOR
--------------------------------------------------------------------------------
{-# ANN module "HLint: ignore Use camelCase" #-}
|
Peaker/GLFW-b
|
Graphics/UI/GLFW/C.hs
|
bsd-2-clause
| 20,750
| 0
| 10
| 4,164
| 5,255
| 2,543
| 2,712
| 499
| 0
|
-- |
-- Module : Text.Megaparsec
-- Copyright : Β© 2015 Megaparsec contributors
-- Β© 2007 Paolo Martini
-- Β© 1999β2001 Daan Leijen
-- License : BSD3
--
-- Maintainer : Mark Karpov <markkarpov@opmbx.org>
-- Stability : experimental
-- Portability : portable
--
-- This module includes everything you need to get started writing a parser.
--
-- By default this module is set up to parse character data. If you'd like to
-- parse the result of your own tokenizer you should start with the following
-- imports:
--
-- > import Text.Megaparsec.Prim
-- > import Text.Megaparsec.Combinator
--
-- Then you can implement your own version of 'satisfy' on top of the
-- 'token' primitive.
--
-- Typical import section looks like this:
--
-- > import Text.Megaparsec
-- > import Text.Megaparsec.String
-- > -- import Text.Megaparsec.ByteString
-- > -- import Text.Megaparsec.ByteString.Lazy
-- > -- import Text.Megaparsec.Text
-- > -- import Text.Megaparsec.Text.Lazy
--
-- As you can see the second import depends on data type you want to use as
-- input stream. It just defines useful type-synonym @Parser@ and
-- @parseFromFile@ function.
--
-- Megaparsec is capable of a lot. Apart from this standard functionality
-- you can parse permutation phrases with "Text.Megaparsec.Perm" and even
-- entire languages with "Text.Megaparsec.Lexer". These modules should be
-- imported explicitly along with the two modules mentioned above.
module Text.Megaparsec
( -- * Running parser
Parsec
, ParsecT
, runParser
, runParserT
, parse
, parse'
, parseTest
-- * Combinators
, (A.<|>)
-- $assocbo
, A.many
-- $many
, A.some
-- $some
, A.optional
-- $optional
, unexpected
, (<?>)
, label
, hidden
, try
, lookAhead
, notFollowedBy
, eof
, token
, tokens
, between
, choice
, count
, count'
, endBy
, endBy1
, manyTill
, someTill
, option
, sepBy
, sepBy1
, skipMany
, skipSome
-- Deprecated combinators
, chainl
, chainl1
, chainr
, chainr1
, sepEndBy
, sepEndBy1
-- * Character parsing
, newline
, crlf
, eol
, tab
, space
, controlChar
, spaceChar
, upperChar
, lowerChar
, letterChar
, alphaNumChar
, printChar
, digitChar
, octDigitChar
, hexDigitChar
, markChar
, numberChar
, punctuationChar
, symbolChar
, separatorChar
, asciiChar
, latin1Char
, charCategory
, char
, char'
, anyChar
, oneOf
, oneOf'
, noneOf
, noneOf'
, satisfy
, string
, string'
-- * Error messages
, Message (..)
, messageString
, badMessage
, ParseError
, errorPos
, errorMessages
, errorIsUnknown
-- * Textual source position
, SourcePos
, sourceName
, sourceLine
, sourceColumn
-- * Low-level operations
, Stream (..)
, Consumed (..)
, Reply (..)
, State (..)
, getInput
, setInput
, getPosition
, setPosition
, getTabWidth
, setTabWidth
, getParserState
, setParserState
, updateParserState )
where
import qualified Control.Applicative as A
import Text.Megaparsec.Char
import Text.Megaparsec.Combinator
import Text.Megaparsec.Error
import Text.Megaparsec.Pos
import Text.Megaparsec.Prim
-- $assocbo
--
-- This combinator implements choice. The parser @p \<|> q@ first applies
-- @p@. If it succeeds, the value of @p@ is returned. If @p@ fails
-- /without consuming any input/, parser @q@ is tried.
--
-- The parser is called /predictive/ since @q@ is only tried when parser @p@
-- didn't consume any input (i.e. the look ahead is 1). This
-- non-backtracking behaviour allows for both an efficient implementation of
-- the parser combinators and the generation of good error messages.
-- $many
--
-- @many p@ applies the parser @p@ /zero/ or more times. Returns a list of
-- the returned values of @p@.
--
-- > identifier = (:) <$> letter <*> many (alphaNum <|> char '_')
-- $some
--
-- @some p@ applies the parser @p@ /one/ or more times. Returns a list of
-- the returned values of @p@.
--
-- > word = some letter
-- $optional
--
-- @optional p@ tries to apply parser @p@. It will parse @p@ or nothing. It
-- only fails if @p@ fails after consuming input. On success result of @p@
-- is returned inside of 'Just', on failure 'Nothing' is returned.
|
neongreen/megaparsec
|
Text/Megaparsec.hs
|
bsd-2-clause
| 4,304
| 0
| 5
| 964
| 447
| 326
| 121
| 105
| 0
|
module Toy.Exp.Util
( arithspoon
, boolL
, asToBool
, binResToBool
) where
import Control.DeepSeq (NFData)
import Control.Exception (ArithException, Handler (..))
import Control.Lens (Iso', from, iso)
import Control.Monad.Error.Class (MonadError (..))
import Control.Spoon (spoonWithHandles)
import Data.Maybe (fromJust)
import Data.String (IsString (..))
import Universum
import Toy.Base (Value)
boolL :: Iso' Value Bool
boolL = iso (/= 0) (fromIntegral . fromEnum)
asToBool :: (Bool -> Bool -> Bool) -> Value -> Value -> Value
asToBool f a b = f (a ^. boolL) (b ^. boolL) ^. from boolL
binResToBool :: (Value -> Value -> Bool) -> Value -> Value -> Value
binResToBool f a b = f a b ^. from boolL
-- | Like `teaspoon`, but for `ArithException` only and reports details
-- in case of error
arithspoon :: (MonadError e m, IsString e, NFData a) => a -> m a
arithspoon = either (throwError . fromString) return
. fromJust . spoonWithHandles [Handler handler] . Right
where
handler = return . Just . Left . show @ArithException
|
Martoon-00/toy-compiler
|
src/Toy/Exp/Util.hs
|
bsd-3-clause
| 1,246
| 0
| 10
| 388
| 375
| 209
| 166
| -1
| -1
|
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE BangPatterns
, CPP
, ExistentialQuantification
, NoImplicitPrelude
, RecordWildCards
, TypeSynonymInstances
, FlexibleInstances
#-}
-- |
-- The event manager supports event notification on fds. Each fd may
-- have multiple callbacks registered, each listening for a different
-- set of events. Registrations may be automatically deactivated after
-- the occurrence of an event ("one-shot mode") or active until
-- explicitly unregistered.
--
-- If an fd has only one-shot registrations then we use one-shot
-- polling if available. Otherwise we use multi-shot polling.
module GHC.Event.Manager
#ifdef ghcjs_HOST_OS
() where
#else
( -- * Types
EventManager
-- * Creation
, new
, newWith
, newDefaultBackend
-- * Running
, finished
, loop
, step
, shutdown
, release
, cleanup
, wakeManager
-- * State
, callbackTableVar
, emControl
-- * Registering interest in I/O events
, Lifetime (..)
, Event
, evtRead
, evtWrite
, IOCallback
, FdKey(keyFd)
, FdData
, registerFd
, unregisterFd_
, unregisterFd
, closeFd
, closeFd_
) where
#include "EventConfig.h"
------------------------------------------------------------------------
-- Imports
import Control.Concurrent.MVar (MVar, newMVar, putMVar,
tryPutMVar, takeMVar, withMVar)
import Control.Exception (onException)
import Data.Bits ((.&.))
import Data.Foldable (forM_)
import Data.Functor (void)
import Data.IORef (IORef, atomicModifyIORef', mkWeakIORef, newIORef, readIORef,
writeIORef)
import Data.Maybe (maybe)
import Data.OldList (partition)
import GHC.Arr (Array, (!), listArray)
import GHC.Base
import GHC.Conc.Sync (yield)
import GHC.List (filter, replicate)
import GHC.Num (Num(..))
import GHC.Real (fromIntegral)
import GHC.Show (Show(..))
import GHC.Event.Control
import GHC.Event.IntTable (IntTable)
import GHC.Event.Internal (Backend, Event, evtClose, evtRead, evtWrite,
Lifetime(..), EventLifetime, Timeout(..))
import GHC.Event.Unique (Unique, UniqueSource, newSource, newUnique)
import System.Posix.Types (Fd)
import qualified GHC.Event.IntTable as IT
import qualified GHC.Event.Internal as I
#if defined(HAVE_KQUEUE)
import qualified GHC.Event.KQueue as KQueue
#elif defined(HAVE_EPOLL)
import qualified GHC.Event.EPoll as EPoll
#elif defined(HAVE_POLL)
import qualified GHC.Event.Poll as Poll
#else
# error not implemented for this operating system
#endif
------------------------------------------------------------------------
-- Types
data FdData = FdData {
fdKey :: {-# UNPACK #-} !FdKey
, fdEvents :: {-# UNPACK #-} !EventLifetime
, _fdCallback :: !IOCallback
}
-- | A file descriptor registration cookie.
data FdKey = FdKey {
keyFd :: {-# UNPACK #-} !Fd
, keyUnique :: {-# UNPACK #-} !Unique
} deriving (Eq, Show)
-- | Callback invoked on I/O events.
type IOCallback = FdKey -> Event -> IO ()
data State = Created
| Running
| Dying
| Releasing
| Finished
deriving (Eq, Show)
-- | The event manager state.
data EventManager = EventManager
{ emBackend :: !Backend
, emFds :: {-# UNPACK #-} !(Array Int (MVar (IntTable [FdData])))
, emState :: {-# UNPACK #-} !(IORef State)
, emUniqueSource :: {-# UNPACK #-} !UniqueSource
, emControl :: {-# UNPACK #-} !Control
, emLock :: {-# UNPACK #-} !(MVar ())
}
-- must be power of 2
callbackArraySize :: Int
callbackArraySize = 32
hashFd :: Fd -> Int
hashFd fd = fromIntegral fd .&. (callbackArraySize - 1)
{-# INLINE hashFd #-}
callbackTableVar :: EventManager -> Fd -> MVar (IntTable [FdData])
callbackTableVar mgr fd = emFds mgr ! hashFd fd
{-# INLINE callbackTableVar #-}
haveOneShot :: Bool
{-# INLINE haveOneShot #-}
#if defined(darwin_HOST_OS) || defined(ios_HOST_OS)
haveOneShot = False
#elif defined(HAVE_EPOLL) || defined(HAVE_KQUEUE)
haveOneShot = True
#else
haveOneShot = False
#endif
------------------------------------------------------------------------
-- Creation
handleControlEvent :: EventManager -> Fd -> Event -> IO ()
handleControlEvent mgr fd _evt = do
msg <- readControlMessage (emControl mgr) fd
case msg of
CMsgWakeup -> return ()
CMsgDie -> writeIORef (emState mgr) Finished
_ -> return ()
newDefaultBackend :: IO Backend
#if defined(HAVE_KQUEUE)
newDefaultBackend = KQueue.new
#elif defined(HAVE_EPOLL)
newDefaultBackend = EPoll.new
#elif defined(HAVE_POLL)
newDefaultBackend = Poll.new
#else
newDefaultBackend = error "no back end for this platform"
#endif
-- | Create a new event manager.
new :: IO EventManager
new = newWith =<< newDefaultBackend
-- | Create a new 'EventManager' with the given polling backend.
newWith :: Backend -> IO EventManager
newWith be = do
iofds <- fmap (listArray (0, callbackArraySize-1)) $
replicateM callbackArraySize (newMVar =<< IT.new 8)
ctrl <- newControl False
state <- newIORef Created
us <- newSource
_ <- mkWeakIORef state $ do
st <- atomicModifyIORef' state $ \s -> (Finished, s)
when (st /= Finished) $ do
I.delete be
closeControl ctrl
lockVar <- newMVar ()
let mgr = EventManager { emBackend = be
, emFds = iofds
, emState = state
, emUniqueSource = us
, emControl = ctrl
, emLock = lockVar
}
registerControlFd mgr (controlReadFd ctrl) evtRead
registerControlFd mgr (wakeupReadFd ctrl) evtRead
return mgr
where
replicateM n x = sequence (replicate n x)
failOnInvalidFile :: String -> Fd -> IO Bool -> IO ()
failOnInvalidFile loc fd m = do
ok <- m
when (not ok) $
let msg = "Failed while attempting to modify registration of file " ++
show fd ++ " at location " ++ loc
in error msg
registerControlFd :: EventManager -> Fd -> Event -> IO ()
registerControlFd mgr fd evs =
failOnInvalidFile "registerControlFd" fd $
I.modifyFd (emBackend mgr) fd mempty evs
-- | Asynchronously shuts down the event manager, if running.
shutdown :: EventManager -> IO ()
shutdown mgr = do
state <- atomicModifyIORef' (emState mgr) $ \s -> (Dying, s)
when (state == Running) $ sendDie (emControl mgr)
-- | Asynchronously tell the thread executing the event
-- manager loop to exit.
release :: EventManager -> IO ()
release EventManager{..} = do
state <- atomicModifyIORef' emState $ \s -> (Releasing, s)
when (state == Running) $ sendWakeup emControl
finished :: EventManager -> IO Bool
finished mgr = (== Finished) `liftM` readIORef (emState mgr)
cleanup :: EventManager -> IO ()
cleanup EventManager{..} = do
writeIORef emState Finished
void $ tryPutMVar emLock ()
I.delete emBackend
closeControl emControl
------------------------------------------------------------------------
-- Event loop
-- | Start handling events. This function loops until told to stop,
-- using 'shutdown'.
--
-- /Note/: This loop can only be run once per 'EventManager', as it
-- closes all of its control resources when it finishes.
loop :: EventManager -> IO ()
loop mgr@EventManager{..} = do
void $ takeMVar emLock
state <- atomicModifyIORef' emState $ \s -> case s of
Created -> (Running, s)
Releasing -> (Running, s)
_ -> (s, s)
case state of
Created -> go `onException` cleanup mgr
Releasing -> go `onException` cleanup mgr
Dying -> cleanup mgr
-- While a poll loop is never forked when the event manager is in the
-- 'Finished' state, its state could read 'Finished' once the new thread
-- actually runs. This is not an error, just an unfortunate race condition
-- in Thread.restartPollLoop. See #8235
Finished -> return ()
_ -> do cleanup mgr
error $ "GHC.Event.Manager.loop: state is already " ++
show state
where
go = do state <- step mgr
case state of
Running -> yield >> go
Releasing -> putMVar emLock ()
_ -> cleanup mgr
-- | To make a step, we first do a non-blocking poll, in case
-- there are already events ready to handle. This improves performance
-- because we can make an unsafe foreign C call, thereby avoiding
-- forcing the current Task to release the Capability and forcing a context switch.
-- If the poll fails to find events, we yield, putting the poll loop thread at
-- end of the Haskell run queue. When it comes back around, we do one more
-- non-blocking poll, in case we get lucky and have ready events.
-- If that also returns no events, then we do a blocking poll.
step :: EventManager -> IO State
step mgr@EventManager{..} = do
waitForIO
state <- readIORef emState
state `seq` return state
where
waitForIO = do
n1 <- I.poll emBackend Nothing (onFdEvent mgr)
when (n1 <= 0) $ do
yield
n2 <- I.poll emBackend Nothing (onFdEvent mgr)
when (n2 <= 0) $ do
_ <- I.poll emBackend (Just Forever) (onFdEvent mgr)
return ()
------------------------------------------------------------------------
-- Registering interest in I/O events
-- | Register interest in the given events, without waking the event
-- manager thread. The 'Bool' return value indicates whether the
-- event manager ought to be woken.
registerFd_ :: EventManager -> IOCallback -> Fd -> Event -> Lifetime
-> IO (FdKey, Bool)
registerFd_ mgr@(EventManager{..}) cb fd evs lt = do
u <- newUnique emUniqueSource
let fd' = fromIntegral fd
reg = FdKey fd u
el = I.eventLifetime evs lt
!fdd = FdData reg el cb
(modify,ok) <- withMVar (callbackTableVar mgr fd) $ \tbl -> do
oldFdd <- IT.insertWith (++) fd' [fdd] tbl
let prevEvs :: EventLifetime
prevEvs = maybe mempty eventsOf oldFdd
el' :: EventLifetime
el' = prevEvs `mappend` el
case I.elLifetime el' of
-- All registrations want one-shot semantics and this is supported
OneShot | haveOneShot -> do
ok <- I.modifyFdOnce emBackend fd (I.elEvent el')
if ok
then return (False, True)
else IT.reset fd' oldFdd tbl >> return (False, False)
-- We don't want or don't support one-shot semantics
_ -> do
let modify = prevEvs /= el'
ok <- if modify
then let newEvs = I.elEvent el'
oldEvs = I.elEvent prevEvs
in I.modifyFd emBackend fd oldEvs newEvs
else return True
if ok
then return (modify, True)
else IT.reset fd' oldFdd tbl >> return (False, False)
-- this simulates behavior of old IO manager:
-- i.e. just call the callback if the registration fails.
when (not ok) (cb reg evs)
return (reg,modify)
{-# INLINE registerFd_ #-}
-- | @registerFd mgr cb fd evs lt@ registers interest in the events @evs@
-- on the file descriptor @fd@ for lifetime @lt@. @cb@ is called for
-- each event that occurs. Returns a cookie that can be handed to
-- 'unregisterFd'.
registerFd :: EventManager -> IOCallback -> Fd -> Event -> Lifetime -> IO FdKey
registerFd mgr cb fd evs lt = do
(r, wake) <- registerFd_ mgr cb fd evs lt
when wake $ wakeManager mgr
return r
{-# INLINE registerFd #-}
{-
Building GHC with parallel IO manager on Mac freezes when
compiling the dph libraries in the phase 2. As workaround, we
don't use oneshot and we wake up an IO manager on Mac every time
when we register an event.
For more information, please read:
http://ghc.haskell.org/trac/ghc/ticket/7651
-}
-- | Wake up the event manager.
wakeManager :: EventManager -> IO ()
#if defined(darwin_HOST_OS) || defined(ios_HOST_OS)
wakeManager mgr = sendWakeup (emControl mgr)
#elif defined(HAVE_EPOLL) || defined(HAVE_KQUEUE)
wakeManager _ = return ()
#else
wakeManager mgr = sendWakeup (emControl mgr)
#endif
eventsOf :: [FdData] -> EventLifetime
eventsOf [fdd] = fdEvents fdd
eventsOf fdds = mconcat $ map fdEvents fdds
-- | Drop a previous file descriptor registration, without waking the
-- event manager thread. The return value indicates whether the event
-- manager ought to be woken.
unregisterFd_ :: EventManager -> FdKey -> IO Bool
unregisterFd_ mgr@(EventManager{..}) (FdKey fd u) =
withMVar (callbackTableVar mgr fd) $ \tbl -> do
let dropReg = nullToNothing . filter ((/= u) . keyUnique . fdKey)
fd' = fromIntegral fd
pairEvents :: [FdData] -> IO (EventLifetime, EventLifetime)
pairEvents prev = do
r <- maybe mempty eventsOf `fmap` IT.lookup fd' tbl
return (eventsOf prev, r)
(oldEls, newEls) <- IT.updateWith dropReg fd' tbl >>=
maybe (return (mempty, mempty)) pairEvents
let modify = oldEls /= newEls
when modify $ failOnInvalidFile "unregisterFd_" fd $
case I.elLifetime newEls of
OneShot | I.elEvent newEls /= mempty, haveOneShot ->
I.modifyFdOnce emBackend fd (I.elEvent newEls)
_ ->
I.modifyFd emBackend fd (I.elEvent oldEls) (I.elEvent newEls)
return modify
-- | Drop a previous file descriptor registration.
unregisterFd :: EventManager -> FdKey -> IO ()
unregisterFd mgr reg = do
wake <- unregisterFd_ mgr reg
when wake $ wakeManager mgr
-- | Close a file descriptor in a race-safe way.
closeFd :: EventManager -> (Fd -> IO ()) -> Fd -> IO ()
closeFd mgr close fd = do
fds <- withMVar (callbackTableVar mgr fd) $ \tbl -> do
prev <- IT.delete (fromIntegral fd) tbl
case prev of
Nothing -> close fd >> return []
Just fds -> do
let oldEls = eventsOf fds
when (I.elEvent oldEls /= mempty) $ do
_ <- I.modifyFd (emBackend mgr) fd (I.elEvent oldEls) mempty
wakeManager mgr
close fd
return fds
forM_ fds $ \(FdData reg el cb) -> cb reg (I.elEvent el `mappend` evtClose)
-- | Close a file descriptor in a race-safe way.
-- It assumes the caller will update the callback tables and that the caller
-- holds the callback table lock for the fd. It must hold this lock because
-- this command executes a backend command on the fd.
closeFd_ :: EventManager
-> IntTable [FdData]
-> Fd
-> IO (IO ())
closeFd_ mgr tbl fd = do
prev <- IT.delete (fromIntegral fd) tbl
case prev of
Nothing -> return (return ())
Just fds -> do
let oldEls = eventsOf fds
when (oldEls /= mempty) $ do
_ <- I.modifyFd (emBackend mgr) fd (I.elEvent oldEls) mempty
wakeManager mgr
return $
forM_ fds $ \(FdData reg el cb) ->
cb reg (I.elEvent el `mappend` evtClose)
------------------------------------------------------------------------
-- Utilities
-- | Call the callbacks corresponding to the given file descriptor.
onFdEvent :: EventManager -> Fd -> Event -> IO ()
onFdEvent mgr fd evs
| fd == controlReadFd (emControl mgr) || fd == wakeupReadFd (emControl mgr) =
handleControlEvent mgr fd evs
| otherwise = do
fdds <- withMVar (callbackTableVar mgr fd) $ \tbl ->
IT.delete (fromIntegral fd) tbl >>= maybe (return []) selectCallbacks
forM_ fdds $ \(FdData reg _ cb) -> cb reg evs
where
-- | Here we look through the list of registrations for the fd of interest
-- and sort out which match the events that were triggered. We re-arm
-- the fd as appropriate and return this subset.
selectCallbacks :: [FdData] -> IO [FdData]
selectCallbacks fdds = do
let matches :: FdData -> Bool
matches fd' = evs `I.eventIs` I.elEvent (fdEvents fd')
(triggered, saved) = partition matches fdds
savedEls = eventsOf saved
allEls = eventsOf fdds
case I.elLifetime allEls of
-- we previously armed the fd for multiple shots, no need to rearm
MultiShot | allEls == savedEls ->
return ()
-- either we previously registered for one shot or the
-- events of interest have changed, we must re-arm
_ -> do
case I.elLifetime savedEls of
OneShot | haveOneShot ->
-- if there are no saved events there is no need to re-arm
unless (OneShot == I.elLifetime (eventsOf triggered)
&& mempty == savedEls) $
void $ I.modifyFdOnce (emBackend mgr) fd (I.elEvent savedEls)
_ ->
void $ I.modifyFd (emBackend mgr) fd
(I.elEvent allEls) (I.elEvent savedEls)
return ()
return triggered
nullToNothing :: [a] -> Maybe [a]
nullToNothing [] = Nothing
nullToNothing xs@(_:_) = Just xs
unless :: Monad m => Bool -> m () -> m ()
unless p = when (not p)
#endif
|
forked-upstream-packages-for-ghcjs/ghc
|
libraries/base/GHC/Event/Manager.hs
|
bsd-3-clause
| 17,142
| 0
| 27
| 4,467
| 3,671
| 1,841
| 1,830
| -1
| -1
|
module JDec.Class.Typesafe.FieldRef (
FieldRef(FieldRef),
fieldClass,
fieldNameAndType
) where
import JDec.Class.Typesafe.FieldNameAndType(FieldNameAndType())
import Data.Text(Text)
-- | A reference to a class or interface field
data FieldRef = FieldRef {
fieldClass :: Text, -- ^ A class or interface type that has the field as a member.
fieldNameAndType :: FieldNameAndType -- ^ The name and descriptor of the field.
} deriving Show
|
rel-eng/jdec
|
src/JDec/Class/Typesafe/FieldRef.hs
|
bsd-3-clause
| 442
| 0
| 8
| 66
| 75
| 50
| 25
| 12
| 0
|
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree.
{-# LANGUAGE OverloadedStrings #-}
module Duckling.Quantity.KM.Corpus
( corpus
) where
import Data.String
import Prelude
import Duckling.Locale
import Duckling.Quantity.Types
import Duckling.Resolve
import Duckling.Testing.Types
context :: Context
context = testContext{locale = makeLocale KM Nothing}
corpus :: Corpus
corpus = (context, testOptions, allExamples)
allExamples :: [Example]
allExamples = concat
[ examples (simple Cup 3 Nothing)
[ "ααΈααα"
]
, examples (simple Bowl 1 Nothing)
[ "α‘α
αΆα"
]
, examples (simple Pint 15 Nothing)
[ "αααααααΆαααΌ"
]
, examples (simple (Custom "For Persons") 2 (Just "ααα»ααα"))
[ "ααα»αααα’ααΆαα"
, "ααα»αααααΈαααΆαα"
]
, examples (simple (Custom "For Buildings") 8 (Just "αααα"))
[ "ααααα¨αααα"
, "ααααααααΆαααΈαααα"
]
, examples (simple Gram 1000 Nothing)
[ "αα½αααΆααααααΆα"
, "αα½αααΈα‘αΌααααΆα"
, "αα½αααΆαααΈααΈααααΆα"
]
, examples (between Gram (2,7) Nothing)
[ "α
αΆααααΈ 2 ααα 7 ααααΆα"
, "α
αααααααΈ α’ ααα α§ααααΆα"
, "α
ααααα α’ααααΆα αα·α α§ααααΆα"
, "αααα αα α’-α§ ααααΆα"
, "~2-7ααααΆα"
]
, examples (under Tablespoon 4 Nothing)
[ "αα·α
ααΆααα½αααααΆαααααΆ"
, "αα·αααΎαα€ααααΆαααααΆ"
, "αααααα€ααααΆαααααΆ"
, "αααΆαα
αααΎαα€ααααΆαααααΆ"
]
, examples (above Bowl 10 Nothing)
[ "α
αααΎαααΆααααα
αΆα"
, "αα·ααα·α
ααΆααααα
αΆα"
, "ααΎαααΈαααα
αΆα"
, "αααΆααα·α
αααα
αΆα"
]
]
|
facebookincubator/duckling
|
Duckling/Quantity/KM/Corpus.hs
|
bsd-3-clause
| 2,511
| 0
| 11
| 657
| 368
| 211
| 157
| 47
| 1
|
module Main (main) where
import GeekBar
main :: IO ()
main = putStrLn "Nothing is implemented, yet!"
|
aslpavel/geekbar
|
Main.hs
|
bsd-3-clause
| 103
| 0
| 6
| 19
| 30
| 17
| 13
| 4
| 1
|
module Main(main) where
-- we need function pointer type and free function
import Foreign.Ptr(FunPtr, freeHaskellFunPtr)
foreign import ccall output :: Int -> IO ()
-- a "wrapper" import gives a factory for converting a Haskell function to a foreign function pointer
foreign import ccall "wrapper" wrap :: (Int -> Int) -> IO (FunPtr (Int -> Int))
-- import the foreign function as normal
foreign import ccall twice :: FunPtr (Int -> Int) -> Int -> IO Int
-- here's the function to use as a callback
square :: Int -> Int
square x = x * x
main :: IO ()
main = do
squareW <- wrap square -- make function pointer from the function
let x = 4
y <- twice squareW x -- use the foreign function with our callback
z <- twice squareW y
output y -- see that it worked
output z
freeHaskellFunPtr squareW -- clean up after ourselves
|
bosu/josh
|
t/progs/Callback.hs
|
bsd-3-clause
| 883
| 0
| 11
| 217
| 216
| 112
| 104
| 16
| 1
|
{-# LANGUAGE
ConstraintKinds
, EmptyDataDecls
, FlexibleContexts
, FlexibleInstances
, ScopedTypeVariables
, StandaloneDeriving
, TypeFamilies
#-}
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.UI.Toy.Gtk
-- Copyright : (c) 2011 Michael Sloan
-- License : BSD-style (see the LICENSE file)
-- Maintainer : Michael Sloan <mgsloan@gmail.com>
-- Stability : experimental
-- Portability : GHC only
--
-- Implements the toy-interface for gtk. This provides a simple interface for
-- creating applications which draw things and interact with the mouse and
-- keyboard. It handles the minutiae of setting up the gtk window and canvas,
-- and processes the input events.
--
-- The name \"toy\" comes from the \"toy framework\", a part of the lib2geom
-- library (<http://lib2geom.sourceforge.net/>). It's used in building \"toys\"
-- demonstrating the features of the library. This is a different variety of
-- \"TDD\"- but instead of tests, it's toys! We found that building little demos
-- to be a nice way to drive initial design / development.
--
--------------------------------------------------------------------------------
module Graphics.UI.Toy.Gtk
( module Graphics.UI.Toy
, Toy(..), newToy
, runToy, quitToy
-- * Display
, Gtk
, GtkInteractive
, GtkDisplay(..), simpleDisplay
-- * Key Utilities
, eitherHeld, escapeKeyHandler
) where
import Control.Monad ( when )
import Control.Monad.Reader ( lift )
import Data.IORef
import qualified Data.Map as M
import Graphics.UI.Gtk
import Graphics.UI.Toy
-- | A constructor-less type used to indicate usage of the 'Gtk' backend.
data Gtk
type instance MousePos Gtk = (Double, Double)
type instance KeyModifier Gtk = Modifier
deriving instance Eq (InputState Gtk)
deriving instance Show (InputState Gtk)
-- | This is a constraint synonym for the typeclasses that need to be
-- instantiated in order for 'runToy' to be able to run your toy in a Gtk
-- window.
type GtkInteractive a = (Interactive Gtk a, GtkDisplay a)
-- | The typeclass that applications should implement in order to update the
-- canvas.
class GtkDisplay a where
-- | @display@ is called when the rendering needs to be refreshed. It's
-- called with the 'DrawWindow' that should be drawn to, and the current
-- input state / application state.
display :: DrawWindow -> InputState Gtk -> a -> IO a
display _ _ = return
-- | Postfixes \"_L\" and \"_R\" on the key name, and returns true if either of
-- those keys are being held. This is useful for \"Ctrl\", \"Shift\", and
-- \"Alt\".
eitherHeld :: String -> InputState b -> Bool
eitherHeld key inp = (keyHeld (key ++ "_L") inp || keyHeld (key ++ "_R") inp)
-- | Converts a diagram projection to a function for Interactive 'display'.
simpleDisplay :: (DrawWindow -> a -> a)
-> DrawWindow -> InputState Gtk -> a -> IO a
simpleDisplay f dw _ = return . f dw
-- | Like it says on the can. This is a synonym for 'Graphics.UI.Gtk.mainQuit'.
quitToy :: IO ()
quitToy = mainQuit
-- | Calls 'quitToy' when the escape key is pressed.
escapeKeyHandler :: KeyHandler Gtk a
escapeKeyHandler =
keyHandler $ \k x -> do
when (k == (True, Left "Escape")) quitToy
return x
-- | Main program entry-point. This is how you turn an instance of 'Interactive'
-- into an application.
runToy :: GtkInteractive a => a -> IO ()
runToy toy = do
_ <- initGUI
window <- windowNew
windowSetDefaultSize window 640 480
canvas <- newToy toy
set window $ [containerChild := toyWindow canvas]
widgetShowAll window
--TODO: tell the toy that we're going down
--TODO: or better would catch onDelete events and ask toy what to do
_ <- onDestroy window quitToy
mainGUI
-- | Subroutine data.
data Toy a = Toy
{ toyWindow :: EventBox
-- ^ This root widget catches interactive events. Pack this into your GUI.
, toyCanvas :: DrawingArea
-- ^ This child widget does the drawin
, toyState :: IORef (InputState Gtk, a)
-- ^ This contains our world, exposed so that your other worlds can interfer
}
-- | Subroutine entrypoint. This is how you turn an instance of 'GtkInteractive'
-- into a widget-like thing.
newToy :: forall a. GtkInteractive a => a -> IO (Toy a)
newToy toy = do
window <- eventBoxNew
canvas <- drawingAreaNew
state <- newIORef (InputState (0, 0) M.empty, toy)
requested <- newIORef True
let windowEv :: Signal EventBox (EventM e Bool)
-> (IORef (InputState Gtk, a) -> EventM e ())
-> IO (ConnectId EventBox)
windowEv e f = on window e $ f state >> lift redraw
redraw :: IO Bool
redraw = do
r <- readIORef requested
when (not r) $ do
widgetQueueDraw canvas
writeIORef requested True
return True
_ <- windowEv keyPressEvent (handleKey True)
_ <- windowEv keyReleaseEvent (handleKey False)
_ <- windowEv motionNotifyEvent handleMotion
_ <- windowEv buttonPressEvent handleButton
_ <- windowEv buttonReleaseEvent handleButton
widgetAddEvents window [PointerMotionMask, PointerMotionHintMask, ButtonMotionMask]
widgetSetCanFocus window True
widgetGrabFocus window
_ <- onExposeRect canvas $ \_ -> do
dw <- widgetGetDrawWindow canvas
(inp, x) <- readIORef state
x' <- display dw inp x
writeIORef state (inp, x')
writeIORef requested False
set window $ [containerChild := canvas]
let tickHandler = do
st@(inp, _) <- readIORef state
(state', dodraw) <- uncurry tick st
when dodraw (redraw >> return ())
writeIORef state (inp, state')
return True
--TODO: how does this timer behave when hiding / reshowing windows?
--TODO: do we want timer to run only when window is visible?
--TODO: definitely want timer to stop when widgets are permanently gone
timer <- timeoutAddFull tickHandler priorityHighIdle 60
_ <- onUnrealize window $ timeoutRemove timer
return $ Toy window canvas state
handleKey :: Interactive Gtk a
=> Bool -> IORef (InputState Gtk, a) -> EventM EKey ()
handleKey press st = do
ev <- eventKeyVal
name <- eventKeyName
time <- eventTime
mods <- eventModifier
let kv = maybe (Left name) Right $ keyToChar ev
lift $ do
(InputState p m, x) <- readIORef st
let inp' = InputState p (M.insert name (press, fromIntegral time, mods) m)
x' <- keyboard (press, kv) inp' x
writeIORef st (inp', x')
handleMotion :: Interactive Gtk a
=> IORef (InputState Gtk, a) -> EventM EMotion ()
handleMotion st = do
pos <- eventCoordinates
lift $ do
(InputState _ m, a) <- readIORef st
let inp' = InputState pos m
a' <- mouse Nothing inp' a
writeIORef st (inp', a')
handleButton :: Interactive Gtk a
=> IORef (InputState Gtk, a) -> EventM EButton ()
handleButton st = do
time <- eventTime
mods <- eventModifier
click <- eventClick
bIx <- eventButton
pos <- eventCoordinates
let pres = click /= ReleaseClick
buttonIx = case bIx of
LeftButton -> 0
RightButton -> 1
MiddleButton -> 2
--TODO: guaranteed to not be 0,1,2?
OtherButton ix -> ix
when (click == SingleClick || click == ReleaseClick) . lift $ do
(InputState _ m, a) <- readIORef st
let m' = M.insert ("Mouse" ++ show buttonIx)
(pres, fromIntegral time, mods) m
inp' = InputState pos m'
a' <- mouse (Just (pres, buttonIx)) inp' a
writeIORef st (inp', a')
|
mgsloan/toy-gtk
|
src/Graphics/UI/Toy/Gtk.hs
|
bsd-3-clause
| 7,581
| 0
| 17
| 1,741
| 1,776
| 895
| 881
| -1
| -1
|
{-# LANGUAGE LambdaCase #-}
module Main (main) where
import Control.Applicative
import Control.Exception (IOException)
import Control.Monad
import Data.Foldable (for_, traverse_)
import Data.List (isSuffixOf)
import Data.Maybe (catMaybes, fromMaybe)
import Data.Traversable (traverse)
import Data.Version (showVersion)
import System.Directory (copyFile, createDirectoryIfMissing, getAppUserDataDirectory, getDirectoryContents)
import System.Environment (getArgs)
import System.Exit (exitWith, exitFailure)
import System.FilePath ((</>), takeDirectory)
import System.Info (arch, os)
import System.IO (hPutStrLn, stderr)
import System.IO.Error (catchIOError)
import qualified System.Posix as Posix
import System.Process (runProcess, waitForProcess)
import Text.Printf (printf)
import Paths_pakej (version, getDataFileName)
main :: IO ()
main = getArgs >>= \case
["--init"] -> initPakej
"--recompile" : args -> program >>= recompilePakej args
"--edit" : args -> editPakej args
args -> program >>= runPakej args
-- | Create Pakej app directory and copy pakej.hs template over
initPakej :: IO ()
initPakej = do
s <- sourceFile
createDirectoryIfMissing True (takeDirectory s)
t <- getDataFileName "data/pakej.hs"
copyFile t s
-- | Recompile pakej sources and place the result somewhere
recompilePakej :: [String] -> FilePath -> IO a
recompilePakej args dst = do
source <- sourceFile
appDir <- pakejDirectory
exitWith =<<
waitForProcess =<<
runProcess "cabal" (cabalOpts source ++ args) (Just appDir) Nothing Nothing Nothing Nothing
where
cabalOpts s = ["--no-require-sandbox", "exec", "ghc", "--", "-odir", "obj", "-hidir", "obj", s, "-o", dst, "-O", "-threaded"]
editPakej :: [String] -> IO ()
editPakej args = do
source <- sourceFile
appDir <- pakejDirectory
editor <- lookupEditor
mtime <- getModificationTime source
waitForProcess =<<
runProcess editor [source] (Just appDir) Nothing Nothing Nothing Nothing
mtime' <- getModificationTime source
when (mtime' > mtime) $ do
info (printf "Changes detected in %s; attempting to recompile .." source)
program >>= recompilePakej args
where
lookupEditor =
fmap (fromMaybe "/usr/bin/editor") (liftA2 (<|>) (Posix.getEnv "VISUAL") (Posix.getEnv "EDITOR"))
-- | Run pakej executable with the specified arguments
runPakej :: [String] -> FilePath -> IO a
runPakej args path =
getModificationTime path >>= \case
Nothing ->
die "Pakej executable is missing! Did you forget to run\n\
\ pakej --recompile\n\
\?"
Just mtime ->
pakejDirectory >>= getSources >>= fmap catMaybes . traverse getModificationTime >>= \mtimes -> do
for_ (traverse_ (guard . (> mtime)) mtimes :: Maybe ()) $ \_ ->
warn "Some source files are newer than the pakej executable\n\
\To rebuild it, please run\n\
\ pakej --recompile\n\
\!"
Posix.executeFile path False args Nothing
getSources :: FilePath -> IO [FilePath]
getSources file = do
getUsefulDirectoryContents file >>= fmap concat . traverse getSources
`catchIOError`
\_ -> return [file | any (`isSuffixOf` file) [".hs", ".lhs", ".hsc"]]
{-# ANN getSources "HLint: ignore Redundant do" #-}
getUsefulDirectoryContents :: FilePath -> IO [FilePath]
getUsefulDirectoryContents dir =
(map (\file -> dir </> file) . filter (`notElem` [".", ".."])) <$> getDirectoryContents dir
getModificationTime :: FilePath -> IO (Maybe Posix.EpochTime)
getModificationTime =
handleIOError (\_ -> return Nothing) . fmap (Just . Posix.modificationTime) . Posix.getFileStatus
handleIOError :: (IOException -> IO a) -> IO a -> IO a
handleIOError = flip catchIOError
die :: String -> IO a
die m = warn m >> exitFailure
warn :: String -> IO ()
warn = hPutStrLn stderr
info :: String -> IO ()
info = putStrLn
-- | ~/.pakej/pakej-x86_64-linux
program :: IO FilePath
program = inPakejDirectory (printf "pakej-%s-%s-%s" arch os (showVersion version))
-- | ~/.pakej/pakej.hs
sourceFile :: IO FilePath
sourceFile = inPakejDirectory "pakej.hs"
inPakejDirectory :: FilePath -> IO FilePath
inPakejDirectory path = fmap (</> path) pakejDirectory
pakejDirectory :: IO FilePath
pakejDirectory = getAppUserDataDirectory "pakej"
|
supki/pakej
|
bin/Main.hs
|
bsd-3-clause
| 4,479
| 0
| 19
| 975
| 1,227
| 646
| 581
| 93
| 4
|
{-# LANGUAGE UndecidableInstances #-}
-- | 'Syntactic' instance for functions
--
-- This module is based on having 'BindingT' in the domain. For 'Binding' import module
-- "Data.Syntactic.Sugar.Binding" instead
module Data.Syntactic.Sugar.BindingT where
import Data.Typeable
import Data.Syntactic
import Data.Syntactic.Functional
instance
( Syntactic a, Domain a ~ dom
, Syntactic b, Domain b ~ dom
, BindingT :<: dom
, Typeable (Internal a)
) =>
Syntactic (a -> b)
where
type Domain (a -> b) = Domain a
type Internal (a -> b) = Internal a -> Internal b
desugar f = lamT (desugar . f . sugar)
sugar = error "sugar not implemented for (a -> b)"
|
emwap/syntactic
|
src/Data/Syntactic/Sugar/BindingT.hs
|
bsd-3-clause
| 704
| 0
| 9
| 166
| 176
| 95
| 81
| -1
| -1
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleContexts #-}
module Handlers.Auth.Login(
indexR
)where
import qualified Data.Text as T
import qualified Data.Text.Lazy as LT
import qualified Data.ByteString.Char8 as C8
import Data.Either
import Data.Maybe
import Control.Monad.Trans.Class (MonadTrans, lift)
import Control.Monad.Reader (MonadReader(..),asks)
import qualified Web.Scotty.Trans as Web
import Network.HTTP.Types.Status
import Network.OAuth.OAuth2
import URI.ByteString
import qualified Network.URI as URI
import App.Types
import Utils.URI.String
import Utils.URI.Params
import Utils.Extra.EitherMaybe
import Handlers.Actions.Common
import Models.Schemas
import qualified Models.DB as DB
githubKey :: URI.URI -> GithubConf -> OAuth2
githubKey url g =
let
callback = eitherToMaybe $ parseURI strictURIParserOptions $ C8.pack $ show $ url
authEndpoint = fromJust $ eitherToMaybe $ parseURI strictURIParserOptions "https://github.com/login/oauth/authorize"
tokenEndpoint = fromJust $ eitherToMaybe $ parseURI strictURIParserOptions "https://github.com/login/oauth/access_token"
in
OAuth2 { oauthClientId = T.pack $ githubClientID g
, oauthClientSecret = T.pack $ githubClientSecret g
, oauthCallback = callback
, oauthOAuthorizeEndpoint = authEndpoint
, oauthAccessTokenEndpoint = tokenEndpoint
}
indexProcessor req = do
g <- lift $ asks github
s <- lift $ asks site
let callbackURL = updateUrlParam "state" (LT.unpack req)
$ URI.relativeTo (toURI "/auth/callback") (toURI $ siteHost s)
let oauth = githubKey callbackURL g
let authURL = LT.pack $ C8.unpack $ serializeURIRef' $ authorizationUrl oauth
return (status302,authURL)
authUser req = do
Web.rescue (withAuthorization toRoot req) catcher
where
catcher (Exception status401 _ ) = indexProcessor req
catcher e = Web.raise e
toRoot u r = do
user <- preloadUser u
if isNothing user
then indexProcessor req
else return (status302,req)
indexR :: Response ()
indexR = do
req <- Web.param "_r" `Web.rescue` (\e -> return "/")
view $ authUser req
|
DavidAlphaFox/sblog
|
src/Handlers/Auth/Login.hs
|
bsd-3-clause
| 2,183
| 0
| 14
| 423
| 604
| 328
| 276
| 55
| 3
|
{-# LANGUAGE TemplateHaskell #-}
module Kiosk.Backend.DataSpec (main, spec, testGenerateDataTemplate, encodeDecodeHashTests) where
import Control.Applicative ((<$>))
import Control.Arrow ((***))
import Data.Aeson (Value (..), decode,
eitherDecode, encode, toJSON)
import Data.ByteString.Lazy.Internal (ByteString)
import qualified Data.HashMap.Strict as HM
import Data.List (sort)
import Data.Text (Text)
import Generators (GeneratorType (..), checkStaticGeneratorConsistency,
generateDataTemplateEntry,
generateForm)
import Kiosk.Backend.Data (DataTemplateEntry (..))
import Kiosk.Backend.Data.DataTemplate (DataTemplate (..),
fitDataTemplateToForm,
fromFormToDataTemplate,
fromJSONToDataTemplate)
import Kiosk.Backend.Form
import Language.Haskell.TH
import Test.Hspec
import Test.QuickCheck
import TestImport (testJSON)
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe (nameBase 'fromFormToDataTemplate) $
it "should transform a Actual Onping Form to a DataTemplate" $ do
let
forms = [defaultForm]
dataTemplates = fromFormToDataTemplate <$> forms
isEmpty = null dataTemplates
isEmpty `shouldBe` False
describe (nameBase ''DataTemplate ++ " Dynamic Aeson Serialization Test") $
it "should serialize data and be consistent for multiple inputs" $ do
(tst,expected) <- encodeDecodeDataTemplate
let (tst_items,expected_items) = ((fmap.fmap $ templateItems) *** (fmap.fmap $ templateItems )) (tst,expected)
(sort.concat <$> tst_items) `shouldBe` (sort.concat <$> expected_items)
tst `shouldBe` expected
describe (nameBase 'fromJSONToDataTemplate ++ " IPAD Serialization Test") $
it "check to make sure IPAD serialization matches ours" $ do
let
(Right result) = testJSONIpadEncoding
recodedJSON = encode result
decodeToValue recodedJSON `shouldBe` decodeToValue testJSON
describe (nameBase 'fitDataTemplateToForm) $ do
it "Should match a form with a DataTemplate and try and fix the types" $ do
forms <- generate . generateForm $ Static
let templatesFromForm = fromFormToDataTemplate <$> (take 500 forms)
(Just decodedTemplates) = decode . encode $ templatesFromForm
(newDTs) = zipWith fitDataTemplateToForm forms decodedTemplates
(newDTs) `shouldBe` templatesFromForm
encodeDecodeDataTemplate :: IO (Either String [DataTemplate],Either String [DataTemplate])
encodeDecodeDataTemplate = do
forms <- generate.generateForm $ Static
let
makeDataTemplates :: [Form] -> [DataTemplate]
makeDataTemplates restrictedForms = fromFormToDataTemplate <$>
take 1 restrictedForms
tst = eitherDecode . encode . makeDataTemplates $ forms
return (tst,Right . makeDataTemplates $ forms)
encodeDecodeDataTemplateEntry :: IO (Either String [DataTemplateEntry],Either String [DataTemplateEntry])
encodeDecodeDataTemplateEntry = do
entries <- fmap (take 1) . generate $ generateDataTemplateEntry Static
let tst = eitherDecode . encode $ entries
return (tst, Right entries)
encodeDecodeHashTests :: IO [(Text, Value)]
encodeDecodeHashTests = do
entries <- fmap (take 1) . generate $ generateDataTemplateEntry Static
let (Object tst) = toJSON.head $ entries
return $ HM.foldlWithKey' listSequenceCheck [] tst
where
listSequenceCheck lst k v = (k,v):lst
testJSONIpadEncoding :: Either String DataTemplate
testJSONIpadEncoding = fromJSONToDataTemplate testJSON
decodeToValue :: ByteString -> Maybe Value
decodeToValue v = decode v :: Maybe Value
testGenerateDataTemplate :: IO ByteString
testGenerateDataTemplate = do
_forms <- generate.generateForm $ Static
let
forms = [defaultForm]
dataTemplates = fromFormToDataTemplate <$> forms
return . encode $ dataTemplates
-- | Tests to fix later concerning problems with hashing
spec' :: Spec
spec' = do
describe (nameBase 'checkStaticGeneratorConsistency) $
it "should check that the generative tests hold equivalence for static cases" $
property $ checkStaticGeneratorConsistency
describe (nameBase ''DataTemplateEntry ++ " Dynamic Aeson Test") $
it "should show that serialization works for lots of tests" $ do
(tst,expected) <- encodeDecodeDataTemplateEntry
tst `shouldBe` expected
|
plow-technologies/cobalt-kiosk-data-template
|
test/Kiosk/Backend/DataSpec.hs
|
bsd-3-clause
| 4,941
| 0
| 18
| 1,403
| 1,123
| 594
| 529
| 93
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.