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 TemplateHaskell #-} makeLenses '' PostscriptFont
mpickering/ghc-exactprint
tests/examples/ghc710/SpacesSplice.hs
bsd-3-clause
74
0
6
19
10
4
6
2
0
{-# LANGUAGE CPP, DeriveDataTypeable #-} {-# OPTIONS -Wall #-} module Language.Paraiso.Optimization.Identity ( identity ) where import qualified Data.Graph.Inductive as FGL import qualified Language.Paraiso.Annotation as Anot import Language.Paraiso.Prelude import Language.Paraiso.OM.Graph import Language.Paraiso.Optimization.Graph -- | an optimization that changes nothing. identity :: Optimization identity graph = imap update graph where update :: FGL.Node -> Anot.Annotation -> Anot.Annotation update i a = const a i
nushio3/Paraiso
Language/Paraiso/Optimization/Identity.hs
bsd-3-clause
576
0
9
115
108
67
41
13
1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE NoMonomorphismRestriction #-} module Yi.Paths ( getEvaluatorContextFilename , getConfigFilename , getConfigModules , getArticleDbFilename , getPersistentStateFilename , getConfigDir , getConfigPath , getCustomConfigPath , getDataPath ) where import Control.Monad (liftM) import Control.Monad.Base (MonadBase, liftBase) import System.Directory (createDirectoryIfMissing, doesDirectoryExist, getAppUserDataDirectory) import qualified System.Environment.XDG.BaseDir as XDG (getUserConfigDir, getUserDataDir) import System.FilePath ((</>)) appUserDataCond ::(MonadBase IO m) => (String -> IO FilePath) -> m FilePath appUserDataCond dirQuery = liftBase $ do oldDir <- getAppUserDataDirectory "yi" newDir <- dirQuery "yi" oldDirExists <- doesDirectoryExist oldDir newDirExists <- doesDirectoryExist newDir if newDirExists -- overrides old-style then return newDir else if oldDirExists -- old-style exists, use it then return oldDir else do createDirectoryIfMissing True newDir -- none exists, use new style, but create it return newDir getConfigDir ::(MonadBase IO m) => m FilePath getConfigDir = appUserDataCond XDG.getUserConfigDir getDataDir ::(MonadBase IO m) => m FilePath getDataDir = appUserDataCond XDG.getUserDataDir -- | Given a path relative to application data directory, -- this function finds a path to a given data file. getDataPath :: (MonadBase IO m) => FilePath -> m FilePath getDataPath fp = liftM (</> fp) getDataDir -- | Given a path relative to application configuration directory, -- this function finds a path to a given configuration file. getConfigPath :: MonadBase IO m => FilePath -> m FilePath getConfigPath = getCustomConfigPath getConfigDir -- | Given an action that retrieves config path, and a path relative to it, -- this function joins the two together to create a config file path. getCustomConfigPath :: MonadBase IO m => m FilePath -> FilePath -> m FilePath getCustomConfigPath cd fp = (</> fp) `liftM` cd -- Note: Dyre also uses XDG cache dir - that would be: --getCachePath = getPathHelper XDG.getUserCacheDirectory -- Below are all points that are used in Yi code (to keep it clean.) getEvaluatorContextFilename, getConfigFilename, getConfigModules, getArticleDbFilename, getPersistentStateFilename :: (MonadBase IO m) => m FilePath -- | Get Yi master configuration script. getConfigFilename = getConfigPath "yi.hs" getConfigModules = getConfigPath "modules" -- | Get articles.db database of locations to visit (for Yi.IReader.) getArticleDbFilename = getConfigPath "articles.db" -- | Get path to Yi history that stores state between runs. getPersistentStateFilename = getDataPath "history" -- | Get path to environment file that defines namespace used by Yi -- command evaluator. getEvaluatorContextFilename = getConfigPath $ "local" </> "Env.hs"
TOSPIO/yi
src/library/Yi/Paths.hs
gpl-2.0
3,295
0
12
842
495
276
219
47
3
{-# LANGUAGE TemplateHaskell, QuasiQuotes, DeriveDataTypeable #-} import Control.Monad hiding (void) import Data.Typeable import Language.C.Quote.ObjC import Language.C.Inline.ObjC objc_import ["<Foundation/Foundation.h>"] newtype NSString = NSString (ForeignPtr NSString) deriving Typeable -- needed for now until migrating to new TH objc_typecheck -- make the above type declaration known to Template Haskell stringToNSString :: String -> IO NSString stringToNSString str = $(objc ['str :> ''String] $ Class ''NSString <: [cexp| str |]) newtype NSMutableArray e = NSMutableArray (ForeignPtr (NSMutableArray e)) deriving Typeable -- needed for now until migrating to new TH newtype NSArray e = NSArray (ForeignPtr (NSArray e)) deriving Typeable -- needed for now until migrating to new TH unsafeFreezeNSMutableArray :: NSMutableArray e -> NSArray e unsafeFreezeNSMutableArray (NSMutableArray fptr) = NSArray $ castForeignPtr fptr objc_typecheck listOfStringToNSArray :: [String] -> IO (NSArray NSString) listOfStringToNSArray strs = do { marr <- $(objc [] $ Class [t|NSMutableArray NSString|] <: [cexp| [NSMutableArray arrayWithCapacity:10] |]) ; mapM_ (addElement marr) strs ; return $ unsafeFreezeNSMutableArray marr } where addElement marr str = $(objc ['marr :> Class [t|NSMutableArray NSString|], 'str :> ''String] $ void [cexp| [marr addObject:str] |]) nsArrayToListOfString :: NSArray NSString -> IO [String] nsArrayToListOfString = error "not needed here" objc_marshaller 'listOfStringToNSArray 'nsArrayToListOfString go :: IO () go = $(objc ['msgs :> [t| [String] |]] $ void [cexp| NSLog(@"%@", msgs.description) |]) where msgs = ["Hello", "World!", "This is a bunch of 'String's!"] objc_emit main = objc_initialise >> go
beni55/language-c-inline
tests/objc/marshal-array/Main.hs
bsd-3-clause
1,819
3
13
314
470
257
213
35
1
{-| Module : Language.Qux.Annotated.TypeResolver Description : Type resolving functions that transform the abstract syntax tree to a typed one. Copyright : (c) Henry J. Wylde, 2015 License : BSD3 Maintainer : [email protected] Type resolving functions that transform the abstract syntax tree to a typed one. These functions will transform every 'Ann.Expr' into an 'Ann.TypedExpr' and return the transformed tree. The "Language.Qux.Annotated.TypeChecker" and "Language.Qux.Llvm.Compiler" modules require the tree to be typed. -} module Language.Qux.Annotated.TypeResolver ( module Language.Qux.Context, -- * Environment Resolve, runResolve, -- * Local context Locals, -- * Type resolving resolveProgram, resolveDecl, resolveStmt, resolveExpr, resolveValue, extractType, ) where import Control.Lens hiding (Context) import Control.Monad.Reader import Control.Monad.State import Control.Monad.Writer import Data.Map (Map) import qualified Data.Map as Map import Data.Maybe import Language.Qux.Annotated.Exception import Language.Qux.Annotated.Parser import Language.Qux.Annotated.Syntax (simp) import qualified Language.Qux.Annotated.Syntax as Ann import Language.Qux.Context import Language.Qux.Syntax -- | A type that allows resolving types. -- Requires a 'Context' for evaluation. type Resolve = ReaderT Context (Writer [ResolveException]) -- | Runs the given resolve with the context. runResolve :: Resolve a -> Context -> (a, [ResolveException]) runResolve resolve context = runWriter $ runReaderT resolve context -- | Local context. -- This is a map of variable names to types (e.g., parameters). type Locals = Map Id Type -- | Resolves the types of a program. resolveProgram :: Ann.Program SourcePos -> Resolve (Ann.Program SourcePos) resolveProgram (Ann.Program pos module_ decls) = mapM resolveDecl decls >>= \decls' -> return $ Ann.Program pos module_ decls' -- | Resolves the types of a declaration. resolveDecl :: Ann.Decl SourcePos -> Resolve (Ann.Decl SourcePos) resolveDecl (Ann.FunctionDecl pos attrs name type_ stmts) = do stmts' <- evalStateT (resolveBlock stmts) (Map.fromList [(simp p, simp t) | (t, p) <- type_]) return $ Ann.FunctionDecl pos attrs name type_ stmts' resolveDecl decl = return decl resolveBlock :: [Ann.Stmt SourcePos] -> StateT Locals Resolve [Ann.Stmt SourcePos] resolveBlock = mapM resolveStmt -- | Resolves the types of a statement. resolveStmt :: Ann.Stmt SourcePos -> StateT Locals Resolve (Ann.Stmt SourcePos) resolveStmt (Ann.IfStmt pos condition trueStmts falseStmts) = do condition' <- resolveExpr condition trueStmts' <- resolveBlock trueStmts falseStmts' <- resolveBlock falseStmts return $ Ann.IfStmt pos condition' trueStmts' falseStmts' resolveStmt (Ann.CallStmt pos expr) = do expr' <- resolveExpr expr return $ Ann.CallStmt pos expr' resolveStmt (Ann.ReturnStmt pos mExpr) = do mExpr' <- mapM resolveExpr mExpr return $ Ann.ReturnStmt pos mExpr' resolveStmt (Ann.WhileStmt pos condition stmts) = do condition' <- resolveExpr condition stmts' <- resolveBlock stmts return $ Ann.WhileStmt pos condition' stmts' -- | Resolves the types of an expression. resolveExpr :: Ann.Expr SourcePos -> StateT Locals Resolve (Ann.Expr SourcePos) resolveExpr (Ann.ApplicationExpr {}) = error "internal error: cannot resolve the type of a non-qualified expression (try applying name resolution)" resolveExpr (Ann.BinaryExpr pos op lhs rhs) = do lhs' <- resolveExpr lhs rhs' <- resolveExpr rhs let type_ = case op of Mul -> IntType Div -> IntType Mod -> IntType Add -> extractType lhs' Sub -> extractType lhs' Lt -> BoolType Lte -> BoolType Gt -> BoolType Gte -> BoolType Eq -> BoolType Neq -> BoolType return $ Ann.TypedExpr pos type_ (Ann.BinaryExpr pos op lhs' rhs') resolveExpr (Ann.CallExpr pos id arguments) = views functions (Map.lookup $ map simp id) >>= maybe (error "internal error: undefined function call has no type (try applying name resolution)") (\type_ -> do arguments_ <- mapM resolveExpr arguments return $ Ann.TypedExpr pos (fst $ last type_) (Ann.CallExpr pos id arguments_)) resolveExpr e@(Ann.TypedExpr {}) = return e resolveExpr (Ann.UnaryExpr pos op expr) = do expr' <- resolveExpr expr return $ Ann.TypedExpr pos IntType (Ann.UnaryExpr pos op expr') resolveExpr e@(Ann.ValueExpr pos value) = return $ Ann.TypedExpr pos (resolveValue value) e resolveExpr e@(Ann.VariableExpr pos name) = gets (fromJust . Map.lookup (simp name)) >>= \type_ -> return $ Ann.TypedExpr pos type_ e -- | Resolves the type of a value. resolveValue :: Value -> Type resolveValue (BoolValue _) = BoolType resolveValue (IntValue _) = IntType resolveValue (StrValue _) = StrType -- | Extracts the type from a 'Ann.TypedExpr'. -- If the expression isn't an 'Ann.TypedExpr', an error is raised. extractType :: Ann.Expr a -> Type extractType (Ann.TypedExpr _ type_ _) = type_ extractType _ = error "internal error: type resolution not complete"
qux-lang/language-qux
src/Language/Qux/Annotated/TypeResolver.hs
bsd-3-clause
5,452
0
15
1,261
1,323
676
647
84
11
{-# Language PatternGuards #-} module Blub ( blub , foo , bar ) where import Control.Applicative (r, t, z) import Ugah.Blub ( a , b , c ) import Data.Text f :: Int -> Int f = (+ 3) r :: Int -> Int r =
dan-t/hsimport
tests/goldenFiles/SymbolTest49.hs
bsd-3-clause
229
1
6
74
83
52
31
-1
-1
module Hpack.HaskellSpec (spec) where import Test.Hspec import Hpack.Haskell spec :: Spec spec = do describe "isModule" $ do it "accepts module names" $ do isModule ["Foo", "Bar"] `shouldBe` True it "rejects the empty list" $ do isModule [] `shouldBe` False describe "isQualifiedIdentifier" $ do it "accepts qualified Haskell identifiers" $ do isQualifiedIdentifier ["Foo", "Bar", "baz"] `shouldBe` True it "rejects invalid input" $ do isQualifiedIdentifier ["Foo", "Bar", "Baz"] `shouldBe` False describe "isIdentifier" $ do it "accepts Haskell identifiers" $ do isIdentifier "foo" `shouldBe` True it "rejects reserved keywords" $ do isIdentifier "case" `shouldBe` False it "rejects invalid input" $ do isIdentifier "Foo" `shouldBe` False
haskell-tinc/hpack
test/Hpack/HaskellSpec.hs
mit
845
0
15
208
241
118
123
22
1
{-# LANGUAGE OverloadedStrings #-} import System.Random import System.Environment import Debug.Trace import Data.List import Control.DeepSeq import Data.Map (Map) import qualified Data.Map as Map -- ---------------------------------------------------------------------------- -- <<Talk newtype Talk = Talk Int deriving (Eq,Ord) instance NFData Talk where rnf (Talk x) = x `seq` () instance Show Talk where show (Talk t) = show t -- >> -- <<Person data Person = Person { name :: String , talks :: [Talk] } deriving (Show) -- >> -- <<TimeTable type TimeTable = [[Talk]] -- >> -- ---------------------------------------------------------------------------- -- The parallel skeleton -- <<search_type search :: ( partial -> Maybe solution ) -- <1> -> ( partial -> [ partial ] ) -- <2> -> partial -- <3> -> [solution] -- <4> -- >> -- <<search search finished refine emptysoln = generate emptysoln where generate partial | Just soln <- finished partial = [soln] | otherwise = concat (map generate (refine partial)) -- >> -- ---------------------------------------------------------------------------- -- <<Partial type Partial = (Int, Int, [[Talk]], [Talk], [Talk], [Talk]) -- >> -- <<timetable timetable :: [Person] -> [Talk] -> Int -> Int -> [TimeTable] timetable people allTalks maxTrack maxSlot = search finished refine emptysoln where emptysoln = (0, 0, [], [], allTalks, allTalks) finished (slotNo, trackNo, slots, slot, slotTalks, talks) | slotNo == maxSlot = Just slots | otherwise = Nothing clashes :: Map Talk [Talk] clashes = Map.fromListWith union [ (t, ts) | s <- people , (t, ts) <- selects (talks s) ] refine (slotNo, trackNo, slots, slot, slotTalks, talks) | trackNo == maxTrack = [(slotNo+1, 0, slot:slots, [], talks, talks)] | otherwise = [ (slotNo, trackNo+1, slots, t:slot, slotTalks', talks') | (t, ts) <- selects slotTalks , let clashesWithT = Map.findWithDefault [] t clashes , let slotTalks' = filter (`notElem` clashesWithT) ts , let talks' = filter (/= t) talks ] -- >> -- ---------------------------------------------------------------------------- -- Utils -- <<selects selects :: [a] -> [(a,[a])] selects xs0 = go [] xs0 where go xs [] = [] go xs (y:ys) = (y,xs++ys) : go (y:xs) ys -- >> -- ---------------------------------------------------------------------------- -- Benchmarking / Testing bench :: Int -> Int -> Int -> Int -> Int -> StdGen -> ([Person],[Talk],[TimeTable]) bench nslots ntracks ntalks npersons c_per_s gen = (persons,talks, timetable persons talks ntracks nslots) where total_talks = nslots * ntracks talks = map Talk [1..total_talks] persons = mkpersons npersons gen mkpersons :: Int -> StdGen -> [Person] mkpersons 0 g = [] mkpersons n g = Person ('P':show n) (take c_per_s cs) : rest where (g1,g2) = split g rest = mkpersons (n-1) g2 cs = nub [ talks !! n | n <- randomRs (0,ntalks-1) g ] main = do [ a, b, c, d, e ] <- fmap (fmap read) getArgs let g = mkStdGen 1001 let (ss,cs,ts) = bench a b c d e g print ss print (length ts) -- [ a, b ] <- fmap (fmap read) getArgs -- print (head (test2 a b)) test = timetable testPersons cs 2 2 where cs@[c1,c2,c3,c4] = map Talk [1..4] testPersons = [ Person "P" [c1,c2] , Person "Q" [c2,c3] , Person "R" [c3,c4] ] test2 n m = timetable testPersons cs m n where cs = map Talk [1 .. (n * m)] testPersons = [ Person "1" (take n cs) ]
lywaterman/parconc-examples
timetable1.hs
bsd-3-clause
3,689
0
15
914
1,330
736
594
81
2
module Lit where {-@ test :: {v:Int | v == 30} @-} test = length "cat"
mightymoose/liquidhaskell
tests/neg/lit.hs
bsd-3-clause
72
0
5
17
13
8
5
2
1
{-# LANGUAGE CPP #-} #if !(MIN_VERSION_base(4,6,0)) {-# LANGUAGE MagicHash, UnboxedTuples #-} #endif module Distribution.Server.Util.SigTerm (onSigTermCleanShutdown) where import System.Posix.Signals ( installHandler , Handler(Catch) , softwareTermination ) import Control.Exception ( AsyncException(UserInterrupt), throwTo ) import Control.Concurrent ( myThreadId ) #if MIN_VERSION_base(4,6,0) import Control.Concurrent ( ThreadId, mkWeakThreadId ) import System.Mem.Weak ( Weak ) #else import GHC.Conc.Sync ( ThreadId(..) ) import GHC.Weak ( Weak(..) ) import GHC.IO ( IO(IO) ) import GHC.Exts ( mkWeak#, unsafeCoerce# ) #endif import System.Mem.Weak ( deRefWeak ) -- | On SIGTERM, throw 'UserInterrupt' to the calling thread. -- onSigTermCleanShutdown :: IO () onSigTermCleanShutdown = do wtid <- mkWeakThreadId =<< myThreadId _ <- installHandler softwareTermination (Catch (cleanShutdownHandler wtid)) Nothing return () where cleanShutdownHandler :: Weak ThreadId -> IO () cleanShutdownHandler wtid = do mtid <- deRefWeak wtid case mtid of Nothing -> return () Just tid -> throwTo tid UserInterrupt #if !(MIN_VERSION_base(4,6,0)) mkWeakThreadId :: ThreadId -> IO (Weak ThreadId) mkWeakThreadId t@(ThreadId t#) = IO $ \s -> case mkWeak# t# t (unsafeCoerce# 0#) s of (# s1, w #) -> (# s1, Weak w #) #endif
mpickering/hackage-server
Distribution/Server/Util/SigTerm.hs
bsd-3-clause
1,538
0
13
405
318
174
144
38
2
-- -- Licensed to the Apache Software Foundation (ASF) under one -- or more contributor license agreements. See the NOTICE file -- distributed with this work for additional information -- regarding copyright ownership. The ASF licenses this file -- to you under the Apache License, Version 2.0 (the -- "License"); you may not use this file except in compliance -- with the License. You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, -- software distributed under the License is distributed on an -- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -- KIND, either express or implied. See the License for the -- specific language governing permissions and limitations -- under the License. -- module ThriftTestUtils (ClientFunc, ServerFunc, clientLog, serverLog, testLog, runTest) where import qualified Control.Concurrent import qualified Network import qualified System.IO serverPort :: Network.PortNumber serverPort = 9090 serverAddress :: (String, Network.PortID) serverAddress = ("localhost", Network.PortNumber serverPort) testLog :: String -> IO () testLog str = do System.IO.hPutStr System.IO.stdout $ str ++ "\n" System.IO.hFlush System.IO.stdout clientLog :: String -> IO () clientLog str = testLog $ "CLIENT: " ++ str serverLog :: String -> IO () serverLog str = testLog $ "SERVER: " ++ str type ServerFunc = Network.PortNumber -> IO () type ClientFunc = (String, Network.PortID) -> IO () runTest :: ServerFunc -> ClientFunc -> IO () runTest server client = do _ <- Control.Concurrent.forkIO (server serverPort) -- Fairly horrible; this does not 100% guarantees that the other thread -- has actually opened the socket we need... but not much else we can do -- without this, the client races the server to the socket, and wins every -- time Control.Concurrent.yield Control.Concurrent.threadDelay $ 500 * 1000 -- unit is in _micro_seconds Control.Concurrent.yield client serverAddress testLog "SUCCESS"
jcgruenhage/dendrite
vendor/src/github.com/apache/thrift/test/hs/ThriftTestUtils.hs
apache-2.0
2,088
0
10
370
343
193
150
26
1
{-# LANGUAGE Safe #-} module Main where import M_SafePkg3 main = do putStrLn $ show bigInt
urbanslug/ghc
testsuite/tests/safeHaskell/check/pkg01/ImpSafeOnly04.hs
bsd-3-clause
98
0
8
23
23
13
10
5
1
module LilRender.Color.Named where import LilRender.Color aliceBlue = RGBColor { _red=240, _green=248, _blue=255 } antiqueWhite = RGBColor { _red=250, _green=235, _blue=215 } aquamarine = RGBColor { _red=127, _green=255, _blue=212 } azure = RGBColor { _red=240, _green=255, _blue=255 } beige = RGBColor { _red=245, _green=245, _blue=220 } bisque = RGBColor { _red=255, _green=228, _blue=196 } black = RGBColor { _red=0, _green=0, _blue=0 } blanchedAlmond = RGBColor { _red=255, _green=235, _blue=205 } blue = RGBColor { _red=0, _green=0, _blue=255 } blueViolet = RGBColor { _red=138, _green=43, _blue=226 } brown = RGBColor { _red=165, _green=42, _blue=42 } burlywood = RGBColor { _red=222, _green=184, _blue=135 } cadetBlue = RGBColor { _red=95, _green=158, _blue=160 } chartreuse = RGBColor { _red=127, _green=255, _blue=0 } chocolate = RGBColor { _red=210, _green=105, _blue=30 } coral = RGBColor { _red=255, _green=127, _blue=80 } cornflowerBlue = RGBColor { _red=100, _green=149, _blue=237 } cornsilk = RGBColor { _red=255, _green=248, _blue=220 } cyan = RGBColor { _red=0, _green=255, _blue=255 } darkBlue = RGBColor { _red=0, _green=0, _blue=139 } darkCyan = RGBColor { _red=0, _green=139, _blue=139 } darkGoldenrod = RGBColor { _red=184, _green=134, _blue=11 } darkGreen = RGBColor { _red=0, _green=100, _blue=0 } darkGrey = RGBColor { _red=169, _green=169, _blue=169 } darkKhaki = RGBColor { _red=189, _green=183, _blue=107 } darkMagenta = RGBColor { _red=139, _green=0, _blue=139 } darkOliveGreen = RGBColor { _red=85, _green=107, _blue=47 } darkOrange = RGBColor { _red=255, _green=140, _blue=0 } darkOrchid = RGBColor { _red=153, _green=50, _blue=204 } darkRed = RGBColor { _red=139, _green=0, _blue=0 } darkSalmon = RGBColor { _red=233, _green=150, _blue=122 } darkSeaGreen = RGBColor { _red=143, _green=188, _blue=143 } darkSlateBlue = RGBColor { _red=72, _green=61, _blue=139 } darkSlateGrey = RGBColor { _red=47, _green=79, _blue=79 } darkTurquoise = RGBColor { _red=0, _green=206, _blue=209 } darkViolet = RGBColor { _red=148, _green=0, _blue=211 } deepPink = RGBColor { _red=255, _green=20, _blue=147 } deepSkyBlue = RGBColor { _red=0, _green=191, _blue=255 } dimGrey = RGBColor { _red=105, _green=105, _blue=105 } dodgerBlue = RGBColor { _red=30, _green=144, _blue=255 } firebrick = RGBColor { _red=178, _green=34, _blue=34 } floralWhite = RGBColor { _red=255, _green=250, _blue=240 } forestGreen = RGBColor { _red=34, _green=139, _blue=34 } gainsboro = RGBColor { _red=220, _green=220, _blue=220 } ghostWhite = RGBColor { _red=248, _green=248, _blue=255 } gold = RGBColor { _red=255, _green=215, _blue=0 } goldenrod = RGBColor { _red=218, _green=165, _blue=32 } green = RGBColor { _red=0, _green=255, _blue=0 } greenYellow = RGBColor { _red=173, _green=255, _blue=47 } grey = RGBColor { _red=190, _green=190, _blue=190 } honeydew = RGBColor { _red=240, _green=255, _blue=240 } hotPink = RGBColor { _red=255, _green=105, _blue=180 } indianRed = RGBColor { _red=205, _green=92, _blue=92 } ivory = RGBColor { _red=255, _green=255, _blue=240 } khaki = RGBColor { _red=240, _green=230, _blue=140 } lavender = RGBColor { _red=230, _green=230, _blue=250 } lavenderBlush = RGBColor { _red=255, _green=240, _blue=245 } lawnGreen = RGBColor { _red=124, _green=252, _blue=0 } lemonChiffon = RGBColor { _red=255, _green=250, _blue=205 } lightBlue = RGBColor { _red=173, _green=216, _blue=230 } lightCoral = RGBColor { _red=240, _green=128, _blue=128 } lightCyan = RGBColor { _red=224, _green=255, _blue=255 } lightGoldenrod = RGBColor { _red=238, _green=221, _blue=130 } lightGoldenrodYellow = RGBColor { _red=250, _green=250, _blue=210 } lightGreen = RGBColor { _red=144, _green=238, _blue=144 } lightGrey = RGBColor { _red=211, _green=211, _blue=211 } lightPink = RGBColor { _red=255, _green=182, _blue=193 } lightSalmon = RGBColor { _red=255, _green=160, _blue=122 } lightSeaGreen = RGBColor { _red=32, _green=178, _blue=170 } lightSkyBlue = RGBColor { _red=135, _green=206, _blue=250 } lightSlateBlue = RGBColor { _red=132, _green=112, _blue=255 } lightSlateGrey = RGBColor { _red=119, _green=136, _blue=153 } lightSteelBlue = RGBColor { _red=176, _green=196, _blue=222 } lightYellow = RGBColor { _red=255, _green=255, _blue=224 } limeGreen = RGBColor { _red=50, _green=205, _blue=50 } linen = RGBColor { _red=250, _green=240, _blue=230 } magenta = RGBColor { _red=255, _green=0, _blue=255 } maroon = RGBColor { _red=176, _green=48, _blue=96 } mediumAquamarine = RGBColor { _red=102, _green=205, _blue=170 } mediumBlue = RGBColor { _red=0, _green=0, _blue=205 } mediumOrchid = RGBColor { _red=186, _green=85, _blue=211 } mediumPurple = RGBColor { _red=147, _green=112, _blue=219 } mediumSeaGreen = RGBColor { _red=60, _green=179, _blue=113 } mediumSlateBlue = RGBColor { _red=123, _green=104, _blue=238 } mediumSpringGreen = RGBColor { _red=0, _green=250, _blue=154 } mediumTurquoise = RGBColor { _red=72, _green=209, _blue=204 } mediumVioletRed = RGBColor { _red=199, _green=21, _blue=133 } midnightBlue = RGBColor { _red=25, _green=25, _blue=112 } mintCream = RGBColor { _red=245, _green=255, _blue=250 } mistyRose = RGBColor { _red=255, _green=228, _blue=225 } moccasin = RGBColor { _red=255, _green=228, _blue=181 } navajoWhite = RGBColor { _red=255, _green=222, _blue=173 } navyBlue = RGBColor { _red=0, _green=0, _blue=128 } oldLace = RGBColor { _red=253, _green=245, _blue=230 } oliveDrab = RGBColor { _red=107, _green=142, _blue=35 } orange = RGBColor { _red=255, _green=165, _blue=0 } orangeRed = RGBColor { _red=255, _green=69, _blue=0 } orchid = RGBColor { _red=218, _green=112, _blue=214 } paleGoldenrod = RGBColor { _red=238, _green=232, _blue=170 } paleGreen = RGBColor { _red=152, _green=251, _blue=152 } paleTurquoise = RGBColor { _red=175, _green=238, _blue=238 } paleVioletRed = RGBColor { _red=219, _green=112, _blue=147 } papayaWhip = RGBColor { _red=255, _green=239, _blue=213 } peachPuff = RGBColor { _red=255, _green=218, _blue=185 } peru = RGBColor { _red=205, _green=133, _blue=63 } pink = RGBColor { _red=255, _green=192, _blue=203 } plum = RGBColor { _red=221, _green=160, _blue=221 } powderBlue = RGBColor { _red=176, _green=224, _blue=230 } purple = RGBColor { _red=160, _green=32, _blue=240 } red = RGBColor { _red=255, _green=0, _blue=0 } rosyBrown = RGBColor { _red=188, _green=143, _blue=143 } royalBlue = RGBColor { _red=65, _green=105, _blue=225 } saddleBrown = RGBColor { _red=139, _green=69, _blue=19 } salmon = RGBColor { _red=250, _green=128, _blue=114 } sandyBrown = RGBColor { _red=244, _green=164, _blue=96 } seaGreen = RGBColor { _red=46, _green=139, _blue=87 } seashell = RGBColor { _red=255, _green=245, _blue=238 } sienna = RGBColor { _red=160, _green=82, _blue=45 } skyBlue = RGBColor { _red=135, _green=206, _blue=235 } slateBlue = RGBColor { _red=106, _green=90, _blue=205 } slateGrey = RGBColor { _red=112, _green=128, _blue=144 } snow = RGBColor { _red=255, _green=250, _blue=250 } springGreen = RGBColor { _red=0, _green=255, _blue=127 } steelBlue = RGBColor { _red=70, _green=130, _blue=180 } tan = RGBColor { _red=210, _green=180, _blue=140 } thistle = RGBColor { _red=216, _green=191, _blue=216 } tomato = RGBColor { _red=255, _green=99, _blue=71 } turquoise = RGBColor { _red=64, _green=224, _blue=208 } violet = RGBColor { _red=238, _green=130, _blue=238 } violetRed = RGBColor { _red=208, _green=32, _blue=144 } wheat = RGBColor { _red=245, _green=222, _blue=179 } white = RGBColor { _red=255, _green=255, _blue=255 } whiteSmoke = RGBColor { _red=245, _green=245, _blue=245 } yellow = RGBColor { _red=255, _green=255, _blue=0 } yellowGreen = RGBColor { _red=154, _green=205, _blue=50 }
SASinestro/lil-render
src/LilRender/Color/Named.hs
isc
7,658
0
6
1,087
3,387
2,168
1,219
137
1
{-# LANGUAGE CPP #-} module Jakway.Blackjack.Tests.DatabaseTests.BasicTests (tests) where import Jakway.Blackjack.Tests.DatabaseTests.Common import Jakway.Blackjack.AI import System.Directory import Database.HDBC import Database.HDBC.Sqlite3 import Database.HDBC.Session (withConnectionIO') import Test.HUnit import Control.Monad (liftM, unless, when, mapM) -- |overlapping for convenience--change if necessary import qualified Jakway.Blackjack.IO.DatabaseWrites as DB import qualified Jakway.Blackjack.IO.DatabaseReads as DB import qualified Jakway.Blackjack.IO.DatabaseCommon as DB import qualified Jakway.Blackjack.IO.TableNames as DB import Jakway.Blackjack.Cards import Jakway.Blackjack.CardOps import Data.Maybe import Jakway.Blackjack.Visibility import Data.List (sort, delete) import Test.Framework import Test.Framework.Providers.HUnit import System.Random import Control.Monad.State import Jakway.Blackjack.Game import Data.Monoid (mempty) import Jakway.Blackjack.Tests.Constants (test_db_name) testOpenDatabase :: Assertion #ifdef BUILD_POSTGRESQL --can't check that a file with postgresql, so check that we can connect to --the database without problems testOpenDatabase = withSingleTableTestDatabase $ \_ -> return () #else testOpenDatabase = withSingleTableTestDatabase $ (\_ -> do exists <- doesFileExist test_db_name if exists then return () else assertFailure message) where message = "Database "++test_db_name++" does not exist!" #endif testTableList :: Assertion testTableList = drop >> (withSingleTableTestDatabase $ \conn -> getTables conn >>= (\tables -> unless (tablesEqual tables) (assertFailure $ message tables))) where tables = ["cards", DB.getPlayerTableName basicTestTableNames, DB.getHandTableName basicTestTableNames, DB.getMatchTableName basicTestTableNames] -- | in case sqlite adds an extra schema table tablesEqual readTables = (sort tables) == (sort . (delete "sqlite_sequence") $ readTables) message readTables = "Database tables don't match! Read tables: " ++ (show readTables) drop = withSingleTableTestDatabase $ \dbc -> DB.dropAllTables dbc testInsertPlayers :: Assertion testInsertPlayers = withSingleTableTestDatabase $ \conn -> do let numPlayers = 10 DB.insertPlayers conn basicTestTableNames BasicDealer (replicate numPlayers BasicPlayer) commit conn numPlayerRows <- DB.getNumPlayers conn basicTestTableNames let message = "numPlayerRows is "++(show numPlayerRows)++" (should be"++(show numPlayers)++")" --numPlayers doesn't include the dealer assertBool message ((numPlayers+1) == numPlayerRows) testInsertOneHand :: Assertion testInsertOneHand = withSingleTableTestDatabase $ \conn -> do let whichPlayer = 1 DB.insertPlayers conn basicTestTableNames BasicDealer (replicate 2 BasicPlayer) let hand = [Hidden (Card Spade Ace), Shown (Card Diamond King)] insertStatement <- DB.insertHandStatement conn basicTestTableNames whichHand <- DB.insertHand insertStatement conn basicTestTableNames whichPlayer hand commit conn readStatement <- DB.readHandStatement conn basicTestTableNames res <- DB.readHand readStatement whichHand case res of Nothing -> assertFailure "Could not read hand id!" Just resHand -> assertEqual "" hand resHand testInsertRandStartingHands :: Assertion testInsertRandStartingHands = withSingleTableTestDatabase $ \conn -> do let whichPlayer = 0 DB.insertPlayers conn basicTestTableNames BasicDealer (replicate 2 BasicPlayer) commit conn --insert between 10 and 100 hands numHands <- randomRIO (10, 100) gen <- getStdGen let startingDeck = infiniteShuffledDeck gen --don't need the state monad here--use a fold to keep track of state let hands= fst $ foldr (\_ (accumulatedHands, thisDeck) -> let (drawnHand, resDeck) = runState startingHand thisDeck in (drawnHand : accumulatedHands, resDeck)) (mempty, startingDeck) ([1..numHands] :: [Int]) -- ^ start with an empty list of hands testInsertHands conn whichPlayer hands return () testInsertThreeCardHand :: Assertion testInsertThreeCardHand = withSingleTableTestDatabase $ \conn -> do let whichPlayer = 0 DB.insertPlayers conn basicTestTableNames BasicDealer (replicate 2 BasicPlayer) commit conn gen <- getStdGen let deck = infiniteShuffledDeck gen let hand = return $ flip evalState deck $ do firstCard <- drawCard secondCard <- drawCard thirdCard <- drawCard return [Hidden firstCard, Shown secondCard, Hidden thirdCard] testInsertHands conn 1 hand testGetNextHandId :: Assertion testGetNextHandId = withSingleTableTestDatabase $ \conn -> do let whichPlayer = 1 DB.insertPlayers conn basicTestTableNames BasicDealer (replicate 2 BasicPlayer) commit conn firstHand <- newHand (infiniteShuffledDeck $ mkStdGen 23) secondHand <- newHand (infiniteShuffledDeck $ mkStdGen 25) insHandStatement <- DB.insertHandStatement conn basicTestTableNames DB.insertHands insHandStatement conn basicTestTableNames ([whichPlayer, whichPlayer], [firstHand, secondHand]) commit conn next_hand_id <- DB.nextHandId conn basicTestTableNames let message = "Could not identify the next hand id!" assertBool message (next_hand_id == 2) where newHand whichDeck = return $ flip evalState whichDeck $ do firstCard <- drawCard secondCard <- drawCard thirdCard <- drawCard return [Hidden firstCard, Shown secondCard, Hidden thirdCard] testInsertHands :: (IConnection a) => a -> Int -> [Hand] -> Assertion testInsertHands conn whichPlayer hands | whichPlayer < 0 = assertFailure ("Invalid player id: "++ (show whichPlayer)) | hands == [] = assertFailure "Attempted to insert empty list of hands" | otherwise = do -- |insert the ids then read them back from -- the DB insertStatement <- DB.insertHandStatement conn basicTestTableNames --player ids don't really matter here let playerIds = replicate (length hands) whichPlayer handIds <- DB.insertHands insertStatement conn basicTestTableNames (playerIds, hands) commit conn readStatement <- DB.readHandStatement conn basicTestTableNames commit conn res <- (mapM (DB.readHand readStatement) handIds) :: IO ([Maybe Hand]) --make sure there weren't any problems if ((length . catMaybes $ res) /= (length res)) then assertFailure "failed to insert a hand!" else return () --unwrap the maybes let readHands = map fromJust res assertBool "Ought to have read the same hands we inserted into the database" ((sort hands) == (sort readHands)) tests = testGroup "BasicTests" [testCase "testOpenDatabase" testOpenDatabase, testCase "testTableList" testTableList, testCase "testInsertPlayers" testInsertPlayers, testCase "testInsertOneHand" testInsertOneHand, testCase "testInsertRandStartingHands" testInsertRandStartingHands, testCase "testInsertThreeCardHand" testInsertThreeCardHand, testCase "testGetNextHandId" testGetNextHandId]
tjakway/blackjack-simulator
test/Jakway/Blackjack/Tests/DatabaseTests/BasicTests.hs
mit
8,253
0
20
2,373
1,701
869
832
119
2
{-# LANGUAGE OverloadedStrings #-} module Main where -- import Data.Conduit import Control.Lens import Data.Aeson import Data.Aeson.Lens import qualified Data.HashMap.Strict as H import Data.Maybe (isNothing) import Data.Text (Text) import Data.Vector (Vector, (!?)) import qualified Data.Vector as V import System.IO import Control.Concurrent (threadDelay) import qualified Data.ByteString.Char8 as B import qualified Data.ByteString.Lazy.Char8 as LZ import Data.CaseInsensitive (original) import Data.Monoid ((<>)) import Data.Time.Clock.POSIX (getPOSIXTime, utcTimeToPOSIXSeconds) import Data.Time.Format (readTime) import Network.HTTP.Conduit import Network.HTTP.Types.Header (Header, RequestHeaders, ResponseHeaders) import Network.HTTP.Types.Status (notModified304, statusIsSuccessful) import System.CPUTime (getCPUTime) import System.Environment (getArgs) import System.Exit (exitFailure) import System.Locale (defaultTimeLocale) import Network.Nats (Nats) import qualified Network.Nats as Nats import qualified Control.Exception as EX import Control.Exception (SomeException) -- Datas CallInfo contains all necessary information to manage events searching data CallInfo = CallInfo { _user :: String -- ^ Github username , _pass :: String -- ^ Github password , _etag :: Maybe B.ByteString -- ^ ETag , _timeToWait :: Int -- ^ Time to wait in micro seconds , _firstId :: Maybe Text -- ^ First Event Id , _lastId :: Maybe Text -- ^ Last Event Id , _searchedFirstId :: Maybe Text -- ^ First Event Id searched , _page :: Int -- ^ Page , _nats :: Maybe Nats -- ^ NATS connection object , _topic :: String -- ^ NATS Topic } -------------------------------------------------------------------------------- -- MAIN -------------------------------------------------------------------------------- main :: IO () main = do args <- getArgs case args of [user,pass] -> do nats <- EX.catch (fmap Just (Nats.connect "nats://localhost:4222")) handleNatsException let initCallInfo = CallInfo { _user = user , _pass = pass , _etag = Nothing , _timeToWait = 100000 , _firstId = Nothing , _lastId = Nothing , _searchedFirstId = Nothing , _page = 1 , _nats = nats , _topic = "ghevents" } iterateM_ getEvents initCallInfo _ -> showHelpAndExit handleNatsException :: SomeException -> IO (Maybe Nats) handleNatsException e = do hPrint stderr e hPutStrLn stderr "Will write to standard output" return Nothing -------------------------------------------------------------------------------- showHelpAndExit :: IO () showHelpAndExit = do hPutStrLn stderr "provide your github username and password please" exitFailure -------------------------------------------------------------------------------- -- HTTP Calls -------------------------------------------------------------------------------- authHttpCall :: String -> String -> String -> RequestHeaders -> [(B.ByteString,Maybe B.ByteString)] -> IO (Response LZ.ByteString) authHttpCall url user pass headers params = do r <- parseUrl url let request = r {requestHeaders = headers, checkStatus = \_ _ _ -> Nothing} requestWithParams = setQueryString params request requestWithAuth = applyBasicAuth (B.pack user) (B.pack pass) requestWithParams withManager (httpLbs requestWithAuth) httpGHEvents :: String -> String -> Maybe B.ByteString -> Int -> IO (Response LZ.ByteString) httpGHEvents user pass etag page = authHttpCall "https://api.github.com/events" user pass headers params where headers = ("User-Agent","HTTP-Conduit"): maybe [] (\e -> [("If-None-Match",B.tail (B.tail e))]) etag params = [("page",Just (B.pack (show page)))] -------------------------------------------------------------------------------- -- Date -------------------------------------------------------------------------------- showHeader :: Header -> IO () showHeader (name, value) = B.putStrLn (original name <> ": " <> value) rfc822DateFormat :: String rfc822DateFormat = "%a, %_d %b %Y %H:%M:%S %Z" epochFromString :: String -> Int epochFromString = floor . utcTimeToPOSIXSeconds . readTime defaultTimeLocale rfc822DateFormat -------------------------------------------------------------------------------- -- Count how long a function evaluation took -------------------------------------------------------------------------------- time :: IO a -> IO (Double, a) time action = do startTime <- getCPUTime res <- action endTime <- getCPUTime return (fromIntegral (endTime - startTime)/(10**12),res) -------------------------------------------------------------------------------- -- JSON -------------------------------------------------------------------------------- anArray :: Value -> Maybe Array anArray (Array a) = Just a anArray _ = Nothing anObject :: Value -> Maybe Object anObject (Object a) = Just a anObject _ = Nothing aString :: Value -> Maybe Text aString (String a) = Just a aString _ = Nothing getFirstId :: Maybe Value -> Maybe Text getFirstId events = events >>= anArray >>= (!? 0) >>= anObject >>= H.lookup "id" >>= aString safeVLast :: Vector a -> Maybe a safeVLast v = if V.null v then Nothing else Just (V.last v) getLastId :: Maybe Value -> Maybe Text getLastId events = events >>= anArray >>= safeVLast >>= anObject >>= H.lookup "id" >>= aString -------------------------------------------------------------------------------- -- The Algorithm of getting events -------------------------------------------------------------------------------- -- | Iterate in a monad, mainly the safe as: -- -- @ -- x1 <- f x0 -- x2 <- f x1 -- ... -- @ iterateM_ :: Monad m => (a -> m a) -> a -> m () iterateM_ f x = f x >>= iterateM_ f -- | Getting events return the next CallInfo for the next call getEvents :: CallInfo -> IO CallInfo getEvents callInfo = do -- Call /events on github (req_time, response) <- time (httpGHEvents (_user callInfo) (_pass callInfo) (_etag callInfo) (_page callInfo)) newCallInfo <- getCallInfoFromResponse callInfo response req_time threadDelay (_timeToWait newCallInfo) return newCallInfo -- | the time to wait between two HTTP calls using headers informations getTimeToWaitFromHeaders :: ResponseHeaders -> IO Int getTimeToWaitFromHeaders headers = do -- Ask current date only if server didn't reponsded with its own serverDateEpoch <- case lookup "Date" headers of Nothing -> fmap round getPOSIXTime Just d -> return (epochFromString (B.unpack d)) let remainingHeader = lookup "X-RateLimit-Remaining" headers remaining = maybe 1 (read . B.unpack) remainingHeader resetHeader = lookup "X-RateLimit-Reset" headers reset = maybe 1 (read . B.unpack) resetHeader timeBeforeReset = reset - serverDateEpoch return (1000000 * timeBeforeReset `div` remaining) -- | Get the list of Ids from the body and check if firstId is in it containsId :: Maybe Text -> Maybe Value -> Bool containsId firstId events = maybe False (\i -> Just i `elem` eventsIds) firstId where eventsIds :: [Maybe Text] eventsIds = maybe [] (^.. _Array . traverse . to (^? key "id" . _String)) events -- | given an HTTP response compute the next CallInfo and also publish events -- Beware, this is an heuristic with the hypothesis that there is no more than -- one page to download, by one page. getCallInfoFromResponse :: CallInfo -> Response LZ.ByteString -> Double -> IO CallInfo getCallInfoFromResponse callInfo response req_time = if statusIsSuccessful (responseStatus response) then do let headers = responseHeaders response t <- getTimeToWaitFromHeaders headers let -- Time to wait is time between two HTTP call minus the time -- the last HTTP call took to answer timeToWaitIn_us = max 0 (t - floor (1000000 * req_time)) events = decode (responseBody response) nextFirstId = if _page callInfo == 1 || isNothing (_firstId callInfo) then getFirstId events else _firstId callInfo nextLastId = getLastId events containsSearchedFirstId = containsId (_searchedFirstId callInfo) events etagResponded = lookup "ETag" headers -- Read next pages until we reach the old first ID of the first page -- of the preceeding loop -- return a new page if the first ID wasn't found nextPage = if containsSearchedFirstId || (_page callInfo >= 10) then 1 else _page callInfo + 1 nextSearchedFirstId = if containsSearchedFirstId || (_page callInfo >= 10) then nextFirstId else _searchedFirstId callInfo publish callInfo events return (callInfo { _firstId = nextFirstId , _lastId = nextLastId , _page = nextPage , _etag = etagResponded , _timeToWait = timeToWaitIn_us , _searchedFirstId = nextSearchedFirstId }) else do hPutStrLn stderr (if notModified304 == responseStatus response then "Nothing changed" else "Something went wrong") return callInfo selectEvents :: Maybe Value -> Maybe Text -> Maybe Text -> [Value] selectEvents events firstId lastId = case events of Nothing -> [] Just evts -> (takeWhile ((/= firstId) . getId) . guillotine ((== lastId) . getId) . removeOld) evts where getId e = e ^? key "id" . _String guillotine :: (a -> Bool) -> [a] -> [a] guillotine _ [] = [] guillotine f (x:xs) = if f x then xs else x:xs removeOld evts = case lastId of Nothing -> evts ^.. values Just _ -> if containsId lastId (Just evts) then dropWhile ((/= lastId) . getId) (evts ^.. values) else evts ^.. values publish :: CallInfo -> Maybe Value -> IO () publish callInfo events = mapM_ (publishOneEvent callInfo) (selectEvents events (_firstId callInfo) (_lastId callInfo)) publishOneEvent :: CallInfo -> Value -> IO () publishOneEvent callInfo = case _nats callInfo of Just nats -> Nats.publish nats (_topic callInfo) . encode -- . (^? key "id") Nothing-> LZ.putStrLn . encode -- . (^? key "id")
yogsototh/muraine
src/Main.hs
mit
12,419
0
18
4,238
2,559
1,365
1,194
-1
-1
import Data.List (nub, foldl') import qualified Data.Map.Strict as Map -- Pairs (small side, perimeter) of all square triangles whose perimeter is not greater than 1000 triangles :: [(Int, Int)] triangles = nub [(l*min a b, l*p) | m <- [1..16], n <- [1..m-1], let p = 2*m*(m+n), let a = m*m-n*n, let b = 2*m*n, l <- [1 .. div 1000 p]] -- Map whose key are the perimeters and values the number of triangles with that perimeter scores :: Map.Map Int Int scores = foldl' (\map (a, p) -> Map.insertWith (+) p 1 map) Map.empty triangles -- The pair (perimeter, score) with the highest score maxItem :: (Int, Int) maxItem = Map.foldlWithKey' bestBetween (0, 0) scores where bestBetween current@(_, n) k' n' = if n>n' then current else (k', n') main = do print $ maxItem
dpieroux/euler
0/0039.hs
mit
948
0
13
321
323
180
143
16
2
{-# OPTIONS_GHC -fno-warn-type-defaults #-} import Data.Foldable (for_) import Data.List (sort) import Test.Hspec (Spec, describe, it, shouldBe) import Test.Hspec.Runner (configFastFail, defaultConfig, hspecWith) import Triplet (tripletsWithSum) main :: IO () main = hspecWith defaultConfig {configFastFail = True} specs specs :: Spec specs = describe "pythagoreanTriplets" $ for_ cases test where test (description, n, ts) = it description $ sort (tripletsWithSum n) `shouldBe` ts cases = [ ("triplets whose sum is 12" , 12 , [(3, 4, 5)] ) , ("triplets whose sum is 108" , 108 , [(27, 36, 45)] ) , ("triplets whose sum is 1000" , 1000 , [(200, 375, 425)] ) , ("no matching triplets for 1001" , 1001 , [] ) , ("returns all matching triplets" , 90 , [ (9, 40, 41) , (15, 36, 39) ] ) , ("several matching triplets" , 840 , [ (40, 399, 401) , (56, 390, 394) , (105, 360, 375) , (120, 350, 370) , (140, 336, 364) , (168, 315, 357) , (210, 280, 350) , (240, 252, 348) ] ) , ("triplets for large number" , 30000 , [ (1200, 14375, 14425) , (1875, 14000, 14125) , (5000, 12000, 13000) , (6000, 11250, 12750) , (7500, 10000, 12500) ] ) ] -- 436e9f3a1fbda7cd79190c78bcb1916f51f7c968
exercism/xhaskell
exercises/practice/pythagorean-triplet/test/Tests.hs
mit
1,825
0
11
857
465
294
171
44
1
{-# LANGUAGE PatternSynonyms #-} -- For HasCallStack compatibility {-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} module JSDOM.Generated.SVGAnimatedBoolean (setBaseVal, getBaseVal, getAnimVal, SVGAnimatedBoolean(..), gTypeSVGAnimatedBoolean) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..)) import qualified Prelude (error) import Data.Typeable (Typeable) import Data.Traversable (mapM) import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!)) import Data.Int (Int64) import Data.Word (Word, Word64) import JSDOM.Types import Control.Applicative ((<$>)) import Control.Monad (void) import Control.Lens.Operators ((^.)) import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync) import JSDOM.Enums -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGAnimatedBoolean.baseVal Mozilla SVGAnimatedBoolean.baseVal documentation> setBaseVal :: (MonadDOM m) => SVGAnimatedBoolean -> Bool -> m () setBaseVal self val = liftDOM (self ^. jss "baseVal" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGAnimatedBoolean.baseVal Mozilla SVGAnimatedBoolean.baseVal documentation> getBaseVal :: (MonadDOM m) => SVGAnimatedBoolean -> m Bool getBaseVal self = liftDOM ((self ^. js "baseVal") >>= valToBool) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGAnimatedBoolean.animVal Mozilla SVGAnimatedBoolean.animVal documentation> getAnimVal :: (MonadDOM m) => SVGAnimatedBoolean -> m Bool getAnimVal self = liftDOM ((self ^. js "animVal") >>= valToBool)
ghcjs/jsaddle-dom
src/JSDOM/Generated/SVGAnimatedBoolean.hs
mit
1,853
0
10
210
460
284
176
25
1
import Control.Monad (when) import Data.List (isInfixOf) import qualified Data.Map as M (Map, fromList) import Data.Maybe (fromMaybe) import System.Environment (getEnv) import System.Exit (exitSuccess) import XMonad import qualified XMonad.Actions.FlexibleResize as Flex import XMonad.Actions.Warp (warpToWindow) import XMonad.Hooks.DynamicLog (dynamicLogWithPP, ppOrder, ppOutput, xmobarPP) import XMonad.Hooks.EwmhDesktops (ewmh, fullscreenEventHook) import XMonad.Hooks.ManageDocks (avoidStruts, docksEventHook, manageDocks) import XMonad.Hooks.ManageHelpers (doFullFloat) import XMonad.Layout.GridVariants (Grid (..)) import XMonad.Layout.LayoutHints (layoutHintsWithPlacement) import XMonad.Layout.MouseResizableTile import qualified XMonad.StackSet as W import XMonad.Util.Run (runProcessWithInput) import XMonad.Util.Run (hPutStrLn, spawnPipe) main :: IO () main = do bar <- spawnPipe "xmobar" xmonad $ ewmh def { modMask = mod4Mask , terminal = myterm , borderWidth = 0 , layoutHook = avoidStruts (layoutHintsWithPlacement (0.5, 0.5) (mouseResizableTile { draggerType = FixedDragger 4 4 })) ||| Full , manageHook = myManageHook <+> manageDocks , handleEventHook = handleEventHook def <+> fullscreenEventHook <+> docksEventHook , keys = myKeys , mouseBindings = myMouseBindings , logHook = dynamicLogWithPP xmobarPP {ppOrder = \(ws:_:wt:_) -> [ws, wt], ppOutput = hPutStrLn bar } , startupHook = myStartup } myterm = "urxvtc" -- Some keys brought straight from default config in order to have one overview -- of all active bindings. myKeys :: XConfig Layout -> M.Map (KeyMask, KeySym) (X ()) myKeys conf = M.fromList $ [ ((m, xK_Return), spawn $ XMonad.terminal conf) , ((ms, xK_Return), spawn "xterm") , ((m, xK_Tab), down) , ((ms, xK_Tab), up) , ((m, xK_j), down) , ((m, xK_k), up) , ((ms, xK_j), swapdown) , ((ms, xK_k), swapup) , ((m, xK_d), spawn "dmenu_run -b -i -nf \"#888888\" -nb \"#2D1F21\" -sf \"#ffffff\" -sb \"#6D1F21\" -fn \"Dina-10\" -l 12") , ((m, xK_s), spawn $ myterm ++ " -t fully -e htop") , ((m, xK_x), spawn "emacs") , ((m, xK_c), spawn "firefox") , ((m, xK_o), spawn "swapsinks") , ((m, xK_p), spawn "pavucontrol") , ((0, xK_Print), maim) , ((0, 0x1008ff45), maim) -- F14 , ((m, xK_Delete), spawn "susp") , ((0, 0x1008ff49), spawn "sleep 0.1 && xset dpms force off") -- F18 , ((m, xK_y), spawn "xmonad --recompile && xmonad --restart") , ((ms, xK_y), io exitSuccess) , ((m, xK_q), kill) , ((m, xK_F1), spawn "sudo backlight 64") , ((m, xK_F2), spawn "sudo backlight 200") , ((m, xK_F3), spawn "sudo backlight 400") , ((m, xK_F4), spawn "sudo backlight 852") , ((m, xK_t), sinkAll >> setLayout (XMonad.layoutHook conf)) , ((m, xK_a), sinkAll >> floatAllCurrent) , ((m, xK_f), sendMessage NextLayout) ] ++ [((m .|. mod4Mask, k), windows $ f i) | (i, k) <- zip (XMonad.workspaces conf) [xK_1 .. xK_9] , (f, m) <- [(W.greedyView, 0), (W.shift, shiftMask)]] where setmouse = warpToWindow 0.5 0.5 down = windows W.focusDown >> setmouse up = windows W.focusUp >> setmouse swapdown = windows W.swapDown >> setmouse swapup = windows W.swapUp >> setmouse maim = spawn "maim -s ~/maim$(date +%s).png" m = mod4Mask ms = mod4Mask .|. shiftMask myMouseBindings :: XConfig Layout -> M.Map (KeyMask, Button) (Window -> X ()) myMouseBindings _ = M.fromList [ ((mod4Mask, button1), \w -> focus w >> mouseMoveWindow w >> windows W.shiftMaster) , ((mod4Mask, button2), windows . (W.shiftMaster .) . W.focusWindow) , ((mod4Mask, button3), (\w -> focus w >> Flex.mouseResizeWindow w)) ] myManageHook :: ManageHook myManageHook = composeAll [ title =? "fully" --> doFullFloat , title =? "WAKEUP" --> (doShiftScreen 2 <+> doFullFloat) , title =? "stalonetray" --> doShiftScreen 2 , fmap ("qBittorrent" `isInfixOf`) title --> doShift "8" ] myStartup :: X () myStartup = do spawn "trayer --widthtype request --height 20 --transparent true --tint 0x00000000 --alpha 0" host <- runProcessWithInput "hostname" [] "" let mag = "mag" `isInfixOf` host when mag $ spawn "qbittorrent" doShiftScreen :: ScreenId -> ManageHook doShiftScreen n = liftX (screenWorkspace n) >>= doShift . fromMaybe "0" -- Floats all windows, while keeping them in the positions they were in (unlike -- a simple sequence float where it calculates new positions after each float -- and they end up on top of eachother). floatAllCurrent :: X () floatAllCurrent = do ws <- getWindows wr <- mapM floaty ws mapM_ (windows . uncurry W.float) (zip ws wr) sinkAll :: X () sinkAll = do ws <- getWindows mapM_ (windows . W.sink) ws floaty :: Window -> X W.RationalRect floaty = fmap snd . floatLocation getWindows :: X [Window] getWindows = withWindowSet (return . W.integrate' . W.stack . W.workspace . W.current)
fizzoo/dotfiles
xmonad.hs
mit
5,565
0
18
1,576
1,671
960
711
111
1
{-# LANGUAGE FlexibleInstances, TypeSynonymInstances #-} module Homework.Week07.StringBuffer where import Data.Monoid import Homework.Week07.Buffer instance Buffer String where toString = id fromString = id line n b = safeIndex n (lines b) replaceLine n l b = unlines . uncurry replaceLine' . splitAt n . lines $ b where replaceLine' pre [] = pre replaceLine' pre (_:ls) = pre ++ l:ls numLines = length . lines value = length . words safeIndex :: Int -> [a] -> Maybe a safeIndex n _ | n < 0 = Nothing safeIndex _ [] = Nothing safeIndex 0 (x:_) = Just x safeIndex n (_:xs) = safeIndex (n-1) xs
laser/cis-194-spring-2017
src/Homework/Week07/StringBuffer.hs
mit
663
0
10
174
249
129
120
18
1
import Control.Monad (guard) double :: [a] -> [a] double [] = [] double (x : xs) = x : x : double xs main = do guard $ (double []::[Int]) == [] guard $ double [5, 5] == [5, 5, 5, 5] guard $ double [2, 5, 3] == [2, 2, 5, 5, 3, 3]
rtoal/ple
haskell/double.hs
mit
243
0
11
69
169
93
76
8
1
{-# LANGUAGE OverloadedStrings #-} module HotDB.Core.Commit ( Commit(..) , TaggedCommit , UserId , Timestamp , CommitId , emptyCommitId ) where import Control.Applicative import Data.ByteString (ByteString) import qualified Data.ByteString.Base16 as Base16 import qualified Data.ByteString.Lazy as LB import Data.Int (Int64) import Data.Text (Text) import Data.Text.Encoding (decodeUtf8) import qualified Data.Vector as V import qualified Data.Aeson as A import qualified Crypto.Hash.SHA1 as SHA1 import qualified HotDB.Core.JsonUtils as J import HotDB.Core.Operation (DirectedOperation) type UserId = Text type Timestamp = Int64 type HexHash = Text type CommitId = Text data Commit = Commit { directedOperation :: DirectedOperation , userId :: UserId , timestamp :: Timestamp , parent :: CommitId } deriving (Show, Eq) type TaggedCommit = (CommitId, Commit) instance A.ToJSON Commit where toJSON (Commit dop uId ts p) = A.toJSON (dop, uId, J.Int64 ts, p) instance A.FromJSON Commit where parseJSON j = (\(dop, uId, ts, p) -> Commit dop uId (J.getInt64 ts) p) <$> A.parseJSON j emptyCommitId :: Text emptyCommitId = "da39a3ee5e6b4b0d3255bfef95601890afd80709" serialize :: Commit -> ByteString serialize commit = LB.toStrict $ serialize' commit serialize' :: Commit -> LB.ByteString serialize' commit = A.encode commit serializeAndSum :: Commit -> (ByteString, Text) serializeAndSum commit = (serialized, decodeUtf8 $ Base16.encode $ SHA1.hash serialized) where serialized = serialize commit deserialize :: ByteString -> Maybe Commit deserialize bytes = deserialize' $ LB.fromChunks [bytes] deserialize' :: LB.ByteString -> Maybe Commit deserialize' bytes = A.decode bytes
jjwchoy/hotdb
src/HotDB/Core/Commit.hs
mit
1,698
0
12
249
510
298
212
48
1
{-# OPTIONS_GHC -fno-warn-orphans #-} module Demiurge.World where import Prelude hiding (any) import Control.Applicative((<$>)) import Data.Foldable(any) import Data.Maybe import Control.Monad (join) import qualified Data.Map as Map import Antiqua.Game import Antiqua.Graphics.Renderer import Antiqua.Graphics.TileRenderer import qualified Antiqua.Data.Array2d as A2D import Antiqua.Graphics.Window import Antiqua.Graphics.Assets import Antiqua.Utils import qualified Antiqua.Input.Controls as C import Antiqua.Common import Antiqua.Data.Graph import qualified Antiqua.Pathing.Dijkstra as D import Antiqua.Data.Coordinate import Demiurge.Input.ControlMap import qualified Demiurge.Tile as T import Demiurge.Common import qualified Demiurge.Data.Array3d as A3D import qualified Demiurge.Drawing.Renderable as Demiurge import qualified Demiurge.Entity as E import Demiurge.Worker import Demiurge.Plan import Debug.Trace forbid :: String -> TaskPermission forbid = TaskForbidden . Message updateWorkers :: [EWorker] -> Plan -> Terrain -> ([EWorker], Plan, Terrain) updateWorkers wks p ter = upOne [] wks p ter where upOne up (x:left) p t = let (wk', p', t') = processWorker x p (up ++ left) t in upOne (wk':up) left p' t' upOne up [] p t = (up, p, t) processWorker :: EWorker -> Plan -> [EWorker] -> Terrain -> (EWorker, Plan, Terrain) processWorker (WorkingWorker wk) p _ t = let tsk = getTask wk in case allowed tsk wk t of TaskPermitted -> perform tsk wk p t TaskBlocked _ -> let (wk', p') = unemploy (Message "Blocked") wk p in (pack $ wk', p', t) TaskForbidden rsn -> let (wk', p') = unemploy rsn wk p in (pack $ wk', p', t) processWorker (IdleWorker wk) plan _ t = (pack wk, plan, t) shiftTask :: Plan -> Worker 'Working -> (EWorker, Plan) shiftTask = undefined --do not use unemploy for finished tasks goalToTasks :: Goal -> EWorker -> Terrain -> NonEmpty Task goalToTasks (Build xyz) wk _ = let wPos = getPos wk in let adjPos = xyz ~~> nearestDir wPos xyz in (Navigate wPos adjPos, [Place xyz]) allowed :: Task -> Worker 'Working -> Terrain -> TaskPermission allowed Drop wk _ | (isJust . getResource . pack) wk = TaskPermitted | otherwise = forbid "Has no resource to drop" allowed Gather wk t | (isJust . getResource . pack) wk = forbid "Inventory is full" | not $ hasResource t ((getPos . pack) wk) T.Stone = forbid "No resource here to pick up" | otherwise = TaskPermitted allowed (Navigate _ _) _ _ = TaskPermitted allowed (Path (x, _)) _ t | (not . isWalkable t) x = forbid "Can't walk there" | otherwise = TaskPermitted allowed (Place xyz) _ t | isWholeSolid t xyz = forbid "Somethign is already build there" | otherwise = TaskPermitted perform :: Task -> Worker 'Working -> Plan -> Terrain -> (EWorker, Plan, Terrain) perform Drop wk p t = let (wk', p') = (shiftTask p . spendResource) wk in let t' = addResource t (getPos wk') T.Stone in (wk', p, t') perform Gather wk p t = let (wk', p') = (shiftTask p . giveResource T.Stone) wk in let t' = takeResource t (getPos wk') T.Stone in (wk', p', t') perform (Navigate src dst) wk p t = let path = pfind t src dst in let (wk', p') = case path of Left reason -> let (wk'', p'') = unemploy reason wk p in (pack wk'', p'') Right pth -> (pack $ mapTask (\_ -> Path pth) wk, p) in (wk', p, t) perform (Path (x, y:yx)) wk p t = let wk' = mapTask (\_ -> Path (y, yx)) $ setPos x wk in (pack wk', p, t) perform (Path (x, [])) wk p t = let (wk', p') = unemploy (Message "Task Finished") (setPos x wk) p in (pack wk', p', t) perform (Place xyz) wk p t = let t' = modTile t xyz (\_ -> T.Tile T.WholeSolid []) in (pack wk, p, t') unemploy :: Reason -> Worker 'Working -> Plan -> (Worker 'Idle, Plan) unemploy rsn (Employed e maj@(Major j i g) _) p = let wk = traceShow rsn $ Unemployed e rsn in (wk, reinsert maj p) unemploy rsn (Employed e min@(Minor g) _) p = let wk = traceShow rsn $ Unemployed e rsn in (wk, reinsert min p) type Terrain = A3D.Array3d T.Tile data GameState = GameState Plan Viewer Terrain [EWorker] data Viewer = Viewer Int Int Int (Int,Int,Int) clampView :: Viewer -> Viewer clampView (Viewer x y z m@(xm, ym, zm)) = Viewer (clamp 0 xm x) (clamp 0 ym y) (clamp 0 zm z) m updateViewer :: Viewer -> ControlMap C.TriggerAggregate -> Viewer updateViewer (Viewer x y z clam) ctrls = let up = (select 0 (-1) . C.isPressed . from ctrls) (Get :: Index 'CK'ZUp) in let down = (select up 1 . C.isPressed . from ctrls) (Get :: Index 'CK'ZDown)in clampView $ Viewer x y (z + down) clam class Coordinate c => World w c | w -> c where getTile :: w -> c -> Maybe T.Tile putTile :: w -> c -> T.Tile -> w resources :: w -> c -> [T.Resource] resources arr xy = fromMaybe T.emptyMs $ T.getResources <$> getTile arr xy addResource :: w -> c -> T.Resource -> w addResource arr xy r = modTile arr xy (T.addResource r) takeResource :: w -> c -> T.Resource -> w takeResource arr xy r = modTile arr xy (T.takeResource r) hasResource :: w -> c -> T.Resource -> Bool hasResource w xy r = elem r $ resources w xy modTile :: w -> c -> (T.Tile -> T.Tile) -> w modTile w xy f = let p = f <$> getTile w xy in fromMaybe w $ (putTile w xy) <$> p isStandable :: w -> c -> Bool isWalkable :: w -> c -> Bool isWalkable arr xy = any T.isWalkable (getTile arr xy) isFree :: w -> c -> Bool isFree arr xy = any T.isFree (getTile arr xy) isWholeSolid :: w -> c -> Bool isWholeSolid arr xy = any T.isWholeSolid (getTile arr xy) pfind :: w -> c -> c -> Either Reason (NonEmpty c) instance World (A3D.Array3d T.Tile) XYZ where getTile = A3D.get putTile w xyz tile = let updated = A3D.put w xyz tile in if any T.isFree (getTile w (xyz ~~> D'Upward)) then A3D.put updated (xyz ~~> D'Upward) $ T.Tile T.FloorSolid [] else updated isStandable arr xy = any id $ do t <- getTile arr xy (return . T.isStandable t . getTile arr) (xy ~~> D'Downward) pfind arr src dst = case D.pfind arr src dst of Just (x:xs) -> Right (x, xs) Just [] -> Right (dst, []) Nothing -> (Left . Message) ("No Path from " ++ show src ++ show dst) instance Graph (A3D.Array3d T.Tile) XYZ where neighbors arr (x, y, z) = let ns = [(x-1, y, z), (x+1, y, z), (x, y+1, z), (x, y-1, z)] in (, 1) <$> filter (isStandable arr) ns filterOffscreen :: Viewer -> [EWorker] -> [EWorker] filterOffscreen (Viewer _ _ z _) wks = filter onScreen wks where onScreen w = let (_, _, wz) = getPos w in wz == z instance Drawable GameState where draw (GameState _ v world wks) tex = do let (Viewer _ _ level _) = v let (Just layer) = A3D.getLayer world level let below = A3D.getLayer world (level-1) let ts = Tileset 16 16 16 16 let ren = Renderer tex ts let tr = empty let fl r (p, t) = let b = join $ (\x -> A2D.get x p) <$> below in r <+ (p, T.render t b) let tr' = (A2D.foldl fl tr layer) let rwks = Demiurge.render <$> (filterOffscreen v wks) render ren (tr' <++< rwks) instance Game GameState (ControlMap C.TriggerAggregate, Assets, Window) rng where runFrame (GameState p v w wks) (ctrls, _, _) g = let (wks', p', w') = updateWorkers wks p w in let nv = updateViewer v ctrls in ((GameState p' nv w' wks'), g) mkState :: Int -> Int -> Int -> GameState mkState cols rows layers = let view = Viewer 0 0 1 (0,0,layers-1) in let tiles = A3D.tabulate cols rows layers $ \(_, _, z) -> let tt = case z of 0 -> T.WholeSolid 1 -> T.FloorSolid _ -> T.Free in T.Tile tt [] in let wk = Employed (E.Entity 0 (0,0,1) E.Builder Nothing) undefined (Navigate (0,0,1) (10,10,1), []) in let plan = Plan [] [] (Map.empty) (\_ -> Minor (Build (0,0,0))) Nothing in GameState plan view tiles [pack wk]
olive/demiurge
src/Demiurge/World.hs
mit
8,492
0
21
2,422
3,682
1,896
1,786
-1
-1
{-# LANGUAGE DeriveDataTypeable #-} -- | The command line options module NicoLang.CliOptions ( NicoRunOptions (..) , nicoRunOptions ) where import Data.Data (Data, Typeable) import System.Console.CmdArgs ((&=), name, help, explicit, program, summary, args) data NicoRunOptions = NicoRunOptions { nicoRunTargetSourceFile :: Maybe FilePath , nicoRunTransToBF :: Bool , nicoRunDebug :: Bool , nicoRunShowResultMemory :: Bool } deriving (Data, Typeable) nicoRunOptions :: NicoRunOptions nicoRunOptions = NicoRunOptions { nicoRunTargetSourceFile = Nothing &= args , nicoRunTransToBF = False &= name "trans-bf" &= help "Don't run, compile to the brainf*ck code" &= explicit , nicoRunDebug = False &= name "debug" &= help "show the trace" &= explicit , nicoRunShowResultMemory = False &= name "show-result-memory" &= help "show the app result" &= explicit } &= program "nicorun" &= summary "Run the nico-lang program"
aiya000/nico-lang
app/NicoLang/CliOptions.hs
mit
982
0
12
197
219
126
93
20
1
module Configuration where import Data.Monoid ((<>)) import Data.Version (showVersion) import Data.Text (Text, pack, unpack) import Network.AWS.Data.Text (fromText) import Network.AWS.Types (LogLevel(..), Region) import qualified Network.AWS.CloudFormation.Types as CFN import Options.Applicative ( info , helper , progDesc , long , short , help , metavar , strArgument , showDefault , subparser , execParser , flag , value , optional , infoOption , hidden , str , eitherReader , Parser , ReadM , ParserInfo(..) ) import qualified Options.Applicative.Builder as OB import qualified Paths_evaporate as PackageInfo import Types (StackName(..)) data Command = Check | Get | Delete | Create | Upsert deriving (Show, Eq) data Options = Options { command :: Command , stackNameOption :: Maybe StackName , isDryRun :: Bool , logLevel :: LogLevel , onCreateFailure :: CFN.OnFailure , configFilePath :: FilePath , defaultRegion :: Maybe Region } loadConfiguration :: IO Options loadConfiguration = execParser (info (helper <*> version <*> parseOptions) $ progDesc "A simple, convention-based CloudFormation Stack deployment tool.\ \ The deployment region is read from the environment variable AWS_REGION or\ \ retrieved from the Instance Identity Document (for EC2 instances),\ \ otherwise it defaults to us-east-1.") parseOptions :: Parser Options parseOptions = Options <$> parseCommand <*> parseStackName <*> dryRun <*> verbose <*> onCreateFailureParser <*> configFile <*> optional parseDefaultRegion parseCommand :: Parser Command parseCommand = subparser $ OB.command "check" (pure Check `withInfo` "Check the stack status for a stack") <> OB.command "get" (pure Get `withInfo` "Get stack resources info for a stack") <> OB.command "delete" (pure Delete `withInfo` "Delete a stack") <> OB.command "create" (parseCreate `withInfo` "Create a stack") <> OB.command "upsert" (parseUpsert `withInfo` "Upsert a stack (Update if exists, otherwise Create)") dryRun :: Parser Bool dryRun = flag False True ( long "dry-run" <> help "Print the command that would be executed but don't execute it.") parseStackName :: Parser (Maybe StackName) parseStackName = optional (OB.option (StackName <$> text) ( long "stack-name" <> metavar "STACK_NAME" <> help "The name of the specific stack to be operated on. \ \ If omitted, all stacks defined in evaporate.yaml will be operated on. \ \ Upsert/create operations will fail if the stack being operated on has a \ \ dependency on another stack." )) verbose :: Parser LogLevel verbose = flag Info Trace ( long "verbose" <> short 'V' <> help "Enable verbose logging.") onCreateFailureParser :: Parser CFN.OnFailure onCreateFailureParser = OB.option OB.auto ( long "on-create-fail" <> metavar "FAILURE_BEHAVIOUR" <> value CFN.Rollback <> showDefault <> help "The behaviour that occurs when a stack cannot be created. \ \ Possible values: Delete, DoNothing, Rollback.") version :: Parser (a -> a) version = infoOption displayText ( long "version" <> short 'v' <> help "Print the version of the application." <> hidden ) where displayText = showVersion PackageInfo.version configFile :: Parser FilePath configFile = strArgument ( value "evaporate.yaml" <> metavar "CONFIG_FILE_PATH" <> showDefault <> help "The path to the yaml config file containing your stack \ \ definitions.") parseDefaultRegion :: Parser Region parseDefaultRegion = OB.option readRegion ( long "default-region" <> metavar "REGION" <> help "The default AWS region for your stacks, in the region format, eg `us-east-1`.") text :: ReadM Text text = pack <$> str parseCreate :: Parser Command parseCreate = pure Create parseUpsert :: Parser Command parseUpsert = pure Upsert withInfo :: Parser a -> Text -> ParserInfo a withInfo opts = info (helper <*> opts) . progDesc . unpack readRegion :: ReadM Region readRegion = eitherReader (fromText . pack)
SEEK-Org/evaporate
src/Configuration.hs
mit
5,118
0
13
1,841
925
503
422
121
1
import Control.Applicative import Data.Time.Calendar import Data.Time.Calendar.OrdinalDate main = print $ length sundays sundays = filter isSunday firsts firsts = (,,) <$> [1901..2000] <*> [1..12] <*> [1] isSunday (y,m,d) = (snd $ sundayStartWeek $ fromGregorian y m d) == 0
stu-smith/project-euler-haskell
Euler-019.hs
mit
290
0
8
54
114
64
50
7
1
{-# LANGUAGE OverloadedStrings #-} module Main where import Control.Monad.Trans.State (runState) import Data.ByteString.Char8 (pack, unpack) import Data.Maybe (listToMaybe) import qualified Data.List.NonEmpty as NE import System.ZMQ4 (version) import System.ZMQ4.Monadic (runZMQ, socket, Socket, Router(..), Pub(..), ZMQ, bind, receive, send, sendMulti) import Bidder.State import Bidder.Utils main :: IO () main = do (major,minor,patch) <- version putStrLn $ unwords ["Server running 0MQ",show major,show minor,show patch] runZMQ $ do publisher <- socket Pub receiver <- socket Router bind receiver "tcp://*:5555" bind publisher "tcp://*:5556" receiveJoin receiver (\message -> waitForJoin message 1 initialState publisher receiver) initialState :: Stack initialState = [] type AuctionFunction z x = Stack -> Socket z Pub -> Socket z Router -> ZMQ z x data Message = Message String String deriving (Show,Eq) sendMessage :: Socket z Router -> Message -> ZMQ z () sendMessage receiverSocket (Message ident message) = do sendMulti receiverSocket $ NE.fromList $ map pack [ident,"",message] receiveMessage :: Socket z Router -> ZMQ z Message receiveMessage receiverSocket = do identityBuffer <- receive receiverSocket _ <- receive receiverSocket messageBuffer <- receive receiverSocket return $ Message (unpack identityBuffer) (unpack messageBuffer) work :: AuctionFunction z () work previousState publisherSocket receiverSocket = do msg@(Message ident message) <- receiveMessage receiverSocket print' $ ident ++ ": " ++ message case message of "JOIN" -> do waitForJoin msg 1 previousState publisherSocket receiverSocket _ -> do newState <- receiveBid msg previousState publisherSocket receiverSocket work newState publisherSocket receiverSocket waitForJoin :: Message -> Int -> AuctionFunction z () waitForJoin _ 0 previousState publisherSocket receiverSocket = work previousState publisherSocket receiverSocket waitForJoin msg@(Message ident _) n previousState publisherSocket receiverSocket = do sendMessage receiverSocket (Message ident (show previousState)) send publisherSocket [] $ pack $ unwords ["10001","Client", ident, "has joined the auction."] if (n > 1) then receiveJoin receiverSocket (\_ -> continue ()) -- drop bids until the client joins else continue () where continue = (\() -> waitForJoin msg (n - 1) previousState publisherSocket receiverSocket) receiveJoin :: Socket z Router -> (Message -> ZMQ z x) -> ZMQ z x receiveJoin receiverSocket continuation = do print' "Waiting for a join..." msg@(Message ident message) <- receiveMessage receiverSocket print' $ ident ++ ": " ++ message ++ " (in receiveJoin)" case message of "JOIN" -> continuation msg _ -> do send receiverSocket [] $ "Try again!" receiveJoin receiverSocket continuation receiveBid :: Message -> AuctionFunction z Stack receiveBid (Message ident bidStr) previousState publisherSocket receiverSocket = do print' $ "Got bid: " ++ bidStr sendMessage receiverSocket (Message ident "ACK") let n = read bidStr :: Int let topBid = maybe 0 id $ listToMaybe previousState let (_,newState) = if n > topBid then runState (push n) previousState else ((),previousState) print' newState send publisherSocket [] $ pack $ unwords ["10001",show newState] return newState
elkorn/bidder
src/Bidder/Server/Main.hs
mit
3,897
0
14
1,104
1,115
557
558
105
2
module Immediate.GenerateJs where import Immediate.Syntax import qualified Language.ECMAScript3.Syntax as JS import qualified Language.ECMAScript3.Syntax.QuasiQuote as JsQ import GHC.Real import Data.List (intercalate) runtime = var "___runtime" runtimeMkThunk = JS.DotRef() runtime $ JS.Id() "mkthunk" var = JS.VarRef() . JS.Id() jsInt n = JS.CallExpr() (JS.DotRef() runtime $ JS.Id() "intlit") [JS.StringLit() $ show n] wrapScope :: [JS.Statement ()] -> JS.Expression () wrapScope stmts = JS.CallExpr() (JS.FuncExpr() Nothing [] stmts) [] genLiteral :: Literal -> JS.Expression() genLiteral (LiteralInteger n) = jsInt n genLiteral (LiteralRational (e :% d)) = JS.CallExpr() (JS.DotRef() (jsInt e) $ JS.Id() "div") [jsInt d] genLiteral (LiteralChar c) = JS.StringLit() [c] genLiteral (LiteralString s) = JS.StringLit() s varDecl :: Name -> JS.Expression() -> JS.Statement() varDecl name expr = if elem '.' name then JS.ExprStmt() $ JS.AssignExpr() JS.OpAssign (JS.LVar() name) expr else JS.VarDeclStmt() $ [JS.VarDecl() (JS.Id() name) $ Just $ expr] genVdef :: Vdef -> JS.Statement () genVdef (Vdef name expr) = varDecl name $ genExpr expr defer :: JS.Expression() -> JS.Expression() defer expr = JS.CallExpr() runtimeMkThunk [JS.FuncExpr() Nothing [] [body]] where body = JS.ReturnStmt() $ Just expr forceExp :: JS.Expression() -> JS.Expression() forceExp expr = JS.CallExpr() expr [] genAlt :: Name -> Alt -> JS.Expression() genAlt _ (AltDefault rhs) = genExpr rhs genAlt name (AltLit lit rhs) = JS.CondExpr() cond (genExpr rhs) $ var "undefined" where cond = JS.InfixExpr() JS.OpStrictEq (var name) (genLiteral lit) genAlt name (AltCon conName names rhs) = JS.CallExpr() (JS.DotRef() (var conName) (JS.Id() "unapply")) [ var name , JS.FuncExpr() Nothing (JS.Id() `fmap` names) [ JS.ReturnStmt() $ Just $ genExpr rhs ] ] genExpr :: Expression a -> JS.Expression () genExpr (Lit lit) = genLiteral lit genExpr (Var name) = var name genExpr (Lam name body) = JS.FuncExpr() Nothing [JS.Id() name] [JS.ReturnStmt() $ Just $ genExpr body] genExpr (App f x) = JS.CallExpr() (genExpr f) [genExpr x] genExpr (Let definitons expr) = wrapScope $ fmap genVdef definitons ++ [JS.ReturnStmt() $ Just $ genExpr expr] genExpr (Case expr name alts) = wrapScope [ varDecl name $ genExpr expr , JS.ReturnStmt() $ Just $ foldr joinAlt (var "undefined") alts ] where joinAlt alt els = JS.InfixExpr() JS.OpLOr (genAlt name alt) els genExpr (Force expr) = forceExp $ genExpr expr genExpr (Defer expr) = defer $ genExpr expr {- data Alt = AltDefault (Expression Deferred) | AltLit Literal (Expression Deferred) | AltCon Name [Name] (Expression Deferred) deriving (Show, Eq) -} genTdef :: Tdef -> [JS.Statement ()] genTdef (Data constructors) = concat $ zipWith mkData [0..] constructors where mkData i (Constructor name arity) = [ varDecl name $ defer $ apply arity , varDecl (name ++ ".unapply") $ unapply ] where apply 0 = JS.ArrayLit() $ (JS.IntLit() i) : fmap (\p -> var $ "arg" ++ show p) [arity,arity-1..1] apply p = JS.FuncExpr() Nothing [JS.Id() $ "arg" ++ show p] [JS.ReturnStmt() $ Just $ apply (p-1)] unapply = JS.FuncExpr() Nothing [JS.Id() "data", JS.Id() "f"] [force, iff] where force = JS.ExprStmt() $ JS.AssignExpr() JS.OpAssign (JS.LVar() "data") $ forceExp $ var "data" iff = JS.IfSingleStmt() predicate $ JS.ReturnStmt() $ Just $ callback predicate = JS.InfixExpr() JS.OpEq consId $ JS.IntLit() i consId = JS.BracketRef() (var "data") $ JS.IntLit() 0 callback = JS.CallExpr() (JS.DotRef() (var "f") (JS.Id() "apply")) [var "undefined", args] args = JS.CallExpr() (JS.DotRef() (var "data") (JS.Id() "slice")) [JS.IntLit() 1] genTdef (Newtype name) = [apply, unapply] where apply = varDecl name $ defer $ JS.FuncExpr() Nothing [JS.Id() "x"] [JS.ReturnStmt() $ Just $ var "x"] unapply = varDecl (name ++ ".unapply") $ defer $ JS.FuncExpr() Nothing [JS.Id() "x", JS.Id() "f"] [JS.ReturnStmt() $ Just $ JS.CallExpr() (var "f") [var "x"]] genImport :: Dependency -> JS.Statement() genImport (Dependency varName (exe, parts, name)) = varDecl varName $ JS.CallExpr() (var "require") [JS.StringLit() path] where path = "../" ++ exe ++ "/" ++ intercalate "_" (parts ++ [name]) ++ ".js" genModule :: Module -> JS.JavaScript () genModule (Module name dependencies tdefs vdefs) = JS.Script() $ prolog ++ imprts ++ types ++ values where prolog = [varDecl name $ var "exports"] imprts = fmap genImport (runtimeDep : dependencies) types = tdefs >>= genTdef values = fmap genVdef vdefs runtimeDep = Dependency "___runtime" ("runtime", [], "runtime")
edofic/core.js
src/Immediate/GenerateJs.hs
mit
4,835
0
17
973
2,261
1,124
1,137
85
2
{-# LANGUAGE TemplateHaskell, Arrows, GADTs, TypeFamilies #-} module Main where import System.Exit import Test.QuickCheck import Control.Monad import qualified Data.Set as S import Data.Maybe import Control.Arrow import Automata.Types import Automata.Combinators import Automata.Helpers data MyState = QStart | Q0 | Q1 | QDead deriving(Ord, Eq, Enum, Bounded, Show) data Character = Zero | One deriving(Ord, Eq, Enum, Bounded, Show) f :: MyState -> MyState -> Character -> MyState f q _ Zero = q f _ q One = q dfa = makeDFA [Zero,One] Q0 [Q0,Q1] [ (Q0, f Q0 Q1), (Q1, f QDead Q1), (QDead, const QDead) ] :: DFA (->) MyState Character nfaR = reverseFA QStart dfa nfaRI = intersectFA dfa nfaR parse :: Bool -> Character parse False = Zero parse True = One runFA fa input = (acceptFA fa . applyFA fa) (fmap parse input) isSorted :: [Bool] -> Bool isSorted [] = True isSorted [i] = True isSorted (x:y:xs) = x <= y && isSorted (y:xs) prop_isSortedDFA input = f1 == p where p = isSorted input f1 = runFA dfa input prop_isSortedNFA input = f1 == p where p = isSorted input f1 = runFA (toNFA dfa) input prop_reverse_correct input = runFA dfa input == runFA nfaR (reverse input) prop_intersect_correct input = runFA nfaRI input == (f1 && f2) where f1 = runFA dfa input f2 = runFA nfaR input lNegHalf' :: (ArrowChoice arrow, Ord s, Ord a) => s -> DFA arrow s a -> NFA arrow (s,s) a lNegHalf' q_0 = ((reverseTransitionFA &&& id) >>> uncurry intersectFA) &&& id >>> uncurry finishMod where finishMod nfa origDfa = NFA states (get_E nfa) delta start accepts where states = start `S.insert` get_Q nfa start = (q_0, q_0) accepts = S.singleton (get_q_0 origDfa) `cartProd` get_F origDfa qq = S.fromList [(q,q) | q <- S.toList (get_Q origDfa)] delta = proc (q, sigma) -> if start == q then returnA -< if isNothing sigma then qq else S.empty else transitionFA nfa -< (S.singleton q, sigma) nfa12 = lNegHalf' QStart dfa allEq [] = True allEq [a] = True allEq (x:y:ys) = (x == y) && allEq (y:ys) prop_complex_correct input = runFA nfa12 input == runFA dfa (reverse input ++ input) return [] runAll = $quickCheckAll main = do -- quickCheck prop_complex_correct -- quickCheck prop_intersect_correct -- quickCheck prop_reverse_correct -- quickCheck prop_isSorted success <- runAll unless success exitFailure
terrelln/automata
tests/properties.hs
mit
3,613
1
15
1,715
955
503
452
61
3
module Parser( Parser(..), get, put, maybeParser, maybeParsers, tryParserOtherwise, tryParsersOtherwise, peek, peeks, word, line ) where import Control.Monad(when) import Control.Applicative import Data.Char(isSpace) import Data.Monoid newtype Parser a = P { runP :: String -> Either String (a,String) } instance Monad Parser where return x = P $ \str -> Right (x,str) m >>= f = P $ (\str -> case (runP m $ str) of Left s -> Left s Right (a, str') -> let m' = f a in runP m' $ str') fail s = P $ \str -> Left s -- laws? -- f = \x -> P $ \str -> Right (head str == x, tail str) -- return x >>= k = k a. CHECK -- g = P $ \str -> Right (init str, [last str]) -- m >>= return = m. CHECK instance Functor Parser where fmap g f = f >>= (return . g) -- laws? -- 1. fmap id = id -- 2. fmap (f . g) = fmap f . fmap g = fmap f (fmap g F) instance Applicative Parser where pure = return f <*> g = do f' <- f a <- g fmap f' $ return a -- laws? -- 1. pure id <*> v = v -- 2. pure f <*> pure x = pure (f x) -- 3. u <*> pure y = pure ($ y) <*> u -- 4. u <*> (v <*> w) = pure (.) <*> u <*> v <*> w -- g = P $ \str -> if null str then Left "null str! >:(" else Right (init str, [last str]) -- State -- get :: Parser String get = P $ \s -> Right (s,s) put :: String -> Parser () put s = P $ \s' -> Right ((),s) -- parsing util -- maybeParser :: Parser a -> Parser (Maybe a) maybeParser p = do s <- get either (const $ nothing s) (just) (runP p s) where nothing s = do put s return Nothing just (a,s) = do put s return $ Just a maybeParsers :: [Parser (Maybe a)] -> Parser (Maybe a) maybeParsers = fmap (getFirst . mconcat. map First) . sequence tryParserOtherwise :: Parser a -> Parser a -> Parser a tryParserOtherwise p1 p2 = tryParsersOtherwise [p1] p2 tryParsersOtherwise :: [Parser a] -> Parser a -> Parser a tryParsersOtherwise ps p = do ma <- mp maybe p return ma where mp = maybeParsers $ map maybeParser ps -- token parsing util -- peek :: Parser Char peek = do s <- get when (null s) (fail "Expected character in stream") return $ head s peeks :: Parser String peeks = fmap (:[]) peek word :: Parser String word = do s <- get let (w,s') = break isSpace . dropWhile isSpace $ s when (null w) (fail "Expected word in stream") put s' return w line :: Parser String line = do s <- get let (theline,s') = break (=='\n') s put $ dropFirstIf (=='\n') s' return theline where dropFirstIf _ [] = [] dropFirstIf p (s:ss) = if p s then ss else s:ss
kyle-ilantzis/Simple-ASM
Parser.hs
mit
2,626
33
16
718
996
508
488
76
3
-- Copyright (c) 2012-2014 NVIDIA Corporation. All rights reserved. -- -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -- SOFTWARE. import Distribution.Simple main = defaultMain
nvidia-compiler-sdk/hsnvvm
Setup.hs
mit
1,191
0
4
196
30
25
5
2
1
{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE BangPatterns #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE LambdaCase #-} ----------------------------------------------------------------------------- -- -- Module : IDE.Utils.FileUtils -- Copyright : 2007-2011 Juergen Nicklisch-Franken, Hamish Mackenzie -- License : GPL -- -- Maintainer : [email protected] -- Stability : provisional -- Portability : -- -- | -- ----------------------------------------------------------------------------- module IDE.Utils.FileUtils ( allModules , allHiFiles , allHaskellSourceFiles , isEmptyDirectory , cabalFileName , nixShellFile , loadNixCache , saveNixCache , loadNixEnv , runProjectTool , allCabalFiles , getConfigFilePathForLoad , hasSavedConfigFile , getConfigDir , getConfigFilePathForSave , getCollectorPath , getSysLibDir , moduleNameFromFilePath , moduleNameFromFilePath' , moduleCollectorFileName , findKnownPackages , isSubPath , findSourceFile , findSourceFile' , haskellSrcExts , getCabalUserPackageDir , autoExtractTarFiles , getInstalledPackages , findProjectRoot , cabalProjectBuildDir , getPackageDBs' , getPackageDBs , figureOutGhcOpts , figureOutGhcOpts' , figureOutHaddockOpts , allFilesWithExtensions , myCanonicalizePath ) where import Prelude () import Prelude.Compat hiding (readFile) import Control.Applicative (many, (<|>)) import Control.Arrow (second) import System.FilePath (splitFileName, dropExtension, takeExtension, combine, addExtension, (</>), normalise, splitPath, takeFileName, takeDirectory, dropFileName, takeBaseName) import Distribution.ModuleName (toFilePath, ModuleName) import Control.Monad (when, foldM, filterM, forM, join) import Data.Maybe (fromMaybe, mapMaybe, catMaybes, listToMaybe, maybeToList) import Distribution.Simple.PreProcess.Unlit (unlit) import System.Directory (createDirectoryIfMissing, getAppUserDataDirectory, canonicalizePath, doesDirectoryExist, doesFileExist, setCurrentDirectory, getCurrentDirectory, getDirectoryContents, getHomeDirectory, findExecutable, exeExtension, doesPathExist) import Text.ParserCombinators.Parsec.Language (haskellDef, haskell) import qualified Text.ParserCombinators.Parsec.Token as P (GenTokenParser(..), TokenParser, identStart) import Text.ParserCombinators.Parsec (GenParser, parse, oneOf, alphaNum, noneOf, char, try, (<?>), CharParser) import Data.Set (Set) import Data.List (isPrefixOf, isSuffixOf, stripPrefix, nub) import qualified Data.Set as Set (empty, fromList) import Distribution.Package (UnitId) import Data.Char (ord, isAlphaNum) import Distribution.Text (simpleParse, display) import IDE.Utils.Utils import IDE.Core.CTypes(configDirName, ModuleKey(..), PackageDBs(..)) import qualified Distribution.Text as T (simpleParse) import System.Log.Logger(errorM,warningM,debugM) import IDE.Utils.Tool import Control.Monad.IO.Class (MonadIO(..), MonadIO) import Control.Exception as E (SomeException, catch) import System.IO.Strict (readFile) import qualified Data.Text as T (pack, stripPrefix, isSuffixOf, take, length, unpack, words, splitOn, dropWhileEnd, stripSuffix) import Data.Text (Text) import Control.DeepSeq (deepseq) import IDE.Utils.VersionUtils (ghcExeName, getDefaultGhcVersion) import Data.Aeson (eitherDecodeStrict') import IDE.Utils.CabalPlan (PlanJson(..), piNameAndVersion) import IDE.Utils.CabalProject (findProjectRoot) import qualified Data.ByteString as BS (readFile) import Data.Map (Map) import qualified Data.Text.IO as T (writeFile, readFile) import Text.Read.Compat (readMaybe) import qualified Data.Map as M (insert, fromList, toList, lookup) import System.Process (showCommandForUser) import IDE.Utils.Project (ProjectKey(..), CabalProject(..), StackProject(..), CustomProject(..), pjDir) haskellSrcExts :: [FilePath] haskellSrcExts = ["hs","lhs","chs","hs.pp","lhs.pp","chs.pp","hsc"] -- | canonicalizePath without crashing myCanonicalizePath :: FilePath -> IO FilePath myCanonicalizePath fp = do exists <- doesPathExist fp if exists then canonicalizePath fp else return fp -- | Returns True if the second path is a location which starts with the first path isSubPath :: FilePath -> FilePath -> Bool isSubPath fp1 fp2 = let fpn1 = splitPath $ normalise fp1 fpn2 = splitPath $ normalise fp2 res = isPrefixOf fpn1 fpn2 in res findSourceFile :: [FilePath] -> [FilePath] -> ModuleName -> IO (Maybe FilePath) findSourceFile directories exts modId = let modulePath = toFilePath modId allPathes = map (</> modulePath) directories allPossibles = concatMap (\ p -> map (addExtension p) exts) allPathes in find' allPossibles findSourceFile' :: [FilePath] -> FilePath -> IO (Maybe FilePath) findSourceFile' directories modulePath = let allPathes = map (</> modulePath) directories in find' allPathes find' :: [FilePath] -> IO (Maybe FilePath) find' [] = return Nothing find' (h:t) = E.catch (do exists <- doesFileExist h if exists then Just <$> canonicalizePath h else find' t) $ \ (_ :: SomeException) -> return Nothing -- | The directory where config files reside -- getConfigDir :: IO FilePath getConfigDir = do d <- getHomeDirectory let filePath = d </> configDirName createDirectoryIfMissing False filePath return filePath getConfigDirForLoad :: IO (Maybe FilePath) getConfigDirForLoad = do d <- getHomeDirectory let filePath = d </> configDirName exists <- doesDirectoryExist filePath if exists then return (Just filePath) else return Nothing hasSavedConfigFile :: FilePath -> IO Bool hasSavedConfigFile fn = do savedConfigFile <- getConfigFilePathForSave fn doesFileExist savedConfigFile -- | Gets a config file. If the second argument is Nothing -- first looks in the config dir (~/.leksah-x/), if it's not present -- the data directory at the given location is checked (this is an argument -- because `getDataDir` has to be called in Leksah code. getConfigFilePathForLoad :: FilePath -- ^ Config filename with extension -> Maybe FilePath -- ^ Optional directory to check first -> FilePath -- ^ Data dir to check if not present in config dir -> IO FilePath getConfigFilePathForLoad fn mbFilePath dataDir = do mbCd <- case mbFilePath of Just p -> return (Just p) Nothing -> getConfigDirForLoad case mbCd of Nothing -> getFromData Just cd -> do ex <- doesFileExist (cd </> fn) if ex then return (cd </> fn) else getFromData where getFromData = do ex <- doesFileExist (dataDir </> "data" </> fn) if ex then return (dataDir </> "data" </> fn) else error $"Config file not found: " ++ fn getConfigFilePathForSave :: FilePath -> IO FilePath getConfigFilePathForSave fn = do cd <- getConfigDir return (cd </> fn) allModules :: FilePath -> IO [ModuleName] allModules filePath = E.catch (do exists <- doesDirectoryExist filePath if exists then do filesAndDirs <- getDirectoryContents filePath let filesAndDirs' = map (combine filePath) $filter (\s -> s /= "." && s /= ".." && s /= "_darcs" && s /= "dist" && s /= "dist-newstyle" && s /= "Setup.lhs") filesAndDirs dirs <- filterM doesDirectoryExist filesAndDirs' files <- filterM doesFileExist filesAndDirs' let hsFiles = filter (\f -> let ext = takeExtension f in ext == ".hs" || ext == ".lhs") files mbModuleStrs <- mapM moduleNameFromFilePath hsFiles let mbModuleNames = mapMaybe (maybe Nothing (simpleParse . T.unpack)) mbModuleStrs otherModules <- mapM allModules dirs return (mbModuleNames ++ concat otherModules) else return []) $ \ (_ :: SomeException) -> return [] allHiFiles :: FilePath -> IO [FilePath] allHiFiles = allFilesWithExtensions [".hi"] True [] allCabalFiles :: FilePath -> IO [FilePath] allCabalFiles = allFilesWithExtensions [".cabal"] False [] allHaskellSourceFiles :: FilePath -> IO [FilePath] allHaskellSourceFiles = allFilesWithExtensions [".hs",".lhs"] True [] allFilesWithExtensions :: [FilePath] -> Bool -> [FilePath] -> FilePath -> IO [FilePath] allFilesWithExtensions extensions recurseFurther collecting filePath = E.catch (do exists <- doesDirectoryExist filePath if exists then do filesAndDirs <- getDirectoryContents filePath let filesAndDirs' = map (combine filePath) $filter (\s -> s /= "." && s /= ".." && s /= "_darcs") filesAndDirs dirs <- filterM doesDirectoryExist filesAndDirs' files <- filterM doesFileExist filesAndDirs' let choosenFiles = filter (\f -> let ext = takeExtension f in elem ext extensions) files if recurseFurther || (not recurseFurther && null choosenFiles) then foldM (allFilesWithExtensions extensions recurseFurther) (choosenFiles ++ collecting) dirs else return (choosenFiles ++ collecting) else return collecting) $ \ (_ :: SomeException) -> return collecting moduleNameFromFilePath :: FilePath -> IO (Maybe Text) moduleNameFromFilePath fp = E.catch (do exists <- doesFileExist fp if exists then do str <- readFile fp moduleNameFromFilePath' fp str else return Nothing) $ \ (_ :: SomeException) -> return Nothing moduleNameFromFilePath' :: FilePath -> FilePath -> IO (Maybe Text) moduleNameFromFilePath' fp str = do let unlitRes = if takeExtension fp == ".lhs" then unlit fp str else Left str case unlitRes of Right err -> do errorM "leksah-server" (show err) return Nothing Left str' -> do let parseRes = parse moduleNameParser fp str' case parseRes of Left _ -> return Nothing Right str'' -> return (Just str'') -- | Get the file name to use for the module collector results -- we want to store the file name for Main module since there can be several in one package moduleCollectorFileName :: ModuleKey -- ^ The module key -> String -- ^ The name to use for the collector file (without extension) moduleCollectorFileName (LibModule name) = display name moduleCollectorFileName (MainModule sourcePath) = "Main_" ++ "_" ++ takeFileName (takeDirectory sourcePath) ++ dropExtension (takeFileName sourcePath) lexer :: P.TokenParser st lexer = haskell lexeme :: CharParser st a -> CharParser st a lexeme = P.lexeme lexer whiteSpace :: CharParser st () whiteSpace = P.whiteSpace lexer symbol :: Text -> CharParser st Text symbol = (T.pack <$>) . P.symbol lexer . T.unpack moduleNameParser :: CharParser () Text moduleNameParser = do whiteSpace _ <- many skipPreproc whiteSpace _ <- symbol "module" lexeme mident <?> "module identifier" skipPreproc :: CharParser () () skipPreproc = try (do whiteSpace _ <- char '#' _ <- many (noneOf "\n") return ()) <?> "preproc" mident :: GenParser Char st Text mident = do{ c <- P.identStart haskellDef ; cs <- many (alphaNum <|> oneOf "_'.") ; return (T.pack (c:cs)) } <?> "midentifier" findKnownPackages :: FilePath -> IO (Set Text) findKnownPackages filePath = E.catch (do paths <- getDirectoryContents filePath let nameList = map (T.pack . dropExtension) $ filter (\s -> leksahMetadataSystemFileExtension `isSuffixOf` s) paths return (Set.fromList nameList)) $ \ (_ :: SomeException) -> return Set.empty isEmptyDirectory :: FilePath -> IO Bool isEmptyDirectory filePath = E.catch (do exists <- doesDirectoryExist filePath if exists then do filesAndDirs <- getDirectoryContents filePath return . null $ filter (not . ("." `isPrefixOf`) . takeFileName) filesAndDirs else return False) (\ (_ :: SomeException) -> return False) cabalFileName :: FilePath -> IO (Maybe FilePath) cabalFileName filePath = E.catch (do exists <- doesDirectoryExist filePath if exists then do filesAndDirs <- map (filePath </>) <$> getDirectoryContents filePath files <- filterM doesFileExist filesAndDirs case filter (\f -> let ext = takeExtension f in ext == ".cabal") files of [f] -> return (Just f) [] -> return Nothing _ -> do warningM "leksah-server" "Multiple cabal files" return Nothing else return Nothing) (\ (_ :: SomeException) -> return Nothing) loadNixCache :: MonadIO m => m (Map (FilePath, Text) (Map String String)) loadNixCache = liftIO $ do configDir <- getConfigDir let filePath = configDir </> "nix.cache" doesFileExist filePath >>= \case True -> fromMaybe mempty . readMaybe . T.unpack <$> T.readFile filePath False -> return mempty includeInNixCache :: String -> Bool includeInNixCache name = not (null name) && all (\c -> isAlphaNum c || c == '_') name && name `notElem` ["POSIXLY_CORRECT", "SHELLOPTS", "BASHOPTS"] saveNixCache :: MonadIO m => ProjectKey -> Text -> [ToolOutput] -> m (Map String String) saveNixCache project compiler out = liftIO $ do let newEnv = M.fromList . filter (includeInNixCache . fst) $ mapMaybe (\case ToolOutput line -> Just . fixQuotes . second (drop 1) . span (/='=') $ T.unpack line _ -> Nothing) out configDir <- getConfigDir let filePath = configDir </> "nix.cache" T.writeFile filePath . T.pack . show =<< M.insert (pjDir project, compiler) newEnv <$> loadNixCache return newEnv where fixQuotes ("IFS", _) = ("IFS", " \t\n") fixQuotes (n, '\'':rest) = (n, maybe rest T.unpack . T.stripSuffix "'" $ T.pack rest) fixQuotes x = x loadNixEnv :: MonadIO m => ProjectKey -> Text -> m (Maybe (Map String String)) loadNixEnv project compiler = M.lookup (pjDir project, compiler) <$> loadNixCache nixShellFile :: MonadIO m => ProjectKey -> m (Maybe FilePath) nixShellFile project = do let dir = pjDir project shellNix = dir </> "shell.nix" defaultNix = dir </> "default.nix" liftIO (doesFileExist shellNix) >>= \case True -> return $ Just shellNix False -> liftIO (doesFileExist defaultNix) >>= \case True -> return $ Just defaultNix False -> return Nothing nixPath :: ProjectKey -> IO (Maybe String) nixPath project = nixShellFile project >>= \case Just _ -> loadNixEnv project "ghc" >>= \case Just nixEnv -> return $ M.lookup "PATH" nixEnv Nothing -> return Nothing Nothing -> return Nothing runProjectTool :: Maybe ProjectKey -> FilePath -> [Text] -> Maybe FilePath -> Maybe [(String, String)] -> IO ([ToolOutput], ProcessHandle) runProjectTool Nothing fp args mbDir mbEnv = runTool' fp args mbDir mbEnv runProjectTool (Just project) fp args mbDir mbEnv = nixShellFile project >>= \case Just nixFile -> loadNixEnv project "ghc" >>= \case Just nixEnv -> do debugM "leksah" $ "Using cached nix environment for ghc " <> show project runTool' "bash" ["-c", T.pack . showCommandForUser fp $ map T.unpack args] mbDir $ M.toList <$> Just nixEnv <> (M.fromList <$> mbEnv) Nothing -> do debugM "leksah" $ "Ignoring " <> nixFile <> ". To enable nix right click on the project in the workspace an select 'Refresh Nix Environment Variables'" runTool' fp args mbDir mbEnv Nothing -> runTool' fp args mbDir mbEnv getCabalUserPackageDir :: IO (Maybe FilePath) getCabalUserPackageDir = do (!output,_) <- runTool' "cabal" ["help"] Nothing Nothing output `deepseq` case T.stripPrefix " " (toolline $ last output) of Just s | "config" `T.isSuffixOf` s -> return . Just . T.unpack $ T.take (T.length s - 6) s <> "packages" _ -> return Nothing autoExtractTarFiles :: FilePath -> IO () autoExtractTarFiles filePath = do dir <- getCurrentDirectory autoExtractTarFiles' filePath setCurrentDirectory dir autoExtractTarFiles' :: FilePath -> IO () autoExtractTarFiles' filePath = E.catch (do exists <- doesDirectoryExist filePath when exists $ do filesAndDirs <- getDirectoryContents filePath let filesAndDirs' = map (combine filePath) $ filter (\s -> s /= "." && s /= ".." && not ("00-index" `isPrefixOf` s)) filesAndDirs dirs <- filterM doesDirectoryExist filesAndDirs' files <- filterM doesFileExist filesAndDirs' let choosenFiles = filter (isSuffixOf ".tar.gz") files let decompressionTargets = filter (\f -> (dropExtension . dropExtension) f `notElem` dirs) choosenFiles mapM_ (\f -> let (dir,fn) = splitFileName f command = "tar -zxf " ++ fn in do setCurrentDirectory dir handle <- runCommand command _ <- waitForProcess handle return ()) decompressionTargets mapM_ autoExtractTarFiles' dirs ) $ \ (_ :: SomeException) -> return () getCollectorPath :: MonadIO m => m FilePath getCollectorPath = liftIO $ do configDir <- getConfigDir let filePath = configDir </> "metadata" createDirectoryIfMissing False filePath return filePath getSysLibDir :: Maybe ProjectKey -> Maybe FilePath -> IO (Maybe FilePath) getSysLibDir project ver = E.catch (do (!output,_) <- runProjectTool project (ghcExeName ver) ["--print-libdir"] Nothing Nothing let libDir = listToMaybe [line | ToolOutput line <- output] libDir2 = T.dropWhileEnd ((==) 13 . ord) <$> libDir output `deepseq` return $ normalise . T.unpack <$> libDir2 ) $ \ (_ :: SomeException) -> return Nothing getStackPackages :: StackProject -> IO [(UnitId, Maybe ProjectKey)] getStackPackages project = do (!output', _) <- runTool' "stack" ["--stack-yaml", T.pack (pjStackFile project), "exec", "ghc-pkg", "--", "list", "--simple-output"] Nothing Nothing output' `deepseq` return $ map (,Just (StackTool project)) $ concatMap ghcPkgOutputToPackages output' ghcPkgOutputToPackages :: ToolOutput -> [UnitId] ghcPkgOutputToPackages (ToolOutput n) = mapMaybe (T.simpleParse . T.unpack) (T.words n) ghcPkgOutputToPackages _ = [] --getCabalPackages :: FilePath -> FilePath -> IO [(UnitId, [FilePath])] --getCabalPackages ghcVer project = do -- packageDBs <- getCabalPackageDBs (Just project) ghcVer -- (eitherDecodeStrict' <$> BS.readFile (dropFileName project </> "dist-newstyle" </> "cache" </> "plan.json")) -- >>= \ case -- Left _ -> return [] -- Right plan -> return . map (,packageDBs) $ -- mapMaybe (T.simpleParse . T.unpack . piId) (pjPlan plan) readPlan :: FilePath -> FilePath -> IO (Maybe PlanJson) readPlan projectRoot buildDir = do let distNewstyle = projectRoot </> buildDir planFile = distNewstyle </> "cache" </> "plan.json" doesFileExist planFile >>= \case False -> do debugM "leksah" $ "cabal plan not found : " <> planFile return Nothing True -> (eitherDecodeStrict' <$> BS.readFile planFile) >>= \ case Right plan -> return (Just plan) Left err -> do errorM "leksah" $ "Error parsing cabal plan : " <> err return Nothing cabalProjectBuildDir :: FilePath -> FilePath -> IO (FilePath, FilePath -> FilePath -> FilePath, Maybe FilePath) cabalProjectBuildDir projectRoot buildDir = do let distNewstyle = projectRoot </> buildDir defaultDir = (distNewstyle </> "build", const $ const "build", Nothing) readPlan projectRoot buildDir >>= \ case Just PlanJson { pjCabalVersion = v } | "1.24." `isPrefixOf` v -> return defaultDir Just PlanJson { pjCabalVersion = v , pjCompilerId = Just compilerId , pjOS = Just os , pjArch = Just arch } | "2.0." `isPrefixOf` v -> return (distNewstyle </> "build" </> arch <> "-" <> os </> compilerId, \_ctype component -> "c" </> component </> "build", Just v) Just PlanJson { pjCabalVersion = v , pjCompilerId = Just compilerId , pjOS = Just os , pjArch = Just arch } -> return (distNewstyle </> "build" </> arch <> "-" <> os </> compilerId, \ctype component -> ctype </> component </> "build", Just v) Just plan -> do errorM "leksah" $ "Unexpected cabal plan : " <> show plan return defaultDir Nothing -> return defaultDir -- On windows there is no "ghc-pkg-8.2.2.exe" so we should look also -- for "ghc-pkg.exe" in the directory where "ghc-8.2.2.exe" is found findGhcPkg :: Maybe ProjectKey -> FilePath -> FilePath -> IO FilePath findGhcPkg project hc hVer = maybe (return Nothing) nixPath project >>= \case Just _ -> return preferedName Nothing -> findExecutable preferedName >>= \case Nothing -> maybe preferedName ghcPkgAlongSide <$> findExecutable (hc <> "-" <> hVer <> exeExtension) Just x -> return x where ghcPkgAlongSide f = dropFileName f <> "ghc-pkg" <> takeExtension f preferedName = hc <> "-pkg-" <> hVer getPackages' :: Maybe ProjectKey -> FilePath -> FilePath -> [FilePath] -> IO [UnitId] getPackages' project hc hVer packageDBs = do ghcPkg <- findGhcPkg project hc hVer (!output', _) <- runProjectTool project ghcPkg (["list", "--simple-output"] ++ map (("--package-db="<>) . T.pack) packageDBs) Nothing Nothing output' `deepseq` return $ concatMap ghcPkgOutputToPackages output' getPackages :: Maybe ProjectKey -> FilePath -> FilePath-> [FilePath] -> IO [(UnitId, Maybe ProjectKey)] getPackages project hc hVer packageDBs = map (,project) <$> getPackages' project hc hVer packageDBs -- | Find the packages that the packages in the workspace getInstalledPackages :: FilePath -> [ProjectKey] -> IO [(UnitId, Maybe ProjectKey)] getInstalledPackages ghcVer projects = do debugM "leksah" $ "getInstalledPackages " <> show ghcVer <> " " <> show projects -- versions <- nub . (ghcVer:) <$> forM projects (\project -> E.catch ( -- if takeExtension project == "yaml" -- then return [] -- else do -- x <- getProjectCompilerId -- projectDB <- getProjectPackageDB ghcVer project "dist-newstyle" -- doesDirectoryExist projectDB >>= \case -- False -> return [] -- True -> map (,globalDBs<>[projectDB]) <$> getPackages' [projectDB] -- ) $ \ (_ :: SomeException) -> return []) globalDBs <- sequence [getGlobalPackageDB Nothing (Just ghcVer), Just <$> getStorePackageDB ghcVer] >>= filterM doesDirectoryExist . catMaybes globalPackages <- E.catch (getPackages Nothing "ghc" ghcVer globalDBs) $ \ (_ :: SomeException) -> return [] debugM "leksah" $ "globalPackages = " <> show globalPackages localPackages <- forM projects $ \projectKey -> E.catch ( case projectKey of StackTool project -> getStackPackages project CabalTool project -> do let cabalFile = pjCabalFile project (hc, hVer, projectDB) <- getProjectPackageDB ghcVer project "dist-newstyle" doesDirectoryExist projectDB >>= \case False -> return [] True -> do projGlobalDBs <- sequence [getGlobalPackageDB (Just projectKey) (Just hVer), Just <$> getStorePackageDB hVer] >>= filterM doesDirectoryExist . catMaybes -- projGlobalPackages <- E.catch (getPackages (Just cabalFile) hc hVer projGlobalDBs) $ \ (_ :: SomeException) -> return [] map (,Just projectKey) <$> getPackages' (Just projectKey) hc hVer (projectDB : projGlobalDBs) CustomTool project -> return [] ) $ \ (_ :: SomeException) -> return [] debugM "leksah" $ "localPackages = " <> show localPackages return . nub $ globalPackages <> concat localPackages getGlobalPackageDB :: Maybe ProjectKey -> Maybe FilePath -> IO (Maybe FilePath) getGlobalPackageDB mbProject ghcVersion = do ghcLibDir <- getSysLibDir mbProject ghcVersion -- case mbProject of -- Nothing -> getSysLibDir ghcVersion -- Just project -> do -- let nixFile = dropFileName project </> "default.nix" -- doesFileExist nixFile >>= \case -- False -> getSysLibDir ghcVersion -- True -> getSysLibDirNix nixFile >>= \case -- Nothing -> getSysLibDir ghcVersion -- Just d -> return $ Just d return $ (</> "package.conf.d") <$> ghcLibDir getStorePackageDB :: FilePath -> IO FilePath getStorePackageDB ghcVersion = do cabalDir <- getAppUserDataDirectory "cabal" return $ cabalDir </> "store" </> "ghc-" ++ ghcVersion </> "package.db" getProjectPackageDB :: FilePath -> CabalProject -> FilePath -> IO (FilePath, FilePath, FilePath) getProjectPackageDB ghcVersion project buildDir = do let projectRoot = dropFileName (pjCabalFile project) c <- fromMaybe ("ghc-" <> ghcVersion) <$> getProjectCompilerId projectRoot buildDir let (hc, hVer) = span (/='-') c return (hc, drop 1 hVer, projectRoot </> buildDir </> "packagedb" </> c) getProjectCompilerId :: FilePath -> FilePath -> IO (Maybe FilePath) getProjectCompilerId projectRoot buildDir = join . mapM pjCompilerId <$> readPlan projectRoot buildDir --getProjectCompiler :: FilePath -> FilePath -> IO (Maybe FilePath) --getProjectCompiler projectRoot buildDir = -- getProjectCompilerId projectRoot buildDir >>= \case -- Just PlanJson { pjCompilerId = Just c } -> return . Just . dropWhile (=='-') $ dropWhile (/='-') c -- _ -> return Nothing getCabalPackageDBs :: Maybe CabalProject -> FilePath -> IO [FilePath] getCabalPackageDBs Nothing ghcVersion = sequence [getGlobalPackageDB Nothing (Just ghcVersion), Just <$> getStorePackageDB ghcVersion] >>= filterM doesDirectoryExist . catMaybes getCabalPackageDBs (Just project) ghcVersion = do (_, hVer, projectDB) <- getProjectPackageDB ghcVersion project "dist-newstyle" doesDirectoryExist projectDB >>= \case False -> return [] True -> do projGlobalDBs <- sequence [getGlobalPackageDB (Just (CabalTool project)) (Just hVer), Just <$> getStorePackageDB hVer] >>= filterM doesDirectoryExist . catMaybes return (projectDB : projGlobalDBs) getStackPackageDBs :: StackProject -> IO [FilePath] getStackPackageDBs project = do (!output, _) <- runTool' "stack" ["--stack-yaml", T.pack (pjStackFile project), "path", "--ghc-package-path"] Nothing Nothing filterM doesDirectoryExist $ concatMap paths output where paths (ToolOutput n) = map T.unpack (T.splitOn ":" n) paths _ = [] getPackageDBs' :: FilePath -> Maybe ProjectKey -> IO PackageDBs getPackageDBs' ghcVersion mbProject = E.catch ( case mbProject of Just (StackTool project) -> PackageDBs mbProject Nothing <$> getStackPackageDBs project Just (CabalTool project) -> do dbs <- getCabalPackageDBs (Just project) ghcVersion plan <- readPlan (dropFileName $ pjCabalFile project) "dist-newstyle" return $ PackageDBs mbProject (Set.fromList . map piNameAndVersion . pjPlan <$> plan) dbs _ -> PackageDBs mbProject Nothing <$> getCabalPackageDBs Nothing ghcVersion ) $ \ (_ :: SomeException) -> return $ PackageDBs mbProject Nothing [] getPackageDBs :: [ProjectKey] -> IO [PackageDBs] getPackageDBs projects = do ghcVersion <- getDefaultGhcVersion globalDBs <- sequence [getGlobalPackageDB Nothing (Just ghcVersion), Just <$> getStorePackageDB ghcVersion] >>= filterM doesDirectoryExist . catMaybes nub . (PackageDBs Nothing Nothing globalDBs:) <$> forM projects (getPackageDBs' ghcVersion . Just) figureOutHaddockOpts :: Maybe ProjectKey -> FilePath -> IO [Text] figureOutHaddockOpts mbProject package = do (!output,_) <- runProjectTool mbProject "cabal" ["v1-haddock", "--with-haddock=leksahecho", "--executables"] (Just $ dropFileName package) Nothing let opts = concat [words $ T.unpack l | ToolOutput l <- output] let res = filterOptGhc opts debugM "leksah-server" ("figureOutHaddockOpts " ++ show res) output `deepseq` return $ map T.pack res where filterOptGhc :: [String] -> [String] filterOptGhc [] = [] filterOptGhc (s:r) = case stripPrefix "--optghc=" s of Nothing -> filterOptGhc r Just s' -> s' : filterOptGhc r figureOutGhcOpts :: Maybe ProjectKey -> FilePath -> IO [Text] figureOutGhcOpts mbProject package = do debugM "leksah-server" "figureOutGhcOpts" ghcVersion <- getDefaultGhcVersion packageDBs <- liftIO $ getPackageDBs' ghcVersion mbProject flags <- if takeBaseName package == "base" then do libDir <- getSysLibDir mbProject Nothing return $ ["-finteger-gmp", "-finteger-gmp2"] ++ maybeToList ((\l -> T.pack $ "--configure-option=CFLAGS=-I" <> l </> "include") <$> libDir) else return [] (!output,_) <- runProjectTool mbProject "cabal" ("v1-configure" : flags <> map (("--package-db=" <>) . T.pack) (pDBsPaths packageDBs)) (Just $ dropFileName package) Nothing output `deepseq` figureOutGhcOpts' mbProject package figureOutGhcOpts' :: Maybe ProjectKey -> FilePath -> IO [Text] figureOutGhcOpts' mbProject package = do debugM "leksah-server" "figureOutGhcOpts'" cabalOrSetup <- case mbProject of Nothing -> doesFileExist (takeDirectory package </> "Setup") >>= \case True -> return "./Setup" False -> return "cabal" _ -> return "cabal" (!output,_) <- runProjectTool mbProject cabalOrSetup ["v1-build","--with-ghc=leksahecho","--with-ghcjs=leksahecho"] (Just $ dropFileName package) Nothing let res = case catMaybes [findMake $ T.unpack l | ToolOutput l <- output] of options:_ -> words options _ -> [] debugM "leksah-server" ("figureOutGhcOpts " ++ show res) output `deepseq` return $ map T.pack res where findMake :: String -> Maybe String findMake [] = Nothing findMake line@(_:xs) = case stripPrefix "--make " line of Nothing -> findMake xs s -> s
leksah/leksah-server
src/IDE/Utils/FileUtils.hs
gpl-2.0
32,029
0
31
8,434
8,531
4,323
4,208
600
6
{-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-deprecations #-} {- Copyright (C) 2006-2010 John MacFarlane <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -} {- | Module : Text.Pandoc.Writers.HTML Copyright : Copyright (C) 2006-2010 John MacFarlane License : GNU GPL, version 2 or above Maintainer : John MacFarlane <[email protected]> Stability : alpha Portability : portable Conversion of 'Pandoc' documents to HTML. -} module Text.Pandoc.Writers.HTML ( writeHtml , writeHtmlString ) where import Text.Pandoc.Definition import Text.Pandoc.Shared import Text.Pandoc.Templates import Text.Pandoc.Generic import Text.Pandoc.Readers.TeXMath import Text.Pandoc.Slides import Text.Pandoc.Highlighting ( highlight, styleToCss, formatHtmlInline, formatHtmlBlock ) import Text.Pandoc.XML (stripTags, escapeStringForXML, fromEntities) import Network.HTTP ( urlEncode ) import Numeric ( showHex ) import Data.Char ( ord, toLower ) import Data.List ( isPrefixOf, intersperse ) import Data.String ( fromString ) import Data.Maybe ( catMaybes ) import Control.Monad.State import Text.Blaze import qualified Text.Blaze.Html5 as H5 import qualified Text.Blaze.XHtml1.Transitional as H import qualified Text.Blaze.XHtml1.Transitional.Attributes as A import Text.Blaze.Renderer.String (renderHtml) import Text.TeXMath import Text.XML.Light.Output import System.FilePath (takeExtension) import Data.Monoid (mempty, mconcat) data WriterState = WriterState { stNotes :: [Html] -- ^ List of notes , stMath :: Bool -- ^ Math is used in document , stQuotes :: Bool -- ^ <q> tag is used , stHighlighting :: Bool -- ^ Syntax highlighting is used , stSecNum :: [Int] -- ^ Number of current section } defaultWriterState :: WriterState defaultWriterState = WriterState {stNotes= [], stMath = False, stQuotes = False, stHighlighting = False, stSecNum = []} -- Helpers to render HTML with the appropriate function. strToHtml :: String -> Html strToHtml = preEscapedString . escapeStringForXML -- strToHtml = toHtml -- | Hard linebreak. nl :: WriterOptions -> Html nl opts = if writerWrapText opts then preEscapedString "\n" else mempty -- | Convert Pandoc document to Html string. writeHtmlString :: WriterOptions -> Pandoc -> String writeHtmlString opts d = let (tit, auths, authsMeta, date, toc, body', newvars) = evalState (pandocToHtml opts d) defaultWriterState in if writerStandalone opts then inTemplate opts tit auths authsMeta date toc body' newvars else renderHtml body' -- | Convert Pandoc document to Html structure. writeHtml :: WriterOptions -> Pandoc -> Html writeHtml opts d = let (tit, auths, authsMeta, date, toc, body', newvars) = evalState (pandocToHtml opts d) defaultWriterState in if writerStandalone opts then inTemplate opts tit auths authsMeta date toc body' newvars else body' -- result is (title, authors, date, toc, body, new variables) pandocToHtml :: WriterOptions -> Pandoc -> State WriterState (Html, [Html], [Html], Html, Maybe Html, Html, [(String,String)]) pandocToHtml opts (Pandoc (Meta title' authors' date') blocks) = do let standalone = writerStandalone opts tit <- if standalone then inlineListToHtml opts title' else return mempty auths <- if standalone then mapM (inlineListToHtml opts) authors' else return [] authsMeta <- if standalone then mapM (inlineListToHtml opts . prepForMeta) authors' else return [] date <- if standalone then inlineListToHtml opts date' else return mempty let slideLevel = maybe (getSlideLevel blocks) id $ writerSlideLevel opts let sects = hierarchicalize $ if writerSlideVariant opts == NoSlides then blocks else prepSlides slideLevel blocks toc <- if writerTableOfContents opts then tableOfContents opts sects else return Nothing blocks' <- liftM (mconcat . intersperse (nl opts)) $ mapM (elementToHtml slideLevel opts) sects st <- get let notes = reverse (stNotes st) let thebody = blocks' >> footnoteSection opts notes let math = if stMath st then case writerHTMLMathMethod opts of LaTeXMathML (Just url) -> H.script ! A.src (toValue url) ! A.type_ "text/javascript" $ mempty MathML (Just url) -> H.script ! A.src (toValue url) ! A.type_ "text/javascript" $ mempty MathJax url -> H.script ! A.src (toValue url) ! A.type_ "text/javascript" $ mempty JsMath (Just url) -> H.script ! A.src (toValue url) ! A.type_ "text/javascript" $ mempty _ -> case lookup "mathml-script" (writerVariables opts) of Just s | not (writerHtml5 opts) -> H.script ! A.type_ "text/javascript" $ preEscapedString ("/*<![CDATA[*/\n" ++ s ++ "/*]]>*/\n") | otherwise -> mempty Nothing -> mempty else mempty let newvars = [("highlighting-css", styleToCss $ writerHighlightStyle opts) | stHighlighting st] ++ [("math", renderHtml math) | stMath st] ++ [("quotes", "yes") | stQuotes st] return (tit, auths, authsMeta, date, toc, thebody, newvars) -- | Prepare author for meta tag, converting notes into -- bracketed text and removing links. prepForMeta :: [Inline] -> [Inline] prepForMeta = bottomUp (concatMap fixInline) where fixInline (Note [Para xs]) = [Str " ["] ++ xs ++ [Str "]"] fixInline (Note [Plain xs]) = [Str " ["] ++ xs ++ [Str "]"] fixInline (Link lab _) = lab fixInline (Image lab _) = lab fixInline x = [x] inTemplate :: TemplateTarget a => WriterOptions -> Html -> [Html] -> [Html] -> Html -> Maybe Html -> Html -> [(String,String)] -> a inTemplate opts tit auths authsMeta date toc body' newvars = let title' = renderHtml tit date' = renderHtml date dateMeta = maybe [] (\x -> [("date-meta",x)]) $ normalizeDate date' variables = writerVariables opts ++ newvars context = variables ++ dateMeta ++ [ ("body", dropWhile (=='\n') $ renderHtml body') , ("pagetitle", stripTags title') , ("title", title') , ("date", date') , ("idprefix", writerIdentifierPrefix opts) , ("slidy-url", "http://www.w3.org/Talks/Tools/Slidy2") , ("s5-url", "s5/default") ] ++ [ ("html5","true") | writerHtml5 opts ] ++ (case toc of Just t -> [ ("toc", renderHtml t)] Nothing -> []) ++ [ ("author", renderHtml a) | a <- auths ] ++ [ ("author-meta", stripTags $ renderHtml a) | a <- authsMeta ] in renderTemplate context $ writerTemplate opts -- | Like Text.XHtml's identifier, but adds the writerIdentifierPrefix prefixedId :: WriterOptions -> String -> Attribute prefixedId opts s = A.id $ toValue $ writerIdentifierPrefix opts ++ s -- | Replacement for Text.XHtml's unordList. unordList :: WriterOptions -> ([Html] -> Html) unordList opts items = H.ul $ mconcat $ toListItems opts items -- | Replacement for Text.XHtml's ordList. ordList :: WriterOptions -> ([Html] -> Html) ordList opts items = H.ol $ mconcat $ toListItems opts items -- | Construct table of contents from list of elements. tableOfContents :: WriterOptions -> [Element] -> State WriterState (Maybe Html) tableOfContents _ [] = return Nothing tableOfContents opts sects = do let opts' = opts { writerIgnoreNotes = True } contents <- mapM (elementToListItem opts') sects let tocList = catMaybes contents return $ if null tocList then Nothing else Just $ unordList opts tocList -- | Convert section number to string showSecNum :: [Int] -> String showSecNum = concat . intersperse "." . map show -- | Converts an Element to a list item for a table of contents, -- retrieving the appropriate identifier from state. elementToListItem :: WriterOptions -> Element -> State WriterState (Maybe Html) elementToListItem _ (Blk _) = return Nothing elementToListItem opts (Sec _ num id' headerText subsecs) = do let sectnum = if writerNumberSections opts then (H.span ! A.class_ "toc-section-number" $ toHtml $ showSecNum num) >> preEscapedString " " else mempty txt <- liftM (sectnum >>) $ inlineListToHtml opts headerText subHeads <- mapM (elementToListItem opts) subsecs >>= return . catMaybes let subList = if null subHeads then mempty else unordList opts subHeads return $ Just $ (H.a ! A.href (toValue $ "#" ++ writerIdentifierPrefix opts ++ id') $ toHtml txt) >> subList -- | Convert an Element to Html. elementToHtml :: Int -> WriterOptions -> Element -> State WriterState Html elementToHtml _slideLevel opts (Blk block) = blockToHtml opts block elementToHtml slideLevel opts (Sec level num id' title' elements) = do let slide = writerSlideVariant opts /= NoSlides && level <= slideLevel modify $ \st -> st{stSecNum = num} -- update section number -- always use level 1 for slide titles let level' = if slide then 1 else level let titleSlide = slide && level < slideLevel header' <- blockToHtml opts (Header level' title') let isSec (Sec _ _ _ _ _) = True isSec (Blk _) = False innerContents <- mapM (elementToHtml slideLevel opts) $ if titleSlide -- title slides have no content of their own then filter isSec elements else elements let header'' = if (writerStrictMarkdown opts || writerSectionDivs opts || writerSlideVariant opts == S5Slides || slide) then header' else header' ! prefixedId opts id' let inNl x = mconcat $ nl opts : intersperse (nl opts) x ++ [nl opts] let classes = ["titleslide" | titleSlide] ++ ["slide" | slide] ++ ["level" ++ show level] let secttag = if writerHtml5 opts then H5.section ! A.class_ (toValue $ unwords classes) else H.div ! A.class_ (toValue $ unwords ("section":classes)) return $ if titleSlide then mconcat $ (secttag ! prefixedId opts id' $ header'') : innerContents else if writerSectionDivs opts || slide then secttag ! prefixedId opts id' $ inNl $ header'' : innerContents else mconcat $ intersperse (nl opts) $ header'' : innerContents -- | Convert list of Note blocks to a footnote <div>. -- Assumes notes are sorted. footnoteSection :: WriterOptions -> [Html] -> Html footnoteSection opts notes = if null notes then mempty else nl opts >> (container $ nl opts >> hrtag >> nl opts >> H.ol (mconcat notes >> nl opts) >> nl opts) where container x = if writerHtml5 opts then H5.section ! A.class_ "footnotes" $ x else if writerSlideVariant opts /= NoSlides then H.div ! A.class_ "footnotes slide" $ x else H.div ! A.class_ "footnotes" $ x hrtag = if writerHtml5 opts then H5.hr else H.hr -- | Parse a mailto link; return Just (name, domain) or Nothing. parseMailto :: String -> Maybe (String, String) parseMailto ('m':'a':'i':'l':'t':'o':':':addr) = let (name', rest) = span (/='@') addr domain = drop 1 rest in Just (name', domain) parseMailto _ = Nothing -- | Obfuscate a "mailto:" link. obfuscateLink :: WriterOptions -> String -> String -> Html obfuscateLink opts txt s | writerEmailObfuscation opts == NoObfuscation = H.a ! A.href (toValue s) $ toHtml txt obfuscateLink opts txt s = let meth = writerEmailObfuscation opts s' = map toLower s in case parseMailto s' of (Just (name', domain)) -> let domain' = substitute "." " dot " domain at' = obfuscateChar '@' (linkText, altText) = if txt == drop 7 s' -- autolink then ("'<code>'+e+'</code>'", name' ++ " at " ++ domain') else ("'" ++ txt ++ "'", txt ++ " (" ++ name' ++ " at " ++ domain' ++ ")") in case meth of ReferenceObfuscation -> -- need to use preEscapedString or &'s are escaped to &amp; in URL preEscapedString $ "<a href=\"" ++ (obfuscateString s') ++ "\">" ++ (obfuscateString txt) ++ "</a>" JavascriptObfuscation -> (H.script ! A.type_ "text/javascript" $ preEscapedString ("\n<!--\nh='" ++ obfuscateString domain ++ "';a='" ++ at' ++ "';n='" ++ obfuscateString name' ++ "';e=n+a+h;\n" ++ "document.write('<a h'+'ref'+'=\"ma'+'ilto'+':'+e+'\">'+" ++ linkText ++ "+'<\\/'+'a'+'>');\n// -->\n")) >> H.noscript (preEscapedString $ obfuscateString altText) _ -> error $ "Unknown obfuscation method: " ++ show meth _ -> H.a ! A.href (toValue s) $ toHtml txt -- malformed email -- | Obfuscate character as entity. obfuscateChar :: Char -> String obfuscateChar char = let num = ord char numstr = if even num then show num else "x" ++ showHex num "" in "&#" ++ numstr ++ ";" -- | Obfuscate string using entities. obfuscateString :: String -> String obfuscateString = concatMap obfuscateChar . fromEntities attrsToHtml :: WriterOptions -> Attr -> [Attribute] attrsToHtml opts (id',classes',keyvals) = [A.class_ (toValue $ unwords classes') | not (null classes')] ++ [prefixedId opts id' | not (null id')] ++ map (\(x,y) -> customAttribute (fromString x) (toValue y)) keyvals imageExts :: [String] imageExts = [ "art", "bmp", "cdr", "cdt", "cpt", "cr2", "crw", "djvu", "erf", "gif", "ico", "ief", "jng", "jpg", "jpeg", "nef", "orf", "pat", "pbm", "pcx", "pgm", "png", "pnm", "ppm", "psd", "ras", "rgb", "svg", "tiff", "wbmp", "xbm", "xpm", "xwd" ] treatAsImage :: FilePath -> Bool treatAsImage fp = let ext = map toLower $ drop 1 $ takeExtension fp in null ext || ext `elem` imageExts -- | Convert Pandoc block element to HTML. blockToHtml :: WriterOptions -> Block -> State WriterState Html blockToHtml _ Null = return mempty blockToHtml opts (Plain lst) = inlineListToHtml opts lst blockToHtml opts (Para [Image txt (s,tit)]) = do img <- inlineToHtml opts (Image txt (s,tit)) capt <- inlineListToHtml opts txt return $ if writerHtml5 opts then H5.figure $ mconcat [nl opts, img, H5.figcaption capt, nl opts] else H.div ! A.class_ "figure" $ mconcat [nl opts, img, H.p ! A.class_ "caption" $ capt, nl opts] blockToHtml opts (Para lst) = do contents <- inlineListToHtml opts lst return $ H.p contents blockToHtml _ (RawBlock "html" str) = return $ preEscapedString str blockToHtml _ (RawBlock _ _) = return mempty blockToHtml opts (HorizontalRule) = return $ if writerHtml5 opts then H5.hr else H.hr blockToHtml opts (CodeBlock (id',classes,keyvals) rawCode) = do let tolhs = writerLiterateHaskell opts && any (\c -> map toLower c == "haskell") classes && any (\c -> map toLower c == "literate") classes classes' = if tolhs then map (\c -> if map toLower c == "haskell" then "literatehaskell" else c) classes else filter (/= "literate") classes adjCode = if tolhs then unlines . map ("> " ++) . lines $ rawCode else rawCode case highlight formatHtmlBlock (id',classes,keyvals) adjCode of Nothing -> let attrs = attrsToHtml opts (id', classes', keyvals) in return $ foldl (!) H.pre attrs $ H.code $ toHtml adjCode Just h -> modify (\st -> st{ stHighlighting = True }) >> return (foldl (!) h (attrsToHtml opts (id',[],keyvals))) blockToHtml opts (BlockQuote blocks) = -- in S5, treat list in blockquote specially -- if default is incremental, make it nonincremental; -- otherwise incremental if writerSlideVariant opts /= NoSlides then let inc = not (writerIncremental opts) in case blocks of [BulletList lst] -> blockToHtml (opts {writerIncremental = inc}) (BulletList lst) [OrderedList attribs lst] -> blockToHtml (opts {writerIncremental = inc}) (OrderedList attribs lst) _ -> do contents <- blockListToHtml opts blocks return $ H.blockquote $ nl opts >> contents >> nl opts else do contents <- blockListToHtml opts blocks return $ H.blockquote $ nl opts >> contents >> nl opts blockToHtml opts (Header level lst) = do contents <- inlineListToHtml opts lst secnum <- liftM stSecNum get let contents' = if writerNumberSections opts then (H.span ! A.class_ "header-section-number" $ toHtml $ showSecNum secnum) >> strToHtml " " >> contents else contents let contents'' = if writerTableOfContents opts then H.a ! A.href (toValue $ "#" ++ writerIdentifierPrefix opts ++ "TOC") $ contents' else contents' return $ (case level of 1 -> H.h1 contents'' 2 -> H.h2 contents'' 3 -> H.h3 contents'' 4 -> H.h4 contents'' 5 -> H.h5 contents'' 6 -> H.h6 contents'' _ -> H.p contents'') blockToHtml opts (BulletList lst) = do contents <- mapM (blockListToHtml opts) lst let lst' = unordList opts contents let lst'' = if writerIncremental opts then lst' ! A.class_ "incremental" else lst' return lst'' blockToHtml opts (OrderedList (startnum, numstyle, _) lst) = do contents <- mapM (blockListToHtml opts) lst let numstyle' = camelCaseToHyphenated $ show numstyle let attribs = (if writerIncremental opts then [A.class_ "incremental"] else []) ++ (if startnum /= 1 then [A.start $ toValue startnum] else []) ++ (if numstyle /= DefaultStyle then if writerHtml5 opts then [A.type_ $ case numstyle of Decimal -> "1" LowerAlpha -> "a" UpperAlpha -> "A" LowerRoman -> "i" UpperRoman -> "I" _ -> "1"] else [A.style $ toValue $ "list-style-type: " ++ numstyle'] else []) return $ foldl (!) (ordList opts contents) attribs blockToHtml opts (DefinitionList lst) = do contents <- mapM (\(term, defs) -> do term' <- liftM (H.dt) $ inlineListToHtml opts term defs' <- mapM ((liftM (\x -> H.dd $ (x >> nl opts))) . blockListToHtml opts) defs return $ mconcat $ nl opts : term' : nl opts : defs') lst let lst' = H.dl $ mconcat contents >> nl opts let lst'' = if writerIncremental opts then lst' ! A.class_ "incremental" else lst' return lst'' blockToHtml opts (Table capt aligns widths headers rows') = do captionDoc <- if null capt then return mempty else do cs <- inlineListToHtml opts capt return $ H.caption cs >> nl opts let percent w = show (truncate (100*w) :: Integer) ++ "%" let coltags = if all (== 0.0) widths then mempty else mconcat $ map (\w -> if writerHtml5 opts then H.col ! A.style (toValue $ "width: " ++ percent w) else H.col ! A.width (toValue $ percent w) >> nl opts) widths head' <- if all null headers then return mempty else do contents <- tableRowToHtml opts aligns 0 headers return $ H.thead (nl opts >> contents) >> nl opts body' <- liftM (\x -> H.tbody (nl opts >> mconcat x)) $ zipWithM (tableRowToHtml opts aligns) [1..] rows' return $ H.table $ nl opts >> captionDoc >> coltags >> head' >> body' >> nl opts tableRowToHtml :: WriterOptions -> [Alignment] -> Int -> [[Block]] -> State WriterState Html tableRowToHtml opts aligns rownum cols' = do let mkcell = if rownum == 0 then H.th else H.td let rowclass = case rownum of 0 -> "header" x | x `rem` 2 == 1 -> "odd" _ -> "even" cols'' <- sequence $ zipWith (\alignment item -> tableItemToHtml opts mkcell alignment item) aligns cols' return $ (H.tr ! A.class_ rowclass $ nl opts >> mconcat cols'') >> nl opts alignmentToString :: Alignment -> [Char] alignmentToString alignment = case alignment of AlignLeft -> "left" AlignRight -> "right" AlignCenter -> "center" AlignDefault -> "left" tableItemToHtml :: WriterOptions -> (Html -> Html) -> Alignment -> [Block] -> State WriterState Html tableItemToHtml opts tag' align' item = do contents <- blockListToHtml opts item let alignStr = alignmentToString align' let attribs = if writerHtml5 opts then A.style (toValue $ "text-align: " ++ alignStr ++ ";") else A.align (toValue alignStr) return $ (tag' ! attribs $ contents) >> nl opts toListItems :: WriterOptions -> [Html] -> [Html] toListItems opts items = map (toListItem opts) items ++ [nl opts] toListItem :: WriterOptions -> Html -> Html toListItem opts item = nl opts >> H.li item blockListToHtml :: WriterOptions -> [Block] -> State WriterState Html blockListToHtml opts lst = mapM (blockToHtml opts) lst >>= return . mconcat . intersperse (nl opts) -- | Convert list of Pandoc inline elements to HTML. inlineListToHtml :: WriterOptions -> [Inline] -> State WriterState Html inlineListToHtml opts lst = mapM (inlineToHtml opts) lst >>= return . mconcat -- | Convert Pandoc inline element to HTML. inlineToHtml :: WriterOptions -> Inline -> State WriterState Html inlineToHtml opts inline = case inline of (Str str) -> return $ strToHtml str (Space) -> return $ strToHtml " " (LineBreak) -> return $ if writerHtml5 opts then H5.br else H.br (Emph lst) -> inlineListToHtml opts lst >>= return . H.em (Strong lst) -> inlineListToHtml opts lst >>= return . H.strong (Code attr str) -> case highlight formatHtmlInline attr str of Nothing -> return $ foldl (!) H.code (attrsToHtml opts attr) $ strToHtml str Just h -> return $ foldl (!) h $ attrsToHtml opts (id',[],keyvals) where (id',_,keyvals) = attr (Strikeout lst) -> inlineListToHtml opts lst >>= return . H.del (SmallCaps lst) -> inlineListToHtml opts lst >>= return . (H.span ! A.style "font-variant: small-caps;") (Superscript lst) -> inlineListToHtml opts lst >>= return . H.sup (Subscript lst) -> inlineListToHtml opts lst >>= return . H.sub (Quoted quoteType lst) -> let (leftQuote, rightQuote) = case quoteType of SingleQuote -> (strToHtml "‘", strToHtml "’") DoubleQuote -> (strToHtml "“", strToHtml "”") in if writerHtml5 opts then do modify $ \st -> st{ stQuotes = True } H.q `fmap` inlineListToHtml opts lst else (\x -> leftQuote >> x >> rightQuote) `fmap` inlineListToHtml opts lst (Math t str) -> modify (\st -> st {stMath = True}) >> (case writerHTMLMathMethod opts of LaTeXMathML _ -> -- putting LaTeXMathML in container with class "LaTeX" prevents -- non-math elements on the page from being treated as math by -- the javascript return $ H.span ! A.class_ "LaTeX" $ case t of InlineMath -> toHtml ("$" ++ str ++ "$") DisplayMath -> toHtml ("$$" ++ str ++ "$$") JsMath _ -> do let m = preEscapedString str return $ case t of InlineMath -> H.span ! A.class_ "math" $ m DisplayMath -> H.div ! A.class_ "math" $ m WebTeX url -> do let imtag = if writerHtml5 opts then H5.img else H.img let m = imtag ! A.style "vertical-align:middle" ! A.src (toValue $ url ++ urlEncode str) ! A.alt (toValue str) ! A.title (toValue str) let brtag = if writerHtml5 opts then H5.br else H.br return $ case t of InlineMath -> m DisplayMath -> brtag >> m >> brtag GladTeX -> return $ case t of InlineMath -> preEscapedString $ "<EQ ENV=\"math\">" ++ str ++ "</EQ>" DisplayMath -> preEscapedString $ "<EQ ENV=\"displaymath\">" ++ str ++ "</EQ>" MathML _ -> do let dt = if t == InlineMath then DisplayInline else DisplayBlock let conf = useShortEmptyTags (const False) defaultConfigPP case texMathToMathML dt str of Right r -> return $ preEscapedString $ ppcElement conf r Left _ -> inlineListToHtml opts (readTeXMath str) >>= return . (H.span ! A.class_ "math") MathJax _ -> return $ toHtml $ case t of InlineMath -> "\\(" ++ str ++ "\\)" DisplayMath -> "\\[" ++ str ++ "\\]" PlainMath -> do x <- inlineListToHtml opts (readTeXMath str) let m = H.span ! A.class_ "math" $ x let brtag = if writerHtml5 opts then H5.br else H.br return $ case t of InlineMath -> m DisplayMath -> brtag >> m >> brtag ) (RawInline "latex" str) -> case writerHTMLMathMethod opts of LaTeXMathML _ -> do modify (\st -> st {stMath = True}) return $ toHtml str _ -> return mempty (RawInline "html" str) -> return $ preEscapedString str (RawInline _ _) -> return mempty (Link [Code _ str] (s,_)) | "mailto:" `isPrefixOf` s -> return $ obfuscateLink opts str s (Link txt (s,_)) | "mailto:" `isPrefixOf` s -> do linkText <- inlineListToHtml opts txt return $ obfuscateLink opts (renderHtml linkText) s (Link txt (s,tit)) -> do linkText <- inlineListToHtml opts txt let link = H.a ! A.href (toValue s) $ linkText return $ if null tit then link else link ! A.title (toValue tit) (Image txt (s,tit)) | treatAsImage s -> do let alternate' = stringify txt let attributes = [A.src $ toValue s] ++ (if null tit then [] else [A.title $ toValue tit]) ++ if null txt then [] else [A.alt $ toValue alternate'] let tag = if writerHtml5 opts then H5.img else H.img return $ foldl (!) tag attributes -- note: null title included, as in Markdown.pl (Image _ (s,tit)) -> do let attributes = [A.src $ toValue s] ++ (if null tit then [] else [A.title $ toValue tit]) return $ foldl (!) H5.embed attributes -- note: null title included, as in Markdown.pl (Note contents) -> do st <- get let notes = stNotes st let number = (length notes) + 1 let ref = show number htmlContents <- blockListToNote opts ref contents -- push contents onto front of notes put $ st {stNotes = (htmlContents:notes)} return $ H.sup $ H.a ! A.href (toValue $ "#" ++ writerIdentifierPrefix opts ++ "fn" ++ ref) ! A.class_ "footnoteRef" ! prefixedId opts ("fnref" ++ ref) $ toHtml ref (Cite _ il) -> do contents <- inlineListToHtml opts il return $ H.span ! A.class_ "citation" $ contents blockListToNote :: WriterOptions -> String -> [Block] -> State WriterState Html blockListToNote opts ref blocks = -- If last block is Para or Plain, include the backlink at the end of -- that block. Otherwise, insert a new Plain block with the backlink. let backlink = [Link [Str "↩"] ("#" ++ writerIdentifierPrefix opts ++ "fnref" ++ ref,[])] blocks' = if null blocks then [] else let lastBlock = last blocks otherBlocks = init blocks in case lastBlock of (Para lst) -> otherBlocks ++ [Para (lst ++ backlink)] (Plain lst) -> otherBlocks ++ [Plain (lst ++ backlink)] _ -> otherBlocks ++ [lastBlock, Plain backlink] in do contents <- blockListToHtml opts blocks' return $ nl opts >> (H.li ! (prefixedId opts ("fn" ++ ref)) $ contents)
castaway/pandoc
src/Text/Pandoc/Writers/HTML.hs
gpl-2.0
35,018
0
29
14,050
9,017
4,569
4,448
609
49
-- | Modified from / based on: -- https://github.com/kig/tomtegebra/blob/master/Tomtegebra/Matrix.hs {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE FlexibleInstances #-} {-# OPTIONS_GHC -fno-warn-orphans #-} {-# LANGUAGE PatternSynonyms #-} module GLMatrix ( translationMatrix, frustumMatrix, identityMatrix, toGLFormat, withMatrix, matrixMulVec, matrix4x4To3x3, matrix3x3To4x4, invertMatrix4x4ON, scalingMatrix, rotationMatrix, lookAtMatrixG, orthoMatrix, perspectiveMatrix, addVec, setMatrix4x4Uniform, Matrix4x4, Matrix3x3, Vector4, Vector3 ) where import Data.List (transpose) import Foreign (Ptr) import Foreign.C (withCString) import Foreign.Marshal.Array (withArray) import Graphics.GL (GLfloat, GLuint, glGetUniformLocation, glUniformMatrix4fv, pattern GL_FALSE) -- | 4x4 Matrix in the OpenGL orientation: -- translation column is the last 4 elements. type Matrix4x4 = [[GLfloat]] -- | 3x3 Matrix in the OpenGL orientation. type Matrix3x3 = [[GLfloat]] -- | Four element GLfloat vector. type Vector4 = [GLfloat] -- | Three element GLfloat vector. type Vector3 = [GLfloat] instance Num Matrix4x4 where a * b = map (\row -> map (dotVec row) at) b where at = transpose a a + b = applyToIndices2 a b (+) abs = map (map abs) fromInteger i = [ [fromInteger i, 0, 0, 0], [0, fromInteger i, 0, 0], [0, 0, fromInteger i, 0], [0, 0, 0, fromInteger i] ] signum = map (map signum) setMatrix4x4Uniform :: GLuint -> Matrix4x4 -> String -> IO () setMatrix4x4Uniform shader matrix var = do loc <- withCString var $ glGetUniformLocation shader withMatrix matrix (glUniformMatrix4fv loc 1 GL_FALSE) withMatrix :: Matrix4x4 -> (Ptr GLfloat -> IO a) -> IO a withMatrix = withArray . toGLFormat applyToIndices2 :: [[a]] -> [[b]] -> (a -> b -> c) -> [[c]] applyToIndices2 (a:as) (b:bs) f = applyToIndices a b f : applyToIndices2 as bs f applyToIndices2 _ _ _ = [] applyToIndices :: [a] -> [b] -> (a -> b -> c) -> [c] applyToIndices (a:as) (b:bs) f = f a b : applyToIndices as bs f applyToIndices _ _ _ = [] toGLFormat :: Matrix4x4 -> [GLfloat] toGLFormat = concat {-# INLINE toGLFormat #-} -- | The 'Matrix4x4' identity matrix. identityMatrix :: Matrix4x4 identityMatrix = [ [1,0,0,0], [0,1,0,0], [0,0,1,0], [0,0,0,1] ] {-# INLINE identityMatrix #-} -- | Multiplies a vector by a matrix. matrixMulVec :: Matrix4x4 -> Vector4 -> Vector4 matrixMulVec m v = map (dotVec v) (transpose m) {-# INLINE matrixMulVec #-} -- | Returns the upper-left 3x3 matrix of a 4x4 matrix. matrix4x4To3x3 :: Matrix4x4 -> Matrix3x3 matrix4x4To3x3 m = take 3 $ map vec4To3 m -- | Pads the 3x3 matrix to a 4x4 matrix with a 1 in -- bottom right corner and 0 elsewhere. matrix3x3To4x4 :: Matrix3x3 -> Matrix4x4 matrix3x3To4x4 [x,y,z] = [x ++ [0], y ++ [0], z ++ [0], [0,0,0,1]] matrix3x3To4x4 m = m {-# INLINE matrix3x3To4x4 #-} -- | Inverts a 4x4 orthonormal matrix with the special case trick. invertMatrix4x4ON :: Matrix4x4 -> Matrix4x4 invertMatrix4x4ON m = -- orthonormal matrix inverse let [a,b,c] = transpose $ matrix4x4To3x3 m [_,_,_,t4] = m t = vec4To3 t4 in [ vec3To4 a 0, vec3To4 b 0, vec3To4 c 0, [dotVec a t, dotVec b t, dotVec c t, t4 !! 3] ] -- | Creates the translation matrix that translates points by the given vector. translationMatrix :: Vector3 -> Matrix4x4 translationMatrix [x,y,z] = [[1,0,0,0], [0,1,0,0], [0,0,1,0], [x,y,z,1]] translationMatrix _ = identityMatrix {-# INLINE translationMatrix #-} -- | Creates the scaling matrix that scales points by the factors given by the -- vector components. scalingMatrix :: Vector3 -> Matrix4x4 scalingMatrix [x,y,z] = [[x,0,0,0], [0,y,0,0], [0,0,z,0], [0,0,0,1]] scalingMatrix _ = identityMatrix {-# INLINE scalingMatrix #-} rotationMatrix :: GLfloat -> Vector3 -> Matrix4x4 rotationMatrix angle axis = let [x,y,z] = normalizeVec axis c = cos angle s = sin angle c1 = 1-c in [ [x*x*c1+c, y*x*c1+z*s, z*x*c1-y*s, 0], [x*y*c1-z*s, y*y*c1+c, y*z*c1+x*s, 0], [x*z*c1+y*s, y*z*c1-x*s, z*z*c1+c, 0], [0,0,0,1] ] {-# INLINE rotationMatrix #-} -- | Creates a lookAt matrix from three vectors: the eye position, the point the -- eye is looking at and the up vector of the eye. lookAtMatrixG :: Vector3 -> Vector3 -> Vector3 -> Matrix4x4 lookAtMatrixG eye center up = let z = directionVec eye center x = normalizeVec $ crossVec3 up z y = normalizeVec $ crossVec3 z x in matrix3x3To4x4 (transpose [x,y,z]) * translationMatrix (negateVec eye) {-# INLINE lookAtMatrixG #-} -- | Creates a frustumMatrix from the given -- left, right, bottom, top, znear and zfar -- values for the view frustum. frustumMatrix :: GLfloat -> GLfloat -> GLfloat -> GLfloat -> GLfloat -> GLfloat -> Matrix4x4 frustumMatrix left right bottom top znear zfar = let x = 2*znear/(right-left) y = 2*znear/(top-bottom) a = (right+left)/(right-left) b = (top+bottom)/(top-bottom) c = -(zfar+znear)/(zfar-znear) d = -2*zfar*znear/(zfar-znear) in [[x, 0, 0, 0], [0, y, 0, 0], [a, b, c, -1], [0, 0, d, 0]] {-# INLINE frustumMatrix #-} orthoMatrix :: GLfloat -> GLfloat -> GLfloat -> GLfloat -> GLfloat -> GLfloat -> Matrix4x4 orthoMatrix l r b t n f = let ai = 2/(r-l) bi = 2/(t-b) ci = -2/(f-n) di = -(r+l)/(r-l) ei = -(t+b)/(t-b) fi = -(f+n)/(f-n) in [[ai, 0, 0, 0], [0, bi, 0, 0], [0, 0, ci, 0], [di, ei, fi, 1]] {-# INLINE orthoMatrix #-} -- | Creates a perspective projection matrix for the given field-of-view, -- screen aspect ratio, znear and zfar. perspectiveMatrix :: GLfloat -> GLfloat -> GLfloat -> GLfloat -> Matrix4x4 perspectiveMatrix fovy aspect znear zfar = let ymax = znear * tan (fovy * pi / 360.0) ymin = -ymax xmin = ymin * aspect xmax = ymax * aspect in frustumMatrix xmin xmax ymin ymax znear zfar {-# INLINE perspectiveMatrix #-} -- | Normalizes a vector to a unit vector. normalizeVec :: [GLfloat] -> [GLfloat] normalizeVec v = scaleVec (recip $ lengthVec v) v {-# INLINE normalizeVec #-} -- | Scales a vector by a scalar. scaleVec :: GLfloat -> [GLfloat] -> [GLfloat] scaleVec s = map (s*) {-# INLINE scaleVec #-} -- | Computes the length of a vector. lengthVec :: [GLfloat] -> GLfloat lengthVec v = sqrt.sum $ map square v {-# INLINE lengthVec #-} -- | Inner product of two vectors. innerVec :: [GLfloat] -> [GLfloat] -> [GLfloat] innerVec = zipWith (*) {-# INLINE innerVec #-} -- | Adds two vectors together. addVec :: [GLfloat] -> [GLfloat] -> [GLfloat] addVec = zipWith (+) {-# INLINE addVec #-} -- | Subtracts a vector from another. subVec :: [GLfloat] -> [GLfloat] -> [GLfloat] subVec = zipWith (-) {-# INLINE subVec #-} -- | Negates a vector. negateVec :: [GLfloat] -> [GLfloat] negateVec = map negate {-# INLINE negateVec #-} -- | Computes the direction unit vector between two vectors. directionVec :: [GLfloat] -> [GLfloat] -> [GLfloat] directionVec u v = normalizeVec (subVec u v) {-# INLINE directionVec #-} -- | Vector dot product. dotVec :: [GLfloat] -> [GLfloat] -> GLfloat dotVec a b = sum $ innerVec a b {-# INLINE dotVec #-} -- | Cross product of two 3-vectors. crossVec3 :: [GLfloat] -> [GLfloat] -> [GLfloat] crossVec3 [u0,u1,u2] [v0,v1,v2] = [u1*v2-u2*v1, u2*v0-u0*v2, u0*v1-u1*v0] crossVec3 _ _ = [0,0,1] {-# INLINE crossVec3 #-} -- | Converts a 4-vector into a 3-vector by dropping the fourth element. vec4To3 :: Vector4 -> Vector3 vec4To3 = take 3 {-# INLINE vec4To3 #-} -- | Converts a 3-vector into a 4-vector by appending the given value to it. vec3To4 :: Vector3 -> GLfloat -> Vector4 vec3To4 v i = v ++ [i] {-# INLINE vec3To4 #-} -- | Multiplies a GLfloat by itself. square :: GLfloat -> GLfloat square x = x * x {-# INLINE square #-}
jaredloomis/GLMatrix
GLMatrix.hs
gpl-3.0
8,068
0
13
1,820
2,718
1,548
1,170
191
1
flip :: (a -> b -> c) -> (b -> a -> c) flip f y x = f x y
hmemcpy/milewski-ctfp-pdf
src/content/1.8/code/haskell/snippet27.hs
gpl-3.0
57
0
8
20
49
25
24
2
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.FusionTables.Table.List -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Retrieves a list of tables a user owns. -- -- /See:/ <https://developers.google.com/fusiontables Fusion Tables API Reference> for @fusiontables.table.list@. module Network.Google.Resource.FusionTables.Table.List ( -- * REST Resource TableListResource -- * Creating a Request , tableList' , TableList' -- * Request Lenses , tPageToken , tMaxResults ) where import Network.Google.FusionTables.Types import Network.Google.Prelude -- | A resource alias for @fusiontables.table.list@ method which the -- 'TableList'' request conforms to. type TableListResource = "fusiontables" :> "v2" :> "tables" :> QueryParam "pageToken" Text :> QueryParam "maxResults" (Textual Word32) :> QueryParam "alt" AltJSON :> Get '[JSON] TableList -- | Retrieves a list of tables a user owns. -- -- /See:/ 'tableList'' smart constructor. data TableList' = TableList'' { _tPageToken :: !(Maybe Text) , _tMaxResults :: !(Maybe (Textual Word32)) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'TableList'' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'tPageToken' -- -- * 'tMaxResults' tableList' :: TableList' tableList' = TableList'' { _tPageToken = Nothing , _tMaxResults = Nothing } -- | Continuation token specifying which result page to return. tPageToken :: Lens' TableList' (Maybe Text) tPageToken = lens _tPageToken (\ s a -> s{_tPageToken = a}) -- | Maximum number of tables to return. Default is 5. tMaxResults :: Lens' TableList' (Maybe Word32) tMaxResults = lens _tMaxResults (\ s a -> s{_tMaxResults = a}) . mapping _Coerce instance GoogleRequest TableList' where type Rs TableList' = TableList type Scopes TableList' = '["https://www.googleapis.com/auth/fusiontables", "https://www.googleapis.com/auth/fusiontables.readonly"] requestClient TableList''{..} = go _tPageToken _tMaxResults (Just AltJSON) fusionTablesService where go = buildClient (Proxy :: Proxy TableListResource) mempty
rueshyna/gogol
gogol-fusiontables/gen/Network/Google/Resource/FusionTables/Table/List.hs
mpl-2.0
3,051
0
13
709
408
242
166
60
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} -- | -- Module : Network.Google.MapsEngine -- 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) -- -- The Google Maps Engine API allows developers to store and query -- geospatial vector and raster data. -- -- /See:/ <https://developers.google.com/maps-engine/ Google Maps Engine API Reference> module Network.Google.MapsEngine ( -- * Service Configuration mapsEngineService -- * OAuth Scopes , mapsEngineScope , mapsEngineReadOnlyScope -- * API Declaration , MapsEngineAPI -- * Resources -- ** mapsengine.assets.get , module Network.Google.Resource.MapsEngine.Assets.Get -- ** mapsengine.assets.list , module Network.Google.Resource.MapsEngine.Assets.List -- ** mapsengine.assets.parents.list , module Network.Google.Resource.MapsEngine.Assets.Parents.List -- ** mapsengine.assets.permissions.list , module Network.Google.Resource.MapsEngine.Assets.Permissions.List -- ** mapsengine.layers.cancelProcessing , module Network.Google.Resource.MapsEngine.Layers.CancelProcessing -- ** mapsengine.layers.create , module Network.Google.Resource.MapsEngine.Layers.Create -- ** mapsengine.layers.delete , module Network.Google.Resource.MapsEngine.Layers.Delete -- ** mapsengine.layers.get , module Network.Google.Resource.MapsEngine.Layers.Get -- ** mapsengine.layers.getPublished , module Network.Google.Resource.MapsEngine.Layers.GetPublished -- ** mapsengine.layers.list , module Network.Google.Resource.MapsEngine.Layers.List -- ** mapsengine.layers.listPublished , module Network.Google.Resource.MapsEngine.Layers.ListPublished -- ** mapsengine.layers.parents.list , module Network.Google.Resource.MapsEngine.Layers.Parents.List -- ** mapsengine.layers.patch , module Network.Google.Resource.MapsEngine.Layers.Patch -- ** mapsengine.layers.permissions.batchDelete , module Network.Google.Resource.MapsEngine.Layers.Permissions.BatchDelete -- ** mapsengine.layers.permissions.batchUpdate , module Network.Google.Resource.MapsEngine.Layers.Permissions.BatchUpdate -- ** mapsengine.layers.permissions.list , module Network.Google.Resource.MapsEngine.Layers.Permissions.List -- ** mapsengine.layers.process , module Network.Google.Resource.MapsEngine.Layers.Process -- ** mapsengine.layers.publish , module Network.Google.Resource.MapsEngine.Layers.Publish -- ** mapsengine.layers.unpublish , module Network.Google.Resource.MapsEngine.Layers.UnPublish -- ** mapsengine.maps.create , module Network.Google.Resource.MapsEngine.Maps.Create -- ** mapsengine.maps.delete , module Network.Google.Resource.MapsEngine.Maps.Delete -- ** mapsengine.maps.get , module Network.Google.Resource.MapsEngine.Maps.Get -- ** mapsengine.maps.getPublished , module Network.Google.Resource.MapsEngine.Maps.GetPublished -- ** mapsengine.maps.list , module Network.Google.Resource.MapsEngine.Maps.List -- ** mapsengine.maps.listPublished , module Network.Google.Resource.MapsEngine.Maps.ListPublished -- ** mapsengine.maps.patch , module Network.Google.Resource.MapsEngine.Maps.Patch -- ** mapsengine.maps.permissions.batchDelete , module Network.Google.Resource.MapsEngine.Maps.Permissions.BatchDelete -- ** mapsengine.maps.permissions.batchUpdate , module Network.Google.Resource.MapsEngine.Maps.Permissions.BatchUpdate -- ** mapsengine.maps.permissions.list , module Network.Google.Resource.MapsEngine.Maps.Permissions.List -- ** mapsengine.maps.publish , module Network.Google.Resource.MapsEngine.Maps.Publish -- ** mapsengine.maps.unpublish , module Network.Google.Resource.MapsEngine.Maps.UnPublish -- ** mapsengine.projects.icons.create , module Network.Google.Resource.MapsEngine.Projects.Icons.Create -- ** mapsengine.projects.icons.get , module Network.Google.Resource.MapsEngine.Projects.Icons.Get -- ** mapsengine.projects.icons.list , module Network.Google.Resource.MapsEngine.Projects.Icons.List -- ** mapsengine.projects.list , module Network.Google.Resource.MapsEngine.Projects.List -- ** mapsengine.rasterCollections.cancelProcessing , module Network.Google.Resource.MapsEngine.RasterCollections.CancelProcessing -- ** mapsengine.rasterCollections.create , module Network.Google.Resource.MapsEngine.RasterCollections.Create -- ** mapsengine.rasterCollections.delete , module Network.Google.Resource.MapsEngine.RasterCollections.Delete -- ** mapsengine.rasterCollections.get , module Network.Google.Resource.MapsEngine.RasterCollections.Get -- ** mapsengine.rasterCollections.list , module Network.Google.Resource.MapsEngine.RasterCollections.List -- ** mapsengine.rasterCollections.parents.list , module Network.Google.Resource.MapsEngine.RasterCollections.Parents.List -- ** mapsengine.rasterCollections.patch , module Network.Google.Resource.MapsEngine.RasterCollections.Patch -- ** mapsengine.rasterCollections.permissions.batchDelete , module Network.Google.Resource.MapsEngine.RasterCollections.Permissions.BatchDelete -- ** mapsengine.rasterCollections.permissions.batchUpdate , module Network.Google.Resource.MapsEngine.RasterCollections.Permissions.BatchUpdate -- ** mapsengine.rasterCollections.permissions.list , module Network.Google.Resource.MapsEngine.RasterCollections.Permissions.List -- ** mapsengine.rasterCollections.process , module Network.Google.Resource.MapsEngine.RasterCollections.Process -- ** mapsengine.rasterCollections.rasters.batchDelete , module Network.Google.Resource.MapsEngine.RasterCollections.Rasters.BatchDelete -- ** mapsengine.rasterCollections.rasters.batchInsert , module Network.Google.Resource.MapsEngine.RasterCollections.Rasters.BatchInsert -- ** mapsengine.rasterCollections.rasters.list , module Network.Google.Resource.MapsEngine.RasterCollections.Rasters.List -- ** mapsengine.rasters.delete , module Network.Google.Resource.MapsEngine.Rasters.Delete -- ** mapsengine.rasters.files.insert , module Network.Google.Resource.MapsEngine.Rasters.Files.Insert -- ** mapsengine.rasters.get , module Network.Google.Resource.MapsEngine.Rasters.Get -- ** mapsengine.rasters.list , module Network.Google.Resource.MapsEngine.Rasters.List -- ** mapsengine.rasters.parents.list , module Network.Google.Resource.MapsEngine.Rasters.Parents.List -- ** mapsengine.rasters.patch , module Network.Google.Resource.MapsEngine.Rasters.Patch -- ** mapsengine.rasters.permissions.batchDelete , module Network.Google.Resource.MapsEngine.Rasters.Permissions.BatchDelete -- ** mapsengine.rasters.permissions.batchUpdate , module Network.Google.Resource.MapsEngine.Rasters.Permissions.BatchUpdate -- ** mapsengine.rasters.permissions.list , module Network.Google.Resource.MapsEngine.Rasters.Permissions.List -- ** mapsengine.rasters.process , module Network.Google.Resource.MapsEngine.Rasters.Process -- ** mapsengine.rasters.upload , module Network.Google.Resource.MapsEngine.Rasters.Upload -- ** mapsengine.tables.create , module Network.Google.Resource.MapsEngine.Tables.Create -- ** mapsengine.tables.delete , module Network.Google.Resource.MapsEngine.Tables.Delete -- ** mapsengine.tables.features.batchDelete , module Network.Google.Resource.MapsEngine.Tables.Features.BatchDelete -- ** mapsengine.tables.features.batchInsert , module Network.Google.Resource.MapsEngine.Tables.Features.BatchInsert -- ** mapsengine.tables.features.batchPatch , module Network.Google.Resource.MapsEngine.Tables.Features.BatchPatch -- ** mapsengine.tables.features.get , module Network.Google.Resource.MapsEngine.Tables.Features.Get -- ** mapsengine.tables.features.list , module Network.Google.Resource.MapsEngine.Tables.Features.List -- ** mapsengine.tables.files.insert , module Network.Google.Resource.MapsEngine.Tables.Files.Insert -- ** mapsengine.tables.get , module Network.Google.Resource.MapsEngine.Tables.Get -- ** mapsengine.tables.list , module Network.Google.Resource.MapsEngine.Tables.List -- ** mapsengine.tables.parents.list , module Network.Google.Resource.MapsEngine.Tables.Parents.List -- ** mapsengine.tables.patch , module Network.Google.Resource.MapsEngine.Tables.Patch -- ** mapsengine.tables.permissions.batchDelete , module Network.Google.Resource.MapsEngine.Tables.Permissions.BatchDelete -- ** mapsengine.tables.permissions.batchUpdate , module Network.Google.Resource.MapsEngine.Tables.Permissions.BatchUpdate -- ** mapsengine.tables.permissions.list , module Network.Google.Resource.MapsEngine.Tables.Permissions.List -- ** mapsengine.tables.process , module Network.Google.Resource.MapsEngine.Tables.Process -- ** mapsengine.tables.upload , module Network.Google.Resource.MapsEngine.Tables.Upload -- * Types -- ** ValueRange , ValueRange , valueRange , vrMax , vrMin -- ** GeoJSONProperties , GeoJSONProperties , geoJSONProperties , gjpAddtional -- ** Feature , Feature , feature , fGeometry , fType , fProperties -- ** Parent , Parent , parent , pId -- ** FeaturesBatchPatchRequest , FeaturesBatchPatchRequest , featuresBatchPatchRequest , fbprFeatures , fbprNormalizeGeometries -- ** PermissionsBatchUpdateRequest , PermissionsBatchUpdateRequest , permissionsBatchUpdateRequest , pburPermissions -- ** RasterProcessingStatus , RasterProcessingStatus (..) -- ** LayerProcessingStatus , LayerProcessingStatus (..) -- ** ScaledShapeShape , ScaledShapeShape (..) -- ** PermissionsBatchDeleteRequest , PermissionsBatchDeleteRequest , permissionsBatchDeleteRequest , pbdrIds -- ** RasterCollectionsListResponse , RasterCollectionsListResponse , rasterCollectionsListResponse , rclrNextPageToken , rclrRasterCollections -- ** GeoJSONMultiLineStringType , GeoJSONMultiLineStringType (..) -- ** PermissionRole , PermissionRole (..) -- ** ProjectsListResponse , ProjectsListResponse , projectsListResponse , plrProjects -- ** GeoJSONGeometry , GeoJSONGeometry , geoJSONGeometry -- ** MapLayer , MapLayer , mapLayer , mlDefaultViewport , mlVisibility , mlKey , mlName , mlId , mlType -- ** ZoomLevels , ZoomLevels , zoomLevels , zlMax , zlMin -- ** FeatureInfo , FeatureInfo , featureInfo , fiContent -- ** AcquisitionTimePrecision , AcquisitionTimePrecision (..) -- ** SizeRange , SizeRange , sizeRange , srMax , srMin -- ** ScalingFunctionScalingType , ScalingFunctionScalingType (..) -- ** MapFolder , MapFolder , mapFolder , mfExpandable , mfDefaultViewport , mfContents , mfVisibility , mfKey , mfName , mfType -- ** AssetsListRole , AssetsListRole (..) -- ** RastersListProcessingStatus , RastersListProcessingStatus (..) -- ** Project , Project , project , proName , proId -- ** Color , Color , color , cColor , cOpacity -- ** LayersListProcessingStatus , LayersListProcessingStatus (..) -- ** RasterCollection , RasterCollection , rasterCollection , rcCreationTime , rcWritersCanEditPermissions , rcEtag , rcCreatorEmail , rcRasterType , rcLastModifiedTime , rcLastModifierEmail , rcName , rcBbox , rcProcessingStatus , rcMosaic , rcId , rcProjectId , rcDraftAccessList , rcDescription , rcAttribution , rcTags -- ** LineStyleStroke , LineStyleStroke , lineStyleStroke , lssColor , lssWidth , lssOpacity -- ** RasterCollectionsRastersListRole , RasterCollectionsRastersListRole (..) -- ** GeoJSONMultiPolygonType , GeoJSONMultiPolygonType (..) -- ** GeoJSONMultiPointType , GeoJSONMultiPointType (..) -- ** RasterCollectionsRastersBatchDeleteResponse , RasterCollectionsRastersBatchDeleteResponse , rasterCollectionsRastersBatchDeleteResponse -- ** ProcessResponse , ProcessResponse , processResponse -- ** TableColumn , TableColumn , tableColumn , tcName , tcType -- ** PublishedLayerLayerType , PublishedLayerLayerType (..) -- ** TablesListProcessingStatus , TablesListProcessingStatus (..) -- ** Asset , Asset , asset , aCreationTime , aWritersCanEditPermissions , aEtag , aCreatorEmail , aLastModifiedTime , aLastModifierEmail , aName , aBbox , aResource , aId , aProjectId , aType , aDescription , aTags -- ** LayerLayerType , LayerLayerType (..) -- ** ScaledShape , ScaledShape , scaledShape , ssBOrder , ssFill , ssShape -- ** PermissionType , PermissionType (..) -- ** MapProcessingStatus , MapProcessingStatus (..) -- ** FeaturesBatchDeleteRequest , FeaturesBatchDeleteRequest , featuresBatchDeleteRequest , fbdrPrimaryKeys , fbdrGxIds -- ** MapsGetVersion , MapsGetVersion (..) -- ** TablesListRole , TablesListRole (..) -- ** Icon , Icon , icon , iName , iId , iDescription -- ** VectorStyleType , VectorStyleType (..) -- ** GeoJSONLineStringType , GeoJSONLineStringType (..) -- ** ParentsListResponse , ParentsListResponse , parentsListResponse , plrNextPageToken , plrParents -- ** FeaturesListResponse , FeaturesListResponse , featuresListResponse , flrNextPageToken , flrAllowedQueriesPerSecond , flrSchema , flrFeatures , flrType -- ** RasterCollectionsRastersBatchInsertResponse , RasterCollectionsRastersBatchInsertResponse , rasterCollectionsRastersBatchInsertResponse -- ** LayerPublishingStatus , LayerPublishingStatus (..) -- ** MapKmlLinkType , MapKmlLinkType (..) -- ** LayerDatasourceType , LayerDatasourceType (..) -- ** GeoJSONGeometryCollectionType , GeoJSONGeometryCollectionType (..) -- ** IconsListResponse , IconsListResponse , iconsListResponse , ilrNextPageToken , ilrIcons -- ** LabelStyle , LabelStyle , labelStyle , lsFontStyle , lsColor , lsSize , lsOpacity , lsOutline , lsFontWeight , lsColumn -- ** RasterCollectionsRasterBatchDeleteRequest , RasterCollectionsRasterBatchDeleteRequest , rasterCollectionsRasterBatchDeleteRequest , rcrbdrIds -- ** Schema , Schema , schema , sPrimaryKey , sColumns , sPrimaryGeometry -- ** MapItem , MapItem , mapItem -- ** GeoJSONPointType , GeoJSONPointType (..) -- ** GeoJSONPolygonType , GeoJSONPolygonType (..) -- ** RasterCollectionsRastersBatchInsertRequest , RasterCollectionsRastersBatchInsertRequest , rasterCollectionsRastersBatchInsertRequest , rcrbirIds -- ** PublishedMap , PublishedMap , publishedMap , pmDefaultViewport , pmContents , pmName , pmId , pmProjectId , pmDescription -- ** AcquisitionTime , AcquisitionTime , acquisitionTime , atStart , atPrecision , atEnd -- ** LayersGetVersion , LayersGetVersion (..) -- ** TablesListResponse , TablesListResponse , tablesListResponse , tlrNextPageToken , tlrTables -- ** IconStyle , IconStyle , iconStyle , isScaledShape , isScalingFunction , isName , isId -- ** DisplayRule , DisplayRule , displayRule , drPointOptions , drPolygonOptions , drZoomLevels , drFilters , drName , drLineOptions -- ** BOrder , BOrder , bOrder , boColor , boWidth , boOpacity -- ** Map , Map , map' , mCreationTime , mWritersCanEditPermissions , mEtag , mDefaultViewport , mContents , mPublishingStatus , mCreatorEmail , mLastModifiedTime , mLastModifierEmail , mVersions , mName , mBbox , mProcessingStatus , mId , mProjectId , mDraftAccessList , mPublishedAccessList , mDescription , mTags -- ** MapLayerType , MapLayerType (..) -- ** RasterCollectionsRastersListResponse , RasterCollectionsRastersListResponse , rasterCollectionsRastersListResponse , rcrlrNextPageToken , rcrlrRasters -- ** GeoJSONMultiLineString , GeoJSONMultiLineString , geoJSONMultiLineString , gjmlsCoordinates , gjmlsType -- ** ScalingFunction , ScalingFunction , scalingFunction , sfValueRange , sfSizeRange , sfScalingType , sfColumn -- ** LabelStyleFontWeight , LabelStyleFontWeight (..) -- ** MapFolderType , MapFolderType (..) -- ** RasterCollectionProcessingStatus , RasterCollectionProcessingStatus (..) -- ** TablesFeaturesListVersion , TablesFeaturesListVersion (..) -- ** MapsListProcessingStatus , MapsListProcessingStatus (..) -- ** AssetsListResponse , AssetsListResponse , assetsListResponse , alrNextPageToken , alrAssets -- ** PublishResponse , PublishResponse , publishResponse -- ** FeaturesBatchInsertRequest , FeaturesBatchInsertRequest , featuresBatchInsertRequest , fbirFeatures , fbirNormalizeGeometries -- ** Datasource , Datasource , datasource , dId -- ** LabelStyleFontStyle , LabelStyleFontStyle (..) -- ** RasterCollectionsRaster , RasterCollectionsRaster , rasterCollectionsRaster , rcrCreationTime , rcrRasterType , rcrLastModifiedTime , rcrName , rcrBbox , rcrId , rcrProjectId , rcrDescription , rcrTags -- ** Filter , Filter , filter' , fOperator , fValue , fColumn -- ** GeoJSONMultiPoint , GeoJSONMultiPoint , geoJSONMultiPoint , gjmpCoordinates , gjmpType -- ** AssetType , AssetType (..) -- ** RasterRasterType , RasterRasterType (..) -- ** RasterCollectionsListRole , RasterCollectionsListRole (..) -- ** FilterOperator , FilterOperator (..) -- ** TableColumnType , TableColumnType (..) -- ** GeoJSONMultiPolygon , GeoJSONMultiPolygon , geoJSONMultiPolygon , gjsonmpCoordinates , gjsonmpType -- ** Layer , Layer , layer , layCreationTime , layWritersCanEditPermissions , layStyle , layEtag , layDatasourceType , layPublishingStatus , layCreatorEmail , layLayerType , layLastModifiedTime , layDatasources , layLastModifierEmail , layName , layBbox , layProcessingStatus , layId , layProjectId , layDraftAccessList , layPublishedAccessList , layDescription , layTags -- ** PointStyle , PointStyle , pointStyle , psIcon , psLabel -- ** RasterCollectionsListProcessingStatus , RasterCollectionsListProcessingStatus (..) -- ** Raster , Raster , raster , rrCreationTime , rrWritersCanEditPermissions , rrMaskType , rrEtag , rrCreatorEmail , rrRasterType , rrLastModifiedTime , rrLastModifierEmail , rrAcquisitionTime , rrName , rrBbox , rrProcessingStatus , rrFiles , rrId , rrProjectId , rrDraftAccessList , rrDescription , rrAttribution , rrTags -- ** PolygonStyle , PolygonStyle , polygonStyle , pStroke , pFill , pLabel -- ** Permission , Permission , permission , perRole , perId , perType , perDiscoverable -- ** PublishedLayer , PublishedLayer , publishedLayer , plLayerType , plName , plId , plProjectId , plDescription -- ** LayersListRole , LayersListRole (..) -- ** Table , Table , table , tabCreationTime , tabWritersCanEditPermissions , tabEtag , tabCreatorEmail , tabLastModifiedTime , tabSchema , tabLastModifierEmail , tabName , tabBbox , tabProcessingStatus , tabFiles , tabId , tabProjectId , tabDraftAccessList , tabPublishedAccessList , tabSourceEncoding , tabDescription , tabTags -- ** File , File , file , fSize , fUploadStatus , fFilename -- ** VectorStyle , VectorStyle , vectorStyle , vsDisplayRules , vsFeatureInfo , vsType -- ** PermissionsBatchDeleteResponse , PermissionsBatchDeleteResponse , permissionsBatchDeleteResponse -- ** TablesFeaturesGetVersion , TablesFeaturesGetVersion (..) -- ** MapKmlLink , MapKmlLink , mapKmlLink , mklDefaultViewport , mklVisibility , mklName , mklType , mklKmlURL -- ** RasterCollectionRasterType , RasterCollectionRasterType (..) -- ** RastersListRole , RastersListRole (..) -- ** PermissionsBatchUpdateResponse , PermissionsBatchUpdateResponse , permissionsBatchUpdateResponse -- ** GeoJSONLineString , GeoJSONLineString , geoJSONLineString , gjlsCoordinates , gjlsType -- ** PublishedMapsListResponse , PublishedMapsListResponse , publishedMapsListResponse , pmlrMaps , pmlrNextPageToken -- ** MapsListResponse , MapsListResponse , mapsListResponse , mlrMaps , mlrNextPageToken -- ** MapPublishingStatus , MapPublishingStatus (..) -- ** GeoJSONGeometryCollection , GeoJSONGeometryCollection , geoJSONGeometryCollection , gjgcGeometries , gjgcType -- ** GeoJSONPolygon , GeoJSONPolygon , geoJSONPolygon , gjpCoordinates , gjpType -- ** GeoJSONPoint , GeoJSONPoint , geoJSONPoint , gjsonpCoordinates , gjsonpType -- ** LayersListResponse , LayersListResponse , layersListResponse , llrNextPageToken , llrLayers -- ** RastersListResponse , RastersListResponse , rastersListResponse , rlrNextPageToken , rlrRasters -- ** FileUploadStatus , FileUploadStatus (..) -- ** MapsListRole , MapsListRole (..) -- ** TablesGetVersion , TablesGetVersion (..) -- ** PermissionsListResponse , PermissionsListResponse , permissionsListResponse , plrPermissions -- ** TableProcessingStatus , TableProcessingStatus (..) -- ** LineStyle , LineStyle , lineStyle , lsStroke , lsBOrder , lsDash , lsLabel -- ** PublishedLayersListResponse , PublishedLayersListResponse , publishedLayersListResponse , pllrNextPageToken , pllrLayers ) where import Network.Google.MapsEngine.Types import Network.Google.Prelude import Network.Google.Resource.MapsEngine.Assets.Get import Network.Google.Resource.MapsEngine.Assets.List import Network.Google.Resource.MapsEngine.Assets.Parents.List import Network.Google.Resource.MapsEngine.Assets.Permissions.List import Network.Google.Resource.MapsEngine.Layers.CancelProcessing import Network.Google.Resource.MapsEngine.Layers.Create import Network.Google.Resource.MapsEngine.Layers.Delete import Network.Google.Resource.MapsEngine.Layers.Get import Network.Google.Resource.MapsEngine.Layers.GetPublished import Network.Google.Resource.MapsEngine.Layers.List import Network.Google.Resource.MapsEngine.Layers.ListPublished import Network.Google.Resource.MapsEngine.Layers.Parents.List import Network.Google.Resource.MapsEngine.Layers.Patch import Network.Google.Resource.MapsEngine.Layers.Permissions.BatchDelete import Network.Google.Resource.MapsEngine.Layers.Permissions.BatchUpdate import Network.Google.Resource.MapsEngine.Layers.Permissions.List import Network.Google.Resource.MapsEngine.Layers.Process import Network.Google.Resource.MapsEngine.Layers.Publish import Network.Google.Resource.MapsEngine.Layers.UnPublish import Network.Google.Resource.MapsEngine.Maps.Create import Network.Google.Resource.MapsEngine.Maps.Delete import Network.Google.Resource.MapsEngine.Maps.Get import Network.Google.Resource.MapsEngine.Maps.GetPublished import Network.Google.Resource.MapsEngine.Maps.List import Network.Google.Resource.MapsEngine.Maps.ListPublished import Network.Google.Resource.MapsEngine.Maps.Patch import Network.Google.Resource.MapsEngine.Maps.Permissions.BatchDelete import Network.Google.Resource.MapsEngine.Maps.Permissions.BatchUpdate import Network.Google.Resource.MapsEngine.Maps.Permissions.List import Network.Google.Resource.MapsEngine.Maps.Publish import Network.Google.Resource.MapsEngine.Maps.UnPublish import Network.Google.Resource.MapsEngine.Projects.Icons.Create import Network.Google.Resource.MapsEngine.Projects.Icons.Get import Network.Google.Resource.MapsEngine.Projects.Icons.List import Network.Google.Resource.MapsEngine.Projects.List import Network.Google.Resource.MapsEngine.RasterCollections.CancelProcessing import Network.Google.Resource.MapsEngine.RasterCollections.Create import Network.Google.Resource.MapsEngine.RasterCollections.Delete import Network.Google.Resource.MapsEngine.RasterCollections.Get import Network.Google.Resource.MapsEngine.RasterCollections.List import Network.Google.Resource.MapsEngine.RasterCollections.Parents.List import Network.Google.Resource.MapsEngine.RasterCollections.Patch import Network.Google.Resource.MapsEngine.RasterCollections.Permissions.BatchDelete import Network.Google.Resource.MapsEngine.RasterCollections.Permissions.BatchUpdate import Network.Google.Resource.MapsEngine.RasterCollections.Permissions.List import Network.Google.Resource.MapsEngine.RasterCollections.Process import Network.Google.Resource.MapsEngine.RasterCollections.Rasters.BatchDelete import Network.Google.Resource.MapsEngine.RasterCollections.Rasters.BatchInsert import Network.Google.Resource.MapsEngine.RasterCollections.Rasters.List import Network.Google.Resource.MapsEngine.Rasters.Delete import Network.Google.Resource.MapsEngine.Rasters.Files.Insert import Network.Google.Resource.MapsEngine.Rasters.Get import Network.Google.Resource.MapsEngine.Rasters.List import Network.Google.Resource.MapsEngine.Rasters.Parents.List import Network.Google.Resource.MapsEngine.Rasters.Patch import Network.Google.Resource.MapsEngine.Rasters.Permissions.BatchDelete import Network.Google.Resource.MapsEngine.Rasters.Permissions.BatchUpdate import Network.Google.Resource.MapsEngine.Rasters.Permissions.List import Network.Google.Resource.MapsEngine.Rasters.Process import Network.Google.Resource.MapsEngine.Rasters.Upload import Network.Google.Resource.MapsEngine.Tables.Create import Network.Google.Resource.MapsEngine.Tables.Delete import Network.Google.Resource.MapsEngine.Tables.Features.BatchDelete import Network.Google.Resource.MapsEngine.Tables.Features.BatchInsert import Network.Google.Resource.MapsEngine.Tables.Features.BatchPatch import Network.Google.Resource.MapsEngine.Tables.Features.Get import Network.Google.Resource.MapsEngine.Tables.Features.List import Network.Google.Resource.MapsEngine.Tables.Files.Insert import Network.Google.Resource.MapsEngine.Tables.Get import Network.Google.Resource.MapsEngine.Tables.List import Network.Google.Resource.MapsEngine.Tables.Parents.List import Network.Google.Resource.MapsEngine.Tables.Patch import Network.Google.Resource.MapsEngine.Tables.Permissions.BatchDelete import Network.Google.Resource.MapsEngine.Tables.Permissions.BatchUpdate import Network.Google.Resource.MapsEngine.Tables.Permissions.List import Network.Google.Resource.MapsEngine.Tables.Process import Network.Google.Resource.MapsEngine.Tables.Upload {- $resources TODO -} -- | Represents the entirety of the methods and resources available for the Google Maps Engine API service. type MapsEngineAPI = MapsPermissionsListResource :<|> MapsPermissionsBatchUpdateResource :<|> MapsPermissionsBatchDeleteResource :<|> MapsListResource :<|> MapsListPublishedResource :<|> MapsPatchResource :<|> MapsGetResource :<|> MapsGetPublishedResource :<|> MapsCreateResource :<|> MapsUnPublishResource :<|> MapsDeleteResource :<|> MapsPublishResource :<|> TablesParentsListResource :<|> TablesFeaturesListResource :<|> TablesFeaturesBatchInsertResource :<|> TablesFeaturesGetResource :<|> TablesFeaturesBatchPatchResource :<|> TablesFeaturesBatchDeleteResource :<|> TablesFilesInsertResource :<|> TablesPermissionsListResource :<|> TablesPermissionsBatchUpdateResource :<|> TablesPermissionsBatchDeleteResource :<|> TablesListResource :<|> TablesProcessResource :<|> TablesPatchResource :<|> TablesGetResource :<|> TablesCreateResource :<|> TablesUploadResource :<|> TablesDeleteResource :<|> LayersParentsListResource :<|> LayersPermissionsListResource :<|> LayersPermissionsBatchUpdateResource :<|> LayersPermissionsBatchDeleteResource :<|> LayersListResource :<|> LayersListPublishedResource :<|> LayersProcessResource :<|> LayersPatchResource :<|> LayersGetResource :<|> LayersGetPublishedResource :<|> LayersCreateResource :<|> LayersUnPublishResource :<|> LayersCancelProcessingResource :<|> LayersDeleteResource :<|> LayersPublishResource :<|> RastersParentsListResource :<|> RastersFilesInsertResource :<|> RastersPermissionsListResource :<|> RastersPermissionsBatchUpdateResource :<|> RastersPermissionsBatchDeleteResource :<|> RastersListResource :<|> RastersProcessResource :<|> RastersPatchResource :<|> RastersGetResource :<|> RastersUploadResource :<|> RastersDeleteResource :<|> AssetsParentsListResource :<|> AssetsPermissionsListResource :<|> AssetsListResource :<|> AssetsGetResource :<|> RasterCollectionsParentsListResource :<|> RasterCollectionsPermissionsListResource :<|> RasterCollectionsPermissionsBatchUpdateResource :<|> RasterCollectionsPermissionsBatchDeleteResource :<|> RasterCollectionsRastersListResource :<|> RasterCollectionsRastersBatchInsertResource :<|> RasterCollectionsRastersBatchDeleteResource :<|> RasterCollectionsListResource :<|> RasterCollectionsProcessResource :<|> RasterCollectionsPatchResource :<|> RasterCollectionsGetResource :<|> RasterCollectionsCreateResource :<|> RasterCollectionsCancelProcessingResource :<|> RasterCollectionsDeleteResource :<|> ProjectsIconsListResource :<|> ProjectsIconsGetResource :<|> ProjectsIconsCreateResource :<|> ProjectsListResource
rueshyna/gogol
gogol-maps-engine/gen/Network/Google/MapsEngine.hs
mpl-2.0
32,425
0
80
6,970
3,750
2,745
1,005
726
0
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Module : Network.AWS.Support.DescribeCommunications -- Copyright : (c) 2013-2014 Brendan Hay <[email protected]> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <[email protected]> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | Returns communications (and attachments) for one or more support cases. You -- can use the 'AfterTime' and 'BeforeTime' parameters to filter by date. You can -- use the 'CaseId' parameter to restrict the results to a particular case. -- -- Case data is available for 12 months after creation. If a case was created -- more than 12 months ago, a request for data might cause an error. -- -- You can use the 'MaxResults' and 'NextToken' parameters to control the -- pagination of the result set. Set 'MaxResults' to the number of cases you want -- displayed on each page, and use 'NextToken' to specify the resumption of -- pagination. -- -- <http://docs.aws.amazon.com/awssupport/latest/APIReference/API_DescribeCommunications.html> module Network.AWS.Support.DescribeCommunications ( -- * Request DescribeCommunications -- ** Request constructor , describeCommunications -- ** Request lenses , dc1AfterTime , dc1BeforeTime , dc1CaseId , dc1MaxResults , dc1NextToken -- * Response , DescribeCommunicationsResponse -- ** Response constructor , describeCommunicationsResponse -- ** Response lenses , dcrCommunications , dcrNextToken ) where import Network.AWS.Prelude import Network.AWS.Request.JSON import Network.AWS.Support.Types import qualified GHC.Exts data DescribeCommunications = DescribeCommunications { _dc1AfterTime :: Maybe Text , _dc1BeforeTime :: Maybe Text , _dc1CaseId :: Text , _dc1MaxResults :: Maybe Nat , _dc1NextToken :: Maybe Text } deriving (Eq, Ord, Read, Show) -- | 'DescribeCommunications' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'dc1AfterTime' @::@ 'Maybe' 'Text' -- -- * 'dc1BeforeTime' @::@ 'Maybe' 'Text' -- -- * 'dc1CaseId' @::@ 'Text' -- -- * 'dc1MaxResults' @::@ 'Maybe' 'Natural' -- -- * 'dc1NextToken' @::@ 'Maybe' 'Text' -- describeCommunications :: Text -- ^ 'dc1CaseId' -> DescribeCommunications describeCommunications p1 = DescribeCommunications { _dc1CaseId = p1 , _dc1BeforeTime = Nothing , _dc1AfterTime = Nothing , _dc1NextToken = Nothing , _dc1MaxResults = Nothing } -- | The start date for a filtered date search on support case communications. -- Case communications are available for 12 months after creation. dc1AfterTime :: Lens' DescribeCommunications (Maybe Text) dc1AfterTime = lens _dc1AfterTime (\s a -> s { _dc1AfterTime = a }) -- | The end date for a filtered date search on support case communications. Case -- communications are available for 12 months after creation. dc1BeforeTime :: Lens' DescribeCommunications (Maybe Text) dc1BeforeTime = lens _dc1BeforeTime (\s a -> s { _dc1BeforeTime = a }) -- | The AWS Support case ID requested or returned in the call. The case ID is an -- alphanumeric string formatted as shown in this example: case-/12345678910-2013-c4c1d2bf33c5cf47/ dc1CaseId :: Lens' DescribeCommunications Text dc1CaseId = lens _dc1CaseId (\s a -> s { _dc1CaseId = a }) -- | The maximum number of results to return before paginating. dc1MaxResults :: Lens' DescribeCommunications (Maybe Natural) dc1MaxResults = lens _dc1MaxResults (\s a -> s { _dc1MaxResults = a }) . mapping _Nat -- | A resumption point for pagination. dc1NextToken :: Lens' DescribeCommunications (Maybe Text) dc1NextToken = lens _dc1NextToken (\s a -> s { _dc1NextToken = a }) data DescribeCommunicationsResponse = DescribeCommunicationsResponse { _dcrCommunications :: List "communications" Communication , _dcrNextToken :: Maybe Text } deriving (Eq, Read, Show) -- | 'DescribeCommunicationsResponse' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'dcrCommunications' @::@ ['Communication'] -- -- * 'dcrNextToken' @::@ 'Maybe' 'Text' -- describeCommunicationsResponse :: DescribeCommunicationsResponse describeCommunicationsResponse = DescribeCommunicationsResponse { _dcrCommunications = mempty , _dcrNextToken = Nothing } -- | The communications for the case. dcrCommunications :: Lens' DescribeCommunicationsResponse [Communication] dcrCommunications = lens _dcrCommunications (\s a -> s { _dcrCommunications = a }) . _List -- | A resumption point for pagination. dcrNextToken :: Lens' DescribeCommunicationsResponse (Maybe Text) dcrNextToken = lens _dcrNextToken (\s a -> s { _dcrNextToken = a }) instance ToPath DescribeCommunications where toPath = const "/" instance ToQuery DescribeCommunications where toQuery = const mempty instance ToHeaders DescribeCommunications instance ToJSON DescribeCommunications where toJSON DescribeCommunications{..} = object [ "caseId" .= _dc1CaseId , "beforeTime" .= _dc1BeforeTime , "afterTime" .= _dc1AfterTime , "nextToken" .= _dc1NextToken , "maxResults" .= _dc1MaxResults ] instance AWSRequest DescribeCommunications where type Sv DescribeCommunications = Support type Rs DescribeCommunications = DescribeCommunicationsResponse request = post "DescribeCommunications" response = jsonResponse instance FromJSON DescribeCommunicationsResponse where parseJSON = withObject "DescribeCommunicationsResponse" $ \o -> DescribeCommunicationsResponse <$> o .:? "communications" .!= mempty <*> o .:? "nextToken" instance AWSPager DescribeCommunications where page rq rs | stop (rs ^. dcrNextToken) = Nothing | otherwise = (\x -> rq & dc1NextToken ?~ x) <$> (rs ^. dcrNextToken)
dysinger/amazonka
amazonka-support/gen/Network/AWS/Support/DescribeCommunications.hs
mpl-2.0
6,648
0
12
1,362
892
527
365
92
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.ShoppingContent.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.ShoppingContent.Types.Product where import Network.Google.Prelude import Network.Google.ShoppingContent.Types.Sum -- -- /See:/ 'ordersAcknowledgeRequest' smart constructor. newtype OrdersAcknowledgeRequest = OrdersAcknowledgeRequest' { _oarOperationId :: Maybe Text } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'OrdersAcknowledgeRequest' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'oarOperationId' ordersAcknowledgeRequest :: OrdersAcknowledgeRequest ordersAcknowledgeRequest = OrdersAcknowledgeRequest' { _oarOperationId = Nothing } -- | The ID of the operation. Unique across all operations for a given order. oarOperationId :: Lens' OrdersAcknowledgeRequest (Maybe Text) oarOperationId = lens _oarOperationId (\ s a -> s{_oarOperationId = a}) instance FromJSON OrdersAcknowledgeRequest where parseJSON = withObject "OrdersAcknowledgeRequest" (\ o -> OrdersAcknowledgeRequest' <$> (o .:? "operationId")) instance ToJSON OrdersAcknowledgeRequest where toJSON OrdersAcknowledgeRequest'{..} = object (catMaybes [("operationId" .=) <$> _oarOperationId]) -- | The tax settings of a merchant account. -- -- /See:/ 'accountTax' smart constructor. data AccountTax = AccountTax' { _atRules :: !(Maybe [AccountTaxTaxRule]) , _atKind :: !Text , _atAccountId :: !(Maybe (Textual Word64)) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'AccountTax' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'atRules' -- -- * 'atKind' -- -- * 'atAccountId' accountTax :: AccountTax accountTax = AccountTax' { _atRules = Nothing , _atKind = "content#accountTax" , _atAccountId = Nothing } -- | Tax rules. Updating the tax rules will enable US taxes (not reversible). -- Defining no rules is equivalent to not charging tax at all. atRules :: Lens' AccountTax [AccountTaxTaxRule] atRules = lens _atRules (\ s a -> s{_atRules = a}) . _Default . _Coerce -- | Identifies what kind of resource this is. Value: the fixed string -- \"content#accountTax\". atKind :: Lens' AccountTax Text atKind = lens _atKind (\ s a -> s{_atKind = a}) -- | The ID of the account to which these account tax settings belong. atAccountId :: Lens' AccountTax (Maybe Word64) atAccountId = lens _atAccountId (\ s a -> s{_atAccountId = a}) . mapping _Coerce instance FromJSON AccountTax where parseJSON = withObject "AccountTax" (\ o -> AccountTax' <$> (o .:? "rules" .!= mempty) <*> (o .:? "kind" .!= "content#accountTax") <*> (o .:? "accountId")) instance ToJSON AccountTax where toJSON AccountTax'{..} = object (catMaybes [("rules" .=) <$> _atRules, Just ("kind" .= _atKind), ("accountId" .=) <$> _atAccountId]) -- -- /See:/ 'ordersUpdateMerchantOrderIdRequest' smart constructor. data OrdersUpdateMerchantOrderIdRequest = OrdersUpdateMerchantOrderIdRequest' { _oumoirMerchantOrderId :: !(Maybe Text) , _oumoirOperationId :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'OrdersUpdateMerchantOrderIdRequest' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'oumoirMerchantOrderId' -- -- * 'oumoirOperationId' ordersUpdateMerchantOrderIdRequest :: OrdersUpdateMerchantOrderIdRequest ordersUpdateMerchantOrderIdRequest = OrdersUpdateMerchantOrderIdRequest' { _oumoirMerchantOrderId = Nothing , _oumoirOperationId = Nothing } -- | The merchant order id to be assigned to the order. Must be unique per -- merchant. oumoirMerchantOrderId :: Lens' OrdersUpdateMerchantOrderIdRequest (Maybe Text) oumoirMerchantOrderId = lens _oumoirMerchantOrderId (\ s a -> s{_oumoirMerchantOrderId = a}) -- | The ID of the operation. Unique across all operations for a given order. oumoirOperationId :: Lens' OrdersUpdateMerchantOrderIdRequest (Maybe Text) oumoirOperationId = lens _oumoirOperationId (\ s a -> s{_oumoirOperationId = a}) instance FromJSON OrdersUpdateMerchantOrderIdRequest where parseJSON = withObject "OrdersUpdateMerchantOrderIdRequest" (\ o -> OrdersUpdateMerchantOrderIdRequest' <$> (o .:? "merchantOrderId") <*> (o .:? "operationId")) instance ToJSON OrdersUpdateMerchantOrderIdRequest where toJSON OrdersUpdateMerchantOrderIdRequest'{..} = object (catMaybes [("merchantOrderId" .=) <$> _oumoirMerchantOrderId, ("operationId" .=) <$> _oumoirOperationId]) -- -- /See:/ 'ordersAdvanceTestOrderResponse' smart constructor. newtype OrdersAdvanceTestOrderResponse = OrdersAdvanceTestOrderResponse' { _oatorKind :: Text } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'OrdersAdvanceTestOrderResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'oatorKind' ordersAdvanceTestOrderResponse :: OrdersAdvanceTestOrderResponse ordersAdvanceTestOrderResponse = OrdersAdvanceTestOrderResponse' { _oatorKind = "content#ordersAdvanceTestOrderResponse" } -- | Identifies what kind of resource this is. Value: the fixed string -- \"content#ordersAdvanceTestOrderResponse\". oatorKind :: Lens' OrdersAdvanceTestOrderResponse Text oatorKind = lens _oatorKind (\ s a -> s{_oatorKind = a}) instance FromJSON OrdersAdvanceTestOrderResponse where parseJSON = withObject "OrdersAdvanceTestOrderResponse" (\ o -> OrdersAdvanceTestOrderResponse' <$> (o .:? "kind" .!= "content#ordersAdvanceTestOrderResponse")) instance ToJSON OrdersAdvanceTestOrderResponse where toJSON OrdersAdvanceTestOrderResponse'{..} = object (catMaybes [Just ("kind" .= _oatorKind)]) -- -- /See:/ 'productsCustomBatchResponse' smart constructor. data ProductsCustomBatchResponse = ProductsCustomBatchResponse' { _pcbrEntries :: !(Maybe [ProductsCustomBatchResponseEntry]) , _pcbrKind :: !Text } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ProductsCustomBatchResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pcbrEntries' -- -- * 'pcbrKind' productsCustomBatchResponse :: ProductsCustomBatchResponse productsCustomBatchResponse = ProductsCustomBatchResponse' { _pcbrEntries = Nothing , _pcbrKind = "content#productsCustomBatchResponse" } -- | The result of the execution of the batch requests. pcbrEntries :: Lens' ProductsCustomBatchResponse [ProductsCustomBatchResponseEntry] pcbrEntries = lens _pcbrEntries (\ s a -> s{_pcbrEntries = a}) . _Default . _Coerce -- | Identifies what kind of resource this is. Value: the fixed string -- \"content#productsCustomBatchResponse\". pcbrKind :: Lens' ProductsCustomBatchResponse Text pcbrKind = lens _pcbrKind (\ s a -> s{_pcbrKind = a}) instance FromJSON ProductsCustomBatchResponse where parseJSON = withObject "ProductsCustomBatchResponse" (\ o -> ProductsCustomBatchResponse' <$> (o .:? "entries" .!= mempty) <*> (o .:? "kind" .!= "content#productsCustomBatchResponse")) instance ToJSON ProductsCustomBatchResponse where toJSON ProductsCustomBatchResponse'{..} = object (catMaybes [("entries" .=) <$> _pcbrEntries, Just ("kind" .= _pcbrKind)]) -- -- /See:/ 'testOrderCustomer' smart constructor. data TestOrderCustomer = TestOrderCustomer' { _tocFullName :: !(Maybe Text) , _tocEmail :: !(Maybe Text) , _tocExplicitMarketingPreference :: !(Maybe Bool) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'TestOrderCustomer' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'tocFullName' -- -- * 'tocEmail' -- -- * 'tocExplicitMarketingPreference' testOrderCustomer :: TestOrderCustomer testOrderCustomer = TestOrderCustomer' { _tocFullName = Nothing , _tocEmail = Nothing , _tocExplicitMarketingPreference = Nothing } -- | Full name of the customer. tocFullName :: Lens' TestOrderCustomer (Maybe Text) tocFullName = lens _tocFullName (\ s a -> s{_tocFullName = a}) -- | Email address of the customer. tocEmail :: Lens' TestOrderCustomer (Maybe Text) tocEmail = lens _tocEmail (\ s a -> s{_tocEmail = a}) -- | If set, this indicates the user explicitly chose to opt in or out of -- providing marketing rights to the merchant. If unset, this indicates the -- user has already made this choice in a previous purchase, and was thus -- not shown the marketing right opt in\/out checkbox during the checkout -- flow. Optional. tocExplicitMarketingPreference :: Lens' TestOrderCustomer (Maybe Bool) tocExplicitMarketingPreference = lens _tocExplicitMarketingPreference (\ s a -> s{_tocExplicitMarketingPreference = a}) instance FromJSON TestOrderCustomer where parseJSON = withObject "TestOrderCustomer" (\ o -> TestOrderCustomer' <$> (o .:? "fullName") <*> (o .:? "email") <*> (o .:? "explicitMarketingPreference")) instance ToJSON TestOrderCustomer where toJSON TestOrderCustomer'{..} = object (catMaybes [("fullName" .=) <$> _tocFullName, ("email" .=) <$> _tocEmail, ("explicitMarketingPreference" .=) <$> _tocExplicitMarketingPreference]) -- -- /See:/ 'datafeedstatusesCustomBatchResponse' smart constructor. data DatafeedstatusesCustomBatchResponse = DatafeedstatusesCustomBatchResponse' { _dcbrEntries :: !(Maybe [DatafeedstatusesCustomBatchResponseEntry]) , _dcbrKind :: !Text } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'DatafeedstatusesCustomBatchResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dcbrEntries' -- -- * 'dcbrKind' datafeedstatusesCustomBatchResponse :: DatafeedstatusesCustomBatchResponse datafeedstatusesCustomBatchResponse = DatafeedstatusesCustomBatchResponse' { _dcbrEntries = Nothing , _dcbrKind = "content#datafeedstatusesCustomBatchResponse" } -- | The result of the execution of the batch requests. dcbrEntries :: Lens' DatafeedstatusesCustomBatchResponse [DatafeedstatusesCustomBatchResponseEntry] dcbrEntries = lens _dcbrEntries (\ s a -> s{_dcbrEntries = a}) . _Default . _Coerce -- | Identifies what kind of resource this is. Value: the fixed string -- \"content#datafeedstatusesCustomBatchResponse\". dcbrKind :: Lens' DatafeedstatusesCustomBatchResponse Text dcbrKind = lens _dcbrKind (\ s a -> s{_dcbrKind = a}) instance FromJSON DatafeedstatusesCustomBatchResponse where parseJSON = withObject "DatafeedstatusesCustomBatchResponse" (\ o -> DatafeedstatusesCustomBatchResponse' <$> (o .:? "entries" .!= mempty) <*> (o .:? "kind" .!= "content#datafeedstatusesCustomBatchResponse")) instance ToJSON DatafeedstatusesCustomBatchResponse where toJSON DatafeedstatusesCustomBatchResponse'{..} = object (catMaybes [("entries" .=) <$> _dcbrEntries, Just ("kind" .= _dcbrKind)]) -- -- /See:/ 'orderReturn' smart constructor. data OrderReturn = OrderReturn' { _orQuantity :: !(Maybe (Textual Word32)) , _orActor :: !(Maybe Text) , _orReason :: !(Maybe Text) , _orCreationDate :: !(Maybe Text) , _orReasonText :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'OrderReturn' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'orQuantity' -- -- * 'orActor' -- -- * 'orReason' -- -- * 'orCreationDate' -- -- * 'orReasonText' orderReturn :: OrderReturn orderReturn = OrderReturn' { _orQuantity = Nothing , _orActor = Nothing , _orReason = Nothing , _orCreationDate = Nothing , _orReasonText = Nothing } -- | Quantity that is returned. orQuantity :: Lens' OrderReturn (Maybe Word32) orQuantity = lens _orQuantity (\ s a -> s{_orQuantity = a}) . mapping _Coerce -- | The actor that created the refund. orActor :: Lens' OrderReturn (Maybe Text) orActor = lens _orActor (\ s a -> s{_orActor = a}) -- | The reason for the return. orReason :: Lens' OrderReturn (Maybe Text) orReason = lens _orReason (\ s a -> s{_orReason = a}) -- | Date on which the item has been created, in ISO 8601 format. orCreationDate :: Lens' OrderReturn (Maybe Text) orCreationDate = lens _orCreationDate (\ s a -> s{_orCreationDate = a}) -- | The explanation of the reason. orReasonText :: Lens' OrderReturn (Maybe Text) orReasonText = lens _orReasonText (\ s a -> s{_orReasonText = a}) instance FromJSON OrderReturn where parseJSON = withObject "OrderReturn" (\ o -> OrderReturn' <$> (o .:? "quantity") <*> (o .:? "actor") <*> (o .:? "reason") <*> (o .:? "creationDate") <*> (o .:? "reasonText")) instance ToJSON OrderReturn where toJSON OrderReturn'{..} = object (catMaybes [("quantity" .=) <$> _orQuantity, ("actor" .=) <$> _orActor, ("reason" .=) <$> _orReason, ("creationDate" .=) <$> _orCreationDate, ("reasonText" .=) <$> _orReasonText]) -- | A batch entry encoding a single non-batch accounttax response. -- -- /See:/ 'accounttaxCustomBatchResponseEntry' smart constructor. data AccounttaxCustomBatchResponseEntry = AccounttaxCustomBatchResponseEntry' { _acbreAccountTax :: !(Maybe AccountTax) , _acbreKind :: !Text , _acbreErrors :: !(Maybe Errors) , _acbreBatchId :: !(Maybe (Textual Word32)) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'AccounttaxCustomBatchResponseEntry' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'acbreAccountTax' -- -- * 'acbreKind' -- -- * 'acbreErrors' -- -- * 'acbreBatchId' accounttaxCustomBatchResponseEntry :: AccounttaxCustomBatchResponseEntry accounttaxCustomBatchResponseEntry = AccounttaxCustomBatchResponseEntry' { _acbreAccountTax = Nothing , _acbreKind = "content#accounttaxCustomBatchResponseEntry" , _acbreErrors = Nothing , _acbreBatchId = Nothing } -- | The retrieved or updated account tax settings. acbreAccountTax :: Lens' AccounttaxCustomBatchResponseEntry (Maybe AccountTax) acbreAccountTax = lens _acbreAccountTax (\ s a -> s{_acbreAccountTax = a}) -- | Identifies what kind of resource this is. Value: the fixed string -- \"content#accounttaxCustomBatchResponseEntry\". acbreKind :: Lens' AccounttaxCustomBatchResponseEntry Text acbreKind = lens _acbreKind (\ s a -> s{_acbreKind = a}) -- | A list of errors defined if and only if the request failed. acbreErrors :: Lens' AccounttaxCustomBatchResponseEntry (Maybe Errors) acbreErrors = lens _acbreErrors (\ s a -> s{_acbreErrors = a}) -- | The ID of the request entry this entry responds to. acbreBatchId :: Lens' AccounttaxCustomBatchResponseEntry (Maybe Word32) acbreBatchId = lens _acbreBatchId (\ s a -> s{_acbreBatchId = a}) . mapping _Coerce instance FromJSON AccounttaxCustomBatchResponseEntry where parseJSON = withObject "AccounttaxCustomBatchResponseEntry" (\ o -> AccounttaxCustomBatchResponseEntry' <$> (o .:? "accountTax") <*> (o .:? "kind" .!= "content#accounttaxCustomBatchResponseEntry") <*> (o .:? "errors") <*> (o .:? "batchId")) instance ToJSON AccounttaxCustomBatchResponseEntry where toJSON AccounttaxCustomBatchResponseEntry'{..} = object (catMaybes [("accountTax" .=) <$> _acbreAccountTax, Just ("kind" .= _acbreKind), ("errors" .=) <$> _acbreErrors, ("batchId" .=) <$> _acbreBatchId]) -- -- /See:/ 'inventoryCustomBatchRequest' smart constructor. newtype InventoryCustomBatchRequest = InventoryCustomBatchRequest' { _icbrEntries :: Maybe [InventoryCustomBatchRequestEntry] } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'InventoryCustomBatchRequest' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'icbrEntries' inventoryCustomBatchRequest :: InventoryCustomBatchRequest inventoryCustomBatchRequest = InventoryCustomBatchRequest' { _icbrEntries = Nothing } -- | The request entries to be processed in the batch. icbrEntries :: Lens' InventoryCustomBatchRequest [InventoryCustomBatchRequestEntry] icbrEntries = lens _icbrEntries (\ s a -> s{_icbrEntries = a}) . _Default . _Coerce instance FromJSON InventoryCustomBatchRequest where parseJSON = withObject "InventoryCustomBatchRequest" (\ o -> InventoryCustomBatchRequest' <$> (o .:? "entries" .!= mempty)) instance ToJSON InventoryCustomBatchRequest where toJSON InventoryCustomBatchRequest'{..} = object (catMaybes [("entries" .=) <$> _icbrEntries]) -- -- /See:/ 'accountsAuthInfoResponse' smart constructor. data AccountsAuthInfoResponse = AccountsAuthInfoResponse' { _aairKind :: !Text , _aairAccountIdentifiers :: !(Maybe [AccountIdentifier]) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'AccountsAuthInfoResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'aairKind' -- -- * 'aairAccountIdentifiers' accountsAuthInfoResponse :: AccountsAuthInfoResponse accountsAuthInfoResponse = AccountsAuthInfoResponse' { _aairKind = "content#accountsAuthInfoResponse" , _aairAccountIdentifiers = Nothing } -- | Identifies what kind of resource this is. Value: the fixed string -- \"content#accountsAuthInfoResponse\". aairKind :: Lens' AccountsAuthInfoResponse Text aairKind = lens _aairKind (\ s a -> s{_aairKind = a}) -- | The account identifiers corresponding to the authenticated user. - For -- an individual account: only the merchant ID is defined - For an -- aggregator: only the aggregator ID is defined - For a subaccount of an -- MCA: both the merchant ID and the aggregator ID are defined. aairAccountIdentifiers :: Lens' AccountsAuthInfoResponse [AccountIdentifier] aairAccountIdentifiers = lens _aairAccountIdentifiers (\ s a -> s{_aairAccountIdentifiers = a}) . _Default . _Coerce instance FromJSON AccountsAuthInfoResponse where parseJSON = withObject "AccountsAuthInfoResponse" (\ o -> AccountsAuthInfoResponse' <$> (o .:? "kind" .!= "content#accountsAuthInfoResponse") <*> (o .:? "accountIdentifiers" .!= mempty)) instance ToJSON AccountsAuthInfoResponse where toJSON AccountsAuthInfoResponse'{..} = object (catMaybes [Just ("kind" .= _aairKind), ("accountIdentifiers" .=) <$> _aairAccountIdentifiers]) -- -- /See:/ 'productStatusDestinationStatus' smart constructor. data ProductStatusDestinationStatus = ProductStatusDestinationStatus' { _psdsDestination :: !(Maybe Text) , _psdsIntention :: !(Maybe Text) , _psdsApprovalStatus :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ProductStatusDestinationStatus' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'psdsDestination' -- -- * 'psdsIntention' -- -- * 'psdsApprovalStatus' productStatusDestinationStatus :: ProductStatusDestinationStatus productStatusDestinationStatus = ProductStatusDestinationStatus' { _psdsDestination = Nothing , _psdsIntention = Nothing , _psdsApprovalStatus = Nothing } -- | The name of the destination psdsDestination :: Lens' ProductStatusDestinationStatus (Maybe Text) psdsDestination = lens _psdsDestination (\ s a -> s{_psdsDestination = a}) -- | Whether the destination is required, excluded, selected by default or -- should be validated. psdsIntention :: Lens' ProductStatusDestinationStatus (Maybe Text) psdsIntention = lens _psdsIntention (\ s a -> s{_psdsIntention = a}) -- | The destination\'s approval status. psdsApprovalStatus :: Lens' ProductStatusDestinationStatus (Maybe Text) psdsApprovalStatus = lens _psdsApprovalStatus (\ s a -> s{_psdsApprovalStatus = a}) instance FromJSON ProductStatusDestinationStatus where parseJSON = withObject "ProductStatusDestinationStatus" (\ o -> ProductStatusDestinationStatus' <$> (o .:? "destination") <*> (o .:? "intention") <*> (o .:? "approvalStatus")) instance ToJSON ProductStatusDestinationStatus where toJSON ProductStatusDestinationStatus'{..} = object (catMaybes [("destination" .=) <$> _psdsDestination, ("intention" .=) <$> _psdsIntention, ("approvalStatus" .=) <$> _psdsApprovalStatus]) -- | Tax calculation rule to apply in a state or province (USA only). -- -- /See:/ 'accountTaxTaxRule' smart constructor. data AccountTaxTaxRule = AccountTaxTaxRule' { _attrUseGlobalRate :: !(Maybe Bool) , _attrCountry :: !(Maybe Text) , _attrShippingTaxed :: !(Maybe Bool) , _attrLocationId :: !(Maybe (Textual Word64)) , _attrRatePercent :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'AccountTaxTaxRule' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'attrUseGlobalRate' -- -- * 'attrCountry' -- -- * 'attrShippingTaxed' -- -- * 'attrLocationId' -- -- * 'attrRatePercent' accountTaxTaxRule :: AccountTaxTaxRule accountTaxTaxRule = AccountTaxTaxRule' { _attrUseGlobalRate = Nothing , _attrCountry = Nothing , _attrShippingTaxed = Nothing , _attrLocationId = Nothing , _attrRatePercent = Nothing } -- | Whether the tax rate is taken from a global tax table or specified -- explicitly. attrUseGlobalRate :: Lens' AccountTaxTaxRule (Maybe Bool) attrUseGlobalRate = lens _attrUseGlobalRate (\ s a -> s{_attrUseGlobalRate = a}) -- | Country code in which tax is applicable. attrCountry :: Lens' AccountTaxTaxRule (Maybe Text) attrCountry = lens _attrCountry (\ s a -> s{_attrCountry = a}) -- | If true, shipping charges are also taxed. attrShippingTaxed :: Lens' AccountTaxTaxRule (Maybe Bool) attrShippingTaxed = lens _attrShippingTaxed (\ s a -> s{_attrShippingTaxed = a}) -- | State (or province) is which the tax is applicable, described by its -- location id (also called criteria id). attrLocationId :: Lens' AccountTaxTaxRule (Maybe Word64) attrLocationId = lens _attrLocationId (\ s a -> s{_attrLocationId = a}) . mapping _Coerce -- | Explicit tax rate in percent, represented as a floating point number -- without the percentage character. Must not be negative. attrRatePercent :: Lens' AccountTaxTaxRule (Maybe Text) attrRatePercent = lens _attrRatePercent (\ s a -> s{_attrRatePercent = a}) instance FromJSON AccountTaxTaxRule where parseJSON = withObject "AccountTaxTaxRule" (\ o -> AccountTaxTaxRule' <$> (o .:? "useGlobalRate") <*> (o .:? "country") <*> (o .:? "shippingTaxed") <*> (o .:? "locationId") <*> (o .:? "ratePercent")) instance ToJSON AccountTaxTaxRule where toJSON AccountTaxTaxRule'{..} = object (catMaybes [("useGlobalRate" .=) <$> _attrUseGlobalRate, ("country" .=) <$> _attrCountry, ("shippingTaxed" .=) <$> _attrShippingTaxed, ("locationId" .=) <$> _attrLocationId, ("ratePercent" .=) <$> _attrRatePercent]) -- -- /See:/ 'postalCodeGroup' smart constructor. data PostalCodeGroup = PostalCodeGroup' { _pcgCountry :: !(Maybe Text) , _pcgPostalCodeRanges :: !(Maybe [PostalCodeRange]) , _pcgName :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'PostalCodeGroup' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pcgCountry' -- -- * 'pcgPostalCodeRanges' -- -- * 'pcgName' postalCodeGroup :: PostalCodeGroup postalCodeGroup = PostalCodeGroup' { _pcgCountry = Nothing , _pcgPostalCodeRanges = Nothing , _pcgName = Nothing } -- | The CLDR territory code of the country the postal code group applies to. -- Required. pcgCountry :: Lens' PostalCodeGroup (Maybe Text) pcgCountry = lens _pcgCountry (\ s a -> s{_pcgCountry = a}) -- | A range of postal codes. Required. pcgPostalCodeRanges :: Lens' PostalCodeGroup [PostalCodeRange] pcgPostalCodeRanges = lens _pcgPostalCodeRanges (\ s a -> s{_pcgPostalCodeRanges = a}) . _Default . _Coerce -- | The name of the postal code group, referred to in headers. Required. pcgName :: Lens' PostalCodeGroup (Maybe Text) pcgName = lens _pcgName (\ s a -> s{_pcgName = a}) instance FromJSON PostalCodeGroup where parseJSON = withObject "PostalCodeGroup" (\ o -> PostalCodeGroup' <$> (o .:? "country") <*> (o .:? "postalCodeRanges" .!= mempty) <*> (o .:? "name")) instance ToJSON PostalCodeGroup where toJSON PostalCodeGroup'{..} = object (catMaybes [("country" .=) <$> _pcgCountry, ("postalCodeRanges" .=) <$> _pcgPostalCodeRanges, ("name" .=) <$> _pcgName]) -- -- /See:/ 'productDestination' smart constructor. data ProductDestination = ProductDestination' { _pdIntention :: !(Maybe Text) , _pdDestinationName :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ProductDestination' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pdIntention' -- -- * 'pdDestinationName' productDestination :: ProductDestination productDestination = ProductDestination' { _pdIntention = Nothing , _pdDestinationName = Nothing } -- | Whether the destination is required, excluded or should be validated. pdIntention :: Lens' ProductDestination (Maybe Text) pdIntention = lens _pdIntention (\ s a -> s{_pdIntention = a}) -- | The name of the destination. pdDestinationName :: Lens' ProductDestination (Maybe Text) pdDestinationName = lens _pdDestinationName (\ s a -> s{_pdDestinationName = a}) instance FromJSON ProductDestination where parseJSON = withObject "ProductDestination" (\ o -> ProductDestination' <$> (o .:? "intention") <*> (o .:? "destinationName")) instance ToJSON ProductDestination where toJSON ProductDestination'{..} = object (catMaybes [("intention" .=) <$> _pdIntention, ("destinationName" .=) <$> _pdDestinationName]) -- -- /See:/ 'datafeedsCustomBatchRequest' smart constructor. newtype DatafeedsCustomBatchRequest = DatafeedsCustomBatchRequest' { _dEntries :: Maybe [DatafeedsCustomBatchRequestEntry] } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'DatafeedsCustomBatchRequest' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dEntries' datafeedsCustomBatchRequest :: DatafeedsCustomBatchRequest datafeedsCustomBatchRequest = DatafeedsCustomBatchRequest' { _dEntries = Nothing } -- | The request entries to be processed in the batch. dEntries :: Lens' DatafeedsCustomBatchRequest [DatafeedsCustomBatchRequestEntry] dEntries = lens _dEntries (\ s a -> s{_dEntries = a}) . _Default . _Coerce instance FromJSON DatafeedsCustomBatchRequest where parseJSON = withObject "DatafeedsCustomBatchRequest" (\ o -> DatafeedsCustomBatchRequest' <$> (o .:? "entries" .!= mempty)) instance ToJSON DatafeedsCustomBatchRequest where toJSON DatafeedsCustomBatchRequest'{..} = object (catMaybes [("entries" .=) <$> _dEntries]) -- -- /See:/ 'ordersCustomBatchRequestEntry' smart constructor. data OrdersCustomBatchRequestEntry = OrdersCustomBatchRequestEntry' { _ocbreMerchantId :: !(Maybe (Textual Word64)) , _ocbreCancelLineItem :: !(Maybe OrdersCustomBatchRequestEntryCancelLineItem) , _ocbreRefund :: !(Maybe OrdersCustomBatchRequestEntryRefund) , _ocbreUpdateShipment :: !(Maybe OrdersCustomBatchRequestEntryUpdateShipment) , _ocbreReturnLineItem :: !(Maybe OrdersCustomBatchRequestEntryReturnLineItem) , _ocbreMerchantOrderId :: !(Maybe Text) , _ocbreMethod :: !(Maybe Text) , _ocbreShipLineItems :: !(Maybe OrdersCustomBatchRequestEntryShipLineItems) , _ocbreOperationId :: !(Maybe Text) , _ocbreOrderId :: !(Maybe Text) , _ocbreCancel :: !(Maybe OrdersCustomBatchRequestEntryCancel) , _ocbreBatchId :: !(Maybe (Textual Word32)) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'OrdersCustomBatchRequestEntry' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ocbreMerchantId' -- -- * 'ocbreCancelLineItem' -- -- * 'ocbreRefund' -- -- * 'ocbreUpdateShipment' -- -- * 'ocbreReturnLineItem' -- -- * 'ocbreMerchantOrderId' -- -- * 'ocbreMethod' -- -- * 'ocbreShipLineItems' -- -- * 'ocbreOperationId' -- -- * 'ocbreOrderId' -- -- * 'ocbreCancel' -- -- * 'ocbreBatchId' ordersCustomBatchRequestEntry :: OrdersCustomBatchRequestEntry ordersCustomBatchRequestEntry = OrdersCustomBatchRequestEntry' { _ocbreMerchantId = Nothing , _ocbreCancelLineItem = Nothing , _ocbreRefund = Nothing , _ocbreUpdateShipment = Nothing , _ocbreReturnLineItem = Nothing , _ocbreMerchantOrderId = Nothing , _ocbreMethod = Nothing , _ocbreShipLineItems = Nothing , _ocbreOperationId = Nothing , _ocbreOrderId = Nothing , _ocbreCancel = Nothing , _ocbreBatchId = Nothing } -- | The ID of the managing account. ocbreMerchantId :: Lens' OrdersCustomBatchRequestEntry (Maybe Word64) ocbreMerchantId = lens _ocbreMerchantId (\ s a -> s{_ocbreMerchantId = a}) . mapping _Coerce -- | Required for cancelLineItem method. ocbreCancelLineItem :: Lens' OrdersCustomBatchRequestEntry (Maybe OrdersCustomBatchRequestEntryCancelLineItem) ocbreCancelLineItem = lens _ocbreCancelLineItem (\ s a -> s{_ocbreCancelLineItem = a}) -- | Required for refund method. ocbreRefund :: Lens' OrdersCustomBatchRequestEntry (Maybe OrdersCustomBatchRequestEntryRefund) ocbreRefund = lens _ocbreRefund (\ s a -> s{_ocbreRefund = a}) -- | Required for updateShipment method. ocbreUpdateShipment :: Lens' OrdersCustomBatchRequestEntry (Maybe OrdersCustomBatchRequestEntryUpdateShipment) ocbreUpdateShipment = lens _ocbreUpdateShipment (\ s a -> s{_ocbreUpdateShipment = a}) -- | Required for returnLineItem method. ocbreReturnLineItem :: Lens' OrdersCustomBatchRequestEntry (Maybe OrdersCustomBatchRequestEntryReturnLineItem) ocbreReturnLineItem = lens _ocbreReturnLineItem (\ s a -> s{_ocbreReturnLineItem = a}) -- | The merchant order id. Required for updateMerchantOrderId and -- getByMerchantOrderId methods. ocbreMerchantOrderId :: Lens' OrdersCustomBatchRequestEntry (Maybe Text) ocbreMerchantOrderId = lens _ocbreMerchantOrderId (\ s a -> s{_ocbreMerchantOrderId = a}) -- | The method to apply. ocbreMethod :: Lens' OrdersCustomBatchRequestEntry (Maybe Text) ocbreMethod = lens _ocbreMethod (\ s a -> s{_ocbreMethod = a}) -- | Required for shipLineItems method. ocbreShipLineItems :: Lens' OrdersCustomBatchRequestEntry (Maybe OrdersCustomBatchRequestEntryShipLineItems) ocbreShipLineItems = lens _ocbreShipLineItems (\ s a -> s{_ocbreShipLineItems = a}) -- | The ID of the operation. Unique across all operations for a given order. -- Required for all methods beside get and getByMerchantOrderId. ocbreOperationId :: Lens' OrdersCustomBatchRequestEntry (Maybe Text) ocbreOperationId = lens _ocbreOperationId (\ s a -> s{_ocbreOperationId = a}) -- | The ID of the order. Required for all methods beside -- getByMerchantOrderId. ocbreOrderId :: Lens' OrdersCustomBatchRequestEntry (Maybe Text) ocbreOrderId = lens _ocbreOrderId (\ s a -> s{_ocbreOrderId = a}) -- | Required for cancel method. ocbreCancel :: Lens' OrdersCustomBatchRequestEntry (Maybe OrdersCustomBatchRequestEntryCancel) ocbreCancel = lens _ocbreCancel (\ s a -> s{_ocbreCancel = a}) -- | An entry ID, unique within the batch request. ocbreBatchId :: Lens' OrdersCustomBatchRequestEntry (Maybe Word32) ocbreBatchId = lens _ocbreBatchId (\ s a -> s{_ocbreBatchId = a}) . mapping _Coerce instance FromJSON OrdersCustomBatchRequestEntry where parseJSON = withObject "OrdersCustomBatchRequestEntry" (\ o -> OrdersCustomBatchRequestEntry' <$> (o .:? "merchantId") <*> (o .:? "cancelLineItem") <*> (o .:? "refund") <*> (o .:? "updateShipment") <*> (o .:? "returnLineItem") <*> (o .:? "merchantOrderId") <*> (o .:? "method") <*> (o .:? "shipLineItems") <*> (o .:? "operationId") <*> (o .:? "orderId") <*> (o .:? "cancel") <*> (o .:? "batchId")) instance ToJSON OrdersCustomBatchRequestEntry where toJSON OrdersCustomBatchRequestEntry'{..} = object (catMaybes [("merchantId" .=) <$> _ocbreMerchantId, ("cancelLineItem" .=) <$> _ocbreCancelLineItem, ("refund" .=) <$> _ocbreRefund, ("updateShipment" .=) <$> _ocbreUpdateShipment, ("returnLineItem" .=) <$> _ocbreReturnLineItem, ("merchantOrderId" .=) <$> _ocbreMerchantOrderId, ("method" .=) <$> _ocbreMethod, ("shipLineItems" .=) <$> _ocbreShipLineItems, ("operationId" .=) <$> _ocbreOperationId, ("orderId" .=) <$> _ocbreOrderId, ("cancel" .=) <$> _ocbreCancel, ("batchId" .=) <$> _ocbreBatchId]) -- -- /See:/ 'ordersRefundRequest' smart constructor. data OrdersRefundRequest = OrdersRefundRequest' { _orrAmount :: !(Maybe Price) , _orrReason :: !(Maybe Text) , _orrOperationId :: !(Maybe Text) , _orrReasonText :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'OrdersRefundRequest' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'orrAmount' -- -- * 'orrReason' -- -- * 'orrOperationId' -- -- * 'orrReasonText' ordersRefundRequest :: OrdersRefundRequest ordersRefundRequest = OrdersRefundRequest' { _orrAmount = Nothing , _orrReason = Nothing , _orrOperationId = Nothing , _orrReasonText = Nothing } -- | The amount that is refunded. orrAmount :: Lens' OrdersRefundRequest (Maybe Price) orrAmount = lens _orrAmount (\ s a -> s{_orrAmount = a}) -- | The reason for the refund. orrReason :: Lens' OrdersRefundRequest (Maybe Text) orrReason = lens _orrReason (\ s a -> s{_orrReason = a}) -- | The ID of the operation. Unique across all operations for a given order. orrOperationId :: Lens' OrdersRefundRequest (Maybe Text) orrOperationId = lens _orrOperationId (\ s a -> s{_orrOperationId = a}) -- | The explanation of the reason. orrReasonText :: Lens' OrdersRefundRequest (Maybe Text) orrReasonText = lens _orrReasonText (\ s a -> s{_orrReasonText = a}) instance FromJSON OrdersRefundRequest where parseJSON = withObject "OrdersRefundRequest" (\ o -> OrdersRefundRequest' <$> (o .:? "amount") <*> (o .:? "reason") <*> (o .:? "operationId") <*> (o .:? "reasonText")) instance ToJSON OrdersRefundRequest where toJSON OrdersRefundRequest'{..} = object (catMaybes [("amount" .=) <$> _orrAmount, ("reason" .=) <$> _orrReason, ("operationId" .=) <$> _orrOperationId, ("reasonText" .=) <$> _orrReasonText]) -- | Shipping cost calculation method. Exactly one of the field is set. -- -- /See:/ 'accountShippingShippingServiceCalculationMethod' smart constructor. data AccountShippingShippingServiceCalculationMethod = AccountShippingShippingServiceCalculationMethod' { _assscmPercentageRate :: !(Maybe Text) , _assscmCarrierRate :: !(Maybe Text) , _assscmRateTable :: !(Maybe Text) , _assscmExcluded :: !(Maybe Bool) , _assscmFlatRate :: !(Maybe Price) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'AccountShippingShippingServiceCalculationMethod' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'assscmPercentageRate' -- -- * 'assscmCarrierRate' -- -- * 'assscmRateTable' -- -- * 'assscmExcluded' -- -- * 'assscmFlatRate' accountShippingShippingServiceCalculationMethod :: AccountShippingShippingServiceCalculationMethod accountShippingShippingServiceCalculationMethod = AccountShippingShippingServiceCalculationMethod' { _assscmPercentageRate = Nothing , _assscmCarrierRate = Nothing , _assscmRateTable = Nothing , _assscmExcluded = Nothing , _assscmFlatRate = Nothing } -- | Percentage of the price, represented as a floating point number without -- the percentage character. assscmPercentageRate :: Lens' AccountShippingShippingServiceCalculationMethod (Maybe Text) assscmPercentageRate = lens _assscmPercentageRate (\ s a -> s{_assscmPercentageRate = a}) -- | Name of the carrier rate to use for the calculation. assscmCarrierRate :: Lens' AccountShippingShippingServiceCalculationMethod (Maybe Text) assscmCarrierRate = lens _assscmCarrierRate (\ s a -> s{_assscmCarrierRate = a}) -- | Name of the rate table to use for the calculation. assscmRateTable :: Lens' AccountShippingShippingServiceCalculationMethod (Maybe Text) assscmRateTable = lens _assscmRateTable (\ s a -> s{_assscmRateTable = a}) -- | Delivery is excluded. Valid only within cost rules tree. assscmExcluded :: Lens' AccountShippingShippingServiceCalculationMethod (Maybe Bool) assscmExcluded = lens _assscmExcluded (\ s a -> s{_assscmExcluded = a}) -- | Fixed price shipping, represented as a floating point number associated -- with a currency. assscmFlatRate :: Lens' AccountShippingShippingServiceCalculationMethod (Maybe Price) assscmFlatRate = lens _assscmFlatRate (\ s a -> s{_assscmFlatRate = a}) instance FromJSON AccountShippingShippingServiceCalculationMethod where parseJSON = withObject "AccountShippingShippingServiceCalculationMethod" (\ o -> AccountShippingShippingServiceCalculationMethod' <$> (o .:? "percentageRate") <*> (o .:? "carrierRate") <*> (o .:? "rateTable") <*> (o .:? "excluded") <*> (o .:? "flatRate")) instance ToJSON AccountShippingShippingServiceCalculationMethod where toJSON AccountShippingShippingServiceCalculationMethod'{..} = object (catMaybes [("percentageRate" .=) <$> _assscmPercentageRate, ("carrierRate" .=) <$> _assscmCarrierRate, ("rateTable" .=) <$> _assscmRateTable, ("excluded" .=) <$> _assscmExcluded, ("flatRate" .=) <$> _assscmFlatRate]) -- -- /See:/ 'ordersCustomBatchRequestEntryCancelLineItem' smart constructor. data OrdersCustomBatchRequestEntryCancelLineItem = OrdersCustomBatchRequestEntryCancelLineItem' { _ocbrecliAmount :: !(Maybe Price) , _ocbrecliQuantity :: !(Maybe (Textual Word32)) , _ocbrecliLineItemId :: !(Maybe Text) , _ocbrecliReason :: !(Maybe Text) , _ocbrecliReasonText :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'OrdersCustomBatchRequestEntryCancelLineItem' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ocbrecliAmount' -- -- * 'ocbrecliQuantity' -- -- * 'ocbrecliLineItemId' -- -- * 'ocbrecliReason' -- -- * 'ocbrecliReasonText' ordersCustomBatchRequestEntryCancelLineItem :: OrdersCustomBatchRequestEntryCancelLineItem ordersCustomBatchRequestEntryCancelLineItem = OrdersCustomBatchRequestEntryCancelLineItem' { _ocbrecliAmount = Nothing , _ocbrecliQuantity = Nothing , _ocbrecliLineItemId = Nothing , _ocbrecliReason = Nothing , _ocbrecliReasonText = Nothing } -- | Amount to refund for the cancelation. Optional. If not set, Google will -- calculate the default based on the price and tax of the items involved. -- The amount must not be larger than the net amount left on the order. ocbrecliAmount :: Lens' OrdersCustomBatchRequestEntryCancelLineItem (Maybe Price) ocbrecliAmount = lens _ocbrecliAmount (\ s a -> s{_ocbrecliAmount = a}) -- | The quantity to cancel. ocbrecliQuantity :: Lens' OrdersCustomBatchRequestEntryCancelLineItem (Maybe Word32) ocbrecliQuantity = lens _ocbrecliQuantity (\ s a -> s{_ocbrecliQuantity = a}) . mapping _Coerce -- | The ID of the line item to cancel. ocbrecliLineItemId :: Lens' OrdersCustomBatchRequestEntryCancelLineItem (Maybe Text) ocbrecliLineItemId = lens _ocbrecliLineItemId (\ s a -> s{_ocbrecliLineItemId = a}) -- | The reason for the cancellation. ocbrecliReason :: Lens' OrdersCustomBatchRequestEntryCancelLineItem (Maybe Text) ocbrecliReason = lens _ocbrecliReason (\ s a -> s{_ocbrecliReason = a}) -- | The explanation of the reason. ocbrecliReasonText :: Lens' OrdersCustomBatchRequestEntryCancelLineItem (Maybe Text) ocbrecliReasonText = lens _ocbrecliReasonText (\ s a -> s{_ocbrecliReasonText = a}) instance FromJSON OrdersCustomBatchRequestEntryCancelLineItem where parseJSON = withObject "OrdersCustomBatchRequestEntryCancelLineItem" (\ o -> OrdersCustomBatchRequestEntryCancelLineItem' <$> (o .:? "amount") <*> (o .:? "quantity") <*> (o .:? "lineItemId") <*> (o .:? "reason") <*> (o .:? "reasonText")) instance ToJSON OrdersCustomBatchRequestEntryCancelLineItem where toJSON OrdersCustomBatchRequestEntryCancelLineItem'{..} = object (catMaybes [("amount" .=) <$> _ocbrecliAmount, ("quantity" .=) <$> _ocbrecliQuantity, ("lineItemId" .=) <$> _ocbrecliLineItemId, ("reason" .=) <$> _ocbrecliReason, ("reasonText" .=) <$> _ocbrecliReasonText]) -- -- /See:/ 'orderLineItemShippingDetailsMethod' smart constructor. data OrderLineItemShippingDetailsMethod = OrderLineItemShippingDetailsMethod' { _olisdmCarrier :: !(Maybe Text) , _olisdmMethodName :: !(Maybe Text) , _olisdmMaxDaysInTransit :: !(Maybe (Textual Word32)) , _olisdmMinDaysInTransit :: !(Maybe (Textual Word32)) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'OrderLineItemShippingDetailsMethod' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'olisdmCarrier' -- -- * 'olisdmMethodName' -- -- * 'olisdmMaxDaysInTransit' -- -- * 'olisdmMinDaysInTransit' orderLineItemShippingDetailsMethod :: OrderLineItemShippingDetailsMethod orderLineItemShippingDetailsMethod = OrderLineItemShippingDetailsMethod' { _olisdmCarrier = Nothing , _olisdmMethodName = Nothing , _olisdmMaxDaysInTransit = Nothing , _olisdmMinDaysInTransit = Nothing } -- | The carrier for the shipping. Optional. olisdmCarrier :: Lens' OrderLineItemShippingDetailsMethod (Maybe Text) olisdmCarrier = lens _olisdmCarrier (\ s a -> s{_olisdmCarrier = a}) -- | The name of the shipping method. olisdmMethodName :: Lens' OrderLineItemShippingDetailsMethod (Maybe Text) olisdmMethodName = lens _olisdmMethodName (\ s a -> s{_olisdmMethodName = a}) -- | Maximum transit time. olisdmMaxDaysInTransit :: Lens' OrderLineItemShippingDetailsMethod (Maybe Word32) olisdmMaxDaysInTransit = lens _olisdmMaxDaysInTransit (\ s a -> s{_olisdmMaxDaysInTransit = a}) . mapping _Coerce -- | Minimum transit time. olisdmMinDaysInTransit :: Lens' OrderLineItemShippingDetailsMethod (Maybe Word32) olisdmMinDaysInTransit = lens _olisdmMinDaysInTransit (\ s a -> s{_olisdmMinDaysInTransit = a}) . mapping _Coerce instance FromJSON OrderLineItemShippingDetailsMethod where parseJSON = withObject "OrderLineItemShippingDetailsMethod" (\ o -> OrderLineItemShippingDetailsMethod' <$> (o .:? "carrier") <*> (o .:? "methodName") <*> (o .:? "maxDaysInTransit") <*> (o .:? "minDaysInTransit")) instance ToJSON OrderLineItemShippingDetailsMethod where toJSON OrderLineItemShippingDetailsMethod'{..} = object (catMaybes [("carrier" .=) <$> _olisdmCarrier, ("methodName" .=) <$> _olisdmMethodName, ("maxDaysInTransit" .=) <$> _olisdmMaxDaysInTransit, ("minDaysInTransit" .=) <$> _olisdmMinDaysInTransit]) -- | Datafeed data. -- -- /See:/ 'datafeed' smart constructor. data Datafeed = Datafeed' { _dKind :: !Text , _dFormat :: !(Maybe DatafeedFormat) , _dAttributeLanguage :: !(Maybe Text) , _dTargetCountry :: !(Maybe Text) , _dFetchSchedule :: !(Maybe DatafeedFetchSchedule) , _dName :: !(Maybe Text) , _dIntendedDestinations :: !(Maybe [Text]) , _dId :: !(Maybe (Textual Int64)) , _dContentLanguage :: !(Maybe Text) , _dContentType :: !(Maybe Text) , _dFileName :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'Datafeed' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dKind' -- -- * 'dFormat' -- -- * 'dAttributeLanguage' -- -- * 'dTargetCountry' -- -- * 'dFetchSchedule' -- -- * 'dName' -- -- * 'dIntendedDestinations' -- -- * 'dId' -- -- * 'dContentLanguage' -- -- * 'dContentType' -- -- * 'dFileName' datafeed :: Datafeed datafeed = Datafeed' { _dKind = "content#datafeed" , _dFormat = Nothing , _dAttributeLanguage = Nothing , _dTargetCountry = Nothing , _dFetchSchedule = Nothing , _dName = Nothing , _dIntendedDestinations = Nothing , _dId = Nothing , _dContentLanguage = Nothing , _dContentType = Nothing , _dFileName = Nothing } -- | Identifies what kind of resource this is. Value: the fixed string -- \"content#datafeed\". dKind :: Lens' Datafeed Text dKind = lens _dKind (\ s a -> s{_dKind = a}) -- | Format of the feed file. dFormat :: Lens' Datafeed (Maybe DatafeedFormat) dFormat = lens _dFormat (\ s a -> s{_dFormat = a}) -- | The two-letter ISO 639-1 language in which the attributes are defined in -- the data feed. dAttributeLanguage :: Lens' Datafeed (Maybe Text) dAttributeLanguage = lens _dAttributeLanguage (\ s a -> s{_dAttributeLanguage = a}) -- | The country where the items in the feed will be included in the search -- index, represented as a CLDR territory code. dTargetCountry :: Lens' Datafeed (Maybe Text) dTargetCountry = lens _dTargetCountry (\ s a -> s{_dTargetCountry = a}) -- | Fetch schedule for the feed file. dFetchSchedule :: Lens' Datafeed (Maybe DatafeedFetchSchedule) dFetchSchedule = lens _dFetchSchedule (\ s a -> s{_dFetchSchedule = a}) -- | A descriptive name of the data feed. dName :: Lens' Datafeed (Maybe Text) dName = lens _dName (\ s a -> s{_dName = a}) -- | The list of intended destinations (corresponds to checked check boxes in -- Merchant Center). dIntendedDestinations :: Lens' Datafeed [Text] dIntendedDestinations = lens _dIntendedDestinations (\ s a -> s{_dIntendedDestinations = a}) . _Default . _Coerce -- | The ID of the data feed. dId :: Lens' Datafeed (Maybe Int64) dId = lens _dId (\ s a -> s{_dId = a}) . mapping _Coerce -- | The two-letter ISO 639-1 language of the items in the feed. Must be a -- valid language for targetCountry. dContentLanguage :: Lens' Datafeed (Maybe Text) dContentLanguage = lens _dContentLanguage (\ s a -> s{_dContentLanguage = a}) -- | The type of data feed. dContentType :: Lens' Datafeed (Maybe Text) dContentType = lens _dContentType (\ s a -> s{_dContentType = a}) -- | The filename of the feed. All feeds must have a unique file name. dFileName :: Lens' Datafeed (Maybe Text) dFileName = lens _dFileName (\ s a -> s{_dFileName = a}) instance FromJSON Datafeed where parseJSON = withObject "Datafeed" (\ o -> Datafeed' <$> (o .:? "kind" .!= "content#datafeed") <*> (o .:? "format") <*> (o .:? "attributeLanguage") <*> (o .:? "targetCountry") <*> (o .:? "fetchSchedule") <*> (o .:? "name") <*> (o .:? "intendedDestinations" .!= mempty) <*> (o .:? "id") <*> (o .:? "contentLanguage") <*> (o .:? "contentType") <*> (o .:? "fileName")) instance ToJSON Datafeed where toJSON Datafeed'{..} = object (catMaybes [Just ("kind" .= _dKind), ("format" .=) <$> _dFormat, ("attributeLanguage" .=) <$> _dAttributeLanguage, ("targetCountry" .=) <$> _dTargetCountry, ("fetchSchedule" .=) <$> _dFetchSchedule, ("name" .=) <$> _dName, ("intendedDestinations" .=) <$> _dIntendedDestinations, ("id" .=) <$> _dId, ("contentLanguage" .=) <$> _dContentLanguage, ("contentType" .=) <$> _dContentType, ("fileName" .=) <$> _dFileName]) -- -- /See:/ 'ordersCreateTestOrderResponse' smart constructor. data OrdersCreateTestOrderResponse = OrdersCreateTestOrderResponse' { _octorKind :: !Text , _octorOrderId :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'OrdersCreateTestOrderResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'octorKind' -- -- * 'octorOrderId' ordersCreateTestOrderResponse :: OrdersCreateTestOrderResponse ordersCreateTestOrderResponse = OrdersCreateTestOrderResponse' { _octorKind = "content#ordersCreateTestOrderResponse" , _octorOrderId = Nothing } -- | Identifies what kind of resource this is. Value: the fixed string -- \"content#ordersCreateTestOrderResponse\". octorKind :: Lens' OrdersCreateTestOrderResponse Text octorKind = lens _octorKind (\ s a -> s{_octorKind = a}) -- | The ID of the newly created test order. octorOrderId :: Lens' OrdersCreateTestOrderResponse (Maybe Text) octorOrderId = lens _octorOrderId (\ s a -> s{_octorOrderId = a}) instance FromJSON OrdersCreateTestOrderResponse where parseJSON = withObject "OrdersCreateTestOrderResponse" (\ o -> OrdersCreateTestOrderResponse' <$> (o .:? "kind" .!= "content#ordersCreateTestOrderResponse") <*> (o .:? "orderId")) instance ToJSON OrdersCreateTestOrderResponse where toJSON OrdersCreateTestOrderResponse'{..} = object (catMaybes [Just ("kind" .= _octorKind), ("orderId" .=) <$> _octorOrderId]) -- | A batch entry encoding a single non-batch accounts response. -- -- /See:/ 'accountsCustomBatchResponseEntry' smart constructor. data AccountsCustomBatchResponseEntry = AccountsCustomBatchResponseEntry' { _aKind :: !Text , _aAccount :: !(Maybe Account) , _aErrors :: !(Maybe Errors) , _aBatchId :: !(Maybe (Textual Word32)) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'AccountsCustomBatchResponseEntry' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'aKind' -- -- * 'aAccount' -- -- * 'aErrors' -- -- * 'aBatchId' accountsCustomBatchResponseEntry :: AccountsCustomBatchResponseEntry accountsCustomBatchResponseEntry = AccountsCustomBatchResponseEntry' { _aKind = "content#accountsCustomBatchResponseEntry" , _aAccount = Nothing , _aErrors = Nothing , _aBatchId = Nothing } -- | Identifies what kind of resource this is. Value: the fixed string -- \"content#accountsCustomBatchResponseEntry\". aKind :: Lens' AccountsCustomBatchResponseEntry Text aKind = lens _aKind (\ s a -> s{_aKind = a}) -- | The retrieved, created, or updated account. Not defined if the method -- was delete. aAccount :: Lens' AccountsCustomBatchResponseEntry (Maybe Account) aAccount = lens _aAccount (\ s a -> s{_aAccount = a}) -- | A list of errors defined if and only if the request failed. aErrors :: Lens' AccountsCustomBatchResponseEntry (Maybe Errors) aErrors = lens _aErrors (\ s a -> s{_aErrors = a}) -- | The ID of the request entry this entry responds to. aBatchId :: Lens' AccountsCustomBatchResponseEntry (Maybe Word32) aBatchId = lens _aBatchId (\ s a -> s{_aBatchId = a}) . mapping _Coerce instance FromJSON AccountsCustomBatchResponseEntry where parseJSON = withObject "AccountsCustomBatchResponseEntry" (\ o -> AccountsCustomBatchResponseEntry' <$> (o .:? "kind" .!= "content#accountsCustomBatchResponseEntry") <*> (o .:? "account") <*> (o .:? "errors") <*> (o .:? "batchId")) instance ToJSON AccountsCustomBatchResponseEntry where toJSON AccountsCustomBatchResponseEntry'{..} = object (catMaybes [Just ("kind" .= _aKind), ("account" .=) <$> _aAccount, ("errors" .=) <$> _aErrors, ("batchId" .=) <$> _aBatchId]) -- -- /See:/ 'accountIdentifier' smart constructor. data AccountIdentifier = AccountIdentifier' { _aiMerchantId :: !(Maybe (Textual Word64)) , _aiAggregatorId :: !(Maybe (Textual Word64)) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'AccountIdentifier' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'aiMerchantId' -- -- * 'aiAggregatorId' accountIdentifier :: AccountIdentifier accountIdentifier = AccountIdentifier' { _aiMerchantId = Nothing , _aiAggregatorId = Nothing } -- | The merchant account ID, set for individual accounts and subaccounts. aiMerchantId :: Lens' AccountIdentifier (Maybe Word64) aiMerchantId = lens _aiMerchantId (\ s a -> s{_aiMerchantId = a}) . mapping _Coerce -- | The aggregator ID, set for aggregators and subaccounts (in that case, it -- represents the aggregator of the subaccount). aiAggregatorId :: Lens' AccountIdentifier (Maybe Word64) aiAggregatorId = lens _aiAggregatorId (\ s a -> s{_aiAggregatorId = a}) . mapping _Coerce instance FromJSON AccountIdentifier where parseJSON = withObject "AccountIdentifier" (\ o -> AccountIdentifier' <$> (o .:? "merchantId") <*> (o .:? "aggregatorId")) instance ToJSON AccountIdentifier where toJSON AccountIdentifier'{..} = object (catMaybes [("merchantId" .=) <$> _aiMerchantId, ("aggregatorId" .=) <$> _aiAggregatorId]) -- -- /See:/ 'testOrderPaymentMethod' smart constructor. data TestOrderPaymentMethod = TestOrderPaymentMethod' { _topmExpirationMonth :: !(Maybe (Textual Int32)) , _topmExpirationYear :: !(Maybe (Textual Int32)) , _topmLastFourDigits :: !(Maybe Text) , _topmType :: !(Maybe Text) , _topmPredefinedBillingAddress :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'TestOrderPaymentMethod' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'topmExpirationMonth' -- -- * 'topmExpirationYear' -- -- * 'topmLastFourDigits' -- -- * 'topmType' -- -- * 'topmPredefinedBillingAddress' testOrderPaymentMethod :: TestOrderPaymentMethod testOrderPaymentMethod = TestOrderPaymentMethod' { _topmExpirationMonth = Nothing , _topmExpirationYear = Nothing , _topmLastFourDigits = Nothing , _topmType = Nothing , _topmPredefinedBillingAddress = Nothing } -- | The card expiration month (January = 1, February = 2 etc.). topmExpirationMonth :: Lens' TestOrderPaymentMethod (Maybe Int32) topmExpirationMonth = lens _topmExpirationMonth (\ s a -> s{_topmExpirationMonth = a}) . mapping _Coerce -- | The card expiration year (4-digit, e.g. 2015). topmExpirationYear :: Lens' TestOrderPaymentMethod (Maybe Int32) topmExpirationYear = lens _topmExpirationYear (\ s a -> s{_topmExpirationYear = a}) . mapping _Coerce -- | The last four digits of the card number. topmLastFourDigits :: Lens' TestOrderPaymentMethod (Maybe Text) topmLastFourDigits = lens _topmLastFourDigits (\ s a -> s{_topmLastFourDigits = a}) -- | The type of instrument. Note that real orders might have different -- values than the four values accepted by createTestOrder. topmType :: Lens' TestOrderPaymentMethod (Maybe Text) topmType = lens _topmType (\ s a -> s{_topmType = a}) -- | The billing address. topmPredefinedBillingAddress :: Lens' TestOrderPaymentMethod (Maybe Text) topmPredefinedBillingAddress = lens _topmPredefinedBillingAddress (\ s a -> s{_topmPredefinedBillingAddress = a}) instance FromJSON TestOrderPaymentMethod where parseJSON = withObject "TestOrderPaymentMethod" (\ o -> TestOrderPaymentMethod' <$> (o .:? "expirationMonth") <*> (o .:? "expirationYear") <*> (o .:? "lastFourDigits") <*> (o .:? "type") <*> (o .:? "predefinedBillingAddress")) instance ToJSON TestOrderPaymentMethod where toJSON TestOrderPaymentMethod'{..} = object (catMaybes [("expirationMonth" .=) <$> _topmExpirationMonth, ("expirationYear" .=) <$> _topmExpirationYear, ("lastFourDigits" .=) <$> _topmLastFourDigits, ("type" .=) <$> _topmType, ("predefinedBillingAddress" .=) <$> _topmPredefinedBillingAddress]) -- -- /See:/ 'orderLineItem' smart constructor. data OrderLineItem = OrderLineItem' { _oliQuantityOrdered :: !(Maybe (Textual Word32)) , _oliReturnInfo :: !(Maybe OrderLineItemReturnInfo) , _oliQuantityDelivered :: !(Maybe (Textual Word32)) , _oliShippingDetails :: !(Maybe OrderLineItemShippingDetails) , _oliQuantityPending :: !(Maybe (Textual Word32)) , _oliCancellations :: !(Maybe [OrderCancellation]) , _oliQuantityCanceled :: !(Maybe (Textual Word32)) , _oliId :: !(Maybe Text) , _oliTax :: !(Maybe Price) , _oliPrice :: !(Maybe Price) , _oliQuantityShipped :: !(Maybe (Textual Word32)) , _oliQuantityReturned :: !(Maybe (Textual Word32)) , _oliProduct :: !(Maybe OrderLineItemProduct) , _oliReturns :: !(Maybe [OrderReturn]) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'OrderLineItem' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'oliQuantityOrdered' -- -- * 'oliReturnInfo' -- -- * 'oliQuantityDelivered' -- -- * 'oliShippingDetails' -- -- * 'oliQuantityPending' -- -- * 'oliCancellations' -- -- * 'oliQuantityCanceled' -- -- * 'oliId' -- -- * 'oliTax' -- -- * 'oliPrice' -- -- * 'oliQuantityShipped' -- -- * 'oliQuantityReturned' -- -- * 'oliProduct' -- -- * 'oliReturns' orderLineItem :: OrderLineItem orderLineItem = OrderLineItem' { _oliQuantityOrdered = Nothing , _oliReturnInfo = Nothing , _oliQuantityDelivered = Nothing , _oliShippingDetails = Nothing , _oliQuantityPending = Nothing , _oliCancellations = Nothing , _oliQuantityCanceled = Nothing , _oliId = Nothing , _oliTax = Nothing , _oliPrice = Nothing , _oliQuantityShipped = Nothing , _oliQuantityReturned = Nothing , _oliProduct = Nothing , _oliReturns = Nothing } -- | Number of items ordered. oliQuantityOrdered :: Lens' OrderLineItem (Maybe Word32) oliQuantityOrdered = lens _oliQuantityOrdered (\ s a -> s{_oliQuantityOrdered = a}) . mapping _Coerce -- | Details of the return policy for the line item. oliReturnInfo :: Lens' OrderLineItem (Maybe OrderLineItemReturnInfo) oliReturnInfo = lens _oliReturnInfo (\ s a -> s{_oliReturnInfo = a}) -- | Number of items delivered. oliQuantityDelivered :: Lens' OrderLineItem (Maybe Word32) oliQuantityDelivered = lens _oliQuantityDelivered (\ s a -> s{_oliQuantityDelivered = a}) . mapping _Coerce -- | Details of the requested shipping for the line item. oliShippingDetails :: Lens' OrderLineItem (Maybe OrderLineItemShippingDetails) oliShippingDetails = lens _oliShippingDetails (\ s a -> s{_oliShippingDetails = a}) -- | Number of items pending. oliQuantityPending :: Lens' OrderLineItem (Maybe Word32) oliQuantityPending = lens _oliQuantityPending (\ s a -> s{_oliQuantityPending = a}) . mapping _Coerce -- | Cancellations of the line item. oliCancellations :: Lens' OrderLineItem [OrderCancellation] oliCancellations = lens _oliCancellations (\ s a -> s{_oliCancellations = a}) . _Default . _Coerce -- | Number of items canceled. oliQuantityCanceled :: Lens' OrderLineItem (Maybe Word32) oliQuantityCanceled = lens _oliQuantityCanceled (\ s a -> s{_oliQuantityCanceled = a}) . mapping _Coerce -- | The id of the line item. oliId :: Lens' OrderLineItem (Maybe Text) oliId = lens _oliId (\ s a -> s{_oliId = a}) -- | Total tax amount for the line item. For example, if two items are -- purchased, and each have a cost tax of $2, the total tax amount will be -- $4. oliTax :: Lens' OrderLineItem (Maybe Price) oliTax = lens _oliTax (\ s a -> s{_oliTax = a}) -- | Total price for the line item. For example, if two items for $10 are -- purchased, the total price will be $20. oliPrice :: Lens' OrderLineItem (Maybe Price) oliPrice = lens _oliPrice (\ s a -> s{_oliPrice = a}) -- | Number of items shipped. oliQuantityShipped :: Lens' OrderLineItem (Maybe Word32) oliQuantityShipped = lens _oliQuantityShipped (\ s a -> s{_oliQuantityShipped = a}) . mapping _Coerce -- | Number of items returned. oliQuantityReturned :: Lens' OrderLineItem (Maybe Word32) oliQuantityReturned = lens _oliQuantityReturned (\ s a -> s{_oliQuantityReturned = a}) . mapping _Coerce -- | Product data from the time of the order placement. oliProduct :: Lens' OrderLineItem (Maybe OrderLineItemProduct) oliProduct = lens _oliProduct (\ s a -> s{_oliProduct = a}) -- | Returns of the line item. oliReturns :: Lens' OrderLineItem [OrderReturn] oliReturns = lens _oliReturns (\ s a -> s{_oliReturns = a}) . _Default . _Coerce instance FromJSON OrderLineItem where parseJSON = withObject "OrderLineItem" (\ o -> OrderLineItem' <$> (o .:? "quantityOrdered") <*> (o .:? "returnInfo") <*> (o .:? "quantityDelivered") <*> (o .:? "shippingDetails") <*> (o .:? "quantityPending") <*> (o .:? "cancellations" .!= mempty) <*> (o .:? "quantityCanceled") <*> (o .:? "id") <*> (o .:? "tax") <*> (o .:? "price") <*> (o .:? "quantityShipped") <*> (o .:? "quantityReturned") <*> (o .:? "product") <*> (o .:? "returns" .!= mempty)) instance ToJSON OrderLineItem where toJSON OrderLineItem'{..} = object (catMaybes [("quantityOrdered" .=) <$> _oliQuantityOrdered, ("returnInfo" .=) <$> _oliReturnInfo, ("quantityDelivered" .=) <$> _oliQuantityDelivered, ("shippingDetails" .=) <$> _oliShippingDetails, ("quantityPending" .=) <$> _oliQuantityPending, ("cancellations" .=) <$> _oliCancellations, ("quantityCanceled" .=) <$> _oliQuantityCanceled, ("id" .=) <$> _oliId, ("tax" .=) <$> _oliTax, ("price" .=) <$> _oliPrice, ("quantityShipped" .=) <$> _oliQuantityShipped, ("quantityReturned" .=) <$> _oliQuantityReturned, ("product" .=) <$> _oliProduct, ("returns" .=) <$> _oliReturns]) -- -- /See:/ 'service' smart constructor. data Service = Service' { _sDeliveryCountry :: !(Maybe Text) , _sRateGroups :: !(Maybe [RateGroup]) , _sDeliveryTime :: !(Maybe DeliveryTime) , _sActive :: !(Maybe Bool) , _sName :: !(Maybe Text) , _sCurrency :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'Service' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'sDeliveryCountry' -- -- * 'sRateGroups' -- -- * 'sDeliveryTime' -- -- * 'sActive' -- -- * 'sName' -- -- * 'sCurrency' service :: Service service = Service' { _sDeliveryCountry = Nothing , _sRateGroups = Nothing , _sDeliveryTime = Nothing , _sActive = Nothing , _sName = Nothing , _sCurrency = Nothing } -- | The CLDR territory code of the country to which the service applies. -- Required. sDeliveryCountry :: Lens' Service (Maybe Text) sDeliveryCountry = lens _sDeliveryCountry (\ s a -> s{_sDeliveryCountry = a}) -- | Shipping rate group definitions. Only the last one is allowed to have an -- empty applicableShippingLabels, which means \"everything else\". The -- other applicableShippingLabels must not overlap. sRateGroups :: Lens' Service [RateGroup] sRateGroups = lens _sRateGroups (\ s a -> s{_sRateGroups = a}) . _Default . _Coerce -- | Time spent in various aspects from order to the delivery of the product. -- Required. sDeliveryTime :: Lens' Service (Maybe DeliveryTime) sDeliveryTime = lens _sDeliveryTime (\ s a -> s{_sDeliveryTime = a}) -- | A boolean exposing the active status of the shipping service. Required. sActive :: Lens' Service (Maybe Bool) sActive = lens _sActive (\ s a -> s{_sActive = a}) -- | Free-form name of the service. Must be unique within target account. -- Required. sName :: Lens' Service (Maybe Text) sName = lens _sName (\ s a -> s{_sName = a}) -- | The CLDR code of the currency to which this service applies. Must match -- that of the prices in rate groups. sCurrency :: Lens' Service (Maybe Text) sCurrency = lens _sCurrency (\ s a -> s{_sCurrency = a}) instance FromJSON Service where parseJSON = withObject "Service" (\ o -> Service' <$> (o .:? "deliveryCountry") <*> (o .:? "rateGroups" .!= mempty) <*> (o .:? "deliveryTime") <*> (o .:? "active") <*> (o .:? "name") <*> (o .:? "currency")) instance ToJSON Service where toJSON Service'{..} = object (catMaybes [("deliveryCountry" .=) <$> _sDeliveryCountry, ("rateGroups" .=) <$> _sRateGroups, ("deliveryTime" .=) <$> _sDeliveryTime, ("active" .=) <$> _sActive, ("name" .=) <$> _sName, ("currency" .=) <$> _sCurrency]) -- -- /See:/ 'productstatusesCustomBatchResponse' smart constructor. data ProductstatusesCustomBatchResponse = ProductstatusesCustomBatchResponse' { _pEntries :: !(Maybe [ProductstatusesCustomBatchResponseEntry]) , _pKind :: !Text } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ProductstatusesCustomBatchResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pEntries' -- -- * 'pKind' productstatusesCustomBatchResponse :: ProductstatusesCustomBatchResponse productstatusesCustomBatchResponse = ProductstatusesCustomBatchResponse' { _pEntries = Nothing , _pKind = "content#productstatusesCustomBatchResponse" } -- | The result of the execution of the batch requests. pEntries :: Lens' ProductstatusesCustomBatchResponse [ProductstatusesCustomBatchResponseEntry] pEntries = lens _pEntries (\ s a -> s{_pEntries = a}) . _Default . _Coerce -- | Identifies what kind of resource this is. Value: the fixed string -- \"content#productstatusesCustomBatchResponse\". pKind :: Lens' ProductstatusesCustomBatchResponse Text pKind = lens _pKind (\ s a -> s{_pKind = a}) instance FromJSON ProductstatusesCustomBatchResponse where parseJSON = withObject "ProductstatusesCustomBatchResponse" (\ o -> ProductstatusesCustomBatchResponse' <$> (o .:? "entries" .!= mempty) <*> (o .:? "kind" .!= "content#productstatusesCustomBatchResponse")) instance ToJSON ProductstatusesCustomBatchResponse where toJSON ProductstatusesCustomBatchResponse'{..} = object (catMaybes [("entries" .=) <$> _pEntries, Just ("kind" .= _pKind)]) -- -- /See:/ 'productUnitPricingMeasure' smart constructor. data ProductUnitPricingMeasure = ProductUnitPricingMeasure' { _pupmValue :: !(Maybe (Textual Double)) , _pupmUnit :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ProductUnitPricingMeasure' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pupmValue' -- -- * 'pupmUnit' productUnitPricingMeasure :: ProductUnitPricingMeasure productUnitPricingMeasure = ProductUnitPricingMeasure' { _pupmValue = Nothing , _pupmUnit = Nothing } -- | The measure of an item. pupmValue :: Lens' ProductUnitPricingMeasure (Maybe Double) pupmValue = lens _pupmValue (\ s a -> s{_pupmValue = a}) . mapping _Coerce -- | The unit of the measure. pupmUnit :: Lens' ProductUnitPricingMeasure (Maybe Text) pupmUnit = lens _pupmUnit (\ s a -> s{_pupmUnit = a}) instance FromJSON ProductUnitPricingMeasure where parseJSON = withObject "ProductUnitPricingMeasure" (\ o -> ProductUnitPricingMeasure' <$> (o .:? "value") <*> (o .:? "unit")) instance ToJSON ProductUnitPricingMeasure where toJSON ProductUnitPricingMeasure'{..} = object (catMaybes [("value" .=) <$> _pupmValue, ("unit" .=) <$> _pupmUnit]) -- -- /See:/ 'ordersUpdateShipmentRequest' smart constructor. data OrdersUpdateShipmentRequest = OrdersUpdateShipmentRequest' { _ousrCarrier :: !(Maybe Text) , _ousrStatus :: !(Maybe Text) , _ousrTrackingId :: !(Maybe Text) , _ousrShipmentId :: !(Maybe Text) , _ousrOperationId :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'OrdersUpdateShipmentRequest' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ousrCarrier' -- -- * 'ousrStatus' -- -- * 'ousrTrackingId' -- -- * 'ousrShipmentId' -- -- * 'ousrOperationId' ordersUpdateShipmentRequest :: OrdersUpdateShipmentRequest ordersUpdateShipmentRequest = OrdersUpdateShipmentRequest' { _ousrCarrier = Nothing , _ousrStatus = Nothing , _ousrTrackingId = Nothing , _ousrShipmentId = Nothing , _ousrOperationId = Nothing } -- | The carrier handling the shipment. Not updated if missing. ousrCarrier :: Lens' OrdersUpdateShipmentRequest (Maybe Text) ousrCarrier = lens _ousrCarrier (\ s a -> s{_ousrCarrier = a}) -- | New status for the shipment. Not updated if missing. ousrStatus :: Lens' OrdersUpdateShipmentRequest (Maybe Text) ousrStatus = lens _ousrStatus (\ s a -> s{_ousrStatus = a}) -- | The tracking id for the shipment. Not updated if missing. ousrTrackingId :: Lens' OrdersUpdateShipmentRequest (Maybe Text) ousrTrackingId = lens _ousrTrackingId (\ s a -> s{_ousrTrackingId = a}) -- | The ID of the shipment. ousrShipmentId :: Lens' OrdersUpdateShipmentRequest (Maybe Text) ousrShipmentId = lens _ousrShipmentId (\ s a -> s{_ousrShipmentId = a}) -- | The ID of the operation. Unique across all operations for a given order. ousrOperationId :: Lens' OrdersUpdateShipmentRequest (Maybe Text) ousrOperationId = lens _ousrOperationId (\ s a -> s{_ousrOperationId = a}) instance FromJSON OrdersUpdateShipmentRequest where parseJSON = withObject "OrdersUpdateShipmentRequest" (\ o -> OrdersUpdateShipmentRequest' <$> (o .:? "carrier") <*> (o .:? "status") <*> (o .:? "trackingId") <*> (o .:? "shipmentId") <*> (o .:? "operationId")) instance ToJSON OrdersUpdateShipmentRequest where toJSON OrdersUpdateShipmentRequest'{..} = object (catMaybes [("carrier" .=) <$> _ousrCarrier, ("status" .=) <$> _ousrStatus, ("trackingId" .=) <$> _ousrTrackingId, ("shipmentId" .=) <$> _ousrShipmentId, ("operationId" .=) <$> _ousrOperationId]) -- -- /See:/ 'orderShipmentLineItemShipment' smart constructor. data OrderShipmentLineItemShipment = OrderShipmentLineItemShipment' { _oslisQuantity :: !(Maybe (Textual Word32)) , _oslisLineItemId :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'OrderShipmentLineItemShipment' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'oslisQuantity' -- -- * 'oslisLineItemId' orderShipmentLineItemShipment :: OrderShipmentLineItemShipment orderShipmentLineItemShipment = OrderShipmentLineItemShipment' { _oslisQuantity = Nothing , _oslisLineItemId = Nothing } -- | The quantity that is shipped. oslisQuantity :: Lens' OrderShipmentLineItemShipment (Maybe Word32) oslisQuantity = lens _oslisQuantity (\ s a -> s{_oslisQuantity = a}) . mapping _Coerce -- | The id of the line item that is shipped. oslisLineItemId :: Lens' OrderShipmentLineItemShipment (Maybe Text) oslisLineItemId = lens _oslisLineItemId (\ s a -> s{_oslisLineItemId = a}) instance FromJSON OrderShipmentLineItemShipment where parseJSON = withObject "OrderShipmentLineItemShipment" (\ o -> OrderShipmentLineItemShipment' <$> (o .:? "quantity") <*> (o .:? "lineItemId")) instance ToJSON OrderShipmentLineItemShipment where toJSON OrderShipmentLineItemShipment'{..} = object (catMaybes [("quantity" .=) <$> _oslisQuantity, ("lineItemId" .=) <$> _oslisLineItemId]) -- -- /See:/ 'loyaltyPoints' smart constructor. data LoyaltyPoints = LoyaltyPoints' { _lpRatio :: !(Maybe (Textual Double)) , _lpPointsValue :: !(Maybe (Textual Int64)) , _lpName :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'LoyaltyPoints' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lpRatio' -- -- * 'lpPointsValue' -- -- * 'lpName' loyaltyPoints :: LoyaltyPoints loyaltyPoints = LoyaltyPoints' { _lpRatio = Nothing , _lpPointsValue = Nothing , _lpName = Nothing } -- | The ratio of a point when converted to currency. Google assumes currency -- based on Merchant Center settings. If ratio is left out, it defaults to -- 1.0. lpRatio :: Lens' LoyaltyPoints (Maybe Double) lpRatio = lens _lpRatio (\ s a -> s{_lpRatio = a}) . mapping _Coerce -- | The retailer\'s loyalty points in absolute value. lpPointsValue :: Lens' LoyaltyPoints (Maybe Int64) lpPointsValue = lens _lpPointsValue (\ s a -> s{_lpPointsValue = a}) . mapping _Coerce -- | Name of loyalty points program. It is recommended to limit the name to -- 12 full-width characters or 24 Roman characters. lpName :: Lens' LoyaltyPoints (Maybe Text) lpName = lens _lpName (\ s a -> s{_lpName = a}) instance FromJSON LoyaltyPoints where parseJSON = withObject "LoyaltyPoints" (\ o -> LoyaltyPoints' <$> (o .:? "ratio") <*> (o .:? "pointsValue") <*> (o .:? "name")) instance ToJSON LoyaltyPoints where toJSON LoyaltyPoints'{..} = object (catMaybes [("ratio" .=) <$> _lpRatio, ("pointsValue" .=) <$> _lpPointsValue, ("name" .=) <$> _lpName]) -- -- /See:/ 'accountshippingCustomBatchRequest' smart constructor. newtype AccountshippingCustomBatchRequest = AccountshippingCustomBatchRequest' { _acbrEntries :: Maybe [AccountshippingCustomBatchRequestEntry] } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'AccountshippingCustomBatchRequest' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'acbrEntries' accountshippingCustomBatchRequest :: AccountshippingCustomBatchRequest accountshippingCustomBatchRequest = AccountshippingCustomBatchRequest' { _acbrEntries = Nothing } -- | The request entries to be processed in the batch. acbrEntries :: Lens' AccountshippingCustomBatchRequest [AccountshippingCustomBatchRequestEntry] acbrEntries = lens _acbrEntries (\ s a -> s{_acbrEntries = a}) . _Default . _Coerce instance FromJSON AccountshippingCustomBatchRequest where parseJSON = withObject "AccountshippingCustomBatchRequest" (\ o -> AccountshippingCustomBatchRequest' <$> (o .:? "entries" .!= mempty)) instance ToJSON AccountshippingCustomBatchRequest where toJSON AccountshippingCustomBatchRequest'{..} = object (catMaybes [("entries" .=) <$> _acbrEntries]) -- -- /See:/ 'ordersCustomBatchRequestEntryShipLineItems' smart constructor. data OrdersCustomBatchRequestEntryShipLineItems = OrdersCustomBatchRequestEntryShipLineItems' { _ocbresliCarrier :: !(Maybe Text) , _ocbresliTrackingId :: !(Maybe Text) , _ocbresliShipmentId :: !(Maybe Text) , _ocbresliLineItems :: !(Maybe [OrderShipmentLineItemShipment]) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'OrdersCustomBatchRequestEntryShipLineItems' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ocbresliCarrier' -- -- * 'ocbresliTrackingId' -- -- * 'ocbresliShipmentId' -- -- * 'ocbresliLineItems' ordersCustomBatchRequestEntryShipLineItems :: OrdersCustomBatchRequestEntryShipLineItems ordersCustomBatchRequestEntryShipLineItems = OrdersCustomBatchRequestEntryShipLineItems' { _ocbresliCarrier = Nothing , _ocbresliTrackingId = Nothing , _ocbresliShipmentId = Nothing , _ocbresliLineItems = Nothing } -- | The carrier handling the shipment. ocbresliCarrier :: Lens' OrdersCustomBatchRequestEntryShipLineItems (Maybe Text) ocbresliCarrier = lens _ocbresliCarrier (\ s a -> s{_ocbresliCarrier = a}) -- | The tracking id for the shipment. ocbresliTrackingId :: Lens' OrdersCustomBatchRequestEntryShipLineItems (Maybe Text) ocbresliTrackingId = lens _ocbresliTrackingId (\ s a -> s{_ocbresliTrackingId = a}) -- | The ID of the shipment. ocbresliShipmentId :: Lens' OrdersCustomBatchRequestEntryShipLineItems (Maybe Text) ocbresliShipmentId = lens _ocbresliShipmentId (\ s a -> s{_ocbresliShipmentId = a}) -- | Line items to ship. ocbresliLineItems :: Lens' OrdersCustomBatchRequestEntryShipLineItems [OrderShipmentLineItemShipment] ocbresliLineItems = lens _ocbresliLineItems (\ s a -> s{_ocbresliLineItems = a}) . _Default . _Coerce instance FromJSON OrdersCustomBatchRequestEntryShipLineItems where parseJSON = withObject "OrdersCustomBatchRequestEntryShipLineItems" (\ o -> OrdersCustomBatchRequestEntryShipLineItems' <$> (o .:? "carrier") <*> (o .:? "trackingId") <*> (o .:? "shipmentId") <*> (o .:? "lineItems" .!= mempty)) instance ToJSON OrdersCustomBatchRequestEntryShipLineItems where toJSON OrdersCustomBatchRequestEntryShipLineItems'{..} = object (catMaybes [("carrier" .=) <$> _ocbresliCarrier, ("trackingId" .=) <$> _ocbresliTrackingId, ("shipmentId" .=) <$> _ocbresliShipmentId, ("lineItems" .=) <$> _ocbresliLineItems]) -- | The status of an account, i.e., information about its products, which is -- computed offline and not returned immediately at insertion time. -- -- /See:/ 'accountStatus' smart constructor. data AccountStatus = AccountStatus' { _asDataQualityIssues :: !(Maybe [AccountStatusDataQualityIssue]) , _asKind :: !Text , _asAccountId :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'AccountStatus' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'asDataQualityIssues' -- -- * 'asKind' -- -- * 'asAccountId' accountStatus :: AccountStatus accountStatus = AccountStatus' { _asDataQualityIssues = Nothing , _asKind = "content#accountStatus" , _asAccountId = Nothing } -- | A list of data quality issues. asDataQualityIssues :: Lens' AccountStatus [AccountStatusDataQualityIssue] asDataQualityIssues = lens _asDataQualityIssues (\ s a -> s{_asDataQualityIssues = a}) . _Default . _Coerce -- | Identifies what kind of resource this is. Value: the fixed string -- \"content#accountStatus\". asKind :: Lens' AccountStatus Text asKind = lens _asKind (\ s a -> s{_asKind = a}) -- | The ID of the account for which the status is reported. asAccountId :: Lens' AccountStatus (Maybe Text) asAccountId = lens _asAccountId (\ s a -> s{_asAccountId = a}) instance FromJSON AccountStatus where parseJSON = withObject "AccountStatus" (\ o -> AccountStatus' <$> (o .:? "dataQualityIssues" .!= mempty) <*> (o .:? "kind" .!= "content#accountStatus") <*> (o .:? "accountId")) instance ToJSON AccountStatus where toJSON AccountStatus'{..} = object (catMaybes [("dataQualityIssues" .=) <$> _asDataQualityIssues, Just ("kind" .= _asKind), ("accountId" .=) <$> _asAccountId]) -- -- /See:/ 'ordersReturnLineItemRequest' smart constructor. data OrdersReturnLineItemRequest = OrdersReturnLineItemRequest' { _orlirQuantity :: !(Maybe (Textual Word32)) , _orlirLineItemId :: !(Maybe Text) , _orlirReason :: !(Maybe Text) , _orlirOperationId :: !(Maybe Text) , _orlirReasonText :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'OrdersReturnLineItemRequest' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'orlirQuantity' -- -- * 'orlirLineItemId' -- -- * 'orlirReason' -- -- * 'orlirOperationId' -- -- * 'orlirReasonText' ordersReturnLineItemRequest :: OrdersReturnLineItemRequest ordersReturnLineItemRequest = OrdersReturnLineItemRequest' { _orlirQuantity = Nothing , _orlirLineItemId = Nothing , _orlirReason = Nothing , _orlirOperationId = Nothing , _orlirReasonText = Nothing } -- | The quantity to return. orlirQuantity :: Lens' OrdersReturnLineItemRequest (Maybe Word32) orlirQuantity = lens _orlirQuantity (\ s a -> s{_orlirQuantity = a}) . mapping _Coerce -- | The ID of the line item to return. orlirLineItemId :: Lens' OrdersReturnLineItemRequest (Maybe Text) orlirLineItemId = lens _orlirLineItemId (\ s a -> s{_orlirLineItemId = a}) -- | The reason for the return. orlirReason :: Lens' OrdersReturnLineItemRequest (Maybe Text) orlirReason = lens _orlirReason (\ s a -> s{_orlirReason = a}) -- | The ID of the operation. Unique across all operations for a given order. orlirOperationId :: Lens' OrdersReturnLineItemRequest (Maybe Text) orlirOperationId = lens _orlirOperationId (\ s a -> s{_orlirOperationId = a}) -- | The explanation of the reason. orlirReasonText :: Lens' OrdersReturnLineItemRequest (Maybe Text) orlirReasonText = lens _orlirReasonText (\ s a -> s{_orlirReasonText = a}) instance FromJSON OrdersReturnLineItemRequest where parseJSON = withObject "OrdersReturnLineItemRequest" (\ o -> OrdersReturnLineItemRequest' <$> (o .:? "quantity") <*> (o .:? "lineItemId") <*> (o .:? "reason") <*> (o .:? "operationId") <*> (o .:? "reasonText")) instance ToJSON OrdersReturnLineItemRequest where toJSON OrdersReturnLineItemRequest'{..} = object (catMaybes [("quantity" .=) <$> _orlirQuantity, ("lineItemId" .=) <$> _orlirLineItemId, ("reason" .=) <$> _orlirReason, ("operationId" .=) <$> _orlirOperationId, ("reasonText" .=) <$> _orlirReasonText]) -- | A batch entry encoding a single non-batch accountshipping request. -- -- /See:/ 'shippingSettingsCustomBatchRequestEntry' smart constructor. data ShippingSettingsCustomBatchRequestEntry = ShippingSettingsCustomBatchRequestEntry' { _sscbreMerchantId :: !(Maybe (Textual Word64)) , _sscbreAccountId :: !(Maybe (Textual Word64)) , _sscbreMethod :: !(Maybe Text) , _sscbreShippingSettings :: !(Maybe ShippingSettings) , _sscbreBatchId :: !(Maybe (Textual Word32)) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ShippingSettingsCustomBatchRequestEntry' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'sscbreMerchantId' -- -- * 'sscbreAccountId' -- -- * 'sscbreMethod' -- -- * 'sscbreShippingSettings' -- -- * 'sscbreBatchId' shippingSettingsCustomBatchRequestEntry :: ShippingSettingsCustomBatchRequestEntry shippingSettingsCustomBatchRequestEntry = ShippingSettingsCustomBatchRequestEntry' { _sscbreMerchantId = Nothing , _sscbreAccountId = Nothing , _sscbreMethod = Nothing , _sscbreShippingSettings = Nothing , _sscbreBatchId = Nothing } -- | The ID of the managing account. sscbreMerchantId :: Lens' ShippingSettingsCustomBatchRequestEntry (Maybe Word64) sscbreMerchantId = lens _sscbreMerchantId (\ s a -> s{_sscbreMerchantId = a}) . mapping _Coerce -- | The ID of the account for which to get\/update account shipping -- settings. sscbreAccountId :: Lens' ShippingSettingsCustomBatchRequestEntry (Maybe Word64) sscbreAccountId = lens _sscbreAccountId (\ s a -> s{_sscbreAccountId = a}) . mapping _Coerce sscbreMethod :: Lens' ShippingSettingsCustomBatchRequestEntry (Maybe Text) sscbreMethod = lens _sscbreMethod (\ s a -> s{_sscbreMethod = a}) -- | The account shipping settings to update. Only defined if the method is -- update. sscbreShippingSettings :: Lens' ShippingSettingsCustomBatchRequestEntry (Maybe ShippingSettings) sscbreShippingSettings = lens _sscbreShippingSettings (\ s a -> s{_sscbreShippingSettings = a}) -- | An entry ID, unique within the batch request. sscbreBatchId :: Lens' ShippingSettingsCustomBatchRequestEntry (Maybe Word32) sscbreBatchId = lens _sscbreBatchId (\ s a -> s{_sscbreBatchId = a}) . mapping _Coerce instance FromJSON ShippingSettingsCustomBatchRequestEntry where parseJSON = withObject "ShippingSettingsCustomBatchRequestEntry" (\ o -> ShippingSettingsCustomBatchRequestEntry' <$> (o .:? "merchantId") <*> (o .:? "accountId") <*> (o .:? "method") <*> (o .:? "shippingSettings") <*> (o .:? "batchId")) instance ToJSON ShippingSettingsCustomBatchRequestEntry where toJSON ShippingSettingsCustomBatchRequestEntry'{..} = object (catMaybes [("merchantId" .=) <$> _sscbreMerchantId, ("accountId" .=) <$> _sscbreAccountId, ("method" .=) <$> _sscbreMethod, ("shippingSettings" .=) <$> _sscbreShippingSettings, ("batchId" .=) <$> _sscbreBatchId]) -- -- /See:/ 'accountstatusesCustomBatchRequest' smart constructor. newtype AccountstatusesCustomBatchRequest = AccountstatusesCustomBatchRequest' { _aEntries :: Maybe [AccountstatusesCustomBatchRequestEntry] } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'AccountstatusesCustomBatchRequest' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'aEntries' accountstatusesCustomBatchRequest :: AccountstatusesCustomBatchRequest accountstatusesCustomBatchRequest = AccountstatusesCustomBatchRequest' { _aEntries = Nothing } -- | The request entries to be processed in the batch. aEntries :: Lens' AccountstatusesCustomBatchRequest [AccountstatusesCustomBatchRequestEntry] aEntries = lens _aEntries (\ s a -> s{_aEntries = a}) . _Default . _Coerce instance FromJSON AccountstatusesCustomBatchRequest where parseJSON = withObject "AccountstatusesCustomBatchRequest" (\ o -> AccountstatusesCustomBatchRequest' <$> (o .:? "entries" .!= mempty)) instance ToJSON AccountstatusesCustomBatchRequest where toJSON AccountstatusesCustomBatchRequest'{..} = object (catMaybes [("entries" .=) <$> _aEntries]) -- -- /See:/ 'accounttaxListResponse' smart constructor. data AccounttaxListResponse = AccounttaxListResponse' { _alrNextPageToken :: !(Maybe Text) , _alrKind :: !Text , _alrResources :: !(Maybe [AccountTax]) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'AccounttaxListResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'alrNextPageToken' -- -- * 'alrKind' -- -- * 'alrResources' accounttaxListResponse :: AccounttaxListResponse accounttaxListResponse = AccounttaxListResponse' { _alrNextPageToken = Nothing , _alrKind = "content#accounttaxListResponse" , _alrResources = Nothing } -- | The token for the retrieval of the next page of account tax settings. alrNextPageToken :: Lens' AccounttaxListResponse (Maybe Text) alrNextPageToken = lens _alrNextPageToken (\ s a -> s{_alrNextPageToken = a}) -- | Identifies what kind of resource this is. Value: the fixed string -- \"content#accounttaxListResponse\". alrKind :: Lens' AccounttaxListResponse Text alrKind = lens _alrKind (\ s a -> s{_alrKind = a}) alrResources :: Lens' AccounttaxListResponse [AccountTax] alrResources = lens _alrResources (\ s a -> s{_alrResources = a}) . _Default . _Coerce instance FromJSON AccounttaxListResponse where parseJSON = withObject "AccounttaxListResponse" (\ o -> AccounttaxListResponse' <$> (o .:? "nextPageToken") <*> (o .:? "kind" .!= "content#accounttaxListResponse") <*> (o .:? "resources" .!= mempty)) instance ToJSON AccounttaxListResponse where toJSON AccounttaxListResponse'{..} = object (catMaybes [("nextPageToken" .=) <$> _alrNextPageToken, Just ("kind" .= _alrKind), ("resources" .=) <$> _alrResources]) -- -- /See:/ 'ordersGetTestOrderTemplateResponse' smart constructor. data OrdersGetTestOrderTemplateResponse = OrdersGetTestOrderTemplateResponse' { _ogtotrKind :: !Text , _ogtotrTemplate :: !(Maybe TestOrder) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'OrdersGetTestOrderTemplateResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ogtotrKind' -- -- * 'ogtotrTemplate' ordersGetTestOrderTemplateResponse :: OrdersGetTestOrderTemplateResponse ordersGetTestOrderTemplateResponse = OrdersGetTestOrderTemplateResponse' { _ogtotrKind = "content#ordersGetTestOrderTemplateResponse" , _ogtotrTemplate = Nothing } -- | Identifies what kind of resource this is. Value: the fixed string -- \"content#ordersGetTestOrderTemplateResponse\". ogtotrKind :: Lens' OrdersGetTestOrderTemplateResponse Text ogtotrKind = lens _ogtotrKind (\ s a -> s{_ogtotrKind = a}) -- | The requested test order template. ogtotrTemplate :: Lens' OrdersGetTestOrderTemplateResponse (Maybe TestOrder) ogtotrTemplate = lens _ogtotrTemplate (\ s a -> s{_ogtotrTemplate = a}) instance FromJSON OrdersGetTestOrderTemplateResponse where parseJSON = withObject "OrdersGetTestOrderTemplateResponse" (\ o -> OrdersGetTestOrderTemplateResponse' <$> (o .:? "kind" .!= "content#ordersGetTestOrderTemplateResponse") <*> (o .:? "template")) instance ToJSON OrdersGetTestOrderTemplateResponse where toJSON OrdersGetTestOrderTemplateResponse'{..} = object (catMaybes [Just ("kind" .= _ogtotrKind), ("template" .=) <$> _ogtotrTemplate]) -- | A batch entry encoding a single non-batch accounts request. -- -- /See:/ 'accountsCustomBatchRequestEntry' smart constructor. data AccountsCustomBatchRequestEntry = AccountsCustomBatchRequestEntry' { _accMerchantId :: !(Maybe (Textual Word64)) , _accAccount :: !(Maybe Account) , _accAccountId :: !(Maybe (Textual Word64)) , _accMethod :: !(Maybe Text) , _accBatchId :: !(Maybe (Textual Word32)) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'AccountsCustomBatchRequestEntry' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'accMerchantId' -- -- * 'accAccount' -- -- * 'accAccountId' -- -- * 'accMethod' -- -- * 'accBatchId' accountsCustomBatchRequestEntry :: AccountsCustomBatchRequestEntry accountsCustomBatchRequestEntry = AccountsCustomBatchRequestEntry' { _accMerchantId = Nothing , _accAccount = Nothing , _accAccountId = Nothing , _accMethod = Nothing , _accBatchId = Nothing } -- | The ID of the managing account. accMerchantId :: Lens' AccountsCustomBatchRequestEntry (Maybe Word64) accMerchantId = lens _accMerchantId (\ s a -> s{_accMerchantId = a}) . mapping _Coerce -- | The account to create or update. Only defined if the method is insert or -- update. accAccount :: Lens' AccountsCustomBatchRequestEntry (Maybe Account) accAccount = lens _accAccount (\ s a -> s{_accAccount = a}) -- | The ID of the account to get or delete. Only defined if the method is -- get or delete. accAccountId :: Lens' AccountsCustomBatchRequestEntry (Maybe Word64) accAccountId = lens _accAccountId (\ s a -> s{_accAccountId = a}) . mapping _Coerce accMethod :: Lens' AccountsCustomBatchRequestEntry (Maybe Text) accMethod = lens _accMethod (\ s a -> s{_accMethod = a}) -- | An entry ID, unique within the batch request. accBatchId :: Lens' AccountsCustomBatchRequestEntry (Maybe Word32) accBatchId = lens _accBatchId (\ s a -> s{_accBatchId = a}) . mapping _Coerce instance FromJSON AccountsCustomBatchRequestEntry where parseJSON = withObject "AccountsCustomBatchRequestEntry" (\ o -> AccountsCustomBatchRequestEntry' <$> (o .:? "merchantId") <*> (o .:? "account") <*> (o .:? "accountId") <*> (o .:? "method") <*> (o .:? "batchId")) instance ToJSON AccountsCustomBatchRequestEntry where toJSON AccountsCustomBatchRequestEntry'{..} = object (catMaybes [("merchantId" .=) <$> _accMerchantId, ("account" .=) <$> _accAccount, ("accountId" .=) <$> _accAccountId, ("method" .=) <$> _accMethod, ("batchId" .=) <$> _accBatchId]) -- -- /See:/ 'weight' smart constructor. data Weight = Weight' { _wValue :: !(Maybe Text) , _wUnit :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'Weight' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'wValue' -- -- * 'wUnit' weight :: Weight weight = Weight' { _wValue = Nothing , _wUnit = Nothing } -- | The weight represented as a number. wValue :: Lens' Weight (Maybe Text) wValue = lens _wValue (\ s a -> s{_wValue = a}) -- | The weight unit. wUnit :: Lens' Weight (Maybe Text) wUnit = lens _wUnit (\ s a -> s{_wUnit = a}) instance FromJSON Weight where parseJSON = withObject "Weight" (\ o -> Weight' <$> (o .:? "value") <*> (o .:? "unit")) instance ToJSON Weight where toJSON Weight'{..} = object (catMaybes [("value" .=) <$> _wValue, ("unit" .=) <$> _wUnit]) -- | An error returned by the API. -- -- /See:/ 'error'' smart constructor. data Error' = Error'' { _eDomain :: !(Maybe Text) , _eReason :: !(Maybe Text) , _eMessage :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'Error' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'eDomain' -- -- * 'eReason' -- -- * 'eMessage' error' :: Error' error' = Error'' { _eDomain = Nothing , _eReason = Nothing , _eMessage = Nothing } -- | The domain of the error. eDomain :: Lens' Error' (Maybe Text) eDomain = lens _eDomain (\ s a -> s{_eDomain = a}) -- | The error code. eReason :: Lens' Error' (Maybe Text) eReason = lens _eReason (\ s a -> s{_eReason = a}) -- | A description of the error. eMessage :: Lens' Error' (Maybe Text) eMessage = lens _eMessage (\ s a -> s{_eMessage = a}) instance FromJSON Error' where parseJSON = withObject "Error" (\ o -> Error'' <$> (o .:? "domain") <*> (o .:? "reason") <*> (o .:? "message")) instance ToJSON Error' where toJSON Error''{..} = object (catMaybes [("domain" .=) <$> _eDomain, ("reason" .=) <$> _eReason, ("message" .=) <$> _eMessage]) -- -- /See:/ 'productstatusesListResponse' smart constructor. data ProductstatusesListResponse = ProductstatusesListResponse' { _plrNextPageToken :: !(Maybe Text) , _plrKind :: !Text , _plrResources :: !(Maybe [ProductStatus]) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ProductstatusesListResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'plrNextPageToken' -- -- * 'plrKind' -- -- * 'plrResources' productstatusesListResponse :: ProductstatusesListResponse productstatusesListResponse = ProductstatusesListResponse' { _plrNextPageToken = Nothing , _plrKind = "content#productstatusesListResponse" , _plrResources = Nothing } -- | The token for the retrieval of the next page of products statuses. plrNextPageToken :: Lens' ProductstatusesListResponse (Maybe Text) plrNextPageToken = lens _plrNextPageToken (\ s a -> s{_plrNextPageToken = a}) -- | Identifies what kind of resource this is. Value: the fixed string -- \"content#productstatusesListResponse\". plrKind :: Lens' ProductstatusesListResponse Text plrKind = lens _plrKind (\ s a -> s{_plrKind = a}) plrResources :: Lens' ProductstatusesListResponse [ProductStatus] plrResources = lens _plrResources (\ s a -> s{_plrResources = a}) . _Default . _Coerce instance FromJSON ProductstatusesListResponse where parseJSON = withObject "ProductstatusesListResponse" (\ o -> ProductstatusesListResponse' <$> (o .:? "nextPageToken") <*> (o .:? "kind" .!= "content#productstatusesListResponse") <*> (o .:? "resources" .!= mempty)) instance ToJSON ProductstatusesListResponse where toJSON ProductstatusesListResponse'{..} = object (catMaybes [("nextPageToken" .=) <$> _plrNextPageToken, Just ("kind" .= _plrKind), ("resources" .=) <$> _plrResources]) -- -- /See:/ 'ordersRefundResponse' smart constructor. data OrdersRefundResponse = OrdersRefundResponse' { _orrKind :: !Text , _orrExecutionStatus :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'OrdersRefundResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'orrKind' -- -- * 'orrExecutionStatus' ordersRefundResponse :: OrdersRefundResponse ordersRefundResponse = OrdersRefundResponse' { _orrKind = "content#ordersRefundResponse" , _orrExecutionStatus = Nothing } -- | Identifies what kind of resource this is. Value: the fixed string -- \"content#ordersRefundResponse\". orrKind :: Lens' OrdersRefundResponse Text orrKind = lens _orrKind (\ s a -> s{_orrKind = a}) -- | The status of the execution. orrExecutionStatus :: Lens' OrdersRefundResponse (Maybe Text) orrExecutionStatus = lens _orrExecutionStatus (\ s a -> s{_orrExecutionStatus = a}) instance FromJSON OrdersRefundResponse where parseJSON = withObject "OrdersRefundResponse" (\ o -> OrdersRefundResponse' <$> (o .:? "kind" .!= "content#ordersRefundResponse") <*> (o .:? "executionStatus")) instance ToJSON OrdersRefundResponse where toJSON OrdersRefundResponse'{..} = object (catMaybes [Just ("kind" .= _orrKind), ("executionStatus" .=) <$> _orrExecutionStatus]) -- -- /See:/ 'ordersCreateTestOrderRequest' smart constructor. data OrdersCreateTestOrderRequest = OrdersCreateTestOrderRequest' { _octorTemplateName :: !(Maybe Text) , _octorTestOrder :: !(Maybe TestOrder) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'OrdersCreateTestOrderRequest' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'octorTemplateName' -- -- * 'octorTestOrder' ordersCreateTestOrderRequest :: OrdersCreateTestOrderRequest ordersCreateTestOrderRequest = OrdersCreateTestOrderRequest' { _octorTemplateName = Nothing , _octorTestOrder = Nothing } -- | The test order template to use. Specify as an alternative to testOrder -- as a shortcut for retrieving a template and then creating an order using -- that template. octorTemplateName :: Lens' OrdersCreateTestOrderRequest (Maybe Text) octorTemplateName = lens _octorTemplateName (\ s a -> s{_octorTemplateName = a}) -- | The test order to create. octorTestOrder :: Lens' OrdersCreateTestOrderRequest (Maybe TestOrder) octorTestOrder = lens _octorTestOrder (\ s a -> s{_octorTestOrder = a}) instance FromJSON OrdersCreateTestOrderRequest where parseJSON = withObject "OrdersCreateTestOrderRequest" (\ o -> OrdersCreateTestOrderRequest' <$> (o .:? "templateName") <*> (o .:? "testOrder")) instance ToJSON OrdersCreateTestOrderRequest where toJSON OrdersCreateTestOrderRequest'{..} = object (catMaybes [("templateName" .=) <$> _octorTemplateName, ("testOrder" .=) <$> _octorTestOrder]) -- -- /See:/ 'accountUser' smart constructor. data AccountUser = AccountUser' { _auAdmin :: !(Maybe Bool) , _auEmailAddress :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'AccountUser' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'auAdmin' -- -- * 'auEmailAddress' accountUser :: AccountUser accountUser = AccountUser' { _auAdmin = Nothing , _auEmailAddress = Nothing } -- | Whether user is an admin. auAdmin :: Lens' AccountUser (Maybe Bool) auAdmin = lens _auAdmin (\ s a -> s{_auAdmin = a}) -- | User\'s email address. auEmailAddress :: Lens' AccountUser (Maybe Text) auEmailAddress = lens _auEmailAddress (\ s a -> s{_auEmailAddress = a}) instance FromJSON AccountUser where parseJSON = withObject "AccountUser" (\ o -> AccountUser' <$> (o .:? "admin") <*> (o .:? "emailAddress")) instance ToJSON AccountUser where toJSON AccountUser'{..} = object (catMaybes [("admin" .=) <$> _auAdmin, ("emailAddress" .=) <$> _auEmailAddress]) -- | An example of an item that has poor data quality. An item value on the -- landing page differs from what is submitted, or conflicts with a policy. -- -- /See:/ 'accountStatusExampleItem' smart constructor. data AccountStatusExampleItem = AccountStatusExampleItem' { _aseiSubmittedValue :: !(Maybe Text) , _aseiLink :: !(Maybe Text) , _aseiItemId :: !(Maybe Text) , _aseiTitle :: !(Maybe Text) , _aseiValueOnLandingPage :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'AccountStatusExampleItem' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'aseiSubmittedValue' -- -- * 'aseiLink' -- -- * 'aseiItemId' -- -- * 'aseiTitle' -- -- * 'aseiValueOnLandingPage' accountStatusExampleItem :: AccountStatusExampleItem accountStatusExampleItem = AccountStatusExampleItem' { _aseiSubmittedValue = Nothing , _aseiLink = Nothing , _aseiItemId = Nothing , _aseiTitle = Nothing , _aseiValueOnLandingPage = Nothing } -- | The item value that was submitted. aseiSubmittedValue :: Lens' AccountStatusExampleItem (Maybe Text) aseiSubmittedValue = lens _aseiSubmittedValue (\ s a -> s{_aseiSubmittedValue = a}) -- | Landing page of the item. aseiLink :: Lens' AccountStatusExampleItem (Maybe Text) aseiLink = lens _aseiLink (\ s a -> s{_aseiLink = a}) -- | Unique item ID as specified in the uploaded product data. aseiItemId :: Lens' AccountStatusExampleItem (Maybe Text) aseiItemId = lens _aseiItemId (\ s a -> s{_aseiItemId = a}) -- | Title of the item. aseiTitle :: Lens' AccountStatusExampleItem (Maybe Text) aseiTitle = lens _aseiTitle (\ s a -> s{_aseiTitle = a}) -- | The actual value on the landing page. aseiValueOnLandingPage :: Lens' AccountStatusExampleItem (Maybe Text) aseiValueOnLandingPage = lens _aseiValueOnLandingPage (\ s a -> s{_aseiValueOnLandingPage = a}) instance FromJSON AccountStatusExampleItem where parseJSON = withObject "AccountStatusExampleItem" (\ o -> AccountStatusExampleItem' <$> (o .:? "submittedValue") <*> (o .:? "link") <*> (o .:? "itemId") <*> (o .:? "title") <*> (o .:? "valueOnLandingPage")) instance ToJSON AccountStatusExampleItem where toJSON AccountStatusExampleItem'{..} = object (catMaybes [("submittedValue" .=) <$> _aseiSubmittedValue, ("link" .=) <$> _aseiLink, ("itemId" .=) <$> _aseiItemId, ("title" .=) <$> _aseiTitle, ("valueOnLandingPage" .=) <$> _aseiValueOnLandingPage]) -- | A batch entry encoding a single non-batch datafeeds request. -- -- /See:/ 'datafeedsCustomBatchRequestEntry' smart constructor. data DatafeedsCustomBatchRequestEntry = DatafeedsCustomBatchRequestEntry' { _dcbreMerchantId :: !(Maybe (Textual Word64)) , _dcbreDatafeed :: !(Maybe Datafeed) , _dcbreMethod :: !(Maybe Text) , _dcbreDatafeedId :: !(Maybe (Textual Word64)) , _dcbreBatchId :: !(Maybe (Textual Word32)) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'DatafeedsCustomBatchRequestEntry' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dcbreMerchantId' -- -- * 'dcbreDatafeed' -- -- * 'dcbreMethod' -- -- * 'dcbreDatafeedId' -- -- * 'dcbreBatchId' datafeedsCustomBatchRequestEntry :: DatafeedsCustomBatchRequestEntry datafeedsCustomBatchRequestEntry = DatafeedsCustomBatchRequestEntry' { _dcbreMerchantId = Nothing , _dcbreDatafeed = Nothing , _dcbreMethod = Nothing , _dcbreDatafeedId = Nothing , _dcbreBatchId = Nothing } -- | The ID of the managing account. dcbreMerchantId :: Lens' DatafeedsCustomBatchRequestEntry (Maybe Word64) dcbreMerchantId = lens _dcbreMerchantId (\ s a -> s{_dcbreMerchantId = a}) . mapping _Coerce -- | The data feed to insert. dcbreDatafeed :: Lens' DatafeedsCustomBatchRequestEntry (Maybe Datafeed) dcbreDatafeed = lens _dcbreDatafeed (\ s a -> s{_dcbreDatafeed = a}) dcbreMethod :: Lens' DatafeedsCustomBatchRequestEntry (Maybe Text) dcbreMethod = lens _dcbreMethod (\ s a -> s{_dcbreMethod = a}) -- | The ID of the data feed to get or delete. dcbreDatafeedId :: Lens' DatafeedsCustomBatchRequestEntry (Maybe Word64) dcbreDatafeedId = lens _dcbreDatafeedId (\ s a -> s{_dcbreDatafeedId = a}) . mapping _Coerce -- | An entry ID, unique within the batch request. dcbreBatchId :: Lens' DatafeedsCustomBatchRequestEntry (Maybe Word32) dcbreBatchId = lens _dcbreBatchId (\ s a -> s{_dcbreBatchId = a}) . mapping _Coerce instance FromJSON DatafeedsCustomBatchRequestEntry where parseJSON = withObject "DatafeedsCustomBatchRequestEntry" (\ o -> DatafeedsCustomBatchRequestEntry' <$> (o .:? "merchantId") <*> (o .:? "datafeed") <*> (o .:? "method") <*> (o .:? "datafeedId") <*> (o .:? "batchId")) instance ToJSON DatafeedsCustomBatchRequestEntry where toJSON DatafeedsCustomBatchRequestEntry'{..} = object (catMaybes [("merchantId" .=) <$> _dcbreMerchantId, ("datafeed" .=) <$> _dcbreDatafeed, ("method" .=) <$> _dcbreMethod, ("datafeedId" .=) <$> _dcbreDatafeedId, ("batchId" .=) <$> _dcbreBatchId]) -- | The single value of a rate group or the value of a rate group table\'s -- cell. Exactly one of noShipping, flatRate, pricePercentage, -- carrierRateName, subtableName must be set. -- -- /See:/ 'value' smart constructor. data Value = Value' { _vPricePercentage :: !(Maybe Text) , _vCarrierRateName :: !(Maybe Text) , _vFlatRate :: !(Maybe Price) , _vSubtableName :: !(Maybe Text) , _vNoShipping :: !(Maybe Bool) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'Value' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'vPricePercentage' -- -- * 'vCarrierRateName' -- -- * 'vFlatRate' -- -- * 'vSubtableName' -- -- * 'vNoShipping' value :: Value value = Value' { _vPricePercentage = Nothing , _vCarrierRateName = Nothing , _vFlatRate = Nothing , _vSubtableName = Nothing , _vNoShipping = Nothing } -- | A percentage of the price represented as a number in decimal notation -- (e.g., \"5.4\"). Can only be set if all other fields are not set. vPricePercentage :: Lens' Value (Maybe Text) vPricePercentage = lens _vPricePercentage (\ s a -> s{_vPricePercentage = a}) -- | The name of a carrier rate referring to a carrier rate defined in the -- same rate group. Can only be set if all other fields are not set. vCarrierRateName :: Lens' Value (Maybe Text) vCarrierRateName = lens _vCarrierRateName (\ s a -> s{_vCarrierRateName = a}) -- | A flat rate. Can only be set if all other fields are not set. vFlatRate :: Lens' Value (Maybe Price) vFlatRate = lens _vFlatRate (\ s a -> s{_vFlatRate = a}) -- | The name of a subtable. Can only be set in table cells (i.e., not for -- single values), and only if all other fields are not set. vSubtableName :: Lens' Value (Maybe Text) vSubtableName = lens _vSubtableName (\ s a -> s{_vSubtableName = a}) -- | If true, then the product can\'t ship. Must be true when set, can only -- be set if all other fields are not set. vNoShipping :: Lens' Value (Maybe Bool) vNoShipping = lens _vNoShipping (\ s a -> s{_vNoShipping = a}) instance FromJSON Value where parseJSON = withObject "Value" (\ o -> Value' <$> (o .:? "pricePercentage") <*> (o .:? "carrierRateName") <*> (o .:? "flatRate") <*> (o .:? "subtableName") <*> (o .:? "noShipping")) instance ToJSON Value where toJSON Value'{..} = object (catMaybes [("pricePercentage" .=) <$> _vPricePercentage, ("carrierRateName" .=) <$> _vCarrierRateName, ("flatRate" .=) <$> _vFlatRate, ("subtableName" .=) <$> _vSubtableName, ("noShipping" .=) <$> _vNoShipping]) -- -- /See:/ 'installment' smart constructor. data Installment = Installment' { _iAmount :: !(Maybe Price) , _iMonths :: !(Maybe (Textual Int64)) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'Installment' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'iAmount' -- -- * 'iMonths' installment :: Installment installment = Installment' { _iAmount = Nothing , _iMonths = Nothing } -- | The amount the buyer has to pay per month. iAmount :: Lens' Installment (Maybe Price) iAmount = lens _iAmount (\ s a -> s{_iAmount = a}) -- | The number of installments the buyer has to pay. iMonths :: Lens' Installment (Maybe Int64) iMonths = lens _iMonths (\ s a -> s{_iMonths = a}) . mapping _Coerce instance FromJSON Installment where parseJSON = withObject "Installment" (\ o -> Installment' <$> (o .:? "amount") <*> (o .:? "months")) instance ToJSON Installment where toJSON Installment'{..} = object (catMaybes [("amount" .=) <$> _iAmount, ("months" .=) <$> _iMonths]) -- | The required fields vary based on the frequency of fetching. For a -- monthly fetch schedule, day_of_month and hour are required. For a weekly -- fetch schedule, weekday and hour are required. For a daily fetch -- schedule, only hour is required. -- -- /See:/ 'datafeedFetchSchedule' smart constructor. data DatafeedFetchSchedule = DatafeedFetchSchedule' { _dfsFetchURL :: !(Maybe Text) , _dfsUsername :: !(Maybe Text) , _dfsMinuteOfHour :: !(Maybe (Textual Word32)) , _dfsPassword :: !(Maybe Text) , _dfsDayOfMonth :: !(Maybe (Textual Word32)) , _dfsHour :: !(Maybe (Textual Word32)) , _dfsWeekday :: !(Maybe Text) , _dfsTimeZone :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'DatafeedFetchSchedule' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dfsFetchURL' -- -- * 'dfsUsername' -- -- * 'dfsMinuteOfHour' -- -- * 'dfsPassword' -- -- * 'dfsDayOfMonth' -- -- * 'dfsHour' -- -- * 'dfsWeekday' -- -- * 'dfsTimeZone' datafeedFetchSchedule :: DatafeedFetchSchedule datafeedFetchSchedule = DatafeedFetchSchedule' { _dfsFetchURL = Nothing , _dfsUsername = Nothing , _dfsMinuteOfHour = Nothing , _dfsPassword = Nothing , _dfsDayOfMonth = Nothing , _dfsHour = Nothing , _dfsWeekday = Nothing , _dfsTimeZone = Nothing } -- | The URL where the feed file can be fetched. Google Merchant Center will -- support automatic scheduled uploads using the HTTP, HTTPS, FTP, or SFTP -- protocols, so the value will need to be a valid link using one of those -- four protocols. dfsFetchURL :: Lens' DatafeedFetchSchedule (Maybe Text) dfsFetchURL = lens _dfsFetchURL (\ s a -> s{_dfsFetchURL = a}) -- | An optional user name for fetch_url. dfsUsername :: Lens' DatafeedFetchSchedule (Maybe Text) dfsUsername = lens _dfsUsername (\ s a -> s{_dfsUsername = a}) -- | The minute of the hour the feed file should be fetched (0-59). -- Read-only. dfsMinuteOfHour :: Lens' DatafeedFetchSchedule (Maybe Word32) dfsMinuteOfHour = lens _dfsMinuteOfHour (\ s a -> s{_dfsMinuteOfHour = a}) . mapping _Coerce -- | An optional password for fetch_url. dfsPassword :: Lens' DatafeedFetchSchedule (Maybe Text) dfsPassword = lens _dfsPassword (\ s a -> s{_dfsPassword = a}) -- | The day of the month the feed file should be fetched (1-31). dfsDayOfMonth :: Lens' DatafeedFetchSchedule (Maybe Word32) dfsDayOfMonth = lens _dfsDayOfMonth (\ s a -> s{_dfsDayOfMonth = a}) . mapping _Coerce -- | The hour of the day the feed file should be fetched (0-23). dfsHour :: Lens' DatafeedFetchSchedule (Maybe Word32) dfsHour = lens _dfsHour (\ s a -> s{_dfsHour = a}) . mapping _Coerce -- | The day of the week the feed file should be fetched. dfsWeekday :: Lens' DatafeedFetchSchedule (Maybe Text) dfsWeekday = lens _dfsWeekday (\ s a -> s{_dfsWeekday = a}) -- | Time zone used for schedule. UTC by default. E.g., -- \"America\/Los_Angeles\". dfsTimeZone :: Lens' DatafeedFetchSchedule (Maybe Text) dfsTimeZone = lens _dfsTimeZone (\ s a -> s{_dfsTimeZone = a}) instance FromJSON DatafeedFetchSchedule where parseJSON = withObject "DatafeedFetchSchedule" (\ o -> DatafeedFetchSchedule' <$> (o .:? "fetchUrl") <*> (o .:? "username") <*> (o .:? "minuteOfHour") <*> (o .:? "password") <*> (o .:? "dayOfMonth") <*> (o .:? "hour") <*> (o .:? "weekday") <*> (o .:? "timeZone")) instance ToJSON DatafeedFetchSchedule where toJSON DatafeedFetchSchedule'{..} = object (catMaybes [("fetchUrl" .=) <$> _dfsFetchURL, ("username" .=) <$> _dfsUsername, ("minuteOfHour" .=) <$> _dfsMinuteOfHour, ("password" .=) <$> _dfsPassword, ("dayOfMonth" .=) <$> _dfsDayOfMonth, ("hour" .=) <$> _dfsHour, ("weekday" .=) <$> _dfsWeekday, ("timeZone" .=) <$> _dfsTimeZone]) -- -- /See:/ 'ordersCustomBatchRequest' smart constructor. newtype OrdersCustomBatchRequest = OrdersCustomBatchRequest' { _ocbrEntries :: Maybe [OrdersCustomBatchRequestEntry] } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'OrdersCustomBatchRequest' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ocbrEntries' ordersCustomBatchRequest :: OrdersCustomBatchRequest ordersCustomBatchRequest = OrdersCustomBatchRequest' { _ocbrEntries = Nothing } -- | The request entries to be processed in the batch. ocbrEntries :: Lens' OrdersCustomBatchRequest [OrdersCustomBatchRequestEntry] ocbrEntries = lens _ocbrEntries (\ s a -> s{_ocbrEntries = a}) . _Default . _Coerce instance FromJSON OrdersCustomBatchRequest where parseJSON = withObject "OrdersCustomBatchRequest" (\ o -> OrdersCustomBatchRequest' <$> (o .:? "entries" .!= mempty)) instance ToJSON OrdersCustomBatchRequest where toJSON OrdersCustomBatchRequest'{..} = object (catMaybes [("entries" .=) <$> _ocbrEntries]) -- -- /See:/ 'shippingSettingsGetSupportedCarriersResponse' smart constructor. data ShippingSettingsGetSupportedCarriersResponse = ShippingSettingsGetSupportedCarriersResponse' { _ssgscrKind :: !Text , _ssgscrCarriers :: !(Maybe [CarriersCarrier]) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ShippingSettingsGetSupportedCarriersResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ssgscrKind' -- -- * 'ssgscrCarriers' shippingSettingsGetSupportedCarriersResponse :: ShippingSettingsGetSupportedCarriersResponse shippingSettingsGetSupportedCarriersResponse = ShippingSettingsGetSupportedCarriersResponse' { _ssgscrKind = "content#shippingsettingsGetSupportedCarriersResponse" , _ssgscrCarriers = Nothing } -- | Identifies what kind of resource this is. Value: the fixed string -- \"content#shippingsettingsGetSupportedCarriersResponse\". ssgscrKind :: Lens' ShippingSettingsGetSupportedCarriersResponse Text ssgscrKind = lens _ssgscrKind (\ s a -> s{_ssgscrKind = a}) -- | A list of supported carriers. May be empty. ssgscrCarriers :: Lens' ShippingSettingsGetSupportedCarriersResponse [CarriersCarrier] ssgscrCarriers = lens _ssgscrCarriers (\ s a -> s{_ssgscrCarriers = a}) . _Default . _Coerce instance FromJSON ShippingSettingsGetSupportedCarriersResponse where parseJSON = withObject "ShippingSettingsGetSupportedCarriersResponse" (\ o -> ShippingSettingsGetSupportedCarriersResponse' <$> (o .:? "kind" .!= "content#shippingsettingsGetSupportedCarriersResponse") <*> (o .:? "carriers" .!= mempty)) instance ToJSON ShippingSettingsGetSupportedCarriersResponse where toJSON ShippingSettingsGetSupportedCarriersResponse'{..} = object (catMaybes [Just ("kind" .= _ssgscrKind), ("carriers" .=) <$> _ssgscrCarriers]) -- -- /See:/ 'accountsListResponse' smart constructor. data AccountsListResponse = AccountsListResponse' { _accNextPageToken :: !(Maybe Text) , _accKind :: !Text , _accResources :: !(Maybe [Account]) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'AccountsListResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'accNextPageToken' -- -- * 'accKind' -- -- * 'accResources' accountsListResponse :: AccountsListResponse accountsListResponse = AccountsListResponse' { _accNextPageToken = Nothing , _accKind = "content#accountsListResponse" , _accResources = Nothing } -- | The token for the retrieval of the next page of accounts. accNextPageToken :: Lens' AccountsListResponse (Maybe Text) accNextPageToken = lens _accNextPageToken (\ s a -> s{_accNextPageToken = a}) -- | Identifies what kind of resource this is. Value: the fixed string -- \"content#accountsListResponse\". accKind :: Lens' AccountsListResponse Text accKind = lens _accKind (\ s a -> s{_accKind = a}) accResources :: Lens' AccountsListResponse [Account] accResources = lens _accResources (\ s a -> s{_accResources = a}) . _Default . _Coerce instance FromJSON AccountsListResponse where parseJSON = withObject "AccountsListResponse" (\ o -> AccountsListResponse' <$> (o .:? "nextPageToken") <*> (o .:? "kind" .!= "content#accountsListResponse") <*> (o .:? "resources" .!= mempty)) instance ToJSON AccountsListResponse where toJSON AccountsListResponse'{..} = object (catMaybes [("nextPageToken" .=) <$> _accNextPageToken, Just ("kind" .= _accKind), ("resources" .=) <$> _accResources]) -- -- /See:/ 'productStatusDataQualityIssue' smart constructor. data ProductStatusDataQualityIssue = ProductStatusDataQualityIssue' { _psdqiLocation :: !(Maybe Text) , _psdqiFetchStatus :: !(Maybe Text) , _psdqiSeverity :: !(Maybe Text) , _psdqiValueProvided :: !(Maybe Text) , _psdqiId :: !(Maybe Text) , _psdqiValueOnLandingPage :: !(Maybe Text) , _psdqiTimestamp :: !(Maybe Text) , _psdqiDetail :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ProductStatusDataQualityIssue' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'psdqiLocation' -- -- * 'psdqiFetchStatus' -- -- * 'psdqiSeverity' -- -- * 'psdqiValueProvided' -- -- * 'psdqiId' -- -- * 'psdqiValueOnLandingPage' -- -- * 'psdqiTimestamp' -- -- * 'psdqiDetail' productStatusDataQualityIssue :: ProductStatusDataQualityIssue productStatusDataQualityIssue = ProductStatusDataQualityIssue' { _psdqiLocation = Nothing , _psdqiFetchStatus = Nothing , _psdqiSeverity = Nothing , _psdqiValueProvided = Nothing , _psdqiId = Nothing , _psdqiValueOnLandingPage = Nothing , _psdqiTimestamp = Nothing , _psdqiDetail = Nothing } -- | The attribute name that is relevant for the issue. psdqiLocation :: Lens' ProductStatusDataQualityIssue (Maybe Text) psdqiLocation = lens _psdqiLocation (\ s a -> s{_psdqiLocation = a}) -- | The fetch status for landing_page_errors. psdqiFetchStatus :: Lens' ProductStatusDataQualityIssue (Maybe Text) psdqiFetchStatus = lens _psdqiFetchStatus (\ s a -> s{_psdqiFetchStatus = a}) -- | The severity of the data quality issue. psdqiSeverity :: Lens' ProductStatusDataQualityIssue (Maybe Text) psdqiSeverity = lens _psdqiSeverity (\ s a -> s{_psdqiSeverity = a}) -- | The value the attribute had at time of evaluation. psdqiValueProvided :: Lens' ProductStatusDataQualityIssue (Maybe Text) psdqiValueProvided = lens _psdqiValueProvided (\ s a -> s{_psdqiValueProvided = a}) -- | The id of the data quality issue. psdqiId :: Lens' ProductStatusDataQualityIssue (Maybe Text) psdqiId = lens _psdqiId (\ s a -> s{_psdqiId = a}) -- | The value of that attribute that was found on the landing page psdqiValueOnLandingPage :: Lens' ProductStatusDataQualityIssue (Maybe Text) psdqiValueOnLandingPage = lens _psdqiValueOnLandingPage (\ s a -> s{_psdqiValueOnLandingPage = a}) -- | The time stamp of the data quality issue. psdqiTimestamp :: Lens' ProductStatusDataQualityIssue (Maybe Text) psdqiTimestamp = lens _psdqiTimestamp (\ s a -> s{_psdqiTimestamp = a}) -- | A more detailed error string. psdqiDetail :: Lens' ProductStatusDataQualityIssue (Maybe Text) psdqiDetail = lens _psdqiDetail (\ s a -> s{_psdqiDetail = a}) instance FromJSON ProductStatusDataQualityIssue where parseJSON = withObject "ProductStatusDataQualityIssue" (\ o -> ProductStatusDataQualityIssue' <$> (o .:? "location") <*> (o .:? "fetchStatus") <*> (o .:? "severity") <*> (o .:? "valueProvided") <*> (o .:? "id") <*> (o .:? "valueOnLandingPage") <*> (o .:? "timestamp") <*> (o .:? "detail")) instance ToJSON ProductStatusDataQualityIssue where toJSON ProductStatusDataQualityIssue'{..} = object (catMaybes [("location" .=) <$> _psdqiLocation, ("fetchStatus" .=) <$> _psdqiFetchStatus, ("severity" .=) <$> _psdqiSeverity, ("valueProvided" .=) <$> _psdqiValueProvided, ("id" .=) <$> _psdqiId, ("valueOnLandingPage" .=) <$> _psdqiValueOnLandingPage, ("timestamp" .=) <$> _psdqiTimestamp, ("detail" .=) <$> _psdqiDetail]) -- -- /See:/ 'carriersCarrier' smart constructor. data CarriersCarrier = CarriersCarrier' { _ccCountry :: !(Maybe Text) , _ccName :: !(Maybe Text) , _ccServices :: !(Maybe [Text]) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'CarriersCarrier' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ccCountry' -- -- * 'ccName' -- -- * 'ccServices' carriersCarrier :: CarriersCarrier carriersCarrier = CarriersCarrier' { _ccCountry = Nothing , _ccName = Nothing , _ccServices = Nothing } -- | The CLDR country code of the carrier (e.g., \"US\"). Always present. ccCountry :: Lens' CarriersCarrier (Maybe Text) ccCountry = lens _ccCountry (\ s a -> s{_ccCountry = a}) -- | The name of the carrier (e.g., \"UPS\"). Always present. ccName :: Lens' CarriersCarrier (Maybe Text) ccName = lens _ccName (\ s a -> s{_ccName = a}) -- | A list of supported services (e.g., \"ground\") for that carrier. -- Contains at least one service. ccServices :: Lens' CarriersCarrier [Text] ccServices = lens _ccServices (\ s a -> s{_ccServices = a}) . _Default . _Coerce instance FromJSON CarriersCarrier where parseJSON = withObject "CarriersCarrier" (\ o -> CarriersCarrier' <$> (o .:? "country") <*> (o .:? "name") <*> (o .:? "services" .!= mempty)) instance ToJSON CarriersCarrier where toJSON CarriersCarrier'{..} = object (catMaybes [("country" .=) <$> _ccCountry, ("name" .=) <$> _ccName, ("services" .=) <$> _ccServices]) -- -- /See:/ 'carrierRate' smart constructor. data CarrierRate = CarrierRate' { _crOriginPostalCode :: !(Maybe Text) , _crFlatAdjustment :: !(Maybe Price) , _crCarrierService :: !(Maybe Text) , _crName :: !(Maybe Text) , _crPercentageAdjustment :: !(Maybe Text) , _crCarrierName :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'CarrierRate' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'crOriginPostalCode' -- -- * 'crFlatAdjustment' -- -- * 'crCarrierService' -- -- * 'crName' -- -- * 'crPercentageAdjustment' -- -- * 'crCarrierName' carrierRate :: CarrierRate carrierRate = CarrierRate' { _crOriginPostalCode = Nothing , _crFlatAdjustment = Nothing , _crCarrierService = Nothing , _crName = Nothing , _crPercentageAdjustment = Nothing , _crCarrierName = Nothing } -- | Shipping origin for this carrier rate. Required. crOriginPostalCode :: Lens' CarrierRate (Maybe Text) crOriginPostalCode = lens _crOriginPostalCode (\ s a -> s{_crOriginPostalCode = a}) -- | Additive shipping rate modifier. Can be negative. For example { -- \"value\": \"1\", \"currency\" : \"USD\" } adds $1 to the rate, { -- \"value\": \"-3\", \"currency\" : \"USD\" } removes $3 from the rate. -- Optional. crFlatAdjustment :: Lens' CarrierRate (Maybe Price) crFlatAdjustment = lens _crFlatAdjustment (\ s a -> s{_crFlatAdjustment = a}) -- | Carrier service, such as \"ground\" or \"2 days\". The list of supported -- services for a carrier can be retrieved via the getSupportedCarriers -- method. Required. crCarrierService :: Lens' CarrierRate (Maybe Text) crCarrierService = lens _crCarrierService (\ s a -> s{_crCarrierService = a}) -- | Name of the carrier rate. Must be unique per rate group. Required. crName :: Lens' CarrierRate (Maybe Text) crName = lens _crName (\ s a -> s{_crName = a}) -- | Multiplicative shipping rate modifier as a number in decimal notation. -- Can be negative. For example \"5.4\" increases the rate by 5.4%, \"-3\" -- decreases the rate by 3%. Optional. crPercentageAdjustment :: Lens' CarrierRate (Maybe Text) crPercentageAdjustment = lens _crPercentageAdjustment (\ s a -> s{_crPercentageAdjustment = a}) -- | Carrier service, such as \"UPS\" or \"Fedex\". The list of supported -- carriers can be retrieved via the getSupportedCarriers method. Required. crCarrierName :: Lens' CarrierRate (Maybe Text) crCarrierName = lens _crCarrierName (\ s a -> s{_crCarrierName = a}) instance FromJSON CarrierRate where parseJSON = withObject "CarrierRate" (\ o -> CarrierRate' <$> (o .:? "originPostalCode") <*> (o .:? "flatAdjustment") <*> (o .:? "carrierService") <*> (o .:? "name") <*> (o .:? "percentageAdjustment") <*> (o .:? "carrierName")) instance ToJSON CarrierRate where toJSON CarrierRate'{..} = object (catMaybes [("originPostalCode" .=) <$> _crOriginPostalCode, ("flatAdjustment" .=) <$> _crFlatAdjustment, ("carrierService" .=) <$> _crCarrierService, ("name" .=) <$> _crName, ("percentageAdjustment" .=) <$> _crPercentageAdjustment, ("carrierName" .=) <$> _crCarrierName]) -- -- /See:/ 'shippingSettingsListResponse' smart constructor. data ShippingSettingsListResponse = ShippingSettingsListResponse' { _sslrNextPageToken :: !(Maybe Text) , _sslrKind :: !Text , _sslrResources :: !(Maybe [ShippingSettings]) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ShippingSettingsListResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'sslrNextPageToken' -- -- * 'sslrKind' -- -- * 'sslrResources' shippingSettingsListResponse :: ShippingSettingsListResponse shippingSettingsListResponse = ShippingSettingsListResponse' { _sslrNextPageToken = Nothing , _sslrKind = "content#shippingsettingsListResponse" , _sslrResources = Nothing } -- | The token for the retrieval of the next page of shipping settings. sslrNextPageToken :: Lens' ShippingSettingsListResponse (Maybe Text) sslrNextPageToken = lens _sslrNextPageToken (\ s a -> s{_sslrNextPageToken = a}) -- | Identifies what kind of resource this is. Value: the fixed string -- \"content#shippingsettingsListResponse\". sslrKind :: Lens' ShippingSettingsListResponse Text sslrKind = lens _sslrKind (\ s a -> s{_sslrKind = a}) sslrResources :: Lens' ShippingSettingsListResponse [ShippingSettings] sslrResources = lens _sslrResources (\ s a -> s{_sslrResources = a}) . _Default . _Coerce instance FromJSON ShippingSettingsListResponse where parseJSON = withObject "ShippingSettingsListResponse" (\ o -> ShippingSettingsListResponse' <$> (o .:? "nextPageToken") <*> (o .:? "kind" .!= "content#shippingsettingsListResponse") <*> (o .:? "resources" .!= mempty)) instance ToJSON ShippingSettingsListResponse where toJSON ShippingSettingsListResponse'{..} = object (catMaybes [("nextPageToken" .=) <$> _sslrNextPageToken, Just ("kind" .= _sslrKind), ("resources" .=) <$> _sslrResources]) -- -- /See:/ 'ordersShipLineItemsRequest' smart constructor. data OrdersShipLineItemsRequest = OrdersShipLineItemsRequest' { _oslirCarrier :: !(Maybe Text) , _oslirTrackingId :: !(Maybe Text) , _oslirShipmentId :: !(Maybe Text) , _oslirLineItems :: !(Maybe [OrderShipmentLineItemShipment]) , _oslirOperationId :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'OrdersShipLineItemsRequest' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'oslirCarrier' -- -- * 'oslirTrackingId' -- -- * 'oslirShipmentId' -- -- * 'oslirLineItems' -- -- * 'oslirOperationId' ordersShipLineItemsRequest :: OrdersShipLineItemsRequest ordersShipLineItemsRequest = OrdersShipLineItemsRequest' { _oslirCarrier = Nothing , _oslirTrackingId = Nothing , _oslirShipmentId = Nothing , _oslirLineItems = Nothing , _oslirOperationId = Nothing } -- | The carrier handling the shipment. oslirCarrier :: Lens' OrdersShipLineItemsRequest (Maybe Text) oslirCarrier = lens _oslirCarrier (\ s a -> s{_oslirCarrier = a}) -- | The tracking id for the shipment. oslirTrackingId :: Lens' OrdersShipLineItemsRequest (Maybe Text) oslirTrackingId = lens _oslirTrackingId (\ s a -> s{_oslirTrackingId = a}) -- | The ID of the shipment. oslirShipmentId :: Lens' OrdersShipLineItemsRequest (Maybe Text) oslirShipmentId = lens _oslirShipmentId (\ s a -> s{_oslirShipmentId = a}) -- | Line items to ship. oslirLineItems :: Lens' OrdersShipLineItemsRequest [OrderShipmentLineItemShipment] oslirLineItems = lens _oslirLineItems (\ s a -> s{_oslirLineItems = a}) . _Default . _Coerce -- | The ID of the operation. Unique across all operations for a given order. oslirOperationId :: Lens' OrdersShipLineItemsRequest (Maybe Text) oslirOperationId = lens _oslirOperationId (\ s a -> s{_oslirOperationId = a}) instance FromJSON OrdersShipLineItemsRequest where parseJSON = withObject "OrdersShipLineItemsRequest" (\ o -> OrdersShipLineItemsRequest' <$> (o .:? "carrier") <*> (o .:? "trackingId") <*> (o .:? "shipmentId") <*> (o .:? "lineItems" .!= mempty) <*> (o .:? "operationId")) instance ToJSON OrdersShipLineItemsRequest where toJSON OrdersShipLineItemsRequest'{..} = object (catMaybes [("carrier" .=) <$> _oslirCarrier, ("trackingId" .=) <$> _oslirTrackingId, ("shipmentId" .=) <$> _oslirShipmentId, ("lineItems" .=) <$> _oslirLineItems, ("operationId" .=) <$> _oslirOperationId]) -- -- /See:/ 'accountsCustomBatchResponse' smart constructor. data AccountsCustomBatchResponse = AccountsCustomBatchResponse' { _acbrcEntries :: !(Maybe [AccountsCustomBatchResponseEntry]) , _acbrcKind :: !Text } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'AccountsCustomBatchResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'acbrcEntries' -- -- * 'acbrcKind' accountsCustomBatchResponse :: AccountsCustomBatchResponse accountsCustomBatchResponse = AccountsCustomBatchResponse' { _acbrcEntries = Nothing , _acbrcKind = "content#accountsCustomBatchResponse" } -- | The result of the execution of the batch requests. acbrcEntries :: Lens' AccountsCustomBatchResponse [AccountsCustomBatchResponseEntry] acbrcEntries = lens _acbrcEntries (\ s a -> s{_acbrcEntries = a}) . _Default . _Coerce -- | Identifies what kind of resource this is. Value: the fixed string -- \"content#accountsCustomBatchResponse\". acbrcKind :: Lens' AccountsCustomBatchResponse Text acbrcKind = lens _acbrcKind (\ s a -> s{_acbrcKind = a}) instance FromJSON AccountsCustomBatchResponse where parseJSON = withObject "AccountsCustomBatchResponse" (\ o -> AccountsCustomBatchResponse' <$> (o .:? "entries" .!= mempty) <*> (o .:? "kind" .!= "content#accountsCustomBatchResponse")) instance ToJSON AccountsCustomBatchResponse where toJSON AccountsCustomBatchResponse'{..} = object (catMaybes [("entries" .=) <$> _acbrcEntries, Just ("kind" .= _acbrcKind)]) -- -- /See:/ 'productTax' smart constructor. data ProductTax = ProductTax' { _ptTaxShip :: !(Maybe Bool) , _ptCountry :: !(Maybe Text) , _ptPostalCode :: !(Maybe Text) , _ptRate :: !(Maybe (Textual Double)) , _ptRegion :: !(Maybe Text) , _ptLocationId :: !(Maybe (Textual Int64)) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ProductTax' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ptTaxShip' -- -- * 'ptCountry' -- -- * 'ptPostalCode' -- -- * 'ptRate' -- -- * 'ptRegion' -- -- * 'ptLocationId' productTax :: ProductTax productTax = ProductTax' { _ptTaxShip = Nothing , _ptCountry = Nothing , _ptPostalCode = Nothing , _ptRate = Nothing , _ptRegion = Nothing , _ptLocationId = Nothing } -- | Set to true if tax is charged on shipping. ptTaxShip :: Lens' ProductTax (Maybe Bool) ptTaxShip = lens _ptTaxShip (\ s a -> s{_ptTaxShip = a}) -- | The country within which the item is taxed, specified as a CLDR -- territory code. ptCountry :: Lens' ProductTax (Maybe Text) ptCountry = lens _ptCountry (\ s a -> s{_ptCountry = a}) -- | The postal code range that the tax rate applies to, represented by a ZIP -- code, a ZIP code prefix using * wildcard, a range between two ZIP codes -- or two ZIP code prefixes of equal length. Examples: 94114, 94*, -- 94002-95460, 94*-95*. ptPostalCode :: Lens' ProductTax (Maybe Text) ptPostalCode = lens _ptPostalCode (\ s a -> s{_ptPostalCode = a}) -- | The percentage of tax rate that applies to the item price. ptRate :: Lens' ProductTax (Maybe Double) ptRate = lens _ptRate (\ s a -> s{_ptRate = a}) . mapping _Coerce -- | The geographic region to which the tax rate applies. ptRegion :: Lens' ProductTax (Maybe Text) ptRegion = lens _ptRegion (\ s a -> s{_ptRegion = a}) -- | The numeric id of a location that the tax rate applies to as defined in -- the AdWords API. ptLocationId :: Lens' ProductTax (Maybe Int64) ptLocationId = lens _ptLocationId (\ s a -> s{_ptLocationId = a}) . mapping _Coerce instance FromJSON ProductTax where parseJSON = withObject "ProductTax" (\ o -> ProductTax' <$> (o .:? "taxShip") <*> (o .:? "country") <*> (o .:? "postalCode") <*> (o .:? "rate") <*> (o .:? "region") <*> (o .:? "locationId")) instance ToJSON ProductTax where toJSON ProductTax'{..} = object (catMaybes [("taxShip" .=) <$> _ptTaxShip, ("country" .=) <$> _ptCountry, ("postalCode" .=) <$> _ptPostalCode, ("rate" .=) <$> _ptRate, ("region" .=) <$> _ptRegion, ("locationId" .=) <$> _ptLocationId]) -- -- /See:/ 'orderShipment' smart constructor. data OrderShipment = OrderShipment' { _osCarrier :: !(Maybe Text) , _osStatus :: !(Maybe Text) , _osTrackingId :: !(Maybe Text) , _osLineItems :: !(Maybe [OrderShipmentLineItemShipment]) , _osId :: !(Maybe Text) , _osCreationDate :: !(Maybe Text) , _osDeliveryDate :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'OrderShipment' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'osCarrier' -- -- * 'osStatus' -- -- * 'osTrackingId' -- -- * 'osLineItems' -- -- * 'osId' -- -- * 'osCreationDate' -- -- * 'osDeliveryDate' orderShipment :: OrderShipment orderShipment = OrderShipment' { _osCarrier = Nothing , _osStatus = Nothing , _osTrackingId = Nothing , _osLineItems = Nothing , _osId = Nothing , _osCreationDate = Nothing , _osDeliveryDate = Nothing } -- | The carrier handling the shipment. osCarrier :: Lens' OrderShipment (Maybe Text) osCarrier = lens _osCarrier (\ s a -> s{_osCarrier = a}) -- | The status of the shipment. osStatus :: Lens' OrderShipment (Maybe Text) osStatus = lens _osStatus (\ s a -> s{_osStatus = a}) -- | The tracking id for the shipment. osTrackingId :: Lens' OrderShipment (Maybe Text) osTrackingId = lens _osTrackingId (\ s a -> s{_osTrackingId = a}) -- | The line items that are shipped. osLineItems :: Lens' OrderShipment [OrderShipmentLineItemShipment] osLineItems = lens _osLineItems (\ s a -> s{_osLineItems = a}) . _Default . _Coerce -- | The id of the shipment. osId :: Lens' OrderShipment (Maybe Text) osId = lens _osId (\ s a -> s{_osId = a}) -- | Date on which the shipment has been created, in ISO 8601 format. osCreationDate :: Lens' OrderShipment (Maybe Text) osCreationDate = lens _osCreationDate (\ s a -> s{_osCreationDate = a}) -- | Date on which the shipment has been delivered, in ISO 8601 format. -- Present only if status is delievered osDeliveryDate :: Lens' OrderShipment (Maybe Text) osDeliveryDate = lens _osDeliveryDate (\ s a -> s{_osDeliveryDate = a}) instance FromJSON OrderShipment where parseJSON = withObject "OrderShipment" (\ o -> OrderShipment' <$> (o .:? "carrier") <*> (o .:? "status") <*> (o .:? "trackingId") <*> (o .:? "lineItems" .!= mempty) <*> (o .:? "id") <*> (o .:? "creationDate") <*> (o .:? "deliveryDate")) instance ToJSON OrderShipment where toJSON OrderShipment'{..} = object (catMaybes [("carrier" .=) <$> _osCarrier, ("status" .=) <$> _osStatus, ("trackingId" .=) <$> _osTrackingId, ("lineItems" .=) <$> _osLineItems, ("id" .=) <$> _osId, ("creationDate" .=) <$> _osCreationDate, ("deliveryDate" .=) <$> _osDeliveryDate]) -- -- /See:/ 'orderLineItemReturnInfo' smart constructor. data OrderLineItemReturnInfo = OrderLineItemReturnInfo' { _oliriIsReturnable :: !(Maybe Bool) , _oliriPolicyURL :: !(Maybe Text) , _oliriDaysToReturn :: !(Maybe (Textual Int32)) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'OrderLineItemReturnInfo' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'oliriIsReturnable' -- -- * 'oliriPolicyURL' -- -- * 'oliriDaysToReturn' orderLineItemReturnInfo :: OrderLineItemReturnInfo orderLineItemReturnInfo = OrderLineItemReturnInfo' { _oliriIsReturnable = Nothing , _oliriPolicyURL = Nothing , _oliriDaysToReturn = Nothing } -- | Whether the item is returnable. oliriIsReturnable :: Lens' OrderLineItemReturnInfo (Maybe Bool) oliriIsReturnable = lens _oliriIsReturnable (\ s a -> s{_oliriIsReturnable = a}) -- | URL of the item return policy. oliriPolicyURL :: Lens' OrderLineItemReturnInfo (Maybe Text) oliriPolicyURL = lens _oliriPolicyURL (\ s a -> s{_oliriPolicyURL = a}) -- | How many days later the item can be returned. oliriDaysToReturn :: Lens' OrderLineItemReturnInfo (Maybe Int32) oliriDaysToReturn = lens _oliriDaysToReturn (\ s a -> s{_oliriDaysToReturn = a}) . mapping _Coerce instance FromJSON OrderLineItemReturnInfo where parseJSON = withObject "OrderLineItemReturnInfo" (\ o -> OrderLineItemReturnInfo' <$> (o .:? "isReturnable") <*> (o .:? "policyUrl") <*> (o .:? "daysToReturn")) instance ToJSON OrderLineItemReturnInfo where toJSON OrderLineItemReturnInfo'{..} = object (catMaybes [("isReturnable" .=) <$> _oliriIsReturnable, ("policyUrl" .=) <$> _oliriPolicyURL, ("daysToReturn" .=) <$> _oliriDaysToReturn]) -- -- /See:/ 'accountShippingRateTableCell' smart constructor. data AccountShippingRateTableCell = AccountShippingRateTableCell' { _asrtcRate :: !(Maybe Price) , _asrtcCondition :: !(Maybe AccountShippingCondition) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'AccountShippingRateTableCell' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'asrtcRate' -- -- * 'asrtcCondition' accountShippingRateTableCell :: AccountShippingRateTableCell accountShippingRateTableCell = AccountShippingRateTableCell' { _asrtcRate = Nothing , _asrtcCondition = Nothing } -- | The rate applicable if the cell conditions are matched. asrtcRate :: Lens' AccountShippingRateTableCell (Maybe Price) asrtcRate = lens _asrtcRate (\ s a -> s{_asrtcRate = a}) -- | Conditions for which the cell is valid. All cells in a table must use -- the same dimension or pair of dimensions among price, weight, shipping -- label or delivery location. If no condition is specified, the cell acts -- as a catch-all and matches all the elements that are not matched by -- other cells in this dimension. asrtcCondition :: Lens' AccountShippingRateTableCell (Maybe AccountShippingCondition) asrtcCondition = lens _asrtcCondition (\ s a -> s{_asrtcCondition = a}) instance FromJSON AccountShippingRateTableCell where parseJSON = withObject "AccountShippingRateTableCell" (\ o -> AccountShippingRateTableCell' <$> (o .:? "rate") <*> (o .:? "condition")) instance ToJSON AccountShippingRateTableCell where toJSON AccountShippingRateTableCell'{..} = object (catMaybes [("rate" .=) <$> _asrtcRate, ("condition" .=) <$> _asrtcCondition]) -- | Account data. -- -- /See:/ 'account' smart constructor. data Account = Account' { _aaUsers :: !(Maybe [AccountUser]) , _aaKind :: !Text , _aaSellerId :: !(Maybe Text) , _aaName :: !(Maybe Text) , _aaReviewsURL :: !(Maybe Text) , _aaId :: !(Maybe (Textual Word64)) , _aaWebsiteURL :: !(Maybe Text) , _aaAdwordsLinks :: !(Maybe [AccountAdwordsLink]) , _aaAdultContent :: !(Maybe Bool) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'Account' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'aaUsers' -- -- * 'aaKind' -- -- * 'aaSellerId' -- -- * 'aaName' -- -- * 'aaReviewsURL' -- -- * 'aaId' -- -- * 'aaWebsiteURL' -- -- * 'aaAdwordsLinks' -- -- * 'aaAdultContent' account :: Account account = Account' { _aaUsers = Nothing , _aaKind = "content#account" , _aaSellerId = Nothing , _aaName = Nothing , _aaReviewsURL = Nothing , _aaId = Nothing , _aaWebsiteURL = Nothing , _aaAdwordsLinks = Nothing , _aaAdultContent = Nothing } -- | Users with access to the account. Every account (except for subaccounts) -- must have at least one admin user. aaUsers :: Lens' Account [AccountUser] aaUsers = lens _aaUsers (\ s a -> s{_aaUsers = a}) . _Default . _Coerce -- | Identifies what kind of resource this is. Value: the fixed string -- \"content#account\". aaKind :: Lens' Account Text aaKind = lens _aaKind (\ s a -> s{_aaKind = a}) -- | Client-specific, locally-unique, internal ID for the child account. aaSellerId :: Lens' Account (Maybe Text) aaSellerId = lens _aaSellerId (\ s a -> s{_aaSellerId = a}) -- | Display name for the account. aaName :: Lens' Account (Maybe Text) aaName = lens _aaName (\ s a -> s{_aaName = a}) -- | URL for individual seller reviews, i.e., reviews for each child account. aaReviewsURL :: Lens' Account (Maybe Text) aaReviewsURL = lens _aaReviewsURL (\ s a -> s{_aaReviewsURL = a}) -- | Merchant Center account ID. aaId :: Lens' Account (Maybe Word64) aaId = lens _aaId (\ s a -> s{_aaId = a}) . mapping _Coerce -- | The merchant\'s website. aaWebsiteURL :: Lens' Account (Maybe Text) aaWebsiteURL = lens _aaWebsiteURL (\ s a -> s{_aaWebsiteURL = a}) -- | List of linked AdWords accounts that are active or pending approval. To -- create a new link request, add a new link with status active to the -- list. It will remain in a pending state until approved or rejected -- either in the AdWords interface or through the AdWords API. To delete an -- active link, or to cancel a link request, remove it from the list. aaAdwordsLinks :: Lens' Account [AccountAdwordsLink] aaAdwordsLinks = lens _aaAdwordsLinks (\ s a -> s{_aaAdwordsLinks = a}) . _Default . _Coerce -- | Indicates whether the merchant sells adult content. aaAdultContent :: Lens' Account (Maybe Bool) aaAdultContent = lens _aaAdultContent (\ s a -> s{_aaAdultContent = a}) instance FromJSON Account where parseJSON = withObject "Account" (\ o -> Account' <$> (o .:? "users" .!= mempty) <*> (o .:? "kind" .!= "content#account") <*> (o .:? "sellerId") <*> (o .:? "name") <*> (o .:? "reviewsUrl") <*> (o .:? "id") <*> (o .:? "websiteUrl") <*> (o .:? "adwordsLinks" .!= mempty) <*> (o .:? "adultContent")) instance ToJSON Account where toJSON Account'{..} = object (catMaybes [("users" .=) <$> _aaUsers, Just ("kind" .= _aaKind), ("sellerId" .=) <$> _aaSellerId, ("name" .=) <$> _aaName, ("reviewsUrl" .=) <$> _aaReviewsURL, ("id" .=) <$> _aaId, ("websiteUrl" .=) <$> _aaWebsiteURL, ("adwordsLinks" .=) <$> _aaAdwordsLinks, ("adultContent" .=) <$> _aaAdultContent]) -- -- /See:/ 'inventorySetRequest' smart constructor. data InventorySetRequest = InventorySetRequest' { _isrLoyaltyPoints :: !(Maybe LoyaltyPoints) , _isrQuantity :: !(Maybe (Textual Word32)) , _isrInstallment :: !(Maybe Installment) , _isrSalePrice :: !(Maybe Price) , _isrAvailability :: !(Maybe Text) , _isrPickup :: !(Maybe InventoryPickup) , _isrSalePriceEffectiveDate :: !(Maybe Text) , _isrSellOnGoogleQuantity :: !(Maybe (Textual Word32)) , _isrPrice :: !(Maybe Price) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'InventorySetRequest' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'isrLoyaltyPoints' -- -- * 'isrQuantity' -- -- * 'isrInstallment' -- -- * 'isrSalePrice' -- -- * 'isrAvailability' -- -- * 'isrPickup' -- -- * 'isrSalePriceEffectiveDate' -- -- * 'isrSellOnGoogleQuantity' -- -- * 'isrPrice' inventorySetRequest :: InventorySetRequest inventorySetRequest = InventorySetRequest' { _isrLoyaltyPoints = Nothing , _isrQuantity = Nothing , _isrInstallment = Nothing , _isrSalePrice = Nothing , _isrAvailability = Nothing , _isrPickup = Nothing , _isrSalePriceEffectiveDate = Nothing , _isrSellOnGoogleQuantity = Nothing , _isrPrice = Nothing } -- | Loyalty points that users receive after purchasing the item. Japan only. isrLoyaltyPoints :: Lens' InventorySetRequest (Maybe LoyaltyPoints) isrLoyaltyPoints = lens _isrLoyaltyPoints (\ s a -> s{_isrLoyaltyPoints = a}) -- | The quantity of the product. Must be equal to or greater than zero. -- Supported only for local products. isrQuantity :: Lens' InventorySetRequest (Maybe Word32) isrQuantity = lens _isrQuantity (\ s a -> s{_isrQuantity = a}) . mapping _Coerce -- | Number and amount of installments to pay for an item. Brazil only. isrInstallment :: Lens' InventorySetRequest (Maybe Installment) isrInstallment = lens _isrInstallment (\ s a -> s{_isrInstallment = a}) -- | The sale price of the product. Mandatory if sale_price_effective_date is -- defined. isrSalePrice :: Lens' InventorySetRequest (Maybe Price) isrSalePrice = lens _isrSalePrice (\ s a -> s{_isrSalePrice = a}) -- | The availability of the product. isrAvailability :: Lens' InventorySetRequest (Maybe Text) isrAvailability = lens _isrAvailability (\ s a -> s{_isrAvailability = a}) -- | Store pickup information. Only supported for local inventory. Not -- setting pickup means \"don\'t update\" while setting it to the empty -- value ({} in JSON) means \"delete\". Otherwise, pickupMethod and -- pickupSla must be set together, unless pickupMethod is \"not -- supported\". isrPickup :: Lens' InventorySetRequest (Maybe InventoryPickup) isrPickup = lens _isrPickup (\ s a -> s{_isrPickup = a}) -- | A date range represented by a pair of ISO 8601 dates separated by a -- space, comma, or slash. Both dates might be specified as \'null\' if -- undecided. isrSalePriceEffectiveDate :: Lens' InventorySetRequest (Maybe Text) isrSalePriceEffectiveDate = lens _isrSalePriceEffectiveDate (\ s a -> s{_isrSalePriceEffectiveDate = a}) -- | The quantity of the product that is reserved for sell-on-google ads. -- Supported only for online products. isrSellOnGoogleQuantity :: Lens' InventorySetRequest (Maybe Word32) isrSellOnGoogleQuantity = lens _isrSellOnGoogleQuantity (\ s a -> s{_isrSellOnGoogleQuantity = a}) . mapping _Coerce -- | The price of the product. isrPrice :: Lens' InventorySetRequest (Maybe Price) isrPrice = lens _isrPrice (\ s a -> s{_isrPrice = a}) instance FromJSON InventorySetRequest where parseJSON = withObject "InventorySetRequest" (\ o -> InventorySetRequest' <$> (o .:? "loyaltyPoints") <*> (o .:? "quantity") <*> (o .:? "installment") <*> (o .:? "salePrice") <*> (o .:? "availability") <*> (o .:? "pickup") <*> (o .:? "salePriceEffectiveDate") <*> (o .:? "sellOnGoogleQuantity") <*> (o .:? "price")) instance ToJSON InventorySetRequest where toJSON InventorySetRequest'{..} = object (catMaybes [("loyaltyPoints" .=) <$> _isrLoyaltyPoints, ("quantity" .=) <$> _isrQuantity, ("installment" .=) <$> _isrInstallment, ("salePrice" .=) <$> _isrSalePrice, ("availability" .=) <$> _isrAvailability, ("pickup" .=) <$> _isrPickup, ("salePriceEffectiveDate" .=) <$> _isrSalePriceEffectiveDate, ("sellOnGoogleQuantity" .=) <$> _isrSellOnGoogleQuantity, ("price" .=) <$> _isrPrice]) -- | Building block of the cost calculation decision tree. - The tree root -- should have no condition and no calculation method. - All the children -- must have a condition on the same dimension. The first child matching a -- condition is entered, therefore, price and weight conditions form -- contiguous intervals. - The last child of an element must have no -- condition and matches all elements not previously matched. - Children -- and calculation method are mutually exclusive, and exactly one of them -- must be defined; the root must only have children. -- -- /See:/ 'accountShippingShippingServiceCostRule' smart constructor. data AccountShippingShippingServiceCostRule = AccountShippingShippingServiceCostRule' { _assscrChildren :: !(Maybe [AccountShippingShippingServiceCostRule]) , _assscrCalculationMethod :: !(Maybe AccountShippingShippingServiceCalculationMethod) , _assscrCondition :: !(Maybe AccountShippingCondition) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'AccountShippingShippingServiceCostRule' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'assscrChildren' -- -- * 'assscrCalculationMethod' -- -- * 'assscrCondition' accountShippingShippingServiceCostRule :: AccountShippingShippingServiceCostRule accountShippingShippingServiceCostRule = AccountShippingShippingServiceCostRule' { _assscrChildren = Nothing , _assscrCalculationMethod = Nothing , _assscrCondition = Nothing } -- | Subsequent rules to be applied, only for inner nodes. The last child -- must not specify a condition and acts as a catch-all. assscrChildren :: Lens' AccountShippingShippingServiceCostRule [AccountShippingShippingServiceCostRule] assscrChildren = lens _assscrChildren (\ s a -> s{_assscrChildren = a}) . _Default . _Coerce -- | Final calculation method to be used only in leaf nodes. assscrCalculationMethod :: Lens' AccountShippingShippingServiceCostRule (Maybe AccountShippingShippingServiceCalculationMethod) assscrCalculationMethod = lens _assscrCalculationMethod (\ s a -> s{_assscrCalculationMethod = a}) -- | Condition for this rule to be applicable. If no condition is specified, -- the rule acts as a catch-all. assscrCondition :: Lens' AccountShippingShippingServiceCostRule (Maybe AccountShippingCondition) assscrCondition = lens _assscrCondition (\ s a -> s{_assscrCondition = a}) instance FromJSON AccountShippingShippingServiceCostRule where parseJSON = withObject "AccountShippingShippingServiceCostRule" (\ o -> AccountShippingShippingServiceCostRule' <$> (o .:? "children" .!= mempty) <*> (o .:? "calculationMethod") <*> (o .:? "condition")) instance ToJSON AccountShippingShippingServiceCostRule where toJSON AccountShippingShippingServiceCostRule'{..} = object (catMaybes [("children" .=) <$> _assscrChildren, ("calculationMethod" .=) <$> _assscrCalculationMethod, ("condition" .=) <$> _assscrCondition]) -- -- /See:/ 'ordersCancelLineItemRequest' smart constructor. data OrdersCancelLineItemRequest = OrdersCancelLineItemRequest' { _oclirAmount :: !(Maybe Price) , _oclirQuantity :: !(Maybe (Textual Word32)) , _oclirLineItemId :: !(Maybe Text) , _oclirReason :: !(Maybe Text) , _oclirOperationId :: !(Maybe Text) , _oclirReasonText :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'OrdersCancelLineItemRequest' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'oclirAmount' -- -- * 'oclirQuantity' -- -- * 'oclirLineItemId' -- -- * 'oclirReason' -- -- * 'oclirOperationId' -- -- * 'oclirReasonText' ordersCancelLineItemRequest :: OrdersCancelLineItemRequest ordersCancelLineItemRequest = OrdersCancelLineItemRequest' { _oclirAmount = Nothing , _oclirQuantity = Nothing , _oclirLineItemId = Nothing , _oclirReason = Nothing , _oclirOperationId = Nothing , _oclirReasonText = Nothing } -- | Amount to refund for the cancelation. Optional. If not set, Google will -- calculate the default based on the price and tax of the items involved. -- The amount must not be larger than the net amount left on the order. oclirAmount :: Lens' OrdersCancelLineItemRequest (Maybe Price) oclirAmount = lens _oclirAmount (\ s a -> s{_oclirAmount = a}) -- | The quantity to cancel. oclirQuantity :: Lens' OrdersCancelLineItemRequest (Maybe Word32) oclirQuantity = lens _oclirQuantity (\ s a -> s{_oclirQuantity = a}) . mapping _Coerce -- | The ID of the line item to cancel. oclirLineItemId :: Lens' OrdersCancelLineItemRequest (Maybe Text) oclirLineItemId = lens _oclirLineItemId (\ s a -> s{_oclirLineItemId = a}) -- | The reason for the cancellation. oclirReason :: Lens' OrdersCancelLineItemRequest (Maybe Text) oclirReason = lens _oclirReason (\ s a -> s{_oclirReason = a}) -- | The ID of the operation. Unique across all operations for a given order. oclirOperationId :: Lens' OrdersCancelLineItemRequest (Maybe Text) oclirOperationId = lens _oclirOperationId (\ s a -> s{_oclirOperationId = a}) -- | The explanation of the reason. oclirReasonText :: Lens' OrdersCancelLineItemRequest (Maybe Text) oclirReasonText = lens _oclirReasonText (\ s a -> s{_oclirReasonText = a}) instance FromJSON OrdersCancelLineItemRequest where parseJSON = withObject "OrdersCancelLineItemRequest" (\ o -> OrdersCancelLineItemRequest' <$> (o .:? "amount") <*> (o .:? "quantity") <*> (o .:? "lineItemId") <*> (o .:? "reason") <*> (o .:? "operationId") <*> (o .:? "reasonText")) instance ToJSON OrdersCancelLineItemRequest where toJSON OrdersCancelLineItemRequest'{..} = object (catMaybes [("amount" .=) <$> _oclirAmount, ("quantity" .=) <$> _oclirQuantity, ("lineItemId" .=) <$> _oclirLineItemId, ("reason" .=) <$> _oclirReason, ("operationId" .=) <$> _oclirOperationId, ("reasonText" .=) <$> _oclirReasonText]) -- -- /See:/ 'productShippingWeight' smart constructor. data ProductShippingWeight = ProductShippingWeight' { _pswValue :: !(Maybe (Textual Double)) , _pswUnit :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ProductShippingWeight' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pswValue' -- -- * 'pswUnit' productShippingWeight :: ProductShippingWeight productShippingWeight = ProductShippingWeight' { _pswValue = Nothing , _pswUnit = Nothing } -- | The weight of the product used to calculate the shipping cost of the -- item. pswValue :: Lens' ProductShippingWeight (Maybe Double) pswValue = lens _pswValue (\ s a -> s{_pswValue = a}) . mapping _Coerce -- | The unit of value. pswUnit :: Lens' ProductShippingWeight (Maybe Text) pswUnit = lens _pswUnit (\ s a -> s{_pswUnit = a}) instance FromJSON ProductShippingWeight where parseJSON = withObject "ProductShippingWeight" (\ o -> ProductShippingWeight' <$> (o .:? "value") <*> (o .:? "unit")) instance ToJSON ProductShippingWeight where toJSON ProductShippingWeight'{..} = object (catMaybes [("value" .=) <$> _pswValue, ("unit" .=) <$> _pswUnit]) -- | A batch entry encoding a single non-batch accountstatuses request. -- -- /See:/ 'accountstatusesCustomBatchRequestEntry' smart constructor. data AccountstatusesCustomBatchRequestEntry = AccountstatusesCustomBatchRequestEntry' { _acbrecMerchantId :: !(Maybe (Textual Word64)) , _acbrecAccountId :: !(Maybe (Textual Word64)) , _acbrecMethod :: !(Maybe Text) , _acbrecBatchId :: !(Maybe (Textual Word32)) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'AccountstatusesCustomBatchRequestEntry' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'acbrecMerchantId' -- -- * 'acbrecAccountId' -- -- * 'acbrecMethod' -- -- * 'acbrecBatchId' accountstatusesCustomBatchRequestEntry :: AccountstatusesCustomBatchRequestEntry accountstatusesCustomBatchRequestEntry = AccountstatusesCustomBatchRequestEntry' { _acbrecMerchantId = Nothing , _acbrecAccountId = Nothing , _acbrecMethod = Nothing , _acbrecBatchId = Nothing } -- | The ID of the managing account. acbrecMerchantId :: Lens' AccountstatusesCustomBatchRequestEntry (Maybe Word64) acbrecMerchantId = lens _acbrecMerchantId (\ s a -> s{_acbrecMerchantId = a}) . mapping _Coerce -- | The ID of the (sub-)account whose status to get. acbrecAccountId :: Lens' AccountstatusesCustomBatchRequestEntry (Maybe Word64) acbrecAccountId = lens _acbrecAccountId (\ s a -> s{_acbrecAccountId = a}) . mapping _Coerce -- | The method (get). acbrecMethod :: Lens' AccountstatusesCustomBatchRequestEntry (Maybe Text) acbrecMethod = lens _acbrecMethod (\ s a -> s{_acbrecMethod = a}) -- | An entry ID, unique within the batch request. acbrecBatchId :: Lens' AccountstatusesCustomBatchRequestEntry (Maybe Word32) acbrecBatchId = lens _acbrecBatchId (\ s a -> s{_acbrecBatchId = a}) . mapping _Coerce instance FromJSON AccountstatusesCustomBatchRequestEntry where parseJSON = withObject "AccountstatusesCustomBatchRequestEntry" (\ o -> AccountstatusesCustomBatchRequestEntry' <$> (o .:? "merchantId") <*> (o .:? "accountId") <*> (o .:? "method") <*> (o .:? "batchId")) instance ToJSON AccountstatusesCustomBatchRequestEntry where toJSON AccountstatusesCustomBatchRequestEntry'{..} = object (catMaybes [("merchantId" .=) <$> _acbrecMerchantId, ("accountId" .=) <$> _acbrecAccountId, ("method" .=) <$> _acbrecMethod, ("batchId" .=) <$> _acbrecBatchId]) -- -- /See:/ 'deliveryTime' smart constructor. data DeliveryTime = DeliveryTime' { _dtMinTransitTimeInDays :: !(Maybe (Textual Word32)) , _dtMaxTransitTimeInDays :: !(Maybe (Textual Word32)) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'DeliveryTime' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dtMinTransitTimeInDays' -- -- * 'dtMaxTransitTimeInDays' deliveryTime :: DeliveryTime deliveryTime = DeliveryTime' { _dtMinTransitTimeInDays = Nothing , _dtMaxTransitTimeInDays = Nothing } -- | Minimum number of business days that is spent in transit. 0 means same -- day delivery, 1 means next day delivery. Required. dtMinTransitTimeInDays :: Lens' DeliveryTime (Maybe Word32) dtMinTransitTimeInDays = lens _dtMinTransitTimeInDays (\ s a -> s{_dtMinTransitTimeInDays = a}) . mapping _Coerce -- | Maximum number of business days that is spent in transit. 0 means same -- day delivery, 1 means next day delivery. Must be greater than or equal -- to minTransitTimeInDays. Required. dtMaxTransitTimeInDays :: Lens' DeliveryTime (Maybe Word32) dtMaxTransitTimeInDays = lens _dtMaxTransitTimeInDays (\ s a -> s{_dtMaxTransitTimeInDays = a}) . mapping _Coerce instance FromJSON DeliveryTime where parseJSON = withObject "DeliveryTime" (\ o -> DeliveryTime' <$> (o .:? "minTransitTimeInDays") <*> (o .:? "maxTransitTimeInDays")) instance ToJSON DeliveryTime where toJSON DeliveryTime'{..} = object (catMaybes [("minTransitTimeInDays" .=) <$> _dtMinTransitTimeInDays, ("maxTransitTimeInDays" .=) <$> _dtMaxTransitTimeInDays]) -- | A batch entry encoding a single non-batch productstatuses response. -- -- /See:/ 'productstatusesCustomBatchResponseEntry' smart constructor. data ProductstatusesCustomBatchResponseEntry = ProductstatusesCustomBatchResponseEntry' { _pcbreKind :: !Text , _pcbreProductStatus :: !(Maybe ProductStatus) , _pcbreErrors :: !(Maybe Errors) , _pcbreBatchId :: !(Maybe (Textual Word32)) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ProductstatusesCustomBatchResponseEntry' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pcbreKind' -- -- * 'pcbreProductStatus' -- -- * 'pcbreErrors' -- -- * 'pcbreBatchId' productstatusesCustomBatchResponseEntry :: ProductstatusesCustomBatchResponseEntry productstatusesCustomBatchResponseEntry = ProductstatusesCustomBatchResponseEntry' { _pcbreKind = "content#productstatusesCustomBatchResponseEntry" , _pcbreProductStatus = Nothing , _pcbreErrors = Nothing , _pcbreBatchId = Nothing } -- | Identifies what kind of resource this is. Value: the fixed string -- \"content#productstatusesCustomBatchResponseEntry\". pcbreKind :: Lens' ProductstatusesCustomBatchResponseEntry Text pcbreKind = lens _pcbreKind (\ s a -> s{_pcbreKind = a}) -- | The requested product status. Only defined if the request was -- successful. pcbreProductStatus :: Lens' ProductstatusesCustomBatchResponseEntry (Maybe ProductStatus) pcbreProductStatus = lens _pcbreProductStatus (\ s a -> s{_pcbreProductStatus = a}) -- | A list of errors, if the request failed. pcbreErrors :: Lens' ProductstatusesCustomBatchResponseEntry (Maybe Errors) pcbreErrors = lens _pcbreErrors (\ s a -> s{_pcbreErrors = a}) -- | The ID of the request entry this entry responds to. pcbreBatchId :: Lens' ProductstatusesCustomBatchResponseEntry (Maybe Word32) pcbreBatchId = lens _pcbreBatchId (\ s a -> s{_pcbreBatchId = a}) . mapping _Coerce instance FromJSON ProductstatusesCustomBatchResponseEntry where parseJSON = withObject "ProductstatusesCustomBatchResponseEntry" (\ o -> ProductstatusesCustomBatchResponseEntry' <$> (o .:? "kind" .!= "content#productstatusesCustomBatchResponseEntry") <*> (o .:? "productStatus") <*> (o .:? "errors") <*> (o .:? "batchId")) instance ToJSON ProductstatusesCustomBatchResponseEntry where toJSON ProductstatusesCustomBatchResponseEntry'{..} = object (catMaybes [Just ("kind" .= _pcbreKind), ("productStatus" .=) <$> _pcbreProductStatus, ("errors" .=) <$> _pcbreErrors, ("batchId" .=) <$> _pcbreBatchId]) -- -- /See:/ 'ordersCustomBatchRequestEntryCancel' smart constructor. data OrdersCustomBatchRequestEntryCancel = OrdersCustomBatchRequestEntryCancel' { _ocbrecReason :: !(Maybe Text) , _ocbrecReasonText :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'OrdersCustomBatchRequestEntryCancel' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ocbrecReason' -- -- * 'ocbrecReasonText' ordersCustomBatchRequestEntryCancel :: OrdersCustomBatchRequestEntryCancel ordersCustomBatchRequestEntryCancel = OrdersCustomBatchRequestEntryCancel' { _ocbrecReason = Nothing , _ocbrecReasonText = Nothing } -- | The reason for the cancellation. ocbrecReason :: Lens' OrdersCustomBatchRequestEntryCancel (Maybe Text) ocbrecReason = lens _ocbrecReason (\ s a -> s{_ocbrecReason = a}) -- | The explanation of the reason. ocbrecReasonText :: Lens' OrdersCustomBatchRequestEntryCancel (Maybe Text) ocbrecReasonText = lens _ocbrecReasonText (\ s a -> s{_ocbrecReasonText = a}) instance FromJSON OrdersCustomBatchRequestEntryCancel where parseJSON = withObject "OrdersCustomBatchRequestEntryCancel" (\ o -> OrdersCustomBatchRequestEntryCancel' <$> (o .:? "reason") <*> (o .:? "reasonText")) instance ToJSON OrdersCustomBatchRequestEntryCancel where toJSON OrdersCustomBatchRequestEntryCancel'{..} = object (catMaybes [("reason" .=) <$> _ocbrecReason, ("reasonText" .=) <$> _ocbrecReasonText]) -- -- /See:/ 'datafeedFormat' smart constructor. data DatafeedFormat = DatafeedFormat' { _dfQuotingMode :: !(Maybe Text) , _dfFileEncoding :: !(Maybe Text) , _dfColumnDelimiter :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'DatafeedFormat' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dfQuotingMode' -- -- * 'dfFileEncoding' -- -- * 'dfColumnDelimiter' datafeedFormat :: DatafeedFormat datafeedFormat = DatafeedFormat' { _dfQuotingMode = Nothing , _dfFileEncoding = Nothing , _dfColumnDelimiter = Nothing } -- | Specifies how double quotes are interpreted. If not specified, the mode -- will be auto-detected. Ignored for non-DSV data feeds. dfQuotingMode :: Lens' DatafeedFormat (Maybe Text) dfQuotingMode = lens _dfQuotingMode (\ s a -> s{_dfQuotingMode = a}) -- | Character encoding scheme of the data feed. If not specified, the -- encoding will be auto-detected. dfFileEncoding :: Lens' DatafeedFormat (Maybe Text) dfFileEncoding = lens _dfFileEncoding (\ s a -> s{_dfFileEncoding = a}) -- | Delimiter for the separation of values in a delimiter-separated values -- feed. If not specified, the delimiter will be auto-detected. Ignored for -- non-DSV data feeds. dfColumnDelimiter :: Lens' DatafeedFormat (Maybe Text) dfColumnDelimiter = lens _dfColumnDelimiter (\ s a -> s{_dfColumnDelimiter = a}) instance FromJSON DatafeedFormat where parseJSON = withObject "DatafeedFormat" (\ o -> DatafeedFormat' <$> (o .:? "quotingMode") <*> (o .:? "fileEncoding") <*> (o .:? "columnDelimiter")) instance ToJSON DatafeedFormat where toJSON DatafeedFormat'{..} = object (catMaybes [("quotingMode" .=) <$> _dfQuotingMode, ("fileEncoding" .=) <$> _dfFileEncoding, ("columnDelimiter" .=) <$> _dfColumnDelimiter]) -- -- /See:/ 'productShipping' smart constructor. data ProductShipping = ProductShipping' { _psService :: !(Maybe Text) , _psLocationGroupName :: !(Maybe Text) , _psCountry :: !(Maybe Text) , _psPostalCode :: !(Maybe Text) , _psPrice :: !(Maybe Price) , _psRegion :: !(Maybe Text) , _psLocationId :: !(Maybe (Textual Int64)) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ProductShipping' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'psService' -- -- * 'psLocationGroupName' -- -- * 'psCountry' -- -- * 'psPostalCode' -- -- * 'psPrice' -- -- * 'psRegion' -- -- * 'psLocationId' productShipping :: ProductShipping productShipping = ProductShipping' { _psService = Nothing , _psLocationGroupName = Nothing , _psCountry = Nothing , _psPostalCode = Nothing , _psPrice = Nothing , _psRegion = Nothing , _psLocationId = Nothing } -- | A free-form description of the service class or delivery speed. psService :: Lens' ProductShipping (Maybe Text) psService = lens _psService (\ s a -> s{_psService = a}) -- | The location where the shipping is applicable, represented by a location -- group name. psLocationGroupName :: Lens' ProductShipping (Maybe Text) psLocationGroupName = lens _psLocationGroupName (\ s a -> s{_psLocationGroupName = a}) -- | The CLDR territory code of the country to which an item will ship. psCountry :: Lens' ProductShipping (Maybe Text) psCountry = lens _psCountry (\ s a -> s{_psCountry = a}) -- | The postal code range that the shipping rate applies to, represented by -- a postal code, a postal code prefix followed by a * wildcard, a range -- between two postal codes or two postal code prefixes of equal length. psPostalCode :: Lens' ProductShipping (Maybe Text) psPostalCode = lens _psPostalCode (\ s a -> s{_psPostalCode = a}) -- | Fixed shipping price, represented as a number. psPrice :: Lens' ProductShipping (Maybe Price) psPrice = lens _psPrice (\ s a -> s{_psPrice = a}) -- | The geographic region to which a shipping rate applies (e.g. zip code). psRegion :: Lens' ProductShipping (Maybe Text) psRegion = lens _psRegion (\ s a -> s{_psRegion = a}) -- | The numeric id of a location that the shipping rate applies to as -- defined in the AdWords API. psLocationId :: Lens' ProductShipping (Maybe Int64) psLocationId = lens _psLocationId (\ s a -> s{_psLocationId = a}) . mapping _Coerce instance FromJSON ProductShipping where parseJSON = withObject "ProductShipping" (\ o -> ProductShipping' <$> (o .:? "service") <*> (o .:? "locationGroupName") <*> (o .:? "country") <*> (o .:? "postalCode") <*> (o .:? "price") <*> (o .:? "region") <*> (o .:? "locationId")) instance ToJSON ProductShipping where toJSON ProductShipping'{..} = object (catMaybes [("service" .=) <$> _psService, ("locationGroupName" .=) <$> _psLocationGroupName, ("country" .=) <$> _psCountry, ("postalCode" .=) <$> _psPostalCode, ("price" .=) <$> _psPrice, ("region" .=) <$> _psRegion, ("locationId" .=) <$> _psLocationId]) -- -- /See:/ 'shippingSettingsCustomBatchRequest' smart constructor. newtype ShippingSettingsCustomBatchRequest = ShippingSettingsCustomBatchRequest' { _sscbrEntries :: Maybe [ShippingSettingsCustomBatchRequestEntry] } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ShippingSettingsCustomBatchRequest' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'sscbrEntries' shippingSettingsCustomBatchRequest :: ShippingSettingsCustomBatchRequest shippingSettingsCustomBatchRequest = ShippingSettingsCustomBatchRequest' { _sscbrEntries = Nothing } -- | The request entries to be processed in the batch. sscbrEntries :: Lens' ShippingSettingsCustomBatchRequest [ShippingSettingsCustomBatchRequestEntry] sscbrEntries = lens _sscbrEntries (\ s a -> s{_sscbrEntries = a}) . _Default . _Coerce instance FromJSON ShippingSettingsCustomBatchRequest where parseJSON = withObject "ShippingSettingsCustomBatchRequest" (\ o -> ShippingSettingsCustomBatchRequest' <$> (o .:? "entries" .!= mempty)) instance ToJSON ShippingSettingsCustomBatchRequest where toJSON ShippingSettingsCustomBatchRequest'{..} = object (catMaybes [("entries" .=) <$> _sscbrEntries]) -- | A batch entry encoding a single non-batch accountshipping request. -- -- /See:/ 'accountshippingCustomBatchRequestEntry' smart constructor. data AccountshippingCustomBatchRequestEntry = AccountshippingCustomBatchRequestEntry' { _aaMerchantId :: !(Maybe (Textual Word64)) , _aaAccountId :: !(Maybe (Textual Word64)) , _aaMethod :: !(Maybe Text) , _aaAccountShipping :: !(Maybe AccountShipping) , _aaBatchId :: !(Maybe (Textual Word32)) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'AccountshippingCustomBatchRequestEntry' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'aaMerchantId' -- -- * 'aaAccountId' -- -- * 'aaMethod' -- -- * 'aaAccountShipping' -- -- * 'aaBatchId' accountshippingCustomBatchRequestEntry :: AccountshippingCustomBatchRequestEntry accountshippingCustomBatchRequestEntry = AccountshippingCustomBatchRequestEntry' { _aaMerchantId = Nothing , _aaAccountId = Nothing , _aaMethod = Nothing , _aaAccountShipping = Nothing , _aaBatchId = Nothing } -- | The ID of the managing account. aaMerchantId :: Lens' AccountshippingCustomBatchRequestEntry (Maybe Word64) aaMerchantId = lens _aaMerchantId (\ s a -> s{_aaMerchantId = a}) . mapping _Coerce -- | The ID of the account for which to get\/update account shipping -- settings. aaAccountId :: Lens' AccountshippingCustomBatchRequestEntry (Maybe Word64) aaAccountId = lens _aaAccountId (\ s a -> s{_aaAccountId = a}) . mapping _Coerce aaMethod :: Lens' AccountshippingCustomBatchRequestEntry (Maybe Text) aaMethod = lens _aaMethod (\ s a -> s{_aaMethod = a}) -- | The account shipping settings to update. Only defined if the method is -- update. aaAccountShipping :: Lens' AccountshippingCustomBatchRequestEntry (Maybe AccountShipping) aaAccountShipping = lens _aaAccountShipping (\ s a -> s{_aaAccountShipping = a}) -- | An entry ID, unique within the batch request. aaBatchId :: Lens' AccountshippingCustomBatchRequestEntry (Maybe Word32) aaBatchId = lens _aaBatchId (\ s a -> s{_aaBatchId = a}) . mapping _Coerce instance FromJSON AccountshippingCustomBatchRequestEntry where parseJSON = withObject "AccountshippingCustomBatchRequestEntry" (\ o -> AccountshippingCustomBatchRequestEntry' <$> (o .:? "merchantId") <*> (o .:? "accountId") <*> (o .:? "method") <*> (o .:? "accountShipping") <*> (o .:? "batchId")) instance ToJSON AccountshippingCustomBatchRequestEntry where toJSON AccountshippingCustomBatchRequestEntry'{..} = object (catMaybes [("merchantId" .=) <$> _aaMerchantId, ("accountId" .=) <$> _aaAccountId, ("method" .=) <$> _aaMethod, ("accountShipping" .=) <$> _aaAccountShipping, ("batchId" .=) <$> _aaBatchId]) -- -- /See:/ 'accountsCustomBatchRequest' smart constructor. newtype AccountsCustomBatchRequest = AccountsCustomBatchRequest' { _accEntries :: Maybe [AccountsCustomBatchRequestEntry] } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'AccountsCustomBatchRequest' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'accEntries' accountsCustomBatchRequest :: AccountsCustomBatchRequest accountsCustomBatchRequest = AccountsCustomBatchRequest' { _accEntries = Nothing } -- | The request entries to be processed in the batch. accEntries :: Lens' AccountsCustomBatchRequest [AccountsCustomBatchRequestEntry] accEntries = lens _accEntries (\ s a -> s{_accEntries = a}) . _Default . _Coerce instance FromJSON AccountsCustomBatchRequest where parseJSON = withObject "AccountsCustomBatchRequest" (\ o -> AccountsCustomBatchRequest' <$> (o .:? "entries" .!= mempty)) instance ToJSON AccountsCustomBatchRequest where toJSON AccountsCustomBatchRequest'{..} = object (catMaybes [("entries" .=) <$> _accEntries]) -- -- /See:/ 'productCustomAttribute' smart constructor. data ProductCustomAttribute = ProductCustomAttribute' { _pcaValue :: !(Maybe Text) , _pcaName :: !(Maybe Text) , _pcaType :: !(Maybe Text) , _pcaUnit :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ProductCustomAttribute' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pcaValue' -- -- * 'pcaName' -- -- * 'pcaType' -- -- * 'pcaUnit' productCustomAttribute :: ProductCustomAttribute productCustomAttribute = ProductCustomAttribute' { _pcaValue = Nothing , _pcaName = Nothing , _pcaType = Nothing , _pcaUnit = Nothing } -- | The value of the attribute. pcaValue :: Lens' ProductCustomAttribute (Maybe Text) pcaValue = lens _pcaValue (\ s a -> s{_pcaValue = a}) -- | The name of the attribute. Underscores will be replaced by spaces upon -- insertion. pcaName :: Lens' ProductCustomAttribute (Maybe Text) pcaName = lens _pcaName (\ s a -> s{_pcaName = a}) -- | The type of the attribute. pcaType :: Lens' ProductCustomAttribute (Maybe Text) pcaType = lens _pcaType (\ s a -> s{_pcaType = a}) -- | Free-form unit of the attribute. Unit can only be used for values of -- type INT or FLOAT. pcaUnit :: Lens' ProductCustomAttribute (Maybe Text) pcaUnit = lens _pcaUnit (\ s a -> s{_pcaUnit = a}) instance FromJSON ProductCustomAttribute where parseJSON = withObject "ProductCustomAttribute" (\ o -> ProductCustomAttribute' <$> (o .:? "value") <*> (o .:? "name") <*> (o .:? "type") <*> (o .:? "unit")) instance ToJSON ProductCustomAttribute where toJSON ProductCustomAttribute'{..} = object (catMaybes [("value" .=) <$> _pcaValue, ("name" .=) <$> _pcaName, ("type" .=) <$> _pcaType, ("unit" .=) <$> _pcaUnit]) -- | A postal code range, that can be either: - A range of postal codes -- (e.g., start=12340, end=12359) - A range of postal codes prefixes (e.g., -- start=1234* end=1235*). Prefixes must be of the same length (e.g., -- start=12* end=2* is invalid). -- -- /See:/ 'accountShippingPostalCodeRange' smart constructor. data AccountShippingPostalCodeRange = AccountShippingPostalCodeRange' { _aspcrStart :: !(Maybe Text) , _aspcrEnd :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'AccountShippingPostalCodeRange' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'aspcrStart' -- -- * 'aspcrEnd' accountShippingPostalCodeRange :: AccountShippingPostalCodeRange accountShippingPostalCodeRange = AccountShippingPostalCodeRange' { _aspcrStart = Nothing , _aspcrEnd = Nothing } -- | The first (inclusive) postal code or prefix of the range. aspcrStart :: Lens' AccountShippingPostalCodeRange (Maybe Text) aspcrStart = lens _aspcrStart (\ s a -> s{_aspcrStart = a}) -- | The last (inclusive) postal code or prefix of the range. aspcrEnd :: Lens' AccountShippingPostalCodeRange (Maybe Text) aspcrEnd = lens _aspcrEnd (\ s a -> s{_aspcrEnd = a}) instance FromJSON AccountShippingPostalCodeRange where parseJSON = withObject "AccountShippingPostalCodeRange" (\ o -> AccountShippingPostalCodeRange' <$> (o .:? "start") <*> (o .:? "end")) instance ToJSON AccountShippingPostalCodeRange where toJSON AccountShippingPostalCodeRange'{..} = object (catMaybes [("start" .=) <$> _aspcrStart, ("end" .=) <$> _aspcrEnd]) -- -- /See:/ 'ordersListResponse' smart constructor. data OrdersListResponse = OrdersListResponse' { _olrNextPageToken :: !(Maybe Text) , _olrKind :: !Text , _olrResources :: !(Maybe [Order]) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'OrdersListResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'olrNextPageToken' -- -- * 'olrKind' -- -- * 'olrResources' ordersListResponse :: OrdersListResponse ordersListResponse = OrdersListResponse' { _olrNextPageToken = Nothing , _olrKind = "content#ordersListResponse" , _olrResources = Nothing } -- | The token for the retrieval of the next page of orders. olrNextPageToken :: Lens' OrdersListResponse (Maybe Text) olrNextPageToken = lens _olrNextPageToken (\ s a -> s{_olrNextPageToken = a}) -- | Identifies what kind of resource this is. Value: the fixed string -- \"content#ordersListResponse\". olrKind :: Lens' OrdersListResponse Text olrKind = lens _olrKind (\ s a -> s{_olrKind = a}) olrResources :: Lens' OrdersListResponse [Order] olrResources = lens _olrResources (\ s a -> s{_olrResources = a}) . _Default . _Coerce instance FromJSON OrdersListResponse where parseJSON = withObject "OrdersListResponse" (\ o -> OrdersListResponse' <$> (o .:? "nextPageToken") <*> (o .:? "kind" .!= "content#ordersListResponse") <*> (o .:? "resources" .!= mempty)) instance ToJSON OrdersListResponse where toJSON OrdersListResponse'{..} = object (catMaybes [("nextPageToken" .=) <$> _olrNextPageToken, Just ("kind" .= _olrKind), ("resources" .=) <$> _olrResources]) -- | A non-empty list of row or column headers for a table. Exactly one of -- prices, weights, numItems, postalCodeGroupNames, or locations must be -- set. -- -- /See:/ 'headers' smart constructor. data Headers = Headers' { _hNumberOfItems :: !(Maybe [Text]) , _hPostalCodeGroupNames :: !(Maybe [Text]) , _hPrices :: !(Maybe [Price]) , _hWeights :: !(Maybe [Weight]) , _hLocations :: !(Maybe [LocationIdSet]) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'Headers' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'hNumberOfItems' -- -- * 'hPostalCodeGroupNames' -- -- * 'hPrices' -- -- * 'hWeights' -- -- * 'hLocations' headers :: Headers headers = Headers' { _hNumberOfItems = Nothing , _hPostalCodeGroupNames = Nothing , _hPrices = Nothing , _hWeights = Nothing , _hLocations = Nothing } -- | A list of inclusive number of items upper bounds. The last value can be -- \"infinity\". For example [\"10\", \"50\", \"infinity\"] represents the -- headers \"\<= 10 items\", \" 50 items\". Must be non-empty. Can only be -- set if all other fields are not set. hNumberOfItems :: Lens' Headers [Text] hNumberOfItems = lens _hNumberOfItems (\ s a -> s{_hNumberOfItems = a}) . _Default . _Coerce -- | A list of postal group names. The last value can be \"all other -- locations\". Example: [\"zone 1\", \"zone 2\", \"all other locations\"]. -- The referred postal code groups must match the delivery country of the -- service. Must be non-empty. Can only be set if all other fields are not -- set. hPostalCodeGroupNames :: Lens' Headers [Text] hPostalCodeGroupNames = lens _hPostalCodeGroupNames (\ s a -> s{_hPostalCodeGroupNames = a}) . _Default . _Coerce -- | be \"infinity\". For example [{\"value\": \"10\", \"currency\": -- \"USD\"}, {\"value\": \"500\", \"currency\": \"USD\"}, {\"value\": -- \"infinity\", \"currency\": \"USD\"}] represents the headers \"\<= -- $10\", \" $500\". All prices within a service must have the same -- currency. Must be non-empty. Can only be set if all other fields are not -- set. hPrices :: Lens' Headers [Price] hPrices = lens _hPrices (\ s a -> s{_hPrices = a}) . _Default . _Coerce -- | be \"infinity\". For example [{\"value\": \"10\", \"unit\": \"kg\"}, -- {\"value\": \"50\", \"unit\": \"kg\"}, {\"value\": \"infinity\", -- \"unit\": \"kg\"}] represents the headers \"\<= 10kg\", \" 50kg\". All -- weights within a service must have the same unit. Must be non-empty. Can -- only be set if all other fields are not set. hWeights :: Lens' Headers [Weight] hWeights = lens _hWeights (\ s a -> s{_hWeights = a}) . _Default . _Coerce -- | A list of location ID sets. Must be non-empty. Can only be set if all -- other fields are not set. hLocations :: Lens' Headers [LocationIdSet] hLocations = lens _hLocations (\ s a -> s{_hLocations = a}) . _Default . _Coerce instance FromJSON Headers where parseJSON = withObject "Headers" (\ o -> Headers' <$> (o .:? "numberOfItems" .!= mempty) <*> (o .:? "postalCodeGroupNames" .!= mempty) <*> (o .:? "prices" .!= mempty) <*> (o .:? "weights" .!= mempty) <*> (o .:? "locations" .!= mempty)) instance ToJSON Headers where toJSON Headers'{..} = object (catMaybes [("numberOfItems" .=) <$> _hNumberOfItems, ("postalCodeGroupNames" .=) <$> _hPostalCodeGroupNames, ("prices" .=) <$> _hPrices, ("weights" .=) <$> _hWeights, ("locations" .=) <$> _hLocations]) -- -- /See:/ 'ordersShipLineItemsResponse' smart constructor. data OrdersShipLineItemsResponse = OrdersShipLineItemsResponse' { _oslirKind :: !Text , _oslirExecutionStatus :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'OrdersShipLineItemsResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'oslirKind' -- -- * 'oslirExecutionStatus' ordersShipLineItemsResponse :: OrdersShipLineItemsResponse ordersShipLineItemsResponse = OrdersShipLineItemsResponse' { _oslirKind = "content#ordersShipLineItemsResponse" , _oslirExecutionStatus = Nothing } -- | Identifies what kind of resource this is. Value: the fixed string -- \"content#ordersShipLineItemsResponse\". oslirKind :: Lens' OrdersShipLineItemsResponse Text oslirKind = lens _oslirKind (\ s a -> s{_oslirKind = a}) -- | The status of the execution. oslirExecutionStatus :: Lens' OrdersShipLineItemsResponse (Maybe Text) oslirExecutionStatus = lens _oslirExecutionStatus (\ s a -> s{_oslirExecutionStatus = a}) instance FromJSON OrdersShipLineItemsResponse where parseJSON = withObject "OrdersShipLineItemsResponse" (\ o -> OrdersShipLineItemsResponse' <$> (o .:? "kind" .!= "content#ordersShipLineItemsResponse") <*> (o .:? "executionStatus")) instance ToJSON OrdersShipLineItemsResponse where toJSON OrdersShipLineItemsResponse'{..} = object (catMaybes [Just ("kind" .= _oslirKind), ("executionStatus" .=) <$> _oslirExecutionStatus]) -- | Shipping services provided in a country. -- -- /See:/ 'accountShippingShippingService' smart constructor. data AccountShippingShippingService = AccountShippingShippingService' { _asssCostRuleTree :: !(Maybe AccountShippingShippingServiceCostRule) , _asssSaleCountry :: !(Maybe Text) , _asssMaxDaysInTransit :: !(Maybe (Textual Word64)) , _asssCalculationMethod :: !(Maybe AccountShippingShippingServiceCalculationMethod) , _asssActive :: !(Maybe Bool) , _asssName :: !(Maybe Text) , _asssMinDaysInTransit :: !(Maybe (Textual Word64)) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'AccountShippingShippingService' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'asssCostRuleTree' -- -- * 'asssSaleCountry' -- -- * 'asssMaxDaysInTransit' -- -- * 'asssCalculationMethod' -- -- * 'asssActive' -- -- * 'asssName' -- -- * 'asssMinDaysInTransit' accountShippingShippingService :: AccountShippingShippingService accountShippingShippingService = AccountShippingShippingService' { _asssCostRuleTree = Nothing , _asssSaleCountry = Nothing , _asssMaxDaysInTransit = Nothing , _asssCalculationMethod = Nothing , _asssActive = Nothing , _asssName = Nothing , _asssMinDaysInTransit = Nothing } -- | Decision tree for \"complicated\" shipping cost calculation. asssCostRuleTree :: Lens' AccountShippingShippingService (Maybe AccountShippingShippingServiceCostRule) asssCostRuleTree = lens _asssCostRuleTree (\ s a -> s{_asssCostRuleTree = a}) -- | The CLDR territory code of the sale country for which this service can -- be used. asssSaleCountry :: Lens' AccountShippingShippingService (Maybe Text) asssSaleCountry = lens _asssSaleCountry (\ s a -> s{_asssSaleCountry = a}) -- | The maximum number of days in transit. Must be a value between 0 and 250 -- included. A value of 0 means same day delivery. asssMaxDaysInTransit :: Lens' AccountShippingShippingService (Maybe Word64) asssMaxDaysInTransit = lens _asssMaxDaysInTransit (\ s a -> s{_asssMaxDaysInTransit = a}) . mapping _Coerce -- | Calculation method for the \"simple\" case that needs no rules. asssCalculationMethod :: Lens' AccountShippingShippingService (Maybe AccountShippingShippingServiceCalculationMethod) asssCalculationMethod = lens _asssCalculationMethod (\ s a -> s{_asssCalculationMethod = a}) -- | Whether the shipping service is available. asssActive :: Lens' AccountShippingShippingService (Maybe Bool) asssActive = lens _asssActive (\ s a -> s{_asssActive = a}) -- | The name of this shipping service. asssName :: Lens' AccountShippingShippingService (Maybe Text) asssName = lens _asssName (\ s a -> s{_asssName = a}) -- | The minimum number of days in transit. Must be a value between 0 and -- maxDaysIntransit included. A value of 0 means same day delivery. asssMinDaysInTransit :: Lens' AccountShippingShippingService (Maybe Word64) asssMinDaysInTransit = lens _asssMinDaysInTransit (\ s a -> s{_asssMinDaysInTransit = a}) . mapping _Coerce instance FromJSON AccountShippingShippingService where parseJSON = withObject "AccountShippingShippingService" (\ o -> AccountShippingShippingService' <$> (o .:? "costRuleTree") <*> (o .:? "saleCountry") <*> (o .:? "maxDaysInTransit") <*> (o .:? "calculationMethod") <*> (o .:? "active") <*> (o .:? "name") <*> (o .:? "minDaysInTransit")) instance ToJSON AccountShippingShippingService where toJSON AccountShippingShippingService'{..} = object (catMaybes [("costRuleTree" .=) <$> _asssCostRuleTree, ("saleCountry" .=) <$> _asssSaleCountry, ("maxDaysInTransit" .=) <$> _asssMaxDaysInTransit, ("calculationMethod" .=) <$> _asssCalculationMethod, ("active" .=) <$> _asssActive, ("name" .=) <$> _asssName, ("minDaysInTransit" .=) <$> _asssMinDaysInTransit]) -- | A single or bi-dimensional table of shipping rates. Each dimension is -- defined in terms of consecutive price\/weight ranges, delivery -- locations, or shipping labels. -- -- /See:/ 'accountShippingRateTable' smart constructor. data AccountShippingRateTable = AccountShippingRateTable' { _asrtSaleCountry :: !(Maybe Text) , _asrtContent :: !(Maybe [AccountShippingRateTableCell]) , _asrtName :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'AccountShippingRateTable' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'asrtSaleCountry' -- -- * 'asrtContent' -- -- * 'asrtName' accountShippingRateTable :: AccountShippingRateTable accountShippingRateTable = AccountShippingRateTable' { _asrtSaleCountry = Nothing , _asrtContent = Nothing , _asrtName = Nothing } -- | The sale country for which this table is valid, represented as a CLDR -- territory code. asrtSaleCountry :: Lens' AccountShippingRateTable (Maybe Text) asrtSaleCountry = lens _asrtSaleCountry (\ s a -> s{_asrtSaleCountry = a}) -- | One-dimensional table cells define one condition along the same -- dimension. Bi-dimensional table cells use two dimensions with -- respectively M and N distinct values and must contain exactly M * N -- cells with distinct conditions (for each possible value pairs). asrtContent :: Lens' AccountShippingRateTable [AccountShippingRateTableCell] asrtContent = lens _asrtContent (\ s a -> s{_asrtContent = a}) . _Default . _Coerce -- | The name of the rate table. asrtName :: Lens' AccountShippingRateTable (Maybe Text) asrtName = lens _asrtName (\ s a -> s{_asrtName = a}) instance FromJSON AccountShippingRateTable where parseJSON = withObject "AccountShippingRateTable" (\ o -> AccountShippingRateTable' <$> (o .:? "saleCountry") <*> (o .:? "content" .!= mempty) <*> (o .:? "name")) instance ToJSON AccountShippingRateTable where toJSON AccountShippingRateTable'{..} = object (catMaybes [("saleCountry" .=) <$> _asrtSaleCountry, ("content" .=) <$> _asrtContent, ("name" .=) <$> _asrtName]) -- -- /See:/ 'accountshippingCustomBatchResponse' smart constructor. data AccountshippingCustomBatchResponse = AccountshippingCustomBatchResponse' { _acccEntries :: !(Maybe [AccountshippingCustomBatchResponseEntry]) , _acccKind :: !Text } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'AccountshippingCustomBatchResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'acccEntries' -- -- * 'acccKind' accountshippingCustomBatchResponse :: AccountshippingCustomBatchResponse accountshippingCustomBatchResponse = AccountshippingCustomBatchResponse' { _acccEntries = Nothing , _acccKind = "content#accountshippingCustomBatchResponse" } -- | The result of the execution of the batch requests. acccEntries :: Lens' AccountshippingCustomBatchResponse [AccountshippingCustomBatchResponseEntry] acccEntries = lens _acccEntries (\ s a -> s{_acccEntries = a}) . _Default . _Coerce -- | Identifies what kind of resource this is. Value: the fixed string -- \"content#accountshippingCustomBatchResponse\". acccKind :: Lens' AccountshippingCustomBatchResponse Text acccKind = lens _acccKind (\ s a -> s{_acccKind = a}) instance FromJSON AccountshippingCustomBatchResponse where parseJSON = withObject "AccountshippingCustomBatchResponse" (\ o -> AccountshippingCustomBatchResponse' <$> (o .:? "entries" .!= mempty) <*> (o .:? "kind" .!= "content#accountshippingCustomBatchResponse")) instance ToJSON AccountshippingCustomBatchResponse where toJSON AccountshippingCustomBatchResponse'{..} = object (catMaybes [("entries" .=) <$> _acccEntries, Just ("kind" .= _acccKind)]) -- | The merchant account\'s shipping settings. -- -- /See:/ 'shippingSettings' smart constructor. data ShippingSettings = ShippingSettings' { _ssPostalCodeGroups :: !(Maybe [PostalCodeGroup]) , _ssAccountId :: !(Maybe (Textual Word64)) , _ssServices :: !(Maybe [Service]) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ShippingSettings' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ssPostalCodeGroups' -- -- * 'ssAccountId' -- -- * 'ssServices' shippingSettings :: ShippingSettings shippingSettings = ShippingSettings' { _ssPostalCodeGroups = Nothing , _ssAccountId = Nothing , _ssServices = Nothing } -- | A list of postal code groups that can be referred to in services. -- Optional. ssPostalCodeGroups :: Lens' ShippingSettings [PostalCodeGroup] ssPostalCodeGroups = lens _ssPostalCodeGroups (\ s a -> s{_ssPostalCodeGroups = a}) . _Default . _Coerce -- | The ID of the account to which these account shipping settings belong. -- Ignored upon update, always present in get request responses. ssAccountId :: Lens' ShippingSettings (Maybe Word64) ssAccountId = lens _ssAccountId (\ s a -> s{_ssAccountId = a}) . mapping _Coerce -- | The target account\'s list of services. Optional. ssServices :: Lens' ShippingSettings [Service] ssServices = lens _ssServices (\ s a -> s{_ssServices = a}) . _Default . _Coerce instance FromJSON ShippingSettings where parseJSON = withObject "ShippingSettings" (\ o -> ShippingSettings' <$> (o .:? "postalCodeGroups" .!= mempty) <*> (o .:? "accountId") <*> (o .:? "services" .!= mempty)) instance ToJSON ShippingSettings where toJSON ShippingSettings'{..} = object (catMaybes [("postalCodeGroups" .=) <$> _ssPostalCodeGroups, ("accountId" .=) <$> _ssAccountId, ("services" .=) <$> _ssServices]) -- -- /See:/ 'postalCodeRange' smart constructor. data PostalCodeRange = PostalCodeRange' { _pcrPostalCodeRangeBegin :: !(Maybe Text) , _pcrPostalCodeRangeEnd :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'PostalCodeRange' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pcrPostalCodeRangeBegin' -- -- * 'pcrPostalCodeRangeEnd' postalCodeRange :: PostalCodeRange postalCodeRange = PostalCodeRange' { _pcrPostalCodeRangeBegin = Nothing , _pcrPostalCodeRangeEnd = Nothing } -- | A postal code or a pattern of the form prefix* denoting the inclusive -- lower bound of the range defining the area. Examples values: \"94108\", -- \"9410*\", \"9*\". Required. pcrPostalCodeRangeBegin :: Lens' PostalCodeRange (Maybe Text) pcrPostalCodeRangeBegin = lens _pcrPostalCodeRangeBegin (\ s a -> s{_pcrPostalCodeRangeBegin = a}) -- | A postal code or a pattern of the form prefix* denoting the inclusive -- upper bound of the range defining the area. It must have the same length -- as postalCodeRangeBegin: if postalCodeRangeBegin is a postal code then -- postalCodeRangeEnd must be a postal code too; if postalCodeRangeBegin is -- a pattern then postalCodeRangeEnd must be a pattern with the same prefix -- length. Optional: if not set, then the area is defined as being all the -- postal codes matching postalCodeRangeBegin. pcrPostalCodeRangeEnd :: Lens' PostalCodeRange (Maybe Text) pcrPostalCodeRangeEnd = lens _pcrPostalCodeRangeEnd (\ s a -> s{_pcrPostalCodeRangeEnd = a}) instance FromJSON PostalCodeRange where parseJSON = withObject "PostalCodeRange" (\ o -> PostalCodeRange' <$> (o .:? "postalCodeRangeBegin") <*> (o .:? "postalCodeRangeEnd")) instance ToJSON PostalCodeRange where toJSON PostalCodeRange'{..} = object (catMaybes [("postalCodeRangeBegin" .=) <$> _pcrPostalCodeRangeBegin, ("postalCodeRangeEnd" .=) <$> _pcrPostalCodeRangeEnd]) -- -- /See:/ 'ordersUpdateShipmentResponse' smart constructor. data OrdersUpdateShipmentResponse = OrdersUpdateShipmentResponse' { _ousrKind :: !Text , _ousrExecutionStatus :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'OrdersUpdateShipmentResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ousrKind' -- -- * 'ousrExecutionStatus' ordersUpdateShipmentResponse :: OrdersUpdateShipmentResponse ordersUpdateShipmentResponse = OrdersUpdateShipmentResponse' { _ousrKind = "content#ordersUpdateShipmentResponse" , _ousrExecutionStatus = Nothing } -- | Identifies what kind of resource this is. Value: the fixed string -- \"content#ordersUpdateShipmentResponse\". ousrKind :: Lens' OrdersUpdateShipmentResponse Text ousrKind = lens _ousrKind (\ s a -> s{_ousrKind = a}) -- | The status of the execution. ousrExecutionStatus :: Lens' OrdersUpdateShipmentResponse (Maybe Text) ousrExecutionStatus = lens _ousrExecutionStatus (\ s a -> s{_ousrExecutionStatus = a}) instance FromJSON OrdersUpdateShipmentResponse where parseJSON = withObject "OrdersUpdateShipmentResponse" (\ o -> OrdersUpdateShipmentResponse' <$> (o .:? "kind" .!= "content#ordersUpdateShipmentResponse") <*> (o .:? "executionStatus")) instance ToJSON OrdersUpdateShipmentResponse where toJSON OrdersUpdateShipmentResponse'{..} = object (catMaybes [Just ("kind" .= _ousrKind), ("executionStatus" .=) <$> _ousrExecutionStatus]) -- -- /See:/ 'productstatusesCustomBatchRequest' smart constructor. newtype ProductstatusesCustomBatchRequest = ProductstatusesCustomBatchRequest' { _proEntries :: Maybe [ProductstatusesCustomBatchRequestEntry] } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ProductstatusesCustomBatchRequest' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'proEntries' productstatusesCustomBatchRequest :: ProductstatusesCustomBatchRequest productstatusesCustomBatchRequest = ProductstatusesCustomBatchRequest' { _proEntries = Nothing } -- | The request entries to be processed in the batch. proEntries :: Lens' ProductstatusesCustomBatchRequest [ProductstatusesCustomBatchRequestEntry] proEntries = lens _proEntries (\ s a -> s{_proEntries = a}) . _Default . _Coerce instance FromJSON ProductstatusesCustomBatchRequest where parseJSON = withObject "ProductstatusesCustomBatchRequest" (\ o -> ProductstatusesCustomBatchRequest' <$> (o .:? "entries" .!= mempty)) instance ToJSON ProductstatusesCustomBatchRequest where toJSON ProductstatusesCustomBatchRequest'{..} = object (catMaybes [("entries" .=) <$> _proEntries]) -- -- /See:/ 'ordersReturnLineItemResponse' smart constructor. data OrdersReturnLineItemResponse = OrdersReturnLineItemResponse' { _orlirKind :: !Text , _orlirExecutionStatus :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'OrdersReturnLineItemResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'orlirKind' -- -- * 'orlirExecutionStatus' ordersReturnLineItemResponse :: OrdersReturnLineItemResponse ordersReturnLineItemResponse = OrdersReturnLineItemResponse' { _orlirKind = "content#ordersReturnLineItemResponse" , _orlirExecutionStatus = Nothing } -- | Identifies what kind of resource this is. Value: the fixed string -- \"content#ordersReturnLineItemResponse\". orlirKind :: Lens' OrdersReturnLineItemResponse Text orlirKind = lens _orlirKind (\ s a -> s{_orlirKind = a}) -- | The status of the execution. orlirExecutionStatus :: Lens' OrdersReturnLineItemResponse (Maybe Text) orlirExecutionStatus = lens _orlirExecutionStatus (\ s a -> s{_orlirExecutionStatus = a}) instance FromJSON OrdersReturnLineItemResponse where parseJSON = withObject "OrdersReturnLineItemResponse" (\ o -> OrdersReturnLineItemResponse' <$> (o .:? "kind" .!= "content#ordersReturnLineItemResponse") <*> (o .:? "executionStatus")) instance ToJSON OrdersReturnLineItemResponse where toJSON OrdersReturnLineItemResponse'{..} = object (catMaybes [Just ("kind" .= _orlirKind), ("executionStatus" .=) <$> _orlirExecutionStatus]) -- -- /See:/ 'productCustomGroup' smart constructor. data ProductCustomGroup = ProductCustomGroup' { _pName :: !(Maybe Text) , _pAttributes :: !(Maybe [ProductCustomAttribute]) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ProductCustomGroup' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pName' -- -- * 'pAttributes' productCustomGroup :: ProductCustomGroup productCustomGroup = ProductCustomGroup' { _pName = Nothing , _pAttributes = Nothing } -- | The name of the group. Underscores will be replaced by spaces upon -- insertion. pName :: Lens' ProductCustomGroup (Maybe Text) pName = lens _pName (\ s a -> s{_pName = a}) -- | The sub-attributes. pAttributes :: Lens' ProductCustomGroup [ProductCustomAttribute] pAttributes = lens _pAttributes (\ s a -> s{_pAttributes = a}) . _Default . _Coerce instance FromJSON ProductCustomGroup where parseJSON = withObject "ProductCustomGroup" (\ o -> ProductCustomGroup' <$> (o .:? "name") <*> (o .:? "attributes" .!= mempty)) instance ToJSON ProductCustomGroup where toJSON ProductCustomGroup'{..} = object (catMaybes [("name" .=) <$> _pName, ("attributes" .=) <$> _pAttributes]) -- -- /See:/ 'accountstatusesCustomBatchResponse' smart constructor. data AccountstatusesCustomBatchResponse = AccountstatusesCustomBatchResponse' { _acbr1Entries :: !(Maybe [AccountstatusesCustomBatchResponseEntry]) , _acbr1Kind :: !Text } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'AccountstatusesCustomBatchResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'acbr1Entries' -- -- * 'acbr1Kind' accountstatusesCustomBatchResponse :: AccountstatusesCustomBatchResponse accountstatusesCustomBatchResponse = AccountstatusesCustomBatchResponse' { _acbr1Entries = Nothing , _acbr1Kind = "content#accountstatusesCustomBatchResponse" } -- | The result of the execution of the batch requests. acbr1Entries :: Lens' AccountstatusesCustomBatchResponse [AccountstatusesCustomBatchResponseEntry] acbr1Entries = lens _acbr1Entries (\ s a -> s{_acbr1Entries = a}) . _Default . _Coerce -- | Identifies what kind of resource this is. Value: the fixed string -- \"content#accountstatusesCustomBatchResponse\". acbr1Kind :: Lens' AccountstatusesCustomBatchResponse Text acbr1Kind = lens _acbr1Kind (\ s a -> s{_acbr1Kind = a}) instance FromJSON AccountstatusesCustomBatchResponse where parseJSON = withObject "AccountstatusesCustomBatchResponse" (\ o -> AccountstatusesCustomBatchResponse' <$> (o .:? "entries" .!= mempty) <*> (o .:? "kind" .!= "content#accountstatusesCustomBatchResponse")) instance ToJSON AccountstatusesCustomBatchResponse where toJSON AccountstatusesCustomBatchResponse'{..} = object (catMaybes [("entries" .=) <$> _acbr1Entries, Just ("kind" .= _acbr1Kind)]) -- | A batch entry encoding a single non-batch shipping settings response. -- -- /See:/ 'shippingSettingsCustomBatchResponseEntry' smart constructor. data ShippingSettingsCustomBatchResponseEntry = ShippingSettingsCustomBatchResponseEntry' { _sKind :: !Text , _sShippingSettings :: !(Maybe ShippingSettings) , _sErrors :: !(Maybe Errors) , _sBatchId :: !(Maybe (Textual Word32)) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ShippingSettingsCustomBatchResponseEntry' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'sKind' -- -- * 'sShippingSettings' -- -- * 'sErrors' -- -- * 'sBatchId' shippingSettingsCustomBatchResponseEntry :: ShippingSettingsCustomBatchResponseEntry shippingSettingsCustomBatchResponseEntry = ShippingSettingsCustomBatchResponseEntry' { _sKind = "content#shippingsettingsCustomBatchResponseEntry" , _sShippingSettings = Nothing , _sErrors = Nothing , _sBatchId = Nothing } -- | Identifies what kind of resource this is. Value: the fixed string -- \"content#shippingsettingsCustomBatchResponseEntry\". sKind :: Lens' ShippingSettingsCustomBatchResponseEntry Text sKind = lens _sKind (\ s a -> s{_sKind = a}) -- | The retrieved or updated account shipping settings. sShippingSettings :: Lens' ShippingSettingsCustomBatchResponseEntry (Maybe ShippingSettings) sShippingSettings = lens _sShippingSettings (\ s a -> s{_sShippingSettings = a}) -- | A list of errors defined if, and only if, the request failed. sErrors :: Lens' ShippingSettingsCustomBatchResponseEntry (Maybe Errors) sErrors = lens _sErrors (\ s a -> s{_sErrors = a}) -- | The ID of the request entry to which this entry responds. sBatchId :: Lens' ShippingSettingsCustomBatchResponseEntry (Maybe Word32) sBatchId = lens _sBatchId (\ s a -> s{_sBatchId = a}) . mapping _Coerce instance FromJSON ShippingSettingsCustomBatchResponseEntry where parseJSON = withObject "ShippingSettingsCustomBatchResponseEntry" (\ o -> ShippingSettingsCustomBatchResponseEntry' <$> (o .:? "kind" .!= "content#shippingsettingsCustomBatchResponseEntry") <*> (o .:? "shippingSettings") <*> (o .:? "errors") <*> (o .:? "batchId")) instance ToJSON ShippingSettingsCustomBatchResponseEntry where toJSON ShippingSettingsCustomBatchResponseEntry'{..} = object (catMaybes [Just ("kind" .= _sKind), ("shippingSettings" .=) <$> _sShippingSettings, ("errors" .=) <$> _sErrors, ("batchId" .=) <$> _sBatchId]) -- | The status of a product, i.e., information about a product computed -- asynchronously by the data quality analysis. -- -- /See:/ 'productStatus' smart constructor. data ProductStatus = ProductStatus' { _psDataQualityIssues :: !(Maybe [ProductStatusDataQualityIssue]) , _psKind :: !Text , _psLink :: !(Maybe Text) , _psDestinationStatuses :: !(Maybe [ProductStatusDestinationStatus]) , _psLastUpdateDate :: !(Maybe Text) , _psCreationDate :: !(Maybe Text) , _psTitle :: !(Maybe Text) , _psGoogleExpirationDate :: !(Maybe Text) , _psProductId :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ProductStatus' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'psDataQualityIssues' -- -- * 'psKind' -- -- * 'psLink' -- -- * 'psDestinationStatuses' -- -- * 'psLastUpdateDate' -- -- * 'psCreationDate' -- -- * 'psTitle' -- -- * 'psGoogleExpirationDate' -- -- * 'psProductId' productStatus :: ProductStatus productStatus = ProductStatus' { _psDataQualityIssues = Nothing , _psKind = "content#productStatus" , _psLink = Nothing , _psDestinationStatuses = Nothing , _psLastUpdateDate = Nothing , _psCreationDate = Nothing , _psTitle = Nothing , _psGoogleExpirationDate = Nothing , _psProductId = Nothing } -- | A list of data quality issues associated with the product. psDataQualityIssues :: Lens' ProductStatus [ProductStatusDataQualityIssue] psDataQualityIssues = lens _psDataQualityIssues (\ s a -> s{_psDataQualityIssues = a}) . _Default . _Coerce -- | Identifies what kind of resource this is. Value: the fixed string -- \"content#productStatus\". psKind :: Lens' ProductStatus Text psKind = lens _psKind (\ s a -> s{_psKind = a}) -- | The link to the product. psLink :: Lens' ProductStatus (Maybe Text) psLink = lens _psLink (\ s a -> s{_psLink = a}) -- | The intended destinations for the product. psDestinationStatuses :: Lens' ProductStatus [ProductStatusDestinationStatus] psDestinationStatuses = lens _psDestinationStatuses (\ s a -> s{_psDestinationStatuses = a}) . _Default . _Coerce -- | Date on which the item has been last updated, in ISO 8601 format. psLastUpdateDate :: Lens' ProductStatus (Maybe Text) psLastUpdateDate = lens _psLastUpdateDate (\ s a -> s{_psLastUpdateDate = a}) -- | Date on which the item has been created, in ISO 8601 format. psCreationDate :: Lens' ProductStatus (Maybe Text) psCreationDate = lens _psCreationDate (\ s a -> s{_psCreationDate = a}) -- | The title of the product. psTitle :: Lens' ProductStatus (Maybe Text) psTitle = lens _psTitle (\ s a -> s{_psTitle = a}) -- | Date on which the item expires in Google Shopping, in ISO 8601 format. psGoogleExpirationDate :: Lens' ProductStatus (Maybe Text) psGoogleExpirationDate = lens _psGoogleExpirationDate (\ s a -> s{_psGoogleExpirationDate = a}) -- | The id of the product for which status is reported. psProductId :: Lens' ProductStatus (Maybe Text) psProductId = lens _psProductId (\ s a -> s{_psProductId = a}) instance FromJSON ProductStatus where parseJSON = withObject "ProductStatus" (\ o -> ProductStatus' <$> (o .:? "dataQualityIssues" .!= mempty) <*> (o .:? "kind" .!= "content#productStatus") <*> (o .:? "link") <*> (o .:? "destinationStatuses" .!= mempty) <*> (o .:? "lastUpdateDate") <*> (o .:? "creationDate") <*> (o .:? "title") <*> (o .:? "googleExpirationDate") <*> (o .:? "productId")) instance ToJSON ProductStatus where toJSON ProductStatus'{..} = object (catMaybes [("dataQualityIssues" .=) <$> _psDataQualityIssues, Just ("kind" .= _psKind), ("link" .=) <$> _psLink, ("destinationStatuses" .=) <$> _psDestinationStatuses, ("lastUpdateDate" .=) <$> _psLastUpdateDate, ("creationDate" .=) <$> _psCreationDate, ("title" .=) <$> _psTitle, ("googleExpirationDate" .=) <$> _psGoogleExpirationDate, ("productId" .=) <$> _psProductId]) -- -- /See:/ 'accountstatusesListResponse' smart constructor. data AccountstatusesListResponse = AccountstatusesListResponse' { _alrlNextPageToken :: !(Maybe Text) , _alrlKind :: !Text , _alrlResources :: !(Maybe [AccountStatus]) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'AccountstatusesListResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'alrlNextPageToken' -- -- * 'alrlKind' -- -- * 'alrlResources' accountstatusesListResponse :: AccountstatusesListResponse accountstatusesListResponse = AccountstatusesListResponse' { _alrlNextPageToken = Nothing , _alrlKind = "content#accountstatusesListResponse" , _alrlResources = Nothing } -- | The token for the retrieval of the next page of account statuses. alrlNextPageToken :: Lens' AccountstatusesListResponse (Maybe Text) alrlNextPageToken = lens _alrlNextPageToken (\ s a -> s{_alrlNextPageToken = a}) -- | Identifies what kind of resource this is. Value: the fixed string -- \"content#accountstatusesListResponse\". alrlKind :: Lens' AccountstatusesListResponse Text alrlKind = lens _alrlKind (\ s a -> s{_alrlKind = a}) alrlResources :: Lens' AccountstatusesListResponse [AccountStatus] alrlResources = lens _alrlResources (\ s a -> s{_alrlResources = a}) . _Default . _Coerce instance FromJSON AccountstatusesListResponse where parseJSON = withObject "AccountstatusesListResponse" (\ o -> AccountstatusesListResponse' <$> (o .:? "nextPageToken") <*> (o .:? "kind" .!= "content#accountstatusesListResponse") <*> (o .:? "resources" .!= mempty)) instance ToJSON AccountstatusesListResponse where toJSON AccountstatusesListResponse'{..} = object (catMaybes [("nextPageToken" .=) <$> _alrlNextPageToken, Just ("kind" .= _alrlKind), ("resources" .=) <$> _alrlResources]) -- -- /See:/ 'accounttaxCustomBatchRequest' smart constructor. newtype AccounttaxCustomBatchRequest = AccounttaxCustomBatchRequest' { _aaEntries :: Maybe [AccounttaxCustomBatchRequestEntry] } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'AccounttaxCustomBatchRequest' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'aaEntries' accounttaxCustomBatchRequest :: AccounttaxCustomBatchRequest accounttaxCustomBatchRequest = AccounttaxCustomBatchRequest' { _aaEntries = Nothing } -- | The request entries to be processed in the batch. aaEntries :: Lens' AccounttaxCustomBatchRequest [AccounttaxCustomBatchRequestEntry] aaEntries = lens _aaEntries (\ s a -> s{_aaEntries = a}) . _Default . _Coerce instance FromJSON AccounttaxCustomBatchRequest where parseJSON = withObject "AccounttaxCustomBatchRequest" (\ o -> AccounttaxCustomBatchRequest' <$> (o .:? "entries" .!= mempty)) instance ToJSON AccounttaxCustomBatchRequest where toJSON AccounttaxCustomBatchRequest'{..} = object (catMaybes [("entries" .=) <$> _aaEntries]) -- | A batch entry encoding a single non-batch products request. -- -- /See:/ 'productsCustomBatchRequestEntry' smart constructor. data ProductsCustomBatchRequestEntry = ProductsCustomBatchRequestEntry' { _pMerchantId :: !(Maybe (Textual Word64)) , _pMethod :: !(Maybe Text) , _pProduct :: !(Maybe Product) , _pProductId :: !(Maybe Text) , _pBatchId :: !(Maybe (Textual Word32)) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ProductsCustomBatchRequestEntry' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pMerchantId' -- -- * 'pMethod' -- -- * 'pProduct' -- -- * 'pProductId' -- -- * 'pBatchId' productsCustomBatchRequestEntry :: ProductsCustomBatchRequestEntry productsCustomBatchRequestEntry = ProductsCustomBatchRequestEntry' { _pMerchantId = Nothing , _pMethod = Nothing , _pProduct = Nothing , _pProductId = Nothing , _pBatchId = Nothing } -- | The ID of the managing account. pMerchantId :: Lens' ProductsCustomBatchRequestEntry (Maybe Word64) pMerchantId = lens _pMerchantId (\ s a -> s{_pMerchantId = a}) . mapping _Coerce pMethod :: Lens' ProductsCustomBatchRequestEntry (Maybe Text) pMethod = lens _pMethod (\ s a -> s{_pMethod = a}) -- | The product to insert. Only required if the method is insert. pProduct :: Lens' ProductsCustomBatchRequestEntry (Maybe Product) pProduct = lens _pProduct (\ s a -> s{_pProduct = a}) -- | The ID of the product to get or delete. Only defined if the method is -- get or delete. pProductId :: Lens' ProductsCustomBatchRequestEntry (Maybe Text) pProductId = lens _pProductId (\ s a -> s{_pProductId = a}) -- | An entry ID, unique within the batch request. pBatchId :: Lens' ProductsCustomBatchRequestEntry (Maybe Word32) pBatchId = lens _pBatchId (\ s a -> s{_pBatchId = a}) . mapping _Coerce instance FromJSON ProductsCustomBatchRequestEntry where parseJSON = withObject "ProductsCustomBatchRequestEntry" (\ o -> ProductsCustomBatchRequestEntry' <$> (o .:? "merchantId") <*> (o .:? "method") <*> (o .:? "product") <*> (o .:? "productId") <*> (o .:? "batchId")) instance ToJSON ProductsCustomBatchRequestEntry where toJSON ProductsCustomBatchRequestEntry'{..} = object (catMaybes [("merchantId" .=) <$> _pMerchantId, ("method" .=) <$> _pMethod, ("product" .=) <$> _pProduct, ("productId" .=) <$> _pProductId, ("batchId" .=) <$> _pBatchId]) -- | A batch entry encoding a single non-batch datafeedstatuses request. -- -- /See:/ 'datafeedstatusesCustomBatchRequestEntry' smart constructor. data DatafeedstatusesCustomBatchRequestEntry = DatafeedstatusesCustomBatchRequestEntry' { _dMerchantId :: !(Maybe (Textual Word64)) , _dMethod :: !(Maybe Text) , _dDatafeedId :: !(Maybe (Textual Word64)) , _dBatchId :: !(Maybe (Textual Word32)) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'DatafeedstatusesCustomBatchRequestEntry' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dMerchantId' -- -- * 'dMethod' -- -- * 'dDatafeedId' -- -- * 'dBatchId' datafeedstatusesCustomBatchRequestEntry :: DatafeedstatusesCustomBatchRequestEntry datafeedstatusesCustomBatchRequestEntry = DatafeedstatusesCustomBatchRequestEntry' { _dMerchantId = Nothing , _dMethod = Nothing , _dDatafeedId = Nothing , _dBatchId = Nothing } -- | The ID of the managing account. dMerchantId :: Lens' DatafeedstatusesCustomBatchRequestEntry (Maybe Word64) dMerchantId = lens _dMerchantId (\ s a -> s{_dMerchantId = a}) . mapping _Coerce dMethod :: Lens' DatafeedstatusesCustomBatchRequestEntry (Maybe Text) dMethod = lens _dMethod (\ s a -> s{_dMethod = a}) -- | The ID of the data feed to get or delete. dDatafeedId :: Lens' DatafeedstatusesCustomBatchRequestEntry (Maybe Word64) dDatafeedId = lens _dDatafeedId (\ s a -> s{_dDatafeedId = a}) . mapping _Coerce -- | An entry ID, unique within the batch request. dBatchId :: Lens' DatafeedstatusesCustomBatchRequestEntry (Maybe Word32) dBatchId = lens _dBatchId (\ s a -> s{_dBatchId = a}) . mapping _Coerce instance FromJSON DatafeedstatusesCustomBatchRequestEntry where parseJSON = withObject "DatafeedstatusesCustomBatchRequestEntry" (\ o -> DatafeedstatusesCustomBatchRequestEntry' <$> (o .:? "merchantId") <*> (o .:? "method") <*> (o .:? "datafeedId") <*> (o .:? "batchId")) instance ToJSON DatafeedstatusesCustomBatchRequestEntry where toJSON DatafeedstatusesCustomBatchRequestEntry'{..} = object (catMaybes [("merchantId" .=) <$> _dMerchantId, ("method" .=) <$> _dMethod, ("datafeedId" .=) <$> _dDatafeedId, ("batchId" .=) <$> _dBatchId]) -- -- /See:/ 'orderCustomer' smart constructor. data OrderCustomer = OrderCustomer' { _ocFullName :: !(Maybe Text) , _ocEmail :: !(Maybe Text) , _ocExplicitMarketingPreference :: !(Maybe Bool) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'OrderCustomer' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ocFullName' -- -- * 'ocEmail' -- -- * 'ocExplicitMarketingPreference' orderCustomer :: OrderCustomer orderCustomer = OrderCustomer' { _ocFullName = Nothing , _ocEmail = Nothing , _ocExplicitMarketingPreference = Nothing } -- | Full name of the customer. ocFullName :: Lens' OrderCustomer (Maybe Text) ocFullName = lens _ocFullName (\ s a -> s{_ocFullName = a}) -- | Email address of the customer. ocEmail :: Lens' OrderCustomer (Maybe Text) ocEmail = lens _ocEmail (\ s a -> s{_ocEmail = a}) -- | If set, this indicates the user explicitly chose to opt in or out of -- providing marketing rights to the merchant. If unset, this indicates the -- user has already made this choice in a previous purchase, and was thus -- not shown the marketing right opt in\/out checkbox during the checkout -- flow. ocExplicitMarketingPreference :: Lens' OrderCustomer (Maybe Bool) ocExplicitMarketingPreference = lens _ocExplicitMarketingPreference (\ s a -> s{_ocExplicitMarketingPreference = a}) instance FromJSON OrderCustomer where parseJSON = withObject "OrderCustomer" (\ o -> OrderCustomer' <$> (o .:? "fullName") <*> (o .:? "email") <*> (o .:? "explicitMarketingPreference")) instance ToJSON OrderCustomer where toJSON OrderCustomer'{..} = object (catMaybes [("fullName" .=) <$> _ocFullName, ("email" .=) <$> _ocEmail, ("explicitMarketingPreference" .=) <$> _ocExplicitMarketingPreference]) -- | A batch entry encoding a single non-batch inventory response. -- -- /See:/ 'inventoryCustomBatchResponseEntry' smart constructor. data InventoryCustomBatchResponseEntry = InventoryCustomBatchResponseEntry' { _icbreKind :: !Text , _icbreErrors :: !(Maybe Errors) , _icbreBatchId :: !(Maybe (Textual Word32)) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'InventoryCustomBatchResponseEntry' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'icbreKind' -- -- * 'icbreErrors' -- -- * 'icbreBatchId' inventoryCustomBatchResponseEntry :: InventoryCustomBatchResponseEntry inventoryCustomBatchResponseEntry = InventoryCustomBatchResponseEntry' { _icbreKind = "content#inventoryCustomBatchResponseEntry" , _icbreErrors = Nothing , _icbreBatchId = Nothing } -- | Identifies what kind of resource this is. Value: the fixed string -- \"content#inventoryCustomBatchResponseEntry\". icbreKind :: Lens' InventoryCustomBatchResponseEntry Text icbreKind = lens _icbreKind (\ s a -> s{_icbreKind = a}) -- | A list of errors defined if and only if the request failed. icbreErrors :: Lens' InventoryCustomBatchResponseEntry (Maybe Errors) icbreErrors = lens _icbreErrors (\ s a -> s{_icbreErrors = a}) -- | The ID of the request entry this entry responds to. icbreBatchId :: Lens' InventoryCustomBatchResponseEntry (Maybe Word32) icbreBatchId = lens _icbreBatchId (\ s a -> s{_icbreBatchId = a}) . mapping _Coerce instance FromJSON InventoryCustomBatchResponseEntry where parseJSON = withObject "InventoryCustomBatchResponseEntry" (\ o -> InventoryCustomBatchResponseEntry' <$> (o .:? "kind" .!= "content#inventoryCustomBatchResponseEntry") <*> (o .:? "errors") <*> (o .:? "batchId")) instance ToJSON InventoryCustomBatchResponseEntry where toJSON InventoryCustomBatchResponseEntry'{..} = object (catMaybes [Just ("kind" .= _icbreKind), ("errors" .=) <$> _icbreErrors, ("batchId" .=) <$> _icbreBatchId]) -- -- /See:/ 'accountshippingListResponse' smart constructor. data AccountshippingListResponse = AccountshippingListResponse' { _alr1NextPageToken :: !(Maybe Text) , _alr1Kind :: !Text , _alr1Resources :: !(Maybe [AccountShipping]) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'AccountshippingListResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'alr1NextPageToken' -- -- * 'alr1Kind' -- -- * 'alr1Resources' accountshippingListResponse :: AccountshippingListResponse accountshippingListResponse = AccountshippingListResponse' { _alr1NextPageToken = Nothing , _alr1Kind = "content#accountshippingListResponse" , _alr1Resources = Nothing } -- | The token for the retrieval of the next page of account shipping -- settings. alr1NextPageToken :: Lens' AccountshippingListResponse (Maybe Text) alr1NextPageToken = lens _alr1NextPageToken (\ s a -> s{_alr1NextPageToken = a}) -- | Identifies what kind of resource this is. Value: the fixed string -- \"content#accountshippingListResponse\". alr1Kind :: Lens' AccountshippingListResponse Text alr1Kind = lens _alr1Kind (\ s a -> s{_alr1Kind = a}) alr1Resources :: Lens' AccountshippingListResponse [AccountShipping] alr1Resources = lens _alr1Resources (\ s a -> s{_alr1Resources = a}) . _Default . _Coerce instance FromJSON AccountshippingListResponse where parseJSON = withObject "AccountshippingListResponse" (\ o -> AccountshippingListResponse' <$> (o .:? "nextPageToken") <*> (o .:? "kind" .!= "content#accountshippingListResponse") <*> (o .:? "resources" .!= mempty)) instance ToJSON AccountshippingListResponse where toJSON AccountshippingListResponse'{..} = object (catMaybes [("nextPageToken" .=) <$> _alr1NextPageToken, Just ("kind" .= _alr1Kind), ("resources" .=) <$> _alr1Resources]) -- -- /See:/ 'locationIdSet' smart constructor. newtype LocationIdSet = LocationIdSet' { _lisLocationIds :: Maybe [Text] } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'LocationIdSet' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lisLocationIds' locationIdSet :: LocationIdSet locationIdSet = LocationIdSet' { _lisLocationIds = Nothing } -- | A non-empty list of location IDs. They must all be of the same location -- type (e.g., state). lisLocationIds :: Lens' LocationIdSet [Text] lisLocationIds = lens _lisLocationIds (\ s a -> s{_lisLocationIds = a}) . _Default . _Coerce instance FromJSON LocationIdSet where parseJSON = withObject "LocationIdSet" (\ o -> LocationIdSet' <$> (o .:? "locationIds" .!= mempty)) instance ToJSON LocationIdSet where toJSON LocationIdSet'{..} = object (catMaybes [("locationIds" .=) <$> _lisLocationIds]) -- -- /See:/ 'row' smart constructor. newtype Row = Row' { _rCells :: Maybe [Value] } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'Row' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'rCells' row :: Row row = Row' { _rCells = Nothing } -- | The list of cells that constitute the row. Must have the same length as -- columnHeaders for two-dimensional tables, a length of 1 for -- one-dimensional tables. Required. rCells :: Lens' Row [Value] rCells = lens _rCells (\ s a -> s{_rCells = a}) . _Default . _Coerce instance FromJSON Row where parseJSON = withObject "Row" (\ o -> Row' <$> (o .:? "cells" .!= mempty)) instance ToJSON Row where toJSON Row'{..} = object (catMaybes [("cells" .=) <$> _rCells]) -- -- /See:/ 'inventory' smart constructor. data Inventory = Inventory' { _iLoyaltyPoints :: !(Maybe LoyaltyPoints) , _iKind :: !Text , _iQuantity :: !(Maybe (Textual Word32)) , _iInstallment :: !(Maybe Installment) , _iSalePrice :: !(Maybe Price) , _iAvailability :: !(Maybe Text) , _iPickup :: !(Maybe InventoryPickup) , _iSalePriceEffectiveDate :: !(Maybe Text) , _iSellOnGoogleQuantity :: !(Maybe (Textual Word32)) , _iPrice :: !(Maybe Price) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'Inventory' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'iLoyaltyPoints' -- -- * 'iKind' -- -- * 'iQuantity' -- -- * 'iInstallment' -- -- * 'iSalePrice' -- -- * 'iAvailability' -- -- * 'iPickup' -- -- * 'iSalePriceEffectiveDate' -- -- * 'iSellOnGoogleQuantity' -- -- * 'iPrice' inventory :: Inventory inventory = Inventory' { _iLoyaltyPoints = Nothing , _iKind = "content#inventory" , _iQuantity = Nothing , _iInstallment = Nothing , _iSalePrice = Nothing , _iAvailability = Nothing , _iPickup = Nothing , _iSalePriceEffectiveDate = Nothing , _iSellOnGoogleQuantity = Nothing , _iPrice = Nothing } -- | Loyalty points that users receive after purchasing the item. Japan only. iLoyaltyPoints :: Lens' Inventory (Maybe LoyaltyPoints) iLoyaltyPoints = lens _iLoyaltyPoints (\ s a -> s{_iLoyaltyPoints = a}) -- | Identifies what kind of resource this is. Value: the fixed string -- \"content#inventory\". iKind :: Lens' Inventory Text iKind = lens _iKind (\ s a -> s{_iKind = a}) -- | The quantity of the product. Must be equal to or greater than zero. -- Supported only for local products. iQuantity :: Lens' Inventory (Maybe Word32) iQuantity = lens _iQuantity (\ s a -> s{_iQuantity = a}) . mapping _Coerce -- | Number and amount of installments to pay for an item. Brazil only. iInstallment :: Lens' Inventory (Maybe Installment) iInstallment = lens _iInstallment (\ s a -> s{_iInstallment = a}) -- | The sale price of the product. Mandatory if sale_price_effective_date is -- defined. iSalePrice :: Lens' Inventory (Maybe Price) iSalePrice = lens _iSalePrice (\ s a -> s{_iSalePrice = a}) -- | The availability of the product. iAvailability :: Lens' Inventory (Maybe Text) iAvailability = lens _iAvailability (\ s a -> s{_iAvailability = a}) -- | Store pickup information. Only supported for local inventory. Not -- setting pickup means \"don\'t update\" while setting it to the empty -- value ({} in JSON) means \"delete\". Otherwise, pickupMethod and -- pickupSla must be set together, unless pickupMethod is \"not -- supported\". iPickup :: Lens' Inventory (Maybe InventoryPickup) iPickup = lens _iPickup (\ s a -> s{_iPickup = a}) -- | A date range represented by a pair of ISO 8601 dates separated by a -- space, comma, or slash. Both dates might be specified as \'null\' if -- undecided. iSalePriceEffectiveDate :: Lens' Inventory (Maybe Text) iSalePriceEffectiveDate = lens _iSalePriceEffectiveDate (\ s a -> s{_iSalePriceEffectiveDate = a}) -- | The quantity of the product that is reserved for sell-on-google ads. -- Supported only for online products. iSellOnGoogleQuantity :: Lens' Inventory (Maybe Word32) iSellOnGoogleQuantity = lens _iSellOnGoogleQuantity (\ s a -> s{_iSellOnGoogleQuantity = a}) . mapping _Coerce -- | The price of the product. iPrice :: Lens' Inventory (Maybe Price) iPrice = lens _iPrice (\ s a -> s{_iPrice = a}) instance FromJSON Inventory where parseJSON = withObject "Inventory" (\ o -> Inventory' <$> (o .:? "loyaltyPoints") <*> (o .:? "kind" .!= "content#inventory") <*> (o .:? "quantity") <*> (o .:? "installment") <*> (o .:? "salePrice") <*> (o .:? "availability") <*> (o .:? "pickup") <*> (o .:? "salePriceEffectiveDate") <*> (o .:? "sellOnGoogleQuantity") <*> (o .:? "price")) instance ToJSON Inventory where toJSON Inventory'{..} = object (catMaybes [("loyaltyPoints" .=) <$> _iLoyaltyPoints, Just ("kind" .= _iKind), ("quantity" .=) <$> _iQuantity, ("installment" .=) <$> _iInstallment, ("salePrice" .=) <$> _iSalePrice, ("availability" .=) <$> _iAvailability, ("pickup" .=) <$> _iPickup, ("salePriceEffectiveDate" .=) <$> _iSalePriceEffectiveDate, ("sellOnGoogleQuantity" .=) <$> _iSellOnGoogleQuantity, ("price" .=) <$> _iPrice]) -- -- /See:/ 'ordersGetByMerchantOrderIdResponse' smart constructor. data OrdersGetByMerchantOrderIdResponse = OrdersGetByMerchantOrderIdResponse' { _ogbmoirKind :: !Text , _ogbmoirOrder :: !(Maybe Order) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'OrdersGetByMerchantOrderIdResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ogbmoirKind' -- -- * 'ogbmoirOrder' ordersGetByMerchantOrderIdResponse :: OrdersGetByMerchantOrderIdResponse ordersGetByMerchantOrderIdResponse = OrdersGetByMerchantOrderIdResponse' { _ogbmoirKind = "content#ordersGetByMerchantOrderIdResponse" , _ogbmoirOrder = Nothing } -- | Identifies what kind of resource this is. Value: the fixed string -- \"content#ordersGetByMerchantOrderIdResponse\". ogbmoirKind :: Lens' OrdersGetByMerchantOrderIdResponse Text ogbmoirKind = lens _ogbmoirKind (\ s a -> s{_ogbmoirKind = a}) -- | The requested order. ogbmoirOrder :: Lens' OrdersGetByMerchantOrderIdResponse (Maybe Order) ogbmoirOrder = lens _ogbmoirOrder (\ s a -> s{_ogbmoirOrder = a}) instance FromJSON OrdersGetByMerchantOrderIdResponse where parseJSON = withObject "OrdersGetByMerchantOrderIdResponse" (\ o -> OrdersGetByMerchantOrderIdResponse' <$> (o .:? "kind" .!= "content#ordersGetByMerchantOrderIdResponse") <*> (o .:? "order")) instance ToJSON OrdersGetByMerchantOrderIdResponse where toJSON OrdersGetByMerchantOrderIdResponse'{..} = object (catMaybes [Just ("kind" .= _ogbmoirKind), ("order" .=) <$> _ogbmoirOrder]) -- -- /See:/ 'orderPromotionBenefit' smart constructor. data OrderPromotionBenefit = OrderPromotionBenefit' { _opbTaxImpact :: !(Maybe Price) , _opbDiscount :: !(Maybe Price) , _opbOfferIds :: !(Maybe [Text]) , _opbSubType :: !(Maybe Text) , _opbType :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'OrderPromotionBenefit' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'opbTaxImpact' -- -- * 'opbDiscount' -- -- * 'opbOfferIds' -- -- * 'opbSubType' -- -- * 'opbType' orderPromotionBenefit :: OrderPromotionBenefit orderPromotionBenefit = OrderPromotionBenefit' { _opbTaxImpact = Nothing , _opbDiscount = Nothing , _opbOfferIds = Nothing , _opbSubType = Nothing , _opbType = Nothing } -- | The impact on tax when the promotion is applied. opbTaxImpact :: Lens' OrderPromotionBenefit (Maybe Price) opbTaxImpact = lens _opbTaxImpact (\ s a -> s{_opbTaxImpact = a}) -- | The discount in the order price when the promotion is applied. opbDiscount :: Lens' OrderPromotionBenefit (Maybe Price) opbDiscount = lens _opbDiscount (\ s a -> s{_opbDiscount = a}) -- | The OfferId(s) that were purchased in this order and map to this -- specific benefit of the promotion. opbOfferIds :: Lens' OrderPromotionBenefit [Text] opbOfferIds = lens _opbOfferIds (\ s a -> s{_opbOfferIds = a}) . _Default . _Coerce -- | Further describes the benefit of the promotion. Note that we will expand -- on this enumeration as we support new promotion sub-types. opbSubType :: Lens' OrderPromotionBenefit (Maybe Text) opbSubType = lens _opbSubType (\ s a -> s{_opbSubType = a}) -- | Describes whether the promotion applies to products (e.g. 20% off) or to -- shipping (e.g. Free Shipping). opbType :: Lens' OrderPromotionBenefit (Maybe Text) opbType = lens _opbType (\ s a -> s{_opbType = a}) instance FromJSON OrderPromotionBenefit where parseJSON = withObject "OrderPromotionBenefit" (\ o -> OrderPromotionBenefit' <$> (o .:? "taxImpact") <*> (o .:? "discount") <*> (o .:? "offerIds" .!= mempty) <*> (o .:? "subType") <*> (o .:? "type")) instance ToJSON OrderPromotionBenefit where toJSON OrderPromotionBenefit'{..} = object (catMaybes [("taxImpact" .=) <$> _opbTaxImpact, ("discount" .=) <$> _opbDiscount, ("offerIds" .=) <$> _opbOfferIds, ("subType" .=) <$> _opbSubType, ("type" .=) <$> _opbType]) -- -- /See:/ 'ordersCancelRequest' smart constructor. data OrdersCancelRequest = OrdersCancelRequest' { _ocrReason :: !(Maybe Text) , _ocrOperationId :: !(Maybe Text) , _ocrReasonText :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'OrdersCancelRequest' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ocrReason' -- -- * 'ocrOperationId' -- -- * 'ocrReasonText' ordersCancelRequest :: OrdersCancelRequest ordersCancelRequest = OrdersCancelRequest' { _ocrReason = Nothing , _ocrOperationId = Nothing , _ocrReasonText = Nothing } -- | The reason for the cancellation. ocrReason :: Lens' OrdersCancelRequest (Maybe Text) ocrReason = lens _ocrReason (\ s a -> s{_ocrReason = a}) -- | The ID of the operation. Unique across all operations for a given order. ocrOperationId :: Lens' OrdersCancelRequest (Maybe Text) ocrOperationId = lens _ocrOperationId (\ s a -> s{_ocrOperationId = a}) -- | The explanation of the reason. ocrReasonText :: Lens' OrdersCancelRequest (Maybe Text) ocrReasonText = lens _ocrReasonText (\ s a -> s{_ocrReasonText = a}) instance FromJSON OrdersCancelRequest where parseJSON = withObject "OrdersCancelRequest" (\ o -> OrdersCancelRequest' <$> (o .:? "reason") <*> (o .:? "operationId") <*> (o .:? "reasonText")) instance ToJSON OrdersCancelRequest where toJSON OrdersCancelRequest'{..} = object (catMaybes [("reason" .=) <$> _ocrReason, ("operationId" .=) <$> _ocrOperationId, ("reasonText" .=) <$> _ocrReasonText]) -- -- /See:/ 'orderLineItemProductVariantAttribute' smart constructor. data OrderLineItemProductVariantAttribute = OrderLineItemProductVariantAttribute' { _olipvaDimension :: !(Maybe Text) , _olipvaValue :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'OrderLineItemProductVariantAttribute' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'olipvaDimension' -- -- * 'olipvaValue' orderLineItemProductVariantAttribute :: OrderLineItemProductVariantAttribute orderLineItemProductVariantAttribute = OrderLineItemProductVariantAttribute' { _olipvaDimension = Nothing , _olipvaValue = Nothing } -- | The dimension of the variant. olipvaDimension :: Lens' OrderLineItemProductVariantAttribute (Maybe Text) olipvaDimension = lens _olipvaDimension (\ s a -> s{_olipvaDimension = a}) -- | The value for the dimension. olipvaValue :: Lens' OrderLineItemProductVariantAttribute (Maybe Text) olipvaValue = lens _olipvaValue (\ s a -> s{_olipvaValue = a}) instance FromJSON OrderLineItemProductVariantAttribute where parseJSON = withObject "OrderLineItemProductVariantAttribute" (\ o -> OrderLineItemProductVariantAttribute' <$> (o .:? "dimension") <*> (o .:? "value")) instance ToJSON OrderLineItemProductVariantAttribute where toJSON OrderLineItemProductVariantAttribute'{..} = object (catMaybes [("dimension" .=) <$> _olipvaDimension, ("value" .=) <$> _olipvaValue]) -- -- /See:/ 'ordersCustomBatchResponseEntry' smart constructor. data OrdersCustomBatchResponseEntry = OrdersCustomBatchResponseEntry' { _oKind :: !Text , _oExecutionStatus :: !(Maybe Text) , _oErrors :: !(Maybe Errors) , _oOrder :: !(Maybe Order) , _oBatchId :: !(Maybe (Textual Word32)) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'OrdersCustomBatchResponseEntry' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'oKind' -- -- * 'oExecutionStatus' -- -- * 'oErrors' -- -- * 'oOrder' -- -- * 'oBatchId' ordersCustomBatchResponseEntry :: OrdersCustomBatchResponseEntry ordersCustomBatchResponseEntry = OrdersCustomBatchResponseEntry' { _oKind = "content#ordersCustomBatchResponseEntry" , _oExecutionStatus = Nothing , _oErrors = Nothing , _oOrder = Nothing , _oBatchId = Nothing } -- | Identifies what kind of resource this is. Value: the fixed string -- \"content#ordersCustomBatchResponseEntry\". oKind :: Lens' OrdersCustomBatchResponseEntry Text oKind = lens _oKind (\ s a -> s{_oKind = a}) -- | The status of the execution. Only defined if the method is not get or -- getByMerchantOrderId and if the request was successful. oExecutionStatus :: Lens' OrdersCustomBatchResponseEntry (Maybe Text) oExecutionStatus = lens _oExecutionStatus (\ s a -> s{_oExecutionStatus = a}) -- | A list of errors defined if and only if the request failed. oErrors :: Lens' OrdersCustomBatchResponseEntry (Maybe Errors) oErrors = lens _oErrors (\ s a -> s{_oErrors = a}) -- | The retrieved order. Only defined if the method is get and if the -- request was successful. oOrder :: Lens' OrdersCustomBatchResponseEntry (Maybe Order) oOrder = lens _oOrder (\ s a -> s{_oOrder = a}) -- | The ID of the request entry this entry responds to. oBatchId :: Lens' OrdersCustomBatchResponseEntry (Maybe Word32) oBatchId = lens _oBatchId (\ s a -> s{_oBatchId = a}) . mapping _Coerce instance FromJSON OrdersCustomBatchResponseEntry where parseJSON = withObject "OrdersCustomBatchResponseEntry" (\ o -> OrdersCustomBatchResponseEntry' <$> (o .:? "kind" .!= "content#ordersCustomBatchResponseEntry") <*> (o .:? "executionStatus") <*> (o .:? "errors") <*> (o .:? "order") <*> (o .:? "batchId")) instance ToJSON OrdersCustomBatchResponseEntry where toJSON OrdersCustomBatchResponseEntry'{..} = object (catMaybes [Just ("kind" .= _oKind), ("executionStatus" .=) <$> _oExecutionStatus, ("errors" .=) <$> _oErrors, ("order" .=) <$> _oOrder, ("batchId" .=) <$> _oBatchId]) -- | A carrier-calculated shipping rate. -- -- /See:/ 'accountShippingCarrierRate' smart constructor. data AccountShippingCarrierRate = AccountShippingCarrierRate' { _ascrCarrier :: !(Maybe Text) , _ascrSaleCountry :: !(Maybe Text) , _ascrShippingOrigin :: !(Maybe Text) , _ascrCarrierService :: !(Maybe Text) , _ascrModifierPercent :: !(Maybe Text) , _ascrName :: !(Maybe Text) , _ascrModifierFlatRate :: !(Maybe Price) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'AccountShippingCarrierRate' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ascrCarrier' -- -- * 'ascrSaleCountry' -- -- * 'ascrShippingOrigin' -- -- * 'ascrCarrierService' -- -- * 'ascrModifierPercent' -- -- * 'ascrName' -- -- * 'ascrModifierFlatRate' accountShippingCarrierRate :: AccountShippingCarrierRate accountShippingCarrierRate = AccountShippingCarrierRate' { _ascrCarrier = Nothing , _ascrSaleCountry = Nothing , _ascrShippingOrigin = Nothing , _ascrCarrierService = Nothing , _ascrModifierPercent = Nothing , _ascrName = Nothing , _ascrModifierFlatRate = Nothing } -- | The carrier that is responsible for the shipping, such as \"UPS\", -- \"FedEx\", or \"USPS\". ascrCarrier :: Lens' AccountShippingCarrierRate (Maybe Text) ascrCarrier = lens _ascrCarrier (\ s a -> s{_ascrCarrier = a}) -- | The sale country for which this carrier rate is valid, represented as a -- CLDR territory code. ascrSaleCountry :: Lens' AccountShippingCarrierRate (Maybe Text) ascrSaleCountry = lens _ascrSaleCountry (\ s a -> s{_ascrSaleCountry = a}) -- | Shipping origin represented as a postal code. ascrShippingOrigin :: Lens' AccountShippingCarrierRate (Maybe Text) ascrShippingOrigin = lens _ascrShippingOrigin (\ s a -> s{_ascrShippingOrigin = a}) -- | The carrier service, such as \"Ground\" or \"2Day\". ascrCarrierService :: Lens' AccountShippingCarrierRate (Maybe Text) ascrCarrierService = lens _ascrCarrierService (\ s a -> s{_ascrCarrierService = a}) -- | Multiplicative shipping rate modifier in percent. Represented as a -- floating point number without the percentage character. ascrModifierPercent :: Lens' AccountShippingCarrierRate (Maybe Text) ascrModifierPercent = lens _ascrModifierPercent (\ s a -> s{_ascrModifierPercent = a}) -- | The name of the carrier rate. ascrName :: Lens' AccountShippingCarrierRate (Maybe Text) ascrName = lens _ascrName (\ s a -> s{_ascrName = a}) -- | Additive shipping rate modifier. ascrModifierFlatRate :: Lens' AccountShippingCarrierRate (Maybe Price) ascrModifierFlatRate = lens _ascrModifierFlatRate (\ s a -> s{_ascrModifierFlatRate = a}) instance FromJSON AccountShippingCarrierRate where parseJSON = withObject "AccountShippingCarrierRate" (\ o -> AccountShippingCarrierRate' <$> (o .:? "carrier") <*> (o .:? "saleCountry") <*> (o .:? "shippingOrigin") <*> (o .:? "carrierService") <*> (o .:? "modifierPercent") <*> (o .:? "name") <*> (o .:? "modifierFlatRate")) instance ToJSON AccountShippingCarrierRate where toJSON AccountShippingCarrierRate'{..} = object (catMaybes [("carrier" .=) <$> _ascrCarrier, ("saleCountry" .=) <$> _ascrSaleCountry, ("shippingOrigin" .=) <$> _ascrShippingOrigin, ("carrierService" .=) <$> _ascrCarrierService, ("modifierPercent" .=) <$> _ascrModifierPercent, ("name" .=) <$> _ascrName, ("modifierFlatRate" .=) <$> _ascrModifierFlatRate]) -- -- /See:/ 'rateGroup' smart constructor. data RateGroup = RateGroup' { _rgCarrierRates :: !(Maybe [CarrierRate]) , _rgApplicableShippingLabels :: !(Maybe [Text]) , _rgMainTable :: !(Maybe Table) , _rgSingleValue :: !(Maybe Value) , _rgSubtables :: !(Maybe [Table]) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'RateGroup' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'rgCarrierRates' -- -- * 'rgApplicableShippingLabels' -- -- * 'rgMainTable' -- -- * 'rgSingleValue' -- -- * 'rgSubtables' rateGroup :: RateGroup rateGroup = RateGroup' { _rgCarrierRates = Nothing , _rgApplicableShippingLabels = Nothing , _rgMainTable = Nothing , _rgSingleValue = Nothing , _rgSubtables = Nothing } -- | A list of carrier rates that can be referred to by mainTable or -- singleValue. rgCarrierRates :: Lens' RateGroup [CarrierRate] rgCarrierRates = lens _rgCarrierRates (\ s a -> s{_rgCarrierRates = a}) . _Default . _Coerce -- | A list of shipping labels defining the products to which this rate group -- applies to. This is a disjunction: only one of the labels has to match -- for the rate group to apply. May only be empty for the last rate group -- of a service. Required. rgApplicableShippingLabels :: Lens' RateGroup [Text] rgApplicableShippingLabels = lens _rgApplicableShippingLabels (\ s a -> s{_rgApplicableShippingLabels = a}) . _Default . _Coerce -- | A table defining the rate group, when singleValue is not expressive -- enough. Can only be set if singleValue is not set. rgMainTable :: Lens' RateGroup (Maybe Table) rgMainTable = lens _rgMainTable (\ s a -> s{_rgMainTable = a}) -- | The value of the rate group (e.g. flat rate $10). Can only be set if -- mainTable and subtables are not set. rgSingleValue :: Lens' RateGroup (Maybe Value) rgSingleValue = lens _rgSingleValue (\ s a -> s{_rgSingleValue = a}) -- | A list of subtables referred to by mainTable. Can only be set if -- mainTable is set. rgSubtables :: Lens' RateGroup [Table] rgSubtables = lens _rgSubtables (\ s a -> s{_rgSubtables = a}) . _Default . _Coerce instance FromJSON RateGroup where parseJSON = withObject "RateGroup" (\ o -> RateGroup' <$> (o .:? "carrierRates" .!= mempty) <*> (o .:? "applicableShippingLabels" .!= mempty) <*> (o .:? "mainTable") <*> (o .:? "singleValue") <*> (o .:? "subtables" .!= mempty)) instance ToJSON RateGroup where toJSON RateGroup'{..} = object (catMaybes [("carrierRates" .=) <$> _rgCarrierRates, ("applicableShippingLabels" .=) <$> _rgApplicableShippingLabels, ("mainTable" .=) <$> _rgMainTable, ("singleValue" .=) <$> _rgSingleValue, ("subtables" .=) <$> _rgSubtables]) -- -- /See:/ 'orderPromotion' smart constructor. data OrderPromotion = OrderPromotion' { _opEffectiveDates :: !(Maybe Text) , _opGenericRedemptionCode :: !(Maybe Text) , _opRedemptionChannel :: !(Maybe Text) , _opBenefits :: !(Maybe [OrderPromotionBenefit]) , _opLongTitle :: !(Maybe Text) , _opId :: !(Maybe Text) , _opProductApplicability :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'OrderPromotion' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'opEffectiveDates' -- -- * 'opGenericRedemptionCode' -- -- * 'opRedemptionChannel' -- -- * 'opBenefits' -- -- * 'opLongTitle' -- -- * 'opId' -- -- * 'opProductApplicability' orderPromotion :: OrderPromotion orderPromotion = OrderPromotion' { _opEffectiveDates = Nothing , _opGenericRedemptionCode = Nothing , _opRedemptionChannel = Nothing , _opBenefits = Nothing , _opLongTitle = Nothing , _opId = Nothing , _opProductApplicability = Nothing } -- | The date and time frame when the promotion is active and ready for -- validation review. Note that the promotion live time may be delayed for -- a few hours due to the validation review. Start date and end date are -- separated by a forward slash (\/). The start date is specified by the -- format (YYYY-MM-DD), followed by the letter ?T?, the time of the day -- when the sale starts (in Greenwich Mean Time, GMT), followed by an -- expression of the time zone for the sale. The end date is in the same -- format. opEffectiveDates :: Lens' OrderPromotion (Maybe Text) opEffectiveDates = lens _opEffectiveDates (\ s a -> s{_opEffectiveDates = a}) -- | Optional. The text code that corresponds to the promotion when applied -- on the retailer?s website. opGenericRedemptionCode :: Lens' OrderPromotion (Maybe Text) opGenericRedemptionCode = lens _opGenericRedemptionCode (\ s a -> s{_opGenericRedemptionCode = a}) -- | Indicates that the promotion is valid online. opRedemptionChannel :: Lens' OrderPromotion (Maybe Text) opRedemptionChannel = lens _opRedemptionChannel (\ s a -> s{_opRedemptionChannel = a}) opBenefits :: Lens' OrderPromotion [OrderPromotionBenefit] opBenefits = lens _opBenefits (\ s a -> s{_opBenefits = a}) . _Default . _Coerce -- | The full title of the promotion. opLongTitle :: Lens' OrderPromotion (Maybe Text) opLongTitle = lens _opLongTitle (\ s a -> s{_opLongTitle = a}) -- | The unique ID of the promotion. opId :: Lens' OrderPromotion (Maybe Text) opId = lens _opId (\ s a -> s{_opId = a}) -- | Whether the promotion is applicable to all products or only specific -- products. opProductApplicability :: Lens' OrderPromotion (Maybe Text) opProductApplicability = lens _opProductApplicability (\ s a -> s{_opProductApplicability = a}) instance FromJSON OrderPromotion where parseJSON = withObject "OrderPromotion" (\ o -> OrderPromotion' <$> (o .:? "effectiveDates") <*> (o .:? "genericRedemptionCode") <*> (o .:? "redemptionChannel") <*> (o .:? "benefits" .!= mempty) <*> (o .:? "longTitle") <*> (o .:? "id") <*> (o .:? "productApplicability")) instance ToJSON OrderPromotion where toJSON OrderPromotion'{..} = object (catMaybes [("effectiveDates" .=) <$> _opEffectiveDates, ("genericRedemptionCode" .=) <$> _opGenericRedemptionCode, ("redemptionChannel" .=) <$> _opRedemptionChannel, ("benefits" .=) <$> _opBenefits, ("longTitle" .=) <$> _opLongTitle, ("id" .=) <$> _opId, ("productApplicability" .=) <$> _opProductApplicability]) -- -- /See:/ 'price' smart constructor. data Price = Price' { _pValue :: !(Maybe Text) , _pCurrency :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'Price' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pValue' -- -- * 'pCurrency' price :: Price price = Price' { _pValue = Nothing , _pCurrency = Nothing } -- | The price represented as a number. pValue :: Lens' Price (Maybe Text) pValue = lens _pValue (\ s a -> s{_pValue = a}) -- | The currency of the price. pCurrency :: Lens' Price (Maybe Text) pCurrency = lens _pCurrency (\ s a -> s{_pCurrency = a}) instance FromJSON Price where parseJSON = withObject "Price" (\ o -> Price' <$> (o .:? "value") <*> (o .:? "currency")) instance ToJSON Price where toJSON Price'{..} = object (catMaybes [("value" .=) <$> _pValue, ("currency" .=) <$> _pCurrency]) -- -- /See:/ 'orderLineItemShippingDetails' smart constructor. data OrderLineItemShippingDetails = OrderLineItemShippingDetails' { _olisdShipByDate :: !(Maybe Text) , _olisdMethod :: !(Maybe OrderLineItemShippingDetailsMethod) , _olisdDeliverByDate :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'OrderLineItemShippingDetails' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'olisdShipByDate' -- -- * 'olisdMethod' -- -- * 'olisdDeliverByDate' orderLineItemShippingDetails :: OrderLineItemShippingDetails orderLineItemShippingDetails = OrderLineItemShippingDetails' { _olisdShipByDate = Nothing , _olisdMethod = Nothing , _olisdDeliverByDate = Nothing } -- | The ship by date, in ISO 8601 format. olisdShipByDate :: Lens' OrderLineItemShippingDetails (Maybe Text) olisdShipByDate = lens _olisdShipByDate (\ s a -> s{_olisdShipByDate = a}) -- | Details of the shipping method. olisdMethod :: Lens' OrderLineItemShippingDetails (Maybe OrderLineItemShippingDetailsMethod) olisdMethod = lens _olisdMethod (\ s a -> s{_olisdMethod = a}) -- | The delivery by date, in ISO 8601 format. olisdDeliverByDate :: Lens' OrderLineItemShippingDetails (Maybe Text) olisdDeliverByDate = lens _olisdDeliverByDate (\ s a -> s{_olisdDeliverByDate = a}) instance FromJSON OrderLineItemShippingDetails where parseJSON = withObject "OrderLineItemShippingDetails" (\ o -> OrderLineItemShippingDetails' <$> (o .:? "shipByDate") <*> (o .:? "method") <*> (o .:? "deliverByDate")) instance ToJSON OrderLineItemShippingDetails where toJSON OrderLineItemShippingDetails'{..} = object (catMaybes [("shipByDate" .=) <$> _olisdShipByDate, ("method" .=) <$> _olisdMethod, ("deliverByDate" .=) <$> _olisdDeliverByDate]) -- -- /See:/ 'datafeedsCustomBatchResponse' smart constructor. data DatafeedsCustomBatchResponse = DatafeedsCustomBatchResponse' { _datEntries :: !(Maybe [DatafeedsCustomBatchResponseEntry]) , _datKind :: !Text } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'DatafeedsCustomBatchResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'datEntries' -- -- * 'datKind' datafeedsCustomBatchResponse :: DatafeedsCustomBatchResponse datafeedsCustomBatchResponse = DatafeedsCustomBatchResponse' { _datEntries = Nothing , _datKind = "content#datafeedsCustomBatchResponse" } -- | The result of the execution of the batch requests. datEntries :: Lens' DatafeedsCustomBatchResponse [DatafeedsCustomBatchResponseEntry] datEntries = lens _datEntries (\ s a -> s{_datEntries = a}) . _Default . _Coerce -- | Identifies what kind of resource this is. Value: the fixed string -- \"content#datafeedsCustomBatchResponse\". datKind :: Lens' DatafeedsCustomBatchResponse Text datKind = lens _datKind (\ s a -> s{_datKind = a}) instance FromJSON DatafeedsCustomBatchResponse where parseJSON = withObject "DatafeedsCustomBatchResponse" (\ o -> DatafeedsCustomBatchResponse' <$> (o .:? "entries" .!= mempty) <*> (o .:? "kind" .!= "content#datafeedsCustomBatchResponse")) instance ToJSON DatafeedsCustomBatchResponse where toJSON DatafeedsCustomBatchResponse'{..} = object (catMaybes [("entries" .=) <$> _datEntries, Just ("kind" .= _datKind)]) -- -- /See:/ 'orderDeliveryDetails' smart constructor. data OrderDeliveryDetails = OrderDeliveryDetails' { _oddAddress :: !(Maybe OrderAddress) , _oddPhoneNumber :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'OrderDeliveryDetails' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'oddAddress' -- -- * 'oddPhoneNumber' orderDeliveryDetails :: OrderDeliveryDetails orderDeliveryDetails = OrderDeliveryDetails' { _oddAddress = Nothing , _oddPhoneNumber = Nothing } -- | The delivery address oddAddress :: Lens' OrderDeliveryDetails (Maybe OrderAddress) oddAddress = lens _oddAddress (\ s a -> s{_oddAddress = a}) -- | The phone number of the person receiving the delivery. oddPhoneNumber :: Lens' OrderDeliveryDetails (Maybe Text) oddPhoneNumber = lens _oddPhoneNumber (\ s a -> s{_oddPhoneNumber = a}) instance FromJSON OrderDeliveryDetails where parseJSON = withObject "OrderDeliveryDetails" (\ o -> OrderDeliveryDetails' <$> (o .:? "address") <*> (o .:? "phoneNumber")) instance ToJSON OrderDeliveryDetails where toJSON OrderDeliveryDetails'{..} = object (catMaybes [("address" .=) <$> _oddAddress, ("phoneNumber" .=) <$> _oddPhoneNumber]) -- -- /See:/ 'ordersCancelResponse' smart constructor. data OrdersCancelResponse = OrdersCancelResponse' { _ocrKind :: !Text , _ocrExecutionStatus :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'OrdersCancelResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ocrKind' -- -- * 'ocrExecutionStatus' ordersCancelResponse :: OrdersCancelResponse ordersCancelResponse = OrdersCancelResponse' { _ocrKind = "content#ordersCancelResponse" , _ocrExecutionStatus = Nothing } -- | Identifies what kind of resource this is. Value: the fixed string -- \"content#ordersCancelResponse\". ocrKind :: Lens' OrdersCancelResponse Text ocrKind = lens _ocrKind (\ s a -> s{_ocrKind = a}) -- | The status of the execution. ocrExecutionStatus :: Lens' OrdersCancelResponse (Maybe Text) ocrExecutionStatus = lens _ocrExecutionStatus (\ s a -> s{_ocrExecutionStatus = a}) instance FromJSON OrdersCancelResponse where parseJSON = withObject "OrdersCancelResponse" (\ o -> OrdersCancelResponse' <$> (o .:? "kind" .!= "content#ordersCancelResponse") <*> (o .:? "executionStatus")) instance ToJSON OrdersCancelResponse where toJSON OrdersCancelResponse'{..} = object (catMaybes [Just ("kind" .= _ocrKind), ("executionStatus" .=) <$> _ocrExecutionStatus]) -- -- /See:/ 'testOrder' smart constructor. data TestOrder = TestOrder' { _toKind :: !Text , _toLineItems :: !(Maybe [TestOrderLineItem]) , _toShippingOption :: !(Maybe Text) , _toPredefinedDeliveryAddress :: !(Maybe Text) , _toShippingCostTax :: !(Maybe Price) , _toCustomer :: !(Maybe TestOrderCustomer) , _toPaymentMethod :: !(Maybe TestOrderPaymentMethod) , _toPromotions :: !(Maybe [OrderPromotion]) , _toShippingCost :: !(Maybe Price) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'TestOrder' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'toKind' -- -- * 'toLineItems' -- -- * 'toShippingOption' -- -- * 'toPredefinedDeliveryAddress' -- -- * 'toShippingCostTax' -- -- * 'toCustomer' -- -- * 'toPaymentMethod' -- -- * 'toPromotions' -- -- * 'toShippingCost' testOrder :: TestOrder testOrder = TestOrder' { _toKind = "content#testOrder" , _toLineItems = Nothing , _toShippingOption = Nothing , _toPredefinedDeliveryAddress = Nothing , _toShippingCostTax = Nothing , _toCustomer = Nothing , _toPaymentMethod = Nothing , _toPromotions = Nothing , _toShippingCost = Nothing } -- | Identifies what kind of resource this is. Value: the fixed string -- \"content#testOrder\". toKind :: Lens' TestOrder Text toKind = lens _toKind (\ s a -> s{_toKind = a}) -- | Line items that are ordered. At least one line item must be provided. toLineItems :: Lens' TestOrder [TestOrderLineItem] toLineItems = lens _toLineItems (\ s a -> s{_toLineItems = a}) . _Default . _Coerce -- | The requested shipping option. toShippingOption :: Lens' TestOrder (Maybe Text) toShippingOption = lens _toShippingOption (\ s a -> s{_toShippingOption = a}) -- | Identifier of one of the predefined delivery addresses for the delivery. toPredefinedDeliveryAddress :: Lens' TestOrder (Maybe Text) toPredefinedDeliveryAddress = lens _toPredefinedDeliveryAddress (\ s a -> s{_toPredefinedDeliveryAddress = a}) -- | The tax for the total shipping cost. toShippingCostTax :: Lens' TestOrder (Maybe Price) toShippingCostTax = lens _toShippingCostTax (\ s a -> s{_toShippingCostTax = a}) -- | The details of the customer who placed the order. toCustomer :: Lens' TestOrder (Maybe TestOrderCustomer) toCustomer = lens _toCustomer (\ s a -> s{_toCustomer = a}) -- | The details of the payment method. toPaymentMethod :: Lens' TestOrder (Maybe TestOrderPaymentMethod) toPaymentMethod = lens _toPaymentMethod (\ s a -> s{_toPaymentMethod = a}) -- | The details of the merchant provided promotions applied to the order. -- More details about the program are here. toPromotions :: Lens' TestOrder [OrderPromotion] toPromotions = lens _toPromotions (\ s a -> s{_toPromotions = a}) . _Default . _Coerce -- | The total cost of shipping for all items. toShippingCost :: Lens' TestOrder (Maybe Price) toShippingCost = lens _toShippingCost (\ s a -> s{_toShippingCost = a}) instance FromJSON TestOrder where parseJSON = withObject "TestOrder" (\ o -> TestOrder' <$> (o .:? "kind" .!= "content#testOrder") <*> (o .:? "lineItems" .!= mempty) <*> (o .:? "shippingOption") <*> (o .:? "predefinedDeliveryAddress") <*> (o .:? "shippingCostTax") <*> (o .:? "customer") <*> (o .:? "paymentMethod") <*> (o .:? "promotions" .!= mempty) <*> (o .:? "shippingCost")) instance ToJSON TestOrder where toJSON TestOrder'{..} = object (catMaybes [Just ("kind" .= _toKind), ("lineItems" .=) <$> _toLineItems, ("shippingOption" .=) <$> _toShippingOption, ("predefinedDeliveryAddress" .=) <$> _toPredefinedDeliveryAddress, ("shippingCostTax" .=) <$> _toShippingCostTax, ("customer" .=) <$> _toCustomer, ("paymentMethod" .=) <$> _toPaymentMethod, ("promotions" .=) <$> _toPromotions, ("shippingCost" .=) <$> _toShippingCost]) -- | A batch entry encoding a single non-batch datafeedstatuses response. -- -- /See:/ 'datafeedstatusesCustomBatchResponseEntry' smart constructor. data DatafeedstatusesCustomBatchResponseEntry = DatafeedstatusesCustomBatchResponseEntry' { _datErrors :: !(Maybe Errors) , _datDatafeedStatus :: !(Maybe DatafeedStatus) , _datBatchId :: !(Maybe (Textual Word32)) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'DatafeedstatusesCustomBatchResponseEntry' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'datErrors' -- -- * 'datDatafeedStatus' -- -- * 'datBatchId' datafeedstatusesCustomBatchResponseEntry :: DatafeedstatusesCustomBatchResponseEntry datafeedstatusesCustomBatchResponseEntry = DatafeedstatusesCustomBatchResponseEntry' { _datErrors = Nothing , _datDatafeedStatus = Nothing , _datBatchId = Nothing } -- | A list of errors defined if and only if the request failed. datErrors :: Lens' DatafeedstatusesCustomBatchResponseEntry (Maybe Errors) datErrors = lens _datErrors (\ s a -> s{_datErrors = a}) -- | The requested data feed status. Defined if and only if the request was -- successful. datDatafeedStatus :: Lens' DatafeedstatusesCustomBatchResponseEntry (Maybe DatafeedStatus) datDatafeedStatus = lens _datDatafeedStatus (\ s a -> s{_datDatafeedStatus = a}) -- | The ID of the request entry this entry responds to. datBatchId :: Lens' DatafeedstatusesCustomBatchResponseEntry (Maybe Word32) datBatchId = lens _datBatchId (\ s a -> s{_datBatchId = a}) . mapping _Coerce instance FromJSON DatafeedstatusesCustomBatchResponseEntry where parseJSON = withObject "DatafeedstatusesCustomBatchResponseEntry" (\ o -> DatafeedstatusesCustomBatchResponseEntry' <$> (o .:? "errors") <*> (o .:? "datafeedStatus") <*> (o .:? "batchId")) instance ToJSON DatafeedstatusesCustomBatchResponseEntry where toJSON DatafeedstatusesCustomBatchResponseEntry'{..} = object (catMaybes [("errors" .=) <$> _datErrors, ("datafeedStatus" .=) <$> _datDatafeedStatus, ("batchId" .=) <$> _datBatchId]) -- -- /See:/ 'orderRefund' smart constructor. data OrderRefund = OrderRefund' { _oAmount :: !(Maybe Price) , _oActor :: !(Maybe Text) , _oReason :: !(Maybe Text) , _oCreationDate :: !(Maybe Text) , _oReasonText :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'OrderRefund' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'oAmount' -- -- * 'oActor' -- -- * 'oReason' -- -- * 'oCreationDate' -- -- * 'oReasonText' orderRefund :: OrderRefund orderRefund = OrderRefund' { _oAmount = Nothing , _oActor = Nothing , _oReason = Nothing , _oCreationDate = Nothing , _oReasonText = Nothing } -- | The amount that is refunded. oAmount :: Lens' OrderRefund (Maybe Price) oAmount = lens _oAmount (\ s a -> s{_oAmount = a}) -- | The actor that created the refund. oActor :: Lens' OrderRefund (Maybe Text) oActor = lens _oActor (\ s a -> s{_oActor = a}) -- | The reason for the refund. oReason :: Lens' OrderRefund (Maybe Text) oReason = lens _oReason (\ s a -> s{_oReason = a}) -- | Date on which the item has been created, in ISO 8601 format. oCreationDate :: Lens' OrderRefund (Maybe Text) oCreationDate = lens _oCreationDate (\ s a -> s{_oCreationDate = a}) -- | The explanation of the reason. oReasonText :: Lens' OrderRefund (Maybe Text) oReasonText = lens _oReasonText (\ s a -> s{_oReasonText = a}) instance FromJSON OrderRefund where parseJSON = withObject "OrderRefund" (\ o -> OrderRefund' <$> (o .:? "amount") <*> (o .:? "actor") <*> (o .:? "reason") <*> (o .:? "creationDate") <*> (o .:? "reasonText")) instance ToJSON OrderRefund where toJSON OrderRefund'{..} = object (catMaybes [("amount" .=) <$> _oAmount, ("actor" .=) <$> _oActor, ("reason" .=) <$> _oReason, ("creationDate" .=) <$> _oCreationDate, ("reasonText" .=) <$> _oReasonText]) -- -- /See:/ 'testOrderLineItemProduct' smart constructor. data TestOrderLineItemProduct = TestOrderLineItemProduct' { _tolipImageLink :: !(Maybe Text) , _tolipChannel :: !(Maybe Text) , _tolipBrand :: !(Maybe Text) , _tolipTargetCountry :: !(Maybe Text) , _tolipGtin :: !(Maybe Text) , _tolipItemGroupId :: !(Maybe Text) , _tolipOfferId :: !(Maybe Text) , _tolipPrice :: !(Maybe Price) , _tolipVariantAttributes :: !(Maybe [OrderLineItemProductVariantAttribute]) , _tolipTitle :: !(Maybe Text) , _tolipContentLanguage :: !(Maybe Text) , _tolipMpn :: !(Maybe Text) , _tolipCondition :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'TestOrderLineItemProduct' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'tolipImageLink' -- -- * 'tolipChannel' -- -- * 'tolipBrand' -- -- * 'tolipTargetCountry' -- -- * 'tolipGtin' -- -- * 'tolipItemGroupId' -- -- * 'tolipOfferId' -- -- * 'tolipPrice' -- -- * 'tolipVariantAttributes' -- -- * 'tolipTitle' -- -- * 'tolipContentLanguage' -- -- * 'tolipMpn' -- -- * 'tolipCondition' testOrderLineItemProduct :: TestOrderLineItemProduct testOrderLineItemProduct = TestOrderLineItemProduct' { _tolipImageLink = Nothing , _tolipChannel = Nothing , _tolipBrand = Nothing , _tolipTargetCountry = Nothing , _tolipGtin = Nothing , _tolipItemGroupId = Nothing , _tolipOfferId = Nothing , _tolipPrice = Nothing , _tolipVariantAttributes = Nothing , _tolipTitle = Nothing , _tolipContentLanguage = Nothing , _tolipMpn = Nothing , _tolipCondition = Nothing } -- | URL of an image of the item. tolipImageLink :: Lens' TestOrderLineItemProduct (Maybe Text) tolipImageLink = lens _tolipImageLink (\ s a -> s{_tolipImageLink = a}) -- | The item\'s channel. tolipChannel :: Lens' TestOrderLineItemProduct (Maybe Text) tolipChannel = lens _tolipChannel (\ s a -> s{_tolipChannel = a}) -- | Brand of the item. tolipBrand :: Lens' TestOrderLineItemProduct (Maybe Text) tolipBrand = lens _tolipBrand (\ s a -> s{_tolipBrand = a}) -- | The CLDR territory code of the target country of the product. tolipTargetCountry :: Lens' TestOrderLineItemProduct (Maybe Text) tolipTargetCountry = lens _tolipTargetCountry (\ s a -> s{_tolipTargetCountry = a}) -- | Global Trade Item Number (GTIN) of the item. Optional. tolipGtin :: Lens' TestOrderLineItemProduct (Maybe Text) tolipGtin = lens _tolipGtin (\ s a -> s{_tolipGtin = a}) -- | Shared identifier for all variants of the same product. Optional. tolipItemGroupId :: Lens' TestOrderLineItemProduct (Maybe Text) tolipItemGroupId = lens _tolipItemGroupId (\ s a -> s{_tolipItemGroupId = a}) -- | An identifier of the item. tolipOfferId :: Lens' TestOrderLineItemProduct (Maybe Text) tolipOfferId = lens _tolipOfferId (\ s a -> s{_tolipOfferId = a}) -- | The price for the product. tolipPrice :: Lens' TestOrderLineItemProduct (Maybe Price) tolipPrice = lens _tolipPrice (\ s a -> s{_tolipPrice = a}) -- | Variant attributes for the item. Optional. tolipVariantAttributes :: Lens' TestOrderLineItemProduct [OrderLineItemProductVariantAttribute] tolipVariantAttributes = lens _tolipVariantAttributes (\ s a -> s{_tolipVariantAttributes = a}) . _Default . _Coerce -- | The title of the product. tolipTitle :: Lens' TestOrderLineItemProduct (Maybe Text) tolipTitle = lens _tolipTitle (\ s a -> s{_tolipTitle = a}) -- | The two-letter ISO 639-1 language code for the item. tolipContentLanguage :: Lens' TestOrderLineItemProduct (Maybe Text) tolipContentLanguage = lens _tolipContentLanguage (\ s a -> s{_tolipContentLanguage = a}) -- | Manufacturer Part Number (MPN) of the item. Optional. tolipMpn :: Lens' TestOrderLineItemProduct (Maybe Text) tolipMpn = lens _tolipMpn (\ s a -> s{_tolipMpn = a}) -- | Condition or state of the item. tolipCondition :: Lens' TestOrderLineItemProduct (Maybe Text) tolipCondition = lens _tolipCondition (\ s a -> s{_tolipCondition = a}) instance FromJSON TestOrderLineItemProduct where parseJSON = withObject "TestOrderLineItemProduct" (\ o -> TestOrderLineItemProduct' <$> (o .:? "imageLink") <*> (o .:? "channel") <*> (o .:? "brand") <*> (o .:? "targetCountry") <*> (o .:? "gtin") <*> (o .:? "itemGroupId") <*> (o .:? "offerId") <*> (o .:? "price") <*> (o .:? "variantAttributes" .!= mempty) <*> (o .:? "title") <*> (o .:? "contentLanguage") <*> (o .:? "mpn") <*> (o .:? "condition")) instance ToJSON TestOrderLineItemProduct where toJSON TestOrderLineItemProduct'{..} = object (catMaybes [("imageLink" .=) <$> _tolipImageLink, ("channel" .=) <$> _tolipChannel, ("brand" .=) <$> _tolipBrand, ("targetCountry" .=) <$> _tolipTargetCountry, ("gtin" .=) <$> _tolipGtin, ("itemGroupId" .=) <$> _tolipItemGroupId, ("offerId" .=) <$> _tolipOfferId, ("price" .=) <$> _tolipPrice, ("variantAttributes" .=) <$> _tolipVariantAttributes, ("title" .=) <$> _tolipTitle, ("contentLanguage" .=) <$> _tolipContentLanguage, ("mpn" .=) <$> _tolipMpn, ("condition" .=) <$> _tolipCondition]) -- -- /See:/ 'accounttaxCustomBatchResponse' smart constructor. data AccounttaxCustomBatchResponse = AccounttaxCustomBatchResponse' { _a2Entries :: !(Maybe [AccounttaxCustomBatchResponseEntry]) , _a2Kind :: !Text } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'AccounttaxCustomBatchResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'a2Entries' -- -- * 'a2Kind' accounttaxCustomBatchResponse :: AccounttaxCustomBatchResponse accounttaxCustomBatchResponse = AccounttaxCustomBatchResponse' { _a2Entries = Nothing , _a2Kind = "content#accounttaxCustomBatchResponse" } -- | The result of the execution of the batch requests. a2Entries :: Lens' AccounttaxCustomBatchResponse [AccounttaxCustomBatchResponseEntry] a2Entries = lens _a2Entries (\ s a -> s{_a2Entries = a}) . _Default . _Coerce -- | Identifies what kind of resource this is. Value: the fixed string -- \"content#accounttaxCustomBatchResponse\". a2Kind :: Lens' AccounttaxCustomBatchResponse Text a2Kind = lens _a2Kind (\ s a -> s{_a2Kind = a}) instance FromJSON AccounttaxCustomBatchResponse where parseJSON = withObject "AccounttaxCustomBatchResponse" (\ o -> AccounttaxCustomBatchResponse' <$> (o .:? "entries" .!= mempty) <*> (o .:? "kind" .!= "content#accounttaxCustomBatchResponse")) instance ToJSON AccounttaxCustomBatchResponse where toJSON AccounttaxCustomBatchResponse'{..} = object (catMaybes [("entries" .=) <$> _a2Entries, Just ("kind" .= _a2Kind)]) -- | A batch entry encoding a single non-batch inventory request. -- -- /See:/ 'inventoryCustomBatchRequestEntry' smart constructor. data InventoryCustomBatchRequestEntry = InventoryCustomBatchRequestEntry' { _iMerchantId :: !(Maybe (Textual Word64)) , _iStoreCode :: !(Maybe Text) , _iInventory :: !(Maybe Inventory) , _iProductId :: !(Maybe Text) , _iBatchId :: !(Maybe (Textual Word32)) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'InventoryCustomBatchRequestEntry' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'iMerchantId' -- -- * 'iStoreCode' -- -- * 'iInventory' -- -- * 'iProductId' -- -- * 'iBatchId' inventoryCustomBatchRequestEntry :: InventoryCustomBatchRequestEntry inventoryCustomBatchRequestEntry = InventoryCustomBatchRequestEntry' { _iMerchantId = Nothing , _iStoreCode = Nothing , _iInventory = Nothing , _iProductId = Nothing , _iBatchId = Nothing } -- | The ID of the managing account. iMerchantId :: Lens' InventoryCustomBatchRequestEntry (Maybe Word64) iMerchantId = lens _iMerchantId (\ s a -> s{_iMerchantId = a}) . mapping _Coerce -- | The code of the store for which to update price and availability. Use -- online to update price and availability of an online product. iStoreCode :: Lens' InventoryCustomBatchRequestEntry (Maybe Text) iStoreCode = lens _iStoreCode (\ s a -> s{_iStoreCode = a}) -- | Price and availability of the product. iInventory :: Lens' InventoryCustomBatchRequestEntry (Maybe Inventory) iInventory = lens _iInventory (\ s a -> s{_iInventory = a}) -- | The ID of the product for which to update price and availability. iProductId :: Lens' InventoryCustomBatchRequestEntry (Maybe Text) iProductId = lens _iProductId (\ s a -> s{_iProductId = a}) -- | An entry ID, unique within the batch request. iBatchId :: Lens' InventoryCustomBatchRequestEntry (Maybe Word32) iBatchId = lens _iBatchId (\ s a -> s{_iBatchId = a}) . mapping _Coerce instance FromJSON InventoryCustomBatchRequestEntry where parseJSON = withObject "InventoryCustomBatchRequestEntry" (\ o -> InventoryCustomBatchRequestEntry' <$> (o .:? "merchantId") <*> (o .:? "storeCode") <*> (o .:? "inventory") <*> (o .:? "productId") <*> (o .:? "batchId")) instance ToJSON InventoryCustomBatchRequestEntry where toJSON InventoryCustomBatchRequestEntry'{..} = object (catMaybes [("merchantId" .=) <$> _iMerchantId, ("storeCode" .=) <$> _iStoreCode, ("inventory" .=) <$> _iInventory, ("productId" .=) <$> _iProductId, ("batchId" .=) <$> _iBatchId]) -- -- /See:/ 'orderAddress' smart constructor. data OrderAddress = OrderAddress' { _oaRecipientName :: !(Maybe Text) , _oaStreetAddress :: !(Maybe [Text]) , _oaCountry :: !(Maybe Text) , _oaPostalCode :: !(Maybe Text) , _oaLocality :: !(Maybe Text) , _oaIsPostOfficeBox :: !(Maybe Bool) , _oaFullAddress :: !(Maybe [Text]) , _oaRegion :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'OrderAddress' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'oaRecipientName' -- -- * 'oaStreetAddress' -- -- * 'oaCountry' -- -- * 'oaPostalCode' -- -- * 'oaLocality' -- -- * 'oaIsPostOfficeBox' -- -- * 'oaFullAddress' -- -- * 'oaRegion' orderAddress :: OrderAddress orderAddress = OrderAddress' { _oaRecipientName = Nothing , _oaStreetAddress = Nothing , _oaCountry = Nothing , _oaPostalCode = Nothing , _oaLocality = Nothing , _oaIsPostOfficeBox = Nothing , _oaFullAddress = Nothing , _oaRegion = Nothing } -- | Name of the recipient. oaRecipientName :: Lens' OrderAddress (Maybe Text) oaRecipientName = lens _oaRecipientName (\ s a -> s{_oaRecipientName = a}) -- | Street-level part of the address. oaStreetAddress :: Lens' OrderAddress [Text] oaStreetAddress = lens _oaStreetAddress (\ s a -> s{_oaStreetAddress = a}) . _Default . _Coerce -- | CLDR country code (e.g. \"US\"). oaCountry :: Lens' OrderAddress (Maybe Text) oaCountry = lens _oaCountry (\ s a -> s{_oaCountry = a}) -- | Postal Code or ZIP (e.g. \"94043\"). oaPostalCode :: Lens' OrderAddress (Maybe Text) oaPostalCode = lens _oaPostalCode (\ s a -> s{_oaPostalCode = a}) -- | City, town or commune. May also include dependent localities or -- sublocalities (e.g. neighborhoods or suburbs). oaLocality :: Lens' OrderAddress (Maybe Text) oaLocality = lens _oaLocality (\ s a -> s{_oaLocality = a}) -- | Whether the address is a post office box. oaIsPostOfficeBox :: Lens' OrderAddress (Maybe Bool) oaIsPostOfficeBox = lens _oaIsPostOfficeBox (\ s a -> s{_oaIsPostOfficeBox = a}) -- | Strings representing the lines of the printed label for mailing the -- order, for example: John Smith 1600 Amphitheatre Parkway Mountain View, -- CA, 94043 United States oaFullAddress :: Lens' OrderAddress [Text] oaFullAddress = lens _oaFullAddress (\ s a -> s{_oaFullAddress = a}) . _Default . _Coerce -- | Top-level administrative subdivision of the country (e.g. \"CA\"). oaRegion :: Lens' OrderAddress (Maybe Text) oaRegion = lens _oaRegion (\ s a -> s{_oaRegion = a}) instance FromJSON OrderAddress where parseJSON = withObject "OrderAddress" (\ o -> OrderAddress' <$> (o .:? "recipientName") <*> (o .:? "streetAddress" .!= mempty) <*> (o .:? "country") <*> (o .:? "postalCode") <*> (o .:? "locality") <*> (o .:? "isPostOfficeBox") <*> (o .:? "fullAddress" .!= mempty) <*> (o .:? "region")) instance ToJSON OrderAddress where toJSON OrderAddress'{..} = object (catMaybes [("recipientName" .=) <$> _oaRecipientName, ("streetAddress" .=) <$> _oaStreetAddress, ("country" .=) <$> _oaCountry, ("postalCode" .=) <$> _oaPostalCode, ("locality" .=) <$> _oaLocality, ("isPostOfficeBox" .=) <$> _oaIsPostOfficeBox, ("fullAddress" .=) <$> _oaFullAddress, ("region" .=) <$> _oaRegion]) -- -- /See:/ 'productUnitPricingBaseMeasure' smart constructor. data ProductUnitPricingBaseMeasure = ProductUnitPricingBaseMeasure' { _pupbmValue :: !(Maybe (Textual Int64)) , _pupbmUnit :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ProductUnitPricingBaseMeasure' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pupbmValue' -- -- * 'pupbmUnit' productUnitPricingBaseMeasure :: ProductUnitPricingBaseMeasure productUnitPricingBaseMeasure = ProductUnitPricingBaseMeasure' { _pupbmValue = Nothing , _pupbmUnit = Nothing } -- | The denominator of the unit price. pupbmValue :: Lens' ProductUnitPricingBaseMeasure (Maybe Int64) pupbmValue = lens _pupbmValue (\ s a -> s{_pupbmValue = a}) . mapping _Coerce -- | The unit of the denominator. pupbmUnit :: Lens' ProductUnitPricingBaseMeasure (Maybe Text) pupbmUnit = lens _pupbmUnit (\ s a -> s{_pupbmUnit = a}) instance FromJSON ProductUnitPricingBaseMeasure where parseJSON = withObject "ProductUnitPricingBaseMeasure" (\ o -> ProductUnitPricingBaseMeasure' <$> (o .:? "value") <*> (o .:? "unit")) instance ToJSON ProductUnitPricingBaseMeasure where toJSON ProductUnitPricingBaseMeasure'{..} = object (catMaybes [("value" .=) <$> _pupbmValue, ("unit" .=) <$> _pupbmUnit]) -- -- /See:/ 'accountShippingCondition' smart constructor. data AccountShippingCondition = AccountShippingCondition' { _ascWeightMax :: !(Maybe Weight) , _ascDeliveryPostalCode :: !(Maybe Text) , _ascDeliveryLocationGroup :: !(Maybe Text) , _ascPriceMax :: !(Maybe Price) , _ascShippingLabel :: !(Maybe Text) , _ascDeliveryLocationId :: !(Maybe (Textual Int64)) , _ascDeliveryPostalCodeRange :: !(Maybe AccountShippingPostalCodeRange) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'AccountShippingCondition' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ascWeightMax' -- -- * 'ascDeliveryPostalCode' -- -- * 'ascDeliveryLocationGroup' -- -- * 'ascPriceMax' -- -- * 'ascShippingLabel' -- -- * 'ascDeliveryLocationId' -- -- * 'ascDeliveryPostalCodeRange' accountShippingCondition :: AccountShippingCondition accountShippingCondition = AccountShippingCondition' { _ascWeightMax = Nothing , _ascDeliveryPostalCode = Nothing , _ascDeliveryLocationGroup = Nothing , _ascPriceMax = Nothing , _ascShippingLabel = Nothing , _ascDeliveryLocationId = Nothing , _ascDeliveryPostalCodeRange = Nothing } -- | Maximum shipping weight. Forms an interval between the maximum of -- smaller weight (exclusive) and this weight (inclusive). ascWeightMax :: Lens' AccountShippingCondition (Maybe Weight) ascWeightMax = lens _ascWeightMax (\ s a -> s{_ascWeightMax = a}) -- | Delivery location in terms of a postal code. ascDeliveryPostalCode :: Lens' AccountShippingCondition (Maybe Text) ascDeliveryPostalCode = lens _ascDeliveryPostalCode (\ s a -> s{_ascDeliveryPostalCode = a}) -- | Delivery location in terms of a location group name. A location group -- with this name must be specified among location groups. ascDeliveryLocationGroup :: Lens' AccountShippingCondition (Maybe Text) ascDeliveryLocationGroup = lens _ascDeliveryLocationGroup (\ s a -> s{_ascDeliveryLocationGroup = a}) -- | Maximum shipping price. Forms an interval between the maximum of smaller -- prices (exclusive) and this price (inclusive). ascPriceMax :: Lens' AccountShippingCondition (Maybe Price) ascPriceMax = lens _ascPriceMax (\ s a -> s{_ascPriceMax = a}) -- | Shipping label of the product. The products with the label are matched. ascShippingLabel :: Lens' AccountShippingCondition (Maybe Text) ascShippingLabel = lens _ascShippingLabel (\ s a -> s{_ascShippingLabel = a}) -- | Delivery location in terms of a location ID. Can be used to represent -- administrative areas, smaller country subdivisions, or cities. ascDeliveryLocationId :: Lens' AccountShippingCondition (Maybe Int64) ascDeliveryLocationId = lens _ascDeliveryLocationId (\ s a -> s{_ascDeliveryLocationId = a}) . mapping _Coerce -- | Delivery location in terms of a postal code range. ascDeliveryPostalCodeRange :: Lens' AccountShippingCondition (Maybe AccountShippingPostalCodeRange) ascDeliveryPostalCodeRange = lens _ascDeliveryPostalCodeRange (\ s a -> s{_ascDeliveryPostalCodeRange = a}) instance FromJSON AccountShippingCondition where parseJSON = withObject "AccountShippingCondition" (\ o -> AccountShippingCondition' <$> (o .:? "weightMax") <*> (o .:? "deliveryPostalCode") <*> (o .:? "deliveryLocationGroup") <*> (o .:? "priceMax") <*> (o .:? "shippingLabel") <*> (o .:? "deliveryLocationId") <*> (o .:? "deliveryPostalCodeRange")) instance ToJSON AccountShippingCondition where toJSON AccountShippingCondition'{..} = object (catMaybes [("weightMax" .=) <$> _ascWeightMax, ("deliveryPostalCode" .=) <$> _ascDeliveryPostalCode, ("deliveryLocationGroup" .=) <$> _ascDeliveryLocationGroup, ("priceMax" .=) <$> _ascPriceMax, ("shippingLabel" .=) <$> _ascShippingLabel, ("deliveryLocationId" .=) <$> _ascDeliveryLocationId, ("deliveryPostalCodeRange" .=) <$> _ascDeliveryPostalCodeRange]) -- -- /See:/ 'datafeedsListResponse' smart constructor. data DatafeedsListResponse = DatafeedsListResponse' { _dlrNextPageToken :: !(Maybe Text) , _dlrKind :: !Text , _dlrResources :: !(Maybe [Datafeed]) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'DatafeedsListResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dlrNextPageToken' -- -- * 'dlrKind' -- -- * 'dlrResources' datafeedsListResponse :: DatafeedsListResponse datafeedsListResponse = DatafeedsListResponse' { _dlrNextPageToken = Nothing , _dlrKind = "content#datafeedsListResponse" , _dlrResources = Nothing } -- | The token for the retrieval of the next page of datafeeds. dlrNextPageToken :: Lens' DatafeedsListResponse (Maybe Text) dlrNextPageToken = lens _dlrNextPageToken (\ s a -> s{_dlrNextPageToken = a}) -- | Identifies what kind of resource this is. Value: the fixed string -- \"content#datafeedsListResponse\". dlrKind :: Lens' DatafeedsListResponse Text dlrKind = lens _dlrKind (\ s a -> s{_dlrKind = a}) dlrResources :: Lens' DatafeedsListResponse [Datafeed] dlrResources = lens _dlrResources (\ s a -> s{_dlrResources = a}) . _Default . _Coerce instance FromJSON DatafeedsListResponse where parseJSON = withObject "DatafeedsListResponse" (\ o -> DatafeedsListResponse' <$> (o .:? "nextPageToken") <*> (o .:? "kind" .!= "content#datafeedsListResponse") <*> (o .:? "resources" .!= mempty)) instance ToJSON DatafeedsListResponse where toJSON DatafeedsListResponse'{..} = object (catMaybes [("nextPageToken" .=) <$> _dlrNextPageToken, Just ("kind" .= _dlrKind), ("resources" .=) <$> _dlrResources]) -- | A batch entry encoding a single non-batch products response. -- -- /See:/ 'productsCustomBatchResponseEntry' smart constructor. data ProductsCustomBatchResponseEntry = ProductsCustomBatchResponseEntry' { _proKind :: !Text , _proProduct :: !(Maybe Product) , _proErrors :: !(Maybe Errors) , _proBatchId :: !(Maybe (Textual Word32)) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ProductsCustomBatchResponseEntry' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'proKind' -- -- * 'proProduct' -- -- * 'proErrors' -- -- * 'proBatchId' productsCustomBatchResponseEntry :: ProductsCustomBatchResponseEntry productsCustomBatchResponseEntry = ProductsCustomBatchResponseEntry' { _proKind = "content#productsCustomBatchResponseEntry" , _proProduct = Nothing , _proErrors = Nothing , _proBatchId = Nothing } -- | Identifies what kind of resource this is. Value: the fixed string -- \"content#productsCustomBatchResponseEntry\". proKind :: Lens' ProductsCustomBatchResponseEntry Text proKind = lens _proKind (\ s a -> s{_proKind = a}) -- | The inserted product. Only defined if the method is insert and if the -- request was successful. proProduct :: Lens' ProductsCustomBatchResponseEntry (Maybe Product) proProduct = lens _proProduct (\ s a -> s{_proProduct = a}) -- | A list of errors defined if and only if the request failed. proErrors :: Lens' ProductsCustomBatchResponseEntry (Maybe Errors) proErrors = lens _proErrors (\ s a -> s{_proErrors = a}) -- | The ID of the request entry this entry responds to. proBatchId :: Lens' ProductsCustomBatchResponseEntry (Maybe Word32) proBatchId = lens _proBatchId (\ s a -> s{_proBatchId = a}) . mapping _Coerce instance FromJSON ProductsCustomBatchResponseEntry where parseJSON = withObject "ProductsCustomBatchResponseEntry" (\ o -> ProductsCustomBatchResponseEntry' <$> (o .:? "kind" .!= "content#productsCustomBatchResponseEntry") <*> (o .:? "product") <*> (o .:? "errors") <*> (o .:? "batchId")) instance ToJSON ProductsCustomBatchResponseEntry where toJSON ProductsCustomBatchResponseEntry'{..} = object (catMaybes [Just ("kind" .= _proKind), ("product" .=) <$> _proProduct, ("errors" .=) <$> _proErrors, ("batchId" .=) <$> _proBatchId]) -- -- /See:/ 'orderPaymentMethod' smart constructor. data OrderPaymentMethod = OrderPaymentMethod' { _opmExpirationMonth :: !(Maybe (Textual Int32)) , _opmExpirationYear :: !(Maybe (Textual Int32)) , _opmPhoneNumber :: !(Maybe Text) , _opmBillingAddress :: !(Maybe OrderAddress) , _opmLastFourDigits :: !(Maybe Text) , _opmType :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'OrderPaymentMethod' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'opmExpirationMonth' -- -- * 'opmExpirationYear' -- -- * 'opmPhoneNumber' -- -- * 'opmBillingAddress' -- -- * 'opmLastFourDigits' -- -- * 'opmType' orderPaymentMethod :: OrderPaymentMethod orderPaymentMethod = OrderPaymentMethod' { _opmExpirationMonth = Nothing , _opmExpirationYear = Nothing , _opmPhoneNumber = Nothing , _opmBillingAddress = Nothing , _opmLastFourDigits = Nothing , _opmType = Nothing } -- | The card expiration month (January = 1, February = 2 etc.). opmExpirationMonth :: Lens' OrderPaymentMethod (Maybe Int32) opmExpirationMonth = lens _opmExpirationMonth (\ s a -> s{_opmExpirationMonth = a}) . mapping _Coerce -- | The card expiration year (4-digit, e.g. 2015). opmExpirationYear :: Lens' OrderPaymentMethod (Maybe Int32) opmExpirationYear = lens _opmExpirationYear (\ s a -> s{_opmExpirationYear = a}) . mapping _Coerce -- | The billing phone number. opmPhoneNumber :: Lens' OrderPaymentMethod (Maybe Text) opmPhoneNumber = lens _opmPhoneNumber (\ s a -> s{_opmPhoneNumber = a}) -- | The billing address. opmBillingAddress :: Lens' OrderPaymentMethod (Maybe OrderAddress) opmBillingAddress = lens _opmBillingAddress (\ s a -> s{_opmBillingAddress = a}) -- | The last four digits of the card number. opmLastFourDigits :: Lens' OrderPaymentMethod (Maybe Text) opmLastFourDigits = lens _opmLastFourDigits (\ s a -> s{_opmLastFourDigits = a}) -- | The type of instrument (VISA, Mastercard, etc). opmType :: Lens' OrderPaymentMethod (Maybe Text) opmType = lens _opmType (\ s a -> s{_opmType = a}) instance FromJSON OrderPaymentMethod where parseJSON = withObject "OrderPaymentMethod" (\ o -> OrderPaymentMethod' <$> (o .:? "expirationMonth") <*> (o .:? "expirationYear") <*> (o .:? "phoneNumber") <*> (o .:? "billingAddress") <*> (o .:? "lastFourDigits") <*> (o .:? "type")) instance ToJSON OrderPaymentMethod where toJSON OrderPaymentMethod'{..} = object (catMaybes [("expirationMonth" .=) <$> _opmExpirationMonth, ("expirationYear" .=) <$> _opmExpirationYear, ("phoneNumber" .=) <$> _opmPhoneNumber, ("billingAddress" .=) <$> _opmBillingAddress, ("lastFourDigits" .=) <$> _opmLastFourDigits, ("type" .=) <$> _opmType]) -- | Product data. -- -- /See:/ 'product' smart constructor. data Product = Product' { _ppDisplayAdsLink :: !(Maybe Text) , _ppCustomLabel1 :: !(Maybe Text) , _ppShippingWidth :: !(Maybe ProductShippingDimension) , _ppCustomGroups :: !(Maybe [ProductCustomGroup]) , _ppImageLink :: !(Maybe Text) , _ppDisplayAdsValue :: !(Maybe (Textual Double)) , _ppLoyaltyPoints :: !(Maybe LoyaltyPoints) , _ppAdditionalImageLinks :: !(Maybe [Text]) , _ppValidatedDestinations :: !(Maybe [Text]) , _ppColor :: !(Maybe Text) , _ppCustomLabel0 :: !(Maybe Text) , _ppKind :: !Text , _ppMultipack :: !(Maybe (Textual Int64)) , _ppPattern :: !(Maybe Text) , _ppLink :: !(Maybe Text) , _ppSizeSystem :: !(Maybe Text) , _ppUnitPricingBaseMeasure :: !(Maybe ProductUnitPricingBaseMeasure) , _ppTaxes :: !(Maybe [ProductTax]) , _ppMaterial :: !(Maybe Text) , _ppInstallment :: !(Maybe Installment) , _ppChannel :: !(Maybe Text) , _ppProductType :: !(Maybe Text) , _ppIdentifierExists :: !(Maybe Bool) , _ppOnlineOnly :: !(Maybe Bool) , _ppBrand :: !(Maybe Text) , _ppUnitPricingMeasure :: !(Maybe ProductUnitPricingMeasure) , _ppSalePrice :: !(Maybe Price) , _ppShippingLength :: !(Maybe ProductShippingDimension) , _ppCustomLabel3 :: !(Maybe Text) , _ppWarnings :: !(Maybe [Error']) , _ppAdditionalProductTypes :: !(Maybe [Text]) , _ppAvailability :: !(Maybe Text) , _ppTargetCountry :: !(Maybe Text) , _ppShippingLabel :: !(Maybe Text) , _ppCustomAttributes :: !(Maybe [ProductCustomAttribute]) , _ppGtin :: !(Maybe Text) , _ppAgeGroup :: !(Maybe Text) , _ppDisplayAdsTitle :: !(Maybe Text) , _ppGender :: !(Maybe Text) , _ppDestinations :: !(Maybe [ProductDestination]) , _ppExpirationDate :: !(Maybe Text) , _ppItemGroupId :: !(Maybe Text) , _ppAdwordsGrouping :: !(Maybe Text) , _ppSalePriceEffectiveDate :: !(Maybe Text) , _ppCustomLabel2 :: !(Maybe Text) , _ppGoogleProductCategory :: !(Maybe Text) , _ppShipping :: !(Maybe [ProductShipping]) , _ppAdwordsRedirect :: !(Maybe Text) , _ppShippingWeight :: !(Maybe ProductShippingWeight) , _ppSellOnGoogleQuantity :: !(Maybe (Textual Int64)) , _ppShippingHeight :: !(Maybe ProductShippingDimension) , _ppAvailabilityDate :: !(Maybe Text) , _ppOfferId :: !(Maybe Text) , _ppId :: !(Maybe Text) , _ppAdwordsLabels :: !(Maybe [Text]) , _ppPrice :: !(Maybe Price) , _ppPromotionIds :: !(Maybe [Text]) , _ppSizeType :: !(Maybe Text) , _ppMobileLink :: !(Maybe Text) , _ppTitle :: !(Maybe Text) , _ppAdult :: !(Maybe Bool) , _ppContentLanguage :: !(Maybe Text) , _ppAspects :: !(Maybe [ProductAspect]) , _ppEnergyEfficiencyClass :: !(Maybe Text) , _ppDisplayAdsSimilarIds :: !(Maybe [Text]) , _ppMpn :: !(Maybe Text) , _ppCondition :: !(Maybe Text) , _ppSizes :: !(Maybe [Text]) , _ppIsBundle :: !(Maybe Bool) , _ppDescription :: !(Maybe Text) , _ppCustomLabel4 :: !(Maybe Text) , _ppDisplayAdsId :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'Product' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ppDisplayAdsLink' -- -- * 'ppCustomLabel1' -- -- * 'ppShippingWidth' -- -- * 'ppCustomGroups' -- -- * 'ppImageLink' -- -- * 'ppDisplayAdsValue' -- -- * 'ppLoyaltyPoints' -- -- * 'ppAdditionalImageLinks' -- -- * 'ppValidatedDestinations' -- -- * 'ppColor' -- -- * 'ppCustomLabel0' -- -- * 'ppKind' -- -- * 'ppMultipack' -- -- * 'ppPattern' -- -- * 'ppLink' -- -- * 'ppSizeSystem' -- -- * 'ppUnitPricingBaseMeasure' -- -- * 'ppTaxes' -- -- * 'ppMaterial' -- -- * 'ppInstallment' -- -- * 'ppChannel' -- -- * 'ppProductType' -- -- * 'ppIdentifierExists' -- -- * 'ppOnlineOnly' -- -- * 'ppBrand' -- -- * 'ppUnitPricingMeasure' -- -- * 'ppSalePrice' -- -- * 'ppShippingLength' -- -- * 'ppCustomLabel3' -- -- * 'ppWarnings' -- -- * 'ppAdditionalProductTypes' -- -- * 'ppAvailability' -- -- * 'ppTargetCountry' -- -- * 'ppShippingLabel' -- -- * 'ppCustomAttributes' -- -- * 'ppGtin' -- -- * 'ppAgeGroup' -- -- * 'ppDisplayAdsTitle' -- -- * 'ppGender' -- -- * 'ppDestinations' -- -- * 'ppExpirationDate' -- -- * 'ppItemGroupId' -- -- * 'ppAdwordsGrouping' -- -- * 'ppSalePriceEffectiveDate' -- -- * 'ppCustomLabel2' -- -- * 'ppGoogleProductCategory' -- -- * 'ppShipping' -- -- * 'ppAdwordsRedirect' -- -- * 'ppShippingWeight' -- -- * 'ppSellOnGoogleQuantity' -- -- * 'ppShippingHeight' -- -- * 'ppAvailabilityDate' -- -- * 'ppOfferId' -- -- * 'ppId' -- -- * 'ppAdwordsLabels' -- -- * 'ppPrice' -- -- * 'ppPromotionIds' -- -- * 'ppSizeType' -- -- * 'ppMobileLink' -- -- * 'ppTitle' -- -- * 'ppAdult' -- -- * 'ppContentLanguage' -- -- * 'ppAspects' -- -- * 'ppEnergyEfficiencyClass' -- -- * 'ppDisplayAdsSimilarIds' -- -- * 'ppMpn' -- -- * 'ppCondition' -- -- * 'ppSizes' -- -- * 'ppIsBundle' -- -- * 'ppDescription' -- -- * 'ppCustomLabel4' -- -- * 'ppDisplayAdsId' product :: Product product = Product' { _ppDisplayAdsLink = Nothing , _ppCustomLabel1 = Nothing , _ppShippingWidth = Nothing , _ppCustomGroups = Nothing , _ppImageLink = Nothing , _ppDisplayAdsValue = Nothing , _ppLoyaltyPoints = Nothing , _ppAdditionalImageLinks = Nothing , _ppValidatedDestinations = Nothing , _ppColor = Nothing , _ppCustomLabel0 = Nothing , _ppKind = "content#product" , _ppMultipack = Nothing , _ppPattern = Nothing , _ppLink = Nothing , _ppSizeSystem = Nothing , _ppUnitPricingBaseMeasure = Nothing , _ppTaxes = Nothing , _ppMaterial = Nothing , _ppInstallment = Nothing , _ppChannel = Nothing , _ppProductType = Nothing , _ppIdentifierExists = Nothing , _ppOnlineOnly = Nothing , _ppBrand = Nothing , _ppUnitPricingMeasure = Nothing , _ppSalePrice = Nothing , _ppShippingLength = Nothing , _ppCustomLabel3 = Nothing , _ppWarnings = Nothing , _ppAdditionalProductTypes = Nothing , _ppAvailability = Nothing , _ppTargetCountry = Nothing , _ppShippingLabel = Nothing , _ppCustomAttributes = Nothing , _ppGtin = Nothing , _ppAgeGroup = Nothing , _ppDisplayAdsTitle = Nothing , _ppGender = Nothing , _ppDestinations = Nothing , _ppExpirationDate = Nothing , _ppItemGroupId = Nothing , _ppAdwordsGrouping = Nothing , _ppSalePriceEffectiveDate = Nothing , _ppCustomLabel2 = Nothing , _ppGoogleProductCategory = Nothing , _ppShipping = Nothing , _ppAdwordsRedirect = Nothing , _ppShippingWeight = Nothing , _ppSellOnGoogleQuantity = Nothing , _ppShippingHeight = Nothing , _ppAvailabilityDate = Nothing , _ppOfferId = Nothing , _ppId = Nothing , _ppAdwordsLabels = Nothing , _ppPrice = Nothing , _ppPromotionIds = Nothing , _ppSizeType = Nothing , _ppMobileLink = Nothing , _ppTitle = Nothing , _ppAdult = Nothing , _ppContentLanguage = Nothing , _ppAspects = Nothing , _ppEnergyEfficiencyClass = Nothing , _ppDisplayAdsSimilarIds = Nothing , _ppMpn = Nothing , _ppCondition = Nothing , _ppSizes = Nothing , _ppIsBundle = Nothing , _ppDescription = Nothing , _ppCustomLabel4 = Nothing , _ppDisplayAdsId = Nothing } -- | URL directly to your item\'s landing page for dynamic remarketing -- campaigns. ppDisplayAdsLink :: Lens' Product (Maybe Text) ppDisplayAdsLink = lens _ppDisplayAdsLink (\ s a -> s{_ppDisplayAdsLink = a}) -- | Custom label 1 for custom grouping of items in a Shopping campaign. ppCustomLabel1 :: Lens' Product (Maybe Text) ppCustomLabel1 = lens _ppCustomLabel1 (\ s a -> s{_ppCustomLabel1 = a}) -- | Width of the item for shipping. ppShippingWidth :: Lens' Product (Maybe ProductShippingDimension) ppShippingWidth = lens _ppShippingWidth (\ s a -> s{_ppShippingWidth = a}) -- | A list of custom (merchant-provided) custom attribute groups. ppCustomGroups :: Lens' Product [ProductCustomGroup] ppCustomGroups = lens _ppCustomGroups (\ s a -> s{_ppCustomGroups = a}) . _Default . _Coerce -- | URL of an image of the item. ppImageLink :: Lens' Product (Maybe Text) ppImageLink = lens _ppImageLink (\ s a -> s{_ppImageLink = a}) -- | Offer margin for dynamic remarketing campaigns. ppDisplayAdsValue :: Lens' Product (Maybe Double) ppDisplayAdsValue = lens _ppDisplayAdsValue (\ s a -> s{_ppDisplayAdsValue = a}) . mapping _Coerce -- | Loyalty points that users receive after purchasing the item. Japan only. ppLoyaltyPoints :: Lens' Product (Maybe LoyaltyPoints) ppLoyaltyPoints = lens _ppLoyaltyPoints (\ s a -> s{_ppLoyaltyPoints = a}) -- | Additional URLs of images of the item. ppAdditionalImageLinks :: Lens' Product [Text] ppAdditionalImageLinks = lens _ppAdditionalImageLinks (\ s a -> s{_ppAdditionalImageLinks = a}) . _Default . _Coerce -- | The read-only list of intended destinations which passed validation. ppValidatedDestinations :: Lens' Product [Text] ppValidatedDestinations = lens _ppValidatedDestinations (\ s a -> s{_ppValidatedDestinations = a}) . _Default . _Coerce -- | Color of the item. ppColor :: Lens' Product (Maybe Text) ppColor = lens _ppColor (\ s a -> s{_ppColor = a}) -- | Custom label 0 for custom grouping of items in a Shopping campaign. ppCustomLabel0 :: Lens' Product (Maybe Text) ppCustomLabel0 = lens _ppCustomLabel0 (\ s a -> s{_ppCustomLabel0 = a}) -- | Identifies what kind of resource this is. Value: the fixed string -- \"content#product\". ppKind :: Lens' Product Text ppKind = lens _ppKind (\ s a -> s{_ppKind = a}) -- | The number of identical products in a merchant-defined multipack. ppMultipack :: Lens' Product (Maybe Int64) ppMultipack = lens _ppMultipack (\ s a -> s{_ppMultipack = a}) . mapping _Coerce -- | The item\'s pattern (e.g. polka dots). ppPattern :: Lens' Product (Maybe Text) ppPattern = lens _ppPattern (\ s a -> s{_ppPattern = a}) -- | URL directly linking to your item\'s page on your website. ppLink :: Lens' Product (Maybe Text) ppLink = lens _ppLink (\ s a -> s{_ppLink = a}) -- | System in which the size is specified. Recommended for apparel items. ppSizeSystem :: Lens' Product (Maybe Text) ppSizeSystem = lens _ppSizeSystem (\ s a -> s{_ppSizeSystem = a}) -- | The preference of the denominator of the unit price. ppUnitPricingBaseMeasure :: Lens' Product (Maybe ProductUnitPricingBaseMeasure) ppUnitPricingBaseMeasure = lens _ppUnitPricingBaseMeasure (\ s a -> s{_ppUnitPricingBaseMeasure = a}) -- | Tax information. ppTaxes :: Lens' Product [ProductTax] ppTaxes = lens _ppTaxes (\ s a -> s{_ppTaxes = a}) . _Default . _Coerce -- | The material of which the item is made. ppMaterial :: Lens' Product (Maybe Text) ppMaterial = lens _ppMaterial (\ s a -> s{_ppMaterial = a}) -- | Number and amount of installments to pay for an item. Brazil only. ppInstallment :: Lens' Product (Maybe Installment) ppInstallment = lens _ppInstallment (\ s a -> s{_ppInstallment = a}) -- | The item\'s channel (online or local). ppChannel :: Lens' Product (Maybe Text) ppChannel = lens _ppChannel (\ s a -> s{_ppChannel = a}) -- | Your category of the item (formatted as in products feed specification). ppProductType :: Lens' Product (Maybe Text) ppProductType = lens _ppProductType (\ s a -> s{_ppProductType = a}) -- | False when the item does not have unique product identifiers appropriate -- to its category, such as GTIN, MPN, and brand. Required according to the -- Unique Product Identifier Rules for all target countries except for -- Canada. ppIdentifierExists :: Lens' Product (Maybe Bool) ppIdentifierExists = lens _ppIdentifierExists (\ s a -> s{_ppIdentifierExists = a}) -- | Whether an item is available for purchase only online. ppOnlineOnly :: Lens' Product (Maybe Bool) ppOnlineOnly = lens _ppOnlineOnly (\ s a -> s{_ppOnlineOnly = a}) -- | Brand of the item. ppBrand :: Lens' Product (Maybe Text) ppBrand = lens _ppBrand (\ s a -> s{_ppBrand = a}) -- | The measure and dimension of an item. ppUnitPricingMeasure :: Lens' Product (Maybe ProductUnitPricingMeasure) ppUnitPricingMeasure = lens _ppUnitPricingMeasure (\ s a -> s{_ppUnitPricingMeasure = a}) -- | Advertised sale price of the item. ppSalePrice :: Lens' Product (Maybe Price) ppSalePrice = lens _ppSalePrice (\ s a -> s{_ppSalePrice = a}) -- | Length of the item for shipping. ppShippingLength :: Lens' Product (Maybe ProductShippingDimension) ppShippingLength = lens _ppShippingLength (\ s a -> s{_ppShippingLength = a}) -- | Custom label 3 for custom grouping of items in a Shopping campaign. ppCustomLabel3 :: Lens' Product (Maybe Text) ppCustomLabel3 = lens _ppCustomLabel3 (\ s a -> s{_ppCustomLabel3 = a}) -- | Read-only warnings. ppWarnings :: Lens' Product [Error'] ppWarnings = lens _ppWarnings (\ s a -> s{_ppWarnings = a}) . _Default . _Coerce -- | Additional categories of the item (formatted as in products feed -- specification). ppAdditionalProductTypes :: Lens' Product [Text] ppAdditionalProductTypes = lens _ppAdditionalProductTypes (\ s a -> s{_ppAdditionalProductTypes = a}) . _Default . _Coerce -- | Availability status of the item. ppAvailability :: Lens' Product (Maybe Text) ppAvailability = lens _ppAvailability (\ s a -> s{_ppAvailability = a}) -- | The CLDR territory code for the item. ppTargetCountry :: Lens' Product (Maybe Text) ppTargetCountry = lens _ppTargetCountry (\ s a -> s{_ppTargetCountry = a}) -- | The shipping label of the product, used to group product in -- account-level shipping rules. ppShippingLabel :: Lens' Product (Maybe Text) ppShippingLabel = lens _ppShippingLabel (\ s a -> s{_ppShippingLabel = a}) -- | A list of custom (merchant-provided) attributes. It can also be used for -- submitting any attribute of the feed specification in its generic form -- (e.g., { \"name\": \"size type\", \"type\": \"text\", \"value\": -- \"regular\" }). This is useful for submitting attributes not explicitly -- exposed by the API. ppCustomAttributes :: Lens' Product [ProductCustomAttribute] ppCustomAttributes = lens _ppCustomAttributes (\ s a -> s{_ppCustomAttributes = a}) . _Default . _Coerce -- | Global Trade Item Number (GTIN) of the item. ppGtin :: Lens' Product (Maybe Text) ppGtin = lens _ppGtin (\ s a -> s{_ppGtin = a}) -- | Target age group of the item. ppAgeGroup :: Lens' Product (Maybe Text) ppAgeGroup = lens _ppAgeGroup (\ s a -> s{_ppAgeGroup = a}) -- | Title of an item for dynamic remarketing campaigns. ppDisplayAdsTitle :: Lens' Product (Maybe Text) ppDisplayAdsTitle = lens _ppDisplayAdsTitle (\ s a -> s{_ppDisplayAdsTitle = a}) -- | Target gender of the item. ppGender :: Lens' Product (Maybe Text) ppGender = lens _ppGender (\ s a -> s{_ppGender = a}) -- | Specifies the intended destinations for the product. ppDestinations :: Lens' Product [ProductDestination] ppDestinations = lens _ppDestinations (\ s a -> s{_ppDestinations = a}) . _Default . _Coerce -- | Date on which the item should expire, as specified upon insertion, in -- ISO 8601 format. The actual expiration date in Google Shopping is -- exposed in productstatuses as googleExpirationDate and might be earlier -- if expirationDate is too far in the future. ppExpirationDate :: Lens' Product (Maybe Text) ppExpirationDate = lens _ppExpirationDate (\ s a -> s{_ppExpirationDate = a}) -- | Shared identifier for all variants of the same product. ppItemGroupId :: Lens' Product (Maybe Text) ppItemGroupId = lens _ppItemGroupId (\ s a -> s{_ppItemGroupId = a}) -- | Used to group items in an arbitrary way. Only for CPA%, discouraged -- otherwise. ppAdwordsGrouping :: Lens' Product (Maybe Text) ppAdwordsGrouping = lens _ppAdwordsGrouping (\ s a -> s{_ppAdwordsGrouping = a}) -- | Date range during which the item is on sale (see products feed -- specification). ppSalePriceEffectiveDate :: Lens' Product (Maybe Text) ppSalePriceEffectiveDate = lens _ppSalePriceEffectiveDate (\ s a -> s{_ppSalePriceEffectiveDate = a}) -- | Custom label 2 for custom grouping of items in a Shopping campaign. ppCustomLabel2 :: Lens' Product (Maybe Text) ppCustomLabel2 = lens _ppCustomLabel2 (\ s a -> s{_ppCustomLabel2 = a}) -- | Google\'s category of the item (see Google product taxonomy). ppGoogleProductCategory :: Lens' Product (Maybe Text) ppGoogleProductCategory = lens _ppGoogleProductCategory (\ s a -> s{_ppGoogleProductCategory = a}) -- | Shipping rules. ppShipping :: Lens' Product [ProductShipping] ppShipping = lens _ppShipping (\ s a -> s{_ppShipping = a}) . _Default . _Coerce -- | Allows advertisers to override the item URL when the product is shown -- within the context of Product Ads. ppAdwordsRedirect :: Lens' Product (Maybe Text) ppAdwordsRedirect = lens _ppAdwordsRedirect (\ s a -> s{_ppAdwordsRedirect = a}) -- | Weight of the item for shipping. ppShippingWeight :: Lens' Product (Maybe ProductShippingWeight) ppShippingWeight = lens _ppShippingWeight (\ s a -> s{_ppShippingWeight = a}) -- | The quantity of the product that is reserved for sell-on-google ads. ppSellOnGoogleQuantity :: Lens' Product (Maybe Int64) ppSellOnGoogleQuantity = lens _ppSellOnGoogleQuantity (\ s a -> s{_ppSellOnGoogleQuantity = a}) . mapping _Coerce -- | Height of the item for shipping. ppShippingHeight :: Lens' Product (Maybe ProductShippingDimension) ppShippingHeight = lens _ppShippingHeight (\ s a -> s{_ppShippingHeight = a}) -- | The day a pre-ordered product becomes available for delivery, in ISO -- 8601 format. ppAvailabilityDate :: Lens' Product (Maybe Text) ppAvailabilityDate = lens _ppAvailabilityDate (\ s a -> s{_ppAvailabilityDate = a}) -- | An identifier of the item. Leading and trailing whitespaces are stripped -- and multiple whitespaces are replaced by a single whitespace upon -- submission. Only valid unicode characters are accepted. See the products -- feed specification for details. ppOfferId :: Lens' Product (Maybe Text) ppOfferId = lens _ppOfferId (\ s a -> s{_ppOfferId = a}) -- | The REST id of the product. ppId :: Lens' Product (Maybe Text) ppId = lens _ppId (\ s a -> s{_ppId = a}) -- | Similar to adwords_grouping, but only works on CPC. ppAdwordsLabels :: Lens' Product [Text] ppAdwordsLabels = lens _ppAdwordsLabels (\ s a -> s{_ppAdwordsLabels = a}) . _Default . _Coerce -- | Price of the item. ppPrice :: Lens' Product (Maybe Price) ppPrice = lens _ppPrice (\ s a -> s{_ppPrice = a}) -- | The unique ID of a promotion. ppPromotionIds :: Lens' Product [Text] ppPromotionIds = lens _ppPromotionIds (\ s a -> s{_ppPromotionIds = a}) . _Default . _Coerce -- | The cut of the item. Recommended for apparel items. ppSizeType :: Lens' Product (Maybe Text) ppSizeType = lens _ppSizeType (\ s a -> s{_ppSizeType = a}) -- | Link to a mobile-optimized version of the landing page. ppMobileLink :: Lens' Product (Maybe Text) ppMobileLink = lens _ppMobileLink (\ s a -> s{_ppMobileLink = a}) -- | Title of the item. ppTitle :: Lens' Product (Maybe Text) ppTitle = lens _ppTitle (\ s a -> s{_ppTitle = a}) -- | Set to true if the item is targeted towards adults. ppAdult :: Lens' Product (Maybe Bool) ppAdult = lens _ppAdult (\ s a -> s{_ppAdult = a}) -- | The two-letter ISO 639-1 language code for the item. ppContentLanguage :: Lens' Product (Maybe Text) ppContentLanguage = lens _ppContentLanguage (\ s a -> s{_ppContentLanguage = a}) -- | Specifies the intended aspects for the product. ppAspects :: Lens' Product [ProductAspect] ppAspects = lens _ppAspects (\ s a -> s{_ppAspects = a}) . _Default . _Coerce -- | The energy efficiency class as defined in EU directive 2010\/30\/EU. ppEnergyEfficiencyClass :: Lens' Product (Maybe Text) ppEnergyEfficiencyClass = lens _ppEnergyEfficiencyClass (\ s a -> s{_ppEnergyEfficiencyClass = a}) -- | Advertiser-specified recommendations. ppDisplayAdsSimilarIds :: Lens' Product [Text] ppDisplayAdsSimilarIds = lens _ppDisplayAdsSimilarIds (\ s a -> s{_ppDisplayAdsSimilarIds = a}) . _Default . _Coerce -- | Manufacturer Part Number (MPN) of the item. ppMpn :: Lens' Product (Maybe Text) ppMpn = lens _ppMpn (\ s a -> s{_ppMpn = a}) -- | Condition or state of the item. ppCondition :: Lens' Product (Maybe Text) ppCondition = lens _ppCondition (\ s a -> s{_ppCondition = a}) -- | Size of the item. ppSizes :: Lens' Product [Text] ppSizes = lens _ppSizes (\ s a -> s{_ppSizes = a}) . _Default . _Coerce -- | Whether the item is a merchant-defined bundle. A bundle is a custom -- grouping of different products sold by a merchant for a single price. ppIsBundle :: Lens' Product (Maybe Bool) ppIsBundle = lens _ppIsBundle (\ s a -> s{_ppIsBundle = a}) -- | Description of the item. ppDescription :: Lens' Product (Maybe Text) ppDescription = lens _ppDescription (\ s a -> s{_ppDescription = a}) -- | Custom label 4 for custom grouping of items in a Shopping campaign. ppCustomLabel4 :: Lens' Product (Maybe Text) ppCustomLabel4 = lens _ppCustomLabel4 (\ s a -> s{_ppCustomLabel4 = a}) -- | An identifier for an item for dynamic remarketing campaigns. ppDisplayAdsId :: Lens' Product (Maybe Text) ppDisplayAdsId = lens _ppDisplayAdsId (\ s a -> s{_ppDisplayAdsId = a}) instance FromJSON Product where parseJSON = withObject "Product" (\ o -> Product' <$> (o .:? "displayAdsLink") <*> (o .:? "customLabel1") <*> (o .:? "shippingWidth") <*> (o .:? "customGroups" .!= mempty) <*> (o .:? "imageLink") <*> (o .:? "displayAdsValue") <*> (o .:? "loyaltyPoints") <*> (o .:? "additionalImageLinks" .!= mempty) <*> (o .:? "validatedDestinations" .!= mempty) <*> (o .:? "color") <*> (o .:? "customLabel0") <*> (o .:? "kind" .!= "content#product") <*> (o .:? "multipack") <*> (o .:? "pattern") <*> (o .:? "link") <*> (o .:? "sizeSystem") <*> (o .:? "unitPricingBaseMeasure") <*> (o .:? "taxes" .!= mempty) <*> (o .:? "material") <*> (o .:? "installment") <*> (o .:? "channel") <*> (o .:? "productType") <*> (o .:? "identifierExists") <*> (o .:? "onlineOnly") <*> (o .:? "brand") <*> (o .:? "unitPricingMeasure") <*> (o .:? "salePrice") <*> (o .:? "shippingLength") <*> (o .:? "customLabel3") <*> (o .:? "warnings" .!= mempty) <*> (o .:? "additionalProductTypes" .!= mempty) <*> (o .:? "availability") <*> (o .:? "targetCountry") <*> (o .:? "shippingLabel") <*> (o .:? "customAttributes" .!= mempty) <*> (o .:? "gtin") <*> (o .:? "ageGroup") <*> (o .:? "displayAdsTitle") <*> (o .:? "gender") <*> (o .:? "destinations" .!= mempty) <*> (o .:? "expirationDate") <*> (o .:? "itemGroupId") <*> (o .:? "adwordsGrouping") <*> (o .:? "salePriceEffectiveDate") <*> (o .:? "customLabel2") <*> (o .:? "googleProductCategory") <*> (o .:? "shipping" .!= mempty) <*> (o .:? "adwordsRedirect") <*> (o .:? "shippingWeight") <*> (o .:? "sellOnGoogleQuantity") <*> (o .:? "shippingHeight") <*> (o .:? "availabilityDate") <*> (o .:? "offerId") <*> (o .:? "id") <*> (o .:? "adwordsLabels" .!= mempty) <*> (o .:? "price") <*> (o .:? "promotionIds" .!= mempty) <*> (o .:? "sizeType") <*> (o .:? "mobileLink") <*> (o .:? "title") <*> (o .:? "adult") <*> (o .:? "contentLanguage") <*> (o .:? "aspects" .!= mempty) <*> (o .:? "energyEfficiencyClass") <*> (o .:? "displayAdsSimilarIds" .!= mempty) <*> (o .:? "mpn") <*> (o .:? "condition") <*> (o .:? "sizes" .!= mempty) <*> (o .:? "isBundle") <*> (o .:? "description") <*> (o .:? "customLabel4") <*> (o .:? "displayAdsId")) instance ToJSON Product where toJSON Product'{..} = object (catMaybes [("displayAdsLink" .=) <$> _ppDisplayAdsLink, ("customLabel1" .=) <$> _ppCustomLabel1, ("shippingWidth" .=) <$> _ppShippingWidth, ("customGroups" .=) <$> _ppCustomGroups, ("imageLink" .=) <$> _ppImageLink, ("displayAdsValue" .=) <$> _ppDisplayAdsValue, ("loyaltyPoints" .=) <$> _ppLoyaltyPoints, ("additionalImageLinks" .=) <$> _ppAdditionalImageLinks, ("validatedDestinations" .=) <$> _ppValidatedDestinations, ("color" .=) <$> _ppColor, ("customLabel0" .=) <$> _ppCustomLabel0, Just ("kind" .= _ppKind), ("multipack" .=) <$> _ppMultipack, ("pattern" .=) <$> _ppPattern, ("link" .=) <$> _ppLink, ("sizeSystem" .=) <$> _ppSizeSystem, ("unitPricingBaseMeasure" .=) <$> _ppUnitPricingBaseMeasure, ("taxes" .=) <$> _ppTaxes, ("material" .=) <$> _ppMaterial, ("installment" .=) <$> _ppInstallment, ("channel" .=) <$> _ppChannel, ("productType" .=) <$> _ppProductType, ("identifierExists" .=) <$> _ppIdentifierExists, ("onlineOnly" .=) <$> _ppOnlineOnly, ("brand" .=) <$> _ppBrand, ("unitPricingMeasure" .=) <$> _ppUnitPricingMeasure, ("salePrice" .=) <$> _ppSalePrice, ("shippingLength" .=) <$> _ppShippingLength, ("customLabel3" .=) <$> _ppCustomLabel3, ("warnings" .=) <$> _ppWarnings, ("additionalProductTypes" .=) <$> _ppAdditionalProductTypes, ("availability" .=) <$> _ppAvailability, ("targetCountry" .=) <$> _ppTargetCountry, ("shippingLabel" .=) <$> _ppShippingLabel, ("customAttributes" .=) <$> _ppCustomAttributes, ("gtin" .=) <$> _ppGtin, ("ageGroup" .=) <$> _ppAgeGroup, ("displayAdsTitle" .=) <$> _ppDisplayAdsTitle, ("gender" .=) <$> _ppGender, ("destinations" .=) <$> _ppDestinations, ("expirationDate" .=) <$> _ppExpirationDate, ("itemGroupId" .=) <$> _ppItemGroupId, ("adwordsGrouping" .=) <$> _ppAdwordsGrouping, ("salePriceEffectiveDate" .=) <$> _ppSalePriceEffectiveDate, ("customLabel2" .=) <$> _ppCustomLabel2, ("googleProductCategory" .=) <$> _ppGoogleProductCategory, ("shipping" .=) <$> _ppShipping, ("adwordsRedirect" .=) <$> _ppAdwordsRedirect, ("shippingWeight" .=) <$> _ppShippingWeight, ("sellOnGoogleQuantity" .=) <$> _ppSellOnGoogleQuantity, ("shippingHeight" .=) <$> _ppShippingHeight, ("availabilityDate" .=) <$> _ppAvailabilityDate, ("offerId" .=) <$> _ppOfferId, ("id" .=) <$> _ppId, ("adwordsLabels" .=) <$> _ppAdwordsLabels, ("price" .=) <$> _ppPrice, ("promotionIds" .=) <$> _ppPromotionIds, ("sizeType" .=) <$> _ppSizeType, ("mobileLink" .=) <$> _ppMobileLink, ("title" .=) <$> _ppTitle, ("adult" .=) <$> _ppAdult, ("contentLanguage" .=) <$> _ppContentLanguage, ("aspects" .=) <$> _ppAspects, ("energyEfficiencyClass" .=) <$> _ppEnergyEfficiencyClass, ("displayAdsSimilarIds" .=) <$> _ppDisplayAdsSimilarIds, ("mpn" .=) <$> _ppMpn, ("condition" .=) <$> _ppCondition, ("sizes" .=) <$> _ppSizes, ("isBundle" .=) <$> _ppIsBundle, ("description" .=) <$> _ppDescription, ("customLabel4" .=) <$> _ppCustomLabel4, ("displayAdsId" .=) <$> _ppDisplayAdsId]) -- | A list of errors returned by a failed batch entry. -- -- /See:/ 'errors' smart constructor. data Errors = Errors' { _errCode :: !(Maybe (Textual Word32)) , _errMessage :: !(Maybe Text) , _errErrors :: !(Maybe [Error']) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'Errors' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'errCode' -- -- * 'errMessage' -- -- * 'errErrors' errors :: Errors errors = Errors' { _errCode = Nothing , _errMessage = Nothing , _errErrors = Nothing } -- | The HTTP status of the first error in errors. errCode :: Lens' Errors (Maybe Word32) errCode = lens _errCode (\ s a -> s{_errCode = a}) . mapping _Coerce -- | The message of the first error in errors. errMessage :: Lens' Errors (Maybe Text) errMessage = lens _errMessage (\ s a -> s{_errMessage = a}) -- | A list of errors. errErrors :: Lens' Errors [Error'] errErrors = lens _errErrors (\ s a -> s{_errErrors = a}) . _Default . _Coerce instance FromJSON Errors where parseJSON = withObject "Errors" (\ o -> Errors' <$> (o .:? "code") <*> (o .:? "message") <*> (o .:? "errors" .!= mempty)) instance ToJSON Errors where toJSON Errors'{..} = object (catMaybes [("code" .=) <$> _errCode, ("message" .=) <$> _errMessage, ("errors" .=) <$> _errErrors]) -- | A batch entry encoding a single non-batch accountstatuses response. -- -- /See:/ 'accountstatusesCustomBatchResponseEntry' smart constructor. data AccountstatusesCustomBatchResponseEntry = AccountstatusesCustomBatchResponseEntry' { _acccAccountStatus :: !(Maybe AccountStatus) , _acccErrors :: !(Maybe Errors) , _acccBatchId :: !(Maybe (Textual Word32)) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'AccountstatusesCustomBatchResponseEntry' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'acccAccountStatus' -- -- * 'acccErrors' -- -- * 'acccBatchId' accountstatusesCustomBatchResponseEntry :: AccountstatusesCustomBatchResponseEntry accountstatusesCustomBatchResponseEntry = AccountstatusesCustomBatchResponseEntry' { _acccAccountStatus = Nothing , _acccErrors = Nothing , _acccBatchId = Nothing } -- | The requested account status. Defined if and only if the request was -- successful. acccAccountStatus :: Lens' AccountstatusesCustomBatchResponseEntry (Maybe AccountStatus) acccAccountStatus = lens _acccAccountStatus (\ s a -> s{_acccAccountStatus = a}) -- | A list of errors defined if and only if the request failed. acccErrors :: Lens' AccountstatusesCustomBatchResponseEntry (Maybe Errors) acccErrors = lens _acccErrors (\ s a -> s{_acccErrors = a}) -- | The ID of the request entry this entry responds to. acccBatchId :: Lens' AccountstatusesCustomBatchResponseEntry (Maybe Word32) acccBatchId = lens _acccBatchId (\ s a -> s{_acccBatchId = a}) . mapping _Coerce instance FromJSON AccountstatusesCustomBatchResponseEntry where parseJSON = withObject "AccountstatusesCustomBatchResponseEntry" (\ o -> AccountstatusesCustomBatchResponseEntry' <$> (o .:? "accountStatus") <*> (o .:? "errors") <*> (o .:? "batchId")) instance ToJSON AccountstatusesCustomBatchResponseEntry where toJSON AccountstatusesCustomBatchResponseEntry'{..} = object (catMaybes [("accountStatus" .=) <$> _acccAccountStatus, ("errors" .=) <$> _acccErrors, ("batchId" .=) <$> _acccBatchId]) -- -- /See:/ 'inventorySetResponse' smart constructor. newtype InventorySetResponse = InventorySetResponse' { _isrKind :: Text } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'InventorySetResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'isrKind' inventorySetResponse :: InventorySetResponse inventorySetResponse = InventorySetResponse' { _isrKind = "content#inventorySetResponse" } -- | Identifies what kind of resource this is. Value: the fixed string -- \"content#inventorySetResponse\". isrKind :: Lens' InventorySetResponse Text isrKind = lens _isrKind (\ s a -> s{_isrKind = a}) instance FromJSON InventorySetResponse where parseJSON = withObject "InventorySetResponse" (\ o -> InventorySetResponse' <$> (o .:? "kind" .!= "content#inventorySetResponse")) instance ToJSON InventorySetResponse where toJSON InventorySetResponse'{..} = object (catMaybes [Just ("kind" .= _isrKind)]) -- -- /See:/ 'ordersCancelLineItemResponse' smart constructor. data OrdersCancelLineItemResponse = OrdersCancelLineItemResponse' { _oclirKind :: !Text , _oclirExecutionStatus :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'OrdersCancelLineItemResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'oclirKind' -- -- * 'oclirExecutionStatus' ordersCancelLineItemResponse :: OrdersCancelLineItemResponse ordersCancelLineItemResponse = OrdersCancelLineItemResponse' { _oclirKind = "content#ordersCancelLineItemResponse" , _oclirExecutionStatus = Nothing } -- | Identifies what kind of resource this is. Value: the fixed string -- \"content#ordersCancelLineItemResponse\". oclirKind :: Lens' OrdersCancelLineItemResponse Text oclirKind = lens _oclirKind (\ s a -> s{_oclirKind = a}) -- | The status of the execution. oclirExecutionStatus :: Lens' OrdersCancelLineItemResponse (Maybe Text) oclirExecutionStatus = lens _oclirExecutionStatus (\ s a -> s{_oclirExecutionStatus = a}) instance FromJSON OrdersCancelLineItemResponse where parseJSON = withObject "OrdersCancelLineItemResponse" (\ o -> OrdersCancelLineItemResponse' <$> (o .:? "kind" .!= "content#ordersCancelLineItemResponse") <*> (o .:? "executionStatus")) instance ToJSON OrdersCancelLineItemResponse where toJSON OrdersCancelLineItemResponse'{..} = object (catMaybes [Just ("kind" .= _oclirKind), ("executionStatus" .=) <$> _oclirExecutionStatus]) -- -- /See:/ 'testOrderLineItem' smart constructor. data TestOrderLineItem = TestOrderLineItem' { _toliQuantityOrdered :: !(Maybe (Textual Word32)) , _toliReturnInfo :: !(Maybe OrderLineItemReturnInfo) , _toliShippingDetails :: !(Maybe OrderLineItemShippingDetails) , _toliProduct :: !(Maybe TestOrderLineItemProduct) , _toliUnitTax :: !(Maybe Price) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'TestOrderLineItem' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'toliQuantityOrdered' -- -- * 'toliReturnInfo' -- -- * 'toliShippingDetails' -- -- * 'toliProduct' -- -- * 'toliUnitTax' testOrderLineItem :: TestOrderLineItem testOrderLineItem = TestOrderLineItem' { _toliQuantityOrdered = Nothing , _toliReturnInfo = Nothing , _toliShippingDetails = Nothing , _toliProduct = Nothing , _toliUnitTax = Nothing } -- | Number of items ordered. toliQuantityOrdered :: Lens' TestOrderLineItem (Maybe Word32) toliQuantityOrdered = lens _toliQuantityOrdered (\ s a -> s{_toliQuantityOrdered = a}) . mapping _Coerce -- | Details of the return policy for the line item. toliReturnInfo :: Lens' TestOrderLineItem (Maybe OrderLineItemReturnInfo) toliReturnInfo = lens _toliReturnInfo (\ s a -> s{_toliReturnInfo = a}) -- | Details of the requested shipping for the line item. toliShippingDetails :: Lens' TestOrderLineItem (Maybe OrderLineItemShippingDetails) toliShippingDetails = lens _toliShippingDetails (\ s a -> s{_toliShippingDetails = a}) -- | Product data from the time of the order placement. toliProduct :: Lens' TestOrderLineItem (Maybe TestOrderLineItemProduct) toliProduct = lens _toliProduct (\ s a -> s{_toliProduct = a}) -- | Unit tax for the line item. toliUnitTax :: Lens' TestOrderLineItem (Maybe Price) toliUnitTax = lens _toliUnitTax (\ s a -> s{_toliUnitTax = a}) instance FromJSON TestOrderLineItem where parseJSON = withObject "TestOrderLineItem" (\ o -> TestOrderLineItem' <$> (o .:? "quantityOrdered") <*> (o .:? "returnInfo") <*> (o .:? "shippingDetails") <*> (o .:? "product") <*> (o .:? "unitTax")) instance ToJSON TestOrderLineItem where toJSON TestOrderLineItem'{..} = object (catMaybes [("quantityOrdered" .=) <$> _toliQuantityOrdered, ("returnInfo" .=) <$> _toliReturnInfo, ("shippingDetails" .=) <$> _toliShippingDetails, ("product" .=) <$> _toliProduct, ("unitTax" .=) <$> _toliUnitTax]) -- | A batch entry encoding a single non-batch productstatuses request. -- -- /See:/ 'productstatusesCustomBatchRequestEntry' smart constructor. data ProductstatusesCustomBatchRequestEntry = ProductstatusesCustomBatchRequestEntry' { _pcbrecMerchantId :: !(Maybe (Textual Word64)) , _pcbrecMethod :: !(Maybe Text) , _pcbrecProductId :: !(Maybe Text) , _pcbrecBatchId :: !(Maybe (Textual Word32)) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ProductstatusesCustomBatchRequestEntry' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pcbrecMerchantId' -- -- * 'pcbrecMethod' -- -- * 'pcbrecProductId' -- -- * 'pcbrecBatchId' productstatusesCustomBatchRequestEntry :: ProductstatusesCustomBatchRequestEntry productstatusesCustomBatchRequestEntry = ProductstatusesCustomBatchRequestEntry' { _pcbrecMerchantId = Nothing , _pcbrecMethod = Nothing , _pcbrecProductId = Nothing , _pcbrecBatchId = Nothing } -- | The ID of the managing account. pcbrecMerchantId :: Lens' ProductstatusesCustomBatchRequestEntry (Maybe Word64) pcbrecMerchantId = lens _pcbrecMerchantId (\ s a -> s{_pcbrecMerchantId = a}) . mapping _Coerce pcbrecMethod :: Lens' ProductstatusesCustomBatchRequestEntry (Maybe Text) pcbrecMethod = lens _pcbrecMethod (\ s a -> s{_pcbrecMethod = a}) -- | The ID of the product whose status to get. pcbrecProductId :: Lens' ProductstatusesCustomBatchRequestEntry (Maybe Text) pcbrecProductId = lens _pcbrecProductId (\ s a -> s{_pcbrecProductId = a}) -- | An entry ID, unique within the batch request. pcbrecBatchId :: Lens' ProductstatusesCustomBatchRequestEntry (Maybe Word32) pcbrecBatchId = lens _pcbrecBatchId (\ s a -> s{_pcbrecBatchId = a}) . mapping _Coerce instance FromJSON ProductstatusesCustomBatchRequestEntry where parseJSON = withObject "ProductstatusesCustomBatchRequestEntry" (\ o -> ProductstatusesCustomBatchRequestEntry' <$> (o .:? "merchantId") <*> (o .:? "method") <*> (o .:? "productId") <*> (o .:? "batchId")) instance ToJSON ProductstatusesCustomBatchRequestEntry where toJSON ProductstatusesCustomBatchRequestEntry'{..} = object (catMaybes [("merchantId" .=) <$> _pcbrecMerchantId, ("method" .=) <$> _pcbrecMethod, ("productId" .=) <$> _pcbrecProductId, ("batchId" .=) <$> _pcbrecBatchId]) -- -- /See:/ 'shippingSettingsCustomBatchResponse' smart constructor. data ShippingSettingsCustomBatchResponse = ShippingSettingsCustomBatchResponse' { _shiEntries :: !(Maybe [ShippingSettingsCustomBatchResponseEntry]) , _shiKind :: !Text } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ShippingSettingsCustomBatchResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'shiEntries' -- -- * 'shiKind' shippingSettingsCustomBatchResponse :: ShippingSettingsCustomBatchResponse shippingSettingsCustomBatchResponse = ShippingSettingsCustomBatchResponse' { _shiEntries = Nothing , _shiKind = "content#shippingsettingsCustomBatchResponse" } -- | The result of the execution of the batch requests. shiEntries :: Lens' ShippingSettingsCustomBatchResponse [ShippingSettingsCustomBatchResponseEntry] shiEntries = lens _shiEntries (\ s a -> s{_shiEntries = a}) . _Default . _Coerce -- | Identifies what kind of resource this is. Value: the fixed string -- \"content#shippingsettingsCustomBatchResponse\". shiKind :: Lens' ShippingSettingsCustomBatchResponse Text shiKind = lens _shiKind (\ s a -> s{_shiKind = a}) instance FromJSON ShippingSettingsCustomBatchResponse where parseJSON = withObject "ShippingSettingsCustomBatchResponse" (\ o -> ShippingSettingsCustomBatchResponse' <$> (o .:? "entries" .!= mempty) <*> (o .:? "kind" .!= "content#shippingsettingsCustomBatchResponse")) instance ToJSON ShippingSettingsCustomBatchResponse where toJSON ShippingSettingsCustomBatchResponse'{..} = object (catMaybes [("entries" .=) <$> _shiEntries, Just ("kind" .= _shiKind)]) -- | A batch entry encoding a single non-batch accountshipping response. -- -- /See:/ 'accountshippingCustomBatchResponseEntry' smart constructor. data AccountshippingCustomBatchResponseEntry = AccountshippingCustomBatchResponseEntry' { _acbre1Kind :: !Text , _acbre1Errors :: !(Maybe Errors) , _acbre1AccountShipping :: !(Maybe AccountShipping) , _acbre1BatchId :: !(Maybe (Textual Word32)) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'AccountshippingCustomBatchResponseEntry' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'acbre1Kind' -- -- * 'acbre1Errors' -- -- * 'acbre1AccountShipping' -- -- * 'acbre1BatchId' accountshippingCustomBatchResponseEntry :: AccountshippingCustomBatchResponseEntry accountshippingCustomBatchResponseEntry = AccountshippingCustomBatchResponseEntry' { _acbre1Kind = "content#accountshippingCustomBatchResponseEntry" , _acbre1Errors = Nothing , _acbre1AccountShipping = Nothing , _acbre1BatchId = Nothing } -- | Identifies what kind of resource this is. Value: the fixed string -- \"content#accountshippingCustomBatchResponseEntry\". acbre1Kind :: Lens' AccountshippingCustomBatchResponseEntry Text acbre1Kind = lens _acbre1Kind (\ s a -> s{_acbre1Kind = a}) -- | A list of errors defined if and only if the request failed. acbre1Errors :: Lens' AccountshippingCustomBatchResponseEntry (Maybe Errors) acbre1Errors = lens _acbre1Errors (\ s a -> s{_acbre1Errors = a}) -- | The retrieved or updated account shipping settings. acbre1AccountShipping :: Lens' AccountshippingCustomBatchResponseEntry (Maybe AccountShipping) acbre1AccountShipping = lens _acbre1AccountShipping (\ s a -> s{_acbre1AccountShipping = a}) -- | The ID of the request entry this entry responds to. acbre1BatchId :: Lens' AccountshippingCustomBatchResponseEntry (Maybe Word32) acbre1BatchId = lens _acbre1BatchId (\ s a -> s{_acbre1BatchId = a}) . mapping _Coerce instance FromJSON AccountshippingCustomBatchResponseEntry where parseJSON = withObject "AccountshippingCustomBatchResponseEntry" (\ o -> AccountshippingCustomBatchResponseEntry' <$> (o .:? "kind" .!= "content#accountshippingCustomBatchResponseEntry") <*> (o .:? "errors") <*> (o .:? "accountShipping") <*> (o .:? "batchId")) instance ToJSON AccountshippingCustomBatchResponseEntry where toJSON AccountshippingCustomBatchResponseEntry'{..} = object (catMaybes [Just ("kind" .= _acbre1Kind), ("errors" .=) <$> _acbre1Errors, ("accountShipping" .=) <$> _acbre1AccountShipping, ("batchId" .=) <$> _acbre1BatchId]) -- -- /See:/ 'productAspect' smart constructor. data ProductAspect = ProductAspect' { _paIntention :: !(Maybe Text) , _paAspectName :: !(Maybe Text) , _paDestinationName :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ProductAspect' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'paIntention' -- -- * 'paAspectName' -- -- * 'paDestinationName' productAspect :: ProductAspect productAspect = ProductAspect' { _paIntention = Nothing , _paAspectName = Nothing , _paDestinationName = Nothing } -- | Whether the aspect is required, excluded or should be validated. paIntention :: Lens' ProductAspect (Maybe Text) paIntention = lens _paIntention (\ s a -> s{_paIntention = a}) -- | The name of the aspect. paAspectName :: Lens' ProductAspect (Maybe Text) paAspectName = lens _paAspectName (\ s a -> s{_paAspectName = a}) -- | The name of the destination. Leave out to apply to all destinations. paDestinationName :: Lens' ProductAspect (Maybe Text) paDestinationName = lens _paDestinationName (\ s a -> s{_paDestinationName = a}) instance FromJSON ProductAspect where parseJSON = withObject "ProductAspect" (\ o -> ProductAspect' <$> (o .:? "intention") <*> (o .:? "aspectName") <*> (o .:? "destinationName")) instance ToJSON ProductAspect where toJSON ProductAspect'{..} = object (catMaybes [("intention" .=) <$> _paIntention, ("aspectName" .=) <$> _paAspectName, ("destinationName" .=) <$> _paDestinationName]) -- | The shipping settings of a merchant account. -- -- /See:/ 'accountShipping' smart constructor. data AccountShipping = AccountShipping' { _assRateTables :: !(Maybe [AccountShippingRateTable]) , _assCarrierRates :: !(Maybe [AccountShippingCarrierRate]) , _assKind :: !Text , _assLocationGroups :: !(Maybe [AccountShippingLocationGroup]) , _assAccountId :: !(Maybe (Textual Word64)) , _assServices :: !(Maybe [AccountShippingShippingService]) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'AccountShipping' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'assRateTables' -- -- * 'assCarrierRates' -- -- * 'assKind' -- -- * 'assLocationGroups' -- -- * 'assAccountId' -- -- * 'assServices' accountShipping :: AccountShipping accountShipping = AccountShipping' { _assRateTables = Nothing , _assCarrierRates = Nothing , _assKind = "content#accountShipping" , _assLocationGroups = Nothing , _assAccountId = Nothing , _assServices = Nothing } -- | Rate tables definitions. assRateTables :: Lens' AccountShipping [AccountShippingRateTable] assRateTables = lens _assRateTables (\ s a -> s{_assRateTables = a}) . _Default . _Coerce -- | Carrier-based shipping calculations. assCarrierRates :: Lens' AccountShipping [AccountShippingCarrierRate] assCarrierRates = lens _assCarrierRates (\ s a -> s{_assCarrierRates = a}) . _Default . _Coerce -- | Identifies what kind of resource this is. Value: the fixed string -- \"content#accountShipping\". assKind :: Lens' AccountShipping Text assKind = lens _assKind (\ s a -> s{_assKind = a}) -- | Location groups for shipping. assLocationGroups :: Lens' AccountShipping [AccountShippingLocationGroup] assLocationGroups = lens _assLocationGroups (\ s a -> s{_assLocationGroups = a}) . _Default . _Coerce -- | The ID of the account to which these account shipping settings belong. assAccountId :: Lens' AccountShipping (Maybe Word64) assAccountId = lens _assAccountId (\ s a -> s{_assAccountId = a}) . mapping _Coerce -- | Shipping services describing shipping fees calculation. assServices :: Lens' AccountShipping [AccountShippingShippingService] assServices = lens _assServices (\ s a -> s{_assServices = a}) . _Default . _Coerce instance FromJSON AccountShipping where parseJSON = withObject "AccountShipping" (\ o -> AccountShipping' <$> (o .:? "rateTables" .!= mempty) <*> (o .:? "carrierRates" .!= mempty) <*> (o .:? "kind" .!= "content#accountShipping") <*> (o .:? "locationGroups" .!= mempty) <*> (o .:? "accountId") <*> (o .:? "services" .!= mempty)) instance ToJSON AccountShipping where toJSON AccountShipping'{..} = object (catMaybes [("rateTables" .=) <$> _assRateTables, ("carrierRates" .=) <$> _assCarrierRates, Just ("kind" .= _assKind), ("locationGroups" .=) <$> _assLocationGroups, ("accountId" .=) <$> _assAccountId, ("services" .=) <$> _assServices]) -- -- /See:/ 'ordersUpdateMerchantOrderIdResponse' smart constructor. data OrdersUpdateMerchantOrderIdResponse = OrdersUpdateMerchantOrderIdResponse' { _oumoirKind :: !Text , _oumoirExecutionStatus :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'OrdersUpdateMerchantOrderIdResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'oumoirKind' -- -- * 'oumoirExecutionStatus' ordersUpdateMerchantOrderIdResponse :: OrdersUpdateMerchantOrderIdResponse ordersUpdateMerchantOrderIdResponse = OrdersUpdateMerchantOrderIdResponse' { _oumoirKind = "content#ordersUpdateMerchantOrderIdResponse" , _oumoirExecutionStatus = Nothing } -- | Identifies what kind of resource this is. Value: the fixed string -- \"content#ordersUpdateMerchantOrderIdResponse\". oumoirKind :: Lens' OrdersUpdateMerchantOrderIdResponse Text oumoirKind = lens _oumoirKind (\ s a -> s{_oumoirKind = a}) -- | The status of the execution. oumoirExecutionStatus :: Lens' OrdersUpdateMerchantOrderIdResponse (Maybe Text) oumoirExecutionStatus = lens _oumoirExecutionStatus (\ s a -> s{_oumoirExecutionStatus = a}) instance FromJSON OrdersUpdateMerchantOrderIdResponse where parseJSON = withObject "OrdersUpdateMerchantOrderIdResponse" (\ o -> OrdersUpdateMerchantOrderIdResponse' <$> (o .:? "kind" .!= "content#ordersUpdateMerchantOrderIdResponse") <*> (o .:? "executionStatus")) instance ToJSON OrdersUpdateMerchantOrderIdResponse where toJSON OrdersUpdateMerchantOrderIdResponse'{..} = object (catMaybes [Just ("kind" .= _oumoirKind), ("executionStatus" .=) <$> _oumoirExecutionStatus]) -- -- /See:/ 'inventoryPickup' smart constructor. data InventoryPickup = InventoryPickup' { _ipPickupSla :: !(Maybe Text) , _ipPickupMethod :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'InventoryPickup' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ipPickupSla' -- -- * 'ipPickupMethod' inventoryPickup :: InventoryPickup inventoryPickup = InventoryPickup' { _ipPickupSla = Nothing , _ipPickupMethod = Nothing } -- | The expected date that an order will be ready for pickup, relative to -- when the order is placed. Only supported for local inventory. Must be -- submitted together with pickupMethod. ipPickupSla :: Lens' InventoryPickup (Maybe Text) ipPickupSla = lens _ipPickupSla (\ s a -> s{_ipPickupSla = a}) -- | Whether store pickup is available for this offer and whether the pickup -- option should be shown as buy, reserve, or not supported. Only supported -- for local inventory. Unless the value is \"not supported\", must be -- submitted together with pickupSla. ipPickupMethod :: Lens' InventoryPickup (Maybe Text) ipPickupMethod = lens _ipPickupMethod (\ s a -> s{_ipPickupMethod = a}) instance FromJSON InventoryPickup where parseJSON = withObject "InventoryPickup" (\ o -> InventoryPickup' <$> (o .:? "pickupSla") <*> (o .:? "pickupMethod")) instance ToJSON InventoryPickup where toJSON InventoryPickup'{..} = object (catMaybes [("pickupSla" .=) <$> _ipPickupSla, ("pickupMethod" .=) <$> _ipPickupMethod]) -- | An example occurrence for a particular error. -- -- /See:/ 'datafeedStatusExample' smart constructor. data DatafeedStatusExample = DatafeedStatusExample' { _dseLineNumber :: !(Maybe (Textual Word64)) , _dseItemId :: !(Maybe Text) , _dseValue :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'DatafeedStatusExample' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dseLineNumber' -- -- * 'dseItemId' -- -- * 'dseValue' datafeedStatusExample :: DatafeedStatusExample datafeedStatusExample = DatafeedStatusExample' { _dseLineNumber = Nothing , _dseItemId = Nothing , _dseValue = Nothing } -- | Line number in the data feed where the example is found. dseLineNumber :: Lens' DatafeedStatusExample (Maybe Word64) dseLineNumber = lens _dseLineNumber (\ s a -> s{_dseLineNumber = a}) . mapping _Coerce -- | The ID of the example item. dseItemId :: Lens' DatafeedStatusExample (Maybe Text) dseItemId = lens _dseItemId (\ s a -> s{_dseItemId = a}) -- | The problematic value. dseValue :: Lens' DatafeedStatusExample (Maybe Text) dseValue = lens _dseValue (\ s a -> s{_dseValue = a}) instance FromJSON DatafeedStatusExample where parseJSON = withObject "DatafeedStatusExample" (\ o -> DatafeedStatusExample' <$> (o .:? "lineNumber") <*> (o .:? "itemId") <*> (o .:? "value")) instance ToJSON DatafeedStatusExample where toJSON DatafeedStatusExample'{..} = object (catMaybes [("lineNumber" .=) <$> _dseLineNumber, ("itemId" .=) <$> _dseItemId, ("value" .=) <$> _dseValue]) -- -- /See:/ 'ordersAcknowledgeResponse' smart constructor. data OrdersAcknowledgeResponse = OrdersAcknowledgeResponse' { _oarKind :: !Text , _oarExecutionStatus :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'OrdersAcknowledgeResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'oarKind' -- -- * 'oarExecutionStatus' ordersAcknowledgeResponse :: OrdersAcknowledgeResponse ordersAcknowledgeResponse = OrdersAcknowledgeResponse' { _oarKind = "content#ordersAcknowledgeResponse" , _oarExecutionStatus = Nothing } -- | Identifies what kind of resource this is. Value: the fixed string -- \"content#ordersAcknowledgeResponse\". oarKind :: Lens' OrdersAcknowledgeResponse Text oarKind = lens _oarKind (\ s a -> s{_oarKind = a}) -- | The status of the execution. oarExecutionStatus :: Lens' OrdersAcknowledgeResponse (Maybe Text) oarExecutionStatus = lens _oarExecutionStatus (\ s a -> s{_oarExecutionStatus = a}) instance FromJSON OrdersAcknowledgeResponse where parseJSON = withObject "OrdersAcknowledgeResponse" (\ o -> OrdersAcknowledgeResponse' <$> (o .:? "kind" .!= "content#ordersAcknowledgeResponse") <*> (o .:? "executionStatus")) instance ToJSON OrdersAcknowledgeResponse where toJSON OrdersAcknowledgeResponse'{..} = object (catMaybes [Just ("kind" .= _oarKind), ("executionStatus" .=) <$> _oarExecutionStatus]) -- -- /See:/ 'table' smart constructor. data Table = Table' { _tRows :: !(Maybe [Row]) , _tName :: !(Maybe Text) , _tColumnHeaders :: !(Maybe Headers) , _tRowHeaders :: !(Maybe Headers) } 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: -- -- * 'tRows' -- -- * 'tName' -- -- * 'tColumnHeaders' -- -- * 'tRowHeaders' table :: Table table = Table' { _tRows = Nothing , _tName = Nothing , _tColumnHeaders = Nothing , _tRowHeaders = Nothing } -- | The list of rows that constitute the table. Must have the same length as -- rowHeaders. Required. tRows :: Lens' Table [Row] tRows = lens _tRows (\ s a -> s{_tRows = a}) . _Default . _Coerce -- | Name of the table. Required for subtables, ignored for the main table. tName :: Lens' Table (Maybe Text) tName = lens _tName (\ s a -> s{_tName = a}) -- | Headers of the table\'s columns. Optional: if not set then the table has -- only one dimension. tColumnHeaders :: Lens' Table (Maybe Headers) tColumnHeaders = lens _tColumnHeaders (\ s a -> s{_tColumnHeaders = a}) -- | Headers of the table\'s rows. Required. tRowHeaders :: Lens' Table (Maybe Headers) tRowHeaders = lens _tRowHeaders (\ s a -> s{_tRowHeaders = a}) instance FromJSON Table where parseJSON = withObject "Table" (\ o -> Table' <$> (o .:? "rows" .!= mempty) <*> (o .:? "name") <*> (o .:? "columnHeaders") <*> (o .:? "rowHeaders")) instance ToJSON Table where toJSON Table'{..} = object (catMaybes [("rows" .=) <$> _tRows, ("name" .=) <$> _tName, ("columnHeaders" .=) <$> _tColumnHeaders, ("rowHeaders" .=) <$> _tRowHeaders]) -- -- /See:/ 'order' smart constructor. data Order = Order' { _ooStatus :: !(Maybe Text) , _ooMerchantId :: !(Maybe (Textual Word64)) , _ooRefunds :: !(Maybe [OrderRefund]) , _ooKind :: !Text , _ooLineItems :: !(Maybe [OrderLineItem]) , _ooShipments :: !(Maybe [OrderShipment]) , _ooNetAmount :: !(Maybe Price) , _ooPlacedDate :: !(Maybe Text) , _ooDeliveryDetails :: !(Maybe OrderDeliveryDetails) , _ooShippingOption :: !(Maybe Text) , _ooMerchantOrderId :: !(Maybe Text) , _ooAcknowledged :: !(Maybe Bool) , _ooShippingCostTax :: !(Maybe Price) , _ooCustomer :: !(Maybe OrderCustomer) , _ooId :: !(Maybe Text) , _ooPaymentMethod :: !(Maybe OrderPaymentMethod) , _ooPromotions :: !(Maybe [OrderPromotion]) , _ooChannelType :: !(Maybe Text) , _ooPaymentStatus :: !(Maybe Text) , _ooShippingCost :: !(Maybe Price) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'Order' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ooStatus' -- -- * 'ooMerchantId' -- -- * 'ooRefunds' -- -- * 'ooKind' -- -- * 'ooLineItems' -- -- * 'ooShipments' -- -- * 'ooNetAmount' -- -- * 'ooPlacedDate' -- -- * 'ooDeliveryDetails' -- -- * 'ooShippingOption' -- -- * 'ooMerchantOrderId' -- -- * 'ooAcknowledged' -- -- * 'ooShippingCostTax' -- -- * 'ooCustomer' -- -- * 'ooId' -- -- * 'ooPaymentMethod' -- -- * 'ooPromotions' -- -- * 'ooChannelType' -- -- * 'ooPaymentStatus' -- -- * 'ooShippingCost' order :: Order order = Order' { _ooStatus = Nothing , _ooMerchantId = Nothing , _ooRefunds = Nothing , _ooKind = "content#order" , _ooLineItems = Nothing , _ooShipments = Nothing , _ooNetAmount = Nothing , _ooPlacedDate = Nothing , _ooDeliveryDetails = Nothing , _ooShippingOption = Nothing , _ooMerchantOrderId = Nothing , _ooAcknowledged = Nothing , _ooShippingCostTax = Nothing , _ooCustomer = Nothing , _ooId = Nothing , _ooPaymentMethod = Nothing , _ooPromotions = Nothing , _ooChannelType = Nothing , _ooPaymentStatus = Nothing , _ooShippingCost = Nothing } -- | The status of the order. ooStatus :: Lens' Order (Maybe Text) ooStatus = lens _ooStatus (\ s a -> s{_ooStatus = a}) ooMerchantId :: Lens' Order (Maybe Word64) ooMerchantId = lens _ooMerchantId (\ s a -> s{_ooMerchantId = a}) . mapping _Coerce -- | Refunds for the order. ooRefunds :: Lens' Order [OrderRefund] ooRefunds = lens _ooRefunds (\ s a -> s{_ooRefunds = a}) . _Default . _Coerce -- | Identifies what kind of resource this is. Value: the fixed string -- \"content#order\". ooKind :: Lens' Order Text ooKind = lens _ooKind (\ s a -> s{_ooKind = a}) -- | Line items that are ordered. ooLineItems :: Lens' Order [OrderLineItem] ooLineItems = lens _ooLineItems (\ s a -> s{_ooLineItems = a}) . _Default . _Coerce -- | Shipments of the order. ooShipments :: Lens' Order [OrderShipment] ooShipments = lens _ooShipments (\ s a -> s{_ooShipments = a}) . _Default . _Coerce -- | The net amount for the order. For example, if an order was originally -- for a grand total of $100 and a refund was issued for $20, the net -- amount will be $80. ooNetAmount :: Lens' Order (Maybe Price) ooNetAmount = lens _ooNetAmount (\ s a -> s{_ooNetAmount = a}) -- | The date when the order was placed, in ISO 8601 format. ooPlacedDate :: Lens' Order (Maybe Text) ooPlacedDate = lens _ooPlacedDate (\ s a -> s{_ooPlacedDate = a}) -- | The details for the delivery. ooDeliveryDetails :: Lens' Order (Maybe OrderDeliveryDetails) ooDeliveryDetails = lens _ooDeliveryDetails (\ s a -> s{_ooDeliveryDetails = a}) -- | The requested shipping option. ooShippingOption :: Lens' Order (Maybe Text) ooShippingOption = lens _ooShippingOption (\ s a -> s{_ooShippingOption = a}) -- | Merchant-provided id of the order. ooMerchantOrderId :: Lens' Order (Maybe Text) ooMerchantOrderId = lens _ooMerchantOrderId (\ s a -> s{_ooMerchantOrderId = a}) -- | Whether the order was acknowledged. ooAcknowledged :: Lens' Order (Maybe Bool) ooAcknowledged = lens _ooAcknowledged (\ s a -> s{_ooAcknowledged = a}) -- | The tax for the total shipping cost. ooShippingCostTax :: Lens' Order (Maybe Price) ooShippingCostTax = lens _ooShippingCostTax (\ s a -> s{_ooShippingCostTax = a}) -- | The details of the customer who placed the order. ooCustomer :: Lens' Order (Maybe OrderCustomer) ooCustomer = lens _ooCustomer (\ s a -> s{_ooCustomer = a}) -- | The REST id of the order. Globally unique. ooId :: Lens' Order (Maybe Text) ooId = lens _ooId (\ s a -> s{_ooId = a}) -- | The details of the payment method. ooPaymentMethod :: Lens' Order (Maybe OrderPaymentMethod) ooPaymentMethod = lens _ooPaymentMethod (\ s a -> s{_ooPaymentMethod = a}) -- | The details of the merchant provided promotions applied to the order. -- More details about the program are here. ooPromotions :: Lens' Order [OrderPromotion] ooPromotions = lens _ooPromotions (\ s a -> s{_ooPromotions = a}) . _Default . _Coerce -- | The channel type of the order: \"purchaseOnGoogle\" or -- \"googleExpress\". ooChannelType :: Lens' Order (Maybe Text) ooChannelType = lens _ooChannelType (\ s a -> s{_ooChannelType = a}) -- | The status of the payment. ooPaymentStatus :: Lens' Order (Maybe Text) ooPaymentStatus = lens _ooPaymentStatus (\ s a -> s{_ooPaymentStatus = a}) -- | The total cost of shipping for all items. ooShippingCost :: Lens' Order (Maybe Price) ooShippingCost = lens _ooShippingCost (\ s a -> s{_ooShippingCost = a}) instance FromJSON Order where parseJSON = withObject "Order" (\ o -> Order' <$> (o .:? "status") <*> (o .:? "merchantId") <*> (o .:? "refunds" .!= mempty) <*> (o .:? "kind" .!= "content#order") <*> (o .:? "lineItems" .!= mempty) <*> (o .:? "shipments" .!= mempty) <*> (o .:? "netAmount") <*> (o .:? "placedDate") <*> (o .:? "deliveryDetails") <*> (o .:? "shippingOption") <*> (o .:? "merchantOrderId") <*> (o .:? "acknowledged") <*> (o .:? "shippingCostTax") <*> (o .:? "customer") <*> (o .:? "id") <*> (o .:? "paymentMethod") <*> (o .:? "promotions" .!= mempty) <*> (o .:? "channelType") <*> (o .:? "paymentStatus") <*> (o .:? "shippingCost")) instance ToJSON Order where toJSON Order'{..} = object (catMaybes [("status" .=) <$> _ooStatus, ("merchantId" .=) <$> _ooMerchantId, ("refunds" .=) <$> _ooRefunds, Just ("kind" .= _ooKind), ("lineItems" .=) <$> _ooLineItems, ("shipments" .=) <$> _ooShipments, ("netAmount" .=) <$> _ooNetAmount, ("placedDate" .=) <$> _ooPlacedDate, ("deliveryDetails" .=) <$> _ooDeliveryDetails, ("shippingOption" .=) <$> _ooShippingOption, ("merchantOrderId" .=) <$> _ooMerchantOrderId, ("acknowledged" .=) <$> _ooAcknowledged, ("shippingCostTax" .=) <$> _ooShippingCostTax, ("customer" .=) <$> _ooCustomer, ("id" .=) <$> _ooId, ("paymentMethod" .=) <$> _ooPaymentMethod, ("promotions" .=) <$> _ooPromotions, ("channelType" .=) <$> _ooChannelType, ("paymentStatus" .=) <$> _ooPaymentStatus, ("shippingCost" .=) <$> _ooShippingCost]) -- -- /See:/ 'inventoryCustomBatchResponse' smart constructor. data InventoryCustomBatchResponse = InventoryCustomBatchResponse' { _invEntries :: !(Maybe [InventoryCustomBatchResponseEntry]) , _invKind :: !Text } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'InventoryCustomBatchResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'invEntries' -- -- * 'invKind' inventoryCustomBatchResponse :: InventoryCustomBatchResponse inventoryCustomBatchResponse = InventoryCustomBatchResponse' { _invEntries = Nothing , _invKind = "content#inventoryCustomBatchResponse" } -- | The result of the execution of the batch requests. invEntries :: Lens' InventoryCustomBatchResponse [InventoryCustomBatchResponseEntry] invEntries = lens _invEntries (\ s a -> s{_invEntries = a}) . _Default . _Coerce -- | Identifies what kind of resource this is. Value: the fixed string -- \"content#inventoryCustomBatchResponse\". invKind :: Lens' InventoryCustomBatchResponse Text invKind = lens _invKind (\ s a -> s{_invKind = a}) instance FromJSON InventoryCustomBatchResponse where parseJSON = withObject "InventoryCustomBatchResponse" (\ o -> InventoryCustomBatchResponse' <$> (o .:? "entries" .!= mempty) <*> (o .:? "kind" .!= "content#inventoryCustomBatchResponse")) instance ToJSON InventoryCustomBatchResponse where toJSON InventoryCustomBatchResponse'{..} = object (catMaybes [("entries" .=) <$> _invEntries, Just ("kind" .= _invKind)]) -- -- /See:/ 'orderLineItemProduct' smart constructor. data OrderLineItemProduct = OrderLineItemProduct' { _olipImageLink :: !(Maybe Text) , _olipShownImage :: !(Maybe Text) , _olipChannel :: !(Maybe Text) , _olipBrand :: !(Maybe Text) , _olipTargetCountry :: !(Maybe Text) , _olipGtin :: !(Maybe Text) , _olipItemGroupId :: !(Maybe Text) , _olipOfferId :: !(Maybe Text) , _olipId :: !(Maybe Text) , _olipPrice :: !(Maybe Price) , _olipVariantAttributes :: !(Maybe [OrderLineItemProductVariantAttribute]) , _olipTitle :: !(Maybe Text) , _olipContentLanguage :: !(Maybe Text) , _olipMpn :: !(Maybe Text) , _olipCondition :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'OrderLineItemProduct' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'olipImageLink' -- -- * 'olipShownImage' -- -- * 'olipChannel' -- -- * 'olipBrand' -- -- * 'olipTargetCountry' -- -- * 'olipGtin' -- -- * 'olipItemGroupId' -- -- * 'olipOfferId' -- -- * 'olipId' -- -- * 'olipPrice' -- -- * 'olipVariantAttributes' -- -- * 'olipTitle' -- -- * 'olipContentLanguage' -- -- * 'olipMpn' -- -- * 'olipCondition' orderLineItemProduct :: OrderLineItemProduct orderLineItemProduct = OrderLineItemProduct' { _olipImageLink = Nothing , _olipShownImage = Nothing , _olipChannel = Nothing , _olipBrand = Nothing , _olipTargetCountry = Nothing , _olipGtin = Nothing , _olipItemGroupId = Nothing , _olipOfferId = Nothing , _olipId = Nothing , _olipPrice = Nothing , _olipVariantAttributes = Nothing , _olipTitle = Nothing , _olipContentLanguage = Nothing , _olipMpn = Nothing , _olipCondition = Nothing } -- | URL of an image of the item. olipImageLink :: Lens' OrderLineItemProduct (Maybe Text) olipImageLink = lens _olipImageLink (\ s a -> s{_olipImageLink = a}) -- | URL to the cached image shown to the user when order was placed. olipShownImage :: Lens' OrderLineItemProduct (Maybe Text) olipShownImage = lens _olipShownImage (\ s a -> s{_olipShownImage = a}) -- | The item\'s channel (online or local). olipChannel :: Lens' OrderLineItemProduct (Maybe Text) olipChannel = lens _olipChannel (\ s a -> s{_olipChannel = a}) -- | Brand of the item. olipBrand :: Lens' OrderLineItemProduct (Maybe Text) olipBrand = lens _olipBrand (\ s a -> s{_olipBrand = a}) -- | The CLDR territory code of the target country of the product. olipTargetCountry :: Lens' OrderLineItemProduct (Maybe Text) olipTargetCountry = lens _olipTargetCountry (\ s a -> s{_olipTargetCountry = a}) -- | Global Trade Item Number (GTIN) of the item. olipGtin :: Lens' OrderLineItemProduct (Maybe Text) olipGtin = lens _olipGtin (\ s a -> s{_olipGtin = a}) -- | Shared identifier for all variants of the same product. olipItemGroupId :: Lens' OrderLineItemProduct (Maybe Text) olipItemGroupId = lens _olipItemGroupId (\ s a -> s{_olipItemGroupId = a}) -- | An identifier of the item. olipOfferId :: Lens' OrderLineItemProduct (Maybe Text) olipOfferId = lens _olipOfferId (\ s a -> s{_olipOfferId = a}) -- | The REST id of the product. olipId :: Lens' OrderLineItemProduct (Maybe Text) olipId = lens _olipId (\ s a -> s{_olipId = a}) -- | Price of the item. olipPrice :: Lens' OrderLineItemProduct (Maybe Price) olipPrice = lens _olipPrice (\ s a -> s{_olipPrice = a}) -- | Variant attributes for the item. These are dimensions of the product, -- such as color, gender, material, pattern, and size. You can find a -- comprehensive list of variant attributes here. olipVariantAttributes :: Lens' OrderLineItemProduct [OrderLineItemProductVariantAttribute] olipVariantAttributes = lens _olipVariantAttributes (\ s a -> s{_olipVariantAttributes = a}) . _Default . _Coerce -- | The title of the product. olipTitle :: Lens' OrderLineItemProduct (Maybe Text) olipTitle = lens _olipTitle (\ s a -> s{_olipTitle = a}) -- | The two-letter ISO 639-1 language code for the item. olipContentLanguage :: Lens' OrderLineItemProduct (Maybe Text) olipContentLanguage = lens _olipContentLanguage (\ s a -> s{_olipContentLanguage = a}) -- | Manufacturer Part Number (MPN) of the item. olipMpn :: Lens' OrderLineItemProduct (Maybe Text) olipMpn = lens _olipMpn (\ s a -> s{_olipMpn = a}) -- | Condition or state of the item. olipCondition :: Lens' OrderLineItemProduct (Maybe Text) olipCondition = lens _olipCondition (\ s a -> s{_olipCondition = a}) instance FromJSON OrderLineItemProduct where parseJSON = withObject "OrderLineItemProduct" (\ o -> OrderLineItemProduct' <$> (o .:? "imageLink") <*> (o .:? "shownImage") <*> (o .:? "channel") <*> (o .:? "brand") <*> (o .:? "targetCountry") <*> (o .:? "gtin") <*> (o .:? "itemGroupId") <*> (o .:? "offerId") <*> (o .:? "id") <*> (o .:? "price") <*> (o .:? "variantAttributes" .!= mempty) <*> (o .:? "title") <*> (o .:? "contentLanguage") <*> (o .:? "mpn") <*> (o .:? "condition")) instance ToJSON OrderLineItemProduct where toJSON OrderLineItemProduct'{..} = object (catMaybes [("imageLink" .=) <$> _olipImageLink, ("shownImage" .=) <$> _olipShownImage, ("channel" .=) <$> _olipChannel, ("brand" .=) <$> _olipBrand, ("targetCountry" .=) <$> _olipTargetCountry, ("gtin" .=) <$> _olipGtin, ("itemGroupId" .=) <$> _olipItemGroupId, ("offerId" .=) <$> _olipOfferId, ("id" .=) <$> _olipId, ("price" .=) <$> _olipPrice, ("variantAttributes" .=) <$> _olipVariantAttributes, ("title" .=) <$> _olipTitle, ("contentLanguage" .=) <$> _olipContentLanguage, ("mpn" .=) <$> _olipMpn, ("condition" .=) <$> _olipCondition]) -- | A batch entry encoding a single non-batch accounttax request. -- -- /See:/ 'accounttaxCustomBatchRequestEntry' smart constructor. data AccounttaxCustomBatchRequestEntry = AccounttaxCustomBatchRequestEntry' { _a2AccountTax :: !(Maybe AccountTax) , _a2MerchantId :: !(Maybe (Textual Word64)) , _a2AccountId :: !(Maybe (Textual Word64)) , _a2Method :: !(Maybe Text) , _a2BatchId :: !(Maybe (Textual Word32)) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'AccounttaxCustomBatchRequestEntry' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'a2AccountTax' -- -- * 'a2MerchantId' -- -- * 'a2AccountId' -- -- * 'a2Method' -- -- * 'a2BatchId' accounttaxCustomBatchRequestEntry :: AccounttaxCustomBatchRequestEntry accounttaxCustomBatchRequestEntry = AccounttaxCustomBatchRequestEntry' { _a2AccountTax = Nothing , _a2MerchantId = Nothing , _a2AccountId = Nothing , _a2Method = Nothing , _a2BatchId = Nothing } -- | The account tax settings to update. Only defined if the method is -- update. a2AccountTax :: Lens' AccounttaxCustomBatchRequestEntry (Maybe AccountTax) a2AccountTax = lens _a2AccountTax (\ s a -> s{_a2AccountTax = a}) -- | The ID of the managing account. a2MerchantId :: Lens' AccounttaxCustomBatchRequestEntry (Maybe Word64) a2MerchantId = lens _a2MerchantId (\ s a -> s{_a2MerchantId = a}) . mapping _Coerce -- | The ID of the account for which to get\/update account tax settings. a2AccountId :: Lens' AccounttaxCustomBatchRequestEntry (Maybe Word64) a2AccountId = lens _a2AccountId (\ s a -> s{_a2AccountId = a}) . mapping _Coerce a2Method :: Lens' AccounttaxCustomBatchRequestEntry (Maybe Text) a2Method = lens _a2Method (\ s a -> s{_a2Method = a}) -- | An entry ID, unique within the batch request. a2BatchId :: Lens' AccounttaxCustomBatchRequestEntry (Maybe Word32) a2BatchId = lens _a2BatchId (\ s a -> s{_a2BatchId = a}) . mapping _Coerce instance FromJSON AccounttaxCustomBatchRequestEntry where parseJSON = withObject "AccounttaxCustomBatchRequestEntry" (\ o -> AccounttaxCustomBatchRequestEntry' <$> (o .:? "accountTax") <*> (o .:? "merchantId") <*> (o .:? "accountId") <*> (o .:? "method") <*> (o .:? "batchId")) instance ToJSON AccounttaxCustomBatchRequestEntry where toJSON AccounttaxCustomBatchRequestEntry'{..} = object (catMaybes [("accountTax" .=) <$> _a2AccountTax, ("merchantId" .=) <$> _a2MerchantId, ("accountId" .=) <$> _a2AccountId, ("method" .=) <$> _a2Method, ("batchId" .=) <$> _a2BatchId]) -- | An error occurring in the feed, like \"invalid price\". -- -- /See:/ 'datafeedStatusError' smart constructor. data DatafeedStatusError = DatafeedStatusError' { _dseCount :: !(Maybe (Textual Word64)) , _dseCode :: !(Maybe Text) , _dseMessage :: !(Maybe Text) , _dseExamples :: !(Maybe [DatafeedStatusExample]) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'DatafeedStatusError' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dseCount' -- -- * 'dseCode' -- -- * 'dseMessage' -- -- * 'dseExamples' datafeedStatusError :: DatafeedStatusError datafeedStatusError = DatafeedStatusError' { _dseCount = Nothing , _dseCode = Nothing , _dseMessage = Nothing , _dseExamples = Nothing } -- | The number of occurrences of the error in the feed. dseCount :: Lens' DatafeedStatusError (Maybe Word64) dseCount = lens _dseCount (\ s a -> s{_dseCount = a}) . mapping _Coerce -- | The code of the error, e.g., \"validation\/invalid_value\". dseCode :: Lens' DatafeedStatusError (Maybe Text) dseCode = lens _dseCode (\ s a -> s{_dseCode = a}) -- | The error message, e.g., \"Invalid price\". dseMessage :: Lens' DatafeedStatusError (Maybe Text) dseMessage = lens _dseMessage (\ s a -> s{_dseMessage = a}) -- | A list of example occurrences of the error, grouped by product. dseExamples :: Lens' DatafeedStatusError [DatafeedStatusExample] dseExamples = lens _dseExamples (\ s a -> s{_dseExamples = a}) . _Default . _Coerce instance FromJSON DatafeedStatusError where parseJSON = withObject "DatafeedStatusError" (\ o -> DatafeedStatusError' <$> (o .:? "count") <*> (o .:? "code") <*> (o .:? "message") <*> (o .:? "examples" .!= mempty)) instance ToJSON DatafeedStatusError where toJSON DatafeedStatusError'{..} = object (catMaybes [("count" .=) <$> _dseCount, ("code" .=) <$> _dseCode, ("message" .=) <$> _dseMessage, ("examples" .=) <$> _dseExamples]) -- -- /See:/ 'productsCustomBatchRequest' smart constructor. newtype ProductsCustomBatchRequest = ProductsCustomBatchRequest' { _pcbrcEntries :: Maybe [ProductsCustomBatchRequestEntry] } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ProductsCustomBatchRequest' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pcbrcEntries' productsCustomBatchRequest :: ProductsCustomBatchRequest productsCustomBatchRequest = ProductsCustomBatchRequest' { _pcbrcEntries = Nothing } -- | The request entries to be processed in the batch. pcbrcEntries :: Lens' ProductsCustomBatchRequest [ProductsCustomBatchRequestEntry] pcbrcEntries = lens _pcbrcEntries (\ s a -> s{_pcbrcEntries = a}) . _Default . _Coerce instance FromJSON ProductsCustomBatchRequest where parseJSON = withObject "ProductsCustomBatchRequest" (\ o -> ProductsCustomBatchRequest' <$> (o .:? "entries" .!= mempty)) instance ToJSON ProductsCustomBatchRequest where toJSON ProductsCustomBatchRequest'{..} = object (catMaybes [("entries" .=) <$> _pcbrcEntries]) -- -- /See:/ 'ordersCustomBatchRequestEntryReturnLineItem' smart constructor. data OrdersCustomBatchRequestEntryReturnLineItem = OrdersCustomBatchRequestEntryReturnLineItem' { _ocbrerliQuantity :: !(Maybe (Textual Word32)) , _ocbrerliLineItemId :: !(Maybe Text) , _ocbrerliReason :: !(Maybe Text) , _ocbrerliReasonText :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'OrdersCustomBatchRequestEntryReturnLineItem' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ocbrerliQuantity' -- -- * 'ocbrerliLineItemId' -- -- * 'ocbrerliReason' -- -- * 'ocbrerliReasonText' ordersCustomBatchRequestEntryReturnLineItem :: OrdersCustomBatchRequestEntryReturnLineItem ordersCustomBatchRequestEntryReturnLineItem = OrdersCustomBatchRequestEntryReturnLineItem' { _ocbrerliQuantity = Nothing , _ocbrerliLineItemId = Nothing , _ocbrerliReason = Nothing , _ocbrerliReasonText = Nothing } -- | The quantity to return. ocbrerliQuantity :: Lens' OrdersCustomBatchRequestEntryReturnLineItem (Maybe Word32) ocbrerliQuantity = lens _ocbrerliQuantity (\ s a -> s{_ocbrerliQuantity = a}) . mapping _Coerce -- | The ID of the line item to return. ocbrerliLineItemId :: Lens' OrdersCustomBatchRequestEntryReturnLineItem (Maybe Text) ocbrerliLineItemId = lens _ocbrerliLineItemId (\ s a -> s{_ocbrerliLineItemId = a}) -- | The reason for the return. ocbrerliReason :: Lens' OrdersCustomBatchRequestEntryReturnLineItem (Maybe Text) ocbrerliReason = lens _ocbrerliReason (\ s a -> s{_ocbrerliReason = a}) -- | The explanation of the reason. ocbrerliReasonText :: Lens' OrdersCustomBatchRequestEntryReturnLineItem (Maybe Text) ocbrerliReasonText = lens _ocbrerliReasonText (\ s a -> s{_ocbrerliReasonText = a}) instance FromJSON OrdersCustomBatchRequestEntryReturnLineItem where parseJSON = withObject "OrdersCustomBatchRequestEntryReturnLineItem" (\ o -> OrdersCustomBatchRequestEntryReturnLineItem' <$> (o .:? "quantity") <*> (o .:? "lineItemId") <*> (o .:? "reason") <*> (o .:? "reasonText")) instance ToJSON OrdersCustomBatchRequestEntryReturnLineItem where toJSON OrdersCustomBatchRequestEntryReturnLineItem'{..} = object (catMaybes [("quantity" .=) <$> _ocbrerliQuantity, ("lineItemId" .=) <$> _ocbrerliLineItemId, ("reason" .=) <$> _ocbrerliReason, ("reasonText" .=) <$> _ocbrerliReasonText]) -- -- /See:/ 'ordersCustomBatchRequestEntryUpdateShipment' smart constructor. data OrdersCustomBatchRequestEntryUpdateShipment = OrdersCustomBatchRequestEntryUpdateShipment' { _ocbreusCarrier :: !(Maybe Text) , _ocbreusStatus :: !(Maybe Text) , _ocbreusTrackingId :: !(Maybe Text) , _ocbreusShipmentId :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'OrdersCustomBatchRequestEntryUpdateShipment' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ocbreusCarrier' -- -- * 'ocbreusStatus' -- -- * 'ocbreusTrackingId' -- -- * 'ocbreusShipmentId' ordersCustomBatchRequestEntryUpdateShipment :: OrdersCustomBatchRequestEntryUpdateShipment ordersCustomBatchRequestEntryUpdateShipment = OrdersCustomBatchRequestEntryUpdateShipment' { _ocbreusCarrier = Nothing , _ocbreusStatus = Nothing , _ocbreusTrackingId = Nothing , _ocbreusShipmentId = Nothing } -- | The carrier handling the shipment. Not updated if missing. ocbreusCarrier :: Lens' OrdersCustomBatchRequestEntryUpdateShipment (Maybe Text) ocbreusCarrier = lens _ocbreusCarrier (\ s a -> s{_ocbreusCarrier = a}) -- | New status for the shipment. Not updated if missing. ocbreusStatus :: Lens' OrdersCustomBatchRequestEntryUpdateShipment (Maybe Text) ocbreusStatus = lens _ocbreusStatus (\ s a -> s{_ocbreusStatus = a}) -- | The tracking id for the shipment. Not updated if missing. ocbreusTrackingId :: Lens' OrdersCustomBatchRequestEntryUpdateShipment (Maybe Text) ocbreusTrackingId = lens _ocbreusTrackingId (\ s a -> s{_ocbreusTrackingId = a}) -- | The ID of the shipment. ocbreusShipmentId :: Lens' OrdersCustomBatchRequestEntryUpdateShipment (Maybe Text) ocbreusShipmentId = lens _ocbreusShipmentId (\ s a -> s{_ocbreusShipmentId = a}) instance FromJSON OrdersCustomBatchRequestEntryUpdateShipment where parseJSON = withObject "OrdersCustomBatchRequestEntryUpdateShipment" (\ o -> OrdersCustomBatchRequestEntryUpdateShipment' <$> (o .:? "carrier") <*> (o .:? "status") <*> (o .:? "trackingId") <*> (o .:? "shipmentId")) instance ToJSON OrdersCustomBatchRequestEntryUpdateShipment where toJSON OrdersCustomBatchRequestEntryUpdateShipment'{..} = object (catMaybes [("carrier" .=) <$> _ocbreusCarrier, ("status" .=) <$> _ocbreusStatus, ("trackingId" .=) <$> _ocbreusTrackingId, ("shipmentId" .=) <$> _ocbreusShipmentId]) -- | The status of a datafeed, i.e., the result of the last retrieval of the -- datafeed computed asynchronously when the feed processing is finished. -- -- /See:/ 'datafeedStatus' smart constructor. data DatafeedStatus = DatafeedStatus' { _dsItemsTotal :: !(Maybe (Textual Word64)) , _dsKind :: !Text , _dsWarnings :: !(Maybe [DatafeedStatusError]) , _dsDatafeedId :: !(Maybe (Textual Word64)) , _dsProcessingStatus :: !(Maybe Text) , _dsLastUploadDate :: !(Maybe Text) , _dsItemsValid :: !(Maybe (Textual Word64)) , _dsErrors :: !(Maybe [DatafeedStatusError]) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'DatafeedStatus' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dsItemsTotal' -- -- * 'dsKind' -- -- * 'dsWarnings' -- -- * 'dsDatafeedId' -- -- * 'dsProcessingStatus' -- -- * 'dsLastUploadDate' -- -- * 'dsItemsValid' -- -- * 'dsErrors' datafeedStatus :: DatafeedStatus datafeedStatus = DatafeedStatus' { _dsItemsTotal = Nothing , _dsKind = "content#datafeedStatus" , _dsWarnings = Nothing , _dsDatafeedId = Nothing , _dsProcessingStatus = Nothing , _dsLastUploadDate = Nothing , _dsItemsValid = Nothing , _dsErrors = Nothing } -- | The number of items in the feed that were processed. dsItemsTotal :: Lens' DatafeedStatus (Maybe Word64) dsItemsTotal = lens _dsItemsTotal (\ s a -> s{_dsItemsTotal = a}) . mapping _Coerce -- | Identifies what kind of resource this is. Value: the fixed string -- \"content#datafeedStatus\". dsKind :: Lens' DatafeedStatus Text dsKind = lens _dsKind (\ s a -> s{_dsKind = a}) -- | The list of errors occurring in the feed. dsWarnings :: Lens' DatafeedStatus [DatafeedStatusError] dsWarnings = lens _dsWarnings (\ s a -> s{_dsWarnings = a}) . _Default . _Coerce -- | The ID of the feed for which the status is reported. dsDatafeedId :: Lens' DatafeedStatus (Maybe Word64) dsDatafeedId = lens _dsDatafeedId (\ s a -> s{_dsDatafeedId = a}) . mapping _Coerce -- | The processing status of the feed. dsProcessingStatus :: Lens' DatafeedStatus (Maybe Text) dsProcessingStatus = lens _dsProcessingStatus (\ s a -> s{_dsProcessingStatus = a}) -- | The last date at which the feed was uploaded. dsLastUploadDate :: Lens' DatafeedStatus (Maybe Text) dsLastUploadDate = lens _dsLastUploadDate (\ s a -> s{_dsLastUploadDate = a}) -- | The number of items in the feed that were valid. dsItemsValid :: Lens' DatafeedStatus (Maybe Word64) dsItemsValid = lens _dsItemsValid (\ s a -> s{_dsItemsValid = a}) . mapping _Coerce -- | The list of errors occurring in the feed. dsErrors :: Lens' DatafeedStatus [DatafeedStatusError] dsErrors = lens _dsErrors (\ s a -> s{_dsErrors = a}) . _Default . _Coerce instance FromJSON DatafeedStatus where parseJSON = withObject "DatafeedStatus" (\ o -> DatafeedStatus' <$> (o .:? "itemsTotal") <*> (o .:? "kind" .!= "content#datafeedStatus") <*> (o .:? "warnings" .!= mempty) <*> (o .:? "datafeedId") <*> (o .:? "processingStatus") <*> (o .:? "lastUploadDate") <*> (o .:? "itemsValid") <*> (o .:? "errors" .!= mempty)) instance ToJSON DatafeedStatus where toJSON DatafeedStatus'{..} = object (catMaybes [("itemsTotal" .=) <$> _dsItemsTotal, Just ("kind" .= _dsKind), ("warnings" .=) <$> _dsWarnings, ("datafeedId" .=) <$> _dsDatafeedId, ("processingStatus" .=) <$> _dsProcessingStatus, ("lastUploadDate" .=) <$> _dsLastUploadDate, ("itemsValid" .=) <$> _dsItemsValid, ("errors" .=) <$> _dsErrors]) -- -- /See:/ 'datafeedstatusesCustomBatchRequest' smart constructor. newtype DatafeedstatusesCustomBatchRequest = DatafeedstatusesCustomBatchRequest' { _dcbrcEntries :: Maybe [DatafeedstatusesCustomBatchRequestEntry] } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'DatafeedstatusesCustomBatchRequest' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dcbrcEntries' datafeedstatusesCustomBatchRequest :: DatafeedstatusesCustomBatchRequest datafeedstatusesCustomBatchRequest = DatafeedstatusesCustomBatchRequest' { _dcbrcEntries = Nothing } -- | The request entries to be processed in the batch. dcbrcEntries :: Lens' DatafeedstatusesCustomBatchRequest [DatafeedstatusesCustomBatchRequestEntry] dcbrcEntries = lens _dcbrcEntries (\ s a -> s{_dcbrcEntries = a}) . _Default . _Coerce instance FromJSON DatafeedstatusesCustomBatchRequest where parseJSON = withObject "DatafeedstatusesCustomBatchRequest" (\ o -> DatafeedstatusesCustomBatchRequest' <$> (o .:? "entries" .!= mempty)) instance ToJSON DatafeedstatusesCustomBatchRequest where toJSON DatafeedstatusesCustomBatchRequest'{..} = object (catMaybes [("entries" .=) <$> _dcbrcEntries]) -- | A user-defined locations group in a given country. All the locations of -- the group must be of the same type. -- -- /See:/ 'accountShippingLocationGroup' smart constructor. data AccountShippingLocationGroup = AccountShippingLocationGroup' { _aslgCountry :: !(Maybe Text) , _aslgLocationIds :: !(Maybe [Textual Int64]) , _aslgPostalCodeRanges :: !(Maybe [AccountShippingPostalCodeRange]) , _aslgName :: !(Maybe Text) , _aslgPostalCodes :: !(Maybe [Text]) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'AccountShippingLocationGroup' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'aslgCountry' -- -- * 'aslgLocationIds' -- -- * 'aslgPostalCodeRanges' -- -- * 'aslgName' -- -- * 'aslgPostalCodes' accountShippingLocationGroup :: AccountShippingLocationGroup accountShippingLocationGroup = AccountShippingLocationGroup' { _aslgCountry = Nothing , _aslgLocationIds = Nothing , _aslgPostalCodeRanges = Nothing , _aslgName = Nothing , _aslgPostalCodes = Nothing } -- | The CLDR territory code of the country in which this location group is. aslgCountry :: Lens' AccountShippingLocationGroup (Maybe Text) aslgCountry = lens _aslgCountry (\ s a -> s{_aslgCountry = a}) -- | A location ID (also called criteria ID) representing administrative -- areas, smaller country subdivisions (counties), or cities. aslgLocationIds :: Lens' AccountShippingLocationGroup [Int64] aslgLocationIds = lens _aslgLocationIds (\ s a -> s{_aslgLocationIds = a}) . _Default . _Coerce -- | A postal code range representing a city or a set of cities. aslgPostalCodeRanges :: Lens' AccountShippingLocationGroup [AccountShippingPostalCodeRange] aslgPostalCodeRanges = lens _aslgPostalCodeRanges (\ s a -> s{_aslgPostalCodeRanges = a}) . _Default . _Coerce -- | The name of the location group. aslgName :: Lens' AccountShippingLocationGroup (Maybe Text) aslgName = lens _aslgName (\ s a -> s{_aslgName = a}) -- | A postal code representing a city or a set of cities. - A single postal -- code (e.g., 12345) - A postal code prefix followed by a star (e.g., -- 1234*) aslgPostalCodes :: Lens' AccountShippingLocationGroup [Text] aslgPostalCodes = lens _aslgPostalCodes (\ s a -> s{_aslgPostalCodes = a}) . _Default . _Coerce instance FromJSON AccountShippingLocationGroup where parseJSON = withObject "AccountShippingLocationGroup" (\ o -> AccountShippingLocationGroup' <$> (o .:? "country") <*> (o .:? "locationIds" .!= mempty) <*> (o .:? "postalCodeRanges" .!= mempty) <*> (o .:? "name") <*> (o .:? "postalCodes" .!= mempty)) instance ToJSON AccountShippingLocationGroup where toJSON AccountShippingLocationGroup'{..} = object (catMaybes [("country" .=) <$> _aslgCountry, ("locationIds" .=) <$> _aslgLocationIds, ("postalCodeRanges" .=) <$> _aslgPostalCodeRanges, ("name" .=) <$> _aslgName, ("postalCodes" .=) <$> _aslgPostalCodes]) -- -- /See:/ 'accountStatusDataQualityIssue' smart constructor. data AccountStatusDataQualityIssue = AccountStatusDataQualityIssue' { _asdqiSubmittedValue :: !(Maybe Text) , _asdqiCountry :: !(Maybe Text) , _asdqiDisplayedValue :: !(Maybe Text) , _asdqiNumItems :: !(Maybe (Textual Word32)) , _asdqiSeverity :: !(Maybe Text) , _asdqiExampleItems :: !(Maybe [AccountStatusExampleItem]) , _asdqiLastChecked :: !(Maybe Text) , _asdqiId :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'AccountStatusDataQualityIssue' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'asdqiSubmittedValue' -- -- * 'asdqiCountry' -- -- * 'asdqiDisplayedValue' -- -- * 'asdqiNumItems' -- -- * 'asdqiSeverity' -- -- * 'asdqiExampleItems' -- -- * 'asdqiLastChecked' -- -- * 'asdqiId' accountStatusDataQualityIssue :: AccountStatusDataQualityIssue accountStatusDataQualityIssue = AccountStatusDataQualityIssue' { _asdqiSubmittedValue = Nothing , _asdqiCountry = Nothing , _asdqiDisplayedValue = Nothing , _asdqiNumItems = Nothing , _asdqiSeverity = Nothing , _asdqiExampleItems = Nothing , _asdqiLastChecked = Nothing , _asdqiId = Nothing } -- | Submitted value that causes the issue. asdqiSubmittedValue :: Lens' AccountStatusDataQualityIssue (Maybe Text) asdqiSubmittedValue = lens _asdqiSubmittedValue (\ s a -> s{_asdqiSubmittedValue = a}) -- | Country for which this issue is reported. asdqiCountry :: Lens' AccountStatusDataQualityIssue (Maybe Text) asdqiCountry = lens _asdqiCountry (\ s a -> s{_asdqiCountry = a}) -- | Actual value displayed on the landing page. asdqiDisplayedValue :: Lens' AccountStatusDataQualityIssue (Maybe Text) asdqiDisplayedValue = lens _asdqiDisplayedValue (\ s a -> s{_asdqiDisplayedValue = a}) -- | Number of items in the account found to have the said issue. asdqiNumItems :: Lens' AccountStatusDataQualityIssue (Maybe Word32) asdqiNumItems = lens _asdqiNumItems (\ s a -> s{_asdqiNumItems = a}) . mapping _Coerce -- | Severity of the problem. asdqiSeverity :: Lens' AccountStatusDataQualityIssue (Maybe Text) asdqiSeverity = lens _asdqiSeverity (\ s a -> s{_asdqiSeverity = a}) -- | Example items featuring the issue. asdqiExampleItems :: Lens' AccountStatusDataQualityIssue [AccountStatusExampleItem] asdqiExampleItems = lens _asdqiExampleItems (\ s a -> s{_asdqiExampleItems = a}) . _Default . _Coerce -- | Last time the account was checked for this issue. asdqiLastChecked :: Lens' AccountStatusDataQualityIssue (Maybe Text) asdqiLastChecked = lens _asdqiLastChecked (\ s a -> s{_asdqiLastChecked = a}) -- | Issue identifier. asdqiId :: Lens' AccountStatusDataQualityIssue (Maybe Text) asdqiId = lens _asdqiId (\ s a -> s{_asdqiId = a}) instance FromJSON AccountStatusDataQualityIssue where parseJSON = withObject "AccountStatusDataQualityIssue" (\ o -> AccountStatusDataQualityIssue' <$> (o .:? "submittedValue") <*> (o .:? "country") <*> (o .:? "displayedValue") <*> (o .:? "numItems") <*> (o .:? "severity") <*> (o .:? "exampleItems" .!= mempty) <*> (o .:? "lastChecked") <*> (o .:? "id")) instance ToJSON AccountStatusDataQualityIssue where toJSON AccountStatusDataQualityIssue'{..} = object (catMaybes [("submittedValue" .=) <$> _asdqiSubmittedValue, ("country" .=) <$> _asdqiCountry, ("displayedValue" .=) <$> _asdqiDisplayedValue, ("numItems" .=) <$> _asdqiNumItems, ("severity" .=) <$> _asdqiSeverity, ("exampleItems" .=) <$> _asdqiExampleItems, ("lastChecked" .=) <$> _asdqiLastChecked, ("id" .=) <$> _asdqiId]) -- -- /See:/ 'productShippingDimension' smart constructor. data ProductShippingDimension = ProductShippingDimension' { _psdValue :: !(Maybe (Textual Double)) , _psdUnit :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ProductShippingDimension' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'psdValue' -- -- * 'psdUnit' productShippingDimension :: ProductShippingDimension productShippingDimension = ProductShippingDimension' { _psdValue = Nothing , _psdUnit = Nothing } -- | The dimension of the product used to calculate the shipping cost of the -- item. psdValue :: Lens' ProductShippingDimension (Maybe Double) psdValue = lens _psdValue (\ s a -> s{_psdValue = a}) . mapping _Coerce -- | The unit of value. Acceptable values are: - \"cm\" - \"in\" psdUnit :: Lens' ProductShippingDimension (Maybe Text) psdUnit = lens _psdUnit (\ s a -> s{_psdUnit = a}) instance FromJSON ProductShippingDimension where parseJSON = withObject "ProductShippingDimension" (\ o -> ProductShippingDimension' <$> (o .:? "value") <*> (o .:? "unit")) instance ToJSON ProductShippingDimension where toJSON ProductShippingDimension'{..} = object (catMaybes [("value" .=) <$> _psdValue, ("unit" .=) <$> _psdUnit]) -- | A batch entry encoding a single non-batch datafeeds response. -- -- /See:/ 'datafeedsCustomBatchResponseEntry' smart constructor. data DatafeedsCustomBatchResponseEntry = DatafeedsCustomBatchResponseEntry' { _dcbrecDatafeed :: !(Maybe Datafeed) , _dcbrecErrors :: !(Maybe Errors) , _dcbrecBatchId :: !(Maybe (Textual Word32)) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'DatafeedsCustomBatchResponseEntry' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dcbrecDatafeed' -- -- * 'dcbrecErrors' -- -- * 'dcbrecBatchId' datafeedsCustomBatchResponseEntry :: DatafeedsCustomBatchResponseEntry datafeedsCustomBatchResponseEntry = DatafeedsCustomBatchResponseEntry' { _dcbrecDatafeed = Nothing , _dcbrecErrors = Nothing , _dcbrecBatchId = Nothing } -- | The requested data feed. Defined if and only if the request was -- successful. dcbrecDatafeed :: Lens' DatafeedsCustomBatchResponseEntry (Maybe Datafeed) dcbrecDatafeed = lens _dcbrecDatafeed (\ s a -> s{_dcbrecDatafeed = a}) -- | A list of errors defined if and only if the request failed. dcbrecErrors :: Lens' DatafeedsCustomBatchResponseEntry (Maybe Errors) dcbrecErrors = lens _dcbrecErrors (\ s a -> s{_dcbrecErrors = a}) -- | The ID of the request entry this entry responds to. dcbrecBatchId :: Lens' DatafeedsCustomBatchResponseEntry (Maybe Word32) dcbrecBatchId = lens _dcbrecBatchId (\ s a -> s{_dcbrecBatchId = a}) . mapping _Coerce instance FromJSON DatafeedsCustomBatchResponseEntry where parseJSON = withObject "DatafeedsCustomBatchResponseEntry" (\ o -> DatafeedsCustomBatchResponseEntry' <$> (o .:? "datafeed") <*> (o .:? "errors") <*> (o .:? "batchId")) instance ToJSON DatafeedsCustomBatchResponseEntry where toJSON DatafeedsCustomBatchResponseEntry'{..} = object (catMaybes [("datafeed" .=) <$> _dcbrecDatafeed, ("errors" .=) <$> _dcbrecErrors, ("batchId" .=) <$> _dcbrecBatchId]) -- -- /See:/ 'ordersCustomBatchRequestEntryRefund' smart constructor. data OrdersCustomBatchRequestEntryRefund = OrdersCustomBatchRequestEntryRefund' { _ocbrerAmount :: !(Maybe Price) , _ocbrerReason :: !(Maybe Text) , _ocbrerReasonText :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'OrdersCustomBatchRequestEntryRefund' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ocbrerAmount' -- -- * 'ocbrerReason' -- -- * 'ocbrerReasonText' ordersCustomBatchRequestEntryRefund :: OrdersCustomBatchRequestEntryRefund ordersCustomBatchRequestEntryRefund = OrdersCustomBatchRequestEntryRefund' { _ocbrerAmount = Nothing , _ocbrerReason = Nothing , _ocbrerReasonText = Nothing } -- | The amount that is refunded. ocbrerAmount :: Lens' OrdersCustomBatchRequestEntryRefund (Maybe Price) ocbrerAmount = lens _ocbrerAmount (\ s a -> s{_ocbrerAmount = a}) -- | The reason for the refund. ocbrerReason :: Lens' OrdersCustomBatchRequestEntryRefund (Maybe Text) ocbrerReason = lens _ocbrerReason (\ s a -> s{_ocbrerReason = a}) -- | The explanation of the reason. ocbrerReasonText :: Lens' OrdersCustomBatchRequestEntryRefund (Maybe Text) ocbrerReasonText = lens _ocbrerReasonText (\ s a -> s{_ocbrerReasonText = a}) instance FromJSON OrdersCustomBatchRequestEntryRefund where parseJSON = withObject "OrdersCustomBatchRequestEntryRefund" (\ o -> OrdersCustomBatchRequestEntryRefund' <$> (o .:? "amount") <*> (o .:? "reason") <*> (o .:? "reasonText")) instance ToJSON OrdersCustomBatchRequestEntryRefund where toJSON OrdersCustomBatchRequestEntryRefund'{..} = object (catMaybes [("amount" .=) <$> _ocbrerAmount, ("reason" .=) <$> _ocbrerReason, ("reasonText" .=) <$> _ocbrerReasonText]) -- -- /See:/ 'datafeedstatusesListResponse' smart constructor. data DatafeedstatusesListResponse = DatafeedstatusesListResponse' { _dlrlNextPageToken :: !(Maybe Text) , _dlrlKind :: !Text , _dlrlResources :: !(Maybe [DatafeedStatus]) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'DatafeedstatusesListResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dlrlNextPageToken' -- -- * 'dlrlKind' -- -- * 'dlrlResources' datafeedstatusesListResponse :: DatafeedstatusesListResponse datafeedstatusesListResponse = DatafeedstatusesListResponse' { _dlrlNextPageToken = Nothing , _dlrlKind = "content#datafeedstatusesListResponse" , _dlrlResources = Nothing } -- | The token for the retrieval of the next page of datafeed statuses. dlrlNextPageToken :: Lens' DatafeedstatusesListResponse (Maybe Text) dlrlNextPageToken = lens _dlrlNextPageToken (\ s a -> s{_dlrlNextPageToken = a}) -- | Identifies what kind of resource this is. Value: the fixed string -- \"content#datafeedstatusesListResponse\". dlrlKind :: Lens' DatafeedstatusesListResponse Text dlrlKind = lens _dlrlKind (\ s a -> s{_dlrlKind = a}) dlrlResources :: Lens' DatafeedstatusesListResponse [DatafeedStatus] dlrlResources = lens _dlrlResources (\ s a -> s{_dlrlResources = a}) . _Default . _Coerce instance FromJSON DatafeedstatusesListResponse where parseJSON = withObject "DatafeedstatusesListResponse" (\ o -> DatafeedstatusesListResponse' <$> (o .:? "nextPageToken") <*> (o .:? "kind" .!= "content#datafeedstatusesListResponse") <*> (o .:? "resources" .!= mempty)) instance ToJSON DatafeedstatusesListResponse where toJSON DatafeedstatusesListResponse'{..} = object (catMaybes [("nextPageToken" .=) <$> _dlrlNextPageToken, Just ("kind" .= _dlrlKind), ("resources" .=) <$> _dlrlResources]) -- -- /See:/ 'productsListResponse' smart constructor. data ProductsListResponse = ProductsListResponse' { _plrlNextPageToken :: !(Maybe Text) , _plrlKind :: !Text , _plrlResources :: !(Maybe [Product]) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ProductsListResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'plrlNextPageToken' -- -- * 'plrlKind' -- -- * 'plrlResources' productsListResponse :: ProductsListResponse productsListResponse = ProductsListResponse' { _plrlNextPageToken = Nothing , _plrlKind = "content#productsListResponse" , _plrlResources = Nothing } -- | The token for the retrieval of the next page of products. plrlNextPageToken :: Lens' ProductsListResponse (Maybe Text) plrlNextPageToken = lens _plrlNextPageToken (\ s a -> s{_plrlNextPageToken = a}) -- | Identifies what kind of resource this is. Value: the fixed string -- \"content#productsListResponse\". plrlKind :: Lens' ProductsListResponse Text plrlKind = lens _plrlKind (\ s a -> s{_plrlKind = a}) plrlResources :: Lens' ProductsListResponse [Product] plrlResources = lens _plrlResources (\ s a -> s{_plrlResources = a}) . _Default . _Coerce instance FromJSON ProductsListResponse where parseJSON = withObject "ProductsListResponse" (\ o -> ProductsListResponse' <$> (o .:? "nextPageToken") <*> (o .:? "kind" .!= "content#productsListResponse") <*> (o .:? "resources" .!= mempty)) instance ToJSON ProductsListResponse where toJSON ProductsListResponse'{..} = object (catMaybes [("nextPageToken" .=) <$> _plrlNextPageToken, Just ("kind" .= _plrlKind), ("resources" .=) <$> _plrlResources]) -- -- /See:/ 'accountAdwordsLink' smart constructor. data AccountAdwordsLink = AccountAdwordsLink' { _aalStatus :: !(Maybe Text) , _aalAdwordsId :: !(Maybe (Textual Word64)) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'AccountAdwordsLink' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'aalStatus' -- -- * 'aalAdwordsId' accountAdwordsLink :: AccountAdwordsLink accountAdwordsLink = AccountAdwordsLink' { _aalStatus = Nothing , _aalAdwordsId = Nothing } -- | Status of the link between this Merchant Center account and the AdWords -- account. Upon retrieval, it represents the actual status of the link and -- can be either active if it was approved in Google AdWords or pending if -- it\'s pending approval. Upon insertion, it represents the intended -- status of the link. Re-uploading a link with status active when it\'s -- still pending or with status pending when it\'s already active will have -- no effect: the status will remain unchanged. Re-uploading a link with -- deprecated status inactive is equivalent to not submitting the link at -- all and will delete the link if it was active or cancel the link request -- if it was pending. aalStatus :: Lens' AccountAdwordsLink (Maybe Text) aalStatus = lens _aalStatus (\ s a -> s{_aalStatus = a}) -- | Customer ID of the AdWords account. aalAdwordsId :: Lens' AccountAdwordsLink (Maybe Word64) aalAdwordsId = lens _aalAdwordsId (\ s a -> s{_aalAdwordsId = a}) . mapping _Coerce instance FromJSON AccountAdwordsLink where parseJSON = withObject "AccountAdwordsLink" (\ o -> AccountAdwordsLink' <$> (o .:? "status") <*> (o .:? "adwordsId")) instance ToJSON AccountAdwordsLink where toJSON AccountAdwordsLink'{..} = object (catMaybes [("status" .=) <$> _aalStatus, ("adwordsId" .=) <$> _aalAdwordsId]) -- -- /See:/ 'orderCancellation' smart constructor. data OrderCancellation = OrderCancellation' { _ocQuantity :: !(Maybe (Textual Word32)) , _ocActor :: !(Maybe Text) , _ocReason :: !(Maybe Text) , _ocCreationDate :: !(Maybe Text) , _ocReasonText :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'OrderCancellation' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ocQuantity' -- -- * 'ocActor' -- -- * 'ocReason' -- -- * 'ocCreationDate' -- -- * 'ocReasonText' orderCancellation :: OrderCancellation orderCancellation = OrderCancellation' { _ocQuantity = Nothing , _ocActor = Nothing , _ocReason = Nothing , _ocCreationDate = Nothing , _ocReasonText = Nothing } -- | The quantity that was canceled. ocQuantity :: Lens' OrderCancellation (Maybe Word32) ocQuantity = lens _ocQuantity (\ s a -> s{_ocQuantity = a}) . mapping _Coerce -- | The actor that created the cancellation. ocActor :: Lens' OrderCancellation (Maybe Text) ocActor = lens _ocActor (\ s a -> s{_ocActor = a}) -- | The reason for the cancellation. Orders that are cancelled with a -- noInventory reason will lead to the removal of the product from POG -- until you make an update to that product. This will not affect your -- Shopping ads. ocReason :: Lens' OrderCancellation (Maybe Text) ocReason = lens _ocReason (\ s a -> s{_ocReason = a}) -- | Date on which the cancellation has been created, in ISO 8601 format. ocCreationDate :: Lens' OrderCancellation (Maybe Text) ocCreationDate = lens _ocCreationDate (\ s a -> s{_ocCreationDate = a}) -- | The explanation of the reason. ocReasonText :: Lens' OrderCancellation (Maybe Text) ocReasonText = lens _ocReasonText (\ s a -> s{_ocReasonText = a}) instance FromJSON OrderCancellation where parseJSON = withObject "OrderCancellation" (\ o -> OrderCancellation' <$> (o .:? "quantity") <*> (o .:? "actor") <*> (o .:? "reason") <*> (o .:? "creationDate") <*> (o .:? "reasonText")) instance ToJSON OrderCancellation where toJSON OrderCancellation'{..} = object (catMaybes [("quantity" .=) <$> _ocQuantity, ("actor" .=) <$> _ocActor, ("reason" .=) <$> _ocReason, ("creationDate" .=) <$> _ocCreationDate, ("reasonText" .=) <$> _ocReasonText]) -- -- /See:/ 'ordersCustomBatchResponse' smart constructor. data OrdersCustomBatchResponse = OrdersCustomBatchResponse' { _ordEntries :: !(Maybe [OrdersCustomBatchResponseEntry]) , _ordKind :: !Text } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'OrdersCustomBatchResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ordEntries' -- -- * 'ordKind' ordersCustomBatchResponse :: OrdersCustomBatchResponse ordersCustomBatchResponse = OrdersCustomBatchResponse' { _ordEntries = Nothing , _ordKind = "content#ordersCustomBatchResponse" } -- | The result of the execution of the batch requests. ordEntries :: Lens' OrdersCustomBatchResponse [OrdersCustomBatchResponseEntry] ordEntries = lens _ordEntries (\ s a -> s{_ordEntries = a}) . _Default . _Coerce -- | Identifies what kind of resource this is. Value: the fixed string -- \"content#ordersCustomBatchResponse\". ordKind :: Lens' OrdersCustomBatchResponse Text ordKind = lens _ordKind (\ s a -> s{_ordKind = a}) instance FromJSON OrdersCustomBatchResponse where parseJSON = withObject "OrdersCustomBatchResponse" (\ o -> OrdersCustomBatchResponse' <$> (o .:? "entries" .!= mempty) <*> (o .:? "kind" .!= "content#ordersCustomBatchResponse")) instance ToJSON OrdersCustomBatchResponse where toJSON OrdersCustomBatchResponse'{..} = object (catMaybes [("entries" .=) <$> _ordEntries, Just ("kind" .= _ordKind)])
rueshyna/gogol
gogol-shopping-content/gen/Network/Google/ShoppingContent/Types/Product.hs
mpl-2.0
443,650
0
82
111,082
84,246
48,248
35,998
9,527
1
module Common where import System.IO.Temp import System.Environment import DMSS.Config withTemporaryTestDirectory :: FilePath -> (FilePath -> IO a) -> IO a withTemporaryTestDirectory t f = withSystemTempDirectory t ( \s -> do -- Change HOME environment variable to temporary directory setEnv "HOME" s -- Create local home directory for DMSS createLocalDirectory -- Run test f s )
dmp1ce/DMSS
src-test/Common.hs
unlicense
410
0
10
85
89
47
42
9
1
module Identity where import Test.QuickCheck import Test.QuickCheck.Checkers import Test.QuickCheck.Classes newtype Identity a = Identity a deriving (Eq, Show) instance Functor Identity where fmap f (Identity a) = Identity (f a) instance Applicative Identity where pure = Identity Identity f <*> Identity a = Identity (f a) -- QuickCheck arbitrary instance Arbitrary a => Arbitrary (Identity a) where arbitrary = Identity <$> do arbitrary -- Required for checkers instance (Eq a) => EqProp (Identity a) where (=-=) = eq -- Use checkers to verify the Applicative and Functor for Identity are valid verifyIdentityIsFunctor :: IO () verifyIdentityIsFunctor = quickBatch $ functor (undefined :: Identity (Int,Int,Int)) verifyIdentityIsApplicative :: IO () verifyIdentityIsApplicative = quickBatch $ applicative (undefined :: Identity (Int,Int,Int))
dmp1ce/Haskell-Programming-Exercises
Chapter 17/ApplicativeInstances/src/Identity.hs
unlicense
858
0
9
130
259
140
119
16
1
{-# LANGUAGE GADTs #-} module TutorialD.Interpreter.TransactionGraphOperator where import TutorialD.Interpreter.Base import ProjectM36.TransactionGraph hiding (autoMergeToHead) import ProjectM36.Client as C import ProjectM36.Base import ProjectM36.Relation (relationTrue) import Data.Functor data ConvenienceTransactionGraphOperator = AutoMergeToHead MergeStrategy HeadName deriving (Show) convenienceTransactionGraphOpP :: Parser ConvenienceTransactionGraphOperator convenienceTransactionGraphOpP = autoMergeToHeadP autoMergeToHeadP :: Parser ConvenienceTransactionGraphOperator autoMergeToHeadP = do reserved ":automergetohead" AutoMergeToHead <$> mergeTransactionStrategyP <*> identifier jumpToHeadP :: Parser TransactionGraphOperator jumpToHeadP = do reservedOp ":jumphead" JumpToHead <$> identifier jumpToTransactionP :: Parser TransactionGraphOperator jumpToTransactionP = do reservedOp ":jump" JumpToTransaction <$> uuidP walkBackToTimeP :: Parser TransactionGraphOperator walkBackToTimeP = do reservedOp ":walkbacktotime" WalkBackToTime <$> utcTimeP branchTransactionP :: Parser TransactionGraphOperator branchTransactionP = do reservedOp ":branch" Branch <$> identifier deleteBranchP :: Parser TransactionGraphOperator deleteBranchP = do reserved ":deletebranch" DeleteBranch <$> identifier commitTransactionP :: Parser TransactionGraphOperator commitTransactionP = do reservedOp ":commit" pure Commit rollbackTransactionP :: Parser TransactionGraphOperator rollbackTransactionP = do reservedOp ":rollback" return Rollback showGraphP :: Parser ROTransactionGraphOperator showGraphP = do reservedOp ":showgraph" return ShowGraph mergeTransactionStrategyP :: Parser MergeStrategy mergeTransactionStrategyP = (reserved "union" $> UnionMergeStrategy) <|> (do reserved "selectedbranch" SelectedBranchMergeStrategy <$> identifier) <|> (do reserved "unionpreferbranch" UnionPreferMergeStrategy <$> identifier) mergeTransactionsP :: Parser TransactionGraphOperator mergeTransactionsP = do reservedOp ":mergetrans" MergeTransactions <$> mergeTransactionStrategyP <*> identifier <*> identifier validateMerkleHashesP :: Parser ROTransactionGraphOperator validateMerkleHashesP = reservedOp ":validatemerklehashes" $> ValidateMerkleHashes transactionGraphOpP :: Parser TransactionGraphOperator transactionGraphOpP = jumpToHeadP <|> jumpToTransactionP <|> walkBackToTimeP <|> branchTransactionP <|> deleteBranchP <|> commitTransactionP <|> rollbackTransactionP <|> mergeTransactionsP roTransactionGraphOpP :: Parser ROTransactionGraphOperator roTransactionGraphOpP = showGraphP <|> validateMerkleHashesP {- -- for interpreter-specific operations interpretOps :: U.UUID -> DisconnectedTransaction -> TransactionGraph -> String -> (DisconnectedTransaction, TransactionGraph, TutorialDOperatorResult) interpretOps newUUID trans@(DisconnectedTransaction _ context) transGraph instring = case parse interpreterOps "" instring of Left _ -> (trans, transGraph, NoActionResult) Right ops -> case ops of Left contextOp -> (trans, transGraph, (evalContextOp context contextOp)) Right graphOp -> case evalGraphOp newUUID trans transGraph graphOp of Left err -> (trans, transGraph, DisplayErrorResult $ T.pack (show err)) Right (newDiscon, newGraph, result) -> (newDiscon, newGraph, result) -} evalROGraphOp :: SessionId -> Connection -> ROTransactionGraphOperator -> IO (Either RelationalError Relation) evalROGraphOp sessionId conn ShowGraph = transactionGraphAsRelation sessionId conn evalROGraphOp sessionId conn ValidateMerkleHashes = do eVal <- C.validateMerkleHashes sessionId conn case eVal of Left err -> pure (Left err) Right _ -> pure (Right relationTrue) evalConvenienceGraphOp :: SessionId -> Connection -> ConvenienceTransactionGraphOperator -> IO (Either RelationalError ()) evalConvenienceGraphOp sessionId conn (AutoMergeToHead strat head') = autoMergeToHead sessionId conn strat head'
agentm/project-m36
src/bin/TutorialD/Interpreter/TransactionGraphOperator.hs
unlicense
4,234
0
12
725
667
327
340
83
2
{-# LANGUAGE OverloadedStrings #-} module Base64 where import qualified Data.ByteString.Base64.URL as B64 import qualified Data.ByteString.Char8 as C encode :: C.ByteString -> C.ByteString encode = unpad . B64.encode decode :: C.ByteString -> C.ByteString decode bs = either error id $ B64.decode $ pad bs pad :: C.ByteString -> C.ByteString pad bs | nPads /= 0 = C.append bs $ C.replicate (4 - nPads) '=' | otherwise = bs where nPads = C.length bs `mod` 4 unpad :: C.ByteString -> C.ByteString unpad = C.reverse . C.dropWhile (== '=') . C.reverse
alexandrelucchesi/pfec
jwt-min/src/Base64.hs
apache-2.0
575
0
9
115
207
112
95
15
1
module HelperSequences.A000005 (a000005) where import Helpers.Primes (primePowers) a000005 :: Integer -> Integer a000005 n = product $ map ((+1) . fromIntegral . snd) $ primePowers n
peterokagey/haskellOEIS
src/HelperSequences/A000005.hs
apache-2.0
184
0
11
27
67
37
30
4
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TemplateHaskell #-} {-# OPTIONS_GHC -Wall #-} {-| = Handling primitive Fortran values symbolically. There are a few challenges that this module attempts to solve: Fortran uses fixed-width machine integers and floating point reals. Sometimes we might want to reason about these directly (which is supported by SBV and therefore feasible). However, sometimes they get in the way of the logic and we just want to pretend that they're the pure mathematical values that they approximate. For example floating point addition obeys very few algebraic laws, so most theorems about real numbers don't hold at all for floating point numbers. In addition, Fortran's boolean values are actually arbitrary signed integers. If we treat all boolean values symbolically as bit-vectors, logic can become very slow; so it might be best to pretend that all booleans are single bits. However, sometimes we might want to verify properties that rely on the actual bit-vector representation of booleans. This module deals with these problems by abstracting over the choices: the user should be able to choose which representation they want to use for each primitive data type. The user provides a 'PrimReprSpec' which specifies how each data type should be treated. Some examples are provided: 'prsPrecise' treats all values precisely as they are represented in the Fortran program. This makes logic slow and makes it very difficult to prove many things, but it is most accurate. On the other hand, 'prsIdealized' treats all values as their idealized mathematical equivalents. This makes logic fast and lots intuitive properties can be proved easily. However, these properties often will not hold in actual running Fortran programs: sometimes in weird edge cases and sometimes in sensible-seeming executions. It would be interesting future work to provide an analysis that helps to determine which of the two applies to a particular program! -} module Language.Fortran.Model.Repr.Prim where import Data.Int (Int16, Int32, Int64, Int8) import Data.Word (Word8) import Control.Lens import Control.Monad.Reader (MonadReader (..)) import qualified Data.SBV as SBV import Data.SBV.Dynamic (SVal) import Data.SBV.Internals (SBV (..)) import Language.Fortran.Model.Types -------------------------------------------------------------------------------- -- * Types data IntRepr a = MachineInt | ArbitraryInt deriving (Eq, Ord, Show) data RealRepr a = MachineFloat | ArbitraryReal deriving (Eq, Ord, Show) data BoolRepr a = IntBool | BitBool deriving (Eq, Ord, Show) data PrimReprHandler a = PrimReprHandler { _prhKind :: !SBV.Kind , _prhLiteral :: !(a -> SVal) , _prhSymbolic :: !(String -> SBV.Symbolic SVal) } data PrimReprSpec = PrimReprSpec { _prsInt8Repr :: !(IntRepr Int8) , _prsInt16Repr :: !(IntRepr Int16) , _prsInt32Repr :: !(IntRepr Int32) , _prsInt64Repr :: !(IntRepr Int64) , _prsFloatRepr :: !(RealRepr Float) , _prsDoubleRepr :: !(RealRepr Double) , _prsBool8Repr :: !(BoolRepr Bool8) , _prsBool16Repr :: !(BoolRepr Bool16) , _prsBool32Repr :: !(BoolRepr Bool32) , _prsBool64Repr :: !(BoolRepr Bool64) } -------------------------------------------------------------------------------- -- ** Lenses makeLenses ''PrimReprHandler makeLenses ''PrimReprSpec -------------------------------------------------------------------------------- -- * Standard specs prsPrecise :: PrimReprSpec prsPrecise = PrimReprSpec { _prsInt8Repr = MachineInt , _prsInt16Repr = MachineInt , _prsInt32Repr = MachineInt , _prsInt64Repr = MachineInt , _prsFloatRepr = MachineFloat , _prsDoubleRepr = MachineFloat , _prsBool8Repr = IntBool , _prsBool16Repr = IntBool , _prsBool32Repr = IntBool , _prsBool64Repr = IntBool } prsIdealized :: PrimReprSpec prsIdealized = PrimReprSpec { _prsInt8Repr = ArbitraryInt , _prsInt16Repr = ArbitraryInt , _prsInt32Repr = ArbitraryInt , _prsInt64Repr = ArbitraryInt , _prsFloatRepr = ArbitraryReal , _prsDoubleRepr = ArbitraryReal , _prsBool8Repr = BitBool , _prsBool16Repr = BitBool , _prsBool32Repr = BitBool , _prsBool64Repr = BitBool } prsWithArbitraryInts :: Bool -> PrimReprSpec -> PrimReprSpec prsWithArbitraryInts useArbitrary | useArbitrary = set prsInt8Repr ArbitraryInt . set prsInt16Repr ArbitraryInt . set prsInt32Repr ArbitraryInt . set prsInt64Repr ArbitraryInt | otherwise = set prsInt8Repr MachineInt . set prsInt16Repr MachineInt . set prsInt32Repr MachineInt . set prsInt64Repr MachineInt prsWithArbitraryReals :: Bool -> PrimReprSpec -> PrimReprSpec prsWithArbitraryReals useArbitrary | useArbitrary = set prsFloatRepr ArbitraryReal . set prsDoubleRepr ArbitraryReal | otherwise = set prsFloatRepr MachineFloat . set prsDoubleRepr MachineFloat -------------------------------------------------------------------------------- -- * Using specs makeSymRepr :: PrimReprSpec -> Prim p k a -> PrimReprHandler a makeSymRepr spec = \case PInt8 -> intRepr prsInt8Repr PInt16 -> intRepr prsInt16Repr PInt32 -> intRepr prsInt32Repr PInt64 -> intRepr prsInt64Repr PFloat -> realRepr prsFloatRepr PDouble -> realRepr prsDoubleRepr PBool8 -> boolRepr getBool8 prsBool8Repr PBool16 -> boolRepr getBool16 prsBool16Repr PBool32 -> boolRepr getBool32 prsBool32Repr PBool64 -> boolRepr getBool64 prsBool64Repr PChar -> bySymWord (0 :: Word8) getChar8 where intRepr :: (Integral a, SBV.SymWord a) => Lens' PrimReprSpec (IntRepr a) -> PrimReprHandler a intRepr l = case spec ^. l of MachineInt -> bySymWord 0 id ArbitraryInt -> bySymWord (0 :: Integer) fromIntegral realRepr :: (RealFloat a, SBV.SymWord a) => Lens' PrimReprSpec (RealRepr a) -> PrimReprHandler a realRepr l = case spec ^. l of MachineFloat -> bySymWord 0 id ArbitraryReal -> bySymWord (0 :: SBV.AlgReal) realToFrac boolRepr :: (Integral b, SBV.SymWord b) => (a -> b) -> Lens' PrimReprSpec (BoolRepr a) -> PrimReprHandler a boolRepr unwrap l = case spec ^. l of IntBool -> bySymWord 0 unwrap BitBool -> bySymWord (False :: Bool) (toBool . unwrap) bySymWord :: (SBV.SymWord b) => b -> (a -> b) -> PrimReprHandler a bySymWord (repValue :: b) fromPrim = PrimReprHandler { _prhKind = SBV.kindOf repValue , _prhLiteral = unSBV . SBV.literal . fromPrim , _prhSymbolic = fmap (unSBV :: SBV b -> SVal) . SBV.symbolic } toBool :: (Ord a, Num a) => a -> Bool toBool x = x > 0 -------------------------------------------------------------------------------- -- * Monadic Accessors class HasPrimReprHandlers r where primReprHandlers :: r -> PrimReprHandlers primReprHandlers env = PrimReprHandlers (primReprHandler env) primReprHandler :: r -> Prim p k a -> PrimReprHandler a primReprHandler = unPrimReprHandlers . primReprHandlers newtype PrimReprHandlers = PrimReprHandlers { unPrimReprHandlers :: forall p k a. Prim p k a -> PrimReprHandler a } instance HasPrimReprHandlers PrimReprHandlers where primReprHandlers = id primSBVKind :: (MonadReader r m, HasPrimReprHandlers r) => Prim p k a -> m SBV.Kind primSBVKind p = view (to (flip primReprHandler p) . prhKind) primLit :: (MonadReader r m, HasPrimReprHandlers r) => Prim p k a -> a -> m SVal primLit p a = do lit <- view (to (flip primReprHandler p) . prhLiteral) return (lit a) primSymbolic :: (MonadReader r m, HasPrimReprHandlers r) => Prim p k a -> String -> m (SBV.Symbolic SVal) primSymbolic p nm = do symbolic <- view (to (flip primReprHandler p) . prhSymbolic) return (symbolic nm)
dorchard/camfort
src/Language/Fortran/Model/Repr/Prim.hs
apache-2.0
8,234
0
13
1,723
1,651
879
772
172
14
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QFocusFrame.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:25 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Gui.QFocusFrame ( QqFocusFrame(..) ,qFocusFrame_delete ,qFocusFrame_deleteLater ) where import Foreign.C.Types import Qth.ClassTypes.Core import Qtc.Enums.Base import Qtc.Enums.Gui.QPaintDevice import Qtc.Enums.Core.Qt import Qtc.Classes.Base import Qtc.Classes.Qccs import Qtc.Classes.Core import Qtc.ClassTypes.Core import Qth.ClassTypes.Core import Qtc.Classes.Gui import Qtc.ClassTypes.Gui instance QuserMethod (QFocusFrame ()) (()) (IO ()) where userMethod qobj evid () = withObjectPtr qobj $ \cobj_qobj -> qtc_QFocusFrame_userMethod cobj_qobj (toCInt evid) foreign import ccall "qtc_QFocusFrame_userMethod" qtc_QFocusFrame_userMethod :: Ptr (TQFocusFrame a) -> CInt -> IO () instance QuserMethod (QFocusFrameSc a) (()) (IO ()) where userMethod qobj evid () = withObjectPtr qobj $ \cobj_qobj -> qtc_QFocusFrame_userMethod cobj_qobj (toCInt evid) instance QuserMethod (QFocusFrame ()) (QVariant ()) (IO (QVariant ())) where userMethod qobj evid qvoj = withObjectRefResult $ withObjectPtr qobj $ \cobj_qobj -> withObjectPtr qvoj $ \cobj_qvoj -> qtc_QFocusFrame_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj foreign import ccall "qtc_QFocusFrame_userMethodVariant" qtc_QFocusFrame_userMethodVariant :: Ptr (TQFocusFrame a) -> CInt -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ())) instance QuserMethod (QFocusFrameSc a) (QVariant ()) (IO (QVariant ())) where userMethod qobj evid qvoj = withObjectRefResult $ withObjectPtr qobj $ \cobj_qobj -> withObjectPtr qvoj $ \cobj_qvoj -> qtc_QFocusFrame_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj class QqFocusFrame x1 where qFocusFrame :: x1 -> IO (QFocusFrame ()) instance QqFocusFrame (()) where qFocusFrame () = withQFocusFrameResult $ qtc_QFocusFrame foreign import ccall "qtc_QFocusFrame" qtc_QFocusFrame :: IO (Ptr (TQFocusFrame ())) instance QqFocusFrame ((QWidget t1)) where qFocusFrame (x1) = withQFocusFrameResult $ withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame1 cobj_x1 foreign import ccall "qtc_QFocusFrame1" qtc_QFocusFrame1 :: Ptr (TQWidget t1) -> IO (Ptr (TQFocusFrame ())) instance Qevent (QFocusFrame ()) ((QEvent t1)) where event x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_event_h cobj_x0 cobj_x1 foreign import ccall "qtc_QFocusFrame_event_h" qtc_QFocusFrame_event_h :: Ptr (TQFocusFrame a) -> Ptr (TQEvent t1) -> IO CBool instance Qevent (QFocusFrameSc a) ((QEvent t1)) where event x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_event_h cobj_x0 cobj_x1 instance QeventFilter (QFocusFrame ()) ((QObject t1, QEvent t2)) where eventFilter x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QFocusFrame_eventFilter cobj_x0 cobj_x1 cobj_x2 foreign import ccall "qtc_QFocusFrame_eventFilter" qtc_QFocusFrame_eventFilter :: Ptr (TQFocusFrame a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool instance QeventFilter (QFocusFrameSc a) ((QObject t1, QEvent t2)) where eventFilter x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QFocusFrame_eventFilter cobj_x0 cobj_x1 cobj_x2 instance QinitStyleOption (QFocusFrame ()) ((QStyleOption t1)) where initStyleOption x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_initStyleOption cobj_x0 cobj_x1 foreign import ccall "qtc_QFocusFrame_initStyleOption" qtc_QFocusFrame_initStyleOption :: Ptr (TQFocusFrame a) -> Ptr (TQStyleOption t1) -> IO () instance QinitStyleOption (QFocusFrameSc a) ((QStyleOption t1)) where initStyleOption x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_initStyleOption cobj_x0 cobj_x1 instance QpaintEvent (QFocusFrame ()) ((QPaintEvent t1)) where paintEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_paintEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QFocusFrame_paintEvent_h" qtc_QFocusFrame_paintEvent_h :: Ptr (TQFocusFrame a) -> Ptr (TQPaintEvent t1) -> IO () instance QpaintEvent (QFocusFrameSc a) ((QPaintEvent t1)) where paintEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_paintEvent_h cobj_x0 cobj_x1 instance QsetWidget (QFocusFrame a) ((QWidget t1)) where setWidget x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_setWidget cobj_x0 cobj_x1 foreign import ccall "qtc_QFocusFrame_setWidget" qtc_QFocusFrame_setWidget :: Ptr (TQFocusFrame a) -> Ptr (TQWidget t1) -> IO () instance Qwidget (QFocusFrame a) (()) where widget x0 () = withQWidgetResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFocusFrame_widget cobj_x0 foreign import ccall "qtc_QFocusFrame_widget" qtc_QFocusFrame_widget :: Ptr (TQFocusFrame a) -> IO (Ptr (TQWidget ())) qFocusFrame_delete :: QFocusFrame a -> IO () qFocusFrame_delete x0 = withObjectPtr x0 $ \cobj_x0 -> qtc_QFocusFrame_delete cobj_x0 foreign import ccall "qtc_QFocusFrame_delete" qtc_QFocusFrame_delete :: Ptr (TQFocusFrame a) -> IO () qFocusFrame_deleteLater :: QFocusFrame a -> IO () qFocusFrame_deleteLater x0 = withObjectPtr x0 $ \cobj_x0 -> qtc_QFocusFrame_deleteLater cobj_x0 foreign import ccall "qtc_QFocusFrame_deleteLater" qtc_QFocusFrame_deleteLater :: Ptr (TQFocusFrame a) -> IO () instance QactionEvent (QFocusFrame ()) ((QActionEvent t1)) where actionEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_actionEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QFocusFrame_actionEvent_h" qtc_QFocusFrame_actionEvent_h :: Ptr (TQFocusFrame a) -> Ptr (TQActionEvent t1) -> IO () instance QactionEvent (QFocusFrameSc a) ((QActionEvent t1)) where actionEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_actionEvent_h cobj_x0 cobj_x1 instance QaddAction (QFocusFrame ()) ((QAction t1)) (IO ()) where addAction x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_addAction cobj_x0 cobj_x1 foreign import ccall "qtc_QFocusFrame_addAction" qtc_QFocusFrame_addAction :: Ptr (TQFocusFrame a) -> Ptr (TQAction t1) -> IO () instance QaddAction (QFocusFrameSc a) ((QAction t1)) (IO ()) where addAction x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_addAction cobj_x0 cobj_x1 instance QchangeEvent (QFocusFrame ()) ((QEvent t1)) where changeEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_changeEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QFocusFrame_changeEvent_h" qtc_QFocusFrame_changeEvent_h :: Ptr (TQFocusFrame a) -> Ptr (TQEvent t1) -> IO () instance QchangeEvent (QFocusFrameSc a) ((QEvent t1)) where changeEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_changeEvent_h cobj_x0 cobj_x1 instance QcloseEvent (QFocusFrame ()) ((QCloseEvent t1)) where closeEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_closeEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QFocusFrame_closeEvent_h" qtc_QFocusFrame_closeEvent_h :: Ptr (TQFocusFrame a) -> Ptr (TQCloseEvent t1) -> IO () instance QcloseEvent (QFocusFrameSc a) ((QCloseEvent t1)) where closeEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_closeEvent_h cobj_x0 cobj_x1 instance QcontextMenuEvent (QFocusFrame ()) ((QContextMenuEvent t1)) where contextMenuEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_contextMenuEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QFocusFrame_contextMenuEvent_h" qtc_QFocusFrame_contextMenuEvent_h :: Ptr (TQFocusFrame a) -> Ptr (TQContextMenuEvent t1) -> IO () instance QcontextMenuEvent (QFocusFrameSc a) ((QContextMenuEvent t1)) where contextMenuEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_contextMenuEvent_h cobj_x0 cobj_x1 instance Qcreate (QFocusFrame ()) (()) (IO ()) where create x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QFocusFrame_create cobj_x0 foreign import ccall "qtc_QFocusFrame_create" qtc_QFocusFrame_create :: Ptr (TQFocusFrame a) -> IO () instance Qcreate (QFocusFrameSc a) (()) (IO ()) where create x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QFocusFrame_create cobj_x0 instance Qcreate (QFocusFrame ()) ((QVoid t1)) (IO ()) where create x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_create1 cobj_x0 cobj_x1 foreign import ccall "qtc_QFocusFrame_create1" qtc_QFocusFrame_create1 :: Ptr (TQFocusFrame a) -> Ptr (TQVoid t1) -> IO () instance Qcreate (QFocusFrameSc a) ((QVoid t1)) (IO ()) where create x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_create1 cobj_x0 cobj_x1 instance Qcreate (QFocusFrame ()) ((QVoid t1, Bool)) (IO ()) where create x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_create2 cobj_x0 cobj_x1 (toCBool x2) foreign import ccall "qtc_QFocusFrame_create2" qtc_QFocusFrame_create2 :: Ptr (TQFocusFrame a) -> Ptr (TQVoid t1) -> CBool -> IO () instance Qcreate (QFocusFrameSc a) ((QVoid t1, Bool)) (IO ()) where create x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_create2 cobj_x0 cobj_x1 (toCBool x2) instance Qcreate (QFocusFrame ()) ((QVoid t1, Bool, Bool)) (IO ()) where create x0 (x1, x2, x3) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_create3 cobj_x0 cobj_x1 (toCBool x2) (toCBool x3) foreign import ccall "qtc_QFocusFrame_create3" qtc_QFocusFrame_create3 :: Ptr (TQFocusFrame a) -> Ptr (TQVoid t1) -> CBool -> CBool -> IO () instance Qcreate (QFocusFrameSc a) ((QVoid t1, Bool, Bool)) (IO ()) where create x0 (x1, x2, x3) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_create3 cobj_x0 cobj_x1 (toCBool x2) (toCBool x3) instance Qdestroy (QFocusFrame ()) (()) where destroy x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QFocusFrame_destroy cobj_x0 foreign import ccall "qtc_QFocusFrame_destroy" qtc_QFocusFrame_destroy :: Ptr (TQFocusFrame a) -> IO () instance Qdestroy (QFocusFrameSc a) (()) where destroy x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QFocusFrame_destroy cobj_x0 instance Qdestroy (QFocusFrame ()) ((Bool)) where destroy x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QFocusFrame_destroy1 cobj_x0 (toCBool x1) foreign import ccall "qtc_QFocusFrame_destroy1" qtc_QFocusFrame_destroy1 :: Ptr (TQFocusFrame a) -> CBool -> IO () instance Qdestroy (QFocusFrameSc a) ((Bool)) where destroy x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QFocusFrame_destroy1 cobj_x0 (toCBool x1) instance Qdestroy (QFocusFrame ()) ((Bool, Bool)) where destroy x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QFocusFrame_destroy2 cobj_x0 (toCBool x1) (toCBool x2) foreign import ccall "qtc_QFocusFrame_destroy2" qtc_QFocusFrame_destroy2 :: Ptr (TQFocusFrame a) -> CBool -> CBool -> IO () instance Qdestroy (QFocusFrameSc a) ((Bool, Bool)) where destroy x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QFocusFrame_destroy2 cobj_x0 (toCBool x1) (toCBool x2) instance QdevType (QFocusFrame ()) (()) where devType x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFocusFrame_devType_h cobj_x0 foreign import ccall "qtc_QFocusFrame_devType_h" qtc_QFocusFrame_devType_h :: Ptr (TQFocusFrame a) -> IO CInt instance QdevType (QFocusFrameSc a) (()) where devType x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFocusFrame_devType_h cobj_x0 instance QdragEnterEvent (QFocusFrame ()) ((QDragEnterEvent t1)) where dragEnterEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_dragEnterEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QFocusFrame_dragEnterEvent_h" qtc_QFocusFrame_dragEnterEvent_h :: Ptr (TQFocusFrame a) -> Ptr (TQDragEnterEvent t1) -> IO () instance QdragEnterEvent (QFocusFrameSc a) ((QDragEnterEvent t1)) where dragEnterEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_dragEnterEvent_h cobj_x0 cobj_x1 instance QdragLeaveEvent (QFocusFrame ()) ((QDragLeaveEvent t1)) where dragLeaveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_dragLeaveEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QFocusFrame_dragLeaveEvent_h" qtc_QFocusFrame_dragLeaveEvent_h :: Ptr (TQFocusFrame a) -> Ptr (TQDragLeaveEvent t1) -> IO () instance QdragLeaveEvent (QFocusFrameSc a) ((QDragLeaveEvent t1)) where dragLeaveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_dragLeaveEvent_h cobj_x0 cobj_x1 instance QdragMoveEvent (QFocusFrame ()) ((QDragMoveEvent t1)) where dragMoveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_dragMoveEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QFocusFrame_dragMoveEvent_h" qtc_QFocusFrame_dragMoveEvent_h :: Ptr (TQFocusFrame a) -> Ptr (TQDragMoveEvent t1) -> IO () instance QdragMoveEvent (QFocusFrameSc a) ((QDragMoveEvent t1)) where dragMoveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_dragMoveEvent_h cobj_x0 cobj_x1 instance QdropEvent (QFocusFrame ()) ((QDropEvent t1)) where dropEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_dropEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QFocusFrame_dropEvent_h" qtc_QFocusFrame_dropEvent_h :: Ptr (TQFocusFrame a) -> Ptr (TQDropEvent t1) -> IO () instance QdropEvent (QFocusFrameSc a) ((QDropEvent t1)) where dropEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_dropEvent_h cobj_x0 cobj_x1 instance QenabledChange (QFocusFrame ()) ((Bool)) where enabledChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QFocusFrame_enabledChange cobj_x0 (toCBool x1) foreign import ccall "qtc_QFocusFrame_enabledChange" qtc_QFocusFrame_enabledChange :: Ptr (TQFocusFrame a) -> CBool -> IO () instance QenabledChange (QFocusFrameSc a) ((Bool)) where enabledChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QFocusFrame_enabledChange cobj_x0 (toCBool x1) instance QenterEvent (QFocusFrame ()) ((QEvent t1)) where enterEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_enterEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QFocusFrame_enterEvent_h" qtc_QFocusFrame_enterEvent_h :: Ptr (TQFocusFrame a) -> Ptr (TQEvent t1) -> IO () instance QenterEvent (QFocusFrameSc a) ((QEvent t1)) where enterEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_enterEvent_h cobj_x0 cobj_x1 instance QfocusInEvent (QFocusFrame ()) ((QFocusEvent t1)) where focusInEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_focusInEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QFocusFrame_focusInEvent_h" qtc_QFocusFrame_focusInEvent_h :: Ptr (TQFocusFrame a) -> Ptr (TQFocusEvent t1) -> IO () instance QfocusInEvent (QFocusFrameSc a) ((QFocusEvent t1)) where focusInEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_focusInEvent_h cobj_x0 cobj_x1 instance QfocusNextChild (QFocusFrame ()) (()) where focusNextChild x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFocusFrame_focusNextChild cobj_x0 foreign import ccall "qtc_QFocusFrame_focusNextChild" qtc_QFocusFrame_focusNextChild :: Ptr (TQFocusFrame a) -> IO CBool instance QfocusNextChild (QFocusFrameSc a) (()) where focusNextChild x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFocusFrame_focusNextChild cobj_x0 instance QfocusNextPrevChild (QFocusFrame ()) ((Bool)) where focusNextPrevChild x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFocusFrame_focusNextPrevChild cobj_x0 (toCBool x1) foreign import ccall "qtc_QFocusFrame_focusNextPrevChild" qtc_QFocusFrame_focusNextPrevChild :: Ptr (TQFocusFrame a) -> CBool -> IO CBool instance QfocusNextPrevChild (QFocusFrameSc a) ((Bool)) where focusNextPrevChild x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFocusFrame_focusNextPrevChild cobj_x0 (toCBool x1) instance QfocusOutEvent (QFocusFrame ()) ((QFocusEvent t1)) where focusOutEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_focusOutEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QFocusFrame_focusOutEvent_h" qtc_QFocusFrame_focusOutEvent_h :: Ptr (TQFocusFrame a) -> Ptr (TQFocusEvent t1) -> IO () instance QfocusOutEvent (QFocusFrameSc a) ((QFocusEvent t1)) where focusOutEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_focusOutEvent_h cobj_x0 cobj_x1 instance QfocusPreviousChild (QFocusFrame ()) (()) where focusPreviousChild x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFocusFrame_focusPreviousChild cobj_x0 foreign import ccall "qtc_QFocusFrame_focusPreviousChild" qtc_QFocusFrame_focusPreviousChild :: Ptr (TQFocusFrame a) -> IO CBool instance QfocusPreviousChild (QFocusFrameSc a) (()) where focusPreviousChild x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFocusFrame_focusPreviousChild cobj_x0 instance QfontChange (QFocusFrame ()) ((QFont t1)) where fontChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_fontChange cobj_x0 cobj_x1 foreign import ccall "qtc_QFocusFrame_fontChange" qtc_QFocusFrame_fontChange :: Ptr (TQFocusFrame a) -> Ptr (TQFont t1) -> IO () instance QfontChange (QFocusFrameSc a) ((QFont t1)) where fontChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_fontChange cobj_x0 cobj_x1 instance QheightForWidth (QFocusFrame ()) ((Int)) where heightForWidth x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFocusFrame_heightForWidth_h cobj_x0 (toCInt x1) foreign import ccall "qtc_QFocusFrame_heightForWidth_h" qtc_QFocusFrame_heightForWidth_h :: Ptr (TQFocusFrame a) -> CInt -> IO CInt instance QheightForWidth (QFocusFrameSc a) ((Int)) where heightForWidth x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFocusFrame_heightForWidth_h cobj_x0 (toCInt x1) instance QhideEvent (QFocusFrame ()) ((QHideEvent t1)) where hideEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_hideEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QFocusFrame_hideEvent_h" qtc_QFocusFrame_hideEvent_h :: Ptr (TQFocusFrame a) -> Ptr (TQHideEvent t1) -> IO () instance QhideEvent (QFocusFrameSc a) ((QHideEvent t1)) where hideEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_hideEvent_h cobj_x0 cobj_x1 instance QinputMethodEvent (QFocusFrame ()) ((QInputMethodEvent t1)) where inputMethodEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_inputMethodEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QFocusFrame_inputMethodEvent" qtc_QFocusFrame_inputMethodEvent :: Ptr (TQFocusFrame a) -> Ptr (TQInputMethodEvent t1) -> IO () instance QinputMethodEvent (QFocusFrameSc a) ((QInputMethodEvent t1)) where inputMethodEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_inputMethodEvent cobj_x0 cobj_x1 instance QinputMethodQuery (QFocusFrame ()) ((InputMethodQuery)) where inputMethodQuery x0 (x1) = withQVariantResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFocusFrame_inputMethodQuery_h cobj_x0 (toCLong $ qEnum_toInt x1) foreign import ccall "qtc_QFocusFrame_inputMethodQuery_h" qtc_QFocusFrame_inputMethodQuery_h :: Ptr (TQFocusFrame a) -> CLong -> IO (Ptr (TQVariant ())) instance QinputMethodQuery (QFocusFrameSc a) ((InputMethodQuery)) where inputMethodQuery x0 (x1) = withQVariantResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFocusFrame_inputMethodQuery_h cobj_x0 (toCLong $ qEnum_toInt x1) instance QkeyPressEvent (QFocusFrame ()) ((QKeyEvent t1)) where keyPressEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_keyPressEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QFocusFrame_keyPressEvent_h" qtc_QFocusFrame_keyPressEvent_h :: Ptr (TQFocusFrame a) -> Ptr (TQKeyEvent t1) -> IO () instance QkeyPressEvent (QFocusFrameSc a) ((QKeyEvent t1)) where keyPressEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_keyPressEvent_h cobj_x0 cobj_x1 instance QkeyReleaseEvent (QFocusFrame ()) ((QKeyEvent t1)) where keyReleaseEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_keyReleaseEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QFocusFrame_keyReleaseEvent_h" qtc_QFocusFrame_keyReleaseEvent_h :: Ptr (TQFocusFrame a) -> Ptr (TQKeyEvent t1) -> IO () instance QkeyReleaseEvent (QFocusFrameSc a) ((QKeyEvent t1)) where keyReleaseEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_keyReleaseEvent_h cobj_x0 cobj_x1 instance QlanguageChange (QFocusFrame ()) (()) where languageChange x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QFocusFrame_languageChange cobj_x0 foreign import ccall "qtc_QFocusFrame_languageChange" qtc_QFocusFrame_languageChange :: Ptr (TQFocusFrame a) -> IO () instance QlanguageChange (QFocusFrameSc a) (()) where languageChange x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QFocusFrame_languageChange cobj_x0 instance QleaveEvent (QFocusFrame ()) ((QEvent t1)) where leaveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_leaveEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QFocusFrame_leaveEvent_h" qtc_QFocusFrame_leaveEvent_h :: Ptr (TQFocusFrame a) -> Ptr (TQEvent t1) -> IO () instance QleaveEvent (QFocusFrameSc a) ((QEvent t1)) where leaveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_leaveEvent_h cobj_x0 cobj_x1 instance Qmetric (QFocusFrame ()) ((PaintDeviceMetric)) where metric x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFocusFrame_metric cobj_x0 (toCLong $ qEnum_toInt x1) foreign import ccall "qtc_QFocusFrame_metric" qtc_QFocusFrame_metric :: Ptr (TQFocusFrame a) -> CLong -> IO CInt instance Qmetric (QFocusFrameSc a) ((PaintDeviceMetric)) where metric x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFocusFrame_metric cobj_x0 (toCLong $ qEnum_toInt x1) instance QqminimumSizeHint (QFocusFrame ()) (()) where qminimumSizeHint x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFocusFrame_minimumSizeHint_h cobj_x0 foreign import ccall "qtc_QFocusFrame_minimumSizeHint_h" qtc_QFocusFrame_minimumSizeHint_h :: Ptr (TQFocusFrame a) -> IO (Ptr (TQSize ())) instance QqminimumSizeHint (QFocusFrameSc a) (()) where qminimumSizeHint x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFocusFrame_minimumSizeHint_h cobj_x0 instance QminimumSizeHint (QFocusFrame ()) (()) where minimumSizeHint x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QFocusFrame_minimumSizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h foreign import ccall "qtc_QFocusFrame_minimumSizeHint_qth_h" qtc_QFocusFrame_minimumSizeHint_qth_h :: Ptr (TQFocusFrame a) -> Ptr CInt -> Ptr CInt -> IO () instance QminimumSizeHint (QFocusFrameSc a) (()) where minimumSizeHint x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QFocusFrame_minimumSizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h instance QmouseDoubleClickEvent (QFocusFrame ()) ((QMouseEvent t1)) where mouseDoubleClickEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_mouseDoubleClickEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QFocusFrame_mouseDoubleClickEvent_h" qtc_QFocusFrame_mouseDoubleClickEvent_h :: Ptr (TQFocusFrame a) -> Ptr (TQMouseEvent t1) -> IO () instance QmouseDoubleClickEvent (QFocusFrameSc a) ((QMouseEvent t1)) where mouseDoubleClickEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_mouseDoubleClickEvent_h cobj_x0 cobj_x1 instance QmouseMoveEvent (QFocusFrame ()) ((QMouseEvent t1)) where mouseMoveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_mouseMoveEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QFocusFrame_mouseMoveEvent_h" qtc_QFocusFrame_mouseMoveEvent_h :: Ptr (TQFocusFrame a) -> Ptr (TQMouseEvent t1) -> IO () instance QmouseMoveEvent (QFocusFrameSc a) ((QMouseEvent t1)) where mouseMoveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_mouseMoveEvent_h cobj_x0 cobj_x1 instance QmousePressEvent (QFocusFrame ()) ((QMouseEvent t1)) where mousePressEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_mousePressEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QFocusFrame_mousePressEvent_h" qtc_QFocusFrame_mousePressEvent_h :: Ptr (TQFocusFrame a) -> Ptr (TQMouseEvent t1) -> IO () instance QmousePressEvent (QFocusFrameSc a) ((QMouseEvent t1)) where mousePressEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_mousePressEvent_h cobj_x0 cobj_x1 instance QmouseReleaseEvent (QFocusFrame ()) ((QMouseEvent t1)) where mouseReleaseEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_mouseReleaseEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QFocusFrame_mouseReleaseEvent_h" qtc_QFocusFrame_mouseReleaseEvent_h :: Ptr (TQFocusFrame a) -> Ptr (TQMouseEvent t1) -> IO () instance QmouseReleaseEvent (QFocusFrameSc a) ((QMouseEvent t1)) where mouseReleaseEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_mouseReleaseEvent_h cobj_x0 cobj_x1 instance Qmove (QFocusFrame ()) ((Int, Int)) where move x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QFocusFrame_move1 cobj_x0 (toCInt x1) (toCInt x2) foreign import ccall "qtc_QFocusFrame_move1" qtc_QFocusFrame_move1 :: Ptr (TQFocusFrame a) -> CInt -> CInt -> IO () instance Qmove (QFocusFrameSc a) ((Int, Int)) where move x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QFocusFrame_move1 cobj_x0 (toCInt x1) (toCInt x2) instance Qmove (QFocusFrame ()) ((Point)) where move x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCPoint x1 $ \cpoint_x1_x cpoint_x1_y -> qtc_QFocusFrame_move_qth cobj_x0 cpoint_x1_x cpoint_x1_y foreign import ccall "qtc_QFocusFrame_move_qth" qtc_QFocusFrame_move_qth :: Ptr (TQFocusFrame a) -> CInt -> CInt -> IO () instance Qmove (QFocusFrameSc a) ((Point)) where move x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCPoint x1 $ \cpoint_x1_x cpoint_x1_y -> qtc_QFocusFrame_move_qth cobj_x0 cpoint_x1_x cpoint_x1_y instance Qqmove (QFocusFrame ()) ((QPoint t1)) where qmove x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_move cobj_x0 cobj_x1 foreign import ccall "qtc_QFocusFrame_move" qtc_QFocusFrame_move :: Ptr (TQFocusFrame a) -> Ptr (TQPoint t1) -> IO () instance Qqmove (QFocusFrameSc a) ((QPoint t1)) where qmove x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_move cobj_x0 cobj_x1 instance QmoveEvent (QFocusFrame ()) ((QMoveEvent t1)) where moveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_moveEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QFocusFrame_moveEvent_h" qtc_QFocusFrame_moveEvent_h :: Ptr (TQFocusFrame a) -> Ptr (TQMoveEvent t1) -> IO () instance QmoveEvent (QFocusFrameSc a) ((QMoveEvent t1)) where moveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_moveEvent_h cobj_x0 cobj_x1 instance QpaintEngine (QFocusFrame ()) (()) where paintEngine x0 () = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFocusFrame_paintEngine_h cobj_x0 foreign import ccall "qtc_QFocusFrame_paintEngine_h" qtc_QFocusFrame_paintEngine_h :: Ptr (TQFocusFrame a) -> IO (Ptr (TQPaintEngine ())) instance QpaintEngine (QFocusFrameSc a) (()) where paintEngine x0 () = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFocusFrame_paintEngine_h cobj_x0 instance QpaletteChange (QFocusFrame ()) ((QPalette t1)) where paletteChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_paletteChange cobj_x0 cobj_x1 foreign import ccall "qtc_QFocusFrame_paletteChange" qtc_QFocusFrame_paletteChange :: Ptr (TQFocusFrame a) -> Ptr (TQPalette t1) -> IO () instance QpaletteChange (QFocusFrameSc a) ((QPalette t1)) where paletteChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_paletteChange cobj_x0 cobj_x1 instance Qrepaint (QFocusFrame ()) (()) where repaint x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QFocusFrame_repaint cobj_x0 foreign import ccall "qtc_QFocusFrame_repaint" qtc_QFocusFrame_repaint :: Ptr (TQFocusFrame a) -> IO () instance Qrepaint (QFocusFrameSc a) (()) where repaint x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QFocusFrame_repaint cobj_x0 instance Qrepaint (QFocusFrame ()) ((Int, Int, Int, Int)) where repaint x0 (x1, x2, x3, x4) = withObjectPtr x0 $ \cobj_x0 -> qtc_QFocusFrame_repaint2 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4) foreign import ccall "qtc_QFocusFrame_repaint2" qtc_QFocusFrame_repaint2 :: Ptr (TQFocusFrame a) -> CInt -> CInt -> CInt -> CInt -> IO () instance Qrepaint (QFocusFrameSc a) ((Int, Int, Int, Int)) where repaint x0 (x1, x2, x3, x4) = withObjectPtr x0 $ \cobj_x0 -> qtc_QFocusFrame_repaint2 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4) instance Qrepaint (QFocusFrame ()) ((QRegion t1)) where repaint x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_repaint1 cobj_x0 cobj_x1 foreign import ccall "qtc_QFocusFrame_repaint1" qtc_QFocusFrame_repaint1 :: Ptr (TQFocusFrame a) -> Ptr (TQRegion t1) -> IO () instance Qrepaint (QFocusFrameSc a) ((QRegion t1)) where repaint x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_repaint1 cobj_x0 cobj_x1 instance QresetInputContext (QFocusFrame ()) (()) where resetInputContext x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QFocusFrame_resetInputContext cobj_x0 foreign import ccall "qtc_QFocusFrame_resetInputContext" qtc_QFocusFrame_resetInputContext :: Ptr (TQFocusFrame a) -> IO () instance QresetInputContext (QFocusFrameSc a) (()) where resetInputContext x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QFocusFrame_resetInputContext cobj_x0 instance Qresize (QFocusFrame ()) ((Int, Int)) (IO ()) where resize x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QFocusFrame_resize1 cobj_x0 (toCInt x1) (toCInt x2) foreign import ccall "qtc_QFocusFrame_resize1" qtc_QFocusFrame_resize1 :: Ptr (TQFocusFrame a) -> CInt -> CInt -> IO () instance Qresize (QFocusFrameSc a) ((Int, Int)) (IO ()) where resize x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QFocusFrame_resize1 cobj_x0 (toCInt x1) (toCInt x2) instance Qqresize (QFocusFrame ()) ((QSize t1)) where qresize x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_resize cobj_x0 cobj_x1 foreign import ccall "qtc_QFocusFrame_resize" qtc_QFocusFrame_resize :: Ptr (TQFocusFrame a) -> Ptr (TQSize t1) -> IO () instance Qqresize (QFocusFrameSc a) ((QSize t1)) where qresize x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_resize cobj_x0 cobj_x1 instance Qresize (QFocusFrame ()) ((Size)) (IO ()) where resize x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCSize x1 $ \csize_x1_w csize_x1_h -> qtc_QFocusFrame_resize_qth cobj_x0 csize_x1_w csize_x1_h foreign import ccall "qtc_QFocusFrame_resize_qth" qtc_QFocusFrame_resize_qth :: Ptr (TQFocusFrame a) -> CInt -> CInt -> IO () instance Qresize (QFocusFrameSc a) ((Size)) (IO ()) where resize x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCSize x1 $ \csize_x1_w csize_x1_h -> qtc_QFocusFrame_resize_qth cobj_x0 csize_x1_w csize_x1_h instance QresizeEvent (QFocusFrame ()) ((QResizeEvent t1)) where resizeEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_resizeEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QFocusFrame_resizeEvent_h" qtc_QFocusFrame_resizeEvent_h :: Ptr (TQFocusFrame a) -> Ptr (TQResizeEvent t1) -> IO () instance QresizeEvent (QFocusFrameSc a) ((QResizeEvent t1)) where resizeEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_resizeEvent_h cobj_x0 cobj_x1 instance QsetGeometry (QFocusFrame ()) ((Int, Int, Int, Int)) where setGeometry x0 (x1, x2, x3, x4) = withObjectPtr x0 $ \cobj_x0 -> qtc_QFocusFrame_setGeometry1 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4) foreign import ccall "qtc_QFocusFrame_setGeometry1" qtc_QFocusFrame_setGeometry1 :: Ptr (TQFocusFrame a) -> CInt -> CInt -> CInt -> CInt -> IO () instance QsetGeometry (QFocusFrameSc a) ((Int, Int, Int, Int)) where setGeometry x0 (x1, x2, x3, x4) = withObjectPtr x0 $ \cobj_x0 -> qtc_QFocusFrame_setGeometry1 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4) instance QqsetGeometry (QFocusFrame ()) ((QRect t1)) where qsetGeometry x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_setGeometry cobj_x0 cobj_x1 foreign import ccall "qtc_QFocusFrame_setGeometry" qtc_QFocusFrame_setGeometry :: Ptr (TQFocusFrame a) -> Ptr (TQRect t1) -> IO () instance QqsetGeometry (QFocusFrameSc a) ((QRect t1)) where qsetGeometry x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_setGeometry cobj_x0 cobj_x1 instance QsetGeometry (QFocusFrame ()) ((Rect)) where setGeometry x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h -> qtc_QFocusFrame_setGeometry_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h foreign import ccall "qtc_QFocusFrame_setGeometry_qth" qtc_QFocusFrame_setGeometry_qth :: Ptr (TQFocusFrame a) -> CInt -> CInt -> CInt -> CInt -> IO () instance QsetGeometry (QFocusFrameSc a) ((Rect)) where setGeometry x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h -> qtc_QFocusFrame_setGeometry_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h instance QsetMouseTracking (QFocusFrame ()) ((Bool)) where setMouseTracking x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QFocusFrame_setMouseTracking cobj_x0 (toCBool x1) foreign import ccall "qtc_QFocusFrame_setMouseTracking" qtc_QFocusFrame_setMouseTracking :: Ptr (TQFocusFrame a) -> CBool -> IO () instance QsetMouseTracking (QFocusFrameSc a) ((Bool)) where setMouseTracking x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QFocusFrame_setMouseTracking cobj_x0 (toCBool x1) instance QsetVisible (QFocusFrame ()) ((Bool)) where setVisible x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QFocusFrame_setVisible_h cobj_x0 (toCBool x1) foreign import ccall "qtc_QFocusFrame_setVisible_h" qtc_QFocusFrame_setVisible_h :: Ptr (TQFocusFrame a) -> CBool -> IO () instance QsetVisible (QFocusFrameSc a) ((Bool)) where setVisible x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QFocusFrame_setVisible_h cobj_x0 (toCBool x1) instance QshowEvent (QFocusFrame ()) ((QShowEvent t1)) where showEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_showEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QFocusFrame_showEvent_h" qtc_QFocusFrame_showEvent_h :: Ptr (TQFocusFrame a) -> Ptr (TQShowEvent t1) -> IO () instance QshowEvent (QFocusFrameSc a) ((QShowEvent t1)) where showEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_showEvent_h cobj_x0 cobj_x1 instance QqsizeHint (QFocusFrame ()) (()) where qsizeHint x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFocusFrame_sizeHint_h cobj_x0 foreign import ccall "qtc_QFocusFrame_sizeHint_h" qtc_QFocusFrame_sizeHint_h :: Ptr (TQFocusFrame a) -> IO (Ptr (TQSize ())) instance QqsizeHint (QFocusFrameSc a) (()) where qsizeHint x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFocusFrame_sizeHint_h cobj_x0 instance QsizeHint (QFocusFrame ()) (()) where sizeHint x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QFocusFrame_sizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h foreign import ccall "qtc_QFocusFrame_sizeHint_qth_h" qtc_QFocusFrame_sizeHint_qth_h :: Ptr (TQFocusFrame a) -> Ptr CInt -> Ptr CInt -> IO () instance QsizeHint (QFocusFrameSc a) (()) where sizeHint x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QFocusFrame_sizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h instance QtabletEvent (QFocusFrame ()) ((QTabletEvent t1)) where tabletEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_tabletEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QFocusFrame_tabletEvent_h" qtc_QFocusFrame_tabletEvent_h :: Ptr (TQFocusFrame a) -> Ptr (TQTabletEvent t1) -> IO () instance QtabletEvent (QFocusFrameSc a) ((QTabletEvent t1)) where tabletEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_tabletEvent_h cobj_x0 cobj_x1 instance QupdateMicroFocus (QFocusFrame ()) (()) where updateMicroFocus x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QFocusFrame_updateMicroFocus cobj_x0 foreign import ccall "qtc_QFocusFrame_updateMicroFocus" qtc_QFocusFrame_updateMicroFocus :: Ptr (TQFocusFrame a) -> IO () instance QupdateMicroFocus (QFocusFrameSc a) (()) where updateMicroFocus x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QFocusFrame_updateMicroFocus cobj_x0 instance QwheelEvent (QFocusFrame ()) ((QWheelEvent t1)) where wheelEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_wheelEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QFocusFrame_wheelEvent_h" qtc_QFocusFrame_wheelEvent_h :: Ptr (TQFocusFrame a) -> Ptr (TQWheelEvent t1) -> IO () instance QwheelEvent (QFocusFrameSc a) ((QWheelEvent t1)) where wheelEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_wheelEvent_h cobj_x0 cobj_x1 instance QwindowActivationChange (QFocusFrame ()) ((Bool)) where windowActivationChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QFocusFrame_windowActivationChange cobj_x0 (toCBool x1) foreign import ccall "qtc_QFocusFrame_windowActivationChange" qtc_QFocusFrame_windowActivationChange :: Ptr (TQFocusFrame a) -> CBool -> IO () instance QwindowActivationChange (QFocusFrameSc a) ((Bool)) where windowActivationChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QFocusFrame_windowActivationChange cobj_x0 (toCBool x1) instance QchildEvent (QFocusFrame ()) ((QChildEvent t1)) where childEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_childEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QFocusFrame_childEvent" qtc_QFocusFrame_childEvent :: Ptr (TQFocusFrame a) -> Ptr (TQChildEvent t1) -> IO () instance QchildEvent (QFocusFrameSc a) ((QChildEvent t1)) where childEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_childEvent cobj_x0 cobj_x1 instance QconnectNotify (QFocusFrame ()) ((String)) where connectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QFocusFrame_connectNotify cobj_x0 cstr_x1 foreign import ccall "qtc_QFocusFrame_connectNotify" qtc_QFocusFrame_connectNotify :: Ptr (TQFocusFrame a) -> CWString -> IO () instance QconnectNotify (QFocusFrameSc a) ((String)) where connectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QFocusFrame_connectNotify cobj_x0 cstr_x1 instance QcustomEvent (QFocusFrame ()) ((QEvent t1)) where customEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_customEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QFocusFrame_customEvent" qtc_QFocusFrame_customEvent :: Ptr (TQFocusFrame a) -> Ptr (TQEvent t1) -> IO () instance QcustomEvent (QFocusFrameSc a) ((QEvent t1)) where customEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_customEvent cobj_x0 cobj_x1 instance QdisconnectNotify (QFocusFrame ()) ((String)) where disconnectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QFocusFrame_disconnectNotify cobj_x0 cstr_x1 foreign import ccall "qtc_QFocusFrame_disconnectNotify" qtc_QFocusFrame_disconnectNotify :: Ptr (TQFocusFrame a) -> CWString -> IO () instance QdisconnectNotify (QFocusFrameSc a) ((String)) where disconnectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QFocusFrame_disconnectNotify cobj_x0 cstr_x1 instance Qreceivers (QFocusFrame ()) ((String)) where receivers x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QFocusFrame_receivers cobj_x0 cstr_x1 foreign import ccall "qtc_QFocusFrame_receivers" qtc_QFocusFrame_receivers :: Ptr (TQFocusFrame a) -> CWString -> IO CInt instance Qreceivers (QFocusFrameSc a) ((String)) where receivers x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QFocusFrame_receivers cobj_x0 cstr_x1 instance Qsender (QFocusFrame ()) (()) where sender x0 () = withQObjectResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFocusFrame_sender cobj_x0 foreign import ccall "qtc_QFocusFrame_sender" qtc_QFocusFrame_sender :: Ptr (TQFocusFrame a) -> IO (Ptr (TQObject ())) instance Qsender (QFocusFrameSc a) (()) where sender x0 () = withQObjectResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QFocusFrame_sender cobj_x0 instance QtimerEvent (QFocusFrame ()) ((QTimerEvent t1)) where timerEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_timerEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QFocusFrame_timerEvent" qtc_QFocusFrame_timerEvent :: Ptr (TQFocusFrame a) -> Ptr (TQTimerEvent t1) -> IO () instance QtimerEvent (QFocusFrameSc a) ((QTimerEvent t1)) where timerEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QFocusFrame_timerEvent cobj_x0 cobj_x1
keera-studios/hsQt
Qtc/Gui/QFocusFrame.hs
bsd-2-clause
44,637
0
14
7,194
14,490
7,347
7,143
-1
-1
import Controller import Network.Wai.Handler.FastCGI (run) main :: IO () main = withLounge run
fortytools/lounge
fastcgi.hs
bsd-2-clause
96
0
6
14
34
19
15
4
1
{-# LANGUAGE Haskell2010 #-} {-# LANGUAGE ExistentialQuantification, PatternSynonyms, PolyKinds, TypeOperators #-} -- | Testing some pattern synonyms module PatternSyns where -- | FooType doc data FooType x = FooCtor x -- | Pattern synonym for 'Foo' x pattern Foo x = FooCtor x -- | Pattern synonym for 'Bar' x pattern Bar x = FooCtor (Foo x) -- | Pattern synonym for (':<->') pattern x :<-> y = (Foo x, Bar y) -- | BlubType is existentially quantified data BlubType = forall x. Show x => BlubCtor x -- | Pattern synonym for 'Blub' x pattern Blub x = BlubCtor x -- | Doc for ('><') data (a :: *) >< b = Empty -- | Pattern for 'Empty' pattern E = Empty -- | Earlier ghc versions didn't allow explicit signatures -- on pattern synonyms. pattern PatWithExplicitSig :: Eq somex => somex -> FooType somex pattern PatWithExplicitSig x = FooCtor x
haskell/haddock
html-test/src/PatternSyns.hs
bsd-2-clause
851
0
8
162
179
96
83
13
0
{-# OPTIONS_GHC -Wall #-} module Messages.Types where -- inspired by: -- https://wiki.haskell.org/Internationalization_of_Haskell_programs_using_Haskell_data_types data Message = ErrorsHeading | ErrorFileLocation | FilesWillBeOverwritten [FilePath] | NoElmFilesFound [FilePath] | TooManyInputSources | CantWriteToOutputBecauseInputIsDirectory | ProcessingFile FilePath
fredcy/elm-format
src/Messages/Types.hs
bsd-3-clause
386
0
7
48
46
30
16
10
0
import Debug.Trace import FRP.Helm import qualified FRP.Helm.Keyboard as Keyboard import qualified FRP.Helm.Window as Window import qualified FRP.Helm.Time as Time data State = State { xpos :: Double, ypos :: Double, xvel :: Double, yvel :: Double } deriving (Show) data Impulse = Impulse { dx :: Int, dy :: Int, dt :: Time.Time } deriving (Show) {-| Given an impulse and a state, returns a new state with updated velocities and positions |-} update :: Impulse -> State -> State update (Impulse { dx = dx, dy = dy, dt = dt}) state = trace (show newstate) newstate where newstate = state { xvel = realToFrac dx / 100.0 + xvel state, yvel = realToFrac dy / 100.0 + yvel state, xpos = xpos state + dt * xvel state, ypos = ypos state + dt * yvel state } {-| Combine arrow inputs and time delta to an impulse |-} impulse :: (Int, Int) -> Time.Time -> Impulse impulse (dx, dy) dt = trace (show i) i where i = Impulse { dx = dx, dy = dy, dt = dt } {-| Given a viewport size, returns rendering functions (State -> Element) |-} render :: (Int, Int) -> State -> Element render (w, h) (State { xpos = xpos, ypos = ypos }) = centeredCollage w h [move (xpos, ypos) $ filled red $ square 100] main :: IO () main = do engine <- startup defaultConfig -- read as "run(engine((render <~ (Window.dimensions engine)) ~~ stepper))" -- where "Window.dimensions engine" is a signal generator for viewport sizes, -- "render <~" that is a rendering function signal generator, and -- that "~~ stepper" applies those functions to states generated by the -- updater signal generator run engine $ render <~ Window.dimensions engine ~~ updater where state = State { xpos = 0, ypos = 0, xvel = 0, yvel = 0 } updater = foldp update state (lift2 impulse Keyboard.arrows (Time.delay (Time.fps 60)))
ilkka/helm-learning
Main.hs
bsd-3-clause
1,916
0
14
474
551
312
239
27
1
module Development.GCCxml.Types where deepDeclarations = [ xml_NN_CASTING_OPERATOR , xml_NN_CONSTRUCTOR , xml_NN_DESTRUCTOR , xml_NN_ENUMERATION , xml_NN_FILE , xml_NN_FUNCTION , xml_NN_FREE_OPERATOR , xml_NN_MEMBER_OPERATOR , xml_NN_METHOD , xml_NN_FUNCTION_TYPE , xml_NN_METHOD_TYPE ] -- Convention -- xml_NN - XML Node Name -- xml_AN - XML Attribute Name xml_AN_ABSTRACT = "abstract" xml_AN_ACCESS = "access" xml_AN_ALIGN = "align" xml_AN_ARTIFICIAL = "artificial" xml_AN_ATTRIBUTES = "attributes" xml_AN_BASE_TYPE = "basetype" xml_AN_BASES = "bases" xml_AN_BITS = "bits" xml_AN_CONST = "const" xml_AN_CONTEXT = "context" xml_AN_CVS_REVISION = "cvs_revision" xml_AN_DEFAULT = "default" xml_AN_DEMANGLED = "demangled" xml_AN_EXTERN = "extern" xml_AN_FILE = "file" xml_AN_ID = "id" xml_AN_INCOMPLETE = "incomplete" xml_AN_INIT = "init" xml_AN_LINE = "line" xml_AN_MANGLED = "mangled" xml_AN_MAX = "max" xml_AN_MEMBERS = "members" xml_AN_MUTABLE = "mutable" xml_AN_NAME = "name" xml_AN_OFFSET = "offset" xml_AN_PURE_VIRTUAL = "pure_virtual" xml_AN_RESTRICT = "restrict" xml_AN_RETURNS = "returns" xml_AN_SIZE = "size" xml_AN_STATIC = "static" xml_AN_THROW = "throw" xml_AN_TYPE = "type" xml_AN_VIRTUAL = "virtual" xml_AN_VOLATILE = "volatile" xml_NN_ARGUMENT = "Argument" xml_NN_ARRAY_TYPE = "ArrayType" xml_NN_CASTING_OPERATOR = "Converter" xml_NN_CLASS = "Class" xml_NN_CONSTRUCTOR = "Constructor" xml_NN_CV_QUALIFIED_TYPE = "CvQualifiedType" xml_NN_DESTRUCTOR = "Destructor" xml_NN_ELLIPSIS = "Ellipsis" xml_NN_ENUMERATION = "Enumeration" xml_NN_ENUMERATION_VALUE = "EnumValue" xml_NN_FIELD = "Field" xml_NN_FILE = "File" xml_NN_FUNCTION = "Function" xml_NN_FUNCTION_TYPE = "FunctionType" xml_NN_FUNDAMENTAL_TYPE = "FundamentalType" xml_NN_FREE_OPERATOR = "OperatorFunction" xml_NN_GCC_xml = "GCC_xml" xml_NN_MEMBER_OPERATOR = "OperatorMethod" xml_NN_METHOD = "Method" xml_NN_METHOD_TYPE = "MethodType" xml_NN_NAMESPACE = "Namespace" xml_NN_OFFSET_TYPE = "OffsetType" xml_NN_POINTER_TYPE = "PointerType" xml_NN_REFERENCE_TYPE = "ReferenceType" xml_NN_ROOT = "GCC_xml" xml_NN_STRUCT = "Struct" xml_NN_TYPEDEF = "Typedef" xml_NN_UNION = "Union" xml_NN_VARIABLE = "Variable"
avaitla/Haskell-to-C---Bridge
src/GCCXML/Types.hs
bsd-3-clause
2,221
0
5
277
363
222
141
76
1
module Lib ( Node , createMaze , renderMaze , solveMaze ) where import qualified Data.Map as Map import qualified Data.Set as Set import Data.Maybe import Data.List (find, nub) import System.Random (RandomGen, randomR, randomRs, split) type Node = (Int, Int) data Adjacent = LeftNode | UpNode | BothNodes deriving (Show, Eq, Ord) data Dir = R | L | D | U deriving (Show, Eq, Ord, Enum, Bounded) data Maze = Maze { mazeWidth :: Int , mazeHeight :: Int , mazeEdges :: Map.Map Node Adjacent } deriving (Show, Eq) getNeighbour :: Maze -> Node -> Dir -> Maybe Node getNeighbour (Maze w h _) (x, y) d | x > 1 && x <= w && d == L = Just (x-1, y ) | x >= 1 && x < w && d == R = Just (x+1, y ) | y > 1 && y <= h && d == U = Just (x , y-1) | y >= 1 && y < h && d == D = Just (x , y+1) | otherwise = Nothing getDirection :: Node -> Node -> Dir getDirection (x1, y1) (x2, y2) | x1 == x2 && y1 < y2 = D | x1 == x2 && y1 > y2 = U | x1 < x2 && y1 == y2 = R | x1 > x2 && y1 == y2 = L | otherwise = error "Can't get direction if not neighbours" isOpenWall :: Maze -> Node -> Dir -> Bool isOpenWall m@(Maze _ _ edges) node dir | isNothing neigh = False | isNothing adj = False | adj == Just BothNodes = True | dir == R || dir == L = adj == Just LeftNode | dir == U || dir == D = adj == Just UpNode where neigh = getNeighbour m node dir adj = Map.lookup (max node $ fromJust neigh) edges isVisited :: Maze -> Node -> Bool isVisited m n = any (isOpenWall m n) $ enumFrom minBound openWall :: Maze -> Node -> Dir -> Maze openWall m@(Maze w h edges) node dir | isNothing neigh = m | dir == U && hasNoAdj = Maze w h $ Map.insert node UpNode edges | dir == L && hasNoAdj = Maze w h $ Map.insert node LeftNode edges | (dir == U || dir == L) && (not hasNoAdj) = Maze w h $ Map.insert node BothNodes edges | dir == D = openWall m (fromJust neigh) U | dir == R = openWall m (fromJust neigh) L where neigh = getNeighbour m node dir hasNoAdj = isNothing $ Map.lookup node edges renderMaze :: Maze -> [Node] -> String renderMaze (Maze w h edges) path = unlines $ concatMap renderRow [1..h+1] where renderRow r = [concatMap head rowString, concatMap (head . tail) rowString] where rowString = map (renderNode r) [1..w+1] renderNode y x | x == w+1 && y == h+1 = [ "*" , "" ] -- bottom right corner | x == w+1 = [ "*" , "|" ] -- right wall | y == h+1 = [ "*---", "" ] -- bottom wall | adj == Just BothNodes = [ "* ", " " ++ nodeStr ++ " " ] -- left and up are open | adj == Just LeftNode = [ "*---", " " ++ nodeStr ++ " " ] -- left is open | adj == Just UpNode = [ "* ", "| " ++ nodeStr ++ " " ] -- up is open | otherwise = [ "*---", "| " ++ nodeStr ++ " " ] -- left and up are closed where adj = Map.lookup (x, y) edges -- FIXME: last is linear, will bomb nodeStr = if (x, y) == last path then "👽" else case lookup (x, y) $ zip path (tail path) of Nothing -> " " Just to -> dirToStr $ getDirection (x, y) to dirToStr d = case d of L -> "←" R -> "→" U -> "↑" D -> "↓" randomEnumList :: (Enum a, RandomGen g) => (a, a) -> g -> [a] randomEnumList (rangeMin, rangeMax) = map toEnum . take l . nub . randomRs (fromEnum rangeMin, fromEnum rangeMax) where l = length [rangeMin .. rangeMax] initMaze :: Int -> Int -> Maze initMaze w h = Maze w h Map.empty createMaze :: (RandomGen g) => g -> Int -> Int -> Maze createMaze gen w h = walk (gen0, initMaze w h) (startX, startY) where (gen0, gen1) = split gen (startX, gen2) = randomR (1, w) gen1 (startY, _ ) = randomR (1, h) gen2 walk (g, maze) n = foldl (walk' n) maze neighbours where (gen3, gen4) = split g neighbours = mapMaybe (getNeighbour maze n) (randomEnumList (minBound, maxBound) gen3) walk' fromNode maze toNode | isVisited maze toNode = maze | otherwise = walk (gen4, openWall maze fromNode dir) toNode where dir = getDirection fromNode toNode dfs :: (Eq a, Ord a) => (a -> [a]) -> a -> a -> Maybe [a] dfs neighboursOf start fin = fst $ dfs' Set.empty $ start where dfs' v cur | cur == fin = (Just [cur], v') | null ns = (Nothing, v') | otherwise = case foldl (\(r, v'') n -> case r of Just p -> (Just p, v'') Nothing -> (dfs' v'' n)) (Nothing, v') ns of (Nothing, v''') -> (Nothing, v''') (Just p, v''') -> (Just (cur : p), v''') where ns = filter (not . flip Set.member v) (neighboursOf cur) v' = Set.insert cur v solveMaze :: Maze -> Node -> Node -> [Node] solveMaze maze start fin = fromMaybe [] $ dfs (getOpenNeighbours maze) start fin where getOpenNeighbours maze node = mapMaybe (getNeighbour maze node) (filter (isOpenWall maze node) [minBound .. ])
ford-prefect/haskell-maze
src/Lib.hs
bsd-3-clause
5,441
0
16
1,914
2,268
1,169
1,099
109
6
-- | Common handler functions. module Handler.Common where import Data.FileEmbed (embedFile) import Import -- These handlers embed files in the executable at compile time to avoid a -- runtime dependency, and for efficiency. getFaviconR :: Handler TypedContent getFaviconR = return $ TypedContent "image/x-icon" $ toContent $(embedFile "config/favicon.ico") getRobotsR :: Handler TypedContent getRobotsR = return $ TypedContent typePlain $ toContent $(embedFile "config/robots.txt") renderTimeStamp :: UTCTime -> String renderTimeStamp t = formatTime defaultTimeLocale "%d %b %Y %X" t renderDate:: UTCTime -> String renderDate t = formatTime defaultTimeLocale "%d %b %Y" t
roggenkamps/steveroggenkamp.com
Handler/Common.hs
bsd-3-clause
721
0
9
137
138
71
67
13
1
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-} -- | The HeadTail class used for parsing with either strings or bytestrings. module Data.HeadTail(HeadTail(..)) where import qualified Data.ByteString.Lazy.Char8 as BS class HeadTail l a | l -> a where headTail :: l -> Maybe (a,l) instance HeadTail [a] a where headTail [] = Nothing headTail (x:xs) = Just (x,xs) instance HeadTail BS.ByteString Char where headTail s | BS.null s = Nothing | otherwise = Just (BS.head s, BS.tail s)
GaloisInc/sk-dev-platform
libs/SCD/src/Data/HeadTail.hs
bsd-3-clause
546
0
10
109
168
91
77
12
0
module HGraph.Path where import Control.Applicative import Control.Monad.State import qualified Data.Map as M import qualified Data.Maybe as MB import qualified Data.PQueue.Prio.Min as PQ import qualified Data.Set as S import HGraph.Edge import HGraph.Graph import HGraph.Query import HGraph.Types type PathAncestors = M.Map Id (Maybe (Node, Edge)) getAncestor :: PathAncestors -> Node -> Maybe (Node, Edge) getAncestor pa n = MB.fromJust $ M.lookup (nodeId n) pa constructPath :: PathAncestors -> Node -> Path constructPath pa n = aux n [] where aux cn p | MB.isNothing lr = Path cn p | otherwise = aux an ((e, cn):p) where lr = getAncestor pa cn (an, e) = MB.fromJust lr addPathToPathTree :: Path -> PathTree -> PathTree addPathToPathTree (Path pn po) (PathTree ptn pto) = if pn == ptn then PathTree ptn (aux2 po pto) else PathTree ptn pto where aux2 [] x = x aux2 ((e, on):xs2) [] = [(e, addPathToPathTree (Path on xs2) (PathTree on []))] aux2 ((e, on):xs2) ((te, PathTree tn to):xs1) = if tn == on then (te, addPathToPathTree (Path on xs2) (PathTree tn to)):xs1 else (te, PathTree tn to):aux2 ((e, on):xs2) xs1 addPathToPathTree' :: (Ord a, Num a) => (a, Path) -> PathTree -> PathTree addPathToPathTree' (_, p) = addPathToPathTree p constructPathTree :: Node -> [Path] -> PathTree constructPathTree n = foldr addPathToPathTree (PathTree n []) constructPathTreeW :: (Ord a, Num a) => Node -> [(a, Path)] -> PathTree constructPathTreeW n = foldr addPathToPathTree' (PathTree n []) dijkstraG' :: (Ord a, Num a) => Graph -> Int -> Int -> Direction -> (Node -> Bool) -> (Edge -> Bool) -> (Label -> Bool) -> (Edge -> a) -> PQ.MinPQueue a (Node, Maybe Edge) -> PQ.MinPQueue a (Node, Maybe Edge) -> PathAncestors -> [(a, Path)] -> [(a, Path)] dijkstraG' g de count di nbf ebf lbf vf cq nq pa ps | de < 0 || count == 0 = ps | cqn && nqn = ps | cqn = dijkstraG' g (de - 1) count di nbf ebf lbf vf nq PQ.empty pa ps | otherwise = dijkstraG' g de nn di nbf ebf lbf vf ncq nnq npa nps where cqn = PQ.null cq nqn = PQ.null nq ((k, (v, me)), ncq) = PQ.deleteFindMin cq vi = nodeId v ncs = nbf v nn = if ncs then count - 1 else count gsEdges | di == DOUT = getFilteredOutNodesN ebf lbf v | di == DIN = getFilteredInNodesN ebf lbf v | di == DBOTH = combineGS (++) (getFilteredInNodesN ebf lbf v) (getFilteredOutNodesN ebf lbf v) | otherwise = return [] es = filter (\(_, n) -> not $ (nodeId n == vi) || M.member (nodeId n) pa) $ evalState gsEdges g nnq = if ncs then nq else foldl (\a (e, n) -> PQ.insert (k + vf e) (n, Just e) a) nq es apa = aux pa npa = if ncs then pa else apa nps = if ncs then ps ++ [(k, constructPath apa v)] else ps aux tpa = MB.maybe (M.insert vi Nothing tpa) (\e -> M.insert vi (Just (unpackStateValue getStartNodeN g e, e)) tpa) me dijkstraGN :: (Ord a, Num a) => Int -> Int -> Direction -> (Node -> Bool) -> (Edge -> Bool) -> (Label -> Bool) -> (Edge -> a) -> Node -> GS [(a, Path)] dijkstraGN de count di nbf ebf lbf vf n = do g <- get let ni = nodeId n return $ dijkstraG' g de count di nbf ebf lbf vf (PQ.singleton 0 (n, Nothing)) PQ.empty M.empty [] dijkstraG :: (Ord a, Num a) => Int -> Int -> Direction -> (Node -> Bool) -> (Edge -> Bool) -> (Label -> Bool) -> (Edge -> a) -> Id -> GS [(a, Path)] dijkstraG de count di nbf ebf lbf vf i = getNodeByIdUnsafe i >>= dijkstraGN de count di nbf ebf lbf vf dijkstraGTreeN :: (Ord a, Num a) => Int -> Int -> Direction -> (Node -> Bool) -> (Edge -> Bool) -> (Label -> Bool) -> (Edge -> a) -> Node -> GS PathTree dijkstraGTreeN de count di nbf ebf lbf vf n = constructPathTreeW n <$> dijkstraGN de count di nbf ebf lbf vf n dijkstraGTree :: (Ord a, Num a) => Int -> Int -> Direction -> (Node -> Bool) -> (Edge -> Bool) -> (Label -> Bool) -> (Edge -> a) -> Id -> GS PathTree dijkstraGTree de count di nbf ebf lbf vf i = getNodeByIdUnsafe i >>= dijkstraGTreeN de count di nbf ebf lbf vf dijkstraN :: (Ord a, Num a) => Int -> Int -> Direction -> (Node -> Bool) -> [Label] -> (Edge -> a) -> Node -> GS [(a, Path)] dijkstraN de count di nbf ls = dijkstraGN de count di nbf (const True) (`elem` ls) dijkstra :: (Ord a, Num a) => Int -> Int -> Direction -> (Node -> Bool) -> [Label] -> (Edge -> a) -> Id -> GS [(a, Path)] dijkstra de count di nbf ls vf i = getNodeByIdUnsafe i >>= dijkstraN de count di nbf ls vf dijkstraTreeN :: (Ord a, Num a) => Int -> Int -> Direction -> (Node -> Bool) -> [Label] -> (Edge -> a) -> Node -> GS PathTree dijkstraTreeN de count di nbf ls vf n = constructPathTreeW n <$> dijkstraN de count di nbf ls vf n dijkstraTree :: (Ord a, Num a) => Int -> Int -> Direction -> (Node -> Bool) -> [Label] -> (Edge -> a) -> Id -> GS PathTree dijkstraTree de count di nbf ls vf i = getNodeByIdUnsafe i >>= dijkstraTreeN de count di nbf ls vf dijkstraFieldN :: (Ord a, Num a) => Int -> Int -> Direction -> (Node -> Bool) -> [Label] -> Key -> a -> (Value -> a) -> Node -> GS [(a, Path)] dijkstraFieldN de count di nbf ls k dt vvf = dijkstraGN de count di nbf (const True) (`elem` ls) (MB.maybe dt vvf . getEdgePropertySE k) dijkstraField :: (Ord a, Num a) => Int -> Int -> Direction -> (Node -> Bool) -> [Label] -> Key -> a -> (Value -> a) -> Id -> GS [(a, Path)] dijkstraField de count di nbf ls k dt vvf i = getNodeByIdUnsafe i >>= dijkstraFieldN de count di nbf ls k dt vvf dijkstraFieldTreeN :: (Ord a, Num a) => Int -> Int -> Direction -> (Node -> Bool) -> [Label] -> Key -> a -> (Value -> a) -> Node -> GS PathTree dijkstraFieldTreeN de count di nbf ls k dt vvf n = constructPathTreeW n <$> dijkstraFieldN de count di nbf ls k dt vvf n dijkstraFieldTree :: (Ord a, Num a) => Int -> Int -> Direction -> (Node -> Bool) -> [Label] -> Key -> a -> (Value -> a) -> Id -> GS PathTree dijkstraFieldTree de count di nbf ls k dt vvf i = getNodeByIdUnsafe i >>= dijkstraFieldTreeN de count di nbf ls k dt vvf shortestPathGN :: Int -> Int -> Direction -> (Node -> Bool) -> (Edge -> Bool) -> (Label -> Bool) -> Node -> GS [(Int, Path)] shortestPathGN de count di nbf ebf lbf = dijkstraGN de count di nbf ebf lbf (const 1) shortestPathG :: Int -> Int -> Direction -> (Node -> Bool) -> (Edge -> Bool) -> (Label -> Bool) -> Id -> GS [(Int, Path)] shortestPathG de count di nbf ebf lbf i = getNodeByIdUnsafe i >>= shortestPathGN de count di nbf ebf lbf shortestPathGTreeN :: Int -> Int -> Direction -> (Node -> Bool) -> (Edge -> Bool) -> (Label -> Bool) -> Node -> GS PathTree shortestPathGTreeN de count di nbf ebf lbf = dijkstraGTreeN de count di nbf ebf lbf (const (1 :: Int)) shortestPathGTree :: Int -> Int -> Direction -> (Node -> Bool) -> (Edge -> Bool) -> (Label -> Bool) -> Id -> GS PathTree shortestPathGTree de count di nbf ebf lbf i = getNodeByIdUnsafe i >>= shortestPathGTreeN de count di nbf ebf lbf shortestPathN :: Int -> Int -> Direction -> (Node -> Bool) -> [Label] -> Node -> GS [(Int, Path)] shortestPathN de count di nbf ls = dijkstraN de count di nbf ls (const 1) shortestPath :: Int -> Int -> Direction -> (Node -> Bool) -> [Label] -> Id -> GS [(Int, Path)] shortestPath de count di nbf ls i = getNodeByIdUnsafe i >>= shortestPathN de count di nbf ls shortestPathTreeN :: Int -> Int -> Direction -> (Node -> Bool) -> [Label] -> Node -> GS PathTree shortestPathTreeN de count di nbf ls = dijkstraTreeN de count di nbf ls (const (1 :: Int)) shortestPathTree :: Int -> Int -> Direction -> (Node -> Bool) -> [Label] -> Id -> GS PathTree shortestPathTree de count di nbf ls i = getNodeByIdUnsafe i >>= shortestPathTreeN de count di nbf ls
gpahal/hgraph
src/HGraph/Path.hs
bsd-3-clause
9,410
0
19
3,459
3,687
1,923
1,764
144
5
module Math.Primes where import Control.Monad import Control.Monad.Random import Math.Modular millerRabinStep :: Integer -> Integer -> Bool millerRabinStep a n = if gcd a n /= 1 then a `mod` n == 0 else let (r, d) = removeTwos (n-1) base = modPow a d n powers = take (fromInteger r) $ iterate (\x -> (x * x) `mod` n) base in base == 1 || any (== n - 1) powers removeTwos :: Integer -> (Integer, Integer) removeTwos 0 = (0, 0) removeTwos n = if even n then let (r, d) = removeTwos (n `div` 2) in (r+1, d) else (0, n) millerRabin :: MonadRandom m => Int -> Integer -> m Bool millerRabin 0 _ = return True millerRabin k n = do witness <- getRandomR (1, n-1) if millerRabinStep witness n then millerRabin (k-1) n else return False -- randomPrime n returns a random prime with n bits randomPrime :: MonadRandom m => Int -> m Integer randomPrime n = do candidate <- fmap (\x -> 2*x + 1) (getRandomR (2^(n-2), 2^(n-1) - 1)) isPrime <- millerRabin k candidate if isPrime then return candidate else randomPrime n where k = 64
bhamrick/hsmath
Math/Primes.hs
bsd-3-clause
1,150
0
16
327
498
262
236
32
2
import System.Environment (getArgs) age :: Int -> String age i | i < 0 || i > 100 = "This program is for humans" | i < 3 = "Still in Mama's arms" | i < 5 = "Preschool Maniac" | i < 12 = "Elementary school" | i < 15 = "Middle school" | i < 19 = "High school" | i < 23 = "College" | i < 66 = "Working for the man" | otherwise = "The Golden Years" main :: IO () main = do [inpFile] <- getArgs input <- readFile inpFile putStr . unlines . map (age . read) $ lines input
nikai3d/ce-challenges
easy/age_distribution.hs
bsd-3-clause
608
0
11
249
209
99
110
16
1
{-# LANGUAGE ScopedTypeVariables, DisambiguateRecordFields #-} {-# LANGUAGE DeriveFunctor, DeriveFoldable, DeriveTraversable #-} module Data.Octree.Internal(Vector3(..), dist, Octree(..), lookup, nearest, withinRange, fromList, toList, insert, -- internal ODir(..), octreeStep, octantDistance, splitBy', joinStep, splitStep, allOctants, octantDistance', cmp, pickClosest, depth, size, subnodes ) where import Data.Functor (Functor (..)) import Data.Foldable (Foldable (foldr)) import Data.Traversable(Traversable(..)) import Data.Vector.V3 import Data.Vector.Class --import Text.Show import Prelude hiding(lookup, foldr) import Data.List(sort, sortBy) import Data.Maybe(maybeToList, listToMaybe) import Data.Bits((.&.)) import Control.Arrow(second) import Test.QuickCheck.All(quickCheckAll) import Test.QuickCheck.Arbitrary -- | norm of a vector norm :: Vector3 -> Double norm a = sqrt (a `vdot` a) -- | distance between two vectors dist :: Vector3 -> Vector3 -> Double dist u v = norm (u - v) -- | Datatype for nodes within Octree. data Octree a = Node { split :: Vector3, nwu, nwd, neu, ned, swu, swd, seu, sed :: Octree a } | Leaf { unLeaf :: [(Vector3, a)] } deriving (Show, Functor, Foldable, Traversable) -- | Enumerated type to indicate octants in 3D-space relative to given center. data ODir = SWD | SED | NWD | NED | SWU | SEU | NWU | NEU deriving (Eq, Ord, Enum, Show, Bounded) -- | Internal method that gives octant of a first vector relative to the second vector as a center. cmp :: Vector3 -> Vector3 -> ODir cmp ca cb = joinStep (cx, cy, cz) where cx = v3x ca >= v3x cb cy = v3y ca >= v3y cb cz = v3z ca >= v3z cb -- | Internal method that joins result of three coordinate comparisons and makes an octant name `ODir` joinStep :: (Enum a1, Enum a3, Enum a2, Enum a) => (a1, a2, a3) -> a joinStep (cx, cy, cz) = toEnum (fromEnum cx + 2 * fromEnum cy + 4 * fromEnum cz) -- | This function converts octant name to a function that steps down in an Octree towards this octant octreeStep :: Octree a -> ODir -> Octree a octreeStep ot NWU = nwu ot octreeStep ot NWD = nwd ot octreeStep ot NEU = neu ot octreeStep ot NED = ned ot octreeStep ot SWU = swu ot octreeStep ot SWD = swd ot octreeStep ot SEU = seu ot octreeStep ot SED = sed ot -- | Function that splits octant name into three boolean values, depending of sign of a relative coordinate in that octant. -- | (Coordinate is relative to a split point within Octree.) splitStep :: ODir -> (Bool, Bool, Bool) splitStep step = ((val .&. 1) == 1, (val .&. 2) == 2, (val .&. 4) == 4) where val = fromEnum step -- | Internal function that finds a lower bound for a distance between a point of relative coordinates, -- | and octant of given name. It works only when coordinates of a given point are all positive. -- | It is used only by `octantDistance`, which respectively changes octant name depending of signs of -- | relative coordinates. -- here we assume that a, b, c > 0 (otherwise we will take abs, and correspondingly invert results) -- same octant -- dp = difference between given point and the center of Octree node octantDistance' :: Vector3 -> ODir -> Scalar octantDistance' dp NEU = 0.0 -- adjacent by plane octantDistance' dp NWU = v3x dp octantDistance' dp SEU = v3y dp octantDistance' dp NED = v3z dp -- adjacent by edge octantDistance' dp SWU = sqrt ( v3x dp * v3x dp + v3y dp * v3y dp) octantDistance' dp SED = sqrt ( v3y dp * v3y dp + v3z dp * v3z dp) octantDistance' dp NWD = sqrt ( v3x dp * v3x dp + v3z dp * v3z dp) -- adjacent by point octantDistance' dp SWD = norm dp -- | List of all octant names. allOctants :: [ODir] allOctants = [minBound..maxBound] -- | Internal function that makes code clearer. xor :: Bool -> Bool -> Bool xor = (/=) -- | Finds a minimum bounds for a distance between a given point -- | in relative coordinates and a given octant. octantDistance :: Vector3 -> ODir -> Double octantDistance dp odir = octantDistance' (abs dp) (toggle dp odir) -- | Toggles octant names depending on a signs of vector coordinates -- | for use in octantDistance. toggle :: Vector3 -> ODir -> ODir toggle dp odir = joinStep ((v3x dp >= 0) `xor` not u, (v3y dp >= 0) `xor` not v, (v3z dp >= 0) `xor` not w) where (u, v, w) = splitStep odir -- | Given a point in relative coordinates, gives list of all octants and minimum distances from this point. octantDistances :: Vector3 -> [(ODir, Double)] octantDistances dp = [(o, octantDistance dp o) | o <- allOctants] -- | splits a list of vectors and "payload" tuples -- | into a tuple with elements destined for different octants. -- FIXME: VERY IMPORTANT - add prop_splitBy vs cmp splitBy :: Vector3 -> [(Vector3, a)] -> ([(Vector3, a)], [(Vector3, a)], [(Vector3, a)], [(Vector3, a)], [(Vector3, a)], [(Vector3, a)], [(Vector3, a)], [(Vector3, a)]) splitBy _splitPoint [] = ([], [], [], [], [], [], [], []) splitBy splitPoint ((pt@(coord, a)):aList) = case i of SWD -> (pt:swd, sed, nwd, ned, swu, seu, nwu, neu) SED -> ( swd, pt:sed, nwd, ned, swu, seu, nwu, neu) NWD -> ( swd, sed, pt:nwd, ned, swu, seu, nwu, neu) NED -> ( swd, sed, nwd, pt:ned, swu, seu, nwu, neu) SWU -> ( swd, sed, nwd, ned, pt:swu, seu, nwu, neu) SEU -> ( swd, sed, nwd, ned, swu, pt:seu, nwu, neu) NWU -> ( swd, sed, nwd, ned, swu, seu, pt:nwu, neu) NEU -> ( swd, sed, nwd, ned, swu, seu, nwu, pt:neu) where i = cmp coord splitPoint (swd, sed, nwd, ned, swu, seu, nwu, neu) = splitBy splitPoint aList -- | Computes a center of mass for a given list of vectors - used to find a splitPoint. massCenter :: Fractional a => [(a, b)] -> a massCenter aList = sum (map fst aList) / count where count = fromInteger . toInteger . length $ aList -- | Helper function to map over an 8-element tuple tmap :: (t -> t1)-> (t, t, t, t, t, t, t, t)-> (t1, t1, t1, t1, t1, t1, t1, t1) tmap t (a, b, c, d, e, f, g, h) = (t a, t b, t c, t d, t e, t f, t g, t h) -- | Maximum number of elements before Octree leaf is split. leafLimit :: Int leafLimit = 16 -- | Creates an Octree from a list of (index, payload) tuples. fromList :: [(Vector3, a)] -> Octree a fromList aList = if length aList <= leafLimit then Leaf aList else let splitPoint :: Vector3 = massCenter aList in splitBy' fromList splitPoint aList -- | Internal method, that splits a list into octants depending on coordinates, -- | and then applies a specified function to each of these sublists, -- | in order to create subnodes of the Octree splitBy' :: ([(Vector3, a)] -> Octree a1)-> Vector3-> [(Vector3, a)]-> Octree a1 splitBy' f splitPoint aList = Node { split = splitPoint, nwu = tnwu, nwd = tnwd, neu = tneu, ned = tned, swu = tswu, swd = tswd, seu = tseu, sed = tsed } where (tswd, tsed, tnwd, tned, tswu, tseu, tnwu, tneu) = tmap f $ splitBy splitPoint aList -- TODO: use arrays for memory savings -- | Internal method that prepends contents of the given subtree to a list -- | given as argument. toList' :: Octree t -> [(Vector3, t)] -> [(Vector3, t)] toList' (Leaf l ) tmp = l ++ tmp toList' (Node { nwu = a, nwd = b, neu = c, ned = d, swu = e, swd = f, seu = g, sed = h }) tmp = foldr toList' tmp [a, b, c, d, e, f, g, h] -- | Creates an Octree from list, trying to keep split points near centers -- | of mass for each subtree. toList :: Octree t -> [(Vector3, t)] toList t = toList' t [] -- | Finds a path to a Leaf where a given point should be, -- | and returns a list of octant names. pathTo :: Vector3 -> Octree a -> [ODir] pathTo pt (Leaf _) = [] pathTo pt node = aStep : pathTo pt (octreeStep node aStep) where aStep = cmp pt (split node) -- | Applies a given function to a node specified by a path (list of octant names), -- | and then returns a modified Octree. applyByPath :: (Octree a -> Octree a) -> [ODir] -> Octree a -> Octree a applyByPath f [] ot = f ot applyByPath f (step:path) node = case step of NWU -> node{ nwu = applyByPath f path (nwu node) } NWD -> node{ nwd = applyByPath f path (nwd node) } NEU -> node{ neu = applyByPath f path (neu node) } NED -> node{ ned = applyByPath f path (ned node) } SWU -> node{ swu = applyByPath f path (swu node) } SWD -> node{ swd = applyByPath f path (swd node) } SEU -> node{ seu = applyByPath f path (seu node) } SED -> node{ sed = applyByPath f path (sed node) } -- | Inserts a point into an Octree. -- | NOTE: insert accepts duplicate points, but lookup would not find them - use withinRange in such case. insert :: (Vector3, a) -> Octree a -> Octree a insert (pt, dat) ot = applyByPath insert' path ot where path = pathTo pt ot insert' (Leaf l) = fromList ((pt, dat) : l) insert' _ = error "Impossible in insert'" -- | Internal: finds candidates for nearest neighbour lazily for each octant; -- | they are returned in a list of (octant, min. bound for distance, Maybe candidate) tuples. candidates' :: Vector3 -> Octree a -> [(ODir, Double, [(Vector3, a)])] candidates' pt (Leaf l) = [] candidates' pt node = map findCandidates . sortBy compareDistance . octantDistances $ pt - split node where findCandidates (octant, d) = (octant, d, maybeToList . pickClosest pt . toList . octreeStep node $ octant) compareDistance a b = compare (snd a) (snd b) -- | Finds a given point, if it is in the tree. lookup :: Octree a -> Vector3 -> Maybe (Vector3, a) lookup (Leaf l) pt = listToMaybe . filter ((==pt) . fst) $ l lookup node pt = flip lookup pt . octreeStep node . cmp pt . split $ node -- | Finds nearest neighbour for a given point. nearest :: Octree a -> Vector3 -> Maybe (Vector3, a) nearest (Leaf l) pt = pickClosest pt l nearest node pt = selectFrom candidates where candidates = map findCandidate . sortBy compareDistance . octantDistances $ pt - split node compareDistance a b = compare (snd a) (snd b) findCandidate (octant, d) = (maybeToList . nearest' . octreeStep node $ octant, d) selectFrom (([], _d) : cs) = selectFrom cs selectFrom (([best], _d) : cs) = selectFrom' best cs selectFrom [] = Nothing nearest' n = nearest n pt selectFrom' best (([], d) : cs) = selectFrom' best cs -- TODO: FAILS: shortcut guard to avoid recursion over whole structure (since d is bound for distance within octant): selectFrom' best ((c, d) : cs) | d > dist pt (fst best) = Just best selectFrom' best (([next], d) : cs) = selectFrom' nextBest cs where nextBest = if dist pt (fst best) <= dist pt (fst next) then best else next selectFrom' best [] = Just best -- | Internal method that picks from a given list a point closest to argument, pickClosest :: Vector3 -> [(Vector3, t)] -> Maybe (Vector3, t) pickClosest pt [] = Nothing pickClosest pt (a:as) = Just $ foldr (pickCloser pt) a as pickCloser pt va@(a, _a) vb@(b, _b) = if dist pt a <= dist pt b then va else vb -- | Returns all points within Octree that are within a given distance from argument. withinRange :: Octree a -> Scalar -> Vector3 -> [(Vector3, a)] withinRange (Leaf l) r pt = filter (\(lpt, _) -> dist pt lpt <= r) l withinRange node r pt = concatMap recurseOctant . -- recurse over remaining octants, and merge results filter ((<=r) . snd) . -- discard octants that are out of range octantDistances $ pt - split node -- find octant distances where recurseOctant (octant, _d) = (\o -> withinRange o r pt) . octreeStep node $ octant subnodes :: Octree a -> [Octree a] subnodes (Leaf _) = [] subnodes node = map (octreeStep node) allOctants depth :: Octree a -> Int depth (Leaf _) = 0 depth node = foldr max 0 . map ((+1) . depth) . subnodes $ node size :: Octree a -> Int size = length . toList
seppeljordan/octree
Data/Octree/Internal.hs
bsd-3-clause
13,753
0
13
4,524
4,018
2,226
1,792
195
8
{-# LANGUAGE ViewPatterns, MultiParamTypeClasses, FlexibleInstances, TypeSynonymInstances #-} module HSE.Match where import Data.Char import HSE.Type import HSE.Util import qualified Language.Haskell.Exts as HSE_ class View a b where view :: a -> b data App2 = NoApp2 | App2 Exp_ Exp_ Exp_ deriving Show instance View Exp_ App2 where view (fromParen -> InfixApp _ lhs op rhs) = App2 (opExp op) lhs rhs view (fromParen -> App _ (fromParen -> App _ f x) y) = App2 f x y view _ = NoApp2 data App1 = NoApp1 | App1 Exp_ Exp_ deriving Show instance View Exp_ App1 where view (fromParen -> App _ f x) = App1 f x view _ = NoApp1 data PVar_ = NoPVar_ | PVar_ String instance View Pat_ PVar_ where view (fromPParen -> PVar _ x) = PVar_ $ fromNamed x view _ = NoPVar_ data Var_ = NoVar_ | Var_ String deriving Eq instance View Exp_ Var_ where view (fromParen -> Var _ (UnQual _ x)) = Var_ $ fromNamed x view _ = NoVar_ (~=) :: Named a => a -> String -> Bool (~=) = (==) . fromNamed -- | fromNamed will return \"\" when it cannot be represented -- toNamed may crash on \"\" class Named a where toNamed :: String -> a fromNamed :: a -> String isCtor (x:_) = isUpper x || x == ':' isCtor _ = False isSym (x:_) = not $ isAlpha x || x `elem` "_'" isSym _ = False instance Named (Exp S) where fromNamed (Var _ x) = fromNamed x fromNamed (Con _ x) = fromNamed x fromNamed (List _ []) = "[]" fromNamed _ = "" toNamed "[]" = List an [] toNamed x | isCtor x = Con an $ toNamed x | otherwise = Var an $ toNamed x instance Named (QName S) where fromNamed (Special _ Cons{}) = ":" fromNamed (Special _ UnitCon{}) = "()" fromNamed (UnQual _ x) = fromNamed x fromNamed _ = "" toNamed ":" = Special an $ Cons an toNamed x = UnQual an $ toNamed x instance Named HSE_.QName where fromNamed (HSE_.Special HSE_.Cons) = ":" fromNamed (HSE_.Special HSE_.UnitCon) = "()" fromNamed (HSE_.UnQual x) = fromNamed x fromNamed _ = "" toNamed ":" = HSE_.Special HSE_.Cons toNamed x = HSE_.UnQual $ toNamed x instance Named (Name S) where fromNamed (Ident _ x) = x fromNamed (Symbol _ x) = x toNamed x | isSym x = Symbol an x | otherwise = Ident an x instance Named HSE_.Name where fromNamed (HSE_.Ident x) = x fromNamed (HSE_.Symbol x) = x toNamed x | isSym x = HSE_.Symbol x | otherwise = HSE_.Ident x instance Named (ModuleName S) where fromNamed (ModuleName _ x) = x toNamed = ModuleName an instance Named (Pat S) where fromNamed (PVar _ x) = fromNamed x fromNamed (PApp _ x []) = fromNamed x fromNamed _ = "" toNamed x | isCtor x = PApp an (toNamed x) [] | otherwise = PVar an $ toNamed x instance Named (TyVarBind S) where fromNamed (KindedVar _ x _) = fromNamed x fromNamed (UnkindedVar _ x) = fromNamed x toNamed x = UnkindedVar an (toNamed x) instance Named (QOp S) where fromNamed (QVarOp _ x) = fromNamed x fromNamed (QConOp _ x) = fromNamed x toNamed x | isCtor x = QConOp an $ toNamed x | otherwise = QVarOp an $ toNamed x instance Named (Match S) where fromNamed (Match _ x _ _ _) = fromNamed x fromNamed (InfixMatch _ _ x _ _ _) = fromNamed x toNamed = error "No toNamed for Match" instance Named (DeclHead S) where fromNamed (DHead _ x _) = fromNamed x fromNamed (DHInfix _ _ x _) = fromNamed x fromNamed (DHParen _ x) = fromNamed x toNamed = error "No toNamed for DeclHead" instance Named (Decl S) where fromNamed (TypeDecl _ name _) = fromNamed name fromNamed (DataDecl _ _ _ name _ _) = fromNamed name fromNamed (GDataDecl _ _ _ name _ _ _) = fromNamed name fromNamed (TypeFamDecl _ name _) = fromNamed name fromNamed (DataFamDecl _ _ name _) = fromNamed name fromNamed (ClassDecl _ _ name _ _) = fromNamed name fromNamed (PatBind _ (PVar _ name) _ _ _) = fromNamed name fromNamed (FunBind _ (name:_)) = fromNamed name fromNamed (ForImp _ _ _ _ name _) = fromNamed name fromNamed (ForExp _ _ _ name _) = fromNamed name fromNamed (TypeSig _ (name:_) _) = fromNamed name fromNamed _ = "" toNamed = error "No toNamed for Decl"
bergmark/hlint
src/HSE/Match.hs
bsd-3-clause
4,293
0
12
1,143
1,812
887
925
107
1
{-# LANGUAGE OverloadedStrings #-} module Main where import Git.FastExport import Git.FastExport.Filter import Git.FastExport.AuthorFilter import Git.FastExport.BShow import Data.Conduit import qualified Git.FastExport.Conduit as FE import Data.Conduit.Binary import System.IO (stdin, stdout) import System.Exit import System.Environment (getArgs, getProgName) import Data.Maybe (listToMaybe) import Control.Monad (guard) import Control.Applicative import Data.ByteString (ByteString) import qualified Data.ByteString.Char8 as BC (pack,unpack) import System.Console.CmdTheLine as CL import System.FilePath as FP (searchPathSeparator) newtype PathList = PathList {unPL :: [Path]} instance ArgVal ByteString where converter = let (parser,pp) = converter in (fmap BC.pack . parser, pp . BC.unpack) instance ArgVal PathList where converter = (fmap PathList . parserL, ppL . unPL) where (parserL, ppL) = list searchPathSeparator doStuff src sink authorsPath droppedPaths = do authorFilter <- maybe (return return) loadPersonRename authorsPath let fltr b = do splitBranches [ ("trunk/", "refs/heads/trunk") , ("branches/branch1/", "refs/heads/branch1") , ("branches/branch2/", "refs/heads/branch2") ] b >>= dropPaths droppedPaths >>= authorFilter runResourceT $ src $= FE.parser $= FE.filter fltr $= FE.to_bs $$ sink passthru src sink = runResourceT $ src $= FE.parseEvents $= FE.to_bs $$ sink usage prog = prog ++ " [<input file> [<output file>]]\n\n" ++ "\tFilter git fast-export stream from input to output. '-' means stdin/stdout\n" main = run $ (passthru <$> src <*> sink, termInfo) --(doStuff <$> src <*> sink <*> authorPath <*> droppedPaths, termInfo) where termInfo = defTI { termName = "git-fastexport-filter" , termDoc = "Filter git fast-export streams." , version = "0.1" } droppedPaths = fmap unPL . value $ opt (PathList []) (optInfo ["d","drop-paths"]){ optDoc = "Paths to drop, separated by " ++ [searchPathSeparator]} src = fmap (sourceHandle stdin ||| sourceFile) $ value $ pos 0 "-" posInfo{ posName = "IN", posDoc = "Path to input file. - for stdin." } sink = fmap (sinkHandle stdout ||| sinkFile) . value $ pos 1 "-" posInfo{ posName = "OUT", posDoc = "Path to output file. - for stdout" } (def ||| f) s = case s of "-" -> def _ -> f s -- authorPath = value $ opt Nothing (optInfo ["a","authors"]){ optDoc = "Path to authors file" }
lumimies/git-fastexport-filter
src-main/Git-fastexport-filter.hs
bsd-3-clause
2,436
20
17
423
686
384
302
53
2
module Domains.Negatable where class Negatable a where neg :: a -> a instance Negatable Int where neg = Prelude.negate instance Negatable Integer where neg = Prelude.negate instance Negatable Double where neg = Prelude.negate
pmilne/algebra
src/Domains/Negatable.hs
bsd-3-clause
238
0
7
45
69
37
32
9
0
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} module ErrorMessages ( tests ) where import Prelude () import Prelude.Compat import Data.Aeson (FromJSON(..), eitherDecode) import Data.Proxy (Proxy(..)) import Instances () import Numeric.Natural (Natural) import Test.Framework (Test) import Test.Framework.Providers.HUnit (testCase) import Test.HUnit (Assertion, assertFailure, assertEqual) import qualified Data.ByteString.Lazy.Char8 as L import qualified Data.HashMap.Strict as HM tests :: [Test] tests = [ testCase "Int" int , testCase "Integer" integer , testCase "Natural" natural , testCase "String" string , testCase "HashMap" hashMap ] int :: Assertion int = do let t = test (Proxy :: Proxy Int) t "\"\"" $ expected "Int" "String" t "[]" $ expected "Int" "Array" t "{}" $ expected "Int" "Object" t "null" $ expected "Int" "Null" integer :: Assertion integer = do let t = test (Proxy :: Proxy Integer) t "44.44" $ expected "Integer" "floating number 44.44" natural :: Assertion natural = do let t = test (Proxy :: Proxy Natural) t "44.44" $ expected "Natural" "floating number 44.44" t "-50" $ expected "Natural" "negative number -50" string :: Assertion string = do let t = test (Proxy :: Proxy String) t "1" $ expected "String" "Number" t "[]" $ expected "String" "Array" t "{}" $ expected "String" "Object" t "null" $ expected "String" "Null" hashMap :: Assertion hashMap = do let t = test (Proxy :: Proxy (HM.HashMap String Int)) t "\"\"" $ expected "HashMap k v" "String" t "[]" $ expected "HashMap k v" "Array" expected :: String -> String -> String expected ex enc = "Error in $: expected " ++ ex ++ ", encountered " ++ enc test :: forall a proxy . (FromJSON a, Show a) => proxy a -> L.ByteString -> String -> Assertion test _ v msg = case eitherDecode v of Left e -> assertEqual "Invalid error message" msg e Right (x :: a) -> assertFailure $ "Expected parsing to fail but it suceeded with: " ++ show x
sol/aeson
tests/ErrorMessages.hs
bsd-3-clause
2,035
0
15
412
679
345
334
58
2
module Parser where import Text.Parsec import Text.Parsec.String (Parser) import qualified Text.Parsec.Expr as Ex import qualified Text.Parsec.Token as Tok import Data.Functor.Identity import Syntax -- Tokens langDef :: Tok.LanguageDef () langDef = Tok.LanguageDef { Tok.commentStart = "{-" , Tok.commentEnd = "-}" , Tok.commentLine = "--" , Tok.nestedComments = True , Tok.identStart = letter , Tok.identLetter = alphaNum <|> oneOf "_'" , Tok.opStart = oneOf ":!#$%&*+./<=>?@\\^|-~" , Tok.opLetter = oneOf ":!#$%&*+./<=>?@\\^|-~" , Tok.reservedNames = [] , Tok.reservedOpNames = [] , Tok.caseSensitive = True } -- Lexer lexer :: Tok.TokenParser () lexer = Tok.makeTokenParser langDef parens :: Parser a -> Parser a parens = Tok.parens lexer reserved :: String -> Parser () reserved = Tok.reserved lexer semiSep :: Parser a -> Parser [a] semiSep = Tok.semiSep lexer reservedOp :: String -> Parser () reservedOp = Tok.reservedOp lexer prefixOp :: String -> (a -> a) -> Ex.Operator String () Identity a prefixOp s f = Ex.Prefix (reservedOp s >> return f) -- Prefix operators table :: Ex.OperatorTable String () Identity Expr table = [ [ prefixOp "succ" Succ , prefixOp "pred" Pred , prefixOp "iszero" IsZero ] ] -- if/then/else ifthen :: Parser Expr ifthen = do reserved "if" cond <- expr reservedOp "then" tr <- expr reservedOp "else" fl <- expr return $ If cond tr fl -- Constants true, false, zero :: Parser Expr true = reserved "true" >> return Tr false = reserved "false" >> return Fl zero = reservedOp "0" >> return Zero expr :: Parser Expr expr = Ex.buildExpressionParser table factor factor :: Parser Expr factor = true <|> false <|> zero <|> ifthen <|> parens expr contents :: Parser a -> Parser a contents p = do Tok.whiteSpace lexer r <- p eof return r parseExpr s = parse (contents expr) "<stdin>" s
zanesterling/haskell-compiler
src/TypedPeanoArithmetic/Parser.hs
bsd-3-clause
1,962
0
8
446
655
341
314
67
1
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TemplateHaskell #-} -- | Deal with downloading, cloning, or whatever else is necessary for -- getting a 'PackageLocation' into something Stack can work with. module Stack.PackageLocation ( resolveSinglePackageLocation , resolveMultiPackageLocation , loadSingleRawCabalFile , loadMultiRawCabalFiles , loadMultiRawCabalFilesIndex ) where import qualified Codec.Archive.Tar as Tar import qualified Codec.Archive.Zip as Zip import qualified Codec.Compression.GZip as GZip import Stack.Prelude import Crypto.Hash (hashWith, SHA256(..)) import qualified Data.ByteArray as Mem (convert) import qualified Data.ByteString as S import qualified Data.ByteString.Base64.URL as B64URL import qualified Data.ByteString.Lazy as L import qualified Data.Text as T import Data.Text.Encoding (encodeUtf8, decodeUtf8) import Network.HTTP.Client (parseUrlThrow) import Network.HTTP.Download.Verified import Path import Path.Extra import Path.IO import Stack.Package import Stack.Types.BuildPlan import Stack.Types.Config import Stack.Types.PackageIdentifier import qualified System.Directory as Dir import System.Process.Read import System.Process.Run -- | Same as 'resolveMultiPackageLocation', but works on a -- 'SinglePackageLocation'. resolveSinglePackageLocation :: HasConfig env => EnvOverride -> Path Abs Dir -- ^ project root -> PackageLocation FilePath -> RIO env (Path Abs Dir) resolveSinglePackageLocation _ projRoot (PLFilePath fp) = resolveDir projRoot fp resolveSinglePackageLocation _ projRoot (PLArchive (Archive url subdir msha)) = do workDir <- view workDirL -- TODO: dedupe with code for snapshot hash? let name = T.unpack $ decodeUtf8 $ S.take 12 $ B64URL.encode $ Mem.convert $ hashWith SHA256 $ encodeUtf8 url root = projRoot </> workDir </> $(mkRelDir "downloaded") fileExtension' = ".http-archive" fileRel <- parseRelFile $ name ++ fileExtension' dirRel <- parseRelDir name dirRelTmp <- parseRelDir $ name ++ ".tmp" let fileDownload = root </> fileRel dir = root </> dirRel exists <- doesDirExist dir unless exists $ do liftIO $ ignoringAbsence (removeDirRecur dir) let dirTmp = root </> dirRelTmp liftIO $ ignoringAbsence (removeDirRecur dirTmp) urlExists <- liftIO $ Dir.doesFileExist $ T.unpack url file <- if urlExists then do file <- liftIO $ Dir.canonicalizePath (T.unpack url) >>= parseAbsFile case msha of Nothing -> return () Just sha -> do actualSha <- mkStaticSHA256FromFile file when (sha /= actualSha) $ error $ concat [ "Invalid SHA256 found for local archive " , show file , "\nExpected: " , T.unpack $ staticSHA256ToText sha , "\nActual: " , T.unpack $ staticSHA256ToText actualSha ] return file else do req <- parseUrlThrow $ T.unpack url let dreq = DownloadRequest { drRequest = req , drHashChecks = case msha of Nothing -> [] Just sha -> [HashCheck { hashCheckAlgorithm = SHA256 , hashCheckHexDigest = CheckHexDigestByteString $ staticSHA256ToBase16 sha }] , drLengthCheck = Nothing -- TODO add length info? , drRetryPolicy = drRetryPolicyDefault } _ <- verifiedDownload dreq fileDownload (const $ return ()) return fileDownload let fp = toFilePath file let tryTar = do logDebug $ "Trying to untar " <> T.pack fp liftIO $ withBinaryFile fp ReadMode $ \h -> do lbs <- L.hGetContents h let entries = Tar.read $ GZip.decompress lbs Tar.unpack (toFilePath dirTmp) entries tryZip = do logDebug $ "Trying to unzip " <> T.pack fp archive <- fmap Zip.toArchive $ liftIO $ L.readFile fp liftIO $ Zip.extractFilesFromArchive [Zip.OptDestination (toFilePath dirTmp)] archive err = throwM $ UnableToExtractArchive url file catchAnyLog goodpath handler = catchAny goodpath $ \e -> do logDebug $ "Got exception: " <> T.pack (show e) handler tryTar `catchAnyLog` tryZip `catchAnyLog` err renameDir dirTmp dir x <- listDir dir case x of ([dir'], []) -> resolveDir dir' subdir (dirs, files) -> liftIO $ do ignoringAbsence (removeFile fileDownload) ignoringAbsence (removeDirRecur dir) throwIO $ UnexpectedArchiveContents dirs files resolveSinglePackageLocation menv projRoot (PLRepo (Repo url commit repoType' subdir)) = cloneRepo menv projRoot url commit repoType' >>= flip resolveDir subdir -- | Resolve a PackageLocation into a path, downloading and cloning as -- necessary. -- -- Returns the updated PackageLocation value with just a single subdir -- (if relevant). resolveMultiPackageLocation :: HasConfig env => EnvOverride -> Path Abs Dir -- ^ project root -> PackageLocation Subdirs -> RIO env [(Path Abs Dir, PackageLocation FilePath)] resolveMultiPackageLocation x y (PLFilePath fp) = do dir <- resolveSinglePackageLocation x y (PLFilePath fp) return [(dir, PLFilePath fp)] resolveMultiPackageLocation x y (PLArchive (Archive url subdirs msha)) = do dir <- resolveSinglePackageLocation x y (PLArchive (Archive url "." msha)) let subdirs' = case subdirs of DefaultSubdirs -> ["."] ExplicitSubdirs subs -> subs forM subdirs' $ \subdir -> do dir' <- resolveDir dir subdir return (dir', PLArchive (Archive url subdir msha)) resolveMultiPackageLocation menv projRoot (PLRepo (Repo url commit repoType' subdirs)) = do dir <- cloneRepo menv projRoot url commit repoType' let subdirs' = case subdirs of DefaultSubdirs -> ["."] ExplicitSubdirs subs -> subs forM subdirs' $ \subdir -> do dir' <- resolveDir dir subdir return (dir', PLRepo $ Repo url commit repoType' subdir) cloneRepo :: HasConfig env => EnvOverride -> Path Abs Dir -- ^ project root -> Text -- ^ URL -> Text -- ^ commit -> RepoType -> RIO env (Path Abs Dir) cloneRepo menv projRoot url commit repoType' = do workDir <- view workDirL let nameBeforeHashing = case repoType' of RepoGit -> T.unwords [url, commit] RepoHg -> T.unwords [url, commit, "hg"] -- TODO: dedupe with code for snapshot hash? name = T.unpack $ decodeUtf8 $ S.take 12 $ B64URL.encode $ Mem.convert $ hashWith SHA256 $ encodeUtf8 nameBeforeHashing root = projRoot </> workDir </> $(mkRelDir "downloaded") dirRel <- parseRelDir name let dir = root </> dirRel exists <- doesDirExist dir unless exists $ do liftIO $ ignoringAbsence (removeDirRecur dir) let cloneAndExtract commandName cloneArgs resetCommand = do ensureDir root logInfo $ "Cloning " <> commit <> " from " <> url callProcessInheritStderrStdout Cmd { cmdDirectoryToRunIn = Just root , cmdCommandToRun = commandName , cmdEnvOverride = menv , cmdCommandLineArguments = "clone" : cloneArgs ++ [ T.unpack url , toFilePathNoTrailingSep dir ] } created <- doesDirExist dir unless created $ throwM $ FailedToCloneRepo commandName readProcessNull (Just dir) menv commandName (resetCommand ++ [T.unpack commit, "--"]) `catch` \case ex@ProcessFailed{} -> do logInfo $ "Please ensure that commit " <> commit <> " exists within " <> url throwM ex ex -> throwM ex case repoType' of RepoGit -> cloneAndExtract "git" ["--recursive"] ["--git-dir=.git", "reset", "--hard"] RepoHg -> cloneAndExtract "hg" [] ["--repository", ".", "update", "-C"] return dir -- | Load the raw bytes in the cabal files present in the given -- 'SinglePackageLocation'. loadSingleRawCabalFile :: forall env. HasConfig env => (PackageIdentifierRevision -> IO ByteString) -- ^ lookup in index -> EnvOverride -> Path Abs Dir -- ^ project root, used for checking out necessary files -> PackageLocationIndex FilePath -> RIO env ByteString -- Need special handling of PLIndex for efficiency (just read from the -- index tarball) and correctness (get the cabal file from the index, -- not the package tarball itself, yay Hackage revisions). loadSingleRawCabalFile loadFromIndex _ _ (PLIndex pir) = liftIO $ loadFromIndex pir loadSingleRawCabalFile _ menv root (PLOther loc) = resolveSinglePackageLocation menv root loc >>= findOrGenerateCabalFile >>= liftIO . S.readFile . toFilePath -- | Same as 'loadMultiRawCabalFiles' but for 'PackageLocationIndex'. loadMultiRawCabalFilesIndex :: forall env. HasConfig env => (PackageIdentifierRevision -> IO ByteString) -- ^ lookup in index -> EnvOverride -> Path Abs Dir -- ^ project root, used for checking out necessary files -> PackageLocationIndex Subdirs -> RIO env [(ByteString, PackageLocationIndex FilePath)] -- Need special handling of PLIndex for efficiency (just read from the -- index tarball) and correctness (get the cabal file from the index, -- not the package tarball itself, yay Hackage revisions). loadMultiRawCabalFilesIndex loadFromIndex _ _ (PLIndex pir) = do bs <- liftIO $ loadFromIndex pir return [(bs, PLIndex pir)] loadMultiRawCabalFilesIndex _ x y (PLOther z) = map (second PLOther) <$> loadMultiRawCabalFiles x y z -- | Same as 'loadSingleRawCabalFile', but for 'PackageLocation' There -- may be multiple results if dealing with a repository with subdirs, -- in which case the returned 'PackageLocation' will have just the -- relevant subdirectory selected. loadMultiRawCabalFiles :: forall env. HasConfig env => EnvOverride -> Path Abs Dir -- ^ project root, used for checking out necessary files -> PackageLocation Subdirs -> RIO env [(ByteString, PackageLocation FilePath)] loadMultiRawCabalFiles menv root loc = resolveMultiPackageLocation menv root loc >>= mapM go where go (dir, loc') = do cabalFile <- findOrGenerateCabalFile dir bs <- liftIO $ S.readFile $ toFilePath cabalFile return (bs, loc')
MichielDerhaeg/stack
src/Stack/PackageLocation.hs
bsd-3-clause
11,324
8
28
3,345
2,609
1,311
1,298
228
5
module Opaleye.Internal.QueryArr where import Prelude hiding (id) import qualified Opaleye.Internal.Unpackspec as U import qualified Opaleye.Internal.Tag as Tag import Opaleye.Internal.Tag (Tag) import qualified Opaleye.Internal.PrimQuery as PQ import qualified Opaleye.Internal.HaskellDB.PrimQuery as HPQ import qualified Control.Arrow as Arr import Control.Arrow ((&&&), (***), arr) import qualified Control.Category as C import Control.Category ((<<<), id) import Control.Applicative (Applicative, pure, (<*>)) import qualified Data.Profunctor as P import qualified Data.Profunctor.Product as PP newtype QueryArr a b = QueryArr ((a, PQ.PrimQuery, Tag) -> (b, PQ.PrimQuery, Tag)) type Query = QueryArr () simpleQueryArr :: ((a, Tag) -> (b, PQ.PrimQuery, Tag)) -> QueryArr a b simpleQueryArr f = QueryArr g where g (a0, primQuery, t0) = (a1, PQ.times primQuery primQuery', t1) where (a1, primQuery', t1) = f (a0, t0) runQueryArr :: QueryArr a b -> (a, PQ.PrimQuery, Tag) -> (b, PQ.PrimQuery, Tag) runQueryArr (QueryArr f) = f runSimpleQueryArr :: QueryArr a b -> (a, Tag) -> (b, PQ.PrimQuery, Tag) runSimpleQueryArr f (a, t) = runQueryArr f (a, PQ.Unit, t) runSimpleQueryArrStart :: QueryArr a b -> a -> (b, PQ.PrimQuery, Tag) runSimpleQueryArrStart q a = runSimpleQueryArr q (a, Tag.start) runQueryArrUnpack :: U.Unpackspec a b -> Query a -> ([HPQ.PrimExpr], PQ.PrimQuery, Tag) runQueryArrUnpack unpackspec q = (primExprs, primQ, endTag) where (columns, primQ, endTag) = runSimpleQueryArrStart q () f pe = ([pe], pe) primExprs :: [HPQ.PrimExpr] (primExprs, _) = U.runUnpackspec unpackspec f columns first3 :: (a1 -> b) -> (a1, a2, a3) -> (b, a2, a3) first3 f (a1, a2, a3) = (f a1, a2, a3) instance C.Category QueryArr where id = QueryArr id QueryArr f . QueryArr g = QueryArr (f . g) instance Arr.Arrow QueryArr where arr f = QueryArr (first3 f) first f = QueryArr g where g ((b, d), primQ, t0) = ((c, d), primQ', t1) where (c, primQ', t1) = runQueryArr f (b, primQ, t0) instance Functor (QueryArr a) where fmap f = (arr f <<<) instance Applicative (QueryArr a) where pure = arr . const f <*> g = arr (uncurry ($)) <<< (f &&& g) instance P.Profunctor QueryArr where dimap f g a = arr g <<< a <<< arr f instance PP.ProductProfunctor QueryArr where empty = id (***!) = (***)
silkapp/haskell-opaleye
src/Opaleye/Internal/QueryArr.hs
bsd-3-clause
2,436
0
11
515
981
568
413
53
1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE ScopedTypeVariables #-} -- | -- Module : Data.Array.Nikola.Language.Reify -- Copyright : (c) The President and Fellows of Harvard College 2009-2010 -- Copyright : (c) Geoffrey Mainland 2012 -- License : BSD-style -- -- Maintainer : Geoffrey Mainland <[email protected]> -- Stability : experimental -- Portability : non-portable module Data.Array.Nikola.Language.Reify ( Reifiable(..), delayE, vapply ) where import Prelude hiding ((++), map, replicate, reverse) import qualified Prelude as P import Data.Typeable (Typeable) -- import Text.PrettyPrint.Mainland import Data.Array.Nikola.Array import Data.Array.Nikola.Exp import Data.Array.Nikola.Eval import Data.Array.Nikola.Repr.Global import Data.Array.Nikola.Shape import Data.Array.Nikola.Language.Generic import Data.Array.Nikola.Language.Monad import Data.Array.Nikola.Language.Sharing import qualified Data.Array.Nikola.Language.Syntax as S import Data.Array.Nikola.Language.Syntax hiding (Exp, Var) -- import Data.Array.Nikola.Pretty -- | 'Reifiable a b' mean that an 'a' can be reified as a 'b'. class Typeable a => Reifiable a b where reify :: a -> R b b -- These are the base cases instance (IsElem (Exp t a)) => Reifiable (Exp t a) S.Exp where reify e = return $ unE e instance ( Reifiable (Exp t a) S.Exp , Reifiable (Exp t b) S.Exp ) => Reifiable (Exp t a, Exp t b) S.Exp where reify (ea, eb) = return $ TupleE [unE ea, unE eb] instance Reifiable (P ()) S.Exp where reify m = m >> return (ReturnE UnitE) instance (IsElem (Exp t a)) => Reifiable (P (Exp t a)) S.Exp where reify m = m >>= returnK instance (Typeable r, Shape sh, IsElem a, Load r sh a) => Reifiable (Array r sh a) S.Exp where reify arr = do AGlobal _ arr <- computeP arr returnK $ E arr instance (Shape sh, IsElem a) => Reifiable (P (Array G sh a)) S.Exp where reify m = do AGlobal _ arr <- m returnK $ E arr returnK :: Exp t a -> P S.Exp returnK = return . ReturnE . unE -- These are the inductive cases instance (IsElem (Exp t a), Reifiable b S.Exp) => Reifiable (Exp t a -> b) S.Exp where reify f = do v <- gensym "x" lamE [(v, ScalarT tau)] $ do reify $ f (E (VarE v)) where tau :: ScalarType tau = typeOf (undefined :: Exp t a) instance (Shape sh, IsElem a, Reifiable b S.Exp) => Reifiable (Array G sh a -> b) S.Exp where reify f = do v <- gensym "arr" let n = rank (undefined :: sh) let dims = [DimE i n (VarE v) | i <- [0..n-1]] let sh = shapeOfList (P.map E dims) lamE [(v, ArrayT tau n)] $ do reify $ f (AGlobal sh (VarE v)) where tau :: ScalarType tau = typeOf (undefined :: a) instance (Shape sh, IsElem a, Reifiable b S.Exp) => Reifiable (MArray G sh a -> b) S.Exp where reify f = do v <- gensym "marr" let n = rank (undefined :: sh) let dims = [DimE i n (VarE v) | i <- [0..n-1]] let sh = shapeOfList (P.map E dims) lamE [(v, ArrayT tau n)] $ do reify $ f (MGlobal sh (VarE v)) where tau :: ScalarType tau = typeOf (undefined :: a) delayE :: Reifiable a S.Exp => a -> S.Exp delayE e = DelayedE (cacheExp e (reset (reify e >>= detectSharing ExpA))) -- | @vapply@ is a bit tricky... We first build a @DelayedE@ AST node containing -- an action that reifies the lambda. Then we wrap the result in enough -- (Haskell) lambdas and (Nikola) @AppE@ constructors to turn in back into a -- Haskell function (at the original type) whose body is a Nikola application -- term. class (Reifiable a S.Exp) => VApply a where vapply :: a -> a vapply f = vapplyk (delayE f) [] vapplyk :: S.Exp -> [S.Exp] -> a instance (IsElem (Exp t a), IsElem (Exp t b)) => VApply (Exp t a -> Exp t b) where vapplyk f es = \e -> E $ AppE f (P.reverse (unE e : es)) instance (IsElem (Exp t a), VApply (b -> c)) => VApply (Exp t a -> b -> c) where vapplyk f es = \e -> vapplyk f (unE e : es)
mainland/nikola
src/Data/Array/Nikola/Language/Reify.hs
bsd-3-clause
4,329
0
16
1,197
1,535
807
728
-1
-1
-- {-# LANGUAGE MultiParamTypeClasses #-} -- {-# LANGUAGE FlexibleInstances #-} -- {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE DataKinds #-} -- {-# LANGUAGE PolyKinds #-} -- {-# LANGUAGE TypeFamilies #-} module Opaleye.TF.Text where import qualified Opaleye.Internal.Column as Op (Column (..), binOp) import qualified Opaleye.Internal.HaskellDB.PrimQuery as Op import Opaleye.TF.BaseTypes import Opaleye.TF.Expr -- * Regular expression operators -- See https://www.postgresql.org/docs/9.5/static/functions-matching.html#FUNCTIONS-POSIX-REGEXP -- | Matches regular expression, case sensitive (~.) :: Expr s 'PGText -> Expr s 'PGText -> Expr s 'PGBoolean Expr a ~. Expr b = case Op.binOp (Op.OpOther "~.") (Op.Column a) (Op.Column b) of Op.Column c -> Expr c -- | Matches regular expression, case insensitive (~*) :: Expr s 'PGText -> Expr s 'PGText -> Expr s 'PGBoolean Expr a ~* Expr b = case Op.binOp (Op.OpOther "~*") (Op.Column a) (Op.Column b) of Op.Column c -> Expr c -- | Does not match regular expression, case sensitive (!~) :: Expr s 'PGText -> Expr s 'PGText -> Expr s 'PGBoolean Expr a !~ Expr b = case Op.binOp (Op.OpOther "!~") (Op.Column a) (Op.Column b) of Op.Column c -> Expr c -- | Does not match regular expression, case insensitive (!~*) :: Expr s 'PGText -> Expr s 'PGText -> Expr s 'PGBoolean Expr a !~* Expr b = case Op.binOp (Op.OpOther "!~*") (Op.Column a) (Op.Column b) of Op.Column c -> Expr c -- See https://www.postgresql.org/docs/9.5/static/functions-Expr s.'PGHtml -- * Standard SQL functions bitLength :: Expr s 'PGText -> Expr s 'PGInteger bitLength (Expr a) = Expr (Op.FunExpr "bit_length" [a]) charLength :: Expr s 'PGText -> Expr s 'PGInteger charLength (Expr a) = Expr (Op.FunExpr "char_length" [a]) lower :: Expr s 'PGText -> Expr s 'PGText lower (Expr a) = Expr (Op.FunExpr "lower" [a]) octetLength :: Expr s 'PGText -> Expr s 'PGInteger octetLength (Expr a) = Expr (Op.FunExpr "octet_length" [a]) upper :: Expr s 'PGText -> Expr s 'PGText upper (Expr a) = Expr (Op.FunExpr "upper" [a]) -- * PostgreSQL functions ascii :: Expr s 'PGText -> Expr s 'PGInteger ascii (Expr a) = Expr (Op.FunExpr "ascii" [a]) btrim :: Expr s 'PGText -> Maybe (Expr s 'PGText) -> Expr s 'PGText btrim (Expr a) mb = Expr (Op.FunExpr "btrim" ([a] ++ maybe [] (\(Expr x) -> [x]) mb)) chr :: Expr s 'PGInteger -> Expr s 'PGText chr (Expr a) = Expr (Op.FunExpr "chr" [a]) -- concat :: NonEmptyList (AnyExpr s) -> Expr s 'PGText -- concat = _ -- concatWs :: Expr s 'PGText -> NonEmptyList (AnyExpr s) -> Expr s 'PGText -- concatWs = _ convert :: Expr s 'PGBytea -> Expr s name -> Expr s name -> Expr s 'PGBytea convert (Expr a) (Expr b) (Expr c) = Expr (Op.FunExpr "convert" [a,b,c]) convertFrom :: Expr s 'PGBytea -> Expr s name -> Expr s 'PGText convertFrom (Expr a) (Expr b) = Expr (Op.FunExpr "convert_from" [a,b]) convertTo :: Expr s 'PGText -> Expr s name -> Expr s 'PGBytea convertTo (Expr a) (Expr b) = Expr (Op.FunExpr "convert_to" [a,b]) decode :: Expr s 'PGText -> Expr s 'PGText -> Expr s 'PGBytea decode (Expr a) (Expr b) = Expr (Op.FunExpr "decode" [a,b]) encode :: Expr s 'PGBytea -> Expr s 'PGText -> Expr s 'PGText encode (Expr a) (Expr b) = Expr (Op.FunExpr "encode" [a,b]) -- format :: Expr s 'PGText -> NonEmptyList (AnyExpr s) -> Expr s 'PGText -- format = _ initcap :: Expr s 'PGText -> Expr s 'PGText initcap (Expr a) = Expr (Op.FunExpr "initcap" [a]) left :: Expr s 'PGText -> Expr s 'PGInteger -> Expr s 'PGText left (Expr a) (Expr b) = Expr (Op.FunExpr "left" [a, b]) length :: Expr s 'PGText -> Expr s 'PGInteger length (Expr a) = Expr (Op.FunExpr "length" [a]) lengthEncoding :: Expr s 'PGBytea -> Expr s name -> Expr s 'PGInteger lengthEncoding (Expr a) (Expr b) = Expr (Op.FunExpr "length" [a,b]) lpad :: Expr s 'PGText -> Expr s 'PGInteger -> Maybe (Expr s 'PGText) -> Expr s 'PGText lpad (Expr a) (Expr b) mc = Expr (Op.FunExpr "lpad" ([a,b] ++ maybe [] (\(Expr x) -> [x]) mc)) ltrim :: Expr s 'PGText -> Maybe (Expr s 'PGText) -> Expr s 'PGText ltrim (Expr a) mb = Expr (Op.FunExpr "ltrim" ([a] ++ maybe [] (\(Expr x) -> [x]) mb)) md5 :: Expr s 'PGText -> Expr s 'PGText md5 (Expr a) = Expr (Op.FunExpr "md5" [a]) pgClientEncoding :: Expr s name pgClientEncoding = Expr (Op.FunExpr "pg_client_encoding" []) quoteIdent :: Expr s 'PGText -> Expr s 'PGText quoteIdent (Expr a) = Expr (Op.FunExpr "quote_ident" [a]) quoteLiteral :: Expr s 'PGText -> Expr s 'PGText quoteLiteral (Expr a) = Expr (Op.FunExpr "quote_literal" [a]) quoteLiteralCoerce :: Expr s a -> Expr s 'PGText quoteLiteralCoerce (Expr a) = Expr (Op.FunExpr "quote_literal_coerce" [a]) quoteNullable :: Expr s 'PGText -> Expr s 'PGText quoteNullable (Expr a) = Expr (Op.FunExpr "quote_nullable" [a]) quoteNullableCoerce :: Expr s a -> Expr s 'PGText quoteNullableCoerce (Expr a) = Expr (Op.FunExpr "quote_nullable_coerce" [a]) -- regexpMatches :: Expr s 'PGText -> Expr s 'PGText -> Maybe (Expr s 'PGText) -> Expr s (setof 'PGText) -- regexpMatches (Expr a) (Expr b) mc = Expr (Op.FunExpr "regexp_matches" ([a,b] ++ maybe [] (\(Expr x) -> [x]) mc)) regexpReplace :: Expr s 'PGText -> Expr s 'PGText -> Expr s 'PGText -> Maybe (Expr s 'PGText) -> Expr s 'PGText regexpReplace (Expr a) (Expr b) (Expr c) md = Expr (Op.FunExpr "regexp_replace" ([a,b,c] ++ maybe [] (\(Expr x) -> [x]) md)) regexpSplitToArray :: Expr s 'PGText -> Expr s 'PGText -> Maybe (Expr s 'PGText) -> Expr s 'PGText regexpSplitToArray (Expr a) (Expr b) mc = Expr (Op.FunExpr "regexp_split_to_array" ([a,b] ++ maybe [] (\(Expr x) -> [x]) mc)) -- regexpSplitToTable :: Expr s 'PGText -> Expr s 'PGText -> Maybe (Expr s 'PGText) -> Expr s (setof 'PGText) -- regexpSplitToTable (Expr a) (Expr b) mc = Expr (Op.FunExpr "regexp_split_to_table" [a,b,c]) repeat :: Expr s 'PGText -> Expr s 'PGInteger -> Expr s 'PGText repeat (Expr a) (Expr b) = Expr (Op.FunExpr "repeat" [a,b]) replace :: Expr s 'PGText -> Expr s 'PGText -> Expr s 'PGText -> Expr s 'PGText replace (Expr a) (Expr b) (Expr c) = Expr (Op.FunExpr "replace" [a,b,c]) reverse :: Expr s 'PGText -> Expr s 'PGText reverse (Expr a) = Expr (Op.FunExpr "reverse" [a]) right :: Expr s 'PGText -> Expr s 'PGInteger -> Expr s 'PGText right (Expr a) (Expr b) = Expr (Op.FunExpr "right" [a, b]) rpad :: Expr s 'PGText -> Expr s 'PGInteger -> Maybe (Expr s 'PGText) -> Expr s 'PGText rpad (Expr a) (Expr b) mc = Expr (Op.FunExpr "rpad" ([a,b] ++ maybe [] (\(Expr x) -> [x]) mc)) rtrim :: Expr s 'PGText -> Maybe (Expr s 'PGText) -> Expr s 'PGText rtrim (Expr a) mb = Expr (Op.FunExpr "rtrim" ([a] ++ maybe [] (\(Expr x) -> [x]) mb)) splitPart :: Expr s 'PGText -> Expr s 'PGText -> Expr s 'PGInteger -> Expr s 'PGText splitPart (Expr a) (Expr b) (Expr c) = Expr (Op.FunExpr "split_part" [a,b,c]) strpos :: Expr s 'PGText -> Expr s 'PGText -> Expr s 'PGInteger strpos (Expr a) (Expr b) = Expr (Op.FunExpr "strpos" [a,b]) substr :: Expr s 'PGText -> Expr s 'PGInteger -> Maybe (Expr s 'PGInteger) -> Expr s 'PGText substr (Expr str) (Expr from) mcount = Expr (Op.FunExpr "substr" ([str,from] ++ maybe [] (\(Expr x) -> [x]) mcount)) toAscii :: Expr s 'PGText -> Expr s 'PGText -> Expr s 'PGText toAscii (Expr a) (Expr b) = Expr (Op.FunExpr "toAscii" [a,b]) toHex :: Expr s 'PGInteger -> Expr s 'PGText toHex (Expr a) = Expr (Op.FunExpr "toHex" [a]) translate :: Expr s 'PGText -> Expr s 'PGText -> Expr s 'PGText -> Expr s 'PGText translate (Expr a) (Expr b) (Expr c) = Expr (Op.FunExpr "translate" [a,b,c])
ocharles/opaleye-tf
src/Opaleye/TF/Text.hs
bsd-3-clause
7,543
0
14
1,401
3,518
1,759
1,759
102
1
{-# OPTIONS_GHC -Wall #-} module Transform.Canonicalize.Type (tipe) where import Control.Arrow (second) import Control.Applicative ((<$>),(<*>)) import Control.Monad.Error import qualified Data.Map as Map import Data.Traversable (traverse) import qualified AST.Type as T import qualified AST.Variable as Var import Transform.Canonicalize.Environment import qualified Transform.Canonicalize.Variable as Canonicalize tipe :: Environment -> T.RawType -> Canonicalizer String T.CanonicalType tipe env typ = let go = tipe env in case typ of T.Var x -> return (T.Var x) T.Type _ -> canonicalizeApp env typ [] T.App t ts -> canonicalizeApp env t ts T.Lambda a b -> T.Lambda <$> go a <*> go b T.Aliased name t -> T.Aliased name <$> go t T.Record fields ext -> let go' (f,t) = (,) f <$> go t in T.Record <$> mapM go' fields <*> traverse go ext canonicalizeApp :: Environment -> T.RawType -> [T.RawType] -> Canonicalizer String T.CanonicalType canonicalizeApp env f args = case f of T.Type (Var.Raw rawName) -> do answer <- Canonicalize.tvar env rawName case answer of Right alias -> canonicalizeAlias env alias args Left name -> case args of [] -> return (T.Type name) _ -> T.App (T.Type name) <$> mapM (tipe env) args _ -> T.App <$> tipe env f <*> mapM (tipe env) args canonicalizeAlias :: Environment -> (Var.Canonical, [String], T.CanonicalType) -> [T.RawType] -> Canonicalizer String T.CanonicalType canonicalizeAlias env (name, tvars, dealiasedTipe) tipes = do when (tipesLen /= tvarsLen) (throwError msg) tipes' <- mapM (tipe env) tipes let tipe' = replace (Map.fromList (zip tvars tipes')) dealiasedTipe return $ T.Aliased name tipe' where tipesLen = length tipes tvarsLen = length tvars msg :: String msg = "Type alias '" ++ Var.toString name ++ "' expects " ++ show tvarsLen ++ " type argument" ++ (if tvarsLen == 1 then "" else "s") ++ " but was given " ++ show tipesLen replace :: Map.Map String T.CanonicalType -> T.CanonicalType -> T.CanonicalType replace typeTable t = let go = replace typeTable in case t of T.Lambda a b -> T.Lambda (go a) (go b) T.Var x -> Map.findWithDefault t x typeTable T.Record fields ext -> T.Record (map (second go) fields) (fmap go ext) T.Aliased original t' -> T.Aliased original (go t') T.Type _ -> t T.App f args -> T.App (go f) (map go args)
JoeyEremondi/utrecht-apa-p1
src/Transform/Canonicalize/Type.hs
bsd-3-clause
2,803
0
20
892
978
488
490
76
7
module Main where import Control.Exception import Control.Monad import Network.Bluetooth import Network.Socket import System.Environment import System.IO import Utils main :: IO () main = getArgs >>= \args -> case args of addr:port:_ -> withSocketsDo $ client (read addr) (read port) _ -> printUsage client :: BluetoothAddr -> BluetoothPort -> IO () client addr port = do let respLen = 4096 sock <- commentate "Calling socket" $ btSocket RFCOMM commentate ("Calling connect on address " ++ show addr ++ " and port " ++ show port) $ btConnect sock addr port let conversation :: IO () conversation = do putStr "\nPlease enter a message to send: " hFlush stdout message <- getLine when (null message) $ do putStrLn "Message must be non-empty." conversation messBytes <- commentate ("Calling send with message [" ++ message ++ "]") $ send sock message putStrLn $ "Sent message! " ++ show messBytes ++ " bytes." response <- commentate ("Calling recv with " ++ show respLen ++ " bytes") $ recv sock respLen putStrLn $ "Received response! [" ++ response ++ "]" conversation conversation `onException` close sock printUsage :: IO () printUsage = getProgName >>= putStrLn . usage usage :: String -> String usage name = unlines [ "usage: " ++ name ++ " <XX:XX:XX:XX:XX:XX> <port>" , " where XX:XX:XX:XX:XX:XX is the remote Bluetooth address to which to connect" ]
bneijt/bluetooth
examples/rfcomm-client-no-sdp/Main.hs
bsd-3-clause
1,682
0
18
550
429
207
222
40
2
module Koan.Monad where import Prelude hiding (Monad, fmap, (<$), (<$>)) enrolled :: Bool enrolled = False class Applicative m => Monad m where (>>=) :: m a -> (a -> m b) -> m b (>>) :: m a -> m b -> m b (>>) = error "TODO: Implement (>>)" return :: a -> m a return = error "TODO: Implement return" (=<<) :: Monad m => (a -> m b) -> m a -> m b (=<<) = error "TODO: Implement (==<)" (>=>) :: Monad m => (a -> m b) -> (b -> m c) -> (a -> m c) (>=>) = error "TODO: Implement (>=>)"
Kheldar/hw-koans
koan/Koan/Monad.hs
bsd-3-clause
517
0
11
147
249
135
114
14
1
-- {-# OPTIONS_GHC -fno-warn-redundant-constraints #-} {-# LANGUAGE RankNTypes, LiberalTypeSynonyms #-} -- This test checks that deep skolemisation and deep -- instantiation work right. A buggy prototype -- of GHC 7.0, where the type checker generated wrong -- code, sent applyTypeToArgs into a loop. module Twins where import Data.Data type GenericQ r = forall a. Data a => a -> r type GenericM m = forall a. Data a => a -> m a gzip :: GenericQ (GenericM Maybe) -> GenericQ (GenericM Maybe) gzip f x y = f x y `orElse` if toConstr x == toConstr y then gzipWithM (gzip f) x y else Nothing gzipWithM :: Monad m => GenericQ (GenericM m) -> GenericQ (GenericM m) gzipWithM _ = error "urk" orElse :: Maybe a -> Maybe a -> Maybe a orElse = error "urk"
rahulmutt/ghcvm
tests/suite/typecheck/compile/twins.hs
bsd-3-clause
774
0
9
163
220
114
106
16
2
{-# LANGUAGE TypeFamilies, FlexibleContexts, FlexibleInstances, MultiParamTypeClasses, RankNTypes, GADTs, ScopedTypeVariables, FunctionalDependencies, RecursiveDo, UndecidableInstances, GeneralizedNewtypeDeriving, StandaloneDeriving, EmptyDataDecls, NoMonomorphismRestriction, TypeOperators, DeriveDataTypeable, PackageImports, TemplateHaskell, LambdaCase, ConstraintKinds, CPP #-} module Reflex.Dom.Internal where import Prelude hiding (mapM, mapM_, concat, sequence, sequence_) import Reflex.Dom.Internal.Foreign import Reflex.Dom.Class import GHCJS.DOM hiding (runWebGUI) import GHCJS.DOM.Types hiding (Widget, unWidget, Event) import GHCJS.DOM.Node import GHCJS.DOM.HTMLElement import GHCJS.DOM.Document import Reflex.Class import Reflex.Host.Class import Reflex.Spider (Spider, SpiderHost (..)) import Control.Lens import Control.Monad hiding (mapM, mapM_, forM, forM_, sequence, sequence_) import Control.Monad.Reader hiding (mapM, mapM_, forM, forM_, sequence, sequence_) import Control.Monad.Ref import Control.Monad.State.Strict hiding (mapM, mapM_, forM, forM_, sequence, sequence_, get) import Control.Monad.Exception import Control.Concurrent import Control.Applicative import Data.ByteString (ByteString) import Data.Dependent.Sum (DSum (..)) import Data.Foldable import Data.Traversable import qualified Data.Text as T import Data.Text.Encoding import Data.Monoid ((<>)) data GuiEnv t h = GuiEnv { _guiEnvDocument :: !HTMLDocument , _guiEnvPostGui :: !(h () -> IO ()) , _guiEnvRunWithActions :: !([DSum (EventTrigger t)] -> h ()) , _guiEnvWebView :: !WebView } --TODO: Poorly named newtype Gui t h m a = Gui { unGui :: ReaderT (GuiEnv t h) m a } deriving (Functor, Applicative, Monad, MonadIO, MonadFix, MonadException, MonadAsyncException) runGui :: Gui t h m a -> GuiEnv t h -> m a runGui (Gui g) env = runReaderT g env instance MonadTrans (Gui t h) where lift = Gui . lift instance MonadRef m => MonadRef (Gui t h m) where type Ref (Gui t h m) = Ref m newRef = lift . newRef readRef = lift . readRef writeRef r = lift . writeRef r instance MonadAtomicRef m => MonadAtomicRef (Gui t h m) where atomicModifyRef r f = lift $ atomicModifyRef r f instance MonadSample t m => MonadSample t (Gui t h m) where sample b = lift $ sample b instance MonadHold t m => MonadHold t (Gui t h m) where hold a0 e = lift $ hold a0 e instance (Reflex t, MonadReflexCreateTrigger t m) => MonadReflexCreateTrigger t (Gui t h m) where newEventWithTrigger = lift . newEventWithTrigger newFanEventWithTrigger f = lift $ newFanEventWithTrigger f data WidgetEnv = WidgetEnv { _widgetEnvParent :: !Node } data WidgetState t m = WidgetState { _widgetStatePostBuild :: !(m ()) , _widgetStateVoidActions :: ![Event t (m ())] --TODO: Would it help to make this a strict list? } liftM concat $ mapM makeLenses [ ''WidgetEnv , ''WidgetState , ''GuiEnv ] instance Monad m => HasDocument (Gui t h m) where askDocument = Gui $ view guiEnvDocument instance HasDocument m => HasDocument (Widget t m) where askDocument = lift askDocument instance Monad m => HasWebView (Gui t h m) where askWebView = Gui $ view guiEnvWebView instance MonadIORestore m => MonadIORestore (Gui t h m) where askRestore = Gui $ do r <- askRestore return $ Restore $ restore r . unGui instance HasWebView m => HasWebView (Widget t m) where askWebView = lift askWebView instance (MonadRef h, Ref h ~ Ref m, MonadRef m) => HasPostGui t h (Gui t h m) where askPostGui = Gui $ view guiEnvPostGui askRunWithActions = Gui $ view guiEnvRunWithActions instance HasPostGui t h m => HasPostGui t h (Widget t m) where askPostGui = lift askPostGui askRunWithActions = lift askRunWithActions type WidgetInternal t m a = ReaderT WidgetEnv (StateT (WidgetState t m) m) a instance MonadTrans (Widget t) where lift = Widget . lift . lift newtype Widget t m a = Widget { unWidget :: WidgetInternal t m a } deriving (Functor, Applicative, Monad, MonadFix, MonadIO, MonadException, MonadAsyncException) instance MonadSample t m => MonadSample t (Widget t m) where sample b = lift $ sample b instance MonadHold t m => MonadHold t (Widget t m) where hold v0 e = lift $ hold v0 e -- Need to build FRP circuit first, then elements -- Can't read from FRP until the whole thing is built --TODO: Use JSString when in JS instance MonadRef m => MonadRef (Widget t m) where type Ref (Widget t m) = Ref m newRef = lift . newRef readRef = lift . readRef writeRef r = lift . writeRef r instance MonadAtomicRef m => MonadAtomicRef (Widget t m) where atomicModifyRef r f = lift $ atomicModifyRef r f instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (Widget t m) where newEventWithTrigger = lift . newEventWithTrigger newFanEventWithTrigger f = lift $ newFanEventWithTrigger f instance ( MonadRef m, Ref m ~ Ref IO, MonadRef h, Ref h ~ Ref IO --TODO: Shouldn't need to be IO , MonadIO m, MonadAsyncException m, MonadIO h, MonadAsyncException h, Functor m , ReflexHost t, MonadReflexCreateTrigger t m, MonadSample t m, MonadHold t m , MonadFix m, HasWebView h, HasPostGui t h h ) => MonadWidget t (Widget t (Gui t h m)) where type WidgetHost (Widget t (Gui t h m)) = Gui t h m type GuiAction (Widget t (Gui t h m)) = h askParent = Widget $ view widgetEnvParent --TODO: Use types to separate cohorts of possibly-recursive events/behaviors -- | Schedule an action to occur after the current cohort has been built; this is necessary because Behaviors built in the current cohort may not be read until after it is complete --schedulePostBuild :: Monad m => m () -> WidgetInternal t m () liftWidgetHost = Widget . lift . lift schedulePostBuild a = Widget $ widgetStatePostBuild %= (a>>) --TODO: Can this >> be made strict? --addVoidAction :: Monad m => Event t (m ()) -> WidgetInternal t m () addVoidAction a = Widget $ widgetStateVoidActions %= (a:) subWidget n child = Widget $ local (widgetEnvParent .~ toNode n) $ unWidget child subWidgetWithVoidActions n child = Widget $ do oldActions <- use widgetStateVoidActions widgetStateVoidActions .= [] result <- local (widgetEnvParent .~ toNode n) $ unWidget child actions <- use widgetStateVoidActions widgetStateVoidActions .= oldActions return (result, mergeWith (>>) actions) -- runWidget :: (Monad m, IsNode n, Reflex t) => n -> Widget t m a -> m (a, Event t (m ())) getRunWidget = return runWidget runWidget :: (Monad m, Reflex t, IsNode n) => n -> Widget t (Gui t h m) a -> WidgetHost (Widget t (Gui t h m)) (a, WidgetHost (Widget t (Gui t h m)) (), Event t (WidgetHost (Widget t (Gui t h m)) ())) runWidget rootElement w = do (result, WidgetState postBuild voidActions) <- runStateT (runReaderT (unWidget w) (WidgetEnv $ toNode rootElement)) (WidgetState (return ()) []) let voidAction = mergeWith (>>) voidActions return (result, postBuild, voidAction) holdOnStartup :: MonadWidget t m => a -> WidgetHost m a -> m (Behavior t a) holdOnStartup a0 ma = do (startupDone, startupDoneTriggerRef) <- newEventWithTriggerRef schedulePostBuild $ do a <- ma runFrameWithTriggerRef startupDoneTriggerRef a hold a0 startupDone mainWidget :: Widget Spider (Gui Spider (WithWebView SpiderHost) (HostFrame Spider)) () -> IO () mainWidget w = runWebGUI $ \webView -> do Just doc <- liftM (fmap castToHTMLDocument) $ webViewGetDomDocument webView Just body <- documentGetBody doc attachWidget body webView w mainWidgetWithHead :: Widget Spider (Gui Spider (WithWebView SpiderHost) (HostFrame Spider)) () -> Widget Spider (Gui Spider (WithWebView SpiderHost) (HostFrame Spider)) () -> IO () mainWidgetWithHead h b = runWebGUI $ \webView -> do Just doc <- liftM (fmap castToHTMLDocument) $ webViewGetDomDocument webView Just headElement <- liftM (fmap castToHTMLElement) $ documentGetHead doc attachWidget headElement webView h Just body <- documentGetBody doc attachWidget body webView b mainWidgetWithCss :: ByteString -> Widget Spider (Gui Spider (WithWebView SpiderHost) (HostFrame Spider)) () -> IO () mainWidgetWithCss css w = runWebGUI $ \webView -> do Just doc <- liftM (fmap castToHTMLDocument) $ webViewGetDomDocument webView Just headElement <- liftM (fmap castToHTMLElement) $ documentGetHead doc htmlElementSetInnerHTML headElement $ "<style>" <> T.unpack (decodeUtf8 css) <> "</style>" --TODO: Fix this Just body <- documentGetBody doc attachWidget body webView w newtype WithWebView m a = WithWebView { unWithWebView :: ReaderT WebView m a } deriving (Functor, Applicative, Monad, MonadIO, MonadFix, MonadException, MonadAsyncException) instance (Monad m) => HasWebView (WithWebView m) where askWebView = WithWebView ask instance HasPostGui t h m => HasPostGui t (WithWebView h) (WithWebView m) where askPostGui = do postGui <- lift askPostGui webView <- askWebView return $ \h -> postGui $ runWithWebView h webView askRunWithActions = do runWithActions <- lift askRunWithActions return $ lift . runWithActions instance HasPostGui Spider SpiderHost SpiderHost where askPostGui = return $ \h -> liftIO $ runSpiderHost h askRunWithActions = return fireEvents instance MonadTrans WithWebView where lift = WithWebView . lift instance MonadRef m => MonadRef (WithWebView m) where type Ref (WithWebView m) = Ref m newRef = lift . newRef readRef = lift . readRef writeRef r = lift . writeRef r instance MonadAtomicRef m => MonadAtomicRef (WithWebView m) where atomicModifyRef r = lift . atomicModifyRef r instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (WithWebView m) where newEventWithTrigger = lift . newEventWithTrigger newFanEventWithTrigger f = lift $ newFanEventWithTrigger f instance MonadSubscribeEvent t m => MonadSubscribeEvent t (WithWebView m) where subscribeEvent = lift . subscribeEvent instance MonadReflexHost t m => MonadReflexHost t (WithWebView m) where type ReadPhase (WithWebView m) = ReadPhase m fireEventsAndRead dm a = lift $ fireEventsAndRead dm a runHostFrame = lift . runHostFrame runWithWebView :: WithWebView m a -> WebView -> m a runWithWebView = runReaderT . unWithWebView attachWidget :: (IsHTMLElement e) => e -> WebView -> Widget Spider (Gui Spider (WithWebView SpiderHost) (HostFrame Spider)) a -> IO a attachWidget rootElement wv w = runSpiderHost $ flip runWithWebView wv $ do --TODO: It seems to re-run this handler if the URL changes, even if it's only the fragment Just doc <- liftM (fmap castToHTMLDocument) $ liftIO $ nodeGetOwnerDocument rootElement frames <- liftIO newChan rec let guiEnv = GuiEnv doc (writeChan frames . runSpiderHost . flip runWithWebView wv) runWithActions wv :: GuiEnv Spider (WithWebView SpiderHost) runWithActions dm = do voidActionNeeded <- fireEventsAndRead dm $ do sequence =<< readEvent voidActionHandle runHostFrame $ runGui (sequence_ voidActionNeeded) guiEnv Just df <- liftIO $ documentCreateDocumentFragment doc (result, voidAction) <- runHostFrame $ flip runGui guiEnv $ do (r, postBuild, va) <- runWidget df w postBuild -- This probably shouldn't be run inside the frame; we need to make sure we don't run a frame inside of a frame return (r, va) liftIO $ htmlElementSetInnerHTML rootElement "" _ <- liftIO $ nodeAppendChild rootElement $ Just df voidActionHandle <- subscribeEvent voidAction --TODO: Should be unnecessary --postGUISync seems to leak memory on GHC (unknown on GHCJS) _ <- liftIO $ forkIO $ forever $ postGUISync =<< readChan frames -- postGUISync is necessary to prevent segfaults in GTK, which is not thread-safe return result --type MonadWidget t h m = (t ~ Spider, h ~ Gui Spider SpiderHost (HostFrame Spider), m ~ Widget t h, Monad h, MonadHold t h, HasDocument h, MonadSample t h, MonadRef h, MonadIO h, Functor (Event t), Functor h, Reflex t) -- Locking down these types seems to help a little in GHCJS, but not really in GHC
nomeata/reflex-dom
src/Reflex/Dom/Internal.hs
bsd-3-clause
12,160
0
20
2,311
3,727
1,883
1,844
215
1
-- | Takes the last item from a GitHub activity feed {-# LANGUAGE OverloadedStrings #-} module NumberSix.Handlers.GitHub ( handler ) where -------------------------------------------------------------------------------- import Control.Monad.Trans (liftIO) import Data.Text (Text) import Text.XmlHtml import Text.XmlHtml.Cursor -------------------------------------------------------------------------------- import NumberSix.Bang import NumberSix.Irc import NumberSix.Message import NumberSix.Util.BitLy import NumberSix.Util.Error import NumberSix.Util.Http -------------------------------------------------------------------------------- gitHub :: Text -> IO Text gitHub query = do result <- httpScrape Xml url id $ \cursor -> do entry <- findChild (byTagName "entry") cursor title <- findChild (byTagName "title") entry link <- findRec (byTagName "link") entry href <- getAttribute "href" $ current link let text = nodeText $ current title return (text, href) case result of Just (text, href) -> textAndUrl text href Nothing -> randomError where url = "http://github.com/" <> urlEncode query <> ".atom" -------------------------------------------------------------------------------- handler :: UninitializedHandler handler = makeBangHandler "GitHub" ["!github"] $ liftIO . gitHub
itkovian/number-six
src/NumberSix/Handlers/GitHub.hs
bsd-3-clause
1,504
0
16
356
302
159
143
28
2
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances, CPP #-} -- |This module provides a text-editing widget. Edit widgets can -- operate in single- and multi-line modes. -- -- Edit widgets support the following special keystrokes: -- -- * Arrow keys to navigate the text -- -- * @Enter@ - Activate single-line edit widgets or insert new lines -- into multi-line widgets -- -- * @Home@ / @Control-a@ - Go to beginning of the current line -- -- * @End@ / @Control-e@ - Go to end of the current line -- -- * @Control-k@ - Remove text from the cursor to the end of the line, -- or remove the line if it is empty -- -- * @Del@ / @Control-d@ - delete the current character -- -- * @Backspace@ - delete the previous character -- -- Edit widgets may be configured with a line limit which limits the -- number of lines of text the widget will store. It does not provide -- any limit control on the length of its lines, though. -- -- Edit widgets support multi-column characters. (For some -- information, see <http://www.unicode.org/reports/tr11/>.) When the -- edit widget scrolling reaches a point where a wide character cannot -- be drawn because it is bisected by the editing window's boundary, -- it will be replaced with an indicator (\"$\") until the scrolling -- window is moved enough to reveal the character. This is done to -- preserve the relative alignment of all of the rows in the widget in -- the presence of characters of different widths. Note that this is -- a visual aid only and does not affect the underlying text content -- of the widget. module Graphics.Vty.Widgets.Edit ( Edit , editWidget , multiLineEditWidget , getEditText , getEditCurrentLine , setEditText , setEditRewriter , setCharFilter , getEditCursorPosition , setEditCursorPosition , setEditLineLimit , getEditLineLimit , setEditMaxLength , getEditMaxLength , applyEdit , onActivate , onChange , onCursorMove #ifdef TESTING , doClipping , indicatorChar #endif ) where import Control.Applicative ((<$>)) import Control.Monad import Data.Maybe (isJust) import qualified Data.Text as T import Graphics.Vty import Graphics.Vty.Widgets.Core import Graphics.Vty.Widgets.Events import Graphics.Vty.Widgets.Util import Graphics.Vty.Widgets.TextClip import qualified Graphics.Vty.Widgets.TextZipper as Z data Edit = Edit { contents :: Z.TextZipper T.Text , clipRect :: ClipRect , activateHandlers :: Handlers (Widget Edit) , changeHandlers :: Handlers T.Text , cursorMoveHandlers :: Handlers (Int, Int) , lineLimit :: Maybe Int , maxLength :: Maybe Int , rewriter :: Char -> Char , charFilter :: Char -> Bool } instance Show Edit where show e = concat [ "Edit { " , "contents = ", show $ contents e , ", lineLimit = ", show $ lineLimit e , ", clipRect = ", show $ clipRect e , " }" ] editWidget' :: IO (Widget Edit) editWidget' = do ahs <- newHandlers chs <- newHandlers cmhs <- newHandlers let initSt = Edit { contents = Z.textZipper [] , clipRect = ClipRect { clipLeft = 0 , clipWidth = 0 , clipTop = 0 , clipHeight = 1 } , activateHandlers = ahs , changeHandlers = chs , cursorMoveHandlers = cmhs , lineLimit = Nothing , maxLength = Nothing , rewriter = id , charFilter = const True } wRef <- newWidget initSt $ \w -> w { growHorizontal_ = const $ return True , growVertical_ = \this -> do case lineLimit this of Just v | v == 1 -> return False _ -> return True , getCursorPosition_ = internalGetCursorPosition , render_ = renderEditWidget , keyEventHandler = editKeyEvent } return wRef internalGetCursorPosition :: Widget Edit -> IO (Maybe DisplayRegion) internalGetCursorPosition this = do st <- getState this f <- focused <~ this pos <- getCurrentPosition this let (cursorRow, _) = Z.cursorPosition (contents st) Phys offset = physCursorCol st - clipLeft (clipRect st) newPos = pos `withWidth` (toEnum ((fromEnum $ regionWidth pos) + offset)) `plusHeight` (toEnum (cursorRow - (fromEnum $ clipTop $ clipRect st))) return $ if f then Just newPos else Nothing -- |Set the function which rewrites all characters at rendering time. Defaults -- to 'id'. Does not affect text stored in the editor. setEditRewriter :: Widget Edit -> (Char -> Char) -> IO () setEditRewriter w f = updateWidgetState w $ \st -> st { rewriter = f } -- |Set the function which allows typed characters in the edit widget. -- Defaults to 'const' 'True', allowing all characters. For example, setting the -- filter to ('elem' \"0123456789\") will only allow numbers in the edit widget. setCharFilter :: Widget Edit -> (Char -> Bool) -> IO () setCharFilter w f = updateWidgetState w $ \st -> st { charFilter = f } renderEditWidget :: Widget Edit -> DisplayRegion -> RenderContext -> IO Image renderEditWidget this size ctx = do resizeEdit this ( Phys $ fromEnum $ regionHeight size , Phys $ fromEnum $ regionWidth size ) st <- getState this isFocused <- focused <~ this let nAttr = mergeAttrs [ overrideAttr ctx , normalAttr ctx ] attr = if isFocused then focusAttr ctx else nAttr clipped = doClipping (Z.getText $ contents st) (clipRect st) rewritten = ((rewriter st) <$>) <$> clipped totalAllowedLines = fromEnum $ regionHeight size numEmptyLines = lim - length rewritten where lim = case lineLimit st of Just v -> min v totalAllowedLines Nothing -> totalAllowedLines emptyLines = replicate numEmptyLines "" lineWidget s = let Phys physLineLength = sum $ chWidth <$> s in string attr s <|> charFill attr ' ' (regionWidth size - toEnum physLineLength) 1 return $ vertCat $ lineWidget <$> (rewritten ++ emptyLines) doClipping :: [T.Text] -> ClipRect -> [String] doClipping ls rect = let sliced True = [indicatorChar] sliced False = "" truncatedLines = clip2d rect ls in [ sliced lslice ++ (T.unpack r) ++ sliced rslice | (r, lslice, rslice) <- truncatedLines ] -- |Convert a logical column number (corresponding to a character) to -- a physical column number (corresponding to a terminal cell). toPhysical :: Int -> [Char] -> Phys toPhysical col line = sum $ chWidth <$> take col line indicatorChar :: Char indicatorChar = '$' -- |Construct a text widget for editing a single line of text. -- Single-line edit widgets will send activation events when the user -- presses @Enter@ (see 'onActivate'). editWidget :: IO (Widget Edit) editWidget = do wRef <- editWidget' setNormalAttribute wRef $ style underline setFocusAttribute wRef $ style underline setEditLineLimit wRef $ Just 1 return wRef -- |Construct a text widget for editing multi-line documents. -- Multi-line edit widgets never send activation events, since the -- @Enter@ key inserts a new line at the cursor position. multiLineEditWidget :: IO (Widget Edit) multiLineEditWidget = do wRef <- editWidget' setEditLineLimit wRef Nothing return wRef -- |Set the limit on the number of lines for the edit widget. -- 'Nothing' indicates no limit, while 'Just' indicates a limit of the -- specified number of lines. setEditLineLimit :: Widget Edit -> Maybe Int -> IO () setEditLineLimit _ (Just v) | v <= 0 = return () setEditLineLimit w v = updateWidgetState w $ \st -> st { lineLimit = v } -- |Get the current line limit, if any, for the edit widget. getEditLineLimit :: Widget Edit -> IO (Maybe Int) getEditLineLimit = (lineLimit <~~) -- |Set the maximum length of the contents of an edit widget. Applies to every -- line of text in the editor. 'Nothing' indicates no limit, while 'Just' -- indicates a limit of the specified number of characters. setEditMaxLength :: Widget Edit -> Maybe Int -> IO () setEditMaxLength _ (Just v) | v <= 0 = return () setEditMaxLength w v = updateWidgetState w $ \st -> st { maxLength = v } -- |Get the current maximum length, if any, for the edit widget. getEditMaxLength :: Widget Edit -> IO (Maybe Int) getEditMaxLength = (maxLength <~~) resizeEdit :: Widget Edit -> (Phys, Phys) -> IO () resizeEdit e (newHeight, newWidth) = do updateWidgetState e $ \st -> let newRect = (clipRect st) { clipHeight = newHeight , clipWidth = newWidth } (cursorRow, _) = Z.cursorPosition $ contents st adjusted = updateRect (Phys cursorRow, physCursorCol st) newRect in st { clipRect = adjusted } updateWidgetState e $ \s -> let r = clipRect s (_, cursorColumn) = Z.cursorPosition $ contents s curLine = T.unpack $ Z.currentLine $ contents s (_, _, ri) = clip1d (clipLeft r) (clipWidth r) (T.pack curLine) newCharLen = if cursorColumn >= 0 && cursorColumn < length curLine then chWidth $ curLine !! cursorColumn else Phys 1 newPhysCol = toPhysical cursorColumn curLine extra = if ri && newPhysCol >= ((clipLeft r) + (clipWidth r) - Phys 1) then newCharLen - 1 else 0 newLeft = clipLeft (clipRect s) + extra in s { clipRect = (clipRect s) { clipLeft = newLeft } } -- |Register handlers to be invoked when the edit widget has been -- ''activated'' (when the user presses Enter while the widget is -- focused). These handlers will only be invoked when a single-line -- edit widget is activated; multi-line widgets never generate these -- events. onActivate :: Widget Edit -> (Widget Edit -> IO ()) -> IO () onActivate = addHandler (activateHandlers <~~) notifyActivateHandlers :: Widget Edit -> IO () notifyActivateHandlers wRef = fireEvent wRef (activateHandlers <~~) wRef notifyChangeHandlers :: Widget Edit -> IO () notifyChangeHandlers wRef = do s <- getEditText wRef fireEvent wRef (changeHandlers <~~) s notifyCursorMoveHandlers :: Widget Edit -> IO () notifyCursorMoveHandlers wRef = do pos <- getEditCursorPosition wRef fireEvent wRef (cursorMoveHandlers <~~) pos -- |Register handlers to be invoked when the edit widget's contents -- change. Handlers will be passed the new contents. onChange :: Widget Edit -> (T.Text -> IO ()) -> IO () onChange = addHandler (changeHandlers <~~) -- |Register handlers to be invoked when the edit widget's cursor -- position changes. Handlers will be passed the new cursor position, -- relative to the beginning of the text (position (0, 0)). onCursorMove :: Widget Edit -> ((Int, Int) -> IO ()) -> IO () onCursorMove = addHandler (cursorMoveHandlers <~~) -- |Get the current contents of the edit widget. This returns all of -- the lines of text in the widget, separated by newlines. getEditText :: Widget Edit -> IO T.Text getEditText = (((T.intercalate (T.pack "\n")) . Z.getText . contents) <~~) -- |Get the contents of the current line of the edit widget (the line -- on which the cursor is positioned). getEditCurrentLine :: Widget Edit -> IO T.Text getEditCurrentLine = ((Z.currentLine . contents) <~~) -- |Set the contents of the edit widget. Newlines will be used to -- break up the text in multiline widgets. If the edit widget has a -- line limit, only those lines within the limit will be set. If the edit -- widget has a line length limit, lines will be truncated. setEditText :: Widget Edit -> T.Text -> IO () setEditText wRef str = do lim <- lineLimit <~~ wRef maxL <- maxLength <~~ wRef let ls1 = case lim of Nothing -> T.lines str Just l -> take l $ T.lines str ls2 = case maxL of Nothing -> ls1 Just l -> ((T.take l) <$>) $ T.lines str updateWidgetState wRef $ \st -> st { contents = Z.textZipper ls2 } notifyChangeHandlers wRef -- |Get the edit widget's current cursor position (row, column). getEditCursorPosition :: Widget Edit -> IO (Int, Int) getEditCursorPosition = ((Z.cursorPosition . contents) <~~) -- |Set the cursor position to the specified row and column. Invalid -- cursor positions will be ignored. setEditCursorPosition :: (Int, Int) -> Widget Edit -> IO () setEditCursorPosition pos = applyEdit (Z.moveCursor pos) -- |Compute the physical cursor position (column) for the cursor in a -- given edit widget state. The physical position is relative to the -- beginning of the current line (i.e., zero, as opposed to the -- displayStart and related state). physCursorCol :: Edit -> Phys physCursorCol s = let curLine = T.unpack $ Z.currentLine $ contents s (_, cursorColumn) = Z.cursorPosition $ contents s in toPhysical cursorColumn curLine -- |Apply an editing transformation to the edit widget's text. If the -- transformation modifies the text or the cursor, the appropriate -- event handlers will be notified. If a line limit is in effect and -- the transformation violates it, the transformation will be ignored. applyEdit :: (Z.TextZipper T.Text -> Z.TextZipper T.Text) -> Widget Edit -> IO () applyEdit f this = do old <- contents <~~ this llim <- lineLimit <~~ this maxL <- maxLength <~~ this let checkLines tz = case llim of Nothing -> Just tz Just l -> if length (Z.getText tz) > l then Nothing else Just tz checkLength tz = case maxL of Nothing -> Just tz Just l -> if or ((> l) <$> (Z.lineLengths tz)) then Nothing else Just tz newContents = checkLength =<< checkLines (f old) when (isJust newContents) $ do let Just new = newContents updateWidgetState this $ \s -> s { contents = new } when (Z.getText old /= Z.getText new) $ notifyChangeHandlers this when (Z.cursorPosition old /= Z.cursorPosition new) $ notifyCursorMoveHandlers this editKeyEvent :: Widget Edit -> Key -> [Modifier] -> IO Bool editKeyEvent this k mods = do let run f = applyEdit f this >> return True case (k, mods) of (KChar 'a', [MCtrl]) -> run Z.gotoBOL (KChar 'k', [MCtrl]) -> run Z.killToEOL (KChar 'e', [MCtrl]) -> run Z.gotoEOL (KChar 'd', [MCtrl]) -> run Z.deleteChar (KLeft, []) -> run Z.moveLeft (KRight, []) -> run Z.moveRight (KUp, []) -> run Z.moveUp (KDown, []) -> run Z.moveDown (KBS, []) -> do v <- run Z.deletePrevChar when (v) $ do -- We want deletions to cause content earlier on the line(s) to -- slide in from the left rather than letting the cursor reach the -- beginning of the edit widget, preventing the user from seeing -- characters being deleted. To do this, after deletion (if we -- can) we slide the clipping window one column to the left. updateWidgetState this $ \st -> let r = clipRect st in if clipLeft r > 0 then st { clipRect = r { clipLeft = clipLeft r - Phys 1 } } else st return v (KDel, []) -> run Z.deleteChar (KChar ch, []) -> do st <- getState this if charFilter st ch then run (Z.insertChar ch) else return True -- True even if the filter rejected the character. (KHome, []) -> run Z.gotoBOL (KEnd, []) -> run Z.gotoEOL (KEnter, []) -> do lim <- lineLimit <~~ this case lim of Just 1 -> notifyActivateHandlers this >> return True _ -> run Z.breakLine _ -> return False
KommuSoft/vty-ui
src/Graphics/Vty/Widgets/Edit.hs
bsd-3-clause
16,507
0
25
4,733
3,782
1,971
1,811
267
18
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE CPP #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE OverloadedStrings #-} module Snap.Internal.Http.Server.Address ( getHostAddr , getHostAddrImpl , getSockAddr , getSockAddrImpl , getAddress , getAddressImpl , AddressNotSupportedException(..) ) where ------------------------------------------------------------------------------ #if !MIN_VERSION_base(4,8,0) import Control.Applicative ((<$>)) #endif import Control.Exception (Exception, throwIO) import Control.Monad (liftM) import Data.ByteString.Char8 (ByteString) import qualified Data.ByteString.Char8 as S import Data.Maybe (fromMaybe) import qualified Data.Text as T import qualified Data.Text.Encoding as T import Data.Typeable (Typeable) import Network.Socket (AddrInfo (addrAddress, addrFamily, addrFlags, addrSocketType), AddrInfoFlag (AI_NUMERICSERV, AI_PASSIVE), Family (AF_INET, AF_INET6), HostName, NameInfoFlag (NI_NUMERICHOST), ServiceName, SockAddr (SockAddrInet, SockAddrInet6, SockAddrUnix), SocketType (Stream), defaultHints, getAddrInfo, getNameInfo) ------------------------------------------------------------------------------ data AddressNotSupportedException = AddressNotSupportedException String deriving (Typeable) instance Show AddressNotSupportedException where show (AddressNotSupportedException x) = "Address not supported: " ++ x instance Exception AddressNotSupportedException ------------------------------------------------------------------------------ getHostAddr :: SockAddr -> IO String getHostAddr = getHostAddrImpl getNameInfo ------------------------------------------------------------------------------ getHostAddrImpl :: ([NameInfoFlag] -> Bool -> Bool -> SockAddr -> IO (Maybe HostName, Maybe ServiceName)) -> SockAddr -> IO String getHostAddrImpl !_getNameInfo addr = (fromMaybe "" . fst) `liftM` _getNameInfo [NI_NUMERICHOST] True False addr ------------------------------------------------------------------------------ getAddress :: SockAddr -> IO (Int, ByteString) getAddress = getAddressImpl getHostAddr ------------------------------------------------------------------------------ getAddressImpl :: (SockAddr -> IO String) -> SockAddr -> IO (Int, ByteString) getAddressImpl !_getHostAddr addr = case addr of SockAddrInet p _ -> host (fromIntegral p) SockAddrInet6 p _ _ _ -> host (fromIntegral p) SockAddrUnix path -> return (-1, prefix path) #if MIN_VERSION_network(2,6,0) _ -> fail "Unsupported address type" #endif where prefix path = T.encodeUtf8 $! T.pack $ "unix:" ++ path host port = (,) port . S.pack <$> _getHostAddr addr ------------------------------------------------------------------------------ getSockAddr :: Int -> ByteString -> IO (Family, SockAddr) getSockAddr = getSockAddrImpl getAddrInfo ------------------------------------------------------------------------------ getSockAddrImpl :: (Maybe AddrInfo -> Maybe String -> Maybe String -> IO [AddrInfo]) -> Int -> ByteString -> IO (Family, SockAddr) getSockAddrImpl !_getAddrInfo p s = case () of !_ | s == "*" -> getAddrs isIPv4 (Just wildhints) Nothing (Just $ show p) | s == "::" -> getAddrs isIPv6 (Just wildhints) Nothing (Just $ show p) | otherwise -> getAddrs (const True) (Just hints) (Just $ S.unpack s) (Just $ show p) where isIPv4 ai = addrFamily ai == AF_INET isIPv6 ai = addrFamily ai == AF_INET6 getAddrs flt a b c = do ais <- filter flt <$> _getAddrInfo a b c if null ais then throwIO $ AddressNotSupportedException $ show s else do let ai = head ais let fm = addrFamily ai let sa = addrAddress ai return (fm, sa) wildhints = hints { addrFlags = [AI_NUMERICSERV, AI_PASSIVE] } hints = defaultHints { addrFlags = [AI_NUMERICSERV] , addrSocketType = Stream }
sopvop/snap-server
src/Snap/Internal/Http/Server/Address.hs
bsd-3-clause
4,277
1
17
1,005
1,004
546
458
74
3
{-# LANGUAGE OverloadedStrings #-} module Format (formatString) where import qualified Data.ByteString.Char8 as B import qualified TclObj as T import Data.Char (chr) import BSParse (pchar,(.>>),choose,emit,wrapWith,parseMany,parseLit ,getPred1 ,(</>) ,pass ,parseDecInt) data Format = FInt | FStr | FChar deriving Show getFormat f v = case f of FInt -> T.asInt v >>= return . B.pack . show FStr -> return . T.asBStr $ v FChar -> T.asInt v >>= return . B.singleton . chr formatString str xl = case parseFormatStr str of Right (fl,r) -> if B.null r then construct fl xl [] >>= return . B.concat else fail "invalid format string" Left e -> fail e construct [] [] acc = return $ reverse acc construct [] _ _ = fail "extra arguments to format" construct ((Left s):xs) a acc = construct xs a (s:acc) construct _ [] _ = fail "not enough arguments to format" construct ((Right (p,f)):xs) (a:ax) acc = do s <- getFormat f a >>= return . pad p construct xs ax (s:acc) pad n s = if plen > 0 then B.append (B.replicate plen ' ') s else s where plen = n - B.length s parseFormatStr = parseMany $ choose [normal `wrapWith` Left, parseFormat `wrapWith` Right, (parseLit "%%" .>> emit "%") `wrapWith` Left] where normal = getPred1 (/= '%') "non-format" parseFormat = pchar '%' .>> choose [fstr,fchar,fint] where mk (c,v) = (padding `pass` pchar c) `wrapWith` (\p -> (p,v)) fchar = mk ('c',FChar) fstr = mk ('s', FStr) fint = mk ('d',FInt) padding = parseDecInt </> emit 0
muspellsson/hiccup
Format.hs
lgpl-2.1
1,769
0
12
566
675
366
309
39
3
----------------------------------------------------------------------------- -- | -- Module : Graphics.Rendering.OpenGL.GL.Shaders.ProgramObjects -- Copyright : (c) Sven Panne 2006-2013 -- License : BSD3 -- -- Maintainer : Sven Panne <[email protected]> -- Stability : stable -- Portability : portable -- -- This module corresponds to section 7.3 (Program Objects) of the OpenGL 4.4 -- spec. -- ----------------------------------------------------------------------------- module Graphics.Rendering.OpenGL.GL.Shaders.ProgramObjects ( -- * Program Objects Program, createProgram, programDeleteStatus, attachShader, detachShader, attachedShaders, linkProgram, linkStatus, validateProgram, validateStatus, programInfoLog, currentProgram, programSeparable, programBinaryRetrievableHint, -- TODOs: -- glCreateShaderProgramv -- ProgramInterface type (from 7.3.1) -- glGetProgramInterfaceiv -- glGetProgramResourceIndex -- glGetProgramResourceName -- glGetProgramResourceiv -- glGetProgramResourceLocation -- glGetProgramResourceLocationIndex -- * Fragment Data bindFragDataLocation, getFragDataLocation ) where import Data.List import Data.Maybe import Foreign.Marshal.Array import Foreign.Ptr import Graphics.Rendering.OpenGL.GL.ByteString import Graphics.Rendering.OpenGL.GL.Framebuffer import Graphics.Rendering.OpenGL.GL.GLboolean import Graphics.Rendering.OpenGL.GL.QueryUtils import Graphics.Rendering.OpenGL.GL.Shaders.Program import Graphics.Rendering.OpenGL.GL.Shaders.Shader import Graphics.Rendering.OpenGL.GL.StateVar import Graphics.Rendering.OpenGL.Raw -------------------------------------------------------------------------------- createProgram :: IO Program createProgram = fmap Program glCreateProgram -------------------------------------------------------------------------------- attachShader :: Program -> Shader -> IO () attachShader p s = glAttachShader (programID p) (shaderID s) detachShader :: Program -> Shader -> IO () detachShader p s = glDetachShader (programID p) (shaderID s) attachedShaders :: Program -> StateVar [Shader] attachedShaders program = makeStateVar (getAttachedShaders program) (setAttachedShaders program) getAttachedShaders :: Program -> IO [Shader] getAttachedShaders program = do numShaders <- get (numAttachedShaders program) ids <- allocaArray (fromIntegral numShaders) $ \buf -> do glGetAttachedShaders (programID program) numShaders nullPtr buf peekArray (fromIntegral numShaders) buf return $ map Shader ids setAttachedShaders :: Program -> [Shader] -> IO () setAttachedShaders program newShaders = do currentShaders <- getAttachedShaders program mapM_ (attachShader program) (newShaders \\ currentShaders) mapM_ (detachShader program) (currentShaders \\ newShaders) -------------------------------------------------------------------------------- linkProgram :: Program -> IO () linkProgram = glLinkProgram . programID currentProgram :: StateVar (Maybe Program) currentProgram = makeStateVar (do p <- fmap Program $ getInteger1 fromIntegral GetCurrentProgram return $ if p == noProgram then Nothing else Just p) (glUseProgram . programID . fromMaybe noProgram) noProgram :: Program noProgram = Program 0 validateProgram :: Program -> IO () validateProgram = glValidateProgram . programID programInfoLog :: Program -> GettableStateVar String programInfoLog = makeGettableStateVar . fmap unpackUtf8 . stringQuery programInfoLogLength (glGetProgramInfoLog . programID) -------------------------------------------------------------------------------- programSeparable :: Program -> StateVar Bool programSeparable = programStateVarBool ProgramSeparable programBinaryRetrievableHint :: Program -> StateVar Bool programBinaryRetrievableHint = programStateVarBool ProgramBinaryRetrievableHint programStateVarBool :: GetProgramPName -> Program -> StateVar Bool programStateVarBool pname program = makeStateVar (get (programVar1 unmarshalGLboolean pname program)) (glProgramParameteri (programID program) (marshalGetProgramPName pname) . marshalGLboolean) -------------------------------------------------------------------------------- programDeleteStatus :: Program -> GettableStateVar Bool programDeleteStatus = programVar1 unmarshalGLboolean ProgramDeleteStatus linkStatus :: Program -> GettableStateVar Bool linkStatus = programVar1 unmarshalGLboolean LinkStatus validateStatus :: Program -> GettableStateVar Bool validateStatus = programVar1 unmarshalGLboolean ValidateStatus programInfoLogLength :: Program -> GettableStateVar GLsizei programInfoLogLength = programVar1 fromIntegral ProgramInfoLogLength numAttachedShaders :: Program -> GettableStateVar GLsizei numAttachedShaders = programVar1 fromIntegral AttachedShaders -------------------------------------------------------------------------------- -- | 'bindFragDataLocation' binds a varying variable, specified by program and name, to a -- drawbuffer. The effects only take place after succesfull linking of the program. -- invalid arguments and conditions are -- - an index larger than maxDrawBufferIndex -- - names starting with 'gl_' -- linking failure will ocure when -- - one of the arguments was invalid -- - more than one varying varuable name is bound to the same index -- It's not an error to specify unused variables, those will be ingored. bindFragDataLocation :: Program -> String -> SettableStateVar DrawBufferIndex bindFragDataLocation (Program program) varName = makeSettableStateVar $ \ind -> withGLstring varName $ glBindFragDataLocation program ind -- | query the binding of a given variable, specified by program and name. The program has to be -- linked. The result is Nothing if an error occures or the name is not a name of a varying -- variable. If the program hasn't been linked an 'InvalidOperation' error is generated. getFragDataLocation :: Program -> String -> IO (Maybe DrawBufferIndex) getFragDataLocation (Program program) varName = do r <- withGLstring varName $ glGetFragDataLocation program if r < 0 then return Nothing else return . Just $ fromIntegral r
hesiod/OpenGL
src/Graphics/Rendering/OpenGL/GL/Shaders/ProgramObjects.hs
bsd-3-clause
6,267
0
14
902
1,067
576
491
88
2
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE NoImplicitPrelude , BangPatterns , NondecreasingIndentation #-} {-# OPTIONS_GHC -funbox-strict-fields #-} ----------------------------------------------------------------------------- -- | -- Module : GHC.IO.Encoding.Latin1 -- Copyright : (c) The University of Glasgow, 2009 -- License : see libraries/base/LICENSE -- -- Maintainer : [email protected] -- Stability : internal -- Portability : non-portable -- -- UTF-32 Codecs for the IO library -- -- Portions Copyright : (c) Tom Harper 2008-2009, -- (c) Bryan O'Sullivan 2009, -- (c) Duncan Coutts 2009 -- ----------------------------------------------------------------------------- module GHC.IO.Encoding.Latin1 ( latin1, mkLatin1, latin1_checked, mkLatin1_checked, latin1_decode, latin1_encode, latin1_checked_encode, ) where import GHC.Base import GHC.Real import GHC.Num -- import GHC.IO import GHC.IO.Buffer import GHC.IO.Encoding.Failure import GHC.IO.Encoding.Types -- ----------------------------------------------------------------------------- -- Latin1 latin1 :: TextEncoding latin1 = mkLatin1 ErrorOnCodingFailure -- | /Since: 4.4.0.0/ mkLatin1 :: CodingFailureMode -> TextEncoding mkLatin1 cfm = TextEncoding { textEncodingName = "ISO8859-1", mkTextDecoder = latin1_DF cfm, mkTextEncoder = latin1_EF cfm } latin1_DF :: CodingFailureMode -> IO (TextDecoder ()) latin1_DF cfm = return (BufferCodec { encode = latin1_decode, recover = recoverDecode cfm, close = return (), getState = return (), setState = const $ return () }) latin1_EF :: CodingFailureMode -> IO (TextEncoder ()) latin1_EF cfm = return (BufferCodec { encode = latin1_encode, recover = recoverEncode cfm, close = return (), getState = return (), setState = const $ return () }) latin1_checked :: TextEncoding latin1_checked = mkLatin1_checked ErrorOnCodingFailure -- | /Since: 4.4.0.0/ mkLatin1_checked :: CodingFailureMode -> TextEncoding mkLatin1_checked cfm = TextEncoding { textEncodingName = "ISO8859-1(checked)", mkTextDecoder = latin1_DF cfm, mkTextEncoder = latin1_checked_EF cfm } latin1_checked_EF :: CodingFailureMode -> IO (TextEncoder ()) latin1_checked_EF cfm = return (BufferCodec { encode = latin1_checked_encode, recover = recoverEncode cfm, close = return (), getState = return (), setState = const $ return () }) latin1_decode :: DecodeBuffer latin1_decode input@Buffer{ bufRaw=iraw, bufL=ir0, bufR=iw, bufSize=_ } output@Buffer{ bufRaw=oraw, bufL=_, bufR=ow0, bufSize=os } = let loop !ir !ow | ow >= os = done OutputUnderflow ir ow | ir >= iw = done InputUnderflow ir ow | otherwise = do c0 <- readWord8Buf iraw ir ow' <- writeCharBuf oraw ow (unsafeChr (fromIntegral c0)) loop (ir+1) ow' -- lambda-lifted, to avoid thunks being built in the inner-loop: done why !ir !ow = return (why, if ir == iw then input{ bufL=0, bufR=0 } else input{ bufL=ir }, output{ bufR=ow }) in loop ir0 ow0 latin1_encode :: EncodeBuffer latin1_encode input@Buffer{ bufRaw=iraw, bufL=ir0, bufR=iw, bufSize=_ } output@Buffer{ bufRaw=oraw, bufL=_, bufR=ow0, bufSize=os } = let done why !ir !ow = return (why, if ir == iw then input{ bufL=0, bufR=0 } else input{ bufL=ir }, output{ bufR=ow }) loop !ir !ow | ow >= os = done OutputUnderflow ir ow | ir >= iw = done InputUnderflow ir ow | otherwise = do (c,ir') <- readCharBuf iraw ir writeWord8Buf oraw ow (fromIntegral (ord c)) loop ir' (ow+1) in loop ir0 ow0 latin1_checked_encode :: EncodeBuffer latin1_checked_encode input@Buffer{ bufRaw=iraw, bufL=ir0, bufR=iw, bufSize=_ } output@Buffer{ bufRaw=oraw, bufL=_, bufR=ow0, bufSize=os } = let done why !ir !ow = return (why, if ir == iw then input{ bufL=0, bufR=0 } else input{ bufL=ir }, output{ bufR=ow }) loop !ir !ow | ow >= os = done OutputUnderflow ir ow | ir >= iw = done InputUnderflow ir ow | otherwise = do (c,ir') <- readCharBuf iraw ir if ord c > 0xff then invalid else do writeWord8Buf oraw ow (fromIntegral (ord c)) loop ir' (ow+1) where invalid = done InvalidSequence ir ow in loop ir0 ow0
lukexi/ghc
libraries/base/GHC/IO/Encoding/Latin1.hs
bsd-3-clause
5,132
0
19
1,719
1,300
708
592
106
3
{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses #-} ----------------------------------------------------------------------------- -- | -- Module : XMonad.Layout.TabBarDecoration -- Copyright : (c) 2007 Andrea Rossato -- License : BSD-style (see xmonad/LICENSE) -- -- Maintainer : [email protected] -- Stability : unstable -- Portability : unportable -- -- A layout modifier to add a bar of tabs to your layouts. ----------------------------------------------------------------------------- module XMonad.Layout.TabBarDecoration ( -- * Usage -- $usage simpleTabBar, tabBar , def, defaultTheme, shrinkText , TabBarDecoration (..), XPPosition (..) , module XMonad.Layout.ResizeScreen ) where import Data.List import XMonad import qualified XMonad.StackSet as S import XMonad.Layout.Decoration import XMonad.Layout.ResizeScreen import XMonad.Prompt ( XPPosition (..) ) -- $usage -- You can use this module with the following in your -- @~\/.xmonad\/xmonad.hs@: -- -- > import XMonad.Layout.TabBarDecoration -- -- Then edit your @layoutHook@ by adding the layout you want: -- -- > main = xmonad def { layoutHook = simpleTabBar $ layoutHook def} -- -- For more detailed instructions on editing the layoutHook see: -- -- "XMonad.Doc.Extending#Editing_the_layout_hook" -- -- 'tabBar' will give you the possibility of setting a custom shrinker -- and a custom theme. -- -- The deafult theme can be dynamically change with the xmonad theme -- selector. See "XMonad.Prompt.Theme". For more themse, look at -- "XMonad.Util.Themes" -- | Add, on the top of the screen, a simple bar of tabs to a given -- | layout, with the default theme and the default shrinker. simpleTabBar :: Eq a => l a -> ModifiedLayout (Decoration TabBarDecoration DefaultShrinker) (ModifiedLayout ResizeScreen l) a simpleTabBar = decoration shrinkText def (TabBar Top) . resizeVertical 20 -- | Same of 'simpleTabBar', but with the possibility of setting a -- custom shrinker, a custom theme and the position: 'Top' or -- 'Bottom'. tabBar :: (Eq a, Shrinker s) => s -> Theme -> XPPosition -> l a -> ModifiedLayout (Decoration TabBarDecoration s) l a tabBar s t p = decoration s t (TabBar p) data TabBarDecoration a = TabBar XPPosition deriving (Read, Show) instance Eq a => DecorationStyle TabBarDecoration a where describeDeco _ = "TabBar" shrink _ _ r = r decorationCatchClicksHook _ mainw _ _ = focus mainw >> return True pureDecoration (TabBar p) _ dht (Rectangle x y wh ht) s _ (w,_) = if isInStack s w then Just $ Rectangle nx ny wid (fi dht) else Nothing where wrs = S.integrate s loc i = (wh * fi i) `div` max 1 (fi $ length wrs) wid = maybe (fi x) (\i -> loc (i+1) - loc i) $ w `elemIndex` wrs ny = case p of Top -> y Bottom -> y + fi ht - fi dht nx = (x +) $ maybe 0 (fi . loc) $ w `elemIndex` wrs
pjones/xmonad-test
vendor/xmonad-contrib/XMonad/Layout/TabBarDecoration.hs
bsd-2-clause
2,993
0
16
656
603
340
263
32
1
{-# LANGUAGE TypeFamilies, DataKinds #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeApplications #-} {-# OPTIONS_GHC -fplugin GHC.TypeLits.Normalise #-} {-# OPTIONS_GHC -fplugin GHC.TypeLits.KnownNat.Solver #-} {-# OPTIONS_GHC -fconstraint-solver-iterations=20 #-} module AI.Funn.Network.Mixing (amixLayer) where import GHC.TypeLits import Control.Applicative import Data.Foldable import Data.Traversable import Data.Monoid import Data.Proxy import Data.Random import Control.DeepSeq import qualified Data.Vector.Generic as V import AI.Funn.Diff.Diff (Derivable(..), Additive(..), Diff(..)) import AI.Funn.Flat.Blob (Blob(..)) import qualified AI.Funn.Flat.Blob as Blob import qualified AI.Funn.Flat.Mixing as Diff import AI.Funn.Network.Network amixLayer :: forall s a b m. (Monad m, KnownNat s, KnownNat a, KnownNat b) => Proxy s -> Network m (Blob a) (Blob b) amixLayer proxy = Network Proxy (Diff.amixDiff proxy) initial where -- Could probably do better than this... initial = Blob.generate (normal 0 (1 / sqrt (fromIntegral s))) s = natVal (Proxy @ s)
nshepperd/funn
AI/Funn/Network/Mixing.hs
mit
1,210
0
14
270
283
172
111
26
1
{-# htermination index :: (Ordering,Ordering) -> Ordering -> Int #-}
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/full_haskell/Prelude_index_5.hs
mit
69
0
2
10
3
2
1
1
0
module Main where main :: IO () main = putStrLn "Test suite not yet implemented"
loganbraga/hunch
test/Spec.hs
mit
82
0
6
16
22
12
10
3
1
module GHCJS.DOM.NavigatorUserMediaErrorCallback ( ) where
manyoo/ghcjs-dom
ghcjs-dom-webkit/src/GHCJS/DOM/NavigatorUserMediaErrorCallback.hs
mit
61
0
3
7
10
7
3
1
0
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE DuplicateRecordFields #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE OverloadedStrings #-} module Language.LSP.Types.Progress where import Control.Monad (unless) import qualified Data.Aeson as A import Data.Aeson.TH import Data.Maybe (catMaybes) import Data.Text (Text) import Language.LSP.Types.Common import Language.LSP.Types.Utils -- | A token used to report progress back or return partial results for a -- specific request. -- @since 0.17.0.0 data ProgressToken = ProgressNumericToken Int32 | ProgressTextToken Text deriving (Show, Read, Eq, Ord) deriveJSON lspOptionsUntagged ''ProgressToken -- | Parameters for a $/progress notification. data ProgressParams t = ProgressParams { _token :: ProgressToken , _value :: t } deriving (Show, Read, Eq, Functor) deriveJSON lspOptions ''ProgressParams -- | Parameters for 'WorkDoneProgressBeginNotification'. -- -- @since 0.10.0.0 data WorkDoneProgressBeginParams = WorkDoneProgressBeginParams { -- | Mandatory title of the progress operation. -- Used to briefly inform about the kind of operation being -- performed. Examples: "Indexing" or "Linking dependencies". _title :: Text -- | Controls if a cancel button should show to allow the user to cancel the -- long running operation. Clients that don't support cancellation are allowed -- to ignore the setting. , _cancellable :: Maybe Bool -- | Optional, more detailed associated progress -- message. Contains complementary information to the -- '_title'. Examples: "3/25 files", -- "project/src/module2", "node_modules/some_dep". If -- unset, the previous progress message (if any) is -- still valid. , _message :: Maybe Text -- | Optional progress percentage to display (value 100 is considered 100%). -- If not provided infinite progress is assumed and clients are allowed -- to ignore the '_percentage' value in subsequent in report notifications. -- -- The value should be steadily rising. Clients are free to ignore values -- that are not following this rule. , _percentage :: Maybe UInt } deriving (Show, Read, Eq) instance A.ToJSON WorkDoneProgressBeginParams where toJSON WorkDoneProgressBeginParams{..} = A.object $ catMaybes [ Just $ "kind" A..= ("begin" :: Text) , Just $ "title" A..= _title , ("cancellable" A..=) <$> _cancellable , ("message" A..=) <$> _message , ("percentage" A..=) <$> _percentage ] instance A.FromJSON WorkDoneProgressBeginParams where parseJSON = A.withObject "WorkDoneProgressBegin" $ \o -> do kind <- o A..: "kind" unless (kind == ("begin" :: Text)) $ fail $ "Expected kind \"begin\" but got " ++ show kind _title <- o A..: "title" _cancellable <- o A..:? "cancellable" _message <- o A..:? "message" _percentage <- o A..:? "percentage" pure WorkDoneProgressBeginParams{..} -- The $/progress begin notification is sent from the server to the -- client to ask the client to start progress. -- -- @since 0.10.0.0 -- | Parameters for 'WorkDoneProgressReportNotification' -- -- @since 0.10.0.0 data WorkDoneProgressReportParams = WorkDoneProgressReportParams { _cancellable :: Maybe Bool -- | Optional, more detailed associated progress -- message. Contains complementary information to the -- '_title'. Examples: "3/25 files", -- "project/src/module2", "node_modules/some_dep". If -- unset, the previous progress message (if any) is -- still valid. , _message :: Maybe Text -- | Optional progress percentage to display (value 100 is considered 100%). -- If infinite progress was indicated in the start notification client -- are allowed to ignore the value. In addition the value should be steadily -- rising. Clients are free to ignore values that are not following this rule. , _percentage :: Maybe UInt } deriving (Show, Read, Eq) instance A.ToJSON WorkDoneProgressReportParams where toJSON WorkDoneProgressReportParams{..} = A.object $ catMaybes [ Just $ "kind" A..= ("report" :: Text) , ("cancellable" A..=) <$> _cancellable , ("message" A..=) <$> _message , ("percentage" A..=) <$> _percentage ] instance A.FromJSON WorkDoneProgressReportParams where parseJSON = A.withObject "WorkDoneProgressReport" $ \o -> do kind <- o A..: "kind" unless (kind == ("report" :: Text)) $ fail $ "Expected kind \"report\" but got " ++ show kind _cancellable <- o A..:? "cancellable" _message <- o A..:? "message" _percentage <- o A..:? "percentage" pure WorkDoneProgressReportParams{..} -- The workdone $/progress report notification is sent from the server to the -- client to report progress for a previously started progress. -- -- @since 0.10.0.0 -- | Parameters for 'WorkDoneProgressEndNotification'. -- -- @since 0.10.0.0 data WorkDoneProgressEndParams = WorkDoneProgressEndParams { _message :: Maybe Text } deriving (Show, Read, Eq) instance A.ToJSON WorkDoneProgressEndParams where toJSON WorkDoneProgressEndParams{..} = A.object $ catMaybes [ Just $ "kind" A..= ("end" :: Text) , ("message" A..=) <$> _message ] instance A.FromJSON WorkDoneProgressEndParams where parseJSON = A.withObject "WorkDoneProgressEnd" $ \o -> do kind <- o A..: "kind" unless (kind == ("end" :: Text)) $ fail $ "Expected kind \"end\" but got " ++ show kind _message <- o A..:? "message" pure WorkDoneProgressEndParams{..} -- The $/progress end notification is sent from the server to the -- client to stop a previously started progress. -- -- @since 0.10.0.0 -- | Parameters for 'WorkDoneProgressCancelNotification'. -- -- @since 0.10.0.0 data WorkDoneProgressCancelParams = WorkDoneProgressCancelParams { -- | A unique identifier to associate multiple progress -- notifications with the same progress. _token :: ProgressToken } deriving (Show, Read, Eq) deriveJSON lspOptions ''WorkDoneProgressCancelParams -- The window/workDoneProgress/cancel notification is sent from the client to the server -- to inform the server that the user has pressed the cancel button on the progress UX. -- A server receiving a cancel request must still close a progress using the done notification. -- -- @since 0.10.0.0 data WorkDoneProgressCreateParams = WorkDoneProgressCreateParams { _token :: ProgressToken } deriving (Show, Read, Eq) deriveJSON lspOptions ''WorkDoneProgressCreateParams data WorkDoneProgressOptions = WorkDoneProgressOptions { _workDoneProgress :: Maybe Bool } deriving (Read, Show, Eq) deriveJSON lspOptions ''WorkDoneProgressOptions data WorkDoneProgressParams = WorkDoneProgressParams { -- | An optional token that a server can use to report work done progress _workDoneToken :: Maybe ProgressToken } deriving (Read,Show,Eq) deriveJSON lspOptions ''WorkDoneProgressParams data SomeProgressParams = Begin WorkDoneProgressBeginParams | Report WorkDoneProgressReportParams | End WorkDoneProgressEndParams deriving Eq deriveJSON lspOptionsUntagged ''SomeProgressParams data PartialResultParams = PartialResultParams { -- | An optional token that a server can use to report partial results -- (e.g. streaming) to the client. _partialResultToken :: Maybe ProgressToken } deriving (Read,Show,Eq) deriveJSON lspOptions ''PartialResultParams
wz1000/haskell-lsp
lsp-types/src/Language/LSP/Types/Progress.hs
mit
7,625
0
16
1,562
1,238
689
549
115
0
-- we want to use `functionDefaults` and `globalVariableDefaults` and so on without warnings -- (maybe it would be better if llvm-hs split these out into their own types so the record updates -- would not be incomplete, but ¯\_(ツ)_/¯) {-# OPTIONS_GHC -Wno-incomplete-record-updates #-} module LLVM (translateFunctions, Module) where import MyPrelude import Data.List (transpose) import qualified Data.Char import qualified Data.Map.Strict as Map import qualified LLVM.AST as L import qualified LLVM.AST.CallingConvention as L import qualified LLVM.AST.Constant as LC import qualified LLVM.AST.Global as LG import qualified LLVM.AST.IntegerPredicate as L import LLVM.AST (Module, Definition, Global, Parameter (Parameter), BasicBlock (BasicBlock), Instruction, Terminator, Named (Do, (:=)), Operand (LocalReference, ConstantOperand)) import LLVM.AST.Constant (Constant (GlobalReference)) import LLVM.AST.Type (i1, i8, i32, i64, ptr, void) import qualified Pretty import qualified Name import qualified Type import qualified IR ---------------------------------------------------------------------------------------------------- TRANSLATION FRONTEND instance Pretty.Render Module where render = Pretty.pretty . showText outputWithStyle _ handle = hPutStr handle . showText translateFunctions :: [IR.Function] -> Module translateFunctions functions = result where result = L.defaultModule { L.moduleDefinitions = definitions } definitions = map L.GlobalDefinition (fst (runTwoPass generate)) generate :: LLVM m => m () generate = do emitGlobal externPrintf emitGlobal externScanf emitBlock "return" do let returnArg = IR.Name (IR.ID 0) Type.Int "" translateArguments [returnArg] returnValue64 <- load returnArg let instr = L.Trunc { L.operand0 = returnValue64, L.type' = i32, L.metadata = [] } returnName32 <- freshName emit (returnName32 := instr) let returnValue32 = LocalReference i32 returnName32 return (L.Ret { L.returnOperand = Just returnValue32, L.metadata' = [] }, []) emitBlock "start" do -- NOTE the name "start" is significant (to `runTwoPass`) let block = todo translateBlock block externPrintf = L.functionDefaults { LG.name = "printf", LG.parameters = ([Parameter (ptr i8) "" []], True), LG.returnType = i32 } externScanf = L.functionDefaults { LG.name = "scanf", LG.parameters = ([Parameter (ptr i8) "" []], True), LG.returnType = i32 } class Monad m => LLVM m where emitBlock :: L.Name -> m (Terminator, [CallsBlockWith]) -> m () getArguments :: m [CalledByBlockWith] emit :: Named Instruction -> m () emitAlloca :: L.Type -> L.Name -> m () emitGlobal :: Global -> m () freshName :: m L.Name data CallsBlockWith = CallsBlockWith { calledBlock :: L.Name, argumentsPassed :: [Operand] } deriving (Generic, Eq, Show) data CalledByBlockWith = CalledByBlockWith { callingBlock :: L.Name, argumentsReceived :: [Operand] } deriving (Generic, Eq, Show) translatedType :: IR.Type -> L.Type translatedType = \case Type.Bool -> i1 Type.Int -> i64 Type.Text -> ptr i8 Type.Unit -> void Type.Function argTypes returnType -> ptr (L.FunctionType (translatedType returnType) (map translatedType (filter (!= Type.Unit) argTypes)) False) allocaForLet :: IR.Name -> Operand allocaForLet (IR.Name ident nameType _) = LocalReference (ptr (translatedType nameType)) (translatedID ident) translatedID :: IR.ID -> L.Name translatedID = \case IR.ID num -> L.mkName (show num) IR.ASTName name -> L.mkName (textToString (Name.qualifiedName name)) alloca :: LLVM m => IR.Name -> m () alloca (IR.Name ident nameType _) = emitAlloca (translatedType nameType) (translatedID ident) load :: LLVM m => IR.Name -> m Operand load name = do newName <- freshName let instr = L.Load { L.volatile = False, L.address = allocaForLet name, L.maybeAtomicity = Nothing, L.alignment = 0, L.metadata = [] } emit (newName := instr) return (LocalReference (translatedType (IR.nameType name)) newName) store :: LLVM m => IR.Name -> Operand -> m () store name operand = do let instr = L.Store { L.volatile = False, L.address = allocaForLet name, L.value = operand, L.maybeAtomicity = Nothing, L.alignment = 0, L.metadata = [] } emit (Do instr) translateValue :: LLVM m => IR.Value -> m Operand translateValue = \case IR.Literal literal -> case literal of IR.Int num -> do return (number (Bits 64) (fromIntegral num)) IR.Text text -> do translateStringLiteral text IR.Named name -> do load name newtype Bits = Bits Word32 number :: Bits -> Integer -> Operand number (Bits bits) value = ConstantOperand (LC.Int { LC.integerBits = bits, LC.integerValue = value }) translateUnaryOp :: Operand -> UnaryOperator -> Instruction translateUnaryOp operand = \case Not -> L.Xor { L.operand0 = number (Bits 1) 1, L.operand1 = operand, L.metadata = [] } Negate -> L.Sub { L.operand0 = number (Bits 64) 0, L.operand1 = operand, L.metadata = [], L.nsw = False, L.nuw = False } translateBinaryOp :: Operand -> Operand -> BinaryOperator -> Instruction translateBinaryOp operand0 operand1 = \case -- TODO: Handle the UB cases :( ArithmeticOperator Add -> L.Add { L.operand0, L.operand1, L.metadata = [], L.nsw = False, L.nuw = False } ArithmeticOperator Sub -> L.Sub { L.operand0, L.operand1, L.metadata = [], L.nsw = False, L.nuw = False } ArithmeticOperator Mul -> L.Add { L.operand0, L.operand1, L.metadata = [], L.nsw = False, L.nuw = False } ArithmeticOperator Div -> L.SDiv { L.operand0, L.operand1, L.metadata = [], L.exact = False } ArithmeticOperator Mod -> L.SRem { L.operand0, L.operand1, L.metadata = [] } -- TODO: remainder vs. modulo semantics? LogicalOperator And -> L.And { L.operand0, L.operand1, L.metadata = [] } LogicalOperator Or -> L.Or { L.operand0, L.operand1, L.metadata = [] } ComparisonOperator op -> L.ICmp { L.operand0, L.operand1, L.metadata = [], L.iPredicate = predicateFor op } where predicateFor = \case Less -> L.SLT LessEqual -> L.SLE Greater -> L.SGT GreaterEqual -> L.SGE Equal -> L.EQ NotEqual -> L.NE translateExpression :: LLVM m => IR.Expression -> m Operand translateExpression expr = let localRef = LocalReference (translatedType (IR.typeOf expr)) in case expr of IR.Value value -> do translateValue value IR.UnaryOperator op value -> do operand <- translateValue value newName <- freshName emit (newName := translateUnaryOp operand op) return (localRef newName) IR.BinaryOperator value1 op value2 -> do operand1 <- translateValue value1 operand2 <- translateValue value2 newName <- freshName emit (newName := translateBinaryOp operand1 operand2 op) return (localRef newName) IR.Call fn args -> do let value = todo operand <- translateValue value printFormat <- translateStringLiteral "%s " emit (Do (call printf [printFormat, operand])) scanFormat <- translateStringLiteral "%26lld" let instr = L.Alloca { -- TODO factor this out from `emitAlloca` L.allocatedType = i64, L.numElements = Nothing, L.alignment = 0, L.metadata = [] } outputName <- freshName emit (outputName := instr) let outputPtr = LocalReference (ptr i64) outputName emit (Do (call scanf [scanFormat, outputPtr])) loadedName <- freshName let loadInstr = L.Load { -- TODO factor this out from `load` L.volatile = False, L.address = outputPtr, L.maybeAtomicity = Nothing, L.alignment = 0, L.metadata = [] } emit (loadedName := loadInstr) return (LocalReference i64 loadedName) translateStringLiteral :: LLVM m => Text -> m Operand translateStringLiteral text = do globalName <- freshName let (type', global) = stringConstant globalName text emitGlobal global ptrName <- freshName -- TODO: Should we use a Constant GetElementPtr instead? -- No we shouldn't: only the string itself needs to be part of the binary, not the pointer to it. -- If yes, can we give it the string constant directly, or do we need 2 separate globals? -- We'd need two separate ones: it expects a constant *pointer* as argument (not an array). let instr = L.GetElementPtr { L.address = ConstantOperand (GlobalReference (ptr type') globalName), L.indices = replicate 2 (number (Bits 32) 0), L.inBounds = False, L.metadata = [] } emit (ptrName := instr) return (LocalReference (ptr i8) ptrName) stringConstant :: L.Name -> Text -> (L.Type, Global) stringConstant name text = (type', globalConstant name type' constant) where type' = L.ArrayType (fromIntegral (length charList)) i8 constant = (LC.Array i8 . map (LC.Int 8 . fromIntegral . Data.Char.ord)) charList charList = textToString text ++ [Data.Char.chr 0] globalConstant :: L.Name -> L.Type -> Constant -> Global globalConstant name type' value = LG.globalVariableDefaults { LG.name = name, LG.initializer = Just value, LG.isConstant = True, LG.type' = type' } translateStatement :: LLVM m => IR.Statement -> m () translateStatement = \case IR.BlockDecl (IR.Name ident _ _) body -> do emitBlock (translatedID ident) do translateBlock body IR.Let name expr -> do alloca name operand <- translateExpression expr store name operand IR.Assign name value -> do operand <- translateValue value store name operand {- IR.Say value -> do formatPtr <- translateStringLiteral "%s\n" operand <- translateValue value emit (Do (call printf [formatPtr, operand])) IR.Write value -> do formatPtr <- translateStringLiteral "%lld\n" operand <- translateValue value emit (Do (call printf [formatPtr, operand])) -} call :: Operand -> [Operand] -> Instruction call callee args = L.Call { L.tailCallKind = Nothing, L.callingConvention = L.C, L.returnAttributes = [], L.function = Right callee, L.arguments = map (\arg -> (arg, [])) args, L.functionAttributes = [], L.metadata = [] } printf :: Operand printf = ConstantOperand (GlobalReference (ptr (L.FunctionType i32 [ptr i8] True)) "printf") scanf :: Operand scanf = ConstantOperand (GlobalReference (ptr (L.FunctionType i32 [ptr i8] True)) "scanf") translateBlock :: LLVM m => IR.Block -> m (Terminator, [CallsBlockWith]) translateBlock IR.Block { IR.arguments, IR.body, IR.transfer } = do translateArguments arguments mapM_ translateStatement body translateTransfer transfer translateArguments :: LLVM m => [IR.Name] -> m () translateArguments arguments = do -- [For each calling block: CalledByBlockWith { callingBlock = block's name, argumentsReceived = [values it passed for arguments] }] calledByBlocks <- getArguments forM_ calledByBlocks \CalledByBlockWith { argumentsReceived } -> do assertEqM (length argumentsReceived) (length arguments) -- [For each calling block: [For each argument it passed: (the argument's value, the block's name)]] let incomingValuesGroupedByBlock = map (\CalledByBlockWith { callingBlock, argumentsReceived } -> map (\operand -> (operand, callingBlock)) argumentsReceived) calledByBlocks -- [For each argument: [For each calling block: (the argument's value, the block's name)]] let incomingValuesGroupedByArg = transpose incomingValuesGroupedByBlock -- `++ repeat []` so we process all the arguments even if this block is never called (which is always the case in the FirstPass!!) forM_ (zip arguments (incomingValuesGroupedByArg ++ repeat [])) \(argument, incomingValues) -> do phiName <- freshName when (incomingValues != []) do let instr = L.Phi { L.type' = translatedType (IR.nameType argument), L.incomingValues = incomingValues, L.metadata = [] } emit (phiName := instr) -- HACK: We make an alloca for each argument, despite them never being mutated or anything, -- just so we can refer to them consistently using the `allocaForLet` mapped names, just like normal `let`s. alloca argument store argument (LocalReference (translatedType (IR.nameType argument)) phiName) translateTransfer :: LLVM m => IR.Transfer -> m (Terminator, [CallsBlockWith]) translateTransfer = \case IR.Jump target -> do callsBlockWith <- translateTarget target let instr = L.Br { L.dest = calledBlock callsBlockWith, L.metadata' = [] } return (instr, [callsBlockWith]) IR.Branch value targets -> do operand <- translateValue value assertEqM (length targets) 2 callsBlocksWith <- mapM translateTarget targets let instr = L.CondBr { L.condition = operand, L.trueDest = calledBlock (callsBlocksWith !! 1), L.falseDest = calledBlock (callsBlocksWith !! 0), L.metadata' = [] } return (instr, callsBlocksWith) translateTarget :: LLVM m => IR.Target -> m CallsBlockWith translateTarget IR.Target { IR.targetBlock, IR.targetArgs } = do operands <- mapM translateValue targetArgs return CallsBlockWith { calledBlock = translatedID (IR.nameID targetBlock), argumentsPassed = operands } ---------------------------------------------------------------------------------------------------- TRANSLATION BACKEND -- Two passes using plain state monads runTwoPass :: (forall m. LLVM m => m a) -> ([Global], a) runTwoPass generate = result where firstResult = execState (FirstState 0 Map.empty) (runFirstPass generate) secondResult = runState (SecondState 0 (callersMap firstResult) [] [] [] dummyBlock) (runSecondPass generate) dummyBlock = UnfinishedBlock (L.UnName maxBound) [] Nothing resultValue = fst secondResult SecondState { globals, allocas, finishedBlocks, unfinishedBlocks } = snd secondResult allocaBlock = BasicBlock "alloca" allocas (Do (L.Br { L.dest = "start", L.metadata' = [] })) createdFn = LG.functionDefaults { LG.name = "main", LG.returnType = i32, LG.basicBlocks = allocaBlock : finishedBlocks } result = if unfinishedBlocks == dummyBlock then (createdFn : globals, resultValue) else bug "The dummy block changed somehow!" newtype FirstPass a = FirstPass { runFirstPass :: State FirstState a } deriving (Functor, Applicative, Monad, MonadState FirstState) data FirstState = FirstState { freshNamer :: Word, callersMap :: Map L.Name [CalledByBlockWith] } deriving Generic instance LLVM FirstPass where freshName = do field @"freshNamer" += 1 num <- getM (field @"freshNamer") return (L.UnName num) emitBlock blockName bodyAction = do (_, callsBlocksWith) <- bodyAction forM_ callsBlocksWith \CallsBlockWith { calledBlock, argumentsPassed } -> do when (argumentsPassed != []) do let calledByThisBlock = CalledByBlockWith { callingBlock = blockName, argumentsReceived = argumentsPassed } modifyM (field @"callersMap") (Map.alter (Just . prepend calledByThisBlock . fromMaybe []) calledBlock) return () emit _ = return () emitAlloca _ _ = return () emitGlobal _ = return () getArguments = return [] newtype SecondPass a = SecondPass { runSecondPass :: State SecondState a } deriving (Functor, Applicative, Monad, MonadState SecondState) data SecondState = SecondState { secondNamer :: Word, callersOfBlocks :: Map L.Name [CalledByBlockWith], -- readonly allocas :: [Named Instruction], globals :: [Global], finishedBlocks :: [BasicBlock], unfinishedBlocks :: UnfinishedBlock } deriving Generic data UnfinishedBlock = UnfinishedBlock { blockName :: L.Name, instructions :: [Named Instruction], previousBlock :: Maybe UnfinishedBlock } deriving (Generic, Eq) instance LLVM SecondPass where freshName = do field @"secondNamer" += 1 num <- getM (field @"secondNamer") return (L.UnName num) emit instruction = do modifyM (field @"unfinishedBlocks" . field @"instructions") (++ [instruction]) return () emitAlloca type' name = do let instr = L.Alloca { L.allocatedType = type', L.numElements = Nothing, L.alignment = 0, L.metadata = [] } modifyM (field @"allocas") (++ [name := instr]) return () emitGlobal global = do modifyM (field @"globals") (prepend global) return () getArguments = do thisBlock <- getM (field @"unfinishedBlocks" . field @"blockName") callers <- getM (field @"callersOfBlocks") return (Map.findWithDefault [] thisBlock callers) emitBlock blockName bodyAction = do modifyM (field @"unfinishedBlocks") (UnfinishedBlock blockName [] . Just) (terminator, callsBlocksWith) <- bodyAction -- here we just assert that the `callsBlocksWith` is the same as what we got in the first pass forM_ callsBlocksWith \CallsBlockWith { calledBlock, argumentsPassed } -> do -- TODO assert that the `calledBlock` is one of those in `terminator` savedCallers <- liftM (Map.findWithDefault [] calledBlock) (getM (field @"callersOfBlocks")) let calledByUs = filter (\CalledByBlockWith { callingBlock } -> callingBlock == blockName) savedCallers -- TODO there is a probably a simpler way to express this? if argumentsPassed == [] then do assertEqM calledByUs [] else do assertEqM calledByUs [CalledByBlockWith { callingBlock = blockName, argumentsReceived = argumentsPassed }] doModifyM (field @"finishedBlocks") \finishedBlocks -> do instructions <- getM (field @"unfinishedBlocks" . field @"instructions") savedName <- getM (field @"unfinishedBlocks" . field @"blockName") assertEqM blockName savedName let newBlock = BasicBlock savedName instructions (Do terminator) return (newBlock : finishedBlocks) modifyM (field @"unfinishedBlocks" ) (assert . previousBlock) return ()
glaebhoerl/stageless
src/LLVM.hs
mit
19,549
0
22
5,251
5,491
2,848
2,643
-1
-1
{-# htermination (ltOrdering :: Ordering -> Ordering -> MyBool) #-} import qualified Prelude data MyBool = MyTrue | MyFalse data List a = Cons a (List a) | Nil data Ordering = LT | EQ | GT ; compare0 x y MyTrue = GT; otherwise :: MyBool; otherwise = MyTrue; compare1 x y MyTrue = LT; compare1 x y MyFalse = compare0 x y otherwise; ltEsOrdering :: Ordering -> Ordering -> MyBool ltEsOrdering LT LT = MyTrue; ltEsOrdering LT EQ = MyTrue; ltEsOrdering LT GT = MyTrue; ltEsOrdering EQ LT = MyFalse; ltEsOrdering EQ EQ = MyTrue; ltEsOrdering EQ GT = MyTrue; ltEsOrdering GT LT = MyFalse; ltEsOrdering GT EQ = MyFalse; ltEsOrdering GT GT = MyTrue; compare2 x y MyTrue = EQ; compare2 x y MyFalse = compare1 x y (ltEsOrdering x y); esEsOrdering :: Ordering -> Ordering -> MyBool esEsOrdering LT LT = MyTrue; esEsOrdering LT EQ = MyFalse; esEsOrdering LT GT = MyFalse; esEsOrdering EQ LT = MyFalse; esEsOrdering EQ EQ = MyTrue; esEsOrdering EQ GT = MyFalse; esEsOrdering GT LT = MyFalse; esEsOrdering GT EQ = MyFalse; esEsOrdering GT GT = MyTrue; compare3 x y = compare2 x y (esEsOrdering x y); compareOrdering :: Ordering -> Ordering -> Ordering compareOrdering x y = compare3 x y; ltOrdering :: Ordering -> Ordering -> MyBool ltOrdering x y = esEsOrdering (compareOrdering x y) LT;
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/basic_haskell/LT_6.hs
mit
1,311
0
8
262
466
253
213
36
1
module Rebase.System.IO.Error ( module System.IO.Error ) where import System.IO.Error
nikita-volkov/rebase
library/Rebase/System/IO/Error.hs
mit
89
0
5
12
23
16
7
4
0
{- - Run-length encoding of a list (direct solution). - Implement the so-called run-length encoding data compression method - directly, i.e. don't explicitly create the sublists containing the - duplicates, as in problem 9, but only count them. As in problem 11, - simplify the result list by replacing the singleton lists (1 x) by X. -} import qualified P11 encodeDirect :: (Eq a) => [a] -> [P11.Element a] encodeDirect [] = [] encodeDirect all@(x:xs) = let (block, rest) = span (==x) all in trans block : encodeDirect rest where trans (x:[]) = P11.Single x trans all@(x:xs) = P11.Multiple (length all) x
LucianU/99problems
P13.hs
mit
634
0
10
130
157
82
75
8
2
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE QuasiQuotes #-} module Dotfiles.PostInstall (postInstall) where import System.Directory import System.FilePath import System.Process import Control.Monad import Data.Maybe import Dotfiles.Core import Dotfiles.Print import Dotfiles.Process remapCapsLockToCtrl :: Config -> IO () remapCapsLockToCtrl (Config _ root' _) = do run_ "osascript" [root' </> "lib" </> "remap-capslock-to-ctrl.scpt"] success "Caps Lock mapped to CTRL!" enableWakelock :: Config -> IO () enableWakelock Config{} = do run_ "systemctl" ["--user", "enable", "wakelock.service"] success "Wakelock enabled!" postInstall :: Config -> IO () postInstall c@(Config OSX _ _) = do remapCapsLockToCtrl c postInstall c@(Config (Linux _) _ _) = enableWakelock c
owickstrom/dotfiles
src/Dotfiles/PostInstall.hs
mit
870
0
10
198
230
119
111
24
1
{- This module was generated from data in the Kate syntax highlighting file djangotemplate.xml, version 1.3, by Matthew Marshall ([email protected]) -} module Text.Highlighting.Kate.Syntax.Djangotemplate (highlight, parseExpression, syntaxName, syntaxExtensions) where import Text.Highlighting.Kate.Types import Text.Highlighting.Kate.Common import qualified Text.Highlighting.Kate.Syntax.Alert import qualified Text.Highlighting.Kate.Syntax.Css import qualified Text.Highlighting.Kate.Syntax.Javascript import Text.ParserCombinators.Parsec hiding (State) import Control.Monad.State import Data.Char (isSpace) import qualified Data.Set as Set -- | Full name of language. syntaxName :: String syntaxName = "Django HTML Template" -- | Filename extensions for this language. syntaxExtensions :: String syntaxExtensions = "*.htm;*.html" -- | Highlight source code using this syntax definition. highlight :: String -> [SourceLine] highlight input = evalState (mapM parseSourceLine $ lines input) startingState parseSourceLine :: String -> State SyntaxState SourceLine parseSourceLine = mkParseSourceLine (parseExpression Nothing) -- | Parse an expression using appropriate local context. parseExpression :: Maybe (String,String) -> KateParser Token parseExpression mbcontext = do (lang,cont) <- maybe currentContext return mbcontext result <- parseRules (lang,cont) optional $ do eof updateState $ \st -> st{ synStPrevChar = '\n' } pEndLine return result startingState = SyntaxState {synStContexts = [("Django HTML Template","Start")], synStLineNumber = 0, synStPrevChar = '\n', synStPrevNonspace = False, synStContinuation = False, synStCaseSensitive = True, synStKeywordCaseSensitive = True, synStCaptures = []} pEndLine = do updateState $ \st -> st{ synStPrevNonspace = False } context <- currentContext contexts <- synStContexts `fmap` getState st <- getState if length contexts >= 2 then case context of _ | synStContinuation st -> updateState $ \st -> st{ synStContinuation = False } ("Django HTML Template","Start") -> return () ("Django HTML Template","In Block") -> return () ("Django HTML Template","FindTemplate") -> return () ("Django HTML Template","Template Comment") -> return () ("Django HTML Template","Template Var") -> return () ("Django HTML Template","Template Filter") -> return () ("Django HTML Template","Template Tag") -> return () ("Django HTML Template","Found Block Tag") -> return () ("Django HTML Template","In Block Tag") -> return () ("Django HTML Template","Non Matching Tag") -> return () ("Django HTML Template","In Template Tag") -> return () ("Django HTML Template","Single A-string") -> return () ("Django HTML Template","Single Q-string") -> return () ("Django HTML Template","FindHTML") -> return () ("Django HTML Template","FindEntityRefs") -> return () ("Django HTML Template","FindPEntityRefs") -> return () ("Django HTML Template","FindAttributes") -> return () ("Django HTML Template","FindDTDRules") -> return () ("Django HTML Template","Comment") -> return () ("Django HTML Template","CDATA") -> return () ("Django HTML Template","PI") -> return () ("Django HTML Template","Doctype") -> return () ("Django HTML Template","Doctype Internal Subset") -> return () ("Django HTML Template","Doctype Markupdecl") -> return () ("Django HTML Template","Doctype Markupdecl DQ") -> return () ("Django HTML Template","Doctype Markupdecl SQ") -> return () ("Django HTML Template","El Open") -> return () ("Django HTML Template","El Close") -> return () ("Django HTML Template","El Close 2") -> return () ("Django HTML Template","El Close 3") -> return () ("Django HTML Template","CSS") -> return () ("Django HTML Template","CSS content") -> return () ("Django HTML Template","JS") -> return () ("Django HTML Template","JS content") -> return () ("Django HTML Template","JS comment close") -> (popContext) >> pEndLine ("Django HTML Template","Value") -> return () ("Django HTML Template","Value NQ") -> (popContext >> popContext) >> pEndLine ("Django HTML Template","Value DQ") -> return () ("Django HTML Template","Value SQ") -> return () _ -> return () else return () withAttribute attr txt = do when (null txt) $ fail "Parser matched no text" updateState $ \st -> st { synStPrevChar = last txt , synStPrevNonspace = synStPrevNonspace st || not (all isSpace txt) } return (attr, txt) list_blocktags = Set.fromList $ words $ "for block if ifequal ifnotequal ifchanged blocktrans spaceless autoescape" list_endblocktags = Set.fromList $ words $ "endfor endblock endif endifequal endifnotequal endifchanged endblocktrans endspaceless endautoescape" regex_'5c'7b'25'5cs'2aend'5ba'2dz'5d'2b'5cs'2a'25'5c'7d = compileRegex True "\\{%\\s*end[a-z]+\\s*%\\}" regex_'5c'7b'25'5cs'2acomment'5cs'2a'25'5c'7d = compileRegex True "\\{%\\s*comment\\s*%\\}" regex_'5c'7b'25'5cs'2aendcomment'5cs'2a'25'5c'7d = compileRegex True "\\{%\\s*endcomment\\s*%\\}" regex_'28'5bA'2dZa'2dz'5f'3a'5d'5b'5cw'2e'3a'5f'2d'5d'2a'29 = compileRegex True "([A-Za-z_:][\\w.:_-]*)" regex_'3c'21DOCTYPE'5cs'2b = compileRegex True "<!DOCTYPE\\s+" regex_'3c'5c'3f'5b'5cw'3a'2d'5d'2a = compileRegex True "<\\?[\\w:-]*" regex_'3cstyle'5cb = compileRegex True "<style\\b" regex_'3cscript'5cb = compileRegex True "<script\\b" regex_'3cpre'5cb = compileRegex True "<pre\\b" regex_'3cdiv'5cb = compileRegex True "<div\\b" regex_'3ctable'5cb = compileRegex True "<table\\b" regex_'3c'5bA'2dZa'2dz'5f'3a'5d'5b'5cw'2e'3a'5f'2d'5d'2a = compileRegex True "<[A-Za-z_:][\\w.:_-]*" regex_'3c'2fpre'5cb = compileRegex True "</pre\\b" regex_'3c'2fdiv'5cb = compileRegex True "</div\\b" regex_'3c'2ftable'5cb = compileRegex True "</table\\b" regex_'3c'2f'5bA'2dZa'2dz'5f'3a'5d'5b'5cw'2e'3a'5f'2d'5d'2a = compileRegex True "</[A-Za-z_:][\\w.:_-]*" regex_'26'28'23'5b0'2d9'5d'2b'7c'23'5bxX'5d'5b0'2d9A'2dFa'2df'5d'2b'7c'5bA'2dZa'2dz'5f'3a'5d'5b'5cw'2e'3a'5f'2d'5d'2a'29'3b = compileRegex True "&(#[0-9]+|#[xX][0-9A-Fa-f]+|[A-Za-z_:][\\w.:_-]*);" regex_'25'5bA'2dZa'2dz'5f'3a'5d'5b'5cw'2e'3a'5f'2d'5d'2a'3b = compileRegex True "%[A-Za-z_:][\\w.:_-]*;" regex_'5bA'2dZa'2dz'5f'3a'5d'5b'5cw'2e'3a'5f'2d'5d'2a = compileRegex True "[A-Za-z_:][\\w.:_-]*" regex_'5cs'2b'5bA'2dZa'2dz'5f'3a'5d'5b'5cw'2e'3a'5f'2d'5d'2a = compileRegex True "\\s+[A-Za-z_:][\\w.:_-]*" regex_'3c'21'28ELEMENT'7cENTITY'7cATTLIST'7cNOTATION'29'5cb = compileRegex True "<!(ELEMENT|ENTITY|ATTLIST|NOTATION)\\b" regex_'2d'28'2d'28'3f'21'2d'3e'29'29'2b = compileRegex True "-(-(?!->))+" regex_'5cS = compileRegex True "\\S" regex_'3c'2fstyle'5cb = compileRegex True "</style\\b" regex_'3c'2fscript'5cb = compileRegex True "</script\\b" regex_'2f'2f'28'3f'3d'2e'2a'3c'2fscript'5cb'29 = compileRegex True "//(?=.*</script\\b)" regex_'2f'28'3f'21'3e'29 = compileRegex True "/(?!>)" regex_'5b'5e'2f'3e'3c'22'27'5cs'5d = compileRegex True "[^/><\"'\\s]" parseRules ("Django HTML Template","Start") = (((pRegExpr regex_'5c'7b'25'5cs'2aend'5ba'2dz'5d'2b'5cs'2a'25'5c'7d >>= withAttribute ErrorTok)) <|> ((parseRules ("Django HTML Template","FindTemplate"))) <|> ((parseRules ("Django HTML Template","FindHTML"))) <|> (currentContext >>= \x -> guard (x == ("Django HTML Template","Start")) >> pDefault >>= withAttribute NormalTok)) parseRules ("Django HTML Template","In Block") = (((lookAhead (pRegExpr regex_'5c'7b'25'5cs'2aend'5ba'2dz'5d'2b'5cs'2a'25'5c'7d) >> (popContext) >> currentContext >>= parseRules)) <|> ((parseRules ("Django HTML Template","FindTemplate"))) <|> ((parseRules ("Django HTML Template","FindHTML"))) <|> (currentContext >>= \x -> guard (x == ("Django HTML Template","In Block")) >> pDefault >>= withAttribute NormalTok)) parseRules ("Django HTML Template","FindTemplate") = (((pRegExpr regex_'5c'7b'25'5cs'2acomment'5cs'2a'25'5c'7d >>= withAttribute CommentTok) >>~ pushContext ("Django HTML Template","Template Comment")) <|> ((pDetect2Chars False '{' '{' >>= withAttribute FunctionTok) >>~ pushContext ("Django HTML Template","Template Var")) <|> ((pDetect2Chars False '{' '%' >>= withAttribute FunctionTok) >>~ pushContext ("Django HTML Template","Template Tag")) <|> (currentContext >>= \x -> guard (x == ("Django HTML Template","FindTemplate")) >> pDefault >>= withAttribute NormalTok)) parseRules ("Django HTML Template","Template Comment") = (((pRegExpr regex_'5c'7b'25'5cs'2aendcomment'5cs'2a'25'5c'7d >>= withAttribute CommentTok) >>~ (popContext)) <|> (currentContext >>= \x -> guard (x == ("Django HTML Template","Template Comment")) >> pDefault >>= withAttribute CommentTok)) parseRules ("Django HTML Template","Template Var") = (((pDetect2Chars False '}' '}' >>= withAttribute FunctionTok) >>~ (popContext)) <|> ((pDetectChar False '|' >>= withAttribute OtherTok) >>~ pushContext ("Django HTML Template","Template Filter")) <|> ((pDetect2Chars False '{' '{' >>= withAttribute ErrorTok)) <|> ((pDetect2Chars False '{' '%' >>= withAttribute ErrorTok)) <|> ((pDetect2Chars False '%' '}' >>= withAttribute ErrorTok)) <|> (currentContext >>= \x -> guard (x == ("Django HTML Template","Template Var")) >> pDefault >>= withAttribute FunctionTok)) parseRules ("Django HTML Template","Template Filter") = (((pDetect2Chars False '}' '}' >>= withAttribute FunctionTok) >>~ (popContext >> popContext)) <|> ((pDetectChar False '\'' >>= withAttribute StringTok) >>~ pushContext ("Django HTML Template","Single A-string")) <|> ((pDetectChar False '"' >>= withAttribute StringTok) >>~ pushContext ("Django HTML Template","Single Q-string")) <|> ((pDetect2Chars False '{' '{' >>= withAttribute ErrorTok)) <|> ((pDetect2Chars False '{' '%' >>= withAttribute ErrorTok)) <|> ((pDetect2Chars False '%' '}' >>= withAttribute ErrorTok)) <|> (currentContext >>= \x -> guard (x == ("Django HTML Template","Template Filter")) >> pDefault >>= withAttribute OtherTok)) parseRules ("Django HTML Template","Template Tag") = (((lookAhead (pKeyword " \n\t.():!+,-<=>%&*/;?[]^{|}~\\" list_blocktags) >> pushContext ("Django HTML Template","Found Block Tag") >> currentContext >>= parseRules)) <|> ((pDetectIdentifier >>= withAttribute FunctionTok) >>~ pushContext ("Django HTML Template","In Template Tag")) <|> (currentContext >>= \x -> guard (x == ("Django HTML Template","Template Tag")) >> pDefault >>= withAttribute FunctionTok)) parseRules ("Django HTML Template","Found Block Tag") = (((pRegExpr regex_'28'5bA'2dZa'2dz'5f'3a'5d'5b'5cw'2e'3a'5f'2d'5d'2a'29 >>= withAttribute FunctionTok) >>~ pushContext ("Django HTML Template","In Block Tag")) <|> (currentContext >>= \x -> guard (x == ("Django HTML Template","Found Block Tag")) >> pDefault >>= withAttribute FunctionTok)) parseRules ("Django HTML Template","In Block Tag") = (((pRegExprDynamic "\\{%\\s*end%1\\s*%\\}" >>= withAttribute FunctionTok) >>~ (popContext >> popContext >> popContext)) <|> ((lookAhead (pRegExpr regex_'5c'7b'25'5cs'2aend'5ba'2dz'5d'2b'5cs'2a'25'5c'7d) >> pushContext ("Django HTML Template","Non Matching Tag") >> currentContext >>= parseRules)) <|> ((pDetect2Chars False '%' '}' >>= withAttribute FunctionTok) >>~ pushContext ("Django HTML Template","In Block")) <|> ((parseRules ("Django HTML Template","In Template Tag"))) <|> (currentContext >>= \x -> guard (x == ("Django HTML Template","In Block Tag")) >> pDefault >>= withAttribute FunctionTok)) parseRules ("Django HTML Template","Non Matching Tag") = (((pKeyword " \n\t.():!+,-<=>%&*/;?[]^{|}~\\" list_endblocktags >>= withAttribute ErrorTok) >>~ (popContext)) <|> ((pDetectIdentifier >>= withAttribute FunctionTok) >>~ (popContext)) <|> (currentContext >>= \x -> guard (x == ("Django HTML Template","Non Matching Tag")) >> pDefault >>= withAttribute FunctionTok)) parseRules ("Django HTML Template","In Template Tag") = (((pDetect2Chars False '%' '}' >>= withAttribute FunctionTok) >>~ (popContext >> popContext)) <|> ((pDetectChar False '\'' >>= withAttribute StringTok) >>~ pushContext ("Django HTML Template","Single A-string")) <|> ((pDetectChar False '"' >>= withAttribute StringTok) >>~ pushContext ("Django HTML Template","Single Q-string")) <|> ((pDetect2Chars False '{' '{' >>= withAttribute ErrorTok)) <|> ((pDetect2Chars False '{' '%' >>= withAttribute ErrorTok)) <|> ((pDetect2Chars False '}' '}' >>= withAttribute ErrorTok)) <|> (currentContext >>= \x -> guard (x == ("Django HTML Template","In Template Tag")) >> pDefault >>= withAttribute FunctionTok)) parseRules ("Django HTML Template","Single A-string") = (((pHlCStringChar >>= withAttribute StringTok)) <|> ((pDetectChar False '\'' >>= withAttribute StringTok) >>~ (popContext)) <|> (currentContext >>= \x -> guard (x == ("Django HTML Template","Single A-string")) >> pDefault >>= withAttribute StringTok)) parseRules ("Django HTML Template","Single Q-string") = (((pHlCStringChar >>= withAttribute StringTok)) <|> ((pDetectChar False '"' >>= withAttribute StringTok) >>~ (popContext)) <|> (currentContext >>= \x -> guard (x == ("Django HTML Template","Single Q-string")) >> pDefault >>= withAttribute StringTok)) parseRules ("Django HTML Template","FindHTML") = (((pDetectSpaces >>= withAttribute NormalTok)) <|> ((pDetectIdentifier >>= withAttribute NormalTok)) <|> ((pString False "<!--" >>= withAttribute CommentTok) >>~ pushContext ("Django HTML Template","Comment")) <|> ((pString False "<![CDATA[" >>= withAttribute BaseNTok) >>~ pushContext ("Django HTML Template","CDATA")) <|> ((pRegExpr regex_'3c'21DOCTYPE'5cs'2b >>= withAttribute DataTypeTok) >>~ pushContext ("Django HTML Template","Doctype")) <|> ((pRegExpr regex_'3c'5c'3f'5b'5cw'3a'2d'5d'2a >>= withAttribute KeywordTok) >>~ pushContext ("Django HTML Template","PI")) <|> ((pRegExpr regex_'3cstyle'5cb >>= withAttribute KeywordTok) >>~ pushContext ("Django HTML Template","CSS")) <|> ((pRegExpr regex_'3cscript'5cb >>= withAttribute KeywordTok) >>~ pushContext ("Django HTML Template","JS")) <|> ((pRegExpr regex_'3cpre'5cb >>= withAttribute KeywordTok) >>~ pushContext ("Django HTML Template","El Open")) <|> ((pRegExpr regex_'3cdiv'5cb >>= withAttribute KeywordTok) >>~ pushContext ("Django HTML Template","El Open")) <|> ((pRegExpr regex_'3ctable'5cb >>= withAttribute KeywordTok) >>~ pushContext ("Django HTML Template","El Open")) <|> ((pRegExpr regex_'3c'5bA'2dZa'2dz'5f'3a'5d'5b'5cw'2e'3a'5f'2d'5d'2a >>= withAttribute KeywordTok) >>~ pushContext ("Django HTML Template","El Open")) <|> ((pRegExpr regex_'3c'2fpre'5cb >>= withAttribute KeywordTok) >>~ pushContext ("Django HTML Template","El Close")) <|> ((pRegExpr regex_'3c'2fdiv'5cb >>= withAttribute KeywordTok) >>~ pushContext ("Django HTML Template","El Close")) <|> ((pRegExpr regex_'3c'2ftable'5cb >>= withAttribute KeywordTok) >>~ pushContext ("Django HTML Template","El Close")) <|> ((pRegExpr regex_'3c'2f'5bA'2dZa'2dz'5f'3a'5d'5b'5cw'2e'3a'5f'2d'5d'2a >>= withAttribute KeywordTok) >>~ pushContext ("Django HTML Template","El Close")) <|> ((parseRules ("Django HTML Template","FindDTDRules"))) <|> ((parseRules ("Django HTML Template","FindEntityRefs"))) <|> (currentContext >>= \x -> guard (x == ("Django HTML Template","FindHTML")) >> pDefault >>= withAttribute NormalTok)) parseRules ("Django HTML Template","FindEntityRefs") = (((pRegExpr regex_'26'28'23'5b0'2d9'5d'2b'7c'23'5bxX'5d'5b0'2d9A'2dFa'2df'5d'2b'7c'5bA'2dZa'2dz'5f'3a'5d'5b'5cw'2e'3a'5f'2d'5d'2a'29'3b >>= withAttribute DecValTok)) <|> ((pAnyChar "&<" >>= withAttribute ErrorTok)) <|> (currentContext >>= \x -> guard (x == ("Django HTML Template","FindEntityRefs")) >> pDefault >>= withAttribute NormalTok)) parseRules ("Django HTML Template","FindPEntityRefs") = (((pRegExpr regex_'26'28'23'5b0'2d9'5d'2b'7c'23'5bxX'5d'5b0'2d9A'2dFa'2df'5d'2b'7c'5bA'2dZa'2dz'5f'3a'5d'5b'5cw'2e'3a'5f'2d'5d'2a'29'3b >>= withAttribute DecValTok)) <|> ((pRegExpr regex_'25'5bA'2dZa'2dz'5f'3a'5d'5b'5cw'2e'3a'5f'2d'5d'2a'3b >>= withAttribute DecValTok)) <|> ((pAnyChar "&%" >>= withAttribute ErrorTok)) <|> (currentContext >>= \x -> guard (x == ("Django HTML Template","FindPEntityRefs")) >> pDefault >>= withAttribute NormalTok)) parseRules ("Django HTML Template","FindAttributes") = (((pColumn 0 >> pRegExpr regex_'5bA'2dZa'2dz'5f'3a'5d'5b'5cw'2e'3a'5f'2d'5d'2a >>= withAttribute OtherTok)) <|> ((pRegExpr regex_'5cs'2b'5bA'2dZa'2dz'5f'3a'5d'5b'5cw'2e'3a'5f'2d'5d'2a >>= withAttribute OtherTok)) <|> ((pDetectChar False '=' >>= withAttribute OtherTok) >>~ pushContext ("Django HTML Template","Value")) <|> (currentContext >>= \x -> guard (x == ("Django HTML Template","FindAttributes")) >> pDefault >>= withAttribute NormalTok)) parseRules ("Django HTML Template","FindDTDRules") = (((pRegExpr regex_'3c'21'28ELEMENT'7cENTITY'7cATTLIST'7cNOTATION'29'5cb >>= withAttribute DataTypeTok) >>~ pushContext ("Django HTML Template","Doctype Markupdecl")) <|> (currentContext >>= \x -> guard (x == ("Django HTML Template","FindDTDRules")) >> pDefault >>= withAttribute NormalTok)) parseRules ("Django HTML Template","Comment") = (((pDetectSpaces >>= withAttribute CommentTok)) <|> ((Text.Highlighting.Kate.Syntax.Alert.parseExpression (Just ("Alerts","")) >>= ((withAttribute CommentTok) . snd))) <|> ((parseRules ("Django HTML Template","FindTemplate"))) <|> ((pDetectIdentifier >>= withAttribute CommentTok)) <|> ((pString False "-->" >>= withAttribute CommentTok) >>~ (popContext)) <|> ((pRegExpr regex_'2d'28'2d'28'3f'21'2d'3e'29'29'2b >>= withAttribute ErrorTok)) <|> (currentContext >>= \x -> guard (x == ("Django HTML Template","Comment")) >> pDefault >>= withAttribute CommentTok)) parseRules ("Django HTML Template","CDATA") = (((pDetectSpaces >>= withAttribute NormalTok)) <|> ((pDetectIdentifier >>= withAttribute NormalTok)) <|> ((pString False "]]>" >>= withAttribute BaseNTok) >>~ (popContext)) <|> ((pString False "]]&gt;" >>= withAttribute DecValTok)) <|> (currentContext >>= \x -> guard (x == ("Django HTML Template","CDATA")) >> pDefault >>= withAttribute NormalTok)) parseRules ("Django HTML Template","PI") = (((pDetect2Chars False '?' '>' >>= withAttribute KeywordTok) >>~ (popContext)) <|> (currentContext >>= \x -> guard (x == ("Django HTML Template","PI")) >> pDefault >>= withAttribute NormalTok)) parseRules ("Django HTML Template","Doctype") = (((pDetectChar False '>' >>= withAttribute DataTypeTok) >>~ (popContext)) <|> ((pDetectChar False '[' >>= withAttribute DataTypeTok) >>~ pushContext ("Django HTML Template","Doctype Internal Subset")) <|> (currentContext >>= \x -> guard (x == ("Django HTML Template","Doctype")) >> pDefault >>= withAttribute NormalTok)) parseRules ("Django HTML Template","Doctype Internal Subset") = (((pDetectChar False ']' >>= withAttribute DataTypeTok) >>~ (popContext)) <|> ((parseRules ("Django HTML Template","FindDTDRules"))) <|> ((pString False "<!--" >>= withAttribute CommentTok) >>~ pushContext ("Django HTML Template","Comment")) <|> ((pRegExpr regex_'3c'5c'3f'5b'5cw'3a'2d'5d'2a >>= withAttribute KeywordTok) >>~ pushContext ("Django HTML Template","PI")) <|> ((parseRules ("Django HTML Template","FindPEntityRefs"))) <|> (currentContext >>= \x -> guard (x == ("Django HTML Template","Doctype Internal Subset")) >> pDefault >>= withAttribute NormalTok)) parseRules ("Django HTML Template","Doctype Markupdecl") = (((pDetectChar False '>' >>= withAttribute DataTypeTok) >>~ (popContext)) <|> ((pDetectChar False '"' >>= withAttribute StringTok) >>~ pushContext ("Django HTML Template","Doctype Markupdecl DQ")) <|> ((pDetectChar False '\'' >>= withAttribute StringTok) >>~ pushContext ("Django HTML Template","Doctype Markupdecl SQ")) <|> (currentContext >>= \x -> guard (x == ("Django HTML Template","Doctype Markupdecl")) >> pDefault >>= withAttribute NormalTok)) parseRules ("Django HTML Template","Doctype Markupdecl DQ") = (((pDetectChar False '"' >>= withAttribute StringTok) >>~ (popContext)) <|> ((parseRules ("Django HTML Template","FindPEntityRefs"))) <|> (currentContext >>= \x -> guard (x == ("Django HTML Template","Doctype Markupdecl DQ")) >> pDefault >>= withAttribute StringTok)) parseRules ("Django HTML Template","Doctype Markupdecl SQ") = (((pDetectChar False '\'' >>= withAttribute StringTok) >>~ (popContext)) <|> ((parseRules ("Django HTML Template","FindPEntityRefs"))) <|> (currentContext >>= \x -> guard (x == ("Django HTML Template","Doctype Markupdecl SQ")) >> pDefault >>= withAttribute StringTok)) parseRules ("Django HTML Template","El Open") = (((pDetect2Chars False '/' '>' >>= withAttribute KeywordTok) >>~ (popContext)) <|> ((pDetectChar False '>' >>= withAttribute KeywordTok) >>~ (popContext)) <|> ((parseRules ("Django HTML Template","FindAttributes"))) <|> ((parseRules ("Django HTML Template","FindTemplate"))) <|> ((pRegExpr regex_'5cS >>= withAttribute ErrorTok)) <|> (currentContext >>= \x -> guard (x == ("Django HTML Template","El Open")) >> pDefault >>= withAttribute NormalTok)) parseRules ("Django HTML Template","El Close") = (((pDetectChar False '>' >>= withAttribute KeywordTok) >>~ (popContext)) <|> ((pRegExpr regex_'5cS >>= withAttribute ErrorTok)) <|> (currentContext >>= \x -> guard (x == ("Django HTML Template","El Close")) >> pDefault >>= withAttribute NormalTok)) parseRules ("Django HTML Template","El Close 2") = (((pDetectChar False '>' >>= withAttribute KeywordTok) >>~ (popContext >> popContext >> popContext)) <|> ((pRegExpr regex_'5cS >>= withAttribute ErrorTok)) <|> (currentContext >>= \x -> guard (x == ("Django HTML Template","El Close 2")) >> pDefault >>= withAttribute NormalTok)) parseRules ("Django HTML Template","El Close 3") = (((pDetectChar False '>' >>= withAttribute KeywordTok) >>~ (popContext >> popContext >> popContext >> popContext)) <|> ((pRegExpr regex_'5cS >>= withAttribute ErrorTok)) <|> (currentContext >>= \x -> guard (x == ("Django HTML Template","El Close 3")) >> pDefault >>= withAttribute NormalTok)) parseRules ("Django HTML Template","CSS") = (((pDetect2Chars False '/' '>' >>= withAttribute KeywordTok) >>~ (popContext)) <|> ((pDetectChar False '>' >>= withAttribute KeywordTok) >>~ pushContext ("Django HTML Template","CSS content")) <|> ((parseRules ("Django HTML Template","FindAttributes"))) <|> ((parseRules ("Django HTML Template","FindTemplate"))) <|> ((pRegExpr regex_'5cS >>= withAttribute ErrorTok)) <|> (currentContext >>= \x -> guard (x == ("Django HTML Template","CSS")) >> pDefault >>= withAttribute NormalTok)) parseRules ("Django HTML Template","CSS content") = (((pRegExpr regex_'3c'2fstyle'5cb >>= withAttribute KeywordTok) >>~ pushContext ("Django HTML Template","El Close 2")) <|> ((parseRules ("Django HTML Template","FindTemplate"))) <|> ((Text.Highlighting.Kate.Syntax.Css.parseExpression (Just ("CSS","")))) <|> (currentContext >>= \x -> guard (x == ("Django HTML Template","CSS content")) >> pDefault >>= withAttribute NormalTok)) parseRules ("Django HTML Template","JS") = (((pDetect2Chars False '/' '>' >>= withAttribute KeywordTok) >>~ (popContext)) <|> ((pDetectChar False '>' >>= withAttribute KeywordTok) >>~ pushContext ("Django HTML Template","JS content")) <|> ((parseRules ("Django HTML Template","FindTemplate"))) <|> ((parseRules ("Django HTML Template","FindAttributes"))) <|> ((pRegExpr regex_'5cS >>= withAttribute ErrorTok)) <|> (currentContext >>= \x -> guard (x == ("Django HTML Template","JS")) >> pDefault >>= withAttribute NormalTok)) parseRules ("Django HTML Template","JS content") = (((pRegExpr regex_'3c'2fscript'5cb >>= withAttribute KeywordTok) >>~ pushContext ("Django HTML Template","El Close 2")) <|> ((pRegExpr regex_'2f'2f'28'3f'3d'2e'2a'3c'2fscript'5cb'29 >>= withAttribute CommentTok) >>~ pushContext ("Django HTML Template","JS comment close")) <|> ((parseRules ("Django HTML Template","FindTemplate"))) <|> ((Text.Highlighting.Kate.Syntax.Javascript.parseExpression (Just ("JavaScript","Normal")))) <|> (currentContext >>= \x -> guard (x == ("Django HTML Template","JS content")) >> pDefault >>= withAttribute NormalTok)) parseRules ("Django HTML Template","JS comment close") = (((pRegExpr regex_'3c'2fscript'5cb >>= withAttribute KeywordTok) >>~ pushContext ("Django HTML Template","El Close 3")) <|> ((parseRules ("Django HTML Template","FindTemplate"))) <|> ((Text.Highlighting.Kate.Syntax.Alert.parseExpression (Just ("Alerts","")) >>= ((withAttribute CommentTok) . snd))) <|> (currentContext >>= \x -> guard (x == ("Django HTML Template","JS comment close")) >> pDefault >>= withAttribute CommentTok)) parseRules ("Django HTML Template","Value") = (((pDetectChar False '"' >>= withAttribute StringTok) >>~ pushContext ("Django HTML Template","Value DQ")) <|> ((pDetectChar False '\'' >>= withAttribute StringTok) >>~ pushContext ("Django HTML Template","Value SQ")) <|> ((pDetectSpaces >>= withAttribute NormalTok)) <|> (pushContext ("Django HTML Template","Value NQ") >> currentContext >>= parseRules)) parseRules ("Django HTML Template","Value NQ") = (((parseRules ("Django HTML Template","FindEntityRefs"))) <|> ((parseRules ("Django HTML Template","FindTemplate"))) <|> ((pRegExpr regex_'2f'28'3f'21'3e'29 >>= withAttribute StringTok)) <|> ((pRegExpr regex_'5b'5e'2f'3e'3c'22'27'5cs'5d >>= withAttribute StringTok)) <|> ((popContext >> popContext) >> currentContext >>= parseRules)) parseRules ("Django HTML Template","Value DQ") = (((pDetectChar False '"' >>= withAttribute StringTok) >>~ (popContext >> popContext)) <|> ((parseRules ("Django HTML Template","FindTemplate"))) <|> ((parseRules ("Django HTML Template","FindEntityRefs"))) <|> (currentContext >>= \x -> guard (x == ("Django HTML Template","Value DQ")) >> pDefault >>= withAttribute StringTok)) parseRules ("Django HTML Template","Value SQ") = (((pDetectChar False '\'' >>= withAttribute StringTok) >>~ (popContext >> popContext)) <|> ((parseRules ("Django HTML Template","FindTemplate"))) <|> ((parseRules ("Django HTML Template","FindEntityRefs"))) <|> (currentContext >>= \x -> guard (x == ("Django HTML Template","Value SQ")) >> pDefault >>= withAttribute StringTok)) parseRules ("Alerts", _) = Text.Highlighting.Kate.Syntax.Alert.parseExpression Nothing parseRules ("CSS", _) = Text.Highlighting.Kate.Syntax.Css.parseExpression Nothing parseRules ("JavaScript", _) = Text.Highlighting.Kate.Syntax.Javascript.parseExpression Nothing parseRules x = parseRules ("Django HTML Template","Start") <|> fail ("Unknown context" ++ show x)
ambiata/highlighting-kate
Text/Highlighting/Kate/Syntax/Djangotemplate.hs
gpl-2.0
27,383
0
27
4,100
7,488
4,020
3,468
467
42
{-# LANGUAGE MultiParamTypeClasses, TypeSynonymInstances, FlexibleInstances #-} {- | Module : ./Comorphisms/SuleCFOL2SoftFOL.hs Description : Coding of a CASL subset into SoftFOL Copyright : (c) Klaus Luettich and Uni Bremen 2005 License : GPLv2 or higher, see LICENSE.txt Maintainer : [email protected] Stability : provisional Portability : non-portable (imports Logic.Logic) The translating comorphism from a CASL subset to SoftFOL. -} module Comorphisms.SuleCFOL2SoftFOL ( suleCFOL2SoftFOL , suleCFOL2SoftFOLInduction , suleCFOL2SoftFOLInduction2 , extractCASLModel ) where import Control.Exception (assert) import Control.Monad (foldM) import Logic.Logic as Logic import Logic.Comorphism import Common.AS_Annotation import Common.Id import Common.Result import Common.DocUtils import Common.ProofTree import Common.Utils import qualified Common.Lib.Rel as Rel import qualified Common.Lib.MapSet as MapSet import Text.ParserCombinators.Parsec import qualified Data.Map as Map import qualified Data.Set as Set import Data.List as List import Data.Maybe import Data.Char import Data.Function import CASL.Logic_CASL import CASL.AS_Basic_CASL import CASL.Cycle import CASL.Sublogic as SL import CASL.Sign as CSign import CASL.MapSentence import CASL.Morphism import CASL.Quantification import CASL.Overload import CASL.Utils import CASL.Inject import CASL.Induction (generateInductionLemmas) import CASL.Simplify import CASL.ToDoc import SoftFOL.Sign as SPSign import SoftFOL.Logic_SoftFOL import SoftFOL.Translate import SoftFOL.ParseTPTP data PlainSoftFOL = PlainSoftFOL instance Show PlainSoftFOL where show PlainSoftFOL = "SoftFOL" data SoftFOLInduction = SoftFOLInduction deriving Show data SoftFOLInduction2 = SoftFOLInduction2 deriving Show -- | The identity of the comorphisms data GenSuleCFOL2SoftFOL a = GenSuleCFOL2SoftFOL a deriving Show suleCFOL2SoftFOL :: GenSuleCFOL2SoftFOL PlainSoftFOL suleCFOL2SoftFOL = GenSuleCFOL2SoftFOL PlainSoftFOL suleCFOL2SoftFOLInduction :: GenSuleCFOL2SoftFOL SoftFOLInduction suleCFOL2SoftFOLInduction = GenSuleCFOL2SoftFOL SoftFOLInduction suleCFOL2SoftFOLInduction2 :: GenSuleCFOL2SoftFOL SoftFOLInduction2 suleCFOL2SoftFOLInduction2 = GenSuleCFOL2SoftFOL SoftFOLInduction2 -- | SoftFOL theories type SoftFOLTheory = (SPSign.Sign, [Named SPTerm]) data CType = CSort | CVar SORT | CPred CSign.PredType | COp CSign.OpType deriving (Eq, Ord, Show) toCKType :: CType -> CKType toCKType ct = case ct of CSort -> CKSort CVar _ -> CKVar CPred _ -> CKPred COp _ -> CKOp -- | CASL Ids with Types mapped to SPIdentifier type IdTypeSPIdMap = Map.Map Id (Map.Map CType SPIdentifier) -- | specialized lookup for IdTypeSPIdMap lookupSPId :: Id -> CType -> IdTypeSPIdMap -> Maybe SPIdentifier lookupSPId i t = maybe Nothing (Map.lookup t) . Map.lookup i -- | specialized insert (with error) for IdTypeSPIdMap insertSPId :: Id -> CType -> SPIdentifier -> IdTypeSPIdMap -> IdTypeSPIdMap insertSPId i t spid m = assert (checkIdentifier (toCKType t) $ show spid) $ Map.insertWith (Map.unionWith err) i (Map.insert t spid Map.empty) m where err = error ("SuleCFOL2SoftFOL: for Id \"" ++ show i ++ "\" the type \"" ++ show t ++ "\" can't be mapped to different SoftFOL identifiers") deleteSPId :: Id -> CType -> IdTypeSPIdMap -> IdTypeSPIdMap deleteSPId i t m = maybe m (\ m2 -> let m2' = Map.delete t m2 in if Map.null m2' then Map.delete i m else Map.insert i m2' m) $ Map.lookup i m -- | specialized elems into a set for IdTypeSPIdMap elemsSPIdSet :: IdTypeSPIdMap -> Set.Set SPIdentifier elemsSPIdSet = Map.fold (\ m res -> Set.union res (Set.fromList (Map.elems m))) Set.empty -- extended signature translation type SignTranslator f e = CSign.Sign f e -> e -> SoftFOLTheory -> SoftFOLTheory -- extended signature translation for CASL sigTrCASL :: SignTranslator () () sigTrCASL _ _ = id -- extended formula translation type FormulaTranslator f e = CSign.Sign f e -> IdTypeSPIdMap -> f -> SPTerm -- extended formula translation for CASL formTrCASL :: FormulaTranslator () () formTrCASL _ _ = error "SuleCFOL2SoftFOL: No extended formulas allowed in CASL" instance Show a => Language (GenSuleCFOL2SoftFOL a) where language_name (GenSuleCFOL2SoftFOL a) = "CASL2" ++ show a instance Show a => Comorphism (GenSuleCFOL2SoftFOL a) CASL CASL_Sublogics CASLBasicSpec CASLFORMULA SYMB_ITEMS SYMB_MAP_ITEMS CASLSign CASLMor CSign.Symbol RawSymbol ProofTree SoftFOL () [SPSign.TPTP] SPTerm () () SPSign.Sign SoftFOLMorphism SFSymbol () ProofTree where sourceLogic (GenSuleCFOL2SoftFOL _) = CASL sourceSublogic (GenSuleCFOL2SoftFOL a) = SL.cFol { sub_features = LocFilSub , cons_features = emptyMapConsFeature , has_empty_sorts = show a == show PlainSoftFOL } sourceSublogicLossy (GenSuleCFOL2SoftFOL a) = SL.fol { sub_features = LocFilSub , has_empty_sorts = show a == show PlainSoftFOL } targetLogic (GenSuleCFOL2SoftFOL _) = SoftFOL mapSublogic cid sl = if isSubElem sl $ sourceSublogic cid then Just () else Nothing map_theory (GenSuleCFOL2SoftFOL a) = transTheory sigTrCASL formTrCASL . case show a of str | str == show SoftFOLInduction -> generateInductionLemmas True | str == show SoftFOLInduction2 -> generateInductionLemmas False | otherwise -> id extractModel (GenSuleCFOL2SoftFOL _) = extractCASLModel has_model_expansion (GenSuleCFOL2SoftFOL _) = True -- -------------------------- Signature ----------------------------- transFuncMap :: IdTypeSPIdMap -> CSign.Sign e f -> (FuncMap, IdTypeSPIdMap) transFuncMap idMap sign = Map.foldWithKey toSPOpType (Map.empty, idMap) . MapSet.toMap $ CSign.opMap sign where toSPOpType iden typeSet (fm, im) = if isSingleton typeSet then let oType = Set.findMin typeSet sid' = sid fm oType in (Map.insert sid' (Set.singleton (transOpType oType)) fm, insertSPId iden (COp oType) sid' im) else foldr insOIdSet (fm, im) $ Rel.partSet (leqF sign) typeSet where insOIdSet tset (fm', im') = let sid' = sid fm' (Set.findMax tset) in (Map.insert sid' (Set.map transOpType tset) fm', Set.fold (\ x -> insertSPId iden (COp x) sid') im' tset) sid fma t = disSPOId CKOp (transId CKOp iden) (uType (transOpType t)) (Set.union (Map.keysSet fma) (elemsSPIdSet idMap)) uType t = fst t ++ [snd t] transPredMap :: IdTypeSPIdMap -> CSign.Sign e f -> (SPSign.PredMap, IdTypeSPIdMap) transPredMap idMap sign = Map.foldWithKey toSPPredType (Map.empty, idMap) . MapSet.toMap $ CSign.predMap sign where toSPPredType iden typeSet (fm, im) = if isSingleton typeSet then let pType = Set.findMin typeSet sid' = sid fm pType in (Map.insert sid' (Set.singleton (transPredType pType)) fm , insertSPId iden (CPred pType) sid' im) else case -- genPredImplicationDisjunctions sign $ Rel.partSet (leqP sign) typeSet of splitTySet -> foldr insOIdSet (fm, im) splitTySet where insOIdSet tset (fm', im') = let sid' = sid fm' (Set.findMax tset) in (Map.insert sid' (Set.map transPredType tset) fm', Set.fold (\ x -> insertSPId iden (CPred x) sid') im' tset) sid fma t = disSPOId CKPred (transId CKPred iden) (transPredType t) (Set.union (Map.keysSet fma) (elemsSPIdSet idMap)) {- left typing implies right typing; explicit overloading sentences are generated from these pairs, type TypePair = (CType,CType) -} -- | disambiguation of SoftFOL Identifiers disSPOId :: CKType -- ^ Type of CASl identifier -> SPIdentifier -- ^ translated CASL Identifier -> [SPIdentifier] {- ^ translated Sort Symbols of the profile (maybe empty) -} -> Set.Set SPIdentifier -- ^ SoftFOL Identifiers already in use -> SPIdentifier {- ^ fresh Identifier generated from second argument; if the identifier was not in the set this is just the second argument -} disSPOId cType sid ty idSet | checkIdentifier cType (show sid) && not (lkup $ show sid) = sid | otherwise = let nSid = disSPOId' $ show sid in assert (checkIdentifier cType nSid) $ mkSimpleId nSid where disSPOId' sid' | not (lkup asid) = asid | otherwise = addType asid 1 where asid = sid' ++ case cType of CKSort -> "" CKVar -> "" x -> '_' : show (length ty - (case x of CKOp -> 1 _ -> 0)) addType res n = let nres = asid ++ '_' : fc n nres' = nres ++ '_' : show n in if nres == res then if nres' == res then error ("SuleCFOL2SoftFOL: " ++ "cannot calculate" ++ " unambiguous id for " ++ show sid ++ " with type " ++ show ty ++ " and nres = " ++ nres ++ "\n with idSet " ++ show idSet) else if not (lkup nres') then nres' else addType nres (n + 1) else if not (lkup nres) then nres else addType nres (n + 1) lkup x = Set.member (mkSimpleId x) idSet fc n = concatMap (take n . show) ty transOpType :: CSign.OpType -> ([SPIdentifier], SPIdentifier) transOpType ot = (map transIdSort (CSign.opArgs ot), transIdSort (CSign.opRes ot)) transPredType :: CSign.PredType -> [SPIdentifier] transPredType = map transIdSort . CSign.predArgs -- | translate every Id as Sort transIdSort :: Id -> SPIdentifier transIdSort = transId CKSort integrateGenerated :: IdTypeSPIdMap -> [Named (FORMULA f)] -> SPSign.Sign -> Result (IdTypeSPIdMap, SPSign.Sign, [Named SPTerm]) integrateGenerated idMap genSens sign | null genSens = return (idMap, sign, []) | otherwise = case partition isAxiom genSens of (genAxs, genGoals) -> case makeGenGoals sign idMap genGoals of (newPredsMap, idMap', goalsAndSentences) -> -- makeGens must not invent new sorts case makeGens sign idMap' genAxs of Result dias mv -> maybe (Result dias Nothing) (\ (spSortMap_makeGens, newOpsMap, idMap'', exhaustSens) -> let spSortMap' = Map.union spSortMap_makeGens (SPSign.sortMap sign) in assert (Map.size spSortMap' == Map.size (SPSign.sortMap sign)) (Result dias (Just (idMap'', sign { sortMap = spSortMap' , funcMap = Map.union (funcMap sign) newOpsMap , SPSign.predMap = Map.union (SPSign.predMap sign) newPredsMap}, mkInjSentences idMap' newOpsMap ++ goalsAndSentences ++ exhaustSens)))) mv makeGenGoals :: SPSign.Sign -> IdTypeSPIdMap -> [Named (FORMULA f)] -> (SPSign.PredMap, IdTypeSPIdMap, [Named SPTerm]) makeGenGoals sign idMap fs = let Result _ res = makeGens sign idMap fs in case res of Nothing -> (Map.empty, idMap, []) Just (_, _, idMap', fs') -> let fs'' = map (\ s -> s {isAxiom = False}) fs' in (Map.empty, idMap', fs'') {- Sort_gen_ax as goals only implemented through a hack." sketch of full implementation : - invent new predicate P that is supposed to hold on every x in the (freely) generated sort. - generate formulas with this predicate for each constructor. - recursive constructors hold if the predicate holds on the variables - prove forall x . P(x) implementation is postponed as this translation does not produce only one goal, but additional symbols, axioms and a goal -} makeGens :: SPSign.Sign -> IdTypeSPIdMap -> [Named (FORMULA f)] -> Result (SortMap, FuncMap, IdTypeSPIdMap, [Named SPTerm]) {- ^ The list of SoftFOL sentences gives exhaustiveness for generated sorts with only constant constructors and\/or subsort injections, by simply translating such sort generation constraints to disjunctions -} makeGens sign idMap fs = case foldl (makeGen sign) (return (Map.empty, idMap, [], [])) fs of Result ds mv -> maybe (Result ds Nothing) (\ (opM, idMap', pairs, exhaustSens) -> Result ds (Just (foldr (uncurry Map.insert) Map.empty pairs, opM, idMap', exhaustSens))) mv makeGen :: SPSign.Sign -> Result (FuncMap, IdTypeSPIdMap, [(SPIdentifier, Maybe Generated)], [Named SPTerm]) -> Named (FORMULA f) -> Result (FuncMap, IdTypeSPIdMap, [(SPIdentifier, Maybe Generated)], [Named SPTerm]) makeGen sign r@(Result ods omv) nf = maybe (Result ods Nothing) process omv where process (oMap, iMap, rList, eSens) = case sentence nf of Sort_gen_ax constrs free -> if null mp then (case mapAccumL makeGenP (oMap, iMap, []) srts of ((oMap', iMap', eSens'), genPairs) -> Result ods (Just (oMap', iMap', rList ++ genPairs, eSens ++ eSens'))) else mkError ("Sort generation constraints with " ++ "non-injective sort mappings cannot " ++ "be translated to SoftFOL") mp where -- compute standard form of sort generation constraints (srts, ops, mp) = recover_Sort_gen_ax constrs -- test whether a constructor belongs to a specific sort hasTheSort s (Qual_op_name _ ot _) = s == res_OP_TYPE ot hasTheSort _ _ = error "SuleCFOL2SoftFOL.hasTheSort" mkGen = Just . Generated free . map fst -- translate constraint for one sort makeGenP (opM, idMap, exSens) s = ((newOpMap, newIdMap, exSens ++ eSen ops_of_s s), (s', mkGen cons)) where ((newOpMap, newIdMap), cons) = mapAccumL mkInjOp (opM, idMap) ops_of_s ops_of_s = List.filter (hasTheSort s) ops s' = fromMaybe (error $ "SuleCFOL2SoftFOL.makeGen: " ++ "No mapping found for '" ++ shows s "'") (lookupSPId s CSort idMap) {- is an operation a constant or an injection ? (we currently can translate only these) -} isConstorInj o = nullArgs o || isInjName (opSymbName o) -- generate sentences for one sort eSen os s = [ makeNamed (newName s) (SPQuantTerm SPForall [typedVarTerm var1 $ fromMaybe (error "lookup failed") (lookupSPId s CSort iMap)] (disj var1 os)) | all isConstorInj os ] -- generate sentences: compute one disjunct (for one alternative) mkDisjunct v o@(Qual_op_name _ (Op_type _ args res _) _) = -- a constant? then just compare with it case args of [] -> mkEq (varTerm v) $ varTerm $ transOPSYMB iMap o {- an injection? then quantify existentially (for the injection's argument) since injections are identities, we can leave them out -} [arg] -> let ta = transIdSort arg in SPQuantTerm SPExists [ typedVarTerm var2 ta ] $ mkEq (varTerm v) $ if Rel.member ta (transIdSort res) $ SPSign.sortRel sign then varTerm var2 else compTerm (spSym $ transOPSYMB iMap o) [varTerm var2] _ -> error "cannot handle ordinary constructors" mkDisjunct _ _ = error "unqualified operation symbol" -- make disjunction out of all the alternatives disj v os = case map (mkDisjunct v) os of [] -> error "SuleCFOL2SoftFOL: no constructors found" [x] -> x xs -> foldl1 mkDisj xs -- generate enough variables var = fromJust (find (\ x -> not (Set.member (mkSimpleId x) usedIds)) ("X" : ['X' : show i | i <- [(1 :: Int) ..]])) var1 = mkSimpleId var var2 = mkSimpleId $ var ++ "a" varTerm = simpTerm . spSym newName s = "ga_exhaustive_generated_sort_" ++ show (pretty s) usedIds = elemsSPIdSet iMap nullArgs o = case o of Qual_op_name _ (Op_type _ args _ _) _ -> null args _ -> error "SuleCFOL2SoftFOL: wrong constructor" _ -> r mkInjOp :: (FuncMap, IdTypeSPIdMap) -> OP_SYMB -> ((FuncMap, IdTypeSPIdMap), (SPIdentifier, ([SPIdentifier], SPIdentifier))) mkInjOp (opM, idMap) qo@(Qual_op_name i ot _) = if isInjName i && isNothing lsid then ((Map.insert i' (Set.singleton (transOpType ot')) opM, insertSPId i (COp ot') i' idMap), (i', transOpType ot')) else ((opM, idMap), (fromMaybe err lsid, transOpType ot')) where i' = disSPOId CKOp (transId CKOp i) (utype (transOpType ot')) usedNames ot' = CSign.toOpType ot lsid = lookupSPId i (COp ot') idMap usedNames = Map.keysSet opM err = error ("SuleCFOL2SoftFOL.mkInjOp: Cannot find SPId for '" ++ show qo ++ "'") utype t = fst t ++ [snd t] mkInjOp _ _ = error "SuleCFOL2SoftFOL.mkInjOp: Wrong constructor!!" mkInjSentences :: IdTypeSPIdMap -> FuncMap -> [Named SPTerm] mkInjSentences idMap = Map.foldWithKey genInjs [] where genInjs k tset fs = Set.fold (genInj k) fs tset genInj k (args, res) = assert (length args == 1) . (makeNamed (newName (show k) (show $ head args) $ show res) (SPQuantTerm SPForall [typedVarTerm var $ head args] (compTerm SPEqual [compTerm (spSym k) [simpTerm (spSym var)], simpTerm (spSym var)])) :) var = mkSimpleId $ fromJust (find (\ x -> not (Set.member (mkSimpleId x) usedIds)) ("Y" : [ 'Y' : show i | i <- [(1 :: Int) ..]])) newName o a r = "ga_" ++ o ++ '_' : a ++ '_' : r ++ "_id" usedIds = elemsSPIdSet idMap {- | Translate a CASL signature into SoftFOL signature 'SoftFOL.Sign.Sign'. Before translating, eqPredicate symbols where removed from signature. -} transSign :: CSign.Sign f e -> (SPSign.Sign, IdTypeSPIdMap) transSign sign = (SPSign.emptySign { SPSign.sortRel = Rel.map transIdSort (CSign.sortRel sign) , sortMap = spSortMap , funcMap = fMap , SPSign.predMap = pMap , singleSorted = isSingleSorted sign } , idMap'') where (spSortMap, idMap) = Set.fold (\ i (sm, im) -> let sid = disSPOId CKSort (transIdSort i) [mkSimpleId $ take 20 (cycle "So")] (Map.keysSet sm) in (Map.insert sid Nothing sm, insertSPId i CSort sid im)) (Map.empty, Map.empty) (CSign.sortSet sign) (fMap, idMap') = transFuncMap idMap sign (pMap, idMap'') = transPredMap idMap' sign nonEmptySortSens :: CSign.Sign f e -> IdTypeSPIdMap -> SortMap -> [Named SPTerm] nonEmptySortSens sig idMap sm = let es = Set.difference (sortSet sig) $ emptySortSet sig in [ extSen s | nes <- Set.toList es , let s = fromMaybe (transIdSort nes) $ lookupSPId nes CSort idMap , Set.member s $ Map.keysSet sm ] where extSen s = makeNamed ("ga_non_empty_sort_" ++ show s) $ SPQuantTerm SPExists [varTerm] $ compTerm (spSym s) [varTerm] where varTerm = simpTerm $ spSym $ mkSimpleId $ newVar s newVar s = fromJust $ find (/= show s) $ "Y" : ['Y' : show i | i <- [(1 :: Int) ..]] disjointTopSorts :: CSign.Sign f e -> IdTypeSPIdMap -> [Named SPTerm] disjointTopSorts sign idMap = let s = CSign.sortSet sign sl = Rel.partSet (haveCommonSupersorts True sign) s l = map (\ p -> case keepMinimals1 False sign id $ Set.toList p of [e] -> e _ -> error "disjointTopSorts") sl pairs ls = case ls of s1 : r -> map (\ s2 -> (s1, s2)) r ++ pairs r _ -> [] v1 = simpTerm $ spSym $ mkSimpleId "Y1" v2 = simpTerm $ spSym $ mkSimpleId "Y2" in map (\ (t1, t2) -> makeNamed ("disjoint_sorts_" ++ shows t1 "_" ++ show t2) $ SPQuantTerm SPForall [ compTerm (spSym t1) [v1] , compTerm (spSym t2) [v2]] $ compTerm SPNot [mkEq v1 v2]) $ pairs $ map (\ t -> fromMaybe (transIdSort t) $ lookupSPId t CSort idMap) l transTheory :: (FormExtension f, Eq f) => SignTranslator f e -> FormulaTranslator f e -> (CSign.Sign f e, [Named (FORMULA f)]) -> Result SoftFOLTheory transTheory trSig trForm (sign, sens) = let (nsig, sm) = removeSortCycles sign in transTheoryAux trSig trForm (nsig , map (mapNamed $ mapMorphForm (return id) ((embedMorphism () sign nsig) { sort_map = sm })) sens) transTheoryAux :: (FormExtension f, Eq f) => SignTranslator f e -> FormulaTranslator f e -> (CSign.Sign f e, [Named (FORMULA f)]) -> Result SoftFOLTheory transTheoryAux trSig trForm (sign, sens) = fmap (trSig sign (CSign.extendedInfo sign)) (case transSign (filterPreds $ foldl insInjOps sign genAxs) of (tSign, idMap) -> do (idMap', tSign', sentencesAndGoals) <- integrateGenerated idMap genSens tSign let tSignElim = if SPSign.singleSortNotGen tSign' then tSign' {sortMap = Map.empty} else tSign' return (tSignElim, disjointTopSorts sign idMap' ++ sentencesAndGoals ++ nonEmptySortSens sign idMap' (sortMap tSignElim) ++ map (mapNamed (transFORM (singleSortNotGen tSign') eqPreds sign idMap' trForm)) realSens')) where (genSens, realSens) = partition (\ s -> case sentence s of Sort_gen_ax _ _ -> True _ -> False) sens (eqPreds, realSens') = foldl findEqPredicates (Set.empty, []) realSens genAxs = filter isAxiom genSens insInjOps sig s = case sentence s of (Sort_gen_ax constrs _) -> case recover_Sort_gen_ax constrs of (_, ops, mp) -> assert (null mp) (insertInjOps sig ops) _ -> error "SuleCFOL2SoftFOL.transTheory.insInjOps" filterPreds sig = sig { CSign.predMap = MapSet.difference (CSign.predMap sig) (Set.fold (\ pl -> case pl of Pred_name pn -> MapSet.insert pn (PredType []) Qual_pred_name pn pt _ -> MapSet.insert pn $ CSign.toPredType pt) MapSet.empty eqPreds) } {- | Finds definitions (Equivalences) where one side is a binary predicate and the other side is a built-in equality application (Strong_equation). The given Named (FORMULA f) is checked for this and if so, will be put into the set of such predicates. -} findEqPredicates :: (Eq f) => (Set.Set PRED_SYMB, [Named (FORMULA f)]) -- ^ previous list of found predicates and valid sentences -> Named (FORMULA f) -- ^ sentence to check -> (Set.Set PRED_SYMB, [Named (FORMULA f)]) findEqPredicates (eqPreds, sens) sen = case sentence sen of Quantification Universal var_decl quantFormula _ -> isEquiv (foldl (\ vList (Var_decl v s _) -> vList ++ map (\ vl -> (vl, s)) v) [] var_decl) quantFormula _ -> validSens where validSens = (eqPreds, sens ++ [sen]) isEquiv vars qf = {- Exact two variables are checked if they have the same Sort. If more than two variables should be compared, use foldl. -} if (length vars == 2) && (snd (head vars) == snd (vars !! 1)) then case qf of Relation f1 Equivalence f2 _ -> isStrong_eq vars f1 f2 _ -> validSens else validSens isStrong_eq vars f1 f2 = let f1n = case f1 of Equation _ Strong _ _ -> f1 _ -> f2 f2n = case f1 of Equation _ Strong _ _ -> f2 _ -> f1 in case f1n of Equation eq_t1 Strong eq_t2 _ -> case f2n of Predication eq_pred_symb pterms _ -> if Map.toList (Map.fromList $ sortedVarTermList pterms) == Map.toList (Map.fromList vars) && Map.toList (Map.fromList $ sortedVarTermList [eq_t1, eq_t2]) == Map.toList (Map.fromList vars) then (Set.insert eq_pred_symb eqPreds, sens) else validSens _ -> validSens _ -> validSens {- | Creates a list of (VAR, SORT) out of a list of TERMs. Only Qual_var TERMs are inserted which will be checked using 'Comorphisms.SuleCFOL2SoftFOL.hasSortedVarTerm'. -} sortedVarTermList :: [TERM f] -> [(VAR, SORT)] sortedVarTermList = mapMaybe hasSortedVarTerm {- | Finds a 'CASL.AS_Basic_CASL.Qual_var' term recursively if super term(s) is 'CASL.AS_Basic_CASL.Sorted_term' or 'CASL.AS_Basic_CASL.Cast'. -} hasSortedVarTerm :: TERM f -> Maybe (VAR, SORT) hasSortedVarTerm t = case t of Qual_var v s _ -> Just (v, s) Sorted_term tx _ _ -> hasSortedVarTerm tx Cast tx _ _ -> hasSortedVarTerm tx _ -> Nothing -- ---------------------------- Formulas ------------------------------ transOPSYMB :: IdTypeSPIdMap -> OP_SYMB -> SPIdentifier transOPSYMB idMap ~qo@(Qual_op_name op ot _) = fromMaybe (error $ "SuleCFOL2SoftFOL.transOPSYMB: unknown op: " ++ show qo) (lookupSPId op (COp (CSign.toOpType ot)) idMap) transPREDSYMB :: IdTypeSPIdMap -> PRED_SYMB -> SPIdentifier transPREDSYMB idMap ~qp@(Qual_pred_name p pt _) = fromMaybe (error $ "SuleCFOL2SoftFOL.transPREDSYMB: unknown pred: " ++ show qp) (lookupSPId p (CPred (CSign.toPredType pt)) idMap) -- | Translate the quantifier quantify :: QUANTIFIER -> SPQuantSym quantify q = case q of Universal -> SPForall Existential -> SPExists Unique_existential -> error "SuleCFOL2SoftFOL: no translation for existential quantification." transVarTup :: (Set.Set SPIdentifier, IdTypeSPIdMap) -> (VAR, SORT) -> ((Set.Set SPIdentifier, IdTypeSPIdMap), (SPIdentifier, SPIdentifier)) {- ^ ((new set of used Ids, new map of Ids to original Ids), (var as sp_Id, sort as sp_Id)) -} transVarTup (usedIds, idMap) (v, s) = ((Set.insert sid usedIds, insertSPId vi (CVar s) sid $ deleteSPId vi (CVar s) idMap) , (sid, spSort)) where spSort = fromMaybe (error $ "SuleCFOL2SoftFOL: translation of sort \"" ++ showDoc s "\" not found") (lookupSPId s CSort idMap) vi = simpleIdToId v sid = disSPOId CKVar (transId CKVar vi) [mkSimpleId $ "_Va_" ++ showDoc s "_Va"] usedIds transFORM :: (Eq f, FormExtension f) => Bool -- ^ single sorted flag -> Set.Set PRED_SYMB -- ^ list of predicates to substitute -> CSign.Sign f e -> IdTypeSPIdMap -> FormulaTranslator f e -> FORMULA f -> SPTerm transFORM siSo eqPreds sign i tr phi = transFORMULA siSo sign i tr phi' where phi' = codeOutConditionalF id (codeOutUniqueExtF id id (substEqPreds eqPreds id phi)) transFORMULA :: FormExtension f => Bool -> CSign.Sign f e -> IdTypeSPIdMap -> FormulaTranslator f e -> FORMULA f -> SPTerm transFORMULA siSo sign idMap tr frm = case frm of Quantification qu vdecl phi _ -> SPQuantTerm (quantify qu) vList (transFORMULA siSo sign idMap' tr phi) where ((_, idMap'), vList) = mapAccumL (\ acc e -> let (acc', e') = transVarTup acc e in (acc', (if siSo then simpTerm . spSym . fst else uncurry typedVarTerm) e')) (sidSet, idMap) (flatVAR_DECLs vdecl) sidSet = elemsSPIdSet idMap Junction j phis _ -> let (n, op) = if j == Dis then (SPFalse, mkDisj) else (SPTrue, mkConj) in if null phis then simpTerm n else foldl1 op (map (transFORMULA siSo sign idMap tr) phis) Relation phi1 c phi2 _ -> compTerm (if c == Equivalence then SPEquiv else SPImplies) [transFORMULA siSo sign idMap tr phi1, transFORMULA siSo sign idMap tr phi2] Negation phi _ -> compTerm SPNot [transFORMULA siSo sign idMap tr phi] Atom b _ -> simpTerm $ if b then SPTrue else SPFalse Predication psymb args _ -> compTerm (spSym (transPREDSYMB idMap psymb)) (map (transTERM siSo sign idMap tr) args) Equation t1 _ t2 _ -> -- sortOfTerm t1 == sortOfTerm t2 mkEq (transTERM siSo sign idMap tr t1) (transTERM siSo sign idMap tr t2) ExtFORMULA phi -> tr sign idMap phi Definedness _ _ -> simpTerm SPTrue -- assume totality Membership t s _ -> if siSo then simpTerm SPTrue else maybe (error ("SuleCFOL2SoftFOL.tF: no SoftFOL Id found for \"" ++ showDoc s "\"")) (\ si -> compTerm (spSym si) [transTERM siSo sign idMap tr t]) (lookupSPId s CSort idMap) _ -> error $ "SuleCFOL2SoftFOL.transFORMULA: unknown FORMULA '" ++ showDoc frm "'" transTERM :: FormExtension f => Bool -> CSign.Sign f e -> IdTypeSPIdMap -> FormulaTranslator f e -> TERM f -> SPTerm transTERM siSo sign idMap tr term = case term of Qual_var v s _ -> maybe (error ("SuleCFOL2SoftFOL.tT: no SoftFOL Id found for \"" ++ showDoc v "\"")) (simpTerm . spSym) (lookupSPId (simpleIdToId v) (CVar s) idMap) Application opsymb args _ -> compTerm (spSym (transOPSYMB idMap opsymb)) (map (transTERM siSo sign idMap tr) args) Conditional _t1 _phi _t2 _ -> error "SuleCFOL2SoftFOL.transTERM: Conditional terms must be coded out." Sorted_term t _s _ -> -- sortOfTerm t isSubsortOf s transTERM siSo sign idMap tr t Cast t _s _ -> -- s isSubsortOf sortOfTerm t transTERM siSo sign idMap tr t _ -> error ("SuleCFOL2SoftFOL.transTERM: unknown TERM '" ++ showDoc term "'") isSingleSorted :: CSign.Sign f e -> Bool isSingleSorted sign = Set.size (CSign.sortSet sign) == 1 && Set.null (emptySortSet sign) -- empty sorts need relativization -- * extract model out of darwin output stored in a proof tree extractCASLModel :: CASLSign -> ProofTree -> Result (CASLSign, [Named (FORMULA ())]) extractCASLModel sign (ProofTree output) = case parse tptpModel "" output of Right rfs -> do let idMap = snd $ transSign sign rMap = getSignMap idMap (rs, fs1) = partition ((== "interpretation_atoms") . fst) rfs (ds, fs2) = partition ((== "interpretation_domain") . fst) fs1 (dds, fs3) = partition ((== "interpretation_domain_distinct") . fst) fs2 (es, nm0) = foldl (\ (l, m) (_, s) -> let (e, m2) = typeCheckForm False sign m s in (l ++ e, m2)) ([], rMap) rs nm = foldl (\ m (_, s) -> snd $ typeCheckForm True sign m s) nm0 $ fs3 ++ ds ++ dds nops = Map.filter (\ v -> case v of (COp _, Nothing) -> True _ -> False) nm os = opMap sign nos = foldr (\ (i, ~(COp ot, _)) -> addOpTo (simpleIdToId i) ot) os $ Map.toList nops nsign = sign { opMap = nos } mkWarn s = Diag Warning s nullRange doms <- if Set.null (sortSet sign) then return [] else mapM (\ (n, f) -> do diss <- getDomElems f nf <- createDomain sign nm diss return $ makeNamed n nf) ds distfs <- mapM (\ (n, f) -> do let fs = splitConjs f ets = map (fst . typeCheckForm False sign nm) fs cs = filter (null . fst) $ zip ets fs dts <- foldM getUneqElems Set.empty fs let ws = concatMap ((\ (s, _, _) -> s) . typeCheckTerm sign Nothing nm) $ Set.toList dts Result (map mkWarn ws) $ Just () tfs <- mapM (toForm nsign nm . snd) cs return $ makeNamed n $ simplifyFormula id $ conjunct tfs) dds terms <- mapM (\ (n, f) -> do let fs = splitConjs f ets = map (fst . typeCheckForm False sign nm) fs (cs, ws) = partition (null . fst) $ zip ets fs Result (map mkWarn $ concatMap fst ws) $ Just () tfs <- mapM (toForm nsign nm . snd) cs return $ makeNamed n $ simplifyFormula id $ conjunct tfs) fs3 sens <- mapM (\ (n, f) -> do cf <- toForm nsign nm f return $ makeNamed n $ simplifyFormula id cf) rs Result (map mkWarn es) $ Just () return (nsign, doms ++ distfs ++ terms ++ sens) Left err -> fail $ showErr err type RMap = Map.Map SPIdentifier (CType, Maybe Id) getSignMap :: IdTypeSPIdMap -> RMap getSignMap = foldr (\ (i, m) g -> foldr (\ (t, s) -> case t of CSort -> Map.insert s (CPred $ PredType [i], Nothing) _ -> Map.insert s (t, Just i)) g $ Map.toList m) Map.empty . Map.toList splitConjs :: SPTerm -> [SPTerm] splitConjs trm = case trm of SPComplexTerm SPAnd args -> concatMap splitConjs args _ -> [trm] getUneqElems :: Set.Set SPTerm -> SPTerm -> Result (Set.Set SPTerm) getUneqElems s trm = case trm of SPComplexTerm SPNot [SPComplexTerm SPEqual [a1, a2]] -> return $ Set.insert a2 $ Set.insert a1 s _ -> fail $ "unexpected disjointness formula: " ++ showDoc trm "" splitDisjs :: SPTerm -> [SPTerm] splitDisjs trm = case trm of SPComplexTerm SPOr args -> concatMap splitDisjs args _ -> [trm] getDomElems :: SPTerm -> Result [SPTerm] getDomElems trm = case trm of SPQuantTerm SPForall [var] frm -> mapM (\ t -> case t of SPComplexTerm SPEqual [a1, a2] | var == a1 -> return a2 | var == a2 -> return a1 _ -> fail $ "expecting equation with " ++ show var ++ ", got: " ++ showDoc t "") $ splitDisjs frm _ -> fail $ "expecting simple quantified disjunction, got: " ++ showDoc trm "" createDomain :: CASLSign -> RMap -> [SPTerm] -> Result (FORMULA ()) createDomain sign m l = do let es = map ((\ (e, _, s) -> (e, s)) . typeCheckTerm sign Nothing m) l tys <- mapM (\ (e, ms) -> case ms of Just s -> return s _ -> fail $ unlines e) es cs <- mapM (\ ds -> do ts@(trm : r) <- mapM (toTERM m . snd) ds let mtys = keepMinimals sign id . Set.toList . foldl1 Set.intersection $ map (\ (ty, _) -> Set.insert ty $ supersortsOf ty sign) ds case mtys of [] -> fail $ "no common supersort found for: " ++ showDoc ds "" ty : _ -> do let v = mkVarDeclStr "X" ty return $ mkForall [v] $ if null r then mkStEq (toQualVar v) trm else disjunct $ map (mkStEq $ toQualVar v) ts) . Rel.partList (on (haveCommonSupersorts True sign) fst) $ zip tys l return $ conjunct cs typeCheckForm :: Bool -> CASLSign -> RMap -> SPTerm -> ([String], RMap) typeCheckForm rev sign m trm = let srts = sortSet sign aty = if Set.size srts == 1 then Just $ Set.findMin srts else Nothing in case trm of SPQuantTerm _ vars frm -> let vs = concatMap getVars vars rm = foldr Map.delete m vs (errs, nm) = typeCheckForm rev sign rm frm m2 = foldr Map.delete nm vs in (errs, Map.union m m2) SPComplexTerm SPEqual [a1, a2] -> let (r1, m1, ety) = typeCheckEq sign aty m a1 a2 in case ety of Nothing -> (r1, m1) Just _ -> let (r2, m2, _) = typeCheckEq sign ety m1 a2 a1 in (r2, m2) SPComplexTerm (SPCustomSymbol cst) args -> case Map.lookup cst m of Just (CPred pt, _) | length args == length (predArgs pt) -> foldl (\ (b, p) (s, a) -> let (nb, nm, _) = typeCheckTerm sign (Just s) p a in (b ++ nb, nm)) ([], m) $ zip (predArgs pt) args _ -> (["unknown predicate: " ++ show cst], m) SPComplexTerm _ args -> foldl (\ (b, p) a -> let (nb, nm) = typeCheckForm rev sign p a in (b ++ nb, nm)) ([], m) $ if rev then reverse args else args typeCheckEq :: CASLSign -> Maybe SORT -> RMap -> SPTerm -> SPTerm -> ([String], RMap, Maybe SORT) typeCheckEq sign aty m a1 a2 = let (r1, m1, ty1) = typeCheckTerm sign aty m a1 (r2, m2, ty2) = typeCheckTerm sign aty m1 a2 in case (ty1, ty2) of (Just s1, Just s2) -> (r1 ++ r2 ++ [ "different types " ++ show (s1, s2) ++ " in equation: " ++ showDoc a1 " = " ++ showDoc a2 "" | not $ haveCommonSupersorts True sign s1 s2], m2, Nothing) (Nothing, _) -> (r1, m2, ty2) (_, Nothing) -> (r1 ++ r2, m2, ty1) typeCheckTerm :: CASLSign -> Maybe SORT -> RMap -> SPTerm -> ([String], RMap, Maybe SORT) typeCheckTerm sign ty m trm = let srts = sortSet sign aty = if Set.size srts == 1 then Just $ Set.findMin srts else Nothing in case trm of SPComplexTerm (SPCustomSymbol cst) args -> case Map.lookup cst m of Nothing -> let (fb, fm, aTys) = foldr (\ a (b, p, tys) -> let (nb, nm, tya) = typeCheckTerm sign aty p a in (b ++ nb, nm, tya : tys)) ([], m, []) args in case ty of Just r | all isJust aTys -> if null args && isVar cst then (fb, Map.insert cst (CVar r, Nothing) fm, ty) else (fb, Map.insert cst (COp $ mkTotOpType (catMaybes aTys) r, Nothing) fm , ty) _ -> (["no type for: " ++ showDoc trm ""], fm, ty) Just (COp ot, _) -> let aTys = opArgs ot rTy = opRes ot (fb, fm) = foldl (\ (b, p) (s, a) -> let (nb, nm, _) = typeCheckTerm sign (Just s) p a in (b ++ nb, nm)) ([], m) $ zip aTys args aTyL = length aTys argL = length args in (fb ++ ["expected " ++ show aTyL ++ " arguments, but found " ++ show argL ++ " for: " ++ show cst | aTyL /= argL] ++ case ty of Just r -> ["expected result sort " ++ show r ++ ", but found " ++ show rTy ++ " for: " ++ show cst | not $ leqSort sign rTy r ] _ -> [], fm, Just rTy) Just (CVar s2, _) -> (["unexpected arguments for variable: " ++ show cst | not $ null args] ++ case ty of Just r -> ["expected variable sort " ++ show r ++ ", but found " ++ show s2 ++ " for: " ++ show cst | not $ leqSort sign s2 r ] _ -> [], m, Just s2) _ -> (["unexpected predicate in term: " ++ showDoc trm ""], m, ty) _ -> (["unexpected term: " ++ showDoc trm ""], m, ty) toForm :: Monad m => CASLSign -> RMap -> SPTerm -> m (FORMULA ()) toForm sign m t = case t of SPQuantTerm q vars frm -> do let vs = concatMap getVars vars rm = foldr Map.delete m vs (b, nm) = typeCheckForm False sign rm frm nvs = mapMaybe (toVar nm) vars nf <- toForm sign nm frm if null b then return $ Quantification (toQuant q) nvs nf nullRange else fail $ unlines b SPComplexTerm SPEqual [a1, a2] -> do t1 <- toTERM m a1 t2 <- toTERM m a2 return $ mkStEq t1 t2 SPComplexTerm (SPCustomSymbol cst) args -> case Map.lookup cst m of Just (CPred pt, mi) | length args == length (predArgs pt) -> do ts <- mapM (toTERM m) args case mi of Nothing -> case args of [_] -> return trueForm _ -> fail $ "unkown predicate: " ++ show cst Just i -> return $ mkPredication (mkQualPred i $ toPRED_TYPE pt) ts _ -> fail $ "inconsistent pred symbol: " ++ show cst SPComplexTerm symb args -> do fs <- mapM (toForm sign m) args case (symb, fs) of (SPNot, [f]) -> return (mkNeg f) (SPImplies, [f1, f2]) -> return (mkImpl f1 f2) -- During parsing, "f2 if f1" is saved as "Relation f1 RevImpl f2 _" (SPImplied, [f2, f1]) -> return (Relation f1 RevImpl f2 nullRange) (SPEquiv, [f1, f2]) -> return (mkEqv f1 f2) (SPAnd, _) -> return (conjunct fs) (SPOr, _) -> return (disjunct fs) (SPTrue, []) -> return trueForm (SPFalse, []) -> return falseForm _ -> fail $ "wrong boolean formula: " ++ showDoc t "" toTERM :: Monad m => RMap -> SPTerm -> m (TERM ()) toTERM m spt = case spt of SPComplexTerm (SPCustomSymbol cst) args -> case Map.lookup cst m of Just (CVar s, _) | null args -> return $ Qual_var cst s nullRange Just (COp ot, mi) | length args == length (opArgs ot) -> do ts <- mapM (toTERM m) args return $ Application (Qual_op_name (case mi of Just i -> i _ -> simpleIdToId cst) (toOP_TYPE ot) nullRange) ts nullRange _ -> fail $ "cannot reconstruct term: " ++ showDoc spt "" _ -> fail $ "cannot reconstruct term: " ++ showDoc spt "" toQuant :: SPQuantSym -> QUANTIFIER toQuant sp = case sp of SPForall -> Universal SPExists -> Existential _ -> error "toQuant" toVar :: Monad m => RMap -> SPTerm -> m VAR_DECL toVar m sp = case sp of SPComplexTerm (SPCustomSymbol cst) [] | isVar cst -> case Map.lookup cst m of Just (CVar s, _) -> return $ Var_decl [cst] s nullRange _ -> fail $ "unknown variable: " ++ show cst _ -> fail $ "quantified term as variable: " ++ showDoc sp "" isVar :: SPIdentifier -> Bool isVar cst = case tokStr cst of c : _ -> isUpper c "" -> error "isVar" getVars :: SPTerm -> [SPIdentifier] getVars tm = case tm of SPComplexTerm (SPCustomSymbol cst) args -> if null args then [cst] else concatMap getVars args _ -> []
spechub/Hets
Comorphisms/SuleCFOL2SoftFOL.hs
gpl-2.0
46,238
0
31
16,677
13,742
7,000
6,742
886
17
module Dates ( daysInMonths, leapYear, yearToDays, Day(..), Month(..) ) where import Primes(divides) import Util(runningTotal) data Day = Sunday | Monday | Tuesday | Wednesday | Thursday | Friday | Saturday deriving (Show, Enum, Bounded, Eq) daysPerWeek = fromEnum (maxBound::Day) + 1 data Month = January | February | March | April | May | June | July | August | September | October | November | December deriving (Show, Enum, Bounded, Eq) monthsPerYear = fromEnum (maxBound::Month) + 1 leapYear :: Int -> Bool leapYear year = let quart = 4 `divides` year century = 100 `divides` year quartCentury = 400 `divides` year in quartCentury || quart && not century daysIn :: Month -> Int -> Int daysIn January _ = 31 daysIn February y = if leapYear y then 29 else 28 daysIn March _ = 31 daysIn April _ = 30 daysIn May _ = 31 daysIn June _ = 30 daysIn July _ = 31 daysIn August _ = 31 daysIn September _ = 30 daysIn October _ = 31 daysIn November _ = 30 daysIn December _ = 31 daysInMonths :: Int -> [Int] daysInMonths year = zipWith3 ($) (repeat daysIn) [(minBound::Month)..] (repeat year) yearToDays :: Int -> Day -> [Day] yearToDays year start = let dayCounts = daysInMonths year position = fromEnum start running = runningTotal $ position:dayCounts weekRing = map (`mod` daysPerWeek) running in map toEnum weekRing :: [Day]
liefswanson/projectEuler
src/Dates.hs
gpl-2.0
1,715
0
10
627
535
298
237
63
2
{-# LANGUAGE LambdaCase, OverloadedStrings, ExtendedDefaultRules, TupleSections #-} module LexiconEditor ( LexRow(..), createEditableLexicon, segsFromFt ) where import Graphics.UI.Gtk import Control.FRPNow hiding (swap, when) import Control.FRPNow.GTK import Control.Monad import Control.Exception import Data.Foldable import Data.Tuple import Data.Tuple.Select import Data.Maybe import Text.PhonotacticLearner.PhonotacticConstraints import Text.PhonotacticLearner.PhonotacticConstraints.FileFormats import Text.PhonotacticLearner 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 as B import qualified Data.Map.Lazy as M import qualified Data.Set as S import Control.DeepSeq import Text.Read (readMaybe) default(T.Text) data LexSourceType = FieroList | FieroText data LexSource = Custom | FromStored LexSourceType T.Text segsFromFt :: FeatureTable String -> S.Set String segsFromFt = M.keysSet . segLookup setLexContents :: TreeView -> S.Set String -> [LexRow] -> IO (ListStore LexRow) setLexContents editor segs initlist = do model <- listStoreNew initlist oldcols <- treeViewGetColumns editor forM_ oldcols $ \col -> treeViewRemoveColumn editor col treeViewSetModel editor model wcol <- treeViewColumnNew set wcol [treeViewColumnTitle := "Word", treeViewColumnExpand := True] wcell <- cellRendererTextNew set wcell [cellTextEditable := True] cellLayoutPackStart wcol wcell True treeViewAppendColumn editor wcol cellLayoutSetAttributes wcol wcell model $ \(LexRow w _) -> [cellText := joinFiero segs w] on wcell edited $ \[i] rawword -> do let newword = segmentFiero segs rawword LexRow w f <- listStoreGetValue model i when (w /= newword) $ listStoreSetValue model i (LexRow newword f) adj <- adjustmentNew 1 1 10000 1 10 0 fcol <- treeViewColumnNew set fcol [treeViewColumnTitle := "Frequency"] fcell <- cellRendererSpinNew set fcell [cellTextEditable := True, cellRendererSpinAdjustment := adj] cellLayoutPackStart fcol fcell True treeViewAppendColumn editor fcol cellLayoutSetAttributes fcol fcell model $ \(LexRow _ f) -> [cellText := show f] on fcell edited $ \[i] newval -> do LexRow w f <- listStoreGetValue model i case readMaybe newval of Just newfreq | (f /= newfreq) -> listStoreSetValue model i (LexRow w newfreq) _ -> return () return model watchLexModel :: LexSource -> S.Set String -> ListStore LexRow -> Now (Behavior (LexSource, S.Set String, [LexRow])) watchLexModel src segs model = do (lexChanged, changeLex) <- callbackStream initlist <- sync $ listStoreToList model let changecb = listStoreToList model >>= changeLex sync $ do on model rowChanged $ \_ _ -> changecb on model rowInserted $ \_ _ -> changecb on model rowDeleted $ \_ -> changecb sample $ fromChanges (src, segs, initlist) (fmap (Custom, segs, ) lexChanged) createEditableLexicon :: Maybe Window -> Behavior (S.Set String) -> EvStream [LexRow] -> Now (VBox, Behavior [LexRow]) createEditableLexicon transwin currentsegs extreplace = do vb <- sync $ vBoxNew False 2 editor <- sync treeViewNew (addButton,addPressed) <- createButton (Just "list-add") Nothing (delButton,delPressed) <- createButton (Just "list-remove") Nothing (loadListButton, loadListPressed) <- createButton (Just "document-open") (Just "Load Lexicon") (loadTextButton, loadTextPressed) <- createButton (Just "document-open") (Just "Collate Text") (saveButton, savePressed) <- createButton (Just "document-save") (Just "Save Lexicon") vb <- createVBox 2 $ do bstretch =<< createFrame ShadowIn =<< createScrolledWindow editor bpack <=< createHBox 2 $ do bpack addButton bpack delButton bspacer bpack loadListButton bpack loadTextButton bpack saveButton let segsChanged = toChanges currentsegs (modelChanged, changeModel) <- callbackStream (dLexChanged, changeDLex) <- callbackStream initsegs <- sample $ currentsegs initmodel <- sync $ setLexContents editor initsegs [] initDLex <- watchLexModel Custom initsegs initmodel currentModel <- sample $ fromChanges initmodel modelChanged currentLex <- sample $ foldrSwitch initDLex dLexChanged flip callStream addPressed $ \_ -> do (store) <- sample currentModel let newRow = LexRow [] 1 sync $ listStoreAppend store newRow return () flip callStream delPressed $ \_ -> do (store) <- sample currentModel (cur, _) <- sync $ treeViewGetCursor editor sync $ case cur of [i] -> listStoreRemove store i _ -> return () {- txtfilter <- sync fileFilterNew allfilter <- sync fileFilterNew sync $ do fileFilterAddMimeType txtfilter "text/*" fileFilterSetName txtfilter "Text Files" fileFilterAddPattern allfilter "*" fileFilterSetName allfilter "All Files" -} saveDialog <- sync $ fileChooserDialogNew (Just "Save Lexicon") transwin FileChooserActionSave [("gtk-cancel", ResponseCancel), ("gtk-save", ResponseAccept)] --sync $ fileChooserAddFilter saveDialog txtfilter --sync $ fileChooserAddFilter saveDialog allfilter sync $ set saveDialog [windowModal := True] flip callStream savePressed $ \_ -> do (_,segs,rows) <- sample currentLex savePicked <- runFileChooserDialog saveDialog planNow . ffor savePicked $ \case Nothing -> return () Just fn -> do async $ do let out = serWordlist segs rows binout = T.encodeUtf8 out B.writeFile fn binout putStrLn $ "Wrote Feature Table " ++ fn return () return () loadListDialog <- sync $ fileChooserDialogNew (Just "Load Lexicon") transwin FileChooserActionOpen [("gtk-cancel", ResponseCancel), ("gtk-open", ResponseAccept)] --sync $ fileChooserAddFilter loadListDialog txtfilter --sync $ fileChooserAddFilter loadListDialog allfilter sync $ set loadListDialog [windowModal := True] flip callStream loadListPressed $ \_ -> do filePicked <- runFileChooserDialog loadListDialog loaded <- planNow . ffor filePicked $ \case Nothing -> return never Just fn -> async $ do rawfile <- fmap (T.decodeUtf8With T.lenientDecode) (B.readFile fn) evaluate rawfile return (fn,rawfile) planNow . ffor (join loaded) $ \(fn,rawfile) -> do segs <- sample currentsegs let initrows = parseWordlist segs rawfile src = FromStored FieroList rawfile newmodel <- sync $ setLexContents editor segs initrows newDLex <- watchLexModel src segs newmodel sync $ do changeModel newmodel changeDLex newDLex putStrLn "Lexicon sucessfully loaded." return () loadTextDialog <- sync $ fileChooserDialogNew (Just "Load Text For New Lexicon") transwin FileChooserActionOpen [("gtk-cancel", ResponseCancel), ("gtk-open", ResponseAccept)] --sync $ fileChooserAddFilter loadTextDialog allfilter --sync $ fileChooserAddFilter loadTextDialog txtfilter sync $ set loadTextDialog [windowModal := True] flip callStream loadTextPressed $ \_ -> do filePicked <- runFileChooserDialog loadTextDialog loaded <- planNow . ffor filePicked $ \case Nothing -> return never Just fn -> async $ do rawfile <- fmap (T.decodeUtf8With T.lenientDecode) (B.readFile fn) evaluate rawfile return (fn,rawfile) planNow . ffor (join loaded) $ \(fn,rawfile) -> do segs <- sample currentsegs let initrows = collateWordlist segs rawfile src = FromStored FieroText rawfile newmodel <- sync $ setLexContents editor segs initrows newDLex <- watchLexModel src segs newmodel sync $ do changeModel newmodel changeDLex newDLex putStrLn "Lexicon sucessfully created." return () flip callStream segsChanged $ \newsegs' -> do let newsegs = last newsegs' (src, oldsegs, oldrows) <- sample currentLex let newrows = case src of Custom -> let raw = serWordlist oldsegs oldrows in parseWordlist newsegs raw FromStored FieroList raw -> parseWordlist newsegs raw FromStored FieroText raw -> collateWordlist newsegs raw newmodel <- sync $ setLexContents editor newsegs newrows newDLex <- watchLexModel src newsegs newmodel sync $ do changeModel newmodel changeDLex newDLex putStrLn "Lexicon resegmented." flip callStream extreplace $ \newrows' -> do let newrows = last newrows' segs <- sample currentsegs newmodel <- sync $ setLexContents editor segs newrows newDLex <- watchLexModel Custom segs newmodel sync $ do changeModel newmodel changeDLex newDLex return (vb, fmap sel3 currentLex)
george-steel/maxent-learner
maxent-learner-hw-gui/app/LexiconEditor.hs
gpl-2.0
9,491
0
24
2,519
2,641
1,264
1,377
189
7
{-# LANGUAGE OverloadedStrings, ScopedTypeVariables #-} module Json ( Journal(..) , Notifications(..) , J.PostList(..) , ApiError(..) ) where import Data.Aeson import Data.Text (Text, pack) import Control.Applicative import Control.Monad import qualified Data.HashMap.Strict as HMS import qualified Internal.Json as J data ApiError = ApiError { errorText :: Text , returnCode :: Int } deriving (Show, Eq) data Journal = Journal { userid :: Text , shortname :: Text } deriving (Show, Eq) data Notifications = Notifications { umailCount :: Integer , discussCount :: Integer , commentsCount :: Integer , discussions :: J.DiscussionList , umails :: J.UmailList , comments :: J.CommentList } deriving (Show, Eq) instance FromJSON Notifications where parseJSON = withObject "notifications" $ \n -> do umailCount <- (\x -> read x :: Integer) <$> n .: "umail_count" commentsCount <- (\x -> read x :: Integer) <$> n .: "comments_count" discussCount <- (\x -> read x :: Integer) <$> n .: "discuss_count" (comments :: J.CommentList) <- parseJSON =<< n .: "comments" (umails :: J.UmailList) <- parseJSON =<< n .: "umail" (discussions :: J.DiscussionList) <- parseJSON =<< n .: "discuss" return Notifications { umailCount = umailCount, commentsCount = commentsCount, discussCount = discussCount, comments = comments, umails = umails, discussions = discussions } instance FromJSON Journal where parseJSON = withObject "journal" $ \j -> do journal <- j .: "journal" userid <- pack <$> journal .: "userid" shortname <- pack <$> journal .: "shortname" return Journal { userid = userid, shortname = shortname } instance FromJSON ApiError where parseJSON (Object ae) = ApiError <$> ae .: "error" <*> ((\x -> read x :: Int) <$> ae .: "result" ) parseJSON _ = mzero
capgelka/hapidry
src/Json.hs
gpl-2.0
2,070
0
15
593
589
331
258
53
0
{-| Implementation of the Ganeti confd server functionality. -} {- Copyright (C) 2011, 2012, 2013 Google Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -} module Ganeti.Confd.Server ( main , checkMain , prepMain ) where import Control.Applicative((<$>)) import Control.Concurrent import Control.Monad (forever, liftM) import Data.IORef import Data.List import qualified Data.Map as M import Data.Maybe (fromMaybe) import qualified Network.Socket as S import System.Exit import System.IO import qualified Text.JSON as J import Ganeti.BasicTypes import Ganeti.Errors import Ganeti.Daemon import Ganeti.JSON import Ganeti.Objects import Ganeti.Confd.Types import Ganeti.Confd.Utils import Ganeti.Config import Ganeti.ConfigReader import Ganeti.Hash import Ganeti.Logging import qualified Ganeti.Constants as C import qualified Ganeti.Query.Cluster as QCluster import Ganeti.Utils -- * Types and constants definitions -- | What we store as configuration. type CRef = IORef (Result (ConfigData, LinkIpMap)) -- | A small type alias for readability. type StatusAnswer = (ConfdReplyStatus, J.JSValue) -- | Unknown entry standard response. queryUnknownEntry :: StatusAnswer queryUnknownEntry = (ReplyStatusError, J.showJSON ConfdErrorUnknownEntry) {- not used yet -- | Internal error standard response. queryInternalError :: StatusAnswer queryInternalError = (ReplyStatusError, J.showJSON ConfdErrorInternal) -} -- | Argument error standard response. queryArgumentError :: StatusAnswer queryArgumentError = (ReplyStatusError, J.showJSON ConfdErrorArgument) -- | Converter from specific error to a string format. gntErrorToResult :: ErrorResult a -> Result a gntErrorToResult (Bad err) = Bad (show err) gntErrorToResult (Ok x) = Ok x -- * Confd base functionality -- | Computes the node role. nodeRole :: ConfigData -> String -> Result ConfdNodeRole nodeRole cfg name = do cmaster <- errToResult $ QCluster.clusterMasterNodeName cfg mnode <- errToResult $ getNode cfg name let role = case mnode of node | cmaster == name -> NodeRoleMaster | nodeDrained node -> NodeRoleDrained | nodeOffline node -> NodeRoleOffline | nodeMasterCandidate node -> NodeRoleCandidate _ -> NodeRoleRegular return role -- | Does an instance ip -> instance -> primary node -> primary ip -- transformation. getNodePipByInstanceIp :: ConfigData -> LinkIpMap -> String -> String -> StatusAnswer getNodePipByInstanceIp cfg linkipmap link instip = case M.lookup instip (M.findWithDefault M.empty link linkipmap) of Nothing -> queryUnknownEntry Just instname -> case getInstPrimaryNode cfg instname of Bad _ -> queryUnknownEntry -- either instance or node not found Ok node -> (ReplyStatusOk, J.showJSON (nodePrimaryIp node)) -- | Returns a node name for a given UUID uuidToNodeName :: ConfigData -> String -> Result String uuidToNodeName cfg uuid = gntErrorToResult $ nodeName <$> getNode cfg uuid -- | Encodes a list of minors into a JSON representation, converting UUIDs to -- names in the process encodeMinors :: ConfigData -> (String, Int, String, String, String, String) -> Result J.JSValue encodeMinors cfg (node_uuid, a, b, c, d, peer_uuid) = do node_name <- uuidToNodeName cfg node_uuid peer_name <- uuidToNodeName cfg peer_uuid return . J.JSArray $ [J.showJSON node_name, J.showJSON a, J.showJSON b, J.showJSON c, J.showJSON d, J.showJSON peer_name] -- | Builds the response to a given query. buildResponse :: (ConfigData, LinkIpMap) -> ConfdRequest -> Result StatusAnswer buildResponse (cfg, _) (ConfdRequest { confdRqType = ReqPing }) = return (ReplyStatusOk, J.showJSON (configVersion cfg)) buildResponse cdata req@(ConfdRequest { confdRqType = ReqClusterMaster }) = case confdRqQuery req of EmptyQuery -> liftM ((,) ReplyStatusOk . J.showJSON) master_name PlainQuery _ -> return queryArgumentError DictQuery reqq -> do mnode <- gntErrorToResult $ getNode cfg master_uuid mname <- master_name let fvals = map (\field -> case field of ReqFieldName -> mname ReqFieldIp -> clusterMasterIp cluster ReqFieldMNodePip -> nodePrimaryIp mnode ) (confdReqQFields reqq) return (ReplyStatusOk, J.showJSON fvals) where master_uuid = clusterMasterNode cluster master_name = errToResult $ QCluster.clusterMasterNodeName cfg cluster = configCluster cfg cfg = fst cdata buildResponse cdata req@(ConfdRequest { confdRqType = ReqNodeRoleByName }) = do node_name <- case confdRqQuery req of PlainQuery str -> return str _ -> fail $ "Invalid query type " ++ show (confdRqQuery req) role <- nodeRole (fst cdata) node_name return (ReplyStatusOk, J.showJSON role) buildResponse cdata (ConfdRequest { confdRqType = ReqNodePipList }) = -- note: we use foldlWithKey because that's present accross more -- versions of the library return (ReplyStatusOk, J.showJSON $ M.foldlWithKey (\accu _ n -> nodePrimaryIp n:accu) [] (fromContainer . configNodes . fst $ cdata)) buildResponse cdata (ConfdRequest { confdRqType = ReqMcPipList }) = -- note: we use foldlWithKey because that's present accross more -- versions of the library return (ReplyStatusOk, J.showJSON $ M.foldlWithKey (\accu _ n -> if nodeMasterCandidate n then nodePrimaryIp n:accu else accu) [] (fromContainer . configNodes . fst $ cdata)) buildResponse (cfg, linkipmap) req@(ConfdRequest { confdRqType = ReqInstIpsList }) = do link <- case confdRqQuery req of PlainQuery str -> return str EmptyQuery -> return (getDefaultNicLink cfg) _ -> fail "Invalid query type" return (ReplyStatusOk, J.showJSON $ getInstancesIpByLink linkipmap link) buildResponse cdata (ConfdRequest { confdRqType = ReqNodePipByInstPip , confdRqQuery = DictQuery query}) = let (cfg, linkipmap) = cdata link = fromMaybe (getDefaultNicLink cfg) (confdReqQLink query) in case confdReqQIp query of Just ip -> return $ getNodePipByInstanceIp cfg linkipmap link ip Nothing -> return (ReplyStatusOk, J.showJSON $ map (getNodePipByInstanceIp cfg linkipmap link) (confdReqQIpList query)) buildResponse _ (ConfdRequest { confdRqType = ReqNodePipByInstPip }) = return queryArgumentError buildResponse cdata req@(ConfdRequest { confdRqType = ReqNodeDrbd }) = do let cfg = fst cdata node_name <- case confdRqQuery req of PlainQuery str -> return str _ -> fail $ "Invalid query type " ++ show (confdRqQuery req) node <- gntErrorToResult $ getNode cfg node_name let minors = concatMap (getInstMinorsForNode (nodeUuid node)) . M.elems . fromContainer . configInstances $ cfg encoded <- mapM (encodeMinors cfg) minors return (ReplyStatusOk, J.showJSON encoded) -- | Return the list of instances for a node (as ([primary], [secondary])) given -- the node name. buildResponse cdata req@(ConfdRequest { confdRqType = ReqNodeInstances }) = do let cfg = fst cdata node_name <- case confdRqQuery req of PlainQuery str -> return str _ -> fail $ "Invalid query type " ++ show (confdRqQuery req) node <- case getNode cfg node_name of Ok n -> return n Bad e -> fail $ "Node not found in the configuration: " ++ show e let node_uuid = nodeUuid node instances = getNodeInstances cfg node_uuid return (ReplyStatusOk, J.showJSON instances) -- | Creates a ConfdReply from a given answer. serializeResponse :: Result StatusAnswer -> ConfdReply serializeResponse r = let (status, result) = case r of Bad err -> (ReplyStatusError, J.showJSON err) Ok (code, val) -> (code, val) in ConfdReply { confdReplyProtocol = 1 , confdReplyStatus = status , confdReplyAnswer = result , confdReplySerial = 0 } -- ** Client input/output handlers -- | Main loop for a given client. responder :: CRef -> S.Socket -> HashKey -> String -> S.SockAddr -> IO () responder cfgref socket hmac msg peer = do ctime <- getCurrentTime case parseRequest hmac msg ctime of Ok (origmsg, rq) -> do logDebug $ "Processing request: " ++ rStripSpace origmsg mcfg <- readIORef cfgref let response = respondInner mcfg hmac rq _ <- S.sendTo socket response peer logDebug $ "Response sent: " ++ response return () Bad err -> logInfo $ "Failed to parse incoming message: " ++ err return () -- | Inner helper function for a given client. This generates the -- final encoded message (as a string), ready to be sent out to the -- client. respondInner :: Result (ConfigData, LinkIpMap) -> HashKey -> ConfdRequest -> String respondInner cfg hmac rq = let rsalt = confdRqRsalt rq innermsg = serializeResponse (cfg >>= flip buildResponse rq) innerserialised = J.encodeStrict innermsg outermsg = signMessage hmac rsalt innerserialised outerserialised = C.confdMagicFourcc ++ J.encodeStrict outermsg in outerserialised -- | Main listener loop. listener :: S.Socket -> HashKey -> (S.Socket -> HashKey -> String -> S.SockAddr -> IO ()) -> IO () listener s hmac resp = do (msg, _, peer) <- S.recvFrom s 4096 if C.confdMagicFourcc `isPrefixOf` msg then forkIO (resp s hmac (drop 4 msg) peer) >> return () else logDebug "Invalid magic code!" >> return () return () -- | Type alias for prepMain results type PrepResult = (S.Socket, IORef (Result (ConfigData, LinkIpMap))) -- | Check function for confd. checkMain :: CheckFn (S.Family, S.SockAddr) checkMain opts = do parseresult <- parseAddress opts C.defaultConfdPort case parseresult of Bad msg -> do hPutStrLn stderr $ "parsing bind address: " ++ msg return . Left $ ExitFailure 1 Ok v -> return $ Right v -- | Prepare function for confd. prepMain :: PrepFn (S.Family, S.SockAddr) PrepResult prepMain _ (af_family, bindaddr) = do s <- S.socket af_family S.Datagram S.defaultProtocol S.bindSocket s bindaddr cref <- newIORef (Bad "Configuration not yet loaded") return (s, cref) -- | Main function. main :: MainFn (S.Family, S.SockAddr) PrepResult main _ _ (s, cref) = do let cfg_transform :: Result ConfigData -> Result (ConfigData, LinkIpMap) cfg_transform = liftM (\cfg -> (cfg, buildLinkIpInstnameMap cfg)) initConfigReader cfg_transform cref hmac <- getClusterHmac -- enter the responder loop forever $ listener s hmac (responder cref)
vladimir-ipatov/ganeti
src/Ganeti/Confd/Server.hs
gpl-2.0
11,755
0
19
2,864
2,892
1,474
1,418
209
13
module Commons where import Affection import GEGL as G import qualified SDL import qualified Data.Map as M import Types import Debug.Trace updateClockString :: Affection UserData () updateClockString = do ud <- getAffection let hours = floor (tminus ud / 3600) :: Int hx = show $ hours `div` 10 hi = show $ hours `mod` 10 minutes = floor ((tminus ud - fromIntegral (hours * 3600)) / 60) :: Int mx = show $ minutes `div` 10 mi = show $ minutes `mod` 10 seconds = floor ((tminus ud - fromIntegral (hours * 3600) - fromIntegral (minutes * 60))) :: Int sx = show $ seconds `div` 10 si = show $ seconds `mod` 10 musec = floor $ ((tminus ud) - fromIntegral (hours * 3600) - fromIntegral (minutes * 60) - fromIntegral seconds ) * 100 :: Int ux = show $ musec `div` 10 ui = show $ musec `mod` 10 liftIO $ gegl_node_set (nodeGraph ud M.! KeyClock) $ textOperation [ Property "string" $ PropertyString $ hx ++ hi ++ "-" ++ mx ++ mi ++ "-" ++ sx ++ si ++ "-" ++ ux ++ ui ] toggleScreen :: Affection UserData () toggleScreen = do liftIO $ traceIO "f pressed" ad <- get ud <- getAffection case screen ud of Windowed -> do SDL.setWindowMode (drawWindow ad) SDL.Fullscreen liftIO $ traceIO "going fullscreen" putAffection ud { screen = Full } Full -> do SDL.setWindowMode (drawWindow ad) SDL.Windowed liftIO $ traceIO "going windowed" putAffection ud { screen = Windowed }
nek0/countdown.hs
src/Commons.hs
gpl-3.0
1,671
0
22
564
577
302
275
53
2
{- Copyright (C) 2015 Michael Dunsmuir 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/>. -} {-# LANGUAGE DeriveDataTypeable, TypeFamilies, TemplateHaskell #-} import Control.Applicative import Control.Monad.State.Class import Control.Monad.Reader import Data.Aeson import Data.SafeCopy import Data.Acid import Data.Typeable import Data.Char (isSpace) import qualified Data.Foldable as F import qualified Data.Set as S import qualified Data.Map as M import qualified Data.ByteString.Lazy.Char8 as B import Network.HTTP import Text.ProtocolBuffers.WireMessage import Com.Google.Transit.Realtime.FeedMessage import RoutequeryService.GTFSRealtime import Com.Google.Transit.Realtime.FeedEntity import Com.Google.Transit.Realtime.TripUpdate data TripUpdateMap = TripUpdateMap (M.Map Integer (S.Set TripUpdate)) deriving Typeable insertTripUpdate :: TripUpdate -> Update TripUpdateMap () insertTripUpdate tu@(TripUpdate _ _ _ (Just timestamp) _ _) = do TripUpdateMap map <- get let map' = M.insertWith S.union timestamp' (S.singleton tu) map put $ TripUpdateMap map' where timestamp' = toInteger timestamp insertTripUpdate _ = return () tripUpdatesForTimestamp :: Integer -> Query TripUpdateMap (S.Set TripUpdate) tripUpdatesForTimestamp ts = do TripUpdateMap map <- ask return $ M.findWithDefault S.empty ts map getMap :: Query TripUpdateMap (M.Map Integer (S.Set TripUpdate)) getMap = do TripUpdateMap map <- ask return map $(deriveSafeCopy 0 'base ''TripUpdateMap) $(makeAcidic ''TripUpdateMap ['insertTripUpdate, 'tripUpdatesForTimestamp, 'getMap]) loadKey :: IO String loadKey = trim <$> readFile "key.txt" where trim :: String -> String trim = f . f where f = reverse . dropWhile isSpace requestWithKey = ("http://api.pugetsound.onebusaway.org/api/gtfs_realtime/trip-updates-for-agency/1.pb?key=" ++) main = do key <- loadKey http <- simpleHTTP (getRequest (requestWithKey key)) message <- B.pack <$> getResponseBody http let getted = messageGet message :: Either String (FeedMessage, B.ByteString) case getted of Left error -> putStrLn error Right (message, _) -> storeUpdates message storeUpdates :: FeedMessage -> IO () storeUpdates (FeedMessage _ entities _) = do let updates = map trip_update $ F.toList entities acid <- openLocalState $ TripUpdateMap M.empty F.forM_ updates $ \tripUpdate -> case tripUpdate of (Just tripUpdate) -> update acid $ InsertTripUpdate tripUpdate Nothing -> return () updates <- query acid $ TripUpdatesForTimestamp 1425842139 B.putStrLn $ encode updates
mdunsmuir/routequery-service
src/Historian.hs
gpl-3.0
3,249
3
13
600
763
390
373
61
2
{- | Module : Sound.FModEx.Raw.DSP Description : DSP FModEx library Haskell raw binding Copyright : (c) Dimitri Sabadie License : GPL-3 Maintainer : [email protected] Stability : experimental Portability : Linux only for now DSP FModEx raw Haskell API. -} module Sound.FModEx.Raw.DSP ( module X ) where import Sound.FModEx.Raw.DSP.Types as X
phaazon/hsFModEx
Sound/FModEx/Raw/DSP.hs
gpl-3.0
381
0
4
81
25
19
6
3
0
module Server where import Happstack.Server ( simpleHTTP , nullConf ) import Happstack.Server.ClientSession ( getDefaultKey , sessionPath , withClientSessionT , mkSessionConf ) import Routes ( entryPoint ) run :: IO () run = do key <- getDefaultKey let sessionConf = mkSessionConf key simpleHTTP nullConf $ withClientSessionT sessionConf entryPoint
MortimerMcMire315/sparkive
src/Server.hs
gpl-3.0
561
0
10
259
94
51
43
13
1
module HW1 where --Data ------ type RealName = String type UserName = String type GroupName = String type Message = String data Post = Post UserName Message deriving (Show, Eq) data To = UserID UserName | GroupID GroupName deriving (Show, Eq) data User = User UserName RealName [UserName] [Post] deriving (Show, Eq) data Group = Group GroupName [UserName] [Post] deriving (Show, Eq) data DB = DB [User] [Group] deriving (Show, Eq) --1. Commands newUser :: DB -> User -> DB addFriend :: DB -> UserName -> UserName -> DB sendPost :: DB -> UserName -> Message -> [To] -> DB newGroup :: DB -> GroupName -> DB addMember :: DB -> GroupName -> UserName -> DB removeMember :: DB -> GroupName -> UserName -> DB --2. Queries getFriendNames :: DB -> UserName -> [RealName] getPosts :: DB -> To -> [Post] listGroups :: DB -> UserName -> [Group] suggestFriends :: DB -> User -> Int -> [User] ---- IMPLEMENTATIONS ---- --User Getters-- userName :: User -> UserName userName (User uName _ _ _ ) = uName realName :: User -> RealName realName (User _ rName _ _ ) = rName friendListU :: User -> [UserName] friendListU (User _ _ uNameList _ ) = uNameList postListU :: User -> [Post] postListU (User _ _ _ pList ) = pList --DB Getters-- userList :: DB -> [User] userList (DB uList _ ) = uList groupList :: DB -> [Group] groupList (DB _ gList) = gList --Group Getters-- groupName :: Group -> GroupName groupName (Group gName _ _ ) = gName userNameListG :: Group -> [UserName] userNameListG (Group _ uList _ ) = uList postListG :: Group -> [Post] postListG (Group _ _ pList) = pList -- alreadyUser :: [User]-> UserName -> Bool alreadyUser [] name = False alreadyUser (x:xs) name | name == (userName x) = True | otherwise = alreadyUser xs name newUser database user = if alreadyUser (userList database) (userName user) then database else (DB (userList database ++ [user]) (groupList database)) -- addFriendR :: [User] -> UserName -> UserName -> [User] addFriendR [] user1 user2 = [] addFriendR (x:xs) user1 user2 | (userName x) == user1 = [(User (user1) (realName x) (friendListU x ++ [user2]) (postListU x))] ++ (addFriendR xs user1 user2) | (userName x) == user2 = [(User (user2) (realName x) (friendListU x ++ [user1]) (postListU x))] ++ (addFriendR xs user1 user2) | otherwise = [x] ++ (addFriendR xs user1 user2) addFriend database user1 user2 = DB (addFriendR (userList database) user1 user2) (groupList database) -- sendPostRecursivelyG :: [Group] -> GroupName -> Post -> [Group] sendPostRecursivelyG [] gName post = [] sendPostRecursivelyG (x:xs) gName post | ((groupName x) == gName) && (post `elem` (postListG x))/=True= [(Group gName (userNameListG x) ((postListG x) ++ [post]))] ++ xs | otherwise = [x] ++ (sendPostRecursivelyG xs gName post) sendPostRecursivelyU :: [User] -> UserName -> Post -> [User] sendPostRecursivelyU [] uName post = [] sendPostRecursivelyU (x:xs) uName post | ((userName x) == uName)&& (post `elem` (postListU x))/=True = [(User (uName) (realName x) (friendListU x) ((postListU) x ++ [post]))] ++ xs | otherwise = [x] ++ (sendPostRecursivelyU xs uName post) toExtend:: Group -> [To] toExtend group = [(UserID to) | to <- (userNameListG group)] sendPost database user1 sentence [] = database sendPost database user1 sentence ((GroupID x):xs) = sendPost (DB (userList database) (sendPostRecursivelyG (groupList database) x (Post user1 sentence))) user1 sentence (xs ++ toExtend(findGroup (groupList database) x)) sendPost database user1 sentence ((UserID x):xs) = sendPost (DB (sendPostRecursivelyU (userList database) x (Post user1 sentence)) (groupList database)) user1 sentence xs -- newGroup database gName = (DB (userList database) ( (groupList database) ++ [Group gName [] []] )) -- addMemberR :: [UserName] -> UserName -> [UserName] addMemberR [] uName = [uName] addMemberR (x:xs) uName | x == uName = x:xs | otherwise = x:(addMemberR xs uName) addMemberGroupFind :: [Group] -> GroupName -> UserName -> [Group] addMemberGroupFind [] gName uName= [] addMemberGroupFind (x:xs) gName uName | (groupName x) == gName = (Group gName (addMemberR (userNameListG x) uName) (postListG x)):xs | otherwise = x:(addMemberGroupFind xs gName uName) addMember database gName uName = (DB (userList database) (addMemberGroupFind (groupList database) gName uName)) -- removeMemberGroupFind :: [Group] -> GroupName -> UserName -> [Group] removeMemberGroupFind [] gName uName= [] removeMemberGroupFind (x:xs) gName uName | (groupName x) == gName = (Group gName ([a | a<-(userNameListG x),a/=uName]) (postListG x)):xs | otherwise = x:(removeMemberGroupFind xs gName uName) removeMember database gName uName = (DB (userList database) (removeMemberGroupFind (groupList database) gName uName)) -- findUser :: [User] -> UserName -> User findUser (x:xs) uName | uName==(userName x) = x | otherwise = findUser xs uName namePairs :: [User] -> [(UserName,RealName)] namePairs [] = [] namePairs (x:xs) = ((userName x), (realName x)):(namePairs xs) findInPairs :: UserName -> [(UserName,RealName)] -> RealName findInPairs uname ((uName,rName):xs) | uname == uName = rName | otherwise = findInPairs uname xs realFriends :: [UserName] -> [(UserName,RealName)] -> [RealName] realFriends [] _ = [] realFriends (x:xs) pairs = (findInPairs x pairs) : (realFriends xs pairs) getFriendNames database uName = realFriends (friendListU(findUser (userList database) uName)) (namePairs (userList database)) -- listGroups database uName = [a | a<-(groupList database), uName `elem` (userNameListG a) ] -- findGroup :: [Group] -> GroupName -> Group findGroup (x:xs) gName | (groupName x) == gName = x | otherwise = findGroup xs gName getPosts db (GroupID gName) = postListG ( findGroup (groupList db) gName) getPosts db (UserID uName) = postListU ( findUser (userList db) uName) -- suggestFriendsList :: [User] -> User -> Int -> [User] suggestFriendsList [] _ _ = [] suggestFriendsList (x:xs) user num | (userName x) == (userName user) = suggestFriendsList xs user num | (userName x) `elem` (friendListU user) = suggestFriendsList xs user num | (length([a | a <- (friendListU user), a `elem` (friendListU x)])) >= num = x:(suggestFriendsList xs user num) | otherwise = suggestFriendsList xs user num suggestFriends database user num = suggestFriendsList (userList database) user num
kadircet/CENG
242/hw1/tester/HW1-Kopya.hs
gpl-3.0
6,377
32
16
1,087
2,864
1,496
1,368
116
2