code
stringlengths 5
1.03M
| repo_name
stringlengths 5
90
| path
stringlengths 4
158
| license
stringclasses 15
values | size
int64 5
1.03M
| n_ast_errors
int64 0
53.9k
| ast_max_depth
int64 2
4.17k
| n_whitespaces
int64 0
365k
| n_ast_nodes
int64 3
317k
| n_ast_terminals
int64 1
171k
| n_ast_nonterminals
int64 1
146k
| loc
int64 -1
37.3k
| cycloplexity
int64 -1
1.31k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# LANGUAGE LambdaCase, TupleSections, BangPatterns #-}
module Reducer.Base where
import Data.IntMap.Strict (IntMap)
import Data.Map (Map)
import Grin.Grin
import Grin.Pretty
import Text.PrettyPrint.ANSI.Leijen
import qualified Data.Map as Map
import qualified Data.IntMap.Strict as IntMap
-- models cpu registers
type Env = Map Name RTVal
type SimpleRTVal = RTVal
data RTVal
= RT_ConstTagNode Tag [SimpleRTVal]
| RT_VarTagNode Name [SimpleRTVal]
| RT_ValTag Tag
| RT_Unit
| RT_Lit Lit
| RT_Var Name
| RT_Loc Int
| RT_Undefined
deriving (Show, Eq, Ord)
instance Pretty RTVal where
pretty = \case
RT_ConstTagNode tag args -> parens $ hsep (pretty tag : map pretty args)
RT_VarTagNode name args -> parens $ hsep (pretty name : map pretty args)
RT_ValTag tag -> pretty tag
RT_Unit -> parens empty
RT_Lit lit -> pretty lit
RT_Var name -> pretty name
RT_Loc a -> keyword "loc" <+> int a
RT_Undefined -> keyword "undefined"
data Statistics
= Statistics
{ storeFetched :: !(IntMap Int)
, storeUpdated :: !(IntMap Int)
}
emptyStatistics = Statistics mempty mempty
instance Pretty Statistics where
pretty (Statistics f u) =
vsep
[ text "Fetched:"
, indent 4 $ prettyKeyValue $ IntMap.toList $ IntMap.filter (>0) f
, text "Updated:"
, indent 4 $ prettyKeyValue $ IntMap.toList $ IntMap.filter (>0) u
]
keyword :: String -> Doc
keyword = yellow . text
selectNodeItem :: Maybe Int -> RTVal -> RTVal
selectNodeItem Nothing val = val
selectNodeItem (Just 0) (RT_ConstTagNode tag args) = RT_ValTag tag
selectNodeItem (Just i) (RT_ConstTagNode tag args) = args !! (i - 1)
bindPatMany :: Env -> [RTVal] -> [LPat] -> Env
bindPatMany env [] [] = env
bindPatMany env (val : vals) (lpat : lpats) = bindPatMany (bindPat env val lpat) vals lpats
bindPatMany env [] (lpat : lpats) = bindPatMany (bindPat env RT_Undefined lpat) [] lpats
bindPatMany _ vals lpats = error $ "bindPatMany - pattern mismatch: " ++ show (vals, lpats)
bindPat :: Env -> RTVal -> LPat -> Env
bindPat env !val lpat = case lpat of
Var n -> case val of
RT_Unit -> Map.insert n val env
RT_Lit{} -> Map.insert n val env
RT_Loc{} -> Map.insert n val env
RT_Undefined -> Map.insert n val env
RT_ConstTagNode{} -> Map.insert n val env
_ -> error $ "bindPat - illegal value: " ++ show val
ConstTagNode ptag pargs -> case val of
RT_ConstTagNode vtag vargs | ptag == vtag -> bindPatMany env vargs pargs
_ -> error $ "bindPat - illegal value for ConstTagNode: " ++ show val ++ " vs " ++ show (ConstTagNode ptag pargs)
VarTagNode varname pargs -> case val of
RT_ConstTagNode vtag vargs -> bindPatMany (Map.insert varname (RT_ValTag vtag) env) vargs pargs
_ -> error $ "bindPat - illegal value for ConstTagNode: " ++ show val
Unit -> env
_ -> error $ "bindPat - pattern mismatch" ++ show (val,lpat)
lookupEnv :: Name -> Env -> RTVal
lookupEnv n env = Map.findWithDefault (error $ "missing variable: " ++ unpackName n) n env
evalVal :: Env -> Val -> RTVal
evalVal env = \case
Lit lit -> RT_Lit lit
Var n -> lookupEnv n env
ConstTagNode t a -> RT_ConstTagNode t $ map (evalVal env) a
VarTagNode n a -> case lookupEnv n env of
RT_Var n -> RT_VarTagNode n $ map (evalVal env) a
RT_ValTag t -> RT_ConstTagNode t $ map (evalVal env) a
x -> error $ "evalVal - invalid VarTagNode tag: " ++ show x
ValTag tag -> RT_ValTag tag
Unit -> RT_Unit
Undefined t -> RT_Undefined
x -> error $ "evalVal: " ++ show x
| andorp/grin | grin/src/Reducer/Base.hs | bsd-3-clause | 3,775 | 0 | 15 | 1,016 | 1,288 | 642 | 646 | 90 | 12 |
{-# LANGUAGE GeneralizedNewtypeDeriving
, FlexibleInstances
, ScopedTypeVariables
, MultiParamTypeClasses
, UndecidableInstances
, TypeFamilies
, GeneralizedNewtypeDeriving
, Rank2Types
, StandaloneDeriving
#-}
module DB.Flex.Monad where
import Control.Applicative
import Control.Exception
import qualified Control.Monad.CatchIO as C
import Control.Monad.Cont
import Control.Monad.Error
import Control.Monad.RWS
import Control.Monad.Reader
import Database.HDBC hiding (execute)
import qualified Database.HDBC as HDBC
newtype DbT m a = DbT { unDbT :: ReaderT ConnWrapper m a }
deriving (Functor, Applicative, Monad, MonadReader ConnWrapper, MonadFix, C.MonadCatchIO, MonadPlus, MonadIO, Alternative)
class (Functor m, MonadIO m) => DbMonad m where
askConn :: m ConnWrapper
instance (Functor m, MonadIO m) => DbMonad (DbT m) where askConn = ask
instance (Error e, DbMonad m) => DbMonad (ErrorT e m) where askConn = lift askConn
instance DbMonad m => DbMonad (ReaderT d m) where askConn = lift askConn
runDb_ :: (MonadIO m, HDBC.IConnection c) => c -> DbT m a -> m a
runDb_ conn (DbT db) =
do res <- runReaderT db (ConnWrapper conn)
liftIO $ commit conn
return res
runDbIO_ :: HDBC.IConnection c => c -> DbT IO a -> IO a
runDbIO_ conn db =
do res <- runDb_ conn db `onException` rollback conn
commit conn
return res
maxDbTries :: Int
maxDbTries = 3
catchRecoverableExceptions :: IO a -> (SomeException -> IO a) -> IO a
catchRecoverableExceptions action handler = action `catches`
[ Handler $ \(e :: AsyncException) -> throwIO e
, Handler $ \(e :: BlockedIndefinitelyOnSTM) -> throwIO e
, Handler $ \(e :: BlockedIndefinitelyOnMVar) -> throwIO e
, Handler $ \(e :: Deadlock) -> throwIO e
, Handler $ \(e :: SomeException) -> handler e
]
unsafeIOToDb :: DbMonad m => IO a -> m a
unsafeIOToDb = liftIO
runSql :: DbMonad m => String -> [SqlValue] -> m Integer
runSql q ps =
do conn <- askConn
unsafeIOToDb $ run conn q ps
runSql_ :: DbMonad m => String -> [SqlValue] -> m ()
runSql_ q ps = () <$ runSql q ps
querySql :: DbMonad m => String -> [SqlValue] -> m [[SqlValue]]
querySql q ps =
do conn <- askConn
unsafeIOToDb $ quickQuery' conn q ps
prepareSql :: DbMonad m => String -> m Statement
prepareSql q =
do conn <- askConn
unsafeIOToDb $ prepare conn q
execute :: DbMonad m => Statement -> [SqlValue] -> m Integer
execute q = unsafeIOToDb . HDBC.execute q
executeMany :: DbMonad m => Statement -> [[SqlValue]] -> m ()
executeMany q = unsafeIOToDb . HDBC.executeMany q
fetchRow :: DbMonad m => Statement -> m (Maybe [SqlValue])
fetchRow = unsafeIOToDb . HDBC.fetchRow
executeBatch :: DbMonad m => String -> [[SqlValue]] -> m [[[SqlValue]]]
executeBatch q vs =
do st <- prepareSql q
forM vs $ \v ->
do _ <- execute st v
unsafeIOToDb $ fetchAllRows st
| craffit/flexdb | src/DB/Flex/Monad.hs | bsd-3-clause | 2,990 | 0 | 12 | 695 | 1,064 | 543 | 521 | 73 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module TestTagCompleter where
import Control.Monad (when)
import Control.Applicative ((<$>))
import Data.Aeson
import qualified Data.Text as T
import Data.Char
import Data.Aeson.Types
import Data.Either
import Data.HashMap.Lazy (fromList)
import Data.Maybe
import qualified Data.Vector as V
import Tagger.Types
import Tagger.TagCompleter
import TestUtils
import Test.Framework.Providers.HUnit
import Test.Framework.Providers.QuickCheck2
import Test.HUnit
import Test.QuickCheck
tests = [ testCase "completeTrack" completeTrack
, testCase "completeAlbum" completeAlbum
, testCase "completeAll" completeAll
, testCase "callService" callService
, testCase "parseAlbum" parseAlbum
, testCase "parseDate" test_parse_date
, testProperty "uppercase" prop_first_upper
, testProperty "preserve_tail" prop_preserve_tail
, testProperty "zip_tracks_preserve_location" prop_tracks_preserve_location
, testProperty "zip_tracks_preserve_file" prop_tracks_preserve_file
, testProperty "zip_tracks_prefer_first" prop_tracks_prefer_first
, testProperty "zip_albums_prefer_first" prop_albs_prefer_first
, testProperty "zip_albums_zip_tracks" prop_albs_zip_tracks
]
prop_first_upper xs = not (null xs) && isAlpha (head xs) ==>
isUpper . head . capitalize $ xs
prop_preserve_tail xs = not (null xs) ==> tail (capitalize xs) == tail xs
prop_tracks_preserve_file a b = let c = addTTags a b in file c == file a
prop_tracks_preserve_location a b = let c = addTTags a b
in location c == location a
prop_tracks_prefer_first a b = let c = addTTags a b in and
[ if isJust (name a) then name c == name a else name c == name b
, if isJust (rank a) then rank c == rank a else rank c == rank b ]
prop_albs_prefer_first a b = let c = addATags a b in and
[ if isJust (albRelease a)
then albRelease c == albRelease a
else albRelease c == albRelease b
, if isJust (albGenre a)
then albGenre c == albGenre a
else albGenre c == albGenre b ]
prop_albs_zip_tracks a b =
let c = addATags a b in albTracks c == combined (albTracks a) (albTracks b)
where combined [] _ = []
combined _ [] = []
combined (a:as) (b:bs) = addTTags a b : combined as bs
test_parse_date = do
parseDate "Sat, 19 Dec 2009 03:15:17 +0000" @?= 2009
parseDate "Wed, 20 Sep 1999 04:25:37 +0000" @?= 1999
completeTrack = let track = Track "file" "loc" Nothing Nothing
album = Album "Nihility" [track] (Just 2007) (Just "Death Metal")
artist = Artist "Decapitated" [album]
in do (errs, res) <- partitionEithers <$> complete [artist]
length errs @?= 0
length res @?= 1
let dec = head res
artName dec @?= "Decapitated"
let nih = head $ filter (\a -> albName a == "Nihility") (artAlbs dec)
albName nih @?= "Nihility"
albRelease nih @?= Just 2007
albGenre nih @?= Just "Death Metal"
let tracks = albTracks nih
length tracks @?= 1
let t1 = head tracks
location t1 @?= "loc"
file t1 @?= "file"
name t1 @?= Just "Perfect Dehumanisation (The Answer)"
rank t1 @?= Just 1
completeAlbum = let track = Track "file" "loc" (Just "Perfect Dehumanisation") (Just 1)
album = Album "Nihility" [track] Nothing Nothing
artist = Artist "Decapitated" [album]
in do (errs, res) <- partitionEithers <$> complete [artist]
length errs @?= 0
length res @?= 1
let dec = head res
artName dec @?= "Decapitated"
let nih = head $ filter (\a -> albName a == "Nihility") (artAlbs dec)
albName nih @?= "Nihility"
albRelease nih @?= Just 2007
albGenre nih @?= Just "Death Metal"
let tracks = albTracks nih
length tracks @?= 1
let t1 = head tracks
location t1 @?= "loc"
file t1 @?= "file"
name t1 @?= Just "Perfect Dehumanisation"
rank t1 @?= Just 1
completeAll = let track = Track "file" "loc" Nothing Nothing
album = Album "Nihility" [track] Nothing Nothing
artist = Artist "Decapitated" [album]
in do (errs, res) <- partitionEithers <$> complete [artist]
length errs @?= 0
length res @?= 1
let dec = head res
artName dec @?= "Decapitated"
let nih = head $ filter (\a -> albName a == "Nihility") (artAlbs dec)
albName nih @?= "Nihility"
albRelease nih @?= Just 2007
albGenre nih @?= Just "Death Metal"
let tracks = albTracks nih
length tracks @?= 1
let t1 = head tracks
location t1 @?= "loc"
file t1 @?= "file"
name t1 @?= Just "Perfect Dehumanisation (The Answer)"
rank t1 @?= Just 1
callService = let artist = Artist "Immortal" [album]
album = Album "At the Heart of Winter" [] Nothing Nothing
in do res <- query "Immortal" "At the Heart of Winter"
when (isLeft res) (assertFailure "no response from service")
let alb = fromRight res
length (albTracks alb) @?= 6
albRelease alb @?= Just 2007
albGenre alb @?= Just "Black Metal"
let t1 = head $ albTracks alb
name t1 @?= Just "Withstand the Fall of Time"
rank t1 @?= Just 1
let t6 = (albTracks alb) !! 5
name t6 @?= Just "Years of Silent Sorrow"
rank t6 @?= Just 6
parseAlbum = do let rlalb = parseEither parseJSON last_album
when (isLeft rlalb) (assertFailure $ fromLeft rlalb)
let alb = fromRight rlalb
albName alb @?= "Descend Into Depravity"
albRelease alb @?= Just 2009
albGenre alb @?= Just "Death Metal"
length (albTracks alb) @?= 2
let t1 = head (albTracks alb)
name t1 @?= Just "Your Treachery Will Die With You"
rank t1 @?= Just 1
let t2 = (albTracks alb) !! 1
name t2 @?= Just "Ethos of Coercion"
rank t2 @?= Just 8
isLeft (Left _ ) = True
isLeft _ = False
fromLeft (Left x) = x
fromRight (Right x) = x
last_tracks :: Value
last_tracks = Array (V.fromList [Object $ fromList [
("name",String "Your Treachery Will Die With You")
,("url",String "http://www.last.fm/music/Dying+Fetus/_/Your+Treachery+Will+Die+WIth+You")
,("artist",Object (fromList [ ("name",String "Dying Fetus") , ("url",String "http://www.last.fm/") , ("mbid",String "f76167bb-c117-4022-8b6b-54c796edf5c9") ]))
,("mbid",String "68e9067d-1da5-45d6-a76d-d1d609af6dff")
,("@attr",Object (fromList [ ("rank",String "1") ]))
,("duration",String "214")
,("streamable",Object (fromList [ ("#text",String "1") , ("fulltrack",String "1")]))]
,Object $ fromList [
("name",String "Ethos of Coercion")
,("url",String "http://www.last.fm/music/Dying+Fetus/_/Ethos+of+Coercion")
,("artist",Object $ fromList [ ("name",String "Dying Fetus") ,("url",String "http://www.lying+Fetus") ,("mbid",String "f76167bb-c117-4022-8b6b-54c796edf5c9")])
,("mbid",String "1dd30bea-e8f6-4767-9c12-250a3549caf9")
,("@attr",Object $ fromList [ ("rank",String "8")])
,("duration",String "196")
,("streamable",Object $ fromList [ ("#text",String "1") ,("fulltrack",String "1")])]])
last_album :: Value
last_album = Object $ fromList [
("album",Object $ fromList [
("wiki",Object $ fromList [
("published",String "Sat, 19 Dec 2009 03:15:17 +0000")
,("summary",String "Descend into Depravity is the sixth studio album by class=\"bbcode_artist\">Dying Fetus</a>, released on September 15, 2009.")
,("content",String "<strong><em>Descend into Depravity</em></strong> is the sixth studio album by SA License and may also be available under the GNU FDL.")
])
,("playcount",String "649071")
,("name",String "Descend Into Depravity")
,("url",String "http://www.last.fm/music/Dying+Fetus/Descend+Into+Depravity")
,("artist",String "Dying Fetus")
,("tracks", Object $ fromList [ ("track",last_tracks) ])
,("mbid",String "4aa2f613-0478-44ba-aa35-28230a3e2456")
,("id",String "77974816")
,("listeners",String "37944")
,("image",Array (V.fromList [
Object $ fromList [("size",String "small") ,("#text",String "http://userserve-ak.last.fm/serve/34s/63608935.png")]
,Object $ fromList [("size",String "medium") ,("#text",String "http://userserve-ak.last.fm/serve/64s/63608935.png")]
,Object $ fromList [("size",String "large") ,("#text",String "http://userserve-ak.last.fm/serve/174s/63608935.png")]
,Object $ fromList [("size",String "extralarge") ,("#text",String "http://userserve-ak.last.fm/serve/300x300/63608935.png")]
,Object $ fromList [("size",String "mega") ,("#text",String "http://userserve-ak.last.fm/serve/_/63608935/Descend+Into+Depravity+High+quality+PNG.png")]]))
,("releasedate",String " 15 Sep 2009, 00:00")
,("toptags",Object $ fromList [
("tag",Array (V.fromList [
Object $ fromList [
("name",String "death metal")
,("url",String "http://www.last.fm/tag/death%20metal")]
,Object $ fromList [
("name",String "brutal death metal")
,("url",String "http://www.last.fm/tag/brutal%20death%20metal")]
,Object $ fromList [
("name",String "technical death metal")
,("url",String "http://www.last.fm/tag/technical%20death%20metal")]
,Object $ fromList [
("name",String "2009")
,("url",String "http://www.last.fm/tag/2009")]
,Object $ fromList [("name",String "metal"),("url",String "http://www.last.fm/tag/metal")]]))])
])]
| rethab/tagger | test/TestTagCompleter.hs | bsd-3-clause | 11,154 | 0 | 25 | 3,754 | 3,035 | 1,509 | 1,526 | -1 | -1 |
{-# LANGUAGE CPP #-}
-- ---------------------------------------------------------------------------
-- |
-- Module : Data.Vector.Algorithms.Optimal
-- Copyright : (c) 2008-2010 Dan Doel
-- Maintainer : Dan Doel
-- Stability : Experimental
-- Portability : Portable
--
-- Optimal sorts for very small array sizes, or for small numbers of
-- particular indices in a larger array (to be used, for instance, for
-- sorting a median of 3 values into the lowest position in an array
-- for a median-of-3 quicksort).
-- The code herein was adapted from a C algorithm for optimal sorts
-- of small arrays. The original code was produced for the article
-- /Sorting Revisited/ by Paul Hsieh, available here:
--
-- http://www.azillionmonkeys.com/qed/sort.html
--
-- The LICENSE file contains the relevant copyright information for
-- the reference C code.
module Data.Vector.Algorithms.Optimal
( sort2ByIndex
, sort2ByOffset
, sort3ByIndex
, sort3ByOffset
, sort4ByIndex
, sort4ByOffset
, Comparison
) where
import Prelude hiding (read, length)
import Control.Monad.Primitive
import Data.Vector.Generic.Mutable
import Data.Vector.Algorithms.Common (Comparison)
#include "vector.h"
-- | Sorts the elements at the positions 'off' and 'off + 1' in the given
-- array using the comparison.
sort2ByOffset :: (PrimMonad m, MVector v e)
=> Comparison e -> v (PrimState m) e -> Int -> m ()
sort2ByOffset cmp a off = sort2ByIndex cmp a off (off + 1)
{-# INLINABLE sort2ByOffset #-}
-- | Sorts the elements at the two given indices using the comparison. This
-- is essentially a compare-and-swap, although the first index is assumed to
-- be the 'lower' of the two.
sort2ByIndex :: (PrimMonad m, MVector v e)
=> Comparison e -> v (PrimState m) e -> Int -> Int -> m ()
sort2ByIndex cmp a i j = UNSAFE_CHECK(checkIndex) "sort2ByIndex" i (length a)
$ UNSAFE_CHECK(checkIndex) "sort2ByIndex" j (length a) $ do
a0 <- unsafeRead a i
a1 <- unsafeRead a j
case cmp a0 a1 of
GT -> unsafeWrite a i a1 >> unsafeWrite a j a0
_ -> return ()
{-# INLINABLE sort2ByIndex #-}
-- | Sorts the three elements starting at the given offset in the array.
sort3ByOffset :: (PrimMonad m, MVector v e)
=> Comparison e -> v (PrimState m) e -> Int -> m ()
sort3ByOffset cmp a off = sort3ByIndex cmp a off (off + 1) (off + 2)
{-# INLINABLE sort3ByOffset #-}
-- | Sorts the elements at the three given indices. The indices are assumed
-- to be given from lowest to highest, so if 'l < m < u' then
-- 'sort3ByIndex cmp a m l u' essentially sorts the median of three into the
-- lowest position in the array.
sort3ByIndex :: (PrimMonad m, MVector v e)
=> Comparison e -> v (PrimState m) e -> Int -> Int -> Int -> m ()
sort3ByIndex cmp a i j k = UNSAFE_CHECK(checkIndex) "sort3ByIndex" i (length a)
$ UNSAFE_CHECK(checkIndex) "sort3ByIndex" j (length a)
$ UNSAFE_CHECK(checkIndex) "sort3ByIndex" k (length a) $ do
a0 <- unsafeRead a i
a1 <- unsafeRead a j
a2 <- unsafeRead a k
case cmp a0 a1 of
GT -> case cmp a0 a2 of
GT -> case cmp a2 a1 of
LT -> do unsafeWrite a i a2
unsafeWrite a k a0
_ -> do unsafeWrite a i a1
unsafeWrite a j a2
unsafeWrite a k a0
_ -> do unsafeWrite a i a1
unsafeWrite a j a0
_ -> case cmp a1 a2 of
GT -> case cmp a0 a2 of
GT -> do unsafeWrite a i a2
unsafeWrite a j a0
unsafeWrite a k a1
_ -> do unsafeWrite a j a2
unsafeWrite a k a1
_ -> return ()
{-# INLINABLE sort3ByIndex #-}
-- | Sorts the four elements beginning at the offset.
sort4ByOffset :: (PrimMonad m, MVector v e)
=> Comparison e -> v (PrimState m) e -> Int -> m ()
sort4ByOffset cmp a off = sort4ByIndex cmp a off (off + 1) (off + 2) (off + 3)
{-# INLINABLE sort4ByOffset #-}
-- The horror...
-- | Sorts the elements at the four given indices. Like the 2 and 3 element
-- versions, this assumes that the indices are given in increasing order, so
-- it can be used to sort medians into particular positions and so on.
sort4ByIndex :: (PrimMonad m, MVector v e)
=> Comparison e -> v (PrimState m) e -> Int -> Int -> Int -> Int -> m ()
sort4ByIndex cmp a i j k l = UNSAFE_CHECK(checkIndex) "sort4ByIndex" i (length a)
$ UNSAFE_CHECK(checkIndex) "sort4ByIndex" j (length a)
$ UNSAFE_CHECK(checkIndex) "sort4ByIndex" k (length a)
$ UNSAFE_CHECK(checkIndex) "sort4ByIndex" l (length a) $ do
a0 <- unsafeRead a i
a1 <- unsafeRead a j
a2 <- unsafeRead a k
a3 <- unsafeRead a l
case cmp a0 a1 of
GT -> case cmp a0 a2 of
GT -> case cmp a1 a2 of
GT -> case cmp a1 a3 of
GT -> case cmp a2 a3 of
GT -> do unsafeWrite a i a3
unsafeWrite a j a2
unsafeWrite a k a1
unsafeWrite a l a0
_ -> do unsafeWrite a i a2
unsafeWrite a j a3
unsafeWrite a k a1
unsafeWrite a l a0
_ -> case cmp a0 a3 of
GT -> do unsafeWrite a i a2
unsafeWrite a j a1
unsafeWrite a k a3
unsafeWrite a l a0
_ -> do unsafeWrite a i a2
unsafeWrite a j a1
unsafeWrite a k a0
unsafeWrite a l a3
_ -> case cmp a2 a3 of
GT -> case cmp a1 a3 of
GT -> do unsafeWrite a i a3
unsafeWrite a j a1
unsafeWrite a k a2
unsafeWrite a l a0
_ -> do unsafeWrite a i a1
unsafeWrite a j a3
unsafeWrite a k a2
unsafeWrite a l a0
_ -> case cmp a0 a3 of
GT -> do unsafeWrite a i a1
unsafeWrite a j a2
unsafeWrite a k a3
unsafeWrite a l a0
_ -> do unsafeWrite a i a1
unsafeWrite a j a2
unsafeWrite a k a0
-- unsafeWrite a l a3
_ -> case cmp a0 a3 of
GT -> case cmp a1 a3 of
GT -> do unsafeWrite a i a3
-- unsafeWrite a j a1
unsafeWrite a k a0
unsafeWrite a l a2
_ -> do unsafeWrite a i a1
unsafeWrite a j a3
unsafeWrite a k a0
unsafeWrite a l a2
_ -> case cmp a2 a3 of
GT -> do unsafeWrite a i a1
unsafeWrite a j a0
unsafeWrite a k a3
unsafeWrite a l a2
_ -> do unsafeWrite a i a1
unsafeWrite a j a0
-- unsafeWrite a k a2
-- unsafeWrite a l a3
_ -> case cmp a1 a2 of
GT -> case cmp a0 a2 of
GT -> case cmp a0 a3 of
GT -> case cmp a2 a3 of
GT -> do unsafeWrite a i a3
unsafeWrite a j a2
unsafeWrite a k a0
unsafeWrite a l a1
_ -> do unsafeWrite a i a2
unsafeWrite a j a3
unsafeWrite a k a0
unsafeWrite a l a1
_ -> case cmp a1 a3 of
GT -> do unsafeWrite a i a2
unsafeWrite a j a0
unsafeWrite a k a3
unsafeWrite a l a1
_ -> do unsafeWrite a i a2
unsafeWrite a j a0
unsafeWrite a k a1
-- unsafeWrite a l a3
_ -> case cmp a2 a3 of
GT -> case cmp a0 a3 of
GT -> do unsafeWrite a i a3
unsafeWrite a j a0
-- unsafeWrite a k a2
unsafeWrite a l a1
_ -> do -- unsafeWrite a i a0
unsafeWrite a j a3
-- unsafeWrite a k a2
unsafeWrite a l a1
_ -> case cmp a1 a3 of
GT -> do -- unsafeWrite a i a0
unsafeWrite a j a2
unsafeWrite a k a3
unsafeWrite a l a1
_ -> do -- unsafeWrite a i a0
unsafeWrite a j a2
unsafeWrite a k a1
-- unsafeWrite a l a3
_ -> case cmp a1 a3 of
GT -> case cmp a0 a3 of
GT -> do unsafeWrite a i a3
unsafeWrite a j a0
unsafeWrite a k a1
unsafeWrite a l a2
_ -> do -- unsafeWrite a i a0
unsafeWrite a j a3
unsafeWrite a k a1
unsafeWrite a l a2
_ -> case cmp a2 a3 of
GT -> do -- unsafeWrite a i a0
-- unsafeWrite a j a1
unsafeWrite a k a3
unsafeWrite a l a2
_ -> do -- unsafeWrite a i a0
-- unsafeWrite a j a1
-- unsafeWrite a k a2
-- unsafeWrite a l a3
return ()
{-# INLINABLE sort4ByIndex #-}
| tolysz/vector-algorithms | src/Data/Vector/Algorithms/Optimal.hs | bsd-3-clause | 11,982 | 0 | 37 | 6,433 | 2,492 | 1,168 | 1,324 | 175 | 24 |
module Serv.Wai.Error where
import Data.Set (Set)
import Network.HTTP.Kinder.Verb
-- | Errors which arise during the "handling" portion of dealing with a response.
data RoutingError
= NotFound
| BadRequest (Maybe String)
| UnsupportedMediaType
| MethodNotAllowed (Set Verb)
-- | An ignorable error is one which backtracks the routing search
-- instead of forcing a response.
ignorable :: RoutingError -> Bool
ignorable NotFound = True
ignorable _ = False
| tel/serv | serv-wai/src/Serv/Wai/Error.hs | bsd-3-clause | 503 | 0 | 8 | 115 | 84 | 50 | 34 | 11 | 1 |
module Part2.Problem48 where
--
-- Problem 48: Self powers
--
-- The series, 1^1 + 2^2 + 3^3 + ... + 10^10 = 10405071317.
--
-- Find the last ten digits of the series, 1^1 + 2^2 + 3^3 + ... + 1000^1000.
problem48 :: Integer
problem48 = sum [x^x | x <- [1..1000]] `mod` 10^10
| c0deaddict/project-euler | src/Part2/Problem48.hs | bsd-3-clause | 277 | 0 | 11 | 58 | 55 | 34 | 21 | 3 | 1 |
-- | This module implements encoding and decoding
-- of [comma-separated values (CSV)](https://en.wikipedia.org/wiki/Comma-separated_values)
-- data. The implementation is [RFC 4180](https://tools.ietf.org/html/rfc4180)
-- compliant, with the following extensions:
--
-- * Empty lines are ignored.
--
-- * Non-escaped fields may contain any characters except
-- double-quotes, commas, carriage returns, and newlines.
--
-- * Escaped fields may contain any characters (but double-quotes
-- need to be escaped).
module Data.Csv
(
-- * Usage examples
-- $example
-- ** Encoding and decoding custom data types
-- $example-instance
-- *** Index-based record conversion
-- $example-indexed-instance
-- *** Name-based record conversion
-- $example-named-instance
-- * Treating CSV data as opaque byte strings
-- $generic-processing
-- * Custom type conversions for fields
-- $customtypeconversions
-- ** Dealing with bad data
-- $baddata
-- * Encoding and decoding
-- $encoding
HasHeader(..)
, decode
, decodeByName
, encode
, encodeByName
, encodeDefaultOrderedByName
, DefaultOrdered(..)
-- ** Encoding and decoding options
-- $options
, DecodeOptions(..)
, defaultDecodeOptions
, decodeWith
, decodeWithP
, decodeByNameWith
, decodeByNameWithP
, EncodeOptions(..)
, Quoting(..)
, defaultEncodeOptions
, encodeWith
, encodeByNameWith
, encodeDefaultOrderedByNameWith
-- * Core CSV types
, Csv
, Record
, Field
, Header
, Name
, NamedRecord
-- * Type conversion
-- $typeconversion
-- ** Index-based record conversion
-- $indexbased
, FromRecord(..)
, Parser
, runParser
, index
, (.!)
, unsafeIndex
, ToRecord(..)
, record
, Only(..)
-- ** Name-based record conversion
-- $namebased
, FromNamedRecord(..)
, lookup
, (.:)
, ToNamedRecord(..)
, namedRecord
, namedField
, (.=)
, header
-- ** Field conversion
-- $fieldconversion
, FromField(..)
, ToField(..)
-- ** 'Generic' record conversion
-- $genericconversion
, genericParseRecord
, genericToRecord
, genericParseNamedRecord
, genericToNamedRecord
, genericHeaderOrder
-- *** 'Generic' type conversion options
, Options
, defaultOptions
, fieldLabelModifier
-- *** 'Generic' type conversion class name
-- $genericconversionclass
, GFromRecord
, GToRecord
, GFromNamedRecord
, GToNamedRecordHeader
) where
import Prelude hiding (lookup)
import Data.Csv.Conversion
import Data.Csv.Encoding
import Data.Csv.Types
-- $example
--
-- Encoding standard Haskell types:
--
-- >>> :set -XOverloadedStrings
-- >>> import Data.Text (Text)
-- >>> encode [("John" :: Text, 27 :: Int), ("Jane", 28)]
-- "John,27\r\nJane,28\r\n"
--
-- Since we enabled the [-XOverloadedStrings extension](https://downloads.haskell.org/~ghc/8.2.1/docs/html/users_guide/glasgow_exts.html#overloaded-string-literals),
-- string literals are polymorphic and we have to supply a type
-- signature as the compiler couldn't deduce which string type (i.e.
-- 'String', 'Data.Text.Short.ShortText', or 'Data.Text.Text') we want to use. In most cases
-- type inference will infer the type from the context and you can
-- omit type signatures.
--
-- Decoding standard Haskell types:
--
-- >>> import Data.Vector (Vector)
-- >>> decode NoHeader "John,27\r\nJane,28\r\n" :: Either String (Vector (Text, Int))
-- Right [("John",27),("Jane",28)]
--
-- We pass 'NoHeader' as the first argument to indicate that the CSV
-- input data isn't preceded by a header.
--
-- In practice, the return type of 'decode' rarely needs to be given,
-- as it can often be inferred from the context.
-- $example-instance
--
-- To encode and decode your own data types you need to defined
-- instances of either 'ToRecord' and 'FromRecord' or 'ToNamedRecord'
-- and 'FromNamedRecord'. The former is used for encoding/decoding
-- using the column index and the latter using the column name.
--
-- There are two ways to to define these instances, either by manually
-- defining them or by using GHC generics to derive them automatically.
-- $example-indexed-instance
--
-- "GHC.Generics"-derived:
--
-- > {-# LANGUAGE DeriveGeneric #-}
-- >
-- > import Data.Text (Text)
-- > import GHC.Generics (Generic)
-- >
-- > data Person = Person { name :: !Text , salary :: !Int }
-- > deriving (Generic, Show)
-- >
-- > instance FromRecord Person
-- > instance ToRecord Person
--
-- Manually defined:
--
-- > import Control.Monad (mzero)
-- >
-- > data Person = Person { name :: !Text , salary :: !Int }
-- > deriving (Show)
-- >
-- > instance FromRecord Person where
-- > parseRecord v
-- > | length v == 2 = Person <$> v .! 0 <*> v .! 1
-- > | otherwise = mzero
-- > instance ToRecord Person where
-- > toRecord (Person name' age') = record [
-- > toField name', toField age']
--
-- We can now use e.g. 'encode' and 'decode' to encode and decode our
-- data type.
--
-- Encoding:
--
-- >>> encode [Person ("John" :: Text) 27]
-- "John,27\r\n"
--
-- Decoding:
--
-- >>> decode NoHeader "John,27\r\n" :: Either String (Vector Person)
-- Right [Person {name = "John", salary = 27}]
--
-- $example-named-instance
--
-- "GHC.Generics"-derived:
--
-- > {-# LANGUAGE DeriveGeneric #-}
-- >
-- > import Data.Text (Text)
-- > import GHC.Generics (Generic)
-- >
-- > data Person = Person { name :: !Text , salary :: !Int }
-- > deriving (Generic, Show)
-- >
-- > instance FromNamedRecord Person
-- > instance ToNamedRecord Person
-- > instance DefaultOrdered Person
--
-- Manually defined:
--
-- > data Person = Person { name :: !Text , salary :: !Int }
-- > deriving (Show)
-- >
-- > instance FromNamedRecord Person where
-- > parseNamedRecord m = Person <$> m .: "name" <*> m .: "salary"
-- > instance ToNamedRecord Person where
-- > toNamedRecord (Person name salary) = namedRecord [
-- > "name" .= name, "salary" .= salary]
-- > instance DefaultOrdered Person where
-- > headerOrder _ = header ["name", "salary"]
--
-- We can now use e.g. 'encodeDefaultOrderedByName' (or 'encodeByName'
-- with an explicit header order) and 'decodeByName' to encode and
-- decode our data type.
--
-- Encoding:
--
-- >>> encodeDefaultOrderedByName [Person ("John" :: Text) 27]
-- "name,salary\r\nJohn,27\r\n"
--
-- Decoding:
--
-- >>> decodeByName "name,salary\r\nJohn,27\r\n" :: Either String (Header, Vector Person)
-- Right (["name","salary"],[Person {name = "John", salary = 27}])
--
-- $generic-processing
--
-- Sometimes you might want to work with a CSV file which contents is
-- unknown to you. For example, you might want remove the second
-- column of a file without knowing anything about its content. To
-- parse a CSV file to a generic representation, just convert each
-- record to a @'Vector' 'ByteString'@ value, like so:
--
-- >>> import Data.ByteString (ByteString)
-- >>> decode NoHeader "John,27\r\nJane,28\r\n" :: Either String (Vector (Vector ByteString))
-- Right [["John","27"],["Jane","28"]]
--
-- As the example output above shows, all the fields are returned as
-- uninterpreted 'ByteString' values.
-- $customtypeconversions
--
-- Most of the time the existing 'FromField' and 'ToField' instances
-- do what you want. However, if you need to parse a different format
-- (e.g. hex) but use a type (e.g. 'Int') for which there's already a
-- 'FromField' instance, you need to use a @newtype@. Example:
--
-- > newtype Hex = Hex Int
-- >
-- > parseHex :: ByteString -> Parser Int
-- > parseHex = ...
-- >
-- > instance FromField Hex where
-- > parseField s = Hex <$> parseHex s
--
-- Other than giving an explicit type signature, you can pattern match
-- on the @newtype@ constructor to indicate which type conversion you
-- want to have the library use:
--
-- > case decode NoHeader "0xff,0xaa\r\n0x11,0x22\r\n" of
-- > Left err -> putStrLn err
-- > Right v -> forM_ v $ \ (Hex val1, Hex val2) ->
-- > print (val1, val2)
--
-- If a field might be in one several different formats, you can use a
-- newtype to normalize the result:
--
-- > newtype HexOrDecimal = HexOrDecimal Int
-- >
-- > instance FromField DefaultToZero where
-- > parseField s = case runParser (parseField s :: Parser Hex) of
-- > Left err -> HexOrDecimal <$> parseField s -- Uses Int instance
-- > Right n -> pure $ HexOrDecimal n
--
-- You can use the unit type, @()@, to ignore a column. The
-- 'parseField' method for @()@ doesn't look at the 'Field' and thus
-- always decodes successfully. Note that it lacks a corresponding
-- 'ToField' instance. Example:
--
-- > case decode NoHeader "foo,1\r\nbar,22" of
-- > Left err -> putStrLn err
-- > Right v -> forM_ v $ \ ((), i) -> print (i :: Int)
-- $baddata
--
-- If your input might contain invalid fields, you can write a custom
-- 'FromField' instance to deal with them. Example:
--
-- > newtype DefaultToZero = DefaultToZero Int
-- >
-- > instance FromField DefaultToZero where
-- > parseField s = case runParser (parseField s) of
-- > Left err -> pure $ DefaultToZero 0
-- > Right n -> pure $ DefaultToZero n
-- $encoding
--
-- Encoding and decoding is a two step process. To encode a value, it
-- is first converted to a generic representation, using either
-- 'ToRecord' or 'ToNamedRecord'. The generic representation is then
-- encoded as CSV data. To decode a value the process is reversed and
-- either 'FromRecord' or 'FromNamedRecord' is used instead. Both
-- these steps are combined in the 'encode' and 'decode' functions.
-- $typeconversion
--
-- There are two ways to convert CSV records to and from and
-- user-defined data types: index-based conversion and name-based
-- conversion.
-- $indexbased
--
-- Index-based conversion lets you convert CSV records to and from
-- user-defined data types by referring to a field's position (its
-- index) in the record. The first column in a CSV file is given index
-- 0, the second index 1, and so on.
-- $namebased
--
-- Name-based conversion lets you convert CSV records to and from
-- user-defined data types by referring to a field's name. The names
-- of the fields are defined by the first line in the file, also known
-- as the header. Name-based conversion is more robust to changes in
-- the file structure e.g. to reording or addition of columns, but can
-- be a bit slower.
-- $options
--
-- These functions can be used to control how data is encoded and
-- decoded. For example, they can be used to encode data in a
-- tab-separated format instead of in a comma-separated format.
-- $fieldconversion
--
-- The 'FromField' and 'ToField' classes define how to convert between
-- 'Field's and values you care about (e.g. 'Int's). Most of the time
-- you don't need to write your own instances as the standard ones
-- cover most use cases.
-- $genericconversion
--
-- There may be times that you do not want to manually write out class
-- instances for record conversion, but you can't rely upon the
-- default instances (e.g. you can't create field names that match the
-- actual column names in expected data).
--
-- For example, consider you have a type @MyType@ where you have
-- prefixed certain columns with an underscore, but in the actual data
-- they're not. You can then write:
--
-- > myOptions :: Options
-- > myOptions = defaultOptions { fieldLabelModifier = rmUnderscore }
-- > where
-- > rmUnderscore ('_':str) = str
-- > rmUnderscore str = str
-- >
-- > instance ToNamedRecord MyType where
-- > toNamedRecord = genericToNamedRecord myOptions
-- >
-- > instance FromNamedRecord MyType where
-- > parseNamedRecord = genericParseNamedRecord myOptions
-- >
-- > instance DefaultOrdered MyType where
-- > headerOrder = genericHeaderOrder myOptions
-- $genericconversionclass
--
-- __NOTE__: Only the class /names/ are exposed in order to make it possible to write type signatures referring to these classes
-- $setup
-- >>> :set -XOverloadedStrings -XDeriveGeneric
-- >>> import Data.Text (Text)
-- >>> import Data.Vector (Vector)
-- >>> import GHC.Generics (Generic)
-- >>>
-- >>> data Person = Person { name :: !Text, salary :: !Int } deriving (Generic, Show)
-- >>> instance FromRecord Person
-- >>> instance ToRecord Person
-- >>> instance FromNamedRecord Person
-- >>> instance ToNamedRecord Person
-- >>> instance DefaultOrdered Person
| hvr/cassava | src/Data/Csv.hs | bsd-3-clause | 12,598 | 0 | 5 | 2,557 | 568 | 488 | 80 | 62 | 0 |
{-# LANGUAGE BangPatterns #-}
module Main where
import Codec.Archive.Tar as Tar
import Control.Exception (Exception, throwIO)
import Control.Monad.IO.Class
import Control.Monad.State.Lazy (state)
import Data.Foldable
import Data.Map.Lazy as Map
import System.Exit (ExitCode(ExitSuccess))
import System.FilePath
import System.IO
import System.Process (readCreateProcessWithExitCode, shell)
import Z3.Monad as Z3
import qualified Data.Text.Encoding.Error as T
import qualified Data.Text.Lazy as Tl
import qualified Data.Text.Lazy.Encoding as Tl
import Distribution.Compiler
import Distribution.Package
import Distribution.PackageDescription
import Distribution.PackageDescription.Parse
import Distribution.Version
import Development.Hake.Solver
import qualified Data.ByteString.Lazy as Bl
packageTarball :: IO String
packageTarball = do
let cmd = shell "grep remote-repo-cache ~/.cabal/config | awk '{print $2}'"
(ExitSuccess, dirs, _) <- readCreateProcessWithExitCode cmd ""
case lines dirs of
[dir] -> return $ combine dir "hackage.haskell.org/00-index.tar"
_ -> fail "uhm"
foldEntriesM
:: (Exception e, MonadIO m)
=> (a -> Entry -> m a)
-> a
-> Entries e
-> m a
foldEntriesM f = step where
step !s (Next e es) = f s e >>= flip step es
step s Tar.Done = return s
step _ (Fail e) = liftIO $ throwIO e
takeEntries
:: Int
-> Entries e
-> Entries e
takeEntries 0 _ = Tar.Done
takeEntries i (Next e es) = Next e (takeEntries (i-1) es)
takeEntries _ x = x
loadPackageDescriptions
:: Map PackageIdentifier GenericPackageDescription
-> Entry
-> IO (Map PackageIdentifier GenericPackageDescription)
loadPackageDescriptions !agg e
| ".cabal" <- takeExtension (entryPath e)
, NormalFile lbs _fs <- entryContent e
, ParseOk _ gpd <- parsePackageDescription (Tl.unpack (Tl.decodeUtf8With T.ignore lbs)) = do
putChar '.'
hFlush stdout
return $ Map.insert (packageId gpd) gpd agg
| otherwise = do
putChar 'x'
hFlush stdout
return agg
loadGlobalDatabase
:: HakeSolverT Z3 ()
loadGlobalDatabase = do
entries <- liftIO $ Tar.read <$> (Bl.readFile =<< packageTarball)
let entries' = takeEntries 10000 entries
gpdMap <- liftIO $ foldEntriesM loadPackageDescriptions Map.empty entries'
let gpdHakeMap = splitPackageIdentifiers gpdMap
state (\ x -> ((), x{hakeSolverGenDesc = gpdHakeMap}))
query :: Z3 (Result, Maybe String)
query = do
x <- mkFreshBoolVar "x"
assert x
(res, mmodel) <- getModel
case mmodel of
Just model -> do
str <- modelToString model
return (res, Just str)
Nothing -> return (res, Nothing)
main :: IO ()
main = do
env <- Z3.newEnv Nothing stdOpts
st <- execHakeSolverT defaultSolverState env loadGlobalDatabase
let prog = do
setASTPrintMode Z3_PRINT_SMTLIB2_COMPLIANT
ghcFlag <- getGlobalConfVar (Impl GHC anyVersion)
assert ghcFlag
Just x <- getDependency $ Dependency (PackageName "Coroutine") anyVersion
bs <- astToString x
liftIO $ putStrLn bs
_b <- getDependency $ Dependency (PackageName "base") anyVersion
bns <- getDependencyNodes $ Dependency (PackageName "base") anyVersion
b <- getDistinctVersion $ Dependency (PackageName "base") anyVersion
bs <- astToString b
liftIO $ putStrLn bs
assert b
assert x
(res, mmodel) <- getModel
case mmodel of
Just model -> do
-- str <- modelToString model
for_ bns $ \ (pn, bn) -> do
mmev <- evalBool model bn
liftIO $ case mmev of
Just True -> putStrLn $ "Ploz install: " ++ show pn
Just False -> putStrLn $ "Skip: " ++ show pn
Nothing -> putStrLn $ "Undef: " ++ show pn
return (res, Just "")
Nothing -> return (res, Nothing)
(x, _st') <- runLocalHakeSolverT st env prog
case x of
(Sat, Just str) -> do
putStrLn "found model"
putStr str
_ -> print x
| HakeIO/hake-solver | tests/Main.hs | bsd-3-clause | 4,021 | 0 | 26 | 951 | 1,314 | 649 | 665 | 115 | 5 |
-- | Adapter for "System.Console.GetOpt".
module System.Console.CmdTheLine.GetOpt where
import Data.Maybe
import Data.Traversable
import System.Console.GetOpt
import System.Console.CmdTheLine
-- | Sequence a list of @'OptDescr's@ into a term. Absent flags
-- (specified with 'NoArg') are filtered out.
optDescrsTerm :: [OptDescr a] -> Term [a]
optDescrsTerm = fmap catMaybes . sequenceA . map optDescrToTerm
-- | Convert an 'OptDescr' into a 'Term' which returns 'Nothing' if
-- 'NoArg' is specified and the flag is absent or 'Just' the argument
-- otherwise.
optDescrToTerm :: OptDescr a -> Term (Maybe a)
optDescrToTerm (Option shorts longs argDescr descr) =
case argDescr of
NoArg x -> fmap (optional x) $ value $ flag $ optInf ""
ReqArg to name -> fmap (fmap to) $ value $ opt Nothing $ optInf name
OptArg to name -> fmap (Just . to) $ value $ defaultOpt Nothing Nothing $ optInf name
where
optional :: a -> Bool -> Maybe a
optional x present | present = Just x
| otherwise = Nothing
optInf :: String -> OptInfo
optInf name = (optInfo options) { optDoc = descr
, optName = name
}
options :: [String]
options = map (:[]) shorts ++ longs
| glutamate/cmdtheline | src/System/Console/CmdTheLine/GetOpt.hs | mit | 1,359 | 0 | 13 | 410 | 344 | 177 | 167 | 21 | 3 |
{- |
Module : ./CASL/Parse_AS_Basic.hs
Description : Parsing CASL's SIG-ITEMS, BASIC-ITEMS and BASIC-SPEC
Copyright : (c) Christian Maeder, Uni Bremen 2002-2004
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : provisional
Portability : portable
Parser for CASL basic specifications (SIG-ITEMS, BASIC-ITEMS, BASIC-SPEC)
Follows Sect. II:3.1 of the CASL Reference Manual.
-}
{-
http://www.cofi.info/Documents/CASL/Summary/
from 25 March 2001
C.2.1 Basic Specifications with Subsorts
-}
module CASL.Parse_AS_Basic where
import Common.AS_Annotation
import Common.AnnoState
import Common.Id
import Common.Keywords
import Common.Lexer
import Common.GlobalAnnotations (PrefixMap)
import CASL.AS_Basic_CASL
import CASL.Formula
import CASL.SortItem
import CASL.OpItem
import Text.ParserCombinators.Parsec
-- * signature items
sortItems, typeItems, opItems, predItems, sigItems
:: (AParsable s, TermParser f) => [String] -> AParser st (SIG_ITEMS s f)
sortItems ks = itemList ks esortS sortItem (Sort_items PossiblyEmptySorts)
<|> itemList ks sortS sortItem (Sort_items NonEmptySorts)
typeItems ks = itemList ks typeS datatype (Datatype_items NonEmptySorts)
<|> itemList ks etypeS datatype (Datatype_items PossiblyEmptySorts)
opItems ks = itemList ks opS opItem Op_items
predItems ks = itemList ks predS predItem Pred_items
sigItems ks = fmap Ext_SIG_ITEMS aparser <|>
sortItems ks <|> opItems ks <|> predItems ks <|> typeItems ks
-- * helpers
datatypeToFreetype :: (AParsable b, AParsable s, TermParser f) =>
SIG_ITEMS s f -> Range -> BASIC_ITEMS b s f
datatypeToFreetype d pos =
case d of
Datatype_items sk ts ps -> Free_datatype sk ts (pos `appRange` ps)
_ -> error "datatypeToFreetype"
axiomToLocalVarAxioms :: (AParsable b, AParsable s, TermParser f) =>
BASIC_ITEMS b s f -> [Annotation] -> [VAR_DECL] -> Range
-> BASIC_ITEMS b s f
axiomToLocalVarAxioms ai a vs posl =
case ai of
Axiom_items (Annoted ft qs as rs : fs) ds ->
let aft = Annoted ft qs (a ++ as) rs
in Local_var_axioms vs (aft : fs) (posl `appRange` ds)
_ -> error "axiomToLocalVarAxioms"
-- * basic items
basicItems :: (AParsable b, AParsable s, TermParser f) =>
[String] -> AParser st (BASIC_ITEMS b s f)
basicItems ks = fmap Ext_BASIC_ITEMS aparser <|> fmap Sig_items (sigItems ks)
<|> do
f <- asKey freeS
ti <- typeItems ks
return (datatypeToFreetype ti (tokPos f))
<|> do
g <- asKey generatedS
do t <- typeItems ks
return (Sort_gen [Annoted t nullRange [] []] $ tokPos g)
<|> do
o <- oBraceT
is <- annosParser (sigItems ks)
c <- cBraceT
a <- lineAnnos
return (Sort_gen (init is ++ [appendAnno (last is) a])
(toRange g [o] c))
<|> do
v <- pluralKeyword varS
(vs, ps) <- varItems ks
return (Var_items vs (catRange (v : ps)))
<|> do
f <- forallT
(vs, ps) <- varDecls ks
a <- annos
ai <- dotFormulae True ks
return (axiomToLocalVarAxioms ai a vs $ catRange (f : ps))
<|> dotFormulae True ks
<|> itemList ks axiomS formula Axiom_items
varItems :: [String] -> AParser st ([VAR_DECL], [Token])
varItems ks =
do v <- varDecl ks
do s <- trySemiOrComma
do tryItemEnd (ks ++ startKeyword)
return ([v], [s])
<|> do
(vs, ts) <- varItems ks
return (v : vs, s : ts)
<|> return ([v], [])
dotFormulae :: (AParsable b, AParsable s, TermParser f) =>
Bool -> [String] -> AParser st (BASIC_ITEMS b s f)
dotFormulae requireDot ks =
do d <- (if requireDot then id else option $ mkSimpleId ".") dotT
(fs, ds) <- aFormula ks `separatedBy` dotT
(m, an) <- optSemi
let ps = catRange (d : ds)
ns = init fs ++ [appendAnno (last fs) an]
return $ Axiom_items ns (ps `appRange` catRange m)
aFormula :: TermParser f => [String] -> AParser st (Annoted (FORMULA f))
aFormula = allAnnoParser . formula
-- * basic spec
basicSpec :: (TermParser f, AParsable s, AParsable b) =>
[String] -> PrefixMap -> AParser st (BASIC_SPEC b s f)
basicSpec bi _ = (fmap Basic_spec . annosParser . basicItems) bi
| spechub/Hets | CASL/Parse_AS_Basic.hs | gpl-2.0 | 4,310 | 0 | 23 | 1,056 | 1,440 | 720 | 720 | 91 | 2 |
module Paths_carettah where
import Data.Version
getDataFileName :: FilePath -> IO FilePath
getDataFileName = return
version :: Version
version = Version {versionBranch = [0,0,0], versionTags = ["dummy"]}
| uemurax/carettah | data/Paths_carettah.hs | gpl-2.0 | 206 | 0 | 7 | 28 | 62 | 38 | 24 | 6 | 1 |
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Spark.Core.IntegrationUtilities where
import GHC.Generics (Generic)
import Data.Text(Text)
import Data.Aeson(ToJSON)
import Spark.Core.Context
import Spark.Core.Types
import Spark.Core.Row
import Spark.Core.Column
data TestStruct1 = TestStruct1 {
ts1f1 :: Int,
ts1f2 :: Maybe Int } deriving (Show, Eq, Generic)
instance ToSQL TestStruct1
instance FromSQL TestStruct1
instance SQLTypeable TestStruct1
data TestStruct2 = TestStruct2 {
ts2f1 :: [Int]
} deriving (Show, Generic)
instance SQLTypeable TestStruct2
data TestStruct3 = TestStruct3 {
ts3f1 :: Int
} deriving (Show, Eq, Generic)
instance ToSQL TestStruct3
instance SQLTypeable TestStruct3
data TestStruct4 = TestStruct4 {
ts4f1 :: TestStruct3
} deriving (Show, Eq, Generic)
data TestStruct5 = TestStruct5 {
ts5f1 :: Int,
ts5f2 :: Int
} deriving (Show, Eq, Generic, Ord)
-- instance ToJSON TestStruct5
instance SQLTypeable TestStruct5
instance FromSQL TestStruct5
instance ToSQL TestStruct5
data TestStruct6 = TestStruct6 {
ts6f1 :: Int,
ts6f2 :: Int,
ts6f3 :: TestStruct3
} deriving (Show, Eq, Generic)
data TestStruct7 = TestStruct7 {
ts7f1 :: Text
} deriving (Show, Eq, Generic)
instance ToSQL TestStruct7
instance SQLTypeable TestStruct7
instance ToJSON TestStruct7
newtype TestT1 = TestT1 {
unTestT1 :: Int
} deriving (Eq, Show, Generic, Num)
data MyPair = MyPair {
myKey :: Text,
myVal :: Int } deriving (Generic, Show)
myKey' :: StaticColProjection MyPair Text
myKey' = unsafeStaticProjection buildType "myKey"
myVal' :: StaticColProjection MyPair Int
myVal' = unsafeStaticProjection buildType "myVal"
instance SQLTypeable MyPair
instance ToSQL MyPair
| krapsh/kraps-haskell | test-integration/Spark/Core/IntegrationUtilities.hs | apache-2.0 | 1,811 | 0 | 9 | 274 | 508 | 282 | 226 | 60 | 1 |
{-# OPTIONS_GHC -cpp #-}
-----------------------------------------------------------------------------
-- |
-- Module : CabalSetup
-- Copyright : (c) The University of Glasgow 2006
--
-- Maintainer : http://hackage.haskell.org/trac/hackage
-- Stability : alpha
-- Portability : portable
--
-- The user interface to building and installing Cabal packages.
module Main (main) where
import Distribution.Simple
import Distribution.Simple.Utils
import Distribution.Simple.Configure
( configCompiler, getInstalledPackages,
configDependency )
import Distribution.Setup ( reqPathArg )
import Distribution.PackageDescription
( readPackageDescription,
PackageDescription(..) )
import System.Console.GetOpt
import System.Environment
import Control.Monad ( when )
import System.Directory ( doesFileExist )
main = do
args <- getArgs
-- read the .cabal file
-- - attempt to find the version of Cabal required
-- if there's a Setup script,
-- - if we find GHC,
-- - build it with the right version of Cabal
-- - invoke it with args
-- - if we find runhaskell (TODO)
-- - use runhaskell to invoke it
-- otherwise,
-- - behave like a boilerplate Setup.hs
--
-- Later:
-- - add support for multiple packages, by figuring out
-- dependencies here and building/installing the sub packages
-- in the right order.
pkg_descr_file <- defaultPackageDesc
pkg_descr <- readPackageDescription pkg_descr_file
let (flag_fn, non_opts, unrec_opts, errs) = getOpt' Permute opts args
when (not (null errs)) $ die (unlines errs)
let flags = foldr (.) id flag_fn defaultFlags
comp <- configCompiler (Just GHC) (withCompiler flags) (withHcPkg flags) 0
cabal_flag <- configCabalFlag flags (descCabalVersion pkg_descr) comp
let
trySetupScript f on_fail = do
b <- doesFileExist f
if not b then on_fail else do
rawSystemExit (verbose flags)
(compilerPath comp)
(cabal_flag ++
["--make", f, "-o", "setup", "-v"++show (verbose flags)])
rawSystemExit (verbose flags)
('.':pathSeparator:"setup")
args
trySetupScript "Setup.hs" $ do
trySetupScript "Setup.lhs" $ do
trySetupScript ".Setup.hs" $ do
-- Setup.hs doesn't exist, we need to behave like defaultMain
if descCabalVersion pkg_descr == AnyVersion
then defaultMain
-- doesn't matter which version we use, so no need to compile
-- a special Setup.hs.
else do writeFile ".Setup.hs"
"import Distribution.Simple; main=defaultMain"
trySetupScript ".Setup.hs" $ error "panic! shouldn't happen"
data Flags
= Flags {
withCompiler :: Maybe FilePath,
withHcPkg :: Maybe FilePath,
verbose :: Int
}
defaultFlags = Flags {
withCompiler = Nothing,
withHcPkg = Nothing,
verbose = 0
}
setWithCompiler f flags = flags{ withCompiler=f }
setWithHcPkg f flags = flags{ withHcPkg=f }
setVerbose v flags = flags{ verbose=v }
opts :: [OptDescr (Flags -> Flags)]
opts = [
Option "w" ["with-compiler"] (reqPathArg (setWithCompiler.Just))
"give the path to a particular compiler",
Option "" ["with-hc-pkg"] (reqPathArg (setWithHcPkg.Just))
"give the path to the package tool",
Option "v" ["verbose"] (OptArg (setVerbose . maybe 3 read) "n") "Control verbosity (n is 0--5, normal verbosity level is 1, -v alone is equivalent to -v3)"
]
noSetupScript = error "noSetupScript"
configCabalFlag :: Flags -> VersionRange -> Compiler -> IO [String]
configCabalFlag flags AnyVersion _ = return []
configCabalFlag flags range comp = do
ipkgs <- getInstalledPackages comp True (verbose flags)
-- user packages are *allowed* here, no portability problem
cabal_pkgid <- configDependency ipkgs (Dependency "Cabal" range)
return ["-package", showPackageId cabal_pkgid]
pathSeparator :: Char
#if mingw32_HOST_OS || mingw32_TARGET_OS
pathSeparator = '\\'
#else
pathSeparator = '/'
#endif
| FranklinChen/hugs98-plus-Sep2006 | packages/Cabal/cabal-setup/CabalSetup.hs | bsd-3-clause | 4,026 | 23 | 22 | 880 | 855 | 457 | 398 | -1 | -1 |
--==========================================================--
--=== The parser. ===--
--=== Parser.hs ===--
--==========================================================--
module Parser where
{- FIX THESE UP -}
--utLookupDef env k def
-- = head ( [ vv | (kk,vv) <- env, kk == k] ++ [def] )
panic = error
{- END FIXUPS -}
--paLiteral :: Parser Literal
paLiteral
= pgAlts
[
pgApply (LiteralInt.leStringToInt) (pgItem Lintlit),
pgApply (LiteralChar.head) (pgItem Lcharlit),
pgApply LiteralString (pgItem Lstringlit)
]
paExpr
= pgAlts
[
paCaseExpr,
paLetExpr,
paLamExpr,
paIfExpr,
paUnaryMinusExpr,
hsDoExpr []
]
paUnaryMinusExpr
= pgThen2
(\minus (_, aexpr, _) ->
ExprApp (ExprApp (ExprVar "-") (ExprLiteral (LiteralInt 0))) aexpr)
paMinus
paAExpr
paCaseExpr
= pgThen4
(\casee expr off alts -> ExprCase expr alts)
(pgItem Lcase)
paExpr
(pgItem Lof)
(pgDeclList paAlt)
paAlt
= pgAlts
[
pgThen4
(\pat arrow expr wheres
-> MkExprCaseAlt pat (pa_MakeWhereExpr expr wheres))
paPat
(pgItem Larrow)
paExpr
(pgOptional paWhereClause),
pgThen3
(\pat agrdrhss wheres
-> MkExprCaseAlt pat
(pa_MakeWhereExpr (ExprGuards agrdrhss) wheres))
paPat
(pgOneOrMore paGalt)
(pgOptional paWhereClause)
]
paGalt
= pgThen4
(\bar guard arrow expr -> (guard, expr))
(pgItem Lbar)
paExpr
(pgItem Larrow)
paExpr
paLamExpr
= pgThen4
(\lam patterns arrow rhs -> ExprLam patterns rhs)
(pgItem Lslash)
(pgZeroOrMore paAPat)
(pgItem Larrow)
paExpr
paLetExpr
= pgThen4
(\lett decls inn rhs -> ExprLetrec decls rhs)
(pgItem Llet)
paValdefs
(pgItem Lin)
paExpr
paValdefs
= pgApply pa_MergeValdefs (pgDeclList paValdef)
pa_MergeValdefs
= id
paLhs
= pgAlts
[
pgThen2 (\v ps -> LhsVar v ps) paVar (pgOneOrMore paPat),
pgApply LhsPat paPat
]
paValdef
= pgAlts
[
pgThen4
(\(line, lhs) eq rhs wheres
-> MkValBind line lhs (pa_MakeWhereExpr rhs wheres))
(pgGetLineNumber paLhs)
(pgItem Lequals)
paExpr
(pgOptional paWhereClause),
pgThen3
(\(line, lhs) grdrhss wheres
-> MkValBind line lhs
(pa_MakeWhereExpr (ExprGuards grdrhss) wheres))
(pgGetLineNumber paLhs)
(pgOneOrMore paGrhs)
(pgOptional paWhereClause)
]
pa_MakeWhereExpr expr Nothing
= expr
pa_MakeWhereExpr expr (Just whereClauses)
= ExprWhere expr whereClauses
paWhereClause
= pgThen2 (\x y -> y) (pgItem Lwhere) paValdefs
paGrhs
= pgThen4
(\bar guard equals expr -> (guard, expr))
(pgItem Lbar)
paExpr
(pgItem Lequals)
paExpr
paAPat
= pgAlts
[
pgApply PatVar paVar,
pgApply (\id -> PatCon id []) paCon,
pgApply (const PatWild) (pgItem Lunder),
pgApply PatTuple
(pgThen3 (\l es r -> es)
(pgItem Llparen)
(pgTwoOrMoreWithSep paPat (pgItem Lcomma))
(pgItem Lrparen)),
pgApply PatList
(pgThen3 (\l es r -> es)
(pgItem Llbrack)
(pgZeroOrMoreWithSep paPat (pgItem Lcomma))
(pgItem Lrbrack)),
pgThen3 (\l p r -> p)
(pgItem Llparen)
paPat
(pgItem Lrparen)
]
paPat
= pgAlts
[
pgThen2 (\c ps -> PatCon c ps)
paCon
(pgOneOrMore paAPat),
pgThen3 (\ap c pa -> PatCon c [ap,pa])
paAPat
paConop
paPat,
paAPat
]
paIfExpr
= pgThen4
(\iff c thenn (t,f) -> ExprIf c t f)
(pgItem Lif)
paExpr
(pgItem Lthen)
(pgThen3
(\t elsee f -> (t,f))
paExpr
(pgItem Lelse)
paExpr
)
paAExpr
= pgApply (\x -> (False, x, []))
(pgAlts
[
pgApply ExprVar paVar,
pgApply ExprCon paCon,
pgApply ExprLiteral paLiteral,
pgApply ExprList paListExpr,
pgApply ExprTuple paTupleExpr,
pgThen3 (\l e r -> e) (pgItem Llparen) paExpr (pgItem Lrparen)
]
)
paListExpr
= pgThen3 (\l es r -> es)
(pgItem Llbrack)
(pgZeroOrMoreWithSep paExpr (pgItem Lcomma))
(pgItem Lrbrack)
paTupleExpr
= pgThen3 (\l es r -> es)
(pgItem Llparen)
(pgTwoOrMoreWithSep paExpr (pgItem Lcomma))
(pgItem Lrparen)
paVar = pgItem Lvar
paCon = pgItem Lcon
paVarop = pgItem Lvarop
paConop = pgItem Lconop
paMinus = pgItem Lminus
paOp
= pgAlts [
pgApply (\x -> (True, ExprVar x, x)) paVarop,
pgApply (\x -> (True, ExprCon x, x)) paConop,
pgApply (\x -> (True, ExprVar x, x)) paMinus
]
paDataDecl
= pgThen2
(\dataa useful -> useful)
(pgItem Ldata)
paDataDecl_main
paDataDecl_main
= pgThen4
(\name params eq drhs -> MkDataDecl name (params, drhs))
paCon
(pgZeroOrMore paVar)
(pgItem Lequals)
(pgOneOrMoreWithSep paConstrs (pgItem Lbar))
paConstrs
= pgThen2
(\con texprs -> (con, texprs))
paCon
(pgZeroOrMore paAType)
paType
= pgAlts
[
pgThen3
(\atype arrow typee -> TypeArr atype typee)
paAType
(pgItem Larrow)
paType,
pgThen2
TypeCon
paCon
(pgOneOrMore paAType),
paAType
]
paAType
= pgAlts
[
pgApply TypeVar paVar,
pgApply (\tycon -> TypeCon tycon []) paCon,
pgThen3
(\l t r -> t)
(pgItem Llparen)
paType
(pgItem Lrparen),
pgThen3
(\l t r -> TypeList t)
(pgItem Llbrack)
paType
(pgItem Lrbrack),
pgThen3
(\l t r -> TypeTuple t)
(pgItem Llparen)
(pgTwoOrMoreWithSep paType (pgItem Lcomma))
(pgItem Lrparen)
]
paInfixDecl env toks
= let dump (ExprVar v) = v
dump (ExprCon c) = c
in
pa_UpdateFixityEnv
(pgThen3
(\assoc prio name -> MkFixDecl name (assoc, prio))
paInfixWord
(pgApply leStringToInt (pgItem Lintlit))
(pgApply (\(_, op, _) -> dump op) paOp)
env
toks
)
paInfixWord
= pgAlts
[
pgApply (const InfixL) (pgItem Linfixl),
pgApply (const InfixR) (pgItem Linfixr),
pgApply (const InfixN) (pgItem Linfix)
]
pa_UpdateFixityEnv (PFail tok)
= PFail tok
pa_UpdateFixityEnv (POk env toks (MkFixDecl name assoc_prio))
= let
new_env = (name, assoc_prio) : env
in
POk new_env toks (MkFixDecl name assoc_prio)
paTopDecl
= pgAlts
[
pgApply MkTopF paInfixDecl,
pgApply MkTopD paDataDecl,
pgApply MkTopV paValdef
]
paModule
= pgThen4
(\modyule name wheree topdecls -> MkModule name topdecls)
(pgItem Lmodule)
paCon
(pgItem Lwhere)
(pgDeclList paTopDecl)
parser_test toks
= let parser_to_test
= --paPat
--paExpr
--paValdef
--pgZeroOrMore paInfixDecl
--paDataDecl
--paType
paModule
--pgTwoOrMoreWithSep (pgItem Lsemi) (pgItem Lcomma)
in
parser_to_test hsPrecTable toks
--==============================================--
--=== The Operator-Precedence parser (yuck!) ===--
--==============================================--
--
--==========================================================--
--
hsAExprOrOp
= pgAlts [paAExpr, paOp]
--hsDoExpr :: [PEntry] -> Parser Expr
-- [PaEntry] is a stack of operators and atomic expressions
-- hsDoExpr uses a parser (hsAexpOrOp :: Parsr PaEntry) for atomic
-- expressions or operators
hsDoExpr stack env toks =
let
(validIn, restIn, parseIn, err)
= case hsAExprOrOp env toks of
POk env1 toks1 item1
-> (True, toks1, item1, panic "hsDoExpr(1)")
PFail err
-> (False, panic "hsDoExpr(2)", panic "hsDoExpr(3)", err)
(opIn, valueIn, nameIn)
= parseIn
(assocIn, priorIn)
= utLookupDef env nameIn (InfixL, 9)
shift
= hsDoExpr (parseIn:stack) env restIn
in
case stack of
s1:s2:s3:ss
| validIn && opS2 && opIn && priorS2 > priorIn
-> reduce
| validIn && opS2 && opIn && priorS2 == priorIn
-> if assocS2 == InfixL &&
assocIn == InfixL
then reduce
else
if assocS2 == InfixR &&
assocIn == InfixR
then shift
else PFail (head toks) -- Because of ambiguousness
| not validIn && opS2
-> reduce
where
(opS1, valueS1, nameS1) = s1
(opS2, valueS2, nameS2) = s2
(opS3, valueS3, nameS3) = s3
(assocS2, priorS2) = utLookupDef env nameS2 (InfixL, 9)
reduce = hsDoExpr ((False, ExprApp (ExprApp valueS2 valueS3)
valueS1, [])
: ss) env toks
s1:s2:ss
| validIn && (opS1 || opS2) -> shift
| otherwise -> reduce
where
(opS1, valueS1, nameS1) = s1
(opS2, valueS2, nameS2) = s2
reduce = hsDoExpr ((False, ExprApp valueS2 valueS1, []) : ss)
env toks
(s1:[])
| validIn -> shift
| otherwise -> POk env toks valueS1
where
(opS1, valueS1, nameS1) = s1
[]
| validIn -> shift
| otherwise -> PFail err
--==========================================================--
--=== end Parser.hs ===--
--==========================================================--
hsPrecTable = [
("-", (InfixL, 6)),
("+", (InfixL, 6)),
("*", (InfixL, 7)),
("div", (InfixN, 7)),
("mod", (InfixN, 7)),
("<", (InfixN, 4)),
("<=", (InfixN, 4)),
("==", (InfixN, 4)),
("/=", (InfixN, 4)),
(">=", (InfixN, 4)),
(">", (InfixN, 4)),
("C:", (InfixR, 5)),
("++", (InfixR, 5)),
("\\", (InfixN, 5)),
("!!", (InfixL, 9)),
(".", (InfixR, 9)),
("^", (InfixR, 8)),
("elem", (InfixN, 4)),
("notElem", (InfixN, 4)),
("||", (InfixR, 2)),
("&&", (InfixR, 3))]
{- FIX THESE UP -}
--utLookupDef env k def
-- = head ( [ vv | (kk,vv) <- env, kk == k] ++ [def] )
panic = error
{- END FIXUPS -}
--paLiteral :: Parser Literal
paLiteral
= pgAlts
[
pgApply (LiteralInt.leStringToInt) (pgItem Lintlit),
pgApply (LiteralChar.head) (pgItem Lcharlit),
pgApply LiteralString (pgItem Lstringlit)
]
paExpr
= pgAlts
[
paCaseExpr,
paLetExpr,
paLamExpr,
paIfExpr,
paUnaryMinusExpr,
hsDoExpr []
]
paUnaryMinusExpr
= pgThen2
(\minus (_, aexpr, _) ->
ExprApp (ExprApp (ExprVar "-") (ExprLiteral (LiteralInt 0))) aexpr)
paMinus
paAExpr
paCaseExpr
= pgThen4
(\casee expr off alts -> ExprCase expr alts)
(pgItem Lcase)
paExpr
(pgItem Lof)
(pgDeclList paAlt)
paAlt
= pgAlts
[
pgThen4
(\pat arrow expr wheres
-> MkExprCaseAlt pat (pa_MakeWhereExpr expr wheres))
paPat
(pgItem Larrow)
paExpr
(pgOptional paWhereClause),
pgThen3
(\pat agrdrhss wheres
-> MkExprCaseAlt pat
(pa_MakeWhereExpr (ExprGuards agrdrhss) wheres))
paPat
(pgOneOrMore paGalt)
(pgOptional paWhereClause)
]
paGalt
= pgThen4
(\bar guard arrow expr -> (guard, expr))
(pgItem Lbar)
paExpr
(pgItem Larrow)
paExpr
paLamExpr
= pgThen4
(\lam patterns arrow rhs -> ExprLam patterns rhs)
(pgItem Lslash)
(pgZeroOrMore paAPat)
(pgItem Larrow)
paExpr
paLetExpr
= pgThen4
(\lett decls inn rhs -> ExprLetrec decls rhs)
(pgItem Llet)
paValdefs
(pgItem Lin)
paExpr
paValdefs
= pgApply pa_MergeValdefs (pgDeclList paValdef)
pa_MergeValdefs
= id
paLhs
= pgAlts
[
pgThen2 (\v ps -> LhsVar v ps) paVar (pgOneOrMore paPat),
pgApply LhsPat paPat
]
paValdef
= pgAlts
[
pgThen4
(\(line, lhs) eq rhs wheres
-> MkValBind line lhs (pa_MakeWhereExpr rhs wheres))
(pgGetLineNumber paLhs)
(pgItem Lequals)
paExpr
(pgOptional paWhereClause),
pgThen3
(\(line, lhs) grdrhss wheres
-> MkValBind line lhs
(pa_MakeWhereExpr (ExprGuards grdrhss) wheres))
(pgGetLineNumber paLhs)
(pgOneOrMore paGrhs)
(pgOptional paWhereClause)
]
pa_MakeWhereExpr expr Nothing
= expr
pa_MakeWhereExpr expr (Just whereClauses)
= ExprWhere expr whereClauses
paWhereClause
= pgThen2 (\x y -> y) (pgItem Lwhere) paValdefs
paGrhs
= pgThen4
(\bar guard equals expr -> (guard, expr))
(pgItem Lbar)
paExpr
(pgItem Lequals)
paExpr
paAPat
= pgAlts
[
pgApply PatVar paVar,
pgApply (\id -> PatCon id []) paCon,
pgApply (const PatWild) (pgItem Lunder),
pgApply PatTuple
(pgThen3 (\l es r -> es)
(pgItem Llparen)
(pgTwoOrMoreWithSep paPat (pgItem Lcomma))
(pgItem Lrparen)),
pgApply PatList
(pgThen3 (\l es r -> es)
(pgItem Llbrack)
(pgZeroOrMoreWithSep paPat (pgItem Lcomma))
(pgItem Lrbrack)),
pgThen3 (\l p r -> p)
(pgItem Llparen)
paPat
(pgItem Lrparen)
]
paPat
= pgAlts
[
pgThen2 (\c ps -> PatCon c ps)
paCon
(pgOneOrMore paAPat),
pgThen3 (\ap c pa -> PatCon c [ap,pa])
paAPat
paConop
paPat,
paAPat
]
paIfExpr
= pgThen4
(\iff c thenn (t,f) -> ExprIf c t f)
(pgItem Lif)
paExpr
(pgItem Lthen)
(pgThen3
(\t elsee f -> (t,f))
paExpr
(pgItem Lelse)
paExpr
)
paAExpr
= pgApply (\x -> (False, x, []))
(pgAlts
[
pgApply ExprVar paVar,
pgApply ExprCon paCon,
pgApply ExprLiteral paLiteral,
pgApply ExprList paListExpr,
pgApply ExprTuple paTupleExpr,
pgThen3 (\l e r -> e) (pgItem Llparen) paExpr (pgItem Lrparen)
]
)
paListExpr
= pgThen3 (\l es r -> es)
(pgItem Llbrack)
(pgZeroOrMoreWithSep paExpr (pgItem Lcomma))
(pgItem Lrbrack)
paTupleExpr
= pgThen3 (\l es r -> es)
(pgItem Llparen)
(pgTwoOrMoreWithSep paExpr (pgItem Lcomma))
(pgItem Lrparen)
paVar = pgItem Lvar
paCon = pgItem Lcon
paVarop = pgItem Lvarop
paConop = pgItem Lconop
paMinus = pgItem Lminus
paOp
= pgAlts [
pgApply (\x -> (True, ExprVar x, x)) paVarop,
pgApply (\x -> (True, ExprCon x, x)) paConop,
pgApply (\x -> (True, ExprVar x, x)) paMinus
]
paDataDecl
= pgThen2
(\dataa useful -> useful)
(pgItem Ldata)
paDataDecl_main
paDataDecl_main
= pgThen4
(\name params eq drhs -> MkDataDecl name (params, drhs))
paCon
(pgZeroOrMore paVar)
(pgItem Lequals)
(pgOneOrMoreWithSep paConstrs (pgItem Lbar))
paConstrs
= pgThen2
(\con texprs -> (con, texprs))
paCon
(pgZeroOrMore paAType)
paType
= pgAlts
[
pgThen3
(\atype arrow typee -> TypeArr atype typee)
paAType
(pgItem Larrow)
paType,
pgThen2
TypeCon
paCon
(pgOneOrMore paAType),
paAType
]
paAType
= pgAlts
[
pgApply TypeVar paVar,
pgApply (\tycon -> TypeCon tycon []) paCon,
pgThen3
(\l t r -> t)
(pgItem Llparen)
paType
(pgItem Lrparen),
pgThen3
(\l t r -> TypeList t)
(pgItem Llbrack)
paType
(pgItem Lrbrack),
pgThen3
(\l t r -> TypeTuple t)
(pgItem Llparen)
(pgTwoOrMoreWithSep paType (pgItem Lcomma))
(pgItem Lrparen)
]
paInfixDecl env toks
= let dump (ExprVar v) = v
dump (ExprCon c) = c
in
pa_UpdateFixityEnv
(pgThen3
(\assoc prio name -> MkFixDecl name (assoc, prio))
paInfixWord
(pgApply leStringToInt (pgItem Lintlit))
(pgApply (\(_, op, _) -> dump op) paOp)
env
toks
)
paInfixWord
= pgAlts
[
pgApply (const InfixL) (pgItem Linfixl),
pgApply (const InfixR) (pgItem Linfixr),
pgApply (const InfixN) (pgItem Linfix)
]
pa_UpdateFixityEnv (PFail tok)
= PFail tok
pa_UpdateFixityEnv (POk env toks (MkFixDecl name assoc_prio))
= let
new_env = (name, assoc_prio) : env
in
POk new_env toks (MkFixDecl name assoc_prio)
paTopDecl
= pgAlts
[
pgApply MkTopF paInfixDecl,
pgApply MkTopD paDataDecl,
pgApply MkTopV paValdef
]
paModule
= pgThen4
(\modyule name wheree topdecls -> MkModule name topdecls)
(pgItem Lmodule)
paCon
(pgItem Lwhere)
(pgDeclList paTopDecl)
parser_test toks
= let parser_to_test
= --paPat
--paExpr
--paValdef
--pgZeroOrMore paInfixDecl
--paDataDecl
--paType
paModule
--pgTwoOrMoreWithSep (pgItem Lsemi) (pgItem Lcomma)
in
parser_to_test hsPrecTable toks
--==============================================--
--=== The Operator-Precedence parser (yuck!) ===--
--==============================================--
--
--==========================================================--
--
hsAExprOrOp
= pgAlts [paAExpr, paOp]
--hsDoExpr :: [PEntry] -> Parser Expr
-- [PaEntry] is a stack of operators and atomic expressions
-- hsDoExpr uses a parser (hsAexpOrOp :: Parsr PaEntry) for atomic
-- expressions or operators
hsDoExpr stack env toks =
let
(validIn, restIn, parseIn, err)
= case hsAExprOrOp env toks of
POk env1 toks1 item1
-> (True, toks1, item1, panic "hsDoExpr(1)")
PFail err
-> (False, panic "hsDoExpr(2)", panic "hsDoExpr(3)", err)
(opIn, valueIn, nameIn)
= parseIn
(assocIn, priorIn)
= utLookupDef env nameIn (InfixL, 9)
shift
= hsDoExpr (parseIn:stack) env restIn
in
case stack of
s1:s2:s3:ss
| validIn && opS2 && opIn && priorS2 > priorIn
-> reduce
| validIn && opS2 && opIn && priorS2 == priorIn
-> if assocS2 == InfixL &&
assocIn == InfixL
then reduce
else
if assocS2 == InfixR &&
assocIn == InfixR
then shift
else PFail (head toks) -- Because of ambiguousness
| not validIn && opS2
-> reduce
where
(opS1, valueS1, nameS1) = s1
(opS2, valueS2, nameS2) = s2
(opS3, valueS3, nameS3) = s3
(assocS2, priorS2) = utLookupDef env nameS2 (InfixL, 9)
reduce = hsDoExpr ((False, ExprApp (ExprApp valueS2 valueS3)
valueS1, [])
: ss) env toks
s1:s2:ss
| validIn && (opS1 || opS2) -> shift
| otherwise -> reduce
where
(opS1, valueS1, nameS1) = s1
(opS2, valueS2, nameS2) = s2
reduce = hsDoExpr ((False, ExprApp valueS2 valueS1, []) : ss)
env toks
(s1:[])
| validIn -> shift
| otherwise -> POk env toks valueS1
where
(opS1, valueS1, nameS1) = s1
[]
| validIn -> shift
| otherwise -> PFail err
--==========================================================--
--=== end Parser.hs ===--
--==========================================================--
hsPrecTable = [
("-", (InfixL, 6)),
("+", (InfixL, 6)),
("*", (InfixL, 7)),
("div", (InfixN, 7)),
("mod", (InfixN, 7)),
("<", (InfixN, 4)),
("<=", (InfixN, 4)),
("==", (InfixN, 4)),
("/=", (InfixN, 4)),
(">=", (InfixN, 4)),
(">", (InfixN, 4)),
("C:", (InfixR, 5)),
("++", (InfixR, 5)),
("\\", (InfixN, 5)),
("!!", (InfixL, 9)),
(".", (InfixR, 9)),
("^", (InfixR, 8)),
("elem", (InfixN, 4)),
("notElem", (InfixN, 4)),
("||", (InfixR, 2)),
("&&", (InfixR, 3))]
{- FIX THESE UP -}
--utLookupDef env k def
-- = head ( [ vv | (kk,vv) <- env, kk == k] ++ [def] )
panic = error
{- END FIXUPS -}
--paLiteral :: Parser Literal
paLiteral
= pgAlts
[
pgApply (LiteralInt.leStringToInt) (pgItem Lintlit),
pgApply (LiteralChar.head) (pgItem Lcharlit),
pgApply LiteralString (pgItem Lstringlit)
]
paExpr
= pgAlts
[
paCaseExpr,
paLetExpr,
paLamExpr,
paIfExpr,
paUnaryMinusExpr,
hsDoExpr []
]
paUnaryMinusExpr
= pgThen2
(\minus (_, aexpr, _) ->
ExprApp (ExprApp (ExprVar "-") (ExprLiteral (LiteralInt 0))) aexpr)
paMinus
paAExpr
paCaseExpr
= pgThen4
(\casee expr off alts -> ExprCase expr alts)
(pgItem Lcase)
paExpr
(pgItem Lof)
(pgDeclList paAlt)
paAlt
= pgAlts
[
pgThen4
(\pat arrow expr wheres
-> MkExprCaseAlt pat (pa_MakeWhereExpr expr wheres))
paPat
(pgItem Larrow)
paExpr
(pgOptional paWhereClause),
pgThen3
(\pat agrdrhss wheres
-> MkExprCaseAlt pat
(pa_MakeWhereExpr (ExprGuards agrdrhss) wheres))
paPat
(pgOneOrMore paGalt)
(pgOptional paWhereClause)
]
paGalt
= pgThen4
(\bar guard arrow expr -> (guard, expr))
(pgItem Lbar)
paExpr
(pgItem Larrow)
paExpr
paLamExpr
= pgThen4
(\lam patterns arrow rhs -> ExprLam patterns rhs)
(pgItem Lslash)
(pgZeroOrMore paAPat)
(pgItem Larrow)
paExpr
paLetExpr
= pgThen4
(\lett decls inn rhs -> ExprLetrec decls rhs)
(pgItem Llet)
paValdefs
(pgItem Lin)
paExpr
paValdefs
= pgApply pa_MergeValdefs (pgDeclList paValdef)
pa_MergeValdefs
= id
paLhs
= pgAlts
[
pgThen2 (\v ps -> LhsVar v ps) paVar (pgOneOrMore paPat),
pgApply LhsPat paPat
]
paValdef
= pgAlts
[
pgThen4
(\(line, lhs) eq rhs wheres
-> MkValBind line lhs (pa_MakeWhereExpr rhs wheres))
(pgGetLineNumber paLhs)
(pgItem Lequals)
paExpr
(pgOptional paWhereClause),
pgThen3
(\(line, lhs) grdrhss wheres
-> MkValBind line lhs
(pa_MakeWhereExpr (ExprGuards grdrhss) wheres))
(pgGetLineNumber paLhs)
(pgOneOrMore paGrhs)
(pgOptional paWhereClause)
]
pa_MakeWhereExpr expr Nothing
= expr
pa_MakeWhereExpr expr (Just whereClauses)
= ExprWhere expr whereClauses
paWhereClause
= pgThen2 (\x y -> y) (pgItem Lwhere) paValdefs
paGrhs
= pgThen4
(\bar guard equals expr -> (guard, expr))
(pgItem Lbar)
paExpr
(pgItem Lequals)
paExpr
paAPat
= pgAlts
[
pgApply PatVar paVar,
pgApply (\id -> PatCon id []) paCon,
pgApply (const PatWild) (pgItem Lunder),
pgApply PatTuple
(pgThen3 (\l es r -> es)
(pgItem Llparen)
(pgTwoOrMoreWithSep paPat (pgItem Lcomma))
(pgItem Lrparen)),
pgApply PatList
(pgThen3 (\l es r -> es)
(pgItem Llbrack)
(pgZeroOrMoreWithSep paPat (pgItem Lcomma))
(pgItem Lrbrack)),
pgThen3 (\l p r -> p)
(pgItem Llparen)
paPat
(pgItem Lrparen)
]
paPat
= pgAlts
[
pgThen2 (\c ps -> PatCon c ps)
paCon
(pgOneOrMore paAPat),
pgThen3 (\ap c pa -> PatCon c [ap,pa])
paAPat
paConop
paPat,
paAPat
]
paIfExpr
= pgThen4
(\iff c thenn (t,f) -> ExprIf c t f)
(pgItem Lif)
paExpr
(pgItem Lthen)
(pgThen3
(\t elsee f -> (t,f))
paExpr
(pgItem Lelse)
paExpr
)
paAExpr
= pgApply (\x -> (False, x, []))
(pgAlts
[
pgApply ExprVar paVar,
pgApply ExprCon paCon,
pgApply ExprLiteral paLiteral,
pgApply ExprList paListExpr,
pgApply ExprTuple paTupleExpr,
pgThen3 (\l e r -> e) (pgItem Llparen) paExpr (pgItem Lrparen)
]
)
paListExpr
= pgThen3 (\l es r -> es)
(pgItem Llbrack)
(pgZeroOrMoreWithSep paExpr (pgItem Lcomma))
(pgItem Lrbrack)
paTupleExpr
= pgThen3 (\l es r -> es)
(pgItem Llparen)
(pgTwoOrMoreWithSep paExpr (pgItem Lcomma))
(pgItem Lrparen)
paVar = pgItem Lvar
paCon = pgItem Lcon
paVarop = pgItem Lvarop
paConop = pgItem Lconop
paMinus = pgItem Lminus
paOp
= pgAlts [
pgApply (\x -> (True, ExprVar x, x)) paVarop,
pgApply (\x -> (True, ExprCon x, x)) paConop,
pgApply (\x -> (True, ExprVar x, x)) paMinus
]
paDataDecl
= pgThen2
(\dataa useful -> useful)
(pgItem Ldata)
paDataDecl_main
paDataDecl_main
= pgThen4
(\name params eq drhs -> MkDataDecl name (params, drhs))
paCon
(pgZeroOrMore paVar)
(pgItem Lequals)
(pgOneOrMoreWithSep paConstrs (pgItem Lbar))
paConstrs
= pgThen2
(\con texprs -> (con, texprs))
paCon
(pgZeroOrMore paAType)
paType
= pgAlts
[
pgThen3
(\atype arrow typee -> TypeArr atype typee)
paAType
(pgItem Larrow)
paType,
pgThen2
TypeCon
paCon
(pgOneOrMore paAType),
paAType
]
paAType
= pgAlts
[
pgApply TypeVar paVar,
pgApply (\tycon -> TypeCon tycon []) paCon,
pgThen3
(\l t r -> t)
(pgItem Llparen)
paType
(pgItem Lrparen),
pgThen3
(\l t r -> TypeList t)
(pgItem Llbrack)
paType
(pgItem Lrbrack),
pgThen3
(\l t r -> TypeTuple t)
(pgItem Llparen)
(pgTwoOrMoreWithSep paType (pgItem Lcomma))
(pgItem Lrparen)
]
paInfixDecl env toks
= let dump (ExprVar v) = v
dump (ExprCon c) = c
in
pa_UpdateFixityEnv
(pgThen3
(\assoc prio name -> MkFixDecl name (assoc, prio))
paInfixWord
(pgApply leStringToInt (pgItem Lintlit))
(pgApply (\(_, op, _) -> dump op) paOp)
env
toks
)
paInfixWord
= pgAlts
[
pgApply (const InfixL) (pgItem Linfixl),
pgApply (const InfixR) (pgItem Linfixr),
pgApply (const InfixN) (pgItem Linfix)
]
pa_UpdateFixityEnv (PFail tok)
= PFail tok
pa_UpdateFixityEnv (POk env toks (MkFixDecl name assoc_prio))
= let
new_env = (name, assoc_prio) : env
in
POk new_env toks (MkFixDecl name assoc_prio)
paTopDecl
= pgAlts
[
pgApply MkTopF paInfixDecl,
pgApply MkTopD paDataDecl,
pgApply MkTopV paValdef
]
paModule
= pgThen4
(\modyule name wheree topdecls -> MkModule name topdecls)
(pgItem Lmodule)
paCon
(pgItem Lwhere)
(pgDeclList paTopDecl)
parser_test toks
= let parser_to_test
= --paPat
--paExpr
--paValdef
--pgZeroOrMore paInfixDecl
--paDataDecl
--paType
paModule
--pgTwoOrMoreWithSep (pgItem Lsemi) (pgItem Lcomma)
in
parser_to_test hsPrecTable toks
--==============================================--
--=== The Operator-Precedence parser (yuck!) ===--
--==============================================--
--
--==========================================================--
--
hsAExprOrOp
= pgAlts [paAExpr, paOp]
--hsDoExpr :: [PEntry] -> Parser Expr
-- [PaEntry] is a stack of operators and atomic expressions
-- hsDoExpr uses a parser (hsAexpOrOp :: Parsr PaEntry) for atomic
-- expressions or operators
hsDoExpr stack env toks =
let
(validIn, restIn, parseIn, err)
= case hsAExprOrOp env toks of
POk env1 toks1 item1
-> (True, toks1, item1, panic "hsDoExpr(1)")
PFail err
-> (False, panic "hsDoExpr(2)", panic "hsDoExpr(3)", err)
(opIn, valueIn, nameIn)
= parseIn
(assocIn, priorIn)
= utLookupDef env nameIn (InfixL, 9)
shift
= hsDoExpr (parseIn:stack) env restIn
in
case stack of
s1:s2:s3:ss
| validIn && opS2 && opIn && priorS2 > priorIn
-> reduce
| validIn && opS2 && opIn && priorS2 == priorIn
-> if assocS2 == InfixL &&
assocIn == InfixL
then reduce
else
if assocS2 == InfixR &&
assocIn == InfixR
then shift
else PFail (head toks) -- Because of ambiguousness
| not validIn && opS2
-> reduce
where
(opS1, valueS1, nameS1) = s1
(opS2, valueS2, nameS2) = s2
(opS3, valueS3, nameS3) = s3
(assocS2, priorS2) = utLookupDef env nameS2 (InfixL, 9)
reduce = hsDoExpr ((False, ExprApp (ExprApp valueS2 valueS3)
valueS1, [])
: ss) env toks
s1:s2:ss
| validIn && (opS1 || opS2) -> shift
| otherwise -> reduce
where
(opS1, valueS1, nameS1) = s1
(opS2, valueS2, nameS2) = s2
reduce = hsDoExpr ((False, ExprApp valueS2 valueS1, []) : ss)
env toks
(s1:[])
| validIn -> shift
| otherwise -> POk env toks valueS1
where
(opS1, valueS1, nameS1) = s1
[]
| validIn -> shift
| otherwise -> PFail err
--==========================================================--
--=== end Parser.hs ===--
--==========================================================--
hsPrecTable = [
("-", (InfixL, 6)),
("+", (InfixL, 6)),
("*", (InfixL, 7)),
("div", (InfixN, 7)),
("mod", (InfixN, 7)),
("<", (InfixN, 4)),
("<=", (InfixN, 4)),
("==", (InfixN, 4)),
("/=", (InfixN, 4)),
(">=", (InfixN, 4)),
(">", (InfixN, 4)),
("C:", (InfixR, 5)),
("++", (InfixR, 5)),
("\\", (InfixN, 5)),
("!!", (InfixL, 9)),
(".", (InfixR, 9)),
("^", (InfixR, 8)),
("elem", (InfixN, 4)),
("notElem", (InfixN, 4)),
("||", (InfixR, 2)),
("&&", (InfixR, 3))]
{- FIX THESE UP -}
--utLookupDef env k def
-- = head ( [ vv | (kk,vv) <- env, kk == k] ++ [def] )
panic = error
{- END FIXUPS -}
--paLiteral :: Parser Literal
paLiteral
= pgAlts
[
pgApply (LiteralInt.leStringToInt) (pgItem Lintlit),
pgApply (LiteralChar.head) (pgItem Lcharlit),
pgApply LiteralString (pgItem Lstringlit)
]
paExpr
= pgAlts
[
paCaseExpr,
paLetExpr,
paLamExpr,
paIfExpr,
paUnaryMinusExpr,
hsDoExpr []
]
paUnaryMinusExpr
= pgThen2
(\minus (_, aexpr, _) ->
ExprApp (ExprApp (ExprVar "-") (ExprLiteral (LiteralInt 0))) aexpr)
paMinus
paAExpr
paCaseExpr
= pgThen4
(\casee expr off alts -> ExprCase expr alts)
(pgItem Lcase)
paExpr
(pgItem Lof)
(pgDeclList paAlt)
paAlt
= pgAlts
[
pgThen4
(\pat arrow expr wheres
-> MkExprCaseAlt pat (pa_MakeWhereExpr expr wheres))
paPat
(pgItem Larrow)
paExpr
(pgOptional paWhereClause),
pgThen3
(\pat agrdrhss wheres
-> MkExprCaseAlt pat
(pa_MakeWhereExpr (ExprGuards agrdrhss) wheres))
paPat
(pgOneOrMore paGalt)
(pgOptional paWhereClause)
]
paGalt
= pgThen4
(\bar guard arrow expr -> (guard, expr))
(pgItem Lbar)
paExpr
(pgItem Larrow)
paExpr
paLamExpr
= pgThen4
(\lam patterns arrow rhs -> ExprLam patterns rhs)
(pgItem Lslash)
(pgZeroOrMore paAPat)
(pgItem Larrow)
paExpr
paLetExpr
= pgThen4
(\lett decls inn rhs -> ExprLetrec decls rhs)
(pgItem Llet)
paValdefs
(pgItem Lin)
paExpr
paValdefs
= pgApply pa_MergeValdefs (pgDeclList paValdef)
pa_MergeValdefs
= id
paLhs
= pgAlts
[
pgThen2 (\v ps -> LhsVar v ps) paVar (pgOneOrMore paPat),
pgApply LhsPat paPat
]
paValdef
= pgAlts
[
pgThen4
(\(line, lhs) eq rhs wheres
-> MkValBind line lhs (pa_MakeWhereExpr rhs wheres))
(pgGetLineNumber paLhs)
(pgItem Lequals)
paExpr
(pgOptional paWhereClause),
pgThen3
(\(line, lhs) grdrhss wheres
-> MkValBind line lhs
(pa_MakeWhereExpr (ExprGuards grdrhss) wheres))
(pgGetLineNumber paLhs)
(pgOneOrMore paGrhs)
(pgOptional paWhereClause)
]
pa_MakeWhereExpr expr Nothing
= expr
pa_MakeWhereExpr expr (Just whereClauses)
= ExprWhere expr whereClauses
paWhereClause
= pgThen2 (\x y -> y) (pgItem Lwhere) paValdefs
paGrhs
= pgThen4
(\bar guard equals expr -> (guard, expr))
(pgItem Lbar)
paExpr
(pgItem Lequals)
paExpr
paAPat
= pgAlts
[
pgApply PatVar paVar,
pgApply (\id -> PatCon id []) paCon,
pgApply (const PatWild) (pgItem Lunder),
pgApply PatTuple
(pgThen3 (\l es r -> es)
(pgItem Llparen)
(pgTwoOrMoreWithSep paPat (pgItem Lcomma))
(pgItem Lrparen)),
pgApply PatList
(pgThen3 (\l es r -> es)
(pgItem Llbrack)
(pgZeroOrMoreWithSep paPat (pgItem Lcomma))
(pgItem Lrbrack)),
pgThen3 (\l p r -> p)
(pgItem Llparen)
paPat
(pgItem Lrparen)
]
paPat
= pgAlts
[
pgThen2 (\c ps -> PatCon c ps)
paCon
(pgOneOrMore paAPat),
pgThen3 (\ap c pa -> PatCon c [ap,pa])
paAPat
paConop
paPat,
paAPat
]
paIfExpr
= pgThen4
(\iff c thenn (t,f) -> ExprIf c t f)
(pgItem Lif)
paExpr
(pgItem Lthen)
(pgThen3
(\t elsee f -> (t,f))
paExpr
(pgItem Lelse)
paExpr
)
paAExpr
= pgApply (\x -> (False, x, []))
(pgAlts
[
pgApply ExprVar paVar,
pgApply ExprCon paCon,
pgApply ExprLiteral paLiteral,
pgApply ExprList paListExpr,
pgApply ExprTuple paTupleExpr,
pgThen3 (\l e r -> e) (pgItem Llparen) paExpr (pgItem Lrparen)
]
)
paListExpr
= pgThen3 (\l es r -> es)
(pgItem Llbrack)
(pgZeroOrMoreWithSep paExpr (pgItem Lcomma))
(pgItem Lrbrack)
paTupleExpr
= pgThen3 (\l es r -> es)
(pgItem Llparen)
(pgTwoOrMoreWithSep paExpr (pgItem Lcomma))
(pgItem Lrparen)
paVar = pgItem Lvar
paCon = pgItem Lcon
paVarop = pgItem Lvarop
paConop = pgItem Lconop
paMinus = pgItem Lminus
paOp
= pgAlts [
pgApply (\x -> (True, ExprVar x, x)) paVarop,
pgApply (\x -> (True, ExprCon x, x)) paConop,
pgApply (\x -> (True, ExprVar x, x)) paMinus
]
paDataDecl
= pgThen2
(\dataa useful -> useful)
(pgItem Ldata)
paDataDecl_main
paDataDecl_main
= pgThen4
(\name params eq drhs -> MkDataDecl name (params, drhs))
paCon
(pgZeroOrMore paVar)
(pgItem Lequals)
(pgOneOrMoreWithSep paConstrs (pgItem Lbar))
paConstrs
= pgThen2
(\con texprs -> (con, texprs))
paCon
(pgZeroOrMore paAType)
paType
= pgAlts
[
pgThen3
(\atype arrow typee -> TypeArr atype typee)
paAType
(pgItem Larrow)
paType,
pgThen2
TypeCon
paCon
(pgOneOrMore paAType),
paAType
]
paAType
= pgAlts
[
pgApply TypeVar paVar,
pgApply (\tycon -> TypeCon tycon []) paCon,
pgThen3
(\l t r -> t)
(pgItem Llparen)
paType
(pgItem Lrparen),
pgThen3
(\l t r -> TypeList t)
(pgItem Llbrack)
paType
(pgItem Lrbrack),
pgThen3
(\l t r -> TypeTuple t)
(pgItem Llparen)
(pgTwoOrMoreWithSep paType (pgItem Lcomma))
(pgItem Lrparen)
]
paInfixDecl env toks
= let dump (ExprVar v) = v
dump (ExprCon c) = c
in
pa_UpdateFixityEnv
(pgThen3
(\assoc prio name -> MkFixDecl name (assoc, prio))
paInfixWord
(pgApply leStringToInt (pgItem Lintlit))
(pgApply (\(_, op, _) -> dump op) paOp)
env
toks
)
paInfixWord
= pgAlts
[
pgApply (const InfixL) (pgItem Linfixl),
pgApply (const InfixR) (pgItem Linfixr),
pgApply (const InfixN) (pgItem Linfix)
]
pa_UpdateFixityEnv (PFail tok)
= PFail tok
pa_UpdateFixityEnv (POk env toks (MkFixDecl name assoc_prio))
= let
new_env = (name, assoc_prio) : env
in
POk new_env toks (MkFixDecl name assoc_prio)
paTopDecl
= pgAlts
[
pgApply MkTopF paInfixDecl,
pgApply MkTopD paDataDecl,
pgApply MkTopV paValdef
]
paModule
= pgThen4
(\modyule name wheree topdecls -> MkModule name topdecls)
(pgItem Lmodule)
paCon
(pgItem Lwhere)
(pgDeclList paTopDecl)
parser_test toks
= let parser_to_test
= --paPat
--paExpr
--paValdef
--pgZeroOrMore paInfixDecl
--paDataDecl
--paType
paModule
--pgTwoOrMoreWithSep (pgItem Lsemi) (pgItem Lcomma)
in
parser_to_test hsPrecTable toks
--==============================================--
--=== The Operator-Precedence parser (yuck!) ===--
--==============================================--
--
--==========================================================--
--
hsAExprOrOp
= pgAlts [paAExpr, paOp]
--hsDoExpr :: [PEntry] -> Parser Expr
-- [PaEntry] is a stack of operators and atomic expressions
-- hsDoExpr uses a parser (hsAexpOrOp :: Parsr PaEntry) for atomic
-- expressions or operators
hsDoExpr stack env toks =
let
(validIn, restIn, parseIn, err)
= case hsAExprOrOp env toks of
POk env1 toks1 item1
-> (True, toks1, item1, panic "hsDoExpr(1)")
PFail err
-> (False, panic "hsDoExpr(2)", panic "hsDoExpr(3)", err)
(opIn, valueIn, nameIn)
= parseIn
(assocIn, priorIn)
= utLookupDef env nameIn (InfixL, 9)
shift
= hsDoExpr (parseIn:stack) env restIn
in
case stack of
s1:s2:s3:ss
| validIn && opS2 && opIn && priorS2 > priorIn
-> reduce
| validIn && opS2 && opIn && priorS2 == priorIn
-> if assocS2 == InfixL &&
assocIn == InfixL
then reduce
else
if assocS2 == InfixR &&
assocIn == InfixR
then shift
else PFail (head toks) -- Because of ambiguousness
| not validIn && opS2
-> reduce
where
(opS1, valueS1, nameS1) = s1
(opS2, valueS2, nameS2) = s2
(opS3, valueS3, nameS3) = s3
(assocS2, priorS2) = utLookupDef env nameS2 (InfixL, 9)
reduce = hsDoExpr ((False, ExprApp (ExprApp valueS2 valueS3)
valueS1, [])
: ss) env toks
s1:s2:ss
| validIn && (opS1 || opS2) -> shift
| otherwise -> reduce
where
(opS1, valueS1, nameS1) = s1
(opS2, valueS2, nameS2) = s2
reduce = hsDoExpr ((False, ExprApp valueS2 valueS1, []) : ss)
env toks
(s1:[])
| validIn -> shift
| otherwise -> POk env toks valueS1
where
(opS1, valueS1, nameS1) = s1
[]
| validIn -> shift
| otherwise -> PFail err
--==========================================================--
--=== end Parser.hs ===--
--==========================================================--
hsPrecTable = [
("-", (InfixL, 6)),
("+", (InfixL, 6)),
("*", (InfixL, 7)),
("div", (InfixN, 7)),
("mod", (InfixN, 7)),
("<", (InfixN, 4)),
("<=", (InfixN, 4)),
("==", (InfixN, 4)),
("/=", (InfixN, 4)),
(">=", (InfixN, 4)),
(">", (InfixN, 4)),
("C:", (InfixR, 5)),
("++", (InfixR, 5)),
("\\", (InfixN, 5)),
("!!", (InfixL, 9)),
(".", (InfixR, 9)),
("^", (InfixR, 8)),
("elem", (InfixN, 4)),
("notElem", (InfixN, 4)),
("||", (InfixR, 2)),
("&&", (InfixR, 3))]
# | roberth/uu-helium | test/simple/benchmarks/big_big_test.hs | gpl-3.0 | 44,424 | 141 | 21 | 17,443 | 13,113 | 7,070 | 6,043 | -1 | -1 |
{-# LANGUAGE MagicHash #-}
-- |
-- Module : Data.Text.UnsafeShift
-- Copyright : (c) Bryan O'Sullivan 2009
--
-- License : BSD-style
-- Maintainer : [email protected], [email protected],
-- [email protected]
-- Stability : experimental
-- Portability : GHC
--
-- Fast, unchecked bit shifting functions.
module Data.Text.UnsafeShift
(
UnsafeShift(..)
) where
-- import qualified Data.Bits as Bits
import GHC.Base
import GHC.Word
-- | This is a workaround for poor optimisation in GHC 6.8.2. It
-- fails to notice constant-width shifts, and adds a test and branch
-- to every shift. This imposes about a 10% performance hit.
--
-- These functions are undefined when the amount being shifted by is
-- greater than the size in bits of a machine Int#.
class UnsafeShift a where
shiftL :: a -> Int -> a
shiftR :: a -> Int -> a
instance UnsafeShift Word16 where
{-# INLINE shiftL #-}
shiftL (W16# x#) (I# i#) = W16# (narrow16Word# (x# `uncheckedShiftL#` i#))
{-# INLINE shiftR #-}
shiftR (W16# x#) (I# i#) = W16# (x# `uncheckedShiftRL#` i#)
instance UnsafeShift Word32 where
{-# INLINE shiftL #-}
shiftL (W32# x#) (I# i#) = W32# (narrow32Word# (x# `uncheckedShiftL#` i#))
{-# INLINE shiftR #-}
shiftR (W32# x#) (I# i#) = W32# (x# `uncheckedShiftRL#` i#)
instance UnsafeShift Word64 where
{-# INLINE shiftL #-}
shiftL (W64# x#) (I# i#) = W64# (x# `uncheckedShiftL64#` i#)
{-# INLINE shiftR #-}
shiftR (W64# x#) (I# i#) = W64# (x# `uncheckedShiftRL64#` i#)
instance UnsafeShift Int where
{-# INLINE shiftL #-}
shiftL (I# x#) (I# i#) = I# (x# `iShiftL#` i#)
{-# INLINE shiftR #-}
shiftR (I# x#) (I# i#) = I# (x# `iShiftRA#` i#)
{-
instance UnsafeShift Integer where
{-# INLINE shiftL #-}
shiftL = Bits.shiftL
{-# INLINE shiftR #-}
shiftR = Bits.shiftR
-}
| abakst/liquidhaskell | benchmarks/text-0.11.2.3/Data/Text/UnsafeShift.hs | bsd-3-clause | 1,901 | 0 | 10 | 434 | 405 | 229 | 176 | 29 | 0 |
module Fail1 where
-- define an infix constructor and attempt to remove it...
data T1 a b = a :$: b | b :#: a
g :: T1 Int Int -> Int
g (x :$: y) = x + y
f x y = g (x :$: y)
| kmate/HaRe | old/testing/removeCon/Fail1_TokOut.hs | bsd-3-clause | 179 | 0 | 7 | 54 | 78 | 43 | 35 | 5 | 1 |
{-# LANGUAGE MagicHash #-}
module Main where
import GHC.Exts ( Float(F#),
eqFloat#, neFloat#, ltFloat#,
leFloat#, gtFloat#, geFloat#,
tagToEnum#
)
fcmp_eq, fcmp_ne, fcmp_lt, fcmp_le, fcmp_gt, fcmp_ge :: (String, Float -> Float -> Bool)
fcmp_eq = ("==", \ (F# a) (F# b) -> tagToEnum# (a `eqFloat#` b))
fcmp_ne = ("/=", \ (F# a) (F# b) -> tagToEnum# (a `neFloat#` b))
fcmp_lt = ("< ", \ (F# a) (F# b) -> tagToEnum# (a `ltFloat#` b))
fcmp_le = ("<=", \ (F# a) (F# b) -> tagToEnum# (a `leFloat#` b))
fcmp_gt = ("> ", \ (F# a) (F# b) -> tagToEnum# (a `gtFloat#` b))
fcmp_ge = (">=", \ (F# a) (F# b) -> tagToEnum# (a `geFloat#` b))
float_fns = [fcmp_eq, fcmp_ne, fcmp_lt, fcmp_le, fcmp_gt, fcmp_ge]
float_vals :: [Float]
float_vals = [0.0, 1.0, read "NaN"]
float_text
= [show4 arg1 ++ " " ++ fn_name ++ " " ++ show4 arg2 ++ " = " ++ show (fn arg1 arg2)
| (fn_name, fn) <- float_fns,
arg1 <- float_vals,
arg2 <- float_vals
]
where
show4 x = take 4 (show x ++ repeat ' ')
main
= putStrLn (unlines float_text)
| seereason/ghcjs | test/ghc/numeric/arith016.hs | mit | 1,091 | 6 | 12 | 272 | 496 | 285 | 211 | 24 | 1 |
{-# LANGUAGE TemplateHaskell #-}
module T7918A where
import Language.Haskell.TH
import Language.Haskell.TH.Quote
qq = QuasiQuoter {
quoteExp = \str -> case str of
"e1" -> [| True |]
"e2" -> [| id True |]
"e3" -> [| True || False |]
"e4" -> [| False |]
, quoteType = \str -> case str of
"t1" -> [t| Bool |]
"t2" -> [t| Maybe Bool |]
"t3" -> [t| Either Bool Int |]
"t4" -> [t| Int |]
, quotePat = let x = VarP (mkName "x")
y = VarP (mkName "y")
in \str -> case str of
"p1" -> return $ x
"p2" -> return $ ConP 'Just [x]
"p3" -> return $ TupP [x, y]
"p4" -> return $ y
, quoteDec = undefined
}
| siddhanathan/ghc | testsuite/tests/quasiquotation/T7918A.hs | bsd-3-clause | 1,070 | 0 | 15 | 605 | 244 | 146 | 98 | 23 | 10 |
{-# LANGUAGE OverloadedLists #-}
{-# LANGUAGE ViewPatterns #-}
module Data.AER.SIFT where
import Data.AER.DVS128
import Data.AER.Types
import System.Environment
import qualified Data.Vector as V
import qualified Data.Vector.Unboxed as UV
import qualified Data.Vector.Unboxed.Mutable as UMV
import Data.Thyme.Clock
import Data.AdditiveGroup
import Data.AffineSpace
import Data.Traversable
import Data.Foldable
import Control.Applicative
import Control.Monad.Cont
import Numeric.LinearAlgebra.HMatrix
import Prelude hiding (mapM)
-- kernels as calculated by:
-- http://dev.theomader.com/gaussian-kernel-calculator/
kernel1x3 = matrix 3 [0.077847,0.123317,0.077847
,0.123317,0.195346,0.123317
,0.077847,0.123317,0.077847
]
kernels = take 8 $ iterate (conv2 kernel1x3) (matrix 1 [1])
imgSizes = take 8 $ iterate (`div` 2) 128
kernelSizes = take 8 $ map (fst . size) kernels
globalLeak = 0.1
type Neuron = (Float,UTCTime)
updateNeuron :: Float -> Float -> Neuron -> UTCTime -> (Bool,Neuron)
updateNeuron l w (v,t) now = do
let dt = toSeconds (now .-. t)
v' = max 0 (v - dt * l) + w
if (v' > 1)
then (True,(0,now))
else (False,(v',now))
{-updatePLCont level accs now p x y = do-}
{- let x' = x `div` (2^level)-}
{- y' = y `div` (2^level)-}
{- ls = 128 `div` (2^level)-}
{- li = x' + y' * ls-}
{- oldNeuron <- UMV.read accs li -}
{- let (spike,newNeuron) = updateNeuron globalLeak (-}
{-updatePyramidLevel :: Int -> UMV.IOVector Neuron -> UTCTime -> Int -> Int -> Float -> IO ()-}
updatePyramidLevel level accs now p x y cont = do
-- calculate level coords
let x' = x `div` 2
y' = y `div` 2
ls = 128 `div` 2^level
li = x' + y' * ls
oldNeuron <- UMV.read accs li
let (spike,newNeuron) = updateNeuron globalLeak (p*0.25) oldNeuron now
UMV.write accs li newNeuron
let spikeDesc = (level,x',y',p)
if spike
then (spikeDesc:) <$> cont x' y'
else return []
-- | FIXME not sure if this is the correct way to downsample
-- maybe it is better to "distribute" the charge to every level
-- instead of propagating events
updatePyramid :: [UMV.IOVector Neuron] -> UTCTime -> Float -> Int -> Int
-> IO [(Int, Int, Int, Float)]
updatePyramid accs now p x y = do
updatePyramidLevel 1 (accs !! 1) now p x y $ \x y -> do
putStrLn $ "level " ++ show 1 ++ " fired at " ++ show x ++ " " ++ show y
updatePyramidLevel 2 (accs !! 2) now p x y $ \x y -> do
putStrLn $ "level " ++ show 2 ++ " fired at " ++ show x ++ " " ++ show y
updatePyramidLevel 3 (accs !! 3) now p x y $ \x y -> do
putStrLn $ "level " ++ show 3 ++ " fired at " ++ show x ++ " " ++ show y
updatePyramidLevel 4 (accs !! 4) now p x y $ \x y -> do
putStrLn $ "level " ++ show 4 ++ " fired at " ++ show x ++ " " ++ show y
updatePyramidLevel 5 (accs !! 5) now p x y $ \x y -> do
putStrLn $ "level " ++ show 5 ++ " fired at " ++ show x ++ " " ++ show y
updatePyramidLevel 6 (accs !! 6) now p x y $ \x y -> do
putStrLn $ "level " ++ show 6 ++ " fired at " ++ show x ++ " " ++ show y
updatePyramidLevel 7 (accs !! 7) now p x y $ \x y -> do
putStrLn $ "level " ++ show 7 ++ " fired at " ++ show x ++ " " ++ show y
return []
unP U = 1
unP D = -1
isUEvent (qview -> (p,_,_,_)) = p == U
isDEvent (qview -> (p,_,_,_)) = p == D
infix 4 <$$>
f <$$> x = fmap (fmap f) x
main = do
startTime <- getCurrentTime
accs <- mapM (\s -> UMV.replicate (s*s) (0,startTime)) imgSizes :: IO [UMV.IOVector Neuron]
-- read aedat file as specified on the commandline
[filename] <- getArgs
(Right es) <- V.filter isUEvent . V.fromList <$$> readDVSData filename
spikes <- forM es $ \(qview -> (p,x,y,t)) -> do
let now = startTime .+^ t
updatePyramid accs now (unP p) (fromIntegral x) (fromIntegral y)
let spikes' = asum spikes
putStrLn "done"
| fhaust/aer-utils | src/Data/AER/SIFT.hs | mit | 4,232 | 0 | 40 | 1,281 | 1,450 | 762 | 688 | 79 | 2 |
{-# LANGUAGE Arrows #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE TemplateHaskell #-}
module Db.Place
( Place'(Place)
, NewPlace
, Place
, placeQuery
, allPlaces
, getPlace
, insertPlace
, upsertPlaceByName
, placeId
, placeName
, placePlaceCategoryId
) where
import BasePrelude hiding (optional)
import Control.Lens
import Data.Profunctor.Product.TH (makeAdaptorAndInstance)
import Data.Text (Text)
import Opaleye
import Db.Internal
data Place' a b c = Place
{ _placeId :: a
, _placeName :: b
, _placePlaceCategoryId :: c
} deriving (Eq,Show)
makeLenses ''Place'
type Place = Place' Int Text (Maybe Int)
type PlaceColumn = Place' (Column PGInt4) (Column PGText) (Column (Nullable PGInt4))
makeAdaptorAndInstance "pPlace" ''Place'
type NewPlace = Place' (Maybe Int) Text (Maybe Int)
type NewPlaceColumn = Place' (Maybe (Column PGInt4)) (Column PGText) (Column (Nullable PGInt4))
placeTable :: Table NewPlaceColumn PlaceColumn
placeTable = Table "place" $ pPlace Place
{ _placeId = optional "id"
, _placeName = required "name"
, _placePlaceCategoryId = required "place_category_id"
}
placeQuery :: Query PlaceColumn
placeQuery = queryTable placeTable
allPlaces :: CanDb c e m => m [Place]
allPlaces = liftQuery placeQuery
insertPlace :: CanDb c e m => NewPlace -> m Int
insertPlace =
liftInsertReturningFirst placeTable (view placeId) . packNew
findPlaceByName :: CanDb c e m => Text -> m (Maybe Place)
findPlaceByName n = liftQueryFirst $ proc () -> do
a <- placeQuery -< ()
restrict -< a^.placeName .== pgStrictText n
returnA -< a
upsertPlaceByName :: CanDb c e m => NewPlace -> m Int
upsertPlaceByName na = do
a <- findPlaceByName (na^.placeName)
maybe (insertPlace na) (pure . (^.placeId)) a
getPlace :: CanDb c e m => Int -> m (Maybe Place)
getPlace i = liftQueryFirst $ proc () -> do
p <- placeQuery -< ()
restrict -< p^.placeId .== pgInt4 i
returnA -< p
packNew :: NewPlace -> NewPlaceColumn
packNew = pPlace Place
{ _placeId = fmap pgInt4
, _placeName = pgStrictText
, _placePlaceCategoryId = maybeToNullable . fmap pgInt4
}
| benkolera/talk-stacking-your-monads | code-classy/src/Db/Place.hs | mit | 2,351 | 2 | 11 | 528 | 719 | 378 | 341 | 69 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE RecordWildCards, NamedFieldPuns #-}
{-# LANGUAGE TupleSections #-}
module Main where
import Data.Maybe (mapMaybe)
import Control.Monad
import Control.Monad.State
import qualified Data.ByteString.Lazy as T (ByteString)
import Data.Aeson
import GHC.Generics
import System.Directory (listDirectory)
import Data.List (isSuffixOf)
import Types
import Monad
import Iterate
import BroadcastServer
import Debug.Trace
data Command = Reset | Connect
| RawTuple {rawLabel :: Label, rawNodes :: [Node]}
-- TODO: these should be a logical relation
-- | Hover {ref :: Node} | UnHover {ref :: Node}
deriving (Generic, Show)
deriving instance Generic Label
deriving instance Generic Id
deriving instance Generic Node
deriving instance Generic Polarity
instance ToJSON Label where
toEncoding = genericToEncoding defaultOptions
instance ToJSON Id where
toEncoding = genericToEncoding defaultOptions
instance ToJSON Node where
toEncoding = genericToEncoding defaultOptions
instance ToJSON Polarity where
toEncoding = genericToEncoding defaultOptions
instance ToJSON Command where
toEncoding = genericToEncoding defaultOptions
instance FromJSON Label where
instance FromJSON Id where
instance FromJSON Node where
instance FromJSON Command where
jsCommands =
[ "js/element"
, "js/attr"
, "js/edit"
, "js/text"
, "refresh-code-mirror"
, "child"
, "background-color"
, "js/style"
, "class"
]
decodeCommand = decode
convert :: Msg -> Maybe (Polarity, Label, [Node], Node, Bool)
convert (MT p t) | not (fix (label t) `elem` jsCommands) = Nothing
where
fix (LA s _) = L s
convert (MT p T{..}) = Just (p, label, nodes, NNode (Id tid), fix tval)
where
fix (Truth t) = t
fix NoVal = True
-- TODO!
fix (TVNode n) = True
-- TODO remove arity tags?
encodeEvents :: [Msg] -> T.ByteString
encodeEvents = encode . mapMaybe convert
data State = State PS SystemState InterpreterState
type Init = (PS, DB, [Msg])
-- returns result of removing suffix, if it is a suffix
msuffix :: String -> String -> Maybe String
msuffix suf s = fix (reverse suf) (reverse s)
where
fix [] s = Just $ reverse s
fix (a:as) (b:bs) | a == b = fix as bs
fix _ _ = Nothing
scriptSuffix = ".arrow"
dataSuffix = ".stuff"
loadStuff dir str = do
f <- readFile (dir ++ "/" ++ str ++ dataSuffix)
let ls = lines f
return $ do
fid <- freshNode
ls <- mapM (uncurry $ toLine fid) $ zip [0..] ls
eof <- eof fid (length ls)
fmsg <- fileMsg fid
return $ fmsg : eof : ls
where
toLine f i l =
MT Positive <$> packTuple (LA "io/line" 3, [f, NInt i, NString l]) (Extern [])
eof f i =
MT Positive <$> packTuple (LA "io/eof" 2, [f, NInt i]) (Extern [])
fileMsg f =
MT Positive <$> packTuple (LA "io/file" 1, [f]) (Extern [])
loadDirectory dir = do
dirfiles <- listDirectory dir
let scripts = mapMaybe (msuffix scriptSuffix) dirfiles
resources = mapMaybe (msuffix dataSuffix) dirfiles
files = map (\(i, s) -> (show i, dir ++ "/" ++ s ++ scriptSuffix)) (zip [1..] scripts)
fileMsgsM <- sequence <$> mapM (loadStuff dir) resources
strs <- mapM (readFile . snd) files
let fix s = do
n1 <- freshNode
m1 <- packTuple (LA "make-app" 2, [n1, NString s]) (Extern [])
return $ CMsg (MT Positive m1)
return $ runStack emptySS emptyIS $ do
ps <- initMetaPS (zip (map fst files) strs)
ms <- lift $ mapM (fix . fst) files
fileMsgs <- lift $ concat <$> fileMsgsM
-- register rulesets
(output1, ps1) <- solve ms ps
worker <- gets worker_id
(output2, ps2) <- solve (map (CActor worker) $ fileMsgs) ps1
return (output2++output1, ps2)
makeDB1 = do
let files = [ ("refl", "ui/components/refl.arrow")
, ("button", "ui/components/button.arrow")
-- ? TODO not using this:
, ("rules", "ui/components/rule-set.arrow") ]
strs <- mapM (readFile . snd) files
let fix s = do
n1 <- freshNode
m1 <- packTuple (LA "make-app" 2, [n1, NString s]) (Extern [])
return $ CMsg (MT Positive m1)
return $ runStack emptySS emptyIS $ do
ps <- initMetaPS (zip (map fst files) strs)
ms <- lift $ mapM (fix . fst) files
-- register rulesets
(output1, ps1) <- solve ms ps
return (output1, ps1)
makeDB2 = do
let files = [ ("ui", "ui/jelly/io.arrow")
, ("level", "ui/jelly/level.arrow")
, ("logic", "ui/jelly/logic.arrow")
]
strs <- mapM (readFile . snd) files
let fix s = do
n1 <- freshNode
m1 <- packTuple (LA "make-app" 2, [n1, NString s]) (Extern [])
return $ CMsg (MT Positive m1)
return $ runStack emptySS emptyIS $ do
ps <- initMetaPS (zip (map fst files) strs)
ms <- lift $ mapM (fix . fst) files
-- register rulesets
(output1, ps1) <- solve ms ps
return (output1, ps1)
makeDB4 = loadDirectory "ui/slides"
noDebug = False
handler connId msg s0@(State ps ss is) =
case decodeCommand msg of
Just Reset -> do
putStrLn "reset"
(((msgs, ps'), ss'), is') <- makeDB4
-- TODO only send relevant tuples
--let (_, outputEvents) = step2 msgs emptyFS
putStrLn $ "init: " ++ unlines (map ppMsg msgs)
return (Just (encodeEvents msgs), State ps' ss' is')
Just Connect -> do
putStrLn "not implemented"
return (Nothing, s0)
Just RawTuple{rawLabel, rawNodes} -> do
putStrLn "parsed event"
let
(((msgs, ps'), ss'), is') = runStack ss is $ do
-- reset gas limit
lift $ setGas 500
-- TODO mark tuple with connection id
let ns = rawNodes
l = LA (lstring rawLabel) (length ns)
t <- lift $ packTuple (l, ns) (Extern [])
worker <- gets worker_id
let msg = (CActor worker (MT Positive t))
solve [msg] ps
unless noDebug $ do
putStrLn "new"
mapM_ (putStrLn . ppMsg) msgs
putStrLn "done"
return (Just (encodeEvents msgs), State ps' ss' is')
Nothing -> do
putStrLn "decode failed"
return (Nothing, s0)
main = do
putStrLn "server starting"
runServer (State emptyPS emptySS emptyIS) handler
| kovach/web2 | server/Main.hs | mit | 6,359 | 0 | 22 | 1,639 | 2,286 | 1,154 | 1,132 | 165 | 4 |
module Main where
import System.Environment
main :: IO ()
main = do
putStrLn ("Type a name:")
args <- getLine
putStrLn ("Hello, " ++ args) | rodrigoalviani/haskell-exercises | e01.03.hs | mit | 145 | 0 | 9 | 30 | 53 | 27 | 26 | 7 | 1 |
module Network.CryptoNote.P2P.Command.GetObjects.Request where
import Network.CryptoNote.Crypto.Hash (Hash, Id)
-- cryptonote_protocol_handler.h
-- cryptonote_protocol_defs.h
-- #define BC_COMMANDS_POOL_BASE 2000
-- const static int ID = BC_COMMANDS_POOL_BASE + 3;
data RequestGetObjects = RequestGetObjects
{ txs :: [Hash Id]
, blocks :: [Hash Id]
} deriving (Show, Eq)
| nvmd/hs-cryptonote | src/Network/CryptoNote/P2P/Command/GetObjects/Request.hs | mit | 390 | 0 | 10 | 61 | 73 | 47 | 26 | 6 | 0 |
module Graphics.CG.Primitives.BoundBox(BoundBox (..), boundPoints, pointInBoundBox) where
import Graphics.Gloss.Data.Point
data BoundBox a = BoundBox !a !a !a !a deriving (Show, Eq)
boundPoints :: Ord a => [(a, a)] -> BoundBox a
boundPoints ps =
let
xs = map fst ps
ys = map snd ps
in BoundBox (minimum xs) (minimum ys) (maximum xs) (maximum ys)
pointInBoundBox :: Point -> BoundBox (Float) -> Bool
pointInBoundBox pt (BoundBox a b c d) = pointInBox pt (a, b) (c, d)
| jagajaga/CG-Haskell | Graphics/CG/Primitives/BoundBox.hs | mit | 493 | 0 | 9 | 102 | 216 | 115 | 101 | 19 | 1 |
-- Problem 7
-- (**) Flatten a nested list structure.
--
-- We have to define a new data type, because lists in Haskell are homogeneous.
-- data NestedList a = Elem a | List [NestedList a]
-- > flatten (Elem 5)
-- [5]
-- > flatten (List [Elem 1, List [Elem 2, List [Elem 3, Elem 4], Elem 5]])
-- [1,2,3,4,5]
-- > flatten (List [])
-- []
data NestedList a = Elem a | List [NestedList a]
flatten :: NestedList a -> [a]
flatten (Elem x) = [x]
flatten (List []) = []
flatten (List (x:xs)) = flatten x ++ flatten (List xs)
| usami-k/H-99-Ninety-Nine-Haskell-Problems | 01-10/07.hs | mit | 522 | 0 | 9 | 109 | 120 | 67 | 53 | 5 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Game.Halma.TelegramBot.View.Pretty
( prettyUser
, localeFlag
, teamEmoji
) where
import Game.Halma.Board
import Game.Halma.TelegramBot.Model.Types
import Data.Monoid ((<>))
import qualified Data.Text as T
import qualified Web.Telegram.API.Bot as TG
prettyUser :: TG.User -> T.Text
prettyUser user =
case TG.user_username user of
Just username -> "@" <> username
Nothing ->
TG.user_first_name user <>
maybe "" (" " <>) (TG.user_last_name user)
localeFlag :: LocaleId -> T.Text
localeFlag localeId =
case localeId of
De -> "\127465\127466" -- german flag :de:
En -> "\127468\127463" -- union jack :gb:
teamEmoji :: Team -> T.Text
teamEmoji dir =
case dir of
North -> "\128309" -- :large_blue_circle: for blue
Northeast -> "\128154" -- :green_heart: for green
Northwest -> "\128156" -- :purple_heart: for purple
South -> "\128308" -- :red_circle: for red
Southeast -> "\9899" -- :medium_black_circle: for black
Southwest -> "\128310" -- :large_orange_diamond: for orange | timjb/halma | halma-telegram-bot/src/Game/Halma/TelegramBot/View/Pretty.hs | mit | 1,091 | 0 | 12 | 220 | 244 | 141 | 103 | 31 | 6 |
module Signs.Term where
{-
- lambda term ADT
- parser
- pretty printer
- export to latex
-}
import Prelude hiding (drop)
import Signs.Tex
import Signs.Type
import Signs.Parse
import Data.Char
import Text.ParserCombinators.Parsec hiding (option)
import Text.ParserCombinators.Parsec.Expr
import Control.Monad
import Data.List hiding (drop)
import qualified Data.Map as Map
tests =
["\\x.x"
,"\\x.\\f.\\d.option(x,f,d)"
,"\\f.f (John :: t)"
,"John :: t"
,"\\x. bla x"
,"\\x . \\ y . y x"
,"\\x y . y x"
]
type Variable = String
-- data type of terms
infixl 9 `App`
data Term
-- basic
= Var Variable
| MetaVar Variable
| Con { conName :: String , conType :: Type }
| App (Term) (Term)
| Lam Variable (Term)
| MetaLam Variable (Term)
-- tuples
| Pair (Term) (Term)
| Fst (Term )
| Snd (Term )
-- sums (not used atm)
| L (Term)
| R (Term)
| Case (Term) (Term) (Term)
-- option
| Nil
| NotNil (Term)
| CaseO (Term) (Term) (Term)
deriving (Ord,Eq)
instance Show Term where
show t = case t of
Var v -> v
(Con con (Atom "f")) -> concat ["\"",con,"\""]
(App (App (Con "+" _) m) n) -> concat [show m ," ",show n]
(App (App (Con "And" _) m) n) -> concat [show m ,"/\\",show n]
(Con con t) -> con
App m n -> concat ["(",show m," ",show n,")"]
Lam v b -> concat ["\\",v,".",show b]
instance Parse Term where parseDef = term
term = buildExpressionParser termtable (simpleterm term con)
<?> "expression"
term' = buildExpressionParser termtable (simpleterm term' con')
<?> "expression"
ident = identifier
var = liftM Var (many1 lower)
close :: Term -> Term
close term = let
freeVars = free term in
foldr Lam term freeVars
simpleterm trm constant = do {
t <- choice
[ pparens trm
, omitted <?> "*"
, emptystring
, identity
, constant <?> "constant"
, lam ident trm <?> "lambda abst"
, forall_ ident trm
, exists_ ident trm
, option trm
, var
-- , app (pparens trm <|> constant <|> var) (pparens trm)
]
; spaces
; return t
} <?> "simple expression"
app m n = m `chainl1` ( do { string " " ; n' <- n ; return (flip App) } )
t = Atom "t"
tt = t :-> t
f = Atom "f"
ff = f :-> f
fff = f :-> f :-> f
-- Parsing lambda terms
omitted = reserved "*" >> return Nil
emptystring = reserved "_" >> return (Con "Eps" (Atom "f"))
identity = do
reserved "id"
return (Lam "x" (Var "x") )
-- parses a single lambda var : a ab abc a' a'' a'''
variableParser = do
letters <- many1 lower
quotes <- many (char '\'')
return $ letters++quotes
-- parses a lambda var + body
lam :: Parser String -> Parser Term -> Parser Term
lam pVar trm = do
string "\\"
vars <- (sepBy1 (variableParser) (skipMany1 space)) -- lowercase string, separated by multiple spaces
string "."
spaces
body <- trm
return (expandLambdas vars body)
-- expandLambdas [a,b..z] m = Lam a (Lam b .. (Lam z m) .. )
expandLambdas :: [String] -> Term -> Term
expandLambdas strings body = case strings of
[] -> body
(var:vars) -> Lam var (expandLambdas vars body)
forall_ vr trm = do
reserved "forall"
spaces
var <- vr
spaces
string "."
spaces
term <- trm
return (for_all var term)
<?> "universal quantifier expression"
-- exists 'pVariable' . 'pTerm'
exists_ pVariable pTerm = do
reserved "exists"
spaces
var <- pVariable
spaces
string "."
spaces
term <- pTerm
return (exists var term)
<?> "existential quantifier expression"
con = choice
[ agent
, patient
, goal
, do char '\"'
x <- many $ noneOf "\""
char '\"'
return (Con x (Atom "f"))
, do
x <- upper
xs <- many $ alphaNum <|> oneOf "_'-"
spaces
reserved "::"
spaces
typ <- typ
return (Con (x:xs) typ)
]
con' = (do
char '\"'
x <- many $ noneOf "\""
char '\"'
return (Con x (Atom "f"))
)
<|>
do
x <- upper
xs <- many $ upper <|> lower <|> char '\''
--return (Var (x:xs))
return (Con (x:xs) Void)
option trm = do
{ reserved "option"
; string "(" ; spaces
; x <- trm ; spaces
; string "," ; spaces
; f <- trm ; spaces
; string "," ; spaces
; d <- trm ; spaces
; string ")"
; return (CaseO x f d)
}
agent = do
{ reserved "AG"
; return $ Con "AG" ( (Atom "e" :-> (Atom "e" :-> Atom "t")) )
}
patient = do
{ reserved "PAT"
; return $ Con "PAT" ( (Atom "e" :-> (Atom "e" :-> Atom "t")) )
}
goal = do
{ reserved "GOAL"
; return $ Con "GOAL" ( (Atom "e" :-> (Atom "e" :-> Atom "t")) )
}
termtable =
[
[ postfix "^" (NotNil)]
, [ binary "+" (.+) AssocRight , binary "/\\" (/\) AssocLeft]
, [ binary "\\/" (\/) AssocRight]
, [ binary "@" (composition) AssocLeft]
, [ binary "" (App) AssocLeft]
]
nextFreshVar term = head $ (map (:[]) ['a'..]) \\ free term
composition a b = let fv = head $ (map (:[]) ['a'..]) \\ free (App a b) in
Lam fv $ a `App` (b `App` (Var fv))
f .+ g = (Con "+" (Atom "f" :-> Atom "f" :-> Atom "f")) `App` f `App` g
f /\ g = (Con "And" (Atom "t" :-> Atom "t" :-> Atom "t")) `App` f `App` g
f \/ g = (Con "Or" (Atom "t" :-> Atom "t" :-> Atom "t")) `App` f `App` g
neg f = (Con "Not" (Atom "t" :-> Atom "t")) `App` f
for_all var term = Con "forall" ( (Atom "e" :-> Atom "t") :-> Atom "t") `App` (Lam var term)
exists var term = Con "exists" ( (Atom "e" :-> Atom "t") :-> Atom "t") `App` (Lam var term)
stringConcat a b = a .+ b
-- free : takes a term and returns a list with all free (unbound) variables in the term
free :: Term -> [Variable]
free term = case term of
Con c t -> []
Nil -> []
NotNil v -> free v
Var v -> [v]
Fst v -> free v
Snd v -> free v
L t -> free t
R t -> free t
App u s -> free u `union` free s
Pair u s -> free u `union` free s
Lam x u -> free u \\ [x]
(Case m l r) -> foldr union [] $ map free [m,l,r]
(CaseO m l r) -> foldr union [] $ map free [m,l,r]
instance Tex Term where
tex term = case term of
Nil -> text "\\ast"
NotNil a -> hcat [text "\\overline{ " , tex a , text "}" ]
Var c -> tex $ c
Con s t -> text $ "{ \\sf " ++ s ++ "}"
App (App (Con "Not" (Atom "f" :-> Atom "f" :-> Atom "f")) m) n -> hcat [tex m ,text "\\bullet " ,tex n]
App (App (Con "+" (Atom "f" :-> Atom "f" :-> Atom "f")) m) n -> hcat [tex m ,text "\\bullet " ,tex n]
App (App (Con "And" (Atom "t" :-> Atom "t" :-> Atom "t")) m) n -> hcat [tex m ,text "\\wedge " ,tex n]
App (App (Con "Or" (Atom "t" :-> Atom "t" :-> Atom "t")) m) n -> hcat [tex m ,text "\\vee " ,tex n]
App m n -> hcat [tex m,text "(", tex n, text ")"]
Pair m n -> hcat [text"\\langle", tex m ,text ",", tex n ,text"\\rangle"]
L m -> hcat [text"inl(", tex m,text")" ]
R m -> hcat [text"inr(", tex m,text")" ]
Lam v n -> hcat[text"( \\lambda ", tex v,text" . ", tex n ,text" )"]
Fst n -> hcat [text"fst" , parens $ tex n ]
Snd n -> hcat [text"snd" , parens $ tex n ]
Case m l r -> hcat [text"case(",tex m ,text", ",tex l,text",",tex r,text")"]
CaseO m l r -> hcat [text"caseO(",tex m ,text", ",tex l,text",",tex r,text")"]
texTerm style@"SEM" term = let tex' = texTerm "SEM" in case term of
Nil -> text "\\ast"
NotNil a -> hcat [text "\\overline{ " , tex' a , text "}" ]
Var "e" -> text $ "\\e"
Var c -> text $ addPrimeIfUpperCase c
Con "TRUE" (Atom "t") -> text "\\top"
Con x t -> hcat [text "\\sem{",text $ map toLower x,text "_{" , texStyle style t ,text"}}" ]
App (App (Con "And" (Atom "t" :-> Atom "t" :-> Atom "t")) m) n -> hcat [tex' m ,text "\\wedge " ,tex' n]
App (App (Con "Or" (Atom "t" :-> Atom "t" :-> Atom "t")) m) n -> hcat [tex' m ,text "\\vee " ,tex' n]
App (Con "Not" (Atom "t" :-> Atom "t" )) m -> hcat [text "\\neg " , tex' m]
App (Con "forall" ((Atom "e" :-> Atom "t") :-> Atom "t")) (Lam var term) -> hcat [text "\\forall ",texV var,text ".",tex' term]
App (Con "exists" ((Atom "e" :-> Atom "t") :-> Atom "t")) (Lam var term) -> hcat [text "\\exists ",texV var,text ".",tex' term]
App (Con "exists" ((Atom "e" :-> Atom "t") :-> Atom "t")) (Con c (Atom "e" :-> Atom "t")) -> hcat [text "\\exists(",tex' term]
App (App (Con "AG" (Atom "e" :-> Atom "e" :-> Atom "t")) m) n -> hcat [text "\\AG(",tex' m , text "," , tex' n,text ")"]
App (App (Con "PAT" (Atom "e" :-> Atom "e" :-> Atom "t")) m) n -> hcat [text "\\PAT(",tex' m , text "," , tex' n,text ")"]
App (App (Con "GOAL" (Atom "e" :-> Atom "e" :-> Atom "t")) m) n -> hcat [text "\\GOAL(",tex' m , text "," , tex' n,text ")"]
App m n -> hcat $ [tex' m,parens $ tex' n]
Pair m n -> hcat [text"\\langle", tex' m ,text ",", tex' n ,text"\\rangle"]
L m -> hcat [text"inl(", tex' m,text")" ]
R m -> hcat [text"inr(", tex' m,text")" ]
Lam v n -> hcat[text" \\lambda ", texV $ addPrimeIfUpperCase v,text" . ", tex' n ,text" "]
Fst n -> hcat [text"fst" , parens $ tex' n ]
Snd n -> hcat [text"snd" , parens $ tex' n ]
Case m l r -> hcat [text"case(",tex' m ,text", ",tex' l,text",",tex' r,text")"]
CaseO m l r -> text "\\option(" <> tex' m <> text "\\hskip-3pt" <> narray [[text", ",tex' l,text",",tex' r,text")"]]
texTerm n x = error $ "missing case in texTerm for "++ n ++" for " ++ show x
texV x = text $ if x == "e" then "\\e" else x
addPrimeIfUpperCase [c]
| isUpper c = [toLower c , '\'' ]
| otherwise = [c]
addPrimeIfUpperCase x = x
-- the homomorphic extension of a monadic function acting on constants
hextendM :: Monad m => (Term -> m Term) -> Term -> m Term
hextendM f term = let cmap' = hextendM f in
case term of
constant@(Con c t) -> f constant
Var c -> return $ Var c
App m n -> liftM2 App (cmap' m) (cmap' n)
Lam v m -> cmap' m >>= (\x -> return $ Lam v x)
Pair m n -> liftM2 Pair (cmap' m) (cmap' n)
Fst m -> liftM Fst (cmap' m)
Snd n -> liftM Snd (cmap' n)
L m -> liftM L (cmap' m)
R n -> liftM R (cmap' n)
Case o l r -> liftM3 Case (cmap' o) (cmap' l) (cmap' r)
Nil -> return Nil
NotNil j -> liftM NotNil (cmap' j)
CaseO o j d -> liftM3 CaseO (cmap' o) (cmap' j) (cmap' d)
| ChrisBlom/Signs | src/Signs/Term.hs | mit | 10,222 | 0 | 18 | 2,753 | 4,938 | 2,432 | 2,506 | 263 | 24 |
module P03 where
least_divisor :: Integer -> Integer -> Integer
least_divisor k n =
let factors = dropWhile (\x -> n `mod` x > 0) [k .. n]
in case factors of
[] -> n
f:fs -> f
pfactors k n =
if d == n
then [n]
else d : pfactors d (n `div` d)
where d = least_divisor k n
solution = maximum $ pfactors 2 600851475143
main = do print solution
| drcabana/euler-fp | source/hs/P03.hs | epl-1.0 | 373 | 0 | 13 | 107 | 169 | 90 | 79 | 14 | 2 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleInstances, TypeSynonymInstances, OverlappingInstances #-}
module NLP.GenI.Test.Semantics ( suite ) where
import Control.Applicative ( (<$>), (<*>) )
import Control.Arrow ( first )
import Data.Maybe ( isJust, maybeToList )
import qualified Data.Map as Map
import Control.Error
import NLP.GenI.Semantics
import NLP.GenI.GeniVal
import NLP.GenI.Pretty
import NLP.GenI.Test.GeniVal hiding ( suite )
import Test.HUnit
import Test.QuickCheck hiding (collect)
import Test.QuickCheck ( suchThat )
import Test.QuickCheck.Arbitrary
-- import Test.SmallCheck
-- import qualified Test.SmallCheck as SmallCheck
-- import Test.SmallCheck.Series
import Test.Framework
import Test.Framework.Providers.HUnit
-- import Test.Framework.Providers.SmallCheck
import Test.Framework.Providers.QuickCheck2
-- ----------------------------------------------------------------------
-- Testing
-- ----------------------------------------------------------------------
suite :: Test.Framework.Test
suite = testGroup "NLP.GenI.Semantics"
[ testGroup "subsumeLiteral"
[ testProperty "reflexive" prop_subsumePred_reflexive
, testProperty "antisymmetric" prop_subsumePred_antisymmetric
]
, testGroup "subsumeSem"
[ testProperty "reflexive" prop_subsumeSem_reflexive
-- , testProperty "only return matching portion" prop_subsumeSem_length
, testCase "works 1" $ assertBool "" $ not . null $ sem1 `subsumeSem` sem2
, testCase "works 2" $ assertBool "" $ not . null $ sem1 `subsumeSem` (sem2 ++ sem2)
, testCase "distinct" $ assertBool "" $ null $ (sem1 ++ sem1) `subsumeSem` sem2
]
, testGroup "unifySem"
[ testCase "works x" $ assertMatchSem [ sem_x ] $ unifySem sem1 sem_x
, testCase "works xy" $ assertMatchSem [ sem_xy ] $ unifySem sem_x sem_y
, testCase "works xV" $ assertMatchSem [ sem_xy, sem_xy ] $ unifySem sem1 sem_xy
]
{-
[ testProperty "reflexive" prop_unifyPred_reflexive
, testProperty "antisymmetric" prop_unifyPred_antisymmetric
]
-}
]
where
assertMatchSem sems xs = assertEqual "" (map sortSem sems) $ map fst xs
sem1 = [ lit1 ]
sem2 = sem_x
sem_x = [ lit_x ]
sem_y = [ lit_y ]
sem_xy = [ lit_x, lit_y ]
lit1 = Literal (mkGConstNone "a") (mkGConstNone "apple") [mkGVarNone "A"]
lit_x = Literal (mkGConstNone "a") (mkGConstNone "apple") [mkGConstNone "x"]
lit_y = Literal (mkGConstNone "a") (mkGConstNone "apple") [mkGConstNone "y"]
prop_subsumeSem_length :: [GTestLiteral] -> [GTestLiteral] -> Property
prop_subsumeSem_length lits1 lits2 =
not (null sboth) ==>
all (\x -> length (fst x) == s1_len) sboth
where
sboth = s1 `subsumeSem` s2
s1_len = length s1
s1 = map fromGTestLiteral lits1
s2 = map fromGTestLiteral lits2
prop_subsumeSem_reflexive :: [GTestLiteral] -> Bool
prop_subsumeSem_reflexive lits = not . null $ s `subsumeSem` s
where
s = map fromGTestLiteral lits
prop_subsumePred_reflexive :: GTestLiteral -> Bool
prop_subsumePred_reflexive pr = s `ttSubsumeLiteral` s
where
s = fromGTestLiteral pr
prop_subsumePred_antisymmetric :: SubsumedPair GTestLiteral -> Bool
prop_subsumePred_antisymmetric (SubsumedPair x_ y_) =
x `tt_literal_equiv` y || not (y `ttSubsumeLiteral` x)
where
x = fromGTestLiteral x_
y = fromGTestLiteral y_
class Subsumable a where
subsume :: a -> a -> [(a, Subst)]
instance Subsumable GeniVal where
subsume x y = fromUnificationResult (x `subsumeOne` y)
instance Subsumable GeniValLite where
subsume x y = map (first GeniValLite) . fromUnificationResult
$ fromGeniValLite x `subsumeOne` fromGeniValLite y
instance Subsumable (Literal GeniVal) where
subsume x y = maybeToList . hush $ x `subsumeLiteral` y
instance Subsumable GTestLiteral where
subsume x y = map (first tp) . maybeToList . hush
$ fromGTestLiteral x `subsumeLiteral` fromGTestLiteral y
where
tp (Literal x y z) = GTestLiteral x y z
instance (Arbitrary a, Show a, Subsumable a) => Show (SubsumedPair a) where
show (SubsumedPair x y) = show (x,y)
data (Subsumable a, Arbitrary a) => SubsumedPair a = SubsumedPair a a
unzipSubsumedPair :: (Subsumable a, Arbitrary a) => [SubsumedPair a] -> ([a],[a])
unzipSubsumedPair = unzip . map helper
where
helper (SubsumedPair x y) = (x,y)
instance (Show a, DescendGeniVal a, Collectable a, Subsumable a, Arbitrary a) => Arbitrary (SubsumedPair a) where
arbitrary = do
x <- finaliseVars "-1" `fmap` arbitrary
y <- (finaliseVars "-2" `fmap` arbitrary) `suchThat` (\y -> not (null (x `subsume` y)))
return (SubsumedPair x y)
instance Arbitrary (SubsumedPair GTestLiteral) where
arbitrary = do
(SubsumedPair h1 h2) <- arbitrary
(SubsumedPair p1 p2) <- arbitrary
(args1, args2) <- unzipSubsumedPair `fmap` arbitrary
return $ SubsumedPair (mkPred h1 p1 args1) (mkPred h2 p2 args2)
where
mkPred x y zs = GTestLiteral (fromGeniValLite x)
(fromGeniValLite y)
(map fromGeniValLite zs)
isSuccess :: UnificationResult -> Bool
isSuccess NLP.GenI.GeniVal.Failure = False
isSuccess (SuccessSans _) = True
isSuccess (SuccessRep _ _) = True
isSuccess (SuccessRep2 _ _ _) = True
fromUnificationResult :: UnificationResult -> [(GeniVal,Subst)]
fromUnificationResult NLP.GenI.GeniVal.Failure = []
fromUnificationResult (SuccessSans g) = [(g, Map.empty)]
fromUnificationResult (SuccessRep v g) = [(g, Map.fromList [(v,g)])]
fromUnificationResult (SuccessRep2 v1 v2 g) = [(g, Map.fromList [(v1,g),(v2,g)])]
ttSubsumeLiteral :: Literal GeniVal -> Literal GeniVal -> Bool
ttSubsumeLiteral x y = isRight (subsumeLiteral x y)
tt_literal_equiv :: Literal GeniVal -> Literal GeniVal -> Bool
tt_literal_equiv (Literal h1 p1 as1) (Literal h2 p2 as2) =
and $ zipWith tt_equiv (h1 : p1 : as1) (h2 : p2 : as2)
fromGTestLiteral :: GTestLiteral -> Literal GeniVal
fromGTestLiteral (GTestLiteral h r as) = Literal h r as
data GTestLiteral = GTestLiteral GeniVal GeniVal [GeniVal]
instance Arbitrary (Literal GeniVal) where
arbitrary = Literal <$> arbitrary
<*> arbitrary
<*> arbitrary
shrink l = Literal <$> shrink (lHandle l)
<*> shrink (lPredicate l)
<*> shrinkList2 shrink (lArgs l)
instance Show GTestLiteral where
show = show . fromGTestLiteral
instance Arbitrary GTestLiteral where
arbitrary =
do handle <- arbitraryGConst
rel <- arbitrary
args <- arbitrary
return $ GTestLiteral handle (fromGeniValLite rel) (map fromGeniValLite args)
-- ----------------------------------------------------------------------
-- SmallCheck
-- ----------------------------------------------------------------------
{-
instance Serial a => Serial (Literal a) where
series = cons3 Literal
coseries rs d
= [\ t ->
case t of
Literal x1 x2 x3 -> t0 x1 x2 x3
| t0 <- alts3 rs d]
-}
{-!
-- deriving instance (Arbitrary a, Serial a) => Serial (SubsumedPair a)
-- deriving instance Serial GTestLiteral
!-}
| kowey/GenI | geni-test/NLP/GenI/Test/Semantics.hs | gpl-2.0 | 7,161 | 0 | 16 | 1,439 | 2,043 | 1,089 | 954 | 127 | 1 |
-- | Playing with Traversables.
--
-- Sources:
-- - https://en.wikibooks.org/wiki/Haskell/Traversable
module Lib where
import Control.Applicative
import Control.Monad.State.Lazy
import Data.Foldable
import Data.Monoid
someFunc :: IO ()
someFunc = putStrLn "someFunc"
-- * Functors made for walking
data Tree a = Leaf a | Branch (Tree a) (Tree a) deriving (Show)
instance Functor Tree where
fmap f (Leaf a) = Leaf (f a)
fmap f (Branch lt rt) = Branch (fmap f lt) (fmap f rt)
instance Foldable Tree where
foldr f z (Leaf a) = f a z
-- foldr :: (a -> b -> b) -> b -> Tree a -> b
foldr f z (Branch lt rt) = foldr f (foldr f z rt) lt
instance Traversable Tree where
-- traverse :: Applicative f => (a -> f b) -> Tree a -> f (Tree b)
traverse f (Leaf a) = Leaf <$> f a
traverse f (Branch lt rt) = Branch <$> traverse f lt <*> traverse f rt
-- * Interpretations of Traversable
-- ** Building an intuition for sequences
--
-- > sequenceA [[0, 1, 2]]
-- > [[0],[1],[2]]
--
-- > sequenceA [[0, 1, 2], [3]]
-- > [[0,3],[1,3],[2,3]]
--
-- > sequenceA [[2, 3], [4, 5]]
-- > [[2,4],[2,5],[3,4],[3,5]]
--
-- > sequenceA [[0, 1], [2, 3], [4, 5]]
-- > [[0,2,4],[0,2,5],[0,3,4],[0,3,5],[1,2,4],[1,2,5],[1,3,4],[1,3,5]]
-- ** Exercises
-- | Matrix type. Matrices are represented in row-major order, e.g. the matrix:
--
-- ```
-- | 1 2 |
-- | 3 4 |
-- | 5 6 |
-- ```
--
-- Is represented as the following list:
--
-- > [[1, 2], [3, 4], [5, 6]]
--
newtype Matrix a = Matrix { mtx :: [[a]] } deriving Show
instance Functor Matrix where
fmap f = Matrix . fmap (fmap f) . mtx
instance Foldable Matrix where
-- foldr :: (a -> b -> b) -> b -> Matrix a -> b
foldr f z = foldr f z . concat . mtx
instance Traversable Matrix where
-- traverse :: Applicative f => (a -> f b) -> Matrix a -> f (Matrix b)
traverse f m = Matrix <$> sequenceA (map (traverse f) (mtx m))
tstMatrix0 = Matrix [[0, 1], [2, 3]]
tstMatrix1 = Matrix [[5, 4, 3], [4, 0, 4], [7, 10, 3]]
transpose :: Matrix a -> Matrix a
transpose = Matrix . getZipList . traverse ZipList . mtx
-- Making sense out of this implementation:
--
-- > ZipList :: [a] -> ZipList a
-- > traverse ZipList :: Traversable t => t [b] -> ZipList (t b)
--
-- In particular when t = []:
--
-- > traverse ZipList :: Traversable t => [[b]] -> ZipList ([b])
--
-- > traverse ZipList [[0, 1], [2, 3]]
-- > traverse id [[0, 1], [2, 3]]
-- | The mapAccumL function behaves like a combination of fmap and foldl; it
-- applies a function to each element of a structure, passing an accumulating
-- parameter from left to right, and returning a final value of this
-- accumulator together with the new structure.
mapAccumL :: Traversable t => (a -> b -> (a, c)) -> a -> t b -> (a, t c)
-- (b -> a -> (a, c)) -> t b -> a -> (a, t c)
-- (b -> State a c) -> t b -> State a (t c)
-- traverse :: Applicative f => (b -> f c) -> t b -> f (t c)
mapAccumL f acc = undefined -- traverse (state . flip f)
moco :: Traversable t => (a -> (b -> (c, a))) -> t b -> State a (t c)
moco f = traverse (state . flip f)
mapAccumLS :: Traversable t => (b -> State a c) -> t b -> State a (t c)
mapAccumLS step t = traverse step t -- i.e. mapAccumLS = traverse
-- | This won't even compile :/ (taken from the Wiki...)
-- mapAccumL' :: Traversable t => (a -> b -> (a, c)) -> a -> t b -> (a, t c)
-- mapAccumL' step z t = runState (traverse (state . flip step) t) z
-- * The traversable laws
-- If t is an applicative homomorphism, then:
--
-- > t . traverse f = traverse (t . f) -- naturality
--
-- where
--
-- > t :: f a -> g a
--
-- We have:
--
-- > traverse :: (Applicative f, Traversable t) => (a -> f b) -> t a -> f (t b)
-- > f :: a -> f b
-- > t . f :: a -> g b
-- > traverse f :: t a -> f (t b)
--
-- And thus:
-- > t . traverse f :: t a -> g (t b)
-- > traverse (t . f) :: t a -> g (t b)
--
-- Regarding the remaining law we have:
--
-- traverse (Compose . fmap g . f) = Compose . fmap (traverse g) . traverse f -- composition
--
-- > f :: a -> f b
-- > g :: b -> g c
-- > Compose :: f (g z) -> Compose f g z
-- > traverse f :: t a -> f (t b)
-- > traverse g :: t b -> g (t c)
-- > fmap (traverse g) :: h (t b) -> h (g (t c))
-- > fmap (traverse g) . traverse f :: t a -> f (g (t b))
-- > Compose . (fmap (traverse g) . traverse f) :: t a -> Compose f g (t b)
-- > fmap g . f :: a -> f (g b)
-- > Compose . (fmap g . f) :: a -> Compose f g b
-- > traverse (Compose . (fmap g . f)) :: t a -> Compose f g (t b)
-- * Recovering `fmap` and `foldMap`
-- Let's recover `fmap`:
-- > fmap :: Functor f => (a -> b) -> f a -> f b
-- > traverse :: (Applicative f, Traversable t) => (a -> f b) -> t a -> f (t b)
-- > f :: a -> b
-- > Identity :: b -> Identity b
-- > Identity . f :: a -> Identity b
-- > traverse (Identity . f) :: t a -> Identity (t b)
--
-- > fmap :: (a -> b) -> t a -> t b
-- > fmap f = runIdentity . traverse (Identity . f)
-- What about foldmap
--
-- > foldMap :: (Monoid m, Foldable t) => (a -> m) -> t a -> m
-- > Const :: a -> Const a b
-- > f :: a -> m
-- > Const . f :: a -> Const m b
-- > traverse (Const . f) :: (Applicative (Const m), Traversable t)
-- => (a -> Const m b) -> t a -> Const m (t b)
| capitanbatata/sandbox | pw-traversables/src/Lib.hs | gpl-3.0 | 5,240 | 0 | 11 | 1,318 | 836 | 489 | 347 | 34 | 1 |
import Control.Monad
import Data.Char
main = forever $ do
l <- getLine
putStrLn $ map toUpper l
| medik/lang-hack | Haskell/LearnYouAHaskell/c09/capslocker.hs | gpl-3.0 | 101 | 0 | 9 | 22 | 39 | 19 | 20 | 5 | 1 |
-- Functions related to the management and creation of modules
module HandlerManagement
( addHandler
, EventHandler
) where
import qualified Data.Map as Map
import Network.Socket
import Control.Monad.State
import Request
addHandler :: Command -> EventHandler -> BotState -> BotState
addHandler command handler botState =
case handlers of
Nothing -> botState {botHandlers = Map.fromList [(command, [handler])]}
Just xs -> botState {botHandlers = Map.insert command (handler : xs) (botHandlers botState)}
where handlers = Map.lookup command (botHandlers botState)
| UndeadMastodon/ShrubBot | HandlerManagement.hs | gpl-3.0 | 579 | 0 | 13 | 91 | 158 | 89 | 69 | 13 | 2 |
module Problem024 (answer) where
import Data.List (unfoldr)
import NumUtil (recompose)
answer :: Int
answer = recompose $ unfoldr choseDigit (1000000-1, [0..9])
choseDigit :: (Int, [Int]) -> Maybe (Int, (Int, [Int]))
choseDigit (_, []) = Nothing
choseDigit (target, digits)
| target <= 0 = Just (head digits, (target, tail digits))
| otherwise = Just (digits !! d, (newTarget, newDigits))
where
f = fact $ length digits - 1
d = target `div` f
newTarget = target - d * f
newDigits = pickIndex d digits
fact :: Int -> Int
fact 0 = 1
fact n = product [1..n]
pickIndex :: Int -> [a] -> [a]
pickIndex _ [] = undefined
pickIndex i (x:xs)
| i == 0 = xs
| otherwise = x : pickIndex (i-1) xs
| geekingfrog/project-euler | Problem024.hs | gpl-3.0 | 727 | 0 | 9 | 171 | 354 | 192 | 162 | 22 | 1 |
{-# LANGUAGE TemplateHaskell #-}
{- |
Module : Mine
Description : Something that stays in place and explode when anything touches it
Copyright : (c) Frédéric BISSON, 2015
License : GPL-3
Maintainer : [email protected]
Stability : experimental
Portability : POSIX
A `Mine` is something that stays in place and explode when anything comes to
touch it.
-}
module Tank.Elements.Mine
( Mine (..)
-- * Mine lenses
, minePos
) where
import Control.Lens
import Tank.Units
{-|
A `Mine` is an ammunition that can be buried somewhere.
-}
data Mine = Mine { _minePos :: Coords } deriving (Eq, Show, Read)
makeLenses ''Mine | Zigazou/Tank | src/Tank/Elements/Mine.hs | gpl-3.0 | 630 | 0 | 8 | 120 | 71 | 43 | 28 | 8 | 0 |
module L0308 where
import L0307 hiding (fresh,rlabel)
rlabel :: Tree a -> Int -> (Tree Int,Int)
rlabel (Leaf _) n = (Leaf n,n+1)
rlabel (Node l r) n = let (l1,n') = rlabel l n
(r1,n'') = rlabel r n' in (Node l1 r1,n'')
-- rlabel' :: Tree a -> Int -> Tree Int
fresh :: ST Int Int
fresh = ST (\n -> (n,n+1))
-- fresh = do
-- n <- get id
-- update (+1)
-- return n
alabel :: Tree a -> ST Int (Tree Int)
-- alabel (Leaf _) = ST (\n -> (Leaf n,n+1))
alabel (Leaf _) = Leaf <$> fresh
-- alabel (Leaf _) = pure Leaf <*> fresh
alabel (Node l r) = Node <$> alabel l <*> alabel r
mlabel :: Tree a -> ST Int (Tree Int)
mlabel (Leaf _) = do
n <- fresh
return (Leaf n)
mlabel (Node l r) = do
l' <- mlabel l
r' <- mlabel r
return (Node l' r')
fib :: Integer -> Integer
fib 0 = 0
fib 1 = 1
fib n = fib (n-1) + fib (n-2)
fiblist = 0:1:[fiblist!!x + fiblist!!(x+1)|x <- [0..]]
nextfib :: ST (Integer,Integer) Integer
nextfib = ST(\(x,y) -> let z = x + y in (z,(y,z)))
newfibpair :: Integer -> (Integer,Integer)
newfibpair 0 = (0,0)
newfibpair 1 = (0,1)
newfibpair n = snd $ app nextfib (newfibpair (n-1))
newfib n = snd $ newfibpair n
| cwlmyjm/haskell | AFP/L0308.hs | mpl-2.0 | 1,273 | 0 | 12 | 394 | 615 | 321 | 294 | 31 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Web.All
( generateAllJS
, generateAllCSS
) where
import Control.Monad (when, forM_)
import Control.Monad.IO.Class (liftIO)
import Foreign.Ptr (Ptr)
import Foreign.Marshal.Alloc (allocaBytes)
import System.IO (withBinaryFile, IOMode(ReadMode, WriteMode), hPutChar, hGetBufSome, hPutBuf, Handle)
import Web
import Files
import Web.Types
import Web.Generate
import Web.Libs
generateMerged :: [WebFilePath] -> WebGenerator
generateMerged inputFiles = \fileToGenInfo@(fileToGen, _) -> do
fp <- liftIO $ unRawFilePath $ webFileAbs fileToGen
webRegenerate
(allocaBytes totalAlloc $ \allocatedPtr ->
withBinaryFile fp WriteMode $ \generatingFileWriteHandle ->
forM_ inputFiles $ \inputFile -> do
fps <- unRawFilePath $ webFileAbs inputFile
withBinaryFile fps ReadMode $ bufferedCopy allocatedPtr generatingFileWriteHandle
hPutChar generatingFileWriteHandle '\n')
[]
inputFiles
fileToGenInfo
where
bufferedCopy :: Ptr a -> Handle -> Handle -> IO ()
bufferedCopy buffer output input = do
n <- hGetBufSome input buffer totalAlloc
when (n > 0) $ do
hPutBuf output buffer n
bufferedCopy buffer output input
totalAlloc = 32768
generateAllJS :: WebGenerator
generateAllJS = \f -> do
let debugOn = True
deps <- liftIO $ webDeps debugOn
appMinJs <- liftIO $ makeWebFilePath "app.min.js"
generateMerged (deps ++ [appMinJs]) f
generateAllCSS :: WebGenerator
generateAllCSS = \f -> do
css <- liftIO $ cssWebDeps False
generateMerged css f
| databrary/databrary | src/Web/All.hs | agpl-3.0 | 1,576 | 0 | 20 | 303 | 461 | 240 | 221 | 44 | 1 |
{-
Copyright (C) 2009 John Goerzen <[email protected]>
All rights reserved.
For license and copyright information, see the file COPYRIGHT
-}
module TestTime where
import TestInfrastructure
import Data.Convertible
import Test.QuickCheck
import Test.QuickCheck.Tools
import Test.QuickCheck.Instances
import qualified System.Time as ST
import Data.Time
import Data.Time.Clock.POSIX
import Data.Ratio
import Foreign.C.Types
instance Arbitrary ST.ClockTime where
arbitrary = do r1 <- arbitrary
r2 <- sized $ \n -> choose (0, 1000000000000 - 1)
return (ST.TOD r1 r2)
coarbitrary (ST.TOD a b) = coarbitrary a . coarbitrary b
instance Arbitrary ST.CalendarTime where
arbitrary = do r <- arbitrary
return $ convert (r::POSIXTime)
instance Arbitrary NominalDiffTime where
arbitrary = do r <- arbitrary
return $ convert (r::ST.ClockTime)
instance Arbitrary UTCTime where
arbitrary = do r <- arbitrary
return $ convert (r::POSIXTime)
instance Arbitrary ZonedTime where
arbitrary = do r <- arbitrary
return $ convert (r::POSIXTime)
instance Eq ZonedTime where
a == b = zonedTimeToUTC a == zonedTimeToUTC b
propCltCalt :: ST.ClockTime -> Result
propCltCalt x =
safeConvert x @?= Right (ST.toUTCTime x)
propCltCaltClt :: ST.ClockTime -> Result
propCltCaltClt x =
Right x @=? do r1 <- ((safeConvert x)::ConvertResult ST.CalendarTime)
safeConvert r1
propCltPT :: ST.ClockTime -> Result
propCltPT x@(ST.TOD y z) =
safeConvert x @?= Right (r::POSIXTime)
where r = fromRational $ fromInteger y + fromRational (z % 1000000000000)
propPTClt :: POSIXTime -> Result
propPTClt x =
safeConvert x @?= Right (r::ST.ClockTime)
where r = ST.TOD rsecs rpico
rsecs = floor x
rpico = truncate $ abs $ 1000000000000 * (x - (fromIntegral rsecs))
propCaltPT :: ST.CalendarTime -> Result
propCaltPT x =
safeConvert x @?= expected
where expected = do r <- safeConvert x
(safeConvert (r :: ST.ClockTime))::ConvertResult POSIXTime
propCltPTClt :: ST.ClockTime -> Result
propCltPTClt x =
Right (toTOD x) @=? case do r1 <- (safeConvert x)::ConvertResult POSIXTime
safeConvert r1
of Left x -> Left x
Right y -> Right $ toTOD y
where toTOD (ST.TOD x y) = (x, y)
{-
Right x @=? do r1 <- (safeConvert x)::ConvertResult POSIXTime
safeConvert r1
-}
propPTZTPT :: POSIXTime -> Result
propPTZTPT x =
Right x @=? do r1 <- safeConvert x
safeConvert (r1 :: ZonedTime)
propPTCltPT :: POSIXTime -> Result
propPTCltPT x =
Right x @=? do r1 <- (safeConvert x)::ConvertResult ST.ClockTime
safeConvert r1
propPTCalPT :: POSIXTime -> Result
propPTCalPT x =
Right x @=? do r1 <- safeConvert x
safeConvert (r1::ST.CalendarTime)
propUTCCaltUTC :: UTCTime -> Result
propUTCCaltUTC x =
Right x @=? do r1 <- safeConvert x
safeConvert (r1::ST.CalendarTime)
propPTUTC :: POSIXTime -> Result
propPTUTC x =
safeConvert x @?= Right (posixSecondsToUTCTime x)
propUTCPT :: UTCTime -> Result
propUTCPT x =
safeConvert x @?= Right (utcTimeToPOSIXSeconds x)
propCltUTC :: ST.ClockTime -> Result
propCltUTC x =
safeConvert x @?= Right (posixSecondsToUTCTime . convert $ x)
propZTCTeqZTCaltCt :: ZonedTime -> Result
propZTCTeqZTCaltCt x =
route1 @=? route2
where route1 = (safeConvert x)::ConvertResult ST.ClockTime
route2 = do calt <- safeConvert x
safeConvert (calt :: ST.CalendarTime)
propCaltZTCalt :: ST.ClockTime -> Result
propCaltZTCalt x =
Right x @=? do zt <- ((safeConvert calt)::ConvertResult ZonedTime)
calt' <- ((safeConvert zt)::ConvertResult ST.CalendarTime)
return (ST.toClockTime calt')
where calt = ST.toUTCTime x
propCaltZTCalt2 :: ST.CalendarTime -> Result
propCaltZTCalt2 x =
Right x @=? do zt <- safeConvert x
safeConvert (zt :: ZonedTime)
propZTCaltCtZT :: ZonedTime -> Result
propZTCaltCtZT x =
Right x @=? do calt <- safeConvert x
ct <- safeConvert (calt :: ST.CalendarTime)
safeConvert (ct :: ST.ClockTime)
propZTCtCaltZT :: ZonedTime -> Result
propZTCtCaltZT x =
Right x @=? do ct <- safeConvert x
calt <- safeConvert (ct :: ST.ClockTime)
safeConvert (calt :: ST.CalendarTime)
propZTCaltZT :: ZonedTime -> Result
propZTCaltZT x =
Right x @=? do calt <- safeConvert x
safeConvert (calt :: ST.CalendarTime)
propZTCtCaltCtZT :: ZonedTime -> Result
propZTCtCaltCtZT x =
Right x @=? do ct <- safeConvert x
calt <- safeConvert (ct :: ST.ClockTime)
ct' <- safeConvert (calt :: ST.CalendarTime)
safeConvert (ct' :: ST.ClockTime)
propUTCZT :: UTCTime -> Bool
propUTCZT x =
x == zonedTimeToUTC (convert x)
propUTCZTUTC :: UTCTime -> Result
propUTCZTUTC x =
Right x @=? do r1 <- ((safeConvert x)::ConvertResult ZonedTime)
safeConvert r1
propNdtTdNdt :: NominalDiffTime -> Result
propNdtTdNdt x =
Right x @=? do r1 <- ((safeConvert x)::ConvertResult ST.TimeDiff)
safeConvert r1
propPTCPT :: POSIXTime -> Result
propPTCPT x =
Right testval @=? do r1 <- safeConvert testval
safeConvert (r1 :: CTime)
where testval = (convert ((truncate x)::Integer))::POSIXTime -- CTime doesn't support picosecs
allt = [q "ClockTime -> CalendarTime" propCltCalt,
q "ClockTime -> CalendarTime -> ClockTime" propCltCaltClt,
q "ClockTime -> POSIXTime" propCltPT,
q "POSIXTime -> ClockTime" propPTClt,
q "CalendarTime -> POSIXTime" propCaltPT,
q "identity ClockTime -> POSIXTime -> ClockTime" propCltPTClt,
q "identity POSIXTime -> ClockTime -> POSIXTime" propPTCltPT,
q "identity POSIXTime -> ZonedTime -> POSIXTime" propPTZTPT,
q "identity POSIXTime -> CalendarTime -> POSIXTime" propPTCalPT,
q "identity UTCTime -> CalendarTime -> UTCTime" propUTCCaltUTC,
q "POSIXTime -> UTCTime" propPTUTC,
q "UTCTime -> POSIXTime" propUTCPT,
q "ClockTime -> UTCTime" propCltUTC,
q "ZonedTime -> ClockTime == ZonedTime -> CalendarTime -> ClockTime" propZTCTeqZTCaltCt,
q "identity CalendarTime -> ZonedTime -> CalendarTime" propCaltZTCalt,
q "identity CalendarTime -> ZonedTime -> CalenderTime, test 2" propCaltZTCalt2,
q "identity ZonedTime -> CalendarTime -> ZonedTime" propZTCaltZT,
q "ZonedTime -> CalendarTime -> ClockTime -> ZonedTime" propZTCaltCtZT,
q "ZonedTime -> ClockTime -> CalendarTime -> ZonedTime" propZTCtCaltZT,
q "ZonedTime -> ColckTime -> CalendarTime -> ClockTime -> ZonedTime" propZTCtCaltCtZT,
q "UTCTime -> ZonedTime" propUTCZT,
q "UTCTime -> ZonedTime -> UTCTime" propUTCZTUTC,
q "identity NominalDiffTime -> TimeDiff -> NominalDiffTime" propNdtTdNdt,
q "identity POSIXTime -> CTime -> POSIXTime" propPTCPT
]
| snoyberg/convertible | testsrc/TestTime.hs | lgpl-2.1 | 7,302 | 0 | 13 | 1,950 | 1,959 | 975 | 984 | 160 | 2 |
{-# LANGUAGE PackageImports #-}
{-# LANGUAGE QuasiQuotes #-}
module Main (main) where
import "hspec" Test.Hspec (hspec, describe)
-- local imports
import qualified QM.Spec
import qualified QN.Spec
import qualified QMB.Spec
import qualified QNB.Spec
import qualified QMS.Spec
import qualified QNS.Spec
-- Generated tests for CRLF line breaks
import qualified LineBreaks.CRLF.QM.Spec
import qualified LineBreaks.CRLF.QN.Spec
import qualified LineBreaks.CRLF.QMB.Spec
import qualified LineBreaks.CRLF.QNB.Spec
import qualified LineBreaks.CRLF.QMS.Spec
import qualified LineBreaks.CRLF.QNS.Spec
main :: IO ()
main = hspec $ do
describe "QM" QM.Spec.spec
describe "QN (QM but without interpolation)" QN.Spec.spec
describe "QMB (interpolated string with line-*B*reaks)" QMB.Spec.spec
describe "QNB (QMB but without interpolation)" QNB.Spec.spec
describe "QMS (interpolated string with line breaks replaced with *S*paces)"
QMS.Spec.spec
describe "QNS (QMS but without interpolation)" QNS.Spec.spec
describe "QM (CRLF line breaks)" LineBreaks.CRLF.QM.Spec.spec
describe "QN (CRLF line breaks)" LineBreaks.CRLF.QN.Spec.spec
describe "QMB (CRLF line breaks)" LineBreaks.CRLF.QMB.Spec.spec
describe "QNB (CRLF line breaks)" LineBreaks.CRLF.QNB.Spec.spec
describe "QMS (CRLF line breaks)" LineBreaks.CRLF.QMS.Spec.spec
describe "QNS (CRLF line breaks)" LineBreaks.CRLF.QNS.Spec.spec
| unclechu/haskell-qm-interpolated-string | test/Spec.hs | unlicense | 1,416 | 0 | 9 | 195 | 274 | 161 | 113 | 31 | 1 |
module Main where
import Digits
import Factors
import Data.List
pandigitalProduct productNum = any isPandigital $ factorsWithout1andSelf productNum
where
isPandigital factor = isUniqueCombination (digits factor) (digits $ productNum `div` factor) (digits productNum)
isUniqueCombination multiplicantDigs multiplierDigs productNumDigs = (sort $ multiplicantDigs ++ multiplierDigs ++ productNumDigs) == [1..9]
findAllPandigitalProducts = filter pandigitalProduct [1000..10000]
main = print $ sum findAllPandigitalProducts
| kliuchnikau/project-euler | 032/Main.hs | apache-2.0 | 534 | 0 | 11 | 70 | 138 | 73 | 65 | 9 | 1 |
insertAt :: a -> [a] -> Int -> [a]
insertAt y xs 1 = y:xs
insertAt y (x:xs) n = x:insertAt y xs (n - 1)
| plilja/h99 | p21.hs | apache-2.0 | 104 | 0 | 8 | 26 | 77 | 40 | 37 | 3 | 1 |
{-# LANGUAGE ExtendedDefaultRules #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
-- Module : Rifactor.Types.AWS
-- Copyright : (c) 2015 Knewton, Inc <[email protected]>
-- (c) 2015 Tim Dysinger <[email protected]> (contributor)
-- License : Apache 2.0 http://opensource.org/licenses/Apache-2.0
-- Maintainer : Tim Dysinger <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
module Rifactor.Types.AWS where
import BasePrelude
import Control.Lens hiding ((.=))
import Data.Text (Text)
import qualified Network.AWS as AWS
import qualified Network.AWS.EC2 as EC2
import Rifactor.Types.Model
default (Text)
type AwsEnv = Env AWS.Env
type AwsResource = Resource AWS.Env EC2.ReservedInstances EC2.Instance
type AwsPlan = Plan AwsResource
type AwsPlanTransition = Transition AwsPlan
data IGroup
= C1
| C2
| C3
| C4
| CC2
| CG1
| CR1
| D2
| G2
| HI1
| HS1
| HS2
| I2
| M1
| M2
| M3
| M4
| R3
| T1
| T2
| X1
deriving (Enum,Eq,Ord,Show)
data ISize
= Nano
| Micro
| Small
| Medium
| Large
| XLarge
| XLarge2X
| XLarge4X
| XLarge8X
| XLarge10X
| XLarge32X
deriving (Enum,Eq,Ord,Show)
data IType =
IType {_insGroup :: IGroup
,_insType :: EC2.InstanceType
,_insFactor :: Double}
deriving (Eq,Ord,Show)
$(makeLenses ''IType)
| Knewton/rifactor | src/Rifactor/Types/AWS.hs | apache-2.0 | 1,473 | 0 | 9 | 359 | 319 | 199 | 120 | 58 | 0 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Kubernetes.V1.ObjectReference where
import GHC.Generics
import Data.Text
import qualified Data.Aeson
-- | ObjectReference contains enough information to let you inspect or modify the referred object.
data ObjectReference = ObjectReference
{ kind :: Maybe Text -- ^ Kind of the referent. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds
, namespace :: Maybe Text -- ^ Namespace of the referent. More info: http://releases.k8s.io/HEAD/docs/user-guide/namespaces.md
, name :: Maybe Text -- ^ Name of the referent. More info: http://releases.k8s.io/HEAD/docs/user-guide/identifiers.md#names
, uid :: Maybe Text -- ^ UID of the referent. More info: http://releases.k8s.io/HEAD/docs/user-guide/identifiers.md#uids
, apiVersion :: Maybe Text -- ^ API version of the referent.
, resourceVersion :: Maybe Text -- ^ Specific resourceVersion to which this reference is made, if any. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#concurrency-control-and-consistency
, fieldPath :: Maybe Text -- ^ If referring to a piece of an object instead of an entire object, this string should contain a valid JSON/Go field access statement, such as desiredState.manifest.containers[2]. For example, if the object reference is to a container within a pod, this would take on a value like: \"spec.containers{name}\" (where \"name\" refers to the name of the container that triggered the event) or if no container name is specified \"spec.containers[2]\" (container with index 2 in this pod). This syntax is chosen only to have some well-defined way of referencing a part of an object.
} deriving (Show, Eq, Generic)
instance Data.Aeson.FromJSON ObjectReference
instance Data.Aeson.ToJSON ObjectReference
| minhdoboi/deprecated-openshift-haskell-api | kubernetes/lib/Kubernetes/V1/ObjectReference.hs | apache-2.0 | 1,952 | 0 | 9 | 290 | 143 | 86 | 57 | 20 | 0 |
{-# LANGUAGE DataKinds, EmptyDataDecls, TypeOperators, UndecidableInstances #-}
{-|
Module: HaskHOL.Lib.Bool.Context
Copyright: (c) Evan Austin 2015
LICENSE: BSD3
Maintainer: [email protected]
Stability: unstable
Portability: unknown
This module extends the 'ctxtBase' context with the 'loadBoolLib' computation.
It exports the theory context, quasi-quoter, and compile-time proof methods
for the Boolean logic library.
-}
module HaskHOL.Lib.Bool.Context
( -- * Theory Context
-- $ThryCtxt
BoolType
, BoolThry
, BoolCtxt
, ctxtBool
) where
import HaskHOL.Core
-- New Theory Type and Constraint
data BoolThry
type instance BoolThry == BoolThry = 'True
instance CtxtName BoolThry where
ctxtName _ = "BoolCtxt"
type instance PolyTheory BoolType b = BoolCtxt b
type family BoolCtxt a :: Constraint where
BoolCtxt a = (Typeable a, BaseCtxt a, BoolContext a ~ 'True)
-- Assert Theory Hierarchy
type BoolType = ExtThry BoolThry BaseThry
type family BoolContext a :: Bool where
BoolContext UnsafeThry = 'True
BoolContext BaseThry = 'False
BoolContext (ExtThry a b) = BoolContext b || (a == BoolThry)
-- Build Context
ctxtBool :: TheoryPath BoolType
ctxtBool = extendTheory ctxtBase $(thisModule') $
do parseAsPrefix "~"
mapM_ parseAsInfix [ ("==>", (4, "right"))
, ("\\/", (6, "right"))
, ("/\\", (8, "right"))
, ("<=>", (2, "right")) ]
mapM_ parseAsBinder ["!", "?", "?!"]
mapM_ parseAsTyBinder ["!!", "??"]
overrideInterface "<=>" [txt| (=):bool->bool->bool |]
mapM_ newBasicDefinition
[ ("T", [txt| T = ((\ p:bool . p) = (\ p:bool . p)) |])
, ("/\\", [txt| (/\) = \ p q . (\ f:bool->bool->bool . f p q) =
(\ f . f T T) |])
, ("==>", [txt| (==>) = \ p q . p /\ q <=> p |])
, ("!", [txt| (!) = \ P:A->bool . P = \ x . T |])
, ("?", [txt| (?) = \ P:A->bool . ! q . (! x . P x ==> q) ==> q |])
, ("\\/", [txt| (\/) = \ p q . ! r . (p ==> r) ==> (q ==> r) ==> r |])
, ("F", [txt| F = ! p:bool . p |])
, ("_FALSITY_", [txt| _FALSITY_ = F |])
, ("~", [txt| (~) = \ p . p ==> F |])
, ("?!", [txt| (?!) = \ P:A->bool. ((?) P) /\
(!x y. P x /\ P y ==> x = y) |])
, ("!!", [txt| (!!) = \ P : (% 'A. bool). P = (\\ 'A. T) |])
, ("??", [txt| (??) = \ P : (% 'A. bool). ~(P = (\\ 'A . F)) |])
]
| ecaustin/haskhol-deductive | src/HaskHOL/Lib/Bool/Context.hs | bsd-2-clause | 2,592 | 1 | 11 | 816 | 502 | 317 | 185 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
{-|
Module : Lang.Cortho.Types
Description : Core Cortho types
Copyright : (c) Benjamin F Jones, 2016
License : BSD-3
Maintainer : [email protected]
Stability : experimental
Portability : POSIX
This module contains all the core types for Cortho. In particular it defines
and provides instances for the main expression type.
-}
module Lang.Cortho.Types
( -- * core expression type
CoreExpr
, CoreAlter
, Expr(..)
, Alter(..)
, Program(..)
, ScDef(..)
-- * Auxilliary types
, BinOp(..)
, UnaryOp(..)
, Ident
, unIdent
, identFromText
, identFromStr
)
where
import Prelude hiding ((<>))
import Data.Text (Text)
import qualified Data.Text as T
import GHC.Exts (IsString(..))
import Text.PrettyPrint.HughesPJClass
------------------------------------------------------------------------
-- Core Types
------------------------------------------------------------------------
-- | Identifier used for names
newtype Ident = Ident { unIdent :: Text {-^ unwrap an 'Ident' -} }
deriving (Eq, Show)
-- | Text -> Ident
identFromText = Ident
-- | String -> Ident
identFromStr = Ident . T.pack
instance IsString Ident where
fromString = Ident . T.pack
-- | Core program type, a list of supercombinator definitions
data Program = Program [ScDef]
deriving (Eq, Show)
-- | Supercombinator definition
data ScDef = ScDef
{ scName :: Ident -- ^ name
, scBinds :: [Ident] -- ^ binders (arguments)
, scExpr :: CoreExpr -- ^ right-hand side
}
deriving (Eq, Show)
-- | The core expression data type, parametrized over a binders type
data Expr a
= EVar !Ident -- ^ variable identifier
| ENum Integer -- ^ number
| EBinOp BinOp !(Expr a) !(Expr a) -- ^ binary operator
| EUnaOp UnaryOp !(Expr a) -- ^ prefix unary operator
| EConstr Int Int -- ^ data constructor
| EAp !(Expr a) !(Expr a) -- ^ function application
| ELet Bool ![(a, Expr a)] !(Expr a) -- ^ let/letrec expression (True <-> letrec)
| ECase !(Expr a) ![Alter a] -- ^ case expression
| ELam ![a] !(Expr a) -- ^ lambda
deriving (Eq, Show)
-- | Classify expressions as atoms and non-atoms
isAtom :: Expr a -> Bool
isAtom (EVar _) = True
isAtom (ENum _) = True
isAtom (EConstr _ _) = True
isAtom (EAp _ _) = False
isAtom (ELet _ _ _) = False
isAtom (ECase _ _) = False
isAtom (ELam _ _) = False
-- | CoreExpr is the usual expression type where binders are names
type CoreExpr = Expr Ident
-- | CoreAlter is the case alternative type where binders are names
type CoreAlter = Alter Ident
-- | Case alternative, a pattern/expression pair
data Alter a
= APattern !Int ![a] !(Expr a) -- ^ non-trivial data c'tor pattern match
| ADefault !(Expr a) -- ^ default "fall-through" case
deriving (Eq, Show)
-- | Binary Operators. Precedence is encoded in the parser.
data BinOp
= -- Arithmetic Operators
OpAdd -- ^ Addition (+)
| OpSub -- ^ Subtraction (-)
| OpMult -- ^ Multiplication (*)
| OpDiv -- ^ Division (/)
-- Relational operators. Precedence is encoded in the parser.
| OpLT -- ^ Less than (<)
| OpLE -- ^ Less or equal (<=)
| OpGT -- ^ Greater than (>)
| OpGE -- ^ Greater or equal (>=)
| OpEQ -- ^ Equal (==)
| OpNEQ -- ^ Not Equal (/=)
-- Boolean Operators.
| OpAnd -- ^ Boolean and (&)
| OpOr -- ^ Boolean or (|)
deriving (Eq, Show)
-- | Unary Operators. Note: unary negation is handled by the 'negate'
-- prelude function.
data UnaryOp
= OpNot -- ^ Boolean negation (~)
deriving (Eq, Show)
------------------------------------------------------------------------
-- Pretty Printing
------------------------------------------------------------------------
-- | Number of spaces to indent
ispace :: Int
ispace = 2
instance Pretty Ident where
pPrint = text . T.unpack . unIdent
instance Pretty ScDef where
pPrint (ScDef name vars expr) =
pPrint name <+> hsep (pPrint <$> vars) <+> equals <+> pPrint expr
instance Pretty Program where
pPrint (Program sds) = vcat (pPrint <$> sds)
instance Pretty a => Pretty (Expr a) where
pPrint (EVar x) = pPrint x
pPrint (ENum x) = pPrint x
pPrint (EBinOp op x y) = pPrint x <> pPrint op <> pPrint y
pPrint (EUnaOp op x) = pPrint op <> pPrint x
pPrint (EConstr t a) = text "Pack{" <> int t <> text "," <> int a <> text "}"
pPrint (EAp f a) | isAtom a = pPrint f <+> pPrint a
| otherwise = pPrint f <+> parens (pPrint a)
pPrint (ELet b decls body) =
text (if b then "letrec" else "let") <+> hsep (map pBind decls) <+> text "in" <+>
pPrint body
pPrint (ECase c as) =
text "case" <+> pPrint c <+> text "of" $$
nest ispace (vcat . map pPrint $ as)
pPrint (ELam vs e) = parens (text "\\" <> pPrint vs <> text "->" <+> pPrint e)
instance Pretty a => Pretty (Alter a) where
pPrint (APattern t vs e) =
text "<" <> int t <> text ">" <+> hsep (map pPrint vs) <+> text "->" <+>
pPrint e
pPrint (ADefault e) =
text "_" <+> text "->" <+> pPrint e
instance Pretty BinOp where
pPrint OpAdd = text " + "
pPrint OpSub = text " - "
pPrint OpMult = text "*"
pPrint OpDiv = text "/"
pPrint OpLT = text " < "
pPrint OpLE = text " <= "
pPrint OpGT = text " > "
pPrint OpGE = text " >= "
pPrint OpEQ = text " == "
pPrint OpNEQ = text " != "
pPrint OpAnd = text " & "
pPrint OpOr = text " | "
instance Pretty UnaryOp where
pPrint OpNot = text "~"
-- | Pretty print a variable binding
pBind :: Pretty a => (a, Expr a) -> Doc
pBind (name, expr) = pPrint name <> equals <> pPrint expr <> text ";"
| benjaminfjones/cortho | src/Lang/Cortho/Types.hs | bsd-2-clause | 5,823 | 0 | 11 | 1,504 | 1,555 | 822 | 733 | 154 | 1 |
{-# Language OverloadedStrings #-}
{-# Language GADTs #-}
{-# Language TypeOperators #-}
{-# Language DataKinds #-}
{-# Language FlexibleContexts #-}
{-# Language FlexibleInstances #-}
{-# Language MultiParamTypeClasses #-}
module Hooks.Algebra where
import GHC.TypeLits
import Control.Monad.Reader
import Network.IRC
import Data.ByteString.Lazy (ByteString)
import Control.Lens ((^.))
import Network.Wreq hiding (Payload, Proxy)
import Data.CaseInsensitive (CI)
import qualified Data.ByteString as BS (ByteString)
import Data.Text (Text)
import qualified Data.Text as T
import Data.Time (UTCTime)
import qualified Data.Time as Time
import qualified Data.Acid.Database as DB
import Plugin
import Types
instance HasApp app (ReadState app) where
getApp = readStateApp
sendMessage :: (MonadReader (ReadState app) m, MonadIO m) => OutMsg -> m ()
sendMessage msg = asks readStateOutChannel >>= \c -> liftIO (sendMessage' c msg)
respondTarget :: Text -> Text -> Text
respondTarget nick target = if "#" `T.isPrefixOf` target then target else nick
respondTo :: (MonadReader (ReadState app) m, MonadIO m) => Text -> Text -> Text -> m ()
respondTo nick trg msg = sendMessage (Msg (respondTarget nick trg) msg)
| MasseR/FreeIrc | src/Hooks/Algebra.hs | bsd-3-clause | 1,212 | 0 | 10 | 175 | 344 | 200 | 144 | 31 | 2 |
{-# Language DataKinds #-}
{-# Language TypeOperators #-}
{-# Language TypeFamilies #-}
{-# Language GADTs #-}
{-# Language AllowAmbiguousTypes #-}
{-# Language PolyKinds #-}
{-# Language UndecidableInstances #-}
{-# Language ScopedTypeVariables #-}
import GHC.TypeLits
data Proxy a = Proxy
data End
data (path :: k) :/ b = Proxy path :/ b
infixr 9 :/
type Path = "foo" :/ "bar" :/ "baz" :/ End
foo p = symbolVal p
class Render path where
type R path :: *
render :: Proxy path -> String
instance Render End where
render _ = ""
instance (KnownSymbol path, Render subpath) => Render (path :/ subpath) where
type R (path :/ subpath) = R subpath
render p = symbolVal proxy ++ "/" ++ render (Proxy :: Proxy subpath)
where proxy = Proxy :: Proxy path
| MasseR/Blog | queue/typelit.hs | bsd-3-clause | 768 | 0 | 9 | 155 | 218 | 120 | 98 | -1 | -1 |
{-# LANGUAGE CPP, DeriveDataTypeable, FlexibleContexts,
GeneralizedNewtypeDeriving, MultiParamTypeClasses,
TemplateHaskell, TypeFamilies, RecordWildCards #-}
module DataState where
import Control.Applicative ( (<$>) )
import Control.Exception ( bracket )
import Control.Monad ( msum )
import Control.Monad.Reader ( ask )
import Control.Monad.State ( get, put )
import Data.Data ( Data, Typeable )
import Data.Acid ( AcidState, Query, Update
, makeAcidic, openLocalState )
import Data.Acid.Advanced ( query', update' )
import Data.Acid.Local ( createCheckpointAndClose )
import Data.Acid.Memory
import Data.Acid.Memory.Pure
import Data.SafeCopy ( base, deriveSafeCopy )
import Database ( Database, Attribute, Attributes, emptyDB )
import qualified Database as DB
import MLPCCG (mlpccg)
data DataState = DataState { database :: Database, tags :: Attributes }
deriving (Eq, Ord, Read, Show, Data, Typeable)
$(deriveSafeCopy 0 'base ''DataState)
initialDataState :: DataState
initialDataState = DataState (emptyDB)
-- Update Functions
addAttribute :: Attribute -> Update DataState ()
addAttribute a =
do d@DataState{..} <- get
let newTags = (Set.insert a tags)
put $ d { tags = newTags }
addAttributes :: Attributes -> Update DataState ()
addAttributes as =
do d@DataState{..} <- get
let newTags = (Set.union as tags)
put $ d { tags = newTags }
addTag :: Card -> Attribute -> Update DataState ()
addTag c a =
do d@DataState{..} <- get
let newTags = (Set.insert a tags)
newDB = DB.addAttrib c a database
put $ d { database = newDB, tags = newTags }
addCards :: Cardlist -> Update DataState ()
addCards cs =
do d@DataState{..} <- get
let newDB = DB.addCards cs database
put $ d { database = newDB }
initialize :: Cardlist -> DataState
initialize = flip addCards initialDataState
addCard :: Card -> Update DataState ()
addCard c =
do d@DataState{..} <- get
let newDB = DB.addCard c database
put $ d { database = newDB }
addEntry :: Card -> Attributes -> Update DataState ()
addEntry c as =
do d@DataState{..} <- get
let newTags = (Set.union as tags)
newDB = DB.addEntry c database
-- Query Functions
queryCard :: Card -> Query DataState Bool
queryCard c = (member c.assocs.database) <$> ask
queryCards :: Query DataState Cardlist
queryCards = (keysSet.assocs.database) <$> ask
queryAssocs :: Card -> Query DataState Attributes
queryAssocs c = (lookup c.assocs.database) <$> ask
queryAttrs :: Query DataState Attributes
queryAttrs = tags <$> ask
queryEntries :: (Card -> Attributes -> Bool) -> Query DataState Database
queryEntries p = ((filterWithKey p).assocs.database) <$> ask
| archaephyrryx/CCG-Project | src/CCG/DataState.hs | bsd-3-clause | 2,671 | 75 | 13 | 484 | 858 | 484 | 374 | -1 | -1 |
module Simulator where
{- X86lite Simulator -}
{- See the documentation in the X86lite specification, available on the
course web pages, for a detailed explanation of the instruction
semantics.
-}
import X86
import Data.Int (Int64)
import Data.Word (Word8)
import Data.Bits (shiftR, shiftL, (.&.), (.|.))
import Data.Char (ord)
{- simulator machine state -------------------------------------------------- -}
mem_bot, mem_top, mem_size, ins_size, exit_addr :: Int64
mem_bot = 0x400000 {- lowest valid address -}
mem_top = 0x410000 {- one past the last byte in memory -}
mem_size = mem_top - mem_bot
ins_size = 4 {- assume we have a 4-byte encoding -}
exit_addr = 0xfdead {- halt when m.regs(%rip) = exit_addr -}
nregs :: Int
nregs = 17 {- including Rip -}
{- Your simulator should raise this exception if it tries to read from or
store to an address not within the valid address space. -}
--exception X86lite_segfault
{- The simulator memory maps addresses to symbolic bytes. Symbolic
bytes are either actual data indicated by the Byte constructor or
'symbolic instructions' that take up four bytes for the purposes of
layout.
The symbolic bytes abstract away from the details of how
instructions are represented in memory. Each instruction takes
exactly four consecutive bytes, where the first byte InsB0 stores
the actual instruction, and the next three bytes are InsFrag
elements, which aren't valid data.
For example, the two-instruction sequence:
at&t syntax ocaml syntax
movq %rdi, (%rsp) Movq, [~%Rdi; Ind2 Rsp]
decq %rdi Decq, [~%Rdi]
is represented by the following elements of the mem array (starting
at address 0x400000):
0x400000 : InsB0 (Movq, [~%Rdi; Ind2 Rsp])
0x400001 : InsFrag
0x400002 : InsFrag
0x400003 : InsFrag
0x400004 : InsB0 (Decq, [~%Rdi])
0x400005 : InsFrag
0x400006 : InsFrag
0x400007 : InsFrag
-}
data Sbyte = InsB0 Ins {- 1st byte of an instruction -}
| InsFrag {- 2nd, 3rd, or 4th byte of an instruction -}
| Byte Word8 {- non-instruction byte -}
{- memory maps addresses to symbolic bytes -}
type Mem = [Sbyte] -- TODO use array
{- Flags for condition codes -}
data Flags = Flags {
fo :: Bool,
fs :: Bool,
fz :: Bool }
{- Register files -}
type Regs = [Int64] -- TODO: use array
{- Complete machine state -}
data Mach = Mach {
flags :: Flags,
regs :: Regs,
mem :: Mem }
{- simulator helper functions ----------------------------------------------- -}
{- The index of a register in the regs array -}
rind :: Reg -> Int
rind r = case r of
Rip -> 16
Rax -> 0 ; Rbx -> 1 ; Rcx -> 2 ; Rdx -> 3
Rsi -> 4 ; Rdi -> 5 ; Rbp -> 6 ; Rsp -> 7
R08 -> 8 ; R09 -> 9 ; R10 -> 10 ; R11 -> 11
R12 -> 12 ; R13 -> 13 ; R14 -> 14 ; R15 -> 15
{- Helper functions for reading/writing sbytes -}
{- Convert an int64 to its sbyte representation -}
int64ToSbytes :: Int64 -> [Sbyte]
int64ToSbytes i = map (\n -> Byte (fromIntegral (shiftR i n) .&. 0xff)) [0,8..56]
{- Convert an sbyte representation to an int64 -}
sBytesToInt64 :: [Sbyte] -> Int64
sBytesToInt64 = foldr f 0
where f (Byte b) i = (shiftL i 8) .|. (fromIntegral b)
f _ _ = 0
{- Convert a string to its sbyte representation -}
stringToSbytes :: String -> [Sbyte]
stringToSbytes [] = [Byte 0]
stringToSbytes (c:cs) = Byte (fromIntegral $ ord c) : stringToSbytes cs
{- Serialize an instruction to sbytes -}
insToSbytes :: Ins -> [Sbyte]
insToSbytes ins@(Ins op args) =
let err = error "insToSbytes: tried to serialize a label!"
check (Imm (Lbl _)) = err
check (Ind1 (Lbl _)) = err
check (Ind3 (Lbl _) _) = err
check _ = ()
in seq (map check args) [InsB0 ins, InsFrag, InsFrag, InsFrag]
{- Serialize a data element to sbytes -}
dataToSbytes :: Data -> [Sbyte]
dataToSbytes (Asciz s) = stringToSbytes s
dataToSbytes (Quad (Lit i)) = int64ToSbytes i
dataToSbytes (Quad (Lbl _)) = error "dataToSbytes: tried to serialize a label!"
{- It might be useful to toggle printing of intermediate states of your
simulator. -}
debug_simulator = False
{- Interpret a condition code with respect to the given flags. -}
--let interp_cnd {fo; fs; fz} : cnd -> bool = fun x -> failwith "interp_cnd unimplemented"
{- Maps an X86lite address into Some OCaml array index,
or None if the address is not within the legal address space. -}
--let map_addr (addr:quad) : int option =
-- failwith "map_addr not implemented"
{- Simulates one step of the machine:
- fetch the instruction at %rip
- compute the source and/or destination information from the operands
- simulate the instruction semantics
- update the registers and/or memory appropriately
- set the condition flags
-}
--let step (m:mach) : unit =
--failwith "step unimplemented"
{- Runs the machine until the rip register reaches a designated
memory address. -}
--let run (m:mach) : int64 =
-- while m.regs.(rind Rip) <> exit_addr do step m done;
-- m.regs.(rind Rax)
{- assembling and linking --------------------------------------------------- -}
{- A representation of the executable -}
--type exec = { entry : quad {- address of the entry point -}
-- ; text_pos : quad {- starting address of the code -}
-- ; data_pos : quad {- starting address of the data -}
-- ; text_seg : sbyte list {- contents of the text segment -}
-- ; data_seg : sbyte list {- contents of the data segment -}
-- }
{- Assemble should raise this when a label is used but not defined -}
--exception Undefined_sym of lbl
{- Assemble should raise this when a label is defined more than once -}
--exception Redefined_sym of lbl
{- Convert an X86 program into an object file:
- separate the text and data segments
- compute the size of each segment
Note: the size of an Asciz string section is (1 + the string length)
- resolve the labels to concrete addresses and 'patch' the instructions to
replace Lbl values with the corresponding Imm values.
- the text segment starts at the lowest address
- the data segment starts after the text segment
HINT: List.fold_left and List.fold_right are your friends.
-}
--let assemble (p:prog) : exec =
--failwith "assemble unimplemented"
{- Convert an object file into an executable machine state.
- allocate the mem array
- set up the memory state by writing the symbolic bytes to the
appropriate locations
- create the inital register state
- initialize rip to the entry point address
- initializes rsp to the last word in memory
- the other registers are initialized to 0
- the condition code flags start as 'false'
Hint: The Array.make, Array.blit, and Array.of_list library functions
may be of use.
-}
--let load {entry; text_pos; data_pos; text_seg; data_seg} : mach =
--failwith "load unimplemented"
| halfaya/cis341 | haskell/src/Simulator.hs | bsd-3-clause | 7,179 | 0 | 13 | 1,801 | 813 | 476 | 337 | 56 | 17 |
module Language.CCS.Printer where
import Language.CCS.Data
import Text.PrettyPrint
import qualified Data.HashSet as HS
import qualified Data.HashMap.Strict as HM
includeToC :: CInclude -> Doc
includeToC (CInclude s) = text "#include" <+> (doubleQuotes $ text s)
headersToC = vcat . map includeToC
nativeTxtToM (StructOffset _ _) = empty
nativeTxtToM (StructSize _) = empty
nativeTxtToM (MacroDef s) = text "macro_" <> (text s)
<+> text "="
<> (text s)
<> text "-;;-"
macroPrintStmt :: String -> Doc
macroPrintStmt s = nest 8 $ text "printf("
<> (doubleQuotes $ text "macro" <+> text s <+> text "=(%lu);\\n")
<+> text ","
<+> text s
<+> text ");"
structSizePrintStmt :: String -> Doc
structSizePrintStmt s = nest 8 $ text "printf("
<> (doubleQuotes $ text "sizeof" <+> text s <+> text "=(%lu);\\n")
<+> text ","
<+> text "sizeof(struct" <+> text s <> text ")"
<+> text ");"
offsetPrintStmt :: String -> String -> Doc
offsetPrintStmt s f = nest 8 $ text "printf("
<> (doubleQuotes $ text "offset" <+> text s <+> text f <+> text "=(%lu);\\n")
<+> text ","
<+> text "offsetof(struct" <+> text s <> text "," <+> text f <> text ")"
<+> text ");"
nativeTxtToC (MacroDef s) = empty -- vcat [text "#ifdef" <+> (text s), macroPrintStmt s, text "#endif"]
nativeTxtToC (StructSize s) = structSizePrintStmt s
nativeTxtToC (StructOffset s f) = offsetPrintStmt s f
printStmts = vcat . map nativeTxtToC . filter isNotMacro . HS.toList
macroStmts = vcat . map nativeTxtToM . filter isMacro . HS.toList
mainBegin :: Doc
mainBegin = text "int main(int argc, char **argv){"
mainClose :: Doc
mainClose = vcat [ nest 8 $ text "return 0;", text "}"]
mCodeBegin :: Doc
mCodeBegin = text "--CCS2CS--Macro-Expansions--"
stdhdrs = map CInclude ["stdio.h", "stddef.h","string.h", "errno.h"]
appendHdrs :: [CInclude] -> [CInclude]
appendHdrs hdrs = stdhdrs ++ hdrs
cCode :: HS.HashSet NativeTxt -> [CInclude] -> Doc
cCode set hdrs = vcat [headersToC . appendHdrs $ hdrs, mainBegin, printStmts set, mainClose]
mCode :: HS.HashSet NativeTxt -> [CInclude] -> Doc
mCode set hdrs = vcat [headersToC . appendHdrs $ hdrs, mCodeBegin, macroStmts set]
prologToDoc :: CSPrologue -> Doc
prologToDoc (CSPrologue lines) = vcat $ map text lines
nativeToDoc (NativeVal x) = text x
unkval = NativeVal "**UNKNOWN**"
extractNMap :: NativeTxt -> CCSMap -> Doc
extractNMap n = nativeToDoc . HM.lookupDefault unkval n
csValToDoc :: CCSMap -> CSVal -> Doc
csValToDoc nm (CFieldOffset s v) = extractNMap (StructOffset s v) nm
csValToDoc nm (CHashDef s) = extractNMap (MacroDef s) nm
csValToDoc nm (CSizeOf s) = extractNMap (StructSize s) nm
csValToDoc _ (CSVerbatim txt) = text txt
csValToDoc _ CDblHash = text "#"
epilogToDoc nm vals = hcat $ map (csValToDoc nm) vals
enumValToDoc :: CCSMap -> EnumValue -> Doc
enumValToDoc nm EmptyEnum = empty
enumValToDoc nm (FromMacro s) = extractNMap (MacroDef s) nm
enumValToDoc nm (EnumText s) = text s
enumValToDoc nm (EnumComplex vs) = hcat $ [lbrace] ++ ( map (enumValToDoc nm) vs) ++ [rbrace]
enumValToDoc nm (EnumSize s) = extractNMap (StructSize s) nm
enumValToDoc nm (EnumOffset s f) = extractNMap (StructOffset s f) nm
enumFieldToDoc :: CCSMap -> (String, EnumValue) -> Doc
enumFieldToDoc nm (name, EmptyEnum) = text name
enumFieldToDoc nm (name, v) = nest 4 $ text name <+> text "=" <+> (enumValToDoc nm v)
enumFieldsToDoc :: CCSMap -> [(String, EnumValue)] -> Doc
enumFieldsToDoc _ [] = empty
enumFieldsToDoc nm [single] = enumFieldToDoc nm single
enumFieldsToDoc nm (f:s:rest) = enumFieldToDoc nm f <+> comma $+$ (enumFieldsToDoc nm (s:rest))
clsFieldToDoc :: CCSMap -> (String ,String, EnumValue) -> Doc
clsFieldToDoc _ (typ,f, EmptyEnum) = nest 4 $ text "internal" <+> text "static" <+> text typ <+> text "{ get; set; }"
clsFieldToDoc nm (typ, f, EnumText s) = nest 4 $ hsep [text "internal", text "static", text typ , text f , text "=" , text s]
clsFieldToDoc nm (typ, f, e@(EnumComplex vs) ) = nest 4 $ hsep [text "internal", text "const", text typ , text f , enumValToDoc nm e]
clsFieldToDoc nm (typ, f, e ) = nest 4 $ hsep [text "internal", text "const", text typ , text f , text "=" , enumValToDoc nm e]
enumToDoc :: CCSMap -> String -> [(String, EnumValue)] -> Doc
enumToDoc nm enumName lst = nest 8 enumDef
where enumDef = vcat $ [text "internal" <+> text "enum",
lbrace,
enumFieldsToDoc nm lst,
rbrace]
clsToDoc :: CCSMap ->String -> [(String, String, EnumValue)] -> Doc
clsToDoc nm enumName lst = nest 8 clsDef
where clsDef = (vcat $ (text "internal" <+> text "static" <+> text "class" <> lbrace) : (map (clsFieldToDoc nm) lst) ) $$ rbrace
strToDoc :: CCSMap -> String ->String -> [(String, String, String)] -> Doc
strToDoc nm clsName cstr lst = nest 8 strDef
where strDef = vcat $ [text "internal" <+> text "class" <+> text clsName <> lbrace , consdef] ++ (map strFieldToDoc lst) ++ [genMeth,rbrace]
consdef = nest 4 $ hsep [ text "private" , text clsName , text "()", lbrace, rbrace]
genMeth = nest 4 $ vcat $ [ text "public" <+> text "static" <+> text clsName <+> text "Unmarshal(IntPtr _nativePointer)" <+> lbrace, instLine] ++
(map marshalFields lst) ++ [nest 4 $ text "return _instance;", rbrace]
strFieldToDoc (t, f, _) = nest 4 $ hsep [text "internal", text t, text f, semi]
marshalFields (t,f, cf) = nest 4 $ text "_instance." <> text f <+> equals <+> text "System.Runtime.InteropServices.Marshal.Read" <> text t <>
lparen <> text "_nativePointer" <> comma <+> (extractNMap (StructOffset cstr cf) nm) <> rparen <> semi
instLine = nest 4 $ text clsName <+> text "_instance" <+> equals <+> text "new" <+> text clsName <> lparen <> rparen <> semi
ccsTypeToDoc :: CCSMap -> CCSType -> Doc
ccsTypeToDoc nm (CSEnum s lst) = enumToDoc nm s lst
ccsTypeToDoc nm (CSClass s lst) = clsToDoc nm s lst
ccsTypeToDoc nm (CSStruct s1 s2 lst) = strToDoc nm s1 s2 lst
ccsFileToDoc :: CCSMap -> CCSFile -> Doc
ccsFileToDoc nm (CCSFile p _ _ _ types e) = vcat $ [prologToDoc p ] ++ map (ccsTypeToDoc nm) types ++ [epilogToDoc nm e]
csFile :: CCSMap -> CCSFile -> String
csFile nmap ccs = render $ ccsFileToDoc nmap ccs
| kapilash/dc | src/ccs2c/ccs2cs-lib/src/Language/CCS/Printer.hs | bsd-3-clause | 6,729 | 0 | 18 | 1,716 | 2,467 | 1,239 | 1,228 | 109 | 1 |
-- | Helper functions
module Matasano.Utils
(
usage
) where
import System.Environment (getProgName)
import System.Exit (exitWith, ExitCode(..))
usage :: String -> IO ()
usage args = do
progName <- getProgName
putStrLn $ "Usage: " ++ progName ++ " " ++ args
exitWith $ ExitFailure 1 | carletes/matasano | src/Matasano/Utils.hs | bsd-3-clause | 307 | 0 | 10 | 70 | 97 | 52 | 45 | 10 | 1 |
module CLaSH.Normalize.Types
( NormalizeState(..)
, NormalizeSession
, NormalizeStep
, nsNormalized
, nsBindings
, nsNetlistState
, emptyNormalizeState
)
where
-- External Modules
import Control.Monad.State.Strict (StateT)
import qualified Data.Label
import Data.Map (Map,empty)
import Language.KURE (RewriteM)
-- GHC API
import qualified CoreSyn
-- Internal Modules
import CLaSH.Netlist.Types (NetlistState, empytNetlistState)
import CLaSH.Util.CoreHW (Term, Var, CoreContext, TransformSession)
-- | State kept by the normalization phase
data NormalizeState = NormalizeState
{
-- | Cached normalized binders
_nsNormalized :: Map Var Term
-- | Cached global binders
, _nsBindings :: Map Var Term
-- | The state of the netlist-generation stage, intended to decide if
-- types are representable
, _nsNetlistState :: NetlistState
}
-- Make lenses for the normalization stage state
Data.Label.mkLabels [''NormalizeState]
-- | Create an empty state for the normalization session
emptyNormalizeState ::
Map Var Term -- ^ Cache of global binders
-> NetlistState -- ^ Current netlist state
-> NormalizeState
emptyNormalizeState bindings nlState = NormalizeState empty bindings nlState
-- | The normalization session is a transformation session with extra state
-- to cache information on already normalized binders. Needs IO to load
-- external binder information
type NormalizeSession = TransformSession (StateT NormalizeState IO)
type NormalizeStep =
[CoreContext]
-> Term
-> RewriteM NormalizeSession [CoreContext] Term
| christiaanb/clash-tryout | src/CLaSH/Normalize/Types.hs | bsd-3-clause | 1,616 | 0 | 9 | 302 | 258 | 158 | 100 | -1 | -1 |
{-# LANGUAGE TemplateHaskell, GeneralizedNewtypeDeriving, FlexibleInstances, MultiParamTypeClasses #-}
module Match ( Bindings
, Value(..)
, Matcher
, runMatcher
, unA
, unB
, unS
, unN
, unL
, Pack
, pack
, unpack
, parseMatch
) where
import Control.Applicative hiding ((<|>), many)
import Control.Monad
import Control.Monad.Reader
import Control.Monad.State
import Control.Monad.Error
import Data.Accessor
import Data.Accessor.Template
import qualified Data.Map as M
import Text.Parsec.Prim
import Text.Parsec.Char
import Text.Parsec.Combinator
import Text.Parsec.String
import ParserUtils
import Syscall
data Value = B Bool | A String | N Int | S String | L [Value]
deriving (Eq, Show)
type Bindings = M.Map String Value
newtype Matcher a = Matcher { unMatcher :: ErrorT String (StateT Bindings (Reader Bindings)) a }
deriving ( Functor
, Applicative
, Monad
, MonadReader Bindings
, MonadError String
, MonadState Bindings)
runMatcher :: Matcher a -> Int -> Syscall -> Bindings -> (Either String a, Bindings)
runMatcher m t s b = runReader (runStateT (runErrorT (unMatcher m)) b) (mkEnv t s)
unB :: Value -> Matcher Bool
unB (B x) = return x
unB x = throwError $ "Expected boolean, got " ++ show x
unN :: Value -> Matcher Int
unN (N x) = return x
unN x = throwError $ "Expected integer, got " ++ show x
unS :: Value -> Matcher String
unS (S x) = return x
unS x = throwError $ "Expected string, got " ++ show x
unA :: Value -> Matcher String
unA (A x) = return x
unA x = throwError $ "Expected atom, got " ++ show x
unL :: Value -> Matcher [Value]
unL (L x) = return x
unL x = throwError $ "Expected list, got " ++ show x
class Pack a where
pack :: a -> Value
unpack :: Value -> Matcher a
instance Pack Int where
pack = N
unpack = unN
instance Pack [Char] where
pack = S
unpack = unS
instance Pack Bool where
pack = B
unpack = unB
instance Pack [Value] where
pack = L
unpack = unL
typeN :: Value
typeN = A "number"
typeS :: Value
typeS = A "string"
typeM :: Value
typeM = A "mask"
typeL :: Value
typeL = A "labelled"
typeO :: Value
typeO = A "object"
encode :: Argument -> Value
encode (NumLiteral n) = L [typeN, N n]
encode (StrLiteral s) = L [typeS, S s]
encode (Mask strs) = L (typeM : map A strs)
encode (Labelled l a) = L [typeL, A l, encode a]
encode (Object a) = L (typeO : map encode a)
mkEnv :: Int -> Syscall -> Bindings
mkEnv t s = M.fromList [ ("tid", N t)
, ("syscall", S (getVal scName s))
, ("retcode", N (getVal scRet s))
, ("args", L (map encode $ getVal scArgs s))
]
boolLit :: Parser Bool
boolLit = char '#' >> ((char 'f' >> return False) <|> (char 't' >> return True))
quoted :: Parser Value
quoted = do
char '\''
e <- expr
return $ L [A "quote", e]
expr :: Parser Value
expr = quoted <|>
(B <$> boolLit) <|>
(A <$> identifier) <|>
(N <$> number) <|>
(S <$> doubleQuoted) <|>
(L <$> list)
list = char '(' *> exprs <* char ')'
exprs :: Parser [Value]
exprs = spaces *> many (expr <* spaces)
parseMatch :: String -> Either String Value
parseMatch s = case parse exprs "" s of
Left e -> Left $ show e
Right [] -> Left $ "Empty expression"
Right [v] -> Right v
Right s -> Right $ L (A "progn" : s) | ratatosk/traceblade | Match.hs | bsd-3-clause | 3,710 | 0 | 12 | 1,183 | 1,340 | 705 | 635 | 114 | 4 |
module Tests.Integration where
import Test.Tasty ( TestTree, testGroup)
import Test.Tasty.HUnit
integrationTests :: TestTree
integrationTests = testGroup "Integration Tests"
[ testCase "Exit failure with no cabal files."
testNoCabalFiles
]
testNoCabalFiles :: Assertion
testNoCabalFiles = assertFailure "fail on purpose."
| creswick/cabal-query | tests/src/Tests/Integration.hs | bsd-3-clause | 386 | 0 | 7 | 101 | 61 | 35 | 26 | 9 | 1 |
---------------------------------------------------------------------------------
-- |
-- Module : Math.LinearEquationSolver
-- Copyright : (c) Levent Erkok
-- License : BSD3
-- Maintainer : [email protected]
-- Stability : stable
--
-- (The linear equation solver library is hosted at <http://github.com/LeventErkok/linearEqSolver>.
-- Comments, bug reports, and patches are always welcome.)
--
-- Solvers for linear equations over integers and rationals. Both single solution and all
-- solution variants are supported.
---------------------------------------------------------------------------------
module Math.LinearEquationSolver (
-- * Available SMT solvers
-- $solverInfo
Solver(..)
-- * Solutions over Integers
, solveIntegerLinearEqs
, solveIntegerLinearEqsAll
-- * Solutions over Rationals
, solveRationalLinearEqs
, solveRationalLinearEqsAll
) where
import Data.SBV
-- | Solve a system of linear integer equations. The first argument is
-- the matrix of coefficients, known as @A@, of size @mxn@. The second argument
-- is the vector of results, known as @b@, of size @mx1@. The result will be
-- either `Nothing`, if there is no solution, or @Just x@ -- such that @Ax = b@ holds.
-- (Naturally, the result @x@ will be a vector of size @nx1@ in this case.)
--
-- Here's an example call, to solve the following system of equations:
--
-- @
-- 2x + 3y + 4z = 20
-- 6x - 3y + 9z = -6
-- 2x + z = 8
-- @
--
-- >>> solveIntegerLinearEqs Z3 [[2, 3, 4],[6, -3, 9],[2, 0, 1]] [20, -6, 8]
-- Just [5,6,-2]
--
-- The first argument picks the SMT solver to use. Valid values are 'z3' and
-- 'cvc4'. Naturally, you should have the chosen solver installed on your system.
--
-- In case there are no solutions, we will get `Nothing`:
--
-- >>> solveIntegerLinearEqs Z3 [[1], [1]] [2, 3]
-- Nothing
--
-- Note that there are no solutions to this second system as it stipulates the unknown is
-- equal to both 2 and 3. (Overspecified.)
solveIntegerLinearEqs :: Solver -- ^ SMT Solver to use
-> [[Integer]] -- ^ Coefficient matrix (A)
-> [Integer] -- ^ Result vector (b)
-> IO (Maybe [Integer]) -- ^ A solution to @Ax = b@, if any
solveIntegerLinearEqs cfg coeffs res = extractModel `fmap` satWith (defaultSolverConfig cfg) cs
where cs = buildConstraints "solveIntegerLinearEqs" coeffs res
-- | Similar to `solveIntegerLinearEqs`, except in case the system has an infinite
-- number of solutions, then it will return the number of solutions requested. (Note
-- that if the system is underspecified, then there are an infinite number of
-- solutions.) So, the result can be empty, a singleton, or precisely the number requested, last of
-- which indicates there are an infinite number of solutions.
--
-- Here's an example call, where we underspecify the system and hence there are
-- multiple (in this case an infinite number of) solutions. Here, we ask for the first
-- 3 elements for testing purposes.
--
-- @
-- 2x + 3y + 4z = 20
-- 6x - 3y + 9z = -6
-- @
--
-- We have:
--
-- >>> solveIntegerLinearEqsAll Z3 3 [[2, 3, 4],[6, -3, 9]] [20, -6]
-- [[-47,-2,30],[-34,0,22],[-21,2,14]]
--
-- The solutions you get might differ, depending on what the solver returns. (Though they'll be correct!)
solveIntegerLinearEqsAll :: Solver -- ^ SMT Solver to use
-> Int -- ^ Maximum number of solutions to return, in case infinite
-> [[Integer]] -- ^ Coefficient matrix (A)
-> [Integer] -- ^ Result vector (b)
-> IO [[Integer]] -- ^ All solutions to @Ax = b@
solveIntegerLinearEqsAll s maxNo coeffs res = extractModels `fmap` allSatWith cfg cs
where cs = buildConstraints "solveIntegerLinearEqsAll" coeffs res
cfg = (defaultSolverConfig s) {allSatMaxModelCount = Just maxNo}
-- | Solve a system of linear equations over rationals. Same as the integer
-- version `solveIntegerLinearEqs`, except it takes rational coefficients
-- and returns rational results.
--
-- Here's an example call, to solve the following system of equations:
--
-- @
-- 2.4x + 3.6y = 12
-- 7.2x - 5y = -8.5
-- @
--
-- >>> solveRationalLinearEqs Z3 [[2.4, 3.6],[7.2, -5]] [12, -8.5]
-- Just [245 % 316,445 % 158]
solveRationalLinearEqs :: Solver -- ^ SMT Solver to use
-> [[Rational]] -- ^ Coefficient matrix (A)
-> [Rational] -- ^ Result vector (b)
-> IO (Maybe [Rational]) -- ^ A solution to @Ax = b@, if any
solveRationalLinearEqs cfg coeffs res = (fmap from . extractModel) `fmap` satWith (defaultSolverConfig cfg) cs
where to = map (fromRational :: Rational -> AlgReal)
from = map (toRational :: AlgReal -> Rational)
cs = buildConstraints "solveRationalLinearEqs" (map to coeffs) (to res)
-- | Solve a system of linear equations over rationals. Similar to `solveRationalLinearEqs`,
-- except if the system is underspecified, then returns the number of solutions requested.
--
-- Example system:
--
-- @
-- 2.4x + 3.6y = 12
-- @
--
-- In this case, the system has infinitely many solutions. We can compute three of them as follows:
--
-- >>> solveRationalLinearEqsAll Z3 3 [[2.4, 3.6]] [12]
-- [[0 % 1,10 % 3],[3 % 4,17 % 6],[3 % 2,7 % 3]]
--
-- The solutions you get might differ, depending on what the solver returns. (Though they'll be correct!)
solveRationalLinearEqsAll :: Solver -- ^ SMT Solver to use
-> Int -- ^ Maximum number of solutions to return, in case infinite
-> [[Rational]] -- ^ Coefficient matrix (A)
-> [Rational] -- ^ Result vector (b)
-> IO [[Rational]] -- ^ All solutions to @Ax = b@
solveRationalLinearEqsAll s maxNo coeffs res = (map from . extractModels) `fmap` allSatWith cfg cs
where to = map (fromRational :: Rational -> AlgReal)
from = map (toRational :: AlgReal -> Rational)
cs = buildConstraints "solveRationalLinearEqsAll" (map to coeffs) (to res)
cfg = (defaultSolverConfig s) {allSatMaxModelCount = Just maxNo}
-- | Build the constraints as given by the coefficient matrix and the resulting vector
buildConstraints :: (Ord a, Num a, SymVal a) => String -> [[a]] -> [a] -> Symbolic SBool
buildConstraints f coeffs res
| m == 0 || any (/= n) ns || m /= length res
= error $ f ++ ": received ill-formed input."
| True
= do xs <- mkFreeVars n
let rowEq row r = sum (zipWith (*) xs row) .== r
solve $ zipWith rowEq (map (map literal) coeffs) (map literal res)
where m = length coeffs
n:ns = map length coeffs
{- $solverInfo
Note that while we allow all SMT-solvers supported by SBV to be used, not all will work. In particular,
the backend solver will need to understand unbounded integers and rationals. Currently, the following
solvers provide the required capability: 'Z3', 'CVC4', and 'MathSAT'. Passing other instances will result
in an "unsupported" error, though this can of course change as the SBV package itself evolves.
-}
| LeventErkok/linearEqSolver | Math/LinearEquationSolver.hs | bsd-3-clause | 7,353 | 0 | 14 | 1,845 | 845 | 499 | 346 | 49 | 1 |
module Data.Geo.GPX.Lens.DgpsidL where
import Data.Geo.GPX.Type.DgpsStation
import Data.Lens.Common
class DgpsidL a where
dgpsidL :: Lens a (Maybe DgpsStation)
| tonymorris/geo-gpx | src/Data/Geo/GPX/Lens/DgpsidL.hs | bsd-3-clause | 165 | 0 | 9 | 22 | 48 | 29 | 19 | 5 | 0 |
-- Programatica Front-End Commands, level 0
module Pfe0Cmds where
import Prelude hiding (print,putStr,putStrLn,catch,readFile)
import List((\\))
import Monad(unless,when)
import Maybe(fromJust)
import PFE0
import HsName(ModuleName(..),isMainModule,sameModuleName)
--import HsConstants(main_mod)
import HsLexerPass1(rmSpace,Pos(line)) -- for lines of code metrics
import PfeParse
import PrettyPrint
import MUtils
import SimpleGraphs(reverseGraph,reachable)
import DirUtils(optCreateDirectory)
import AbstractIO
import Statistics
pfe0 parseModule args = runPFE0Cmds () pfe0Cmds parseModule args
--runPFE0Cmds ext cmds = runPFE0 ext $ doCmd (cmds, projectStatus)
runPFE0Cmds ext cmds = runCmds (runPFE0 ext) cmds
pfe0Cmds = projman++graphqueries
addHelpCmd prg cmds0 = cmds where cmds=cmds0++helpCmd prg cmds
helpCmd prg cmds =
[("help",(noArgs (putStrLn (usage prg cmds)),"list available commands"))]
projman =
-- Project management (a project is a set of source files)
[("new" , (qfileArgs new, "create a new project containing zero or more files")),
("add" , (qfileArgs add, "add files to the project")),
("remove" , (qfileArgs remove, "remove files from the project")),
("prune" , (moduleArgs prune,"remove unreachable modules from the project")),
("files" , (noArgs files,"list files in the project")),
("options" , (noArgs options,"show options in effect"))]
graphqueries =
-- Module graph queries
[("modules" , (moduleArgs modules,"show a topologically sorted list of modules")),
("graph" , (graphArgs graph,"show module dependecy (sub)graph")),
-- ("dirgraph", (moduleArgs dirgraph,"show source directory dependecy (sub)graph")),
-- ("dotdirgraph", (moduleArgs dotdirgraph,"dot format source directory dependecy (sub)graph")),
("unused" , (moduleArgs unused,"list unimported and unreachable modules")),
("file" , (moduleArg file,"which file is the module in")),
("module" , (fileArg module',"which module does the file contain")),
("loc" , (moduleArgs locModules, "number of lines of code")),
("sizemetrics" , (noArgs sizeMetrics, "number of lines per module metrics")),
("locmetrics" , (noArgs locMetrics, "number of lines of code per module metrics")),
("importmetrics",(noArgs importMetrics, "number of imports per module metrics")),
("exportmetrics",(noArgs exportMetrics, "number of exports (importers) per module metrics"))]
--- Project management ---------------------------------------------------------
new quiet args = do newProject; addPaths quiet args
add quiet args = addPaths quiet args
remove quiet args = removePaths quiet args
files = putStr . unlines =<< allFiles
options = print =<< parserFlags
qfileArgs f = f #@ kwOption "-quiet" <@ filenames
--- Module graph queries -------------------------------------------------------
modules ms = do g <- getSortedSubGraph (just ms)
let sccs = map (map (fst.snd)) g
putStrLn "Topologically sorted strongly connected components:"
putStr (unlines (map (unwords.map pp) sccs))
graphArgs = moduleArgs' graphOpts
where
graphOpts = (,,) #@ kwOption "-rev" <@ kwOption "-dot" <@ kwOption "-dir"
graph (rev,dot,dir) =
pput . out_conv_dirs @@ getSubGraph . just
where
out_conv_dirs = if dir then out_conv . srcdirGraph else out_conv . map snd
out_conv = out . conv
out = if dot then dotFormat else makeFormat
conv = if rev then reverseGraph else id
-- Dot format functions contributed by Claus Reinke:
dotFormat g =
"digraph ModuleGraph {size=\"7.5,10.5\";ratio=fill;" $$
vcat [q x<>"->"<>braces (fsep [q d<>";"|d<-xs])|(x,xs)<-g] $$
"}"
where
q = doubleQuotes
makeFormat g = vcat [x<>":"<+>fsep xs|(x,xs)<-g]
--dirgraph ms = pput . makeFormat =<< srcdirGraph ms
--dotdirgraph ms = pput . dotFormat =<< srcdirGraph ms
srcdirGraph g = dg
where moddirs = [(m,dirname path)|(path,(m,_))<-g]
moddir m = fromJust (lookup m moddirs)
dg = mapSnd usort $
collectByFst
[(moddir m,dir')|(_,(m,ms))<-g,dir'<-usort (map moddir ms)]
dirname = current . reverse . dropWhile (/='/') . reverse
where current "" = "./"
current path = path
file m =
do g <- getCurrentModuleGraph
pput $ vcat [m<>":"<+>f|(f,(m',_))<-g,m'==m]
module' f =
do g <- getCurrentModuleGraph
pput $ vcat [f<>":"<+>m|(f',(m,_))<-g,f'==f]
getUnused ms =
do fg <- getCurrentModuleGraph
let g = map snd fg
unimported = map fst g \\ [m|(m,_:_)<-reverseGraph g]
roots = if null ms then mains else ms
where mains = [m|(m,_)<-g,isMainModule m]
r = reachable g roots
unreached = map fst g \\ r
when (null roots) $
fail "No root modules given, no Main module in the project"
return (fg,roots,unimported,unreached)
mainModules =
do fg <- getCurrentModuleGraph
return [m|(f,(m,_))<-fg,isMainModule m]
unused ms =
do (_,roots,us,unr) <- getUnused ms
if null us -- unlikely...
then putStrLn "All modules are imported somewhere"
else pput $ "The following modules are never imported:" $$
nest 4 (fsep us)
unless (null unr) $
do pput $
sep [ppi "The following modules are unreachable from",
nest 2 (fsep roots<>":")]
pput $ nest 4 (fsep unr)
prune ms =
do (fg,_,_,unreached) <- getUnused ms
removePaths False [f|(f,(m,_))<-fg,m `elem` unreached]
sizeMetrics =
pput . ppStatistics "number of lines" "module"
=<< mapM (forkM (fst.snd) (size #. readFile . fst))
=<< getCurrentModuleGraph
where
size = length . lines
locMetrics =
pput . ppStatistics "number of lines of code" "module"
=<< mapM (forkM (fst.snd) (loc . snd #. lex0SourceFile.fst))
=<< getCurrentModuleGraph
--forkM f g x = (,) (f x) # g x
forkM f g x =
do y <- g x
-- seq to process one file at a time in locMetrics & sizeMetrics
seq y (return (f x,y))
loc = length . squeezeDups . map (line.fst.snd) . rmSpace
locModules = mapM_ locModule
locModule = locFile @@ findFile
locFile = pput . loc . snd @@ lex0SourceFile
importMetrics = graphMetrics id "number of imports"
exportMetrics = graphMetrics reverseGraph "number of importers"
graphMetrics f lbl =
do g <- mapSnd length . f . map snd # getCurrentModuleGraph
pput $ ppStatistics lbl "module" g
| forste/haReFork | tools/pfe/Pfe0Cmds.hs | bsd-3-clause | 6,354 | 48 | 19 | 1,284 | 1,966 | 1,067 | 899 | -1 | -1 |
module Kite.Test.TypeCheck (typeCheckTests) where
import Prelude hiding (lex)
import Test.Tasty
import Test.Tasty.HUnit
import Kite.Driver
import Kite.Environment
data TypeCheckError = TypeE | RefE | ArE | UnE deriving (Show, Eq)
run prog = case (analyze False . parse . lex) prog of
Right _ -> Nothing
Left ((TypeError _), _) -> Just TypeE
Left ((ReferenceError _), _) -> Just RefE
Left ((ArityError _), _) -> Just ArE
Left (UnknownError, _) -> Just UnE
-- test expression
testE name ex prog = testCase name $ run prog @?= ex
typeCheckTests =
testGroup "Inference test"
[ testGroup "Function application"
[ testE "Simple function application"
Nothing "id = |x| -> { return x}\
\one = id(1)"
, testE "Immediate function application"
Nothing "one = |x| -> { return x}(1)"
, testE "Immediate application of non-function"
(Just TypeE) "foo = \"foo\"(1)"
, testE "Application of returned function (HoF)"
Nothing "id = |x| -> { return x}\
\one = id(|x| -> { return x})(1)"
, testE "Multiple nested applications of returned functions (HoF)"
Nothing "id = |x| -> { return x }\
\foo = id(|x| -> { \
\ return |y| -> {\
\ return x + y\
\ }\
\})(1)(1)"
]
, testGroup "Type Check"
[ testE "Assignment"
Nothing "one = 2"
, testE "Reassignment (top level)"
(Just RefE) "one = 2; one = 1;"
, testE "Reassignment"
(Just RefE) "main = -> { one = 2; one = 1; }"
, testE "Illegal reassignment (top level)"
(Just RefE) "one = 2; one = \"the\";"
, testE "Illegal reassignment"
(Just RefE) "main = -> { one = 2; one = \"the\"; }"
, testE "Reference"
Nothing "main = -> { one = 1; two = 1 + one; }"
, testE "Reference not defined"
(Just RefE) "two = 1 + one"
, testE "Reference itself not defined"
(Just RefE) "two = 1 + two"
, testE "Function call"
Nothing "one = |a| -> { return a }; main = -> { one(1) }"
, testE "Function call with arg of wrong type"
(Just TypeE) "one = |a| -> { return 1+a }; main = -> { one(\"1\") }"
, testE "Function call with multiple parameters"
Nothing "foo = |a, b| -> { return 1 }; main = -> { foo(1, 2) }"
, testE "Function call with wrong number of args"
(Just TypeE) "foo = |a| -> { return a }; main = -> { foo(1, 2) }"
, testE "Function call to undefined function"
(Just RefE) "main = -> { foo(2) }"
, testE "Recursive function"
Nothing "fib = |n| -> { return if n == 0 then 0 else if n == 1 then 1 else fib (n - 1) + fib (n - 2)}; main = -> { fib(5) }"
, testE "List assignment same type"
Nothing "list = [1, 2, 3]"
, testE "List assignment illegal values"
(Just TypeE) "list = [1, True, \"Three\"]"
, testE "Varying types in list"
(Just TypeE) "list = [1, 2.0, 3]"
, testE "Append to list"
Nothing "list = [1, 2] + [3]"
, testE "Append to list with wrong type"
(Just TypeE) "list = [1, 2] + 3.0"
, testE "Concatenate string"
Nothing "s = \"str\" + \"ing\""
, testE "Concatenate string with numbers in sting"
Nothing "s = \"2\" + \"2.0\""
, testE "Concatenate string with numbers"
(Just TypeE) "s = \"2\" + 2.0"
, testE "Illegal arithmic operator"
(Just TypeE) "list = [1, 2, 3] / [4, 5, 6]; s = \"test\" / \"string\"; a = 1 + \"two\""
]
]
| kite-lang/kite | tests/Kite/Test/TypeCheck.hs | mit | 3,506 | 0 | 11 | 1,043 | 620 | 317 | 303 | 74 | 5 |
module DeriveNounTests (tests) where
import Data.Acquire
import Data.Conduit
import Data.Conduit.List
import Test.QuickCheck hiding ((.&.))
import Test.Tasty
import Test.Tasty.QuickCheck
import Test.Tasty.TH
import Urbit.Prelude
import Urbit.Vere.Log
import Urbit.Vere.Pier.Types
import Control.Concurrent (runInBoundThread, threadDelay)
import Data.LargeWord (LargeKey(..))
import GHC.Natural (Natural)
import qualified Urbit.Vere.Log as Log
-- Sum Types -------------------------------------------------------------------
data Nums = One | Two | TwentyTwo | NineHundredNintyNine
deriving (Eq, Show, Enum, Bounded)
data ThreeWords = ThreeWords Word Word Word
deriving (Eq, Show)
data FooBar = FooBarQueenAlice Word Word
| FooBarBob Word
| FooBarCharlie
deriving (Eq, Show)
data BarZaz = BZQueenAlice Word Word
| BZBob Word
| BZCharlie
deriving (Eq, Show)
data ZazBaz = QueenAlice Word Word
| Bob Word
| Charlie
deriving (Eq, Show)
data Empty
data Poly a b = PLeft a
| PRite b
deriving (Eq, Show)
deriveNoun ''Nums
deriveNoun ''ThreeWords
deriveNoun ''FooBar
deriveNoun ''BarZaz
deriveNoun ''ZazBaz
deriveNoun ''Empty
deriveNoun ''Poly
instance Arbitrary ThreeWords where
arbitrary = ThreeWords <$> arbitrary <*> arbitrary <*> arbitrary
instance Arbitrary Nums where
arbitrary = oneof (pure <$> [ minBound .. maxBound ])
instance Arbitrary FooBar where
arbitrary = oneof [ FooBarQueenAlice <$> arbitrary <*> arbitrary
, FooBarBob <$> arbitrary
, pure FooBarCharlie
]
instance Arbitrary BarZaz where
arbitrary = oneof [ BZQueenAlice <$> arbitrary <*> arbitrary
, BZBob <$> arbitrary
, pure BZCharlie
]
instance Arbitrary ZazBaz where
arbitrary = oneof [ QueenAlice <$> arbitrary <*> arbitrary
, Bob <$> arbitrary
, pure Charlie
]
instance (Arbitrary a, Arbitrary b) => Arbitrary (Poly a b) where
arbitrary = oneof [ PLeft <$> arbitrary
, PRite <$> arbitrary
]
-- Utils -----------------------------------------------------------------------
roundTrip :: forall a. (Eq a, ToNoun a, FromNoun a) => a -> Bool
roundTrip x = Just x == fromNoun (toNoun x)
throughNoun :: (ToNoun a, FromNoun b) => a -> Maybe b
throughNoun = fromNoun . toNoun
nounEquiv :: (Eq a, Eq b, ToNoun a, ToNoun b, FromNoun a, FromNoun b)
=> (a -> b) -> a -> Bool
nounEquiv cvt x =
and [ Just x == throughNoun y
, Just y == throughNoun x
]
where y = cvt x
-- Sanity Checks ---------------------------------------------------------------
enumSanity :: Nums -> Bool
enumSanity x = toNoun x == byHand x
where
byHand = \case
One -> toNoun (Cord "one")
Two -> toNoun (Cord "two")
TwentyTwo -> toNoun (Cord "twenty-two")
NineHundredNintyNine -> toNoun (Cord "nine-hundred-ninty-nine")
recSanity :: ThreeWords -> Bool
recSanity x = toNoun x == byHand x
where
byHand (ThreeWords x y z) = toNoun (x, y, z)
sumSanity :: ZazBaz -> Bool
sumSanity x = toNoun x == byHand x
where
byHand = \case
QueenAlice x y -> toNoun (Cord "queen-alice", x, y)
Bob x -> toNoun (Cord "bob", x)
Charlie -> toNoun (Cord "charlie")
abbrPrefixSanity :: BarZaz -> Bool
abbrPrefixSanity x = toNoun x == byHand x
where
byHand = \case
BZQueenAlice x y -> toNoun (Cord "queen-alice", x, y)
BZBob x -> toNoun (Cord "bob", x)
BZCharlie -> toNoun (Cord "charlie")
typePrefixSanity :: FooBar -> Bool
typePrefixSanity x = toNoun x == byHand x
where
byHand = \case
FooBarQueenAlice x y -> toNoun (Cord "queen-alice", x, y)
FooBarBob x -> toNoun (Cord "bob", x)
FooBarCharlie -> toNoun (Cord "charlie")
-- Strip Sum Prefixes ----------------------------------------------------------
barZazBaz :: BarZaz -> Bool
barZazBaz = nounEquiv $ \case BZQueenAlice x y -> QueenAlice x y
BZBob x -> Bob x
BZCharlie -> Charlie
fooBarBaz :: FooBar -> Bool
fooBarBaz = nounEquiv $ \case FooBarQueenAlice x y -> QueenAlice x y
FooBarBob x -> Bob x
FooBarCharlie -> Charlie
--------------------------------------------------------------------------------
tests :: TestTree
tests =
testGroup "Log"
[ testProperty "Enum Sanity" $ enumSanity
, testProperty "Sum Sanity" $ sumSanity
, testProperty "Record Sanity" $ recSanity
, testProperty "Type-Prefix Sanity" $ abbrPrefixSanity
, testProperty "Abbrv-Prefix Sanity" $ typePrefixSanity
, testProperty "Round Trip Rec (Poly)" $ roundTrip @(Poly Bool Bool)
, testProperty "Round Trip Rec (ThreeWords)" $ roundTrip @ThreeWords
, testProperty "Round Trip Enum (Nums)" $ roundTrip @Nums
, testProperty "Round Trip Sum (FooBar)" $ roundTrip @FooBar
, testProperty "Round Trip Sum (BarZaz)" $ roundTrip @BarZaz
, testProperty "Round Trip Sum (ZazBaz)" $ roundTrip @ZazBaz
, testProperty "Prefix Test 1" $ barZazBaz
, testProperty "Prefix Test 2" $ fooBarBaz
]
-- Generate Arbitrary Values ---------------------------------------------------
arb :: Arbitrary a => Gen a
arb = arbitrary
| ngzax/urbit | pkg/hs/urbit-king/test/DeriveNounTests.hs | mit | 5,715 | 0 | 12 | 1,684 | 1,550 | 801 | 749 | -1 | -1 |
{-# LANGUAGE Arrows #-}
{-# LANGUAGE FlexibleContexts #-}
module SugarScape.Agent.Agent
( agentMsf
) where
import Control.Monad.Random
import Control.Monad.Trans.MSF.Reader
import Control.Monad.Trans.MSF.State
import Control.Monad.Trans.MSF.Writer
import Data.MonadicStreamFunction
import SugarScape.Agent.Ageing
import SugarScape.Agent.Common
import SugarScape.Agent.Culture
import SugarScape.Agent.Disease
import SugarScape.Agent.Dying
import SugarScape.Agent.Loan
import SugarScape.Agent.Mating
import SugarScape.Agent.Metabolism
import SugarScape.Agent.Move
import SugarScape.Agent.Polution
import SugarScape.Agent.Trading
import SugarScape.Agent.Utils
import SugarScape.Core.Common
import SugarScape.Core.Model
import SugarScape.Core.Utils
------------------------------------------------------------------------------------------------------------------------
agentMsf :: RandomGen g => SugarScapeAgent g
agentMsf params aid s0 = feedback s0 (proc (evt, s) -> do
-- WriterT for the AgentOut, the agent never reads from it!
(s', (ao', _)) <- runStateS (runReaderS (runWriterS generalEventHandler)) -< (s, ((params, aid), evt))
let obs = sugObservableFromState s
returnA -< ((ao', obs), s'))
generalEventHandler :: RandomGen g => EventHandler g
generalEventHandler =
-- optionally switching the top event handler
continueWithAfter
(proc evt ->
case evt of
Tick dt -> do
mhdl <- arrM handleTick -< dt
returnA -< ((), mhdl)
-- MATING EVENTS
(DomainEvent sender (MatingRequest otherGender)) -> do
arrM (uncurry handleMatingRequest) -< (sender, otherGender)
returnA -< ((), Nothing)
(DomainEvent sender (MatingTx childId)) -> do
arrM (uncurry handleMatingTx) -< (sender, childId)
returnA -< ((), Nothing)
-- INHERITANCE EVENTS
(DomainEvent _ (Inherit share)) -> do
arrM handleInheritance -< share
returnA -< ((), Nothing)
-- CULTURAL PROCESS EVENTS
(DomainEvent sender (CulturalProcess tag)) -> do
arrM (uncurry handleCulturalProcess) -< (sender, tag)
returnA -< ((), Nothing)
-- COMBAT EVENTS
(DomainEvent sender KilledInCombat) -> do
arrM handleKilledInCombat -< sender
returnA -< ((), Nothing)
-- TRADING EVENTS
(DomainEvent sender (TradingOffer traderMrsBefore traderMrsAfter)) -> do
arrM (uncurry3 handleTradingOffer) -< (sender, traderMrsBefore, traderMrsAfter)
returnA -< ((), Nothing)
-- LOAN EVENTS
(DomainEvent _ (LoanOffer loan)) -> do
arrM handleLoanOffer -< loan
returnA -< ((), Nothing)
(DomainEvent sender (LoanPayback loan sugarBack spiceBack)) -> do
arrM (uncurry4 handleLoanPayback) -< (sender, loan, sugarBack, spiceBack)
returnA -< ((), Nothing)
(DomainEvent sender (LoanLenderDied children)) -> do
arrM (uncurry handleLoanLenderDied) -< (sender, children)
returnA -< ((), Nothing)
(DomainEvent sender (LoanInherit loan)) -> do
arrM (uncurry handleLoanInherit) -< (sender, loan)
returnA -< ((), Nothing)
-- DISEASE EVENTS
(DomainEvent _ (DiseaseTransmit disease)) -> do
arrM handleDiseaseTransmit -< disease
returnA -< ((), Nothing)
_ -> do
aid <- constM myId -< ()
returnA -< error $ "Agent " ++ show aid ++ ": undefined event " ++ show evt ++ " in agent, terminating!")
handleTick :: RandomGen g
=> DTime
-> AgentLocalMonad g (Maybe (EventHandler g))
handleTick dt = do
agentAgeing dt
harvestAmount <- agentMove
metabAmount <- agentMetabolism
-- initialize net-income to gathering minus metabolism, might adjusted later during Loan-handling
updateAgentState (\s -> s { sugAgNetIncome = harvestAmount - metabAmount
, sugAgTrades = []}) -- reset trades of the current Tick
-- compute polution and diffusion
agentPolute harvestAmount metabAmount
-- NOTE: ordering is important to replicate the dynamics
-- after having aged, moved and applied metabolism, the
-- agent could have died already, thus not able to apply other rules
ifThenElseM
(starvedToDeath `orM` dieOfAge)
(do
agentDies agentMsf
return Nothing)
(agentMating agentMsf agentContAfterMating)
agentContAfterMating :: RandomGen g => AgentLocalMonad g (Maybe (EventHandler g))
agentContAfterMating = do
agentCultureProcess
agentTrade cont
where
cont = agentContAfterTrading
agentContAfterTrading :: RandomGen g => AgentLocalMonad g (Maybe (EventHandler g))
agentContAfterTrading = agentLoan agentContAfterLoan
agentContAfterLoan :: RandomGen g => AgentLocalMonad g (Maybe (EventHandler g))
agentContAfterLoan = agentDisease cont
where
cont = defaultCont
defaultCont :: RandomGen g => AgentLocalMonad g (Maybe (EventHandler g))
defaultCont = return $ Just generalEventHandler | thalerjonathan/phd | thesis/code/sugarscape/src/SugarScape/Agent/Agent.hs | gpl-3.0 | 5,211 | 2 | 17 | 1,304 | 1,325 | 695 | 630 | 101 | 13 |
-- yammat - Yet Another MateMAT
-- Copyright (C) 2015 Amedeo Molnár
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU Affero General Public License as published
-- by the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU Affero General Public License for more details.
--
-- You should have received a copy of the GNU Affero General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
module Handler.Statistics where
import Import
import Handler.Common
import Data.List hiding (length)
import Data.Maybe (fromMaybe)
import Data.Time.Calendar (addDays)
getStatisticsR :: Handler RepJson
getStatisticsR = do
today <- liftIO $ utctDay <$> getCurrentTime
users <- runDB $ selectList [] [Asc UserId]
positiveBalance <- return $ foldl (\acc (Entity _ u) -> if userBalance u >= 0
then acc + (fromIntegral $ userBalance u) / 100
else acc
) 0 users
negativeBalance <- return $ foldl (\acc (Entity _ u) -> if userBalance u < 0
then acc + (fromIntegral $ userBalance u) / 100
else acc
) 0 users
aUsers <- runDB $ selectList [UserTimestamp >=. addDays (-30) today] [Asc UserId]
aPositiveBalance <- return $ foldl (\acc (Entity _ u) -> if userBalance u >= 0
then acc + (fromIntegral $ userBalance u) / 100
else acc
) 0 aUsers
aNegativeBalance <- return $ foldl (\acc (Entity _ u) -> if userBalance u < 0
then acc + (fromIntegral $ userBalance u) / 100
else acc
) 0 aUsers
dUsers <- runDB $ selectList [UserTimestamp <. addDays (-30) today] [Asc UserId]
dPositiveBalance <- return $ foldl (\acc (Entity _ u) -> if userBalance u >= 0
then acc + (fromIntegral $ userBalance u) / 100
else acc
) 0 dUsers
dNegativeBalance <- return $ foldl (\acc (Entity _ u) -> if userBalance u < 0
then acc + (fromIntegral $ userBalance u) / 100
else acc
) 0 dUsers
totalBalance <- (/100) . fromIntegral <$> getCashierBalance
goodUsers <- runDB $ selectList [UserBalance >=. 0] []
noobAngels <- runDB $ selectList [UserBalance >=. 0, UserBalance <=. 1000] []
noobDevils <- runDB $ selectList [UserBalance <=. 0, UserBalance >=. -1000] []
archangels <- runDB $ selectList [UserBalance >. 5000] []
archdevils <- runDB $ selectList [UserBalance <. -5000] []
bevs <- runDB $ selectList [] [Asc BeverageId]
-- let totalLossPrime = foldl (\acc (Entity _ bev) -> let primePrice = (fromIntegral $ fromMaybe 0 (beveragePricePerCrate bev)) / (fromIntegral $ fromMaybe 1 (beveragePerCrate bev)) in acc + (((fromIntegral $ abs $ beverageCorrectedAmount bev) * primePrice) / 100)) 0 bevs
totalLossRetail <- return $ foldl (\acc (Entity _ bev) ->
acc + ((fromIntegral $ abs $ beverageCorrectedAmount bev) * (fromIntegral $ beveragePrice bev) / 100)
) 0 bevs
return $ repJson $ toJSON $ Statistics
(length users)
(length aUsers)
(length dUsers)
positiveBalance
negativeBalance
totalBalance
(length goodUsers)
(length users - length goodUsers)
(length noobAngels)
(length noobDevils)
(length archangels)
(length archdevils)
aPositiveBalance
aNegativeBalance
dPositiveBalance
dNegativeBalance
-- totalLossPrime
totalLossRetail
data Statistics = Statistics
{ totalUsers :: Int
, activeUsers :: Int
, deadUsers :: Int
, positiveBalance :: Double
, negativeBalance :: Double
, totalBalance :: Double
, goodUsers :: Int
, evilUsers :: Int
, noobAngels :: Int
, noobDevils :: Int
, archangels :: Int
, archdevils :: Int
, activeUsersPositiveBalance :: Double
, activeUsersNegativeBalance :: Double
, deadUsersPositiveBalance :: Double
, deadUsersNegativeBalance :: Double
-- , totalLossPrime :: Double
, totalLossRetail :: Double
}
instance ToJSON Statistics where
toJSON (Statistics tu au du pb nb tb gu eu na nd aa ad aupb aunb dupb dunb tlr) =
object
[ "total_users" .= tu
, "active_users" .= au
, "inactive_users" .= du
, "positive_balance" .= pb
, "negative_balance" .= nb
, "total_balance" .= tb
, "good_users" .= gu
, "evil_users" .= eu
, "noob_angels" .= na
, "noob_devils" .= nd
, "archangels" .= aa
, "archdevils" .= ad
, "active_users_positive_balance" .= aupb
, "active_users_negative_balance" .= aunb
, "inactive_users_positive_balance" .= dupb
, "inactive_users_negative_balance" .= dunb
-- , "total_loss_prime_price" .= tlp
, "total_loss_retail_price" .= tlr
]
| nek0/yammat | Handler/Statistics.hs | agpl-3.0 | 4,842 | 0 | 18 | 1,083 | 1,268 | 673 | 595 | 102 | 7 |
-- this file is used by the cabal tool
-- to install this package use the command: cabal install
import Distribution.Simple
main = defaultMain
| wouwouwou/2017_module_8 | src/haskell/PP-project-2017/lib/sprockell-2017/Setup.hs | apache-2.0 | 143 | 0 | 4 | 24 | 13 | 8 | 5 | 2 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE NoImplicitPrelude #-}
module Test.Foundation.Parser
( testParsers
) where
import Foundation
import Foundation.Parser
import qualified Foundation.Parser as P
import Test.Tasty
import Test.Tasty.HUnit
data TestCaseRes a
= TestCaseOk String a
| TestCaseMore String (TestCaseRes a)
| TestCaseFail
deriving (Show)
parseTestCase :: (Show a, Eq a)
=> String
-> Parser String a
-> TestCaseRes a
-> Assertion
parseTestCase buff parser = check (parse parser buff)
check :: (Show a, Eq a) => Result String a -> TestCaseRes a -> Assertion
check r e = case (r, e) of
(ParseOk remain a, TestCaseOk eRemain ea) -> do
assertEqual "remaining buffer" eRemain remain
assertEqual "returned value" ea a
(ParseMore fr, TestCaseMore mb res') -> check (fr mb) res'
(ParseFailed _, TestCaseFail) -> return ()
_ -> assertFailure $ toList $
"parseTestCase failed: "
<> "expected: " <> show e <> " "
<> "buf received: " <> show r
-- Some custom test cases
parseTestCases :: TestTree
parseTestCases = testGroup "units"
[ testGroup "element"
[ testCase "Ok" $ parseTestCase "a" (element 'a') (TestCaseOk "" ())
, testCase "Fail" $ parseTestCase "b" (element 'a') TestCaseFail
, testCase "MoreOk" $ parseTestCase "a" (element 'a' >> element 'a') (TestCaseMore "a" (TestCaseOk "" ()))
, testCase "MoreFail" $ parseTestCase "a" (element 'a' >> element 'a') (TestCaseMore mempty TestCaseFail)
]
, testGroup "elements"
[ testCase "Ok" $ parseTestCase "abc" (elements "ab") (TestCaseOk "c" ())
, testCase "Fail" $ parseTestCase "ac" (elements "ab") TestCaseFail
, testCase "MoreOk" $ parseTestCase "a" (elements "abc") (TestCaseMore "bc" (TestCaseOk "" ()))
, testCase "MoreMoreOk" $ parseTestCase "a" (elements "abc") (TestCaseMore "b" $ TestCaseMore "c" (TestCaseOk "" ()))
, testCase "MoreMoreFail" $ parseTestCase "a" (elements "abc") (TestCaseMore "b" $ TestCaseMore mempty TestCaseFail)
]
, testGroup "anyElement"
[ testCase "OK" $ parseTestCase "a" anyElement (TestCaseOk "" 'a')
, testCase "OkRemains" $ parseTestCase "abc" anyElement (TestCaseOk "bc" 'a')
, testCase "MoreOk" $ parseTestCase "a" (anyElement *> anyElement) $ TestCaseMore "abc" (TestCaseOk "bc" 'a')
, testCase "MoreFail" $ parseTestCase "a" (anyElement <* anyElement) $ TestCaseMore mempty TestCaseFail
]
, testGroup "take"
[ testCase "OK" $ parseTestCase "a" (P.take 1) (TestCaseOk "" "a")
, testCase "OkRemains" $ parseTestCase "abc" (P.take 2) (TestCaseOk "c" "ab")
, testCase "MoreOk" $ parseTestCase "a" (P.take 2) $ TestCaseMore "bc" (TestCaseOk "c" "ab")
, testCase "MoreFail" $ parseTestCase "a" (P.take 2) $ TestCaseMore mempty TestCaseFail
]
, testGroup "takeWhile"
[ testCase "OK" $ parseTestCase "a " (P.takeWhile (' ' /=)) (TestCaseOk " " "a")
, testCase "OkRemains" $ parseTestCase "ab bc" (P.takeWhile (' ' /=)) (TestCaseOk " bc" "ab")
, testCase "MoreOk" $ parseTestCase "ab" (P.takeWhile (' ' /=)) $ TestCaseMore "cd " (TestCaseOk " " "abcd")
, testCase "MoreEmptyOK" $ parseTestCase "aa" (P.takeWhile (' ' /=)) $ TestCaseMore mempty (TestCaseOk "" "aa")
]
, testGroup "takeAll"
[ testCase "OK" $ parseTestCase "abc" takeAll (TestCaseMore mempty $ TestCaseOk "" "abc")
]
, testGroup "skip"
[ testCase "OK" $ parseTestCase "a" (skip 1) (TestCaseOk "" ())
, testCase "OkRemains" $ parseTestCase "abc" (skip 2) (TestCaseOk "c" ())
, testCase "MoreOk" $ parseTestCase "a" (skip 2) $ TestCaseMore "bc" (TestCaseOk "c" ())
, testCase "MoreFail" $ parseTestCase "a" (skip 2) $ TestCaseMore mempty TestCaseFail
]
, testGroup "skipWhile"
[ testCase "OK" $ parseTestCase "a " (skipWhile (' ' /=)) (TestCaseOk " " ())
, testCase "OkRemains" $ parseTestCase "ab bc" (skipWhile (' ' /=)) (TestCaseOk " bc" ())
, testCase "MoreOk" $ parseTestCase "ab" (skipWhile (' ' /=)) $ TestCaseMore "cd " (TestCaseOk " " ())
, testCase "MoreEmptyOk" $ parseTestCase "aa" (skipWhile (' ' /=)) $ TestCaseMore mempty (TestCaseOk "" ())
]
, testGroup "skipAll"
[ testCase "OK" $ parseTestCase "abc" skipAll (TestCaseMore mempty $ TestCaseOk "" ())
]
, testGroup "optional"
[ testCase "Nothing" $ parseTestCase "aaa" (optional $ elements "bbb") (TestCaseOk "aaa" Nothing)
, testCase "Just" $ parseTestCase "aaa" (optional $ elements "a") (TestCaseOk "aa" (Just ()))
]
, testGroup "many"
[ testCase "many elements" $ parseTestCase "101010\0"
(many ((element '1' >> pure True) <|> (element '0' >> pure False) ) )
(TestCaseOk "\0" [True, False, True, False, True, False])
]
, testGroup "parseOnly"
[ testCase "takeWhile" $ case parseOnly (P.takeWhile (' ' /=)) ("abc" :: [Char]) of
Right "abc" -> return ()
_ -> error "failed"
]
]
testParsers :: TestTree
testParsers = testGroup "Parsers"
[ parseTestCases
]
| vincenthz/hs-foundation | foundation/tests/Test/Foundation/Parser.hs | bsd-3-clause | 5,356 | 0 | 17 | 1,387 | 1,788 | 890 | 898 | 87 | 4 |
-- |
-- Module : Console.Options.Monad
-- License : BSD-style
-- Maintainer : Vincent Hanquez <[email protected]>
-- Stability : experimental
-- Portability : Good
--
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE Rank2Types #-}
module Console.Options.Monad
( ProgramDesc(..)
, ProgramMeta(..)
, OptionDesc
, gatherDesc
, getNextID
, getNextIndex
, modify
) where
import Control.Applicative
import Console.Options.Nid
import Console.Options.Types
import Console.Options.Utils
import System.Exit
import Foundation.Monad
import Foundation.Monad.State
-- | Ongoing State of the program description, as filled by monadic action
data ProgramDesc r = ProgramDesc
{ stMeta :: ProgramMeta
, stCT :: Command r -- the command with the return type of actions
, stNextID :: !NidGenerator -- next id for flag
, stNextIndex :: !UnnamedIndex -- next index for unnamed argument
}
-- | Program meta information
data ProgramMeta = ProgramMeta
{ programMetaName :: Maybe String -- ^ Program name (usually name of the executable)
, programMetaDescription :: Maybe String -- ^ Program long description
, programMetaVersion :: Maybe String -- ^ Program version
, programMetaHelp :: [String] -- ^ Flag that triggers Help.
}
programMetaDefault :: ProgramMeta
programMetaDefault = ProgramMeta Nothing Nothing Nothing ["-h", "--help"]
-- | Option description Monad
newtype OptionDesc r a = OptionDesc { runOptionDesc :: StateT (ProgramDesc r) Identity a }
deriving (Functor,Applicative,Monad)
instance MonadState (OptionDesc r) where
type State (OptionDesc r) = ProgramDesc r
withState f = OptionDesc $ withState f
-- | Run option description
gatherDesc :: OptionDesc r a -> ProgramDesc r
gatherDesc dsl = snd $ runIdentity $ runStateT (runOptionDesc dsl) initialProgramDesc
initialProgramDesc :: ProgramDesc r
initialProgramDesc = ProgramDesc { stMeta = programMetaDefault
, stCT = iniCommand
, stNextID = nidGenerator
, stNextIndex = 0
}
where
iniCommand :: Command r
iniCommand = Command (CommandLeaf []) "..." [] NoActionWrapped
-- | Return the next unique argument ID
getNextID :: OptionDesc r Nid
getNextID = do
(nid, nidGen) <- nidNext . stNextID <$> get
withState $ \st -> ((), st { stNextID = nidGen })
return nid
modify :: (ProgramDesc r -> ProgramDesc r) -> OptionDesc r ()
modify f = withState $ \st -> ((), f st)
-- | Return the next unique position argument ID
getNextIndex :: OptionDesc r UnnamedIndex
getNextIndex = do
idx <- stNextIndex <$> get
withState $ \st -> ((), st { stNextIndex = idx + 1 })
return idx
| NicolasDP/hs-cli | Console/Options/Monad.hs | bsd-3-clause | 2,906 | 0 | 12 | 777 | 606 | 345 | 261 | -1 | -1 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DeriveDataTypeable #-}
module Hans.Addr.Types where
import Hans.IP4.Packet (IP4,putIP4,showIP4)
import Data.Hashable (Hashable)
import Data.Serialize (Put)
import Data.Typeable (Typeable)
import GHC.Generics (Generic)
data Addr = Addr4 !IP4
deriving (Eq,Ord,Show,Generic,Typeable)
instance Hashable Addr
putAddr :: Addr -> Put
putAddr (Addr4 ip) = putIP4 ip
showAddr :: Addr -> ShowS
showAddr (Addr4 ip4) = showIP4 ip4
sameFamily :: Addr -> Addr -> Bool
sameFamily Addr4{} Addr4{} = True
| GaloisInc/HaNS | src/Hans/Addr/Types.hs | bsd-3-clause | 552 | 0 | 7 | 90 | 189 | 104 | 85 | 19 | 1 |
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances #-}
module Language.Hakaru.Linter where
import Language.Hakaru.Syntax
newtype Linter a = Linter Bool
instance (Number a) => Order Linter a where
less = apply2
equal = apply2
instance Num (Linter a) where
fromInteger x = Linter True
(+) = apply2
(-) = apply2
(*) = apply2
abs = apply1
negate = apply1
signum = apply1
instance Fractional (Linter a) where
(/) = apply2
recip = apply1
fromRational x = Linter True
instance Floating (Linter a) where
pi = Linter True
exp = apply1
sqrt = apply1
log = apply1
(**) = apply2
logBase = apply2
sin = apply1
cos = apply1
asin = apply1
acos = apply1
atan = apply1
sinh = apply1
cosh = apply1
tanh = apply1
asinh = apply1
atanh = apply1
acosh = apply1
instance Base Linter where
unit = Linter True
pair = apply2
unpair xy k = apply2 (apply1 xy) (fun2 k)
inl = apply1
inr = apply1
uneither xy kx ky = apply3 (apply1 xy) (fun1 kx) (fun1 ky)
true = Linter True
false = Linter True
if_ = apply3
nil = Linter True
cons = apply2
unlist an kn kc = apply3 an kn (fun2 kc)
unsafeProb = apply1
fromProb = apply1
fromInt = apply1
pi_ = Linter True
exp_ = apply1
erf = const1 (Linter False)
erf_ = const1 (Linter False)
log_ = apply1
sqrt_ = apply1
pow_ = apply2
infinity = Linter False
negativeInfinity = Linter False
gammaFunc = const1 (Linter False)
betaFunc = const2 (Linter False)
fix = apply1 . fun1
instance Mochastic Linter where
dirac = apply1
bind m k = apply2 m (fun1 k)
lebesgue = Linter False
counting = Linter False
superpose = applyPairs
uniform = apply2
normal = apply2
categorical = apply1
poisson = apply1
gamma = apply2
beta = apply2
instance Integrate Linter where
integrate = const3 (Linter False)
summate = const3 (Linter False)
instance Lambda Linter where
lam = fun1
app = apply2
runLinter :: Linter a -> Bool
runLinter (Linter a) = a
apply1 :: Linter a -> Linter b
apply1 (Linter a) = Linter a
apply2 :: Linter a -> Linter b -> Linter c
apply2 (Linter a) (Linter b) = Linter $ and [a,b]
apply3 :: Linter a -> Linter b -> Linter c -> Linter d
apply3 (Linter a) (Linter b) (Linter c) = Linter $ and [a,b,c]
applyPairs :: [(Linter a, Linter b)] -> Linter c
applyPairs [] = Linter True
applyPairs ((Linter a,Linter b):xs) =
apply2 (Linter $ and [a,b]) (applyPairs xs)
fun1 :: (Linter a -> Linter b) -> Linter (a -> b)
fun1 f = apply1 $ f $ Linter True
fun2 :: (Linter a -> Linter b -> Linter c) ->
Linter (a -> b -> c)
fun2 f = apply1 $ f (Linter True) (Linter True)
const1 :: a -> b -> a
const1 = const
const2 :: a -> b -> c -> a
const2 a b c = a
const3 :: a -> b -> c -> d -> a
const3 a b c d = a
| bitemyapp/hakaru | Language/Hakaru/Linter.hs | bsd-3-clause | 3,524 | 0 | 9 | 1,435 | 1,160 | 611 | 549 | 106 | 1 |
{-# LANGUAGE DeriveDataTypeable, TypeFamilies, TemplateHaskell,
FlexibleInstances, FlexibleContexts, MultiParamTypeClasses,
TypeOperators, TypeSynonymInstances #-}
module Distribution.Server.Packages.State where
import Distribution.Server.Framework.Instances ()
import Distribution.Server.Users.State ()
import Distribution.Package
import Distribution.Server.Packages.PackageIndex (PackageIndex)
import qualified Distribution.Server.Packages.PackageIndex as PackageIndex
import Distribution.Server.Packages.Types (PkgInfo(..), CandPkgInfo(..), pkgUploadUser, pkgUploadTime)
import qualified Distribution.Server.Users.Group as Group
import Distribution.Server.Users.Group (UserList)
import Distribution.Server.Users.Types (UserId)
import Distribution.Server.Framework.BlobStorage (BlobId)
import Data.TarIndex (TarIndex)
import qualified Data.Serialize as Serialize
import Data.Acid (Query, Update, makeAcidic)
import Data.SafeCopy (SafeCopy(..), base, contain, deriveSafeCopy, safeGet, safePut)
import Data.Typeable
import Control.Monad.Reader
import qualified Control.Monad.State as State
import Data.Monoid
import Data.Maybe (fromMaybe)
import Data.Time (UTCTime)
import Data.List (sortBy)
import Data.Ord (comparing)
import qualified Data.Map as Map
---------------------------------- State for PackageIndex
instance (Package pkg, SafeCopy pkg) => SafeCopy (PackageIndex pkg) where
putCopy index = contain $ do
safePut $ PackageIndex.allPackages index
getCopy = contain $ do
packages <- safeGet
return $ PackageIndex.fromList packages
---------------------------------- Index of metadata and tarballs
data PackagesState = PackagesState {
packageList :: !(PackageIndex PkgInfo)
}
deriving (Eq, Typeable, Show)
$(deriveSafeCopy 0 'base ''PackagesState)
initialPackagesState :: PackagesState
initialPackagesState = PackagesState {
packageList = mempty
}
instance SafeCopy PkgInfo where
putCopy = contain . Serialize.put
getCopy = contain Serialize.get
insertPkgIfAbsent :: PkgInfo -> Update PackagesState Bool
insertPkgIfAbsent pkg = do
pkgsState <- State.get
case PackageIndex.lookupPackageId (packageList pkgsState) (packageId pkg) of
Nothing -> do State.put $ pkgsState { packageList = PackageIndex.insert pkg (packageList pkgsState) }
return True
Just{} -> do return False
-- could also return something to indicate existence
mergePkg :: PkgInfo -> Update PackagesState ()
mergePkg pkg = State.modify $ \pkgsState -> pkgsState { packageList = PackageIndex.insertWith mergeFunc pkg (packageList pkgsState) }
where
mergeFunc newPkg oldPkg = oldPkg {
pkgDesc = pkgDesc newPkg,
pkgData = pkgData newPkg,
pkgTarball = sortByDate $ pkgTarball newPkg ++ pkgTarball oldPkg,
-- the old package data paired with when and by whom it was replaced
pkgDataOld = sortByDate $ (pkgData oldPkg, pkgUploadData newPkg):(pkgDataOld oldPkg ++ pkgDataOld newPkg)
}
sortByDate :: Ord a => [(a1, (a, b))] -> [(a1, (a, b))]
sortByDate xs = sortBy (comparing (fst . snd)) xs
deletePackageVersion :: PackageId -> Update PackagesState ()
deletePackageVersion pkg = State.modify $ \pkgsState -> pkgsState { packageList = deleteVersion (packageList pkgsState) }
where deleteVersion = PackageIndex.deletePackageId pkg
replacePackageUploader :: PackageId -> UserId -> Update PackagesState (Maybe String)
replacePackageUploader pkg uid = modifyPkgInfo pkg $ \pkgInfo -> pkgInfo { pkgUploadData = (pkgUploadTime pkgInfo, uid) }
replacePackageUploadTime :: PackageId -> UTCTime -> Update PackagesState (Maybe String)
replacePackageUploadTime pkg time = modifyPkgInfo pkg $ \pkgInfo -> pkgInfo { pkgUploadData = (time, pkgUploadUser pkgInfo) }
modifyPkgInfo :: PackageId -> (PkgInfo -> PkgInfo) -> Update PackagesState (Maybe String)
modifyPkgInfo pkg f = do
pkgsState <- State.get
case PackageIndex.lookupPackageId (packageList pkgsState) pkg of
Nothing -> return (Just "No such package")
Just pkgInfo -> do
State.put $ pkgsState { packageList = PackageIndex.insert (f pkgInfo) (packageList pkgsState) }
return Nothing
-- |Replace all existing packages and reports
replacePackagesState :: PackagesState -> Update PackagesState ()
replacePackagesState = State.put
getPackagesState :: Query PackagesState PackagesState
getPackagesState = ask
-- TODO: add more querying functions; there are too many
-- `fmap packageList $ query GetPackagesState' throughout code
$(makeAcidic ''PackagesState ['getPackagesState
,'replacePackagesState
,'replacePackageUploadTime
,'replacePackageUploader
,'insertPkgIfAbsent
,'mergePkg
,'deletePackageVersion
])
---------------------------------- Index of candidate tarballs and metadata
-- boilerplate code based on PackagesState
data CandidatePackages = CandidatePackages {
candidateList :: !(PackageIndex.PackageIndex CandPkgInfo)
} deriving (Typeable, Show)
$(deriveSafeCopy 0 'base ''CandidatePackages)
initialCandidatePackages :: CandidatePackages
initialCandidatePackages = CandidatePackages {
candidateList = mempty
}
$(deriveSafeCopy 0 'base ''CandPkgInfo)
replaceCandidate :: CandPkgInfo -> Update CandidatePackages ()
replaceCandidate pkg = State.modify $ \candidates -> candidates { candidateList = replaceVersions (candidateList candidates) }
where replaceVersions = PackageIndex.insert pkg . PackageIndex.deletePackageName (packageName pkg)
addCandidate :: CandPkgInfo -> Update CandidatePackages ()
addCandidate pkg = State.modify $ \candidates -> candidates { candidateList = addVersion (candidateList candidates) }
where addVersion = PackageIndex.insert pkg
deleteCandidate :: PackageId -> Update CandidatePackages ()
deleteCandidate pkg = State.modify $ \candidates -> candidates { candidateList = deleteVersion (candidateList candidates) }
where deleteVersion = PackageIndex.deletePackageId pkg
deleteCandidates :: PackageName -> Update CandidatePackages ()
deleteCandidates pkg = State.modify $ \candidates -> candidates { candidateList = deleteVersions (candidateList candidates) }
where deleteVersions = PackageIndex.deletePackageName pkg
-- |Replace all existing packages and reports
replaceCandidatePackages :: CandidatePackages -> Update CandidatePackages ()
replaceCandidatePackages = State.put
getCandidatePackages :: Query CandidatePackages CandidatePackages
getCandidatePackages = ask
$(makeAcidic ''CandidatePackages ['getCandidatePackages
,'replaceCandidatePackages
,'replaceCandidate
,'addCandidate
,'deleteCandidate
,'deleteCandidates
])
---------------------------------- Documentation
data Documentation = Documentation {
documentation :: Map.Map PackageIdentifier (BlobId, TarIndex)
} deriving (Typeable, Show)
initialDocumentation :: Documentation
initialDocumentation = Documentation Map.empty
instance SafeCopy Documentation where
putCopy (Documentation m) = contain $ safePut m
getCopy = contain $ liftM Documentation safeGet
instance SafeCopy BlobId where
putCopy = contain . Serialize.put
getCopy = contain Serialize.get
lookupDocumentation :: PackageIdentifier -> Query Documentation (Maybe (BlobId, TarIndex))
lookupDocumentation pkgId
= do m <- asks documentation
return $ Map.lookup pkgId m
hasDocumentation :: PackageIdentifier -> Query Documentation Bool
hasDocumentation pkgId
= lookupDocumentation pkgId >>= \x -> case x of
Just{} -> return True
_ -> return False
insertDocumentation :: PackageIdentifier -> BlobId -> TarIndex -> Update Documentation ()
insertDocumentation pkgId blob index
= State.modify $ \doc -> doc {documentation = Map.insert pkgId (blob, index) (documentation doc)}
getDocumentation :: Query Documentation Documentation
getDocumentation = ask
-- |Replace all existing documentation
replaceDocumentation :: Documentation -> Update Documentation ()
replaceDocumentation = State.put
$(makeAcidic ''Documentation ['insertDocumentation
,'lookupDocumentation
,'hasDocumentation
,'getDocumentation
,'replaceDocumentation
])
-------------------------------- Maintainer list
data PackageMaintainers = PackageMaintainers {
maintainers :: Map.Map PackageName UserList
} deriving (Eq, Show, Typeable)
$(deriveSafeCopy 0 'base ''PackageMaintainers)
initialPackageMaintainers :: PackageMaintainers
initialPackageMaintainers = PackageMaintainers Map.empty
getPackageMaintainers :: PackageName -> Query PackageMaintainers UserList
getPackageMaintainers name = asks $ fromMaybe Group.empty . Map.lookup name . maintainers
modifyPackageMaintainers :: PackageName -> (UserList -> UserList) -> Update PackageMaintainers ()
modifyPackageMaintainers name func = State.modify (\pm -> pm {maintainers = alterFunc (maintainers pm) })
where alterFunc = Map.alter (Just . func . fromMaybe Group.empty) name
addPackageMaintainer :: PackageName -> UserId -> Update PackageMaintainers ()
addPackageMaintainer name uid = modifyPackageMaintainers name (Group.add uid)
removePackageMaintainer :: PackageName -> UserId -> Update PackageMaintainers ()
removePackageMaintainer name uid = modifyPackageMaintainers name (Group.remove uid)
setPackageMaintainers :: PackageName -> UserList -> Update PackageMaintainers ()
setPackageMaintainers name ulist = modifyPackageMaintainers name (const ulist)
allPackageMaintainers :: Query PackageMaintainers PackageMaintainers
allPackageMaintainers = ask
replacePackageMaintainers :: PackageMaintainers -> Update PackageMaintainers ()
replacePackageMaintainers = State.put
$(makeAcidic ''PackageMaintainers ['getPackageMaintainers
,'addPackageMaintainer
,'removePackageMaintainer
,'setPackageMaintainers
,'replacePackageMaintainers
,'allPackageMaintainers
])
-------------------------------- Trustee list
-- this could be reasonably merged into the above, as a PackageGroups data structure
data HackageTrustees = HackageTrustees {
trusteeList :: UserList
} deriving (Show, Typeable)
$(deriveSafeCopy 0 'base ''HackageTrustees)
initialHackageTrustees :: HackageTrustees
initialHackageTrustees = HackageTrustees Group.empty
getHackageTrustees :: Query HackageTrustees UserList
getHackageTrustees = asks trusteeList
modifyHackageTrustees :: (UserList -> UserList) -> Update HackageTrustees ()
modifyHackageTrustees func = State.modify (\ht -> ht {trusteeList = func (trusteeList ht) })
addHackageTrustee :: UserId -> Update HackageTrustees ()
addHackageTrustee uid = modifyHackageTrustees (Group.add uid)
removeHackageTrustee :: UserId -> Update HackageTrustees ()
removeHackageTrustee uid = modifyHackageTrustees (Group.remove uid)
replaceHackageTrustees :: UserList -> Update HackageTrustees ()
replaceHackageTrustees ulist = modifyHackageTrustees (const ulist)
$(makeAcidic ''HackageTrustees ['getHackageTrustees
,'addHackageTrustee
,'removeHackageTrustee
,'replaceHackageTrustees
])
| isomorphism/hackage2 | Distribution/Server/Packages/State.hs | bsd-3-clause | 11,800 | 0 | 17 | 2,391 | 2,715 | 1,457 | 1,258 | 198 | 2 |
{-# LANGUAGE GADTs,RebindableSyntax,CPP,FlexibleContexts,FlexibleInstances,ConstraintKinds #-}
{-# OPTIONS_GHC -dcore-lint #-}
{-
- This test suite demonstrates that the special functions `log1p`, `expm1`, and `hypot` all work.
-}
module Main
where
import SubHask
-- import Prelude as P
--
-- fromRational = P.fromRational
--
-- (<) :: Ord a => a -> a -> Bool
-- (<) = (P.<)
--------------------------------------------------------------------------------
-- test1 :: Floating a => a -> a -> a
test1 :: Double -> Double -> Double
test1 a b = sqrt (a*a + b*b)
test2 :: Double -> Double
test2 a = log (1 + a)
test3 :: Double -> Double
test3 a = exp a - 1
--------------------------------------------------------------------------------
main = return ()
| mikeizbicki/HerbiePlugin | test/SpecialFunctions.hs | bsd-3-clause | 765 | 0 | 9 | 126 | 121 | 69 | 52 | 11 | 1 |
{-# LANGUAGE BangPatterns,OverloadedStrings, FlexibleContexts #-}
module TclLib.StringCmds (stringCmds,
stringInits,
stringTests) where
import Common
import Control.Monad (liftM)
import Util
import Match (match, matchTests)
import qualified System.IO.Error as IOE
import qualified Data.ByteString.Char8 as B
import qualified TclObj as T
import Data.Char (toLower,toUpper,isSpace)
import Data.Maybe (listToMaybe)
import TclLib.LibUtil
import Text.Regex.Posix
import ArgParse
import Test.HUnit
stringInits = [registerEnsem "string" cmdString]
stringCmds = makeCmdList [
("regexp", cmdRegexp),
("append", cmdAppend), ("split", cmdSplit)
]
cmdString = mkEnsemble "string" [
("trimleft", string_trimleft),
("trimright", string_trimright),
("trim", string_trim),
("first", string_first),
("map", string_map),
("tolower", string_op "tolower" (B.map toLower)),
("toupper", string_op "toupper" (B.map toUpper)),
("reverse", string_reverse),
("length", string_length), ("range", string_range),
("match", string_match), ("compare", string_compare),
("equal", string_equal), ("index", string_index)
]
string_trimleft = trimcmd "trimleft" trimleft
string_trimright = trimcmd "trimright" trimright
string_trim = trimcmd "trim" trim
trimleft pred = B.dropWhile pred
trimright pred = fst . B.spanEnd pred
trim pred = trimright pred . trimleft pred
trimcmd name f args = case args of
[s] -> go isSpace s
[s,cs] -> go (elemOf cs) s
_ -> vArgErr . pack $ "string " ++ name ++ " ?chars?"
where go pred = treturn . f pred . T.asBStr
elemOf s = let bstr = T.asBStr s in (`B.elem` bstr)
string_reverse args = case args of
[s] -> treturn $! (B.reverse (T.asBStr s))
_ -> vArgErr "string reverse string"
string_op :: String -> (BString -> BString) -> [T.TclObj] -> TclM T.TclObj
string_op name op args = case args of
[s] -> treturn . op . T.asBStr $ s
[s,i1] -> do
let bs = T.asBStr s
ind1 <- toIndex (B.length bs) i1
do_op bs ind1 1
[s,i1,i2] -> do
let bs = T.asBStr s
[ind1,ind2] <- mapM (toIndex (B.length bs)) [i1,i2]
let oplen = 1 + ind2 - ind1
do_op bs ind1 oplen
_ -> vArgErr . pack $ "string " ++ name ++ " string ?first? ?last?"
where do_op str ind oplen = do
let (pre,rest) = B.splitAt ind str
let (mid,end) = B.splitAt oplen rest
treturn . B.concat $ [pre, op mid, end]
string_length args = case args of
[s] -> return . T.fromInt . B.length . T.asBStr $ s
_ -> vArgErr "string length string"
data CompSpec = CompSpec { csNoCase :: Bool, csLen :: Maybe T.TclObj }
compSpecs = mkArgSpecs 2 [
NoArg "nocase" (\cs -> cs { csNoCase = True }),
OneArg "length" (\i cs -> cs { csLen = Just i })
]
specCompare (CompSpec nocase len) s1 s2 = do
let modder1 = if nocase then downCase else id
modder2 <- lengthMod
let modder = modder1 . modder2 . T.asBStr
return (compare (modder s1) (modder s2))
where lengthMod = case len of
Nothing -> return id
Just o -> do
i <- T.asInt o
if i < 0 then return id
else return (B.take i)
string_compare args_ = do
(cspec, args) <- parseArgs compSpecs (CompSpec False Nothing) args_
case args of
[s1,s2] -> liftM ord2int (specCompare cspec s1 s2)
_ -> vArgErr "string compare ?-nocase? ?-length int? string1 string2"
where ord2int o = case o of
EQ -> T.fromInt 0
LT -> T.fromInt (-1)
GT -> T.fromInt 1
string_equal args_ = do
(cspec, args) <- parseArgs compSpecs (CompSpec False Nothing) args_
case args of
[s1,s2] -> specCompare cspec s1 s2 >>= return . T.fromBool . (== EQ)
_ -> vArgErr "string equal ?-nocase? ?-length int? string1 string2"
noCaseSpec = boolFlagSpec "nocase" 2
string_match args_ = do
(nocase,args) <- parseArgs noCaseSpec False args_
case args of
[s1,s2] -> domatch nocase (T.asBStr s1) (T.asBStr s2)
_ -> vArgErr "string match ?-nocase? pattern string"
where domatch nocase a b = return (T.fromBool (Match.match nocase a b))
string_index args = case args of
[s,i] -> do let str = T.asBStr s
let slen = B.length str
ind <- toIndex slen i
if ind >= slen || ind < 0
then ret
else treturn $ B.take 1 (B.drop ind str)
_ -> vArgErr "string index string charIndex"
string_map args_ = do
(nocase,args) <- parseArgs noCaseSpec False args_
case args of
[tcm,s] -> do
cm <- T.asList tcm >>= toPairs . map T.asBStr
return . T.fromBStr . mapReplace nocase cm . T.asBStr $ s
_ -> vArgErr "string map ?-nocase? charMap string"
-- TODO: This is inefficiently implemented, but can be easily improved.
mapReplace nocase ml = go
where firstMatch str = let ncstr = downcase str
in listToMaybe [(k,v) | (k,v) <- ncml, k `B.isPrefixOf` ncstr]
downcase = B.map toLower
ncml = if nocase then mapFst downcase ml else ml
go s = case firstMatch s of
Nothing -> case B.uncons s of
Nothing -> s
Just (c,r) -> B.cons c (go r)
Just (k,v) -> let rest = B.drop (B.length k) s
in B.append v (go rest)
string_first args = case args of
[s1,s2] -> let (bs1,bs2) = (T.asBStr s1, T.asBStr s2)
in go bs1 bs2 0
[s1,s2,ind] -> do
let (bs1,bs2) = (T.asBStr s1, T.asBStr s2)
index <- toIndex (B.length bs2) ind
go bs1 bs2 index
_ -> vArgErr "string first needleString haystackString ?startIndex?"
where go s1 s2 off = return . T.fromInt $
case findSubstring s1 (B.drop off s2) of
Nothing -> -1
Just i -> off + i
-- Copied from BS docs, since findSubstring is deprecated.
findSubstring :: B.ByteString -> B.ByteString -> Maybe Int
findSubstring s l
| B.null s = Just 0
| otherwise = case B.breakSubstring s l of
(x,y) | B.null y -> Nothing
| otherwise -> Just (B.length x)
string_range args = case args of
[s,i1,i2] -> do
let str = T.asBStr s
let slen = B.length str
ind1 <- toIndex slen i1
ind2 <- toIndex slen i2
treturn $ B.drop ind1 (B.take (ind2+1) str)
_ -> vArgErr "string range string first last"
cmdAppend args = case args of
(v:vx) -> do val <- varGetNS (T.asVarName v) `ifFails` T.empty
let cated = oconcat (val:vx)
varSetNS (T.asVarName v) cated
_ -> vArgErr "append varName ?value value ...?"
where oconcat = T.fromBStr . B.concat . map T.asBStr
cmdSplit args = case args of
[str] -> dosplit (T.asBStr str) "\t\n "
[str,chars] -> let splitChars = T.asBStr chars
bstr = T.asBStr str
in case B.length splitChars of
0 -> lreturn $ map B.singleton (B.unpack bstr)
1 -> lreturn $! B.split (B.head splitChars) bstr
_ -> dosplit bstr splitChars
_ -> vArgErr "split string ?splitChars?"
where dosplit str chars = lreturn (B.splitWith (`B.elem` chars) str)
cmdRegexp :: [T.TclObj] -> TclM T.TclObj
cmdRegexp args = case args of
[pat,str] -> liftM T.fromBool (wrapRE (T.asBStr str =~ T.asBStr pat))
[pat,str,matchVar] -> do m <- wrapRE (T.asBStr str =~~ T.asBStr pat)
case m of
[] -> return (T.fromBool False)
(mv:_) -> do
varSetNS (T.asVarName matchVar) (T.fromBStr mv)
return (T.fromBool True)
_ -> vArgErr "regexp exp string ?matchVar?"
where wrapRE f = do r <- io $ IOE.try (return $! f)
case r of
Left _ -> fail "invalid regex"
Right v -> return $! v
stringTests = TestList [ matchTests, toIndTests, mapReplaceTests ]
mapReplaceTests = TestList [
([("a","1"),("b","2")], "aabbca", False) `should_be` "1122c1"
,([("a","1"),("b","2")], "bca", False) `should_be` "2c1"
,([("a","1"),("b","2")], "BCA", True) `should_be` "2C1"
,([("A","1"),("B","2")], "bca", True) `should_be` "2c1"
] where should_be (ml,s,nocase) b = b ~=? mapReplace nocase ml s
toIndTests = TestList [
(someLen, "10") `should_be` 10
,(someLen, "end") `should_be` lastInd
,(someLen, "e") `should_be` lastInd
,(someLen, "en") `should_be` lastInd
,(someLen, "end-1") `should_be` (lastInd - 1)
,(someLen, "e-4") `should_fail` ()
,(someLen, "") `should_fail` ()
] where should_be p b = show p ~: go p ~=? (Right b)
should_fail p@(_,s) _ = show p ~: Left ("bad index: " ++ show s) ~=? go p
go (l,i) = (toIndex l (T.fromStr i)) :: Either String Int
someLen = 5
lastInd = someLen - 1
| muspellsson/hiccup | TclLib/StringCmds.hs | lgpl-2.1 | 9,345 | 0 | 18 | 2,974 | 3,469 | 1,802 | 1,667 | 206 | 5 |
module TestDoElim where
main = do putStrLn "Hello World"
let hello = "Hello"
world <- return "World"
do let again = "Again"
putStrLn (hello++" "++world++" "++again)
| forste/haReFork | StrategyLib-4.0-beta/examples/haskell/TestDoElim.hs | bsd-3-clause | 193 | 3 | 13 | 54 | 71 | 34 | 37 | 6 | 1 |
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE CPP #-}
module Test.Haddock.Config
( TestPackage(..), CheckConfig(..), DirConfig(..), Config(..)
, defaultDirConfig
, cfgSrcDir, cfgRefDir, cfgOutDir, cfgResDir
, parseArgs, checkOpt, loadConfig
) where
import Control.Applicative
import Control.Monad
import qualified Data.List as List
import Data.Maybe
import Distribution.InstalledPackageInfo
import Distribution.Package
import Distribution.Simple.Compiler hiding (Flag)
import Distribution.Simple.GHC
import Distribution.Simple.PackageIndex
import Distribution.Simple.Program
import Distribution.Simple.Utils
import Distribution.Verbosity
import System.Console.GetOpt
import System.Directory
import System.Exit
import System.Environment
import System.FilePath
import System.IO
import Test.Haddock.Process
import Test.Haddock.Utils
data TestPackage = TestPackage
{ tpkgName :: String
, tpkgFiles :: [FilePath]
}
data CheckConfig c = CheckConfig
{ ccfgRead :: String -> Maybe c
-- ^ @f contents@ parses file contents @contents@ to
-- produce a thing to be compared.
, ccfgClean :: String -> c -> c
-- ^ @f fname x@ cleans @x@ to such that it can be compared
, ccfgDump :: c -> String
, ccfgEqual :: c -> c -> Bool
}
data DirConfig = DirConfig
{ dcfgSrcDir :: FilePath
, dcfgRefDir :: FilePath
, dcfgOutDir :: FilePath
, dcfgResDir :: FilePath
, dcfgCheckIgnore :: FilePath -> Bool
}
defaultDirConfig :: FilePath -> DirConfig
defaultDirConfig baseDir = DirConfig
{ dcfgSrcDir = baseDir </> "src"
, dcfgRefDir = baseDir </> "ref"
, dcfgOutDir = baseDir </> "out"
, dcfgResDir = rootDir </> "resources"
, dcfgCheckIgnore = const False
}
where
rootDir = baseDir </> ".."
data Config c = Config
{ cfgHaddockPath :: FilePath
, cfgPackages :: [TestPackage]
, cfgHaddockArgs :: [String]
, cfgHaddockStdOut :: FilePath
, cfgDiffTool :: Maybe FilePath
, cfgEnv :: Environment
, cfgAccept :: Bool
, cfgCheckConfig :: CheckConfig c
, cfgDirConfig :: DirConfig
}
cfgSrcDir, cfgRefDir, cfgOutDir, cfgResDir :: Config c -> FilePath
cfgSrcDir = dcfgSrcDir . cfgDirConfig
cfgRefDir = dcfgRefDir . cfgDirConfig
cfgOutDir = dcfgOutDir . cfgDirConfig
cfgResDir = dcfgResDir . cfgDirConfig
data Flag
= FlagHaddockPath FilePath
| FlagHaddockOptions String
| FlagHaddockStdOut FilePath
| FlagDiffTool FilePath
| FlagNoDiff
| FlagAccept
| FlagHelp
deriving Eq
flagsHaddockPath :: [Flag] -> Maybe FilePath
flagsHaddockPath flags = mlast [ path | FlagHaddockPath path <- flags ]
flagsHaddockOptions :: [Flag] -> [String]
flagsHaddockOptions flags = concat
[ words opts | FlagHaddockOptions opts <- flags ]
flagsHaddockStdOut :: [Flag] -> Maybe FilePath
flagsHaddockStdOut flags = mlast [ path | FlagHaddockStdOut path <- flags ]
flagsDiffTool :: [Flag] -> Maybe FilePath
flagsDiffTool flags = mlast [ path | FlagDiffTool path <- flags ]
options :: [OptDescr Flag]
options =
[ Option [] ["haddock-path"] (ReqArg FlagHaddockPath "FILE")
"path to Haddock executable to exectue tests with"
, Option [] ["haddock-options"] (ReqArg FlagHaddockOptions "OPTS")
"additional options to run Haddock with"
, Option [] ["haddock-stdout"] (ReqArg FlagHaddockStdOut "FILE")
"where to redirect Haddock output"
, Option [] ["diff-tool"] (ReqArg FlagDiffTool "PATH")
"diff tool to use when printing failed cases"
, Option ['a'] ["accept"] (NoArg FlagAccept)
"accept generated output"
, Option [] ["no-diff"] (NoArg FlagNoDiff)
"do not print diff for failed cases"
, Option ['h'] ["help"] (NoArg FlagHelp)
"display this help end exit"
]
parseArgs :: CheckConfig c -> DirConfig -> [String] -> IO (Config c)
parseArgs ccfg dcfg args = uncurry (loadConfig ccfg dcfg) =<< checkOpt args
checkOpt :: [String] -> IO ([Flag], [String])
checkOpt args = do
let (flags, files, errors) = getOpt Permute options args
unless (null errors) $ do
hPutStr stderr $ concat errors
exitFailure
when (FlagHelp `elem` flags) $ do
hPutStrLn stderr $ usageInfo "" options
exitSuccess
return (flags, files)
loadConfig :: CheckConfig c -> DirConfig -> [Flag] -> [String] -> IO (Config c)
loadConfig ccfg dcfg flags files = do
cfgEnv <- (:) ("haddock_datadir", dcfgResDir dcfg) <$> getEnvironment
systemHaddockPath <- List.lookup "HADDOCK_PATH" <$> getEnvironment
cfgHaddockPath <- case flagsHaddockPath flags <|> systemHaddockPath of
Just path -> pure path
Nothing -> do
hPutStrLn stderr $ "Haddock executable not specified"
exitFailure
ghcPath <- init <$> rawSystemStdout normal cfgHaddockPath
["--print-ghc-path"]
printVersions cfgEnv cfgHaddockPath
cfgPackages <- processFileArgs dcfg files
cfgHaddockArgs <- liftM concat . sequence $
[ pure ["--no-warnings"]
, pure ["--odir=" ++ dcfgOutDir dcfg]
, pure ["--optghc=-w"]
, pure $ flagsHaddockOptions flags
, baseDependencies ghcPath
]
let cfgHaddockStdOut = fromMaybe "/dev/null" (flagsHaddockStdOut flags)
cfgDiffTool <- if FlagNoDiff `elem` flags
then pure Nothing
else (<|>) <$> pure (flagsDiffTool flags) <*> defaultDiffTool
let cfgAccept = FlagAccept `elem` flags
let cfgCheckConfig = ccfg
let cfgDirConfig = dcfg
return $ Config { .. }
printVersions :: Environment -> FilePath -> IO ()
printVersions env haddockPath = do
handleHaddock <- runProcess' haddockPath $ processConfig
{ pcEnv = Just env
, pcArgs = ["--version"]
}
waitForSuccess "Failed to run `haddock --version`" handleHaddock
handleGhc <- runProcess' haddockPath $ processConfig
{ pcEnv = Just env
, pcArgs = ["--ghc-version"]
}
waitForSuccess "Failed to run `haddock --ghc-version`" handleGhc
baseDependencies :: FilePath -> IO [String]
baseDependencies ghcPath = do
-- The 'getInstalledPackages' crashes if used when "GHC_PACKAGE_PATH" is
-- set to some value. I am not sure why is that happening and what are the
-- consequences of unsetting it - but looks like it works (for now).
unsetEnv "GHC_PACKAGE_PATH"
(comp, _, cfg) <- configure normal (Just ghcPath) Nothing
defaultProgramConfiguration
#if MIN_VERSION_Cabal(1,23,0)
pkgIndex <- getInstalledPackages normal comp [GlobalPackageDB] cfg
#else
pkgIndex <- getInstalledPackages normal [GlobalPackageDB] cfg
#endif
mapM (getDependency pkgIndex) ["base", "process", "ghc-prim"]
where
getDependency pkgIndex name = case ifaces pkgIndex name of
[] -> do
hPutStrLn stderr $ "Couldn't find base test dependency: " ++ name
exitFailure
(ifArg:_) -> pure ifArg
ifaces pkgIndex name = do
pkg <- join $ snd <$> lookupPackageName pkgIndex (PackageName name)
iface <$> haddockInterfaces pkg <*> haddockHTMLs pkg
iface file html = "--read-interface=" ++ html ++ "," ++ file
defaultDiffTool :: IO (Maybe FilePath)
defaultDiffTool =
liftM listToMaybe . filterM isAvailable $ ["colordiff", "diff"]
where
isAvailable = liftM isJust . findProgramLocation silent
processFileArgs :: DirConfig -> [String] -> IO [TestPackage]
processFileArgs dcfg [] =
processFileArgs' dcfg . filter isValidEntry =<< getDirectoryContents srcDir
where
isValidEntry entry
| hasExtension entry = isSourceFile entry
| otherwise = isRealDir entry
srcDir = dcfgSrcDir dcfg
processFileArgs dcfg args = processFileArgs' dcfg args
processFileArgs' :: DirConfig -> [String] -> IO [TestPackage]
processFileArgs' dcfg args = do
(dirs, mdls) <- partitionM doesDirectoryExist' . map takeBaseName $ args
rootPkg <- pure $ TestPackage
{ tpkgName = ""
, tpkgFiles = map (srcDir </>) mdls
}
otherPkgs <- forM dirs $ \dir -> do
let srcDir' = srcDir </> dir
files <- filterM (isModule dir) =<< getDirectoryContents srcDir'
pure $ TestPackage
{ tpkgName = dir
, tpkgFiles = map (srcDir' </>) files
}
pure . filter (not . null . tpkgFiles) $ rootPkg:otherPkgs
where
doesDirectoryExist' path = doesDirectoryExist (srcDir </> path)
isModule dir file = (isSourceFile file &&) <$>
doesFileExist (srcDir </> dir </> file)
srcDir = dcfgSrcDir dcfg
isSourceFile :: FilePath -> Bool
isSourceFile file = takeExtension file `elem` [".hs", ".lhs"]
isRealDir :: FilePath -> Bool
isRealDir dir = not $ dir `elem` [".", ".."]
| Helkafen/haddock | haddock-test/src/Test/Haddock/Config.hs | bsd-2-clause | 8,758 | 0 | 16 | 2,019 | 2,326 | 1,229 | 1,097 | 196 | 3 |
{-# LANGUAGE OverloadedStrings #-}
{-| Logical Volumer information parser
This module holds the definition of the parser that extracts status
information about the logical volumes (LVs) of the system from the output of the
@lvs@ command.
-}
{-
Copyright (C) 2013 Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Ganeti.Storage.Lvm.LVParser (lvParser, lvCommand, lvParams) where
import Control.Applicative ((<*>), (*>), (<*), (<$>))
import qualified Data.Attoparsec.Text as A
import qualified Data.Attoparsec.Combinator as AC
import Data.Attoparsec.Text (Parser)
import Data.Text (unpack)
import Ganeti.Storage.Lvm.Types
-- | The separator of the fields returned by @lvs@
lvsSeparator :: Char
lvsSeparator = ';'
-- * Utility functions
-- | Our own space-skipping function, because A.skipSpace also skips
-- newline characters. It skips ZERO or more spaces, so it does not
-- fail if there are no spaces.
skipSpaces :: Parser ()
skipSpaces = A.skipWhile A.isHorizontalSpace
-- | A parser recognizing a number of bytes, represented as a number preceeded
-- by a separator and followed by the "B" character.
bytesP :: Parser Int
bytesP = A.char lvsSeparator *> A.decimal <* A.char 'B'
-- | A parser recognizing a number discarding the preceeding separator
intP :: Parser Int
intP = A.char lvsSeparator *> A.signed A.decimal
-- | A parser recognizing a string starting with and closed by a separator (both
-- are discarded)
stringP :: Parser String
stringP =
A.char lvsSeparator *> fmap unpack (A.takeWhile (`notElem`
[ lvsSeparator
, '\n']
))
-- * Parser implementation
-- | The command providing the data, in the format the parser expects
lvCommand :: String
lvCommand = "lvs"
-- | The parameters for getting the data in the format the parser expects
lvParams :: [String]
lvParams =
[ "--noheadings"
, "--units", "B"
, "--separator", ";"
, "-o", "lv_uuid,lv_name,lv_attr,lv_major,lv_minor,lv_kernel_major\
\,lv_kernel_minor,lv_size,seg_count,lv_tags,modules,vg_uuid,vg_name,segtype\
\,seg_start,seg_start_pe,seg_size,seg_tags,seg_pe_ranges,devices"
]
-- | The parser for one line of the diskstatus file.
oneLvParser :: Parser LVInfo
oneLvParser =
let uuidP = skipSpaces *> fmap unpack (A.takeWhile (/= lvsSeparator))
nameP = stringP
attrP = stringP
majorP = intP
minorP = intP
kernelMajorP = intP
kernelMinorP = intP
sizeP = bytesP
segCountP = intP
tagsP = stringP
modulesP = stringP
vgUuidP = stringP
vgNameP = stringP
segtypeP = stringP
segStartP = bytesP
segStartPeP = intP
segSizeP = bytesP
segTagsP = stringP
segPeRangesP = stringP
devicesP = stringP
in
LVInfo
<$> uuidP <*> nameP <*> attrP <*> majorP <*> minorP <*> kernelMajorP
<*> kernelMinorP <*> sizeP <*> segCountP <*> tagsP <*> modulesP
<*> vgUuidP <*> vgNameP <*> segtypeP <*> segStartP <*> segStartPeP
<*> segSizeP <*> segTagsP <*> segPeRangesP <*> devicesP
<*> return Nothing <* A.endOfLine
-- | The parser for a whole diskstatus file.
lvParser :: Parser [LVInfo]
lvParser = oneLvParser `AC.manyTill` A.endOfInput
| apyrgio/ganeti | src/Ganeti/Storage/Lvm/LVParser.hs | bsd-2-clause | 4,424 | 0 | 28 | 841 | 554 | 325 | 229 | 59 | 1 |
{-# LANGUAGE RankNTypes, NamedFieldPuns, RecordWildCards #-}
module Distribution.Server.Features.PackageContents (
PackageContentsFeature(..),
PackageContentsResource(..),
initPackageContentsFeature
) where
import Distribution.Server.Framework
import Distribution.Server.Framework.ResponseContentTypes as Resource
import Distribution.Server.Features.Core
import Distribution.Server.Features.TarIndexCache
import Distribution.Server.Packages.ChangeLog
import Distribution.Server.Packages.Readme
import Distribution.Server.Packages.Types
import Distribution.Server.Packages.Render
import Distribution.Server.Features.Users
import Distribution.Server.Util.ServeTarball
import Distribution.Server.Pages.Template (hackagePage)
import Distribution.Text
import Distribution.Package
import qualified Cheapskate as Markdown (markdown, Options(..))
import qualified Cheapskate.Html as Markdown (renderDoc)
import qualified Text.Blaze.Html.Renderer.Pretty as Blaze (renderHtml)
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.Text.Encoding.Error as T
import qualified Data.ByteString.Lazy as BS (ByteString, toStrict)
import qualified Text.XHtml.Strict as XHtml
import Text.XHtml.Strict ((<<), (!))
import System.FilePath.Posix (takeExtension)
data PackageContentsFeature = PackageContentsFeature {
packageFeatureInterface :: HackageFeature,
packageContentsResource :: PackageContentsResource,
-- necessary information for the representation of a package resource
-- This needs to be here in order to extract from the tar file
packageRender :: PkgInfo -> IO PackageRender
}
instance IsHackageFeature PackageContentsFeature where
getFeatureInterface = packageFeatureInterface
data PackageContentsResource = PackageContentsResource {
packageContents :: Resource,
packageContentsChangeLog :: Resource,
packageContentsReadme :: Resource,
packageContentsChangeLogUri :: PackageId -> String
}
initPackageContentsFeature :: ServerEnv
-> IO (CoreFeature
-> TarIndexCacheFeature
-> UserFeature
-> IO PackageContentsFeature)
initPackageContentsFeature _ = do
return $ \core tarIndexCache user -> do
let feature = packageContentsFeature core tarIndexCache user
return feature
packageContentsFeature :: CoreFeature
-> TarIndexCacheFeature
-> UserFeature
-> PackageContentsFeature
packageContentsFeature CoreFeature{ coreResource = CoreResource{
packageInPath
, lookupPackageId
}
}
TarIndexCacheFeature{packageTarball, findToplevelFile}
UserFeature{queryGetUserDb}
= PackageContentsFeature{..}
where
packageFeatureInterface = (emptyHackageFeature "package-contents") {
featureResources =
map ($ packageContentsResource) [
packageContents
, packageContentsChangeLog
, packageContentsReadme
]
, featureState = []
, featureDesc = "The PackageContents feature shows the contents of packages and caches their TarIndexes"
}
packageContentsResource = PackageContentsResource {
packageContents = (resourceAt "/package/:package/src/..") {
resourceGet = [("", serveContents)]
}
, packageContentsChangeLog = (resourceAt "/package/:package/changelog.:format") {
resourceGet = [("txt", serveChangeLogText)
,("html", serveChangeLogHtml)]
}
, packageContentsReadme = (resourceAt "/package/:package/readme.:format") {
resourceGet = [("txt", serveReadmeText)
,("html", serveReadmeHtml)]
}
, packageContentsChangeLogUri = \pkgid ->
renderResource (packageContentsChangeLog packageContentsResource) [display pkgid, display (packageName pkgid)]
}
packageRender :: PkgInfo -> IO PackageRender
packageRender pkg = do
users <- queryGetUserDb
changeLog <- findToplevelFile pkg isChangeLogFile
>>= either (\_ -> return Nothing) (return . Just)
readme <- findToplevelFile pkg isReadmeFile
>>= either (\_ -> return Nothing) (return . Just)
let render = doPackageRender users pkg
return $ render { rendChangeLog = changeLog, rendReadme = readme }
{-------------------------------------------------------------------------------
TODO: everything below is duplicated in PackageCandidates.
-------------------------------------------------------------------------------}
-- result: changelog or not-found error
serveChangeLogText :: DynamicPath -> ServerPartE Response
serveChangeLogText dpath = do
pkg <- packageInPath dpath >>= lookupPackageId
mChangeLog <- liftIO $ findToplevelFile pkg isChangeLogFile
case mChangeLog of
Left err ->
errNotFound "Changelog not found" [MText err]
Right (tarfile, etag, offset, filename) -> do
cacheControl [Public, maxAgeDays 30] etag
liftIO $ serveTarEntry tarfile offset filename
serveChangeLogHtml :: DynamicPath -> ServerPartE Response
serveChangeLogHtml dpath = do
pkg <- packageInPath dpath >>= lookupPackageId
mReadme <- liftIO $ findToplevelFile pkg isChangeLogFile
case mReadme of
Left err ->
errNotFound "Changelog not found" [MText err]
Right (tarfile, etag, offset, filename) -> do
contents <- either (\err -> errInternalError [MText err])
(return . snd)
=<< liftIO (loadTarEntry tarfile offset)
cacheControl [Public, maxAgeDays 30] etag
return $ toResponse $ Resource.XHtml $
let title = "Changelog for " ++ display (packageId pkg) in
hackagePage title
[ XHtml.h2 << title
, XHtml.thediv ! [XHtml.theclass "embedded-author-content"]
<< if supposedToBeMarkdown filename
then renderMarkdown contents
else XHtml.thediv ! [XHtml.theclass "preformatted"]
<< unpackUtf8 contents
]
serveReadmeText :: DynamicPath -> ServerPartE Response
serveReadmeText dpath = do
pkg <- packageInPath dpath >>= lookupPackageId
mReadme <- liftIO $ findToplevelFile pkg isReadmeFile
case mReadme of
Left err ->
errNotFound "Readme not found" [MText err]
Right (tarfile, etag, offset, filename) -> do
cacheControl [Public, maxAgeDays 30] etag
liftIO $ serveTarEntry tarfile offset filename
serveReadmeHtml :: DynamicPath -> ServerPartE Response
serveReadmeHtml dpath = do
pkg <- packageInPath dpath >>= lookupPackageId
mReadme <- liftIO $ findToplevelFile pkg isReadmeFile
case mReadme of
Left err ->
errNotFound "Readme not found" [MText err]
Right (tarfile, etag, offset, filename) -> do
contents <- either (\err -> errInternalError [MText err])
(return . snd)
=<< liftIO (loadTarEntry tarfile offset)
cacheControl [Public, maxAgeDays 30] etag
return $ toResponse $ Resource.XHtml $
let title = "Readme for " ++ display (packageId pkg) in
hackagePage title
[ XHtml.h2 << title
, XHtml.thediv ! [XHtml.theclass "embedded-author-content"]
<< if supposedToBeMarkdown filename
then renderMarkdown contents
else XHtml.thediv ! [XHtml.theclass "preformatted"]
<< unpackUtf8 contents
]
-- return: not-found error or tarball
serveContents :: DynamicPath -> ServerPartE Response
serveContents dpath = do
pkg <- packageInPath dpath >>= lookupPackageId
mTarball <- liftIO $ packageTarball pkg
case mTarball of
Left err ->
errNotFound "Could not serve package contents" [MText err]
Right (fp, etag, index) ->
serveTarball (display (packageId pkg) ++ " source tarball")
["index.html"] (display (packageId pkg)) fp index
[Public, maxAgeDays 30] etag
renderMarkdown :: BS.ByteString -> XHtml.Html
renderMarkdown = XHtml.primHtml . Blaze.renderHtml
. Markdown.renderDoc . Markdown.markdown opts
. T.decodeUtf8With T.lenientDecode . BS.toStrict
where
opts =
Markdown.Options
{ Markdown.sanitize = True
, Markdown.allowRawHtml = False
, Markdown.preserveHardBreaks = False
, Markdown.debug = False
}
supposedToBeMarkdown :: FilePath -> Bool
supposedToBeMarkdown fname = takeExtension fname `elem` [".md", ".markdown"]
unpackUtf8 :: BS.ByteString -> String
unpackUtf8 = T.unpack
. T.decodeUtf8With T.lenientDecode
. BS.toStrict
| ocharles/hackage-server | Distribution/Server/Features/PackageContents.hs | bsd-3-clause | 9,527 | 4 | 28 | 2,840 | 1,968 | 1,051 | 917 | 175 | 8 |
{-# LANGUAGE ParallelArrays #-}
{-# OPTIONS -fvectorise #-}
module SumNatsVect (sumNats) where
import Data.Array.Parallel.Prelude
import Data.Array.Parallel.Prelude.Int as I
import qualified Prelude as P
sumNats :: Int -> Int
sumNats maxN
= sumP [: x | x <- enumFromToP 0 (maxN I.- 1)
, (x `mod` 3 I.== 0) || (x `mod` 5 I.== 0) :]
| urbanslug/ghc | testsuite/tests/dph/sumnats/SumNatsVect.hs | bsd-3-clause | 347 | 3 | 11 | 71 | 121 | 73 | 48 | 10 | 1 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE DeriveGeneric #-}
module DB.Common where
import GHC.Generics
import Database.Persist.TH
data TransferState = Proposed | Prepared | Executed | Rejected
deriving (Show, Read, Eq, Generic)
derivePersistField "TransferState"
data TranferRejectionReason = Cancelled | Expired
deriving (Show, Read, Eq, Generic)
derivePersistField "TranferRejectionReason"
data FundType = Credit | Debit
deriving (Show, Read, Eq, Generic)
derivePersistField "FundType"
| gip/cinq-cloches-ledger | src/DB/Common.hs | mit | 502 | 0 | 6 | 68 | 130 | 71 | 59 | 14 | 0 |
findLass [] = Nothing
findLass [x] = Just x
findLass (x:xs) = findLass(xs)
findLastButOne [] = error "nothing"
findLastButOne (x:[]) = error "nothing"
findLastButOne (x:y:[]) = x
findLastButOne (x:xs) = findLastButOne xs
elemenAt [] _ = error "no element"
elemenAt (x:xs) k = if (k <= 0)
then error "no element"
else if (k == 1)
then x
else elemenAt xs (k - 1)
myLength [] = 0
myLength (x:xs) = 1 + myLength xs
myReverse [] = []
myReverse (x:xs) = (myReverse xs) ++ [x]
isPalindrome l = l == (myReverse l)
data NestedList a = Elem a | List [NestedList a]
flatten (Elem x) = [x]
flatten (List l) = concatMap flatten l
compress [] = []
compress (x:[]) = [x]
compress (x:y:xs) = if (x == y)
then compress (x:xs)
else x:(compress (y:xs))
pack l = let result = foldl f ([], []) l
where
f ([], r) y = ([y], r)
f (rest@(x:xs), r) y = if (x == y)
then (y:x:xs, r)
else ([y], r ++ [rest])
in snd result ++ [(fst result)]
encode [] = []
encode (x:xs) = let (first, rest) = span (==x) xs
in
(length first + 1, x) : (encode rest)
data Encode a = Multiple Int a | Single a deriving(Show)
encodeModified [] = []
encodeModified (x:xs) = let (first, rest) = span (==x) xs
in
if ((length first) == 0)
then (Single x): (encodeModified rest)
else (Multiple ((length first) + 1) x) : (encodeModified rest)
ins y [] = [[y]]
ins y l@(x:xs) = f [] y (x:xs)
where
f first y [] = [first ++ [y]]
f first y l@(x:xs) = (first ++ [y] ++ l) : (f (first ++ [x]) y xs)
permutation [] = [[]]
permutation l@(x:xs) = concatMap (ins x) (permutation xs)
problem1 = sum [x | x <- [1 .. 999], x `rem` 3 == 0 || x `rem` 5 == 0]
fibs = map fst $ iterate (\ (a, b) -> (b, a + b)) (0,1)
factors :: Integer -> [Integer]
factors n
| n == 1 = [1]
| otherwise = f n 2 [1]
where f n i l
| n `rem` i == 0 = f (n `div` i) i (i:l)
| (fromIntegral i) <= n = f n (i + 1) l
| otherwise = l
problem3 = head . factors
p31 = g 10 [200,100,50,20,10,5,2,1]
where
g 0 _ = [[]] -- exactly one way to get 0 sum, with no coins at all
g n [] = [] -- no way to sum up no coins to a non-zero sum
g n coins@(c:rest)
| c <= n = map (c:) (g (n-c) coins) -- with the top coin
++ g n rest
| otherwise = g n rest
ways [] = 1 : repeat 0
ways (coin:coins) = n
where n = zipWith (+) (ways coins) (replicate coin 0 ++ n)
problem_31 = ways [1,2,5,10,20,50,100,200] !! 200
dupli [] = []
dupli (x:xs) = x:x:(dupli xs)
repli [] _= []
repli (x:xs) n = take n (repeat x) ++ (repli xs n)
dropEvery l n = f l n 1
where
f [] _ _ = []
f (x:xs) n k = if (k == n)
then (f xs n 1)
else x:(f xs n (k + 1))
split l n = getResult r
where
r = foldl f ([], [], 0, n) l
where f (left, right, k, n) x
| k < n = ((x:left), right, k + 1, n)
| otherwise = (left, (x:right), k + 1, n)
getResult (x, y, _, _) = (x, y)
slice [] _ _ = []
slice (x:xs) a b
| b < 1 = []
| a > 1 = slice xs (a - 1) (b - 1)
| a <= 1 = x:(slice xs 0 (b - 1))
| b >= 1 = [x]
rotate l n = getResult r
where
index = if (n < 0)
then (length l) + n
else n
f (temp, result, k, i) x
| k <= i = (x:temp, result, (k + 1), i)
| otherwise = (temp, x:result, (k + 1), i)
r = foldl f ([], [], 1, index) l
getResult (x, y, _, _) = reverse y ++ reverse x
removeAt l n = getResult r
where
f (removed, rest, k, n) x
| k == n = (x:removed, rest, k + 1, n)
| otherwise = (removed, x:rest, k + 1, n)
r = foldl f ([], [], 1, n) l
getResult (x, y, _, _) = (reverse x, reverse y)
insertAt e l 1 = e:l
insertAt e (x:xs) n = x: insertAt e xs (n - 1)
range a b =
if (b < a)
then error "not good"
else
if (a == b)
then [a]
else a: range (a + 1) b
ins a [] = [[a]]
ins a l@(x:xs) = getResult r
where
f (left, right, result, a) x = (
left ++ [x],
tail right,
(left ++ [a] ++ right):result,
a)
r = foldl f ([], l, [], a) l
getResult (_, _, r, _) = (l ++ [a]):r
myPermute [] = [[]]
myPermute (x:xs) = concatMap (ins x) (myPermute xs)
combinations :: Int -> [a] -> [[a]]
combinations 0 _ = [[]]
combinations _ [] = []
combinations n (x:xs) = (map (x:) (combinations (n - 1) xs)) ++ (combinations n xs)
-- findRest l1 l2
-- find all elements in l2 that does not appear in l1
findRest [] l2 = l2
findRest _ [] = []
findRest (x:xs) l2 = let
rest = findRest xs l2
in
filter (\ e -> e /= x) rest
-- find all the elements in l2 that does not appear in the list of list of elements in l1
findRestAll l1 l2 = foldr f l2 l1
where
f el1 l = findRest el1 l
group [] elems = [[]]
group (x:xs) elems = let
rest = group xs elems
combinationsX elemRest= (combinations x $ findRestAll elemRest elems)
f x elemRest = map (:elemRest) (combinationsX elemRest)
in
concatMap (f x) rest
| hibou107/algocpp | euler.hs | mit | 6,105 | 0 | 15 | 2,618 | 2,991 | 1,595 | 1,396 | 141 | 3 |
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Network.Connection (
ConnOpts,
Conn,
initWS,
withOptions,
runConnection,
awaitData,
yieldData,
yieldResponse,
dispatchVoid,
dispatch,
closeConnection,
get,
log
) where
import Prelude hiding (log)
import System.Locale
import qualified System.Log.Logger as L
import Network.URI
import qualified Network.HTTP as HTTP
import qualified Network.Stream as HTTP
import qualified Network.WebSockets as WS
import Data.API
import Data.Time
import Data.Word
import Data.Aeson
import Data.Text (Text)
import Data.ByteString.Lazy (ByteString)
import Data.Monoid (mappend)
import qualified Data.Text as T
import Control.Applicative
import Control.Monad (forever)
import Control.Monad.Reader
import Control.Monad.Except
import Control.Concurrent
import Util.Common
data ConnOpts = ConnOpts { connection :: WS.Connection }
newtype Conn a = Conn { runConn :: ReaderT ConnOpts (ExceptT ConnError IO) a }
deriving (Functor, Applicative, Monad, MonadReader ConnOpts, MonadError ConnError, MonadIO)
initWS address port onConnection = do
L.updateGlobalLogger "wikit" (L.setLevel L.INFO)
ioLog L.INFO ("live @ ws://" ++ address ++ ":" ++ show port)
WS.runServer address port $ \pending -> do
connection <- WS.acceptRequest pending
WS.forkPingThread connection 30
--
-- This runs forever, and wil decode incoming requests,
-- if unsuccessful it will just return a parse error to
-- the client, otherwise it will handle the request as normal
--
runConnection (ConnOpts connection) onConnection
withOptions :: ConnOpts -> Conn a -> IO (Either ConnError a)
withOptions options conn = runExceptT (runReaderT (runConn conn) options)
runConnection :: ConnOpts -> Conn a -> IO ()
runConnection options conn = forever (withOptions options conn)
awaitData :: WS.WebSocketsData a => Conn a
awaitData = do
socketConnection <- asks connection
liftIO (WS.receiveData socketConnection)
yieldData :: WS.WebSocketsData a => a -> Conn ()
yieldData response = do
socketConnection <- asks connection
liftIO (WS.sendTextData socketConnection response)
closeConnection :: FatalError -> Conn ()
closeConnection reason = do
socketConnection <- asks connection
liftIO (WS.sendClose socketConnection (encode reason))
yieldResponse :: ToJSON a => a -> Conn ()
yieldResponse response = yieldData (encode response)
dispatchVoid :: Conn a -> Conn ()
dispatchVoid = void . dispatch
dispatch :: Conn a -> Conn ThreadId
dispatch task = ask >>= \options ->
--
-- forks a new thread and if it errors returns an
-- internal error to the client, so it knowns shit
-- went down when it didn't get what it wanted
--
liftIO . forkIO . void . withOptions options $
catchError (void task) $ \result -> do
log L.ERROR ("An error occured,\n " ++ show result)
closeConnection UnknownFatalError
{-- UTILITY --}
get :: URI -> Conn (HTTP.Response ByteString)
get url = liftIO (HTTP.simpleHTTP (HTTP.mkRequest HTTP.GET url)) >>= \case
Left error -> throwError (FailedConnection error)
Right resp -> return resp
log :: L.Priority -> String -> Conn ()
log ltype message = liftIO (ioLog ltype message)
ioLog :: L.Priority -> String -> IO ()
ioLog ltype message = do
epoch <- formatTime defaultTimeLocale "%s" <$> getCurrentTime
L.logM "wikit.socket" ltype ("[" ++ show ltype ++ " @ " ++ epoch ++ "] " ++ message)
| AKST/wikit | socket-server/src/Network/Connection.hs | mit | 3,525 | 0 | 14 | 653 | 1,025 | 532 | 493 | 84 | 2 |
{-# LANGUAGE FlexibleContexts #-}
module Network.VoiceText (
basicAuth,
ttsParams,
addFormat,
addEmotion,
addEmotionLevel,
addPitch,
addSpeed,
addVolume,
tts,
ttsToFile,
BasicAuth(..),
TtsParams(..),
Speaker(..),
Format(..),
Emotion(..),
Error(..)) where
import Control.Monad.Trans.Resource (runResourceT)
import Data.ByteString (hPut)
import Data.ByteString.Lazy (toStrict)
import Data.Maybe (catMaybes)
import Network.HTTP.Client.TLS (tlsManagerSettings)
import Network.HTTP.Conduit (applyBasicAuth, httpLbs, newManager, parseRequest, responseBody, responseStatus, urlEncodedBody)
import Network.HTTP.Types (statusCode, statusMessage)
import Network.VoiceText.Types
import System.IO (openFile, IOMode(WriteMode))
import qualified Data.ByteString.Lazy.Internal as LI
import qualified Data.ByteString.Char8 as C8
import qualified Data.ByteString.UTF8 as U8
apiURLBase :: String
apiURLBase = "https://api.voicetext.jp/"
ttsToFile :: FilePath -> BasicAuth -> TtsParams -> IO (Either Error ())
ttsToFile filePath basicAuth ttsParam = do
res <- tts basicAuth ttsParam
case res of
Left err -> return $ Left err
Right bytes -> do
fileH <- openFile filePath WriteMode
result <- hPut fileH $ toStrict bytes
return $ Right result
tts :: BasicAuth -> TtsParams -> IO (Either Error LI.ByteString)
tts basicAuth ttsParam = doRequest basicAuth "v1/tts" $ [textParam, speakerParam] ++ optionParams
where
textParam = ("text", text ttsParam)
speakerParam = ("speaker", speakerName $ speaker ttsParam)
optionParams = catMaybes [
fmap (\f -> ("format", formatName f)) $ format ttsParam,
fmap (\e -> ("emotion", emotionName e)) $ emotion ttsParam,
fmap (\el -> ("emotion_level", show el)) $ emotionLevel ttsParam,
fmap (\p -> ("pitch", show p)) $ pitch ttsParam,
fmap (\s -> ("speed", show s)) $ speed ttsParam,
fmap (\v -> ("volume", show v)) $ volume ttsParam]
doRequest :: BasicAuth -> String -> [(String, String)] -> IO (Either Error LI.ByteString)
doRequest basicAuth path params = do
req <- (parseRequest $ apiURLBase ++ path)
>>= return . applyBasicAuth user pass
>>= return . urlEncodedBody packedParams
manager <- newManager tlsManagerSettings
runResourceT $ do
res <- httpLbs req manager
return $ returnValue res
where
user = C8.pack $ username basicAuth
pass = C8.pack $ password basicAuth
packedParams = map (\(k, v) -> (C8.pack k, U8.fromString v)) params
returnValue res
| statusCode status == 200 = Right $ responseBody res
| otherwise = Left $ Error { code = statusCode status, message = C8.unpack $ statusMessage status, body = LI.unpackChars $ responseBody res}
where
status = responseStatus res
| zaneli/network-voicetext | src/Network/VoiceText.hs | mit | 2,784 | 0 | 14 | 531 | 936 | 510 | 426 | 68 | 2 |
-----------------------------------------------------------------------------
--
-- Module : Transient.Indeterminism
-- Copyright :
-- License : GPL (Just (Version {versionBranch = [3], versionTags = []}))
--
-- Maintainer : [email protected]
-- Stability :
-- Portability :
--
-- | see <https://www.fpcomplete.com/user/agocorona/beautiful-parallel-non-determinism-transient-effects-iii>
--
-----------------------------------------------------------------------------
{-# LANGUAGE BangPatterns #-}
module Transient.Indeterminism (
choose, choose', collect, collect', group, groupByTime
) where
import Transient.Base
import Transient.Backtrack(checkFinalize)
import Transient.Internals(killChildren, EventF(..),hangThread)
import Data.IORef
import Control.Applicative
import Data.Monoid
import Control.Concurrent
import Data.Typeable
import Control.Monad.State
import Control.Concurrent.STM as STM
import GHC.Conc
import Data.Time.Clock
-- | slurp a list of values and process them in parallel . To limit the number of processing
-- threads, use `threads`
choose :: Show a => [a] -> TransIO a
choose []= empty
choose xs = do
evs <- liftIO $ newIORef xs
r <- parallel $ do
es <- atomicModifyIORef' evs $ \es -> let !tes= tail es in (tes,es)
case es of
[x] -> x `seq` return $ SLast x
x:_ -> x `seq` return $ SMore x
checkFinalize r
-- | group the output of a possible multithreaded process in groups of n elements.
group :: Int -> TransIO a -> TransIO [a]
group num proc = do
v <- liftIO $ newIORef (0,[])
x <- proc
mn <- liftIO $ atomicModifyIORef' v $ \(n,xs) ->
let !n'=n +1
in if n'== num
then ((0,[]), Just xs)
else ((n', x:xs),Nothing)
case mn of
Nothing -> stop
Just xs -> return xs
-- | group result for a time interval, measured with `diffUTCTime`
groupByTime :: Integer -> TransIO a -> TransIO [a]
groupByTime time proc = do
v <- liftIO $ newIORef (0,[])
t <- liftIO getCurrentTime
x <- proc
t' <- liftIO getCurrentTime
mn <- liftIO $ atomicModifyIORef' v $ \(n,xs) -> let !n'=n +1
in
if diffUTCTime t' t < fromIntegral time
then ((n', x:xs),Nothing)
else ((0,[]), Just xs)
case mn of
Nothing -> stop
Just xs -> return xs
-- | alternative definition with more parallelism, as the composition of n `async` sentences
choose' :: [a] -> TransIO a
choose' xs = foldl (<|>) empty $ map (async . return) xs
-- collect the results of a search done in parallel, usually initiated by
-- `choose` .
--
-- execute a process and get at least the first n solutions (they could be more).
-- if the process end without finding the number of solutions requested, it return the found ones
-- if he find the number of solutions requested, it kill the non-free threads of the process and return
-- It works monitoring the solutions found and the number of active threads.
-- If the first parameter is 0, collect will return all the results
collect :: Int -> TransIO a -> TransIO [a]
collect n = collect' n 0.1 0
-- | search also between two time intervals. If the first interval has passed and there is no result,
--it stops.
-- After the second interval, it stop unconditionally and return the current results.
-- It also stops as soon as there are enough results specified in the first parameter.
collect' :: Int -> NominalDiffTime -> NominalDiffTime -> TransIO a -> TransIO [a]
collect' n t1 t2 search= hookedThreads $ do
rv <- liftIO $ atomically $ newTVar (0,[]) -- !> "NEWMVAR"
endflag <- liftIO $ newTVarIO False
st <- newPool
t <- liftIO getCurrentTime
let worker = do
r <- search
liftIO $ atomically $ do
(n1,rs) <- readTVar rv
writeTVar rv (n1+1,r:rs) -- !> "MODIFY"
stop
monitor= freeThreads $ do
xs <- async $ atomically $
do (n', xs) <- readTVar rv
ns <- readTVar $ children st
t' <- unsafeIOToSTM getCurrentTime
if
(n > 0 && n' >= n) ||
(null ns && (diffUTCTime t' t > t1)) ||
(t2 > 0 && diffUTCTime t' t > t2)
-- !> (diffUTCTime t' t, n', length ns)
then return xs else retry
liftIO . killChildren $ children st
return xs
monitor <|> worker
where
newPool = do
chs <- liftIO $ newTVarIO []
s <- get
let s'= s{children= chs}
put s'
return s'
| geraldus/transient | src/Transient/Indeterminism.hs | mit | 4,763 | 0 | 25 | 1,393 | 1,176 | 607 | 569 | 85 | 3 |
module Hydrogen.Syntax.Types where
import Hydrogen.Prelude
import Hydrogen.Parsing
type POPs a = [(SourcePos, POP a)]
data POP a where
Token :: TokenType -> [Char] -> [Char] -> POP a
Block :: BlockType -> [Char] -> POPs a -> POP a
Value :: a -> String -> POP a
deriving (Eq, Show, Typeable, Generic)
instance Serialize a => Serialize (POP a)
data TokenType where
AposString :: TokenType
QuotString :: TokenType
TickString :: TokenType
SomethingT :: TokenType
deriving (Eq, Ord, Enum, Show, Typeable, Generic)
instance Serialize TokenType
data BlockType where
Grouping :: BlockType
Brackets :: BlockType
Mustache :: BlockType
deriving (Eq, Ord, Enum, Show, Typeable, Generic)
instance Serialize BlockType
data Token where
TSpecial :: Char -> Token
TBraceOpen :: [Char] -> Char -> Token
TBraceClose :: Char -> Token
TSomething :: [Char] -> Token
TIndent :: Int -> Token
TSpaces :: Token
TString :: [Char] -> Char -> [Char] -> Token
deriving (Eq, Ord, Show, Typeable, Generic)
instance Serialize Token
| hydrogen-tools/hydrogen-syntax | src/Hydrogen/Syntax/Types.hs | mit | 1,085 | 1 | 10 | 243 | 356 | 203 | 153 | -1 | -1 |
module Render.Render where
import Data.Monoid
import qualified Data.HashSet as S
import Graphics.Gloss
import Types.GameObjs
import FRP.Yampa
import Render.ImageIO
import Control.Lens (view)
-- | 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 renderState
renderState :: GameState -> Picture
renderState s =
placeBkgd s <>
placePlayer s <>
(mconcat $ placeGameObjs s) <>
placeText s
placeGameObjs :: GameState -> [Picture]
placeGameObjs g = let
os' = view (board.objs) g :: S.HashSet GameObj
os = S.filter (_display) os'
(px,py) = mapTup fromIntegral $ view (board.player1.gameObj.position) g
myPos o = ((fromIntegral$fst$_position o),(fromIntegral$snd$_position o))
f o = translate (fst $myPos o-px) (snd $myPos o-py) $ snd $ getImg g o
in
map f (S.toList os)
-- | keep the player centered at all times
placePlayer :: GameState -> Picture
placePlayer g = let
p = snd $ getImg g $ view (board.player1) g
--(x,y) = mapTup fromIntegral ((view (board.player1.position)) g)
in
translate 0 0 p
-- | move the background around the player
placeBkgd :: GameState -> Picture
placeBkgd g = let
bkgd = snd$ getImg g $ view (board.levelName) g
(x,y) = mapTup fromIntegral $ view (board.player1.gameObj.position) g
in
translate (-x) (-y) bkgd
placeText :: GameState -> Picture
placeText g =
translate (50) (120) $ text $ show $ (10000 - (_aliveTime._player1._board) g)
mapTup :: (a -> b) -> (a, a) -> (b, b)
mapTup f (a1, a2) = (f a1, f a2)
| santolucito/Euterpea_Projects | TransGame/src/Render/Render.hs | mit | 1,616 | 0 | 15 | 320 | 592 | 307 | 285 | 38 | 1 |
{-# LANGUAGE PackageImports #-}
{-# OPTIONS_GHC -fno-warn-dodgy-exports -fno-warn-unused-imports #-}
-- | Reexports "Foreign.Marshal.Alloc.Compat"
-- from a globally unique namespace.
module Foreign.Marshal.Alloc.Compat.Repl.Batteries (
module Foreign.Marshal.Alloc.Compat
) where
import "this" Foreign.Marshal.Alloc.Compat
| haskell-compat/base-compat | base-compat-batteries/src/Foreign/Marshal/Alloc/Compat/Repl/Batteries.hs | mit | 326 | 0 | 5 | 31 | 32 | 25 | 7 | 5 | 0 |
module Common where
import Data.List
import Control.Monad
import Control.Monad.Random
import Data.Array.ST
import GHC.Arr
import Data.List.Split
slidingWindow :: Int -> [a] -> [[a]]
slidingWindow n xs = take (length xs + 1 - n) . map (take n) . tails $ xs
eps :: Double
eps = 2 ** (-32)
shuffle :: MonadRandom m => [a] -> m [a]
shuffle xs = do
let l = length xs
rands <- take l `fmap` getRandomRs (0, l-1)
let ar' = runSTArray $ do
ar <- thawSTArray $ listArray (0, l-1) xs
forM_ (zip [0..(l-1)] rands) $ \(i, j) -> do
vi <- readSTArray ar i
vj <- readSTArray ar j
writeSTArray ar j vi
writeSTArray ar i vj
return ar
return (elems ar')
applyM :: Monad m => Int -> (a -> m a) -> a -> m a
applyM 0 _ m = return m
applyM n f m = f m >>= applyM (n - 1) f
iterateList :: Int -> (a -> [a]) -> a -> [a]
iterateList 0 _ x = [x]
iterateList n f x = f x >>= iterateList (n - 1) f
withoutI :: Int -> [a] -> [a]
withoutI i list = take i list ++ drop (i + 1) list
removeUniformly :: Int -> [a] -> Int -> [a]
removeUniformly n list len = concatMap tail $ chunksOf ((len - 1) `div` n + 1) list
intertwine :: [Int] -> [a] -> [a] -> [a]
intertwine is as bs = concat $! intertwine' lens as bs
where lens = zipWith subtract (0 : is) is
intertwine' [] as' _ = [as']
intertwine' (l : ls) as' bs' = take l as' : intertwine' ls (drop l bs') (drop l as')
| LukaHorvat/ArtGallery | src/Common.hs | mit | 1,488 | 0 | 19 | 444 | 759 | 389 | 370 | 39 | 2 |
{-|
Some sample things to try and make ...
-------------------------------
Single Well
Cell Modem Polled Well Set
Elynx Well Definition
GCS Well
Schlumberger Well
------------------------------
I think having a setting like default Maybe makes a lot of sense.
* If DefaultOptional is turned on, then every field is actually assumed to be optional
I think it also makes sense to make this the default.
* So you would specify 'NoDefaultOptional' to turn it off
* perhaps even a UseOptionalMaybe, UserOptionalEither or something like that in the future
* Stealing the typeclasses on Value in Data.Aeson leads me to some interesting stuff
Eq Value
Data Value
Show Value
Typeable Value
IsString Value
NFData Value
Hashable Value
* don't know about the hashable, NFData and IsString... but the rest of it I want for sure.
* RecordConstructors should be generated the same way they are in persistent
* The type graph should be inferred based on the way these structures interlink
* newtype wrappers should be generated for every primitive.
|-}
data OnpingTagCombined = OnpingTagCombined {
location_id :: LocationId
,slave_parameter_id :: Int
,parameter_tag_id :: Int
,description :: Text
,unit_id :: Int
,status_active :: Int
,status_writable :: Int
,last_update :: UTCTime
,result :: Text
,validation_code :: Text
,permissions :: Int
,delete :: Int
,companyIdRef :: CompanyIdRef
,siteIdRef :: SiteIdRef
,location :: Location
,pid :: Int
}
data Location = Location {
siteIdRef :: Int
,slaveId :: Int
,refId :: Int -
,name :: Text
,url :: Text
,delete :: Int
,companyIdRef :: Int
}
-- Drill down constraints only... no "many's"
-- Violating this rule will produce an alternate
data GCSDevice = GCSDevice {
,well :: Location | LocationCompanyId == 6
,tankBattery :: Loation | LocationCompanyId == 6
,activeTankLevel :: OnpingTagCombinedParameterTagId | OnpingTagCombinedParameterTagId == 30 , OnpingTagCombinedLocationId == GCSDeviceWellRefId
,transferDischargePressure :: OnpingTagCombinedParameterTagId | OnpingTagCombinedParameterTagId == 31 , OnpingTagCombinedLocationId == GCSDeviceWellRefId
,runStatus :: OnpingTagCombinedParameterTagId | OnpingTagCombinedParameterTagId == 32 , OnpingTagCombinedLocationId == GCSDeviceWellRefId
,operatingFrequency :: OnpingTagCombinedParameterTagId | OnpingTagCombinedParameterTagId == 33 , OnpingTagCombinedLocationId == GCSDeviceWellRefId
,aPhaseOut :: OnpingTagCombinedParameterTagId | OnpingTagCombinedParameterTagId == 34 , OnpingTagCombinedLocationId == GCSDeviceWellRefId
,bPhaseOut :: OnpingTagCombinedParameterTagId | OnpingTagCombinedParameterTagId == 35 , OnpingTagCombinedLocationId == GCSDeviceWellRefId
,cPhaseOut :: OnpingTagCombinedParameterTagId | OnpingTagCombinedParameterTagId == 36 , OnpingTagCombinedLocationId == GCSDeviceWellRefId
,abInput :: OnpingTagCombinedParameterTagId | OnpingTagCombinedParameterTagId == 37 , OnpingTagCombinedLocationId == GCSDeviceWellRefId
,bcInput :: OnpingTagCombinedParameterTagId | OnpingTagCombinedParameterTagId == 38 , OnpingTagCombinedLocationId == GCSDeviceWellRefId
,caInput :: OnpingTagCombinedParameterTagId | OnpingTagCombinedParameterTagId == 39 , OnpingTagCombinedLocationId == GCSDeviceWellRefId
,bhp :: OnpingTagCombinedParameterTagId | OnpingTagCombinedParameterTagId == 310 , OnpingTagCombinedLocationId == GCSDeviceWellRefId
,bht :: OnpingTagCombinedParameterTagId | OnpingTagCombinedParameterTagId == 311 , OnpingTagCombinedLocationId == GCSDeviceWellRefId
,tubing :: OnpingTagCombinedParameterTagId | OnpingTagCombinedParameterTagId == 312 , OnpingTagCombinedLocationId == GCSDeviceWellRefId
,casing :: OnpingTagCombinedParameterTagId | OnpingTagCombinedParameterTagId == 313 , OnpingTagCombinedLocationId == GCSDeviceWellRefId
,flowRate :: OnpingTagCombinedParameterTagId | OnpingTagCombinedParameterTagId == 4 , OnpingTagCombinedLocationId == GCSTankBatteryRefId
previousDayFlowRate :: OnpingTagCombinedParameterTagId | OnpingTagCombinedParameterTagId == 3 , OnpingTagCombinedLocationId == GCSTankBatteryRefId
}
data SchlumbergerDevice = SchlumbergerDevice {
,well :: Location | LocationCompanyId == 6
,tankBattery :: Loation | LocationCompanyId == 6
,activeTankLevel :: OnpingTagCombinedParameterTagId | OnpingTagCombinedParameterTagId == 0 , OnpingTagCombinedLocationId == GCSDeviceWellRefId
,transferDischargePressure :: OnpingTagCombinedParameterTagId | OnpingTagCombinedParameterTagId == 1 , OnpingTagCombinedLocationId == GCSDeviceWellRefId
,runStatus :: OnpingTagCombinedParameterTagId | OnpingTagCombinedParameterTagId == 2 , OnpingTagCombinedLocationId == GCSDeviceWellRefId
,operatingFrequency :: OnpingTagCombinedParameterTagId | OnpingTagCombinedParameterTagId == 3 , OnpingTagCombinedLocationId == GCSDeviceWellRefId
,aPhaseOut :: OnpingTagCombinedParameterTagId | OnpingTagCombinedParameterTagId == 4 , OnpingTagCombinedLocationId == GCSDeviceWellRefId
,bPhaseOut :: OnpingTagCombinedParameterTagId | OnpingTagCombinedParameterTagId == 5 , OnpingTagCombinedLocationId == GCSDeviceWellRefId
,cPhaseOut :: OnpingTagCombinedParameterTagId | OnpingTagCombinedParameterTagId == 6 , OnpingTagCombinedLocationId == GCSDeviceWellRefId
,abInput :: OnpingTagCombinedParameterTagId | OnpingTagCombinedParameterTagId == 7 , OnpingTagCombinedLocationId == GCSDeviceWellRefId
,bcInput :: OnpingTagCombinedParameterTagId | OnpingTagCombinedParameterTagId == 8 , OnpingTagCombinedLocationId == GCSDeviceWellRefId
,caInput :: OnpingTagCombinedParameterTagId | OnpingTagCombinedParameterTagId == 9 , OnpingTagCombinedLocationId == GCSDeviceWellRefId
,bhp :: OnpingTagCombinedParameterTagId | OnpingTagCombinedParameterTagId == 10 , OnpingTagCombinedLocationId == GCSDeviceWellRefId
,bht :: OnpingTagCombinedParameterTagId | OnpingTagCombinedParameterTagId == 11 , OnpingTagCombinedLocationId == GCSDeviceWellRefId
,tubing :: OnpingTagCombinedParameterTagId | OnpingTagCombinedParameterTagId == 12 , OnpingTagCombinedLocationId == GCSDeviceWellRefId
,casing :: OnpingTagCombinedParameterTagId | OnpingTagCombinedParameterTagId == 13 , OnpingTagCombinedLocationId == GCSDeviceWellRefId
,flowRate :: OnpingTagCombinedParameterTagId | OnpingTagCombinedParameterTagId == 4 , OnpingTagCombinedLocationId == GCSTankBatteryRefId
previousDayFlowRate :: OnpingTagCombinedParameterTagId | OnpingTagCombinedParameterTagId == 3 , OnpingTagCombinedLocationId == GCSTankBatteryRefId
}
data ElynxWellFlowRate = ElynxWellFlowRate1 GCSDeviceFlowRate | ElynxWellFlowRate2 SchlumbergerFlowRate
data ElynxWellCasingPressure = ElynxWellCasingPressure1 GCSDeviceCasing | ElynxWellCasingPressure2 SchlumbergerDeviceCasing
data ElynxWell = ElynxWell {
flowRate :: ElynxWellFlowRate
,casingPressure :: ElynxWellCasingPressure
}
| smurphy8/contraption | experiments/haskelly.hs | mit | 7,991 | 109 | 10 | 1,972 | 908 | 532 | 376 | -1 | -1 |
module Search (
alphabeta,
alphabetaWEndSolver,
Result(..)
) where
-- friends
import qualified BitBoard
import qualified Move
import qualified MoveGenerator
import qualified Eval
import qualified Tree
import qualified ProofNumberSearch
-- import qualified SlackMessenger
-- GHC
-- libraries
-- std
import Control.Arrow
data Result = Result {va :: Eval.Value, pv :: [Move.Mv]} deriving (Eq, Ord)
instance Show Result where
show (Result va pv) = "va: " ++ show va ++ ", pv : " ++ show pv
conv :: Move.Mv -> Result -> Result
conv mv res = Result (va res) (mv : pv res)
moves :: (BitBoard.Bb, Result) -> [(BitBoard.Bb, Result)]
moves (bd, result) =
map (\ x -> (BitBoard.move bd x, conv x result)) $ MoveGenerator.moveGenerationFull bd
gametree :: BitBoard.Bb -> Tree.Tree (BitBoard.Bb, Result)
gametree p = Tree.reptree moves (p, Result 0 [])
-- alphabeta
alphabeta :: (Num a, Eq a) => a -> BitBoard.Bb -> Result
alphabeta depth = normalizeResult . minimum . Tree.minimize' . Tree.maptree ((Eval.eval . fst) &&& snd) . Tree.prune depth . gametree
alphabetaWEndSolver :: (Num a, Eq a) => a -> BitBoard.Bb -> Result
alphabetaWEndSolver depth bb
| BitBoard.getNumVacant bb <= pnsDepth =
if va pnsRes > 0 then
-- SlackMessenger.unsafeSendMessageNow ("PNS Search success!: " ++ show pnsRes ++ ".")
pnsRes else
alphaRes
| otherwise = alphaRes
where
pnsDepth = 10
pnsRes = normalizeSolverResult (ProofNumberSearch.pnsSearch pnsDepth bb)
alphaRes = alphabeta depth bb
normalizeSolverResult :: ProofNumberSearch.Result -> Result
normalizeSolverResult pnsRes = Result (normalizePNSValue $ ProofNumberSearch.va pnsRes) (ProofNumberSearch.pv pnsRes)
normalizePNSValue :: ProofNumberSearch.ProofDisproofNumber -> Eval.Value
normalizePNSValue val = case val of
ProofNumberSearch.LeafProven -> 999
ProofNumberSearch.LeafDisproven -> -999
ProofNumberSearch.LeafUnknown -> 0
ProofNumberSearch.ProofDisproofNumber {ProofNumberSearch.proof = n, ProofNumberSearch.disproof = m} ->
if n > m then 9999 else -9999
normalizeResult :: (Eval.Value, Result) -> Result
normalizeResult (value, result) =
Result value pvs
where
pvs = if not (null pvFromRes) then pvFromRes else [Move.Nil]
pvFromRes = reverse $ pv result | ysnrkdm/Hamlet | src/Search.hs | mit | 2,347 | 0 | 13 | 467 | 727 | 392 | 335 | 47 | 5 |
------------------------------------------------------------------------------
-- |
-- Module : Main
-- Copyright : (C) 2014 Samuli Thomasson
-- License : BSD-style (see the file LICENSE)
-- Maintainer : Samuli Thomasson <[email protected]>
-- Stability : experimental
-- Portability : non-portable
------------------------------------------------------------------------------
module Main (main, tests) where
import System.Posix
import qualified Test.QuickCheck.Property as Q
import qualified MahjongTest.Mentsu as Mentsu
import qualified MahjongTest.Hand as Hand
import qualified MahjongTest.Mechanics as Mechanics
import qualified MahjongTest.Yaku as Yaku
-- import qualified HajongTest.CLI.PrettyPrint as PrettyPrint
-- import qualified HajongTest.CLI.Client as Client
import qualified HajongTest.Server.Server as Server
import qualified HajongTest.Server.Worker as Worker
main :: IO ()
main = do
-- The server process used by the client tests
putStrLn "Starting server process :9160..."
_st <- Server.forkTestServer
defaultMain tests
tests :: TestTree
tests = testGroup "Hajong tests"
[ Mentsu.tests
, Yaku.tests
, Mechanics.tests
, Hand.tests
--, PrettyPrint.tests
--, Client.tests
, Worker.tests
]
| SimSaladin/hajong | hajong-server/tests/tests.hs | mit | 1,352 | 0 | 8 | 277 | 166 | 109 | 57 | 21 | 1 |
module GHCJS.DOM.BeforeUnloadEvent (
) where
| manyoo/ghcjs-dom | ghcjs-dom-webkit/src/GHCJS/DOM/BeforeUnloadEvent.hs | mit | 47 | 0 | 3 | 7 | 10 | 7 | 3 | 1 | 0 |
module Lambdit.Requests where
import Control.Monad (liftM)
import Data.Maybe (listToMaybe)
import Debug.Trace (traceShow)
import Lambdit.Types
import Network.HTTP
import Network.Stream (Result)
import Network.URI (parseURI)
data Session = Session String deriving (Show)
class Reddit x where
mine :: x -> IO (JsonResponse MineResponseData)
instance Reddit Session where
mine _ = undefined
traceShow' :: (Show a) => a -> a
traceShow' x = traceShow x x
redditBase :: String
redditBase = "http://www.reddit.com"
-- This is PLAINTEXT OVER HTTP --
login :: String -> String -> IO (Maybe Session)
login uname pword = parseSession `liftM` submitPostRequest loginUrl ""
where loginUrl = redditBase ++ "/api/login?user=" ++ uname ++ "&passwd=" ++ pword ++ "&api_type=json"
parseSession :: Result (Response String) -> Maybe Session
parseSession (Left e) = traceShow e Nothing
parseSession (Right r) = if rspCode r == (2,0,0) then traceShow r (traceShow' (readCookie r)) else traceShow r Nothing
where readCookie :: Response String -> Maybe Session
readCookie s = Session `liftM` hdrValue `liftM` listToMaybe (filter (\h -> hdrName h == HdrSetCookie) (rspHeaders s))
submitPostRequest :: String -> String -> IO (Result (Response String))
submitPostRequest uriStr body =
case parseURI uriStr of
Nothing -> error "url syntax error"
Just uri -> simpleHTTP $ traceShow' rq
where
rq = Request
{ rqURI = uri
, rqMethod = POST
, rqHeaders = [ Header HdrContentType "application/x-www-form-urlencoded"
, Header HdrContentLength (show (length body))
]
, rqBody = body
}
| ejconlon/lambdit | src/Lambdit/Requests.hs | gpl-2.0 | 1,730 | 0 | 17 | 409 | 537 | 283 | 254 | 36 | 2 |
{-# LANGUAGE BangPatterns #-}
import Graphics.Rendering.OpenGL.GL.Tensor
import Data.Array.Accelerate as A
import qualified Data.Array.Accelerate.CUDA as I
import Data.List hiding (intersect)
import Foreign.C.Types
import Foreign.Ptr
import Data.Int
import Prelude as P
import Data.Word
import qualified Graphics.UI.GLUT as G
import Graphics.Rendering.OpenGL.GL.CoordTrans
width :: Int
width = 640
height :: Int
height = 480
fov :: Float
fov = 45.0
maxdepth :: Int
maxdepth = 6
type VectorF = Vertex3 Float
type VectorI = Vertex3 Int
type Vec a = (a, a, a)
type VecF = Vec Float
type SphereIntersect = (Bool, Sphere, Float)
type Index = (Int, Int)
type ArrayPlane a = Array DIM2 a
nullVector :: Exp (VecF)
nullVector = constant (0.0, 0.0, 0.0)
infixl 6 -.
infixl 6 +.
infixl 7 *.
(-.), (+.), (*.) :: (Elt a, IsNum a) => Exp (Vec a) -> Exp (Vec a) -> Exp (Vec a)
(-.) = vzipWith (-)
(+.) = vzipWith (+)
(*.) = vzipWith (*)
infixl 6 --.
infixl 6 ++.
infix 7 //.
infixl 7 **.
(--.), (++.), (**.) :: (Elt a, IsNum a) => Exp (Vec a) -> Exp a -> Exp (Vec a)
(--.) v f = vmap (flip (-) f) v
(++.) v f = vmap (f+) v
(**.) v f = vmap (f*) v
(//.) :: (Elt a, IsNum a, IsFloating a) => Exp (Vec a) -> Exp a -> Exp (Vec a)
(//.) v f = vmap (flip (/) f) v
cfalse :: Exp Bool
cfalse = constant False
ctrue :: Exp Bool
ctrue = constant True
vmap :: (Elt a, Elt b) => (Exp a -> Exp b) -> Exp (Vec a) -> Exp (Vec b)
vmap f v = let (x1,y1,z1) = unlift v
in
lift (f x1, f y1, f z1)
vzipWith :: (Elt a, Elt b, Elt c) => (Exp a -> Exp b -> Exp c) -> Exp (Vec a) -> Exp (Vec b) -> Exp (Vec c)
vzipWith f v1 v2
= let (x1,y1,z1) = unlift v1
(x2,y2,z2) = unlift v2
in
lift (f x1 x2, f y1 y2, f z1 z2)
dot :: (Elt a, IsNum a) => Exp (Vec a) -> Exp (Vec a) -> Exp a
dot a b = let
(x1, y1, z1) = unlift a
(x2, y2, z2) = unlift b
in
x1 * x2 + y1 * y2 + z1 * z2
mag :: (Elt a, IsNum a, A.IsFloating a) => A.Exp (Vec a) -> A.Exp a
mag l = sqrt $ dot l l
normalized :: (Elt a, A.IsNum a, IsFloating a) => A.Exp (Vec a) -> (A.Exp (Vec a))
normalized l = l //. (mag l)
type Ray = (VecF, --start
VecF) --dir
start :: Exp Ray -> Exp VecF
start r = A.fst r
dir :: Exp Ray -> Exp VecF
dir r = A.snd r
nullRay :: Exp Ray
nullRay = lift (nullVector, nullVector)
type Sphere = (VecF, --center
Float, --radius
VecF, --scolor
Float, --reflection
Float) --transparency
center :: Exp Sphere -> Exp VecF
center s = let (c, _, _, _, _) = unlift s :: (Exp VecF, Exp Float, Exp VecF, Exp Float, Exp Float)
in c
radius :: Exp Sphere -> Exp Float
radius s = let (_, r, _, _, _) = unlift s :: (Exp VecF, Exp Float, Exp VecF, Exp Float, Exp Float)
in lift r
scolor :: Exp Sphere -> Exp VecF
scolor s = let (_, _, c, _, _) = unlift s :: (Exp VecF, Exp Float, Exp VecF, Exp Float, Exp Float)
in lift c
reflection :: Exp Sphere -> Exp Float
reflection s = let (_, _, _, r, _) = unlift s :: (Exp VecF, Exp Float, Exp VecF, Exp Float, Exp Float)
in lift r
transparency :: Exp Sphere -> Exp Float
transparency s = let (_, _, _, _, t) = unlift s :: (Exp VecF, Exp Float, Exp VecF, Exp Float, Exp Float)
in lift t
type Light = (VecF, --position
VecF) --color
position :: Exp Light -> Exp VecF
position l = A.fst l
color :: Exp Light -> Exp VecF
color l = A.snd l
type Scene = (Vector Sphere, Vector Light)
type MultiBounceFactor = (Float, -- reflection
Float) -- refraction
nullMultiBounceFactor :: Exp MultiBounceFactor
nullMultiBounceFactor = constant $ (0.0, 0.0)
type MultiRay = (Ray, Ray, MultiBounceFactor)
nullMultiRay :: Exp MultiRay
nullMultiRay = lift (nullRay, nullRay, nullMultiBounceFactor) :: Exp MultiRay
objects :: Scene -> Vector Sphere
objects (spheres, lights) = spheres
lights :: Scene -> Vector Light
lights (spheres, lights) = lights
intersect :: Exp Sphere -> Exp Ray -> Exp Bool
intersect se re =
let
rs = start re
cs = center se
sr = radius se
dr = dir re
v = cs -. rs
a = dot v dr
b2 = dot v v - a * a
r2 = sr * sr
in
(a <* 0 ||* b2 >* r2) ? (constant False, constant True)
normalizeSphereSurface :: Exp Sphere -> Exp VecF -> Exp VecF
normalizeSphereSurface s v = normalized (v -. (center s))
intersectDist :: Exp Ray -> Exp Sphere -> Exp SphereIntersect
intersectDist r s =
let
v = (center s) -. (start r)
a = dot v (dir r)
b2 = dot v v - a * a
r2 = (radius s) * (radius s)
c = sqrt(r2 - b2)
near = a - c
far = a + c
distance = (near <* 0) ? (far, near)
in
(a <* 0 ||* b2 >* r2) ? (
lift $ (constant False, s, constant (-1.0)),
lift $ (constant True, s, distance)
)
predComp :: Exp SphereIntersect -> Exp SphereIntersect -> Exp SphereIntersect
predComp a b = (b1 ==* cfalse &&* b2 ==* cfalse) ? (a,
(b1 ==* cfalse &&* b2 ==* ctrue) ? (b,
(b1 ==* ctrue &&* b2 ==* cfalse) ? (a,
(b1 ==* ctrue &&* b2 ==* ctrue &&* d1 A.<* d2) ? (a, b))))
where
(b1, s1, d1) = A.unlift a :: (Exp Bool, Exp Sphere, Exp Float)
(b2, s2, d2) = A.unlift b :: (Exp Bool, Exp Sphere, Exp Float)
minInterSects :: Scene -> Acc (Array DIM2 Ray) -> Acc (Array DIM2 SphereIntersect)
minInterSects s rays = let
objs = objects s
usedObjs = use objs
dummySphere = ((0.0, 0, 0),
0.0,
(0.0, 0.0, 0.0),
0.0,
0.0)
dummyTuple = constant (False, dummySphere, -1.0)
k = size usedObjs
cols = A.replicate (lift $ Z :. All :. All :. k) rays
rows = A.replicate (lift $ Z :. width :. height :. All) usedObjs
intersects = A.fold predComp dummyTuple $ A.zipWith intersectDist cols rows
in
intersects
colorforlight :: Scene -> Exp Sphere -> Exp VecF -> Exp VecF -> Exp Light -> Exp VecF
colorforlight s sph pip norm l =
let
lightpos = position l
lightdirection = normalized (lightpos -. pip)
blocked = Main.intersect sph $ lift (pip, lightdirection)
clr = ((color l) **. (P.max 0.0 (dot norm lightdirection)))
*. (scolor sph) **. (1.0 - reflection sph)
in
(blocked) ? (constant (0.0, 0.0, 0.0), clr)
traceStep :: Scene -> Acc (ArrayPlane Int) -> Acc (ArrayPlane Ray) -> Acc (ArrayPlane MultiBounceFactor) -> Acc (ArrayPlane (MultiRay, Int, VecF))
traceStep scene depths rays factors = let
minintersects = minInterSects scene rays
intersectsWithRays = A.zip minintersects rays
usedLights = use $ lights scene
l = size usedLights
bounceCols = A.replicate (lift $ Z :. All :. All :. l) factors
depthCols = A.replicate (lift $ Z :. All :. All :. l) depths
cols = A.replicate (lift $ Z :. All :. All :. l) intersectsWithRays
rows = A.replicate (lift $ Z :. width :. height :. All) usedLights
in
A.fold1
(
\a b ->
let
(multiray1, depth1, color1) = unlift a :: (Exp MultiRay, Exp Int, Exp VecF)
(multiray2, depth2, color2) = unlift b :: (Exp MultiRay, Exp Int, Exp VecF)
in
lift (multiray2, depth1 + depth2, color1 +. color2)
)
$
A.zipWith4 (trace scene) depthCols cols rows bounceCols
infixl 6 $+.
($+.) :: Acc (ArrayPlane VecF) -> Acc (ArrayPlane VecF) -> Acc (ArrayPlane VecF)
($+.) a b = A.zipWith (+.) a b
infixl 6 $-.
($-.) :: Acc (ArrayPlane VecF) -> Acc (ArrayPlane VecF) -> Acc (ArrayPlane VecF)
($-.) a b = A.zipWith (-.) a b
infixl 7 $*.
($*.) :: Acc (ArrayPlane VecF) -> Acc (ArrayPlane Float) -> Acc (ArrayPlane VecF)
($*.) a b = A.zipWith (**.) a b
traceAll :: Acc (ArrayPlane Ray) -> Scene -> Acc (ArrayPlane VecF)
traceAll rays scene = let
d0 = generate (index2 (lift width) (lift height)) (\a -> (constant 0))
factor0 = generate (index2 (lift width) (lift height)) (\a -> (constant (1.0, 0.0)))
ray0 = generate (index2 (lift width) (lift height)) (\a -> nullRay)
multiray0 = A.zip3 rays ray0 factor0
traceMapStep :: Acc (ArrayPlane MultiRay) ->
(Acc (ArrayPlane VecF), [Acc (ArrayPlane MultiRay)])
traceMapStep r = let
(reflectionRays, refractionRays, bounceFactors) = A.unzip3 r
(reflectionFactors, refractionFactors) = A.unzip bounceFactors
reflectionContribution = traceStep scene d0 reflectionRays bounceFactors
(reflMultiRays, reflDepths, reflImage) = A.unzip3 reflectionContribution
refractionContribution = traceStep scene d0 refractionRays bounceFactors
(refrMultiRays, refrDepths, refrImage) = A.unzip3 refractionContribution
(refrReflRays, refrRefrRays, refrBounceFactors) = A.unzip3 refrMultiRays
reflDeltaImage = reflImage $+. refrImage
newList = [reflMultiRays]
--P.++ [refrMultiRays]
in
(reflDeltaImage, newList)
traceIter :: (Acc (ArrayPlane VecF), [Acc (ArrayPlane MultiRay)]) ->
(Acc (ArrayPlane VecF), [Acc (ArrayPlane MultiRay)])
traceIter (c0, rayList) = let
(newDeltaImages, newRays) = P.unzip $
P.map traceMapStep rayList
accImage = P.foldl ($+.) c0 newDeltaImages
newRayList = P.concat newRays
in
(accImage, newRayList)
trace0 = traceMapStep multiray0
(accImage, _) = foldr ($) trace0 (Data.List.take maxdepth (repeat traceIter))
in
accImage
-- Ray -> Sphere -> Normal -> dotNormal -> PointOfHit -> FresnelEffect -> (FresnelEffect, Ray)
reflectionFactorAndRay :: Exp Ray -> Exp Sphere -> Exp VecF -> Exp Float -> Exp VecF -> Exp Float -> Exp (Float, Ray)
reflectionFactorAndRay r s n dn pip f = lift (f, lift (pip, reflectiondirection) :: Exp Ray)
where
reflectionRatio = reflection (lift s)
facing = P.max 0.0 (-dn)
reflectiondirection = (dir r) -. (n **. (2.0 * dn))
-- Ray -> Sphere -> Normal -> PointOfImpact -> Inside -> Fresnel -> Depth -> (RefractionEffect, Ray)
refractionFactorAndRay :: Exp Ray -> Exp Sphere -> Exp VecF -> Exp VecF -> Exp Bool -> Exp Float -> Exp Int -> Exp (Float, Ray)
refractionFactorAndRay r s n pip ins f d = let
nullRay = ((constant (0.0, 0.0, 0.0)), (constant (0.0, 0.0, 0.0)))
nullElement = lift (constant 0, nullRay)
in
(transparency s >* 0.0) ?
(
let
ce = (dot (dir r) n) * (-1.0)
iorconst = constant 1.5
ior = ins ? (1.0 / iorconst, iorconst) :: Exp Float
eta = 1.0 / ior
gf = (dir r) +. (n **. (ce * eta))
sin_t1_2 = 1.0 - ce * ce
sin_t2_2 = sin_t1_2 * (eta * eta)
in
(sin_t2_2 <* 1.0) ? (
let
gc = n **. (sqrt 1 - sin_t2_2)
refraction_direction = gf -. gc
refraction = (1.0 - f) * (transparency s)
in
lift (refraction, (pip, refraction_direction)),
nullElement
),
nullElement)
trace :: Scene -> Exp Int -> Exp (SphereIntersect, Ray) -> Exp Light -> Exp (Float, Float)-> Exp (MultiRay, Int, VecF)
trace s d i l f = let
(reflectionFactor, refractionFactor) = unlift f :: (Exp Float, Exp Float)
(intersectingSphere, ray) = unlift i :: (Exp SphereIntersect, Exp Ray)
(hasIntersect, sp, di) = unlift intersectingSphere :: (Exp Bool, Exp Sphere, Exp Float)
(rstart, rdir) = unlift ray :: (Exp VecF, Exp VecF)
in
--((ray /=* nullRay) &&* hasIntersect) ? (
(hasIntersect) ? (
let
pointofhit = (dir ray) **. (lift di) +. start ray
normal_unrefl = normalizeSphereSurface (lift sp) pointofhit
dotnormalray_unrefl = dot normal_unrefl (dir ray)
isinside = (dotnormalray_unrefl >* 0) ? (ctrue, cfalse)
dotnormalray = (dotnormalray_unrefl >* 0) ? (-dotnormalray_unrefl, dotnormalray_unrefl)
normal = (dotnormalray_unrefl >* 0) ? (normal_unrefl **. (-1.0), normal_unrefl)
refl = reflection (lift sp)
transparencyratio = transparency (lift sp)
facing = P.max 0.0 (-dotnormalray)
fresneleffect = refl + (1.0 - refl) * ((1.0 -facing) ^^ 5)
traceclr = colorforlight s (lift sp) pointofhit (normal **. 1.0) l
clr = traceclr **. (reflectionFactor + refractionFactor)
nullFloatRay = lift ((constant 0.0), nullRay) :: Exp (Float, Ray)
(newReflectionFactor, reflectionRay) = unlift (
(d <* constant maxdepth) ? (
--reflection
(refl ==* 0.0) ? (
nullFloatRay,
--calculate next ray direction and color factor for next trace
reflectionFactorAndRay ray
sp
normal
dotnormalray
pointofhit
fresneleffect),
nullFloatRay)) :: (Exp Float, Exp Ray)
(newRefractionFactor, refractionRay) = unlift (
(d <* constant maxdepth) ? (
--reflection
(refractionFactor ==* 0.0) ? (
nullFloatRay,
--calculate next ray direction and color factor for next trace
refractionFactorAndRay ray
sp
normal
pointofhit
isinside
fresneleffect
d),
nullFloatRay)) :: (Exp Float, Exp Ray)
in
lift (
lift (
reflectionRay, refractionRay,
lift (newReflectionFactor, newRefractionFactor) :: Exp MultiBounceFactor
) :: Exp MultiRay,
d + 1, clr),
lift (nullMultiRay, d, nullVector)
)
updatePixel :: Index -> VecF -> IO ()
updatePixel p@(x, y) c@(r, g, b) = do
G.renderPrimitive G.Points $ do
G.color $ G.Color3 (CFloat r) (CFloat g) (CFloat b)
G.vertex $ Vertex3 (CFloat (P.fromIntegral x)) (CFloat (P.fromIntegral (height - y))) 0
constructRay :: Scene -> Exp VecF -> Exp Index -> Exp Ray
constructRay s eye idx = let
(x, y) = unlift idx :: (Exp Int, Exp Int)
h = constant $ (tan (fov / 360.0 * 2.0 * pi / 2.0)) * 2.0
ww = A.fromIntegral $ constant width :: Exp Float
hh = A.fromIntegral $ constant height :: Exp Float
w = h * ww / hh
rx = ((A.fromIntegral x) - ww/2.0) /ww * w
ry = (hh / 2.0 - (A.fromIntegral y)) / hh * h
dir = normalized $ lift (rx, ry, constant (-1.0))
ray = (lift (eye, dir))
in
ray
calcPixels :: Scene -> Exp VecF -> Acc (Array DIM2 Index) -> Acc (Array DIM2 VecF)
calcPixels s eye idx = let
rays = A.map (constructRay s eye) idx
in
traceAll rays s
updateAllPixels :: Array DIM2 (Index, VecF) -> Int -> Int -> IO ()
updateAllPixels p i j
| i >= width = updateAllPixels p 0 (j+1)
| j >= height = return ()
| otherwise =
do
let (idx, color) = p `indexArray` (Z :. i :. j)
updatePixel idx color
updateAllPixels p (i+1) (j)
render :: Scene -> IO ()
render s = do
let
eye = constant (0.0, 0.0, 0.0)
indices = A.generate (lift $ Z :. width :. height) unindex2
pixels = calcPixels s eye indices
pixelsWithIndices = I.run $ A.zip indices pixels
putStrLn "calculation done"
updateAllPixels pixelsWithIndices 0 0
mainDbg :: IO ()
mainDbg = do
let scene = ( (fromList (Z :. 5) [
((0.0, -10002.0, -20.0),
10000.0,
(0.8, 0.8, 0.8),
0.0,
0.0),
((0.0, 2.0, -20.0),
4.0,
(0.8, 0.5, 0.5),
0.5,
0.0),
((5.0, 0.0, -15.0),
2.0,
(0.3, 0.8, 0.8),
0.2,
0.0),
((-5.0, 0.0, -15.0),
2.0,
(0.3, 0.5, 0.8),
0.2,
0.0),
((-2.0, -1.0, -10.0),
1.0,
(0.1, 0.1, 0.1),
0.1,
0.8)
]),
(fromList (Z :. 1) [
((-10.0, 20.0, 30.0),
(2.0, 2.0, 2.0))
])
)
eye = constant (0.0, 0.0, 0.0)
indices = A.generate (lift $ Z :. width :. height) unindex2
pixels = calcPixels scene eye indices
!pixelsWithIndices = I.run $ A.zip indices pixels
putStrLn "calculation done"
mainNormal :: IO ()
mainNormal = do
(progname, _) <- G.getArgsAndInitialize
w <- G.createWindow "Haskell raytracer"
G.windowSize G.$= (G.Size (CInt (P.fromIntegral width)) (CInt (P.fromIntegral height)))
let scene = ( (fromList (Z :. 5) [
((0.0, -10002.0, -20.0),
10000.0,
(0.8, 0.8, 0.8),
0.0,
0.0),
((0.0, 2.0, -20.0),
4.0,
(0.8, 0.5, 0.5),
0.5,
0.0),
((5.0, 0.0, -15.0),
2.0,
(0.3, 0.8, 0.8),
0.2,
0.0),
((-5.0, 0.0, -15.0),
2.0,
(0.3, 0.5, 0.8),
0.2,
0.0),
((-2.0, -1.0, -10.0),
1.0,
(0.1, 0.1, 0.1),
0.1,
0.8)
]),
(fromList (Z :. 1) [
((-10.0, 20.0, 30.0),
(2.0, 2.0, 2.0))
])
)
G.reshapeCallback G.$= Just Main.reshape
G.displayCallback G.$= display scene
G.mainLoop
main :: IO ()
main = mainNormal
reshape :: Size -> IO ()
reshape size@(Size w h) = do
G.viewport G.$= (Position 0 0, size)
G.matrixMode G.$= Projection
G.loadIdentity
ortho 0.0 (P.fromIntegral w) 0.0 (P.fromIntegral h) (-1.0) 1.0
G.matrixMode G.$= Modelview 0
display :: Scene -> IO ()
display s = do
G.clear [G.ColorBuffer]
render s
G.swapBuffers
| apriori/accelerate-raytracer | raytracer.hs | gpl-2.0 | 26,680 | 0 | 20 | 14,456 | 7,236 | 3,856 | 3,380 | -1 | -1 |
{-#LANGUAGE OverloadedStrings #-}
module Language.Ammonite.Interpreter.RTS
( RTS(..)
, newRTS
, mkExnVal
, appendTrace
) where
import Language.Ammonite.Gensym
import Language.Ammonite.Syntax.Abstract
import Language.Ammonite.Syntax.Printer
import Data.Monoid
import Control.Applicative
import Control.Monad.State
import Data.Symbol
import Data.Maybe
import qualified Data.Sequence as Seq
import qualified Data.Map as Map
data RTS sysval = RTS
{ rtsExnCue :: Value sysval
, rtsExnType :: Value sysval
, rtsScopeError :: Value sysval
, rtsAccessError :: Value sysval
, rtsUpdateError :: Value sysval
, rtsTypeError :: Value sysval
, rtsUnhandledExn :: Value sysval
}
newRTS :: GensymSource -> (RTS sysval, GensymSource)
newRTS source = flip runState source $ do
exnCue <- gensym
exnType <- gensym
scopeError <- gensym
accessError <- gensym
updateError <- gensym
typeError <- gensym
unhandledExn <- gensym
pure $ RTS
{ rtsExnCue = CueVal exnCue (Nothing, Just "EXN")
, rtsExnType = TagVal (exnType, (Nothing, Just "Exn"))
, rtsScopeError = TagVal (scopeError, (Nothing, Just "ScopeError"))
, rtsAccessError = TagVal (accessError, (Nothing, Just "AccessError"))
, rtsUpdateError = TagVal (updateError, (Nothing, Just "UpdateError"))
, rtsTypeError = TagVal (typeError, (Nothing, Just "TypeError"))
, rtsUnhandledExn = TagVal (unhandledExn, (Nothing, Just "UnhandledExn"))
}
mkExnVal :: RTS sysval -> Value sysval -> Value sysval -> Value sysval
mkExnVal rts tag msg =
let TagVal exnType = rtsExnType rts
in AbsVal exnType RecordVal
{ rvPos = Seq.fromList [tag]
, rvKw = Map.fromList [(intern "msg", msg)]
}
-- TODO once I figure out how to do exists/access/update/delete/call on abstypes, stuff will look nice
unpackExn :: RTS sysval -> Value sysval -> Maybe (Tag, Value sysval)
unpackExn rts (AbsVal (tag, meta) v) =
let TagVal (exnTag, _) = rtsExnType rts
in if tag == exnTag
then Just ((tag, meta), v)
else Nothing
appendTrace :: (ReportValue sysval) => RTS sysval -> Value sysval -> Continuation sysval -> Maybe (Value sysval)
appendTrace rts it k = do
(tag, v@(RecordVal { rvKw = kw })) <- unpackExn rts it
trace <- case Map.lookup (intern "trace") kw of
Just (StrVal below) -> Just . StrVal $ stackTrace k <> "\n" <> below
Nothing -> Just . StrVal $ stackTrace k
Just _ -> Nothing
Just $ AbsVal tag (v { rvKw = Map.insert (intern "trace") trace kw })
gensym :: State GensymSource Gensym
gensym = do
(it, rest) <- step <$> get
put rest
pure it
| Zankoku-Okuno/ammonite | Language/Ammonite/Interpreter/RTS.hs | gpl-3.0 | 2,775 | 0 | 14 | 703 | 884 | 470 | 414 | 66 | 3 |
module ContMap (
GeneralContinuation,
Cont,
ContId,
ContMap,
YesodCC(..),
run,
resume,
answerGet,
readContMap,
modifyContMap,
insertContMap,
lookupContMap,
inquire,
inquireFinish,
inquireGet,
inquireGetUntil,
inquirePost,
inquirePostUntil,
inquirePostButton,
inquirePostUntilButton,
generateCcFormGet,
generateCcFormPost,
generateCcLabel,
) where
import Form
import Import.NoFoundation
import Text.Blaze (Markup)
import Data.Unique
--import Data.IORef
import qualified Data.Map as Map
import qualified Data.Text as T
import Control.Monad.CC.CCCxe
-- type AppHandler = HandlerT App IO
type GeneralContinuation m a = a -> CC (PS a) m a
type Cont site = GeneralContinuation (HandlerT site IO) Html
type ContId = Int
type ContMap site = Map ContId (Cont site)
-- Missing instances
-- instance Monad m => Functor (CC p m) where
-- fmap f cc = do a <- cc
-- return (f a)
-- instance Monad m => Applicative (CC p m) where
-- pure = return
-- m <*> x = do a <- m
-- b <- x
-- return (a b)
---------------------- Define the type class ------------------------
class YesodCC site where
getCcPool :: site -> IORef (ContMap site)
newCcPool :: IO (IORef (ContMap site))
newCcPool = newIORef Map.empty
-------------- Access to the global continuation store --------------
readContMap :: YesodCC site => HandlerT site IO (ContMap site)
readContMap = do
yesod <- getYesod
liftIO $ readIORef $ getCcPool yesod
modifyContMap :: YesodCC site => ( (ContMap site) -> (ContMap site) ) -> HandlerT site IO ()
modifyContMap f = do
yesod <- getYesod
let ioref = getCcPool yesod
liftIO $ modifyIORef' ioref f
insertContMap :: YesodCC site => ContId -> Cont site -> HandlerT site IO ()
insertContMap klabel k =
modifyContMap (Map.insert klabel k)
lookupContMap :: YesodCC site => ContId -> HandlerT site IO (Maybe (Cont site))
lookupContMap klabel = do
cont_map <- readContMap
return $ Map.lookup klabel cont_map
---------------------- Continuation primitives ----------------------
sendk :: YesodCC site
=> ContId
-> Html
-> (Html -> CC (PS Html) (HandlerT site IO) Html)
-> CC (PS Html) (HandlerT site IO) Html
sendk klabel html k = do
lift $ insertContMap klabel k
return html
inquire :: YesodCC site => ContId -> Html -> CC (PS Html) (HandlerT site IO) Html
inquire klabel html = do
shiftP ps $ sendk klabel html
inquireFinish :: YesodCC site => Html -> CC (PS Html) (HandlerT site IO) Html
inquireFinish html = abortP ps $ return html
inquireGet :: YesodCC site
=> ContId -> Html
-> (Html -> MForm (HandlerT site IO) (FormResult a, t))
-> CC (PS Html) (HandlerT site IO) (FormResult a)
inquireGet klabel html form = do
_ <- inquire klabel html
((result, _widget), _enctype) <- lift $ runFormGet form
return result
inquireGetUntil :: YesodCC site
=> ContId -> Html
-> (Html -> MForm (HandlerT site IO) (FormResult a, t))
-> CC (PS Html) (HandlerT site IO) a
inquireGetUntil klabel html form = do
_ <- inquire klabel html
((result, _widget), _enctype) <- lift $ runFormGet form
case result of
FormSuccess r -> return r
_ -> inquireGetUntil klabel html form
inquirePostUntil :: (YesodCC site, RenderMessage site FormMessage)
=> ContId -> Html
-> (Html -> MForm (HandlerT site IO) (FormResult a, t))
-> CC (PS Html) (HandlerT site IO) a
inquirePostUntil klabel html form = do
_ <- inquire klabel html
((result, _widget), _enctype) <- lift $ runFormPost form
case result of
FormSuccess r -> return r
_ -> inquirePostUntil klabel html form
inquirePost :: (YesodCC site, RenderMessage site FormMessage)
=> ContId -> Html
-> (Html -> MForm (HandlerT site IO) (FormResult a, t))
-> CC (PS Html) (HandlerT site IO) (FormResult a)
inquirePost klabel html form = do
_ <- inquire klabel html
((result, _widget), _enctype) <- lift $ runFormPost form
return result
inquirePostUntilButton :: (YesodCC site, RenderMessage site FormMessage, Show a, Show b)
=> ContId -> Html
-> (Html -> MForm (HandlerT site IO) (FormResult a, t))
-> [(Text,b)]
-> CC (PS Html) (HandlerT site IO) (a, Maybe b)
inquirePostUntilButton klabel html form buttons = do
x <- inquirePostUntil klabel html form
r <- lift $ runFormPostButtons buttons
case r of
Just _button -> return (x, r)
Nothing -> inquirePostUntilButton klabel html form buttons
inquirePostButton :: (YesodCC site, RenderMessage site FormMessage, Show a, Show b)
=> ContId -> Html
-> (Html -> MForm (HandlerT site IO) (FormResult a, t))
-> [(Text,b)]
-> CC (PS Html) (HandlerT site IO) (FormResult a, Maybe b)
inquirePostButton klabel html form buttons = do
result <- inquirePost klabel html form
case result of
FormMissing -> return (FormMissing , Nothing)
FormFailure err -> return (FormFailure err , Nothing)
FormSuccess a -> do
r <- lift $ runFormPostButtons buttons
case r of
Just _button -> return (FormSuccess a, r)
Nothing -> return (FormFailure ["no such buttons"] , r)
runFormPostButtons :: (YesodCC site, Show b)
=> [(Text,b)] -> (HandlerT site IO) (Maybe b)
runFormPostButtons [] = return Nothing
runFormPostButtons ((name,value):xs) = do
p <- lookupPostParam name
case p of
Just _ -> return (Just value)
_ -> runFormPostButtons xs
-- answerGet :: (MonadTrans t, Monad (t AppHandler))
-- => (Html -> MForm AppHandler (FormResult a, Widget)) -> t AppHandler a -> t AppHandler a
answerGet :: (MonadTrans t, MonadHandler m, Monad (t m)) =>
(Markup -> MForm m (FormResult a, t1)) -> t m a -> t m a
answerGet form error_action = do
((result, _widget), _enctype) <- lift $ runFormGet form
case result of
FormSuccess r -> return r
_ -> error_action
run :: (YesodCC site) => CC (PS a) (HandlerT site IO) a -> HandlerT site IO a
run f = do
$(logInfo) $ T.pack $ "Running a new continuation"
runCC $ pushPrompt ps f
resume :: YesodCC site => ContId -> Html -> Html -> HandlerT site IO Html
resume klabel contHtml notFoundHtml = do
$(logInfo) $ T.pack $ "resuming " ++ show klabel
mk <- lookupContMap klabel
case mk of
Just k -> runCC $ k contHtml
Nothing -> return notFoundHtml
---------------------------- Yesod defs ----------------------------
generateCcFormGet :: (RenderMessage (HandlerSite m) FormMessage, MonadHandler m)
=> (Markup -> MForm m (FormResult a, xml)) -> m (Int, xml, Enctype)
generateCcFormGet form = do
(widget, enctype) <- generateFormGet' form
klabel <- generateCcLabel
return (klabel, widget, enctype)
generateCcFormPost :: (RenderMessage (HandlerSite m) FormMessage, MonadHandler m)
=> (Markup -> MForm m (FormResult a, xml)) -> m (Int, xml, Enctype)
generateCcFormPost form = do
(widget, enctype) <- generateFormPost form
klabel <- generateCcLabel
return (klabel, widget, enctype)
-- Now we are on a 64bit system! maxBound::Int = 9223372036854775807!
generateCcLabel :: (RenderMessage (HandlerSite m) FormMessage, MonadHandler m)
=> m Int
generateCcLabel = do
unique <- liftIO $ newUnique
let klabel = hashUnique unique
return klabel
| nishiuramakoto/logiku | app/ContMap.hs | gpl-3.0 | 7,826 | 0 | 18 | 2,138 | 2,554 | 1,291 | 1,263 | -1 | -1 |
{-# LANGUAGE DeriveDataTypeable #-}
-- | Core functionality for the Anorak system.
module Anorak.Results (aggregate,
awayWins,
biggestWins,
convertResult,
form,
Goal(..),
highestAggregates,
homeWins,
prepareResults,
Result(..),
Results(..),
Team,
TeamResult(..)) where
import Data.ByteString.Char8(ByteString)
import qualified Data.ByteString.Char8 as BS(unpack)
import Data.List(groupBy, partition, sortBy)
import Data.Map(Map)
import qualified Data.Map as Map(empty, findWithDefault, insertWith, map, mapWithKey)
import Data.Ord(comparing)
import Data.Time.Calendar(Day(..))
import Data.Time.Format(defaultTimeLocale, formatTime)
import Util.List(equal, takeAtLeast)
-- | A team is represented simply by its name.
type Team = ByteString
-- | A match result consists of a date, two teams and the goals scored by each.
data Result = Result {date :: !Day, -- ^ The day that the match was played.
homeTeam :: !Team, -- ^ The team playing at home.
homeScore :: !Int, -- ^ The number of goals scored by the home team.
awayTeam :: !Team, -- ^ The visiting team.
awayScore :: !Int, -- ^ The number of goals scored by the away team.
homeGoals :: [Goal], -- ^ An optional list of home goals.
awayGoals :: [Goal] -- ^ An optional list of away goals.
}
instance Show Result where
show result = formatTime defaultTimeLocale "%e %b %Y: " (date result) ++
BS.unpack (homeTeam result) ++ " " ++
show (homeScore result) ++ " - " ++
show (awayScore result) ++ " " ++
BS.unpack (awayTeam result)
instance Eq Result where
(==) result1 result2 = date result1 == date result2
&& homeTeam result1 == homeTeam result2
&& awayTeam result1 == awayTeam result2
&& homeScore result1 == homeScore result2
&& awayScore result1 == awayScore result2
instance Ord Result where
compare result1 result2
| date result1 == date result2 = comparing homeTeam result1 result2
| otherwise = comparing date result1 result2
-- | Returns the match aggregate (total number of goals).
aggregate :: Result -> Int
aggregate result = homeScore result + awayScore result
-- | A TeamResult is another way of organising information about the result of the match, relative to
-- a particular team.
data TeamResult = TeamResult {day :: !Day,
opposition :: !Team,
venue :: !Char,
scored :: !Int,
conceded :: !Int,
outcome :: !Char,
goalsFor :: [Goal],
goalsAgainst :: [Goal]}
instance Show TeamResult where
show result = formatTime defaultTimeLocale "%e %b %Y: " (day result) ++
BS.unpack (opposition result) ++ "(" ++ [venue result] ++ ") " ++ [outcome result] ++ " " ++
show (scored result) ++ "-" ++ show (conceded result)
-- | The data about a goal consists of the name of the player who scored it and the minute of the match (1-90) in which it was scored.
data Goal = Goal {scorer :: !ByteString, -- ^ The name of the player that scored the goal.
minute :: !Int, -- ^ The minute (1-90) in which the goal was scored. First-half injury time is always 45, second-half added time always 90.
goalType :: !ByteString -- ^ \"p\" for penalty, \"o\" for own goal, empty string for all others.
}
deriving (Eq, Show)
-- | Data structure for holding the different variants of the results data set.
data Results = Results {list :: ![Result], -- ^ A list of all results for all teams for the season, ordered by date.
byTeam :: !(Map Team [Result]), -- ^ Map from team name to list of results that team was involved in.
homeOnly :: !(Map Team [Result]), -- ^ Home results by team.
awayOnly :: !(Map Team [Result]), -- ^ Away results by team.
byDate :: !(Map Day [Result]), -- ^ Results by date, each date is mapped to a list of matches on that day.
firstHalf :: Map Team [Result], -- ^ Half-time scores by team.
secondHalf :: Map Team [Result] -- ^ Second-half scores by team.
}
-- | Convert a flat list of results into a mapping from team to list of results that that team was involved in.
resultsByTeam :: [Result] -> Map ByteString Team -> Map Team [Result]
resultsByTeam [] _ = Map.empty
resultsByTeam (Result d ht hs at as hg ag:rs) aliases = addResultToMap (addResultToMap (resultsByTeam rs aliases) homeTeam aliasedHResult) awayTeam aliasedAResult
-- Map aliased team names so that all results for the same team are recorded against the current team name.
where hTeam = Map.findWithDefault ht ht aliases
aTeam = Map.findWithDefault at at aliases
aliasedHResult = Result d hTeam hs at as hg ag
aliasedAResult = Result d ht hs aTeam as hg ag
-- | Convert a flat list of results into a mapping from date to list of matches played on that date.
resultsByDate :: [Result] -> Map Day [Result]
resultsByDate [] = Map.empty
resultsByDate (result:rs) = addResultToMap (resultsByDate rs) date result
-- | Helper function for adding a result to a map that maps an aribtrary key type to a list of results.
addResultToMap :: Ord k => Map k [Result] -> (Result -> k) -> Result -> Map k [Result]
addResultToMap rMap keyFunction result = Map.insertWith (++) (keyFunction result) [result] rMap
-- | Splits each team's results into home results and away results. The first item in the mapped tuple is the team's
-- home results, the second is their away results.
splitHomeAndAway :: Map Team [Result] -> Map Team ([Result], [Result])
splitHomeAndAway = Map.mapWithKey partitionResults
where partitionResults team = partition ((team ==) . homeTeam)
-- | Maps a single result for a particular team to a character ('W', 'D' or 'L').
form :: Team -> Result -> Char
form team result
| homeScore result == awayScore result = 'D'
| (homeTeam result == team && homeScore result > awayScore result)
|| (awayTeam result == team && awayScore result > homeScore result) = 'W'
| otherwise = 'L'
-- | Converts a Result into a TeamResult for the specified team.
convertResult :: Team -> Result -> TeamResult
convertResult team result
| team == homeTeam result = TeamResult (date result) (awayTeam result) 'H' (homeScore result) (awayScore result) (form team result) (homeGoals result) (awayGoals result)
| otherwise = TeamResult (date result) (homeTeam result) 'A' (awayScore result) (homeScore result) (form team result) (awayGoals result) (homeGoals result)
-- | Returns the margin of victory for a result (zero if it is a draw).
margin :: Result -> Int
margin result = abs $ homeScore result - awayScore result
-- | Filter the list of results and return only matches in which the home team won (omit draws and away wins).
homeWins :: [Result] -> [Result]
homeWins = filter (\r -> homeScore r > awayScore r)
-- | Filter the list of results and return only matches in which the away team won (omit draws and home wins).
awayWins :: [Result] -> [Result]
awayWins = filter (\r -> homeScore r < awayScore r)
-- | Return the results with the biggest margins of victory. Returns at least 3 results (unless
-- there are less than 3 in total). Any results that are equivalent to the third result are also
-- returned. So, for example, if the biggest margin is 4 goals and there are 5 matches with
-- a 4-goal margin, all 5 will be returned.
biggestWins :: [Result] -> [Result]
biggestWins results = takeAtLeast 3 $ groupBy (equal margin) sortedResults
where sortedResults = sortBy (flip $ comparing margin) results
-- | Return the results with the highest total number of goals. Returns at least 3 results (unless
-- there are less than 3 in total). Any results that are equivalent to the third result are also
-- returned. So, for example, if the highest aggregate is 10 goals and there are 5 matches with
-- 10 goals, all 5 will be returned.
highestAggregates :: [Result] -> [Result]
highestAggregates results = takeAtLeast 3 $ groupBy (equal aggregate) sortedResults
where sortedResults = sortBy (flip $ comparing aggregate) results
-- | Covert a list of 90-minute results into hypothetical first-half and second-half results.
splitFirstAndSecondHalf :: [Result] -> ([Result], [Result])
splitFirstAndSecondHalf = unzip . map splitResult
-- | Convert a single 90-minute result into hypothetical first-half and second-half results.
splitResult :: Result -> (Result, Result)
splitResult (Result d ht _ at _ hg ag) = (firstHalfResult, secondHalfResult)
where (fstHalfHGoals, laterHGoals) = partition ((<= 45).minute) hg
(fstHalfAGoals, laterAGoals) = partition ((<= 45).minute) ag
-- Filter out any extra-time goals.
sndHalfHGoals = filter ((<= 90).minute) laterHGoals
sndHalfAGoals = filter ((<= 90).minute) laterAGoals
firstHalfResult = Result d ht (length fstHalfHGoals) at (length fstHalfAGoals) fstHalfHGoals fstHalfAGoals
secondHalfResult = Result d ht (length sndHalfHGoals) at (length sndHalfAGoals) sndHalfHGoals sndHalfAGoals
-- | Take a list of results and return a set of useful transformations of that data.
prepareResults :: [Result] -> Map ByteString Team -> Results
prepareResults results aliases = Results results teamResults (Map.map fst homeAndAway) (Map.map snd homeAndAway) matchDays firstHalfByTeam secondHalfByTeam
where teamResults = resultsByTeam results aliases
matchDays = resultsByDate results
(firstHalfResults, secondHalfResults) = splitFirstAndSecondHalf results
firstHalfByTeam = resultsByTeam firstHalfResults aliases
secondHalfByTeam = resultsByTeam secondHalfResults aliases
homeAndAway = splitHomeAndAway teamResults
| dwdyer/anorak | src/haskell/Anorak/Results.hs | gpl-3.0 | 11,477 | 0 | 17 | 3,781 | 2,172 | 1,167 | 1,005 | 165 | 1 |
module Shrdlite.Planner where
import Shrdlite.AStar
import Shrdlite.Common
import Shrdlite.Grammar
import Control.Monad
import Data.Maybe
import qualified Data.List as L
import qualified Data.Map as M
import qualified Data.Set as S
-- | Creates Just a list of moves which together creates a "Plan". The plan can
-- consist of messages to the user and commands in the form of
-- "pick FLOOR_SPACE" and "drop FLOOR_SPACE". If no plan could be found,
-- returns Nothing
solve :: World -> Maybe Id -> Objects -> [Goal] -> Maybe Plan
solve _ _ _ [] = Nothing
solve w h o (g:[]) = let plan = aStar (worldGraph o) (heuristics g) (check g) (w,h)
in plan
solve w h o (g:gs) = case plan of
Nothing -> Nothing
Just p -> case newPlan of
Nothing -> Nothing
Just p' -> Just $ p ++ p'
where (newWorld, newHolding) = simulatePlan w h p
newPlan = solve newWorld newHolding o gs
where
plan = aStar (worldGraph o) (heuristics g) (check g) (w,h)
simulatePlan :: World -> Maybe Id -> Plan -> (World, Maybe Id)
simulatePlan oldWorld h [] = (oldWorld, h)
simulatePlan oldWorld (Just h) (p:ps) = simulatePlan newWorld Nothing ps
where (left, col:right) = L.splitAt (read (last (words p))::Int) oldWorld
newWorld = left ++ [col ++ [h]] ++ right
simulatePlan oldWorld Nothing (p:ps) = simulatePlan newWorld (Just c) ps
where (left, (c:col):right) = L.splitAt (read (last (words p))::Int) oldWorld
newWorld = left ++ col:right
-- | Given a state, produces a set of all possible neighbours
worldGraph :: Objects -> WorldHolding -> S.Set WorldHolding
worldGraph o (w, h) = case h of
Just i -> foldr (placeObject o i) S.empty worldParts
Nothing -> foldr (takeObject o) S.empty worldParts
where
worldParts = init $ zip (L.inits w) (L.tails w)
-- | Puts the World parts together, with the Id added to the beginning of
-- the second list
placeObject :: Objects -> Id -> ([[Id]], [[Id]]) -> S.Set WorldHolding
-> S.Set WorldHolding
placeObject o h e s = case newWorld h of
Nothing -> s
Just w -> S.insert (w, Nothing) s
where
newWorld elm = joinModified o e (\x -> x ++ [elm])
-- | Takes the top object from the first list of the last World part
takeObject :: Objects -> ([[Id]], [[Id]]) -> S.Set WorldHolding -> S.Set WorldHolding
takeObject o e s = case takeHighest e of
Nothing -> s
Just i -> S.insert (newWorld, Just i) s
where
newWorld = fromMaybe (error "Error: Physical laws violated")
(joinModified o e maybeInit)
maybeInit [] = []
maybeInit xs = init xs
-- | Takes the highest object in one of the lists
takeHighest :: ([[Id]], [[Id]]) -> Maybe Id
takeHighest ([], []) = Nothing
takeHighest (xs, []) = maybeLast $ last xs
takeHighest (_, y:_) = maybeLast y
-- | The last element of the list, if it is not empty
maybeLast :: [a] -> Maybe a
maybeLast [] = Nothing
maybeLast xs = Just $ last xs
-- | Joins two parts of the world together, modifying the first element in the
-- second list. The function is what modifies the element (which is itself a
-- list) and is normally either placing or taking an object from the top of
-- the list. Returns Just a new world
joinModified :: Objects -> ([[Id]], [[Id]]) -> ([Id] -> [Id]) -> Maybe [[Id]]
joinModified _ ([], []) _ = Nothing
joinModified _ (_, []) _ = Nothing
joinModified objs (xs, y:ys) f = case val objs (f y) of
Nothing -> Nothing
Just y' -> Just $ xs ++ y':ys
-- | Takes a column and checks if the the two topmost objects are in the correct
-- order. If there are less than two object we assume there can be no conflicts.
val :: Objects -> [Id] -> Maybe [Id]
val objs y' | length y' > 1 = case l y1 of
Nothing -> Nothing
Just y1' -> case l y2 of
Nothing -> Nothing
Just y2' -> if validate y1' y2'
then Just y'
else Nothing
| otherwise = Just y'
where l ys' = M.lookup ys' objs
[y1, y2] = take 2 $ reverse y'
-- | Heuristic defining how good a state is
heuristics :: Goal -> WorldHolding -> Int
heuristics (TakeGoal obj) (w, h) = case obj of
Flr -> error "Take floor goal cannot be assessed"
(Obj _ i) -> case h of
Nothing -> 1 + 2 * fromMaybe (error "object is not in the world")
(idHeight i w)
Just holdingId ->
if i == holdingId
then 0
else 2 + 2 * fromMaybe (error "object is not in the world")
(idHeight i w)
heuristics (MoveGoal Ontop (Obj _ i) Flr) (w,h) = if getFloorSpace w
then case h of
Nothing -> if hght == 0 then 0
else 2 + 2 * oAbove
Just holdingId | i == holdingId -> 1
| hght == 0 -> 0
| otherwise -> 2 + 2 * oAbove
else
case h of
Nothing -> if hght == 0
then 0
else 2 * hght + minimum fs
-- put it down, move the smallest pile and then pick it up and put it on the floor
Just holdingId | i == holdingId -> 3 + minimum fs
-- Is our object already on the floor? good
| hght == 0 -> 0
-- put the holding down, clear the objects above, move the smallest pile
| otherwise -> 3 + 2 * oAbove + minimum fs
where
oAbove = fromMaybe (error "object isn't in the world") (idHeight i w)
hght = fromMaybe (error "planner: where did the object go?") (objPos i w)
fs = makeFloorSpace w
heuristics g@(MoveGoal rel (Obj _ i1) (Obj _ i2)) (w,h) =
if check g (w,h) -- if goal fulfilled, it has to be 0
then 0
else case rel of
Ontop -> let h1 = fromMaybe 0 $ liftM (*2) $ idHeight i1 w
h2 = fromMaybe 0 $ liftM (*2) $ idHeight i2 w
in case h of
Nothing -> 2 + h1 + h2
Just holdingId
| holdingId == i1 -> 1 + h1 + h2 -- put the object down
-- put the holding object down and move object 1 ontop
| otherwise -> 3 + h1 + h2
Inside -> let h1 = fromMaybe 0 $ liftM (*2) $ idHeight i1 w
h2 = fromMaybe 0 $ liftM (*2) $ idHeight i2 w
in case h of
Nothing -> if check g (w,h)
then 0
else 2 + h1 + h2
Just holdingId
| holdingId == i1 -> 1 + h1 + h2 -- put the object down
-- put the holding object down and move object 1 ontop
| otherwise -> 3 + h1 + h2
Beside -> case h of
Nothing -> cheapestCost i1 i2 w
Just holdingId -> if holdingId == i1 || holdingId == i2
then 1
else 2 + cheapestCost i1 i2 w
Leftof -> case h of
Nothing -> cheapestCost i1 i2 w
Just holdingId -> if holdingId == i1 || holdingId == i2
then 1
else 2 + cheapestCost i1 i2 w
Rightof -> case h of
Nothing -> cheapestCost i1 i2 w
Just holdingId -> if holdingId == i1 || holdingId == i2
then 1
else 2 + cheapestCost i1 i2 w
Above -> case h of
Nothing -> cheapestCost i1 i2 w
Just holdingId -> if holdingId == i1 || holdingId == i2
then 1
else 2 + cheapestCost i1 i2 w
Under -> case h of
Nothing -> cheapestCost i1 i2 w
Just holdingId -> if holdingId == i1 || holdingId == i2
then 1
else 2 + cheapestCost i1 i2 w
-- | Returns the cheapest heuristics to move all objects above one of the
-- two given objects.
cheapestCost :: Id -> Id -> World -> Int
cheapestCost i1 i2 w = (*) 2 $ minimum [h1,h2]
where h1 = fromMaybe 1 $ idHeight i1 w
h2 = fromMaybe 1 $ idHeight i2 w
-- | Checks whether there exits an empty floor space.
getFloorSpace :: World -> Bool
getFloorSpace [] = False
getFloorSpace ([]:_) = True
getFloorSpace (_:ws) = getFloorSpace ws
-- | Returns the number of elements in every column.
makeFloorSpace :: World -> [Int]
makeFloorSpace [] = error "Planner.makeFloorSpace: World seems to be empty"
makeFloorSpace [w] = [length w]
makeFloorSpace (w:ws) = 2 * length w : makeFloorSpace ws
-- | Returns the column a given object exists in.
clmn :: Int -> Id -> World -> Maybe Int
clmn _ _ [] = Nothing
clmn row i (w:ws) = case L.elemIndex i w of
Nothing -> clmn (row+1) i ws
Just _ -> return row
-- | Gives an int for how far down the object is
idHeight :: Id -> World -> Maybe Int
idHeight _ [] = Nothing
idHeight i (w:ws) = case idHeight' i w of
Nothing -> idHeight i ws
mVal -> mVal
-- | A helper function to idHeight which returns the number of objects above a
-- given object if it exits.
idHeight' :: Id -> [Id] -> Maybe Int
idHeight' i ws = case L.elemIndex i ws of
Nothing -> Nothing
Just index -> return $ (length ws - 1) - index
-- | Returns an objects height in a column where 0 is the bottom.
objPos :: Id -> World -> Maybe Int
objPos _ [] = Nothing
objPos i (w:ws) = case L.elemIndex i w of
Nothing -> objPos i ws
Just index -> return index
-- | Checks if the first object is over the second.
isOver :: Id -- ^ Object above
-> Id -- ^ Object below
-> Bool -- ^ Should the object be just above?
-> World -- ^ World to look in
-> Bool
isOver _ _ _ [] = False
isOver i1 i2 above (w:ws) = case L.elemIndex i1 w of
Nothing -> isOver i1 i2 above ws
Just index1 -> case L.elemIndex i2 w of
Nothing -> False
Just index2 -> let d = index1 - index2
in if above then d == 1
else d > 0
-- | Checks if the goal is fulfilled in the provided state
check :: Goal -> WorldHolding -> Bool
check goal (w, h) = case goal of
TakeGoal Flr -> error "Take floor goal cannot be assessed"
TakeGoal (Obj _ i) -> case h of
Nothing -> False
Just holdingId -> i == holdingId
MoveGoal Ontop (Obj _ i) Flr -> case objPos i w of
Just height -> height == 0
Nothing -> False
MoveGoal rel (Obj _ i1) (Obj _ i2) -> case rel of
Ontop -> isOver i1 i2 True w
Inside -> isOver i1 i2 True w
Beside -> isBeside i1 i2 w
Leftof -> let c1 = fromMaybe (-1) $ clmn 0 i1 w
c2 = fromMaybe (-1) $ clmn 0 i2 w
in (c1 /= (-1) && c2 /= (-1)) && c1 < c2
Rightof -> let c1 = fromMaybe (-1) $ clmn 0 i1 w
c2 = fromMaybe (-1) $ clmn 0 i2 w
in ((c1 /= (-1) && c2 /= (-1)) && c1 > c2)
Above -> isOver i1 i2 False w
Under -> isOver i2 i1 False w
MoveGoal {} -> error "MoveGoal not fully implemented yet"
-- | Checks if the second object is in the column strictly beside the first
-- objects column.
isBeside :: Id -> Id -> World -> Bool
isBeside _ _ [] = False
isBeside _ _ [_] = False
isBeside i1 i2 (w:v:ws) = if isHere i1 i2 w
then isHere i1 i2 v
else isBeside i1 i2 (v:ws)
where
isHere _ _ [] = False
isHere i j (o:os) = (i == o || j == o) || isHere i j os
| chip2n/tin172-project | haskell/src/Shrdlite/Planner.hs | gpl-3.0 | 11,789 | 0 | 21 | 4,157 | 3,816 | 1,947 | 1,869 | 219 | 29 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE RecordWildCards #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Routes.Utils where
import Prelude as P
import Pusher.Options
import Html
import Types
import UserOps
import Session
import Aws.S3.Core
import System.FilePath
import System.Directory (getCurrentDirectory, getTemporaryDirectory)
import Web.Scotty.Trans hiding (get, post)
import Network.HTTP.Types.Status
import Network.HTTP.Client
import Network.Wai
import Control.Concurrent.STM
import Control.Monad (when)
import Control.Monad.Trans.Reader
import Control.Monad.IO.Class (liftIO)
import Data.String (fromString,IsString)
import Data.Time.Clock
import Data.Configurator as DC
import Data.Text as T
import Data.Text.IO (writeFile)
--import Text.Blaze
import qualified Text.Blaze.Html5 as H
import qualified Web.Scotty.Trans as WST
import qualified Control.Monad.Morph as MT
import qualified Data.ByteString.Char8 as B
import qualified Data.Text.Lazy as LT
import qualified Data.Map.Strict as M
--------------------------------------------------------------------------------
-- Route helpers
--------------------------------------------------------------------------------
newUniqueId :: ActionP UniqueId
newUniqueId = do
uidVar <- MT.lift $ asks pNextID
uid <- liftIO $ atomically $ readTVar uidVar
liftIO $ atomically $ modifyTVar' uidVar succ
return uid
getTasksVar :: ActionP TasksVar
getTasksVar = MT.lift $ asks pTasks
getManager :: ActionP Manager
getManager = MT.lift $ asks pMngr
getUsers :: ActionP Users
getUsers = do
uvar <- MT.lift $ asks pUsersVar
liftIO $ atomically $ readTVar uvar
getCredsFor :: Text -> B.ByteString -> Bucket -> ActionP (Maybe AwsCreds)
getCredsFor name pass bucket = do
users <- MT.lift $ asks pUsersVar
liftIO $ atomically $ (getAwsCreds name pass bucket) <$> readTVar users
findUser :: UserName -> ActionP (Maybe UserDetail)
findUser name = do
muser <- getUser
users <- getUsers
let op = do thatUser <- M.lookup name users
thisUser <- muser
if userLevel thatUser > userLevel thisUser || userName thatUser == name
then return thatUser
else fail ""
return op
flushLogToDisk :: ActionP ()
flushLogToDisk = do
utc <- liftIO getCurrentTime
cwd <- liftIO getCurrentDirectory
var <- MT.lift $ asks pLogVar
-- Get our log file.
cfg <- MT.lift $ asks pConfig
logFile <- liftIO (DC.lookupDefault "log" cfg "log-file" :: IO String)
let lfp = if P.head logFile == '/'
then logFile
else cwd </> logFile
Log lg <- liftIO $ atomically $ readTVar var
let fn = P.unwords [lfp, "-", show utc]
liftIO $ do Data.Text.IO.writeFile fn $ T.pack $ show lg
atomically $ modifyTVar' var (const $ Log [])
saveDataToDisk :: ActionP ()
saveDataToDisk = do
cfg <- MT.lift $ asks pConfig
saveFile <- liftIO $ DC.lookupDefault "save.txt" cfg "save-file"
users <- getUsers
cfdsVar <- MT.lift $ asks pCFDistros
cfds <- liftIO $ atomically $ readTVar cfdsVar
let save = SaveState users cfds
liftIO $ do Data.Text.IO.writeFile saveFile $ T.pack $ show save
log_ :: Text -> ActionP ()
log_ path = do
utc <- liftIO getCurrentTime
ps <- params
musr <- getUser
let ps' = P.map nullpass ps
nullpass (k,v) = if k `elem` hides then (k,"***") else (k, v)
hides = ["pass","authpass","key","secret"]
usr = maybe ("guest") userName musr
entry = LogEntry usr utc ps' path
var <- MT.lift $ asks pLogVar
Log lg <- liftIO $ atomically $ readTVar var
when (P.length lg >= 1000) flushLogToDisk
liftIO $ atomically $ modifyTVar' var $ \(Log lg') -> Log (entry:lg')
get :: Url -> ActionP () -> ScottyP ()
get url f = WST.get (fromString $ show url) $ log_ (T.pack $ show url) >> f
post :: Url -> ActionP () -> ScottyP ()
post url f = WST.post (fromString $ show url) $ log_ (T.pack $ show url) >> f
optionalParam :: Parsable a
=> LT.Text -> ActionP (Maybe a)
optionalParam x = (fmap Just $ param x) `rescue` (const $ return Nothing)
defaultParam :: Parsable a
=> LT.Text -> a -> ActionP a
defaultParam x def = do
mP <- optionalParam x
return $ case mP of
Nothing -> def
Just pm -> pm
redirectToLogin :: ActionP ()
redirectToLogin = do
path <- T.unpack . T.append "/" . T.intercalate "/" . pathInfo <$> request
redirect $ LT.pack $ show $ Uri UrlUserLogin [("r", path)]
withAuthdNamePass :: UserName -> B.ByteString -> (UserDetail -> ActionP ()) -> ActionP ()
withAuthdNamePass authname authpass f = do
users <- getUsers
let authd = getUserIsValid authname authpass users
if not authd
then redirectToLogin
else case M.lookup authname users of
Nothing -> redirectToLogin
Just u -> writeLoginCookie u >> f u
withAuthdUser :: (UserDetail -> ActionP ()) -> ActionP ()
withAuthdUser f = do
mu <- getUser
case mu of
Nothing -> redirectToLogin
Just u -> writeLoginCookie u >> f u
withAuthLvl :: Int -> ActionP () -> ActionP ()
withAuthLvl lvl f = withAuthdUser $ \UserDetail{..} -> do
if userLevel <= lvl then f
else do status unauthorized401
blaze $ guestContainer $ H.div "unauthorized 401"
getUser :: ActionP (Maybe UserDetail)
getUser = do
mcook <- readUserCookie
users <- getUsers
case mcook of
Just (UserCookie UserDetail{..} _) -> return $ M.lookup userName users
Nothing -> do mname <- optionalParam "authname"
mpass <- optionalParam "authpass"
let mnp = (,) <$> mname <*> mpass
case mnp of
Nothing -> return Nothing
Just (n,p) -> return $ if getUserIsValid n p users
then M.lookup n users
else fail ""
saveUser :: UserDetail -> ActionP (Either String ())
saveUser u@UserDetail{..} = do
uv <- MT.lift $ asks pUsersVar
us <- liftIO $ atomically $ readTVar uv
case M.lookup userName us of
Nothing -> return $ Left $ "Could not find user " ++ T.unpack userName
Just _ -> do liftIO $ atomically $ modifyTVar' uv $ M.insert userName u
saveDataToDisk
return $ Right ()
getCloudfrontDistroForBucket :: Bucket -> ActionP (Maybe Text)
getCloudfrontDistroForBucket b = do
cfdsVar <- MT.lift $ asks pCFDistros
cfds <- liftIO $ atomically $ readTVar cfdsVar
case M.lookup b cfds of
Nothing -> return Nothing
Just "" -> return Nothing
Just a -> return $ Just a
getHtmlContainer :: ActionP (H.Html -> H.Html)
getHtmlContainer = do
mu <- getUser
return $ maybe guestContainer (const userContainer) mu
getDefaultCreds :: ActionP (Maybe AwsCreds)
getDefaultCreds = do
muser <- getUser
case muser of
Nothing -> return Nothing
Just (UserDetail{..}) -> do bucket <- param "bucket"
getCredsFor userName userPass bucket
withDefaultCreds :: (AwsCreds -> ActionP ()) -> ActionP ()
withDefaultCreds f = do
mcreds <- getDefaultCreds
case mcreds of
Nothing -> redirectToLogin
Just c -> f c
withCredsFor :: Text -> B.ByteString -> Bucket -> (AwsCreds -> ActionP ())
-> ActionP ()
withCredsFor name pass bucket f = do
mc <- getCredsFor name pass bucket
case mc of
Nothing -> return ()
Just c -> f c
instance Parsable CannedAcl where
parseParam = maybe (Left "Not a valid canned ACL")
Right . readAcl . LT.unpack
nothingIfNull :: (IsString a, Eq a)
=> Maybe a -> Maybe a
nothingIfNull m = case m of
Nothing -> Nothing
Just "" -> Nothing
Just b -> Just b
withStaticDir :: (String -> ActionP a) -> ActionP a
withStaticDir f = do
cfg <- MT.lift $ asks pConfig
dir <- liftIO $ do cwd <- getCurrentDirectory
lookupDefault (cwd ++ "/static") cfg "static-dir"
f dir
getTempDir :: ActionP FilePath
getTempDir = do
cfg <- MT.lift $ asks pConfig
tmp <- liftIO $ do tmp <- getTemporaryDirectory
lookupDefault tmp cfg "tmp-dir"
return tmp
showS3Error :: S3Error -> ActionP ()
showS3Error err = do
status status500
blaze $ userContainer $ H.toHtml err
| schell/pusher | src/Routes/Utils.hs | gpl-3.0 | 8,791 | 0 | 18 | 2,371 | 2,871 | 1,408 | 1,463 | 221 | 4 |
-- |Simple module for controlling DMX. This doesn't
-- check all errors, like writing over headers with
-- negative addresses.
module DMX where
import Data.Bits
import Data.Word
import System.IO
import Data.Array.IO
data Bus = Bus {
devH :: Handle
, states :: IOUArray Int Word8
}
busChans = 512 :: Int -- Channels on bus.
dataLength = busChans + 5 -- Header included.
label = 6 -- Mystical constant.
firstChan = 4 -- Byte offset of first channel.
-- |Opens DMX device initializes DMX data structure. |in DMX data
-- structure. Initial table is given as a plain 8-bit array.
--createBus :: FilePath -> [Word8] -> IO Bus
createBus device initial = do
-- Opens DMX device.
h <- openFile device WriteMode
-- Every channel is 0 by default.
arr <- newArray (0,dataLength-1) 0
-- First 2 bytes.
writeArray arr 0 0x7e
writeArray arr 1 label
-- Write bus channel count in little-endian format. Array contains
-- Word8 elements, therefore .&. 0xff is done automatically.
writeArray arr 2 $ fromIntegral busChans
writeArray arr 3 $ fromIntegral (shiftR busChans 8)
-- Writes terminating byte.
writeArray arr (dataLength-1) 0xe7
-- Fill in initial values.
let bus = Bus h arr
mapM_ (uncurry $ setChannel bus) initial
-- Send initial content
sendDMX bus
return bus
closeBus :: Bus -> IO ()
closeBus bus = do
hClose $ devH bus
sendDMX :: Bus -> IO ()
sendDMX bus = do
hPutArray (devH bus) (states bus) dataLength
--setChannel :: (MArray IOUArray Word8 m) => Bus -> Int -> Word8 -> m ()
setChannel bus channel value = do
writeArray (states bus) (channel+firstChan) value
| zouppen/valo | DMX.hs | gpl-3.0 | 1,671 | 0 | 10 | 382 | 371 | 190 | 181 | 32 | 1 |
{- |
Module : Tct.Encoding.Polynomial
Copyright : (c) Martin Avanzini <[email protected]>,
Georg Moser <[email protected]>,
Andreas Schnabl <[email protected]>
License : LGPL (see COPYING)
Maintainer : Andreas Schnabl <[email protected]>
Stability : unstable
Portability : unportable
-}
{-# LANGUAGE DeriveDataTypeable #-}
module Tct.Encoding.Polynomial where
import qualified Data.List as List
import Data.Typeable
import Qlogic.Semiring
newtype Polynomial a b = Poly [Monomial a b]
deriving (Eq, Ord, Show, Typeable)
data Monomial a b = Mono b [Power a]
deriving (Eq, Ord, Show, Typeable)
data Power a = Pow a Int
deriving (Eq, Ord, Show, Typeable)
getCoeff :: (Eq a, Semiring b) => [Power a] -> Polynomial a b -> b
getCoeff _ (Poly []) = zero
getCoeff v (Poly (Mono n w:ms)) | powsEq v w = n `plus` getCoeff v (Poly ms)
| otherwise = getCoeff v $ Poly ms
getFirstCoeff :: Eq a => [Power a] -> Polynomial a b -> Maybe b
getFirstCoeff _ (Poly []) = Nothing
getFirstCoeff v (Poly (Mono n w:ms)) | powsEq v w = Just n
| otherwise = getFirstCoeff v $ Poly ms
deleteCoeff :: Eq a => [Power a] -> Polynomial a b -> Polynomial a b
deleteCoeff _ (Poly []) = Poly []
deleteCoeff v (Poly (Mono n w:ms)) | powsEq v w = Poly subresult
| otherwise = Poly $ Mono n w:subresult
where Poly subresult = deleteCoeff v $ Poly ms
deleteFirstCoeff :: Eq a => [Power a] -> Polynomial a b -> Polynomial a b
deleteFirstCoeff _ (Poly []) = Poly []
deleteFirstCoeff v (Poly (Mono n w:ms)) | powsEq v w = Poly ms
| otherwise = Poly $ Mono n w:subresult
where Poly subresult = deleteFirstCoeff v $ Poly ms
splitFirstCoeff :: Eq a => [Power a] -> Polynomial a b -> (Maybe b, Polynomial a b)
splitFirstCoeff _ (Poly []) = (Nothing, Poly [])
splitFirstCoeff v (Poly (Mono n w:ms)) | powsEq v w = (Just n, Poly ms)
| otherwise = (subres, Poly $ Mono n w:subpoly)
where (subres, Poly subpoly) = splitFirstCoeff v $ Poly ms
powsEq :: Eq a => [Power a] -> [Power a] -> Bool
powsEq [] [] = True
powsEq [] _ = False
powsEq (v:vs) ws | v `elem` ws = powsEq vs $ List.delete v ws
| otherwise = False
pplus :: (Eq a, Eq b, Semiring b) => Polynomial a b -> Polynomial a b -> Polynomial a b
pplus (Poly xs) (Poly ys) = shallowSimp $ Poly $ xs ++ ys
bigPplus :: (Eq a, Eq b, Semiring b) => [Polynomial a b] -> Polynomial a b
bigPplus = shallowSimp . Poly . concat . map (\(Poly p) -> p)
shallowSimp :: (Eq a, Eq b, Semiring b) => Polynomial a b -> Polynomial a b
shallowSimp (Poly []) = Poly []
shallowSimp (Poly (Mono n _ :ms)) | n == zero = shallowSimp $ Poly ms
shallowSimp (Poly (Mono n xs:ms)) | otherwise = Poly $ (Mono (foldl addcoeff n xss) xs):subresult
where (xss, yss) = List.partition (\(Mono _ xs') -> xs == xs') ms
addcoeff x (Mono y _) = x `plus` y
Poly subresult = shallowSimp $ Poly yss
unEmpty :: Semiring b => Polynomial a b -> Polynomial a b
unEmpty (Poly []) = constToPoly zero
unEmpty p = p
pprod :: (Eq a, Eq b, Semiring b) => Polynomial a b -> Polynomial a b -> Polynomial a b
pprod (Poly xs) p = bigPplus $ map (\x -> pmprod x p) xs
bigPprod :: (Eq a, Eq b, Semiring b) => [Polynomial a b] -> Polynomial a b
bigPprod = foldr pprod $ constToPoly one
pmprod :: (Eq a, Semiring b) => Monomial a b -> Polynomial a b -> Polynomial a b
pmprod m (Poly ns) = Poly $ map (\n -> mprod m n) ns
mprod :: (Eq a, Semiring b) => Monomial a b -> Monomial a b -> Monomial a b
mprod (Mono m xs) (Mono n ys) = simpMono $ Mono (m `prod` n) (xs ++ ys)
cpprod :: Semiring b => b -> Polynomial a b -> Polynomial a b
cpprod n (Poly xs) = Poly $ map (cmprod n) xs
cmprod :: Semiring b => b -> Monomial a b -> Monomial a b
cmprod n (Mono m vs) = Mono (n `prod` m) vs
simpMono :: Eq a => Monomial a b -> Monomial a b
simpMono (Mono n xs) = Mono n $ simpPower xs
simpPower :: Eq a => [Power a] -> [Power a]
simpPower [] = []
simpPower ((Pow _ n):xs) | n == 0 = simpPower xs
simpPower ((Pow v n):xs) | otherwise = (Pow v (foldl addpow n xss):(simpPower yss))
where (xss, yss) = List.partition isRightPow xs
isRightPow (Pow w _) = v == w
addpow x (Pow _ y) = x + y
varToPoly :: Semiring b => a -> Polynomial a b
varToPoly v = Poly [Mono one [Pow v 1]]
constToPoly :: b -> Polynomial a b
constToPoly n = Poly [Mono n []]
| mzini/TcT | source/Tct/Encoding/Polynomial.hs | gpl-3.0 | 5,000 | 0 | 11 | 1,632 | 2,186 | 1,075 | 1,111 | 78 | 1 |
{-# LANGUAGE CPP, PackageImports #-}
#if __GLASGOW_HASKELL__ >= 701
{-# LANGUAGE Trustworthy #-}
#endif
module Data.Array (
-- * Immutable non-strict arrays
-- $intro
module Data.Ix -- export all of Ix
, Array -- Array type is abstract
-- * Array construction
, array -- :: (Ix a) => (a,a) -> [(a,b)] -> Array a b
, listArray -- :: (Ix a) => (a,a) -> [b] -> Array a b
, accumArray -- :: (Ix a) => (b -> c -> b) -> b -> (a,a) -> [(a,c)] -> Array a b
-- * Accessing arrays
, (!) -- :: (Ix a) => Array a b -> a -> b
, bounds -- :: (Ix a) => Array a b -> (a,a)
, indices -- :: (Ix a) => Array a b -> [a]
, elems -- :: (Ix a) => Array a b -> [b]
, assocs -- :: (Ix a) => Array a b -> [(a,b)]
-- * Incremental array updates
, (//) -- :: (Ix a) => Array a b -> [(a,b)] -> Array a b
, accum -- :: (Ix a) => (b -> c -> b) -> Array a b -> [(a,c)] -> Array a b
-- * Derived arrays
, ixmap -- :: (Ix a, Ix b) => (a,a) -> (a -> b) -> Array b c -> Array a b
-- * Specification
-- $code
) where
import qualified "array" Data.Array as Array
import "array" Data.Array hiding (array, (//))
import "base" Data.Ix
{- $intro
Haskell provides indexable /arrays/, which may be thought of as functions
whose domains are isomorphic to contiguous subsets of the integers.
Functions restricted in this way can be implemented efficiently;
in particular, a programmer may reasonably expect rapid access to
the components. To ensure the possibility of such an implementation,
arrays are treated as data, not as general functions.
Since most array functions involve the class 'Ix', the contents of the
module "Data.Ix" are re-exported from "Data.Array" for convenience:
-}
-- SDM: copied documentation for 'array' to remove GHC reference
-- | Construct an array with the specified bounds and containing values
-- for given indices within these bounds.
--
-- The array is undefined (i.e. bottom) if any index in the list is
-- out of bounds. If any
-- two associations in the list have the same index, the value at that
-- index is undefined (i.e. bottom).
--
-- Because the indices must be checked for these errors, 'array' is
-- strict in the bounds argument and in the indices of the association
-- list, but non-strict in the values. Thus, recurrences such as the
-- following are possible:
--
-- > a = array (1,100) ((1,1) : [(i, i * a!(i-1)) | i <- [2..100]])
--
-- Not every index within the bounds of the array need appear in the
-- association list, but the values associated with indices that do not
-- appear will be undefined (i.e. bottom).
--
-- If, in any dimension, the lower bound is greater than the upper bound,
-- then the array is legal, but empty. Indexing an empty array always
-- gives an array-bounds error, but 'bounds' still yields the bounds
-- with which the array was constructed.
array :: Ix i
=> (i,i) -- ^ a pair of /bounds/, each of the index type
-- of the array. These bounds are the lowest and
-- highest indices in the array, in that order.
-- For example, a one-origin vector of length
-- '10' has bounds '(1,10)', and a one-origin '10'
-- by '10' matrix has bounds '((1,1),(10,10))'.
-> [(i, e)] -- ^ a list of /associations/ of the form
-- (/index/, /value/). Typically, this list will
-- be expressed as a comprehension. An
-- association '(i, x)' defines the value of
-- the array at index 'i' to be 'x'.
-> Array i e
array = Array.array
-- SDM copied docs for (//) to remove GHC reference
-- | Constructs an array identical to the first argument except that it has
-- been updated by the associations in the right argument.
-- For example, if @m@ is a 1-origin, @n@ by @n@ matrix, then
--
-- > m//[((i,i), 0) | i <- [1..n]]
--
-- is the same matrix, except with the diagonal zeroed.
--
-- Repeated indices in the association list are handled as for 'array':
-- the resulting array is undefined (i.e. bottom),
(//) :: Ix i => Array i e -> [(i, e)] -> Array i e
(//) = (Array.//)
{- $code
> module Array (
> module Data.Ix, -- export all of Data.Ix
> Array, array, listArray, (!), bounds, indices, elems, assocs,
> accumArray, (//), accum, ixmap ) where
>
> import Data.Ix
> import Data.List( (\\) )
>
> infixl 9 !, //
>
> data (Ix a) => Array a b = MkArray (a,a) (a -> b) deriving ()
>
> array :: (Ix a) => (a,a) -> [(a,b)] -> Array a b
> array b ivs
> | any (not . inRange b. fst) ivs
> = error "Data.Array.array: out-of-range array association"
> | otherwise
> = MkArray b arr
> where
> arr j = case [ v | (i,v) <- ivs, i == j ] of
> [v] -> v
> [] -> error "Data.Array.!: undefined array element"
> _ -> error "Data.Array.!: multiply defined array element"
>
> listArray :: (Ix a) => (a,a) -> [b] -> Array a b
> listArray b vs = array b (zipWith (\ a b -> (a,b)) (range b) vs)
>
> (!) :: (Ix a) => Array a b -> a -> b
> (!) (MkArray _ f) = f
>
> bounds :: (Ix a) => Array a b -> (a,a)
> bounds (MkArray b _) = b
>
> indices :: (Ix a) => Array a b -> [a]
> indices = range . bounds
>
> elems :: (Ix a) => Array a b -> [b]
> elems a = [a!i | i <- indices a]
>
> assocs :: (Ix a) => Array a b -> [(a,b)]
> assocs a = [(i, a!i) | i <- indices a]
>
> (//) :: (Ix a) => Array a b -> [(a,b)] -> Array a b
> a // new_ivs = array (bounds a) (old_ivs ++ new_ivs)
> where
> old_ivs = [(i,a!i) | i <- indices a,
> i `notElem` new_is]
> new_is = [i | (i,_) <- new_ivs]
>
> accum :: (Ix a) => (b -> c -> b) -> Array a b -> [(a,c)]
> -> Array a b
> accum f = foldl (\a (i,v) -> a // [(i,f (a!i) v)])
>
> accumArray :: (Ix a) => (b -> c -> b) -> b -> (a,a) -> [(a,c)]
> -> Array a b
> accumArray f z b = accum f (array b [(i,z) | i <- range b])
>
> ixmap :: (Ix a, Ix b) => (a,a) -> (a -> b) -> Array b c
> -> Array a c
> ixmap b f a = array b [(i, a ! f i) | i <- range b]
>
> instance (Ix a) => Functor (Array a) where
> fmap fn (MkArray b f) = MkArray b (fn . f)
>
> instance (Ix a, Eq b) => Eq (Array a b) where
> a == a' = assocs a == assocs a'
>
> instance (Ix a, Ord b) => Ord (Array a b) where
> a <= a' = assocs a <= assocs a'
>
> instance (Ix a, Show a, Show b) => Show (Array a b) where
> showsPrec p a = showParen (p > arrPrec) (
> showString "array " .
> showsPrec (arrPrec+1) (bounds a) . showChar ' ' .
> showsPrec (arrPrec+1) (assocs a) )
>
> instance (Ix a, Read a, Read b) => Read (Array a b) where
> readsPrec p = readParen (p > arrPrec)
> (\r -> [ (array b as, u)
> | ("array",s) <- lex r,
> (b,t) <- readsPrec (arrPrec+1) s,
> (as,u) <- readsPrec (arrPrec+1) t ])
>
> -- Precedence of the 'array' function is that of application itself
> arrPrec = 10
-}
| jwiegley/ghc-release | libraries/haskell2010/Data/Array.hs | gpl-3.0 | 7,705 | 0 | 9 | 2,614 | 258 | 189 | 69 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
{- Parser.hs
Reads the components of a reaction system from string.
Copyright 2014 by Sergiu Ivanov <[email protected]>
This file is part of brsim.
brsim 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.
brsim is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
-}
module Parser ( readSymbols
, readPlusSymbols
, readSpaceSymbols
, readPlainReaction
, readArrowReaction
, readPlainReactions
, readArrowReactions
, readListOfListsOfSymbols
) where
import ReactionSystems
import qualified Data.Text.Lazy as Text
import qualified Data.Set as Set
-- Strips leading and trailing whitespace from all texts in the
-- supplied list and discards the empty elements afterwards.
stripFilter :: [Text.Text] -> [Text.Text]
stripFilter = filter (not . Text.null) . map Text.strip
-- Removes symbols with dots as their names. Such symbols stand for
-- the empty set.
dropEmpty :: [Symbol] -> [Symbol]
dropEmpty = filter ((/=) "." . name)
-- | Parses a list of symbols (second argument) separated by the given
-- sequence of symbols (first argument).
readSymbols :: Text.Text -> Text.Text -> Symbols
readSymbols sep = Set.fromList . dropEmpty . map (Symbol . Text.unpack) . stripFilter . Text.splitOn sep
-- | Parses a plus-separated list of symbols.
readPlusSymbols = readSymbols "+"
-- | Parses a space-separated list of symbols.
readSpaceSymbols = readSymbols " "
-- | Parses a reaction in plain format. A reaction which consumes
-- symbols 'a' and 'b', produces 'c' and 'd', and is inhibited by 'e'
-- and 'f' is written as follows: a b, e f, c d.
readPlainReaction :: Text.Text -> Reaction
readPlainReaction txt = let parts = Text.splitOn "," txt
[rcts, inh, prods] = map readSpaceSymbols parts
in Reaction rcts inh prods
-- | Parses a reaction in arrow format. A reaction which consumes
-- symbols 'a' and 'b', produces 'c' and 'd', and is inhibited by 'e'
-- and 'f' is written as follows: a+b -> c+d|e f.
readArrowReaction :: Text.Text -> Reaction
readArrowReaction txt =
let (txtRcts, rest) = Text.breakOn "->" txt
(txtProds, txtInh) = Text.breakOn "|" $ Text.drop 2 rest
rcts = readPlusSymbols txtRcts
prods = readPlusSymbols txtProds
inh = if not $ Text.null txtInh
then readSpaceSymbols $ Text.tail txtInh
else Set.empty
in Reaction rcts inh prods
-- Splits the supplied text (third argument) into lines, throws away
-- the lines for which the filtering function (first argument) is
-- true, and applies the processing function (second argument) to the
-- remaining lines.
--
-- This function will also discard whitespace lines.
mapGoodLines :: (Text.Text -> Bool) -> (Text.Text -> a) -> Text.Text -> [a]
mapGoodLines flt func = map func . filter (not . flt) . stripFilter . Text.lines
commentLine = Text.isPrefixOf "#"
-- | Reads a list of reactions in plain format. Reactions are given
-- one per line. Whitespace lines and lines starting with the hash
-- symbol are discarded.
readPlainReactions :: Text.Text -> [Reaction]
readPlainReactions = mapGoodLines commentLine readPlainReaction
-- | Reads a list of reactions in arrow format. Reactions are given
-- one per line. Whitespace lines and lines starting with the hash
-- symbol are discarded.
readArrowReactions :: Text.Text -> [Reaction]
readArrowReactions = mapGoodLines commentLine readArrowReaction
-- | Reads a list of lists of symbol. Lists of symbols are given one
-- per line. Whitespace lines and lines starting with the hash symbol
-- are discarded.
readListOfListsOfSymbols :: Text.Text -> [Symbols]
readListOfListsOfSymbols = mapGoodLines commentLine readSpaceSymbols
| scolobb/brsim | Parser.hs | gpl-3.0 | 4,310 | 0 | 12 | 891 | 588 | 328 | 260 | 43 | 2 |
{-# LANGUAGE OverloadedStrings #-}
module Prompt where
import Control.Concurrent
import Control.Monad (forever, when, unless)
import Data.List (nub)
import Data.IORef
import qualified Data.Text.IO as T.IO
import System.IO
import Cards
import Simulate
handleSetting :: IO ()
handleSetting = do
putStr "Input cards as a comma-separated list in shorthand notation."
putStrLn " (example: Ah,Th,5h)\n"
bottom' <- promptCards "Your Bottom row: "
middle' <- promptCards "Your Middle row: "
top' <- promptCards "Your Top row: "
oppBottom <- promptCards "Opponent's Bottom row: "
oppMiddle <- promptCards "Opponent's Middle row: "
oppTop <- promptCards "Opponent's Top row: "
card <- promptCard "Card you are about to play: "
let p1 = Player bottom' middle' top'
let p2 = Player oppBottom oppMiddle oppTop
if validate p1 p2 card
then giveEVs p1 p2 card
else putStrLn "Not a valid setting. Did you reuse a card? Try again."
return ()
promptCards :: String -> IO [Card]
promptCards txt = do
putStr txt
gotTxt <- T.IO.getLine
let cards = parseCards gotTxt
maybe (do
putStrLn "Not a valid list of cards. Try again."
promptCards txt)
return cards
promptCard :: String -> IO Card
promptCard txt = do
putStr txt
gotTxt <- T.IO.getLine
maybe (do
putStrLn "Not a valid card. Try again."
promptCard txt)
return (parseCard gotTxt)
validate :: Player -> Player -> Card -> Bool
validate (Player b1 m1 t1) (Player b2 m2 t2) c =
cards == nub cards
where cards = c:(b1 ++ m1 ++ t1 ++ b2 ++ m2 ++ t2)
--counts
--Number of simulations to run, consider increasing to 1-2 million
--after optimization for more stable results
sims :: Int
sims = 200000
giveEVs :: Player -> Player -> Card -> IO ()
giveEVs (Player b1 m1 t1) p2 c = do
putStrLn ""
done <- newIORef (3 :: Int)
when (length b1 < 5) $
do res <- simulate (Player b1' m1 t1) p2 sims
printResult "Bottom: " res
when (length m1 < 5) $
do res <- simulate (Player b1 m1' t1) p2 sims
printResult "Middle: " res
when (length t1 < 3) $
do res <- simulate (Player b1 m1 t1') p2 sims
printResult "Top: " res
areWeDone done
where printResult str f = putStrLn $ str ++ show f
b1' = c:b1
m1' = c:m1
t1' = c:t1
areWeDone y = readIORef y >>= \x -> unless (x == 3) (areWeDone y)
| dtrifuno/holz | src/Prompt.hs | gpl-3.0 | 2,359 | 0 | 13 | 556 | 790 | 378 | 412 | 69 | 2 |
-- This file is part of KSQuant2.
-- Copyright (c) 2010 - 2011, Kilian Sprotte. All rights reserved.
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
module Lily (showLily
, Score
, Part
, Voice
, Dur(..)
, Elt(..)
, Measure(..)
, Measures
, Name(..)
, Accidental(..)
, Pitch(..)
, powerToSimpleDur)
where
import qualified Types as T (WInt, WRat)
import Data.Ratio ((%), denominator)
import Data.List (intercalate)
import qualified AbstractScore as A (Score
, Part
, Voice
, scoreParts
, partVoices
, voiceItems)
data Measure = Measure Int Int [Elt]
deriving Show
type Score = A.Score Measures
type Part = A.Part Measures
type Voice = A.Voice Measures
type Measures = [Measure]
-- | This represents durations without dot.
data SimpleDur = D1 | D2 | D4 | D8 | D16 | D32 | D64 | D128
deriving (Show,Enum)
-- | 1 / 2^n
powerToSimpleDur :: Int -> SimpleDur
powerToSimpleDur = toEnum
data Dur = Dur SimpleDur Int
deriving Show
type Tied = Bool
type Octave = T.WInt
data Name = A | B | C | D | E | F | G
deriving Show
data Accidental = Natural | Sharp | Flat
deriving Show
data Pitch = Pitch Name Accidental Octave
deriving Show
data Elt = Chord Dur [Pitch] Tied
| Rest Dur
| Times Int Int [Elt]
deriving Show
simpleDurToRatio :: SimpleDur -> T.WRat
simpleDurToRatio x =
case x of
D1 -> 1 % 1
D2 -> 1 % 2
D4 -> 1 % 4
D8 -> 1 % 8
D16 -> 1 % 16
D32 -> 1 % 32
D64 -> 1 % 64
D128 -> 1 % 128
pitchToLily :: Pitch -> String
pitchToLily (Pitch B Natural 3) = "b"
pitchToLily (Pitch C Natural 4) = "c'"
pitchToLily (Pitch C Sharp 4) = "cis'"
pitchToLily (Pitch D Natural 4) = "d'"
pitchToLily (Pitch E Natural 4) = "e'"
pitchToLily (Pitch F Natural 4) = "f'"
pitchToLily p = error $ "pitchToLily not implemented: " ++ show p
durToLily :: Dur -> String
durToLily (Dur x d) = (show . denominator . simpleDurToRatio) x ++ replicate d '.'
eltToLily :: Elt -> String
eltToLily (Chord d ps tie) = "<" ++ ps' ++ ">" ++ durToLily d ++ if tie then " ~" else ""
where ps' = unwords (map pitchToLily ps)
eltToLily (Rest d) = 'r' : durToLily d
eltToLily (Times n d xs) = "\\times " ++ show n ++ "/" ++ show d ++ " { " ++
unwords (map eltToLily xs) ++ " }"
measureToLily :: (Measure, Bool) -> String
measureToLily (Measure n d xs, change) =
(if change then
"\\time " ++ show n ++ "/" ++ show d ++ " "
else "")
++
unwords (map eltToLily xs) ++ " |"
-- | Return a list of equal length as xs indicating if the corresponing
-- elt of xs is different from its predecessor.
indicateChanges :: Eq b => [b] -> [Bool]
indicateChanges xs = True : map (not . uncurry (==)) (zip (drop 1 xs) xs)
measureTimeSignature :: Measure -> (Int, Int)
measureTimeSignature (Measure n d _) = (n,d)
measureChanges :: Measures -> [Bool]
measureChanges xs = indicateChanges (map measureTimeSignature xs)
measuresToLily :: Measures -> String
measuresToLily xs = intercalate "\n " $ zipWith (curry measureToLily) xs (measureChanges xs)
voiceToLily :: Voice -> String
voiceToLily v = "{ " ++ measuresToLily (A.voiceItems v) ++ " }"
wrap :: String -> String
wrap content =
"\\version \"2.12.3\"\n" ++
"\\header { }\n" ++
"\\score {\n" ++
" <<\n " ++
content ++ "\n" ++
" >>\n" ++
" \\layout { }\n" ++
"}\n"
showLily :: Score -> String
showLily s = wrap (intercalate "\n" (map voiceToLily (concatMap A.partVoices (A.scoreParts s))))
| kisp/ksquant2 | Lily.hs | gpl-3.0 | 4,450 | 0 | 14 | 1,305 | 1,231 | 677 | 554 | 101 | 8 |
{-# 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.Slides.Types.Product
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
module Network.Google.Slides.Types.Product where
import Network.Google.Prelude
import Network.Google.Slides.Types.Sum
-- | The autofit properties of a Shape.
--
-- /See:/ 'autofit' smart constructor.
data Autofit =
Autofit'
{ _aFontScale :: !(Maybe (Textual Double))
, _aLineSpacingReduction :: !(Maybe (Textual Double))
, _aAutofitType :: !(Maybe AutofitAutofitType)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Autofit' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'aFontScale'
--
-- * 'aLineSpacingReduction'
--
-- * 'aAutofitType'
autofit
:: Autofit
autofit =
Autofit'
{ _aFontScale = Nothing
, _aLineSpacingReduction = Nothing
, _aAutofitType = Nothing
}
-- | The font scale applied to the shape. For shapes with autofit_type NONE
-- or SHAPE_AUTOFIT, this value is the default value of 1. For
-- TEXT_AUTOFIT, this value multiplied by the font_size gives the font size
-- that is rendered in the editor. This property is read-only.
aFontScale :: Lens' Autofit (Maybe Double)
aFontScale
= lens _aFontScale (\ s a -> s{_aFontScale = a}) .
mapping _Coerce
-- | The line spacing reduction applied to the shape. For shapes with
-- autofit_type NONE or SHAPE_AUTOFIT, this value is the default value of
-- 0. For TEXT_AUTOFIT, this value subtracted from the line_spacing gives
-- the line spacing that is rendered in the editor. This property is
-- read-only.
aLineSpacingReduction :: Lens' Autofit (Maybe Double)
aLineSpacingReduction
= lens _aLineSpacingReduction
(\ s a -> s{_aLineSpacingReduction = a})
. mapping _Coerce
-- | The autofit type of the shape. If the autofit type is
-- AUTOFIT_TYPE_UNSPECIFIED, the autofit type is inherited from a parent
-- placeholder if it exists. The field is automatically set to NONE if a
-- request is made that might affect text fitting within its bounding text
-- box. In this case the font_scale is applied to the font_size and the
-- line_spacing_reduction is applied to the line_spacing. Both properties
-- are also reset to default values.
aAutofitType :: Lens' Autofit (Maybe AutofitAutofitType)
aAutofitType
= lens _aAutofitType (\ s a -> s{_aAutofitType = a})
instance FromJSON Autofit where
parseJSON
= withObject "Autofit"
(\ o ->
Autofit' <$>
(o .:? "fontScale") <*>
(o .:? "lineSpacingReduction")
<*> (o .:? "autofitType"))
instance ToJSON Autofit where
toJSON Autofit'{..}
= object
(catMaybes
[("fontScale" .=) <$> _aFontScale,
("lineSpacingReduction" .=) <$>
_aLineSpacingReduction,
("autofitType" .=) <$> _aAutofitType])
-- | A TextElement kind that represents the beginning of a new paragraph.
--
-- /See:/ 'paragraphMarker' smart constructor.
data ParagraphMarker =
ParagraphMarker'
{ _pmStyle :: !(Maybe ParagraphStyle)
, _pmBullet :: !(Maybe Bullet)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ParagraphMarker' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pmStyle'
--
-- * 'pmBullet'
paragraphMarker
:: ParagraphMarker
paragraphMarker = ParagraphMarker' {_pmStyle = Nothing, _pmBullet = Nothing}
-- | The paragraph\'s style
pmStyle :: Lens' ParagraphMarker (Maybe ParagraphStyle)
pmStyle = lens _pmStyle (\ s a -> s{_pmStyle = a})
-- | The bullet for this paragraph. If not present, the paragraph does not
-- belong to a list.
pmBullet :: Lens' ParagraphMarker (Maybe Bullet)
pmBullet = lens _pmBullet (\ s a -> s{_pmBullet = a})
instance FromJSON ParagraphMarker where
parseJSON
= withObject "ParagraphMarker"
(\ o ->
ParagraphMarker' <$>
(o .:? "style") <*> (o .:? "bullet"))
instance ToJSON ParagraphMarker where
toJSON ParagraphMarker'{..}
= object
(catMaybes
[("style" .=) <$> _pmStyle,
("bullet" .=) <$> _pmBullet])
-- | Deletes a row from a table.
--
-- /See:/ 'deleteTableRowRequest' smart constructor.
data DeleteTableRowRequest =
DeleteTableRowRequest'
{ _dtrrCellLocation :: !(Maybe TableCellLocation)
, _dtrrTableObjectId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'DeleteTableRowRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'dtrrCellLocation'
--
-- * 'dtrrTableObjectId'
deleteTableRowRequest
:: DeleteTableRowRequest
deleteTableRowRequest =
DeleteTableRowRequest'
{_dtrrCellLocation = Nothing, _dtrrTableObjectId = Nothing}
-- | The reference table cell location from which a row will be deleted. The
-- row this cell spans will be deleted. If this is a merged cell, multiple
-- rows will be deleted. If no rows remain in the table after this
-- deletion, the whole table is deleted.
dtrrCellLocation :: Lens' DeleteTableRowRequest (Maybe TableCellLocation)
dtrrCellLocation
= lens _dtrrCellLocation
(\ s a -> s{_dtrrCellLocation = a})
-- | The table to delete rows from.
dtrrTableObjectId :: Lens' DeleteTableRowRequest (Maybe Text)
dtrrTableObjectId
= lens _dtrrTableObjectId
(\ s a -> s{_dtrrTableObjectId = a})
instance FromJSON DeleteTableRowRequest where
parseJSON
= withObject "DeleteTableRowRequest"
(\ o ->
DeleteTableRowRequest' <$>
(o .:? "cellLocation") <*> (o .:? "tableObjectId"))
instance ToJSON DeleteTableRowRequest where
toJSON DeleteTableRowRequest'{..}
= object
(catMaybes
[("cellLocation" .=) <$> _dtrrCellLocation,
("tableObjectId" .=) <$> _dtrrTableObjectId])
-- | The thumbnail of a page.
--
-- /See:/ 'thumbnail' smart constructor.
data Thumbnail =
Thumbnail'
{ _tHeight :: !(Maybe (Textual Int32))
, _tWidth :: !(Maybe (Textual Int32))
, _tContentURL :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Thumbnail' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'tHeight'
--
-- * 'tWidth'
--
-- * 'tContentURL'
thumbnail
:: Thumbnail
thumbnail =
Thumbnail' {_tHeight = Nothing, _tWidth = Nothing, _tContentURL = Nothing}
-- | The positive height in pixels of the thumbnail image.
tHeight :: Lens' Thumbnail (Maybe Int32)
tHeight
= lens _tHeight (\ s a -> s{_tHeight = a}) .
mapping _Coerce
-- | The positive width in pixels of the thumbnail image.
tWidth :: Lens' Thumbnail (Maybe Int32)
tWidth
= lens _tWidth (\ s a -> s{_tWidth = a}) .
mapping _Coerce
-- | The content URL of the thumbnail image. The URL to the image has a
-- default lifetime of 30 minutes. This URL is tagged with the account of
-- the requester. Anyone with the URL effectively accesses the image as the
-- original requester. Access to the image may be lost if the
-- presentation\'s sharing settings change. The mime type of the thumbnail
-- image is the same as specified in the \`GetPageThumbnailRequest\`.
tContentURL :: Lens' Thumbnail (Maybe Text)
tContentURL
= lens _tContentURL (\ s a -> s{_tContentURL = a})
instance FromJSON Thumbnail where
parseJSON
= withObject "Thumbnail"
(\ o ->
Thumbnail' <$>
(o .:? "height") <*> (o .:? "width") <*>
(o .:? "contentUrl"))
instance ToJSON Thumbnail where
toJSON Thumbnail'{..}
= object
(catMaybes
[("height" .=) <$> _tHeight,
("width" .=) <$> _tWidth,
("contentUrl" .=) <$> _tContentURL])
-- | The properties of each border cell.
--
-- /See:/ 'tableBOrderCell' smart constructor.
data TableBOrderCell =
TableBOrderCell'
{ _tbocLocation :: !(Maybe TableCellLocation)
, _tbocTableBOrderProperties :: !(Maybe TableBOrderProperties)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'TableBOrderCell' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'tbocLocation'
--
-- * 'tbocTableBOrderProperties'
tableBOrderCell
:: TableBOrderCell
tableBOrderCell =
TableBOrderCell'
{_tbocLocation = Nothing, _tbocTableBOrderProperties = Nothing}
-- | The location of the border within the border table.
tbocLocation :: Lens' TableBOrderCell (Maybe TableCellLocation)
tbocLocation
= lens _tbocLocation (\ s a -> s{_tbocLocation = a})
-- | The border properties.
tbocTableBOrderProperties :: Lens' TableBOrderCell (Maybe TableBOrderProperties)
tbocTableBOrderProperties
= lens _tbocTableBOrderProperties
(\ s a -> s{_tbocTableBOrderProperties = a})
instance FromJSON TableBOrderCell where
parseJSON
= withObject "TableBOrderCell"
(\ o ->
TableBOrderCell' <$>
(o .:? "location") <*>
(o .:? "tableBorderProperties"))
instance ToJSON TableBOrderCell where
toJSON TableBOrderCell'{..}
= object
(catMaybes
[("location" .=) <$> _tbocLocation,
("tableBorderProperties" .=) <$>
_tbocTableBOrderProperties])
-- | Common properties for a page element. Note: When you initially create a
-- PageElement, the API may modify the values of both \`size\` and
-- \`transform\`, but the visual size will be unchanged.
--
-- /See:/ 'pageElementProperties' smart constructor.
data PageElementProperties =
PageElementProperties'
{ _pepTransform :: !(Maybe AffineTransform)
, _pepSize :: !(Maybe Size)
, _pepPageObjectId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'PageElementProperties' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pepTransform'
--
-- * 'pepSize'
--
-- * 'pepPageObjectId'
pageElementProperties
:: PageElementProperties
pageElementProperties =
PageElementProperties'
{_pepTransform = Nothing, _pepSize = Nothing, _pepPageObjectId = Nothing}
-- | The transform for the element.
pepTransform :: Lens' PageElementProperties (Maybe AffineTransform)
pepTransform
= lens _pepTransform (\ s a -> s{_pepTransform = a})
-- | The size of the element.
pepSize :: Lens' PageElementProperties (Maybe Size)
pepSize = lens _pepSize (\ s a -> s{_pepSize = a})
-- | The object ID of the page where the element is located.
pepPageObjectId :: Lens' PageElementProperties (Maybe Text)
pepPageObjectId
= lens _pepPageObjectId
(\ s a -> s{_pepPageObjectId = a})
instance FromJSON PageElementProperties where
parseJSON
= withObject "PageElementProperties"
(\ o ->
PageElementProperties' <$>
(o .:? "transform") <*> (o .:? "size") <*>
(o .:? "pageObjectId"))
instance ToJSON PageElementProperties where
toJSON PageElementProperties'{..}
= object
(catMaybes
[("transform" .=) <$> _pepTransform,
("size" .=) <$> _pepSize,
("pageObjectId" .=) <$> _pepPageObjectId])
-- | The result of replacing shapes with an image.
--
-- /See:/ 'replaceAllShapesWithImageResponse' smart constructor.
newtype ReplaceAllShapesWithImageResponse =
ReplaceAllShapesWithImageResponse'
{ _raswirOccurrencesChanged :: Maybe (Textual Int32)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ReplaceAllShapesWithImageResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'raswirOccurrencesChanged'
replaceAllShapesWithImageResponse
:: ReplaceAllShapesWithImageResponse
replaceAllShapesWithImageResponse =
ReplaceAllShapesWithImageResponse' {_raswirOccurrencesChanged = Nothing}
-- | The number of shapes replaced with images.
raswirOccurrencesChanged :: Lens' ReplaceAllShapesWithImageResponse (Maybe Int32)
raswirOccurrencesChanged
= lens _raswirOccurrencesChanged
(\ s a -> s{_raswirOccurrencesChanged = a})
. mapping _Coerce
instance FromJSON ReplaceAllShapesWithImageResponse
where
parseJSON
= withObject "ReplaceAllShapesWithImageResponse"
(\ o ->
ReplaceAllShapesWithImageResponse' <$>
(o .:? "occurrencesChanged"))
instance ToJSON ReplaceAllShapesWithImageResponse
where
toJSON ReplaceAllShapesWithImageResponse'{..}
= object
(catMaybes
[("occurrencesChanged" .=) <$>
_raswirOccurrencesChanged])
-- | The fill of the outline.
--
-- /See:/ 'outlineFill' smart constructor.
newtype OutlineFill =
OutlineFill'
{ _ofSolidFill :: Maybe SolidFill
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'OutlineFill' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ofSolidFill'
outlineFill
:: OutlineFill
outlineFill = OutlineFill' {_ofSolidFill = Nothing}
-- | Solid color fill.
ofSolidFill :: Lens' OutlineFill (Maybe SolidFill)
ofSolidFill
= lens _ofSolidFill (\ s a -> s{_ofSolidFill = a})
instance FromJSON OutlineFill where
parseJSON
= withObject "OutlineFill"
(\ o -> OutlineFill' <$> (o .:? "solidFill"))
instance ToJSON OutlineFill where
toJSON OutlineFill'{..}
= object
(catMaybes [("solidFill" .=) <$> _ofSolidFill])
-- | A PageElement kind representing an image.
--
-- /See:/ 'image' smart constructor.
data Image =
Image'
{ _iImageProperties :: !(Maybe ImageProperties)
, _iContentURL :: !(Maybe Text)
, _iSourceURL :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Image' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'iImageProperties'
--
-- * 'iContentURL'
--
-- * 'iSourceURL'
image
:: Image
image =
Image'
{_iImageProperties = Nothing, _iContentURL = Nothing, _iSourceURL = Nothing}
-- | The properties of the image.
iImageProperties :: Lens' Image (Maybe ImageProperties)
iImageProperties
= lens _iImageProperties
(\ s a -> s{_iImageProperties = a})
-- | An URL to an image with a default lifetime of 30 minutes. This URL is
-- tagged with the account of the requester. Anyone with the URL
-- effectively accesses the image as the original requester. Access to the
-- image may be lost if the presentation\'s sharing settings change.
iContentURL :: Lens' Image (Maybe Text)
iContentURL
= lens _iContentURL (\ s a -> s{_iContentURL = a})
-- | The source URL is the URL used to insert the image. The source URL can
-- be empty.
iSourceURL :: Lens' Image (Maybe Text)
iSourceURL
= lens _iSourceURL (\ s a -> s{_iSourceURL = a})
instance FromJSON Image where
parseJSON
= withObject "Image"
(\ o ->
Image' <$>
(o .:? "imageProperties") <*> (o .:? "contentUrl")
<*> (o .:? "sourceUrl"))
instance ToJSON Image where
toJSON Image'{..}
= object
(catMaybes
[("imageProperties" .=) <$> _iImageProperties,
("contentUrl" .=) <$> _iContentURL,
("sourceUrl" .=) <$> _iSourceURL])
-- | Updates the properties of a Line.
--
-- /See:/ 'updateLinePropertiesRequest' smart constructor.
data UpdateLinePropertiesRequest =
UpdateLinePropertiesRequest'
{ _ulprLineProperties :: !(Maybe LineProperties)
, _ulprObjectId :: !(Maybe Text)
, _ulprFields :: !(Maybe GFieldMask)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'UpdateLinePropertiesRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ulprLineProperties'
--
-- * 'ulprObjectId'
--
-- * 'ulprFields'
updateLinePropertiesRequest
:: UpdateLinePropertiesRequest
updateLinePropertiesRequest =
UpdateLinePropertiesRequest'
{ _ulprLineProperties = Nothing
, _ulprObjectId = Nothing
, _ulprFields = Nothing
}
-- | The line properties to update.
ulprLineProperties :: Lens' UpdateLinePropertiesRequest (Maybe LineProperties)
ulprLineProperties
= lens _ulprLineProperties
(\ s a -> s{_ulprLineProperties = a})
-- | The object ID of the line the update is applied to.
ulprObjectId :: Lens' UpdateLinePropertiesRequest (Maybe Text)
ulprObjectId
= lens _ulprObjectId (\ s a -> s{_ulprObjectId = a})
-- | The fields that should be updated. At least one field must be specified.
-- The root \`lineProperties\` is implied and should not be specified. A
-- single \`\"*\"\` can be used as short-hand for listing every field. For
-- example to update the line solid fill color, set \`fields\` to
-- \`\"lineFill.solidFill.color\"\`. To reset a property to its default
-- value, include its field name in the field mask but leave the field
-- itself unset.
ulprFields :: Lens' UpdateLinePropertiesRequest (Maybe GFieldMask)
ulprFields
= lens _ulprFields (\ s a -> s{_ulprFields = a})
instance FromJSON UpdateLinePropertiesRequest where
parseJSON
= withObject "UpdateLinePropertiesRequest"
(\ o ->
UpdateLinePropertiesRequest' <$>
(o .:? "lineProperties") <*> (o .:? "objectId") <*>
(o .:? "fields"))
instance ToJSON UpdateLinePropertiesRequest where
toJSON UpdateLinePropertiesRequest'{..}
= object
(catMaybes
[("lineProperties" .=) <$> _ulprLineProperties,
("objectId" .=) <$> _ulprObjectId,
("fields" .=) <$> _ulprFields])
-- | The crop properties of an object enclosed in a container. For example,
-- an Image. The crop properties is represented by the offsets of four
-- edges which define a crop rectangle. The offsets are measured in
-- percentage from the corresponding edges of the object\'s original
-- bounding rectangle towards inside, relative to the object\'s original
-- dimensions. - If the offset is in the interval (0, 1), the corresponding
-- edge of crop rectangle is positioned inside of the object\'s original
-- bounding rectangle. - If the offset is negative or greater than 1, the
-- corresponding edge of crop rectangle is positioned outside of the
-- object\'s original bounding rectangle. - If the left edge of the crop
-- rectangle is on the right side of its right edge, the object will be
-- flipped horizontally. - If the top edge of the crop rectangle is below
-- its bottom edge, the object will be flipped vertically. - If all offsets
-- and rotation angle is 0, the object is not cropped. After cropping, the
-- content in the crop rectangle will be stretched to fit its container.
--
-- /See:/ 'cropProperties' smart constructor.
data CropProperties =
CropProperties'
{ _cpBottomOffSet :: !(Maybe (Textual Double))
, _cpTopOffSet :: !(Maybe (Textual Double))
, _cpAngle :: !(Maybe (Textual Double))
, _cpRightOffSet :: !(Maybe (Textual Double))
, _cpLeftOffSet :: !(Maybe (Textual Double))
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'CropProperties' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cpBottomOffSet'
--
-- * 'cpTopOffSet'
--
-- * 'cpAngle'
--
-- * 'cpRightOffSet'
--
-- * 'cpLeftOffSet'
cropProperties
:: CropProperties
cropProperties =
CropProperties'
{ _cpBottomOffSet = Nothing
, _cpTopOffSet = Nothing
, _cpAngle = Nothing
, _cpRightOffSet = Nothing
, _cpLeftOffSet = Nothing
}
-- | The offset specifies the bottom edge of the crop rectangle that is
-- located above the original bounding rectangle bottom edge, relative to
-- the object\'s original height.
cpBottomOffSet :: Lens' CropProperties (Maybe Double)
cpBottomOffSet
= lens _cpBottomOffSet
(\ s a -> s{_cpBottomOffSet = a})
. mapping _Coerce
-- | The offset specifies the top edge of the crop rectangle that is located
-- below the original bounding rectangle top edge, relative to the
-- object\'s original height.
cpTopOffSet :: Lens' CropProperties (Maybe Double)
cpTopOffSet
= lens _cpTopOffSet (\ s a -> s{_cpTopOffSet = a}) .
mapping _Coerce
-- | The rotation angle of the crop window around its center, in radians.
-- Rotation angle is applied after the offset.
cpAngle :: Lens' CropProperties (Maybe Double)
cpAngle
= lens _cpAngle (\ s a -> s{_cpAngle = a}) .
mapping _Coerce
-- | The offset specifies the right edge of the crop rectangle that is
-- located to the left of the original bounding rectangle right edge,
-- relative to the object\'s original width.
cpRightOffSet :: Lens' CropProperties (Maybe Double)
cpRightOffSet
= lens _cpRightOffSet
(\ s a -> s{_cpRightOffSet = a})
. mapping _Coerce
-- | The offset specifies the left edge of the crop rectangle that is located
-- to the right of the original bounding rectangle left edge, relative to
-- the object\'s original width.
cpLeftOffSet :: Lens' CropProperties (Maybe Double)
cpLeftOffSet
= lens _cpLeftOffSet (\ s a -> s{_cpLeftOffSet = a})
. mapping _Coerce
instance FromJSON CropProperties where
parseJSON
= withObject "CropProperties"
(\ o ->
CropProperties' <$>
(o .:? "bottomOffset") <*> (o .:? "topOffset") <*>
(o .:? "angle")
<*> (o .:? "rightOffset")
<*> (o .:? "leftOffset"))
instance ToJSON CropProperties where
toJSON CropProperties'{..}
= object
(catMaybes
[("bottomOffset" .=) <$> _cpBottomOffSet,
("topOffset" .=) <$> _cpTopOffSet,
("angle" .=) <$> _cpAngle,
("rightOffset" .=) <$> _cpRightOffSet,
("leftOffset" .=) <$> _cpLeftOffSet])
-- | The properties of the Line. When unset, these fields default to values
-- that match the appearance of new lines created in the Slides editor.
--
-- /See:/ 'lineProperties' smart constructor.
data LineProperties =
LineProperties'
{ _lpWeight :: !(Maybe Dimension)
, _lpLink :: !(Maybe Link)
, _lpStartConnection :: !(Maybe LineConnection)
, _lpDashStyle :: !(Maybe LinePropertiesDashStyle)
, _lpStartArrow :: !(Maybe LinePropertiesStartArrow)
, _lpLineFill :: !(Maybe LineFill)
, _lpEndConnection :: !(Maybe LineConnection)
, _lpEndArrow :: !(Maybe LinePropertiesEndArrow)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'LineProperties' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lpWeight'
--
-- * 'lpLink'
--
-- * 'lpStartConnection'
--
-- * 'lpDashStyle'
--
-- * 'lpStartArrow'
--
-- * 'lpLineFill'
--
-- * 'lpEndConnection'
--
-- * 'lpEndArrow'
lineProperties
:: LineProperties
lineProperties =
LineProperties'
{ _lpWeight = Nothing
, _lpLink = Nothing
, _lpStartConnection = Nothing
, _lpDashStyle = Nothing
, _lpStartArrow = Nothing
, _lpLineFill = Nothing
, _lpEndConnection = Nothing
, _lpEndArrow = Nothing
}
-- | The thickness of the line.
lpWeight :: Lens' LineProperties (Maybe Dimension)
lpWeight = lens _lpWeight (\ s a -> s{_lpWeight = a})
-- | The hyperlink destination of the line. If unset, there is no link.
lpLink :: Lens' LineProperties (Maybe Link)
lpLink = lens _lpLink (\ s a -> s{_lpLink = a})
-- | The connection at the beginning of the line. If unset, there is no
-- connection. Only lines with a Type indicating it is a \"connector\" can
-- have a \`start_connection\`.
lpStartConnection :: Lens' LineProperties (Maybe LineConnection)
lpStartConnection
= lens _lpStartConnection
(\ s a -> s{_lpStartConnection = a})
-- | The dash style of the line.
lpDashStyle :: Lens' LineProperties (Maybe LinePropertiesDashStyle)
lpDashStyle
= lens _lpDashStyle (\ s a -> s{_lpDashStyle = a})
-- | The style of the arrow at the beginning of the line.
lpStartArrow :: Lens' LineProperties (Maybe LinePropertiesStartArrow)
lpStartArrow
= lens _lpStartArrow (\ s a -> s{_lpStartArrow = a})
-- | The fill of the line. The default line fill matches the defaults for new
-- lines created in the Slides editor.
lpLineFill :: Lens' LineProperties (Maybe LineFill)
lpLineFill
= lens _lpLineFill (\ s a -> s{_lpLineFill = a})
-- | The connection at the end of the line. If unset, there is no connection.
-- Only lines with a Type indicating it is a \"connector\" can have an
-- \`end_connection\`.
lpEndConnection :: Lens' LineProperties (Maybe LineConnection)
lpEndConnection
= lens _lpEndConnection
(\ s a -> s{_lpEndConnection = a})
-- | The style of the arrow at the end of the line.
lpEndArrow :: Lens' LineProperties (Maybe LinePropertiesEndArrow)
lpEndArrow
= lens _lpEndArrow (\ s a -> s{_lpEndArrow = a})
instance FromJSON LineProperties where
parseJSON
= withObject "LineProperties"
(\ o ->
LineProperties' <$>
(o .:? "weight") <*> (o .:? "link") <*>
(o .:? "startConnection")
<*> (o .:? "dashStyle")
<*> (o .:? "startArrow")
<*> (o .:? "lineFill")
<*> (o .:? "endConnection")
<*> (o .:? "endArrow"))
instance ToJSON LineProperties where
toJSON LineProperties'{..}
= object
(catMaybes
[("weight" .=) <$> _lpWeight,
("link" .=) <$> _lpLink,
("startConnection" .=) <$> _lpStartConnection,
("dashStyle" .=) <$> _lpDashStyle,
("startArrow" .=) <$> _lpStartArrow,
("lineFill" .=) <$> _lpLineFill,
("endConnection" .=) <$> _lpEndConnection,
("endArrow" .=) <$> _lpEndArrow])
-- | A PageElement kind representing a joined collection of PageElements.
--
-- /See:/ 'group'' smart constructor.
newtype Group =
Group'
{ _gChildren :: Maybe [PageElement]
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Group' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gChildren'
group'
:: Group
group' = Group' {_gChildren = Nothing}
-- | The collection of elements in the group. The minimum size of a group is
-- 2.
gChildren :: Lens' Group [PageElement]
gChildren
= lens _gChildren (\ s a -> s{_gChildren = a}) .
_Default
. _Coerce
instance FromJSON Group where
parseJSON
= withObject "Group"
(\ o -> Group' <$> (o .:? "children" .!= mempty))
instance ToJSON Group where
toJSON Group'{..}
= object (catMaybes [("children" .=) <$> _gChildren])
-- | Replaces an existing image with a new image. Replacing an image removes
-- some image effects from the existing image.
--
-- /See:/ 'replaceImageRequest' smart constructor.
data ReplaceImageRequest =
ReplaceImageRequest'
{ _rirImageReplaceMethod :: !(Maybe ReplaceImageRequestImageReplaceMethod)
, _rirImageObjectId :: !(Maybe Text)
, _rirURL :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ReplaceImageRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'rirImageReplaceMethod'
--
-- * 'rirImageObjectId'
--
-- * 'rirURL'
replaceImageRequest
:: ReplaceImageRequest
replaceImageRequest =
ReplaceImageRequest'
{ _rirImageReplaceMethod = Nothing
, _rirImageObjectId = Nothing
, _rirURL = Nothing
}
-- | The replacement method.
rirImageReplaceMethod :: Lens' ReplaceImageRequest (Maybe ReplaceImageRequestImageReplaceMethod)
rirImageReplaceMethod
= lens _rirImageReplaceMethod
(\ s a -> s{_rirImageReplaceMethod = a})
-- | The ID of the existing image that will be replaced.
rirImageObjectId :: Lens' ReplaceImageRequest (Maybe Text)
rirImageObjectId
= lens _rirImageObjectId
(\ s a -> s{_rirImageObjectId = a})
-- | The image URL. The image is fetched once at insertion time and a copy is
-- stored for display inside the presentation. Images must be less than
-- 50MB in size, cannot exceed 25 megapixels, and must be in one of PNG,
-- JPEG, or GIF format. The provided URL can be at most 2 kB in length. The
-- URL itself is saved with the image, and exposed via the Image.source_url
-- field.
rirURL :: Lens' ReplaceImageRequest (Maybe Text)
rirURL = lens _rirURL (\ s a -> s{_rirURL = a})
instance FromJSON ReplaceImageRequest where
parseJSON
= withObject "ReplaceImageRequest"
(\ o ->
ReplaceImageRequest' <$>
(o .:? "imageReplaceMethod") <*>
(o .:? "imageObjectId")
<*> (o .:? "url"))
instance ToJSON ReplaceImageRequest where
toJSON ReplaceImageRequest'{..}
= object
(catMaybes
[("imageReplaceMethod" .=) <$>
_rirImageReplaceMethod,
("imageObjectId" .=) <$> _rirImageObjectId,
("url" .=) <$> _rirURL])
-- | Request message for PresentationsService.BatchUpdatePresentation.
--
-- /See:/ 'batchUpdatePresentationRequest' smart constructor.
data BatchUpdatePresentationRequest =
BatchUpdatePresentationRequest'
{ _buprRequests :: !(Maybe [Request'])
, _buprWriteControl :: !(Maybe WriteControl)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'BatchUpdatePresentationRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'buprRequests'
--
-- * 'buprWriteControl'
batchUpdatePresentationRequest
:: BatchUpdatePresentationRequest
batchUpdatePresentationRequest =
BatchUpdatePresentationRequest'
{_buprRequests = Nothing, _buprWriteControl = Nothing}
-- | A list of updates to apply to the presentation.
buprRequests :: Lens' BatchUpdatePresentationRequest [Request']
buprRequests
= lens _buprRequests (\ s a -> s{_buprRequests = a})
. _Default
. _Coerce
-- | Provides control over how write requests are executed.
buprWriteControl :: Lens' BatchUpdatePresentationRequest (Maybe WriteControl)
buprWriteControl
= lens _buprWriteControl
(\ s a -> s{_buprWriteControl = a})
instance FromJSON BatchUpdatePresentationRequest
where
parseJSON
= withObject "BatchUpdatePresentationRequest"
(\ o ->
BatchUpdatePresentationRequest' <$>
(o .:? "requests" .!= mempty) <*>
(o .:? "writeControl"))
instance ToJSON BatchUpdatePresentationRequest where
toJSON BatchUpdatePresentationRequest'{..}
= object
(catMaybes
[("requests" .=) <$> _buprRequests,
("writeControl" .=) <$> _buprWriteControl])
-- | Updates the Z-order of page elements. Z-order is an ordering of the
-- elements on the page from back to front. The page element in the front
-- may cover the elements that are behind it.
--
-- /See:/ 'updatePageElementsZOrderRequest' smart constructor.
data UpdatePageElementsZOrderRequest =
UpdatePageElementsZOrderRequest'
{ _upezorOperation :: !(Maybe UpdatePageElementsZOrderRequestOperation)
, _upezorPageElementObjectIds :: !(Maybe [Text])
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'UpdatePageElementsZOrderRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'upezorOperation'
--
-- * 'upezorPageElementObjectIds'
updatePageElementsZOrderRequest
:: UpdatePageElementsZOrderRequest
updatePageElementsZOrderRequest =
UpdatePageElementsZOrderRequest'
{_upezorOperation = Nothing, _upezorPageElementObjectIds = Nothing}
-- | The Z-order operation to apply on the page elements. When applying the
-- operation on multiple page elements, the relative Z-orders within these
-- page elements before the operation is maintained.
upezorOperation :: Lens' UpdatePageElementsZOrderRequest (Maybe UpdatePageElementsZOrderRequestOperation)
upezorOperation
= lens _upezorOperation
(\ s a -> s{_upezorOperation = a})
-- | The object IDs of the page elements to update. All the page elements
-- must be on the same page and must not be grouped.
upezorPageElementObjectIds :: Lens' UpdatePageElementsZOrderRequest [Text]
upezorPageElementObjectIds
= lens _upezorPageElementObjectIds
(\ s a -> s{_upezorPageElementObjectIds = a})
. _Default
. _Coerce
instance FromJSON UpdatePageElementsZOrderRequest
where
parseJSON
= withObject "UpdatePageElementsZOrderRequest"
(\ o ->
UpdatePageElementsZOrderRequest' <$>
(o .:? "operation") <*>
(o .:? "pageElementObjectIds" .!= mempty))
instance ToJSON UpdatePageElementsZOrderRequest where
toJSON UpdatePageElementsZOrderRequest'{..}
= object
(catMaybes
[("operation" .=) <$> _upezorOperation,
("pageElementObjectIds" .=) <$>
_upezorPageElementObjectIds])
-- | Creates a new shape.
--
-- /See:/ 'createShapeRequest' smart constructor.
data CreateShapeRequest =
CreateShapeRequest'
{ _csrShapeType :: !(Maybe CreateShapeRequestShapeType)
, _csrObjectId :: !(Maybe Text)
, _csrElementProperties :: !(Maybe PageElementProperties)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'CreateShapeRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'csrShapeType'
--
-- * 'csrObjectId'
--
-- * 'csrElementProperties'
createShapeRequest
:: CreateShapeRequest
createShapeRequest =
CreateShapeRequest'
{ _csrShapeType = Nothing
, _csrObjectId = Nothing
, _csrElementProperties = Nothing
}
-- | The shape type.
csrShapeType :: Lens' CreateShapeRequest (Maybe CreateShapeRequestShapeType)
csrShapeType
= lens _csrShapeType (\ s a -> s{_csrShapeType = a})
-- | A user-supplied object ID. If you specify an ID, it must be unique among
-- all pages and page elements in the presentation. The ID must start with
-- an alphanumeric character or an underscore (matches regex
-- \`[a-zA-Z0-9_]\`); remaining characters may include those as well as a
-- hyphen or colon (matches regex \`[a-zA-Z0-9_-:]\`). The length of the ID
-- must not be less than 5 or greater than 50. If empty, a unique
-- identifier will be generated.
csrObjectId :: Lens' CreateShapeRequest (Maybe Text)
csrObjectId
= lens _csrObjectId (\ s a -> s{_csrObjectId = a})
-- | The element properties for the shape.
csrElementProperties :: Lens' CreateShapeRequest (Maybe PageElementProperties)
csrElementProperties
= lens _csrElementProperties
(\ s a -> s{_csrElementProperties = a})
instance FromJSON CreateShapeRequest where
parseJSON
= withObject "CreateShapeRequest"
(\ o ->
CreateShapeRequest' <$>
(o .:? "shapeType") <*> (o .:? "objectId") <*>
(o .:? "elementProperties"))
instance ToJSON CreateShapeRequest where
toJSON CreateShapeRequest'{..}
= object
(catMaybes
[("shapeType" .=) <$> _csrShapeType,
("objectId" .=) <$> _csrObjectId,
("elementProperties" .=) <$> _csrElementProperties])
-- | A TextElement kind that represents auto text.
--
-- /See:/ 'autoText' smart constructor.
data AutoText =
AutoText'
{ _atStyle :: !(Maybe TextStyle)
, _atContent :: !(Maybe Text)
, _atType :: !(Maybe AutoTextType)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'AutoText' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'atStyle'
--
-- * 'atContent'
--
-- * 'atType'
autoText
:: AutoText
autoText =
AutoText' {_atStyle = Nothing, _atContent = Nothing, _atType = Nothing}
-- | The styling applied to this auto text.
atStyle :: Lens' AutoText (Maybe TextStyle)
atStyle = lens _atStyle (\ s a -> s{_atStyle = a})
-- | The rendered content of this auto text, if available.
atContent :: Lens' AutoText (Maybe Text)
atContent
= lens _atContent (\ s a -> s{_atContent = a})
-- | The type of this auto text.
atType :: Lens' AutoText (Maybe AutoTextType)
atType = lens _atType (\ s a -> s{_atType = a})
instance FromJSON AutoText where
parseJSON
= withObject "AutoText"
(\ o ->
AutoText' <$>
(o .:? "style") <*> (o .:? "content") <*>
(o .:? "type"))
instance ToJSON AutoText where
toJSON AutoText'{..}
= object
(catMaybes
[("style" .=) <$> _atStyle,
("content" .=) <$> _atContent,
("type" .=) <$> _atType])
-- | Replaces all shapes that match the given criteria with the provided
-- Google Sheets chart. The chart will be scaled and centered to fit within
-- the bounds of the original shape. NOTE: Replacing shapes with a chart
-- requires at least one of the spreadsheets.readonly, spreadsheets,
-- drive.readonly, or drive OAuth scopes.
--
-- /See:/ 'replaceAllShapesWithSheetsChartRequest' smart constructor.
data ReplaceAllShapesWithSheetsChartRequest =
ReplaceAllShapesWithSheetsChartRequest'
{ _raswscrPageObjectIds :: !(Maybe [Text])
, _raswscrSpreadsheetId :: !(Maybe Text)
, _raswscrLinkingMode :: !(Maybe ReplaceAllShapesWithSheetsChartRequestLinkingMode)
, _raswscrContainsText :: !(Maybe SubstringMatchCriteria)
, _raswscrChartId :: !(Maybe (Textual Int32))
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ReplaceAllShapesWithSheetsChartRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'raswscrPageObjectIds'
--
-- * 'raswscrSpreadsheetId'
--
-- * 'raswscrLinkingMode'
--
-- * 'raswscrContainsText'
--
-- * 'raswscrChartId'
replaceAllShapesWithSheetsChartRequest
:: ReplaceAllShapesWithSheetsChartRequest
replaceAllShapesWithSheetsChartRequest =
ReplaceAllShapesWithSheetsChartRequest'
{ _raswscrPageObjectIds = Nothing
, _raswscrSpreadsheetId = Nothing
, _raswscrLinkingMode = Nothing
, _raswscrContainsText = Nothing
, _raswscrChartId = Nothing
}
-- | If non-empty, limits the matches to page elements only on the given
-- pages. Returns a 400 bad request error if given the page object ID of a
-- notes page or a notes master, or if a page with that object ID doesn\'t
-- exist in the presentation.
raswscrPageObjectIds :: Lens' ReplaceAllShapesWithSheetsChartRequest [Text]
raswscrPageObjectIds
= lens _raswscrPageObjectIds
(\ s a -> s{_raswscrPageObjectIds = a})
. _Default
. _Coerce
-- | The ID of the Google Sheets spreadsheet that contains the chart.
raswscrSpreadsheetId :: Lens' ReplaceAllShapesWithSheetsChartRequest (Maybe Text)
raswscrSpreadsheetId
= lens _raswscrSpreadsheetId
(\ s a -> s{_raswscrSpreadsheetId = a})
-- | The mode with which the chart is linked to the source spreadsheet. When
-- not specified, the chart will be an image that is not linked.
raswscrLinkingMode :: Lens' ReplaceAllShapesWithSheetsChartRequest (Maybe ReplaceAllShapesWithSheetsChartRequestLinkingMode)
raswscrLinkingMode
= lens _raswscrLinkingMode
(\ s a -> s{_raswscrLinkingMode = a})
-- | The criteria that the shapes must match in order to be replaced. The
-- request will replace all of the shapes that contain the given text.
raswscrContainsText :: Lens' ReplaceAllShapesWithSheetsChartRequest (Maybe SubstringMatchCriteria)
raswscrContainsText
= lens _raswscrContainsText
(\ s a -> s{_raswscrContainsText = a})
-- | The ID of the specific chart in the Google Sheets spreadsheet.
raswscrChartId :: Lens' ReplaceAllShapesWithSheetsChartRequest (Maybe Int32)
raswscrChartId
= lens _raswscrChartId
(\ s a -> s{_raswscrChartId = a})
. mapping _Coerce
instance FromJSON
ReplaceAllShapesWithSheetsChartRequest
where
parseJSON
= withObject "ReplaceAllShapesWithSheetsChartRequest"
(\ o ->
ReplaceAllShapesWithSheetsChartRequest' <$>
(o .:? "pageObjectIds" .!= mempty) <*>
(o .:? "spreadsheetId")
<*> (o .:? "linkingMode")
<*> (o .:? "containsText")
<*> (o .:? "chartId"))
instance ToJSON
ReplaceAllShapesWithSheetsChartRequest
where
toJSON ReplaceAllShapesWithSheetsChartRequest'{..}
= object
(catMaybes
[("pageObjectIds" .=) <$> _raswscrPageObjectIds,
("spreadsheetId" .=) <$> _raswscrSpreadsheetId,
("linkingMode" .=) <$> _raswscrLinkingMode,
("containsText" .=) <$> _raswscrContainsText,
("chartId" .=) <$> _raswscrChartId])
-- | A List describes the look and feel of bullets belonging to paragraphs
-- associated with a list. A paragraph that is part of a list has an
-- implicit reference to that list\'s ID.
--
-- /See:/ 'list' smart constructor.
data List =
List'
{ _lListId :: !(Maybe Text)
, _lNestingLevel :: !(Maybe ListNestingLevel)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'List' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lListId'
--
-- * 'lNestingLevel'
list
:: List
list = List' {_lListId = Nothing, _lNestingLevel = Nothing}
-- | The ID of the list.
lListId :: Lens' List (Maybe Text)
lListId = lens _lListId (\ s a -> s{_lListId = a})
-- | A map of nesting levels to the properties of bullets at the associated
-- level. A list has at most nine levels of nesting, so the possible values
-- for the keys of this map are 0 through 8, inclusive.
lNestingLevel :: Lens' List (Maybe ListNestingLevel)
lNestingLevel
= lens _lNestingLevel
(\ s a -> s{_lNestingLevel = a})
instance FromJSON List where
parseJSON
= withObject "List"
(\ o ->
List' <$>
(o .:? "listId") <*> (o .:? "nestingLevel"))
instance ToJSON List where
toJSON List'{..}
= object
(catMaybes
[("listId" .=) <$> _lListId,
("nestingLevel" .=) <$> _lNestingLevel])
-- | The properties of Page that are only relevant for pages with page_type
-- NOTES.
--
-- /See:/ 'notesProperties' smart constructor.
newtype NotesProperties =
NotesProperties'
{ _npSpeakerNotesObjectId :: Maybe Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'NotesProperties' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'npSpeakerNotesObjectId'
notesProperties
:: NotesProperties
notesProperties = NotesProperties' {_npSpeakerNotesObjectId = Nothing}
-- | The object ID of the shape on this notes page that contains the speaker
-- notes for the corresponding slide. The actual shape may not always exist
-- on the notes page. Inserting text using this object ID will
-- automatically create the shape. In this case, the actual shape may have
-- different object ID. The \`GetPresentation\` or \`GetPage\` action will
-- always return the latest object ID.
npSpeakerNotesObjectId :: Lens' NotesProperties (Maybe Text)
npSpeakerNotesObjectId
= lens _npSpeakerNotesObjectId
(\ s a -> s{_npSpeakerNotesObjectId = a})
instance FromJSON NotesProperties where
parseJSON
= withObject "NotesProperties"
(\ o ->
NotesProperties' <$> (o .:? "speakerNotesObjectId"))
instance ToJSON NotesProperties where
toJSON NotesProperties'{..}
= object
(catMaybes
[("speakerNotesObjectId" .=) <$>
_npSpeakerNotesObjectId])
-- | The result of grouping objects.
--
-- /See:/ 'groupObjectsResponse' smart constructor.
newtype GroupObjectsResponse =
GroupObjectsResponse'
{ _gorObjectId :: Maybe Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'GroupObjectsResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gorObjectId'
groupObjectsResponse
:: GroupObjectsResponse
groupObjectsResponse = GroupObjectsResponse' {_gorObjectId = Nothing}
-- | The object ID of the created group.
gorObjectId :: Lens' GroupObjectsResponse (Maybe Text)
gorObjectId
= lens _gorObjectId (\ s a -> s{_gorObjectId = a})
instance FromJSON GroupObjectsResponse where
parseJSON
= withObject "GroupObjectsResponse"
(\ o -> GroupObjectsResponse' <$> (o .:? "objectId"))
instance ToJSON GroupObjectsResponse where
toJSON GroupObjectsResponse'{..}
= object
(catMaybes [("objectId" .=) <$> _gorObjectId])
-- | An RGB color.
--
-- /See:/ 'rgbColor' smart constructor.
data RgbColor =
RgbColor'
{ _rcRed :: !(Maybe (Textual Double))
, _rcGreen :: !(Maybe (Textual Double))
, _rcBlue :: !(Maybe (Textual Double))
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'RgbColor' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'rcRed'
--
-- * 'rcGreen'
--
-- * 'rcBlue'
rgbColor
:: RgbColor
rgbColor = RgbColor' {_rcRed = Nothing, _rcGreen = Nothing, _rcBlue = Nothing}
-- | The red component of the color, from 0.0 to 1.0.
rcRed :: Lens' RgbColor (Maybe Double)
rcRed
= lens _rcRed (\ s a -> s{_rcRed = a}) .
mapping _Coerce
-- | The green component of the color, from 0.0 to 1.0.
rcGreen :: Lens' RgbColor (Maybe Double)
rcGreen
= lens _rcGreen (\ s a -> s{_rcGreen = a}) .
mapping _Coerce
-- | The blue component of the color, from 0.0 to 1.0.
rcBlue :: Lens' RgbColor (Maybe Double)
rcBlue
= lens _rcBlue (\ s a -> s{_rcBlue = a}) .
mapping _Coerce
instance FromJSON RgbColor where
parseJSON
= withObject "RgbColor"
(\ o ->
RgbColor' <$>
(o .:? "red") <*> (o .:? "green") <*> (o .:? "blue"))
instance ToJSON RgbColor where
toJSON RgbColor'{..}
= object
(catMaybes
[("red" .=) <$> _rcRed, ("green" .=) <$> _rcGreen,
("blue" .=) <$> _rcBlue])
-- | Updates the properties of a Page.
--
-- /See:/ 'updatePagePropertiesRequest' smart constructor.
data UpdatePagePropertiesRequest =
UpdatePagePropertiesRequest'
{ _upprObjectId :: !(Maybe Text)
, _upprPageProperties :: !(Maybe PageProperties)
, _upprFields :: !(Maybe GFieldMask)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'UpdatePagePropertiesRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'upprObjectId'
--
-- * 'upprPageProperties'
--
-- * 'upprFields'
updatePagePropertiesRequest
:: UpdatePagePropertiesRequest
updatePagePropertiesRequest =
UpdatePagePropertiesRequest'
{ _upprObjectId = Nothing
, _upprPageProperties = Nothing
, _upprFields = Nothing
}
-- | The object ID of the page the update is applied to.
upprObjectId :: Lens' UpdatePagePropertiesRequest (Maybe Text)
upprObjectId
= lens _upprObjectId (\ s a -> s{_upprObjectId = a})
-- | The page properties to update.
upprPageProperties :: Lens' UpdatePagePropertiesRequest (Maybe PageProperties)
upprPageProperties
= lens _upprPageProperties
(\ s a -> s{_upprPageProperties = a})
-- | The fields that should be updated. At least one field must be specified.
-- The root \`pageProperties\` is implied and should not be specified. A
-- single \`\"*\"\` can be used as short-hand for listing every field. For
-- example to update the page background solid fill color, set \`fields\`
-- to \`\"pageBackgroundFill.solidFill.color\"\`. To reset a property to
-- its default value, include its field name in the field mask but leave
-- the field itself unset.
upprFields :: Lens' UpdatePagePropertiesRequest (Maybe GFieldMask)
upprFields
= lens _upprFields (\ s a -> s{_upprFields = a})
instance FromJSON UpdatePagePropertiesRequest where
parseJSON
= withObject "UpdatePagePropertiesRequest"
(\ o ->
UpdatePagePropertiesRequest' <$>
(o .:? "objectId") <*> (o .:? "pageProperties") <*>
(o .:? "fields"))
instance ToJSON UpdatePagePropertiesRequest where
toJSON UpdatePagePropertiesRequest'{..}
= object
(catMaybes
[("objectId" .=) <$> _upprObjectId,
("pageProperties" .=) <$> _upprPageProperties,
("fields" .=) <$> _upprFields])
-- | Creates an embedded Google Sheets chart. NOTE: Chart creation requires
-- at least one of the spreadsheets.readonly, spreadsheets, drive.readonly,
-- drive.file, or drive OAuth scopes.
--
-- /See:/ 'createSheetsChartRequest' smart constructor.
data CreateSheetsChartRequest =
CreateSheetsChartRequest'
{ _cscrObjectId :: !(Maybe Text)
, _cscrSpreadsheetId :: !(Maybe Text)
, _cscrLinkingMode :: !(Maybe CreateSheetsChartRequestLinkingMode)
, _cscrElementProperties :: !(Maybe PageElementProperties)
, _cscrChartId :: !(Maybe (Textual Int32))
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'CreateSheetsChartRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cscrObjectId'
--
-- * 'cscrSpreadsheetId'
--
-- * 'cscrLinkingMode'
--
-- * 'cscrElementProperties'
--
-- * 'cscrChartId'
createSheetsChartRequest
:: CreateSheetsChartRequest
createSheetsChartRequest =
CreateSheetsChartRequest'
{ _cscrObjectId = Nothing
, _cscrSpreadsheetId = Nothing
, _cscrLinkingMode = Nothing
, _cscrElementProperties = Nothing
, _cscrChartId = Nothing
}
-- | A user-supplied object ID. If specified, the ID must be unique among all
-- pages and page elements in the presentation. The ID should start with a
-- word character [a-zA-Z0-9_] and then followed by any number of the
-- following characters [a-zA-Z0-9_-:]. The length of the ID should not be
-- less than 5 or greater than 50. If empty, a unique identifier will be
-- generated.
cscrObjectId :: Lens' CreateSheetsChartRequest (Maybe Text)
cscrObjectId
= lens _cscrObjectId (\ s a -> s{_cscrObjectId = a})
-- | The ID of the Google Sheets spreadsheet that contains the chart. You
-- might need to add a resource key to the HTTP header for a subset of old
-- files. For more information, see [Access link-shared files using
-- resource
-- keys](https:\/\/developers.google.com\/drive\/api\/v3\/resource-keys).
cscrSpreadsheetId :: Lens' CreateSheetsChartRequest (Maybe Text)
cscrSpreadsheetId
= lens _cscrSpreadsheetId
(\ s a -> s{_cscrSpreadsheetId = a})
-- | The mode with which the chart is linked to the source spreadsheet. When
-- not specified, the chart will be an image that is not linked.
cscrLinkingMode :: Lens' CreateSheetsChartRequest (Maybe CreateSheetsChartRequestLinkingMode)
cscrLinkingMode
= lens _cscrLinkingMode
(\ s a -> s{_cscrLinkingMode = a})
-- | The element properties for the chart. When the aspect ratio of the
-- provided size does not match the chart aspect ratio, the chart is scaled
-- and centered with respect to the size in order to maintain aspect ratio.
-- The provided transform is applied after this operation.
cscrElementProperties :: Lens' CreateSheetsChartRequest (Maybe PageElementProperties)
cscrElementProperties
= lens _cscrElementProperties
(\ s a -> s{_cscrElementProperties = a})
-- | The ID of the specific chart in the Google Sheets spreadsheet.
cscrChartId :: Lens' CreateSheetsChartRequest (Maybe Int32)
cscrChartId
= lens _cscrChartId (\ s a -> s{_cscrChartId = a}) .
mapping _Coerce
instance FromJSON CreateSheetsChartRequest where
parseJSON
= withObject "CreateSheetsChartRequest"
(\ o ->
CreateSheetsChartRequest' <$>
(o .:? "objectId") <*> (o .:? "spreadsheetId") <*>
(o .:? "linkingMode")
<*> (o .:? "elementProperties")
<*> (o .:? "chartId"))
instance ToJSON CreateSheetsChartRequest where
toJSON CreateSheetsChartRequest'{..}
= object
(catMaybes
[("objectId" .=) <$> _cscrObjectId,
("spreadsheetId" .=) <$> _cscrSpreadsheetId,
("linkingMode" .=) <$> _cscrLinkingMode,
("elementProperties" .=) <$> _cscrElementProperties,
("chartId" .=) <$> _cscrChartId])
-- | Properties of each row in a table.
--
-- /See:/ 'tableRowProperties' smart constructor.
newtype TableRowProperties =
TableRowProperties'
{ _trpMinRowHeight :: Maybe Dimension
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'TableRowProperties' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'trpMinRowHeight'
tableRowProperties
:: TableRowProperties
tableRowProperties = TableRowProperties' {_trpMinRowHeight = Nothing}
-- | Minimum height of the row. The row will be rendered in the Slides editor
-- at a height equal to or greater than this value in order to show all the
-- text in the row\'s cell(s).
trpMinRowHeight :: Lens' TableRowProperties (Maybe Dimension)
trpMinRowHeight
= lens _trpMinRowHeight
(\ s a -> s{_trpMinRowHeight = a})
instance FromJSON TableRowProperties where
parseJSON
= withObject "TableRowProperties"
(\ o ->
TableRowProperties' <$> (o .:? "minRowHeight"))
instance ToJSON TableRowProperties where
toJSON TableRowProperties'{..}
= object
(catMaybes
[("minRowHeight" .=) <$> _trpMinRowHeight])
-- | Updates the properties of a Table row.
--
-- /See:/ 'updateTableRowPropertiesRequest' smart constructor.
data UpdateTableRowPropertiesRequest =
UpdateTableRowPropertiesRequest'
{ _utrprTableRowProperties :: !(Maybe TableRowProperties)
, _utrprRowIndices :: !(Maybe [Textual Int32])
, _utrprObjectId :: !(Maybe Text)
, _utrprFields :: !(Maybe GFieldMask)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'UpdateTableRowPropertiesRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'utrprTableRowProperties'
--
-- * 'utrprRowIndices'
--
-- * 'utrprObjectId'
--
-- * 'utrprFields'
updateTableRowPropertiesRequest
:: UpdateTableRowPropertiesRequest
updateTableRowPropertiesRequest =
UpdateTableRowPropertiesRequest'
{ _utrprTableRowProperties = Nothing
, _utrprRowIndices = Nothing
, _utrprObjectId = Nothing
, _utrprFields = Nothing
}
-- | The table row properties to update.
utrprTableRowProperties :: Lens' UpdateTableRowPropertiesRequest (Maybe TableRowProperties)
utrprTableRowProperties
= lens _utrprTableRowProperties
(\ s a -> s{_utrprTableRowProperties = a})
-- | The list of zero-based indices specifying which rows to update. If no
-- indices are provided, all rows in the table will be updated.
utrprRowIndices :: Lens' UpdateTableRowPropertiesRequest [Int32]
utrprRowIndices
= lens _utrprRowIndices
(\ s a -> s{_utrprRowIndices = a})
. _Default
. _Coerce
-- | The object ID of the table.
utrprObjectId :: Lens' UpdateTableRowPropertiesRequest (Maybe Text)
utrprObjectId
= lens _utrprObjectId
(\ s a -> s{_utrprObjectId = a})
-- | The fields that should be updated. At least one field must be specified.
-- The root \`tableRowProperties\` is implied and should not be specified.
-- A single \`\"*\"\` can be used as short-hand for listing every field.
-- For example to update the minimum row height, set \`fields\` to
-- \`\"min_row_height\"\`. If \'\"min_row_height\"\' is included in the
-- field mask but the property is left unset, the minimum row height will
-- default to 0.
utrprFields :: Lens' UpdateTableRowPropertiesRequest (Maybe GFieldMask)
utrprFields
= lens _utrprFields (\ s a -> s{_utrprFields = a})
instance FromJSON UpdateTableRowPropertiesRequest
where
parseJSON
= withObject "UpdateTableRowPropertiesRequest"
(\ o ->
UpdateTableRowPropertiesRequest' <$>
(o .:? "tableRowProperties") <*>
(o .:? "rowIndices" .!= mempty)
<*> (o .:? "objectId")
<*> (o .:? "fields"))
instance ToJSON UpdateTableRowPropertiesRequest where
toJSON UpdateTableRowPropertiesRequest'{..}
= object
(catMaybes
[("tableRowProperties" .=) <$>
_utrprTableRowProperties,
("rowIndices" .=) <$> _utrprRowIndices,
("objectId" .=) <$> _utrprObjectId,
("fields" .=) <$> _utrprFields])
-- | The properties of Page that are only relevant for pages with page_type
-- MASTER.
--
-- /See:/ 'masterProperties' smart constructor.
newtype MasterProperties =
MasterProperties'
{ _mpDisplayName :: Maybe Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'MasterProperties' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'mpDisplayName'
masterProperties
:: MasterProperties
masterProperties = MasterProperties' {_mpDisplayName = Nothing}
-- | The human-readable name of the master.
mpDisplayName :: Lens' MasterProperties (Maybe Text)
mpDisplayName
= lens _mpDisplayName
(\ s a -> s{_mpDisplayName = a})
instance FromJSON MasterProperties where
parseJSON
= withObject "MasterProperties"
(\ o -> MasterProperties' <$> (o .:? "displayName"))
instance ToJSON MasterProperties where
toJSON MasterProperties'{..}
= object
(catMaybes [("displayName" .=) <$> _mpDisplayName])
-- | Deletes text from a shape or a table cell.
--
-- /See:/ 'deleteTextRequest' smart constructor.
data DeleteTextRequest =
DeleteTextRequest'
{ _dtrTextRange :: !(Maybe Range)
, _dtrObjectId :: !(Maybe Text)
, _dtrCellLocation :: !(Maybe TableCellLocation)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'DeleteTextRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'dtrTextRange'
--
-- * 'dtrObjectId'
--
-- * 'dtrCellLocation'
deleteTextRequest
:: DeleteTextRequest
deleteTextRequest =
DeleteTextRequest'
{ _dtrTextRange = Nothing
, _dtrObjectId = Nothing
, _dtrCellLocation = Nothing
}
-- | The range of text to delete, based on TextElement indexes. There is
-- always an implicit newline character at the end of a shape\'s or table
-- cell\'s text that cannot be deleted. \`Range.Type.ALL\` will use the
-- correct bounds, but care must be taken when specifying explicit bounds
-- for range types \`FROM_START_INDEX\` and \`FIXED_RANGE\`. For example,
-- if the text is \"ABC\", followed by an implicit newline, then the
-- maximum value is 2 for \`text_range.start_index\` and 3 for
-- \`text_range.end_index\`. Deleting text that crosses a paragraph
-- boundary may result in changes to paragraph styles and lists as the two
-- paragraphs are merged. Ranges that include only one code unit of a
-- surrogate pair are expanded to include both code units.
dtrTextRange :: Lens' DeleteTextRequest (Maybe Range)
dtrTextRange
= lens _dtrTextRange (\ s a -> s{_dtrTextRange = a})
-- | The object ID of the shape or table from which the text will be deleted.
dtrObjectId :: Lens' DeleteTextRequest (Maybe Text)
dtrObjectId
= lens _dtrObjectId (\ s a -> s{_dtrObjectId = a})
-- | The optional table cell location if the text is to be deleted from a
-- table cell. If present, the object_id must refer to a table.
dtrCellLocation :: Lens' DeleteTextRequest (Maybe TableCellLocation)
dtrCellLocation
= lens _dtrCellLocation
(\ s a -> s{_dtrCellLocation = a})
instance FromJSON DeleteTextRequest where
parseJSON
= withObject "DeleteTextRequest"
(\ o ->
DeleteTextRequest' <$>
(o .:? "textRange") <*> (o .:? "objectId") <*>
(o .:? "cellLocation"))
instance ToJSON DeleteTextRequest where
toJSON DeleteTextRequest'{..}
= object
(catMaybes
[("textRange" .=) <$> _dtrTextRange,
("objectId" .=) <$> _dtrObjectId,
("cellLocation" .=) <$> _dtrCellLocation])
-- | Inserts columns into a table. Other columns in the table will be resized
-- to fit the new column.
--
-- /See:/ 'insertTableColumnsRequest' smart constructor.
data InsertTableColumnsRequest =
InsertTableColumnsRequest'
{ _itcrInsertRight :: !(Maybe Bool)
, _itcrNumber :: !(Maybe (Textual Int32))
, _itcrCellLocation :: !(Maybe TableCellLocation)
, _itcrTableObjectId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'InsertTableColumnsRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'itcrInsertRight'
--
-- * 'itcrNumber'
--
-- * 'itcrCellLocation'
--
-- * 'itcrTableObjectId'
insertTableColumnsRequest
:: InsertTableColumnsRequest
insertTableColumnsRequest =
InsertTableColumnsRequest'
{ _itcrInsertRight = Nothing
, _itcrNumber = Nothing
, _itcrCellLocation = Nothing
, _itcrTableObjectId = Nothing
}
-- | Whether to insert new columns to the right of the reference cell
-- location. - \`True\`: insert to the right. - \`False\`: insert to the
-- left.
itcrInsertRight :: Lens' InsertTableColumnsRequest (Maybe Bool)
itcrInsertRight
= lens _itcrInsertRight
(\ s a -> s{_itcrInsertRight = a})
-- | The number of columns to be inserted. Maximum 20 per request.
itcrNumber :: Lens' InsertTableColumnsRequest (Maybe Int32)
itcrNumber
= lens _itcrNumber (\ s a -> s{_itcrNumber = a}) .
mapping _Coerce
-- | The reference table cell location from which columns will be inserted. A
-- new column will be inserted to the left (or right) of the column where
-- the reference cell is. If the reference cell is a merged cell, a new
-- column will be inserted to the left (or right) of the merged cell.
itcrCellLocation :: Lens' InsertTableColumnsRequest (Maybe TableCellLocation)
itcrCellLocation
= lens _itcrCellLocation
(\ s a -> s{_itcrCellLocation = a})
-- | The table to insert columns into.
itcrTableObjectId :: Lens' InsertTableColumnsRequest (Maybe Text)
itcrTableObjectId
= lens _itcrTableObjectId
(\ s a -> s{_itcrTableObjectId = a})
instance FromJSON InsertTableColumnsRequest where
parseJSON
= withObject "InsertTableColumnsRequest"
(\ o ->
InsertTableColumnsRequest' <$>
(o .:? "insertRight") <*> (o .:? "number") <*>
(o .:? "cellLocation")
<*> (o .:? "tableObjectId"))
instance ToJSON InsertTableColumnsRequest where
toJSON InsertTableColumnsRequest'{..}
= object
(catMaybes
[("insertRight" .=) <$> _itcrInsertRight,
("number" .=) <$> _itcrNumber,
("cellLocation" .=) <$> _itcrCellLocation,
("tableObjectId" .=) <$> _itcrTableObjectId])
-- | The bulleted lists contained in this text, keyed by list ID.
--
-- /See:/ 'textContentLists' smart constructor.
newtype TextContentLists =
TextContentLists'
{ _tclAddtional :: HashMap Text List
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'TextContentLists' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'tclAddtional'
textContentLists
:: HashMap Text List -- ^ 'tclAddtional'
-> TextContentLists
textContentLists pTclAddtional_ =
TextContentLists' {_tclAddtional = _Coerce # pTclAddtional_}
tclAddtional :: Lens' TextContentLists (HashMap Text List)
tclAddtional
= lens _tclAddtional (\ s a -> s{_tclAddtional = a})
. _Coerce
instance FromJSON TextContentLists where
parseJSON
= withObject "TextContentLists"
(\ o -> TextContentLists' <$> (parseJSONObject o))
instance ToJSON TextContentLists where
toJSON = toJSON . _tclAddtional
-- | A width and height.
--
-- /See:/ 'size' smart constructor.
data Size =
Size'
{ _sHeight :: !(Maybe Dimension)
, _sWidth :: !(Maybe Dimension)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Size' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'sHeight'
--
-- * 'sWidth'
size
:: Size
size = Size' {_sHeight = Nothing, _sWidth = Nothing}
-- | The height of the object.
sHeight :: Lens' Size (Maybe Dimension)
sHeight = lens _sHeight (\ s a -> s{_sHeight = a})
-- | The width of the object.
sWidth :: Lens' Size (Maybe Dimension)
sWidth = lens _sWidth (\ s a -> s{_sWidth = a})
instance FromJSON Size where
parseJSON
= withObject "Size"
(\ o ->
Size' <$> (o .:? "height") <*> (o .:? "width"))
instance ToJSON Size where
toJSON Size'{..}
= object
(catMaybes
[("height" .=) <$> _sHeight,
("width" .=) <$> _sWidth])
-- | The stretched picture fill. The page or page element is filled entirely
-- with the specified picture. The picture is stretched to fit its
-- container.
--
-- /See:/ 'stretchedPictureFill' smart constructor.
data StretchedPictureFill =
StretchedPictureFill'
{ _spfSize :: !(Maybe Size)
, _spfContentURL :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'StretchedPictureFill' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'spfSize'
--
-- * 'spfContentURL'
stretchedPictureFill
:: StretchedPictureFill
stretchedPictureFill =
StretchedPictureFill' {_spfSize = Nothing, _spfContentURL = Nothing}
-- | The original size of the picture fill. This field is read-only.
spfSize :: Lens' StretchedPictureFill (Maybe Size)
spfSize = lens _spfSize (\ s a -> s{_spfSize = a})
-- | Reading the content_url: An URL to a picture with a default lifetime of
-- 30 minutes. This URL is tagged with the account of the requester. Anyone
-- with the URL effectively accesses the picture as the original requester.
-- Access to the picture may be lost if the presentation\'s sharing
-- settings change. Writing the content_url: The picture is fetched once at
-- insertion time and a copy is stored for display inside the presentation.
-- Pictures must be less than 50MB in size, cannot exceed 25 megapixels,
-- and must be in one of PNG, JPEG, or GIF format. The provided URL can be
-- at most 2 kB in length.
spfContentURL :: Lens' StretchedPictureFill (Maybe Text)
spfContentURL
= lens _spfContentURL
(\ s a -> s{_spfContentURL = a})
instance FromJSON StretchedPictureFill where
parseJSON
= withObject "StretchedPictureFill"
(\ o ->
StretchedPictureFill' <$>
(o .:? "size") <*> (o .:? "contentUrl"))
instance ToJSON StretchedPictureFill where
toJSON StretchedPictureFill'{..}
= object
(catMaybes
[("size" .=) <$> _spfSize,
("contentUrl" .=) <$> _spfContentURL])
-- | The fill of the border.
--
-- /See:/ 'tableBOrderFill' smart constructor.
newtype TableBOrderFill =
TableBOrderFill'
{ _tbofSolidFill :: Maybe SolidFill
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'TableBOrderFill' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'tbofSolidFill'
tableBOrderFill
:: TableBOrderFill
tableBOrderFill = TableBOrderFill' {_tbofSolidFill = Nothing}
-- | Solid fill.
tbofSolidFill :: Lens' TableBOrderFill (Maybe SolidFill)
tbofSolidFill
= lens _tbofSolidFill
(\ s a -> s{_tbofSolidFill = a})
instance FromJSON TableBOrderFill where
parseJSON
= withObject "TableBOrderFill"
(\ o -> TableBOrderFill' <$> (o .:? "solidFill"))
instance ToJSON TableBOrderFill where
toJSON TableBOrderFill'{..}
= object
(catMaybes [("solidFill" .=) <$> _tbofSolidFill])
-- | A PageElement kind representing a linked chart embedded from Google
-- Sheets.
--
-- /See:/ 'sheetsChart' smart constructor.
data SheetsChart =
SheetsChart'
{ _scSpreadsheetId :: !(Maybe Text)
, _scContentURL :: !(Maybe Text)
, _scSheetsChartProperties :: !(Maybe SheetsChartProperties)
, _scChartId :: !(Maybe (Textual Int32))
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'SheetsChart' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'scSpreadsheetId'
--
-- * 'scContentURL'
--
-- * 'scSheetsChartProperties'
--
-- * 'scChartId'
sheetsChart
:: SheetsChart
sheetsChart =
SheetsChart'
{ _scSpreadsheetId = Nothing
, _scContentURL = Nothing
, _scSheetsChartProperties = Nothing
, _scChartId = Nothing
}
-- | The ID of the Google Sheets spreadsheet that contains the source chart.
scSpreadsheetId :: Lens' SheetsChart (Maybe Text)
scSpreadsheetId
= lens _scSpreadsheetId
(\ s a -> s{_scSpreadsheetId = a})
-- | The URL of an image of the embedded chart, with a default lifetime of 30
-- minutes. This URL is tagged with the account of the requester. Anyone
-- with the URL effectively accesses the image as the original requester.
-- Access to the image may be lost if the presentation\'s sharing settings
-- change.
scContentURL :: Lens' SheetsChart (Maybe Text)
scContentURL
= lens _scContentURL (\ s a -> s{_scContentURL = a})
-- | The properties of the Sheets chart.
scSheetsChartProperties :: Lens' SheetsChart (Maybe SheetsChartProperties)
scSheetsChartProperties
= lens _scSheetsChartProperties
(\ s a -> s{_scSheetsChartProperties = a})
-- | The ID of the specific chart in the Google Sheets spreadsheet that is
-- embedded.
scChartId :: Lens' SheetsChart (Maybe Int32)
scChartId
= lens _scChartId (\ s a -> s{_scChartId = a}) .
mapping _Coerce
instance FromJSON SheetsChart where
parseJSON
= withObject "SheetsChart"
(\ o ->
SheetsChart' <$>
(o .:? "spreadsheetId") <*> (o .:? "contentUrl") <*>
(o .:? "sheetsChartProperties")
<*> (o .:? "chartId"))
instance ToJSON SheetsChart where
toJSON SheetsChart'{..}
= object
(catMaybes
[("spreadsheetId" .=) <$> _scSpreadsheetId,
("contentUrl" .=) <$> _scContentURL,
("sheetsChartProperties" .=) <$>
_scSheetsChartProperties,
("chartId" .=) <$> _scChartId])
-- | The result of creating a shape.
--
-- /See:/ 'createShapeResponse' smart constructor.
newtype CreateShapeResponse =
CreateShapeResponse'
{ _cObjectId :: Maybe Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'CreateShapeResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cObjectId'
createShapeResponse
:: CreateShapeResponse
createShapeResponse = CreateShapeResponse' {_cObjectId = Nothing}
-- | The object ID of the created shape.
cObjectId :: Lens' CreateShapeResponse (Maybe Text)
cObjectId
= lens _cObjectId (\ s a -> s{_cObjectId = a})
instance FromJSON CreateShapeResponse where
parseJSON
= withObject "CreateShapeResponse"
(\ o -> CreateShapeResponse' <$> (o .:? "objectId"))
instance ToJSON CreateShapeResponse where
toJSON CreateShapeResponse'{..}
= object (catMaybes [("objectId" .=) <$> _cObjectId])
-- | Deletes a column from a table.
--
-- /See:/ 'deleteTableColumnRequest' smart constructor.
data DeleteTableColumnRequest =
DeleteTableColumnRequest'
{ _dtcrCellLocation :: !(Maybe TableCellLocation)
, _dtcrTableObjectId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'DeleteTableColumnRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'dtcrCellLocation'
--
-- * 'dtcrTableObjectId'
deleteTableColumnRequest
:: DeleteTableColumnRequest
deleteTableColumnRequest =
DeleteTableColumnRequest'
{_dtcrCellLocation = Nothing, _dtcrTableObjectId = Nothing}
-- | The reference table cell location from which a column will be deleted.
-- The column this cell spans will be deleted. If this is a merged cell,
-- multiple columns will be deleted. If no columns remain in the table
-- after this deletion, the whole table is deleted.
dtcrCellLocation :: Lens' DeleteTableColumnRequest (Maybe TableCellLocation)
dtcrCellLocation
= lens _dtcrCellLocation
(\ s a -> s{_dtcrCellLocation = a})
-- | The table to delete columns from.
dtcrTableObjectId :: Lens' DeleteTableColumnRequest (Maybe Text)
dtcrTableObjectId
= lens _dtcrTableObjectId
(\ s a -> s{_dtcrTableObjectId = a})
instance FromJSON DeleteTableColumnRequest where
parseJSON
= withObject "DeleteTableColumnRequest"
(\ o ->
DeleteTableColumnRequest' <$>
(o .:? "cellLocation") <*> (o .:? "tableObjectId"))
instance ToJSON DeleteTableColumnRequest where
toJSON DeleteTableColumnRequest'{..}
= object
(catMaybes
[("cellLocation" .=) <$> _dtcrCellLocation,
("tableObjectId" .=) <$> _dtcrTableObjectId])
-- | Contents of each border row in a table.
--
-- /See:/ 'tableBOrderRow' smart constructor.
newtype TableBOrderRow =
TableBOrderRow'
{ _tborTableBOrderCells :: Maybe [TableBOrderCell]
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'TableBOrderRow' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'tborTableBOrderCells'
tableBOrderRow
:: TableBOrderRow
tableBOrderRow = TableBOrderRow' {_tborTableBOrderCells = Nothing}
-- | Properties of each border cell. When a border\'s adjacent table cells
-- are merged, it is not included in the response.
tborTableBOrderCells :: Lens' TableBOrderRow [TableBOrderCell]
tborTableBOrderCells
= lens _tborTableBOrderCells
(\ s a -> s{_tborTableBOrderCells = a})
. _Default
. _Coerce
instance FromJSON TableBOrderRow where
parseJSON
= withObject "TableBOrderRow"
(\ o ->
TableBOrderRow' <$>
(o .:? "tableBorderCells" .!= mempty))
instance ToJSON TableBOrderRow where
toJSON TableBOrderRow'{..}
= object
(catMaybes
[("tableBorderCells" .=) <$> _tborTableBOrderCells])
-- | The properties for one end of a Line connection.
--
-- /See:/ 'lineConnection' smart constructor.
data LineConnection =
LineConnection'
{ _lcConnectedObjectId :: !(Maybe Text)
, _lcConnectionSiteIndex :: !(Maybe (Textual Int32))
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'LineConnection' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lcConnectedObjectId'
--
-- * 'lcConnectionSiteIndex'
lineConnection
:: LineConnection
lineConnection =
LineConnection'
{_lcConnectedObjectId = Nothing, _lcConnectionSiteIndex = Nothing}
-- | The object ID of the connected page element. Some page elements, such as
-- groups, tables, and lines do not have connection sites and therefore
-- cannot be connected to a connector line.
lcConnectedObjectId :: Lens' LineConnection (Maybe Text)
lcConnectedObjectId
= lens _lcConnectedObjectId
(\ s a -> s{_lcConnectedObjectId = a})
-- | The index of the connection site on the connected page element. In most
-- cases, it corresponds to the predefined connection site index from the
-- ECMA-376 standard. More information on those connection sites can be
-- found in the description of the \"cnx\" attribute in section 20.1.9.9
-- and Annex H. \"Predefined DrawingML Shape and Text Geometries\" of
-- \"Office Open XML File Formats-Fundamentals and Markup Language
-- Reference\", part 1 of [ECMA-376 5th edition]
-- (http:\/\/www.ecma-international.org\/publications\/standards\/Ecma-376.htm).
-- The position of each connection site can also be viewed from Slides
-- editor.
lcConnectionSiteIndex :: Lens' LineConnection (Maybe Int32)
lcConnectionSiteIndex
= lens _lcConnectionSiteIndex
(\ s a -> s{_lcConnectionSiteIndex = a})
. mapping _Coerce
instance FromJSON LineConnection where
parseJSON
= withObject "LineConnection"
(\ o ->
LineConnection' <$>
(o .:? "connectedObjectId") <*>
(o .:? "connectionSiteIndex"))
instance ToJSON LineConnection where
toJSON LineConnection'{..}
= object
(catMaybes
[("connectedObjectId" .=) <$> _lcConnectedObjectId,
("connectionSiteIndex" .=) <$>
_lcConnectionSiteIndex])
-- | A hypertext link.
--
-- /See:/ 'link' smart constructor.
data Link =
Link'
{ _lURL :: !(Maybe Text)
, _lPageObjectId :: !(Maybe Text)
, _lRelativeLink :: !(Maybe LinkRelativeLink)
, _lSlideIndex :: !(Maybe (Textual Int32))
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Link' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lURL'
--
-- * 'lPageObjectId'
--
-- * 'lRelativeLink'
--
-- * 'lSlideIndex'
link
:: Link
link =
Link'
{ _lURL = Nothing
, _lPageObjectId = Nothing
, _lRelativeLink = Nothing
, _lSlideIndex = Nothing
}
-- | If set, indicates this is a link to the external web page at this URL.
lURL :: Lens' Link (Maybe Text)
lURL = lens _lURL (\ s a -> s{_lURL = a})
-- | If set, indicates this is a link to the specific page in this
-- presentation with this ID. A page with this ID may not exist.
lPageObjectId :: Lens' Link (Maybe Text)
lPageObjectId
= lens _lPageObjectId
(\ s a -> s{_lPageObjectId = a})
-- | If set, indicates this is a link to a slide in this presentation,
-- addressed by its position.
lRelativeLink :: Lens' Link (Maybe LinkRelativeLink)
lRelativeLink
= lens _lRelativeLink
(\ s a -> s{_lRelativeLink = a})
-- | If set, indicates this is a link to the slide at this zero-based index
-- in the presentation. There may not be a slide at this index.
lSlideIndex :: Lens' Link (Maybe Int32)
lSlideIndex
= lens _lSlideIndex (\ s a -> s{_lSlideIndex = a}) .
mapping _Coerce
instance FromJSON Link where
parseJSON
= withObject "Link"
(\ o ->
Link' <$>
(o .:? "url") <*> (o .:? "pageObjectId") <*>
(o .:? "relativeLink")
<*> (o .:? "slideIndex"))
instance ToJSON Link where
toJSON Link'{..}
= object
(catMaybes
[("url" .=) <$> _lURL,
("pageObjectId" .=) <$> _lPageObjectId,
("relativeLink" .=) <$> _lRelativeLink,
("slideIndex" .=) <$> _lSlideIndex])
-- | Groups objects to create an object group. For example, groups
-- PageElements to create a Group on the same page as all the children.
--
-- /See:/ 'groupObjectsRequest' smart constructor.
data GroupObjectsRequest =
GroupObjectsRequest'
{ _gorGroupObjectId :: !(Maybe Text)
, _gorChildrenObjectIds :: !(Maybe [Text])
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'GroupObjectsRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gorGroupObjectId'
--
-- * 'gorChildrenObjectIds'
groupObjectsRequest
:: GroupObjectsRequest
groupObjectsRequest =
GroupObjectsRequest'
{_gorGroupObjectId = Nothing, _gorChildrenObjectIds = Nothing}
-- | A user-supplied object ID for the group to be created. If you specify an
-- ID, it must be unique among all pages and page elements in the
-- presentation. The ID must start with an alphanumeric character or an
-- underscore (matches regex \`[a-zA-Z0-9_]\`); remaining characters may
-- include those as well as a hyphen or colon (matches regex
-- \`[a-zA-Z0-9_-:]\`). The length of the ID must not be less than 5 or
-- greater than 50. If you don\'t specify an ID, a unique one is generated.
gorGroupObjectId :: Lens' GroupObjectsRequest (Maybe Text)
gorGroupObjectId
= lens _gorGroupObjectId
(\ s a -> s{_gorGroupObjectId = a})
-- | The object IDs of the objects to group. Only page elements can be
-- grouped. There should be at least two page elements on the same page
-- that are not already in another group. Some page elements, such as
-- videos, tables and placeholders cannot be grouped.
gorChildrenObjectIds :: Lens' GroupObjectsRequest [Text]
gorChildrenObjectIds
= lens _gorChildrenObjectIds
(\ s a -> s{_gorChildrenObjectIds = a})
. _Default
. _Coerce
instance FromJSON GroupObjectsRequest where
parseJSON
= withObject "GroupObjectsRequest"
(\ o ->
GroupObjectsRequest' <$>
(o .:? "groupObjectId") <*>
(o .:? "childrenObjectIds" .!= mempty))
instance ToJSON GroupObjectsRequest where
toJSON GroupObjectsRequest'{..}
= object
(catMaybes
[("groupObjectId" .=) <$> _gorGroupObjectId,
("childrenObjectIds" .=) <$> _gorChildrenObjectIds])
-- | A magnitude in a single direction in the specified units.
--
-- /See:/ 'dimension' smart constructor.
data Dimension =
Dimension'
{ _dMagnitude :: !(Maybe (Textual Double))
, _dUnit :: !(Maybe DimensionUnit)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Dimension' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'dMagnitude'
--
-- * 'dUnit'
dimension
:: Dimension
dimension = Dimension' {_dMagnitude = Nothing, _dUnit = Nothing}
-- | The magnitude.
dMagnitude :: Lens' Dimension (Maybe Double)
dMagnitude
= lens _dMagnitude (\ s a -> s{_dMagnitude = a}) .
mapping _Coerce
-- | The units for magnitude.
dUnit :: Lens' Dimension (Maybe DimensionUnit)
dUnit = lens _dUnit (\ s a -> s{_dUnit = a})
instance FromJSON Dimension where
parseJSON
= withObject "Dimension"
(\ o ->
Dimension' <$>
(o .:? "magnitude") <*> (o .:? "unit"))
instance ToJSON Dimension where
toJSON Dimension'{..}
= object
(catMaybes
[("magnitude" .=) <$> _dMagnitude,
("unit" .=) <$> _dUnit])
-- | Response message from a batch update.
--
-- /See:/ 'batchUpdatePresentationResponse' smart constructor.
data BatchUpdatePresentationResponse =
BatchUpdatePresentationResponse'
{ _bPresentationId :: !(Maybe Text)
, _bReplies :: !(Maybe [Response])
, _bWriteControl :: !(Maybe WriteControl)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'BatchUpdatePresentationResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'bPresentationId'
--
-- * 'bReplies'
--
-- * 'bWriteControl'
batchUpdatePresentationResponse
:: BatchUpdatePresentationResponse
batchUpdatePresentationResponse =
BatchUpdatePresentationResponse'
{_bPresentationId = Nothing, _bReplies = Nothing, _bWriteControl = Nothing}
-- | The presentation the updates were applied to.
bPresentationId :: Lens' BatchUpdatePresentationResponse (Maybe Text)
bPresentationId
= lens _bPresentationId
(\ s a -> s{_bPresentationId = a})
-- | The reply of the updates. This maps 1:1 with the updates, although
-- replies to some requests may be empty.
bReplies :: Lens' BatchUpdatePresentationResponse [Response]
bReplies
= lens _bReplies (\ s a -> s{_bReplies = a}) .
_Default
. _Coerce
-- | The updated write control after applying the request.
bWriteControl :: Lens' BatchUpdatePresentationResponse (Maybe WriteControl)
bWriteControl
= lens _bWriteControl
(\ s a -> s{_bWriteControl = a})
instance FromJSON BatchUpdatePresentationResponse
where
parseJSON
= withObject "BatchUpdatePresentationResponse"
(\ o ->
BatchUpdatePresentationResponse' <$>
(o .:? "presentationId") <*>
(o .:? "replies" .!= mempty)
<*> (o .:? "writeControl"))
instance ToJSON BatchUpdatePresentationResponse where
toJSON BatchUpdatePresentationResponse'{..}
= object
(catMaybes
[("presentationId" .=) <$> _bPresentationId,
("replies" .=) <$> _bReplies,
("writeControl" .=) <$> _bWriteControl])
-- | The object being duplicated may contain other objects, for example when
-- duplicating a slide or a group page element. This map defines how the
-- IDs of duplicated objects are generated: the keys are the IDs of the
-- original objects and its values are the IDs that will be assigned to the
-- corresponding duplicate object. The ID of the source object\'s duplicate
-- may be specified in this map as well, using the same value of the
-- \`object_id\` field as a key and the newly desired ID as the value. All
-- keys must correspond to existing IDs in the presentation. All values
-- must be unique in the presentation and must start with an alphanumeric
-- character or an underscore (matches regex \`[a-zA-Z0-9_]\`); remaining
-- characters may include those as well as a hyphen or colon (matches regex
-- \`[a-zA-Z0-9_-:]\`). The length of the new ID must not be less than 5 or
-- greater than 50. If any IDs of source objects are omitted from the map,
-- a new random ID will be assigned. If the map is empty or unset, all
-- duplicate objects will receive a new random ID.
--
-- /See:/ 'duplicateObjectRequestObjectIds' smart constructor.
newtype DuplicateObjectRequestObjectIds =
DuplicateObjectRequestObjectIds'
{ _doroiAddtional :: HashMap Text Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'DuplicateObjectRequestObjectIds' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'doroiAddtional'
duplicateObjectRequestObjectIds
:: HashMap Text Text -- ^ 'doroiAddtional'
-> DuplicateObjectRequestObjectIds
duplicateObjectRequestObjectIds pDoroiAddtional_ =
DuplicateObjectRequestObjectIds'
{_doroiAddtional = _Coerce # pDoroiAddtional_}
doroiAddtional :: Lens' DuplicateObjectRequestObjectIds (HashMap Text Text)
doroiAddtional
= lens _doroiAddtional
(\ s a -> s{_doroiAddtional = a})
. _Coerce
instance FromJSON DuplicateObjectRequestObjectIds
where
parseJSON
= withObject "DuplicateObjectRequestObjectIds"
(\ o ->
DuplicateObjectRequestObjectIds' <$>
(parseJSONObject o))
instance ToJSON DuplicateObjectRequestObjectIds where
toJSON = toJSON . _doroiAddtional
-- | The result of replacing shapes with a Google Sheets chart.
--
-- /See:/ 'replaceAllShapesWithSheetsChartResponse' smart constructor.
newtype ReplaceAllShapesWithSheetsChartResponse =
ReplaceAllShapesWithSheetsChartResponse'
{ _raswscrOccurrencesChanged :: Maybe (Textual Int32)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ReplaceAllShapesWithSheetsChartResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'raswscrOccurrencesChanged'
replaceAllShapesWithSheetsChartResponse
:: ReplaceAllShapesWithSheetsChartResponse
replaceAllShapesWithSheetsChartResponse =
ReplaceAllShapesWithSheetsChartResponse'
{_raswscrOccurrencesChanged = Nothing}
-- | The number of shapes replaced with charts.
raswscrOccurrencesChanged :: Lens' ReplaceAllShapesWithSheetsChartResponse (Maybe Int32)
raswscrOccurrencesChanged
= lens _raswscrOccurrencesChanged
(\ s a -> s{_raswscrOccurrencesChanged = a})
. mapping _Coerce
instance FromJSON
ReplaceAllShapesWithSheetsChartResponse
where
parseJSON
= withObject
"ReplaceAllShapesWithSheetsChartResponse"
(\ o ->
ReplaceAllShapesWithSheetsChartResponse' <$>
(o .:? "occurrencesChanged"))
instance ToJSON
ReplaceAllShapesWithSheetsChartResponse
where
toJSON ReplaceAllShapesWithSheetsChartResponse'{..}
= object
(catMaybes
[("occurrencesChanged" .=) <$>
_raswscrOccurrencesChanged])
-- | Creates a new table.
--
-- /See:/ 'createTableRequest' smart constructor.
data CreateTableRequest =
CreateTableRequest'
{ _ctrObjectId :: !(Maybe Text)
, _ctrRows :: !(Maybe (Textual Int32))
, _ctrElementProperties :: !(Maybe PageElementProperties)
, _ctrColumns :: !(Maybe (Textual Int32))
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'CreateTableRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ctrObjectId'
--
-- * 'ctrRows'
--
-- * 'ctrElementProperties'
--
-- * 'ctrColumns'
createTableRequest
:: CreateTableRequest
createTableRequest =
CreateTableRequest'
{ _ctrObjectId = Nothing
, _ctrRows = Nothing
, _ctrElementProperties = Nothing
, _ctrColumns = Nothing
}
-- | A user-supplied object ID. If you specify an ID, it must be unique among
-- all pages and page elements in the presentation. The ID must start with
-- an alphanumeric character or an underscore (matches regex
-- \`[a-zA-Z0-9_]\`); remaining characters may include those as well as a
-- hyphen or colon (matches regex \`[a-zA-Z0-9_-:]\`). The length of the ID
-- must not be less than 5 or greater than 50. If you don\'t specify an ID,
-- a unique one is generated.
ctrObjectId :: Lens' CreateTableRequest (Maybe Text)
ctrObjectId
= lens _ctrObjectId (\ s a -> s{_ctrObjectId = a})
-- | Number of rows in the table.
ctrRows :: Lens' CreateTableRequest (Maybe Int32)
ctrRows
= lens _ctrRows (\ s a -> s{_ctrRows = a}) .
mapping _Coerce
-- | The element properties for the table. The table will be created at the
-- provided size, subject to a minimum size. If no size is provided, the
-- table will be automatically sized. Table transforms must have a scale of
-- 1 and no shear components. If no transform is provided, the table will
-- be centered on the page.
ctrElementProperties :: Lens' CreateTableRequest (Maybe PageElementProperties)
ctrElementProperties
= lens _ctrElementProperties
(\ s a -> s{_ctrElementProperties = a})
-- | Number of columns in the table.
ctrColumns :: Lens' CreateTableRequest (Maybe Int32)
ctrColumns
= lens _ctrColumns (\ s a -> s{_ctrColumns = a}) .
mapping _Coerce
instance FromJSON CreateTableRequest where
parseJSON
= withObject "CreateTableRequest"
(\ o ->
CreateTableRequest' <$>
(o .:? "objectId") <*> (o .:? "rows") <*>
(o .:? "elementProperties")
<*> (o .:? "columns"))
instance ToJSON CreateTableRequest where
toJSON CreateTableRequest'{..}
= object
(catMaybes
[("objectId" .=) <$> _ctrObjectId,
("rows" .=) <$> _ctrRows,
("elementProperties" .=) <$> _ctrElementProperties,
("columns" .=) <$> _ctrColumns])
-- | The border styling properties of the TableBorderCell.
--
-- /See:/ 'tableBOrderProperties' smart constructor.
data TableBOrderProperties =
TableBOrderProperties'
{ _tbopTableBOrderFill :: !(Maybe TableBOrderFill)
, _tbopWeight :: !(Maybe Dimension)
, _tbopDashStyle :: !(Maybe TableBOrderPropertiesDashStyle)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'TableBOrderProperties' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'tbopTableBOrderFill'
--
-- * 'tbopWeight'
--
-- * 'tbopDashStyle'
tableBOrderProperties
:: TableBOrderProperties
tableBOrderProperties =
TableBOrderProperties'
{ _tbopTableBOrderFill = Nothing
, _tbopWeight = Nothing
, _tbopDashStyle = Nothing
}
-- | The fill of the table border.
tbopTableBOrderFill :: Lens' TableBOrderProperties (Maybe TableBOrderFill)
tbopTableBOrderFill
= lens _tbopTableBOrderFill
(\ s a -> s{_tbopTableBOrderFill = a})
-- | The thickness of the border.
tbopWeight :: Lens' TableBOrderProperties (Maybe Dimension)
tbopWeight
= lens _tbopWeight (\ s a -> s{_tbopWeight = a})
-- | The dash style of the border.
tbopDashStyle :: Lens' TableBOrderProperties (Maybe TableBOrderPropertiesDashStyle)
tbopDashStyle
= lens _tbopDashStyle
(\ s a -> s{_tbopDashStyle = a})
instance FromJSON TableBOrderProperties where
parseJSON
= withObject "TableBOrderProperties"
(\ o ->
TableBOrderProperties' <$>
(o .:? "tableBorderFill") <*> (o .:? "weight") <*>
(o .:? "dashStyle"))
instance ToJSON TableBOrderProperties where
toJSON TableBOrderProperties'{..}
= object
(catMaybes
[("tableBorderFill" .=) <$> _tbopTableBOrderFill,
("weight" .=) <$> _tbopWeight,
("dashStyle" .=) <$> _tbopDashStyle])
-- | A single response from an update.
--
-- /See:/ 'response' smart constructor.
data Response =
Response'
{ _rReplaceAllShapesWithImage :: !(Maybe ReplaceAllShapesWithImageResponse)
, _rCreateLine :: !(Maybe CreateLineResponse)
, _rReplaceAllText :: !(Maybe ReplaceAllTextResponse)
, _rReplaceAllShapesWithSheetsChart :: !(Maybe ReplaceAllShapesWithSheetsChartResponse)
, _rCreateShape :: !(Maybe CreateShapeResponse)
, _rGroupObjects :: !(Maybe GroupObjectsResponse)
, _rCreateSheetsChart :: !(Maybe CreateSheetsChartResponse)
, _rDuplicateObject :: !(Maybe DuplicateObjectResponse)
, _rCreateTable :: !(Maybe CreateTableResponse)
, _rCreateVideo :: !(Maybe CreateVideoResponse)
, _rCreateImage :: !(Maybe CreateImageResponse)
, _rCreateSlide :: !(Maybe CreateSlideResponse)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Response' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'rReplaceAllShapesWithImage'
--
-- * 'rCreateLine'
--
-- * 'rReplaceAllText'
--
-- * 'rReplaceAllShapesWithSheetsChart'
--
-- * 'rCreateShape'
--
-- * 'rGroupObjects'
--
-- * 'rCreateSheetsChart'
--
-- * 'rDuplicateObject'
--
-- * 'rCreateTable'
--
-- * 'rCreateVideo'
--
-- * 'rCreateImage'
--
-- * 'rCreateSlide'
response
:: Response
response =
Response'
{ _rReplaceAllShapesWithImage = Nothing
, _rCreateLine = Nothing
, _rReplaceAllText = Nothing
, _rReplaceAllShapesWithSheetsChart = Nothing
, _rCreateShape = Nothing
, _rGroupObjects = Nothing
, _rCreateSheetsChart = Nothing
, _rDuplicateObject = Nothing
, _rCreateTable = Nothing
, _rCreateVideo = Nothing
, _rCreateImage = Nothing
, _rCreateSlide = Nothing
}
-- | The result of replacing all shapes matching some criteria with an image.
rReplaceAllShapesWithImage :: Lens' Response (Maybe ReplaceAllShapesWithImageResponse)
rReplaceAllShapesWithImage
= lens _rReplaceAllShapesWithImage
(\ s a -> s{_rReplaceAllShapesWithImage = a})
-- | The result of creating a line.
rCreateLine :: Lens' Response (Maybe CreateLineResponse)
rCreateLine
= lens _rCreateLine (\ s a -> s{_rCreateLine = a})
-- | The result of replacing text.
rReplaceAllText :: Lens' Response (Maybe ReplaceAllTextResponse)
rReplaceAllText
= lens _rReplaceAllText
(\ s a -> s{_rReplaceAllText = a})
-- | The result of replacing all shapes matching some criteria with a Google
-- Sheets chart.
rReplaceAllShapesWithSheetsChart :: Lens' Response (Maybe ReplaceAllShapesWithSheetsChartResponse)
rReplaceAllShapesWithSheetsChart
= lens _rReplaceAllShapesWithSheetsChart
(\ s a -> s{_rReplaceAllShapesWithSheetsChart = a})
-- | The result of creating a shape.
rCreateShape :: Lens' Response (Maybe CreateShapeResponse)
rCreateShape
= lens _rCreateShape (\ s a -> s{_rCreateShape = a})
-- | The result of grouping objects.
rGroupObjects :: Lens' Response (Maybe GroupObjectsResponse)
rGroupObjects
= lens _rGroupObjects
(\ s a -> s{_rGroupObjects = a})
-- | The result of creating a Google Sheets chart.
rCreateSheetsChart :: Lens' Response (Maybe CreateSheetsChartResponse)
rCreateSheetsChart
= lens _rCreateSheetsChart
(\ s a -> s{_rCreateSheetsChart = a})
-- | The result of duplicating an object.
rDuplicateObject :: Lens' Response (Maybe DuplicateObjectResponse)
rDuplicateObject
= lens _rDuplicateObject
(\ s a -> s{_rDuplicateObject = a})
-- | The result of creating a table.
rCreateTable :: Lens' Response (Maybe CreateTableResponse)
rCreateTable
= lens _rCreateTable (\ s a -> s{_rCreateTable = a})
-- | The result of creating a video.
rCreateVideo :: Lens' Response (Maybe CreateVideoResponse)
rCreateVideo
= lens _rCreateVideo (\ s a -> s{_rCreateVideo = a})
-- | The result of creating an image.
rCreateImage :: Lens' Response (Maybe CreateImageResponse)
rCreateImage
= lens _rCreateImage (\ s a -> s{_rCreateImage = a})
-- | The result of creating a slide.
rCreateSlide :: Lens' Response (Maybe CreateSlideResponse)
rCreateSlide
= lens _rCreateSlide (\ s a -> s{_rCreateSlide = a})
instance FromJSON Response where
parseJSON
= withObject "Response"
(\ o ->
Response' <$>
(o .:? "replaceAllShapesWithImage") <*>
(o .:? "createLine")
<*> (o .:? "replaceAllText")
<*> (o .:? "replaceAllShapesWithSheetsChart")
<*> (o .:? "createShape")
<*> (o .:? "groupObjects")
<*> (o .:? "createSheetsChart")
<*> (o .:? "duplicateObject")
<*> (o .:? "createTable")
<*> (o .:? "createVideo")
<*> (o .:? "createImage")
<*> (o .:? "createSlide"))
instance ToJSON Response where
toJSON Response'{..}
= object
(catMaybes
[("replaceAllShapesWithImage" .=) <$>
_rReplaceAllShapesWithImage,
("createLine" .=) <$> _rCreateLine,
("replaceAllText" .=) <$> _rReplaceAllText,
("replaceAllShapesWithSheetsChart" .=) <$>
_rReplaceAllShapesWithSheetsChart,
("createShape" .=) <$> _rCreateShape,
("groupObjects" .=) <$> _rGroupObjects,
("createSheetsChart" .=) <$> _rCreateSheetsChart,
("duplicateObject" .=) <$> _rDuplicateObject,
("createTable" .=) <$> _rCreateTable,
("createVideo" .=) <$> _rCreateVideo,
("createImage" .=) <$> _rCreateImage,
("createSlide" .=) <$> _rCreateSlide])
-- | A color that can either be fully opaque or fully transparent.
--
-- /See:/ 'optionalColor' smart constructor.
newtype OptionalColor =
OptionalColor'
{ _ocOpaqueColor :: Maybe OpaqueColor
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'OptionalColor' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ocOpaqueColor'
optionalColor
:: OptionalColor
optionalColor = OptionalColor' {_ocOpaqueColor = Nothing}
-- | If set, this will be used as an opaque color. If unset, this represents
-- a transparent color.
ocOpaqueColor :: Lens' OptionalColor (Maybe OpaqueColor)
ocOpaqueColor
= lens _ocOpaqueColor
(\ s a -> s{_ocOpaqueColor = a})
instance FromJSON OptionalColor where
parseJSON
= withObject "OptionalColor"
(\ o -> OptionalColor' <$> (o .:? "opaqueColor"))
instance ToJSON OptionalColor where
toJSON OptionalColor'{..}
= object
(catMaybes [("opaqueColor" .=) <$> _ocOpaqueColor])
-- | Duplicates a slide or page element. When duplicating a slide, the
-- duplicate slide will be created immediately following the specified
-- slide. When duplicating a page element, the duplicate will be placed on
-- the same page at the same position as the original.
--
-- /See:/ 'duplicateObjectRequest' smart constructor.
data DuplicateObjectRequest =
DuplicateObjectRequest'
{ _dorObjectId :: !(Maybe Text)
, _dorObjectIds :: !(Maybe DuplicateObjectRequestObjectIds)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'DuplicateObjectRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'dorObjectId'
--
-- * 'dorObjectIds'
duplicateObjectRequest
:: DuplicateObjectRequest
duplicateObjectRequest =
DuplicateObjectRequest' {_dorObjectId = Nothing, _dorObjectIds = Nothing}
-- | The ID of the object to duplicate.
dorObjectId :: Lens' DuplicateObjectRequest (Maybe Text)
dorObjectId
= lens _dorObjectId (\ s a -> s{_dorObjectId = a})
-- | The object being duplicated may contain other objects, for example when
-- duplicating a slide or a group page element. This map defines how the
-- IDs of duplicated objects are generated: the keys are the IDs of the
-- original objects and its values are the IDs that will be assigned to the
-- corresponding duplicate object. The ID of the source object\'s duplicate
-- may be specified in this map as well, using the same value of the
-- \`object_id\` field as a key and the newly desired ID as the value. All
-- keys must correspond to existing IDs in the presentation. All values
-- must be unique in the presentation and must start with an alphanumeric
-- character or an underscore (matches regex \`[a-zA-Z0-9_]\`); remaining
-- characters may include those as well as a hyphen or colon (matches regex
-- \`[a-zA-Z0-9_-:]\`). The length of the new ID must not be less than 5 or
-- greater than 50. If any IDs of source objects are omitted from the map,
-- a new random ID will be assigned. If the map is empty or unset, all
-- duplicate objects will receive a new random ID.
dorObjectIds :: Lens' DuplicateObjectRequest (Maybe DuplicateObjectRequestObjectIds)
dorObjectIds
= lens _dorObjectIds (\ s a -> s{_dorObjectIds = a})
instance FromJSON DuplicateObjectRequest where
parseJSON
= withObject "DuplicateObjectRequest"
(\ o ->
DuplicateObjectRequest' <$>
(o .:? "objectId") <*> (o .:? "objectIds"))
instance ToJSON DuplicateObjectRequest where
toJSON DuplicateObjectRequest'{..}
= object
(catMaybes
[("objectId" .=) <$> _dorObjectId,
("objectIds" .=) <$> _dorObjectIds])
-- | Ungroups objects, such as groups.
--
-- /See:/ 'unGroupObjectsRequest' smart constructor.
newtype UnGroupObjectsRequest =
UnGroupObjectsRequest'
{ _ugorObjectIds :: Maybe [Text]
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'UnGroupObjectsRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ugorObjectIds'
unGroupObjectsRequest
:: UnGroupObjectsRequest
unGroupObjectsRequest = UnGroupObjectsRequest' {_ugorObjectIds = Nothing}
-- | The object IDs of the objects to ungroup. Only groups that are not
-- inside other groups can be ungrouped. All the groups should be on the
-- same page. The group itself is deleted. The visual sizes and positions
-- of all the children are preserved.
ugorObjectIds :: Lens' UnGroupObjectsRequest [Text]
ugorObjectIds
= lens _ugorObjectIds
(\ s a -> s{_ugorObjectIds = a})
. _Default
. _Coerce
instance FromJSON UnGroupObjectsRequest where
parseJSON
= withObject "UnGroupObjectsRequest"
(\ o ->
UnGroupObjectsRequest' <$>
(o .:? "objectIds" .!= mempty))
instance ToJSON UnGroupObjectsRequest where
toJSON UnGroupObjectsRequest'{..}
= object
(catMaybes [("objectIds" .=) <$> _ugorObjectIds])
-- | A page in a presentation.
--
-- /See:/ 'page' smart constructor.
data Page =
Page'
{ _pNotesProperties :: !(Maybe NotesProperties)
, _pMasterProperties :: !(Maybe MasterProperties)
, _pObjectId :: !(Maybe Text)
, _pPageElements :: !(Maybe [PageElement])
, _pSlideProperties :: !(Maybe SlideProperties)
, _pPageProperties :: !(Maybe PageProperties)
, _pLayoutProperties :: !(Maybe LayoutProperties)
, _pPageType :: !(Maybe PagePageType)
, _pRevisionId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Page' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pNotesProperties'
--
-- * 'pMasterProperties'
--
-- * 'pObjectId'
--
-- * 'pPageElements'
--
-- * 'pSlideProperties'
--
-- * 'pPageProperties'
--
-- * 'pLayoutProperties'
--
-- * 'pPageType'
--
-- * 'pRevisionId'
page
:: Page
page =
Page'
{ _pNotesProperties = Nothing
, _pMasterProperties = Nothing
, _pObjectId = Nothing
, _pPageElements = Nothing
, _pSlideProperties = Nothing
, _pPageProperties = Nothing
, _pLayoutProperties = Nothing
, _pPageType = Nothing
, _pRevisionId = Nothing
}
-- | Notes specific properties. Only set if page_type = NOTES.
pNotesProperties :: Lens' Page (Maybe NotesProperties)
pNotesProperties
= lens _pNotesProperties
(\ s a -> s{_pNotesProperties = a})
-- | Master specific properties. Only set if page_type = MASTER.
pMasterProperties :: Lens' Page (Maybe MasterProperties)
pMasterProperties
= lens _pMasterProperties
(\ s a -> s{_pMasterProperties = a})
-- | The object ID for this page. Object IDs used by Page and PageElement
-- share the same namespace.
pObjectId :: Lens' Page (Maybe Text)
pObjectId
= lens _pObjectId (\ s a -> s{_pObjectId = a})
-- | The page elements rendered on the page.
pPageElements :: Lens' Page [PageElement]
pPageElements
= lens _pPageElements
(\ s a -> s{_pPageElements = a})
. _Default
. _Coerce
-- | Slide specific properties. Only set if page_type = SLIDE.
pSlideProperties :: Lens' Page (Maybe SlideProperties)
pSlideProperties
= lens _pSlideProperties
(\ s a -> s{_pSlideProperties = a})
-- | The properties of the page.
pPageProperties :: Lens' Page (Maybe PageProperties)
pPageProperties
= lens _pPageProperties
(\ s a -> s{_pPageProperties = a})
-- | Layout specific properties. Only set if page_type = LAYOUT.
pLayoutProperties :: Lens' Page (Maybe LayoutProperties)
pLayoutProperties
= lens _pLayoutProperties
(\ s a -> s{_pLayoutProperties = a})
-- | The type of the page.
pPageType :: Lens' Page (Maybe PagePageType)
pPageType
= lens _pPageType (\ s a -> s{_pPageType = a})
-- | The revision ID of the presentation containing this page. Can be used in
-- update requests to assert that the presentation revision hasn\'t changed
-- since the last read operation. Only populated if the user has edit
-- access to the presentation. The format of the revision ID may change
-- over time, so it should be treated opaquely. A returned revision ID is
-- only guaranteed to be valid for 24 hours after it has been returned and
-- cannot be shared across users. If the revision ID is unchanged between
-- calls, then the presentation has not changed. Conversely, a changed ID
-- (for the same presentation and user) usually means the presentation has
-- been updated; however, a changed ID can also be due to internal factors
-- such as ID format changes.
pRevisionId :: Lens' Page (Maybe Text)
pRevisionId
= lens _pRevisionId (\ s a -> s{_pRevisionId = a})
instance FromJSON Page where
parseJSON
= withObject "Page"
(\ o ->
Page' <$>
(o .:? "notesProperties") <*>
(o .:? "masterProperties")
<*> (o .:? "objectId")
<*> (o .:? "pageElements" .!= mempty)
<*> (o .:? "slideProperties")
<*> (o .:? "pageProperties")
<*> (o .:? "layoutProperties")
<*> (o .:? "pageType")
<*> (o .:? "revisionId"))
instance ToJSON Page where
toJSON Page'{..}
= object
(catMaybes
[("notesProperties" .=) <$> _pNotesProperties,
("masterProperties" .=) <$> _pMasterProperties,
("objectId" .=) <$> _pObjectId,
("pageElements" .=) <$> _pPageElements,
("slideProperties" .=) <$> _pSlideProperties,
("pageProperties" .=) <$> _pPageProperties,
("layoutProperties" .=) <$> _pLayoutProperties,
("pageType" .=) <$> _pPageType,
("revisionId" .=) <$> _pRevisionId])
-- | The result of replacing text.
--
-- /See:/ 'replaceAllTextResponse' smart constructor.
newtype ReplaceAllTextResponse =
ReplaceAllTextResponse'
{ _ratrOccurrencesChanged :: Maybe (Textual Int32)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ReplaceAllTextResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ratrOccurrencesChanged'
replaceAllTextResponse
:: ReplaceAllTextResponse
replaceAllTextResponse =
ReplaceAllTextResponse' {_ratrOccurrencesChanged = Nothing}
-- | The number of occurrences changed by replacing all text.
ratrOccurrencesChanged :: Lens' ReplaceAllTextResponse (Maybe Int32)
ratrOccurrencesChanged
= lens _ratrOccurrencesChanged
(\ s a -> s{_ratrOccurrencesChanged = a})
. mapping _Coerce
instance FromJSON ReplaceAllTextResponse where
parseJSON
= withObject "ReplaceAllTextResponse"
(\ o ->
ReplaceAllTextResponse' <$>
(o .:? "occurrencesChanged"))
instance ToJSON ReplaceAllTextResponse where
toJSON ReplaceAllTextResponse'{..}
= object
(catMaybes
[("occurrencesChanged" .=) <$>
_ratrOccurrencesChanged])
-- | Describes the bullet of a paragraph.
--
-- /See:/ 'bullet' smart constructor.
data Bullet =
Bullet'
{ _bGlyph :: !(Maybe Text)
, _bListId :: !(Maybe Text)
, _bNestingLevel :: !(Maybe (Textual Int32))
, _bBulletStyle :: !(Maybe TextStyle)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Bullet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'bGlyph'
--
-- * 'bListId'
--
-- * 'bNestingLevel'
--
-- * 'bBulletStyle'
bullet
:: Bullet
bullet =
Bullet'
{ _bGlyph = Nothing
, _bListId = Nothing
, _bNestingLevel = Nothing
, _bBulletStyle = Nothing
}
-- | The rendered bullet glyph for this paragraph.
bGlyph :: Lens' Bullet (Maybe Text)
bGlyph = lens _bGlyph (\ s a -> s{_bGlyph = a})
-- | The ID of the list this paragraph belongs to.
bListId :: Lens' Bullet (Maybe Text)
bListId = lens _bListId (\ s a -> s{_bListId = a})
-- | The nesting level of this paragraph in the list.
bNestingLevel :: Lens' Bullet (Maybe Int32)
bNestingLevel
= lens _bNestingLevel
(\ s a -> s{_bNestingLevel = a})
. mapping _Coerce
-- | The paragraph specific text style applied to this bullet.
bBulletStyle :: Lens' Bullet (Maybe TextStyle)
bBulletStyle
= lens _bBulletStyle (\ s a -> s{_bBulletStyle = a})
instance FromJSON Bullet where
parseJSON
= withObject "Bullet"
(\ o ->
Bullet' <$>
(o .:? "glyph") <*> (o .:? "listId") <*>
(o .:? "nestingLevel")
<*> (o .:? "bulletStyle"))
instance ToJSON Bullet where
toJSON Bullet'{..}
= object
(catMaybes
[("glyph" .=) <$> _bGlyph,
("listId" .=) <$> _bListId,
("nestingLevel" .=) <$> _bNestingLevel,
("bulletStyle" .=) <$> _bBulletStyle])
-- | Update the properties of an Image.
--
-- /See:/ 'updateImagePropertiesRequest' smart constructor.
data UpdateImagePropertiesRequest =
UpdateImagePropertiesRequest'
{ _uiprObjectId :: !(Maybe Text)
, _uiprImageProperties :: !(Maybe ImageProperties)
, _uiprFields :: !(Maybe GFieldMask)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'UpdateImagePropertiesRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'uiprObjectId'
--
-- * 'uiprImageProperties'
--
-- * 'uiprFields'
updateImagePropertiesRequest
:: UpdateImagePropertiesRequest
updateImagePropertiesRequest =
UpdateImagePropertiesRequest'
{ _uiprObjectId = Nothing
, _uiprImageProperties = Nothing
, _uiprFields = Nothing
}
-- | The object ID of the image the updates are applied to.
uiprObjectId :: Lens' UpdateImagePropertiesRequest (Maybe Text)
uiprObjectId
= lens _uiprObjectId (\ s a -> s{_uiprObjectId = a})
-- | The image properties to update.
uiprImageProperties :: Lens' UpdateImagePropertiesRequest (Maybe ImageProperties)
uiprImageProperties
= lens _uiprImageProperties
(\ s a -> s{_uiprImageProperties = a})
-- | The fields that should be updated. At least one field must be specified.
-- The root \`imageProperties\` is implied and should not be specified. A
-- single \`\"*\"\` can be used as short-hand for listing every field. For
-- example to update the image outline color, set \`fields\` to
-- \`\"outline.outlineFill.solidFill.color\"\`. To reset a property to its
-- default value, include its field name in the field mask but leave the
-- field itself unset.
uiprFields :: Lens' UpdateImagePropertiesRequest (Maybe GFieldMask)
uiprFields
= lens _uiprFields (\ s a -> s{_uiprFields = a})
instance FromJSON UpdateImagePropertiesRequest where
parseJSON
= withObject "UpdateImagePropertiesRequest"
(\ o ->
UpdateImagePropertiesRequest' <$>
(o .:? "objectId") <*> (o .:? "imageProperties") <*>
(o .:? "fields"))
instance ToJSON UpdateImagePropertiesRequest where
toJSON UpdateImagePropertiesRequest'{..}
= object
(catMaybes
[("objectId" .=) <$> _uiprObjectId,
("imageProperties" .=) <$> _uiprImageProperties,
("fields" .=) <$> _uiprFields])
-- | The properties of Page that are only relevant for pages with page_type
-- SLIDE.
--
-- /See:/ 'slideProperties' smart constructor.
data SlideProperties =
SlideProperties'
{ _spLayoutObjectId :: !(Maybe Text)
, _spMasterObjectId :: !(Maybe Text)
, _spIsSkipped :: !(Maybe Bool)
, _spNotesPage :: !(Maybe Page)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'SlideProperties' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'spLayoutObjectId'
--
-- * 'spMasterObjectId'
--
-- * 'spIsSkipped'
--
-- * 'spNotesPage'
slideProperties
:: SlideProperties
slideProperties =
SlideProperties'
{ _spLayoutObjectId = Nothing
, _spMasterObjectId = Nothing
, _spIsSkipped = Nothing
, _spNotesPage = Nothing
}
-- | The object ID of the layout that this slide is based on. This property
-- is read-only.
spLayoutObjectId :: Lens' SlideProperties (Maybe Text)
spLayoutObjectId
= lens _spLayoutObjectId
(\ s a -> s{_spLayoutObjectId = a})
-- | The object ID of the master that this slide is based on. This property
-- is read-only.
spMasterObjectId :: Lens' SlideProperties (Maybe Text)
spMasterObjectId
= lens _spMasterObjectId
(\ s a -> s{_spMasterObjectId = a})
-- | Whether the slide is skipped in the presentation mode. Defaults to
-- false.
spIsSkipped :: Lens' SlideProperties (Maybe Bool)
spIsSkipped
= lens _spIsSkipped (\ s a -> s{_spIsSkipped = a})
-- | The notes page that this slide is associated with. It defines the visual
-- appearance of a notes page when printing or exporting slides with
-- speaker notes. A notes page inherits properties from the notes master.
-- The placeholder shape with type BODY on the notes page contains the
-- speaker notes for this slide. The ID of this shape is identified by the
-- speakerNotesObjectId field. The notes page is read-only except for the
-- text content and styles of the speaker notes shape. This property is
-- read-only.
spNotesPage :: Lens' SlideProperties (Maybe Page)
spNotesPage
= lens _spNotesPage (\ s a -> s{_spNotesPage = a})
instance FromJSON SlideProperties where
parseJSON
= withObject "SlideProperties"
(\ o ->
SlideProperties' <$>
(o .:? "layoutObjectId") <*> (o .:? "masterObjectId")
<*> (o .:? "isSkipped")
<*> (o .:? "notesPage"))
instance ToJSON SlideProperties where
toJSON SlideProperties'{..}
= object
(catMaybes
[("layoutObjectId" .=) <$> _spLayoutObjectId,
("masterObjectId" .=) <$> _spMasterObjectId,
("isSkipped" .=) <$> _spIsSkipped,
("notesPage" .=) <$> _spNotesPage])
-- | A Google Slides presentation.
--
-- /See:/ 'presentation' smart constructor.
data Presentation =
Presentation'
{ _preSlides :: !(Maybe [Page])
, _preNotesMaster :: !(Maybe Page)
, _preMasters :: !(Maybe [Page])
, _preLocale :: !(Maybe Text)
, _prePresentationId :: !(Maybe Text)
, _preTitle :: !(Maybe Text)
, _preRevisionId :: !(Maybe Text)
, _prePageSize :: !(Maybe Size)
, _preLayouts :: !(Maybe [Page])
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Presentation' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'preSlides'
--
-- * 'preNotesMaster'
--
-- * 'preMasters'
--
-- * 'preLocale'
--
-- * 'prePresentationId'
--
-- * 'preTitle'
--
-- * 'preRevisionId'
--
-- * 'prePageSize'
--
-- * 'preLayouts'
presentation
:: Presentation
presentation =
Presentation'
{ _preSlides = Nothing
, _preNotesMaster = Nothing
, _preMasters = Nothing
, _preLocale = Nothing
, _prePresentationId = Nothing
, _preTitle = Nothing
, _preRevisionId = Nothing
, _prePageSize = Nothing
, _preLayouts = Nothing
}
-- | The slides in the presentation. A slide inherits properties from a slide
-- layout.
preSlides :: Lens' Presentation [Page]
preSlides
= lens _preSlides (\ s a -> s{_preSlides = a}) .
_Default
. _Coerce
-- | The notes master in the presentation. It serves three purposes: -
-- Placeholder shapes on a notes master contain the default text styles and
-- shape properties of all placeholder shapes on notes pages. Specifically,
-- a \`SLIDE_IMAGE\` placeholder shape contains the slide thumbnail, and a
-- \`BODY\` placeholder shape contains the speaker notes. - The notes
-- master page properties define the common page properties inherited by
-- all notes pages. - Any other shapes on the notes master appear on all
-- notes pages. The notes master is read-only.
preNotesMaster :: Lens' Presentation (Maybe Page)
preNotesMaster
= lens _preNotesMaster
(\ s a -> s{_preNotesMaster = a})
-- | The slide masters in the presentation. A slide master contains all
-- common page elements and the common properties for a set of layouts.
-- They serve three purposes: - Placeholder shapes on a master contain the
-- default text styles and shape properties of all placeholder shapes on
-- pages that use that master. - The master page properties define the
-- common page properties inherited by its layouts. - Any other shapes on
-- the master slide appear on all slides using that master, regardless of
-- their layout.
preMasters :: Lens' Presentation [Page]
preMasters
= lens _preMasters (\ s a -> s{_preMasters = a}) .
_Default
. _Coerce
-- | The locale of the presentation, as an IETF BCP 47 language tag.
preLocale :: Lens' Presentation (Maybe Text)
preLocale
= lens _preLocale (\ s a -> s{_preLocale = a})
-- | The ID of the presentation.
prePresentationId :: Lens' Presentation (Maybe Text)
prePresentationId
= lens _prePresentationId
(\ s a -> s{_prePresentationId = a})
-- | The title of the presentation.
preTitle :: Lens' Presentation (Maybe Text)
preTitle = lens _preTitle (\ s a -> s{_preTitle = a})
-- | The revision ID of the presentation. Can be used in update requests to
-- assert that the presentation revision hasn\'t changed since the last
-- read operation. Only populated if the user has edit access to the
-- presentation. The format of the revision ID may change over time, so it
-- should be treated opaquely. A returned revision ID is only guaranteed to
-- be valid for 24 hours after it has been returned and cannot be shared
-- across users. If the revision ID is unchanged between calls, then the
-- presentation has not changed. Conversely, a changed ID (for the same
-- presentation and user) usually means the presentation has been updated;
-- however, a changed ID can also be due to internal factors such as ID
-- format changes.
preRevisionId :: Lens' Presentation (Maybe Text)
preRevisionId
= lens _preRevisionId
(\ s a -> s{_preRevisionId = a})
-- | The size of pages in the presentation.
prePageSize :: Lens' Presentation (Maybe Size)
prePageSize
= lens _prePageSize (\ s a -> s{_prePageSize = a})
-- | The layouts in the presentation. A layout is a template that determines
-- how content is arranged and styled on the slides that inherit from that
-- layout.
preLayouts :: Lens' Presentation [Page]
preLayouts
= lens _preLayouts (\ s a -> s{_preLayouts = a}) .
_Default
. _Coerce
instance FromJSON Presentation where
parseJSON
= withObject "Presentation"
(\ o ->
Presentation' <$>
(o .:? "slides" .!= mempty) <*> (o .:? "notesMaster")
<*> (o .:? "masters" .!= mempty)
<*> (o .:? "locale")
<*> (o .:? "presentationId")
<*> (o .:? "title")
<*> (o .:? "revisionId")
<*> (o .:? "pageSize")
<*> (o .:? "layouts" .!= mempty))
instance ToJSON Presentation where
toJSON Presentation'{..}
= object
(catMaybes
[("slides" .=) <$> _preSlides,
("notesMaster" .=) <$> _preNotesMaster,
("masters" .=) <$> _preMasters,
("locale" .=) <$> _preLocale,
("presentationId" .=) <$> _prePresentationId,
("title" .=) <$> _preTitle,
("revisionId" .=) <$> _preRevisionId,
("pageSize" .=) <$> _prePageSize,
("layouts" .=) <$> _preLayouts])
-- | A pair mapping a theme color type to the concrete color it represents.
--
-- /See:/ 'themeColorPair' smart constructor.
data ThemeColorPair =
ThemeColorPair'
{ _tcpColor :: !(Maybe RgbColor)
, _tcpType :: !(Maybe ThemeColorPairType)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ThemeColorPair' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'tcpColor'
--
-- * 'tcpType'
themeColorPair
:: ThemeColorPair
themeColorPair = ThemeColorPair' {_tcpColor = Nothing, _tcpType = Nothing}
-- | The concrete color corresponding to the theme color type above.
tcpColor :: Lens' ThemeColorPair (Maybe RgbColor)
tcpColor = lens _tcpColor (\ s a -> s{_tcpColor = a})
-- | The type of the theme color.
tcpType :: Lens' ThemeColorPair (Maybe ThemeColorPairType)
tcpType = lens _tcpType (\ s a -> s{_tcpType = a})
instance FromJSON ThemeColorPair where
parseJSON
= withObject "ThemeColorPair"
(\ o ->
ThemeColorPair' <$>
(o .:? "color") <*> (o .:? "type"))
instance ToJSON ThemeColorPair where
toJSON ThemeColorPair'{..}
= object
(catMaybes
[("color" .=) <$> _tcpColor,
("type" .=) <$> _tcpType])
-- | The shadow properties of a page element. If these fields are unset, they
-- may be inherited from a parent placeholder if it exists. If there is no
-- parent, the fields will default to the value used for new page elements
-- created in the Slides editor, which may depend on the page element kind.
--
-- /See:/ 'shadow' smart constructor.
data Shadow =
Shadow'
{ _sTransform :: !(Maybe AffineTransform)
, _sColor :: !(Maybe OpaqueColor)
, _sBlurRadius :: !(Maybe Dimension)
, _sRotateWithShape :: !(Maybe Bool)
, _sAlpha :: !(Maybe (Textual Double))
, _sAlignment :: !(Maybe ShadowAlignment)
, _sPropertyState :: !(Maybe ShadowPropertyState)
, _sType :: !(Maybe ShadowType)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Shadow' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'sTransform'
--
-- * 'sColor'
--
-- * 'sBlurRadius'
--
-- * 'sRotateWithShape'
--
-- * 'sAlpha'
--
-- * 'sAlignment'
--
-- * 'sPropertyState'
--
-- * 'sType'
shadow
:: Shadow
shadow =
Shadow'
{ _sTransform = Nothing
, _sColor = Nothing
, _sBlurRadius = Nothing
, _sRotateWithShape = Nothing
, _sAlpha = Nothing
, _sAlignment = Nothing
, _sPropertyState = Nothing
, _sType = Nothing
}
-- | Transform that encodes the translate, scale, and skew of the shadow,
-- relative to the alignment position.
sTransform :: Lens' Shadow (Maybe AffineTransform)
sTransform
= lens _sTransform (\ s a -> s{_sTransform = a})
-- | The shadow color value.
sColor :: Lens' Shadow (Maybe OpaqueColor)
sColor = lens _sColor (\ s a -> s{_sColor = a})
-- | The radius of the shadow blur. The larger the radius, the more diffuse
-- the shadow becomes.
sBlurRadius :: Lens' Shadow (Maybe Dimension)
sBlurRadius
= lens _sBlurRadius (\ s a -> s{_sBlurRadius = a})
-- | Whether the shadow should rotate with the shape. This property is
-- read-only.
sRotateWithShape :: Lens' Shadow (Maybe Bool)
sRotateWithShape
= lens _sRotateWithShape
(\ s a -> s{_sRotateWithShape = a})
-- | The alpha of the shadow\'s color, from 0.0 to 1.0.
sAlpha :: Lens' Shadow (Maybe Double)
sAlpha
= lens _sAlpha (\ s a -> s{_sAlpha = a}) .
mapping _Coerce
-- | The alignment point of the shadow, that sets the origin for translate,
-- scale and skew of the shadow. This property is read-only.
sAlignment :: Lens' Shadow (Maybe ShadowAlignment)
sAlignment
= lens _sAlignment (\ s a -> s{_sAlignment = a})
-- | The shadow property state. Updating the shadow on a page element will
-- implicitly update this field to \`RENDERED\`, unless another value is
-- specified in the same request. To have no shadow on a page element, set
-- this field to \`NOT_RENDERED\`. In this case, any other shadow fields
-- set in the same request will be ignored.
sPropertyState :: Lens' Shadow (Maybe ShadowPropertyState)
sPropertyState
= lens _sPropertyState
(\ s a -> s{_sPropertyState = a})
-- | The type of the shadow. This property is read-only.
sType :: Lens' Shadow (Maybe ShadowType)
sType = lens _sType (\ s a -> s{_sType = a})
instance FromJSON Shadow where
parseJSON
= withObject "Shadow"
(\ o ->
Shadow' <$>
(o .:? "transform") <*> (o .:? "color") <*>
(o .:? "blurRadius")
<*> (o .:? "rotateWithShape")
<*> (o .:? "alpha")
<*> (o .:? "alignment")
<*> (o .:? "propertyState")
<*> (o .:? "type"))
instance ToJSON Shadow where
toJSON Shadow'{..}
= object
(catMaybes
[("transform" .=) <$> _sTransform,
("color" .=) <$> _sColor,
("blurRadius" .=) <$> _sBlurRadius,
("rotateWithShape" .=) <$> _sRotateWithShape,
("alpha" .=) <$> _sAlpha,
("alignment" .=) <$> _sAlignment,
("propertyState" .=) <$> _sPropertyState,
("type" .=) <$> _sType])
-- | Updates the properties of a Slide.
--
-- /See:/ 'updateSlidePropertiesRequest' smart constructor.
data UpdateSlidePropertiesRequest =
UpdateSlidePropertiesRequest'
{ _usprObjectId :: !(Maybe Text)
, _usprSlideProperties :: !(Maybe SlideProperties)
, _usprFields :: !(Maybe GFieldMask)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'UpdateSlidePropertiesRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'usprObjectId'
--
-- * 'usprSlideProperties'
--
-- * 'usprFields'
updateSlidePropertiesRequest
:: UpdateSlidePropertiesRequest
updateSlidePropertiesRequest =
UpdateSlidePropertiesRequest'
{ _usprObjectId = Nothing
, _usprSlideProperties = Nothing
, _usprFields = Nothing
}
-- | The object ID of the slide the update is applied to.
usprObjectId :: Lens' UpdateSlidePropertiesRequest (Maybe Text)
usprObjectId
= lens _usprObjectId (\ s a -> s{_usprObjectId = a})
-- | The slide properties to update.
usprSlideProperties :: Lens' UpdateSlidePropertiesRequest (Maybe SlideProperties)
usprSlideProperties
= lens _usprSlideProperties
(\ s a -> s{_usprSlideProperties = a})
-- | The fields that should be updated. At least one field must be specified.
-- The root \'slideProperties\' is implied and should not be specified. A
-- single \`\"*\"\` can be used as short-hand for listing every field. For
-- example to update whether a slide is skipped, set \`fields\` to
-- \`\"isSkipped\"\`. To reset a property to its default value, include its
-- field name in the field mask but leave the field itself unset.
usprFields :: Lens' UpdateSlidePropertiesRequest (Maybe GFieldMask)
usprFields
= lens _usprFields (\ s a -> s{_usprFields = a})
instance FromJSON UpdateSlidePropertiesRequest where
parseJSON
= withObject "UpdateSlidePropertiesRequest"
(\ o ->
UpdateSlidePropertiesRequest' <$>
(o .:? "objectId") <*> (o .:? "slideProperties") <*>
(o .:? "fields"))
instance ToJSON UpdateSlidePropertiesRequest where
toJSON UpdateSlidePropertiesRequest'{..}
= object
(catMaybes
[("objectId" .=) <$> _usprObjectId,
("slideProperties" .=) <$> _usprSlideProperties,
("fields" .=) <$> _usprFields])
-- | The properties of the Image.
--
-- /See:/ 'imageProperties' smart constructor.
data ImageProperties =
ImageProperties'
{ _ipCropProperties :: !(Maybe CropProperties)
, _ipLink :: !(Maybe Link)
, _ipTransparency :: !(Maybe (Textual Double))
, _ipShadow :: !(Maybe Shadow)
, _ipContrast :: !(Maybe (Textual Double))
, _ipRecolor :: !(Maybe Recolor)
, _ipOutline :: !(Maybe Outline)
, _ipBrightness :: !(Maybe (Textual Double))
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ImageProperties' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ipCropProperties'
--
-- * 'ipLink'
--
-- * 'ipTransparency'
--
-- * 'ipShadow'
--
-- * 'ipContrast'
--
-- * 'ipRecolor'
--
-- * 'ipOutline'
--
-- * 'ipBrightness'
imageProperties
:: ImageProperties
imageProperties =
ImageProperties'
{ _ipCropProperties = Nothing
, _ipLink = Nothing
, _ipTransparency = Nothing
, _ipShadow = Nothing
, _ipContrast = Nothing
, _ipRecolor = Nothing
, _ipOutline = Nothing
, _ipBrightness = Nothing
}
-- | The crop properties of the image. If not set, the image is not cropped.
-- This property is read-only.
ipCropProperties :: Lens' ImageProperties (Maybe CropProperties)
ipCropProperties
= lens _ipCropProperties
(\ s a -> s{_ipCropProperties = a})
-- | The hyperlink destination of the image. If unset, there is no link.
ipLink :: Lens' ImageProperties (Maybe Link)
ipLink = lens _ipLink (\ s a -> s{_ipLink = a})
-- | The transparency effect of the image. The value should be in the
-- interval [0.0, 1.0], where 0 means no effect and 1 means completely
-- transparent. This property is read-only.
ipTransparency :: Lens' ImageProperties (Maybe Double)
ipTransparency
= lens _ipTransparency
(\ s a -> s{_ipTransparency = a})
. mapping _Coerce
-- | The shadow of the image. If not set, the image has no shadow. This
-- property is read-only.
ipShadow :: Lens' ImageProperties (Maybe Shadow)
ipShadow = lens _ipShadow (\ s a -> s{_ipShadow = a})
-- | The contrast effect of the image. The value should be in the interval
-- [-1.0, 1.0], where 0 means no effect. This property is read-only.
ipContrast :: Lens' ImageProperties (Maybe Double)
ipContrast
= lens _ipContrast (\ s a -> s{_ipContrast = a}) .
mapping _Coerce
-- | The recolor effect of the image. If not set, the image is not recolored.
-- This property is read-only.
ipRecolor :: Lens' ImageProperties (Maybe Recolor)
ipRecolor
= lens _ipRecolor (\ s a -> s{_ipRecolor = a})
-- | The outline of the image. If not set, the image has no outline.
ipOutline :: Lens' ImageProperties (Maybe Outline)
ipOutline
= lens _ipOutline (\ s a -> s{_ipOutline = a})
-- | The brightness effect of the image. The value should be in the interval
-- [-1.0, 1.0], where 0 means no effect. This property is read-only.
ipBrightness :: Lens' ImageProperties (Maybe Double)
ipBrightness
= lens _ipBrightness (\ s a -> s{_ipBrightness = a})
. mapping _Coerce
instance FromJSON ImageProperties where
parseJSON
= withObject "ImageProperties"
(\ o ->
ImageProperties' <$>
(o .:? "cropProperties") <*> (o .:? "link") <*>
(o .:? "transparency")
<*> (o .:? "shadow")
<*> (o .:? "contrast")
<*> (o .:? "recolor")
<*> (o .:? "outline")
<*> (o .:? "brightness"))
instance ToJSON ImageProperties where
toJSON ImageProperties'{..}
= object
(catMaybes
[("cropProperties" .=) <$> _ipCropProperties,
("link" .=) <$> _ipLink,
("transparency" .=) <$> _ipTransparency,
("shadow" .=) <$> _ipShadow,
("contrast" .=) <$> _ipContrast,
("recolor" .=) <$> _ipRecolor,
("outline" .=) <$> _ipOutline,
("brightness" .=) <$> _ipBrightness])
-- | A PageElement kind representing a non-connector line, straight
-- connector, curved connector, or bent connector.
--
-- /See:/ 'line' smart constructor.
data Line =
Line'
{ _lLineProperties :: !(Maybe LineProperties)
, _lLineCategory :: !(Maybe LineLineCategory)
, _lLineType :: !(Maybe LineLineType)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Line' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lLineProperties'
--
-- * 'lLineCategory'
--
-- * 'lLineType'
line
:: Line
line =
Line'
{_lLineProperties = Nothing, _lLineCategory = Nothing, _lLineType = Nothing}
-- | The properties of the line.
lLineProperties :: Lens' Line (Maybe LineProperties)
lLineProperties
= lens _lLineProperties
(\ s a -> s{_lLineProperties = a})
-- | The category of the line. It matches the \`category\` specified in
-- CreateLineRequest, and can be updated with UpdateLineCategoryRequest.
lLineCategory :: Lens' Line (Maybe LineLineCategory)
lLineCategory
= lens _lLineCategory
(\ s a -> s{_lLineCategory = a})
-- | The type of the line.
lLineType :: Lens' Line (Maybe LineLineType)
lLineType
= lens _lLineType (\ s a -> s{_lLineType = a})
instance FromJSON Line where
parseJSON
= withObject "Line"
(\ o ->
Line' <$>
(o .:? "lineProperties") <*> (o .:? "lineCategory")
<*> (o .:? "lineType"))
instance ToJSON Line where
toJSON Line'{..}
= object
(catMaybes
[("lineProperties" .=) <$> _lLineProperties,
("lineCategory" .=) <$> _lLineCategory,
("lineType" .=) <$> _lLineType])
-- | The result of creating a video.
--
-- /See:/ 'createVideoResponse' smart constructor.
newtype CreateVideoResponse =
CreateVideoResponse'
{ _cvrObjectId :: Maybe Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'CreateVideoResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cvrObjectId'
createVideoResponse
:: CreateVideoResponse
createVideoResponse = CreateVideoResponse' {_cvrObjectId = Nothing}
-- | The object ID of the created video.
cvrObjectId :: Lens' CreateVideoResponse (Maybe Text)
cvrObjectId
= lens _cvrObjectId (\ s a -> s{_cvrObjectId = a})
instance FromJSON CreateVideoResponse where
parseJSON
= withObject "CreateVideoResponse"
(\ o -> CreateVideoResponse' <$> (o .:? "objectId"))
instance ToJSON CreateVideoResponse where
toJSON CreateVideoResponse'{..}
= object
(catMaybes [("objectId" .=) <$> _cvrObjectId])
-- | Slide layout reference. This may reference either: - A predefined layout
-- - One of the layouts in the presentation.
--
-- /See:/ 'layoutReference' smart constructor.
data LayoutReference =
LayoutReference'
{ _lrPredefinedLayout :: !(Maybe LayoutReferencePredefinedLayout)
, _lrLayoutId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'LayoutReference' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lrPredefinedLayout'
--
-- * 'lrLayoutId'
layoutReference
:: LayoutReference
layoutReference =
LayoutReference' {_lrPredefinedLayout = Nothing, _lrLayoutId = Nothing}
-- | Predefined layout.
lrPredefinedLayout :: Lens' LayoutReference (Maybe LayoutReferencePredefinedLayout)
lrPredefinedLayout
= lens _lrPredefinedLayout
(\ s a -> s{_lrPredefinedLayout = a})
-- | Layout ID: the object ID of one of the layouts in the presentation.
lrLayoutId :: Lens' LayoutReference (Maybe Text)
lrLayoutId
= lens _lrLayoutId (\ s a -> s{_lrLayoutId = a})
instance FromJSON LayoutReference where
parseJSON
= withObject "LayoutReference"
(\ o ->
LayoutReference' <$>
(o .:? "predefinedLayout") <*> (o .:? "layoutId"))
instance ToJSON LayoutReference where
toJSON LayoutReference'{..}
= object
(catMaybes
[("predefinedLayout" .=) <$> _lrPredefinedLayout,
("layoutId" .=) <$> _lrLayoutId])
-- | The fill of the line.
--
-- /See:/ 'lineFill' smart constructor.
newtype LineFill =
LineFill'
{ _lfSolidFill :: Maybe SolidFill
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'LineFill' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lfSolidFill'
lineFill
:: LineFill
lineFill = LineFill' {_lfSolidFill = Nothing}
-- | Solid color fill.
lfSolidFill :: Lens' LineFill (Maybe SolidFill)
lfSolidFill
= lens _lfSolidFill (\ s a -> s{_lfSolidFill = a})
instance FromJSON LineFill where
parseJSON
= withObject "LineFill"
(\ o -> LineFill' <$> (o .:? "solidFill"))
instance ToJSON LineFill where
toJSON LineFill'{..}
= object
(catMaybes [("solidFill" .=) <$> _lfSolidFill])
-- | Updates the transform of a page element. Updating the transform of a
-- group will change the absolute transform of the page elements in that
-- group, which can change their visual appearance. See the documentation
-- for PageElement.transform for more details.
--
-- /See:/ 'updatePageElementTransformRequest' smart constructor.
data UpdatePageElementTransformRequest =
UpdatePageElementTransformRequest'
{ _upetrTransform :: !(Maybe AffineTransform)
, _upetrObjectId :: !(Maybe Text)
, _upetrApplyMode :: !(Maybe UpdatePageElementTransformRequestApplyMode)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'UpdatePageElementTransformRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'upetrTransform'
--
-- * 'upetrObjectId'
--
-- * 'upetrApplyMode'
updatePageElementTransformRequest
:: UpdatePageElementTransformRequest
updatePageElementTransformRequest =
UpdatePageElementTransformRequest'
{ _upetrTransform = Nothing
, _upetrObjectId = Nothing
, _upetrApplyMode = Nothing
}
-- | The input transform matrix used to update the page element.
upetrTransform :: Lens' UpdatePageElementTransformRequest (Maybe AffineTransform)
upetrTransform
= lens _upetrTransform
(\ s a -> s{_upetrTransform = a})
-- | The object ID of the page element to update.
upetrObjectId :: Lens' UpdatePageElementTransformRequest (Maybe Text)
upetrObjectId
= lens _upetrObjectId
(\ s a -> s{_upetrObjectId = a})
-- | The apply mode of the transform update.
upetrApplyMode :: Lens' UpdatePageElementTransformRequest (Maybe UpdatePageElementTransformRequestApplyMode)
upetrApplyMode
= lens _upetrApplyMode
(\ s a -> s{_upetrApplyMode = a})
instance FromJSON UpdatePageElementTransformRequest
where
parseJSON
= withObject "UpdatePageElementTransformRequest"
(\ o ->
UpdatePageElementTransformRequest' <$>
(o .:? "transform") <*> (o .:? "objectId") <*>
(o .:? "applyMode"))
instance ToJSON UpdatePageElementTransformRequest
where
toJSON UpdatePageElementTransformRequest'{..}
= object
(catMaybes
[("transform" .=) <$> _upetrTransform,
("objectId" .=) <$> _upetrObjectId,
("applyMode" .=) <$> _upetrApplyMode])
-- | Inserts rows into a table.
--
-- /See:/ 'insertTableRowsRequest' smart constructor.
data InsertTableRowsRequest =
InsertTableRowsRequest'
{ _itrrInsertBelow :: !(Maybe Bool)
, _itrrNumber :: !(Maybe (Textual Int32))
, _itrrCellLocation :: !(Maybe TableCellLocation)
, _itrrTableObjectId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'InsertTableRowsRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'itrrInsertBelow'
--
-- * 'itrrNumber'
--
-- * 'itrrCellLocation'
--
-- * 'itrrTableObjectId'
insertTableRowsRequest
:: InsertTableRowsRequest
insertTableRowsRequest =
InsertTableRowsRequest'
{ _itrrInsertBelow = Nothing
, _itrrNumber = Nothing
, _itrrCellLocation = Nothing
, _itrrTableObjectId = Nothing
}
-- | Whether to insert new rows below the reference cell location. -
-- \`True\`: insert below the cell. - \`False\`: insert above the cell.
itrrInsertBelow :: Lens' InsertTableRowsRequest (Maybe Bool)
itrrInsertBelow
= lens _itrrInsertBelow
(\ s a -> s{_itrrInsertBelow = a})
-- | The number of rows to be inserted. Maximum 20 per request.
itrrNumber :: Lens' InsertTableRowsRequest (Maybe Int32)
itrrNumber
= lens _itrrNumber (\ s a -> s{_itrrNumber = a}) .
mapping _Coerce
-- | The reference table cell location from which rows will be inserted. A
-- new row will be inserted above (or below) the row where the reference
-- cell is. If the reference cell is a merged cell, a new row will be
-- inserted above (or below) the merged cell.
itrrCellLocation :: Lens' InsertTableRowsRequest (Maybe TableCellLocation)
itrrCellLocation
= lens _itrrCellLocation
(\ s a -> s{_itrrCellLocation = a})
-- | The table to insert rows into.
itrrTableObjectId :: Lens' InsertTableRowsRequest (Maybe Text)
itrrTableObjectId
= lens _itrrTableObjectId
(\ s a -> s{_itrrTableObjectId = a})
instance FromJSON InsertTableRowsRequest where
parseJSON
= withObject "InsertTableRowsRequest"
(\ o ->
InsertTableRowsRequest' <$>
(o .:? "insertBelow") <*> (o .:? "number") <*>
(o .:? "cellLocation")
<*> (o .:? "tableObjectId"))
instance ToJSON InsertTableRowsRequest where
toJSON InsertTableRowsRequest'{..}
= object
(catMaybes
[("insertBelow" .=) <$> _itrrInsertBelow,
("number" .=) <$> _itrrNumber,
("cellLocation" .=) <$> _itrrCellLocation,
("tableObjectId" .=) <$> _itrrTableObjectId])
-- | Unmerges cells in a Table.
--
-- /See:/ 'unmergeTableCellsRequest' smart constructor.
data UnmergeTableCellsRequest =
UnmergeTableCellsRequest'
{ _utcrObjectId :: !(Maybe Text)
, _utcrTableRange :: !(Maybe TableRange)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'UnmergeTableCellsRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'utcrObjectId'
--
-- * 'utcrTableRange'
unmergeTableCellsRequest
:: UnmergeTableCellsRequest
unmergeTableCellsRequest =
UnmergeTableCellsRequest' {_utcrObjectId = Nothing, _utcrTableRange = Nothing}
-- | The object ID of the table.
utcrObjectId :: Lens' UnmergeTableCellsRequest (Maybe Text)
utcrObjectId
= lens _utcrObjectId (\ s a -> s{_utcrObjectId = a})
-- | The table range specifying which cells of the table to unmerge. All
-- merged cells in this range will be unmerged, and cells that are already
-- unmerged will not be affected. If the range has no merged cells, the
-- request will do nothing. If there is text in any of the merged cells,
-- the text will remain in the upper-left (\"head\") cell of the resulting
-- block of unmerged cells.
utcrTableRange :: Lens' UnmergeTableCellsRequest (Maybe TableRange)
utcrTableRange
= lens _utcrTableRange
(\ s a -> s{_utcrTableRange = a})
instance FromJSON UnmergeTableCellsRequest where
parseJSON
= withObject "UnmergeTableCellsRequest"
(\ o ->
UnmergeTableCellsRequest' <$>
(o .:? "objectId") <*> (o .:? "tableRange"))
instance ToJSON UnmergeTableCellsRequest where
toJSON UnmergeTableCellsRequest'{..}
= object
(catMaybes
[("objectId" .=) <$> _utcrObjectId,
("tableRange" .=) <$> _utcrTableRange])
-- | A PageElement kind representing a video.
--
-- /See:/ 'video' smart constructor.
data Video =
Video'
{ _vURL :: !(Maybe Text)
, _vSource :: !(Maybe VideoSource)
, _vId :: !(Maybe Text)
, _vVideoProperties :: !(Maybe VideoProperties)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Video' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'vURL'
--
-- * 'vSource'
--
-- * 'vId'
--
-- * 'vVideoProperties'
video
:: Video
video =
Video'
{ _vURL = Nothing
, _vSource = Nothing
, _vId = Nothing
, _vVideoProperties = Nothing
}
-- | An URL to a video. The URL is valid as long as the source video exists
-- and sharing settings do not change.
vURL :: Lens' Video (Maybe Text)
vURL = lens _vURL (\ s a -> s{_vURL = a})
-- | The video source.
vSource :: Lens' Video (Maybe VideoSource)
vSource = lens _vSource (\ s a -> s{_vSource = a})
-- | The video source\'s unique identifier for this video.
vId :: Lens' Video (Maybe Text)
vId = lens _vId (\ s a -> s{_vId = a})
-- | The properties of the video.
vVideoProperties :: Lens' Video (Maybe VideoProperties)
vVideoProperties
= lens _vVideoProperties
(\ s a -> s{_vVideoProperties = a})
instance FromJSON Video where
parseJSON
= withObject "Video"
(\ o ->
Video' <$>
(o .:? "url") <*> (o .:? "source") <*> (o .:? "id")
<*> (o .:? "videoProperties"))
instance ToJSON Video where
toJSON Video'{..}
= object
(catMaybes
[("url" .=) <$> _vURL, ("source" .=) <$> _vSource,
("id" .=) <$> _vId,
("videoProperties" .=) <$> _vVideoProperties])
-- | Updates the properties of a Table column.
--
-- /See:/ 'updateTableColumnPropertiesRequest' smart constructor.
data UpdateTableColumnPropertiesRequest =
UpdateTableColumnPropertiesRequest'
{ _utcprObjectId :: !(Maybe Text)
, _utcprTableColumnProperties :: !(Maybe TableColumnProperties)
, _utcprFields :: !(Maybe GFieldMask)
, _utcprColumnIndices :: !(Maybe [Textual Int32])
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'UpdateTableColumnPropertiesRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'utcprObjectId'
--
-- * 'utcprTableColumnProperties'
--
-- * 'utcprFields'
--
-- * 'utcprColumnIndices'
updateTableColumnPropertiesRequest
:: UpdateTableColumnPropertiesRequest
updateTableColumnPropertiesRequest =
UpdateTableColumnPropertiesRequest'
{ _utcprObjectId = Nothing
, _utcprTableColumnProperties = Nothing
, _utcprFields = Nothing
, _utcprColumnIndices = Nothing
}
-- | The object ID of the table.
utcprObjectId :: Lens' UpdateTableColumnPropertiesRequest (Maybe Text)
utcprObjectId
= lens _utcprObjectId
(\ s a -> s{_utcprObjectId = a})
-- | The table column properties to update. If the value of
-- \`table_column_properties#column_width\` in the request is less than
-- 406,400 EMU (32 points), a 400 bad request error is returned.
utcprTableColumnProperties :: Lens' UpdateTableColumnPropertiesRequest (Maybe TableColumnProperties)
utcprTableColumnProperties
= lens _utcprTableColumnProperties
(\ s a -> s{_utcprTableColumnProperties = a})
-- | The fields that should be updated. At least one field must be specified.
-- The root \`tableColumnProperties\` is implied and should not be
-- specified. A single \`\"*\"\` can be used as short-hand for listing
-- every field. For example to update the column width, set \`fields\` to
-- \`\"column_width\"\`. If \'\"column_width\"\' is included in the field
-- mask but the property is left unset, the column width will default to
-- 406,400 EMU (32 points).
utcprFields :: Lens' UpdateTableColumnPropertiesRequest (Maybe GFieldMask)
utcprFields
= lens _utcprFields (\ s a -> s{_utcprFields = a})
-- | The list of zero-based indices specifying which columns to update. If no
-- indices are provided, all columns in the table will be updated.
utcprColumnIndices :: Lens' UpdateTableColumnPropertiesRequest [Int32]
utcprColumnIndices
= lens _utcprColumnIndices
(\ s a -> s{_utcprColumnIndices = a})
. _Default
. _Coerce
instance FromJSON UpdateTableColumnPropertiesRequest
where
parseJSON
= withObject "UpdateTableColumnPropertiesRequest"
(\ o ->
UpdateTableColumnPropertiesRequest' <$>
(o .:? "objectId") <*>
(o .:? "tableColumnProperties")
<*> (o .:? "fields")
<*> (o .:? "columnIndices" .!= mempty))
instance ToJSON UpdateTableColumnPropertiesRequest
where
toJSON UpdateTableColumnPropertiesRequest'{..}
= object
(catMaybes
[("objectId" .=) <$> _utcprObjectId,
("tableColumnProperties" .=) <$>
_utcprTableColumnProperties,
("fields" .=) <$> _utcprFields,
("columnIndices" .=) <$> _utcprColumnIndices])
-- | The properties of the TableCell.
--
-- /See:/ 'tableCellProperties' smart constructor.
data TableCellProperties =
TableCellProperties'
{ _tcpTableCellBackgRoundFill :: !(Maybe TableCellBackgRoundFill)
, _tcpContentAlignment :: !(Maybe TableCellPropertiesContentAlignment)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'TableCellProperties' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'tcpTableCellBackgRoundFill'
--
-- * 'tcpContentAlignment'
tableCellProperties
:: TableCellProperties
tableCellProperties =
TableCellProperties'
{_tcpTableCellBackgRoundFill = Nothing, _tcpContentAlignment = Nothing}
-- | The background fill of the table cell. The default fill matches the fill
-- for newly created table cells in the Slides editor.
tcpTableCellBackgRoundFill :: Lens' TableCellProperties (Maybe TableCellBackgRoundFill)
tcpTableCellBackgRoundFill
= lens _tcpTableCellBackgRoundFill
(\ s a -> s{_tcpTableCellBackgRoundFill = a})
-- | The alignment of the content in the table cell. The default alignment
-- matches the alignment for newly created table cells in the Slides
-- editor.
tcpContentAlignment :: Lens' TableCellProperties (Maybe TableCellPropertiesContentAlignment)
tcpContentAlignment
= lens _tcpContentAlignment
(\ s a -> s{_tcpContentAlignment = a})
instance FromJSON TableCellProperties where
parseJSON
= withObject "TableCellProperties"
(\ o ->
TableCellProperties' <$>
(o .:? "tableCellBackgroundFill") <*>
(o .:? "contentAlignment"))
instance ToJSON TableCellProperties where
toJSON TableCellProperties'{..}
= object
(catMaybes
[("tableCellBackgroundFill" .=) <$>
_tcpTableCellBackgRoundFill,
("contentAlignment" .=) <$> _tcpContentAlignment])
-- | The result of creating a line.
--
-- /See:/ 'createLineResponse' smart constructor.
newtype CreateLineResponse =
CreateLineResponse'
{ _clrObjectId :: Maybe Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'CreateLineResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'clrObjectId'
createLineResponse
:: CreateLineResponse
createLineResponse = CreateLineResponse' {_clrObjectId = Nothing}
-- | The object ID of the created line.
clrObjectId :: Lens' CreateLineResponse (Maybe Text)
clrObjectId
= lens _clrObjectId (\ s a -> s{_clrObjectId = a})
instance FromJSON CreateLineResponse where
parseJSON
= withObject "CreateLineResponse"
(\ o -> CreateLineResponse' <$> (o .:? "objectId"))
instance ToJSON CreateLineResponse where
toJSON CreateLineResponse'{..}
= object
(catMaybes [("objectId" .=) <$> _clrObjectId])
-- | A PageElement kind representing word art.
--
-- /See:/ 'wordArt' smart constructor.
newtype WordArt =
WordArt'
{ _waRenderedText :: Maybe Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'WordArt' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'waRenderedText'
wordArt
:: WordArt
wordArt = WordArt' {_waRenderedText = Nothing}
-- | The text rendered as word art.
waRenderedText :: Lens' WordArt (Maybe Text)
waRenderedText
= lens _waRenderedText
(\ s a -> s{_waRenderedText = a})
instance FromJSON WordArt where
parseJSON
= withObject "WordArt"
(\ o -> WordArt' <$> (o .:? "renderedText"))
instance ToJSON WordArt where
toJSON WordArt'{..}
= object
(catMaybes [("renderedText" .=) <$> _waRenderedText])
-- | The table cell background fill.
--
-- /See:/ 'tableCellBackgRoundFill' smart constructor.
data TableCellBackgRoundFill =
TableCellBackgRoundFill'
{ _tcbrfSolidFill :: !(Maybe SolidFill)
, _tcbrfPropertyState :: !(Maybe TableCellBackgRoundFillPropertyState)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'TableCellBackgRoundFill' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'tcbrfSolidFill'
--
-- * 'tcbrfPropertyState'
tableCellBackgRoundFill
:: TableCellBackgRoundFill
tableCellBackgRoundFill =
TableCellBackgRoundFill'
{_tcbrfSolidFill = Nothing, _tcbrfPropertyState = Nothing}
-- | Solid color fill.
tcbrfSolidFill :: Lens' TableCellBackgRoundFill (Maybe SolidFill)
tcbrfSolidFill
= lens _tcbrfSolidFill
(\ s a -> s{_tcbrfSolidFill = a})
-- | The background fill property state. Updating the fill on a table cell
-- will implicitly update this field to \`RENDERED\`, unless another value
-- is specified in the same request. To have no fill on a table cell, set
-- this field to \`NOT_RENDERED\`. In this case, any other fill fields set
-- in the same request will be ignored.
tcbrfPropertyState :: Lens' TableCellBackgRoundFill (Maybe TableCellBackgRoundFillPropertyState)
tcbrfPropertyState
= lens _tcbrfPropertyState
(\ s a -> s{_tcbrfPropertyState = a})
instance FromJSON TableCellBackgRoundFill where
parseJSON
= withObject "TableCellBackgRoundFill"
(\ o ->
TableCellBackgRoundFill' <$>
(o .:? "solidFill") <*> (o .:? "propertyState"))
instance ToJSON TableCellBackgRoundFill where
toJSON TableCellBackgRoundFill'{..}
= object
(catMaybes
[("solidFill" .=) <$> _tcbrfSolidFill,
("propertyState" .=) <$> _tcbrfPropertyState])
-- | A TextElement kind that represents a run of text that all has the same
-- styling.
--
-- /See:/ 'textRun' smart constructor.
data TextRun =
TextRun'
{ _trStyle :: !(Maybe TextStyle)
, _trContent :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'TextRun' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'trStyle'
--
-- * 'trContent'
textRun
:: TextRun
textRun = TextRun' {_trStyle = Nothing, _trContent = Nothing}
-- | The styling applied to this run.
trStyle :: Lens' TextRun (Maybe TextStyle)
trStyle = lens _trStyle (\ s a -> s{_trStyle = a})
-- | The text of this run.
trContent :: Lens' TextRun (Maybe Text)
trContent
= lens _trContent (\ s a -> s{_trContent = a})
instance FromJSON TextRun where
parseJSON
= withObject "TextRun"
(\ o ->
TextRun' <$> (o .:? "style") <*> (o .:? "content"))
instance ToJSON TextRun where
toJSON TextRun'{..}
= object
(catMaybes
[("style" .=) <$> _trStyle,
("content" .=) <$> _trContent])
-- | Refreshes an embedded Google Sheets chart by replacing it with the
-- latest version of the chart from Google Sheets. NOTE: Refreshing charts
-- requires at least one of the spreadsheets.readonly, spreadsheets,
-- drive.readonly, or drive OAuth scopes.
--
-- /See:/ 'refreshSheetsChartRequest' smart constructor.
newtype RefreshSheetsChartRequest =
RefreshSheetsChartRequest'
{ _rscrObjectId :: Maybe Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'RefreshSheetsChartRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'rscrObjectId'
refreshSheetsChartRequest
:: RefreshSheetsChartRequest
refreshSheetsChartRequest = RefreshSheetsChartRequest' {_rscrObjectId = Nothing}
-- | The object ID of the chart to refresh.
rscrObjectId :: Lens' RefreshSheetsChartRequest (Maybe Text)
rscrObjectId
= lens _rscrObjectId (\ s a -> s{_rscrObjectId = a})
instance FromJSON RefreshSheetsChartRequest where
parseJSON
= withObject "RefreshSheetsChartRequest"
(\ o ->
RefreshSheetsChartRequest' <$> (o .:? "objectId"))
instance ToJSON RefreshSheetsChartRequest where
toJSON RefreshSheetsChartRequest'{..}
= object
(catMaybes [("objectId" .=) <$> _rscrObjectId])
-- | Properties and contents of each row in a table.
--
-- /See:/ 'tableRow' smart constructor.
data TableRow =
TableRow'
{ _trTableRowProperties :: !(Maybe TableRowProperties)
, _trTableCells :: !(Maybe [TableCell])
, _trRowHeight :: !(Maybe Dimension)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'TableRow' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'trTableRowProperties'
--
-- * 'trTableCells'
--
-- * 'trRowHeight'
tableRow
:: TableRow
tableRow =
TableRow'
{ _trTableRowProperties = Nothing
, _trTableCells = Nothing
, _trRowHeight = Nothing
}
-- | Properties of the row.
trTableRowProperties :: Lens' TableRow (Maybe TableRowProperties)
trTableRowProperties
= lens _trTableRowProperties
(\ s a -> s{_trTableRowProperties = a})
-- | Properties and contents of each cell. Cells that span multiple columns
-- are represented only once with a column_span greater than 1. As a
-- result, the length of this collection does not always match the number
-- of columns of the entire table.
trTableCells :: Lens' TableRow [TableCell]
trTableCells
= lens _trTableCells (\ s a -> s{_trTableCells = a})
. _Default
. _Coerce
-- | Height of a row.
trRowHeight :: Lens' TableRow (Maybe Dimension)
trRowHeight
= lens _trRowHeight (\ s a -> s{_trRowHeight = a})
instance FromJSON TableRow where
parseJSON
= withObject "TableRow"
(\ o ->
TableRow' <$>
(o .:? "tableRowProperties") <*>
(o .:? "tableCells" .!= mempty)
<*> (o .:? "rowHeight"))
instance ToJSON TableRow where
toJSON TableRow'{..}
= object
(catMaybes
[("tableRowProperties" .=) <$> _trTableRowProperties,
("tableCells" .=) <$> _trTableCells,
("rowHeight" .=) <$> _trRowHeight])
-- | Represents a font family and weight used to style a TextRun.
--
-- /See:/ 'weightedFontFamily' smart constructor.
data WeightedFontFamily =
WeightedFontFamily'
{ _wffFontFamily :: !(Maybe Text)
, _wffWeight :: !(Maybe (Textual Int32))
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'WeightedFontFamily' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'wffFontFamily'
--
-- * 'wffWeight'
weightedFontFamily
:: WeightedFontFamily
weightedFontFamily =
WeightedFontFamily' {_wffFontFamily = Nothing, _wffWeight = Nothing}
-- | The font family of the text. The font family can be any font from the
-- Font menu in Slides or from [Google Fonts]
-- (https:\/\/fonts.google.com\/). If the font name is unrecognized, the
-- text is rendered in \`Arial\`.
wffFontFamily :: Lens' WeightedFontFamily (Maybe Text)
wffFontFamily
= lens _wffFontFamily
(\ s a -> s{_wffFontFamily = a})
-- | The rendered weight of the text. This field can have any value that is a
-- multiple of \`100\` between \`100\` and \`900\`, inclusive. This range
-- corresponds to the numerical values described in the CSS 2.1
-- Specification, [section
-- 15.6](https:\/\/www.w3.org\/TR\/CSS21\/fonts.html#font-boldness), with
-- non-numerical values disallowed. Weights greater than or equal to
-- \`700\` are considered bold, and weights less than \`700\`are not bold.
-- The default value is \`400\` (\"normal\").
wffWeight :: Lens' WeightedFontFamily (Maybe Int32)
wffWeight
= lens _wffWeight (\ s a -> s{_wffWeight = a}) .
mapping _Coerce
instance FromJSON WeightedFontFamily where
parseJSON
= withObject "WeightedFontFamily"
(\ o ->
WeightedFontFamily' <$>
(o .:? "fontFamily") <*> (o .:? "weight"))
instance ToJSON WeightedFontFamily where
toJSON WeightedFontFamily'{..}
= object
(catMaybes
[("fontFamily" .=) <$> _wffFontFamily,
("weight" .=) <$> _wffWeight])
-- | Creates a video. NOTE: Creating a video from Google Drive requires that
-- the requesting app have at least one of the drive, drive.readonly, or
-- drive.file OAuth scopes.
--
-- /See:/ 'createVideoRequest' smart constructor.
data CreateVideoRequest =
CreateVideoRequest'
{ _creObjectId :: !(Maybe Text)
, _creElementProperties :: !(Maybe PageElementProperties)
, _creSource :: !(Maybe CreateVideoRequestSource)
, _creId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'CreateVideoRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'creObjectId'
--
-- * 'creElementProperties'
--
-- * 'creSource'
--
-- * 'creId'
createVideoRequest
:: CreateVideoRequest
createVideoRequest =
CreateVideoRequest'
{ _creObjectId = Nothing
, _creElementProperties = Nothing
, _creSource = Nothing
, _creId = Nothing
}
-- | A user-supplied object ID. If you specify an ID, it must be unique among
-- all pages and page elements in the presentation. The ID must start with
-- an alphanumeric character or an underscore (matches regex
-- \`[a-zA-Z0-9_]\`); remaining characters may include those as well as a
-- hyphen or colon (matches regex \`[a-zA-Z0-9_-:]\`). The length of the ID
-- must not be less than 5 or greater than 50. If you don\'t specify an ID,
-- a unique one is generated.
creObjectId :: Lens' CreateVideoRequest (Maybe Text)
creObjectId
= lens _creObjectId (\ s a -> s{_creObjectId = a})
-- | The element properties for the video. The PageElementProperties.size
-- property is optional. If you don\'t specify a size, a default size is
-- chosen by the server. The PageElementProperties.transform property is
-- optional. The transform must not have shear components. If you don\'t
-- specify a transform, the video will be placed at the top left corner of
-- the page.
creElementProperties :: Lens' CreateVideoRequest (Maybe PageElementProperties)
creElementProperties
= lens _creElementProperties
(\ s a -> s{_creElementProperties = a})
-- | The video source.
creSource :: Lens' CreateVideoRequest (Maybe CreateVideoRequestSource)
creSource
= lens _creSource (\ s a -> s{_creSource = a})
-- | The video source\'s unique identifier for this video. e.g. For YouTube
-- video https:\/\/www.youtube.com\/watch?v=7U3axjORYZ0, the ID is
-- 7U3axjORYZ0. For a Google Drive video
-- https:\/\/drive.google.com\/file\/d\/1xCgQLFTJi5_Xl8DgW_lcUYq5e-q6Hi5Q
-- the ID is 1xCgQLFTJi5_Xl8DgW_lcUYq5e-q6Hi5Q. To access a Google Drive
-- video file, you might need to add a resource key to the HTTP header for
-- a subset of old files. For more information, see [Access link-shared
-- files using resource
-- keys](https:\/\/developers.google.com\/drive\/api\/v3\/resource-keys).
creId :: Lens' CreateVideoRequest (Maybe Text)
creId = lens _creId (\ s a -> s{_creId = a})
instance FromJSON CreateVideoRequest where
parseJSON
= withObject "CreateVideoRequest"
(\ o ->
CreateVideoRequest' <$>
(o .:? "objectId") <*> (o .:? "elementProperties")
<*> (o .:? "source")
<*> (o .:? "id"))
instance ToJSON CreateVideoRequest where
toJSON CreateVideoRequest'{..}
= object
(catMaybes
[("objectId" .=) <$> _creObjectId,
("elementProperties" .=) <$> _creElementProperties,
("source" .=) <$> _creSource, ("id" .=) <$> _creId])
-- | The general text content. The text must reside in a compatible shape
-- (e.g. text box or rectangle) or a table cell in a page.
--
-- /See:/ 'textContent' smart constructor.
data TextContent =
TextContent'
{ _tcTextElements :: !(Maybe [TextElement])
, _tcLists :: !(Maybe TextContentLists)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'TextContent' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'tcTextElements'
--
-- * 'tcLists'
textContent
:: TextContent
textContent = TextContent' {_tcTextElements = Nothing, _tcLists = Nothing}
-- | The text contents broken down into its component parts, including
-- styling information. This property is read-only.
tcTextElements :: Lens' TextContent [TextElement]
tcTextElements
= lens _tcTextElements
(\ s a -> s{_tcTextElements = a})
. _Default
. _Coerce
-- | The bulleted lists contained in this text, keyed by list ID.
tcLists :: Lens' TextContent (Maybe TextContentLists)
tcLists = lens _tcLists (\ s a -> s{_tcLists = a})
instance FromJSON TextContent where
parseJSON
= withObject "TextContent"
(\ o ->
TextContent' <$>
(o .:? "textElements" .!= mempty) <*>
(o .:? "lists"))
instance ToJSON TextContent where
toJSON TextContent'{..}
= object
(catMaybes
[("textElements" .=) <$> _tcTextElements,
("lists" .=) <$> _tcLists])
-- | A PageElement kind representing a generic shape that does not have a
-- more specific classification.
--
-- /See:/ 'shape' smart constructor.
data Shape =
Shape'
{ _sShapeType :: !(Maybe ShapeShapeType)
, _sText :: !(Maybe TextContent)
, _sPlaceholder :: !(Maybe Placeholder)
, _sShapeProperties :: !(Maybe ShapeProperties)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Shape' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'sShapeType'
--
-- * 'sText'
--
-- * 'sPlaceholder'
--
-- * 'sShapeProperties'
shape
:: Shape
shape =
Shape'
{ _sShapeType = Nothing
, _sText = Nothing
, _sPlaceholder = Nothing
, _sShapeProperties = Nothing
}
-- | The type of the shape.
sShapeType :: Lens' Shape (Maybe ShapeShapeType)
sShapeType
= lens _sShapeType (\ s a -> s{_sShapeType = a})
-- | The text content of the shape.
sText :: Lens' Shape (Maybe TextContent)
sText = lens _sText (\ s a -> s{_sText = a})
-- | Placeholders are page elements that inherit from corresponding
-- placeholders on layouts and masters. If set, the shape is a placeholder
-- shape and any inherited properties can be resolved by looking at the
-- parent placeholder identified by the Placeholder.parent_object_id field.
sPlaceholder :: Lens' Shape (Maybe Placeholder)
sPlaceholder
= lens _sPlaceholder (\ s a -> s{_sPlaceholder = a})
-- | The properties of the shape.
sShapeProperties :: Lens' Shape (Maybe ShapeProperties)
sShapeProperties
= lens _sShapeProperties
(\ s a -> s{_sShapeProperties = a})
instance FromJSON Shape where
parseJSON
= withObject "Shape"
(\ o ->
Shape' <$>
(o .:? "shapeType") <*> (o .:? "text") <*>
(o .:? "placeholder")
<*> (o .:? "shapeProperties"))
instance ToJSON Shape where
toJSON Shape'{..}
= object
(catMaybes
[("shapeType" .=) <$> _sShapeType,
("text" .=) <$> _sText,
("placeholder" .=) <$> _sPlaceholder,
("shapeProperties" .=) <$> _sShapeProperties])
-- | AffineTransform uses a 3x3 matrix with an implied last row of [ 0 0 1 ]
-- to transform source coordinates (x,y) into destination coordinates (x\',
-- y\') according to: x\' x = shear_y scale_y translate_y 1 [ 1 ] After
-- transformation, x\' = scale_x * x + shear_x * y + translate_x; y\' =
-- scale_y * y + shear_y * x + translate_y; This message is therefore
-- composed of these six matrix elements.
--
-- /See:/ 'affineTransform' smart constructor.
data AffineTransform =
AffineTransform'
{ _atTranslateX :: !(Maybe (Textual Double))
, _atShearY :: !(Maybe (Textual Double))
, _atTranslateY :: !(Maybe (Textual Double))
, _atShearX :: !(Maybe (Textual Double))
, _atScaleX :: !(Maybe (Textual Double))
, _atUnit :: !(Maybe AffineTransformUnit)
, _atScaleY :: !(Maybe (Textual Double))
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'AffineTransform' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'atTranslateX'
--
-- * 'atShearY'
--
-- * 'atTranslateY'
--
-- * 'atShearX'
--
-- * 'atScaleX'
--
-- * 'atUnit'
--
-- * 'atScaleY'
affineTransform
:: AffineTransform
affineTransform =
AffineTransform'
{ _atTranslateX = Nothing
, _atShearY = Nothing
, _atTranslateY = Nothing
, _atShearX = Nothing
, _atScaleX = Nothing
, _atUnit = Nothing
, _atScaleY = Nothing
}
-- | The X coordinate translation element.
atTranslateX :: Lens' AffineTransform (Maybe Double)
atTranslateX
= lens _atTranslateX (\ s a -> s{_atTranslateX = a})
. mapping _Coerce
-- | The Y coordinate shearing element.
atShearY :: Lens' AffineTransform (Maybe Double)
atShearY
= lens _atShearY (\ s a -> s{_atShearY = a}) .
mapping _Coerce
-- | The Y coordinate translation element.
atTranslateY :: Lens' AffineTransform (Maybe Double)
atTranslateY
= lens _atTranslateY (\ s a -> s{_atTranslateY = a})
. mapping _Coerce
-- | The X coordinate shearing element.
atShearX :: Lens' AffineTransform (Maybe Double)
atShearX
= lens _atShearX (\ s a -> s{_atShearX = a}) .
mapping _Coerce
-- | The X coordinate scaling element.
atScaleX :: Lens' AffineTransform (Maybe Double)
atScaleX
= lens _atScaleX (\ s a -> s{_atScaleX = a}) .
mapping _Coerce
-- | The units for translate elements.
atUnit :: Lens' AffineTransform (Maybe AffineTransformUnit)
atUnit = lens _atUnit (\ s a -> s{_atUnit = a})
-- | The Y coordinate scaling element.
atScaleY :: Lens' AffineTransform (Maybe Double)
atScaleY
= lens _atScaleY (\ s a -> s{_atScaleY = a}) .
mapping _Coerce
instance FromJSON AffineTransform where
parseJSON
= withObject "AffineTransform"
(\ o ->
AffineTransform' <$>
(o .:? "translateX") <*> (o .:? "shearY") <*>
(o .:? "translateY")
<*> (o .:? "shearX")
<*> (o .:? "scaleX")
<*> (o .:? "unit")
<*> (o .:? "scaleY"))
instance ToJSON AffineTransform where
toJSON AffineTransform'{..}
= object
(catMaybes
[("translateX" .=) <$> _atTranslateX,
("shearY" .=) <$> _atShearY,
("translateY" .=) <$> _atTranslateY,
("shearX" .=) <$> _atShearX,
("scaleX" .=) <$> _atScaleX, ("unit" .=) <$> _atUnit,
("scaleY" .=) <$> _atScaleY])
-- | The result of creating an embedded Google Sheets chart.
--
-- /See:/ 'createSheetsChartResponse' smart constructor.
newtype CreateSheetsChartResponse =
CreateSheetsChartResponse'
{ _cscrsObjectId :: Maybe Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'CreateSheetsChartResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cscrsObjectId'
createSheetsChartResponse
:: CreateSheetsChartResponse
createSheetsChartResponse =
CreateSheetsChartResponse' {_cscrsObjectId = Nothing}
-- | The object ID of the created chart.
cscrsObjectId :: Lens' CreateSheetsChartResponse (Maybe Text)
cscrsObjectId
= lens _cscrsObjectId
(\ s a -> s{_cscrsObjectId = a})
instance FromJSON CreateSheetsChartResponse where
parseJSON
= withObject "CreateSheetsChartResponse"
(\ o ->
CreateSheetsChartResponse' <$> (o .:? "objectId"))
instance ToJSON CreateSheetsChartResponse where
toJSON CreateSheetsChartResponse'{..}
= object
(catMaybes [("objectId" .=) <$> _cscrsObjectId])
-- | Specifies a contiguous range of an indexed collection, such as
-- characters in text.
--
-- /See:/ 'range' smart constructor.
data Range =
Range'
{ _rEndIndex :: !(Maybe (Textual Int32))
, _rType :: !(Maybe RangeType)
, _rStartIndex :: !(Maybe (Textual Int32))
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Range' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'rEndIndex'
--
-- * 'rType'
--
-- * 'rStartIndex'
range
:: Range
range = Range' {_rEndIndex = Nothing, _rType = Nothing, _rStartIndex = Nothing}
-- | The optional zero-based index of the end of the collection. Required for
-- \`FIXED_RANGE\` ranges.
rEndIndex :: Lens' Range (Maybe Int32)
rEndIndex
= lens _rEndIndex (\ s a -> s{_rEndIndex = a}) .
mapping _Coerce
-- | The type of range.
rType :: Lens' Range (Maybe RangeType)
rType = lens _rType (\ s a -> s{_rType = a})
-- | The optional zero-based index of the beginning of the collection.
-- Required for \`FIXED_RANGE\` and \`FROM_START_INDEX\` ranges.
rStartIndex :: Lens' Range (Maybe Int32)
rStartIndex
= lens _rStartIndex (\ s a -> s{_rStartIndex = a}) .
mapping _Coerce
instance FromJSON Range where
parseJSON
= withObject "Range"
(\ o ->
Range' <$>
(o .:? "endIndex") <*> (o .:? "type") <*>
(o .:? "startIndex"))
instance ToJSON Range where
toJSON Range'{..}
= object
(catMaybes
[("endIndex" .=) <$> _rEndIndex,
("type" .=) <$> _rType,
("startIndex" .=) <$> _rStartIndex])
-- | Creates an image.
--
-- /See:/ 'createImageRequest' smart constructor.
data CreateImageRequest =
CreateImageRequest'
{ _cirObjectId :: !(Maybe Text)
, _cirURL :: !(Maybe Text)
, _cirElementProperties :: !(Maybe PageElementProperties)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'CreateImageRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cirObjectId'
--
-- * 'cirURL'
--
-- * 'cirElementProperties'
createImageRequest
:: CreateImageRequest
createImageRequest =
CreateImageRequest'
{_cirObjectId = Nothing, _cirURL = Nothing, _cirElementProperties = Nothing}
-- | A user-supplied object ID. If you specify an ID, it must be unique among
-- all pages and page elements in the presentation. The ID must start with
-- an alphanumeric character or an underscore (matches regex
-- \`[a-zA-Z0-9_]\`); remaining characters may include those as well as a
-- hyphen or colon (matches regex \`[a-zA-Z0-9_-:]\`). The length of the ID
-- must not be less than 5 or greater than 50. If you don\'t specify an ID,
-- a unique one is generated.
cirObjectId :: Lens' CreateImageRequest (Maybe Text)
cirObjectId
= lens _cirObjectId (\ s a -> s{_cirObjectId = a})
-- | The image URL. The image is fetched once at insertion time and a copy is
-- stored for display inside the presentation. Images must be less than
-- 50MB in size, cannot exceed 25 megapixels, and must be in one of PNG,
-- JPEG, or GIF format. The provided URL can be at most 2 kB in length. The
-- URL itself is saved with the image, and exposed via the Image.source_url
-- field.
cirURL :: Lens' CreateImageRequest (Maybe Text)
cirURL = lens _cirURL (\ s a -> s{_cirURL = a})
-- | The element properties for the image. When the aspect ratio of the
-- provided size does not match the image aspect ratio, the image is scaled
-- and centered with respect to the size in order to maintain aspect ratio.
-- The provided transform is applied after this operation. The
-- PageElementProperties.size property is optional. If you don\'t specify
-- the size, the default size of the image is used. The
-- PageElementProperties.transform property is optional. If you don\'t
-- specify a transform, the image will be placed at the top left corner of
-- the page.
cirElementProperties :: Lens' CreateImageRequest (Maybe PageElementProperties)
cirElementProperties
= lens _cirElementProperties
(\ s a -> s{_cirElementProperties = a})
instance FromJSON CreateImageRequest where
parseJSON
= withObject "CreateImageRequest"
(\ o ->
CreateImageRequest' <$>
(o .:? "objectId") <*> (o .:? "url") <*>
(o .:? "elementProperties"))
instance ToJSON CreateImageRequest where
toJSON CreateImageRequest'{..}
= object
(catMaybes
[("objectId" .=) <$> _cirObjectId,
("url" .=) <$> _cirURL,
("elementProperties" .=) <$> _cirElementProperties])
-- | Merges cells in a Table.
--
-- /See:/ 'mergeTableCellsRequest' smart constructor.
data MergeTableCellsRequest =
MergeTableCellsRequest'
{ _mtcrObjectId :: !(Maybe Text)
, _mtcrTableRange :: !(Maybe TableRange)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'MergeTableCellsRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'mtcrObjectId'
--
-- * 'mtcrTableRange'
mergeTableCellsRequest
:: MergeTableCellsRequest
mergeTableCellsRequest =
MergeTableCellsRequest' {_mtcrObjectId = Nothing, _mtcrTableRange = Nothing}
-- | The object ID of the table.
mtcrObjectId :: Lens' MergeTableCellsRequest (Maybe Text)
mtcrObjectId
= lens _mtcrObjectId (\ s a -> s{_mtcrObjectId = a})
-- | The table range specifying which cells of the table to merge. Any text
-- in the cells being merged will be concatenated and stored in the
-- upper-left (\"head\") cell of the range. If the range is non-rectangular
-- (which can occur in some cases where the range covers cells that are
-- already merged), a 400 bad request error is returned.
mtcrTableRange :: Lens' MergeTableCellsRequest (Maybe TableRange)
mtcrTableRange
= lens _mtcrTableRange
(\ s a -> s{_mtcrTableRange = a})
instance FromJSON MergeTableCellsRequest where
parseJSON
= withObject "MergeTableCellsRequest"
(\ o ->
MergeTableCellsRequest' <$>
(o .:? "objectId") <*> (o .:? "tableRange"))
instance ToJSON MergeTableCellsRequest where
toJSON MergeTableCellsRequest'{..}
= object
(catMaybes
[("objectId" .=) <$> _mtcrObjectId,
("tableRange" .=) <$> _mtcrTableRange])
-- | Provides control over how write requests are executed.
--
-- /See:/ 'writeControl' smart constructor.
newtype WriteControl =
WriteControl'
{ _wcRequiredRevisionId :: Maybe Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'WriteControl' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'wcRequiredRevisionId'
writeControl
:: WriteControl
writeControl = WriteControl' {_wcRequiredRevisionId = Nothing}
-- | The revision ID of the presentation required for the write request. If
-- specified and the \`required_revision_id\` doesn\'t exactly match the
-- presentation\'s current \`revision_id\`, the request will not be
-- processed and will return a 400 bad request error.
wcRequiredRevisionId :: Lens' WriteControl (Maybe Text)
wcRequiredRevisionId
= lens _wcRequiredRevisionId
(\ s a -> s{_wcRequiredRevisionId = a})
instance FromJSON WriteControl where
parseJSON
= withObject "WriteControl"
(\ o ->
WriteControl' <$> (o .:? "requiredRevisionId"))
instance ToJSON WriteControl where
toJSON WriteControl'{..}
= object
(catMaybes
[("requiredRevisionId" .=) <$>
_wcRequiredRevisionId])
-- | Represents the styling that can be applied to a TextRun. If this text is
-- contained in a shape with a parent placeholder, then these text styles
-- may be inherited from the parent. Which text styles are inherited depend
-- on the nesting level of lists: * A text run in a paragraph that is not
-- in a list will inherit its text style from the the newline character in
-- the paragraph at the 0 nesting level of the list inside the parent
-- placeholder. * A text run in a paragraph that is in a list will inherit
-- its text style from the newline character in the paragraph at its
-- corresponding nesting level of the list inside the parent placeholder.
-- Inherited text styles are represented as unset fields in this message.
-- If text is contained in a shape without a parent placeholder, unsetting
-- these fields will revert the style to a value matching the defaults in
-- the Slides editor.
--
-- /See:/ 'textStyle' smart constructor.
data TextStyle =
TextStyle'
{ _tsFontFamily :: !(Maybe Text)
, _tsLink :: !(Maybe Link)
, _tsBackgRoundColor :: !(Maybe OptionalColor)
, _tsBaselineOffSet :: !(Maybe TextStyleBaselineOffSet)
, _tsForegRoundColor :: !(Maybe OptionalColor)
, _tsFontSize :: !(Maybe Dimension)
, _tsSmallCaps :: !(Maybe Bool)
, _tsUnderline :: !(Maybe Bool)
, _tsWeightedFontFamily :: !(Maybe WeightedFontFamily)
, _tsItalic :: !(Maybe Bool)
, _tsBold :: !(Maybe Bool)
, _tsStrikethrough :: !(Maybe Bool)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'TextStyle' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'tsFontFamily'
--
-- * 'tsLink'
--
-- * 'tsBackgRoundColor'
--
-- * 'tsBaselineOffSet'
--
-- * 'tsForegRoundColor'
--
-- * 'tsFontSize'
--
-- * 'tsSmallCaps'
--
-- * 'tsUnderline'
--
-- * 'tsWeightedFontFamily'
--
-- * 'tsItalic'
--
-- * 'tsBold'
--
-- * 'tsStrikethrough'
textStyle
:: TextStyle
textStyle =
TextStyle'
{ _tsFontFamily = Nothing
, _tsLink = Nothing
, _tsBackgRoundColor = Nothing
, _tsBaselineOffSet = Nothing
, _tsForegRoundColor = Nothing
, _tsFontSize = Nothing
, _tsSmallCaps = Nothing
, _tsUnderline = Nothing
, _tsWeightedFontFamily = Nothing
, _tsItalic = Nothing
, _tsBold = Nothing
, _tsStrikethrough = Nothing
}
-- | The font family of the text. The font family can be any font from the
-- Font menu in Slides or from [Google Fonts]
-- (https:\/\/fonts.google.com\/). If the font name is unrecognized, the
-- text is rendered in \`Arial\`. Some fonts can affect the weight of the
-- text. If an update request specifies values for both \`font_family\` and
-- \`bold\`, the explicitly-set \`bold\` value is used.
tsFontFamily :: Lens' TextStyle (Maybe Text)
tsFontFamily
= lens _tsFontFamily (\ s a -> s{_tsFontFamily = a})
-- | The hyperlink destination of the text. If unset, there is no link. Links
-- are not inherited from parent text. Changing the link in an update
-- request causes some other changes to the text style of the range: * When
-- setting a link, the text foreground color will be set to
-- ThemeColorType.HYPERLINK and the text will be underlined. If these
-- fields are modified in the same request, those values will be used
-- instead of the link defaults. * Setting a link on a text range that
-- overlaps with an existing link will also update the existing link to
-- point to the new URL. * Links are not settable on newline characters. As
-- a result, setting a link on a text range that crosses a paragraph
-- boundary, such as \`\"ABC\\n123\"\`, will separate the newline
-- character(s) into their own text runs. The link will be applied
-- separately to the runs before and after the newline. * Removing a link
-- will update the text style of the range to match the style of the
-- preceding text (or the default text styles if the preceding text is
-- another link) unless different styles are being set in the same request.
tsLink :: Lens' TextStyle (Maybe Link)
tsLink = lens _tsLink (\ s a -> s{_tsLink = a})
-- | The background color of the text. If set, the color is either opaque or
-- transparent, depending on if the \`opaque_color\` field in it is set.
tsBackgRoundColor :: Lens' TextStyle (Maybe OptionalColor)
tsBackgRoundColor
= lens _tsBackgRoundColor
(\ s a -> s{_tsBackgRoundColor = a})
-- | The text\'s vertical offset from its normal position. Text with
-- \`SUPERSCRIPT\` or \`SUBSCRIPT\` baseline offsets is automatically
-- rendered in a smaller font size, computed based on the \`font_size\`
-- field. The \`font_size\` itself is not affected by changes in this
-- field.
tsBaselineOffSet :: Lens' TextStyle (Maybe TextStyleBaselineOffSet)
tsBaselineOffSet
= lens _tsBaselineOffSet
(\ s a -> s{_tsBaselineOffSet = a})
-- | The color of the text itself. If set, the color is either opaque or
-- transparent, depending on if the \`opaque_color\` field in it is set.
tsForegRoundColor :: Lens' TextStyle (Maybe OptionalColor)
tsForegRoundColor
= lens _tsForegRoundColor
(\ s a -> s{_tsForegRoundColor = a})
-- | The size of the text\'s font. When read, the \`font_size\` will
-- specified in points.
tsFontSize :: Lens' TextStyle (Maybe Dimension)
tsFontSize
= lens _tsFontSize (\ s a -> s{_tsFontSize = a})
-- | Whether or not the text is in small capital letters.
tsSmallCaps :: Lens' TextStyle (Maybe Bool)
tsSmallCaps
= lens _tsSmallCaps (\ s a -> s{_tsSmallCaps = a})
-- | Whether or not the text is underlined.
tsUnderline :: Lens' TextStyle (Maybe Bool)
tsUnderline
= lens _tsUnderline (\ s a -> s{_tsUnderline = a})
-- | The font family and rendered weight of the text. This field is an
-- extension of \`font_family\` meant to support explicit font weights
-- without breaking backwards compatibility. As such, when reading the
-- style of a range of text, the value of
-- \`weighted_font_family#font_family\` will always be equal to that of
-- \`font_family\`. However, when writing, if both fields are included in
-- the field mask (either explicitly or through the wildcard \`\"*\"\`),
-- their values are reconciled as follows: * If \`font_family\` is set and
-- \`weighted_font_family\` is not, the value of \`font_family\` is applied
-- with weight \`400\` (\"normal\"). * If both fields are set, the value of
-- \`font_family\` must match that of \`weighted_font_family#font_family\`.
-- If so, the font family and weight of \`weighted_font_family\` is
-- applied. Otherwise, a 400 bad request error is returned. * If
-- \`weighted_font_family\` is set and \`font_family\` is not, the font
-- family and weight of \`weighted_font_family\` is applied. * If neither
-- field is set, the font family and weight of the text inherit from the
-- parent. Note that these properties cannot inherit separately from each
-- other. If an update request specifies values for both
-- \`weighted_font_family\` and \`bold\`, the \`weighted_font_family\` is
-- applied first, then \`bold\`. If \`weighted_font_family#weight\` is not
-- set, it defaults to \`400\`. If \`weighted_font_family\` is set, then
-- \`weighted_font_family#font_family\` must also be set with a non-empty
-- value. Otherwise, a 400 bad request error is returned.
tsWeightedFontFamily :: Lens' TextStyle (Maybe WeightedFontFamily)
tsWeightedFontFamily
= lens _tsWeightedFontFamily
(\ s a -> s{_tsWeightedFontFamily = a})
-- | Whether or not the text is italicized.
tsItalic :: Lens' TextStyle (Maybe Bool)
tsItalic = lens _tsItalic (\ s a -> s{_tsItalic = a})
-- | Whether or not the text is rendered as bold.
tsBold :: Lens' TextStyle (Maybe Bool)
tsBold = lens _tsBold (\ s a -> s{_tsBold = a})
-- | Whether or not the text is struck through.
tsStrikethrough :: Lens' TextStyle (Maybe Bool)
tsStrikethrough
= lens _tsStrikethrough
(\ s a -> s{_tsStrikethrough = a})
instance FromJSON TextStyle where
parseJSON
= withObject "TextStyle"
(\ o ->
TextStyle' <$>
(o .:? "fontFamily") <*> (o .:? "link") <*>
(o .:? "backgroundColor")
<*> (o .:? "baselineOffset")
<*> (o .:? "foregroundColor")
<*> (o .:? "fontSize")
<*> (o .:? "smallCaps")
<*> (o .:? "underline")
<*> (o .:? "weightedFontFamily")
<*> (o .:? "italic")
<*> (o .:? "bold")
<*> (o .:? "strikethrough"))
instance ToJSON TextStyle where
toJSON TextStyle'{..}
= object
(catMaybes
[("fontFamily" .=) <$> _tsFontFamily,
("link" .=) <$> _tsLink,
("backgroundColor" .=) <$> _tsBackgRoundColor,
("baselineOffset" .=) <$> _tsBaselineOffSet,
("foregroundColor" .=) <$> _tsForegRoundColor,
("fontSize" .=) <$> _tsFontSize,
("smallCaps" .=) <$> _tsSmallCaps,
("underline" .=) <$> _tsUnderline,
("weightedFontFamily" .=) <$> _tsWeightedFontFamily,
("italic" .=) <$> _tsItalic, ("bold" .=) <$> _tsBold,
("strikethrough" .=) <$> _tsStrikethrough])
-- | A solid color fill. The page or page element is filled entirely with the
-- specified color value. If any field is unset, its value may be inherited
-- from a parent placeholder if it exists.
--
-- /See:/ 'solidFill' smart constructor.
data SolidFill =
SolidFill'
{ _sfColor :: !(Maybe OpaqueColor)
, _sfAlpha :: !(Maybe (Textual Double))
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'SolidFill' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'sfColor'
--
-- * 'sfAlpha'
solidFill
:: SolidFill
solidFill = SolidFill' {_sfColor = Nothing, _sfAlpha = Nothing}
-- | The color value of the solid fill.
sfColor :: Lens' SolidFill (Maybe OpaqueColor)
sfColor = lens _sfColor (\ s a -> s{_sfColor = a})
-- | The fraction of this \`color\` that should be applied to the pixel. That
-- is, the final pixel color is defined by the equation: pixel color =
-- alpha * (color) + (1.0 - alpha) * (background color) This means that a
-- value of 1.0 corresponds to a solid color, whereas a value of 0.0
-- corresponds to a completely transparent color.
sfAlpha :: Lens' SolidFill (Maybe Double)
sfAlpha
= lens _sfAlpha (\ s a -> s{_sfAlpha = a}) .
mapping _Coerce
instance FromJSON SolidFill where
parseJSON
= withObject "SolidFill"
(\ o ->
SolidFill' <$> (o .:? "color") <*> (o .:? "alpha"))
instance ToJSON SolidFill where
toJSON SolidFill'{..}
= object
(catMaybes
[("color" .=) <$> _sfColor,
("alpha" .=) <$> _sfAlpha])
-- | Update the styling of text in a Shape or Table.
--
-- /See:/ 'updateTextStyleRequest' smart constructor.
data UpdateTextStyleRequest =
UpdateTextStyleRequest'
{ _utsrStyle :: !(Maybe TextStyle)
, _utsrTextRange :: !(Maybe Range)
, _utsrObjectId :: !(Maybe Text)
, _utsrCellLocation :: !(Maybe TableCellLocation)
, _utsrFields :: !(Maybe GFieldMask)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'UpdateTextStyleRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'utsrStyle'
--
-- * 'utsrTextRange'
--
-- * 'utsrObjectId'
--
-- * 'utsrCellLocation'
--
-- * 'utsrFields'
updateTextStyleRequest
:: UpdateTextStyleRequest
updateTextStyleRequest =
UpdateTextStyleRequest'
{ _utsrStyle = Nothing
, _utsrTextRange = Nothing
, _utsrObjectId = Nothing
, _utsrCellLocation = Nothing
, _utsrFields = Nothing
}
-- | The style(s) to set on the text. If the value for a particular style
-- matches that of the parent, that style will be set to inherit. Certain
-- text style changes may cause other changes meant to mirror the behavior
-- of the Slides editor. See the documentation of TextStyle for more
-- information.
utsrStyle :: Lens' UpdateTextStyleRequest (Maybe TextStyle)
utsrStyle
= lens _utsrStyle (\ s a -> s{_utsrStyle = a})
-- | The range of text to style. The range may be extended to include
-- adjacent newlines. If the range fully contains a paragraph belonging to
-- a list, the paragraph\'s bullet is also updated with the matching text
-- style.
utsrTextRange :: Lens' UpdateTextStyleRequest (Maybe Range)
utsrTextRange
= lens _utsrTextRange
(\ s a -> s{_utsrTextRange = a})
-- | The object ID of the shape or table with the text to be styled.
utsrObjectId :: Lens' UpdateTextStyleRequest (Maybe Text)
utsrObjectId
= lens _utsrObjectId (\ s a -> s{_utsrObjectId = a})
-- | The location of the cell in the table containing the text to style. If
-- \`object_id\` refers to a table, \`cell_location\` must have a value.
-- Otherwise, it must not.
utsrCellLocation :: Lens' UpdateTextStyleRequest (Maybe TableCellLocation)
utsrCellLocation
= lens _utsrCellLocation
(\ s a -> s{_utsrCellLocation = a})
-- | The fields that should be updated. At least one field must be specified.
-- The root \`style\` is implied and should not be specified. A single
-- \`\"*\"\` can be used as short-hand for listing every field. For
-- example, to update the text style to bold, set \`fields\` to
-- \`\"bold\"\`. To reset a property to its default value, include its
-- field name in the field mask but leave the field itself unset.
utsrFields :: Lens' UpdateTextStyleRequest (Maybe GFieldMask)
utsrFields
= lens _utsrFields (\ s a -> s{_utsrFields = a})
instance FromJSON UpdateTextStyleRequest where
parseJSON
= withObject "UpdateTextStyleRequest"
(\ o ->
UpdateTextStyleRequest' <$>
(o .:? "style") <*> (o .:? "textRange") <*>
(o .:? "objectId")
<*> (o .:? "cellLocation")
<*> (o .:? "fields"))
instance ToJSON UpdateTextStyleRequest where
toJSON UpdateTextStyleRequest'{..}
= object
(catMaybes
[("style" .=) <$> _utsrStyle,
("textRange" .=) <$> _utsrTextRange,
("objectId" .=) <$> _utsrObjectId,
("cellLocation" .=) <$> _utsrCellLocation,
("fields" .=) <$> _utsrFields])
-- | A recolor effect applied on an image.
--
-- /See:/ 'recolor' smart constructor.
data Recolor =
Recolor'
{ _rName :: !(Maybe RecolorName)
, _rRecolorStops :: !(Maybe [ColorStop])
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Recolor' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'rName'
--
-- * 'rRecolorStops'
recolor
:: Recolor
recolor = Recolor' {_rName = Nothing, _rRecolorStops = Nothing}
-- | The name of the recolor effect. The name is determined from the
-- \`recolor_stops\` by matching the gradient against the colors in the
-- page\'s current color scheme. This property is read-only.
rName :: Lens' Recolor (Maybe RecolorName)
rName = lens _rName (\ s a -> s{_rName = a})
-- | The recolor effect is represented by a gradient, which is a list of
-- color stops. The colors in the gradient will replace the corresponding
-- colors at the same position in the color palette and apply to the image.
-- This property is read-only.
rRecolorStops :: Lens' Recolor [ColorStop]
rRecolorStops
= lens _rRecolorStops
(\ s a -> s{_rRecolorStops = a})
. _Default
. _Coerce
instance FromJSON Recolor where
parseJSON
= withObject "Recolor"
(\ o ->
Recolor' <$>
(o .:? "name") <*> (o .:? "recolorStops" .!= mempty))
instance ToJSON Recolor where
toJSON Recolor'{..}
= object
(catMaybes
[("name" .=) <$> _rName,
("recolorStops" .=) <$> _rRecolorStops])
-- | The properties of the Page. The page will inherit properties from the
-- parent page. Depending on the page type the hierarchy is defined in
-- either SlideProperties or LayoutProperties.
--
-- /See:/ 'pageProperties' smart constructor.
data PageProperties =
PageProperties'
{ _ppPageBackgRoundFill :: !(Maybe PageBackgRoundFill)
, _ppColorScheme :: !(Maybe ColorScheme)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'PageProperties' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ppPageBackgRoundFill'
--
-- * 'ppColorScheme'
pageProperties
:: PageProperties
pageProperties =
PageProperties' {_ppPageBackgRoundFill = Nothing, _ppColorScheme = Nothing}
-- | The background fill of the page. If unset, the background fill is
-- inherited from a parent page if it exists. If the page has no parent,
-- then the background fill defaults to the corresponding fill in the
-- Slides editor.
ppPageBackgRoundFill :: Lens' PageProperties (Maybe PageBackgRoundFill)
ppPageBackgRoundFill
= lens _ppPageBackgRoundFill
(\ s a -> s{_ppPageBackgRoundFill = a})
-- | The color scheme of the page. If unset, the color scheme is inherited
-- from a parent page. If the page has no parent, the color scheme uses a
-- default Slides color scheme, matching the defaults in the Slides editor.
-- Only the concrete colors of the first 12 ThemeColorTypes are editable.
-- In addition, only the color scheme on \`Master\` pages can be updated.
-- To update the field, a color scheme containing mappings from all the
-- first 12 ThemeColorTypes to their concrete colors must be provided.
-- Colors for the remaining ThemeColorTypes will be ignored.
ppColorScheme :: Lens' PageProperties (Maybe ColorScheme)
ppColorScheme
= lens _ppColorScheme
(\ s a -> s{_ppColorScheme = a})
instance FromJSON PageProperties where
parseJSON
= withObject "PageProperties"
(\ o ->
PageProperties' <$>
(o .:? "pageBackgroundFill") <*>
(o .:? "colorScheme"))
instance ToJSON PageProperties where
toJSON PageProperties'{..}
= object
(catMaybes
[("pageBackgroundFill" .=) <$> _ppPageBackgRoundFill,
("colorScheme" .=) <$> _ppColorScheme])
-- | The page background fill.
--
-- /See:/ 'pageBackgRoundFill' smart constructor.
data PageBackgRoundFill =
PageBackgRoundFill'
{ _pbrfStretchedPictureFill :: !(Maybe StretchedPictureFill)
, _pbrfSolidFill :: !(Maybe SolidFill)
, _pbrfPropertyState :: !(Maybe PageBackgRoundFillPropertyState)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'PageBackgRoundFill' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pbrfStretchedPictureFill'
--
-- * 'pbrfSolidFill'
--
-- * 'pbrfPropertyState'
pageBackgRoundFill
:: PageBackgRoundFill
pageBackgRoundFill =
PageBackgRoundFill'
{ _pbrfStretchedPictureFill = Nothing
, _pbrfSolidFill = Nothing
, _pbrfPropertyState = Nothing
}
-- | Stretched picture fill.
pbrfStretchedPictureFill :: Lens' PageBackgRoundFill (Maybe StretchedPictureFill)
pbrfStretchedPictureFill
= lens _pbrfStretchedPictureFill
(\ s a -> s{_pbrfStretchedPictureFill = a})
-- | Solid color fill.
pbrfSolidFill :: Lens' PageBackgRoundFill (Maybe SolidFill)
pbrfSolidFill
= lens _pbrfSolidFill
(\ s a -> s{_pbrfSolidFill = a})
-- | The background fill property state. Updating the fill on a page will
-- implicitly update this field to \`RENDERED\`, unless another value is
-- specified in the same request. To have no fill on a page, set this field
-- to \`NOT_RENDERED\`. In this case, any other fill fields set in the same
-- request will be ignored.
pbrfPropertyState :: Lens' PageBackgRoundFill (Maybe PageBackgRoundFillPropertyState)
pbrfPropertyState
= lens _pbrfPropertyState
(\ s a -> s{_pbrfPropertyState = a})
instance FromJSON PageBackgRoundFill where
parseJSON
= withObject "PageBackgRoundFill"
(\ o ->
PageBackgRoundFill' <$>
(o .:? "stretchedPictureFill") <*>
(o .:? "solidFill")
<*> (o .:? "propertyState"))
instance ToJSON PageBackgRoundFill where
toJSON PageBackgRoundFill'{..}
= object
(catMaybes
[("stretchedPictureFill" .=) <$>
_pbrfStretchedPictureFill,
("solidFill" .=) <$> _pbrfSolidFill,
("propertyState" .=) <$> _pbrfPropertyState])
-- | Contains properties describing the look and feel of a list bullet at a
-- given level of nesting.
--
-- /See:/ 'nestingLevel' smart constructor.
newtype NestingLevel =
NestingLevel'
{ _nlBulletStyle :: Maybe TextStyle
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'NestingLevel' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'nlBulletStyle'
nestingLevel
:: NestingLevel
nestingLevel = NestingLevel' {_nlBulletStyle = Nothing}
-- | The style of a bullet at this level of nesting.
nlBulletStyle :: Lens' NestingLevel (Maybe TextStyle)
nlBulletStyle
= lens _nlBulletStyle
(\ s a -> s{_nlBulletStyle = a})
instance FromJSON NestingLevel where
parseJSON
= withObject "NestingLevel"
(\ o -> NestingLevel' <$> (o .:? "bulletStyle"))
instance ToJSON NestingLevel where
toJSON NestingLevel'{..}
= object
(catMaybes [("bulletStyle" .=) <$> _nlBulletStyle])
-- | A themeable solid color value.
--
-- /See:/ 'opaqueColor' smart constructor.
data OpaqueColor =
OpaqueColor'
{ _ocThemeColor :: !(Maybe OpaqueColorThemeColor)
, _ocRgbColor :: !(Maybe RgbColor)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'OpaqueColor' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ocThemeColor'
--
-- * 'ocRgbColor'
opaqueColor
:: OpaqueColor
opaqueColor = OpaqueColor' {_ocThemeColor = Nothing, _ocRgbColor = Nothing}
-- | An opaque theme color.
ocThemeColor :: Lens' OpaqueColor (Maybe OpaqueColorThemeColor)
ocThemeColor
= lens _ocThemeColor (\ s a -> s{_ocThemeColor = a})
-- | An opaque RGB color.
ocRgbColor :: Lens' OpaqueColor (Maybe RgbColor)
ocRgbColor
= lens _ocRgbColor (\ s a -> s{_ocRgbColor = a})
instance FromJSON OpaqueColor where
parseJSON
= withObject "OpaqueColor"
(\ o ->
OpaqueColor' <$>
(o .:? "themeColor") <*> (o .:? "rgbColor"))
instance ToJSON OpaqueColor where
toJSON OpaqueColor'{..}
= object
(catMaybes
[("themeColor" .=) <$> _ocThemeColor,
("rgbColor" .=) <$> _ocRgbColor])
-- | Creates a new slide.
--
-- /See:/ 'createSlideRequest' smart constructor.
data CreateSlideRequest =
CreateSlideRequest'
{ _csrsObjectId :: !(Maybe Text)
, _csrsSlideLayoutReference :: !(Maybe LayoutReference)
, _csrsInsertionIndex :: !(Maybe (Textual Int32))
, _csrsPlaceholderIdMAppings :: !(Maybe [LayoutPlaceholderIdMApping])
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'CreateSlideRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'csrsObjectId'
--
-- * 'csrsSlideLayoutReference'
--
-- * 'csrsInsertionIndex'
--
-- * 'csrsPlaceholderIdMAppings'
createSlideRequest
:: CreateSlideRequest
createSlideRequest =
CreateSlideRequest'
{ _csrsObjectId = Nothing
, _csrsSlideLayoutReference = Nothing
, _csrsInsertionIndex = Nothing
, _csrsPlaceholderIdMAppings = Nothing
}
-- | A user-supplied object ID. If you specify an ID, it must be unique among
-- all pages and page elements in the presentation. The ID must start with
-- an alphanumeric character or an underscore (matches regex
-- \`[a-zA-Z0-9_]\`); remaining characters may include those as well as a
-- hyphen or colon (matches regex \`[a-zA-Z0-9_-:]\`). The length of the ID
-- must not be less than 5 or greater than 50. If you don\'t specify an ID,
-- a unique one is generated.
csrsObjectId :: Lens' CreateSlideRequest (Maybe Text)
csrsObjectId
= lens _csrsObjectId (\ s a -> s{_csrsObjectId = a})
-- | Layout reference of the slide to be inserted, based on the *current
-- master*, which is one of the following: - The master of the previous
-- slide index. - The master of the first slide, if the insertion_index is
-- zero. - The first master in the presentation, if there are no slides. If
-- the LayoutReference is not found in the current master, a 400 bad
-- request error is returned. If you don\'t specify a layout reference,
-- then the new slide will use the predefined layout \`BLANK\`.
csrsSlideLayoutReference :: Lens' CreateSlideRequest (Maybe LayoutReference)
csrsSlideLayoutReference
= lens _csrsSlideLayoutReference
(\ s a -> s{_csrsSlideLayoutReference = a})
-- | The optional zero-based index indicating where to insert the slides. If
-- you don\'t specify an index, the new slide is created at the end.
csrsInsertionIndex :: Lens' CreateSlideRequest (Maybe Int32)
csrsInsertionIndex
= lens _csrsInsertionIndex
(\ s a -> s{_csrsInsertionIndex = a})
. mapping _Coerce
-- | An optional list of object ID mappings from the placeholder(s) on the
-- layout to the placeholder(s) that will be created on the new slide from
-- that specified layout. Can only be used when \`slide_layout_reference\`
-- is specified.
csrsPlaceholderIdMAppings :: Lens' CreateSlideRequest [LayoutPlaceholderIdMApping]
csrsPlaceholderIdMAppings
= lens _csrsPlaceholderIdMAppings
(\ s a -> s{_csrsPlaceholderIdMAppings = a})
. _Default
. _Coerce
instance FromJSON CreateSlideRequest where
parseJSON
= withObject "CreateSlideRequest"
(\ o ->
CreateSlideRequest' <$>
(o .:? "objectId") <*> (o .:? "slideLayoutReference")
<*> (o .:? "insertionIndex")
<*> (o .:? "placeholderIdMappings" .!= mempty))
instance ToJSON CreateSlideRequest where
toJSON CreateSlideRequest'{..}
= object
(catMaybes
[("objectId" .=) <$> _csrsObjectId,
("slideLayoutReference" .=) <$>
_csrsSlideLayoutReference,
("insertionIndex" .=) <$> _csrsInsertionIndex,
("placeholderIdMappings" .=) <$>
_csrsPlaceholderIdMAppings])
-- | A location of a single table cell within a table.
--
-- /See:/ 'tableCellLocation' smart constructor.
data TableCellLocation =
TableCellLocation'
{ _tclColumnIndex :: !(Maybe (Textual Int32))
, _tclRowIndex :: !(Maybe (Textual Int32))
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'TableCellLocation' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'tclColumnIndex'
--
-- * 'tclRowIndex'
tableCellLocation
:: TableCellLocation
tableCellLocation =
TableCellLocation' {_tclColumnIndex = Nothing, _tclRowIndex = Nothing}
-- | The 0-based column index.
tclColumnIndex :: Lens' TableCellLocation (Maybe Int32)
tclColumnIndex
= lens _tclColumnIndex
(\ s a -> s{_tclColumnIndex = a})
. mapping _Coerce
-- | The 0-based row index.
tclRowIndex :: Lens' TableCellLocation (Maybe Int32)
tclRowIndex
= lens _tclRowIndex (\ s a -> s{_tclRowIndex = a}) .
mapping _Coerce
instance FromJSON TableCellLocation where
parseJSON
= withObject "TableCellLocation"
(\ o ->
TableCellLocation' <$>
(o .:? "columnIndex") <*> (o .:? "rowIndex"))
instance ToJSON TableCellLocation where
toJSON TableCellLocation'{..}
= object
(catMaybes
[("columnIndex" .=) <$> _tclColumnIndex,
("rowIndex" .=) <$> _tclRowIndex])
-- | Updates the position of slides in the presentation.
--
-- /See:/ 'updateSlidesPositionRequest' smart constructor.
data UpdateSlidesPositionRequest =
UpdateSlidesPositionRequest'
{ _usprSlideObjectIds :: !(Maybe [Text])
, _usprInsertionIndex :: !(Maybe (Textual Int32))
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'UpdateSlidesPositionRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'usprSlideObjectIds'
--
-- * 'usprInsertionIndex'
updateSlidesPositionRequest
:: UpdateSlidesPositionRequest
updateSlidesPositionRequest =
UpdateSlidesPositionRequest'
{_usprSlideObjectIds = Nothing, _usprInsertionIndex = Nothing}
-- | The IDs of the slides in the presentation that should be moved. The
-- slides in this list must be in existing presentation order, without
-- duplicates.
usprSlideObjectIds :: Lens' UpdateSlidesPositionRequest [Text]
usprSlideObjectIds
= lens _usprSlideObjectIds
(\ s a -> s{_usprSlideObjectIds = a})
. _Default
. _Coerce
-- | The index where the slides should be inserted, based on the slide
-- arrangement before the move takes place. Must be between zero and the
-- number of slides in the presentation, inclusive.
usprInsertionIndex :: Lens' UpdateSlidesPositionRequest (Maybe Int32)
usprInsertionIndex
= lens _usprInsertionIndex
(\ s a -> s{_usprInsertionIndex = a})
. mapping _Coerce
instance FromJSON UpdateSlidesPositionRequest where
parseJSON
= withObject "UpdateSlidesPositionRequest"
(\ o ->
UpdateSlidesPositionRequest' <$>
(o .:? "slideObjectIds" .!= mempty) <*>
(o .:? "insertionIndex"))
instance ToJSON UpdateSlidesPositionRequest where
toJSON UpdateSlidesPositionRequest'{..}
= object
(catMaybes
[("slideObjectIds" .=) <$> _usprSlideObjectIds,
("insertionIndex" .=) <$> _usprInsertionIndex])
-- | Replaces all shapes that match the given criteria with the provided
-- image. The images replacing the shapes are rectangular after being
-- inserted into the presentation and do not take on the forms of the
-- shapes.
--
-- /See:/ 'replaceAllShapesWithImageRequest' smart constructor.
data ReplaceAllShapesWithImageRequest =
ReplaceAllShapesWithImageRequest'
{ _raswirImageReplaceMethod :: !(Maybe ReplaceAllShapesWithImageRequestImageReplaceMethod)
, _raswirPageObjectIds :: !(Maybe [Text])
, _raswirContainsText :: !(Maybe SubstringMatchCriteria)
, _raswirImageURL :: !(Maybe Text)
, _raswirReplaceMethod :: !(Maybe ReplaceAllShapesWithImageRequestReplaceMethod)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ReplaceAllShapesWithImageRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'raswirImageReplaceMethod'
--
-- * 'raswirPageObjectIds'
--
-- * 'raswirContainsText'
--
-- * 'raswirImageURL'
--
-- * 'raswirReplaceMethod'
replaceAllShapesWithImageRequest
:: ReplaceAllShapesWithImageRequest
replaceAllShapesWithImageRequest =
ReplaceAllShapesWithImageRequest'
{ _raswirImageReplaceMethod = Nothing
, _raswirPageObjectIds = Nothing
, _raswirContainsText = Nothing
, _raswirImageURL = Nothing
, _raswirReplaceMethod = Nothing
}
-- | The image replace method. If you specify both a \`replace_method\` and
-- an \`image_replace_method\`, the \`image_replace_method\` takes
-- precedence. If you do not specify a value for \`image_replace_method\`,
-- but specify a value for \`replace_method\`, then the specified
-- \`replace_method\` value is used. If you do not specify either, then
-- CENTER_INSIDE is used.
raswirImageReplaceMethod :: Lens' ReplaceAllShapesWithImageRequest (Maybe ReplaceAllShapesWithImageRequestImageReplaceMethod)
raswirImageReplaceMethod
= lens _raswirImageReplaceMethod
(\ s a -> s{_raswirImageReplaceMethod = a})
-- | If non-empty, limits the matches to page elements only on the given
-- pages. Returns a 400 bad request error if given the page object ID of a
-- notes page or a notes master, or if a page with that object ID doesn\'t
-- exist in the presentation.
raswirPageObjectIds :: Lens' ReplaceAllShapesWithImageRequest [Text]
raswirPageObjectIds
= lens _raswirPageObjectIds
(\ s a -> s{_raswirPageObjectIds = a})
. _Default
. _Coerce
-- | If set, this request will replace all of the shapes that contain the
-- given text.
raswirContainsText :: Lens' ReplaceAllShapesWithImageRequest (Maybe SubstringMatchCriteria)
raswirContainsText
= lens _raswirContainsText
(\ s a -> s{_raswirContainsText = a})
-- | The image URL. The image is fetched once at insertion time and a copy is
-- stored for display inside the presentation. Images must be less than
-- 50MB in size, cannot exceed 25 megapixels, and must be in one of PNG,
-- JPEG, or GIF format. The provided URL can be at most 2 kB in length. The
-- URL itself is saved with the image, and exposed via the Image.source_url
-- field.
raswirImageURL :: Lens' ReplaceAllShapesWithImageRequest (Maybe Text)
raswirImageURL
= lens _raswirImageURL
(\ s a -> s{_raswirImageURL = a})
-- | The replace method. *Deprecated*: use \`image_replace_method\` instead.
-- If you specify both a \`replace_method\` and an
-- \`image_replace_method\`, the \`image_replace_method\` takes precedence.
raswirReplaceMethod :: Lens' ReplaceAllShapesWithImageRequest (Maybe ReplaceAllShapesWithImageRequestReplaceMethod)
raswirReplaceMethod
= lens _raswirReplaceMethod
(\ s a -> s{_raswirReplaceMethod = a})
instance FromJSON ReplaceAllShapesWithImageRequest
where
parseJSON
= withObject "ReplaceAllShapesWithImageRequest"
(\ o ->
ReplaceAllShapesWithImageRequest' <$>
(o .:? "imageReplaceMethod") <*>
(o .:? "pageObjectIds" .!= mempty)
<*> (o .:? "containsText")
<*> (o .:? "imageUrl")
<*> (o .:? "replaceMethod"))
instance ToJSON ReplaceAllShapesWithImageRequest
where
toJSON ReplaceAllShapesWithImageRequest'{..}
= object
(catMaybes
[("imageReplaceMethod" .=) <$>
_raswirImageReplaceMethod,
("pageObjectIds" .=) <$> _raswirPageObjectIds,
("containsText" .=) <$> _raswirContainsText,
("imageUrl" .=) <$> _raswirImageURL,
("replaceMethod" .=) <$> _raswirReplaceMethod])
-- | A visual element rendered on a page.
--
-- /See:/ 'pageElement' smart constructor.
data PageElement =
PageElement'
{ _peTransform :: !(Maybe AffineTransform)
, _peImage :: !(Maybe Image)
, _peSize :: !(Maybe Size)
, _peSheetsChart :: !(Maybe SheetsChart)
, _peObjectId :: !(Maybe Text)
, _peLine :: !(Maybe Line)
, _peElementGroup :: !(Maybe Group)
, _peVideo :: !(Maybe Video)
, _peWordArt :: !(Maybe WordArt)
, _peShape :: !(Maybe Shape)
, _peTitle :: !(Maybe Text)
, _peTable :: !(Maybe Table)
, _peDescription :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'PageElement' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'peTransform'
--
-- * 'peImage'
--
-- * 'peSize'
--
-- * 'peSheetsChart'
--
-- * 'peObjectId'
--
-- * 'peLine'
--
-- * 'peElementGroup'
--
-- * 'peVideo'
--
-- * 'peWordArt'
--
-- * 'peShape'
--
-- * 'peTitle'
--
-- * 'peTable'
--
-- * 'peDescription'
pageElement
:: PageElement
pageElement =
PageElement'
{ _peTransform = Nothing
, _peImage = Nothing
, _peSize = Nothing
, _peSheetsChart = Nothing
, _peObjectId = Nothing
, _peLine = Nothing
, _peElementGroup = Nothing
, _peVideo = Nothing
, _peWordArt = Nothing
, _peShape = Nothing
, _peTitle = Nothing
, _peTable = Nothing
, _peDescription = Nothing
}
-- | The transform of the page element. The visual appearance of the page
-- element is determined by its absolute transform. To compute the absolute
-- transform, preconcatenate a page element\'s transform with the
-- transforms of all of its parent groups. If the page element is not in a
-- group, its absolute transform is the same as the value in this field.
-- The initial transform for the newly created Group is always the identity
-- transform.
peTransform :: Lens' PageElement (Maybe AffineTransform)
peTransform
= lens _peTransform (\ s a -> s{_peTransform = a})
-- | An image page element.
peImage :: Lens' PageElement (Maybe Image)
peImage = lens _peImage (\ s a -> s{_peImage = a})
-- | The size of the page element.
peSize :: Lens' PageElement (Maybe Size)
peSize = lens _peSize (\ s a -> s{_peSize = a})
-- | A linked chart embedded from Google Sheets. Unlinked charts are
-- represented as images.
peSheetsChart :: Lens' PageElement (Maybe SheetsChart)
peSheetsChart
= lens _peSheetsChart
(\ s a -> s{_peSheetsChart = a})
-- | The object ID for this page element. Object IDs used by
-- google.apps.slides.v1.Page and google.apps.slides.v1.PageElement share
-- the same namespace.
peObjectId :: Lens' PageElement (Maybe Text)
peObjectId
= lens _peObjectId (\ s a -> s{_peObjectId = a})
-- | A line page element.
peLine :: Lens' PageElement (Maybe Line)
peLine = lens _peLine (\ s a -> s{_peLine = a})
-- | A collection of page elements joined as a single unit.
peElementGroup :: Lens' PageElement (Maybe Group)
peElementGroup
= lens _peElementGroup
(\ s a -> s{_peElementGroup = a})
-- | A video page element.
peVideo :: Lens' PageElement (Maybe Video)
peVideo = lens _peVideo (\ s a -> s{_peVideo = a})
-- | A word art page element.
peWordArt :: Lens' PageElement (Maybe WordArt)
peWordArt
= lens _peWordArt (\ s a -> s{_peWordArt = a})
-- | A generic shape.
peShape :: Lens' PageElement (Maybe Shape)
peShape = lens _peShape (\ s a -> s{_peShape = a})
-- | The title of the page element. Combined with description to display alt
-- text. The field is not supported for Group elements.
peTitle :: Lens' PageElement (Maybe Text)
peTitle = lens _peTitle (\ s a -> s{_peTitle = a})
-- | A table page element.
peTable :: Lens' PageElement (Maybe Table)
peTable = lens _peTable (\ s a -> s{_peTable = a})
-- | The description of the page element. Combined with title to display alt
-- text. The field is not supported for Group elements.
peDescription :: Lens' PageElement (Maybe Text)
peDescription
= lens _peDescription
(\ s a -> s{_peDescription = a})
instance FromJSON PageElement where
parseJSON
= withObject "PageElement"
(\ o ->
PageElement' <$>
(o .:? "transform") <*> (o .:? "image") <*>
(o .:? "size")
<*> (o .:? "sheetsChart")
<*> (o .:? "objectId")
<*> (o .:? "line")
<*> (o .:? "elementGroup")
<*> (o .:? "video")
<*> (o .:? "wordArt")
<*> (o .:? "shape")
<*> (o .:? "title")
<*> (o .:? "table")
<*> (o .:? "description"))
instance ToJSON PageElement where
toJSON PageElement'{..}
= object
(catMaybes
[("transform" .=) <$> _peTransform,
("image" .=) <$> _peImage, ("size" .=) <$> _peSize,
("sheetsChart" .=) <$> _peSheetsChart,
("objectId" .=) <$> _peObjectId,
("line" .=) <$> _peLine,
("elementGroup" .=) <$> _peElementGroup,
("video" .=) <$> _peVideo,
("wordArt" .=) <$> _peWordArt,
("shape" .=) <$> _peShape, ("title" .=) <$> _peTitle,
("table" .=) <$> _peTable,
("description" .=) <$> _peDescription])
-- | A color and position in a gradient band.
--
-- /See:/ 'colorStop' smart constructor.
data ColorStop =
ColorStop'
{ _csColor :: !(Maybe OpaqueColor)
, _csAlpha :: !(Maybe (Textual Double))
, _csPosition :: !(Maybe (Textual Double))
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ColorStop' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'csColor'
--
-- * 'csAlpha'
--
-- * 'csPosition'
colorStop
:: ColorStop
colorStop =
ColorStop' {_csColor = Nothing, _csAlpha = Nothing, _csPosition = Nothing}
-- | The color of the gradient stop.
csColor :: Lens' ColorStop (Maybe OpaqueColor)
csColor = lens _csColor (\ s a -> s{_csColor = a})
-- | The alpha value of this color in the gradient band. Defaults to 1.0,
-- fully opaque.
csAlpha :: Lens' ColorStop (Maybe Double)
csAlpha
= lens _csAlpha (\ s a -> s{_csAlpha = a}) .
mapping _Coerce
-- | The relative position of the color stop in the gradient band measured in
-- percentage. The value should be in the interval [0.0, 1.0].
csPosition :: Lens' ColorStop (Maybe Double)
csPosition
= lens _csPosition (\ s a -> s{_csPosition = a}) .
mapping _Coerce
instance FromJSON ColorStop where
parseJSON
= withObject "ColorStop"
(\ o ->
ColorStop' <$>
(o .:? "color") <*> (o .:? "alpha") <*>
(o .:? "position"))
instance ToJSON ColorStop where
toJSON ColorStop'{..}
= object
(catMaybes
[("color" .=) <$> _csColor,
("alpha" .=) <$> _csAlpha,
("position" .=) <$> _csPosition])
-- | Deletes an object, either pages or page elements, from the presentation.
--
-- /See:/ 'deleteObjectRequest' smart constructor.
newtype DeleteObjectRequest =
DeleteObjectRequest'
{ _dObjectId :: Maybe Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'DeleteObjectRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'dObjectId'
deleteObjectRequest
:: DeleteObjectRequest
deleteObjectRequest = DeleteObjectRequest' {_dObjectId = Nothing}
-- | The object ID of the page or page element to delete. If after a delete
-- operation a group contains only 1 or no page elements, the group is also
-- deleted. If a placeholder is deleted on a layout, any empty inheriting
-- placeholders are also deleted.
dObjectId :: Lens' DeleteObjectRequest (Maybe Text)
dObjectId
= lens _dObjectId (\ s a -> s{_dObjectId = a})
instance FromJSON DeleteObjectRequest where
parseJSON
= withObject "DeleteObjectRequest"
(\ o -> DeleteObjectRequest' <$> (o .:? "objectId"))
instance ToJSON DeleteObjectRequest where
toJSON DeleteObjectRequest'{..}
= object (catMaybes [("objectId" .=) <$> _dObjectId])
-- | The result of creating a slide.
--
-- /See:/ 'createSlideResponse' smart constructor.
newtype CreateSlideResponse =
CreateSlideResponse'
{ _ccObjectId :: Maybe Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'CreateSlideResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ccObjectId'
createSlideResponse
:: CreateSlideResponse
createSlideResponse = CreateSlideResponse' {_ccObjectId = Nothing}
-- | The object ID of the created slide.
ccObjectId :: Lens' CreateSlideResponse (Maybe Text)
ccObjectId
= lens _ccObjectId (\ s a -> s{_ccObjectId = a})
instance FromJSON CreateSlideResponse where
parseJSON
= withObject "CreateSlideResponse"
(\ o -> CreateSlideResponse' <$> (o .:? "objectId"))
instance ToJSON CreateSlideResponse where
toJSON CreateSlideResponse'{..}
= object
(catMaybes [("objectId" .=) <$> _ccObjectId])
-- | The palette of predefined colors for a page.
--
-- /See:/ 'colorScheme' smart constructor.
newtype ColorScheme =
ColorScheme'
{ _csColors :: Maybe [ThemeColorPair]
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ColorScheme' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'csColors'
colorScheme
:: ColorScheme
colorScheme = ColorScheme' {_csColors = Nothing}
-- | The ThemeColorType and corresponding concrete color pairs.
csColors :: Lens' ColorScheme [ThemeColorPair]
csColors
= lens _csColors (\ s a -> s{_csColors = a}) .
_Default
. _Coerce
instance FromJSON ColorScheme where
parseJSON
= withObject "ColorScheme"
(\ o -> ColorScheme' <$> (o .:? "colors" .!= mempty))
instance ToJSON ColorScheme where
toJSON ColorScheme'{..}
= object (catMaybes [("colors" .=) <$> _csColors])
-- | Properties and contents of each table cell.
--
-- /See:/ 'tableCell' smart constructor.
data TableCell =
TableCell'
{ _tcColumnSpan :: !(Maybe (Textual Int32))
, _tcLocation :: !(Maybe TableCellLocation)
, _tcText :: !(Maybe TextContent)
, _tcRowSpan :: !(Maybe (Textual Int32))
, _tcTableCellProperties :: !(Maybe TableCellProperties)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'TableCell' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'tcColumnSpan'
--
-- * 'tcLocation'
--
-- * 'tcText'
--
-- * 'tcRowSpan'
--
-- * 'tcTableCellProperties'
tableCell
:: TableCell
tableCell =
TableCell'
{ _tcColumnSpan = Nothing
, _tcLocation = Nothing
, _tcText = Nothing
, _tcRowSpan = Nothing
, _tcTableCellProperties = Nothing
}
-- | Column span of the cell.
tcColumnSpan :: Lens' TableCell (Maybe Int32)
tcColumnSpan
= lens _tcColumnSpan (\ s a -> s{_tcColumnSpan = a})
. mapping _Coerce
-- | The location of the cell within the table.
tcLocation :: Lens' TableCell (Maybe TableCellLocation)
tcLocation
= lens _tcLocation (\ s a -> s{_tcLocation = a})
-- | The text content of the cell.
tcText :: Lens' TableCell (Maybe TextContent)
tcText = lens _tcText (\ s a -> s{_tcText = a})
-- | Row span of the cell.
tcRowSpan :: Lens' TableCell (Maybe Int32)
tcRowSpan
= lens _tcRowSpan (\ s a -> s{_tcRowSpan = a}) .
mapping _Coerce
-- | The properties of the table cell.
tcTableCellProperties :: Lens' TableCell (Maybe TableCellProperties)
tcTableCellProperties
= lens _tcTableCellProperties
(\ s a -> s{_tcTableCellProperties = a})
instance FromJSON TableCell where
parseJSON
= withObject "TableCell"
(\ o ->
TableCell' <$>
(o .:? "columnSpan") <*> (o .:? "location") <*>
(o .:? "text")
<*> (o .:? "rowSpan")
<*> (o .:? "tableCellProperties"))
instance ToJSON TableCell where
toJSON TableCell'{..}
= object
(catMaybes
[("columnSpan" .=) <$> _tcColumnSpan,
("location" .=) <$> _tcLocation,
("text" .=) <$> _tcText,
("rowSpan" .=) <$> _tcRowSpan,
("tableCellProperties" .=) <$>
_tcTableCellProperties])
-- | A map of nesting levels to the properties of bullets at the associated
-- level. A list has at most nine levels of nesting, so the possible values
-- for the keys of this map are 0 through 8, inclusive.
--
-- /See:/ 'listNestingLevel' smart constructor.
newtype ListNestingLevel =
ListNestingLevel'
{ _lnlAddtional :: HashMap Text NestingLevel
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ListNestingLevel' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lnlAddtional'
listNestingLevel
:: HashMap Text NestingLevel -- ^ 'lnlAddtional'
-> ListNestingLevel
listNestingLevel pLnlAddtional_ =
ListNestingLevel' {_lnlAddtional = _Coerce # pLnlAddtional_}
lnlAddtional :: Lens' ListNestingLevel (HashMap Text NestingLevel)
lnlAddtional
= lens _lnlAddtional (\ s a -> s{_lnlAddtional = a})
. _Coerce
instance FromJSON ListNestingLevel where
parseJSON
= withObject "ListNestingLevel"
(\ o -> ListNestingLevel' <$> (parseJSONObject o))
instance ToJSON ListNestingLevel where
toJSON = toJSON . _lnlAddtional
-- | The outline of a PageElement. If these fields are unset, they may be
-- inherited from a parent placeholder if it exists. If there is no parent,
-- the fields will default to the value used for new page elements created
-- in the Slides editor, which may depend on the page element kind.
--
-- /See:/ 'outline' smart constructor.
data Outline =
Outline'
{ _oOutlineFill :: !(Maybe OutlineFill)
, _oWeight :: !(Maybe Dimension)
, _oDashStyle :: !(Maybe OutlineDashStyle)
, _oPropertyState :: !(Maybe OutlinePropertyState)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Outline' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'oOutlineFill'
--
-- * 'oWeight'
--
-- * 'oDashStyle'
--
-- * 'oPropertyState'
outline
:: Outline
outline =
Outline'
{ _oOutlineFill = Nothing
, _oWeight = Nothing
, _oDashStyle = Nothing
, _oPropertyState = Nothing
}
-- | The fill of the outline.
oOutlineFill :: Lens' Outline (Maybe OutlineFill)
oOutlineFill
= lens _oOutlineFill (\ s a -> s{_oOutlineFill = a})
-- | The thickness of the outline.
oWeight :: Lens' Outline (Maybe Dimension)
oWeight = lens _oWeight (\ s a -> s{_oWeight = a})
-- | The dash style of the outline.
oDashStyle :: Lens' Outline (Maybe OutlineDashStyle)
oDashStyle
= lens _oDashStyle (\ s a -> s{_oDashStyle = a})
-- | The outline property state. Updating the outline on a page element will
-- implicitly update this field to \`RENDERED\`, unless another value is
-- specified in the same request. To have no outline on a page element, set
-- this field to \`NOT_RENDERED\`. In this case, any other outline fields
-- set in the same request will be ignored.
oPropertyState :: Lens' Outline (Maybe OutlinePropertyState)
oPropertyState
= lens _oPropertyState
(\ s a -> s{_oPropertyState = a})
instance FromJSON Outline where
parseJSON
= withObject "Outline"
(\ o ->
Outline' <$>
(o .:? "outlineFill") <*> (o .:? "weight") <*>
(o .:? "dashStyle")
<*> (o .:? "propertyState"))
instance ToJSON Outline where
toJSON Outline'{..}
= object
(catMaybes
[("outlineFill" .=) <$> _oOutlineFill,
("weight" .=) <$> _oWeight,
("dashStyle" .=) <$> _oDashStyle,
("propertyState" .=) <$> _oPropertyState])
-- | Update the properties of a Video.
--
-- /See:/ 'updateVideoPropertiesRequest' smart constructor.
data UpdateVideoPropertiesRequest =
UpdateVideoPropertiesRequest'
{ _uvprObjectId :: !(Maybe Text)
, _uvprVideoProperties :: !(Maybe VideoProperties)
, _uvprFields :: !(Maybe GFieldMask)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'UpdateVideoPropertiesRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'uvprObjectId'
--
-- * 'uvprVideoProperties'
--
-- * 'uvprFields'
updateVideoPropertiesRequest
:: UpdateVideoPropertiesRequest
updateVideoPropertiesRequest =
UpdateVideoPropertiesRequest'
{ _uvprObjectId = Nothing
, _uvprVideoProperties = Nothing
, _uvprFields = Nothing
}
-- | The object ID of the video the updates are applied to.
uvprObjectId :: Lens' UpdateVideoPropertiesRequest (Maybe Text)
uvprObjectId
= lens _uvprObjectId (\ s a -> s{_uvprObjectId = a})
-- | The video properties to update.
uvprVideoProperties :: Lens' UpdateVideoPropertiesRequest (Maybe VideoProperties)
uvprVideoProperties
= lens _uvprVideoProperties
(\ s a -> s{_uvprVideoProperties = a})
-- | The fields that should be updated. At least one field must be specified.
-- The root \`videoProperties\` is implied and should not be specified. A
-- single \`\"*\"\` can be used as short-hand for listing every field. For
-- example to update the video outline color, set \`fields\` to
-- \`\"outline.outlineFill.solidFill.color\"\`. To reset a property to its
-- default value, include its field name in the field mask but leave the
-- field itself unset.
uvprFields :: Lens' UpdateVideoPropertiesRequest (Maybe GFieldMask)
uvprFields
= lens _uvprFields (\ s a -> s{_uvprFields = a})
instance FromJSON UpdateVideoPropertiesRequest where
parseJSON
= withObject "UpdateVideoPropertiesRequest"
(\ o ->
UpdateVideoPropertiesRequest' <$>
(o .:? "objectId") <*> (o .:? "videoProperties") <*>
(o .:? "fields"))
instance ToJSON UpdateVideoPropertiesRequest where
toJSON UpdateVideoPropertiesRequest'{..}
= object
(catMaybes
[("objectId" .=) <$> _uvprObjectId,
("videoProperties" .=) <$> _uvprVideoProperties,
("fields" .=) <$> _uvprFields])
-- | The properties of the Video.
--
-- /See:/ 'videoProperties' smart constructor.
data VideoProperties =
VideoProperties'
{ _vpStart :: !(Maybe (Textual Word32))
, _vpAutoPlay :: !(Maybe Bool)
, _vpMute :: !(Maybe Bool)
, _vpEnd :: !(Maybe (Textual Word32))
, _vpOutline :: !(Maybe Outline)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'VideoProperties' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'vpStart'
--
-- * 'vpAutoPlay'
--
-- * 'vpMute'
--
-- * 'vpEnd'
--
-- * 'vpOutline'
videoProperties
:: VideoProperties
videoProperties =
VideoProperties'
{ _vpStart = Nothing
, _vpAutoPlay = Nothing
, _vpMute = Nothing
, _vpEnd = Nothing
, _vpOutline = Nothing
}
-- | The time at which to start playback, measured in seconds from the
-- beginning of the video. If set, the start time should be before the end
-- time. If you set this to a value that exceeds the video\'s length in
-- seconds, the video will be played from the last second. If not set, the
-- video will be played from the beginning.
vpStart :: Lens' VideoProperties (Maybe Word32)
vpStart
= lens _vpStart (\ s a -> s{_vpStart = a}) .
mapping _Coerce
-- | Whether to enable video autoplay when the page is displayed in present
-- mode. Defaults to false.
vpAutoPlay :: Lens' VideoProperties (Maybe Bool)
vpAutoPlay
= lens _vpAutoPlay (\ s a -> s{_vpAutoPlay = a})
-- | Whether to mute the audio during video playback. Defaults to false.
vpMute :: Lens' VideoProperties (Maybe Bool)
vpMute = lens _vpMute (\ s a -> s{_vpMute = a})
-- | The time at which to end playback, measured in seconds from the
-- beginning of the video. If set, the end time should be after the start
-- time. If not set or if you set this to a value that exceeds the video\'s
-- length, the video will be played until its end.
vpEnd :: Lens' VideoProperties (Maybe Word32)
vpEnd
= lens _vpEnd (\ s a -> s{_vpEnd = a}) .
mapping _Coerce
-- | The outline of the video. The default outline matches the defaults for
-- new videos created in the Slides editor.
vpOutline :: Lens' VideoProperties (Maybe Outline)
vpOutline
= lens _vpOutline (\ s a -> s{_vpOutline = a})
instance FromJSON VideoProperties where
parseJSON
= withObject "VideoProperties"
(\ o ->
VideoProperties' <$>
(o .:? "start") <*> (o .:? "autoPlay") <*>
(o .:? "mute")
<*> (o .:? "end")
<*> (o .:? "outline"))
instance ToJSON VideoProperties where
toJSON VideoProperties'{..}
= object
(catMaybes
[("start" .=) <$> _vpStart,
("autoPlay" .=) <$> _vpAutoPlay,
("mute" .=) <$> _vpMute, ("end" .=) <$> _vpEnd,
("outline" .=) <$> _vpOutline])
-- | The user-specified ID mapping for a placeholder that will be created on
-- a slide from a specified layout.
--
-- /See:/ 'layoutPlaceholderIdMApping' smart constructor.
data LayoutPlaceholderIdMApping =
LayoutPlaceholderIdMApping'
{ _lpimaObjectId :: !(Maybe Text)
, _lpimaLayoutPlaceholderObjectId :: !(Maybe Text)
, _lpimaLayoutPlaceholder :: !(Maybe Placeholder)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'LayoutPlaceholderIdMApping' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lpimaObjectId'
--
-- * 'lpimaLayoutPlaceholderObjectId'
--
-- * 'lpimaLayoutPlaceholder'
layoutPlaceholderIdMApping
:: LayoutPlaceholderIdMApping
layoutPlaceholderIdMApping =
LayoutPlaceholderIdMApping'
{ _lpimaObjectId = Nothing
, _lpimaLayoutPlaceholderObjectId = Nothing
, _lpimaLayoutPlaceholder = Nothing
}
-- | A user-supplied object ID for the placeholder identified above that to
-- be created onto a slide. If you specify an ID, it must be unique among
-- all pages and page elements in the presentation. The ID must start with
-- an alphanumeric character or an underscore (matches regex
-- \`[a-zA-Z0-9_]\`); remaining characters may include those as well as a
-- hyphen or colon (matches regex \`[a-zA-Z0-9_-:]\`). The length of the ID
-- must not be less than 5 or greater than 50. If you don\'t specify an ID,
-- a unique one is generated.
lpimaObjectId :: Lens' LayoutPlaceholderIdMApping (Maybe Text)
lpimaObjectId
= lens _lpimaObjectId
(\ s a -> s{_lpimaObjectId = a})
-- | The object ID of the placeholder on a layout that will be applied to a
-- slide.
lpimaLayoutPlaceholderObjectId :: Lens' LayoutPlaceholderIdMApping (Maybe Text)
lpimaLayoutPlaceholderObjectId
= lens _lpimaLayoutPlaceholderObjectId
(\ s a -> s{_lpimaLayoutPlaceholderObjectId = a})
-- | The placeholder on a layout that will be applied to a slide. Only type
-- and index are needed. For example, a predefined \`TITLE_AND_BODY\`
-- layout may usually have a TITLE placeholder with index 0 and a BODY
-- placeholder with index 0.
lpimaLayoutPlaceholder :: Lens' LayoutPlaceholderIdMApping (Maybe Placeholder)
lpimaLayoutPlaceholder
= lens _lpimaLayoutPlaceholder
(\ s a -> s{_lpimaLayoutPlaceholder = a})
instance FromJSON LayoutPlaceholderIdMApping where
parseJSON
= withObject "LayoutPlaceholderIdMApping"
(\ o ->
LayoutPlaceholderIdMApping' <$>
(o .:? "objectId") <*>
(o .:? "layoutPlaceholderObjectId")
<*> (o .:? "layoutPlaceholder"))
instance ToJSON LayoutPlaceholderIdMApping where
toJSON LayoutPlaceholderIdMApping'{..}
= object
(catMaybes
[("objectId" .=) <$> _lpimaObjectId,
("layoutPlaceholderObjectId" .=) <$>
_lpimaLayoutPlaceholderObjectId,
("layoutPlaceholder" .=) <$>
_lpimaLayoutPlaceholder])
-- | The result of creating an image.
--
-- /See:/ 'createImageResponse' smart constructor.
newtype CreateImageResponse =
CreateImageResponse'
{ _ciriObjectId :: Maybe Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'CreateImageResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ciriObjectId'
createImageResponse
:: CreateImageResponse
createImageResponse = CreateImageResponse' {_ciriObjectId = Nothing}
-- | The object ID of the created image.
ciriObjectId :: Lens' CreateImageResponse (Maybe Text)
ciriObjectId
= lens _ciriObjectId (\ s a -> s{_ciriObjectId = a})
instance FromJSON CreateImageResponse where
parseJSON
= withObject "CreateImageResponse"
(\ o -> CreateImageResponse' <$> (o .:? "objectId"))
instance ToJSON CreateImageResponse where
toJSON CreateImageResponse'{..}
= object
(catMaybes [("objectId" .=) <$> _ciriObjectId])
-- | A TextElement describes the content of a range of indices in the text
-- content of a Shape or TableCell.
--
-- /See:/ 'textElement' smart constructor.
data TextElement =
TextElement'
{ _teParagraphMarker :: !(Maybe ParagraphMarker)
, _teAutoText :: !(Maybe AutoText)
, _teEndIndex :: !(Maybe (Textual Int32))
, _teTextRun :: !(Maybe TextRun)
, _teStartIndex :: !(Maybe (Textual Int32))
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'TextElement' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'teParagraphMarker'
--
-- * 'teAutoText'
--
-- * 'teEndIndex'
--
-- * 'teTextRun'
--
-- * 'teStartIndex'
textElement
:: TextElement
textElement =
TextElement'
{ _teParagraphMarker = Nothing
, _teAutoText = Nothing
, _teEndIndex = Nothing
, _teTextRun = Nothing
, _teStartIndex = Nothing
}
-- | A marker representing the beginning of a new paragraph. The
-- \`start_index\` and \`end_index\` of this TextElement represent the
-- range of the paragraph. Other TextElements with an index range contained
-- inside this paragraph\'s range are considered to be part of this
-- paragraph. The range of indices of two separate paragraphs will never
-- overlap.
teParagraphMarker :: Lens' TextElement (Maybe ParagraphMarker)
teParagraphMarker
= lens _teParagraphMarker
(\ s a -> s{_teParagraphMarker = a})
-- | A TextElement representing a spot in the text that is dynamically
-- replaced with content that can change over time.
teAutoText :: Lens' TextElement (Maybe AutoText)
teAutoText
= lens _teAutoText (\ s a -> s{_teAutoText = a})
-- | The zero-based end index of this text element, exclusive, in Unicode
-- code units.
teEndIndex :: Lens' TextElement (Maybe Int32)
teEndIndex
= lens _teEndIndex (\ s a -> s{_teEndIndex = a}) .
mapping _Coerce
-- | A TextElement representing a run of text where all of the characters in
-- the run have the same TextStyle. The \`start_index\` and \`end_index\`
-- of TextRuns will always be fully contained in the index range of a
-- single \`paragraph_marker\` TextElement. In other words, a TextRun will
-- never span multiple paragraphs.
teTextRun :: Lens' TextElement (Maybe TextRun)
teTextRun
= lens _teTextRun (\ s a -> s{_teTextRun = a})
-- | The zero-based start index of this text element, in Unicode code units.
teStartIndex :: Lens' TextElement (Maybe Int32)
teStartIndex
= lens _teStartIndex (\ s a -> s{_teStartIndex = a})
. mapping _Coerce
instance FromJSON TextElement where
parseJSON
= withObject "TextElement"
(\ o ->
TextElement' <$>
(o .:? "paragraphMarker") <*> (o .:? "autoText") <*>
(o .:? "endIndex")
<*> (o .:? "textRun")
<*> (o .:? "startIndex"))
instance ToJSON TextElement where
toJSON TextElement'{..}
= object
(catMaybes
[("paragraphMarker" .=) <$> _teParagraphMarker,
("autoText" .=) <$> _teAutoText,
("endIndex" .=) <$> _teEndIndex,
("textRun" .=) <$> _teTextRun,
("startIndex" .=) <$> _teStartIndex])
-- | Deletes bullets from all of the paragraphs that overlap with the given
-- text index range. The nesting level of each paragraph will be visually
-- preserved by adding indent to the start of the corresponding paragraph.
--
-- /See:/ 'deleteParagraphBulletsRequest' smart constructor.
data DeleteParagraphBulletsRequest =
DeleteParagraphBulletsRequest'
{ _dpbrTextRange :: !(Maybe Range)
, _dpbrObjectId :: !(Maybe Text)
, _dpbrCellLocation :: !(Maybe TableCellLocation)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'DeleteParagraphBulletsRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'dpbrTextRange'
--
-- * 'dpbrObjectId'
--
-- * 'dpbrCellLocation'
deleteParagraphBulletsRequest
:: DeleteParagraphBulletsRequest
deleteParagraphBulletsRequest =
DeleteParagraphBulletsRequest'
{ _dpbrTextRange = Nothing
, _dpbrObjectId = Nothing
, _dpbrCellLocation = Nothing
}
-- | The range of text to delete bullets from, based on TextElement indexes.
dpbrTextRange :: Lens' DeleteParagraphBulletsRequest (Maybe Range)
dpbrTextRange
= lens _dpbrTextRange
(\ s a -> s{_dpbrTextRange = a})
-- | The object ID of the shape or table containing the text to delete
-- bullets from.
dpbrObjectId :: Lens' DeleteParagraphBulletsRequest (Maybe Text)
dpbrObjectId
= lens _dpbrObjectId (\ s a -> s{_dpbrObjectId = a})
-- | The optional table cell location if the text to be modified is in a
-- table cell. If present, the object_id must refer to a table.
dpbrCellLocation :: Lens' DeleteParagraphBulletsRequest (Maybe TableCellLocation)
dpbrCellLocation
= lens _dpbrCellLocation
(\ s a -> s{_dpbrCellLocation = a})
instance FromJSON DeleteParagraphBulletsRequest where
parseJSON
= withObject "DeleteParagraphBulletsRequest"
(\ o ->
DeleteParagraphBulletsRequest' <$>
(o .:? "textRange") <*> (o .:? "objectId") <*>
(o .:? "cellLocation"))
instance ToJSON DeleteParagraphBulletsRequest where
toJSON DeleteParagraphBulletsRequest'{..}
= object
(catMaybes
[("textRange" .=) <$> _dpbrTextRange,
("objectId" .=) <$> _dpbrObjectId,
("cellLocation" .=) <$> _dpbrCellLocation])
-- | Inserts text into a shape or a table cell.
--
-- /See:/ 'insertTextRequest' smart constructor.
data InsertTextRequest =
InsertTextRequest'
{ _itrText :: !(Maybe Text)
, _itrObjectId :: !(Maybe Text)
, _itrInsertionIndex :: !(Maybe (Textual Int32))
, _itrCellLocation :: !(Maybe TableCellLocation)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'InsertTextRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'itrText'
--
-- * 'itrObjectId'
--
-- * 'itrInsertionIndex'
--
-- * 'itrCellLocation'
insertTextRequest
:: InsertTextRequest
insertTextRequest =
InsertTextRequest'
{ _itrText = Nothing
, _itrObjectId = Nothing
, _itrInsertionIndex = Nothing
, _itrCellLocation = Nothing
}
-- | The text to be inserted. Inserting a newline character will implicitly
-- create a new ParagraphMarker at that index. The paragraph style of the
-- new paragraph will be copied from the paragraph at the current insertion
-- index, including lists and bullets. Text styles for inserted text will
-- be determined automatically, generally preserving the styling of
-- neighboring text. In most cases, the text will be added to the TextRun
-- that exists at the insertion index. Some control characters
-- (U+0000-U+0008, U+000C-U+001F) and characters from the Unicode Basic
-- Multilingual Plane Private Use Area (U+E000-U+F8FF) will be stripped out
-- of the inserted text.
itrText :: Lens' InsertTextRequest (Maybe Text)
itrText = lens _itrText (\ s a -> s{_itrText = a})
-- | The object ID of the shape or table where the text will be inserted.
itrObjectId :: Lens' InsertTextRequest (Maybe Text)
itrObjectId
= lens _itrObjectId (\ s a -> s{_itrObjectId = a})
-- | The index where the text will be inserted, in Unicode code units, based
-- on TextElement indexes. The index is zero-based and is computed from the
-- start of the string. The index may be adjusted to prevent insertions
-- inside Unicode grapheme clusters. In these cases, the text will be
-- inserted immediately after the grapheme cluster.
itrInsertionIndex :: Lens' InsertTextRequest (Maybe Int32)
itrInsertionIndex
= lens _itrInsertionIndex
(\ s a -> s{_itrInsertionIndex = a})
. mapping _Coerce
-- | The optional table cell location if the text is to be inserted into a
-- table cell. If present, the object_id must refer to a table.
itrCellLocation :: Lens' InsertTextRequest (Maybe TableCellLocation)
itrCellLocation
= lens _itrCellLocation
(\ s a -> s{_itrCellLocation = a})
instance FromJSON InsertTextRequest where
parseJSON
= withObject "InsertTextRequest"
(\ o ->
InsertTextRequest' <$>
(o .:? "text") <*> (o .:? "objectId") <*>
(o .:? "insertionIndex")
<*> (o .:? "cellLocation"))
instance ToJSON InsertTextRequest where
toJSON InsertTextRequest'{..}
= object
(catMaybes
[("text" .=) <$> _itrText,
("objectId" .=) <$> _itrObjectId,
("insertionIndex" .=) <$> _itrInsertionIndex,
("cellLocation" .=) <$> _itrCellLocation])
-- | Updates the properties of the table borders in a Table.
--
-- /See:/ 'updateTableBOrderPropertiesRequest' smart constructor.
data UpdateTableBOrderPropertiesRequest =
UpdateTableBOrderPropertiesRequest'
{ _utboprBOrderPosition :: !(Maybe UpdateTableBOrderPropertiesRequestBOrderPosition)
, _utboprObjectId :: !(Maybe Text)
, _utboprTableBOrderProperties :: !(Maybe TableBOrderProperties)
, _utboprTableRange :: !(Maybe TableRange)
, _utboprFields :: !(Maybe GFieldMask)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'UpdateTableBOrderPropertiesRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'utboprBOrderPosition'
--
-- * 'utboprObjectId'
--
-- * 'utboprTableBOrderProperties'
--
-- * 'utboprTableRange'
--
-- * 'utboprFields'
updateTableBOrderPropertiesRequest
:: UpdateTableBOrderPropertiesRequest
updateTableBOrderPropertiesRequest =
UpdateTableBOrderPropertiesRequest'
{ _utboprBOrderPosition = Nothing
, _utboprObjectId = Nothing
, _utboprTableBOrderProperties = Nothing
, _utboprTableRange = Nothing
, _utboprFields = Nothing
}
-- | The border position in the table range the updates should apply to. If a
-- border position is not specified, the updates will apply to all borders
-- in the table range.
utboprBOrderPosition :: Lens' UpdateTableBOrderPropertiesRequest (Maybe UpdateTableBOrderPropertiesRequestBOrderPosition)
utboprBOrderPosition
= lens _utboprBOrderPosition
(\ s a -> s{_utboprBOrderPosition = a})
-- | The object ID of the table.
utboprObjectId :: Lens' UpdateTableBOrderPropertiesRequest (Maybe Text)
utboprObjectId
= lens _utboprObjectId
(\ s a -> s{_utboprObjectId = a})
-- | The table border properties to update.
utboprTableBOrderProperties :: Lens' UpdateTableBOrderPropertiesRequest (Maybe TableBOrderProperties)
utboprTableBOrderProperties
= lens _utboprTableBOrderProperties
(\ s a -> s{_utboprTableBOrderProperties = a})
-- | The table range representing the subset of the table to which the
-- updates are applied. If a table range is not specified, the updates will
-- apply to the entire table.
utboprTableRange :: Lens' UpdateTableBOrderPropertiesRequest (Maybe TableRange)
utboprTableRange
= lens _utboprTableRange
(\ s a -> s{_utboprTableRange = a})
-- | The fields that should be updated. At least one field must be specified.
-- The root \`tableBorderProperties\` is implied and should not be
-- specified. A single \`\"*\"\` can be used as short-hand for listing
-- every field. For example to update the table border solid fill color,
-- set \`fields\` to \`\"tableBorderFill.solidFill.color\"\`. To reset a
-- property to its default value, include its field name in the field mask
-- but leave the field itself unset.
utboprFields :: Lens' UpdateTableBOrderPropertiesRequest (Maybe GFieldMask)
utboprFields
= lens _utboprFields (\ s a -> s{_utboprFields = a})
instance FromJSON UpdateTableBOrderPropertiesRequest
where
parseJSON
= withObject "UpdateTableBOrderPropertiesRequest"
(\ o ->
UpdateTableBOrderPropertiesRequest' <$>
(o .:? "borderPosition") <*> (o .:? "objectId") <*>
(o .:? "tableBorderProperties")
<*> (o .:? "tableRange")
<*> (o .:? "fields"))
instance ToJSON UpdateTableBOrderPropertiesRequest
where
toJSON UpdateTableBOrderPropertiesRequest'{..}
= object
(catMaybes
[("borderPosition" .=) <$> _utboprBOrderPosition,
("objectId" .=) <$> _utboprObjectId,
("tableBorderProperties" .=) <$>
_utboprTableBOrderProperties,
("tableRange" .=) <$> _utboprTableRange,
("fields" .=) <$> _utboprFields])
-- | Creates a line.
--
-- /See:/ 'createLineRequest' smart constructor.
data CreateLineRequest =
CreateLineRequest'
{ _clrlCategory :: !(Maybe CreateLineRequestCategory)
, _clrlObjectId :: !(Maybe Text)
, _clrlLineCategory :: !(Maybe CreateLineRequestLineCategory)
, _clrlElementProperties :: !(Maybe PageElementProperties)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'CreateLineRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'clrlCategory'
--
-- * 'clrlObjectId'
--
-- * 'clrlLineCategory'
--
-- * 'clrlElementProperties'
createLineRequest
:: CreateLineRequest
createLineRequest =
CreateLineRequest'
{ _clrlCategory = Nothing
, _clrlObjectId = Nothing
, _clrlLineCategory = Nothing
, _clrlElementProperties = Nothing
}
-- | The category of the line to be created. The exact line type created is
-- determined based on the category and how it\'s routed to connect to
-- other page elements. If you specify both a \`category\` and a
-- \`line_category\`, the \`category\` takes precedence. If you do not
-- specify a value for \`category\`, but specify a value for
-- \`line_category\`, then the specified \`line_category\` value is used.
-- If you do not specify either, then STRAIGHT is used.
clrlCategory :: Lens' CreateLineRequest (Maybe CreateLineRequestCategory)
clrlCategory
= lens _clrlCategory (\ s a -> s{_clrlCategory = a})
-- | A user-supplied object ID. If you specify an ID, it must be unique among
-- all pages and page elements in the presentation. The ID must start with
-- an alphanumeric character or an underscore (matches regex
-- \`[a-zA-Z0-9_]\`); remaining characters may include those as well as a
-- hyphen or colon (matches regex \`[a-zA-Z0-9_-:]\`). The length of the ID
-- must not be less than 5 or greater than 50. If you don\'t specify an ID,
-- a unique one is generated.
clrlObjectId :: Lens' CreateLineRequest (Maybe Text)
clrlObjectId
= lens _clrlObjectId (\ s a -> s{_clrlObjectId = a})
-- | The category of the line to be created. *Deprecated*: use \`category\`
-- instead. The exact line type created is determined based on the category
-- and how it\'s routed to connect to other page elements. If you specify
-- both a \`category\` and a \`line_category\`, the \`category\` takes
-- precedence.
clrlLineCategory :: Lens' CreateLineRequest (Maybe CreateLineRequestLineCategory)
clrlLineCategory
= lens _clrlLineCategory
(\ s a -> s{_clrlLineCategory = a})
-- | The element properties for the line.
clrlElementProperties :: Lens' CreateLineRequest (Maybe PageElementProperties)
clrlElementProperties
= lens _clrlElementProperties
(\ s a -> s{_clrlElementProperties = a})
instance FromJSON CreateLineRequest where
parseJSON
= withObject "CreateLineRequest"
(\ o ->
CreateLineRequest' <$>
(o .:? "category") <*> (o .:? "objectId") <*>
(o .:? "lineCategory")
<*> (o .:? "elementProperties"))
instance ToJSON CreateLineRequest where
toJSON CreateLineRequest'{..}
= object
(catMaybes
[("category" .=) <$> _clrlCategory,
("objectId" .=) <$> _clrlObjectId,
("lineCategory" .=) <$> _clrlLineCategory,
("elementProperties" .=) <$> _clrlElementProperties])
-- | The placeholder information that uniquely identifies a placeholder
-- shape.
--
-- /See:/ 'placeholder' smart constructor.
data Placeholder =
Placeholder'
{ _pParentObjectId :: !(Maybe Text)
, _pType :: !(Maybe PlaceholderType)
, _pIndex :: !(Maybe (Textual Int32))
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Placeholder' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pParentObjectId'
--
-- * 'pType'
--
-- * 'pIndex'
placeholder
:: Placeholder
placeholder =
Placeholder' {_pParentObjectId = Nothing, _pType = Nothing, _pIndex = Nothing}
-- | The object ID of this shape\'s parent placeholder. If unset, the parent
-- placeholder shape does not exist, so the shape does not inherit
-- properties from any other shape.
pParentObjectId :: Lens' Placeholder (Maybe Text)
pParentObjectId
= lens _pParentObjectId
(\ s a -> s{_pParentObjectId = a})
-- | The type of the placeholder.
pType :: Lens' Placeholder (Maybe PlaceholderType)
pType = lens _pType (\ s a -> s{_pType = a})
-- | The index of the placeholder. If the same placeholder types are present
-- in the same page, they would have different index values.
pIndex :: Lens' Placeholder (Maybe Int32)
pIndex
= lens _pIndex (\ s a -> s{_pIndex = a}) .
mapping _Coerce
instance FromJSON Placeholder where
parseJSON
= withObject "Placeholder"
(\ o ->
Placeholder' <$>
(o .:? "parentObjectId") <*> (o .:? "type") <*>
(o .:? "index"))
instance ToJSON Placeholder where
toJSON Placeholder'{..}
= object
(catMaybes
[("parentObjectId" .=) <$> _pParentObjectId,
("type" .=) <$> _pType, ("index" .=) <$> _pIndex])
-- | The properties of Page are only relevant for pages with page_type
-- LAYOUT.
--
-- /See:/ 'layoutProperties' smart constructor.
data LayoutProperties =
LayoutProperties'
{ _lpMasterObjectId :: !(Maybe Text)
, _lpName :: !(Maybe Text)
, _lpDisplayName :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'LayoutProperties' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lpMasterObjectId'
--
-- * 'lpName'
--
-- * 'lpDisplayName'
layoutProperties
:: LayoutProperties
layoutProperties =
LayoutProperties'
{_lpMasterObjectId = Nothing, _lpName = Nothing, _lpDisplayName = Nothing}
-- | The object ID of the master that this layout is based on.
lpMasterObjectId :: Lens' LayoutProperties (Maybe Text)
lpMasterObjectId
= lens _lpMasterObjectId
(\ s a -> s{_lpMasterObjectId = a})
-- | The name of the layout.
lpName :: Lens' LayoutProperties (Maybe Text)
lpName = lens _lpName (\ s a -> s{_lpName = a})
-- | The human-readable name of the layout.
lpDisplayName :: Lens' LayoutProperties (Maybe Text)
lpDisplayName
= lens _lpDisplayName
(\ s a -> s{_lpDisplayName = a})
instance FromJSON LayoutProperties where
parseJSON
= withObject "LayoutProperties"
(\ o ->
LayoutProperties' <$>
(o .:? "masterObjectId") <*> (o .:? "name") <*>
(o .:? "displayName"))
instance ToJSON LayoutProperties where
toJSON LayoutProperties'{..}
= object
(catMaybes
[("masterObjectId" .=) <$> _lpMasterObjectId,
("name" .=) <$> _lpName,
("displayName" .=) <$> _lpDisplayName])
-- | Update the properties of a Shape.
--
-- /See:/ 'updateShapePropertiesRequest' smart constructor.
data UpdateShapePropertiesRequest =
UpdateShapePropertiesRequest'
{ _uObjectId :: !(Maybe Text)
, _uShapeProperties :: !(Maybe ShapeProperties)
, _uFields :: !(Maybe GFieldMask)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'UpdateShapePropertiesRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'uObjectId'
--
-- * 'uShapeProperties'
--
-- * 'uFields'
updateShapePropertiesRequest
:: UpdateShapePropertiesRequest
updateShapePropertiesRequest =
UpdateShapePropertiesRequest'
{_uObjectId = Nothing, _uShapeProperties = Nothing, _uFields = Nothing}
-- | The object ID of the shape the updates are applied to.
uObjectId :: Lens' UpdateShapePropertiesRequest (Maybe Text)
uObjectId
= lens _uObjectId (\ s a -> s{_uObjectId = a})
-- | The shape properties to update.
uShapeProperties :: Lens' UpdateShapePropertiesRequest (Maybe ShapeProperties)
uShapeProperties
= lens _uShapeProperties
(\ s a -> s{_uShapeProperties = a})
-- | The fields that should be updated. At least one field must be specified.
-- The root \`shapeProperties\` is implied and should not be specified. A
-- single \`\"*\"\` can be used as short-hand for listing every field. For
-- example to update the shape background solid fill color, set \`fields\`
-- to \`\"shapeBackgroundFill.solidFill.color\"\`. To reset a property to
-- its default value, include its field name in the field mask but leave
-- the field itself unset.
uFields :: Lens' UpdateShapePropertiesRequest (Maybe GFieldMask)
uFields = lens _uFields (\ s a -> s{_uFields = a})
instance FromJSON UpdateShapePropertiesRequest where
parseJSON
= withObject "UpdateShapePropertiesRequest"
(\ o ->
UpdateShapePropertiesRequest' <$>
(o .:? "objectId") <*> (o .:? "shapeProperties") <*>
(o .:? "fields"))
instance ToJSON UpdateShapePropertiesRequest where
toJSON UpdateShapePropertiesRequest'{..}
= object
(catMaybes
[("objectId" .=) <$> _uObjectId,
("shapeProperties" .=) <$> _uShapeProperties,
("fields" .=) <$> _uFields])
-- | A PageElement kind representing a table.
--
-- /See:/ 'table' smart constructor.
data Table =
Table'
{ _tTableRows :: !(Maybe [TableRow])
, _tVerticalBOrderRows :: !(Maybe [TableBOrderRow])
, _tRows :: !(Maybe (Textual Int32))
, _tColumns :: !(Maybe (Textual Int32))
, _tHorizontalBOrderRows :: !(Maybe [TableBOrderRow])
, _tTableColumns :: !(Maybe [TableColumnProperties])
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Table' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'tTableRows'
--
-- * 'tVerticalBOrderRows'
--
-- * 'tRows'
--
-- * 'tColumns'
--
-- * 'tHorizontalBOrderRows'
--
-- * 'tTableColumns'
table
:: Table
table =
Table'
{ _tTableRows = Nothing
, _tVerticalBOrderRows = Nothing
, _tRows = Nothing
, _tColumns = Nothing
, _tHorizontalBOrderRows = Nothing
, _tTableColumns = Nothing
}
-- | Properties and contents of each row. Cells that span multiple rows are
-- contained in only one of these rows and have a row_span greater than 1.
tTableRows :: Lens' Table [TableRow]
tTableRows
= lens _tTableRows (\ s a -> s{_tTableRows = a}) .
_Default
. _Coerce
-- | Properties of vertical cell borders. A table\'s vertical cell borders
-- are represented as a grid. The grid has the same number of rows as the
-- table and one more column than the number of columns in the table. For
-- example, if the table is 3 x 3, its vertical borders will be represented
-- as a grid with 3 rows and 4 columns.
tVerticalBOrderRows :: Lens' Table [TableBOrderRow]
tVerticalBOrderRows
= lens _tVerticalBOrderRows
(\ s a -> s{_tVerticalBOrderRows = a})
. _Default
. _Coerce
-- | Number of rows in the table.
tRows :: Lens' Table (Maybe Int32)
tRows
= lens _tRows (\ s a -> s{_tRows = a}) .
mapping _Coerce
-- | Number of columns in the table.
tColumns :: Lens' Table (Maybe Int32)
tColumns
= lens _tColumns (\ s a -> s{_tColumns = a}) .
mapping _Coerce
-- | Properties of horizontal cell borders. A table\'s horizontal cell
-- borders are represented as a grid. The grid has one more row than the
-- number of rows in the table and the same number of columns as the table.
-- For example, if the table is 3 x 3, its horizontal borders will be
-- represented as a grid with 4 rows and 3 columns.
tHorizontalBOrderRows :: Lens' Table [TableBOrderRow]
tHorizontalBOrderRows
= lens _tHorizontalBOrderRows
(\ s a -> s{_tHorizontalBOrderRows = a})
. _Default
. _Coerce
-- | Properties of each column.
tTableColumns :: Lens' Table [TableColumnProperties]
tTableColumns
= lens _tTableColumns
(\ s a -> s{_tTableColumns = a})
. _Default
. _Coerce
instance FromJSON Table where
parseJSON
= withObject "Table"
(\ o ->
Table' <$>
(o .:? "tableRows" .!= mempty) <*>
(o .:? "verticalBorderRows" .!= mempty)
<*> (o .:? "rows")
<*> (o .:? "columns")
<*> (o .:? "horizontalBorderRows" .!= mempty)
<*> (o .:? "tableColumns" .!= mempty))
instance ToJSON Table where
toJSON Table'{..}
= object
(catMaybes
[("tableRows" .=) <$> _tTableRows,
("verticalBorderRows" .=) <$> _tVerticalBOrderRows,
("rows" .=) <$> _tRows, ("columns" .=) <$> _tColumns,
("horizontalBorderRows" .=) <$>
_tHorizontalBOrderRows,
("tableColumns" .=) <$> _tTableColumns])
-- | Updates the category of a line.
--
-- /See:/ 'updateLineCategoryRequest' smart constructor.
data UpdateLineCategoryRequest =
UpdateLineCategoryRequest'
{ _ulcrObjectId :: !(Maybe Text)
, _ulcrLineCategory :: !(Maybe UpdateLineCategoryRequestLineCategory)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'UpdateLineCategoryRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ulcrObjectId'
--
-- * 'ulcrLineCategory'
updateLineCategoryRequest
:: UpdateLineCategoryRequest
updateLineCategoryRequest =
UpdateLineCategoryRequest'
{_ulcrObjectId = Nothing, _ulcrLineCategory = Nothing}
-- | The object ID of the line the update is applied to. Only a line with a
-- category indicating it is a \"connector\" can be updated. The line may
-- be rerouted after updating its category.
ulcrObjectId :: Lens' UpdateLineCategoryRequest (Maybe Text)
ulcrObjectId
= lens _ulcrObjectId (\ s a -> s{_ulcrObjectId = a})
-- | The line category to update to. The exact line type is determined based
-- on the category to update to and how it\'s routed to connect to other
-- page elements.
ulcrLineCategory :: Lens' UpdateLineCategoryRequest (Maybe UpdateLineCategoryRequestLineCategory)
ulcrLineCategory
= lens _ulcrLineCategory
(\ s a -> s{_ulcrLineCategory = a})
instance FromJSON UpdateLineCategoryRequest where
parseJSON
= withObject "UpdateLineCategoryRequest"
(\ o ->
UpdateLineCategoryRequest' <$>
(o .:? "objectId") <*> (o .:? "lineCategory"))
instance ToJSON UpdateLineCategoryRequest where
toJSON UpdateLineCategoryRequest'{..}
= object
(catMaybes
[("objectId" .=) <$> _ulcrObjectId,
("lineCategory" .=) <$> _ulcrLineCategory])
-- | The properties of a Shape. If the shape is a placeholder shape as
-- determined by the placeholder field, then these properties may be
-- inherited from a parent placeholder shape. Determining the rendered
-- value of the property depends on the corresponding property_state field
-- value. Any text autofit settings on the shape are automatically
-- deactivated by requests that can impact how text fits in the shape.
--
-- /See:/ 'shapeProperties' smart constructor.
data ShapeProperties =
ShapeProperties'
{ _spAutofit :: !(Maybe Autofit)
, _spLink :: !(Maybe Link)
, _spShadow :: !(Maybe Shadow)
, _spOutline :: !(Maybe Outline)
, _spContentAlignment :: !(Maybe ShapePropertiesContentAlignment)
, _spShapeBackgRoundFill :: !(Maybe ShapeBackgRoundFill)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ShapeProperties' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'spAutofit'
--
-- * 'spLink'
--
-- * 'spShadow'
--
-- * 'spOutline'
--
-- * 'spContentAlignment'
--
-- * 'spShapeBackgRoundFill'
shapeProperties
:: ShapeProperties
shapeProperties =
ShapeProperties'
{ _spAutofit = Nothing
, _spLink = Nothing
, _spShadow = Nothing
, _spOutline = Nothing
, _spContentAlignment = Nothing
, _spShapeBackgRoundFill = Nothing
}
-- | The autofit properties of the shape. This property is only set for
-- shapes that allow text.
spAutofit :: Lens' ShapeProperties (Maybe Autofit)
spAutofit
= lens _spAutofit (\ s a -> s{_spAutofit = a})
-- | The hyperlink destination of the shape. If unset, there is no link.
-- Links are not inherited from parent placeholders.
spLink :: Lens' ShapeProperties (Maybe Link)
spLink = lens _spLink (\ s a -> s{_spLink = a})
-- | The shadow properties of the shape. If unset, the shadow is inherited
-- from a parent placeholder if it exists. If the shape has no parent, then
-- the default shadow matches the defaults for new shapes created in the
-- Slides editor. This property is read-only.
spShadow :: Lens' ShapeProperties (Maybe Shadow)
spShadow = lens _spShadow (\ s a -> s{_spShadow = a})
-- | The outline of the shape. If unset, the outline is inherited from a
-- parent placeholder if it exists. If the shape has no parent, then the
-- default outline depends on the shape type, matching the defaults for new
-- shapes created in the Slides editor.
spOutline :: Lens' ShapeProperties (Maybe Outline)
spOutline
= lens _spOutline (\ s a -> s{_spOutline = a})
-- | The alignment of the content in the shape. If unspecified, the alignment
-- is inherited from a parent placeholder if it exists. If the shape has no
-- parent, the default alignment matches the alignment for new shapes
-- created in the Slides editor.
spContentAlignment :: Lens' ShapeProperties (Maybe ShapePropertiesContentAlignment)
spContentAlignment
= lens _spContentAlignment
(\ s a -> s{_spContentAlignment = a})
-- | The background fill of the shape. If unset, the background fill is
-- inherited from a parent placeholder if it exists. If the shape has no
-- parent, then the default background fill depends on the shape type,
-- matching the defaults for new shapes created in the Slides editor.
spShapeBackgRoundFill :: Lens' ShapeProperties (Maybe ShapeBackgRoundFill)
spShapeBackgRoundFill
= lens _spShapeBackgRoundFill
(\ s a -> s{_spShapeBackgRoundFill = a})
instance FromJSON ShapeProperties where
parseJSON
= withObject "ShapeProperties"
(\ o ->
ShapeProperties' <$>
(o .:? "autofit") <*> (o .:? "link") <*>
(o .:? "shadow")
<*> (o .:? "outline")
<*> (o .:? "contentAlignment")
<*> (o .:? "shapeBackgroundFill"))
instance ToJSON ShapeProperties where
toJSON ShapeProperties'{..}
= object
(catMaybes
[("autofit" .=) <$> _spAutofit,
("link" .=) <$> _spLink, ("shadow" .=) <$> _spShadow,
("outline" .=) <$> _spOutline,
("contentAlignment" .=) <$> _spContentAlignment,
("shapeBackgroundFill" .=) <$>
_spShapeBackgRoundFill])
-- | The shape background fill.
--
-- /See:/ 'shapeBackgRoundFill' smart constructor.
data ShapeBackgRoundFill =
ShapeBackgRoundFill'
{ _sbrfSolidFill :: !(Maybe SolidFill)
, _sbrfPropertyState :: !(Maybe ShapeBackgRoundFillPropertyState)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ShapeBackgRoundFill' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'sbrfSolidFill'
--
-- * 'sbrfPropertyState'
shapeBackgRoundFill
:: ShapeBackgRoundFill
shapeBackgRoundFill =
ShapeBackgRoundFill' {_sbrfSolidFill = Nothing, _sbrfPropertyState = Nothing}
-- | Solid color fill.
sbrfSolidFill :: Lens' ShapeBackgRoundFill (Maybe SolidFill)
sbrfSolidFill
= lens _sbrfSolidFill
(\ s a -> s{_sbrfSolidFill = a})
-- | The background fill property state. Updating the fill on a shape will
-- implicitly update this field to \`RENDERED\`, unless another value is
-- specified in the same request. To have no fill on a shape, set this
-- field to \`NOT_RENDERED\`. In this case, any other fill fields set in
-- the same request will be ignored.
sbrfPropertyState :: Lens' ShapeBackgRoundFill (Maybe ShapeBackgRoundFillPropertyState)
sbrfPropertyState
= lens _sbrfPropertyState
(\ s a -> s{_sbrfPropertyState = a})
instance FromJSON ShapeBackgRoundFill where
parseJSON
= withObject "ShapeBackgRoundFill"
(\ o ->
ShapeBackgRoundFill' <$>
(o .:? "solidFill") <*> (o .:? "propertyState"))
instance ToJSON ShapeBackgRoundFill where
toJSON ShapeBackgRoundFill'{..}
= object
(catMaybes
[("solidFill" .=) <$> _sbrfSolidFill,
("propertyState" .=) <$> _sbrfPropertyState])
-- | Creates bullets for all of the paragraphs that overlap with the given
-- text index range. The nesting level of each paragraph will be determined
-- by counting leading tabs in front of each paragraph. To avoid excess
-- space between the bullet and the corresponding paragraph, these leading
-- tabs are removed by this request. This may change the indices of parts
-- of the text. If the paragraph immediately before paragraphs being
-- updated is in a list with a matching preset, the paragraphs being
-- updated are added to that preceding list.
--
-- /See:/ 'createParagraphBulletsRequest' smart constructor.
data CreateParagraphBulletsRequest =
CreateParagraphBulletsRequest'
{ _cpbrTextRange :: !(Maybe Range)
, _cpbrObjectId :: !(Maybe Text)
, _cpbrBulletPreset :: !(Maybe CreateParagraphBulletsRequestBulletPreset)
, _cpbrCellLocation :: !(Maybe TableCellLocation)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'CreateParagraphBulletsRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cpbrTextRange'
--
-- * 'cpbrObjectId'
--
-- * 'cpbrBulletPreset'
--
-- * 'cpbrCellLocation'
createParagraphBulletsRequest
:: CreateParagraphBulletsRequest
createParagraphBulletsRequest =
CreateParagraphBulletsRequest'
{ _cpbrTextRange = Nothing
, _cpbrObjectId = Nothing
, _cpbrBulletPreset = Nothing
, _cpbrCellLocation = Nothing
}
-- | The range of text to apply the bullet presets to, based on TextElement
-- indexes.
cpbrTextRange :: Lens' CreateParagraphBulletsRequest (Maybe Range)
cpbrTextRange
= lens _cpbrTextRange
(\ s a -> s{_cpbrTextRange = a})
-- | The object ID of the shape or table containing the text to add bullets
-- to.
cpbrObjectId :: Lens' CreateParagraphBulletsRequest (Maybe Text)
cpbrObjectId
= lens _cpbrObjectId (\ s a -> s{_cpbrObjectId = a})
-- | The kinds of bullet glyphs to be used. Defaults to the
-- \`BULLET_DISC_CIRCLE_SQUARE\` preset.
cpbrBulletPreset :: Lens' CreateParagraphBulletsRequest (Maybe CreateParagraphBulletsRequestBulletPreset)
cpbrBulletPreset
= lens _cpbrBulletPreset
(\ s a -> s{_cpbrBulletPreset = a})
-- | The optional table cell location if the text to be modified is in a
-- table cell. If present, the object_id must refer to a table.
cpbrCellLocation :: Lens' CreateParagraphBulletsRequest (Maybe TableCellLocation)
cpbrCellLocation
= lens _cpbrCellLocation
(\ s a -> s{_cpbrCellLocation = a})
instance FromJSON CreateParagraphBulletsRequest where
parseJSON
= withObject "CreateParagraphBulletsRequest"
(\ o ->
CreateParagraphBulletsRequest' <$>
(o .:? "textRange") <*> (o .:? "objectId") <*>
(o .:? "bulletPreset")
<*> (o .:? "cellLocation"))
instance ToJSON CreateParagraphBulletsRequest where
toJSON CreateParagraphBulletsRequest'{..}
= object
(catMaybes
[("textRange" .=) <$> _cpbrTextRange,
("objectId" .=) <$> _cpbrObjectId,
("bulletPreset" .=) <$> _cpbrBulletPreset,
("cellLocation" .=) <$> _cpbrCellLocation])
-- | Updates the alt text title and\/or description of a page element.
--
-- /See:/ 'updatePageElementAltTextRequest' smart constructor.
data UpdatePageElementAltTextRequest =
UpdatePageElementAltTextRequest'
{ _upeatrObjectId :: !(Maybe Text)
, _upeatrTitle :: !(Maybe Text)
, _upeatrDescription :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'UpdatePageElementAltTextRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'upeatrObjectId'
--
-- * 'upeatrTitle'
--
-- * 'upeatrDescription'
updatePageElementAltTextRequest
:: UpdatePageElementAltTextRequest
updatePageElementAltTextRequest =
UpdatePageElementAltTextRequest'
{ _upeatrObjectId = Nothing
, _upeatrTitle = Nothing
, _upeatrDescription = Nothing
}
-- | The object ID of the page element the updates are applied to.
upeatrObjectId :: Lens' UpdatePageElementAltTextRequest (Maybe Text)
upeatrObjectId
= lens _upeatrObjectId
(\ s a -> s{_upeatrObjectId = a})
-- | The updated alt text title of the page element. If unset the existing
-- value will be maintained. The title is exposed to screen readers and
-- other accessibility interfaces. Only use human readable values related
-- to the content of the page element.
upeatrTitle :: Lens' UpdatePageElementAltTextRequest (Maybe Text)
upeatrTitle
= lens _upeatrTitle (\ s a -> s{_upeatrTitle = a})
-- | The updated alt text description of the page element. If unset the
-- existing value will be maintained. The description is exposed to screen
-- readers and other accessibility interfaces. Only use human readable
-- values related to the content of the page element.
upeatrDescription :: Lens' UpdatePageElementAltTextRequest (Maybe Text)
upeatrDescription
= lens _upeatrDescription
(\ s a -> s{_upeatrDescription = a})
instance FromJSON UpdatePageElementAltTextRequest
where
parseJSON
= withObject "UpdatePageElementAltTextRequest"
(\ o ->
UpdatePageElementAltTextRequest' <$>
(o .:? "objectId") <*> (o .:? "title") <*>
(o .:? "description"))
instance ToJSON UpdatePageElementAltTextRequest where
toJSON UpdatePageElementAltTextRequest'{..}
= object
(catMaybes
[("objectId" .=) <$> _upeatrObjectId,
("title" .=) <$> _upeatrTitle,
("description" .=) <$> _upeatrDescription])
-- | Update the properties of a TableCell.
--
-- /See:/ 'updateTableCellPropertiesRequest' smart constructor.
data UpdateTableCellPropertiesRequest =
UpdateTableCellPropertiesRequest'
{ _updObjectId :: !(Maybe Text)
, _updTableCellProperties :: !(Maybe TableCellProperties)
, _updTableRange :: !(Maybe TableRange)
, _updFields :: !(Maybe GFieldMask)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'UpdateTableCellPropertiesRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'updObjectId'
--
-- * 'updTableCellProperties'
--
-- * 'updTableRange'
--
-- * 'updFields'
updateTableCellPropertiesRequest
:: UpdateTableCellPropertiesRequest
updateTableCellPropertiesRequest =
UpdateTableCellPropertiesRequest'
{ _updObjectId = Nothing
, _updTableCellProperties = Nothing
, _updTableRange = Nothing
, _updFields = Nothing
}
-- | The object ID of the table.
updObjectId :: Lens' UpdateTableCellPropertiesRequest (Maybe Text)
updObjectId
= lens _updObjectId (\ s a -> s{_updObjectId = a})
-- | The table cell properties to update.
updTableCellProperties :: Lens' UpdateTableCellPropertiesRequest (Maybe TableCellProperties)
updTableCellProperties
= lens _updTableCellProperties
(\ s a -> s{_updTableCellProperties = a})
-- | The table range representing the subset of the table to which the
-- updates are applied. If a table range is not specified, the updates will
-- apply to the entire table.
updTableRange :: Lens' UpdateTableCellPropertiesRequest (Maybe TableRange)
updTableRange
= lens _updTableRange
(\ s a -> s{_updTableRange = a})
-- | The fields that should be updated. At least one field must be specified.
-- The root \`tableCellProperties\` is implied and should not be specified.
-- A single \`\"*\"\` can be used as short-hand for listing every field.
-- For example to update the table cell background solid fill color, set
-- \`fields\` to \`\"tableCellBackgroundFill.solidFill.color\"\`. To reset
-- a property to its default value, include its field name in the field
-- mask but leave the field itself unset.
updFields :: Lens' UpdateTableCellPropertiesRequest (Maybe GFieldMask)
updFields
= lens _updFields (\ s a -> s{_updFields = a})
instance FromJSON UpdateTableCellPropertiesRequest
where
parseJSON
= withObject "UpdateTableCellPropertiesRequest"
(\ o ->
UpdateTableCellPropertiesRequest' <$>
(o .:? "objectId") <*> (o .:? "tableCellProperties")
<*> (o .:? "tableRange")
<*> (o .:? "fields"))
instance ToJSON UpdateTableCellPropertiesRequest
where
toJSON UpdateTableCellPropertiesRequest'{..}
= object
(catMaybes
[("objectId" .=) <$> _updObjectId,
("tableCellProperties" .=) <$>
_updTableCellProperties,
("tableRange" .=) <$> _updTableRange,
("fields" .=) <$> _updFields])
-- | The properties of the SheetsChart.
--
-- /See:/ 'sheetsChartProperties' smart constructor.
newtype SheetsChartProperties =
SheetsChartProperties'
{ _scpChartImageProperties :: Maybe ImageProperties
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'SheetsChartProperties' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'scpChartImageProperties'
sheetsChartProperties
:: SheetsChartProperties
sheetsChartProperties =
SheetsChartProperties' {_scpChartImageProperties = Nothing}
-- | The properties of the embedded chart image.
scpChartImageProperties :: Lens' SheetsChartProperties (Maybe ImageProperties)
scpChartImageProperties
= lens _scpChartImageProperties
(\ s a -> s{_scpChartImageProperties = a})
instance FromJSON SheetsChartProperties where
parseJSON
= withObject "SheetsChartProperties"
(\ o ->
SheetsChartProperties' <$>
(o .:? "chartImageProperties"))
instance ToJSON SheetsChartProperties where
toJSON SheetsChartProperties'{..}
= object
(catMaybes
[("chartImageProperties" .=) <$>
_scpChartImageProperties])
-- | Styles that apply to a whole paragraph. If this text is contained in a
-- shape with a parent placeholder, then these paragraph styles may be
-- inherited from the parent. Which paragraph styles are inherited depend
-- on the nesting level of lists: * A paragraph not in a list will inherit
-- its paragraph style from the paragraph at the 0 nesting level of the
-- list inside the parent placeholder. * A paragraph in a list will inherit
-- its paragraph style from the paragraph at its corresponding nesting
-- level of the list inside the parent placeholder. Inherited paragraph
-- styles are represented as unset fields in this message.
--
-- /See:/ 'paragraphStyle' smart constructor.
data ParagraphStyle =
ParagraphStyle'
{ _psLineSpacing :: !(Maybe (Textual Double))
, _psDirection :: !(Maybe ParagraphStyleDirection)
, _psIndentFirstLine :: !(Maybe Dimension)
, _psIndentEnd :: !(Maybe Dimension)
, _psIndentStart :: !(Maybe Dimension)
, _psAlignment :: !(Maybe ParagraphStyleAlignment)
, _psSpaceBelow :: !(Maybe Dimension)
, _psSpacingMode :: !(Maybe ParagraphStyleSpacingMode)
, _psSpaceAbove :: !(Maybe Dimension)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ParagraphStyle' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'psLineSpacing'
--
-- * 'psDirection'
--
-- * 'psIndentFirstLine'
--
-- * 'psIndentEnd'
--
-- * 'psIndentStart'
--
-- * 'psAlignment'
--
-- * 'psSpaceBelow'
--
-- * 'psSpacingMode'
--
-- * 'psSpaceAbove'
paragraphStyle
:: ParagraphStyle
paragraphStyle =
ParagraphStyle'
{ _psLineSpacing = Nothing
, _psDirection = Nothing
, _psIndentFirstLine = Nothing
, _psIndentEnd = Nothing
, _psIndentStart = Nothing
, _psAlignment = Nothing
, _psSpaceBelow = Nothing
, _psSpacingMode = Nothing
, _psSpaceAbove = Nothing
}
-- | The amount of space between lines, as a percentage of normal, where
-- normal is represented as 100.0. If unset, the value is inherited from
-- the parent.
psLineSpacing :: Lens' ParagraphStyle (Maybe Double)
psLineSpacing
= lens _psLineSpacing
(\ s a -> s{_psLineSpacing = a})
. mapping _Coerce
-- | The text direction of this paragraph. If unset, the value defaults to
-- LEFT_TO_RIGHT since text direction is not inherited.
psDirection :: Lens' ParagraphStyle (Maybe ParagraphStyleDirection)
psDirection
= lens _psDirection (\ s a -> s{_psDirection = a})
-- | The amount of indentation for the start of the first line of the
-- paragraph. If unset, the value is inherited from the parent.
psIndentFirstLine :: Lens' ParagraphStyle (Maybe Dimension)
psIndentFirstLine
= lens _psIndentFirstLine
(\ s a -> s{_psIndentFirstLine = a})
-- | The amount indentation for the paragraph on the side that corresponds to
-- the end of the text, based on the current text direction. If unset, the
-- value is inherited from the parent.
psIndentEnd :: Lens' ParagraphStyle (Maybe Dimension)
psIndentEnd
= lens _psIndentEnd (\ s a -> s{_psIndentEnd = a})
-- | The amount indentation for the paragraph on the side that corresponds to
-- the start of the text, based on the current text direction. If unset,
-- the value is inherited from the parent.
psIndentStart :: Lens' ParagraphStyle (Maybe Dimension)
psIndentStart
= lens _psIndentStart
(\ s a -> s{_psIndentStart = a})
-- | The text alignment for this paragraph.
psAlignment :: Lens' ParagraphStyle (Maybe ParagraphStyleAlignment)
psAlignment
= lens _psAlignment (\ s a -> s{_psAlignment = a})
-- | The amount of extra space below the paragraph. If unset, the value is
-- inherited from the parent.
psSpaceBelow :: Lens' ParagraphStyle (Maybe Dimension)
psSpaceBelow
= lens _psSpaceBelow (\ s a -> s{_psSpaceBelow = a})
-- | The spacing mode for the paragraph.
psSpacingMode :: Lens' ParagraphStyle (Maybe ParagraphStyleSpacingMode)
psSpacingMode
= lens _psSpacingMode
(\ s a -> s{_psSpacingMode = a})
-- | The amount of extra space above the paragraph. If unset, the value is
-- inherited from the parent.
psSpaceAbove :: Lens' ParagraphStyle (Maybe Dimension)
psSpaceAbove
= lens _psSpaceAbove (\ s a -> s{_psSpaceAbove = a})
instance FromJSON ParagraphStyle where
parseJSON
= withObject "ParagraphStyle"
(\ o ->
ParagraphStyle' <$>
(o .:? "lineSpacing") <*> (o .:? "direction") <*>
(o .:? "indentFirstLine")
<*> (o .:? "indentEnd")
<*> (o .:? "indentStart")
<*> (o .:? "alignment")
<*> (o .:? "spaceBelow")
<*> (o .:? "spacingMode")
<*> (o .:? "spaceAbove"))
instance ToJSON ParagraphStyle where
toJSON ParagraphStyle'{..}
= object
(catMaybes
[("lineSpacing" .=) <$> _psLineSpacing,
("direction" .=) <$> _psDirection,
("indentFirstLine" .=) <$> _psIndentFirstLine,
("indentEnd" .=) <$> _psIndentEnd,
("indentStart" .=) <$> _psIndentStart,
("alignment" .=) <$> _psAlignment,
("spaceBelow" .=) <$> _psSpaceBelow,
("spacingMode" .=) <$> _psSpacingMode,
("spaceAbove" .=) <$> _psSpaceAbove])
-- | The result of creating a table.
--
-- /See:/ 'createTableResponse' smart constructor.
newtype CreateTableResponse =
CreateTableResponse'
{ _ctrtObjectId :: Maybe Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'CreateTableResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ctrtObjectId'
createTableResponse
:: CreateTableResponse
createTableResponse = CreateTableResponse' {_ctrtObjectId = Nothing}
-- | The object ID of the created table.
ctrtObjectId :: Lens' CreateTableResponse (Maybe Text)
ctrtObjectId
= lens _ctrtObjectId (\ s a -> s{_ctrtObjectId = a})
instance FromJSON CreateTableResponse where
parseJSON
= withObject "CreateTableResponse"
(\ o -> CreateTableResponse' <$> (o .:? "objectId"))
instance ToJSON CreateTableResponse where
toJSON CreateTableResponse'{..}
= object
(catMaybes [("objectId" .=) <$> _ctrtObjectId])
-- | Reroutes a line such that it\'s connected at the two closest connection
-- sites on the connected page elements.
--
-- /See:/ 'rerouteLineRequest' smart constructor.
newtype RerouteLineRequest =
RerouteLineRequest'
{ _rlrObjectId :: Maybe Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'RerouteLineRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'rlrObjectId'
rerouteLineRequest
:: RerouteLineRequest
rerouteLineRequest = RerouteLineRequest' {_rlrObjectId = Nothing}
-- | The object ID of the line to reroute. Only a line with a category
-- indicating it is a \"connector\" can be rerouted. The start and end
-- connections of the line must be on different page elements.
rlrObjectId :: Lens' RerouteLineRequest (Maybe Text)
rlrObjectId
= lens _rlrObjectId (\ s a -> s{_rlrObjectId = a})
instance FromJSON RerouteLineRequest where
parseJSON
= withObject "RerouteLineRequest"
(\ o -> RerouteLineRequest' <$> (o .:? "objectId"))
instance ToJSON RerouteLineRequest where
toJSON RerouteLineRequest'{..}
= object
(catMaybes [("objectId" .=) <$> _rlrObjectId])
-- | Properties of each column in a table.
--
-- /See:/ 'tableColumnProperties' smart constructor.
newtype TableColumnProperties =
TableColumnProperties'
{ _tcpColumnWidth :: Maybe Dimension
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'TableColumnProperties' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'tcpColumnWidth'
tableColumnProperties
:: TableColumnProperties
tableColumnProperties = TableColumnProperties' {_tcpColumnWidth = Nothing}
-- | Width of a column.
tcpColumnWidth :: Lens' TableColumnProperties (Maybe Dimension)
tcpColumnWidth
= lens _tcpColumnWidth
(\ s a -> s{_tcpColumnWidth = a})
instance FromJSON TableColumnProperties where
parseJSON
= withObject "TableColumnProperties"
(\ o ->
TableColumnProperties' <$> (o .:? "columnWidth"))
instance ToJSON TableColumnProperties where
toJSON TableColumnProperties'{..}
= object
(catMaybes [("columnWidth" .=) <$> _tcpColumnWidth])
-- | The response of duplicating an object.
--
-- /See:/ 'duplicateObjectResponse' smart constructor.
newtype DuplicateObjectResponse =
DuplicateObjectResponse'
{ _dupObjectId :: Maybe Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'DuplicateObjectResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'dupObjectId'
duplicateObjectResponse
:: DuplicateObjectResponse
duplicateObjectResponse = DuplicateObjectResponse' {_dupObjectId = Nothing}
-- | The ID of the new duplicate object.
dupObjectId :: Lens' DuplicateObjectResponse (Maybe Text)
dupObjectId
= lens _dupObjectId (\ s a -> s{_dupObjectId = a})
instance FromJSON DuplicateObjectResponse where
parseJSON
= withObject "DuplicateObjectResponse"
(\ o ->
DuplicateObjectResponse' <$> (o .:? "objectId"))
instance ToJSON DuplicateObjectResponse where
toJSON DuplicateObjectResponse'{..}
= object
(catMaybes [("objectId" .=) <$> _dupObjectId])
-- | Updates the styling for all of the paragraphs within a Shape or Table
-- that overlap with the given text index range.
--
-- /See:/ 'updateParagraphStyleRequest' smart constructor.
data UpdateParagraphStyleRequest =
UpdateParagraphStyleRequest'
{ _upsrStyle :: !(Maybe ParagraphStyle)
, _upsrTextRange :: !(Maybe Range)
, _upsrObjectId :: !(Maybe Text)
, _upsrCellLocation :: !(Maybe TableCellLocation)
, _upsrFields :: !(Maybe GFieldMask)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'UpdateParagraphStyleRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'upsrStyle'
--
-- * 'upsrTextRange'
--
-- * 'upsrObjectId'
--
-- * 'upsrCellLocation'
--
-- * 'upsrFields'
updateParagraphStyleRequest
:: UpdateParagraphStyleRequest
updateParagraphStyleRequest =
UpdateParagraphStyleRequest'
{ _upsrStyle = Nothing
, _upsrTextRange = Nothing
, _upsrObjectId = Nothing
, _upsrCellLocation = Nothing
, _upsrFields = Nothing
}
-- | The paragraph\'s style.
upsrStyle :: Lens' UpdateParagraphStyleRequest (Maybe ParagraphStyle)
upsrStyle
= lens _upsrStyle (\ s a -> s{_upsrStyle = a})
-- | The range of text containing the paragraph(s) to style.
upsrTextRange :: Lens' UpdateParagraphStyleRequest (Maybe Range)
upsrTextRange
= lens _upsrTextRange
(\ s a -> s{_upsrTextRange = a})
-- | The object ID of the shape or table with the text to be styled.
upsrObjectId :: Lens' UpdateParagraphStyleRequest (Maybe Text)
upsrObjectId
= lens _upsrObjectId (\ s a -> s{_upsrObjectId = a})
-- | The location of the cell in the table containing the paragraph(s) to
-- style. If \`object_id\` refers to a table, \`cell_location\` must have a
-- value. Otherwise, it must not.
upsrCellLocation :: Lens' UpdateParagraphStyleRequest (Maybe TableCellLocation)
upsrCellLocation
= lens _upsrCellLocation
(\ s a -> s{_upsrCellLocation = a})
-- | The fields that should be updated. At least one field must be specified.
-- The root \`style\` is implied and should not be specified. A single
-- \`\"*\"\` can be used as short-hand for listing every field. For
-- example, to update the paragraph alignment, set \`fields\` to
-- \`\"alignment\"\`. To reset a property to its default value, include its
-- field name in the field mask but leave the field itself unset.
upsrFields :: Lens' UpdateParagraphStyleRequest (Maybe GFieldMask)
upsrFields
= lens _upsrFields (\ s a -> s{_upsrFields = a})
instance FromJSON UpdateParagraphStyleRequest where
parseJSON
= withObject "UpdateParagraphStyleRequest"
(\ o ->
UpdateParagraphStyleRequest' <$>
(o .:? "style") <*> (o .:? "textRange") <*>
(o .:? "objectId")
<*> (o .:? "cellLocation")
<*> (o .:? "fields"))
instance ToJSON UpdateParagraphStyleRequest where
toJSON UpdateParagraphStyleRequest'{..}
= object
(catMaybes
[("style" .=) <$> _upsrStyle,
("textRange" .=) <$> _upsrTextRange,
("objectId" .=) <$> _upsrObjectId,
("cellLocation" .=) <$> _upsrCellLocation,
("fields" .=) <$> _upsrFields])
-- | Replaces all instances of text matching a criteria with replace text.
--
-- /See:/ 'replaceAllTextRequest' smart constructor.
data ReplaceAllTextRequest =
ReplaceAllTextRequest'
{ _ratrPageObjectIds :: !(Maybe [Text])
, _ratrContainsText :: !(Maybe SubstringMatchCriteria)
, _ratrReplaceText :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ReplaceAllTextRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ratrPageObjectIds'
--
-- * 'ratrContainsText'
--
-- * 'ratrReplaceText'
replaceAllTextRequest
:: ReplaceAllTextRequest
replaceAllTextRequest =
ReplaceAllTextRequest'
{ _ratrPageObjectIds = Nothing
, _ratrContainsText = Nothing
, _ratrReplaceText = Nothing
}
-- | If non-empty, limits the matches to page elements only on the given
-- pages. Returns a 400 bad request error if given the page object ID of a
-- notes master, or if a page with that object ID doesn\'t exist in the
-- presentation.
ratrPageObjectIds :: Lens' ReplaceAllTextRequest [Text]
ratrPageObjectIds
= lens _ratrPageObjectIds
(\ s a -> s{_ratrPageObjectIds = a})
. _Default
. _Coerce
-- | Finds text in a shape matching this substring.
ratrContainsText :: Lens' ReplaceAllTextRequest (Maybe SubstringMatchCriteria)
ratrContainsText
= lens _ratrContainsText
(\ s a -> s{_ratrContainsText = a})
-- | The text that will replace the matched text.
ratrReplaceText :: Lens' ReplaceAllTextRequest (Maybe Text)
ratrReplaceText
= lens _ratrReplaceText
(\ s a -> s{_ratrReplaceText = a})
instance FromJSON ReplaceAllTextRequest where
parseJSON
= withObject "ReplaceAllTextRequest"
(\ o ->
ReplaceAllTextRequest' <$>
(o .:? "pageObjectIds" .!= mempty) <*>
(o .:? "containsText")
<*> (o .:? "replaceText"))
instance ToJSON ReplaceAllTextRequest where
toJSON ReplaceAllTextRequest'{..}
= object
(catMaybes
[("pageObjectIds" .=) <$> _ratrPageObjectIds,
("containsText" .=) <$> _ratrContainsText,
("replaceText" .=) <$> _ratrReplaceText])
-- | A table range represents a reference to a subset of a table. It\'s
-- important to note that the cells specified by a table range do not
-- necessarily form a rectangle. For example, let\'s say we have a 3 x 3
-- table where all the cells of the last row are merged together. The table
-- looks like this: [ ] A table range with location = (0, 0), row span = 3
-- and column span = 2 specifies the following cells: x x [ x x x ]
--
-- /See:/ 'tableRange' smart constructor.
data TableRange =
TableRange'
{ _trColumnSpan :: !(Maybe (Textual Int32))
, _trLocation :: !(Maybe TableCellLocation)
, _trRowSpan :: !(Maybe (Textual Int32))
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'TableRange' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'trColumnSpan'
--
-- * 'trLocation'
--
-- * 'trRowSpan'
tableRange
:: TableRange
tableRange =
TableRange'
{_trColumnSpan = Nothing, _trLocation = Nothing, _trRowSpan = Nothing}
-- | The column span of the table range.
trColumnSpan :: Lens' TableRange (Maybe Int32)
trColumnSpan
= lens _trColumnSpan (\ s a -> s{_trColumnSpan = a})
. mapping _Coerce
-- | The starting location of the table range.
trLocation :: Lens' TableRange (Maybe TableCellLocation)
trLocation
= lens _trLocation (\ s a -> s{_trLocation = a})
-- | The row span of the table range.
trRowSpan :: Lens' TableRange (Maybe Int32)
trRowSpan
= lens _trRowSpan (\ s a -> s{_trRowSpan = a}) .
mapping _Coerce
instance FromJSON TableRange where
parseJSON
= withObject "TableRange"
(\ o ->
TableRange' <$>
(o .:? "columnSpan") <*> (o .:? "location") <*>
(o .:? "rowSpan"))
instance ToJSON TableRange where
toJSON TableRange'{..}
= object
(catMaybes
[("columnSpan" .=) <$> _trColumnSpan,
("location" .=) <$> _trLocation,
("rowSpan" .=) <$> _trRowSpan])
-- | A single kind of update to apply to a presentation.
--
-- /See:/ 'request'' smart constructor.
data Request' =
Request''
{ _reqReplaceAllShapesWithImage :: !(Maybe ReplaceAllShapesWithImageRequest)
, _reqDeleteObject :: !(Maybe DeleteObjectRequest)
, _reqUpdateSlidesPosition :: !(Maybe UpdateSlidesPositionRequest)
, _reqUpdateShapeProperties :: !(Maybe UpdateShapePropertiesRequest)
, _reqCreateParagraphBullets :: !(Maybe CreateParagraphBulletsRequest)
, _reqUpdateLineCategory :: !(Maybe UpdateLineCategoryRequest)
, _reqCreateLine :: !(Maybe CreateLineRequest)
, _reqInsertText :: !(Maybe InsertTextRequest)
, _reqUpdateTableBOrderProperties :: !(Maybe UpdateTableBOrderPropertiesRequest)
, _reqDeleteParagraphBullets :: !(Maybe DeleteParagraphBulletsRequest)
, _reqDeleteTableRow :: !(Maybe DeleteTableRowRequest)
, _reqUpdateTableCellProperties :: !(Maybe UpdateTableCellPropertiesRequest)
, _reqReplaceAllText :: !(Maybe ReplaceAllTextRequest)
, _reqUpdatePageElementAltText :: !(Maybe UpdatePageElementAltTextRequest)
, _reqUpdateParagraphStyle :: !(Maybe UpdateParagraphStyleRequest)
, _reqRerouteLine :: !(Maybe RerouteLineRequest)
, _reqReplaceImage :: !(Maybe ReplaceImageRequest)
, _reqReplaceAllShapesWithSheetsChart :: !(Maybe ReplaceAllShapesWithSheetsChartRequest)
, _reqCreateShape :: !(Maybe CreateShapeRequest)
, _reqUpdatePageElementsZOrder :: !(Maybe UpdatePageElementsZOrderRequest)
, _reqUpdatePageProperties :: !(Maybe UpdatePagePropertiesRequest)
, _reqUpdateLineProperties :: !(Maybe UpdateLinePropertiesRequest)
, _reqDeleteTableColumn :: !(Maybe DeleteTableColumnRequest)
, _reqGroupObjects :: !(Maybe GroupObjectsRequest)
, _reqDeleteText :: !(Maybe DeleteTextRequest)
, _reqUpdateTableRowProperties :: !(Maybe UpdateTableRowPropertiesRequest)
, _reqCreateSheetsChart :: !(Maybe CreateSheetsChartRequest)
, _reqInsertTableColumns :: !(Maybe InsertTableColumnsRequest)
, _reqUpdateSlideProperties :: !(Maybe UpdateSlidePropertiesRequest)
, _reqUpdateImageProperties :: !(Maybe UpdateImagePropertiesRequest)
, _reqUnGroupObjects :: !(Maybe UnGroupObjectsRequest)
, _reqDuplicateObject :: !(Maybe DuplicateObjectRequest)
, _reqCreateTable :: !(Maybe CreateTableRequest)
, _reqCreateVideo :: !(Maybe CreateVideoRequest)
, _reqRefreshSheetsChart :: !(Maybe RefreshSheetsChartRequest)
, _reqUpdateTableColumnProperties :: !(Maybe UpdateTableColumnPropertiesRequest)
, _reqUnmergeTableCells :: !(Maybe UnmergeTableCellsRequest)
, _reqUpdatePageElementTransform :: !(Maybe UpdatePageElementTransformRequest)
, _reqInsertTableRows :: !(Maybe InsertTableRowsRequest)
, _reqCreateImage :: !(Maybe CreateImageRequest)
, _reqMergeTableCells :: !(Maybe MergeTableCellsRequest)
, _reqCreateSlide :: !(Maybe CreateSlideRequest)
, _reqUpdateTextStyle :: !(Maybe UpdateTextStyleRequest)
, _reqUpdateVideoProperties :: !(Maybe UpdateVideoPropertiesRequest)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Request' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'reqReplaceAllShapesWithImage'
--
-- * 'reqDeleteObject'
--
-- * 'reqUpdateSlidesPosition'
--
-- * 'reqUpdateShapeProperties'
--
-- * 'reqCreateParagraphBullets'
--
-- * 'reqUpdateLineCategory'
--
-- * 'reqCreateLine'
--
-- * 'reqInsertText'
--
-- * 'reqUpdateTableBOrderProperties'
--
-- * 'reqDeleteParagraphBullets'
--
-- * 'reqDeleteTableRow'
--
-- * 'reqUpdateTableCellProperties'
--
-- * 'reqReplaceAllText'
--
-- * 'reqUpdatePageElementAltText'
--
-- * 'reqUpdateParagraphStyle'
--
-- * 'reqRerouteLine'
--
-- * 'reqReplaceImage'
--
-- * 'reqReplaceAllShapesWithSheetsChart'
--
-- * 'reqCreateShape'
--
-- * 'reqUpdatePageElementsZOrder'
--
-- * 'reqUpdatePageProperties'
--
-- * 'reqUpdateLineProperties'
--
-- * 'reqDeleteTableColumn'
--
-- * 'reqGroupObjects'
--
-- * 'reqDeleteText'
--
-- * 'reqUpdateTableRowProperties'
--
-- * 'reqCreateSheetsChart'
--
-- * 'reqInsertTableColumns'
--
-- * 'reqUpdateSlideProperties'
--
-- * 'reqUpdateImageProperties'
--
-- * 'reqUnGroupObjects'
--
-- * 'reqDuplicateObject'
--
-- * 'reqCreateTable'
--
-- * 'reqCreateVideo'
--
-- * 'reqRefreshSheetsChart'
--
-- * 'reqUpdateTableColumnProperties'
--
-- * 'reqUnmergeTableCells'
--
-- * 'reqUpdatePageElementTransform'
--
-- * 'reqInsertTableRows'
--
-- * 'reqCreateImage'
--
-- * 'reqMergeTableCells'
--
-- * 'reqCreateSlide'
--
-- * 'reqUpdateTextStyle'
--
-- * 'reqUpdateVideoProperties'
request'
:: Request'
request' =
Request''
{ _reqReplaceAllShapesWithImage = Nothing
, _reqDeleteObject = Nothing
, _reqUpdateSlidesPosition = Nothing
, _reqUpdateShapeProperties = Nothing
, _reqCreateParagraphBullets = Nothing
, _reqUpdateLineCategory = Nothing
, _reqCreateLine = Nothing
, _reqInsertText = Nothing
, _reqUpdateTableBOrderProperties = Nothing
, _reqDeleteParagraphBullets = Nothing
, _reqDeleteTableRow = Nothing
, _reqUpdateTableCellProperties = Nothing
, _reqReplaceAllText = Nothing
, _reqUpdatePageElementAltText = Nothing
, _reqUpdateParagraphStyle = Nothing
, _reqRerouteLine = Nothing
, _reqReplaceImage = Nothing
, _reqReplaceAllShapesWithSheetsChart = Nothing
, _reqCreateShape = Nothing
, _reqUpdatePageElementsZOrder = Nothing
, _reqUpdatePageProperties = Nothing
, _reqUpdateLineProperties = Nothing
, _reqDeleteTableColumn = Nothing
, _reqGroupObjects = Nothing
, _reqDeleteText = Nothing
, _reqUpdateTableRowProperties = Nothing
, _reqCreateSheetsChart = Nothing
, _reqInsertTableColumns = Nothing
, _reqUpdateSlideProperties = Nothing
, _reqUpdateImageProperties = Nothing
, _reqUnGroupObjects = Nothing
, _reqDuplicateObject = Nothing
, _reqCreateTable = Nothing
, _reqCreateVideo = Nothing
, _reqRefreshSheetsChart = Nothing
, _reqUpdateTableColumnProperties = Nothing
, _reqUnmergeTableCells = Nothing
, _reqUpdatePageElementTransform = Nothing
, _reqInsertTableRows = Nothing
, _reqCreateImage = Nothing
, _reqMergeTableCells = Nothing
, _reqCreateSlide = Nothing
, _reqUpdateTextStyle = Nothing
, _reqUpdateVideoProperties = Nothing
}
-- | Replaces all shapes matching some criteria with an image.
reqReplaceAllShapesWithImage :: Lens' Request' (Maybe ReplaceAllShapesWithImageRequest)
reqReplaceAllShapesWithImage
= lens _reqReplaceAllShapesWithImage
(\ s a -> s{_reqReplaceAllShapesWithImage = a})
-- | Deletes a page or page element from the presentation.
reqDeleteObject :: Lens' Request' (Maybe DeleteObjectRequest)
reqDeleteObject
= lens _reqDeleteObject
(\ s a -> s{_reqDeleteObject = a})
-- | Updates the position of a set of slides in the presentation.
reqUpdateSlidesPosition :: Lens' Request' (Maybe UpdateSlidesPositionRequest)
reqUpdateSlidesPosition
= lens _reqUpdateSlidesPosition
(\ s a -> s{_reqUpdateSlidesPosition = a})
-- | Updates the properties of a Shape.
reqUpdateShapeProperties :: Lens' Request' (Maybe UpdateShapePropertiesRequest)
reqUpdateShapeProperties
= lens _reqUpdateShapeProperties
(\ s a -> s{_reqUpdateShapeProperties = a})
-- | Creates bullets for paragraphs.
reqCreateParagraphBullets :: Lens' Request' (Maybe CreateParagraphBulletsRequest)
reqCreateParagraphBullets
= lens _reqCreateParagraphBullets
(\ s a -> s{_reqCreateParagraphBullets = a})
-- | Updates the category of a line.
reqUpdateLineCategory :: Lens' Request' (Maybe UpdateLineCategoryRequest)
reqUpdateLineCategory
= lens _reqUpdateLineCategory
(\ s a -> s{_reqUpdateLineCategory = a})
-- | Creates a line.
reqCreateLine :: Lens' Request' (Maybe CreateLineRequest)
reqCreateLine
= lens _reqCreateLine
(\ s a -> s{_reqCreateLine = a})
-- | Inserts text into a shape or table cell.
reqInsertText :: Lens' Request' (Maybe InsertTextRequest)
reqInsertText
= lens _reqInsertText
(\ s a -> s{_reqInsertText = a})
-- | Updates the properties of the table borders in a Table.
reqUpdateTableBOrderProperties :: Lens' Request' (Maybe UpdateTableBOrderPropertiesRequest)
reqUpdateTableBOrderProperties
= lens _reqUpdateTableBOrderProperties
(\ s a -> s{_reqUpdateTableBOrderProperties = a})
-- | Deletes bullets from paragraphs.
reqDeleteParagraphBullets :: Lens' Request' (Maybe DeleteParagraphBulletsRequest)
reqDeleteParagraphBullets
= lens _reqDeleteParagraphBullets
(\ s a -> s{_reqDeleteParagraphBullets = a})
-- | Deletes a row from a table.
reqDeleteTableRow :: Lens' Request' (Maybe DeleteTableRowRequest)
reqDeleteTableRow
= lens _reqDeleteTableRow
(\ s a -> s{_reqDeleteTableRow = a})
-- | Updates the properties of a TableCell.
reqUpdateTableCellProperties :: Lens' Request' (Maybe UpdateTableCellPropertiesRequest)
reqUpdateTableCellProperties
= lens _reqUpdateTableCellProperties
(\ s a -> s{_reqUpdateTableCellProperties = a})
-- | Replaces all instances of specified text.
reqReplaceAllText :: Lens' Request' (Maybe ReplaceAllTextRequest)
reqReplaceAllText
= lens _reqReplaceAllText
(\ s a -> s{_reqReplaceAllText = a})
-- | Updates the alt text title and\/or description of a page element.
reqUpdatePageElementAltText :: Lens' Request' (Maybe UpdatePageElementAltTextRequest)
reqUpdatePageElementAltText
= lens _reqUpdatePageElementAltText
(\ s a -> s{_reqUpdatePageElementAltText = a})
-- | Updates the styling of paragraphs within a Shape or Table.
reqUpdateParagraphStyle :: Lens' Request' (Maybe UpdateParagraphStyleRequest)
reqUpdateParagraphStyle
= lens _reqUpdateParagraphStyle
(\ s a -> s{_reqUpdateParagraphStyle = a})
-- | Reroutes a line such that it\'s connected at the two closest connection
-- sites on the connected page elements.
reqRerouteLine :: Lens' Request' (Maybe RerouteLineRequest)
reqRerouteLine
= lens _reqRerouteLine
(\ s a -> s{_reqRerouteLine = a})
-- | Replaces an existing image with a new image.
reqReplaceImage :: Lens' Request' (Maybe ReplaceImageRequest)
reqReplaceImage
= lens _reqReplaceImage
(\ s a -> s{_reqReplaceImage = a})
-- | Replaces all shapes matching some criteria with a Google Sheets chart.
reqReplaceAllShapesWithSheetsChart :: Lens' Request' (Maybe ReplaceAllShapesWithSheetsChartRequest)
reqReplaceAllShapesWithSheetsChart
= lens _reqReplaceAllShapesWithSheetsChart
(\ s a -> s{_reqReplaceAllShapesWithSheetsChart = a})
-- | Creates a new shape.
reqCreateShape :: Lens' Request' (Maybe CreateShapeRequest)
reqCreateShape
= lens _reqCreateShape
(\ s a -> s{_reqCreateShape = a})
-- | Updates the Z-order of page elements.
reqUpdatePageElementsZOrder :: Lens' Request' (Maybe UpdatePageElementsZOrderRequest)
reqUpdatePageElementsZOrder
= lens _reqUpdatePageElementsZOrder
(\ s a -> s{_reqUpdatePageElementsZOrder = a})
-- | Updates the properties of a Page.
reqUpdatePageProperties :: Lens' Request' (Maybe UpdatePagePropertiesRequest)
reqUpdatePageProperties
= lens _reqUpdatePageProperties
(\ s a -> s{_reqUpdatePageProperties = a})
-- | Updates the properties of a Line.
reqUpdateLineProperties :: Lens' Request' (Maybe UpdateLinePropertiesRequest)
reqUpdateLineProperties
= lens _reqUpdateLineProperties
(\ s a -> s{_reqUpdateLineProperties = a})
-- | Deletes a column from a table.
reqDeleteTableColumn :: Lens' Request' (Maybe DeleteTableColumnRequest)
reqDeleteTableColumn
= lens _reqDeleteTableColumn
(\ s a -> s{_reqDeleteTableColumn = a})
-- | Groups objects, such as page elements.
reqGroupObjects :: Lens' Request' (Maybe GroupObjectsRequest)
reqGroupObjects
= lens _reqGroupObjects
(\ s a -> s{_reqGroupObjects = a})
-- | Deletes text from a shape or a table cell.
reqDeleteText :: Lens' Request' (Maybe DeleteTextRequest)
reqDeleteText
= lens _reqDeleteText
(\ s a -> s{_reqDeleteText = a})
-- | Updates the properties of a Table row.
reqUpdateTableRowProperties :: Lens' Request' (Maybe UpdateTableRowPropertiesRequest)
reqUpdateTableRowProperties
= lens _reqUpdateTableRowProperties
(\ s a -> s{_reqUpdateTableRowProperties = a})
-- | Creates an embedded Google Sheets chart.
reqCreateSheetsChart :: Lens' Request' (Maybe CreateSheetsChartRequest)
reqCreateSheetsChart
= lens _reqCreateSheetsChart
(\ s a -> s{_reqCreateSheetsChart = a})
-- | Inserts columns into a table.
reqInsertTableColumns :: Lens' Request' (Maybe InsertTableColumnsRequest)
reqInsertTableColumns
= lens _reqInsertTableColumns
(\ s a -> s{_reqInsertTableColumns = a})
-- | Updates the properties of a Slide
reqUpdateSlideProperties :: Lens' Request' (Maybe UpdateSlidePropertiesRequest)
reqUpdateSlideProperties
= lens _reqUpdateSlideProperties
(\ s a -> s{_reqUpdateSlideProperties = a})
-- | Updates the properties of an Image.
reqUpdateImageProperties :: Lens' Request' (Maybe UpdateImagePropertiesRequest)
reqUpdateImageProperties
= lens _reqUpdateImageProperties
(\ s a -> s{_reqUpdateImageProperties = a})
-- | Ungroups objects, such as groups.
reqUnGroupObjects :: Lens' Request' (Maybe UnGroupObjectsRequest)
reqUnGroupObjects
= lens _reqUnGroupObjects
(\ s a -> s{_reqUnGroupObjects = a})
-- | Duplicates a slide or page element.
reqDuplicateObject :: Lens' Request' (Maybe DuplicateObjectRequest)
reqDuplicateObject
= lens _reqDuplicateObject
(\ s a -> s{_reqDuplicateObject = a})
-- | Creates a new table.
reqCreateTable :: Lens' Request' (Maybe CreateTableRequest)
reqCreateTable
= lens _reqCreateTable
(\ s a -> s{_reqCreateTable = a})
-- | Creates a video.
reqCreateVideo :: Lens' Request' (Maybe CreateVideoRequest)
reqCreateVideo
= lens _reqCreateVideo
(\ s a -> s{_reqCreateVideo = a})
-- | Refreshes a Google Sheets chart.
reqRefreshSheetsChart :: Lens' Request' (Maybe RefreshSheetsChartRequest)
reqRefreshSheetsChart
= lens _reqRefreshSheetsChart
(\ s a -> s{_reqRefreshSheetsChart = a})
-- | Updates the properties of a Table column.
reqUpdateTableColumnProperties :: Lens' Request' (Maybe UpdateTableColumnPropertiesRequest)
reqUpdateTableColumnProperties
= lens _reqUpdateTableColumnProperties
(\ s a -> s{_reqUpdateTableColumnProperties = a})
-- | Unmerges cells in a Table.
reqUnmergeTableCells :: Lens' Request' (Maybe UnmergeTableCellsRequest)
reqUnmergeTableCells
= lens _reqUnmergeTableCells
(\ s a -> s{_reqUnmergeTableCells = a})
-- | Updates the transform of a page element.
reqUpdatePageElementTransform :: Lens' Request' (Maybe UpdatePageElementTransformRequest)
reqUpdatePageElementTransform
= lens _reqUpdatePageElementTransform
(\ s a -> s{_reqUpdatePageElementTransform = a})
-- | Inserts rows into a table.
reqInsertTableRows :: Lens' Request' (Maybe InsertTableRowsRequest)
reqInsertTableRows
= lens _reqInsertTableRows
(\ s a -> s{_reqInsertTableRows = a})
-- | Creates an image.
reqCreateImage :: Lens' Request' (Maybe CreateImageRequest)
reqCreateImage
= lens _reqCreateImage
(\ s a -> s{_reqCreateImage = a})
-- | Merges cells in a Table.
reqMergeTableCells :: Lens' Request' (Maybe MergeTableCellsRequest)
reqMergeTableCells
= lens _reqMergeTableCells
(\ s a -> s{_reqMergeTableCells = a})
-- | Creates a new slide.
reqCreateSlide :: Lens' Request' (Maybe CreateSlideRequest)
reqCreateSlide
= lens _reqCreateSlide
(\ s a -> s{_reqCreateSlide = a})
-- | Updates the styling of text within a Shape or Table.
reqUpdateTextStyle :: Lens' Request' (Maybe UpdateTextStyleRequest)
reqUpdateTextStyle
= lens _reqUpdateTextStyle
(\ s a -> s{_reqUpdateTextStyle = a})
-- | Updates the properties of a Video.
reqUpdateVideoProperties :: Lens' Request' (Maybe UpdateVideoPropertiesRequest)
reqUpdateVideoProperties
= lens _reqUpdateVideoProperties
(\ s a -> s{_reqUpdateVideoProperties = a})
instance FromJSON Request' where
parseJSON
= withObject "Request"
(\ o ->
Request'' <$>
(o .:? "replaceAllShapesWithImage") <*>
(o .:? "deleteObject")
<*> (o .:? "updateSlidesPosition")
<*> (o .:? "updateShapeProperties")
<*> (o .:? "createParagraphBullets")
<*> (o .:? "updateLineCategory")
<*> (o .:? "createLine")
<*> (o .:? "insertText")
<*> (o .:? "updateTableBorderProperties")
<*> (o .:? "deleteParagraphBullets")
<*> (o .:? "deleteTableRow")
<*> (o .:? "updateTableCellProperties")
<*> (o .:? "replaceAllText")
<*> (o .:? "updatePageElementAltText")
<*> (o .:? "updateParagraphStyle")
<*> (o .:? "rerouteLine")
<*> (o .:? "replaceImage")
<*> (o .:? "replaceAllShapesWithSheetsChart")
<*> (o .:? "createShape")
<*> (o .:? "updatePageElementsZOrder")
<*> (o .:? "updatePageProperties")
<*> (o .:? "updateLineProperties")
<*> (o .:? "deleteTableColumn")
<*> (o .:? "groupObjects")
<*> (o .:? "deleteText")
<*> (o .:? "updateTableRowProperties")
<*> (o .:? "createSheetsChart")
<*> (o .:? "insertTableColumns")
<*> (o .:? "updateSlideProperties")
<*> (o .:? "updateImageProperties")
<*> (o .:? "ungroupObjects")
<*> (o .:? "duplicateObject")
<*> (o .:? "createTable")
<*> (o .:? "createVideo")
<*> (o .:? "refreshSheetsChart")
<*> (o .:? "updateTableColumnProperties")
<*> (o .:? "unmergeTableCells")
<*> (o .:? "updatePageElementTransform")
<*> (o .:? "insertTableRows")
<*> (o .:? "createImage")
<*> (o .:? "mergeTableCells")
<*> (o .:? "createSlide")
<*> (o .:? "updateTextStyle")
<*> (o .:? "updateVideoProperties"))
instance ToJSON Request' where
toJSON Request''{..}
= object
(catMaybes
[("replaceAllShapesWithImage" .=) <$>
_reqReplaceAllShapesWithImage,
("deleteObject" .=) <$> _reqDeleteObject,
("updateSlidesPosition" .=) <$>
_reqUpdateSlidesPosition,
("updateShapeProperties" .=) <$>
_reqUpdateShapeProperties,
("createParagraphBullets" .=) <$>
_reqCreateParagraphBullets,
("updateLineCategory" .=) <$> _reqUpdateLineCategory,
("createLine" .=) <$> _reqCreateLine,
("insertText" .=) <$> _reqInsertText,
("updateTableBorderProperties" .=) <$>
_reqUpdateTableBOrderProperties,
("deleteParagraphBullets" .=) <$>
_reqDeleteParagraphBullets,
("deleteTableRow" .=) <$> _reqDeleteTableRow,
("updateTableCellProperties" .=) <$>
_reqUpdateTableCellProperties,
("replaceAllText" .=) <$> _reqReplaceAllText,
("updatePageElementAltText" .=) <$>
_reqUpdatePageElementAltText,
("updateParagraphStyle" .=) <$>
_reqUpdateParagraphStyle,
("rerouteLine" .=) <$> _reqRerouteLine,
("replaceImage" .=) <$> _reqReplaceImage,
("replaceAllShapesWithSheetsChart" .=) <$>
_reqReplaceAllShapesWithSheetsChart,
("createShape" .=) <$> _reqCreateShape,
("updatePageElementsZOrder" .=) <$>
_reqUpdatePageElementsZOrder,
("updatePageProperties" .=) <$>
_reqUpdatePageProperties,
("updateLineProperties" .=) <$>
_reqUpdateLineProperties,
("deleteTableColumn" .=) <$> _reqDeleteTableColumn,
("groupObjects" .=) <$> _reqGroupObjects,
("deleteText" .=) <$> _reqDeleteText,
("updateTableRowProperties" .=) <$>
_reqUpdateTableRowProperties,
("createSheetsChart" .=) <$> _reqCreateSheetsChart,
("insertTableColumns" .=) <$> _reqInsertTableColumns,
("updateSlideProperties" .=) <$>
_reqUpdateSlideProperties,
("updateImageProperties" .=) <$>
_reqUpdateImageProperties,
("ungroupObjects" .=) <$> _reqUnGroupObjects,
("duplicateObject" .=) <$> _reqDuplicateObject,
("createTable" .=) <$> _reqCreateTable,
("createVideo" .=) <$> _reqCreateVideo,
("refreshSheetsChart" .=) <$> _reqRefreshSheetsChart,
("updateTableColumnProperties" .=) <$>
_reqUpdateTableColumnProperties,
("unmergeTableCells" .=) <$> _reqUnmergeTableCells,
("updatePageElementTransform" .=) <$>
_reqUpdatePageElementTransform,
("insertTableRows" .=) <$> _reqInsertTableRows,
("createImage" .=) <$> _reqCreateImage,
("mergeTableCells" .=) <$> _reqMergeTableCells,
("createSlide" .=) <$> _reqCreateSlide,
("updateTextStyle" .=) <$> _reqUpdateTextStyle,
("updateVideoProperties" .=) <$>
_reqUpdateVideoProperties])
-- | A criteria that matches a specific string of text in a shape or table.
--
-- /See:/ 'substringMatchCriteria' smart constructor.
data SubstringMatchCriteria =
SubstringMatchCriteria'
{ _smcMatchCase :: !(Maybe Bool)
, _smcText :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'SubstringMatchCriteria' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'smcMatchCase'
--
-- * 'smcText'
substringMatchCriteria
:: SubstringMatchCriteria
substringMatchCriteria =
SubstringMatchCriteria' {_smcMatchCase = Nothing, _smcText = Nothing}
-- | Indicates whether the search should respect case: - \`True\`: the search
-- is case sensitive. - \`False\`: the search is case insensitive.
smcMatchCase :: Lens' SubstringMatchCriteria (Maybe Bool)
smcMatchCase
= lens _smcMatchCase (\ s a -> s{_smcMatchCase = a})
-- | The text to search for in the shape or table.
smcText :: Lens' SubstringMatchCriteria (Maybe Text)
smcText = lens _smcText (\ s a -> s{_smcText = a})
instance FromJSON SubstringMatchCriteria where
parseJSON
= withObject "SubstringMatchCriteria"
(\ o ->
SubstringMatchCriteria' <$>
(o .:? "matchCase") <*> (o .:? "text"))
instance ToJSON SubstringMatchCriteria where
toJSON SubstringMatchCriteria'{..}
= object
(catMaybes
[("matchCase" .=) <$> _smcMatchCase,
("text" .=) <$> _smcText])
| brendanhay/gogol | gogol-slides/gen/Network/Google/Slides/Types/Product.hs | mpl-2.0 | 338,645 | 0 | 54 | 79,205 | 57,016 | 32,926 | 24,090 | 6,304 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.